Coverage Report

Created: 2026-05-24 07:14

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