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