Coverage Report

Created: 2025-06-13 06:58

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