blob: 8db74c0ca66a6c8118b6b07a0fd93525c3037f15 [file] [log] [blame]
Andrey Andreev43f6cdb2014-08-27 22:26:40 +03001<?php
2/**
3 * CodeIgniter
4 *
Andrey Andreevbf6b11d2015-01-12 17:27:12 +02005 * An open source application development framework for PHP
Andrey Andreev43f6cdb2014-08-27 22:26:40 +03006 *
Andrey Andreev46f2f262014-11-11 14:37:51 +02007 * This content is released under the MIT License (MIT)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +03008 *
Andrey Andreev125ef472016-01-11 12:33:00 +02009 * Copyright (c) 2014 - 2016, British Columbia Institute of Technology
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030010 *
Andrey Andreev46f2f262014-11-11 14:37:51 +020011 * Permission is hereby granted, free of charge, to any person obtaining a copy
12 * of this software and associated documentation files (the "Software"), to deal
13 * in the Software without restriction, including without limitation the rights
14 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 * copies of the Software, and to permit persons to whom the Software is
16 * furnished to do so, subject to the following conditions:
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030017 *
Andrey Andreev46f2f262014-11-11 14:37:51 +020018 * The above copyright notice and this permission notice shall be included in
19 * all copies or substantial portions of the Software.
20 *
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 * THE SOFTWARE.
28 *
29 * @package CodeIgniter
30 * @author EllisLab Dev Team
Andrey Andreev1924e872016-01-11 12:55:34 +020031 * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
Andrey Andreev125ef472016-01-11 12:33:00 +020032 * @copyright Copyright (c) 2014 - 2016, British Columbia Institute of Technology (http://bcit.ca/)
Andrey Andreev46f2f262014-11-11 14:37:51 +020033 * @license http://opensource.org/licenses/MIT MIT License
Andrey Andreevbd202c92016-01-11 12:50:18 +020034 * @link https://codeigniter.com
Andrey Andreev46f2f262014-11-11 14:37:51 +020035 * @since Version 3.0.0
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030036 * @filesource
37 */
38defined('BASEPATH') OR exit('No direct script access allowed');
39
40/**
41 * CodeIgniter Session Redis Driver
42 *
Andrey Andreev46f2f262014-11-11 14:37:51 +020043 * @package CodeIgniter
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030044 * @subpackage Libraries
45 * @category Sessions
Andrey Andreev46f2f262014-11-11 14:37:51 +020046 * @author Andrey Andreev
Andrey Andreevbd202c92016-01-11 12:50:18 +020047 * @link https://codeigniter.com/user_guide/libraries/sessions.html
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030048 */
49class CI_Session_redis_driver extends CI_Session_driver implements SessionHandlerInterface {
50
51 /**
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030052 * phpRedis instance
53 *
54 * @var resource
55 */
56 protected $_redis;
57
58 /**
59 * Key prefix
60 *
61 * @var string
62 */
63 protected $_key_prefix = 'ci_session:';
64
65 /**
66 * Lock key
67 *
68 * @var string
69 */
70 protected $_lock_key;
71
Andrey Andreev173cf412016-02-05 14:36:50 +020072 /**
73 * Key exists flag
74 *
75 * @var bool
76 */
77 protected $_key_exists = FALSE;
78
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030079 // ------------------------------------------------------------------------
80
81 /**
82 * Class constructor
83 *
84 * @param array $params Configuration parameters
85 * @return void
86 */
87 public function __construct(&$params)
88 {
89 parent::__construct($params);
90
Andrey Andreevdfb39be2014-10-06 01:50:14 +030091 if (empty($this->_config['save_path']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030092 {
93 log_message('error', 'Session: No Redis save path configured.');
94 }
Andrey Andreevdfb39be2014-10-06 01:50:14 +030095 elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_config['save_path'], $matches))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030096 {
Andrey Andreev39ec2952014-09-17 14:16:05 +030097 isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below
Andrey Andreevdfb39be2014-10-06 01:50:14 +030098 $this->_config['save_path'] = array(
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030099 'host' => $matches[1],
100 'port' => empty($matches[2]) ? NULL : $matches[2],
101 'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : NULL,
102 'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : NULL,
103 'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : NULL
104 );
105
106 preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->_key_prefix = $match[1];
107 }
108 else
109 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300110 log_message('error', 'Session: Invalid Redis save path format: '.$this->_config['save_path']);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300111 }
112
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300113 if ($this->_config['match_ip'] === TRUE)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300114 {
115 $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':';
116 }
117 }
118
119 // ------------------------------------------------------------------------
120
Andrey Andreev10411fc2015-01-19 13:54:53 +0200121 /**
122 * Open
123 *
124 * Sanitizes save_path and initializes connection.
125 *
126 * @param string $save_path Server path
127 * @param string $name Session cookie name, unused
128 * @return bool
129 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300130 public function open($save_path, $name)
131 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300132 if (empty($this->_config['save_path']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300133 {
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200134 return $this->_fail();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300135 }
136
137 $redis = new Redis();
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300138 if ( ! $redis->connect($this->_config['save_path']['host'], $this->_config['save_path']['port'], $this->_config['save_path']['timeout']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300139 {
140 log_message('error', 'Session: Unable to connect to Redis with the configured settings.');
141 }
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300142 elseif (isset($this->_config['save_path']['password']) && ! $redis->auth($this->_config['save_path']['password']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300143 {
144 log_message('error', 'Session: Unable to authenticate to Redis instance.');
145 }
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300146 elseif (isset($this->_config['save_path']['database']) && ! $redis->select($this->_config['save_path']['database']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300147 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300148 log_message('error', 'Session: Unable to select Redis database with index '.$this->_config['save_path']['database']);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300149 }
150 else
151 {
152 $this->_redis = $redis;
Andrey Andreevaf849692015-12-12 14:07:39 +0200153 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300154 }
155
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200156 return $this->_fail();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300157 }
158
159 // ------------------------------------------------------------------------
160
Andrey Andreev10411fc2015-01-19 13:54:53 +0200161 /**
162 * Read
163 *
164 * Reads session data and acquires a lock
165 *
166 * @param string $session_id Session ID
167 * @return string Serialized session data
168 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300169 public function read($session_id)
170 {
171 if (isset($this->_redis) && $this->_get_lock($session_id))
172 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200173 // Needed by write() to detect session_regenerate_id() calls
174 $this->_session_id = $session_id;
175
Andrey Andreev173cf412016-02-05 14:36:50 +0200176 $session_data = $this->_redis->get($this->_key_prefix.$session_id);
177
178 is_string($session_data)
179 ? $this->_key_exists = TRUE
180 : $session_data = '';
181
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300182 $this->_fingerprint = md5($session_data);
183 return $session_data;
184 }
185
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200186 return $this->_fail();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300187 }
188
Andrey Andreev10411fc2015-01-19 13:54:53 +0200189 // ------------------------------------------------------------------------
190
191 /**
192 * Write
193 *
194 * Writes (create / update) session data
195 *
196 * @param string $session_id Session ID
197 * @param string $session_data Serialized session data
198 * @return bool
199 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300200 public function write($session_id, $session_data)
201 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200202 if ( ! isset($this->_redis))
203 {
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200204 return $this->_fail();
Andrey Andreev7474a672014-10-31 23:35:32 +0200205 }
206 // Was the ID regenerated?
207 elseif ($session_id !== $this->_session_id)
208 {
209 if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
210 {
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200211 return $this->_fail();
Andrey Andreev7474a672014-10-31 23:35:32 +0200212 }
213
Andrey Andreev173cf412016-02-05 14:36:50 +0200214 $this->_key_exists = FALSE;
Andrey Andreev7474a672014-10-31 23:35:32 +0200215 $this->_session_id = $session_id;
216 }
217
218 if (isset($this->_lock_key))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300219 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200220 $this->_redis->setTimeout($this->_lock_key, 300);
Andrey Andreev173cf412016-02-05 14:36:50 +0200221 if ($this->_fingerprint !== ($fingerprint = md5($session_data)) OR $this->_key_exists === FALSE)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300222 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300223 if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300224 {
225 $this->_fingerprint = $fingerprint;
Andrey Andreev173cf412016-02-05 14:36:50 +0200226 $this->_key_exists = TRUE;
Andrey Andreevaf849692015-12-12 14:07:39 +0200227 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300228 }
229
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200230 return $this->_fail();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300231 }
232
Andrey Andreevaf849692015-12-12 14:07:39 +0200233 return ($this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration']))
234 ? $this->_success
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200235 : $this->_fail();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300236 }
237
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200238 return $this->_fail();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300239 }
240
241 // ------------------------------------------------------------------------
242
Andrey Andreev10411fc2015-01-19 13:54:53 +0200243 /**
244 * Close
245 *
246 * Releases locks and closes connection.
247 *
Gabriel Potkány1fb50002015-02-04 01:45:59 +0100248 * @return bool
Andrey Andreev10411fc2015-01-19 13:54:53 +0200249 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300250 public function close()
251 {
252 if (isset($this->_redis))
253 {
254 try {
255 if ($this->_redis->ping() === '+PONG')
256 {
Andrey Andreevf06858c2016-02-29 17:35:12 +0200257 $this->_release_lock();
Andrey Andreevd6807792016-05-26 10:28:04 +0300258 if ($this->_redis->close() === FALSE)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300259 {
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200260 return $this->_fail();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300261 }
262 }
263 }
264 catch (RedisException $e)
265 {
266 log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
267 }
268
269 $this->_redis = NULL;
Andrey Andreevaf849692015-12-12 14:07:39 +0200270 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300271 }
272
Andrey Andreevaf849692015-12-12 14:07:39 +0200273 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300274 }
275
276 // ------------------------------------------------------------------------
277
Andrey Andreev10411fc2015-01-19 13:54:53 +0200278 /**
279 * Destroy
280 *
281 * Destroys the current session.
282 *
283 * @param string $session_id Session ID
284 * @return bool
285 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300286 public function destroy($session_id)
287 {
288 if (isset($this->_redis, $this->_lock_key))
289 {
Andrey Andreevabc8f002015-02-23 08:38:06 +0200290 if (($result = $this->_redis->delete($this->_key_prefix.$session_id)) !== 1)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300291 {
292 log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.');
293 }
294
Andrey Andreevaf849692015-12-12 14:07:39 +0200295 $this->_cookie_destroy();
296 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300297 }
298
Andrey Andreeva027a7f2016-03-10 13:59:20 +0200299 return $this->_fail();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300300 }
301
302 // ------------------------------------------------------------------------
303
Andrey Andreev10411fc2015-01-19 13:54:53 +0200304 /**
305 * Garbage Collector
306 *
307 * Deletes expired sessions
308 *
309 * @param int $maxlifetime Maximum lifetime of sessions
310 * @return bool
311 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300312 public function gc($maxlifetime)
313 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200314 // Not necessary, Redis takes care of that.
Andrey Andreevaf849692015-12-12 14:07:39 +0200315 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300316 }
317
318 // ------------------------------------------------------------------------
319
Andrey Andreev10411fc2015-01-19 13:54:53 +0200320 /**
321 * Get lock
322 *
323 * Acquires an (emulated) lock.
324 *
325 * @param string $session_id Session ID
326 * @return bool
327 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300328 protected function _get_lock($session_id)
329 {
Andrey Andreev79b8a082016-01-07 13:55:21 +0200330 // PHP 7 reuses the SessionHandler object on regeneration,
331 // so we need to check here if the lock key is for the
332 // correct session ID.
333 if ($this->_lock_key === $this->_key_prefix.$session_id.':lock')
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300334 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200335 return $this->_redis->setTimeout($this->_lock_key, 300);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300336 }
337
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200338 // 30 attempts to obtain a lock, in case another request already has it
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300339 $lock_key = $this->_key_prefix.$session_id.':lock';
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300340 $attempt = 0;
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200341 do
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300342 {
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300343 if (($ttl = $this->_redis->ttl($lock_key)) > 0)
344 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200345 sleep(1);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300346 continue;
347 }
348
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200349 if ( ! $this->_redis->setex($lock_key, 300, time()))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300350 {
351 log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
352 return FALSE;
353 }
354
355 $this->_lock_key = $lock_key;
356 break;
357 }
Andrey Andreev73b9e852015-04-30 13:06:40 +0300358 while (++$attempt < 30);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300359
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200360 if ($attempt === 30)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300361 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200362 log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.');
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300363 return FALSE;
364 }
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200365 elseif ($ttl === -1)
366 {
367 log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
368 }
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300369
370 $this->_lock = TRUE;
371 return TRUE;
372 }
373
374 // ------------------------------------------------------------------------
375
Andrey Andreev10411fc2015-01-19 13:54:53 +0200376 /**
377 * Release lock
378 *
379 * Releases a previously acquired lock
380 *
381 * @return bool
382 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300383 protected function _release_lock()
384 {
385 if (isset($this->_redis, $this->_lock_key) && $this->_lock)
386 {
387 if ( ! $this->_redis->delete($this->_lock_key))
388 {
Andrey Andreev00025882015-02-11 16:23:46 +0200389 log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300390 return FALSE;
391 }
392
393 $this->_lock_key = NULL;
394 $this->_lock = FALSE;
395 }
396
397 return TRUE;
398 }
399
400}