Statistics
| Branch: | Revision:

ffmpeg / libavformat / http.c @ e4f28e08

History | View | Annotate | Download (14.6 KB)

1
/*
2
 * HTTP protocol for ffmpeg client
3
 * Copyright (c) 2000, 2001 Fabrice Bellard
4
 *
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

    
22
#include "libavutil/avstring.h"
23
#include "avformat.h"
24
#include <unistd.h>
25
#include <strings.h>
26
#include "internal.h"
27
#include "network.h"
28
#include "http.h"
29
#include "os_support.h"
30
#include "httpauth.h"
31

    
32
/* XXX: POST protocol is not completely implemented because ffmpeg uses
33
   only a subset of it. */
34

    
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
    int64_t chunksize;      /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
46
    int64_t off, filesize;
47
    char location[URL_SIZE];
48
    HTTPAuthState auth_state;
49
    int init;
50
    unsigned char headers[BUFFER_SIZE];
51
    int is_chunked;
52
} HTTPContext;
53

    
54
static int http_connect(URLContext *h, const char *path, const char *hoststr,
55
                        const char *auth, int *new_location);
56
static int http_write(URLContext *h, const uint8_t *buf, int size);
57

    
58
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

    
69
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
/* 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
    HTTPAuthType cur_auth_type;
84
    HTTPContext *s = h->priv_data;
85
    URLContext *hd = NULL;
86

    
87
    s->init = 1;
88
    proxy_path = getenv("http_proxy");
89
    use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
90
        av_strstart(proxy_path, "http://", NULL);
91

    
92
    /* fill the dest addr */
93
 redo:
94
    /* needed in any case to build the host string */
95
    ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
96
                 path1, sizeof(path1), s->location);
97
    ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
98

    
99
    if (use_proxy) {
100
        ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
101
                     NULL, 0, proxy_path);
102
        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
    ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
113
    err = url_open(&hd, buf, URL_RDWR);
114
    if (err < 0)
115
        goto fail;
116

    
117
    s->hd = hd;
118
    cur_auth_type = s->auth_state.auth_type;
119
    if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
120
        goto fail;
121
    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
    if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
129
        /* url moved, get next */
130
        url_close(hd);
131
        if (redirects++ >= MAX_REDIRECTS)
132
            return AVERROR(EIO);
133
        location_changed = 0;
134
        goto redo;
135
    }
136
    return 0;
137
 fail:
138
    if (hd)
139
        url_close(hd);
140
    s->hd = NULL;
141
    return AVERROR(EIO);
142
}
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
    s->chunksize = -1;
157
    s->is_chunked = 1;
158
    s->off = 0;
159
    s->init = 0;
160
    s->hd = NULL;
161
    *s->headers = '\0';
162
    memset(&s->auth_state, 0, sizeof(s->auth_state));
163
    av_strlcpy(s->location, uri, URL_SIZE);
164

    
165
    return 0;
166
}
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
            return AVERROR(EIO);
174
        } 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
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
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

    
226
        dprintf(NULL, "http_code=%d\n", s->http_code);
227

    
228
        /* 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
            return -1;
232
    } 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
        } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
259
            s->filesize = -1;
260
            s->chunksize = 0;
261
        } 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
        }
266
    }
267
    return 1;
268
}
269

    
270
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
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
    int post, err;
281
    char line[1024];
282
    char headers[1024] = "";
283
    char *authstr = NULL;
284
    int64_t off = s->off;
285
    int len = 0;
286

    
287

    
288
    /* send http header */
289
    post = h->flags & URL_WRONLY;
290
    authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
291
                                        post ? "POST" : "GET");
292

    
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
                           "Range: bytes=%"PRId64"-\r\n", s->off);
303
    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
    snprintf(s->buffer, sizeof(s->buffer),
314
             "%s %s HTTP/1.1\r\n"
315
             "%s"
316
             "%s"
317
             "%s"
318
             "\r\n",
319
             post ? "POST" : "GET",
320
             path,
321
             post && s->is_chunked ? "Transfer-Encoding: chunked\r\n" : "",
322
             headers,
323
             authstr ? authstr : "");
324

    
325
    av_freep(&authstr);
326
    if (http_write(h, s->buffer, strlen(s->buffer)) < 0)
327
        return AVERROR(EIO);
328

    
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
    s->filesize = -1;
335
    if (post) {
336
        /* always use chunked encoding for upload data */
337
        s->chunksize = 0;
338
        /* 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
        return 0;
343
    }
344

    
345
    /* wait for header */
346
    for(;;) {
347
        if (http_get_line(s, line, sizeof(line)) < 0)
348
            return AVERROR(EIO);
349

    
350
        dprintf(NULL, "header='%s'\n", line);
351

    
352
        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
    }
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
    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
    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
    /* 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
    if (len > 0) {
412
        s->off += len;
413
        if (s->chunksize > 0)
414
            s->chunksize -= len;
415
    }
416
    return len;
417
}
418

    
419
/* used only when posting data */
420
static int http_write(URLContext *h, const uint8_t *buf, int size)
421
{
422
    char temp[11] = "";  /* 32-bit hex + CRLF + nul */
423
    int ret;
424
    char crlf[] = "\r\n";
425
    HTTPContext *s = h->priv_data;
426

    
427
    if (!s->init) {
428
        int ret = http_open_cnx(h);
429
        if (ret != 0)
430
            return ret;
431
    }
432

    
433
    if (s->chunksize == -1) {
434
        /* headers are sent without any special encoding */
435
        return url_write(s->hd, buf, size);
436
    }
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
        if(s->is_chunked) {
443
            snprintf(temp, sizeof(temp), "%x\r\n", size);
444
            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

    
451
        if (s->is_chunked && (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
452
            return ret;
453
    }
454
    return size;
455
}
456

    
457
static int http_close(URLContext *h)
458
{
459
    int ret = 0;
460
    char footer[] = "0\r\n\r\n";
461
    HTTPContext *s = h->priv_data;
462

    
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
    if (s->hd)
470
        url_close(s->hd);
471
    av_free(s);
472
    return ret;
473
}
474

    
475
static int64_t http_seek(URLContext *h, int64_t off, int whence)
476
{
477
    HTTPContext *s = h->priv_data;
478
    URLContext *old_hd = s->hd;
479
    int64_t old_off = s->off;
480
    uint8_t old_buf[BUFFER_SIZE];
481
    int old_buf_size;
482

    
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
    old_buf_size = s->buf_end - s->buf_ptr;
490
    memcpy(old_buf, s->buf_ptr, old_buf_size);
491
    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
        memcpy(s->buffer, old_buf, old_buf_size);
501
        s->buf_ptr = s->buffer;
502
        s->buf_end = s->buffer + old_buf_size;
503
        s->hd = old_hd;
504
        s->off = old_off;
505
        return -1;
506
    }
507
    url_close(old_hd);
508
    return off;
509
}
510

    
511
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
URLProtocol http_protocol = {
519
    "http",
520
    http_open,
521
    http_read,
522
    http_write,
523
    http_seek,
524
    http_close,
525
    .url_get_file_handle = http_get_file_handle,
526
};