Subversion-Projekte lars-tiefland.ci

Revision

Revision 2254 | Zur aktuellen Revision | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
68 lars 1
<?php
2
/**
3
 * CodeIgniter
4
 *
5
 * An open source application development framework for PHP
6
 *
7
 * This content is released under the MIT License (MIT)
8
 *
2257 lars 9
 * Copyright (c) 2014 - 2018, British Columbia Institute of Technology
68 lars 10
 *
11
 * 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:
17
 *
18
 * 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
31
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
2257 lars 32
 * @copyright	Copyright (c) 2014 - 2018, British Columbia Institute of Technology (http://bcit.ca/)
68 lars 33
 * @license	http://opensource.org/licenses/MIT	MIT License
34
 * @link	https://codeigniter.com
35
 * @since	Version 3.0.0
36
 * @filesource
37
 */
38
defined('BASEPATH') OR exit('No direct script access allowed');
39
 
40
/**
41
 * CodeIgniter Session Redis Driver
42
 *
43
 * @package	CodeIgniter
44
 * @subpackage	Libraries
45
 * @category	Sessions
46
 * @author	Andrey Andreev
47
 * @link	https://codeigniter.com/user_guide/libraries/sessions.html
48
 */
49
class CI_Session_redis_driver extends CI_Session_driver implements SessionHandlerInterface {
50
 
51
	/**
52
	 * phpRedis instance
53
	 *
2107 lars 54
	 * @var	Redis
68 lars 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
	 * Key exists flag
74
	 *
75
	 * @var bool
76
	 */
77
	protected $_key_exists = FALSE;
78
 
79
	// ------------------------------------------------------------------------
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
 
91
		if (empty($this->_config['save_path']))
92
		{
93
			log_message('error', 'Session: No Redis save path configured.');
94
		}
95
		elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_config['save_path'], $matches))
96
		{
97
			isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below
98
			$this->_config['save_path'] = array(
99
				'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
		{
110
			log_message('error', 'Session: Invalid Redis save path format: '.$this->_config['save_path']);
111
		}
112
 
113
		if ($this->_config['match_ip'] === TRUE)
114
		{
115
			$this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':';
116
		}
117
	}
118
 
119
	// ------------------------------------------------------------------------
120
 
121
	/**
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
	 */
130
	public function open($save_path, $name)
131
	{
132
		if (empty($this->_config['save_path']))
133
		{
134
			return $this->_fail();
135
		}
136
 
137
		$redis = new Redis();
138
		if ( ! $redis->connect($this->_config['save_path']['host'], $this->_config['save_path']['port'], $this->_config['save_path']['timeout']))
139
		{
140
			log_message('error', 'Session: Unable to connect to Redis with the configured settings.');
141
		}
142
		elseif (isset($this->_config['save_path']['password']) && ! $redis->auth($this->_config['save_path']['password']))
143
		{
144
			log_message('error', 'Session: Unable to authenticate to Redis instance.');
145
		}
146
		elseif (isset($this->_config['save_path']['database']) && ! $redis->select($this->_config['save_path']['database']))
147
		{
148
			log_message('error', 'Session: Unable to select Redis database with index '.$this->_config['save_path']['database']);
149
		}
150
		else
151
		{
152
			$this->_redis = $redis;
153
			return $this->_success;
154
		}
155
 
156
		return $this->_fail();
157
	}
158
 
159
	// ------------------------------------------------------------------------
160
 
161
	/**
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
	 */
169
	public function read($session_id)
170
	{
171
		if (isset($this->_redis) && $this->_get_lock($session_id))
172
		{
173
			// Needed by write() to detect session_regenerate_id() calls
174
			$this->_session_id = $session_id;
175
 
176
			$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
 
182
			$this->_fingerprint = md5($session_data);
183
			return $session_data;
184
		}
185
 
186
		return $this->_fail();
187
	}
188
 
189
	// ------------------------------------------------------------------------
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
	 */
200
	public function write($session_id, $session_data)
201
	{
2049 lars 202
		if ( ! isset($this->_redis, $this->_lock_key))
68 lars 203
		{
204
			return $this->_fail();
205
		}
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
			{
211
				return $this->_fail();
212
			}
213
 
214
			$this->_key_exists = FALSE;
215
			$this->_session_id = $session_id;
216
		}
217
 
2049 lars 218
		$this->_redis->setTimeout($this->_lock_key, 300);
219
		if ($this->_fingerprint !== ($fingerprint = md5($session_data)) OR $this->_key_exists === FALSE)
68 lars 220
		{
2049 lars 221
			if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration']))
68 lars 222
			{
2049 lars 223
				$this->_fingerprint = $fingerprint;
224
				$this->_key_exists = TRUE;
225
				return $this->_success;
68 lars 226
			}
227
 
2049 lars 228
			return $this->_fail();
68 lars 229
		}
230
 
2049 lars 231
		return ($this->_redis->setTimeout($this->_key_prefix.$session_id, $this->_config['expiration']))
232
			? $this->_success
233
			: $this->_fail();
68 lars 234
	}
235
 
236
	// ------------------------------------------------------------------------
237
 
238
	/**
239
	 * Close
240
	 *
241
	 * Releases locks and closes connection.
242
	 *
243
	 * @return	bool
244
	 */
245
	public function close()
246
	{
247
		if (isset($this->_redis))
248
		{
249
			try {
250
				if ($this->_redis->ping() === '+PONG')
251
				{
252
					$this->_release_lock();
253
					if ($this->_redis->close() === FALSE)
254
					{
255
						return $this->_fail();
256
					}
257
				}
258
			}
259
			catch (RedisException $e)
260
			{
261
				log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
262
			}
263
 
264
			$this->_redis = NULL;
265
			return $this->_success;
266
		}
267
 
268
		return $this->_success;
269
	}
270
 
271
	// ------------------------------------------------------------------------
272
 
273
	/**
274
	 * Destroy
275
	 *
276
	 * Destroys the current session.
277
	 *
278
	 * @param	string	$session_id	Session ID
279
	 * @return	bool
280
	 */
281
	public function destroy($session_id)
282
	{
283
		if (isset($this->_redis, $this->_lock_key))
284
		{
285
			if (($result = $this->_redis->delete($this->_key_prefix.$session_id)) !== 1)
286
			{
287
				log_message('debug', 'Session: Redis::delete() expected to return 1, got '.var_export($result, TRUE).' instead.');
288
			}
289
 
290
			$this->_cookie_destroy();
291
			return $this->_success;
292
		}
293
 
294
		return $this->_fail();
295
	}
296
 
297
	// ------------------------------------------------------------------------
298
 
299
	/**
300
	 * Garbage Collector
301
	 *
302
	 * Deletes expired sessions
303
	 *
304
	 * @param	int 	$maxlifetime	Maximum lifetime of sessions
305
	 * @return	bool
306
	 */
307
	public function gc($maxlifetime)
308
	{
309
		// Not necessary, Redis takes care of that.
310
		return $this->_success;
311
	}
312
 
313
	// ------------------------------------------------------------------------
314
 
315
	/**
316
	 * Get lock
317
	 *
318
	 * Acquires an (emulated) lock.
319
	 *
320
	 * @param	string	$session_id	Session ID
321
	 * @return	bool
322
	 */
323
	protected function _get_lock($session_id)
324
	{
325
		// PHP 7 reuses the SessionHandler object on regeneration,
326
		// so we need to check here if the lock key is for the
327
		// correct session ID.
328
		if ($this->_lock_key === $this->_key_prefix.$session_id.':lock')
329
		{
330
			return $this->_redis->setTimeout($this->_lock_key, 300);
331
		}
332
 
333
		// 30 attempts to obtain a lock, in case another request already has it
334
		$lock_key = $this->_key_prefix.$session_id.':lock';
335
		$attempt = 0;
336
		do
337
		{
338
			if (($ttl = $this->_redis->ttl($lock_key)) > 0)
339
			{
340
				sleep(1);
341
				continue;
342
			}
343
 
2107 lars 344
			$result = ($ttl === -2)
345
				? $this->_redis->set($lock_key, time(), array('nx', 'ex' => 300))
346
				: $this->_redis->setex($lock_key, 300, time());
347
 
348
			if ( ! $result)
68 lars 349
			{
350
				log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
351
				return FALSE;
352
			}
353
 
354
			$this->_lock_key = $lock_key;
355
			break;
356
		}
357
		while (++$attempt < 30);
358
 
359
		if ($attempt === 30)
360
		{
361
			log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.');
362
			return FALSE;
363
		}
364
		elseif ($ttl === -1)
365
		{
366
			log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
367
		}
368
 
369
		$this->_lock = TRUE;
370
		return TRUE;
371
	}
372
 
373
	// ------------------------------------------------------------------------
374
 
375
	/**
376
	 * Release lock
377
	 *
378
	 * Releases a previously acquired lock
379
	 *
380
	 * @return	bool
381
	 */
382
	protected function _release_lock()
383
	{
384
		if (isset($this->_redis, $this->_lock_key) && $this->_lock)
385
		{
386
			if ( ! $this->_redis->delete($this->_lock_key))
387
			{
388
				log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
389
				return FALSE;
390
			}
391
 
392
			$this->_lock_key = NULL;
393
			$this->_lock = FALSE;
394
		}
395
 
396
		return TRUE;
397
	}
398
 
399
}