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