NativeSessionStorage.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\Session\Storage;
  11. use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
  12. use Symfony\Component\HttpFoundation\Session\SessionUtils;
  13. use Symfony\Component\HttpFoundation\Session\Storage\Handler\StrictSessionHandler;
  14. use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
  15. use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
  16. // Help opcache.preload discover always-needed symbols
  17. class_exists(MetadataBag::class);
  18. class_exists(StrictSessionHandler::class);
  19. class_exists(SessionHandlerProxy::class);
  20. /**
  21. * This provides a base class for session attribute storage.
  22. *
  23. * @author Drak <drak@zikula.org>
  24. */
  25. class NativeSessionStorage implements SessionStorageInterface
  26. {
  27. /**
  28. * @var SessionBagInterface[]
  29. */
  30. protected $bags = [];
  31. /**
  32. * @var bool
  33. */
  34. protected $started = false;
  35. /**
  36. * @var bool
  37. */
  38. protected $closed = false;
  39. /**
  40. * @var AbstractProxy|\SessionHandlerInterface
  41. */
  42. protected $saveHandler;
  43. /**
  44. * @var MetadataBag
  45. */
  46. protected $metadataBag;
  47. /**
  48. * @var string|null
  49. */
  50. private $emulateSameSite;
  51. /**
  52. * Depending on how you want the storage driver to behave you probably
  53. * want to override this constructor entirely.
  54. *
  55. * List of options for $options array with their defaults.
  56. *
  57. * @see https://php.net/session.configuration for options
  58. * but we omit 'session.' from the beginning of the keys for convenience.
  59. *
  60. * ("auto_start", is not supported as it tells PHP to start a session before
  61. * PHP starts to execute user-land code. Setting during runtime has no effect).
  62. *
  63. * cache_limiter, "" (use "0" to prevent headers from being sent entirely).
  64. * cache_expire, "0"
  65. * cookie_domain, ""
  66. * cookie_httponly, ""
  67. * cookie_lifetime, "0"
  68. * cookie_path, "/"
  69. * cookie_secure, ""
  70. * cookie_samesite, null
  71. * gc_divisor, "100"
  72. * gc_maxlifetime, "1440"
  73. * gc_probability, "1"
  74. * lazy_write, "1"
  75. * name, "PHPSESSID"
  76. * referer_check, ""
  77. * serialize_handler, "php"
  78. * use_strict_mode, "1"
  79. * use_cookies, "1"
  80. * use_only_cookies, "1"
  81. * use_trans_sid, "0"
  82. * upload_progress.enabled, "1"
  83. * upload_progress.cleanup, "1"
  84. * upload_progress.prefix, "upload_progress_"
  85. * upload_progress.name, "PHP_SESSION_UPLOAD_PROGRESS"
  86. * upload_progress.freq, "1%"
  87. * upload_progress.min-freq, "1"
  88. * url_rewriter.tags, "a=href,area=href,frame=src,form=,fieldset="
  89. * sid_length, "32"
  90. * sid_bits_per_character, "5"
  91. * trans_sid_hosts, $_SERVER['HTTP_HOST']
  92. * trans_sid_tags, "a=href,area=href,frame=src,form="
  93. *
  94. * @param AbstractProxy|\SessionHandlerInterface|null $handler
  95. */
  96. public function __construct(array $options = [], $handler = null, MetadataBag $metaBag = null)
  97. {
  98. if (!\extension_loaded('session')) {
  99. throw new \LogicException('PHP extension "session" is required.');
  100. }
  101. $options += [
  102. 'cache_limiter' => '',
  103. 'cache_expire' => 0,
  104. 'use_cookies' => 1,
  105. 'lazy_write' => 1,
  106. 'use_strict_mode' => 1,
  107. ];
  108. session_register_shutdown();
  109. $this->setMetadataBag($metaBag);
  110. $this->setOptions($options);
  111. $this->setSaveHandler($handler);
  112. }
  113. /**
  114. * Gets the save handler instance.
  115. *
  116. * @return AbstractProxy|\SessionHandlerInterface
  117. */
  118. public function getSaveHandler()
  119. {
  120. return $this->saveHandler;
  121. }
  122. /**
  123. * {@inheritdoc}
  124. */
  125. public function start()
  126. {
  127. if ($this->started) {
  128. return true;
  129. }
  130. if (\PHP_SESSION_ACTIVE === session_status()) {
  131. throw new \RuntimeException('Failed to start the session: already started by PHP.');
  132. }
  133. if (filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN) && headers_sent($file, $line)) {
  134. throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
  135. }
  136. $sessionId = $_COOKIE[session_name()] ?? null;
  137. /*
  138. * Explanation of the session ID regular expression: `/^[a-zA-Z0-9,-]{22,250}$/`.
  139. *
  140. * ---------- Part 1
  141. *
  142. * The part `[a-zA-Z0-9,-]` is related to the PHP ini directive `session.sid_bits_per_character` defined as 6.
  143. * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-bits-per-character.
  144. * Allowed values are integers such as:
  145. * - 4 for range `a-f0-9`
  146. * - 5 for range `a-v0-9`
  147. * - 6 for range `a-zA-Z0-9,-`
  148. *
  149. * ---------- Part 2
  150. *
  151. * The part `{22,250}` is related to the PHP ini directive `session.sid_length`.
  152. * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-length.
  153. * Allowed values are integers between 22 and 256, but we use 250 for the max.
  154. *
  155. * Where does the 250 come from?
  156. * - The length of Windows and Linux filenames is limited to 255 bytes. Then the max must not exceed 255.
  157. * - The session filename prefix is `sess_`, a 5 bytes string. Then the max must not exceed 255 - 5 = 250.
  158. *
  159. * ---------- Conclusion
  160. *
  161. * The parts 1 and 2 prevent the warning below:
  162. * `PHP Warning: SessionHandler::read(): Session ID is too long or contains illegal characters. Only the A-Z, a-z, 0-9, "-", and "," characters are allowed.`
  163. *
  164. * The part 2 prevents the warning below:
  165. * `PHP Warning: SessionHandler::read(): open(filepath, O_RDWR) failed: No such file or directory (2).`
  166. */
  167. if ($sessionId && $this->saveHandler instanceof AbstractProxy && 'files' === $this->saveHandler->getSaveHandlerName() && !preg_match('/^[a-zA-Z0-9,-]{22,250}$/', $sessionId)) {
  168. // the session ID in the header is invalid, create a new one
  169. session_id(session_create_id());
  170. }
  171. // ok to try and start the session
  172. if (!session_start()) {
  173. throw new \RuntimeException('Failed to start the session.');
  174. }
  175. if (null !== $this->emulateSameSite) {
  176. $originalCookie = SessionUtils::popSessionCookie(session_name(), session_id());
  177. if (null !== $originalCookie) {
  178. header(sprintf('%s; SameSite=%s', $originalCookie, $this->emulateSameSite), false);
  179. }
  180. }
  181. $this->loadSession();
  182. return true;
  183. }
  184. /**
  185. * {@inheritdoc}
  186. */
  187. public function getId()
  188. {
  189. return $this->saveHandler->getId();
  190. }
  191. /**
  192. * {@inheritdoc}
  193. */
  194. public function setId($id)
  195. {
  196. $this->saveHandler->setId($id);
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. public function getName()
  202. {
  203. return $this->saveHandler->getName();
  204. }
  205. /**
  206. * {@inheritdoc}
  207. */
  208. public function setName($name)
  209. {
  210. $this->saveHandler->setName($name);
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. public function regenerate($destroy = false, $lifetime = null)
  216. {
  217. // Cannot regenerate the session ID for non-active sessions.
  218. if (\PHP_SESSION_ACTIVE !== session_status()) {
  219. return false;
  220. }
  221. if (headers_sent()) {
  222. return false;
  223. }
  224. if (null !== $lifetime && $lifetime != \ini_get('session.cookie_lifetime')) {
  225. $this->save();
  226. ini_set('session.cookie_lifetime', $lifetime);
  227. $this->start();
  228. }
  229. if ($destroy) {
  230. $this->metadataBag->stampNew();
  231. }
  232. $isRegenerated = session_regenerate_id($destroy);
  233. if (null !== $this->emulateSameSite) {
  234. $originalCookie = SessionUtils::popSessionCookie(session_name(), session_id());
  235. if (null !== $originalCookie) {
  236. header(sprintf('%s; SameSite=%s', $originalCookie, $this->emulateSameSite), false);
  237. }
  238. }
  239. return $isRegenerated;
  240. }
  241. /**
  242. * {@inheritdoc}
  243. */
  244. public function save()
  245. {
  246. // Store a copy so we can restore the bags in case the session was not left empty
  247. $session = $_SESSION;
  248. foreach ($this->bags as $bag) {
  249. if (empty($_SESSION[$key = $bag->getStorageKey()])) {
  250. unset($_SESSION[$key]);
  251. }
  252. }
  253. if ($_SESSION && [$key = $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) {
  254. unset($_SESSION[$key]);
  255. }
  256. // Register error handler to add information about the current save handler
  257. $previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) {
  258. if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) {
  259. $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
  260. $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', \get_class($handler));
  261. }
  262. return $previousHandler ? $previousHandler($type, $msg, $file, $line) : false;
  263. });
  264. try {
  265. session_write_close();
  266. } finally {
  267. restore_error_handler();
  268. // Restore only if not empty
  269. if ($_SESSION) {
  270. $_SESSION = $session;
  271. }
  272. }
  273. $this->closed = true;
  274. $this->started = false;
  275. }
  276. /**
  277. * {@inheritdoc}
  278. */
  279. public function clear()
  280. {
  281. // clear out the bags
  282. foreach ($this->bags as $bag) {
  283. $bag->clear();
  284. }
  285. // clear out the session
  286. $_SESSION = [];
  287. // reconnect the bags to the session
  288. $this->loadSession();
  289. }
  290. /**
  291. * {@inheritdoc}
  292. */
  293. public function registerBag(SessionBagInterface $bag)
  294. {
  295. if ($this->started) {
  296. throw new \LogicException('Cannot register a bag when the session is already started.');
  297. }
  298. $this->bags[$bag->getName()] = $bag;
  299. }
  300. /**
  301. * {@inheritdoc}
  302. */
  303. public function getBag($name)
  304. {
  305. if (!isset($this->bags[$name])) {
  306. throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.', $name));
  307. }
  308. if (!$this->started && $this->saveHandler->isActive()) {
  309. $this->loadSession();
  310. } elseif (!$this->started) {
  311. $this->start();
  312. }
  313. return $this->bags[$name];
  314. }
  315. public function setMetadataBag(MetadataBag $metaBag = null)
  316. {
  317. if (null === $metaBag) {
  318. $metaBag = new MetadataBag();
  319. }
  320. $this->metadataBag = $metaBag;
  321. }
  322. /**
  323. * Gets the MetadataBag.
  324. *
  325. * @return MetadataBag
  326. */
  327. public function getMetadataBag()
  328. {
  329. return $this->metadataBag;
  330. }
  331. /**
  332. * {@inheritdoc}
  333. */
  334. public function isStarted()
  335. {
  336. return $this->started;
  337. }
  338. /**
  339. * Sets session.* ini variables.
  340. *
  341. * For convenience we omit 'session.' from the beginning of the keys.
  342. * Explicitly ignores other ini keys.
  343. *
  344. * @param array $options Session ini directives [key => value]
  345. *
  346. * @see https://php.net/session.configuration
  347. */
  348. public function setOptions(array $options)
  349. {
  350. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  351. return;
  352. }
  353. $validOptions = array_flip([
  354. 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly',
  355. 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'cookie_samesite',
  356. 'gc_divisor', 'gc_maxlifetime', 'gc_probability',
  357. 'lazy_write', 'name', 'referer_check',
  358. 'serialize_handler', 'use_strict_mode', 'use_cookies',
  359. 'use_only_cookies', 'use_trans_sid', 'upload_progress.enabled',
  360. 'upload_progress.cleanup', 'upload_progress.prefix', 'upload_progress.name',
  361. 'upload_progress.freq', 'upload_progress.min_freq', 'url_rewriter.tags',
  362. 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags',
  363. ]);
  364. foreach ($options as $key => $value) {
  365. if (isset($validOptions[$key])) {
  366. if ('cookie_samesite' === $key && \PHP_VERSION_ID < 70300) {
  367. // PHP < 7.3 does not support same_site cookies. We will emulate it in
  368. // the start() method instead.
  369. $this->emulateSameSite = $value;
  370. continue;
  371. }
  372. if ('cookie_secure' === $key && 'auto' === $value) {
  373. continue;
  374. }
  375. ini_set('url_rewriter.tags' !== $key ? 'session.'.$key : $key, $value);
  376. }
  377. }
  378. }
  379. /**
  380. * Registers session save handler as a PHP session handler.
  381. *
  382. * To use internal PHP session save handlers, override this method using ini_set with
  383. * session.save_handler and session.save_path e.g.
  384. *
  385. * ini_set('session.save_handler', 'files');
  386. * ini_set('session.save_path', '/tmp');
  387. *
  388. * or pass in a \SessionHandler instance which configures session.save_handler in the
  389. * constructor, for a template see NativeFileSessionHandler.
  390. *
  391. * @see https://php.net/session-set-save-handler
  392. * @see https://php.net/sessionhandlerinterface
  393. * @see https://php.net/sessionhandler
  394. *
  395. * @param AbstractProxy|\SessionHandlerInterface|null $saveHandler
  396. *
  397. * @throws \InvalidArgumentException
  398. */
  399. public function setSaveHandler($saveHandler = null)
  400. {
  401. if (!$saveHandler instanceof AbstractProxy &&
  402. !$saveHandler instanceof \SessionHandlerInterface &&
  403. null !== $saveHandler) {
  404. throw new \InvalidArgumentException('Must be instance of AbstractProxy; implement \SessionHandlerInterface; or be null.');
  405. }
  406. // Wrap $saveHandler in proxy and prevent double wrapping of proxy
  407. if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  408. $saveHandler = new SessionHandlerProxy($saveHandler);
  409. } elseif (!$saveHandler instanceof AbstractProxy) {
  410. $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
  411. }
  412. $this->saveHandler = $saveHandler;
  413. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  414. return;
  415. }
  416. if ($this->saveHandler instanceof SessionHandlerProxy) {
  417. session_set_save_handler($this->saveHandler, false);
  418. }
  419. }
  420. /**
  421. * Load the session with attributes.
  422. *
  423. * After starting the session, PHP retrieves the session from whatever handlers
  424. * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
  425. * PHP takes the return value from the read() handler, unserializes it
  426. * and populates $_SESSION with the result automatically.
  427. */
  428. protected function loadSession(array &$session = null)
  429. {
  430. if (null === $session) {
  431. $session = &$_SESSION;
  432. }
  433. $bags = array_merge($this->bags, [$this->metadataBag]);
  434. foreach ($bags as $bag) {
  435. $key = $bag->getStorageKey();
  436. $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : [];
  437. $bag->initialize($session[$key]);
  438. }
  439. $this->started = true;
  440. $this->closed = false;
  441. }
  442. }