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