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