NativeSessionStorage.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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|null $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. public function start(): bool
  107. {
  108. if ($this->started) {
  109. return true;
  110. }
  111. if (\PHP_SESSION_ACTIVE === session_status()) {
  112. throw new \RuntimeException('Failed to start the session: already started by PHP.');
  113. }
  114. if (filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOL) && headers_sent($file, $line)) {
  115. throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
  116. }
  117. $sessionId = $_COOKIE[session_name()] ?? null;
  118. /*
  119. * Explanation of the session ID regular expression: `/^[a-zA-Z0-9,-]{22,250}$/`.
  120. *
  121. * ---------- Part 1
  122. *
  123. * The part `[a-zA-Z0-9,-]` is related to the PHP ini directive `session.sid_bits_per_character` defined as 6.
  124. * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-bits-per-character.
  125. * Allowed values are integers such as:
  126. * - 4 for range `a-f0-9`
  127. * - 5 for range `a-v0-9`
  128. * - 6 for range `a-zA-Z0-9,-`
  129. *
  130. * ---------- Part 2
  131. *
  132. * The part `{22,250}` is related to the PHP ini directive `session.sid_length`.
  133. * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-length.
  134. * Allowed values are integers between 22 and 256, but we use 250 for the max.
  135. *
  136. * Where does the 250 come from?
  137. * - The length of Windows and Linux filenames is limited to 255 bytes. Then the max must not exceed 255.
  138. * - The session filename prefix is `sess_`, a 5 bytes string. Then the max must not exceed 255 - 5 = 250.
  139. *
  140. * ---------- Conclusion
  141. *
  142. * The parts 1 and 2 prevent the warning below:
  143. * `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.`
  144. *
  145. * The part 2 prevents the warning below:
  146. * `PHP Warning: SessionHandler::read(): open(filepath, O_RDWR) failed: No such file or directory (2).`
  147. */
  148. if ($sessionId && $this->saveHandler instanceof AbstractProxy && 'files' === $this->saveHandler->getSaveHandlerName() && !preg_match('/^[a-zA-Z0-9,-]{22,250}$/', $sessionId)) {
  149. // the session ID in the header is invalid, create a new one
  150. session_id(session_create_id());
  151. }
  152. // ok to try and start the session
  153. if (!session_start()) {
  154. throw new \RuntimeException('Failed to start the session.');
  155. }
  156. $this->loadSession();
  157. return true;
  158. }
  159. public function getId(): string
  160. {
  161. return $this->saveHandler->getId();
  162. }
  163. /**
  164. * @return void
  165. */
  166. public function setId(string $id)
  167. {
  168. $this->saveHandler->setId($id);
  169. }
  170. public function getName(): string
  171. {
  172. return $this->saveHandler->getName();
  173. }
  174. /**
  175. * @return void
  176. */
  177. public function setName(string $name)
  178. {
  179. $this->saveHandler->setName($name);
  180. }
  181. public function regenerate(bool $destroy = false, ?int $lifetime = null): bool
  182. {
  183. // Cannot regenerate the session ID for non-active sessions.
  184. if (\PHP_SESSION_ACTIVE !== session_status()) {
  185. return false;
  186. }
  187. if (headers_sent()) {
  188. return false;
  189. }
  190. if (null !== $lifetime && $lifetime != \ini_get('session.cookie_lifetime')) {
  191. $this->save();
  192. ini_set('session.cookie_lifetime', $lifetime);
  193. $this->start();
  194. }
  195. if ($destroy) {
  196. $this->metadataBag->stampNew();
  197. }
  198. return session_regenerate_id($destroy);
  199. }
  200. /**
  201. * @return void
  202. */
  203. public function save()
  204. {
  205. // Store a copy so we can restore the bags in case the session was not left empty
  206. $session = $_SESSION;
  207. foreach ($this->bags as $bag) {
  208. if (empty($_SESSION[$key = $bag->getStorageKey()])) {
  209. unset($_SESSION[$key]);
  210. }
  211. }
  212. if ($_SESSION && [$key = $this->metadataBag->getStorageKey()] === array_keys($_SESSION)) {
  213. unset($_SESSION[$key]);
  214. }
  215. // Register error handler to add information about the current save handler
  216. $previousHandler = set_error_handler(function ($type, $msg, $file, $line) use (&$previousHandler) {
  217. if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) {
  218. $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
  219. $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', $handler::class);
  220. }
  221. return $previousHandler ? $previousHandler($type, $msg, $file, $line) : false;
  222. });
  223. try {
  224. session_write_close();
  225. } finally {
  226. restore_error_handler();
  227. // Restore only if not empty
  228. if ($_SESSION) {
  229. $_SESSION = $session;
  230. }
  231. }
  232. $this->closed = true;
  233. $this->started = false;
  234. }
  235. /**
  236. * @return void
  237. */
  238. public function clear()
  239. {
  240. // clear out the bags
  241. foreach ($this->bags as $bag) {
  242. $bag->clear();
  243. }
  244. // clear out the session
  245. $_SESSION = [];
  246. // reconnect the bags to the session
  247. $this->loadSession();
  248. }
  249. /**
  250. * @return void
  251. */
  252. public function registerBag(SessionBagInterface $bag)
  253. {
  254. if ($this->started) {
  255. throw new \LogicException('Cannot register a bag when the session is already started.');
  256. }
  257. $this->bags[$bag->getName()] = $bag;
  258. }
  259. public function getBag(string $name): SessionBagInterface
  260. {
  261. if (!isset($this->bags[$name])) {
  262. throw new \InvalidArgumentException(sprintf('The SessionBagInterface "%s" is not registered.', $name));
  263. }
  264. if (!$this->started && $this->saveHandler->isActive()) {
  265. $this->loadSession();
  266. } elseif (!$this->started) {
  267. $this->start();
  268. }
  269. return $this->bags[$name];
  270. }
  271. /**
  272. * @return void
  273. */
  274. public function setMetadataBag(?MetadataBag $metaBag = null)
  275. {
  276. if (1 > \func_num_args()) {
  277. trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
  278. }
  279. $this->metadataBag = $metaBag ?? new MetadataBag();
  280. }
  281. /**
  282. * Gets the MetadataBag.
  283. */
  284. public function getMetadataBag(): MetadataBag
  285. {
  286. return $this->metadataBag;
  287. }
  288. public function isStarted(): bool
  289. {
  290. return $this->started;
  291. }
  292. /**
  293. * Sets session.* ini variables.
  294. *
  295. * For convenience we omit 'session.' from the beginning of the keys.
  296. * Explicitly ignores other ini keys.
  297. *
  298. * @param array $options Session ini directives [key => value]
  299. *
  300. * @see https://php.net/session.configuration
  301. *
  302. * @return void
  303. */
  304. public function setOptions(array $options)
  305. {
  306. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  307. return;
  308. }
  309. $validOptions = array_flip([
  310. 'cache_expire', 'cache_limiter', 'cookie_domain', 'cookie_httponly',
  311. 'cookie_lifetime', 'cookie_path', 'cookie_secure', 'cookie_samesite',
  312. 'gc_divisor', 'gc_maxlifetime', 'gc_probability',
  313. 'lazy_write', 'name', 'referer_check',
  314. 'serialize_handler', 'use_strict_mode', 'use_cookies',
  315. 'use_only_cookies', 'use_trans_sid',
  316. 'sid_length', 'sid_bits_per_character', 'trans_sid_hosts', 'trans_sid_tags',
  317. ]);
  318. foreach ($options as $key => $value) {
  319. if (isset($validOptions[$key])) {
  320. if ('cookie_secure' === $key && 'auto' === $value) {
  321. continue;
  322. }
  323. ini_set('session.'.$key, $value);
  324. }
  325. }
  326. }
  327. /**
  328. * Registers session save handler as a PHP session handler.
  329. *
  330. * To use internal PHP session save handlers, override this method using ini_set with
  331. * session.save_handler and session.save_path e.g.
  332. *
  333. * ini_set('session.save_handler', 'files');
  334. * ini_set('session.save_path', '/tmp');
  335. *
  336. * or pass in a \SessionHandler instance which configures session.save_handler in the
  337. * constructor, for a template see NativeFileSessionHandler.
  338. *
  339. * @see https://php.net/session-set-save-handler
  340. * @see https://php.net/sessionhandlerinterface
  341. * @see https://php.net/sessionhandler
  342. *
  343. * @return void
  344. *
  345. * @throws \InvalidArgumentException
  346. */
  347. public function setSaveHandler(AbstractProxy|\SessionHandlerInterface|null $saveHandler = null)
  348. {
  349. if (1 > \func_num_args()) {
  350. trigger_deprecation('symfony/http-foundation', '6.2', 'Calling "%s()" without any arguments is deprecated, pass null explicitly instead.', __METHOD__);
  351. }
  352. // Wrap $saveHandler in proxy and prevent double wrapping of proxy
  353. if (!$saveHandler instanceof AbstractProxy && $saveHandler instanceof \SessionHandlerInterface) {
  354. $saveHandler = new SessionHandlerProxy($saveHandler);
  355. } elseif (!$saveHandler instanceof AbstractProxy) {
  356. $saveHandler = new SessionHandlerProxy(new StrictSessionHandler(new \SessionHandler()));
  357. }
  358. $this->saveHandler = $saveHandler;
  359. if (headers_sent() || \PHP_SESSION_ACTIVE === session_status()) {
  360. return;
  361. }
  362. if ($this->saveHandler instanceof SessionHandlerProxy) {
  363. session_set_save_handler($this->saveHandler, false);
  364. }
  365. }
  366. /**
  367. * Load the session with attributes.
  368. *
  369. * After starting the session, PHP retrieves the session from whatever handlers
  370. * are set to (either PHP's internal, or a custom save handler set with session_set_save_handler()).
  371. * PHP takes the return value from the read() handler, unserializes it
  372. * and populates $_SESSION with the result automatically.
  373. *
  374. * @return void
  375. */
  376. protected function loadSession(?array &$session = null)
  377. {
  378. if (null === $session) {
  379. $session = &$_SESSION;
  380. }
  381. $bags = array_merge($this->bags, [$this->metadataBag]);
  382. foreach ($bags as $bag) {
  383. $key = $bag->getStorageKey();
  384. $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : [];
  385. $bag->initialize($session[$key]);
  386. }
  387. $this->started = true;
  388. $this->closed = false;
  389. }
  390. }