]> git.ipfire.org Git - thirdparty/openssl.git/blame - crypto/http/http_client.c
ci: omit tests that consume too much memory
[thirdparty/openssl.git] / crypto / http / http_client.c
CommitLineData
29f178bd 1/*
4333b89f 2 * Copyright 2001-2021 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
11#include "e_os.h"
12#include <stdio.h>
13#include <stdlib.h>
14#include "crypto/ctype.h"
15#include <string.h>
16#include <openssl/asn1.h>
17#include <openssl/evp.h>
18#include <openssl/err.h>
19#include <openssl/httperr.h>
20#include <openssl/cmperr.h>
21#include <openssl/buffer.h>
22#include <openssl/http.h>
23#include "internal/sockets.h"
4b1fe471 24#include "internal/cryptlib.h" /* for ossl_assert() */
29f178bd 25
b6fec965 26#define HAS_PREFIX(str, prefix) (strncmp(str, prefix, sizeof(prefix) - 1) == 0)
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);
325 if (add_host && strcasecmp("host", hdr->name) == 0)
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".
372 * We need to obtain the numeric code and (optional) informational message.
373 */
374
19f97fe6 375static int parse_http_line1(char *line, int *found_keep_alive)
29f178bd 376{
be799eb7 377 int i, retcode;
29f178bd
DDO
378 char *code, *reason, *end;
379
b6fec965 380 if (!HAS_PREFIX(line, HTTP_PREFIX_VERSION))
19f97fe6
DDO
381 goto err;
382 /* above HTTP 1.0, connection persistence is the default */
8df299d6 383 *found_keep_alive = line[strlen(HTTP_PREFIX_VERSION)] > '0';
19f97fe6 384
29f178bd
DDO
385 /* Skip to first whitespace (past protocol info) */
386 for (code = line; *code != '\0' && !ossl_isspace(*code); code++)
387 continue;
19f97fe6
DDO
388 if (*code == '\0')
389 goto err;
29f178bd
DDO
390
391 /* Skip past whitespace to start of response code */
392 while (*code != '\0' && ossl_isspace(*code))
393 code++;
19f97fe6
DDO
394 if (*code == '\0')
395 goto err;
29f178bd
DDO
396
397 /* Find end of response code: first whitespace after start of code */
398 for (reason = code; *reason != '\0' && !ossl_isspace(*reason); reason++)
399 continue;
400
19f97fe6
DDO
401 if (*reason == '\0')
402 goto err;
29f178bd
DDO
403
404 /* Set end of response code and start of message */
405 *reason++ = '\0';
406
407 /* Attempt to parse numeric code */
408 retcode = strtoul(code, &end, 10);
29f178bd 409 if (*end != '\0')
19f97fe6 410 goto err;
29f178bd
DDO
411
412 /* Skip over any leading whitespace in message */
413 while (*reason != '\0' && ossl_isspace(*reason))
414 reason++;
415
416 if (*reason != '\0') {
417 /*
418 * Finally zap any trailing whitespace in message (include CRLF)
419 */
420
421 /* chop any trailing whitespace from reason */
422 /* We know reason has a non-whitespace character so this is OK */
423 for (end = reason + strlen(reason) - 1; ossl_isspace(*end); end--)
424 *end = '\0';
425 }
426
427 switch (retcode) {
428 case HTTP_STATUS_CODE_OK:
429 case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
430 case HTTP_STATUS_CODE_FOUND:
431 return retcode;
432 default:
433 if (retcode < 400)
a150f8e1 434 retcode = HTTP_R_STATUS_CODE_UNSUPPORTED;
29f178bd 435 else
a150f8e1 436 retcode = HTTP_R_RECEIVED_ERROR;
29f178bd 437 if (*reason == '\0')
552aeaef 438 ERR_raise_data(ERR_LIB_HTTP, retcode, "code=%s", code);
29f178bd 439 else
a150f8e1 440 ERR_raise_data(ERR_LIB_HTTP, retcode,
552aeaef 441 "code=%s, reason=%s", code, reason);
29f178bd
DDO
442 return 0;
443 }
19f97fe6
DDO
444
445 err:
be799eb7
DDO
446 i = 0;
447 while (i < 60 && ossl_isprint(line[i]))
448 i++;
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
467/*
468 * Try exchanging request and response via HTTP on (non-)blocking BIO in rctx.
469 * Returns 1 on success, 0 on error or redirection, -1 on BIO_should_retry.
470 */
471int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx)
472{
19f97fe6 473 int i, found_expected_ct = 0, found_keep_alive = 0;
673474b1 474 long n;
be799eb7 475 size_t resp_len;
29f178bd
DDO
476 const unsigned char *p;
477 char *key, *value, *line_end = NULL;
478
479 if (rctx == NULL) {
9311d0c4 480 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
29f178bd
DDO
481 return 0;
482 }
a6d40689
DDO
483 if (rctx->mem == NULL || rctx->wbio == NULL || rctx->rbio == NULL) {
484 ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
485 return 0;
486 }
29f178bd
DDO
487
488 rctx->redirection_url = NULL;
489 next_io:
490 if ((rctx->state & OHS_NOREAD) == 0) {
be799eb7 491 if (rctx->expect_asn1)
e2c38c1a 492 n = BIO_read(rctx->rbio, rctx->buf, rctx->buf_size);
be799eb7 493 else
e2c38c1a 494 n = BIO_gets(rctx->rbio, (char *)rctx->buf, rctx->buf_size);
29f178bd
DDO
495 if (n <= 0) {
496 if (BIO_should_retry(rctx->rbio))
497 return -1;
a6d40689 498 ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA);
29f178bd
DDO
499 return 0;
500 }
501
502 /* Write data to memory BIO */
e2c38c1a 503 if (BIO_write(rctx->mem, rctx->buf, n) != n)
29f178bd
DDO
504 return 0;
505 }
506
507 switch (rctx->state) {
8b5ca511 508 case OHS_ADD_HEADERS:
29f178bd
DDO
509 /* Last operation was adding headers: need a final \r\n */
510 if (BIO_write(rctx->mem, "\r\n", 2) != 2) {
511 rctx->state = OHS_ERROR;
512 return 0;
513 }
514 rctx->state = OHS_WRITE_INIT;
515
516 /* fall thru */
517 case OHS_WRITE_INIT:
8b5ca511
DDO
518 rctx->len_to_send = BIO_get_mem_data(rctx->mem, &rctx->pos);
519 rctx->state = OHS_WRITE_HDR;
29f178bd
DDO
520
521 /* fall thru */
8b5ca511
DDO
522 case OHS_WRITE_HDR:
523 /* Copy some chunk of data from rctx->mem to rctx->wbio */
524 case OHS_WRITE_REQ:
525 /* Copy some chunk of data from rctx->req to rctx->wbio */
526
527 if (rctx->len_to_send > 0) {
528 i = BIO_write(rctx->wbio, rctx->pos, rctx->len_to_send);
529 if (i <= 0) {
530 if (BIO_should_retry(rctx->wbio))
531 return -1;
532 rctx->state = OHS_ERROR;
533 return 0;
534 }
535 rctx->pos += i;
536 rctx->len_to_send -= i;
537 goto next_io;
29f178bd 538 }
8b5ca511
DDO
539 if (rctx->state == OHS_WRITE_HDR) {
540 (void)BIO_reset(rctx->mem);
541 rctx->state = OHS_WRITE_REQ;
542 }
543 if (rctx->req != NULL && !BIO_eof(rctx->req)) {
e2c38c1a 544 n = BIO_read(rctx->req, rctx->buf, rctx->buf_size);
8b5ca511
DDO
545 if (n <= 0) {
546 if (BIO_should_retry(rctx->rbio))
547 return -1;
548 ERR_raise(ERR_LIB_HTTP, HTTP_R_FAILED_READING_DATA);
549 return 0;
550 }
e2c38c1a 551 rctx->pos = rctx->buf;
8b5ca511 552 rctx->len_to_send = n;
29f178bd 553 goto next_io;
8b5ca511 554 }
29f178bd
DDO
555 rctx->state = OHS_FLUSH;
556
29f178bd
DDO
557 /* fall thru */
558 case OHS_FLUSH:
559
560 i = BIO_flush(rctx->wbio);
561
562 if (i > 0) {
563 rctx->state = OHS_FIRSTLINE;
564 goto next_io;
565 }
566
567 if (BIO_should_retry(rctx->wbio))
568 return -1;
569
570 rctx->state = OHS_ERROR;
571 return 0;
572
573 case OHS_ERROR:
574 return 0;
575
576 case OHS_FIRSTLINE:
577 case OHS_HEADERS:
578 case OHS_REDIRECT:
579
580 /* Attempt to read a line in */
581 next_line:
582 /*
583 * Due to strange memory BIO behavior with BIO_gets we have to check
584 * there's a complete line in there before calling BIO_gets or we'll
585 * just get a partial read.
586 */
587 n = BIO_get_mem_data(rctx->mem, &p);
588 if (n <= 0 || memchr(p, '\n', n) == 0) {
e2c38c1a 589 if (n >= rctx->buf_size) {
29f178bd
DDO
590 rctx->state = OHS_ERROR;
591 return 0;
592 }
593 goto next_io;
594 }
e2c38c1a 595 n = BIO_gets(rctx->mem, (char *)rctx->buf, rctx->buf_size);
29f178bd
DDO
596
597 if (n <= 0) {
598 if (BIO_should_retry(rctx->mem))
599 goto next_io;
600 rctx->state = OHS_ERROR;
601 return 0;
602 }
603
604 /* Don't allow excessive lines */
e2c38c1a 605 if (n == rctx->buf_size) {
9311d0c4 606 ERR_raise(ERR_LIB_HTTP, HTTP_R_RESPONSE_LINE_TOO_LONG);
29f178bd
DDO
607 rctx->state = OHS_ERROR;
608 return 0;
609 }
610
611 /* First line */
612 if (rctx->state == OHS_FIRSTLINE) {
e2c38c1a 613 switch (parse_http_line1((char *)rctx->buf, &found_keep_alive)) {
29f178bd
DDO
614 case HTTP_STATUS_CODE_OK:
615 rctx->state = OHS_HEADERS;
616 goto next_line;
617 case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
618 case HTTP_STATUS_CODE_FOUND: /* i.e., moved temporarily */
046fba44 619 if (!rctx->method_POST) { /* method is GET */
29f178bd
DDO
620 rctx->state = OHS_REDIRECT;
621 goto next_line;
622 }
9311d0c4 623 ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED);
29f178bd
DDO
624 /* redirection is not supported/recommended for POST */
625 /* fall through */
626 default:
627 rctx->state = OHS_ERROR;
628 return 0;
629 }
630 }
e2c38c1a 631 key = (char *)rctx->buf;
29f178bd
DDO
632 value = strchr(key, ':');
633 if (value != NULL) {
634 *(value++) = '\0';
635 while (ossl_isspace(*value))
636 value++;
637 line_end = strchr(value, '\r');
638 if (line_end == NULL)
639 line_end = strchr(value, '\n');
640 if (line_end != NULL)
641 *line_end = '\0';
642 }
643 if (value != NULL && line_end != NULL) {
afe554c2
DDO
644 if (rctx->state == OHS_REDIRECT
645 && strcasecmp(key, "Location") == 0) {
29f178bd
DDO
646 rctx->redirection_url = value;
647 return 0;
648 }
afe554c2
DDO
649 if (rctx->expected_ct != NULL
650 && strcasecmp(key, "Content-Type") == 0) {
651 if (strcasecmp(rctx->expected_ct, value) != 0) {
a150f8e1
RL
652 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_UNEXPECTED_CONTENT_TYPE,
653 "expected=%s, actual=%s",
654 rctx->expected_ct, value);
29f178bd
DDO
655 return 0;
656 }
19f97fe6
DDO
657 found_expected_ct = 1;
658 }
659
660 /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
661 if (strcasecmp(key, "Connection") == 0) {
662 if (strcasecmp(value, "keep-alive") == 0)
663 found_keep_alive = 1;
664 else if (strcasecmp(value, "close") == 0)
665 found_keep_alive = 0;
e2c38c1a 666 } else if (strcasecmp(key, "Content-Length") == 0) {
be799eb7 667 resp_len = (size_t)strtoul(value, &line_end, 10);
29f178bd 668 if (line_end == value || *line_end != '\0') {
a150f8e1
RL
669 ERR_raise_data(ERR_LIB_HTTP,
670 HTTP_R_ERROR_PARSING_CONTENT_LENGTH,
671 "input=%s", value);
29f178bd
DDO
672 return 0;
673 }
674 if (!check_set_resp_len(rctx, resp_len))
675 return 0;
676 }
677 }
678
d337af18 679 /* Look for blank line indicating end of headers */
e2c38c1a 680 for (p = rctx->buf; *p != '\0'; p++) {
29f178bd
DDO
681 if (*p != '\r' && *p != '\n')
682 break;
683 }
684 if (*p != '\0') /* not end of headers */
685 goto next_line;
686
19f97fe6 687 if (rctx->expected_ct != NULL && !found_expected_ct) {
a150f8e1
RL
688 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MISSING_CONTENT_TYPE,
689 "expected=%s", rctx->expected_ct);
29f178bd
DDO
690 return 0;
691 }
19f97fe6
DDO
692 if (rctx->keep_alive != 0 /* do not let server initiate keep_alive */
693 && !found_keep_alive /* otherwise there is no change */) {
694 if (rctx->keep_alive == 2) {
695 rctx->keep_alive = 0;
696 ERR_raise(ERR_LIB_HTTP, HTTP_R_SERVER_CANCELED_CONNECTION);
697 return 0;
698 }
699 rctx->keep_alive = 0;
700 }
701
29f178bd
DDO
702 if (rctx->state == OHS_REDIRECT) {
703 /* http status code indicated redirect but there was no Location */
9311d0c4 704 ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_REDIRECT_LOCATION);
29f178bd
DDO
705 return 0;
706 }
707
708 if (!rctx->expect_asn1) {
be799eb7
DDO
709 rctx->state = OHS_STREAM;
710 return 1;
29f178bd
DDO
711 }
712
713 rctx->state = OHS_ASN1_HEADER;
714
715 /* Fall thru */
716 case OHS_ASN1_HEADER:
717 /*
718 * Now reading ASN1 header: can read at least 2 bytes which is enough
719 * for ASN1 SEQUENCE header and either length field or at least the
720 * length of the length field.
721 */
722 n = BIO_get_mem_data(rctx->mem, &p);
723 if (n < 2)
724 goto next_io;
725
726 /* Check it is an ASN1 SEQUENCE */
727 if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
9311d0c4 728 ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_ASN1_ENCODING);
29f178bd
DDO
729 return 0;
730 }
731
732 /* Check out length field */
733 if ((*p & 0x80) != 0) {
734 /*
735 * If MSB set on initial length octet we can now always read 6
736 * octets: make sure we have them.
737 */
738 if (n < 6)
739 goto next_io;
740 n = *p & 0x7F;
741 /* Not NDEF or excessive length */
742 if (n == 0 || (n > 4)) {
9311d0c4 743 ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_ASN1_LENGTH);
29f178bd
DDO
744 return 0;
745 }
746 p++;
747 resp_len = 0;
748 for (i = 0; i < n; i++) {
749 resp_len <<= 8;
750 resp_len |= *p++;
751 }
752 resp_len += n + 2;
753 } else {
754 resp_len = *p + 2;
755 }
756 if (!check_set_resp_len(rctx, resp_len))
757 return 0;
758
be799eb7 759 rctx->state = OHS_ASN1_CONTENT;
29f178bd
DDO
760
761 /* Fall thru */
be799eb7 762 case OHS_ASN1_CONTENT:
29f178bd
DDO
763 default:
764 n = BIO_get_mem_data(rctx->mem, NULL);
be799eb7 765 if (n < 0 || (size_t)n < rctx->resp_len)
29f178bd
DDO
766 goto next_io;
767
be799eb7 768 rctx->state = OHS_ASN1_DONE;
29f178bd
DDO
769 return 1;
770 }
771}
772
8f965908
DDO
773int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX *rctx,
774 ASN1_VALUE **pval, const ASN1_ITEM *it)
775{
776 const unsigned char *p;
777 int rv;
778
779 *pval = NULL;
780 if ((rv = OSSL_HTTP_REQ_CTX_nbio(rctx)) != 1)
781 return rv;
782 *pval = ASN1_item_d2i(NULL, &p, BIO_get_mem_data(rctx->mem, &p), it);
783 return *pval != NULL;
784
785}
786
29f178bd
DDO
787#ifndef OPENSSL_NO_SOCK
788
789/* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
e2c38c1a 790static BIO *http_new_bio(const char *server /* optionally includes ":port" */,
afe554c2 791 const char *server_port /* explicit server port */,
79a2bccd
DDO
792 int use_ssl,
793 const char *proxy /* optionally includes ":port" */,
794 const char *proxy_port /* explicit proxy port */)
29f178bd 795{
79a2bccd 796 const char *host = server;
29f178bd
DDO
797 const char *port = server_port;
798 BIO *cbio;
799
4b1fe471 800 if (!ossl_assert(server != NULL))
29f178bd 801 return NULL;
29f178bd
DDO
802
803 if (proxy != NULL) {
804 host = proxy;
79a2bccd 805 port = proxy_port;
29f178bd 806 }
afe554c2 807
79a2bccd
DDO
808 if (port == NULL && strchr(host, ':') == NULL)
809 port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
afe554c2
DDO
810
811 cbio = BIO_new_connect(host /* optionally includes ":port" */);
29f178bd
DDO
812 if (cbio == NULL)
813 goto end;
814 if (port != NULL)
815 (void)BIO_set_conn_port(cbio, port);
816
817 end:
818 return cbio;
819}
e8d0819d 820#endif /* OPENSSL_NO_SOCK */
29f178bd 821
82990287 822/* Exchange request and response via HTTP on (non-)blocking BIO */
8f965908 823BIO *OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX *rctx)
29f178bd 824{
29f178bd
DDO
825 int rv;
826
827 if (rctx == NULL) {
9311d0c4 828 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
29f178bd
DDO
829 return NULL;
830 }
831
832 for (;;) {
833 rv = OSSL_HTTP_REQ_CTX_nbio(rctx);
834 if (rv != -1)
835 break;
836 /* BIO_should_retry was true */
29f178bd 837 /* will not actually wait if rctx->max_time == 0 */
e8d0819d 838 if (BIO_wait(rctx->rbio, rctx->max_time, 100 /* milliseconds */) <= 0)
29f178bd
DDO
839 return NULL;
840 }
841
842 if (rv == 0) {
843 if (rctx->redirection_url == NULL) { /* an error occurred */
1e6174b1 844 if (rctx->len_to_send > 0)
9311d0c4 845 ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_SENDING);
29f178bd 846 else
9311d0c4 847 ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_RECEIVING);
29f178bd
DDO
848 }
849 return NULL;
850 }
be799eb7 851 return rctx->state == OHS_STREAM ? rctx->rbio : rctx->mem;
29f178bd
DDO
852}
853
19f97fe6 854int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX *rctx)
29f178bd 855{
19f97fe6 856 return rctx != NULL && rctx->keep_alive != 0;
29f178bd
DDO
857}
858
19f97fe6
DDO
859/* High-level HTTP API implementation */
860
861/* Initiate an HTTP session using bio, else use given server, proxy, etc. */
8f965908
DDO
862OSSL_HTTP_REQ_CTX *OSSL_HTTP_open(const char *server, const char *port,
863 const char *proxy, const char *no_proxy,
864 int use_ssl, BIO *bio, BIO *rbio,
865 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
be799eb7 866 int buf_size, int overall_timeout)
8f965908 867{
19f97fe6
DDO
868 BIO *cbio; /* == bio if supplied, used as connection BIO if rbio is NULL */
869 OSSL_HTTP_REQ_CTX *rctx = NULL;
29f178bd
DDO
870
871 if (use_ssl && bio_update_fn == NULL) {
9311d0c4 872 ERR_raise(ERR_LIB_HTTP, HTTP_R_TLS_NOT_ENABLED);
29f178bd
DDO
873 return NULL;
874 }
875 if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) {
9311d0c4 876 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
29f178bd
DDO
877 return NULL;
878 }
29f178bd 879
4b1fe471 880 if (bio != NULL) {
29f178bd 881 cbio = bio;
82990287
DDO
882 if (proxy != NULL || no_proxy != NULL) {
883 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
884 return NULL;
885 }
4b1fe471 886 } else {
e8d0819d 887#ifndef OPENSSL_NO_SOCK
79a2bccd
DDO
888 char *proxy_host = NULL, *proxy_port = NULL;
889
4b1fe471 890 if (server == NULL) {
9311d0c4 891 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
4b1fe471
DDO
892 return NULL;
893 }
19f97fe6 894 if (port != NULL && *port == '\0')
4b1fe471
DDO
895 port = NULL;
896 if (port == NULL && strchr(server, ':') == NULL)
897 port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
ab9d67ef 898 proxy = OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl);
79a2bccd
DDO
899 if (proxy != NULL
900 && !OSSL_HTTP_parse_url(proxy, NULL /* use_ssl */, NULL /* user */,
901 &proxy_host, &proxy_port, NULL /* num */,
902 NULL /* path */, NULL, NULL))
903 return NULL;
e2c38c1a 904 cbio = http_new_bio(server, port, use_ssl, proxy_host, proxy_port);
79a2bccd
DDO
905 OPENSSL_free(proxy_host);
906 OPENSSL_free(proxy_port);
907 if (cbio == NULL)
e8d0819d
DDO
908 return NULL;
909#else
9311d0c4 910 ERR_raise(ERR_LIB_HTTP, HTTP_R_SOCK_NOT_SUPPORTED);
29f178bd 911 return NULL;
e8d0819d 912#endif
4b1fe471 913 }
29f178bd
DDO
914
915 (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
19f97fe6
DDO
916 if (rbio == NULL && BIO_do_connect_retry(cbio, overall_timeout, -1) <= 0) {
917 if (bio == NULL) /* cbio was not provided by caller */
918 BIO_free_all(cbio);
29f178bd 919 goto end;
19f97fe6
DDO
920 }
921 /* now overall_timeout is guaranteed to be >= 0 */
29f178bd
DDO
922
923 /* callback can be used to wrap or prepend TLS session */
924 if (bio_update_fn != NULL) {
925 BIO *orig_bio = cbio;
19f97fe6 926
29f178bd
DDO
927 cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl);
928 if (cbio == NULL) {
929 cbio = orig_bio;
930 goto end;
931 }
932 }
933
19f97fe6
DDO
934 rctx = http_req_ctx_new(bio == NULL, cbio, rbio != NULL ? rbio : cbio,
935 bio_update_fn, arg, use_ssl, proxy, server, port,
be799eb7 936 buf_size, overall_timeout);
19f97fe6
DDO
937
938 end:
939 if (rctx != NULL)
940 /* remove any spurious error queue entries by ssl_add_cert_chain() */
941 (void)ERR_pop_to_mark();
942 else
943 (void)ERR_clear_last_mark();
944
945 return rctx;
946}
947
8ccbf00d
DDO
948int OSSL_HTTP_set1_request(OSSL_HTTP_REQ_CTX *rctx, const char *path,
949 const STACK_OF(CONF_VALUE) *headers,
950 const char *content_type, BIO *req,
951 const char *expected_content_type, int expect_asn1,
952 size_t max_resp_len, int timeout, int keep_alive)
19f97fe6
DDO
953{
954 int use_http_proxy;
955
956 if (rctx == NULL) {
957 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
958 return 0;
959 }
960 use_http_proxy = rctx->proxy != NULL && !rctx->use_ssl;
961 if (use_http_proxy && (rctx->server == NULL || rctx->port == NULL)) {
962 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
963 return 0;
964 }
be799eb7 965 rctx->max_resp_len = max_resp_len; /* allows for 0: indefinite */
19f97fe6 966
8b5ca511 967 return OSSL_HTTP_REQ_CTX_set_request_line(rctx, req != NULL,
19f97fe6
DDO
968 use_http_proxy ? rctx->server
969 : NULL, rctx->port, path)
e2c38c1a 970 && add1_headers(rctx, headers, rctx->server)
19f97fe6
DDO
971 && OSSL_HTTP_REQ_CTX_set_expected(rctx, expected_content_type,
972 expect_asn1, timeout, keep_alive)
de5a0198 973 && set1_content(rctx, content_type, req);
19f97fe6
DDO
974}
975
976/*-
977 * Exchange single HTTP request and response according to rctx.
978 * If rctx->method_POST then use POST, else use GET and ignore content_type.
979 * The redirection_url output (freed by caller) parameter is used only for GET.
980 */
981BIO *OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX *rctx, char **redirection_url)
982{
983 BIO *resp;
984
985 if (rctx == NULL) {
986 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
987 return NULL;
988 }
989
990 if (redirection_url != NULL)
991 *redirection_url = NULL; /* do this beforehand to prevent dbl free */
29f178bd 992
8f965908 993 resp = OSSL_HTTP_REQ_CTX_exchange(rctx);
29f178bd
DDO
994 if (resp == NULL) {
995 if (rctx->redirection_url != NULL) {
996 if (redirection_url == NULL)
9311d0c4 997 ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED);
29f178bd
DDO
998 else
999 /* may be NULL if out of memory: */
1000 *redirection_url = OPENSSL_strdup(rctx->redirection_url);
1001 } else {
1002 char buf[200];
1003 unsigned long err = ERR_peek_error();
1004 int lib = ERR_GET_LIB(err);
1005 int reason = ERR_GET_REASON(err);
1006
1007 if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP
1008 || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT)
1009 || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR)
4b1fe471 1010#ifndef OPENSSL_NO_CMP
29f178bd 1011 || (lib == ERR_LIB_CMP
100cc8b0 1012 && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
4b1fe471 1013#endif
100cc8b0 1014 ) {
19f97fe6 1015 if (rctx->server != NULL) {
22fe2b12
DDO
1016 BIO_snprintf(buf, sizeof(buf), "server=http%s://%s%s%s",
1017 rctx->use_ssl ? "s" : "", rctx->server,
1018 rctx->port != NULL ? ":" : "",
1019 rctx->port != NULL ? rctx->port : "");
1020 ERR_add_error_data(1, buf);
19f97fe6 1021 }
19f97fe6
DDO
1022 if (rctx->proxy != NULL)
1023 ERR_add_error_data(2, " proxy=", rctx->proxy);
29f178bd 1024 if (err == 0) {
22fe2b12 1025 BIO_snprintf(buf, sizeof(buf), " peer has disconnected%s",
19f97fe6 1026 rctx->use_ssl ? " violating the protocol" :
29f178bd
DDO
1027 ", likely because it requires the use of TLS");
1028 ERR_add_error_data(1, buf);
1029 }
1030 }
1031 }
1032 }
6466cc97
DDO
1033
1034 if (resp != NULL && !BIO_up_ref(resp))
1035 resp = NULL;
29f178bd
DDO
1036 return resp;
1037}
1038
1039static int redirection_ok(int n_redir, const char *old_url, const char *new_url)
1040{
29f178bd 1041 if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) {
9311d0c4 1042 ERR_raise(ERR_LIB_HTTP, HTTP_R_TOO_MANY_REDIRECTIONS);
29f178bd
DDO
1043 return 0;
1044 }
1045 if (*new_url == '/') /* redirection to same server => same protocol */
1046 return 1;
b6fec965
DDO
1047 if (HAS_PREFIX(old_url, OSSL_HTTPS_NAME":") &&
1048 !HAS_PREFIX(new_url, OSSL_HTTPS_NAME":")) {
9311d0c4 1049 ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP);
29f178bd
DDO
1050 return 0;
1051 }
1052 return 1;
1053}
1054
1055/* Get data via HTTP from server at given URL, potentially with redirection */
afe554c2 1056BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy,
29f178bd
DDO
1057 BIO *bio, BIO *rbio,
1058 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
68bb06f7 1059 int buf_size, const STACK_OF(CONF_VALUE) *headers,
8f965908 1060 const char *expected_ct, int expect_asn1,
c4005c8b 1061 size_t max_resp_len, int timeout)
29f178bd 1062{
8f965908 1063 char *current_url, *redirection_url = NULL;
29f178bd
DDO
1064 int n_redirs = 0;
1065 char *host;
1066 char *port;
1067 char *path;
1068 int use_ssl;
19f97fe6 1069 OSSL_HTTP_REQ_CTX *rctx;
29f178bd
DDO
1070 BIO *resp = NULL;
1071
1072 if (url == NULL) {
9311d0c4 1073 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
29f178bd
DDO
1074 return NULL;
1075 }
1076 if ((current_url = OPENSSL_strdup(url)) == NULL)
1077 return NULL;
1078
1079 for (;;) {
7932982b
DDO
1080 if (!OSSL_HTTP_parse_url(current_url, &use_ssl, NULL /* user */, &host,
1081 &port, NULL /* port_num */, &path, NULL, NULL))
29f178bd
DDO
1082 break;
1083
19f97fe6
DDO
1084 rctx = OSSL_HTTP_open(host, port, proxy, no_proxy,
1085 use_ssl, bio, rbio, bio_update_fn, arg,
be799eb7 1086 buf_size, timeout);
8801240b 1087 new_rpath:
19f97fe6 1088 if (rctx != NULL) {
8ccbf00d
DDO
1089 if (!OSSL_HTTP_set1_request(rctx, path, headers,
1090 NULL /* content_type */,
1091 NULL /* req */,
1092 expected_ct, expect_asn1, max_resp_len,
1093 -1 /* use same max time (timeout) */,
1094 0 /* no keep_alive */))
19f97fe6 1095 OSSL_HTTP_REQ_CTX_free(rctx);
8801240b 1096 else
19f97fe6 1097 resp = OSSL_HTTP_exchange(rctx, &redirection_url);
19f97fe6 1098 }
29f178bd
DDO
1099 OPENSSL_free(path);
1100 if (resp == NULL && redirection_url != NULL) {
1101 if (redirection_ok(++n_redirs, current_url, redirection_url)) {
1102 (void)BIO_reset(bio);
1103 OPENSSL_free(current_url);
1104 current_url = redirection_url;
1105 if (*redirection_url == '/') { /* redirection to same server */
1106 path = OPENSSL_strdup(redirection_url);
1107 goto new_rpath;
1108 }
1109 OPENSSL_free(host);
1110 OPENSSL_free(port);
8801240b 1111 (void)OSSL_HTTP_close(rctx, 1);
29f178bd
DDO
1112 continue;
1113 }
8801240b 1114 /* if redirection not allowed, ignore it */
29f178bd
DDO
1115 OPENSSL_free(redirection_url);
1116 }
1117 OPENSSL_free(host);
1118 OPENSSL_free(port);
8801240b
DDO
1119 if (!OSSL_HTTP_close(rctx, resp != NULL)) {
1120 BIO_free(resp);
1121 resp = NULL;
1122 }
29f178bd
DDO
1123 break;
1124 }
1125 OPENSSL_free(current_url);
1126 return resp;
1127}
1128
82990287 1129/* Exchange request and response over a connection managed via |prctx| */
19f97fe6
DDO
1130BIO *OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX **prctx,
1131 const char *server, const char *port,
1132 const char *path, int use_ssl,
1133 const char *proxy, const char *no_proxy,
1134 BIO *bio, BIO *rbio,
1135 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
1136 int buf_size, const STACK_OF(CONF_VALUE) *headers,
1137 const char *content_type, BIO *req,
1138 const char *expected_ct, int expect_asn1,
be799eb7 1139 size_t max_resp_len, int timeout, int keep_alive)
19f97fe6
DDO
1140{
1141 OSSL_HTTP_REQ_CTX *rctx = prctx == NULL ? NULL : *prctx;
1142 BIO *resp = NULL;
1143
1144 if (rctx == NULL) {
1145 rctx = OSSL_HTTP_open(server, port, proxy, no_proxy,
1146 use_ssl, bio, rbio, bio_update_fn, arg,
be799eb7 1147 buf_size, timeout);
19f97fe6
DDO
1148 timeout = -1; /* Already set during opening the connection */
1149 }
1150 if (rctx != NULL) {
8ccbf00d
DDO
1151 if (OSSL_HTTP_set1_request(rctx, path, headers, content_type, req,
1152 expected_ct, expect_asn1,
1153 max_resp_len, timeout, keep_alive))
19f97fe6
DDO
1154 resp = OSSL_HTTP_exchange(rctx, NULL);
1155 if (resp == NULL || !OSSL_HTTP_is_alive(rctx)) {
82990287
DDO
1156 if (!OSSL_HTTP_close(rctx, resp != NULL)) {
1157 BIO_free(resp);
19f97fe6 1158 resp = NULL;
82990287 1159 }
19f97fe6
DDO
1160 rctx = NULL;
1161 }
1162 }
1163 if (prctx != NULL)
1164 *prctx = rctx;
1165 return resp;
1166}
1167
8f965908 1168int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX *rctx, int ok)
29f178bd 1169{
19f97fe6
DDO
1170 int ret = 1;
1171
1172 /* callback can be used to clean up TLS session on disconnect */
1173 if (rctx != NULL && rctx->upd_fn != NULL)
1174 ret = (*rctx->upd_fn)(rctx->wbio, rctx->upd_arg, 0, ok) != NULL;
1175 OSSL_HTTP_REQ_CTX_free(rctx);
1176 return ret;
29f178bd
DDO
1177}
1178
1179/* BASE64 encoder used for encoding basic proxy authentication credentials */
1180static char *base64encode(const void *buf, size_t len)
1181{
1182 int i;
1183 size_t outl;
1184 char *out;
1185
1186 /* Calculate size of encoded data */
1187 outl = (len / 3);
1188 if (len % 3 > 0)
1189 outl++;
1190 outl <<= 2;
1191 out = OPENSSL_malloc(outl + 1);
1192 if (out == NULL)
1193 return 0;
1194
1195 i = EVP_EncodeBlock((unsigned char *)out, buf, len);
1196 if (!ossl_assert(0 <= i && (size_t)i <= outl)) {
1197 OPENSSL_free(out);
1198 return NULL;
1199 }
1200 return out;
1201}
1202
1203/*
1204 * Promote the given connection BIO using the CONNECT method for a TLS proxy.
1205 * This is typically called by an app, so bio_err and prog are used unless NULL
1206 * to print additional diagnostic information in a user-oriented way.
1207 */
1208int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port,
1209 const char *proxyuser, const char *proxypass,
1210 int timeout, BIO *bio_err, const char *prog)
1211{
4b1fe471
DDO
1212#undef BUF_SIZE
1213#define BUF_SIZE (8 * 1024)
29f178bd
DDO
1214 char *mbuf = OPENSSL_malloc(BUF_SIZE);
1215 char *mbufp;
1216 int read_len = 0;
29f178bd
DDO
1217 int ret = 0;
1218 BIO *fbio = BIO_new(BIO_f_buffer());
e8d0819d 1219 int rv;
29f178bd
DDO
1220 time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
1221
4b1fe471 1222 if (bio == NULL || server == NULL
29f178bd 1223 || (bio_err != NULL && prog == NULL)) {
9311d0c4 1224 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
29f178bd
DDO
1225 goto end;
1226 }
4b1fe471
DDO
1227 if (port == NULL || *port == '\0')
1228 port = OSSL_HTTPS_PORT;
29f178bd
DDO
1229
1230 if (mbuf == NULL || fbio == NULL) {
1231 BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog);
1232 goto end;
1233 }
1234 BIO_push(fbio, bio);
1235
19f97fe6 1236 BIO_printf(fbio, "CONNECT %s:%s "HTTP_1_0"\r\n", server, port);
29f178bd
DDO
1237
1238 /*
1239 * Workaround for broken proxies which would otherwise close
1240 * the connection when entering tunnel mode (e.g., Squid 2.6)
1241 */
1242 BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n");
1243
1244 /* Support for basic (base64) proxy authentication */
1245 if (proxyuser != NULL) {
1246 size_t len = strlen(proxyuser) + 1;
1247 char *proxyauth, *proxyauthenc = NULL;
1248
1249 if (proxypass != NULL)
1250 len += strlen(proxypass);
1251 proxyauth = OPENSSL_malloc(len + 1);
1252 if (proxyauth == NULL)
1253 goto end;
1254 if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser,
1255 proxypass != NULL ? proxypass : "") != (int)len)
1256 goto proxy_end;
1257 proxyauthenc = base64encode(proxyauth, len);
1258 if (proxyauthenc != NULL) {
1259 BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc);
1260 OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc));
1261 }
a6d40689 1262 proxy_end:
29f178bd
DDO
1263 OPENSSL_clear_free(proxyauth, len);
1264 if (proxyauthenc == NULL)
1265 goto end;
1266 }
1267
1268 /* Terminate the HTTP CONNECT request */
1269 BIO_printf(fbio, "\r\n");
1270
1271 for (;;) {
1272 if (BIO_flush(fbio) != 0)
1273 break;
1274 /* potentially needs to be retried if BIO is non-blocking */
1275 if (!BIO_should_retry(fbio))
1276 break;
1277 }
1278
1279 for (;;) {
1280 /* will not actually wait if timeout == 0 */
e8d0819d 1281 rv = BIO_wait(fbio, max_time, 100 /* milliseconds */);
29f178bd
DDO
1282 if (rv <= 0) {
1283 BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog,
1284 rv == 0 ? "timed out" : "failed waiting for data");
1285 goto end;
1286 }
1287
1288 /*-
1289 * The first line is the HTTP response.
1290 * According to RFC 7230, it is formatted exactly like this:
552aeaef 1291 * HTTP/d.d ddd reason text\r\n
29f178bd
DDO
1292 */
1293 read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1294 /* the BIO may not block, so we must wait for the 1st line to come in */
765860a3 1295 if (read_len < (int)HTTP_LINE1_MINLEN)
29f178bd
DDO
1296 continue;
1297
19f97fe6 1298 /* Check for HTTP/1.x */
b6fec965 1299 if (!HAS_PREFIX(mbuf, HTTP_PREFIX) != 0) {
19f97fe6 1300 ERR_raise(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR);
29f178bd
DDO
1301 BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n",
1302 prog);
1303 /* Wrong protocol, not even HTTP, so stop reading headers */
1304 goto end;
1305 }
1306 mbufp = mbuf + strlen(HTTP_PREFIX);
b6fec965 1307 if (!HAS_PREFIX(mbufp, HTTP_VERSION_PATT) != 0) {
9311d0c4 1308 ERR_raise(ERR_LIB_HTTP, HTTP_R_RECEIVED_WRONG_HTTP_VERSION);
29f178bd
DDO
1309 BIO_printf(bio_err,
1310 "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
19f97fe6 1311 prog, (int)HTTP_VERSION_STR_LEN, mbufp);
29f178bd
DDO
1312 goto end;
1313 }
1314 mbufp += HTTP_VERSION_STR_LEN;
19f97fe6
DDO
1315
1316 /* RFC 7231 4.3.6: any 2xx status code is valid */
b6fec965 1317 if (!HAS_PREFIX(mbufp, " 2")) {
29f178bd
DDO
1318 /* chop any trailing whitespace */
1319 while (read_len > 0 && ossl_isspace(mbuf[read_len - 1]))
1320 read_len--;
1321 mbuf[read_len] = '\0';
a150f8e1 1322 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_CONNECT_FAILURE,
552aeaef
DDO
1323 "reason=%s", mbufp);
1324 BIO_printf(bio_err, "%s: HTTP CONNECT failed, reason=%s\n",
29f178bd
DDO
1325 prog, mbufp);
1326 goto end;
1327 }
1328 ret = 1;
1329 break;
1330 }
1331
1332 /* Read past all following headers */
1333 do {
1334 /*
60e91cc4 1335 * This does not necessarily catch the case when the full
29f178bd
DDO
1336 * HTTP response came in in more than a single TCP message.
1337 */
1338 read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1339 } while (read_len > 2);
1340
1341 end:
1342 if (fbio != NULL) {
1343 (void)BIO_flush(fbio);
1344 BIO_pop(fbio);
1345 BIO_free(fbio);
1346 }
1347 OPENSSL_free(mbuf);
1348 return ret;
4b1fe471 1349#undef BUF_SIZE
29f178bd 1350}