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