PageRenderTime 58ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/ext/session/session.c

https://github.com/php/php-src
C | 3207 lines | 2434 code | 492 blank | 281 comment | 628 complexity | 2879ea42affe4928cdd3f0e01349a846 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  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. #ifdef HAVE_CONFIG_H
  18. #include "config.h"
  19. #endif
  20. #include "php.h"
  21. #ifdef PHP_WIN32
  22. # include "win32/winutil.h"
  23. # include "win32/time.h"
  24. #else
  25. # include <sys/time.h>
  26. #endif
  27. #include <sys/stat.h>
  28. #include <fcntl.h>
  29. #include "php_ini.h"
  30. #include "SAPI.h"
  31. #include "rfc1867.h"
  32. #include "php_variables.h"
  33. #include "php_session.h"
  34. #include "session_arginfo.h"
  35. #include "ext/standard/php_random.h"
  36. #include "ext/standard/php_var.h"
  37. #include "ext/date/php_date.h"
  38. #include "ext/standard/php_lcg.h"
  39. #include "ext/standard/url_scanner_ex.h"
  40. #include "ext/standard/info.h"
  41. #include "zend_smart_str.h"
  42. #include "ext/standard/url.h"
  43. #include "ext/standard/basic_functions.h"
  44. #include "ext/standard/head.h"
  45. #include "mod_files.h"
  46. #include "mod_user.h"
  47. #ifdef HAVE_LIBMM
  48. #include "mod_mm.h"
  49. #endif
  50. PHPAPI ZEND_DECLARE_MODULE_GLOBALS(ps)
  51. static int php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra);
  52. static int (*php_session_rfc1867_orig_callback)(unsigned int event, void *event_data, void **extra);
  53. static void php_session_track_init(void);
  54. /* SessionHandler class */
  55. zend_class_entry *php_session_class_entry;
  56. /* SessionHandlerInterface */
  57. zend_class_entry *php_session_iface_entry;
  58. /* SessionIdInterface */
  59. zend_class_entry *php_session_id_iface_entry;
  60. /* SessionUpdateTimestampInterface */
  61. zend_class_entry *php_session_update_timestamp_iface_entry;
  62. #define PS_MAX_SID_LENGTH 256
  63. /* ***********
  64. * Helpers *
  65. *********** */
  66. #define IF_SESSION_VARS() \
  67. if (Z_ISREF_P(&PS(http_session_vars)) && Z_TYPE_P(Z_REFVAL(PS(http_session_vars))) == IS_ARRAY)
  68. #define SESSION_CHECK_ACTIVE_STATE \
  69. if (PS(session_status) == php_session_active) { \
  70. php_error_docref(NULL, E_WARNING, "Session ini settings cannot be changed when a session is active"); \
  71. return FAILURE; \
  72. }
  73. #define SESSION_CHECK_OUTPUT_STATE \
  74. if (SG(headers_sent) && stage != ZEND_INI_STAGE_DEACTIVATE) { \
  75. php_error_docref(NULL, E_WARNING, "Session ini settings cannot be changed after headers have already been sent"); \
  76. return FAILURE; \
  77. }
  78. #define APPLY_TRANS_SID (PS(use_trans_sid) && !PS(use_only_cookies))
  79. static int php_session_send_cookie(void);
  80. static int php_session_abort(void);
  81. /* Initialized in MINIT, readonly otherwise. */
  82. static int my_module_number = 0;
  83. /* Dispatched by RINIT and by php_session_destroy */
  84. static inline void php_rinit_session_globals(void) /* {{{ */
  85. {
  86. /* Do NOT init PS(mod_user_names) here! */
  87. /* TODO: These could be moved to MINIT and removed. These should be initialized by php_rshutdown_session_globals() always when execution is finished. */
  88. PS(id) = NULL;
  89. PS(session_status) = php_session_none;
  90. PS(in_save_handler) = 0;
  91. PS(set_handler) = 0;
  92. PS(mod_data) = NULL;
  93. PS(mod_user_is_open) = 0;
  94. PS(define_sid) = 1;
  95. PS(session_vars) = NULL;
  96. PS(module_number) = my_module_number;
  97. ZVAL_UNDEF(&PS(http_session_vars));
  98. }
  99. /* }}} */
  100. /* Dispatched by RSHUTDOWN and by php_session_destroy */
  101. static inline void php_rshutdown_session_globals(void) /* {{{ */
  102. {
  103. /* Do NOT destroy PS(mod_user_names) here! */
  104. if (!Z_ISUNDEF(PS(http_session_vars))) {
  105. zval_ptr_dtor(&PS(http_session_vars));
  106. ZVAL_UNDEF(&PS(http_session_vars));
  107. }
  108. if (PS(mod_data) || PS(mod_user_implemented)) {
  109. zend_try {
  110. PS(mod)->s_close(&PS(mod_data));
  111. } zend_end_try();
  112. }
  113. if (PS(id)) {
  114. zend_string_release_ex(PS(id), 0);
  115. PS(id) = NULL;
  116. }
  117. if (PS(session_vars)) {
  118. zend_string_release_ex(PS(session_vars), 0);
  119. PS(session_vars) = NULL;
  120. }
  121. /* User save handlers may end up directly here by misuse, bugs in user script, etc. */
  122. /* Set session status to prevent error while restoring save handler INI value. */
  123. PS(session_status) = php_session_none;
  124. }
  125. /* }}} */
  126. PHPAPI int php_session_destroy(void) /* {{{ */
  127. {
  128. int retval = SUCCESS;
  129. if (PS(session_status) != php_session_active) {
  130. php_error_docref(NULL, E_WARNING, "Trying to destroy uninitialized session");
  131. return FAILURE;
  132. }
  133. if (PS(id) && PS(mod)->s_destroy(&PS(mod_data), PS(id)) == FAILURE) {
  134. retval = FAILURE;
  135. if (!EG(exception)) {
  136. php_error_docref(NULL, E_WARNING, "Session object destruction failed");
  137. }
  138. }
  139. php_rshutdown_session_globals();
  140. php_rinit_session_globals();
  141. return retval;
  142. }
  143. /* }}} */
  144. PHPAPI void php_add_session_var(zend_string *name) /* {{{ */
  145. {
  146. IF_SESSION_VARS() {
  147. zval *sess_var = Z_REFVAL(PS(http_session_vars));
  148. SEPARATE_ARRAY(sess_var);
  149. if (!zend_hash_exists(Z_ARRVAL_P(sess_var), name)) {
  150. zval empty_var;
  151. ZVAL_NULL(&empty_var);
  152. zend_hash_update(Z_ARRVAL_P(sess_var), name, &empty_var);
  153. }
  154. }
  155. }
  156. /* }}} */
  157. PHPAPI zval* php_set_session_var(zend_string *name, zval *state_val, php_unserialize_data_t *var_hash) /* {{{ */
  158. {
  159. IF_SESSION_VARS() {
  160. zval *sess_var = Z_REFVAL(PS(http_session_vars));
  161. SEPARATE_ARRAY(sess_var);
  162. return zend_hash_update(Z_ARRVAL_P(sess_var), name, state_val);
  163. }
  164. return NULL;
  165. }
  166. /* }}} */
  167. PHPAPI zval* php_get_session_var(zend_string *name) /* {{{ */
  168. {
  169. IF_SESSION_VARS() {
  170. return zend_hash_find(Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars))), name);
  171. }
  172. return NULL;
  173. }
  174. /* }}} */
  175. static void php_session_track_init(void) /* {{{ */
  176. {
  177. zval session_vars;
  178. zend_string *var_name = zend_string_init("_SESSION", sizeof("_SESSION") - 1, 0);
  179. /* Unconditionally destroy existing array -- possible dirty data */
  180. zend_delete_global_variable(var_name);
  181. if (!Z_ISUNDEF(PS(http_session_vars))) {
  182. zval_ptr_dtor(&PS(http_session_vars));
  183. }
  184. array_init(&session_vars);
  185. ZVAL_NEW_REF(&PS(http_session_vars), &session_vars);
  186. Z_ADDREF_P(&PS(http_session_vars));
  187. zend_hash_update_ind(&EG(symbol_table), var_name, &PS(http_session_vars));
  188. zend_string_release_ex(var_name, 0);
  189. }
  190. /* }}} */
  191. static zend_string *php_session_encode(void) /* {{{ */
  192. {
  193. IF_SESSION_VARS() {
  194. if (!PS(serializer)) {
  195. php_error_docref(NULL, E_WARNING, "Unknown session.serialize_handler. Failed to encode session object");
  196. return NULL;
  197. }
  198. return PS(serializer)->encode();
  199. } else {
  200. php_error_docref(NULL, E_WARNING, "Cannot encode non-existent session");
  201. }
  202. return NULL;
  203. }
  204. /* }}} */
  205. static int php_session_decode(zend_string *data) /* {{{ */
  206. {
  207. if (!PS(serializer)) {
  208. php_error_docref(NULL, E_WARNING, "Unknown session.serialize_handler. Failed to decode session object");
  209. return FAILURE;
  210. }
  211. if (PS(serializer)->decode(ZSTR_VAL(data), ZSTR_LEN(data)) == FAILURE) {
  212. php_session_destroy();
  213. php_session_track_init();
  214. php_error_docref(NULL, E_WARNING, "Failed to decode session object. Session has been destroyed");
  215. return FAILURE;
  216. }
  217. return SUCCESS;
  218. }
  219. /* }}} */
  220. /*
  221. * Note that we cannot use the BASE64 alphabet here, because
  222. * it contains "/" and "+": both are unacceptable for simple inclusion
  223. * into URLs.
  224. */
  225. static const char hexconvtab[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-";
  226. static void bin_to_readable(unsigned char *in, size_t inlen, char *out, size_t outlen, char nbits) /* {{{ */
  227. {
  228. unsigned char *p, *q;
  229. unsigned short w;
  230. int mask;
  231. int have;
  232. p = (unsigned char *)in;
  233. q = (unsigned char *)in + inlen;
  234. w = 0;
  235. have = 0;
  236. mask = (1 << nbits) - 1;
  237. while (outlen--) {
  238. if (have < nbits) {
  239. if (p < q) {
  240. w |= *p++ << have;
  241. have += 8;
  242. } else {
  243. /* Should never happen. Input must be large enough. */
  244. ZEND_UNREACHABLE();
  245. break;
  246. }
  247. }
  248. /* consume nbits */
  249. *out++ = hexconvtab[w & mask];
  250. w >>= nbits;
  251. have -= nbits;
  252. }
  253. *out = '\0';
  254. }
  255. /* }}} */
  256. #define PS_EXTRA_RAND_BYTES 60
  257. PHPAPI zend_string *php_session_create_id(PS_CREATE_SID_ARGS) /* {{{ */
  258. {
  259. unsigned char rbuf[PS_MAX_SID_LENGTH + PS_EXTRA_RAND_BYTES];
  260. zend_string *outid;
  261. /* It would be enough to read ceil(sid_length * sid_bits_per_character / 8) bytes here.
  262. * We read sid_length bytes instead for simplicity. */
  263. /* Read additional PS_EXTRA_RAND_BYTES just in case CSPRNG is not safe enough */
  264. if (php_random_bytes_throw(rbuf, PS(sid_length) + PS_EXTRA_RAND_BYTES) == FAILURE) {
  265. return NULL;
  266. }
  267. outid = zend_string_alloc(PS(sid_length), 0);
  268. bin_to_readable(
  269. rbuf, PS(sid_length),
  270. ZSTR_VAL(outid), ZSTR_LEN(outid),
  271. (char)PS(sid_bits_per_character));
  272. return outid;
  273. }
  274. /* }}} */
  275. /* Default session id char validation function allowed by ps_modules.
  276. * If you change the logic here, please also update the error message in
  277. * ps_modules appropriately */
  278. PHPAPI int php_session_valid_key(const char *key) /* {{{ */
  279. {
  280. size_t len;
  281. const char *p;
  282. char c;
  283. int ret = SUCCESS;
  284. for (p = key; (c = *p); p++) {
  285. /* valid characters are a..z,A..Z,0..9 */
  286. if (!((c >= 'a' && c <= 'z')
  287. || (c >= 'A' && c <= 'Z')
  288. || (c >= '0' && c <= '9')
  289. || c == ','
  290. || c == '-')) {
  291. ret = FAILURE;
  292. break;
  293. }
  294. }
  295. len = p - key;
  296. /* Somewhat arbitrary length limit here, but should be way more than
  297. anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */
  298. if (len == 0 || len > PS_MAX_SID_LENGTH) {
  299. ret = FAILURE;
  300. }
  301. return ret;
  302. }
  303. /* }}} */
  304. static zend_long php_session_gc(bool immediate) /* {{{ */
  305. {
  306. int nrand;
  307. zend_long num = -1;
  308. /* GC must be done before reading session data. */
  309. if ((PS(mod_data) || PS(mod_user_implemented))) {
  310. if (immediate) {
  311. PS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &num);
  312. return num;
  313. }
  314. nrand = (zend_long) ((float) PS(gc_divisor) * php_combined_lcg());
  315. if (PS(gc_probability) > 0 && nrand < PS(gc_probability)) {
  316. PS(mod)->s_gc(&PS(mod_data), PS(gc_maxlifetime), &num);
  317. }
  318. }
  319. return num;
  320. } /* }}} */
  321. static int php_session_initialize(void) /* {{{ */
  322. {
  323. zend_string *val = NULL;
  324. PS(session_status) = php_session_active;
  325. if (!PS(mod)) {
  326. PS(session_status) = php_session_disabled;
  327. php_error_docref(NULL, E_WARNING, "No storage module chosen - failed to initialize session");
  328. return FAILURE;
  329. }
  330. /* Open session handler first */
  331. if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name)) == FAILURE
  332. /* || PS(mod_data) == NULL */ /* FIXME: open must set valid PS(mod_data) with success */
  333. ) {
  334. php_session_abort();
  335. if (!EG(exception)) {
  336. php_error_docref(NULL, E_WARNING, "Failed to initialize storage module: %s (path: %s)", PS(mod)->s_name, PS(save_path));
  337. }
  338. return FAILURE;
  339. }
  340. /* If there is no ID, use session module to create one */
  341. if (!PS(id) || !ZSTR_VAL(PS(id))[0]) {
  342. if (PS(id)) {
  343. zend_string_release_ex(PS(id), 0);
  344. }
  345. PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
  346. if (!PS(id)) {
  347. php_session_abort();
  348. if (!EG(exception)) {
  349. zend_throw_error(NULL, "Failed to create session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
  350. }
  351. return FAILURE;
  352. }
  353. if (PS(use_cookies)) {
  354. PS(send_cookie) = 1;
  355. }
  356. } else if (PS(use_strict_mode) && PS(mod)->s_validate_sid &&
  357. PS(mod)->s_validate_sid(&PS(mod_data), PS(id)) == FAILURE
  358. ) {
  359. if (PS(id)) {
  360. zend_string_release_ex(PS(id), 0);
  361. }
  362. PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
  363. if (!PS(id)) {
  364. PS(id) = php_session_create_id(NULL);
  365. }
  366. if (PS(use_cookies)) {
  367. PS(send_cookie) = 1;
  368. }
  369. }
  370. if (php_session_reset_id() == FAILURE) {
  371. php_session_abort();
  372. return FAILURE;
  373. }
  374. /* Read data */
  375. php_session_track_init();
  376. if (PS(mod)->s_read(&PS(mod_data), PS(id), &val, PS(gc_maxlifetime)) == FAILURE) {
  377. php_session_abort();
  378. /* FYI: Some broken save handlers return FAILURE for non-existent session ID, this is incorrect */
  379. if (!EG(exception)) {
  380. php_error_docref(NULL, E_WARNING, "Failed to read session data: %s (path: %s)", PS(mod)->s_name, PS(save_path));
  381. }
  382. return FAILURE;
  383. }
  384. /* GC must be done after read */
  385. php_session_gc(0);
  386. if (PS(session_vars)) {
  387. zend_string_release_ex(PS(session_vars), 0);
  388. PS(session_vars) = NULL;
  389. }
  390. if (val) {
  391. if (PS(lazy_write)) {
  392. PS(session_vars) = zend_string_copy(val);
  393. }
  394. php_session_decode(val);
  395. zend_string_release_ex(val, 0);
  396. }
  397. return SUCCESS;
  398. }
  399. /* }}} */
  400. static void php_session_save_current_state(int write) /* {{{ */
  401. {
  402. int ret = FAILURE;
  403. if (write) {
  404. IF_SESSION_VARS() {
  405. if (PS(mod_data) || PS(mod_user_implemented)) {
  406. zend_string *val;
  407. val = php_session_encode();
  408. if (val) {
  409. if (PS(lazy_write) && PS(session_vars)
  410. && PS(mod)->s_update_timestamp
  411. && PS(mod)->s_update_timestamp != php_session_update_timestamp
  412. && zend_string_equals(val, PS(session_vars))
  413. ) {
  414. ret = PS(mod)->s_update_timestamp(&PS(mod_data), PS(id), val, PS(gc_maxlifetime));
  415. } else {
  416. ret = PS(mod)->s_write(&PS(mod_data), PS(id), val, PS(gc_maxlifetime));
  417. }
  418. zend_string_release_ex(val, 0);
  419. } else {
  420. ret = PS(mod)->s_write(&PS(mod_data), PS(id), ZSTR_EMPTY_ALLOC(), PS(gc_maxlifetime));
  421. }
  422. }
  423. if ((ret == FAILURE) && !EG(exception)) {
  424. if (!PS(mod_user_implemented)) {
  425. php_error_docref(NULL, E_WARNING, "Failed to write session data (%s). Please "
  426. "verify that the current setting of session.save_path "
  427. "is correct (%s)",
  428. PS(mod)->s_name,
  429. PS(save_path));
  430. } else {
  431. php_error_docref(NULL, E_WARNING, "Failed to write session data using user "
  432. "defined save handler. (session.save_path: %s)", PS(save_path));
  433. }
  434. }
  435. }
  436. }
  437. if (PS(mod_data) || PS(mod_user_implemented)) {
  438. PS(mod)->s_close(&PS(mod_data));
  439. }
  440. }
  441. /* }}} */
  442. static void php_session_normalize_vars(void) /* {{{ */
  443. {
  444. PS_ENCODE_VARS;
  445. IF_SESSION_VARS() {
  446. PS_ENCODE_LOOP(
  447. if (Z_TYPE_P(struc) == IS_PTR) {
  448. zval *zv = (zval *)Z_PTR_P(struc);
  449. ZVAL_COPY_VALUE(struc, zv);
  450. ZVAL_UNDEF(zv);
  451. }
  452. );
  453. }
  454. }
  455. /* }}} */
  456. /* *************************
  457. * INI Settings/Handlers *
  458. ************************* */
  459. static PHP_INI_MH(OnUpdateSaveHandler) /* {{{ */
  460. {
  461. const ps_module *tmp;
  462. int err_type = E_ERROR;
  463. SESSION_CHECK_ACTIVE_STATE;
  464. SESSION_CHECK_OUTPUT_STATE;
  465. tmp = _php_find_ps_module(ZSTR_VAL(new_value));
  466. if (stage == ZEND_INI_STAGE_RUNTIME) {
  467. err_type = E_WARNING;
  468. }
  469. if (PG(modules_activated) && !tmp) {
  470. /* Do not output error when restoring ini options. */
  471. if (stage != ZEND_INI_STAGE_DEACTIVATE) {
  472. php_error_docref(NULL, err_type, "Session save handler \"%s\" cannot be found", ZSTR_VAL(new_value));
  473. }
  474. return FAILURE;
  475. }
  476. /* "user" save handler should not be set by user */
  477. if (!PS(set_handler) && tmp == ps_user_ptr) {
  478. php_error_docref(NULL, err_type, "Session save handler \"user\" cannot be set by ini_set()");
  479. return FAILURE;
  480. }
  481. PS(default_mod) = PS(mod);
  482. PS(mod) = tmp;
  483. return SUCCESS;
  484. }
  485. /* }}} */
  486. static PHP_INI_MH(OnUpdateSerializer) /* {{{ */
  487. {
  488. const ps_serializer *tmp;
  489. SESSION_CHECK_ACTIVE_STATE;
  490. SESSION_CHECK_OUTPUT_STATE;
  491. tmp = _php_find_ps_serializer(ZSTR_VAL(new_value));
  492. if (PG(modules_activated) && !tmp) {
  493. int err_type;
  494. if (stage == ZEND_INI_STAGE_RUNTIME) {
  495. err_type = E_WARNING;
  496. } else {
  497. err_type = E_ERROR;
  498. }
  499. /* Do not output error when restoring ini options. */
  500. if (stage != ZEND_INI_STAGE_DEACTIVATE) {
  501. php_error_docref(NULL, err_type, "Serialization handler \"%s\" cannot be found", ZSTR_VAL(new_value));
  502. }
  503. return FAILURE;
  504. }
  505. PS(serializer) = tmp;
  506. return SUCCESS;
  507. }
  508. /* }}} */
  509. static PHP_INI_MH(OnUpdateTransSid) /* {{{ */
  510. {
  511. SESSION_CHECK_ACTIVE_STATE;
  512. SESSION_CHECK_OUTPUT_STATE;
  513. if (zend_string_equals_literal_ci(new_value, "on")) {
  514. PS(use_trans_sid) = (bool) 1;
  515. } else {
  516. PS(use_trans_sid) = (bool) atoi(ZSTR_VAL(new_value));
  517. }
  518. return SUCCESS;
  519. }
  520. /* }}} */
  521. static PHP_INI_MH(OnUpdateSaveDir) /* {{{ */
  522. {
  523. SESSION_CHECK_ACTIVE_STATE;
  524. SESSION_CHECK_OUTPUT_STATE;
  525. /* Only do the safemode/open_basedir check at runtime */
  526. if (stage == PHP_INI_STAGE_RUNTIME || stage == PHP_INI_STAGE_HTACCESS) {
  527. char *p;
  528. if (memchr(ZSTR_VAL(new_value), '\0', ZSTR_LEN(new_value)) != NULL) {
  529. return FAILURE;
  530. }
  531. /* we do not use zend_memrchr() since path can contain ; itself */
  532. if ((p = strchr(ZSTR_VAL(new_value), ';'))) {
  533. char *p2;
  534. p++;
  535. if ((p2 = strchr(p, ';'))) {
  536. p = p2 + 1;
  537. }
  538. } else {
  539. p = ZSTR_VAL(new_value);
  540. }
  541. if (PG(open_basedir) && *p && php_check_open_basedir(p)) {
  542. return FAILURE;
  543. }
  544. }
  545. return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  546. }
  547. /* }}} */
  548. static PHP_INI_MH(OnUpdateName) /* {{{ */
  549. {
  550. SESSION_CHECK_ACTIVE_STATE;
  551. SESSION_CHECK_OUTPUT_STATE;
  552. /* Numeric session.name won't work at all */
  553. if ((!ZSTR_LEN(new_value) || is_numeric_string(ZSTR_VAL(new_value), ZSTR_LEN(new_value), NULL, NULL, 0))) {
  554. int err_type;
  555. if (stage == ZEND_INI_STAGE_RUNTIME || stage == ZEND_INI_STAGE_ACTIVATE || stage == ZEND_INI_STAGE_STARTUP) {
  556. err_type = E_WARNING;
  557. } else {
  558. err_type = E_ERROR;
  559. }
  560. /* Do not output error when restoring ini options. */
  561. if (stage != ZEND_INI_STAGE_DEACTIVATE) {
  562. php_error_docref(NULL, err_type, "session.name \"%s\" cannot be numeric or empty", ZSTR_VAL(new_value));
  563. }
  564. return FAILURE;
  565. }
  566. return OnUpdateStringUnempty(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  567. }
  568. /* }}} */
  569. static PHP_INI_MH(OnUpdateCookieLifetime) /* {{{ */
  570. {
  571. SESSION_CHECK_ACTIVE_STATE;
  572. SESSION_CHECK_OUTPUT_STATE;
  573. if (atol(ZSTR_VAL(new_value)) < 0) {
  574. php_error_docref(NULL, E_WARNING, "CookieLifetime cannot be negative");
  575. return FAILURE;
  576. }
  577. return OnUpdateLongGEZero(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  578. }
  579. /* }}} */
  580. static PHP_INI_MH(OnUpdateSessionLong) /* {{{ */
  581. {
  582. SESSION_CHECK_ACTIVE_STATE;
  583. SESSION_CHECK_OUTPUT_STATE;
  584. return OnUpdateLong(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  585. }
  586. /* }}} */
  587. static PHP_INI_MH(OnUpdateSessionString) /* {{{ */
  588. {
  589. SESSION_CHECK_ACTIVE_STATE;
  590. SESSION_CHECK_OUTPUT_STATE;
  591. return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  592. }
  593. /* }}} */
  594. static PHP_INI_MH(OnUpdateSessionBool) /* {{{ */
  595. {
  596. SESSION_CHECK_OUTPUT_STATE;
  597. SESSION_CHECK_ACTIVE_STATE;
  598. return OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  599. }
  600. /* }}} */
  601. static PHP_INI_MH(OnUpdateSidLength) /* {{{ */
  602. {
  603. zend_long val;
  604. char *endptr = NULL;
  605. SESSION_CHECK_OUTPUT_STATE;
  606. SESSION_CHECK_ACTIVE_STATE;
  607. val = ZEND_STRTOL(ZSTR_VAL(new_value), &endptr, 10);
  608. if (endptr && (*endptr == '\0')
  609. && val >= 22 && val <= PS_MAX_SID_LENGTH) {
  610. /* Numeric value */
  611. PS(sid_length) = val;
  612. return SUCCESS;
  613. }
  614. php_error_docref(NULL, E_WARNING, "session.configuration \"session.sid_length\" must be between 22 and 256");
  615. return FAILURE;
  616. }
  617. /* }}} */
  618. static PHP_INI_MH(OnUpdateSidBits) /* {{{ */
  619. {
  620. zend_long val;
  621. char *endptr = NULL;
  622. SESSION_CHECK_OUTPUT_STATE;
  623. SESSION_CHECK_ACTIVE_STATE;
  624. val = ZEND_STRTOL(ZSTR_VAL(new_value), &endptr, 10);
  625. if (endptr && (*endptr == '\0')
  626. && val >= 4 && val <=6) {
  627. /* Numeric value */
  628. PS(sid_bits_per_character) = val;
  629. return SUCCESS;
  630. }
  631. php_error_docref(NULL, E_WARNING, "session.configuration \"session.sid_bits_per_character\" must be between 4 and 6");
  632. return FAILURE;
  633. }
  634. /* }}} */
  635. static PHP_INI_MH(OnUpdateLazyWrite) /* {{{ */
  636. {
  637. SESSION_CHECK_ACTIVE_STATE;
  638. SESSION_CHECK_OUTPUT_STATE;
  639. return OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
  640. }
  641. /* }}} */
  642. static PHP_INI_MH(OnUpdateRfc1867Freq) /* {{{ */
  643. {
  644. int tmp = ZEND_ATOL(ZSTR_VAL(new_value));
  645. if(tmp < 0) {
  646. php_error_docref(NULL, E_WARNING, "session.upload_progress.freq must be greater than or equal to 0");
  647. return FAILURE;
  648. }
  649. if(ZSTR_LEN(new_value) > 0 && ZSTR_VAL(new_value)[ZSTR_LEN(new_value)-1] == '%') {
  650. if(tmp > 100) {
  651. php_error_docref(NULL, E_WARNING, "session.upload_progress.freq must be less than or equal to 100%%");
  652. return FAILURE;
  653. }
  654. PS(rfc1867_freq) = -tmp;
  655. } else {
  656. PS(rfc1867_freq) = tmp;
  657. }
  658. return SUCCESS;
  659. } /* }}} */
  660. /* {{{ PHP_INI */
  661. PHP_INI_BEGIN()
  662. STD_PHP_INI_ENTRY("session.save_path", "", PHP_INI_ALL, OnUpdateSaveDir, save_path, php_ps_globals, ps_globals)
  663. STD_PHP_INI_ENTRY("session.name", "PHPSESSID", PHP_INI_ALL, OnUpdateName, session_name, php_ps_globals, ps_globals)
  664. PHP_INI_ENTRY("session.save_handler", "files", PHP_INI_ALL, OnUpdateSaveHandler)
  665. STD_PHP_INI_BOOLEAN("session.auto_start", "0", PHP_INI_PERDIR, OnUpdateBool, auto_start, php_ps_globals, ps_globals)
  666. STD_PHP_INI_ENTRY("session.gc_probability", "1", PHP_INI_ALL, OnUpdateSessionLong, gc_probability, php_ps_globals, ps_globals)
  667. STD_PHP_INI_ENTRY("session.gc_divisor", "100", PHP_INI_ALL, OnUpdateSessionLong, gc_divisor, php_ps_globals, ps_globals)
  668. STD_PHP_INI_ENTRY("session.gc_maxlifetime", "1440", PHP_INI_ALL, OnUpdateSessionLong, gc_maxlifetime, php_ps_globals, ps_globals)
  669. PHP_INI_ENTRY("session.serialize_handler", "php", PHP_INI_ALL, OnUpdateSerializer)
  670. STD_PHP_INI_ENTRY("session.cookie_lifetime", "0", PHP_INI_ALL, OnUpdateCookieLifetime,cookie_lifetime, php_ps_globals, ps_globals)
  671. STD_PHP_INI_ENTRY("session.cookie_path", "/", PHP_INI_ALL, OnUpdateSessionString, cookie_path, php_ps_globals, ps_globals)
  672. STD_PHP_INI_ENTRY("session.cookie_domain", "", PHP_INI_ALL, OnUpdateSessionString, cookie_domain, php_ps_globals, ps_globals)
  673. STD_PHP_INI_ENTRY("session.cookie_secure", "0", PHP_INI_ALL, OnUpdateSessionBool, cookie_secure, php_ps_globals, ps_globals)
  674. STD_PHP_INI_ENTRY("session.cookie_httponly", "0", PHP_INI_ALL, OnUpdateSessionBool, cookie_httponly, php_ps_globals, ps_globals)
  675. STD_PHP_INI_ENTRY("session.cookie_samesite", "", PHP_INI_ALL, OnUpdateString, cookie_samesite, php_ps_globals, ps_globals)
  676. STD_PHP_INI_ENTRY("session.use_cookies", "1", PHP_INI_ALL, OnUpdateSessionBool, use_cookies, php_ps_globals, ps_globals)
  677. STD_PHP_INI_ENTRY("session.use_only_cookies", "1", PHP_INI_ALL, OnUpdateSessionBool, use_only_cookies, php_ps_globals, ps_globals)
  678. STD_PHP_INI_ENTRY("session.use_strict_mode", "0", PHP_INI_ALL, OnUpdateSessionBool, use_strict_mode, php_ps_globals, ps_globals)
  679. STD_PHP_INI_ENTRY("session.referer_check", "", PHP_INI_ALL, OnUpdateSessionString, extern_referer_chk, php_ps_globals, ps_globals)
  680. STD_PHP_INI_ENTRY("session.cache_limiter", "nocache", PHP_INI_ALL, OnUpdateSessionString, cache_limiter, php_ps_globals, ps_globals)
  681. STD_PHP_INI_ENTRY("session.cache_expire", "180", PHP_INI_ALL, OnUpdateSessionLong, cache_expire, php_ps_globals, ps_globals)
  682. PHP_INI_ENTRY("session.use_trans_sid", "0", PHP_INI_ALL, OnUpdateTransSid)
  683. PHP_INI_ENTRY("session.sid_length", "32", PHP_INI_ALL, OnUpdateSidLength)
  684. PHP_INI_ENTRY("session.sid_bits_per_character", "4", PHP_INI_ALL, OnUpdateSidBits)
  685. STD_PHP_INI_BOOLEAN("session.lazy_write", "1", PHP_INI_ALL, OnUpdateLazyWrite, lazy_write, php_ps_globals, ps_globals)
  686. /* Upload progress */
  687. STD_PHP_INI_BOOLEAN("session.upload_progress.enabled",
  688. "1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_enabled, php_ps_globals, ps_globals)
  689. STD_PHP_INI_BOOLEAN("session.upload_progress.cleanup",
  690. "1", ZEND_INI_PERDIR, OnUpdateBool, rfc1867_cleanup, php_ps_globals, ps_globals)
  691. STD_PHP_INI_ENTRY("session.upload_progress.prefix",
  692. "upload_progress_", ZEND_INI_PERDIR, OnUpdateString, rfc1867_prefix, php_ps_globals, ps_globals)
  693. STD_PHP_INI_ENTRY("session.upload_progress.name",
  694. "PHP_SESSION_UPLOAD_PROGRESS", ZEND_INI_PERDIR, OnUpdateString, rfc1867_name, php_ps_globals, ps_globals)
  695. STD_PHP_INI_ENTRY("session.upload_progress.freq", "1%", ZEND_INI_PERDIR, OnUpdateRfc1867Freq, rfc1867_freq, php_ps_globals, ps_globals)
  696. STD_PHP_INI_ENTRY("session.upload_progress.min_freq",
  697. "1", ZEND_INI_PERDIR, OnUpdateReal, rfc1867_min_freq,php_ps_globals, ps_globals)
  698. /* Commented out until future discussion */
  699. /* PHP_INI_ENTRY("session.encode_sources", "globals,track", PHP_INI_ALL, NULL) */
  700. PHP_INI_END()
  701. /* }}} */
  702. /* ***************
  703. * Serializers *
  704. *************** */
  705. PS_SERIALIZER_ENCODE_FUNC(php_serialize) /* {{{ */
  706. {
  707. smart_str buf = {0};
  708. php_serialize_data_t var_hash;
  709. IF_SESSION_VARS() {
  710. PHP_VAR_SERIALIZE_INIT(var_hash);
  711. php_var_serialize(&buf, Z_REFVAL(PS(http_session_vars)), &var_hash);
  712. PHP_VAR_SERIALIZE_DESTROY(var_hash);
  713. }
  714. return buf.s;
  715. }
  716. /* }}} */
  717. PS_SERIALIZER_DECODE_FUNC(php_serialize) /* {{{ */
  718. {
  719. const char *endptr = val + vallen;
  720. zval session_vars;
  721. php_unserialize_data_t var_hash;
  722. int result;
  723. zend_string *var_name = zend_string_init("_SESSION", sizeof("_SESSION") - 1, 0);
  724. ZVAL_NULL(&session_vars);
  725. PHP_VAR_UNSERIALIZE_INIT(var_hash);
  726. result = php_var_unserialize(
  727. &session_vars, (const unsigned char **)&val, (const unsigned char *)endptr, &var_hash);
  728. PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
  729. if (!result) {
  730. zval_ptr_dtor(&session_vars);
  731. ZVAL_NULL(&session_vars);
  732. }
  733. if (!Z_ISUNDEF(PS(http_session_vars))) {
  734. zval_ptr_dtor(&PS(http_session_vars));
  735. }
  736. if (Z_TYPE(session_vars) == IS_NULL) {
  737. array_init(&session_vars);
  738. }
  739. ZVAL_NEW_REF(&PS(http_session_vars), &session_vars);
  740. Z_ADDREF_P(&PS(http_session_vars));
  741. zend_hash_update_ind(&EG(symbol_table), var_name, &PS(http_session_vars));
  742. zend_string_release_ex(var_name, 0);
  743. return result || !vallen ? SUCCESS : FAILURE;
  744. }
  745. /* }}} */
  746. #define PS_BIN_NR_OF_BITS 8
  747. #define PS_BIN_UNDEF (1<<(PS_BIN_NR_OF_BITS-1))
  748. #define PS_BIN_MAX (PS_BIN_UNDEF-1)
  749. PS_SERIALIZER_ENCODE_FUNC(php_binary) /* {{{ */
  750. {
  751. smart_str buf = {0};
  752. php_serialize_data_t var_hash;
  753. PS_ENCODE_VARS;
  754. PHP_VAR_SERIALIZE_INIT(var_hash);
  755. PS_ENCODE_LOOP(
  756. if (ZSTR_LEN(key) > PS_BIN_MAX) continue;
  757. smart_str_appendc(&buf, (unsigned char)ZSTR_LEN(key));
  758. smart_str_appendl(&buf, ZSTR_VAL(key), ZSTR_LEN(key));
  759. php_var_serialize(&buf, struc, &var_hash);
  760. );
  761. smart_str_0(&buf);
  762. PHP_VAR_SERIALIZE_DESTROY(var_hash);
  763. return buf.s;
  764. }
  765. /* }}} */
  766. PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */
  767. {
  768. const char *p;
  769. const char *endptr = val + vallen;
  770. int namelen;
  771. zend_string *name;
  772. php_unserialize_data_t var_hash;
  773. zval *current, rv;
  774. PHP_VAR_UNSERIALIZE_INIT(var_hash);
  775. for (p = val; p < endptr; ) {
  776. namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF);
  777. if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) {
  778. PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
  779. return FAILURE;
  780. }
  781. name = zend_string_init(p + 1, namelen, 0);
  782. p += namelen + 1;
  783. current = var_tmp_var(&var_hash);
  784. if (php_var_unserialize(current, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash)) {
  785. ZVAL_PTR(&rv, current);
  786. php_set_session_var(name, &rv, &var_hash);
  787. } else {
  788. zend_string_release_ex(name, 0);
  789. php_session_normalize_vars();
  790. PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
  791. return FAILURE;
  792. }
  793. zend_string_release_ex(name, 0);
  794. }
  795. php_session_normalize_vars();
  796. PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
  797. return SUCCESS;
  798. }
  799. /* }}} */
  800. #define PS_DELIMITER '|'
  801. PS_SERIALIZER_ENCODE_FUNC(php) /* {{{ */
  802. {
  803. smart_str buf = {0};
  804. php_serialize_data_t var_hash;
  805. PS_ENCODE_VARS;
  806. PHP_VAR_SERIALIZE_INIT(var_hash);
  807. PS_ENCODE_LOOP(
  808. smart_str_appendl(&buf, ZSTR_VAL(key), ZSTR_LEN(key));
  809. if (memchr(ZSTR_VAL(key), PS_DELIMITER, ZSTR_LEN(key))) {
  810. PHP_VAR_SERIALIZE_DESTROY(var_hash);
  811. smart_str_free(&buf);
  812. return NULL;
  813. }
  814. smart_str_appendc(&buf, PS_DELIMITER);
  815. php_var_serialize(&buf, struc, &var_hash);
  816. );
  817. smart_str_0(&buf);
  818. PHP_VAR_SERIALIZE_DESTROY(var_hash);
  819. return buf.s;
  820. }
  821. /* }}} */
  822. PS_SERIALIZER_DECODE_FUNC(php) /* {{{ */
  823. {
  824. const char *p, *q;
  825. const char *endptr = val + vallen;
  826. ptrdiff_t namelen;
  827. zend_string *name;
  828. int retval = SUCCESS;
  829. php_unserialize_data_t var_hash;
  830. zval *current, rv;
  831. PHP_VAR_UNSERIALIZE_INIT(var_hash);
  832. p = val;
  833. while (p < endptr) {
  834. q = p;
  835. while (*q != PS_DELIMITER) {
  836. if (++q >= endptr) {
  837. retval = FAILURE;
  838. goto break_outer_loop;
  839. }
  840. }
  841. namelen = q - p;
  842. name = zend_string_init(p, namelen, 0);
  843. q++;
  844. current = var_tmp_var(&var_hash);
  845. if (php_var_unserialize(current, (const unsigned char **)&q, (const unsigned char *)endptr, &var_hash)) {
  846. ZVAL_PTR(&rv, current);
  847. php_set_session_var(name, &rv, &var_hash);
  848. } else {
  849. zend_string_release_ex(name, 0);
  850. retval = FAILURE;
  851. goto break_outer_loop;
  852. }
  853. zend_string_release_ex(name, 0);
  854. p = q;
  855. }
  856. break_outer_loop:
  857. php_session_normalize_vars();
  858. PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
  859. return retval;
  860. }
  861. /* }}} */
  862. #define MAX_SERIALIZERS 32
  863. #define PREDEFINED_SERIALIZERS 3
  864. static ps_serializer ps_serializers[MAX_SERIALIZERS + 1] = {
  865. PS_SERIALIZER_ENTRY(php_serialize),
  866. PS_SERIALIZER_ENTRY(php),
  867. PS_SERIALIZER_ENTRY(php_binary)
  868. };
  869. PHPAPI int php_session_register_serializer(const char *name, zend_string *(*encode)(PS_SERIALIZER_ENCODE_ARGS), int (*decode)(PS_SERIALIZER_DECODE_ARGS)) /* {{{ */
  870. {
  871. int ret = FAILURE;
  872. int i;
  873. for (i = 0; i < MAX_SERIALIZERS; i++) {
  874. if (ps_serializers[i].name == NULL) {
  875. ps_serializers[i].name = name;
  876. ps_serializers[i].encode = encode;
  877. ps_serializers[i].decode = decode;
  878. ps_serializers[i + 1].name = NULL;
  879. ret = SUCCESS;
  880. break;
  881. }
  882. }
  883. return ret;
  884. }
  885. /* }}} */
  886. /* *******************
  887. * Storage Modules *
  888. ******************* */
  889. #define MAX_MODULES 32
  890. #define PREDEFINED_MODULES 2
  891. static const ps_module *ps_modules[MAX_MODULES + 1] = {
  892. ps_files_ptr,
  893. ps_user_ptr
  894. };
  895. PHPAPI int php_session_register_module(const ps_module *ptr) /* {{{ */
  896. {
  897. int ret = FAILURE;
  898. int i;
  899. for (i = 0; i < MAX_MODULES; i++) {
  900. if (!ps_modules[i]) {
  901. ps_modules[i] = ptr;
  902. ret = SUCCESS;
  903. break;
  904. }
  905. }
  906. return ret;
  907. }
  908. /* }}} */
  909. /* Dummy PS module function */
  910. PHPAPI int php_session_validate_sid(PS_VALIDATE_SID_ARGS) {
  911. return SUCCESS;
  912. }
  913. /* Dummy PS module function */
  914. PHPAPI int php_session_update_timestamp(PS_UPDATE_TIMESTAMP_ARGS) {
  915. return SUCCESS;
  916. }
  917. /* ******************
  918. * Cache Limiters *
  919. ****************** */
  920. typedef struct {
  921. char *name;
  922. void (*func)(void);
  923. } php_session_cache_limiter_t;
  924. #define CACHE_LIMITER(name) _php_cache_limiter_##name
  925. #define CACHE_LIMITER_FUNC(name) static void CACHE_LIMITER(name)(void)
  926. #define CACHE_LIMITER_ENTRY(name) { #name, CACHE_LIMITER(name) },
  927. #define ADD_HEADER(a) sapi_add_header(a, strlen(a), 1);
  928. #define MAX_STR 512
  929. static const char *month_names[] = {
  930. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  931. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  932. };
  933. static const char *week_days[] = {
  934. "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
  935. };
  936. static inline void strcpy_gmt(char *ubuf, time_t *when) /* {{{ */
  937. {
  938. char buf[MAX_STR];
  939. struct tm tm, *res;
  940. int n;
  941. res = php_gmtime_r(when, &tm);
  942. if (!res) {
  943. ubuf[0] = '\0';
  944. return;
  945. }
  946. n = slprintf(buf, sizeof(buf), "%s, %02d %s %d %02d:%02d:%02d GMT", /* SAFE */
  947. week_days[tm.tm_wday], tm.tm_mday,
  948. month_names[tm.tm_mon], tm.tm_year + 1900,
  949. tm.tm_hour, tm.tm_min,
  950. tm.tm_sec);
  951. memcpy(ubuf, buf, n);
  952. ubuf[n] = '\0';
  953. }
  954. /* }}} */
  955. static inline void last_modified(void) /* {{{ */
  956. {
  957. const char *path;
  958. zend_stat_t sb;
  959. char buf[MAX_STR + 1];
  960. path = SG(request_info).path_translated;
  961. if (path) {
  962. if (VCWD_STAT(path, &sb) == -1) {
  963. return;
  964. }
  965. #define LAST_MODIFIED "Last-Modified: "
  966. memcpy(buf, LAST_MODIFIED, sizeof(LAST_MODIFIED) - 1);
  967. strcpy_gmt(buf + sizeof(LAST_MODIFIED) - 1, &sb.st_mtime);
  968. ADD_HEADER(buf);
  969. }
  970. }
  971. /* }}} */
  972. #define EXPIRES "Expires: "
  973. CACHE_LIMITER_FUNC(public) /* {{{ */
  974. {
  975. char buf[MAX_STR + 1];
  976. struct timeval tv;
  977. time_t now;
  978. gettimeofday(&tv, NULL);
  979. now = tv.tv_sec + PS(cache_expire) * 60;
  980. memcpy(buf, EXPIRES, sizeof(EXPIRES) - 1);
  981. strcpy_gmt(buf + sizeof(EXPIRES) - 1, &now);
  982. ADD_HEADER(buf);
  983. snprintf(buf, sizeof(buf) , "Cache-Control: public, max-age=" ZEND_LONG_FMT, PS(cache_expire) * 60); /* SAFE */
  984. ADD_HEADER(buf);
  985. last_modified();
  986. }
  987. /* }}} */
  988. CACHE_LIMITER_FUNC(private_no_expire) /* {{{ */
  989. {
  990. char buf[MAX_STR + 1];
  991. snprintf(buf, sizeof(buf), "Cache-Control: private, max-age=" ZEND_LONG_FMT, PS(cache_expire) * 60); /* SAFE */
  992. ADD_HEADER(buf);
  993. last_modified();
  994. }
  995. /* }}} */
  996. CACHE_LIMITER_FUNC(private) /* {{{ */
  997. {
  998. ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
  999. CACHE_LIMITER(private_no_expire)();
  1000. }
  1001. /* }}} */
  1002. CACHE_LIMITER_FUNC(nocache) /* {{{ */
  1003. {
  1004. ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
  1005. /* For HTTP/1.1 conforming clients */
  1006. ADD_HEADER("Cache-Control: no-store, no-cache, must-revalidate");
  1007. /* For HTTP/1.0 conforming clients */
  1008. ADD_HEADER("Pragma: no-cache");
  1009. }
  1010. /* }}} */
  1011. static const php_session_cache_limiter_t php_session_cache_limiters[] = {
  1012. CACHE_LIMITER_ENTRY(public)
  1013. CACHE_LIMITER_ENTRY(private)
  1014. CACHE_LIMITER_ENTRY(private_no_expire)
  1015. CACHE_LIMITER_ENTRY(nocache)
  1016. {0}
  1017. };
  1018. static int php_session_cache_limiter(void) /* {{{ */
  1019. {
  1020. const php_session_cache_limiter_t *lim;
  1021. if (PS(cache_limiter)[0] == '\0') return 0;
  1022. if (PS(session_status) != php_session_active) return -1;
  1023. if (SG(headers_sent)) {
  1024. const char *output_start_filename = php_output_get_start_filename();
  1025. int output_start_lineno = php_output_get_start_lineno();
  1026. php_session_abort();
  1027. if (output_start_filename) {
  1028. 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);
  1029. } else {
  1030. php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be sent after headers have already been sent");
  1031. }
  1032. return -2;
  1033. }
  1034. for (lim = php_session_cache_limiters; lim->name; lim++) {
  1035. if (!strcasecmp(lim->name, PS(cache_limiter))) {
  1036. lim->func();
  1037. return 0;
  1038. }
  1039. }
  1040. return -1;
  1041. }
  1042. /* }}} */
  1043. /* *********************
  1044. * Cookie Management *
  1045. ********************* */
  1046. /*
  1047. * Remove already sent session ID cookie.
  1048. * It must be directly removed from SG(sapi_header) because sapi_add_header_ex()
  1049. * removes all of matching cookie. i.e. It deletes all of Set-Cookie headers.
  1050. */
  1051. static void php_session_remove_cookie(void) {
  1052. sapi_header_struct *header;
  1053. zend_llist *l = &SG(sapi_headers).headers;
  1054. zend_llist_element *next;
  1055. zend_llist_element *current;
  1056. char *session_cookie;
  1057. size_t session_cookie_len;
  1058. size_t len = sizeof("Set-Cookie")-1;
  1059. ZEND_ASSERT(strpbrk(PS(session_name), "=,; \t\r\n\013\014") == NULL);
  1060. spprintf(&session_cookie, 0, "Set-Cookie: %s=", PS(session_name));
  1061. session_cookie_len = strlen(session_cookie);
  1062. current = l->head;
  1063. while (current) {
  1064. header = (sapi_header_struct *)(current->data);
  1065. next = current->next;
  1066. if (header->header_len > len && header->header[len] == ':'
  1067. && !strncmp(header->header, session_cookie, session_cookie_len)) {
  1068. if (current->prev) {
  1069. current->prev->next = next;
  1070. } else {
  1071. l->head = next;
  1072. }
  1073. if (next) {
  1074. next->prev = current->prev;
  1075. } else {
  1076. l->tail = current->prev;
  1077. }
  1078. sapi_free_header(header);
  1079. efree(current);
  1080. --l->count;
  1081. }
  1082. current = next;
  1083. }
  1084. efree(session_cookie);
  1085. }
  1086. static int php_session_send_cookie(void) /* {{{ */
  1087. {
  1088. smart_str ncookie = {0};
  1089. zend_string *date_fmt = NULL;
  1090. zend_string *e_id;
  1091. if (SG(headers_sent)) {
  1092. const char *output_start_filename = php_output_get_start_filename();
  1093. int output_start_lineno = php_output_get_start_lineno();
  1094. if (output_start_filename) {
  1095. 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);
  1096. } else {
  1097. php_error_docref(NULL, E_WARNING, "Session cookie cannot be sent after headers have already been sent");
  1098. }
  1099. return FAILURE;
  1100. }
  1101. /* Prevent broken Set-Cookie header, because the session_name might be user supplied */
  1102. if (strpbrk(PS(session_name), "=,; \t\r\n\013\014") != NULL) { /* man isspace for \013 and \014 */
  1103. php_error_docref(NULL, E_WARNING, "session.name cannot contain any of the following '=,; \\t\\r\\n\\013\\014'");
  1104. return FAILURE;
  1105. }
  1106. /* URL encode id because it might be user supplied */
  1107. e_id = php_url_encode(ZSTR_VAL(PS(id)), ZSTR_LEN(PS(id)));
  1108. smart_str_appendl(&ncookie, "Set-Cookie: ", sizeof("Set-Cookie: ")-1);
  1109. smart_str_appendl(&ncookie, PS(session_name), strlen(PS(session_name)));
  1110. smart_str_appendc(&ncookie, '=');
  1111. smart_str_appendl(&ncookie, ZSTR_VAL(e_id), ZSTR_LEN(e_id));
  1112. zend_string_release_ex(e_id, 0);
  1113. if (PS(cookie_lifetime) > 0) {
  1114. struct timeval tv;
  1115. time_t t;
  1116. gettimeofday(&tv, NULL);
  1117. t = tv.tv_sec + PS(cookie_lifetime);
  1118. if (t > 0) {
  1119. date_fmt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, t, 0);
  1120. smart_str_appends(&ncookie, COOKIE_EXPIRES);
  1121. smart_str_appendl(&ncookie, ZSTR_VAL(date_fmt), ZSTR_LEN(date_fmt));
  1122. zend_string_release_ex(date_fmt, 0);
  1123. smart_str_appends(&ncookie, COOKIE_MAX_AGE);
  1124. smart_str_append_long(&ncookie, PS(cookie_lifetime));
  1125. }
  1126. }
  1127. if (PS(cookie_path)[0]) {
  1128. smart_str_appends(&ncookie, COOKIE_PATH);
  1129. smart_str_appends(&ncookie, PS(cookie_path));
  1130. }
  1131. if (PS(cookie_domain)[0]) {
  1132. smart_str_appends(&ncookie, COOKIE_DOMAIN);
  1133. smart_str_appends(&ncookie, PS(cookie_domain));
  1134. }
  1135. if (PS(cookie_secure)) {
  1136. smart_str_appends(&ncookie, COOKIE_SECURE);
  1137. }
  1138. if (PS(cookie_httponly)) {
  1139. smart_str_appends(&ncookie, COOKIE_HTTPONLY);
  1140. }
  1141. if (PS(cookie_samesite)[0]) {
  1142. smart_str_appends(&ncookie, COOKIE_SAMESITE);
  1143. smart_str_appends(&ncookie, PS(cookie_samesite));
  1144. }
  1145. smart_str_0(&ncookie);
  1146. php_session_remove_cookie(); /* remove already sent session ID cookie */
  1147. /* 'replace' must be 0 here, else a previous Set-Cookie
  1148. header, probably sent with setcookie() will be replaced! */
  1149. sapi_add_header_ex(estrndup(ZSTR_VAL(ncookie.s), ZSTR_LEN(ncookie.s)), ZSTR_LEN(ncookie.s), 0, 0);
  1150. smart_str_free(&ncookie);
  1151. return SUCCESS;
  1152. }
  1153. /* }}} */
  1154. PHPAPI const ps_module *_php_find_ps_module(const char *name) /* {{{ */
  1155. {
  1156. const ps_module *ret = NULL;
  1157. const ps_module **mod;
  1158. int i;
  1159. for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
  1160. if (*mod && !strcasecmp(name, (*mod)->s_name)) {
  1161. ret = *mod;
  1162. break;
  1163. }
  1164. }
  1165. return ret;
  1166. }
  1167. /* }}} */
  1168. PHPAPI const ps_serializer *_php_find_ps_serializer(const char *name) /* {{{ */
  1169. {
  1170. const ps_serializer *ret = NULL;
  1171. const ps_serializer *mod;
  1172. for (mod = ps_serializers; mod->name; mod++) {
  1173. if (!strcasecmp(name, mod->name)) {
  1174. ret = mod;
  1175. break;
  1176. }
  1177. }
  1178. return ret;
  1179. }
  1180. /* }}} */
  1181. static void ppid2sid(zval *ppid) {
  1182. ZVAL_DEREF(ppid);
  1183. if (Z_TYPE_P(ppid) == IS_STRING) {
  1184. PS(id) = zend_string_init(Z_STRVAL_P(ppid), Z_STRLEN_P(ppid), 0);
  1185. PS(send_cookie) = 0;
  1186. } else {
  1187. PS(id) = NULL;
  1188. PS(send_cookie) = 1;
  1189. }
  1190. }
  1191. PHPAPI int php_session_reset_id(void) /* {{{ */
  1192. {
  1193. int module_number = PS(module_number);
  1194. zval *sid, *data, *ppid;
  1195. bool apply_trans_sid;
  1196. if (!PS(id)) {
  1197. php_error_docref(NULL, E_WARNING, "Cannot set session ID - session ID is not initialized");
  1198. return FAILURE;
  1199. }
  1200. if (PS(use_cookies) && PS(send_cookie)) {
  1201. php_session_send_cookie();
  1202. PS(send_cookie) = 0;
  1203. }
  1204. /* If the SID constant exists, destroy it. */
  1205. /* We must not delete any items in EG(zend_constants) */
  1206. /* zend_hash_str_del(EG(zend_constants), "sid", sizeof("sid") - 1); */
  1207. sid = zend_get_constant_str("SID", sizeof("SID") - 1);
  1208. if (PS(define_sid)) {
  1209. smart_str var = {0};
  1210. smart_str_appends(&var, PS(session_name));
  1211. smart_str_appendc(&var, '=');
  1212. smart_str_appends(&var, ZSTR_VAL(PS(id)));
  1213. smart_str_0(&var);
  1214. if (sid) {
  1215. zval_ptr_dtor_str(sid);
  1216. ZVAL_NEW_STR(sid, var.s);
  1217. } else {
  1218. REGISTER_STRINGL_CONSTANT("SID", ZSTR_VAL(var.s), ZSTR_LEN(var.s), 0);
  1219. smart_str_free(&var);
  1220. }
  1221. } else {
  1222. if (sid) {
  1223. zval_ptr_dtor_str(sid);
  1224. ZVAL_EMPTY_STRING(sid);
  1225. } else {
  1226. REGISTER_STRINGL_CONSTANT("SID", "", 0, 0);
  1227. }
  1228. }
  1229. /* Apply trans sid if sid cookie is not set */
  1230. apply_trans_sid = 0;
  1231. if (APPLY_TRANS_SID) {
  1232. apply_trans_sid = 1;
  1233. if (PS(use_cookies) &&
  1234. (data = zend_hash_str_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE") - 1))) {
  1235. ZVAL_DEREF(data);
  1236. if (Z_TYPE_P(data) == IS_ARRAY &&
  1237. (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), strlen(PS(session_name))))) {
  1238. ZVAL_DEREF(ppid);
  1239. apply_trans_sid = 0;
  1240. }
  1241. }
  1242. }
  1243. if (apply_trans_sid) {
  1244. zend_string *sname;
  1245. sname = zend_string_init(PS(session_name), strlen(PS(session_name)), 0);
  1246. php_url_scanner_reset_session_var(sname, 1); /* This may fail when session name has changed */
  1247. zend_string_release_ex(sname, 0);
  1248. php_url_scanner_add_session_var(PS(session_name), strlen(PS(session_name)), ZSTR_VAL(PS(id)), ZSTR_LEN(PS(id)), 1);
  1249. }
  1250. return SUCCESS;
  1251. }
  1252. /* }}} */
  1253. PHPAPI int php_session_start(void) /* {{{ */
  1254. {
  1255. zval *ppid;
  1256. zval *data;
  1257. char *p, *value;
  1258. size_t lensess;
  1259. switch (PS(session_status)) {
  1260. case php_session_active:
  1261. php_error(E_NOTICE, "Ignoring session_start() because a session has already been started");
  1262. return FAILURE;
  1263. break;
  1264. case php_session_disabled:
  1265. value = zend_ini_string("session.save_handler", sizeof("session.save_handler") - 1, 0);
  1266. if (!PS(mod) && value) {
  1267. PS(mod) = _php_find_ps_module(value);
  1268. if (!PS(mod)) {
  1269. php_error_docref(NULL, E_WARNING, "Cannot find session save handler \"%s\" - session startup failed", value);
  1270. return FAILURE;
  1271. }
  1272. }
  1273. value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler") - 1, 0);
  1274. if (!PS(serializer) && value) {
  1275. PS(serializer) = _php_find_ps_serializer(value);
  1276. if (!PS(serializer)) {
  1277. php_error_docref(NULL, E_WARNING, "Cannot find session serialization handler \"%s\" - session startup failed", value);
  1278. return FAILURE;
  1279. }
  1280. }
  1281. PS(session_status) = php_session_none;
  1282. ZEND_FALLTHROUGH;
  1283. case php_session_none:
  1284. default:
  1285. /* Setup internal flags */
  1286. PS(define_sid) = !PS(use_only_cookies); /* SID constant is defined when non-cookie ID is used */
  1287. PS(send_cookie) = PS(use_cookies) || PS(use_only_cookies);
  1288. }
  1289. lensess = strlen(PS(session_name));
  1290. /*
  1291. * Cookies are preferred, because initially cookie and get
  1292. * variables will be available.
  1293. * URL/POST session ID may be used when use_only_cookies=Off.
  1294. * session.use_strice_mode=On prevents session adoption.
  1295. * Session based file upload progress uses non-cookie ID.
  1296. */
  1297. if (!PS(id)) {
  1298. if (PS(use_cookies) && (data = zend_hash_str_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE") - 1))) {
  1299. ZVAL_DEREF(data);
  1300. if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
  1301. ppid2sid(ppid);
  1302. PS(send_cookie) = 0;
  1303. PS(define_sid) = 0;
  1304. }
  1305. }
  1306. /* Initialize session ID from non cookie values */
  1307. if (!PS(use_only_cookies)) {
  1308. if (!PS(id) && (data = zend_hash_str_find(&EG(symbol_table), "_GET", sizeof("_GET") - 1))) {
  1309. ZVAL_DEREF(data);
  1310. if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
  1311. ppid2sid(ppid);
  1312. }
  1313. }
  1314. if (!PS(id) && (data = zend_hash_str_find(&EG(symbol_table), "_POST", sizeof("_POST") - 1))) {
  1315. ZVAL_DEREF(data);
  1316. if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
  1317. ppid2sid(ppid);
  1318. }
  1319. }
  1320. /* Check the REQUEST_URI symbol for a string of the form
  1321. * '<session-name>=<session-id>' to allow URLs of the form
  1322. * http://yoursite/<session-name>=<session-id>/script.php */
  1323. if (!PS(id) && zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER)) == SUCCESS &&
  1324. (data = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "REQUEST_URI", sizeof("REQUEST_URI") - 1)) &&
  1325. Z_TYPE_P(data) == IS_STRING &&
  1326. (p = strstr(Z_STRVAL_P(data), PS(session_name))) &&
  1327. p[lensess] == '='
  1328. ) {
  1329. char *q;
  1330. p += lensess + 1;
  1331. if ((q = strpbrk(p, "/?\\"))) {
  1332. PS(id) = zend_string_init(p, q - p, 0);
  1333. }
  1334. }
  1335. /* Check whether the current request was referred to by
  1336. * an external site which invalidates the previously found id. */
  1337. if (PS(id) && PS(extern_referer_chk)[0] != '\0' &&
  1338. !Z_ISUNDEF(PG(http_globals)[TRACK_VARS_SERVER]) &&
  1339. (data = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_REFERER", sizeof("HTTP_REFERER") - 1)) &&
  1340. Z_TYPE_P(data) == IS_STRING &&
  1341. Z_STRLEN_P(data) != 0 &&
  1342. strstr(Z_STRVAL_P(data), PS(extern_referer_chk)) == NULL
  1343. ) {
  1344. zend_string_release_ex(PS(id), 0);
  1345. PS(id) = NULL;
  1346. }
  1347. }
  1348. }
  1349. /* Finally check session id for dangerous characters
  1350. * Security note: session id may be embedded in HTML pages.*/
  1351. if (PS(id) && strpbrk(ZSTR_VAL(PS(id)), "\r\n\t <>'\"\\")) {
  1352. zend_string_release_ex(PS(id), 0);
  1353. PS(id) = NULL;
  1354. }
  1355. if (php_session_initialize() == FAILURE
  1356. || php_session_cache_limiter() == -2) {
  1357. PS(session_status) = php_session_none;
  1358. if (PS(id)) {
  1359. zend_string_release_ex(PS(id), 0);
  1360. PS(id) = NULL;
  1361. }
  1362. return FAILURE;
  1363. }
  1364. return SUCCESS;
  1365. }
  1366. /* }}} */
  1367. PHPAPI int php_session_flush(int write) /* {{{ */
  1368. {
  1369. if (PS(session_status) == php_session_active) {
  1370. php_session_save_current_state(write);
  1371. PS(session_status) = php_session_none;
  1372. return SUCCESS;
  1373. }
  1374. return FAILURE;
  1375. }
  1376. /* }}} */
  1377. static int php_session_abort(void) /* {{{ */
  1378. {
  1379. if (PS(session_status) == php_session_active) {
  1380. if (PS(mod_data) || PS(mod_user_implemented)) {
  1381. PS(mod)->s_close(&PS(mod_data));
  1382. }
  1383. PS(session_status) = php_session_none;
  1384. return SUCCESS;
  1385. }
  1386. return FAILURE;
  1387. }
  1388. /* }}} */
  1389. static int php_session_reset(void) /* {{{ */
  1390. {
  1391. if (PS(session_status) == php_session_active
  1392. && php_session_initialize() == SUCCESS) {
  1393. return SUCCESS;
  1394. }
  1395. return FAILURE;
  1396. }
  1397. /* }}} */
  1398. /* This API is not used by any PHP modules including session currently.
  1399. session_adapt_url() may be used to set Session ID to target url without
  1400. starting "URL-Rewriter" output handler. */
  1401. PHPAPI void session_adapt_url(const char *url, size_t url_len, char **new_url, size_t *new_len) /* {{{ */
  1402. {
  1403. if (APPLY_TRANS_SID && (PS(session_status) == php_session_active)) {
  1404. *new_url = php_url_scanner_adapt_single_url(url, url_len, PS(session_name), ZSTR_VAL(PS(id)), new_len, 1);
  1405. }
  1406. }
  1407. /* }}} */
  1408. /* ********************************
  1409. * Userspace exported functions *
  1410. ******************************** */
  1411. /* {{{ session_set_cookie_params(array options)
  1412. Set session cookie parameters */
  1413. PHP_FUNCTION(session_set_cookie_params)
  1414. {
  1415. HashTable *options_ht;
  1416. zend_long lifetime_long;
  1417. zend_string *lifetime = NULL, *path = NULL, *domain = NULL, *samesite = NULL;
  1418. bool secure = 0, secure_null = 1;
  1419. bool httponly = 0, httponly_null = 1;
  1420. zend_string *ini_name;
  1421. int result;
  1422. int found = 0;
  1423. if (!PS(use_cookies)) {
  1424. return;
  1425. }
  1426. ZEND_PARSE_PARAMETERS_START(1, 5)
  1427. Z_PARAM_ARRAY_HT_OR_LONG(options_ht, lifetime_long)
  1428. Z_PARAM_OPTIONAL
  1429. Z_PARAM_STR_OR_NULL(path)
  1430. Z_PARAM_STR_OR_NULL(domain)
  1431. Z_PARAM_BOOL_OR_NULL(secure, secure_null)
  1432. Z_PARAM_BOOL_OR_NULL(httponly, httponly_null)
  1433. ZEND_PARSE_PARAMETERS_END();
  1434. if (PS(session_status) == php_session_active) {
  1435. php_error_docref(NULL, E_WARNING, "Session cookie parameters cannot be changed when a session is active");
  1436. RETURN_FALSE;
  1437. }
  1438. if (SG(headers_sent)) {
  1439. php_error_docref(NULL, E_WARNING, "Session cookie parameters cannot be changed after headers have already been sent");
  1440. RETURN_FALSE;
  1441. }
  1442. if (options_ht) {
  1443. zend_string *key;
  1444. zval *value;
  1445. if (path) {
  1446. zend_argument_value_error(2, "must be null when argument #1 ($lifetime_or_options) is an array");
  1447. RETURN_THROWS();
  1448. }
  1449. if (domain) {
  1450. zend_argument_value_error(3, "must be null when argument #1 ($lifetime_or_options) is an array");
  1451. RETURN_THROWS();
  1452. }
  1453. if (!secure_null) {
  1454. zend_argument_value_error(4, "must be null when argument #1 ($lifetime_or_options) is an array");
  1455. RETURN_THROWS();
  1456. }
  1457. if (!httponly_null) {
  1458. zend_argument_value_error(5, "must be null when argument #1 ($lifetime_or_options) is an array");
  1459. RETURN_THROWS();
  1460. }
  1461. ZEND_HASH_FOREACH_STR_KEY_VAL(options_ht, key, value) {
  1462. if (key) {
  1463. ZVAL_DEREF(value);
  1464. if (zend_string_equals_literal_ci(key, "lifetime")) {
  1465. lifetime = zval_get_string(value);
  1466. found++;
  1467. } else if (zend_string_equals_literal_ci(key, "path")) {
  1468. path = zval_get_string(value);
  1469. found++;
  1470. } else if (zend_string_equals_literal_ci(key, "domain")) {
  1471. domain = zval_get_string(value);
  1472. found++;
  1473. } else if (zend_string_equals_literal_ci(key, "secure")) {
  1474. secure = zval_is_true(value);
  1475. secure_null = 0;
  1476. found++;
  1477. } else if (zend_string_equals_literal_ci(key, "httponly")) {
  1478. httponly = zval_is_true(value);
  1479. httponly_null = 0;
  1480. found++;
  1481. } else if (zend_string_equals_literal_ci(key, "samesite")) {
  1482. samesite = zval_get_string(value);
  1483. found++;
  1484. } else {
  1485. php_error_docref(NULL, E_WARNING, "Argument …

Large files files are truncated, but you can click here to view the full file