Coverage Report

Created: 2026-05-24 07:14

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