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