xref: /PHP-8.4/main/fopen_wrappers.c (revision 3fbca7fb)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | 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 #ifdef HAVE_PWD_H
44 #include <pwd.h>
45 #endif
46 
47 #include <sys/types.h>
48 #ifdef 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 #ifdef 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 #ifdef 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 
378 			length = s - (path_info + 2);
379 			if (length > sizeof(user) - 1) {
380 				length = sizeof(user) - 1;
381 			}
382 			memcpy(user, path_info + 2, length);
383 			user[length] = '\0';
384 
385 			struct passwd *pw;
386 #if defined(ZTS) && defined(HAVE_GETPWNAM_R) && defined(_SC_GETPW_R_SIZE_MAX)
387 			struct passwd pwstruc;
388 			long pwbuflen = sysconf(_SC_GETPW_R_SIZE_MAX);
389 			char *pwbuf;
390 			int err;
391 
392 			if (pwbuflen < 1) {
393 				pwbuflen = 1024;
394 			}
395 # if ZEND_DEBUG
396 			/* Test retry logic */
397 			pwbuflen = 1;
398 # endif
399 			pwbuf = emalloc(pwbuflen);
400 
401 try_again:
402 			err = getpwnam_r(user, &pwstruc, pwbuf, pwbuflen, &pw);
403 			if (err) {
404 				if (err == ERANGE) {
405 					pwbuflen *= 2;
406 					pwbuf = erealloc(pwbuf, pwbuflen);
407 					goto try_again;
408 				}
409 				efree(pwbuf);
410 				return FAILURE;
411 			}
412 #else
413 			pw = getpwnam(user);
414 #endif
415 			if (pw && pw->pw_dir) {
416 				filename = zend_strpprintf(0, "%s%c%s%c%s", pw->pw_dir, PHP_DIR_SEPARATOR, PG(user_dir), PHP_DIR_SEPARATOR, s + 1); /* Safe */
417 			} else if (SG(request_info).path_translated) {
418 				filename = zend_string_init(SG(request_info).path_translated,
419 					strlen(SG(request_info).path_translated), 0);
420 			}
421 #if defined(ZTS) && defined(HAVE_GETPWNAM_R) && defined(_SC_GETPW_R_SIZE_MAX)
422 			efree(pwbuf);
423 #endif
424 		}
425 	} else
426 #endif
427 	if (PG(doc_root) && path_info && (length = strlen(PG(doc_root))) &&
428 		IS_ABSOLUTE_PATH(PG(doc_root), length)) {
429 		size_t path_len = strlen(path_info);
430 		filename = zend_string_alloc(length + path_len + 2, 0);
431 		memcpy(ZSTR_VAL(filename), PG(doc_root), length);
432 		if (!IS_SLASH(ZSTR_VAL(filename)[length - 1])) {	/* length is never 0 */
433 			ZSTR_VAL(filename)[length++] = PHP_DIR_SEPARATOR;
434 		}
435 		if (IS_SLASH(path_info[0])) {
436 			length--;
437 		}
438 		strncpy(ZSTR_VAL(filename) + length, path_info, path_len + 1);
439 		ZSTR_LEN(filename) = length + path_len;
440 	} else if (SG(request_info).path_translated) {
441 		filename = zend_string_init(SG(request_info).path_translated,
442 			strlen(SG(request_info).path_translated), 0);
443 	}
444 
445 
446 	if (filename) {
447 		resolved_path = zend_resolve_path(filename);
448 	}
449 
450 	if (!resolved_path) {
451 		if (filename) {
452 			zend_string_release(filename);
453 		}
454 		/* we have to free SG(request_info).path_translated here because
455 		 * php_destroy_request_info assumes that it will get
456 		 * freed when the include_names hash is emptied, but
457 		 * we're not adding it in this case */
458 		if (SG(request_info).path_translated) {
459 			efree(SG(request_info).path_translated);
460 			SG(request_info).path_translated = NULL;
461 		}
462 		return FAILURE;
463 	}
464 	zend_string_release_ex(resolved_path, 0);
465 
466 	orig_display_errors = PG(display_errors);
467 	PG(display_errors) = 0;
468 	zend_stream_init_filename_ex(file_handle, filename);
469 	file_handle->primary_script = 1;
470 	if (filename) {
471 		zend_string_delref(filename);
472 	}
473 	if (zend_stream_open(file_handle) == FAILURE) {
474 		PG(display_errors) = orig_display_errors;
475 		if (SG(request_info).path_translated) {
476 			efree(SG(request_info).path_translated);
477 			SG(request_info).path_translated = NULL;
478 		}
479 		return FAILURE;
480 	}
481 	PG(display_errors) = orig_display_errors;
482 
483 	return SUCCESS;
484 }
485 /* }}} */
486 
487 static zend_string *tsrm_realpath_str(const char *path) {
488 	char *realpath = tsrm_realpath(path, NULL);
489 	if (!realpath) {
490 		return NULL;
491 	}
492 	zend_string *realpath_str = zend_string_init(realpath, strlen(realpath), 0);
493 	efree(realpath);
494 	return realpath_str;
495 }
496 
497 /* {{{ php_resolve_path
498  * Returns the realpath for given filename according to include path
499  */
500 PHPAPI zend_string *php_resolve_path(const char *filename, size_t filename_length, const char *path)
501 {
502 	zend_string *resolved_path;
503 	char trypath[MAXPATHLEN];
504 	const char *ptr, *end, *p;
505 	const char *actual_path;
506 	php_stream_wrapper *wrapper;
507 	zend_string *exec_filename;
508 
509 	if (!filename || CHECK_NULL_PATH(filename, filename_length)) {
510 		return NULL;
511 	}
512 
513 	/* Don't resolve paths which contain protocol (except of file://) */
514 	for (p = filename; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++);
515 	if ((*p == ':') && (p - filename > 1) && (p[1] == '/') && (p[2] == '/')) {
516 		wrapper = php_stream_locate_url_wrapper(filename, &actual_path, STREAM_OPEN_FOR_INCLUDE);
517 		if (wrapper == &php_plain_files_wrapper) {
518 			if ((resolved_path = tsrm_realpath_str(actual_path))) {
519 				return resolved_path;
520 			}
521 		}
522 		return NULL;
523 	}
524 
525 	if ((*filename == '.' &&
526 	     (IS_SLASH(filename[1]) ||
527 	      ((filename[1] == '.') && IS_SLASH(filename[2])))) ||
528 	    IS_ABSOLUTE_PATH(filename, filename_length) ||
529 #ifdef PHP_WIN32
530 		/* This should count as an absolute local path as well, however
531 		   IS_ABSOLUTE_PATH doesn't care about this path form till now. It
532 		   might be a big thing to extend, thus just a local handling for
533 		   now. */
534 		filename_length >=2 && IS_SLASH(filename[0]) && !IS_SLASH(filename[1]) ||
535 #endif
536 	    !path ||
537 	    !*path) {
538 		return tsrm_realpath_str(filename);
539 	}
540 
541 	ptr = path;
542 	while (ptr && *ptr) {
543 		/* Check for stream wrapper */
544 		int is_stream_wrapper = 0;
545 
546 		for (p = ptr; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++);
547 		if ((*p == ':') && (p - ptr > 1) && (p[1] == '/') && (p[2] == '/')) {
548 			/* .:// or ..:// is not a stream wrapper */
549 			if (p[-1] != '.' || p[-2] != '.' || p - 2 != ptr) {
550 				p += 3;
551 				is_stream_wrapper = 1;
552 			}
553 		}
554 		end = strchr(p, DEFAULT_DIR_SEPARATOR);
555 		if (end) {
556 			if (filename_length > (MAXPATHLEN - 2) || (end-ptr) > MAXPATHLEN || (end-ptr) + 1 + filename_length + 1 >= MAXPATHLEN) {
557 				ptr = end + 1;
558 				continue;
559 			}
560 			memcpy(trypath, ptr, end-ptr);
561 			trypath[end-ptr] = '/';
562 			memcpy(trypath+(end-ptr)+1, filename, filename_length+1);
563 			ptr = end+1;
564 		} else {
565 			size_t len = strlen(ptr);
566 
567 			if (filename_length > (MAXPATHLEN - 2) || len > MAXPATHLEN || len + 1 + filename_length + 1 >= MAXPATHLEN) {
568 				break;
569 			}
570 			memcpy(trypath, ptr, len);
571 			trypath[len] = '/';
572 			memcpy(trypath+len+1, filename, filename_length+1);
573 			ptr = NULL;
574 		}
575 		actual_path = trypath;
576 		if (is_stream_wrapper) {
577 			wrapper = php_stream_locate_url_wrapper(trypath, &actual_path, STREAM_OPEN_FOR_INCLUDE);
578 			if (!wrapper) {
579 				continue;
580 			} else if (wrapper != &php_plain_files_wrapper) {
581 				if (wrapper->wops->url_stat) {
582 					php_stream_statbuf ssb;
583 
584 					if (SUCCESS == wrapper->wops->url_stat(wrapper, trypath, PHP_STREAM_URL_STAT_QUIET, &ssb, NULL)) {
585 						return zend_string_init(trypath, strlen(trypath), 0);
586 					}
587 					if (EG(exception)) {
588 						return NULL;
589 					}
590 				}
591 				continue;
592 			}
593 		}
594 		if ((resolved_path = tsrm_realpath_str(actual_path))) {
595 			return resolved_path;
596 		}
597 	} /* end provided path */
598 
599 	/* check in calling scripts' current working directory as a fallback case
600 	 */
601 	if (zend_is_executing() &&
602 	    (exec_filename = zend_get_executed_filename_ex()) != NULL) {
603 		const char *exec_fname = ZSTR_VAL(exec_filename);
604 		size_t exec_fname_length = ZSTR_LEN(exec_filename);
605 
606 		while ((--exec_fname_length < SIZE_MAX) && !IS_SLASH(exec_fname[exec_fname_length]));
607 		if (exec_fname_length > 0 &&
608 			filename_length < (MAXPATHLEN - 2) &&
609 		    exec_fname_length + 1 + filename_length + 1 < MAXPATHLEN) {
610 			memcpy(trypath, exec_fname, exec_fname_length + 1);
611 			memcpy(trypath+exec_fname_length + 1, filename, filename_length+1);
612 			actual_path = trypath;
613 
614 			/* Check for stream wrapper */
615 			for (p = trypath; isalnum((int)*p) || *p == '+' || *p == '-' || *p == '.'; p++);
616 			if ((*p == ':') && (p - trypath > 1) && (p[1] == '/') && (p[2] == '/')) {
617 				wrapper = php_stream_locate_url_wrapper(trypath, &actual_path, STREAM_OPEN_FOR_INCLUDE);
618 				if (!wrapper) {
619 					return NULL;
620 				} else if (wrapper != &php_plain_files_wrapper) {
621 					if (wrapper->wops->url_stat) {
622 						php_stream_statbuf ssb;
623 
624 						if (SUCCESS == wrapper->wops->url_stat(wrapper, trypath, PHP_STREAM_URL_STAT_QUIET, &ssb, NULL)) {
625 							return zend_string_init(trypath, strlen(trypath), 0);
626 						}
627 						if (EG(exception)) {
628 							return NULL;
629 						}
630 					}
631 					return NULL;
632 				}
633 			}
634 
635 			return tsrm_realpath_str(actual_path);
636 		}
637 	}
638 
639 	return NULL;
640 }
641 /* }}} */
642 
643 /* {{{ php_fopen_with_path
644  * Tries to open a file with a PATH-style list of directories.
645  * If the filename starts with "." or "/", the path is ignored.
646  */
647 PHPAPI FILE *php_fopen_with_path(const char *filename, const char *mode, const char *path, zend_string **opened_path)
648 {
649 	char *pathbuf, *ptr, *end;
650 	char trypath[MAXPATHLEN];
651 	FILE *fp;
652 	size_t filename_length;
653 	zend_string *exec_filename;
654 
655 	if (opened_path) {
656 		*opened_path = NULL;
657 	}
658 
659 	if (!filename) {
660 		return NULL;
661 	}
662 
663 	filename_length = strlen(filename);
664 #ifndef PHP_WIN32
665 	(void) filename_length;
666 #endif
667 
668 	/* Relative path open */
669 	if ((*filename == '.')
670 	/* Absolute path open */
671 	 || IS_ABSOLUTE_PATH(filename, filename_length)
672 	 || (!path || !*path)
673 	) {
674 		return php_fopen_and_set_opened_path(filename, mode, opened_path);
675 	}
676 
677 	/* check in provided path */
678 	/* append the calling scripts' current working directory
679 	 * as a fallback case
680 	 */
681 	if (zend_is_executing() &&
682 	    (exec_filename = zend_get_executed_filename_ex()) != NULL) {
683 		const char *exec_fname = ZSTR_VAL(exec_filename);
684 		size_t exec_fname_length = ZSTR_LEN(exec_filename);
685 
686 		while ((--exec_fname_length < SIZE_MAX) && !IS_SLASH(exec_fname[exec_fname_length]));
687 		if ((exec_fname && exec_fname[0] == '[') || exec_fname_length <= 0) {
688 			/* [no active file] or no path */
689 			pathbuf = estrdup(path);
690 		} else {
691 			size_t path_length = strlen(path);
692 
693 			pathbuf = (char *) emalloc(exec_fname_length + path_length + 1 + 1);
694 			memcpy(pathbuf, path, path_length);
695 			pathbuf[path_length] = DEFAULT_DIR_SEPARATOR;
696 			memcpy(pathbuf + path_length + 1, exec_fname, exec_fname_length);
697 			pathbuf[path_length + exec_fname_length + 1] = '\0';
698 		}
699 	} else {
700 		pathbuf = estrdup(path);
701 	}
702 
703 	ptr = pathbuf;
704 
705 	while (ptr && *ptr) {
706 		end = strchr(ptr, DEFAULT_DIR_SEPARATOR);
707 		if (end != NULL) {
708 			*end = '\0';
709 			end++;
710 		}
711 		if (snprintf(trypath, MAXPATHLEN, "%s/%s", ptr, filename) >= MAXPATHLEN) {
712 			php_error_docref(NULL, E_NOTICE, "%s/%s path was truncated to %d", ptr, filename, MAXPATHLEN);
713 		}
714 		fp = php_fopen_and_set_opened_path(trypath, mode, opened_path);
715 		if (fp) {
716 			efree(pathbuf);
717 			return fp;
718 		}
719 		ptr = end;
720 	} /* end provided path */
721 
722 	efree(pathbuf);
723 	return NULL;
724 }
725 /* }}} */
726 
727 /* {{{ php_strip_url_passwd */
728 PHPAPI char *php_strip_url_passwd(char *url)
729 {
730 	char *p, *url_start;
731 
732 	if (url == NULL) {
733 		return "";
734 	}
735 
736 	p = url;
737 
738 	while (*p) {
739 		if (*p == ':' && *(p + 1) == '/' && *(p + 2) == '/') {
740 			/* found protocol */
741 			url_start = p = p + 3;
742 
743 			while (*p) {
744 				if (*p == '@') {
745 					int i;
746 
747 					for (i = 0; i < 3 && url_start < p; i++, url_start++) {
748 						*url_start = '.';
749 					}
750 					for (; *p; p++) {
751 						*url_start++ = *p;
752 					}
753 					*url_start=0;
754 					break;
755 				}
756 				p++;
757 			}
758 			return url;
759 		}
760 		p++;
761 	}
762 	return url;
763 }
764 /* }}} */
765 
766 /* {{{ expand_filepath */
767 PHPAPI char *expand_filepath(const char *filepath, char *real_path)
768 {
769 	return expand_filepath_ex(filepath, real_path, NULL, 0);
770 }
771 /* }}} */
772 
773 /* {{{ expand_filepath_ex */
774 PHPAPI char *expand_filepath_ex(const char *filepath, char *real_path, const char *relative_to, size_t relative_to_len)
775 {
776 	return expand_filepath_with_mode(filepath, real_path, relative_to, relative_to_len, CWD_FILEPATH);
777 }
778 /* }}} */
779 
780 /* {{{ expand_filepath_use_realpath */
781 PHPAPI char *expand_filepath_with_mode(const char *filepath, char *real_path, const char *relative_to, size_t relative_to_len, int realpath_mode)
782 {
783 	cwd_state new_state;
784 	char cwd[MAXPATHLEN];
785 	size_t copy_len;
786 	size_t path_len;
787 
788 	if (!filepath[0]) {
789 		return NULL;
790 	}
791 
792 	path_len = strlen(filepath);
793 
794 	if (IS_ABSOLUTE_PATH(filepath, path_len)) {
795 		cwd[0] = '\0';
796 	} else {
797 		const char *iam = SG(request_info).path_translated;
798 		const char *result;
799 		if (relative_to) {
800 			if (relative_to_len > MAXPATHLEN-1U) {
801 				return NULL;
802 			}
803 			result = relative_to;
804 			memcpy(cwd, relative_to, relative_to_len+1U);
805 		} else {
806 			result = VCWD_GETCWD(cwd, MAXPATHLEN);
807 		}
808 
809 		if (!result && (iam != filepath)) {
810 			int fdtest = -1;
811 
812 			fdtest = VCWD_OPEN(filepath, O_RDONLY);
813 			if (fdtest != -1) {
814 				/* return a relative file path if for any reason
815 				 * we cannot getcwd() and the requested,
816 				 * relatively referenced file is accessible */
817 				copy_len = path_len > MAXPATHLEN - 1 ? MAXPATHLEN - 1 : path_len;
818 				if (real_path) {
819 					memcpy(real_path, filepath, copy_len);
820 					real_path[copy_len] = '\0';
821 				} else {
822 					real_path = estrndup(filepath, copy_len);
823 				}
824 				close(fdtest);
825 				return real_path;
826 			} else {
827 				cwd[0] = '\0';
828 			}
829 		} else if (!result) {
830 			cwd[0] = '\0';
831 		}
832 	}
833 
834 	new_state.cwd = estrdup(cwd);
835 	new_state.cwd_length = strlen(cwd);
836 
837 	if (virtual_file_ex(&new_state, filepath, NULL, realpath_mode)) {
838 		efree(new_state.cwd);
839 		return NULL;
840 	}
841 
842 	if (real_path) {
843 		copy_len = new_state.cwd_length > MAXPATHLEN - 1 ? MAXPATHLEN - 1 : new_state.cwd_length;
844 		memcpy(real_path, new_state.cwd, copy_len);
845 		real_path[copy_len] = '\0';
846 	} else {
847 		real_path = estrndup(new_state.cwd, new_state.cwd_length);
848 	}
849 	efree(new_state.cwd);
850 
851 	return real_path;
852 }
853 /* }}} */
854