Coverage Report

Created: 2026-05-20 07:05

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