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