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