xref: /php-src/ext/standard/head.c (revision 3af5f47c)
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@lerdorf.on.ca>                        |
14    +----------------------------------------------------------------------+
15  */
16 
17 #include <stdio.h>
18 #include "php.h"
19 #include "ext/standard/php_standard.h"
20 #include "ext/date/php_date.h"
21 #include "SAPI.h"
22 #include "php_main.h"
23 #include "head.h"
24 #include <time.h>
25 
26 #include "php_globals.h"
27 #include "zend_smart_str.h"
28 
29 
30 /* Implementation of the language Header() function */
31 /* {{{ Sends a raw HTTP header */
PHP_FUNCTION(header)32 PHP_FUNCTION(header)
33 {
34 	bool rep = 1;
35 	sapi_header_line ctr = {0};
36 	char *line;
37 	size_t len;
38 
39 	ZEND_PARSE_PARAMETERS_START(1, 3)
40 		Z_PARAM_STRING(line, len)
41 		Z_PARAM_OPTIONAL
42 		Z_PARAM_BOOL(rep)
43 		Z_PARAM_LONG(ctr.response_code)
44 	ZEND_PARSE_PARAMETERS_END();
45 
46 	ctr.line = line;
47 	ctr.line_len = (uint32_t)len;
48 	sapi_header_op(rep ? SAPI_HEADER_REPLACE:SAPI_HEADER_ADD, &ctr);
49 }
50 /* }}} */
51 
52 /* {{{ Removes an HTTP header previously set using header() */
PHP_FUNCTION(header_remove)53 PHP_FUNCTION(header_remove)
54 {
55 	sapi_header_line ctr = {0};
56 	char *line = NULL;
57 	size_t len = 0;
58 
59 	ZEND_PARSE_PARAMETERS_START(0, 1)
60 		Z_PARAM_OPTIONAL
61 		Z_PARAM_STRING_OR_NULL(line, len)
62 	ZEND_PARSE_PARAMETERS_END();
63 
64 	ctr.line = line;
65 	ctr.line_len = (uint32_t)len;
66 	sapi_header_op(line == NULL ? SAPI_HEADER_DELETE_ALL : SAPI_HEADER_DELETE, &ctr);
67 }
68 /* }}} */
69 
php_header(void)70 PHPAPI int php_header(void)
71 {
72 	if (sapi_send_headers()==FAILURE || SG(request_info).headers_only) {
73 		return 0; /* don't allow output */
74 	} else {
75 		return 1; /* allow output */
76 	}
77 }
78 
79 #define ILLEGAL_COOKIE_CHARACTER "\",\", \";\", \" \", \"\\t\", \"\\r\", \"\\n\", \"\\013\", or \"\\014\""
php_setcookie(zend_string * name,zend_string * value,time_t expires,zend_string * path,zend_string * domain,bool secure,bool httponly,zend_string * samesite,bool url_encode)80 PHPAPI zend_result php_setcookie(zend_string *name, zend_string *value, time_t expires,
81 	zend_string *path, zend_string *domain, bool secure, bool httponly,
82 	zend_string *samesite, bool url_encode)
83 {
84 	zend_string *dt;
85 	sapi_header_line ctr = {0};
86 	zend_result result;
87 	smart_str buf = {0};
88 
89 	if (!ZSTR_LEN(name)) {
90 		zend_argument_value_error(1, "cannot be empty");
91 		return FAILURE;
92 	}
93 	if (strpbrk(ZSTR_VAL(name), "=,; \t\r\n\013\014") != NULL) {   /* man isspace for \013 and \014 */
94 		zend_argument_value_error(1, "cannot contain \"=\", " ILLEGAL_COOKIE_CHARACTER);
95 		return FAILURE;
96 	}
97 	if (!url_encode && value &&
98 			strpbrk(ZSTR_VAL(value), ",; \t\r\n\013\014") != NULL) { /* man isspace for \013 and \014 */
99 		zend_argument_value_error(2, "cannot contain " ILLEGAL_COOKIE_CHARACTER);
100 		return FAILURE;
101 	}
102 
103 	if (path && strpbrk(ZSTR_VAL(path), ",; \t\r\n\013\014") != NULL) { /* man isspace for \013 and \014 */
104 		zend_value_error("%s(): \"path\" option cannot contain " ILLEGAL_COOKIE_CHARACTER,
105 			get_active_function_name());
106 		return FAILURE;
107 	}
108 	if (domain && strpbrk(ZSTR_VAL(domain), ",; \t\r\n\013\014") != NULL) { /* man isspace for \013 and \014 */
109 		zend_value_error("%s(): \"domain\" option cannot contain " ILLEGAL_COOKIE_CHARACTER,
110 			get_active_function_name());
111 		return FAILURE;
112 	}
113 #ifdef ZEND_ENABLE_ZVAL_LONG64
114 	if (expires >= 253402300800) {
115 		zend_value_error("%s(): \"expires\" option cannot have a year greater than 9999",
116 			get_active_function_name());
117 		return FAILURE;
118 	}
119 #endif
120 
121 	/* Should check value of SameSite? */
122 
123 	if (value == NULL || ZSTR_LEN(value) == 0) {
124 		/*
125 		 * MSIE doesn't delete a cookie when you set it to a null value
126 		 * so in order to force cookies to be deleted, even on MSIE, we
127 		 * pick an expiry date in the past
128 		 */
129 		dt = php_format_date("D, d M Y H:i:s \\G\\M\\T", sizeof("D, d M Y H:i:s \\G\\M\\T")-1, 1, 0);
130 		smart_str_appends(&buf, "Set-Cookie: ");
131 		smart_str_append(&buf, name);
132 		smart_str_appends(&buf, "=deleted; expires=");
133 		smart_str_append(&buf, dt);
134 		smart_str_appends(&buf, "; Max-Age=0");
135 		zend_string_free(dt);
136 	} else {
137 		smart_str_appends(&buf, "Set-Cookie: ");
138 		smart_str_append(&buf, name);
139 		smart_str_appendc(&buf, '=');
140 		if (url_encode) {
141 			zend_string *encoded_value = php_raw_url_encode(ZSTR_VAL(value), ZSTR_LEN(value));
142 			smart_str_append(&buf, encoded_value);
143 			zend_string_release_ex(encoded_value, 0);
144 		} else {
145 			smart_str_append(&buf, value);
146 		}
147 
148 		if (expires > 0) {
149 			double diff;
150 
151 			smart_str_appends(&buf, COOKIE_EXPIRES);
152 			dt = php_format_date("D, d M Y H:i:s \\G\\M\\T", sizeof("D, d M Y H:i:s \\G\\M\\T")-1, expires, 0);
153 
154 			smart_str_append(&buf, dt);
155 			zend_string_free(dt);
156 
157 			diff = difftime(expires, php_time());
158 			if (diff < 0) {
159 				diff = 0;
160 			}
161 
162 			smart_str_appends(&buf, COOKIE_MAX_AGE);
163 			smart_str_append_long(&buf, (zend_long) diff);
164 		}
165 	}
166 
167 	if (path && ZSTR_LEN(path)) {
168 		smart_str_appends(&buf, COOKIE_PATH);
169 		smart_str_append(&buf, path);
170 	}
171 	if (domain && ZSTR_LEN(domain)) {
172 		smart_str_appends(&buf, COOKIE_DOMAIN);
173 		smart_str_append(&buf, domain);
174 	}
175 	if (secure) {
176 		smart_str_appends(&buf, COOKIE_SECURE);
177 	}
178 	if (httponly) {
179 		smart_str_appends(&buf, COOKIE_HTTPONLY);
180 	}
181 	if (samesite && ZSTR_LEN(samesite)) {
182 		smart_str_appends(&buf, COOKIE_SAMESITE);
183 		smart_str_append(&buf, samesite);
184 	}
185 
186 	ctr.line = ZSTR_VAL(buf.s);
187 	ctr.line_len = (uint32_t) ZSTR_LEN(buf.s);
188 
189 	result = sapi_header_op(SAPI_HEADER_ADD, &ctr);
190 	zend_string_release(buf.s);
191 	return result;
192 }
193 
php_head_parse_cookie_options_array(HashTable * options,zend_long * expires,zend_string ** path,zend_string ** domain,bool * secure,bool * httponly,zend_string ** samesite)194 static zend_result php_head_parse_cookie_options_array(HashTable *options, zend_long *expires, zend_string **path,
195 		zend_string **domain, bool *secure, bool *httponly, zend_string **samesite)
196 {
197 	zend_string *key;
198 	zval *value;
199 
200 	ZEND_HASH_FOREACH_STR_KEY_VAL(options, key, value) {
201 		if (!key) {
202 			zend_value_error("%s(): option array cannot have numeric keys", get_active_function_name());
203 			return FAILURE;
204 		}
205 		if (zend_string_equals_literal_ci(key, "expires")) {
206 			*expires = zval_get_long(value);
207 		} else if (zend_string_equals_literal_ci(key, "path")) {
208 			*path = zval_get_string(value);
209 		} else if (zend_string_equals_literal_ci(key, "domain")) {
210 			*domain = zval_get_string(value);
211 		} else if (zend_string_equals_literal_ci(key, "secure")) {
212 			*secure = zval_is_true(value);
213 		} else if (zend_string_equals_literal_ci(key, "httponly")) {
214 			*httponly = zval_is_true(value);
215 		} else if (zend_string_equals_literal_ci(key, "samesite")) {
216 			*samesite = zval_get_string(value);
217 		} else {
218 			zend_value_error("%s(): option \"%s\" is invalid", get_active_function_name(), ZSTR_VAL(key));
219 			return FAILURE;
220 		}
221 	} ZEND_HASH_FOREACH_END();
222 	return SUCCESS;
223 }
224 
php_setcookie_common(INTERNAL_FUNCTION_PARAMETERS,bool is_raw)225 static void php_setcookie_common(INTERNAL_FUNCTION_PARAMETERS, bool is_raw)
226 {
227 	HashTable *options = NULL;
228 	zend_long expires = 0;
229 	zend_string *name, *value = NULL, *path = NULL, *domain = NULL, *samesite = NULL;
230 	bool secure = 0, httponly = 0;
231 
232 	ZEND_PARSE_PARAMETERS_START(1, 7)
233 		Z_PARAM_STR(name)
234 		Z_PARAM_OPTIONAL
235 		Z_PARAM_STR(value)
236 		Z_PARAM_ARRAY_HT_OR_LONG(options, expires)
237 		Z_PARAM_STR(path)
238 		Z_PARAM_STR(domain)
239 		Z_PARAM_BOOL(secure)
240 		Z_PARAM_BOOL(httponly)
241 	ZEND_PARSE_PARAMETERS_END();
242 
243 	if (options) {
244 		if (UNEXPECTED(ZEND_NUM_ARGS() > 3)) {
245 			zend_argument_count_error("%s(): Expects exactly 3 arguments when argument #3 "
246 				"($expires_or_options) is an array", get_active_function_name());
247 			RETURN_THROWS();
248 		}
249 
250 		if (FAILURE == php_head_parse_cookie_options_array(options, &expires, &path,
251 			&domain, &secure, &httponly, &samesite)
252 		) {
253 			goto cleanup;
254 		}
255 	}
256 
257 	if (php_setcookie(name, value, expires, path, domain, secure, httponly, samesite, !is_raw) == SUCCESS) {
258 		RETVAL_TRUE;
259 	} else {
260 		RETVAL_FALSE;
261 	}
262 
263 	if (options) {
264 cleanup:
265 		if (path) {
266 			zend_string_release(path);
267 		}
268 		if (domain) {
269 			zend_string_release(domain);
270 		}
271 		if (samesite) {
272 			zend_string_release(samesite);
273 		}
274 	}
275 }
276 
277 /* {{{ setcookie(string name [, string value [, array options]])
278    Send a cookie */
PHP_FUNCTION(setcookie)279 PHP_FUNCTION(setcookie)
280 {
281 	php_setcookie_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, false);
282 }
283 /* }}} */
284 
285 /* {{{ setrawcookie(string name [, string value [, array options]])
286    Send a cookie with no url encoding of the value */
PHP_FUNCTION(setrawcookie)287 PHP_FUNCTION(setrawcookie)
288 {
289 	php_setcookie_common(INTERNAL_FUNCTION_PARAM_PASSTHRU, true);
290 }
291 /* }}} */
292 
293 
294 /* {{{ Returns true if headers have already been sent, false otherwise */
PHP_FUNCTION(headers_sent)295 PHP_FUNCTION(headers_sent)
296 {
297 	zval *arg1 = NULL, *arg2 = NULL;
298 	const char *file="";
299 	int line=0;
300 
301 	ZEND_PARSE_PARAMETERS_START(0, 2)
302 		Z_PARAM_OPTIONAL
303 		Z_PARAM_ZVAL(arg1)
304 		Z_PARAM_ZVAL(arg2)
305 	ZEND_PARSE_PARAMETERS_END();
306 
307 	if (SG(headers_sent)) {
308 		line = php_output_get_start_lineno();
309 		file = php_output_get_start_filename();
310 	}
311 
312 	switch(ZEND_NUM_ARGS()) {
313 	case 2:
314 		ZEND_TRY_ASSIGN_REF_LONG(arg2, line);
315 		ZEND_FALLTHROUGH;
316 	case 1:
317 		if (file) {
318 			ZEND_TRY_ASSIGN_REF_STRING(arg1, file);
319 		} else {
320 			ZEND_TRY_ASSIGN_REF_EMPTY_STRING(arg1);
321 		}
322 		break;
323 	}
324 
325 	if (SG(headers_sent)) {
326 		RETURN_TRUE;
327 	} else {
328 		RETURN_FALSE;
329 	}
330 }
331 /* }}} */
332 
333 /* {{{ php_head_apply_header_list_to_hash
334    Turn an llist of sapi_header_struct headers into a numerically indexed zval hash */
php_head_apply_header_list_to_hash(void * data,void * arg)335 static void php_head_apply_header_list_to_hash(void *data, void *arg)
336 {
337 	sapi_header_struct *sapi_header = (sapi_header_struct *)data;
338 
339 	if (arg && sapi_header) {
340 		add_next_index_string((zval *)arg, (char *)(sapi_header->header));
341 	}
342 }
343 
344 /* {{{ Return list of headers to be sent / already sent */
PHP_FUNCTION(headers_list)345 PHP_FUNCTION(headers_list)
346 {
347 	ZEND_PARSE_PARAMETERS_NONE();
348 
349 	array_init(return_value);
350 	zend_llist_apply_with_argument(&SG(sapi_headers).headers, php_head_apply_header_list_to_hash, return_value);
351 }
352 /* }}} */
353 
354 /* {{{ Sets a response code, or returns the current HTTP response code */
PHP_FUNCTION(http_response_code)355 PHP_FUNCTION(http_response_code)
356 {
357 	zend_long response_code = 0;
358 
359 	ZEND_PARSE_PARAMETERS_START(0, 1)
360 		Z_PARAM_OPTIONAL
361 		Z_PARAM_LONG(response_code)
362 	ZEND_PARSE_PARAMETERS_END();
363 
364 	if (response_code)
365 	{
366 		if (SG(headers_sent) && !SG(request_info).no_headers) {
367 			const char *output_start_filename = php_output_get_start_filename();
368 			int output_start_lineno = php_output_get_start_lineno();
369 
370 			if (output_start_filename) {
371 				php_error_docref(NULL, E_WARNING, "Cannot set response code - headers already sent "
372 					"(output started at %s:%d)", output_start_filename, output_start_lineno);
373 			} else {
374 				php_error_docref(NULL, E_WARNING, "Cannot set response code - headers already sent");
375 			}
376 			RETURN_FALSE;
377 		}
378 		zend_long old_response_code;
379 
380 		old_response_code = SG(sapi_headers).http_response_code;
381 		SG(sapi_headers).http_response_code = (int)response_code;
382 
383 		if (old_response_code) {
384 			RETURN_LONG(old_response_code);
385 		}
386 
387 		RETURN_TRUE;
388 	}
389 
390 	if (!SG(sapi_headers).http_response_code) {
391 		RETURN_FALSE;
392 	}
393 
394 	RETURN_LONG(SG(sapi_headers).http_response_code);
395 }
396 /* }}} */
397