-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathFileHandler.php
333 lines (270 loc) · 9 KB
/
FileHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\I18n\Time;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\Session as SessionConfig;
use ReturnTypeWillChange;
/**
* Session handler using file system for storage
*/
class FileHandler extends BaseHandler
{
/**
* Where to save the session files to.
*
* @var string
*/
protected $savePath;
/**
* The file handle
*
* @var resource|null
*/
protected $fileHandle;
/**
* File Name
*
* @var string
*/
protected $filePath;
/**
* Whether this is a new file.
*
* @var bool
*/
protected $fileNew;
/**
* Whether IP addresses should be matched.
*
* @var bool
*/
protected $matchIP = false;
/**
* Regex of session ID
*
* @var string
*/
protected $sessionIDRegex = '';
public function __construct(SessionConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
if (! empty($this->savePath)) {
$this->savePath = rtrim($this->savePath, '/\\');
ini_set('session.save_path', $this->savePath);
} else {
$sessionPath = rtrim(ini_get('session.save_path'), '/\\');
if ($sessionPath === '') {
$sessionPath = WRITEPATH . 'session';
}
$this->savePath = $sessionPath;
}
$this->configureSessionIDRegex();
}
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*
* @throws SessionException
*/
public function open($path, $name): bool
{
if (! is_dir($path) && ! mkdir($path, 0700, true)) {
throw SessionException::forInvalidSavePath($this->savePath);
}
if (! is_writable($path)) {
throw SessionException::forWriteProtectedSavePath($this->savePath);
}
$this->savePath = $path;
// we'll use the session name as prefix to avoid collisions
$this->filePath = $this->savePath . '/' . $name . ($this->matchIP ? md5($this->ipAddress) : '');
return true;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
// This might seem weird, but PHP 5.6 introduced session_reset(),
// which re-reads session data
if ($this->fileHandle === null) {
$this->fileNew = ! is_file($this->filePath . $id);
if (($this->fileHandle = fopen($this->filePath . $id, 'c+b')) === false) {
$this->logger->error("Session: Unable to open file '" . $this->filePath . $id . "'.");
return false;
}
if (flock($this->fileHandle, LOCK_EX) === false) {
$this->logger->error("Session: Unable to obtain lock for file '" . $this->filePath . $id . "'.");
fclose($this->fileHandle);
$this->fileHandle = null;
return false;
}
if (! isset($this->sessionID)) {
$this->sessionID = $id;
}
if ($this->fileNew) {
chmod($this->filePath . $id, 0600);
$this->fingerprint = md5('');
return '';
}
} else {
rewind($this->fileHandle);
}
$data = '';
$buffer = 0;
clearstatcache(); // Address https://github.com/codeigniter4/CodeIgniter4/issues/2056
for ($read = 0, $length = filesize($this->filePath . $id); $read < $length; $read += strlen($buffer)) {
if (($buffer = fread($this->fileHandle, $length - $read)) === false) {
break;
}
$data .= $buffer;
}
$this->fingerprint = md5($data);
return $data;
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
// If the two IDs don't match, we have a session_regenerate_id() call
if ($id !== $this->sessionID) {
$this->sessionID = $id;
}
if (! is_resource($this->fileHandle)) {
return false;
}
if ($this->fingerprint === md5($data)) {
return ($this->fileNew) ? true : touch($this->filePath . $id);
}
if (! $this->fileNew) {
ftruncate($this->fileHandle, 0);
rewind($this->fileHandle);
}
if (($length = strlen($data)) > 0) {
$result = null;
for ($written = 0; $written < $length; $written += $result) {
if (($result = fwrite($this->fileHandle, substr($data, $written))) === false) {
break;
}
}
if (! is_int($result)) {
$this->fingerprint = md5(substr($data, 0, $written));
$this->logger->error('Session: Unable to write data.');
return false;
}
}
$this->fingerprint = md5($data);
return true;
}
/**
* Closes the current session.
*/
public function close(): bool
{
if (is_resource($this->fileHandle)) {
flock($this->fileHandle, LOCK_UN);
fclose($this->fileHandle);
$this->fileHandle = null;
$this->fileNew = false;
}
return true;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
if ($this->close()) {
return is_file($this->filePath . $id)
? (unlink($this->filePath . $id) && $this->destroyCookie())
: true;
}
if ($this->filePath !== null) {
clearstatcache();
return is_file($this->filePath . $id)
? (unlink($this->filePath . $id) && $this->destroyCookie())
: true;
}
return false;
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
if (! is_dir($this->savePath) || ($directory = opendir($this->savePath)) === false) {
$this->logger->debug("Session: Garbage collector couldn't list files under directory '" . $this->savePath . "'.");
return false;
}
$ts = Time::now()->getTimestamp() - $max_lifetime;
$pattern = $this->matchIP === true ? '[0-9a-f]{32}' : '';
$pattern = sprintf(
'#\A%s' . $pattern . $this->sessionIDRegex . '\z#',
preg_quote($this->cookieName, '#'),
);
$collected = 0;
while (($file = readdir($directory)) !== false) {
// If the filename doesn't match this pattern, it's either not a session file or is not ours
if (preg_match($pattern, $file) !== 1
|| ! is_file($this->savePath . DIRECTORY_SEPARATOR . $file)
|| ($mtime = filemtime($this->savePath . DIRECTORY_SEPARATOR . $file)) === false
|| $mtime > $ts
) {
continue;
}
unlink($this->savePath . DIRECTORY_SEPARATOR . $file);
$collected++;
}
closedir($directory);
return $collected;
}
/**
* Configure Session ID regular expression
*
* To make life easier, we force the PHP defaults. Because PHP9 forces them.
* See https://wiki.php.net/rfc/deprecations_php_8_4#sessionsid_length_and_sessionsid_bits_per_character
*/
protected function configureSessionIDRegex()
{
$bitsPerCharacter = (int) ini_get('session.sid_bits_per_character');
$sidLength = (int) ini_get('session.sid_length');
// We force the PHP defaults.
if (PHP_VERSION_ID < 90000) {
if ($bitsPerCharacter !== 4) {
ini_set('session.sid_bits_per_character', '4');
}
if ($sidLength !== 32) {
ini_set('session.sid_length', '32');
}
}
$this->sessionIDRegex = '[0-9a-f]{32}';
}
}