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