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 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
			{
2414 lars 138
				log_message('error', "Session: Configured save path '".$this->_config['save_path']."' is not a directory, doesn't exist or cannot be created.");
139
				return $this->_failure;
68 lars 140
			}
141
		}
142
		elseif ( ! is_writable($save_path))
143
		{
2414 lars 144
			log_message('error', "Session: Configured save path '".$this->_config['save_path']."' is not writable by the PHP process.");
145
			return $this->_failure;
68 lars 146
		}
147
 
148
		$this->_config['save_path'] = $save_path;
149
		$this->_file_path = $this->_config['save_path'].DIRECTORY_SEPARATOR
150
			.$name // we'll use the session cookie name as a prefix to avoid collisions
151
			.($this->_config['match_ip'] ? md5($_SERVER['REMOTE_ADDR']) : '');
152
 
2414 lars 153
		$this->php5_validate_id();
154
 
68 lars 155
		return $this->_success;
156
	}
157
 
158
	// ------------------------------------------------------------------------
159
 
160
	/**
161
	 * Read
162
	 *
163
	 * Reads session data and acquires a lock
164
	 *
165
	 * @param	string	$session_id	Session ID
166
	 * @return	string	Serialized session data
167
	 */
168
	public function read($session_id)
169
	{
170
		// This might seem weird, but PHP 5.6 introduces session_reset(),
171
		// which re-reads session data
172
		if ($this->_file_handle === NULL)
173
		{
1257 lars 174
			$this->_file_new = ! file_exists($this->_file_path.$session_id);
175
 
176
			if (($this->_file_handle = fopen($this->_file_path.$session_id, 'c+b')) === FALSE)
68 lars 177
			{
178
				log_message('error', "Session: Unable to open file '".$this->_file_path.$session_id."'.");
179
				return $this->_failure;
180
			}
181
 
182
			if (flock($this->_file_handle, LOCK_EX) === FALSE)
183
			{
184
				log_message('error', "Session: Unable to obtain lock for file '".$this->_file_path.$session_id."'.");
185
				fclose($this->_file_handle);
186
				$this->_file_handle = NULL;
187
				return $this->_failure;
188
			}
189
 
190
			// Needed by write() to detect session_regenerate_id() calls
191
			$this->_session_id = $session_id;
192
 
193
			if ($this->_file_new)
194
			{
195
				chmod($this->_file_path.$session_id, 0600);
196
				$this->_fingerprint = md5('');
197
				return '';
198
			}
199
		}
200
		// We shouldn't need this, but apparently we do ...
201
		// See https://github.com/bcit-ci/CodeIgniter/issues/4039
202
		elseif ($this->_file_handle === FALSE)
203
		{
204
			return $this->_failure;
205
		}
206
		else
207
		{
208
			rewind($this->_file_handle);
209
		}
210
 
211
		$session_data = '';
1257 lars 212
		for ($read = 0, $length = filesize($this->_file_path.$session_id); $read < $length; $read += self::strlen($buffer))
68 lars 213
		{
214
			if (($buffer = fread($this->_file_handle, $length - $read)) === FALSE)
215
			{
216
				break;
217
			}
218
 
219
			$session_data .= $buffer;
220
		}
221
 
222
		$this->_fingerprint = md5($session_data);
223
		return $session_data;
224
	}
225
 
226
	// ------------------------------------------------------------------------
227
 
228
	/**
229
	 * Write
230
	 *
231
	 * Writes (create / update) session data
232
	 *
233
	 * @param	string	$session_id	Session ID
234
	 * @param	string	$session_data	Serialized session data
235
	 * @return	bool
236
	 */
237
	public function write($session_id, $session_data)
238
	{
239
		// If the two IDs don't match, we have a session_regenerate_id() call
240
		// and we need to close the old handle and open a new one
241
		if ($session_id !== $this->_session_id && ($this->close() === $this->_failure OR $this->read($session_id) === $this->_failure))
242
		{
243
			return $this->_failure;
244
		}
245
 
246
		if ( ! is_resource($this->_file_handle))
247
		{
248
			return $this->_failure;
249
		}
250
		elseif ($this->_fingerprint === md5($session_data))
251
		{
252
			return ( ! $this->_file_new && ! touch($this->_file_path.$session_id))
253
				? $this->_failure
254
				: $this->_success;
255
		}
256
 
257
		if ( ! $this->_file_new)
258
		{
259
			ftruncate($this->_file_handle, 0);
260
			rewind($this->_file_handle);
261
		}
262
 
263
		if (($length = strlen($session_data)) > 0)
264
		{
265
			for ($written = 0; $written < $length; $written += $result)
266
			{
267
				if (($result = fwrite($this->_file_handle, substr($session_data, $written))) === FALSE)
268
				{
269
					break;
270
				}
271
			}
272
 
273
			if ( ! is_int($result))
274
			{
275
				$this->_fingerprint = md5(substr($session_data, 0, $written));
276
				log_message('error', 'Session: Unable to write data.');
277
				return $this->_failure;
278
			}
279
		}
280
 
281
		$this->_fingerprint = md5($session_data);
282
		return $this->_success;
283
	}
284
 
285
	// ------------------------------------------------------------------------
286
 
287
	/**
288
	 * Close
289
	 *
290
	 * Releases locks and closes file descriptor.
291
	 *
292
	 * @return	bool
293
	 */
294
	public function close()
295
	{
296
		if (is_resource($this->_file_handle))
297
		{
298
			flock($this->_file_handle, LOCK_UN);
299
			fclose($this->_file_handle);
300
 
301
			$this->_file_handle = $this->_file_new = $this->_session_id = NULL;
302
		}
303
 
304
		return $this->_success;
305
	}
306
 
307
	// ------------------------------------------------------------------------
308
 
309
	/**
310
	 * Destroy
311
	 *
312
	 * Destroys the current session.
313
	 *
314
	 * @param	string	$session_id	Session ID
315
	 * @return	bool
316
	 */
317
	public function destroy($session_id)
318
	{
319
		if ($this->close() === $this->_success)
320
		{
321
			if (file_exists($this->_file_path.$session_id))
322
			{
323
				$this->_cookie_destroy();
324
				return unlink($this->_file_path.$session_id)
325
					? $this->_success
326
					: $this->_failure;
327
			}
328
 
329
			return $this->_success;
330
		}
331
		elseif ($this->_file_path !== NULL)
332
		{
333
			clearstatcache();
334
			if (file_exists($this->_file_path.$session_id))
335
			{
336
				$this->_cookie_destroy();
337
				return unlink($this->_file_path.$session_id)
338
					? $this->_success
339
					: $this->_failure;
340
			}
341
 
342
			return $this->_success;
343
		}
344
 
345
		return $this->_failure;
346
	}
347
 
348
	// ------------------------------------------------------------------------
349
 
350
	/**
351
	 * Garbage Collector
352
	 *
353
	 * Deletes expired sessions
354
	 *
355
	 * @param	int 	$maxlifetime	Maximum lifetime of sessions
356
	 * @return	bool
357
	 */
358
	public function gc($maxlifetime)
359
	{
360
		if ( ! is_dir($this->_config['save_path']) OR ($directory = opendir($this->_config['save_path'])) === FALSE)
361
		{
362
			log_message('debug', "Session: Garbage collector couldn't list files under directory '".$this->_config['save_path']."'.");
363
			return $this->_failure;
364
		}
365
 
366
		$ts = time() - $maxlifetime;
367
 
1257 lars 368
		$pattern = ($this->_config['match_ip'] === TRUE)
369
			? '[0-9a-f]{32}'
370
			: '';
371
 
68 lars 372
		$pattern = sprintf(
1257 lars 373
			'#\A%s'.$pattern.$this->_sid_regexp.'\z#',
374
			preg_quote($this->_config['cookie_name'])
68 lars 375
		);
376
 
377
		while (($file = readdir($directory)) !== FALSE)
378
		{
379
			// If the filename doesn't match this pattern, it's either not a session file or is not ours
380
			if ( ! preg_match($pattern, $file)
381
				OR ! is_file($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)
382
				OR ($mtime = filemtime($this->_config['save_path'].DIRECTORY_SEPARATOR.$file)) === FALSE
383
				OR $mtime > $ts)
384
			{
385
				continue;
386
			}
387
 
388
			unlink($this->_config['save_path'].DIRECTORY_SEPARATOR.$file);
389
		}
390
 
391
		closedir($directory);
392
 
393
		return $this->_success;
394
	}
395
 
1257 lars 396
	// --------------------------------------------------------------------
397
 
398
	/**
2414 lars 399
	 * Validate ID
400
	 *
401
	 * Checks whether a session ID record exists server-side,
402
	 * to enforce session.use_strict_mode.
403
	 *
404
	 * @param	string	$id
405
	 * @return	bool
406
	 */
407
	public function validateSessionId($id)
408
	{
409
		$result = is_file($this->_file_path.$id);
410
		clearstatcache(TRUE, $this->_file_path.$id);
411
		return $result;
412
	}
413
 
414
	// --------------------------------------------------------------------
415
 
416
	/**
1257 lars 417
	 * Byte-safe strlen()
418
	 *
419
	 * @param	string	$str
420
	 * @return	int
421
	 */
422
	protected static function strlen($str)
423
	{
2107 lars 424
		return (self::$func_overload)
1257 lars 425
			? mb_strlen($str, '8bit')
426
			: strlen($str);
427
	}
428
}