3
declare(strict_types=1);
6
* This file is part of CodeIgniter 4 framework.
8
* (c) CodeIgniter Foundation <admin@codeigniter.com>
10
* For the full copyright and license information, please view
11
* the LICENSE file that was distributed with this source code.
14
namespace CodeIgniter\Session\Handlers;
16
use CodeIgniter\I18n\Time;
17
use CodeIgniter\Session\Exceptions\SessionException;
18
use Config\Session as SessionConfig;
21
use ReturnTypeWillChange;
24
* Session handler using Redis for persistence
26
class RedisHandler extends BaseHandler
28
private const DEFAULT_PORT = 6379;
29
private const DEFAULT_PROTOCOL = 'tcp';
43
protected $keyPrefix = 'ci_session:';
57
protected $keyExists = false;
60
* Number of seconds until the session ends.
64
protected $sessionExpiration = 7200;
67
* Time (microseconds) to wait if lock cannot be acquired.
69
private int $lockRetryInterval = 100_000;
72
* Maximum number of lock acquisition attempts.
74
private int $lockMaxRetries = 300;
77
* @param string $ipAddress User's IP address
79
* @throws SessionException
81
public function __construct(SessionConfig $config, string $ipAddress)
83
parent::__construct($config, $ipAddress);
85
// Store Session configurations
86
$this->sessionExpiration = ($config->expiration === 0)
87
? (int) ini_get('session.gc_maxlifetime')
88
: $config->expiration;
90
// Add sessionCookieName for multiple session cookies.
91
$this->keyPrefix .= $config->cookieName . ':';
95
if ($this->matchIP === true) {
96
$this->keyPrefix .= $this->ipAddress . ':';
99
$this->lockRetryInterval = $config->lockWait ?? $this->lockRetryInterval;
100
$this->lockMaxRetries = $config->lockAttempts ?? $this->lockMaxRetries;
103
protected function setSavePath(): void
105
if (empty($this->savePath)) {
106
throw SessionException::forEmptySavepath();
109
$url = parse_url($this->savePath);
112
if ($url === false) {
113
// Unix domain socket like `unix:///var/run/redis/redis.sock?persistent=1`.
114
if (preg_match('#unix://(/[^:?]+)(\?.+)?#', $this->savePath, $matches)) {
118
if (isset($matches[2])) {
119
parse_str(ltrim($matches[2], '?'), $query);
122
throw SessionException::forInvalidSavePathFormat($this->savePath);
125
// Also accepts `/var/run/redis.sock` for backward compatibility.
126
if (isset($url['path']) && $url['path'][0] === '/') {
127
$host = $url['path'];
131
if (! isset($url['host'])) {
132
throw SessionException::forInvalidSavePathFormat($this->savePath);
135
$protocol = $url['scheme'] ?? self::DEFAULT_PROTOCOL;
136
$host = $protocol . '://' . $url['host'];
137
$port = $url['port'] ?? self::DEFAULT_PORT;
140
if (isset($url['query'])) {
141
parse_str($url['query'], $query);
145
$password = $query['auth'] ?? null;
146
$database = isset($query['database']) ? (int) $query['database'] : 0;
147
$timeout = isset($query['timeout']) ? (float) $query['timeout'] : 0.0;
148
$prefix = $query['prefix'] ?? null;
153
'password' => $password,
154
'database' => $database,
155
'timeout' => $timeout,
158
if ($prefix !== null) {
159
$this->keyPrefix = $prefix;
164
* Re-initialize existing session, or creates a new one.
166
* @param string $path The path where to store/retrieve the session
167
* @param string $name The session name
169
* @throws RedisException
171
public function open($path, $name): bool
173
if (empty($this->savePath)) {
177
$redis = new Redis();
181
$this->savePath['host'],
182
$this->savePath['port'],
183
$this->savePath['timeout']
186
$this->logger->error('Session: Unable to connect to Redis with the configured settings.');
187
} elseif (isset($this->savePath['password']) && ! $redis->auth($this->savePath['password'])) {
188
$this->logger->error('Session: Unable to authenticate to Redis instance.');
189
} elseif (isset($this->savePath['database']) && ! $redis->select($this->savePath['database'])) {
190
$this->logger->error(
191
'Session: Unable to select Redis database with index ' . $this->savePath['database']
194
$this->redis = $redis;
203
* Reads the session data from the session storage, and returns the results.
205
* @param string $id The session ID
207
* @return false|string Returns an encoded string of the read data.
208
* If nothing was read, it must return false.
210
* @throws RedisException
212
#[ReturnTypeWillChange]
213
public function read($id)
215
if (isset($this->redis) && $this->lockSession($id)) {
216
if (! isset($this->sessionID)) {
217
$this->sessionID = $id;
220
$data = $this->redis->get($this->keyPrefix . $id);
222
if (is_string($data)) {
223
$this->keyExists = true;
228
$this->fingerprint = md5($data);
237
* Writes the session data to the session storage.
239
* @param string $id The session ID
240
* @param string $data The encoded session data
242
* @throws RedisException
244
public function write($id, $data): bool
246
if (! isset($this->redis)) {
250
if ($this->sessionID !== $id) {
251
if (! $this->releaseLock() || ! $this->lockSession($id)) {
255
$this->keyExists = false;
256
$this->sessionID = $id;
259
if (isset($this->lockKey)) {
260
$this->redis->expire($this->lockKey, 300);
262
if ($this->fingerprint !== ($fingerprint = md5($data)) || $this->keyExists === false) {
263
if ($this->redis->set($this->keyPrefix . $id, $data, $this->sessionExpiration)) {
264
$this->fingerprint = $fingerprint;
265
$this->keyExists = true;
273
return $this->redis->expire($this->keyPrefix . $id, $this->sessionExpiration);
280
* Closes the current session.
282
public function close(): bool
284
if (isset($this->redis)) {
286
$pingReply = $this->redis->ping();
288
if (($pingReply === true) || ($pingReply === '+PONG')) {
289
if (isset($this->lockKey) && ! $this->releaseLock()) {
293
if (! $this->redis->close()) {
297
} catch (RedisException $e) {
298
$this->logger->error('Session: Got RedisException on close(): ' . $e->getMessage());
312
* @param string $id The session ID being destroyed
314
* @throws RedisException
316
public function destroy($id): bool
318
if (isset($this->redis, $this->lockKey)) {
319
if (($result = $this->redis->del($this->keyPrefix . $id)) !== 1) {
320
$this->logger->debug(
321
'Session: Redis::del() expected to return 1, got ' . var_export($result, true) . ' instead.'
325
return $this->destroyCookie();
332
* Cleans up expired sessions.
334
* @param int $max_lifetime Sessions that have not updated
335
* for the last max_lifetime seconds will be removed.
337
* @return false|int Returns the number of deleted sessions on success, or false on failure.
339
#[ReturnTypeWillChange]
340
public function gc($max_lifetime)
346
* Acquires an emulated lock.
348
* @param string $sessionID Session ID
350
* @throws RedisException
352
protected function lockSession(string $sessionID): bool
354
$lockKey = $this->keyPrefix . $sessionID . ':lock';
356
// PHP 7 reuses the SessionHandler object on regeneration,
357
// so we need to check here if the lock key is for the
358
// correct session ID.
359
if ($this->lockKey === $lockKey) {
360
// If there is the lock, make the ttl longer.
361
return $this->redis->expire($this->lockKey, 300);
367
$result = $this->redis->set(
369
(string) Time::now()->getTimestamp(),
370
// NX -- Only set the key if it does not already exist.
371
// EX seconds -- Set the specified expire time, in seconds.
376
usleep($this->lockRetryInterval);
381
$this->lockKey = $lockKey;
383
} while (++$attempt < $this->lockMaxRetries);
385
if ($attempt === 300) {
386
$this->logger->error(
387
'Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID
388
. ' after 300 attempts, aborting.'
400
* Releases a previously acquired lock
402
* @throws RedisException
404
protected function releaseLock(): bool
406
if (isset($this->redis, $this->lockKey) && $this->lock) {
407
if (! $this->redis->del($this->lockKey)) {
408
$this->logger->error('Session: Error while trying to free lock for ' . $this->lockKey);
413
$this->lockKey = null;