Subversion-Projekte lars-tiefland.ci

Revision

Revision 2107 | 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
 *
2242 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/)
2242 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 Files 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_files_driver extends CI_Session_driver implements SessionHandlerInterface {
50
 
51
	/**
52
	 * Save path
53
	 *
54
	 * @var	string
55
	 */
56
	protected $_save_path;
57
 
58
	/**
59
	 * File handle
60
	 *
61
	 * @var	resource
62
	 */
63
	protected $_file_handle;
64
 
65
	/**
66
	 * File name
67
	 *
68
	 * @var	resource
69
	 */
70
	protected $_file_path;
71
 
72
	/**
73
	 * File new flag
74
	 *
75
	 * @var	bool
76
	 */
77
	protected $_file_new;
78
 
1257 lars 79
	/**
80
	 * Validate SID regular expression
81
	 *
82
	 * @var	string
83
	 */
84
	protected $_sid_regexp;
85
 
86
	/**
2107 lars 87
	 * mbstring.func_overload flag
1257 lars 88
	 *
89
	 * @var	bool
90
	 */
2107 lars 91
	protected static $func_overload;
1257 lars 92
 
68 lars 93
	// ------------------------------------------------------------------------
94
 
95
	/**
96
	 * Class constructor
97
	 *
98
	 * @param	array	$params	Configuration parameters
99
	 * @return	void
100
	 */
101
	public function __construct(&$params)
102
	{
103
		parent::__construct($params);
104
 
105
		if (isset($this->_config['save_path']))
106
		{
107
			$this->_config['save_path'] = rtrim($this->_config['save_path'], '/\\');
108
			ini_set('session.save_path', $this->_config['save_path']);
109
		}
110
		else
111
		{
112
			log_message('debug', 'Session: "sess_save_path" is empty; using "session.save_path" value from php.ini.');
113
			$this->_config['save_path'] = rtrim(ini_get('session.save_path'), '/\\');
114
		}
1257 lars 115
 
116
		$this->_sid_regexp = $this->_config['_sid_regexp'];
117
 
2107 lars 118
		isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload'));
68 lars 119
	}
120
 
121
	// ------------------------------------------------------------------------
122
 
123
	/**
124
	 * Open
125
	 *
126
	 * Sanitizes the save_path directory.
127
	 *
128
	 * @param	string	$save_path	Path to session files' directory
129
	 * @param	string	$name		Session cookie name
130
	 * @return	bool
131
	 */
132
	public function open($save_path, $name)
133
	{
134
		if ( ! is_dir($save_path))
135
		{
136
			if ( ! mkdir($save_path, 0700, TRUE))
137
			{
138
				throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not a directory, doesn't exist or cannot be created.");
139
			}
140
		}
141
		elseif ( ! is_writable($save_path))
142
		{
143
			throw new Exception("Session: Configured save path '".$this->_config['save_path']."' is not writable by the PHP process.");
144
		}
145
 
146
		$this->_config['save_path'] = $save_path;
147
		$this->_file_path = $this->_config['save_path'].DIRECTORY_SEPARATOR
148
			.$name // we'll use the session cookie name as a prefix to avoid collisions
149
			.($this->_config['match_ip'] ? md5($_SERVER['REMOTE_ADDR']) : '');
150
 
2242 lars 151
		$this->php5_validate_id();
152
 
68 lars 153
		return $this->_success;
154
	}
155
 
156
	// ------------------------------------------------------------------------
157
 
158
	/**
159
	 * Read
160
	 *
161
	 * Reads session data and acquires a lock
162
	 *
163
	 * @param	string	$session_id	Session ID
164
	 * @return	string	Serialized session data
165
	 */
166
	public function read($session_id)
167
	{
168
		// This might seem weird, but PHP 5.6 introduces session_reset(),
169
		// which re-reads session data
170
		if ($this->_file_handle === NULL)
171
		{
1257 lars 172
			$this->_file_new = ! file_exists($this->_file_path.$session_id);
173
 
174
			if (($this->_file_handle = fopen($this->_file_path.$session_id, 'c+b')) === FALSE)
68 lars 175
			{
176
				log_message('error', "Session: Unable to open file '".$this->_file_path.$session_id."'.");
177
				return $this->_failure;
178
			}
179
 
180
			if (flock($this->_file_handle, LOCK_EX) === FALSE)
181
			{
182
				log_message('error', "Session: Unable to obtain lock for file '".$this->_file_path.$session_id."'.");
183
				fclose($this->_file_handle);
184
				$this->_file_handle = NULL;
185
				return $this->_failure;
186
			}
187
 
188
			// Needed by write() to detect session_regenerate_id() calls
189
			$this->_session_id = $session_id;
190
 
191
			if ($this->_file_new)
192
			{
193
				chmod($this->_file_path.$session_id, 0600);
194
				$this->_fingerprint = md5('');
195
				return '';
196
			}
197
		}
198
		// We shouldn't need this, but apparently we do ...
199
		// See https://github.com/bcit-ci/CodeIgniter/issues/4039
200
		elseif ($this->_file_handle === FALSE)
201
		{
202
			return $this->_failure;
203
		}
204
		else
205
		{
206
			rewind($this->_file_handle);
207
		}
208
 
209
		$session_data = '';
1257 lars 210
		for ($read = 0, $length = filesize($this->_file_path.$session_id); $read < $length; $read += self::strlen($buffer))
68 lars 211
		{
212
			if (($buffer = fread($this->_file_handle, $length - $read)) === FALSE)
213
			{
214
				break;
215
			}
216
 
217
			$session_data .= $buffer;
218
		}
219
 
220
		$this->_fingerprint = md5($session_data);
221
		return $session_data;
222
	}
223
 
224
	// ------------------------------------------------------------------------
225
 
226
	/**
227
	 * Write
228
	 *
229
	 * Writes (create / update) session data
230
	 *
231
	 * @param	string	$session_id	Session ID
232
	 * @param	string	$session_data	Serialized session data
233
	 * @return	bool
234
	 */
235
	public function write($session_id, $session_data)
236
	{
237
		// If the two IDs don't match, we have a session_regenerate_id() call
238
		// and we need to close the old handle and open a new one
239
		if ($session_id !== $this->_session_id && ($this->close() === $this->_failure OR $this->read($session_id) === $this->_failure))
240
		{
241
			return $this->_failure;
242
		}
243
 
244
		if ( ! is_resource($this->_file_handle))
245
		{
246
			return $this->_failure;
247
		}
248
		elseif ($this->_fingerprint === md5($session_data))
249
		{
250
			return ( ! $this->_file_new && ! touch($this->_file_path.$session_id))
251
				? $this->_failure
252
				: $this->_success;
253
		}
254
 
255
		if ( ! $this->_file_new)
256
		{
257
			ftruncate($this->_file_handle, 0);
258
			rewind($this->_file_handle);
259
		}
260
 
261
		if (($length = strlen($session_data)) > 0)
262
		{
263
			for ($written = 0; $written < $length; $written += $result)
264
			{
265
				if (($result = fwrite($this->_file_handle, substr($session_data, $written))) === FALSE)
266
				{
267
					break;
268
				}
269
			}
270
 
271
			if ( ! is_int($result))
272
			{
273
				$this->_fingerprint = md5(substr($session_data, 0, $written));
274
				log_message('error', 'Session: Unable to write data.');
275
				return $this->_failure;
276
			}
277
		}
278
 
279
		$this->_fingerprint = md5($session_data);
280
		return $this->_success;
281
	}
282
 
283
	// ------------------------------------------------------------------------
284
 
285
	/**
286
	 * Close
287
	 *
288
	 * Releases locks and closes file descriptor.
289
	 *
290
	 * @return	bool
291
	 */
292
	public function close()
293
	{
294
		if (is_resource($this->_file_handle))
295
		{
296
			flock($this->_file_handle, LOCK_UN);
297
			fclose($this->_file_handle);
298
 
299
			$this->_file_handle = $this->_file_new = $this->_session_id = NULL;
300
		}
301
 
302
		return $this->_success;
303
	}
304
 
305
	// ------------------------------------------------------------------------
306
 
307
	/**
308
	 * Destroy
309
	 *
310
	 * Destroys the current session.
311
	 *
312
	 * @param	string	$session_id	Session ID
313
	 * @return	bool
314
	 */
315
	public function destroy($session_id)
316
	{
317
		if ($this->close() === $this->_success)
318
		{
319
			if (file_exists($this->_file_path.$session_id))
320
			{
321
				$this->_cookie_destroy();
322
				return unlink($this->_file_path.$session_id)
323
					? $this->_success
324
					: $this->_failure;
325
			}
326
 
327
			return $this->_success;
328
		}
329
		elseif ($this->_file_path !== NULL)
330
		{
331
			clearstatcache();
332
			if (file_exists($this->_file_path.$session_id))
333
			{
334
				$this->_cookie_destroy();
335
				return unlink($this->_file_path.$session_id)
336
					? $this->_success
337
					: $this->_failure;
338
			}
339
 
340
			return $this->_success;
341
		}
342
 
343
		return $this->_failure;
344
	}
345
 
346
	// ------------------------------------------------------------------------
347
 
348
	/**
349
	 * Garbage Collector
350
	 *
351
	 * Deletes expired sessions
352
	 *
353
	 * @param	int 	$maxlifetime	Maximum lifetime of sessions
354
	 * @return	bool
355
	 */
356
	public function gc($maxlifetime)
357
	{
358
		if ( ! is_dir($this->_config['save_path']) OR ($directory = opendir($this->_config['save_path'])) === FALSE)
359
		{
360
			log_message('debug', "Session: Garbage collector couldn't list files under directory '".$this->_config['save_path']."'.");
361
			return $this->_failure;
362
		}
363
 
364
		$ts = time() - $maxlifetime;
365
 
1257 lars 366
		$pattern = ($this->_config['match_ip'] === TRUE)
367
			? '[0-9a-f]{32}'
368
			: '';
369
 
68 lars 370
		$pattern = sprintf(
1257 lars 371
			'#\A%s'.$pattern.$this->_sid_regexp.'\z#',
372
			preg_quote($this->_config['cookie_name'])
68 lars 373
		);
374
 
375
		while (($file = readdir($directory)) !== FALSE)
376
		{
377
			// If the filename doesn't match this pattern, it's either not a session file or is not ours
378
			if ( ! preg_match($pattern, $file)
379
				OR ! is_file($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)
380
				OR ($mtime = filemtime($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)) === FALSE
381
				OR $mtime > $ts)
382
			{
383
				continue;
384
			}
385
 
386
			unlink($this->_config['save_path'].DIRECTORY_SEPARATOR.$file);
387
		}
388
 
389
		closedir($directory);
390
 
391
		return $this->_success;
392
	}
393
 
1257 lars 394
	// --------------------------------------------------------------------
395
 
396
	/**
2242 lars 397
	 * Validate ID
398
	 *
399
	 * Checks whether a session ID record exists server-side,
400
	 * to enforce session.use_strict_mode.
401
	 *
402
	 * @param	string	$id
403
	 * @return	bool
404
	 */
405
	public function validateId($id)
406
	{
407
		return is_file($this->_file_path.$id);
408
	}
409
 
410
	// --------------------------------------------------------------------
411
 
412
	/**
1257 lars 413
	 * Byte-safe strlen()
414
	 *
415
	 * @param	string	$str
416
	 * @return	int
417
	 */
418
	protected static function strlen($str)
419
	{
2107 lars 420
		return (self::$func_overload)
1257 lars 421
			? mb_strlen($str, '8bit')
422
			: strlen($str);
423
	}
424
}