PdoSessionHandler.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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\Handler;
  11. /**
  12. * Session handler using a PDO connection to read and write data.
  13. *
  14. * It works with MySQL, PostgreSQL, Oracle, SQL Server and SQLite and implements
  15. * different locking strategies to handle concurrent access to the same session.
  16. * Locking is necessary to prevent loss of data due to race conditions and to keep
  17. * the session data consistent between read() and write(). With locking, requests
  18. * for the same session will wait until the other one finished writing. For this
  19. * reason it's best practice to close a session as early as possible to improve
  20. * concurrency. PHPs internal files session handler also implements locking.
  21. *
  22. * Attention: Since SQLite does not support row level locks but locks the whole database,
  23. * it means only one session can be accessed at a time. Even different sessions would wait
  24. * for another to finish. So saving session in SQLite should only be considered for
  25. * development or prototypes.
  26. *
  27. * Session data is a binary string that can contain non-printable characters like the null byte.
  28. * For this reason it must be saved in a binary column in the database like BLOB in MySQL.
  29. * Saving it in a character column could corrupt the data. You can use createTable()
  30. * to initialize a correctly defined table.
  31. *
  32. * @see https://php.net/sessionhandlerinterface
  33. *
  34. * @author Fabien Potencier <fabien@symfony.com>
  35. * @author Michael Williams <michael.williams@funsational.com>
  36. * @author Tobias Schultze <http://tobion.de>
  37. */
  38. class PdoSessionHandler extends AbstractSessionHandler
  39. {
  40. /**
  41. * No locking is done. This means sessions are prone to loss of data due to
  42. * race conditions of concurrent requests to the same session. The last session
  43. * write will win in this case. It might be useful when you implement your own
  44. * logic to deal with this like an optimistic approach.
  45. */
  46. public const LOCK_NONE = 0;
  47. /**
  48. * Creates an application-level lock on a session. The disadvantage is that the
  49. * lock is not enforced by the database and thus other, unaware parts of the
  50. * application could still concurrently modify the session. The advantage is it
  51. * does not require a transaction.
  52. * This mode is not available for SQLite and not yet implemented for oci and sqlsrv.
  53. */
  54. public const LOCK_ADVISORY = 1;
  55. /**
  56. * Issues a real row lock. Since it uses a transaction between opening and
  57. * closing a session, you have to be careful when you use same database connection
  58. * that you also use for your application logic. This mode is the default because
  59. * it's the only reliable solution across DBMSs.
  60. */
  61. public const LOCK_TRANSACTIONAL = 2;
  62. private const MAX_LIFETIME = 315576000;
  63. /**
  64. * @var \PDO|null PDO instance or null when not connected yet
  65. */
  66. private $pdo;
  67. /**
  68. * @var string|false|null DSN string or null for session.save_path or false when lazy connection disabled
  69. */
  70. private $dsn = false;
  71. /**
  72. * @var string Database driver
  73. */
  74. private $driver;
  75. /**
  76. * @var string Table name
  77. */
  78. private $table = 'sessions';
  79. /**
  80. * @var string Column for session id
  81. */
  82. private $idCol = 'sess_id';
  83. /**
  84. * @var string Column for session data
  85. */
  86. private $dataCol = 'sess_data';
  87. /**
  88. * @var string Column for lifetime
  89. */
  90. private $lifetimeCol = 'sess_lifetime';
  91. /**
  92. * @var string Column for timestamp
  93. */
  94. private $timeCol = 'sess_time';
  95. /**
  96. * @var string Username when lazy-connect
  97. */
  98. private $username = '';
  99. /**
  100. * @var string Password when lazy-connect
  101. */
  102. private $password = '';
  103. /**
  104. * @var array Connection options when lazy-connect
  105. */
  106. private $connectionOptions = [];
  107. /**
  108. * @var int The strategy for locking, see constants
  109. */
  110. private $lockMode = self::LOCK_TRANSACTIONAL;
  111. /**
  112. * It's an array to support multiple reads before closing which is manual, non-standard usage.
  113. *
  114. * @var \PDOStatement[] An array of statements to release advisory locks
  115. */
  116. private $unlockStatements = [];
  117. /**
  118. * @var bool True when the current session exists but expired according to session.gc_maxlifetime
  119. */
  120. private $sessionExpired = false;
  121. /**
  122. * @var bool Whether a transaction is active
  123. */
  124. private $inTransaction = false;
  125. /**
  126. * @var bool Whether gc() has been called
  127. */
  128. private $gcCalled = false;
  129. /**
  130. * You can either pass an existing database connection as PDO instance or
  131. * pass a DSN string that will be used to lazy-connect to the database
  132. * when the session is actually used. Furthermore it's possible to pass null
  133. * which will then use the session.save_path ini setting as PDO DSN parameter.
  134. *
  135. * List of available options:
  136. * * db_table: The name of the table [default: sessions]
  137. * * db_id_col: The column where to store the session id [default: sess_id]
  138. * * db_data_col: The column where to store the session data [default: sess_data]
  139. * * db_lifetime_col: The column where to store the lifetime [default: sess_lifetime]
  140. * * db_time_col: The column where to store the timestamp [default: sess_time]
  141. * * db_username: The username when lazy-connect [default: '']
  142. * * db_password: The password when lazy-connect [default: '']
  143. * * db_connection_options: An array of driver-specific connection options [default: []]
  144. * * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL]
  145. *
  146. * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null
  147. *
  148. * @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
  149. */
  150. public function __construct($pdoOrDsn = null, array $options = [])
  151. {
  152. if ($pdoOrDsn instanceof \PDO) {
  153. if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
  154. throw new \InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)).', __CLASS__));
  155. }
  156. $this->pdo = $pdoOrDsn;
  157. $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
  158. } elseif (\is_string($pdoOrDsn) && str_contains($pdoOrDsn, '://')) {
  159. $this->dsn = $this->buildDsnFromUrl($pdoOrDsn);
  160. } else {
  161. $this->dsn = $pdoOrDsn;
  162. }
  163. $this->table = $options['db_table'] ?? $this->table;
  164. $this->idCol = $options['db_id_col'] ?? $this->idCol;
  165. $this->dataCol = $options['db_data_col'] ?? $this->dataCol;
  166. $this->lifetimeCol = $options['db_lifetime_col'] ?? $this->lifetimeCol;
  167. $this->timeCol = $options['db_time_col'] ?? $this->timeCol;
  168. $this->username = $options['db_username'] ?? $this->username;
  169. $this->password = $options['db_password'] ?? $this->password;
  170. $this->connectionOptions = $options['db_connection_options'] ?? $this->connectionOptions;
  171. $this->lockMode = $options['lock_mode'] ?? $this->lockMode;
  172. }
  173. /**
  174. * Creates the table to store sessions which can be called once for setup.
  175. *
  176. * Session ID is saved in a column of maximum length 128 because that is enough even
  177. * for a 512 bit configured session.hash_function like Whirlpool. Session data is
  178. * saved in a BLOB. One could also use a shorter inlined varbinary column
  179. * if one was sure the data fits into it.
  180. *
  181. * @throws \PDOException When the table already exists
  182. * @throws \DomainException When an unsupported PDO driver is used
  183. */
  184. public function createTable()
  185. {
  186. // connect if we are not yet
  187. $this->getConnection();
  188. switch ($this->driver) {
  189. case 'mysql':
  190. // We use varbinary for the ID column because it prevents unwanted conversions:
  191. // - character set conversions between server and client
  192. // - trailing space removal
  193. // - case-insensitivity
  194. // - language processing like é == e
  195. $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB";
  196. break;
  197. case 'sqlite':
  198. $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
  199. break;
  200. case 'pgsql':
  201. $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
  202. break;
  203. case 'oci':
  204. $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
  205. break;
  206. case 'sqlsrv':
  207. $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
  208. break;
  209. default:
  210. throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver));
  211. }
  212. try {
  213. $this->pdo->exec($sql);
  214. $this->pdo->exec("CREATE INDEX EXPIRY ON $this->table ($this->lifetimeCol)");
  215. } catch (\PDOException $e) {
  216. $this->rollback();
  217. throw $e;
  218. }
  219. }
  220. /**
  221. * Returns true when the current session exists but expired according to session.gc_maxlifetime.
  222. *
  223. * Can be used to distinguish between a new session and one that expired due to inactivity.
  224. *
  225. * @return bool Whether current session expired
  226. */
  227. public function isSessionExpired()
  228. {
  229. return $this->sessionExpired;
  230. }
  231. /**
  232. * @return bool
  233. */
  234. #[\ReturnTypeWillChange]
  235. public function open($savePath, $sessionName)
  236. {
  237. $this->sessionExpired = false;
  238. if (null === $this->pdo) {
  239. $this->connect($this->dsn ?: $savePath);
  240. }
  241. return parent::open($savePath, $sessionName);
  242. }
  243. /**
  244. * @return string
  245. */
  246. #[\ReturnTypeWillChange]
  247. public function read($sessionId)
  248. {
  249. try {
  250. return parent::read($sessionId);
  251. } catch (\PDOException $e) {
  252. $this->rollback();
  253. throw $e;
  254. }
  255. }
  256. /**
  257. * @return int|false
  258. */
  259. #[\ReturnTypeWillChange]
  260. public function gc($maxlifetime)
  261. {
  262. // We delay gc() to close() so that it is executed outside the transactional and blocking read-write process.
  263. // This way, pruning expired sessions does not block them from being started while the current session is used.
  264. $this->gcCalled = true;
  265. return 0;
  266. }
  267. /**
  268. * {@inheritdoc}
  269. */
  270. protected function doDestroy(string $sessionId)
  271. {
  272. // delete the record associated with this id
  273. $sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
  274. try {
  275. $stmt = $this->pdo->prepare($sql);
  276. $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  277. $stmt->execute();
  278. } catch (\PDOException $e) {
  279. $this->rollback();
  280. throw $e;
  281. }
  282. return true;
  283. }
  284. /**
  285. * {@inheritdoc}
  286. */
  287. protected function doWrite(string $sessionId, string $data)
  288. {
  289. $maxlifetime = (int) ini_get('session.gc_maxlifetime');
  290. try {
  291. // We use a single MERGE SQL query when supported by the database.
  292. $mergeStmt = $this->getMergeStatement($sessionId, $data, $maxlifetime);
  293. if (null !== $mergeStmt) {
  294. $mergeStmt->execute();
  295. return true;
  296. }
  297. $updateStmt = $this->getUpdateStatement($sessionId, $data, $maxlifetime);
  298. $updateStmt->execute();
  299. // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in
  300. // duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior).
  301. // We can just catch such an error and re-execute the update. This is similar to a serializable
  302. // transaction with retry logic on serialization failures but without the overhead and without possible
  303. // false positives due to longer gap locking.
  304. if (!$updateStmt->rowCount()) {
  305. try {
  306. $insertStmt = $this->getInsertStatement($sessionId, $data, $maxlifetime);
  307. $insertStmt->execute();
  308. } catch (\PDOException $e) {
  309. // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
  310. if (str_starts_with($e->getCode(), '23')) {
  311. $updateStmt->execute();
  312. } else {
  313. throw $e;
  314. }
  315. }
  316. }
  317. } catch (\PDOException $e) {
  318. $this->rollback();
  319. throw $e;
  320. }
  321. return true;
  322. }
  323. /**
  324. * @return bool
  325. */
  326. #[\ReturnTypeWillChange]
  327. public function updateTimestamp($sessionId, $data)
  328. {
  329. $expiry = time() + (int) ini_get('session.gc_maxlifetime');
  330. try {
  331. $updateStmt = $this->pdo->prepare(
  332. "UPDATE $this->table SET $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id"
  333. );
  334. $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  335. $updateStmt->bindParam(':expiry', $expiry, \PDO::PARAM_INT);
  336. $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  337. $updateStmt->execute();
  338. } catch (\PDOException $e) {
  339. $this->rollback();
  340. throw $e;
  341. }
  342. return true;
  343. }
  344. /**
  345. * @return bool
  346. */
  347. #[\ReturnTypeWillChange]
  348. public function close()
  349. {
  350. $this->commit();
  351. while ($unlockStmt = array_shift($this->unlockStatements)) {
  352. $unlockStmt->execute();
  353. }
  354. if ($this->gcCalled) {
  355. $this->gcCalled = false;
  356. // delete the session records that have expired
  357. $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time AND $this->lifetimeCol > :min";
  358. $stmt = $this->pdo->prepare($sql);
  359. $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
  360. $stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT);
  361. $stmt->execute();
  362. // to be removed in 6.0
  363. if ('mysql' === $this->driver) {
  364. $legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol + $this->timeCol < :time";
  365. } else {
  366. $legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol < :time - $this->timeCol";
  367. }
  368. $stmt = $this->pdo->prepare($legacySql);
  369. $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
  370. $stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT);
  371. $stmt->execute();
  372. }
  373. if (false !== $this->dsn) {
  374. $this->pdo = null; // only close lazy-connection
  375. }
  376. return true;
  377. }
  378. /**
  379. * Lazy-connects to the database.
  380. */
  381. private function connect(string $dsn): void
  382. {
  383. $this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions);
  384. $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  385. $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
  386. }
  387. /**
  388. * Builds a PDO DSN from a URL-like connection string.
  389. *
  390. * @todo implement missing support for oci DSN (which look totally different from other PDO ones)
  391. */
  392. private function buildDsnFromUrl(string $dsnOrUrl): string
  393. {
  394. // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
  395. $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $dsnOrUrl);
  396. $params = parse_url($url);
  397. if (false === $params) {
  398. return $dsnOrUrl; // If the URL is not valid, let's assume it might be a DSN already.
  399. }
  400. $params = array_map('rawurldecode', $params);
  401. // Override the default username and password. Values passed through options will still win over these in the constructor.
  402. if (isset($params['user'])) {
  403. $this->username = $params['user'];
  404. }
  405. if (isset($params['pass'])) {
  406. $this->password = $params['pass'];
  407. }
  408. if (!isset($params['scheme'])) {
  409. throw new \InvalidArgumentException('URLs without scheme are not supported to configure the PdoSessionHandler.');
  410. }
  411. $driverAliasMap = [
  412. 'mssql' => 'sqlsrv',
  413. 'mysql2' => 'mysql', // Amazon RDS, for some weird reason
  414. 'postgres' => 'pgsql',
  415. 'postgresql' => 'pgsql',
  416. 'sqlite3' => 'sqlite',
  417. ];
  418. $driver = $driverAliasMap[$params['scheme']] ?? $params['scheme'];
  419. // Doctrine DBAL supports passing its internal pdo_* driver names directly too (allowing both dashes and underscores). This allows supporting the same here.
  420. if (str_starts_with($driver, 'pdo_') || str_starts_with($driver, 'pdo-')) {
  421. $driver = substr($driver, 4);
  422. }
  423. $dsn = null;
  424. switch ($driver) {
  425. case 'mysql':
  426. $dsn = 'mysql:';
  427. if ('' !== ($params['query'] ?? '')) {
  428. $queryParams = [];
  429. parse_str($params['query'], $queryParams);
  430. if ('' !== ($queryParams['charset'] ?? '')) {
  431. $dsn .= 'charset='.$queryParams['charset'].';';
  432. }
  433. if ('' !== ($queryParams['unix_socket'] ?? '')) {
  434. $dsn .= 'unix_socket='.$queryParams['unix_socket'].';';
  435. if (isset($params['path'])) {
  436. $dbName = substr($params['path'], 1); // Remove the leading slash
  437. $dsn .= 'dbname='.$dbName.';';
  438. }
  439. return $dsn;
  440. }
  441. }
  442. // If "unix_socket" is not in the query, we continue with the same process as pgsql
  443. // no break
  444. case 'pgsql':
  445. $dsn ?? $dsn = 'pgsql:';
  446. if (isset($params['host']) && '' !== $params['host']) {
  447. $dsn .= 'host='.$params['host'].';';
  448. }
  449. if (isset($params['port']) && '' !== $params['port']) {
  450. $dsn .= 'port='.$params['port'].';';
  451. }
  452. if (isset($params['path'])) {
  453. $dbName = substr($params['path'], 1); // Remove the leading slash
  454. $dsn .= 'dbname='.$dbName.';';
  455. }
  456. return $dsn;
  457. case 'sqlite':
  458. return 'sqlite:'.substr($params['path'], 1);
  459. case 'sqlsrv':
  460. $dsn = 'sqlsrv:server=';
  461. if (isset($params['host'])) {
  462. $dsn .= $params['host'];
  463. }
  464. if (isset($params['port']) && '' !== $params['port']) {
  465. $dsn .= ','.$params['port'];
  466. }
  467. if (isset($params['path'])) {
  468. $dbName = substr($params['path'], 1); // Remove the leading slash
  469. $dsn .= ';Database='.$dbName;
  470. }
  471. return $dsn;
  472. default:
  473. throw new \InvalidArgumentException(sprintf('The scheme "%s" is not supported by the PdoSessionHandler URL configuration. Pass a PDO DSN directly.', $params['scheme']));
  474. }
  475. }
  476. /**
  477. * Helper method to begin a transaction.
  478. *
  479. * Since SQLite does not support row level locks, we have to acquire a reserved lock
  480. * on the database immediately. Because of https://bugs.php.net/42766 we have to create
  481. * such a transaction manually which also means we cannot use PDO::commit or
  482. * PDO::rollback or PDO::inTransaction for SQLite.
  483. *
  484. * Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions
  485. * due to https://percona.com/blog/2013/12/12/one-more-innodb-gap-lock-to-avoid/ .
  486. * So we change it to READ COMMITTED.
  487. */
  488. private function beginTransaction(): void
  489. {
  490. if (!$this->inTransaction) {
  491. if ('sqlite' === $this->driver) {
  492. $this->pdo->exec('BEGIN IMMEDIATE TRANSACTION');
  493. } else {
  494. if ('mysql' === $this->driver) {
  495. $this->pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
  496. }
  497. $this->pdo->beginTransaction();
  498. }
  499. $this->inTransaction = true;
  500. }
  501. }
  502. /**
  503. * Helper method to commit a transaction.
  504. */
  505. private function commit(): void
  506. {
  507. if ($this->inTransaction) {
  508. try {
  509. // commit read-write transaction which also releases the lock
  510. if ('sqlite' === $this->driver) {
  511. $this->pdo->exec('COMMIT');
  512. } else {
  513. $this->pdo->commit();
  514. }
  515. $this->inTransaction = false;
  516. } catch (\PDOException $e) {
  517. $this->rollback();
  518. throw $e;
  519. }
  520. }
  521. }
  522. /**
  523. * Helper method to rollback a transaction.
  524. */
  525. private function rollback(): void
  526. {
  527. // We only need to rollback if we are in a transaction. Otherwise the resulting
  528. // error would hide the real problem why rollback was called. We might not be
  529. // in a transaction when not using the transactional locking behavior or when
  530. // two callbacks (e.g. destroy and write) are invoked that both fail.
  531. if ($this->inTransaction) {
  532. if ('sqlite' === $this->driver) {
  533. $this->pdo->exec('ROLLBACK');
  534. } else {
  535. $this->pdo->rollBack();
  536. }
  537. $this->inTransaction = false;
  538. }
  539. }
  540. /**
  541. * Reads the session data in respect to the different locking strategies.
  542. *
  543. * We need to make sure we do not return session data that is already considered garbage according
  544. * to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes.
  545. *
  546. * @return string
  547. */
  548. protected function doRead(string $sessionId)
  549. {
  550. if (self::LOCK_ADVISORY === $this->lockMode) {
  551. $this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
  552. }
  553. $selectSql = $this->getSelectSql();
  554. $selectStmt = $this->pdo->prepare($selectSql);
  555. $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  556. $insertStmt = null;
  557. do {
  558. $selectStmt->execute();
  559. $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM);
  560. if ($sessionRows) {
  561. $expiry = (int) $sessionRows[0][1];
  562. if ($expiry <= self::MAX_LIFETIME) {
  563. $expiry += $sessionRows[0][2];
  564. }
  565. if ($expiry < time()) {
  566. $this->sessionExpired = true;
  567. return '';
  568. }
  569. return \is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
  570. }
  571. if (null !== $insertStmt) {
  572. $this->rollback();
  573. throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.');
  574. }
  575. if (!filter_var(ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
  576. // In strict mode, session fixation is not possible: new sessions always start with a unique
  577. // random id, so that concurrency is not possible and this code path can be skipped.
  578. // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block
  579. // until other connections to the session are committed.
  580. try {
  581. $insertStmt = $this->getInsertStatement($sessionId, '', 0);
  582. $insertStmt->execute();
  583. } catch (\PDOException $e) {
  584. // Catch duplicate key error because other connection created the session already.
  585. // It would only not be the case when the other connection destroyed the session.
  586. if (str_starts_with($e->getCode(), '23')) {
  587. // Retrieve finished session data written by concurrent connection by restarting the loop.
  588. // We have to start a new transaction as a failed query will mark the current transaction as
  589. // aborted in PostgreSQL and disallow further queries within it.
  590. $this->rollback();
  591. $this->beginTransaction();
  592. continue;
  593. }
  594. throw $e;
  595. }
  596. }
  597. return '';
  598. } while (true);
  599. }
  600. /**
  601. * Executes an application-level lock on the database.
  602. *
  603. * @return \PDOStatement The statement that needs to be executed later to release the lock
  604. *
  605. * @throws \DomainException When an unsupported PDO driver is used
  606. *
  607. * @todo implement missing advisory locks
  608. * - for oci using DBMS_LOCK.REQUEST
  609. * - for sqlsrv using sp_getapplock with LockOwner = Session
  610. */
  611. private function doAdvisoryLock(string $sessionId): \PDOStatement
  612. {
  613. switch ($this->driver) {
  614. case 'mysql':
  615. // MySQL 5.7.5 and later enforces a maximum length on lock names of 64 characters. Previously, no limit was enforced.
  616. $lockId = substr($sessionId, 0, 64);
  617. // should we handle the return value? 0 on timeout, null on error
  618. // we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout
  619. $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)');
  620. $stmt->bindValue(':key', $lockId, \PDO::PARAM_STR);
  621. $stmt->execute();
  622. $releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)');
  623. $releaseStmt->bindValue(':key', $lockId, \PDO::PARAM_STR);
  624. return $releaseStmt;
  625. case 'pgsql':
  626. // Obtaining an exclusive session level advisory lock requires an integer key.
  627. // When session.sid_bits_per_character > 4, the session id can contain non-hex-characters.
  628. // So we cannot just use hexdec().
  629. if (4 === \PHP_INT_SIZE) {
  630. $sessionInt1 = $this->convertStringToInt($sessionId);
  631. $sessionInt2 = $this->convertStringToInt(substr($sessionId, 4, 4));
  632. $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)');
  633. $stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
  634. $stmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
  635. $stmt->execute();
  636. $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key1, :key2)');
  637. $releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
  638. $releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
  639. } else {
  640. $sessionBigInt = $this->convertStringToInt($sessionId);
  641. $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)');
  642. $stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
  643. $stmt->execute();
  644. $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key)');
  645. $releaseStmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
  646. }
  647. return $releaseStmt;
  648. case 'sqlite':
  649. throw new \DomainException('SQLite does not support advisory locks.');
  650. default:
  651. throw new \DomainException(sprintf('Advisory locks are currently not implemented for PDO driver "%s".', $this->driver));
  652. }
  653. }
  654. /**
  655. * Encodes the first 4 (when PHP_INT_SIZE == 4) or 8 characters of the string as an integer.
  656. *
  657. * Keep in mind, PHP integers are signed.
  658. */
  659. private function convertStringToInt(string $string): int
  660. {
  661. if (4 === \PHP_INT_SIZE) {
  662. return (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
  663. }
  664. $int1 = (\ord($string[7]) << 24) + (\ord($string[6]) << 16) + (\ord($string[5]) << 8) + \ord($string[4]);
  665. $int2 = (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
  666. return $int2 + ($int1 << 32);
  667. }
  668. /**
  669. * Return a locking or nonlocking SQL query to read session information.
  670. *
  671. * @throws \DomainException When an unsupported PDO driver is used
  672. */
  673. private function getSelectSql(): string
  674. {
  675. if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
  676. $this->beginTransaction();
  677. // selecting the time column should be removed in 6.0
  678. switch ($this->driver) {
  679. case 'mysql':
  680. case 'oci':
  681. case 'pgsql':
  682. return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
  683. case 'sqlsrv':
  684. return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
  685. case 'sqlite':
  686. // we already locked when starting transaction
  687. break;
  688. default:
  689. throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver));
  690. }
  691. }
  692. return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id";
  693. }
  694. /**
  695. * Returns an insert statement supported by the database for writing session data.
  696. */
  697. private function getInsertStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement
  698. {
  699. switch ($this->driver) {
  700. case 'oci':
  701. $data = fopen('php://memory', 'r+');
  702. fwrite($data, $sessionData);
  703. rewind($data);
  704. $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, EMPTY_BLOB(), :expiry, :time) RETURNING $this->dataCol into :data";
  705. break;
  706. default:
  707. $data = $sessionData;
  708. $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time)";
  709. break;
  710. }
  711. $stmt = $this->pdo->prepare($sql);
  712. $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  713. $stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  714. $stmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT);
  715. $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
  716. return $stmt;
  717. }
  718. /**
  719. * Returns an update statement supported by the database for writing session data.
  720. */
  721. private function getUpdateStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement
  722. {
  723. switch ($this->driver) {
  724. case 'oci':
  725. $data = fopen('php://memory', 'r+');
  726. fwrite($data, $sessionData);
  727. rewind($data);
  728. $sql = "UPDATE $this->table SET $this->dataCol = EMPTY_BLOB(), $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id RETURNING $this->dataCol into :data";
  729. break;
  730. default:
  731. $data = $sessionData;
  732. $sql = "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id";
  733. break;
  734. }
  735. $stmt = $this->pdo->prepare($sql);
  736. $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  737. $stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  738. $stmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT);
  739. $stmt->bindValue(':time', time(), \PDO::PARAM_INT);
  740. return $stmt;
  741. }
  742. /**
  743. * Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data.
  744. */
  745. private function getMergeStatement(string $sessionId, string $data, int $maxlifetime): ?\PDOStatement
  746. {
  747. switch (true) {
  748. case 'mysql' === $this->driver:
  749. $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time) ".
  750. "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
  751. break;
  752. case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
  753. // MERGE is only available since SQL Server 2008 and must be terminated by semicolon
  754. // It also requires HOLDLOCK according to https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/
  755. $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ".
  756. "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
  757. "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;";
  758. break;
  759. case 'sqlite' === $this->driver:
  760. $mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time)";
  761. break;
  762. case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='):
  763. $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time) ".
  764. "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)";
  765. break;
  766. default:
  767. // MERGE is not supported with LOBs: https://oracle.com/technetwork/articles/fuecks-lobs-095315.html
  768. return null;
  769. }
  770. $mergeStmt = $this->pdo->prepare($mergeSql);
  771. if ('sqlsrv' === $this->driver) {
  772. $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR);
  773. $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR);
  774. $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB);
  775. $mergeStmt->bindValue(4, time() + $maxlifetime, \PDO::PARAM_INT);
  776. $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT);
  777. $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB);
  778. $mergeStmt->bindValue(7, time() + $maxlifetime, \PDO::PARAM_INT);
  779. $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT);
  780. } else {
  781. $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
  782. $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
  783. $mergeStmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT);
  784. $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
  785. }
  786. return $mergeStmt;
  787. }
  788. /**
  789. * Return a PDO instance.
  790. *
  791. * @return \PDO
  792. */
  793. protected function getConnection()
  794. {
  795. if (null === $this->pdo) {
  796. $this->connect($this->dsn ?: ini_get('session.save_path'));
  797. }
  798. return $this->pdo;
  799. }
  800. }