xref: /php-src/main/fopen_wrappers.c (revision 127ad707)
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    | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca>                       |
14    |          Jim Winstead <jimw@php.net>                                 |
15    +----------------------------------------------------------------------+
16  */
17 
18 /* {{{ includes */
19 #include "php.h"
20 #include "php_globals.h"
21 #include "SAPI.h"
22 
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <errno.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <fcntl.h>
29 
30 #ifdef PHP_WIN32
31 #define O_RDONLY _O_RDONLY
32 #include "win32/param.h"
33 #else
34 #include <sys/param.h>
35 #endif
36 
37 #include "ext/standard/head.h"
38 #include "ext/standard/php_standard.h"
39 #include "zend_compile.h"
40 #include "php_network.h"
41 #include "zend_smart_str.h"
42 
43 #if HAVE_PWD_H
44 #include <pwd.h>
45 #endif
46 
47 #include <sys/types.h>
48 #if HAVE_SYS_SOCKET_H
49 #include <sys/socket.h>
50 #endif
51 
52 #ifdef PHP_WIN32
53 #include <winsock2.h>
54 #else
55 #include <netinet/in.h>
56 #include <netdb.h>
57 #if HAVE_ARPA_INET_H
58 #include <arpa/inet.h>
59 #endif
60 #endif
61 
62 #if defined(PHP_WIN32) || defined(__riscos__)
63 #undef AF_UNIX
64 #endif
65 
66 #if defined(AF_UNIX)
67 #include <sys/un.h>
68 #endif
69 /* }}} */
70 
71 /* {{{ OnUpdateBaseDir
72 Allows any change to open_basedir setting in during Startup and Shutdown events,
73 or a tightening during activation/runtime/deactivation */
ZEND_INI_MH(OnUpdateBaseDir)74 PHPAPI ZEND_INI_MH(OnUpdateBaseDir)
75 {
76 	char **p = (char **) ZEND_INI_GET_ADDR();
77 	char *pathbuf, *ptr, *end;
78 
79 	if (stage == PHP_INI_STAGE_STARTUP || stage == PHP_INI_STAGE_SHUTDOWN || stage == PHP_INI_STAGE_ACTIVATE || stage == PHP_INI_STAGE_DEACTIVATE) {
80 		if (PG(open_basedir_modified)) {
81 			efree(*p);
82 		}
83 		/* We're in a PHP_INI_SYSTEM context, no restrictions */
84 		*p = new_value ? ZSTR_VAL(new_value) : NULL;
85 		PG(open_basedir_modified) = false;
86 		return SUCCESS;
87 	}
88 
89 	/* Shortcut: When we have a open_basedir and someone tries to unset, we know it'll fail */
90 	if (!new_value || !*ZSTR_VAL(new_value)) {
91 		return FAILURE;
92 	}
93 
94 	/* Is the proposed open_basedir at least as restrictive as the current setting? */
95 	smart_str buf = {0};
96 	ptr = pathbuf = estrdup(ZSTR_VAL(new_value));
97 	while (ptr && *ptr) {
98 		end = strchr(ptr, DEFAULT_DIR_SEPARATOR);
99 		if (end != NULL) {
100 			*end = '\0';
101 			end++;
102 		}
103 		char resolved_name[MAXPATHLEN + 1];
104 		if (expand_filepath(ptr, resolved_name) == NULL) {
105 			efree(pathbuf);
106 			smart_str_free(&buf);
107 			return FAILURE;
108 		}
109 		if (php_check_open_basedir_ex(resolved_name, 0) != 0) {
110 			/* At least one portion of this open_basedir is less restrictive than the prior one, FAIL */
111 			efree(pathbuf);
112 			smart_str_free(&buf);
113 			return FAILURE;
114 		}
115 		if (smart_str_get_len(&buf) != 0) {
116 			smart_str_appendc(&buf, DEFAULT_DIR_SEPARATOR);
117 		}
118 		smart_str_appends(&buf, resolved_name);
119 		ptr = end;
120 	}
121 	efree(pathbuf);
122 
123 	/* Everything checks out, set it */
124 	zend_string *tmp = smart_str_extract(&buf);
125 	char *result = estrdup(ZSTR_VAL(tmp));
126 	if (PG(open_basedir_modified)) {
127 		efree(*p);
128 	}
129 	*p = result;
130 	PG(open_basedir_modified) = true;
131 	zend_string_release(tmp);
132 
133 	return SUCCESS;
134 }
135 /* }}} */
136 
137 /* {{{ php_check_specific_open_basedir
138 	When open_basedir is not NULL, check if the given filename is located in
139 	open_basedir. Returns -1 if error or not in the open_basedir, else 0.
140 	When open_basedir is NULL, always return 0.
141 */
php_check_specific_open_basedir(const char * basedir,const char * path)142 PHPAPI int php_check_specific_open_basedir(const char *basedir, const char *path)
143 {
144 	char resolved_name[MAXPATHLEN + 1];
145 	char resolved_basedir[MAXPATHLEN + 1];
146 	char local_open_basedir[MAXPATHLEN];
147 	char path_tmp[MAXPATHLEN + 1];
148 	char *path_file;
149 	size_t resolved_basedir_len;
150 	size_t resolved_name_len;
151 	size_t path_len;
152 	int nesting_level = 0;
153 
154 	/* Special case basedir==".": Use script-directory */
155 	if (strcmp(basedir, ".") || !VCWD_GETCWD(local_open_basedir, MAXPATHLEN)) {
156 		/* Else use the unmodified path */
157 		strlcpy(local_open_basedir, basedir, sizeof(local_open_basedir));
158 	}
159 
160 	path_len = strlen(path);
161 	if (path_len > (MAXPATHLEN - 1)) {
162 		/* empty and too long paths are invalid */
163 		return -1;
164 	}
165 
166 	/* normalize and expand path */
167 	if (expand_filepath(path, resolved_name) == NULL) {
168 		return -1;
169 	}
170 
171 	path_len = strlen(resolved_name);
172 	memcpy(path_tmp, resolved_name, path_len + 1); /* safe */
173 
174 	while (VCWD_REALPATH(path_tmp, resolved_name) == NULL) {
175 #if defined(PHP_WIN32) || defined(HAVE_SYMLINK)
176 		if (nesting_level == 0) {
177 			ssize_t ret;
178 			char buf[MAXPATHLEN];
179 
180 			ret = php_sys_readlink(path_tmp, buf, MAXPATHLEN - 1);
181 			if (ret == -1) {
182 				/* not a broken symlink, move along.. */
183 			} else {
184 				/* put the real path into the path buffer */
185 				memcpy(path_tmp, buf, ret);
186 				path_tmp[ret] = '\0';
187 			}
188 		}
189 #endif
190 
191 #ifdef PHP_WIN32
192 		path_file = strrchr(path_tmp, DEFAULT_SLASH);
193 		if (!path_file) {
194 			path_file = strrchr(path_tmp, '/');
195 		}
196 #else
197 		path_file = strrchr(path_tmp, DEFAULT_SLASH);
198 #endif
199 		if (!path_file) {
200 			/* none of the path components exist. definitely not in open_basedir.. */
201 			return -1;
202 		} else {
203 			path_len = path_file - path_tmp + 1;
204 #ifdef PHP_WIN32
205 			if (path_len > 1 && path_tmp[path_len - 2] == ':') {
206 				if (path_len != 3) {
207 					return -1;
208 				}
209 				/* this is c:\ */
210 				path_tmp[path_len] = '\0';
211 			} else {
212 				path_tmp[path_len - 1] = '\0';
213 			}
214 #else
215 			path_tmp[path_len - 1] = '\0';
216 #endif
217 		}
218 		if (*path_tmp == '\0') {
219 			/* Do not pass an empty string to realpath(), as this will resolve to CWD. */
220 			break;
221 		}
222 		nesting_level++;
223 	}
224 
225 	/* Resolve open_basedir to resolved_basedir */
226 	if (expand_filepath(local_open_basedir, resolved_basedir) != NULL) {
227 		size_t basedir_len = strlen(basedir);
228 		/* Handler for basedirs that end with a / */
229 		resolved_basedir_len = strlen(resolved_basedir);
230 #ifdef PHP_WIN32
231 		if (basedir[basedir_len - 1] == PHP_DIR_SEPARATOR || basedir[basedir_len - 1] == '/') {
232 #else
233 		if (basedir[basedir_len - 1] == PHP_DIR_SEPARATOR) {
234 #endif
235 			if (resolved_basedir[resolved_basedir_len - 1] != PHP_DIR_SEPARATOR) {
236 				resolved_basedir[resolved_basedir_len] = PHP_DIR_SEPARATOR;
237 				resolved_basedir[++resolved_basedir_len] = '\0';
238 			}
239 		} else {
240 				resolved_basedir[resolved_basedir_len++] = PHP_DIR_SEPARATOR;
241 				resolved_basedir[resolved_basedir_len] = '\0';
242 		}
243 
244 		resolved_name_len = strlen(resolved_name);
245 		if (path_tmp[path_len - 1] == PHP_DIR_SEPARATOR) {
246 			if (resolved_name[resolved_name_len - 1] != PHP_DIR_SEPARATOR) {
247 				resolved_name[resolved_name_len] = PHP_DIR_SEPARATOR;
248 				resolved_name[++resolved_name_len] = '\0';
249 			}
250 		}
251 
252 		/* Check the path */
253 #ifdef PHP_WIN32
254 		if (strncasecmp(resolved_basedir, resolved_name, resolved_basedir_len) == 0) {
255 #else
256 		if (strncmp(resolved_basedir, resolved_name, resolved_basedir_len) == 0) {
257 #endif
258 			if (resolved_name_len > resolved_basedir_len &&
259 				resolved_name[resolved_basedir_len - 1] != PHP_DIR_SEPARATOR) {
260 				return -1;
261 			} else {
262 				/* File is in the right directory */
263 				return 0;
264 			}
265 		} else {
266 			/* /openbasedir/ and /openbasedir are the same directory */
267 			if (resolved_basedir_len == (resolved_name_len + 1) && resolved_basedir[resolved_basedir_len - 1] == PHP_DIR_SEPARATOR) {
268 #ifdef PHP_WIN32
269 				if (strncasecmp(resolved_basedir, resolved_name, resolved_name_len) == 0) {
270 #else
271 				if (strncmp(resolved_basedir, resolved_name, resolved_name_len) == 0) {
272 #endif
273 					return 0;
274 				}
275 			}
276 			return -1;
277 		}
278 	} else {
279 		/* Unable to resolve the real path, return -1 */
280 		return -1;
281 	}
282 }
283 /* }}} */
284 
285 PHPAPI int php_check_open_basedir(const char *path)
286 {
287 	return php_check_open_basedir_ex(path, 1);
288 }
289 
290 /* {{{ php_check_open_basedir */
291 PHPAPI int php_check_open_basedir_ex(const char *path, int warn)
292 {
293 	/* Only check when open_basedir is available */
294 	if (PG(open_basedir) && *PG(open_basedir)) {
295 		char *pathbuf;
296 		char *ptr;
297 		char *end;
298 
299 		/* Check if the path is too long so we can give a more useful error
300 		* message. */
301 		if (strlen(path) > (MAXPATHLEN - 1)) {
302 			php_error_docref(NULL, E_WARNING, "File name is longer than the maximum allowed path length on this platform (%d): %s", MAXPATHLEN, path);
303 			errno = EINVAL;
304 			return -1;
305 		}
306 
307 		pathbuf = estrdup(PG(open_basedir));
308 
309 		ptr = pathbuf;
310 
311 		while (ptr && *ptr) {
312 			end = strchr(ptr, DEFAULT_DIR_SEPARATOR);
313 			if (end != NULL) {
314 				*end = '\0';
315 				end++;
316 			}
317 
318 			if (php_check_specific_open_basedir(ptr, path) == 0) {
319 				efree(pathbuf);
320 				return 0;
321 			}
322 
323 			ptr = end;
324 		}
325 		if (warn) {
326 			php_error_docref(NULL, E_WARNING, "open_basedir restriction in effect. File(%s) is not within the allowed path(s): (%s)", path, PG(open_basedir));
327 		}
328 		efree(pathbuf);
329 		errno = EPERM; /* we deny permission to open it */
330 		return -1;
331 	}
332 
333 	/* Nothing to check... */
334 	return 0;
335 }
336 /* }}} */
337 
338 /* {{{ php_fopen_and_set_opened_path */
339 static FILE *php_fopen_and_set_opened_path(const char *path, const char *mode, zend_string **opened_path)
340 {
341 	FILE *fp;
342 
343 	if (php_check_open_basedir((char *)path)) {
344 		return NULL;
345 	}
346 	fp = VCWD_FOPEN(path, mode);
347 	if (fp && opened_path) {
348 		//TODO :avoid reallocation
349 		char *tmp = expand_filepath_with_mode(path, NULL, NULL, 0, CWD_EXPAND);
350 		if (tmp) {
351 			*opened_path = zend_string_init(tmp, strlen(tmp), 0);
352 			efree(tmp);
353 		}
354 	}
355 	return fp;
356 }
357 /* }}} */
358 
359 /* {{{ php_fopen_primary_script */
360 PHPAPI int php_fopen_primary_script(zend_file_handle *file_handle)
361 {
362 	char *path_info;
363 	zend_string *filename = NULL;
364 	zend_string *resolved_path = NULL;
365 	size_t length;
366 	bool orig_display_errors;
367 
368 	memset(file_handle, 0, sizeof(zend_file_handle));
369 
370 	path_info = SG(request_info).request_uri;
371 #if HAVE_PWD_H
372 	if (PG(user_dir) && *PG(user_dir) && path_info && '/' == path_info[0] && '~' == path_info[1]) {
373 		char *s = strchr(path_info + 2, '/');
374 
375 		if (s) {			/* if there is no path name after the file, do not bother */
376 			char user[32];			/* to try open the directory */
377 			struct passwd *pw;
378 #if defined(ZTS) && defined(HAVE_GETPWNAM_R) && defined(_SC_GETPW_R_SIZE_MAX)
379 			struct passwd pwstruc;
380 			long pwbuflen = sysconf(_SC_GETPW_R_SIZE_MAX);
381 			char *pwbuf;
382 
383 			if (pwbuflen < 1) {
384 				return FAILURE;
385 			}
386 
387 			pwbuf = emalloc(pwbuflen);
388 #endif
389 			length = s - (path_info + 2);
390 			if (length > sizeof(user) - 1) {
391 				length = sizeof(user) - 1;
392 			}
393 			memcpy(user, path_info + 2, length);
394 			user[length] = '\0';
395 #if defined(ZTS) && defined(HAVE_GETPWNAM_R) && defined(_SC_GETPW_R_SIZE_MAX)
396 			if (getpwnam_r(user, &pwstruc, pwbuf, pwbuflen, &pw)) {
397 				efree(pwbuf);
398 				return FAILURE;
399 			}
400 #else
401 			pw = getpwnam(user);
402 #endif
403 			if (pw && pw->pw_dir) {
404 				filename = zend_strpprintf(0, "%s%c%s%c%s", pw->pw_dir, PHP_DIR_SEPARATOR, PG(user_dir), PHP_DIR_SEPARATOR, s + 1); /* Safe */
405 			} else if (SG(request_info).path_translated) {
406 				filename = zend_string_init(SG(request_info).path_translated,
407 					strlen(SG(request_info).path_translated), 0);
408 			}
409 #if defined(ZTS) && defined(HAVE_GETPWNAM_R) && defined(_SC_GETPW_R_SIZE_MAX)
410 			efree(pwbuf);
411 #endif
412 		}
413 	} else
414 #endif
415 	if (PG(doc_root) && path_info && (length = strlen(PG(doc_root))) &&
416 		IS_ABSOLUTE_PATH(PG(doc_root), length)) {
417 		size_t path_len = strlen(path_info);
418 		filename = zend_string_alloc(length + path_len + 2, 0);
419 		memcpy(ZSTR_VAL(filename), PG(doc_root), length);
420 		if (!IS_SLASH(ZSTR_VAL(filename)[length - 1])) {	/* length is never 0 */
421 			ZSTR_VAL(filename)[length++] = PHP_DIR_SEPARATOR;
422 		}
423 		if (IS_SLASH(path_info[0])) {
424 			length--;
425 		}
426 		strncpy(ZSTR_VAL(filename) + length, path_info, path_len + 1);
427 		ZSTR_LEN(filename) = length + path_len;
428 	} else if (SG(request_info).path_translated) {
429 		filename = zend_string_init(SG(request_info).path_translated,
430 			strlen(SG(request_info).path_translated), 0);
431 	}
432 
433 
434 	if (filename) {
435 		resolved_path = zend_resolve_path(filename);
436 	}
437 
438 	if (!resolved_path) {
439 		if (filename) {
440 			zend_string_release(filename);
441 		}
442 		/* we have to free SG(request_info).path_translated here because
443 		 * php_destroy_request_info assumes that it will get
444 		 * freed when the include_names hash is emptied, but
445 		 * we're not adding it in this case */
446 		if (SG(request_info).path_translated) {
447 			efree(SG(request_info).path_translated);
448 			SG(request_info).path_translated = NULL;
449 		}
450 		return FAILURE;
451 	}
452 	zend_string_release_ex(resolved_path, 0);
453 
454 	orig_display_errors = PG(display_errors);
455 	PG(display_errors) = 0;
456 	zend_stream_init_filename_ex(file_handle, filename);
457 	file_handle->primary_script = 1;
458 	if (filename) {
459 		zend_string_delref(filename);
460 	}
461 	if (zend_stream_open(file_handle) == FAILURE) {
462 		PG(display_errors) = orig_display_errors;
463 		if (SG(request_info).path_translated) {
464 			efree(SG(request_info).path_translated);
465 			SG(request_info).path_translated = NULL;
466 		}
467 		return FAILURE;
468 	}
469 	PG(display_errors) = orig_display_errors;
470 
471 	return SUCCESS;
472 }
473 /* }}} */
474 
475 static zend_string *tsrm_realpath_str(const char *path) {
476 	char *realpath = tsrm_realpath(path, NULL);
477 	if (!realpath) {
478 		return NULL;
479 	}
480 	zend_string *realpath_str = zend_string_init(realpath, strlen(realpath), 0);
481 	efree(realpath);
482 	return realpath_str;
483 }
484 
485 /* {{{ php_resolve_path
486  * Returns the realpath for given filename according to include path
487  */
488 PHPAPI zend_string *php_resolve_path(const char *filename, size_t filename_length, const char *path)
489 {
490 	zend_string *resolved_path;
491 	char trypath[MAXPATHLEN];
492 	const char *ptr, *end, *p;
493 	const char *actual_path;
494 	php_stream_wrapper *wrapper;
495 	zend_string *exec_filename;
496 
497 	if (!filename || CHECK_NULL_PATH(filename, filename_length)) {
498 		return NULL;
499 	}
500 
501 	/* Don't resolve paths which contain protocol (except of file://) */
502 	for (p = filename; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++);
503 	if ((*p == ':') && (p - filename > 1) && (p[1] == '/') && (p[2] == '/')) {
504 		wrapper = php_stream_locate_url_wrapper(filename, &actual_path, STREAM_OPEN_FOR_INCLUDE);
505 		if (wrapper == &php_plain_files_wrapper) {
506 			if ((resolved_path = tsrm_realpath_str(actual_path))) {
507 				return resolved_path;
508 			}
509 		}
510 		return NULL;
511 	}
512 
513 	if ((*filename == '.' &&
514 	     (IS_SLASH(filename[1]) ||
515 	      ((filename[1] == '.') && IS_SLASH(filename[2])))) ||
516 	    IS_ABSOLUTE_PATH(filename, filename_length) ||
517 #ifdef PHP_WIN32
518 		/* This should count as an absolute local path as well, however
519 		   IS_ABSOLUTE_PATH doesn't care about this path form till now. It
520 		   might be a big thing to extend, thus just a local handling for
521 		   now. */
522 		filename_length >=2 && IS_SLASH(filename[0]) && !IS_SLASH(filename[1]) ||
523 #endif
524 	    !path ||
525 	    !*path) {
526 		return tsrm_realpath_str(filename);
527 	}
528 
529 	ptr = path;
530 	while (ptr && *ptr) {
531 		/* Check for stream wrapper */
532 		int is_stream_wrapper = 0;
533 
534 		for (p = ptr; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++);
535 		if ((*p == ':') && (p - ptr > 1) && (p[1] == '/') && (p[2] == '/')) {
536 			/* .:// or ..:// is not a stream wrapper */
537 			if (p[-1] != '.' || p[-2] != '.' || p - 2 != ptr) {
538 				p += 3;
539 				is_stream_wrapper = 1;
540 			}
541 		}
542 		end = strchr(p, DEFAULT_DIR_SEPARATOR);
543 		if (end) {
544 			if (filename_length > (MAXPATHLEN - 2) || (end-ptr) > MAXPATHLEN || (end-ptr) + 1 + filename_length + 1 >= MAXPATHLEN) {
545 				ptr = end + 1;
546 				continue;
547 			}
548 			memcpy(trypath, ptr, end-ptr);
549 			trypath[end-ptr] = '/';
550 			memcpy(trypath+(end-ptr)+1, filename, filename_length+1);
551 			ptr = end+1;
552 		} else {
553 			size_t len = strlen(ptr);
554 
555 			if (filename_length > (MAXPATHLEN - 2) || len > MAXPATHLEN || len + 1 + filename_length + 1 >= MAXPATHLEN) {
556 				break;
557 			}
558 			memcpy(trypath, ptr, len);
559 			trypath[len] = '/';
560 			memcpy(trypath+len+1, filename, filename_length+1);
561 			ptr = NULL;
562 		}
563 		actual_path = trypath;
564 		if (is_stream_wrapper) {
565 			wrapper = php_stream_locate_url_wrapper(trypath, &actual_path, STREAM_OPEN_FOR_INCLUDE);
566 			if (!wrapper) {
567 				continue;
568 			} else if (wrapper != &php_plain_files_wrapper) {
569 				if (wrapper->wops->url_stat) {
570 					php_stream_statbuf ssb;
571 
572 					if (SUCCESS == wrapper->wops->url_stat(wrapper, trypath, PHP_STREAM_URL_STAT_QUIET, &ssb, NULL)) {
573 						return zend_string_init(trypath, strlen(trypath), 0);
574 					}
575 					if (EG(exception)) {
576 						return NULL;
577 					}
578 				}
579 				continue;
580 			}
581 		}
582 		if ((resolved_path = tsrm_realpath_str(actual_path))) {
583 			return resolved_path;
584 		}
585 	} /* end provided path */
586 
587 	/* check in calling scripts' current working directory as a fallback case
588 	 */
589 	if (zend_is_executing() &&
590 	    (exec_filename = zend_get_executed_filename_ex()) != NULL) {
591 		const char *exec_fname = ZSTR_VAL(exec_filename);
592 		size_t exec_fname_length = ZSTR_LEN(exec_filename);
593 
594 		while ((--exec_fname_length < SIZE_MAX) && !IS_SLASH(exec_fname[exec_fname_length]));
595 		if (exec_fname_length > 0 &&
596 			filename_length < (MAXPATHLEN - 2) &&
597 		    exec_fname_length + 1 + filename_length + 1 < MAXPATHLEN) {
598 			memcpy(trypath, exec_fname, exec_fname_length + 1);
599 			memcpy(trypath+exec_fname_length + 1, filename, filename_length+1);
600 			actual_path = trypath;
601 
602 			/* Check for stream wrapper */
603 			for (p = trypath; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++);
604 			if ((*p == ':') && (p - trypath > 1) && (p[1] == '/') && (p[2] == '/')) {
605 				wrapper = php_stream_locate_url_wrapper(trypath, &actual_path, STREAM_OPEN_FOR_INCLUDE);
606 				if (!wrapper) {
607 					return NULL;
608 				} else if (wrapper != &php_plain_files_wrapper) {
609 					if (wrapper->wops->url_stat) {
610 						php_stream_statbuf ssb;
611 
612 						if (SUCCESS == wrapper->wops->url_stat(wrapper, trypath, PHP_STREAM_URL_STAT_QUIET, &ssb, NULL)) {
613 							return zend_string_init(trypath, strlen(trypath), 0);
614 						}
615 						if (EG(exception)) {
616 							return NULL;
617 						}
618 					}
619 					return NULL;
620 				}
621 			}
622 
623 			return tsrm_realpath_str(actual_path);
624 		}
625 	}
626 
627 	return NULL;
628 }
629 /* }}} */
630 
631 /* {{{ php_fopen_with_path
632  * Tries to open a file with a PATH-style list of directories.
633  * If the filename starts with "." or "/", the path is ignored.
634  */
635 PHPAPI FILE *php_fopen_with_path(const char *filename, const char *mode, const char *path, zend_string **opened_path)
636 {
637 	char *pathbuf, *ptr, *end;
638 	char trypath[MAXPATHLEN];
639 	FILE *fp;
640 	size_t filename_length;
641 	zend_string *exec_filename;
642 
643 	if (opened_path) {
644 		*opened_path = NULL;
645 	}
646 
647 	if (!filename) {
648 		return NULL;
649 	}
650 
651 	filename_length = strlen(filename);
652 #ifndef PHP_WIN32
653 	(void) filename_length;
654 #endif
655 
656 	/* Relative path open */
657 	if ((*filename == '.')
658 	/* Absolute path open */
659 	 || IS_ABSOLUTE_PATH(filename, filename_length)
660 	 || (!path || !*path)
661 	) {
662 		return php_fopen_and_set_opened_path(filename, mode, opened_path);
663 	}
664 
665 	/* check in provided path */
666 	/* append the calling scripts' current working directory
667 	 * as a fallback case
668 	 */
669 	if (zend_is_executing() &&
670 	    (exec_filename = zend_get_executed_filename_ex()) != NULL) {
671 		const char *exec_fname = ZSTR_VAL(exec_filename);
672 		size_t exec_fname_length = ZSTR_LEN(exec_filename);
673 
674 		while ((--exec_fname_length < SIZE_MAX) && !IS_SLASH(exec_fname[exec_fname_length]));
675 		if ((exec_fname && exec_fname[0] == '[') || exec_fname_length <= 0) {
676 			/* [no active file] or no path */
677 			pathbuf = estrdup(path);
678 		} else {
679 			size_t path_length = strlen(path);
680 
681 			pathbuf = (char *) emalloc(exec_fname_length + path_length + 1 + 1);
682 			memcpy(pathbuf, path, path_length);
683 			pathbuf[path_length] = DEFAULT_DIR_SEPARATOR;
684 			memcpy(pathbuf + path_length + 1, exec_fname, exec_fname_length);
685 			pathbuf[path_length + exec_fname_length + 1] = '\0';
686 		}
687 	} else {
688 		pathbuf = estrdup(path);
689 	}
690 
691 	ptr = pathbuf;
692 
693 	while (ptr && *ptr) {
694 		end = strchr(ptr, DEFAULT_DIR_SEPARATOR);
695 		if (end != NULL) {
696 			*end = '\0';
697 			end++;
698 		}
699 		if (snprintf(trypath, MAXPATHLEN, "%s/%s", ptr, filename) >= MAXPATHLEN) {
700 			php_error_docref(NULL, E_NOTICE, "%s/%s path was truncated to %d", ptr, filename, MAXPATHLEN);
701 		}
702 		fp = php_fopen_and_set_opened_path(trypath, mode, opened_path);
703 		if (fp) {
704 			efree(pathbuf);
705 			return fp;
706 		}
707 		ptr = end;
708 	} /* end provided path */
709 
710 	efree(pathbuf);
711 	return NULL;
712 }
713 /* }}} */
714 
715 /* {{{ php_strip_url_passwd */
716 PHPAPI char *php_strip_url_passwd(char *url)
717 {
718 	char *p, *url_start;
719 
720 	if (url == NULL) {
721 		return "";
722 	}
723 
724 	p = url;
725 
726 	while (*p) {
727 		if (*p == ':' && *(p + 1) == '/' && *(p + 2) == '/') {
728 			/* found protocol */
729 			url_start = p = p + 3;
730 
731 			while (*p) {
732 				if (*p == '@') {
733 					int i;
734 
735 					for (i = 0; i < 3 && url_start < p; i++, url_start++) {
736 						*url_start = '.';
737 					}
738 					for (; *p; p++) {
739 						*url_start++ = *p;
740 					}
741 					*url_start=0;
742 					break;
743 				}
744 				p++;
745 			}
746 			return url;
747 		}
748 		p++;
749 	}
750 	return url;
751 }
752 /* }}} */
753 
754 /* {{{ expand_filepath */
755 PHPAPI char *expand_filepath(const char *filepath, char *real_path)
756 {
757 	return expand_filepath_ex(filepath, real_path, NULL, 0);
758 }
759 /* }}} */
760 
761 /* {{{ expand_filepath_ex */
762 PHPAPI char *expand_filepath_ex(const char *filepath, char *real_path, const char *relative_to, size_t relative_to_len)
763 {
764 	return expand_filepath_with_mode(filepath, real_path, relative_to, relative_to_len, CWD_FILEPATH);
765 }
766 /* }}} */
767 
768 /* {{{ expand_filepath_use_realpath */
769 PHPAPI char *expand_filepath_with_mode(const char *filepath, char *real_path, const char *relative_to, size_t relative_to_len, int realpath_mode)
770 {
771 	cwd_state new_state;
772 	char cwd[MAXPATHLEN];
773 	size_t copy_len;
774 	size_t path_len;
775 
776 	if (!filepath[0]) {
777 		return NULL;
778 	}
779 
780 	path_len = strlen(filepath);
781 
782 	if (IS_ABSOLUTE_PATH(filepath, path_len)) {
783 		cwd[0] = '\0';
784 	} else {
785 		const char *iam = SG(request_info).path_translated;
786 		const char *result;
787 		if (relative_to) {
788 			if (relative_to_len > MAXPATHLEN-1U) {
789 				return NULL;
790 			}
791 			result = relative_to;
792 			memcpy(cwd, relative_to, relative_to_len+1U);
793 		} else {
794 			result = VCWD_GETCWD(cwd, MAXPATHLEN);
795 		}
796 
797 		if (!result && (iam != filepath)) {
798 			int fdtest = -1;
799 
800 			fdtest = VCWD_OPEN(filepath, O_RDONLY);
801 			if (fdtest != -1) {
802 				/* return a relative file path if for any reason
803 				 * we cannot getcwd() and the requested,
804 				 * relatively referenced file is accessible */
805 				copy_len = path_len > MAXPATHLEN - 1 ? MAXPATHLEN - 1 : path_len;
806 				if (real_path) {
807 					memcpy(real_path, filepath, copy_len);
808 					real_path[copy_len] = '\0';
809 				} else {
810 					real_path = estrndup(filepath, copy_len);
811 				}
812 				close(fdtest);
813 				return real_path;
814 			} else {
815 				cwd[0] = '\0';
816 			}
817 		} else if (!result) {
818 			cwd[0] = '\0';
819 		}
820 	}
821 
822 	new_state.cwd = estrdup(cwd);
823 	new_state.cwd_length = strlen(cwd);
824 
825 	if (virtual_file_ex(&new_state, filepath, NULL, realpath_mode)) {
826 		efree(new_state.cwd);
827 		return NULL;
828 	}
829 
830 	if (real_path) {
831 		copy_len = new_state.cwd_length > MAXPATHLEN - 1 ? MAXPATHLEN - 1 : new_state.cwd_length;
832 		memcpy(real_path, new_state.cwd, copy_len);
833 		real_path[copy_len] = '\0';
834 	} else {
835 		real_path = estrndup(new_state.cwd, new_state.cwd_length);
836 	}
837 	efree(new_state.cwd);
838 
839 	return real_path;
840 }
841 /* }}} */
842