xref: /php-src/ext/standard/mail.c (revision 04e8e55f)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Author: Rasmus Lerdorf <rasmus@php.net>                              |
14    +----------------------------------------------------------------------+
15  */
16 
17 #include <stdlib.h>
18 #include <ctype.h>
19 #include <stdio.h>
20 #include <time.h>
21 #include "php.h"
22 #include "ext/standard/info.h"
23 #include "ext/standard/php_string.h"
24 #include "ext/standard/basic_functions.h"
25 #include "ext/date/php_date.h"
26 #include "zend_smart_str.h"
27 
28 #ifdef HAVE_SYSEXITS_H
29 # include <sysexits.h>
30 #endif
31 #ifdef HAVE_SYS_SYSEXITS_H
32 # include <sys/sysexits.h>
33 #endif
34 
35 #if PHP_SIGCHILD
36 # include <signal.h>
37 #endif
38 
39 #include "php_syslog.h"
40 #include "php_mail.h"
41 #include "php_ini.h"
42 #include "php_string.h"
43 #include "exec.h"
44 
45 #ifdef PHP_WIN32
46 # include "win32/sendmail.h"
47 #endif
48 
49 #define SKIP_LONG_HEADER_SEP(str, pos)																	\
50 	if (str[pos] == '\r' && str[pos + 1] == '\n' && (str[pos + 2] == ' ' || str[pos + 2] == '\t')) {	\
51 		pos += 2;																						\
52 		while (str[pos + 1] == ' ' || str[pos + 1] == '\t') {											\
53 			pos++;																						\
54 		}																								\
55 		continue;																						\
56 	}																									\
57 
58 extern zend_long php_getuid(void);
59 
php_mail_build_headers_check_field_value(zval * val)60 static php_mail_header_value_error_type php_mail_build_headers_check_field_value(zval *val)
61 {
62 	size_t len = 0;
63 	zend_string *value = Z_STR_P(val);
64 
65 	/* https://tools.ietf.org/html/rfc2822#section-2.2.1 */
66 	/* https://tools.ietf.org/html/rfc2822#section-2.2.3 */
67 	while (len < value->len) {
68 		if (*(value->val+len) == '\r') {
69 			if (*(value->val+len+1) != '\n') {
70 				return CONTAINS_CR_ONLY;
71 			}
72 
73 			if (value->len - len >= 3
74 				&& (*(value->val+len+2) == ' '  || *(value->val+len+2) == '\t')) {
75 				len += 3;
76 				continue;
77 			}
78 
79 			return CONTAINS_CRLF;
80 		}
81 		/**
82 		 * The RFC does not allow using LF alone for folding. However, LF is
83 		 * often treated similarly to CRLF, and there are likely many user
84 		 * environments that use LF for folding.
85 		 * Therefore, considering such an environment, folding with LF alone
86 		 * is allowed.
87 		 */
88 		if (*(value->val+len) == '\n') {
89 			if (value->len - len >= 2
90 				&& (*(value->val+len+1) == ' '  || *(value->val+len+1) == '\t')) {
91 				len += 2;
92 				continue;
93 			}
94 			return CONTAINS_LF_ONLY;
95 		}
96 		if (*(value->val+len) == '\0') {
97 			return CONTAINS_NULL;
98 		}
99 		len++;
100 	}
101 	return NO_HEADER_ERROR;
102 }
103 
104 
php_mail_build_headers_check_field_name(zend_string * key)105 static bool php_mail_build_headers_check_field_name(zend_string *key)
106 {
107 	size_t len = 0;
108 
109 	/* https://tools.ietf.org/html/rfc2822#section-2.2 */
110 	while (len < key->len) {
111 		if (*(key->val+len) < 33 || *(key->val+len) > 126 || *(key->val+len) == ':') {
112 			return FAILURE;
113 		}
114 		len++;
115 	}
116 	return SUCCESS;
117 }
118 
119 
120 static void php_mail_build_headers_elems(smart_str *s, zend_string *key, zval *val);
121 
php_mail_build_headers_elem(smart_str * s,zend_string * key,zval * val)122 static void php_mail_build_headers_elem(smart_str *s, zend_string *key, zval *val)
123 {
124 	switch(Z_TYPE_P(val)) {
125 		case IS_STRING:
126 			if (php_mail_build_headers_check_field_name(key) != SUCCESS) {
127 				zend_value_error("Header name \"%s\" contains invalid characters", ZSTR_VAL(key));
128 				return;
129 			}
130 
131 			php_mail_header_value_error_type error_type = php_mail_build_headers_check_field_value(val);
132 			switch (error_type) {
133 				case NO_HEADER_ERROR:
134 					break;
135 				case CONTAINS_LF_ONLY:
136 					zend_value_error("Header \"%s\" contains LF character that is not allowed in the header", ZSTR_VAL(key));
137 					return;
138 				case CONTAINS_CR_ONLY:
139 					zend_value_error("Header \"%s\" contains CR character that is not allowed in the header", ZSTR_VAL(key));
140 					return;
141 				case CONTAINS_CRLF:
142 					zend_value_error("Header \"%s\" contains CRLF characters that are used as a line separator and are not allowed in the header", ZSTR_VAL(key));
143 					return;
144 				case CONTAINS_NULL:
145 					zend_value_error("Header \"%s\" contains NULL character that is not allowed in the header", ZSTR_VAL(key));
146 					return;
147 				default:
148 					// fallback
149 					zend_value_error("Header \"%s\" has invalid format, or contains invalid characters", ZSTR_VAL(key));
150 					return;
151 			}
152 			smart_str_append(s, key);
153 			smart_str_appendl(s, ": ", 2);
154 			smart_str_appends(s, Z_STRVAL_P(val));
155 			smart_str_appendl(s, "\r\n", 2);
156 			break;
157 		case IS_ARRAY:
158 			php_mail_build_headers_elems(s, key, val);
159 			break;
160 		default:
161 			zend_type_error("Header \"%s\" must be of type array|string, %s given", ZSTR_VAL(key), zend_zval_value_name(val));
162 	}
163 }
164 
165 
php_mail_build_headers_elems(smart_str * s,zend_string * key,zval * val)166 static void php_mail_build_headers_elems(smart_str *s, zend_string *key, zval *val)
167 {
168 	zend_string *tmp_key;
169 	zval *tmp_val;
170 
171 	ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(val), tmp_key, tmp_val) {
172 		if (tmp_key) {
173 			zend_type_error("Header \"%s\" must only contain numeric keys, \"%s\" found", ZSTR_VAL(key), ZSTR_VAL(tmp_key));
174 			break;
175 		}
176 		ZVAL_DEREF(tmp_val);
177 		if (Z_TYPE_P(tmp_val) != IS_STRING) {
178 			zend_type_error("Header \"%s\" must only contain values of type string, %s found", ZSTR_VAL(key), zend_zval_value_name(tmp_val));
179 			break;
180 		}
181 		php_mail_build_headers_elem(s, key, tmp_val);
182 	} ZEND_HASH_FOREACH_END();
183 }
184 
185 
php_mail_build_headers(HashTable * headers)186 PHPAPI zend_string *php_mail_build_headers(HashTable *headers)
187 {
188 	zend_ulong idx;
189 	zend_string *key;
190 	zval *val;
191 	smart_str s = {0};
192 
193 	ZEND_HASH_FOREACH_KEY_VAL(headers, idx, key, val) {
194 		if (!key) {
195 			zend_type_error("Header name cannot be numeric, " ZEND_LONG_FMT " given", idx);
196 			break;
197 		}
198 		ZVAL_DEREF(val);
199 		/* https://tools.ietf.org/html/rfc2822#section-3.6 */
200 		if (zend_string_equals_literal_ci(key, "orig-date")) {
201 			PHP_MAIL_BUILD_HEADER_CHECK("orig-date", s, key, val);
202 		} else if (zend_string_equals_literal_ci(key, "from")) {
203 			PHP_MAIL_BUILD_HEADER_CHECK("from", s, key, val);
204 		} else if (zend_string_equals_literal_ci(key, "sender")) {
205 			PHP_MAIL_BUILD_HEADER_CHECK("sender", s, key, val);
206 		} else if (zend_string_equals_literal_ci(key, "reply-to")) {
207 			PHP_MAIL_BUILD_HEADER_CHECK("reply-to", s, key, val);
208 		} else if (zend_string_equals_literal_ci(key, "to")) {
209 			zend_value_error("The additional headers cannot contain the \"To\" header");
210 		} else if (zend_string_equals_literal_ci(key, "cc")) {
211 			PHP_MAIL_BUILD_HEADER_CHECK("cc", s, key, val);
212 		} else if (zend_string_equals_literal_ci(key, "bcc")) {
213 			PHP_MAIL_BUILD_HEADER_CHECK("bcc", s, key, val);
214 		} else if (zend_string_equals_literal_ci(key, "message-id")) {
215 			PHP_MAIL_BUILD_HEADER_CHECK("message-id", s, key, val);
216 		} else if (zend_string_equals_literal_ci(key, "references")) {
217 			PHP_MAIL_BUILD_HEADER_CHECK("references", s, key, val);
218 		} else if (zend_string_equals_literal_ci(key, "in-reply-to")) {
219 			PHP_MAIL_BUILD_HEADER_CHECK("in-reply-to", s, key, val);
220 		} else if (zend_string_equals_literal_ci(key, "subject")) {
221 			zend_value_error("The additional headers cannot contain the \"Subject\" header");
222 		} else {
223 			PHP_MAIL_BUILD_HEADER_DEFAULT(s, key, val);
224 		}
225 
226 		if (EG(exception)) {
227 			smart_str_free(&s);
228 			return NULL;
229 		}
230 	} ZEND_HASH_FOREACH_END();
231 
232 	/* Remove the last \r\n */
233 	if (s.s) s.s->len -= 2;
234 	smart_str_0(&s);
235 
236 	return s.s;
237 }
238 
239 
240 /* {{{ Send an email message */
PHP_FUNCTION(mail)241 PHP_FUNCTION(mail)
242 {
243 	char *to=NULL, *message=NULL;
244 	char *subject=NULL;
245 	zend_string *extra_cmd=NULL;
246 	zend_string *headers_str = NULL;
247 	HashTable *headers_ht = NULL;
248 	size_t to_len, message_len;
249 	size_t subject_len, i;
250 	char *force_extra_parameters = INI_STR("mail.force_extra_parameters");
251 	char *to_r, *subject_r;
252 
253 	ZEND_PARSE_PARAMETERS_START(3, 5)
254 		Z_PARAM_PATH(to, to_len)
255 		Z_PARAM_PATH(subject, subject_len)
256 		Z_PARAM_PATH(message, message_len)
257 		Z_PARAM_OPTIONAL
258 		Z_PARAM_ARRAY_HT_OR_STR(headers_ht, headers_str)
259 		Z_PARAM_PATH_STR(extra_cmd)
260 	ZEND_PARSE_PARAMETERS_END();
261 
262 	if (headers_str) {
263 		if (strlen(ZSTR_VAL(headers_str)) != ZSTR_LEN(headers_str)) {
264 			zend_argument_value_error(4, "must not contain any null bytes");
265 			RETURN_THROWS();
266 		}
267 		headers_str = php_trim(headers_str, NULL, 0, 2);
268 	} else if (headers_ht) {
269 		headers_str = php_mail_build_headers(headers_ht);
270 		if (EG(exception)) {
271 			RETURN_THROWS();
272 		}
273 	}
274 
275 	if (to_len > 0) {
276 		to_r = estrndup(to, to_len);
277 		for (; to_len; to_len--) {
278 			if (!isspace((unsigned char) to_r[to_len - 1])) {
279 				break;
280 			}
281 			to_r[to_len - 1] = '\0';
282 		}
283 		for (i = 0; to_r[i]; i++) {
284 			if (iscntrl((unsigned char) to_r[i])) {
285 				/* According to RFC 822, section 3.1.1 long headers may be separated into
286 				 * parts using CRLF followed at least one linear-white-space character ('\t' or ' ').
287 				 * To prevent these separators from being replaced with a space, we use the
288 				 * SKIP_LONG_HEADER_SEP to skip over them. */
289 				SKIP_LONG_HEADER_SEP(to_r, i);
290 				to_r[i] = ' ';
291 			}
292 		}
293 	} else {
294 		to_r = to;
295 	}
296 
297 	if (subject_len > 0) {
298 		subject_r = estrndup(subject, subject_len);
299 		for (; subject_len; subject_len--) {
300 			if (!isspace((unsigned char) subject_r[subject_len - 1])) {
301 				break;
302 			}
303 			subject_r[subject_len - 1] = '\0';
304 		}
305 		for (i = 0; subject_r[i]; i++) {
306 			if (iscntrl((unsigned char) subject_r[i])) {
307 				SKIP_LONG_HEADER_SEP(subject_r, i);
308 				subject_r[i] = ' ';
309 			}
310 		}
311 	} else {
312 		subject_r = subject;
313 	}
314 
315 	if (force_extra_parameters) {
316 		extra_cmd = php_escape_shell_cmd(force_extra_parameters);
317 	} else if (extra_cmd) {
318 		extra_cmd = php_escape_shell_cmd(ZSTR_VAL(extra_cmd));
319 	}
320 
321 	if (php_mail(to_r, subject_r, message, headers_str && ZSTR_LEN(headers_str) ? ZSTR_VAL(headers_str) : NULL, extra_cmd ? ZSTR_VAL(extra_cmd) : NULL)) {
322 		RETVAL_TRUE;
323 	} else {
324 		RETVAL_FALSE;
325 	}
326 
327 	if (headers_str) {
328 		zend_string_release_ex(headers_str, 0);
329 	}
330 
331 	if (extra_cmd) {
332 		zend_string_release_ex(extra_cmd, 0);
333 	}
334 	if (to_r != to) {
335 		efree(to_r);
336 	}
337 	if (subject_r != subject) {
338 		efree(subject_r);
339 	}
340 }
341 /* }}} */
342 
343 
php_mail_log_crlf_to_spaces(char * message)344 void php_mail_log_crlf_to_spaces(char *message) {
345 	/* Find all instances of carriage returns or line feeds and
346 	 * replace them with spaces. Thus, a log line is always one line
347 	 * long
348 	 */
349 	char *p = message;
350 	while ((p = strpbrk(p, "\r\n"))) {
351 		*p = ' ';
352 	}
353 }
354 
php_mail_log_to_syslog(char * message)355 void php_mail_log_to_syslog(char *message) {
356 	/* Write 'message' to syslog. */
357 #ifdef HAVE_SYSLOG_H
358 	php_syslog(LOG_NOTICE, "%s", message);
359 #endif
360 }
361 
362 
php_mail_log_to_file(char * filename,char * message,size_t message_size)363 void php_mail_log_to_file(char *filename, char *message, size_t message_size) {
364 	/* Write 'message' to the given file. */
365 	uint32_t flags = REPORT_ERRORS | STREAM_DISABLE_OPEN_BASEDIR;
366 	php_stream *stream = php_stream_open_wrapper(filename, "a", flags, NULL);
367 	if (stream) {
368 		php_stream_write(stream, message, message_size);
369 		php_stream_close(stream);
370 	}
371 }
372 
373 
php_mail_detect_multiple_crlf(const char * hdr)374 static int php_mail_detect_multiple_crlf(const char *hdr) {
375 	/* This function detects multiple/malformed multiple newlines. */
376 
377 	if (!hdr || !strlen(hdr)) {
378 		return 0;
379 	}
380 
381 	/* Should not have any newlines at the beginning. */
382 	/* RFC 2822 2.2. Header Fields */
383 	if (*hdr < 33 || *hdr > 126 || *hdr == ':') {
384 		return 1;
385 	}
386 
387 	while(*hdr) {
388 		if (*hdr == '\r') {
389 			if (*(hdr+1) == '\0' || *(hdr+1) == '\r' || (*(hdr+1) == '\n' && (*(hdr+2) == '\0' || *(hdr+2) == '\n' || *(hdr+2) == '\r'))) {
390 				/* Malformed or multiple newlines. */
391 				return 1;
392 			} else {
393 				hdr += 2;
394 			}
395 		} else if (*hdr == '\n') {
396 			if (*(hdr+1) == '\0' || *(hdr+1) == '\r' || *(hdr+1) == '\n') {
397 				/* Malformed or multiple newlines. */
398 				return 1;
399 			} else {
400 				hdr += 2;
401 			}
402 		} else {
403 			hdr++;
404 		}
405 	}
406 
407 	return 0;
408 }
409 
410 
411 /* {{{ php_mail */
php_mail(const char * to,const char * subject,const char * message,const char * headers,const char * extra_cmd)412 PHPAPI int php_mail(const char *to, const char *subject, const char *message, const char *headers, const char *extra_cmd)
413 {
414 #ifdef PHP_WIN32
415 	int tsm_err;
416 	char *tsm_errmsg = NULL;
417 #endif
418 	FILE *sendmail;
419 	int ret;
420 	char *sendmail_path = INI_STR("sendmail_path");
421 	char *sendmail_cmd = NULL;
422 	char *mail_log = INI_STR("mail.log");
423 	const char *hdr = headers;
424 	char *ahdr = NULL;
425 #if PHP_SIGCHILD
426 	void (*sig_handler)() = NULL;
427 #endif
428 
429 #define MAIL_RET(val) \
430 	if (ahdr != NULL) {	\
431 		efree(ahdr);	\
432 	}	\
433 	return val;	\
434 
435 	if (mail_log && *mail_log) {
436 		char *logline;
437 
438 		spprintf(&logline, 0, "mail() on [%s:%d]: To: %s -- Headers: %s -- Subject: %s", zend_get_executed_filename(), zend_get_executed_lineno(), to, hdr ? hdr : "", subject);
439 
440 		if (hdr) {
441 			php_mail_log_crlf_to_spaces(logline);
442 		}
443 
444 		if (!strcmp(mail_log, "syslog")) {
445 			php_mail_log_to_syslog(logline);
446 		} else {
447 			/* Add date when logging to file */
448 			char *tmp;
449 			time_t curtime;
450 			zend_string *date_str;
451 			size_t len;
452 
453 
454 			time(&curtime);
455 			date_str = php_format_date("d-M-Y H:i:s e", 13, curtime, 1);
456 			len = spprintf(&tmp, 0, "[%s] %s%s", date_str->val, logline, PHP_EOL);
457 
458 			php_mail_log_to_file(mail_log, tmp, len);
459 
460 			zend_string_free(date_str);
461 			efree(tmp);
462 		}
463 
464 		efree(logline);
465 	}
466 
467 	if (EG(exception)) {
468 		MAIL_RET(0);
469 	}
470 
471 	char *line_sep = PG(mail_mixed_lf_and_crlf) ? "\n" : "\r\n";
472 
473 	if (PG(mail_x_header)) {
474 		const char *tmp = zend_get_executed_filename();
475 		zend_string *f;
476 
477 		f = php_basename(tmp, strlen(tmp), NULL, 0);
478 
479 		if (headers != NULL && *headers) {
480 			spprintf(&ahdr, 0, "X-PHP-Originating-Script: " ZEND_LONG_FMT ":%s%s%s", php_getuid(), ZSTR_VAL(f), line_sep, headers);
481 		} else {
482 			spprintf(&ahdr, 0, "X-PHP-Originating-Script: " ZEND_LONG_FMT ":%s", php_getuid(), ZSTR_VAL(f));
483 		}
484 		hdr = ahdr;
485 		zend_string_release_ex(f, 0);
486 	}
487 
488 	if (hdr && php_mail_detect_multiple_crlf(hdr)) {
489 		php_error_docref(NULL, E_WARNING, "Multiple or malformed newlines found in additional_header");
490 		MAIL_RET(0);
491 	}
492 
493 	if (!sendmail_path) {
494 #ifdef PHP_WIN32
495 		/* handle old style win smtp sending */
496 		if (TSendMail(INI_STR("SMTP"), &tsm_err, &tsm_errmsg, hdr, subject, to, message, NULL, NULL, NULL) == FAILURE) {
497 			if (tsm_errmsg) {
498 				php_error_docref(NULL, E_WARNING, "%s", tsm_errmsg);
499 				efree(tsm_errmsg);
500 			} else {
501 				php_error_docref(NULL, E_WARNING, "%s", GetSMErrorText(tsm_err));
502 			}
503 			MAIL_RET(0);
504 		}
505 		MAIL_RET(1);
506 #else
507 		MAIL_RET(0);
508 #endif
509 	}
510 	if (extra_cmd != NULL) {
511 		spprintf(&sendmail_cmd, 0, "%s %s", sendmail_path, extra_cmd);
512 	} else {
513 		sendmail_cmd = sendmail_path;
514 	}
515 
516 #if PHP_SIGCHILD
517 	/* Set signal handler of SIGCHLD to default to prevent other signal handlers
518 	 * from being called and reaping the return code when our child exits.
519 	 * The original handler needs to be restored after pclose() */
520 	sig_handler = (void *)signal(SIGCHLD, SIG_DFL);
521 	if (sig_handler == SIG_ERR) {
522 		sig_handler = NULL;
523 	}
524 #endif
525 
526 #ifdef PHP_WIN32
527 	sendmail = popen_ex(sendmail_cmd, "wb", NULL, NULL);
528 #else
529 	/* Since popen() doesn't indicate if the internal fork() doesn't work
530 	 * (e.g. the shell can't be executed) we explicitly set it to 0 to be
531 	 * sure we don't catch any older errno value. */
532 	errno = 0;
533 	sendmail = popen(sendmail_cmd, "w");
534 #endif
535 	if (extra_cmd != NULL) {
536 		efree (sendmail_cmd);
537 	}
538 
539 	if (sendmail) {
540 #ifndef PHP_WIN32
541 		if (EACCES == errno) {
542 			php_error_docref(NULL, E_WARNING, "Permission denied: unable to execute shell to run mail delivery binary '%s'", sendmail_path);
543 			pclose(sendmail);
544 #if PHP_SIGCHILD
545 			/* Restore handler in case of error on Windows
546 			   Not sure if this applicable on Win but just in case. */
547 			if (sig_handler) {
548 				signal(SIGCHLD, sig_handler);
549 			}
550 #endif
551 			MAIL_RET(0);
552 		}
553 #endif
554 		fprintf(sendmail, "To: %s%s", to, line_sep);
555 		fprintf(sendmail, "Subject: %s%s", subject, line_sep);
556 		if (hdr != NULL) {
557 			fprintf(sendmail, "%s%s", hdr, line_sep);
558 		}
559 		fprintf(sendmail, "%s%s%s", line_sep, message, line_sep);
560 		ret = pclose(sendmail);
561 
562 #if PHP_SIGCHILD
563 		if (sig_handler) {
564 			signal(SIGCHLD, sig_handler);
565 		}
566 #endif
567 
568 #ifdef PHP_WIN32
569 		if (ret == -1)
570 #else
571 #if defined(EX_TEMPFAIL)
572 		if ((ret != EX_OK)&&(ret != EX_TEMPFAIL))
573 #elif defined(EX_OK)
574 		if (ret != EX_OK)
575 #else
576 		if (ret != 0)
577 #endif
578 #endif
579 		{
580 			MAIL_RET(0);
581 		} else {
582 			MAIL_RET(1);
583 		}
584 	} else {
585 		php_error_docref(NULL, E_WARNING, "Could not execute mail delivery program '%s'", sendmail_path);
586 #if PHP_SIGCHILD
587 		if (sig_handler) {
588 			signal(SIGCHLD, sig_handler);
589 		}
590 #endif
591 		MAIL_RET(0);
592 	}
593 
594 	MAIL_RET(1); /* never reached */
595 }
596 /* }}} */
597 
598 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(mail)599 PHP_MINFO_FUNCTION(mail)
600 {
601 	char *sendmail_path = INI_STR("sendmail_path");
602 
603 #ifdef PHP_WIN32
604 	if (!sendmail_path) {
605 		php_info_print_table_row(2, "Internal Sendmail Support for Windows", "enabled");
606 	} else {
607 		php_info_print_table_row(2, "Path to sendmail", sendmail_path);
608 	}
609 #else
610 	php_info_print_table_row(2, "Path to sendmail", sendmail_path);
611 #endif
612 }
613 /* }}} */
614