Statistics
| Branch: | Revision:

ffmpeg / libavformat / http.c @ 4ceb8b34

History | View | Annotate | Download (14.2 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
} HTTPContext;
52

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

    
57
void ff_http_set_headers(URLContext *h, const char *headers)
58
{
59
    HTTPContext *s = h->priv_data;
60
    int len = strlen(headers);
61

    
62
    if (len && strcmp("\r\n", headers + len - 2))
63
        av_log(NULL, AV_LOG_ERROR, "No trailing CRLF found in HTTP header.\n");
64

    
65
    av_strlcpy(s->headers, headers, sizeof(s->headers));
66
}
67

    
68
/* return non zero if error */
69
static int http_open_cnx(URLContext *h)
70
{
71
    const char *path, *proxy_path;
72
    char hostname[1024], hoststr[1024];
73
    char auth[1024];
74
    char path1[1024];
75
    char buf[1024];
76
    int port, use_proxy, err, location_changed = 0, redirects = 0;
77
    HTTPAuthType cur_auth_type;
78
    HTTPContext *s = h->priv_data;
79
    URLContext *hd = NULL;
80

    
81
    s->init = 1;
82
    proxy_path = getenv("http_proxy");
83
    use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
84
        av_strstart(proxy_path, "http://", NULL);
85

    
86
    /* fill the dest addr */
87
 redo:
88
    /* needed in any case to build the host string */
89
    ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
90
                 path1, sizeof(path1), s->location);
91
    ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
92

    
93
    if (use_proxy) {
94
        ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
95
                     NULL, 0, proxy_path);
96
        path = s->location;
97
    } else {
98
        if (path1[0] == '\0')
99
            path = "/";
100
        else
101
            path = path1;
102
    }
103
    if (port < 0)
104
        port = 80;
105

    
106
    ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
107
    err = url_open(&hd, buf, URL_RDWR);
108
    if (err < 0)
109
        goto fail;
110

    
111
    s->hd = hd;
112
    cur_auth_type = s->auth_state.auth_type;
113
    if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
114
        goto fail;
115
    if (s->http_code == 401) {
116
        if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
117
            url_close(hd);
118
            goto redo;
119
        } else
120
            goto fail;
121
    }
122
    if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
123
        /* url moved, get next */
124
        url_close(hd);
125
        if (redirects++ >= MAX_REDIRECTS)
126
            return AVERROR(EIO);
127
        location_changed = 0;
128
        goto redo;
129
    }
130
    return 0;
131
 fail:
132
    if (hd)
133
        url_close(hd);
134
    return AVERROR(EIO);
135
}
136

    
137
static int http_open(URLContext *h, const char *uri, int flags)
138
{
139
    HTTPContext *s;
140

    
141
    h->is_streamed = 1;
142

    
143
    s = av_malloc(sizeof(HTTPContext));
144
    if (!s) {
145
        return AVERROR(ENOMEM);
146
    }
147
    h->priv_data = s;
148
    s->filesize = -1;
149
    s->chunksize = -1;
150
    s->off = 0;
151
    s->init = 0;
152
    *s->headers = '\0';
153
    memset(&s->auth_state, 0, sizeof(s->auth_state));
154
    av_strlcpy(s->location, uri, URL_SIZE);
155

    
156
    return 0;
157
}
158
static int http_getc(HTTPContext *s)
159
{
160
    int len;
161
    if (s->buf_ptr >= s->buf_end) {
162
        len = url_read(s->hd, s->buffer, BUFFER_SIZE);
163
        if (len < 0) {
164
            return AVERROR(EIO);
165
        } else if (len == 0) {
166
            return -1;
167
        } else {
168
            s->buf_ptr = s->buffer;
169
            s->buf_end = s->buffer + len;
170
        }
171
    }
172
    return *s->buf_ptr++;
173
}
174

    
175
static int http_get_line(HTTPContext *s, char *line, int line_size)
176
{
177
    int ch;
178
    char *q;
179

    
180
    q = line;
181
    for(;;) {
182
        ch = http_getc(s);
183
        if (ch < 0)
184
            return AVERROR(EIO);
185
        if (ch == '\n') {
186
            /* process line */
187
            if (q > line && q[-1] == '\r')
188
                q--;
189
            *q = '\0';
190

    
191
            return 0;
192
        } else {
193
            if ((q - line) < line_size - 1)
194
                *q++ = ch;
195
        }
196
    }
197
}
198

    
199
static int process_line(URLContext *h, char *line, int line_count,
200
                        int *new_location)
201
{
202
    HTTPContext *s = h->priv_data;
203
    char *tag, *p;
204

    
205
    /* end of header */
206
    if (line[0] == '\0')
207
        return 0;
208

    
209
    p = line;
210
    if (line_count == 0) {
211
        while (!isspace(*p) && *p != '\0')
212
            p++;
213
        while (isspace(*p))
214
            p++;
215
        s->http_code = strtol(p, NULL, 10);
216

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

    
219
        /* error codes are 4xx and 5xx, but regard 401 as a success, so we
220
         * don't abort until all headers have been parsed. */
221
        if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401)
222
            return -1;
223
    } else {
224
        while (*p != '\0' && *p != ':')
225
            p++;
226
        if (*p != ':')
227
            return 1;
228

    
229
        *p = '\0';
230
        tag = line;
231
        p++;
232
        while (isspace(*p))
233
            p++;
234
        if (!strcmp(tag, "Location")) {
235
            strcpy(s->location, p);
236
            *new_location = 1;
237
        } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
238
            s->filesize = atoll(p);
239
        } else if (!strcmp (tag, "Content-Range")) {
240
            /* "bytes $from-$to/$document_size" */
241
            const char *slash;
242
            if (!strncmp (p, "bytes ", 6)) {
243
                p += 6;
244
                s->off = atoll(p);
245
                if ((slash = strchr(p, '/')) && strlen(slash) > 0)
246
                    s->filesize = atoll(slash+1);
247
            }
248
            h->is_streamed = 0; /* we _can_ in fact seek */
249
        } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
250
            s->filesize = -1;
251
            s->chunksize = 0;
252
        } else if (!strcmp (tag, "WWW-Authenticate")) {
253
            ff_http_auth_handle_header(&s->auth_state, tag, p);
254
        } else if (!strcmp (tag, "Authentication-Info")) {
255
            ff_http_auth_handle_header(&s->auth_state, tag, p);
256
        }
257
    }
258
    return 1;
259
}
260

    
261
static inline int has_header(const char *str, const char *header)
262
{
263
    /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
264
    return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
265
}
266

    
267
static int http_connect(URLContext *h, const char *path, const char *hoststr,
268
                        const char *auth, int *new_location)
269
{
270
    HTTPContext *s = h->priv_data;
271
    int post, err;
272
    char line[1024];
273
    char headers[1024] = "";
274
    char *authstr = NULL;
275
    int64_t off = s->off;
276
    int len = 0;
277

    
278

    
279
    /* send http header */
280
    post = h->flags & URL_WRONLY;
281
    authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
282
                                        post ? "POST" : "GET");
283

    
284
    /* set default headers if needed */
285
    if (!has_header(s->headers, "\r\nUser-Agent: "))
286
       len += av_strlcatf(headers + len, sizeof(headers) - len,
287
                          "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
288
    if (!has_header(s->headers, "\r\nAccept: "))
289
        len += av_strlcpy(headers + len, "Accept: */*\r\n",
290
                          sizeof(headers) - len);
291
    if (!has_header(s->headers, "\r\nRange: "))
292
        len += av_strlcatf(headers + len, sizeof(headers) - len,
293
                           "Range: bytes=%"PRId64"-\r\n", s->off);
294
    if (!has_header(s->headers, "\r\nConnection: "))
295
        len += av_strlcpy(headers + len, "Connection: close\r\n",
296
                          sizeof(headers)-len);
297
    if (!has_header(s->headers, "\r\nHost: "))
298
        len += av_strlcatf(headers + len, sizeof(headers) - len,
299
                           "Host: %s\r\n", hoststr);
300

    
301
    /* now add in custom headers */
302
    av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
303

    
304
    snprintf(s->buffer, sizeof(s->buffer),
305
             "%s %s HTTP/1.1\r\n"
306
             "%s"
307
             "%s"
308
             "%s"
309
             "\r\n",
310
             post ? "POST" : "GET",
311
             path,
312
             post ? "Transfer-Encoding: chunked\r\n" : "",
313
             headers,
314
             authstr ? authstr : "");
315

    
316
    av_freep(&authstr);
317
    if (http_write(h, s->buffer, strlen(s->buffer)) < 0)
318
        return AVERROR(EIO);
319

    
320
    /* init input buffer */
321
    s->buf_ptr = s->buffer;
322
    s->buf_end = s->buffer;
323
    s->line_count = 0;
324
    s->off = 0;
325
    s->filesize = -1;
326
    if (post) {
327
        /* always use chunked encoding for upload data */
328
        s->chunksize = 0;
329
        /* Pretend that it did work. We didn't read any header yet, since
330
         * we've still to send the POST data, but the code calling this
331
         * function will check http_code after we return. */
332
        s->http_code = 200;
333
        return 0;
334
    }
335

    
336
    /* wait for header */
337
    for(;;) {
338
        if (http_get_line(s, line, sizeof(line)) < 0)
339
            return AVERROR(EIO);
340

    
341
        dprintf(NULL, "header='%s'\n", line);
342

    
343
        err = process_line(h, line, s->line_count, new_location);
344
        if (err < 0)
345
            return err;
346
        if (err == 0)
347
            break;
348
        s->line_count++;
349
    }
350

    
351
    return (off == s->off) ? 0 : -1;
352
}
353

    
354

    
355
static int http_read(URLContext *h, uint8_t *buf, int size)
356
{
357
    HTTPContext *s = h->priv_data;
358
    int len;
359

    
360
    if (!s->init) {
361
        int ret = http_open_cnx(h);
362
        if (ret != 0)
363
            return ret;
364
    }
365

    
366
    /* A size of zero can be used to force
367
     * initializaton of the connection. */
368
    if (!size)
369
        return 0;
370

    
371
    if (s->chunksize >= 0) {
372
        if (!s->chunksize) {
373
            char line[32];
374

    
375
            for(;;) {
376
                do {
377
                    if (http_get_line(s, line, sizeof(line)) < 0)
378
                        return AVERROR(EIO);
379
                } while (!*line);    /* skip CR LF from last chunk */
380

    
381
                s->chunksize = strtoll(line, NULL, 16);
382

    
383
                dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
384

    
385
                if (!s->chunksize)
386
                    return 0;
387
                break;
388
            }
389
        }
390
        size = FFMIN(size, s->chunksize);
391
    }
392
    /* read bytes from input buffer first */
393
    len = s->buf_end - s->buf_ptr;
394
    if (len > 0) {
395
        if (len > size)
396
            len = size;
397
        memcpy(buf, s->buf_ptr, len);
398
        s->buf_ptr += len;
399
    } else {
400
        len = url_read(s->hd, buf, size);
401
    }
402
    if (len > 0) {
403
        s->off += len;
404
        if (s->chunksize > 0)
405
            s->chunksize -= len;
406
    }
407
    return len;
408
}
409

    
410
/* used only when posting data */
411
static int http_write(URLContext *h, const uint8_t *buf, int size)
412
{
413
    char temp[11];  /* 32-bit hex + CRLF + nul */
414
    int ret;
415
    char crlf[] = "\r\n";
416
    HTTPContext *s = h->priv_data;
417

    
418
    if (!s->init) {
419
        int ret = http_open_cnx(h);
420
        if (ret != 0)
421
            return ret;
422
    }
423

    
424
    if (s->chunksize == -1) {
425
        /* headers are sent without any special encoding */
426
        return url_write(s->hd, buf, size);
427
    }
428

    
429
    /* silently ignore zero-size data since chunk encoding that would
430
     * signal EOF */
431
    if (size > 0) {
432
        /* upload data using chunked encoding */
433
        snprintf(temp, sizeof(temp), "%x\r\n", size);
434

    
435
        if ((ret = url_write(s->hd, temp, strlen(temp))) < 0 ||
436
            (ret = url_write(s->hd, buf, size)) < 0 ||
437
            (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
438
            return ret;
439
    }
440
    return size;
441
}
442

    
443
static int http_close(URLContext *h)
444
{
445
    int ret = 0;
446
    char footer[] = "0\r\n\r\n";
447
    HTTPContext *s = h->priv_data;
448

    
449
    /* signal end of chunked encoding if used */
450
    if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
451
        ret = url_write(s->hd, footer, sizeof(footer) - 1);
452
        ret = ret > 0 ? 0 : ret;
453
    }
454

    
455
    url_close(s->hd);
456
    av_free(s);
457
    return ret;
458
}
459

    
460
static int64_t http_seek(URLContext *h, int64_t off, int whence)
461
{
462
    HTTPContext *s = h->priv_data;
463
    URLContext *old_hd = s->hd;
464
    int64_t old_off = s->off;
465
    uint8_t old_buf[BUFFER_SIZE];
466
    int old_buf_size;
467

    
468
    if (whence == AVSEEK_SIZE)
469
        return s->filesize;
470
    else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
471
        return -1;
472

    
473
    /* we save the old context in case the seek fails */
474
    old_buf_size = s->buf_end - s->buf_ptr;
475
    memcpy(old_buf, s->buf_ptr, old_buf_size);
476
    s->hd = NULL;
477
    if (whence == SEEK_CUR)
478
        off += s->off;
479
    else if (whence == SEEK_END)
480
        off += s->filesize;
481
    s->off = off;
482

    
483
    /* if it fails, continue on old connection */
484
    if (http_open_cnx(h) < 0) {
485
        memcpy(s->buffer, old_buf, old_buf_size);
486
        s->buf_ptr = s->buffer;
487
        s->buf_end = s->buffer + old_buf_size;
488
        s->hd = old_hd;
489
        s->off = old_off;
490
        return -1;
491
    }
492
    url_close(old_hd);
493
    return off;
494
}
495

    
496
static int
497
http_get_file_handle(URLContext *h)
498
{
499
    HTTPContext *s = h->priv_data;
500
    return url_get_file_handle(s->hd);
501
}
502

    
503
URLProtocol http_protocol = {
504
    "http",
505
    http_open,
506
    http_read,
507
    http_write,
508
    http_seek,
509
    http_close,
510
    .url_get_file_handle = http_get_file_handle,
511
};