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