NativeSessionStorage.php 13 KB

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