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