2 * Copyright 2001-2021 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
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/cryptlib.h" /* for ossl_assert() */
26 #include "http_local.h"
28 #define HTTP_PREFIX "HTTP/"
29 #define HTTP_VERSION_PATT "1." /* allow 1.x */
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_VERSION_PATT_LEN strlen(HTTP_PREFIX_VERSION)
33 #define HTTP_VERSION_STR_LEN (HTTP_VERSION_PATT_LEN + 1)
34 #define HTTP_LINE1_MINLEN ((int)strlen(HTTP_PREFIX_VERSION "x 200\n"))
35 #define HTTP_VERSION_MAX_REDIRECTIONS 50
37 #define HTTP_STATUS_CODE_OK 200
38 #define HTTP_STATUS_CODE_MOVED_PERMANENTLY 301
39 #define HTTP_STATUS_CODE_FOUND 302
41 /* Stateful HTTP request code, supporting blocking and non-blocking I/O */
43 /* Opaque HTTP request status structure */
45 struct ossl_http_req_ctx_st
{
46 int state
; /* Current I/O state */
47 unsigned char *readbuf
; /* Buffer for reading response by line */
48 int readbuflen
; /* Buffer length, equals buf_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 host name */
57 char *port
; /* Optional server port */
58 BIO
*mem
; /* Memory BIO holding request and response */
59 int method_POST
; /* HTTP method is POST (else GET) */
60 char *expected_ct
; /* Optional expected Content-Type */
61 int expect_asn1
; /* Response must be ASN.1-encoded */
62 long len_to_send
; /* Number of bytes in request still to send */
63 unsigned long resp_len
; /* Length of response */
64 size_t max_resp_len
; /* Maximum length of response */
65 int keep_alive
; /* Persistent conn. 0=no, 1=prefer, 2=require */
66 time_t max_time
; /* Maximum end time of current transfer, or 0 */
67 time_t max_total_time
; /* Maximum end time of total transfer, or 0 */
68 char *redirection_url
; /* Location obtained from HTTP status 301/302 */
73 #define OHS_NOREAD 0x1000 /* If set no reading should be performed */
74 #define OHS_ERROR (0 | OHS_NOREAD) /* Error condition */
75 #define OHS_FIRSTLINE 1 /* First line being read */
76 #define OHS_REDIRECT 0xa /* Looking for redirection location */
77 #define OHS_HEADERS 2 /* MIME headers being read */
78 #define OHS_ASN1_HEADER 3 /* HTTP initial header (tag+length) being read */
79 #define OHS_CONTENT 4 /* HTTP content octets being read */
80 #define OHS_WRITE_INIT (5 | OHS_NOREAD) /* 1st call: ready to start send */
81 #define OHS_WRITE (6 | OHS_NOREAD) /* Request being sent */
82 #define OHS_FLUSH (7 | OHS_NOREAD) /* Request being flushed */
83 #define OHS_DONE (8 | OHS_NOREAD) /* Completed */
84 #define OHS_HTTP_HEADER (9 | OHS_NOREAD) /* Headers set, w/o final \r\n */
86 /* Low-level HTTP API implementation */
88 OSSL_HTTP_REQ_CTX
*OSSL_HTTP_REQ_CTX_new(BIO
*wbio
, BIO
*rbio
, int buf_size
)
90 OSSL_HTTP_REQ_CTX
*rctx
;
92 if (wbio
== NULL
|| rbio
== NULL
) {
93 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
97 if ((rctx
= OPENSSL_zalloc(sizeof(*rctx
))) == NULL
)
99 rctx
->state
= OHS_ERROR
;
100 rctx
->readbuflen
= buf_size
> 0 ? buf_size
: HTTP_DEFAULT_MAX_LINE_LENGTH
;
101 rctx
->readbuf
= OPENSSL_malloc(rctx
->readbuflen
);
104 if (rctx
->readbuf
== NULL
) {
108 rctx
->max_resp_len
= HTTP_DEFAULT_MAX_RESP_LEN
;
109 /* everything else is 0, e.g. rctx->len_to_send, or NULL, e.g. rctx->mem */
113 void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX
*rctx
)
118 * Use BIO_free_all() because bio_update_fn may prepend or append to cbio.
119 * This also frees any (e.g., SSL/TLS) BIOs linked with bio and,
120 * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer.
123 BIO_free_all(rctx
->wbio
);
124 /* do not free rctx->rbio */
125 BIO_free(rctx
->mem
); /* this may indirectly call ERR_clear_error() */
126 OPENSSL_free(rctx
->readbuf
);
127 OPENSSL_free(rctx
->proxy
);
128 OPENSSL_free(rctx
->server
);
129 OPENSSL_free(rctx
->port
);
130 OPENSSL_free(rctx
->expected_ct
);
134 BIO
*OSSL_HTTP_REQ_CTX_get0_mem_bio(const OSSL_HTTP_REQ_CTX
*rctx
)
137 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
143 size_t OSSL_HTTP_REQ_CTX_get_resp_len(const OSSL_HTTP_REQ_CTX
*rctx
)
146 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
149 return rctx
->resp_len
;
152 void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX
*rctx
,
156 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
159 rctx
->max_resp_len
= len
!= 0 ? (size_t)len
: HTTP_DEFAULT_MAX_RESP_LEN
;
163 * Create request line using |rctx| and |path| (or "/" in case |path| is NULL).
164 * Server name (and port) must be given if and only if plain HTTP proxy is used.
166 int OSSL_HTTP_REQ_CTX_set_request_line(OSSL_HTTP_REQ_CTX
*rctx
, int method_POST
,
167 const char *server
, const char *port
,
171 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
175 if ((rctx
->mem
= BIO_new(BIO_s_mem())) == NULL
)
178 rctx
->method_POST
= method_POST
!= 0;
179 if (BIO_printf(rctx
->mem
, "%s ", rctx
->method_POST
? "POST" : "GET") <= 0)
182 if (server
!= NULL
) { /* HTTP (but not HTTPS) proxy is used */
184 * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only
185 * allowed when using a proxy
187 if (BIO_printf(rctx
->mem
, OSSL_HTTP_PREFIX
"%s", server
) <= 0)
189 if (port
!= NULL
&& BIO_printf(rctx
->mem
, ":%s", port
) <= 0)
193 /* Make sure path includes a forward slash */
196 if (path
[0] != '/' && BIO_printf(rctx
->mem
, "/") <= 0)
199 if (BIO_printf(rctx
->mem
, "%s "HTTP_1_0
"\r\n", path
) <= 0)
202 rctx
->state
= OHS_HTTP_HEADER
;
206 int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX
*rctx
,
207 const char *name
, const char *value
)
209 if (rctx
== NULL
|| name
== NULL
) {
210 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
213 if (rctx
->mem
== NULL
) {
214 ERR_raise(ERR_LIB_HTTP
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
218 if (BIO_puts(rctx
->mem
, name
) <= 0)
221 if (BIO_write(rctx
->mem
, ": ", 2) != 2)
223 if (BIO_puts(rctx
->mem
, value
) <= 0)
226 return BIO_write(rctx
->mem
, "\r\n", 2) == 2;
229 int OSSL_HTTP_REQ_CTX_set_expected(OSSL_HTTP_REQ_CTX
*rctx
,
230 const char *content_type
, int asn1
,
231 int timeout
, int keep_alive
)
234 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
238 && rctx
->state
!= OHS_ERROR
&& rctx
->state
!= OHS_HTTP_HEADER
) {
239 /* Cannot anymore set keep-alive in request header */
240 ERR_raise(ERR_LIB_HTTP
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
244 OPENSSL_free(rctx
->expected_ct
);
245 rctx
->expected_ct
= NULL
;
246 if (content_type
!= NULL
247 && (rctx
->expected_ct
= OPENSSL_strdup(content_type
)) == NULL
)
250 rctx
->expect_asn1
= asn1
;
252 rctx
->max_time
= timeout
> 0 ? time(NULL
) + timeout
: 0;
254 rctx
->max_time
= rctx
->max_total_time
;
255 rctx
->keep_alive
= keep_alive
;
259 static int ossl_http_req_ctx_set_content(OSSL_HTTP_REQ_CTX
*rctx
,
260 const char *content_type
, BIO
*req_mem
)
262 const unsigned char *req
;
265 if (rctx
== NULL
|| (req_mem
== NULL
&& content_type
!= NULL
)) {
266 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
270 if (rctx
->keep_alive
!= 0
271 && !OSSL_HTTP_REQ_CTX_add1_header(rctx
, "Connection", "keep-alive"))
273 rctx
->state
= OHS_WRITE_INIT
;
277 if (!rctx
->method_POST
) {
278 ERR_raise(ERR_LIB_HTTP
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
282 if (content_type
!= NULL
283 && BIO_printf(rctx
->mem
, "Content-Type: %s\r\n", content_type
) <= 0)
286 if ((req_len
= BIO_get_mem_data(req_mem
, &req
)) <= 0)
289 return BIO_printf(rctx
->mem
, "Content-Length: %ld\r\n\r\n", req_len
) > 0
290 && BIO_write(rctx
->mem
, req
, req_len
) == (int)req_len
;
293 int OSSL_HTTP_REQ_CTX_set1_req(OSSL_HTTP_REQ_CTX
*rctx
, const char *content_type
,
294 const ASN1_ITEM
*it
, const ASN1_VALUE
*req
)
299 if (rctx
== NULL
|| it
== NULL
|| req
== NULL
) {
300 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
304 res
= (mem
= ASN1_item_i2d_mem_bio(it
, req
)) != NULL
305 && ossl_http_req_ctx_set_content(rctx
, content_type
, mem
);
310 static int OSSL_HTTP_REQ_CTX_add1_headers(OSSL_HTTP_REQ_CTX
*rctx
,
311 const STACK_OF(CONF_VALUE
) *headers
,
315 int add_host
= host
!= NULL
&& *host
!= '\0';
318 for (i
= 0; i
< sk_CONF_VALUE_num(headers
); i
++) {
319 hdr
= sk_CONF_VALUE_value(headers
, i
);
320 if (add_host
&& strcasecmp("host", hdr
->name
) == 0)
322 if (!OSSL_HTTP_REQ_CTX_add1_header(rctx
, hdr
->name
, hdr
->value
))
326 if (add_host
&& !OSSL_HTTP_REQ_CTX_add1_header(rctx
, "Host", host
))
331 /* Create OSSL_HTTP_REQ_CTX structure using the values provided. */
332 static OSSL_HTTP_REQ_CTX
*http_req_ctx_new(int free_wbio
, BIO
*wbio
, BIO
*rbio
,
333 OSSL_HTTP_bio_cb_t bio_update_fn
,
334 void *arg
, int use_ssl
,
336 const char *server
, const char *port
,
337 int buf_size
, unsigned long max_len
,
340 OSSL_HTTP_REQ_CTX
*rctx
= OSSL_HTTP_REQ_CTX_new(wbio
, rbio
, buf_size
);
344 OSSL_HTTP_REQ_CTX_set_max_response_length(rctx
, max_len
);
345 rctx
->free_wbio
= free_wbio
;
346 rctx
->upd_fn
= bio_update_fn
;
348 rctx
->use_ssl
= use_ssl
;
350 && (rctx
->proxy
= OPENSSL_strdup(proxy
)) == NULL
)
353 && (rctx
->server
= OPENSSL_strdup(server
)) == NULL
)
356 && (rctx
->port
= OPENSSL_strdup(port
)) == NULL
)
358 rctx
->max_total_time
=
359 overall_timeout
> 0 ? time(NULL
) + overall_timeout
: 0;
363 OSSL_HTTP_REQ_CTX_free(rctx
);
368 * Parse first HTTP response line. This should be like this: "HTTP/1.0 200 OK".
369 * We need to obtain the numeric code and (optional) informational message.
372 static int parse_http_line1(char *line
, int *found_keep_alive
)
375 char *code
, *reason
, *end
;
377 if (strncmp(line
, HTTP_PREFIX_VERSION
, HTTP_VERSION_PATT_LEN
) != 0)
379 /* above HTTP 1.0, connection persistence is the default */
380 *found_keep_alive
= line
[HTTP_VERSION_PATT_LEN
] > '0';
382 /* Skip to first whitespace (past protocol info) */
383 for (code
= line
; *code
!= '\0' && !ossl_isspace(*code
); code
++)
388 /* Skip past whitespace to start of response code */
389 while (*code
!= '\0' && ossl_isspace(*code
))
394 /* Find end of response code: first whitespace after start of code */
395 for (reason
= code
; *reason
!= '\0' && !ossl_isspace(*reason
); reason
++)
401 /* Set end of response code and start of message */
404 /* Attempt to parse numeric code */
405 retcode
= strtoul(code
, &end
, 10);
409 /* Skip over any leading whitespace in message */
410 while (*reason
!= '\0' && ossl_isspace(*reason
))
413 if (*reason
!= '\0') {
415 * Finally zap any trailing whitespace in message (include CRLF)
418 /* chop any trailing whitespace from reason */
419 /* We know reason has a non-whitespace character so this is OK */
420 for (end
= reason
+ strlen(reason
) - 1; ossl_isspace(*end
); end
--)
425 case HTTP_STATUS_CODE_OK
:
426 case HTTP_STATUS_CODE_MOVED_PERMANENTLY
:
427 case HTTP_STATUS_CODE_FOUND
:
431 retcode
= HTTP_R_STATUS_CODE_UNSUPPORTED
;
433 retcode
= HTTP_R_RECEIVED_ERROR
;
435 ERR_raise_data(ERR_LIB_HTTP
, retcode
, "Code=%s", code
);
437 ERR_raise_data(ERR_LIB_HTTP
, retcode
,
438 "Code=%s, Reason=%s", code
, reason
);
443 ERR_raise_data(ERR_LIB_HTTP
, HTTP_R_HEADER_PARSE_ERROR
, "%.40s", line
);
447 static int check_set_resp_len(OSSL_HTTP_REQ_CTX
*rctx
, unsigned long len
)
449 if (len
> rctx
->max_resp_len
)
450 ERR_raise_data(ERR_LIB_HTTP
, HTTP_R_MAX_RESP_LEN_EXCEEDED
,
451 "length=%lu, max=%lu", len
, rctx
->max_resp_len
);
452 if (rctx
->resp_len
!= 0 && rctx
->resp_len
!= len
)
453 ERR_raise_data(ERR_LIB_HTTP
, HTTP_R_INCONSISTENT_CONTENT_LENGTH
,
454 "ASN.1 length=%lu, Content-Length=%lu",
455 len
, rctx
->resp_len
);
456 rctx
->resp_len
= len
;
461 * Try exchanging request and response via HTTP on (non-)blocking BIO in rctx.
462 * Returns 1 on success, 0 on error or redirection, -1 on BIO_should_retry.
464 int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX
*rctx
)
466 int i
, found_expected_ct
= 0, found_keep_alive
= 0;
468 unsigned long resp_len
;
469 const unsigned char *p
;
470 char *key
, *value
, *line_end
= NULL
;
473 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
476 if (rctx
->mem
== NULL
|| rctx
->wbio
== NULL
|| rctx
->rbio
== NULL
) {
477 ERR_raise(ERR_LIB_HTTP
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
481 rctx
->redirection_url
= NULL
;
483 if ((rctx
->state
& OHS_NOREAD
) == 0) {
484 n
= BIO_read(rctx
->rbio
, rctx
->readbuf
, rctx
->readbuflen
);
486 if (BIO_should_retry(rctx
->rbio
))
488 ERR_raise(ERR_LIB_HTTP
, HTTP_R_FAILED_READING_DATA
);
492 /* Write data to memory BIO */
493 if (BIO_write(rctx
->mem
, rctx
->readbuf
, n
) != n
)
497 switch (rctx
->state
) {
498 case OHS_HTTP_HEADER
:
499 /* Last operation was adding headers: need a final \r\n */
500 if (BIO_write(rctx
->mem
, "\r\n", 2) != 2) {
501 rctx
->state
= OHS_ERROR
;
504 rctx
->state
= OHS_WRITE_INIT
;
508 rctx
->len_to_send
= BIO_get_mem_data(rctx
->mem
, NULL
);
509 rctx
->state
= OHS_WRITE
;
513 n
= BIO_get_mem_data(rctx
->mem
, &p
) - rctx
->len_to_send
;
514 i
= BIO_write(rctx
->wbio
, p
+ n
, rctx
->len_to_send
);
517 if (BIO_should_retry(rctx
->wbio
))
519 rctx
->state
= OHS_ERROR
;
523 rctx
->len_to_send
-= i
;
525 if (rctx
->len_to_send
> 0)
528 rctx
->state
= OHS_FLUSH
;
530 (void)BIO_reset(rctx
->mem
);
535 i
= BIO_flush(rctx
->wbio
);
538 rctx
->state
= OHS_FIRSTLINE
;
542 if (BIO_should_retry(rctx
->wbio
))
545 rctx
->state
= OHS_ERROR
;
555 /* Attempt to read a line in */
558 * Due to strange memory BIO behavior with BIO_gets we have to check
559 * there's a complete line in there before calling BIO_gets or we'll
560 * just get a partial read.
562 n
= BIO_get_mem_data(rctx
->mem
, &p
);
563 if (n
<= 0 || memchr(p
, '\n', n
) == 0) {
564 if (n
>= rctx
->readbuflen
) {
565 rctx
->state
= OHS_ERROR
;
570 n
= BIO_gets(rctx
->mem
, (char *)rctx
->readbuf
, rctx
->readbuflen
);
573 if (BIO_should_retry(rctx
->mem
))
575 rctx
->state
= OHS_ERROR
;
579 /* Don't allow excessive lines */
580 if (n
== rctx
->readbuflen
) {
581 ERR_raise(ERR_LIB_HTTP
, HTTP_R_RESPONSE_LINE_TOO_LONG
);
582 rctx
->state
= OHS_ERROR
;
587 if (rctx
->state
== OHS_FIRSTLINE
) {
588 switch (parse_http_line1((char *)rctx
->readbuf
, &found_keep_alive
)) {
589 case HTTP_STATUS_CODE_OK
:
590 rctx
->state
= OHS_HEADERS
;
592 case HTTP_STATUS_CODE_MOVED_PERMANENTLY
:
593 case HTTP_STATUS_CODE_FOUND
: /* i.e., moved temporarily */
594 if (!rctx
->method_POST
) { /* method is GET */
595 rctx
->state
= OHS_REDIRECT
;
598 ERR_raise(ERR_LIB_HTTP
, HTTP_R_REDIRECTION_NOT_ENABLED
);
599 /* redirection is not supported/recommended for POST */
602 rctx
->state
= OHS_ERROR
;
606 key
= (char *)rctx
->readbuf
;
607 value
= strchr(key
, ':');
610 while (ossl_isspace(*value
))
612 line_end
= strchr(value
, '\r');
613 if (line_end
== NULL
)
614 line_end
= strchr(value
, '\n');
615 if (line_end
!= NULL
)
618 if (value
!= NULL
&& line_end
!= NULL
) {
619 if (rctx
->state
== OHS_REDIRECT
620 && strcasecmp(key
, "Location") == 0) {
621 rctx
->redirection_url
= value
;
624 if (rctx
->expected_ct
!= NULL
625 && strcasecmp(key
, "Content-Type") == 0) {
626 if (strcasecmp(rctx
->expected_ct
, value
) != 0) {
627 ERR_raise_data(ERR_LIB_HTTP
, HTTP_R_UNEXPECTED_CONTENT_TYPE
,
628 "expected=%s, actual=%s",
629 rctx
->expected_ct
, value
);
632 found_expected_ct
= 1;
635 /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
636 if (strcasecmp(key
, "Connection") == 0) {
637 if (strcasecmp(value
, "keep-alive") == 0)
638 found_keep_alive
= 1;
639 else if (strcasecmp(value
, "close") == 0)
640 found_keep_alive
= 0;
642 if (strcasecmp(key
, "Content-Length") == 0) {
643 resp_len
= strtoul(value
, &line_end
, 10);
644 if (line_end
== value
|| *line_end
!= '\0') {
645 ERR_raise_data(ERR_LIB_HTTP
,
646 HTTP_R_ERROR_PARSING_CONTENT_LENGTH
,
650 if (!check_set_resp_len(rctx
, resp_len
))
655 /* Look for blank line indicating end of headers */
656 for (p
= rctx
->readbuf
; *p
!= '\0'; p
++) {
657 if (*p
!= '\r' && *p
!= '\n')
660 if (*p
!= '\0') /* not end of headers */
663 if (rctx
->expected_ct
!= NULL
&& !found_expected_ct
) {
664 ERR_raise_data(ERR_LIB_HTTP
, HTTP_R_MISSING_CONTENT_TYPE
,
665 "expected=%s", rctx
->expected_ct
);
668 if (rctx
->keep_alive
!= 0 /* do not let server initiate keep_alive */
669 && !found_keep_alive
/* otherwise there is no change */) {
670 if (rctx
->keep_alive
== 2) {
671 rctx
->keep_alive
= 0;
672 ERR_raise(ERR_LIB_HTTP
, HTTP_R_SERVER_CANCELED_CONNECTION
);
675 rctx
->keep_alive
= 0;
678 if (rctx
->state
== OHS_REDIRECT
) {
679 /* http status code indicated redirect but there was no Location */
680 ERR_raise(ERR_LIB_HTTP
, HTTP_R_MISSING_REDIRECT_LOCATION
);
684 if (!rctx
->expect_asn1
) {
685 rctx
->state
= OHS_CONTENT
;
689 rctx
->state
= OHS_ASN1_HEADER
;
692 case OHS_ASN1_HEADER
:
694 * Now reading ASN1 header: can read at least 2 bytes which is enough
695 * for ASN1 SEQUENCE header and either length field or at least the
696 * length of the length field.
698 n
= BIO_get_mem_data(rctx
->mem
, &p
);
702 /* Check it is an ASN1 SEQUENCE */
703 if (*p
++ != (V_ASN1_SEQUENCE
| V_ASN1_CONSTRUCTED
)) {
704 ERR_raise(ERR_LIB_HTTP
, HTTP_R_MISSING_ASN1_ENCODING
);
708 /* Check out length field */
709 if ((*p
& 0x80) != 0) {
711 * If MSB set on initial length octet we can now always read 6
712 * octets: make sure we have them.
717 /* Not NDEF or excessive length */
718 if (n
== 0 || (n
> 4)) {
719 ERR_raise(ERR_LIB_HTTP
, HTTP_R_ERROR_PARSING_ASN1_LENGTH
);
724 for (i
= 0; i
< n
; i
++) {
732 if (!check_set_resp_len(rctx
, resp_len
))
736 rctx
->state
= OHS_CONTENT
;
741 n
= BIO_get_mem_data(rctx
->mem
, NULL
);
742 if (n
< (long)rctx
->resp_len
/* may be 0 if no Content-Length or ASN.1 */)
745 rctx
->state
= OHS_DONE
;
750 int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX
*rctx
,
751 ASN1_VALUE
**pval
, const ASN1_ITEM
*it
)
753 const unsigned char *p
;
757 if ((rv
= OSSL_HTTP_REQ_CTX_nbio(rctx
)) != 1)
759 *pval
= ASN1_item_d2i(NULL
, &p
, BIO_get_mem_data(rctx
->mem
, &p
), it
);
760 return *pval
!= NULL
;
764 #ifndef OPENSSL_NO_SOCK
766 /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
767 static BIO
*HTTP_new_bio(const char *server
/* optionally includes ":port" */,
768 const char *server_port
/* explicit server port */,
770 const char *proxy
/* optionally includes ":port" */,
771 const char *proxy_port
/* explicit proxy port */)
773 const char *host
= server
;
774 const char *port
= server_port
;
777 if (!ossl_assert(server
!= NULL
))
785 if (port
== NULL
&& strchr(host
, ':') == NULL
)
786 port
= use_ssl
? OSSL_HTTPS_PORT
: OSSL_HTTP_PORT
;
788 cbio
= BIO_new_connect(host
/* optionally includes ":port" */);
792 (void)BIO_set_conn_port(cbio
, port
);
797 #endif /* OPENSSL_NO_SOCK */
799 BIO
*OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX
*rctx
)
804 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
809 rv
= OSSL_HTTP_REQ_CTX_nbio(rctx
);
812 /* BIO_should_retry was true */
813 /* will not actually wait if rctx->max_time == 0 */
814 if (BIO_wait(rctx
->rbio
, rctx
->max_time
, 100 /* milliseconds */) <= 0)
819 if (rctx
->redirection_url
== NULL
) { /* an error occurred */
820 if (rctx
->len_to_send
> 0)
821 ERR_raise(ERR_LIB_HTTP
, HTTP_R_ERROR_SENDING
);
823 ERR_raise(ERR_LIB_HTTP
, HTTP_R_ERROR_RECEIVING
);
830 int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX
*rctx
)
832 return rctx
!= NULL
&& rctx
->keep_alive
!= 0;
835 /* High-level HTTP API implementation */
837 /* Initiate an HTTP session using bio, else use given server, proxy, etc. */
838 OSSL_HTTP_REQ_CTX
*OSSL_HTTP_open(const char *server
, const char *port
,
839 const char *proxy
, const char *no_proxy
,
840 int use_ssl
, BIO
*bio
, BIO
*rbio
,
841 OSSL_HTTP_bio_cb_t bio_update_fn
, void *arg
,
842 int buf_size
, unsigned long max_resp_len
,
845 BIO
*cbio
; /* == bio if supplied, used as connection BIO if rbio is NULL */
846 OSSL_HTTP_REQ_CTX
*rctx
= NULL
;
848 if (use_ssl
&& bio_update_fn
== NULL
) {
849 ERR_raise(ERR_LIB_HTTP
, HTTP_R_TLS_NOT_ENABLED
);
852 if (rbio
!= NULL
&& (bio
== NULL
|| bio_update_fn
!= NULL
)) {
853 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_INVALID_ARGUMENT
);
860 #ifndef OPENSSL_NO_SOCK
861 char *proxy_host
= NULL
, *proxy_port
= NULL
;
863 if (server
== NULL
) {
864 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
867 if (port
!= NULL
&& *port
== '\0')
869 if (port
== NULL
&& strchr(server
, ':') == NULL
)
870 port
= use_ssl
? OSSL_HTTPS_PORT
: OSSL_HTTP_PORT
;
871 proxy
= ossl_http_adapt_proxy(proxy
, no_proxy
, server
, use_ssl
);
873 && !OSSL_HTTP_parse_url(proxy
, NULL
/* use_ssl */, NULL
/* user */,
874 &proxy_host
, &proxy_port
, NULL
/* num */,
875 NULL
/* path */, NULL
, NULL
))
877 cbio
= HTTP_new_bio(server
, port
, use_ssl
, proxy_host
, proxy_port
);
878 OPENSSL_free(proxy_host
);
879 OPENSSL_free(proxy_port
);
883 ERR_raise(ERR_LIB_HTTP
, HTTP_R_SOCK_NOT_SUPPORTED
);
888 (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
889 if (rbio
== NULL
&& BIO_do_connect_retry(cbio
, overall_timeout
, -1) <= 0) {
890 if (bio
== NULL
) /* cbio was not provided by caller */
894 /* now overall_timeout is guaranteed to be >= 0 */
896 /* callback can be used to wrap or prepend TLS session */
897 if (bio_update_fn
!= NULL
) {
898 BIO
*orig_bio
= cbio
;
900 cbio
= (*bio_update_fn
)(cbio
, arg
, 1 /* connect */, use_ssl
);
907 rctx
= http_req_ctx_new(bio
== NULL
, cbio
, rbio
!= NULL
? rbio
: cbio
,
908 bio_update_fn
, arg
, use_ssl
, proxy
, server
, port
,
909 buf_size
, max_resp_len
, overall_timeout
);
913 /* remove any spurious error queue entries by ssl_add_cert_chain() */
914 (void)ERR_pop_to_mark();
916 (void)ERR_clear_last_mark();
921 int OSSL_HTTP_set_request(OSSL_HTTP_REQ_CTX
*rctx
, const char *path
,
922 const STACK_OF(CONF_VALUE
) *headers
,
923 const char *content_type
, BIO
*req_mem
,
924 const char *expected_content_type
, int expect_asn1
,
925 int timeout
, int keep_alive
)
930 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
933 use_http_proxy
= rctx
->proxy
!= NULL
&& !rctx
->use_ssl
;
934 if (use_http_proxy
&& (rctx
->server
== NULL
|| rctx
->port
== NULL
)) {
935 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_INVALID_ARGUMENT
);
939 return OSSL_HTTP_REQ_CTX_set_request_line(rctx
, req_mem
!= NULL
,
940 use_http_proxy
? rctx
->server
941 : NULL
, rctx
->port
, path
)
942 && OSSL_HTTP_REQ_CTX_add1_headers(rctx
, headers
, rctx
->server
)
943 && OSSL_HTTP_REQ_CTX_set_expected(rctx
, expected_content_type
,
944 expect_asn1
, timeout
, keep_alive
)
945 && ossl_http_req_ctx_set_content(rctx
, content_type
, req_mem
);
949 * Exchange single HTTP request and response according to rctx.
950 * If rctx->method_POST then use POST, else use GET and ignore content_type.
951 * The redirection_url output (freed by caller) parameter is used only for GET.
953 BIO
*OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX
*rctx
, char **redirection_url
)
958 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
962 if (redirection_url
!= NULL
)
963 *redirection_url
= NULL
; /* do this beforehand to prevent dbl free */
965 resp
= OSSL_HTTP_REQ_CTX_exchange(rctx
);
967 if (rctx
->redirection_url
!= NULL
) {
968 if (redirection_url
== NULL
)
969 ERR_raise(ERR_LIB_HTTP
, HTTP_R_REDIRECTION_NOT_ENABLED
);
971 /* may be NULL if out of memory: */
972 *redirection_url
= OPENSSL_strdup(rctx
->redirection_url
);
975 unsigned long err
= ERR_peek_error();
976 int lib
= ERR_GET_LIB(err
);
977 int reason
= ERR_GET_REASON(err
);
979 if (lib
== ERR_LIB_SSL
|| lib
== ERR_LIB_HTTP
980 || (lib
== ERR_LIB_BIO
&& reason
== BIO_R_CONNECT_TIMEOUT
)
981 || (lib
== ERR_LIB_BIO
&& reason
== BIO_R_CONNECT_ERROR
)
982 #ifndef OPENSSL_NO_CMP
983 || (lib
== ERR_LIB_CMP
984 && reason
== CMP_R_POTENTIALLY_INVALID_CERTIFICATE
)
987 if (rctx
->server
!= NULL
) {
988 BIO_snprintf(buf
, 200, "server=http%s://%s",
989 rctx
->use_ssl
? "s" : "", rctx
->server
);
990 if (rctx
->port
!= NULL
)
991 BIO_snprintf(buf
+ strlen(buf
), 200 - strlen(buf
),
994 ERR_add_error_data(1, buf
);
995 if (rctx
->proxy
!= NULL
)
996 ERR_add_error_data(2, " proxy=", rctx
->proxy
);
998 BIO_snprintf(buf
, 200, " peer has disconnected%s",
999 rctx
->use_ssl
? " violating the protocol" :
1000 ", likely because it requires the use of TLS");
1001 ERR_add_error_data(1, buf
);
1007 if (resp
!= NULL
&& !BIO_up_ref(resp
))
1012 static int redirection_ok(int n_redir
, const char *old_url
, const char *new_url
)
1014 size_t https_len
= strlen(OSSL_HTTPS_NAME
":");
1016 if (n_redir
>= HTTP_VERSION_MAX_REDIRECTIONS
) {
1017 ERR_raise(ERR_LIB_HTTP
, HTTP_R_TOO_MANY_REDIRECTIONS
);
1020 if (*new_url
== '/') /* redirection to same server => same protocol */
1022 if (strncmp(old_url
, OSSL_HTTPS_NAME
":", https_len
) == 0 &&
1023 strncmp(new_url
, OSSL_HTTPS_NAME
":", https_len
) != 0) {
1024 ERR_raise(ERR_LIB_HTTP
, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP
);
1030 /* Get data via HTTP from server at given URL, potentially with redirection */
1031 BIO
*OSSL_HTTP_get(const char *url
, const char *proxy
, const char *no_proxy
,
1032 BIO
*bio
, BIO
*rbio
,
1033 OSSL_HTTP_bio_cb_t bio_update_fn
, void *arg
,
1034 int buf_size
, const STACK_OF(CONF_VALUE
) *headers
,
1035 const char *expected_ct
, int expect_asn1
,
1036 size_t max_resp_len
, int timeout
)
1038 char *current_url
, *redirection_url
= NULL
;
1044 OSSL_HTTP_REQ_CTX
*rctx
;
1048 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
1051 if ((current_url
= OPENSSL_strdup(url
)) == NULL
)
1055 if (!OSSL_HTTP_parse_url(current_url
, &use_ssl
, NULL
/* user */, &host
,
1056 &port
, NULL
/* port_num */, &path
, NULL
, NULL
))
1059 rctx
= OSSL_HTTP_open(host
, port
, proxy
, no_proxy
,
1060 use_ssl
, bio
, rbio
, bio_update_fn
, arg
,
1061 buf_size
, max_resp_len
, timeout
);
1064 if (!OSSL_HTTP_set_request(rctx
, path
, headers
,
1065 NULL
/* content_type */,
1067 expected_ct
, expect_asn1
,
1068 -1 /* use same max time */,
1069 0 /* no keep_alive */))
1070 OSSL_HTTP_REQ_CTX_free(rctx
);
1072 resp
= OSSL_HTTP_exchange(rctx
, &redirection_url
);
1075 if (resp
== NULL
&& redirection_url
!= NULL
) {
1076 if (redirection_ok(++n_redirs
, current_url
, redirection_url
)) {
1077 (void)BIO_reset(bio
);
1078 OPENSSL_free(current_url
);
1079 current_url
= redirection_url
;
1080 if (*redirection_url
== '/') { /* redirection to same server */
1081 path
= OPENSSL_strdup(redirection_url
);
1086 (void)OSSL_HTTP_close(rctx
, 1);
1089 /* if redirection not allowed, ignore it */
1090 OPENSSL_free(redirection_url
);
1094 if (!OSSL_HTTP_close(rctx
, resp
!= NULL
)) {
1100 OPENSSL_free(current_url
);
1104 BIO
*OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX
**prctx
,
1105 const char *server
, const char *port
,
1106 const char *path
, int use_ssl
,
1107 const char *proxy
, const char *no_proxy
,
1108 BIO
*bio
, BIO
*rbio
,
1109 OSSL_HTTP_bio_cb_t bio_update_fn
, void *arg
,
1110 int buf_size
, const STACK_OF(CONF_VALUE
) *headers
,
1111 const char *content_type
, BIO
*req
,
1112 const char *expected_ct
, int expect_asn1
,
1113 unsigned long max_resp_len
, int timeout
, int keep_alive
)
1115 OSSL_HTTP_REQ_CTX
*rctx
= prctx
== NULL
? NULL
: *prctx
;
1119 rctx
= OSSL_HTTP_open(server
, port
, proxy
, no_proxy
,
1120 use_ssl
, bio
, rbio
, bio_update_fn
, arg
,
1121 buf_size
, max_resp_len
, timeout
);
1122 timeout
= -1; /* Already set during opening the connection */
1125 if (OSSL_HTTP_set_request(rctx
, path
, headers
, content_type
, req
,
1126 expected_ct
, expect_asn1
, timeout
, keep_alive
))
1127 resp
= OSSL_HTTP_exchange(rctx
, NULL
);
1128 if (resp
== NULL
|| !OSSL_HTTP_is_alive(rctx
)) {
1129 if (!OSSL_HTTP_close(rctx
, resp
!= NULL
))
1139 int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX
*rctx
, int ok
)
1143 /* callback can be used to clean up TLS session on disconnect */
1144 if (rctx
!= NULL
&& rctx
->upd_fn
!= NULL
)
1145 ret
= (*rctx
->upd_fn
)(rctx
->wbio
, rctx
->upd_arg
, 0, ok
) != NULL
;
1146 OSSL_HTTP_REQ_CTX_free(rctx
);
1150 /* BASE64 encoder used for encoding basic proxy authentication credentials */
1151 static char *base64encode(const void *buf
, size_t len
)
1157 /* Calculate size of encoded data */
1162 out
= OPENSSL_malloc(outl
+ 1);
1166 i
= EVP_EncodeBlock((unsigned char *)out
, buf
, len
);
1167 if (!ossl_assert(0 <= i
&& (size_t)i
<= outl
)) {
1175 * Promote the given connection BIO using the CONNECT method for a TLS proxy.
1176 * This is typically called by an app, so bio_err and prog are used unless NULL
1177 * to print additional diagnostic information in a user-oriented way.
1179 int OSSL_HTTP_proxy_connect(BIO
*bio
, const char *server
, const char *port
,
1180 const char *proxyuser
, const char *proxypass
,
1181 int timeout
, BIO
*bio_err
, const char *prog
)
1184 #define BUF_SIZE (8 * 1024)
1185 char *mbuf
= OPENSSL_malloc(BUF_SIZE
);
1189 BIO
*fbio
= BIO_new(BIO_f_buffer());
1191 time_t max_time
= timeout
> 0 ? time(NULL
) + timeout
: 0;
1193 if (bio
== NULL
|| server
== NULL
1194 || (bio_err
!= NULL
&& prog
== NULL
)) {
1195 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
1198 if (port
== NULL
|| *port
== '\0')
1199 port
= OSSL_HTTPS_PORT
;
1201 if (mbuf
== NULL
|| fbio
== NULL
) {
1202 BIO_printf(bio_err
/* may be NULL */, "%s: out of memory", prog
);
1205 BIO_push(fbio
, bio
);
1207 BIO_printf(fbio
, "CONNECT %s:%s "HTTP_1_0
"\r\n", server
, port
);
1210 * Workaround for broken proxies which would otherwise close
1211 * the connection when entering tunnel mode (e.g., Squid 2.6)
1213 BIO_printf(fbio
, "Proxy-Connection: Keep-Alive\r\n");
1215 /* Support for basic (base64) proxy authentication */
1216 if (proxyuser
!= NULL
) {
1217 size_t len
= strlen(proxyuser
) + 1;
1218 char *proxyauth
, *proxyauthenc
= NULL
;
1220 if (proxypass
!= NULL
)
1221 len
+= strlen(proxypass
);
1222 proxyauth
= OPENSSL_malloc(len
+ 1);
1223 if (proxyauth
== NULL
)
1225 if (BIO_snprintf(proxyauth
, len
+ 1, "%s:%s", proxyuser
,
1226 proxypass
!= NULL
? proxypass
: "") != (int)len
)
1228 proxyauthenc
= base64encode(proxyauth
, len
);
1229 if (proxyauthenc
!= NULL
) {
1230 BIO_printf(fbio
, "Proxy-Authorization: Basic %s\r\n", proxyauthenc
);
1231 OPENSSL_clear_free(proxyauthenc
, strlen(proxyauthenc
));
1234 OPENSSL_clear_free(proxyauth
, len
);
1235 if (proxyauthenc
== NULL
)
1239 /* Terminate the HTTP CONNECT request */
1240 BIO_printf(fbio
, "\r\n");
1243 if (BIO_flush(fbio
) != 0)
1245 /* potentially needs to be retried if BIO is non-blocking */
1246 if (!BIO_should_retry(fbio
))
1251 /* will not actually wait if timeout == 0 */
1252 rv
= BIO_wait(fbio
, max_time
, 100 /* milliseconds */);
1254 BIO_printf(bio_err
, "%s: HTTP CONNECT %s\n", prog
,
1255 rv
== 0 ? "timed out" : "failed waiting for data");
1260 * The first line is the HTTP response.
1261 * According to RFC 7230, it is formatted exactly like this:
1262 * HTTP/d.d ddd Reason text\r\n
1264 read_len
= BIO_gets(fbio
, mbuf
, BUF_SIZE
);
1265 /* the BIO may not block, so we must wait for the 1st line to come in */
1266 if (read_len
< HTTP_LINE1_MINLEN
)
1269 /* Check for HTTP/1.x */
1270 if (strncmp(mbuf
, HTTP_PREFIX
, strlen(HTTP_PREFIX
)) != 0) {
1271 ERR_raise(ERR_LIB_HTTP
, HTTP_R_HEADER_PARSE_ERROR
);
1272 BIO_printf(bio_err
, "%s: HTTP CONNECT failed, non-HTTP response\n",
1274 /* Wrong protocol, not even HTTP, so stop reading headers */
1277 mbufp
= mbuf
+ strlen(HTTP_PREFIX
);
1278 if (strncmp(mbufp
, HTTP_VERSION_PATT
, HTTP_VERSION_PATT_LEN
) != 0) {
1279 ERR_raise(ERR_LIB_HTTP
, HTTP_R_RECEIVED_WRONG_HTTP_VERSION
);
1281 "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
1282 prog
, (int)HTTP_VERSION_STR_LEN
, mbufp
);
1285 mbufp
+= HTTP_VERSION_STR_LEN
;
1287 /* RFC 7231 4.3.6: any 2xx status code is valid */
1288 if (strncmp(mbufp
, " 2", strlen(" 2")) != 0) {
1290 /* chop any trailing whitespace */
1291 while (read_len
> 0 && ossl_isspace(mbuf
[read_len
- 1]))
1293 mbuf
[read_len
] = '\0';
1294 ERR_raise_data(ERR_LIB_HTTP
, HTTP_R_CONNECT_FAILURE
,
1295 "Reason=%s", mbufp
);
1296 BIO_printf(bio_err
, "%s: HTTP CONNECT failed, Reason=%s\n",
1304 /* Read past all following headers */
1307 * TODO: This does not necessarily catch the case when the full
1308 * HTTP response came in in more than a single TCP message.
1310 read_len
= BIO_gets(fbio
, mbuf
, BUF_SIZE
);
1311 } while (read_len
> 2);
1315 (void)BIO_flush(fbio
);