1 /*
2 +----------------------------------------------------------------------+
3 | Copyright (c) The PHP Group |
4 +----------------------------------------------------------------------+
5 | This source file is subject to version 3.01 of the PHP license, |
6 | that is bundled with this package in the file LICENSE, and is |
7 | available through the world-wide-web at the following url: |
8 | https://www.php.net/license/3_01.txt |
9 | If you did not receive a copy of the PHP license and are unable to |
10 | obtain it through the world-wide-web, please send a note to |
11 | license@php.net so we can mail you a copy immediately. |
12 +----------------------------------------------------------------------+
13 | Authors: Sascha Schumann <sascha@schumann.cx> |
14 | Andrei Zmievski <andrei@php.net> |
15 +----------------------------------------------------------------------+
16 */
17
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21
22 #include "php.h"
23
24 #ifdef PHP_WIN32
25 # include "win32/winutil.h"
26 # include "win32/time.h"
27 #else
28 # include <sys/time.h>
29 #endif
30
31 #include <sys/stat.h>
32 #include <fcntl.h>
33
34 #include "php_ini.h"
35 #include "SAPI.h"
36 #include "rfc1867.h"
37 #include "php_variables.h"
38 #include "php_session.h"
39 #include "session_arginfo.h"
40 #include "ext/standard/php_var.h"
41 #include "ext/date/php_date.h"
42 #include "ext/standard/url_scanner_ex.h"
43 #include "ext/standard/info.h"
44 #include "zend_smart_str.h"
45 #include "ext/standard/url.h"
46 #include "ext/standard/basic_functions.h"
47 #include "ext/standard/head.h"
48 #include "ext/random/php_random.h"
49 #include "ext/random/php_random_csprng.h"
50
51 #include "mod_files.h"
52 #include "mod_user.h"
53
54 #ifdef HAVE_LIBMM
55 #include "mod_mm.h"
56 #endif
57
58 PHPAPI ZEND_DECLARE_MODULE_GLOBALS(ps)
59
60 static zend_result php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra);
61 static zend_result (*php_session_rfc1867_orig_callback)(unsigned int event, void *event_data, void **extra);
62 static void php_session_track_init(void);
63
64 /* SessionHandler class */
65 zend_class_entry *php_session_class_entry;
66
67 /* SessionHandlerInterface */
68 zend_class_entry *php_session_iface_entry;
69
70 /* SessionIdInterface */
71 zend_class_entry *php_session_id_iface_entry;
72
73 /* SessionUpdateTimestampInterface */
74 zend_class_entry *php_session_update_timestamp_iface_entry;
75
76 #define PS_MAX_SID_LENGTH 256
77
78 /* ***********
79 * Helpers *
80 *********** */
81
82 #define IF_SESSION_VARS() \
83 if (Z_ISREF_P(&PS(http_session_vars)) && Z_TYPE_P(Z_REFVAL(PS(http_session_vars))) == IS_ARRAY)
84
85 #define SESSION_CHECK_ACTIVE_STATE \
86 if (PS(session_status) == php_session_active) { \
87 php_error_docref(NULL, E_WARNING, "Session ini settings cannot be changed when a session is active"); \
88 return FAILURE; \
89 }
90
91 #define SESSION_CHECK_OUTPUT_STATE \
92 if (SG(headers_sent) && stage != ZEND_INI_STAGE_DEACTIVATE) { \
93 php_error_docref(NULL, E_WARNING, "Session ini settings cannot be changed after headers have already been sent"); \
94 return FAILURE; \
95 }
96
97 #define SESSION_FORBIDDEN_CHARS "=,;.[ \t\r\n\013\014"
98
99 #define APPLY_TRANS_SID (PS(use_trans_sid) && !PS(use_only_cookies))
100
101 static zend_result php_session_send_cookie(void);
102 static zend_result php_session_abort(void);
103
104 /* Initialized in MINIT, readonly otherwise. */
105 static int my_module_number = 0;
106
107 /* Dispatched by RINIT and by php_session_destroy */
php_rinit_session_globals(void)108 static inline void php_rinit_session_globals(void) /* {{{ */
109 {
110 /* Do NOT init PS(mod_user_names) here! */
111 /* TODO: These could be moved to MINIT and removed. These should be initialized by php_rshutdown_session_globals() always when execution is finished. */
112 PS(id) = NULL;
113 PS(session_status) = php_session_none;
114 PS(in_save_handler) = 0;
115 PS(set_handler) = 0;
116 PS(mod_data) = NULL;
117 PS(mod_user_is_open) = 0;
118 PS(define_sid) = 1;
119 PS(session_vars) = NULL;
120 PS(module_number) = my_module_number;
121 ZVAL_UNDEF(&PS(http_session_vars));
122 }
123 /* }}} */
124
php_session_cleanup_filename(void)125 static inline void php_session_cleanup_filename(void) /* {{{ */
126 {
127 if (PS(session_started_filename)) {
128 zend_string_release(PS(session_started_filename));
129 PS(session_started_filename) = NULL;
130 PS(session_started_lineno) = 0;
131 }
132 }
133 /* }}} */
134
135 /* Dispatched by RSHUTDOWN and by php_session_destroy */
php_rshutdown_session_globals(void)136 static inline void php_rshutdown_session_globals(void) /* {{{ */
137 {
138 /* Do NOT destroy PS(mod_user_names) here! */
139 if (!Z_ISUNDEF(PS(http_session_vars))) {
140 zval_ptr_dtor(&PS(http_session_vars));
141 ZVAL_UNDEF(&PS(http_session_vars));
142 }
143 if (PS(mod_data) || PS(mod_user_implemented)) {
144 zend_try {
145 PS(mod)->s_close(&PS(mod_data));
146 } zend_end_try();
147 }
148 if (PS(id)) {
149 zend_string_release_ex(PS(id), 0);
150 PS(id) = NULL;
151 }
152
153 if (PS(session_vars)) {
154 zend_string_release_ex(PS(session_vars), 0);
155 PS(session_vars) = NULL;
156 }
157
158 if (PS(mod_user_class_name)) {
159 zend_string_release(PS(mod_user_class_name));
160 PS(mod_user_class_name) = NULL;
161 }
162
163 php_session_cleanup_filename();
164
165 /* User save handlers may end up directly here by misuse, bugs in user script, etc. */
166 /* Set session status to prevent error while restoring save handler INI value. */
167 PS(session_status) = php_session_none;
168 }
169 /* }}} */
170
php_session_destroy(void)171 PHPAPI zend_result php_session_destroy(void) /* {{{ */
172 {
173 zend_result retval = SUCCESS;
174
175 if (PS(session_status) != php_session_active) {
176 php_error_docref(NULL, E_WARNING, "Trying to destroy uninitialized session");
177 return FAILURE;
178 }
179
180 if (PS(id) && PS(mod)->s_destroy(&PS(mod_data), PS(id)) == FAILURE) {
181 retval = FAILURE;
182 if (!EG(exception)) {
183 php_error_docref(NULL, E_WARNING, "Session object destruction failed");
184 }
185 }
186
187 php_rshutdown_session_globals();
188 php_rinit_session_globals();
189
190 return retval;
191 }
192 /* }}} */
193
php_add_session_var(zend_string * name)194 PHPAPI void php_add_session_var(zend_string *name) /* {{{ */
195 {
196 IF_SESSION_VARS() {
197 zval *sess_var = Z_REFVAL(PS(http_session_vars));
198 SEPARATE_ARRAY(sess_var);
199 if (!zend_hash_exists(Z_ARRVAL_P(sess_var), name)) {
200 zval empty_var;
201 ZVAL_NULL(&empty_var);
202 zend_hash_update(Z_ARRVAL_P(sess_var), name, &empty_var);
203 }
204 }
205 }
206 /* }}} */
207
php_set_session_var(zend_string * name,zval * state_val,php_unserialize_data_t * var_hash)208 PHPAPI zval* php_set_session_var(zend_string *name, zval *state_val, php_unserialize_data_t *var_hash) /* {{{ */
209 {
210 IF_SESSION_VARS() {
211 zval *sess_var = Z_REFVAL(PS(http_session_vars));
212 SEPARATE_ARRAY(sess_var);
213 return zend_hash_update(Z_ARRVAL_P(sess_var), name, state_val);
214 }
215 return NULL;
216 }
217 /* }}} */
218
php_get_session_var(zend_string * name)219 PHPAPI zval* php_get_session_var(zend_string *name) /* {{{ */
220 {
221 IF_SESSION_VARS() {
222 return zend_hash_find(Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars))), name);
223 }
224 return NULL;
225 }
226 /* }}} */
227
php_session_track_init(void)228 static void php_session_track_init(void) /* {{{ */
229 {
230 zval session_vars;
231 zend_string *var_name = ZSTR_INIT_LITERAL("_SESSION", 0);
232 /* Unconditionally destroy existing array -- possible dirty data */
233 zend_delete_global_variable(var_name);
234
235 if (!Z_ISUNDEF(PS(http_session_vars))) {
236 zval_ptr_dtor(&PS(http_session_vars));
237 }
238
239 array_init(&session_vars);
240 ZVAL_NEW_REF(&PS(http_session_vars), &session_vars);
241 Z_ADDREF_P(&PS(http_session_vars));
242 zend_hash_update_ind(&EG(symbol_table), var_name, &PS(http_session_vars));
243 zend_string_release_ex(var_name, 0);
244 }
245 /* }}} */
246
php_session_encode(void)247 static zend_string *php_session_encode(void) /* {{{ */
248 {
249 IF_SESSION_VARS() {
250 if (!PS(serializer)) {
251 php_error_docref(NULL, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
252 return NULL;
253 }
254 return PS(serializer)->encode();
255 } else {
256 php_error_docref(NULL, E_WARNING, "Cannot encode non-existent session");
257 }
258 return NULL;
259 }
260 /* }}} */
261
php_session_cancel_decode(void)262 static ZEND_COLD void php_session_cancel_decode(void)
263 {
264 php_session_destroy();
265 php_session_track_init();
266 php_error_docref(NULL, E_WARNING, "Failed to decode session object. Session has been destroyed");
267 }
268
php_session_decode(zend_string * data)269 static zend_result php_session_decode(zend_string *data) /* {{{ */
270 {
271 if (!PS(serializer)) {
272 php_error_docref(NULL, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object");
273 return FAILURE;
274 }
275 zend_try {
276 if (PS(serializer)->decode(ZSTR_VAL(data), ZSTR_LEN(data)) == FAILURE) {
277 php_session_cancel_decode();
278 return FAILURE;
279 }
280 } zend_catch {
281 php_session_cancel_decode();
282 zend_bailout();
283 } zend_end_try();
284 return SUCCESS;
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 zend_error(E_DEPRECATED, "Calling session_set_save_handler() with more than 2 arguments is deprecated");
2107 if (UNEXPECTED(EG(exception))) {
2108 RETURN_THROWS();
2109 }
2110
2111 /* Procedural version */
2112 zend_fcall_info open_fci = {0};
2113 zend_fcall_info_cache open_fcc;
2114 zend_fcall_info close_fci = {0};
2115 zend_fcall_info_cache close_fcc;
2116 zend_fcall_info read_fci = {0};
2117 zend_fcall_info_cache read_fcc;
2118 zend_fcall_info write_fci = {0};
2119 zend_fcall_info_cache write_fcc;
2120 zend_fcall_info destroy_fci = {0};
2121 zend_fcall_info_cache destroy_fcc;
2122 zend_fcall_info gc_fci = {0};
2123 zend_fcall_info_cache gc_fcc;
2124 zend_fcall_info create_id_fci = {0};
2125 zend_fcall_info_cache create_id_fcc;
2126 zend_fcall_info validate_id_fci = {0};
2127 zend_fcall_info_cache validate_id_fcc;
2128 zend_fcall_info update_timestamp_fci = {0};
2129 zend_fcall_info_cache update_timestamp_fcc;
2130
2131 if (zend_parse_parameters(ZEND_NUM_ARGS(),
2132 "ffffff|f!f!f!",
2133 &open_fci, &open_fcc,
2134 &close_fci, &close_fcc,
2135 &read_fci, &read_fcc,
2136 &write_fci, &write_fcc,
2137 &destroy_fci, &destroy_fcc,
2138 &gc_fci, &gc_fcc,
2139 &create_id_fci, &create_id_fcc,
2140 &validate_id_fci, &validate_id_fcc,
2141 &update_timestamp_fci, &update_timestamp_fcc) == FAILURE
2142 ) {
2143 RETURN_THROWS();
2144 }
2145 if (!can_session_handler_be_changed()) {
2146 RETURN_FALSE;
2147 }
2148
2149 /* If a custom session handler is already set, release relevant info */
2150 if (PS(mod_user_class_name)) {
2151 zend_string_release(PS(mod_user_class_name));
2152 PS(mod_user_class_name) = NULL;
2153 }
2154
2155 /* remove shutdown function */
2156 remove_user_shutdown_function("session_shutdown", strlen("session_shutdown"));
2157
2158 if (!PS(mod) || PS(mod) != &ps_mod_user) {
2159 set_user_save_handler_ini();
2160 }
2161
2162 /* Define mandatory handlers */
2163 SESSION_SET_USER_HANDLER_PROCEDURAL(ps_open, open_fci);
2164 SESSION_SET_USER_HANDLER_PROCEDURAL(ps_close, close_fci);
2165 SESSION_SET_USER_HANDLER_PROCEDURAL(ps_read, read_fci);
2166 SESSION_SET_USER_HANDLER_PROCEDURAL(ps_write, write_fci);
2167 SESSION_SET_USER_HANDLER_PROCEDURAL(ps_destroy, destroy_fci);
2168 SESSION_SET_USER_HANDLER_PROCEDURAL(ps_gc, gc_fci);
2169
2170 /* Check for optional handlers */
2171 SESSION_SET_USER_HANDLER_PROCEDURAL_OPTIONAL(ps_create_sid, create_id_fci);
2172 SESSION_SET_USER_HANDLER_PROCEDURAL_OPTIONAL(ps_validate_sid, validate_id_fci);
2173 SESSION_SET_USER_HANDLER_PROCEDURAL_OPTIONAL(ps_update_timestamp, update_timestamp_fci);
2174
2175 RETURN_TRUE;
2176 }
2177 /* }}} */
2178
2179 /* {{{ 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)2180 PHP_FUNCTION(session_save_path)
2181 {
2182 zend_string *name = NULL;
2183 zend_string *ini_name;
2184
2185 if (zend_parse_parameters(ZEND_NUM_ARGS(), "|P!", &name) == FAILURE) {
2186 RETURN_THROWS();
2187 }
2188
2189 if (name && PS(session_status) == php_session_active) {
2190 php_error_docref(NULL, E_WARNING, "Session save path cannot be changed when a session is active");
2191 RETURN_FALSE;
2192 }
2193
2194 if (name && SG(headers_sent)) {
2195 php_error_docref(NULL, E_WARNING, "Session save path cannot be changed after headers have already been sent");
2196 RETURN_FALSE;
2197 }
2198
2199 RETVAL_STRING(PS(save_path));
2200
2201 if (name) {
2202 ini_name = ZSTR_INIT_LITERAL("session.save_path", 0);
2203 zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
2204 zend_string_release_ex(ini_name, 0);
2205 }
2206 }
2207 /* }}} */
2208
2209 /* {{{ Return the current session id. If newid is given, the session id is replaced with newid */
PHP_FUNCTION(session_id)2210 PHP_FUNCTION(session_id)
2211 {
2212 zend_string *name = NULL;
2213
2214 if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!", &name) == FAILURE) {
2215 RETURN_THROWS();
2216 }
2217
2218 if (name && PS(session_status) == php_session_active) {
2219 php_error_docref(NULL, E_WARNING, "Session ID cannot be changed when a session is active");
2220 RETURN_FALSE;
2221 }
2222
2223 if (name && PS(use_cookies) && SG(headers_sent)) {
2224 php_error_docref(NULL, E_WARNING, "Session ID cannot be changed after headers have already been sent");
2225 RETURN_FALSE;
2226 }
2227
2228 if (PS(id)) {
2229 /* keep compatibility for "\0" characters ???
2230 * see: ext/session/tests/session_id_error3.phpt */
2231 size_t len = strlen(ZSTR_VAL(PS(id)));
2232 if (UNEXPECTED(len != ZSTR_LEN(PS(id)))) {
2233 RETVAL_NEW_STR(zend_string_init(ZSTR_VAL(PS(id)), len, 0));
2234 } else {
2235 RETVAL_STR_COPY(PS(id));
2236 }
2237 } else {
2238 RETVAL_EMPTY_STRING();
2239 }
2240
2241 if (name) {
2242 if (PS(id)) {
2243 zend_string_release_ex(PS(id), 0);
2244 }
2245 PS(id) = zend_string_copy(name);
2246 }
2247 }
2248 /* }}} */
2249
2250 /* {{{ 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)2251 PHP_FUNCTION(session_regenerate_id)
2252 {
2253 bool del_ses = 0;
2254 zend_string *data;
2255
2256 if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &del_ses) == FAILURE) {
2257 RETURN_THROWS();
2258 }
2259
2260 if (PS(session_status) != php_session_active) {
2261 php_error_docref(NULL, E_WARNING, "Session ID cannot be regenerated when there is no active session");
2262 RETURN_FALSE;
2263 }
2264
2265 if (SG(headers_sent)) {
2266 php_error_docref(NULL, E_WARNING, "Session ID cannot be regenerated after headers have already been sent");
2267 RETURN_FALSE;
2268 }
2269
2270 /* Process old session data */
2271 if (del_ses) {
2272 if (PS(mod)->s_destroy(&PS(mod_data), PS(id)) == FAILURE) {
2273 PS(mod)->s_close(&PS(mod_data));
2274 PS(session_status) = php_session_none;
2275 if (!EG(exception)) {
2276 php_error_docref(NULL, E_WARNING, "Session object destruction failed. ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2277 }
2278 RETURN_FALSE;
2279 }
2280 } else {
2281 zend_result ret;
2282 data = php_session_encode();
2283 if (data) {
2284 ret = PS(mod)->s_write(&PS(mod_data), PS(id), data, PS(gc_maxlifetime));
2285 zend_string_release_ex(data, 0);
2286 } else {
2287 ret = PS(mod)->s_write(&PS(mod_data), PS(id), ZSTR_EMPTY_ALLOC(), PS(gc_maxlifetime));
2288 }
2289 if (ret == FAILURE) {
2290 PS(mod)->s_close(&PS(mod_data));
2291 PS(session_status) = php_session_none;
2292 php_error_docref(NULL, E_WARNING, "Session write failed. ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2293 RETURN_FALSE;
2294 }
2295 }
2296 PS(mod)->s_close(&PS(mod_data));
2297
2298 /* New session data */
2299 if (PS(session_vars)) {
2300 zend_string_release_ex(PS(session_vars), 0);
2301 PS(session_vars) = NULL;
2302 }
2303 zend_string_release_ex(PS(id), 0);
2304 PS(id) = NULL;
2305
2306 if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name)) == FAILURE) {
2307 PS(session_status) = php_session_none;
2308 if (!EG(exception)) {
2309 zend_throw_error(NULL, "Failed to open session: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2310 }
2311 RETURN_THROWS();
2312 }
2313
2314 PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
2315 if (!PS(id)) {
2316 PS(session_status) = php_session_none;
2317 if (!EG(exception)) {
2318 zend_throw_error(NULL, "Failed to create new session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2319 }
2320 RETURN_THROWS();
2321 }
2322 if (PS(use_strict_mode)) {
2323 if ((!PS(mod_user_implemented) && PS(mod)->s_validate_sid) || !Z_ISUNDEF(PS(mod_user_names).ps_validate_sid)) {
2324 int limit = 3;
2325 /* Try to generate non-existing ID */
2326 while (limit-- && PS(mod)->s_validate_sid(&PS(mod_data), PS(id)) == SUCCESS) {
2327 zend_string_release_ex(PS(id), 0);
2328 PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
2329 if (!PS(id)) {
2330 PS(mod)->s_close(&PS(mod_data));
2331 PS(session_status) = php_session_none;
2332 if (!EG(exception)) {
2333 zend_throw_error(NULL, "Failed to create session ID by collision: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2334 }
2335 RETURN_THROWS();
2336 }
2337 }
2338 }
2339 // TODO warn that ID cannot be verified? else { }
2340 }
2341 /* Read is required to make new session data at this point. */
2342 if (PS(mod)->s_read(&PS(mod_data), PS(id), &data, PS(gc_maxlifetime)) == FAILURE) {
2343 PS(mod)->s_close(&PS(mod_data));
2344 PS(session_status) = php_session_none;
2345 if (!EG(exception)) {
2346 zend_throw_error(NULL, "Failed to create(read) session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
2347 }
2348 RETURN_THROWS();
2349 }
2350 if (data) {
2351 zend_string_release_ex(data, 0);
2352 }
2353
2354 if (PS(use_cookies)) {
2355 PS(send_cookie) = 1;
2356 }
2357 if (php_session_reset_id() == FAILURE) {
2358 RETURN_FALSE;
2359 }
2360
2361 RETURN_TRUE;
2362 }
2363 /* }}} */
2364
2365 /* {{{ Generate new session ID. Intended for user save handlers. */
PHP_FUNCTION(session_create_id)2366 PHP_FUNCTION(session_create_id)
2367 {
2368 zend_string *prefix = NULL, *new_id;
2369 smart_str id = {0};
2370
2371 if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &prefix) == FAILURE) {
2372 RETURN_THROWS();
2373 }
2374
2375 if (prefix && ZSTR_LEN(prefix)) {
2376 if (php_session_valid_key(ZSTR_VAL(prefix)) == FAILURE) {
2377 /* E_ERROR raised for security reason. */
2378 php_error_docref(NULL, E_WARNING, "Prefix cannot contain special characters. Only the A-Z, a-z, 0-9, \"-\", and \",\" characters are allowed");
2379 RETURN_FALSE;
2380 } else {
2381 smart_str_append(&id, prefix);
2382 }
2383 }
2384
2385 if (!PS(in_save_handler) && PS(session_status) == php_session_active) {
2386 int limit = 3;
2387 while (limit--) {
2388 new_id = PS(mod)->s_create_sid(&PS(mod_data));
2389 if (!PS(mod)->s_validate_sid || (PS(mod_user_implemented) && Z_ISUNDEF(PS(mod_user_names).ps_validate_sid))) {
2390 break;
2391 } else {
2392 /* Detect collision and retry */
2393 if (PS(mod)->s_validate_sid(&PS(mod_data), new_id) == SUCCESS) {
2394 zend_string_release_ex(new_id, 0);
2395 new_id = NULL;
2396 continue;
2397 }
2398 break;
2399 }
2400 }
2401 } else {
2402 new_id = php_session_create_id(NULL);
2403 }
2404
2405 if (new_id) {
2406 smart_str_append(&id, new_id);
2407 zend_string_release_ex(new_id, 0);
2408 } else {
2409 smart_str_free(&id);
2410 php_error_docref(NULL, E_WARNING, "Failed to create new ID");
2411 RETURN_FALSE;
2412 }
2413 RETVAL_STR(smart_str_extract(&id));
2414 }
2415 /* }}} */
2416
2417 /* {{{ 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)2418 PHP_FUNCTION(session_cache_limiter)
2419 {
2420 zend_string *limiter = NULL;
2421 zend_string *ini_name;
2422
2423 if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!", &limiter) == FAILURE) {
2424 RETURN_THROWS();
2425 }
2426
2427 if (limiter && PS(session_status) == php_session_active) {
2428 php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be changed when a session is active");
2429 RETURN_FALSE;
2430 }
2431
2432 if (limiter && SG(headers_sent)) {
2433 php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be changed after headers have already been sent");
2434 RETURN_FALSE;
2435 }
2436
2437 RETVAL_STRING(PS(cache_limiter));
2438
2439 if (limiter) {
2440 ini_name = ZSTR_INIT_LITERAL("session.cache_limiter", 0);
2441 zend_alter_ini_entry(ini_name, limiter, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
2442 zend_string_release_ex(ini_name, 0);
2443 }
2444 }
2445 /* }}} */
2446
2447 /* {{{ 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)2448 PHP_FUNCTION(session_cache_expire)
2449 {
2450 zend_long expires;
2451 bool expires_is_null = 1;
2452
2453 if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &expires, &expires_is_null) == FAILURE) {
2454 RETURN_THROWS();
2455 }
2456
2457 if (!expires_is_null && PS(session_status) == php_session_active) {
2458 php_error_docref(NULL, E_WARNING, "Session cache expiration cannot be changed when a session is active");
2459 RETURN_LONG(PS(cache_expire));
2460 }
2461
2462 if (!expires_is_null && SG(headers_sent)) {
2463 php_error_docref(NULL, E_WARNING, "Session cache expiration cannot be changed after headers have already been sent");
2464 RETURN_FALSE;
2465 }
2466
2467 RETVAL_LONG(PS(cache_expire));
2468
2469 if (!expires_is_null) {
2470 zend_string *ini_name = ZSTR_INIT_LITERAL("session.cache_expire", 0);
2471 zend_string *ini_value = zend_long_to_str(expires);
2472 zend_alter_ini_entry(ini_name, ini_value, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);
2473 zend_string_release_ex(ini_name, 0);
2474 zend_string_release_ex(ini_value, 0);
2475 }
2476 }
2477 /* }}} */
2478
2479 /* {{{ Serializes the current setup and returns the serialized representation */
PHP_FUNCTION(session_encode)2480 PHP_FUNCTION(session_encode)
2481 {
2482 zend_string *enc;
2483
2484 if (zend_parse_parameters_none() == FAILURE) {
2485 RETURN_THROWS();
2486 }
2487
2488 enc = php_session_encode();
2489 if (enc == NULL) {
2490 RETURN_FALSE;
2491 }
2492
2493 RETURN_STR(enc);
2494 }
2495 /* }}} */
2496
2497 /* {{{ Deserializes data and reinitializes the variables */
PHP_FUNCTION(session_decode)2498 PHP_FUNCTION(session_decode)
2499 {
2500 zend_string *str = NULL;
2501
2502 if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &str) == FAILURE) {
2503 RETURN_THROWS();
2504 }
2505
2506 if (PS(session_status) != php_session_active) {
2507 php_error_docref(NULL, E_WARNING, "Session data cannot be decoded when there is no active session");
2508 RETURN_FALSE;
2509 }
2510
2511 if (php_session_decode(str) == FAILURE) {
2512 RETURN_FALSE;
2513 }
2514 RETURN_TRUE;
2515 }
2516 /* }}} */
2517
php_session_start_set_ini(zend_string * varname,zend_string * new_value)2518 static zend_result php_session_start_set_ini(zend_string *varname, zend_string *new_value) {
2519 zend_result ret;
2520 smart_str buf ={0};
2521 smart_str_appends(&buf, "session");
2522 smart_str_appendc(&buf, '.');
2523 smart_str_append(&buf, varname);
2524 smart_str_0(&buf);
2525 ret = zend_alter_ini_entry_ex(buf.s, new_value, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0);
2526 smart_str_free(&buf);
2527 return ret;
2528 }
2529
2530 /* {{{ Begin session */
PHP_FUNCTION(session_start)2531 PHP_FUNCTION(session_start)
2532 {
2533 zval *options = NULL;
2534 zval *value;
2535 zend_ulong num_idx;
2536 zend_string *str_idx;
2537 zend_long read_and_close = 0;
2538
2539 if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a", &options) == FAILURE) {
2540 RETURN_THROWS();
2541 }
2542
2543 if (PS(session_status) == php_session_active) {
2544 if (PS(session_started_filename)) {
2545 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));
2546 } else if (PS(auto_start)) {
2547 /* This option can't be changed at runtime, so we can assume it's because of this */
2548 php_error_docref(NULL, E_NOTICE, "Ignoring session_start() because a session is already automatically active");
2549 } else {
2550 php_error_docref(NULL, E_NOTICE, "Ignoring session_start() because a session is already active");
2551 }
2552 RETURN_TRUE;
2553 }
2554
2555 /*
2556 * TODO: To prevent unusable session with trans sid, actual output started status is
2557 * required. i.e. There shouldn't be any outputs in output buffer, otherwise session
2558 * module is unable to rewrite output.
2559 */
2560 if (PS(use_cookies) && SG(headers_sent)) {
2561 php_error_docref(NULL, E_WARNING, "Session cannot be started after headers have already been sent");
2562 RETURN_FALSE;
2563 }
2564
2565 /* set options */
2566 if (options) {
2567 ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(options), num_idx, str_idx, value) {
2568 if (str_idx) {
2569 switch(Z_TYPE_P(value)) {
2570 case IS_STRING:
2571 case IS_TRUE:
2572 case IS_FALSE:
2573 case IS_LONG:
2574 if (zend_string_equals_literal(str_idx, "read_and_close")) {
2575 read_and_close = zval_get_long(value);
2576 } else {
2577 zend_string *tmp_val;
2578 zend_string *val = zval_get_tmp_string(value, &tmp_val);
2579 if (php_session_start_set_ini(str_idx, val) == FAILURE) {
2580 php_error_docref(NULL, E_WARNING, "Setting option \"%s\" failed", ZSTR_VAL(str_idx));
2581 }
2582 zend_tmp_string_release(tmp_val);
2583 }
2584 break;
2585 default:
2586 zend_type_error("%s(): Option \"%s\" must be of type string|int|bool, %s given",
2587 get_active_function_name(), ZSTR_VAL(str_idx), zend_zval_value_name(value)
2588 );
2589 RETURN_THROWS();
2590 }
2591 }
2592 (void) num_idx;
2593 } ZEND_HASH_FOREACH_END();
2594 }
2595
2596 php_session_start();
2597
2598 if (PS(session_status) != php_session_active) {
2599 IF_SESSION_VARS() {
2600 zval *sess_var = Z_REFVAL(PS(http_session_vars));
2601 SEPARATE_ARRAY(sess_var);
2602 /* Clean $_SESSION. */
2603 zend_hash_clean(Z_ARRVAL_P(sess_var));
2604 }
2605 RETURN_FALSE;
2606 }
2607
2608 if (read_and_close) {
2609 php_session_flush(0);
2610 }
2611
2612 RETURN_TRUE;
2613 }
2614 /* }}} */
2615
2616 /* {{{ Destroy the current session and all data associated with it */
PHP_FUNCTION(session_destroy)2617 PHP_FUNCTION(session_destroy)
2618 {
2619 if (zend_parse_parameters_none() == FAILURE) {
2620 RETURN_THROWS();
2621 }
2622
2623 RETURN_BOOL(php_session_destroy() == SUCCESS);
2624 }
2625 /* }}} */
2626
2627 /* {{{ Unset all registered variables */
PHP_FUNCTION(session_unset)2628 PHP_FUNCTION(session_unset)
2629 {
2630 if (zend_parse_parameters_none() == FAILURE) {
2631 RETURN_THROWS();
2632 }
2633
2634 if (PS(session_status) != php_session_active) {
2635 RETURN_FALSE;
2636 }
2637
2638 IF_SESSION_VARS() {
2639 zval *sess_var = Z_REFVAL(PS(http_session_vars));
2640 SEPARATE_ARRAY(sess_var);
2641
2642 /* Clean $_SESSION. */
2643 zend_hash_clean(Z_ARRVAL_P(sess_var));
2644 }
2645 RETURN_TRUE;
2646 }
2647 /* }}} */
2648
2649 /* {{{ Perform GC and return number of deleted sessions */
PHP_FUNCTION(session_gc)2650 PHP_FUNCTION(session_gc)
2651 {
2652 zend_long num;
2653
2654 if (zend_parse_parameters_none() == FAILURE) {
2655 RETURN_THROWS();
2656 }
2657
2658 if (PS(session_status) != php_session_active) {
2659 php_error_docref(NULL, E_WARNING, "Session cannot be garbage collected when there is no active session");
2660 RETURN_FALSE;
2661 }
2662
2663 num = php_session_gc(1);
2664 if (num < 0) {
2665 RETURN_FALSE;
2666 }
2667
2668 RETURN_LONG(num);
2669 }
2670 /* }}} */
2671
2672
2673 /* {{{ Write session data and end session */
PHP_FUNCTION(session_write_close)2674 PHP_FUNCTION(session_write_close)
2675 {
2676 if (zend_parse_parameters_none() == FAILURE) {
2677 RETURN_THROWS();
2678 }
2679
2680 if (PS(session_status) != php_session_active) {
2681 RETURN_FALSE;
2682 }
2683 php_session_flush(1);
2684 RETURN_TRUE;
2685 }
2686 /* }}} */
2687
2688 /* {{{ Abort session and end session. Session data will not be written */
PHP_FUNCTION(session_abort)2689 PHP_FUNCTION(session_abort)
2690 {
2691 if (zend_parse_parameters_none() == FAILURE) {
2692 RETURN_THROWS();
2693 }
2694
2695 if (PS(session_status) != php_session_active) {
2696 RETURN_FALSE;
2697 }
2698 php_session_abort();
2699 RETURN_TRUE;
2700 }
2701 /* }}} */
2702
2703 /* {{{ Reset session data from saved session data */
PHP_FUNCTION(session_reset)2704 PHP_FUNCTION(session_reset)
2705 {
2706 if (zend_parse_parameters_none() == FAILURE) {
2707 RETURN_THROWS();
2708 }
2709
2710 if (PS(session_status) != php_session_active) {
2711 RETURN_FALSE;
2712 }
2713 php_session_reset();
2714 RETURN_TRUE;
2715 }
2716 /* }}} */
2717
2718 /* {{{ Returns the current session status */
PHP_FUNCTION(session_status)2719 PHP_FUNCTION(session_status)
2720 {
2721 if (zend_parse_parameters_none() == FAILURE) {
2722 RETURN_THROWS();
2723 }
2724
2725 RETURN_LONG(PS(session_status));
2726 }
2727 /* }}} */
2728
2729 /* {{{ Registers session_write_close() as a shutdown function */
PHP_FUNCTION(session_register_shutdown)2730 PHP_FUNCTION(session_register_shutdown)
2731 {
2732 php_shutdown_function_entry shutdown_function_entry;
2733 zval callable;
2734 zend_result result;
2735
2736 ZEND_PARSE_PARAMETERS_NONE();
2737
2738 /* This function is registered itself as a shutdown function by
2739 * session_set_save_handler($obj). The reason we now register another
2740 * shutdown function is in case the user registered their own shutdown
2741 * function after calling session_set_save_handler(), which expects
2742 * the session still to be available.
2743 */
2744 ZVAL_STRING(&callable, "session_write_close");
2745 result = zend_fcall_info_init(&callable, 0, &shutdown_function_entry.fci,
2746 &shutdown_function_entry.fci_cache, NULL, NULL);
2747
2748 ZEND_ASSERT(result == SUCCESS);
2749
2750 if (!append_user_shutdown_function(&shutdown_function_entry)) {
2751 zval_ptr_dtor(&callable);
2752
2753 /* Unable to register shutdown function, presumably because of lack
2754 * of memory, so flush the session now. It would be done in rshutdown
2755 * anyway but the handler will have had it's dtor called by then.
2756 * If the user does have a later shutdown function which needs the
2757 * session then tough luck.
2758 */
2759 php_session_flush(1);
2760 php_error_docref(NULL, E_WARNING, "Session shutdown function cannot be registered");
2761 }
2762 }
2763 /* }}} */
2764
2765 /* ********************************
2766 * Module Setup and Destruction *
2767 ******************************** */
2768
php_rinit_session(bool auto_start)2769 static zend_result php_rinit_session(bool auto_start) /* {{{ */
2770 {
2771 php_rinit_session_globals();
2772
2773 PS(mod) = NULL;
2774 {
2775 char *value;
2776
2777 value = zend_ini_string("session.save_handler", sizeof("session.save_handler") - 1, 0);
2778 if (value) {
2779 PS(mod) = _php_find_ps_module(value);
2780 }
2781 }
2782
2783 if (PS(serializer) == NULL) {
2784 char *value;
2785
2786 value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler") - 1, 0);
2787 if (value) {
2788 PS(serializer) = _php_find_ps_serializer(value);
2789 }
2790 }
2791
2792 if (PS(mod) == NULL || PS(serializer) == NULL) {
2793 /* current status is unusable */
2794 PS(session_status) = php_session_disabled;
2795 return SUCCESS;
2796 }
2797
2798 if (auto_start) {
2799 php_session_start();
2800 }
2801
2802 return SUCCESS;
2803 } /* }}} */
2804
PHP_RINIT_FUNCTION(session)2805 static PHP_RINIT_FUNCTION(session) /* {{{ */
2806 {
2807 return php_rinit_session(PS(auto_start));
2808 }
2809 /* }}} */
2810
2811 #define SESSION_FREE_USER_HANDLER(struct_name) \
2812 if (!Z_ISUNDEF(PS(mod_user_names).struct_name)) { \
2813 zval_ptr_dtor(&PS(mod_user_names).struct_name); \
2814 ZVAL_UNDEF(&PS(mod_user_names).struct_name); \
2815 }
2816
2817
PHP_RSHUTDOWN_FUNCTION(session)2818 static PHP_RSHUTDOWN_FUNCTION(session) /* {{{ */
2819 {
2820 if (PS(session_status) == php_session_active) {
2821 zend_try {
2822 php_session_flush(1);
2823 } zend_end_try();
2824 }
2825 php_rshutdown_session_globals();
2826
2827 /* this should NOT be done in php_rshutdown_session_globals() */
2828 /* Free user defined handlers */
2829 SESSION_FREE_USER_HANDLER(ps_open);
2830 SESSION_FREE_USER_HANDLER(ps_close);
2831 SESSION_FREE_USER_HANDLER(ps_read);
2832 SESSION_FREE_USER_HANDLER(ps_write);
2833 SESSION_FREE_USER_HANDLER(ps_destroy);
2834 SESSION_FREE_USER_HANDLER(ps_gc);
2835 SESSION_FREE_USER_HANDLER(ps_create_sid);
2836 SESSION_FREE_USER_HANDLER(ps_validate_sid);
2837 SESSION_FREE_USER_HANDLER(ps_update_timestamp);
2838
2839 return SUCCESS;
2840 }
2841 /* }}} */
2842
PHP_GINIT_FUNCTION(ps)2843 static PHP_GINIT_FUNCTION(ps) /* {{{ */
2844 {
2845 #if defined(COMPILE_DL_SESSION) && defined(ZTS)
2846 ZEND_TSRMLS_CACHE_UPDATE();
2847 #endif
2848
2849 ps_globals->save_path = NULL;
2850 ps_globals->session_name = NULL;
2851 ps_globals->id = NULL;
2852 ps_globals->mod = NULL;
2853 ps_globals->serializer = NULL;
2854 ps_globals->mod_data = NULL;
2855 ps_globals->session_status = php_session_none;
2856 ps_globals->default_mod = NULL;
2857 ps_globals->mod_user_implemented = 0;
2858 ps_globals->mod_user_class_name = NULL;
2859 ps_globals->mod_user_is_open = 0;
2860 ps_globals->session_vars = NULL;
2861 ps_globals->set_handler = 0;
2862 ps_globals->session_started_filename = NULL;
2863 ps_globals->session_started_lineno = 0;
2864 /* Unset user defined handlers */
2865 ZVAL_UNDEF(&ps_globals->mod_user_names.ps_open);
2866 ZVAL_UNDEF(&ps_globals->mod_user_names.ps_close);
2867 ZVAL_UNDEF(&ps_globals->mod_user_names.ps_read);
2868 ZVAL_UNDEF(&ps_globals->mod_user_names.ps_write);
2869 ZVAL_UNDEF(&ps_globals->mod_user_names.ps_destroy);
2870 ZVAL_UNDEF(&ps_globals->mod_user_names.ps_gc);
2871 ZVAL_UNDEF(&ps_globals->mod_user_names.ps_create_sid);
2872 ZVAL_UNDEF(&ps_globals->mod_user_names.ps_validate_sid);
2873 ZVAL_UNDEF(&ps_globals->mod_user_names.ps_update_timestamp);
2874 ZVAL_UNDEF(&ps_globals->http_session_vars);
2875 }
2876 /* }}} */
2877
PHP_MINIT_FUNCTION(session)2878 static PHP_MINIT_FUNCTION(session) /* {{{ */
2879 {
2880 zend_register_auto_global(zend_string_init_interned("_SESSION", sizeof("_SESSION") - 1, 1), 0, NULL);
2881
2882 my_module_number = module_number;
2883 PS(module_number) = module_number;
2884
2885 PS(session_status) = php_session_none;
2886 REGISTER_INI_ENTRIES();
2887
2888 #ifdef HAVE_LIBMM
2889 PHP_MINIT(ps_mm) (INIT_FUNC_ARGS_PASSTHRU);
2890 #endif
2891 php_session_rfc1867_orig_callback = php_rfc1867_callback;
2892 php_rfc1867_callback = php_session_rfc1867_callback;
2893
2894 /* Register interfaces */
2895 php_session_iface_entry = register_class_SessionHandlerInterface();
2896
2897 php_session_id_iface_entry = register_class_SessionIdInterface();
2898
2899 php_session_update_timestamp_iface_entry = register_class_SessionUpdateTimestampHandlerInterface();
2900
2901 /* Register base class */
2902 php_session_class_entry = register_class_SessionHandler(php_session_iface_entry, php_session_id_iface_entry);
2903
2904 register_session_symbols(module_number);
2905
2906 return SUCCESS;
2907 }
2908 /* }}} */
2909
PHP_MSHUTDOWN_FUNCTION(session)2910 static PHP_MSHUTDOWN_FUNCTION(session) /* {{{ */
2911 {
2912 UNREGISTER_INI_ENTRIES();
2913
2914 #ifdef HAVE_LIBMM
2915 PHP_MSHUTDOWN(ps_mm) (SHUTDOWN_FUNC_ARGS_PASSTHRU);
2916 #endif
2917
2918 /* reset rfc1867 callbacks */
2919 php_session_rfc1867_orig_callback = NULL;
2920 if (php_rfc1867_callback == php_session_rfc1867_callback) {
2921 php_rfc1867_callback = NULL;
2922 }
2923
2924 ps_serializers[PREDEFINED_SERIALIZERS].name = NULL;
2925 memset(ZEND_VOIDP(&ps_modules[PREDEFINED_MODULES]), 0, (MAX_MODULES-PREDEFINED_MODULES)*sizeof(ps_module *));
2926
2927 return SUCCESS;
2928 }
2929 /* }}} */
2930
PHP_MINFO_FUNCTION(session)2931 static PHP_MINFO_FUNCTION(session) /* {{{ */
2932 {
2933 const ps_module **mod;
2934 ps_serializer *ser;
2935 smart_str save_handlers = {0};
2936 smart_str ser_handlers = {0};
2937 int i;
2938
2939 /* Get save handlers */
2940 for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
2941 if (*mod && (*mod)->s_name) {
2942 smart_str_appends(&save_handlers, (*mod)->s_name);
2943 smart_str_appendc(&save_handlers, ' ');
2944 }
2945 }
2946
2947 /* Get serializer handlers */
2948 for (i = 0, ser = ps_serializers; i < MAX_SERIALIZERS; i++, ser++) {
2949 if (ser->name) {
2950 smart_str_appends(&ser_handlers, ser->name);
2951 smart_str_appendc(&ser_handlers, ' ');
2952 }
2953 }
2954
2955 php_info_print_table_start();
2956 php_info_print_table_row(2, "Session Support", "enabled" );
2957
2958 if (save_handlers.s) {
2959 smart_str_0(&save_handlers);
2960 php_info_print_table_row(2, "Registered save handlers", ZSTR_VAL(save_handlers.s));
2961 smart_str_free(&save_handlers);
2962 } else {
2963 php_info_print_table_row(2, "Registered save handlers", "none");
2964 }
2965
2966 if (ser_handlers.s) {
2967 smart_str_0(&ser_handlers);
2968 php_info_print_table_row(2, "Registered serializer handlers", ZSTR_VAL(ser_handlers.s));
2969 smart_str_free(&ser_handlers);
2970 } else {
2971 php_info_print_table_row(2, "Registered serializer handlers", "none");
2972 }
2973
2974 php_info_print_table_end();
2975
2976 DISPLAY_INI_ENTRIES();
2977 }
2978 /* }}} */
2979
2980 static const zend_module_dep session_deps[] = { /* {{{ */
2981 ZEND_MOD_OPTIONAL("hash")
2982 ZEND_MOD_REQUIRED("spl")
2983 ZEND_MOD_END
2984 };
2985 /* }}} */
2986
2987 /* ************************
2988 * Upload hook handling *
2989 ************************ */
2990
early_find_sid_in(zval * dest,int where,php_session_rfc1867_progress * progress)2991 static bool early_find_sid_in(zval *dest, int where, php_session_rfc1867_progress *progress) /* {{{ */
2992 {
2993 zval *ppid;
2994
2995 if (Z_ISUNDEF(PG(http_globals)[where])) {
2996 return 0;
2997 }
2998
2999 if ((ppid = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[where]), PS(session_name), progress->sname_len))
3000 && Z_TYPE_P(ppid) == IS_STRING) {
3001 zval_ptr_dtor(dest);
3002 ZVAL_COPY_DEREF(dest, ppid);
3003 return 1;
3004 }
3005
3006 return 0;
3007 } /* }}} */
3008
php_session_rfc1867_early_find_sid(php_session_rfc1867_progress * progress)3009 static void php_session_rfc1867_early_find_sid(php_session_rfc1867_progress *progress) /* {{{ */
3010 {
3011
3012 if (PS(use_cookies)) {
3013 sapi_module.treat_data(PARSE_COOKIE, NULL, NULL);
3014 if (early_find_sid_in(&progress->sid, TRACK_VARS_COOKIE, progress)) {
3015 progress->apply_trans_sid = 0;
3016 return;
3017 }
3018 }
3019 if (PS(use_only_cookies)) {
3020 return;
3021 }
3022 sapi_module.treat_data(PARSE_GET, NULL, NULL);
3023 early_find_sid_in(&progress->sid, TRACK_VARS_GET, progress);
3024 } /* }}} */
3025
php_check_cancel_upload(php_session_rfc1867_progress * progress)3026 static bool php_check_cancel_upload(php_session_rfc1867_progress *progress) /* {{{ */
3027 {
3028 zval *progress_ary, *cancel_upload;
3029
3030 if ((progress_ary = zend_symtable_find(Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars))), progress->key.s)) == NULL) {
3031 return 0;
3032 }
3033 if (Z_TYPE_P(progress_ary) != IS_ARRAY) {
3034 return 0;
3035 }
3036 if ((cancel_upload = zend_hash_str_find(Z_ARRVAL_P(progress_ary), "cancel_upload", sizeof("cancel_upload") - 1)) == NULL) {
3037 return 0;
3038 }
3039 return Z_TYPE_P(cancel_upload) == IS_TRUE;
3040 } /* }}} */
3041
php_session_rfc1867_update(php_session_rfc1867_progress * progress,int force_update)3042 static void php_session_rfc1867_update(php_session_rfc1867_progress *progress, int force_update) /* {{{ */
3043 {
3044 if (!force_update) {
3045 if (Z_LVAL_P(progress->post_bytes_processed) < progress->next_update) {
3046 return;
3047 }
3048 #ifdef HAVE_GETTIMEOFDAY
3049 if (PS(rfc1867_min_freq) > 0.0) {
3050 struct timeval tv = {0};
3051 double dtv;
3052 gettimeofday(&tv, NULL);
3053 dtv = (double) tv.tv_sec + tv.tv_usec / 1000000.0;
3054 if (dtv < progress->next_update_time) {
3055 return;
3056 }
3057 progress->next_update_time = dtv + PS(rfc1867_min_freq);
3058 }
3059 #endif
3060 progress->next_update = Z_LVAL_P(progress->post_bytes_processed) + progress->update_step;
3061 }
3062
3063 php_session_initialize();
3064 PS(session_status) = php_session_active;
3065 IF_SESSION_VARS() {
3066 zval *sess_var = Z_REFVAL(PS(http_session_vars));
3067 SEPARATE_ARRAY(sess_var);
3068
3069 progress->cancel_upload |= php_check_cancel_upload(progress);
3070 Z_TRY_ADDREF(progress->data);
3071 zend_hash_update(Z_ARRVAL_P(sess_var), progress->key.s, &progress->data);
3072 }
3073 php_session_flush(1);
3074 } /* }}} */
3075
php_session_rfc1867_cleanup(php_session_rfc1867_progress * progress)3076 static void php_session_rfc1867_cleanup(php_session_rfc1867_progress *progress) /* {{{ */
3077 {
3078 php_session_initialize();
3079 PS(session_status) = php_session_active;
3080 IF_SESSION_VARS() {
3081 zval *sess_var = Z_REFVAL(PS(http_session_vars));
3082 SEPARATE_ARRAY(sess_var);
3083 zend_hash_del(Z_ARRVAL_P(sess_var), progress->key.s);
3084 }
3085 php_session_flush(1);
3086 } /* }}} */
3087
php_session_rfc1867_callback(unsigned int event,void * event_data,void ** extra)3088 static zend_result php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra) /* {{{ */
3089 {
3090 php_session_rfc1867_progress *progress;
3091 zend_result retval = SUCCESS;
3092
3093 if (php_session_rfc1867_orig_callback) {
3094 retval = php_session_rfc1867_orig_callback(event, event_data, extra);
3095 }
3096 if (!PS(rfc1867_enabled)) {
3097 return retval;
3098 }
3099
3100 progress = PS(rfc1867_progress);
3101
3102 switch(event) {
3103 case MULTIPART_EVENT_START: {
3104 multipart_event_start *data = (multipart_event_start *) event_data;
3105 progress = ecalloc(1, sizeof(php_session_rfc1867_progress));
3106 progress->content_length = data->content_length;
3107 progress->sname_len = strlen(PS(session_name));
3108 PS(rfc1867_progress) = progress;
3109 }
3110 break;
3111 case MULTIPART_EVENT_FORMDATA: {
3112 multipart_event_formdata *data = (multipart_event_formdata *) event_data;
3113 size_t value_len;
3114
3115 if (Z_TYPE(progress->sid) && progress->key.s) {
3116 break;
3117 }
3118
3119 /* orig callback may have modified *data->newlength */
3120 if (data->newlength) {
3121 value_len = *data->newlength;
3122 } else {
3123 value_len = data->length;
3124 }
3125
3126 if (data->name && data->value && value_len) {
3127 size_t name_len = strlen(data->name);
3128
3129 if (name_len == progress->sname_len && memcmp(data->name, PS(session_name), name_len) == 0) {
3130 zval_ptr_dtor(&progress->sid);
3131 ZVAL_STRINGL(&progress->sid, (*data->value), value_len);
3132 } else if (name_len == strlen(PS(rfc1867_name)) && memcmp(data->name, PS(rfc1867_name), name_len + 1) == 0) {
3133 smart_str_free(&progress->key);
3134 smart_str_appends(&progress->key, PS(rfc1867_prefix));
3135 smart_str_appendl(&progress->key, *data->value, value_len);
3136 smart_str_0(&progress->key);
3137
3138 progress->apply_trans_sid = APPLY_TRANS_SID;
3139 php_session_rfc1867_early_find_sid(progress);
3140 }
3141 }
3142 }
3143 break;
3144 case MULTIPART_EVENT_FILE_START: {
3145 multipart_event_file_start *data = (multipart_event_file_start *) event_data;
3146
3147 /* Do nothing when $_POST["PHP_SESSION_UPLOAD_PROGRESS"] is not set
3148 * or when we have no session id */
3149 if (!Z_TYPE(progress->sid) || !progress->key.s) {
3150 break;
3151 }
3152
3153 /* First FILE_START event, initializing data */
3154 if (Z_ISUNDEF(progress->data)) {
3155
3156 if (PS(rfc1867_freq) >= 0) {
3157 progress->update_step = PS(rfc1867_freq);
3158 } else if (PS(rfc1867_freq) < 0) { /* % of total size */
3159 progress->update_step = progress->content_length * -PS(rfc1867_freq) / 100;
3160 }
3161 progress->next_update = 0;
3162 progress->next_update_time = 0.0;
3163
3164 array_init(&progress->data);
3165 array_init(&progress->files);
3166
3167 add_assoc_long_ex(&progress->data, "start_time", sizeof("start_time") - 1, (zend_long)sapi_get_request_time());
3168 add_assoc_long_ex(&progress->data, "content_length", sizeof("content_length") - 1, progress->content_length);
3169 add_assoc_long_ex(&progress->data, "bytes_processed", sizeof("bytes_processed") - 1, data->post_bytes_processed);
3170 add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 0);
3171 add_assoc_zval_ex(&progress->data, "files", sizeof("files") - 1, &progress->files);
3172
3173 progress->post_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->data), "bytes_processed", sizeof("bytes_processed") - 1);
3174
3175 php_rinit_session(0);
3176 PS(id) = zend_string_init(Z_STRVAL(progress->sid), Z_STRLEN(progress->sid), 0);
3177 if (progress->apply_trans_sid) {
3178 /* Enable trans sid by modifying flags */
3179 PS(use_trans_sid) = 1;
3180 PS(use_only_cookies) = 0;
3181 }
3182 PS(send_cookie) = 0;
3183 }
3184
3185 array_init(&progress->current_file);
3186
3187 /* Each uploaded file has its own array. Trying to make it close to $_FILES entries. */
3188 add_assoc_string_ex(&progress->current_file, "field_name", sizeof("field_name") - 1, data->name);
3189 add_assoc_string_ex(&progress->current_file, "name", sizeof("name") - 1, *data->filename);
3190 add_assoc_null_ex(&progress->current_file, "tmp_name", sizeof("tmp_name") - 1);
3191 add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, 0);
3192
3193 add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1, 0);
3194 add_assoc_long_ex(&progress->current_file, "start_time", sizeof("start_time") - 1, (zend_long)time(NULL));
3195 add_assoc_long_ex(&progress->current_file, "bytes_processed", sizeof("bytes_processed") - 1, 0);
3196
3197 add_next_index_zval(&progress->files, &progress->current_file);
3198
3199 progress->current_file_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->current_file), "bytes_processed", sizeof("bytes_processed") - 1);
3200
3201 Z_LVAL_P(progress->current_file_bytes_processed) = data->post_bytes_processed;
3202 php_session_rfc1867_update(progress, 0);
3203 }
3204 break;
3205 case MULTIPART_EVENT_FILE_DATA: {
3206 multipart_event_file_data *data = (multipart_event_file_data *) event_data;
3207
3208 if (!Z_TYPE(progress->sid) || !progress->key.s) {
3209 break;
3210 }
3211
3212 Z_LVAL_P(progress->current_file_bytes_processed) = data->offset + data->length;
3213 Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
3214
3215 php_session_rfc1867_update(progress, 0);
3216 }
3217 break;
3218 case MULTIPART_EVENT_FILE_END: {
3219 multipart_event_file_end *data = (multipart_event_file_end *) event_data;
3220
3221 if (!Z_TYPE(progress->sid) || !progress->key.s) {
3222 break;
3223 }
3224
3225 if (data->temp_filename) {
3226 add_assoc_string_ex(&progress->current_file, "tmp_name", sizeof("tmp_name") - 1, data->temp_filename);
3227 }
3228
3229 add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, data->cancel_upload);
3230 add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1, 1);
3231
3232 Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
3233
3234 php_session_rfc1867_update(progress, 0);
3235 }
3236 break;
3237 case MULTIPART_EVENT_END: {
3238 multipart_event_end *data = (multipart_event_end *) event_data;
3239
3240 if (Z_TYPE(progress->sid) && progress->key.s) {
3241 if (PS(rfc1867_cleanup)) {
3242 php_session_rfc1867_cleanup(progress);
3243 } else {
3244 if (!Z_ISUNDEF(progress->data)) {
3245 SEPARATE_ARRAY(&progress->data);
3246 add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 1);
3247 Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
3248 php_session_rfc1867_update(progress, 1);
3249 }
3250 }
3251 php_rshutdown_session_globals();
3252 }
3253
3254 if (!Z_ISUNDEF(progress->data)) {
3255 zval_ptr_dtor(&progress->data);
3256 }
3257 zval_ptr_dtor(&progress->sid);
3258 smart_str_free(&progress->key);
3259 efree(progress);
3260 progress = NULL;
3261 PS(rfc1867_progress) = NULL;
3262 }
3263 break;
3264 }
3265
3266 if (progress && progress->cancel_upload) {
3267 return FAILURE;
3268 }
3269 return retval;
3270
3271 } /* }}} */
3272
3273 zend_module_entry session_module_entry = {
3274 STANDARD_MODULE_HEADER_EX,
3275 NULL,
3276 session_deps,
3277 "session",
3278 ext_functions,
3279 PHP_MINIT(session), PHP_MSHUTDOWN(session),
3280 PHP_RINIT(session), PHP_RSHUTDOWN(session),
3281 PHP_MINFO(session),
3282 PHP_SESSION_VERSION,
3283 PHP_MODULE_GLOBALS(ps),
3284 PHP_GINIT(ps),
3285 NULL,
3286 NULL,
3287 STANDARD_MODULE_PROPERTIES_EX
3288 };
3289
3290 #ifdef COMPILE_DL_SESSION
3291 #ifdef ZTS
3292 ZEND_TSRMLS_CACHE_DEFINE()
3293 #endif
3294 ZEND_GET_MODULE(session)
3295 #endif
3296