blob: e8915306f7c89f3cbe513954e3dcd4b9d7aa9f2c [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 Andreevbf6b11d2015-01-12 17:27:12 +02009 * Copyright (c) 2014 - 2015, 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 Andreev43f6cdb2014-08-27 22:26:40 +030031 * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
Andrey Andreevbf6b11d2015-01-12 17:27:12 +020032 * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
Andrey Andreev46f2f262014-11-11 14:37:51 +020033 * @license http://opensource.org/licenses/MIT MIT License
34 * @link http://codeigniter.com
35 * @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
47 * @link http://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
72 // ------------------------------------------------------------------------
73
74 /**
75 * Class constructor
76 *
77 * @param array $params Configuration parameters
78 * @return void
79 */
80 public function __construct(&$params)
81 {
82 parent::__construct($params);
83
Andrey Andreevdfb39be2014-10-06 01:50:14 +030084 if (empty($this->_config['save_path']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030085 {
86 log_message('error', 'Session: No Redis save path configured.');
87 }
Andrey Andreevdfb39be2014-10-06 01:50:14 +030088 elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_config['save_path'], $matches))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030089 {
Andrey Andreev39ec2952014-09-17 14:16:05 +030090 isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below
Andrey Andreevdfb39be2014-10-06 01:50:14 +030091 $this->_config['save_path'] = array(
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030092 'host' => $matches[1],
93 'port' => empty($matches[2]) ? NULL : $matches[2],
94 'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : NULL,
95 'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : NULL,
96 'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : NULL
97 );
98
99 preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->_key_prefix = $match[1];
100 }
101 else
102 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300103 log_message('error', 'Session: Invalid Redis save path format: '.$this->_config['save_path']);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300104 }
105
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300106 if ($this->_config['match_ip'] === TRUE)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300107 {
108 $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':';
109 }
110 }
111
112 // ------------------------------------------------------------------------
113
Andrey Andreev10411fc2015-01-19 13:54:53 +0200114 /**
115 * Open
116 *
117 * Sanitizes save_path and initializes connection.
118 *
119 * @param string $save_path Server path
120 * @param string $name Session cookie name, unused
121 * @return bool
122 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300123 public function open($save_path, $name)
124 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300125 if (empty($this->_config['save_path']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300126 {
Andrey Andreevaf849692015-12-12 14:07:39 +0200127 return $this->_failure;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300128 }
129
130 $redis = new Redis();
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300131 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 +0300132 {
133 log_message('error', 'Session: Unable to connect to Redis with the configured settings.');
134 }
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300135 elseif (isset($this->_config['save_path']['password']) && ! $redis->auth($this->_config['save_path']['password']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300136 {
137 log_message('error', 'Session: Unable to authenticate to Redis instance.');
138 }
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300139 elseif (isset($this->_config['save_path']['database']) && ! $redis->select($this->_config['save_path']['database']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300140 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300141 log_message('error', 'Session: Unable to select Redis database with index '.$this->_config['save_path']['database']);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300142 }
143 else
144 {
145 $this->_redis = $redis;
Andrey Andreevaf849692015-12-12 14:07:39 +0200146 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300147 }
148
Andrey Andreevaf849692015-12-12 14:07:39 +0200149 return $this->_failure;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300150 }
151
152 // ------------------------------------------------------------------------
153
Andrey Andreev10411fc2015-01-19 13:54:53 +0200154 /**
155 * Read
156 *
157 * Reads session data and acquires a lock
158 *
159 * @param string $session_id Session ID
160 * @return string Serialized session data
161 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300162 public function read($session_id)
163 {
164 if (isset($this->_redis) && $this->_get_lock($session_id))
165 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200166 // Needed by write() to detect session_regenerate_id() calls
167 $this->_session_id = $session_id;
168
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300169 $session_data = (string) $this->_redis->get($this->_key_prefix.$session_id);
170 $this->_fingerprint = md5($session_data);
171 return $session_data;
172 }
173
Andrey Andreevaf849692015-12-12 14:07:39 +0200174 return $this->_failure;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300175 }
176
Andrey Andreev10411fc2015-01-19 13:54:53 +0200177 // ------------------------------------------------------------------------
178
179 /**
180 * Write
181 *
182 * Writes (create / update) session data
183 *
184 * @param string $session_id Session ID
185 * @param string $session_data Serialized session data
186 * @return bool
187 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300188 public function write($session_id, $session_data)
189 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200190 if ( ! isset($this->_redis))
191 {
Andrey Andreevaf849692015-12-12 14:07:39 +0200192 return $this->_failure;
Andrey Andreev7474a672014-10-31 23:35:32 +0200193 }
194 // Was the ID regenerated?
195 elseif ($session_id !== $this->_session_id)
196 {
197 if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
198 {
Andrey Andreevaf849692015-12-12 14:07:39 +0200199 return $this->_failure;
Andrey Andreev7474a672014-10-31 23:35:32 +0200200 }
201
202 $this->_fingerprint = md5('');
203 $this->_session_id = $session_id;
204 }
205
206 if (isset($this->_lock_key))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300207 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200208 $this->_redis->setTimeout($this->_lock_key, 300);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300209 if ($this->_fingerprint !== ($fingerprint = md5($session_data)))
210 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300211 if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300212 {
213 $this->_fingerprint = $fingerprint;
Andrey Andreevaf849692015-12-12 14:07:39 +0200214 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300215 }
216
Andrey Andreevaf849692015-12-12 14:07:39 +0200217 return $this->_failure;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300218 }
219
Andrey Andreevaf849692015-12-12 14:07:39 +0200220 return ($this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration']))
221 ? $this->_success
222 : $this->_failure;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300223 }
224
Andrey Andreevaf849692015-12-12 14:07:39 +0200225 return $this->_failure;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300226 }
227
228 // ------------------------------------------------------------------------
229
Andrey Andreev10411fc2015-01-19 13:54:53 +0200230 /**
231 * Close
232 *
233 * Releases locks and closes connection.
234 *
Gabriel Potkány1fb50002015-02-04 01:45:59 +0100235 * @return bool
Andrey Andreev10411fc2015-01-19 13:54:53 +0200236 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300237 public function close()
238 {
239 if (isset($this->_redis))
240 {
241 try {
242 if ($this->_redis->ping() === '+PONG')
243 {
244 isset($this->_lock_key) && $this->_redis->delete($this->_lock_key);
245 if ( ! $this->_redis->close())
246 {
Andrey Andreevaf849692015-12-12 14:07:39 +0200247 return $this->_failure;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300248 }
249 }
250 }
251 catch (RedisException $e)
252 {
253 log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
254 }
255
256 $this->_redis = NULL;
Andrey Andreevaf849692015-12-12 14:07:39 +0200257 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300258 }
259
Andrey Andreevaf849692015-12-12 14:07:39 +0200260 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300261 }
262
263 // ------------------------------------------------------------------------
264
Andrey Andreev10411fc2015-01-19 13:54:53 +0200265 /**
266 * Destroy
267 *
268 * Destroys the current session.
269 *
270 * @param string $session_id Session ID
271 * @return bool
272 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300273 public function destroy($session_id)
274 {
275 if (isset($this->_redis, $this->_lock_key))
276 {
Andrey Andreevabc8f002015-02-23 08:38:06 +0200277 if (($result = $this->_redis->delete($this->_key_prefix.$session_id)) !== 1)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300278 {
279 log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.');
280 }
281
Andrey Andreevaf849692015-12-12 14:07:39 +0200282 $this->_cookie_destroy();
283 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300284 }
285
Andrey Andreevaf849692015-12-12 14:07:39 +0200286 return $this->_failure;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300287 }
288
289 // ------------------------------------------------------------------------
290
Andrey Andreev10411fc2015-01-19 13:54:53 +0200291 /**
292 * Garbage Collector
293 *
294 * Deletes expired sessions
295 *
296 * @param int $maxlifetime Maximum lifetime of sessions
297 * @return bool
298 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300299 public function gc($maxlifetime)
300 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200301 // Not necessary, Redis takes care of that.
Andrey Andreevaf849692015-12-12 14:07:39 +0200302 return $this->_success;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300303 }
304
305 // ------------------------------------------------------------------------
306
Andrey Andreev10411fc2015-01-19 13:54:53 +0200307 /**
308 * Get lock
309 *
310 * Acquires an (emulated) lock.
311 *
312 * @param string $session_id Session ID
313 * @return bool
314 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300315 protected function _get_lock($session_id)
316 {
317 if (isset($this->_lock_key))
318 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200319 return $this->_redis->setTimeout($this->_lock_key, 300);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300320 }
321
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200322 // 30 attempts to obtain a lock, in case another request already has it
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300323 $lock_key = $this->_key_prefix.$session_id.':lock';
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300324 $attempt = 0;
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200325 do
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300326 {
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300327 if (($ttl = $this->_redis->ttl($lock_key)) > 0)
328 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200329 sleep(1);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300330 continue;
331 }
332
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200333 if ( ! $this->_redis->setex($lock_key, 300, time()))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300334 {
335 log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
336 return FALSE;
337 }
338
339 $this->_lock_key = $lock_key;
340 break;
341 }
Andrey Andreev73b9e852015-04-30 13:06:40 +0300342 while (++$attempt < 30);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300343
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200344 if ($attempt === 30)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300345 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200346 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 +0300347 return FALSE;
348 }
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200349 elseif ($ttl === -1)
350 {
351 log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
352 }
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300353
354 $this->_lock = TRUE;
355 return TRUE;
356 }
357
358 // ------------------------------------------------------------------------
359
Andrey Andreev10411fc2015-01-19 13:54:53 +0200360 /**
361 * Release lock
362 *
363 * Releases a previously acquired lock
364 *
365 * @return bool
366 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300367 protected function _release_lock()
368 {
369 if (isset($this->_redis, $this->_lock_key) && $this->_lock)
370 {
371 if ( ! $this->_redis->delete($this->_lock_key))
372 {
Andrey Andreev00025882015-02-11 16:23:46 +0200373 log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300374 return FALSE;
375 }
376
377 $this->_lock_key = NULL;
378 $this->_lock = FALSE;
379 }
380
381 return TRUE;
382 }
383
384}