NativeSessionStorage.php 14 KB

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