Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php

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