Coverage Report

Created: 2025-12-31 06:58

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