VirtualBox

source: vbox/trunk/src/libs/openssl-3.1.0/crypto/http/http_client.c@ 99507

最後變更 在這個檔案從99507是 99366,由 vboxsync 提交於 2 年 前

openssl-3.1.0: Applied and adjusted our OpenSSL changes to 3.0.7. bugref:10418

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette