Improve BIO_socket_wait(), BIO_wait(), BIO_connect_retry(), and their docs
[openssl.git] / crypto / http / http_client.c
1 /*
2  * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright Siemens AG 2018-2020
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #include "e_os.h"
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include "crypto/ctype.h"
15 #include <string.h>
16 #include <openssl/asn1.h>
17 #include <openssl/evp.h>
18 #include <openssl/err.h>
19 #include <openssl/httperr.h>
20 #include <openssl/cmperr.h>
21 #include <openssl/buffer.h>
22 #include <openssl/http.h>
23 #include "internal/sockets.h"
24 #include "internal/cryptlib.h" /* for ossl_assert() */
25
26 #include "http_local.h"
27
28 DEFINE_STACK_OF(CONF_VALUE)
29
30 #define HTTP_PREFIX "HTTP/"
31 #define HTTP_VERSION_PATT "1." /* allow 1.x */
32 #define HTTP_VERSION_STR_LEN 3
33 #define HTTP_LINE1_MINLEN ((int)strlen(HTTP_PREFIX HTTP_VERSION_PATT "x 200\n"))
34 #define HTTP_VERSION_MAX_REDIRECTIONS 50
35
36 #define HTTP_STATUS_CODE_OK                200
37 #define HTTP_STATUS_CODE_MOVED_PERMANENTLY 301
38 #define HTTP_STATUS_CODE_FOUND             302
39
40
41 /* Stateful HTTP request code, supporting blocking and non-blocking I/O */
42
43 /* Opaque HTTP request status structure */
44
45 struct ossl_http_req_ctx_st {
46     int state;                  /* Current I/O state */
47     unsigned char *iobuf;       /* Line buffer */
48     int iobuflen;               /* Line buffer length */
49     BIO *wbio;                  /* BIO to send request to */
50     BIO *rbio;                  /* BIO to read response from */
51     BIO *mem;                   /* Memory BIO response is built into */
52     int method_GET;             /* HTTP method "GET" or "POST" */
53     const char *expected_ct;    /* expected Content-Type, or NULL */
54     int expect_asn1;            /* response must be ASN.1-encoded */
55     unsigned long resp_len;     /* length of response */
56     unsigned long max_resp_len; /* Maximum length of response */
57     time_t max_time;            /* Maximum end time of the transfer, or 0 */
58     char *redirection_url;      /* Location given with HTTP status 301/302 */
59 };
60
61 #define HTTP_DEFAULT_MAX_LINE_LENGTH (4 * 1024)
62 #define HTTP_DEFAULT_MAX_RESP_LEN (100 * 1024)
63
64 /* HTTP states */
65
66 #define OHS_NOREAD          0x1000 /* If set no reading should be performed */
67 #define OHS_ERROR           (0 | OHS_NOREAD) /* Error condition */
68 #define OHS_FIRSTLINE       1 /* First line being read */
69 #define OHS_REDIRECT        0xa /* Looking for redirection location */
70 #define OHS_HEADERS         2 /* MIME headers being read */
71 #define OHS_ASN1_HEADER     3 /* HTTP initial header (tag+length) being read */
72 #define OHS_CONTENT         4 /* HTTP content octets being read */
73 #define OHS_WRITE_INIT     (5 | OHS_NOREAD) /* 1st call: ready to start I/O */
74 #define OHS_WRITE          (6 | OHS_NOREAD) /* Request being sent */
75 #define OHS_FLUSH          (7 | OHS_NOREAD) /* Request being flushed */
76 #define OHS_DONE           (8 | OHS_NOREAD) /* Completed */
77 #define OHS_HTTP_HEADER    (9 | OHS_NOREAD) /* Headers set, w/o final \r\n */
78
79 OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio,
80                                          int method_GET, int maxline,
81                                          unsigned long max_resp_len,
82                                          int timeout,
83                                          const char *expected_content_type,
84                                          int expect_asn1)
85 {
86     OSSL_HTTP_REQ_CTX *rctx;
87
88     if (wbio == NULL || rbio == NULL) {
89         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
90         return NULL;
91     }
92
93     if ((rctx = OPENSSL_zalloc(sizeof(*rctx))) == NULL)
94         return NULL;
95     rctx->state = OHS_ERROR;
96     rctx->iobuflen = maxline > 0 ? maxline : HTTP_DEFAULT_MAX_LINE_LENGTH;
97     rctx->iobuf = OPENSSL_malloc(rctx->iobuflen);
98     rctx->wbio = wbio;
99     rctx->rbio = rbio;
100     rctx->mem = BIO_new(BIO_s_mem());
101     if (rctx->iobuf == NULL || rctx->mem == NULL) {
102         OSSL_HTTP_REQ_CTX_free(rctx);
103         return NULL;
104     }
105     rctx->method_GET = method_GET;
106     rctx->expected_ct = expected_content_type;
107     rctx->expect_asn1 = expect_asn1;
108     rctx->resp_len = 0;
109     OSSL_HTTP_REQ_CTX_set_max_response_length(rctx, max_resp_len);
110     rctx->max_time = timeout > 0 ? time(NULL) + timeout : 0;
111     return rctx;
112 }
113
114 void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx)
115 {
116     if (rctx == NULL)
117         return;
118     BIO_free(rctx->mem); /* this may indirectly call ERR_clear_error() */
119     OPENSSL_free(rctx->iobuf);
120     OPENSSL_free(rctx);
121 }
122
123 BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(OSSL_HTTP_REQ_CTX *rctx)
124 {
125     if (rctx == NULL) {
126         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
127         return NULL;
128     }
129     return rctx->mem;
130 }
131
132 void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx,
133                                                unsigned long len)
134 {
135     if (rctx == NULL) {
136         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
137         return;
138     }
139     rctx->max_resp_len = len != 0 ? len : HTTP_DEFAULT_MAX_RESP_LEN;
140 }
141
142 /*
143  * Create HTTP header using given op and path (or "/" in case path is NULL).
144  * Server name (and port) must be given if and only if plain HTTP proxy is used.
145  */
146 int OSSL_HTTP_REQ_CTX_header(OSSL_HTTP_REQ_CTX *rctx, const char *server,
147                              const char *port, const char *path)
148 {
149     if (rctx == NULL) {
150         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
151         return 0;
152     }
153
154     if (BIO_printf(rctx->mem, "%s ", rctx->method_GET ? "GET" : "POST") <= 0)
155         return 0;
156
157     if (server != NULL) { /* HTTP (but not HTTPS) proxy is used */
158         /*
159          * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only
160          * allowed when using a proxy
161          */
162         if (BIO_printf(rctx->mem, OSSL_HTTP_PREFIX"%s", server) <= 0)
163             return 0;
164         if (port != NULL && BIO_printf(rctx->mem, ":%s", port) <= 0)
165             return 0;
166     }
167
168     /* Make sure path includes a forward slash */
169     if (path == NULL)
170         path = "/";
171     if (path[0] != '/' && BIO_printf(rctx->mem, "/") <= 0)
172         return 0;
173
174     if (BIO_printf(rctx->mem, "%s "HTTP_PREFIX"1.0\r\n", path) <= 0)
175         return 0;
176     rctx->state = OHS_HTTP_HEADER;
177     return 1;
178 }
179
180 int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx,
181                                   const char *name, const char *value)
182 {
183     if (rctx == NULL || name == NULL) {
184         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
185         return 0;
186     }
187
188     if (BIO_puts(rctx->mem, name) <= 0)
189         return 0;
190     if (value != NULL) {
191         if (BIO_write(rctx->mem, ": ", 2) != 2)
192             return 0;
193         if (BIO_puts(rctx->mem, value) <= 0)
194             return 0;
195     }
196     if (BIO_write(rctx->mem, "\r\n", 2) != 2)
197         return 0;
198     rctx->state = OHS_HTTP_HEADER;
199     return 1;
200 }
201
202 static int OSSL_HTTP_REQ_CTX_content(OSSL_HTTP_REQ_CTX *rctx,
203                                      const char *content_type, BIO *req_mem)
204 {
205     const unsigned char *req;
206     long req_len;
207
208     if (rctx == NULL || req_mem == NULL) {
209         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
210         return 0;
211     }
212
213     if (content_type != NULL
214             && BIO_printf(rctx->mem, "Content-Type: %s\r\n", content_type) <= 0)
215         return 0;
216
217     if ((req_len = BIO_get_mem_data(req_mem, &req)) <= 0)
218         return 0;
219     rctx->state = OHS_WRITE_INIT;
220
221     return BIO_printf(rctx->mem, "Content-Length: %ld\r\n\r\n", req_len) > 0
222         && BIO_write(rctx->mem, req, req_len) == (int)req_len;
223 }
224
225 BIO *HTTP_asn1_item2bio(const ASN1_ITEM *it, const ASN1_VALUE *val)
226 {
227     BIO *res;
228
229     if (it == NULL || val == NULL) {
230         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
231         return NULL;
232     }
233
234     if ((res = BIO_new(BIO_s_mem())) == NULL)
235         return NULL;
236     if (ASN1_item_i2d_bio(it, res, val) <= 0) {
237         BIO_free(res);
238         res = NULL;
239     }
240     return res;
241 }
242
243 int OSSL_HTTP_REQ_CTX_i2d(OSSL_HTTP_REQ_CTX *rctx, const char *content_type,
244                           const ASN1_ITEM *it, ASN1_VALUE *req)
245 {
246     BIO *mem;
247     int res;
248
249     if (rctx == NULL || it == NULL || req == NULL) {
250         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
251         return 0;
252     }
253
254     res = (mem = HTTP_asn1_item2bio(it, req)) != NULL
255         && OSSL_HTTP_REQ_CTX_content(rctx, content_type, mem);
256     BIO_free(mem);
257     return res;
258 }
259
260 static int OSSL_HTTP_REQ_CTX_add1_headers(OSSL_HTTP_REQ_CTX *rctx,
261                                           const STACK_OF(CONF_VALUE) *headers,
262                                           const char *host)
263 {
264     int i;
265     int add_host = 1;
266     CONF_VALUE *hdr;
267
268     for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
269         hdr = sk_CONF_VALUE_value(headers, i);
270         if (add_host && strcasecmp("host", hdr->name) == 0)
271             add_host = 0;
272         if (!OSSL_HTTP_REQ_CTX_add1_header(rctx, hdr->name, hdr->value))
273             return 0;
274     }
275
276     if (add_host && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Host", host))
277         return 0;
278     return 1;
279 }
280
281 /*-
282  * Create OSSL_HTTP_REQ_CTX structure using the values provided.
283  * If !use_http_proxy then the 'server' and 'port' parameters are ignored.
284  * If req_mem == NULL then use GET and ignore content_type, else POST.
285  */
286 OSSL_HTTP_REQ_CTX *HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int use_http_proxy,
287                                     const char *server, const char *port,
288                                     const char *path,
289                                     const STACK_OF(CONF_VALUE) *headers,
290                                     const char *content_type, BIO *req_mem,
291                                     int maxline, unsigned long max_resp_len,
292                                     int timeout,
293                                     const char *expected_content_type,
294                                     int expect_asn1)
295 {
296     OSSL_HTTP_REQ_CTX *rctx;
297
298     if (use_http_proxy && (server == NULL || port == NULL)) {
299         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
300         return NULL;
301     }
302     /* remaining parameters are checked indirectly by the functions called */
303
304     if ((rctx = OSSL_HTTP_REQ_CTX_new(wbio, rbio, req_mem == NULL, maxline,
305                                       max_resp_len, timeout,
306                                       expected_content_type, expect_asn1))
307         == NULL)
308         return NULL;
309
310     if (OSSL_HTTP_REQ_CTX_header(rctx, use_http_proxy ? server : NULL,
311                                  port, path)
312         && OSSL_HTTP_REQ_CTX_add1_headers(rctx, headers, server)
313         && (req_mem == NULL
314             || OSSL_HTTP_REQ_CTX_content(rctx, content_type, req_mem)))
315         return rctx;
316
317     OSSL_HTTP_REQ_CTX_free(rctx);
318     return NULL;
319 }
320
321 /*
322  * Parse first HTTP response line. This should be like this: "HTTP/1.0 200 OK".
323  * We need to obtain the numeric code and (optional) informational message.
324  */
325
326 static int parse_http_line1(char *line)
327 {
328     int retcode;
329     char *code, *reason, *end;
330
331     /* Skip to first whitespace (past protocol info) */
332     for (code = line; *code != '\0' && !ossl_isspace(*code); code++)
333         continue;
334     if (*code == '\0') {
335         HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
336         return 0;
337     }
338
339     /* Skip past whitespace to start of response code */
340     while (*code != '\0' && ossl_isspace(*code))
341         code++;
342
343     if (*code == '\0') {
344         HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
345         return 0;
346     }
347
348     /* Find end of response code: first whitespace after start of code */
349     for (reason = code; *reason != '\0' && !ossl_isspace(*reason); reason++)
350         continue;
351
352     if (*reason == '\0') {
353         HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
354         return 0;
355     }
356
357     /* Set end of response code and start of message */
358     *reason++ = '\0';
359
360     /* Attempt to parse numeric code */
361     retcode = strtoul(code, &end, 10);
362
363     if (*end != '\0')
364         return 0;
365
366     /* Skip over any leading whitespace in message */
367     while (*reason != '\0' && ossl_isspace(*reason))
368         reason++;
369
370     if (*reason != '\0') {
371         /*
372          * Finally zap any trailing whitespace in message (include CRLF)
373          */
374
375         /* chop any trailing whitespace from reason */
376         /* We know reason has a non-whitespace character so this is OK */
377         for (end = reason + strlen(reason) - 1; ossl_isspace(*end); end--)
378             *end = '\0';
379     }
380
381     switch (retcode) {
382     case HTTP_STATUS_CODE_OK:
383     case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
384     case HTTP_STATUS_CODE_FOUND:
385         return retcode;
386     default:
387         if (retcode < 400)
388             HTTPerr(0, HTTP_R_STATUS_CODE_UNSUPPORTED);
389         else
390             HTTPerr(0, HTTP_R_RECEIVED_ERROR);
391         if (*reason == '\0')
392             ERR_add_error_data(2, "Code=", code);
393         else
394             ERR_add_error_data(4, "Code=", code, ",Reason=", reason);
395         return 0;
396     }
397 }
398
399 static int check_set_resp_len(OSSL_HTTP_REQ_CTX *rctx, unsigned long len)
400 {
401     const char *tag = NULL;
402     unsigned long val = 0;
403
404     if (len > rctx->max_resp_len) {
405         HTTPerr(0, HTTP_R_MAX_RESP_LEN_EXCEEDED);
406         tag = ",max=";
407         val = rctx->max_resp_len;
408     }
409     if (rctx->resp_len != 0 && rctx->resp_len != len) {
410         HTTPerr(0, HTTP_R_INCONSISTENT_CONTENT_LENGTH);
411         tag = ",before=";
412         val = rctx->resp_len;
413     }
414     if (tag != NULL) {
415         char len_str[32];
416         char str[32];
417
418         BIO_snprintf(len_str, sizeof(len_str), "%lu", len);
419         BIO_snprintf(str, sizeof(str), "%lu", val);
420         ERR_add_error_data(4, "length=", len_str, tag, str);
421         return 0;
422     }
423     rctx->resp_len = len;
424     return 1;
425 }
426
427 /*
428  * Try exchanging request and response via HTTP on (non-)blocking BIO in rctx.
429  * Returns 1 on success, 0 on error or redirection, -1 on BIO_should_retry.
430  */
431 int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx)
432 {
433     int i;
434     long n, n_to_send = 0;
435     unsigned long resp_len;
436     const unsigned char *p;
437     char *key, *value, *line_end = NULL;
438
439     if (rctx == NULL) {
440         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
441         return 0;
442     }
443
444     rctx->redirection_url = NULL;
445  next_io:
446     if ((rctx->state & OHS_NOREAD) == 0) {
447         n = BIO_read(rctx->rbio, rctx->iobuf, rctx->iobuflen);
448         if (n <= 0) {
449             if (BIO_should_retry(rctx->rbio))
450                 return -1;
451             return 0;
452         }
453
454         /* Write data to memory BIO */
455         if (BIO_write(rctx->mem, rctx->iobuf, n) != n)
456             return 0;
457     }
458
459     switch (rctx->state) {
460     case OHS_HTTP_HEADER:
461         /* Last operation was adding headers: need a final \r\n */
462         if (BIO_write(rctx->mem, "\r\n", 2) != 2) {
463             rctx->state = OHS_ERROR;
464             return 0;
465         }
466         rctx->state = OHS_WRITE_INIT;
467
468         /* fall thru */
469     case OHS_WRITE_INIT:
470         n_to_send = BIO_get_mem_data(rctx->mem, NULL);
471         rctx->state = OHS_WRITE;
472
473         /* fall thru */
474     case OHS_WRITE:
475         n = BIO_get_mem_data(rctx->mem, &p);
476
477         i = BIO_write(rctx->wbio, p + (n - n_to_send), n_to_send);
478
479         if (i <= 0) {
480             if (BIO_should_retry(rctx->wbio))
481                 return -1;
482             rctx->state = OHS_ERROR;
483             return 0;
484         }
485
486         n_to_send -= i;
487
488         if (n_to_send > 0)
489             goto next_io;
490
491         rctx->state = OHS_FLUSH;
492
493         (void)BIO_reset(rctx->mem);
494
495         /* fall thru */
496     case OHS_FLUSH:
497
498         i = BIO_flush(rctx->wbio);
499
500         if (i > 0) {
501             rctx->state = OHS_FIRSTLINE;
502             goto next_io;
503         }
504
505         if (BIO_should_retry(rctx->wbio))
506             return -1;
507
508         rctx->state = OHS_ERROR;
509         return 0;
510
511     case OHS_ERROR:
512         return 0;
513
514     case OHS_FIRSTLINE:
515     case OHS_HEADERS:
516     case OHS_REDIRECT:
517
518         /* Attempt to read a line in */
519  next_line:
520         /*
521          * Due to strange memory BIO behavior with BIO_gets we have to check
522          * there's a complete line in there before calling BIO_gets or we'll
523          * just get a partial read.
524          */
525         n = BIO_get_mem_data(rctx->mem, &p);
526         if (n <= 0 || memchr(p, '\n', n) == 0) {
527             if (n >= rctx->iobuflen) {
528                 rctx->state = OHS_ERROR;
529                 return 0;
530             }
531             goto next_io;
532         }
533         n = BIO_gets(rctx->mem, (char *)rctx->iobuf, rctx->iobuflen);
534
535         if (n <= 0) {
536             if (BIO_should_retry(rctx->mem))
537                 goto next_io;
538             rctx->state = OHS_ERROR;
539             return 0;
540         }
541
542         /* Don't allow excessive lines */
543         if (n == rctx->iobuflen) {
544             HTTPerr(0, HTTP_R_RESPONSE_LINE_TOO_LONG);
545             rctx->state = OHS_ERROR;
546             return 0;
547         }
548
549         /* First line */
550         if (rctx->state == OHS_FIRSTLINE) {
551             switch (parse_http_line1((char *)rctx->iobuf)) {
552             case HTTP_STATUS_CODE_OK:
553                 rctx->state = OHS_HEADERS;
554                 goto next_line;
555             case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
556             case HTTP_STATUS_CODE_FOUND: /* i.e., moved temporarily */
557                 if (rctx->method_GET) {
558                     rctx->state = OHS_REDIRECT;
559                     goto next_line;
560                 }
561                 HTTPerr(0, HTTP_R_REDIRECTION_NOT_ENABLED);
562                 /* redirection is not supported/recommended for POST */
563                 /* fall through */
564             default:
565                 rctx->state = OHS_ERROR;
566                 return 0;
567             }
568         }
569         key = (char *)rctx->iobuf;
570         value = strchr(key, ':');
571         if (value != NULL) {
572             *(value++) = '\0';
573             while (ossl_isspace(*value))
574                 value++;
575             line_end = strchr(value, '\r');
576             if (line_end == NULL)
577                 line_end = strchr(value, '\n');
578             if (line_end != NULL)
579                 *line_end = '\0';
580         }
581         if (value != NULL && line_end != NULL) {
582             if (rctx->state == OHS_REDIRECT
583                     && strcasecmp(key, "Location") == 0) {
584                 rctx->redirection_url = value;
585                 return 0;
586             }
587             if (rctx->expected_ct != NULL
588                     && strcasecmp(key, "Content-Type") == 0) {
589                 if (strcasecmp(rctx->expected_ct, value) != 0) {
590                     HTTPerr(0, HTTP_R_UNEXPECTED_CONTENT_TYPE);
591                     ERR_add_error_data(4, "expected=", rctx->expected_ct,
592                                        ",actual=", value);
593                     return 0;
594                 }
595                 rctx->expected_ct = NULL; /* content-type has been found */
596             }
597             if (strcasecmp(key, "Content-Length") == 0) {
598                 resp_len = strtoul(value, &line_end, 10);
599                 if (line_end == value || *line_end != '\0') {
600                     HTTPerr(0, HTTP_R_ERROR_PARSING_CONTENT_LENGTH);
601                     ERR_add_error_data(2, "input=", value);
602                     return 0;
603                 }
604                 if (!check_set_resp_len(rctx, resp_len))
605                     return 0;
606             }
607         }
608
609         /* Look for blank line: end of headers */
610         for (p = rctx->iobuf; *p != '\0'; p++) {
611             if (*p != '\r' && *p != '\n')
612                 break;
613         }
614         if (*p != '\0') /* not end of headers */
615             goto next_line;
616
617         if (rctx->expected_ct != NULL) {
618             HTTPerr(0, HTTP_R_MISSING_CONTENT_TYPE);
619             ERR_add_error_data(2, "expected=", rctx->expected_ct);
620             return 0;
621         }
622         if (rctx->state == OHS_REDIRECT) {
623             /* http status code indicated redirect but there was no Location */
624             HTTPerr(0, HTTP_R_MISSING_REDIRECT_LOCATION);
625             return 0;
626         }
627
628         if (!rctx->expect_asn1) {
629             rctx->state = OHS_CONTENT;
630             goto content;
631         }
632
633         rctx->state = OHS_ASN1_HEADER;
634
635         /* Fall thru */
636     case OHS_ASN1_HEADER:
637         /*
638          * Now reading ASN1 header: can read at least 2 bytes which is enough
639          * for ASN1 SEQUENCE header and either length field or at least the
640          * length of the length field.
641          */
642         n = BIO_get_mem_data(rctx->mem, &p);
643         if (n < 2)
644             goto next_io;
645
646         /* Check it is an ASN1 SEQUENCE */
647         if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
648             HTTPerr(0, HTTP_R_MISSING_ASN1_ENCODING);
649             return 0;
650         }
651
652         /* Check out length field */
653         if ((*p & 0x80) != 0) {
654             /*
655              * If MSB set on initial length octet we can now always read 6
656              * octets: make sure we have them.
657              */
658             if (n < 6)
659                 goto next_io;
660             n = *p & 0x7F;
661             /* Not NDEF or excessive length */
662             if (n == 0 || (n > 4)) {
663                 HTTPerr(0, HTTP_R_ERROR_PARSING_ASN1_LENGTH);
664                 return 0;
665             }
666             p++;
667             resp_len = 0;
668             for (i = 0; i < n; i++) {
669                 resp_len <<= 8;
670                 resp_len |= *p++;
671             }
672             resp_len += n + 2;
673         } else {
674             resp_len = *p + 2;
675         }
676         if (!check_set_resp_len(rctx, resp_len))
677             return 0;
678
679  content:
680         rctx->state = OHS_CONTENT;
681
682         /* Fall thru */
683     case OHS_CONTENT:
684     default:
685         n = BIO_get_mem_data(rctx->mem, NULL);
686         if (n < (long)rctx->resp_len /* may be 0 if no Content-Type or ASN.1 */)
687             goto next_io;
688
689         rctx->state = OHS_DONE;
690         return 1;
691     }
692 }
693
694 #ifndef OPENSSL_NO_SOCK
695
696 /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
697 static BIO *HTTP_new_bio(const char *server /* optionally includes ":port" */,
698                          const char *server_port /* explicit server port */,
699                          const char *proxy /* optionally includes ":port" */)
700 {
701     const char *host = server, *host_end;
702     char host_name[100];
703     const char *port = server_port;
704     BIO *cbio;
705
706     if (!ossl_assert(server != NULL))
707         return NULL;
708
709     if (proxy != NULL) {
710         host = proxy;
711         port = NULL;
712     }
713
714     host_end = strchr(host, '/');
715     if (host_end != NULL && (size_t)(host_end - host) < sizeof(host_name)) {
716         /* chop trailing string starting with '/' */
717         strncpy(host_name, host, host_end - host + 1);
718         host = host_name;
719     }
720
721     cbio = BIO_new_connect(host /* optionally includes ":port" */);
722     if (cbio == NULL)
723         goto end;
724     if (port != NULL)
725         (void)BIO_set_conn_port(cbio, port);
726
727  end:
728     return cbio;
729 }
730 #endif /* OPENSSL_NO_SOCK */
731
732 static ASN1_VALUE *BIO_mem_d2i(BIO *mem, const ASN1_ITEM *it)
733 {
734     const unsigned char *p;
735     long len = BIO_get_mem_data(mem, &p);
736     ASN1_VALUE *resp = ASN1_item_d2i(NULL, &p, len, it);
737
738     if (resp == NULL)
739         HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
740     return resp;
741 }
742
743 static BIO *OSSL_HTTP_REQ_CTX_transfer(OSSL_HTTP_REQ_CTX *rctx)
744 {
745     int sending = 1;
746     int rv;
747
748     if (rctx == NULL) {
749         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
750         return NULL;
751     }
752
753     for (;;) {
754         rv = OSSL_HTTP_REQ_CTX_nbio(rctx);
755         if (rv != -1)
756             break;
757         /* BIO_should_retry was true */
758         sending = 0;
759         /* will not actually wait if rctx->max_time == 0 */
760         if (BIO_wait(rctx->rbio, rctx->max_time, 100 /* milliseconds */) <= 0)
761             return NULL;
762     }
763
764     if (rv == 0) {
765         if (rctx->redirection_url == NULL) { /* an error occurred */
766             if (sending && (rctx->state & OHS_NOREAD) != 0)
767                 HTTPerr(0, HTTP_R_ERROR_SENDING);
768             else
769                 HTTPerr(0, HTTP_R_ERROR_RECEIVING);
770         }
771         return NULL;
772     }
773     if (!BIO_up_ref(rctx->mem))
774         return NULL;
775     return rctx->mem;
776 }
777
778 /* Exchange ASN.1-encoded request and response via HTTP on (non-)blocking BIO */
779 ASN1_VALUE *OSSL_HTTP_REQ_CTX_sendreq_d2i(OSSL_HTTP_REQ_CTX *rctx,
780                                           const ASN1_ITEM *it)
781 {
782     if (rctx == NULL || it == NULL) {
783         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
784         return NULL;
785     }
786     return BIO_mem_d2i(OSSL_HTTP_REQ_CTX_transfer(rctx), it);
787 }
788
789 static int update_timeout(int timeout, time_t start_time)
790 {
791     long elapsed_time;
792
793     if (timeout == 0)
794         return 0;
795     elapsed_time = (long)(time(NULL) - start_time); /* this might overflow */
796     return timeout <= elapsed_time ? -1 : timeout - elapsed_time;
797 }
798
799 /*-
800  * Exchange HTTP request and response with the given server.
801  * If req_mem == NULL then use GET and ignore content_type, else POST.
802  * The redirection_url output (freed by caller) parameter is used only for GET.
803  *
804  * Typically the bio and rbio parameters are NULL and a network BIO is created
805  * internally for connecting to the given server and port, optionally via a
806  * proxy and its port, and is then used for exchanging the request and response.
807  * If bio is given and rbio is NULL then this BIO is used instead.
808  * If both bio and rbio are given (which may be memory BIOs for instance)
809  * then no explicit connection is attempted,
810  * bio is used for writing the request, and rbio for reading the response.
811  *
812  * bio_update_fn is an optional BIO connect/disconnect callback function,
813  * which has the prototype
814  *   BIO *(*OSSL_HTTP_bio_cb_t) (BIO *bio, void *arg, int conn, int detail);
815  * The callback may modify the HTTP BIO provided in the bio argument,
816  * whereby it may make use of any custom defined argument 'arg'.
817  * During connection establishment, just after BIO_do_connect_retry(),
818  * the callback function is invoked with the 'conn' argument being 1
819  * 'detail' indicating whether a HTTPS (i.e., TLS) connection is requested.
820  * On disconnect 'conn' is 0 and 'detail' indicates that no error occurred.
821  * For instance, on connect the funct may prepend a TLS BIO to implement HTTPS;
822  * after disconnect it may do some error diagnostics and/or specific cleanup.
823  * The function should return NULL to indicate failure.
824  * After disconnect the modified BIO will be deallocated using BIO_free_all().
825  */
826 BIO *OSSL_HTTP_transfer(const char *server, const char *port, const char *path,
827                         int use_ssl, const char *proxy, const char *no_proxy,
828                         BIO *bio, BIO *rbio,
829                         OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
830                         const STACK_OF(CONF_VALUE) *headers,
831                         const char *content_type, BIO *req_mem,
832                         int maxline, unsigned long max_resp_len, int timeout,
833                         const char *expected_ct, int expect_asn1,
834                         char **redirection_url)
835 {
836     time_t start_time = timeout > 0 ? time(NULL) : 0;
837     BIO *cbio; /* = bio if present, used as connection BIO if rbio is NULL */
838     OSSL_HTTP_REQ_CTX *rctx;
839     BIO *resp = NULL;
840
841     if (redirection_url != NULL)
842         *redirection_url = NULL; /* do this beforehand to prevent dbl free */
843
844     if (use_ssl && bio_update_fn == NULL) {
845         HTTPerr(0, HTTP_R_TLS_NOT_ENABLED);
846         return NULL;
847     }
848     if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) {
849         HTTPerr(0, ERR_R_PASSED_INVALID_ARGUMENT);
850         return NULL;
851     }
852
853     if (bio != NULL) {
854         cbio = bio;
855     } else {
856 #ifndef OPENSSL_NO_SOCK
857         if (server == NULL) {
858             HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
859             return NULL;
860         }
861         if (*port == '\0')
862             port = NULL;
863         if (port == NULL && strchr(server, ':') == NULL)
864             port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
865         proxy = http_adapt_proxy(proxy, no_proxy, server, use_ssl);
866         if ((cbio = HTTP_new_bio(server, port, proxy)) == NULL)
867             return NULL;
868 #else
869         HTTPerr(0, HTTP_R_SOCK_NOT_SUPPORTED);
870         return NULL;
871 #endif
872     }
873     /* remaining parameters are checked indirectly by the functions called */
874
875     (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
876     if (rbio == NULL && BIO_do_connect_retry(cbio, timeout, -1) <= 0)
877         goto end;
878     /* now timeout is guaranteed to be >= 0 */
879
880     /* callback can be used to wrap or prepend TLS session */
881     if (bio_update_fn != NULL) {
882         BIO *orig_bio = cbio;
883         cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl);
884         if (cbio == NULL) {
885             cbio = orig_bio;
886             goto end;
887         }
888     }
889
890     rctx = HTTP_REQ_CTX_new(cbio, rbio != NULL ? rbio : cbio,
891                             !use_ssl && proxy != NULL, server, port, path,
892                             headers, content_type, req_mem, maxline,
893                             max_resp_len, update_timeout(timeout, start_time),
894                             expected_ct, expect_asn1);
895     if (rctx == NULL)
896         goto end;
897
898     resp = OSSL_HTTP_REQ_CTX_transfer(rctx);
899     if (resp == NULL) {
900         if (rctx->redirection_url != NULL) {
901             if (redirection_url == NULL)
902                 HTTPerr(0, HTTP_R_REDIRECTION_NOT_ENABLED);
903             else
904                 /* may be NULL if out of memory: */
905                 *redirection_url = OPENSSL_strdup(rctx->redirection_url);
906         } else {
907             char buf[200];
908             unsigned long err = ERR_peek_error();
909             int lib = ERR_GET_LIB(err);
910             int reason = ERR_GET_REASON(err);
911
912             if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP
913                     || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT)
914                     || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR)
915 #ifndef OPENSSL_NO_CMP
916                     || (lib == ERR_LIB_CMP
917                         && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
918 #endif
919                 ) {
920                 BIO_snprintf(buf, 200, "server=%s:%s", server, port);
921                 ERR_add_error_data(1, buf);
922                 if (proxy != NULL)
923                     ERR_add_error_data(2, " proxy=", proxy);
924                 if (err == 0) {
925                     BIO_snprintf(buf, 200, " peer has disconnected%s",
926                                  use_ssl ? " violating the protocol" :
927                                  ", likely because it requires the use of TLS");
928                     ERR_add_error_data(1, buf);
929                 }
930             }
931         }
932     }
933     OSSL_HTTP_REQ_CTX_free(rctx);
934
935     /* callback can be used to clean up TLS session */
936     if (bio_update_fn != NULL
937             && (*bio_update_fn)(cbio, arg, 0, resp != NULL) == NULL) {
938         BIO_free(resp);
939         resp = NULL;
940     }
941
942  end:
943     /*
944      * Use BIO_free_all() because bio_update_fn may prepend or append to cbio.
945      * This also frees any (e.g., SSL/TLS) BIOs linked with bio and,
946      * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer.
947      */
948     if (bio == NULL) /* cbio was not provided by caller */
949         BIO_free_all(cbio);
950
951     if (resp != NULL)
952         /* remove any spurious error queue entries by ssl_add_cert_chain() */
953         (void)ERR_pop_to_mark();
954     else
955         (void)ERR_clear_last_mark();
956
957     return resp;
958 }
959
960 static int redirection_ok(int n_redir, const char *old_url, const char *new_url)
961 {
962     size_t https_len = strlen(OSSL_HTTPS_NAME":");
963
964     if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) {
965         HTTPerr(0, HTTP_R_TOO_MANY_REDIRECTIONS);
966         return 0;
967     }
968     if (*new_url == '/') /* redirection to same server => same protocol */
969         return 1;
970     if (strncmp(old_url, OSSL_HTTPS_NAME":", https_len) == 0 &&
971         strncmp(new_url, OSSL_HTTPS_NAME":", https_len) != 0) {
972         HTTPerr(0, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP);
973         return 0;
974     }
975     return 1;
976 }
977
978 /* Get data via HTTP from server at given URL, potentially with redirection */
979 BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy,
980                    BIO *bio, BIO *rbio,
981                    OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
982                    const STACK_OF(CONF_VALUE) *headers,
983                    int maxline, unsigned long max_resp_len, int timeout,
984                    const char *expected_content_type, int expect_asn1)
985 {
986     time_t start_time = timeout > 0 ? time(NULL) : 0;
987     char *current_url, *redirection_url;
988     int n_redirs = 0;
989     char *host;
990     char *port;
991     char *path;
992     int use_ssl;
993     BIO *resp = NULL;
994
995     if (url == NULL) {
996         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
997         return NULL;
998     }
999     if ((current_url = OPENSSL_strdup(url)) == NULL)
1000         return NULL;
1001
1002     for (;;) {
1003         if (!OSSL_HTTP_parse_url(current_url, &host, &port, &path, &use_ssl))
1004             break;
1005
1006      new_rpath:
1007         resp = OSSL_HTTP_transfer(host, port, path, use_ssl, proxy, no_proxy,
1008                                   bio, rbio,
1009                                   bio_update_fn, arg, headers, NULL, NULL,
1010                                   maxline, max_resp_len,
1011                                   update_timeout(timeout, start_time),
1012                                   expected_content_type, expect_asn1,
1013                                   &redirection_url);
1014         OPENSSL_free(path);
1015         if (resp == NULL && redirection_url != NULL) {
1016             if (redirection_ok(++n_redirs, current_url, redirection_url)) {
1017                 (void)BIO_reset(bio);
1018                 OPENSSL_free(current_url);
1019                 current_url = redirection_url;
1020                 if (*redirection_url == '/') { /* redirection to same server */
1021                     path = OPENSSL_strdup(redirection_url);
1022                     goto new_rpath;
1023                 }
1024                 OPENSSL_free(host);
1025                 OPENSSL_free(port);
1026                 continue;
1027             }
1028             OPENSSL_free(redirection_url);
1029         }
1030         OPENSSL_free(host);
1031         OPENSSL_free(port);
1032         break;
1033     }
1034     OPENSSL_free(current_url);
1035     return resp;
1036 }
1037
1038 /* Get ASN.1-encoded data via HTTP from server at given URL */
1039 ASN1_VALUE *OSSL_HTTP_get_asn1(const char *url,
1040                                const char *proxy, const char *no_proxy,
1041                                BIO *bio, BIO *rbio,
1042                                OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
1043                                const STACK_OF(CONF_VALUE) *headers,
1044                                int maxline, unsigned long max_resp_len,
1045                                int timeout, const char *expected_content_type,
1046                                const ASN1_ITEM *it)
1047 {
1048     BIO *mem;
1049     ASN1_VALUE *resp = NULL;
1050
1051     if (url == NULL || it == NULL) {
1052         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
1053         return NULL;
1054     }
1055     if ((mem = OSSL_HTTP_get(url, proxy, no_proxy, bio, rbio, bio_update_fn,
1056                              arg, headers, maxline, max_resp_len, timeout,
1057                              expected_content_type, 1 /* expect_asn1 */))
1058         != NULL)
1059         resp = BIO_mem_d2i(mem, it);
1060     BIO_free(mem);
1061     return resp;
1062 }
1063
1064 /* Post ASN.1-encoded request via HTTP to server return ASN.1 response */
1065 ASN1_VALUE *OSSL_HTTP_post_asn1(const char *server, const char *port,
1066                                 const char *path, int use_ssl,
1067                                 const char *proxy, const char *no_proxy,
1068                                 BIO *bio, BIO *rbio,
1069                                 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
1070                                 const STACK_OF(CONF_VALUE) *headers,
1071                                 const char *content_type,
1072                                 const ASN1_VALUE *req, const ASN1_ITEM *req_it,
1073                                 int maxline, unsigned long max_resp_len,
1074                                 int timeout, const char *expected_ct,
1075                                 const ASN1_ITEM *rsp_it)
1076 {
1077     BIO *req_mem;
1078     BIO *res_mem;
1079     ASN1_VALUE *resp = NULL;
1080
1081     if (req == NULL) {
1082         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
1083         return NULL;
1084     }
1085     /* remaining parameters are checked indirectly */
1086
1087     req_mem = HTTP_asn1_item2bio(req_it, req);
1088     res_mem = OSSL_HTTP_transfer(server, port, path, use_ssl, proxy, no_proxy,
1089                                  bio, rbio,
1090                                  bio_update_fn, arg, headers, content_type,
1091                                  req_mem /* may be NULL */, maxline,
1092                                  max_resp_len, timeout,
1093                                  expected_ct, 1 /* expect_asn1 */, NULL);
1094     BIO_free(req_mem);
1095     if (res_mem != NULL)
1096         resp = BIO_mem_d2i(res_mem, rsp_it);
1097     BIO_free(res_mem);
1098     return resp;
1099 }
1100
1101 /* BASE64 encoder used for encoding basic proxy authentication credentials */
1102 static char *base64encode(const void *buf, size_t len)
1103 {
1104     int i;
1105     size_t outl;
1106     char *out;
1107
1108     /* Calculate size of encoded data */
1109     outl = (len / 3);
1110     if (len % 3 > 0)
1111         outl++;
1112     outl <<= 2;
1113     out = OPENSSL_malloc(outl + 1);
1114     if (out == NULL)
1115         return 0;
1116
1117     i = EVP_EncodeBlock((unsigned char *)out, buf, len);
1118     if (!ossl_assert(0 <= i && (size_t)i <= outl)) {
1119         OPENSSL_free(out);
1120         return NULL;
1121     }
1122     return out;
1123 }
1124
1125 /*
1126  * Promote the given connection BIO using the CONNECT method for a TLS proxy.
1127  * This is typically called by an app, so bio_err and prog are used unless NULL
1128  * to print additional diagnostic information in a user-oriented way.
1129  */
1130 int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port,
1131                             const char *proxyuser, const char *proxypass,
1132                             int timeout, BIO *bio_err, const char *prog)
1133 {
1134 #undef BUF_SIZE
1135 #define BUF_SIZE (8 * 1024)
1136     char *mbuf = OPENSSL_malloc(BUF_SIZE);
1137     char *mbufp;
1138     int read_len = 0;
1139     int ret = 0;
1140     BIO *fbio = BIO_new(BIO_f_buffer());
1141     int rv;
1142     time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
1143
1144     if (bio == NULL || server == NULL
1145             || (bio_err != NULL && prog == NULL)) {
1146         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
1147         goto end;
1148     }
1149     if (port == NULL || *port == '\0')
1150         port = OSSL_HTTPS_PORT;
1151
1152     if (mbuf == NULL || fbio == NULL) {
1153         BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog);
1154         goto end;
1155     }
1156     BIO_push(fbio, bio);
1157
1158     BIO_printf(fbio, "CONNECT %s:%s "HTTP_PREFIX"1.0\r\n", server, port);
1159
1160     /*
1161      * Workaround for broken proxies which would otherwise close
1162      * the connection when entering tunnel mode (e.g., Squid 2.6)
1163      */
1164     BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n");
1165
1166     /* Support for basic (base64) proxy authentication */
1167     if (proxyuser != NULL) {
1168         size_t len = strlen(proxyuser) + 1;
1169         char *proxyauth, *proxyauthenc = NULL;
1170
1171         if (proxypass != NULL)
1172             len += strlen(proxypass);
1173         proxyauth = OPENSSL_malloc(len + 1);
1174         if (proxyauth == NULL)
1175             goto end;
1176         if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser,
1177                          proxypass != NULL ? proxypass : "") != (int)len)
1178             goto proxy_end;
1179         proxyauthenc = base64encode(proxyauth, len);
1180         if (proxyauthenc != NULL) {
1181             BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc);
1182             OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc));
1183         }
1184      proxy_end:
1185         OPENSSL_clear_free(proxyauth, len);
1186         if (proxyauthenc == NULL)
1187             goto end;
1188     }
1189
1190     /* Terminate the HTTP CONNECT request */
1191     BIO_printf(fbio, "\r\n");
1192
1193     for (;;) {
1194         if (BIO_flush(fbio) != 0)
1195             break;
1196         /* potentially needs to be retried if BIO is non-blocking */
1197         if (!BIO_should_retry(fbio))
1198             break;
1199     }
1200
1201     for (;;) {
1202         /* will not actually wait if timeout == 0 */
1203         rv = BIO_wait(fbio, max_time, 100 /* milliseconds */);
1204         if (rv <= 0) {
1205             BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog,
1206                        rv == 0 ? "timed out" : "failed waiting for data");
1207             goto end;
1208         }
1209
1210         /*-
1211          * The first line is the HTTP response.
1212          * According to RFC 7230, it is formatted exactly like this:
1213          * HTTP/d.d ddd Reason text\r\n
1214          */
1215         read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1216         /* the BIO may not block, so we must wait for the 1st line to come in */
1217         if (read_len < HTTP_LINE1_MINLEN)
1218             continue;
1219
1220         /* RFC 7231 4.3.6: any 2xx status code is valid */
1221         if (strncmp(mbuf, HTTP_PREFIX, strlen(HTTP_PREFIX)) != 0) {
1222             HTTPerr(0, HTTP_R_RESPONSE_PARSE_ERROR);
1223             BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n",
1224                        prog);
1225             /* Wrong protocol, not even HTTP, so stop reading headers */
1226             goto end;
1227         }
1228         mbufp = mbuf + strlen(HTTP_PREFIX);
1229         if (strncmp(mbufp, HTTP_VERSION_PATT, strlen(HTTP_VERSION_PATT)) != 0) {
1230             HTTPerr(0, HTTP_R_RECEIVED_WRONG_HTTP_VERSION);
1231             BIO_printf(bio_err,
1232                        "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
1233                        prog, HTTP_VERSION_STR_LEN, mbufp);
1234             goto end;
1235         }
1236         mbufp += HTTP_VERSION_STR_LEN;
1237         if (strncmp(mbufp, " 2", strlen(" 2")) != 0) {
1238             mbufp += 1;
1239             /* chop any trailing whitespace */
1240             while (read_len > 0 && ossl_isspace(mbuf[read_len - 1]))
1241                 read_len--;
1242             mbuf[read_len] = '\0';
1243             HTTPerr(0, HTTP_R_CONNECT_FAILURE);
1244             ERR_add_error_data(2, "Reason=", mbufp);
1245             BIO_printf(bio_err, "%s: HTTP CONNECT failed, Reason=%s\n",
1246                        prog, mbufp);
1247             goto end;
1248         }
1249         ret = 1;
1250         break;
1251     }
1252
1253     /* Read past all following headers */
1254     do {
1255         /*
1256          * TODO: This does not necessarily catch the case when the full
1257          * HTTP response came in in more than a single TCP message.
1258          */
1259         read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1260     } while (read_len > 2);
1261
1262  end:
1263     if (fbio != NULL) {
1264         (void)BIO_flush(fbio);
1265         BIO_pop(fbio);
1266         BIO_free(fbio);
1267     }
1268     OPENSSL_free(mbuf);
1269     return ret;
1270 #undef BUF_SIZE
1271 }