This commit is contained in:
Markus
2022-04-28 09:40:10 +02:00
commit 795794f992
9586 changed files with 1146991 additions and 0 deletions

View File

@@ -0,0 +1,91 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use ReturnTypeWillChange;
/**
* Session handler using static array for storage.
* Intended only for use during testing.
*/
class ArrayHandler extends BaseHandler
{
protected static $cache = [];
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*/
public function open($path, $name): bool
{
return true;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
return '';
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
return true;
}
/**
* Closes the current session.
*/
public function close(): bool
{
return true;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
return true;
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
return 1;
}
}

View File

@@ -0,0 +1,166 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use Config\App as AppConfig;
use Psr\Log\LoggerAwareTrait;
use SessionHandlerInterface;
/**
* Base class for session handling
*/
abstract class BaseHandler implements SessionHandlerInterface
{
use LoggerAwareTrait;
/**
* The Data fingerprint.
*
* @var string
*/
protected $fingerprint;
/**
* Lock placeholder.
*
* @var mixed
*/
protected $lock = false;
/**
* Cookie prefix
*
* @var string
*/
protected $cookiePrefix = '';
/**
* Cookie domain
*
* @var string
*/
protected $cookieDomain = '';
/**
* Cookie path
*
* @var string
*/
protected $cookiePath = '/';
/**
* Cookie secure?
*
* @var bool
*/
protected $cookieSecure = false;
/**
* Cookie name to use
*
* @var string
*/
protected $cookieName;
/**
* Match IP addresses for cookies?
*
* @var bool
*/
protected $matchIP = false;
/**
* Current session ID
*
* @var string
*/
protected $sessionID;
/**
* The 'save path' for the session
* varies between
*
* @var array|string
*/
protected $savePath;
/**
* User's IP address.
*
* @var string
*/
protected $ipAddress;
public function __construct(AppConfig $config, string $ipAddress)
{
$this->cookiePrefix = $config->cookiePrefix;
$this->cookieDomain = $config->cookieDomain;
$this->cookiePath = $config->cookiePath;
$this->cookieSecure = $config->cookieSecure;
$this->cookieName = $config->sessionCookieName;
$this->matchIP = $config->sessionMatchIP;
$this->savePath = $config->sessionSavePath;
$this->ipAddress = $ipAddress;
}
/**
* Internal method to force removal of a cookie by the client
* when session_destroy() is called.
*/
protected function destroyCookie(): bool
{
return setcookie(
$this->cookieName,
'',
['expires' => 1, 'path' => $this->cookiePath, 'domain' => $this->cookieDomain, 'secure' => $this->cookieSecure, 'httponly' => true]
);
}
/**
* A dummy method allowing drivers with no locking functionality
* (databases other than PostgreSQL and MySQL) to act as if they
* do acquire a lock.
*/
protected function lockSession(string $sessionID): bool
{
$this->lock = true;
return true;
}
/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
$this->lock = false;
return true;
}
/**
* Drivers other than the 'files' one don't (need to) use the
* session.save_path INI setting, but that leads to confusing
* error messages emitted by PHP when open() or write() fail,
* as the message contains session.save_path ...
*
* To work around the problem, the drivers will call this method
* so that the INI is set just in time for the error message to
* be properly generated.
*/
protected function fail(): bool
{
ini_set('session.save_path', $this->savePath);
return false;
}
}

View File

@@ -0,0 +1,324 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\App as AppConfig;
use Config\Database;
use ReturnTypeWillChange;
/**
* Session handler using current Database for storage
*/
class DatabaseHandler extends BaseHandler
{
/**
* The database group to use for storage.
*
* @var string
*/
protected $DBGroup;
/**
* The name of the table to store session info.
*
* @var string
*/
protected $table;
/**
* The DB Connection instance.
*
* @var BaseConnection
*/
protected $db;
/**
* The database type, for locking purposes.
*
* @var string
*/
protected $platform;
/**
* Row exists flag
*
* @var bool
*/
protected $rowExists = false;
/**
* @throws SessionException
*/
public function __construct(AppConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
$this->table = $config->sessionSavePath;
if (empty($this->table)) {
throw SessionException::forMissingDatabaseTable();
}
$this->DBGroup = $config->sessionDBGroup ?? config(Database::class)->defaultGroup;
$this->db = Database::connect($this->DBGroup);
$driver = strtolower(get_class($this->db));
if (strpos($driver, 'mysql') !== false) {
$this->platform = 'mysql';
} elseif (strpos($driver, 'postgre') !== false) {
$this->platform = 'postgre';
}
}
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*/
public function open($path, $name): bool
{
if (empty($this->db->connID)) {
$this->db->initialize();
}
return true;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
if ($this->lockSession($id) === false) {
$this->fingerprint = md5('');
return '';
}
if (! isset($this->sessionID)) {
$this->sessionID = $id;
}
$builder = $this->db->table($this->table)
->select($this->platform === 'postgre' ? "encode(data, 'base64') AS data" : 'data')
->where('id', $id);
if ($this->matchIP) {
$builder = $builder->where('ip_address', $this->ipAddress);
}
$result = $builder->get()->getRow();
if ($result === null) {
// PHP7 will reuse the same SessionHandler object after
// ID regeneration, so we need to explicitly set this to
// FALSE instead of relying on the default ...
$this->rowExists = false;
$this->fingerprint = md5('');
return '';
}
if (is_bool($result)) {
$result = '';
} else {
$result = ($this->platform === 'postgre') ? base64_decode(rtrim($result->data), true) : $result->data;
}
$this->fingerprint = md5($result);
$this->rowExists = true;
return $result;
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
if ($this->lock === false) {
return $this->fail();
}
if ($this->sessionID !== $id) {
$this->rowExists = false;
$this->sessionID = $id;
}
if ($this->rowExists === false) {
$insertData = [
'id' => $id,
'ip_address' => $this->ipAddress,
'data' => $this->platform === 'postgre' ? '\x' . bin2hex($data) : $data,
];
if (! $this->db->table($this->table)->set('timestamp', 'now()', false)->insert($insertData)) {
return $this->fail();
}
$this->fingerprint = md5($data);
$this->rowExists = true;
return true;
}
$builder = $this->db->table($this->table)->where('id', $id);
if ($this->matchIP) {
$builder = $builder->where('ip_address', $this->ipAddress);
}
$updateData = [];
if ($this->fingerprint !== md5($data)) {
$updateData['data'] = ($this->platform === 'postgre') ? '\x' . bin2hex($data) : $data;
}
if (! $builder->set('timestamp', 'now()', false)->update($updateData)) {
return $this->fail();
}
$this->fingerprint = md5($data);
return true;
}
/**
* Closes the current session.
*/
public function close(): bool
{
return ($this->lock && ! $this->releaseLock()) ? $this->fail() : true;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
if ($this->lock) {
$builder = $this->db->table($this->table)->where('id', $id);
if ($this->matchIP) {
$builder = $builder->where('ip_address', $this->ipAddress);
}
if (! $builder->delete()) {
return $this->fail();
}
}
if ($this->close()) {
$this->destroyCookie();
return true;
}
return $this->fail();
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
$separator = $this->platform === 'postgre' ? '\'' : ' ';
$interval = implode($separator, ['', "{$max_lifetime} second", '']);
return $this->db->table($this->table)->where('timestamp <', "now() - INTERVAL {$interval}", false)->delete() ? 1 : $this->fail();
}
/**
* Lock the session.
*/
protected function lockSession(string $sessionID): bool
{
if ($this->platform === 'mysql') {
$arg = md5($sessionID . ($this->matchIP ? '_' . $this->ipAddress : ''));
if ($this->db->query("SELECT GET_LOCK('{$arg}', 300) AS ci_session_lock")->getRow()->ci_session_lock) {
$this->lock = $arg;
return true;
}
return $this->fail();
}
if ($this->platform === 'postgre') {
$arg = "hashtext('{$sessionID}')" . ($this->matchIP ? ", hashtext('{$this->ipAddress}')" : '');
if ($this->db->simpleQuery("SELECT pg_advisory_lock({$arg})")) {
$this->lock = $arg;
return true;
}
return $this->fail();
}
// Unsupported DB? Let the parent handle the simplified version.
return parent::lockSession($sessionID);
}
/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
if (! $this->lock) {
return true;
}
if ($this->platform === 'mysql') {
if ($this->db->query("SELECT RELEASE_LOCK('{$this->lock}') AS ci_session_lock")->getRow()->ci_session_lock) {
$this->lock = false;
return true;
}
return $this->fail();
}
if ($this->platform === 'postgre') {
if ($this->db->simpleQuery("SELECT pg_advisory_unlock({$this->lock})")) {
$this->lock = false;
return true;
}
return $this->fail();
}
// Unsupported DB? Let the parent handle the simple version.
return parent::releaseLock();
}
}

View File

@@ -0,0 +1,339 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\App as AppConfig;
use ReturnTypeWillChange;
/**
* Session handler using file system for storage
*/
class FileHandler extends BaseHandler
{
/**
* Where to save the session files to.
*
* @var string
*/
protected $savePath;
/**
* The file handle
*
* @var resource|null
*/
protected $fileHandle;
/**
* File Name
*
* @var string
*/
protected $filePath;
/**
* Whether this is a new file.
*
* @var bool
*/
protected $fileNew;
/**
* Whether IP addresses should be matched.
*
* @var bool
*/
protected $matchIP = false;
/**
* Regex of session ID
*
* @var string
*/
protected $sessionIDRegex = '';
public function __construct(AppConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
if (! empty($config->sessionSavePath)) {
$this->savePath = rtrim($config->sessionSavePath, '/\\');
ini_set('session.save_path', $config->sessionSavePath);
} else {
$sessionPath = rtrim(ini_get('session.save_path'), '/\\');
if (! $sessionPath) {
$sessionPath = WRITEPATH . 'session';
}
$this->savePath = $sessionPath;
}
$this->matchIP = $config->sessionMatchIP;
$this->configureSessionIDRegex();
}
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*
* @throws SessionException
*/
public function open($path, $name): bool
{
if (! is_dir($path) && ! mkdir($path, 0700, true)) {
throw SessionException::forInvalidSavePath($this->savePath);
}
if (! is_writable($path)) {
throw SessionException::forWriteProtectedSavePath($this->savePath);
}
$this->savePath = $path;
// we'll use the session name as prefix to avoid collisions
$this->filePath = $this->savePath . '/' . $name . ($this->matchIP ? md5($this->ipAddress) : '');
return true;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
// This might seem weird, but PHP 5.6 introduced session_reset(),
// which re-reads session data
if ($this->fileHandle === null) {
$this->fileNew = ! is_file($this->filePath . $id);
if (($this->fileHandle = fopen($this->filePath . $id, 'c+b')) === false) {
$this->logger->error("Session: Unable to open file '" . $this->filePath . $id . "'.");
return false;
}
if (flock($this->fileHandle, LOCK_EX) === false) {
$this->logger->error("Session: Unable to obtain lock for file '" . $this->filePath . $id . "'.");
fclose($this->fileHandle);
$this->fileHandle = null;
return false;
}
if (! isset($this->sessionID)) {
$this->sessionID = $id;
}
if ($this->fileNew) {
chmod($this->filePath . $id, 0600);
$this->fingerprint = md5('');
return '';
}
} else {
rewind($this->fileHandle);
}
$data = '';
$buffer = 0;
clearstatcache(); // Address https://github.com/codeigniter4/CodeIgniter4/issues/2056
for ($read = 0, $length = filesize($this->filePath . $id); $read < $length; $read += strlen($buffer)) {
if (($buffer = fread($this->fileHandle, $length - $read)) === false) {
break;
}
$data .= $buffer;
}
$this->fingerprint = md5($data);
return $data;
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
// If the two IDs don't match, we have a session_regenerate_id() call
if ($id !== $this->sessionID) {
$this->sessionID = $id;
}
if (! is_resource($this->fileHandle)) {
return false;
}
if ($this->fingerprint === md5($data)) {
return ($this->fileNew) ? true : touch($this->filePath . $id);
}
if (! $this->fileNew) {
ftruncate($this->fileHandle, 0);
rewind($this->fileHandle);
}
if (($length = strlen($data)) > 0) {
$result = null;
for ($written = 0; $written < $length; $written += $result) {
if (($result = fwrite($this->fileHandle, substr($data, $written))) === false) {
break;
}
}
if (! is_int($result)) {
$this->fingerprint = md5(substr($data, 0, $written));
$this->logger->error('Session: Unable to write data.');
return false;
}
}
$this->fingerprint = md5($data);
return true;
}
/**
* Closes the current session.
*/
public function close(): bool
{
if (is_resource($this->fileHandle)) {
flock($this->fileHandle, LOCK_UN);
fclose($this->fileHandle);
$this->fileHandle = null;
$this->fileNew = false;
}
return true;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
if ($this->close()) {
return is_file($this->filePath . $id)
? (unlink($this->filePath . $id) && $this->destroyCookie())
: true;
}
if ($this->filePath !== null) {
clearstatcache();
return is_file($this->filePath . $id)
? (unlink($this->filePath . $id) && $this->destroyCookie())
: true;
}
return false;
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
if (! is_dir($this->savePath) || ($directory = opendir($this->savePath)) === false) {
$this->logger->debug("Session: Garbage collector couldn't list files under directory '" . $this->savePath . "'.");
return false;
}
$ts = time() - $max_lifetime;
$pattern = $this->matchIP === true ? '[0-9a-f]{32}' : '';
$pattern = sprintf(
'#\A%s' . $pattern . $this->sessionIDRegex . '\z#',
preg_quote($this->cookieName, '#')
);
$collected = 0;
while (($file = readdir($directory)) !== false) {
// If the filename doesn't match this pattern, it's either not a session file or is not ours
if (! preg_match($pattern, $file)
|| ! is_file($this->savePath . DIRECTORY_SEPARATOR . $file)
|| ($mtime = filemtime($this->savePath . DIRECTORY_SEPARATOR . $file)) === false
|| $mtime > $ts
) {
continue;
}
unlink($this->savePath . DIRECTORY_SEPARATOR . $file);
$collected++;
}
closedir($directory);
return $collected;
}
/**
* Configure Session ID regular expression
*/
protected function configureSessionIDRegex()
{
$bitsPerCharacter = (int) ini_get('session.sid_bits_per_character');
$SIDLength = (int) ini_get('session.sid_length');
if (($bits = $SIDLength * $bitsPerCharacter) < 160) {
// Add as many more characters as necessary to reach at least 160 bits
$SIDLength += (int) ceil((160 % $bits) / $bitsPerCharacter);
ini_set('session.sid_length', (string) $SIDLength);
}
switch ($bitsPerCharacter) {
case 4:
$this->sessionIDRegex = '[0-9a-f]';
break;
case 5:
$this->sessionIDRegex = '[0-9a-v]';
break;
case 6:
$this->sessionIDRegex = '[0-9a-zA-Z,-]';
break;
}
$this->sessionIDRegex .= '{' . $SIDLength . '}';
}
}

View File

@@ -0,0 +1,303 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\App as AppConfig;
use Memcached;
use ReturnTypeWillChange;
/**
* Session handler using Memcache for persistence
*/
class MemcachedHandler extends BaseHandler
{
/**
* Memcached instance
*
* @var Memcached|null
*/
protected $memcached;
/**
* Key prefix
*
* @var string
*/
protected $keyPrefix = 'ci_session:';
/**
* Lock key
*
* @var string|null
*/
protected $lockKey;
/**
* Number of seconds until the session ends.
*
* @var int
*/
protected $sessionExpiration = 7200;
/**
* @throws SessionException
*/
public function __construct(AppConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
if (empty($this->savePath)) {
throw SessionException::forEmptySavepath();
}
if ($this->matchIP === true) {
$this->keyPrefix .= $this->ipAddress . ':';
}
if (! empty($this->keyPrefix)) {
ini_set('memcached.sess_prefix', $this->keyPrefix);
}
$this->sessionExpiration = $config->sessionExpiration;
}
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*/
public function open($path, $name): bool
{
$this->memcached = new Memcached();
$this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true); // required for touch() usage
$serverList = [];
foreach ($this->memcached->getServerList() as $server) {
$serverList[] = $server['host'] . ':' . $server['port'];
}
if (! preg_match_all('#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->savePath, $matches, PREG_SET_ORDER)) {
$this->memcached = null;
$this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath);
return false;
}
foreach ($matches as $match) {
// If Memcached already has this server (or if the port is invalid), skip it
if (in_array($match[1] . ':' . $match[2], $serverList, true)) {
$this->logger->debug('Session: Memcached server pool already has ' . $match[1] . ':' . $match[2]);
continue;
}
if (! $this->memcached->addServer($match[1], $match[2], $match[3] ?? 0)) {
$this->logger->error('Could not add ' . $match[1] . ':' . $match[2] . ' to Memcached server pool.');
} else {
$serverList[] = $match[1] . ':' . $match[2];
}
}
if (empty($serverList)) {
$this->logger->error('Session: Memcached server pool is empty.');
return false;
}
return true;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
if (isset($this->memcached) && $this->lockSession($id)) {
if (! isset($this->sessionID)) {
$this->sessionID = $id;
}
$data = (string) $this->memcached->get($this->keyPrefix . $id);
$this->fingerprint = md5($data);
return $data;
}
return '';
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
if (! isset($this->memcached)) {
return false;
}
if ($this->sessionID !== $id) {
if (! $this->releaseLock() || ! $this->lockSession($id)) {
return false;
}
$this->fingerprint = md5('');
$this->sessionID = $id;
}
if (isset($this->lockKey)) {
$this->memcached->replace($this->lockKey, time(), 300);
if ($this->fingerprint !== ($fingerprint = md5($data))) {
if ($this->memcached->set($this->keyPrefix . $id, $data, $this->sessionExpiration)) {
$this->fingerprint = $fingerprint;
return true;
}
return false;
}
return $this->memcached->touch($this->keyPrefix . $id, $this->sessionExpiration);
}
return false;
}
/**
* Closes the current session.
*/
public function close(): bool
{
if (isset($this->memcached)) {
if (isset($this->lockKey)) {
$this->memcached->delete($this->lockKey);
}
if (! $this->memcached->quit()) {
return false;
}
$this->memcached = null;
return true;
}
return false;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
if (isset($this->memcached, $this->lockKey)) {
$this->memcached->delete($this->keyPrefix . $id);
return $this->destroyCookie();
}
return false;
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
return 1;
}
/**
* Acquires an emulated lock.
*
* @param string $sessionID Session ID
*/
protected function lockSession(string $sessionID): bool
{
if (isset($this->lockKey)) {
return $this->memcached->replace($this->lockKey, time(), 300);
}
$lockKey = $this->keyPrefix . $sessionID . ':lock';
$attempt = 0;
do {
if ($this->memcached->get($lockKey)) {
sleep(1);
continue;
}
if (! $this->memcached->set($lockKey, time(), 300)) {
$this->logger->error('Session: Error while trying to obtain lock for ' . $this->keyPrefix . $sessionID);
return false;
}
$this->lockKey = $lockKey;
break;
} while (++$attempt < 30);
if ($attempt === 30) {
$this->logger->error('Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID . ' after 30 attempts, aborting.');
return false;
}
$this->lock = true;
return true;
}
/**
* Releases a previously acquired lock
*/
protected function releaseLock(): bool
{
if (isset($this->memcached, $this->lockKey) && $this->lock) {
if (
! $this->memcached->delete($this->lockKey)
&& $this->memcached->getResultCode() !== Memcached::RES_NOTFOUND
) {
$this->logger->error('Session: Error while trying to free lock for ' . $this->lockKey);
return false;
}
$this->lockKey = null;
$this->lock = false;
}
return true;
}
}

View File

@@ -0,0 +1,329 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\App as AppConfig;
use Redis;
use RedisException;
use ReturnTypeWillChange;
/**
* Session handler using Redis for persistence
*/
class RedisHandler extends BaseHandler
{
/**
* phpRedis instance
*
* @var Redis|null
*/
protected $redis;
/**
* Key prefix
*
* @var string
*/
protected $keyPrefix = 'ci_session:';
/**
* Lock key
*
* @var string|null
*/
protected $lockKey;
/**
* Key exists flag
*
* @var bool
*/
protected $keyExists = false;
/**
* Number of seconds until the session ends.
*
* @var int
*/
protected $sessionExpiration = 7200;
/**
* @throws SessionException
*/
public function __construct(AppConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
if (empty($this->savePath)) {
throw SessionException::forEmptySavepath();
}
if (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->savePath, $matches)) {
if (! isset($matches[3])) {
$matches[3] = ''; // Just to avoid undefined index notices below
}
$this->savePath = [
'host' => $matches[1],
'port' => empty($matches[2]) ? null : $matches[2],
'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : null,
'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : null,
'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : null,
];
preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->keyPrefix = $match[1];
} else {
throw SessionException::forInvalidSavePathFormat($this->savePath);
}
if ($this->matchIP === true) {
$this->keyPrefix .= $this->ipAddress . ':';
}
$this->sessionExpiration = empty($config->sessionExpiration)
? (int) ini_get('session.gc_maxlifetime')
: (int) $config->sessionExpiration;
}
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*/
public function open($path, $name): bool
{
if (empty($this->savePath)) {
return false;
}
$redis = new Redis();
if (! $redis->connect($this->savePath['host'], $this->savePath['port'], $this->savePath['timeout'])) {
$this->logger->error('Session: Unable to connect to Redis with the configured settings.');
} elseif (isset($this->savePath['password']) && ! $redis->auth($this->savePath['password'])) {
$this->logger->error('Session: Unable to authenticate to Redis instance.');
} elseif (isset($this->savePath['database']) && ! $redis->select($this->savePath['database'])) {
$this->logger->error('Session: Unable to select Redis database with index ' . $this->savePath['database']);
} else {
$this->redis = $redis;
return true;
}
return false;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
if (isset($this->redis) && $this->lockSession($id)) {
if (! isset($this->sessionID)) {
$this->sessionID = $id;
}
$data = $this->redis->get($this->keyPrefix . $id);
if (is_string($data)) {
$this->keyExists = true;
} else {
$data = '';
}
$this->fingerprint = md5($data);
return $data;
}
return '';
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
if (! isset($this->redis)) {
return false;
}
if ($this->sessionID !== $id) {
if (! $this->releaseLock() || ! $this->lockSession($id)) {
return false;
}
$this->keyExists = false;
$this->sessionID = $id;
}
if (isset($this->lockKey)) {
$this->redis->expire($this->lockKey, 300);
if ($this->fingerprint !== ($fingerprint = md5($data)) || $this->keyExists === false) {
if ($this->redis->set($this->keyPrefix . $id, $data, $this->sessionExpiration)) {
$this->fingerprint = $fingerprint;
$this->keyExists = true;
return true;
}
return false;
}
return $this->redis->expire($this->keyPrefix . $id, $this->sessionExpiration);
}
return false;
}
/**
* Closes the current session.
*/
public function close(): bool
{
if (isset($this->redis)) {
try {
$pingReply = $this->redis->ping();
if (($pingReply === true) || ($pingReply === '+PONG')) {
if (isset($this->lockKey)) {
$this->redis->del($this->lockKey);
}
if (! $this->redis->close()) {
return false;
}
}
} catch (RedisException $e) {
$this->logger->error('Session: Got RedisException on close(): ' . $e->getMessage());
}
$this->redis = null;
return true;
}
return true;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
if (isset($this->redis, $this->lockKey)) {
if (($result = $this->redis->del($this->keyPrefix . $id)) !== 1) {
$this->logger->debug('Session: Redis::del() expected to return 1, got ' . var_export($result, true) . ' instead.');
}
return $this->destroyCookie();
}
return false;
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
return 1;
}
/**
* Acquires an emulated lock.
*
* @param string $sessionID Session ID
*/
protected function lockSession(string $sessionID): bool
{
// PHP 7 reuses the SessionHandler object on regeneration,
// so we need to check here if the lock key is for the
// correct session ID.
if ($this->lockKey === $this->keyPrefix . $sessionID . ':lock') {
return $this->redis->expire($this->lockKey, 300);
}
$lockKey = $this->keyPrefix . $sessionID . ':lock';
$attempt = 0;
do {
if (($ttl = $this->redis->ttl($lockKey)) > 0) {
sleep(1);
continue;
}
if (! $this->redis->setex($lockKey, 300, (string) time())) {
$this->logger->error('Session: Error while trying to obtain lock for ' . $this->keyPrefix . $sessionID);
return false;
}
$this->lockKey = $lockKey;
break;
} while (++$attempt < 30);
if ($attempt === 30) {
log_message('error', 'Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID . ' after 30 attempts, aborting.');
return false;
}
if ($ttl === -1) {
log_message('debug', 'Session: Lock for ' . $this->keyPrefix . $sessionID . ' had no TTL, overriding.');
}
$this->lock = true;
return true;
}
/**
* Releases a previously acquired lock
*/
protected function releaseLock(): bool
{
if (isset($this->redis, $this->lockKey) && $this->lock) {
if (! $this->redis->del($this->lockKey)) {
$this->logger->error('Session: Error while trying to free lock for ' . $this->lockKey);
return false;
}
$this->lockKey = null;
$this->lock = false;
}
return true;
}
}