xref: /php-src/ext/session/mod_files.c (revision 42443b4c)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Author: Sascha Schumann <sascha@schumann.cx>                         |
14    +----------------------------------------------------------------------+
15  */
16 
17 /**************************************************************************
18  * Files save handler should be used as reference implementations of session
19  * save handlers. PS_* functions are called as follows with standard usage.
20  *
21  *    PS_OPEN_FUNC()  - Create module data that manages save handler.
22  *    PS_CREATE_SID() and/or PS_VALIDATE_SID()
23  *                    - PS_CREATE_ID() is called if session ID(key) is not
24  *                      provided or invalid. PS_VALIDATE_SID() is called to
25  *                      verify session ID already exists or not to mitigate
26  *                      session adoption vulnerability risk.
27  *    PS_READ_FUNC()  - Read data from storage.
28  *    PS_GC_FUNC()    - Perform GC. Called by probability
29  *                                (session.gc_probability/session.gc_divisor).
30  *    PS_WRITE_FUNC() or PS_UPDATE_TIMESTAMP()
31  *                    - Write session data or update session data timestamp.
32  *                      It depends on session data change.
33  *    PS_CLOSE_FUNC() - Clean up module data created by PS_OPEN_FUNC().
34  *
35  * Session module guarantees PS_OPEN_FUNC() is called before calling other
36  * PS_*_FUNC() functions. Other than this, session module may call any
37  * PS_*_FUNC() at any time. You may assume non null *mod_data created by
38  * PS_OPEN_FUNC() is passed to PS_*_FUNC().
39  *
40  * NOTE:
41  *  - Save handlers _MUST_NOT_ change/refer PS() values.
42  *    i.e. PS(id), PS(session_status), PS(mod) and any other PS() values.
43  *    Use only function parameters passed from session module.
44  *  - Save handler _MUST_ use PS_GET_MOD_DATA()/PS_SET_MOD_DATA() macro to
45  *    set/get save handler module data(mod_data). mod_data contains
46  *    data required by PS modules. It will not be NULL except PS_OPEN_FUNC().
47  *  - Refer to PS_* macros in php_session.h for function/parameter definitions.
48  *  - Returning FAILURE state from PS_* function results in raising errors.
49  *    Avoid failure state as much as possible.
50  *  - Use static ps_[module name]_[function name] functions for internal use.
51  *************************************************************************/
52 
53 #include "php.h"
54 
55 #include <sys/stat.h>
56 #include <sys/types.h>
57 
58 #ifdef HAVE_SYS_FILE_H
59 #include <sys/file.h>
60 #endif
61 
62 #ifdef HAVE_DIRENT_H
63 #include <dirent.h>
64 #endif
65 
66 #ifdef PHP_WIN32
67 #include "win32/readdir.h"
68 #endif
69 #include <time.h>
70 
71 #include <fcntl.h>
72 #include <errno.h>
73 
74 #ifdef HAVE_UNISTD_H
75 #include <unistd.h>
76 #endif
77 
78 #include "php_session.h"
79 #include "mod_files.h"
80 #include "ext/standard/flock_compat.h"
81 #include "php_open_temporary_file.h"
82 
83 #define FILE_PREFIX "sess_"
84 
85 #ifdef PHP_WIN32
86 # ifndef O_NOFOLLOW
87 #  define O_NOFOLLOW 0
88 # endif
89 #define SESS_FILE_BUF_SIZE(sz) ((unsigned int)(sz > INT_MAX ? INT_MAX : (unsigned int)sz))
90 #endif
91 
92 typedef struct {
93 	zend_string *last_key;
94 	zend_string *basedir;
95 	size_t dirdepth;
96 	size_t st_size;
97 	int filemode;
98 	int fd;
99 } ps_files;
100 
101 const ps_module ps_mod_files = {
102 	/* New save handlers MUST use PS_MOD_UPDATE_TIMESTAMP macro */
103 	PS_MOD_UPDATE_TIMESTAMP(files)
104 };
105 
106 
ps_files_path_create(char * buf,size_t buflen,ps_files * data,const zend_string * key)107 static char *ps_files_path_create(char *buf, size_t buflen, ps_files *data, const zend_string *key)
108 {
109 	const char *p;
110 	int i;
111 	size_t n;
112 
113 	if (!data || ZSTR_LEN(key) <= data->dirdepth ||
114 		buflen < (ZSTR_LEN(data->basedir) + 2 * data->dirdepth + ZSTR_LEN(key) + 5 + sizeof(FILE_PREFIX))) {
115 		return NULL;
116 	}
117 
118 	p = ZSTR_VAL(key);
119 	memcpy(buf, ZSTR_VAL(data->basedir), ZSTR_LEN(data->basedir));
120 	n = ZSTR_LEN(data->basedir);
121 	buf[n++] = PHP_DIR_SEPARATOR;
122 	for (i = 0; i < (int)data->dirdepth; i++) {
123 		buf[n++] = *p++;
124 		buf[n++] = PHP_DIR_SEPARATOR;
125 	}
126 	memcpy(buf + n, FILE_PREFIX, sizeof(FILE_PREFIX) - 1);
127 	n += sizeof(FILE_PREFIX) - 1;
128 	memcpy(buf + n, ZSTR_VAL(key), ZSTR_LEN(key));
129 	n += ZSTR_LEN(key);
130 	buf[n] = '\0';
131 
132 	return buf;
133 }
134 
135 #ifndef O_BINARY
136 # define O_BINARY 0
137 #endif
138 
ps_files_close(ps_files * data)139 static void ps_files_close(ps_files *data)
140 {
141 	if (data->fd != -1) {
142 #ifdef PHP_WIN32
143 		/* On Win32 locked files that are closed without being explicitly unlocked
144 		   will be unlocked only when "system resources become available". */
145 		flock(data->fd, LOCK_UN);
146 #endif
147 		close(data->fd);
148 		data->fd = -1;
149 	}
150 }
151 
ps_files_open(ps_files * data,zend_string * key)152 static void ps_files_open(ps_files *data, /* const */ zend_string *key)
153 {
154 	char buf[MAXPATHLEN];
155 #if !defined(O_NOFOLLOW) || !defined(PHP_WIN32)
156     struct stat sbuf = {0};
157 #endif
158 	int ret;
159 
160 	if (data->fd < 0 || !data->last_key || !zend_string_equals(key, data->last_key)) {
161 		if (data->last_key) {
162 			zend_string_release_ex(data->last_key, /* persistent */ false);
163 			data->last_key = NULL;
164 		}
165 
166 		ps_files_close(data);
167 
168 		if (php_session_valid_key(ZSTR_VAL(key)) == FAILURE) {
169 			php_error_docref(NULL, E_WARNING, "Session ID is too long or contains illegal characters. Only the A-Z, a-z, 0-9, \"-\", and \",\" characters are allowed");
170 			return;
171 		}
172 
173 		if (!ps_files_path_create(buf, sizeof(buf), data, key)) {
174 			php_error_docref(NULL, E_WARNING, "Failed to create session data file path. Too short session ID, invalid save_path or path length exceeds %d characters", MAXPATHLEN);
175 			return;
176 		}
177 
178 		data->last_key = zend_string_copy(key);
179 
180 		/* O_NOFOLLOW to prevent us from following evil symlinks */
181 #ifdef O_NOFOLLOW
182 		data->fd = VCWD_OPEN_MODE(buf, O_CREAT | O_RDWR | O_BINARY | O_NOFOLLOW, data->filemode);
183 #else
184 		/* Check to make sure that the opened file is not outside of allowable dirs.
185 		   This is not 100% safe but it's hard to do something better without O_NOFOLLOW */
186 		if(PG(open_basedir) && lstat(buf, &sbuf) == 0 && S_ISLNK(sbuf.st_mode) && php_check_open_basedir(buf)) {
187 			return;
188 		}
189 		data->fd = VCWD_OPEN_MODE(buf, O_CREAT | O_RDWR | O_BINARY, data->filemode);
190 #endif
191 
192 		if (data->fd != -1) {
193 #ifndef PHP_WIN32
194 			/* check that this session file was created by us or root – we
195 			   don't want to end up accepting the sessions of another webapp
196 
197 			   If the process is ran by root, we ignore session file ownership
198 			   Use case: session is initiated by Apache under non-root and then
199 			   accessed by backend with root permissions to execute some system tasks.
200 
201 			   */
202 			if (zend_fstat(data->fd, &sbuf) || (sbuf.st_uid != 0 && sbuf.st_uid != getuid() && sbuf.st_uid != geteuid() && getuid() != 0)) {
203 				close(data->fd);
204 				data->fd = -1;
205 				php_error_docref(NULL, E_WARNING, "Session data file is not created by your uid");
206 				return;
207 			}
208 #endif
209 			do {
210 				ret = flock(data->fd, LOCK_EX);
211 			} while (ret == -1 && errno == EINTR);
212 
213 #ifdef F_SETFD
214 # ifndef FD_CLOEXEC
215 #  define FD_CLOEXEC 1
216 # endif
217 			if (fcntl(data->fd, F_SETFD, FD_CLOEXEC)) {
218 				php_error_docref(NULL, E_WARNING, "fcntl(%d, F_SETFD, FD_CLOEXEC) failed: %s (%d)", data->fd, strerror(errno), errno);
219 			}
220 #endif
221 		} else {
222 			php_error_docref(NULL, E_WARNING, "open(%s, O_RDWR) failed: %s (%d)", buf, strerror(errno), errno);
223 		}
224 	}
225 }
226 
ps_files_write(ps_files * data,zend_string * key,zend_string * val)227 static zend_result ps_files_write(ps_files *data, zend_string *key, zend_string *val)
228 {
229 	size_t n = 0;
230 
231 	/* PS(id) may be changed by calling session_regenerate_id().
232 	   Re-initialization should be tried here. ps_files_open() checks
233        data->last_key and reopen when it is needed. */
234 	ps_files_open(data, key);
235 	if (data->fd < 0) {
236 		return FAILURE;
237 	}
238 
239 	/* Truncate file if the amount of new data is smaller than the existing data set. */
240 	if (ZSTR_LEN(val) < data->st_size) {
241 		php_ignore_value(ftruncate(data->fd, 0));
242 	}
243 
244 #ifdef HAVE_PWRITE
245 	n = pwrite(data->fd, ZSTR_VAL(val), ZSTR_LEN(val), 0);
246 #else
247 	lseek(data->fd, 0, SEEK_SET);
248 #ifdef PHP_WIN32
249 	{
250 		unsigned int to_write = SESS_FILE_BUF_SIZE(ZSTR_LEN(val));
251 		char *buf = ZSTR_VAL(val);
252 		int wrote;
253 
254 		do {
255 			wrote = _write(data->fd, buf, to_write);
256 
257 			n += wrote;
258 			buf = wrote > -1 ? buf + wrote : 0;
259 			to_write = wrote > -1 ? SESS_FILE_BUF_SIZE(ZSTR_LEN(val) - n) : 0;
260 
261 		} while(wrote > 0);
262 	}
263 #else
264 	n = write(data->fd, ZSTR_VAL(val), ZSTR_LEN(val));
265 #endif
266 #endif
267 
268 	if (n != ZSTR_LEN(val)) {
269 		if (n == (size_t)-1) {
270 			php_error_docref(NULL, E_WARNING, "Write failed: %s (%d)", strerror(errno), errno);
271 		} else {
272 			php_error_docref(NULL, E_WARNING, "Write wrote less bytes than requested");
273 		}
274 		return FAILURE;
275 	}
276 
277 	return SUCCESS;
278 }
279 
ps_files_cleanup_dir(const zend_string * dirname,zend_long maxlifetime)280 static int ps_files_cleanup_dir(const zend_string *dirname, zend_long maxlifetime)
281 {
282 	DIR *dir;
283 	struct dirent *entry;
284 	zend_stat_t sbuf = {0};
285 	char buf[MAXPATHLEN];
286 	time_t now;
287 	int nrdels = 0;
288 
289 	dir = opendir(ZSTR_VAL(dirname));
290 	if (!dir) {
291 		php_error_docref(NULL, E_NOTICE, "ps_files_cleanup_dir: opendir(%s) failed: %s (%d)", ZSTR_VAL(dirname), strerror(errno), errno);
292 		return -1;
293 	}
294 
295 	time(&now);
296 
297 	if (ZSTR_LEN(dirname) >= MAXPATHLEN) {
298 		php_error_docref(NULL, E_NOTICE, "ps_files_cleanup_dir: dirname(%s) is too long", ZSTR_VAL(dirname));
299 		closedir(dir);
300 		return -1;
301 	}
302 
303 	/* Prepare buffer (dirname never changes) */
304 	memcpy(buf, ZSTR_VAL(dirname), ZSTR_LEN(dirname));
305 	buf[ZSTR_LEN(dirname)] = PHP_DIR_SEPARATOR;
306 
307 	while ((entry = readdir(dir))) {
308 		/* does the file start with our prefix? */
309 		if (!strncmp(entry->d_name, FILE_PREFIX, sizeof(FILE_PREFIX) - 1)) {
310 			size_t entry_len = strlen(entry->d_name);
311 
312 			/* does it fit into our buffer? */
313 			if (entry_len + ZSTR_LEN(dirname) + 2 < MAXPATHLEN) {
314 				/* create the full path.. */
315 				memcpy(buf + ZSTR_LEN(dirname) + 1, entry->d_name, entry_len);
316 
317 				/* NUL terminate it and */
318 				buf[ZSTR_LEN(dirname) + entry_len + 1] = '\0';
319 
320 				/* check whether its last access was more than maxlifetime ago */
321 				if (VCWD_STAT(buf, &sbuf) == 0 &&
322 						(now - sbuf.st_mtime) > maxlifetime) {
323 					VCWD_UNLINK(buf);
324 					nrdels++;
325 				}
326 			}
327 		}
328 	}
329 
330 	closedir(dir);
331 
332 	return (nrdels);
333 }
334 
ps_files_key_exists(ps_files * data,const zend_string * key)335 static zend_result ps_files_key_exists(ps_files *data, const zend_string *key)
336 {
337 	char buf[MAXPATHLEN];
338 	zend_stat_t sbuf = {0};
339 
340 	if (!key || !ps_files_path_create(buf, sizeof(buf), data, key)) {
341 		return FAILURE;
342 	}
343 	if (VCWD_STAT(buf, &sbuf)) {
344 		return FAILURE;
345 	}
346 	return SUCCESS;
347 }
348 
349 
350 #define PS_FILES_DATA ps_files *data = PS_GET_MOD_DATA()
351 
352 
353 /*
354  * Open save handler. Setup resources that are needed by the handler.
355  * PARAMETERS: PS_OPEN_ARGS in php_session.h
356  * RETURN VALUE: SUCCESS or FAILURE. Must set non-NULL valid module data
357  * (void **mod_data) with SUCCESS, NULL(default) for FAILUREs.
358  *
359  * Files save handler checks/create save_path directory and setup ps_files data.
360  * Note that files save handler supports splitting session data into multiple
361  * directories.
362  * *mod_data, *save_path, *session_name are guaranteed to have non-NULL values.
363  */
PS_OPEN_FUNC(files)364 PS_OPEN_FUNC(files)
365 {
366 	ps_files *data;
367 	const char *p, *last;
368 	const char *argv[3];
369 	int argc = 0;
370 	size_t dirdepth = 0;
371 	int filemode = 0600;
372 
373 	if (*save_path == '\0') {
374 		/* if save path is an empty string, determine the temporary dir */
375 		save_path = php_get_temporary_directory();
376 
377 		if (php_check_open_basedir(save_path)) {
378 			return FAILURE;
379 		}
380 	}
381 
382 	/* split up input parameter */
383 	last = save_path;
384 	p = strchr(save_path, ';');
385 	while (p) {
386 		argv[argc++] = last;
387 		last = ++p;
388 		p = strchr(p, ';');
389 		if (argc > 1) break;
390 	}
391 	argv[argc++] = last;
392 
393 	if (argc > 1) {
394 		errno = 0;
395 		dirdepth = (size_t) ZEND_STRTOL(argv[0], NULL, 10);
396 		if (errno == ERANGE) {
397 			php_error(E_WARNING, "The first parameter in session.save_path is invalid");
398 			return FAILURE;
399 		}
400 	}
401 
402 	if (argc > 2) {
403 		errno = 0;
404 		filemode = (int)ZEND_STRTOL(argv[1], NULL, 8);
405 		if (errno == ERANGE || filemode < 0 || filemode > 07777) {
406 			php_error(E_WARNING, "The second parameter in session.save_path is invalid");
407 			return FAILURE;
408 		}
409 	}
410 	save_path = argv[argc - 1];
411 
412 	data = ecalloc(1, sizeof(*data));
413 
414 	data->fd = -1;
415 	data->dirdepth = dirdepth;
416 	data->filemode = filemode;
417 	data->basedir = zend_string_init(save_path, strlen(save_path), /* persistent */ false);
418 
419 	if (PS_GET_MOD_DATA()) {
420 		ps_close_files(mod_data);
421 	}
422 	PS_SET_MOD_DATA(data);
423 
424 	return SUCCESS;
425 }
426 
427 
428 /*
429  * Clean up opened resources.
430  * PARAMETERS: PS_CLOSE_ARGS in php_session.h
431  * RETURN VALUE: SUCCESS. Must set PS module data(void **mod_data) to NULL.
432  *
433  * Files save handler closes open files and it's memory.
434  * *mod_data is guaranteed to have non-NULL value.
435  * PS_CLOSE_FUNC() must set *mod_data to NULL. PS_CLOSE_FUNC() should not
436  * fail.
437  */
PS_CLOSE_FUNC(files)438 PS_CLOSE_FUNC(files)
439 {
440 	PS_FILES_DATA;
441 
442 	ps_files_close(data);
443 
444 	if (data->last_key) {
445 		zend_string_release_ex(data->last_key, /* persistent */ false);
446 		data->last_key = NULL;
447 	}
448 
449 	zend_string_release_ex(data->basedir, /* persistent */ false);
450 	efree(data);
451 	PS_SET_MOD_DATA(NULL);
452 
453 	return SUCCESS;
454 }
455 
456 
457 /*
458  * Read session data from opened resource.
459  * PARAMETERS: PS_READ_ARGS in php_session.h
460  * RETURN VALUE: SUCCESS or FAILURE. Must set non-NULL session data to (zend_string **val)
461  * for SUCCESS. NULL(default) for FAILUREs.
462  *
463  * Files save handler supports splitting session data into multiple
464  * directories.
465  * *mod_data, *key are guaranteed to have non-NULL values.
466  */
PS_READ_FUNC(files)467 PS_READ_FUNC(files)
468 {
469 	zend_long n = 0;
470 	zend_stat_t sbuf = {0};
471 	PS_FILES_DATA;
472 
473 	ps_files_open(data, key);
474 	if (data->fd < 0) {
475 		return FAILURE;
476 	}
477 
478 	if (zend_fstat(data->fd, &sbuf)) {
479 		return FAILURE;
480 	}
481 
482 	data->st_size = sbuf.st_size;
483 
484 	if (sbuf.st_size == 0) {
485 		*val = ZSTR_EMPTY_ALLOC();
486 		return SUCCESS;
487 	}
488 
489 	*val = zend_string_alloc(sbuf.st_size, 0);
490 
491 #ifdef HAVE_PREAD
492 	n = pread(data->fd, ZSTR_VAL(*val), ZSTR_LEN(*val), 0);
493 #else
494 	lseek(data->fd, 0, SEEK_SET);
495 #ifdef PHP_WIN32
496 	{
497 		unsigned int to_read = SESS_FILE_BUF_SIZE(ZSTR_LEN(*val));
498 		char *buf = ZSTR_VAL(*val);
499 		int read_in;
500 
501 		do {
502 			read_in = _read(data->fd, buf, to_read);
503 
504 			n += read_in;
505 			buf = read_in > -1 ? buf + read_in : 0;
506 			to_read = read_in > -1 ? SESS_FILE_BUF_SIZE(ZSTR_LEN(*val) - n) : 0;
507 
508 		} while(read_in > 0);
509 
510 	}
511 #else
512 	n = read(data->fd, ZSTR_VAL(*val), ZSTR_LEN(*val));
513 #endif
514 #endif
515 
516 	if (n != (zend_long)sbuf.st_size) {
517 		if (n == -1) {
518 			php_error_docref(NULL, E_WARNING, "Read failed: %s (%d)", strerror(errno), errno);
519 		} else {
520 			php_error_docref(NULL, E_WARNING, "Read returned less bytes than requested");
521 		}
522 		zend_string_release_ex(*val, 0);
523 		*val =  ZSTR_EMPTY_ALLOC();
524 		return FAILURE;
525 	}
526 
527 	ZSTR_VAL(*val)[ZSTR_LEN(*val)] = '\0';
528 	return SUCCESS;
529 }
530 
531 
532 /*
533  * Write session data.
534  * PARAMETERS: PS_WRITE_ARGS in php_session.h
535  * RETURN VALUE: SUCCESS or FAILURE.
536  *
537  * PS_WRITE_FUNC() must write session data(zend_string *val) unconditionally.
538  * *mod_data, *key, *val are guaranteed to have non-NULL values.
539  */
PS_WRITE_FUNC(files)540 PS_WRITE_FUNC(files)
541 {
542 	PS_FILES_DATA;
543 
544 	return ps_files_write(data, key, val);
545 }
546 
547 
548 /*
549  * Update session data modification/access time stamp.
550  * PARAMETERS: PS_UPDATE_TIMESTAMP_ARGS in php_session.h
551  * RETURN VALUE: SUCCESS or FAILURE.
552  *
553  * PS_UPDATE_TIMESTAMP_FUNC() updates time stamp(mtime) so that active session
554  * data files will not be purged by GC. If session data storage does not need to
555  * update timestamp, it should return SUCCESS simply. (e.g. Memcache)
556  * *mod_data, *key, *val are guaranteed to have non-NULL values.
557  *
558  * NOTE: Updating access timestamp at PS_READ_FUNC() may extend life of obsolete
559  * session data. Use of PS_UPDATE_TIMESTAMP_FUNC() is preferred whenever it is
560  * possible.
561  */
PS_UPDATE_TIMESTAMP_FUNC(files)562 PS_UPDATE_TIMESTAMP_FUNC(files)
563 {
564 	char buf[MAXPATHLEN];
565 	int ret;
566 	PS_FILES_DATA;
567 
568 	if (!ps_files_path_create(buf, sizeof(buf), data, key)) {
569 		return FAILURE;
570 	}
571 
572 	/* Update mtime */
573 	ret = VCWD_UTIME(buf, NULL);
574 	if (ret == -1) {
575 		/* New session ID, create data file */
576 		return ps_files_write(data, key, val);
577 	}
578 
579 	return SUCCESS;
580 }
581 
582 
583 /*
584  * Delete session data.
585  * PARAMETERS: PS_DESTROY_ARGS in php_session.h
586  * RETURN VALUE: SUCCESS or FAILURE.
587  *
588  * PS_DESTROY_FUNC() must remove the session data specified by *key from
589  * session data storage unconditionally. It must not return FAILURE for
590  * non-existent session data.
591  * *mod_data, *key are guaranteed to have non-NULL values.
592  */
PS_DESTROY_FUNC(files)593 PS_DESTROY_FUNC(files)
594 {
595 	char buf[MAXPATHLEN];
596 	PS_FILES_DATA;
597 
598 	if (!ps_files_path_create(buf, sizeof(buf), data, key)) {
599 		return FAILURE;
600 	}
601 
602 	if (data->fd != -1) {
603 		ps_files_close(data);
604 
605 		if (VCWD_UNLINK(buf) == -1) {
606 			/* This is a little safety check for instances when we are dealing with a regenerated session
607 			 * that was not yet written to disk. */
608 			if (!VCWD_ACCESS(buf, F_OK)) {
609 				return FAILURE;
610 			}
611 		}
612 	}
613 
614 	return SUCCESS;
615 }
616 
617 
618 /*
619  * Cleanup expired session data.
620  * PARAMETERS: PS_GC_ARGS in php_session.h
621  * RETURN VALUE: SUCCESS or FAILURE. Number of deleted records(int *nrdels(default=-1)).
622  *
623  * PS_GC_FUNC() must remove session data that are not accessed
624  * 'session.maxlifetime'(seconds). If storage does not need manual GC, it
625  * may return SUCCESS simply. (e.g. Memcache) It must set number of records
626  * deleted(nrdels).
627  * *mod_data is guaranteed to have non-NULL value.
628  */
PS_GC_FUNC(files)629 PS_GC_FUNC(files)
630 {
631 	PS_FILES_DATA;
632 
633 	/* We don't perform any cleanup, if dirdepth is larger than 0.
634 	   we return SUCCESS, since all cleanup should be handled by
635 	   an external entity (i.e. find -ctime x | xargs rm) */
636 
637 	if (data->dirdepth == 0) {
638 		*nrdels = ps_files_cleanup_dir(data->basedir, maxlifetime);
639 	} else {
640 		*nrdels = -1; // Cannot process multiple depth save dir
641 	}
642 
643 	return *nrdels;
644 }
645 
646 
647 /*
648  * Create session ID.
649  * PARAMETERS: PS_CREATE_SID_ARGS in php_session.h
650  * RETURN VALUE: Valid session ID(zend_string *) or NULL for FAILURE.
651  *
652  * PS_CREATE_SID_FUNC() must check collision. i.e. Check session data if
653  * new sid exists already.
654  * *mod_data is guaranteed to have non-NULL value.
655  * NOTE: Default php_session_create_id() does not check collision. If
656  * NULL is returned, session module create new ID by using php_session_create_id().
657  * If php_session_create_id() fails due to invalid configuration, it raises E_ERROR.
658  * NULL return value checks from php_session_create_id() is not required generally.
659  */
PS_CREATE_SID_FUNC(files)660 PS_CREATE_SID_FUNC(files)
661 {
662 	zend_string *sid;
663 	int maxfail = 3;
664 	PS_FILES_DATA;
665 
666 	do {
667 		sid = php_session_create_id((void**)&data);
668 		if (!sid) {
669 			if (--maxfail < 0) {
670 				return NULL;
671 			} else {
672 				continue;
673 			}
674 		}
675 		/* Check collision */
676 		/* FIXME: mod_data(data) should not be NULL (User handler could be NULL) */
677 		if (data && ps_files_key_exists(data, sid) == SUCCESS) {
678 			zend_string_release_ex(sid, 0);
679 			sid = NULL;
680 			if (--maxfail < 0) {
681 				return NULL;
682 			}
683 		}
684 	} while(!sid);
685 
686 	return sid;
687 }
688 
689 
690 /*
691  * Check session ID existence for use_strict_mode support.
692  * PARAMETERS: PS_VALIDATE_SID_ARGS in php_session.h
693  * RETURN VALUE: SUCCESS or FAILURE.
694  *
695  * Return SUCCESS for valid key(already existing session).
696  * Return FAILURE for invalid key(non-existing session).
697  * *mod_data, *key are guaranteed to have non-NULL values.
698  */
PS_VALIDATE_SID_FUNC(files)699 PS_VALIDATE_SID_FUNC(files)
700 {
701 	PS_FILES_DATA;
702 
703 	return ps_files_key_exists(data, key);
704 }
705