xref: /PHP-8.1/ext/standard/filestat.c (revision 81048b9f)
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 #if HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31 
32 #if HAVE_SYS_PARAM_H
33 # include <sys/param.h>
34 #endif
35 
36 #if 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 #if 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 #if 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 
317 		if (grbuflen < 1) {
318 			return FAILURE;
319 		}
320 
321 		grbuf = emalloc(grbuflen);
322 		if (getgrnam_r(name, &gr, grbuf, grbuflen, &retgrptr) != 0 || retgrptr == NULL) {
323 			efree(grbuf);
324 			return FAILURE;
325 		}
326 		efree(grbuf);
327 		*gid = gr.gr_gid;
328 #else
329 		struct group *gr = getgrnam(name);
330 
331 		if (!gr) {
332 			return FAILURE;
333 		}
334 		*gid = gr->gr_gid;
335 #endif
336 		return SUCCESS;
337 }
338 #endif
339 
php_do_chgrp(INTERNAL_FUNCTION_PARAMETERS,int do_lchgrp)340 static void php_do_chgrp(INTERNAL_FUNCTION_PARAMETERS, int do_lchgrp) /* {{{ */
341 {
342 	char *filename;
343 	size_t filename_len;
344 	zend_string *group_str;
345 	zend_long group_long;
346 #if !defined(WINDOWS)
347 	gid_t gid;
348 	int ret;
349 #endif
350 	php_stream_wrapper *wrapper;
351 
352 	ZEND_PARSE_PARAMETERS_START(2, 2)
353 		Z_PARAM_PATH(filename, filename_len)
354 		Z_PARAM_STR_OR_LONG(group_str, group_long)
355 	ZEND_PARSE_PARAMETERS_END();
356 
357 	wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
358 	if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) {
359 		if(wrapper && wrapper->wops->stream_metadata) {
360 			int option;
361 			void *value;
362 			if (group_str) {
363 				option = PHP_STREAM_META_GROUP_NAME;
364 				value = ZSTR_VAL(group_str);
365 			} else {
366 				option = PHP_STREAM_META_GROUP;
367 				value = &group_long;
368 			}
369 
370 			if(wrapper->wops->stream_metadata(wrapper, filename, option, value, NULL)) {
371 				RETURN_TRUE;
372 			} else {
373 				RETURN_FALSE;
374 			}
375 		} else {
376 #if !defined(WINDOWS)
377 /* On Windows, we expect regular chgrp to fail silently by default */
378 			php_error_docref(NULL, E_WARNING, "Can not call chgrp() for a non-standard stream");
379 #endif
380 			RETURN_FALSE;
381 		}
382 	}
383 
384 #if defined(WINDOWS)
385 	/* We have no native chgrp on Windows, nothing left to do if stream doesn't have own implementation */
386 	RETURN_FALSE;
387 #else
388 	if (group_str) {
389 		if (php_get_gid_by_name(ZSTR_VAL(group_str), &gid) != SUCCESS) {
390 			php_error_docref(NULL, E_WARNING, "Unable to find gid for %s", ZSTR_VAL(group_str));
391 			RETURN_FALSE;
392 		}
393 	} else {
394 		gid = (gid_t) group_long;
395 	}
396 
397 	/* Check the basedir */
398 	if (php_check_open_basedir(filename)) {
399 		RETURN_FALSE;
400 	}
401 
402 	if (do_lchgrp) {
403 #if HAVE_LCHOWN
404 		ret = VCWD_LCHOWN(filename, -1, gid);
405 #endif
406 	} else {
407 		ret = VCWD_CHOWN(filename, -1, gid);
408 	}
409 	if (ret == -1) {
410 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
411 		RETURN_FALSE;
412 	}
413 	RETURN_TRUE;
414 #endif
415 }
416 /* }}} */
417 
418 /* {{{ Change file group */
PHP_FUNCTION(chgrp)419 PHP_FUNCTION(chgrp)
420 {
421 	php_do_chgrp(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
422 }
423 /* }}} */
424 
425 /* {{{ Change symlink group */
426 #if HAVE_LCHOWN
PHP_FUNCTION(lchgrp)427 PHP_FUNCTION(lchgrp)
428 {
429 	php_do_chgrp(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
430 }
431 #endif
432 /* }}} */
433 
434 #ifndef PHP_WIN32
php_get_uid_by_name(const char * name,uid_t * uid)435 PHPAPI uid_t php_get_uid_by_name(const char *name, uid_t *uid)
436 {
437 #if defined(ZTS) && defined(_SC_GETPW_R_SIZE_MAX) && defined(HAVE_GETPWNAM_R)
438 		struct passwd pw;
439 		struct passwd *retpwptr = NULL;
440 		long pwbuflen = sysconf(_SC_GETPW_R_SIZE_MAX);
441 		char *pwbuf;
442 
443 		if (pwbuflen < 1) {
444 			return FAILURE;
445 		}
446 
447 		pwbuf = emalloc(pwbuflen);
448 		if (getpwnam_r(name, &pw, pwbuf, pwbuflen, &retpwptr) != 0 || retpwptr == NULL) {
449 			efree(pwbuf);
450 			return FAILURE;
451 		}
452 		efree(pwbuf);
453 		*uid = pw.pw_uid;
454 #else
455 		struct passwd *pw = getpwnam(name);
456 
457 		if (!pw) {
458 			return FAILURE;
459 		}
460 		*uid = pw->pw_uid;
461 #endif
462 		return SUCCESS;
463 }
464 #endif
465 
php_do_chown(INTERNAL_FUNCTION_PARAMETERS,int do_lchown)466 static void php_do_chown(INTERNAL_FUNCTION_PARAMETERS, int do_lchown) /* {{{ */
467 {
468 	char *filename;
469 	size_t filename_len;
470 	zend_string *user_str;
471 	zend_long user_long;
472 #if !defined(WINDOWS)
473 	uid_t uid;
474 	int ret;
475 #endif
476 	php_stream_wrapper *wrapper;
477 
478 	ZEND_PARSE_PARAMETERS_START(2, 2)
479 		Z_PARAM_PATH(filename, filename_len)
480 		Z_PARAM_STR_OR_LONG(user_str, user_long)
481 	ZEND_PARSE_PARAMETERS_END();
482 
483 	wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
484 	if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) {
485 		if(wrapper && wrapper->wops->stream_metadata) {
486 			int option;
487 			void *value;
488 			if (user_str) {
489 				option = PHP_STREAM_META_OWNER_NAME;
490 				value = ZSTR_VAL(user_str);
491 			} else {
492 				option = PHP_STREAM_META_OWNER;
493 				value = &user_long;
494 			}
495 
496 			if(wrapper->wops->stream_metadata(wrapper, filename, option, value, NULL)) {
497 				RETURN_TRUE;
498 			} else {
499 				RETURN_FALSE;
500 			}
501 		} else {
502 #if !defined(WINDOWS)
503 /* On Windows, we expect regular chown to fail silently by default */
504 			php_error_docref(NULL, E_WARNING, "Can not call chown() for a non-standard stream");
505 #endif
506 			RETURN_FALSE;
507 		}
508 	}
509 
510 #if defined(WINDOWS)
511 	/* We have no native chown on Windows, nothing left to do if stream doesn't have own implementation */
512 	RETURN_FALSE;
513 #else
514 
515 	if (user_str) {
516 		if (php_get_uid_by_name(ZSTR_VAL(user_str), &uid) != SUCCESS) {
517 			php_error_docref(NULL, E_WARNING, "Unable to find uid for %s", ZSTR_VAL(user_str));
518 			RETURN_FALSE;
519 		}
520 	} else {
521 		uid = (uid_t) user_long;
522 	}
523 
524 	/* Check the basedir */
525 	if (php_check_open_basedir(filename)) {
526 		RETURN_FALSE;
527 	}
528 
529 	if (do_lchown) {
530 #if HAVE_LCHOWN
531 		ret = VCWD_LCHOWN(filename, uid, -1);
532 #endif
533 	} else {
534 		ret = VCWD_CHOWN(filename, uid, -1);
535 	}
536 	if (ret == -1) {
537 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
538 		RETURN_FALSE;
539 	}
540 	RETURN_TRUE;
541 #endif
542 }
543 /* }}} */
544 
545 
546 /* {{{ Change file owner */
PHP_FUNCTION(chown)547 PHP_FUNCTION(chown)
548 {
549 	php_do_chown(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
550 }
551 /* }}} */
552 
553 /* {{{ Change file owner */
554 #if HAVE_LCHOWN
PHP_FUNCTION(lchown)555 PHP_FUNCTION(lchown)
556 {
557 	RETVAL_TRUE;
558 	php_do_chown(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
559 }
560 #endif
561 /* }}} */
562 
563 /* {{{ Change file mode */
PHP_FUNCTION(chmod)564 PHP_FUNCTION(chmod)
565 {
566 	char *filename;
567 	size_t filename_len;
568 	zend_long mode;
569 	int ret;
570 	mode_t imode;
571 	php_stream_wrapper *wrapper;
572 
573 	ZEND_PARSE_PARAMETERS_START(2, 2)
574 		Z_PARAM_PATH(filename, filename_len)
575 		Z_PARAM_LONG(mode)
576 	ZEND_PARSE_PARAMETERS_END();
577 
578 	wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
579 	if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) {
580 		if(wrapper && wrapper->wops->stream_metadata) {
581 			if(wrapper->wops->stream_metadata(wrapper, filename, PHP_STREAM_META_ACCESS, &mode, NULL)) {
582 				RETURN_TRUE;
583 			} else {
584 				RETURN_FALSE;
585 			}
586 		} else {
587 			php_error_docref(NULL, E_WARNING, "Can not call chmod() for a non-standard stream");
588 			RETURN_FALSE;
589 		}
590 	}
591 
592 	/* Check the basedir */
593 	if (php_check_open_basedir(filename)) {
594 		RETURN_FALSE;
595 	}
596 
597 	imode = (mode_t) mode;
598 
599 	ret = VCWD_CHMOD(filename, imode);
600 	if (ret == -1) {
601 		php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
602 		RETURN_FALSE;
603 	}
604 	RETURN_TRUE;
605 }
606 /* }}} */
607 
608 #if HAVE_UTIME
609 /* {{{ Set modification time of file */
PHP_FUNCTION(touch)610 PHP_FUNCTION(touch)
611 {
612 	char *filename;
613 	size_t filename_len;
614 	zend_long filetime = 0, fileatime = 0;
615 	bool filetime_is_null = 1, fileatime_is_null = 1;
616 	int ret;
617 	FILE *file;
618 	struct utimbuf newtimebuf;
619 	struct utimbuf *newtime = &newtimebuf;
620 	php_stream_wrapper *wrapper;
621 
622 	ZEND_PARSE_PARAMETERS_START(1, 3)
623 		Z_PARAM_PATH(filename, filename_len)
624 		Z_PARAM_OPTIONAL
625 		Z_PARAM_LONG_OR_NULL(filetime, filetime_is_null)
626 		Z_PARAM_LONG_OR_NULL(fileatime, fileatime_is_null)
627 	ZEND_PARSE_PARAMETERS_END();
628 
629 	if (!filename_len) {
630 		RETURN_FALSE;
631 	}
632 
633 	if (filetime_is_null && fileatime_is_null) {
634 		newtime = NULL;
635 	} else if (!filetime_is_null && fileatime_is_null) {
636 		newtime->modtime = newtime->actime = filetime;
637 	} else if (filetime_is_null && !fileatime_is_null) {
638 		zend_argument_value_error(2, "cannot be null when argument #3 ($atime) is an integer");
639 		RETURN_THROWS();
640 	} else {
641 		newtime->modtime = filetime;
642 		newtime->actime = fileatime;
643 	}
644 
645 	wrapper = php_stream_locate_url_wrapper(filename, NULL, 0);
646 	if(wrapper != &php_plain_files_wrapper || strncasecmp("file://", filename, 7) == 0) {
647 		if(wrapper && wrapper->wops->stream_metadata) {
648 			if(wrapper->wops->stream_metadata(wrapper, filename, PHP_STREAM_META_TOUCH, newtime, NULL)) {
649 				RETURN_TRUE;
650 			} else {
651 				RETURN_FALSE;
652 			}
653 		} else {
654 			php_stream *stream;
655 			if(!filetime_is_null || !fileatime_is_null) {
656 				php_error_docref(NULL, E_WARNING, "Can not call touch() for a non-standard stream");
657 				RETURN_FALSE;
658 			}
659 			stream = php_stream_open_wrapper_ex(filename, "c", REPORT_ERRORS, NULL, NULL);
660 			if(stream != NULL) {
661 				php_stream_close(stream);
662 				RETURN_TRUE;
663 			} else {
664 				RETURN_FALSE;
665 			}
666 		}
667 	}
668 
669 	/* Check the basedir */
670 	if (php_check_open_basedir(filename)) {
671 		RETURN_FALSE;
672 	}
673 
674 	/* create the file if it doesn't exist already */
675 	if (VCWD_ACCESS(filename, F_OK) != 0) {
676 		file = VCWD_FOPEN(filename, "w");
677 		if (file == NULL) {
678 			php_error_docref(NULL, E_WARNING, "Unable to create file %s because %s", filename, strerror(errno));
679 			RETURN_FALSE;
680 		}
681 		fclose(file);
682 	}
683 
684 	ret = VCWD_UTIME(filename, newtime);
685 	if (ret == -1) {
686 		php_error_docref(NULL, E_WARNING, "Utime failed: %s", strerror(errno));
687 		RETURN_FALSE;
688 	}
689 	RETURN_TRUE;
690 }
691 /* }}} */
692 #endif
693 
694 /* {{{ php_clear_stat_cache() */
php_clear_stat_cache(bool clear_realpath_cache,const char * filename,size_t filename_len)695 PHPAPI void php_clear_stat_cache(bool clear_realpath_cache, const char *filename, size_t filename_len)
696 {
697 	/* always clear CurrentStatFile and CurrentLStatFile even if filename is not NULL
698 	 * as it may contain outdated data (e.g. "nlink" for a directory when deleting a file
699 	 * in this directory, as shown by lstat_stat_variation9.phpt) */
700 	if (BG(CurrentStatFile)) {
701 		zend_string_release(BG(CurrentStatFile));
702 		BG(CurrentStatFile) = NULL;
703 	}
704 	if (BG(CurrentLStatFile)) {
705 		zend_string_release(BG(CurrentLStatFile));
706 		BG(CurrentLStatFile) = NULL;
707 	}
708 	if (clear_realpath_cache) {
709 		if (filename != NULL) {
710 			realpath_cache_del(filename, filename_len);
711 		} else {
712 			realpath_cache_clean();
713 		}
714 	}
715 }
716 /* }}} */
717 
718 /* {{{ Clear file stat cache */
PHP_FUNCTION(clearstatcache)719 PHP_FUNCTION(clearstatcache)
720 {
721 	bool  clear_realpath_cache = 0;
722 	char      *filename             = NULL;
723 	size_t     filename_len         = 0;
724 
725 	ZEND_PARSE_PARAMETERS_START(0, 2)
726 		Z_PARAM_OPTIONAL
727 		Z_PARAM_BOOL(clear_realpath_cache)
728 		Z_PARAM_PATH(filename, filename_len)
729 	ZEND_PARSE_PARAMETERS_END();
730 
731 	php_clear_stat_cache(clear_realpath_cache, filename, filename_len);
732 }
733 /* }}} */
734 
735 #define IS_LINK_OPERATION(__t) ((__t) == FS_TYPE || (__t) == FS_IS_LINK || (__t) == FS_LSTAT || (__t) == FS_LPERMS)
736 #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)
737 #define IS_ABLE_CHECK(__t) ((__t) == FS_IS_R || (__t) == FS_IS_W || (__t) == FS_IS_X)
738 #define IS_ACCESS_CHECK(__t) (IS_ABLE_CHECK(type) || (__t) == FS_EXISTS)
739 
740 /* {{{ php_stat */
php_stat(zend_string * filename,int type,zval * return_value)741 PHPAPI void php_stat(zend_string *filename, int type, zval *return_value)
742 {
743 	zend_stat_t *stat_sb;
744 	php_stream_statbuf ssb;
745 	int flags = 0, rmask=S_IROTH, wmask=S_IWOTH, xmask=S_IXOTH; /* access rights defaults to other */
746 	const char *local = NULL;
747 	php_stream_wrapper *wrapper = NULL;
748 
749 	if (IS_ACCESS_CHECK(type)) {
750 		if (!ZSTR_LEN(filename) || CHECK_NULL_PATH(ZSTR_VAL(filename), ZSTR_LEN(filename))) {
751 			if (ZSTR_LEN(filename) && !IS_EXISTS_CHECK(type)) {
752 				php_error_docref(NULL, E_WARNING, "Filename contains null byte");
753 			}
754 			RETURN_FALSE;
755 		}
756 
757 		if ((wrapper = php_stream_locate_url_wrapper(ZSTR_VAL(filename), &local, 0)) == &php_plain_files_wrapper
758 		 && php_check_open_basedir(local)) {
759 			RETURN_FALSE;
760 		}
761 
762 		if (wrapper == &php_plain_files_wrapper) {
763 
764 			switch (type) {
765 #ifdef F_OK
766 				case FS_EXISTS:
767 					RETURN_BOOL(VCWD_ACCESS(local, F_OK) == 0);
768 					break;
769 #endif
770 #ifdef W_OK
771 				case FS_IS_W:
772 					RETURN_BOOL(VCWD_ACCESS(local, W_OK) == 0);
773 					break;
774 #endif
775 #ifdef R_OK
776 				case FS_IS_R:
777 					RETURN_BOOL(VCWD_ACCESS(local, R_OK) == 0);
778 					break;
779 #endif
780 #ifdef X_OK
781 				case FS_IS_X:
782 					RETURN_BOOL(VCWD_ACCESS(local, X_OK) == 0);
783 					break;
784 #endif
785 			}
786 		}
787 	}
788 
789 	if (IS_LINK_OPERATION(type)) {
790 		flags |= PHP_STREAM_URL_STAT_LINK;
791 	}
792 	if (IS_EXISTS_CHECK(type)) {
793 		flags |= PHP_STREAM_URL_STAT_QUIET;
794 	}
795 
796 	do {
797 		/* Try to hit the cache first */
798 		if (flags & PHP_STREAM_URL_STAT_LINK) {
799 			if (filename == BG(CurrentLStatFile)
800 			 || (BG(CurrentLStatFile)
801 			  && zend_string_equal_content(filename, BG(CurrentLStatFile)))) {
802 				memcpy(&ssb, &BG(lssb), sizeof(php_stream_statbuf));
803 				break;
804 			}
805 		} else {
806 			if (filename == BG(CurrentStatFile)
807 			 || (BG(CurrentStatFile)
808 			  && zend_string_equal_content(filename, BG(CurrentStatFile)))) {
809 				memcpy(&ssb, &BG(ssb), sizeof(php_stream_statbuf));
810 				break;
811 			}
812 		}
813 
814 		if (!wrapper) {
815 			if (!ZSTR_LEN(filename) || CHECK_NULL_PATH(ZSTR_VAL(filename), ZSTR_LEN(filename))) {
816 				if (ZSTR_LEN(filename) && !IS_EXISTS_CHECK(type)) {
817 					php_error_docref(NULL, E_WARNING, "Filename contains null byte");
818 				}
819 				RETURN_FALSE;
820 			}
821 
822 			if ((wrapper = php_stream_locate_url_wrapper(ZSTR_VAL(filename), &local, 0)) == &php_plain_files_wrapper
823 			 && php_check_open_basedir(local)) {
824 				RETURN_FALSE;
825 			}
826 		}
827 
828 		if (!wrapper
829 		 || !wrapper->wops->url_stat
830 		 || wrapper->wops->url_stat(wrapper, local, flags | PHP_STREAM_URL_STAT_IGNORE_OPEN_BASEDIR, &ssb, NULL)) {
831 			/* Error Occurred */
832 			if (!IS_EXISTS_CHECK(type)) {
833 				php_error_docref(NULL, E_WARNING, "%sstat failed for %s", IS_LINK_OPERATION(type) ? "L" : "", ZSTR_VAL(filename));
834 			}
835 			RETURN_FALSE;
836 		}
837 
838 		/* Drop into cache */
839 		if (flags & PHP_STREAM_URL_STAT_LINK) {
840 			if (BG(CurrentLStatFile)) {
841 				zend_string_release(BG(CurrentLStatFile));
842 			}
843 			BG(CurrentLStatFile) = zend_string_copy(filename);
844 			memcpy(&BG(lssb), &ssb, sizeof(php_stream_statbuf));
845 		}
846 		if (!(flags & PHP_STREAM_URL_STAT_LINK)
847 		 || !S_ISLNK(ssb.sb.st_mode)) {
848 			if (BG(CurrentStatFile)) {
849 				zend_string_release(BG(CurrentStatFile));
850 			}
851 			BG(CurrentStatFile) = zend_string_copy(filename);
852 			memcpy(&BG(ssb), &ssb, sizeof(php_stream_statbuf));
853 		}
854 	} while (0);
855 
856 	stat_sb = &ssb.sb;
857 
858 	if (type >= FS_IS_W && type <= FS_IS_X) {
859 		if(ssb.sb.st_uid==getuid()) {
860 			rmask=S_IRUSR;
861 			wmask=S_IWUSR;
862 			xmask=S_IXUSR;
863 		} else if(ssb.sb.st_gid==getgid()) {
864 			rmask=S_IRGRP;
865 			wmask=S_IWGRP;
866 			xmask=S_IXGRP;
867 		} else {
868 			int   groups, n, i;
869 			gid_t *gids;
870 
871 			groups = getgroups(0, NULL);
872 			if(groups > 0) {
873 				gids=(gid_t *)safe_emalloc(groups, sizeof(gid_t), 0);
874 				n=getgroups(groups, gids);
875 				for(i=0;i<n;i++){
876 					if(ssb.sb.st_gid==gids[i]) {
877 						rmask=S_IRGRP;
878 						wmask=S_IWGRP;
879 						xmask=S_IXGRP;
880 						break;
881 					}
882 				}
883 				efree(gids);
884 			}
885 		}
886 	}
887 
888 	if (IS_ABLE_CHECK(type) && getuid() == 0) {
889 		/* root has special perms on plain_wrapper */
890 		if (wrapper == &php_plain_files_wrapper) {
891 			if (type == FS_IS_X) {
892 				xmask = S_IXROOT;
893 			} else {
894 				RETURN_TRUE;
895 			}
896 		}
897 	}
898 
899 	switch (type) {
900 	case FS_PERMS:
901 	case FS_LPERMS:
902 		RETURN_LONG((zend_long)ssb.sb.st_mode);
903 	case FS_INODE:
904 		RETURN_LONG((zend_long)ssb.sb.st_ino);
905 	case FS_SIZE:
906 		RETURN_LONG((zend_long)ssb.sb.st_size);
907 	case FS_OWNER:
908 		RETURN_LONG((zend_long)ssb.sb.st_uid);
909 	case FS_GROUP:
910 		RETURN_LONG((zend_long)ssb.sb.st_gid);
911 	case FS_ATIME:
912 		RETURN_LONG((zend_long)ssb.sb.st_atime);
913 	case FS_MTIME:
914 		RETURN_LONG((zend_long)ssb.sb.st_mtime);
915 	case FS_CTIME:
916 		RETURN_LONG((zend_long)ssb.sb.st_ctime);
917 	case FS_TYPE:
918 		if (S_ISLNK(ssb.sb.st_mode)) {
919 			RETURN_STRING("link");
920 		}
921 		switch(ssb.sb.st_mode & S_IFMT) {
922 		case S_IFIFO: RETURN_STRING("fifo");
923 		case S_IFCHR: RETURN_STRING("char");
924 		case S_IFDIR: RETURN_STRING("dir");
925 		case S_IFBLK: RETURN_STRING("block");
926 		case S_IFREG: RETURN_STRING("file");
927 #if defined(S_IFSOCK) && !defined(PHP_WIN32)
928 		case S_IFSOCK: RETURN_STRING("socket");
929 #endif
930 		}
931 		php_error_docref(NULL, E_NOTICE, "Unknown file type (%d)", ssb.sb.st_mode&S_IFMT);
932 		RETURN_STRING("unknown");
933 	case FS_IS_W:
934 		RETURN_BOOL((ssb.sb.st_mode & wmask) != 0);
935 	case FS_IS_R:
936 		RETURN_BOOL((ssb.sb.st_mode&rmask)!=0);
937 	case FS_IS_X:
938 		RETURN_BOOL((ssb.sb.st_mode&xmask)!=0);
939 	case FS_IS_FILE:
940 		RETURN_BOOL(S_ISREG(ssb.sb.st_mode));
941 	case FS_IS_DIR:
942 		RETURN_BOOL(S_ISDIR(ssb.sb.st_mode));
943 	case FS_IS_LINK:
944 		RETURN_BOOL(S_ISLNK(ssb.sb.st_mode));
945 	case FS_EXISTS:
946 		RETURN_TRUE; /* the false case was done earlier */
947 	case FS_LSTAT:
948 		/* FALLTHROUGH */
949 	case FS_STAT: {
950 		char *stat_sb_names[] = {
951 			"dev", "ino", "mode", "nlink", "uid", "gid", "rdev",
952 			"size", "atime", "mtime", "ctime", "blksize", "blocks"
953 		};
954 		zval stat_dev, stat_ino, stat_mode, stat_nlink, stat_uid, stat_gid, stat_rdev,
955 			stat_size, stat_atime, stat_mtime, stat_ctime, stat_blksize, stat_blocks;
956 		zval *stat_sb_addresses[] = {
957 			&stat_dev, &stat_ino, &stat_mode, &stat_nlink, &stat_uid, &stat_gid, &stat_rdev,
958 			&stat_size, &stat_atime, &stat_mtime, &stat_ctime, &stat_blksize, &stat_blocks
959 		};
960 		size_t i, size_stat_sb = sizeof(stat_sb_addresses) / sizeof(*stat_sb_addresses);
961 
962 		array_init(return_value);
963 
964 		ZVAL_LONG(&stat_dev, stat_sb->st_dev);
965 		ZVAL_LONG(&stat_ino, stat_sb->st_ino);
966 		ZVAL_LONG(&stat_mode, stat_sb->st_mode);
967 		ZVAL_LONG(&stat_nlink, stat_sb->st_nlink);
968 		ZVAL_LONG(&stat_uid, stat_sb->st_uid);
969 		ZVAL_LONG(&stat_gid, stat_sb->st_gid);
970 #ifdef HAVE_STRUCT_STAT_ST_RDEV
971 		ZVAL_LONG(&stat_rdev, stat_sb->st_rdev);
972 #else
973 		ZVAL_LONG(&stat_rdev, -1);
974 #endif
975 		ZVAL_LONG(&stat_size, stat_sb->st_size);
976 		ZVAL_LONG(&stat_atime, stat_sb->st_atime);
977 		ZVAL_LONG(&stat_mtime, stat_sb->st_mtime);
978 		ZVAL_LONG(&stat_ctime, stat_sb->st_ctime);
979 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
980 		ZVAL_LONG(&stat_blksize, stat_sb->st_blksize);
981 #else
982 		ZVAL_LONG(&stat_blksize,-1);
983 #endif
984 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
985 		ZVAL_LONG(&stat_blocks, stat_sb->st_blocks);
986 #else
987 		ZVAL_LONG(&stat_blocks,-1);
988 #endif
989 		for (i = 0; i < size_stat_sb; i++) {
990 			/* Store numeric indexes in proper order */
991 			zend_hash_next_index_insert(Z_ARRVAL_P(return_value), stat_sb_addresses[i]);
992 		}
993 
994 		for (i = 0; i < size_stat_sb; i++) {
995 			/* Store string indexes referencing the same zval */
996 			zend_hash_str_add_new(Z_ARRVAL_P(return_value), stat_sb_names[i], strlen(stat_sb_names[i]), stat_sb_addresses[i]);
997 		}
998 
999 		return;
1000 	    }
1001 	}
1002 	php_error_docref(NULL, E_WARNING, "Didn't understand stat call");
1003 	RETURN_FALSE;
1004 }
1005 /* }}} */
1006 
1007 /* another quickie macro to make defining similar functions easier */
1008 /* {{{ FileFunction(name, funcnum) */
1009 #define FileFunction(name, funcnum) \
1010 ZEND_NAMED_FUNCTION(name) { \
1011 	zend_string *filename; \
1012 	\
1013 	ZEND_PARSE_PARAMETERS_START(1, 1) \
1014 		Z_PARAM_STR(filename) \
1015 	ZEND_PARSE_PARAMETERS_END(); \
1016 	\
1017 	php_stat(filename, funcnum, return_value); \
1018 }
1019 /* }}} */
1020 
1021 /* {{{ Get file permissions */
FileFunction(PHP_FN (fileperms),FS_PERMS)1022 FileFunction(PHP_FN(fileperms), FS_PERMS)
1023 /* }}} */
1024 
1025 /* {{{ Get file inode */
1026 FileFunction(PHP_FN(fileinode), FS_INODE)
1027 /* }}} */
1028 
1029 /* {{{ Get file size */
1030 FileFunction(PHP_FN(filesize), FS_SIZE)
1031 /* }}} */
1032 
1033 /* {{{ Get file owner */
1034 FileFunction(PHP_FN(fileowner), FS_OWNER)
1035 /* }}} */
1036 
1037 /* {{{ Get file group */
1038 FileFunction(PHP_FN(filegroup), FS_GROUP)
1039 /* }}} */
1040 
1041 /* {{{ Get last access time of file */
1042 FileFunction(PHP_FN(fileatime), FS_ATIME)
1043 /* }}} */
1044 
1045 /* {{{ Get last modification time of file */
1046 FileFunction(PHP_FN(filemtime), FS_MTIME)
1047 /* }}} */
1048 
1049 /* {{{ Get inode modification time of file */
1050 FileFunction(PHP_FN(filectime), FS_CTIME)
1051 /* }}} */
1052 
1053 /* {{{ Get file type */
1054 FileFunction(PHP_FN(filetype), FS_TYPE)
1055 /* }}} */
1056 
1057 /* {{{ Returns true if file can be written */
1058 FileFunction(PHP_FN(is_writable), FS_IS_W)
1059 /* }}} */
1060 
1061 /* {{{ Returns true if file can be read */
1062 FileFunction(PHP_FN(is_readable), FS_IS_R)
1063 /* }}} */
1064 
1065 /* {{{ Returns true if file is executable */
1066 FileFunction(PHP_FN(is_executable), FS_IS_X)
1067 /* }}} */
1068 
1069 /* {{{ Returns true if file is a regular file */
1070 FileFunction(PHP_FN(is_file), FS_IS_FILE)
1071 /* }}} */
1072 
1073 /* {{{ Returns true if file is directory */
1074 FileFunction(PHP_FN(is_dir), FS_IS_DIR)
1075 /* }}} */
1076 
1077 /* {{{ Returns true if file is symbolic link */
1078 FileFunction(PHP_FN(is_link), FS_IS_LINK)
1079 /* }}} */
1080 
1081 /* {{{ Returns true if filename exists */
1082 FileFunction(PHP_FN(file_exists), FS_EXISTS)
1083 /* }}} */
1084 
1085 /* {{{ Give information about a file or symbolic link */
1086 FileFunction(PHP_FN(lstat), FS_LSTAT)
1087 /* }}} */
1088 
1089 /* {{{ Give information about a file */
1090 FileFunction(PHP_FN(stat), FS_STAT)
1091 /* }}} */
1092 
1093 /* {{{ Get current size of realpath cache */
1094 PHP_FUNCTION(realpath_cache_size)
1095 {
1096 	ZEND_PARSE_PARAMETERS_NONE();
1097 
1098 	RETURN_LONG(realpath_cache_size());
1099 }
1100 
1101 /* {{{ Get current size of realpath cache */
PHP_FUNCTION(realpath_cache_get)1102 PHP_FUNCTION(realpath_cache_get)
1103 {
1104 	realpath_cache_bucket **buckets = realpath_cache_get_buckets(), **end = buckets + realpath_cache_max_buckets();
1105 
1106 	ZEND_PARSE_PARAMETERS_NONE();
1107 
1108 	array_init(return_value);
1109 	while(buckets < end) {
1110 		realpath_cache_bucket *bucket = *buckets;
1111 		while(bucket) {
1112 			zval entry;
1113 
1114 			array_init(&entry);
1115 
1116 			/* bucket->key is unsigned long */
1117 			if (ZEND_LONG_MAX >= bucket->key) {
1118 				add_assoc_long_ex(&entry, "key", sizeof("key") - 1, bucket->key);
1119 			} else {
1120 				add_assoc_double_ex(&entry, "key", sizeof("key") - 1, (double)bucket->key);
1121 			}
1122 			add_assoc_bool_ex(&entry, "is_dir", sizeof("is_dir") - 1, bucket->is_dir);
1123 			add_assoc_stringl_ex(&entry, "realpath", sizeof("realpath") - 1, bucket->realpath, bucket->realpath_len);
1124 			add_assoc_long_ex(&entry, "expires", sizeof("expires") - 1, bucket->expires);
1125 #ifdef PHP_WIN32
1126 			add_assoc_bool_ex(&entry, "is_rvalid", sizeof("is_rvalid") - 1, bucket->is_rvalid);
1127 			add_assoc_bool_ex(&entry, "is_wvalid", sizeof("is_wvalid") - 1, bucket->is_wvalid);
1128 			add_assoc_bool_ex(&entry, "is_readable", sizeof("is_readable") - 1, bucket->is_readable);
1129 			add_assoc_bool_ex(&entry, "is_writable", sizeof("is_writable") - 1, bucket->is_writable);
1130 #endif
1131 			zend_hash_str_update(Z_ARRVAL_P(return_value), bucket->path, bucket->path_len, &entry);
1132 			bucket = bucket->next;
1133 		}
1134 		buckets++;
1135 	}
1136 }
1137