PdoSessionHandler.php 38 KB

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