Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; Chris@0: Chris@0: /** Chris@0: * Session handler using a PDO connection to read and write data. Chris@0: * Chris@0: * It works with MySQL, PostgreSQL, Oracle, SQL Server and SQLite and implements Chris@0: * different locking strategies to handle concurrent access to the same session. Chris@0: * Locking is necessary to prevent loss of data due to race conditions and to keep Chris@0: * the session data consistent between read() and write(). With locking, requests Chris@0: * for the same session will wait until the other one finished writing. For this Chris@0: * reason it's best practice to close a session as early as possible to improve Chris@0: * concurrency. PHPs internal files session handler also implements locking. Chris@0: * Chris@0: * Attention: Since SQLite does not support row level locks but locks the whole database, Chris@0: * it means only one session can be accessed at a time. Even different sessions would wait Chris@0: * for another to finish. So saving session in SQLite should only be considered for Chris@0: * development or prototypes. Chris@0: * Chris@0: * Session data is a binary string that can contain non-printable characters like the null byte. Chris@0: * For this reason it must be saved in a binary column in the database like BLOB in MySQL. Chris@0: * Saving it in a character column could corrupt the data. You can use createTable() Chris@0: * to initialize a correctly defined table. Chris@0: * Chris@0: * @see http://php.net/sessionhandlerinterface Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: * @author Michael Williams Chris@0: * @author Tobias Schultze Chris@0: */ Chris@14: class PdoSessionHandler extends AbstractSessionHandler Chris@0: { Chris@0: /** Chris@0: * No locking is done. This means sessions are prone to loss of data due to Chris@0: * race conditions of concurrent requests to the same session. The last session Chris@0: * write will win in this case. It might be useful when you implement your own Chris@0: * logic to deal with this like an optimistic approach. Chris@0: */ Chris@0: const LOCK_NONE = 0; Chris@0: Chris@0: /** Chris@0: * Creates an application-level lock on a session. The disadvantage is that the Chris@0: * lock is not enforced by the database and thus other, unaware parts of the Chris@0: * application could still concurrently modify the session. The advantage is it Chris@0: * does not require a transaction. Chris@0: * This mode is not available for SQLite and not yet implemented for oci and sqlsrv. Chris@0: */ Chris@0: const LOCK_ADVISORY = 1; Chris@0: Chris@0: /** Chris@0: * Issues a real row lock. Since it uses a transaction between opening and Chris@0: * closing a session, you have to be careful when you use same database connection Chris@0: * that you also use for your application logic. This mode is the default because Chris@0: * it's the only reliable solution across DBMSs. Chris@0: */ Chris@0: const LOCK_TRANSACTIONAL = 2; Chris@0: Chris@0: /** Chris@0: * @var \PDO|null PDO instance or null when not connected yet Chris@0: */ Chris@0: private $pdo; Chris@0: Chris@0: /** Chris@17: * @var string|false|null DSN string or null for session.save_path or false when lazy connection disabled Chris@0: */ Chris@0: private $dsn = false; Chris@0: Chris@0: /** Chris@0: * @var string Database driver Chris@0: */ Chris@0: private $driver; Chris@0: Chris@0: /** Chris@0: * @var string Table name Chris@0: */ Chris@0: private $table = 'sessions'; Chris@0: Chris@0: /** Chris@0: * @var string Column for session id Chris@0: */ Chris@0: private $idCol = 'sess_id'; Chris@0: Chris@0: /** Chris@0: * @var string Column for session data Chris@0: */ Chris@0: private $dataCol = 'sess_data'; Chris@0: Chris@0: /** Chris@0: * @var string Column for lifetime Chris@0: */ Chris@0: private $lifetimeCol = 'sess_lifetime'; Chris@0: Chris@0: /** Chris@0: * @var string Column for timestamp Chris@0: */ Chris@0: private $timeCol = 'sess_time'; Chris@0: Chris@0: /** Chris@0: * @var string Username when lazy-connect Chris@0: */ Chris@0: private $username = ''; Chris@0: Chris@0: /** Chris@0: * @var string Password when lazy-connect Chris@0: */ Chris@0: private $password = ''; Chris@0: Chris@0: /** Chris@0: * @var array Connection options when lazy-connect Chris@0: */ Chris@17: private $connectionOptions = []; Chris@0: Chris@0: /** Chris@0: * @var int The strategy for locking, see constants Chris@0: */ Chris@0: private $lockMode = self::LOCK_TRANSACTIONAL; Chris@0: Chris@0: /** Chris@0: * It's an array to support multiple reads before closing which is manual, non-standard usage. Chris@0: * Chris@0: * @var \PDOStatement[] An array of statements to release advisory locks Chris@0: */ Chris@17: private $unlockStatements = []; Chris@0: Chris@0: /** Chris@0: * @var bool True when the current session exists but expired according to session.gc_maxlifetime Chris@0: */ Chris@0: private $sessionExpired = false; Chris@0: Chris@0: /** Chris@0: * @var bool Whether a transaction is active Chris@0: */ Chris@0: private $inTransaction = false; Chris@0: Chris@0: /** Chris@0: * @var bool Whether gc() has been called Chris@0: */ Chris@0: private $gcCalled = false; Chris@0: Chris@0: /** Chris@0: * You can either pass an existing database connection as PDO instance or Chris@0: * pass a DSN string that will be used to lazy-connect to the database Chris@0: * when the session is actually used. Furthermore it's possible to pass null Chris@0: * which will then use the session.save_path ini setting as PDO DSN parameter. Chris@0: * Chris@0: * List of available options: Chris@0: * * db_table: The name of the table [default: sessions] Chris@0: * * db_id_col: The column where to store the session id [default: sess_id] Chris@0: * * db_data_col: The column where to store the session data [default: sess_data] Chris@0: * * db_lifetime_col: The column where to store the lifetime [default: sess_lifetime] Chris@0: * * db_time_col: The column where to store the timestamp [default: sess_time] Chris@0: * * db_username: The username when lazy-connect [default: ''] Chris@0: * * db_password: The password when lazy-connect [default: ''] Chris@17: * * db_connection_options: An array of driver-specific connection options [default: []] Chris@0: * * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL] Chris@0: * Chris@14: * @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null Chris@0: * @param array $options An associative array of options Chris@0: * Chris@0: * @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION Chris@0: */ Chris@17: public function __construct($pdoOrDsn = null, array $options = []) Chris@0: { Chris@0: if ($pdoOrDsn instanceof \PDO) { Chris@0: if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) { Chris@0: 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__)); Chris@0: } Chris@0: Chris@0: $this->pdo = $pdoOrDsn; Chris@0: $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); Chris@17: } elseif (\is_string($pdoOrDsn) && false !== strpos($pdoOrDsn, '://')) { Chris@14: $this->dsn = $this->buildDsnFromUrl($pdoOrDsn); Chris@0: } else { Chris@0: $this->dsn = $pdoOrDsn; Chris@0: } Chris@0: Chris@0: $this->table = isset($options['db_table']) ? $options['db_table'] : $this->table; Chris@0: $this->idCol = isset($options['db_id_col']) ? $options['db_id_col'] : $this->idCol; Chris@0: $this->dataCol = isset($options['db_data_col']) ? $options['db_data_col'] : $this->dataCol; Chris@0: $this->lifetimeCol = isset($options['db_lifetime_col']) ? $options['db_lifetime_col'] : $this->lifetimeCol; Chris@0: $this->timeCol = isset($options['db_time_col']) ? $options['db_time_col'] : $this->timeCol; Chris@0: $this->username = isset($options['db_username']) ? $options['db_username'] : $this->username; Chris@0: $this->password = isset($options['db_password']) ? $options['db_password'] : $this->password; Chris@0: $this->connectionOptions = isset($options['db_connection_options']) ? $options['db_connection_options'] : $this->connectionOptions; Chris@0: $this->lockMode = isset($options['lock_mode']) ? $options['lock_mode'] : $this->lockMode; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates the table to store sessions which can be called once for setup. Chris@0: * Chris@0: * Session ID is saved in a column of maximum length 128 because that is enough even Chris@0: * for a 512 bit configured session.hash_function like Whirlpool. Session data is Chris@0: * saved in a BLOB. One could also use a shorter inlined varbinary column Chris@0: * if one was sure the data fits into it. Chris@0: * Chris@0: * @throws \PDOException When the table already exists Chris@0: * @throws \DomainException When an unsupported PDO driver is used Chris@0: */ Chris@0: public function createTable() Chris@0: { Chris@0: // connect if we are not yet Chris@0: $this->getConnection(); Chris@0: Chris@0: switch ($this->driver) { Chris@0: case 'mysql': Chris@0: // We use varbinary for the ID column because it prevents unwanted conversions: Chris@0: // - character set conversions between server and client Chris@0: // - trailing space removal Chris@0: // - case-insensitivity Chris@0: // - language processing like é == e Chris@0: $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol MEDIUMINT NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8_bin, ENGINE = InnoDB"; Chris@0: break; Chris@0: case 'sqlite': Chris@0: $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; Chris@0: break; Chris@0: case 'pgsql': Chris@0: $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; Chris@0: break; Chris@0: case 'oci': Chris@0: $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; Chris@0: break; Chris@0: case 'sqlsrv': Chris@0: $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; Chris@0: break; Chris@0: default: Chris@0: throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver)); Chris@0: } Chris@0: Chris@0: try { Chris@0: $this->pdo->exec($sql); Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true when the current session exists but expired according to session.gc_maxlifetime. Chris@0: * Chris@0: * Can be used to distinguish between a new session and one that expired due to inactivity. Chris@0: * Chris@0: * @return bool Whether current session expired Chris@0: */ Chris@0: public function isSessionExpired() Chris@0: { Chris@0: return $this->sessionExpired; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function open($savePath, $sessionName) Chris@0: { Chris@14: $this->sessionExpired = false; Chris@14: Chris@0: if (null === $this->pdo) { Chris@0: $this->connect($this->dsn ?: $savePath); Chris@0: } Chris@0: Chris@14: return parent::open($savePath, $sessionName); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function read($sessionId) Chris@0: { Chris@0: try { Chris@14: return parent::read($sessionId); Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function gc($maxlifetime) Chris@0: { Chris@0: // We delay gc() to close() so that it is executed outside the transactional and blocking read-write process. Chris@0: // This way, pruning expired sessions does not block them from being started while the current session is used. Chris@0: $this->gcCalled = true; Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@14: protected function doDestroy($sessionId) Chris@0: { Chris@0: // delete the record associated with this id Chris@0: $sql = "DELETE FROM $this->table WHERE $this->idCol = :id"; Chris@0: Chris@0: try { Chris@0: $stmt = $this->pdo->prepare($sql); Chris@0: $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@0: $stmt->execute(); Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@14: protected function doWrite($sessionId, $data) Chris@0: { Chris@0: $maxlifetime = (int) ini_get('session.gc_maxlifetime'); Chris@0: Chris@0: try { Chris@0: // We use a single MERGE SQL query when supported by the database. Chris@0: $mergeStmt = $this->getMergeStatement($sessionId, $data, $maxlifetime); Chris@0: if (null !== $mergeStmt) { Chris@0: $mergeStmt->execute(); Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@14: $updateStmt = $this->getUpdateStatement($sessionId, $data, $maxlifetime); Chris@0: $updateStmt->execute(); Chris@0: Chris@0: // When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in Chris@0: // duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior). Chris@0: // We can just catch such an error and re-execute the update. This is similar to a serializable Chris@0: // transaction with retry logic on serialization failures but without the overhead and without possible Chris@0: // false positives due to longer gap locking. Chris@0: if (!$updateStmt->rowCount()) { Chris@0: try { Chris@14: $insertStmt = $this->getInsertStatement($sessionId, $data, $maxlifetime); Chris@0: $insertStmt->execute(); Chris@0: } catch (\PDOException $e) { Chris@0: // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys Chris@0: if (0 === strpos($e->getCode(), '23')) { Chris@0: $updateStmt->execute(); Chris@0: } else { Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: } Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@14: public function updateTimestamp($sessionId, $data) Chris@14: { Chris@14: $maxlifetime = (int) ini_get('session.gc_maxlifetime'); Chris@14: Chris@14: try { Chris@14: $updateStmt = $this->pdo->prepare( Chris@14: "UPDATE $this->table SET $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id" Chris@14: ); Chris@14: $updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@14: $updateStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); Chris@14: $updateStmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@14: $updateStmt->execute(); Chris@14: } catch (\PDOException $e) { Chris@14: $this->rollback(); Chris@14: Chris@14: throw $e; Chris@14: } Chris@14: Chris@14: return true; Chris@14: } Chris@14: Chris@14: /** Chris@14: * {@inheritdoc} Chris@14: */ Chris@0: public function close() Chris@0: { Chris@0: $this->commit(); Chris@0: Chris@0: while ($unlockStmt = array_shift($this->unlockStatements)) { Chris@0: $unlockStmt->execute(); Chris@0: } Chris@0: Chris@0: if ($this->gcCalled) { Chris@0: $this->gcCalled = false; Chris@0: Chris@0: // delete the session records that have expired Chris@14: if ('mysql' === $this->driver) { Chris@14: $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol < :time"; Chris@14: } else { Chris@14: $sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time - $this->timeCol"; Chris@14: } Chris@0: Chris@0: $stmt = $this->pdo->prepare($sql); Chris@0: $stmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@0: $stmt->execute(); Chris@0: } Chris@0: Chris@0: if (false !== $this->dsn) { Chris@0: $this->pdo = null; // only close lazy-connection Chris@0: } Chris@0: Chris@0: return true; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Lazy-connects to the database. Chris@0: * Chris@0: * @param string $dsn DSN string Chris@0: */ Chris@0: private function connect($dsn) Chris@0: { Chris@0: $this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions); Chris@0: $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); Chris@0: $this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME); Chris@0: } Chris@0: Chris@0: /** Chris@14: * Builds a PDO DSN from a URL-like connection string. Chris@14: * Chris@14: * @param string $dsnOrUrl Chris@14: * Chris@14: * @return string Chris@14: * Chris@14: * @todo implement missing support for oci DSN (which look totally different from other PDO ones) Chris@14: */ Chris@14: private function buildDsnFromUrl($dsnOrUrl) Chris@14: { Chris@14: // (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid Chris@14: $url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $dsnOrUrl); Chris@14: Chris@14: $params = parse_url($url); Chris@14: Chris@14: if (false === $params) { Chris@14: return $dsnOrUrl; // If the URL is not valid, let's assume it might be a DSN already. Chris@14: } Chris@14: Chris@14: $params = array_map('rawurldecode', $params); Chris@14: Chris@14: // Override the default username and password. Values passed through options will still win over these in the constructor. Chris@14: if (isset($params['user'])) { Chris@14: $this->username = $params['user']; Chris@14: } Chris@14: Chris@14: if (isset($params['pass'])) { Chris@14: $this->password = $params['pass']; Chris@14: } Chris@14: Chris@14: if (!isset($params['scheme'])) { Chris@14: throw new \InvalidArgumentException('URLs without scheme are not supported to configure the PdoSessionHandler'); Chris@14: } Chris@14: Chris@17: $driverAliasMap = [ Chris@14: 'mssql' => 'sqlsrv', Chris@14: 'mysql2' => 'mysql', // Amazon RDS, for some weird reason Chris@14: 'postgres' => 'pgsql', Chris@14: 'postgresql' => 'pgsql', Chris@14: 'sqlite3' => 'sqlite', Chris@17: ]; Chris@14: Chris@14: $driver = isset($driverAliasMap[$params['scheme']]) ? $driverAliasMap[$params['scheme']] : $params['scheme']; Chris@14: Chris@14: // Doctrine DBAL supports passing its internal pdo_* driver names directly too (allowing both dashes and underscores). This allows supporting the same here. Chris@14: if (0 === strpos($driver, 'pdo_') || 0 === strpos($driver, 'pdo-')) { Chris@14: $driver = substr($driver, 4); Chris@14: } Chris@14: Chris@14: switch ($driver) { Chris@14: case 'mysql': Chris@14: case 'pgsql': Chris@14: $dsn = $driver.':'; Chris@14: Chris@14: if (isset($params['host']) && '' !== $params['host']) { Chris@14: $dsn .= 'host='.$params['host'].';'; Chris@14: } Chris@14: Chris@14: if (isset($params['port']) && '' !== $params['port']) { Chris@14: $dsn .= 'port='.$params['port'].';'; Chris@14: } Chris@14: Chris@14: if (isset($params['path'])) { Chris@14: $dbName = substr($params['path'], 1); // Remove the leading slash Chris@14: $dsn .= 'dbname='.$dbName.';'; Chris@14: } Chris@14: Chris@14: return $dsn; Chris@14: Chris@14: case 'sqlite': Chris@14: return 'sqlite:'.substr($params['path'], 1); Chris@14: Chris@14: case 'sqlsrv': Chris@14: $dsn = 'sqlsrv:server='; Chris@14: Chris@14: if (isset($params['host'])) { Chris@14: $dsn .= $params['host']; Chris@14: } Chris@14: Chris@14: if (isset($params['port']) && '' !== $params['port']) { Chris@14: $dsn .= ','.$params['port']; Chris@14: } Chris@14: Chris@14: if (isset($params['path'])) { Chris@14: $dbName = substr($params['path'], 1); // Remove the leading slash Chris@14: $dsn .= ';Database='.$dbName; Chris@14: } Chris@14: Chris@14: return $dsn; Chris@14: Chris@14: default: Chris@14: throw new \InvalidArgumentException(sprintf('The scheme "%s" is not supported by the PdoSessionHandler URL configuration. Pass a PDO DSN directly.', $params['scheme'])); Chris@14: } Chris@14: } Chris@14: Chris@14: /** Chris@0: * Helper method to begin a transaction. Chris@0: * Chris@0: * Since SQLite does not support row level locks, we have to acquire a reserved lock Chris@0: * on the database immediately. Because of https://bugs.php.net/42766 we have to create Chris@0: * such a transaction manually which also means we cannot use PDO::commit or Chris@0: * PDO::rollback or PDO::inTransaction for SQLite. Chris@0: * Chris@0: * Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions Chris@0: * due to http://www.mysqlperformanceblog.com/2013/12/12/one-more-innodb-gap-lock-to-avoid/ . Chris@0: * So we change it to READ COMMITTED. Chris@0: */ Chris@0: private function beginTransaction() Chris@0: { Chris@0: if (!$this->inTransaction) { Chris@0: if ('sqlite' === $this->driver) { Chris@0: $this->pdo->exec('BEGIN IMMEDIATE TRANSACTION'); Chris@0: } else { Chris@0: if ('mysql' === $this->driver) { Chris@0: $this->pdo->exec('SET TRANSACTION ISOLATION LEVEL READ COMMITTED'); Chris@0: } Chris@0: $this->pdo->beginTransaction(); Chris@0: } Chris@0: $this->inTransaction = true; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper method to commit a transaction. Chris@0: */ Chris@0: private function commit() Chris@0: { Chris@0: if ($this->inTransaction) { Chris@0: try { Chris@0: // commit read-write transaction which also releases the lock Chris@0: if ('sqlite' === $this->driver) { Chris@0: $this->pdo->exec('COMMIT'); Chris@0: } else { Chris@0: $this->pdo->commit(); Chris@0: } Chris@0: $this->inTransaction = false; Chris@0: } catch (\PDOException $e) { Chris@0: $this->rollback(); Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Helper method to rollback a transaction. Chris@0: */ Chris@0: private function rollback() Chris@0: { Chris@0: // We only need to rollback if we are in a transaction. Otherwise the resulting Chris@0: // error would hide the real problem why rollback was called. We might not be Chris@0: // in a transaction when not using the transactional locking behavior or when Chris@0: // two callbacks (e.g. destroy and write) are invoked that both fail. Chris@0: if ($this->inTransaction) { Chris@0: if ('sqlite' === $this->driver) { Chris@0: $this->pdo->exec('ROLLBACK'); Chris@0: } else { Chris@0: $this->pdo->rollBack(); Chris@0: } Chris@0: $this->inTransaction = false; Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Reads the session data in respect to the different locking strategies. Chris@0: * Chris@0: * We need to make sure we do not return session data that is already considered garbage according Chris@0: * to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes. Chris@0: * Chris@0: * @param string $sessionId Session ID Chris@0: * Chris@0: * @return string The session data Chris@0: */ Chris@14: protected function doRead($sessionId) Chris@0: { Chris@0: if (self::LOCK_ADVISORY === $this->lockMode) { Chris@0: $this->unlockStatements[] = $this->doAdvisoryLock($sessionId); Chris@0: } Chris@0: Chris@0: $selectSql = $this->getSelectSql(); Chris@0: $selectStmt = $this->pdo->prepare($selectSql); Chris@0: $selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@16: $insertStmt = null; Chris@0: Chris@0: do { Chris@0: $selectStmt->execute(); Chris@0: $sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM); Chris@0: Chris@0: if ($sessionRows) { Chris@0: if ($sessionRows[0][1] + $sessionRows[0][2] < time()) { Chris@0: $this->sessionExpired = true; Chris@0: Chris@0: return ''; Chris@0: } Chris@0: Chris@17: return \is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0]; Chris@0: } Chris@0: Chris@16: if (null !== $insertStmt) { Chris@16: $this->rollback(); Chris@16: throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.'); Chris@16: } Chris@16: Chris@17: if (!filter_var(ini_get('session.use_strict_mode'), FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) { Chris@14: // In strict mode, session fixation is not possible: new sessions always start with a unique Chris@14: // random id, so that concurrency is not possible and this code path can be skipped. Chris@0: // Exclusive-reading of non-existent rows does not block, so we need to do an insert to block Chris@0: // until other connections to the session are committed. Chris@0: try { Chris@14: $insertStmt = $this->getInsertStatement($sessionId, '', 0); Chris@0: $insertStmt->execute(); Chris@0: } catch (\PDOException $e) { Chris@0: // Catch duplicate key error because other connection created the session already. Chris@0: // It would only not be the case when the other connection destroyed the session. Chris@0: if (0 === strpos($e->getCode(), '23')) { Chris@0: // Retrieve finished session data written by concurrent connection by restarting the loop. Chris@0: // We have to start a new transaction as a failed query will mark the current transaction as Chris@0: // aborted in PostgreSQL and disallow further queries within it. Chris@0: $this->rollback(); Chris@0: $this->beginTransaction(); Chris@0: continue; Chris@0: } Chris@0: Chris@0: throw $e; Chris@0: } Chris@0: } Chris@0: Chris@0: return ''; Chris@0: } while (true); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Executes an application-level lock on the database. Chris@0: * Chris@0: * @param string $sessionId Session ID Chris@0: * Chris@0: * @return \PDOStatement The statement that needs to be executed later to release the lock Chris@0: * Chris@0: * @throws \DomainException When an unsupported PDO driver is used Chris@0: * Chris@0: * @todo implement missing advisory locks Chris@0: * - for oci using DBMS_LOCK.REQUEST Chris@0: * - for sqlsrv using sp_getapplock with LockOwner = Session Chris@0: */ Chris@0: private function doAdvisoryLock($sessionId) Chris@0: { Chris@0: switch ($this->driver) { Chris@0: case 'mysql': Chris@16: // MySQL 5.7.5 and later enforces a maximum length on lock names of 64 characters. Previously, no limit was enforced. Chris@16: $lockId = \substr($sessionId, 0, 64); Chris@0: // should we handle the return value? 0 on timeout, null on error Chris@0: // we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout Chris@0: $stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)'); Chris@16: $stmt->bindValue(':key', $lockId, \PDO::PARAM_STR); Chris@0: $stmt->execute(); Chris@0: Chris@0: $releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)'); Chris@16: $releaseStmt->bindValue(':key', $lockId, \PDO::PARAM_STR); Chris@0: Chris@0: return $releaseStmt; Chris@0: case 'pgsql': Chris@0: // Obtaining an exclusive session level advisory lock requires an integer key. Chris@14: // When session.sid_bits_per_character > 4, the session id can contain non-hex-characters. Chris@14: // So we cannot just use hexdec(). Chris@14: if (4 === \PHP_INT_SIZE) { Chris@14: $sessionInt1 = $this->convertStringToInt($sessionId); Chris@14: $sessionInt2 = $this->convertStringToInt(substr($sessionId, 4, 4)); Chris@0: Chris@0: $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)'); Chris@0: $stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT); Chris@0: $stmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT); Chris@0: $stmt->execute(); Chris@0: Chris@0: $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key1, :key2)'); Chris@0: $releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT); Chris@0: $releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT); Chris@0: } else { Chris@14: $sessionBigInt = $this->convertStringToInt($sessionId); Chris@0: Chris@0: $stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)'); Chris@0: $stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT); Chris@0: $stmt->execute(); Chris@0: Chris@0: $releaseStmt = $this->pdo->prepare('SELECT pg_advisory_unlock(:key)'); Chris@0: $releaseStmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT); Chris@0: } Chris@0: Chris@0: return $releaseStmt; Chris@0: case 'sqlite': Chris@0: throw new \DomainException('SQLite does not support advisory locks.'); Chris@0: default: Chris@0: throw new \DomainException(sprintf('Advisory locks are currently not implemented for PDO driver "%s".', $this->driver)); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@14: * Encodes the first 4 (when PHP_INT_SIZE == 4) or 8 characters of the string as an integer. Chris@14: * Chris@14: * Keep in mind, PHP integers are signed. Chris@14: * Chris@14: * @param string $string Chris@14: * Chris@14: * @return int Chris@14: */ Chris@14: private function convertStringToInt($string) Chris@14: { Chris@14: if (4 === \PHP_INT_SIZE) { Chris@17: return (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]); Chris@14: } Chris@14: Chris@17: $int1 = (\ord($string[7]) << 24) + (\ord($string[6]) << 16) + (\ord($string[5]) << 8) + \ord($string[4]); Chris@17: $int2 = (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]); Chris@14: Chris@14: return $int2 + ($int1 << 32); Chris@14: } Chris@14: Chris@14: /** Chris@0: * Return a locking or nonlocking SQL query to read session information. Chris@0: * Chris@0: * @return string The SQL string Chris@0: * Chris@0: * @throws \DomainException When an unsupported PDO driver is used Chris@0: */ Chris@0: private function getSelectSql() Chris@0: { Chris@0: if (self::LOCK_TRANSACTIONAL === $this->lockMode) { Chris@0: $this->beginTransaction(); Chris@0: Chris@0: switch ($this->driver) { Chris@0: case 'mysql': Chris@0: case 'oci': Chris@0: case 'pgsql': Chris@0: return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE"; Chris@0: case 'sqlsrv': Chris@0: return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id"; Chris@0: case 'sqlite': Chris@0: // we already locked when starting transaction Chris@0: break; Chris@0: default: Chris@0: throw new \DomainException(sprintf('Transactional locks are currently not implemented for PDO driver "%s".', $this->driver)); Chris@0: } Chris@0: } Chris@0: Chris@0: return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id"; Chris@0: } Chris@0: Chris@0: /** Chris@14: * Returns an insert statement supported by the database for writing session data. Chris@14: * Chris@14: * @param string $sessionId Session ID Chris@14: * @param string $sessionData Encoded session data Chris@14: * @param int $maxlifetime session.gc_maxlifetime Chris@14: * Chris@14: * @return \PDOStatement The insert statement Chris@14: */ Chris@14: private function getInsertStatement($sessionId, $sessionData, $maxlifetime) Chris@14: { Chris@14: switch ($this->driver) { Chris@14: case 'oci': Chris@14: $data = fopen('php://memory', 'r+'); Chris@14: fwrite($data, $sessionData); Chris@14: rewind($data); Chris@14: $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, EMPTY_BLOB(), :lifetime, :time) RETURNING $this->dataCol into :data"; Chris@14: break; Chris@14: default: Chris@14: $data = $sessionData; Chris@14: $sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"; Chris@14: break; Chris@14: } Chris@14: Chris@14: $stmt = $this->pdo->prepare($sql); Chris@14: $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@14: $stmt->bindParam(':data', $data, \PDO::PARAM_LOB); Chris@14: $stmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); Chris@14: $stmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@14: Chris@14: return $stmt; Chris@14: } Chris@14: Chris@14: /** Chris@14: * Returns an update statement supported by the database for writing session data. Chris@14: * Chris@14: * @param string $sessionId Session ID Chris@14: * @param string $sessionData Encoded session data Chris@14: * @param int $maxlifetime session.gc_maxlifetime Chris@14: * Chris@14: * @return \PDOStatement The update statement Chris@14: */ Chris@14: private function getUpdateStatement($sessionId, $sessionData, $maxlifetime) Chris@14: { Chris@14: switch ($this->driver) { Chris@14: case 'oci': Chris@14: $data = fopen('php://memory', 'r+'); Chris@14: fwrite($data, $sessionData); Chris@14: rewind($data); Chris@14: $sql = "UPDATE $this->table SET $this->dataCol = EMPTY_BLOB(), $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id RETURNING $this->dataCol into :data"; Chris@14: break; Chris@14: default: Chris@14: $data = $sessionData; Chris@14: $sql = "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id"; Chris@14: break; Chris@14: } Chris@14: Chris@14: $stmt = $this->pdo->prepare($sql); Chris@14: $stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@14: $stmt->bindParam(':data', $data, \PDO::PARAM_LOB); Chris@14: $stmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); Chris@14: $stmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@14: Chris@14: return $stmt; Chris@14: } Chris@14: Chris@14: /** Chris@0: * Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data. Chris@0: * Chris@0: * @param string $sessionId Session ID Chris@0: * @param string $data Encoded session data Chris@0: * @param int $maxlifetime session.gc_maxlifetime Chris@0: * Chris@0: * @return \PDOStatement|null The merge statement or null when not supported Chris@0: */ Chris@0: private function getMergeStatement($sessionId, $data, $maxlifetime) Chris@0: { Chris@0: switch (true) { Chris@0: case 'mysql' === $this->driver: Chris@0: $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". Chris@0: "ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)"; Chris@0: break; Chris@0: case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='): Chris@0: // MERGE is only available since SQL Server 2008 and must be terminated by semicolon Chris@0: // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx Chris@0: $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ". Chris@0: "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ". Chris@0: "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;"; Chris@0: break; Chris@0: case 'sqlite' === $this->driver: Chris@0: $mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"; Chris@0: break; Chris@0: case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='): Chris@0: $mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ". Chris@0: "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)"; Chris@0: break; Chris@14: default: Chris@14: // MERGE is not supported with LOBs: http://www.oracle.com/technetwork/articles/fuecks-lobs-095315.html Chris@14: return null; Chris@0: } Chris@0: Chris@14: $mergeStmt = $this->pdo->prepare($mergeSql); Chris@0: Chris@14: if ('sqlsrv' === $this->driver) { Chris@14: $mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR); Chris@14: $mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR); Chris@14: $mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB); Chris@14: $mergeStmt->bindParam(4, $maxlifetime, \PDO::PARAM_INT); Chris@14: $mergeStmt->bindValue(5, time(), \PDO::PARAM_INT); Chris@14: $mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB); Chris@14: $mergeStmt->bindParam(7, $maxlifetime, \PDO::PARAM_INT); Chris@14: $mergeStmt->bindValue(8, time(), \PDO::PARAM_INT); Chris@14: } else { Chris@14: $mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR); Chris@14: $mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB); Chris@14: $mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT); Chris@14: $mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT); Chris@14: } Chris@0: Chris@14: return $mergeStmt; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Return a PDO instance. Chris@0: * Chris@0: * @return \PDO Chris@0: */ Chris@0: protected function getConnection() Chris@0: { Chris@0: if (null === $this->pdo) { Chris@0: $this->connect($this->dsn ?: ini_get('session.save_path')); Chris@0: } Chris@0: Chris@0: return $this->pdo; Chris@0: } Chris@0: }