first commit
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* 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\Cookie as CookieConfig;
|
||||
use Config\Session as SessionConfig;
|
||||
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 bool|string
|
||||
*/
|
||||
protected $lock = false;
|
||||
|
||||
/**
|
||||
* Cookie prefix
|
||||
*
|
||||
* The Config\Cookie::$prefix setting is completely ignored.
|
||||
* See https://codeigniter.com/user_guide/libraries/sessions.html#session-preferences
|
||||
*
|
||||
* @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|null
|
||||
*/
|
||||
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(SessionConfig $config, string $ipAddress)
|
||||
{
|
||||
// Store Session configurations
|
||||
$this->cookieName = $config->cookieName;
|
||||
$this->matchIP = $config->matchIP;
|
||||
$this->savePath = $config->savePath;
|
||||
|
||||
$cookie = config(CookieConfig::class);
|
||||
|
||||
// Session cookies have no prefix.
|
||||
$this->cookieDomain = $cookie->domain;
|
||||
$this->cookiePath = $cookie->path;
|
||||
$this->cookieSecure = $cookie->secure;
|
||||
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* 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\Database;
|
||||
|
||||
use CodeIgniter\Session\Handlers\DatabaseHandler;
|
||||
|
||||
/**
|
||||
* Session handler for MySQLi
|
||||
*
|
||||
* @see \CodeIgniter\Session\Handlers\Database\MySQLiHandlerTest
|
||||
*/
|
||||
class MySQLiHandler extends DatabaseHandler
|
||||
{
|
||||
/**
|
||||
* Lock the session.
|
||||
*/
|
||||
protected function lockSession(string $sessionID): bool
|
||||
{
|
||||
$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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the lock, if any.
|
||||
*/
|
||||
protected function releaseLock(): bool
|
||||
{
|
||||
if (! $this->lock) {
|
||||
return true;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* 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\Database;
|
||||
|
||||
use CodeIgniter\Database\BaseBuilder;
|
||||
use CodeIgniter\Session\Handlers\DatabaseHandler;
|
||||
use ReturnTypeWillChange;
|
||||
|
||||
/**
|
||||
* Session handler for Postgre
|
||||
*
|
||||
* @see \CodeIgniter\Session\Handlers\Database\PostgreHandlerTest
|
||||
*/
|
||||
class PostgreHandler extends DatabaseHandler
|
||||
{
|
||||
/**
|
||||
* Sets SELECT clause
|
||||
*/
|
||||
protected function setSelect(BaseBuilder $builder)
|
||||
{
|
||||
$builder->select("encode(data, 'base64') AS data");
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes column data
|
||||
*
|
||||
* @param string $data
|
||||
*
|
||||
* @return false|string
|
||||
*/
|
||||
protected function decodeData($data)
|
||||
{
|
||||
return base64_decode(rtrim($data), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare data to insert/update
|
||||
*/
|
||||
protected function prepareData(string $data): string
|
||||
{
|
||||
return '\x' . bin2hex($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 = '\'';
|
||||
$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
|
||||
{
|
||||
$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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the lock, if any.
|
||||
*/
|
||||
protected function releaseLock(): bool
|
||||
{
|
||||
if (! $this->lock) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($this->db->simpleQuery("SELECT pg_advisory_unlock({$this->lock})")) {
|
||||
$this->lock = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->fail();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* 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\BaseBuilder;
|
||||
use CodeIgniter\Database\BaseConnection;
|
||||
use CodeIgniter\Session\Exceptions\SessionException;
|
||||
use Config\Database;
|
||||
use Config\Session as SessionConfig;
|
||||
use ReturnTypeWillChange;
|
||||
|
||||
/**
|
||||
* Base database session handler
|
||||
*
|
||||
* Do not use this class. Use database specific handler class.
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $platform;
|
||||
|
||||
/**
|
||||
* Row exists flag
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $rowExists = false;
|
||||
|
||||
/**
|
||||
* ID prefix for multiple session cookies
|
||||
*/
|
||||
protected string $idPrefix;
|
||||
|
||||
/**
|
||||
* @throws SessionException
|
||||
*/
|
||||
public function __construct(SessionConfig $config, string $ipAddress)
|
||||
{
|
||||
parent::__construct($config, $ipAddress);
|
||||
|
||||
// Store Session configurations
|
||||
$this->DBGroup = $config->DBGroup ?? config(Database::class)->defaultGroup;
|
||||
// Add sessionCookieName for multiple session cookies.
|
||||
$this->idPrefix = $config->cookieName . ':';
|
||||
|
||||
$this->table = $this->savePath;
|
||||
if (empty($this->table)) {
|
||||
throw SessionException::forMissingDatabaseTable();
|
||||
}
|
||||
|
||||
$this->db = Database::connect($this->DBGroup);
|
||||
$this->platform = $this->db->getPlatform();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)->where('id', $this->idPrefix . $id);
|
||||
|
||||
if ($this->matchIP) {
|
||||
$builder = $builder->where('ip_address', $this->ipAddress);
|
||||
}
|
||||
|
||||
$this->setSelect($builder);
|
||||
|
||||
$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 '';
|
||||
}
|
||||
|
||||
$result = is_bool($result) ? '' : $this->decodeData($result->data);
|
||||
|
||||
$this->fingerprint = md5($result);
|
||||
$this->rowExists = true;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets SELECT clause
|
||||
*/
|
||||
protected function setSelect(BaseBuilder $builder)
|
||||
{
|
||||
$builder->select('data');
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes column data
|
||||
*
|
||||
* @param string $data
|
||||
*
|
||||
* @return false|string
|
||||
*/
|
||||
protected function decodeData($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 ($this->lock === false) {
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
if ($this->sessionID !== $id) {
|
||||
$this->rowExists = false;
|
||||
$this->sessionID = $id;
|
||||
}
|
||||
|
||||
if ($this->rowExists === false) {
|
||||
$insertData = [
|
||||
'id' => $this->idPrefix . $id,
|
||||
'ip_address' => $this->ipAddress,
|
||||
'data' => $this->prepareData($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', $this->idPrefix . $id);
|
||||
|
||||
if ($this->matchIP) {
|
||||
$builder = $builder->where('ip_address', $this->ipAddress);
|
||||
}
|
||||
|
||||
$updateData = [];
|
||||
|
||||
if ($this->fingerprint !== md5($data)) {
|
||||
$updateData['data'] = $this->prepareData($data);
|
||||
}
|
||||
|
||||
if (! $builder->set('timestamp', 'now()', false)->update($updateData)) {
|
||||
return $this->fail();
|
||||
}
|
||||
|
||||
$this->fingerprint = md5($data);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare data to insert/update
|
||||
*/
|
||||
protected function prepareData(string $data): string
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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', $this->idPrefix . $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 = ' ';
|
||||
$interval = implode($separator, ['', "{$max_lifetime} second", '']);
|
||||
|
||||
return $this->db->table($this->table)->where(
|
||||
'timestamp <',
|
||||
"now() - INTERVAL {$interval}",
|
||||
false
|
||||
)->delete() ? 1 : $this->fail();
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the lock, if any.
|
||||
*/
|
||||
protected function releaseLock(): bool
|
||||
{
|
||||
if (! $this->lock) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Unsupported DB? Let the parent handle the simple version.
|
||||
return parent::releaseLock();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* 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\I18n\Time;
|
||||
use CodeIgniter\Session\Exceptions\SessionException;
|
||||
use Config\Session as SessionConfig;
|
||||
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(SessionConfig $config, string $ipAddress)
|
||||
{
|
||||
parent::__construct($config, $ipAddress);
|
||||
|
||||
if (! empty($this->savePath)) {
|
||||
$this->savePath = rtrim($this->savePath, '/\\');
|
||||
ini_set('session.save_path', $this->savePath);
|
||||
} else {
|
||||
$sessionPath = rtrim(ini_get('session.save_path'), '/\\');
|
||||
|
||||
if ($sessionPath === '') {
|
||||
$sessionPath = WRITEPATH . 'session';
|
||||
}
|
||||
|
||||
$this->savePath = $sessionPath;
|
||||
}
|
||||
|
||||
$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::now()->getTimestamp() - $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 . '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* 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\I18n\Time;
|
||||
use CodeIgniter\Session\Exceptions\SessionException;
|
||||
use Config\Session as SessionConfig;
|
||||
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(SessionConfig $config, string $ipAddress)
|
||||
{
|
||||
parent::__construct($config, $ipAddress);
|
||||
|
||||
$this->sessionExpiration = $config->expiration;
|
||||
|
||||
if (empty($this->savePath)) {
|
||||
throw SessionException::forEmptySavepath();
|
||||
}
|
||||
|
||||
// Add sessionCookieName for multiple session cookies.
|
||||
$this->keyPrefix .= $config->cookieName . ':';
|
||||
|
||||
if ($this->matchIP === true) {
|
||||
$this->keyPrefix .= $this->ipAddress . ':';
|
||||
}
|
||||
|
||||
ini_set('memcached.sess_prefix', $this->keyPrefix);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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], (int) $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 ($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::now()->getTimestamp(), 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::now()->getTimestamp(), 300);
|
||||
}
|
||||
|
||||
$lockKey = $this->keyPrefix . $sessionID . ':lock';
|
||||
$attempt = 0;
|
||||
|
||||
do {
|
||||
if ($this->memcached->get($lockKey)) {
|
||||
sleep(1);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $this->memcached->set($lockKey, Time::now()->getTimestamp(), 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* 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\I18n\Time;
|
||||
use CodeIgniter\Session\Exceptions\SessionException;
|
||||
use Config\Session as SessionConfig;
|
||||
use Redis;
|
||||
use RedisException;
|
||||
use ReturnTypeWillChange;
|
||||
|
||||
/**
|
||||
* Session handler using Redis for persistence
|
||||
*/
|
||||
class RedisHandler extends BaseHandler
|
||||
{
|
||||
private const DEFAULT_PORT = 6379;
|
||||
private const DEFAULT_PROTOCOL = 'tcp';
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* Time (microseconds) to wait if lock cannot be acquired.
|
||||
*/
|
||||
private int $lockRetryInterval = 100_000;
|
||||
|
||||
/**
|
||||
* Maximum number of lock acquisition attempts.
|
||||
*/
|
||||
private int $lockMaxRetries = 300;
|
||||
|
||||
/**
|
||||
* @param string $ipAddress User's IP address
|
||||
*
|
||||
* @throws SessionException
|
||||
*/
|
||||
public function __construct(SessionConfig $config, string $ipAddress)
|
||||
{
|
||||
parent::__construct($config, $ipAddress);
|
||||
|
||||
// Store Session configurations
|
||||
$this->sessionExpiration = ($config->expiration === 0)
|
||||
? (int) ini_get('session.gc_maxlifetime')
|
||||
: $config->expiration;
|
||||
|
||||
// Add sessionCookieName for multiple session cookies.
|
||||
$this->keyPrefix .= $config->cookieName . ':';
|
||||
|
||||
$this->setSavePath();
|
||||
|
||||
if ($this->matchIP === true) {
|
||||
$this->keyPrefix .= $this->ipAddress . ':';
|
||||
}
|
||||
|
||||
$this->lockRetryInterval = $config->lockWait ?? $this->lockRetryInterval;
|
||||
$this->lockMaxRetries = $config->lockAttempts ?? $this->lockMaxRetries;
|
||||
}
|
||||
|
||||
protected function setSavePath(): void
|
||||
{
|
||||
if (empty($this->savePath)) {
|
||||
throw SessionException::forEmptySavepath();
|
||||
}
|
||||
|
||||
$url = parse_url($this->savePath);
|
||||
$query = [];
|
||||
|
||||
if ($url === false) {
|
||||
// Unix domain socket like `unix:///var/run/redis/redis.sock?persistent=1`.
|
||||
if (preg_match('#unix://(/[^:?]+)(\?.+)?#', $this->savePath, $matches)) {
|
||||
$host = $matches[1];
|
||||
$port = 0;
|
||||
|
||||
if (isset($matches[2])) {
|
||||
parse_str(ltrim($matches[2], '?'), $query);
|
||||
}
|
||||
} else {
|
||||
throw SessionException::forInvalidSavePathFormat($this->savePath);
|
||||
}
|
||||
} else {
|
||||
// Also accepts `/var/run/redis.sock` for backward compatibility.
|
||||
if (isset($url['path']) && $url['path'][0] === '/') {
|
||||
$host = $url['path'];
|
||||
$port = 0;
|
||||
} else {
|
||||
// TCP connection.
|
||||
if (! isset($url['host'])) {
|
||||
throw SessionException::forInvalidSavePathFormat($this->savePath);
|
||||
}
|
||||
|
||||
$protocol = $url['scheme'] ?? self::DEFAULT_PROTOCOL;
|
||||
$host = $protocol . '://' . $url['host'];
|
||||
$port = $url['port'] ?? self::DEFAULT_PORT;
|
||||
}
|
||||
|
||||
if (isset($url['query'])) {
|
||||
parse_str($url['query'], $query);
|
||||
}
|
||||
}
|
||||
|
||||
$password = $query['auth'] ?? null;
|
||||
$database = isset($query['database']) ? (int) $query['database'] : 0;
|
||||
$timeout = isset($query['timeout']) ? (float) $query['timeout'] : 0.0;
|
||||
$prefix = $query['prefix'] ?? null;
|
||||
|
||||
$this->savePath = [
|
||||
'host' => $host,
|
||||
'port' => $port,
|
||||
'password' => $password,
|
||||
'database' => $database,
|
||||
'timeout' => $timeout,
|
||||
];
|
||||
|
||||
if ($prefix !== null) {
|
||||
$this->keyPrefix = $prefix;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 RedisException
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @throws RedisException
|
||||
*/
|
||||
#[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 false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the session data to the session storage.
|
||||
*
|
||||
* @param string $id The session ID
|
||||
* @param string $data The encoded session data
|
||||
*
|
||||
* @throws RedisException
|
||||
*/
|
||||
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->releaseLock()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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
|
||||
*
|
||||
* @throws RedisException
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @throws RedisException
|
||||
*/
|
||||
protected function lockSession(string $sessionID): bool
|
||||
{
|
||||
$lockKey = $this->keyPrefix . $sessionID . ':lock';
|
||||
|
||||
// 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 === $lockKey) {
|
||||
// If there is the lock, make the ttl longer.
|
||||
return $this->redis->expire($this->lockKey, 300);
|
||||
}
|
||||
|
||||
$attempt = 0;
|
||||
|
||||
do {
|
||||
$result = $this->redis->set(
|
||||
$lockKey,
|
||||
(string) Time::now()->getTimestamp(),
|
||||
// NX -- Only set the key if it does not already exist.
|
||||
// EX seconds -- Set the specified expire time, in seconds.
|
||||
['nx', 'ex' => 300]
|
||||
);
|
||||
|
||||
if (! $result) {
|
||||
usleep($this->lockRetryInterval);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->lockKey = $lockKey;
|
||||
break;
|
||||
} while (++$attempt < $this->lockMaxRetries);
|
||||
|
||||
if ($attempt === 300) {
|
||||
$this->logger->error(
|
||||
'Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID
|
||||
. ' after 300 attempts, aborting.'
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->lock = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases a previously acquired lock
|
||||
*
|
||||
* @throws RedisException
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user