xref: /PHP-8.2/ext/standard/filestat.c (revision 3fbca7fb)
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:  Jim Winstead <jimw@php.net>                                 |
14    +----------------------------------------------------------------------+
15  */
16 
17 #include "php.h"
18 #include "fopen_wrappers.h"
19 #include "php_globals.h"
20 
21 #include <stdlib.h>
22 #include <sys/stat.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <ctype.h>
26 #include <time.h>
27 
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31 
32 #ifdef HAVE_SYS_PARAM_H
33 # include <sys/param.h>
34 #endif
35 
36 #ifdef HAVE_SYS_VFS_H
37 # include <sys/vfs.h>
38 #endif
39 
40 #ifdef OS2
41 #  define INCL_DOS
42 #  include <os2.h>
43 #endif
44 
45 #if defined(__APPLE__)
46   /*
47    Apple statvfs has an interger overflow in libc copying to statvfs.
48    cvt_statfs_to_statvfs(struct statfs *from, struct statvfs *to) {
49    to->f_blocks = (fsblkcnt_t)from->f_blocks;
50    */
51 #  undef HAVE_SYS_STATVFS_H
52 #  undef HAVE_STATVFS
53 #endif
54 
55 #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
56 # include <sys/statvfs.h>
57 #elif defined(HAVE_SYS_STATFS_H) && defined(HAVE_STATFS)
58 # include <sys/statfs.h>
59 #elif defined(HAVE_SYS_MOUNT_H) && defined(HAVE_STATFS)
60 # include <sys/mount.h>
61 #endif
62 
63 #ifdef HAVE_PWD_H
64 # ifdef PHP_WIN32
65 #  include "win32/pwd.h"
66 # else
67 #  include <pwd.h>
68 # endif
69 #endif
70 
71 #if HAVE_GRP_H
72 # include <grp.h>
73 #endif
74 
75 #ifdef HAVE_UTIME
76 # ifdef PHP_WIN32
77 #  include <sys/utime.h>
78 # else
79 #  include <utime.h>
80 # endif
81 #endif
82 
83 #ifdef PHP_WIN32
84 #include "win32/winutil.h"
85 #endif
86 
87 #include "basic_functions.h"
88 #include "php_filestat.h"
89 
PHP_RINIT_FUNCTION(filestat)90 PHP_RINIT_FUNCTION(filestat) /* {{{ */
91 {
92 	BG(CurrentStatFile)=NULL;
93 	BG(CurrentLStatFile)=NULL;
94 	return SUCCESS;
95 }
96 /* }}} */
97 
PHP_RSHUTDOWN_FUNCTION(filestat)98 PHP_RSHUTDOWN_FUNCTION(filestat) /* {{{ */
99 {
100 	if (BG(CurrentStatFile)) {
101 		zend_string_release(BG(CurrentStatFile));
102 		BG(CurrentStatFile) = NULL;
103 	}
104 	if (BG(CurrentLStatFile)) {
105 		zend_string_release(BG(CurrentLStatFile));
106 		BG(CurrentLStatFile) = NULL;
107 	}
108 	return SUCCESS;
109 }
110 /* }}} */
111 
php_disk_total_space(char * path,double * space)112 static int php_disk_total_space(char *path, double *space) /* {{{ */
113 #if defined(WINDOWS) /* {{{ */
114 {
115 	ULARGE_INTEGER FreeBytesAvailableToCaller;
116 	ULARGE_INTEGER TotalNumberOfBytes;
117 	ULARGE_INTEGER TotalNumberOfFreeBytes;
118 	PHP_WIN32_IOUTIL_INIT_W(path)
119 
120 	if (GetDiskFreeSpaceExW(pathw, &FreeBytesAvailableToCaller, &TotalNumberOfBytes, &TotalNumberOfFreeBytes) == 0) {
121 		char *err = php_win_err();
122 		php_error_docref(NULL, E_WARNING, "%s", err);
123 		php_win_err_free(err);
124 		PHP_WIN32_IOUTIL_CLEANUP_W()
125 		return FAILURE;
126 	}
127 
128 	/* i know - this is ugly, but i works <thies@thieso.net> */
129 	*space = TotalNumberOfBytes.HighPart * (double) (((zend_ulong)1) << 31) * 2.0 + TotalNumberOfBytes.LowPart;
130 
131 	PHP_WIN32_IOUTIL_CLEANUP_W()
132 
133 	return SUCCESS;
134 }
135 /* }}} */
136 #elif defined(OS2) /* {{{ */
137 {
138 	double bytestotal = 0;
139 	FSALLOCATE fsinfo;
140 	char drive = path[0] & 95;
141 
142 	if (DosQueryFSInfo( drive ? drive - 64 : 0, FSIL_ALLOC, &fsinfo, sizeof( fsinfo ) ) == 0) {
143 		bytestotal = (double)fsinfo.cbSector * fsinfo.cSectorUnit * fsinfo.cUnit;
144 		*space = bytestotal;
145 		return SUCCESS;
146 	}
147 	return FAILURE;
148 }
149 /* }}} */
150 #else /* {{{ if !defined(OS2) && !defined(WINDOWS) */
151 {
152 	double bytestotal = 0;
153 #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
154 	struct statvfs buf;
155 #elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS)
156 	struct statfs buf;
157 #endif
158 
159 #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
160 	if (statvfs(path, &buf)) {
161 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
162 		return FAILURE;
163 	}
164 	if (buf.f_frsize) {
165 		bytestotal = (((double)buf.f_blocks) * ((double)buf.f_frsize));
166 	} else {
167 		bytestotal = (((double)buf.f_blocks) * ((double)buf.f_bsize));
168 	}
169 
170 #elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS)
171 	if (statfs(path, &buf)) {
172 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
173 		return FAILURE;
174 	}
175 	bytestotal = (((double)buf.f_bsize) * ((double)buf.f_blocks));
176 #endif
177 
178 	*space = bytestotal;
179 	return SUCCESS;
180 }
181 #endif
182 /* }}} */
183 /* }}} */
184 
185 /* {{{ Get total disk space for filesystem that path is on */
PHP_FUNCTION(disk_total_space)186 PHP_FUNCTION(disk_total_space)
187 {
188 	double bytestotal;
189 	char *path, fullpath[MAXPATHLEN];
190 	size_t path_len;
191 
192 	ZEND_PARSE_PARAMETERS_START(1, 1)
193 		Z_PARAM_PATH(path, path_len)
194 	ZEND_PARSE_PARAMETERS_END();
195 
196 	if (!expand_filepath(path, fullpath)) {
197 		RETURN_FALSE;
198 	}
199 
200 	if (php_check_open_basedir(fullpath)) {
201 		RETURN_FALSE;
202 	}
203 
204 	if (php_disk_total_space(fullpath, &bytestotal) == SUCCESS) {
205 		RETURN_DOUBLE(bytestotal);
206 	}
207 	RETURN_FALSE;
208 }
209 /* }}} */
210 
php_disk_free_space(char * path,double * space)211 static int php_disk_free_space(char *path, double *space) /* {{{ */
212 #if defined(WINDOWS) /* {{{ */
213 {
214 	ULARGE_INTEGER FreeBytesAvailableToCaller;
215 	ULARGE_INTEGER TotalNumberOfBytes;
216 	ULARGE_INTEGER TotalNumberOfFreeBytes;
217 	PHP_WIN32_IOUTIL_INIT_W(path)
218 
219 	if (GetDiskFreeSpaceExW(pathw, &FreeBytesAvailableToCaller, &TotalNumberOfBytes, &TotalNumberOfFreeBytes) == 0) {
220 		char *err = php_win_err();
221 		php_error_docref(NULL, E_WARNING, "%s", err);
222 		php_win_err_free(err);
223 		PHP_WIN32_IOUTIL_CLEANUP_W()
224 		return FAILURE;
225 	}
226 
227 	*space = FreeBytesAvailableToCaller.HighPart * (double) (1ULL << 32)  + FreeBytesAvailableToCaller.LowPart;
228 
229 	PHP_WIN32_IOUTIL_CLEANUP_W()
230 
231 	return SUCCESS;
232 }
233 /* }}} */
234 #elif defined(OS2) /* {{{ */
235 {
236 	double bytesfree = 0;
237 	FSALLOCATE fsinfo;
238 	char drive = path[0] & 95;
239 
240 	if (DosQueryFSInfo( drive ? drive - 64 : 0, FSIL_ALLOC, &fsinfo, sizeof( fsinfo ) ) == 0) {
241 		bytesfree = (double)fsinfo.cbSector * fsinfo.cSectorUnit * fsinfo.cUnitAvail;
242 		*space = bytesfree;
243 		return SUCCESS;
244 	}
245 	return FAILURE;
246 }
247 /* }}} */
248 #else /* {{{ if !defined(OS2) && !defined(WINDOWS) */
249 {
250 	double bytesfree = 0;
251 #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
252 	struct statvfs buf;
253 #elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS)
254 	struct statfs buf;
255 #endif
256 
257 #if defined(HAVE_SYS_STATVFS_H) && defined(HAVE_STATVFS)
258 	if (statvfs(path, &buf)) {
259 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
260 		return FAILURE;
261 	}
262 	if (buf.f_frsize) {
263 		bytesfree = (((double)buf.f_bavail) * ((double)buf.f_frsize));
264 	} else {
265 		bytesfree = (((double)buf.f_bavail) * ((double)buf.f_bsize));
266 	}
267 #elif (defined(HAVE_SYS_STATFS_H) || defined(HAVE_SYS_MOUNT_H)) && defined(HAVE_STATFS)
268 	if (statfs(path, &buf)) {
269 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
270 		return FAILURE;
271 	}
272 	bytesfree = (((double)buf.f_bsize) * ((double)buf.f_bavail));
273 #endif
274 
275 	*space = bytesfree;
276 	return SUCCESS;
277 }
278 #endif
279 /* }}} */
280 /* }}} */
281 
282 /* {{{ Get free disk space for filesystem that path is on */
PHP_FUNCTION(disk_free_space)283 PHP_FUNCTION(disk_free_space)
284 {
285 	double bytesfree;
286 	char *path, fullpath[MAXPATHLEN];
287 	size_t path_len;
288 
289 	ZEND_PARSE_PARAMETERS_START(1, 1)
290 		Z_PARAM_PATH(path, path_len)
291 	ZEND_PARSE_PARAMETERS_END();
292 
293 	if (!expand_filepath(path, fullpath)) {
294 		RETURN_FALSE;
295 	}
296 
297 	if (php_check_open_basedir(fullpath)) {
298 		RETURN_FALSE;
299 	}
300 
301 	if (php_disk_free_space(fullpath, &bytesfree) == SUCCESS) {
302 		RETURN_DOUBLE(bytesfree);
303 	}
304 	RETURN_FALSE;
305 }
306 /* }}} */
307 
308 #ifndef PHP_WIN32
php_get_gid_by_name(const char * name,gid_t * gid)309 PHPAPI int php_get_gid_by_name(const char *name, gid_t *gid)
310 {
311 #if defined(ZTS) && defined(HAVE_GETGRNAM_R) && defined(_SC_GETGR_R_SIZE_MAX)
312 		struct group gr;
313 		struct group *retgrptr;
314 		long grbuflen = sysconf(_SC_GETGR_R_SIZE_MAX);
315 		char *grbuf;
316 		int err;
317 
318 		if (grbuflen < 1) {
319 			grbuflen = 1024;
320 		}
321 # if ZEND_DEBUG
322 		/* Test retry logic */
323 		grbuflen = 1;
324 # endif
325 		grbuf = emalloc(grbuflen);
326 
327 try_again:
328 		err = getgrnam_r(name, &gr, grbuf, grbuflen, &retgrptr);
329 		if (err != 0 || retgrptr == NULL) {
330 			if (err == ERANGE) {
331 				grbuflen *= 2;
332 				grbuf = erealloc(grbuf, grbuflen);
333 				goto try_again;
334 			}
335 			efree(grbuf);
336 			return FAILURE;
337 		}
338 		efree(grbuf);
339 		*gid = gr.gr_gid;
340 #else
341 		struct group *gr = getgrnam(name);
342 
343 		if (!gr) {
344 			return FAILURE;
345 		}
346 		*gid = gr->gr_gid;
347 #endif
348 		return SUCCESS;
349 }
350 #endif
351 
php_do_chgrp(INTERNAL_FUNCTION_PARAMETERS,int do_lchgrp)352 static void php_do_chgrp(INTERNAL_FUNCTION_PARAMETERS, int do_lchgrp) /* {{{ */
353 {
354 	char *filename;
355 	size_t filename_len;
356 	zend_string *group_str;
357 	zend_long group_long;
358 #if !defined(WINDOWS)
359 	gid_t gid;
360 	int ret;
361 #endif
362 	php_stream_wrapper *wrapper;
363 
364 	ZEND_PARSE_PARAMETERS_START(2, 2)
365 		Z_PARAM_PATH(filename, filename_len)
366 		Z_PARAM_STR_OR_LONG(group_str, group_long)
367 	ZEND_PARSE_PARAMETERS_END();
368 
369 	wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
370 	if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) {
371 		if(wrapper && wrapper->wops->stream_metadata) {
372 			int option;
373 			void *value;
374 			if (group_str) {
375 				option = PHP_STREAM_META_GROUP_NAME;
376 				value = ZSTR_VAL(group_str);
377 			} else {
378 				option = PHP_STREAM_META_GROUP;
379 				value = &group_long;
380 			}
381 
382 			if(wrapper->wops->stream_metadata(wrapper, filename, option, value, NULL)) {
383 				RETURN_TRUE;
384 			} else {
385 				RETURN_FALSE;
386 			}
387 		} else {
388 #ifndef WINDOWS
389 /* On Windows, we expect regular chgrp to fail silently by default */
390 			php_error_docref(NULL, E_WARNING, "Cannot call chgrp() for a non-standard stream");
391 #endif
392 			RETURN_FALSE;
393 		}
394 	}
395 
396 #ifdef WINDOWS
397 	/* We have no native chgrp on Windows, nothing left to do if stream doesn't have own implementation */
398 	RETURN_FALSE;
399 #else
400 	if (group_str) {
401 		if (php_get_gid_by_name(ZSTR_VAL(group_str), &gid) != SUCCESS) {
402 			php_error_docref(NULL, E_WARNING, "Unable to find gid for %s", ZSTR_VAL(group_str));
403 			RETURN_FALSE;
404 		}
405 	} else {
406 		gid = (gid_t) group_long;
407 	}
408 
409 	/* Check the basedir */
410 	if (php_check_open_basedir(filename)) {
411 		RETURN_FALSE;
412 	}
413 
414 	if (do_lchgrp) {
415 #ifdef HAVE_LCHOWN
416 		ret = VCWD_LCHOWN(filename, -1, gid);
417 #endif
418 	} else {
419 		ret = VCWD_CHOWN(filename, -1, gid);
420 	}
421 	if (ret == -1) {
422 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
423 		RETURN_FALSE;
424 	}
425 	RETURN_TRUE;
426 #endif
427 }
428 /* }}} */
429 
430 /* {{{ Change file group */
PHP_FUNCTION(chgrp)431 PHP_FUNCTION(chgrp)
432 {
433 	php_do_chgrp(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
434 }
435 /* }}} */
436 
437 /* {{{ Change symlink group */
438 #ifdef HAVE_LCHOWN
PHP_FUNCTION(lchgrp)439 PHP_FUNCTION(lchgrp)
440 {
441 	php_do_chgrp(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
442 }
443 #endif
444 /* }}} */
445 
446 #ifndef PHP_WIN32
php_get_uid_by_name(const char * name,uid_t * uid)447 PHPAPI uid_t php_get_uid_by_name(const char *name, uid_t *uid)
448 {
449 #if defined(ZTS) && defined(_SC_GETPW_R_SIZE_MAX) && defined(HAVE_GETPWNAM_R)
450 		struct passwd pw;
451 		struct passwd *retpwptr = NULL;
452 		long pwbuflen = sysconf(_SC_GETPW_R_SIZE_MAX);
453 		char *pwbuf;
454 		int err;
455 
456 		if (pwbuflen < 1) {
457 			pwbuflen = 1024;
458 		}
459 # if ZEND_DEBUG
460 		/* Test retry logic */
461 		pwbuflen = 1;
462 # endif
463 		pwbuf = emalloc(pwbuflen);
464 
465 try_again:
466 		err = getpwnam_r(name, &pw, pwbuf, pwbuflen, &retpwptr);
467 		if (err != 0 || retpwptr == NULL) {
468 			if (err == EAGAIN) {
469 				pwbuflen *= 2;
470 				pwbuf = erealloc(pwbuf, pwbuflen);
471 				goto try_again;
472 			}
473 			efree(pwbuf);
474 			return FAILURE;
475 		}
476 		efree(pwbuf);
477 		*uid = pw.pw_uid;
478 #else
479 		struct passwd *pw = getpwnam(name);
480 
481 		if (!pw) {
482 			return FAILURE;
483 		}
484 		*uid = pw->pw_uid;
485 #endif
486 		return SUCCESS;
487 }
488 #endif
489 
php_do_chown(INTERNAL_FUNCTION_PARAMETERS,int do_lchown)490 static void php_do_chown(INTERNAL_FUNCTION_PARAMETERS, int do_lchown) /* {{{ */
491 {
492 	char *filename;
493 	size_t filename_len;
494 	zend_string *user_str;
495 	zend_long user_long;
496 #if !defined(WINDOWS)
497 	uid_t uid;
498 	int ret;
499 #endif
500 	php_stream_wrapper *wrapper;
501 
502 	ZEND_PARSE_PARAMETERS_START(2, 2)
503 		Z_PARAM_PATH(filename, filename_len)
504 		Z_PARAM_STR_OR_LONG(user_str, user_long)
505 	ZEND_PARSE_PARAMETERS_END();
506 
507 	wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
508 	if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) {
509 		if(wrapper && wrapper->wops->stream_metadata) {
510 			int option;
511 			void *value;
512 			if (user_str) {
513 				option = PHP_STREAM_META_OWNER_NAME;
514 				value = ZSTR_VAL(user_str);
515 			} else {
516 				option = PHP_STREAM_META_OWNER;
517 				value = &user_long;
518 			}
519 
520 			if(wrapper->wops->stream_metadata(wrapper, filename, option, value, NULL)) {
521 				RETURN_TRUE;
522 			} else {
523 				RETURN_FALSE;
524 			}
525 		} else {
526 #ifndef WINDOWS
527 /* On Windows, we expect regular chown to fail silently by default */
528 			php_error_docref(NULL, E_WARNING, "Cannot call chown() for a non-standard stream");
529 #endif
530 			RETURN_FALSE;
531 		}
532 	}
533 
534 #ifdef WINDOWS
535 	/* We have no native chown on Windows, nothing left to do if stream doesn't have own implementation */
536 	RETURN_FALSE;
537 #else
538 
539 	if (user_str) {
540 		if (php_get_uid_by_name(ZSTR_VAL(user_str), &uid) != SUCCESS) {
541 			php_error_docref(NULL, E_WARNING, "Unable to find uid for %s", ZSTR_VAL(user_str));
542 			RETURN_FALSE;
543 		}
544 	} else {
545 		uid = (uid_t) user_long;
546 	}
547 
548 	/* Check the basedir */
549 	if (php_check_open_basedir(filename)) {
550 		RETURN_FALSE;
551 	}
552 
553 	if (do_lchown) {
554 #ifdef HAVE_LCHOWN
555 		ret = VCWD_LCHOWN(filename, uid, -1);
556 #endif
557 	} else {
558 		ret = VCWD_CHOWN(filename, uid, -1);
559 	}
560 	if (ret == -1) {
561 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
562 		RETURN_FALSE;
563 	}
564 	RETURN_TRUE;
565 #endif
566 }
567 /* }}} */
568 
569 
570 /* {{{ Change file owner */
PHP_FUNCTION(chown)571 PHP_FUNCTION(chown)
572 {
573 	php_do_chown(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
574 }
575 /* }}} */
576 
577 /* {{{ Change file owner */
578 #ifdef HAVE_LCHOWN
PHP_FUNCTION(lchown)579 PHP_FUNCTION(lchown)
580 {
581 	RETVAL_TRUE;
582 	php_do_chown(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
583 }
584 #endif
585 /* }}} */
586 
587 /* {{{ Change file mode */
PHP_FUNCTION(chmod)588 PHP_FUNCTION(chmod)
589 {
590 	char *filename;
591 	size_t filename_len;
592 	zend_long mode;
593 	int ret;
594 	mode_t imode;
595 	php_stream_wrapper *wrapper;
596 
597 	ZEND_PARSE_PARAMETERS_START(2, 2)
598 		Z_PARAM_PATH(filename, filename_len)
599 		Z_PARAM_LONG(mode)
600 	ZEND_PARSE_PARAMETERS_END();
601 
602 	wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
603 	if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) {
604 		if(wrapper && wrapper->wops->stream_metadata) {
605 			if(wrapper->wops->stream_metadata(wrapper, filename, PHP_STREAM_META_ACCESS, &mode, NULL)) {
606 				RETURN_TRUE;
607 			} else {
608 				RETURN_FALSE;
609 			}
610 		} else {
611 			php_error_docref(NULL, E_WARNING, "Cannot call chmod() for a non-standard stream");
612 			RETURN_FALSE;
613 		}
614 	}
615 
616 	/* Check the basedir */
617 	if (php_check_open_basedir(filename)) {
618 		RETURN_FALSE;
619 	}
620 
621 	imode = (mode_t) mode;
622 
623 	ret = VCWD_CHMOD(filename, imode);
624 	if (ret == -1) {
625 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
626 		RETURN_FALSE;
627 	}
628 	RETURN_TRUE;
629 }
630 /* }}} */
631 
632 #ifdef HAVE_UTIME
633 /* {{{ Set modification time of file */
PHP_FUNCTION(touch)634 PHP_FUNCTION(touch)
635 {
636 	char *filename;
637 	size_t filename_len;
638 	zend_long filetime = 0, fileatime = 0;
639 	bool filetime_is_null = 1, fileatime_is_null = 1;
640 	int ret;
641 	FILE *file;
642 	struct utimbuf newtimebuf;
643 	struct utimbuf *newtime = &newtimebuf;
644 	php_stream_wrapper *wrapper;
645 
646 	ZEND_PARSE_PARAMETERS_START(1, 3)
647 		Z_PARAM_PATH(filename, filename_len)
648 		Z_PARAM_OPTIONAL
649 		Z_PARAM_LONG_OR_NULL(filetime, filetime_is_null)
650 		Z_PARAM_LONG_OR_NULL(fileatime, fileatime_is_null)
651 	ZEND_PARSE_PARAMETERS_END();
652 
653 	if (!filename_len) {
654 		RETURN_FALSE;
655 	}
656 
657 	if (filetime_is_null && fileatime_is_null) {
658 		newtime = NULL;
659 	} else if (!filetime_is_null && fileatime_is_null) {
660 		newtime->modtime = newtime->actime = filetime;
661 	} else if (filetime_is_null && !fileatime_is_null) {
662 		zend_argument_value_error(2, "cannot be null when argument #3 ($atime) is an integer");
663 		RETURN_THROWS();
664 	} else {
665 		newtime->modtime = filetime;
666 		newtime->actime = fileatime;
667 	}
668 
669 	wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
670 	if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) {
671 		if(wrapper && wrapper->wops->stream_metadata) {
672 			if(wrapper->wops->stream_metadata(wrapper, filename, PHP_STREAM_META_TOUCH, newtime, NULL)) {
673 				RETURN_TRUE;
674 			} else {
675 				RETURN_FALSE;
676 			}
677 		} else {
678 			php_stream *stream;
679 			if(!filetime_is_null || !fileatime_is_null) {
680 				php_error_docref(NULL, E_WARNING, "Cannot call touch() for a non-standard stream");
681 				RETURN_FALSE;
682 			}
683 			stream = php_stream_open_wrapper_ex(filename, "c", REPORT_ERRORS, NULL, NULL);
684 			if(stream != NULL) {
685 				php_stream_close(stream);
686 				RETURN_TRUE;
687 			} else {
688 				RETURN_FALSE;
689 			}
690 		}
691 	}
692 
693 	/* Check the basedir */
694 	if (php_check_open_basedir(filename)) {
695 		RETURN_FALSE;
696 	}
697 
698 	/* create the file if it doesn't exist already */
699 	if (VCWD_ACCESS(filename, F_OK) != 0) {
700 		file = VCWD_FOPEN(filename, "w");
701 		if (file == NULL) {
702 			php_error_docref(NULL, E_WARNING, "Unable to create file %s because %s", filename, strerror(errno));
703 			RETURN_FALSE;
704 		}
705 		fclose(file);
706 	}
707 
708 	ret = VCWD_UTIME(filename, newtime);
709 	if (ret == -1) {
710 		php_error_docref(NULL, E_WARNING, "Utime failed: %s", strerror(errno));
711 		RETURN_FALSE;
712 	}
713 	RETURN_TRUE;
714 }
715 /* }}} */
716 #endif
717 
718 /* {{{ php_clear_stat_cache() */
php_clear_stat_cache(bool clear_realpath_cache,const char * filename,size_t filename_len)719 PHPAPI void php_clear_stat_cache(bool clear_realpath_cache, const char *filename, size_t filename_len)
720 {
721 	/* always clear CurrentStatFile and CurrentLStatFile even if filename is not NULL
722 	 * as it may contain outdated data (e.g. "nlink" for a directory when deleting a file
723 	 * in this directory, as shown by lstat_stat_variation9.phpt) */
724 	if (BG(CurrentStatFile)) {
725 		zend_string_release(BG(CurrentStatFile));
726 		BG(CurrentStatFile) = NULL;
727 	}
728 	if (BG(CurrentLStatFile)) {
729 		zend_string_release(BG(CurrentLStatFile));
730 		BG(CurrentLStatFile) = NULL;
731 	}
732 	if (clear_realpath_cache) {
733 		if (filename != NULL) {
734 			realpath_cache_del(filename, filename_len);
735 		} else {
736 			realpath_cache_clean();
737 		}
738 	}
739 }
740 /* }}} */
741 
742 /* {{{ Clear file stat cache */
PHP_FUNCTION(clearstatcache)743 PHP_FUNCTION(clearstatcache)
744 {
745 	bool  clear_realpath_cache = 0;
746 	char      *filename             = NULL;
747 	size_t     filename_len         = 0;
748 
749 	ZEND_PARSE_PARAMETERS_START(0, 2)
750 		Z_PARAM_OPTIONAL
751 		Z_PARAM_BOOL(clear_realpath_cache)
752 		Z_PARAM_PATH(filename, filename_len)
753 	ZEND_PARSE_PARAMETERS_END();
754 
755 	php_clear_stat_cache(clear_realpath_cache, filename, filename_len);
756 }
757 /* }}} */
758 
759 #define IS_LINK_OPERATION(__t) ((__t) == FS_TYPE || (__t) == FS_IS_LINK || (__t) == FS_LSTAT || (__t) == FS_LPERMS)
760 #define IS_EXISTS_CHECK(__t) ((__t) == FS_EXISTS  || (__t) == FS_IS_W || (__t) == FS_IS_R || (__t) == FS_IS_X || (__t) == FS_IS_FILE || (__t) == FS_IS_DIR || (__t) == FS_IS_LINK || (__t) == FS_LPERMS)
761 #define IS_ABLE_CHECK(__t) ((__t) == FS_IS_R || (__t) == FS_IS_W || (__t) == FS_IS_X)
762 #define IS_ACCESS_CHECK(__t) (IS_ABLE_CHECK(type) || (__t) == FS_EXISTS)
763 
764 /* {{{ php_stat */
php_stat(zend_string * filename,int type,zval * return_value)765 PHPAPI void php_stat(zend_string *filename, int type, zval *return_value)
766 {
767 	zend_stat_t *stat_sb = {0};
768 	php_stream_statbuf ssb = {0};
769 	int flags = 0, rmask=S_IROTH, wmask=S_IWOTH, xmask=S_IXOTH; /* access rights defaults to other */
770 	const char *local = NULL;
771 	php_stream_wrapper *wrapper = NULL;
772 
773 	if (IS_ACCESS_CHECK(type)) {
774 		if (!ZSTR_LEN(filename) || CHECK_NULL_PATH(ZSTR_VAL(filename), ZSTR_LEN(filename))) {
775 			if (ZSTR_LEN(filename) && !IS_EXISTS_CHECK(type)) {
776 				php_error_docref(NULL, E_WARNING, "Filename contains null byte");
777 			}
778 			RETURN_FALSE;
779 		}
780 
781 		if ((wrapper = php_stream_locate_url_wrapper(ZSTR_VAL(filename), &local, 0)) == &php_plain_files_wrapper
782 		 && php_check_open_basedir(local)) {
783 			RETURN_FALSE;
784 		}
785 
786 		if (wrapper == &php_plain_files_wrapper) {
787 
788 			switch (type) {
789 #ifdef F_OK
790 				case FS_EXISTS:
791 					RETURN_BOOL(VCWD_ACCESS(local, F_OK) == 0);
792 					break;
793 #endif
794 #ifdef W_OK
795 				case FS_IS_W:
796 					RETURN_BOOL(VCWD_ACCESS(local, W_OK) == 0);
797 					break;
798 #endif
799 #ifdef R_OK
800 				case FS_IS_R:
801 					RETURN_BOOL(VCWD_ACCESS(local, R_OK) == 0);
802 					break;
803 #endif
804 #ifdef X_OK
805 				case FS_IS_X:
806 					RETURN_BOOL(VCWD_ACCESS(local, X_OK) == 0);
807 					break;
808 #endif
809 			}
810 		}
811 	}
812 
813 	if (IS_LINK_OPERATION(type)) {
814 		flags |= PHP_STREAM_URL_STAT_LINK;
815 	}
816 	if (IS_EXISTS_CHECK(type)) {
817 		flags |= PHP_STREAM_URL_STAT_QUIET;
818 	}
819 
820 	do {
821 		/* Try to hit the cache first */
822 		if (flags & PHP_STREAM_URL_STAT_LINK) {
823 			if (filename == BG(CurrentLStatFile)
824 			 || (BG(CurrentLStatFile)
825 			  && zend_string_equal_content(filename, BG(CurrentLStatFile)))) {
826 				memcpy(&ssb, &BG(lssb), sizeof(php_stream_statbuf));
827 				break;
828 			}
829 		} else {
830 			if (filename == BG(CurrentStatFile)
831 			 || (BG(CurrentStatFile)
832 			  && zend_string_equal_content(filename, BG(CurrentStatFile)))) {
833 				memcpy(&ssb, &BG(ssb), sizeof(php_stream_statbuf));
834 				break;
835 			}
836 		}
837 
838 		if (!wrapper) {
839 			if (!ZSTR_LEN(filename) || CHECK_NULL_PATH(ZSTR_VAL(filename), ZSTR_LEN(filename))) {
840 				if (ZSTR_LEN(filename) && !IS_EXISTS_CHECK(type)) {
841 					php_error_docref(NULL, E_WARNING, "Filename contains null byte");
842 				}
843 				RETURN_FALSE;
844 			}
845 
846 			if ((wrapper = php_stream_locate_url_wrapper(ZSTR_VAL(filename), &local, 0)) == &php_plain_files_wrapper
847 			 && php_check_open_basedir(local)) {
848 				RETURN_FALSE;
849 			}
850 		}
851 
852 		if (!wrapper
853 		 || !wrapper->wops->url_stat
854 		 || wrapper->wops->url_stat(wrapper, local, flags | PHP_STREAM_URL_STAT_IGNORE_OPEN_BASEDIR, &ssb, NULL)) {
855 			/* Error Occurred */
856 			if (!IS_EXISTS_CHECK(type)) {
857 				php_error_docref(NULL, E_WARNING, "%sstat failed for %s", IS_LINK_OPERATION(type) ? "L" : "", ZSTR_VAL(filename));
858 			}
859 			RETURN_FALSE;
860 		}
861 
862 		/* Drop into cache */
863 		if (flags & PHP_STREAM_URL_STAT_LINK) {
864 			if (BG(CurrentLStatFile)) {
865 				zend_string_release(BG(CurrentLStatFile));
866 			}
867 			BG(CurrentLStatFile) = zend_string_copy(filename);
868 			memcpy(&BG(lssb), &ssb, sizeof(php_stream_statbuf));
869 		}
870 		if (!(flags & PHP_STREAM_URL_STAT_LINK)
871 		 || !S_ISLNK(ssb.sb.st_mode)) {
872 			if (BG(CurrentStatFile)) {
873 				zend_string_release(BG(CurrentStatFile));
874 			}
875 			BG(CurrentStatFile) = zend_string_copy(filename);
876 			memcpy(&BG(ssb), &ssb, sizeof(php_stream_statbuf));
877 		}
878 	} while (0);
879 
880 	stat_sb = &ssb.sb;
881 
882 	if (type >= FS_IS_W && type <= FS_IS_X) {
883 		if(ssb.sb.st_uid==getuid()) {
884 			rmask=S_IRUSR;
885 			wmask=S_IWUSR;
886 			xmask=S_IXUSR;
887 		} else if(ssb.sb.st_gid==getgid()) {
888 			rmask=S_IRGRP;
889 			wmask=S_IWGRP;
890 			xmask=S_IXGRP;
891 		} else {
892 			int   groups, n, i;
893 			gid_t *gids;
894 
895 			groups = getgroups(0, NULL);
896 			if(groups > 0) {
897 				gids=(gid_t *)safe_emalloc(groups, sizeof(gid_t), 0);
898 				n=getgroups(groups, gids);
899 				for(i=0;i<n;i++){
900 					if(ssb.sb.st_gid==gids[i]) {
901 						rmask=S_IRGRP;
902 						wmask=S_IWGRP;
903 						xmask=S_IXGRP;
904 						break;
905 					}
906 				}
907 				efree(gids);
908 			}
909 		}
910 	}
911 
912 	if (IS_ABLE_CHECK(type) && getuid() == 0) {
913 		/* root has special perms on plain_wrapper */
914 		if (wrapper == &php_plain_files_wrapper) {
915 			if (type == FS_IS_X) {
916 				xmask = S_IXROOT;
917 			} else {
918 				RETURN_TRUE;
919 			}
920 		}
921 	}
922 
923 	switch (type) {
924 	case FS_PERMS:
925 	case FS_LPERMS:
926 		RETURN_LONG((zend_long)ssb.sb.st_mode);
927 	case FS_INODE:
928 		RETURN_LONG((zend_long)ssb.sb.st_ino);
929 	case FS_SIZE:
930 		RETURN_LONG((zend_long)ssb.sb.st_size);
931 	case FS_OWNER:
932 		RETURN_LONG((zend_long)ssb.sb.st_uid);
933 	case FS_GROUP:
934 		RETURN_LONG((zend_long)ssb.sb.st_gid);
935 	case FS_ATIME:
936 		RETURN_LONG((zend_long)ssb.sb.st_atime);
937 	case FS_MTIME:
938 		RETURN_LONG((zend_long)ssb.sb.st_mtime);
939 	case FS_CTIME:
940 		RETURN_LONG((zend_long)ssb.sb.st_ctime);
941 	case FS_TYPE:
942 		if (S_ISLNK(ssb.sb.st_mode)) {
943 			RETURN_STRING("link");
944 		}
945 		switch(ssb.sb.st_mode & S_IFMT) {
946 		case S_IFIFO: RETURN_STRING("fifo");
947 		case S_IFCHR: RETURN_STRING("char");
948 		case S_IFDIR: RETURN_STRING("dir");
949 		case S_IFBLK: RETURN_STRING("block");
950 		case S_IFREG: RETURN_STRING("file");
951 #if defined(S_IFSOCK) && !defined(PHP_WIN32)
952 		case S_IFSOCK: RETURN_STRING("socket");
953 #endif
954 		}
955 		php_error_docref(NULL, E_NOTICE, "Unknown file type (%d)", ssb.sb.st_mode&S_IFMT);
956 		RETURN_STRING("unknown");
957 	case FS_IS_W:
958 		RETURN_BOOL((ssb.sb.st_mode & wmask) != 0);
959 	case FS_IS_R:
960 		RETURN_BOOL((ssb.sb.st_mode&rmask)!=0);
961 	case FS_IS_X:
962 		RETURN_BOOL((ssb.sb.st_mode&xmask)!=0);
963 	case FS_IS_FILE:
964 		RETURN_BOOL(S_ISREG(ssb.sb.st_mode));
965 	case FS_IS_DIR:
966 		RETURN_BOOL(S_ISDIR(ssb.sb.st_mode));
967 	case FS_IS_LINK:
968 		RETURN_BOOL(S_ISLNK(ssb.sb.st_mode));
969 	case FS_EXISTS:
970 		RETURN_TRUE; /* the false case was done earlier */
971 	case FS_LSTAT:
972 		/* FALLTHROUGH */
973 	case FS_STAT: {
974 		char *stat_sb_names[] = {
975 			"dev", "ino", "mode", "nlink", "uid", "gid", "rdev",
976 			"size", "atime", "mtime", "ctime", "blksize", "blocks"
977 		};
978 		zval stat_dev, stat_ino, stat_mode, stat_nlink, stat_uid, stat_gid, stat_rdev,
979 			stat_size, stat_atime, stat_mtime, stat_ctime, stat_blksize, stat_blocks;
980 		zval *stat_sb_addresses[] = {
981 			&stat_dev, &stat_ino, &stat_mode, &stat_nlink, &stat_uid, &stat_gid, &stat_rdev,
982 			&stat_size, &stat_atime, &stat_mtime, &stat_ctime, &stat_blksize, &stat_blocks
983 		};
984 		size_t i, size_stat_sb = sizeof(stat_sb_addresses) / sizeof(*stat_sb_addresses);
985 
986 		array_init(return_value);
987 
988 		ZVAL_LONG(&stat_dev, stat_sb->st_dev);
989 		ZVAL_LONG(&stat_ino, stat_sb->st_ino);
990 		ZVAL_LONG(&stat_mode, stat_sb->st_mode);
991 		ZVAL_LONG(&stat_nlink, stat_sb->st_nlink);
992 		ZVAL_LONG(&stat_uid, stat_sb->st_uid);
993 		ZVAL_LONG(&stat_gid, stat_sb->st_gid);
994 #ifdef HAVE_STRUCT_STAT_ST_RDEV
995 		ZVAL_LONG(&stat_rdev, stat_sb->st_rdev);
996 #else
997 		ZVAL_LONG(&stat_rdev, -1);
998 #endif
999 		ZVAL_LONG(&stat_size, stat_sb->st_size);
1000 		ZVAL_LONG(&stat_atime, stat_sb->st_atime);
1001 		ZVAL_LONG(&stat_mtime, stat_sb->st_mtime);
1002 		ZVAL_LONG(&stat_ctime, stat_sb->st_ctime);
1003 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1004 		ZVAL_LONG(&stat_blksize, stat_sb->st_blksize);
1005 #else
1006 		ZVAL_LONG(&stat_blksize,-1);
1007 #endif
1008 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1009 		ZVAL_LONG(&stat_blocks, stat_sb->st_blocks);
1010 #else
1011 		ZVAL_LONG(&stat_blocks,-1);
1012 #endif
1013 		for (i = 0; i < size_stat_sb; i++) {
1014 			/* Store numeric indexes in proper order */
1015 			zend_hash_next_index_insert(Z_ARRVAL_P(return_value), stat_sb_addresses[i]);
1016 		}
1017 
1018 		for (i = 0; i < size_stat_sb; i++) {
1019 			/* Store string indexes referencing the same zval */
1020 			zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[i], strlen(stat_sb_names[i]), stat_sb_addresses[i]);
1021 		}
1022 
1023 		return;
1024 	    }
1025 	}
1026 	php_error_docref(NULL, E_WARNING, "Didn't understand stat call");
1027 	RETURN_FALSE;
1028 }
1029 /* }}} */
1030 
1031 /* another quickie macro to make defining similar functions easier */
1032 /* {{{ FileFunction(name, funcnum) */
1033 #define FileFunction(name, funcnum) \
1034 ZEND_NAMED_FUNCTION(name) { \
1035 	zend_string *filename; \
1036 	\
1037 	ZEND_PARSE_PARAMETERS_START(1, 1) \
1038 		Z_PARAM_STR(filename) \
1039 	ZEND_PARSE_PARAMETERS_END(); \
1040 	\
1041 	php_stat(filename, funcnum, return_value); \
1042 }
1043 /* }}} */
1044 
1045 /* {{{ Get file permissions */
FileFunction(PHP_FN (fileperms),FS_PERMS)1046 FileFunction(PHP_FN(fileperms), FS_PERMS)
1047 /* }}} */
1048 
1049 /* {{{ Get file inode */
1050 FileFunction(PHP_FN(fileinode), FS_INODE)
1051 /* }}} */
1052 
1053 /* {{{ Get file size */
1054 FileFunction(PHP_FN(filesize), FS_SIZE)
1055 /* }}} */
1056 
1057 /* {{{ Get file owner */
1058 FileFunction(PHP_FN(fileowner), FS_OWNER)
1059 /* }}} */
1060 
1061 /* {{{ Get file group */
1062 FileFunction(PHP_FN(filegroup), FS_GROUP)
1063 /* }}} */
1064 
1065 /* {{{ Get last access time of file */
1066 FileFunction(PHP_FN(fileatime), FS_ATIME)
1067 /* }}} */
1068 
1069 /* {{{ Get last modification time of file */
1070 FileFunction(PHP_FN(filemtime), FS_MTIME)
1071 /* }}} */
1072 
1073 /* {{{ Get inode modification time of file */
1074 FileFunction(PHP_FN(filectime), FS_CTIME)
1075 /* }}} */
1076 
1077 /* {{{ Get file type */
1078 FileFunction(PHP_FN(filetype), FS_TYPE)
1079 /* }}} */
1080 
1081 /* {{{ Returns true if file can be written */
1082 FileFunction(PHP_FN(is_writable), FS_IS_W)
1083 /* }}} */
1084 
1085 /* {{{ Returns true if file can be read */
1086 FileFunction(PHP_FN(is_readable), FS_IS_R)
1087 /* }}} */
1088 
1089 /* {{{ Returns true if file is executable */
1090 FileFunction(PHP_FN(is_executable), FS_IS_X)
1091 /* }}} */
1092 
1093 /* {{{ Returns true if file is a regular file */
1094 FileFunction(PHP_FN(is_file), FS_IS_FILE)
1095 /* }}} */
1096 
1097 /* {{{ Returns true if file is directory */
1098 FileFunction(PHP_FN(is_dir), FS_IS_DIR)
1099 /* }}} */
1100 
1101 /* {{{ Returns true if file is symbolic link */
1102 FileFunction(PHP_FN(is_link), FS_IS_LINK)
1103 /* }}} */
1104 
1105 /* {{{ Returns true if filename exists */
1106 FileFunction(PHP_FN(file_exists), FS_EXISTS)
1107 /* }}} */
1108 
1109 /* {{{ Give information about a file or symbolic link */
1110 FileFunction(PHP_FN(lstat), FS_LSTAT)
1111 /* }}} */
1112 
1113 /* {{{ Give information about a file */
1114 FileFunction(PHP_FN(stat), FS_STAT)
1115 /* }}} */
1116 
1117 /* {{{ Get current size of realpath cache */
1118 PHP_FUNCTION(realpath_cache_size)
1119 {
1120 	ZEND_PARSE_PARAMETERS_NONE();
1121 
1122 	RETURN_LONG(realpath_cache_size());
1123 }
1124 
1125 /* {{{ Get current size of realpath cache */
PHP_FUNCTION(realpath_cache_get)1126 PHP_FUNCTION(realpath_cache_get)
1127 {
1128 	realpath_cache_bucket **buckets = realpath_cache_get_buckets(), **end = buckets + realpath_cache_max_buckets();
1129 
1130 	ZEND_PARSE_PARAMETERS_NONE();
1131 
1132 	array_init(return_value);
1133 	while(buckets < end) {
1134 		realpath_cache_bucket *bucket = *buckets;
1135 		while(bucket) {
1136 			zval entry;
1137 
1138 			array_init(&entry);
1139 
1140 			/* bucket->key is unsigned long */
1141 			if (ZEND_LONG_MAX >= bucket->key) {
1142 				add_assoc_long_ex(&entry, "key", sizeof("key") - 1, bucket->key);
1143 			} else {
1144 				add_assoc_double_ex(&entry, "key", sizeof("key") - 1, (double)bucket->key);
1145 			}
1146 			add_assoc_bool_ex(&entry, "is_dir", sizeof("is_dir") - 1, bucket->is_dir);
1147 			add_assoc_stringl_ex(&entry, "realpath", sizeof("realpath") - 1, bucket->realpath, bucket->realpath_len);
1148 			add_assoc_long_ex(&entry, "expires", sizeof("expires") - 1, bucket->expires);
1149 #ifdef PHP_WIN32
1150 			add_assoc_bool_ex(&entry, "is_rvalid", sizeof("is_rvalid") - 1, bucket->is_rvalid);
1151 			add_assoc_bool_ex(&entry, "is_wvalid", sizeof("is_wvalid") - 1, bucket->is_wvalid);
1152 			add_assoc_bool_ex(&entry, "is_readable", sizeof("is_readable") - 1, bucket->is_readable);
1153 			add_assoc_bool_ex(&entry, "is_writable", sizeof("is_writable") - 1, bucket->is_writable);
1154 #endif
1155 			zend_hash_str_update(Z_ARRVAL_P(return_value), bucket->path, bucket->path_len, &entry);
1156 			bucket = bucket->next;
1157 		}
1158 		buckets++;
1159 	}
1160 }
1161