<commit_before>/*
    +--------------------------------------------------------------------+
    | PECL :: http                                                       |
    +--------------------------------------------------------------------+
    | Redistribution and use in source and binary forms, with or without |
    | modification, are permitted provided that the conditions mentioned |
    | in the accompanying LICENSE file are met.                          |
    +--------------------------------------------------------------------+
    | Copyright (c) 2004-2011, <NAME> <<EMAIL>>            |
    +--------------------------------------------------------------------+
*/

#include "php_http_api.h"

PHP_HTTP_API zend_bool php_http_message_info_callback(php_http_message_t **message, HashTable **headers, php_http_info_t *info TSRMLS_DC)
{
	php_http_message_t *old = *message;

	/* advance message */
	if (old->type || zend_hash_num_elements(&old->hdrs) || PHP_HTTP_BUFFER_LEN(old)) {
		(*message) = php_http_message_init(NULL, 0 TSRMLS_CC);
		(*message)->parent = old;
		(*headers) = &((*message)->hdrs);
	}

	php_http_message_set_info(*message, info);

	return old != *message;
}

PHP_HTTP_API php_http_message_t *php_http_message_init(php_http_message_t *message, php_http_message_type_t type TSRMLS_DC)
{
	if (!message) {
		message = emalloc(sizeof(*message));
	}
	memset(message, 0, sizeof(*message));
	TSRMLS_SET_CTX(message->ts);

	php_http_message_set_type(message, type);
	zend_hash_init(&message->hdrs, 0, NULL, ZVAL_PTR_DTOR, 0);
	php_http_message_body_init(&message->body, NULL TSRMLS_CC);

	return message;
}

PHP_HTTP_API php_http_message_t *php_http_message_init_env(php_http_message_t *message, php_http_message_type_t type TSRMLS_DC)
{
	int free_msg = !message;
	zval *sval, tval;
	php_http_message_body_t *mbody;
	
	message = php_http_message_init(message, type TSRMLS_CC);
	
	switch (type) {
		case PHP_HTTP_REQUEST:
			if ((sval = php_http_env_get_server_var(ZEND_STRL("SERVER_PROTOCOL"), 1 TSRMLS_CC)) && !strncmp(Z_STRVAL_P(sval), "HTTP/", lenof("HTTP/"))) {
				php_http_version_parse(&message->http.version, Z_STRVAL_P(sval) TSRMLS_CC);
			} else {
				message->http.version.major = 1;
				message->http.version.minor = 1;
			}
			if ((sval = php_http_env_get_server_var(ZEND_STRL("REQUEST_METHOD"), 1 TSRMLS_CC))) {
				message->http.info.request.method = estrdup(Z_STRVAL_P(sval));
			}
			if ((sval = php_http_env_get_server_var(ZEND_STRL("REQUEST_URI"), 1 TSRMLS_CC))) {
				message->http.info.request.url = estrdup(Z_STRVAL_P(sval));
			}
			
			php_http_env_get_request_headers(&message->hdrs TSRMLS_CC);

			if ((mbody = php_http_env_get_request_body(TSRMLS_C))) {
				php_http_message_body_dtor(&message->body);
				php_http_message_body_copy(mbody, &message->body, 0);
			}
			break;
			
		case PHP_HTTP_RESPONSE:
			if (!SG(sapi_headers).http_status_line || !php_http_info_parse((php_http_info_t *) &message->http, SG(sapi_headers).http_status_line TSRMLS_CC)) {
				message->http.version.major = 1;
				message->http.version.minor = 1;
				switch ((message->http.info.response.code = SG(sapi_headers).http_response_code)) {
					case 0:
						message->http.info.response.code = 200;
					case 200:
						message->http.info.response.status = estrdup("Ok");
						break;
					default:
						message->http.info.response.status = estrdup("");
						break;
				}

			}
			
			php_http_env_get_response_headers(&message->hdrs TSRMLS_CC);

			if (php_output_get_level(TSRMLS_C)) {
				if (php_output_get_status(TSRMLS_C) & PHP_OUTPUT_SENT) {
					php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "Could not fetch response body, output has already been sent at %s:%d", php_output_get_start_filename(TSRMLS_C), php_output_get_start_lineno(TSRMLS_C));
					goto error;
				} else if (SUCCESS != php_output_get_contents(&tval TSRMLS_CC)) {
					php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "Could not fetch response body");
					goto error;
				} else {
					php_http_message_body_append(&message->body, Z_STRVAL(tval), Z_STRLEN(tval));
					zval_dtor(&tval);
				}
			}
			break;
			
		default:
		error:
			if (free_msg) {
				php_http_message_free(&message);
			} else {
				message = NULL;
			}
			break;
	}
	
	return message;
}

PHP_HTTP_API php_http_message_t *php_http_message_parse(php_http_message_t *msg, const char *str, size_t len TSRMLS_DC)
{
	php_http_message_parser_t p;
	php_http_buffer_t buf;
	int free_msg;

	php_http_buffer_from_string_ex(&buf, str, len);
	php_http_message_parser_init(&p TSRMLS_CC);

	if ((free_msg = !msg)) {
		msg = php_http_message_init(NULL, 0 TSRMLS_CC);
	}

	if (FAILURE == php_http_message_parser_parse(&p, &buf, PHP_HTTP_MESSAGE_PARSER_CLEANUP, &msg)) {
		if (free_msg) {
			php_http_message_free(&msg);
		}
		msg = NULL;
	}

	php_http_message_parser_dtor(&p);
	php_http_buffer_dtor(&buf);

	return msg;
}

PHP_HTTP_API zval *php_http_message_header(php_http_message_t *msg, char *key_str, size_t key_len, int join)
{
	zval *ret = NULL, **header;
	char *key = php_http_pretty_key(estrndup(key_str, key_len), key_len, 1, 1);

	if (SUCCESS == zend_symtable_find(&msg->hdrs, key, key_len + 1, (void *) &header)) {
		if (join && Z_TYPE_PP(header) == IS_ARRAY) {
			zval *header_str, **val;
			HashPosition pos;
			php_http_buffer_t str;
			TSRMLS_FETCH_FROM_CTX(msg->ts);

			php_http_buffer_init(&str);
			MAKE_STD_ZVAL(header_str);
			FOREACH_VAL(pos, *header, val) {
				zval *strval = php_http_ztyp(IS_STRING, *val);
				php_http_buffer_appendf(&str, PHP_HTTP_BUFFER_LEN(&str) ? ", %s":"%s", Z_STRVAL_P(strval));
				zval_ptr_dtor(&strval);
			}
			php_http_buffer_fix(&str);
			ZVAL_STRINGL(header_str, PHP_HTTP_BUFFER_VAL(&str), PHP_HTTP_BUFFER_LEN(&str), 0);
			ret = header_str;
		} else {
			Z_ADDREF_PP(header);
			ret = *header;
		}
	}

	efree(key);

	return ret;
}


/* */
PHP_HTTP_API void php_http_message_set_type(php_http_message_t *message, php_http_message_type_t type)
{
	/* just act if different */
	if (type != message->type) {

		/* free request info */
		switch (message->type = type) {
			case PHP_HTTP_REQUEST:
				STR_FREE(message->http.info.request.method);
				STR_FREE(message->http.info.request.url);
				break;
			
			case PHP_HTTP_RESPONSE:
				STR_FREE(message->http.info.response.status);
				break;
			
			default:
				break;
		}

		memset(&message->http, 0, sizeof(message->http));
	}
}

PHP_HTTP_API void php_http_message_set_info(php_http_message_t *message, php_http_info_t *info)
{
	php_http_message_set_type(message, info->type);
	message->http.version = info->http.version;
	switch (message->type) {
		case PHP_HTTP_REQUEST:
			STR_SET(PHP_HTTP_INFO(message).request.url, PHP_HTTP_INFO(info).request.url ? estrdup(PHP_HTTP_INFO(info).request.url) : NULL);
			STR_SET(PHP_HTTP_INFO(message).request.method, PHP_HTTP_INFO(info).request.method ? estrdup(PHP_HTTP_INFO(info).request.method) : NULL);
			break;
		
		case PHP_HTTP_RESPONSE:
			PHP_HTTP_INFO(message).response.code = PHP_HTTP_INFO(info).response.code;
			STR_SET(PHP_HTTP_INFO(message).response.status, PHP_HTTP_INFO(info).response.status ? estrdup(PHP_HTTP_INFO(info).response.status) : NULL);
			break;
		
		default:
			break;
	}
}

static inline void message_headers(php_http_message_t *msg, php_http_buffer_t *str)
{
	php_http_array_hashkey_t key = php_http_array_hashkey_init(0);
	HashPosition pos1;
	zval **header, *h;
	size_t size;
	TSRMLS_FETCH_FROM_CTX(msg->ts);

	switch (msg->type) {
		case PHP_HTTP_REQUEST:
			php_http_buffer_appendf(str, PHP_HTTP_INFO_REQUEST_FMT_ARGS(&msg->http, PHP_HTTP_CRLF));
			break;

		case PHP_HTTP_RESPONSE:
			php_http_buffer_appendf(str, PHP_HTTP_INFO_RESPONSE_FMT_ARGS(&msg->http, PHP_HTTP_CRLF));
			break;

		default:
			break;
	}

	if ((size = php_http_message_body_size(&msg->body))) {
		MAKE_STD_ZVAL(h);
		ZVAL_LONG(h, size);
		zend_hash_update(&msg->hdrs, "Content-Length", sizeof("Content-Length"), &h, sizeof(zval *), NULL);

		if (msg->body.boundary) {
			char *str;
			size_t len;

			if (!(h = php_http_message_header(msg, ZEND_STRL("Content-Type"), 1))) {
				len = spprintf(&str, 0, "multipart/form-data; boundary=\"%s\"", msg->body.boundary);
				MAKE_STD_ZVAL(h);
				ZVAL_STRINGL(h, str, len, 0);
				zend_hash_update(&msg->hdrs, "Content-Type", sizeof("Content-Type"), &h, sizeof(zval *), NULL);
			} else if (!php_http_match(Z_STRVAL_P(h), "boundary=", PHP_HTTP_MATCH_WORD)) {
				zval_dtor(h);
				Z_STRLEN_P(h) = spprintf(&Z_STRVAL_P(h), 0, "%s; boundary=\"%s\"", Z_STRVAL_P(h), msg->body.boundary);
				zend_hash_update(&msg->hdrs, "Content-Type", sizeof("Content-Type"), &h, sizeof(zval *), NULL);
			} else {
				zval_ptr_dtor(&h);
			}
		}
	}

	FOREACH_HASH_KEYVAL(pos1, &msg->hdrs, key, header) {
		if (key.type == HASH_KEY_IS_STRING) {
			HashPosition pos2;
			zval **single_header;

			switch (Z_TYPE_PP(header)) {
				case IS_BOOL:
					php_http_buffer_appendf(str, "%s: %s" PHP_HTTP_CRLF, key.str, Z_BVAL_PP(header)?"true":"false");
					break;
					
				case IS_LONG:
					php_http_buffer_appendf(str, "%s: %ld" PHP_HTTP_CRLF, key.str, Z_LVAL_PP(header));
					break;
					
				case IS_DOUBLE:
					php_http_buffer_appendf(str, "%s: %F" PHP_HTTP_CRLF, key.str, Z_DVAL_PP(header));
					break;
					
				case IS_STRING:
					if (Z_STRVAL_PP(header)[Z_STRLEN_PP(header)-1] == '\r') fprintf(stderr, "DOH!\n");
					php_http_buffer_appendf(str, "%s: %s" PHP_HTTP_CRLF, key.str, Z_STRVAL_PP(header));
					break;

				case IS_ARRAY:
					FOREACH_VAL(pos2, *header, single_header) {
						switch (Z_TYPE_PP(single_header)) {
							case IS_BOOL:
								php_http_buffer_appendf(str, "%s: %s" PHP_HTTP_CRLF, key.str, Z_BVAL_PP(single_header)?"true":"false");
								break;
								
							case IS_LONG:
								php_http_buffer_appendf(str, "%s: %ld" PHP_HTTP_CRLF, key.str, Z_LVAL_PP(single_header));
								break;
								
							case IS_DOUBLE:
								php_http_buffer_appendf(str, "%s: %F" PHP_HTTP_CRLF, key.str, Z_DVAL_PP(single_header));
								break;
								
							case IS_STRING:
								php_http_buffer_appendf(str, "%s: %s" PHP_HTTP_CRLF, key.str, Z_STRVAL_PP(single_header));
								break;
						}
					}
					break;
			}
		}
	}
}

PHP_HTTP_API void php_http_message_to_callback(php_http_message_t *msg, php_http_pass_callback_t cb, void *cb_arg)
{
	php_http_buffer_t str;

	php_http_buffer_init_ex(&str, 0x1000, 0);
	message_headers(msg, &str);
	cb(cb_arg, PHP_HTTP_BUFFER_VAL(&str), PHP_HTTP_BUFFER_LEN(&str));
	php_http_buffer_dtor(&str);

	if (php_http_message_body_size(&msg->body)) {
		cb(cb_arg, ZEND_STRL(PHP_HTTP_CRLF));
		php_http_message_body_to_callback(&msg->body, cb, cb_arg, 0, 0);
		cb(cb_arg, ZEND_STRL(PHP_HTTP_CRLF));
	}
}

PHP_HTTP_API void php_http_message_to_string(php_http_message_t *msg, char **string, size_t *length)
{
	php_http_buffer_t str;
	char *data;

	php_http_buffer_init_ex(&str, 0x1000, 0);
	message_headers(msg, &str);
	if (php_http_message_body_size(&msg->body)) {
		php_http_buffer_appends(&str, PHP_HTTP_CRLF);
		php_http_message_body_to_callback(&msg->body, (php_http_pass_callback_t) php_http_buffer_append, &str, 0, 0);
		php_http_buffer_appends(&str, PHP_HTTP_CRLF);
	}

	data = php_http_buffer_data(&str, string, length);
	if (!string) {
		efree(data);
	}

	php_http_buffer_dtor(&str);
}

PHP_HTTP_API void php_http_message_serialize(php_http_message_t *message, char **string, size_t *length)
{
	char *buf;
	size_t len;
	php_http_buffer_t str;

	php_http_buffer_init(&str);

	do {
		php_http_message_to_string(message, &buf, &len);
		php_http_buffer_prepend(&str, buf, len);
		efree(buf);
	} while ((message = message->parent));

	buf = php_http_buffer_data(&str, string, length);
	if (!string) {
		efree(buf);
	}

	php_http_buffer_dtor(&str);
}

PHP_HTTP_API php_http_message_t *php_http_message_reverse(php_http_message_t *msg)
{
	int i, c = 0;
	
	php_http_message_count(c, msg);
	
	if (c > 1) {
		php_http_message_t *tmp = msg, **arr;

		arr = ecalloc(c, sizeof(**arr));
		for (i = 0; i < c; ++i) {
			arr[i] = tmp;
			tmp = tmp->parent;
		}
		arr[0]->parent = NULL;
		for (i = 0; i < c-1; ++i) {
			arr[i+1]->parent = arr[i];
		}
		
		msg = arr[c-1];
		efree(arr);
	}
	
	return msg;
}

PHP_HTTP_API php_http_message_t *php_http_message_interconnect(php_http_message_t *m1, php_http_message_t *m2)
{
	if (m1 && m2) {
		int i = 0, c1 = 0, c2 = 0;
		php_http_message_t *t1 = m1, *t2 = m2, *p1, *p2;
		
		php_http_message_count(c1, m1);
		php_http_message_count(c2, m2);
		
		while (i++ < (c1 - c2)) {
			t1 = t1->parent;
		}
		while (i++ <= c1) {
			p1 = t1->parent;
			p2 = t2->parent;
			t1->parent = t2;
			t2->parent = p1;
			t1 = p1;
			t2 = p2;
		}
	} else if (!m1 && m2) {
		m1 = m2;
	}
	return m1;
}

PHP_HTTP_API void php_http_message_to_struct(php_http_message_t *msg, zval *obj)
{
	zval strct;
	zval *headers;
	char *version;
	TSRMLS_FETCH_FROM_CTX(msg->ts);
	
	INIT_PZVAL_ARRAY(&strct, HASH_OF(obj));
	
	add_assoc_long(&strct, "type", msg->type);
	spprintf(&version, 0 ,"%u.%u", msg->http.version.major, msg->http.version.minor);
	add_assoc_string_ex(&strct, ZEND_STRL("httpVersion"), version, 0);
	switch (msg->type)
	{
		case PHP_HTTP_RESPONSE:
			add_assoc_long(&strct, "responseCode", msg->http.info.response.code);
			add_assoc_string(&strct, "responseStatus", STR_PTR(msg->http.info.response.status), 1);
		break;
		
		case PHP_HTTP_REQUEST:
			add_assoc_string(&strct, "requestMethod", STR_PTR(msg->http.info.request.method), 1);
			add_assoc_string(&strct, "requestUrl", STR_PTR(msg->http.info.request.url), 1);
		break;
		
		case PHP_HTTP_NONE:
			/* avoid compiler warning */
		break;
	}
	
	MAKE_STD_ZVAL(headers);
	array_init(headers);
	zend_hash_copy(Z_ARRVAL_P(headers), &msg->hdrs, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
	add_assoc_zval(&strct, "headers", headers);
	
	add_assoc_stringl(&strct, "body", PHP_HTTP_BUFFER_VAL(msg), PHP_HTTP_BUFFER_LEN(msg), 1);
	
	if (msg->parent) {
		zval *parent;
		
		MAKE_STD_ZVAL(parent);
		if (Z_TYPE_P(obj) == IS_ARRAY) {
			array_init(parent);
		} else {
			object_init(parent);
		}
		add_assoc_zval(&strct, "parentMessage", parent);
		php_http_message_to_struct(msg->parent, parent);
	} else {
		add_assoc_null(&strct, "parentMessage");
	}
}
/*
PHP_HTTP_API STATUS _http_message_send(http_message *message TSRMLS_DC)
{
	STATUS rs = FAILURE;

	switch (message->type) {
		case PHP_HTTP_RESPONSE:
		{
			php_http_array_hashkey_t key = php_http_array_hashkey_init(0);
			zval **val;
			HashPosition pos;

			FOREACH_HASH_KEYVAL(pos, &message->hdrs, key, val) {
				if (key.type == HASH_KEY_IS_STRING) {
					http_send_header_zval_ex(key.str, key.len-1, val, 1);
				}
			}
			rs =	SUCCESS == http_send_status(message->http.info.response.code) &&
					SUCCESS == http_send_data(PHP_HTTP_BUFFER_VAL(message), PHP_HTTP_BUFFER_LEN(message)) ?
					SUCCESS : FAILURE;
			break;
		}

		case PHP_HTTP_REQUEST:
		{
#ifdef PHP_HTTP_HAVE_CURL
			char *uri = NULL;
			http_request request;
			zval **zhost, *options, *headers;
			
			MAKE_STD_ZVAL(options);
			MAKE_STD_ZVAL(headers);
			array_init(options);
			array_init(headers);
			zend_hash_copy(Z_ARRVAL_P(headers), &message->hdrs, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
			add_assoc_zval(options, "headers", headers);

			if (SUCCESS == zend_hash_find(&message->hdrs, "Host", sizeof("Host"), (void *) &zhost) && Z_TYPE_PP(zhost) == IS_STRING) {
				char *colon = NULL;
				php_url parts, *url = php_url_parse(message->http.info.request.url);
				
				memset(&parts, 0, sizeof(php_url));

				if ((colon = strchr(Z_STRVAL_PP(zhost), ':'))) {
					parts.port = atoi(colon + 1);
					parts.host = estrndup(Z_STRVAL_PP(zhost), (Z_STRVAL_PP(zhost) - colon - 1));
				} else {
					parts.host = estrndup(Z_STRVAL_PP(zhost), Z_STRLEN_PP(zhost));
				}
				
				http_build_url(PHP_HTTP_URL_REPLACE, url, &parts, NULL, &uri, NULL);
				php_url_free(url);
				efree(parts.host);
			} else {
				uri = http_absolute_url(message->http.info.request.url);
			}

			if ((request.meth = http_request_method_exists(1, 0, message->http.info.request.method))) {
				http_request_body body;
				
				http_request_init_ex(&request, NULL, request.meth, uri);
				request.body = http_request_body_init_ex(&body, PHP_HTTP_REQUEST_BODY_CSTRING, PHP_HTTP_BUFFER_VAL(message), PHP_HTTP_BUFFER_LEN(message), 0);
				if (SUCCESS == (rs = http_request_prepare(&request, Z_ARRVAL_P(options)))) {
					http_request_exec(&request);
				}
				http_request_dtor(&request);
			} else {
				http_error_ex(HE_WARNING, PHP_HTTP_E_REQUEST_METHOD,
					"Cannot send HttpMessage. Request method %s not supported",
					message->http.info.request.method);
			}
			efree(uri);
			zval_ptr_dtor(&options);
#else
			http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "HTTP requests not supported - ext/http was not linked against libcurl.");
#endif
		break;
		}

		case PHP_HTTP_NONE:
		default:
			php_http_error(HE_WARNING, PHP_HTTP_E_MESSAGE_TYPE, "HttpMessage is neither of type PHP_HTTP_REQUEST nor PHP_HTTP_RESPONSE");
			break;
	}

	return rs;
}
*/

PHP_HTTP_API php_http_message_t *php_http_message_copy_ex(php_http_message_t *from, php_http_message_t *to, zend_bool parents)
{
	php_http_message_t *temp, *copy = NULL;
	php_http_info_t info;
	TSRMLS_FETCH_FROM_CTX(from->ts);
	
	if (from) {
		info.type = from->type;
		info.http = from->http;
		
		copy = temp = php_http_message_init(to, 0 TSRMLS_CC);
		php_http_message_set_info(temp, &info);
		zend_hash_copy(&temp->hdrs, &from->hdrs, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
		php_http_message_body_copy(&from->body, &temp->body, 1);
	
		if (parents) while (from->parent) {
			info.type = from->parent->type;
			info.http = from->parent->http;
		
			temp->parent = php_http_message_init(NULL, 0 TSRMLS_CC);
			php_http_message_set_info(temp->parent, &info);
			zend_hash_copy(&temp->parent->hdrs, &from->parent->hdrs, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
			php_http_message_body_copy(&from->body, &temp->body, 1);
		
			temp = temp->parent;
			from = from->parent;
		}
	}
	
	return copy;
}

PHP_HTTP_API php_http_message_t *php_http_message_copy(php_http_message_t *from, php_http_message_t *to)
{
	return php_http_message_copy_ex(from, to, 1);
}

PHP_HTTP_API void php_http_message_dtor(php_http_message_t *message)
{
	if (message) {
		zend_hash_destroy(&message->hdrs);<commit_msg>fix type initialization and leaks; fix prepend<commit_after>/*
    +--------------------------------------------------------------------+
    | PECL :: http                                                       |
    +--------------------------------------------------------------------+
    | Redistribution and use in source and binary forms, with or without |
    | modification, are permitted provided that the conditions mentioned |
    | in the accompanying LICENSE file are met.                          |
    +--------------------------------------------------------------------+
    | Copyright (c) 2004-2011, <NAME> <<EMAIL>>            |
    +--------------------------------------------------------------------+
*/

#include "php_http_api.h"

PHP_HTTP_API zend_bool php_http_message_info_callback(php_http_message_t **message, HashTable **headers, php_http_info_t *info TSRMLS_DC)
{
	php_http_message_t *old = *message;

	/* advance message */
	if (old->type || zend_hash_num_elements(&old->hdrs) || PHP_HTTP_BUFFER_LEN(old)) {
		(*message) = php_http_message_init(NULL, 0 TSRMLS_CC);
		(*message)->parent = old;
		(*headers) = &((*message)->hdrs);
	}

	php_http_message_set_info(*message, info);

	return old != *message;
}

PHP_HTTP_API php_http_message_t *php_http_message_init(php_http_message_t *message, php_http_message_type_t type TSRMLS_DC)
{
	if (!message) {
		message = emalloc(sizeof(*message));
	}
	memset(message, 0, sizeof(*message));
	TSRMLS_SET_CTX(message->ts);

	php_http_message_set_type(message, type);
	zend_hash_init(&message->hdrs, 0, NULL, ZVAL_PTR_DTOR, 0);
	php_http_message_body_init(&message->body, NULL TSRMLS_CC);

	return message;
}

PHP_HTTP_API php_http_message_t *php_http_message_init_env(php_http_message_t *message, php_http_message_type_t type TSRMLS_DC)
{
	int free_msg = !message;
	zval *sval, tval;
	php_http_message_body_t *mbody;
	
	message = php_http_message_init(message, type TSRMLS_CC);
	
	switch (type) {
		case PHP_HTTP_REQUEST:
			if ((sval = php_http_env_get_server_var(ZEND_STRL("SERVER_PROTOCOL"), 1 TSRMLS_CC)) && !strncmp(Z_STRVAL_P(sval), "HTTP/", lenof("HTTP/"))) {
				php_http_version_parse(&message->http.version, Z_STRVAL_P(sval) TSRMLS_CC);
			} else {
				message->http.version.major = 1;
				message->http.version.minor = 1;
			}
			if ((sval = php_http_env_get_server_var(ZEND_STRL("REQUEST_METHOD"), 1 TSRMLS_CC))) {
				message->http.info.request.method = estrdup(Z_STRVAL_P(sval));
			}
			if ((sval = php_http_env_get_server_var(ZEND_STRL("REQUEST_URI"), 1 TSRMLS_CC))) {
				message->http.info.request.url = estrdup(Z_STRVAL_P(sval));
			}
			
			php_http_env_get_request_headers(&message->hdrs TSRMLS_CC);

			if ((mbody = php_http_env_get_request_body(TSRMLS_C))) {
				php_http_message_body_dtor(&message->body);
				php_http_message_body_copy(mbody, &message->body, 0);
			}
			break;
			
		case PHP_HTTP_RESPONSE:
			if (!SG(sapi_headers).http_status_line || !php_http_info_parse((php_http_info_t *) &message->http, SG(sapi_headers).http_status_line TSRMLS_CC)) {
				message->http.version.major = 1;
				message->http.version.minor = 1;
				switch ((message->http.info.response.code = SG(sapi_headers).http_response_code)) {
					case 0:
						message->http.info.response.code = 200;
					case 200:
						message->http.info.response.status = estrdup("Ok");
						break;
					default:
						message->http.info.response.status = estrdup("");
						break;
				}

			}
			
			php_http_env_get_response_headers(&message->hdrs TSRMLS_CC);

			if (php_output_get_level(TSRMLS_C)) {
				if (php_output_get_status(TSRMLS_C) & PHP_OUTPUT_SENT) {
					php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "Could not fetch response body, output has already been sent at %s:%d", php_output_get_start_filename(TSRMLS_C), php_output_get_start_lineno(TSRMLS_C));
					goto error;
				} else if (SUCCESS != php_output_get_contents(&tval TSRMLS_CC)) {
					php_http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "Could not fetch response body");
					goto error;
				} else {
					php_http_message_body_append(&message->body, Z_STRVAL(tval), Z_STRLEN(tval));
					zval_dtor(&tval);
				}
			}
			break;
			
		default:
		error:
			if (free_msg) {
				php_http_message_free(&message);
			} else {
				message = NULL;
			}
			break;
	}
	
	return message;
}

PHP_HTTP_API php_http_message_t *php_http_message_parse(php_http_message_t *msg, const char *str, size_t len TSRMLS_DC)
{
	php_http_message_parser_t p;
	php_http_buffer_t buf;
	int free_msg;

	php_http_buffer_from_string_ex(&buf, str, len);
	php_http_message_parser_init(&p TSRMLS_CC);

	if ((free_msg = !msg)) {
		msg = php_http_message_init(NULL, 0 TSRMLS_CC);
	}

	if (FAILURE == php_http_message_parser_parse(&p, &buf, PHP_HTTP_MESSAGE_PARSER_CLEANUP, &msg)) {
		if (free_msg) {
			php_http_message_free(&msg);
		}
		msg = NULL;
	}

	php_http_message_parser_dtor(&p);
	php_http_buffer_dtor(&buf);

	return msg;
}

PHP_HTTP_API zval *php_http_message_header(php_http_message_t *msg, char *key_str, size_t key_len, int join)
{
	zval *ret = NULL, **header;
	char *key = php_http_pretty_key(estrndup(key_str, key_len), key_len, 1, 1);

	if (SUCCESS == zend_symtable_find(&msg->hdrs, key, key_len + 1, (void *) &header)) {
		if (join && Z_TYPE_PP(header) == IS_ARRAY) {
			zval *header_str, **val;
			HashPosition pos;
			php_http_buffer_t str;
			TSRMLS_FETCH_FROM_CTX(msg->ts);

			php_http_buffer_init(&str);
			MAKE_STD_ZVAL(header_str);
			FOREACH_VAL(pos, *header, val) {
				zval *strval = php_http_ztyp(IS_STRING, *val);
				php_http_buffer_appendf(&str, PHP_HTTP_BUFFER_LEN(&str) ? ", %s":"%s", Z_STRVAL_P(strval));
				zval_ptr_dtor(&strval);
			}
			php_http_buffer_fix(&str);
			ZVAL_STRINGL(header_str, PHP_HTTP_BUFFER_VAL(&str), PHP_HTTP_BUFFER_LEN(&str), 0);
			ret = header_str;
		} else {
			Z_ADDREF_PP(header);
			ret = *header;
		}
	}

	efree(key);

	return ret;
}


/* */
PHP_HTTP_API void php_http_message_set_type(php_http_message_t *message, php_http_message_type_t type)
{
	/* just act if different */
	if (type != message->type) {

		/* free request info */
		switch (message->type) {
			case PHP_HTTP_REQUEST:
				STR_FREE(message->http.info.request.method);
				STR_FREE(message->http.info.request.url);
				break;
			
			case PHP_HTTP_RESPONSE:
				STR_FREE(message->http.info.response.status);
				break;
			
			default:
				break;
		}

		message->type = type;
		memset(&message->http, 0, sizeof(message->http));
	}
}

PHP_HTTP_API void php_http_message_set_info(php_http_message_t *message, php_http_info_t *info)
{
	php_http_message_set_type(message, info->type);
	message->http.version = info->http.version;
	switch (message->type) {
		case PHP_HTTP_REQUEST:
			STR_SET(PHP_HTTP_INFO(message).request.url, PHP_HTTP_INFO(info).request.url ? estrdup(PHP_HTTP_INFO(info).request.url) : NULL);
			STR_SET(PHP_HTTP_INFO(message).request.method, PHP_HTTP_INFO(info).request.method ? estrdup(PHP_HTTP_INFO(info).request.method) : NULL);
			break;
		
		case PHP_HTTP_RESPONSE:
			PHP_HTTP_INFO(message).response.code = PHP_HTTP_INFO(info).response.code;
			STR_SET(PHP_HTTP_INFO(message).response.status, PHP_HTTP_INFO(info).response.status ? estrdup(PHP_HTTP_INFO(info).response.status) : NULL);
			break;
		
		default:
			break;
	}
}

static inline void message_headers(php_http_message_t *msg, php_http_buffer_t *str)
{
	php_http_array_hashkey_t key = php_http_array_hashkey_init(0);
	HashPosition pos1;
	zval **header, *h;
	size_t size;
	TSRMLS_FETCH_FROM_CTX(msg->ts);

	switch (msg->type) {
		case PHP_HTTP_REQUEST:
			php_http_buffer_appendf(str, PHP_HTTP_INFO_REQUEST_FMT_ARGS(&msg->http, PHP_HTTP_CRLF));
			break;

		case PHP_HTTP_RESPONSE:
			php_http_buffer_appendf(str, PHP_HTTP_INFO_RESPONSE_FMT_ARGS(&msg->http, PHP_HTTP_CRLF));
			break;

		default:
			break;
	}

	if ((size = php_http_message_body_size(&msg->body))) {
		MAKE_STD_ZVAL(h);
		ZVAL_LONG(h, size);
		zend_hash_update(&msg->hdrs, "Content-Length", sizeof("Content-Length"), &h, sizeof(zval *), NULL);

		if (msg->body.boundary) {
			char *str;
			size_t len;

			if (!(h = php_http_message_header(msg, ZEND_STRL("Content-Type"), 1))) {
				len = spprintf(&str, 0, "multipart/form-data; boundary=\"%s\"", msg->body.boundary);
				MAKE_STD_ZVAL(h);
				ZVAL_STRINGL(h, str, len, 0);
				zend_hash_update(&msg->hdrs, "Content-Type", sizeof("Content-Type"), &h, sizeof(zval *), NULL);
			} else if (!php_http_match(Z_STRVAL_P(h), "boundary=", PHP_HTTP_MATCH_WORD)) {
				zval_dtor(h);
				Z_STRLEN_P(h) = spprintf(&Z_STRVAL_P(h), 0, "%s; boundary=\"%s\"", Z_STRVAL_P(h), msg->body.boundary);
				zend_hash_update(&msg->hdrs, "Content-Type", sizeof("Content-Type"), &h, sizeof(zval *), NULL);
			} else {
				zval_ptr_dtor(&h);
			}
		}
	}

	FOREACH_HASH_KEYVAL(pos1, &msg->hdrs, key, header) {
		if (key.type == HASH_KEY_IS_STRING) {
			HashPosition pos2;
			zval **single_header;

			switch (Z_TYPE_PP(header)) {
				case IS_BOOL:
					php_http_buffer_appendf(str, "%s: %s" PHP_HTTP_CRLF, key.str, Z_BVAL_PP(header)?"true":"false");
					break;
					
				case IS_LONG:
					php_http_buffer_appendf(str, "%s: %ld" PHP_HTTP_CRLF, key.str, Z_LVAL_PP(header));
					break;
					
				case IS_DOUBLE:
					php_http_buffer_appendf(str, "%s: %F" PHP_HTTP_CRLF, key.str, Z_DVAL_PP(header));
					break;
					
				case IS_STRING:
					if (Z_STRVAL_PP(header)[Z_STRLEN_PP(header)-1] == '\r') fprintf(stderr, "DOH!\n");
					php_http_buffer_appendf(str, "%s: %s" PHP_HTTP_CRLF, key.str, Z_STRVAL_PP(header));
					break;

				case IS_ARRAY:
					FOREACH_VAL(pos2, *header, single_header) {
						switch (Z_TYPE_PP(single_header)) {
							case IS_BOOL:
								php_http_buffer_appendf(str, "%s: %s" PHP_HTTP_CRLF, key.str, Z_BVAL_PP(single_header)?"true":"false");
								break;
								
							case IS_LONG:
								php_http_buffer_appendf(str, "%s: %ld" PHP_HTTP_CRLF, key.str, Z_LVAL_PP(single_header));
								break;
								
							case IS_DOUBLE:
								php_http_buffer_appendf(str, "%s: %F" PHP_HTTP_CRLF, key.str, Z_DVAL_PP(single_header));
								break;
								
							case IS_STRING:
								php_http_buffer_appendf(str, "%s: %s" PHP_HTTP_CRLF, key.str, Z_STRVAL_PP(single_header));
								break;
						}
					}
					break;
			}
		}
	}
}

PHP_HTTP_API void php_http_message_to_callback(php_http_message_t *msg, php_http_pass_callback_t cb, void *cb_arg)
{
	php_http_buffer_t str;

	php_http_buffer_init_ex(&str, 0x1000, 0);
	message_headers(msg, &str);
	cb(cb_arg, PHP_HTTP_BUFFER_VAL(&str), PHP_HTTP_BUFFER_LEN(&str));
	php_http_buffer_dtor(&str);

	if (php_http_message_body_size(&msg->body)) {
		cb(cb_arg, ZEND_STRL(PHP_HTTP_CRLF));
		php_http_message_body_to_callback(&msg->body, cb, cb_arg, 0, 0);
		cb(cb_arg, ZEND_STRL(PHP_HTTP_CRLF));
	}
}

PHP_HTTP_API void php_http_message_to_string(php_http_message_t *msg, char **string, size_t *length)
{
	php_http_buffer_t str;
	char *data;

	php_http_buffer_init_ex(&str, 0x1000, 0);
	message_headers(msg, &str);
	if (php_http_message_body_size(&msg->body)) {
		php_http_buffer_appends(&str, PHP_HTTP_CRLF);
		php_http_message_body_to_callback(&msg->body, (php_http_pass_callback_t) php_http_buffer_append, &str, 0, 0);
		php_http_buffer_appends(&str, PHP_HTTP_CRLF);
	}

	data = php_http_buffer_data(&str, string, length);
	if (!string) {
		efree(data);
	}

	php_http_buffer_dtor(&str);
}

PHP_HTTP_API void php_http_message_serialize(php_http_message_t *message, char **string, size_t *length)
{
	char *buf;
	size_t len;
	php_http_buffer_t str;

	php_http_buffer_init(&str);

	do {
		php_http_message_to_string(message, &buf, &len);
		php_http_buffer_prepend(&str, buf, len);
		efree(buf);
	} while ((message = message->parent));

	buf = php_http_buffer_data(&str, string, length);
	if (!string) {
		efree(buf);
	}

	php_http_buffer_dtor(&str);
}

PHP_HTTP_API php_http_message_t *php_http_message_reverse(php_http_message_t *msg)
{
	int i, c = 0;
	
	php_http_message_count(c, msg);
	
	if (c > 1) {
		php_http_message_t *tmp = msg, **arr;

		arr = ecalloc(c, sizeof(**arr));
		for (i = 0; i < c; ++i) {
			arr[i] = tmp;
			tmp = tmp->parent;
		}
		arr[0]->parent = NULL;
		for (i = 0; i < c-1; ++i) {
			arr[i+1]->parent = arr[i];
		}
		
		msg = arr[c-1];
		efree(arr);
	}
	
	return msg;
}

PHP_HTTP_API php_http_message_t *php_http_message_interconnect(php_http_message_t *m1, php_http_message_t *m2)
{
	if (m1 && m2) {
		int i = 0, c1 = 0, c2 = 0;
		php_http_message_t *t1 = m1, *t2 = m2, *p1, *p2;
		
		php_http_message_count(c1, m1);
		php_http_message_count(c2, m2);
		
		while (i++ < (c1 - c2)) {
			t1 = t1->parent;
		}
		while (i++ <= c1) {
			p1 = t1->parent;
			p2 = t2->parent;
			t1->parent = t2;
			t2->parent = p1;
			t1 = p1;
			t2 = p2;
		}
	} else if (!m1 && m2) {
		m1 = m2;
	}
	return m1;
}

PHP_HTTP_API void php_http_message_to_struct(php_http_message_t *msg, zval *obj)
{
	zval strct;
	zval *headers;
	char *version;
	TSRMLS_FETCH_FROM_CTX(msg->ts);
	
	INIT_PZVAL_ARRAY(&strct, HASH_OF(obj));
	
	add_assoc_long(&strct, "type", msg->type);
	spprintf(&version, 0 ,"%u.%u", msg->http.version.major, msg->http.version.minor);
	add_assoc_string_ex(&strct, ZEND_STRL("httpVersion"), version, 0);
	switch (msg->type)
	{
		case PHP_HTTP_RESPONSE:
			add_assoc_long(&strct, "responseCode", msg->http.info.response.code);
			add_assoc_string(&strct, "responseStatus", STR_PTR(msg->http.info.response.status), 1);
		break;
		
		case PHP_HTTP_REQUEST:
			add_assoc_string(&strct, "requestMethod", STR_PTR(msg->http.info.request.method), 1);
			add_assoc_string(&strct, "requestUrl", STR_PTR(msg->http.info.request.url), 1);
		break;
		
		case PHP_HTTP_NONE:
			/* avoid compiler warning */
		break;
	}
	
	MAKE_STD_ZVAL(headers);
	array_init(headers);
	zend_hash_copy(Z_ARRVAL_P(headers), &msg->hdrs, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
	add_assoc_zval(&strct, "headers", headers);
	
	add_assoc_stringl(&strct, "body", PHP_HTTP_BUFFER_VAL(msg), PHP_HTTP_BUFFER_LEN(msg), 1);
	
	if (msg->parent) {
		zval *parent;
		
		MAKE_STD_ZVAL(parent);
		if (Z_TYPE_P(obj) == IS_ARRAY) {
			array_init(parent);
		} else {
			object_init(parent);
		}
		add_assoc_zval(&strct, "parentMessage", parent);
		php_http_message_to_struct(msg->parent, parent);
	} else {
		add_assoc_null(&strct, "parentMessage");
	}
}
/*
PHP_HTTP_API STATUS _http_message_send(http_message *message TSRMLS_DC)
{
	STATUS rs = FAILURE;

	switch (message->type) {
		case PHP_HTTP_RESPONSE:
		{
			php_http_array_hashkey_t key = php_http_array_hashkey_init(0);
			zval **val;
			HashPosition pos;

			FOREACH_HASH_KEYVAL(pos, &message->hdrs, key, val) {
				if (key.type == HASH_KEY_IS_STRING) {
					http_send_header_zval_ex(key.str, key.len-1, val, 1);
				}
			}
			rs =	SUCCESS == http_send_status(message->http.info.response.code) &&
					SUCCESS == http_send_data(PHP_HTTP_BUFFER_VAL(message), PHP_HTTP_BUFFER_LEN(message)) ?
					SUCCESS : FAILURE;
			break;
		}

		case PHP_HTTP_REQUEST:
		{
#ifdef PHP_HTTP_HAVE_CURL
			char *uri = NULL;
			http_request request;
			zval **zhost, *options, *headers;
			
			MAKE_STD_ZVAL(options);
			MAKE_STD_ZVAL(headers);
			array_init(options);
			array_init(headers);
			zend_hash_copy(Z_ARRVAL_P(headers), &message->hdrs, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
			add_assoc_zval(options, "headers", headers);

			if (SUCCESS == zend_hash_find(&message->hdrs, "Host", sizeof("Host"), (void *) &zhost) && Z_TYPE_PP(zhost) == IS_STRING) {
				char *colon = NULL;
				php_url parts, *url = php_url_parse(message->http.info.request.url);
				
				memset(&parts, 0, sizeof(php_url));

				if ((colon = strchr(Z_STRVAL_PP(zhost), ':'))) {
					parts.port = atoi(colon + 1);
					parts.host = estrndup(Z_STRVAL_PP(zhost), (Z_STRVAL_PP(zhost) - colon - 1));
				} else {
					parts.host = estrndup(Z_STRVAL_PP(zhost), Z_STRLEN_PP(zhost));
				}
				
				http_build_url(PHP_HTTP_URL_REPLACE, url, &parts, NULL, &uri, NULL);
				php_url_free(url);
				efree(parts.host);
			} else {
				uri = http_absolute_url(message->http.info.request.url);
			}

			if ((request.meth = http_request_method_exists(1, 0, message->http.info.request.method))) {
				http_request_body body;
				
				http_request_init_ex(&request, NULL, request.meth, uri);
				request.body = http_request_body_init_ex(&body, PHP_HTTP_REQUEST_BODY_CSTRING, PHP_HTTP_BUFFER_VAL(message), PHP_HTTP_BUFFER_LEN(message), 0);
				if (SUCCESS == (rs = http_request_prepare(&request, Z_ARRVAL_P(options)))) {
					http_request_exec(&request);
				}
				http_request_dtor(&request);
			} else {
				http_error_ex(HE_WARNING, PHP_HTTP_E_REQUEST_METHOD,
					"Cannot send HttpMessage. Request method %s not supported",
					message->http.info.request.method);
			}
			efree(uri);
			zval_ptr_dtor(&options);
#else
			http_error(HE_WARNING, PHP_HTTP_E_RUNTIME, "HTTP requests not supported - ext/http was not linked against libcurl.");
#endif
		break;
		}

		case PHP_HTTP_NONE:
		default:
			php_http_error(HE_WARNING, PHP_HTTP_E_MESSAGE_TYPE, "HttpMessage is neither of type PHP_HTTP_REQUEST nor PHP_HTTP_RESPONSE");
			break;
	}

	return rs;
}
*/

PHP_HTTP_API php_http_message_t *php_http_message_copy_ex(php_http_message_t *from, php_http_message_t *to, zend_bool parents)
{
	php_http_message_t *temp, *copy = NULL;
	php_http_info_t info;
	TSRMLS_FETCH_FROM_CTX(from->ts);
	
	if (from) {
		info.type = from->type;
		info.http = from->http;
		
		copy = temp = php_http_message_init(to, 0 TSRMLS_CC);
		php_http_message_set_info(temp, &info);
		zend_hash_copy(&temp->hdrs, &from->hdrs, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
		php_http_message_body_copy(&from->body, &temp->body, 1);
	
		if (parents) while (from->parent) {
			info.type = from->parent->type;
			info.http = from->parent->http;
		
			temp->parent = php_http_message_init(NULL, 0 TSRMLS_CC);
			php_http_message_set_info(temp->parent, &info);
			zend_hash_copy(&temp->parent->hdrs, &from->parent->hdrs, (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval *));
			php_http_message_body_copy(&from->parent->body, &temp->parent->body, 1);
		
			temp = temp->parent;
			from = from->parent;
		}
	}
	
	return copy;
}

PHP_HTTP_API php_http_message_t *php_http_message_copy(php_http_message_t *from, php_http_message_t *to)
{
	return php_http_message_copy_ex(from, to, 1);
}

PHP_HTTP_API void php_http_message_dtor(php_http_message_t *message)
{
	if (message) {
		zend_hash_destroy(&message->hdrs);
{'fraction_non_alphanumeric': 0.1515645371577575, 'fraction_numerical': 0.006953498478922208, 'mean_word_length': 4.164398933931828, 'pattern_counts': {'":': 6, '<': 17, '<?xml version=': 0, '>': 226, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '612352', 'n_tokens_mistral': 16559, 'n_tokens_neox': 14400, 'n_words': 2344}