session.c 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215
  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. /* We consider any ID valid (thus also implying that a session with such an ID exists),
  911. thus we always return SUCCESS */
  912. PHPAPI int php_session_validate_sid(PS_VALIDATE_SID_ARGS) {
  913. return SUCCESS;
  914. }
  915. /* Dummy PS module function */
  916. PHPAPI int php_session_update_timestamp(PS_UPDATE_TIMESTAMP_ARGS) {
  917. return SUCCESS;
  918. }
  919. /* ******************
  920. * Cache Limiters *
  921. ****************** */
  922. typedef struct {
  923. char *name;
  924. void (*func)(void);
  925. } php_session_cache_limiter_t;
  926. #define CACHE_LIMITER(name) _php_cache_limiter_##name
  927. #define CACHE_LIMITER_FUNC(name) static void CACHE_LIMITER(name)(void)
  928. #define CACHE_LIMITER_ENTRY(name) { #name, CACHE_LIMITER(name) },
  929. #define ADD_HEADER(a) sapi_add_header(a, strlen(a), 1);
  930. #define MAX_STR 512
  931. static const char *month_names[] = {
  932. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  933. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  934. };
  935. static const char *week_days[] = {
  936. "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
  937. };
  938. static inline void strcpy_gmt(char *ubuf, time_t *when) /* {{{ */
  939. {
  940. char buf[MAX_STR];
  941. struct tm tm, *res;
  942. int n;
  943. res = php_gmtime_r(when, &tm);
  944. if (!res) {
  945. ubuf[0] = '\0';
  946. return;
  947. }
  948. n = slprintf(buf, sizeof(buf), "%s, %02d %s %d %02d:%02d:%02d GMT", /* SAFE */
  949. week_days[tm.tm_wday], tm.tm_mday,
  950. month_names[tm.tm_mon], tm.tm_year + 1900,
  951. tm.tm_hour, tm.tm_min,
  952. tm.tm_sec);
  953. memcpy(ubuf, buf, n);
  954. ubuf[n] = '\0';
  955. }
  956. /* }}} */
  957. static inline void last_modified(void) /* {{{ */
  958. {
  959. const char *path;
  960. zend_stat_t sb;
  961. char buf[MAX_STR + 1];
  962. path = SG(request_info).path_translated;
  963. if (path) {
  964. if (VCWD_STAT(path, &sb) == -1) {
  965. return;
  966. }
  967. #define LAST_MODIFIED "Last-Modified: "
  968. memcpy(buf, LAST_MODIFIED, sizeof(LAST_MODIFIED) - 1);
  969. strcpy_gmt(buf + sizeof(LAST_MODIFIED) - 1, &sb.st_mtime);
  970. ADD_HEADER(buf);
  971. }
  972. }
  973. /* }}} */
  974. #define EXPIRES "Expires: "
  975. CACHE_LIMITER_FUNC(public) /* {{{ */
  976. {
  977. char buf[MAX_STR + 1];
  978. struct timeval tv;
  979. time_t now;
  980. gettimeofday(&tv, NULL);
  981. now = tv.tv_sec + PS(cache_expire) * 60;
  982. memcpy(buf, EXPIRES, sizeof(EXPIRES) - 1);
  983. strcpy_gmt(buf + sizeof(EXPIRES) - 1, &now);
  984. ADD_HEADER(buf);
  985. snprintf(buf, sizeof(buf) , "Cache-Control: public, max-age=" ZEND_LONG_FMT, PS(cache_expire) * 60); /* SAFE */
  986. ADD_HEADER(buf);
  987. last_modified();
  988. }
  989. /* }}} */
  990. CACHE_LIMITER_FUNC(private_no_expire) /* {{{ */
  991. {
  992. char buf[MAX_STR + 1];
  993. snprintf(buf, sizeof(buf), "Cache-Control: private, max-age=" ZEND_LONG_FMT, PS(cache_expire) * 60); /* SAFE */
  994. ADD_HEADER(buf);
  995. last_modified();
  996. }
  997. /* }}} */
  998. CACHE_LIMITER_FUNC(private) /* {{{ */
  999. {
  1000. ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
  1001. CACHE_LIMITER(private_no_expire)();
  1002. }
  1003. /* }}} */
  1004. CACHE_LIMITER_FUNC(nocache) /* {{{ */
  1005. {
  1006. ADD_HEADER("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
  1007. /* For HTTP/1.1 conforming clients */
  1008. ADD_HEADER("Cache-Control: no-store, no-cache, must-revalidate");
  1009. /* For HTTP/1.0 conforming clients */
  1010. ADD_HEADER("Pragma: no-cache");
  1011. }
  1012. /* }}} */
  1013. static const php_session_cache_limiter_t php_session_cache_limiters[] = {
  1014. CACHE_LIMITER_ENTRY(public)
  1015. CACHE_LIMITER_ENTRY(private)
  1016. CACHE_LIMITER_ENTRY(private_no_expire)
  1017. CACHE_LIMITER_ENTRY(nocache)
  1018. {0}
  1019. };
  1020. static int php_session_cache_limiter(void) /* {{{ */
  1021. {
  1022. const php_session_cache_limiter_t *lim;
  1023. if (PS(cache_limiter)[0] == '\0') return 0;
  1024. if (PS(session_status) != php_session_active) return -1;
  1025. if (SG(headers_sent)) {
  1026. const char *output_start_filename = php_output_get_start_filename();
  1027. int output_start_lineno = php_output_get_start_lineno();
  1028. php_session_abort();
  1029. if (output_start_filename) {
  1030. 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);
  1031. } else {
  1032. php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be sent after headers have already been sent");
  1033. }
  1034. return -2;
  1035. }
  1036. for (lim = php_session_cache_limiters; lim->name; lim++) {
  1037. if (!strcasecmp(lim->name, PS(cache_limiter))) {
  1038. lim->func();
  1039. return 0;
  1040. }
  1041. }
  1042. return -1;
  1043. }
  1044. /* }}} */
  1045. /* *********************
  1046. * Cookie Management *
  1047. ********************* */
  1048. /*
  1049. * Remove already sent session ID cookie.
  1050. * It must be directly removed from SG(sapi_header) because sapi_add_header_ex()
  1051. * removes all of matching cookie. i.e. It deletes all of Set-Cookie headers.
  1052. */
  1053. static void php_session_remove_cookie(void) {
  1054. sapi_header_struct *header;
  1055. zend_llist *l = &SG(sapi_headers).headers;
  1056. zend_llist_element *next;
  1057. zend_llist_element *current;
  1058. char *session_cookie;
  1059. size_t session_cookie_len;
  1060. size_t len = sizeof("Set-Cookie")-1;
  1061. ZEND_ASSERT(strpbrk(PS(session_name), "=,; \t\r\n\013\014") == NULL);
  1062. spprintf(&session_cookie, 0, "Set-Cookie: %s=", PS(session_name));
  1063. session_cookie_len = strlen(session_cookie);
  1064. current = l->head;
  1065. while (current) {
  1066. header = (sapi_header_struct *)(current->data);
  1067. next = current->next;
  1068. if (header->header_len > len && header->header[len] == ':'
  1069. && !strncmp(header->header, session_cookie, session_cookie_len)) {
  1070. if (current->prev) {
  1071. current->prev->next = next;
  1072. } else {
  1073. l->head = next;
  1074. }
  1075. if (next) {
  1076. next->prev = current->prev;
  1077. } else {
  1078. l->tail = current->prev;
  1079. }
  1080. sapi_free_header(header);
  1081. efree(current);
  1082. --l->count;
  1083. }
  1084. current = next;
  1085. }
  1086. efree(session_cookie);
  1087. }
  1088. static int php_session_send_cookie(void) /* {{{ */
  1089. {
  1090. smart_str ncookie = {0};
  1091. zend_string *date_fmt = NULL;
  1092. zend_string *e_id;
  1093. if (SG(headers_sent)) {
  1094. const char *output_start_filename = php_output_get_start_filename();
  1095. int output_start_lineno = php_output_get_start_lineno();
  1096. if (output_start_filename) {
  1097. 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);
  1098. } else {
  1099. php_error_docref(NULL, E_WARNING, "Session cookie cannot be sent after headers have already been sent");
  1100. }
  1101. return FAILURE;
  1102. }
  1103. /* Prevent broken Set-Cookie header, because the session_name might be user supplied */
  1104. if (strpbrk(PS(session_name), "=,; \t\r\n\013\014") != NULL) { /* man isspace for \013 and \014 */
  1105. php_error_docref(NULL, E_WARNING, "session.name cannot contain any of the following '=,; \\t\\r\\n\\013\\014'");
  1106. return FAILURE;
  1107. }
  1108. /* URL encode id because it might be user supplied */
  1109. e_id = php_url_encode(ZSTR_VAL(PS(id)), ZSTR_LEN(PS(id)));
  1110. smart_str_appendl(&ncookie, "Set-Cookie: ", sizeof("Set-Cookie: ")-1);
  1111. smart_str_appendl(&ncookie, PS(session_name), strlen(PS(session_name)));
  1112. smart_str_appendc(&ncookie, '=');
  1113. smart_str_appendl(&ncookie, ZSTR_VAL(e_id), ZSTR_LEN(e_id));
  1114. zend_string_release_ex(e_id, 0);
  1115. if (PS(cookie_lifetime) > 0) {
  1116. struct timeval tv;
  1117. time_t t;
  1118. gettimeofday(&tv, NULL);
  1119. t = tv.tv_sec + PS(cookie_lifetime);
  1120. if (t > 0) {
  1121. 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);
  1122. smart_str_appends(&ncookie, COOKIE_EXPIRES);
  1123. smart_str_appendl(&ncookie, ZSTR_VAL(date_fmt), ZSTR_LEN(date_fmt));
  1124. zend_string_release_ex(date_fmt, 0);
  1125. smart_str_appends(&ncookie, COOKIE_MAX_AGE);
  1126. smart_str_append_long(&ncookie, PS(cookie_lifetime));
  1127. }
  1128. }
  1129. if (PS(cookie_path)[0]) {
  1130. smart_str_appends(&ncookie, COOKIE_PATH);
  1131. smart_str_appends(&ncookie, PS(cookie_path));
  1132. }
  1133. if (PS(cookie_domain)[0]) {
  1134. smart_str_appends(&ncookie, COOKIE_DOMAIN);
  1135. smart_str_appends(&ncookie, PS(cookie_domain));
  1136. }
  1137. if (PS(cookie_secure)) {
  1138. smart_str_appends(&ncookie, COOKIE_SECURE);
  1139. }
  1140. if (PS(cookie_httponly)) {
  1141. smart_str_appends(&ncookie, COOKIE_HTTPONLY);
  1142. }
  1143. if (PS(cookie_samesite)[0]) {
  1144. smart_str_appends(&ncookie, COOKIE_SAMESITE);
  1145. smart_str_appends(&ncookie, PS(cookie_samesite));
  1146. }
  1147. smart_str_0(&ncookie);
  1148. php_session_remove_cookie(); /* remove already sent session ID cookie */
  1149. /* 'replace' must be 0 here, else a previous Set-Cookie
  1150. header, probably sent with setcookie() will be replaced! */
  1151. sapi_add_header_ex(estrndup(ZSTR_VAL(ncookie.s), ZSTR_LEN(ncookie.s)), ZSTR_LEN(ncookie.s), 0, 0);
  1152. smart_str_free(&ncookie);
  1153. return SUCCESS;
  1154. }
  1155. /* }}} */
  1156. PHPAPI const ps_module *_php_find_ps_module(const char *name) /* {{{ */
  1157. {
  1158. const ps_module *ret = NULL;
  1159. const ps_module **mod;
  1160. int i;
  1161. for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
  1162. if (*mod && !strcasecmp(name, (*mod)->s_name)) {
  1163. ret = *mod;
  1164. break;
  1165. }
  1166. }
  1167. return ret;
  1168. }
  1169. /* }}} */
  1170. PHPAPI const ps_serializer *_php_find_ps_serializer(const char *name) /* {{{ */
  1171. {
  1172. const ps_serializer *ret = NULL;
  1173. const ps_serializer *mod;
  1174. for (mod = ps_serializers; mod->name; mod++) {
  1175. if (!strcasecmp(name, mod->name)) {
  1176. ret = mod;
  1177. break;
  1178. }
  1179. }
  1180. return ret;
  1181. }
  1182. /* }}} */
  1183. static void ppid2sid(zval *ppid) {
  1184. ZVAL_DEREF(ppid);
  1185. if (Z_TYPE_P(ppid) == IS_STRING) {
  1186. PS(id) = zend_string_init(Z_STRVAL_P(ppid), Z_STRLEN_P(ppid), 0);
  1187. PS(send_cookie) = 0;
  1188. } else {
  1189. PS(id) = NULL;
  1190. PS(send_cookie) = 1;
  1191. }
  1192. }
  1193. PHPAPI int php_session_reset_id(void) /* {{{ */
  1194. {
  1195. int module_number = PS(module_number);
  1196. zval *sid, *data, *ppid;
  1197. bool apply_trans_sid;
  1198. if (!PS(id)) {
  1199. php_error_docref(NULL, E_WARNING, "Cannot set session ID - session ID is not initialized");
  1200. return FAILURE;
  1201. }
  1202. if (PS(use_cookies) && PS(send_cookie)) {
  1203. php_session_send_cookie();
  1204. PS(send_cookie) = 0;
  1205. }
  1206. /* If the SID constant exists, destroy it. */
  1207. /* We must not delete any items in EG(zend_constants) */
  1208. /* zend_hash_str_del(EG(zend_constants), "sid", sizeof("sid") - 1); */
  1209. sid = zend_get_constant_str("SID", sizeof("SID") - 1);
  1210. if (PS(define_sid)) {
  1211. smart_str var = {0};
  1212. smart_str_appends(&var, PS(session_name));
  1213. smart_str_appendc(&var, '=');
  1214. smart_str_appends(&var, ZSTR_VAL(PS(id)));
  1215. smart_str_0(&var);
  1216. if (sid) {
  1217. zval_ptr_dtor_str(sid);
  1218. ZVAL_NEW_STR(sid, var.s);
  1219. } else {
  1220. REGISTER_STRINGL_CONSTANT("SID", ZSTR_VAL(var.s), ZSTR_LEN(var.s), 0);
  1221. smart_str_free(&var);
  1222. }
  1223. } else {
  1224. if (sid) {
  1225. zval_ptr_dtor_str(sid);
  1226. ZVAL_EMPTY_STRING(sid);
  1227. } else {
  1228. REGISTER_STRINGL_CONSTANT("SID", "", 0, 0);
  1229. }
  1230. }
  1231. /* Apply trans sid if sid cookie is not set */
  1232. apply_trans_sid = 0;
  1233. if (APPLY_TRANS_SID) {
  1234. apply_trans_sid = 1;
  1235. if (PS(use_cookies) &&
  1236. (data = zend_hash_str_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE") - 1))) {
  1237. ZVAL_DEREF(data);
  1238. if (Z_TYPE_P(data) == IS_ARRAY &&
  1239. (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), strlen(PS(session_name))))) {
  1240. ZVAL_DEREF(ppid);
  1241. apply_trans_sid = 0;
  1242. }
  1243. }
  1244. }
  1245. if (apply_trans_sid) {
  1246. zend_string *sname;
  1247. sname = zend_string_init(PS(session_name), strlen(PS(session_name)), 0);
  1248. php_url_scanner_reset_session_var(sname, 1); /* This may fail when session name has changed */
  1249. zend_string_release_ex(sname, 0);
  1250. php_url_scanner_add_session_var(PS(session_name), strlen(PS(session_name)), ZSTR_VAL(PS(id)), ZSTR_LEN(PS(id)), 1);
  1251. }
  1252. return SUCCESS;
  1253. }
  1254. /* }}} */
  1255. PHPAPI int php_session_start(void) /* {{{ */
  1256. {
  1257. zval *ppid;
  1258. zval *data;
  1259. char *p, *value;
  1260. size_t lensess;
  1261. switch (PS(session_status)) {
  1262. case php_session_active:
  1263. php_error(E_NOTICE, "Ignoring session_start() because a session has already been started");
  1264. return FAILURE;
  1265. break;
  1266. case php_session_disabled:
  1267. value = zend_ini_string("session.save_handler", sizeof("session.save_handler") - 1, 0);
  1268. if (!PS(mod) && value) {
  1269. PS(mod) = _php_find_ps_module(value);
  1270. if (!PS(mod)) {
  1271. php_error_docref(NULL, E_WARNING, "Cannot find session save handler \"%s\" - session startup failed", value);
  1272. return FAILURE;
  1273. }
  1274. }
  1275. value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler") - 1, 0);
  1276. if (!PS(serializer) && value) {
  1277. PS(serializer) = _php_find_ps_serializer(value);
  1278. if (!PS(serializer)) {
  1279. php_error_docref(NULL, E_WARNING, "Cannot find session serialization handler \"%s\" - session startup failed", value);
  1280. return FAILURE;
  1281. }
  1282. }
  1283. PS(session_status) = php_session_none;
  1284. ZEND_FALLTHROUGH;
  1285. case php_session_none:
  1286. default:
  1287. /* Setup internal flags */
  1288. PS(define_sid) = !PS(use_only_cookies); /* SID constant is defined when non-cookie ID is used */
  1289. PS(send_cookie) = PS(use_cookies) || PS(use_only_cookies);
  1290. }
  1291. lensess = strlen(PS(session_name));
  1292. /*
  1293. * Cookies are preferred, because initially cookie and get
  1294. * variables will be available.
  1295. * URL/POST session ID may be used when use_only_cookies=Off.
  1296. * session.use_strice_mode=On prevents session adoption.
  1297. * Session based file upload progress uses non-cookie ID.
  1298. */
  1299. if (!PS(id)) {
  1300. if (PS(use_cookies) && (data = zend_hash_str_find(&EG(symbol_table), "_COOKIE", sizeof("_COOKIE") - 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. PS(send_cookie) = 0;
  1305. PS(define_sid) = 0;
  1306. }
  1307. }
  1308. /* Initialize session ID from non cookie values */
  1309. if (!PS(use_only_cookies)) {
  1310. if (!PS(id) && (data = zend_hash_str_find(&EG(symbol_table), "_GET", sizeof("_GET") - 1))) {
  1311. ZVAL_DEREF(data);
  1312. if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
  1313. ppid2sid(ppid);
  1314. }
  1315. }
  1316. if (!PS(id) && (data = zend_hash_str_find(&EG(symbol_table), "_POST", sizeof("_POST") - 1))) {
  1317. ZVAL_DEREF(data);
  1318. if (Z_TYPE_P(data) == IS_ARRAY && (ppid = zend_hash_str_find(Z_ARRVAL_P(data), PS(session_name), lensess))) {
  1319. ppid2sid(ppid);
  1320. }
  1321. }
  1322. /* Check the REQUEST_URI symbol for a string of the form
  1323. * '<session-name>=<session-id>' to allow URLs of the form
  1324. * http://yoursite/<session-name>=<session-id>/script.php */
  1325. if (!PS(id) && zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER)) == SUCCESS &&
  1326. (data = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "REQUEST_URI", sizeof("REQUEST_URI") - 1)) &&
  1327. Z_TYPE_P(data) == IS_STRING &&
  1328. (p = strstr(Z_STRVAL_P(data), PS(session_name))) &&
  1329. p[lensess] == '='
  1330. ) {
  1331. char *q;
  1332. p += lensess + 1;
  1333. if ((q = strpbrk(p, "/?\\"))) {
  1334. PS(id) = zend_string_init(p, q - p, 0);
  1335. }
  1336. }
  1337. /* Check whether the current request was referred to by
  1338. * an external site which invalidates the previously found id. */
  1339. if (PS(id) && PS(extern_referer_chk)[0] != '\0' &&
  1340. !Z_ISUNDEF(PG(http_globals)[TRACK_VARS_SERVER]) &&
  1341. (data = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_REFERER", sizeof("HTTP_REFERER") - 1)) &&
  1342. Z_TYPE_P(data) == IS_STRING &&
  1343. Z_STRLEN_P(data) != 0 &&
  1344. strstr(Z_STRVAL_P(data), PS(extern_referer_chk)) == NULL
  1345. ) {
  1346. zend_string_release_ex(PS(id), 0);
  1347. PS(id) = NULL;
  1348. }
  1349. }
  1350. }
  1351. /* Finally check session id for dangerous characters
  1352. * Security note: session id may be embedded in HTML pages.*/
  1353. if (PS(id) && strpbrk(ZSTR_VAL(PS(id)), "\r\n\t <>'\"\\")) {
  1354. zend_string_release_ex(PS(id), 0);
  1355. PS(id) = NULL;
  1356. }
  1357. if (php_session_initialize() == FAILURE
  1358. || php_session_cache_limiter() == -2) {
  1359. PS(session_status) = php_session_none;
  1360. if (PS(id)) {
  1361. zend_string_release_ex(PS(id), 0);
  1362. PS(id) = NULL;
  1363. }
  1364. return FAILURE;
  1365. }
  1366. return SUCCESS;
  1367. }
  1368. /* }}} */
  1369. PHPAPI int php_session_flush(int write) /* {{{ */
  1370. {
  1371. if (PS(session_status) == php_session_active) {
  1372. php_session_save_current_state(write);
  1373. PS(session_status) = php_session_none;
  1374. return SUCCESS;
  1375. }
  1376. return FAILURE;
  1377. }
  1378. /* }}} */
  1379. static int php_session_abort(void) /* {{{ */
  1380. {
  1381. if (PS(session_status) == php_session_active) {
  1382. if (PS(mod_data) || PS(mod_user_implemented)) {
  1383. PS(mod)->s_close(&PS(mod_data));
  1384. }
  1385. PS(session_status) = php_session_none;
  1386. return SUCCESS;
  1387. }
  1388. return FAILURE;
  1389. }
  1390. /* }}} */
  1391. static int php_session_reset(void) /* {{{ */
  1392. {
  1393. if (PS(session_status) == php_session_active
  1394. && php_session_initialize() == SUCCESS) {
  1395. return SUCCESS;
  1396. }
  1397. return FAILURE;
  1398. }
  1399. /* }}} */
  1400. /* This API is not used by any PHP modules including session currently.
  1401. session_adapt_url() may be used to set Session ID to target url without
  1402. starting "URL-Rewriter" output handler. */
  1403. PHPAPI void session_adapt_url(const char *url, size_t url_len, char **new_url, size_t *new_len) /* {{{ */
  1404. {
  1405. if (APPLY_TRANS_SID && (PS(session_status) == php_session_active)) {
  1406. *new_url = php_url_scanner_adapt_single_url(url, url_len, PS(session_name), ZSTR_VAL(PS(id)), new_len, 1);
  1407. }
  1408. }
  1409. /* }}} */
  1410. /* ********************************
  1411. * Userspace exported functions *
  1412. ******************************** */
  1413. /* {{{ session_set_cookie_params(array options)
  1414. Set session cookie parameters */
  1415. PHP_FUNCTION(session_set_cookie_params)
  1416. {
  1417. HashTable *options_ht;
  1418. zend_long lifetime_long;
  1419. zend_string *lifetime = NULL, *path = NULL, *domain = NULL, *samesite = NULL;
  1420. bool secure = 0, secure_null = 1;
  1421. bool httponly = 0, httponly_null = 1;
  1422. zend_string *ini_name;
  1423. int result;
  1424. int found = 0;
  1425. if (!PS(use_cookies)) {
  1426. return;
  1427. }
  1428. ZEND_PARSE_PARAMETERS_START(1, 5)
  1429. Z_PARAM_ARRAY_HT_OR_LONG(options_ht, lifetime_long)
  1430. Z_PARAM_OPTIONAL
  1431. Z_PARAM_STR_OR_NULL(path)
  1432. Z_PARAM_STR_OR_NULL(domain)
  1433. Z_PARAM_BOOL_OR_NULL(secure, secure_null)
  1434. Z_PARAM_BOOL_OR_NULL(httponly, httponly_null)
  1435. ZEND_PARSE_PARAMETERS_END();
  1436. if (PS(session_status) == php_session_active) {
  1437. php_error_docref(NULL, E_WARNING, "Session cookie parameters cannot be changed when a session is active");
  1438. RETURN_FALSE;
  1439. }
  1440. if (SG(headers_sent)) {
  1441. php_error_docref(NULL, E_WARNING, "Session cookie parameters cannot be changed after headers have already been sent");
  1442. RETURN_FALSE;
  1443. }
  1444. if (options_ht) {
  1445. zend_string *key;
  1446. zval *value;
  1447. if (path) {
  1448. zend_argument_value_error(2, "must be null when argument #1 ($lifetime_or_options) is an array");
  1449. RETURN_THROWS();
  1450. }
  1451. if (domain) {
  1452. zend_argument_value_error(3, "must be null when argument #1 ($lifetime_or_options) is an array");
  1453. RETURN_THROWS();
  1454. }
  1455. if (!secure_null) {
  1456. zend_argument_value_error(4, "must be null when argument #1 ($lifetime_or_options) is an array");
  1457. RETURN_THROWS();
  1458. }
  1459. if (!httponly_null) {
  1460. zend_argument_value_error(5, "must be null when argument #1 ($lifetime_or_options) is an array");
  1461. RETURN_THROWS();
  1462. }
  1463. ZEND_HASH_FOREACH_STR_KEY_VAL(options_ht, key, value) {
  1464. if (key) {
  1465. ZVAL_DEREF(value);
  1466. if (zend_string_equals_literal_ci(key, "lifetime")) {
  1467. lifetime = zval_get_string(value);
  1468. found++;
  1469. } else if (zend_string_equals_literal_ci(key, "path")) {
  1470. path = zval_get_string(value);
  1471. found++;
  1472. } else if (zend_string_equals_literal_ci(key, "domain")) {
  1473. domain = zval_get_string(value);
  1474. found++;
  1475. } else if (zend_string_equals_literal_ci(key, "secure")) {
  1476. secure = zval_is_true(value);
  1477. secure_null = 0;
  1478. found++;
  1479. } else if (zend_string_equals_literal_ci(key, "httponly")) {
  1480. httponly = zval_is_true(value);
  1481. httponly_null = 0;
  1482. found++;
  1483. } else if (zend_string_equals_literal_ci(key, "samesite")) {
  1484. samesite = zval_get_string(value);
  1485. found++;
  1486. } else {
  1487. php_error_docref(NULL, E_WARNING, "Argument #1 ($lifetime_or_options) contains an unrecognized key \"%s\"", ZSTR_VAL(key));
  1488. }
  1489. } else {
  1490. php_error_docref(NULL, E_WARNING, "Argument #1 ($lifetime_or_options) cannot contain numeric keys");
  1491. }
  1492. } ZEND_HASH_FOREACH_END();
  1493. if (found == 0) {
  1494. zend_argument_value_error(1, "must contain at least 1 valid key");
  1495. RETURN_THROWS();
  1496. }
  1497. } else {
  1498. lifetime = zend_long_to_str(lifetime_long);
  1499. }
  1500. /* Exception during string conversion */
  1501. if (EG(exception)) {
  1502. goto cleanup;
  1503. }
  1504. if (lifetime) {
  1505. ini_name = zend_string_init("session.cookie_lifetime", sizeof("session.cookie_lifetime") - 1, 0);
  1506. result = zend_alter_ini_entry(ini_name, lifetime, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1507. zend_string_release_ex(ini_name, 0);
  1508. if (result == FAILURE) {
  1509. RETVAL_FALSE;
  1510. goto cleanup;
  1511. }
  1512. }
  1513. if (path) {
  1514. ini_name = zend_string_init("session.cookie_path", sizeof("session.cookie_path") - 1, 0);
  1515. result = zend_alter_ini_entry(ini_name, path, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1516. zend_string_release_ex(ini_name, 0);
  1517. if (result == FAILURE) {
  1518. RETVAL_FALSE;
  1519. goto cleanup;
  1520. }
  1521. }
  1522. if (domain) {
  1523. ini_name = zend_string_init("session.cookie_domain", sizeof("session.cookie_domain") - 1, 0);
  1524. result = zend_alter_ini_entry(ini_name, domain, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1525. zend_string_release_ex(ini_name, 0);
  1526. if (result == FAILURE) {
  1527. RETVAL_FALSE;
  1528. goto cleanup;
  1529. }
  1530. }
  1531. if (!secure_null) {
  1532. ini_name = zend_string_init("session.cookie_secure", sizeof("session.cookie_secure") - 1, 0);
  1533. result = zend_alter_ini_entry_chars(ini_name, secure ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1534. zend_string_release_ex(ini_name, 0);
  1535. if (result == FAILURE) {
  1536. RETVAL_FALSE;
  1537. goto cleanup;
  1538. }
  1539. }
  1540. if (!httponly_null) {
  1541. ini_name = zend_string_init("session.cookie_httponly", sizeof("session.cookie_httponly") - 1, 0);
  1542. result = zend_alter_ini_entry_chars(ini_name, httponly ? "1" : "0", 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1543. zend_string_release_ex(ini_name, 0);
  1544. if (result == FAILURE) {
  1545. RETVAL_FALSE;
  1546. goto cleanup;
  1547. }
  1548. }
  1549. if (samesite) {
  1550. ini_name = zend_string_init("session.cookie_samesite", sizeof("session.cookie_samesite") - 1, 0);
  1551. result = zend_alter_ini_entry(ini_name, samesite, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1552. zend_string_release_ex(ini_name, 0);
  1553. if (result == FAILURE) {
  1554. RETVAL_FALSE;
  1555. goto cleanup;
  1556. }
  1557. }
  1558. RETVAL_TRUE;
  1559. cleanup:
  1560. if (lifetime) zend_string_release(lifetime);
  1561. if (found > 0) {
  1562. if (path) zend_string_release(path);
  1563. if (domain) zend_string_release(domain);
  1564. if (samesite) zend_string_release(samesite);
  1565. }
  1566. }
  1567. /* }}} */
  1568. /* {{{ Return the session cookie parameters */
  1569. PHP_FUNCTION(session_get_cookie_params)
  1570. {
  1571. if (zend_parse_parameters_none() == FAILURE) {
  1572. RETURN_THROWS();
  1573. }
  1574. array_init(return_value);
  1575. add_assoc_long(return_value, "lifetime", PS(cookie_lifetime));
  1576. add_assoc_string(return_value, "path", PS(cookie_path));
  1577. add_assoc_string(return_value, "domain", PS(cookie_domain));
  1578. add_assoc_bool(return_value, "secure", PS(cookie_secure));
  1579. add_assoc_bool(return_value, "httponly", PS(cookie_httponly));
  1580. add_assoc_string(return_value, "samesite", PS(cookie_samesite));
  1581. }
  1582. /* }}} */
  1583. /* {{{ Return the current session name. If newname is given, the session name is replaced with newname */
  1584. PHP_FUNCTION(session_name)
  1585. {
  1586. zend_string *name = NULL;
  1587. zend_string *ini_name;
  1588. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!", &name) == FAILURE) {
  1589. RETURN_THROWS();
  1590. }
  1591. if (name && PS(session_status) == php_session_active) {
  1592. php_error_docref(NULL, E_WARNING, "Session name cannot be changed when a session is active");
  1593. RETURN_FALSE;
  1594. }
  1595. if (name && SG(headers_sent)) {
  1596. php_error_docref(NULL, E_WARNING, "Session name cannot be changed after headers have already been sent");
  1597. RETURN_FALSE;
  1598. }
  1599. RETVAL_STRING(PS(session_name));
  1600. if (name) {
  1601. ini_name = zend_string_init("session.name", sizeof("session.name") - 1, 0);
  1602. zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1603. zend_string_release_ex(ini_name, 0);
  1604. }
  1605. }
  1606. /* }}} */
  1607. /* {{{ Return the current module name used for accessing session data. If newname is given, the module name is replaced with newname */
  1608. PHP_FUNCTION(session_module_name)
  1609. {
  1610. zend_string *name = NULL;
  1611. zend_string *ini_name;
  1612. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!", &name) == FAILURE) {
  1613. RETURN_THROWS();
  1614. }
  1615. if (name && PS(session_status) == php_session_active) {
  1616. php_error_docref(NULL, E_WARNING, "Session save handler module cannot be changed when a session is active");
  1617. RETURN_FALSE;
  1618. }
  1619. if (name && SG(headers_sent)) {
  1620. php_error_docref(NULL, E_WARNING, "Session save handler module cannot be changed after headers have already been sent");
  1621. RETURN_FALSE;
  1622. }
  1623. /* Set return_value to current module name */
  1624. if (PS(mod) && PS(mod)->s_name) {
  1625. RETVAL_STRING(PS(mod)->s_name);
  1626. } else {
  1627. RETVAL_EMPTY_STRING();
  1628. }
  1629. if (name) {
  1630. if (zend_string_equals_literal_ci(name, "user")) {
  1631. zend_argument_value_error(1, "cannot be \"user\"");
  1632. RETURN_THROWS();
  1633. }
  1634. if (!_php_find_ps_module(ZSTR_VAL(name))) {
  1635. php_error_docref(NULL, E_WARNING, "Session handler module \"%s\" cannot be found", ZSTR_VAL(name));
  1636. zval_ptr_dtor_str(return_value);
  1637. RETURN_FALSE;
  1638. }
  1639. if (PS(mod_data) || PS(mod_user_implemented)) {
  1640. PS(mod)->s_close(&PS(mod_data));
  1641. }
  1642. PS(mod_data) = NULL;
  1643. ini_name = zend_string_init("session.save_handler", sizeof("session.save_handler") - 1, 0);
  1644. zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1645. zend_string_release_ex(ini_name, 0);
  1646. }
  1647. }
  1648. /* }}} */
  1649. static int save_handler_check_session(void) {
  1650. if (PS(session_status) == php_session_active) {
  1651. php_error_docref(NULL, E_WARNING, "Session save handler cannot be changed when a session is active");
  1652. return FAILURE;
  1653. }
  1654. if (SG(headers_sent)) {
  1655. php_error_docref(NULL, E_WARNING, "Session save handler cannot be changed after headers have already been sent");
  1656. return FAILURE;
  1657. }
  1658. return SUCCESS;
  1659. }
  1660. static inline void set_user_save_handler_ini(void) {
  1661. zend_string *ini_name, *ini_val;
  1662. ini_name = zend_string_init("session.save_handler", sizeof("session.save_handler") - 1, 0);
  1663. ini_val = zend_string_init("user", sizeof("user") - 1, 0);
  1664. PS(set_handler) = 1;
  1665. zend_alter_ini_entry(ini_name, ini_val, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1666. PS(set_handler) = 0;
  1667. zend_string_release_ex(ini_val, 0);
  1668. zend_string_release_ex(ini_name, 0);
  1669. }
  1670. /* {{{ Sets user-level functions */
  1671. PHP_FUNCTION(session_set_save_handler)
  1672. {
  1673. zval *args = NULL;
  1674. int i, num_args, argc = ZEND_NUM_ARGS();
  1675. if (argc > 0 && argc <= 2) {
  1676. zval *obj = NULL;
  1677. zend_string *func_name;
  1678. zend_function *current_mptr;
  1679. bool register_shutdown = 1;
  1680. if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|b", &obj, php_session_iface_entry, &register_shutdown) == FAILURE) {
  1681. RETURN_THROWS();
  1682. }
  1683. if (save_handler_check_session() == FAILURE) {
  1684. RETURN_FALSE;
  1685. }
  1686. /* For compatibility reason, implemented interface is not checked */
  1687. /* Find implemented methods - SessionHandlerInterface */
  1688. i = 0;
  1689. ZEND_HASH_FOREACH_STR_KEY(&php_session_iface_entry->function_table, func_name) {
  1690. if ((current_mptr = zend_hash_find_ptr(&Z_OBJCE_P(obj)->function_table, func_name))) {
  1691. if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
  1692. zval_ptr_dtor(&PS(mod_user_names).names[i]);
  1693. }
  1694. array_init_size(&PS(mod_user_names).names[i], 2);
  1695. Z_ADDREF_P(obj);
  1696. add_next_index_zval(&PS(mod_user_names).names[i], obj);
  1697. add_next_index_str(&PS(mod_user_names).names[i], zend_string_copy(func_name));
  1698. } else {
  1699. php_error_docref(NULL, E_ERROR, "Session save handler function table is corrupt");
  1700. RETURN_FALSE;
  1701. }
  1702. ++i;
  1703. } ZEND_HASH_FOREACH_END();
  1704. /* Find implemented methods - SessionIdInterface (optional) */
  1705. ZEND_HASH_FOREACH_STR_KEY(&php_session_id_iface_entry->function_table, func_name) {
  1706. if ((current_mptr = zend_hash_find_ptr(&Z_OBJCE_P(obj)->function_table, func_name))) {
  1707. if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
  1708. zval_ptr_dtor(&PS(mod_user_names).names[i]);
  1709. }
  1710. array_init_size(&PS(mod_user_names).names[i], 2);
  1711. Z_ADDREF_P(obj);
  1712. add_next_index_zval(&PS(mod_user_names).names[i], obj);
  1713. add_next_index_str(&PS(mod_user_names).names[i], zend_string_copy(func_name));
  1714. } else {
  1715. if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
  1716. zval_ptr_dtor(&PS(mod_user_names).names[i]);
  1717. ZVAL_UNDEF(&PS(mod_user_names).names[i]);
  1718. }
  1719. }
  1720. ++i;
  1721. } ZEND_HASH_FOREACH_END();
  1722. /* Find implemented methods - SessionUpdateTimestampInterface (optional) */
  1723. ZEND_HASH_FOREACH_STR_KEY(&php_session_update_timestamp_iface_entry->function_table, func_name) {
  1724. if ((current_mptr = zend_hash_find_ptr(&Z_OBJCE_P(obj)->function_table, func_name))) {
  1725. if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
  1726. zval_ptr_dtor(&PS(mod_user_names).names[i]);
  1727. }
  1728. array_init_size(&PS(mod_user_names).names[i], 2);
  1729. Z_ADDREF_P(obj);
  1730. add_next_index_zval(&PS(mod_user_names).names[i], obj);
  1731. add_next_index_str(&PS(mod_user_names).names[i], zend_string_copy(func_name));
  1732. } else {
  1733. if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
  1734. zval_ptr_dtor(&PS(mod_user_names).names[i]);
  1735. ZVAL_UNDEF(&PS(mod_user_names).names[i]);
  1736. }
  1737. }
  1738. ++i;
  1739. } ZEND_HASH_FOREACH_END();
  1740. if (register_shutdown) {
  1741. /* create shutdown function */
  1742. php_shutdown_function_entry shutdown_function_entry;
  1743. zval callable;
  1744. zend_result result;
  1745. ZVAL_STRING(&callable, "session_register_shutdown");
  1746. result = zend_fcall_info_init(&callable, 0, &shutdown_function_entry.fci,
  1747. &shutdown_function_entry.fci_cache, NULL, NULL);
  1748. ZEND_ASSERT(result == SUCCESS);
  1749. /* add shutdown function, removing the old one if it exists */
  1750. if (!register_user_shutdown_function("session_shutdown", sizeof("session_shutdown") - 1, &shutdown_function_entry)) {
  1751. zval_ptr_dtor(&callable);
  1752. php_error_docref(NULL, E_WARNING, "Unable to register session shutdown function");
  1753. RETURN_FALSE;
  1754. }
  1755. } else {
  1756. /* remove shutdown function */
  1757. remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") - 1);
  1758. }
  1759. if (PS(session_status) != php_session_active && (!PS(mod) || PS(mod) != &ps_mod_user)) {
  1760. set_user_save_handler_ini();
  1761. }
  1762. RETURN_TRUE;
  1763. }
  1764. /* Set procedural save handler functions */
  1765. if (argc < 6 || PS_NUM_APIS < argc) {
  1766. WRONG_PARAM_COUNT;
  1767. }
  1768. if (zend_parse_parameters(argc, "+", &args, &num_args) == FAILURE) {
  1769. RETURN_THROWS();
  1770. }
  1771. /* At this point argc can only be between 6 and PS_NUM_APIS */
  1772. for (i = 0; i < argc; i++) {
  1773. if (!zend_is_callable(&args[i], 0, NULL)) {
  1774. zend_string *name = zend_get_callable_name(&args[i]);
  1775. zend_argument_type_error(i + 1, "must be a valid callback, function \"%s\" not found or invalid function name", ZSTR_VAL(name));
  1776. zend_string_release(name);
  1777. RETURN_THROWS();
  1778. }
  1779. }
  1780. if (save_handler_check_session() == FAILURE) {
  1781. RETURN_FALSE;
  1782. }
  1783. /* remove shutdown function */
  1784. remove_user_shutdown_function("session_shutdown", sizeof("session_shutdown") - 1);
  1785. if (!PS(mod) || PS(mod) != &ps_mod_user) {
  1786. set_user_save_handler_ini();
  1787. }
  1788. for (i = 0; i < argc; i++) {
  1789. if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
  1790. zval_ptr_dtor(&PS(mod_user_names).names[i]);
  1791. }
  1792. ZVAL_COPY(&PS(mod_user_names).names[i], &args[i]);
  1793. }
  1794. RETURN_TRUE;
  1795. }
  1796. /* }}} */
  1797. /* {{{ Return the current save path passed to module_name. If newname is given, the save path is replaced with newname */
  1798. PHP_FUNCTION(session_save_path)
  1799. {
  1800. zend_string *name = NULL;
  1801. zend_string *ini_name;
  1802. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|P!", &name) == FAILURE) {
  1803. RETURN_THROWS();
  1804. }
  1805. if (name && PS(session_status) == php_session_active) {
  1806. php_error_docref(NULL, E_WARNING, "Session save path cannot be changed when a session is active");
  1807. RETURN_FALSE;
  1808. }
  1809. if (name && SG(headers_sent)) {
  1810. php_error_docref(NULL, E_WARNING, "Session save path cannot be changed after headers have already been sent");
  1811. RETURN_FALSE;
  1812. }
  1813. RETVAL_STRING(PS(save_path));
  1814. if (name) {
  1815. ini_name = zend_string_init("session.save_path", sizeof("session.save_path") - 1, 0);
  1816. zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  1817. zend_string_release_ex(ini_name, 0);
  1818. }
  1819. }
  1820. /* }}} */
  1821. /* {{{ Return the current session id. If newid is given, the session id is replaced with newid */
  1822. PHP_FUNCTION(session_id)
  1823. {
  1824. zend_string *name = NULL;
  1825. int argc = ZEND_NUM_ARGS();
  1826. if (zend_parse_parameters(argc, "|S!", &name) == FAILURE) {
  1827. RETURN_THROWS();
  1828. }
  1829. if (name && PS(session_status) == php_session_active) {
  1830. php_error_docref(NULL, E_WARNING, "Session ID cannot be changed when a session is active");
  1831. RETURN_FALSE;
  1832. }
  1833. if (name && PS(use_cookies) && SG(headers_sent)) {
  1834. php_error_docref(NULL, E_WARNING, "Session ID cannot be changed after headers have already been sent");
  1835. RETURN_FALSE;
  1836. }
  1837. if (PS(id)) {
  1838. /* keep compatibility for "\0" characters ???
  1839. * see: ext/session/tests/session_id_error3.phpt */
  1840. size_t len = strlen(ZSTR_VAL(PS(id)));
  1841. if (UNEXPECTED(len != ZSTR_LEN(PS(id)))) {
  1842. RETVAL_NEW_STR(zend_string_init(ZSTR_VAL(PS(id)), len, 0));
  1843. } else {
  1844. RETVAL_STR_COPY(PS(id));
  1845. }
  1846. } else {
  1847. RETVAL_EMPTY_STRING();
  1848. }
  1849. if (name) {
  1850. if (PS(id)) {
  1851. zend_string_release_ex(PS(id), 0);
  1852. }
  1853. PS(id) = zend_string_copy(name);
  1854. }
  1855. }
  1856. /* }}} */
  1857. /* {{{ Update the current session id with a newly generated one. If delete_old_session is set to true, remove the old session. */
  1858. PHP_FUNCTION(session_regenerate_id)
  1859. {
  1860. bool del_ses = 0;
  1861. zend_string *data;
  1862. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &del_ses) == FAILURE) {
  1863. RETURN_THROWS();
  1864. }
  1865. if (PS(session_status) != php_session_active) {
  1866. php_error_docref(NULL, E_WARNING, "Session ID cannot be regenerated when there is no active session");
  1867. RETURN_FALSE;
  1868. }
  1869. if (SG(headers_sent)) {
  1870. php_error_docref(NULL, E_WARNING, "Session ID cannot be regenerated after headers have already been sent");
  1871. RETURN_FALSE;
  1872. }
  1873. /* Process old session data */
  1874. if (del_ses) {
  1875. if (PS(mod)->s_destroy(&PS(mod_data), PS(id)) == FAILURE) {
  1876. PS(mod)->s_close(&PS(mod_data));
  1877. PS(session_status) = php_session_none;
  1878. if (!EG(exception)) {
  1879. php_error_docref(NULL, E_WARNING, "Session object destruction failed. ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
  1880. }
  1881. RETURN_FALSE;
  1882. }
  1883. } else {
  1884. int ret;
  1885. data = php_session_encode();
  1886. if (data) {
  1887. ret = PS(mod)->s_write(&PS(mod_data), PS(id), data, PS(gc_maxlifetime));
  1888. zend_string_release_ex(data, 0);
  1889. } else {
  1890. ret = PS(mod)->s_write(&PS(mod_data), PS(id), ZSTR_EMPTY_ALLOC(), PS(gc_maxlifetime));
  1891. }
  1892. if (ret == FAILURE) {
  1893. PS(mod)->s_close(&PS(mod_data));
  1894. PS(session_status) = php_session_none;
  1895. php_error_docref(NULL, E_WARNING, "Session write failed. ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
  1896. RETURN_FALSE;
  1897. }
  1898. }
  1899. PS(mod)->s_close(&PS(mod_data));
  1900. /* New session data */
  1901. if (PS(session_vars)) {
  1902. zend_string_release_ex(PS(session_vars), 0);
  1903. PS(session_vars) = NULL;
  1904. }
  1905. zend_string_release_ex(PS(id), 0);
  1906. PS(id) = NULL;
  1907. if (PS(mod)->s_open(&PS(mod_data), PS(save_path), PS(session_name)) == FAILURE) {
  1908. PS(session_status) = php_session_none;
  1909. if (!EG(exception)) {
  1910. zend_throw_error(NULL, "Failed to open session: %s (path: %s)", PS(mod)->s_name, PS(save_path));
  1911. }
  1912. RETURN_THROWS();
  1913. }
  1914. PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
  1915. if (!PS(id)) {
  1916. PS(session_status) = php_session_none;
  1917. if (!EG(exception)) {
  1918. zend_throw_error(NULL, "Failed to create new session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
  1919. }
  1920. RETURN_THROWS();
  1921. }
  1922. if (PS(use_strict_mode)) {
  1923. if ((!PS(mod_user_implemented) && PS(mod)->s_validate_sid) || !Z_ISUNDEF(PS(mod_user_names).name.ps_validate_sid)) {
  1924. int limit = 3;
  1925. /* Try to generate non-existing ID */
  1926. while (limit-- && PS(mod)->s_validate_sid(&PS(mod_data), PS(id)) == SUCCESS) {
  1927. zend_string_release_ex(PS(id), 0);
  1928. PS(id) = PS(mod)->s_create_sid(&PS(mod_data));
  1929. if (!PS(id)) {
  1930. PS(mod)->s_close(&PS(mod_data));
  1931. PS(session_status) = php_session_none;
  1932. if (!EG(exception)) {
  1933. zend_throw_error(NULL, "Failed to create session ID by collision: %s (path: %s)", PS(mod)->s_name, PS(save_path));
  1934. }
  1935. RETURN_THROWS();
  1936. }
  1937. }
  1938. }
  1939. // TODO warn that ID cannot be verified? else { }
  1940. }
  1941. /* Read is required to make new session data at this point. */
  1942. if (PS(mod)->s_read(&PS(mod_data), PS(id), &data, PS(gc_maxlifetime)) == FAILURE) {
  1943. PS(mod)->s_close(&PS(mod_data));
  1944. PS(session_status) = php_session_none;
  1945. if (!EG(exception)) {
  1946. zend_throw_error(NULL, "Failed to create(read) session ID: %s (path: %s)", PS(mod)->s_name, PS(save_path));
  1947. }
  1948. RETURN_THROWS();
  1949. }
  1950. if (data) {
  1951. zend_string_release_ex(data, 0);
  1952. }
  1953. if (PS(use_cookies)) {
  1954. PS(send_cookie) = 1;
  1955. }
  1956. if (php_session_reset_id() == FAILURE) {
  1957. RETURN_FALSE;
  1958. }
  1959. RETURN_TRUE;
  1960. }
  1961. /* }}} */
  1962. /* {{{ Generate new session ID. Intended for user save handlers. */
  1963. PHP_FUNCTION(session_create_id)
  1964. {
  1965. zend_string *prefix = NULL, *new_id;
  1966. smart_str id = {0};
  1967. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &prefix) == FAILURE) {
  1968. RETURN_THROWS();
  1969. }
  1970. if (prefix && ZSTR_LEN(prefix)) {
  1971. if (php_session_valid_key(ZSTR_VAL(prefix)) == FAILURE) {
  1972. /* E_ERROR raised for security reason. */
  1973. php_error_docref(NULL, E_WARNING, "Prefix cannot contain special characters. Only the A-Z, a-z, 0-9, \"-\", and \",\" characters are allowed");
  1974. RETURN_FALSE;
  1975. } else {
  1976. smart_str_append(&id, prefix);
  1977. }
  1978. }
  1979. if (!PS(in_save_handler) && PS(session_status) == php_session_active) {
  1980. int limit = 3;
  1981. while (limit--) {
  1982. new_id = PS(mod)->s_create_sid(&PS(mod_data));
  1983. if (!PS(mod)->s_validate_sid || (PS(mod_user_implemented) && Z_ISUNDEF(PS(mod_user_names).name.ps_validate_sid))) {
  1984. break;
  1985. } else {
  1986. /* Detect collision and retry */
  1987. if (PS(mod)->s_validate_sid(&PS(mod_data), new_id) == SUCCESS) {
  1988. zend_string_release_ex(new_id, 0);
  1989. new_id = NULL;
  1990. continue;
  1991. }
  1992. break;
  1993. }
  1994. }
  1995. } else {
  1996. new_id = php_session_create_id(NULL);
  1997. }
  1998. if (new_id) {
  1999. smart_str_append(&id, new_id);
  2000. zend_string_release_ex(new_id, 0);
  2001. } else {
  2002. smart_str_free(&id);
  2003. php_error_docref(NULL, E_WARNING, "Failed to create new ID");
  2004. RETURN_FALSE;
  2005. }
  2006. smart_str_0(&id);
  2007. RETVAL_NEW_STR(id.s);
  2008. }
  2009. /* }}} */
  2010. /* {{{ Return the current cache limiter. If new_cache_limited is given, the current cache_limiter is replaced with new_cache_limiter */
  2011. PHP_FUNCTION(session_cache_limiter)
  2012. {
  2013. zend_string *limiter = NULL;
  2014. zend_string *ini_name;
  2015. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!", &limiter) == FAILURE) {
  2016. RETURN_THROWS();
  2017. }
  2018. if (limiter && PS(session_status) == php_session_active) {
  2019. php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be changed when a session is active");
  2020. RETURN_FALSE;
  2021. }
  2022. if (limiter && SG(headers_sent)) {
  2023. php_error_docref(NULL, E_WARNING, "Session cache limiter cannot be changed after headers have already been sent");
  2024. RETURN_FALSE;
  2025. }
  2026. RETVAL_STRING(PS(cache_limiter));
  2027. if (limiter) {
  2028. ini_name = zend_string_init("session.cache_limiter", sizeof("session.cache_limiter") - 1, 0);
  2029. zend_alter_ini_entry(ini_name, limiter, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
  2030. zend_string_release_ex(ini_name, 0);
  2031. }
  2032. }
  2033. /* }}} */
  2034. /* {{{ Return the current cache expire. If new_cache_expire is given, the current cache_expire is replaced with new_cache_expire */
  2035. PHP_FUNCTION(session_cache_expire)
  2036. {
  2037. zend_long expires;
  2038. bool expires_is_null = 1;
  2039. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l!", &expires, &expires_is_null) == FAILURE) {
  2040. RETURN_THROWS();
  2041. }
  2042. if (!expires_is_null && PS(session_status) == php_session_active) {
  2043. php_error_docref(NULL, E_WARNING, "Session cache expiration cannot be changed when a session is active");
  2044. RETURN_LONG(PS(cache_expire));
  2045. }
  2046. if (!expires_is_null && SG(headers_sent)) {
  2047. php_error_docref(NULL, E_WARNING, "Session cache expiration cannot be changed after headers have already been sent");
  2048. RETURN_FALSE;
  2049. }
  2050. RETVAL_LONG(PS(cache_expire));
  2051. if (!expires_is_null) {
  2052. zend_string *ini_name = zend_string_init("session.cache_expire", sizeof("session.cache_expire") - 1, 0);
  2053. zend_string *ini_value = zend_long_to_str(expires);
  2054. zend_alter_ini_entry(ini_name, ini_value, ZEND_INI_USER, ZEND_INI_STAGE_RUNTIME);
  2055. zend_string_release_ex(ini_name, 0);
  2056. zend_string_release_ex(ini_value, 0);
  2057. }
  2058. }
  2059. /* }}} */
  2060. /* {{{ Serializes the current setup and returns the serialized representation */
  2061. PHP_FUNCTION(session_encode)
  2062. {
  2063. zend_string *enc;
  2064. if (zend_parse_parameters_none() == FAILURE) {
  2065. RETURN_THROWS();
  2066. }
  2067. enc = php_session_encode();
  2068. if (enc == NULL) {
  2069. RETURN_FALSE;
  2070. }
  2071. RETURN_STR(enc);
  2072. }
  2073. /* }}} */
  2074. /* {{{ Deserializes data and reinitializes the variables */
  2075. PHP_FUNCTION(session_decode)
  2076. {
  2077. zend_string *str = NULL;
  2078. if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &str) == FAILURE) {
  2079. RETURN_THROWS();
  2080. }
  2081. if (PS(session_status) != php_session_active) {
  2082. php_error_docref(NULL, E_WARNING, "Session data cannot be decoded when there is no active session");
  2083. RETURN_FALSE;
  2084. }
  2085. if (php_session_decode(str) == FAILURE) {
  2086. RETURN_FALSE;
  2087. }
  2088. RETURN_TRUE;
  2089. }
  2090. /* }}} */
  2091. static int php_session_start_set_ini(zend_string *varname, zend_string *new_value) {
  2092. int ret;
  2093. smart_str buf ={0};
  2094. smart_str_appends(&buf, "session");
  2095. smart_str_appendc(&buf, '.');
  2096. smart_str_append(&buf, varname);
  2097. smart_str_0(&buf);
  2098. ret = zend_alter_ini_entry_ex(buf.s, new_value, PHP_INI_USER, PHP_INI_STAGE_RUNTIME, 0);
  2099. smart_str_free(&buf);
  2100. return ret;
  2101. }
  2102. /* {{{ Begin session */
  2103. PHP_FUNCTION(session_start)
  2104. {
  2105. zval *options = NULL;
  2106. zval *value;
  2107. zend_ulong num_idx;
  2108. zend_string *str_idx;
  2109. zend_long read_and_close = 0;
  2110. if (zend_parse_parameters(ZEND_NUM_ARGS(), "|a", &options) == FAILURE) {
  2111. RETURN_THROWS();
  2112. }
  2113. if (PS(session_status) == php_session_active) {
  2114. php_error_docref(NULL, E_NOTICE, "Ignoring session_start() because a session is already active");
  2115. RETURN_TRUE;
  2116. }
  2117. /*
  2118. * TODO: To prevent unusable session with trans sid, actual output started status is
  2119. * required. i.e. There shouldn't be any outputs in output buffer, otherwise session
  2120. * module is unable to rewrite output.
  2121. */
  2122. if (PS(use_cookies) && SG(headers_sent)) {
  2123. php_error_docref(NULL, E_WARNING, "Session cannot be started after headers have already been sent");
  2124. RETURN_FALSE;
  2125. }
  2126. /* set options */
  2127. if (options) {
  2128. ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(options), num_idx, str_idx, value) {
  2129. if (str_idx) {
  2130. switch(Z_TYPE_P(value)) {
  2131. case IS_STRING:
  2132. case IS_TRUE:
  2133. case IS_FALSE:
  2134. case IS_LONG:
  2135. if (zend_string_equals_literal(str_idx, "read_and_close")) {
  2136. read_and_close = zval_get_long(value);
  2137. } else {
  2138. zend_string *tmp_val;
  2139. zend_string *val = zval_get_tmp_string(value, &tmp_val);
  2140. if (php_session_start_set_ini(str_idx, val) == FAILURE) {
  2141. php_error_docref(NULL, E_WARNING, "Setting option \"%s\" failed", ZSTR_VAL(str_idx));
  2142. }
  2143. zend_tmp_string_release(tmp_val);
  2144. }
  2145. break;
  2146. default:
  2147. zend_type_error("%s(): Option \"%s\" must be of type string|int|bool, %s given",
  2148. get_active_function_name(), ZSTR_VAL(str_idx), zend_zval_type_name(value)
  2149. );
  2150. RETURN_THROWS();
  2151. }
  2152. }
  2153. (void) num_idx;
  2154. } ZEND_HASH_FOREACH_END();
  2155. }
  2156. php_session_start();
  2157. if (PS(session_status) != php_session_active) {
  2158. IF_SESSION_VARS() {
  2159. zval *sess_var = Z_REFVAL(PS(http_session_vars));
  2160. SEPARATE_ARRAY(sess_var);
  2161. /* Clean $_SESSION. */
  2162. zend_hash_clean(Z_ARRVAL_P(sess_var));
  2163. }
  2164. RETURN_FALSE;
  2165. }
  2166. if (read_and_close) {
  2167. php_session_flush(0);
  2168. }
  2169. RETURN_TRUE;
  2170. }
  2171. /* }}} */
  2172. /* {{{ Destroy the current session and all data associated with it */
  2173. PHP_FUNCTION(session_destroy)
  2174. {
  2175. if (zend_parse_parameters_none() == FAILURE) {
  2176. RETURN_THROWS();
  2177. }
  2178. RETURN_BOOL(php_session_destroy() == SUCCESS);
  2179. }
  2180. /* }}} */
  2181. /* {{{ Unset all registered variables */
  2182. PHP_FUNCTION(session_unset)
  2183. {
  2184. if (zend_parse_parameters_none() == FAILURE) {
  2185. RETURN_THROWS();
  2186. }
  2187. if (PS(session_status) != php_session_active) {
  2188. RETURN_FALSE;
  2189. }
  2190. IF_SESSION_VARS() {
  2191. zval *sess_var = Z_REFVAL(PS(http_session_vars));
  2192. SEPARATE_ARRAY(sess_var);
  2193. /* Clean $_SESSION. */
  2194. zend_hash_clean(Z_ARRVAL_P(sess_var));
  2195. }
  2196. RETURN_TRUE;
  2197. }
  2198. /* }}} */
  2199. /* {{{ Perform GC and return number of deleted sessions */
  2200. PHP_FUNCTION(session_gc)
  2201. {
  2202. zend_long num;
  2203. if (zend_parse_parameters_none() == FAILURE) {
  2204. RETURN_THROWS();
  2205. }
  2206. if (PS(session_status) != php_session_active) {
  2207. php_error_docref(NULL, E_WARNING, "Session cannot be garbage collected when there is no active session");
  2208. RETURN_FALSE;
  2209. }
  2210. num = php_session_gc(1);
  2211. if (num < 0) {
  2212. RETURN_FALSE;
  2213. }
  2214. RETURN_LONG(num);
  2215. }
  2216. /* }}} */
  2217. /* {{{ Write session data and end session */
  2218. PHP_FUNCTION(session_write_close)
  2219. {
  2220. if (zend_parse_parameters_none() == FAILURE) {
  2221. RETURN_THROWS();
  2222. }
  2223. if (PS(session_status) != php_session_active) {
  2224. RETURN_FALSE;
  2225. }
  2226. php_session_flush(1);
  2227. RETURN_TRUE;
  2228. }
  2229. /* }}} */
  2230. /* {{{ Abort session and end session. Session data will not be written */
  2231. PHP_FUNCTION(session_abort)
  2232. {
  2233. if (zend_parse_parameters_none() == FAILURE) {
  2234. RETURN_THROWS();
  2235. }
  2236. if (PS(session_status) != php_session_active) {
  2237. RETURN_FALSE;
  2238. }
  2239. php_session_abort();
  2240. RETURN_TRUE;
  2241. }
  2242. /* }}} */
  2243. /* {{{ Reset session data from saved session data */
  2244. PHP_FUNCTION(session_reset)
  2245. {
  2246. if (zend_parse_parameters_none() == FAILURE) {
  2247. RETURN_THROWS();
  2248. }
  2249. if (PS(session_status) != php_session_active) {
  2250. RETURN_FALSE;
  2251. }
  2252. php_session_reset();
  2253. RETURN_TRUE;
  2254. }
  2255. /* }}} */
  2256. /* {{{ Returns the current session status */
  2257. PHP_FUNCTION(session_status)
  2258. {
  2259. if (zend_parse_parameters_none() == FAILURE) {
  2260. RETURN_THROWS();
  2261. }
  2262. RETURN_LONG(PS(session_status));
  2263. }
  2264. /* }}} */
  2265. /* {{{ Registers session_write_close() as a shutdown function */
  2266. PHP_FUNCTION(session_register_shutdown)
  2267. {
  2268. php_shutdown_function_entry shutdown_function_entry;
  2269. zval callable;
  2270. zend_result result;
  2271. ZEND_PARSE_PARAMETERS_NONE();
  2272. /* This function is registered itself as a shutdown function by
  2273. * session_set_save_handler($obj). The reason we now register another
  2274. * shutdown function is in case the user registered their own shutdown
  2275. * function after calling session_set_save_handler(), which expects
  2276. * the session still to be available.
  2277. */
  2278. ZVAL_STRING(&callable, "session_write_close");
  2279. result = zend_fcall_info_init(&callable, 0, &shutdown_function_entry.fci,
  2280. &shutdown_function_entry.fci_cache, NULL, NULL);
  2281. ZEND_ASSERT(result == SUCCESS);
  2282. if (!append_user_shutdown_function(&shutdown_function_entry)) {
  2283. zval_ptr_dtor(&callable);
  2284. /* Unable to register shutdown function, presumably because of lack
  2285. * of memory, so flush the session now. It would be done in rshutdown
  2286. * anyway but the handler will have had it's dtor called by then.
  2287. * If the user does have a later shutdown function which needs the
  2288. * session then tough luck.
  2289. */
  2290. php_session_flush(1);
  2291. php_error_docref(NULL, E_WARNING, "Session shutdown function cannot be registered");
  2292. }
  2293. }
  2294. /* }}} */
  2295. /* ********************************
  2296. * Module Setup and Destruction *
  2297. ******************************** */
  2298. static int php_rinit_session(bool auto_start) /* {{{ */
  2299. {
  2300. php_rinit_session_globals();
  2301. PS(mod) = NULL;
  2302. {
  2303. char *value;
  2304. value = zend_ini_string("session.save_handler", sizeof("session.save_handler") - 1, 0);
  2305. if (value) {
  2306. PS(mod) = _php_find_ps_module(value);
  2307. }
  2308. }
  2309. if (PS(serializer) == NULL) {
  2310. char *value;
  2311. value = zend_ini_string("session.serialize_handler", sizeof("session.serialize_handler") - 1, 0);
  2312. if (value) {
  2313. PS(serializer) = _php_find_ps_serializer(value);
  2314. }
  2315. }
  2316. if (PS(mod) == NULL || PS(serializer) == NULL) {
  2317. /* current status is unusable */
  2318. PS(session_status) = php_session_disabled;
  2319. return SUCCESS;
  2320. }
  2321. if (auto_start) {
  2322. php_session_start();
  2323. }
  2324. return SUCCESS;
  2325. } /* }}} */
  2326. static PHP_RINIT_FUNCTION(session) /* {{{ */
  2327. {
  2328. return php_rinit_session(PS(auto_start));
  2329. }
  2330. /* }}} */
  2331. static PHP_RSHUTDOWN_FUNCTION(session) /* {{{ */
  2332. {
  2333. int i;
  2334. if (PS(session_status) == php_session_active) {
  2335. zend_try {
  2336. php_session_flush(1);
  2337. } zend_end_try();
  2338. }
  2339. php_rshutdown_session_globals();
  2340. /* this should NOT be done in php_rshutdown_session_globals() */
  2341. for (i = 0; i < PS_NUM_APIS; i++) {
  2342. if (!Z_ISUNDEF(PS(mod_user_names).names[i])) {
  2343. zval_ptr_dtor(&PS(mod_user_names).names[i]);
  2344. ZVAL_UNDEF(&PS(mod_user_names).names[i]);
  2345. }
  2346. }
  2347. return SUCCESS;
  2348. }
  2349. /* }}} */
  2350. static PHP_GINIT_FUNCTION(ps) /* {{{ */
  2351. {
  2352. int i;
  2353. #if defined(COMPILE_DL_SESSION) && defined(ZTS)
  2354. ZEND_TSRMLS_CACHE_UPDATE();
  2355. #endif
  2356. ps_globals->save_path = NULL;
  2357. ps_globals->session_name = NULL;
  2358. ps_globals->id = NULL;
  2359. ps_globals->mod = NULL;
  2360. ps_globals->serializer = NULL;
  2361. ps_globals->mod_data = NULL;
  2362. ps_globals->session_status = php_session_none;
  2363. ps_globals->default_mod = NULL;
  2364. ps_globals->mod_user_implemented = 0;
  2365. ps_globals->mod_user_is_open = 0;
  2366. ps_globals->session_vars = NULL;
  2367. ps_globals->set_handler = 0;
  2368. for (i = 0; i < PS_NUM_APIS; i++) {
  2369. ZVAL_UNDEF(&ps_globals->mod_user_names.names[i]);
  2370. }
  2371. ZVAL_UNDEF(&ps_globals->http_session_vars);
  2372. }
  2373. /* }}} */
  2374. static PHP_MINIT_FUNCTION(session) /* {{{ */
  2375. {
  2376. zend_register_auto_global(zend_string_init_interned("_SESSION", sizeof("_SESSION") - 1, 1), 0, NULL);
  2377. my_module_number = module_number;
  2378. PS(module_number) = module_number;
  2379. PS(session_status) = php_session_none;
  2380. REGISTER_INI_ENTRIES();
  2381. #ifdef HAVE_LIBMM
  2382. PHP_MINIT(ps_mm) (INIT_FUNC_ARGS_PASSTHRU);
  2383. #endif
  2384. php_session_rfc1867_orig_callback = php_rfc1867_callback;
  2385. php_rfc1867_callback = php_session_rfc1867_callback;
  2386. /* Register interfaces */
  2387. php_session_iface_entry = register_class_SessionHandlerInterface();
  2388. php_session_id_iface_entry = register_class_SessionIdInterface();
  2389. php_session_update_timestamp_iface_entry = register_class_SessionUpdateTimestampHandlerInterface();
  2390. /* Register base class */
  2391. php_session_class_entry = register_class_SessionHandler(php_session_iface_entry, php_session_id_iface_entry);
  2392. REGISTER_LONG_CONSTANT("PHP_SESSION_DISABLED", php_session_disabled, CONST_CS | CONST_PERSISTENT);
  2393. REGISTER_LONG_CONSTANT("PHP_SESSION_NONE", php_session_none, CONST_CS | CONST_PERSISTENT);
  2394. REGISTER_LONG_CONSTANT("PHP_SESSION_ACTIVE", php_session_active, CONST_CS | CONST_PERSISTENT);
  2395. return SUCCESS;
  2396. }
  2397. /* }}} */
  2398. static PHP_MSHUTDOWN_FUNCTION(session) /* {{{ */
  2399. {
  2400. UNREGISTER_INI_ENTRIES();
  2401. #ifdef HAVE_LIBMM
  2402. PHP_MSHUTDOWN(ps_mm) (SHUTDOWN_FUNC_ARGS_PASSTHRU);
  2403. #endif
  2404. /* reset rfc1867 callbacks */
  2405. php_session_rfc1867_orig_callback = NULL;
  2406. if (php_rfc1867_callback == php_session_rfc1867_callback) {
  2407. php_rfc1867_callback = NULL;
  2408. }
  2409. ps_serializers[PREDEFINED_SERIALIZERS].name = NULL;
  2410. memset(ZEND_VOIDP(&ps_modules[PREDEFINED_MODULES]), 0, (MAX_MODULES-PREDEFINED_MODULES)*sizeof(ps_module *));
  2411. return SUCCESS;
  2412. }
  2413. /* }}} */
  2414. static PHP_MINFO_FUNCTION(session) /* {{{ */
  2415. {
  2416. const ps_module **mod;
  2417. ps_serializer *ser;
  2418. smart_str save_handlers = {0};
  2419. smart_str ser_handlers = {0};
  2420. int i;
  2421. /* Get save handlers */
  2422. for (i = 0, mod = ps_modules; i < MAX_MODULES; i++, mod++) {
  2423. if (*mod && (*mod)->s_name) {
  2424. smart_str_appends(&save_handlers, (*mod)->s_name);
  2425. smart_str_appendc(&save_handlers, ' ');
  2426. }
  2427. }
  2428. /* Get serializer handlers */
  2429. for (i = 0, ser = ps_serializers; i < MAX_SERIALIZERS; i++, ser++) {
  2430. if (ser && ser->name) {
  2431. smart_str_appends(&ser_handlers, ser->name);
  2432. smart_str_appendc(&ser_handlers, ' ');
  2433. }
  2434. }
  2435. php_info_print_table_start();
  2436. php_info_print_table_row(2, "Session Support", "enabled" );
  2437. if (save_handlers.s) {
  2438. smart_str_0(&save_handlers);
  2439. php_info_print_table_row(2, "Registered save handlers", ZSTR_VAL(save_handlers.s));
  2440. smart_str_free(&save_handlers);
  2441. } else {
  2442. php_info_print_table_row(2, "Registered save handlers", "none");
  2443. }
  2444. if (ser_handlers.s) {
  2445. smart_str_0(&ser_handlers);
  2446. php_info_print_table_row(2, "Registered serializer handlers", ZSTR_VAL(ser_handlers.s));
  2447. smart_str_free(&ser_handlers);
  2448. } else {
  2449. php_info_print_table_row(2, "Registered serializer handlers", "none");
  2450. }
  2451. php_info_print_table_end();
  2452. DISPLAY_INI_ENTRIES();
  2453. }
  2454. /* }}} */
  2455. static const zend_module_dep session_deps[] = { /* {{{ */
  2456. ZEND_MOD_OPTIONAL("hash")
  2457. ZEND_MOD_REQUIRED("spl")
  2458. ZEND_MOD_END
  2459. };
  2460. /* }}} */
  2461. /* ************************
  2462. * Upload hook handling *
  2463. ************************ */
  2464. static bool early_find_sid_in(zval *dest, int where, php_session_rfc1867_progress *progress) /* {{{ */
  2465. {
  2466. zval *ppid;
  2467. if (Z_ISUNDEF(PG(http_globals)[where])) {
  2468. return 0;
  2469. }
  2470. if ((ppid = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[where]), PS(session_name), progress->sname_len))
  2471. && Z_TYPE_P(ppid) == IS_STRING) {
  2472. zval_ptr_dtor(dest);
  2473. ZVAL_COPY_DEREF(dest, ppid);
  2474. return 1;
  2475. }
  2476. return 0;
  2477. } /* }}} */
  2478. static void php_session_rfc1867_early_find_sid(php_session_rfc1867_progress *progress) /* {{{ */
  2479. {
  2480. if (PS(use_cookies)) {
  2481. sapi_module.treat_data(PARSE_COOKIE, NULL, NULL);
  2482. if (early_find_sid_in(&progress->sid, TRACK_VARS_COOKIE, progress)) {
  2483. progress->apply_trans_sid = 0;
  2484. return;
  2485. }
  2486. }
  2487. if (PS(use_only_cookies)) {
  2488. return;
  2489. }
  2490. sapi_module.treat_data(PARSE_GET, NULL, NULL);
  2491. early_find_sid_in(&progress->sid, TRACK_VARS_GET, progress);
  2492. } /* }}} */
  2493. static bool php_check_cancel_upload(php_session_rfc1867_progress *progress) /* {{{ */
  2494. {
  2495. zval *progress_ary, *cancel_upload;
  2496. if ((progress_ary = zend_symtable_find(Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars))), progress->key.s)) == NULL) {
  2497. return 0;
  2498. }
  2499. if (Z_TYPE_P(progress_ary) != IS_ARRAY) {
  2500. return 0;
  2501. }
  2502. if ((cancel_upload = zend_hash_str_find(Z_ARRVAL_P(progress_ary), "cancel_upload", sizeof("cancel_upload") - 1)) == NULL) {
  2503. return 0;
  2504. }
  2505. return Z_TYPE_P(cancel_upload) == IS_TRUE;
  2506. } /* }}} */
  2507. static void php_session_rfc1867_update(php_session_rfc1867_progress *progress, int force_update) /* {{{ */
  2508. {
  2509. if (!force_update) {
  2510. if (Z_LVAL_P(progress->post_bytes_processed) < progress->next_update) {
  2511. return;
  2512. }
  2513. #ifdef HAVE_GETTIMEOFDAY
  2514. if (PS(rfc1867_min_freq) > 0.0) {
  2515. struct timeval tv = {0};
  2516. double dtv;
  2517. gettimeofday(&tv, NULL);
  2518. dtv = (double) tv.tv_sec + tv.tv_usec / 1000000.0;
  2519. if (dtv < progress->next_update_time) {
  2520. return;
  2521. }
  2522. progress->next_update_time = dtv + PS(rfc1867_min_freq);
  2523. }
  2524. #endif
  2525. progress->next_update = Z_LVAL_P(progress->post_bytes_processed) + progress->update_step;
  2526. }
  2527. php_session_initialize();
  2528. PS(session_status) = php_session_active;
  2529. IF_SESSION_VARS() {
  2530. zval *sess_var = Z_REFVAL(PS(http_session_vars));
  2531. SEPARATE_ARRAY(sess_var);
  2532. progress->cancel_upload |= php_check_cancel_upload(progress);
  2533. Z_TRY_ADDREF(progress->data);
  2534. zend_hash_update(Z_ARRVAL_P(sess_var), progress->key.s, &progress->data);
  2535. }
  2536. php_session_flush(1);
  2537. } /* }}} */
  2538. static void php_session_rfc1867_cleanup(php_session_rfc1867_progress *progress) /* {{{ */
  2539. {
  2540. php_session_initialize();
  2541. PS(session_status) = php_session_active;
  2542. IF_SESSION_VARS() {
  2543. zval *sess_var = Z_REFVAL(PS(http_session_vars));
  2544. SEPARATE_ARRAY(sess_var);
  2545. zend_hash_del(Z_ARRVAL_P(sess_var), progress->key.s);
  2546. }
  2547. php_session_flush(1);
  2548. } /* }}} */
  2549. static int php_session_rfc1867_callback(unsigned int event, void *event_data, void **extra) /* {{{ */
  2550. {
  2551. php_session_rfc1867_progress *progress;
  2552. int retval = SUCCESS;
  2553. if (php_session_rfc1867_orig_callback) {
  2554. retval = php_session_rfc1867_orig_callback(event, event_data, extra);
  2555. }
  2556. if (!PS(rfc1867_enabled)) {
  2557. return retval;
  2558. }
  2559. progress = PS(rfc1867_progress);
  2560. switch(event) {
  2561. case MULTIPART_EVENT_START: {
  2562. multipart_event_start *data = (multipart_event_start *) event_data;
  2563. progress = ecalloc(1, sizeof(php_session_rfc1867_progress));
  2564. progress->content_length = data->content_length;
  2565. progress->sname_len = strlen(PS(session_name));
  2566. PS(rfc1867_progress) = progress;
  2567. }
  2568. break;
  2569. case MULTIPART_EVENT_FORMDATA: {
  2570. multipart_event_formdata *data = (multipart_event_formdata *) event_data;
  2571. size_t value_len;
  2572. if (Z_TYPE(progress->sid) && progress->key.s) {
  2573. break;
  2574. }
  2575. /* orig callback may have modified *data->newlength */
  2576. if (data->newlength) {
  2577. value_len = *data->newlength;
  2578. } else {
  2579. value_len = data->length;
  2580. }
  2581. if (data->name && data->value && value_len) {
  2582. size_t name_len = strlen(data->name);
  2583. if (name_len == progress->sname_len && memcmp(data->name, PS(session_name), name_len) == 0) {
  2584. zval_ptr_dtor(&progress->sid);
  2585. ZVAL_STRINGL(&progress->sid, (*data->value), value_len);
  2586. } else if (name_len == strlen(PS(rfc1867_name)) && memcmp(data->name, PS(rfc1867_name), name_len + 1) == 0) {
  2587. smart_str_free(&progress->key);
  2588. smart_str_appends(&progress->key, PS(rfc1867_prefix));
  2589. smart_str_appendl(&progress->key, *data->value, value_len);
  2590. smart_str_0(&progress->key);
  2591. progress->apply_trans_sid = APPLY_TRANS_SID;
  2592. php_session_rfc1867_early_find_sid(progress);
  2593. }
  2594. }
  2595. }
  2596. break;
  2597. case MULTIPART_EVENT_FILE_START: {
  2598. multipart_event_file_start *data = (multipart_event_file_start *) event_data;
  2599. /* Do nothing when $_POST["PHP_SESSION_UPLOAD_PROGRESS"] is not set
  2600. * or when we have no session id */
  2601. if (!Z_TYPE(progress->sid) || !progress->key.s) {
  2602. break;
  2603. }
  2604. /* First FILE_START event, initializing data */
  2605. if (Z_ISUNDEF(progress->data)) {
  2606. if (PS(rfc1867_freq) >= 0) {
  2607. progress->update_step = PS(rfc1867_freq);
  2608. } else if (PS(rfc1867_freq) < 0) { /* % of total size */
  2609. progress->update_step = progress->content_length * -PS(rfc1867_freq) / 100;
  2610. }
  2611. progress->next_update = 0;
  2612. progress->next_update_time = 0.0;
  2613. array_init(&progress->data);
  2614. array_init(&progress->files);
  2615. add_assoc_long_ex(&progress->data, "start_time", sizeof("start_time") - 1, (zend_long)sapi_get_request_time());
  2616. add_assoc_long_ex(&progress->data, "content_length", sizeof("content_length") - 1, progress->content_length);
  2617. add_assoc_long_ex(&progress->data, "bytes_processed", sizeof("bytes_processed") - 1, data->post_bytes_processed);
  2618. add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 0);
  2619. add_assoc_zval_ex(&progress->data, "files", sizeof("files") - 1, &progress->files);
  2620. progress->post_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->data), "bytes_processed", sizeof("bytes_processed") - 1);
  2621. php_rinit_session(0);
  2622. PS(id) = zend_string_init(Z_STRVAL(progress->sid), Z_STRLEN(progress->sid), 0);
  2623. if (progress->apply_trans_sid) {
  2624. /* Enable trans sid by modifying flags */
  2625. PS(use_trans_sid) = 1;
  2626. PS(use_only_cookies) = 0;
  2627. }
  2628. PS(send_cookie) = 0;
  2629. }
  2630. array_init(&progress->current_file);
  2631. /* Each uploaded file has its own array. Trying to make it close to $_FILES entries. */
  2632. add_assoc_string_ex(&progress->current_file, "field_name", sizeof("field_name") - 1, data->name);
  2633. add_assoc_string_ex(&progress->current_file, "name", sizeof("name") - 1, *data->filename);
  2634. add_assoc_null_ex(&progress->current_file, "tmp_name", sizeof("tmp_name") - 1);
  2635. add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, 0);
  2636. add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1, 0);
  2637. add_assoc_long_ex(&progress->current_file, "start_time", sizeof("start_time") - 1, (zend_long)time(NULL));
  2638. add_assoc_long_ex(&progress->current_file, "bytes_processed", sizeof("bytes_processed") - 1, 0);
  2639. add_next_index_zval(&progress->files, &progress->current_file);
  2640. progress->current_file_bytes_processed = zend_hash_str_find(Z_ARRVAL(progress->current_file), "bytes_processed", sizeof("bytes_processed") - 1);
  2641. Z_LVAL_P(progress->current_file_bytes_processed) = data->post_bytes_processed;
  2642. php_session_rfc1867_update(progress, 0);
  2643. }
  2644. break;
  2645. case MULTIPART_EVENT_FILE_DATA: {
  2646. multipart_event_file_data *data = (multipart_event_file_data *) event_data;
  2647. if (!Z_TYPE(progress->sid) || !progress->key.s) {
  2648. break;
  2649. }
  2650. Z_LVAL_P(progress->current_file_bytes_processed) = data->offset + data->length;
  2651. Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
  2652. php_session_rfc1867_update(progress, 0);
  2653. }
  2654. break;
  2655. case MULTIPART_EVENT_FILE_END: {
  2656. multipart_event_file_end *data = (multipart_event_file_end *) event_data;
  2657. if (!Z_TYPE(progress->sid) || !progress->key.s) {
  2658. break;
  2659. }
  2660. if (data->temp_filename) {
  2661. add_assoc_string_ex(&progress->current_file, "tmp_name", sizeof("tmp_name") - 1, data->temp_filename);
  2662. }
  2663. add_assoc_long_ex(&progress->current_file, "error", sizeof("error") - 1, data->cancel_upload);
  2664. add_assoc_bool_ex(&progress->current_file, "done", sizeof("done") - 1, 1);
  2665. Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
  2666. php_session_rfc1867_update(progress, 0);
  2667. }
  2668. break;
  2669. case MULTIPART_EVENT_END: {
  2670. multipart_event_end *data = (multipart_event_end *) event_data;
  2671. if (Z_TYPE(progress->sid) && progress->key.s) {
  2672. if (PS(rfc1867_cleanup)) {
  2673. php_session_rfc1867_cleanup(progress);
  2674. } else {
  2675. if (!Z_ISUNDEF(progress->data)) {
  2676. SEPARATE_ARRAY(&progress->data);
  2677. add_assoc_bool_ex(&progress->data, "done", sizeof("done") - 1, 1);
  2678. Z_LVAL_P(progress->post_bytes_processed) = data->post_bytes_processed;
  2679. php_session_rfc1867_update(progress, 1);
  2680. }
  2681. }
  2682. php_rshutdown_session_globals();
  2683. }
  2684. if (!Z_ISUNDEF(progress->data)) {
  2685. zval_ptr_dtor(&progress->data);
  2686. }
  2687. zval_ptr_dtor(&progress->sid);
  2688. smart_str_free(&progress->key);
  2689. efree(progress);
  2690. progress = NULL;
  2691. PS(rfc1867_progress) = NULL;
  2692. }
  2693. break;
  2694. }
  2695. if (progress && progress->cancel_upload) {
  2696. return FAILURE;
  2697. }
  2698. return retval;
  2699. } /* }}} */
  2700. zend_module_entry session_module_entry = {
  2701. STANDARD_MODULE_HEADER_EX,
  2702. NULL,
  2703. session_deps,
  2704. "session",
  2705. ext_functions,
  2706. PHP_MINIT(session), PHP_MSHUTDOWN(session),
  2707. PHP_RINIT(session), PHP_RSHUTDOWN(session),
  2708. PHP_MINFO(session),
  2709. PHP_SESSION_VERSION,
  2710. PHP_MODULE_GLOBALS(ps),
  2711. PHP_GINIT(ps),
  2712. NULL,
  2713. NULL,
  2714. STANDARD_MODULE_PROPERTIES_EX
  2715. };
  2716. #ifdef COMPILE_DL_SESSION
  2717. #ifdef ZTS
  2718. ZEND_TSRMLS_CACHE_DEFINE()
  2719. #endif
  2720. ZEND_GET_MODULE(session)
  2721. #endif