xref: /PHP-8.2/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 
42 #if HAVE_PWD_H
43 #include <pwd.h>
44 #endif
45 
46 #include <sys/types.h>
47 #if HAVE_SYS_SOCKET_H
48 #include <sys/socket.h>
49 #endif
50 
51 #ifdef PHP_WIN32
52 #include <winsock2.h>
53 #else
54 #include <netinet/in.h>
55 #include <netdb.h>
56 #if HAVE_ARPA_INET_H
57 #include <arpa/inet.h>
58 #endif
59 #endif
60 
61 #if defined(PHP_WIN32) || defined(__riscos__)
62 #undef AF_UNIX
63 #endif
64 
65 #if defined(AF_UNIX)
66 #include <sys/un.h>
67 #endif
68 /* }}} */
69 
70 /* {{{ OnUpdateBaseDir
71 Allows any change to open_basedir setting in during Startup and Shutdown events,
72 or a tightening during activation/runtime/deactivation */
ZEND_INI_MH(OnUpdateBaseDir)73 PHPAPI ZEND_INI_MH(OnUpdateBaseDir)
74 {
75 	char **p = (char **) ZEND_INI_GET_ADDR();
76 	char *pathbuf, *ptr, *end;
77 
78 	if (stage == PHP_INI_STAGE_STARTUP || stage == PHP_INI_STAGE_SHUTDOWN || stage == PHP_INI_STAGE_ACTIVATE || stage == PHP_INI_STAGE_DEACTIVATE) {
79 		/* We're in a PHP_INI_SYSTEM context, no restrictions */
80 		*p = new_value ? ZSTR_VAL(new_value) : NULL;
81 		return SUCCESS;
82 	}
83 
84 	/* Otherwise we're in runtime */
85 	if (!*p || !**p) {
86 		/* open_basedir not set yet, go ahead and give it a value */
87 		*p = ZSTR_VAL(new_value);
88 		return SUCCESS;
89 	}
90 
91 	/* Shortcut: When we have a open_basedir and someone tries to unset, we know it'll fail */
92 	if (!new_value || !*ZSTR_VAL(new_value)) {
93 		return FAILURE;
94 	}
95 
96 	/* Is the proposed open_basedir at least as restrictive as the current setting? */
97 	ptr = pathbuf = estrdup(ZSTR_VAL(new_value));
98 	while (ptr && *ptr) {
99 		end = strchr(ptr, DEFAULT_DIR_SEPARATOR);
100 		if (end != NULL) {
101 			*end = '\0';
102 			end++;
103 		}
104 		if (ptr[0] == '.' && ptr[1] == '.' && (ptr[2] == '\0' || IS_SLASH(ptr[2]))) {
105 			/* Don't allow paths with a leading .. path component to be set at runtime */
106 			efree(pathbuf);
107 			return FAILURE;
108 		}
109 		if (php_check_open_basedir_ex(ptr, 0) != 0) {
110 			/* At least one portion of this open_basedir is less restrictive than the prior one, FAIL */
111 			efree(pathbuf);
112 			return FAILURE;
113 		}
114 		ptr = end;
115 	}
116 	efree(pathbuf);
117 
118 	/* Everything checks out, set it */
119 	*p = ZSTR_VAL(new_value);
120 
121 	return SUCCESS;
122 }
123 /* }}} */
124 
125 /* {{{ php_check_specific_open_basedir
126 	When open_basedir is not NULL, check if the given filename is located in
127 	open_basedir. Returns -1 if error or not in the open_basedir, else 0.
128 	When open_basedir is NULL, always return 0.
129 */
php_check_specific_open_basedir(const char * basedir,const char * path)130 PHPAPI int php_check_specific_open_basedir(const char *basedir, const char *path)
131 {
132 	char resolved_name[MAXPATHLEN + 1];
133 	char resolved_basedir[MAXPATHLEN + 1];
134 	char local_open_basedir[MAXPATHLEN];
135 	char path_tmp[MAXPATHLEN + 1];
136 	char *path_file;
137 	size_t resolved_basedir_len;
138 	size_t resolved_name_len;
139 	size_t path_len;
140 	int nesting_level = 0;
141 
142 	/* Special case basedir==".": Use script-directory */
143 	if (strcmp(basedir, ".") || !VCWD_GETCWD(local_open_basedir, MAXPATHLEN)) {
144 		/* Else use the unmodified path */
145 		strlcpy(local_open_basedir, basedir, sizeof(local_open_basedir));
146 	}
147 
148 	path_len = strlen(path);
149 	if (path_len > (MAXPATHLEN - 1)) {
150 		/* empty and too long paths are invalid */
151 		return -1;
152 	}
153 
154 	/* normalize and expand path */
155 	if (expand_filepath(path, resolved_name) == NULL) {
156 		return -1;
157 	}
158 
159 	path_len = strlen(resolved_name);
160 	memcpy(path_tmp, resolved_name, path_len + 1); /* safe */
161 
162 	while (VCWD_REALPATH(path_tmp, resolved_name) == NULL) {
163 #if defined(PHP_WIN32) || defined(HAVE_SYMLINK)
164 		if (nesting_level == 0) {
165 			ssize_t ret;
166 			char buf[MAXPATHLEN];
167 
168 			ret = php_sys_readlink(path_tmp, buf, MAXPATHLEN - 1);
169 			if (ret == -1) {
170 				/* not a broken symlink, move along.. */
171 			} else {
172 				/* put the real path into the path buffer */
173 				memcpy(path_tmp, buf, ret);
174 				path_tmp[ret] = '\0';
175 			}
176 		}
177 #endif
178 
179 #ifdef PHP_WIN32
180 		path_file = strrchr(path_tmp, DEFAULT_SLASH);
181 		if (!path_file) {
182 			path_file = strrchr(path_tmp, '/');
183 		}
184 #else
185 		path_file = strrchr(path_tmp, DEFAULT_SLASH);
186 #endif
187 		if (!path_file) {
188 			/* none of the path components exist. definitely not in open_basedir.. */
189 			return -1;
190 		} else {
191 			path_len = path_file - path_tmp + 1;
192 #ifdef PHP_WIN32
193 			if (path_len > 1 && path_tmp[path_len - 2] == ':') {
194 				if (path_len != 3) {
195 					return -1;
196 				}
197 				/* this is c:\ */
198 				path_tmp[path_len] = '\0';
199 			} else {
200 				path_tmp[path_len - 1] = '\0';
201 			}
202 #else
203 			path_tmp[path_len - 1] = '\0';
204 #endif
205 		}
206 		if (*path_tmp == '\0') {
207 			/* Do not pass an empty string to realpath(), as this will resolve to CWD. */
208 			break;
209 		}
210 		nesting_level++;
211 	}
212 
213 	/* Resolve open_basedir to resolved_basedir */
214 	if (expand_filepath(local_open_basedir, resolved_basedir) != NULL) {
215 		size_t basedir_len = strlen(basedir);
216 		/* Handler for basedirs that end with a / */
217 		resolved_basedir_len = strlen(resolved_basedir);
218 #ifdef PHP_WIN32
219 		if (basedir[basedir_len - 1] == PHP_DIR_SEPARATOR || basedir[basedir_len - 1] == '/') {
220 #else
221 		if (basedir[basedir_len - 1] == PHP_DIR_SEPARATOR) {
222 #endif
223 			if (resolved_basedir[resolved_basedir_len - 1] != PHP_DIR_SEPARATOR) {
224 				resolved_basedir[resolved_basedir_len] = PHP_DIR_SEPARATOR;
225 				resolved_basedir[++resolved_basedir_len] = '\0';
226 			}
227 		} else {
228 				resolved_basedir[resolved_basedir_len++] = PHP_DIR_SEPARATOR;
229 				resolved_basedir[resolved_basedir_len] = '\0';
230 		}
231 
232 		resolved_name_len = strlen(resolved_name);
233 		if (path_tmp[path_len - 1] == PHP_DIR_SEPARATOR) {
234 			if (resolved_name[resolved_name_len - 1] != PHP_DIR_SEPARATOR) {
235 				resolved_name[resolved_name_len] = PHP_DIR_SEPARATOR;
236 				resolved_name[++resolved_name_len] = '\0';
237 			}
238 		}
239 
240 		/* Check the path */
241 #ifdef PHP_WIN32
242 		if (strncasecmp(resolved_basedir, resolved_name, resolved_basedir_len) == 0) {
243 #else
244 		if (strncmp(resolved_basedir, resolved_name, resolved_basedir_len) == 0) {
245 #endif
246 			if (resolved_name_len > resolved_basedir_len &&
247 				resolved_name[resolved_basedir_len - 1] != PHP_DIR_SEPARATOR) {
248 				return -1;
249 			} else {
250 				/* File is in the right directory */
251 				return 0;
252 			}
253 		} else {
254 			/* /openbasedir/ and /openbasedir are the same directory */
255 			if (resolved_basedir_len == (resolved_name_len + 1) && resolved_basedir[resolved_basedir_len - 1] == PHP_DIR_SEPARATOR) {
256 #ifdef PHP_WIN32
257 				if (strncasecmp(resolved_basedir, resolved_name, resolved_name_len) == 0) {
258 #else
259 				if (strncmp(resolved_basedir, resolved_name, resolved_name_len) == 0) {
260 #endif
261 					return 0;
262 				}
263 			}
264 			return -1;
265 		}
266 	} else {
267 		/* Unable to resolve the real path, return -1 */
268 		return -1;
269 	}
270 }
271 /* }}} */
272 
273 PHPAPI int php_check_open_basedir(const char *path)
274 {
275 	return php_check_open_basedir_ex(path, 1);
276 }
277 
278 /* {{{ php_check_open_basedir */
279 PHPAPI int php_check_open_basedir_ex(const char *path, int warn)
280 {
281 	/* Only check when open_basedir is available */
282 	if (PG(open_basedir) && *PG(open_basedir)) {
283 		char *pathbuf;
284 		char *ptr;
285 		char *end;
286 
287 		/* Check if the path is too long so we can give a more useful error
288 		* message. */
289 		if (strlen(path) > (MAXPATHLEN - 1)) {
290 			php_error_docref(NULL, E_WARNING, "File name is longer than the maximum allowed path length on this platform (%d): %s", MAXPATHLEN, path);
291 			errno = EINVAL;
292 			return -1;
293 		}
294 
295 		pathbuf = estrdup(PG(open_basedir));
296 
297 		ptr = pathbuf;
298 
299 		while (ptr && *ptr) {
300 			end = strchr(ptr, DEFAULT_DIR_SEPARATOR);
301 			if (end != NULL) {
302 				*end = '\0';
303 				end++;
304 			}
305 
306 			if (php_check_specific_open_basedir(ptr, path) == 0) {
307 				efree(pathbuf);
308 				return 0;
309 			}
310 
311 			ptr = end;
312 		}
313 		if (warn) {
314 			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));
315 		}
316 		efree(pathbuf);
317 		errno = EPERM; /* we deny permission to open it */
318 		return -1;
319 	}
320 
321 	/* Nothing to check... */
322 	return 0;
323 }
324 /* }}} */
325 
326 /* {{{ php_fopen_and_set_opened_path */
327 static FILE *php_fopen_and_set_opened_path(const char *path, const char *mode, zend_string **opened_path)
328 {
329 	FILE *fp;
330 
331 	if (php_check_open_basedir((char *)path)) {
332 		return NULL;
333 	}
334 	fp = VCWD_FOPEN(path, mode);
335 	if (fp && opened_path) {
336 		//TODO :avoid reallocation
337 		char *tmp = expand_filepath_with_mode(path, NULL, NULL, 0, CWD_EXPAND);
338 		if (tmp) {
339 			*opened_path = zend_string_init(tmp, strlen(tmp), 0);
340 			efree(tmp);
341 		}
342 	}
343 	return fp;
344 }
345 /* }}} */
346 
347 /* {{{ php_fopen_primary_script */
348 PHPAPI int php_fopen_primary_script(zend_file_handle *file_handle)
349 {
350 	char *path_info;
351 	zend_string *filename = NULL;
352 	zend_string *resolved_path = NULL;
353 	size_t length;
354 	bool orig_display_errors;
355 
356 	memset(file_handle, 0, sizeof(zend_file_handle));
357 
358 	path_info = SG(request_info).request_uri;
359 #if HAVE_PWD_H
360 	if (PG(user_dir) && *PG(user_dir) && path_info && '/' == path_info[0] && '~' == path_info[1]) {
361 		char *s = strchr(path_info + 2, '/');
362 
363 		if (s) {			/* if there is no path name after the file, do not bother */
364 			char user[32];			/* to try open the directory */
365 
366 			length = s - (path_info + 2);
367 			if (length > sizeof(user) - 1) {
368 				length = sizeof(user) - 1;
369 			}
370 			memcpy(user, path_info + 2, length);
371 			user[length] = '\0';
372 
373 			struct passwd *pw;
374 #if defined(ZTS) && defined(HAVE_GETPWNAM_R) && defined(_SC_GETPW_R_SIZE_MAX)
375 			struct passwd pwstruc;
376 			long pwbuflen = sysconf(_SC_GETPW_R_SIZE_MAX);
377 			char *pwbuf;
378 			int err;
379 
380 			if (pwbuflen < 1) {
381 				pwbuflen = 1024;
382 			}
383 # if ZEND_DEBUG
384 			/* Test retry logic */
385 			pwbuflen = 1;
386 # endif
387 			pwbuf = emalloc(pwbuflen);
388 
389 try_again:
390 			err = getpwnam_r(user, &pwstruc, pwbuf, pwbuflen, &pw);
391 			if (err) {
392 				if (err == ERANGE) {
393 					pwbuflen *= 2;
394 					pwbuf = erealloc(pwbuf, pwbuflen);
395 					goto try_again;
396 				}
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 fall back 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 fall back 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 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