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