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