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 #ifdef 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 #ifdef 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 /* https://www.rfc-editor.org/rfc/rfc9110.html#name-content-length */
795 const char *ptr = http_header_value;
796 /* must contain only digits, no + or - symbols */
797 if (*ptr >= '0' && *ptr <= '9') {
798 char *endptr = NULL;
799 size_t parsed = ZEND_STRTOUL(ptr, &endptr, 10);
800 /* check whether there was no garbage in the header value and the conversion was successful */
801 if (endptr && !*endptr) {
802 /* truncate for 32-bit such that no negative file sizes occur */
803 file_size = MIN(parsed, ZEND_LONG_MAX);
804 php_stream_notify_file_size(context, file_size, http_header_line, 0);
805 }
806 }
807 } else if (
808 !strncasecmp(http_header_line, "Transfer-Encoding:", sizeof("Transfer-Encoding:")-1)
809 && !strncasecmp(http_header_value, "Chunked", sizeof("Chunked")-1)
810 ) {
811
812 /* create filter to decode response body */
813 if (!(options & STREAM_ONLY_GET_HEADERS)) {
814 zend_long decode = 1;
815
816 if (context && (tmpzval = php_stream_context_get_option(context, "http", "auto_decode")) != NULL) {
817 decode = zend_is_true(tmpzval);
818 }
819 if (decode) {
820 transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream));
821 if (transfer_encoding) {
822 /* don't store transfer-encodeing header */
823 continue;
824 }
825 }
826 }
827 }
828
829 {
830 zval http_header;
831 ZVAL_STRINGL(&http_header, http_header_line, http_header_line_length);
832 zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header);
833 }
834 } else {
835 break;
836 }
837 }
838
839 if (!reqok || (location[0] != '\0' && follow_location)) {
840 if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) {
841 goto out;
842 }
843
844 if (location[0] != '\0')
845 php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);
846
847 php_stream_close(stream);
848 stream = NULL;
849
850 if (transfer_encoding) {
851 php_stream_filter_free(transfer_encoding);
852 transfer_encoding = NULL;
853 }
854
855 if (location[0] != '\0') {
856
857 char new_path[HTTP_HEADER_BLOCK_SIZE];
858 char loc_path[HTTP_HEADER_BLOCK_SIZE];
859
860 *new_path='\0';
861 if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) &&
862 strncasecmp(location, "https://", sizeof("https://")-1) &&
863 strncasecmp(location, "ftp://", sizeof("ftp://")-1) &&
864 strncasecmp(location, "ftps://", sizeof("ftps://")-1)))
865 {
866 if (*location != '/') {
867 if (*(location+1) != '\0' && resource->path) {
868 char *s = strrchr(ZSTR_VAL(resource->path), '/');
869 if (!s) {
870 s = ZSTR_VAL(resource->path);
871 if (!ZSTR_LEN(resource->path)) {
872 zend_string_release_ex(resource->path, 0);
873 resource->path = zend_string_init("/", 1, 0);
874 s = ZSTR_VAL(resource->path);
875 } else {
876 *s = '/';
877 }
878 }
879 s[1] = '\0';
880 if (resource->path &&
881 ZSTR_VAL(resource->path)[0] == '/' &&
882 ZSTR_VAL(resource->path)[1] == '\0') {
883 snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", ZSTR_VAL(resource->path), location);
884 } else {
885 snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", ZSTR_VAL(resource->path), location);
886 }
887 } else {
888 snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location);
889 }
890 } else {
891 strlcpy(loc_path, location, sizeof(loc_path));
892 }
893 if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {
894 snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", ZSTR_VAL(resource->scheme), ZSTR_VAL(resource->host), resource->port, loc_path);
895 } else {
896 snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", ZSTR_VAL(resource->scheme), ZSTR_VAL(resource->host), loc_path);
897 }
898 } else {
899 strlcpy(new_path, location, sizeof(new_path));
900 }
901
902 php_url_free(resource);
903 /* check for invalid redirection URLs */
904 if ((resource = php_url_parse(new_path)) == NULL) {
905 php_stream_wrapper_log_error(wrapper, options, "Invalid redirect URL! %s", new_path);
906 goto out;
907 }
908
909 #define CHECK_FOR_CNTRL_CHARS(val) { \
910 if (val) { \
911 unsigned char *s, *e; \
912 ZSTR_LEN(val) = php_url_decode(ZSTR_VAL(val), ZSTR_LEN(val)); \
913 s = (unsigned char*)ZSTR_VAL(val); e = s + ZSTR_LEN(val); \
914 while (s < e) { \
915 if (iscntrl(*s)) { \
916 php_stream_wrapper_log_error(wrapper, options, "Invalid redirect URL! %s", new_path); \
917 goto out; \
918 } \
919 s++; \
920 } \
921 } \
922 }
923 /* check for control characters in login, password & path */
924 if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) {
925 CHECK_FOR_CNTRL_CHARS(resource->user);
926 CHECK_FOR_CNTRL_CHARS(resource->pass);
927 CHECK_FOR_CNTRL_CHARS(resource->path);
928 }
929 int new_flags = HTTP_WRAPPER_REDIRECTED;
930 if (response_code == 307 || response_code == 308) {
931 /* RFC 7538 specifies that status code 308 does not allow changing the request method from POST to GET.
932 * RFC 7231 does the same for status code 307.
933 * 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. */
934 new_flags |= HTTP_WRAPPER_KEEP_METHOD;
935 }
936 stream = php_stream_url_wrap_http_ex(
937 wrapper, new_path, mode, options, opened_path, context,
938 --redirect_max, new_flags, response_header STREAMS_CC);
939 } else {
940 php_stream_wrapper_log_error(wrapper, options, "HTTP request failed! %s", tmp_line);
941 }
942 }
943 out:
944
945 smart_str_free(&req_buf);
946
947 if (http_header_line) {
948 efree(http_header_line);
949 }
950
951 if (resource) {
952 php_url_free(resource);
953 }
954
955 if (stream) {
956 if (header_init) {
957 ZVAL_COPY(&stream->wrapperdata, response_header);
958 }
959 php_stream_notify_progress_init(context, 0, file_size);
960
961 /* Restore original chunk size now that we're done with headers */
962 if (options & STREAM_WILL_CAST)
963 php_stream_set_chunk_size(stream, (int)chunk_size);
964
965 /* restore the users auto-detect-line-endings setting */
966 stream->flags |= eol_detect;
967
968 /* as far as streams are concerned, we are now at the start of
969 * the stream */
970 stream->position = 0;
971
972 /* restore mode */
973 strlcpy(stream->mode, mode, sizeof(stream->mode));
974
975 if (transfer_encoding) {
976 php_stream_filter_append(&stream->readfilters, transfer_encoding);
977 }
978
979 /* It's possible that the server already sent in more data than just the headers.
980 * We account for this by adjusting the progress counter by the difference of
981 * already read header data and the body. */
982 if (stream->writepos > stream->readpos) {
983 php_stream_notify_progress_increment(context, stream->writepos - stream->readpos, 0);
984 }
985 }
986
987 return stream;
988 }
989 /* }}} */
990
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)991 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) /* {{{ */
992 {
993 php_stream *stream;
994 zval headers;
995 ZVAL_UNDEF(&headers);
996
997 stream = php_stream_url_wrap_http_ex(
998 wrapper, path, mode, options, opened_path, context,
999 PHP_URL_REDIRECT_MAX, HTTP_WRAPPER_HEADER_INIT, &headers STREAMS_CC);
1000
1001 if (!Z_ISUNDEF(headers)) {
1002 if (FAILURE == zend_set_local_var_str(
1003 "http_response_header", sizeof("http_response_header")-1, &headers, 0)) {
1004 zval_ptr_dtor(&headers);
1005 }
1006 }
1007
1008 return stream;
1009 }
1010 /* }}} */
1011
php_stream_http_stream_stat(php_stream_wrapper * wrapper,php_stream * stream,php_stream_statbuf * ssb)1012 static int php_stream_http_stream_stat(php_stream_wrapper *wrapper, php_stream *stream, php_stream_statbuf *ssb) /* {{{ */
1013 {
1014 /* one day, we could fill in the details based on Date: and Content-Length:
1015 * headers. For now, we return with a failure code to prevent the underlying
1016 * file's details from being used instead. */
1017 return -1;
1018 }
1019 /* }}} */
1020
1021 static const php_stream_wrapper_ops http_stream_wops = {
1022 php_stream_url_wrap_http,
1023 NULL, /* stream_close */
1024 php_stream_http_stream_stat,
1025 NULL, /* stat_url */
1026 NULL, /* opendir */
1027 "http",
1028 NULL, /* unlink */
1029 NULL, /* rename */
1030 NULL, /* mkdir */
1031 NULL, /* rmdir */
1032 NULL
1033 };
1034
1035 PHPAPI const php_stream_wrapper php_stream_http_wrapper = {
1036 &http_stream_wops,
1037 NULL,
1038 1 /* is_url */
1039 };
1040