Subversion-Projekte lars-tiefland.ci

Revision

Revision 2257 | 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
 *
2414 lars 9
 * Copyright (c) 2014 - 2019, 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/)
2414 lars 32
 * @copyright	Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
33
 * @license	https://opensource.org/licenses/MIT	MIT License
68 lars 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
 
2414 lars 79
	/**
80
	 * Name of setTimeout() method in phpRedis
81
	 *
82
	 * Due to some deprecated methods in phpRedis, we need to call the
83
	 * specific methods depending on the version of phpRedis.
84
	 *
85
	 * @var string
86
	 */
87
	protected $_setTimeout_name;
88
 
89
	/**
90
	 * Name of delete() method in phpRedis
91
	 *
92
	 * Due to some deprecated methods in phpRedis, we need to call the
93
	 * specific methods depending on the version of phpRedis.
94
	 *
95
	 * @var string
96
	 */
97
	protected $_delete_name;
98
 
99
	/**
100
	 * Success return value of ping() method in phpRedis
101
	 *
102
	 * @var mixed
103
	 */
104
	protected $_ping_success;
105
 
68 lars 106
	// ------------------------------------------------------------------------
107
 
108
	/**
109
	 * Class constructor
110
	 *
111
	 * @param	array	$params	Configuration parameters
112
	 * @return	void
113
	 */
114
	public function __construct(&$params)
115
	{
116
		parent::__construct($params);
117
 
2414 lars 118
		// Detect the names of some methods in phpRedis instance
119
		if (version_compare(phpversion('redis'), '5', '>='))
120
		{
121
			$this->_setTimeout_name = 'expire';
122
			$this->_delete_name = 'del';
123
			$this->_ping_success = TRUE;
124
		}
125
		else
126
		{
127
			$this->_setTimeout_name = 'setTimeout';
128
			$this->_delete_name = 'delete';
129
			$this->_ping_success = '+PONG';
130
		}
131
 
68 lars 132
		if (empty($this->_config['save_path']))
133
		{
134
			log_message('error', 'Session: No Redis save path configured.');
135
		}
136
		elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_config['save_path'], $matches))
137
		{
138
			isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below
139
			$this->_config['save_path'] = array(
140
				'host' => $matches[1],
141
				'port' => empty($matches[2]) ? NULL : $matches[2],
142
				'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : NULL,
143
				'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : NULL,
144
				'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : NULL
145
			);
146
 
147
			preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->_key_prefix = $match[1];
148
		}
149
		else
150
		{
151
			log_message('error', 'Session: Invalid Redis save path format: '.$this->_config['save_path']);
152
		}
153
 
154
		if ($this->_config['match_ip'] === TRUE)
155
		{
156
			$this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':';
157
		}
158
	}
159
 
160
	// ------------------------------------------------------------------------
161
 
162
	/**
163
	 * Open
164
	 *
165
	 * Sanitizes save_path and initializes connection.
166
	 *
167
	 * @param	string	$save_path	Server path
168
	 * @param	string	$name		Session cookie name, unused
169
	 * @return	bool
170
	 */
171
	public function open($save_path, $name)
172
	{
173
		if (empty($this->_config['save_path']))
174
		{
2414 lars 175
			return $this->_failure;
68 lars 176
		}
177
 
178
		$redis = new Redis();
179
		if ( ! $redis->connect($this->_config['save_path']['host'], $this->_config['save_path']['port'], $this->_config['save_path']['timeout']))
180
		{
181
			log_message('error', 'Session: Unable to connect to Redis with the configured settings.');
182
		}
183
		elseif (isset($this->_config['save_path']['password']) && ! $redis->auth($this->_config['save_path']['password']))
184
		{
185
			log_message('error', 'Session: Unable to authenticate to Redis instance.');
186
		}
187
		elseif (isset($this->_config['save_path']['database']) && ! $redis->select($this->_config['save_path']['database']))
188
		{
189
			log_message('error', 'Session: Unable to select Redis database with index '.$this->_config['save_path']['database']);
190
		}
191
		else
192
		{
193
			$this->_redis = $redis;
2414 lars 194
			$this->php5_validate_id();
68 lars 195
			return $this->_success;
196
		}
197
 
2414 lars 198
		return $this->_failure;
68 lars 199
	}
200
 
201
	// ------------------------------------------------------------------------
202
 
203
	/**
204
	 * Read
205
	 *
206
	 * Reads session data and acquires a lock
207
	 *
208
	 * @param	string	$session_id	Session ID
209
	 * @return	string	Serialized session data
210
	 */
211
	public function read($session_id)
212
	{
213
		if (isset($this->_redis) && $this->_get_lock($session_id))
214
		{
215
			// Needed by write() to detect session_regenerate_id() calls
216
			$this->_session_id = $session_id;
217
 
218
			$session_data = $this->_redis->get($this->_key_prefix.$session_id);
219
 
220
			is_string($session_data)
221
				? $this->_key_exists = TRUE
222
				: $session_data = '';
223
 
224
			$this->_fingerprint = md5($session_data);
225
			return $session_data;
226
		}
227
 
2414 lars 228
		return $this->_failure;
68 lars 229
	}
230
 
231
	// ------------------------------------------------------------------------
232
 
233
	/**
234
	 * Write
235
	 *
236
	 * Writes (create / update) session data
237
	 *
238
	 * @param	string	$session_id	Session ID
239
	 * @param	string	$session_data	Serialized session data
240
	 * @return	bool
241
	 */
242
	public function write($session_id, $session_data)
243
	{
2049 lars 244
		if ( ! isset($this->_redis, $this->_lock_key))
68 lars 245
		{
2414 lars 246
			return $this->_failure;
68 lars 247
		}
248
		// Was the ID regenerated?
249
		elseif ($session_id !== $this->_session_id)
250
		{
251
			if ( ! $this->_release_lock() OR ! $this->_get_lock($session_id))
252
			{
2414 lars 253
				return $this->_failure;
68 lars 254
			}
255
 
256
			$this->_key_exists = FALSE;
257
			$this->_session_id = $session_id;
258
		}
259
 
2414 lars 260
		$this->_redis->{$this->_setTimeout_name}($this->_lock_key, 300);
2049 lars 261
		if ($this->_fingerprint !== ($fingerprint = md5($session_data)) OR $this->_key_exists === FALSE)
68 lars 262
		{
2049 lars 263
			if ($this->_redis->set($this->_key_prefix.$session_id, $session_data, $this->_config['expiration']))
68 lars 264
			{
2049 lars 265
				$this->_fingerprint = $fingerprint;
266
				$this->_key_exists = TRUE;
267
				return $this->_success;
68 lars 268
			}
269
 
2414 lars 270
			return $this->_failure;
68 lars 271
		}
272
 
2414 lars 273
		return ($this->_redis->{$this->_setTimeout_name}($this->_key_prefix.$session_id, $this->_config['expiration']))
2049 lars 274
			? $this->_success
2414 lars 275
			: $this->_failure;
68 lars 276
	}
277
 
278
	// ------------------------------------------------------------------------
279
 
280
	/**
281
	 * Close
282
	 *
283
	 * Releases locks and closes connection.
284
	 *
285
	 * @return	bool
286
	 */
287
	public function close()
288
	{
289
		if (isset($this->_redis))
290
		{
291
			try {
2414 lars 292
				if ($this->_redis->ping() === $this->_ping_success)
68 lars 293
				{
294
					$this->_release_lock();
295
					if ($this->_redis->close() === FALSE)
296
					{
2414 lars 297
						return $this->_failure;
68 lars 298
					}
299
				}
300
			}
301
			catch (RedisException $e)
302
			{
303
				log_message('error', 'Session: Got RedisException on close(): '.$e->getMessage());
304
			}
305
 
306
			$this->_redis = NULL;
307
			return $this->_success;
308
		}
309
 
310
		return $this->_success;
311
	}
312
 
313
	// ------------------------------------------------------------------------
314
 
315
	/**
316
	 * Destroy
317
	 *
318
	 * Destroys the current session.
319
	 *
320
	 * @param	string	$session_id	Session ID
321
	 * @return	bool
322
	 */
323
	public function destroy($session_id)
324
	{
325
		if (isset($this->_redis, $this->_lock_key))
326
		{
2414 lars 327
			if (($result = $this->_redis->{$this->_delete_name}($this->_key_prefix.$session_id)) !== 1)
68 lars 328
			{
2414 lars 329
				log_message('debug', 'Session: Redis::'.$this->_delete_name.'() expected to return 1, got '.var_export($result, TRUE).' instead.');
68 lars 330
			}
331
 
332
			$this->_cookie_destroy();
333
			return $this->_success;
334
		}
335
 
2414 lars 336
		return $this->_failure;
68 lars 337
	}
338
 
339
	// ------------------------------------------------------------------------
340
 
341
	/**
342
	 * Garbage Collector
343
	 *
344
	 * Deletes expired sessions
345
	 *
346
	 * @param	int 	$maxlifetime	Maximum lifetime of sessions
347
	 * @return	bool
348
	 */
349
	public function gc($maxlifetime)
350
	{
351
		// Not necessary, Redis takes care of that.
352
		return $this->_success;
353
	}
354
 
2414 lars 355
	// --------------------------------------------------------------------
356
 
357
	/**
358
	 * Validate ID
359
	 *
360
	 * Checks whether a session ID record exists server-side,
361
	 * to enforce session.use_strict_mode.
362
	 *
363
	 * @param	string	$id
364
	 * @return	bool
365
	 */
366
	public function validateSessionId($id)
367
	{
368
		return (bool) $this->_redis->exists($this->_key_prefix.$id);
369
	}
370
 
68 lars 371
	// ------------------------------------------------------------------------
372
 
373
	/**
374
	 * Get lock
375
	 *
376
	 * Acquires an (emulated) lock.
377
	 *
378
	 * @param	string	$session_id	Session ID
379
	 * @return	bool
380
	 */
381
	protected function _get_lock($session_id)
382
	{
383
		// PHP 7 reuses the SessionHandler object on regeneration,
384
		// so we need to check here if the lock key is for the
385
		// correct session ID.
386
		if ($this->_lock_key === $this->_key_prefix.$session_id.':lock')
387
		{
2414 lars 388
			return $this->_redis->{$this->_setTimeout_name}($this->_lock_key, 300);
68 lars 389
		}
390
 
391
		// 30 attempts to obtain a lock, in case another request already has it
392
		$lock_key = $this->_key_prefix.$session_id.':lock';
393
		$attempt = 0;
394
		do
395
		{
396
			if (($ttl = $this->_redis->ttl($lock_key)) > 0)
397
			{
398
				sleep(1);
399
				continue;
400
			}
401
 
2414 lars 402
			if ($ttl === -2 && ! $this->_redis->set($lock_key, time(), array('nx', 'ex' => 300)))
68 lars 403
			{
2414 lars 404
				// Sleep for 1s to wait for lock releases.
405
				sleep(1);
406
				continue;
407
			}
408
			elseif ( ! $this->_redis->setex($lock_key, 300, time()))
409
			{
68 lars 410
				log_message('error', 'Session: Error while trying to obtain lock for '.$this->_key_prefix.$session_id);
411
				return FALSE;
412
			}
413
 
414
			$this->_lock_key = $lock_key;
415
			break;
416
		}
417
		while (++$attempt < 30);
418
 
419
		if ($attempt === 30)
420
		{
421
			log_message('error', 'Session: Unable to obtain lock for '.$this->_key_prefix.$session_id.' after 30 attempts, aborting.');
422
			return FALSE;
423
		}
424
		elseif ($ttl === -1)
425
		{
426
			log_message('debug', 'Session: Lock for '.$this->_key_prefix.$session_id.' had no TTL, overriding.');
427
		}
428
 
429
		$this->_lock = TRUE;
430
		return TRUE;
431
	}
432
 
433
	// ------------------------------------------------------------------------
434
 
435
	/**
436
	 * Release lock
437
	 *
438
	 * Releases a previously acquired lock
439
	 *
440
	 * @return	bool
441
	 */
442
	protected function _release_lock()
443
	{
444
		if (isset($this->_redis, $this->_lock_key) && $this->_lock)
445
		{
2414 lars 446
			if ( ! $this->_redis->{$this->_delete_name}($this->_lock_key))
68 lars 447
			{
448
				log_message('error', 'Session: Error while trying to free lock for '.$this->_lock_key);
449
				return FALSE;
450
			}
451
 
452
			$this->_lock_key = NULL;
453
			$this->_lock = FALSE;
454
		}
455
 
456
		return TRUE;
457
	}
458
 
459
}