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