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 request or response */
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/response header */
59 BIO
*req
; /* BIO holding the request provided by caller */
60 int method_POST
; /* HTTP method is POST (else GET) */
61 char *expected_ct
; /* Optional expected Content-Type */
62 int expect_asn1
; /* Response must be ASN.1-encoded */
63 unsigned char *pos
; /* Current position sending data */
64 long len_to_send
; /* Number of bytes still to send */
65 unsigned long resp_len
; /* Length of response */
66 size_t max_resp_len
; /* Maximum length of response */
67 int keep_alive
; /* Persistent conn. 0=no, 1=prefer, 2=require */
68 time_t max_time
; /* Maximum end time of current transfer, or 0 */
69 time_t max_total_time
; /* Maximum end time of total transfer, or 0 */
70 char *redirection_url
; /* Location obtained from HTTP status 301/302 */
75 #define OHS_NOREAD 0x1000 /* If set no reading should be performed */
76 #define OHS_ERROR (0 | OHS_NOREAD) /* Error condition */
77 #define OHS_FIRSTLINE 1 /* First line of response being read */
78 #define OHS_HEADERS 2 /* MIME headers of response being read */
79 #define OHS_REDIRECT 3 /* MIME headers being read, expecting Location */
80 #define OHS_ASN1_HEADER 4 /* HTTP initial header (tag+length) being read */
81 #define OHS_CONTENT 5 /* HTTP content octets being read */
82 #define OHS_ADD_HEADERS (1 | OHS_NOREAD) /* Adding header lines to request */
83 #define OHS_WRITE_INIT (2 | OHS_NOREAD) /* 1st call: ready to start send */
84 #define OHS_WRITE_HDR (3 | OHS_NOREAD) /* Request header being sent */
85 #define OHS_WRITE_REQ (4 | OHS_NOREAD) /* Request contents being sent */
86 #define OHS_FLUSH (5 | OHS_NOREAD) /* Request being flushed */
87 #define OHS_DONE (6 | OHS_NOREAD) /* Completed */
89 /* Low-level HTTP API implementation */
91 OSSL_HTTP_REQ_CTX
*OSSL_HTTP_REQ_CTX_new(BIO
*wbio
, BIO
*rbio
, int buf_size
)
93 OSSL_HTTP_REQ_CTX
*rctx
;
95 if (wbio
== NULL
|| rbio
== NULL
) {
96 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
100 if ((rctx
= OPENSSL_zalloc(sizeof(*rctx
))) == NULL
)
102 rctx
->state
= OHS_ERROR
;
103 rctx
->readbuflen
= buf_size
> 0 ? buf_size
: HTTP_DEFAULT_MAX_LINE_LENGTH
;
104 rctx
->readbuf
= OPENSSL_malloc(rctx
->readbuflen
);
107 if (rctx
->readbuf
== NULL
) {
111 rctx
->max_resp_len
= HTTP_DEFAULT_MAX_RESP_LEN
;
112 /* everything else is 0, e.g. rctx->len_to_send, or NULL, e.g. rctx->mem */
116 void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX
*rctx
)
121 * Use BIO_free_all() because bio_update_fn may prepend or append to cbio.
122 * This also frees any (e.g., SSL/TLS) BIOs linked with bio and,
123 * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer.
126 BIO_free_all(rctx
->wbio
);
127 /* do not free rctx->rbio */
128 BIO_free(rctx
->mem
); /* this may indirectly call ERR_clear_error() */
129 OPENSSL_free(rctx
->readbuf
);
130 OPENSSL_free(rctx
->proxy
);
131 OPENSSL_free(rctx
->server
);
132 OPENSSL_free(rctx
->port
);
133 OPENSSL_free(rctx
->expected_ct
);
137 BIO
*OSSL_HTTP_REQ_CTX_get0_mem_bio(const OSSL_HTTP_REQ_CTX
*rctx
)
140 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
146 size_t OSSL_HTTP_REQ_CTX_get_resp_len(const OSSL_HTTP_REQ_CTX
*rctx
)
149 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
152 return rctx
->resp_len
;
155 void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX
*rctx
,
159 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
162 rctx
->max_resp_len
= len
!= 0 ? (size_t)len
: HTTP_DEFAULT_MAX_RESP_LEN
;
166 * Create request line using |rctx| and |path| (or "/" in case |path| is NULL).
167 * Server name (and port) must be given if and only if plain HTTP proxy is used.
169 int OSSL_HTTP_REQ_CTX_set_request_line(OSSL_HTTP_REQ_CTX
*rctx
, int method_POST
,
170 const char *server
, const char *port
,
174 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
178 if ((rctx
->mem
= BIO_new(BIO_s_mem())) == NULL
)
181 rctx
->method_POST
= method_POST
!= 0;
182 if (BIO_printf(rctx
->mem
, "%s ", rctx
->method_POST
? "POST" : "GET") <= 0)
185 if (server
!= NULL
) { /* HTTP (but not HTTPS) proxy is used */
187 * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only
188 * allowed when using a proxy
190 if (BIO_printf(rctx
->mem
, OSSL_HTTP_PREFIX
"%s", server
) <= 0)
192 if (port
!= NULL
&& BIO_printf(rctx
->mem
, ":%s", port
) <= 0)
196 /* Make sure path includes a forward slash */
199 if (path
[0] != '/' && BIO_printf(rctx
->mem
, "/") <= 0)
202 if (BIO_printf(rctx
->mem
, "%s "HTTP_1_0
"\r\n", path
) <= 0)
205 rctx
->state
= OHS_ADD_HEADERS
;
209 int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX
*rctx
,
210 const char *name
, const char *value
)
212 if (rctx
== NULL
|| name
== NULL
) {
213 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
216 if (rctx
->mem
== NULL
) {
217 ERR_raise(ERR_LIB_HTTP
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
221 if (BIO_puts(rctx
->mem
, name
) <= 0)
224 if (BIO_write(rctx
->mem
, ": ", 2) != 2)
226 if (BIO_puts(rctx
->mem
, value
) <= 0)
229 return BIO_write(rctx
->mem
, "\r\n", 2) == 2;
232 int OSSL_HTTP_REQ_CTX_set_expected(OSSL_HTTP_REQ_CTX
*rctx
,
233 const char *content_type
, int asn1
,
234 int timeout
, int keep_alive
)
237 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
241 && rctx
->state
!= OHS_ERROR
&& rctx
->state
!= OHS_ADD_HEADERS
) {
242 /* Cannot anymore set keep-alive in request header */
243 ERR_raise(ERR_LIB_HTTP
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
247 OPENSSL_free(rctx
->expected_ct
);
248 rctx
->expected_ct
= NULL
;
249 if (content_type
!= NULL
250 && (rctx
->expected_ct
= OPENSSL_strdup(content_type
)) == NULL
)
253 rctx
->expect_asn1
= asn1
;
255 rctx
->max_time
= timeout
> 0 ? time(NULL
) + timeout
: 0;
257 rctx
->max_time
= rctx
->max_total_time
;
258 rctx
->keep_alive
= keep_alive
;
262 static int ossl_http_req_ctx_set_content(OSSL_HTTP_REQ_CTX
*rctx
,
263 const char *content_type
, BIO
*req
)
267 if (rctx
== NULL
|| (req
== NULL
&& content_type
!= NULL
)) {
268 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
272 if (rctx
->keep_alive
!= 0
273 && !OSSL_HTTP_REQ_CTX_add1_header(rctx
, "Connection", "keep-alive"))
278 if (!rctx
->method_POST
) {
279 ERR_raise(ERR_LIB_HTTP
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
283 if (content_type
!= NULL
284 && BIO_printf(rctx
->mem
, "Content-Type: %s\r\n", content_type
) <= 0)
288 if ((req_len
= BIO_ctrl(req
, BIO_CTRL_INFO
, 0, NULL
)) <= 0)
289 return 1; /* streaming BIO may not support querying size */
290 return BIO_printf(rctx
->mem
, "Content-Length: %ld\r\n", req_len
) > 0;
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_ADD_HEADERS
:
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
, &rctx
->pos
);
509 rctx
->state
= OHS_WRITE_HDR
;
513 /* Copy some chunk of data from rctx->mem to rctx->wbio */
515 /* Copy some chunk of data from rctx->req to rctx->wbio */
517 if (rctx
->len_to_send
> 0) {
518 i
= BIO_write(rctx
->wbio
, rctx
->pos
, rctx
->len_to_send
);
520 if (BIO_should_retry(rctx
->wbio
))
522 rctx
->state
= OHS_ERROR
;
526 rctx
->len_to_send
-= i
;
529 if (rctx
->state
== OHS_WRITE_HDR
) {
530 (void)BIO_reset(rctx
->mem
);
531 rctx
->state
= OHS_WRITE_REQ
;
533 if (rctx
->req
!= NULL
&& !BIO_eof(rctx
->req
)) {
534 n
= BIO_read(rctx
->req
, rctx
->readbuf
, rctx
->readbuflen
);
536 if (BIO_should_retry(rctx
->rbio
))
538 ERR_raise(ERR_LIB_HTTP
, HTTP_R_FAILED_READING_DATA
);
541 rctx
->pos
= rctx
->readbuf
;
542 rctx
->len_to_send
= n
;
545 rctx
->state
= OHS_FLUSH
;
550 i
= BIO_flush(rctx
->wbio
);
553 rctx
->state
= OHS_FIRSTLINE
;
557 if (BIO_should_retry(rctx
->wbio
))
560 rctx
->state
= OHS_ERROR
;
570 /* Attempt to read a line in */
573 * Due to strange memory BIO behavior with BIO_gets we have to check
574 * there's a complete line in there before calling BIO_gets or we'll
575 * just get a partial read.
577 n
= BIO_get_mem_data(rctx
->mem
, &p
);
578 if (n
<= 0 || memchr(p
, '\n', n
) == 0) {
579 if (n
>= rctx
->readbuflen
) {
580 rctx
->state
= OHS_ERROR
;
585 n
= BIO_gets(rctx
->mem
, (char *)rctx
->readbuf
, rctx
->readbuflen
);
588 if (BIO_should_retry(rctx
->mem
))
590 rctx
->state
= OHS_ERROR
;
594 /* Don't allow excessive lines */
595 if (n
== rctx
->readbuflen
) {
596 ERR_raise(ERR_LIB_HTTP
, HTTP_R_RESPONSE_LINE_TOO_LONG
);
597 rctx
->state
= OHS_ERROR
;
602 if (rctx
->state
== OHS_FIRSTLINE
) {
603 switch (parse_http_line1((char *)rctx
->readbuf
, &found_keep_alive
)) {
604 case HTTP_STATUS_CODE_OK
:
605 rctx
->state
= OHS_HEADERS
;
607 case HTTP_STATUS_CODE_MOVED_PERMANENTLY
:
608 case HTTP_STATUS_CODE_FOUND
: /* i.e., moved temporarily */
609 if (!rctx
->method_POST
) { /* method is GET */
610 rctx
->state
= OHS_REDIRECT
;
613 ERR_raise(ERR_LIB_HTTP
, HTTP_R_REDIRECTION_NOT_ENABLED
);
614 /* redirection is not supported/recommended for POST */
617 rctx
->state
= OHS_ERROR
;
621 key
= (char *)rctx
->readbuf
;
622 value
= strchr(key
, ':');
625 while (ossl_isspace(*value
))
627 line_end
= strchr(value
, '\r');
628 if (line_end
== NULL
)
629 line_end
= strchr(value
, '\n');
630 if (line_end
!= NULL
)
633 if (value
!= NULL
&& line_end
!= NULL
) {
634 if (rctx
->state
== OHS_REDIRECT
635 && strcasecmp(key
, "Location") == 0) {
636 rctx
->redirection_url
= value
;
639 if (rctx
->expected_ct
!= NULL
640 && strcasecmp(key
, "Content-Type") == 0) {
641 if (strcasecmp(rctx
->expected_ct
, value
) != 0) {
642 ERR_raise_data(ERR_LIB_HTTP
, HTTP_R_UNEXPECTED_CONTENT_TYPE
,
643 "expected=%s, actual=%s",
644 rctx
->expected_ct
, value
);
647 found_expected_ct
= 1;
650 /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
651 if (strcasecmp(key
, "Connection") == 0) {
652 if (strcasecmp(value
, "keep-alive") == 0)
653 found_keep_alive
= 1;
654 else if (strcasecmp(value
, "close") == 0)
655 found_keep_alive
= 0;
657 if (strcasecmp(key
, "Content-Length") == 0) {
658 resp_len
= strtoul(value
, &line_end
, 10);
659 if (line_end
== value
|| *line_end
!= '\0') {
660 ERR_raise_data(ERR_LIB_HTTP
,
661 HTTP_R_ERROR_PARSING_CONTENT_LENGTH
,
665 if (!check_set_resp_len(rctx
, resp_len
))
670 /* Look for blank line indicating end of headers */
671 for (p
= rctx
->readbuf
; *p
!= '\0'; p
++) {
672 if (*p
!= '\r' && *p
!= '\n')
675 if (*p
!= '\0') /* not end of headers */
678 if (rctx
->expected_ct
!= NULL
&& !found_expected_ct
) {
679 ERR_raise_data(ERR_LIB_HTTP
, HTTP_R_MISSING_CONTENT_TYPE
,
680 "expected=%s", rctx
->expected_ct
);
683 if (rctx
->keep_alive
!= 0 /* do not let server initiate keep_alive */
684 && !found_keep_alive
/* otherwise there is no change */) {
685 if (rctx
->keep_alive
== 2) {
686 rctx
->keep_alive
= 0;
687 ERR_raise(ERR_LIB_HTTP
, HTTP_R_SERVER_CANCELED_CONNECTION
);
690 rctx
->keep_alive
= 0;
693 if (rctx
->state
== OHS_REDIRECT
) {
694 /* http status code indicated redirect but there was no Location */
695 ERR_raise(ERR_LIB_HTTP
, HTTP_R_MISSING_REDIRECT_LOCATION
);
699 if (!rctx
->expect_asn1
) {
700 rctx
->state
= OHS_CONTENT
;
704 rctx
->state
= OHS_ASN1_HEADER
;
707 case OHS_ASN1_HEADER
:
709 * Now reading ASN1 header: can read at least 2 bytes which is enough
710 * for ASN1 SEQUENCE header and either length field or at least the
711 * length of the length field.
713 n
= BIO_get_mem_data(rctx
->mem
, &p
);
717 /* Check it is an ASN1 SEQUENCE */
718 if (*p
++ != (V_ASN1_SEQUENCE
| V_ASN1_CONSTRUCTED
)) {
719 ERR_raise(ERR_LIB_HTTP
, HTTP_R_MISSING_ASN1_ENCODING
);
723 /* Check out length field */
724 if ((*p
& 0x80) != 0) {
726 * If MSB set on initial length octet we can now always read 6
727 * octets: make sure we have them.
732 /* Not NDEF or excessive length */
733 if (n
== 0 || (n
> 4)) {
734 ERR_raise(ERR_LIB_HTTP
, HTTP_R_ERROR_PARSING_ASN1_LENGTH
);
739 for (i
= 0; i
< n
; i
++) {
747 if (!check_set_resp_len(rctx
, resp_len
))
751 rctx
->state
= OHS_CONTENT
;
756 n
= BIO_get_mem_data(rctx
->mem
, NULL
);
757 if (n
< (long)rctx
->resp_len
/* may be 0 if no Content-Length or ASN.1 */)
760 rctx
->state
= OHS_DONE
;
765 int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX
*rctx
,
766 ASN1_VALUE
**pval
, const ASN1_ITEM
*it
)
768 const unsigned char *p
;
772 if ((rv
= OSSL_HTTP_REQ_CTX_nbio(rctx
)) != 1)
774 *pval
= ASN1_item_d2i(NULL
, &p
, BIO_get_mem_data(rctx
->mem
, &p
), it
);
775 return *pval
!= NULL
;
779 #ifndef OPENSSL_NO_SOCK
781 /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
782 static BIO
*HTTP_new_bio(const char *server
/* optionally includes ":port" */,
783 const char *server_port
/* explicit server port */,
785 const char *proxy
/* optionally includes ":port" */,
786 const char *proxy_port
/* explicit proxy port */)
788 const char *host
= server
;
789 const char *port
= server_port
;
792 if (!ossl_assert(server
!= NULL
))
800 if (port
== NULL
&& strchr(host
, ':') == NULL
)
801 port
= use_ssl
? OSSL_HTTPS_PORT
: OSSL_HTTP_PORT
;
803 cbio
= BIO_new_connect(host
/* optionally includes ":port" */);
807 (void)BIO_set_conn_port(cbio
, port
);
812 #endif /* OPENSSL_NO_SOCK */
814 /* Exchange request and response via HTTP on (non-)blocking BIO */
815 BIO
*OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX
*rctx
)
820 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
825 rv
= OSSL_HTTP_REQ_CTX_nbio(rctx
);
828 /* BIO_should_retry was true */
829 /* will not actually wait if rctx->max_time == 0 */
830 if (BIO_wait(rctx
->rbio
, rctx
->max_time
, 100 /* milliseconds */) <= 0)
835 if (rctx
->redirection_url
== NULL
) { /* an error occurred */
836 if (rctx
->len_to_send
> 0)
837 ERR_raise(ERR_LIB_HTTP
, HTTP_R_ERROR_SENDING
);
839 ERR_raise(ERR_LIB_HTTP
, HTTP_R_ERROR_RECEIVING
);
846 int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX
*rctx
)
848 return rctx
!= NULL
&& rctx
->keep_alive
!= 0;
851 /* High-level HTTP API implementation */
853 /* Initiate an HTTP session using bio, else use given server, proxy, etc. */
854 OSSL_HTTP_REQ_CTX
*OSSL_HTTP_open(const char *server
, const char *port
,
855 const char *proxy
, const char *no_proxy
,
856 int use_ssl
, BIO
*bio
, BIO
*rbio
,
857 OSSL_HTTP_bio_cb_t bio_update_fn
, void *arg
,
858 int buf_size
, unsigned long max_resp_len
,
861 BIO
*cbio
; /* == bio if supplied, used as connection BIO if rbio is NULL */
862 OSSL_HTTP_REQ_CTX
*rctx
= NULL
;
864 if (use_ssl
&& bio_update_fn
== NULL
) {
865 ERR_raise(ERR_LIB_HTTP
, HTTP_R_TLS_NOT_ENABLED
);
868 if (rbio
!= NULL
&& (bio
== NULL
|| bio_update_fn
!= NULL
)) {
869 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_INVALID_ARGUMENT
);
875 if (proxy
!= NULL
|| no_proxy
!= NULL
) {
876 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_INVALID_ARGUMENT
);
880 #ifndef OPENSSL_NO_SOCK
881 char *proxy_host
= NULL
, *proxy_port
= NULL
;
883 if (server
== NULL
) {
884 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
887 if (port
!= NULL
&& *port
== '\0')
889 if (port
== NULL
&& strchr(server
, ':') == NULL
)
890 port
= use_ssl
? OSSL_HTTPS_PORT
: OSSL_HTTP_PORT
;
891 proxy
= ossl_http_adapt_proxy(proxy
, no_proxy
, server
, use_ssl
);
893 && !OSSL_HTTP_parse_url(proxy
, NULL
/* use_ssl */, NULL
/* user */,
894 &proxy_host
, &proxy_port
, NULL
/* num */,
895 NULL
/* path */, NULL
, NULL
))
897 cbio
= HTTP_new_bio(server
, port
, use_ssl
, proxy_host
, proxy_port
);
898 OPENSSL_free(proxy_host
);
899 OPENSSL_free(proxy_port
);
903 ERR_raise(ERR_LIB_HTTP
, HTTP_R_SOCK_NOT_SUPPORTED
);
908 (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
909 if (rbio
== NULL
&& BIO_do_connect_retry(cbio
, overall_timeout
, -1) <= 0) {
910 if (bio
== NULL
) /* cbio was not provided by caller */
914 /* now overall_timeout is guaranteed to be >= 0 */
916 /* callback can be used to wrap or prepend TLS session */
917 if (bio_update_fn
!= NULL
) {
918 BIO
*orig_bio
= cbio
;
920 cbio
= (*bio_update_fn
)(cbio
, arg
, 1 /* connect */, use_ssl
);
927 rctx
= http_req_ctx_new(bio
== NULL
, cbio
, rbio
!= NULL
? rbio
: cbio
,
928 bio_update_fn
, arg
, use_ssl
, proxy
, server
, port
,
929 buf_size
, max_resp_len
, overall_timeout
);
933 /* remove any spurious error queue entries by ssl_add_cert_chain() */
934 (void)ERR_pop_to_mark();
936 (void)ERR_clear_last_mark();
941 int OSSL_HTTP_set_request(OSSL_HTTP_REQ_CTX
*rctx
, const char *path
,
942 const STACK_OF(CONF_VALUE
) *headers
,
943 const char *content_type
, BIO
*req
,
944 const char *expected_content_type
, int expect_asn1
,
945 int timeout
, int keep_alive
)
950 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
953 use_http_proxy
= rctx
->proxy
!= NULL
&& !rctx
->use_ssl
;
954 if (use_http_proxy
&& (rctx
->server
== NULL
|| rctx
->port
== NULL
)) {
955 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_INVALID_ARGUMENT
);
959 return OSSL_HTTP_REQ_CTX_set_request_line(rctx
, req
!= NULL
,
960 use_http_proxy
? rctx
->server
961 : NULL
, rctx
->port
, path
)
962 && OSSL_HTTP_REQ_CTX_add1_headers(rctx
, headers
, rctx
->server
)
963 && OSSL_HTTP_REQ_CTX_set_expected(rctx
, expected_content_type
,
964 expect_asn1
, timeout
, keep_alive
)
965 && ossl_http_req_ctx_set_content(rctx
, content_type
, req
);
969 * Exchange single HTTP request and response according to rctx.
970 * If rctx->method_POST then use POST, else use GET and ignore content_type.
971 * The redirection_url output (freed by caller) parameter is used only for GET.
973 BIO
*OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX
*rctx
, char **redirection_url
)
978 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
982 if (redirection_url
!= NULL
)
983 *redirection_url
= NULL
; /* do this beforehand to prevent dbl free */
985 resp
= OSSL_HTTP_REQ_CTX_exchange(rctx
);
987 if (rctx
->redirection_url
!= NULL
) {
988 if (redirection_url
== NULL
)
989 ERR_raise(ERR_LIB_HTTP
, HTTP_R_REDIRECTION_NOT_ENABLED
);
991 /* may be NULL if out of memory: */
992 *redirection_url
= OPENSSL_strdup(rctx
->redirection_url
);
995 unsigned long err
= ERR_peek_error();
996 int lib
= ERR_GET_LIB(err
);
997 int reason
= ERR_GET_REASON(err
);
999 if (lib
== ERR_LIB_SSL
|| lib
== ERR_LIB_HTTP
1000 || (lib
== ERR_LIB_BIO
&& reason
== BIO_R_CONNECT_TIMEOUT
)
1001 || (lib
== ERR_LIB_BIO
&& reason
== BIO_R_CONNECT_ERROR
)
1002 #ifndef OPENSSL_NO_CMP
1003 || (lib
== ERR_LIB_CMP
1004 && reason
== CMP_R_POTENTIALLY_INVALID_CERTIFICATE
)
1007 if (rctx
->server
!= NULL
) {
1008 BIO_snprintf(buf
, sizeof(buf
), "server=http%s://%s%s%s",
1009 rctx
->use_ssl
? "s" : "", rctx
->server
,
1010 rctx
->port
!= NULL
? ":" : "",
1011 rctx
->port
!= NULL
? rctx
->port
: "");
1012 ERR_add_error_data(1, buf
);
1014 if (rctx
->proxy
!= NULL
)
1015 ERR_add_error_data(2, " proxy=", rctx
->proxy
);
1017 BIO_snprintf(buf
, sizeof(buf
), " peer has disconnected%s",
1018 rctx
->use_ssl
? " violating the protocol" :
1019 ", likely because it requires the use of TLS");
1020 ERR_add_error_data(1, buf
);
1026 if (resp
!= NULL
&& !BIO_up_ref(resp
))
1031 static int redirection_ok(int n_redir
, const char *old_url
, const char *new_url
)
1033 size_t https_len
= strlen(OSSL_HTTPS_NAME
":");
1035 if (n_redir
>= HTTP_VERSION_MAX_REDIRECTIONS
) {
1036 ERR_raise(ERR_LIB_HTTP
, HTTP_R_TOO_MANY_REDIRECTIONS
);
1039 if (*new_url
== '/') /* redirection to same server => same protocol */
1041 if (strncmp(old_url
, OSSL_HTTPS_NAME
":", https_len
) == 0 &&
1042 strncmp(new_url
, OSSL_HTTPS_NAME
":", https_len
) != 0) {
1043 ERR_raise(ERR_LIB_HTTP
, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP
);
1049 /* Get data via HTTP from server at given URL, potentially with redirection */
1050 BIO
*OSSL_HTTP_get(const char *url
, const char *proxy
, const char *no_proxy
,
1051 BIO
*bio
, BIO
*rbio
,
1052 OSSL_HTTP_bio_cb_t bio_update_fn
, void *arg
,
1053 int buf_size
, const STACK_OF(CONF_VALUE
) *headers
,
1054 const char *expected_ct
, int expect_asn1
,
1055 size_t max_resp_len
, int timeout
)
1057 char *current_url
, *redirection_url
= NULL
;
1063 OSSL_HTTP_REQ_CTX
*rctx
;
1067 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
1070 if ((current_url
= OPENSSL_strdup(url
)) == NULL
)
1074 if (!OSSL_HTTP_parse_url(current_url
, &use_ssl
, NULL
/* user */, &host
,
1075 &port
, NULL
/* port_num */, &path
, NULL
, NULL
))
1078 rctx
= OSSL_HTTP_open(host
, port
, proxy
, no_proxy
,
1079 use_ssl
, bio
, rbio
, bio_update_fn
, arg
,
1080 buf_size
, max_resp_len
, timeout
);
1083 if (!OSSL_HTTP_set_request(rctx
, path
, headers
,
1084 NULL
/* content_type */,
1086 expected_ct
, expect_asn1
,
1087 -1 /* use same max time (timeout) */,
1088 0 /* no keep_alive */))
1089 OSSL_HTTP_REQ_CTX_free(rctx
);
1091 resp
= OSSL_HTTP_exchange(rctx
, &redirection_url
);
1094 if (resp
== NULL
&& redirection_url
!= NULL
) {
1095 if (redirection_ok(++n_redirs
, current_url
, redirection_url
)) {
1096 (void)BIO_reset(bio
);
1097 OPENSSL_free(current_url
);
1098 current_url
= redirection_url
;
1099 if (*redirection_url
== '/') { /* redirection to same server */
1100 path
= OPENSSL_strdup(redirection_url
);
1105 (void)OSSL_HTTP_close(rctx
, 1);
1108 /* if redirection not allowed, ignore it */
1109 OPENSSL_free(redirection_url
);
1113 if (!OSSL_HTTP_close(rctx
, resp
!= NULL
)) {
1119 OPENSSL_free(current_url
);
1123 /* Exchange request and response over a connection managed via |prctx| */
1124 BIO
*OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX
**prctx
,
1125 const char *server
, const char *port
,
1126 const char *path
, int use_ssl
,
1127 const char *proxy
, const char *no_proxy
,
1128 BIO
*bio
, BIO
*rbio
,
1129 OSSL_HTTP_bio_cb_t bio_update_fn
, void *arg
,
1130 int buf_size
, const STACK_OF(CONF_VALUE
) *headers
,
1131 const char *content_type
, BIO
*req
,
1132 const char *expected_ct
, int expect_asn1
,
1133 unsigned long max_resp_len
, int timeout
, int keep_alive
)
1135 OSSL_HTTP_REQ_CTX
*rctx
= prctx
== NULL
? NULL
: *prctx
;
1139 rctx
= OSSL_HTTP_open(server
, port
, proxy
, no_proxy
,
1140 use_ssl
, bio
, rbio
, bio_update_fn
, arg
,
1141 buf_size
, max_resp_len
, timeout
);
1142 timeout
= -1; /* Already set during opening the connection */
1145 if (OSSL_HTTP_set_request(rctx
, path
, headers
, content_type
, req
,
1146 expected_ct
, expect_asn1
,
1147 timeout
, keep_alive
))
1148 resp
= OSSL_HTTP_exchange(rctx
, NULL
);
1149 if (resp
== NULL
|| !OSSL_HTTP_is_alive(rctx
)) {
1150 if (!OSSL_HTTP_close(rctx
, resp
!= NULL
)) {
1162 int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX
*rctx
, int ok
)
1166 /* callback can be used to clean up TLS session on disconnect */
1167 if (rctx
!= NULL
&& rctx
->upd_fn
!= NULL
)
1168 ret
= (*rctx
->upd_fn
)(rctx
->wbio
, rctx
->upd_arg
, 0, ok
) != NULL
;
1169 OSSL_HTTP_REQ_CTX_free(rctx
);
1173 /* BASE64 encoder used for encoding basic proxy authentication credentials */
1174 static char *base64encode(const void *buf
, size_t len
)
1180 /* Calculate size of encoded data */
1185 out
= OPENSSL_malloc(outl
+ 1);
1189 i
= EVP_EncodeBlock((unsigned char *)out
, buf
, len
);
1190 if (!ossl_assert(0 <= i
&& (size_t)i
<= outl
)) {
1198 * Promote the given connection BIO using the CONNECT method for a TLS proxy.
1199 * This is typically called by an app, so bio_err and prog are used unless NULL
1200 * to print additional diagnostic information in a user-oriented way.
1202 int OSSL_HTTP_proxy_connect(BIO
*bio
, const char *server
, const char *port
,
1203 const char *proxyuser
, const char *proxypass
,
1204 int timeout
, BIO
*bio_err
, const char *prog
)
1207 #define BUF_SIZE (8 * 1024)
1208 char *mbuf
= OPENSSL_malloc(BUF_SIZE
);
1212 BIO
*fbio
= BIO_new(BIO_f_buffer());
1214 time_t max_time
= timeout
> 0 ? time(NULL
) + timeout
: 0;
1216 if (bio
== NULL
|| server
== NULL
1217 || (bio_err
!= NULL
&& prog
== NULL
)) {
1218 ERR_raise(ERR_LIB_HTTP
, ERR_R_PASSED_NULL_PARAMETER
);
1221 if (port
== NULL
|| *port
== '\0')
1222 port
= OSSL_HTTPS_PORT
;
1224 if (mbuf
== NULL
|| fbio
== NULL
) {
1225 BIO_printf(bio_err
/* may be NULL */, "%s: out of memory", prog
);
1228 BIO_push(fbio
, bio
);
1230 BIO_printf(fbio
, "CONNECT %s:%s "HTTP_1_0
"\r\n", server
, port
);
1233 * Workaround for broken proxies which would otherwise close
1234 * the connection when entering tunnel mode (e.g., Squid 2.6)
1236 BIO_printf(fbio
, "Proxy-Connection: Keep-Alive\r\n");
1238 /* Support for basic (base64) proxy authentication */
1239 if (proxyuser
!= NULL
) {
1240 size_t len
= strlen(proxyuser
) + 1;
1241 char *proxyauth
, *proxyauthenc
= NULL
;
1243 if (proxypass
!= NULL
)
1244 len
+= strlen(proxypass
);
1245 proxyauth
= OPENSSL_malloc(len
+ 1);
1246 if (proxyauth
== NULL
)
1248 if (BIO_snprintf(proxyauth
, len
+ 1, "%s:%s", proxyuser
,
1249 proxypass
!= NULL
? proxypass
: "") != (int)len
)
1251 proxyauthenc
= base64encode(proxyauth
, len
);
1252 if (proxyauthenc
!= NULL
) {
1253 BIO_printf(fbio
, "Proxy-Authorization: Basic %s\r\n", proxyauthenc
);
1254 OPENSSL_clear_free(proxyauthenc
, strlen(proxyauthenc
));
1257 OPENSSL_clear_free(proxyauth
, len
);
1258 if (proxyauthenc
== NULL
)
1262 /* Terminate the HTTP CONNECT request */
1263 BIO_printf(fbio
, "\r\n");
1266 if (BIO_flush(fbio
) != 0)
1268 /* potentially needs to be retried if BIO is non-blocking */
1269 if (!BIO_should_retry(fbio
))
1274 /* will not actually wait if timeout == 0 */
1275 rv
= BIO_wait(fbio
, max_time
, 100 /* milliseconds */);
1277 BIO_printf(bio_err
, "%s: HTTP CONNECT %s\n", prog
,
1278 rv
== 0 ? "timed out" : "failed waiting for data");
1283 * The first line is the HTTP response.
1284 * According to RFC 7230, it is formatted exactly like this:
1285 * HTTP/d.d ddd Reason text\r\n
1287 read_len
= BIO_gets(fbio
, mbuf
, BUF_SIZE
);
1288 /* the BIO may not block, so we must wait for the 1st line to come in */
1289 if (read_len
< HTTP_LINE1_MINLEN
)
1292 /* Check for HTTP/1.x */
1293 if (strncmp(mbuf
, HTTP_PREFIX
, strlen(HTTP_PREFIX
)) != 0) {
1294 ERR_raise(ERR_LIB_HTTP
, HTTP_R_HEADER_PARSE_ERROR
);
1295 BIO_printf(bio_err
, "%s: HTTP CONNECT failed, non-HTTP response\n",
1297 /* Wrong protocol, not even HTTP, so stop reading headers */
1300 mbufp
= mbuf
+ strlen(HTTP_PREFIX
);
1301 if (strncmp(mbufp
, HTTP_VERSION_PATT
, HTTP_VERSION_PATT_LEN
) != 0) {
1302 ERR_raise(ERR_LIB_HTTP
, HTTP_R_RECEIVED_WRONG_HTTP_VERSION
);
1304 "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
1305 prog
, (int)HTTP_VERSION_STR_LEN
, mbufp
);
1308 mbufp
+= HTTP_VERSION_STR_LEN
;
1310 /* RFC 7231 4.3.6: any 2xx status code is valid */
1311 if (strncmp(mbufp
, " 2", strlen(" 2")) != 0) {
1313 /* chop any trailing whitespace */
1314 while (read_len
> 0 && ossl_isspace(mbuf
[read_len
- 1]))
1316 mbuf
[read_len
] = '\0';
1317 ERR_raise_data(ERR_LIB_HTTP
, HTTP_R_CONNECT_FAILURE
,
1318 "Reason=%s", mbufp
);
1319 BIO_printf(bio_err
, "%s: HTTP CONNECT failed, Reason=%s\n",
1327 /* Read past all following headers */
1330 * TODO: This does not necessarily catch the case when the full
1331 * HTTP response came in in more than a single TCP message.
1333 read_len
= BIO_gets(fbio
, mbuf
, BUF_SIZE
);
1334 } while (read_len
> 2);
1338 (void)BIO_flush(fbio
);