NativeSessionStorage.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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, ""
  60. * serialize_handler, "php"
  61. * use_strict_mode, "1"
  62. * use_cookies, "1"
  63. * use_only_cookies, "1"
  64. * use_trans_sid, "0"
  65. * sid_length, "32"
  66. * sid_bits_per_character, "5"
  67. * trans_sid_hosts, $_SERVER['HTTP_HOST']
  68. * trans_sid_tags, "a=href,area=href,frame=src,form="
  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://www.php.net/manual/en/session.configuration.php#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`
  116. * - 6 for range `a-zA-Z0-9,-`
  117. *
  118. * ---------- Part 2
  119. *
  120. * The part `{22,250}` is related to the PHP ini directive `session.sid_length`.
  121. * See https://www.php.net/manual/en/session.configuration.php#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. * ---------- Conclusion
  129. *
  130. * The parts 1 and 2 prevent the warning below:
  131. * `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.`
  132. *
  133. * The part 2 prevents the warning below:
  134. * `PHP Warning: SessionHandler::read(): open(filepath, O_RDWR) failed: No such file or directory (2).`
  135. */
  136. if ($sessionId && $this->saveHandler instanceof AbstractProxy && 'files' === $this->saveHandler->getSaveHandlerName() && !preg_match('/^[a-zA-Z0-9,-]{22,250}$/', $sessionId)) {
  137. // the session ID in the header is invalid, create a new one
  138. session_id(session_create_id());
  139. }
  140. // ok to try and start the session
  141. if (!session_start()) {
  142. throw new \RuntimeException('Failed to start the session.');
  143. }
  144. $this->loadSession();
  145. return true;
  146. }
  147. public function getId(): string
  148. {
  149. return $this->saveHandler->getId();
  150. }
  151. public function setId(string $id): void
  152. {
  153. $this->saveHandler->setId($id);
  154. }
  155. public function getName(): string
  156. {
  157. return $this->saveHandler->getName();
  158. }
  159. public function setName(string $name): void
  160. {
  161. $this->saveHandler->setName($name);
  162. }
  163. public function regenerate(bool $destroy = false, ?int $lifetime = null): bool
  164. {
  165. // Cannot regenerate the session ID for non-active sessions.
  166. if (\PHP_SESSION_ACTIVE !== session_status()) {
  167. return false;
  168. }
  169. if (headers_sent()) {
  170. return false;
  171. }
  172. if (null !== $lifetime && $lifetime != \ini_get('session.cookie_lifetime')) {
  173. $this->save();
  174. ini_set('session.cookie_lifetime', $lifetime);
  175. $this->start();
  176. }
  177. if ($destroy) {
  178. $this->metadataBag->stampNew();
  179. }
  180. return session_regenerate_id($destroy);
  181. }
  182. public function save(): void
  183. {
  184. // Store a copy so we can restore the bags in case the session was not left empty
  185. $session = $_SESSION;
  186. foreach ($this->bags as $bag) {
  187. if (empty($_SESSION[$key = $bag->getStorageKey()])) {
  188. unset($_SESSION[$key]);
  189. }
  190. }
  191. if ($_SESSION && [$key = $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) {
  192. unset($_SESSION[$key]);
  193. }
  194. // Register error handler to add information about the current save handler
  195. $previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) {
  196. if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) {
  197. $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
  198. $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', $handler::class);
  199. }
  200. return $previousHandler ? $previousHandler($type, $msg, $file, $line) : false;
  201. });
  202. try {
  203. session_write_close();
  204. } finally {
  205. restore_error_handler();
  206. // Restore only if not empty
  207. if ($_SESSION) {
  208. $_SESSION = $session;
  209. }
  210. }
  211. $this->closed = true;
  212. $this->started = false;
  213. }
  214. public function clear(): void
  215. {
  216. // clear out the bags
  217. foreach ($this->bags as $bag) {
  218. $bag->clear();
  219. }
  220. // clear out the session
  221. $_SESSION = [];
  222. // reconnect the bags to the session
  223. $this->loadSession();
  224. }
  225. public function registerBag(SessionBagInterface $bag): void
  226. {
  227. if ($this->started) {
  228. throw new \LogicException('Cannot register a bag when the session is already started.');
  229. }
  230. $this->bags[$bag->getName()] = $bag;
  231. }
  232. public function getBag(string $name): SessionBagInterface
  233. {
  234. if (!isset($this->bags[$name])) {
  235. throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.', $name));
  236. }
  237. if (!$this->started && $this->saveHandler->isActive()) {
  238. $this->loadSession();
  239. } elseif (!$this->started) {
  240. $this->start();
  241. }
  242. return $this->bags[$name];
  243. }
  244. public function setMetadataBag(?MetadataBag $metaBag): void
  245. {
  246. $this->metadataBag = $metaBag ?? new MetadataBag();
  247. }
  248. /**
  249. * Gets the MetadataBag.
  250. */
  251. public function getMetadataBag(): MetadataBag
  252. {
  253. return $this->metadataBag;
  254. }
  255. public function isStarted(): bool
  256. {
  257. return $this->started;
  258. }
  259. /**
  260. * Sets session.* ini variables.
  261. *
  262. * For convenience we omit 'session.' from the beginning of the keys.
  263. * Explicitly ignores other ini keys.
  264. *
  265. * @param array $options Session ini directives [key => value]
  266. *
  267. * @see https://php.net/session.configuration
  268. */
  269. public function setOptions(array $options): void
  270. {
  271. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  272. return;
  273. }
  274. $validOptions = array_flip([
  275. 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly',
  276. 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'cookie_samesite',
  277. 'gc_divisor', 'gc_maxlifetime', 'gc_probability',
  278. 'lazy_write', 'name', 'referer_check',
  279. 'serialize_handler', 'use_strict_mode', 'use_cookies',
  280. 'use_only_cookies', 'use_trans_sid',
  281. 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags',
  282. ]);
  283. foreach ($options as $key => $value) {
  284. if (isset($validOptions[$key])) {
  285. if ('cookie_secure' === $key && 'auto' === $value) {
  286. continue;
  287. }
  288. ini_set('session.'.$key, $value);
  289. }
  290. }
  291. }
  292. /**
  293. * Registers session save handler as a PHP session handler.
  294. *
  295. * To use internal PHP session save handlers, override this method using ini_set with
  296. * session.save_handler and session.save_path e.g.
  297. *
  298. * ini_set('session.save_handler', 'files');
  299. * ini_set('session.save_path', '/tmp');
  300. *
  301. * or pass in a \SessionHandler instance which configures session.save_handler in the
  302. * constructor, for a template see NativeFileSessionHandler.
  303. *
  304. * @see https://php.net/session-set-save-handler
  305. * @see https://php.net/sessionhandlerinterface
  306. * @see https://php.net/sessionhandler
  307. *
  308. * @throws \InvalidArgumentException
  309. */
  310. public function setSaveHandler(AbstractProxy|\SessionHandlerInterface|null $saveHandler): void
  311. {
  312. // Wrap $saveHandler in proxy and prevent double wrapping of proxy
  313. if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  314. $saveHandler = new SessionHandlerProxy($saveHandler);
  315. } elseif (!$saveHandler instanceof AbstractProxy) {
  316. $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
  317. }
  318. $this->saveHandler = $saveHandler;
  319. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  320. return;
  321. }
  322. if ($this->saveHandler instanceof SessionHandlerProxy) {
  323. session_set_save_handler($this->saveHandler, false);
  324. }
  325. }
  326. /**
  327. * Load the session with attributes.
  328. *
  329. * After starting the session, PHP retrieves the session from whatever handlers
  330. * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
  331. * PHP takes the return value from the read() handler, unserializes it
  332. * and populates $_SESSION with the result automatically.
  333. */
  334. protected function loadSession(?array &$session = null): void
  335. {
  336. if (null === $session) {
  337. $session = &$_SESSION;
  338. }
  339. $bags = array_merge($this->bags, [$this->metadataBag]);
  340. foreach ($bags as $bag) {
  341. $key = $bag->getStorageKey();
  342. $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : [];
  343. $bag->initialize($session[$key]);
  344. }
  345. $this->started = true;
  346. $this->closed = false;
  347. }
  348. }