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