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