Statistics
| Branch: | Revision:

ffmpeg / libavformat / http.c @ 57b5555c

History | View | Annotate | Download (11.5 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/base64.h"
23
#include "libavutil/avstring.h"
24
#include "avformat.h"
25
#include <unistd.h>
26
#include <strings.h>
27
#include "network.h"
28
#include "os_support.h"
29

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

    
33
/* used for protocol handling */
34
#define BUFFER_SIZE 1024
35
#define URL_SIZE    4096
36
#define MAX_REDIRECTS 8
37

    
38
typedef struct {
39
    URLContext *hd;
40
    unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
41
    int line_count;
42
    int http_code;
43
    int64_t chunksize;      /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
44
    int64_t off, filesize;
45
    char location[URL_SIZE];
46
} HTTPContext;
47

    
48
static int http_connect(URLContext *h, const char *path, const char *hoststr,
49
                        const char *auth, int *new_location);
50
static int http_write(URLContext *h, uint8_t *buf, int size);
51

    
52

    
53
/* return non zero if error */
54
static int http_open_cnx(URLContext *h)
55
{
56
    const char *path, *proxy_path;
57
    char hostname[1024], hoststr[1024];
58
    char auth[1024];
59
    char path1[1024];
60
    char buf[1024];
61
    int port, use_proxy, err, location_changed = 0, redirects = 0;
62
    HTTPContext *s = h->priv_data;
63
    URLContext *hd = NULL;
64

    
65
    proxy_path = getenv("http_proxy");
66
    use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
67
        av_strstart(proxy_path, "http://", NULL);
68

    
69
    /* fill the dest addr */
70
 redo:
71
    /* needed in any case to build the host string */
72
    url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
73
              path1, sizeof(path1), s->location);
74
    ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
75

    
76
    if (use_proxy) {
77
        url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
78
                  NULL, 0, proxy_path);
79
        path = s->location;
80
    } else {
81
        if (path1[0] == '\0')
82
            path = "/";
83
        else
84
            path = path1;
85
    }
86
    if (port < 0)
87
        port = 80;
88

    
89
    ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
90
    err = url_open(&hd, buf, URL_RDWR);
91
    if (err < 0)
92
        goto fail;
93

    
94
    s->hd = hd;
95
    if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
96
        goto fail;
97
    if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
98
        /* url moved, get next */
99
        url_close(hd);
100
        if (redirects++ >= MAX_REDIRECTS)
101
            return AVERROR(EIO);
102
        location_changed = 0;
103
        goto redo;
104
    }
105
    return 0;
106
 fail:
107
    if (hd)
108
        url_close(hd);
109
    return AVERROR(EIO);
110
}
111

    
112
static int http_open(URLContext *h, const char *uri, int flags)
113
{
114
    HTTPContext *s;
115
    int ret;
116

    
117
    h->is_streamed = 1;
118

    
119
    s = av_malloc(sizeof(HTTPContext));
120
    if (!s) {
121
        return AVERROR(ENOMEM);
122
    }
123
    h->priv_data = s;
124
    s->filesize = -1;
125
    s->chunksize = -1;
126
    s->off = 0;
127
    av_strlcpy(s->location, uri, URL_SIZE);
128

    
129
    ret = http_open_cnx(h);
130
    if (ret != 0)
131
        av_free (s);
132
    return ret;
133
}
134
static int http_getc(HTTPContext *s)
135
{
136
    int len;
137
    if (s->buf_ptr >= s->buf_end) {
138
        len = url_read(s->hd, s->buffer, BUFFER_SIZE);
139
        if (len < 0) {
140
            return AVERROR(EIO);
141
        } else if (len == 0) {
142
            return -1;
143
        } else {
144
            s->buf_ptr = s->buffer;
145
            s->buf_end = s->buffer + len;
146
        }
147
    }
148
    return *s->buf_ptr++;
149
}
150

    
151
static int http_get_line(HTTPContext *s, char *line, int line_size)
152
{
153
    int ch;
154
    char *q;
155

    
156
    q = line;
157
    for(;;) {
158
        ch = http_getc(s);
159
        if (ch < 0)
160
            return AVERROR(EIO);
161
        if (ch == '\n') {
162
            /* process line */
163
            if (q > line && q[-1] == '\r')
164
                q--;
165
            *q = '\0';
166

    
167
            return 0;
168
        } else {
169
            if ((q - line) < line_size - 1)
170
                *q++ = ch;
171
        }
172
    }
173
}
174

    
175
static int process_line(URLContext *h, char *line, int line_count,
176
                        int *new_location)
177
{
178
    HTTPContext *s = h->priv_data;
179
    char *tag, *p;
180

    
181
    /* end of header */
182
    if (line[0] == '\0')
183
        return 0;
184

    
185
    p = line;
186
    if (line_count == 0) {
187
        while (!isspace(*p) && *p != '\0')
188
            p++;
189
        while (isspace(*p))
190
            p++;
191
        s->http_code = strtol(p, NULL, 10);
192

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

    
195
        /* error codes are 4xx and 5xx */
196
        if (s->http_code >= 400 && s->http_code < 600)
197
            return -1;
198
    } else {
199
        while (*p != '\0' && *p != ':')
200
            p++;
201
        if (*p != ':')
202
            return 1;
203

    
204
        *p = '\0';
205
        tag = line;
206
        p++;
207
        while (isspace(*p))
208
            p++;
209
        if (!strcmp(tag, "Location")) {
210
            strcpy(s->location, p);
211
            *new_location = 1;
212
        } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
213
            s->filesize = atoll(p);
214
        } else if (!strcmp (tag, "Content-Range")) {
215
            /* "bytes $from-$to/$document_size" */
216
            const char *slash;
217
            if (!strncmp (p, "bytes ", 6)) {
218
                p += 6;
219
                s->off = atoll(p);
220
                if ((slash = strchr(p, '/')) && strlen(slash) > 0)
221
                    s->filesize = atoll(slash+1);
222
            }
223
            h->is_streamed = 0; /* we _can_ in fact seek */
224
        } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
225
            s->filesize = -1;
226
            s->chunksize = 0;
227
        }
228
    }
229
    return 1;
230
}
231

    
232
static int http_connect(URLContext *h, const char *path, const char *hoststr,
233
                        const char *auth, int *new_location)
234
{
235
    HTTPContext *s = h->priv_data;
236
    int post, err;
237
    char line[1024];
238
    char *auth_b64;
239
    int auth_b64_len = (strlen(auth) + 2) / 3 * 4 + 1;
240
    int64_t off = s->off;
241

    
242

    
243
    /* send http header */
244
    post = h->flags & URL_WRONLY;
245
    auth_b64 = av_malloc(auth_b64_len);
246
    av_base64_encode(auth_b64, auth_b64_len, auth, strlen(auth));
247
    snprintf(s->buffer, sizeof(s->buffer),
248
             "%s %s HTTP/1.1\r\n"
249
             "User-Agent: %s\r\n"
250
             "Accept: */*\r\n"
251
             "Range: bytes=%"PRId64"-\r\n"
252
             "Host: %s\r\n"
253
             "Authorization: Basic %s\r\n"
254
             "Connection: close\r\n"
255
             "%s"
256
             "\r\n",
257
             post ? "POST" : "GET",
258
             path,
259
             LIBAVFORMAT_IDENT,
260
             s->off,
261
             hoststr,
262
             auth_b64,
263
             post ? "Transfer-Encoding: chunked\r\n" : "");
264

    
265
    av_freep(&auth_b64);
266
    if (http_write(h, s->buffer, strlen(s->buffer)) < 0)
267
        return AVERROR(EIO);
268

    
269
    /* init input buffer */
270
    s->buf_ptr = s->buffer;
271
    s->buf_end = s->buffer;
272
    s->line_count = 0;
273
    s->off = 0;
274
    s->filesize = -1;
275
    if (post) {
276
        /* always use chunked encoding for upload data */
277
        s->chunksize = 0;
278
        return 0;
279
    }
280

    
281
    /* wait for header */
282
    for(;;) {
283
        if (http_get_line(s, line, sizeof(line)) < 0)
284
            return AVERROR(EIO);
285

    
286
        dprintf(NULL, "header='%s'\n", line);
287

    
288
        err = process_line(h, line, s->line_count, new_location);
289
        if (err < 0)
290
            return err;
291
        if (err == 0)
292
            break;
293
        s->line_count++;
294
    }
295

    
296
    return (off == s->off) ? 0 : -1;
297
}
298

    
299

    
300
static int http_read(URLContext *h, uint8_t *buf, int size)
301
{
302
    HTTPContext *s = h->priv_data;
303
    int len;
304

    
305
    if (s->chunksize >= 0) {
306
        if (!s->chunksize) {
307
            char line[32];
308

    
309
            for(;;) {
310
                do {
311
                    if (http_get_line(s, line, sizeof(line)) < 0)
312
                        return AVERROR(EIO);
313
                } while (!*line);    /* skip CR LF from last chunk */
314

    
315
                s->chunksize = strtoll(line, NULL, 16);
316

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

    
319
                if (!s->chunksize)
320
                    return 0;
321
                break;
322
            }
323
        }
324
        size = FFMIN(size, s->chunksize);
325
    }
326
    /* read bytes from input buffer first */
327
    len = s->buf_end - s->buf_ptr;
328
    if (len > 0) {
329
        if (len > size)
330
            len = size;
331
        memcpy(buf, s->buf_ptr, len);
332
        s->buf_ptr += len;
333
    } else {
334
        len = url_read(s->hd, buf, size);
335
    }
336
    if (len > 0) {
337
        s->off += len;
338
        if (s->chunksize > 0)
339
            s->chunksize -= len;
340
    }
341
    return len;
342
}
343

    
344
/* used only when posting data */
345
static int http_write(URLContext *h, uint8_t *buf, int size)
346
{
347
    char temp[11];  /* 32-bit hex + CRLF + nul */
348
    int ret;
349
    char crlf[] = "\r\n";
350
    HTTPContext *s = h->priv_data;
351

    
352
    if (s->chunksize == -1) {
353
        /* headers are sent without any special encoding */
354
        return url_write(s->hd, buf, size);
355
    }
356

    
357
    /* silently ignore zero-size data since chunk encoding that would
358
     * signal EOF */
359
    if (size > 0) {
360
        /* upload data using chunked encoding */
361
        snprintf(temp, sizeof(temp), "%x\r\n", size);
362

    
363
        if ((ret = url_write(s->hd, temp, strlen(temp))) < 0 ||
364
            (ret = url_write(s->hd, buf, size)) < 0 ||
365
            (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
366
            return ret;
367
    }
368
    return size;
369
}
370

    
371
static int http_close(URLContext *h)
372
{
373
    int ret = 0;
374
    char footer[] = "0\r\n\r\n";
375
    HTTPContext *s = h->priv_data;
376

    
377
    /* signal end of chunked encoding if used */
378
    if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
379
        ret = url_write(s->hd, footer, sizeof(footer) - 1);
380
        ret = ret > 0 ? 0 : ret;
381
    }
382

    
383
    url_close(s->hd);
384
    av_free(s);
385
    return ret;
386
}
387

    
388
static int64_t http_seek(URLContext *h, int64_t off, int whence)
389
{
390
    HTTPContext *s = h->priv_data;
391
    URLContext *old_hd = s->hd;
392
    int64_t old_off = s->off;
393
    uint8_t old_buf[BUFFER_SIZE];
394
    int old_buf_size;
395

    
396
    if (whence == AVSEEK_SIZE)
397
        return s->filesize;
398
    else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
399
        return -1;
400

    
401
    /* we save the old context in case the seek fails */
402
    old_buf_size = s->buf_end - s->buf_ptr;
403
    memcpy(old_buf, s->buf_ptr, old_buf_size);
404
    s->hd = NULL;
405
    if (whence == SEEK_CUR)
406
        off += s->off;
407
    else if (whence == SEEK_END)
408
        off += s->filesize;
409
    s->off = off;
410

    
411
    /* if it fails, continue on old connection */
412
    if (http_open_cnx(h) < 0) {
413
        memcpy(s->buffer, old_buf, old_buf_size);
414
        s->buf_ptr = s->buffer;
415
        s->buf_end = s->buffer + old_buf_size;
416
        s->hd = old_hd;
417
        s->off = old_off;
418
        return -1;
419
    }
420
    url_close(old_hd);
421
    return off;
422
}
423

    
424
static int
425
http_get_file_handle(URLContext *h)
426
{
427
    HTTPContext *s = h->priv_data;
428
    return url_get_file_handle(s->hd);
429
}
430

    
431
URLProtocol http_protocol = {
432
    "http",
433
    http_open,
434
    http_read,
435
    http_write,
436
    http_seek,
437
    http_close,
438
    .url_get_file_handle = http_get_file_handle,
439
};