summary refs log tree commit diff
path: root/misc/http_client.c
blob: 1b0d5641e01b30bab1d706b99bd406509e64a4e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

#include "iobuf.h"
#include "subr.h"
#include "http_client.h"

struct http_url *
http_url_parse(const char *url)
{
    size_t ulen = strlen(url);
    if (strncmp(url, "http://", 7) != 0)
        return NULL;
    const char *cur, *at, *uri = NULL, *uri_e = NULL;
    const char *host = NULL, *host_e = NULL;
    const char *port = NULL, *port_e = NULL;
    at = strchr(url + 7, '@');
    uri = strchr(url + 7, '/');
    cur = strchr(url + 7, '?');
    if (cur != NULL && (uri == NULL || cur < uri))
        uri = cur;
    if (uri == NULL)
        uri = url + ulen;
    if (at != NULL && at < uri)
        host = at + 1;
    else
        host = url + 7;
    cur = host;
    while (cur < uri && *cur != ':')
        cur++;
    host_e = cur;
    if (host_e == host)
        return NULL;
    if (*cur == ':') {
        cur++;
        port = cur;
        while (cur < uri && *cur >= '0' && *cur <= '9')
            cur++;
        if (cur == port || cur != uri)
            return NULL;
        port_e = cur;
    }
    while (*cur != '\0')
        cur++;
    uri_e = cur;
    struct http_url *res =
        malloc(sizeof(*res) + host_e - host + 1 + uri_e - uri + 2);
    if (res == NULL)
        return NULL;
    if (port != NULL)
        sscanf(port, "%hu", &res->port);
    else
        res->port = 80;
    res->host = (char *)(res + 1);
    res->uri = res->host + (host_e - host + 1);
    bcopy(host, res->host, host_e - host);
    res->host[host_e - host] = '\0';
    if (*uri != '/') {
        res->uri[0] = '/';
        bcopy(uri, res->uri + 1, uri_e - uri);
        res->uri[uri_e - uri + 1] = '\0';
    } else {
        bcopy(uri, res->uri, uri_e - uri);
        res->uri[uri_e - uri] = '\0';
    }
    return res;
}

void
http_url_free(struct http_url *url)
{
    free(url);
}

struct http_req {
    enum {
        PS_HEAD, PS_CHUNK_SIZE, PS_CHUNK_DATA, PS_CHUNK_CRLF, PS_ID_DATA
    } pstate;

    int parsing;
    int cancel;
    int chunked;
    long length;

    http_cb_t cb;
    void *arg;

    struct http_url *url;
    struct iobuf rbuf;
    struct iobuf wbuf;
};

static void
http_free(struct http_req *req)
{
    if (req->url != NULL)
        http_url_free(req->url);
    iobuf_free(&req->rbuf);
    iobuf_free(&req->wbuf);
    free(req);
}

static void
http_error(struct http_req *req)
{
    struct http_response res;
    res.type = HTTP_T_ERR;
    res.v.error = 1;
    req->cb(req, &res, req->arg);
    http_free(req);
}

static char *
strnl(char *str, int *nlsize)
{
    char *nl = strchr(str, '\n');
    if (nl != NULL && nl > str && *(nl - 1) == '\r') {
        *nlsize = 2;
        return nl - 1;
    } else {
        *nlsize = 1;
        return nl;
    }
}

static int
headers_parse(struct http_req *req, char *buf, char *end)
{
    int code, majv, minv, nlsize;
    char *cur, *nl;
    char name[128], value[872];
    struct http_response res;

    req->chunked = 0;
    req->length = -1;

    if (sscanf(buf, "HTTP/%d.%d %d", &majv, &minv, &code) != 3)
        return 0;
    res.type = HTTP_T_CODE;
    res.v.code = code;
    req->cb(req, &res, req->arg);
    if (req->cancel)
        return 1;

    cur = strchr(buf, '\n') + 1;
    nl = strnl(cur, &nlsize);
    while (cur < end) {
        int i;
        char *colon = strchr(cur, ':');
        if (colon == NULL || colon > nl)
            return 0;
        snprintf(name, sizeof(name), "%.*s", (int)(colon - cur), cur);

        cur = colon + 1;
        i = 0;
    val_loop:
        while (isblank(*cur))
            cur++;
        while (cur < nl) {
            if (i < sizeof(value) - 1) {
                value[i] = *cur;
                i++;
            }
            cur++;
        }
        cur += nlsize;
        nl = strnl(cur, &nlsize);
        if (isblank(*cur)) {
            if (i < sizeof(value) - 1) {
                value[i] = ' ';
                i++;
            }
            cur++;
            goto val_loop;
        }
        value[i] = '\0';
        for (i--; i >= 0 && isblank(value[i]); i--)
            value[i] = '\0';

        res.type = HTTP_T_HEADER;
        res.v.header.n = name;
        res.v.header.v = value;
        req->cb(req, &res, req->arg);
        if (req->cancel)
            return 1;
        if ((!req->chunked
                && strcasecmp("Transfer-Encoding", name) == 0
                && strcasecmp("chunked", value) == 0))
            req->chunked = 1;
        if ((!req->chunked && req->length == -1
                && strcasecmp("Content-Length", name) == 0)) {
            errno = 0;
            req->length = strtol(value, NULL, 10);
            if (errno)
                req->length = -1;
        }
    }
    if (req->chunked)
        req->pstate = PS_CHUNK_SIZE;
    else
        req->pstate = PS_ID_DATA;
    return 1;
}

static int
http_parse(struct http_req *req, int len)
{
    char *end, *numend;
    size_t dlen;
    struct http_response res;
again:
    switch (req->pstate) {
    case PS_HEAD:
        if (len == 0)
            goto error;
        if ((end = iobuf_find(&req->rbuf, "\r\n\r\n", 4)) != NULL)
            dlen = 4;
        else if ((end = iobuf_find(&req->rbuf, "\n\n", 2)) != NULL)
            dlen = 2;
        else {
            if (req->rbuf.off < (1 << 15))
                return 1;
            else
                goto error;
        }
        if (!iobuf_write(&req->rbuf, "", 1))
            goto error;
        req->rbuf.off--;
        if (!headers_parse(req, req->rbuf.buf, end))
            goto error;
        if (req->cancel)
            goto cancel;
        iobuf_consumed(&req->rbuf, end - (char *)req->rbuf.buf + dlen);
        goto again;
    case PS_CHUNK_SIZE:
        assert(req->chunked);
        if (len == 0)
            goto error;
        if ((end = iobuf_find(&req->rbuf, "\n", 1)) == NULL) {
            if (req->rbuf.off < 20)
                return 1;
            else
                goto error;
        }
        errno = 0;
        req->length = strtol(req->rbuf.buf, &numend, 16);
        if (req->length < 0 || numend == (char *)req->rbuf.buf || errno)
            goto error;
        if (req->length == 0)
            goto done;
        iobuf_consumed(&req->rbuf, end - (char *)req->rbuf.buf + 1);
        req->pstate = PS_CHUNK_DATA;
        goto again;
    case PS_CHUNK_DATA:
        if (len == 0)
            goto error;
        assert(req->length > 0);
        dlen = min(req->rbuf.off, req->length);
        if (dlen > 0) {
            res.type = HTTP_T_DATA;
            res.v.data.l = dlen;
            res.v.data.p = req->rbuf.buf;
            req->cb(req, &res, req->arg);
            if (req->cancel)
                goto cancel;
            iobuf_consumed(&req->rbuf, dlen);
            req->length -= dlen;
            if (req->length == 0) {
                req->pstate = PS_CHUNK_CRLF;
                goto again;
            }
        }
        return 1;
    case PS_CHUNK_CRLF:
        if (len == 0)
            goto error;
        assert(req->length == 0);
        if (req->rbuf.off < 2)
            return 1;
        if (req->rbuf.buf[0] == '\r' && req->rbuf.buf[1] == '\n')
            dlen = 2;
        else if (req->rbuf.buf[0] == '\n')
            dlen = 1;
        else
            goto error;
        iobuf_consumed(&req->rbuf, dlen);
        req->pstate = PS_CHUNK_SIZE;
        goto again;
    case PS_ID_DATA:
        if (len == 0 && req->length < 0)
            goto done;
        else if (len == 0)
            goto error;
        if (req->length < 0)
            dlen = req->rbuf.off;
        else
            dlen = min(req->rbuf.off, req->length);
        if (dlen > 0) {
            res.type = HTTP_T_DATA;
            res.v.data.p = req->rbuf.buf;
            res.v.data.l = dlen;
            req->cb(req, &res, req->arg);
            if (req->cancel)
                goto cancel;
            iobuf_consumed(&req->rbuf, dlen);
            if (req->length > 0) {
                req->length -= dlen;
                if (req->length == 0)
                    goto done;
            }
        }
        return 1;
    default:
        abort();
    }
error:
    http_error(req);
    return 0;
done:
    res.type = HTTP_T_DONE;
    req->cb(req, &res, req->arg);
cancel:
    http_free(req);
    return 0;
}

struct http_url *
http_url_get(struct http_req *req)
{
    return req->url;
}

int
http_want_read(struct http_req *req)
{
    return 1;
}

int
http_want_write(struct http_req *req)
{
    return req->wbuf.off > 0;
}

int
http_read(struct http_req *req, int sd)
{
    if (!iobuf_accommodate(&req->rbuf, 4096)) {
        http_error(req);
        return 0;
    }
    ssize_t nr = read(sd, req->rbuf.buf + req->rbuf.off, 4096);
    if (nr < 0 && errno == EAGAIN)
        return 1;
    else if (nr < 0) {
        http_error(req);
        return 0;
    } else {
        req->rbuf.off += nr;
        req->parsing = 1;
        if (http_parse(req, nr)) {
            req->parsing = 0;
            return 1;
        } else
            return 0;
    }
}

int
http_write(struct http_req *req, int sd)
{
    assert(req->wbuf.off > 0);
    ssize_t nw =
        write(sd, req->wbuf.buf, req->wbuf.off);
    if (nw < 0 && errno == EAGAIN)
        return 1;
    else if (nw < 0) {
        http_error(req);
        return 0;
    } else {
        iobuf_consumed(&req->wbuf, nw);
        return 1;
    }
}

int
http_get(struct http_req **out, const char *url, const char *hdrs,
    http_cb_t cb, void *arg)
{
    struct http_req *req = calloc(1, sizeof(*req));
    if (req == NULL)
        return 0;
    req->cb = cb;
    req->arg = arg;
    req->url = http_url_parse(url);
    if (req->url == NULL)
        goto error;
    req->rbuf = iobuf_init(4096);
    req->wbuf = iobuf_init(1024);
    if (!iobuf_print(&req->wbuf, "GET %s HTTP/1.1\r\n"
            "Host: %s:%hu\r\n"
            "Accept-Encoding:\r\n"
            "Connection: close\r\n"
            "%s"
            "\r\n", req->url->uri, req->url->host, req->url->port, hdrs))
        goto error;
    if (out != NULL)
        *out = req;
    return 1;
error:
    http_free(req);
    return 0;
}

void
http_cancel(struct http_req *req)
{
    if (req->parsing)
        req->cancel = 1;
    else
        http_free(req);
}