NativeSessionStorage.php 14 KB

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