Statistics
| Branch: | Revision:

ffmpeg / libavformat / http.c @ f2b9b19f

History | View | Annotate | Download (14.6 KB)

1 558b86a5 Luca Barbato
/*
2
 * HTTP protocol for ffmpeg client
3 406792e7 Diego Biurrun
 * Copyright (c) 2000, 2001 Fabrice Bellard
4 558b86a5 Luca Barbato
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21 245976da Diego Biurrun
22
#include "libavutil/avstring.h"
23 558b86a5 Luca Barbato
#include "avformat.h"
24
#include <unistd.h>
25 7995ed8e Peter Holik
#include <strings.h>
26 e4a9e3cc Aurelien Jacobs
#include "internal.h"
27 558b86a5 Luca Barbato
#include "network.h"
28 6964d510 Josh Allmann
#include "http.h"
29 a5e979f4 Ramiro Polla
#include "os_support.h"
30 9405f733 Martin Storsjö
#include "httpauth.h"
31 558b86a5 Luca Barbato
32 e42dba48 Diego Biurrun
/* XXX: POST protocol is not completely implemented because ffmpeg uses
33
   only a subset of it. */
34 558b86a5 Luca Barbato
35
/* used for protocol handling */
36
#define BUFFER_SIZE 1024
37
#define URL_SIZE    4096
38
#define MAX_REDIRECTS 8
39
40
typedef struct {
41
    URLContext *hd;
42
    unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
43
    int line_count;
44
    int http_code;
45 7995ed8e Peter Holik
    int64_t chunksize;      /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
46 bc5c918e Diego Biurrun
    int64_t off, filesize;
47 558b86a5 Luca Barbato
    char location[URL_SIZE];
48 9405f733 Martin Storsjö
    HTTPAuthState auth_state;
49 0f3254b8 Josh Allmann
    int init;
50 6964d510 Josh Allmann
    unsigned char headers[BUFFER_SIZE];
51 f2b9b19f Josh Allmann
    int is_chunked;
52 558b86a5 Luca Barbato
} HTTPContext;
53
54
static int http_connect(URLContext *h, const char *path, const char *hoststr,
55
                        const char *auth, int *new_location);
56 27241cbf Martin Storsjö
static int http_write(URLContext *h, const uint8_t *buf, int size);
57 558b86a5 Luca Barbato
58 6964d510 Josh Allmann
void ff_http_set_headers(URLContext *h, const char *headers)
59
{
60
    HTTPContext *s = h->priv_data;
61
    int len = strlen(headers);
62
63
    if (len && strcmp("\r\n", headers + len - 2))
64
        av_log(NULL, AV_LOG_ERROR, "No trailing CRLF found in HTTP header.\n");
65
66
    av_strlcpy(s->headers, headers, sizeof(s->headers));
67
}
68 558b86a5 Luca Barbato
69 f2b9b19f Josh Allmann
void ff_http_set_chunked_transfer_encoding(URLContext *h, int is_chunked)
70
{
71
    ((HTTPContext*)h->priv_data)->is_chunked = is_chunked;
72
}
73
74 558b86a5 Luca Barbato
/* return non zero if error */
75
static int http_open_cnx(URLContext *h)
76
{
77
    const char *path, *proxy_path;
78
    char hostname[1024], hoststr[1024];
79
    char auth[1024];
80
    char path1[1024];
81
    char buf[1024];
82
    int port, use_proxy, err, location_changed = 0, redirects = 0;
83 9405f733 Martin Storsjö
    HTTPAuthType cur_auth_type;
84 558b86a5 Luca Barbato
    HTTPContext *s = h->priv_data;
85
    URLContext *hd = NULL;
86
87 0f3254b8 Josh Allmann
    s->init = 1;
88 558b86a5 Luca Barbato
    proxy_path = getenv("http_proxy");
89
    use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
90 f7d78f36 Måns Rullgård
        av_strstart(proxy_path, "http://", NULL);
91 558b86a5 Luca Barbato
92
    /* fill the dest addr */
93
 redo:
94
    /* needed in any case to build the host string */
95 c5c6e67c Martin Storsjö
    ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
96 f984dcf6 Martin Storsjö
                 path1, sizeof(path1), s->location);
97 57b5555c Martin Storsjö
    ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
98 558b86a5 Luca Barbato
99
    if (use_proxy) {
100 c5c6e67c Martin Storsjö
        ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
101 f984dcf6 Martin Storsjö
                     NULL, 0, proxy_path);
102 558b86a5 Luca Barbato
        path = s->location;
103
    } else {
104
        if (path1[0] == '\0')
105
            path = "/";
106
        else
107
            path = path1;
108
    }
109
    if (port < 0)
110
        port = 80;
111
112 57b5555c Martin Storsjö
    ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
113 558b86a5 Luca Barbato
    err = url_open(&hd, buf, URL_RDWR);
114
    if (err < 0)
115
        goto fail;
116
117
    s->hd = hd;
118 9405f733 Martin Storsjö
    cur_auth_type = s->auth_state.auth_type;
119 558b86a5 Luca Barbato
    if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
120
        goto fail;
121 9405f733 Martin Storsjö
    if (s->http_code == 401) {
122
        if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
123
            url_close(hd);
124
            goto redo;
125
        } else
126
            goto fail;
127
    }
128 a3fd2bd8 Ronald S. Bultje
    if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
129 558b86a5 Luca Barbato
        /* url moved, get next */
130
        url_close(hd);
131
        if (redirects++ >= MAX_REDIRECTS)
132 6f3e0b21 Panagiotis Issaris
            return AVERROR(EIO);
133 558b86a5 Luca Barbato
        location_changed = 0;
134
        goto redo;
135
    }
136
    return 0;
137
 fail:
138
    if (hd)
139
        url_close(hd);
140 701ea516 Martin Storsjö
    s->hd = NULL;
141 6f3e0b21 Panagiotis Issaris
    return AVERROR(EIO);
142 558b86a5 Luca Barbato
}
143
144
static int http_open(URLContext *h, const char *uri, int flags)
145
{
146
    HTTPContext *s;
147
148
    h->is_streamed = 1;
149
150
    s = av_malloc(sizeof(HTTPContext));
151
    if (!s) {
152
        return AVERROR(ENOMEM);
153
    }
154
    h->priv_data = s;
155
    s->filesize = -1;
156 7995ed8e Peter Holik
    s->chunksize = -1;
157 f2b9b19f Josh Allmann
    s->is_chunked = 1;
158 558b86a5 Luca Barbato
    s->off = 0;
159 0f3254b8 Josh Allmann
    s->init = 0;
160 701ea516 Martin Storsjö
    s->hd = NULL;
161 6964d510 Josh Allmann
    *s->headers = '\0';
162 9405f733 Martin Storsjö
    memset(&s->auth_state, 0, sizeof(s->auth_state));
163 f7d78f36 Måns Rullgård
    av_strlcpy(s->location, uri, URL_SIZE);
164 558b86a5 Luca Barbato
165 0f3254b8 Josh Allmann
    return 0;
166 558b86a5 Luca Barbato
}
167
static int http_getc(HTTPContext *s)
168
{
169
    int len;
170
    if (s->buf_ptr >= s->buf_end) {
171
        len = url_read(s->hd, s->buffer, BUFFER_SIZE);
172
        if (len < 0) {
173 6f3e0b21 Panagiotis Issaris
            return AVERROR(EIO);
174 558b86a5 Luca Barbato
        } else if (len == 0) {
175
            return -1;
176
        } else {
177
            s->buf_ptr = s->buffer;
178
            s->buf_end = s->buffer + len;
179
        }
180
    }
181
    return *s->buf_ptr++;
182
}
183
184 682d49f4 Peter Holik
static int http_get_line(HTTPContext *s, char *line, int line_size)
185
{
186
    int ch;
187
    char *q;
188
189
    q = line;
190
    for(;;) {
191
        ch = http_getc(s);
192
        if (ch < 0)
193
            return AVERROR(EIO);
194
        if (ch == '\n') {
195
            /* process line */
196
            if (q > line && q[-1] == '\r')
197
                q--;
198
            *q = '\0';
199
200
            return 0;
201
        } else {
202
            if ((q - line) < line_size - 1)
203
                *q++ = ch;
204
        }
205
    }
206
}
207
208 558b86a5 Luca Barbato
static int process_line(URLContext *h, char *line, int line_count,
209
                        int *new_location)
210
{
211
    HTTPContext *s = h->priv_data;
212
    char *tag, *p;
213
214
    /* end of header */
215
    if (line[0] == '\0')
216
        return 0;
217
218
    p = line;
219
    if (line_count == 0) {
220
        while (!isspace(*p) && *p != '\0')
221
            p++;
222
        while (isspace(*p))
223
            p++;
224
        s->http_code = strtol(p, NULL, 10);
225 a52dc730 Peter Holik
226
        dprintf(NULL, "http_code=%d\n", s->http_code);
227
228 9405f733 Martin Storsjö
        /* error codes are 4xx and 5xx, but regard 401 as a success, so we
229
         * don't abort until all headers have been parsed. */
230
        if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401)
231 7b19aa64 Alex Beregszaszi
            return -1;
232 558b86a5 Luca Barbato
    } else {
233
        while (*p != '\0' && *p != ':')
234
            p++;
235
        if (*p != ':')
236
            return 1;
237
238
        *p = '\0';
239
        tag = line;
240
        p++;
241
        while (isspace(*p))
242
            p++;
243
        if (!strcmp(tag, "Location")) {
244
            strcpy(s->location, p);
245
            *new_location = 1;
246
        } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
247
            s->filesize = atoll(p);
248
        } else if (!strcmp (tag, "Content-Range")) {
249
            /* "bytes $from-$to/$document_size" */
250
            const char *slash;
251
            if (!strncmp (p, "bytes ", 6)) {
252
                p += 6;
253
                s->off = atoll(p);
254
                if ((slash = strchr(p, '/')) && strlen(slash) > 0)
255
                    s->filesize = atoll(slash+1);
256
            }
257
            h->is_streamed = 0; /* we _can_ in fact seek */
258 7995ed8e Peter Holik
        } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
259
            s->filesize = -1;
260
            s->chunksize = 0;
261 9405f733 Martin Storsjö
        } else if (!strcmp (tag, "WWW-Authenticate")) {
262
            ff_http_auth_handle_header(&s->auth_state, tag, p);
263
        } else if (!strcmp (tag, "Authentication-Info")) {
264
            ff_http_auth_handle_header(&s->auth_state, tag, p);
265 558b86a5 Luca Barbato
        }
266
    }
267
    return 1;
268
}
269
270 6964d510 Josh Allmann
static inline int has_header(const char *str, const char *header)
271
{
272
    /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
273
    return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
274
}
275
276 558b86a5 Luca Barbato
static int http_connect(URLContext *h, const char *path, const char *hoststr,
277
                        const char *auth, int *new_location)
278
{
279
    HTTPContext *s = h->priv_data;
280 682d49f4 Peter Holik
    int post, err;
281
    char line[1024];
282 4ceb8b34 Martin Storsjö
    char headers[1024] = "";
283 9405f733 Martin Storsjö
    char *authstr = NULL;
284 bc5c918e Diego Biurrun
    int64_t off = s->off;
285 6964d510 Josh Allmann
    int len = 0;
286 558b86a5 Luca Barbato
287
288
    /* send http header */
289
    post = h->flags & URL_WRONLY;
290 9405f733 Martin Storsjö
    authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
291
                                        post ? "POST" : "GET");
292 6964d510 Josh Allmann
293
    /* set default headers if needed */
294
    if (!has_header(s->headers, "\r\nUser-Agent: "))
295
       len += av_strlcatf(headers + len, sizeof(headers) - len,
296
                          "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
297
    if (!has_header(s->headers, "\r\nAccept: "))
298
        len += av_strlcpy(headers + len, "Accept: */*\r\n",
299
                          sizeof(headers) - len);
300
    if (!has_header(s->headers, "\r\nRange: "))
301
        len += av_strlcatf(headers + len, sizeof(headers) - len,
302 4ceb8b34 Martin Storsjö
                           "Range: bytes=%"PRId64"-\r\n", s->off);
303 6964d510 Josh Allmann
    if (!has_header(s->headers, "\r\nConnection: "))
304
        len += av_strlcpy(headers + len, "Connection: close\r\n",
305
                          sizeof(headers)-len);
306
    if (!has_header(s->headers, "\r\nHost: "))
307
        len += av_strlcatf(headers + len, sizeof(headers) - len,
308
                           "Host: %s\r\n", hoststr);
309
310
    /* now add in custom headers */
311
    av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
312
313 558b86a5 Luca Barbato
    snprintf(s->buffer, sizeof(s->buffer),
314
             "%s %s HTTP/1.1\r\n"
315 9405f733 Martin Storsjö
             "%s"
316 6964d510 Josh Allmann
             "%s"
317 08f7a8ac Tomas Härdin
             "%s"
318 558b86a5 Luca Barbato
             "\r\n",
319
             post ? "POST" : "GET",
320
             path,
321 f2b9b19f Josh Allmann
             post && s->is_chunked ? "Transfer-Encoding: chunked\r\n" : "",
322 6964d510 Josh Allmann
             headers,
323
             authstr ? authstr : "");
324 558b86a5 Luca Barbato
325 9405f733 Martin Storsjö
    av_freep(&authstr);
326 558b86a5 Luca Barbato
    if (http_write(h, s->buffer, strlen(s->buffer)) < 0)
327 6f3e0b21 Panagiotis Issaris
        return AVERROR(EIO);
328 558b86a5 Luca Barbato
329
    /* init input buffer */
330
    s->buf_ptr = s->buffer;
331
    s->buf_end = s->buffer;
332
    s->line_count = 0;
333
    s->off = 0;
334 ecb4a895 Ronald S. Bultje
    s->filesize = -1;
335 558b86a5 Luca Barbato
    if (post) {
336 08f7a8ac Tomas Härdin
        /* always use chunked encoding for upload data */
337
        s->chunksize = 0;
338 dd798dcd Martin Storsjö
        /* Pretend that it did work. We didn't read any header yet, since
339
         * we've still to send the POST data, but the code calling this
340
         * function will check http_code after we return. */
341
        s->http_code = 200;
342 558b86a5 Luca Barbato
        return 0;
343
    }
344
345
    /* wait for header */
346
    for(;;) {
347 682d49f4 Peter Holik
        if (http_get_line(s, line, sizeof(line)) < 0)
348 6f3e0b21 Panagiotis Issaris
            return AVERROR(EIO);
349 a52dc730 Peter Holik
350
        dprintf(NULL, "header='%s'\n", line);
351
352 2b01a520 Jai Menon
        err = process_line(h, line, s->line_count, new_location);
353
        if (err < 0)
354
            return err;
355
        if (err == 0)
356
            break;
357
        s->line_count++;
358 558b86a5 Luca Barbato
    }
359
360
    return (off == s->off) ? 0 : -1;
361
}
362
363
364
static int http_read(URLContext *h, uint8_t *buf, int size)
365
{
366
    HTTPContext *s = h->priv_data;
367
    int len;
368
369 0f3254b8 Josh Allmann
    if (!s->init) {
370
        int ret = http_open_cnx(h);
371
        if (ret != 0)
372
            return ret;
373
    }
374
375
    /* A size of zero can be used to force
376
     * initializaton of the connection. */
377
    if (!size)
378
        return 0;
379
380 7995ed8e Peter Holik
    if (s->chunksize >= 0) {
381
        if (!s->chunksize) {
382
            char line[32];
383
384
            for(;;) {
385
                do {
386
                    if (http_get_line(s, line, sizeof(line)) < 0)
387
                        return AVERROR(EIO);
388
                } while (!*line);    /* skip CR LF from last chunk */
389
390
                s->chunksize = strtoll(line, NULL, 16);
391
392
                dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
393
394
                if (!s->chunksize)
395
                    return 0;
396
                break;
397
            }
398
        }
399
        size = FFMIN(size, s->chunksize);
400
    }
401 558b86a5 Luca Barbato
    /* read bytes from input buffer first */
402
    len = s->buf_end - s->buf_ptr;
403
    if (len > 0) {
404
        if (len > size)
405
            len = size;
406
        memcpy(buf, s->buf_ptr, len);
407
        s->buf_ptr += len;
408
    } else {
409
        len = url_read(s->hd, buf, size);
410
    }
411 7995ed8e Peter Holik
    if (len > 0) {
412 558b86a5 Luca Barbato
        s->off += len;
413 7995ed8e Peter Holik
        if (s->chunksize > 0)
414
            s->chunksize -= len;
415
    }
416 558b86a5 Luca Barbato
    return len;
417
}
418
419
/* used only when posting data */
420 27241cbf Martin Storsjö
static int http_write(URLContext *h, const uint8_t *buf, int size)
421 558b86a5 Luca Barbato
{
422 f2b9b19f Josh Allmann
    char temp[11] = "";  /* 32-bit hex + CRLF + nul */
423 08f7a8ac Tomas Härdin
    int ret;
424
    char crlf[] = "\r\n";
425 558b86a5 Luca Barbato
    HTTPContext *s = h->priv_data;
426 08f7a8ac Tomas Härdin
427 0f3254b8 Josh Allmann
    if (!s->init) {
428
        int ret = http_open_cnx(h);
429
        if (ret != 0)
430
            return ret;
431
    }
432
433 08f7a8ac Tomas Härdin
    if (s->chunksize == -1) {
434
        /* headers are sent without any special encoding */
435 2edabfdf Ronald S. Bultje
        return url_write(s->hd, buf, size);
436 08f7a8ac Tomas Härdin
    }
437
438
    /* silently ignore zero-size data since chunk encoding that would
439
     * signal EOF */
440
    if (size > 0) {
441
        /* upload data using chunked encoding */
442 f2b9b19f Josh Allmann
        if(s->is_chunked) {
443 08f7a8ac Tomas Härdin
        snprintf(temp, sizeof(temp), "%x\r\n", size);
444 f2b9b19f Josh Allmann
            if ((ret = url_write(s->hd, temp, strlen(temp))) < 0)
445
                return ret;
446
        }
447
448
        if ((ret = url_write(s->hd, buf, size)) < 0)
449
            return ret;
450 08f7a8ac Tomas Härdin
451 f2b9b19f Josh Allmann
        if (s->is_chunked && (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
452 08f7a8ac Tomas Härdin
            return ret;
453
    }
454
    return size;
455 558b86a5 Luca Barbato
}
456
457
static int http_close(URLContext *h)
458
{
459 08f7a8ac Tomas Härdin
    int ret = 0;
460
    char footer[] = "0\r\n\r\n";
461 558b86a5 Luca Barbato
    HTTPContext *s = h->priv_data;
462 08f7a8ac Tomas Härdin
463
    /* signal end of chunked encoding if used */
464
    if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
465
        ret = url_write(s->hd, footer, sizeof(footer) - 1);
466
        ret = ret > 0 ? 0 : ret;
467
    }
468
469 701ea516 Martin Storsjö
    if (s->hd)
470
        url_close(s->hd);
471 558b86a5 Luca Barbato
    av_free(s);
472 08f7a8ac Tomas Härdin
    return ret;
473 558b86a5 Luca Barbato
}
474
475 bc5c918e Diego Biurrun
static int64_t http_seek(URLContext *h, int64_t off, int whence)
476 558b86a5 Luca Barbato
{
477
    HTTPContext *s = h->priv_data;
478
    URLContext *old_hd = s->hd;
479 bc5c918e Diego Biurrun
    int64_t old_off = s->off;
480 08c8e66a Baptiste Coudurier
    uint8_t old_buf[BUFFER_SIZE];
481
    int old_buf_size;
482 558b86a5 Luca Barbato
483
    if (whence == AVSEEK_SIZE)
484
        return s->filesize;
485
    else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
486
        return -1;
487
488
    /* we save the old context in case the seek fails */
489 08c8e66a Baptiste Coudurier
    old_buf_size = s->buf_end - s->buf_ptr;
490
    memcpy(old_buf, s->buf_ptr, old_buf_size);
491 558b86a5 Luca Barbato
    s->hd = NULL;
492
    if (whence == SEEK_CUR)
493
        off += s->off;
494
    else if (whence == SEEK_END)
495
        off += s->filesize;
496
    s->off = off;
497
498
    /* if it fails, continue on old connection */
499
    if (http_open_cnx(h) < 0) {
500 08c8e66a Baptiste Coudurier
        memcpy(s->buffer, old_buf, old_buf_size);
501
        s->buf_ptr = s->buffer;
502
        s->buf_end = s->buffer + old_buf_size;
503 558b86a5 Luca Barbato
        s->hd = old_hd;
504
        s->off = old_off;
505
        return -1;
506
    }
507
    url_close(old_hd);
508
    return off;
509
}
510
511 f0a80394 Ronald S. Bultje
static int
512
http_get_file_handle(URLContext *h)
513
{
514
    HTTPContext *s = h->priv_data;
515
    return url_get_file_handle(s->hd);
516
}
517
518 558b86a5 Luca Barbato
URLProtocol http_protocol = {
519
    "http",
520
    http_open,
521
    http_read,
522
    http_write,
523
    http_seek,
524
    http_close,
525 f0a80394 Ronald S. Bultje
    .url_get_file_handle = http_get_file_handle,
526 558b86a5 Luca Barbato
};