]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/http/http_client.c
HTTP client API: Generalize to arbitrary request and response contents
[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 response by line */
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 and response */
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 long len_to_send; /* Number of bytes in request still to send */
63 unsigned long resp_len; /* Length of response */
64 size_t max_resp_len; /* Maximum length of response */
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_FIRSTLINE 1 /* First line being read */
76 #define OHS_REDIRECT 0xa /* Looking for redirection location */
77 #define OHS_HEADERS 2 /* MIME headers being read */
78 #define OHS_ASN1_HEADER 3 /* HTTP initial header (tag+length) being read */
79 #define OHS_CONTENT 4 /* HTTP content octets being read */
80 #define OHS_WRITE_INIT (5 | OHS_NOREAD) /* 1st call: ready to start send */
81 #define OHS_WRITE (6 | OHS_NOREAD) /* Request being sent */
82 #define OHS_FLUSH (7 | OHS_NOREAD) /* Request being flushed */
83 #define OHS_DONE (8 | OHS_NOREAD) /* Completed */
84 #define OHS_HTTP_HEADER (9 | OHS_NOREAD) /* Headers set, w/o final \r\n */
85
86 /* Low-level HTTP API implementation */
87
88 OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int buf_size)
89 {
90 OSSL_HTTP_REQ_CTX *rctx;
91
92 if (wbio == NULL || rbio == NULL) {
93 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
94 return NULL;
95 }
96
97 if ((rctx = OPENSSL_zalloc(sizeof(*rctx))) == NULL)
98 return NULL;
99 rctx->state = OHS_ERROR;
100 rctx->readbuflen = buf_size > 0 ? buf_size : HTTP_DEFAULT_MAX_LINE_LENGTH;
101 rctx->readbuf = OPENSSL_malloc(rctx->readbuflen);
102 rctx->wbio = wbio;
103 rctx->rbio = rbio;
104 if (rctx->readbuf == NULL) {
105 OPENSSL_free(rctx);
106 return NULL;
107 }
108 rctx->max_resp_len = HTTP_DEFAULT_MAX_RESP_LEN;
109 /* everything else is 0, e.g. rctx->len_to_send, or NULL, e.g. rctx->mem */
110 return rctx;
111 }
112
113 void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx)
114 {
115 if (rctx == NULL)
116 return;
117 /*
118 * Use BIO_free_all() because bio_update_fn may prepend or append to cbio.
119 * This also frees any (e.g., SSL/TLS) BIOs linked with bio and,
120 * like BIO_reset(bio), calls SSL_shutdown() to notify/alert the peer.
121 */
122 if (rctx->free_wbio)
123 BIO_free_all(rctx->wbio);
124 /* do not free rctx->rbio */
125 BIO_free(rctx->mem); /* this may indirectly call ERR_clear_error() */
126 OPENSSL_free(rctx->readbuf);
127 OPENSSL_free(rctx->proxy);
128 OPENSSL_free(rctx->server);
129 OPENSSL_free(rctx->port);
130 OPENSSL_free(rctx->expected_ct);
131 OPENSSL_free(rctx);
132 }
133
134 BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(const OSSL_HTTP_REQ_CTX *rctx)
135 {
136 if (rctx == NULL) {
137 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
138 return NULL;
139 }
140 return rctx->mem;
141 }
142
143 size_t OSSL_HTTP_REQ_CTX_get_resp_len(const OSSL_HTTP_REQ_CTX *rctx)
144 {
145 if (rctx == NULL) {
146 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
147 return 0;
148 }
149 return rctx->resp_len;
150 }
151
152 void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx,
153 unsigned long len)
154 {
155 if (rctx == NULL) {
156 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
157 return;
158 }
159 rctx->max_resp_len = len != 0 ? (size_t)len : HTTP_DEFAULT_MAX_RESP_LEN;
160 }
161
162 /*
163 * Create request line using |rctx| and |path| (or "/" in case |path| is NULL).
164 * Server name (and port) must be given if and only if plain HTTP proxy is used.
165 */
166 int OSSL_HTTP_REQ_CTX_set_request_line(OSSL_HTTP_REQ_CTX *rctx, int method_POST,
167 const char *server, const char *port,
168 const char *path)
169 {
170 if (rctx == NULL) {
171 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
172 return 0;
173 }
174 BIO_free(rctx->mem);
175 if ((rctx->mem = BIO_new(BIO_s_mem())) == NULL)
176 return 0;
177
178 rctx->method_POST = method_POST != 0;
179 if (BIO_printf(rctx->mem, "%s ", rctx->method_POST ? "POST" : "GET") <= 0)
180 return 0;
181
182 if (server != NULL) { /* HTTP (but not HTTPS) proxy is used */
183 /*
184 * Section 5.1.2 of RFC 1945 states that the absoluteURI form is only
185 * allowed when using a proxy
186 */
187 if (BIO_printf(rctx->mem, OSSL_HTTP_PREFIX"%s", server) <= 0)
188 return 0;
189 if (port != NULL && BIO_printf(rctx->mem, ":%s", port) <= 0)
190 return 0;
191 }
192
193 /* Make sure path includes a forward slash */
194 if (path == NULL)
195 path = "/";
196 if (path[0] != '/' && BIO_printf(rctx->mem, "/") <= 0)
197 return 0;
198
199 if (BIO_printf(rctx->mem, "%s "HTTP_1_0"\r\n", path) <= 0)
200 return 0;
201 rctx->resp_len = 0;
202 rctx->state = OHS_HTTP_HEADER;
203 return 1;
204 }
205
206 int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx,
207 const char *name, const char *value)
208 {
209 if (rctx == NULL || name == NULL) {
210 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
211 return 0;
212 }
213 if (rctx->mem == NULL) {
214 ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
215 return 0;
216 }
217
218 if (BIO_puts(rctx->mem, name) <= 0)
219 return 0;
220 if (value != NULL) {
221 if (BIO_write(rctx->mem, ": ", 2) != 2)
222 return 0;
223 if (BIO_puts(rctx->mem, value) <= 0)
224 return 0;
225 }
226 return BIO_write(rctx->mem, "\r\n", 2) == 2;
227 }
228
229 int OSSL_HTTP_REQ_CTX_set_expected(OSSL_HTTP_REQ_CTX *rctx,
230 const char *content_type, int asn1,
231 int timeout, int keep_alive)
232 {
233 if (rctx == NULL) {
234 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
235 return 0;
236 }
237 if (keep_alive != 0
238 && rctx->state != OHS_ERROR && rctx->state != OHS_HTTP_HEADER) {
239 /* Cannot anymore set keep-alive in request header */
240 ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
241 return 0;
242 }
243
244 OPENSSL_free(rctx->expected_ct);
245 rctx->expected_ct = NULL;
246 if (content_type != NULL
247 && (rctx->expected_ct = OPENSSL_strdup(content_type)) == NULL)
248 return 0;
249
250 rctx->expect_asn1 = asn1;
251 if (timeout >= 0)
252 rctx->max_time = timeout > 0 ? time(NULL) + timeout : 0;
253 else
254 rctx->max_time = rctx->max_total_time;
255 rctx->keep_alive = keep_alive;
256 return 1;
257 }
258
259 static int ossl_http_req_ctx_set_content(OSSL_HTTP_REQ_CTX *rctx,
260 const char *content_type, BIO *req_mem)
261 {
262 const unsigned char *req;
263 long req_len;
264
265 if (rctx == NULL || (req_mem == NULL && content_type != NULL)) {
266 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
267 return 0;
268 }
269
270 if (rctx->keep_alive != 0
271 && !OSSL_HTTP_REQ_CTX_add1_header(rctx, "Connection", "keep-alive"))
272 return 0;
273 rctx->state = OHS_WRITE_INIT;
274
275 if (req_mem == NULL)
276 return 1;
277 if (!rctx->method_POST) {
278 ERR_raise(ERR_LIB_HTTP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
279 return 0;
280 }
281
282 if (content_type != NULL
283 && BIO_printf(rctx->mem, "Content-Type: %s\r\n", content_type) <= 0)
284 return 0;
285
286 if ((req_len = BIO_get_mem_data(req_mem, &req)) <= 0)
287 return 0;
288
289 return BIO_printf(rctx->mem, "Content-Length: %ld\r\n\r\n", req_len) > 0
290 && BIO_write(rctx->mem, req, req_len) == (int)req_len;
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_HTTP_HEADER:
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, NULL);
509 rctx->state = OHS_WRITE;
510
511 /* fall thru */
512 case OHS_WRITE:
513 n = BIO_get_mem_data(rctx->mem, &p) - rctx->len_to_send;
514 i = BIO_write(rctx->wbio, p + n, rctx->len_to_send);
515
516 if (i <= 0) {
517 if (BIO_should_retry(rctx->wbio))
518 return -1;
519 rctx->state = OHS_ERROR;
520 return 0;
521 }
522
523 rctx->len_to_send -= i;
524
525 if (rctx->len_to_send > 0)
526 goto next_io;
527
528 rctx->state = OHS_FLUSH;
529
530 (void)BIO_reset(rctx->mem);
531
532 /* fall thru */
533 case OHS_FLUSH:
534
535 i = BIO_flush(rctx->wbio);
536
537 if (i > 0) {
538 rctx->state = OHS_FIRSTLINE;
539 goto next_io;
540 }
541
542 if (BIO_should_retry(rctx->wbio))
543 return -1;
544
545 rctx->state = OHS_ERROR;
546 return 0;
547
548 case OHS_ERROR:
549 return 0;
550
551 case OHS_FIRSTLINE:
552 case OHS_HEADERS:
553 case OHS_REDIRECT:
554
555 /* Attempt to read a line in */
556 next_line:
557 /*
558 * Due to strange memory BIO behavior with BIO_gets we have to check
559 * there's a complete line in there before calling BIO_gets or we'll
560 * just get a partial read.
561 */
562 n = BIO_get_mem_data(rctx->mem, &p);
563 if (n <= 0 || memchr(p, '\n', n) == 0) {
564 if (n >= rctx->readbuflen) {
565 rctx->state = OHS_ERROR;
566 return 0;
567 }
568 goto next_io;
569 }
570 n = BIO_gets(rctx->mem, (char *)rctx->readbuf, rctx->readbuflen);
571
572 if (n <= 0) {
573 if (BIO_should_retry(rctx->mem))
574 goto next_io;
575 rctx->state = OHS_ERROR;
576 return 0;
577 }
578
579 /* Don't allow excessive lines */
580 if (n == rctx->readbuflen) {
581 ERR_raise(ERR_LIB_HTTP, HTTP_R_RESPONSE_LINE_TOO_LONG);
582 rctx->state = OHS_ERROR;
583 return 0;
584 }
585
586 /* First line */
587 if (rctx->state == OHS_FIRSTLINE) {
588 switch (parse_http_line1((char *)rctx->readbuf, &found_keep_alive)) {
589 case HTTP_STATUS_CODE_OK:
590 rctx->state = OHS_HEADERS;
591 goto next_line;
592 case HTTP_STATUS_CODE_MOVED_PERMANENTLY:
593 case HTTP_STATUS_CODE_FOUND: /* i.e., moved temporarily */
594 if (!rctx->method_POST) { /* method is GET */
595 rctx->state = OHS_REDIRECT;
596 goto next_line;
597 }
598 ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED);
599 /* redirection is not supported/recommended for POST */
600 /* fall through */
601 default:
602 rctx->state = OHS_ERROR;
603 return 0;
604 }
605 }
606 key = (char *)rctx->readbuf;
607 value = strchr(key, ':');
608 if (value != NULL) {
609 *(value++) = '\0';
610 while (ossl_isspace(*value))
611 value++;
612 line_end = strchr(value, '\r');
613 if (line_end == NULL)
614 line_end = strchr(value, '\n');
615 if (line_end != NULL)
616 *line_end = '\0';
617 }
618 if (value != NULL && line_end != NULL) {
619 if (rctx->state == OHS_REDIRECT
620 && strcasecmp(key, "Location") == 0) {
621 rctx->redirection_url = value;
622 return 0;
623 }
624 if (rctx->expected_ct != NULL
625 && strcasecmp(key, "Content-Type") == 0) {
626 if (strcasecmp(rctx->expected_ct, value) != 0) {
627 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_UNEXPECTED_CONTENT_TYPE,
628 "expected=%s, actual=%s",
629 rctx->expected_ct, value);
630 return 0;
631 }
632 found_expected_ct = 1;
633 }
634
635 /* https://tools.ietf.org/html/rfc7230#section-6.3 Persistence */
636 if (strcasecmp(key, "Connection") == 0) {
637 if (strcasecmp(value, "keep-alive") == 0)
638 found_keep_alive = 1;
639 else if (strcasecmp(value, "close") == 0)
640 found_keep_alive = 0;
641 }
642 if (strcasecmp(key, "Content-Length") == 0) {
643 resp_len = strtoul(value, &line_end, 10);
644 if (line_end == value || *line_end != '\0') {
645 ERR_raise_data(ERR_LIB_HTTP,
646 HTTP_R_ERROR_PARSING_CONTENT_LENGTH,
647 "input=%s", value);
648 return 0;
649 }
650 if (!check_set_resp_len(rctx, resp_len))
651 return 0;
652 }
653 }
654
655 /* Look for blank line indicating end of headers */
656 for (p = rctx->readbuf; *p != '\0'; p++) {
657 if (*p != '\r' && *p != '\n')
658 break;
659 }
660 if (*p != '\0') /* not end of headers */
661 goto next_line;
662
663 if (rctx->expected_ct != NULL && !found_expected_ct) {
664 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_MISSING_CONTENT_TYPE,
665 "expected=%s", rctx->expected_ct);
666 return 0;
667 }
668 if (rctx->keep_alive != 0 /* do not let server initiate keep_alive */
669 && !found_keep_alive /* otherwise there is no change */) {
670 if (rctx->keep_alive == 2) {
671 rctx->keep_alive = 0;
672 ERR_raise(ERR_LIB_HTTP, HTTP_R_SERVER_CANCELED_CONNECTION);
673 return 0;
674 }
675 rctx->keep_alive = 0;
676 }
677
678 if (rctx->state == OHS_REDIRECT) {
679 /* http status code indicated redirect but there was no Location */
680 ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_REDIRECT_LOCATION);
681 return 0;
682 }
683
684 if (!rctx->expect_asn1) {
685 rctx->state = OHS_CONTENT;
686 goto content;
687 }
688
689 rctx->state = OHS_ASN1_HEADER;
690
691 /* Fall thru */
692 case OHS_ASN1_HEADER:
693 /*
694 * Now reading ASN1 header: can read at least 2 bytes which is enough
695 * for ASN1 SEQUENCE header and either length field or at least the
696 * length of the length field.
697 */
698 n = BIO_get_mem_data(rctx->mem, &p);
699 if (n < 2)
700 goto next_io;
701
702 /* Check it is an ASN1 SEQUENCE */
703 if (*p++ != (V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)) {
704 ERR_raise(ERR_LIB_HTTP, HTTP_R_MISSING_ASN1_ENCODING);
705 return 0;
706 }
707
708 /* Check out length field */
709 if ((*p & 0x80) != 0) {
710 /*
711 * If MSB set on initial length octet we can now always read 6
712 * octets: make sure we have them.
713 */
714 if (n < 6)
715 goto next_io;
716 n = *p & 0x7F;
717 /* Not NDEF or excessive length */
718 if (n == 0 || (n > 4)) {
719 ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_ASN1_LENGTH);
720 return 0;
721 }
722 p++;
723 resp_len = 0;
724 for (i = 0; i < n; i++) {
725 resp_len <<= 8;
726 resp_len |= *p++;
727 }
728 resp_len += n + 2;
729 } else {
730 resp_len = *p + 2;
731 }
732 if (!check_set_resp_len(rctx, resp_len))
733 return 0;
734
735 content:
736 rctx->state = OHS_CONTENT;
737
738 /* Fall thru */
739 case OHS_CONTENT:
740 default:
741 n = BIO_get_mem_data(rctx->mem, NULL);
742 if (n < (long)rctx->resp_len /* may be 0 if no Content-Length or ASN.1 */)
743 goto next_io;
744
745 rctx->state = OHS_DONE;
746 return 1;
747 }
748 }
749
750 int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX *rctx,
751 ASN1_VALUE **pval, const ASN1_ITEM *it)
752 {
753 const unsigned char *p;
754 int rv;
755
756 *pval = NULL;
757 if ((rv = OSSL_HTTP_REQ_CTX_nbio(rctx)) != 1)
758 return rv;
759 *pval = ASN1_item_d2i(NULL, &p, BIO_get_mem_data(rctx->mem, &p), it);
760 return *pval != NULL;
761
762 }
763
764 #ifndef OPENSSL_NO_SOCK
765
766 /* set up a new connection BIO, to HTTP server or to HTTP(S) proxy if given */
767 static BIO *HTTP_new_bio(const char *server /* optionally includes ":port" */,
768 const char *server_port /* explicit server port */,
769 int use_ssl,
770 const char *proxy /* optionally includes ":port" */,
771 const char *proxy_port /* explicit proxy port */)
772 {
773 const char *host = server;
774 const char *port = server_port;
775 BIO *cbio;
776
777 if (!ossl_assert(server != NULL))
778 return NULL;
779
780 if (proxy != NULL) {
781 host = proxy;
782 port = proxy_port;
783 }
784
785 if (port == NULL && strchr(host, ':') == NULL)
786 port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
787
788 cbio = BIO_new_connect(host /* optionally includes ":port" */);
789 if (cbio == NULL)
790 goto end;
791 if (port != NULL)
792 (void)BIO_set_conn_port(cbio, port);
793
794 end:
795 return cbio;
796 }
797 #endif /* OPENSSL_NO_SOCK */
798
799 /* Exchange request and response via HTTP on (non-)blocking BIO */
800 BIO *OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX *rctx)
801 {
802 int rv;
803
804 if (rctx == NULL) {
805 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
806 return NULL;
807 }
808
809 for (;;) {
810 rv = OSSL_HTTP_REQ_CTX_nbio(rctx);
811 if (rv != -1)
812 break;
813 /* BIO_should_retry was true */
814 /* will not actually wait if rctx->max_time == 0 */
815 if (BIO_wait(rctx->rbio, rctx->max_time, 100 /* milliseconds */) <= 0)
816 return NULL;
817 }
818
819 if (rv == 0) {
820 if (rctx->redirection_url == NULL) { /* an error occurred */
821 if (rctx->len_to_send > 0)
822 ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_SENDING);
823 else
824 ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_RECEIVING);
825 }
826 return NULL;
827 }
828 return rctx->mem;
829 }
830
831 int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX *rctx)
832 {
833 return rctx != NULL && rctx->keep_alive != 0;
834 }
835
836 /* High-level HTTP API implementation */
837
838 /* Initiate an HTTP session using bio, else use given server, proxy, etc. */
839 OSSL_HTTP_REQ_CTX *OSSL_HTTP_open(const char *server, const char *port,
840 const char *proxy, const char *no_proxy,
841 int use_ssl, BIO *bio, BIO *rbio,
842 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
843 int buf_size, unsigned long max_resp_len,
844 int overall_timeout)
845 {
846 BIO *cbio; /* == bio if supplied, used as connection BIO if rbio is NULL */
847 OSSL_HTTP_REQ_CTX *rctx = NULL;
848
849 if (use_ssl && bio_update_fn == NULL) {
850 ERR_raise(ERR_LIB_HTTP, HTTP_R_TLS_NOT_ENABLED);
851 return NULL;
852 }
853 if (rbio != NULL && (bio == NULL || bio_update_fn != NULL)) {
854 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
855 return NULL;
856 }
857
858 if (bio != NULL) {
859 cbio = bio;
860 if (proxy != NULL || no_proxy != NULL) {
861 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
862 return NULL;
863 }
864 } else {
865 #ifndef OPENSSL_NO_SOCK
866 char *proxy_host = NULL, *proxy_port = NULL;
867
868 if (server == NULL) {
869 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
870 return NULL;
871 }
872 if (port != NULL && *port == '\0')
873 port = NULL;
874 if (port == NULL && strchr(server, ':') == NULL)
875 port = use_ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT;
876 proxy = ossl_http_adapt_proxy(proxy, no_proxy, server, use_ssl);
877 if (proxy != NULL
878 && !OSSL_HTTP_parse_url(proxy, NULL /* use_ssl */, NULL /* user */,
879 &proxy_host, &proxy_port, NULL /* num */,
880 NULL /* path */, NULL, NULL))
881 return NULL;
882 cbio = HTTP_new_bio(server, port, use_ssl, proxy_host, proxy_port);
883 OPENSSL_free(proxy_host);
884 OPENSSL_free(proxy_port);
885 if (cbio == NULL)
886 return NULL;
887 #else
888 ERR_raise(ERR_LIB_HTTP, HTTP_R_SOCK_NOT_SUPPORTED);
889 return NULL;
890 #endif
891 }
892
893 (void)ERR_set_mark(); /* prepare removing any spurious libssl errors */
894 if (rbio == NULL && BIO_do_connect_retry(cbio, overall_timeout, -1) <= 0) {
895 if (bio == NULL) /* cbio was not provided by caller */
896 BIO_free_all(cbio);
897 goto end;
898 }
899 /* now overall_timeout is guaranteed to be >= 0 */
900
901 /* callback can be used to wrap or prepend TLS session */
902 if (bio_update_fn != NULL) {
903 BIO *orig_bio = cbio;
904
905 cbio = (*bio_update_fn)(cbio, arg, 1 /* connect */, use_ssl);
906 if (cbio == NULL) {
907 cbio = orig_bio;
908 goto end;
909 }
910 }
911
912 rctx = http_req_ctx_new(bio == NULL, cbio, rbio != NULL ? rbio : cbio,
913 bio_update_fn, arg, use_ssl, proxy, server, port,
914 buf_size, max_resp_len, overall_timeout);
915
916 end:
917 if (rctx != NULL)
918 /* remove any spurious error queue entries by ssl_add_cert_chain() */
919 (void)ERR_pop_to_mark();
920 else
921 (void)ERR_clear_last_mark();
922
923 return rctx;
924 }
925
926 int OSSL_HTTP_set_request(OSSL_HTTP_REQ_CTX *rctx, const char *path,
927 const STACK_OF(CONF_VALUE) *headers,
928 const char *content_type, BIO *req_mem,
929 const char *expected_content_type, int expect_asn1,
930 int timeout, int keep_alive)
931 {
932 int use_http_proxy;
933
934 if (rctx == NULL) {
935 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
936 return 0;
937 }
938 use_http_proxy = rctx->proxy != NULL && !rctx->use_ssl;
939 if (use_http_proxy && (rctx->server == NULL || rctx->port == NULL)) {
940 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT);
941 return 0;
942 }
943
944 return OSSL_HTTP_REQ_CTX_set_request_line(rctx, req_mem != NULL,
945 use_http_proxy ? rctx->server
946 : NULL, rctx->port, path)
947 && OSSL_HTTP_REQ_CTX_add1_headers(rctx, headers, rctx->server)
948 && OSSL_HTTP_REQ_CTX_set_expected(rctx, expected_content_type,
949 expect_asn1, timeout, keep_alive)
950 && ossl_http_req_ctx_set_content(rctx, content_type, req_mem);
951 }
952
953 /*-
954 * Exchange single HTTP request and response according to rctx.
955 * If rctx->method_POST then use POST, else use GET and ignore content_type.
956 * The redirection_url output (freed by caller) parameter is used only for GET.
957 */
958 BIO *OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX *rctx, char **redirection_url)
959 {
960 BIO *resp;
961
962 if (rctx == NULL) {
963 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
964 return NULL;
965 }
966
967 if (redirection_url != NULL)
968 *redirection_url = NULL; /* do this beforehand to prevent dbl free */
969
970 resp = OSSL_HTTP_REQ_CTX_exchange(rctx);
971 if (resp == NULL) {
972 if (rctx->redirection_url != NULL) {
973 if (redirection_url == NULL)
974 ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_NOT_ENABLED);
975 else
976 /* may be NULL if out of memory: */
977 *redirection_url = OPENSSL_strdup(rctx->redirection_url);
978 } else {
979 char buf[200];
980 unsigned long err = ERR_peek_error();
981 int lib = ERR_GET_LIB(err);
982 int reason = ERR_GET_REASON(err);
983
984 if (lib == ERR_LIB_SSL || lib == ERR_LIB_HTTP
985 || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_TIMEOUT)
986 || (lib == ERR_LIB_BIO && reason == BIO_R_CONNECT_ERROR)
987 #ifndef OPENSSL_NO_CMP
988 || (lib == ERR_LIB_CMP
989 && reason == CMP_R_POTENTIALLY_INVALID_CERTIFICATE)
990 #endif
991 ) {
992 if (rctx->server != NULL) {
993 BIO_snprintf(buf, sizeof(buf), "server=http%s://%s%s%s",
994 rctx->use_ssl ? "s" : "", rctx->server,
995 rctx->port != NULL ? ":" : "",
996 rctx->port != NULL ? rctx->port : "");
997 ERR_add_error_data(1, buf);
998 }
999 if (rctx->proxy != NULL)
1000 ERR_add_error_data(2, " proxy=", rctx->proxy);
1001 if (err == 0) {
1002 BIO_snprintf(buf, sizeof(buf), " peer has disconnected%s",
1003 rctx->use_ssl ? " violating the protocol" :
1004 ", likely because it requires the use of TLS");
1005 ERR_add_error_data(1, buf);
1006 }
1007 }
1008 }
1009 }
1010
1011 if (resp != NULL && !BIO_up_ref(resp))
1012 resp = NULL;
1013 return resp;
1014 }
1015
1016 static int redirection_ok(int n_redir, const char *old_url, const char *new_url)
1017 {
1018 size_t https_len = strlen(OSSL_HTTPS_NAME":");
1019
1020 if (n_redir >= HTTP_VERSION_MAX_REDIRECTIONS) {
1021 ERR_raise(ERR_LIB_HTTP, HTTP_R_TOO_MANY_REDIRECTIONS);
1022 return 0;
1023 }
1024 if (*new_url == '/') /* redirection to same server => same protocol */
1025 return 1;
1026 if (strncmp(old_url, OSSL_HTTPS_NAME":", https_len) == 0 &&
1027 strncmp(new_url, OSSL_HTTPS_NAME":", https_len) != 0) {
1028 ERR_raise(ERR_LIB_HTTP, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP);
1029 return 0;
1030 }
1031 return 1;
1032 }
1033
1034 /* Get data via HTTP from server at given URL, potentially with redirection */
1035 BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy,
1036 BIO *bio, BIO *rbio,
1037 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
1038 int buf_size, const STACK_OF(CONF_VALUE) *headers,
1039 const char *expected_ct, int expect_asn1,
1040 size_t max_resp_len, int timeout)
1041 {
1042 char *current_url, *redirection_url = NULL;
1043 int n_redirs = 0;
1044 char *host;
1045 char *port;
1046 char *path;
1047 int use_ssl;
1048 OSSL_HTTP_REQ_CTX *rctx;
1049 BIO *resp = NULL;
1050
1051 if (url == NULL) {
1052 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
1053 return NULL;
1054 }
1055 if ((current_url = OPENSSL_strdup(url)) == NULL)
1056 return NULL;
1057
1058 for (;;) {
1059 if (!OSSL_HTTP_parse_url(current_url, &use_ssl, NULL /* user */, &host,
1060 &port, NULL /* port_num */, &path, NULL, NULL))
1061 break;
1062
1063 rctx = OSSL_HTTP_open(host, port, proxy, no_proxy,
1064 use_ssl, bio, rbio, bio_update_fn, arg,
1065 buf_size, max_resp_len, timeout);
1066 new_rpath:
1067 if (rctx != NULL) {
1068 if (!OSSL_HTTP_set_request(rctx, path, headers,
1069 NULL /* content_type */,
1070 NULL /* req_mem */,
1071 expected_ct, expect_asn1,
1072 -1 /* use same max time (timeout) */,
1073 0 /* no keep_alive */))
1074 OSSL_HTTP_REQ_CTX_free(rctx);
1075 else
1076 resp = OSSL_HTTP_exchange(rctx, &redirection_url);
1077 }
1078 OPENSSL_free(path);
1079 if (resp == NULL && redirection_url != NULL) {
1080 if (redirection_ok(++n_redirs, current_url, redirection_url)) {
1081 (void)BIO_reset(bio);
1082 OPENSSL_free(current_url);
1083 current_url = redirection_url;
1084 if (*redirection_url == '/') { /* redirection to same server */
1085 path = OPENSSL_strdup(redirection_url);
1086 goto new_rpath;
1087 }
1088 OPENSSL_free(host);
1089 OPENSSL_free(port);
1090 (void)OSSL_HTTP_close(rctx, 1);
1091 continue;
1092 }
1093 /* if redirection not allowed, ignore it */
1094 OPENSSL_free(redirection_url);
1095 }
1096 OPENSSL_free(host);
1097 OPENSSL_free(port);
1098 if (!OSSL_HTTP_close(rctx, resp != NULL)) {
1099 BIO_free(resp);
1100 resp = NULL;
1101 }
1102 break;
1103 }
1104 OPENSSL_free(current_url);
1105 return resp;
1106 }
1107
1108 /* Exchange request and response over a connection managed via |prctx| */
1109 BIO *OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX **prctx,
1110 const char *server, const char *port,
1111 const char *path, int use_ssl,
1112 const char *proxy, const char *no_proxy,
1113 BIO *bio, BIO *rbio,
1114 OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
1115 int buf_size, const STACK_OF(CONF_VALUE) *headers,
1116 const char *content_type, BIO *req,
1117 const char *expected_ct, int expect_asn1,
1118 unsigned long max_resp_len, int timeout, int keep_alive)
1119 {
1120 OSSL_HTTP_REQ_CTX *rctx = prctx == NULL ? NULL : *prctx;
1121 BIO *resp = NULL;
1122
1123 if (rctx == NULL) {
1124 rctx = OSSL_HTTP_open(server, port, proxy, no_proxy,
1125 use_ssl, bio, rbio, bio_update_fn, arg,
1126 buf_size, max_resp_len, timeout);
1127 timeout = -1; /* Already set during opening the connection */
1128 }
1129 if (rctx != NULL) {
1130 if (OSSL_HTTP_set_request(rctx, path, headers, content_type, req,
1131 expected_ct, expect_asn1,
1132 timeout, keep_alive))
1133 resp = OSSL_HTTP_exchange(rctx, NULL);
1134 if (resp == NULL || !OSSL_HTTP_is_alive(rctx)) {
1135 if (!OSSL_HTTP_close(rctx, resp != NULL)) {
1136 BIO_free(resp);
1137 resp = NULL;
1138 }
1139 rctx = NULL;
1140 }
1141 }
1142 if (prctx != NULL)
1143 *prctx = rctx;
1144 return resp;
1145 }
1146
1147 int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX *rctx, int ok)
1148 {
1149 int ret = 1;
1150
1151 /* callback can be used to clean up TLS session on disconnect */
1152 if (rctx != NULL && rctx->upd_fn != NULL)
1153 ret = (*rctx->upd_fn)(rctx->wbio, rctx->upd_arg, 0, ok) != NULL;
1154 OSSL_HTTP_REQ_CTX_free(rctx);
1155 return ret;
1156 }
1157
1158 /* BASE64 encoder used for encoding basic proxy authentication credentials */
1159 static char *base64encode(const void *buf, size_t len)
1160 {
1161 int i;
1162 size_t outl;
1163 char *out;
1164
1165 /* Calculate size of encoded data */
1166 outl = (len / 3);
1167 if (len % 3 > 0)
1168 outl++;
1169 outl <<= 2;
1170 out = OPENSSL_malloc(outl + 1);
1171 if (out == NULL)
1172 return 0;
1173
1174 i = EVP_EncodeBlock((unsigned char *)out, buf, len);
1175 if (!ossl_assert(0 <= i && (size_t)i <= outl)) {
1176 OPENSSL_free(out);
1177 return NULL;
1178 }
1179 return out;
1180 }
1181
1182 /*
1183 * Promote the given connection BIO using the CONNECT method for a TLS proxy.
1184 * This is typically called by an app, so bio_err and prog are used unless NULL
1185 * to print additional diagnostic information in a user-oriented way.
1186 */
1187 int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port,
1188 const char *proxyuser, const char *proxypass,
1189 int timeout, BIO *bio_err, const char *prog)
1190 {
1191 #undef BUF_SIZE
1192 #define BUF_SIZE (8 * 1024)
1193 char *mbuf = OPENSSL_malloc(BUF_SIZE);
1194 char *mbufp;
1195 int read_len = 0;
1196 int ret = 0;
1197 BIO *fbio = BIO_new(BIO_f_buffer());
1198 int rv;
1199 time_t max_time = timeout > 0 ? time(NULL) + timeout : 0;
1200
1201 if (bio == NULL || server == NULL
1202 || (bio_err != NULL && prog == NULL)) {
1203 ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER);
1204 goto end;
1205 }
1206 if (port == NULL || *port == '\0')
1207 port = OSSL_HTTPS_PORT;
1208
1209 if (mbuf == NULL || fbio == NULL) {
1210 BIO_printf(bio_err /* may be NULL */, "%s: out of memory", prog);
1211 goto end;
1212 }
1213 BIO_push(fbio, bio);
1214
1215 BIO_printf(fbio, "CONNECT %s:%s "HTTP_1_0"\r\n", server, port);
1216
1217 /*
1218 * Workaround for broken proxies which would otherwise close
1219 * the connection when entering tunnel mode (e.g., Squid 2.6)
1220 */
1221 BIO_printf(fbio, "Proxy-Connection: Keep-Alive\r\n");
1222
1223 /* Support for basic (base64) proxy authentication */
1224 if (proxyuser != NULL) {
1225 size_t len = strlen(proxyuser) + 1;
1226 char *proxyauth, *proxyauthenc = NULL;
1227
1228 if (proxypass != NULL)
1229 len += strlen(proxypass);
1230 proxyauth = OPENSSL_malloc(len + 1);
1231 if (proxyauth == NULL)
1232 goto end;
1233 if (BIO_snprintf(proxyauth, len + 1, "%s:%s", proxyuser,
1234 proxypass != NULL ? proxypass : "") != (int)len)
1235 goto proxy_end;
1236 proxyauthenc = base64encode(proxyauth, len);
1237 if (proxyauthenc != NULL) {
1238 BIO_printf(fbio, "Proxy-Authorization: Basic %s\r\n", proxyauthenc);
1239 OPENSSL_clear_free(proxyauthenc, strlen(proxyauthenc));
1240 }
1241 proxy_end:
1242 OPENSSL_clear_free(proxyauth, len);
1243 if (proxyauthenc == NULL)
1244 goto end;
1245 }
1246
1247 /* Terminate the HTTP CONNECT request */
1248 BIO_printf(fbio, "\r\n");
1249
1250 for (;;) {
1251 if (BIO_flush(fbio) != 0)
1252 break;
1253 /* potentially needs to be retried if BIO is non-blocking */
1254 if (!BIO_should_retry(fbio))
1255 break;
1256 }
1257
1258 for (;;) {
1259 /* will not actually wait if timeout == 0 */
1260 rv = BIO_wait(fbio, max_time, 100 /* milliseconds */);
1261 if (rv <= 0) {
1262 BIO_printf(bio_err, "%s: HTTP CONNECT %s\n", prog,
1263 rv == 0 ? "timed out" : "failed waiting for data");
1264 goto end;
1265 }
1266
1267 /*-
1268 * The first line is the HTTP response.
1269 * According to RFC 7230, it is formatted exactly like this:
1270 * HTTP/d.d ddd Reason text\r\n
1271 */
1272 read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1273 /* the BIO may not block, so we must wait for the 1st line to come in */
1274 if (read_len < HTTP_LINE1_MINLEN)
1275 continue;
1276
1277 /* Check for HTTP/1.x */
1278 if (strncmp(mbuf, HTTP_PREFIX, strlen(HTTP_PREFIX)) != 0) {
1279 ERR_raise(ERR_LIB_HTTP, HTTP_R_HEADER_PARSE_ERROR);
1280 BIO_printf(bio_err, "%s: HTTP CONNECT failed, non-HTTP response\n",
1281 prog);
1282 /* Wrong protocol, not even HTTP, so stop reading headers */
1283 goto end;
1284 }
1285 mbufp = mbuf + strlen(HTTP_PREFIX);
1286 if (strncmp(mbufp, HTTP_VERSION_PATT, HTTP_VERSION_PATT_LEN) != 0) {
1287 ERR_raise(ERR_LIB_HTTP, HTTP_R_RECEIVED_WRONG_HTTP_VERSION);
1288 BIO_printf(bio_err,
1289 "%s: HTTP CONNECT failed, bad HTTP version %.*s\n",
1290 prog, (int)HTTP_VERSION_STR_LEN, mbufp);
1291 goto end;
1292 }
1293 mbufp += HTTP_VERSION_STR_LEN;
1294
1295 /* RFC 7231 4.3.6: any 2xx status code is valid */
1296 if (strncmp(mbufp, " 2", strlen(" 2")) != 0) {
1297 mbufp += 1;
1298 /* chop any trailing whitespace */
1299 while (read_len > 0 && ossl_isspace(mbuf[read_len - 1]))
1300 read_len--;
1301 mbuf[read_len] = '\0';
1302 ERR_raise_data(ERR_LIB_HTTP, HTTP_R_CONNECT_FAILURE,
1303 "Reason=%s", mbufp);
1304 BIO_printf(bio_err, "%s: HTTP CONNECT failed, Reason=%s\n",
1305 prog, mbufp);
1306 goto end;
1307 }
1308 ret = 1;
1309 break;
1310 }
1311
1312 /* Read past all following headers */
1313 do {
1314 /*
1315 * TODO: This does not necessarily catch the case when the full
1316 * HTTP response came in in more than a single TCP message.
1317 */
1318 read_len = BIO_gets(fbio, mbuf, BUF_SIZE);
1319 } while (read_len > 2);
1320
1321 end:
1322 if (fbio != NULL) {
1323 (void)BIO_flush(fbio);
1324 BIO_pop(fbio);
1325 BIO_free(fbio);
1326 }
1327 OPENSSL_free(mbuf);
1328 return ret;
1329 #undef BUF_SIZE
1330 }