PdoSessionHandler.php 35 KB

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