xref: /PHP-8.1/ext/standard/http_fopen_wrapper.c (revision 1ede3137)
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@php.net>                             |
14    |          Jim Winstead <jimw@php.net>                                 |
15    |          Hartmut Holzgraefe <hholzgra@php.net>                       |
16    |          Wez Furlong <wez@thebrainroom.com>                          |
17    |          Sara Golemon <pollita@php.net>                              |
18    +----------------------------------------------------------------------+
19  */
20 
21 #include "php.h"
22 #include "php_globals.h"
23 #include "php_streams.h"
24 #include "php_network.h"
25 #include "php_ini.h"
26 #include "ext/standard/basic_functions.h"
27 #include "zend_smart_str.h"
28 
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <fcntl.h>
35 
36 #ifdef PHP_WIN32
37 #define O_RDONLY _O_RDONLY
38 #include "win32/param.h"
39 #else
40 #include <sys/param.h>
41 #endif
42 
43 #include "php_standard.h"
44 
45 #include <sys/types.h>
46 #if HAVE_SYS_SOCKET_H
47 #include <sys/socket.h>
48 #endif
49 
50 #ifdef PHP_WIN32
51 #include <winsock2.h>
52 #else
53 #include <netinet/in.h>
54 #include <netdb.h>
55 #if HAVE_ARPA_INET_H
56 #include <arpa/inet.h>
57 #endif
58 #endif
59 
60 #if defined(PHP_WIN32) || defined(__riscos__)
61 #undef AF_UNIX
62 #endif
63 
64 #if defined(AF_UNIX)
65 #include <sys/un.h>
66 #endif
67 
68 #include "php_fopen_wrappers.h"
69 
70 #define HTTP_HEADER_BLOCK_SIZE		1024
71 #define PHP_URL_REDIRECT_MAX		20
72 #define HTTP_HEADER_USER_AGENT		1
73 #define HTTP_HEADER_HOST			2
74 #define HTTP_HEADER_AUTH			4
75 #define HTTP_HEADER_FROM			8
76 #define HTTP_HEADER_CONTENT_LENGTH	16
77 #define HTTP_HEADER_TYPE			32
78 #define HTTP_HEADER_CONNECTION		64
79 
80 #define HTTP_WRAPPER_HEADER_INIT    1
81 #define HTTP_WRAPPER_REDIRECTED     2
82 #define HTTP_WRAPPER_KEEP_METHOD    4
83 
strip_header(char * header_bag,char * lc_header_bag,const char * lc_header_name)84 static inline void strip_header(char *header_bag, char *lc_header_bag,
85 		const char *lc_header_name)
86 {
87 	char *lc_header_start = strstr(lc_header_bag, lc_header_name);
88 	if (lc_header_start
89 	&& (lc_header_start == lc_header_bag || *(lc_header_start-1) == '\n')
90 	) {
91 		char *header_start = header_bag + (lc_header_start - lc_header_bag);
92 		char *lc_eol = strchr(lc_header_start, '\n');
93 
94 		if (lc_eol) {
95 			char *eol = header_start + (lc_eol - lc_header_start);
96 			size_t eollen = strlen(lc_eol);
97 
98 			memmove(lc_header_start, lc_eol+1, eollen);
99 			memmove(header_start, eol+1, eollen);
100 		} else {
101 			*lc_header_start = '\0';
102 			*header_start = '\0';
103 		}
104 	}
105 }
106 
check_has_header(const char * headers,const char * header)107 static bool check_has_header(const char *headers, const char *header) {
108 	const char *s = headers;
109 	while ((s = strstr(s, header))) {
110 		if (s == headers || *(s-1) == '\n') {
111 			return 1;
112 		}
113 		s++;
114 	}
115 	return 0;
116 }
117 
php_stream_url_wrap_http_ex(php_stream_wrapper * wrapper,const char * path,const char * mode,int options,zend_string ** opened_path,php_stream_context * context,int redirect_max,int flags,zval * response_header STREAMS_DC)118 static php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper,
119 		const char *path, const char *mode, int options, zend_string **opened_path,
120 		php_stream_context *context, int redirect_max, int flags,
121 		zval *response_header STREAMS_DC) /* {{{ */
122 {
123 	php_stream *stream = NULL;
124 	php_url *resource = NULL;
125 	int use_ssl;
126 	int use_proxy = 0;
127 	zend_string *tmp = NULL;
128 	char *ua_str = NULL;
129 	zval *ua_zval = NULL, *tmpzval = NULL, ssl_proxy_peer_name;
130 	char location[HTTP_HEADER_BLOCK_SIZE];
131 	int reqok = 0;
132 	char *http_header_line = NULL;
133 	char tmp_line[128];
134 	size_t chunk_size = 0, file_size = 0;
135 	int eol_detect = 0;
136 	zend_string *transport_string;
137 	zend_string *errstr = NULL;
138 	int have_header = 0;
139 	bool request_fulluri = 0, ignore_errors = 0;
140 	struct timeval timeout;
141 	char *user_headers = NULL;
142 	int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0);
143 	int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0);
144 	int redirect_keep_method = ((flags & HTTP_WRAPPER_KEEP_METHOD) != 0);
145 	bool follow_location = 1;
146 	php_stream_filter *transfer_encoding = NULL;
147 	int response_code;
148 	smart_str req_buf = {0};
149 	bool custom_request_method;
150 
151 	tmp_line[0] = '\0';
152 
153 	if (redirect_max < 1) {
154 		php_stream_wrapper_log_error(wrapper, options, "Redirection limit reached, aborting");
155 		return NULL;
156 	}
157 
158 	resource = php_url_parse(path);
159 	if (resource == NULL) {
160 		return NULL;
161 	}
162 
163 	if (!zend_string_equals_literal_ci(resource->scheme, "http") &&
164 		!zend_string_equals_literal_ci(resource->scheme, "https")) {
165 		if (!context ||
166 			(tmpzval = php_stream_context_get_option(context, wrapper->wops->label, "proxy")) == NULL ||
167 			Z_TYPE_P(tmpzval) != IS_STRING ||
168 			Z_STRLEN_P(tmpzval) == 0) {
169 			php_url_free(resource);
170 			return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context);
171 		}
172 		/* Called from a non-http wrapper with http proxying requested (i.e. ftp) */
173 		request_fulluri = 1;
174 		use_ssl = 0;
175 		use_proxy = 1;
176 		transport_string = zend_string_copy(Z_STR_P(tmpzval));
177 	} else {
178 		/* Normal http request (possibly with proxy) */
179 
180 		if (strpbrk(mode, "awx+")) {
181 			php_stream_wrapper_log_error(wrapper, options, "HTTP wrapper does not support writeable connections");
182 			php_url_free(resource);
183 			return NULL;
184 		}
185 
186 		use_ssl = resource->scheme && (ZSTR_LEN(resource->scheme) > 4) && ZSTR_VAL(resource->scheme)[4] == 's';
187 		/* choose default ports */
188 		if (use_ssl && resource->port == 0)
189 			resource->port = 443;
190 		else if (resource->port == 0)
191 			resource->port = 80;
192 
193 		if (context &&
194 			(tmpzval = php_stream_context_get_option(context, wrapper->wops->label, "proxy")) != NULL &&
195 			Z_TYPE_P(tmpzval) == IS_STRING &&
196 			Z_STRLEN_P(tmpzval) > 0) {
197 			use_proxy = 1;
198 			transport_string = zend_string_copy(Z_STR_P(tmpzval));
199 		} else {
200 			transport_string = zend_strpprintf(0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", ZSTR_VAL(resource->host), resource->port);
201 		}
202 	}
203 
204 	if (context && (tmpzval = php_stream_context_get_option(context, wrapper->wops->label, "timeout")) != NULL) {
205 		double d = zval_get_double(tmpzval);
206 #ifndef PHP_WIN32
207 		timeout.tv_sec = (time_t) d;
208 		timeout.tv_usec = (size_t) ((d - timeout.tv_sec) * 1000000);
209 #else
210 		timeout.tv_sec = (long) d;
211 		timeout.tv_usec = (long) ((d - timeout.tv_sec) * 1000000);
212 #endif
213 	} else {
214 #ifndef PHP_WIN32
215 		timeout.tv_sec = FG(default_socket_timeout);
216 #else
217 		timeout.tv_sec = (long)FG(default_socket_timeout);
218 #endif
219 		timeout.tv_usec = 0;
220 	}
221 
222 	stream = php_stream_xport_create(ZSTR_VAL(transport_string), ZSTR_LEN(transport_string), options,
223 			STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT,
224 			NULL, &timeout, context, &errstr, NULL);
225 
226 	if (stream) {
227 		php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout);
228 	}
229 
230 	if (errstr) {
231 		php_stream_wrapper_log_error(wrapper, options, "%s", ZSTR_VAL(errstr));
232 		zend_string_release_ex(errstr, 0);
233 		errstr = NULL;
234 	}
235 
236 	zend_string_release(transport_string);
237 
238 	if (stream && use_proxy && use_ssl) {
239 		smart_str header = {0};
240 
241 		/* Set peer_name or name verification will try to use the proxy server name */
242 		if (!context || (tmpzval = php_stream_context_get_option(context, "ssl", "peer_name")) == NULL) {
243 			ZVAL_STR_COPY(&ssl_proxy_peer_name, resource->host);
244 			php_stream_context_set_option(PHP_STREAM_CONTEXT(stream), "ssl", "peer_name", &ssl_proxy_peer_name);
245 			zval_ptr_dtor(&ssl_proxy_peer_name);
246 		}
247 
248 		smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1);
249 		smart_str_appends(&header, ZSTR_VAL(resource->host));
250 		smart_str_appendc(&header, ':');
251 		smart_str_append_unsigned(&header, resource->port);
252 		smart_str_appendl(&header, " HTTP/1.0\r\n", sizeof(" HTTP/1.0\r\n")-1);
253 
254 	    /* check if we have Proxy-Authorization header */
255 		if (context && (tmpzval = php_stream_context_get_option(context, "http", "header")) != NULL) {
256 			char *s, *p;
257 
258 			if (Z_TYPE_P(tmpzval) == IS_ARRAY) {
259 				zval *tmpheader = NULL;
260 
261 				ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(tmpzval), tmpheader) {
262 					if (Z_TYPE_P(tmpheader) == IS_STRING) {
263 						s = Z_STRVAL_P(tmpheader);
264 						do {
265 							while (*s == ' ' || *s == '\t') s++;
266 							p = s;
267 							while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++;
268 							if (*p == ':') {
269 								p++;
270 								if (p - s == sizeof("Proxy-Authorization:") - 1 &&
271 								    zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1,
272 								        "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) {
273 									while (*p != 0 && *p != '\r' && *p !='\n') p++;
274 									smart_str_appendl(&header, s, p - s);
275 									smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
276 									goto finish;
277 								} else {
278 									while (*p != 0 && *p != '\r' && *p !='\n') p++;
279 								}
280 							}
281 							s = p;
282 							while (*s == '\r' || *s == '\n') s++;
283 						} while (*s != 0);
284 					}
285 				} ZEND_HASH_FOREACH_END();
286 			} else if (Z_TYPE_P(tmpzval) == IS_STRING && Z_STRLEN_P(tmpzval)) {
287 				s = Z_STRVAL_P(tmpzval);
288 				do {
289 					while (*s == ' ' || *s == '\t') s++;
290 					p = s;
291 					while (*p != 0 && *p != ':' && *p != '\r' && *p !='\n') p++;
292 					if (*p == ':') {
293 						p++;
294 						if (p - s == sizeof("Proxy-Authorization:") - 1 &&
295 						    zend_binary_strcasecmp(s, sizeof("Proxy-Authorization:") - 1,
296 						        "Proxy-Authorization:", sizeof("Proxy-Authorization:") - 1) == 0) {
297 							while (*p != 0 && *p != '\r' && *p !='\n') p++;
298 							smart_str_appendl(&header, s, p - s);
299 							smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
300 							goto finish;
301 						} else {
302 							while (*p != 0 && *p != '\r' && *p !='\n') p++;
303 						}
304 					}
305 					s = p;
306 					while (*s == '\r' || *s == '\n') s++;
307 				} while (*s != 0);
308 			}
309 		}
310 finish:
311 		smart_str_appendl(&header, "\r\n", sizeof("\r\n")-1);
312 
313 		if (php_stream_write(stream, ZSTR_VAL(header.s), ZSTR_LEN(header.s)) != ZSTR_LEN(header.s)) {
314 			php_stream_wrapper_log_error(wrapper, options, "Cannot connect to HTTPS server through proxy");
315 			php_stream_close(stream);
316 			stream = NULL;
317 		}
318 		smart_str_free(&header);
319 
320 		if (stream) {
321 			char header_line[HTTP_HEADER_BLOCK_SIZE];
322 
323 			/* get response header */
324 			while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL) {
325 				if (header_line[0] == '\n' ||
326 				    header_line[0] == '\r' ||
327 				    header_line[0] == '\0') {
328 				  break;
329 				}
330 			}
331 		}
332 
333 		/* enable SSL transport layer */
334 		if (stream) {
335 			if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL) < 0 ||
336 			    php_stream_xport_crypto_enable(stream, 1) < 0) {
337 				php_stream_wrapper_log_error(wrapper, options, "Cannot connect to HTTPS server through proxy");
338 				php_stream_close(stream);
339 				stream = NULL;
340 			}
341 		}
342 	}
343 
344 	if (stream == NULL)
345 		goto out;
346 
347 	/* avoid buffering issues while reading header */
348 	if (options & STREAM_WILL_CAST)
349 		chunk_size = php_stream_set_chunk_size(stream, 1);
350 
351 	/* avoid problems with auto-detecting when reading the headers -> the headers
352 	 * are always in canonical \r\n format */
353 	eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
354 	stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
355 
356 	php_stream_context_set(stream, context);
357 
358 	php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0);
359 
360 	if (header_init && context && (tmpzval = php_stream_context_get_option(context, "http", "max_redirects")) != NULL) {
361 		redirect_max = (int)zval_get_long(tmpzval);
362 	}
363 
364 	custom_request_method = 0;
365 	if (context && (tmpzval = php_stream_context_get_option(context, "http", "method")) != NULL) {
366 		if (Z_TYPE_P(tmpzval) == IS_STRING && Z_STRLEN_P(tmpzval) > 0) {
367 			/* As per the RFC, automatically redirected requests MUST NOT use other methods than
368 			 * GET and HEAD unless it can be confirmed by the user. */
369 			if (!redirected || redirect_keep_method
370 				|| zend_string_equals_literal(Z_STR_P(tmpzval), "GET")
371 				|| zend_string_equals_literal(Z_STR_P(tmpzval), "HEAD")
372 			) {
373 				custom_request_method = 1;
374 				smart_str_append(&req_buf, Z_STR_P(tmpzval));
375 				smart_str_appendc(&req_buf, ' ');
376 			}
377 		}
378 	}
379 
380 	if (!custom_request_method) {
381 		smart_str_appends(&req_buf, "GET ");
382 	}
383 
384 	/* Should we send the entire path in the request line, default to no. */
385 	if (!request_fulluri && context &&
386 		(tmpzval = php_stream_context_get_option(context, "http", "request_fulluri")) != NULL) {
387 		request_fulluri = zend_is_true(tmpzval);
388 	}
389 
390 	if (request_fulluri) {
391 		/* Ask for everything */
392 		smart_str_appends(&req_buf, path);
393 	} else {
394 		/* Send the traditional /path/to/file?query_string */
395 
396 		/* file */
397 		if (resource->path && ZSTR_LEN(resource->path)) {
398 			smart_str_appends(&req_buf, ZSTR_VAL(resource->path));
399 		} else {
400 			smart_str_appendc(&req_buf, '/');
401 		}
402 
403 		/* query string */
404 		if (resource->query) {
405 			smart_str_appendc(&req_buf, '?');
406 			smart_str_appends(&req_buf, ZSTR_VAL(resource->query));
407 		}
408 	}
409 
410 	/* protocol version we are speaking */
411 	if (context && (tmpzval = php_stream_context_get_option(context, "http", "protocol_version")) != NULL) {
412 		char *protocol_version;
413 		spprintf(&protocol_version, 0, "%.1F", zval_get_double(tmpzval));
414 
415 		smart_str_appends(&req_buf, " HTTP/");
416 		smart_str_appends(&req_buf, protocol_version);
417 		smart_str_appends(&req_buf, "\r\n");
418 		efree(protocol_version);
419 	} else {
420 		smart_str_appends(&req_buf, " HTTP/1.1\r\n");
421 	}
422 
423 	if (context && (tmpzval = php_stream_context_get_option(context, "http", "header")) != NULL) {
424 		tmp = NULL;
425 
426 		if (Z_TYPE_P(tmpzval) == IS_ARRAY) {
427 			zval *tmpheader = NULL;
428 			smart_str tmpstr = {0};
429 
430 			ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(tmpzval), tmpheader) {
431 				if (Z_TYPE_P(tmpheader) == IS_STRING) {
432 					smart_str_append(&tmpstr, Z_STR_P(tmpheader));
433 					smart_str_appendl(&tmpstr, "\r\n", sizeof("\r\n") - 1);
434 				}
435 			} ZEND_HASH_FOREACH_END();
436 			smart_str_0(&tmpstr);
437 			/* Remove newlines and spaces from start and end. there's at least one extra \r\n at the end that needs to go. */
438 			if (tmpstr.s) {
439 				tmp = php_trim(tmpstr.s, NULL, 0, 3);
440 				smart_str_free(&tmpstr);
441 			}
442 		} else if (Z_TYPE_P(tmpzval) == IS_STRING && Z_STRLEN_P(tmpzval)) {
443 			/* Remove newlines and spaces from start and end php_trim will estrndup() */
444 			tmp = php_trim(Z_STR_P(tmpzval), NULL, 0, 3);
445 		}
446 		if (tmp && ZSTR_LEN(tmp)) {
447 			char *s;
448 			char *t;
449 
450 			user_headers = estrndup(ZSTR_VAL(tmp), ZSTR_LEN(tmp));
451 
452 			if (ZSTR_IS_INTERNED(tmp)) {
453 				tmp = zend_string_init(ZSTR_VAL(tmp), ZSTR_LEN(tmp), 0);
454 			} else if (GC_REFCOUNT(tmp) > 1) {
455 				GC_DELREF(tmp);
456 				tmp = zend_string_init(ZSTR_VAL(tmp), ZSTR_LEN(tmp), 0);
457 			}
458 
459 			/* Make lowercase for easy comparison against 'standard' headers */
460 			zend_str_tolower(ZSTR_VAL(tmp), ZSTR_LEN(tmp));
461 			t = ZSTR_VAL(tmp);
462 
463 			if (!header_init && !redirect_keep_method) {
464 				/* strip POST headers on redirect */
465 				strip_header(user_headers, t, "content-length:");
466 				strip_header(user_headers, t, "content-type:");
467 			}
468 
469 			if (check_has_header(t, "user-agent:")) {
470 				have_header |= HTTP_HEADER_USER_AGENT;
471 			}
472 			if (check_has_header(t, "host:")) {
473 				have_header |= HTTP_HEADER_HOST;
474 			}
475 			if (check_has_header(t, "from:")) {
476 				have_header |= HTTP_HEADER_FROM;
477 			}
478 			if (check_has_header(t, "authorization:")) {
479 				have_header |= HTTP_HEADER_AUTH;
480 			}
481 			if (check_has_header(t, "content-length:")) {
482 				have_header |= HTTP_HEADER_CONTENT_LENGTH;
483 			}
484 			if (check_has_header(t, "content-type:")) {
485 				have_header |= HTTP_HEADER_TYPE;
486 			}
487 			if (check_has_header(t, "connection:")) {
488 				have_header |= HTTP_HEADER_CONNECTION;
489 			}
490 
491 			/* remove Proxy-Authorization header */
492 			if (use_proxy && use_ssl && (s = strstr(t, "proxy-authorization:")) &&
493 			    (s == t || *(s-1) == '\n')) {
494 				char *p = s + sizeof("proxy-authorization:") - 1;
495 
496 				while (s > t && (*(s-1) == ' ' || *(s-1) == '\t')) s--;
497 				while (*p != 0 && *p != '\r' && *p != '\n') p++;
498 				while (*p == '\r' || *p == '\n') p++;
499 				if (*p == 0) {
500 					if (s == t) {
501 						efree(user_headers);
502 						user_headers = NULL;
503 					} else {
504 						while (s > t && (*(s-1) == '\r' || *(s-1) == '\n')) s--;
505 						user_headers[s - t] = 0;
506 					}
507 				} else {
508 					memmove(user_headers + (s - t), user_headers + (p - t), strlen(p) + 1);
509 				}
510 			}
511 
512 		}
513 		if (tmp) {
514 			zend_string_release_ex(tmp, 0);
515 		}
516 	}
517 
518 	/* auth header if it was specified */
519 	if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user) {
520 		/* make scratch large enough to hold the whole URL (over-estimate) */
521 		size_t scratch_len = strlen(path) + 1;
522 		char *scratch = emalloc(scratch_len);
523 		zend_string *stmp;
524 
525 		/* decode the strings first */
526 		php_url_decode(ZSTR_VAL(resource->user), ZSTR_LEN(resource->user));
527 
528 		strcpy(scratch, ZSTR_VAL(resource->user));
529 		strcat(scratch, ":");
530 
531 		/* Note: password is optional! */
532 		if (resource->pass) {
533 			php_url_decode(ZSTR_VAL(resource->pass), ZSTR_LEN(resource->pass));
534 			strcat(scratch, ZSTR_VAL(resource->pass));
535 		}
536 
537 		stmp = php_base64_encode((unsigned char*)scratch, strlen(scratch));
538 
539 		smart_str_appends(&req_buf, "Authorization: Basic ");
540 		smart_str_appends(&req_buf, ZSTR_VAL(stmp));
541 		smart_str_appends(&req_buf, "\r\n");
542 
543 		php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0);
544 
545 		zend_string_free(stmp);
546 		efree(scratch);
547 	}
548 
549 	/* if the user has configured who they are, send a From: line */
550 	if (!(have_header & HTTP_HEADER_FROM) && FG(from_address)) {
551 		smart_str_appends(&req_buf, "From: ");
552 		smart_str_appends(&req_buf, FG(from_address));
553 		smart_str_appends(&req_buf, "\r\n");
554 	}
555 
556 	/* Send Host: header so name-based virtual hosts work */
557 	if ((have_header & HTTP_HEADER_HOST) == 0) {
558 		smart_str_appends(&req_buf, "Host: ");
559 		smart_str_appends(&req_buf, ZSTR_VAL(resource->host));
560 		if ((use_ssl && resource->port != 443 && resource->port != 0) ||
561 			(!use_ssl && resource->port != 80 && resource->port != 0)) {
562 			smart_str_appendc(&req_buf, ':');
563 			smart_str_append_unsigned(&req_buf, resource->port);
564 		}
565 		smart_str_appends(&req_buf, "\r\n");
566 	}
567 
568 	/* Send a Connection: close header to avoid hanging when the server
569 	 * interprets the RFC literally and establishes a keep-alive connection,
570 	 * unless the user specifically requests something else by specifying a
571 	 * Connection header in the context options. Send that header even for
572 	 * HTTP/1.0 to avoid issues when the server respond with a HTTP/1.1
573 	 * keep-alive response, which is the preferred response type. */
574 	if ((have_header & HTTP_HEADER_CONNECTION) == 0) {
575 		smart_str_appends(&req_buf, "Connection: close\r\n");
576 	}
577 
578 	if (context &&
579 	    (ua_zval = php_stream_context_get_option(context, "http", "user_agent")) != NULL &&
580 		Z_TYPE_P(ua_zval) == IS_STRING) {
581 		ua_str = Z_STRVAL_P(ua_zval);
582 	} else if (FG(user_agent)) {
583 		ua_str = FG(user_agent);
584 	}
585 
586 	if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) {
587 #define _UA_HEADER "User-Agent: %s\r\n"
588 		char *ua;
589 		size_t ua_len;
590 
591 		ua_len = sizeof(_UA_HEADER) + strlen(ua_str);
592 
593 		/* ensure the header is only sent if user_agent is not blank */
594 		if (ua_len > sizeof(_UA_HEADER)) {
595 			ua = emalloc(ua_len + 1);
596 			if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) {
597 				ua[ua_len] = 0;
598 				smart_str_appendl(&req_buf, ua, ua_len);
599 			} else {
600 				php_error_docref(NULL, E_WARNING, "Cannot construct User-agent header");
601 			}
602 			efree(ua);
603 		}
604 	}
605 
606 	if (user_headers) {
607 		/* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST
608 		 * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first.
609 		 */
610 		if (
611 				(header_init || redirect_keep_method) &&
612 				context &&
613 				!(have_header & HTTP_HEADER_CONTENT_LENGTH) &&
614 				(tmpzval = php_stream_context_get_option(context, "http", "content")) != NULL &&
615 				Z_TYPE_P(tmpzval) == IS_STRING && Z_STRLEN_P(tmpzval) > 0
616 		) {
617 			smart_str_appends(&req_buf, "Content-Length: ");
618 			smart_str_append_unsigned(&req_buf, Z_STRLEN_P(tmpzval));
619 			smart_str_appends(&req_buf, "\r\n");
620 			have_header |= HTTP_HEADER_CONTENT_LENGTH;
621 		}
622 
623 		smart_str_appends(&req_buf, user_headers);
624 		smart_str_appends(&req_buf, "\r\n");
625 		efree(user_headers);
626 	}
627 
628 	/* Request content, such as for POST requests */
629 	if ((header_init || redirect_keep_method) && context &&
630 		(tmpzval = php_stream_context_get_option(context, "http", "content")) != NULL &&
631 		Z_TYPE_P(tmpzval) == IS_STRING && Z_STRLEN_P(tmpzval) > 0) {
632 		if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) {
633 			smart_str_appends(&req_buf, "Content-Length: ");
634 			smart_str_append_unsigned(&req_buf, Z_STRLEN_P(tmpzval));
635 			smart_str_appends(&req_buf, "\r\n");
636 		}
637 		if (!(have_header & HTTP_HEADER_TYPE)) {
638 			smart_str_appends(&req_buf, "Content-Type: application/x-www-form-urlencoded\r\n");
639 			php_error_docref(NULL, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded");
640 		}
641 		smart_str_appends(&req_buf, "\r\n");
642 		smart_str_appendl(&req_buf, Z_STRVAL_P(tmpzval), Z_STRLEN_P(tmpzval));
643 	} else {
644 		smart_str_appends(&req_buf, "\r\n");
645 	}
646 
647 	/* send it */
648 	php_stream_write(stream, ZSTR_VAL(req_buf.s), ZSTR_LEN(req_buf.s));
649 
650 	location[0] = '\0';
651 
652 	if (Z_ISUNDEF_P(response_header)) {
653 		array_init(response_header);
654 	}
655 
656 	{
657 		/* get response header */
658 		size_t tmp_line_len;
659 		if (!php_stream_eof(stream) &&
660 			php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) {
661 			zval http_response;
662 
663 			if (tmp_line_len > 9) {
664 				response_code = atoi(tmp_line + 9);
665 			} else {
666 				response_code = 0;
667 			}
668 			if (context && NULL != (tmpzval = php_stream_context_get_option(context, "http", "ignore_errors"))) {
669 				ignore_errors = zend_is_true(tmpzval);
670 			}
671 			/* when we request only the header, don't fail even on error codes */
672 			if ((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) {
673 				reqok = 1;
674 			}
675 
676 			/* status codes of 1xx are "informational", and will be followed by a real response
677 			 * e.g "100 Continue". RFC 7231 states that unexpected 1xx status MUST be parsed,
678 			 * and MAY be ignored. As such, we need to skip ahead to the "real" status*/
679 			if (response_code >= 100 && response_code < 200 && response_code != 101) {
680 				/* consume lines until we find a line starting 'HTTP/1' */
681 				while (
682 					!php_stream_eof(stream)
683 					&& php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL
684 					&& ( tmp_line_len < sizeof("HTTP/1") - 1 || strncasecmp(tmp_line, "HTTP/1", sizeof("HTTP/1") - 1) )
685 				);
686 
687 				if (tmp_line_len > 9) {
688 					response_code = atoi(tmp_line + 9);
689 				} else {
690 					response_code = 0;
691 				}
692 			}
693 			/* all status codes in the 2xx range are defined by the specification as successful;
694 			 * all status codes in the 3xx range are for redirection, and so also should never
695 			 * fail */
696 			if (response_code >= 200 && response_code < 400) {
697 				reqok = 1;
698 			} else {
699 				switch(response_code) {
700 					case 403:
701 						php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT,
702 								tmp_line, response_code);
703 						break;
704 					default:
705 						/* safety net in the event tmp_line == NULL */
706 						if (!tmp_line_len) {
707 							tmp_line[0] = '\0';
708 						}
709 						php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE,
710 								tmp_line, response_code);
711 				}
712 			}
713 			if (tmp_line_len >= 1 && tmp_line[tmp_line_len - 1] == '\n') {
714 				--tmp_line_len;
715 				if (tmp_line_len >= 1 &&tmp_line[tmp_line_len - 1] == '\r') {
716 					--tmp_line_len;
717 				}
718 			} else {
719 				// read and discard rest of status line
720 				char *line = php_stream_get_line(stream, NULL, 0, NULL);
721 				efree(line);
722 			}
723 			ZVAL_STRINGL(&http_response, tmp_line, tmp_line_len);
724 			zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response);
725 		} else {
726 			php_stream_close(stream);
727 			stream = NULL;
728 			php_stream_wrapper_log_error(wrapper, options, "HTTP request failed!");
729 			goto out;
730 		}
731 	}
732 
733 	/* read past HTTP headers */
734 
735 	while (!php_stream_eof(stream)) {
736 		size_t http_header_line_length;
737 
738 		if (http_header_line != NULL) {
739 			efree(http_header_line);
740 		}
741 		if ((http_header_line = php_stream_get_line(stream, NULL, 0, &http_header_line_length)) && *http_header_line != '\n' && *http_header_line != '\r') {
742 			char *e = http_header_line + http_header_line_length - 1;
743 			char *http_header_value;
744 
745 			while (e >= http_header_line && (*e == '\n' || *e == '\r')) {
746 				e--;
747 			}
748 
749 			/* The primary definition of an HTTP header in RFC 7230 states:
750 			 * > Each header field consists of a case-insensitive field name followed
751 			 * > by a colon (":"), optional leading whitespace, the field value, and
752 			 * > optional trailing whitespace. */
753 
754 			/* Strip trailing whitespace */
755 			while (e >= http_header_line && (*e == ' ' || *e == '\t')) {
756 				e--;
757 			}
758 
759 			/* Terminate header line */
760 			e++;
761 			*e = '\0';
762 			http_header_line_length = e - http_header_line;
763 
764 			http_header_value = memchr(http_header_line, ':', http_header_line_length);
765 			if (http_header_value) {
766 				http_header_value++; /* Skip ':' */
767 
768 				/* Strip leading whitespace */
769 				while (http_header_value < e
770 						&& (*http_header_value == ' ' || *http_header_value == '\t')) {
771 					http_header_value++;
772 				}
773 			} else {
774 				/* There is no colon. Set the value to the end of the header line, which is
775 				 * effectively an empty string. */
776 				http_header_value = e;
777 			}
778 
779 			if (!strncasecmp(http_header_line, "Location:", sizeof("Location:")-1)) {
780 				if (context && (tmpzval = php_stream_context_get_option(context, "http", "follow_location")) != NULL) {
781 					follow_location = zval_is_true(tmpzval);
782 				} else if (!((response_code >= 300 && response_code < 304)
783 						|| 307 == response_code || 308 == response_code)) {
784 					/* we shouldn't redirect automatically
785 					if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307)
786 					see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1
787 					RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */
788 					follow_location = 0;
789 				}
790 				strlcpy(location, http_header_value, sizeof(location));
791 			} else if (!strncasecmp(http_header_line, "Content-Type:", sizeof("Content-Type:")-1)) {
792 				php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_value, 0);
793 			} else if (!strncasecmp(http_header_line, "Content-Length:", sizeof("Content-Length:")-1)) {
794 				file_size = atoi(http_header_value);
795 				php_stream_notify_file_size(context, file_size, http_header_line, 0);
796 			} else if (
797 				!strncasecmp(http_header_line, "Transfer-Encoding:", sizeof("Transfer-Encoding:")-1)
798 				&& !strncasecmp(http_header_value, "Chunked", sizeof("Chunked")-1)
799 			) {
800 
801 				/* create filter to decode response body */
802 				if (!(options & STREAM_ONLY_GET_HEADERS)) {
803 					zend_long decode = 1;
804 
805 					if (context && (tmpzval = php_stream_context_get_option(context, "http", "auto_decode")) != NULL) {
806 						decode = zend_is_true(tmpzval);
807 					}
808 					if (decode) {
809 						transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream));
810 						if (transfer_encoding) {
811 							/* don't store transfer-encodeing header */
812 							continue;
813 						}
814 					}
815 				}
816 			}
817 
818 			{
819 				zval http_header;
820 				ZVAL_STRINGL(&http_header, http_header_line, http_header_line_length);
821 				zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header);
822 			}
823 		} else {
824 			break;
825 		}
826 	}
827 
828 	if (!reqok || (location[0] != '\0' && follow_location)) {
829 		if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) {
830 			goto out;
831 		}
832 
833 		if (location[0] != '\0')
834 			php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);
835 
836 		php_stream_close(stream);
837 		stream = NULL;
838 
839 		if (transfer_encoding) {
840 			php_stream_filter_free(transfer_encoding);
841 			transfer_encoding = NULL;
842 		}
843 
844 		if (location[0] != '\0') {
845 
846 			char new_path[HTTP_HEADER_BLOCK_SIZE];
847 			char loc_path[HTTP_HEADER_BLOCK_SIZE];
848 
849 			*new_path='\0';
850 			if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) &&
851 							strncasecmp(location, "https://", sizeof("https://")-1) &&
852 							strncasecmp(location, "ftp://", sizeof("ftp://")-1) &&
853 							strncasecmp(location, "ftps://", sizeof("ftps://")-1)))
854 			{
855 				if (*location != '/') {
856 					if (*(location+1) != '\0' && resource->path) {
857 						char *s = strrchr(ZSTR_VAL(resource->path), '/');
858 						if (!s) {
859 							s = ZSTR_VAL(resource->path);
860 							if (!ZSTR_LEN(resource->path)) {
861 								zend_string_release_ex(resource->path, 0);
862 								resource->path = zend_string_init("/", 1, 0);
863 								s = ZSTR_VAL(resource->path);
864 							} else {
865 								*s = '/';
866 							}
867 						}
868 						s[1] = '\0';
869 						if (resource->path &&
870 							ZSTR_VAL(resource->path)[0] == '/' &&
871 							ZSTR_VAL(resource->path)[1] == '\0') {
872 							snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", ZSTR_VAL(resource->path), location);
873 						} else {
874 							snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", ZSTR_VAL(resource->path), location);
875 						}
876 					} else {
877 						snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location);
878 					}
879 				} else {
880 					strlcpy(loc_path, location, sizeof(loc_path));
881 				}
882 				if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {
883 					snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", ZSTR_VAL(resource->scheme), ZSTR_VAL(resource->host), resource->port, loc_path);
884 				} else {
885 					snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", ZSTR_VAL(resource->scheme), ZSTR_VAL(resource->host), loc_path);
886 				}
887 			} else {
888 				strlcpy(new_path, location, sizeof(new_path));
889 			}
890 
891 			php_url_free(resource);
892 			/* check for invalid redirection URLs */
893 			if ((resource = php_url_parse(new_path)) == NULL) {
894 				php_stream_wrapper_log_error(wrapper, options, "Invalid redirect URL! %s", new_path);
895 				goto out;
896 			}
897 
898 #define CHECK_FOR_CNTRL_CHARS(val) { \
899 	if (val) { \
900 		unsigned char *s, *e; \
901 		ZSTR_LEN(val) = php_url_decode(ZSTR_VAL(val), ZSTR_LEN(val)); \
902 		s = (unsigned char*)ZSTR_VAL(val); e = s + ZSTR_LEN(val); \
903 		while (s < e) { \
904 			if (iscntrl(*s)) { \
905 				php_stream_wrapper_log_error(wrapper, options, "Invalid redirect URL! %s", new_path); \
906 				goto out; \
907 			} \
908 			s++; \
909 		} \
910 	} \
911 }
912 			/* check for control characters in login, password & path */
913 			if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) {
914 				CHECK_FOR_CNTRL_CHARS(resource->user);
915 				CHECK_FOR_CNTRL_CHARS(resource->pass);
916 				CHECK_FOR_CNTRL_CHARS(resource->path);
917 			}
918 			int new_flags = HTTP_WRAPPER_REDIRECTED;
919 			if (response_code == 307 || response_code == 308) {
920 				/* RFC 7538 specifies that status code 308 does not allow changing the request method from POST to GET.
921 				 * RFC 7231 does the same for status code 307.
922 				 * To keep consistency between POST and PATCH requests, we'll also not change the request method from PATCH to GET, even though it's allowed it's not mandated by the RFC. */
923 				new_flags |= HTTP_WRAPPER_KEEP_METHOD;
924 			}
925 			stream = php_stream_url_wrap_http_ex(
926 				wrapper, new_path, mode, options, opened_path, context,
927 				--redirect_max, new_flags, response_header STREAMS_CC);
928 		} else {
929 			php_stream_wrapper_log_error(wrapper, options, "HTTP request failed! %s", tmp_line);
930 		}
931 	}
932 out:
933 
934 	smart_str_free(&req_buf);
935 
936 	if (http_header_line) {
937 		efree(http_header_line);
938 	}
939 
940 	if (resource) {
941 		php_url_free(resource);
942 	}
943 
944 	if (stream) {
945 		if (header_init) {
946 			ZVAL_COPY(&stream->wrapperdata, response_header);
947 		}
948 		php_stream_notify_progress_init(context, 0, file_size);
949 
950 		/* Restore original chunk size now that we're done with headers */
951 		if (options & STREAM_WILL_CAST)
952 			php_stream_set_chunk_size(stream, (int)chunk_size);
953 
954 		/* restore the users auto-detect-line-endings setting */
955 		stream->flags |= eol_detect;
956 
957 		/* as far as streams are concerned, we are now at the start of
958 		 * the stream */
959 		stream->position = 0;
960 
961 		/* restore mode */
962 		strlcpy(stream->mode, mode, sizeof(stream->mode));
963 
964 		if (transfer_encoding) {
965 			php_stream_filter_append(&stream->readfilters, transfer_encoding);
966 		}
967 
968 		/* It's possible that the server already sent in more data than just the headers.
969 		 * We account for this by adjusting the progress counter by the difference of
970 		 * already read header data and the body. */
971 		if (stream->writepos > stream->readpos) {
972 			php_stream_notify_progress_increment(context, stream->writepos - stream->readpos, 0);
973 		}
974 	}
975 
976 	return stream;
977 }
978 /* }}} */
979 
php_stream_url_wrap_http(php_stream_wrapper * wrapper,const char * path,const char * mode,int options,zend_string ** opened_path,php_stream_context * context STREAMS_DC)980 php_stream *php_stream_url_wrap_http(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, zend_string **opened_path, php_stream_context *context STREAMS_DC) /* {{{ */
981 {
982 	php_stream *stream;
983 	zval headers;
984 	ZVAL_UNDEF(&headers);
985 
986 	stream = php_stream_url_wrap_http_ex(
987 		wrapper, path, mode, options, opened_path, context,
988 		PHP_URL_REDIRECT_MAX, HTTP_WRAPPER_HEADER_INIT, &headers STREAMS_CC);
989 
990 	if (!Z_ISUNDEF(headers)) {
991 		if (FAILURE == zend_set_local_var_str(
992 				"http_response_header", sizeof("http_response_header")-1, &headers, 0)) {
993 			zval_ptr_dtor(&headers);
994 		}
995 	}
996 
997 	return stream;
998 }
999 /* }}} */
1000 
php_stream_http_stream_stat(php_stream_wrapper * wrapper,php_stream * stream,php_stream_statbuf * ssb)1001 static int php_stream_http_stream_stat(php_stream_wrapper *wrapper, php_stream *stream, php_stream_statbuf *ssb) /* {{{ */
1002 {
1003 	/* one day, we could fill in the details based on Date: and Content-Length:
1004 	 * headers.  For now, we return with a failure code to prevent the underlying
1005 	 * file's details from being used instead. */
1006 	return -1;
1007 }
1008 /* }}} */
1009 
1010 static const php_stream_wrapper_ops http_stream_wops = {
1011 	php_stream_url_wrap_http,
1012 	NULL, /* stream_close */
1013 	php_stream_http_stream_stat,
1014 	NULL, /* stat_url */
1015 	NULL, /* opendir */
1016 	"http",
1017 	NULL, /* unlink */
1018 	NULL, /* rename */
1019 	NULL, /* mkdir */
1020 	NULL, /* rmdir */
1021 	NULL
1022 };
1023 
1024 PHPAPI const php_stream_wrapper php_stream_http_wrapper = {
1025 	&http_stream_wops,
1026 	NULL,
1027 	1 /* is_url */
1028 };
1029