xref: /PHP-7.2/ext/soap/php_http.c (revision 5f8c22d4)
1 /*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2018 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Brad Lafountain <rodif_bl@yahoo.com>                        |
16   |          Shane Caraveo <shane@caraveo.com>                           |
17   |          Dmitry Stogov <dmitry@zend.com>                             |
18   +----------------------------------------------------------------------+
19 */
20 /* $Id$ */
21 
22 #include "php_soap.h"
23 #include "ext/standard/base64.h"
24 #include "ext/standard/md5.h"
25 #include "ext/standard/php_random.h"
26 
27 static char *get_http_header_value(char *headers, char *type);
28 static zend_string *get_http_body(php_stream *socketd, int close, char *headers);
29 static zend_string *get_http_headers(php_stream *socketd);
30 
31 #define smart_str_append_const(str, const) \
32 	smart_str_appendl(str,const,sizeof(const)-1)
33 
34 /* Proxy HTTP Authentication */
proxy_authentication(zval * this_ptr,smart_str * soap_headers)35 int proxy_authentication(zval* this_ptr, smart_str* soap_headers)
36 {
37 	zval *login, *password;
38 
39 	if ((login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_proxy_login", sizeof("_proxy_login")-1)) != NULL &&
40 	    Z_TYPE_P(login) == IS_STRING) {
41 		zend_string *buf;
42 		smart_str auth = {0};
43 
44 		smart_str_appendl(&auth, Z_STRVAL_P(login), Z_STRLEN_P(login));
45 		smart_str_appendc(&auth, ':');
46 		if ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_proxy_password", sizeof("_proxy_password")-1)) != NULL &&
47 		    Z_TYPE_P(password) == IS_STRING) {
48 			smart_str_appendl(&auth, Z_STRVAL_P(password), Z_STRLEN_P(password));
49 		}
50 		smart_str_0(&auth);
51 		buf = php_base64_encode((unsigned char*)ZSTR_VAL(auth.s), ZSTR_LEN(auth.s));
52 		smart_str_append_const(soap_headers, "Proxy-Authorization: Basic ");
53 		smart_str_appendl(soap_headers, (char*)ZSTR_VAL(buf), ZSTR_LEN(buf));
54 		smart_str_append_const(soap_headers, "\r\n");
55 		zend_string_release(buf);
56 		smart_str_free(&auth);
57 		return 1;
58 	}
59 	return 0;
60 }
61 
62 /* HTTP Authentication */
basic_authentication(zval * this_ptr,smart_str * soap_headers)63 int basic_authentication(zval* this_ptr, smart_str* soap_headers)
64 {
65 	zval *login, *password;
66 
67 	if ((login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login")-1)) != NULL &&
68 	    Z_TYPE_P(login) == IS_STRING &&
69 	    !zend_hash_str_exists(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest")-1)) {
70 		zend_string* buf;
71 		smart_str auth = {0};
72 
73 		smart_str_appendl(&auth, Z_STRVAL_P(login), Z_STRLEN_P(login));
74 		smart_str_appendc(&auth, ':');
75 		if ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL &&
76 		    Z_TYPE_P(password) == IS_STRING) {
77 			smart_str_appendl(&auth, Z_STRVAL_P(password), Z_STRLEN_P(password));
78 		}
79 		smart_str_0(&auth);
80 		buf = php_base64_encode((unsigned char*)ZSTR_VAL(auth.s), ZSTR_LEN(auth.s));
81 		smart_str_append_const(soap_headers, "Authorization: Basic ");
82 		smart_str_appendl(soap_headers, (char*)ZSTR_VAL(buf), ZSTR_LEN(buf));
83 		smart_str_append_const(soap_headers, "\r\n");
84 		zend_string_release(buf);
85 		smart_str_free(&auth);
86 		return 1;
87 	}
88 	return 0;
89 }
90 
91 /* Additional HTTP headers */
http_context_headers(php_stream_context * context,zend_bool has_authorization,zend_bool has_proxy_authorization,zend_bool has_cookies,smart_str * soap_headers)92 void http_context_headers(php_stream_context* context,
93                           zend_bool has_authorization,
94                           zend_bool has_proxy_authorization,
95                           zend_bool has_cookies,
96                           smart_str* soap_headers)
97 {
98 	zval *tmp;
99 
100 	if (context &&
101 		(tmp = php_stream_context_get_option(context, "http", "header")) != NULL &&
102 		Z_TYPE_P(tmp) == IS_STRING && Z_STRLEN_P(tmp)) {
103 		char *s = Z_STRVAL_P(tmp);
104 		char *p;
105 		int name_len;
106 
107 		while (*s) {
108 			/* skip leading newlines and spaces */
109 			while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n') {
110 				s++;
111 			}
112 			/* extract header name */
113 			p = s;
114 			name_len = -1;
115 			while (*p) {
116 				if (*p == ':') {
117 					if (name_len < 0) name_len = p - s;
118 					break;
119 				} else if (*p == ' ' || *p == '\t') {
120 					if (name_len < 0) name_len = p - s;
121 				} else if (*p == '\r' || *p == '\n') {
122 					break;
123 				}
124 				p++;
125 			}
126 			if (*p == ':') {
127 				/* extract header value */
128 				while (*p && *p != '\r' && *p != '\n') {
129 					p++;
130 				}
131 				/* skip some predefined headers */
132 				if ((name_len != sizeof("host")-1 ||
133 				     strncasecmp(s, "host", sizeof("host")-1) != 0) &&
134 				    (name_len != sizeof("connection")-1 ||
135 				     strncasecmp(s, "connection", sizeof("connection")-1) != 0) &&
136 				    (name_len != sizeof("user-agent")-1 ||
137 				     strncasecmp(s, "user-agent", sizeof("user-agent")-1) != 0) &&
138 				    (name_len != sizeof("content-length")-1 ||
139 				     strncasecmp(s, "content-length", sizeof("content-length")-1) != 0) &&
140 				    (name_len != sizeof("content-type")-1 ||
141 				     strncasecmp(s, "content-type", sizeof("content-type")-1) != 0) &&
142 				    (!has_cookies ||
143 				     name_len != sizeof("cookie")-1 ||
144 				     strncasecmp(s, "cookie", sizeof("cookie")-1) != 0) &&
145 				    (!has_authorization ||
146 				     name_len != sizeof("authorization")-1 ||
147 				     strncasecmp(s, "authorization", sizeof("authorization")-1) != 0) &&
148 				    (!has_proxy_authorization ||
149 				     name_len != sizeof("proxy-authorization")-1 ||
150 				     strncasecmp(s, "proxy-authorization", sizeof("proxy-authorization")-1) != 0)) {
151 				    /* add header */
152 					smart_str_appendl(soap_headers, s, p-s);
153 					smart_str_append_const(soap_headers, "\r\n");
154 				}
155 			}
156 			s = (*p) ? (p + 1) : p;
157 		}
158 	}
159 }
160 
http_connect(zval * this_ptr,php_url * phpurl,int use_ssl,php_stream_context * context,int * use_proxy)161 static php_stream* http_connect(zval* this_ptr, php_url *phpurl, int use_ssl, php_stream_context *context, int *use_proxy)
162 {
163 	php_stream *stream;
164 	zval *proxy_host, *proxy_port, *tmp, ssl_proxy_peer_name;
165 	char *host;
166 	char *name;
167 	char *protocol;
168 	zend_long namelen;
169 	int port;
170 	int old_error_reporting;
171 	struct timeval tv;
172 	struct timeval *timeout = NULL;
173 
174 	if ((proxy_host = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_proxy_host", sizeof("_proxy_host")-1)) != NULL &&
175 	    Z_TYPE_P(proxy_host) == IS_STRING &&
176 	    (proxy_port = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_proxy_port", sizeof("_proxy_port")-1)) != NULL &&
177 	    Z_TYPE_P(proxy_port) == IS_LONG) {
178 		host = Z_STRVAL_P(proxy_host);
179 		port = Z_LVAL_P(proxy_port);
180 		*use_proxy = 1;
181 	} else {
182 		host = phpurl->host;
183 		port = phpurl->port;
184 	}
185 	if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_connection_timeout", sizeof("_connection_timeout")-1)) != NULL &&
186 	    Z_TYPE_P(tmp) == IS_LONG && Z_LVAL_P(tmp) > 0) {
187 	  tv.tv_sec = Z_LVAL_P(tmp);
188 	  tv.tv_usec = 0;
189 		timeout = &tv;
190 	}
191 
192 	old_error_reporting = EG(error_reporting);
193 	EG(error_reporting) &= ~(E_WARNING|E_NOTICE|E_USER_WARNING|E_USER_NOTICE);
194 
195 	/* Changed ternary operator to an if/else so that additional comparisons can be done on the ssl_method property */
196 	if (use_ssl && !*use_proxy) {
197 		if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_ssl_method", sizeof("_ssl_method")-1)) != NULL &&
198 			Z_TYPE_P(tmp) == IS_LONG) {
199 			/* uses constants declared in soap.c to determine ssl uri protocol */
200 			switch (Z_LVAL_P(tmp)) {
201 				case SOAP_SSL_METHOD_TLS:
202 					protocol = "tls";
203 					break;
204 
205 				case SOAP_SSL_METHOD_SSLv2:
206 					protocol = "sslv2";
207 					break;
208 
209 				case SOAP_SSL_METHOD_SSLv3:
210 					protocol = "sslv3";
211 					break;
212 
213 				case SOAP_SSL_METHOD_SSLv23:
214 					protocol = "ssl";
215 					break;
216 
217 				default:
218 					protocol = "ssl";
219 					break;
220 
221 			}
222 		} else {
223 			protocol = "ssl";
224 		}
225 	} else {
226 		protocol = "tcp";
227 	}
228 
229 	namelen = spprintf(&name, 0, "%s://%s:%d", protocol, host, port);
230 
231 	stream = php_stream_xport_create(name, namelen,
232 		REPORT_ERRORS,
233 		STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT,
234 		NULL /*persistent_id*/,
235 		timeout,
236 		context,
237 		NULL, NULL);
238 	efree(name);
239 
240 	/* SSL & proxy */
241 	if (stream && *use_proxy && use_ssl) {
242 		smart_str soap_headers = {0};
243 
244 		/* Set peer_name or name verification will try to use the proxy server name */
245 		if (!context || (tmp = php_stream_context_get_option(context, "ssl", "peer_name")) == NULL) {
246 			ZVAL_STRING(&ssl_proxy_peer_name, phpurl->host);
247 			php_stream_context_set_option(PHP_STREAM_CONTEXT(stream), "ssl", "peer_name", &ssl_proxy_peer_name);
248 			zval_ptr_dtor(&ssl_proxy_peer_name);
249 		}
250 
251 		smart_str_append_const(&soap_headers, "CONNECT ");
252 		smart_str_appends(&soap_headers, phpurl->host);
253 		smart_str_appendc(&soap_headers, ':');
254 		smart_str_append_unsigned(&soap_headers, phpurl->port);
255 		smart_str_append_const(&soap_headers, " HTTP/1.1\r\n");
256 		smart_str_append_const(&soap_headers, "Host: ");
257 		smart_str_appends(&soap_headers, phpurl->host);
258 		if (phpurl->port != 80) {
259 			smart_str_appendc(&soap_headers, ':');
260 			smart_str_append_unsigned(&soap_headers, phpurl->port);
261 		}
262 		smart_str_append_const(&soap_headers, "\r\n");
263 		proxy_authentication(this_ptr, &soap_headers);
264 		smart_str_append_const(&soap_headers, "\r\n");
265 		if (php_stream_write(stream, ZSTR_VAL(soap_headers.s), ZSTR_LEN(soap_headers.s)) != ZSTR_LEN(soap_headers.s)) {
266 			php_stream_close(stream);
267 			stream = NULL;
268 		}
269  	 	smart_str_free(&soap_headers);
270 
271  	 	if (stream) {
272 			zend_string *http_headers = get_http_headers(stream);
273 			if (http_headers) {
274 				zend_string_free(http_headers);
275 			} else {
276 				php_stream_close(stream);
277 				stream = NULL;
278 			}
279 		}
280 		/* enable SSL transport layer */
281 		if (stream) {
282 			/* if a stream is created without encryption, check to see if SSL method parameter is specified and use
283  			   proper encrypyion method based on constants defined in soap.c */
284 			int crypto_method = STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
285 			if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_ssl_method", sizeof("_ssl_method")-1)) != NULL &&
286 				Z_TYPE_P(tmp) == IS_LONG) {
287 				switch (Z_LVAL_P(tmp)) {
288 					case SOAP_SSL_METHOD_TLS:
289 						crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
290 						break;
291 
292 					case SOAP_SSL_METHOD_SSLv2:
293 						crypto_method = STREAM_CRYPTO_METHOD_SSLv2_CLIENT;
294 						break;
295 
296 					case SOAP_SSL_METHOD_SSLv3:
297 						crypto_method = STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
298 						break;
299 
300 					case SOAP_SSL_METHOD_SSLv23:
301 						crypto_method = STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
302 						break;
303 
304 					default:
305 						crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
306 						break;
307 				}
308 			}
309 			if (php_stream_xport_crypto_setup(stream, crypto_method, NULL) < 0 ||
310 			    php_stream_xport_crypto_enable(stream, 1) < 0) {
311 				php_stream_close(stream);
312 				stream = NULL;
313 			}
314 		}
315 	}
316 
317 	EG(error_reporting) = old_error_reporting;
318 	return stream;
319 }
320 
in_domain(const char * host,const char * domain)321 static int in_domain(const char *host, const char *domain)
322 {
323   if (domain[0] == '.') {
324     int l1 = strlen(host);
325     int l2 = strlen(domain);
326     if (l1 > l2) {
327     	return strcmp(host+l1-l2,domain) == 0;
328     } else {
329       return 0;
330     }
331   } else {
332     return strcmp(host,domain) == 0;
333   }
334 }
335 
make_http_soap_request(zval * this_ptr,zend_string * buf,char * location,char * soapaction,int soap_version,zval * return_value)336 int make_http_soap_request(zval        *this_ptr,
337                            zend_string *buf,
338                            char        *location,
339                            char        *soapaction,
340                            int          soap_version,
341                            zval        *return_value)
342 {
343 	zend_string *request;
344 	smart_str soap_headers = {0};
345 	smart_str soap_headers_z = {0};
346 	size_t err;
347 	php_url *phpurl = NULL;
348 	php_stream *stream;
349 	zval *trace, *tmp;
350 	int use_proxy = 0;
351 	int use_ssl;
352 	zend_string *http_body;
353 	char *content_type, *http_version, *cookie_itt;
354 	int http_close;
355 	zend_string *http_headers;
356 	char *connection;
357 	int http_1_1;
358 	int http_status;
359 	int content_type_xml = 0;
360 	zend_long redirect_max = 20;
361 	char *content_encoding;
362 	char *http_msg = NULL;
363 	zend_bool old_allow_url_fopen;
364 	php_stream_context *context = NULL;
365 	zend_bool has_authorization = 0;
366 	zend_bool has_proxy_authorization = 0;
367 	zend_bool has_cookies = 0;
368 
369 	if (this_ptr == NULL || Z_TYPE_P(this_ptr) != IS_OBJECT) {
370 		return FALSE;
371 	}
372 
373 	request = buf;
374 	/* Compress request */
375 	if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "compression", sizeof("compression")-1)) != NULL && Z_TYPE_P(tmp) == IS_LONG) {
376 		int level = Z_LVAL_P(tmp) & 0x0f;
377 		int kind  = Z_LVAL_P(tmp) & SOAP_COMPRESSION_DEFLATE;
378 
379 		if (level > 9) {level = 9;}
380 
381 	  if ((Z_LVAL_P(tmp) & SOAP_COMPRESSION_ACCEPT) != 0) {
382 			smart_str_append_const(&soap_headers_z,"Accept-Encoding: gzip, deflate\r\n");
383 	  }
384 	  if (level > 0) {
385 			zval func;
386 			zval retval;
387 			zval params[3];
388 			int n;
389 
390 			ZVAL_STR_COPY(&params[0], buf);
391 			ZVAL_LONG(&params[1], level);
392 			if (kind == SOAP_COMPRESSION_DEFLATE) {
393 				n = 2;
394 				ZVAL_STRING(&func, "gzcompress");
395 				smart_str_append_const(&soap_headers_z,"Content-Encoding: deflate\r\n");
396 			} else {
397 				n = 3;
398 				ZVAL_STRING(&func, "gzencode");
399 				smart_str_append_const(&soap_headers_z,"Content-Encoding: gzip\r\n");
400 				ZVAL_LONG(&params[2], 0x1f);
401 			}
402 			if (call_user_function(CG(function_table), (zval*)NULL, &func, &retval, n, params) == SUCCESS &&
403 			    Z_TYPE(retval) == IS_STRING) {
404 				zval_ptr_dtor(&params[0]);
405 				zval_ptr_dtor(&func);
406 				request = Z_STR(retval);
407 			} else {
408 				zval_ptr_dtor(&params[0]);
409 				zval_ptr_dtor(&func);
410 				if (request != buf) {
411 					zend_string_release(request);
412 				}
413 				smart_str_free(&soap_headers_z);
414 				return FALSE;
415 			}
416 	  }
417 	}
418 
419 	if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1)) != NULL) {
420 		php_stream_from_zval_no_verify(stream,tmp);
421 		if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1)) != NULL && Z_TYPE_P(tmp) == IS_LONG) {
422 			use_proxy = Z_LVAL_P(tmp);
423 		}
424 	} else {
425 		stream = NULL;
426 	}
427 
428 	if (location != NULL && location[0] != '\000') {
429 		phpurl = php_url_parse(location);
430 	}
431 
432 	if (NULL != (tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr),
433 			"_stream_context", sizeof("_stream_context")-1))) {
434 		context = php_stream_context_from_zval(tmp, 0);
435 	}
436 
437 	if (context &&
438 		(tmp = php_stream_context_get_option(context, "http", "max_redirects")) != NULL) {
439 		if (Z_TYPE_P(tmp) != IS_STRING || !is_numeric_string(Z_STRVAL_P(tmp), Z_STRLEN_P(tmp), &redirect_max, NULL, 1)) {
440 			if (Z_TYPE_P(tmp) == IS_LONG)
441 				redirect_max = Z_LVAL_P(tmp);
442 		}
443 	}
444 
445 try_again:
446 	if (phpurl == NULL || phpurl->host == NULL) {
447 	  if (phpurl != NULL) {php_url_free(phpurl);}
448 		if (request != buf) {
449 			zend_string_release(request);
450 		}
451 		add_soap_fault(this_ptr, "HTTP", "Unable to parse URL", NULL, NULL);
452 		smart_str_free(&soap_headers_z);
453 		return FALSE;
454 	}
455 
456 	use_ssl = 0;
457 	if (phpurl->scheme != NULL && strcmp(phpurl->scheme, "https") == 0) {
458 		use_ssl = 1;
459 	} else if (phpurl->scheme == NULL || strcmp(phpurl->scheme, "http") != 0) {
460 		php_url_free(phpurl);
461 		if (request != buf) {
462 			zend_string_release(request);
463 		}
464 		add_soap_fault(this_ptr, "HTTP", "Unknown protocol. Only http and https are allowed.", NULL, NULL);
465 		smart_str_free(&soap_headers_z);
466 		return FALSE;
467 	}
468 
469 	old_allow_url_fopen = PG(allow_url_fopen);
470 	PG(allow_url_fopen) = 1;
471 	if (use_ssl && php_stream_locate_url_wrapper("https://", NULL, STREAM_LOCATE_WRAPPERS_ONLY) == NULL) {
472 		php_url_free(phpurl);
473 		if (request != buf) {
474 			zend_string_release(request);
475 		}
476 		add_soap_fault(this_ptr, "HTTP", "SSL support is not available in this build", NULL, NULL);
477 		PG(allow_url_fopen) = old_allow_url_fopen;
478 		smart_str_free(&soap_headers_z);
479 		return FALSE;
480 	}
481 
482 	if (phpurl->port == 0) {
483 		phpurl->port = use_ssl ? 443 : 80;
484 	}
485 
486 	/* Check if request to the same host */
487 	if (stream != NULL) {
488 	  php_url *orig;
489 		if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1)) != NULL &&
490 		    (orig = (php_url *) zend_fetch_resource_ex(tmp, "httpurl", le_url)) != NULL &&
491 		    ((use_proxy && !use_ssl) ||
492 		     (((use_ssl && orig->scheme != NULL && strcmp(orig->scheme, "https") == 0) ||
493 		      (!use_ssl && orig->scheme == NULL) ||
494 		      (!use_ssl && strcmp(orig->scheme, "https") != 0)) &&
495 		     strcmp(orig->host, phpurl->host) == 0 &&
496 		     orig->port == phpurl->port))) {
497     } else {
498 			php_stream_close(stream);
499 			zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1);
500 			zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
501 			zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
502 			stream = NULL;
503 			use_proxy = 0;
504     }
505 	}
506 
507 	/* Check if keep-alive connection is still opened */
508 	if (stream != NULL && php_stream_eof(stream)) {
509 		php_stream_close(stream);
510 		zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1);
511 		zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
512 		zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
513 		stream = NULL;
514 		use_proxy = 0;
515 	}
516 
517 	if (!stream) {
518 		stream = http_connect(this_ptr, phpurl, use_ssl, context, &use_proxy);
519 		if (stream) {
520 			php_stream_auto_cleanup(stream);
521 			add_property_resource(this_ptr, "httpsocket", stream->res);
522 			GC_REFCOUNT(stream->res)++;
523 			add_property_long(this_ptr, "_use_proxy", use_proxy);
524 		} else {
525 			php_url_free(phpurl);
526 			if (request != buf) {
527 				zend_string_release(request);
528 			}
529 			add_soap_fault(this_ptr, "HTTP", "Could not connect to host", NULL, NULL);
530 			PG(allow_url_fopen) = old_allow_url_fopen;
531 			smart_str_free(&soap_headers_z);
532 			return FALSE;
533 		}
534 	}
535 	PG(allow_url_fopen) = old_allow_url_fopen;
536 
537 	if (stream) {
538 		zval *cookies, *login, *password;
539 		zend_resource *ret = zend_register_resource(phpurl, le_url);
540 
541 		add_property_resource(this_ptr, "httpurl", ret);
542 		GC_REFCOUNT(ret)++;
543 		/*zend_list_addref(ret);*/
544 
545 		if (context &&
546 		    (tmp = php_stream_context_get_option(context, "http", "protocol_version")) != NULL &&
547 		    Z_TYPE_P(tmp) == IS_DOUBLE &&
548 		    Z_DVAL_P(tmp) == 1.0) {
549 			http_1_1 = 0;
550 		} else {
551 			http_1_1 = 1;
552 		}
553 
554 		smart_str_append_const(&soap_headers, "POST ");
555 		if (use_proxy && !use_ssl) {
556 			smart_str_appends(&soap_headers, phpurl->scheme);
557 			smart_str_append_const(&soap_headers, "://");
558 			smart_str_appends(&soap_headers, phpurl->host);
559 			smart_str_appendc(&soap_headers, ':');
560 			smart_str_append_unsigned(&soap_headers, phpurl->port);
561 		}
562 		if (phpurl->path) {
563 			smart_str_appends(&soap_headers, phpurl->path);
564 		} else {
565 			smart_str_appendc(&soap_headers, '/');
566 		}
567 		if (phpurl->query) {
568 			smart_str_appendc(&soap_headers, '?');
569 			smart_str_appends(&soap_headers, phpurl->query);
570 		}
571 		if (phpurl->fragment) {
572 			smart_str_appendc(&soap_headers, '#');
573 			smart_str_appends(&soap_headers, phpurl->fragment);
574 		}
575 		if (http_1_1) {
576 			smart_str_append_const(&soap_headers, " HTTP/1.1\r\n");
577 		} else {
578 			smart_str_append_const(&soap_headers, " HTTP/1.0\r\n");
579 		}
580 		smart_str_append_const(&soap_headers, "Host: ");
581 		smart_str_appends(&soap_headers, phpurl->host);
582 		if (phpurl->port != (use_ssl?443:80)) {
583 			smart_str_appendc(&soap_headers, ':');
584 			smart_str_append_unsigned(&soap_headers, phpurl->port);
585 		}
586 		if (!http_1_1 ||
587 			((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_keep_alive", sizeof("_keep_alive")-1)) != NULL &&
588 			 (Z_TYPE_P(tmp) == IS_FALSE || (Z_TYPE_P(tmp) == IS_LONG && Z_LVAL_P(tmp) == 0)))) {
589 			smart_str_append_const(&soap_headers, "\r\n"
590 				"Connection: close\r\n");
591 		} else {
592 			smart_str_append_const(&soap_headers, "\r\n"
593 				"Connection: Keep-Alive\r\n");
594 		}
595 		if ((tmp = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_user_agent", sizeof("_user_agent")-1)) != NULL &&
596 		    Z_TYPE_P(tmp) == IS_STRING) {
597 			if (Z_STRLEN_P(tmp) > 0) {
598 				smart_str_append_const(&soap_headers, "User-Agent: ");
599 				smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
600 				smart_str_append_const(&soap_headers, "\r\n");
601 			}
602 		} else if (context &&
603 		           (tmp = php_stream_context_get_option(context, "http", "user_agent")) != NULL &&
604 		           Z_TYPE_P(tmp) == IS_STRING) {
605 			if (Z_STRLEN_P(tmp) > 0) {
606 				smart_str_append_const(&soap_headers, "User-Agent: ");
607 				smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
608 				smart_str_append_const(&soap_headers, "\r\n");
609 			}
610 		} else if (FG(user_agent)) {
611 			smart_str_append_const(&soap_headers, "User-Agent: ");
612 			smart_str_appends(&soap_headers, FG(user_agent));
613 			smart_str_append_const(&soap_headers, "\r\n");
614 		} else {
615 			smart_str_append_const(&soap_headers, "User-Agent: PHP-SOAP/"PHP_VERSION"\r\n");
616 		}
617 
618 		smart_str_append_smart_str(&soap_headers, &soap_headers_z);
619 
620 		if (soap_version == SOAP_1_2) {
621 			if (context &&
622 				(tmp = php_stream_context_get_option(context, "http", "content_type")) != NULL &&
623 				Z_TYPE_P(tmp) == IS_STRING &&
624 				Z_STRLEN_P(tmp) > 0
625 			) {
626 				smart_str_append_const(&soap_headers, "Content-Type: ");
627 				smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
628 			} else {
629 				smart_str_append_const(&soap_headers, "Content-Type: application/soap+xml; charset=utf-8");
630 			}
631 			if (soapaction) {
632 				smart_str_append_const(&soap_headers,"; action=\"");
633 				smart_str_appends(&soap_headers, soapaction);
634 				smart_str_append_const(&soap_headers,"\"");
635 			}
636 			smart_str_append_const(&soap_headers,"\r\n");
637 		} else {
638 			if (context &&
639 				(tmp = php_stream_context_get_option(context, "http", "content_type")) != NULL &&
640 				Z_TYPE_P(tmp) == IS_STRING &&
641 				Z_STRLEN_P(tmp) > 0
642 			) {
643 				smart_str_append_const(&soap_headers, "Content-Type: ");
644 				smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
645 				smart_str_append_const(&soap_headers, "\r\n");
646 			} else {
647 				smart_str_append_const(&soap_headers, "Content-Type: text/xml; charset=utf-8\r\n");
648 			}
649 			if (soapaction) {
650 				smart_str_append_const(&soap_headers, "SOAPAction: \"");
651 				smart_str_appends(&soap_headers, soapaction);
652 				smart_str_append_const(&soap_headers, "\"\r\n");
653 			}
654 		}
655 		smart_str_append_const(&soap_headers,"Content-Length: ");
656 		smart_str_append_long(&soap_headers, request->len);
657 		smart_str_append_const(&soap_headers, "\r\n");
658 
659 		/* HTTP Authentication */
660 		if ((login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login")-1)) != NULL &&
661 		    Z_TYPE_P(login) == IS_STRING) {
662 			zval *digest;
663 
664 			has_authorization = 1;
665 			if ((digest = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest")-1)) != NULL) {
666 				if (Z_TYPE_P(digest) == IS_ARRAY) {
667 					char          HA1[33], HA2[33], response[33], cnonce[33], nc[9];
668 					zend_long     nonce;
669 					PHP_MD5_CTX   md5ctx;
670 					unsigned char hash[16];
671 
672 					php_random_bytes_throw(&nonce, sizeof(nonce));
673 					nonce &= 0x7fffffff;
674 
675 					PHP_MD5Init(&md5ctx);
676 					snprintf(cnonce, sizeof(cnonce), ZEND_LONG_FMT, nonce);
677 					PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, strlen(cnonce));
678 					PHP_MD5Final(hash, &md5ctx);
679 					make_digest(cnonce, hash);
680 
681 					if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nc", sizeof("nc")-1)) != NULL &&
682 					    Z_TYPE_P(tmp) == IS_LONG) {
683 						Z_LVAL_P(tmp)++;
684 						snprintf(nc, sizeof(nc), "%08" ZEND_LONG_FMT_SPEC, Z_LVAL_P(tmp));
685 					} else {
686 						add_assoc_long(digest, "nc", 1);
687 						strcpy(nc, "00000001");
688 					}
689 
690 					PHP_MD5Init(&md5ctx);
691 					PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(login), Z_STRLEN_P(login));
692 					PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
693 					if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "realm", sizeof("realm")-1)) != NULL &&
694 					    Z_TYPE_P(tmp) == IS_STRING) {
695 						PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
696 					}
697 					PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
698 					if ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL &&
699 					    Z_TYPE_P(password) == IS_STRING) {
700 						PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(password), Z_STRLEN_P(password));
701 					}
702 					PHP_MD5Final(hash, &md5ctx);
703 					make_digest(HA1, hash);
704 					if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "algorithm", sizeof("algorithm")-1)) != NULL &&
705 					    Z_TYPE_P(tmp) == IS_STRING &&
706 					    Z_STRLEN_P(tmp) == sizeof("md5-sess")-1 &&
707 					    stricmp(Z_STRVAL_P(tmp), "md5-sess") == 0) {
708 						PHP_MD5Init(&md5ctx);
709 						PHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32);
710 						PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
711 						if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nonce", sizeof("nonce")-1)) != NULL &&
712 						    Z_TYPE_P(tmp) == IS_STRING) {
713 							PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
714 						}
715 						PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
716 						PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8);
717 						PHP_MD5Final(hash, &md5ctx);
718 						make_digest(HA1, hash);
719 					}
720 
721 					PHP_MD5Init(&md5ctx);
722 					PHP_MD5Update(&md5ctx, (unsigned char*)"POST:", sizeof("POST:")-1);
723 					if (phpurl->path) {
724 						PHP_MD5Update(&md5ctx, (unsigned char*)phpurl->path, strlen(phpurl->path));
725 					} else {
726 						PHP_MD5Update(&md5ctx, (unsigned char*)"/", 1);
727 					}
728 					if (phpurl->query) {
729 						PHP_MD5Update(&md5ctx, (unsigned char*)"?", 1);
730 						PHP_MD5Update(&md5ctx, (unsigned char*)phpurl->query, strlen(phpurl->query));
731 					}
732 
733 					PHP_MD5Final(hash, &md5ctx);
734 					make_digest(HA2, hash);
735 
736 					PHP_MD5Init(&md5ctx);
737 					PHP_MD5Update(&md5ctx, (unsigned char*)HA1, 32);
738 					PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
739 					if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nonce", sizeof("nonce")-1)) != NULL &&
740 					    Z_TYPE_P(tmp) == IS_STRING) {
741 						PHP_MD5Update(&md5ctx, (unsigned char*)Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
742 					}
743 					PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
744 					if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "qop", sizeof("qop")-1)) != NULL &&
745 					    Z_TYPE_P(tmp) == IS_STRING) {
746 						PHP_MD5Update(&md5ctx, (unsigned char*)nc, 8);
747 						PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
748 						PHP_MD5Update(&md5ctx, (unsigned char*)cnonce, 8);
749 						PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
750 						/* TODO: Support for qop="auth-int" */
751 						PHP_MD5Update(&md5ctx, (unsigned char*)"auth", sizeof("auth")-1);
752 						PHP_MD5Update(&md5ctx, (unsigned char*)":", 1);
753 					}
754 					PHP_MD5Update(&md5ctx, (unsigned char*)HA2, 32);
755 					PHP_MD5Final(hash, &md5ctx);
756 					make_digest(response, hash);
757 
758 					smart_str_append_const(&soap_headers, "Authorization: Digest username=\"");
759 					smart_str_appendl(&soap_headers, Z_STRVAL_P(login), Z_STRLEN_P(login));
760 					if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "realm", sizeof("realm")-1)) != NULL &&
761 					    Z_TYPE_P(tmp) == IS_STRING) {
762 						smart_str_append_const(&soap_headers, "\", realm=\"");
763 						smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
764 					}
765 				if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "nonce", sizeof("nonce")-1)) != NULL &&
766 					    Z_TYPE_P(tmp) == IS_STRING) {
767 						smart_str_append_const(&soap_headers, "\", nonce=\"");
768 						smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
769 					}
770 					smart_str_append_const(&soap_headers, "\", uri=\"");
771 					if (phpurl->path) {
772 						smart_str_appends(&soap_headers, phpurl->path);
773 					} else {
774 						smart_str_appendc(&soap_headers, '/');
775 					}
776 					if (phpurl->query) {
777 						smart_str_appendc(&soap_headers, '?');
778 						smart_str_appends(&soap_headers, phpurl->query);
779 					}
780 					if (phpurl->fragment) {
781 						smart_str_appendc(&soap_headers, '#');
782 						smart_str_appends(&soap_headers, phpurl->fragment);
783 					}
784 					if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "qop", sizeof("qop")-1)) != NULL &&
785 					    Z_TYPE_P(tmp) == IS_STRING) {
786 					/* TODO: Support for qop="auth-int" */
787 						smart_str_append_const(&soap_headers, "\", qop=\"auth");
788 						smart_str_append_const(&soap_headers, "\", nc=\"");
789 						smart_str_appendl(&soap_headers, nc, 8);
790 						smart_str_append_const(&soap_headers, "\", cnonce=\"");
791 						smart_str_appendl(&soap_headers, cnonce, 8);
792 					}
793 					smart_str_append_const(&soap_headers, "\", response=\"");
794 					smart_str_appendl(&soap_headers, response, 32);
795 					if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "opaque", sizeof("opaque")-1)) != NULL &&
796 					    Z_TYPE_P(tmp) == IS_STRING) {
797 						smart_str_append_const(&soap_headers, "\", opaque=\"");
798 						smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
799 					}
800 					if ((tmp = zend_hash_str_find(Z_ARRVAL_P(digest), "algorithm", sizeof("algorithm")-1)) != NULL &&
801 						Z_TYPE_P(tmp) == IS_STRING) {
802 						smart_str_append_const(&soap_headers, "\", algorithm=\"");
803 						smart_str_appendl(&soap_headers, Z_STRVAL_P(tmp), Z_STRLEN_P(tmp));
804 					}
805 					smart_str_append_const(&soap_headers, "\"\r\n");
806 				}
807 			} else {
808 				zend_string *buf;
809 
810 				smart_str auth = {0};
811 				smart_str_appendl(&auth, Z_STRVAL_P(login), Z_STRLEN_P(login));
812 				smart_str_appendc(&auth, ':');
813 				if ((password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL &&
814 				    Z_TYPE_P(password) == IS_STRING) {
815 					smart_str_appendl(&auth, Z_STRVAL_P(password), Z_STRLEN_P(password));
816 				}
817 				smart_str_0(&auth);
818 				buf = php_base64_encode((unsigned char*)ZSTR_VAL(auth.s), ZSTR_LEN(auth.s));
819 				smart_str_append_const(&soap_headers, "Authorization: Basic ");
820 				smart_str_appendl(&soap_headers, (char*)ZSTR_VAL(buf), ZSTR_LEN(buf));
821 				smart_str_append_const(&soap_headers, "\r\n");
822 				zend_string_release(buf);
823 				smart_str_free(&auth);
824 			}
825 		}
826 
827 		/* Proxy HTTP Authentication */
828 		if (use_proxy && !use_ssl) {
829 			has_proxy_authorization = proxy_authentication(this_ptr, &soap_headers);
830 		}
831 
832 		/* Send cookies along with request */
833 		if ((cookies = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_cookies", sizeof("_cookies")-1)) != NULL &&
834 		    Z_TYPE_P(cookies) == IS_ARRAY) {
835 			zval *data;
836 			zend_string *key;
837 			int i, n;
838 
839 			has_cookies = 1;
840 			n = zend_hash_num_elements(Z_ARRVAL_P(cookies));
841 			if (n > 0) {
842 				zend_hash_internal_pointer_reset(Z_ARRVAL_P(cookies));
843 				smart_str_append_const(&soap_headers, "Cookie: ");
844 				for (i = 0; i < n; i++) {
845 					zend_ulong numindx;
846 					int res = zend_hash_get_current_key(Z_ARRVAL_P(cookies), &key, &numindx);
847 					data = zend_hash_get_current_data(Z_ARRVAL_P(cookies));
848 
849 					if (res == HASH_KEY_IS_STRING && Z_TYPE_P(data) == IS_ARRAY) {
850 					  zval *value;
851 
852 						if ((value = zend_hash_index_find(Z_ARRVAL_P(data), 0)) != NULL &&
853 						    Z_TYPE_P(value) == IS_STRING) {
854 						  zval *tmp;
855 						  if (((tmp = zend_hash_index_find(Z_ARRVAL_P(data), 1)) == NULL ||
856 							   Z_TYPE_P(tmp) != IS_STRING ||
857 						       strncmp(phpurl->path?phpurl->path:"/",Z_STRVAL_P(tmp),Z_STRLEN_P(tmp)) == 0) &&
858 						      ((tmp = zend_hash_index_find(Z_ARRVAL_P(data), 2)) == NULL ||
859 							   Z_TYPE_P(tmp) != IS_STRING ||
860 						       in_domain(phpurl->host,Z_STRVAL_P(tmp))) &&
861 						      (use_ssl || (tmp = zend_hash_index_find(Z_ARRVAL_P(data), 3)) == NULL)) {
862 								smart_str_append(&soap_headers, key);
863 								smart_str_appendc(&soap_headers, '=');
864 								smart_str_append(&soap_headers, Z_STR_P(value));
865 								smart_str_appendc(&soap_headers, ';');
866 							}
867 						}
868 					}
869 					zend_hash_move_forward(Z_ARRVAL_P(cookies));
870 				}
871 				smart_str_append_const(&soap_headers, "\r\n");
872 			}
873 		}
874 
875 		http_context_headers(context, has_authorization, has_proxy_authorization, has_cookies, &soap_headers);
876 
877 		smart_str_append_const(&soap_headers, "\r\n");
878 		smart_str_0(&soap_headers);
879 		if ((trace = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "trace", sizeof("trace")-1)) != NULL &&
880 		    (Z_TYPE_P(trace) == IS_TRUE || (Z_TYPE_P(trace) == IS_LONG && Z_LVAL_P(trace) != 0))) {
881 			add_property_stringl(this_ptr, "__last_request_headers", ZSTR_VAL(soap_headers.s), ZSTR_LEN(soap_headers.s));
882 		}
883 		smart_str_appendl(&soap_headers, request->val, request->len);
884 		smart_str_0(&soap_headers);
885 
886 		err = php_stream_write(stream, ZSTR_VAL(soap_headers.s), ZSTR_LEN(soap_headers.s));
887 		if (err != ZSTR_LEN(soap_headers.s)) {
888 			if (request != buf) {
889 				zend_string_release(request);
890 			}
891 			php_stream_close(stream);
892 			zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpurl", sizeof("httpurl")-1);
893 			zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
894 			zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
895 			add_soap_fault(this_ptr, "HTTP", "Failed Sending HTTP SOAP request", NULL, NULL);
896 			smart_str_free(&soap_headers_z);
897 			return FALSE;
898 		}
899 		smart_str_free(&soap_headers);
900 	} else {
901 		add_soap_fault(this_ptr, "HTTP", "Failed to create stream??", NULL, NULL);
902 		smart_str_free(&soap_headers_z);
903 		return FALSE;
904 	}
905 
906 	if (!return_value) {
907 		php_stream_close(stream);
908 		zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
909 		zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
910 		smart_str_free(&soap_headers_z);
911 		return TRUE;
912 	}
913 
914 	do {
915 		http_headers = get_http_headers(stream);
916 		if (!http_headers) {
917 			if (request != buf) {
918 				zend_string_release(request);
919 			}
920 			php_stream_close(stream);
921 			zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
922 			zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
923 			add_soap_fault(this_ptr, "HTTP", "Error Fetching http headers", NULL, NULL);
924 			smart_str_free(&soap_headers_z);
925 			return FALSE;
926 		}
927 
928 		if ((trace = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "trace", sizeof("trace")-1)) != NULL &&
929 		    (Z_TYPE_P(trace) == IS_TRUE || (Z_TYPE_P(trace) == IS_LONG && Z_LVAL_P(trace) != 0))) {
930 			add_property_str(this_ptr, "__last_response_headers", zend_string_copy(http_headers));
931 		}
932 
933 		/* Check to see what HTTP status was sent */
934 		http_1_1 = 0;
935 		http_status = 0;
936 		http_version = get_http_header_value(ZSTR_VAL(http_headers), "HTTP/");
937 		if (http_version) {
938 			char *tmp;
939 
940 			if (!strncmp(http_version,"1.1", 3)) {
941 				http_1_1 = 1;
942 			}
943 
944 			tmp = strstr(http_version," ");
945 			if (tmp != NULL) {
946 				tmp++;
947 				http_status = atoi(tmp);
948 			}
949 			tmp = strstr(tmp," ");
950 			if (tmp != NULL) {
951 				tmp++;
952 				if (http_msg) {
953 					efree(http_msg);
954 				}
955 				http_msg = estrdup(tmp);
956 			}
957 			efree(http_version);
958 
959 			/* Try and get headers again */
960 			if (http_status == 100) {
961 				zend_string_release(http_headers);
962 			}
963 		}
964 	} while (http_status == 100);
965 
966 	/* Grab and send back every cookie */
967 
968 	/* Not going to worry about Path: because
969 	   we shouldn't be changing urls so path dont
970 	   matter too much
971 	*/
972 	cookie_itt = strstr(ZSTR_VAL(http_headers), "Set-Cookie: ");
973 	while (cookie_itt) {
974 		char *cookie;
975 		char *eqpos, *sempos;
976 		zval *cookies;
977 
978 		if ((cookies = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_cookies", sizeof("_cookies")-1)) == NULL ||
979 		    Z_TYPE_P(cookies) != IS_ARRAY) {
980 			zval tmp_cookies;
981 			array_init(&tmp_cookies);
982 			cookies = zend_hash_str_update(Z_OBJPROP_P(this_ptr), "_cookies", sizeof("_cookies")-1, &tmp_cookies);
983 		}
984 
985 		cookie = get_http_header_value(cookie_itt,"Set-Cookie: ");
986 
987 		eqpos = strstr(cookie, "=");
988 		sempos = strstr(cookie, ";");
989 		if (eqpos != NULL && (sempos == NULL || sempos > eqpos)) {
990 			smart_str name = {0};
991 			int cookie_len;
992 			zval zcookie;
993 
994 			if (sempos != NULL) {
995 				cookie_len = sempos-(eqpos+1);
996 			} else {
997 				cookie_len = strlen(cookie)-(eqpos-cookie)-1;
998 			}
999 
1000 			smart_str_appendl(&name, cookie, eqpos - cookie);
1001 			smart_str_0(&name);
1002 
1003 			array_init(&zcookie);
1004 			add_index_stringl(&zcookie, 0, eqpos + 1, cookie_len);
1005 
1006 			if (sempos != NULL) {
1007 				char *options = cookie + cookie_len+1;
1008 				while (*options) {
1009 					while (*options == ' ') {options++;}
1010 					sempos = strstr(options, ";");
1011 					if (strstr(options,"path=") == options) {
1012 						eqpos = options + sizeof("path=")-1;
1013 						add_index_stringl(&zcookie, 1, eqpos, sempos?(size_t)(sempos-eqpos):strlen(eqpos));
1014 					} else if (strstr(options,"domain=") == options) {
1015 						eqpos = options + sizeof("domain=")-1;
1016 						add_index_stringl(&zcookie, 2, eqpos, sempos?(size_t)(sempos-eqpos):strlen(eqpos));
1017 					} else if (strstr(options,"secure") == options) {
1018 						add_index_bool(&zcookie, 3, 1);
1019 					}
1020 					if (sempos != NULL) {
1021 						options = sempos+1;
1022 					} else {
1023 					  break;
1024 					}
1025 				}
1026 			}
1027 			if (!zend_hash_index_exists(Z_ARRVAL(zcookie), 1)) {
1028 				char *t = phpurl->path?phpurl->path:"/";
1029 				char *c = strrchr(t, '/');
1030 				if (c) {
1031 					add_index_stringl(&zcookie, 1, t, c-t);
1032 				}
1033 			}
1034 			if (!zend_hash_index_exists(Z_ARRVAL(zcookie), 2)) {
1035 				add_index_string(&zcookie, 2, phpurl->host);
1036 			}
1037 
1038 			zend_symtable_update(Z_ARRVAL_P(cookies), name.s, &zcookie);
1039 			smart_str_free(&name);
1040 		}
1041 
1042 		cookie_itt = strstr(cookie_itt + sizeof("Set-Cookie: "), "Set-Cookie: ");
1043 		efree(cookie);
1044 	}
1045 
1046 	/* See if the server requested a close */
1047 	if (http_1_1) {
1048 		http_close = FALSE;
1049 		if (use_proxy && !use_ssl) {
1050 			connection = get_http_header_value(ZSTR_VAL(http_headers), "Proxy-Connection: ");
1051 			if (connection) {
1052 				if (strncasecmp(connection, "close", sizeof("close")-1) == 0) {
1053 					http_close = TRUE;
1054 				}
1055 				efree(connection);
1056 			}
1057 		}
1058 		if (http_close == FALSE) {
1059 			connection = get_http_header_value(ZSTR_VAL(http_headers), "Connection: ");
1060 			if (connection) {
1061 				if (strncasecmp(connection, "close", sizeof("close")-1) == 0) {
1062 					http_close = TRUE;
1063 				}
1064 				efree(connection);
1065 			}
1066 		}
1067 	} else {
1068 		http_close = TRUE;
1069 		if (use_proxy && !use_ssl) {
1070 			connection = get_http_header_value(ZSTR_VAL(http_headers), "Proxy-Connection: ");
1071 			if (connection) {
1072 				if (strncasecmp(connection, "Keep-Alive", sizeof("Keep-Alive")-1) == 0) {
1073 					http_close = FALSE;
1074 				}
1075 				efree(connection);
1076 			}
1077 		}
1078 		if (http_close == TRUE) {
1079 			connection = get_http_header_value(ZSTR_VAL(http_headers), "Connection: ");
1080 			if (connection) {
1081 				if (strncasecmp(connection, "Keep-Alive", sizeof("Keep-Alive")-1) == 0) {
1082 					http_close = FALSE;
1083 				}
1084 				efree(connection);
1085 			}
1086 		}
1087 	}
1088 
1089 
1090 	http_body = get_http_body(stream, http_close, ZSTR_VAL(http_headers));
1091 	if (!http_body) {
1092 		if (request != buf) {
1093 			zend_string_release(request);
1094 		}
1095 		php_stream_close(stream);
1096 		zend_string_release(http_headers);
1097 		zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
1098 		zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
1099 		add_soap_fault(this_ptr, "HTTP", "Error Fetching http body, No Content-Length, connection closed or chunked data", NULL, NULL);
1100 		if (http_msg) {
1101 			efree(http_msg);
1102 		}
1103 		smart_str_free(&soap_headers_z);
1104 		return FALSE;
1105 	}
1106 
1107 	if (request != buf) {
1108 		zend_string_release(request);
1109 	}
1110 
1111 	if (http_close) {
1112 		php_stream_close(stream);
1113 		zend_hash_str_del(Z_OBJPROP_P(this_ptr), "httpsocket", sizeof("httpsocket")-1);
1114 		zend_hash_str_del(Z_OBJPROP_P(this_ptr), "_use_proxy", sizeof("_use_proxy")-1);
1115 		stream = NULL;
1116 	}
1117 
1118 	/* Process HTTP status codes */
1119 	if (http_status >= 300 && http_status < 400) {
1120 		char *loc;
1121 
1122 		if ((loc = get_http_header_value(ZSTR_VAL(http_headers), "Location: ")) != NULL) {
1123 			php_url *new_url  = php_url_parse(loc);
1124 
1125 			if (new_url != NULL) {
1126 				zend_string_release(http_headers);
1127 				zend_string_release(http_body);
1128 				efree(loc);
1129 				if (new_url->scheme == NULL && new_url->path != NULL) {
1130 					new_url->scheme = phpurl->scheme ? estrdup(phpurl->scheme) : NULL;
1131 					new_url->host = phpurl->host ? estrdup(phpurl->host) : NULL;
1132 					new_url->port = phpurl->port;
1133 					if (new_url->path && new_url->path[0] != '/') {
1134 						if (phpurl->path) {
1135 							char *t = phpurl->path;
1136 							char *p = strrchr(t, '/');
1137 							if (p) {
1138 								char *s = emalloc((p - t) + strlen(new_url->path) + 2);
1139 								strncpy(s, t, (p - t) + 1);
1140 								s[(p - t) + 1] = 0;
1141 								strcat(s, new_url->path);
1142 								efree(new_url->path);
1143 								new_url->path = s;
1144 							}
1145 						} else {
1146 							char *s = emalloc(strlen(new_url->path) + 2);
1147 							s[0] = '/'; s[1] = 0;
1148 							strcat(s, new_url->path);
1149 							efree(new_url->path);
1150 							new_url->path = s;
1151 						}
1152 					}
1153 				}
1154 				phpurl = new_url;
1155 
1156 				if (--redirect_max < 1) {
1157 					add_soap_fault(this_ptr, "HTTP", "Redirection limit reached, aborting", NULL, NULL);
1158 					smart_str_free(&soap_headers_z);
1159 					return FALSE;
1160 				}
1161 
1162 				goto try_again;
1163 			}
1164 		}
1165 	} else if (http_status == 401) {
1166 		/* Digest authentication */
1167 		zval *digest, *login, *password;
1168 		char *auth = get_http_header_value(ZSTR_VAL(http_headers), "WWW-Authenticate: ");
1169 
1170 		if (auth &&
1171 				strstr(auth, "Digest") == auth &&
1172 		    ((digest = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest")-1)) == NULL ||
1173 		     Z_TYPE_P(digest) != IS_ARRAY) &&
1174 		    (login = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login")-1)) != NULL &&
1175 		    Z_TYPE_P(login) == IS_STRING &&
1176 		    (password = zend_hash_str_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password")-1)) != NULL &&
1177 		    Z_TYPE_P(password) == IS_STRING) {
1178 			char *s;
1179 			zval digest;
1180 
1181 			ZVAL_UNDEF(&digest);
1182 			s = auth + sizeof("Digest")-1;
1183 			while (*s != '\0') {
1184 				char *name, *val;
1185 				while (*s == ' ') ++s;
1186 				name = s;
1187 				while (*s != '\0' && *s != '=') ++s;
1188 				if (*s == '=') {
1189 					*s = '\0';
1190 					++s;
1191 					if (*s == '"') {
1192 						++s;
1193 						val = s;
1194 						while (*s != '\0' && *s != '"') ++s;
1195 					} else {
1196 						val = s;
1197 						while (*s != '\0' && *s != ' ' && *s != ',') ++s;
1198 					}
1199 					if (*s != '\0') {
1200 						if (*s != ',') {
1201 							*s = '\0';
1202 							++s;
1203 							while (*s != '\0' && *s != ',') ++s;
1204 							if (*s != '\0') ++s;
1205 						} else {
1206 							*s = '\0';
1207 							++s;
1208 						}
1209 					}
1210 					if (Z_TYPE(digest) == IS_UNDEF) {
1211 						array_init(&digest);
1212 					}
1213 					add_assoc_string(&digest, name, val);
1214 				}
1215 			}
1216 
1217 			if (Z_TYPE(digest) != IS_UNDEF) {
1218 				php_url *new_url  = emalloc(sizeof(php_url));
1219 
1220 				Z_DELREF(digest);
1221 				add_property_zval_ex(this_ptr, "_digest", sizeof("_digest")-1, &digest);
1222 
1223 				*new_url = *phpurl;
1224 				if (phpurl->scheme) phpurl->scheme = estrdup(phpurl->scheme);
1225 				if (phpurl->user) phpurl->user = estrdup(phpurl->user);
1226 				if (phpurl->pass) phpurl->pass = estrdup(phpurl->pass);
1227 				if (phpurl->host) phpurl->host = estrdup(phpurl->host);
1228 				if (phpurl->path) phpurl->path = estrdup(phpurl->path);
1229 				if (phpurl->query) phpurl->query = estrdup(phpurl->query);
1230 				if (phpurl->fragment) phpurl->fragment = estrdup(phpurl->fragment);
1231 				phpurl = new_url;
1232 
1233 				efree(auth);
1234 				zend_string_release(http_headers);
1235 				zend_string_release(http_body);
1236 
1237 				goto try_again;
1238 			}
1239 		}
1240 		if (auth) efree(auth);
1241 	}
1242 	smart_str_free(&soap_headers_z);
1243 
1244 	/* Check and see if the server even sent a xml document */
1245 	content_type = get_http_header_value(ZSTR_VAL(http_headers), "Content-Type: ");
1246 	if (content_type) {
1247 		char *pos = NULL;
1248 		int cmplen;
1249 		pos = strstr(content_type,";");
1250 		if (pos != NULL) {
1251 			cmplen = pos - content_type;
1252 		} else {
1253 			cmplen = strlen(content_type);
1254 		}
1255 		if (strncmp(content_type, "text/xml", cmplen) == 0 ||
1256 		    strncmp(content_type, "application/soap+xml", cmplen) == 0) {
1257 			content_type_xml = 1;
1258 /*
1259 			if (strncmp(http_body, "<?xml", 5)) {
1260 				zval *err;
1261 				MAKE_STD_ZVAL(err);
1262 				ZVAL_STRINGL(err, http_body, http_body_size, 1);
1263 				add_soap_fault(this_ptr, "HTTP", "Didn't receive an xml document", NULL, err);
1264 				efree(content_type);
1265 				zend_string_release(http_headers);
1266 				efree(http_body);
1267 				return FALSE;
1268 			}
1269 */
1270 		}
1271 		efree(content_type);
1272 	}
1273 
1274 	/* Decompress response */
1275 	content_encoding = get_http_header_value(ZSTR_VAL(http_headers), "Content-Encoding: ");
1276 	if (content_encoding) {
1277 		zval func;
1278 		zval retval;
1279 		zval params[1];
1280 
1281 		if ((strcmp(content_encoding,"gzip") == 0 ||
1282 		     strcmp(content_encoding,"x-gzip") == 0) &&
1283 		     zend_hash_str_exists(EG(function_table), "gzinflate", sizeof("gzinflate")-1)) {
1284 			ZVAL_STRING(&func, "gzinflate");
1285 			ZVAL_STRINGL(&params[0], http_body->val+10, http_body->len-10);
1286 		} else if (strcmp(content_encoding,"deflate") == 0 &&
1287 		           zend_hash_str_exists(EG(function_table), "gzuncompress", sizeof("gzuncompress")-1)) {
1288 			ZVAL_STRING(&func, "gzuncompress");
1289 			ZVAL_STR_COPY(&params[0], http_body);
1290 		} else {
1291 			efree(content_encoding);
1292 			zend_string_release(http_headers);
1293 			zend_string_release(http_body);
1294 			if (http_msg) {
1295 				efree(http_msg);
1296 			}
1297 			add_soap_fault(this_ptr, "HTTP", "Unknown Content-Encoding", NULL, NULL);
1298 			return FALSE;
1299 		}
1300 		if (call_user_function(CG(function_table), (zval*)NULL, &func, &retval, 1, params) == SUCCESS &&
1301 		    Z_TYPE(retval) == IS_STRING) {
1302 			zval_ptr_dtor(&params[0]);
1303 			zval_ptr_dtor(&func);
1304 			zend_string_release(http_body);
1305 			ZVAL_COPY_VALUE(return_value, &retval);
1306 		} else {
1307 			zval_ptr_dtor(&params[0]);
1308 			zval_ptr_dtor(&func);
1309 			efree(content_encoding);
1310 			zend_string_release(http_headers);
1311 			zend_string_release(http_body);
1312 			add_soap_fault(this_ptr, "HTTP", "Can't uncompress compressed response", NULL, NULL);
1313 			if (http_msg) {
1314 				efree(http_msg);
1315 			}
1316 			return FALSE;
1317 		}
1318 		efree(content_encoding);
1319 	} else {
1320 		ZVAL_STR(return_value, http_body);
1321 	}
1322 
1323 	zend_string_release(http_headers);
1324 
1325 	if (http_status >= 400) {
1326 		int error = 0;
1327 
1328 		if (Z_STRLEN_P(return_value) == 0) {
1329 			error = 1;
1330 		} else if (Z_STRLEN_P(return_value) > 0) {
1331 			if (!content_type_xml) {
1332 				char *s = Z_STRVAL_P(return_value);
1333 
1334 				while (*s != '\0' && *s < ' ') {
1335 					s++;
1336 				}
1337 				if (strncmp(s, "<?xml", 5)) {
1338 					error = 1;
1339 				}
1340 			}
1341 		}
1342 
1343 		if (error) {
1344 			zval_ptr_dtor(return_value);
1345 			ZVAL_UNDEF(return_value);
1346 			add_soap_fault(this_ptr, "HTTP", http_msg, NULL, NULL);
1347 			efree(http_msg);
1348 			return FALSE;
1349 		}
1350 	}
1351 
1352 	if (http_msg) {
1353 		efree(http_msg);
1354 	}
1355 
1356 	return TRUE;
1357 }
1358 
get_http_header_value(char * headers,char * type)1359 static char *get_http_header_value(char *headers, char *type)
1360 {
1361 	char *pos, *tmp = NULL;
1362 	int typelen, headerslen;
1363 
1364 	typelen = strlen(type);
1365 	headerslen = strlen(headers);
1366 
1367 	/* header `titles' can be lower case, or any case combination, according
1368 	 * to the various RFC's. */
1369 	pos = headers;
1370 	do {
1371 		/* start of buffer or start of line */
1372 		if (strncasecmp(pos, type, typelen) == 0) {
1373 			char *eol;
1374 
1375 			/* match */
1376 			tmp = pos + typelen;
1377 			eol = strchr(tmp, '\n');
1378 			if (eol == NULL) {
1379 				eol = headers + headerslen;
1380 			} else if (eol > tmp && *(eol-1) == '\r') {
1381 				eol--;
1382 			}
1383 			return estrndup(tmp, eol - tmp);
1384 		}
1385 
1386 		/* find next line */
1387 		pos = strchr(pos, '\n');
1388 		if (pos) {
1389 			pos++;
1390 		}
1391 
1392 	} while (pos);
1393 
1394 	return NULL;
1395 }
1396 
get_http_body(php_stream * stream,int close,char * headers)1397 static zend_string* get_http_body(php_stream *stream, int close, char *headers)
1398 {
1399 	zend_string *http_buf = NULL;
1400 	char *header;
1401 	int header_close = close, header_chunked = 0, header_length = 0, http_buf_size = 0;
1402 
1403 	if (!close) {
1404 		header = get_http_header_value(headers, "Connection: ");
1405 		if (header) {
1406 			if(!strncasecmp(header, "close", sizeof("close")-1)) header_close = 1;
1407 			efree(header);
1408 		}
1409 	}
1410 	header = get_http_header_value(headers, "Transfer-Encoding: ");
1411 	if (header) {
1412 		if(!strncasecmp(header, "chunked", sizeof("chunked")-1)) header_chunked = 1;
1413 		efree(header);
1414 	}
1415 	header = get_http_header_value(headers, "Content-Length: ");
1416 	if (header) {
1417 		header_length = atoi(header);
1418 		efree(header);
1419 		if (!header_length && !header_chunked) {
1420 			/* Empty response */
1421 			return ZSTR_EMPTY_ALLOC();
1422 		}
1423 	}
1424 
1425 	if (header_chunked) {
1426 		char ch, done, headerbuf[8192];
1427 
1428 		done = FALSE;
1429 
1430 		while (!done) {
1431 			int buf_size = 0;
1432 
1433 			php_stream_gets(stream, headerbuf, sizeof(headerbuf));
1434 			if (sscanf(headerbuf, "%x", &buf_size) > 0 ) {
1435 				if (buf_size > 0) {
1436 					int len_size = 0;
1437 
1438 					if (http_buf_size + buf_size + 1 < 0) {
1439 						if (http_buf) {
1440 							zend_string_release(http_buf);
1441 						}
1442 						return NULL;
1443 					}
1444 
1445 					if (http_buf) {
1446 						http_buf = zend_string_realloc(http_buf, http_buf_size + buf_size, 0);
1447 					} else {
1448 						http_buf = zend_string_alloc(buf_size, 0);
1449 					}
1450 
1451 					while (len_size < buf_size) {
1452 						int len_read = php_stream_read(stream, http_buf->val + http_buf_size, buf_size - len_size);
1453 						if (len_read <= 0) {
1454 							/* Error or EOF */
1455 							done = TRUE;
1456 						  break;
1457 						}
1458 						len_size += len_read;
1459 	 					http_buf_size += len_read;
1460  					}
1461 
1462 					/* Eat up '\r' '\n' */
1463 					ch = php_stream_getc(stream);
1464 					if (ch == '\r') {
1465 						ch = php_stream_getc(stream);
1466 					}
1467 					if (ch != '\n') {
1468 						/* Somthing wrong in chunked encoding */
1469 						if (http_buf) {
1470 							zend_string_release(http_buf);
1471 						}
1472 						return NULL;
1473 					}
1474  				}
1475 			} else {
1476 				/* Somthing wrong in chunked encoding */
1477 				if (http_buf) {
1478 					zend_string_release(http_buf);
1479 				}
1480 				return NULL;
1481 			}
1482 			if (buf_size == 0) {
1483 				done = TRUE;
1484 			}
1485 		}
1486 
1487 		/* Ignore trailer headers */
1488 		while (1) {
1489 			if (!php_stream_gets(stream, headerbuf, sizeof(headerbuf))) {
1490 				break;
1491 			}
1492 
1493 			if ((headerbuf[0] == '\r' && headerbuf[1] == '\n') ||
1494 			    (headerbuf[0] == '\n')) {
1495 				/* empty line marks end of headers */
1496 				break;
1497 			}
1498 		}
1499 
1500 		if (http_buf == NULL) {
1501 			return ZSTR_EMPTY_ALLOC();
1502 		}
1503 
1504 	} else if (header_length) {
1505 		if (header_length < 0 || header_length >= INT_MAX) {
1506 			return NULL;
1507 		}
1508 		http_buf = zend_string_alloc(header_length, 0);
1509 		while (http_buf_size < header_length) {
1510 			int len_read = php_stream_read(stream, http_buf->val + http_buf_size, header_length - http_buf_size);
1511 			if (len_read <= 0) {
1512 				break;
1513 			}
1514 			http_buf_size += len_read;
1515 		}
1516 	} else if (header_close) {
1517 		do {
1518 			int len_read;
1519 			if (http_buf) {
1520 				http_buf = zend_string_realloc(http_buf, http_buf_size + 4096, 0);
1521 			} else {
1522 				http_buf = zend_string_alloc(4096, 0);
1523 			}
1524 			len_read = php_stream_read(stream, http_buf->val + http_buf_size, 4096);
1525 			if (len_read > 0) {
1526 				http_buf_size += len_read;
1527 			}
1528 		} while(!php_stream_eof(stream));
1529 	} else {
1530 		return NULL;
1531 	}
1532 
1533 	http_buf->val[http_buf_size] = '\0';
1534 	http_buf->len = http_buf_size;
1535 	return http_buf;
1536 }
1537 
get_http_headers(php_stream * stream)1538 static zend_string *get_http_headers(php_stream *stream)
1539 {
1540 	smart_str tmp_response = {0};
1541 	char headerbuf[8192];
1542 
1543 	while (php_stream_gets(stream, headerbuf, sizeof(headerbuf))) {
1544 		if ((headerbuf[0] == '\r' && headerbuf[1] == '\n') ||
1545 		    (headerbuf[0] == '\n')) {
1546 			/* empty line marks end of headers */
1547 			smart_str_0(&tmp_response);
1548 			return tmp_response.s;
1549 		}
1550 
1551 		/* add header to collection */
1552 		smart_str_appends(&tmp_response, headerbuf);
1553 	}
1554 
1555 	smart_str_free(&tmp_response);
1556 	return NULL;
1557 }
1558 /*
1559  * Local variables:
1560  * tab-width: 4
1561  * c-basic-offset: 4
1562  * End:
1563  * vim600: sw=4 ts=4 fdm=marker
1564  * vim<600: sw=4 ts=4
1565  */
1566