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