blob: cde587b97bc8b150d8e4f4074e9e1cc7ae055486 [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
114 public function open($save_path, $name)
115 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300116 if (empty($this->_config['save_path']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300117 {
118 return FALSE;
119 }
120
121 $redis = new Redis();
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300122 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 +0300123 {
124 log_message('error', 'Session: Unable to connect to Redis with the configured settings.');
125 }
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300126 elseif (isset($this->_config['save_path']['password']) && ! $redis->auth($this->_config['save_path']['password']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300127 {
128 log_message('error', 'Session: Unable to authenticate to Redis instance.');
129 }
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300130 elseif (isset($this->_config['save_path']['database']) && ! $redis->select($this->_config['save_path']['database']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300131 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300132 log_message('error', 'Session: Unable to select Redis database with index '.$this->_config['save_path']['database']);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300133 }
134 else
135 {
136 $this->_redis = $redis;
137 return TRUE;
138 }
139
140 return FALSE;
141 }
142
143 // ------------------------------------------------------------------------
144
145 public function read($session_id)
146 {
147 if (isset($this->_redis) && $this->_get_lock($session_id))
148 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200149 // Needed by write() to detect session_regenerate_id() calls
150 $this->_session_id = $session_id;
151
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300152 $session_data = (string) $this->_redis->get($this->_key_prefix.$session_id);
153 $this->_fingerprint = md5($session_data);
154 return $session_data;
155 }
156
157 return FALSE;
158 }
159
160 public function write($session_id, $session_data)
161 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200162 if ( ! isset($this->_redis))
163 {
164 return FALSE;
165 }
166 // Was the ID regenerated?
167 elseif ($session_id !== $this->_session_id)
168 {
169 if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
170 {
171 return FALSE;
172 }
173
174 $this->_fingerprint = md5('');
175 $this->_session_id = $session_id;
176 }
177
178 if (isset($this->_lock_key))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300179 {
Andrey Andreev2a1f9402014-08-27 23:52:55 +0300180 $this->_redis->setTimeout($this->_lock_key, 5);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300181 if ($this->_fingerprint !== ($fingerprint = md5($session_data)))
182 {
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300183 if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration']))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300184 {
185 $this->_fingerprint = $fingerprint;
186 return TRUE;
187 }
188
189 return FALSE;
190 }
191
Andrey Andreevdfb39be2014-10-06 01:50:14 +0300192 return $this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration']);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300193 }
194
195 return FALSE;
196 }
197
198 // ------------------------------------------------------------------------
199
200 public function close()
201 {
202 if (isset($this->_redis))
203 {
204 try {
205 if ($this->_redis->ping() === '+PONG')
206 {
207 isset($this->_lock_key) && $this->_redis->delete($this->_lock_key);
208 if ( ! $this->_redis->close())
209 {
210 return FALSE;
211 }
212 }
213 }
214 catch (RedisException $e)
215 {
216 log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
217 }
218
219 $this->_redis = NULL;
220 return TRUE;
221 }
222
Andrey Andreev7474a672014-10-31 23:35:32 +0200223 return TRUE;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300224 }
225
226 // ------------------------------------------------------------------------
227
228 public function destroy($session_id)
229 {
230 if (isset($this->_redis, $this->_lock_key))
231 {
232 if ($this->_redis->delete($this->_key_prefix.$session_id) !== 1)
233 {
234 log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.');
235 }
236
Andrey Andreev7474a672014-10-31 23:35:32 +0200237 return $this->_cookie_destroy();
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300238 }
239
Andrey Andreev7474a672014-10-31 23:35:32 +0200240 return FALSE;
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300241 }
242
243 // ------------------------------------------------------------------------
244
245 public function gc($maxlifetime)
246 {
Andrey Andreev7474a672014-10-31 23:35:32 +0200247 // Not necessary, Redis takes care of that.
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300248 return TRUE;
249 }
250
251 // ------------------------------------------------------------------------
252
253 protected function _get_lock($session_id)
254 {
255 if (isset($this->_lock_key))
256 {
257 return $this->_redis->setTimeout($this->_lock_key, 5);
258 }
259
260 $lock_key = $this->_key_prefix.$session_id.':lock';
261 if (($ttl = $this->_redis->ttl($lock_key)) < 1)
262 {
263 if ( ! $this->_redis->setex($lock_key, 5, time()))
264 {
265 log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
266 return FALSE;
267 }
268
269 $this->_lock_key = $lock_key;
270
271 if ($ttl === -1)
272 {
273 log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
274 }
275
276 $this->_lock = TRUE;
277 return TRUE;
278 }
279
280 // Another process has the lock, we'll try to wait for it to free itself ...
281 $attempt = 0;
282 while ($attempt++ < 5)
283 {
284 usleep(($ttl * 1000000) - 20000);
285 if (($ttl = $this->_redis->ttl($lock_key)) > 0)
286 {
287 continue;
288 }
289
290 if ( ! $this->_redis->setex($lock_key, 5, time()))
291 {
292 log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
293 return FALSE;
294 }
295
296 $this->_lock_key = $lock_key;
297 break;
298 }
299
300 if ($attempt === 5)
301 {
302 log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 5 attempts, aborting.');
303 return FALSE;
304 }
305
306 $this->_lock = TRUE;
307 return TRUE;
308 }
309
310 // ------------------------------------------------------------------------
311
312 protected function _release_lock()
313 {
314 if (isset($this->_redis, $this->_lock_key) && $this->_lock)
315 {
316 if ( ! $this->_redis->delete($this->_lock_key))
317 {
318 log_message('error', 'Session: Error while trying to free lock for '.$this->_key_prefix.$session_id);
319 return FALSE;
320 }
321
322 $this->_lock_key = NULL;
323 $this->_lock = FALSE;
324 }
325
326 return TRUE;
327 }
328
329}
330
331/* End of file Session_redis_driver.php */
332/* Location: ./system/libraries/Session/drivers/Session_redis_driver.php */