diff --git a/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_001.phpt b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_001.phpt
new file mode 100644
index 00000000..1f81bfc1
--- /dev/null
+++ b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_001.phpt
@@ -0,0 +1,60 @@
+--TEST--
+GHSA-p3x9-6h7p-cgfc: libxml streams use wrong `content-type` header when requesting a redirected resource (Basic)
+--EXTENSIONS--
+dom
+--SKIPIF--
+
+--FILE--
+
+
+
+ GHSA-p3x9-6h7p-cgfc
+
+
+
+
+
+
+ GHSA-p3x9-6h7p-cgfc
+
+
+EOT;
+ // Intentionally using non-standard casing for content-type to verify it is matched not case sensitively.
+ yield "data://text/plain,HTTP/1.1 200 OK\r\nconteNt-tyPe: text/html; charset=utf-8\r\n\r\n{$xml}";
+}
+
+$r = http_server('genResponses', $output);
+$document = new \DOMDocument();
+$document->loadHTMLFile($r['uri']);
+
+$h1 = $document->getElementsByTagName('h1');
+var_dump($h1->length);
+var_dump($document->saveHTML());
+http_server_kill($r['pid']);
+?>
+--EXPECT--
+int(1)
+string(266) "
+
+
+ GHSA-p3x9-6h7p-cgfc
+
+
+
+
+
+
+ GHSA-p3x9-6h7p-cgfc
+
+
+"
diff --git a/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_002.phpt b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_002.phpt
new file mode 100644
index 00000000..9bd548b6
--- /dev/null
+++ b/ext/dom/tests/ghsa-p3x9-6h7p-cgfc_002.phpt
@@ -0,0 +1,60 @@
+--TEST--
+GHSA-p3x9-6h7p-cgfc: libxml streams use wrong `content-type` header when requesting a redirected resource (Missing content-type)
+--EXTENSIONS--
+dom
+--SKIPIF--
+
+--FILE--
+
+
+
+ GHSA-p3x9-6h7p-cgfc
+
+
+
+
+
+
+ GHSA-p3x9-6h7p-cgfc
+
+
+EOT;
+ // Missing content-type in actual response.
+ yield "data://text/plain,HTTP/1.1 200 OK\r\n\r\n{$xml}";
+}
+
+$r = http_server('genResponses', $output);
+$document = new \DOMDocument();
+$document->loadHTMLFile($r['uri']);
+
+$h1 = $document->getElementsByTagName('h1');
+var_dump($h1->length);
+var_dump($document->saveHTML());
+http_server_kill($r['pid']);
+?>
+--EXPECT--
+int(1)
+string(266) "
+
+
+ GHSA-p3x9-6h7p-cgfc
+
+
+
+
+
+
+ GHSA-p3x9-6h7p-cgfc
+
+
+"
diff --git a/ext/fileinfo/libmagic/cdf.c b/ext/fileinfo/libmagic/cdf.c
index c86763fa..ff542ba4 100644
--- a/ext/fileinfo/libmagic/cdf.c
+++ b/ext/fileinfo/libmagic/cdf.c
@@ -833,8 +833,9 @@ cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
- if (nelements == 0) {
- DPRINTF(("CDF_VECTOR with nelements == 0\n"));
+ if (nelements > CDF_ELEMENT_LIMIT || nelements == 0) {
+ DPRINTF(("CDF_VECTOR with nelements == %"
+ SIZE_T_FORMAT "u\n", nelements));
goto out;
}
o = 2;
@@ -909,8 +910,6 @@ cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
*info = inp;
inp = *info + nelem;
}
- DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
- nelements));
for (j = 0; j < nelements && i < sh.sh_properties;
j++, i++)
{
diff --git a/ext/fileinfo/libmagic/cdf.h b/ext/fileinfo/libmagic/cdf.h
index 00131e02..0dce332e 100644
--- a/ext/fileinfo/libmagic/cdf.h
+++ b/ext/fileinfo/libmagic/cdf.h
@@ -50,6 +50,7 @@
typedef int32_t cdf_secid_t;
#define CDF_LOOP_LIMIT 10000
+#define CDF_ELEMENT_LIMIT 100000
#define CDF_SECID_NULL 0
#define CDF_SECID_FREE -1
diff --git a/ext/filter/sanitizing_filters.c b/ext/filter/sanitizing_filters.c
index 9f3053e6..581667c8 100644
--- a/ext/filter/sanitizing_filters.c
+++ b/ext/filter/sanitizing_filters.c
@@ -71,7 +71,7 @@ static void php_filter_encode_url(zval *value, const unsigned char* chars, const
unsigned char *s = (unsigned char *)chars;
unsigned char *e = s + char_len;
- memset(tmp, 1, sizeof(tmp)-1);
+ memset(tmp, 1, sizeof(tmp));
while (s < e) {
tmp[*s++] = 0;
diff --git a/ext/filter/tests/filter_sanitize_encoded_0xff.phpt b/ext/filter/tests/filter_sanitize_encoded_0xff.phpt
new file mode 100644
index 00000000..1ee61aba
--- /dev/null
+++ b/ext/filter/tests/filter_sanitize_encoded_0xff.phpt
@@ -0,0 +1,12 @@
+--TEST--
+FILTER_SANITIZE_ENCODED percent-encodes 0xFF
+--EXTENSIONS--
+filter
+--FILE--
+
+--EXPECT--
+string(3) "%FF"
+string(10) "%FE%FF%00A"
diff --git a/ext/gd/libgd/gd_gif_in.c b/ext/gd/libgd/gd_gif_in.c
index 16776d36..44a1bdf2 100644
--- a/ext/gd/libgd/gd_gif_in.c
+++ b/ext/gd/libgd/gd_gif_in.c
@@ -449,7 +449,7 @@ LWZReadByte_(gdIOCtx *fd, LZW_STATIC_DATA *sd, char flag, int input_code_size, i
sd->table[1][i] = i;
}
for (; i < (1<table[0][i] = sd->table[1][0] = 0;
+ sd->table[0][i] = sd->table[1][i] = 0;
sd->sp = sd->stack;
@@ -493,6 +493,8 @@ LWZReadByte_(gdIOCtx *fd, LZW_STATIC_DATA *sd, char flag, int input_code_size, i
if (count != 0)
return -2;
+
+ return -2;
}
incode = code;
@@ -559,7 +561,7 @@ ReadImage(gdImagePtr im, gdIOCtx *fd, int len, int height, unsigned char (*cmap)
int v;
int xpos = 0, ypos = 0, pass = 0;
int i;
- LZW_STATIC_DATA sd;
+ LZW_STATIC_DATA sd = {0};
/*
diff --git a/ext/libxml/libxml.c b/ext/libxml/libxml.c
index 02453ffb..e3b1cfe6 100644
--- a/ext/libxml/libxml.c
+++ b/ext/libxml/libxml.c
@@ -411,6 +411,68 @@ php_libxml_input_buffer_create_filename(const char *URI, xmlCharEncoding enc)
return(NULL);
}
+ /* Check if there's been an external transport protocol with an encoding information */
+ if (enc == XML_CHAR_ENCODING_NONE) {
+ php_stream *s = (php_stream *) context;
+
+ if (s->wrapperdata != NULL && Z_TYPE_P(s->wrapperdata) == IS_ARRAY) {
+ HashTable *ht = Z_ARRVAL_P(s->wrapperdata);
+ zval **header;
+
+ /* Scan backwards: The header array might contain the headers for multiple responses, if
+ * a redirect was followed.
+ */
+ zend_hash_internal_pointer_end(ht);
+ while (zend_hash_get_current_data(ht, (void**)&header) == SUCCESS) {
+ const char buf[] = "Content-Type:";
+ if (Z_TYPE_PP(header) == IS_STRING) {
+ /* If no colon is found in the header, we assume it's the HTTP status line and bail out. */
+ char *colon = memchr(Z_STRVAL_PP(header), ':', Z_STRLEN_PP(header));
+ char *space = memchr(Z_STRVAL_PP(header), ' ', Z_STRLEN_PP(header));
+ if (colon == NULL || space < colon) {
+ break;
+ }
+
+ if (!zend_binary_strncasecmp(Z_STRVAL_PP(header), Z_STRLEN_PP(header), buf, sizeof(buf)-1, sizeof(buf)-1)) {
+ char *needle = estrdup("charset=");
+ char *haystack = estrndup(Z_STRVAL_PP(header), Z_STRLEN_PP(header));
+ char *encoding = php_stristr(haystack, needle, Z_STRLEN_PP(header), sizeof("charset=")-1);
+
+ if (encoding) {
+ char *end;
+
+ encoding += sizeof("charset=")-1;
+ if (*encoding == '"') {
+ encoding++;
+ }
+ end = strchr(encoding, ';');
+ if (end == NULL) {
+ end = encoding + strlen(encoding);
+ }
+ end--; /* end == encoding-1 isn't a buffer underrun */
+ while (*end == ' ' || *end == '\t') {
+ end--;
+ }
+ if (*end == '"') {
+ end--;
+ }
+ if (encoding >= end) continue;
+ *(end+1) = '\0';
+ enc = xmlParseCharEncoding(encoding);
+ if (enc <= XML_CHAR_ENCODING_NONE) {
+ enc = XML_CHAR_ENCODING_NONE;
+ }
+ }
+ efree(haystack);
+ efree(needle);
+ break; /* found content-type */
+ }
+ }
+ zend_hash_move_backwards(ht);
+ }
+ }
+ }
+
/* Allocate the Input buffer front-end. */
ret = xmlAllocParserInputBuffer(enc);
if (ret != NULL) {
@@ -502,7 +564,7 @@ static void _php_list_set_error_structure(xmlErrorPtr error, const char *msg)
error_copy.int1 = 0;
error_copy.int2 = 0;
error_copy.ctxt = NULL;
- error_copy.message = xmlStrdup(msg);
+ error_copy.message = (char*)xmlStrdup((xmlChar*)msg);
error_copy.file = NULL;
error_copy.str1 = NULL;
error_copy.str2 = NULL;
diff --git a/ext/libxml/tests/bug51903.phpt b/ext/libxml/tests/bug51903.phpt
new file mode 100644
index 00000000..36a4b557
--- /dev/null
+++ b/ext/libxml/tests/bug51903.phpt
@@ -0,0 +1,38 @@
+--TEST--
+Bug #51903 (simplexml_load_file() doesn't use HTTP headers)
+--SKIPIF--
+
+--FILE--
+\n"
+ . "\xE4\xF6\xFC\n",
+ "data://text/plain,HTTP/1.1 200 OK\r\n"
+ . "Content-Type: text/xml; charset=ISO-8859-1; foo=bar\r\n\r\n"
+ . "\n"
+ . "\xE4\xF6\xFC\n",
+ "data://text/plain,HTTP/1.1 200 OK\r\n"
+ . "Content-Type: text/xml; charset=\"ISO-8859-1\" ; foo=bar\r\n\r\n"
+ . "\n"
+ . "\xE4\xF6\xFC\n",
+];
+$pid = http_server('tcp://127.0.0.1:12342', $responses);
+
+for ($i = 0; $i < count($responses); $i++) {
+ $sxe = simplexml_load_file('http://127.0.0.1:12342/');
+ echo "$sxe\n";
+}
+
+http_server_kill($pid);
+?>
+--EXPECT--
+äöü
+äöü
+äöü
diff --git a/ext/mysqli/tests/fake_server.inc b/ext/mysqli/tests/fake_server.inc
new file mode 100644
index 00000000..a6c21c45
--- /dev/null
+++ b/ext/mysqli/tests/fake_server.inc
@@ -0,0 +1,877 @@
+ array(
+ 'type' => '03',
+ 'charset' => '3f00',
+ 'length' => '0b000000',
+ 'flags' => '0110',
+ 'decimal' => '00',
+ 'query_data_packet_length' => '080000',
+ 'query_data_value' => '023134',
+ 'stmt_data_packet_length' => '0b0000',
+ 'stmt_data_value' => '0e000000'
+ ),
+ 'fltval' => array(
+ 'type' => '04',
+ 'charset' => '3f00',
+ 'length' => '0c000000',
+ 'flags' => '0110',
+ 'decimal' => '1f',
+ 'query_data_packet_length' => '090000',
+ 'query_data_value' => '03322e33',
+ 'stmt_data_packet_length' => '0b0000',
+ 'stmt_data_value' => '33331340',
+ ),
+ 'dblval' => array(
+ 'type' => '05',
+ 'charset' => '3f00',
+ 'length' => '16000000',
+ 'flags' => '0110',
+ 'decimal' => '1f',
+ 'query_data_packet_length' => '090000',
+ 'query_data_value' => '03312e32',
+ 'stmt_data_packet_length' => '0f0000',
+ 'stmt_data_value' => '333333333333f33f'
+ ),
+ 'datval' => array(
+ 'type' => '0a',
+ 'charset' => '3f00',
+ 'length' => '0a000000',
+ 'flags' => '8110',
+ 'decimal' => '00',
+ 'query_data_packet_length' => '100000',
+ 'query_data_value' => '0a323031342d31322d3135',
+ 'stmt_data_packet_length' => '0c0000',
+ 'stmt_data_value' => '04de070c0f'
+ ),
+ 'timval' => array(
+ 'type' => '0b',
+ 'charset' => '3f00',
+ 'length' => '0a000000',
+ 'flags' => '8110',
+ 'decimal' => '00',
+ 'query_data_packet_length' => '0e0000',
+ 'query_data_value' => '0831333a30303a3032',
+ 'stmt_data_packet_length' => '100000',
+ 'stmt_data_value' => '080000000000150801'
+ ),
+ 'dtival' => array(
+ 'type' => '0c',
+ 'charset' => '3f00',
+ 'length' => '13000000',
+ 'flags' => '8110',
+ 'decimal' => '00',
+ 'query_data_packet_length' => '190000',
+ 'query_data_value' => '13323031342d31322d31362031333a30303a3031',
+ 'stmt_data_packet_length' => '0f0000',
+ 'stmt_data_value' => '07de070c100d0001'
+ ),
+ 'bitval' => array(
+ 'type' => '10',
+ 'charset' => '3f00',
+ 'length' => '40000000',
+ 'flags' => '2110',
+ 'decimal' => '00',
+ 'query_data_packet_length' => '0e0000',
+ 'query_data_value' => '080808080808080808',
+ 'stmt_data_packet_length' => '100000',
+ 'stmt_data_value' => '080808080808080808'
+ ),
+ 'strval' => array(
+ 'type' => 'fd',
+ 'charset' => 'e000',
+ 'length' => 'c8000000',
+ 'flags' => '0110',
+ 'decimal' => '00',
+ 'query_data_packet_length' => '0a0000',
+ 'query_data_value' => '0474657374',
+ 'stmt_data_packet_length' => '0c0000',
+ 'stmt_data_value' => '0474657374'
+ ),
+ );
+}
+
+function my_mysqli_data_field($field)
+{
+ $fields = my_mysqli_data_fields();
+ if (!isset($fields[$field])) {
+ throw new Exception("Unknown field $field");
+ }
+ return $fields[$field];
+}
+
+
+
+class my_mysqli_fake_packet_item
+{
+ public function __construct($name, $value, $is_hex = null)
+ {
+ $this->name = $name;
+ $this->value = $value;
+ $this->is_hex = $is_hex === null || $is_hex;
+ }
+}
+
+class my_mysqli_fake_packet
+{
+ private $data = array();
+
+ public function __get($name)
+ {
+ foreach ($this->data as $item) {
+ if ($item->name === $name) {
+ return $item->value;
+ }
+ }
+ return null;
+ }
+
+ public function __set($name, $value)
+ {
+ if ($value instanceof my_mysqli_fake_packet_item) {
+ if ($value->name === null) {
+ $value->name = $name;
+ }
+ } else {
+ $value = new my_mysqli_fake_packet_item($name, $value, true);
+ }
+
+ for ($i = 0; $i < count($this->data); $i++) {
+ if ($this->data[$i]->name === $name) {
+ $this->data[$i] = $value;
+ return;
+ }
+ }
+
+ $this->data[] = $value;
+ }
+
+ public function to_bytes()
+ {
+ $bytes = '';
+ foreach ($this->data as $item) {
+ $bytes .= $item->is_hex ? hex2bin($item->value) : $item->value;
+ }
+ return $bytes;
+ }
+}
+
+class my_mysqli_fake_packet_generator
+{
+ public static function create_packet_item($value, $is_hex = null, $format = null)
+ {
+ if (is_string($value)) {
+ $packed_value = $value;
+ } else {
+ $packed_value = pack($format === null ? 'v' : $format, $value);
+ }
+ return new my_mysqli_fake_packet_item(null, $packed_value, $is_hex == null ? false : $is_hex);
+ }
+
+ public function server_ok()
+ {
+ $packet = new my_mysqli_fake_packet();
+ $packet->packet_length = "070000";
+ $packet->packet_number = "02";
+ $packet->header = "00"; // OK
+ $packet->affected_rows = "00";
+ $packet->last_insert_id = "00";
+ $packet->server_status = "0200";
+ $packet->warning_count = "0000";
+ return $packet;
+ }
+
+ public function server_greetings()
+ {
+ $packet = new my_mysqli_fake_packet();
+ $packet->packet_length = "580000";
+ $packet->packet_number = "00";
+ $packet->proto_version = "0a";
+ $packet->version = self::create_packet_item('5.5.5-10.5.18-MariaDB' . chr(0));
+ $packet->thread_id = "03000000";
+ $packet->salt = "473e3f6047257c67";
+ $packet->filler = "00";
+ $packet->server_capabilities = self::create_packet_item(0b1111011111111110);
+ $packet->server_character_set = "08";
+ $packet->server_status = self::create_packet_item(0b000000000000010);
+ $packet->extended_server_capabilities = self::create_packet_item(0b1000000111111111);
+ $packet->auth_plugin = "15";
+ $packet->unused = "000000000000";
+ $packet->mariadb_extended_server_capabilities = self::create_packet_item(0b1111, false, 'V');
+ $packet->mariadb_extended_server_capabilities_salt = "6c6b55463f49335f686c643100";
+ $packet->mariadb_extended_server_capabilities_auth_plugin = self::create_packet_item('mysql_native_password');
+
+ return $packet;
+ }
+
+ public function server_tabular_query_response()
+ {
+ $qr1 = new my_mysqli_fake_packet();
+ $qr1->packet_length = "010000";
+ $qr1->packet_number = "01";
+ $qr1->field_count = "01";
+
+ $qr2 = new my_mysqli_fake_packet();
+ $qr2->packet_length = "190000";
+ $qr2->packet_number = "02";
+ $qr2->catalog_length_plus_name = "0164";
+ $qr2->db_length_plus_name = "0164";
+ $qr2->table_length_plus_name = "0164";
+ $qr2->original_t = "0164";
+ $qr2->name_length_plus_name = "0164";
+ $qr2->original_n = "0164";
+ $qr2->canary = "0c";
+ $qr2->charset = "3f00";
+ $qr2->length = "0b000000";
+ $qr2->type = "03";
+ $qr2->flags = "0350";
+ $qr2->decimals = "000000";
+
+ $qr3 = new my_mysqli_fake_packet();
+ $qr3->full = "05000003fe00002200";
+
+ $qr4 = new my_mysqli_fake_packet();
+ $qr4->full = "0400000401350174";
+
+ $qr5 = new my_mysqli_fake_packet();
+ $qr5->full = "05000005fe00002200";
+
+ return [$qr1, $qr2, $qr3, $qr4, $qr5];
+ }
+
+ public function server_upsert_query_response()
+ {
+ $qr1 = new my_mysqli_fake_packet();
+ $qr1->packet_length = "010000";
+ $qr1->packet_number = "01";
+ $qr1->field_count = "00"; // UPSERT
+ $qr1->affected_rows = "00";
+ $qr1->affected_rows = "00";
+ $qr1->last_insert_id = "00";
+ $qr1->server_status = "0000";
+ $qr1->warning_count = "0000";
+ $qr1->len = "01";
+ $qr1->filename = "65";
+ $qr1->packet_length = sprintf("%02x0000", strlen($qr1->to_bytes())-4);
+
+ return [$qr1];
+ }
+
+ public function server_stmt_prepare_response_start($num_field)
+ {
+ $pr1 = new my_mysqli_fake_packet();
+ $pr1->packet_length = "0c0000";
+ $pr1->packet_number = "01";
+ $pr1->response_code = '00'; // OK
+ $pr1->statement_id = '01000000';
+ $pr1->num_fields = $num_field;
+ $pr1->num_params = '0000';
+ $pr1->filler = '00';
+ $pr1->warnings = '0000';
+
+ return $pr1;
+ }
+
+ public function server_stmt_prepare_response_end($packer_number)
+ {
+ $pr3 = new my_mysqli_fake_packet();
+ $pr3->packet_length = "050000";
+ $pr3->packet_number = $packer_number;
+ $pr3->packet_type = 'fe'; // EOF
+ $pr3->warnings = '0000';
+ $pr3->server_status = '0200';
+
+ return $pr3;
+ }
+
+ public function server_stmt_prepare_items_response()
+ {
+ $pr1 = $this->server_stmt_prepare_response_start('0100');
+
+ $pr2 = new my_mysqli_fake_packet();
+ $pr2->packet_length = "300000";
+ $pr2->packet_number = "02";
+ $pr2->catalogue_len = '03';
+ $pr2->catalogue = '646566'; // def
+ $pr2->db_len = '08';
+ $pr2->db = '7068705f74657374'; // php_test
+ $pr2->table_len = '05';
+ $pr2->table = '6974656d73'; // items
+ $pr2->orig_table_len = '05';
+ $pr2->orig_table = '6974656d73'; // items
+ $pr2->name_len = '04';
+ $pr2->name = '6974656d';
+ $pr2->orig_name_len = '04';
+ $pr2->orig_name = '6974656d';
+ $pr2->something = '0c';
+ $pr2->charset = 'e000';
+ $pr2->length = 'c8000000';
+ $pr2->field_type = 'fd'; // FIELD_TYPE_VAR_STRING
+ $pr2->flags = '0110';
+ $pr2->decimal = '00';
+ $pr2->padding = '0000';
+
+ $pr3 = $this->server_stmt_prepare_response_end('03');
+
+ return [$pr1, $pr2, $pr3];
+ }
+
+ public function server_stmt_prepare_data_response_field($packet_number, $field_name)
+ {
+ if (strlen($field_name) != 6) {
+ throw new Exception("Invalid field length - only 6 is allowed");
+ }
+
+ $field = my_mysqli_data_field($field_name);
+
+ $pr = new my_mysqli_fake_packet();
+ $pr->packet_length = "320000";
+ $pr->packet_number = $packet_number;
+ $pr->catalogue_len = '03';
+ $pr->catalogue = bin2hex('def');
+ $pr->db_len = '08';
+ $pr->db = bin2hex('php_test');
+ $pr->table_len = '04';
+ $pr->table = bin2hex('data');
+ $pr->orig_table_len = '04';
+ $pr->orig_table = bin2hex('data');
+ $pr->name_len = '06';
+ $pr->name = bin2hex($field_name);
+ $pr->orig_name_len = '06';
+ $pr->orig_name = bin2hex($field_name);
+ $pr->something = '0c';
+ $pr->charset = $field['charset'];
+ $pr->length = $field['length'];
+ $pr->field_type = $field['type'];
+ $pr->flags = $field['flags'];
+ $pr->decimal = $field['decimal'];
+ $pr->padding = '0000';
+
+ return $pr;
+ }
+
+ public function server_stmt_prepare_data_response($field_name)
+ {
+ $pr1 = $this->server_stmt_prepare_response_start('0200');
+
+ $pr2 = $this->server_stmt_prepare_data_response_field('02', 'strval');
+ $pr3 = $this->server_stmt_prepare_data_response_field('03', $field_name);
+
+ $pr4 = $this->server_stmt_prepare_response_end('04');
+
+ return [$pr1, $pr2, $pr3, $pr4];
+ }
+
+ public function server_stmt_execute_items_response()
+ {
+ $pr1 = new my_mysqli_fake_packet();
+ $pr1->packet_length = "010000";
+ $pr1->packet_number = "01";
+ $pr1->num_fields = '01';
+
+ $pr2 = new my_mysqli_fake_packet();
+ $pr2->packet_length = "300000";
+ $pr2->packet_number = "02";
+ $pr2->catalogue_len = '03';
+ $pr2->catalogue = '646566'; // def
+ $pr2->db_len = '08';
+ $pr2->db = '7068705f74657374'; // php_test
+ $pr2->table_len = '05';
+ $pr2->table = '6974656d73'; // items
+ $pr2->orig_table_len = '05';
+ $pr2->orig_table = '6974656d73'; // items
+ $pr2->name_len = '04';
+ $pr2->name = '6974656d';
+ $pr2->orig_name_len = '04';
+ $pr2->orig_name = '6974656d';
+ $pr2->something = '0c';
+ $pr2->charset = 'e000';
+ $pr2->length = 'c8000000';
+ $pr2->field_type = 'fd'; // FIELD_TYPE_VAR_STRING
+ $pr2->flags = '0110';
+ $pr2->decimal = '00';
+ $pr2->padding = '0000';
+
+ $pr3 = new my_mysqli_fake_packet();
+ $pr3->packet_length = "050000";
+ $pr3->packet_number = "03";
+ $pr3->packet_type = 'fe'; // EOF
+ $pr3->warnings = '0000';
+ $pr3->server_status = '2200';
+
+ $pr4 = new my_mysqli_fake_packet();
+ $pr4->packet_length = "070000";
+ $pr4->packet_number = "04";
+ $pr4->packet_type = '00'; // OK
+ $pr4->affected_rows = '00';
+ $pr4->row_data_len = '04';
+ $pr4->row_data = '74657374'; // item
+
+ $pr5 = new my_mysqli_fake_packet();
+ $pr5->full = '05000005fe00002200';
+
+ return [$pr1, $pr2, $pr3, $pr4, $pr5];
+ }
+
+ private function server_execute_data_response_start($field_name)
+ {
+ $pr1 = new my_mysqli_fake_packet();
+ $pr1->packet_length = "010000";
+ $pr1->packet_number = "01";
+ $pr1->num_fields = '02';
+
+ $pr2 = new my_mysqli_fake_packet();
+ $pr2->packet_length = "320000";
+ $pr2->packet_number = "02";
+ $pr2->catalogue_len = '03';
+ $pr2->catalogue = '646566'; // def
+ $pr2->db_len = '08';
+ $pr2->db = '7068705f74657374'; // php_test
+ $pr2->table_len = '04';
+ $pr2->table = bin2hex('data');
+ $pr2->orig_table_len = '04';
+ $pr2->orig_table = bin2hex('data');
+ $pr2->name_len = '06';
+ $pr2->name = bin2hex('strval');
+ $pr2->orig_name_len = '06';
+ $pr2->orig_name = bin2hex('strval');
+ $pr2->something = '0c';
+ $pr2->charset = 'e000';
+ $pr2->length = 'c8000000';
+ $pr2->field_type = 'fd'; // FIELD_TYPE_VAR_STRING
+ $pr2->flags = '0110';
+ $pr2->decimal = '00';
+ $pr2->padding = '0000';
+
+ $field = my_mysqli_data_field($field_name);
+
+ $pr3 = new my_mysqli_fake_packet();
+ $pr3->packet_length = "320000";
+ $pr3->packet_number = "03";
+ $pr3->catalogue_len = '03';
+ $pr3->catalogue = '646566'; // def
+ $pr3->db_len = '08';
+ $pr3->db = '7068705f74657374'; // php_test
+ $pr3->table_len = '04';
+ $pr3->table = bin2hex('data');
+ $pr3->orig_table_len = '04';
+ $pr3->orig_table = bin2hex('data');
+ $pr3->name_len = '06';
+ $pr3->name = bin2hex($field_name);
+ $pr3->orig_name_len = '06';
+ $pr3->orig_name = bin2hex($field_name);
+ $pr3->something = '0c';
+ $pr3->charset = $field['charset'];
+ $pr3->length = $field['length'];
+ $pr3->field_type = $field['type'];
+ $pr3->flags = $field['flags'];
+ $pr3->decimal = $field['decimal'];
+ $pr3->padding = '0000';
+
+ $pr4 = new my_mysqli_fake_packet();
+ $pr4->packet_length = "050000";
+ $pr4->packet_number = "04";
+ $pr4->packet_type = 'fe'; // EOF
+ $pr4->warnings = '0000';
+ $pr4->server_status = '2200';
+
+ return [$field, $pr1, $pr2, $pr3, $pr4];
+ }
+
+ private function server_execute_data_response_end()
+ {
+ $pr6 = new my_mysqli_fake_packet();
+ $pr6->packet_length = '050000';
+ $pr6->packet_number = "06";
+ $pr6->packet_type = 'fe'; // EOF
+ $pr6->warnings = '0000';
+ $pr6->server_status = '2200';
+
+ return $pr6;
+ }
+
+ public function server_stmt_execute_data_response($field_name)
+ {
+ $arr = $this->server_execute_data_response_start($field_name);
+ $field = $arr[0];
+ $pr1 = $arr[1];
+ $pr2 = $arr[2];
+ $pr3 = $arr[3];
+ $pr4 = $arr[4];
+
+ $pr5 = new my_mysqli_fake_packet();
+ $pr5->packet_length = $field['stmt_data_packet_length'];
+ $pr5->packet_number = "05";
+ $pr5->packet_type = '00'; // OK
+ $pr5->affected_rows = '00';
+ $pr5->row_field1_len = '04';
+ $pr5->row_field1_data = '74657374'; // test
+ $pr5->row_field2 = $field['stmt_data_value'];
+
+ return [$pr1, $pr2, $pr3, $pr4, $pr5, $this->server_execute_data_response_end()];
+ }
+
+ public function server_query_execute_data_response($field_name)
+ {
+ $arr = $this->server_execute_data_response_start($field_name);
+ $field = $arr[0];
+ $pr1 = $arr[1];
+ $pr2 = $arr[2];
+ $pr3 = $arr[3];
+ $pr4 = $arr[4];
+
+ $pr5 = new my_mysqli_fake_packet();
+ $pr5->packet_length = $field['query_data_packet_length'];
+ $pr5->packet_number = "05";
+ $pr5->row_field1_len = '04';
+ $pr5->row_field1_data = '74657374'; // test
+ $pr5->row_field2 = $field['query_data_value'];
+
+ return [$pr1, $pr2, $pr3, $pr4, $pr5, $this->server_execute_data_response_end()];
+ }
+}
+
+class my_mysqli_fake_server_conn
+{
+ private $conn;
+ public $packet_generator;
+
+ public function __construct($socket)
+ {
+ $this->packet_generator = new my_mysqli_fake_packet_generator();
+ $this->conn = stream_socket_accept($socket);
+ if ($this->conn) {
+ fprintf(STDERR, "[*] Connection established\n");
+ } else {
+ fprintf(STDERR, "[*] Failed to establish connection\n");
+ }
+ }
+
+ public function packets_to_bytes(array $packets)
+ {
+ return implode('', array_map(function($s) { return $s->to_bytes(); }, $packets));
+ }
+
+ public function send($payload, $message = null)
+ {
+ if ($message) {
+ fprintf(STDERR, "[*] Sending - %s: %s\n", $message, bin2hex($payload));
+ }
+ fwrite($this->conn, $payload);
+ }
+
+ public function read($bytes_len = 1024)
+ {
+ // wait 20ms to fill the buffer
+ usleep(20000);
+ $data = fread($this->conn, $bytes_len);
+ if ($data) {
+ fprintf(STDERR, "[*] Received: %s\n", bin2hex($data));
+ }
+ }
+
+ public function close()
+ {
+ fclose($this->conn);
+ }
+
+ public function send_server_greetings()
+ {
+ $this->send($this->packet_generator->server_greetings()->to_bytes(), "Server Greeting");
+ }
+
+ public function send_server_ok()
+ {
+ $this->send($this->packet_generator->server_ok()->to_bytes(), "Server OK");
+ }
+
+ public function send_server_tabular_query_response()
+ {
+ $packets = $this->packet_generator->server_tabular_query_response();
+ $this->send($this->packets_to_bytes($packets), "Tabular response");
+ }
+
+ public function send_server_stmt_prepare_items_response()
+ {
+ $packets = $this->packet_generator->server_stmt_prepare_items_response();
+ $this->send($this->packets_to_bytes($packets), "Stmt prepare items");
+ }
+
+
+ public function send_server_stmt_prepare_data_response($field_name)
+ {
+ $packets = $this->packet_generator->server_stmt_prepare_data_response($field_name);
+ $this->send($this->packets_to_bytes($packets), "Stmt prepare data $field_name");
+ }
+
+ public function send_server_stmt_execute_items_response()
+ {
+ $packets = $this->packet_generator->server_stmt_execute_items_response();
+ $this->send($this->packets_to_bytes($packets), "Stmt execute items");
+ }
+
+ public function send_server_stmt_execute_data_response($field_name)
+ {
+ $packets = $this->packet_generator->server_stmt_execute_data_response($field_name);
+ $this->send($this->packets_to_bytes($packets), "Stmt execute data $field_name");
+ }
+
+ public function send_server_query_execute_data_response($field_name)
+ {
+ $packets = $this->packet_generator->server_query_execute_data_response($field_name);
+ $this->send($this->packets_to_bytes($packets), "Query execute data $field_name");
+ }
+}
+
+class my_mysqli_fake_server_process
+{
+ public function __construct($process, array $pipes)
+ {
+ $this->process = $process;
+ $this->pipes = $pipes;
+ }
+
+ public function terminate($wait = null)
+ {
+ if ($wait !== null && $wait) {
+ $this->wait();
+ }
+ proc_terminate($this->process);
+ }
+
+ public function wait()
+ {
+ echo fgets($this->pipes[1]);
+ }
+}
+
+function my_mysqli_test_tabular_response_def_over_read(my_mysqli_fake_server_conn $conn)
+{
+ $rh = $conn->packet_generator->server_tabular_query_response();
+
+ // Length of the packet is modified to include the next added data
+ $rh[1]->packet_length = "1e0000";
+
+ // We add a length field encoded on 4 bytes which evaluates to 65536. If the process crashes because
+ // the heap has been overread, lower this value.
+ $rh[1]->extra_def_size = "fd000001"; # 65536
+
+ // Filler
+ $rh[1]->extra_def_data = "aa";
+
+ $trrh = $conn->packets_to_bytes($rh);
+
+ $conn->send_server_greetings();
+ $conn->read();
+ $conn->send_server_ok();
+ $conn->read();
+ $conn->send($trrh, "Malicious Tabular Response [Extract heap through buffer over-read]");
+ $conn->read(65536);
+}
+
+function my_mysqli_test_upsert_response_filename_over_read(my_mysqli_fake_server_conn $conn)
+{
+ $rh = $conn->packet_generator->server_upsert_query_response();
+
+ // Set extra length to overread
+ $rh[0]->len = "fa";
+
+ $trrh = $conn->packets_to_bytes($rh);
+
+ $conn->send_server_greetings();
+ $conn->read();
+ $conn->send_server_ok();
+ $conn->read();
+ $conn->send($trrh, "Malicious Tabular Response [Extract heap through buffer over-read]");
+ $conn->read(65536);
+}
+
+function my_mysqli_test_auth_response_message_over_read(my_mysqli_fake_server_conn $conn)
+{
+ $p = $conn->packet_generator->server_ok();
+ $p->packet_length = "090000";
+ $p->message_len = "fcff";
+
+ $conn->send_server_greetings();
+ $conn->read();
+ $conn->send($p->to_bytes(), "Malicious OK Auth Response [Extract heap through buffer over-read]");
+ $conn->read();
+}
+
+function my_mysqli_test_stmt_response_row_over_read_string(my_mysqli_fake_server_conn $conn)
+{
+ $rh = $conn->packet_generator->server_stmt_execute_items_response();
+
+ // Set extra length to overread
+ $rh[3]->row_data_len = "fa";
+
+ $conn->send_server_greetings();
+ $conn->read();
+ $conn->send_server_ok();
+ $conn->read();
+ $conn->send_server_stmt_prepare_items_response();
+ $conn->read();
+ $conn->send($conn->packets_to_bytes($rh), "Malicious Stmt Response for items [Extract heap through buffer over-read]");
+ $conn->read(65536);
+}
+
+function my_mysqli_test_stmt_response_row_over_read_two_fields(
+ my_mysqli_fake_server_conn $conn,
+ $field_name,
+ $row_field1_len = null
+) {
+ $rh = $conn->packet_generator->server_stmt_execute_data_response($field_name);
+
+ // Set extra length to overread by two bytes
+ $rh[4]->row_field1_len = $row_field1_len === null ? '06' : $row_field1_len;
+
+ $conn->send_server_greetings();
+ $conn->read();
+ $conn->send_server_ok();
+ $conn->read();
+ $conn->send_server_stmt_prepare_data_response($field_name);
+ $conn->read();
+ $conn->send(
+ $conn->packets_to_bytes($rh),
+ "Malicious Stmt Response for data $field_name [Extract heap through buffer over-read]"
+ );
+ $conn->read(65536);
+}
+
+function my_mysqli_test_stmt_response_row_over_read_int(my_mysqli_fake_server_conn $conn)
+{
+ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'intval');
+}
+
+function my_mysqli_test_stmt_response_row_over_read_float(my_mysqli_fake_server_conn $conn)
+{
+ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'fltval');
+}
+
+function my_mysqli_test_stmt_response_row_over_read_double(my_mysqli_fake_server_conn $conn)
+{
+ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'dblval');
+}
+
+function my_mysqli_test_stmt_response_row_over_read_date(my_mysqli_fake_server_conn $conn)
+{
+ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'datval');
+}
+
+function my_mysqli_test_stmt_response_row_over_read_time(my_mysqli_fake_server_conn $conn)
+{
+ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'timval', '0c');
+}
+
+function my_mysqli_test_stmt_response_row_over_read_datetime(my_mysqli_fake_server_conn $conn)
+{
+ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'dtival');
+}
+
+function my_mysqli_test_stmt_response_row_no_space(my_mysqli_fake_server_conn $conn)
+{
+ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'strval', '09');
+}
+
+function my_mysqli_test_stmt_response_row_over_read_bit(my_mysqli_fake_server_conn $conn)
+{
+ my_mysqli_test_stmt_response_row_over_read_two_fields($conn, 'bitval');
+}
+
+function my_mysqli_test_stmt_response_row_read_two_fields(my_mysqli_fake_server_conn $conn)
+{
+ $conn->send_server_greetings();
+ $conn->read();
+ $conn->send_server_ok();
+ $conn->read();
+ $field_names = array_keys(my_mysqli_data_fields());
+ foreach ($field_names as $field_name) {
+ $conn->send_server_stmt_prepare_data_response($field_name);
+ $conn->read(65536);
+ $conn->send_server_stmt_execute_data_response($field_name);
+ $conn->read(65536);
+ }
+}
+
+function my_mysqli_test_query_response_row_length_overflow(my_mysqli_fake_server_conn $conn)
+{
+ $rh = $conn->packet_generator->server_query_execute_data_response('strval');
+
+ // Set extra length to overread by two bytes
+ $rh[4]->row_field2 = 'fefefefefe';
+
+ $conn->send_server_greetings();
+ $conn->read();
+ $conn->send_server_ok();
+ $conn->read();
+ $conn->send($conn->packets_to_bytes($rh), "Malicious Query Response for data strval field [length overflow]");
+ $conn->read(65536);
+}
+
+function my_mysqli_test_query_response_row_read_two_fields(my_mysqli_fake_server_conn $conn)
+{
+ $conn->send_server_greetings();
+ $conn->read();
+ $conn->send_server_ok();
+ $conn->read();
+ $field_names = array_keys(my_mysqli_data_fields());
+ foreach ($field_names as $field_name) {
+ $conn->send_server_query_execute_data_response($field_name);
+ $conn->read();
+ }
+}
+
+function run_fake_server($test_function, $port)
+{
+ $address = '127.0.0.1';
+ if ($port === null) {
+ $port = 33305;
+ }
+
+ $socket = @stream_socket_server("tcp://$address:$port", $errno, $errstr);
+ if (!$socket) {
+ die("Failed to create socket: $errstr ($errno)\n");
+ }
+ echo "[*] Server started\n";
+
+ try {
+ $conn = new my_mysqli_fake_server_conn($socket);
+ $test_function_name = 'my_mysqli_test_' . $test_function;
+ call_user_func($test_function_name, $conn);
+ $conn->close();
+ } catch (Exception $e) {
+ fprintf(STDERR, "[!] Exception: " . $e->getMessage() . "\n");
+ }
+
+ fclose($socket);
+
+ echo "[*] Server finished\n";
+}
+
+
+function run_fake_server_in_background($test_function, $port)
+{
+ $command = array(PHP_BINARY, '-n', __FILE__, 'mysqli_fake_server', $test_function,
+ $port === null ? 33305 : $port);
+
+ $descriptorspec = array(
+ 0 => array("pipe", "r"),
+ 1 => array("pipe", "w"),
+ 2 => STDERR,
+ );
+
+ $process = proc_open(implode(' ', $command), $descriptorspec, $pipes);
+
+ if (is_resource($process)) {
+ return new my_mysqli_fake_server_process($process, $pipes);
+ } else {
+ throw new Exception("Failed to start server process");
+ }
+}
+
+if (isset($argv) && $argc > 2 && $argv[1] == 'mysqli_fake_server') {
+ run_fake_server($argv[2], $argv[3]);
+}
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-auth-message.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-auth-message.phpt
new file mode 100644
index 00000000..09ebcf43
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-auth-message.phpt
@@ -0,0 +1,43 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - auth message buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+try {
+ $conn = new mysqli( $servername, $username, $password, "", $port );
+ $info = mysqli_info($conn);
+ var_dump($info);
+} catch (Exception $e) {
+ echo $e->getMessage() . PHP_EOL;
+}
+
+$process->terminate();
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Malicious OK Auth Response [Extract heap through buffer over-read]: 0900000200000002000000fcff
+
+Warning: mysqli::mysqli(): OK packet message length is past the packet size in %s on line %d
+
+Warning: mysqli::mysqli(): [%d] (trying to connect via tcp://127.0.0.1:33305) in %s on line %d
+%A
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-def.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-def.phpt
new file mode 100644
index 00000000..08aacced
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-def.phpt
@@ -0,0 +1,50 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - tabular default)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Running query on the fake server...\n";
+
+$result = $conn->query("SELECT * from users");
+
+if ($result) {
+ $all_fields = $result->fetch_fields();
+ var_dump($result->fetch_all(MYSQLI_ASSOC));
+ var_dump(get_object_vars($all_fields[0])["def"]);
+}
+
+$conn->close();
+
+$process->terminate();
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Running query on the fake server...
+[*] Received: 140000000353454c454354202a2066726f6d207573657273
+[*] Sending - Malicious Tabular Response [Extract heap through buffer over-read]: 01000001011e0000020164016401640164016401640c3f000b000000030350000000fd000001aa05000003fe00002200040000040135017405000005fe00002200
+
+Warning: mysqli::query(): RSET_FIELD packet additional data length is past 61469 bytes the packet size in %s on line %d
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-filename.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-filename.phpt
new file mode 100644
index 00000000..5d43ab7a
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-filename.phpt
@@ -0,0 +1,46 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - upsert filename buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+echo "[*] Running query on the fake server...\n";
+
+$result = $conn->query("SELECT * from users");
+$info = mysqli_info($conn);
+
+var_dump($info);
+
+$process->terminate();
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Running query on the fake server...
+[*] Received: 140000000353454c454354202a2066726f6d207573657273
+[*] Sending - Malicious Tabular Response [Extract heap through buffer over-read]: 0900000100000000000000fa65
+
+Warning: mysqli::query(): RSET_HEADER packet additional data length is past 249 bytes the packet size in %s on line %d
+
+Warning: mysqli::query(): Error reading result set's header in %s on line %d
+NULL
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-query-len-overflow.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-query-len-overflow.phpt
new file mode 100644
index 00000000..e10510ed
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-query-len-overflow.phpt
@@ -0,0 +1,51 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row no space for the field)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Query the fake server...\n";
+$sql = "SELECT strval, strval FROM data";
+
+$result = $conn->query($sql);
+
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row['strval']);
+ }
+}
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Query the fake server...
+[*] Received: 200000000353454c4543542073747276616c2c2073747276616c2046524f4d2064617461
+[*] Sending - Malicious Query Response for data strval field [length overflow]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000a0000050474657374fefefefefe05000006fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after end of packet in %s on line %A
+[*] Received: 0100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-bit.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-bit.phpt
new file mode 100644
index 00000000..db4793ae
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-bit.phpt
@@ -0,0 +1,56 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row bit buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Preparing statement on the fake server...\n";
+$stmt = $conn->prepare("SELECT bitval, timval FROM data");
+
+$stmt->execute();
+$result = $stmt->get_result();
+
+// Fetch and display the results
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row["bitval"]);
+ }
+}
+$stmt->close();
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Preparing statement on the fake server...
+[*] Received: 200000001653454c4543542062697476616c2c2074696d76616c2046524f4d2064617461
+[*] Sending - Stmt prepare data bitval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Malicious Stmt Response for data bitval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe00002200100000050000067465737408080808080808080805000006fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %A
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-date.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-date.phpt
new file mode 100644
index 00000000..836341d6
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-date.phpt
@@ -0,0 +1,56 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row date buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Preparing statement on the fake server...\n";
+$stmt = $conn->prepare("SELECT strval, datval FROM data");
+
+$stmt->execute();
+$result = $stmt->get_result();
+
+// Fetch and display the results
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row["datval"]);
+ }
+}
+$stmt->close();
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Preparing statement on the fake server...
+[*] Received: 200000001653454c4543542073747276616c2c2064617476616c2046524f4d2064617461
+[*] Sending - Stmt prepare data datval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Malicious Stmt Response for data datval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe000022000c0000050000067465737404de070c0f05000006fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %A
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-datetime.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-datetime.phpt
new file mode 100644
index 00000000..11aa82dc
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-datetime.phpt
@@ -0,0 +1,56 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row datetime buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Preparing statement on the fake server...\n";
+$stmt = $conn->prepare("SELECT strval, dtival FROM data");
+
+$stmt->execute();
+$result = $stmt->get_result();
+
+// Fetch and display the results
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row["dtival"]);
+ }
+}
+$stmt->close();
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Preparing statement on the fake server...
+[*] Received: 200000001653454c4543542073747276616c2c2064746976616c2046524f4d2064617461
+[*] Sending - Stmt prepare data dtival: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Malicious Stmt Response for data dtival [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe000022000f0000050000067465737407de070c100d000105000006fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %A
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-double.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-double.phpt
new file mode 100644
index 00000000..513bccc8
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-double.phpt
@@ -0,0 +1,56 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row double buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Preparing statement on the fake server...\n";
+$stmt = $conn->prepare("SELECT strval, dblval FROM data");
+
+$stmt->execute();
+$result = $stmt->get_result();
+
+// Fetch and display the results
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row["dblval"]);
+ }
+}
+$stmt->close();
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Preparing statement on the fake server...
+[*] Received: 200000001653454c4543542073747276616c2c2064626c76616c2046524f4d2064617461
+[*] Sending - Stmt prepare data dblval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Malicious Stmt Response for data dblval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe000022000f00000500000674657374333333333333f33f05000006fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %A
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-float.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-float.phpt
new file mode 100644
index 00000000..0b51b467
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-float.phpt
@@ -0,0 +1,56 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row int buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Preparing statement on the fake server...\n";
+$stmt = $conn->prepare("SELECT strval, fltval FROM data");
+
+$stmt->execute();
+$result = $stmt->get_result();
+
+// Fetch and display the results
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row["fltval"]);
+ }
+}
+$stmt->close();
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Preparing statement on the fake server...
+[*] Received: 200000001653454c4543542073747276616c2c20666c7476616c2046524f4d2064617461
+[*] Sending - Stmt prepare data fltval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Malicious Stmt Response for data fltval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe000022000b000005000006746573743333134005000006fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %A
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-int.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-int.phpt
new file mode 100644
index 00000000..a97f0261
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-int.phpt
@@ -0,0 +1,56 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row int buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Preparing statement on the fake server...\n";
+$stmt = $conn->prepare("SELECT strval, intval FROM data");
+
+$stmt->execute();
+$result = $stmt->get_result();
+
+// Fetch and display the results
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row["intval"]);
+ }
+}
+$stmt->close();
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Preparing statement on the fake server...
+[*] Received: 200000001653454c4543542073747276616c2c20696e7476616c2046524f4d2064617461
+[*] Sending - Stmt prepare data intval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Malicious Stmt Response for data intval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe000022000b000005000006746573740e00000005000006fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %A
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-no-space.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-no-space.phpt
new file mode 100644
index 00000000..62219cbb
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-no-space.phpt
@@ -0,0 +1,56 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row no space for the field)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Preparing statement on the fake server...\n";
+$stmt = $conn->prepare("SELECT strval, strval FROM data");
+
+$stmt->execute();
+$result = $stmt->get_result();
+
+// Fetch and display the results
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row["strval"]);
+ }
+}
+$stmt->close();
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Preparing statement on the fake server...
+[*] Received: 200000001653454c4543542073747276616c2c2073747276616c2046524f4d2064617461
+[*] Sending - Stmt prepare data strval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Malicious Stmt Response for data strval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000c00000500000974657374047465737405000006fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. No packet space left for the field in %s on line %A
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-string.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-string.phpt
new file mode 100644
index 00000000..1e026826
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-string.phpt
@@ -0,0 +1,56 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row string buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Preparing statement on the fake server...\n";
+$stmt = $conn->prepare("SELECT item FROM items");
+
+$stmt->execute();
+$result = $stmt->get_result();
+
+// Fetch and display the results
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row["item"]);
+ }
+}
+$stmt->close();
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Preparing statement on the fake server...
+[*] Received: 170000001653454c454354206974656d2046524f4d206974656d73
+[*] Sending - Stmt prepare items: 0c0000010001000000010000000000003000000203646566087068705f74657374056974656d73056974656d73046974656d046974656d0ce000c8000000fd011000000005000003fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Malicious Stmt Response for items [Extract heap through buffer over-read]: 01000001013000000203646566087068705f74657374056974656d73056974656d73046974656d046974656d0ce000c8000000fd011000000005000003fe00002200070000040000fa7465737405000005fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %A
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-time.phpt b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-time.phpt
new file mode 100644
index 00000000..81e77103
--- /dev/null
+++ b/ext/mysqli/tests/ghsa-h35g-vwh6-m678-stmt-row-time.phpt
@@ -0,0 +1,56 @@
+--TEST--
+GHSA-h35g-vwh6-m678 (mysqlnd leaks partial content of the heap - stmt row time buffer over-read)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+echo "[*] Preparing statement on the fake server...\n";
+$stmt = $conn->prepare("SELECT strval, timval FROM data");
+
+$stmt->execute();
+$result = $stmt->get_result();
+
+// Fetch and display the results
+if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row["timval"]);
+ }
+}
+$stmt->close();
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Preparing statement on the fake server...
+[*] Received: 200000001653454c4543542073747276616c2c2074696d76616c2046524f4d2064617461
+[*] Sending - Stmt prepare data timval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Malicious Stmt Response for data timval [Extract heap through buffer over-read]: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe000022001000000500000c7465737408000000000015080105000006fe00002200
+
+Warning: mysqli_result::fetch_assoc(): Malformed server packet. Field length pointing after the end of packet in %s on line %A
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/protocol_query_row_fetch_data.phpt b/ext/mysqli/tests/protocol_query_row_fetch_data.phpt
new file mode 100644
index 00000000..1c648812
--- /dev/null
+++ b/ext/mysqli/tests/protocol_query_row_fetch_data.phpt
@@ -0,0 +1,77 @@
+--TEST--
+MySQL protocol - statement row data fetch)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+function my_query($conn, $field)
+{
+ $sql = "SELECT strval, $field FROM data";
+
+ $result = $conn->query($sql);
+
+ if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row[$field]);
+ }
+ }
+}
+
+foreach (my_mysqli_data_fields() as $field_name => $field) {
+ my_query($conn, $field_name);
+}
+
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECT--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Received: 200000000353454c4543542073747276616c2c20696e7476616c2046524f4d2064617461
+[*] Sending - Query execute data intval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe0000220008000005047465737402313405000006fe00002200
+string(2) "14"
+[*] Received: 200000000353454c4543542073747276616c2c20666c7476616c2046524f4d2064617461
+[*] Sending - Query execute data fltval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe0000220009000005047465737403322e3305000006fe00002200
+string(3) "2.3"
+[*] Received: 200000000353454c4543542073747276616c2c2064626c76616c2046524f4d2064617461
+[*] Sending - Query execute data dblval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe0000220009000005047465737403312e3205000006fe00002200
+string(3) "1.2"
+[*] Received: 200000000353454c4543542073747276616c2c2064617476616c2046524f4d2064617461
+[*] Sending - Query execute data datval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe000022001000000504746573740a323031342d31322d313505000006fe00002200
+string(10) "2014-12-15"
+[*] Received: 200000000353454c4543542073747276616c2c2074696d76616c2046524f4d2064617461
+[*] Sending - Query execute data timval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe000022000e00000504746573740831333a30303a303205000006fe00002200
+string(8) "13:00:02"
+[*] Received: 200000000353454c4543542073747276616c2c2064746976616c2046524f4d2064617461
+[*] Sending - Query execute data dtival: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe0000220019000005047465737413323031342d31322d31362031333a30303a303105000006fe00002200
+string(19) "2014-12-16 13:00:01"
+[*] Received: 200000000353454c4543542073747276616c2c2062697476616c2046524f4d2064617461
+[*] Sending - Query execute data bitval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe000022000e000005047465737408080808080808080805000006fe00002200
+string(18) "578721382704613384"
+[*] Received: 200000000353454c4543542073747276616c2c2073747276616c2046524f4d2064617461
+[*] Sending - Query execute data strval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000a0000050474657374047465737405000006fe00002200
+string(4) "test"
+[*] Received: 0100000001
+[*] Server finished
+done!
diff --git a/ext/mysqli/tests/protocol_stmt_row_fetch_data.phpt b/ext/mysqli/tests/protocol_stmt_row_fetch_data.phpt
new file mode 100644
index 00000000..823b82a2
--- /dev/null
+++ b/ext/mysqli/tests/protocol_stmt_row_fetch_data.phpt
@@ -0,0 +1,94 @@
+--TEST--
+MySQL protocol - statement row data fetch)
+--SKIPIF--
+
+--FILE--
+wait();
+
+$conn = new mysqli($servername, $username, $password, "", $port);
+
+function my_query($conn, $field)
+{
+ $stmt = $conn->prepare("SELECT strval, $field FROM data");
+
+ $stmt->execute();
+ $result = $stmt->get_result();
+
+ if ($result->num_rows > 0) {
+ while ($row = $result->fetch_assoc()) {
+ var_dump($row[$field]);
+ }
+ }
+}
+
+foreach (my_mysqli_data_fields() as $field_name => $field) {
+ my_query($conn, $field_name);
+}
+
+$conn->close();
+
+$process->terminate(true);
+
+print "done!";
+?>
+--EXPECTF--
+[*] Server started
+[*] Connection established
+[*] Sending - Server Greeting: 580000000a352e352e352d31302e352e31382d4d6172696144420003000000473e3f6047257c6700fef7080200ff81150000000000000f0000006c6b55463f49335f686c6431006d7973716c5f6e61746976655f70617373776f7264
+[*] Received: 530000018da20a00000000c0080000000000000000000000000000000000000000000000726f6f740000006d7973716c5f6e61746976655f70617373776f726400150c5f636c69656e745f6e616d65076d7973716c6e64
+[*] Sending - Server OK: 0700000200000002000000
+[*] Received: 200000001653454c4543542073747276616c2c20696e7476616c2046524f4d2064617461
+[*] Sending - Stmt prepare data intval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Stmt execute data intval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106696e7476616c06696e7476616c0c3f000b00000003011000000005000004fe000022000b000005000004746573740e00000005000006fe00002200
+int(14)
+[*] Received: 050000001901000000200000001653454c4543542073747276616c2c20666c7476616c2046524f4d2064617461
+[*] Sending - Stmt prepare data fltval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Stmt execute data fltval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f746573740464617461046461746106666c7476616c06666c7476616c0c3f000c0000000401101f000005000004fe000022000b000005000004746573743333134005000006fe00002200
+float(2.3)
+[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2064626c76616c2046524f4d2064617461
+[*] Sending - Stmt prepare data dblval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Stmt execute data dblval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664626c76616c0664626c76616c0c3f00160000000501101f000005000004fe000022000f00000500000474657374333333333333f33f05000006fe00002200
+float(1.2)
+[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2064617476616c2046524f4d2064617461
+[*] Sending - Stmt prepare data datval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Stmt execute data datval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664617476616c0664617476616c0c3f000a0000000a811000000005000004fe000022000c0000050000047465737404de070c0f05000006fe00002200
+string(10) "2014-12-15"
+[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2074696d76616c2046524f4d2064617461
+[*] Sending - Stmt prepare data timval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Stmt execute data timval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610674696d76616c0674696d76616c0c3f000a0000000b811000000005000004fe00002200100000050000047465737408000000000015080105000006fe00002200
+string(8) "21:08:01"
+[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2064746976616c2046524f4d2064617461
+[*] Sending - Stmt prepare data dtival: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Stmt execute data dtival: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610664746976616c0664746976616c0c3f00130000000c811000000005000004fe000022000f0000050000047465737407de070c100d000105000006fe00002200
+string(19) "2014-12-16 13:00:01"
+[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2062697476616c2046524f4d2064617461
+[*] Sending - Stmt prepare data bitval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Stmt execute data bitval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610662697476616c0662697476616c0c3f004000000010211000000005000004fe00002200100000050000047465737408080808080808080805000006fe00002200
+%s578721382704613384%s
+[*] Received: 050000001901000000200000001653454c4543542073747276616c2c2073747276616c2046524f4d2064617461
+[*] Sending - Stmt prepare data strval: 0c0000010001000000020000000000003200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe00000200
+[*] Received: 0b0000001701000000000100000000
+[*] Sending - Stmt execute data strval: 01000001023200000203646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd01100000003200000303646566087068705f74657374046461746104646174610673747276616c0673747276616c0ce000c8000000fd011000000005000004fe000022000c00000500000474657374047465737405000006fe00002200
+string(4) "test"
+[*] Received: 0500000019010000000100000001
+[*] Server finished
+done!
diff --git a/ext/mysqlnd/mysqlnd_ps.c b/ext/mysqlnd/mysqlnd_ps.c
index e3bfc7b7..5ed2ff0a 100644
--- a/ext/mysqlnd/mysqlnd_ps.c
+++ b/ext/mysqlnd/mysqlnd_ps.c
@@ -1975,8 +1975,9 @@ MYSQLND_METHOD(mysqlnd_stmt, free_result)(MYSQLND_STMT * const s TSRMLS_DC)
stmt->state = MYSQLND_STMT_PREPARED;
}
- /* Line is free! */
- CONN_SET_STATE(stmt->conn, CONN_READY);
+ if (CONN_GET_STATE(stmt->conn) != CONN_QUIT_SENT) {
+ CONN_SET_STATE(stmt->conn, CONN_READY);
+ }
DBG_RETURN(PASS);
}
diff --git a/ext/mysqlnd/mysqlnd_ps_codec.c b/ext/mysqlnd/mysqlnd_ps_codec.c
index def140ad..8cf08dba 100644
--- a/ext/mysqlnd/mysqlnd_ps_codec.c
+++ b/ext/mysqlnd/mysqlnd_ps_codec.c
@@ -53,14 +53,50 @@ struct st_mysqlnd_perm_bind mysqlnd_ps_fetch_functions[MYSQL_TYPE_LAST + 1];
#define MYSQLND_PS_SKIP_RESULT_W_LEN -1
#define MYSQLND_PS_SKIP_RESULT_STR -2
+static inline void ps_fetch_over_read_error(zend_uchar ** row)
+{
+ php_error_docref(NULL, E_WARNING, "Malformed server packet. Field length pointing after the end of packet");
+ *row = NULL;
+}
+
+static inline zend_bool ps_fetch_is_packet_over_read_with_variable_length(const unsigned int pack_len,
+ zend_uchar ** row, const zend_uchar *p, unsigned long length)
+{
+ if (pack_len == 0) {
+ return 0;
+ }
+ size_t length_len = *row - p;
+ if (length_len > pack_len || length > pack_len - length_len) {
+ ps_fetch_over_read_error(row);
+ return 1;
+ }
+ return 0;
+}
+
+static inline zend_bool ps_fetch_is_packet_over_read_with_static_length(const unsigned int pack_len,
+ zend_uchar ** row, unsigned long length)
+{
+ if (pack_len > 0 && length > pack_len) {
+ ps_fetch_over_read_error(row);
+ return 1;
+ }
+ return 0;
+}
+
+
/* {{{ ps_fetch_from_1_to_8_bytes */
void
ps_fetch_from_1_to_8_bytes(zval * zv, const MYSQLND_FIELD * const field, unsigned int pack_len,
zend_uchar ** row, unsigned int byte_count TSRMLS_DC)
{
+ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_static_length(pack_len, row, byte_count))) {
+ return;
+ }
+
char tmp[22];
size_t tmp_len = 0;
zend_bool is_bit = field->type == MYSQL_TYPE_BIT;
+
DBG_ENTER("ps_fetch_from_1_to_8_bytes");
DBG_INF_FMT("zv=%p byte_count=%u", zv, byte_count);
if (field->flags & UNSIGNED_FLAG) {
@@ -178,6 +214,11 @@ ps_fetch_float(zval * zv, const MYSQLND_FIELD * const field, unsigned int pack_l
float fval;
double dval;
DBG_ENTER("ps_fetch_float");
+
+ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_static_length(pack_len, row, 4))) {
+ return;
+ }
+
float4get(fval, *row);
(*row)+= 4;
DBG_INF_FMT("value=%f", fval);
@@ -200,6 +241,11 @@ ps_fetch_double(zval * zv, const MYSQLND_FIELD * const field, unsigned int pack_
{
double value;
DBG_ENTER("ps_fetch_double");
+
+ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_static_length(pack_len, row, 8))) {
+ return;
+ }
+
float8get(value, *row);
ZVAL_DOUBLE(zv, value);
(*row)+= 8;
@@ -216,9 +262,14 @@ ps_fetch_time(zval * zv, const MYSQLND_FIELD * const field, unsigned int pack_le
struct st_mysqlnd_time t;
unsigned long length; /* First byte encodes the length*/
char * value;
+ const zend_uchar *p = *row;
DBG_ENTER("ps_fetch_time");
if ((length = php_mysqlnd_net_field_length(row))) {
+ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) {
+ return;
+ }
+
zend_uchar * to= *row;
t.time_type = MYSQLND_TIMESTAMP_TIME;
@@ -259,9 +310,14 @@ ps_fetch_date(zval * zv, const MYSQLND_FIELD * const field, unsigned int pack_le
struct st_mysqlnd_time t = {0};
unsigned long length; /* First byte encodes the length*/
char * value;
+ const zend_uchar *p = *row;
DBG_ENTER("ps_fetch_date");
if ((length = php_mysqlnd_net_field_length(row))) {
+ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) {
+ return;
+ }
+
zend_uchar *to= *row;
t.time_type= MYSQLND_TIMESTAMP_DATE;
@@ -296,9 +352,14 @@ ps_fetch_datetime(zval * zv, const MYSQLND_FIELD * const field, unsigned int pac
struct st_mysqlnd_time t;
unsigned long length; /* First byte encodes the length*/
char * value;
+ const zend_uchar *p = *row;
DBG_ENTER("ps_fetch_datetime");
if ((length = php_mysqlnd_net_field_length(row))) {
+ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) {
+ return;
+ }
+
zend_uchar * to = *row;
t.time_type = MYSQLND_TIMESTAMP_DATETIME;
@@ -341,7 +402,11 @@ ps_fetch_string(zval * zv, const MYSQLND_FIELD * const field, unsigned int pack_
For now just copy, before we make it possible
to write \0 to the row buffer
*/
+ const zend_uchar *p = *row;
const unsigned long length = php_mysqlnd_net_field_length(row);
+ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) {
+ return;
+ }
DBG_ENTER("ps_fetch_string");
DBG_INF_FMT("len = %lu", length);
DBG_INF("copying from the row buffer");
@@ -357,7 +422,11 @@ ps_fetch_string(zval * zv, const MYSQLND_FIELD * const field, unsigned int pack_
static void
ps_fetch_bit(zval * zv, const MYSQLND_FIELD * const field, unsigned int pack_len, zend_uchar ** row TSRMLS_DC)
{
+ const zend_uchar *p = *row;
unsigned long length = php_mysqlnd_net_field_length(row);
+ if (UNEXPECTED(ps_fetch_is_packet_over_read_with_variable_length(pack_len, row, p, length))) {
+ return;
+ }
ps_fetch_from_1_to_8_bytes(zv, field, pack_len, row, length TSRMLS_CC);
}
/* }}} */
diff --git a/ext/mysqlnd/mysqlnd_result.c b/ext/mysqlnd/mysqlnd_result.c
index 2076a004..1055925a 100644
--- a/ext/mysqlnd/mysqlnd_result.c
+++ b/ext/mysqlnd/mysqlnd_result.c
@@ -604,7 +604,7 @@ mysqlnd_query_read_result_set_header(MYSQLND_CONN_DATA * conn, MYSQLND_STMT * s
if (FAIL == (ret = result->m.read_result_metadata(result, conn TSRMLS_CC))) {
/* For PS, we leave them in Prepared state */
if (!stmt && conn->current_result) {
- mnd_efree(conn->current_result);
+ conn->current_result->m.free_result(conn->current_result, TRUE);
conn->current_result = NULL;
}
DBG_ERR("Error occurred while reading metadata");
diff --git a/ext/mysqlnd/mysqlnd_wireprotocol.c b/ext/mysqlnd/mysqlnd_wireprotocol.c
index 6e5c539d..692b274b 100644
--- a/ext/mysqlnd/mysqlnd_wireprotocol.c
+++ b/ext/mysqlnd/mysqlnd_wireprotocol.c
@@ -433,8 +433,31 @@ php_mysqlnd_greet_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC)
if (packet->server_capabilities & CLIENT_PLUGIN_AUTH) {
BAIL_IF_NO_MORE_DATA;
/* The server is 5.5.x and supports authentication plugins */
- packet->auth_protocol = estrdup((char *)p);
- p+= strlen(packet->auth_protocol) + 1; /* eat the '\0' */
+ size_t remaining_size = packet->header.size - (size_t)(p - buf);
+ if (remaining_size == 0) {
+ /* Might be better to fail but this will fail anyway */
+ packet->auth_protocol = estrdup("");
+ } else {
+ /* Check if NUL present */
+ char *null_terminator = memchr(p, '\0', remaining_size);
+ size_t auth_protocol_len;
+ if (null_terminator) {
+ /* If present, do basically estrdup */
+ auth_protocol_len = null_terminator - (char *)p;
+ } else {
+ /* If not present, copy the rest of the buffer */
+ auth_protocol_len = remaining_size;
+ }
+ char *auth_protocol = emalloc(auth_protocol_len + 1);
+ memcpy(auth_protocol, p, auth_protocol_len);
+ auth_protocol[auth_protocol_len] = '\0';
+ packet->auth_protocol = auth_protocol;
+
+ p += auth_protocol_len;
+ if (null_terminator) {
+ p++;
+ }
+ }
}
DBG_INF_FMT("proto=%u server=%s thread_id=%u",
@@ -708,7 +731,14 @@ php_mysqlnd_auth_response_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_D
/* There is a message */
if (packet->header.size > (size_t) (p - buf) && (i = php_mysqlnd_net_field_length(&p))) {
- packet->message_len = MIN(i, buf_len - (p - begin));
+ /* p can get past packet size when getting field length so it needs to be checked first
+ * and after that it can be checked that the i is not greater than the packet size */
+ if ((p - buf) > packet->header.size || packet->header.size - (p - buf) < i) {
+ DBG_ERR_FMT("OK packet message length is past the packet size");
+ php_error_docref(NULL, E_WARNING, "OK packet message length is past the packet size");
+ DBG_RETURN(FAIL);
+ }
+ packet->message_len = i;
packet->message = mnd_pestrndup((char *)p, packet->message_len, FALSE);
} else {
packet->message = NULL;
@@ -1117,6 +1147,17 @@ php_mysqlnd_rset_header_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC)
BAIL_IF_NO_MORE_DATA;
/* Check for additional textual data */
if (packet->header.size > (size_t) (p - buf) && (len = php_mysqlnd_net_field_length(&p))) {
+ /* p can get past packet size when getting field length so it needs to be checked first
+ * and after that it can be checked that the len is not greater than the packet size */
+ if ((p - buf) > packet->header.size || packet->header.size - (p - buf) < len) {
+ size_t local_file_name_over_read = ((p - buf) - packet->header.size) + len;
+ DBG_ERR_FMT("RSET_HEADER packet additional data length is past %zu bytes the packet size",
+ local_file_name_over_read);
+ php_error_docref(NULL, E_WARNING,
+ "RSET_HEADER packet additional data length is past %zu bytes the packet size",
+ local_file_name_over_read);
+ DBG_RETURN(FAIL);
+ }
packet->info_or_local_file = mnd_emalloc(len + 1);
if (packet->info_or_local_file) {
memcpy(packet->info_or_local_file, p, len);
@@ -1298,6 +1339,13 @@ php_mysqlnd_rset_field_read(void * _packet, MYSQLND_CONN_DATA * conn TSRMLS_DC)
{
BAIL_IF_NO_MORE_DATA;
DBG_INF_FMT("Def found, length %lu, persistent=%u", len, packet->persistent_alloc);
+ if (conn->net->cmd_buffer.length - (size_t) (p - buf) < len) {
+ size_t sz = (size_t) (p - buf) - conn->net->cmd_buffer.length + len;
+ DBG_ERR_FMT("RSET_FIELD packet additional data length is past %zu bytes the packet size", sz);
+ php_error_docref(NULL, E_WARNING,
+ "RSET_FIELD packet additional data length is past %zu bytes the packet size", sz);
+ DBG_RETURN(FAIL);
+ }
meta->def = mnd_pemalloc(len + 1, packet->persistent_alloc);
if (!meta->def) {
SET_OOM_ERROR(*conn->error_info);
@@ -1482,8 +1530,10 @@ php_mysqlnd_rowp_read_binary_protocol(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zv
unsigned int field_count, const MYSQLND_FIELD * fields_metadata,
zend_bool as_int_or_float, MYSQLND_STATS * stats TSRMLS_DC)
{
- unsigned int i;
- zend_uchar * p = row_buffer->ptr;
+ unsigned int i, j;
+ size_t rbs = row_buffer->app;
+ zend_uchar * rbp = row_buffer->ptr;
+ zend_uchar * p = rbp;
zend_uchar * null_ptr, bit;
zval **current_field, **end_field, **start_field;
@@ -1523,7 +1573,23 @@ php_mysqlnd_rowp_read_binary_protocol(MYSQLND_MEMORY_POOL_CHUNK * row_buffer, zv
statistic = STAT_BINARY_TYPE_FETCHED_NULL;
} else {
enum_mysqlnd_field_types type = fields_metadata[i].type;
- mysqlnd_ps_fetch_functions[type].func(*current_field, &fields_metadata[i], 0, &p TSRMLS_CC);
+ size_t row_position = p - rbp;
+ if (rbs <= row_position) {
+ for (j = 0, current_field = start_field; current_field < end_field; current_field++, j++) {
+ ZVAL_NULL(*current_field);
+ zval_dtor(*current_field);
+ }
+ php_error_docref(NULL, E_WARNING, "Malformed server packet. No packet space left for the field");
+ DBG_RETURN(FAIL);
+ }
+ mysqlnd_ps_fetch_functions[type].func(*current_field, &fields_metadata[i], rbs - row_position, &p TSRMLS_CC);
+ if (p == NULL) {
+ for (j = 0, current_field = start_field; current_field < end_field; current_field++, j++) {
+ ZVAL_NULL(*current_field);
+ zval_dtor(*current_field);
+ }
+ DBG_RETURN(FAIL);
+ }
if (MYSQLND_G(collect_statistics)) {
switch (fields_metadata[i].type) {
@@ -1610,9 +1676,8 @@ php_mysqlnd_rowp_read_text_protocol_aux(MYSQLND_MEMORY_POOL_CHUNK * row_buffer,
/* php_mysqlnd_net_field_length() call should be after *this_field_len_pos = p; */
const unsigned long len = php_mysqlnd_net_field_length(&p);
- if (len != MYSQLND_NULL_LENGTH && ((p + len) > packet_end)) {
- php_error_docref(NULL TSRMLS_CC, E_WARNING, "Malformed server packet. Field length pointing "MYSQLND_SZ_T_SPEC
- " bytes after end of packet", (p + len) - packet_end - 1);
+ if (len != MYSQLND_NULL_LENGTH && (p > packet_end || len > packet_end - p)) {
+ php_error_docref(NULL, E_WARNING, "Malformed server packet. Field length pointing after end of packet");
DBG_RETURN(FAIL);
}
if (copy_data == FALSE && current_field > start_field && last_field_was_string) {
diff --git a/ext/openssl/tests/ServerClientTestCase-8.1.inc b/ext/openssl/tests/ServerClientTestCase-8.1.inc
new file mode 100644
index 00000000..375f8086
--- /dev/null
+++ b/ext/openssl/tests/ServerClientTestCase-8.1.inc
@@ -0,0 +1,199 @@
+notify($worker, $message);
+}
+
+function phpt_wait($worker = WORKER_DEFAULT_NAME, $timeout = null)
+{
+ return ServerClientTestCase::getInstance()->wait($worker, $timeout);
+}
+
+function phpt_notify_server_start($server)
+{
+ ServerClientTestCase::getInstance()->notify_server_start($server);
+}
+
+function phpt_has_sslv3() {
+ static $result = null;
+ if (!is_null($result)) {
+ return $result;
+ }
+ $server = @stream_socket_server('sslv3://127.0.0.1:10013');
+ if ($result = !!$server) {
+ fclose($server);
+ }
+ return $result;
+}
+
+/**
+ * This is a singleton to let the wait/notify functions work
+ * I know it's horrible, but it's a means to an end
+ */
+class ServerClientTestCase
+{
+ private $isWorker = false;
+
+ private $workerHandle = [];
+
+ private $workerStdIn = [];
+
+ private $workerStdOut = [];
+
+ private static $instance;
+
+ public static function getInstance($isWorker = false)
+ {
+ if (!isset(self::$instance)) {
+ self::$instance = new self($isWorker);
+ }
+
+ return self::$instance;
+ }
+
+ public function __construct($isWorker = false)
+ {
+ if (!isset(self::$instance)) {
+ self::$instance = $this;
+ }
+
+ $this->isWorker = $isWorker;
+ }
+
+ private function spawnWorkerProcess($worker, $code)
+ {
+ if (defined("PHP_WINDOWS_VERSION_MAJOR")) {
+ $ini = php_ini_loaded_file();
+ $cmd = sprintf(
+ '%s %s "%s" %s',
+ PHP_BINARY, $ini ? "-n -c $ini" : "",
+ __FILE__,
+ WORKER_ARGV_VALUE
+ );
+ } else {
+ $cmd = sprintf(
+ '%s "%s" %s %s',
+ PHP_BINARY,
+ __FILE__,
+ WORKER_ARGV_VALUE,
+ $worker
+ );
+ }
+ $this->workerHandle[$worker] = proc_open(
+ $cmd,
+ [['pipe', 'r'], ['pipe', 'w'], STDERR],
+ $pipes
+ );
+ $this->workerStdIn[$worker] = $pipes[0];
+ $this->workerStdOut[$worker] = $pipes[1];
+
+ fwrite($this->workerStdIn[$worker], $code . "\n---\n");
+ }
+
+ private function cleanupWorkerProcess($worker)
+ {
+ fclose($this->workerStdIn[$worker]);
+ fclose($this->workerStdOut[$worker]);
+ proc_close($this->workerHandle[$worker]);
+ }
+
+ private function stripPhpTagsFromCode($code)
+ {
+ return preg_replace('/^\s*<\?(?:php)?|\?>\s*$/i', '', $code);
+ }
+
+ public function runWorker()
+ {
+ $code = '';
+
+ while (1) {
+ $line = fgets(STDIN);
+
+ if (trim($line) === "---") {
+ break;
+ }
+
+ $code .= $line;
+ }
+
+ eval($code);
+ }
+
+ /**
+ * Run client and all workers
+ *
+ * @param string $clientCode The client PHP code
+ * @param string|array $workerCode
+ * @param bool $ephemeral Select whether automatic port selection and automatic awaiting is used
+ * @return void
+ * @throws Exception
+ */
+ public function run($clientCode, $workerCode, $ephemeral = true)
+ {
+ if (!is_array($workerCode)) {
+ $workerCode = [WORKER_DEFAULT_NAME => $workerCode];
+ }
+ reset($workerCode);
+ $code = current($workerCode);
+ $worker = key($workerCode);
+ while ($worker != null) {
+ $this->spawnWorkerProcess($worker, $this->stripPhpTagsFromCode($code));
+ $code = next($workerCode);
+ if ($ephemeral) {
+ $addr = trim($this->wait($worker));
+ if (empty($addr)) {
+ throw new \Exception("Failed server start");
+ }
+ if ($code === false) {
+ $clientCode = preg_replace('/{{\s*ADDR\s*}}/', $addr, $clientCode);
+ } else {
+ $code = preg_replace('/{{\s*ADDR\s*}}/', $addr, $code);
+ }
+ }
+ $worker = key($workerCode);
+ }
+
+ eval($this->stripPhpTagsFromCode($clientCode));
+ foreach ($workerCode as $worker => $code) {
+ $this->cleanupWorkerProcess($worker);
+ }
+ }
+
+ public function wait($worker, $timeout = null)
+ {
+ $handle = $this->isWorker ? STDIN : $this->workerStdOut[$worker];
+ if ($timeout === null) {
+ return fgets($handle);
+ }
+
+ stream_set_blocking($handle, false);
+ $read = [$handle];
+ $result = stream_select($read, $write, $except, $timeout);
+ if (!$result) {
+ return null;
+ }
+
+ $result = fgets($handle);
+ stream_set_blocking($handle, true);
+ return $result;
+ }
+
+ public function notify($worker, $message = "")
+ {
+ fwrite($this->isWorker ? STDOUT : $this->workerStdIn[$worker], "$message\n");
+ }
+
+ public function notify_server_start($server)
+ {
+ echo stream_socket_get_name($server, false) . "\n";
+ }
+}
+
+if (isset($argv[1]) && $argv[1] === WORKER_ARGV_VALUE) {
+ ServerClientTestCase::getInstance(true)->runWorker();
+}
diff --git a/ext/openssl/tests/san_peer_matching.phpt b/ext/openssl/tests/san_peer_matching.phpt
index 0e1f30cb..d0404438 100644
--- a/ext/openssl/tests/san_peer_matching.phpt
+++ b/ext/openssl/tests/san_peer_matching.phpt
@@ -42,7 +42,7 @@ ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
--EXPECTF--
resource(%d) of type (stream)
-Warning: stream_socket_client(): Unable to locate peer certificate CN in %s on line %d
+Warning: stream_socket_client(): Peer certificate subjectAltName did not match expected name `moar.example.org' in %s on line %d
Warning: stream_socket_client(): Failed to enable crypto in %s on line %d
diff --git a/ext/openssl/xp_ssl.c b/ext/openssl/xp_ssl.c
index 7a880cd7..98081e46 100644
--- a/ext/openssl/xp_ssl.c
+++ b/ext/openssl/xp_ssl.c
@@ -358,7 +358,7 @@ static zend_bool matches_wildcard_name(const char *subjectname, const char *cert
suffix_len = strlen(wildcard + 1);
subject_len = strlen(subjectname);
- if (suffix_len <= subject_len) {
+ if (suffix_len + prefix_len <= subject_len) {
/* 2) suffix must match
* 3) no . between prefix and suffix
**/
@@ -370,7 +370,8 @@ static zend_bool matches_wildcard_name(const char *subjectname, const char *cert
}
/* }}} */
-static zend_bool matches_san_list(X509 *peer, const char *subject_name) /* {{{ */
+static zend_bool matches_san_list(
+ X509 *peer, const char *subject_name, zend_bool *has_service_id) /* {{{ */
{
int i, len;
unsigned char *cert_name = NULL;
@@ -379,10 +380,14 @@ static zend_bool matches_san_list(X509 *peer, const char *subject_name) /* {{{ *
GENERAL_NAMES *alt_names = X509_get_ext_d2i(peer, NID_subject_alt_name, 0, 0);
int alt_name_count = sk_GENERAL_NAME_num(alt_names);
+ *has_service_id = 0;
+
for (i = 0; i < alt_name_count; i++) {
GENERAL_NAME *san = sk_GENERAL_NAME_value(alt_names, i);
if (san->type == GEN_DNS) {
+ *has_service_id = 1;
+
ASN1_STRING_to_UTF8(&cert_name, san->d.dNSName);
if (ASN1_STRING_length(san->d.dNSName) != strlen((const char*)cert_name)) {
OPENSSL_free(cert_name);
@@ -417,6 +422,16 @@ static zend_bool matches_san_list(X509 *peer, const char *subject_name) /* {{{ *
* Because IP SAN names are officially deprecated and are
* not allowed by CAs starting in 2015. Deal with it.
*/
+ } else if (san->type == GEN_URI) {
+ *has_service_id = 1;
+ } else if (san->type == GEN_OTHERNAME) {
+ char oid[32];
+
+ /* SRV-ID, matched by OID because NID_SRVName needs OpenSSL 3.0 */
+ if (OBJ_obj2txt(oid, sizeof(oid), san->d.otherName->type_id, 1) > 0
+ && strcmp(oid, "1.3.6.1.5.5.7.8.7") == 0) {
+ *has_service_id = 1;
+ }
}
}
@@ -532,8 +547,16 @@ static int apply_peer_verification_policy(SSL *ssl, X509 *peer, php_stream *stre
}
if (peer_name) {
- if (matches_san_list(peer, peer_name)) {
+ zend_bool has_service_id = 0;
+
+ if (matches_san_list(peer, peer_name, &has_service_id)) {
return SUCCESS;
+ } else if (has_service_id) {
+ /* CN must be ignored if the certificate presents a service identity. */
+ php_error_docref(NULL TSRMLS_CC, E_WARNING,
+ "Peer certificate subjectAltName did not match expected name `%s'",
+ peer_name);
+ return FAILURE;
} else if (matches_common_name(peer, peer_name TSRMLS_CC)) {
return SUCCESS;
} else {
diff --git a/ext/pdo_dblib/dblib_driver.c b/ext/pdo_dblib/dblib_driver.c
index b5744a42..55909f9d 100644
--- a/ext/pdo_dblib/dblib_driver.c
+++ b/ext/pdo_dblib/dblib_driver.c
@@ -147,6 +147,9 @@ static int dblib_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquote
char *q;
int l = 1;
+ if (unquotedlen > (INT_MAX - 3) / 2) {
+ return 0;
+ }
*quoted = q = safe_emalloc(2, unquotedlen, 3);
*q++ = '\'';
diff --git a/ext/pdo_dblib/tests/GHSA-5hqh-c84r-qjcv.phpt b/ext/pdo_dblib/tests/GHSA-5hqh-c84r-qjcv.phpt
new file mode 100644
index 00000000..431c6195
--- /dev/null
+++ b/ext/pdo_dblib/tests/GHSA-5hqh-c84r-qjcv.phpt
@@ -0,0 +1,24 @@
+--TEST--
+GHSA-5hqh-c84r-qjcv (Integer overflow in the dblib quoter causing OOB writes)
+--EXTENSIONS--
+pdo_dblib
+--SKIPIF--
+
+--INI--
+memory_limit=-1
+--FILE--
+quote(str_repeat("'", 2147483646)));
+
+?>
+--EXPECT--
+bool(false)
diff --git a/ext/pdo_firebird/firebird_driver.c b/ext/pdo_firebird/firebird_driver.c
index 589312ac..fc0cbe36 100644
--- a/ext/pdo_firebird/firebird_driver.c
+++ b/ext/pdo_firebird/firebird_driver.c
@@ -292,7 +292,7 @@ free_statement:
static int firebird_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, /* {{{ */
char **quoted, int *quotedlen, enum pdo_param_type paramtype TSRMLS_DC)
{
- int qcount = 0;
+ size_t qcount = 0;
char const *co, *l, *r;
char *c;
@@ -306,7 +306,11 @@ static int firebird_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unqu
/* Firebird only requires single quotes to be doubled if string lengths are used */
/* count the number of ' characters */
for (co = unquoted; (co = strchr(co,'\'')); qcount++, co++);
-
+
+ if (UNEXPECTED(unquotedlen + 2 > INT_MAX - qcount)) {
+ return 0;
+ }
+
*quotedlen = unquotedlen + qcount + 2;
*quoted = c = emalloc(*quotedlen+1);
*c++ = '\'';
diff --git a/ext/pdo_firebird/tests/payload_server.inc b/ext/pdo_firebird/tests/payload_server.inc
new file mode 100644
index 00000000..92cfd7ac
--- /dev/null
+++ b/ext/pdo_firebird/tests/payload_server.inc
@@ -0,0 +1,88 @@
+ STDIN,
+ 1 => STDOUT,
+ 2 => ['pipe', 'w'],
+ );
+ $proc = proc_open($cmd, $descriptorspec, $pipes);
+ if (!is_resource($proc)) die("Failed to run: $cmd");
+
+ // First, wait for the payload server to declare itself ready.
+ $bound = null;
+ stream_set_blocking($pipes[2], false);
+ for ($i = 0; $i < 60; $i++) {
+ usleep(50000); // 50ms per try
+ $status = proc_get_status($proc);
+ if (empty($status['running'])) {
+ echo "Server is not running\n";
+ proc_terminate($proc);
+ exit(1);
+ }
+ while (($line = fgets($pipes[2])) !== false) {
+ if (preg_match('/FB payload server listening on (.+)/', $line, $matches)) {
+ $bound = $matches[1];
+ $bound = preg_replace('/^::1/', '[::1]', $bound);
+ // Now that we've identified the listen address, close STDERR.
+ // Otherwise the pipe may clog up with unread log messages.
+ fclose($pipes[2]);
+ break 2;
+ }
+ }
+ }
+
+ if ($bound === null) {
+ echo "Server did not output startup message";
+ proc_terminate($proc);
+ exit(1);
+ }
+
+ // Now wait for a connection to succeed.
+ // note: even when server prints 'FB payload server listening on localhost:12345'
+ // it might not be listening yet...need to wait until fsockopen() call returns
+ $error = "Unable to connect to server\n";
+ for ($i=0; $i < 60; $i++) {
+ usleep(50000); // 50ms per try
+ $status = proc_get_status($proc);
+ $fp = fsockopen("tcp://$bound");
+ // Failure, the server is no longer running
+ if (!($status && $status['running'])) {
+ $error = "Server is not running\n";
+ break;
+ }
+ // Success, Connected to servers
+ if ($fp) {
+ $error = '';
+ break;
+ }
+ }
+
+ if ($fp) {
+ fclose($fp);
+ }
+
+ if ($error) {
+ echo $error;
+ proc_terminate($proc);
+ exit(1);
+ }
+
+ register_shutdown_function(
+ function($proc) {
+ proc_terminate($proc);
+ /* Wait for server to shutdown */
+ for ($i = 0; $i < 60; $i++) {
+ $status = proc_get_status($proc);
+ if (!($status && $status['running'])) {
+ break;
+ }
+ usleep(50000);
+ }
+ },
+ $proc
+ );
+
+ return $bound;
+}
diff --git a/ext/pdo_firebird/tests/payload_server.php b/ext/pdo_firebird/tests/payload_server.php
new file mode 100644
index 00000000..168929f6
--- /dev/null
+++ b/ext/pdo_firebird/tests/payload_server.php
@@ -0,0 +1,20 @@
+
+--FILE--
+ PDO::ERRMODE_EXCEPTION]);
+?>
+--EXPECT--
diff --git a/ext/pdo_pgsql/pgsql_driver.c b/ext/pdo_pgsql/pgsql_driver.c
index af4e6d7e..fc9f8442 100644
--- a/ext/pdo_pgsql/pgsql_driver.c
+++ b/ext/pdo_pgsql/pgsql_driver.c
@@ -332,11 +332,15 @@ static int pgsql_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquote
unsigned char *escaped;
pdo_pgsql_db_handle *H = (pdo_pgsql_db_handle *)dbh->driver_data;
size_t tmp_len;
+ int err = 0;
switch (paramtype) {
case PDO_PARAM_LOB:
/* escapedlen returned by PQescapeBytea() accounts for trailing 0 */
escaped = PQescapeByteaConn(H->server, (unsigned char *)unquoted, (size_t)unquotedlen, &tmp_len);
+ if (escaped == NULL) {
+ return 0;
+ }
*quotedlen = (int)tmp_len + 1;
*quoted = emalloc(*quotedlen + 1);
memcpy((*quoted)+1, escaped, *quotedlen-2);
@@ -348,7 +352,11 @@ static int pgsql_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquote
default:
*quoted = safe_emalloc(2, unquotedlen, 3);
(*quoted)[0] = '\'';
- *quotedlen = PQescapeStringConn(H->server, *quoted + 1, unquoted, (size_t)unquotedlen, NULL);
+ *quotedlen = PQescapeStringConn(H->server, *quoted + 1, unquoted, (size_t)unquotedlen, &err);
+ if (err) {
+ efree(*quoted);
+ return 0;
+ }
(*quoted)[*quotedlen + 1] = '\'';
(*quoted)[*quotedlen + 2] = '\0';
*quotedlen += 2;
diff --git a/ext/pdo_pgsql/tests/ghsa-hrwm-9436-5mv3.phpt b/ext/pdo_pgsql/tests/ghsa-hrwm-9436-5mv3.phpt
new file mode 100644
index 00000000..60e13613
--- /dev/null
+++ b/ext/pdo_pgsql/tests/ghsa-hrwm-9436-5mv3.phpt
@@ -0,0 +1,22 @@
+--TEST--
+#GHSA-hrwm-9436-5mv3: pdo_pgsql extension does not check for errors during escaping
+--SKIPIF--
+
+--FILE--
+setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+
+$invalid = "ABC\xff\x30';";
+var_dump($db->quote($invalid));
+
+?>
+--EXPECT--
+bool(false)
diff --git a/ext/pgsql/pgsql.c b/ext/pgsql/pgsql.c
index d37bde7d..ed6bda62 100644
--- a/ext/pgsql/pgsql.c
+++ b/ext/pgsql/pgsql.c
@@ -4329,8 +4329,15 @@ PHP_FUNCTION(pg_escape_string)
to = (char *) safe_emalloc_string(from_len, 2, 1);
#ifdef HAVE_PQESCAPE_CONN
if (pgsql_link != NULL || id != -1) {
+ int err = 0;
+
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
- to_len = (int) PQescapeStringConn(pgsql, to, from, (size_t)from_len, NULL);
+ to_len = (int) PQescapeStringConn(pgsql, to, from, (size_t)from_len, &err);
+ if (err) {
+ zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Escaping string failed", 0 TSRMLS_CC);
+ efree(to);
+ return;
+ }
} else
#endif
to_len = (int) PQescapeString(to, from, (size_t)from_len);
@@ -4374,6 +4381,10 @@ PHP_FUNCTION(pg_escape_bytea)
} else
#endif
to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len);
+ if (to == NULL) {
+ zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Escape failure", 0 TSRMLS_CC);
+ return;
+ }
RETVAL_STRINGL_CHECK(to, to_len-1, 1); /* to_len includes additional '\0' */
PQfreemem(to);
@@ -5470,7 +5481,7 @@ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, z
char *escaped;
smart_str querystr = {0};
size_t new_len;
- int i, num_rows;
+ int i, num_rows, err = 0;
zval *elem;
if (!*table_name) {
@@ -5511,7 +5522,14 @@ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, z
"WHERE a.attnum > 0 AND c.relname = '");
}
escaped = (char *)safe_emalloc(strlen(tmp_name2), 2, 1);
- new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), NULL);
+ new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), &err);
+ if (err) {
+ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Escaping table name '%s' failed", table_name);
+ efree(src);
+ efree(escaped);
+ smart_str_free(&querystr);
+ return FAILURE;
+ }
if (new_len) {
smart_str_appendl(&querystr, escaped, new_len);
}
@@ -5519,7 +5537,14 @@ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, z
smart_str_appends(&querystr, "' AND n.nspname = '");
escaped = (char *)safe_emalloc(strlen(tmp_name), 2, 1);
- new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), NULL);
+ new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), &err);
+ if (err) {
+ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Escaping table namespace '%s' failed", table_name);
+ efree(src);
+ efree(escaped);
+ smart_str_free(&querystr);
+ return FAILURE;
+ }
if (new_len) {
smart_str_appendl(&querystr, escaped, new_len);
}
@@ -5750,7 +5775,6 @@ static int php_pgsql_add_quotes(zval *src, zend_bool should_free TSRMLS_DC)
assert(Z_TYPE_P(src) == IS_STRING);
assert(should_free == 1 || should_free == 0);
- smart_str_appendc(&str, 'E');
smart_str_appendc(&str, '\'');
smart_str_appendl(&str, Z_STRVAL_P(src), Z_STRLEN_P(src));
smart_str_appendc(&str, '\'');
@@ -5791,7 +5815,7 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con
uint field_len = -1;
ulong num_idx = -1;
zval *meta, **def, **type, **not_null, **has_default, **is_enum, **val, *new_val;
- int key_type, err = 0, skip_field;
+ int key_type, err = 0, escape_err = 0, skip_field;
php_pgsql_data_type data_type;
assert(pg_link != NULL);
@@ -6037,13 +6061,19 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con
}
else {
char *tmp;
+ size_t tmp_len;
/* PostgreSQL ignores \0 */
- Z_TYPE_P(new_val) = IS_STRING;
tmp = (char *)safe_emalloc(Z_STRLEN_PP(val), 2, 1);
- /* better to use PGSQLescapeLiteral since PGescapeStringConn does not handle special \ */
- Z_STRLEN_P(new_val) = (int)PQescapeStringConn(pg_link, tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val), NULL);
- Z_STRVAL_P(new_val) = tmp;
- php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
+ tmp_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val), &escape_err);
+ if (escape_err) {
+ efree(tmp);
+ err = 1;
+ } else {
+ Z_TYPE_P(new_val) = IS_STRING;
+ Z_STRLEN_P(new_val) = (int)tmp_len;
+ Z_STRVAL_P(new_val) = tmp;
+ php_pgsql_add_quotes(new_val, 1 TSRMLS_CC);
+ }
}
break;
@@ -6066,7 +6096,15 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con
}
PGSQL_CONV_CHECK_IGNORE();
if (err) {
- php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_PP(type), field);
+ if (escape_err) {
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE,
+ "String value escaping failed for PostgreSQL '%s' (%s)",
+ Z_STRVAL_PP(type), field);
+ } else {
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE,
+ "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)",
+ Z_STRVAL_PP(type), field);
+ }
}
break;
@@ -6333,6 +6371,11 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con
#else
tmp = PQescapeBytea(Z_STRVAL_PP(val), (unsigned char *)Z_STRLEN_PP(val), &to_len);
#endif
+ if (tmp == NULL) {
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Escaping value failed for %s field (%s)", Z_STRVAL_PP(type), field);
+ err = 1;
+ break;
+ }
Z_TYPE_P(new_val) = IS_STRING;
Z_STRLEN_P(new_val) = to_len-1; /* PQescapeBytea's to_len includes additional '\0' */
Z_STRVAL_P(new_val) = emalloc(to_len);
@@ -6422,6 +6465,14 @@ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, con
add_assoc_zval(result, field, new_val);
} else {
escaped = PGSQLescapeIdentifier(pg_link, field, field_len);
+ if (escaped == NULL) {
+ /* This cannot fail because of invalid string but only due to failed memory allocation */
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Escaping field '%s' failed", field);
+ zval_dtor(new_val);
+ FREE_ZVAL(new_val);
+ err = 1;
+ break;
+ }
add_assoc_zval(result, escaped, new_val);
PGSQLfree(escaped);
}
@@ -6499,7 +6550,7 @@ static int do_exec(smart_str *querystr, int expect, PGconn *pg_link, ulong opt T
return -1;
}
-static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table)
+static inline int build_tablename(smart_str *querystr, PGconn *pg_link, const char *table TSRMLS_DC)
{
char *table_copy, *escaped, *tmp;
const char *token;
@@ -6516,6 +6567,11 @@ static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const c
smart_str_appendl(querystr, token, len);
} else {
escaped = PGSQLescapeIdentifier(pg_link, token, len);
+ if (escaped == NULL) {
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to escape table name '%s'", table);
+ efree(table_copy);
+ return FAILURE;
+ }
smart_str_appends(querystr, escaped);
PGSQLfree(escaped);
}
@@ -6527,12 +6583,19 @@ static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const c
smart_str_appendl(querystr, tmp, len);
} else {
escaped = PGSQLescapeIdentifier(pg_link, tmp, len);
+ if (escaped == NULL) {
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to escape table name '%s'", table);
+ efree(table_copy);
+ return FAILURE;
+ }
smart_str_appendc(querystr, '.');
smart_str_appends(querystr, escaped);
PGSQLfree(escaped);
}
}
efree(table_copy);
+
+ return SUCCESS;
}
/* {{{ php_pgsql_insert
@@ -6554,7 +6617,9 @@ PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var
if (zend_hash_num_elements(Z_ARRVAL_P(var_array)) == 0) {
smart_str_appends(&querystr, "INSERT INTO ");
- build_tablename(&querystr, pg_link, table);
+ if (build_tablename(&querystr, pg_link, table TSRMLS_CC) == FAILURE) {
+ goto cleanup;
+ }
smart_str_appends(&querystr, " DEFAULT VALUES");
goto no_values;
@@ -6571,7 +6636,9 @@ PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var
}
smart_str_appends(&querystr, "INSERT INTO ");
- build_tablename(&querystr, pg_link, table);
+ if (build_tablename(&querystr, pg_link, table TSRMLS_CC) == FAILURE) {
+ goto cleanup;
+ }
smart_str_appends(&querystr, " (");
zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(var_array), &pos);
@@ -6583,6 +6650,10 @@ PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var
}
if (opt & PGSQL_DML_ESCAPE) {
tmp = PGSQLescapeIdentifier(pg_link, fld, fld_len);
+ if (tmp == NULL) {
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to escape field '%s'", fld);
+ goto cleanup;
+ }
smart_str_appends(&querystr, tmp);
PGSQLfree(tmp);
} else {
@@ -6605,8 +6676,15 @@ PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var
if (opt & PGSQL_DML_ESCAPE) {
size_t new_len;
char *tmp;
+ int error = 0;
tmp = (char *)safe_emalloc(Z_STRLEN_PP(val), 2, 1);
- new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val), NULL);
+ new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val), &error);
+ if (error) {
+ zend_hash_get_current_key_ex(Z_ARRVAL_P(var_array), &fld, &fld_len, &num_idx, 0, &pos);
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to escape field '%s' value", fld);
+ efree(tmp);
+ goto cleanup;
+ }
smart_str_appendc(&querystr, '\'');
smart_str_appendl(&querystr, tmp, new_len);
smart_str_appendc(&querystr, '\'');
@@ -6765,6 +6843,10 @@ static inline int build_assignment_string(PGconn *pg_link, smart_str *querystr,
}
if (opt & PGSQL_DML_ESCAPE) {
tmp = PGSQLescapeIdentifier(pg_link, fld, fld_len);
+ if (tmp == NULL) {
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to escape field '%s'", fld);
+ return -1;
+ }
smart_str_appends(querystr, tmp);
PGSQLfree(tmp);
} else {
@@ -6779,9 +6861,15 @@ static inline int build_assignment_string(PGconn *pg_link, smart_str *querystr,
switch(Z_TYPE_PP(val)) {
case IS_STRING:
if (opt & PGSQL_DML_ESCAPE) {
+ int error = 0;
size_t new_len;
tmp = (char *)safe_emalloc(Z_STRLEN_PP(val), 2, 1);
- new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val), NULL);
+ new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_PP(val), Z_STRLEN_PP(val), &error);
+ if (error) {
+ php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Failed to escape field '%s' value", fld);
+ efree(tmp);
+ return -1;
+ }
smart_str_appendc(querystr, '\'');
smart_str_appendl(querystr, tmp, new_len);
smart_str_appendc(querystr, '\'');
@@ -6845,7 +6933,9 @@ PHP_PGSQL_API int php_pgsql_update(PGconn *pg_link, const char *table, zval *var
}
smart_str_appends(&querystr, "UPDATE ");
- build_tablename(&querystr, pg_link, table);
+ if (build_tablename(&querystr, pg_link, table TSRMLS_CC) == FAILURE) {
+ goto cleanup;
+ }
smart_str_appends(&querystr, " SET ");
if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(var_array), 0, ",", 1, opt TSRMLS_CC))
@@ -6946,7 +7036,9 @@ PHP_PGSQL_API int php_pgsql_delete(PGconn *pg_link, const char *table, zval *ids
}
smart_str_appends(&querystr, "DELETE FROM ");
- build_tablename(&querystr, pg_link, table);
+ if (build_tablename(&querystr, pg_link, table TSRMLS_CC) == FAILURE) {
+ goto cleanup;
+ }
smart_str_appends(&querystr, " WHERE ");
if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt TSRMLS_CC))
@@ -7082,7 +7174,9 @@ PHP_PGSQL_API int php_pgsql_select(PGconn *pg_link, const char *table, zval *ids
}
smart_str_appends(&querystr, "SELECT * FROM ");
- build_tablename(&querystr, pg_link, table);
+ if (build_tablename(&querystr, pg_link, table TSRMLS_CC) == FAILURE) {
+ goto cleanup;
+ }
smart_str_appends(&querystr, " WHERE ");
if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt TSRMLS_CC))
diff --git a/ext/pgsql/tests/10pg_convert.phpt b/ext/pgsql/tests/10pg_convert.phpt
index adc2756e..2752f3d9 100644
--- a/ext/pgsql/tests/10pg_convert.phpt
+++ b/ext/pgsql/tests/10pg_convert.phpt
@@ -23,7 +23,7 @@ array(3) {
[""num""]=>
string(4) "1234"
[""str""]=>
- string(6) "E'AAA'"
+ string(5) "'AAA'"
[""bin""]=>
- string(6) "E'BBB'"
+ string(5) "'BBB'"
}
\ No newline at end of file
diff --git a/ext/pgsql/tests/10pg_convert_9.phpt b/ext/pgsql/tests/10pg_convert_9.phpt
index 827c9625..e52697be 100644
--- a/ext/pgsql/tests/10pg_convert_9.phpt
+++ b/ext/pgsql/tests/10pg_convert_9.phpt
@@ -18,13 +18,19 @@ $fields = array('num'=>'1234', 'str'=>'AAA', 'bin'=>'BBB');
$converted = pg_convert($db, $table_name, $fields);
var_dump($converted);
+
+var_dump(pg_convert($db, $table_name, ['str' => "\\' OR 1=1"]));
?>
--EXPECT--
array(3) {
[""num""]=>
string(4) "1234"
[""str""]=>
- string(6) "E'AAA'"
+ string(5) "'AAA'"
[""bin""]=>
- string(12) "E'\\x424242'"
+ string(11) "'\\x424242'"
+}
+array(1) {
+ [""str""]=>
+ string(13) "'\\'' OR 1=1'"
}
\ No newline at end of file
diff --git a/ext/pgsql/tests/10pg_convert_json_array.phpt b/ext/pgsql/tests/10pg_convert_json_array.phpt
index 960cfd6c..711d0dff 100644
--- a/ext/pgsql/tests/10pg_convert_json_array.phpt
+++ b/ext/pgsql/tests/10pg_convert_json_array.phpt
@@ -30,8 +30,8 @@ if (!pg_insert($db, $table_name_92, $fields)) {
--EXPECT--
array(2) {
[""textary""]=>
- string(51) "E'{"meeting", "lunch", "training", "presentation"}'"
+ string(50) "'{"meeting", "lunch", "training", "presentation"}'"
[""jsn""]=>
- string(22) "E'{"f1":1,"f2":"foo"}'"
+ string(21) "'{"f1":1,"f2":"foo"}'"
}
OK
diff --git a/ext/pgsql/tests/12pg_insert.phpt b/ext/pgsql/tests/12pg_insert.phpt
index 9fd0dd1e..4a502e78 100644
--- a/ext/pgsql/tests/12pg_insert.phpt
+++ b/ext/pgsql/tests/12pg_insert.phpt
@@ -20,5 +20,5 @@ echo pg_insert($db, $table_name, $fields, PGSQL_DML_STRING)."\n";
echo "Ok\n";
?>
--EXPECT--
-INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES (1234,E'AAA',E'BBB');
+INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES (1234,'AAA','BBB');
Ok
\ No newline at end of file
diff --git a/ext/pgsql/tests/12pg_insert_9.phpt b/ext/pgsql/tests/12pg_insert_9.phpt
index b84e25b8..826f1efb 100644
--- a/ext/pgsql/tests/12pg_insert_9.phpt
+++ b/ext/pgsql/tests/12pg_insert_9.phpt
@@ -24,7 +24,7 @@ var_dump( pg_insert($db, $table_name, $fields, PGSQL_DML_EXEC) ); // Return reso
echo "Ok\n";
?>
--EXPECTF--
-INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES (1234,E'AAA',E'\\x424242');
+INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES (1234,'AAA','\\x424242');
INSERT INTO "php_pgsql_test" ("num","str","bin") VALUES ('1234','AAA','BBB');
resource(%d) of type (pgsql result)
Ok
\ No newline at end of file
diff --git a/ext/pgsql/tests/14pg_update.phpt b/ext/pgsql/tests/14pg_update.phpt
index d8045744..d9fdb49e 100644
--- a/ext/pgsql/tests/14pg_update.phpt
+++ b/ext/pgsql/tests/14pg_update.phpt
@@ -22,5 +22,5 @@ echo pg_update($db, $table_name, $fields, $ids, PGSQL_DML_STRING|PGSQL_DML_ESCAP
echo "Ok\n";
?>
--EXPECT--
-UPDATE "php_pgsql_test" SET "num"=1234,"str"=E'ABC',"bin"=E'XYZ' WHERE "num"=1234;
+UPDATE "php_pgsql_test" SET "num"=1234,"str"='ABC',"bin"='XYZ' WHERE "num"=1234;
Ok
\ No newline at end of file
diff --git a/ext/pgsql/tests/14pg_update_9.phpt b/ext/pgsql/tests/14pg_update_9.phpt
index 9f1b516b..da6e4cc8 100644
--- a/ext/pgsql/tests/14pg_update_9.phpt
+++ b/ext/pgsql/tests/14pg_update_9.phpt
@@ -24,6 +24,6 @@ echo pg_update($db, $table_name, $fields, $ids, PGSQL_DML_STRING|PGSQL_DML_ESCAP
echo "Ok\n";
?>
--EXPECT--
-UPDATE "php_pgsql_test" SET "num"=1234,"str"=E'ABC',"bin"=E'\\x58595a' WHERE "num"=1234;
+UPDATE "php_pgsql_test" SET "num"=1234,"str"='ABC',"bin"='\\x58595a' WHERE "num"=1234;
UPDATE "php_pgsql_test" SET "num"='1234',"str"='ABC',"bin"='XYZ' WHERE "num"='1234';
Ok
\ No newline at end of file
diff --git a/ext/pgsql/tests/GHSA-7qpv-r5mr-78m4.phpt b/ext/pgsql/tests/GHSA-7qpv-r5mr-78m4.phpt
new file mode 100644
index 00000000..3fbb1224
--- /dev/null
+++ b/ext/pgsql/tests/GHSA-7qpv-r5mr-78m4.phpt
@@ -0,0 +1,52 @@
+--TEST--
+GHSA-7qpv-r5mr-78m4: SQL injection via E'...' backslash breakout
+--CREDITS--
+expatch.llc
+--SKIPIF--
+
+--FILE--
+ "zzz' OR 1=1 --"];
+var_dump(pg_select($db, 'ghsa_7qpv_r5mr_78m4', $params));
+
+$params = ['name' => "zzz\\' OR 1=1 --"];
+var_dump(pg_select($db, 'ghsa_7qpv_r5mr_78m4', $params));
+echo "\n";
+
+$params = ['name' => "john\\', true) --", 'admin' => 'false'];
+echo pg_insert($db, 'ghsa_7qpv_r5mr_78m4', $params, PGSQL_DML_STRING) . "\n";
+pg_insert($db, 'ghsa_7qpv_r5mr_78m4', $params);
+var_dump(pg_select($db, 'ghsa_7qpv_r5mr_78m4', ['id' => 3])[0]['admin']);
+echo "\n";
+
+$params = ['name' => "jake\\', true) --", 'admin' => 'f'];
+echo pg_insert($db, 'ghsa_7qpv_r5mr_78m4', $params, PGSQL_DML_ESCAPE|PGSQL_DML_STRING) . "\n";
+pg_insert($db, 'ghsa_7qpv_r5mr_78m4', $params, PGSQL_DML_EXEC|PGSQL_DML_ESCAPE);
+var_dump(pg_select($db, 'ghsa_7qpv_r5mr_78m4', ['id' => 4])[0]['admin']);
+
+?>
+--EXPECT--
+bool(false)
+bool(false)
+
+INSERT INTO "ghsa_7qpv_r5mr_78m4" ("name","admin") VALUES ('john\'', true) --','f');
+string(1) "f"
+
+INSERT INTO "ghsa_7qpv_r5mr_78m4" ("name","admin") VALUES ('jake\'', true) --','f');
+string(1) "f"
+--CLEAN--
+
diff --git a/ext/pgsql/tests/bug64609.phpt b/ext/pgsql/tests/bug64609.phpt
index 72fac764..39d25514 100644
--- a/ext/pgsql/tests/bug64609.phpt
+++ b/ext/pgsql/tests/bug64609.phpt
@@ -26,5 +26,5 @@ var_dump($converted);
--EXPECT--
array(1) {
[""a""]=>
- string(5) "E'ok'"
+ string(4) "'ok'"
}
\ No newline at end of file
diff --git a/ext/pgsql/tests/bug68638.phpt b/ext/pgsql/tests/bug68638.phpt
index e0701a79..336438c8 100644
--- a/ext/pgsql/tests/bug68638.phpt
+++ b/ext/pgsql/tests/bug68638.phpt
@@ -32,7 +32,7 @@ pg_query("DROP TABLE $table");
?>
--EXPECT--
-string(52) "UPDATE "test_68638" SET "value"=E'inf' WHERE "id"=1;"
+string(51) "UPDATE "test_68638" SET "value"='inf' WHERE "id"=1;"
array(2) {
["id"]=>
string(1) "1"
diff --git a/ext/pgsql/tests/ghsa-hrwm-9436-5mv3.phpt b/ext/pgsql/tests/ghsa-hrwm-9436-5mv3.phpt
new file mode 100644
index 00000000..c1c5e05d
--- /dev/null
+++ b/ext/pgsql/tests/ghsa-hrwm-9436-5mv3.phpt
@@ -0,0 +1,64 @@
+--TEST--
+#GHSA-hrwm-9436-5mv3: pgsql extension does not check for errors during escaping
+--EXTENSIONS--
+pgsql
+--SKIPIF--
+
+--FILE--
+ 'test'])); // table name str escape in php_pgsql_meta_data
+var_dump(pg_insert($db, "$invalid.tbl", ['bar' => 'test'])); // schema name str escape in php_pgsql_meta_data
+var_dump(pg_insert($db, 'ghsa_hrmw_9436_5mv3', ['bar' => $invalid])); // converted value str escape in php_pgsql_convert
+var_dump(pg_insert($db, $invalid, [])); // ident escape in build_tablename
+var_dump(pg_insert($db, 'ghsa_hrmw_9436_5mv3', [$invalid => 'foo'], $flags)); // ident escape for field php_pgsql_insert
+var_dump(pg_insert($db, 'ghsa_hrmw_9436_5mv3', ['bar' => $invalid], $flags)); // str escape for field value in php_pgsql_insert
+var_dump(pg_update($db, 'ghsa_hrmw_9436_5mv3', ['bar' => 'val'], [$invalid => 'test'], $flags)); // ident escape in build_assignment_string
+var_dump(pg_update($db, 'ghsa_hrmw_9436_5mv3', ['bar' => 'val'], ['bar' => $invalid], $flags)); // invalid str escape in build_assignment_string
+var_dump(pg_escape_literal($db, $invalid)); // pg_escape_literal escape
+var_dump(pg_escape_identifier($db, $invalid)); // pg_escape_identifier escape
+
+?>
+--EXPECTF--
+
+Warning: pg_insert(): Escaping table name 'ABC%s';' failed in %s on line %d
+bool(false)
+
+Warning: pg_insert(): Escaping table namespace 'ABC%s';.tbl' failed in %s on line %d
+bool(false)
+
+Notice: pg_insert(): String value escaping failed for PostgreSQL 'text' (bar) in %s on line %d
+bool(false)
+
+Notice: pg_insert(): Failed to escape table name 'ABC%s';' in %s on line %d
+bool(false)
+
+Notice: pg_insert(): Failed to escape field 'ABC%s';' in %s on line %d
+bool(false)
+
+Notice: pg_insert(): Failed to escape field 'bar' value in %s on line %d
+bool(false)
+
+Notice: pg_update(): Failed to escape field 'ABC%s';' in %s on line %d
+bool(false)
+
+Notice: pg_update(): Failed to escape field 'bar' value in %s on line %d
+bool(false)
+
+Warning: pg_escape_literal(): Failed to escape in %s on line %d
+bool(false)
+
+Warning: pg_escape_identifier(): Failed to escape in %s on line %d
+bool(false)
diff --git a/ext/phar/phar_internal.h b/ext/phar/phar_internal.h
index 5a9bcbf5..ba81888f 100644
--- a/ext/phar/phar_internal.h
+++ b/ext/phar/phar_internal.h
@@ -122,8 +122,13 @@
#define TAR_FILE '0'
#define TAR_LINK '1'
#define TAR_SYMLINK '2'
+#define TAR_CHAR '3'
+#define TAR_BLOCK '4'
#define TAR_DIR '5'
+#define TAR_FIFO '6'
#define TAR_NEW '8'
+#define TAR_LONGLINK 'K'
+#define TAR_LONGNAME 'L'
#define TAR_GLOBAL_HDR 'g'
#define TAR_FILE_HDR 'x'
diff --git a/ext/phar/tar.c b/ext/phar/tar.c
index 7ad95ebb..77fe2631 100644
--- a/ext/phar/tar.c
+++ b/ext/phar/tar.c
@@ -37,6 +37,52 @@ static php_uint32 phar_tar_number(char *buf, int len) /* {{{ */
}
/* }}} */
+static zend_bool phar_tar_type_has_data(char typeflag)
+{
+ switch (typeflag) {
+ case TAR_LINK:
+ case TAR_SYMLINK:
+ case TAR_CHAR:
+ case TAR_BLOCK:
+ case TAR_DIR:
+ case TAR_FIFO:
+ return 0;
+ default:
+ return 1;
+ }
+}
+
+static zend_bool phar_tar_size(const char *buf, size_t len, uint32_t *result)
+{
+ uint64_t num = 0;
+ size_t i = 0;
+
+ while (i < len && buf[i] == ' ') {
+ ++i;
+ }
+
+ /* GNU base-256 encoding is only used for sizes that do not fit the octal field */
+ if (i < len && (((unsigned char) buf[i]) & 0x80)) {
+ return 0;
+ }
+
+ while (i < len && buf[i] >= '0' && buf[i] <= '7') {
+ num = num * 8 + (buf[i] - '0');
+ ++i;
+ }
+
+ while (i < len && (buf[i] == ' ' || buf[i] == '\0')) {
+ ++i;
+ }
+
+ if (i != len || num > UINT32_MAX - 511) {
+ return 0;
+ }
+
+ *result = (uint32_t) num;
+ return 1;
+}
+
/* adapted from format_octal() in libarchive
*
* Copyright (c) 2003-2009 Tim Kientzle
@@ -263,8 +309,32 @@ int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias,
memset(hdr->checksum, ' ', sizeof(hdr->checksum));
sum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header));
- size = entry.uncompressed_filesize = entry.compressed_filesize =
- phar_tar_number(hdr->size, sizeof(hdr->size));
+ if (!phar_tar_size(hdr->size, sizeof(hdr->size), &size)) {
+ if (error) {
+ spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (invalid entry size)", fname);
+ }
+ if (last_was_longlink) {
+ pefree(entry.filename, myphar->is_persistent);
+ }
+ php_stream_close(fp);
+ phar_destroy_phar_data(myphar);
+ return FAILURE;
+ }
+ entry.uncompressed_filesize = entry.compressed_filesize = size;
+
+ /* GNU long link names are not supported, so refuse the record instead of
+ * registering it as an entry and dropping the link target of the entry that follows */
+ if (hdr->typeflag == TAR_LONGLINK) {
+ if (error) {
+ spprintf(error, 4096, "phar error: \"%s\" is a tar file with an unsupported GNU long link entry", fname);
+ }
+ if (last_was_longlink) {
+ pefree(entry.filename, myphar->is_persistent);
+ }
+ php_stream_close(fp);
+ phar_destroy_phar_data(myphar);
+ return FAILURE;
+ }
/* skip global/file headers (pax) */
if (!old && (hdr->typeflag == TAR_GLOBAL_HDR || hdr->typeflag == TAR_FILE_HDR)) {
@@ -350,13 +420,13 @@ bail:
goto bail;
}
- if (!last_was_longlink && hdr->typeflag == 'L') {
+ if (!last_was_longlink && hdr->typeflag == TAR_LONGNAME) {
last_was_longlink = 1;
/* support the ././@LongLink system for storing long filenames */
entry.filename_len = entry.uncompressed_filesize;
/* Check for overflow - bug 61065 */
- if (entry.filename_len == UINT_MAX || entry.filename_len == 0) {
+ if (entry.filename_len == 0 || entry.filename_len > totalsize) {
if (error) {
spprintf(error, 4096, "phar error: \"%s\" is a corrupted tar file (invalid entry size)", fname);
}
@@ -568,7 +638,7 @@ bail:
size = (size+511)&~511;
- if (((hdr->typeflag == '\0') || (hdr->typeflag == TAR_FILE)) && size > 0) {
+ if (phar_tar_type_has_data(hdr->typeflag) && size > 0) {
next:
/* this is not good enough - seek succeeds even on truncated tars */
php_stream_seek(fp, size, SEEK_CUR);
diff --git a/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-longlink.phpt b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-longlink.phpt
new file mode 100644
index 00000000..6257ced4
--- /dev/null
+++ b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-longlink.phpt
@@ -0,0 +1,50 @@
+--TEST--
+GHSA-j3wh-g957-2m85 (././@LongLink name longer than the archive)
+--SKIPIF--
+
+--INI--
+phar.require_hash=0
+--FILE--
+= 148 && $i < 156) ? 0x20 : ord($header[$i]);
+ }
+
+ return substr_replace($header, sprintf("%06o\0 ", $checksum), 148, 8);
+}
+
+$fname = __DIR__ . '/' . basename(__FILE__, '.php') . '.tar';
+
+/* 2 GB of file name announced by a 2 KB archive */
+$tar = tar_header('././@LongLink', "20000000000\0", 'L');
+$tar .= str_pad('long.txt', 512, "\0");
+$tar .= tar_header('short.txt', sprintf("%011o\0", 3)) . str_pad('abc', 512, "\0");
+$tar .= str_repeat("\0", 1024);
+file_put_contents($fname, $tar);
+
+try {
+ new PharData($fname);
+} catch (UnexpectedValueException $e) {
+ echo $e->getMessage(), "\n";
+}
+?>
+--CLEAN--
+
+--EXPECTF--
+phar error: "%s" is a corrupted tar file (invalid entry size)
diff --git a/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-size.phpt b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-size.phpt
new file mode 100644
index 00000000..b480916e
--- /dev/null
+++ b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-size.phpt
@@ -0,0 +1,92 @@
+--TEST--
+GHSA-j3wh-g957-2m85 (tar entry injection via invalid entry size)
+--SKIPIF--
+
+--INI--
+phar.require_hash=0
+--FILE--
+= 148 && $i < 156) ? 0x20 : ord($header[$i]);
+ }
+
+ return substr_replace($header, sprintf("%06o\0 ", $checksum), 148, 8);
+}
+
+function tar_dump($fname)
+{
+ try {
+ $phar = new PharData($fname);
+ $names = [];
+ foreach (new RecursiveIteratorIterator($phar) as $file) {
+ $names[] = $file->getFilename();
+ }
+ sort($names);
+ echo implode(', ', $names), "\n";
+ } catch (UnexpectedValueException $e) {
+ echo $e->getMessage(), "\n";
+ }
+}
+
+$base = __DIR__ . '/' . basename(__FILE__, '.php');
+
+/* the entry after the carrier is never reached by a conforming tar reader */
+$sizes = [
+ 'octal overflow to 0' => "40000000000\0",
+ 'octal overflow to 1' => "40000000001\0",
+ 'octal padding overflow' => "37777777400\0",
+ 'GNU base-256' => "\x80" . str_repeat("\0", 9) . "\x02\x00",
+ 'non-octal digits' => "99999999999\0",
+ 'trailing garbage' => "0000000001XX",
+];
+
+$i = 0;
+foreach ($sizes as $label => $size) {
+ $fname = $base . '.' . $i++ . '.tar';
+ $tar = tar_header('normal.txt', sprintf("%011o\0", 9)) . str_pad('NORMAL_OK', 512, "\0");
+ $tar .= tar_header('carrier.bin', $size);
+ $tar .= tar_header('injected.txt', sprintf("%011o\0", 8)) . str_pad('INJECTED', 512, "\0");
+ $tar .= str_repeat("\0", 1024);
+ file_put_contents($fname, $tar);
+
+ echo $label, ': ';
+ tar_dump($fname);
+}
+
+$fname = $base . '.valid.tar';
+$tar = tar_header('normal.txt', sprintf("%011o\0", 9)) . str_pad('NORMAL_OK', 512, "\0");
+$tar .= tar_header('second.txt', sprintf("%011o\0", 8)) . str_pad('SECOND__', 512, "\0");
+$tar .= str_repeat("\0", 1024);
+file_put_contents($fname, $tar);
+
+echo 'valid archive: ';
+tar_dump($fname);
+?>
+--CLEAN--
+
+--EXPECTF--
+octal overflow to 0: phar error: "%s" is a corrupted tar file (invalid entry size)
+octal overflow to 1: phar error: "%s" is a corrupted tar file (invalid entry size)
+octal padding overflow: phar error: "%s" is a corrupted tar file (invalid entry size)
+GNU base-256: phar error: "%s" is a corrupted tar file (invalid entry size)
+non-octal digits: phar error: "%s" is a corrupted tar file (invalid entry size)
+trailing garbage: phar error: "%s" is a corrupted tar file (invalid entry size)
+valid archive: normal.txt, second.txt
diff --git a/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-typeflag.phpt b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-typeflag.phpt
new file mode 100644
index 00000000..8a1737b5
--- /dev/null
+++ b/ext/phar/tests/tar/GHSA-j3wh-g957-2m85-typeflag.phpt
@@ -0,0 +1,79 @@
+--TEST--
+GHSA-j3wh-g957-2m85 (tar entry injection via entry types that carry data)
+--SKIPIF--
+
+--INI--
+phar.require_hash=0
+--FILE--
+= 148 && $i < 156) ? 0x20 : ord($header[$i]);
+ }
+
+ return substr_replace($header, sprintf("%06o\0 ", $checksum), 148, 8);
+}
+
+$base = __DIR__ . '/' . basename(__FILE__, '.php');
+
+/* '5' and the other types below carry no data in any tar reader, so the
+ * injected header stays visible to all of them and is not hidden from
+ * anything that inspects the archive with a different implementation.
+ * 'K' is a GNU metadata record that is not supported and is refused. */
+$typeflags = [
+ 'contiguous file' => '7',
+ 'unknown type' => 'Z',
+ 'GNU long link' => 'K',
+ 'directory' => '5',
+ 'fifo' => '6',
+];
+
+$i = 0;
+foreach ($typeflags as $label => $typeflag) {
+ $fname = $base . '.' . $i++ . '.tar';
+ $tar = tar_header('normal.txt', sprintf("%011o\0", 9)) . str_pad('NORMAL_OK', 512, "\0");
+ $tar .= tar_header('carrier.bin', sprintf("%011o\0", 512), $typeflag);
+ /* the carrier's only data block is a tar header a conforming reader skips */
+ $tar .= tar_header('injected.txt', sprintf("%011o\0", 0));
+ $tar .= str_repeat("\0", 1024);
+ file_put_contents($fname, $tar);
+
+ echo $label, ': ';
+ try {
+ $phar = new PharData($fname);
+ $names = [];
+ foreach (new RecursiveIteratorIterator($phar) as $file) {
+ $names[] = $file->getFilename();
+ }
+ sort($names);
+ echo implode(', ', $names), "\n";
+ } catch (UnexpectedValueException $e) {
+ echo $e->getMessage(), "\n";
+ }
+}
+?>
+--CLEAN--
+
+--EXPECTF--
+contiguous file: carrier.bin, normal.txt
+unknown type: carrier.bin, normal.txt
+GNU long link: phar error: "%s" is a tar file with an unsupported GNU long link entry
+directory: injected.txt, normal.txt
+fifo: carrier.bin, injected.txt, normal.txt
diff --git a/ext/phar/tests/tar/ghsa-vc5h-9ppw-p5f3-symlink-circular.phpt b/ext/phar/tests/tar/ghsa-vc5h-9ppw-p5f3-symlink-circular.phpt
new file mode 100644
index 00000000..5d397b5b
--- /dev/null
+++ b/ext/phar/tests/tar/ghsa-vc5h-9ppw-p5f3-symlink-circular.phpt
@@ -0,0 +1,27 @@
+--TEST--
+GHSA-vc5h-9ppw-p5f3 (circular symlinks in tar should not cause stack overflow)
+--CREDITS--
+Calvin Young - eWalker Consulting (HK) Limited
+Enoch Chow - Isomorph Cyber
+--SKIPIF--
+
+--FILE--
+getContent() === '');
+
+// rho-shaped cycle (tail leading into a loop)
+$phar = new PharData($base . '/files/circular_symlinks_rho.tar');
+var_dump($phar['file_a']->getContent() === '');
+
+// long cycle (400 entries)
+$phar = new PharData($base . '/files/circular_symlinks_long.tar');
+var_dump($phar['link_0']->getContent() === '');
+?>
+--EXPECT--
+bool(true)
+bool(true)
+bool(true)
diff --git a/ext/phar/util.c b/ext/phar/util.c
index 06e4e55d..264bd1ff 100644
--- a/ext/phar/util.c
+++ b/ext/phar/util.c
@@ -61,27 +61,58 @@ static char *phar_get_link_location(phar_entry_info *entry TSRMLS_DC) /* {{{ */
}
/* }}} */
-phar_entry_info *phar_get_link_source(phar_entry_info *entry TSRMLS_DC) /* {{{ */
+static phar_entry_info *phar_follow_one_link(phar_entry_info *entry TSRMLS_DC) /* {{{ */
{
phar_entry_info *link_entry;
char *link;
- if (!entry->link) {
- return entry;
- }
-
link = phar_get_link_location(entry TSRMLS_CC);
if (SUCCESS == zend_hash_find(&(entry->phar->manifest), entry->link, strlen(entry->link), (void **)&link_entry) ||
SUCCESS == zend_hash_find(&(entry->phar->manifest), link, strlen(link), (void **)&link_entry)) {
if (link != entry->link) {
efree(link);
}
- return phar_get_link_source(link_entry TSRMLS_CC);
- } else {
- if (link != entry->link) {
- efree(link);
+ return link_entry;
+ }
+
+ if (link != entry->link) {
+ efree(link);
+ }
+ return NULL;
+}
+/* }}} */
+
+phar_entry_info *phar_get_link_source(phar_entry_info *entry TSRMLS_DC) /* {{{ */
+{
+ phar_entry_info *slow, *fast;
+
+ if (!entry->link) {
+ return entry;
+ }
+
+ /*
+ * Use Floyd's cycle detection algorithm to follow the symlink chain without unbounded
+ * recursion. Each entry has at most one outgoing link, so if a cycle exists the fast pointer
+ * will eventually meet the slow one. Otherwise the fast pointer reaches the end first.
+ */
+ slow = fast = entry;
+ while (1) {
+ fast = phar_follow_one_link(fast TSRMLS_CC);
+ if (!fast || !fast->link) {
+ return fast;
+ }
+ fast = phar_follow_one_link(fast TSRMLS_CC);
+ if (!fast || !fast->link) {
+ return fast;
+ }
+
+ /* no need to check slow as it's always behind */
+ slow = phar_follow_one_link(slow TSRMLS_CC);
+
+ if (slow == fast) {
+ /* circular symlink chain */
+ return NULL;
}
- return NULL;
}
}
/* }}} */
diff --git a/ext/soap/php_encoding.c b/ext/soap/php_encoding.c
index 40e87f23..bbfadc5b 100644
--- a/ext/soap/php_encoding.c
+++ b/ext/soap/php_encoding.c
@@ -383,6 +383,13 @@ static zend_bool soap_check_xml_ref(zval **data, xmlNodePtr node TSRMLS_DC)
return 1;
}
} else {
+ /* The map holds its own reference so that a value released by its
+ * container (e.g. a duplicate Apache Map key) cannot be reused
+ * through a later href. Only decoding stores zvals in this map
+ * (encoding stores xmlNodePtr values), so the destructor is set
+ * here rather than when the map is created. */
+ SOAP_GLOBAL(ref_map)->pDestructor = ZVAL_PTR_DTOR;
+ Z_ADDREF_PP(data);
zend_hash_index_update(SOAP_GLOBAL(ref_map), (ulong)node, (void**)data, sizeof(zval*), NULL);
}
}
@@ -583,7 +590,12 @@ static zval *master_to_zval_int(encodePtr encode, xmlNodePtr data TSRMLS_DC)
}
}
if (encode->to_zval) {
+ if (SOAP_GLOBAL(decode_depth) >= SOAP_MAX_DECODE_DEPTH) {
+ soap_error0(E_ERROR, "Encoding: Nesting level too deep");
+ }
+ SOAP_GLOBAL(decode_depth)++;
ret = encode->to_zval(&encode->details, data TSRMLS_CC);
+ SOAP_GLOBAL(decode_depth)--;
}
return ret;
}
@@ -3569,6 +3581,7 @@ void encode_reset_ns()
TSRMLS_FETCH();
SOAP_GLOBAL(cur_uniq_ns) = 0;
SOAP_GLOBAL(cur_uniq_ref) = 0;
+ SOAP_GLOBAL(decode_depth) = 0;
if (SOAP_GLOBAL(ref_map)) {
zend_hash_destroy(SOAP_GLOBAL(ref_map));
} else {
@@ -3582,6 +3595,7 @@ void encode_finish()
TSRMLS_FETCH();
SOAP_GLOBAL(cur_uniq_ns) = 0;
SOAP_GLOBAL(cur_uniq_ref) = 0;
+ SOAP_GLOBAL(decode_depth) = 0;
if (SOAP_GLOBAL(ref_map)) {
zend_hash_destroy(SOAP_GLOBAL(ref_map));
efree(SOAP_GLOBAL(ref_map));
diff --git a/ext/soap/php_http.c b/ext/soap/php_http.c
index f3935cb1..aecfd39a 100644
--- a/ext/soap/php_http.c
+++ b/ext/soap/php_http.c
@@ -1111,7 +1111,7 @@ try_again:
char *t = phpurl->path;
char *p = strrchr(t, '/');
if (p) {
- char *s = emalloc((p - t) + strlen(new_url->path) + 2);
+ char *s = safe_emalloc(1, p - t, strlen(new_url->path) + 2);
strncpy(s, t, (p - t) + 1);
s[(p - t) + 1] = 0;
strcat(s, new_url->path);
@@ -1352,11 +1352,24 @@ static char *get_http_header_value(char *headers, char *type)
/* match */
tmp = pos + typelen;
+
+ /* strip leading whitespace */
+ while (*tmp == ' ' || *tmp == '\t') {
+ tmp++;
+ }
+
eol = strchr(tmp, '\n');
if (eol == NULL) {
eol = headers + headerslen;
- } else if (eol > tmp && *(eol-1) == '\r') {
- eol--;
+ } else if (eol > tmp) {
+ if (*(eol-1) == '\r') {
+ eol--;
+ }
+
+ /* strip trailing whitespace */
+ while (eol > tmp && (*(eol-1) == ' ' || *(eol-1) == '\t')) {
+ eol--;
+ }
}
return estrndup(tmp, eol - tmp);
}
@@ -1409,18 +1422,20 @@ static int get_http_body(php_stream *stream, int close, char *headers, char **r
done = FALSE;
while (!done) {
- int buf_size = 0;
+ unsigned int buf_size = 0;
php_stream_gets(stream, headerbuf, sizeof(headerbuf));
if (sscanf(headerbuf, "%x", &buf_size) > 0 ) {
if (buf_size > 0) {
int len_size = 0;
- if (http_buf_size + buf_size + 1 < 0) {
- efree(http_buf);
+ if (buf_size >= (unsigned int)(INT_MAX - http_buf_size)) {
+ if (http_buf) {
+ efree(http_buf);
+ }
return FALSE;
}
- http_buf = erealloc(http_buf, http_buf_size + buf_size + 1);
+ http_buf = safe_erealloc(http_buf, 1, http_buf_size, buf_size + 1);
while (len_size < buf_size) {
int len_read = php_stream_read(stream, http_buf + http_buf_size, buf_size - len_size);
@@ -1490,6 +1505,12 @@ static int get_http_body(php_stream *stream, int close, char *headers, char **r
} else if (header_close) {
do {
int len_read;
+ if (UNEXPECTED(http_buf_size >= INT_MAX - 4096)) {
+ if (http_buf) {
+ efree(http_buf);
+ }
+ return FALSE;
+ }
http_buf = erealloc(http_buf, http_buf_size + 4096 + 1);
len_read = php_stream_read(stream, http_buf + http_buf_size, 4096);
if (len_read > 0) {
diff --git a/ext/soap/php_packet_soap.c b/ext/soap/php_packet_soap.c
index 2bcb042c..73670036 100644
--- a/ext/soap/php_packet_soap.c
+++ b/ext/soap/php_packet_soap.c
@@ -192,15 +192,22 @@ int parse_packet_soap(zval *this_ptr, char *buffer, int buffer_size, sdlFunction
tmp = get_node(fault->children, "faultstring");
if (tmp != NULL && tmp->children != NULL) {
zval *zv = master_to_zval(get_conversion(IS_STRING), tmp TSRMLS_CC);
- faultstring = Z_STRVAL_P(zv);
- FREE_ZVAL(zv);
+ /* a typemap or xsi:type can decode a non-string, and SOAP_GLOBAL(ref_map)
+ * can still hold the zval, so take a private string copy; nil and
+ * false convert to the interned empty string, so copy, never steal */
+ SEPARATE_ZVAL(&zv);
+ convert_to_string(zv);
+ faultstring = estrndup(Z_STRVAL_P(zv), Z_STRLEN_P(zv));
+ zval_ptr_dtor(&zv);
}
tmp = get_node(fault->children, "faultactor");
if (tmp != NULL && tmp->children != NULL) {
zval *zv = master_to_zval(get_conversion(IS_STRING), tmp TSRMLS_CC);
- faultactor = Z_STRVAL_P(zv);
- FREE_ZVAL(zv);
+ SEPARATE_ZVAL(&zv);
+ convert_to_string(zv);
+ faultactor = estrndup(Z_STRVAL_P(zv), Z_STRLEN_P(zv));
+ zval_ptr_dtor(&zv);
}
tmp = get_node(fault->children, "detail");
@@ -222,8 +229,10 @@ int parse_packet_soap(zval *this_ptr, char *buffer, int buffer_size, sdlFunction
tmp = get_node(tmp->children,"Text");
if (tmp != NULL && tmp->children != NULL) {
zval *zv = master_to_zval(get_conversion(IS_STRING), tmp TSRMLS_CC);
- faultstring = Z_STRVAL_P(zv);
- FREE_ZVAL(zv);
+ SEPARATE_ZVAL(&zv);
+ convert_to_string(zv);
+ faultstring = estrndup(Z_STRVAL_P(zv), Z_STRLEN_P(zv));
+ zval_ptr_dtor(&zv);
}
}
@@ -387,8 +396,13 @@ int parse_packet_soap(zval *this_ptr, char *buffer, int buffer_size, sdlFunction
tmp = *(zval**)tmp;
Z_ADDREF_P(tmp);
zval_dtor(return_value);
- *return_value = *tmp;
- FREE_ZVAL(tmp);
+ if (Z_REFCOUNT_P(tmp) == 1) {
+ *return_value = *tmp;
+ FREE_ZVAL(tmp);
+ } else {
+ /* still referenced, e.g. by SOAP_GLOBAL(ref_map) until encode_finish() */
+ ZVAL_ZVAL(return_value, tmp, 1, 1);
+ }
}
}
diff --git a/ext/soap/php_soap.h b/ext/soap/php_soap.h
index a146633c..546bfe95 100644
--- a/ext/soap/php_soap.h
+++ b/ext/soap/php_soap.h
@@ -155,6 +155,8 @@ struct _soapService {
#define SOAP_SSL_METHOD_SSLv3 2
#define SOAP_SSL_METHOD_SSLv23 3
+#define SOAP_MAX_XML_DEPTH 2048
+#define SOAP_MAX_DECODE_DEPTH (SOAP_MAX_XML_DEPTH * 2)
ZEND_BEGIN_MODULE_GLOBALS(soap)
HashTable defEncNs; /* mapping of default namespaces to prefixes */
@@ -180,6 +182,7 @@ ZEND_BEGIN_MODULE_GLOBALS(soap)
HashTable wsdl_cache;
int cur_uniq_ref;
HashTable *ref_map;
+ unsigned int decode_depth;
ZEND_END_MODULE_GLOBALS(soap)
#ifdef ZTS
diff --git a/ext/soap/php_xml.c b/ext/soap/php_xml.c
index 36d303c8..b5562e2f 100644
--- a/ext/soap/php_xml.c
+++ b/ext/soap/php_xml.c
@@ -38,36 +38,72 @@ static int is_blank(const xmlChar* str)
return 1;
}
-/* removes all empty text, comments and other insignoficant nodes */
+/* removes all empty text, comments and other insignoficant nodes.
+ * Iterative because recursion overflows the stack on a deep document. */
static void cleanup_xml_node(xmlNodePtr node)
{
- xmlNodePtr trav;
- xmlNodePtr del = NULL;
+ xmlNodePtr parent = node;
+ xmlNodePtr trav = node->children;
- trav = node->children;
while (trav != NULL) {
- if (del != NULL) {
- xmlUnlinkNode(del);
- xmlFreeNode(del);
- del = NULL;
- }
+ xmlNodePtr next = trav->next;
+
if (trav->type == XML_TEXT_NODE) {
if (is_blank(trav->content)) {
- del = trav;
+ xmlUnlinkNode(trav);
+ xmlFreeNode(trav);
}
} else if ((trav->type != XML_ELEMENT_NODE) &&
(trav->type != XML_CDATA_SECTION_NODE)) {
- del = trav;
+ xmlUnlinkNode(trav);
+ xmlFreeNode(trav);
} else if (trav->children != NULL) {
- cleanup_xml_node(trav);
+ parent = trav;
+ trav = trav->children;
+ continue;
}
- trav = trav->next;
+
+ while (next == NULL) {
+ if (parent == node) {
+ return;
+ }
+ next = parent->next;
+ parent = parent->parent;
+ }
+ trav = next;
}
- if (del != NULL) {
- xmlUnlinkNode(del);
- xmlFreeNode(del);
+}
+
+#if LIBXML_VERSION < 21300
+static int is_nesting_too_deep(xmlNodePtr node)
+{
+ xmlNodePtr trav = node->children;
+ unsigned int depth = 0;
+
+ while (trav != NULL) {
+ /* An entity reference borrows its declaration as child list, and that
+ * declaration hangs off the DTD, so descending leaves the document. */
+ if (trav->children != NULL &&
+ trav->type != XML_ENTITY_REF_NODE &&
+ trav->type != XML_DTD_NODE) {
+ if (++depth > SOAP_MAX_XML_DEPTH) {
+ return TRUE;
+ }
+ trav = trav->children;
+ continue;
+ }
+ while (trav->next == NULL) {
+ trav = trav->parent;
+ if (trav == node) {
+ return FALSE;
+ }
+ depth--;
+ }
+ trav = trav->next;
}
+ return FALSE;
}
+#endif
static void soap_ignorableWhitespace(void *ctx, const xmlChar *ch, int len)
{
@@ -127,6 +163,15 @@ xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC)
*/
if (ret) {
+#if LIBXML_VERSION < 21300
+ if (is_nesting_too_deep((xmlNodePtr)ret)) {
+ /* php_sdl.c reports xmlGetLastError() as the reason, and libxml2 did
+ * not fail here, so drop the error an earlier parse left behind. */
+ xmlResetLastError();
+ xmlFreeDoc(ret);
+ return NULL;
+ }
+#endif
cleanup_xml_node((xmlNodePtr)ret);
}
return ret;
@@ -177,6 +222,13 @@ xmlDocPtr soap_xmlParseMemory(const void *buf, size_t buf_size)
xmlCleanupParser();
*/
+#if LIBXML_VERSION < 21300
+ if (ret && is_nesting_too_deep((xmlNodePtr)ret)) {
+ xmlFreeDoc(ret);
+ ret = NULL;
+ }
+#endif
+
/*
if (ret) {
cleanup_xml_node((xmlNodePtr)ret);
@@ -299,6 +351,8 @@ xmlNodePtr get_node_with_attribute_ex(xmlNodePtr node, char *name, char *name_ns
xmlNodePtr get_node_with_attribute_recursive_ex(xmlNodePtr node, char *name, char *name_ns, char *attribute, char *value, char *attr_ns)
{
+ unsigned int depth = 0;
+
while (node != NULL) {
if (node_is_equal_ex(node, name, name_ns)) {
xmlAttrPtr attr = get_attribute_ex(node->properties, attribute, attr_ns);
@@ -306,11 +360,19 @@ xmlNodePtr get_node_with_attribute_recursive_ex(xmlNodePtr node, char *name, cha
return node;
}
}
- if (node->children != NULL) {
- xmlNodePtr tmp = get_node_with_attribute_recursive_ex(node->children, name, name_ns, attribute, value, attr_ns);
- if (tmp) {
- return tmp;
+ if (node->children != NULL &&
+ node->type != XML_ENTITY_REF_NODE &&
+ node->type != XML_DTD_NODE) {
+ node = node->children;
+ depth++;
+ continue;
+ }
+ while (node->next == NULL) {
+ if (depth == 0) {
+ return NULL;
}
+ node = node->parent;
+ depth--;
}
node = node->next;
}
diff --git a/ext/soap/soap.c b/ext/soap/soap.c
index 21f11be7..4fcf3342 100644
--- a/ext/soap/soap.c
+++ b/ext/soap/soap.c
@@ -584,6 +584,7 @@ static void php_soap_init_globals(zend_soap_globals *soap_globals TSRMLS_DC)
soap_globals->soap_version = SOAP_1_1;
soap_globals->mem_cache = NULL;
soap_globals->ref_map = NULL;
+ soap_globals->decode_depth = 0;
}
PHP_MSHUTDOWN_FUNCTION(soap)
@@ -4519,8 +4520,10 @@ static xmlNodePtr serialize_zval(zval *val, sdlParamPtr param, char *paramName,
enc = NULL;
}
xmlParam = master_to_xml(enc, val, style, parent TSRMLS_CC);
- if (!strcmp((char*)xmlParam->name, "BOGUS")) {
- xmlNodeSetName(xmlParam, BAD_CAST(paramName));
+ if (xmlParam != NULL) {
+ if (xmlParam->name == NULL || strcmp((char*)xmlParam->name, "BOGUS") == 0) {
+ xmlNodeSetName(xmlParam, BAD_CAST(paramName));
+ }
}
return xmlParam;
}
diff --git a/ext/soap/tests/GHSA-85c2-q967-79q5.phpt b/ext/soap/tests/GHSA-85c2-q967-79q5.phpt
new file mode 100644
index 00000000..8bcac26a
--- /dev/null
+++ b/ext/soap/tests/GHSA-85c2-q967-79q5.phpt
@@ -0,0 +1,61 @@
+--TEST--
+GHSA-85c2-q967-79q5: Stale SOAP_GLOBAL(ref_map) pointer with Apache Map
+--CREDITS--
+brettgervasoni
+--EXTENSIONS--
+soap
+--FILE--
+
+
+
+
+
+
+
+
+
+
+XML;
+
+$s = new SoapServer(null, ['uri' => 'urn:a']);
+$s->setClass(Handler::class);
+$s->handle($envelope);
+var_dump($result);
+
+?>
+--EXPECTF--
+
+
+array(2) {
+ [0]=>
+ array(1) {
+ ["foo"]=>
+ string(3) "baz"
+ }
+ [1]=>
+ object(stdClass)#%d (1) {
+ ["object"]=>
+ string(3) "bar"
+ }
+}
diff --git a/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-chain.phpt b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-chain.phpt
new file mode 100644
index 00000000..afb7870e
--- /dev/null
+++ b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-chain.phpt
@@ -0,0 +1,47 @@
+--TEST--
+GHSA-rgrp-mwpx-f6rm: Stack overflow on a chain of href references
+--EXTENSIONS--
+soap
+--FILE--
+' . ($i < $n ? '' : 'leaf') . '';
+ }
+
+ return ''
+ . $links . '';
+}
+
+function test($arg)
+{
+ $GLOBALS['decoded'] = $arg;
+
+ return 'ok';
+}
+
+$server = new SoapServer(null, ['uri' => 'urn:test']);
+$server->addFunction('test');
+
+$server->handle(chain(3));
+var_dump($GLOBALS['decoded']);
+
+$server->handle(chain(12000));
+
+?>
+--EXPECTF--
+
+ok
+object(stdClass)#%d (1) {
+ ["q"]=>
+ object(stdClass)#%d (1) {
+ ["q"]=>
+ string(4) "leaf"
+ }
+}
+
+SOAP-ENV:ServerSOAP-ERROR: Encoding: Nesting level too deep
diff --git a/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-cycle.phpt b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-cycle.phpt
new file mode 100644
index 00000000..06f25b50
--- /dev/null
+++ b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm-href-cycle.phpt
@@ -0,0 +1,43 @@
+--TEST--
+GHSA-rgrp-mwpx-f6rm: Stack overflow on an array element referencing its own array
+--EXTENSIONS--
+soap
+--FILE--
+'
+ . '' . $param . '';
+}
+
+function test($arg)
+{
+ $GLOBALS['decoded'] = $arg;
+
+ return 'ok';
+}
+
+$server = new SoapServer(null, ['uri' => 'urn:test']);
+$server->addFunction('test');
+
+$server->handle(envelope('ab'));
+var_dump($GLOBALS['decoded']);
+
+$server->handle(envelope(''));
+
+?>
+--EXPECTF--
+
+ok
+array(2) {
+ [0]=>
+ string(1) "a"
+ [1]=>
+ string(1) "b"
+}
+
+SOAP-ENV:ServerSOAP-ERROR: Encoding: Nesting level too deep
diff --git a/ext/soap/tests/GHSA-rgrp-mwpx-f6rm.phpt b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm.phpt
new file mode 100644
index 00000000..98f398bf
--- /dev/null
+++ b/ext/soap/tests/GHSA-rgrp-mwpx-f6rm.phpt
@@ -0,0 +1,89 @@
+--TEST--
+GHSA-rgrp-mwpx-f6rm: Stack overflow on deeply nested XML
+--EXTENSIONS--
+soap
+--INI--
+soap.wsdl_cache_enabled=0
+--FILE--
+'
+ . str_repeat('', $depth) . 'leaf' . str_repeat('', $depth)
+ . '';
+}
+
+function test($arg)
+{
+ $depth = 0;
+ while (is_object($arg)) {
+ $depth++;
+ $arg = $arg->a;
+ }
+ $GLOBALS['decoded'] = [$depth, $arg];
+
+ return 'ok';
+}
+
+$server = new SoapServer(null, ['uri' => 'urn:test']);
+$server->addFunction('test');
+
+$server->handle(envelope(200));
+var_dump($GLOBALS['decoded']);
+
+/* libxml2 2.13 rejects past 2048 despite XML_PARSE_HUGE, older ones do not. */
+$wsdl = __DIR__ . '/GHSA-rgrp-mwpx-f6rm.wsdl';
+foreach ([1000, 2100] as $depth) {
+ file_put_contents($wsdl, '' . str_repeat('', $depth) . 'leaf' . str_repeat('', $depth) . '');
+ try {
+ new SoapClient($wsdl);
+ } catch (SoapFault $e) {
+ echo rtrim($e->getMessage()), "\n";
+ }
+}
+
+/* A WSDL reached through an entity reference still loads. Its replacement tree cannot
+ be built deeper than the 2048 libxml2 2.13 enforces, so this pins the entity skip
+ rather than the limit. */
+$entity = __DIR__ . '/GHSA-rgrp-mwpx-f6rm-entity.wsdl';
+$desc = str_repeat('<p>', 300) . 'A test service.' . str_repeat('</p>', 300);
+file_put_contents($entity, '
+]>
+
+ &desc;
+
+
+
+
+
+
+
+');
+var_dump((new SoapClient($entity))->__getFunctions());
+
+$server->handle(envelope(3000));
+
+?>
+--CLEAN--
+
+--EXPECTF--
+
+ok
+array(2) {
+ [0]=>
+ int(199)
+ [1]=>
+ string(4) "leaf"
+}
+SOAP-ERROR: Parsing WSDL: Couldn't find in '%sGHSA-rgrp-mwpx-f6rm.wsdl'
+SOAP-ERROR: Parsing WSDL: Couldn't load from '%sGHSA-rgrp-mwpx-f6rm.wsdl'%S
+array(1) {
+ [0]=>
+ string(9) "void op()"
+}
+
+SOAP-ENV:ClientBad Request
diff --git a/ext/soap/tests/bug47021.phpt b/ext/soap/tests/bug47021.phpt
new file mode 100644
index 00000000..757e74ef
--- /dev/null
+++ b/ext/soap/tests/bug47021.phpt
@@ -0,0 +1,80 @@
+--TEST--
+Bug #47021 SoapClient (SoapClient stumbles over WSDL delivered with "Transfer-Encoding: chunked")
+--INI--
+soap.wsdl_cache_enabled=0
+--SKIPIF--
+
+--FILE--
+ $v) {
+ $chunks[$k] = sprintf("%08x\r\n%s\r\n", strlen($v), $v);
+ }
+
+ return join('', $chunks);
+}
+
+$wsdl = file_get_contents(__DIR__.'/server030.wsdl');
+
+$soap = <<
+- text0
- text1
- text2
- text3
- text4
- text5
- text6
- text7
- text8
- text9
+EOF;
+
+$responses = [
+ "data://text/plain,HTTP/1.1 200 OK\r\n".
+ "Content-Type: text/xml;charset=utf-8\r\n".
+ "Transfer-Encoding: \t chunked\t \r\n".
+ "Connection: close\r\n".
+ "\r\n".
+ chunk_body($wsdl, 64),
+ "data://text/plain,HTTP/1.1 200 OK\r\n".
+ "Content-Type: text/xml;charset=utf-8\r\n".
+ "Transfer-Encoding: \t chunked\t \r\n".
+ "Connection: close\r\n".
+ "\r\n".
+ chunk_body($soap, 156),
+];
+
+
+$pid = http_server('tcp://127.0.0.1:12342', $responses);
+
+$options = [
+ 'trace' => true,
+ 'location' => 'http://127.0.0.1:12342/',
+];
+
+class BugSoapClient extends SoapClient
+{
+ public function __doRequest($request, $location, $action, $version, $one_way = null)
+ {
+ $response = parent::__doRequest($request, $location, $action, $version, $one_way);
+
+ var_dump(strlen($response));
+
+ return $response;
+ }
+}
+
+$client = new BugSoapClient('http://127.0.0.1:12342/', $options);
+
+var_dump(count($client->getItems()));
+
+http_server_kill($pid);
+
+?>
+--EXPECT--
+int(1291)
+int(10)
diff --git a/ext/soap/tests/bugs/bug66049.phpt b/ext/soap/tests/bugs/bug66049.phpt
new file mode 100644
index 00000000..05de9410
--- /dev/null
+++ b/ext/soap/tests/bugs/bug66049.phpt
@@ -0,0 +1,48 @@
+--TEST--
+Fix #66049 Typemap can break parsing in parse_packet_soap leading to a segfault
+--EXTENSIONS--
+soap
+--INI--
+soap.wsdl_cache_enabled=0
+--FILE--
+
+
+
+ SOAP-ENV:Servernot present
+ ';
+ return $res;
+ }
+}
+
+try {
+ $client=new TestSoapClient(null, [
+ 'uri' => 'test://',
+ 'location' => 'test://',
+ 'typemap' => [[
+ "type_ns" => "http://www.w3.org/2001/XMLSchema",
+ "type_name" => "string",
+ "from_xml" => "soap_string_from_xml"
+ ]]]);
+ $client->Mist("");
+} catch (SoapFault $e) {
+ var_dump($e->faultstring);
+ var_dump($e->faultcode);
+}
+?>
+Done
+--EXPECT--
+soap_string_from_xml
+string(3) "2.3"
+string(15) "SOAP-ENV:Server"
+Done
diff --git a/ext/soap/tests/bugs/bug66049_interned.phpt b/ext/soap/tests/bugs/bug66049_interned.phpt
new file mode 100644
index 00000000..99615386
--- /dev/null
+++ b/ext/soap/tests/bugs/bug66049_interned.phpt
@@ -0,0 +1,64 @@
+--TEST--
+Fix #66049 follow-up: nil or typemap-literal fault strings are copied, not freed
+--EXTENSIONS--
+soap
+--INI--
+soap.wsdl_cache_enabled=0
+--FILE--
+response;
+ }
+}
+
+$fault = '
+
+SOAP-ENV:Server%s';
+
+$client = new TestSoapClient(null, ['uri' => 'test://', 'location' => 'test://']);
+$client->response = sprintf($fault,
+ 'xy');
+for ($i = 0; $i < 3; $i++) {
+ try {
+ $client->Mist("");
+ } catch (SoapFault $e) {
+ var_dump($e->faultstring, $e->faultactor);
+ }
+}
+
+$client = new TestSoapClient(null, [
+ 'uri' => 'test://',
+ 'location' => 'test://',
+ 'typemap' => [[
+ "type_ns" => "http://www.w3.org/2001/XMLSchema",
+ "type_name" => "string",
+ "from_xml" => "soap_string_from_xml"
+ ]]]);
+$client->response = sprintf($fault, 'not present');
+for ($i = 0; $i < 3; $i++) {
+ try {
+ $client->Mist("");
+ } catch (SoapFault $e) {
+ var_dump($e->faultstring);
+ }
+}
+?>
+Done
+--EXPECT--
+string(0) ""
+string(0) ""
+string(0) ""
+string(0) ""
+string(0) ""
+string(0) ""
+string(12) "from typemap"
+string(12) "from typemap"
+string(12) "from typemap"
+Done
diff --git a/ext/soap/tests/interop/Round3/GroupE/r3_groupE_list_006w.phpt b/ext/soap/tests/interop/Round3/GroupE/r3_groupE_list_006w.phpt
index 3549f452..9726f848 100644
--- a/ext/soap/tests/interop/Round3/GroupE/r3_groupE_list_006w.phpt
+++ b/ext/soap/tests/interop/Round3/GroupE/r3_groupE_list_006w.phpt
@@ -33,7 +33,7 @@ object(stdClass)#%d (3) {
["varString"]=>
string(4) "arg1"
["child"]=>
- &object(stdClass)#%d (3) {
+ object(stdClass)#%d (3) {
["varInt"]=>
int(2)
["varString"]=>
diff --git a/ext/standard/basic_functions.c b/ext/standard/basic_functions.c
index 1ea19066..3ac986f3 100644
--- a/ext/standard/basic_functions.c
+++ b/ext/standard/basic_functions.c
@@ -3885,7 +3885,7 @@ PHP_NAMED_FUNCTION(php_inet_pton)
int address_len;
char buffer[17];
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &address, &address_len) == FAILURE) {
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &address, &address_len) == FAILURE) {
RETURN_FALSE;
}
@@ -3925,7 +3925,7 @@ PHP_FUNCTION(ip2long)
unsigned long int ip;
#endif
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &addr, &addr_len) == FAILURE) {
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &addr, &addr_len) == FAILURE) {
return;
}
@@ -5596,7 +5596,7 @@ PHP_FUNCTION(getservbyname)
int name_len, proto_len;
struct servent *serv;
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &name, &name_len, &proto, &proto_len) == FAILURE) {
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pp", &name, &name_len, &proto, &proto_len) == FAILURE) {
return;
}
@@ -5630,7 +5630,7 @@ PHP_FUNCTION(getservbyport)
long port;
struct servent *serv;
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ls", &port, &proto, &proto_len) == FAILURE) {
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lp", &port, &proto, &proto_len) == FAILURE) {
return;
}
@@ -5654,7 +5654,7 @@ PHP_FUNCTION(getprotobyname)
int name_len;
struct protoent *ent;
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name, &name_len) == FAILURE) {
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &name, &name_len) == FAILURE) {
return;
}
diff --git a/ext/standard/dns.c b/ext/standard/dns.c
index 2b2797e4..2201432e 100644
--- a/ext/standard/dns.c
+++ b/ext/standard/dns.c
@@ -368,7 +368,7 @@ PHP_FUNCTION(dns_check_record)
struct __res_state *handle = &state;
#endif
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|s", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) {
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|s", &hostname, &hostname_len, &rectype, &rectype_len) == FAILURE) {
return;
}
@@ -454,6 +454,10 @@ static u_char *php_parserr(u_char *cp, u_char *end, querybuf *answer, int type_t
GETLONG(ttl, cp);
GETSHORT(dlen, cp);
CHECKCP(dlen);
+ if (dlen == 0) {
+ /* No data in the response - nothing to do */
+ return NULL;
+ }
if (type_to_fetch != T_ANY && type != type_to_fetch) {
cp += dlen;
return cp;
@@ -784,7 +788,7 @@ PHP_FUNCTION(dns_get_record)
int type, first_query = 1, store_results = 1;
zend_bool raw = 0;
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz!z!b",
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|lz!z!b",
&hostname, &hostname_len, &type_param, &authns, &addtl, &raw) == FAILURE) {
return;
}
@@ -1012,7 +1016,7 @@ PHP_FUNCTION(dns_get_mx)
struct __res_state *handle = &state;
#endif
- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|z", &hostname, &hostname_len, &mx_list, &weight_list) == FAILURE) {
+ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "pz|z", &hostname, &hostname_len, &mx_list, &weight_list) == FAILURE) {
return;
}
diff --git a/ext/standard/filters.c b/ext/standard/filters.c
index 2a256a30..a0a6dfaf 100644
--- a/ext/standard/filters.c
+++ b/ext/standard/filters.c
@@ -372,7 +372,7 @@ static php_conv_err_t php_conv_base64_encode_ctor(php_conv_base64_encode *inst,
inst->line_ccnt = line_len;
inst->line_len = line_len;
if (lbchars != NULL) {
- inst->lbchars = (lbchars_dup ? pestrdup(lbchars, persistent) : lbchars);
+ inst->lbchars = (lbchars_dup ? pestrndup(lbchars, lbchars_len, persistent) : lbchars);
inst->lbchars_len = lbchars_len;
} else {
inst->lbchars = NULL;
@@ -980,7 +980,7 @@ static php_conv_err_t php_conv_qprint_encode_ctor(php_conv_qprint_encode *inst,
inst->line_ccnt = line_len;
inst->line_len = line_len;
if (lbchars != NULL) {
- inst->lbchars = (lbchars_dup ? pestrdup(lbchars, persistent) : lbchars);
+ inst->lbchars = (lbchars_dup ? pestrndup(lbchars, lbchars_len, persistent) : lbchars);
inst->lbchars_len = lbchars_len;
} else {
inst->lbchars = NULL;
@@ -1193,7 +1193,7 @@ static php_conv_err_t php_conv_qprint_decode_ctor(php_conv_qprint_decode *inst,
inst->next_char = 0;
inst->lb_ptr = inst->lb_cnt = 0;
if (lbchars != NULL) {
- inst->lbchars = (lbchars_dup ? pestrdup(lbchars, persistent) : lbchars);
+ inst->lbchars = (lbchars_dup ? pestrndup(lbchars, lbchars_len, persistent) : lbchars);
inst->lbchars_len = lbchars_len;
} else {
inst->lbchars = NULL;
diff --git a/ext/standard/fsock.c b/ext/standard/fsock.c
index fbeaf57c..be96b7ac 100644
--- a/ext/standard/fsock.c
+++ b/ext/standard/fsock.c
@@ -27,6 +27,28 @@
#include "php_network.h"
#include "file.h"
+static size_t php_fsockopen_format_host_port(char **message, const char *prefix, size_t prefix_len,
+ const char *host, size_t host_len, long port)
+{
+ char portbuf[32];
+ int portlen = snprintf(portbuf, sizeof(portbuf), ":%ld", port);
+ size_t total_len = prefix_len + host_len + portlen;
+
+ char *result = emalloc(total_len + 1);
+
+ if (prefix_len > 0) {
+ memcpy(result, prefix, prefix_len);
+ }
+ memcpy(result + prefix_len, host, host_len);
+ memcpy(result + prefix_len + host_len, portbuf, portlen);
+
+ result[total_len] = '\0';
+
+ *message = result;
+
+ return total_len;
+}
+
/* {{{ php_fsockopen() */
static void php_fsockopen_stream(INTERNAL_FUNCTION_PARAMETERS, int persistent)
@@ -52,11 +74,12 @@ static void php_fsockopen_stream(INTERNAL_FUNCTION_PARAMETERS, int persistent)
}
if (persistent) {
- spprintf(&hashkey, 0, "pfsockopen__%s:%ld", host, port);
+ php_fsockopen_format_host_port(&hashkey, "pfsockopen__", strlen("pfsockopen__"), host,
+ host_len, port);
}
if (port > 0) {
- hostname_len = spprintf(&hostname, 0, "%s:%ld", host, port);
+ hostname_len = php_fsockopen_format_host_port(&hostname, "", 0, host, host_len, port);
} else {
hostname_len = host_len;
hostname = host;
diff --git a/ext/standard/http_fopen_wrapper.c b/ext/standard/http_fopen_wrapper.c
index 157ffd71..5a08f49d 100644
--- a/ext/standard/http_fopen_wrapper.c
+++ b/ext/standard/http_fopen_wrapper.c
@@ -72,41 +72,303 @@
#include "php_fopen_wrappers.h"
-#define HTTP_HEADER_BLOCK_SIZE 1024
-#define PHP_URL_REDIRECT_MAX 20
-#define HTTP_HEADER_USER_AGENT 1
-#define HTTP_HEADER_HOST 2
-#define HTTP_HEADER_AUTH 4
-#define HTTP_HEADER_FROM 8
-#define HTTP_HEADER_CONTENT_LENGTH 16
-#define HTTP_HEADER_TYPE 32
-#define HTTP_HEADER_CONNECTION 64
+#define HTTP_HEADER_BLOCK_SIZE 1024
+#define HTTP_HEADER_MAX_LOCATION_SIZE 8182 /* 8192 - 10 (size of "Location: ") */
+#define PHP_URL_REDIRECT_MAX 20
+#define HTTP_HEADER_USER_AGENT 1
+#define HTTP_HEADER_HOST 2
+#define HTTP_HEADER_AUTH 4
+#define HTTP_HEADER_FROM 8
+#define HTTP_HEADER_CONTENT_LENGTH 16
+#define HTTP_HEADER_TYPE 32
+#define HTTP_HEADER_CONNECTION 64
#define HTTP_WRAPPER_HEADER_INIT 1
#define HTTP_WRAPPER_REDIRECTED 2
+#define HTTP_WRAPPER_KEEP_METHOD 4
+#define HTTP_WRAPPER_STRIP_AUTH 8
+static char *next_header_line(char *line)
+{
+ while (*line != '\0' && *line != '\r' && *line != '\n') {
+ line++;
+ }
+ if (*line == '\r') {
+ line++;
+ }
+ if (*line == '\n') {
+ line++;
+ }
+
+ return line;
+}
+
+/* Removes every line whose header name matches, along with the folded
+ * continuation lines carrying the rest of its value. Neither a repeated header
+ * nor an occurrence of the name inside another header's value may leave the real
+ * header behind, as that would defeat HTTP_WRAPPER_STRIP_AUTH. */
static inline void strip_header(char *header_bag, char *lc_header_bag,
const char *lc_header_name)
{
- char *lc_header_start = strstr(lc_header_bag, lc_header_name);
- char *header_start = header_bag + (lc_header_start - lc_header_bag);
+ size_t name_len = strlen(lc_header_name);
+ char *lc_line = lc_header_bag;
- if (lc_header_start
- && (lc_header_start == lc_header_bag || *(lc_header_start-1) == '\n')
- ) {
- char *lc_eol = strchr(lc_header_start, '\n');
- char *eol = header_start + (lc_eol - lc_header_start);
+ while (*lc_line != '\0') {
+ const char *lc_colon;
+ char *lc_next, *line;
+ size_t tail_len;
- if (lc_eol) {
- size_t eollen = strlen(lc_eol);
+ if (strncmp(lc_line, lc_header_name, name_len) != 0) {
+ lc_line = next_header_line(lc_line);
+ continue;
+ }
- memmove(lc_header_start, lc_eol+1, eollen);
- memmove(header_start, eol+1, eollen);
- } else {
- *lc_header_start = '\0';
- *header_start = '\0';
+ /* the whitespace RFC 7230 forbids before the colon is tolerated by some
+ * servers, so it must not hide the header from us either */
+ lc_colon = lc_line + name_len;
+ while (*lc_colon == ' ' || *lc_colon == '\t') {
+ lc_colon++;
+ }
+
+ if (*lc_colon != ':') {
+ lc_line = next_header_line(lc_line);
+ continue;
+ }
+
+ lc_next = next_header_line(lc_line);
+ while (*lc_next == ' ' || *lc_next == '\t') {
+ lc_next = next_header_line(lc_next);
}
+
+ if (*lc_next == '\0') {
+ /* drop the preceding line break too, or the one appended after the bag
+ * would close the header block early */
+ while (lc_line > lc_header_bag
+ && (*(lc_line - 1) == '\r' || *(lc_line - 1) == '\n')) {
+ --lc_line;
+ }
+ }
+
+ tail_len = strlen(lc_next) + 1;
+ line = header_bag + (lc_line - lc_header_bag);
+
+ memmove(line, header_bag + (lc_next - lc_header_bag), tail_len);
+ memmove(lc_line, lc_next, tail_len);
+ }
+}
+
+static zend_bool check_has_header(const char *headers, const char *header) {
+ const char *s = headers;
+ while ((s = strstr(s, header))) {
+ if (s == headers || (*(s-1) == '\n' && *(s-2) == '\r')) {
+ return 1;
+ }
+ s++;
+ }
+ return 0;
+}
+
+typedef struct _php_stream_http_response_header_info {
+ php_stream_filter *transfer_encoding;
+ size_t file_size;
+ int error;
+ int follow_location;
+ char *location;
+ size_t location_len;
+} php_stream_http_response_header_info;
+
+static void php_stream_http_response_header_info_init(
+ php_stream_http_response_header_info *header_info)
+{
+ memset(header_info, 0, sizeof(php_stream_http_response_header_info));
+ header_info->follow_location = 1;
+}
+
+/* Trim white spaces from response header line and update its length */
+static zend_bool php_stream_http_response_header_trim(char *http_header_line,
+ size_t *http_header_line_length)
+{
+ char *http_header_line_end = http_header_line + *http_header_line_length - 1;
+ while (http_header_line_end >= http_header_line &&
+ (*http_header_line_end == '\n' || *http_header_line_end == '\r')) {
+ http_header_line_end--;
}
+
+ /* The primary definition of an HTTP header in RFC 7230 states:
+ * > Each header field consists of a case-insensitive field name followed
+ * > by a colon (":"), optional leading whitespace, the field value, and
+ * > optional trailing whitespace. */
+
+ /* Strip trailing whitespace */
+ zend_bool space_trim = (*http_header_line_end == ' ' || *http_header_line_end == '\t');
+ if (space_trim) {
+ do {
+ http_header_line_end--;
+ } while (http_header_line_end >= http_header_line &&
+ (*http_header_line_end == ' ' || *http_header_line_end == '\t'));
+ }
+ http_header_line_end++;
+ *http_header_line_end = '\0';
+ *http_header_line_length = http_header_line_end - http_header_line;
+
+ return space_trim;
+}
+
+/* Process folding headers of the current line and if there are none, parse last full response
+ * header line. It returns NULL if the last header is finished, otherwise it returns updated
+ * last header line. */
+static char *php_stream_http_response_headers_parse(php_stream_wrapper *wrapper,
+ php_stream *stream, php_stream_context *context, int options,
+ char **last_header_line, size_t *last_header_line_length,
+ char *header_line, size_t *header_line_length, int response_code,
+ zval *response_header, php_stream_http_response_header_info *header_info)
+{
+ char *last_header_line_end = *last_header_line + *last_header_line_length - 1;
+
+ /* Process non empty header line. */
+ if (header_line && (*header_line != '\n' && *header_line != '\r')) {
+ /* Removing trailing white spaces. */
+ if (php_stream_http_response_header_trim(header_line, header_line_length) &&
+ *header_line_length == 0) {
+ /* Only spaces so treat as an empty folding header. */
+ return *last_header_line;
+ }
+
+ /* Process folding headers if starting with a space or a tab. */
+ if (header_line && (*header_line == ' ' || *header_line == '\t')) {
+ char *http_folded_header_line = header_line;
+ size_t http_folded_header_line_length = *header_line_length;
+ /* Remove the leading white spaces. */
+ while (*http_folded_header_line == ' ' || *http_folded_header_line == '\t') {
+ http_folded_header_line++;
+ http_folded_header_line_length--;
+ }
+ /* It has to have some characters because it would get returned after the call
+ * php_stream_http_response_header_trim above. */
+ ZEND_ASSERT(http_folded_header_line_length > 0);
+ /* Concatenate last header line, space and current header line. */
+ size_t len = *last_header_line_length + 1 + http_folded_header_line_length;
+ char *extended_header = emalloc(len + 1);
+ strncpy(extended_header, *last_header_line, *last_header_line_length);
+ extended_header[*last_header_line_length] = ' ';
+ strncpy(extended_header + *last_header_line_length + 1, http_folded_header_line, http_folded_header_line_length);
+ extended_header[len] = '\0';
+ efree(*last_header_line);
+ *last_header_line = extended_header;
+ *last_header_line_length = len;
+ /* Return new header line. */
+ return *last_header_line;
+ }
+ }
+
+ /* Find header separator position. */
+ char *last_header_value = memchr(*last_header_line, ':', *last_header_line_length);
+ if (last_header_value) {
+ /* Verify there is no space in header name */
+ char *last_header_name = *last_header_line + 1;
+ while (last_header_name < last_header_value) {
+ if (*last_header_name == ' ' || *last_header_name == '\t') {
+ header_info->error = 1;
+ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC,
+ "HTTP invalid response format (space in header name)!");
+ efree(*last_header_line);
+ return NULL;
+ }
+ ++last_header_name;
+ }
+
+ last_header_value++; /* Skip ':'. */
+
+ /* Strip leading whitespace. */
+ while (last_header_value < last_header_line_end
+ && (*last_header_value == ' ' || *last_header_value == '\t')) {
+ last_header_value++;
+ }
+ } else {
+ /* There is no colon which means invalid response so error. */
+ header_info->error = 1;
+ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC,
+ "HTTP invalid response format (no colon in header line)!");
+ efree(*last_header_line);
+ return NULL;
+ }
+
+ zend_bool store_header = 1;
+ zval **tmpzval = NULL;
+
+ if (!strncasecmp(*last_header_line, "Location:", sizeof("Location:")-1)) {
+ /* Check if the location should be followed. */
+ if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) {
+ SEPARATE_ZVAL(tmpzval);
+ convert_to_long_ex(tmpzval);
+ header_info->follow_location = Z_LVAL_PP(tmpzval);
+ } else if (!((response_code >= 300 && response_code < 304)
+ || 307 == response_code || 308 == response_code)) {
+ /* The redirection should not be automatic if follow_location is not set and
+ * response_code not in (300, 301, 302, 303 and 307)
+ * see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1
+ * RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */
+ header_info->follow_location = 0;
+ }
+ size_t last_header_value_len = strlen(last_header_value);
+ if (last_header_value_len > HTTP_HEADER_MAX_LOCATION_SIZE) {
+ header_info->error = 1;
+ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC,
+ "HTTP Location header size is over the limit of %d bytes",
+ HTTP_HEADER_MAX_LOCATION_SIZE);
+ efree(*last_header_line);
+ return NULL;
+ }
+ if (header_info->location_len == 0) {
+ header_info->location = emalloc(last_header_value_len + 1);
+ } else if (header_info->location_len <= last_header_value_len) {
+ header_info->location = erealloc(header_info->location, last_header_value_len + 1);
+ }
+ header_info->location_len = last_header_value_len;
+ memcpy(header_info->location, last_header_value, last_header_value_len + 1);
+ } else if (!strncasecmp(*last_header_line, "Content-Type:", sizeof("Content-Type:")-1)) {
+ php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, last_header_value, 0);
+ } else if (!strncasecmp(*last_header_line, "Content-Length:", sizeof("Content-Length:")-1)) {
+ header_info->file_size = atoi(last_header_value);
+ php_stream_notify_file_size(context, header_info->file_size, *last_header_line, 0);
+ } else if (
+ !strncasecmp(*last_header_line, "Transfer-Encoding:", sizeof("Transfer-Encoding:")-1)
+ && !strncasecmp(last_header_value, "Chunked", sizeof("Chunked")-1)
+ ) {
+ /* Create filter to decode response body. */
+ if (!(options & STREAM_ONLY_GET_HEADERS)) {
+ long decode = 1;
+
+ if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) {
+ SEPARATE_ZVAL(tmpzval);
+ convert_to_boolean(*tmpzval);
+ decode = Z_LVAL_PP(tmpzval);
+ }
+ if (decode) {
+ if (header_info->transfer_encoding != NULL) {
+ /* Prevent a memory leak in case there are more transfer-encoding headers. */
+ php_stream_filter_free(header_info->transfer_encoding TSRMLS_CC);
+ }
+ header_info->transfer_encoding = php_stream_filter_create(
+ "dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC);
+ if (header_info->transfer_encoding != NULL) {
+ /* Do not store transfer-encoding header. */
+ store_header = 0;
+ }
+ }
+ }
+ }
+
+ if (store_header) {
+ zval *http_header;
+ MAKE_STD_ZVAL(http_header);
+ ZVAL_STRINGL(http_header, *last_header_line, *last_header_line_length, 1);
+ zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL);
+ } else {
+ efree(*last_header_line);
+ }
+
+ return NULL;
}
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper,
@@ -123,12 +385,13 @@ php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper,
zval **ua_zval = NULL, **tmpzval = NULL, *ssl_proxy_peer_name = NULL;
int scratch_len = 0;
int body = 0;
- char location[HTTP_HEADER_BLOCK_SIZE];
zval *response_header = NULL;
int reqok = 0;
char *http_header_line = NULL;
+ char *last_header_line = NULL;
+ php_stream_http_response_header_info header_info;
char tmp_line[128];
- size_t chunk_size = 0, file_size = 0;
+ size_t chunk_size = 0;
int eol_detect = 0;
char *transport_string, *errstr = NULL;
int transport_len, have_header = 0, request_fulluri = 0, ignore_errors = 0;
@@ -138,9 +401,8 @@ php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper,
char *user_headers = NULL;
int header_init = ((flags & HTTP_WRAPPER_HEADER_INIT) != 0);
int redirected = ((flags & HTTP_WRAPPER_REDIRECTED) != 0);
- int follow_location = 1;
- php_stream_filter *transfer_encoding = NULL;
- int response_code;
+ int redirect_keep_method = ((flags & HTTP_WRAPPER_KEEP_METHOD) != 0);
+ int response_code = 0;
tmp_line[0] = '\0';
@@ -349,6 +611,8 @@ finish:
}
}
+ php_stream_http_response_header_info_init(&header_info);
+
if (stream == NULL)
goto out;
@@ -374,8 +638,8 @@ finish:
if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) {
if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
/* As per the RFC, automatically redirected requests MUST NOT use other methods than
- * GET and HEAD unless it can be confirmed by the user */
- if (!redirected
+ * GET and HEAD unless it can be confirmed by the user. */
+ if (!redirected || redirect_keep_method
|| (Z_STRLEN_PP(tmpzval) == 3 && memcmp("GET", Z_STRVAL_PP(tmpzval), 3) == 0)
|| (Z_STRLEN_PP(tmpzval) == 4 && memcmp("HEAD",Z_STRVAL_PP(tmpzval), 4) == 0)
) {
@@ -467,51 +731,52 @@ finish:
/* Make lowercase for easy comparison against 'standard' headers */
php_strtolower(tmp, strlen(tmp));
- if (!header_init) {
+ if (!header_init && !redirect_keep_method) {
/* strip POST headers on redirect */
- strip_header(user_headers, tmp, "content-length:");
- strip_header(user_headers, tmp, "content-type:");
+ strip_header(user_headers, tmp, "content-length");
+ strip_header(user_headers, tmp, "content-type");
}
- if ((s = strstr(tmp, "user-agent:")) &&
- (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
- *(s-1) == '\t' || *(s-1) == ' ')) {
- have_header |= HTTP_HEADER_USER_AGENT;
+ if (flags & HTTP_WRAPPER_STRIP_AUTH) {
+ strip_header(user_headers, tmp, "authorization");
+ strip_header(user_headers, tmp, "cookie");
+ if (!use_proxy) {
+ strip_header(user_headers, tmp, "proxy-authorization");
+ }
}
- if ((s = strstr(tmp, "host:")) &&
- (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
- *(s-1) == '\t' || *(s-1) == ' ')) {
- have_header |= HTTP_HEADER_HOST;
+
+ if (*user_headers == '\0') {
+ /* everything got stripped, keeping the empty bag would append a
+ * stray CRLF and end the header block early */
+ efree(user_headers);
+ user_headers = NULL;
}
- if ((s = strstr(tmp, "from:")) &&
- (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
- *(s-1) == '\t' || *(s-1) == ' ')) {
- have_header |= HTTP_HEADER_FROM;
- }
- if ((s = strstr(tmp, "authorization:")) &&
- (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
- *(s-1) == '\t' || *(s-1) == ' ')) {
- have_header |= HTTP_HEADER_AUTH;
+
+ if (check_has_header(tmp, "user-agent:")) {
+ have_header |= HTTP_HEADER_USER_AGENT;
+ }
+ if (check_has_header(tmp, "host:")) {
+ have_header |= HTTP_HEADER_HOST;
}
- if ((s = strstr(tmp, "content-length:")) &&
- (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
- *(s-1) == '\t' || *(s-1) == ' ')) {
- have_header |= HTTP_HEADER_CONTENT_LENGTH;
+ if (check_has_header(tmp, "from:")) {
+ have_header |= HTTP_HEADER_FROM;
}
- if ((s = strstr(tmp, "content-type:")) &&
- (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
- *(s-1) == '\t' || *(s-1) == ' ')) {
- have_header |= HTTP_HEADER_TYPE;
+ if (check_has_header(tmp, "authorization:")) {
+ have_header |= HTTP_HEADER_AUTH;
}
- if ((s = strstr(tmp, "connection:")) &&
- (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
- *(s-1) == '\t' || *(s-1) == ' ')) {
- have_header |= HTTP_HEADER_CONNECTION;
+ if (check_has_header(tmp, "content-length:")) {
+ have_header |= HTTP_HEADER_CONTENT_LENGTH;
}
+ if (check_has_header(tmp, "content-type:")) {
+ have_header |= HTTP_HEADER_TYPE;
+ }
+ if (check_has_header(tmp, "connection:")) {
+ have_header |= HTTP_HEADER_CONNECTION;
+ }
+
/* remove Proxy-Authorization header */
if (use_proxy && use_ssl && (s = strstr(tmp, "proxy-authorization:")) &&
- (s == tmp || *(s-1) == '\r' || *(s-1) == '\n' ||
- *(s-1) == '\t' || *(s-1) == ' ')) {
+ (s == tmp || *(s-1) == '\n')) {
char *p = s + sizeof("proxy-authorization:") - 1;
while (s > tmp && (*(s-1) == ' ' || *(s-1) == '\t')) s--;
@@ -627,7 +892,7 @@ finish:
* see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first.
*/
if (
- header_init &&
+ (header_init || redirect_keep_method) &&
context &&
!(have_header & HTTP_HEADER_CONTENT_LENGTH) &&
php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
@@ -644,7 +909,7 @@ finish:
}
/* Request content, such as for POST requests */
- if (header_init && context &&
+ if ((header_init || redirect_keep_method) && context &&
php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) {
@@ -662,8 +927,6 @@ finish:
php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
}
- location[0] = '\0';
-
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
@@ -758,108 +1021,111 @@ finish:
}
/* read past HTTP headers */
-
- http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE);
-
+ size_t last_header_line_len = 0;
while (!body && !php_stream_eof(stream)) {
size_t http_header_line_length;
- if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') {
- char *e = http_header_line + http_header_line_length - 1;
- if (*e != '\n') {
- do { /* partial header */
- if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) == NULL) {
- php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Failed to read HTTP headers");
+
+ if (http_header_line != NULL) {
+ efree(http_header_line);
+ }
+ if ((http_header_line = php_stream_get_line(stream, NULL, 0, &http_header_line_length))) {
+ zend_bool last_line;
+ if (*http_header_line == '\r') {
+ if (http_header_line[1] != '\n') {
+ php_stream_close(stream);
+ stream = NULL;
+ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC,
+ "HTTP invalid header name (cannot start with CR character)!");
+ goto out;
+ }
+ last_line = 1;
+ } else if (*http_header_line == '\n') {
+ last_line = 1;
+ } else {
+ last_line = 0;
+ }
+
+ if (last_header_line != NULL) {
+ /* Parse last header line. */
+ last_header_line = php_stream_http_response_headers_parse(wrapper, stream,
+ context, options, &last_header_line, &last_header_line_len,
+ http_header_line, &http_header_line_length,
+ response_code, response_header, &header_info);
+ if (EXPECTED(last_header_line == NULL)) {
+ if (UNEXPECTED(header_info.error)) {
+ php_stream_close(stream);
+ stream = NULL;
goto out;
}
- e = http_header_line + http_header_line_length - 1;
- } while (*e != '\n');
- continue;
- }
- while (*e == '\n' || *e == '\r') {
- e--;
- }
- http_header_line_length = e - http_header_line + 1;
- http_header_line[http_header_line_length] = '\0';
-
- if (!strncasecmp(http_header_line, "Location: ", 10)) {
- if (context && php_stream_context_get_option(context, "http", "follow_location", &tmpzval) == SUCCESS) {
- SEPARATE_ZVAL(tmpzval);
- convert_to_long_ex(tmpzval);
- follow_location = Z_LVAL_PP(tmpzval);
- } else if (!(response_code >= 300 && response_code < 304 || 307 == response_code || 308 == response_code)) {
- /* we shouldn't redirect automatically
- if follow_location isn't set and response_code not in (300, 301, 302, 303 and 307)
- see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1
- RFC 7238 defines 308: http://tools.ietf.org/html/rfc7238 */
- follow_location = 0;
+ } else {
+ /* Folding header present so continue. */
+ continue;
}
- strlcpy(location, http_header_line + 10, sizeof(location));
- } else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) {
- php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0);
- } else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) {
- file_size = atoi(http_header_line + 16);
- php_stream_notify_file_size(context, file_size, http_header_line, 0);
- } else if (!strncasecmp(http_header_line, "Transfer-Encoding: chunked", sizeof("Transfer-Encoding: chunked"))) {
-
- /* create filter to decode response body */
- if (!(options & STREAM_ONLY_GET_HEADERS)) {
- long decode = 1;
-
- if (context && php_stream_context_get_option(context, "http", "auto_decode", &tmpzval) == SUCCESS) {
- SEPARATE_ZVAL(tmpzval);
- convert_to_boolean(*tmpzval);
- decode = Z_LVAL_PP(tmpzval);
- }
- if (decode) {
- transfer_encoding = php_stream_filter_create("dechunk", NULL, php_stream_is_persistent(stream) TSRMLS_CC);
- if (transfer_encoding) {
- /* don't store transfer-encodeing header */
- continue;
- }
- }
+ } else if (!last_line) {
+ /* The first line cannot start with spaces. */
+ if (*http_header_line == ' ' || *http_header_line == '\t') {
+ php_stream_close(stream);
+ stream = NULL;
+ php_stream_wrapper_log_error(wrapper, options TSRMLS_CC,
+ "HTTP invalid response format (folding header at the start)!");
+ goto out;
}
+ /* Trim the first line if it is not the last line. */
+ php_stream_http_response_header_trim(http_header_line, &http_header_line_length);
}
-
- if (http_header_line[0] == '\0') {
- body = 1;
- } else {
- zval *http_header;
-
- MAKE_STD_ZVAL(http_header);
-
- ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1);
-
- zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL);
+ if (last_line) {
+ /* For the last line the last header line must be NULL. */
+ assert(last_header_line == NULL);
+ break;
}
+ /* Save current line as the last line so it gets parsed in the next round. */
+ last_header_line = emalloc(http_header_line_length + 1);
+ strncpy(last_header_line, http_header_line, http_header_line_length);
+ last_header_line[http_header_line_length] = '\0';
+ last_header_line_len = http_header_line_length;
} else {
break;
}
}
- if (!reqok || (location[0] != '\0' && follow_location)) {
- if (!follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) {
+ /* If the stream was closed early, we still want to process the last line to keep BC. */
+ if (last_header_line != NULL) {
+ last_header_line = php_stream_http_response_headers_parse(wrapper, stream, context,
+ options, &last_header_line, &last_header_line_len,
+ NULL, NULL, response_code, response_header, &header_info);
+ }
+
+ if (!reqok || (header_info.location != NULL && header_info.follow_location)) {
+ if (!header_info.follow_location || (((options & STREAM_ONLY_GET_HEADERS) || ignore_errors) && redirect_max <= 1)) {
goto out;
}
- if (location[0] != '\0')
- php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);
+ if (header_info.location != NULL)
+ php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, header_info.location, 0);
php_stream_close(stream);
stream = NULL;
- if (location[0] != '\0') {
-
- char new_path[HTTP_HEADER_BLOCK_SIZE];
- char loc_path[HTTP_HEADER_BLOCK_SIZE];
+ if (header_info.transfer_encoding) {
+ php_stream_filter_free(header_info.transfer_encoding TSRMLS_CC);
+ header_info.transfer_encoding = NULL;
+ }
- *new_path='\0';
- if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) &&
- strncasecmp(location, "https://", sizeof("https://")-1) &&
- strncasecmp(location, "ftp://", sizeof("ftp://")-1) &&
- strncasecmp(location, "ftps://", sizeof("ftps://")-1)))
+ if (header_info.location != NULL) {
+ char *new_path = NULL;
+ int new_flags, default_port;
+ php_url *new_resource;
+ zend_bool same_origin;
+
+ if (header_info.location_len < 8 ||
+ (strncasecmp(header_info.location, "http://", sizeof("http://")-1) &&
+ strncasecmp(header_info.location, "https://", sizeof("https://")-1) &&
+ strncasecmp(header_info.location, "ftp://", sizeof("ftp://")-1) &&
+ strncasecmp(header_info.location, "ftps://", sizeof("ftps://")-1)))
{
- if (*location != '/') {
- if (*(location+1) != '\0' && resource->path) {
+ char *loc_path = NULL;
+ if (*header_info.location != '/') {
+ if (header_info.location_len > 1 && resource->path) {
char *s = strrchr(resource->path, '/');
if (!s) {
s = resource->path;
@@ -872,32 +1138,47 @@ finish:
}
s[1] = '\0';
if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') {
- snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location);
+ spprintf(&loc_path, 0, "%s%s", resource->path, header_info.location);
} else {
- snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location);
+ spprintf(&loc_path, 0, "%s/%s", resource->path, header_info.location);
}
} else {
- snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location);
+ spprintf(&loc_path, 0, "/%s", header_info.location);
}
} else {
- strlcpy(loc_path, location, sizeof(loc_path));
+ loc_path = header_info.location;
+ header_info.location = NULL;
}
if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {
- snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path);
+ spprintf(&new_path, 0, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path);
} else {
- snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path);
+ spprintf(&new_path, 0, "%s://%s%s", resource->scheme, resource->host, loc_path);
}
+ efree(loc_path);
} else {
- strlcpy(new_path, location, sizeof(new_path));
+ new_path = header_info.location;
+ header_info.location = NULL;
}
- php_url_free(resource);
/* check for invalid redirection URLs */
- if ((resource = php_url_parse(new_path)) == NULL) {
+ new_resource = php_url_parse(new_path);
+ if (new_resource == NULL) {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path);
+ efree(new_path);
goto out;
}
+ default_port = use_ssl ? 443 : 80;
+ same_origin = resource->scheme && new_resource->scheme
+ && resource->host && new_resource->host
+ && strcasecmp(resource->scheme, new_resource->scheme) == 0
+ && strcasecmp(resource->host, new_resource->host) == 0
+ && (resource->port ? resource->port : default_port)
+ == (new_resource->port ? new_resource->port : default_port);
+
+ php_url_free(resource);
+ resource = new_resource;
+
#define CHECK_FOR_CNTRL_CHARS(val) { \
if (val) { \
unsigned char *s, *e; \
@@ -907,6 +1188,7 @@ finish:
while (s < e) { \
if (iscntrl(*s)) { \
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path); \
+ efree(new_path); \
goto out; \
} \
s++; \
@@ -919,7 +1201,18 @@ finish:
CHECK_FOR_CNTRL_CHARS(resource->pass)
CHECK_FOR_CNTRL_CHARS(resource->path)
}
- stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, HTTP_WRAPPER_REDIRECTED STREAMS_CC TSRMLS_CC);
+ new_flags = HTTP_WRAPPER_REDIRECTED | (flags & HTTP_WRAPPER_STRIP_AUTH);
+ if (!same_origin) {
+ new_flags |= HTTP_WRAPPER_STRIP_AUTH;
+ }
+ if (response_code == 307 || response_code == 308) {
+ /* RFC 7538 specifies that status code 308 does not allow changing the request method from POST to GET.
+ * RFC 7231 does the same for status code 307.
+ * To keep consistency between POST and PATCH requests, we'll also not change the request method from PATCH to GET, even though it's allowed it's not mandated by the RFC. */
+ new_flags |= HTTP_WRAPPER_KEEP_METHOD;
+ }
+ stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, new_flags STREAMS_CC TSRMLS_CC);
+ efree(new_path);
} else {
php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed! %s", tmp_line);
}
@@ -933,6 +1226,10 @@ out:
efree(http_header_line);
}
+ if (header_info.location != NULL) {
+ efree(header_info.location);
+ }
+
if (scratch) {
efree(scratch);
}
@@ -949,7 +1246,7 @@ out:
Z_DELREF_P(response_header);
}
}
- php_stream_notify_progress_init(context, 0, file_size);
+ php_stream_notify_progress_init(context, 0, header_info.file_size);
/* Restore original chunk size now that we're done with headers */
if (options & STREAM_WILL_CAST)
@@ -965,16 +1262,13 @@ out:
/* restore mode */
strlcpy(stream->mode, mode, sizeof(stream->mode));
- if (transfer_encoding) {
- php_stream_filter_append(&stream->readfilters, transfer_encoding);
+ if (header_info.transfer_encoding) {
+ php_stream_filter_append(&stream->readfilters, header_info.transfer_encoding TSRMLS_CC);
}
} else {
if(response_header) {
Z_DELREF_P(response_header);
}
- if (transfer_encoding) {
- php_stream_filter_free(transfer_encoding TSRMLS_CC);
- }
}
return stream;
diff --git a/ext/standard/image.c b/ext/standard/image.c
index db64b3a4..f8858ef7 100644
--- a/ext/standard/image.c
+++ b/ext/standard/image.c
@@ -423,6 +423,21 @@ static int php_skip_variable(php_stream * stream TSRMLS_DC)
}
/* }}} */
+static size_t php_read_stream_all_chunks(php_stream *stream, char *buffer, size_t length TSRMLS_DC)
+{
+ size_t read_total = 0;
+ do {
+ size_t read_now = php_stream_read(stream, buffer, length - read_total);
+ read_total += read_now;
+ if (read_now < stream->chunk_size && read_total != length) {
+ return 0;
+ }
+ buffer += read_now;
+ } while (read_total < length);
+
+ return read_total;
+}
+
/* {{{ php_read_APP
*/
static int php_read_APP(php_stream * stream, unsigned int marker, zval *info TSRMLS_DC)
@@ -440,7 +455,7 @@ static int php_read_APP(php_stream * stream, unsigned int marker, zval *info TSR
buffer = emalloc(length);
- if (php_stream_read(stream, buffer, (long) length) <= 0) {
+ if (php_read_stream_all_chunks(stream, (char *) buffer, length TSRMLS_CC) != length) {
efree(buffer);
return 0;
}
diff --git a/ext/standard/tests/filters/ghsa-88hq-2827-7pg6.phpt b/ext/standard/tests/filters/ghsa-88hq-2827-7pg6.phpt
new file mode 100644
index 00000000..84a85dae
--- /dev/null
+++ b/ext/standard/tests/filters/ghsa-88hq-2827-7pg6.phpt
@@ -0,0 +1,27 @@
+--TEST--
+GHSA-88hq-2827-7pg6: OOB read in convert stream filters when line-break-chars contains NUL
+--FILE--
+ 4, "line-break-chars" => "\0X"];
+$fp = fopen("php://temp", "r+");
+fwrite($fp, str_repeat("A", 6));
+rewind($fp);
+stream_filter_append($fp, "convert.base64-encode", STREAM_FILTER_READ, $opts);
+$out = stream_get_contents($fp);
+fclose($fp);
+
+// base64("AAAAAA") = "QUFBQUFB" (8 chars)
+// With line-length=4: "QUFB" + "\0X" + "QUFB"
+// Hex: 5155464200585155 4642
+echo bin2hex($out), "\n";
+
+echo "Done\n";
+
+?>
+--EXPECT--
+51554642005851554642
+Done
diff --git a/ext/standard/tests/general_functions/getservbyname_variation1.phpt b/ext/standard/tests/general_functions/getservbyname_variation1.phpt
index 7dd01aab..ac7d9fe0 100644
--- a/ext/standard/tests/general_functions/getservbyname_variation1.phpt
+++ b/ext/standard/tests/general_functions/getservbyname_variation1.phpt
@@ -27,14 +27,14 @@ foreach ( $variation_array as $var ) {
--EXPECTF--
*** Test substituting argument 1 with array values ***
-Warning: getservbyname() expects parameter 1 to be string, array given in %s on line %d
+Warning: getservbyname() expects parameter 1 to be a valid path, array given in %s on line %d
NULL
-Warning: getservbyname() expects parameter 1 to be string, array given in %s on line %d
+Warning: getservbyname() expects parameter 1 to be a valid path, array given in %s on line %d
NULL
-Warning: getservbyname() expects parameter 1 to be string, array given in %s on line %d
+Warning: getservbyname() expects parameter 1 to be a valid path, array given in %s on line %d
NULL
-Warning: getservbyname() expects parameter 1 to be string, array given in %s on line %d
+Warning: getservbyname() expects parameter 1 to be a valid path, array given in %s on line %d
NULL
diff --git a/ext/standard/tests/general_functions/getservbyname_variation13.phpt b/ext/standard/tests/general_functions/getservbyname_variation13.phpt
index 8dad8cda..b556d464 100644
--- a/ext/standard/tests/general_functions/getservbyname_variation13.phpt
+++ b/ext/standard/tests/general_functions/getservbyname_variation13.phpt
@@ -34,5 +34,5 @@ foreach ( $variation_array as $var ) {
*** Test substituting argument 2 with object values ***
bool(false)
-Warning: getservbyname() expects parameter 2 to be string, object given in %s.php on line %d
+Warning: getservbyname() expects parameter 2 to be a valid path, object given in %s.php on line %d
NULL
diff --git a/ext/standard/tests/general_functions/getservbyname_variation6.phpt b/ext/standard/tests/general_functions/getservbyname_variation6.phpt
index 0dfafa62..e184c1a1 100644
--- a/ext/standard/tests/general_functions/getservbyname_variation6.phpt
+++ b/ext/standard/tests/general_functions/getservbyname_variation6.phpt
@@ -34,5 +34,5 @@ foreach ( $variation_array as $var ) {
*** Test substituting argument 1 with object values ***
bool(false)
-Warning: getservbyname() expects parameter 1 to be string, object given in %s.php on line %d
+Warning: getservbyname() expects parameter 1 to be a valid path, object given in %s.php on line %d
NULL
diff --git a/ext/standard/tests/general_functions/getservbyname_variation8.phpt b/ext/standard/tests/general_functions/getservbyname_variation8.phpt
index 69d1d77b..78d7d0b7 100644
--- a/ext/standard/tests/general_functions/getservbyname_variation8.phpt
+++ b/ext/standard/tests/general_functions/getservbyname_variation8.phpt
@@ -27,14 +27,14 @@ foreach ( $variation_array as $var ) {
--EXPECTF--
*** Test substituting argument 2 with array values ***
-Warning: getservbyname() expects parameter 2 to be string, array given in %s on line %d
+Warning: getservbyname() expects parameter 2 to be a valid path, array given in %s on line %d
NULL
-Warning: getservbyname() expects parameter 2 to be string, array given in %s on line %d
+Warning: getservbyname() expects parameter 2 to be a valid path, array given in %s on line %d
NULL
-Warning: getservbyname() expects parameter 2 to be string, array given in %s on line %d
+Warning: getservbyname() expects parameter 2 to be a valid path, array given in %s on line %d
NULL
-Warning: getservbyname() expects parameter 2 to be string, array given in %s on line %d
+Warning: getservbyname() expects parameter 2 to be a valid path, array given in %s on line %d
NULL
diff --git a/ext/standard/tests/http/bug61548.phpt b/ext/standard/tests/http/bug61548.phpt
index 38b2bbf0..b4b70794 100644
--- a/ext/standard/tests/http/bug61548.phpt
+++ b/ext/standard/tests/http/bug61548.phpt
@@ -55,7 +55,6 @@ Connection: close
First:1
Second:2
-
POST / HTTP/1.0
Host: 127.0.0.1:12342
Connection: close
@@ -69,7 +68,6 @@ Connection: close
First:1
Second:2
-
POST / HTTP/1.0
Host: 127.0.0.1:12342
Connection: close
diff --git a/ext/standard/tests/http/bug67430.phpt b/ext/standard/tests/http/bug67430.phpt
index a563951c..61c7080f 100644
--- a/ext/standard/tests/http/bug67430.phpt
+++ b/ext/standard/tests/http/bug67430.phpt
@@ -41,7 +41,7 @@ POST / HTTP/1.0
Host: 127.0.0.1:12342
Connection: close
-GET /foo HTTP/1.0
+POST /foo HTTP/1.0
Host: 127.0.0.1:12342
Connection: close
diff --git a/ext/standard/tests/http/bug78719.phpt b/ext/standard/tests/http/bug78719.phpt
new file mode 100644
index 00000000..b12bd395
--- /dev/null
+++ b/ext/standard/tests/http/bug78719.phpt
@@ -0,0 +1,26 @@
+--TEST--
+Bug #78719 (http wrapper silently ignores long Location headers)
+--SKIPIF--
+
+--INI--
+allow_url_fopen=1
+--FILE--
+ ['follow_location' => 0]]);
+$stream = fopen('http://127.0.0.1:12342/', 'r', false, $context);
+var_dump(stream_get_contents($stream));
+var_dump(stream_get_meta_data($stream)['wrapper_data'][1] === "Location: $url");
+
+http_server_kill($pid);
+?>
+--EXPECTF--
+string(4) "Body"
+bool(true)
diff --git a/ext/standard/tests/http/bug79265.phpt b/ext/standard/tests/http/bug79265.phpt
new file mode 100644
index 00000000..4848991b
--- /dev/null
+++ b/ext/standard/tests/http/bug79265.phpt
@@ -0,0 +1,39 @@
+--TEST--
+Bug #79265 (Improper injection of Host header when using fopen for http requests)
+--INI--
+allow_url_fopen=1
+--SKIPIF--
+
+--FILE--
+array(
+ 'method'=>"GET",
+ 'header'=>"RandomHeader: localhost:8080\r\n" .
+ "Cookie: foo=bar\r\n" .
+ "Host: userspecifiedvalue\r\n"
+ )
+);
+$context = stream_context_create($opts);
+$fd = fopen('http://127.0.0.1:12342/', 'rb', false, $context);
+fseek($output, 0, SEEK_SET);
+echo stream_get_contents($output);
+fclose($fd);
+
+http_server_kill($pid);
+
+?>
+--EXPECT--
+GET / HTTP/1.0
+Connection: close
+RandomHeader: localhost:8080
+Cookie: foo=bar
+Host: userspecifiedvalue
diff --git a/ext/standard/tests/http/bug79265_2.phpt b/ext/standard/tests/http/bug79265_2.phpt
new file mode 100644
index 00000000..d2f5bc1e
--- /dev/null
+++ b/ext/standard/tests/http/bug79265_2.phpt
@@ -0,0 +1,38 @@
+--TEST--
+Bug #79265 variation: "host:" not at start of header
+--INI--
+allow_url_fopen=1
+--SKIPIF--
+
+--FILE--
+array(
+ 'method'=>"GET",
+ 'header'=>"RandomHeader: host:8080\r\n" .
+ "Cookie: foo=bar\r\n"
+ )
+);
+$context = stream_context_create($opts);
+$fd = fopen('http://127.0.0.1:12342/', 'rb', false, $context);
+fseek($output, 0, SEEK_SET);
+echo stream_get_contents($output);
+fclose($fd);
+
+http_server_kill($pid);
+
+?>
+--EXPECT--
+GET / HTTP/1.0
+Host: 127.0.0.1:12342
+Connection: close
+RandomHeader: host:8080
+Cookie: foo=bar
diff --git a/ext/standard/tests/http/bug80256.phpt b/ext/standard/tests/http/bug80256.phpt
new file mode 100644
index 00000000..8df081d8
--- /dev/null
+++ b/ext/standard/tests/http/bug80256.phpt
@@ -0,0 +1,29 @@
+--TEST--
+Bug #80256: file_get_contents strip first line with chunked encoding redirect
+--SKIPIF--
+
+--INI--
+allow_url_fopen=1
+--FILE--
+
+--EXPECT--
+string(4) "1234"
diff --git a/ext/standard/tests/http/gh11274.phpt b/ext/standard/tests/http/gh11274.phpt
new file mode 100644
index 00000000..25f9bdee
--- /dev/null
+++ b/ext/standard/tests/http/gh11274.phpt
@@ -0,0 +1,62 @@
+--TEST--
+GH-11274 (POST/PATCH request via file_get_contents + stream_context_create switches to GET after a HTTP 308 redirect)
+--INI--
+allow_url_fopen=1
+--CONFLICTS--
+server
+--FILE--
+ ['method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query(['hello' => 'world'])]]));
+ echo file_get_contents("http://" . PHP_CLI_SERVER_ADDRESS . "/test$suffix", false, stream_context_create(['http' => ['method' => 'PATCH', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query(['hello' => 'world'])]]));
+ echo file_get_contents("http://" . PHP_CLI_SERVER_ADDRESS . "/test/$suffix", false, stream_context_create(['http' => ['method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query(['hello' => 'world'])]]));
+ echo file_get_contents("http://" . PHP_CLI_SERVER_ADDRESS . "/test/$suffix", false, stream_context_create(['http' => ['method' => 'PATCH', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query(['hello' => 'world'])]]));
+}
+?>
+--EXPECT--
+-- Testing unredirected request --
+method: POST; body: hello=world
+method: PATCH; body: hello=world
+method: POST; body: hello=world
+method: PATCH; body: hello=world
+-- Testing redirect status code 301 --
+method: GET; body:
+method: GET; body:
+method: GET; body:
+method: GET; body:
+-- Testing redirect status code 302 --
+method: GET; body:
+method: GET; body:
+method: GET; body:
+method: GET; body:
+-- Testing redirect status code 307 --
+method: POST; body: hello=world
+method: PATCH; body: hello=world
+method: POST; body: hello=world
+method: PATCH; body: hello=world
+-- Testing redirect status code 308 --
+method: POST; body: hello=world
+method: PATCH; body: hello=world
+method: POST; body: hello=world
+method: PATCH; body: hello=world
diff --git a/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-001.phpt b/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-001.phpt
new file mode 100644
index 00000000..401be664
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-001.phpt
@@ -0,0 +1,58 @@
+--TEST--
+GHSA-52jp-hrpf-2jff: HTTP stream wrapper truncate redirect location to 1024 bytes (success)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ $loc = str_repeat("y", 8000);
+ fwrite($conn, "HTTP/1.0 301 Ok\r\nContent-Type: text/html;\r\nLocation: $loc\r\n\r\nbody\r\n");
+CODE;
+
+$clientCode = <<<'CODE'
+ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
+ switch($notification_code) {
+ case STREAM_NOTIFY_MIME_TYPE_IS:
+ echo "Found the mime-type: ", $message, PHP_EOL;
+ break;
+ case STREAM_NOTIFY_REDIRECTED:
+ echo "Redirected: ";
+ var_dump($message);
+ }
+ }
+
+ $ctx = stream_context_create();
+ stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
+ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx)));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+Found the mime-type: text/html;
+Redirected: string(8000) "%s"
+
+Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: %s
+string(0) ""
+array(3) {
+ [0]=>
+ string(15) "HTTP/1.0 301 Ok"
+ [1]=>
+ string(24) "Content-Type: text/html;"
+ [2]=>
+ string(8010) "Location: %s"
+}
diff --git a/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-002.phpt b/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-002.phpt
new file mode 100644
index 00000000..97611ca7
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-52jp-hrpf-2jff-002.phpt
@@ -0,0 +1,55 @@
+--TEST--
+GHSA-52jp-hrpf-2jff: HTTP stream wrapper truncate redirect location to 1024 bytes (over limit)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ $loc = str_repeat("y", 9000);
+ fwrite($conn, "HTTP/1.0 301 Ok\r\nContent-Type: text/html;\r\nLocation: $loc\r\n\r\nbody\r\n");
+CODE;
+
+$clientCode = <<<'CODE'
+ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
+ switch($notification_code) {
+ case STREAM_NOTIFY_MIME_TYPE_IS:
+ echo "Found the mime-type: ", $message, PHP_EOL;
+ break;
+ case STREAM_NOTIFY_REDIRECTED:
+ echo "Redirected: ";
+ var_dump($message);
+ }
+ }
+
+ $ctx = stream_context_create();
+ stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
+ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx)));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+Found the mime-type: text/html;
+
+Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP Location header size is over the limit of 8182 bytes in %s
+string(0) ""
+array(2) {
+ [0]=>
+ string(15) "HTTP/1.0 301 Ok"
+ [1]=>
+ string(24) "Content-Type: text/html;"
+}
diff --git a/ext/standard/tests/http/ghsa-fpwc-w8rq-cr92.phpt b/ext/standard/tests/http/ghsa-fpwc-w8rq-cr92.phpt
new file mode 100644
index 00000000..a6c595fe
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-fpwc-w8rq-cr92.phpt
@@ -0,0 +1,181 @@
+--TEST--
+GHSA-fpwc-w8rq-cr92: strip credentials from user headers on cross-origin redirect
+--INI--
+allow_url_fopen=1
+--SKIPIF--
+
+--FILE--
+ [
+ 'header' => "Authorization: Bearer SECRET\r\n"
+ . "Cookie: sid=abc\r\n"
+ . "Proxy-Authorization: Basic Zm9vOmJhcg==\r\n"
+ . "X-Custom: keep-me",
+ 'follow_location' => 1,
+]]);
+
+/* server B listens on a different port than server A, so the hop from A to B is
+ * cross-origin; B then redirects to itself: credentials must stay withheld for
+ * that same-origin hop too */
+$uriB = 'tcp://127.0.0.1:12342';
+$captureB = null;
+$pidB = http_server($uriB, [
+ "data://text/plain,HTTP/1.1 302 Found\r\nLocation: /second\r\nContent-Length: 0\r\n\r\n",
+ "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK",
+], $captureB);
+$uriB = preg_replace('#^tcp://#', 'http://', $uriB);
+
+$uriA = 'tcp://127.0.0.1:12343';
+$captureA = null;
+$pidA = http_server($uriA, [
+ "data://text/plain,HTTP/1.1 302 Found\r\nLocation: $uriB/first\r\nContent-Length: 0\r\n\r\n",
+], $captureA);
+$uriA = preg_replace('#^tcp://#', 'http://', $uriA);
+
+var_dump(file_get_contents($uriA . '/src', false, $ctx));
+
+http_server_kill($pidA);
+http_server_kill($pidB);
+
+rewind($captureA);
+rewind($captureB);
+report('--- origin A (1 request) ---', stream_get_contents($captureA));
+report('--- origin B (2 requests) ---', stream_get_contents($captureB));
+
+/* same origin throughout: credentials must be sent on both hops */
+$uriC = 'tcp://127.0.0.1:12344';
+$captureC = null;
+$pidC = http_server($uriC, [
+ "data://text/plain,HTTP/1.1 302 Found\r\nLocation: /next\r\nContent-Length: 0\r\n\r\n",
+ "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK",
+], $captureC);
+$uriC = preg_replace('#^tcp://#', 'http://', $uriC);
+
+var_dump(file_get_contents($uriC . '/first', false, $ctx));
+
+http_server_kill($pidC);
+
+rewind($captureC);
+report('--- origin C (2 requests) ---', stream_get_contents($captureC));
+
+/* a stripped header that was last in the bag must not leave a trailing line break
+ * behind, or the request body would be pushed out of the request */
+$ctx = stream_context_create(['http' => [
+ 'method' => 'POST',
+ 'content' => 'hello=world',
+ 'header' => "X-Custom: keep-me\r\nAuthorization: Bearer SECRET",
+ 'follow_location' => 1,
+]]);
+
+$uriH = 'tcp://127.0.0.1:12345';
+$captureH = null;
+$pidH = http_server($uriH, [
+ "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK",
+], $captureH);
+$uriH = preg_replace('#^tcp://#', 'http://', $uriH);
+
+$uriG = 'tcp://127.0.0.1:12346';
+$captureG = null;
+$pidG = http_server($uriG, [
+ "data://text/plain,HTTP/1.1 307 Temporary Redirect\r\nLocation: $uriH/second\r\nContent-Length: 0\r\n\r\n",
+], $captureG);
+$uriG = preg_replace('#^tcp://#', 'http://', $uriG);
+
+var_dump(@file_get_contents($uriG . '/first', false, $ctx));
+
+http_server_kill($pidG);
+http_server_kill($pidH);
+
+rewind($captureH);
+echo "--- credential header last in the bag (307) ---\n";
+echo preg_replace('/^Host:.*$/m', 'Host: ...', stream_get_contents($captureH));
+
+echo "--- malformed header bags ---\n";
+foreach ([
+ 'folded value ' => "Authorization:\r\n Bearer SECRET\r\nX-Custom: keep-me",
+ 'folded value (tab)' => "Authorization:\r\n\tBearer SECRET\r\nX-Custom: keep-me",
+ 'lone CR ' => "X-Custom: keep-me\rAuthorization: Bearer SECRET",
+ 'space before colon' => "Authorization : Bearer SECRET\r\nX-Custom: keep-me",
+ 'tab before colon ' => "Authorization\t: Bearer SECRET\r\nX-Custom: keep-me",
+] as $label => $header) {
+ $ctx = stream_context_create(['http' => ['header' => $header, 'follow_location' => 1]]);
+
+ $uriF = 'tcp://127.0.0.1:12347';
+ $captureF = null;
+ $pidF = http_server($uriF, [
+ "data://text/plain,HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK",
+ ], $captureF);
+ $uriF = preg_replace('#^tcp://#', 'http://', $uriF);
+
+ $uriE = 'tcp://127.0.0.1:12348';
+ $captureE = null;
+ $pidE = http_server($uriE, [
+ "data://text/plain,HTTP/1.1 302 Found\r\nLocation: $uriF/second\r\nContent-Length: 0\r\n\r\n",
+ ], $captureE);
+ $uriE = preg_replace('#^tcp://#', 'http://', $uriE);
+
+ file_get_contents($uriE . '/first', false, $ctx);
+
+ http_server_kill($pidE);
+ http_server_kill($pidF);
+
+ rewind($captureF);
+ $request = stream_get_contents($captureF);
+ printf(" %s SECRET leaked: %d, X-Custom kept: %d\n", $label,
+ strpos($request, 'SECRET') !== false, strpos($request, 'X-Custom') !== false);
+}
+?>
+--EXPECT--
+string(2) "OK"
+--- origin A (1 request) ---
+ Authorization: 1
+ Cookie: 1
+ Proxy-Authorization: 1
+ X-Custom: 1
+--- origin B (2 requests) ---
+ Authorization: 0
+ Cookie: 0
+ Proxy-Authorization: 0
+ X-Custom: 2
+string(2) "OK"
+--- origin C (2 requests) ---
+ Authorization: 2
+ Cookie: 2
+ Proxy-Authorization: 2
+ X-Custom: 2
+string(2) "OK"
+--- credential header last in the bag (307) ---
+POST /second HTTP/1.0
+Host: ...
+Connection: close
+Content-Length: 11
+X-Custom: keep-me
+Content-Type: application/x-www-form-urlencoded
+
+hello=world--- malformed header bags ---
+ folded value SECRET leaked: 0, X-Custom kept: 1
+ folded value (tab) SECRET leaked: 0, X-Custom kept: 1
+ lone CR SECRET leaked: 0, X-Custom kept: 1
+ space before colon SECRET leaked: 0, X-Custom kept: 1
+ tab before colon SECRET leaked: 0, X-Custom kept: 1
diff --git a/ext/standard/tests/http/ghsa-hgf5-96fm-v528-001.phpt b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-001.phpt
new file mode 100644
index 00000000..cdb30eab
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-001.phpt
@@ -0,0 +1,72 @@
+--TEST--
+GHSA-hgf5-96fm-v528: Stream HTTP wrapper header check might omit basic auth header (incorrect inside pos)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ $result = "";
+ while (1) {
+ $result2 = fread($conn, 1024);
+ $result .= $result2;
+ if (preg_match('/\r\n\r\n$/s', $result)) {
+ break;
+ }
+ }
+ $encoded_result = base64_encode($result);
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html; charset=utf-8\r\n\r\n$encoded_result\r\n");
+
+CODE;
+
+$clientCode = <<<'CODE'
+ $opts = [
+ "http" => [
+ "method" => "GET",
+ "header" => "Cookie: foo=bar\nauthorization:x\r\n"
+ ]
+ ];
+ $ctx = stream_context_create($opts);
+ var_dump(explode("\r\n", base64_decode(file_get_contents("http://user:pwd@{{ ADDR }}", false, $ctx))));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+array(7) {
+ [0]=>
+ string(14) "GET / HTTP/1.0"
+ [1]=>
+ string(33) "Authorization: Basic dXNlcjpwd2Q="
+ [2]=>
+ string(21) "Host: 127.0.0.1:%d"
+ [3]=>
+ string(17) "Connection: close"
+ [4]=>
+ string(31) "Cookie: foo=bar
+authorization:x"
+ [5]=>
+ string(0) ""
+ [6]=>
+ string(0) ""
+}
+array(2) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+ [1]=>
+ string(38) "Content-Type: text/html; charset=utf-8"
+}
diff --git a/ext/standard/tests/http/ghsa-hgf5-96fm-v528-002.phpt b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-002.phpt
new file mode 100644
index 00000000..dda22505
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-002.phpt
@@ -0,0 +1,69 @@
+--TEST--
+GHSA-hgf5-96fm-v528: Header parser of http stream wrapper does not handle folded headers (correct start pos)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ $result = "";
+ while (1) {
+ $result2 = fread($conn, 1024);
+ $result .= $result2;
+ if (preg_match('/\r\n\r\n$/s', $result)) {
+ break;
+ }
+ }
+ $encoded_result = base64_encode($result);
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html; charset=utf-8\r\n\r\n$encoded_result\r\n");
+
+CODE;
+
+$clientCode = <<<'CODE'
+ $opts = [
+ "http" => [
+ "method" => "GET",
+ "header" => "Authorization: Bearer x\r\n"
+ ]
+ ];
+ $ctx = stream_context_create($opts);
+ var_dump(explode("\r\n", base64_decode(file_get_contents("http://user:pwd@{{ ADDR }}", false, $ctx))));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+array(6) {
+ [0]=>
+ string(14) "GET / HTTP/1.0"
+ [1]=>
+ string(21) "Host: 127.0.0.1:%d"
+ [2]=>
+ string(17) "Connection: close"
+ [3]=>
+ string(23) "Authorization: Bearer x"
+ [4]=>
+ string(0) ""
+ [5]=>
+ string(0) ""
+}
+array(2) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+ [1]=>
+ string(38) "Content-Type: text/html; charset=utf-8"
+}
diff --git a/ext/standard/tests/http/ghsa-hgf5-96fm-v528-003.phpt b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-003.phpt
new file mode 100644
index 00000000..d17ba7c3
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-hgf5-96fm-v528-003.phpt
@@ -0,0 +1,71 @@
+--TEST--
+GHSA-hgf5-96fm-v528: Header parser of http stream wrapper does not handle folded headers (correct middle pos)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ $result = "";
+ while (1) {
+ $result2 = fread($conn, 1024);
+ $result .= $result2;
+ if (preg_match('/\r\n\r\n$/s', $result)) {
+ break;
+ }
+ }
+ $encoded_result = base64_encode($result);
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html; charset=utf-8\r\n\r\n$encoded_result\r\n");
+
+CODE;
+
+$clientCode = <<<'CODE'
+ $opts = [
+ "http" => [
+ "method" => "GET",
+ "header" => "Cookie: x=y\r\nAuthorization: Bearer x\r\n"
+ ]
+ ];
+ $ctx = stream_context_create($opts);
+ var_dump(explode("\r\n", base64_decode(file_get_contents("http://user:pwd@{{ ADDR }}", false, $ctx))));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+array(7) {
+ [0]=>
+ string(14) "GET / HTTP/1.0"
+ [1]=>
+ string(21) "Host: 127.0.0.1:%d"
+ [2]=>
+ string(17) "Connection: close"
+ [3]=>
+ string(11) "Cookie: x=y"
+ [4]=>
+ string(23) "Authorization: Bearer x"
+ [5]=>
+ string(0) ""
+ [6]=>
+ string(0) ""
+}
+array(2) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+ [1]=>
+ string(38) "Content-Type: text/html; charset=utf-8"
+}
diff --git a/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-001.phpt b/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-001.phpt
new file mode 100644
index 00000000..3a39deca
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-001.phpt
@@ -0,0 +1,51 @@
+--TEST--
+GHSA-pcmh-g36c-qc44: Header parser of http stream wrapper does not verify header name and colon (colon)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html\r\nWrong-Header\r\nGood-Header: test\r\n\r\nbody\r\n");
+CODE;
+
+$clientCode = <<<'CODE'
+ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
+ switch($notification_code) {
+ case STREAM_NOTIFY_MIME_TYPE_IS:
+ echo "Found the mime-type: ", $message, PHP_EOL;
+ break;
+ }
+ }
+
+ $ctx = stream_context_create();
+ stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
+ var_dump(file_get_contents("http://{{ ADDR }}", false, $ctx));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+Found the mime-type: text/html
+
+Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP invalid response format (no colon in header line)! in %s
+bool(false)
+array(2) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+ [1]=>
+ string(23) "Content-Type: text/html"
+}
diff --git a/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-002.phpt b/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-002.phpt
new file mode 100644
index 00000000..b849643e
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-pcmh-g36c-qc44-002.phpt
@@ -0,0 +1,51 @@
+--TEST--
+GHSA-pcmh-g36c-qc44: Header parser of http stream wrapper does not verify header name and colon (name)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html\r\nWrong-Header : test\r\nGood-Header: test\r\n\r\nbody\r\n");
+CODE;
+
+$clientCode = <<<'CODE'
+ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
+ switch($notification_code) {
+ case STREAM_NOTIFY_MIME_TYPE_IS:
+ echo "Found the mime-type: ", $message, PHP_EOL;
+ break;
+ }
+ }
+
+ $ctx = stream_context_create();
+ stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
+ var_dump(file_get_contents("http://{{ ADDR }}", false, $ctx));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+Found the mime-type: text/html
+
+Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP invalid response format (space in header name)! in %s
+bool(false)
+array(2) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+ [1]=>
+ string(23) "Content-Type: text/html"
+}
diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-001.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-001.phpt
new file mode 100644
index 00000000..16756551
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-001.phpt
@@ -0,0 +1,49 @@
+--TEST--
+GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (single)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html;\r\n charset=utf-8\r\n\r\nbody\r\n");
+CODE;
+
+$clientCode = <<<'CODE'
+ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
+ switch($notification_code) {
+ case STREAM_NOTIFY_MIME_TYPE_IS:
+ echo "Found the mime-type: ", $message, PHP_EOL;
+ break;
+ }
+ }
+
+ $ctx = stream_context_create();
+ stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
+ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx)));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+Found the mime-type: text/html; charset=utf-8
+string(4) "body"
+array(2) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+ [1]=>
+ string(38) "Content-Type: text/html; charset=utf-8"
+}
diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-002.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-002.phpt
new file mode 100644
index 00000000..22ab70f4
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-002.phpt
@@ -0,0 +1,51 @@
+--TEST--
+GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (multiple)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html;\r\nCustom-Header: somevalue;\r\n param1=value1; \r\n param2=value2\r\n\r\nbody\r\n");
+CODE;
+
+$clientCode = <<<'CODE'
+ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
+ switch($notification_code) {
+ case STREAM_NOTIFY_MIME_TYPE_IS:
+ echo "Found the mime-type: ", $message, PHP_EOL;
+ break;
+ }
+ }
+
+ $ctx = stream_context_create();
+ stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
+ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx)));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+Found the mime-type: text/html;
+string(4) "body"
+array(3) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+ [1]=>
+ string(24) "Content-Type: text/html;"
+ [2]=>
+ string(54) "Custom-Header: somevalue; param1=value1; param2=value2"
+}
diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-003.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-003.phpt
new file mode 100644
index 00000000..a283f998
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-003.phpt
@@ -0,0 +1,49 @@
+--TEST--
+GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (empty)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\nContent-Type: text/html;\r\n \r\n charset=utf-8\r\n\r\nbody\r\n");
+CODE;
+
+$clientCode = <<<'CODE'
+ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
+ switch($notification_code) {
+ case STREAM_NOTIFY_MIME_TYPE_IS:
+ echo "Found the mime-type: ", $message, PHP_EOL;
+ break;
+ }
+ }
+
+ $ctx = stream_context_create();
+ stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
+ var_dump(trim(file_get_contents("http://{{ ADDR }}", false, $ctx)));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+Found the mime-type: text/html; charset=utf-8
+string(4) "body"
+array(2) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+ [1]=>
+ string(38) "Content-Type: text/html; charset=utf-8"
+}
diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-004.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-004.phpt
new file mode 100644
index 00000000..68fc3303
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-004.phpt
@@ -0,0 +1,48 @@
+--TEST--
+GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (first line)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\n Content-Type: text/html;\r\n \r\n charset=utf-8\r\n\r\nbody\r\n");
+CODE;
+
+$clientCode = <<<'CODE'
+ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
+ switch($notification_code) {
+ case STREAM_NOTIFY_MIME_TYPE_IS:
+ echo "Found the mime-type: ", $message, PHP_EOL;
+ break;
+ }
+ }
+
+ $ctx = stream_context_create();
+ stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
+ var_dump(file_get_contents("http://{{ ADDR }}", false, $ctx));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+
+Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP invalid response format (folding header at the start)! in %s
+bool(false)
+array(1) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+}
diff --git a/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-005.phpt b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-005.phpt
new file mode 100644
index 00000000..df89de57
--- /dev/null
+++ b/ext/standard/tests/http/ghsa-v8xr-gpvj-cx9g-005.phpt
@@ -0,0 +1,48 @@
+--TEST--
+GHSA-v8xr-gpvj-cx9g: Header parser of http stream wrapper does not handle folded headers (CR before header name)
+--FILE--
+ [
+ "tcp_nodelay" => true
+ ]
+ ]);
+
+ $server = stream_socket_server(
+ "tcp://127.0.0.1:0", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctxt);
+ phpt_notify_server_start($server);
+
+ $conn = stream_socket_accept($server);
+
+ phpt_notify(WORKER_DEFAULT_NAME, "server-accepted");
+
+ fwrite($conn, "HTTP/1.0 200 Ok\r\n\rIgnored: ignored\r\n\r\nbody\r\n");
+CODE;
+
+$clientCode = <<<'CODE'
+ function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
+ switch($notification_code) {
+ case STREAM_NOTIFY_MIME_TYPE_IS:
+ echo "Found the mime-type: ", $message, PHP_EOL;
+ break;
+ }
+ }
+
+ $ctx = stream_context_create();
+ stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
+ var_dump(file_get_contents("http://{{ ADDR }}", false, $ctx));
+ var_dump($http_response_header);
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase-8.1.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECTF--
+
+Warning: file_get_contents(http://127.0.0.1:%d): failed to open stream: HTTP invalid header name (cannot start with CR character)! in %s
+bool(false)
+array(1) {
+ [0]=>
+ string(15) "HTTP/1.0 200 Ok"
+}
diff --git a/ext/standard/tests/http/http_empty_location_redirect.phpt b/ext/standard/tests/http/http_empty_location_redirect.phpt
new file mode 100644
index 00000000..e870e750
--- /dev/null
+++ b/ext/standard/tests/http/http_empty_location_redirect.phpt
@@ -0,0 +1,37 @@
+--TEST--
+Empty Location header must not over-read when building the redirect target
+--FILE--
+ ['follow_location' => 1]]);
+phpt_wait();
+echo @file_get_contents("http://127.0.0.1:12342/a/b", false, $ctx), "\n";
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECT--
+uri=/
diff --git a/ext/standard/tests/http/http_single_char_location_redirect.phpt b/ext/standard/tests/http/http_single_char_location_redirect.phpt
new file mode 100644
index 00000000..4e9b3eb3
--- /dev/null
+++ b/ext/standard/tests/http/http_single_char_location_redirect.phpt
@@ -0,0 +1,40 @@
+--TEST--
+Single-char relative Location header keeps resolving against the host root (pre-GH-23467 behavior)
+--DESCRIPTION--
+Not RFC 3986 compliant ("x" against "/a/b" gives "/a/x"), but matches
+PHP's long-standing behavior of resolving against the host root. See GH-23521.
+--FILE--
+ ['follow_location' => 1]]);
+phpt_wait();
+echo @file_get_contents("http://127.0.0.1:12342/a/b", false, $ctx), "\n";
+CODE;
+
+include sprintf("%s/../../../openssl/tests/ServerClientTestCase.inc", __DIR__);
+ServerClientTestCase::getInstance()->run($clientCode, $serverCode);
+?>
+--EXPECT--
+uri=/x
diff --git a/ext/standard/tests/http/server-8.0.inc b/ext/standard/tests/http/server-8.0.inc
new file mode 100644
index 00000000..55a26806
--- /dev/null
+++ b/ext/standard/tests/http/server-8.0.inc
@@ -0,0 +1,124 @@
+ $pid,
+ 'uri' => 'http://' . stream_socket_get_name($server, false),
+ ];
+ }
+
+ return $server;
+}
+
+/* Minimal HTTP server with predefined responses.
+ *
+ * $socket_string is the socket to create and listen on (e.g. tcp://127.0.0.1:1234)
+ * $files is an iterable of files or callable generator yielding files.
+ * containing N responses for N expected requests. Server dies after N requests.
+ * $output is a stream on which everything sent by clients is written to
+ */
+function http_server($files, &$output = null) {
+
+ if (!is_resource($server = http_server_init($output))) {
+ return $server;
+ }
+
+ if (is_callable($files)) {
+ $files = $files($server);
+ }
+
+ foreach($files as $file) {
+
+ $sock = stream_socket_accept($server);
+ if (!$sock) {
+ exit(1);
+ }
+
+ // read headers
+
+ $content_length = 0;
+
+ stream_set_blocking($sock, false);
+ while (!feof($sock)) {
+
+ list($r, $w, $e) = array(array($sock), null, null);
+ if (!stream_select($r, $w, $e, 1)) continue;
+
+ $line = stream_get_line($sock, 8192, "\r\n");
+ if ($line === '') {
+ fwrite($output, "\r\n");
+ break;
+ } else if ($line !== false) {
+ fwrite($output, "$line\r\n");
+
+ if (preg_match('#^Content-Length\s*:\s*([[:digit:]]+)\s*$#i', $line, $matches)) {
+ $content_length = (int) $matches[1];
+ }
+ }
+ }
+ stream_set_blocking($sock, true);
+
+ // read content
+
+ if ($content_length > 0) {
+ stream_copy_to_stream($sock, $output, $content_length);
+ }
+
+ // send response
+
+ $fd = fopen($file, 'rb');
+ stream_copy_to_stream($fd, $sock);
+
+ fclose($sock);
+ }
+
+ exit(0);
+}
+
+function http_server_sleep($micro_seconds = 500000)
+{
+ if (!is_resource($server = http_server_init($output))) {
+ return $server;
+ }
+
+ $sock = stream_socket_accept($server);
+ if (!$sock) {
+ exit(1);
+ }
+
+ usleep($micro_seconds);
+
+ fclose($sock);
+
+ exit(0);
+}
+
+function http_server_kill($pid) {
+ posix_kill($pid, SIGTERM);
+ pcntl_waitpid($pid, $status);
+}
diff --git a/ext/standard/tests/image/bug71848.phpt b/ext/standard/tests/image/bug71848.phpt
new file mode 100644
index 00000000..d96ac1c5
--- /dev/null
+++ b/ext/standard/tests/image/bug71848.phpt
@@ -0,0 +1,32 @@
+--TEST--
+Bug #71848 (getimagesize with $imageinfo returns false)
+--FILE--
+
+===DONE===
+--EXPECT--
+array(7) {
+ [0]=>
+ int(8)
+ [1]=>
+ int(8)
+ [2]=>
+ int(2)
+ [3]=>
+ string(20) "width="8" height="8""
+ ["bits"]=>
+ int(8)
+ ["channels"]=>
+ int(3)
+ ["mime"]=>
+ string(10) "image/jpeg"
+}
+array(2) {
+ [0]=>
+ string(4) "APP0"
+ [1]=>
+ string(4) "APP5"
+}
+===DONE===
diff --git a/ext/standard/tests/image/gh20584.phpt b/ext/standard/tests/image/gh20584.phpt
new file mode 100644
index 00000000..d117f218
--- /dev/null
+++ b/ext/standard/tests/image/gh20584.phpt
@@ -0,0 +1,39 @@
+--TEST--
+GH-20584 (Information Leak of Memory)
+--CREDITS--
+Nikita Sveshnikov (Positive Technologies)
+--FILE--
+
+--CLEAN--
+
+--EXPECT--
+bool(true)
diff --git a/ext/standard/tests/network/ghsa-3cr5-j632-f35r.phpt b/ext/standard/tests/network/ghsa-3cr5-j632-f35r.phpt
new file mode 100644
index 00000000..e16d3fa9
--- /dev/null
+++ b/ext/standard/tests/network/ghsa-3cr5-j632-f35r.phpt
@@ -0,0 +1,21 @@
+--TEST--
+GHSA-3cr5-j632-f35r: Null byte termination in fsockopen()
+--FILE--
+
+--EXPECTF--
+
+Warning: fsockopen(): unable to connect to localhost:%d (The hostname must not contain null bytes) in %s
+bool(false)
diff --git a/ext/standard/tests/network/ghsa-www2-q4fc-65wf.phpt b/ext/standard/tests/network/ghsa-www2-q4fc-65wf.phpt
new file mode 100644
index 00000000..c9f5d677
--- /dev/null
+++ b/ext/standard/tests/network/ghsa-www2-q4fc-65wf.phpt
@@ -0,0 +1,70 @@
+--TEST--
+GHSA-www2-q4fc-65wf
+--DESCRIPTION--
+This is a ZPP test but *keep* this as it is security-sensitive!
+--FILE--
+getMessage(), "\n";
+}
+try {
+ dns_get_mx("\0", $out);
+} catch (ValueError $e) {
+ echo $e->getMessage(), "\n";
+}
+try {
+ dns_get_record("\0");
+} catch (ValueError $e) {
+ echo $e->getMessage(), "\n";
+}
+try {
+ getprotobyname("\0");
+} catch (ValueError $e) {
+ echo $e->getMessage(), "\n";
+}
+try {
+ getservbyname("\0", "tcp");
+} catch (ValueError $e) {
+ echo $e->getMessage(), "\n";
+}
+try {
+ getservbyname("x", "tcp\0");
+} catch (ValueError $e) {
+ echo $e->getMessage(), "\n";
+}
+try {
+ getservbyport(0, "tcp\0");
+} catch (ValueError $e) {
+ echo $e->getMessage(), "\n";
+}
+try {
+ inet_pton("\0");
+} catch (ValueError $e) {
+ echo $e->getMessage(), "\n";
+}
+try {
+ ip2long("\0");
+} catch (ValueError $e) {
+ echo $e->getMessage(), "\n";
+}
+?>
+--EXPECTF--
+Warning: dns_check_record() expects parameter 1 to be a valid path, string given in %s on line %d
+
+Warning: dns_get_mx() expects parameter 1 to be a valid path, string given in %s on line %d
+
+Warning: dns_get_record() expects parameter 1 to be a valid path, string given in %s on line %d
+
+Warning: getprotobyname() expects parameter 1 to be a valid path, string given in %s on line %d
+
+Warning: getservbyname() expects parameter 1 to be a valid path, string given in %s on line %d
+
+Warning: getservbyname() expects parameter 2 to be a valid path, string given in %s on line %d
+
+Warning: getservbyport() expects parameter 2 to be a valid path, string given in %s on line %d
+
+Warning: inet_pton() expects parameter 1 to be a valid path, string given in %s on line %d
+
+Warning: ip2long() expects parameter 1 to be a valid path, string given in %s on line %d
diff --git a/ext/standard/tests/network/ip.phpt b/ext/standard/tests/network/ip.phpt
index 3fc1b9dc..ac9a5732 100644
--- a/ext/standard/tests/network/ip.phpt
+++ b/ext/standard/tests/network/ip.phpt
@@ -54,7 +54,7 @@ bool(false)
bool(false)
int(1869573999)
-Warning: ip2long() expects parameter 1 to be string, array given in %s on line %d
+Warning: ip2long() expects parameter 1 to be a valid path, array given in %s on line %d
NULL
Warning: long2ip() expects exactly 1 parameter, 0 given in %s on line %d
diff --git a/ext/standard/tests/network/ip2long_variation1.phpt b/ext/standard/tests/network/ip2long_variation1.phpt
index b228c9bd..941a2d64 100644
--- a/ext/standard/tests/network/ip2long_variation1.phpt
+++ b/ext/standard/tests/network/ip2long_variation1.phpt
@@ -141,19 +141,19 @@ bool(false)
bool(false)
--empty array--
-Error: 2 - ip2long() expects parameter 1 to be string, array given, %s(%d)
+Error: 2 - ip2long() expects parameter 1 to be a valid path, array given, %s(%d)
NULL
--int indexed array--
-Error: 2 - ip2long() expects parameter 1 to be string, array given, %s(%d)
+Error: 2 - ip2long() expects parameter 1 to be a valid path, array given, %s(%d)
NULL
--associative array--
-Error: 2 - ip2long() expects parameter 1 to be string, array given, %s(%d)
+Error: 2 - ip2long() expects parameter 1 to be a valid path, array given, %s(%d)
NULL
--nested arrays--
-Error: 2 - ip2long() expects parameter 1 to be string, array given, %s(%d)
+Error: 2 - ip2long() expects parameter 1 to be a valid path, array given, %s(%d)
NULL
--uppercase NULL--
@@ -184,7 +184,7 @@ bool(false)
bool(false)
--instance of classWithoutToString--
-Error: 2 - ip2long() expects parameter 1 to be string, object given, %s(%d)
+Error: 2 - ip2long() expects parameter 1 to be a valid path, object given, %s(%d)
NULL
--undefined var--
@@ -194,6 +194,6 @@ bool(false)
bool(false)
--resource--
-Error: 2 - ip2long() expects parameter 1 to be string, resource given, %s(%d)
+Error: 2 - ip2long() expects parameter 1 to be a valid path, resource given, %s(%d)
NULL
===DONE===
diff --git a/ext/standard/tests/network/ip_x86_64.phpt b/ext/standard/tests/network/ip_x86_64.phpt
index 1fcb8b20..e234dbdc 100644
--- a/ext/standard/tests/network/ip_x86_64.phpt
+++ b/ext/standard/tests/network/ip_x86_64.phpt
@@ -54,7 +54,7 @@ bool(false)
bool(false)
int(1869573999)
-Warning: ip2long() expects parameter 1 to be string, array given in %s on line %d
+Warning: ip2long() expects parameter 1 to be a valid path, array given in %s on line %d
NULL
Warning: long2ip() expects exactly 1 parameter, 0 given in %s on line %d
diff --git a/ext/standard/tests/streams/ghsa-3cr5-j632-f35r.phpt b/ext/standard/tests/streams/ghsa-3cr5-j632-f35r.phpt
new file mode 100644
index 00000000..bc1f34ea
--- /dev/null
+++ b/ext/standard/tests/streams/ghsa-3cr5-j632-f35r.phpt
@@ -0,0 +1,26 @@
+--TEST--
+GHSA-3cr5-j632-f35r: Null byte termination in stream_socket_client()
+--FILE--
+
+--EXPECTF--
+
+Warning: stream_socket_client(): unable to connect to tcp://localhost\0.example.com:%d (The hostname must not contain null bytes) in %s
+bool(false)
diff --git a/main/streams/xp_socket.c b/main/streams/xp_socket.c
index 90c5df0b..cab38677 100644
--- a/main/streams/xp_socket.c
+++ b/main/streams/xp_socket.c
@@ -549,7 +549,16 @@ static inline char *parse_ip_address_ex(const char *str, size_t str_len, int *po
#ifdef HAVE_IPV6
char *p;
+#endif
+ if (memchr(str, '\0', str_len)) {
+ if (get_err) {
+ *err = estrdup("The hostname must not contain null bytes");
+ }
+ return NULL;
+ }
+
+#ifdef HAVE_IPV6
if (*(str) == '[' && str_len > 1) {
/* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */
p = memchr(str + 1, ']', str_len - 2);
diff --git a/sapi/fpm/fpm/fastcgi.c b/sapi/fpm/fpm/fastcgi.c
index 778119e4..6ac568bf 100644
--- a/sapi/fpm/fpm/fastcgi.c
+++ b/sapi/fpm/fpm/fastcgi.c
@@ -786,7 +786,7 @@ static int fcgi_is_allowed() {
if (client_sa.sa.sa_family == AF_INET6) {
for (i=0 ; allowed_clients[i].sa.sa_family ; i++) {
if (allowed_clients[i].sa.sa_family == AF_INET6
- && !memcmp(&client_sa.sa_inet6.sin6_addr, &allowed_clients[i].sa_inet6.sin6_addr, 12)) {
+ && !memcmp(&client_sa.sa_inet6.sin6_addr, &allowed_clients[i].sa_inet6.sin6_addr, sizeof(client_sa.sa_inet6.sin6_addr))) {
return 1;
}
#ifdef IN6_IS_ADDR_V4MAPPED
diff --git a/sapi/fpm/tests/fcgi.inc b/sapi/fpm/tests/fcgi.inc
index b3167626..07603a80 100644
--- a/sapi/fpm/tests/fcgi.inc
+++ b/sapi/fpm/tests/fcgi.inc
@@ -72,25 +72,25 @@ class Client
/**
* Socket
- * @var Resource
+ * @var resource
*/
private $_sock = null;
/**
* Host
- * @var String
+ * @var string
*/
private $_host = null;
/**
* Port
- * @var Integer
+ * @var int
*/
private $_port = null;
/**
* Keep Alive
- * @var Boolean
+ * @var bool
*/
private $_keepAlive = false;
@@ -110,27 +110,27 @@ class Client
/**
* Use persistent sockets to connect to backend
- * @var Boolean
+ * @var bool
*/
private $_persistentSocket = false;
/**
* Connect timeout in milliseconds
- * @var Integer
+ * @var int
*/
private $_connectTimeout = 5000;
/**
* Read/Write timeout in milliseconds
- * @var Integer
+ * @var int
*/
private $_readWriteTimeout = 5000;
/**
* Constructor
*
- * @param String $host Host of the FastCGI application
- * @param Integer $port Port of the FastCGI application
+ * @param string $host Host of the FastCGI application
+ * @param int $port Port of the FastCGI application
*/
public function __construct($host, $port)
{
@@ -138,15 +138,25 @@ class Client
$this->_port = $port;
}
+ /**
+ * Get host.
+ *
+ * @return string
+ */
+ public function getHost()
+ {
+ return $this->_host;
+ }
+
/**
* Define whether or not the FastCGI application should keep the connection
* alive at the end of a request
*
- * @param Boolean $b true if the connection should stay alive, false otherwise
+ * @param bool $b true if the connection should stay alive, false otherwise
*/
public function setKeepAlive($b)
{
- $this->_keepAlive = (boolean)$b;
+ $this->_keepAlive = (bool)$b;
if (!$this->_keepAlive && $this->_sock) {
fclose($this->_sock);
}
@@ -155,7 +165,7 @@ class Client
/**
* Get the keep alive status
*
- * @return Boolean true if the connection should stay alive, false otherwise
+ * @return bool true if the connection should stay alive, false otherwise
*/
public function getKeepAlive()
{
@@ -166,12 +176,12 @@ class Client
* Define whether or not PHP should attempt to re-use sockets opened by previous
* request for efficiency
*
- * @param Boolean $b true if persistent socket should be used, false otherwise
+ * @param bool $b true if persistent socket should be used, false otherwise
*/
public function setPersistentSocket($b)
{
$was_persistent = ($this->_sock && $this->_persistentSocket);
- $this->_persistentSocket = (boolean)$b;
+ $this->_persistentSocket = (bool)$b;
if (!$this->_persistentSocket && $was_persistent) {
fclose($this->_sock);
}
@@ -180,7 +190,7 @@ class Client
/**
* Get the pesistent socket status
*
- * @return Boolean true if the socket should be persistent, false otherwise
+ * @return bool true if the socket should be persistent, false otherwise
*/
public function getPersistentSocket()
{
@@ -191,7 +201,7 @@ class Client
/**
* Set the connect timeout
*
- * @param Integer number of milliseconds before connect will timeout
+ * @param int number of milliseconds before connect will timeout
*/
public function setConnectTimeout($timeoutMs)
{
@@ -201,7 +211,7 @@ class Client
/**
* Get the connect timeout
*
- * @return Integer number of milliseconds before connect will timeout
+ * @return int number of milliseconds before connect will timeout
*/
public function getConnectTimeout()
{
@@ -211,7 +221,7 @@ class Client
/**
* Set the read/write timeout
*
- * @param Integer number of milliseconds before read or write call will timeout
+ * @param int number of milliseconds before read or write call will timeout
*/
public function setReadWriteTimeout($timeoutMs)
{
@@ -222,7 +232,7 @@ class Client
/**
* Get the read timeout
*
- * @return Integer number of milliseconds before read will timeout
+ * @return int number of milliseconds before read will timeout
*/
public function getReadWriteTimeout()
{
@@ -232,14 +242,18 @@ class Client
/**
* Helper to avoid duplicating milliseconds to secs/usecs in a few places
*
- * @param Integer millisecond timeout
- * @return Boolean
+ * @param int millisecond timeout
+ * @return bool
*/
private function set_ms_timeout($timeoutMs) {
if (!$this->_sock) {
return false;
}
- return stream_set_timeout($this->_sock, floor($timeoutMs / 1000), ($timeoutMs % 1000) * 1000);
+ return stream_set_timeout(
+ $this->_sock,
+ floor($timeoutMs / 1000),
+ ($timeoutMs % 1000) * 1000
+ );
}
@@ -250,9 +264,21 @@ class Client
{
if (!$this->_sock) {
if ($this->_persistentSocket) {
- $this->_sock = pfsockopen($this->_host, $this->_port, $errno, $errstr, $this->_connectTimeout/1000);
+ $this->_sock = pfsockopen(
+ $this->_host,
+ $this->_port,
+ $errno,
+ $errstr,
+ $this->_connectTimeout/1000
+ );
} else {
- $this->_sock = fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_connectTimeout/1000);
+ $this->_sock = fsockopen(
+ $this->_host,
+ $this->_port,
+ $errno,
+ $errstr,
+ $this->_connectTimeout/1000
+ );
}
if (!$this->_sock) {
@@ -268,9 +294,10 @@ class Client
/**
* Build a FastCGI packet
*
- * @param Integer $type Type of the packet
- * @param String $content Content of the packet
- * @param Integer $requestId RequestId
+ * @param int $type Type of the packet
+ * @param string $content Content of the packet
+ * @param int $requestId RequestId
+ * @return string
*/
private function buildPacket($type, $content, $requestId = 1)
{
@@ -289,9 +316,9 @@ class Client
/**
* Build an FastCGI Name value pair
*
- * @param String $name Name
- * @param String $value Value
- * @return String FastCGI Name value pair
+ * @param string $name Name
+ * @param string $value Value
+ * @return string FastCGI Name value pair
*/
private function buildNvpair($name, $value)
{
@@ -302,14 +329,16 @@ class Client
$nvpair = chr($nlen);
} else {
/* nameLengthB3 & nameLengthB2 & nameLengthB1 & nameLengthB0 */
- $nvpair = chr(($nlen >> 24) | 0x80) . chr(($nlen >> 16) & 0xFF) . chr(($nlen >> 8) & 0xFF) . chr($nlen & 0xFF);
+ $nvpair = chr(($nlen >> 24) | 0x80) . chr(($nlen >> 16) & 0xFF)
+ . chr(($nlen >> 8) & 0xFF) . chr($nlen & 0xFF);
}
if ($vlen < 128) {
/* valueLengthB0 */
$nvpair .= chr($vlen);
} else {
/* valueLengthB3 & valueLengthB2 & valueLengthB1 & valueLengthB0 */
- $nvpair .= chr(($vlen >> 24) | 0x80) . chr(($vlen >> 16) & 0xFF) . chr(($vlen >> 8) & 0xFF) . chr($vlen & 0xFF);
+ $nvpair .= chr(($vlen >> 24) | 0x80) . chr(($vlen >> 16) & 0xFF)
+ . chr(($vlen >> 8) & 0xFF) . chr($vlen & 0xFF);
}
/* nameData & valueData */
return $nvpair . $name . $value;
@@ -318,7 +347,7 @@ class Client
/**
* Read a set of FastCGI Name value pairs
*
- * @param String $data Data containing the set of FastCGI NVPair
+ * @param string $data Data containing the set of FastCGI NVPair
* @return array of NVPair
*/
private function readNvpair($data, $length = null)
@@ -357,7 +386,7 @@ class Client
/**
* Decode a FastCGI Packet
*
- * @param String $data String containing all the packet
+ * @param string $data string containing all the packet
* @return array
*/
private function decodePacketHeader($data)
@@ -403,6 +432,7 @@ class Client
*
* @param array $requestedInfo information to retrieve
* @return array
+ * @throws \Exception
*/
public function getValues(array $requestedInfo)
{
@@ -423,11 +453,14 @@ class Client
}
/**
- * Execute a request to the FastCGI application
+ * Execute a request to the FastCGI application and return response body
*
* @param array $params Array of parameters
- * @param String $stdin Content
- * @return String
+ * @param string $stdin Content
+ * @return string
+ * @throws ForbiddenException
+ * @throws TimedOutException
+ * @throws \Exception
*/
public function request(array $params, $stdin)
{
@@ -435,20 +468,38 @@ class Client
return $this->wait_for_response($id);
}
+ /**
+ * Execute a request to the FastCGI application and return request data
+ *
+ * @param array $params Array of parameters
+ * @param string $stdin Content
+ * @return array
+ * @throws ForbiddenException
+ * @throws TimedOutException
+ * @throws \Exception
+ */
+ public function request_data(array $params, $stdin)
+ {
+ $id = $this->async_request($params, $stdin);
+ return $this->wait_for_response_data($id);
+ }
+
/**
* Execute a request to the FastCGI application asyncronously
- *
+ *
* This sends request to application and returns the assigned ID for that request.
*
* You should keep this id for later use with wait_for_response(). Ids are chosen randomly
- * rather than seqentially to guard against false-positives when using persistent sockets.
- * In that case it is possible that a delayed response to a request made by a previous script
- * invocation comes back on this socket and is mistaken for response to request made with same ID
- * during this request.
+ * rather than sequentially to guard against false-positives when using persistent sockets.
+ * In that case it is possible that a delayed response to a request made by a previous script
+ * invocation comes back on this socket and is mistaken for response to request made with same
+ * ID during this request.
*
* @param array $params Array of parameters
- * @param String $stdin Content
- * @return Integer
+ * @param string $stdin Content
+ * @return int
+ * @throws TimedOutException
+ * @throws \Exception
*/
public function async_request(array $params, $stdin)
{
@@ -460,10 +511,12 @@ class Client
// Using persistent sockets implies you want them keept alive by server!
$keepAlive = intval($this->_keepAlive || $this->_persistentSocket);
- $request = $this->buildPacket(self::BEGIN_REQUEST
- ,chr(0) . chr(self::RESPONDER) . chr($keepAlive) . str_repeat(chr(0), 5)
- ,$id
- );
+ $request = $this->buildPacket(
+ self::BEGIN_REQUEST,
+ chr(0) . chr(self::RESPONDER) . chr($keepAlive)
+ . str_repeat(chr(0), 5),
+ $id
+ );
$paramsRequest = '';
foreach ($params as $key => $value) {
@@ -494,21 +547,26 @@ class Client
$this->_requests[$id] = array(
'state' => self::REQ_STATE_WRITTEN,
- 'response' => null
+ 'response' => null,
+ 'err_response' => null,
+ 'out_response' => null,
);
return $id;
}
/**
- * Blocking call that waits for response to specific request
- *
- * @param Integer $requestId
- * @param Integer $timeoutMs [optional] the number of milliseconds to wait. Defaults to the ReadWriteTimeout value set.
- * @return string response body
+ * Blocking call that waits for response data of the specific request
+ *
+ * @param int $requestId
+ * @param int $timeoutMs [optional] the number of milliseconds to wait.
+ * @return array response data
+ * @throws ForbiddenException
+ * @throws TimedOutException
+ * @throws \Exception
*/
- public function wait_for_response($requestId, $timeoutMs = 0) {
-
+ public function wait_for_response_data($requestId, $timeoutMs = 0)
+ {
if (!isset($this->_requests[$requestId])) {
throw new \Exception('Invalid request id given');
}
@@ -537,12 +595,15 @@ class Client
if ($resp['type'] == self::STDOUT || $resp['type'] == self::STDERR) {
if ($resp['type'] == self::STDERR) {
$this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_ERR;
+ $this->_requests[$resp['requestId']]['err_response'] .= $resp['content'];
+ } else {
+ $this->_requests[$resp['requestId']]['out_response'] .= $resp['content'];
}
$this->_requests[$resp['requestId']]['response'] .= $resp['content'];
}
if ($resp['type'] == self::END_REQUEST) {
$this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_OK;
- if ($resp['requestId'] == $requestId) {
+ if ($resp['requestId'] == $requestId) {
break;
}
}
@@ -586,7 +647,22 @@ class Client
throw new \Exception('Role value not known [UNKNOWN_ROLE]');
break;
case self::REQUEST_COMPLETE:
- return $this->_requests[$requestId]['response'];
+ return $this->_requests[$requestId];
}
}
+
+ /**
+ * Blocking call that waits for response to specific request
+ *
+ * @param int $requestId
+ * @param int $timeoutMs [optional] the number of milliseconds to wait.
+ * @return string The response content.
+ * @throws ForbiddenException
+ * @throws TimedOutException
+ * @throws \Exception
+ */
+ public function wait_for_response($requestId, $timeoutMs = 0)
+ {
+ return $this->wait_for_response_data($requestId, $timeoutMs)['response'];
+ }
}
diff --git a/sapi/fpm/tests/logtool.inc b/sapi/fpm/tests/logtool.inc
new file mode 100644
index 00000000..12744033
--- /dev/null
+++ b/sapi/fpm/tests/logtool.inc
@@ -0,0 +1,495 @@
+message = ($repeat > 0) ? str_repeat($message, $repeat) : $message;
+ $this->limit = $limit;
+ $this->position = 0;
+ }
+
+ /**
+ * @param string $level
+ * @return int
+ */
+ public function setExpectedLevel(string $level)
+ {
+ return $this->level = $level;
+ }
+
+ /**
+ * @return string
+ */
+ public function getExpectedLevel(): string
+ {
+ return $this->level ?: 'WARNING';
+ }
+
+ /**
+ * @param bool $pipeClosed
+ */
+ public function setPipeClosed(bool $pipeClosed)
+ {
+ $this->pipeClosed = $pipeClosed;
+ }
+
+ /**
+ * @param string $line
+ * @return bool
+ */
+ public function checkTruncatedMessage(string $line)
+ {
+ if ($this->message === null) {
+ throw new \LogicException('The message has not been set');
+ }
+ $lineLen = strlen($line);
+ if (!$this->checkLineLength($line)) {
+ return false;
+ }
+ $this->pattern = '/^PHP message: (.*?)(\.\.\.)?$/';
+ if (preg_match($this->pattern, $line, $matches) === 0) {
+ return $this->error("Unexpected truncated message: {$line}");
+ }
+
+ if ($lineLen === $this->limit - strlen('NOTICE: ') - 1) {
+ if (!isset($matches[2])) {
+ return $this->error("The truncated line is not ended with '...'");
+ }
+ if (!$this->checkMessage($matches[1])) {
+ return false;
+ }
+ } else {
+ if (isset($matches[2])) {
+ // this is expecting that the expected message does not end with '...'
+ // which should not be an issue for the test purpose.
+ return $this->error("The line is complete and should not end with '...'");
+ }
+ if (!$this->checkMessage($matches[1], -1)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @param array $lines
+ * @param bool $terminated
+ * @param bool $decorated
+ * @return bool
+ */
+ public function checkWrappedMessage(array $lines, bool $terminated = true, bool $decorated = true, bool $is_stderr = true)
+ {
+ if ($this->message === null) {
+ throw new \LogicException('The message has not been set');
+ }
+ if ($decorated) {
+ $this->pattern = sprintf(
+ '/^(%s %s: %s)"([^"]*)"(.*)?$/',
+ self::P_TIME,
+ $this->getExpectedLevel(),
+ $is_stderr ? self::P_PREFIX : self::P_PREFIX_STDOUT
+ );
+ } else {
+ $this->pattern = null;
+ }
+
+ $idx = 0;
+ foreach ($lines as $idx => $line) {
+ if (!$this->checkLine($line)) {
+ break;
+ }
+ }
+
+ if ($this->suffixPosition > 0) {
+ $suffixPattern = sprintf(
+ '/^%s %s: %s(.*)$/',
+ self::P_TIME, $this->getExpectedLevel(),
+ $is_stderr ? self::P_PREFIX : self::P_PREFIX_STDOUT
+ );
+ $line = $lines[++$idx];
+ if (preg_match($suffixPattern, $line, $matches) === 0) {
+ return $this->error("Unexpected line: $line");
+ }
+ if ($matches[1] !== substr(self::FINAL_SUFFIX, $this->suffixPosition)) {
+ return $this->error(
+ "The suffix has not been finished from position $this->suffixPosition in line: $line"
+ );
+ }
+ }
+
+ if ($terminated) {
+ return $this->expectTerminatorLines($lines, $idx);
+ }
+
+ return true;
+ }
+
+ /**
+ * @param string $line
+ * @return bool
+ */
+ private function checkLine(string $line)
+ {
+ if ($this->pattern === null) {
+ // plain (not decorated) output
+ $out = rtrim($line);
+ $finalSuffix = null;
+ } elseif (($res = preg_match($this->pattern, $line, $matches)) > 0) {
+ $out = $matches[2];
+ $finalSuffix = $matches[3] ?? false;
+ } else {
+ return $this->error("Unexpected line: $line");
+ }
+
+ $rem = strlen($this->message) - $this->position;
+ $lineLen = strlen($line);
+ if (!$this->checkLineLength($line, $lineLen)) {
+ return false;
+ }
+ if (!$this->checkMessage($out, $this->position)) {
+ return false;
+ }
+ $outLen = strlen($out);
+ if ($rem > $outLen) { // continuous line
+ if ($lineLen !== $this->limit) {
+ if ($lineLen + ($rem - $outLen) < $this->limit) {
+ return $this->error("Printed less than the message len");
+ }
+ return $this->error(
+ "The continuous line length is $lineLen but it should equal to limit $this->limit"
+ );
+ }
+ $this->position += $outLen;
+ return true;
+ }
+ if ($rem !== $outLen) {
+ return $this->error("Printed more than the message len");
+ }
+ if (!$this->pipeClosed || $finalSuffix === null) {
+ return false;
+ }
+ if ($finalSuffix === false) {
+ return $this->error("No final suffix");
+ }
+ if (empty($finalSuffix) || strpos(self::FINAL_SUFFIX, $finalSuffix) === false) {
+ return $this->error("The final suffix has to be equal to ', pipe is closed'");
+ }
+ if (self::FINAL_SUFFIX !== $finalSuffix) {
+ $this->suffixPosition = strlen($finalSuffix);
+ }
+ // complete final suffix printed
+ return false;
+ }
+
+ /**
+ * @param string $line
+ * @param int $lineLen
+ * @return bool
+ */
+ private function checkLineLength(string $line, $lineLen = null) {
+ $lineLen = $lineLen ?: strlen($line);
+ if ($lineLen > $this->limit) {
+ return $this->error(
+ "The line length is $lineLen which is higher than limit $this->limit"
+ );
+ }
+
+ return true;
+ }
+
+ /**
+ * @param string $matchedMessage
+ * @param int $expectedMessageStart
+ * @return bool
+ */
+ private function checkMessage(string $matchedMessage, int $expectedMessageStart = 0)
+ {
+ if ($expectedMessageStart < 0) {
+ $expectedMessage = $this->message;
+ } else {
+ $expectedMessage = substr($this->message, $expectedMessageStart, strlen($matchedMessage));
+ }
+ if ($expectedMessage !== $matchedMessage) {
+ return $this->error(
+ sprintf(
+ "The actual string(%d) does not match expected string(%d):\n",
+ strlen($matchedMessage),
+ strlen($expectedMessage)
+ ) .
+ "- EXPECT: '$expectedMessage'\n" .
+ "- ACTUAL: '$matchedMessage'"
+ );
+ }
+
+ return true;
+ }
+
+ /**
+ * @param array $lines
+ * @return bool
+ */
+ public function expectStartingLines(array $lines)
+ {
+ if ($this->getError()) {
+ return false;
+ }
+
+ if (count($lines) < 2) {
+ return $this->error("No starting lines");
+ }
+
+ return (
+ $this->expectNotice($lines[0], 'fpm is running, pid \d+') &&
+ $this->expectNotice($lines[1], 'ready to handle connections')
+ );
+ }
+
+ /**
+ * @param array $lines
+ * @param int $idx
+ * @return bool
+ */
+ public function expectTerminatorLines(array $lines, int $idx = -1)
+ {
+ if ($this->getError()) {
+ return false;
+ }
+
+ if (count($lines) - $idx < 3) {
+ return $this->error("No terminating lines");
+ }
+
+ return (
+ $this->expectNotice($lines[++$idx], 'Terminating ...') &&
+ $this->expectNotice($lines[++$idx], 'exiting, bye-bye!')
+ );
+ }
+
+ /**
+ * @param string $type
+ * @param string $line
+ * @param string $expectedMessage
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectEntry(string $type, string $line, string $expectedMessage, $pool = null)
+ {
+ if ($this->getError()) {
+ return false;
+ }
+ if ($pool !== null) {
+ $expectedMessage = '\[pool ' . $pool . '\] ' . $expectedMessage;
+ }
+
+ // Allow expected message to contain %s and %s for any string or number
+ // as in run-tests.php
+ $expectRe = str_replace('%s', '[^\r\n]+', $expectedMessage);
+ $expectRe = str_replace('%d', '\d+', $expectRe);
+
+ $line = rtrim($line);
+ $pattern = sprintf('/^%s %s: %s$/', self::P_TIME, $type, $expectRe);
+
+ if (preg_match($pattern, $line, $matches) === 0) {
+ return $this->error(
+ "The $type does not match expected message:\n" .
+ "- PATTERN: $pattern\n" .
+ "- MESSAGE: $line\n" .
+ "- EXPECT: '$expectedMessage'\n" .
+ "- ACTUAL: '" . substr($line, strpos($line, $type) + strlen($type) + 2) . "'"
+ );
+ }
+
+ return true;
+ }
+
+ /**
+ * @param string $line
+ * @param string $expectedMessage
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectDebug(string $line, string $expectedMessage, $pool = null)
+ {
+ return $this->expectEntry('DEBUG', $line, $expectedMessage, $pool);
+ }
+
+ /**
+ * @param string $line
+ * @param string $expectedMessage
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectNotice(string $line, string $expectedMessage, $pool = null)
+ {
+ return $this->expectEntry('NOTICE', $line, $expectedMessage, $pool);
+ }
+
+ /**
+ * @param string $line
+ * @param string $expectedMessage
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectWarning(string $line, string $expectedMessage, $pool = null)
+ {
+ return $this->expectEntry('WARNING', $line, $expectedMessage, $pool);
+ }
+
+ /**
+ * @param string $line
+ * @param string $expectedMessage
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectError(string $line, string $expectedMessage, $pool = null)
+ {
+ return $this->expectEntry('ERROR', $line, $expectedMessage, $pool);
+ }
+
+ /**
+ * @param string $line
+ * @param string $expectedMessage
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectAlert(string $line, string $expectedMessage, $pool = null)
+ {
+ return $this->expectEntry('ALERT', $line, $expectedMessage, $pool);
+ }
+
+
+ /**
+ * @param string $msg
+ * @return bool
+ */
+ private function error(string $msg)
+ {
+ $this->error = $msg;
+ echo "ERROR: $msg\n";
+ return false;
+ }
+
+ /**
+ * @return string
+ */
+ public function getError()
+ {
+ return $this->error;
+ }
+}
+
+if (isset($argv[1]) && $argv[1] === 'logtool-selftest') {
+ $cases = [
+ [
+ 'limit' => 1050,
+ 'lines' => [
+ '[08-Oct-2017 19:53:50] WARNING: [pool unconfined] child 23183 said into stderr: "' .
+ str_repeat('a', 968) . '"',
+ '[08-Oct-2017 19:53:50] WARNING: [pool unconfined] child 23183 said into stderr: "' .
+ str_repeat('a', 968) . '"',
+ '[08-Oct-2017 19:53:50] WARNING: [pool unconfined] child 23183 said into stderr: "' .
+ str_repeat('a', 112) . '", pipe is closed',
+ '[08-Oct-2017 19:53:55] NOTICE: Terminating ...',
+ '[08-Oct-2017 19:53:55] NOTICE: exiting, bye-bye!',
+ ],
+ 'message' => str_repeat('a', 2048),
+ 'type' => 'stdio',
+ ],
+ [
+ 'limit' => 1050,
+ 'lines' => [
+ '[08-Oct-2017 19:53:50] WARNING: [pool unconfined] child 23183 said into stderr: "' .
+ str_repeat('a', 968) . '"',
+ '[08-Oct-2017 19:53:50] WARNING: [pool unconfined] child 23183 said into stderr: "' .
+ str_repeat('a', 968) . '"',
+ '[08-Oct-2017 19:53:50] WARNING: [pool unconfined] child 23183 said into stderr: "' .
+ str_repeat('a', 964) . '", pi',
+ '[08-Oct-2017 19:53:50] WARNING: [pool unconfined] child 23183 said into stderr: pe is closed',
+ '[08-Oct-2017 19:53:55] NOTICE: Terminating ...',
+ '[08-Oct-2017 19:53:55] NOTICE: exiting, bye-bye!',
+ ],
+ 'message' => str_repeat('a', 2900),
+ 'type' => 'stdio',
+ ],
+ [
+ 'limit' => 1024,
+ 'line' => '[08-Oct-2017 19:53:50] WARNING: ' . str_repeat('a',989) . '...',
+ 'message' => str_repeat('a', 2900),
+ 'type' => 'message',
+ ],
+ [
+ 'limit' => 1024,
+ 'line' => '[08-Oct-2017 19:53:50] WARNING: ' . str_repeat('a',20),
+ 'message' => str_repeat('a', 20),
+ 'type' => 'message',
+ ],
+ ];
+ foreach ($cases as $case) {
+ printf("Test message with len %d and limit %d: ", strlen($case['message']), $case['limit']);
+ $logTool = new LogTool();
+ $logTool->setExpectedMessage($case['message'], $case['limit']);
+ if ($case['type'] === 'stdio') {
+ $logTool->checkWrappedMessage($case['lines']);
+ } else {
+ $logTool->checkTruncatedMessage($case['line']);
+ }
+ if (!$logTool->getError()) {
+ echo "OK\n";
+ }
+ }
+ echo "Done\n";
+}
diff --git a/sapi/fpm/tests/response.inc b/sapi/fpm/tests/response.inc
new file mode 100644
index 00000000..54f85bcf
--- /dev/null
+++ b/sapi/fpm/tests/response.inc
@@ -0,0 +1,281 @@
+ $data,
+ 'err_response' => null,
+ 'out_response' => $data,
+ ];
+ }
+
+ $this->data = $data;
+ $this->expectInvalid = $expectInvalid;
+ }
+
+ /**
+ * @param mixed $body
+ * @param string $contentType
+ * @return Response
+ */
+ public function expectBody($body, $contentType = 'text/html')
+ {
+ if ($multiLine = is_array($body)) {
+ $body = implode("\n", $body);
+ }
+
+ if (
+ $this->checkIfValid() &&
+ $this->checkDefaultHeaders($contentType) &&
+ $body !== $this->rawBody
+ ) {
+ if ($multiLine) {
+ $this->error(
+ "==> The expected body:\n$body\n" .
+ "==> does not match the actual body:\n$this->rawBody"
+ );
+ } else {
+ $this->error(
+ "The expected body '$body' does not match actual body '$this->rawBody'"
+ );
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * @return Response
+ */
+ public function expectEmptyBody()
+ {
+ return $this->expectBody('');
+ }
+
+ /**
+ * @param string $contentType
+ * @return string|null
+ */
+ public function getBody($contentType = 'text/html')
+ {
+ if ($this->checkIfValid() && $this->checkDefaultHeaders($contentType)) {
+ return $this->rawBody;
+ }
+
+ return null;
+ }
+
+ /**
+ * Print raw body
+ */
+ public function dumpBody()
+ {
+ var_dump($this->getBody());
+ }
+
+ /**
+ * Print raw body
+ */
+ public function printBody()
+ {
+ echo $this->getBody() . "\n";
+ }
+
+ /**
+ * Debug response output
+ */
+ public function debugOutput()
+ {
+ echo "-------------- RESPONSE: --------------\n";
+ echo "OUT:\n";
+ echo $this->data['out_response'];
+ echo "ERR:\n";
+ echo $this->data['err_response'];
+ echo "---------------------------------------\n\n";
+ }
+
+ /**
+ * @return string|null
+ */
+ public function getErrorData()
+ {
+ return $this->data['err_response'];
+ }
+
+ /**
+ * Check if the response is valid and if not emit error message
+ *
+ * @return bool
+ */
+ private function checkIfValid()
+ {
+ if ($this->isValid()) {
+ return true;
+ }
+
+ if (!$this->expectInvalid) {
+ $this->error("The response is invalid: $this->rawData");
+ }
+
+ return false;
+ }
+
+ /**
+ * @param string $contentType
+ * @return bool
+ */
+ private function checkDefaultHeaders($contentType)
+ {
+ // check default headers
+ return (
+ $this->checkHeader('X-Powered-By', '|^PHP/7|', true) &&
+ $this->checkHeader('Content-type', '|^' . $contentType . '(;\s?charset=\w+)?|', true)
+ );
+ }
+
+ /**
+ * @param string $name
+ * @param string $value
+ * @param bool $useRegex
+ * @return bool
+ */
+ private function checkHeader(string $name, string $value, $useRegex = false)
+ {
+ $lcName = strtolower($name);
+ $headers = $this->getHeaders();
+ if (!isset($headers[$lcName])) {
+ return $this->error("The header $name is not present");
+ }
+ $header = $headers[$lcName];
+
+ if (!$useRegex) {
+ if ($header === $value) {
+ return true;
+ }
+ return $this->error("The header $name value '$header' is not the same as '$value'");
+ }
+
+ if (!preg_match($value, $header)) {
+ return $this->error("The header $name value '$header' does not match RegExp '$value'");
+ }
+
+ return true;
+ }
+
+ /**
+ * @return array|null
+ */
+ private function getHeaders()
+ {
+ if (!$this->isValid()) {
+ return null;
+ }
+
+ if (is_array($this->headers)) {
+ return $this->headers;
+ }
+
+ $headerRows = explode("\r\n", $this->rawHeaders);
+ $headers = [];
+ foreach ($headerRows as $headerRow) {
+ $colonPosition = strpos($headerRow, ':');
+ if ($colonPosition === false) {
+ $this->error("Invalid header row (no colon): $headerRow");
+ }
+ $headers[strtolower(substr($headerRow, 0, $colonPosition))] = trim(
+ substr($headerRow, $colonPosition + 1)
+ );
+ }
+
+ return ($this->headers = $headers);
+ }
+
+ /**
+ * @return bool
+ */
+ private function isValid()
+ {
+ if ($this->valid === null) {
+ $this->processData();
+ }
+
+ return $this->valid;
+ }
+
+ /**
+ * Process data and set validity and raw data
+ */
+ private function processData()
+ {
+ $this->rawData = $this->data['out_response'];
+ $this->valid = (
+ !is_null($this->rawData) &&
+ strpos($this->rawData, self::HEADER_SEPARATOR)
+ );
+ if ($this->valid) {
+ list ($this->rawHeaders, $this->rawBody) = array_map(
+ 'trim',
+ explode(self::HEADER_SEPARATOR, $this->rawData)
+ );
+ }
+ }
+
+ /**
+ * Emit error message
+ *
+ * @param string $message
+ * @return bool
+ */
+ private function error($message)
+ {
+ echo "ERROR: $message\n";
+
+ return false;
+ }
+}
diff --git a/sapi/fpm/tests/tester.inc b/sapi/fpm/tests/tester.inc
new file mode 100644
index 00000000..4ddee842
--- /dev/null
+++ b/sapi/fpm/tests/tester.inc
@@ -0,0 +1,1352 @@
+testConfig();
+ if ($testResult !== null) {
+ self::clean(2);
+ die("skip $testResult");
+ }
+ }
+
+ /**
+ * Skip test if IPv6 is not supported.
+ */
+ static public function skipIfIPv6IsNotSupported()
+ {
+ @stream_socket_client('tcp://[::1]:0', $errno);
+ if ($errno != 111) {
+ die('skip IPv6 is not supported.');
+ }
+ }
+
+ /**
+ * Skip if running on Travis.
+ *
+ * @param $message
+ */
+ static public function skipIfTravis($message)
+ {
+ if (getenv("TRAVIS")) {
+ die('skip Travis: ' . $message);
+ }
+ }
+
+ /**
+ * Skip if not running as root.
+ */
+ static public function skipIfNotRoot()
+ {
+ if (getmyuid() != 0) {
+ die('skip not running as root');
+ }
+ }
+
+ /**
+ * Skip if running as root.
+ */
+ static public function skipIfRoot()
+ {
+ if (getmyuid() == 0) {
+ die('skip running as root');
+ }
+ }
+
+ /**
+ * Skip if posix extension not loaded.
+ */
+ static public function skipIfPosixNotLoaded()
+ {
+ if (!extension_loaded('posix')) {
+ die('skip posix extension not loaded');
+ }
+ }
+
+ /**
+ * Tester constructor.
+ *
+ * @param string|array $configTemplate
+ * @param string $code
+ * @param array $options
+ * @param string $fileName
+ */
+ public function __construct(
+ $configTemplate,
+ string $code = '',
+ array $options = [],
+ $fileName = null
+ ) {
+ $this->configTemplate = $configTemplate;
+ $this->code = $code;
+ $this->options = $options;
+ $this->fileName = $fileName ?: self::getCallerFileName();
+ $this->logTool = new LogTool();
+ $this->debug = (bool) getenv('TEST_FPM_DEBUG');
+ }
+
+ /**
+ * @param string $ini
+ */
+ public function setUserIni(string $ini)
+ {
+ $iniFile = __DIR__ . '/.user.ini';
+ file_put_contents($iniFile, $ini);
+ }
+
+ /**
+ * Test configuration file.
+ *
+ * @return null|string
+ * @throws \Exception
+ */
+ public function testConfig()
+ {
+ $configFile = $this->createConfig();
+ $cmd = self::findExecutable() . ' -t -y ' . $configFile . ' 2>&1';
+ exec($cmd, $output, $code);
+ if ($code) {
+ return preg_replace("/\[.+?\]/", "", $output[0]);
+ }
+
+ return null;
+ }
+
+ /**
+ * Start PHP-FPM master process
+ *
+ * @param string $extraArgs
+ * @return bool
+ * @throws \Exception
+ */
+ public function start(string $extraArgs = '')
+ {
+ $configFile = $this->createConfig();
+ $desc = $this->outDesc ? [] : [1 => array('pipe', 'w')];
+ $asRoot = getenv('TEST_FPM_RUN_AS_ROOT') ? '--allow-to-run-as-root' : '';
+ $cmd = self::findExecutable() . " $asRoot -F -O -y $configFile $extraArgs";
+ /* Since it's not possible to spawn a process under linux without using a
+ * shell in php (why?!?) we need a little shell trickery, so that we can
+ * actually kill php-fpm */
+ $this->masterProcess = proc_open(
+ "killit () { kill \$child 2> /dev/null; }; " .
+ "trap killit TERM; $cmd 2>&1 & child=\$!; wait",
+ $desc,
+ $pipes
+ );
+ register_shutdown_function(
+ function($masterProcess) use($configFile) {
+ @unlink($configFile);
+ if (is_resource($masterProcess)) {
+ @proc_terminate($masterProcess);
+ while (proc_get_status($masterProcess)['running']) {
+ usleep(10000);
+ }
+ }
+ },
+ $this->masterProcess
+ );
+ if (!$this->outDesc !== false) {
+ $this->outDesc = $pipes[1];
+ }
+
+ return true;
+ }
+
+ /**
+ * Run until needle is found in the log.
+ *
+ * @param string $needle
+ * @param int $max
+ * @return bool
+ * @throws \Exception
+ */
+ public function runTill(string $needle, $max = 10)
+ {
+ $this->start();
+ $found = false;
+ for ($i = 0; $i < $max; $i++) {
+ $line = $this->getLogLine();
+ if (is_null($line)) {
+ break;
+ }
+ if (preg_match($needle, $line) === 1) {
+ $found = true;
+ break;
+ }
+ }
+ $this->close(true);
+
+ if (!$found) {
+ return $this->error("The search pattern not found");
+ }
+
+ return true;
+ }
+
+ /**
+ * Check if connection works.
+ *
+ * @param string $host
+ * @param null|string $successMessage
+ * @param null|string $errorMessage
+ * @param int $attempts
+ * @param int $delay
+ */
+ public function checkConnection(
+ $host = '127.0.0.1',
+ $successMessage = null,
+ $errorMessage = 'Connection failed',
+ $attempts = 20,
+ $delay = 50000
+ ) {
+ $i = 0;
+ do {
+ if ($i > 0 && $delay > 0) {
+ usleep($delay);
+ }
+ $fp = @fsockopen($host, $this->getPort());
+ } while ((++$i < $attempts) && !$fp);
+
+ if ($fp) {
+ $this->message($successMessage);
+ fclose($fp);
+ } else {
+ $this->message($errorMessage);
+ }
+ }
+
+
+ /**
+ * Execute request with parameters ordered for better checking.
+ *
+ * @param string $address
+ * @param string|null $successMessage
+ * @param string|null $errorMessage
+ * @param string $uri
+ * @param string $query
+ * @param array $headers
+ * @return Response
+ */
+ public function checkRequest(
+ string $address,
+ string $successMessage = null,
+ string $errorMessage = null,
+ $uri = '/ping',
+ $query = '',
+ $headers = []
+ ) {
+ return $this->request($query, $headers, $uri, $address, $successMessage, $errorMessage);
+ }
+
+ /**
+ * Execute and check ping request.
+ *
+ * @param string $address
+ * @param string $pingPath
+ * @param string $pingResponse
+ */
+ public function ping(
+ string $address = '{{ADDR}}',
+ string $pingResponse = 'pong',
+ string $pingPath = '/ping'
+ ) {
+ $response = $this->request('', [], $pingPath, $address);
+ $response->expectBody($pingResponse, 'text/plain');
+ }
+
+ /**
+ * Execute and check status request(s).
+ *
+ * @param array $expectedFields
+ * @param string|null $address
+ * @param string $statusPath
+ * @param mixed $formats
+ * @throws \Exception
+ */
+ public function status(
+ array $expectedFields,
+ string $address = null,
+ string $statusPath = '/status',
+ $formats = ['plain', 'html', 'xml', 'json']
+ ) {
+ if (!is_array($formats)) {
+ $formats = [$formats];
+ }
+
+ require_once "status.inc";
+ $status = new Status();
+ foreach ($formats as $format) {
+ $query = $format === 'plain' ? '' : $format;
+ $response = $this->request($query, [], $statusPath, $address);
+ $status->checkStatus($response, $expectedFields, $format);
+ }
+ }
+
+ /**
+ * Get request params array.
+ *
+ * @param string $query
+ * @param array $headers
+ * @param string|null $uri
+ * @param string|null $address
+ * @param string|null $successMessage
+ * @param string|null $errorMessage
+ * @param bool $connKeepAlive
+ * @return array
+ */
+ private function getRequestParams(
+ string $query = '',
+ array $headers = [],
+ string $uri = null
+ ) {
+ if (is_null($uri)) {
+ $uri = $this->makeSourceFile();
+ }
+
+ $params = array_merge(
+ [
+ 'GATEWAY_INTERFACE' => 'FastCGI/1.0',
+ 'REQUEST_METHOD' => 'GET',
+ 'SCRIPT_FILENAME' => $uri,
+ 'SCRIPT_NAME' => $uri,
+ 'QUERY_STRING' => $query,
+ 'REQUEST_URI' => $uri . ($query ? '?'.$query : ""),
+ 'DOCUMENT_URI' => $uri,
+ 'SERVER_SOFTWARE' => 'php/fcgiclient',
+ 'REMOTE_ADDR' => '127.0.0.1',
+ 'REMOTE_PORT' => '7777',
+ 'SERVER_ADDR' => '127.0.0.1',
+ 'SERVER_PORT' => '80',
+ 'SERVER_NAME' => php_uname('n'),
+ 'SERVER_PROTOCOL' => 'HTTP/1.1',
+ 'DOCUMENT_ROOT' => __DIR__,
+ 'CONTENT_TYPE' => '',
+ 'CONTENT_LENGTH' => 0
+ ],
+ $headers
+ );
+
+ return array_filter($params, function($value) {
+ return !is_null($value);
+ });
+ }
+
+ /**
+ * Execute request.
+ *
+ * @param string $query
+ * @param array $headers
+ * @param string|null $uri
+ * @param string|null $address
+ * @param string|null $successMessage
+ * @param string|null $errorMessage
+ * @param bool $connKeepAlive
+ * @return Response
+ */
+ public function request(
+ string $query = '',
+ array $headers = [],
+ string $uri = null,
+ string $address = null,
+ string $successMessage = null,
+ string $errorMessage = null,
+ bool $connKeepAlive = false
+ ) {
+ if ($this->hasError()) {
+ return new Response(null, true);
+ }
+
+ $params = $this->getRequestParams($query, $headers, $uri);
+
+ try {
+ $this->response = new Response(
+ $this->getClient($address, $connKeepAlive)->request_data($params, false)
+ );
+ $this->message($successMessage);
+ } catch (\Exception $exception) {
+ if ($errorMessage === null) {
+ $this->error("Request failed", $exception);
+ } else {
+ $this->message($errorMessage);
+ }
+ $this->response = new Response();
+ }
+ if ($this->debug) {
+ $this->response->debugOutput();
+ }
+ return $this->response;
+ }
+
+ /**
+ * Execute multiple requests in parallel.
+ *
+ * @param array|int $requests
+ * @param string|null $address
+ * @param string|null $successMessage
+ * @param string|null $errorMessage
+ * @param bool $connKeepAlive
+ * @return Response[]
+ * @throws \Exception
+ */
+ public function multiRequest(
+ $requests,
+ string $address = null,
+ string $successMessage = null,
+ string $errorMessage = null,
+ bool $connKeepAlive = false
+ ) {
+ if ($this->hasError()) {
+ return new Response(null, true);
+ }
+
+ if (is_numeric($requests)) {
+ $requests = array_fill(0, $requests, []);
+ } elseif (!is_array($requests)) {
+ throw new \Exception('Requests can be either numeric or array');
+ }
+
+ try {
+ $connections = array_map(function ($requestData) use ($address, $connKeepAlive) {
+ $client = $this->getClient($address, $connKeepAlive);
+ $params = $this->getRequestParams(
+ $requestData['query'] ?? '',
+ $requestData['headers'] ?? [],
+ $requestData['uri'] ?? null
+ );
+ return [
+ 'client' => $client,
+ 'requestId' => $client->async_request($params, false),
+ ];
+ }, $requests);
+
+ $responses = array_map(function ($conn) {
+ $response = new Response($conn['client']->wait_for_response_data($conn['requestId']));
+ if ($this->debug) {
+ $response->debugOutput();
+ }
+ return $response;
+ }, $connections);
+ $this->message($successMessage);
+ return $responses;
+ } catch (\Exception $exception) {
+ if ($errorMessage === null) {
+ $this->error("Request failed", $exception);
+ } else {
+ $this->message($errorMessage);
+ }
+ }
+ }
+
+ /**
+ * Get client.
+ *
+ * @param string $address
+ * @param bool $keepAlive
+ * @return Client
+ */
+ private function getClient(string $address = null, $keepAlive = false)
+ {
+ $address = $address ? $this->processTemplate($address) : $this->getAddr();
+ if ($address[0] === '/') { // uds
+ $host = 'unix://' . $address;
+ $port = -1;
+ } elseif ($address[0] === '[') { // ipv6
+ $addressParts = explode(']:', $address);
+ $host = $addressParts[0];
+ if (isset($addressParts[1])) {
+ $host .= ']';
+ $port = $addressParts[1];
+ } else {
+ $port = $this->getPort();
+ }
+ } else { // ipv4
+ $addressParts = explode(':', $address);
+ $host = $addressParts[0];
+ $port = $addressParts[1] ?? $this->getPort();
+ }
+
+ if (!$keepAlive) {
+ return new Client($host, $port);
+ }
+
+ if (!isset($this->clients[$host][$port])) {
+ $client = new Client($host, $port);
+ $client->setKeepAlive(true);
+ $this->clients[$host][$port] = $client;
+ }
+
+ return $this->clients[$host][$port];
+ }
+
+ /**
+ * Display logs
+ *
+ * @param int $number
+ * @param string $ignore
+ */
+ public function displayLog(int $number = 1, string $ignore = 'systemd')
+ {
+ /* Read $number lines or until EOF */
+ while ($number > 0 || ($number < 0 && !feof($this->outDesc))) {
+ $a = fgets($this->outDesc);
+ if (empty($ignore) || !strpos($a, $ignore)) {
+ echo $a;
+ $number--;
+ }
+ }
+ }
+
+ /**
+ * Get a single log line
+ *
+ * @return null|string
+ */
+ private function getLogLine()
+ {
+ $read = [$this->outDesc];
+ $write = null;
+ $except = null;
+ if (stream_select($read, $write, $except, 2 )) {
+ return fgets($this->outDesc);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Get log lines
+ *
+ * @param int $number
+ * @param bool $skipBlank
+ * @param string $ignore
+ * @return array
+ */
+ public function getLogLines(int $number = 1, bool $skipBlank = false, string $ignore = 'systemd')
+ {
+ $lines = [];
+ /* Read $n lines or until EOF */
+ while ($number > 0 || ($number < 0 && !feof($this->outDesc))) {
+ $line = $this->getLogLine();
+ if (is_null($line)) {
+ break;
+ }
+ if ((empty($ignore) || !strpos($line, $ignore)) && (!$skipBlank || strlen(trim($line)) > 0)) {
+ $lines[] = $line;
+ $number--;
+ }
+ }
+
+ return $lines;
+ }
+
+ /**
+ * @return mixed|string
+ */
+ public function getLastLogLine()
+ {
+ $lines = $this->getLogLines();
+
+ return $lines[0] ?? '';
+ }
+
+ /**
+ * @return string
+ */
+ public function getUser()
+ {
+ return get_current_user();
+ }
+
+ /**
+ * @return string
+ */
+ public function getGroup()
+ {
+ return get_current_group();
+ }
+
+ /**
+ * @return int
+ */
+ public function getUid()
+ {
+ return getmyuid();
+ }
+
+ /**
+ * @return int
+ */
+ public function getGid()
+ {
+ return getmygid();
+ }
+
+ /**
+ * Send signal to the supplied PID or the server PID.
+ *
+ * @param string $signal
+ * @param int|null $pid
+ * @return string
+ */
+ public function signal($signal, int $pid = null)
+ {
+ if (is_null($pid)) {
+ $pid = $this->getPid();
+ }
+
+ return exec("kill -$signal $pid");
+ }
+
+ /**
+ * Terminate master process
+ */
+ public function terminate()
+ {
+ proc_terminate($this->masterProcess);
+ }
+
+ /**
+ * Close all open descriptors and process resources
+ *
+ * @param bool $terminate
+ */
+ public function close($terminate = false)
+ {
+ if ($terminate) {
+ $this->terminate();
+ }
+ fclose($this->outDesc);
+ proc_close($this->masterProcess);
+ }
+
+ /**
+ * Create a config file.
+ *
+ * @param string $extension
+ * @return string
+ * @throws \Exception
+ */
+ private function createConfig($extension = 'ini')
+ {
+ if (is_array($this->configTemplate)) {
+ $configTemplates = $this->configTemplate;
+ if (!isset($configTemplates['main'])) {
+ throw new \Exception('The config template array has to have main config');
+ }
+ $mainTemplate = $configTemplates['main'];
+ unset($configTemplates['main']);
+ if (!is_dir(self::CONF_DIR)) {
+ mkdir(self::CONF_DIR);
+ }
+ foreach ($configTemplates as $name => $configTemplate) {
+ $this->makeFile(
+ 'conf',
+ $this->processTemplate($configTemplate),
+ self::CONF_DIR,
+ $name
+ );
+ }
+ } else {
+ $mainTemplate = $this->configTemplate;
+ }
+
+ return $this->makeFile($extension, $this->processTemplate($mainTemplate));
+ }
+
+ /**
+ * Process template string.
+ *
+ * @param string $template
+ * @return string
+ */
+ private function processTemplate(string $template)
+ {
+ $vars = [
+ 'FILE:LOG:ACC' => ['getAbsoluteFile', self::FILE_EXT_LOG_ACC],
+ 'FILE:LOG:ERR' => ['getAbsoluteFile', self::FILE_EXT_LOG_ERR],
+ 'FILE:LOG:SLOW' => ['getAbsoluteFile', self::FILE_EXT_LOG_SLOW],
+ 'FILE:PID' => ['getAbsoluteFile', self::FILE_EXT_PID],
+ 'RFILE:LOG:ACC' => ['getRelativeFile', self::FILE_EXT_LOG_ACC],
+ 'RFILE:LOG:ERR' => ['getRelativeFile', self::FILE_EXT_LOG_ERR],
+ 'RFILE:LOG:SLOW' => ['getRelativeFile', self::FILE_EXT_LOG_SLOW],
+ 'RFILE:PID' => ['getRelativeFile', self::FILE_EXT_PID],
+ 'ADDR:IPv4' => ['getAddr', 'ipv4'],
+ 'ADDR:IPv4:ANY' => ['getAddr', 'ipv4-any'],
+ 'ADDR:IPv6' => ['getAddr', 'ipv6'],
+ 'ADDR:IPv6:ANY' => ['getAddr', 'ipv6-any'],
+ 'ADDR:UDS' => ['getAddr', 'uds'],
+ 'PORT' => ['getPort', 'ip'],
+ 'INCLUDE:CONF' => self::CONF_DIR . '/*.conf',
+ 'USER' => ['getUser'],
+ 'GROUP' => ['getGroup'],
+ 'UID' => ['getUid'],
+ 'GID' => ['getGid'],
+ ];
+ $aliases = [
+ 'ADDR' => 'ADDR:IPv4',
+ 'FILE:LOG' => 'FILE:LOG:ERR',
+ ];
+ foreach ($aliases as $aliasName => $aliasValue) {
+ $vars[$aliasName] = $vars[$aliasValue];
+ }
+
+ return preg_replace_callback(
+ '/{{([a-zA-Z0-9:]+)(\[\w+\])?}}/',
+ function ($matches) use ($vars) {
+ $varName = $matches[1];
+ if (!isset($vars[$varName])) {
+ $this->error("Invalid config variable $varName");
+ return 'INVALID';
+ }
+ $pool = $matches[2] ?? 'default';
+ $varValue = $vars[$varName];
+ if (is_string($varValue)) {
+ return $varValue;
+ }
+ $functionName = array_shift($varValue);
+ $varValue[] = $pool;
+ return call_user_func_array([$this, $functionName], $varValue);
+ },
+ $template
+ );
+ }
+
+ /**
+ * @param string $type
+ * @param string $pool
+ * @return string
+ */
+ public function getAddr(string $type = 'ipv4', $pool = 'default')
+ {
+ $port = $this->getPort($type, $pool, true);
+ if ($type === 'uds') {
+ $address = $this->getFile($port . '.sock');
+
+ // Socket max path length is 108 on Linux and 104 on BSD,
+ // so we use the latter
+ if (strlen($address) <= 104) {
+ return $address;
+ }
+
+ return sys_get_temp_dir().'/'.
+ hash('crc32', dirname($address)).'-'.
+ basename($address);
+ }
+
+ return $this->getHost($type) . ':' . $port;
+ }
+
+ /**
+ * @param string $type
+ * @param string $pool
+ * @param bool $useAsId
+ * @return int
+ */
+ public function getPort(string $type = 'ip', $pool = 'default', $useAsId = false)
+ {
+ if ($type === 'uds' && !$useAsId) {
+ return -1;
+ }
+
+ if (isset($this->ports['values'][$pool])) {
+ return $this->ports['values'][$pool];
+ }
+ $port = ($this->ports['last'] ?? 9000 + PHP_INT_SIZE - 1) + 1;
+ $this->ports['values'][$pool] = $this->ports['last'] = $port;
+
+ return $port;
+ }
+
+ /**
+ * @param string $type
+ * @return string
+ */
+ public function getHost(string $type = 'ipv4')
+ {
+ switch ($type) {
+ case 'ipv6-any':
+ return '[::]';
+ case 'ipv6':
+ return '[::1]';
+ case 'ipv4-any':
+ return '0.0.0.0';
+ default:
+ return '127.0.0.1';
+ }
+ }
+
+ /**
+ * Get listen address.
+ *
+ * @param string|null $template
+ * @return string
+ */
+ public function getListen($template = null)
+ {
+ return $template ? $this->processTemplate($template) : $this->getAddr();
+ }
+
+ /**
+ * Get PID.
+ *
+ * @return int
+ */
+ public function getPid()
+ {
+ $pidFile = $this->getFile('pid');
+ if (!is_file($pidFile)) {
+ return (int) $this->error("PID file has not been created");
+ }
+ $pidContent = file_get_contents($pidFile);
+ if (!is_numeric($pidContent)) {
+ return (int) $this->error("PID content '$pidContent' is not integer");
+ }
+
+ return (int) $pidContent;
+ }
+
+
+ /**
+ * @param string $extension
+ * @param string|null $dir
+ * @param string|null $name
+ * @return string
+ */
+ private function getFile(string $extension, $dir = null, $name = null)
+ {
+ $fileName = (is_null($name) ? $this->fileName : $name . '.') . $extension;
+
+ return is_null($dir) ? $fileName : $dir . '/' . $fileName;
+ }
+
+ /**
+ * @param string $extension
+ * @return string
+ */
+ private function getAbsoluteFile(string $extension)
+ {
+ return $this->getFile($extension);
+ }
+
+ /**
+ * @param string $extension
+ * @return string
+ */
+ private function getRelativeFile(string $extension)
+ {
+ $fileName = rtrim(basename($this->fileName), '.');
+
+ return $this->getFile($extension, null, $fileName);
+ }
+
+ /**
+ * @param string $extension
+ * @param string $prefix
+ * @return string
+ */
+ private function getPrefixedFile(string $extension, string $prefix = null)
+ {
+ $fileName = rtrim($this->fileName, '.');
+ if (!is_null($prefix)) {
+ $fileName = $prefix . '/' . basename($fileName);
+ }
+
+ return $this->getFile($extension, null, $fileName);
+ }
+
+ /**
+ * @param string $extension
+ * @param string $content
+ * @param string|null $dir
+ * @param string|null $name
+ * @return string
+ */
+ private function makeFile(string $extension, string $content = '', $dir = null, $name = null)
+ {
+ $filePath = $this->getFile($extension, $dir, $name);
+ file_put_contents($filePath, $content);
+
+ return $filePath;
+ }
+
+ /**
+ * @return string
+ */
+ public function makeSourceFile()
+ {
+ return $this->makeFile('src.php', $this->code);
+ }
+
+ /**
+ * @param string|null $msg
+ */
+ private function message($msg)
+ {
+ if ($msg !== null) {
+ echo "$msg\n";
+ }
+ }
+
+ /**
+ * @param string $msg
+ * @param \Exception|null $exception
+ */
+ private function error($msg, \Exception $exception = null)
+ {
+ $this->error = 'ERROR: ' . $msg;
+ if ($exception) {
+ $this->error .= '; EXCEPTION: ' . $exception->getMessage();
+ }
+ $this->error .= "\n";
+
+ echo $this->error;
+ }
+
+ /**
+ * @return bool
+ */
+ private function hasError()
+ {
+ return !is_null($this->error) || !is_null($this->logTool->getError());
+ }
+
+ /**
+ * Expect file with a supplied extension to exist.
+ *
+ * @param string $extension
+ * @param string $prefix
+ * @return bool
+ */
+ public function expectFile(string $extension, $prefix = null)
+ {
+ $filePath = $this->getPrefixedFile($extension, $prefix);
+ if (!file_exists($filePath)) {
+ return $this->error("The file $filePath does not exist");
+ }
+
+ return true;
+ }
+
+ /**
+ * Expect file with a supplied extension to not exist.
+ *
+ * @param string $extension
+ * @param string $prefix
+ * @return bool
+ */
+ public function expectNoFile(string $extension, $prefix = null)
+ {
+ $filePath = $this->getPrefixedFile($extension, $prefix);
+ if (file_exists($filePath)) {
+ return $this->error("The file $filePath exists");
+ }
+
+ return true;
+ }
+
+ /**
+ * Expect message to be written to FastCGI error stream.
+ *
+ * @param string $message
+ * @param int $limit
+ * @param int $repeat
+ */
+ public function expectFastCGIErrorMessage(
+ string $message,
+ int $limit = 1024,
+ int $repeat = 0
+ ) {
+ $this->logTool->setExpectedMessage($message, $limit, $repeat);
+ $this->logTool->checkTruncatedMessage($this->response->getErrorData());
+ }
+
+ /**
+ * Expect starting lines to be logged.
+ */
+ public function expectLogStartNotices()
+ {
+ $this->logTool->expectStartingLines($this->getLogLines(2));
+ }
+
+ /**
+ * Expect terminating lines to be logged.
+ */
+ public function expectLogTerminatingNotices()
+ {
+ $this->logTool->expectTerminatorLines($this->getLogLines(-1));
+ }
+
+ /**
+ * Expect log message that can span multiple lines.
+ *
+ * @param string $message
+ * @param int $limit
+ * @param int $repeat
+ * @param bool $decorated
+ * @param bool $wrapped
+ */
+ public function expectLogMessage(
+ string $message,
+ int $limit = 1024,
+ int $repeat = 0,
+ bool $decorated = true,
+ bool $wrapped = true
+ ) {
+ $this->logTool->setExpectedMessage($message, $limit, $repeat);
+ if ($wrapped) {
+ $logLines = $this->getLogLines(-1, true);
+ $this->logTool->checkWrappedMessage($logLines, true, $decorated);
+ } else {
+ $logLines = $this->getLogLines(1, true);
+ $this->logTool->checkTruncatedMessage($logLines[0] ?? '');
+ }
+ if ($this->debug) {
+ $this->message("-------------- LOG LINES: -------------");
+ var_dump($logLines);
+ $this->message("---------------------------------------\n");
+ }
+ }
+
+ /**
+ * Expect a single log line.
+ *
+ * @param string $message
+ * @return bool
+ */
+ public function expectLogLine(string $message, bool $is_stderr = true)
+ {
+ $messageLen = strlen($message);
+ $limit = $messageLen > 1024 ? $messageLen + 16 : 1024;
+ $this->logTool->setExpectedMessage($message, $limit);
+ $logLines = $this->getLogLines(1, true);
+ if ($this->debug) {
+ $this->message("LOG LINE: " . ($logLines[0] ?? ''));
+ }
+
+ return $this->logTool->checkWrappedMessage($logLines, false, true, $is_stderr);
+ }
+
+ /**
+ * Expect a log debug message.
+ *
+ * @param string $message
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectLogDebug(string $message, $pool = null)
+ {
+ return $this->logTool->expectDebug($this->getLastLogLine(), $message, $pool);
+ }
+
+ /**
+ * Expect a log notice.
+ *
+ * @param string $message
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectLogNotice(string $message, $pool = null)
+ {
+ return $this->logTool->expectNotice($this->getLastLogLine(), $message, $pool);
+ }
+
+ /**
+ * Expect a log warning.
+ *
+ * @param string $message
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectLogWarning(string $message, $pool = null)
+ {
+ return $this->logTool->expectWarning($this->getLastLogLine(), $message, $pool);
+ }
+
+ /**
+ * Expect a log error.
+ *
+ * @param string $message
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectLogError(string $message, $pool = null)
+ {
+ return $this->logTool->expectError($this->getLastLogLine(), $message, $pool);
+ }
+
+ /**
+ * Expect a log alert.
+ *
+ * @param string $message
+ * @param string|null $pool
+ * @return bool
+ */
+ public function expectLogAlert(string $message, $pool = null)
+ {
+ return $this->logTool->expectAlert($this->getLastLogLine(), $message, $pool);
+ }
+
+ /**
+ * Expect no log lines to be logged.
+ *
+ * @return bool
+ */
+ public function expectNoLogMessages()
+ {
+ $logLines = $this->getLogLines(-1, true);
+ if (!empty($logLines)) {
+ return $this->error(
+ "Expected no log lines but following lines logged:\n" . implode("\n", $logLines)
+ );
+ }
+
+ return true;
+ }
+
+ /**
+ * Print content of access log.
+ */
+ public function printAccessLog()
+ {
+ $accessLog = $this->getFile('acc.log');
+ if (is_file($accessLog)) {
+ print file_get_contents($accessLog);
+ }
+ }
+}