PageRenderTime 62ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/ext/session/session.c

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

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