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