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