blob: 1ce101dafc800d8e501ebdd6ab976952aeba3727 [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 {
127 return FALSE;
128 }
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;
146 return TRUE;
147 }
148
149 return FALSE;
150 }
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
Gabriel Potkány0dd25382015-02-04 12:15:06 +0100174 return FALSE;
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 {
192 return FALSE;
193 }
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 {
199 return FALSE;
200 }
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;
214 return TRUE;
215 }
216
217 return FALSE;
218 }
219
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300220 return $this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration']);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300221 }
222
223 return FALSE;
224 }
225
226 // ------------------------------------------------------------------------
227
Andrey Andreev10411fc2015-01-19 13:54:53 +0200228 /**
229 * Close
230 *
231 * Releases locks and closes connection.
232 *
Gabriel Potkány1fb50002015-02-04 01:45:59 +0100233 * @return bool
Andrey Andreev10411fc2015-01-19 13:54:53 +0200234 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300235 public function close()
236 {
237 if (isset($this->_redis))
238 {
239 try {
240 if ($this->_redis->ping() === '+PONG')
241 {
242 isset($this->_lock_key) && $this->_redis->delete($this->_lock_key);
243 if ( ! $this->_redis->close())
244 {
245 return FALSE;
246 }
247 }
248 }
249 catch (RedisException $e)
250 {
251 log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
252 }
253
254 $this->_redis = NULL;
255 return TRUE;
256 }
257
Andrey Andreev7474a672014-10-31 23:35:32 +0200258 return TRUE;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300259 }
260
261 // ------------------------------------------------------------------------
262
Andrey Andreev10411fc2015-01-19 13:54:53 +0200263 /**
264 * Destroy
265 *
266 * Destroys the current session.
267 *
268 * @param string $session_id Session ID
269 * @return bool
270 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300271 public function destroy($session_id)
272 {
273 if (isset($this->_redis, $this->_lock_key))
274 {
Andrey Andreevabc8f002015-02-23 08:38:06 +0200275 if (($result = $this->_redis->delete($this->_key_prefix.$session_id)) !== 1)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300276 {
277 log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.');
278 }
279
Andrey Andreev7474a672014-10-31 23:35:32 +0200280 return $this->_cookie_destroy();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300281 }
282
Andrey Andreev7474a672014-10-31 23:35:32 +0200283 return FALSE;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300284 }
285
286 // ------------------------------------------------------------------------
287
Andrey Andreev10411fc2015-01-19 13:54:53 +0200288 /**
289 * Garbage Collector
290 *
291 * Deletes expired sessions
292 *
293 * @param int $maxlifetime Maximum lifetime of sessions
294 * @return bool
295 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300296 public function gc($maxlifetime)
297 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200298 // Not necessary, Redis takes care of that.
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300299 return TRUE;
300 }
301
302 // ------------------------------------------------------------------------
303
Andrey Andreev10411fc2015-01-19 13:54:53 +0200304 /**
305 * Get lock
306 *
307 * Acquires an (emulated) lock.
308 *
309 * @param string $session_id Session ID
310 * @return bool
311 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300312 protected function _get_lock($session_id)
313 {
314 if (isset($this->_lock_key))
315 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200316 return $this->_redis->setTimeout($this->_lock_key, 300);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300317 }
318
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200319 // 30 attempts to obtain a lock, in case another request already has it
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300320 $lock_key = $this->_key_prefix.$session_id.':lock';
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300321 $attempt = 0;
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200322 do
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300323 {
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300324 if (($ttl = $this->_redis->ttl($lock_key)) > 0)
325 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200326 sleep(1);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300327 continue;
328 }
329
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200330 if ( ! $this->_redis->setex($lock_key, 300, time()))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300331 {
332 log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
333 return FALSE;
334 }
335
336 $this->_lock_key = $lock_key;
337 break;
338 }
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200339 while ($attempt++ < 30);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300340
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200341 if ($attempt === 30)
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300342 {
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200343 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 +0300344 return FALSE;
345 }
Andrey Andreeve1a5bb32015-03-04 13:33:39 +0200346 elseif ($ttl === -1)
347 {
348 log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
349 }
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300350
351 $this->_lock = TRUE;
352 return TRUE;
353 }
354
355 // ------------------------------------------------------------------------
356
Andrey Andreev10411fc2015-01-19 13:54:53 +0200357 /**
358 * Release lock
359 *
360 * Releases a previously acquired lock
361 *
362 * @return bool
363 */
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300364 protected function _release_lock()
365 {
366 if (isset($this->_redis, $this->_lock_key) && $this->_lock)
367 {
368 if ( ! $this->_redis->delete($this->_lock_key))
369 {
Andrey Andreev00025882015-02-11 16:23:46 +0200370 log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300371 return FALSE;
372 }
373
374 $this->_lock_key = NULL;
375 $this->_lock = FALSE;
376 }
377
378 return TRUE;
379 }
380
381}