PdoSessionHandler.php 39 KB

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