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