blob: 6d8044da1d441d10c205d5bd48da720475936bce [file] [log] [blame]
Andrey Andreev43f6cdb2014-08-27 22:26:40 +03001<?php
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 5.2.4 or newer
6 *
7 * NOTICE OF LICENSE
8 *
9 * Licensed under the Open Software License version 3.0
10 *
11 * This source file is subject to the Open Software License (OSL 3.0) that is
12 * bundled with this package in the files license.txt / license.rst. It is
13 * also available through the world wide web at this URL:
14 * http://opensource.org/licenses/OSL-3.0
15 * If you did not receive a copy of the license and are unable to obtain it
16 * through the world wide web, please send an email to
17 * licensing@ellislab.com so we can send you a copy immediately.
18 *
19 * @package CodeIgniter
20 * @author Andrey Andreev
21 * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
22 * @license http://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
23 * @link http://codeigniter.com
24 * @since Version 3.0
25 * @filesource
26 */
27defined('BASEPATH') OR exit('No direct script access allowed');
28
29/**
30 * CodeIgniter Session Redis Driver
31 *
32 * @package CodeIgniter
33 * @subpackage Libraries
34 * @category Sessions
35 * @author Andrey Andreev
36 * @link http://codeigniter.com/user_guide/libraries/sessions.html
37 */
38class CI_Session_redis_driver extends CI_Session_driver implements SessionHandlerInterface {
39
40 /**
41 * Save path
42 *
43 * @var string
44 */
45 protected $_save_path;
46
47 /**
48 * phpRedis instance
49 *
50 * @var resource
51 */
52 protected $_redis;
53
54 /**
55 * Key prefix
56 *
57 * @var string
58 */
59 protected $_key_prefix = 'ci_session:';
60
61 /**
62 * Lock key
63 *
64 * @var string
65 */
66 protected $_lock_key;
67
68 // ------------------------------------------------------------------------
69
70 /**
71 * Class constructor
72 *
73 * @param array $params Configuration parameters
74 * @return void
75 */
76 public function __construct(&$params)
77 {
78 parent::__construct($params);
79
80 if (empty($this->_save_path))
81 {
82 log_message('error', 'Session: No Redis save path configured.');
83 }
Andrey Andreev39ec2952014-09-17 14:16:05 +030084 elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_save_path, $matches))
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030085 {
Andrey Andreev39ec2952014-09-17 14:16:05 +030086 isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below
Andrey Andreev43f6cdb2014-08-27 22:26:40 +030087 $this->_save_path = array(
88 'host' => $matches[1],
89 'port' => empty($matches[2]) ? NULL : $matches[2],
90 'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : NULL,
91 'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : NULL,
92 'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : NULL
93 );
94
95 preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->_key_prefix = $match[1];
96 }
97 else
98 {
99 log_message('error', 'Session: Invalid Redis save path format: '.$this->_save_path);
100 }
101
102 if ($this->_match_ip === TRUE)
103 {
104 $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':';
105 }
106 }
107
108 // ------------------------------------------------------------------------
109
110 public function open($save_path, $name)
111 {
112 if (empty($this->_save_path))
113 {
114 return FALSE;
115 }
116
117 $redis = new Redis();
118 if ( ! $redis->connect($this->_save_path['host'], $this->_save_path['port'], $this->_save_path['timeout']))
119 {
120 log_message('error', 'Session: Unable to connect to Redis with the configured settings.');
121 }
122 elseif (isset($this->_save_path['password']) && ! $redis->auth($this->_save_path['password']))
123 {
124 log_message('error', 'Session: Unable to authenticate to Redis instance.');
125 }
126 elseif (isset($this->_save_path['database']) && ! $redis->select($this->_save_path['database']))
127 {
128 log_message('error', 'Session: Unable to select Redis database with index '.$this->_save_path['database']);
129 }
130 else
131 {
132 $this->_redis = $redis;
133 return TRUE;
134 }
135
136 return FALSE;
137 }
138
139 // ------------------------------------------------------------------------
140
141 public function read($session_id)
142 {
143 if (isset($this->_redis) && $this->_get_lock($session_id))
144 {
145 $session_data = (string) $this->_redis->get($this->_key_prefix.$session_id);
146 $this->_fingerprint = md5($session_data);
147 return $session_data;
148 }
149
150 return FALSE;
151 }
152
153 public function write($session_id, $session_data)
154 {
155 if (isset($this->_redis, $this->_lock_key))
156 {
Andrey Andreev2a1f9402014-08-27 23:52:55 +0300157 $this->_redis->setTimeout($this->_lock_key, 5);
Andrey Andreev43f6cdb2014-08-27 22:26:40 +0300158 if ($this->_fingerprint !== ($fingerprint = md5($session_data)))
159 {
160 if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_expiration))
161 {
162 $this->_fingerprint = $fingerprint;
163 return TRUE;
164 }
165
166 return FALSE;
167 }
168
169 return $this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_expiration);
170 }
171
172 return FALSE;
173 }
174
175 // ------------------------------------------------------------------------
176
177 public function close()
178 {
179 if (isset($this->_redis))
180 {
181 try {
182 if ($this->_redis->ping() === '+PONG')
183 {
184 isset($this->_lock_key) && $this->_redis->delete($this->_lock_key);
185 if ( ! $this->_redis->close())
186 {
187 return FALSE;
188 }
189 }
190 }
191 catch (RedisException $e)
192 {
193 log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
194 }
195
196 $this->_redis = NULL;
197 return TRUE;
198 }
199
200 return FALSE;
201 }
202
203 // ------------------------------------------------------------------------
204
205 public function destroy($session_id)
206 {
207 if (isset($this->_redis, $this->_lock_key))
208 {
209 if ($this->_redis->delete($this->_key_prefix.$session_id) !== 1)
210 {
211 log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.');
212 }
213
214 return ($this->_cookie_destroy() && $this->close());
215 }
216
217 return $this->close();
218 }
219
220 // ------------------------------------------------------------------------
221
222 public function gc($maxlifetime)
223 {
224 // TODO: keys()/getKeys() is said to be performance-intensive,
225 // although it supports patterns (*, [charlist] at the very least).
226 // scan() seems to be recommended, but requires redis 2.8
227 // Not sure if we need any of these though, as we set keys with expire times
228 return TRUE;
229 }
230
231 // ------------------------------------------------------------------------
232
233 protected function _get_lock($session_id)
234 {
235 if (isset($this->_lock_key))
236 {
237 return $this->_redis->setTimeout($this->_lock_key, 5);
238 }
239
240 $lock_key = $this->_key_prefix.$session_id.':lock';
241 if (($ttl = $this->_redis->ttl($lock_key)) < 1)
242 {
243 if ( ! $this->_redis->setex($lock_key, 5, time()))
244 {
245 log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
246 return FALSE;
247 }
248
249 $this->_lock_key = $lock_key;
250
251 if ($ttl === -1)
252 {
253 log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
254 }
255
256 $this->_lock = TRUE;
257 return TRUE;
258 }
259
260 // Another process has the lock, we'll try to wait for it to free itself ...
261 $attempt = 0;
262 while ($attempt++ < 5)
263 {
264 usleep(($ttl * 1000000) - 20000);
265 if (($ttl = $this->_redis->ttl($lock_key)) > 0)
266 {
267 continue;
268 }
269
270 if ( ! $this->_redis->setex($lock_key, 5, time()))
271 {
272 log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
273 return FALSE;
274 }
275
276 $this->_lock_key = $lock_key;
277 break;
278 }
279
280 if ($attempt === 5)
281 {
282 log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 5 attempts, aborting.');
283 return FALSE;
284 }
285
286 $this->_lock = TRUE;
287 return TRUE;
288 }
289
290 // ------------------------------------------------------------------------
291
292 protected function _release_lock()
293 {
294 if (isset($this->_redis, $this->_lock_key) && $this->_lock)
295 {
296 if ( ! $this->_redis->delete($this->_lock_key))
297 {
298 log_message('error', 'Session: Error while trying to free lock for '.$this->_key_prefix.$session_id);
299 return FALSE;
300 }
301
302 $this->_lock_key = NULL;
303 $this->_lock = FALSE;
304 }
305
306 return TRUE;
307 }
308
309}
310
311/* End of file Session_redis_driver.php */
312/* Location: ./system/libraries/Session/drivers/Session_redis_driver.php */