2 * Copyright 2001-2022 The OpenSSL Project Authors. All Rights Reserved.
3 * Copyright Siemens AG 2018-2020
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
11 #include "internal/e_os.h"
14 #include "crypto/ctype.h"
16 #include <openssl/asn1.h>
17 #include <openssl/evp.h>
18 #include <openssl/err.h>
19 #include <openssl/httperr.h>
20 #include <openssl/cmperr.h>
21 #include <openssl/buffer.h>
22 #include <openssl/http.h>
23 #include "internal/sockets.h"
24 #include "internal/common.h" /* for ossl_assert() */
26 #define HTTP_PREFIX "HTTP/"
27 #define HTTP_VERSION_PATT "1." /* allow 1.x */
28 #define HTTP_VERSION_STR_LEN sizeof(HTTP_VERSION_PATT) /* == strlen("1.0") */
29 #define HTTP_PREFIX_VERSION HTTP_PREFIX""HTTP_VERSION_PATT
30 #define HTTP_1_0 HTTP_PREFIX_VERSION"0" /* "HTTP/1.0" */
31 #define HTTP_LINE1_MINLEN (sizeof(HTTP_PREFIX_VERSION "x 200\n") - 1)
32 #define HTTP_VERSION_MAX_REDIRECTIONS 50
34 #define HTTP_STATUS_CODE_OK 200
35 #define HTTP_STATUS_CODE_MOVED_PERMANENTLY 301
36 #define HTTP_STATUS_CODE_FOUND 302
38 /* Stateful HTTP request code, supporting blocking and non-blocking I/O */
40 /* Opaque HTTP request status structure */
42 struct ossl_http_req_ctx_st {
43 int state; /* Current I/O state */
44 unsigned char *buf; /* Buffer to write request or read response */
45 int buf_size; /* Buffer size */
46 int free_wbio; /* wbio allocated internally, free with ctx */
47 BIO *wbio; /* BIO to write/send request to */
48 BIO *rbio; /* BIO to read/receive response from */
49 OSSL_HTTP_bio_cb_t upd_fn; /* Optional BIO update callback used for TLS */
50 void *upd_arg; /* Optional arg for update callback function */
51 int use_ssl; /* Use HTTPS */
52 char *proxy; /* Optional proxy name or URI */
53 char *server; /* Optional server host name */
54 char *port; /* Optional server port */
55 BIO *mem; /* Memory BIO holding request/response header */
56 BIO *req; /* BIO holding the request provided by caller */
57 int method_POST; /* HTTP method is POST (else GET) */
58 char *expected_ct; /* Optional expected Content-Type */
59 int expect_asn1; /* Response must be ASN.1-encoded */
60 unsigned char *pos; /* Current position sending data */
61 long len_to_send; /* Number of bytes still to send */
62 size_t resp_len; /* Length of response */
63 size_t max_resp_len; /* Maximum length of response, or 0 */
64 int keep_alive; /* Persistent conn. 0=no, 1=prefer, 2=require */
65 time_t max_time; /* Maximum end time of current transfer, or 0 */
66 time_t max_total_time; /* Maximum end time of total transfer, or 0 */
67 char *redirection_url; /* Location obtained from HTTP status 301/302 */
72 #define OHS_NOREAD 0x1000 /* If set no reading should be performed */
73 #define OHS_ERROR (0 | OHS_NOREAD) /* Error condition */
74 #define OHS_ADD_HEADERS (1 | OHS_NOREAD) /* Adding header lines to request */
75 #define OHS_WRITE_INIT (2 | OHS_NOREAD) /* 1st call: ready to start send */
76 #define OHS_WRITE_HDR (3 | OHS_NOREAD) /* Request header being sent */
77 #define OHS_WRITE_REQ (4 | OHS_NOREAD) /* Request contents being sent */
78 #define OHS_FLUSH (5 | OHS_NOREAD) /* Request being flushed */
79 #define OHS_FIRSTLINE 1 /* First line of response being read */
80 #define OHS_HEADERS 2 /* MIME headers of response being read */
81 #define OHS_REDIRECT 3 /* MIME headers being read, expecting Location */
82 #define OHS_ASN1_HEADER 4 /* ASN1 sequence header (tag+length) being read */
83 #define OHS_ASN1_CONTENT 5 /* ASN1 content octets being read */
84 #define OHS_ASN1_DONE (6 | OHS_NOREAD) /* ASN1 content read completed */
85 #define OHS_STREAM (7 | OHS_NOREAD) /* HTTP content stream to be read */
87 /* Low-level HTTP API implementation */
89 OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int buf_size)
91 OSSL_HTTP_REQ_CTX *rctx;
93 if (wbio == NULL || rbio == NULL) {
94 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
98 if ((rctx = OPENSSL_zalloc(sizeof(*rctx))) == NULL)
100 rctx->state = OHS_ERROR;
101 rctx->buf_size = buf_size > 0 ? buf_size : OSSL_HTTP_DEFAULT_MAX_LINE_LEN;
102 rctx->buf = OPENSSL_malloc(rctx->buf_size);
105 if (rctx->buf == NULL) {
109 rctx->max_resp_len = OSSL_HTTP_DEFAULT_MAX_RESP_LEN;
110 /* everything else is 0, e.g. rctx->len_to_send, or NULL, e.g. rctx->mem */
114 void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx)
119 * Use BIO_free_all() because bio_update_fn may prepend or append to cbio.
120 * This also frees any (e.g., SSL/TLS) BIOs linked with bio and,
121 * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer.
124 BIO_free_all(rctx->wbio);
125 /* do not free rctx->rbio */
128 OPENSSL_free(rctx->buf);
129 OPENSSL_free(rctx->proxy);
130 OPENSSL_free(rctx->server);
131 OPENSSL_free(rctx->port);
132 OPENSSL_free(rctx->expected_ct);
136 BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(const OSSL_HTTP_REQ_CTX *rctx)
139 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
145 size_t OSSL_HTTP_REQ_CTX_get_resp_len(const OSSL_HTTP_REQ_CTX *rctx)
148 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
151 return rctx->resp_len;
154 void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx,
158 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
161 rctx->max_resp_len = len != 0 ? (size_t)len : OSSL_HTTP_DEFAULT_MAX_RESP_LEN;
165 * Create request line using |rctx| and |path| (or "/" in case |path| is NULL).
166 * Server name (and port) must be given if and only if plain HTTP proxy is used.
168 int OSSL_HTTP_REQ_CTX_set_request_line(OSSL_HTTP_REQ_CTX *rctx, int method_POST,
169 const char *server, const char *port,
173 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
177 if ((rctx->mem = BIO_new(BIO_s_mem())) == NULL)
180 rctx->method_POST = method_POST != 0;
181 if (BIO_printf(rctx->mem, "%s ", rctx->method_POST ? "POST" : "GET") <= 0)
184 if (server != NULL) { /* HTTP (but not HTTPS) proxy is used */
186 * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only
187 * allowed when using a proxy
189 if (BIO_printf(rctx->mem, OSSL_HTTP_PREFIX"%s", server) <= 0)
191 if (port != NULL && BIO_printf(rctx->mem, ":%s", port) <= 0)
195 /* Make sure path includes a forward slash */
198 if (path[0] != '/' && BIO_printf(rctx->mem, "/") <= 0)
201 * Add (the rest of) the path and the HTTP version,
202 * which is fixed to 1.0 for straightforward implementation of keep-alive
204 if (BIO_printf(rctx->mem, "%s "HTTP_1_0"\r\n", path) <= 0)
208 rctx->state = OHS_ADD_HEADERS;
212 int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx,
213 const char *name, const char *value)
215 if (rctx == NULL || name == NULL) {
216 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
219 if (rctx->mem == NULL) {
220 ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
224 if (BIO_puts(rctx->mem, name) <= 0)
227 if (BIO_write(rctx->mem, ": ", 2) != 2)
229 if (BIO_puts(rctx->mem, value) <= 0)
232 return BIO_write(rctx->mem, "\r\n", 2) == 2;
235 int OSSL_HTTP_REQ_CTX_set_expected(OSSL_HTTP_REQ_CTX *rctx,
236 const char *content_type, int asn1,
237 int timeout, int keep_alive)
240 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
244 && rctx->state != OHS_ERROR && rctx->state != OHS_ADD_HEADERS) {
245 /* Cannot anymore set keep-alive in request header */
246 ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
250 OPENSSL_free(rctx->expected_ct);
251 rctx->expected_ct = NULL;
252 if (content_type != NULL
253 && (rctx->expected_ct = OPENSSL_strdup(content_type)) == NULL)
256 rctx->expect_asn1 = asn1;
258 rctx->max_time = timeout > 0 ? time(NULL) + timeout : 0;
259 else /* take over any |overall_timeout| arg of OSSL_HTTP_open(), else 0 */
260 rctx->max_time = rctx->max_total_time;
261 rctx->keep_alive = keep_alive;
265 static int set1_content(OSSL_HTTP_REQ_CTX *rctx,
266 const char *content_type, BIO *req)
270 if (rctx == NULL || (req == NULL && content_type != NULL)) {
271 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
275 if (rctx->keep_alive != 0
276 && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Connection", "keep-alive"))
283 if (!rctx->method_POST) {
284 ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
288 if (content_type != NULL
289 && BIO_printf(rctx->mem, "Content-Type: %s\r\n", content_type) <= 0)
292 /* streaming BIO may not support querying size */
293 if (((req_len = BIO_ctrl(req, BIO_CTRL_INFO, 0, NULL)) <= 0
294 || BIO_printf(rctx->mem, "Content-Length: %ld\r\n", req_len) > 0)
295 && BIO_up_ref(req)) {
302 int OSSL_HTTP_REQ_CTX_set1_req(OSSL_HTTP_REQ_CTX *rctx, const char *content_type,
303 const ASN1_ITEM *it, const ASN1_VALUE *req)
309 res = (mem = ASN1_item_i2d_mem_bio(it, req)) != NULL;
310 res = res && set1_content(rctx, content_type, mem);
315 static int add1_headers(OSSL_HTTP_REQ_CTX *rctx,
316 const STACK_OF(CONF_VALUE) *headers, const char *host)
319 int add_host = host != NULL && *host != '\0';
322 for (i = 0; i < sk_CONF_VALUE_num(headers); i++) {
323 hdr = sk_CONF_VALUE_value(headers, i);
324 if (add_host && OPENSSL_strcasecmp("host", hdr->name) == 0)
326 if (!OSSL_HTTP_REQ_CTX_add1_header(rctx, hdr->name, hdr->value))
330 if (add_host && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Host", host))
335 /* Create OSSL_HTTP_REQ_CTX structure using the values provided. */
336 static OSSL_HTTP_REQ_CTX *http_req_ctx_new(int free_wbio, BIO *wbio, BIO *rbio,
337 OSSL_HTTP_bio_cb_t bio_update_fn,
338 void *arg, int use_ssl,
340 const char *server, const char *port,
341 int buf_size, int overall_timeout)
343 OSSL_HTTP_REQ_CTX *rctx = OSSL_HTTP_REQ_CTX_new(wbio, rbio, buf_size);
347 rctx->free_wbio = free_wbio;
348 rctx->upd_fn = bio_update_fn;
350 rctx->use_ssl = use_ssl;
352 && (rctx->proxy = OPENSSL_strdup(proxy)) == NULL)
355 && (rctx->server = OPENSSL_strdup(server)) == NULL)
358 && (rctx->port = OPENSSL_strdup(port)) == NULL)
360 rctx->max_total_time =
361 overall_timeout > 0 ? time(NULL) + overall_timeout : 0;
365 OSSL_HTTP_REQ_CTX_free(rctx);
370 * Parse first HTTP response line. This should be like this: "HTTP/1.0 200 OK".
371 * We need to obtain the status code and (optional) informational message.
372 * Return any received HTTP response status code, or 0 on fatal error.
375 static int parse_http_line1(char *line, int *found_keep_alive)
378 char *code, *reason, *end;
380 if (!CHECK_AND_SKIP_PREFIX(line, HTTP_PREFIX_VERSION))
382 /* above HTTP 1.0, connection persistence is the default */
383 *found_keep_alive = *line > '0';
385 /* Skip to first whitespace (past protocol info) */
386 for (code = line; *code != '\0' && !ossl_isspace(*code); code++)
391 /* Skip past whitespace to start of response code */
392 while (*code != '\0' && ossl_isspace(*code))
397 /* Find end of response code: first whitespace after start of code */
398 for (reason = code; *reason != '\0' && !ossl_isspace(*reason); reason++)
404 /* Set end of response code and start of message */
407 /* Attempt to parse numeric code */
408 retcode = strtoul(code, &end, 10);
412 /* Skip over any leading whitespace in message */
413 while (*reason != '\0' && ossl_isspace(*reason))
416 if (*reason != '\0') {
418 * Finally zap any trailing whitespace in message (include CRLF)
421 /* chop any trailing whitespace from reason */
422 /* We know reason has a non-whitespace character so this is OK */
423 for (end = reason + strlen(reason) - 1; ossl_isspace(*end); end--)
428 case HTTP_STATUS_CODE_OK:
429 case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
430 case HTTP_STATUS_CODE_FOUND:
433 err = HTTP_R_RECEIVED_ERROR;
435 err = HTTP_R_STATUS_CODE_UNSUPPORTED;
437 ERR_raise_data(ERR_LIB_HTTP, err, "code=%s", code);
439 ERR_raise_data(ERR_LIB_HTTP, err, "code=%s, reason=%s", code,
445 for (i = 0; i < 60 && line[i] != '\0'; i++)
446 if (!ossl_isprint(line[i]))
449 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR, "content=%s", line);
453 static int check_set_resp_len(OSSL_HTTP_REQ_CTX *rctx, size_t len)
455 if (rctx->max_resp_len != 0 && len > rctx->max_resp_len)
456 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MAX_RESP_LEN_EXCEEDED,
457 "length=%zu, max=%zu", len, rctx->max_resp_len);
458 if (rctx->resp_len != 0 && rctx->resp_len != len)
459 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_INCONSISTENT_CONTENT_LENGTH,
460 "ASN.1 length=%zu, Content-Length=%zu",
461 len, rctx->resp_len);
462 rctx->resp_len = len;
466 static int may_still_retry(time_t max_time, int *ptimeout)
468 time_t time_diff, now = time(NULL);
471 if (max_time < now) {
472 ERR_raise(ERR_LIB_HTTP, HTTP_R_RETRY_TIMEOUT);
475 time_diff = max_time - now;
476 *ptimeout = time_diff > INT_MAX ? INT_MAX : (int)time_diff;
482 * Try exchanging request and response via HTTP on (non-)blocking BIO in rctx.
483 * Returns 1 on success, 0 on error or redirection, -1 on BIO_should_retry.
485 int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx)
487 int i, found_expected_ct = 0, found_keep_alive = 0;
490 const unsigned char *p;
491 char *buf, *key, *value, *line_end = NULL;
494 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
497 if (rctx->mem == NULL || rctx->wbio == NULL || rctx->rbio == NULL) {
498 ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
502 rctx->redirection_url = NULL;
504 buf = (char *)rctx->buf;
505 if ((rctx->state & OHS_NOREAD) == 0) {
506 if (rctx->expect_asn1) {
507 n = BIO_read(rctx->rbio, rctx->buf, rctx->buf_size);
509 (void)ERR_set_mark();
510 n = BIO_gets(rctx->rbio, buf, rctx->buf_size);
511 if (n == -2) { /* some BIOs, such as SSL, do not support "gets" */
512 (void)ERR_pop_to_mark();
513 n = BIO_get_line(rctx->rbio, buf, rctx->buf_size);
515 (void)ERR_clear_last_mark();
519 if (BIO_should_retry(rctx->rbio))
521 ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA);
525 /* Write data to memory BIO */
526 if (BIO_write(rctx->mem, rctx->buf, n) != n)
530 switch (rctx->state) {
531 case OHS_ADD_HEADERS:
532 /* Last operation was adding headers: need a final \r\n */
533 if (BIO_write(rctx->mem, "\r\n", 2) != 2) {
534 rctx->state = OHS_ERROR;
537 rctx->state = OHS_WRITE_INIT;
541 rctx->len_to_send = BIO_get_mem_data(rctx->mem, &rctx->pos);
542 rctx->state = OHS_WRITE_HDR;
546 /* Copy some chunk of data from rctx->mem to rctx->wbio */
548 /* Copy some chunk of data from rctx->req to rctx->wbio */
550 if (rctx->len_to_send > 0) {
551 i = BIO_write(rctx->wbio, rctx->pos, rctx->len_to_send);
553 if (BIO_should_retry(rctx->wbio))
555 rctx->state = OHS_ERROR;
559 rctx->len_to_send -= i;
562 if (rctx->state == OHS_WRITE_HDR) {
563 (void)BIO_reset(rctx->mem);
564 rctx->state = OHS_WRITE_REQ;
566 if (rctx->req != NULL && !BIO_eof(rctx->req)) {
567 n = BIO_read(rctx->req, rctx->buf, rctx->buf_size);
569 if (BIO_should_retry(rctx->rbio))
571 ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA);
574 rctx->pos = rctx->buf;
575 rctx->len_to_send = n;
578 rctx->state = OHS_FLUSH;
583 i = BIO_flush(rctx->wbio);
586 rctx->state = OHS_FIRSTLINE;
590 if (BIO_should_retry(rctx->wbio))
593 rctx->state = OHS_ERROR;
603 /* Attempt to read a line in */
606 * Due to strange memory BIO behavior with BIO_gets we have to check
607 * there's a complete line in there before calling BIO_gets or we'll
608 * just get a partial read.
610 n = BIO_get_mem_data(rctx->mem, &p);
611 if (n <= 0 || memchr(p, '\n', n) == 0) {
612 if (n >= rctx->buf_size) {
613 rctx->state = OHS_ERROR;
618 n = BIO_gets(rctx->mem, buf, rctx->buf_size);
621 if (BIO_should_retry(rctx->mem))
623 rctx->state = OHS_ERROR;
627 /* Don't allow excessive lines */
628 if (n == rctx->buf_size) {
629 ERR_raise(ERR_LIB_HTTP, HTTP_R_RESPONSE_LINE_TOO_LONG);
630 rctx->state = OHS_ERROR;
635 if (rctx->state == OHS_FIRSTLINE) {
636 switch (parse_http_line1(buf, &found_keep_alive)) {
637 case HTTP_STATUS_CODE_OK:
638 rctx->state = OHS_HEADERS;
640 case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
641 case HTTP_STATUS_CODE_FOUND: /* i.e., moved temporarily */
642 if (!rctx->method_POST) { /* method is GET */
643 rctx->state = OHS_REDIRECT;
646 ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED);
647 /* redirection is not supported/recommended for POST */
650 rctx->state = OHS_ERROR;
655 value = strchr(key, ':');
658 while (ossl_isspace(*value))
660 line_end = strchr(value, '\r');
661 if (line_end == NULL)
662 line_end = strchr(value, '\n');
663 if (line_end != NULL)
666 if (value != NULL && line_end != NULL) {
667 if (rctx->state == OHS_REDIRECT
668 && OPENSSL_strcasecmp(key, "Location") == 0) {
669 rctx->redirection_url = value;
672 if (rctx->state == OHS_HEADERS && rctx->expected_ct != NULL
673 && OPENSSL_strcasecmp(key, "Content-Type") == 0) {
674 if (OPENSSL_strcasecmp(rctx->expected_ct, value) != 0) {
675 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_UNEXPECTED_CONTENT_TYPE,
676 "expected=%s, actual=%s",
677 rctx->expected_ct, value);
680 found_expected_ct = 1;
683 /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
684 if (OPENSSL_strcasecmp(key, "Connection") == 0) {
685 if (OPENSSL_strcasecmp(value, "keep-alive") == 0)
686 found_keep_alive = 1;
687 else if (OPENSSL_strcasecmp(value, "close") == 0)
688 found_keep_alive = 0;
689 } else if (OPENSSL_strcasecmp(key, "Content-Length") == 0) {
690 resp_len = (size_t)strtoul(value, &line_end, 10);
691 if (line_end == value || *line_end != '\0') {
692 ERR_raise_data(ERR_LIB_HTTP,
693 HTTP_R_ERROR_PARSING_CONTENT_LENGTH,
697 if (!check_set_resp_len(rctx, resp_len))
702 /* Look for blank line indicating end of headers */
703 for (p = rctx->buf; *p != '\0'; p++) {
704 if (*p != '\r' && *p != '\n')
707 if (*p != '\0') /* not end of headers */
710 if (rctx->keep_alive != 0 /* do not let server initiate keep_alive */
711 && !found_keep_alive /* otherwise there is no change */) {
712 if (rctx->keep_alive == 2) {
713 rctx->keep_alive = 0;
714 ERR_raise(ERR_LIB_HTTP, HTTP_R_SERVER_CANCELED_CONNECTION);
717 rctx->keep_alive = 0;
720 if (rctx->state == OHS_ERROR)
723 if (rctx->expected_ct != NULL && !found_expected_ct) {
724 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MISSING_CONTENT_TYPE,
725 "expected=%s", rctx->expected_ct);
728 if (rctx->state == OHS_REDIRECT) {
729 /* http status code indicated redirect but there was no Location */
730 ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_REDIRECT_LOCATION);
734 if (!rctx->expect_asn1) {
735 rctx->state = OHS_STREAM;
739 rctx->state = OHS_ASN1_HEADER;
742 case OHS_ASN1_HEADER:
744 * Now reading ASN1 header: can read at least 2 bytes which is enough
745 * for ASN1 SEQUENCE header and either length field or at least the
746 * length of the length field.
748 n = BIO_get_mem_data(rctx->mem, &p);
752 /* Check it is an ASN1 SEQUENCE */
753 if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
754 ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_ASN1_ENCODING);
758 /* Check out length field */
759 if ((*p & 0x80) != 0) {
761 * If MSB set on initial length octet we can now always read 6
762 * octets: make sure we have them.
767 /* Not NDEF or excessive length */
768 if (n == 0 || (n > 4)) {
769 ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_ASN1_LENGTH);
774 for (i = 0; i < n; i++) {
782 if (!check_set_resp_len(rctx, resp_len))
785 rctx->state = OHS_ASN1_CONTENT;
788 case OHS_ASN1_CONTENT:
790 n = BIO_get_mem_data(rctx->mem, NULL);
791 if (n < 0 || (size_t)n < rctx->resp_len)
794 rctx->state = OHS_ASN1_DONE;
799 int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX *rctx,
800 ASN1_VALUE **pval, const ASN1_ITEM *it)
802 const unsigned char *p;
806 if ((rv = OSSL_HTTP_REQ_CTX_nbio(rctx)) != 1)
808 *pval = ASN1_item_d2i(NULL, &p, BIO_get_mem_data(rctx->mem, &p), it);
809 return *pval != NULL;
813 #ifndef OPENSSL_NO_SOCK
815 /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
816 static BIO *http_new_bio(const char *server /* optionally includes ":port" */,
817 const char *server_port /* explicit server port */,
819 const char *proxy /* optionally includes ":port" */,
820 const char *proxy_port /* explicit proxy port */)
822 const char *host = server;
823 const char *port = server_port;
826 if (!ossl_assert(server != NULL))
834 if (port == NULL && strchr(host, ':') == NULL)
835 port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
837 cbio = BIO_new_connect(host /* optionally includes ":port" */);
841 (void)BIO_set_conn_port(cbio, port);
846 #endif /* OPENSSL_NO_SOCK */
848 /* Exchange request and response via HTTP on (non-)blocking BIO */
849 BIO *OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX *rctx)
854 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
859 rv = OSSL_HTTP_REQ_CTX_nbio(rctx);
862 /* BIO_should_retry was true */
863 /* will not actually wait if rctx->max_time == 0 */
864 if (BIO_wait(rctx->rbio, rctx->max_time, 100 /* milliseconds */) <= 0)
869 if (rctx->redirection_url == NULL) { /* an error occurred */
870 if (rctx->len_to_send > 0)
871 ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_SENDING);
873 ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_RECEIVING);
877 return rctx->state == OHS_STREAM ? rctx->rbio : rctx->mem;
880 int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX *rctx)
882 return rctx != NULL && rctx->keep_alive != 0;
885 /* High-level HTTP API implementation */
887 /* Initiate an HTTP session using bio, else use given server, proxy, etc. */
888 OSSL_HTTP_REQ_CTX *OSSL_HTTP_open(const char *server, const char *port,
889 const char *proxy, const char *no_proxy,
890 int use_ssl, BIO *bio, BIO *rbio,
891 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
892 int buf_size, int overall_timeout)
894 BIO *cbio; /* == bio if supplied, used as connection BIO if rbio is NULL */
895 OSSL_HTTP_REQ_CTX *rctx = NULL;
897 if (use_ssl && bio_update_fn == NULL) {
898 ERR_raise(ERR_LIB_HTTP, HTTP_R_TLS_NOT_ENABLED);
901 if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) {
902 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
908 if (proxy != NULL || no_proxy != NULL) {
909 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
913 #ifndef OPENSSL_NO_SOCK
914 char *proxy_host = NULL, *proxy_port = NULL;
916 if (server == NULL) {
917 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
920 if (port != NULL && *port == '\0')
922 if (port == NULL && strchr(server, ':') == NULL)
923 port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
924 proxy = OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl);
926 && !OSSL_HTTP_parse_url(proxy, NULL /* use_ssl */, NULL /* user */,
927 &proxy_host, &proxy_port, NULL /* num */,
928 NULL /* path */, NULL, NULL))
930 cbio = http_new_bio(server, port, use_ssl, proxy_host, proxy_port);
931 OPENSSL_free(proxy_host);
932 OPENSSL_free(proxy_port);
936 ERR_raise(ERR_LIB_HTTP, HTTP_R_SOCK_NOT_SUPPORTED);
941 (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
942 if (rbio == NULL && BIO_do_connect_retry(cbio, overall_timeout, -1) <= 0) {
943 if (bio == NULL) /* cbio was not provided by caller */
947 /* now overall_timeout is guaranteed to be >= 0 */
949 /* adapt in order to fix callback design flaw, see #17088 */
950 /* callback can be used to wrap or prepend TLS session */
951 if (bio_update_fn != NULL) {
952 BIO *orig_bio = cbio;
954 cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl);
956 if (bio == NULL) /* cbio was not provided by caller */
957 BIO_free_all(orig_bio);
962 rctx = http_req_ctx_new(bio == NULL, cbio, rbio != NULL ? rbio : cbio,
963 bio_update_fn, arg, use_ssl, proxy, server, port,
964 buf_size, overall_timeout);
968 /* remove any spurious error queue entries by ssl_add_cert_chain() */
969 (void)ERR_pop_to_mark();
971 (void)ERR_clear_last_mark();
976 int OSSL_HTTP_set1_request(OSSL_HTTP_REQ_CTX *rctx, const char *path,
977 const STACK_OF(CONF_VALUE) *headers,
978 const char *content_type, BIO *req,
979 const char *expected_content_type, int expect_asn1,
980 size_t max_resp_len, int timeout, int keep_alive)
985 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
988 use_http_proxy = rctx->proxy != NULL && !rctx->use_ssl;
989 if (use_http_proxy && rctx->server == NULL) {
990 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
993 rctx->max_resp_len = max_resp_len; /* allows for 0: indefinite */
995 return OSSL_HTTP_REQ_CTX_set_request_line(rctx, req != NULL,
996 use_http_proxy ? rctx->server
997 : NULL, rctx->port, path)
998 && add1_headers(rctx, headers, rctx->server)
999 && OSSL_HTTP_REQ_CTX_set_expected(rctx, expected_content_type,
1000 expect_asn1, timeout, keep_alive)
1001 && set1_content(rctx, content_type, req);
1005 * Exchange single HTTP request and response according to rctx.
1006 * If rctx->method_POST then use POST, else use GET and ignore content_type.
1007 * The redirection_url output (freed by caller) parameter is used only for GET.
1009 BIO *OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX *rctx, char **redirection_url)
1014 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
1018 if (redirection_url != NULL)
1019 *redirection_url = NULL; /* do this beforehand to prevent dbl free */
1021 resp = OSSL_HTTP_REQ_CTX_exchange(rctx);
1023 if (rctx->redirection_url != NULL) {
1024 if (redirection_url == NULL)
1025 ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED);
1027 /* may be NULL if out of memory: */
1028 *redirection_url = OPENSSL_strdup(rctx->redirection_url);
1031 unsigned long err = ERR_peek_error();
1032 int lib = ERR_GET_LIB(err);
1033 int reason = ERR_GET_REASON(err);
1035 if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP
1036 || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT)
1037 || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR)
1038 #ifndef OPENSSL_NO_CMP
1039 || (lib == ERR_LIB_CMP
1040 && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
1043 if (rctx->server != NULL) {
1044 BIO_snprintf(buf, sizeof(buf), "server=http%s://%s%s%s",
1045 rctx->use_ssl ? "s" : "", rctx->server,
1046 rctx->port != NULL ? ":" : "",
1047 rctx->port != NULL ? rctx->port : "");
1048 ERR_add_error_data(1, buf);
1050 if (rctx->proxy != NULL)
1051 ERR_add_error_data(2, " proxy=", rctx->proxy);
1053 BIO_snprintf(buf, sizeof(buf), " peer has disconnected%s",
1054 rctx->use_ssl ? " violating the protocol" :
1055 ", likely because it requires the use of TLS");
1056 ERR_add_error_data(1, buf);
1062 if (resp != NULL && !BIO_up_ref(resp))
1067 static int redirection_ok(int n_redir, const char *old_url, const char *new_url)
1069 if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) {
1070 ERR_raise(ERR_LIB_HTTP, HTTP_R_TOO_MANY_REDIRECTIONS);
1073 if (*new_url == '/') /* redirection to same server => same protocol */
1075 if (HAS_PREFIX(old_url, OSSL_HTTPS_NAME":") &&
1076 !HAS_PREFIX(new_url, OSSL_HTTPS_NAME":")) {
1077 ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP);
1083 /* Get data via HTTP from server at given URL, potentially with redirection */
1084 BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy,
1085 BIO *bio, BIO *rbio,
1086 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
1087 int buf_size, const STACK_OF(CONF_VALUE) *headers,
1088 const char *expected_ct, int expect_asn1,
1089 size_t max_resp_len, int timeout)
1091 char *current_url, *redirection_url = NULL;
1097 OSSL_HTTP_REQ_CTX *rctx;
1099 time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
1102 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
1105 if ((current_url = OPENSSL_strdup(url)) == NULL)
1109 if (!OSSL_HTTP_parse_url(current_url, &use_ssl, NULL /* user */, &host,
1110 &port, NULL /* port_num */, &path, NULL, NULL))
1113 rctx = OSSL_HTTP_open(host, port, proxy, no_proxy,
1114 use_ssl, bio, rbio, bio_update_fn, arg,
1118 if (!OSSL_HTTP_set1_request(rctx, path, headers,
1119 NULL /* content_type */,
1121 expected_ct, expect_asn1, max_resp_len,
1122 -1 /* use same max time (timeout) */,
1123 0 /* no keep_alive */))
1124 OSSL_HTTP_REQ_CTX_free(rctx);
1126 resp = OSSL_HTTP_exchange(rctx, &redirection_url);
1129 if (resp == NULL && redirection_url != NULL) {
1130 if (redirection_ok(++n_redirs, current_url, redirection_url)
1131 && may_still_retry(max_time, &timeout)) {
1132 (void)BIO_reset(bio);
1133 OPENSSL_free(current_url);
1134 current_url = redirection_url;
1135 if (*redirection_url == '/') { /* redirection to same server */
1136 path = OPENSSL_strdup(redirection_url);
1141 (void)OSSL_HTTP_close(rctx, 1);
1144 /* if redirection not allowed, ignore it */
1145 OPENSSL_free(redirection_url);
1149 if (!OSSL_HTTP_close(rctx, resp != NULL)) {
1155 OPENSSL_free(current_url);
1159 /* Exchange request and response over a connection managed via |prctx| */
1160 BIO *OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX **prctx,
1161 const char *server, const char *port,
1162 const char *path, int use_ssl,
1163 const char *proxy, const char *no_proxy,
1164 BIO *bio, BIO *rbio,
1165 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
1166 int buf_size, const STACK_OF(CONF_VALUE) *headers,
1167 const char *content_type, BIO *req,
1168 const char *expected_ct, int expect_asn1,
1169 size_t max_resp_len, int timeout, int keep_alive)
1171 OSSL_HTTP_REQ_CTX *rctx = prctx == NULL ? NULL : *prctx;
1175 rctx = OSSL_HTTP_open(server, port, proxy, no_proxy,
1176 use_ssl, bio, rbio, bio_update_fn, arg,
1178 timeout = -1; /* Already set during opening the connection */
1181 if (OSSL_HTTP_set1_request(rctx, path, headers, content_type, req,
1182 expected_ct, expect_asn1,
1183 max_resp_len, timeout, keep_alive))
1184 resp = OSSL_HTTP_exchange(rctx, NULL);
1185 if (resp == NULL || !OSSL_HTTP_is_alive(rctx)) {
1186 if (!OSSL_HTTP_close(rctx, resp != NULL)) {
1198 int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX *rctx, int ok)
1203 /* callback can be used to finish TLS session and free its BIO */
1204 if (rctx != NULL && rctx->upd_fn != NULL) {
1205 wbio = (*rctx->upd_fn)(rctx->wbio, rctx->upd_arg,
1206 0 /* disconnect */, ok);
1211 OSSL_HTTP_REQ_CTX_free(rctx);
1215 /* BASE64 encoder used for encoding basic proxy authentication credentials */
1216 static char *base64encode(const void *buf, size_t len)
1222 /* Calculate size of encoded data */
1227 out = OPENSSL_malloc(outl + 1);
1231 i = EVP_EncodeBlock((unsigned char *)out, buf, len);
1232 if (!ossl_assert(0 <= i && (size_t)i <= outl)) {
1240 * Promote the given connection BIO using the CONNECT method for a TLS proxy.
1241 * This is typically called by an app, so bio_err and prog are used unless NULL
1242 * to print additional diagnostic information in a user-oriented way.
1244 int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port,
1245 const char *proxyuser, const char *proxypass,
1246 int timeout, BIO *bio_err, const char *prog)
1249 #define BUF_SIZE (8 * 1024)
1250 char *mbuf = OPENSSL_malloc(BUF_SIZE);
1254 BIO *fbio = BIO_new(BIO_f_buffer());
1256 time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
1258 if (bio == NULL || server == NULL
1259 || (bio_err != NULL && prog == NULL)) {
1260 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
1263 if (port == NULL || *port == '\0')
1264 port = OSSL_HTTPS_PORT;
1266 if (mbuf == NULL || fbio == NULL) {
1267 BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog);
1270 BIO_push(fbio, bio);
1272 BIO_printf(fbio, "CONNECT %s:%s "HTTP_1_0"\r\n", server, port);
1275 * Workaround for broken proxies which would otherwise close
1276 * the connection when entering tunnel mode (e.g., Squid 2.6)
1278 BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n");
1280 /* Support for basic (base64) proxy authentication */
1281 if (proxyuser != NULL) {
1282 size_t len = strlen(proxyuser) + 1;
1283 char *proxyauth, *proxyauthenc = NULL;
1285 if (proxypass != NULL)
1286 len += strlen(proxypass);
1287 proxyauth = OPENSSL_malloc(len + 1);
1288 if (proxyauth == NULL)
1290 if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser,
1291 proxypass != NULL ? proxypass : "") != (int)len)
1293 proxyauthenc = base64encode(proxyauth, len);
1294 if (proxyauthenc != NULL) {
1295 BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc);
1296 OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc));
1299 OPENSSL_clear_free(proxyauth, len);
1300 if (proxyauthenc == NULL)
1304 /* Terminate the HTTP CONNECT request */
1305 BIO_printf(fbio, "\r\n");
1308 if (BIO_flush(fbio) != 0)
1310 /* potentially needs to be retried if BIO is non-blocking */
1311 if (!BIO_should_retry(fbio))
1316 /* will not actually wait if timeout == 0 */
1317 rv = BIO_wait(fbio, max_time, 100 /* milliseconds */);
1319 BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog,
1320 rv == 0 ? "timed out" : "failed waiting for data");
1325 * The first line is the HTTP response.
1326 * According to RFC 7230, it is formatted exactly like this:
1327 * HTTP/d.d ddd reason text\r\n
1329 read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1330 /* the BIO may not block, so we must wait for the 1st line to come in */
1331 if (read_len < (int)HTTP_LINE1_MINLEN)
1334 /* Check for HTTP/1.x */
1336 if (!CHECK_AND_SKIP_PREFIX(mbufp, HTTP_PREFIX)) {
1337 ERR_raise(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR);
1338 BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n",
1340 /* Wrong protocol, not even HTTP, so stop reading headers */
1343 if (!HAS_PREFIX(mbufp, HTTP_VERSION_PATT)) {
1344 ERR_raise(ERR_LIB_HTTP, HTTP_R_RECEIVED_WRONG_HTTP_VERSION);
1346 "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
1347 prog, (int)HTTP_VERSION_STR_LEN, mbufp);
1350 mbufp += HTTP_VERSION_STR_LEN;
1352 /* RFC 7231 4.3.6: any 2xx status code is valid */
1353 if (!HAS_PREFIX(mbufp, " 2")) {
1354 if (ossl_isspace(*mbufp))
1356 /* chop any trailing whitespace */
1357 while (read_len > 0 && ossl_isspace(mbuf[read_len - 1]))
1359 mbuf[read_len] = '\0';
1360 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_CONNECT_FAILURE,
1361 "reason=%s", mbufp);
1362 BIO_printf(bio_err, "%s: HTTP CONNECT failed, reason=%s\n",
1370 /* Read past all following headers */
1373 * This does not necessarily catch the case when the full
1374 * HTTP response came in in more than a single TCP message.
1376 read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1377 } while (read_len > 2);
1381 (void)BIO_flush(fbio);