xref: /php-src/ext/session/session.c (revision c7797fc8)
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    | Authors: Sascha Schumann <sascha@schumann.cx>                        |
14    |          Andrei Zmievski <andrei@php.net>                            |
15    +----------------------------------------------------------------------+
16  */
17 
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21 
22 #include "php.h"
23 
24 #ifdef PHP_WIN32
25 # include "win32/winutil.h"
26 # include "win32/time.h"
27 #else
28 # include <sys/time.h>
29 #endif
30 
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 
34 #include "php_ini.h"
35 #include "SAPI.h"
36 #include "rfc1867.h"
37 #include "php_variables.h"
38 #include "php_session.h"
39 #include "session_arginfo.h"
40 #include "ext/standard/php_var.h"
41 #include "ext/date/php_date.h"
42 #include "ext/standard/url_scanner_ex.h"
43 #include "ext/standard/info.h"
44 #include "zend_smart_str.h"
45 #include "ext/standard/url.h"
46 #include "ext/standard/basic_functions.h"
47 #include "ext/standard/head.h"
48 #include "ext/random/php_random.h"
49 #include "ext/random/php_random_csprng.h"
50 
51 #include "mod_files.h"
52 #include "mod_user.h"
53 
54 #ifdef HAVE_LIBMM
55 #include "mod_mm.h"
56 #endif
57 
58 PHPAPI ZEND_DECLARE_MODULE_GLOBALS(ps)
59 
60 static zend_result php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra);
61 static zend_result (*php_session_rfc1867_orig_callback)(unsigned int event, void *event_data, void **extra);
62 static void php_session_track_init(void);
63 
64 /* SessionHandler class */
65 zend_class_entry *php_session_class_entry;
66 
67 /* SessionHandlerInterface */
68 zend_class_entry *php_session_iface_entry;
69 
70 /* SessionIdInterface */
71 zend_class_entry *php_session_id_iface_entry;
72 
73 /* SessionUpdateTimestampInterface */
74 zend_class_entry *php_session_update_timestamp_iface_entry;
75 
76 #define PS_MAX_SID_LENGTH 256
77 
78 /* ***********
79    * Helpers *
80    *********** */
81 
82 #define IF_SESSION_VARS() \
83 	if (Z_ISREF_P(&PS(http_session_vars)) && Z_TYPE_P(Z_REFVAL(PS(http_session_vars))) == IS_ARRAY)
84 
85 #define SESSION_CHECK_ACTIVE_STATE	\
86 	if (PS(session_status) == php_session_active) {	\
87 		php_error_docref(NULL, E_WARNING, "Session ini settings cannot be changed when a session is active");	\
88 		return FAILURE;	\
89 	}
90 
91 #define SESSION_CHECK_OUTPUT_STATE										\
92 	if (SG(headers_sent) && stage != ZEND_INI_STAGE_DEACTIVATE) {												\
93 		php_error_docref(NULL, E_WARNING, "Session ini settings cannot be changed after headers have already been sent");	\
94 		return FAILURE;													\
95 	}
96 
97 #define SESSION_FORBIDDEN_CHARS "=,;.[ \t\r\n\013\014"
98 
99 #define APPLY_TRANS_SID (PS(use_trans_sid) && !PS(use_only_cookies))
100 
101 static zend_result php_session_send_cookie(void);
102 static zend_result php_session_abort(void);
103 
104 /* Initialized in MINIT, readonly otherwise. */
105 static int my_module_number = 0;
106 
107 /* Dispatched by RINIT and by php_session_destroy */
php_rinit_session_globals(void)108 static inline void php_rinit_session_globals(void) /* {{{ */
109 {
110 	/* Do NOT init PS(mod_user_names) here! */
111 	/* TODO: These could be moved to MINIT and removed. These should be initialized by php_rshutdown_session_globals() always when execution is finished. */
112 	PS(id) = NULL;
113 	PS(session_status) = php_session_none;
114 	PS(in_save_handler) = 0;
115 	PS(set_handler) = 0;
116 	PS(mod_data) = NULL;
117 	PS(mod_user_is_open) = 0;
118 	PS(define_sid) = 1;
119 	PS(session_vars) = NULL;
120 	PS(module_number) = my_module_number;
121 	ZVAL_UNDEF(&PS(http_session_vars));
122 }
123 /* }}} */
124 
php_session_cleanup_filename(void)125 static inline void php_session_cleanup_filename(void) /* {{{ */
126 {
127 	if (PS(session_started_filename)) {
128 		zend_string_release(PS(session_started_filename));
129 		PS(session_started_filename) = NULL;
130 		PS(session_started_lineno) = 0;
131 	}
132 }
133 /* }}} */
134 
135 /* Dispatched by RSHUTDOWN and by php_session_destroy */
php_rshutdown_session_globals(void)136 static inline void php_rshutdown_session_globals(void) /* {{{ */
137 {
138 	/* Do NOT destroy PS(mod_user_names) here! */
139 	if (!Z_ISUNDEF(PS(http_session_vars))) {
140 		zval_ptr_dtor(&PS(http_session_vars));
141 		ZVAL_UNDEF(&PS(http_session_vars));
142 	}
143 	if (PS(mod_data) || PS(mod_user_implemented)) {
144 		zend_try {
145 			PS(mod)->s_close(&PS(mod_data));
146 		} zend_end_try();
147 	}
148 	if (PS(id)) {
149 		zend_string_release_ex(PS(id), 0);
150 		PS(id) = NULL;
151 	}
152 
153 	if (PS(session_vars)) {
154 		zend_string_release_ex(PS(session_vars), 0);
155 		PS(session_vars) = NULL;
156 	}
157 
158 	if (PS(mod_user_class_name)) {
159 		zend_string_release(PS(mod_user_class_name));
160 		PS(mod_user_class_name) = NULL;
161 	}
162 
163 	php_session_cleanup_filename();
164 
165 	/* User save handlers may end up directly here by misuse, bugs in user script, etc. */
166 	/* Set session status to prevent error while restoring save handler INI value. */
167 	PS(session_status) = php_session_none;
168 }
169 /* }}} */
170 
php_session_destroy(void)171 PHPAPI zend_result php_session_destroy(void) /* {{{ */
172 {
173 	zend_result retval = SUCCESS;
174 
175 	if (PS(session_status) != php_session_active) {
176 		php_error_docref(NULL, E_WARNING, "Trying to destroy uninitialized session");
177 		return FAILURE;
178 	}
179 
180 	if (PS(id) && PS(mod)->s_destroy(&PS(mod_data), PS(id)) == FAILURE) {
181 		retval = FAILURE;
182 		if (!EG(exception)) {
183 			php_error_docref(NULL, E_WARNING, "Session object destruction failed");
184 		}
185 	}
186 
187 	php_rshutdown_session_globals();
188 	php_rinit_session_globals();
189 
190 	return retval;
191 }
192 /* }}} */
193 
php_add_session_var(zend_string * name)194 PHPAPI void php_add_session_var(zend_string *name) /* {{{ */
195 {
196 	IF_SESSION_VARS() {
197 		zval *sess_var = Z_REFVAL(PS(http_session_vars));
198 		SEPARATE_ARRAY(sess_var);
199 		if (!zend_hash_exists(Z_ARRVAL_P(sess_var), name)) {
200 			zval empty_var;
201 			ZVAL_NULL(&empty_var);
202 			zend_hash_update(Z_ARRVAL_P(sess_var), name, &empty_var);
203 		}
204 	}
205 }
206 /* }}} */
207 
php_set_session_var(zend_string * name,zval * state_val,php_unserialize_data_t * var_hash)208 PHPAPI zval* php_set_session_var(zend_string *name, zval *state_val, php_unserialize_data_t *var_hash) /* {{{ */
209 {
210 	IF_SESSION_VARS() {
211 		zval *sess_var = Z_REFVAL(PS(http_session_vars));
212 		SEPARATE_ARRAY(sess_var);
213 		return zend_hash_update(Z_ARRVAL_P(sess_var), name, state_val);
214 	}
215 	return NULL;
216 }
217 /* }}} */
218 
php_get_session_var(zend_string * name)219 PHPAPI zval* php_get_session_var(zend_string *name) /* {{{ */
220 {
221 	IF_SESSION_VARS() {
222 		return zend_hash_find(Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars))), name);
223 	}
224 	return NULL;
225 }
226 /* }}} */
227 
php_get_session_var_str(const char * name,size_t name_len)228 PHPAPI zval* php_get_session_var_str(const char *name, size_t name_len)
229 {
230 	IF_SESSION_VARS() {
231 		return zend_hash_str_find(Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars))), name, name_len);
232 	}
233 	return NULL;
234 }
235 
php_session_track_init(void)236 static void php_session_track_init(void) /* {{{ */
237 {
238 	zval session_vars;
239 	zend_string *var_name = ZSTR_INIT_LITERAL("_SESSION", 0);
240 	/* Unconditionally destroy existing array -- possible dirty data */
241 	zend_delete_global_variable(var_name);
242 
243 	if (!Z_ISUNDEF(PS(http_session_vars))) {
244 		zval_ptr_dtor(&PS(http_session_vars));
245 	}
246 
247 	array_init(&session_vars);
248 	ZVAL_NEW_REF(&PS(http_session_vars), &session_vars);
249 	Z_ADDREF_P(&PS(http_session_vars));
250 	zend_hash_update_ind(&EG(symbol_table), var_name, &PS(http_session_vars));
251 	zend_string_release_ex(var_name, 0);
252 }
253 /* }}} */
254 
php_session_encode(void)255 static zend_string *php_session_encode(void) /* {{{ */
256 {
257 	IF_SESSION_VARS() {
258         ZEND_ASSERT(PS(serializer));
259 		return PS(serializer)->encode();
260 	} else {
261 		php_error_docref(NULL, E_WARNING, "Cannot encode non-existent session");
262 	}
263 	return NULL;
264 }
265 /* }}} */
266 
php_session_cancel_decode(void)267 static ZEND_COLD void php_session_cancel_decode(void)
268 {
269 	php_session_destroy();
270 	php_session_track_init();
271 	php_error_docref(NULL, E_WARNING, "Failed to decode session object. Session has been destroyed");
272 }
273 
php_session_decode(zend_string * data)274 static zend_result php_session_decode(zend_string *data) /* {{{ */
275 {
276     ZEND_ASSERT(PS(serializer));
277 	zend_result result = SUCCESS;
278 	zend_try {
279 		if (PS(serializer)->decode(ZSTR_VAL(data), ZSTR_LEN(data)) == FAILURE) {
280 			php_session_cancel_decode();
281 			result = FAILURE;
282 		}
283 	} zend_catch {
284 		php_session_cancel_decode();
285 		zend_bailout();
286 	} zend_end_try();
287 	return result;
288 }
289 /* }}} */
290 
291 /*
292  * Note that we cannot use the BASE64 alphabet here, because
293  * it contains "/" and "+": both are unacceptable for simple inclusion
294  * into URLs.
295  */
296 
297 static const char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-";
298 
bin_to_readable(unsigned char * in,size_t inlen,char * out,size_t outlen,char nbits)299 static void bin_to_readable(unsigned char *in, size_t inlen, char *out, size_t outlen, char nbits) /* {{{ */
300 {
301 	unsigned char *p, *q;
302 	unsigned short w;
303 	int mask;
304 	int have;
305 
306 	p = (unsigned char *)in;
307 	q = (unsigned char *)in + inlen;
308 
309 	w = 0;
310 	have = 0;
311 	mask = (1 << nbits) - 1;
312 
313 	while (outlen--) {
314 		if (have < nbits) {
315 			if (p < q) {
316 				w |= *p++ << have;
317 				have += 8;
318 			} else {
319 				/* Should never happen. Input must be large enough. */
320 				ZEND_UNREACHABLE();
321 				break;
322 			}
323 		}
324 
325 		/* consume nbits */
326 		*out++ = hexconvtab[w & mask];
327 		w >>= nbits;
328 		have -= nbits;
329 	}
330 
331 	*out = '\0';
332 }
333 /* }}} */
334 
php_session_create_id(PS_CREATE_SID_ARGS)335 PHPAPI zend_string *php_session_create_id(PS_CREATE_SID_ARGS) /* {{{ */
336 {
337 	unsigned char rbuf[PS_MAX_SID_LENGTH];
338 	zend_string *outid;
339 
340 	/* It would be enough to read ceil(sid_length * sid_bits_per_character / 8) bytes here.
341 	 * We read sid_length bytes instead for simplicity. */
342 	if (php_random_bytes_throw(rbuf, PS(sid_length)) == FAILURE) {
343 		return NULL;
344 	}
345 
346 	outid = zend_string_alloc(PS(sid_length), 0);
347 	bin_to_readable(
348 		rbuf, PS(sid_length),
349 		ZSTR_VAL(outid), ZSTR_LEN(outid),
350 		(char)PS(sid_bits_per_character));
351 
352 	return outid;
353 }
354 /* }}} */
355 
356 /* Default session id char validation function allowed by ps_modules.
357  * If you change the logic here, please also update the error message in
358  * ps_modules appropriately */
php_session_valid_key(const char * key)359 PHPAPI zend_result php_session_valid_key(const char *key) /* {{{ */
360 {
361 	size_t len;
362 	const char *p;
363 	char c;
364 	zend_result ret = SUCCESS;
365 
366 	for (p = key; (c = *p); p++) {
367 		/* valid characters are a..z,A..Z,0..9 */
368 		if (!((c >= 'a' && c <= 'z')
369 				|| (c >= 'A' && c <= 'Z')
370 				|| (c >= '0' && c <= '9')
371 				|| c == ','
372 				|| c == '-')) {
373 			ret = FAILURE;
374 			break;
375 		}
376 	}
377 
378 	len = p - key;
379 
380 	/* Somewhat arbitrary length limit here, but should be way more than
381 	   anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */
382 	if (len == 0 || len > PS_MAX_SID_LENGTH) {
383 		ret = FAILURE;
384 	}
385 
386 	return ret;
387 }
388 /* }}} */
389 
390 
php_session_gc(bool immediate)391 static zend_long php_session_gc(bool immediate) /* {{{ */
392 {
393 	zend_long num = -1;
394 	bool collect = immediate;
395 
396 	/* GC must be done before reading session data. */
397 	if ((PS(mod_data) || PS(mod_user_implemented))) {
398 		if (!collect && PS(gc_probability) > 0) {
399 			collect = php_random_range(PS(random), 0, PS(gc_divisor) - 1) < PS(gc_probability);
400 		}
401 
402 		if (collect) {
403 			PS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &num);
404 		}
405 	}
406 	return num;
407 } /* }}} */
408 
php_session_initialize(void)409 static zend_result php_session_initialize(void) /* {{{ */
410 {
411 	zend_string *val = NULL;
412 
413 	PS(session_status) = php_session_active;
414 
415 	if (!PS(mod)) {
416 		PS(session_status) = php_session_disabled;
417 		php_error_docref(NULL, E_WARNING, "No storage module chosen - failed to initialize session");
418 		return FAILURE;
419 	}
420 
421 	/* Open session handler first */
422 	if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name)) == FAILURE
423 		/* || PS(mod_data) == NULL */ /* FIXME: open must set valid PS(mod_data) with success */
424 	) {
425 		php_session_abort();
426 		if (!EG(exception)) {
427 			php_error_docref(NULL, E_WARNING, "Failed to initialize storage module: %s (path: %s)", PS(mod)->s_name, PS(save_path));
428 		}
429 		return FAILURE;
430 	}
431 
432 	/* If there is no ID, use session module to create one */
433 	if (!PS(id) || !ZSTR_VAL(PS(id))[0]) {
434 		if (PS(id)) {
435 			zend_string_release_ex(PS(id), 0);
436 		}
437 		PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
438 		if (!PS(id)) {
439 			php_session_abort();
440 			if (!EG(exception)) {
441 				zend_throw_error(NULL, "Failed to create session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
442 			}
443 			return FAILURE;
444 		}
445 		if (PS(use_cookies)) {
446 			PS(send_cookie) = 1;
447 		}
448 	} else if (PS(use_strict_mode) && PS(mod)->s_validate_sid &&
449 		PS(mod)->s_validate_sid(&PS(mod_data), PS(id)) == FAILURE
450 	) {
451 		if (PS(id)) {
452 			zend_string_release_ex(PS(id), 0);
453 		}
454 		PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
455 		if (!PS(id)) {
456 			PS(id) = php_session_create_id(NULL);
457 		}
458 		if (PS(use_cookies)) {
459 			PS(send_cookie) = 1;
460 		}
461 	}
462 
463 	if (php_session_reset_id() == FAILURE) {
464 		php_session_abort();
465 		return FAILURE;
466 	}
467 
468 	/* Read data */
469 	php_session_track_init();
470 	if (PS(mod)->s_read(&PS(mod_data), PS(id), &val, PS(gc_maxlifetime)) == FAILURE) {
471 		php_session_abort();
472 		/* FYI: Some broken save handlers return FAILURE for non-existent session ID, this is incorrect */
473 		if (!EG(exception)) {
474 			php_error_docref(NULL, E_WARNING, "Failed to read session data: %s (path: %s)", PS(mod)->s_name, PS(save_path));
475 		}
476 		return FAILURE;
477 	}
478 
479 	/* GC must be done after read */
480 	php_session_gc(0);
481 
482 	if (PS(session_vars)) {
483 		zend_string_release_ex(PS(session_vars), 0);
484 		PS(session_vars) = NULL;
485 	}
486 	if (val) {
487 		if (PS(lazy_write)) {
488 			PS(session_vars) = zend_string_copy(val);
489 		}
490 		php_session_decode(val);
491 		zend_string_release_ex(val, 0);
492 	}
493 
494 	php_session_cleanup_filename();
495 	zend_string *session_started_filename = zend_get_executed_filename_ex();
496 	if (session_started_filename != NULL) {
497 		PS(session_started_filename) = zend_string_copy(session_started_filename);
498 		PS(session_started_lineno) = zend_get_executed_lineno();
499 	}
500 	return SUCCESS;
501 }
502 /* }}} */
503 
php_session_save_current_state(int write)504 static void php_session_save_current_state(int write) /* {{{ */
505 {
506 	zend_result ret = FAILURE;
507 
508 	if (write) {
509 		IF_SESSION_VARS() {
510 			zend_string *handler_class_name = PS(mod_user_class_name);
511 			const char *handler_function_name;
512 
513 			if (PS(mod_data) || PS(mod_user_implemented)) {
514 				zend_string *val;
515 
516 				val = php_session_encode();
517 				if (val) {
518 					if (PS(lazy_write) && PS(session_vars)
519 						&& PS(mod)->s_update_timestamp
520 						&& PS(mod)->s_update_timestamp != php_session_update_timestamp
521 						&& zend_string_equals(val, PS(session_vars))
522 					) {
523 						ret = PS(mod)->s_update_timestamp(&PS(mod_data), PS(id), val, PS(gc_maxlifetime));
524 						handler_function_name = handler_class_name != NULL ? "updateTimestamp" : "update_timestamp";
525 					} else {
526 						ret = PS(mod)->s_write(&PS(mod_data), PS(id), val, PS(gc_maxlifetime));
527 						handler_function_name = "write";
528 					}
529 					zend_string_release_ex(val, 0);
530 				} else {
531 					ret = PS(mod)->s_write(&PS(mod_data), PS(id), ZSTR_EMPTY_ALLOC(), PS(gc_maxlifetime));
532 					handler_function_name = "write";
533 				}
534 			}
535 
536 			if ((ret == FAILURE) && !EG(exception)) {
537 				if (!PS(mod_user_implemented)) {
538 					php_error_docref(NULL, E_WARNING, "Failed to write session data (%s). Please "
539 									 "verify that the current setting of session.save_path "
540 									 "is correct (%s)",
541 									 PS(mod)->s_name,
542 									 PS(save_path));
543 				} else if (handler_class_name != NULL) {
544 					php_error_docref(NULL, E_WARNING, "Failed to write session data using user "
545 									 "defined save handler. (session.save_path: %s, handler: %s::%s)", PS(save_path),
546 									 ZSTR_VAL(handler_class_name), handler_function_name);
547 				} else {
548 					php_error_docref(NULL, E_WARNING, "Failed to write session data using user "
549 									 "defined save handler. (session.save_path: %s, handler: %s)", PS(save_path),
550 									 handler_function_name);
551 				}
552 			}
553 		}
554 	}
555 
556 	if (PS(mod_data) || PS(mod_user_implemented)) {
557 		PS(mod)->s_close(&PS(mod_data));
558 	}
559 }
560 /* }}} */
561 
php_session_normalize_vars(void)562 static void php_session_normalize_vars(void) /* {{{ */
563 {
564 	PS_ENCODE_VARS;
565 
566 	IF_SESSION_VARS() {
567 		PS_ENCODE_LOOP(
568 			if (Z_TYPE_P(struc) == IS_PTR) {
569 				zval *zv = (zval *)Z_PTR_P(struc);
570 				ZVAL_COPY_VALUE(struc, zv);
571 				ZVAL_UNDEF(zv);
572 			}
573 		);
574 	}
575 }
576 /* }}} */
577 
578 /* *************************
579    * INI Settings/Handlers *
580    ************************* */
581 
PHP_INI_MH(OnUpdateSaveHandler)582 static PHP_INI_MH(OnUpdateSaveHandler) /* {{{ */
583 {
584 	const ps_module *tmp;
585 	int err_type = E_ERROR;
586 
587 	SESSION_CHECK_ACTIVE_STATE;
588 	SESSION_CHECK_OUTPUT_STATE;
589 
590 	tmp = _php_find_ps_module(ZSTR_VAL(new_value));
591 
592 	if (stage == ZEND_INI_STAGE_RUNTIME) {
593 		err_type = E_WARNING;
594 	}
595 
596 	if (PG(modules_activated) && !tmp) {
597 		/* Do not output error when restoring ini options. */
598 		if (stage != ZEND_INI_STAGE_DEACTIVATE) {
599 			php_error_docref(NULL, err_type, "Session save handler \"%s\" cannot be found", ZSTR_VAL(new_value));
600 		}
601 
602 		return FAILURE;
603 	}
604 
605 	/* "user" save handler should not be set by user */
606 	if (!PS(set_handler) &&  tmp == ps_user_ptr) {
607 		php_error_docref(NULL, err_type, "Session save handler \"user\" cannot be set by ini_set()");
608 		return FAILURE;
609 	}
610 
611 	PS(default_mod) = PS(mod);
612 	PS(mod) = tmp;
613 
614 	return SUCCESS;
615 }
616 /* }}} */
617 
PHP_INI_MH(OnUpdateSerializer)618 static PHP_INI_MH(OnUpdateSerializer) /* {{{ */
619 {
620 	const ps_serializer *tmp;
621 
622 	SESSION_CHECK_ACTIVE_STATE;
623 	SESSION_CHECK_OUTPUT_STATE;
624 
625 	tmp = _php_find_ps_serializer(ZSTR_VAL(new_value));
626 
627 	if (PG(modules_activated) && !tmp) {
628 		int err_type;
629 
630 		if (stage == ZEND_INI_STAGE_RUNTIME) {
631 			err_type = E_WARNING;
632 		} else {
633 			err_type = E_ERROR;
634 		}
635 
636 		/* Do not output error when restoring ini options. */
637 		if (stage != ZEND_INI_STAGE_DEACTIVATE) {
638 			php_error_docref(NULL, err_type, "Serialization handler \"%s\" cannot be found", ZSTR_VAL(new_value));
639 		}
640 		return FAILURE;
641 	}
642 	PS(serializer) = tmp;
643 
644 	return SUCCESS;
645 }
646 /* }}} */
647 
PHP_INI_MH(OnUpdateSaveDir)648 static PHP_INI_MH(OnUpdateSaveDir) /* {{{ */
649 {
650 	SESSION_CHECK_ACTIVE_STATE;
651 	SESSION_CHECK_OUTPUT_STATE;
652 
653 	/* Only do the safemode/open_basedir check at runtime */
654 	if (stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) {
655 		char *p;
656 
657 		if (memchr(ZSTR_VAL(new_value), '\0', ZSTR_LEN(new_value)) != NULL) {
658 			return FAILURE;
659 		}
660 
661 		/* we do not use zend_memrchr() since path can contain ; itself */
662 		if ((p = strchr(ZSTR_VAL(new_value), ';'))) {
663 			char *p2;
664 			p++;
665 			if ((p2 = strchr(p, ';'))) {
666 				p = p2 + 1;
667 			}
668 		} else {
669 			p = ZSTR_VAL(new_value);
670 		}
671 
672 		if (PG(open_basedir) && *p && php_check_open_basedir(p)) {
673 			return FAILURE;
674 		}
675 	}
676 
677 	return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
678 }
679 /* }}} */
680 
681 
PHP_INI_MH(OnUpdateName)682 static PHP_INI_MH(OnUpdateName) /* {{{ */
683 {
684 	SESSION_CHECK_ACTIVE_STATE;
685 	SESSION_CHECK_OUTPUT_STATE;
686 
687 	/* Numeric session.name won't work at all */
688 	if ((!ZSTR_LEN(new_value) || is_numeric_string(ZSTR_VAL(new_value), ZSTR_LEN(new_value), NULL, NULL, 0))) {
689 		int err_type;
690 
691 		if (stage == ZEND_INI_STAGE_RUNTIME || stage == ZEND_INI_STAGE_ACTIVATE || stage == ZEND_INI_STAGE_STARTUP) {
692 			err_type = E_WARNING;
693 		} else {
694 			err_type = E_ERROR;
695 		}
696 
697 		/* Do not output error when restoring ini options. */
698 		if (stage != ZEND_INI_STAGE_DEACTIVATE) {
699 			php_error_docref(NULL, err_type, "session.name \"%s\" cannot be numeric or empty", ZSTR_VAL(new_value));
700 		}
701 		return FAILURE;
702 	}
703 
704 	return OnUpdateStringUnempty(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
705 }
706 /* }}} */
707 
708 
PHP_INI_MH(OnUpdateCookieLifetime)709 static PHP_INI_MH(OnUpdateCookieLifetime) /* {{{ */
710 {
711 	SESSION_CHECK_ACTIVE_STATE;
712 	SESSION_CHECK_OUTPUT_STATE;
713 	if (atol(ZSTR_VAL(new_value)) < 0) {
714 		php_error_docref(NULL, E_WARNING, "CookieLifetime cannot be negative");
715 		return FAILURE;
716 	}
717 	return OnUpdateLongGEZero(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
718 }
719 /* }}} */
720 
721 
PHP_INI_MH(OnUpdateSessionLong)722 static PHP_INI_MH(OnUpdateSessionLong) /* {{{ */
723 {
724 	SESSION_CHECK_ACTIVE_STATE;
725 	SESSION_CHECK_OUTPUT_STATE;
726 	return OnUpdateLong(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
727 }
728 /* }}} */
729 
730 
PHP_INI_MH(OnUpdateSessionString)731 static PHP_INI_MH(OnUpdateSessionString) /* {{{ */
732 {
733 	SESSION_CHECK_ACTIVE_STATE;
734 	SESSION_CHECK_OUTPUT_STATE;
735 	return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
736 }
737 /* }}} */
738 
739 
PHP_INI_MH(OnUpdateSessionBool)740 static PHP_INI_MH(OnUpdateSessionBool) /* {{{ */
741 {
742 	SESSION_CHECK_ACTIVE_STATE;
743 	SESSION_CHECK_OUTPUT_STATE;
744 	return OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
745 }
746 /* }}} */
747 
748 
PHP_INI_MH(OnUpdateSidLength)749 static PHP_INI_MH(OnUpdateSidLength) /* {{{ */
750 {
751 	zend_long val;
752 	char *endptr = NULL;
753 
754 	SESSION_CHECK_ACTIVE_STATE;
755 	SESSION_CHECK_OUTPUT_STATE;
756 	val = ZEND_STRTOL(ZSTR_VAL(new_value), &endptr, 10);
757 	if (endptr && (*endptr == '\0')
758 		&& val >= 22 && val <= PS_MAX_SID_LENGTH) {
759 		/* Numeric value */
760 		PS(sid_length) = val;
761 		return SUCCESS;
762 	}
763 
764 	php_error_docref(NULL, E_WARNING, "session.configuration \"session.sid_length\" must be between 22 and 256");
765 	return FAILURE;
766 }
767 /* }}} */
768 
PHP_INI_MH(OnUpdateSidBits)769 static PHP_INI_MH(OnUpdateSidBits) /* {{{ */
770 {
771 	zend_long val;
772 	char *endptr = NULL;
773 
774 	SESSION_CHECK_ACTIVE_STATE;
775 	SESSION_CHECK_OUTPUT_STATE;
776 	val = ZEND_STRTOL(ZSTR_VAL(new_value), &endptr, 10);
777 	if (endptr && (*endptr == '\0')
778 		&& val >= 4 && val <=6) {
779 		/* Numeric value */
780 		PS(sid_bits_per_character) = val;
781 		return SUCCESS;
782 	}
783 
784 	php_error_docref(NULL, E_WARNING, "session.configuration \"session.sid_bits_per_character\" must be between 4 and 6");
785 	return FAILURE;
786 }
787 /* }}} */
788 
PHP_INI_MH(OnUpdateRfc1867Freq)789 static PHP_INI_MH(OnUpdateRfc1867Freq) /* {{{ */
790 {
791 	int tmp = ZEND_ATOL(ZSTR_VAL(new_value));
792 	if(tmp < 0) {
793 		php_error_docref(NULL, E_WARNING, "session.upload_progress.freq must be greater than or equal to 0");
794 		return FAILURE;
795 	}
796 	if(ZSTR_LEN(new_value) > 0 && ZSTR_VAL(new_value)[ZSTR_LEN(new_value)-1] == '%') {
797 		if(tmp > 100) {
798 			php_error_docref(NULL, E_WARNING, "session.upload_progress.freq must be less than or equal to 100%%");
799 			return FAILURE;
800 		}
801 		PS(rfc1867_freq) = -tmp;
802 	} else {
803 		PS(rfc1867_freq) = tmp;
804 	}
805 	return SUCCESS;
806 } /* }}} */
807 
808 /* {{{ PHP_INI */
809 PHP_INI_BEGIN()
810 	STD_PHP_INI_ENTRY("session.save_path",          "",          PHP_INI_ALL, OnUpdateSaveDir,       save_path,          php_ps_globals,    ps_globals)
811 	STD_PHP_INI_ENTRY("session.name",               "PHPSESSID", PHP_INI_ALL, OnUpdateName,          session_name,       php_ps_globals,    ps_globals)
812 	PHP_INI_ENTRY("session.save_handler",           "files",     PHP_INI_ALL, OnUpdateSaveHandler)
813 	STD_PHP_INI_BOOLEAN("session.auto_start",       "0",         PHP_INI_PERDIR, OnUpdateBool,       auto_start,         php_ps_globals,    ps_globals)
814 	STD_PHP_INI_ENTRY("session.gc_probability",     "1",         PHP_INI_ALL, OnUpdateSessionLong,          gc_probability,     php_ps_globals,    ps_globals)
815 	STD_PHP_INI_ENTRY("session.gc_divisor",         "100",       PHP_INI_ALL, OnUpdateSessionLong,          gc_divisor,         php_ps_globals,    ps_globals)
816 	STD_PHP_INI_ENTRY("session.gc_maxlifetime",     "1440",      PHP_INI_ALL, OnUpdateSessionLong,          gc_maxlifetime,     php_ps_globals,    ps_globals)
817 	PHP_INI_ENTRY("session.serialize_handler",      "php",       PHP_INI_ALL, OnUpdateSerializer)
818 	STD_PHP_INI_ENTRY("session.cookie_lifetime",    "0",         PHP_INI_ALL, OnUpdateCookieLifetime,cookie_lifetime,    php_ps_globals,    ps_globals)
819 	STD_PHP_INI_ENTRY("session.cookie_path",        "/",         PHP_INI_ALL, OnUpdateSessionString, cookie_path,        php_ps_globals,    ps_globals)
820 	STD_PHP_INI_ENTRY("session.cookie_domain",      "",          PHP_INI_ALL, OnUpdateSessionString, cookie_domain,      php_ps_globals,    ps_globals)
821 	STD_PHP_INI_BOOLEAN("session.cookie_secure",    "0",         PHP_INI_ALL, OnUpdateSessionBool,   cookie_secure,      php_ps_globals,    ps_globals)
822 	STD_PHP_INI_BOOLEAN("session.cookie_httponly",  "0",         PHP_INI_ALL, OnUpdateSessionBool,   cookie_httponly,    php_ps_globals,    ps_globals)
823 	STD_PHP_INI_ENTRY("session.cookie_samesite",    "",          PHP_INI_ALL, OnUpdateSessionString, cookie_samesite,    php_ps_globals,    ps_globals)
824 	STD_PHP_INI_BOOLEAN("session.use_cookies",      "1",         PHP_INI_ALL, OnUpdateSessionBool,   use_cookies,        php_ps_globals,    ps_globals)
825 	STD_PHP_INI_BOOLEAN("session.use_only_cookies", "1",         PHP_INI_ALL, OnUpdateSessionBool,   use_only_cookies,   php_ps_globals,    ps_globals)
826 	STD_PHP_INI_BOOLEAN("session.use_strict_mode",  "0",         PHP_INI_ALL, OnUpdateSessionBool,   use_strict_mode,    php_ps_globals,    ps_globals)
827 	STD_PHP_INI_ENTRY("session.referer_check",      "",          PHP_INI_ALL, OnUpdateSessionString, extern_referer_chk, php_ps_globals,    ps_globals)
828 	STD_PHP_INI_ENTRY("session.cache_limiter",      "nocache",   PHP_INI_ALL, OnUpdateSessionString, cache_limiter,      php_ps_globals,    ps_globals)
829 	STD_PHP_INI_ENTRY("session.cache_expire",       "180",       PHP_INI_ALL, OnUpdateSessionLong,   cache_expire,       php_ps_globals,    ps_globals)
830 	STD_PHP_INI_BOOLEAN("session.use_trans_sid",    "0",         PHP_INI_ALL, OnUpdateSessionBool,   use_trans_sid,      php_ps_globals,    ps_globals)
831 	PHP_INI_ENTRY("session.sid_length",             "32",        PHP_INI_ALL, OnUpdateSidLength)
832 	PHP_INI_ENTRY("session.sid_bits_per_character", "4",         PHP_INI_ALL, OnUpdateSidBits)
833 	STD_PHP_INI_BOOLEAN("session.lazy_write",       "1",         PHP_INI_ALL, OnUpdateSessionBool,    lazy_write,         php_ps_globals,    ps_globals)
834 
835 	/* Upload progress */
836 	STD_PHP_INI_BOOLEAN("session.upload_progress.enabled",
837 	                                                "1",     ZEND_INI_PERDIR, OnUpdateBool,        rfc1867_enabled, php_ps_globals, ps_globals)
838 	STD_PHP_INI_BOOLEAN("session.upload_progress.cleanup",
839 	                                                "1",     ZEND_INI_PERDIR, OnUpdateBool,        rfc1867_cleanup, php_ps_globals, ps_globals)
840 	STD_PHP_INI_ENTRY("session.upload_progress.prefix",
841 	                                     "upload_progress_", ZEND_INI_PERDIR, OnUpdateString,      rfc1867_prefix,  php_ps_globals, ps_globals)
842 	STD_PHP_INI_ENTRY("session.upload_progress.name",
843 	                          "PHP_SESSION_UPLOAD_PROGRESS", ZEND_INI_PERDIR, OnUpdateString,      rfc1867_name,    php_ps_globals, ps_globals)
844 	STD_PHP_INI_ENTRY("session.upload_progress.freq",  "1%", ZEND_INI_PERDIR, OnUpdateRfc1867Freq, rfc1867_freq,    php_ps_globals, ps_globals)
845 	STD_PHP_INI_ENTRY("session.upload_progress.min_freq",
846 	                                                   "1",  ZEND_INI_PERDIR, OnUpdateReal,        rfc1867_min_freq,php_ps_globals, ps_globals)
847 
848 	/* Commented out until future discussion */
849 	/* PHP_INI_ENTRY("session.encode_sources", "globals,track", PHP_INI_ALL, NULL) */
PHP_INI_END()850 PHP_INI_END()
851 /* }}} */
852 
853 /* ***************
854    * Serializers *
855    *************** */
856 PS_SERIALIZER_ENCODE_FUNC(php_serialize) /* {{{ */
857 {
858 	smart_str buf = {0};
859 	php_serialize_data_t var_hash;
860 
861 	IF_SESSION_VARS() {
862 		PHP_VAR_SERIALIZE_INIT(var_hash);
863 		php_var_serialize(&buf, Z_REFVAL(PS(http_session_vars)), &var_hash);
864 		PHP_VAR_SERIALIZE_DESTROY(var_hash);
865 	}
866 	return buf.s;
867 }
868 /* }}} */
869 
PS_SERIALIZER_DECODE_FUNC(php_serialize)870 PS_SERIALIZER_DECODE_FUNC(php_serialize) /* {{{ */
871 {
872 	const char *endptr = val + vallen;
873 	zval session_vars;
874 	php_unserialize_data_t var_hash;
875 	bool result;
876 	zend_string *var_name = ZSTR_INIT_LITERAL("_SESSION", 0);
877 
878 	ZVAL_NULL(&session_vars);
879 	PHP_VAR_UNSERIALIZE_INIT(var_hash);
880 	result = php_var_unserialize(
881 		&session_vars, (const unsigned char **)&val, (const unsigned char *)endptr, &var_hash);
882 	PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
883 	if (!result) {
884 		zval_ptr_dtor(&session_vars);
885 		ZVAL_NULL(&session_vars);
886 	}
887 
888 	if (!Z_ISUNDEF(PS(http_session_vars))) {
889 		zval_ptr_dtor(&PS(http_session_vars));
890 	}
891 	if (Z_TYPE(session_vars) == IS_NULL) {
892 		array_init(&session_vars);
893 	}
894 	ZVAL_NEW_REF(&PS(http_session_vars), &session_vars);
895 	Z_ADDREF_P(&PS(http_session_vars));
896 	zend_hash_update_ind(&EG(symbol_table), var_name, &PS(http_session_vars));
897 	zend_string_release_ex(var_name, 0);
898 	return result || !vallen ? SUCCESS : FAILURE;
899 }
900 /* }}} */
901 
902 #define PS_BIN_NR_OF_BITS 8
903 #define PS_BIN_UNDEF (1<<(PS_BIN_NR_OF_BITS-1))
904 #define PS_BIN_MAX (PS_BIN_UNDEF-1)
905 
PS_SERIALIZER_ENCODE_FUNC(php_binary)906 PS_SERIALIZER_ENCODE_FUNC(php_binary) /* {{{ */
907 {
908 	smart_str buf = {0};
909 	php_serialize_data_t var_hash;
910 	PS_ENCODE_VARS;
911 
912 	PHP_VAR_SERIALIZE_INIT(var_hash);
913 
914 	PS_ENCODE_LOOP(
915 			if (ZSTR_LEN(key) > PS_BIN_MAX) continue;
916 			smart_str_appendc(&buf, (unsigned char)ZSTR_LEN(key));
917 			smart_str_appendl(&buf, ZSTR_VAL(key), ZSTR_LEN(key));
918 			php_var_serialize(&buf, struc, &var_hash);
919 	);
920 
921 	smart_str_0(&buf);
922 	PHP_VAR_SERIALIZE_DESTROY(var_hash);
923 
924 	return buf.s;
925 }
926 /* }}} */
927 
PS_SERIALIZER_DECODE_FUNC(php_binary)928 PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */
929 {
930 	const char *p;
931 	const char *endptr = val + vallen;
932 	zend_string *name;
933 	php_unserialize_data_t var_hash;
934 	zval *current, rv;
935 
936 	PHP_VAR_UNSERIALIZE_INIT(var_hash);
937 
938 	for (p = val; p < endptr; ) {
939 		size_t namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF);
940 
941 		if (namelen > PS_BIN_MAX || (p + namelen) >= endptr) {
942 			PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
943 			return FAILURE;
944 		}
945 
946 		name = zend_string_init(p + 1, namelen, 0);
947 		p += namelen + 1;
948 		current = var_tmp_var(&var_hash);
949 
950 		if (php_var_unserialize(current, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash)) {
951 			ZVAL_PTR(&rv, current);
952 			php_set_session_var(name, &rv, &var_hash);
953 		} else {
954 			zend_string_release_ex(name, 0);
955 			php_session_normalize_vars();
956 			PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
957 			return FAILURE;
958 		}
959 		zend_string_release_ex(name, 0);
960 	}
961 
962 	php_session_normalize_vars();
963 	PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
964 
965 	return SUCCESS;
966 }
967 /* }}} */
968 
969 #define PS_DELIMITER '|'
970 
PS_SERIALIZER_ENCODE_FUNC(php)971 PS_SERIALIZER_ENCODE_FUNC(php) /* {{{ */
972 {
973 	smart_str buf = {0};
974 	php_serialize_data_t var_hash;
975 	PS_ENCODE_VARS;
976 
977 	PHP_VAR_SERIALIZE_INIT(var_hash);
978 
979 	PS_ENCODE_LOOP(
980 		smart_str_appendl(&buf, ZSTR_VAL(key), ZSTR_LEN(key));
981 		if (memchr(ZSTR_VAL(key), PS_DELIMITER, ZSTR_LEN(key))) {
982 			PHP_VAR_SERIALIZE_DESTROY(var_hash);
983 			smart_str_free(&buf);
984 			return NULL;
985 		}
986 		smart_str_appendc(&buf, PS_DELIMITER);
987 		php_var_serialize(&buf, struc, &var_hash);
988 	);
989 
990 	smart_str_0(&buf);
991 
992 	PHP_VAR_SERIALIZE_DESTROY(var_hash);
993 	return buf.s;
994 }
995 /* }}} */
996 
PS_SERIALIZER_DECODE_FUNC(php)997 PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */
998 {
999 	const char *p, *q;
1000 	const char *endptr = val + vallen;
1001 	ptrdiff_t namelen;
1002 	zend_string *name;
1003 	zend_result retval = SUCCESS;
1004 	php_unserialize_data_t var_hash;
1005 	zval *current, rv;
1006 
1007 	PHP_VAR_UNSERIALIZE_INIT(var_hash);
1008 
1009 	p = val;
1010 
1011 	while (p < endptr) {
1012 		q = p;
1013 		while (*q != PS_DELIMITER) {
1014 			if (++q >= endptr) {
1015 				retval = FAILURE;
1016 				goto break_outer_loop;
1017 			}
1018 		}
1019 
1020 		namelen = q - p;
1021 		name = zend_string_init(p, namelen, 0);
1022 		q++;
1023 
1024 		current = var_tmp_var(&var_hash);
1025 		if (php_var_unserialize(current, (const unsigned char **)&q, (const unsigned char *)endptr, &var_hash)) {
1026 			ZVAL_PTR(&rv, current);
1027 			php_set_session_var(name, &rv, &var_hash);
1028 		} else {
1029 			zend_string_release_ex(name, 0);
1030 			retval = FAILURE;
1031 			goto break_outer_loop;
1032 		}
1033 		zend_string_release_ex(name, 0);
1034 		p = q;
1035 	}
1036 
1037 break_outer_loop:
1038 	php_session_normalize_vars();
1039 
1040 	PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
1041 
1042 	return retval;
1043 }
1044 /* }}} */
1045 
1046 #define MAX_SERIALIZERS 32
1047 #define PREDEFINED_SERIALIZERS 3
1048 
1049 static ps_serializer ps_serializers[MAX_SERIALIZERS + 1] = {
1050 	PS_SERIALIZER_ENTRY(php_serialize),
1051 	PS_SERIALIZER_ENTRY(php),
1052 	PS_SERIALIZER_ENTRY(php_binary)
1053 };
1054 
php_session_register_serializer(const char * name,zend_string * (* encode)(PS_SERIALIZER_ENCODE_ARGS),zend_result (* decode)(PS_SERIALIZER_DECODE_ARGS))1055 PHPAPI zend_result php_session_register_serializer(const char *name, zend_string *(*encode)(PS_SERIALIZER_ENCODE_ARGS), zend_result (*decode)(PS_SERIALIZER_DECODE_ARGS)) /* {{{ */
1056 {
1057 	zend_result ret = FAILURE;
1058 
1059 	for (int i = 0; i < MAX_SERIALIZERS; i++) {
1060 		if (ps_serializers[i].name == NULL) {
1061 			ps_serializers[i].name = name;
1062 			ps_serializers[i].encode = encode;
1063 			ps_serializers[i].decode = decode;
1064 			ps_serializers[i + 1].name = NULL;
1065 			ret = SUCCESS;
1066 			break;
1067 		}
1068 	}
1069 	return ret;
1070 }
1071 /* }}} */
1072 
1073 /* *******************
1074    * Storage Modules *
1075    ******************* */
1076 
1077 #define MAX_MODULES 32
1078 #define PREDEFINED_MODULES 2
1079 
1080 static const ps_module *ps_modules[MAX_MODULES + 1] = {
1081 	ps_files_ptr,
1082 	ps_user_ptr
1083 };
1084 
php_session_register_module(const ps_module * ptr)1085 PHPAPI zend_result php_session_register_module(const ps_module *ptr) /* {{{ */
1086 {
1087 	int ret = FAILURE;
1088 
1089 	for (int i = 0; i < MAX_MODULES; i++) {
1090 		if (!ps_modules[i]) {
1091 			ps_modules[i] = ptr;
1092 			ret = SUCCESS;
1093 			break;
1094 		}
1095 	}
1096 	return ret;
1097 }
1098 /* }}} */
1099 
1100 /* Dummy PS module function */
1101 /* We consider any ID valid (thus also implying that a session with such an ID exists),
1102 	thus we always return SUCCESS */
php_session_validate_sid(PS_VALIDATE_SID_ARGS)1103 PHPAPI zend_result php_session_validate_sid(PS_VALIDATE_SID_ARGS) {
1104 	return SUCCESS;
1105 }
1106 
1107 /* Dummy PS module function */
php_session_update_timestamp(PS_UPDATE_TIMESTAMP_ARGS)1108 PHPAPI zend_result php_session_update_timestamp(PS_UPDATE_TIMESTAMP_ARGS) {
1109 	return SUCCESS;
1110 }
1111 
1112 
1113 /* ******************
1114    * Cache Limiters *
1115    ****************** */
1116 
1117 typedef struct {
1118 	char *name;
1119 	void (*func)(void);
1120 } php_session_cache_limiter_t;
1121 
1122 #define CACHE_LIMITER(name) _php_cache_limiter_##name
1123 #define CACHE_LIMITER_FUNC(name) static void CACHE_LIMITER(name)(void)
1124 #define CACHE_LIMITER_ENTRY(name) { #name, CACHE_LIMITER(name) },
1125 #define ADD_HEADER(a) sapi_add_header(a, strlen(a), 1);
1126 #define MAX_STR 512
1127 
1128 static const char *month_names[] = {
1129 	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
1130 	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1131 };
1132 
1133 static const char *week_days[] = {
1134 	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1135 };
1136 
strcpy_gmt(char * ubuf,time_t * when)1137 static inline void strcpy_gmt(char *ubuf, time_t *when) /* {{{ */
1138 {
1139 	char buf[MAX_STR];
1140 	struct tm tm, *res;
1141 	int n;
1142 
1143 	res = php_gmtime_r(when, &tm);
1144 
1145 	if (!res) {
1146 		ubuf[0] = '\0';
1147 		return;
1148 	}
1149 
1150 	n = slprintf(buf, sizeof(buf), "%s, %02d %s %d %02d:%02d:%02d GMT", /* SAFE */
1151 				week_days[tm.tm_wday], tm.tm_mday,
1152 				month_names[tm.tm_mon], tm.tm_year + 1900,
1153 				tm.tm_hour, tm.tm_min,
1154 				tm.tm_sec);
1155 	memcpy(ubuf, buf, n);
1156 	ubuf[n] = '\0';
1157 }
1158 /* }}} */
1159 
last_modified(void)1160 static inline void last_modified(void) /* {{{ */
1161 {
1162 	const char *path;
1163 	zend_stat_t sb = {0};
1164 	char buf[MAX_STR + 1];
1165 
1166 	path = SG(request_info).path_translated;
1167 	if (path) {
1168 		if (VCWD_STAT(path, &sb) == -1) {
1169 			return;
1170 		}
1171 
1172 #define LAST_MODIFIED "Last-Modified: "
1173 		memcpy(buf, LAST_MODIFIED, sizeof(LAST_MODIFIED) - 1);
1174 		strcpy_gmt(buf + sizeof(LAST_MODIFIED) - 1, &sb.st_mtime);
1175 		ADD_HEADER(buf);
1176 	}
1177 }
1178 /* }}} */
1179 
1180 #define EXPIRES "Expires: "
CACHE_LIMITER_FUNC(public)1181 CACHE_LIMITER_FUNC(public) /* {{{ */
1182 {
1183 	char buf[MAX_STR + 1];
1184 	struct timeval tv;
1185 	time_t now;
1186 
1187 	gettimeofday(&tv, NULL);
1188 	now = tv.tv_sec + PS(cache_expire) * 60;
1189 	memcpy(buf, EXPIRES, sizeof(EXPIRES) - 1);
1190 	strcpy_gmt(buf + sizeof(EXPIRES) - 1, &now);
1191 	ADD_HEADER(buf);
1192 
1193 	snprintf(buf, sizeof(buf) , "Cache-Control: public, max-age=" ZEND_LONG_FMT, PS(cache_expire) * 60); /* SAFE */
1194 	ADD_HEADER(buf);
1195 
1196 	last_modified();
1197 }
1198 /* }}} */
1199 
CACHE_LIMITER_FUNC(private_no_expire)1200 CACHE_LIMITER_FUNC(private_no_expire) /* {{{ */
1201 {
1202 	char buf[MAX_STR + 1];
1203 
1204 	snprintf(buf, sizeof(buf), "Cache-Control: private, max-age=" ZEND_LONG_FMT, PS(cache_expire) * 60); /* SAFE */
1205 	ADD_HEADER(buf);
1206 
1207 	last_modified();
1208 }
1209 /* }}} */
1210 
CACHE_LIMITER_FUNC(private)1211 CACHE_LIMITER_FUNC(private) /* {{{ */
1212 {
1213 	ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
1214 	CACHE_LIMITER(private_no_expire)();
1215 }
1216 /* }}} */
1217 
CACHE_LIMITER_FUNC(nocache)1218 CACHE_LIMITER_FUNC(nocache) /* {{{ */
1219 {
1220 	ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
1221 
1222 	/* For HTTP/1.1 conforming clients */
1223 	ADD_HEADER("Cache-Control: no-store, no-cache, must-revalidate");
1224 
1225 	/* For HTTP/1.0 conforming clients */
1226 	ADD_HEADER("Pragma: no-cache");
1227 }
1228 /* }}} */
1229 
1230 static const php_session_cache_limiter_t php_session_cache_limiters[] = {
1231 	CACHE_LIMITER_ENTRY(public)
1232 	CACHE_LIMITER_ENTRY(private)
1233 	CACHE_LIMITER_ENTRY(private_no_expire)
1234 	CACHE_LIMITER_ENTRY(nocache)
1235 	{0}
1236 };
1237 
php_session_cache_limiter(void)1238 static int php_session_cache_limiter(void) /* {{{ */
1239 {
1240 	const php_session_cache_limiter_t *lim;
1241 
1242 	if (PS(cache_limiter)[0] == '\0') return 0;
1243 	if (PS(session_status) != php_session_active) return -1;
1244 
1245 	if (SG(headers_sent)) {
1246 		const char *output_start_filename = php_output_get_start_filename();
1247 		int output_start_lineno = php_output_get_start_lineno();
1248 
1249 		php_session_abort();
1250 		if (output_start_filename) {
1251 			php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be sent after headers have already been sent (output started at %s:%d)", output_start_filename, output_start_lineno);
1252 		} else {
1253 			php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be sent after headers have already been sent");
1254 		}
1255 		return -2;
1256 	}
1257 
1258 	for (lim = php_session_cache_limiters; lim->name; lim++) {
1259 		if (!strcasecmp(lim->name, PS(cache_limiter))) {
1260 			lim->func();
1261 			return 0;
1262 		}
1263 	}
1264 
1265 	return -1;
1266 }
1267 /* }}} */
1268 
1269 /* *********************
1270    * Cookie Management *
1271    ********************* */
1272 
1273 /*
1274  * Remove already sent session ID cookie.
1275  * It must be directly removed from SG(sapi_header) because sapi_add_header_ex()
1276  * removes all of matching cookie. i.e. It deletes all of Set-Cookie headers.
1277  */
php_session_remove_cookie(void)1278 static void php_session_remove_cookie(void) {
1279 	sapi_header_struct *header;
1280 	zend_llist *l = &SG(sapi_headers).headers;
1281 	zend_llist_element *next;
1282 	zend_llist_element *current;
1283 	char *session_cookie;
1284 	size_t session_cookie_len;
1285 	size_t len = sizeof("Set-Cookie")-1;
1286 
1287 	ZEND_ASSERT(strpbrk(PS(session_name), SESSION_FORBIDDEN_CHARS) == NULL);
1288 	spprintf(&session_cookie, 0, "Set-Cookie: %s=", PS(session_name));
1289 
1290 	session_cookie_len = strlen(session_cookie);
1291 	current = l->head;
1292 	while (current) {
1293 		header = (sapi_header_struct *)(current->data);
1294 		next = current->next;
1295 		if (header->header_len > len && header->header[len] == ':'
1296 			&& !strncmp(header->header, session_cookie, session_cookie_len)) {
1297 			if (current->prev) {
1298 				current->prev->next = next;
1299 			} else {
1300 				l->head = next;
1301 			}
1302 			if (next) {
1303 				next->prev = current->prev;
1304 			} else {
1305 				l->tail = current->prev;
1306 			}
1307 			sapi_free_header(header);
1308 			efree(current);
1309 			--l->count;
1310 		}
1311 		current = next;
1312 	}
1313 	efree(session_cookie);
1314 }
1315 
php_session_send_cookie(void)1316 static zend_result php_session_send_cookie(void) /* {{{ */
1317 {
1318 	smart_str ncookie = {0};
1319 	zend_string *date_fmt = NULL;
1320 	zend_string *e_id;
1321 
1322 	if (SG(headers_sent)) {
1323 		const char *output_start_filename = php_output_get_start_filename();
1324 		int output_start_lineno = php_output_get_start_lineno();
1325 
1326 		if (output_start_filename) {
1327 			php_error_docref(NULL, E_WARNING, "Session cookie cannot be sent after headers have already been sent (output started at %s:%d)", output_start_filename, output_start_lineno);
1328 		} else {
1329 			php_error_docref(NULL, E_WARNING, "Session cookie cannot be sent after headers have already been sent");
1330 		}
1331 		return FAILURE;
1332 	}
1333 
1334 	/* Prevent broken Set-Cookie header, because the session_name might be user supplied */
1335 	if (strpbrk(PS(session_name), SESSION_FORBIDDEN_CHARS) != NULL) {   /* man isspace for \013 and \014 */
1336 		php_error_docref(NULL, E_WARNING, "session.name cannot contain any of the following '=,;.[ \\t\\r\\n\\013\\014'");
1337 		return FAILURE;
1338 	}
1339 
1340 	/* URL encode id because it might be user supplied */
1341 	e_id = php_url_encode(ZSTR_VAL(PS(id)), ZSTR_LEN(PS(id)));
1342 
1343 	smart_str_appendl(&ncookie, "Set-Cookie: ", sizeof("Set-Cookie: ")-1);
1344 	smart_str_appendl(&ncookie, PS(session_name), strlen(PS(session_name)));
1345 	smart_str_appendc(&ncookie, '=');
1346 	smart_str_appendl(&ncookie, ZSTR_VAL(e_id), ZSTR_LEN(e_id));
1347 
1348 	zend_string_release_ex(e_id, 0);
1349 
1350 	if (PS(cookie_lifetime) > 0) {
1351 		struct timeval tv;
1352 		time_t t;
1353 
1354 		gettimeofday(&tv, NULL);
1355 		t = tv.tv_sec + PS(cookie_lifetime);
1356 
1357 		if (t > 0) {
1358 			date_fmt = 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, t, 0);
1359 			smart_str_appends(&ncookie, COOKIE_EXPIRES);
1360 			smart_str_appendl(&ncookie, ZSTR_VAL(date_fmt), ZSTR_LEN(date_fmt));
1361 			zend_string_release_ex(date_fmt, 0);
1362 
1363 			smart_str_appends(&ncookie, COOKIE_MAX_AGE);
1364 			smart_str_append_long(&ncookie, PS(cookie_lifetime));
1365 		}
1366 	}
1367 
1368 	if (PS(cookie_path)[0]) {
1369 		smart_str_appends(&ncookie, COOKIE_PATH);
1370 		smart_str_appends(&ncookie, PS(cookie_path));
1371 	}
1372 
1373 	if (PS(cookie_domain)[0]) {
1374 		smart_str_appends(&ncookie, COOKIE_DOMAIN);
1375 		smart_str_appends(&ncookie, PS(cookie_domain));
1376 	}
1377 
1378 	if (PS(cookie_secure)) {
1379 		smart_str_appends(&ncookie, COOKIE_SECURE);
1380 	}
1381 
1382 	if (PS(cookie_httponly)) {
1383 		smart_str_appends(&ncookie, COOKIE_HTTPONLY);
1384 	}
1385 
1386 	if (PS(cookie_samesite)[0]) {
1387 		smart_str_appends(&ncookie, COOKIE_SAMESITE);
1388 		smart_str_appends(&ncookie, PS(cookie_samesite));
1389 	}
1390 
1391 	smart_str_0(&ncookie);
1392 
1393 	php_session_remove_cookie(); /* remove already sent session ID cookie */
1394 	/*	'replace' must be 0 here, else a previous Set-Cookie
1395 		header, probably sent with setcookie() will be replaced! */
1396 	sapi_add_header_ex(estrndup(ZSTR_VAL(ncookie.s), ZSTR_LEN(ncookie.s)), ZSTR_LEN(ncookie.s), 0, 0);
1397 	smart_str_free(&ncookie);
1398 
1399 	return SUCCESS;
1400 }
1401 /* }}} */
1402 
_php_find_ps_module(const char * name)1403 PHPAPI const ps_module *_php_find_ps_module(const char *name) /* {{{ */
1404 {
1405 	const ps_module *ret = NULL;
1406 	const ps_module **mod;
1407 	int i;
1408 
1409 	for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
1410 		if (*mod && !strcasecmp(name, (*mod)->s_name)) {
1411 			ret = *mod;
1412 			break;
1413 		}
1414 	}
1415 	return ret;
1416 }
1417 /* }}} */
1418 
_php_find_ps_serializer(const char * name)1419 PHPAPI const ps_serializer *_php_find_ps_serializer(const char *name) /* {{{ */
1420 {
1421 	const ps_serializer *ret = NULL;
1422 	const ps_serializer *mod;
1423 
1424 	for (mod = ps_serializers; mod->name; mod++) {
1425 		if (!strcasecmp(name, mod->name)) {
1426 			ret = mod;
1427 			break;
1428 		}
1429 	}
1430 	return ret;
1431 }
1432 /* }}} */
1433 
ppid2sid(zval * ppid)1434 static void ppid2sid(zval *ppid) {
1435 	ZVAL_DEREF(ppid);
1436 	if (Z_TYPE_P(ppid) == IS_STRING) {
1437 		PS(id) = zend_string_init(Z_STRVAL_P(ppid), Z_STRLEN_P(ppid), 0);
1438 		PS(send_cookie) = 0;
1439 	} else {
1440 		PS(id) = NULL;
1441 		PS(send_cookie) = 1;
1442 	}
1443 }
1444 
1445 
php_session_reset_id(void)1446 PHPAPI zend_result php_session_reset_id(void) /* {{{ */
1447 {
1448 	int module_number = PS(module_number);
1449 	zval *sid, *data, *ppid;
1450 	bool apply_trans_sid;
1451 
1452 	if (!PS(id)) {
1453 		php_error_docref(NULL, E_WARNING, "Cannot set session ID - session ID is not initialized");
1454 		return FAILURE;
1455 	}
1456 
1457 	if (PS(use_cookies) && PS(send_cookie)) {
1458 		php_session_send_cookie();
1459 		PS(send_cookie) = 0;
1460 	}
1461 
1462 	/* If the SID constant exists, destroy it. */
1463 	/* We must not delete any items in EG(zend_constants) */
1464 	/* zend_hash_str_del(EG(zend_constants), "sid", sizeof("sid") - 1); */
1465 	sid = zend_get_constant_str("SID", sizeof("SID") - 1);
1466 
1467 	if (PS(define_sid)) {
1468 		smart_str var = {0};
1469 
1470 		smart_str_appends(&var, PS(session_name));
1471 		smart_str_appendc(&var, '=');
1472 		smart_str_appends(&var, ZSTR_VAL(PS(id)));
1473 		smart_str_0(&var);
1474 		if (sid) {
1475 			zval_ptr_dtor_str(sid);
1476 			ZVAL_STR(sid, smart_str_extract(&var));
1477 		} else {
1478 			REGISTER_STRINGL_CONSTANT("SID", ZSTR_VAL(var.s), ZSTR_LEN(var.s), 0);
1479 			smart_str_free(&var);
1480 		}
1481 	} else {
1482 		if (sid) {
1483 			zval_ptr_dtor_str(sid);
1484 			ZVAL_EMPTY_STRING(sid);
1485 		} else {
1486 			REGISTER_STRINGL_CONSTANT("SID", "", 0, 0);
1487 		}
1488 	}
1489 
1490 	/* Apply trans sid if sid cookie is not set */
1491 	apply_trans_sid = 0;
1492 	if (APPLY_TRANS_SID) {
1493 		apply_trans_sid = 1;
1494 		if (PS(use_cookies) &&
1495 			(data = zend_hash_str_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE") - 1))) {
1496 			ZVAL_DEREF(data);
1497 			if (Z_TYPE_P(data) == IS_ARRAY &&
1498 				(ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), strlen(PS(session_name))))) {
1499 				ZVAL_DEREF(ppid);
1500 				apply_trans_sid = 0;
1501 			}
1502 		}
1503 	}
1504 	if (apply_trans_sid) {
1505 		zend_string *sname;
1506 		sname = zend_string_init(PS(session_name), strlen(PS(session_name)), 0);
1507 		php_url_scanner_reset_session_var(sname, 1); /* This may fail when session name has changed */
1508 		zend_string_release_ex(sname, 0);
1509 		php_url_scanner_add_session_var(PS(session_name), strlen(PS(session_name)), ZSTR_VAL(PS(id)), ZSTR_LEN(PS(id)), 1);
1510 	}
1511 	return SUCCESS;
1512 }
1513 /* }}} */
1514 
1515 
php_session_start(void)1516 PHPAPI zend_result php_session_start(void) /* {{{ */
1517 {
1518 	zval *ppid;
1519 	zval *data;
1520 	char *value;
1521 	size_t lensess;
1522 
1523 	switch (PS(session_status)) {
1524 		case php_session_active:
1525 			if (PS(session_started_filename)) {
1526 				php_error(E_NOTICE, "Ignoring session_start() because a session has already been started (started from %s on line %"PRIu32")", ZSTR_VAL(PS(session_started_filename)), PS(session_started_lineno));
1527 			} else if (PS(auto_start)) {
1528 				/* This option can't be changed at runtime, so we can assume it's because of this */
1529 				php_error(E_NOTICE, "Ignoring session_start() because a session has already been started automatically");
1530 			} else {
1531 				php_error(E_NOTICE, "Ignoring session_start() because a session has already been started");
1532 			}
1533 			return FAILURE;
1534 			break;
1535 
1536 		case php_session_disabled:
1537 			value = zend_ini_string("session.save_handler", sizeof("session.save_handler") - 1, 0);
1538 			if (!PS(mod) && value) {
1539 				PS(mod) = _php_find_ps_module(value);
1540 				if (!PS(mod)) {
1541 					php_error_docref(NULL, E_WARNING, "Cannot find session save handler \"%s\" - session startup failed", value);
1542 					return FAILURE;
1543 				}
1544 			}
1545 			value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler") - 1, 0);
1546 			if (!PS(serializer) && value) {
1547 				PS(serializer) = _php_find_ps_serializer(value);
1548 				if (!PS(serializer)) {
1549 					php_error_docref(NULL, E_WARNING, "Cannot find session serialization handler \"%s\" - session startup failed", value);
1550 					return FAILURE;
1551 				}
1552 			}
1553 			PS(session_status) = php_session_none;
1554 			ZEND_FALLTHROUGH;
1555 
1556 		case php_session_none:
1557 		default:
1558 			/* Setup internal flags */
1559 			PS(define_sid) = !PS(use_only_cookies); /* SID constant is defined when non-cookie ID is used */
1560 			PS(send_cookie) = PS(use_cookies) || PS(use_only_cookies);
1561 	}
1562 
1563 	lensess = strlen(PS(session_name));
1564 
1565 	/*
1566 	 * Cookies are preferred, because initially cookie and get
1567 	 * variables will be available.
1568 	 * URL/POST session ID may be used when use_only_cookies=Off.
1569 	 * session.use_strice_mode=On prevents session adoption.
1570 	 * Session based file upload progress uses non-cookie ID.
1571 	 */
1572 
1573 	if (!PS(id)) {
1574 		if (PS(use_cookies) && (data = zend_hash_str_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE") - 1))) {
1575 			ZVAL_DEREF(data);
1576 			if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
1577 				ppid2sid(ppid);
1578 				PS(send_cookie) = 0;
1579 				PS(define_sid) = 0;
1580 			}
1581 		}
1582 		/* Initialize session ID from non cookie values */
1583 		if (!PS(use_only_cookies)) {
1584 			if (!PS(id) && (data = zend_hash_str_find(&EG(symbol_table), "_GET", sizeof("_GET") - 1))) {
1585 				ZVAL_DEREF(data);
1586 				if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
1587 					ppid2sid(ppid);
1588 				}
1589 			}
1590 			if (!PS(id) && (data = zend_hash_str_find(&EG(symbol_table), "_POST", sizeof("_POST") - 1))) {
1591 				ZVAL_DEREF(data);
1592 				if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
1593 					ppid2sid(ppid);
1594 				}
1595 			}
1596 			/* Check whether the current request was referred to by
1597 			 * an external site which invalidates the previously found id. */
1598 			if (PS(id) && PS(extern_referer_chk)[0] != '\0' &&
1599 				!Z_ISUNDEF(PG(http_globals)[TRACK_VARS_SERVER]) &&
1600 				(data = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_REFERER", sizeof("HTTP_REFERER") - 1)) &&
1601 				Z_TYPE_P(data) == IS_STRING &&
1602 				Z_STRLEN_P(data) != 0 &&
1603 				strstr(Z_STRVAL_P(data), PS(extern_referer_chk)) == NULL
1604 			) {
1605 				zend_string_release_ex(PS(id), 0);
1606 				PS(id) = NULL;
1607 			}
1608 		}
1609 	}
1610 
1611 	/* Finally check session id for dangerous characters
1612 	 * Security note: session id may be embedded in HTML pages.*/
1613 	if (PS(id) && strpbrk(ZSTR_VAL(PS(id)), "\r\n\t <>'\"\\")) {
1614 		zend_string_release_ex(PS(id), 0);
1615 		PS(id) = NULL;
1616 	}
1617 
1618 	if (php_session_initialize() == FAILURE
1619 		|| php_session_cache_limiter() == -2) {
1620 		PS(session_status) = php_session_none;
1621 		if (PS(id)) {
1622 			zend_string_release_ex(PS(id), 0);
1623 			PS(id) = NULL;
1624 		}
1625 		return FAILURE;
1626 	}
1627 
1628 	return SUCCESS;
1629 }
1630 /* }}} */
1631 
php_session_flush(int write)1632 PHPAPI zend_result php_session_flush(int write) /* {{{ */
1633 {
1634 	if (PS(session_status) == php_session_active) {
1635 		php_session_save_current_state(write);
1636 		PS(session_status) = php_session_none;
1637 		return SUCCESS;
1638 	}
1639 	return FAILURE;
1640 }
1641 /* }}} */
1642 
php_get_session_status(void)1643 PHPAPI php_session_status php_get_session_status(void)
1644 {
1645 	return PS(session_status);
1646 }
1647 
php_session_abort(void)1648 static zend_result php_session_abort(void) /* {{{ */
1649 {
1650 	if (PS(session_status) == php_session_active) {
1651 		if (PS(mod_data) || PS(mod_user_implemented)) {
1652 			PS(mod)->s_close(&PS(mod_data));
1653 		}
1654 		PS(session_status) = php_session_none;
1655 		return SUCCESS;
1656 	}
1657 	return FAILURE;
1658 }
1659 /* }}} */
1660 
php_session_reset(void)1661 static zend_result php_session_reset(void) /* {{{ */
1662 {
1663 	if (PS(session_status) == php_session_active
1664 		&& php_session_initialize() == SUCCESS) {
1665 		return SUCCESS;
1666 	}
1667 	return FAILURE;
1668 }
1669 /* }}} */
1670 
1671 
1672 /* This API is not used by any PHP modules including session currently.
1673    session_adapt_url() may be used to set Session ID to target url without
1674    starting "URL-Rewriter" output handler. */
session_adapt_url(const char * url,size_t url_len,char ** new_url,size_t * new_len)1675 PHPAPI void session_adapt_url(const char *url, size_t url_len, char **new_url, size_t *new_len) /* {{{ */
1676 {
1677 	if (APPLY_TRANS_SID && (PS(session_status) == php_session_active)) {
1678 		*new_url = php_url_scanner_adapt_single_url(url, url_len, PS(session_name), ZSTR_VAL(PS(id)), new_len, 1);
1679 	}
1680 }
1681 /* }}} */
1682 
1683 /* ********************************
1684    * Userspace exported functions *
1685    ******************************** */
1686 
1687 /* {{{ session_set_cookie_params(array options)
1688    Set session cookie parameters */
PHP_FUNCTION(session_set_cookie_params)1689 PHP_FUNCTION(session_set_cookie_params)
1690 {
1691 	HashTable *options_ht;
1692 	zend_long lifetime_long;
1693 	zend_string *lifetime = NULL, *path = NULL, *domain = NULL, *samesite = NULL;
1694 	bool secure = 0, secure_null = 1;
1695 	bool httponly = 0, httponly_null = 1;
1696 	zend_string *ini_name;
1697 	zend_result result;
1698 	int found = 0;
1699 
1700 	if (!PS(use_cookies)) {
1701 		return;
1702 	}
1703 
1704 	ZEND_PARSE_PARAMETERS_START(1, 5)
1705 		Z_PARAM_ARRAY_HT_OR_LONG(options_ht, lifetime_long)
1706 		Z_PARAM_OPTIONAL
1707 		Z_PARAM_STR_OR_NULL(path)
1708 		Z_PARAM_STR_OR_NULL(domain)
1709 		Z_PARAM_BOOL_OR_NULL(secure, secure_null)
1710 		Z_PARAM_BOOL_OR_NULL(httponly, httponly_null)
1711 	ZEND_PARSE_PARAMETERS_END();
1712 
1713 	if (PS(session_status) == php_session_active) {
1714 		php_error_docref(NULL, E_WARNING, "Session cookie parameters cannot be changed when a session is active");
1715 		RETURN_FALSE;
1716 	}
1717 
1718 	if (SG(headers_sent)) {
1719 		php_error_docref(NULL, E_WARNING, "Session cookie parameters cannot be changed after headers have already been sent");
1720 		RETURN_FALSE;
1721 	}
1722 
1723 	if (options_ht) {
1724 		zend_string *key;
1725 		zval *value;
1726 
1727 		if (path) {
1728 			zend_argument_value_error(2, "must be null when argument #1 ($lifetime_or_options) is an array");
1729 			RETURN_THROWS();
1730 		}
1731 
1732 		if (domain) {
1733 			zend_argument_value_error(3, "must be null when argument #1 ($lifetime_or_options) is an array");
1734 			RETURN_THROWS();
1735 		}
1736 
1737 		if (!secure_null) {
1738 			zend_argument_value_error(4, "must be null when argument #1 ($lifetime_or_options) is an array");
1739 			RETURN_THROWS();
1740 		}
1741 
1742 		if (!httponly_null) {
1743 			zend_argument_value_error(5, "must be null when argument #1 ($lifetime_or_options) is an array");
1744 			RETURN_THROWS();
1745 		}
1746 		ZEND_HASH_FOREACH_STR_KEY_VAL(options_ht, key, value) {
1747 			if (key) {
1748 				ZVAL_DEREF(value);
1749 				if (zend_string_equals_literal_ci(key, "lifetime")) {
1750 					lifetime = zval_get_string(value);
1751 					found++;
1752 				} else if (zend_string_equals_literal_ci(key, "path")) {
1753 					path = zval_get_string(value);
1754 					found++;
1755 				} else if (zend_string_equals_literal_ci(key, "domain")) {
1756 					domain = zval_get_string(value);
1757 					found++;
1758 				} else if (zend_string_equals_literal_ci(key, "secure")) {
1759 					secure = zval_is_true(value);
1760 					secure_null = 0;
1761 					found++;
1762 				} else if (zend_string_equals_literal_ci(key, "httponly")) {
1763 					httponly = zval_is_true(value);
1764 					httponly_null = 0;
1765 					found++;
1766 				} else if (zend_string_equals_literal_ci(key, "samesite")) {
1767 					samesite = zval_get_string(value);
1768 					found++;
1769 				} else {
1770 					php_error_docref(NULL, E_WARNING, "Argument #1 ($lifetime_or_options) contains an unrecognized key \"%s\"", ZSTR_VAL(key));
1771 				}
1772 			} else {
1773 				php_error_docref(NULL, E_WARNING, "Argument #1 ($lifetime_or_options) cannot contain numeric keys");
1774 			}
1775 		} ZEND_HASH_FOREACH_END();
1776 
1777 		if (found == 0) {
1778 			zend_argument_value_error(1, "must contain at least 1 valid key");
1779 			RETURN_THROWS();
1780 		}
1781 	} else {
1782 		lifetime = zend_long_to_str(lifetime_long);
1783 	}
1784 
1785 	/* Exception during string conversion */
1786 	if (EG(exception)) {
1787 		goto cleanup;
1788 	}
1789 
1790 	if (lifetime) {
1791 		ini_name = ZSTR_INIT_LITERAL("session.cookie_lifetime", 0);
1792 		result = zend_alter_ini_entry(ini_name, lifetime, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
1793 		zend_string_release_ex(ini_name, 0);
1794 		if (result == FAILURE) {
1795 			RETVAL_FALSE;
1796 			goto cleanup;
1797 		}
1798 	}
1799 	if (path) {
1800 		ini_name = ZSTR_INIT_LITERAL("session.cookie_path", 0);
1801 		result = zend_alter_ini_entry(ini_name, path, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
1802 		zend_string_release_ex(ini_name, 0);
1803 		if (result == FAILURE) {
1804 			RETVAL_FALSE;
1805 			goto cleanup;
1806 		}
1807 	}
1808 	if (domain) {
1809 		ini_name = ZSTR_INIT_LITERAL("session.cookie_domain", 0);
1810 		result = zend_alter_ini_entry(ini_name, domain, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
1811 		zend_string_release_ex(ini_name, 0);
1812 		if (result == FAILURE) {
1813 			RETVAL_FALSE;
1814 			goto cleanup;
1815 		}
1816 	}
1817 	if (!secure_null) {
1818 		ini_name = ZSTR_INIT_LITERAL("session.cookie_secure", 0);
1819 		result = zend_alter_ini_entry_chars(ini_name, secure ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
1820 		zend_string_release_ex(ini_name, 0);
1821 		if (result == FAILURE) {
1822 			RETVAL_FALSE;
1823 			goto cleanup;
1824 		}
1825 	}
1826 	if (!httponly_null) {
1827 		ini_name = ZSTR_INIT_LITERAL("session.cookie_httponly", 0);
1828 		result = zend_alter_ini_entry_chars(ini_name, httponly ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
1829 		zend_string_release_ex(ini_name, 0);
1830 		if (result == FAILURE) {
1831 			RETVAL_FALSE;
1832 			goto cleanup;
1833 		}
1834 	}
1835 	if (samesite) {
1836 		ini_name = ZSTR_INIT_LITERAL("session.cookie_samesite", 0);
1837 		result = zend_alter_ini_entry(ini_name, samesite, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
1838 		zend_string_release_ex(ini_name, 0);
1839 		if (result == FAILURE) {
1840 			RETVAL_FALSE;
1841 			goto cleanup;
1842 		}
1843 	}
1844 
1845 	RETVAL_TRUE;
1846 
1847 cleanup:
1848 	if (lifetime) zend_string_release(lifetime);
1849 	if (found > 0) {
1850 		if (path) zend_string_release(path);
1851 		if (domain) zend_string_release(domain);
1852 		if (samesite) zend_string_release(samesite);
1853 	}
1854 }
1855 /* }}} */
1856 
1857 /* {{{ Return the session cookie parameters */
PHP_FUNCTION(session_get_cookie_params)1858 PHP_FUNCTION(session_get_cookie_params)
1859 {
1860 	if (zend_parse_parameters_none() == FAILURE) {
1861 		RETURN_THROWS();
1862 	}
1863 
1864 	array_init(return_value);
1865 
1866 	add_assoc_long(return_value, "lifetime", PS(cookie_lifetime));
1867 	add_assoc_string(return_value, "path", PS(cookie_path));
1868 	add_assoc_string(return_value, "domain", PS(cookie_domain));
1869 	add_assoc_bool(return_value, "secure", PS(cookie_secure));
1870 	add_assoc_bool(return_value, "httponly", PS(cookie_httponly));
1871 	add_assoc_string(return_value, "samesite", PS(cookie_samesite));
1872 }
1873 /* }}} */
1874 
1875 /* {{{ Return the current session name. If newname is given, the session name is replaced with newname */
PHP_FUNCTION(session_name)1876 PHP_FUNCTION(session_name)
1877 {
1878 	zend_string *name = NULL;
1879 	zend_string *ini_name;
1880 
1881 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!", &name) == FAILURE) {
1882 		RETURN_THROWS();
1883 	}
1884 
1885 	if (name && PS(session_status) == php_session_active) {
1886 		php_error_docref(NULL, E_WARNING, "Session name cannot be changed when a session is active");
1887 		RETURN_FALSE;
1888 	}
1889 
1890 	if (name && SG(headers_sent)) {
1891 		php_error_docref(NULL, E_WARNING, "Session name cannot be changed after headers have already been sent");
1892 		RETURN_FALSE;
1893 	}
1894 
1895 	RETVAL_STRING(PS(session_name));
1896 
1897 	if (name) {
1898 		ini_name = ZSTR_INIT_LITERAL("session.name", 0);
1899 		zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
1900 		zend_string_release_ex(ini_name, 0);
1901 	}
1902 }
1903 /* }}} */
1904 
1905 /* {{{ Return the current module name used for accessing session data. If newname is given, the module name is replaced with newname */
PHP_FUNCTION(session_module_name)1906 PHP_FUNCTION(session_module_name)
1907 {
1908 	zend_string *name = NULL;
1909 	zend_string *ini_name;
1910 
1911 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!", &name) == FAILURE) {
1912 		RETURN_THROWS();
1913 	}
1914 
1915 	if (name && PS(session_status) == php_session_active) {
1916 		php_error_docref(NULL, E_WARNING, "Session save handler module cannot be changed when a session is active");
1917 		RETURN_FALSE;
1918 	}
1919 
1920 	if (name && SG(headers_sent)) {
1921 		php_error_docref(NULL, E_WARNING, "Session save handler module cannot be changed after headers have already been sent");
1922 		RETURN_FALSE;
1923 	}
1924 
1925 	/* Set return_value to current module name */
1926 	if (PS(mod) && PS(mod)->s_name) {
1927 		RETVAL_STRING(PS(mod)->s_name);
1928 	} else {
1929 		RETVAL_EMPTY_STRING();
1930 	}
1931 
1932 	if (name) {
1933 		if (zend_string_equals_ci(name, ZSTR_KNOWN(ZEND_STR_USER))) {
1934 			zend_argument_value_error(1, "cannot be \"user\"");
1935 			RETURN_THROWS();
1936 		}
1937 		if (!_php_find_ps_module(ZSTR_VAL(name))) {
1938 			php_error_docref(NULL, E_WARNING, "Session handler module \"%s\" cannot be found", ZSTR_VAL(name));
1939 
1940 			zval_ptr_dtor_str(return_value);
1941 			RETURN_FALSE;
1942 		}
1943 		if (PS(mod_data) || PS(mod_user_implemented)) {
1944 			PS(mod)->s_close(&PS(mod_data));
1945 		}
1946 		PS(mod_data) = NULL;
1947 
1948 		ini_name = ZSTR_INIT_LITERAL("session.save_handler", 0);
1949 		zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
1950 		zend_string_release_ex(ini_name, 0);
1951 	}
1952 }
1953 /* }}} */
1954 
can_session_handler_be_changed(void)1955 static bool can_session_handler_be_changed(void) {
1956 	if (PS(session_status) == php_session_active) {
1957 		php_error_docref(NULL, E_WARNING, "Session save handler cannot be changed when a session is active");
1958 		return false;
1959 	}
1960 
1961 	if (SG(headers_sent)) {
1962 		php_error_docref(NULL, E_WARNING, "Session save handler cannot be changed after headers have already been sent");
1963 		return false;
1964 	}
1965 
1966 	return true;
1967 }
1968 
set_user_save_handler_ini(void)1969 static inline void set_user_save_handler_ini(void) {
1970 	zend_string *ini_name, *ini_val;
1971 
1972 	ini_name = ZSTR_INIT_LITERAL("session.save_handler", 0);
1973 	ini_val = ZSTR_KNOWN(ZEND_STR_USER);
1974 	PS(set_handler) = 1;
1975 	zend_alter_ini_entry(ini_name, ini_val, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
1976 	PS(set_handler) = 0;
1977 	zend_string_release_ex(ini_val, 0);
1978 	zend_string_release_ex(ini_name, 0);
1979 }
1980 
1981 #define SESSION_RELEASE_USER_HANDLER_OO(struct_name) \
1982 	if (!Z_ISUNDEF(PS(mod_user_names).struct_name)) { \
1983 		zval_ptr_dtor(&PS(mod_user_names).struct_name); \
1984 		ZVAL_UNDEF(&PS(mod_user_names).struct_name); \
1985 	}
1986 
1987 #define SESSION_SET_USER_HANDLER_OO(struct_name, zstr_method_name) \
1988 	array_init_size(&PS(mod_user_names).struct_name, 2); \
1989 	Z_ADDREF_P(obj); \
1990 	add_next_index_zval(&PS(mod_user_names).struct_name, obj); \
1991 	add_next_index_str(&PS(mod_user_names).struct_name, zstr_method_name);
1992 
1993 #define SESSION_SET_USER_HANDLER_OO_MANDATORY(struct_name, method_name) \
1994 	if (!Z_ISUNDEF(PS(mod_user_names).struct_name)) { \
1995 		zval_ptr_dtor(&PS(mod_user_names).struct_name); \
1996 	} \
1997 	array_init_size(&PS(mod_user_names).struct_name, 2); \
1998 	Z_ADDREF_P(obj); \
1999 	add_next_index_zval(&PS(mod_user_names).struct_name, obj); \
2000 	add_next_index_str(&PS(mod_user_names).struct_name, zend_string_init(method_name, strlen(method_name), false));
2001 
2002 #define SESSION_SET_USER_HANDLER_PROCEDURAL(struct_name, fci) \
2003 	if (!Z_ISUNDEF(PS(mod_user_names).struct_name)) { \
2004 		zval_ptr_dtor(&PS(mod_user_names).struct_name); \
2005 	} \
2006 	ZVAL_COPY(&PS(mod_user_names).struct_name, &fci.function_name);
2007 
2008 #define SESSION_SET_USER_HANDLER_PROCEDURAL_OPTIONAL(struct_name, fci) \
2009 	if (ZEND_FCI_INITIALIZED(fci)) { \
2010 		SESSION_SET_USER_HANDLER_PROCEDURAL(struct_name, fci); \
2011 	}
2012 
2013 /* {{{ Sets user-level functions */
PHP_FUNCTION(session_set_save_handler)2014 PHP_FUNCTION(session_set_save_handler)
2015 {
2016 	/* OOP Version */
2017 	if (ZEND_NUM_ARGS() <= 2) {
2018 		zval *obj = NULL;
2019 		bool register_shutdown = 1;
2020 
2021 		if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|b", &obj, php_session_iface_entry, &register_shutdown) == FAILURE) {
2022 			RETURN_THROWS();
2023 		}
2024 
2025 		if (!can_session_handler_be_changed()) {
2026 			RETURN_FALSE;
2027 		}
2028 
2029 		if (PS(mod_user_class_name)) {
2030 			zend_string_release(PS(mod_user_class_name));
2031 		}
2032 		PS(mod_user_class_name) = zend_string_copy(Z_OBJCE_P(obj)->name);
2033 
2034 		/* Define mandatory handlers */
2035 		SESSION_SET_USER_HANDLER_OO_MANDATORY(ps_open, "open");
2036 		SESSION_SET_USER_HANDLER_OO_MANDATORY(ps_close, "close");
2037 		SESSION_SET_USER_HANDLER_OO_MANDATORY(ps_read, "read");
2038 		SESSION_SET_USER_HANDLER_OO_MANDATORY(ps_write, "write");
2039 		SESSION_SET_USER_HANDLER_OO_MANDATORY(ps_destroy, "destroy");
2040 		SESSION_SET_USER_HANDLER_OO_MANDATORY(ps_gc, "gc");
2041 
2042 		/* Elements of object_methods HashTable are zend_function *method */
2043 		HashTable *object_methods = &Z_OBJCE_P(obj)->function_table;
2044 
2045 		/* Find implemented methods - SessionIdInterface (optional) */
2046 		/* First release old handlers */
2047 		SESSION_RELEASE_USER_HANDLER_OO(ps_create_sid);
2048 		zend_string *create_sid_name = ZSTR_INIT_LITERAL("create_sid", false);
2049 		if (instanceof_function(Z_OBJCE_P(obj), php_session_id_iface_entry)) {
2050 			SESSION_SET_USER_HANDLER_OO(ps_create_sid, zend_string_copy(create_sid_name));
2051 		} else if (zend_hash_find_ptr(object_methods, create_sid_name)) {
2052 			/* For BC reasons we accept methods even if the class does not implement the interface */
2053 			SESSION_SET_USER_HANDLER_OO(ps_create_sid, zend_string_copy(create_sid_name));
2054 		}
2055 		zend_string_release_ex(create_sid_name, false);
2056 
2057 		/* Find implemented methods - SessionUpdateTimestampInterface (optional) */
2058 		/* First release old handlers */
2059 		SESSION_RELEASE_USER_HANDLER_OO(ps_validate_sid);
2060 		SESSION_RELEASE_USER_HANDLER_OO(ps_update_timestamp);
2061 		/* Method names need to be lowercase */
2062 		zend_string *validate_sid_name = ZSTR_INIT_LITERAL("validateid", false);
2063 		zend_string *update_timestamp_name = ZSTR_INIT_LITERAL("updatetimestamp", false);
2064 		if (instanceof_function(Z_OBJCE_P(obj), php_session_update_timestamp_iface_entry)) {
2065 			/* Validate ID handler */
2066 			SESSION_SET_USER_HANDLER_OO(ps_validate_sid, zend_string_copy(validate_sid_name));
2067 			/* Update Timestamp handler */
2068 			SESSION_SET_USER_HANDLER_OO(ps_update_timestamp, zend_string_copy(update_timestamp_name));
2069 		} else {
2070 			/* For BC reasons we accept methods even if the class does not implement the interface */
2071 			if (zend_hash_find_ptr(object_methods, validate_sid_name)) {
2072 				/* For BC reasons we accept methods even if the class does not implement the interface */
2073 				SESSION_SET_USER_HANDLER_OO(ps_validate_sid, zend_string_copy(validate_sid_name));
2074 			}
2075 			if (zend_hash_find_ptr(object_methods, update_timestamp_name)) {
2076 				/* For BC reasons we accept methods even if the class does not implement the interface */
2077 				SESSION_SET_USER_HANDLER_OO(ps_update_timestamp, zend_string_copy(update_timestamp_name));
2078 			}
2079 		}
2080 		zend_string_release_ex(validate_sid_name, false);
2081 		zend_string_release_ex(update_timestamp_name, false);
2082 
2083 		if (register_shutdown) {
2084 			/* create shutdown function */
2085 			php_shutdown_function_entry shutdown_function_entry;
2086 			zval callable;
2087 			zend_result result;
2088 
2089 			ZVAL_STRING(&callable, "session_register_shutdown");
2090 			result = zend_fcall_info_init(&callable, 0, &shutdown_function_entry.fci,
2091 				&shutdown_function_entry.fci_cache, NULL, NULL);
2092 
2093 			ZEND_ASSERT(result == SUCCESS);
2094 
2095 			/* add shutdown function, removing the old one if it exists */
2096 			if (!register_user_shutdown_function("session_shutdown", strlen("session_shutdown"), &shutdown_function_entry)) {
2097 				zval_ptr_dtor(&callable);
2098 				php_error_docref(NULL, E_WARNING, "Unable to register session shutdown function");
2099 				RETURN_FALSE;
2100 			}
2101 		} else {
2102 			/* remove shutdown function */
2103 			remove_user_shutdown_function("session_shutdown", strlen("session_shutdown"));
2104 		}
2105 
2106 		if (PS(session_status) != php_session_active && (!PS(mod) || PS(mod) != &ps_mod_user)) {
2107 			set_user_save_handler_ini();
2108 		}
2109 
2110 		RETURN_TRUE;
2111 	}
2112 
2113 	zend_error(E_DEPRECATED, "Calling session_set_save_handler() with more than 2 arguments is deprecated");
2114 	if (UNEXPECTED(EG(exception))) {
2115 		RETURN_THROWS();
2116 	}
2117 
2118 	/* Procedural version */
2119 	zend_fcall_info open_fci = {0};
2120 	zend_fcall_info_cache open_fcc;
2121 	zend_fcall_info close_fci = {0};
2122 	zend_fcall_info_cache close_fcc;
2123 	zend_fcall_info read_fci = {0};
2124 	zend_fcall_info_cache read_fcc;
2125 	zend_fcall_info write_fci = {0};
2126 	zend_fcall_info_cache write_fcc;
2127 	zend_fcall_info destroy_fci = {0};
2128 	zend_fcall_info_cache destroy_fcc;
2129 	zend_fcall_info gc_fci = {0};
2130 	zend_fcall_info_cache gc_fcc;
2131 	zend_fcall_info create_id_fci = {0};
2132 	zend_fcall_info_cache create_id_fcc;
2133 	zend_fcall_info validate_id_fci = {0};
2134 	zend_fcall_info_cache validate_id_fcc;
2135 	zend_fcall_info update_timestamp_fci = {0};
2136 	zend_fcall_info_cache update_timestamp_fcc;
2137 
2138 	if (zend_parse_parameters(ZEND_NUM_ARGS(),
2139 		"ffffff|f!f!f!",
2140 		&open_fci, &open_fcc,
2141 		&close_fci, &close_fcc,
2142 		&read_fci, &read_fcc,
2143 		&write_fci, &write_fcc,
2144 		&destroy_fci, &destroy_fcc,
2145 		&gc_fci, &gc_fcc,
2146 		&create_id_fci, &create_id_fcc,
2147 		&validate_id_fci, &validate_id_fcc,
2148 		&update_timestamp_fci, &update_timestamp_fcc) == FAILURE
2149 	) {
2150 		RETURN_THROWS();
2151 	}
2152 	if (!can_session_handler_be_changed()) {
2153 		RETURN_FALSE;
2154 	}
2155 
2156 	/* If a custom session handler is already set, release relevant info */
2157 	if (PS(mod_user_class_name)) {
2158 		zend_string_release(PS(mod_user_class_name));
2159 		PS(mod_user_class_name) = NULL;
2160 	}
2161 
2162 	/* remove shutdown function */
2163 	remove_user_shutdown_function("session_shutdown", strlen("session_shutdown"));
2164 
2165 	if (!PS(mod) || PS(mod) != &ps_mod_user) {
2166 		set_user_save_handler_ini();
2167 	}
2168 
2169 	/* Define mandatory handlers */
2170 	SESSION_SET_USER_HANDLER_PROCEDURAL(ps_open, open_fci);
2171 	SESSION_SET_USER_HANDLER_PROCEDURAL(ps_close, close_fci);
2172 	SESSION_SET_USER_HANDLER_PROCEDURAL(ps_read, read_fci);
2173 	SESSION_SET_USER_HANDLER_PROCEDURAL(ps_write, write_fci);
2174 	SESSION_SET_USER_HANDLER_PROCEDURAL(ps_destroy, destroy_fci);
2175 	SESSION_SET_USER_HANDLER_PROCEDURAL(ps_gc, gc_fci);
2176 
2177 	/* Check for optional handlers */
2178 	SESSION_SET_USER_HANDLER_PROCEDURAL_OPTIONAL(ps_create_sid, create_id_fci);
2179 	SESSION_SET_USER_HANDLER_PROCEDURAL_OPTIONAL(ps_validate_sid, validate_id_fci);
2180 	SESSION_SET_USER_HANDLER_PROCEDURAL_OPTIONAL(ps_update_timestamp, update_timestamp_fci);
2181 
2182 	RETURN_TRUE;
2183 }
2184 /* }}} */
2185 
2186 /* {{{ Return the current save path passed to module_name. If newname is given, the save path is replaced with newname */
PHP_FUNCTION(session_save_path)2187 PHP_FUNCTION(session_save_path)
2188 {
2189 	zend_string *name = NULL;
2190 	zend_string *ini_name;
2191 
2192 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|P!", &name) == FAILURE) {
2193 		RETURN_THROWS();
2194 	}
2195 
2196 	if (name && PS(session_status) == php_session_active) {
2197 		php_error_docref(NULL, E_WARNING, "Session save path cannot be changed when a session is active");
2198 		RETURN_FALSE;
2199 	}
2200 
2201 	if (name && SG(headers_sent)) {
2202 		php_error_docref(NULL, E_WARNING, "Session save path cannot be changed after headers have already been sent");
2203 		RETURN_FALSE;
2204 	}
2205 
2206 	RETVAL_STRING(PS(save_path));
2207 
2208 	if (name) {
2209 		ini_name = ZSTR_INIT_LITERAL("session.save_path", 0);
2210 		zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
2211 		zend_string_release_ex(ini_name, 0);
2212 	}
2213 }
2214 /* }}} */
2215 
2216 /* {{{ Return the current session id. If newid is given, the session id is replaced with newid */
PHP_FUNCTION(session_id)2217 PHP_FUNCTION(session_id)
2218 {
2219 	zend_string *name = NULL;
2220 
2221 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!", &name) == FAILURE) {
2222 		RETURN_THROWS();
2223 	}
2224 
2225 	if (name && PS(session_status) == php_session_active) {
2226 		php_error_docref(NULL, E_WARNING, "Session ID cannot be changed when a session is active");
2227 		RETURN_FALSE;
2228 	}
2229 
2230 	if (name && PS(use_cookies) && SG(headers_sent)) {
2231 		php_error_docref(NULL, E_WARNING, "Session ID cannot be changed after headers have already been sent");
2232 		RETURN_FALSE;
2233 	}
2234 
2235 	if (PS(id)) {
2236 		/* keep compatibility for "\0" characters ???
2237 		 * see: ext/session/tests/session_id_error3.phpt */
2238 		size_t len = strlen(ZSTR_VAL(PS(id)));
2239 		if (UNEXPECTED(len != ZSTR_LEN(PS(id)))) {
2240 			RETVAL_NEW_STR(zend_string_init(ZSTR_VAL(PS(id)), len, 0));
2241 		} else {
2242 			RETVAL_STR_COPY(PS(id));
2243 		}
2244 	} else {
2245 		RETVAL_EMPTY_STRING();
2246 	}
2247 
2248 	if (name) {
2249 		if (PS(id)) {
2250 			zend_string_release_ex(PS(id), 0);
2251 		}
2252 		PS(id) = zend_string_copy(name);
2253 	}
2254 }
2255 /* }}} */
2256 
2257 /* {{{ Update the current session id with a newly generated one. If delete_old_session is set to true, remove the old session. */
PHP_FUNCTION(session_regenerate_id)2258 PHP_FUNCTION(session_regenerate_id)
2259 {
2260 	bool del_ses = 0;
2261 	zend_string *data;
2262 
2263 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &del_ses) == FAILURE) {
2264 		RETURN_THROWS();
2265 	}
2266 
2267 	if (PS(session_status) != php_session_active) {
2268 		php_error_docref(NULL, E_WARNING, "Session ID cannot be regenerated when there is no active session");
2269 		RETURN_FALSE;
2270 	}
2271 
2272 	if (SG(headers_sent)) {
2273 		php_error_docref(NULL, E_WARNING, "Session ID cannot be regenerated after headers have already been sent");
2274 		RETURN_FALSE;
2275 	}
2276 
2277 	/* Process old session data */
2278 	if (del_ses) {
2279 		if (PS(mod)->s_destroy(&PS(mod_data), PS(id)) == FAILURE) {
2280 			PS(mod)->s_close(&PS(mod_data));
2281 			PS(session_status) = php_session_none;
2282 			if (!EG(exception)) {
2283 				php_error_docref(NULL, E_WARNING, "Session object destruction failed. ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2284 			}
2285 			RETURN_FALSE;
2286 		}
2287 	} else {
2288 		zend_result ret;
2289 		data = php_session_encode();
2290 		if (data) {
2291 			ret = PS(mod)->s_write(&PS(mod_data), PS(id), data, PS(gc_maxlifetime));
2292 			zend_string_release_ex(data, 0);
2293 		} else {
2294 			ret = PS(mod)->s_write(&PS(mod_data), PS(id), ZSTR_EMPTY_ALLOC(), PS(gc_maxlifetime));
2295 		}
2296 		if (ret == FAILURE) {
2297 			PS(mod)->s_close(&PS(mod_data));
2298 			PS(session_status) = php_session_none;
2299 			php_error_docref(NULL, E_WARNING, "Session write failed. ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2300 			RETURN_FALSE;
2301 		}
2302 	}
2303 	PS(mod)->s_close(&PS(mod_data));
2304 
2305 	/* New session data */
2306 	if (PS(session_vars)) {
2307 		zend_string_release_ex(PS(session_vars), 0);
2308 		PS(session_vars) = NULL;
2309 	}
2310 	zend_string_release_ex(PS(id), 0);
2311 	PS(id) = NULL;
2312 
2313 	if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name)) == FAILURE) {
2314 		PS(session_status) = php_session_none;
2315 		if (!EG(exception)) {
2316 			zend_throw_error(NULL, "Failed to open session: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2317 		}
2318 		RETURN_THROWS();
2319 	}
2320 
2321 	PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
2322 	if (!PS(id)) {
2323 		PS(session_status) = php_session_none;
2324 		if (!EG(exception)) {
2325 			zend_throw_error(NULL, "Failed to create new session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2326 		}
2327 		RETURN_THROWS();
2328 	}
2329 	if (PS(use_strict_mode)) {
2330 		if ((!PS(mod_user_implemented) && PS(mod)->s_validate_sid) || !Z_ISUNDEF(PS(mod_user_names).ps_validate_sid)) {
2331 			int limit = 3;
2332 			/* Try to generate non-existing ID */
2333 			while (limit-- && PS(mod)->s_validate_sid(&PS(mod_data), PS(id)) == SUCCESS) {
2334 				zend_string_release_ex(PS(id), 0);
2335 				PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
2336 				if (!PS(id)) {
2337 					PS(mod)->s_close(&PS(mod_data));
2338 					PS(session_status) = php_session_none;
2339 					if (!EG(exception)) {
2340 						zend_throw_error(NULL, "Failed to create session ID by collision: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2341 					}
2342 					RETURN_THROWS();
2343 				}
2344 			}
2345 		}
2346 		// TODO warn that ID cannot be verified? else { }
2347 	}
2348 	/* Read is required to make new session data at this point. */
2349 	if (PS(mod)->s_read(&PS(mod_data), PS(id), &data, PS(gc_maxlifetime)) == FAILURE) {
2350 		PS(mod)->s_close(&PS(mod_data));
2351 		PS(session_status) = php_session_none;
2352 		if (!EG(exception)) {
2353 			zend_throw_error(NULL, "Failed to create(read) session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2354 		}
2355 		RETURN_THROWS();
2356 	}
2357 	if (data) {
2358 		zend_string_release_ex(data, 0);
2359 	}
2360 
2361 	if (PS(use_cookies)) {
2362 		PS(send_cookie) = 1;
2363 	}
2364 	if (php_session_reset_id() == FAILURE) {
2365 		RETURN_FALSE;
2366 	}
2367 
2368 	RETURN_TRUE;
2369 }
2370 /* }}} */
2371 
2372 /* {{{ Generate new session ID. Intended for user save handlers. */
PHP_FUNCTION(session_create_id)2373 PHP_FUNCTION(session_create_id)
2374 {
2375 	zend_string *prefix = NULL, *new_id;
2376 	smart_str id = {0};
2377 
2378 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &prefix) == FAILURE) {
2379 		RETURN_THROWS();
2380 	}
2381 
2382 	if (prefix && ZSTR_LEN(prefix)) {
2383 		if (php_session_valid_key(ZSTR_VAL(prefix)) == FAILURE) {
2384 			/* E_ERROR raised for security reason. */
2385 			php_error_docref(NULL, E_WARNING, "Prefix cannot contain special characters. Only the A-Z, a-z, 0-9, \"-\", and \",\" characters are allowed");
2386 			RETURN_FALSE;
2387 		} else {
2388 			smart_str_append(&id, prefix);
2389 		}
2390 	}
2391 
2392 	if (!PS(in_save_handler) && PS(session_status) == php_session_active) {
2393 		int limit = 3;
2394 		while (limit--) {
2395 			new_id = PS(mod)->s_create_sid(&PS(mod_data));
2396 			if (!PS(mod)->s_validate_sid || (PS(mod_user_implemented) && Z_ISUNDEF(PS(mod_user_names).ps_validate_sid))) {
2397 				break;
2398 			} else {
2399 				/* Detect collision and retry */
2400 				if (PS(mod)->s_validate_sid(&PS(mod_data), new_id) == SUCCESS) {
2401 					zend_string_release_ex(new_id, 0);
2402 					new_id = NULL;
2403 					continue;
2404 				}
2405 				break;
2406 			}
2407 		}
2408 	} else {
2409 		new_id = php_session_create_id(NULL);
2410 	}
2411 
2412 	if (new_id) {
2413 		smart_str_append(&id, new_id);
2414 		zend_string_release_ex(new_id, 0);
2415 	} else {
2416 		smart_str_free(&id);
2417 		php_error_docref(NULL, E_WARNING, "Failed to create new ID");
2418 		RETURN_FALSE;
2419 	}
2420 	RETVAL_STR(smart_str_extract(&id));
2421 }
2422 /* }}} */
2423 
2424 /* {{{ Return the current cache limiter. If new_cache_limited is given, the current cache_limiter is replaced with new_cache_limiter */
PHP_FUNCTION(session_cache_limiter)2425 PHP_FUNCTION(session_cache_limiter)
2426 {
2427 	zend_string *limiter = NULL;
2428 	zend_string *ini_name;
2429 
2430 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!", &limiter) == FAILURE) {
2431 		RETURN_THROWS();
2432 	}
2433 
2434 	if (limiter && PS(session_status) == php_session_active) {
2435 		php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be changed when a session is active");
2436 		RETURN_FALSE;
2437 	}
2438 
2439 	if (limiter && SG(headers_sent)) {
2440 		php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be changed after headers have already been sent");
2441 		RETURN_FALSE;
2442 	}
2443 
2444 	RETVAL_STRING(PS(cache_limiter));
2445 
2446 	if (limiter) {
2447 		ini_name = ZSTR_INIT_LITERAL("session.cache_limiter", 0);
2448 		zend_alter_ini_entry(ini_name, limiter, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
2449 		zend_string_release_ex(ini_name, 0);
2450 	}
2451 }
2452 /* }}} */
2453 
2454 /* {{{ Return the current cache expire. If new_cache_expire is given, the current cache_expire is replaced with new_cache_expire */
PHP_FUNCTION(session_cache_expire)2455 PHP_FUNCTION(session_cache_expire)
2456 {
2457 	zend_long expires;
2458 	bool expires_is_null = 1;
2459 
2460 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &expires, &expires_is_null) == FAILURE) {
2461 		RETURN_THROWS();
2462 	}
2463 
2464 	if (!expires_is_null && PS(session_status) == php_session_active) {
2465 		php_error_docref(NULL, E_WARNING, "Session cache expiration cannot be changed when a session is active");
2466 		RETURN_LONG(PS(cache_expire));
2467 	}
2468 
2469 	if (!expires_is_null && SG(headers_sent)) {
2470 		php_error_docref(NULL, E_WARNING, "Session cache expiration cannot be changed after headers have already been sent");
2471 		RETURN_FALSE;
2472 	}
2473 
2474 	RETVAL_LONG(PS(cache_expire));
2475 
2476 	if (!expires_is_null) {
2477 		zend_string *ini_name = ZSTR_INIT_LITERAL("session.cache_expire", 0);
2478 		zend_string *ini_value = zend_long_to_str(expires);
2479 		zend_alter_ini_entry(ini_name, ini_value, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);
2480 		zend_string_release_ex(ini_name, 0);
2481 		zend_string_release_ex(ini_value, 0);
2482 	}
2483 }
2484 /* }}} */
2485 
2486 /* {{{ Serializes the current setup and returns the serialized representation */
PHP_FUNCTION(session_encode)2487 PHP_FUNCTION(session_encode)
2488 {
2489 	zend_string *enc;
2490 
2491 	if (zend_parse_parameters_none() == FAILURE) {
2492 		RETURN_THROWS();
2493 	}
2494 
2495 	enc = php_session_encode();
2496 	if (enc == NULL) {
2497 		RETURN_FALSE;
2498 	}
2499 
2500 	RETURN_STR(enc);
2501 }
2502 /* }}} */
2503 
2504 /* {{{ Deserializes data and reinitializes the variables */
PHP_FUNCTION(session_decode)2505 PHP_FUNCTION(session_decode)
2506 {
2507 	zend_string *str = NULL;
2508 
2509 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &str) == FAILURE) {
2510 		RETURN_THROWS();
2511 	}
2512 
2513 	if (PS(session_status) != php_session_active) {
2514 		php_error_docref(NULL, E_WARNING, "Session data cannot be decoded when there is no active session");
2515 		RETURN_FALSE;
2516 	}
2517 
2518 	if (php_session_decode(str) == FAILURE) {
2519 		RETURN_FALSE;
2520 	}
2521 	RETURN_TRUE;
2522 }
2523 /* }}} */
2524 
php_session_start_set_ini(zend_string * varname,zend_string * new_value)2525 static zend_result php_session_start_set_ini(zend_string *varname, zend_string *new_value) {
2526 	zend_result ret;
2527 	smart_str buf ={0};
2528 	smart_str_appends(&buf, "session");
2529 	smart_str_appendc(&buf, '.');
2530 	smart_str_append(&buf, varname);
2531 	smart_str_0(&buf);
2532 	ret = zend_alter_ini_entry_ex(buf.s, new_value, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0);
2533 	smart_str_free(&buf);
2534 	return ret;
2535 }
2536 
2537 /* {{{ Begin session */
PHP_FUNCTION(session_start)2538 PHP_FUNCTION(session_start)
2539 {
2540 	zval *options = NULL;
2541 	zval *value;
2542 	zend_ulong num_idx;
2543 	zend_string *str_idx;
2544 	zend_long read_and_close = 0;
2545 
2546 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a", &options) == FAILURE) {
2547 		RETURN_THROWS();
2548 	}
2549 
2550 	if (PS(session_status) == php_session_active) {
2551 		if (PS(session_started_filename)) {
2552 			php_error_docref(NULL, E_NOTICE, "Ignoring session_start() because a session is already active (started from %s on line %"PRIu32")", ZSTR_VAL(PS(session_started_filename)), PS(session_started_lineno));
2553 		} else if (PS(auto_start)) {
2554 			/* This option can't be changed at runtime, so we can assume it's because of this */
2555 			php_error_docref(NULL, E_NOTICE, "Ignoring session_start() because a session is already automatically active");
2556 		} else {
2557 			php_error_docref(NULL, E_NOTICE, "Ignoring session_start() because a session is already active");
2558 		}
2559 		RETURN_TRUE;
2560 	}
2561 
2562 	/*
2563 	 * TODO: To prevent unusable session with trans sid, actual output started status is
2564 	 * required. i.e. There shouldn't be any outputs in output buffer, otherwise session
2565 	 * module is unable to rewrite output.
2566 	 */
2567 	if (PS(use_cookies) && SG(headers_sent)) {
2568 		php_error_docref(NULL, E_WARNING, "Session cannot be started after headers have already been sent");
2569 		RETURN_FALSE;
2570 	}
2571 
2572 	/* set options */
2573 	if (options) {
2574 		ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(options), num_idx, str_idx, value) {
2575 			if (str_idx) {
2576 				switch(Z_TYPE_P(value)) {
2577 					case IS_STRING:
2578 					case IS_TRUE:
2579 					case IS_FALSE:
2580 					case IS_LONG:
2581 						if (zend_string_equals_literal(str_idx, "read_and_close")) {
2582 							read_and_close = zval_get_long(value);
2583 						} else {
2584 							zend_string *tmp_val;
2585 							zend_string *val = zval_get_tmp_string(value, &tmp_val);
2586 							if (php_session_start_set_ini(str_idx, val) == FAILURE) {
2587 								php_error_docref(NULL, E_WARNING, "Setting option \"%s\" failed", ZSTR_VAL(str_idx));
2588 							}
2589 							zend_tmp_string_release(tmp_val);
2590 						}
2591 						break;
2592 					default:
2593 						zend_type_error("%s(): Option \"%s\" must be of type string|int|bool, %s given",
2594 							get_active_function_name(), ZSTR_VAL(str_idx), zend_zval_value_name(value)
2595 						);
2596 						RETURN_THROWS();
2597 				}
2598 			}
2599 			(void) num_idx;
2600 		} ZEND_HASH_FOREACH_END();
2601 	}
2602 
2603 	php_session_start();
2604 
2605 	if (PS(session_status) != php_session_active) {
2606 		IF_SESSION_VARS() {
2607 			zval *sess_var = Z_REFVAL(PS(http_session_vars));
2608 			SEPARATE_ARRAY(sess_var);
2609 			/* Clean $_SESSION. */
2610 			zend_hash_clean(Z_ARRVAL_P(sess_var));
2611 		}
2612 		RETURN_FALSE;
2613 	}
2614 
2615 	if (read_and_close) {
2616 		php_session_flush(0);
2617 	}
2618 
2619 	RETURN_TRUE;
2620 }
2621 /* }}} */
2622 
2623 /* {{{ Destroy the current session and all data associated with it */
PHP_FUNCTION(session_destroy)2624 PHP_FUNCTION(session_destroy)
2625 {
2626 	if (zend_parse_parameters_none() == FAILURE) {
2627 		RETURN_THROWS();
2628 	}
2629 
2630 	RETURN_BOOL(php_session_destroy() == SUCCESS);
2631 }
2632 /* }}} */
2633 
2634 /* {{{ Unset all registered variables */
PHP_FUNCTION(session_unset)2635 PHP_FUNCTION(session_unset)
2636 {
2637 	if (zend_parse_parameters_none() == FAILURE) {
2638 		RETURN_THROWS();
2639 	}
2640 
2641 	if (PS(session_status) != php_session_active) {
2642 		RETURN_FALSE;
2643 	}
2644 
2645 	IF_SESSION_VARS() {
2646 		zval *sess_var = Z_REFVAL(PS(http_session_vars));
2647 		SEPARATE_ARRAY(sess_var);
2648 
2649 		/* Clean $_SESSION. */
2650 		zend_hash_clean(Z_ARRVAL_P(sess_var));
2651 	}
2652 	RETURN_TRUE;
2653 }
2654 /* }}} */
2655 
2656 /* {{{ Perform GC and return number of deleted sessions */
PHP_FUNCTION(session_gc)2657 PHP_FUNCTION(session_gc)
2658 {
2659 	zend_long num;
2660 
2661 	if (zend_parse_parameters_none() == FAILURE) {
2662 		RETURN_THROWS();
2663 	}
2664 
2665 	if (PS(session_status) != php_session_active) {
2666 		php_error_docref(NULL, E_WARNING, "Session cannot be garbage collected when there is no active session");
2667 		RETURN_FALSE;
2668 	}
2669 
2670 	num = php_session_gc(1);
2671 	if (num < 0) {
2672 		RETURN_FALSE;
2673 	}
2674 
2675 	RETURN_LONG(num);
2676 }
2677 /* }}} */
2678 
2679 
2680 /* {{{ Write session data and end session */
PHP_FUNCTION(session_write_close)2681 PHP_FUNCTION(session_write_close)
2682 {
2683 	if (zend_parse_parameters_none() == FAILURE) {
2684 		RETURN_THROWS();
2685 	}
2686 
2687 	if (PS(session_status) != php_session_active) {
2688 		RETURN_FALSE;
2689 	}
2690 	php_session_flush(1);
2691 	RETURN_TRUE;
2692 }
2693 /* }}} */
2694 
2695 /* {{{ Abort session and end session. Session data will not be written */
PHP_FUNCTION(session_abort)2696 PHP_FUNCTION(session_abort)
2697 {
2698 	if (zend_parse_parameters_none() == FAILURE) {
2699 		RETURN_THROWS();
2700 	}
2701 
2702 	if (PS(session_status) != php_session_active) {
2703 		RETURN_FALSE;
2704 	}
2705 	php_session_abort();
2706 	RETURN_TRUE;
2707 }
2708 /* }}} */
2709 
2710 /* {{{ Reset session data from saved session data */
PHP_FUNCTION(session_reset)2711 PHP_FUNCTION(session_reset)
2712 {
2713 	if (zend_parse_parameters_none() == FAILURE) {
2714 		RETURN_THROWS();
2715 	}
2716 
2717 	if (PS(session_status) != php_session_active) {
2718 		RETURN_FALSE;
2719 	}
2720 	php_session_reset();
2721 	RETURN_TRUE;
2722 }
2723 /* }}} */
2724 
2725 /* {{{ Returns the current session status */
PHP_FUNCTION(session_status)2726 PHP_FUNCTION(session_status)
2727 {
2728 	if (zend_parse_parameters_none() == FAILURE) {
2729 		RETURN_THROWS();
2730 	}
2731 
2732 	RETURN_LONG(PS(session_status));
2733 }
2734 /* }}} */
2735 
2736 /* {{{ Registers session_write_close() as a shutdown function */
PHP_FUNCTION(session_register_shutdown)2737 PHP_FUNCTION(session_register_shutdown)
2738 {
2739 	php_shutdown_function_entry shutdown_function_entry;
2740 	zval callable;
2741 	zend_result result;
2742 
2743 	ZEND_PARSE_PARAMETERS_NONE();
2744 
2745 	/* This function is registered itself as a shutdown function by
2746 	 * session_set_save_handler($obj). The reason we now register another
2747 	 * shutdown function is in case the user registered their own shutdown
2748 	 * function after calling session_set_save_handler(), which expects
2749 	 * the session still to be available.
2750 	 */
2751 	ZVAL_STRING(&callable, "session_write_close");
2752 	result = zend_fcall_info_init(&callable, 0, &shutdown_function_entry.fci,
2753 		&shutdown_function_entry.fci_cache, NULL, NULL);
2754 
2755 	ZEND_ASSERT(result == SUCCESS);
2756 
2757 	if (!append_user_shutdown_function(&shutdown_function_entry)) {
2758 		zval_ptr_dtor(&callable);
2759 
2760 		/* Unable to register shutdown function, presumably because of lack
2761 		 * of memory, so flush the session now. It would be done in rshutdown
2762 		 * anyway but the handler will have had it's dtor called by then.
2763 		 * If the user does have a later shutdown function which needs the
2764 		 * session then tough luck.
2765 		 */
2766 		php_session_flush(1);
2767 		php_error_docref(NULL, E_WARNING, "Session shutdown function cannot be registered");
2768 	}
2769 }
2770 /* }}} */
2771 
2772 /* ********************************
2773    * Module Setup and Destruction *
2774    ******************************** */
2775 
php_rinit_session(bool auto_start)2776 static zend_result php_rinit_session(bool auto_start) /* {{{ */
2777 {
2778 	php_rinit_session_globals();
2779 
2780 	PS(mod) = NULL;
2781 	{
2782 		char *value;
2783 
2784 		value = zend_ini_string("session.save_handler", sizeof("session.save_handler") - 1, 0);
2785 		if (value) {
2786 			PS(mod) = _php_find_ps_module(value);
2787 		}
2788 	}
2789 
2790 	if (PS(serializer) == NULL) {
2791 		char *value;
2792 
2793 		value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler") - 1, 0);
2794 		if (value) {
2795 			PS(serializer) = _php_find_ps_serializer(value);
2796 		}
2797 	}
2798 
2799 	if (PS(mod) == NULL || PS(serializer) == NULL) {
2800 		/* current status is unusable */
2801 		PS(session_status) = php_session_disabled;
2802 		return SUCCESS;
2803 	}
2804 
2805 	if (auto_start) {
2806 		php_session_start();
2807 	}
2808 
2809 	return SUCCESS;
2810 } /* }}} */
2811 
PHP_RINIT_FUNCTION(session)2812 static PHP_RINIT_FUNCTION(session) /* {{{ */
2813 {
2814 	return php_rinit_session(PS(auto_start));
2815 }
2816 /* }}} */
2817 
2818 #define SESSION_FREE_USER_HANDLER(struct_name) \
2819 	if (!Z_ISUNDEF(PS(mod_user_names).struct_name)) { \
2820 		zval_ptr_dtor(&PS(mod_user_names).struct_name); \
2821 		ZVAL_UNDEF(&PS(mod_user_names).struct_name); \
2822 	}
2823 
2824 
PHP_RSHUTDOWN_FUNCTION(session)2825 static PHP_RSHUTDOWN_FUNCTION(session) /* {{{ */
2826 {
2827 	if (PS(session_status) == php_session_active) {
2828 		zend_try {
2829 			php_session_flush(1);
2830 		} zend_end_try();
2831 	}
2832 	php_rshutdown_session_globals();
2833 
2834 	/* this should NOT be done in php_rshutdown_session_globals() */
2835 	/* Free user defined handlers */
2836 	SESSION_FREE_USER_HANDLER(ps_open);
2837 	SESSION_FREE_USER_HANDLER(ps_close);
2838 	SESSION_FREE_USER_HANDLER(ps_read);
2839 	SESSION_FREE_USER_HANDLER(ps_write);
2840 	SESSION_FREE_USER_HANDLER(ps_destroy);
2841 	SESSION_FREE_USER_HANDLER(ps_gc);
2842 	SESSION_FREE_USER_HANDLER(ps_create_sid);
2843 	SESSION_FREE_USER_HANDLER(ps_validate_sid);
2844 	SESSION_FREE_USER_HANDLER(ps_update_timestamp);
2845 
2846 	return SUCCESS;
2847 }
2848 /* }}} */
2849 
PHP_GINIT_FUNCTION(ps)2850 static PHP_GINIT_FUNCTION(ps) /* {{{ */
2851 {
2852 #if defined(COMPILE_DL_SESSION) && defined(ZTS)
2853 	ZEND_TSRMLS_CACHE_UPDATE();
2854 #endif
2855 
2856 	ps_globals->save_path = NULL;
2857 	ps_globals->session_name = NULL;
2858 	ps_globals->id = NULL;
2859 	ps_globals->mod = NULL;
2860 	ps_globals->serializer = NULL;
2861 	ps_globals->mod_data = NULL;
2862 	ps_globals->session_status = php_session_none;
2863 	ps_globals->default_mod = NULL;
2864 	ps_globals->mod_user_implemented = 0;
2865 	ps_globals->mod_user_class_name = NULL;
2866 	ps_globals->mod_user_is_open = 0;
2867 	ps_globals->session_vars = NULL;
2868 	ps_globals->set_handler = 0;
2869 	ps_globals->session_started_filename = NULL;
2870 	ps_globals->session_started_lineno = 0;
2871 	/* Unset user defined handlers */
2872 	ZVAL_UNDEF(&ps_globals->mod_user_names.ps_open);
2873 	ZVAL_UNDEF(&ps_globals->mod_user_names.ps_close);
2874 	ZVAL_UNDEF(&ps_globals->mod_user_names.ps_read);
2875 	ZVAL_UNDEF(&ps_globals->mod_user_names.ps_write);
2876 	ZVAL_UNDEF(&ps_globals->mod_user_names.ps_destroy);
2877 	ZVAL_UNDEF(&ps_globals->mod_user_names.ps_gc);
2878 	ZVAL_UNDEF(&ps_globals->mod_user_names.ps_create_sid);
2879 	ZVAL_UNDEF(&ps_globals->mod_user_names.ps_validate_sid);
2880 	ZVAL_UNDEF(&ps_globals->mod_user_names.ps_update_timestamp);
2881 	ZVAL_UNDEF(&ps_globals->http_session_vars);
2882 
2883 	ps_globals->random = (php_random_algo_with_state){
2884 		.algo = &php_random_algo_pcgoneseq128xslrr64,
2885 		.state = &ps_globals->random_state,
2886 	};
2887 	php_random_uint128_t seed;
2888 	if (php_random_bytes_silent(&seed, sizeof(seed)) == FAILURE) {
2889 		seed = php_random_uint128_constant(
2890 			php_random_generate_fallback_seed(),
2891 			php_random_generate_fallback_seed()
2892 		);
2893 	}
2894 	php_random_pcgoneseq128xslrr64_seed128(ps_globals->random.state, seed);
2895 }
2896 /* }}} */
2897 
PHP_MINIT_FUNCTION(session)2898 static PHP_MINIT_FUNCTION(session) /* {{{ */
2899 {
2900 	zend_register_auto_global(zend_string_init_interned("_SESSION", sizeof("_SESSION") - 1, 1), 0, NULL);
2901 
2902 	my_module_number = module_number;
2903 	PS(module_number) = module_number;
2904 
2905 	PS(session_status) = php_session_none;
2906 	REGISTER_INI_ENTRIES();
2907 
2908 #ifdef HAVE_LIBMM
2909 	PHP_MINIT(ps_mm) (INIT_FUNC_ARGS_PASSTHRU);
2910 #endif
2911 	php_session_rfc1867_orig_callback = php_rfc1867_callback;
2912 	php_rfc1867_callback = php_session_rfc1867_callback;
2913 
2914 	/* Register interfaces */
2915 	php_session_iface_entry = register_class_SessionHandlerInterface();
2916 
2917 	php_session_id_iface_entry = register_class_SessionIdInterface();
2918 
2919 	php_session_update_timestamp_iface_entry = register_class_SessionUpdateTimestampHandlerInterface();
2920 
2921 	/* Register base class */
2922 	php_session_class_entry = register_class_SessionHandler(php_session_iface_entry, php_session_id_iface_entry);
2923 
2924 	register_session_symbols(module_number);
2925 
2926 	return SUCCESS;
2927 }
2928 /* }}} */
2929 
PHP_MSHUTDOWN_FUNCTION(session)2930 static PHP_MSHUTDOWN_FUNCTION(session) /* {{{ */
2931 {
2932 	UNREGISTER_INI_ENTRIES();
2933 
2934 #ifdef HAVE_LIBMM
2935 	PHP_MSHUTDOWN(ps_mm) (SHUTDOWN_FUNC_ARGS_PASSTHRU);
2936 #endif
2937 
2938 	/* reset rfc1867 callbacks */
2939 	php_session_rfc1867_orig_callback = NULL;
2940 	if (php_rfc1867_callback == php_session_rfc1867_callback) {
2941 		php_rfc1867_callback = NULL;
2942 	}
2943 
2944 	ps_serializers[PREDEFINED_SERIALIZERS].name = NULL;
2945 	memset(ZEND_VOIDP(&ps_modules[PREDEFINED_MODULES]), 0, (MAX_MODULES-PREDEFINED_MODULES)*sizeof(ps_module *));
2946 
2947 	return SUCCESS;
2948 }
2949 /* }}} */
2950 
PHP_MINFO_FUNCTION(session)2951 static PHP_MINFO_FUNCTION(session) /* {{{ */
2952 {
2953 	const ps_module **mod;
2954 	ps_serializer *ser;
2955 	smart_str save_handlers = {0};
2956 	smart_str ser_handlers = {0};
2957 	int i;
2958 
2959 	/* Get save handlers */
2960 	for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
2961 		if (*mod && (*mod)->s_name) {
2962 			smart_str_appends(&save_handlers, (*mod)->s_name);
2963 			smart_str_appendc(&save_handlers, ' ');
2964 		}
2965 	}
2966 
2967 	/* Get serializer handlers */
2968 	for (i = 0, ser = ps_serializers; i < MAX_SERIALIZERS; i++, ser++) {
2969 		if (ser->name) {
2970 			smart_str_appends(&ser_handlers, ser->name);
2971 			smart_str_appendc(&ser_handlers, ' ');
2972 		}
2973 	}
2974 
2975 	php_info_print_table_start();
2976 	php_info_print_table_row(2, "Session Support", "enabled" );
2977 
2978 	if (save_handlers.s) {
2979 		smart_str_0(&save_handlers);
2980 		php_info_print_table_row(2, "Registered save handlers", ZSTR_VAL(save_handlers.s));
2981 		smart_str_free(&save_handlers);
2982 	} else {
2983 		php_info_print_table_row(2, "Registered save handlers", "none");
2984 	}
2985 
2986 	if (ser_handlers.s) {
2987 		smart_str_0(&ser_handlers);
2988 		php_info_print_table_row(2, "Registered serializer handlers", ZSTR_VAL(ser_handlers.s));
2989 		smart_str_free(&ser_handlers);
2990 	} else {
2991 		php_info_print_table_row(2, "Registered serializer handlers", "none");
2992 	}
2993 
2994 	php_info_print_table_end();
2995 
2996 	DISPLAY_INI_ENTRIES();
2997 }
2998 /* }}} */
2999 
3000 static const zend_module_dep session_deps[] = { /* {{{ */
3001 	ZEND_MOD_OPTIONAL("hash")
3002 	ZEND_MOD_REQUIRED("spl")
3003 	ZEND_MOD_END
3004 };
3005 /* }}} */
3006 
3007 /* ************************
3008    * Upload hook handling *
3009    ************************ */
3010 
early_find_sid_in(zval * dest,int where,php_session_rfc1867_progress * progress)3011 static bool early_find_sid_in(zval *dest, int where, php_session_rfc1867_progress *progress) /* {{{ */
3012 {
3013 	zval *ppid;
3014 
3015 	if (Z_ISUNDEF(PG(http_globals)[where])) {
3016 		return 0;
3017 	}
3018 
3019 	if ((ppid = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[where]), PS(session_name), progress->sname_len))
3020 			&& Z_TYPE_P(ppid) == IS_STRING) {
3021 		zval_ptr_dtor(dest);
3022 		ZVAL_COPY_DEREF(dest, ppid);
3023 		return 1;
3024 	}
3025 
3026 	return 0;
3027 } /* }}} */
3028 
php_session_rfc1867_early_find_sid(php_session_rfc1867_progress * progress)3029 static void php_session_rfc1867_early_find_sid(php_session_rfc1867_progress *progress) /* {{{ */
3030 {
3031 
3032 	if (PS(use_cookies)) {
3033 		sapi_module.treat_data(PARSE_COOKIE, NULL, NULL);
3034 		if (early_find_sid_in(&progress->sid, TRACK_VARS_COOKIE, progress)) {
3035 			progress->apply_trans_sid = 0;
3036 			return;
3037 		}
3038 	}
3039 	if (PS(use_only_cookies)) {
3040 		return;
3041 	}
3042 	sapi_module.treat_data(PARSE_GET, NULL, NULL);
3043 	early_find_sid_in(&progress->sid, TRACK_VARS_GET, progress);
3044 } /* }}} */
3045 
php_check_cancel_upload(php_session_rfc1867_progress * progress)3046 static bool php_check_cancel_upload(php_session_rfc1867_progress *progress) /* {{{ */
3047 {
3048 	zval *progress_ary, *cancel_upload;
3049 
3050 	if ((progress_ary = zend_symtable_find(Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars))), progress->key.s)) == NULL) {
3051 		return 0;
3052 	}
3053 	if (Z_TYPE_P(progress_ary) != IS_ARRAY) {
3054 		return 0;
3055 	}
3056 	if ((cancel_upload = zend_hash_str_find(Z_ARRVAL_P(progress_ary), "cancel_upload", sizeof("cancel_upload") - 1)) == NULL) {
3057 		return 0;
3058 	}
3059 	return Z_TYPE_P(cancel_upload) == IS_TRUE;
3060 } /* }}} */
3061 
php_session_rfc1867_update(php_session_rfc1867_progress * progress,int force_update)3062 static void php_session_rfc1867_update(php_session_rfc1867_progress *progress, int force_update) /* {{{ */
3063 {
3064 	if (!force_update) {
3065 		if (Z_LVAL_P(progress->post_bytes_processed) < progress->next_update) {
3066 			return;
3067 		}
3068 #ifdef HAVE_GETTIMEOFDAY
3069 		if (PS(rfc1867_min_freq) > 0.0) {
3070 			struct timeval tv = {0};
3071 			double dtv;
3072 			gettimeofday(&tv, NULL);
3073 			dtv = (double) tv.tv_sec + tv.tv_usec / 1000000.0;
3074 			if (dtv < progress->next_update_time) {
3075 				return;
3076 			}
3077 			progress->next_update_time = dtv + PS(rfc1867_min_freq);
3078 		}
3079 #endif
3080 		progress->next_update = Z_LVAL_P(progress->post_bytes_processed) + progress->update_step;
3081 	}
3082 
3083 	php_session_initialize();
3084 	PS(session_status) = php_session_active;
3085 	IF_SESSION_VARS() {
3086 		zval *sess_var = Z_REFVAL(PS(http_session_vars));
3087 		SEPARATE_ARRAY(sess_var);
3088 
3089 		progress->cancel_upload |= php_check_cancel_upload(progress);
3090 		Z_TRY_ADDREF(progress->data);
3091 		zend_hash_update(Z_ARRVAL_P(sess_var), progress->key.s, &progress->data);
3092 	}
3093 	php_session_flush(1);
3094 } /* }}} */
3095 
php_session_rfc1867_cleanup(php_session_rfc1867_progress * progress)3096 static void php_session_rfc1867_cleanup(php_session_rfc1867_progress *progress) /* {{{ */
3097 {
3098 	php_session_initialize();
3099 	PS(session_status) = php_session_active;
3100 	IF_SESSION_VARS() {
3101 		zval *sess_var = Z_REFVAL(PS(http_session_vars));
3102 		SEPARATE_ARRAY(sess_var);
3103 		zend_hash_del(Z_ARRVAL_P(sess_var), progress->key.s);
3104 	}
3105 	php_session_flush(1);
3106 } /* }}} */
3107 
php_session_rfc1867_callback(unsigned int event,void * event_data,void ** extra)3108 static zend_result php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra) /* {{{ */
3109 {
3110 	php_session_rfc1867_progress *progress;
3111 	zend_result retval = SUCCESS;
3112 
3113 	if (php_session_rfc1867_orig_callback) {
3114 		retval = php_session_rfc1867_orig_callback(event, event_data, extra);
3115 	}
3116 	if (!PS(rfc1867_enabled)) {
3117 		return retval;
3118 	}
3119 
3120 	progress = PS(rfc1867_progress);
3121 
3122 	switch(event) {
3123 		case MULTIPART_EVENT_START: {
3124 			multipart_event_start *data = (multipart_event_start *) event_data;
3125 			progress = ecalloc(1, sizeof(php_session_rfc1867_progress));
3126 			progress->content_length = data->content_length;
3127 			progress->sname_len  = strlen(PS(session_name));
3128 			PS(rfc1867_progress) = progress;
3129 		}
3130 		break;
3131 		case MULTIPART_EVENT_FORMDATA: {
3132 			multipart_event_formdata *data = (multipart_event_formdata *) event_data;
3133 			size_t value_len;
3134 
3135 			if (Z_TYPE(progress->sid) && progress->key.s) {
3136 				break;
3137 			}
3138 
3139 			/* orig callback may have modified *data->newlength */
3140 			if (data->newlength) {
3141 				value_len = *data->newlength;
3142 			} else {
3143 				value_len = data->length;
3144 			}
3145 
3146 			if (data->name && data->value && value_len) {
3147 				size_t name_len = strlen(data->name);
3148 
3149 				if (name_len == progress->sname_len && memcmp(data->name, PS(session_name), name_len) == 0) {
3150 					zval_ptr_dtor(&progress->sid);
3151 					ZVAL_STRINGL(&progress->sid, (*data->value), value_len);
3152 				} else if (name_len == strlen(PS(rfc1867_name)) && memcmp(data->name, PS(rfc1867_name), name_len + 1) == 0) {
3153 					smart_str_free(&progress->key);
3154 					smart_str_appends(&progress->key, PS(rfc1867_prefix));
3155 					smart_str_appendl(&progress->key, *data->value, value_len);
3156 					smart_str_0(&progress->key);
3157 
3158 					progress->apply_trans_sid = APPLY_TRANS_SID;
3159 					php_session_rfc1867_early_find_sid(progress);
3160 				}
3161 			}
3162 		}
3163 		break;
3164 		case MULTIPART_EVENT_FILE_START: {
3165 			multipart_event_file_start *data = (multipart_event_file_start *) event_data;
3166 
3167 			/* Do nothing when $_POST["PHP_SESSION_UPLOAD_PROGRESS"] is not set
3168 			 * or when we have no session id */
3169 			if (!Z_TYPE(progress->sid) || !progress->key.s) {
3170 				break;
3171 			}
3172 
3173 			/* First FILE_START event, initializing data */
3174 			if (Z_ISUNDEF(progress->data)) {
3175 
3176 				if (PS(rfc1867_freq) >= 0) {
3177 					progress->update_step = PS(rfc1867_freq);
3178 				} else if (PS(rfc1867_freq) < 0) { /* % of total size */
3179 					progress->update_step = progress->content_length * -PS(rfc1867_freq) / 100;
3180 				}
3181 				progress->next_update = 0;
3182 				progress->next_update_time = 0.0;
3183 
3184 				array_init(&progress->data);
3185 				array_init(&progress->files);
3186 
3187 				add_assoc_long_ex(&progress->data, "start_time", sizeof("start_time") - 1, (zend_long)sapi_get_request_time());
3188 				add_assoc_long_ex(&progress->data, "content_length",  sizeof("content_length") - 1, progress->content_length);
3189 				add_assoc_long_ex(&progress->data, "bytes_processed", sizeof("bytes_processed") - 1, data->post_bytes_processed);
3190 				add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 0);
3191 				add_assoc_zval_ex(&progress->data, "files", sizeof("files") - 1, &progress->files);
3192 
3193 				progress->post_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->data), "bytes_processed", sizeof("bytes_processed") - 1);
3194 
3195 				php_rinit_session(0);
3196 				PS(id) = zend_string_init(Z_STRVAL(progress->sid), Z_STRLEN(progress->sid), 0);
3197 				if (progress->apply_trans_sid) {
3198 					/* Enable trans sid by modifying flags */
3199 					PS(use_trans_sid) = 1;
3200 					PS(use_only_cookies) = 0;
3201 				}
3202 				PS(send_cookie) = 0;
3203 			}
3204 
3205 			array_init(&progress->current_file);
3206 
3207 			/* Each uploaded file has its own array. Trying to make it close to $_FILES entries. */
3208 			add_assoc_string_ex(&progress->current_file, "field_name", sizeof("field_name") - 1, data->name);
3209 			add_assoc_string_ex(&progress->current_file, "name", sizeof("name") - 1, *data->filename);
3210 			add_assoc_null_ex(&progress->current_file, "tmp_name", sizeof("tmp_name") - 1);
3211 			add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, 0);
3212 
3213 			add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1, 0);
3214 			add_assoc_long_ex(&progress->current_file, "start_time", sizeof("start_time") - 1, (zend_long)time(NULL));
3215 			add_assoc_long_ex(&progress->current_file, "bytes_processed", sizeof("bytes_processed") - 1, 0);
3216 
3217 			add_next_index_zval(&progress->files, &progress->current_file);
3218 
3219 			progress->current_file_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->current_file), "bytes_processed", sizeof("bytes_processed") - 1);
3220 
3221 			Z_LVAL_P(progress->current_file_bytes_processed) =  data->post_bytes_processed;
3222 			php_session_rfc1867_update(progress, 0);
3223 		}
3224 		break;
3225 		case MULTIPART_EVENT_FILE_DATA: {
3226 			multipart_event_file_data *data = (multipart_event_file_data *) event_data;
3227 
3228 			if (!Z_TYPE(progress->sid) || !progress->key.s) {
3229 				break;
3230 			}
3231 
3232 			Z_LVAL_P(progress->current_file_bytes_processed) = data->offset + data->length;
3233 			Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
3234 
3235 			php_session_rfc1867_update(progress, 0);
3236 		}
3237 		break;
3238 		case MULTIPART_EVENT_FILE_END: {
3239 			multipart_event_file_end *data = (multipart_event_file_end *) event_data;
3240 
3241 			if (!Z_TYPE(progress->sid) || !progress->key.s) {
3242 				break;
3243 			}
3244 
3245 			if (data->temp_filename) {
3246 				add_assoc_string_ex(&progress->current_file, "tmp_name",  sizeof("tmp_name") - 1, data->temp_filename);
3247 			}
3248 
3249 			add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, data->cancel_upload);
3250 			add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1,  1);
3251 
3252 			Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
3253 
3254 			php_session_rfc1867_update(progress, 0);
3255 		}
3256 		break;
3257 		case MULTIPART_EVENT_END: {
3258 			multipart_event_end *data = (multipart_event_end *) event_data;
3259 
3260 			if (Z_TYPE(progress->sid) && progress->key.s) {
3261 				if (PS(rfc1867_cleanup)) {
3262 					php_session_rfc1867_cleanup(progress);
3263 				} else {
3264 					if (!Z_ISUNDEF(progress->data)) {
3265 						SEPARATE_ARRAY(&progress->data);
3266 						add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 1);
3267 						Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
3268 						php_session_rfc1867_update(progress, 1);
3269 					}
3270 				}
3271 				php_rshutdown_session_globals();
3272 			}
3273 
3274 			if (!Z_ISUNDEF(progress->data)) {
3275 				zval_ptr_dtor(&progress->data);
3276 			}
3277 			zval_ptr_dtor(&progress->sid);
3278 			smart_str_free(&progress->key);
3279 			efree(progress);
3280 			progress = NULL;
3281 			PS(rfc1867_progress) = NULL;
3282 		}
3283 		break;
3284 	}
3285 
3286 	if (progress && progress->cancel_upload) {
3287 		return FAILURE;
3288 	}
3289 	return retval;
3290 
3291 } /* }}} */
3292 
3293 zend_module_entry session_module_entry = {
3294 	STANDARD_MODULE_HEADER_EX,
3295 	NULL,
3296 	session_deps,
3297 	"session",
3298 	ext_functions,
3299 	PHP_MINIT(session), PHP_MSHUTDOWN(session),
3300 	PHP_RINIT(session), PHP_RSHUTDOWN(session),
3301 	PHP_MINFO(session),
3302 	PHP_SESSION_VERSION,
3303 	PHP_MODULE_GLOBALS(ps),
3304 	PHP_GINIT(ps),
3305 	NULL,
3306 	NULL,
3307 	STANDARD_MODULE_PROPERTIES_EX
3308 };
3309 
3310 #ifdef COMPILE_DL_SESSION
3311 #ifdef ZTS
3312 ZEND_TSRMLS_CACHE_DEFINE()
3313 #endif
3314 ZEND_GET_MODULE(session)
3315 #endif
3316