fix build for new HTTP client in case OPENSSL_NO_CMP or OPENSSL_NO_OCSP
[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"
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, "http://%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_SERVER_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_SERVER_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_SERVER_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_SERVER_SENT_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 && strcmp(key, "Location") == 0) {
581                 rctx->redirection_url = value;
582                 return 0;
583             }
584             if (rctx->expected_ct != NULL && strcmp(key, "Content-Type") == 0) {
585                 if (strcmp(rctx->expected_ct, value) != 0) {
586                     HTTPerr(0, HTTP_R_UNEXPECTED_CONTENT_TYPE);
587                     ERR_add_error_data(4, "expected=", rctx->expected_ct,
588                                        ",actual=", value);
589                     return 0;
590                 }
591                 rctx->expected_ct = NULL; /* content-type has been found */
592             }
593             if (strcmp(key, "Content-Length") == 0) {
594                 resp_len = strtoul(value, &line_end, 10);
595                 if (line_end == value || *line_end != '\0') {
596                     HTTPerr(0, HTTP_R_ERROR_PARSING_CONTENT_LENGTH);
597                     ERR_add_error_data(2, "input=", value);
598                     return 0;
599                 }
600                 if (!check_set_resp_len(rctx, resp_len))
601                     return 0;
602             }
603         }
604
605         /* Look for blank line: end of headers */
606         for (p = rctx->iobuf; *p != '\0' ; p++) {
607             if (*p != '\r' && *p != '\n')
608                 break;
609         }
610         if (*p != '\0') /* not end of headers */
611             goto next_line;
612
613         if (rctx->expected_ct != NULL) {
614             HTTPerr(0, HTTP_R_MISSING_CONTENT_TYPE);
615             ERR_add_error_data(2, "expected=", rctx->expected_ct);
616             return 0;
617         }
618         if (rctx->state == OHS_REDIRECT) {
619             /* http status code indicated redirect but there was no Location */
620             HTTPerr(0, HTTP_R_MISSING_REDIRECT_LOCATION);
621             return 0;
622         }
623
624         if (!rctx->expect_asn1) {
625             rctx->state = OHS_CONTENT;
626             goto content;
627         }
628
629         rctx->state = OHS_ASN1_HEADER;
630
631         /* Fall thru */
632     case OHS_ASN1_HEADER:
633         /*
634          * Now reading ASN1 header: can read at least 2 bytes which is enough
635          * for ASN1 SEQUENCE header and either length field or at least the
636          * length of the length field.
637          */
638         n = BIO_get_mem_data(rctx->mem, &p);
639         if (n < 2)
640             goto next_io;
641
642         /* Check it is an ASN1 SEQUENCE */
643         if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
644             HTTPerr(0, HTTP_R_MISSING_ASN1_ENCODING);
645             return 0;
646         }
647
648         /* Check out length field */
649         if ((*p & 0x80) != 0) {
650             /*
651              * If MSB set on initial length octet we can now always read 6
652              * octets: make sure we have them.
653              */
654             if (n < 6)
655                 goto next_io;
656             n = *p & 0x7F;
657             /* Not NDEF or excessive length */
658             if (n == 0 || (n > 4)) {
659                 HTTPerr(0, HTTP_R_ERROR_PARSING_ASN1_LENGTH);
660                 return 0;
661             }
662             p++;
663             resp_len = 0;
664             for (i = 0; i < n; i++) {
665                 resp_len <<= 8;
666                 resp_len |= *p++;
667             }
668             resp_len += n + 2;
669         } else {
670             resp_len = *p + 2;
671         }
672         if (!check_set_resp_len(rctx, resp_len))
673             return 0;
674
675  content:
676         rctx->state = OHS_CONTENT;
677
678         /* Fall thru */
679     case OHS_CONTENT:
680     default:
681         n = BIO_get_mem_data(rctx->mem, NULL);
682         if (n < (long)rctx->resp_len /* may be 0 if no Content-Type or ASN.1 */)
683             goto next_io;
684
685         rctx->state = OHS_DONE;
686         return 1;
687     }
688 }
689
690 #ifndef OPENSSL_NO_SOCK
691
692 /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
693 static BIO *HTTP_new_bio(const char *server, const char *server_port,
694                          const char *proxy, const char *proxy_port)
695 {
696     const char *host = server;
697     const char *port = server_port;
698     BIO *cbio;
699
700     if (server == NULL) {
701         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
702         return NULL;
703     }
704
705     if (proxy != NULL) {
706         host = proxy;
707         port = proxy_port;
708     }
709     cbio = BIO_new_connect(host);
710     if (cbio == NULL)
711         goto end;
712     if (port != NULL)
713         (void)BIO_set_conn_port(cbio, port);
714
715  end:
716     return cbio;
717 }
718
719 static ASN1_VALUE *BIO_mem_d2i(BIO *mem, const ASN1_ITEM *it)
720 {
721     const unsigned char *p;
722     long len = BIO_get_mem_data(mem, &p);
723     ASN1_VALUE *resp = ASN1_item_d2i(NULL, &p, len, it);
724
725     if (resp == NULL)
726         HTTPerr(0, HTTP_R_SERVER_RESPONSE_PARSE_ERROR);
727     return resp;
728 }
729
730 static BIO *OSSL_HTTP_REQ_CTX_transfer(OSSL_HTTP_REQ_CTX *rctx)
731 {
732     int sending = 1;
733     int rv;
734
735     if (rctx == NULL) {
736         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
737         return NULL;
738     }
739
740     for (;;) {
741         rv = OSSL_HTTP_REQ_CTX_nbio(rctx);
742         if (rv != -1)
743             break;
744         /* BIO_should_retry was true */
745         sending = 0;
746         /* will not actually wait if rctx->max_time == 0 */
747         if (BIO_wait(rctx->rbio, rctx->max_time) <= 0)
748             return NULL;
749     }
750
751     if (rv == 0) {
752         if (rctx->redirection_url == NULL) { /* an error occurred */
753             if (sending && (rctx->state & OHS_NOREAD) != 0)
754                 HTTPerr(0, HTTP_R_ERROR_SENDING);
755             else
756                 HTTPerr(0, HTTP_R_ERROR_RECEIVING);
757         }
758         return NULL;
759     }
760     if (!BIO_up_ref(rctx->mem))
761         return NULL;
762     return rctx->mem;
763 }
764
765 /* Exchange ASN.1-encoded request and response via HTTP on (non-)blocking BIO */
766 ASN1_VALUE *OSSL_HTTP_REQ_CTX_sendreq_d2i(OSSL_HTTP_REQ_CTX *rctx,
767                                           const ASN1_ITEM *it)
768 {
769     if (rctx == NULL || it == NULL) {
770         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
771         return NULL;
772     }
773     return BIO_mem_d2i(OSSL_HTTP_REQ_CTX_transfer(rctx), it);
774 }
775
776 static int update_timeout(int timeout, time_t start_time)
777 {
778     long elapsed_time;
779
780     if (timeout == 0)
781         return 0;
782     elapsed_time = (long)(time(NULL) - start_time); /* this might overflow */
783     return timeout <= elapsed_time ? -1 : timeout - elapsed_time;
784 }
785
786 /*-
787  * Exchange HTTP request and response with the given server.
788  * If req_mem == NULL then use GET and ignore content_type, else POST.
789  * The redirection_url output (freed by caller) parameter is used only for GET.
790  *
791  * Typically the bio and rbio parameters are NULL and a network BIO is created
792  * internally for connecting to the given server and port, optionally via a
793  * proxy and its port, and is then used for exchanging the request and response.
794  * If bio is given and rbio is NULL then this BIO is used instead.
795  * If both bio and rbio are given (which may be memory BIOs for instance)
796  * then no explicit connection is attempted,
797  * bio is used for writing the request, and rbio for reading the response.
798  *
799  * bio_update_fn is an optional BIO connect/disconnect callback function,
800  * which has the prototype
801  *   BIO *(*OSSL_HTTP_bio_cb_t) (BIO *bio, void *arg, int conn, int detail);
802  * The callback may modify the HTTP BIO provided in the bio argument,
803  * whereby it may make use of any custom defined argument 'arg'.
804  * During connection establishment, just after BIO_connect_retry(),
805  * the callback function is invoked with the 'conn' argument being 1
806  * 'detail' indicating whether a HTTPS (i.e., TLS) connection is requested.
807  * On disconnect 'conn' is 0 and 'detail' indicates that no error occurred.
808  * For instance, on connect the funct may prepend a TLS BIO to implement HTTPS;
809  * after disconnect it may do some error diagnostics and/or specific cleanup.
810  * The function should return NULL to indicate failure.
811  * After disconnect the modified BIO will be deallocated using BIO_free_all().
812  */
813 BIO *OSSL_HTTP_transfer(const char *server, const char *port, const char *path,
814                         int use_ssl, const char *proxy, const char *proxy_port,
815                         BIO *bio, BIO *rbio,
816                         OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
817                         const STACK_OF(CONF_VALUE) *headers,
818                         const char *content_type, BIO *req_mem,
819                         int maxline, unsigned long max_resp_len, int timeout,
820                         const char *expected_ct, int expect_asn1,
821                         char **redirection_url)
822 {
823     time_t start_time = timeout > 0 ? time(NULL) : 0;
824     BIO *cbio; /* = bio if present, used as connection BIO if rbio is NULL */
825     OSSL_HTTP_REQ_CTX *rctx;
826     BIO *resp = NULL;
827
828     if (redirection_url != NULL)
829         *redirection_url = NULL; /* do this beforehand to prevent dbl free */
830
831     if (use_ssl && bio_update_fn == NULL) {
832         HTTPerr(0, HTTP_R_TLS_NOT_ENABLED);
833         return NULL;
834     }
835     if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) {
836         HTTPerr(0, ERR_R_PASSED_INVALID_ARGUMENT);
837         return NULL;
838     }
839     /* remaining parameters are checked indirectly by the functions called */
840
841     if (bio != NULL)
842         cbio = bio;
843     else if ((cbio = HTTP_new_bio(server, port, proxy, proxy_port)) == NULL)
844         return NULL;
845
846     (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
847     if (rbio == NULL && BIO_connect_retry(cbio, timeout) <= 0)
848         goto end;
849     /* now timeout is guaranteed to be >= 0 */
850
851     /* callback can be used to wrap or prepend TLS session */
852     if (bio_update_fn != NULL) {
853         BIO *orig_bio = cbio;
854         cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl);
855         if (cbio == NULL) {
856             cbio = orig_bio;
857             goto end;
858         }
859     }
860
861     rctx = HTTP_REQ_CTX_new(cbio, rbio != NULL ? rbio : cbio,
862                             !use_ssl && proxy != NULL, server, port, path,
863                             headers, content_type, req_mem, maxline,
864                             max_resp_len, update_timeout(timeout, start_time),
865                             expected_ct, expect_asn1);
866     if (rctx == NULL)
867         goto end;
868
869     resp = OSSL_HTTP_REQ_CTX_transfer(rctx);
870     if (resp == NULL) {
871         if (rctx->redirection_url != NULL) {
872             if (redirection_url == NULL)
873                 HTTPerr(0, HTTP_R_REDIRECTION_NOT_ENABLED);
874             else
875                 /* may be NULL if out of memory: */
876                 *redirection_url = OPENSSL_strdup(rctx->redirection_url);
877         } else {
878             char buf[200];
879             unsigned long err = ERR_peek_error();
880             int lib = ERR_GET_LIB(err);
881             int reason = ERR_GET_REASON(err);
882
883             if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP
884                     || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT)
885                     || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR)
886 # ifndef OPENSSL_NO_CMP
887                     || (lib == ERR_LIB_CMP
888                         && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
889 # endif
890                 ) {
891                 BIO_snprintf(buf, 200, "server=%s:%s", server, port);
892                 ERR_add_error_data(1, buf);
893                 if (err == 0) {
894                     BIO_snprintf(buf, 200, "server has disconnected%s",
895                                  use_ssl ? " violating the protocol" :
896                                  ", likely because it requires the use of TLS");
897                     ERR_add_error_data(1, buf);
898                 }
899             }
900         }
901     }
902     OSSL_HTTP_REQ_CTX_free(rctx);
903
904     /* callback can be used to clean up TLS session */
905     if (bio_update_fn != NULL
906             && (*bio_update_fn)(cbio, arg, 0, resp != NULL) == NULL) {
907         BIO_free(resp);
908         resp = NULL;
909     }
910
911  end:
912     /*
913      * Use BIO_free_all() because bio_update_fn may prepend or append to cbio.
914      * This also frees any (e.g., SSL/TLS) BIOs linked with bio and,
915      * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer.
916      */
917     if (bio == NULL) /* cbio was not provided by caller */
918         BIO_free_all(cbio);
919
920     if (resp != NULL)
921         /* remove any spurious error queue entries by ssl_add_cert_chain() */
922         (void)ERR_pop_to_mark();
923     else
924         (void)ERR_clear_last_mark();
925
926     return resp;
927 }
928
929 static int redirection_ok(int n_redir, const char *old_url, const char *new_url)
930 {
931     static const char https[] = "https:";
932     int https_len = 6; /* strlen(https) */
933
934     if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) {
935         HTTPerr(0, HTTP_R_TOO_MANY_REDIRECTIONS);
936         return 0;
937     }
938     if (*new_url == '/') /* redirection to same server => same protocol */
939         return 1;
940     if (strncmp(old_url, https, https_len) == 0 &&
941         strncmp(new_url, https, https_len) != 0) {
942         HTTPerr(0, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP);
943         return 0;
944     }
945     return 1;
946 }
947
948 /* Get data via HTTP from server at given URL, potentially with redirection */
949 BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *proxy_port,
950                    BIO *bio, BIO *rbio,
951                    OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
952                    const STACK_OF(CONF_VALUE) *headers,
953                    int maxline, unsigned long max_resp_len, int timeout,
954                    const char *expected_content_type, int expect_asn1)
955 {
956     time_t start_time = timeout > 0 ? time(NULL) : 0;
957     char *current_url, *redirection_url;
958     int n_redirs = 0;
959     char *host;
960     char *port;
961     char *path;
962     int use_ssl;
963     BIO *resp = NULL;
964
965     if (url == NULL) {
966         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
967         return NULL;
968     }
969     if ((current_url = OPENSSL_strdup(url)) == NULL)
970         return NULL;
971
972     for (;;) {
973         if (!OSSL_HTTP_parse_url(current_url, &host, &port, &path, &use_ssl))
974             break;
975
976      new_rpath:
977         resp = OSSL_HTTP_transfer(host, port, path, use_ssl, proxy, proxy_port,
978                                   bio, rbio,
979                                   bio_update_fn, arg, headers, NULL, NULL,
980                                   maxline, max_resp_len,
981                                   update_timeout(timeout, start_time),
982                                   expected_content_type, expect_asn1,
983                                   &redirection_url);
984         OPENSSL_free(path);
985         if (resp == NULL && redirection_url != NULL) {
986             if (redirection_ok(++n_redirs, current_url, redirection_url)) {
987                 (void)BIO_reset(bio);
988                 OPENSSL_free(current_url);
989                 current_url = redirection_url;
990                 if (*redirection_url == '/') { /* redirection to same server */
991                     path = OPENSSL_strdup(redirection_url);
992                     goto new_rpath;
993                 }
994                 OPENSSL_free(host);
995                 OPENSSL_free(port);
996                 continue;
997             }
998             OPENSSL_free(redirection_url);
999         }
1000         OPENSSL_free(host);
1001         OPENSSL_free(port);
1002         break;
1003     }
1004     OPENSSL_free(current_url);
1005     return resp;
1006 }
1007
1008 /* Get ASN.1-encoded data via HTTP from server at given URL */
1009 ASN1_VALUE *OSSL_HTTP_get_asn1(const char *url,
1010                                const char *proxy, const char *proxy_port,
1011                                BIO *bio, BIO *rbio,
1012                                OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
1013                                const STACK_OF(CONF_VALUE) *headers,
1014                                int maxline, unsigned long max_resp_len,
1015                                int timeout, const char *expected_content_type,
1016                                const ASN1_ITEM *it)
1017 {
1018     BIO *mem;
1019     ASN1_VALUE *resp = NULL;
1020
1021     if (url == NULL || it == NULL) {
1022         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
1023         return NULL;
1024     }
1025     if ((mem = OSSL_HTTP_get(url, proxy, proxy_port, bio, rbio, bio_update_fn,
1026                              arg, headers, maxline, max_resp_len, timeout,
1027                              expected_content_type, 1 /* expect_asn1 */))
1028         != NULL)
1029         resp = BIO_mem_d2i(mem, it);
1030     BIO_free(mem);
1031     return resp;
1032 }
1033
1034 /* Post ASN.1-encoded request via HTTP to server return ASN.1 response */
1035 ASN1_VALUE *OSSL_HTTP_post_asn1(const char *server, const char *port,
1036                                 const char *path, int use_ssl,
1037                                 const char *proxy, const char *proxy_port,
1038                                 BIO *bio, BIO *rbio,
1039                                 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
1040                                 const STACK_OF(CONF_VALUE) *headers,
1041                                 const char *content_type,
1042                                 ASN1_VALUE *req, const ASN1_ITEM *req_it,
1043                                 int maxline, unsigned long max_resp_len,
1044                                 int timeout, const char *expected_ct,
1045                                 const ASN1_ITEM *rsp_it)
1046 {
1047     BIO *req_mem;
1048     BIO *res_mem;
1049     ASN1_VALUE *resp = NULL;
1050
1051     if (req == NULL) {
1052         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
1053         return NULL;
1054     }
1055     /* remaining parameters are checked indirectly */
1056
1057     req_mem = HTTP_asn1_item2bio(req_it, req);
1058     res_mem = OSSL_HTTP_transfer(server, port, path, use_ssl, proxy, proxy_port,
1059                                  bio, rbio,
1060                                  bio_update_fn, arg, headers, content_type,
1061                                  req_mem /* may be NULL */, maxline,
1062                                  max_resp_len, timeout,
1063                                  expected_ct, 1 /* expect_asn1 */, NULL);
1064     BIO_free(req_mem);
1065     if (res_mem != NULL)
1066         resp = BIO_mem_d2i(res_mem, rsp_it);
1067     BIO_free(res_mem);
1068     return resp;
1069 }
1070
1071 /* BASE64 encoder used for encoding basic proxy authentication credentials */
1072 static char *base64encode(const void *buf, size_t len)
1073 {
1074     int i;
1075     size_t outl;
1076     char *out;
1077
1078     /* Calculate size of encoded data */
1079     outl = (len / 3);
1080     if (len % 3 > 0)
1081         outl++;
1082     outl <<= 2;
1083     out = OPENSSL_malloc(outl + 1);
1084     if (out == NULL)
1085         return 0;
1086
1087     i = EVP_EncodeBlock((unsigned char *)out, buf, len);
1088     if (!ossl_assert(0 <= i && (size_t)i <= outl)) {
1089         OPENSSL_free(out);
1090         return NULL;
1091     }
1092     return out;
1093 }
1094
1095 /*
1096  * Promote the given connection BIO using the CONNECT method for a TLS proxy.
1097  * This is typically called by an app, so bio_err and prog are used unless NULL
1098  * to print additional diagnostic information in a user-oriented way.
1099  */
1100 int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port,
1101                             const char *proxyuser, const char *proxypass,
1102                             int timeout, BIO *bio_err, const char *prog)
1103 {
1104 # undef BUF_SIZE
1105 # define BUF_SIZE (8 * 1024)
1106     char *mbuf = OPENSSL_malloc(BUF_SIZE);
1107     char *mbufp;
1108     int read_len = 0;
1109     int rv;
1110     int ret = 0;
1111     BIO *fbio = BIO_new(BIO_f_buffer());
1112     time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
1113
1114     if (bio == NULL || server == NULL || port == NULL
1115             || (bio_err != NULL && prog == NULL)) {
1116         HTTPerr(0, ERR_R_PASSED_NULL_PARAMETER);
1117         goto end;
1118     }
1119
1120     if (mbuf == NULL || fbio == NULL) {
1121         BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog);
1122         goto end;
1123     }
1124     BIO_push(fbio, bio);
1125
1126     BIO_printf(fbio, "CONNECT %s:%s "HTTP_PREFIX"1.0\r\n", server, port);
1127
1128     /*
1129      * Workaround for broken proxies which would otherwise close
1130      * the connection when entering tunnel mode (e.g., Squid 2.6)
1131      */
1132     BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n");
1133
1134     /* Support for basic (base64) proxy authentication */
1135     if (proxyuser != NULL) {
1136         size_t len = strlen(proxyuser) + 1;
1137         char *proxyauth, *proxyauthenc = NULL;
1138
1139         if (proxypass != NULL)
1140             len += strlen(proxypass);
1141         proxyauth = OPENSSL_malloc(len + 1);
1142         if (proxyauth == NULL)
1143             goto end;
1144         if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser,
1145                          proxypass != NULL ? proxypass : "") != (int)len)
1146             goto proxy_end;
1147         proxyauthenc = base64encode(proxyauth, len);
1148         if (proxyauthenc != NULL) {
1149             BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc);
1150             OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc));
1151         }
1152      proxy_end:
1153         OPENSSL_clear_free(proxyauth, len);
1154         if (proxyauthenc == NULL)
1155             goto end;
1156     }
1157
1158     /* Terminate the HTTP CONNECT request */
1159     BIO_printf(fbio, "\r\n");
1160
1161     for (;;) {
1162         if (BIO_flush(fbio) != 0)
1163             break;
1164         /* potentially needs to be retried if BIO is non-blocking */
1165         if (!BIO_should_retry(fbio))
1166             break;
1167     }
1168
1169     for (;;) {
1170         /* will not actually wait if timeout == 0 */
1171         rv = BIO_wait(fbio, max_time);
1172         if (rv <= 0) {
1173             BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog,
1174                        rv == 0 ? "timed out" : "failed waiting for data");
1175             goto end;
1176         }
1177
1178         /*-
1179          * The first line is the HTTP response.
1180          * According to RFC 7230, it is formatted exactly like this:
1181          * HTTP/d.d ddd Reason text\r\n
1182          */
1183         read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1184         /* the BIO may not block, so we must wait for the 1st line to come in */
1185         if (read_len < HTTP_LINE1_MINLEN)
1186             continue;
1187
1188         /* RFC 7231 4.3.6: any 2xx status code is valid */
1189         if (strncmp(mbuf, HTTP_PREFIX, strlen(HTTP_PREFIX)) != 0) {
1190             HTTPerr(0, HTTP_R_SERVER_RESPONSE_PARSE_ERROR);
1191             BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n",
1192                        prog);
1193             /* Wrong protocol, not even HTTP, so stop reading headers */
1194             goto end;
1195         }
1196         mbufp = mbuf + strlen(HTTP_PREFIX);
1197         if (strncmp(mbufp, HTTP_VERSION_PATT, strlen(HTTP_VERSION_PATT)) != 0) {
1198             HTTPerr(0, HTTP_R_SERVER_SENT_WRONG_HTTP_VERSION);
1199             BIO_printf(bio_err,
1200                        "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
1201                        prog, HTTP_VERSION_STR_LEN, mbufp);
1202             goto end;
1203         }
1204         mbufp += HTTP_VERSION_STR_LEN;
1205         if (strncmp(mbufp, " 2", strlen(" 2")) != 0) {
1206             mbufp += 1;
1207             /* chop any trailing whitespace */
1208             while (read_len > 0 && ossl_isspace(mbuf[read_len - 1]))
1209                 read_len--;
1210             mbuf[read_len] = '\0';
1211             HTTPerr(0, HTTP_R_CONNECT_FAILURE);
1212             ERR_add_error_data(2, "Reason=", mbufp);
1213             BIO_printf(bio_err, "%s: HTTP CONNECT failed, Reason=%s\n",
1214                        prog, mbufp);
1215             goto end;
1216         }
1217         ret = 1;
1218         break;
1219     }
1220
1221     /* Read past all following headers */
1222     do {
1223         /*
1224          * TODO: This does not necessarily catch the case when the full
1225          * HTTP response came in in more than a single TCP message.
1226          */
1227         read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1228     } while (read_len > 2);
1229
1230  end:
1231     if (fbio != NULL) {
1232         (void)BIO_flush(fbio);
1233         BIO_pop(fbio);
1234         BIO_free(fbio);
1235     }
1236     OPENSSL_free(mbuf);
1237     return ret;
1238 # undef BUF_SIZE
1239 }
1240
1241 #endif /* !defined(OPENSSL_NO_SOCK) */