OSDN Git Service

ffmetaenc: remove useless initializers
[coroid/libav_saccubus.git] / libavformat / http.c
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 #include "libavutil/opt.h"
32
33 /* XXX: POST protocol is not completely implemented because ffmpeg uses
34    only a subset of it. */
35
36 /* used for protocol handling */
37 #define BUFFER_SIZE 1024
38 #define MAX_REDIRECTS 8
39
40 typedef struct {
41     const AVClass *class;
42     URLContext *hd;
43     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
44     int line_count;
45     int http_code;
46     int64_t chunksize;      /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
47     int64_t off, filesize;
48     char location[MAX_URL_SIZE];
49     HTTPAuthState auth_state;
50     unsigned char headers[BUFFER_SIZE];
51     int willclose;          /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
52 } HTTPContext;
53
54 #define OFFSET(x) offsetof(HTTPContext, x)
55 static const AVOption options[] = {
56 {"chunksize", "use chunked transfer-encoding for posts, -1 disables it, 0 enables it", OFFSET(chunksize), FF_OPT_TYPE_INT64, 0, -1, 0 }, /* Default to 0, for chunked POSTs */
57 {NULL}
58 };
59 static const AVClass httpcontext_class = {
60     "HTTP", av_default_item_name, options, LIBAVUTIL_VERSION_INT
61 };
62
63 static int http_connect(URLContext *h, const char *path, const char *hoststr,
64                         const char *auth, int *new_location);
65
66 void ff_http_set_headers(URLContext *h, const char *headers)
67 {
68     HTTPContext *s = h->priv_data;
69     int len = strlen(headers);
70
71     if (len && strcmp("\r\n", headers + len - 2))
72         av_log(NULL, AV_LOG_ERROR, "No trailing CRLF found in HTTP header.\n");
73
74     av_strlcpy(s->headers, headers, sizeof(s->headers));
75 }
76
77 void ff_http_set_chunked_transfer_encoding(URLContext *h, int is_chunked)
78 {
79     ((HTTPContext*)h->priv_data)->chunksize = is_chunked ? 0 : -1;
80 }
81
82 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
83 {
84     memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
85            &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
86 }
87
88 /* return non zero if error */
89 static int http_open_cnx(URLContext *h)
90 {
91     const char *path, *proxy_path;
92     char hostname[1024], hoststr[1024];
93     char auth[1024];
94     char path1[1024];
95     char buf[1024];
96     int port, use_proxy, err, location_changed = 0, redirects = 0;
97     HTTPAuthType cur_auth_type;
98     HTTPContext *s = h->priv_data;
99     URLContext *hd = NULL;
100
101     proxy_path = getenv("http_proxy");
102     use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
103         av_strstart(proxy_path, "http://", NULL);
104
105     /* fill the dest addr */
106  redo:
107     /* needed in any case to build the host string */
108     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
109                  path1, sizeof(path1), s->location);
110     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
111
112     if (use_proxy) {
113         av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
114                      NULL, 0, proxy_path);
115         path = s->location;
116     } else {
117         if (path1[0] == '\0')
118             path = "/";
119         else
120             path = path1;
121     }
122     if (port < 0)
123         port = 80;
124
125     ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
126     err = url_open(&hd, buf, URL_RDWR);
127     if (err < 0)
128         goto fail;
129
130     s->hd = hd;
131     cur_auth_type = s->auth_state.auth_type;
132     if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
133         goto fail;
134     if (s->http_code == 401) {
135         if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
136             url_close(hd);
137             goto redo;
138         } else
139             goto fail;
140     }
141     if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
142         && location_changed == 1) {
143         /* url moved, get next */
144         url_close(hd);
145         if (redirects++ >= MAX_REDIRECTS)
146             return AVERROR(EIO);
147         location_changed = 0;
148         goto redo;
149     }
150     return 0;
151  fail:
152     if (hd)
153         url_close(hd);
154     s->hd = NULL;
155     return AVERROR(EIO);
156 }
157
158 static int http_open(URLContext *h, const char *uri, int flags)
159 {
160     HTTPContext *s = h->priv_data;
161
162     h->is_streamed = 1;
163
164     s->filesize = -1;
165     av_strlcpy(s->location, uri, sizeof(s->location));
166
167     return http_open_cnx(h);
168 }
169 static int http_getc(HTTPContext *s)
170 {
171     int len;
172     if (s->buf_ptr >= s->buf_end) {
173         len = url_read(s->hd, s->buffer, BUFFER_SIZE);
174         if (len < 0) {
175             return AVERROR(EIO);
176         } else if (len == 0) {
177             return -1;
178         } else {
179             s->buf_ptr = s->buffer;
180             s->buf_end = s->buffer + len;
181         }
182     }
183     return *s->buf_ptr++;
184 }
185
186 static int http_get_line(HTTPContext *s, char *line, int line_size)
187 {
188     int ch;
189     char *q;
190
191     q = line;
192     for(;;) {
193         ch = http_getc(s);
194         if (ch < 0)
195             return AVERROR(EIO);
196         if (ch == '\n') {
197             /* process line */
198             if (q > line && q[-1] == '\r')
199                 q--;
200             *q = '\0';
201
202             return 0;
203         } else {
204             if ((q - line) < line_size - 1)
205                 *q++ = ch;
206         }
207     }
208 }
209
210 static int process_line(URLContext *h, char *line, int line_count,
211                         int *new_location)
212 {
213     HTTPContext *s = h->priv_data;
214     char *tag, *p, *end;
215
216     /* end of header */
217     if (line[0] == '\0')
218         return 0;
219
220     p = line;
221     if (line_count == 0) {
222         while (!isspace(*p) && *p != '\0')
223             p++;
224         while (isspace(*p))
225             p++;
226         s->http_code = strtol(p, &end, 10);
227
228         dprintf(NULL, "http_code=%d\n", s->http_code);
229
230         /* error codes are 4xx and 5xx, but regard 401 as a success, so we
231          * don't abort until all headers have been parsed. */
232         if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401) {
233             end += strspn(end, SPACE_CHARS);
234             av_log(NULL, AV_LOG_WARNING, "HTTP error %d %s\n",
235                    s->http_code, end);
236             return -1;
237         }
238     } else {
239         while (*p != '\0' && *p != ':')
240             p++;
241         if (*p != ':')
242             return 1;
243
244         *p = '\0';
245         tag = line;
246         p++;
247         while (isspace(*p))
248             p++;
249         if (!strcmp(tag, "Location")) {
250             strcpy(s->location, p);
251             *new_location = 1;
252         } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
253             s->filesize = atoll(p);
254         } else if (!strcmp (tag, "Content-Range")) {
255             /* "bytes $from-$to/$document_size" */
256             const char *slash;
257             if (!strncmp (p, "bytes ", 6)) {
258                 p += 6;
259                 s->off = atoll(p);
260                 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
261                     s->filesize = atoll(slash+1);
262             }
263             h->is_streamed = 0; /* we _can_ in fact seek */
264         } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
265             s->filesize = -1;
266             s->chunksize = 0;
267         } else if (!strcmp (tag, "WWW-Authenticate")) {
268             ff_http_auth_handle_header(&s->auth_state, tag, p);
269         } else if (!strcmp (tag, "Authentication-Info")) {
270             ff_http_auth_handle_header(&s->auth_state, tag, p);
271         } else if (!strcmp (tag, "Connection")) {
272             if (!strcmp(p, "close"))
273                 s->willclose = 1;
274         }
275     }
276     return 1;
277 }
278
279 static inline int has_header(const char *str, const char *header)
280 {
281     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
282     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
283 }
284
285 static int http_connect(URLContext *h, const char *path, const char *hoststr,
286                         const char *auth, int *new_location)
287 {
288     HTTPContext *s = h->priv_data;
289     int post, err;
290     char line[1024];
291     char headers[1024] = "";
292     char *authstr = NULL;
293     int64_t off = s->off;
294     int len = 0;
295
296
297     /* send http header */
298     post = h->flags & URL_WRONLY;
299     authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
300                                         post ? "POST" : "GET");
301
302     /* set default headers if needed */
303     if (!has_header(s->headers, "\r\nUser-Agent: "))
304        len += av_strlcatf(headers + len, sizeof(headers) - len,
305                           "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
306     if (!has_header(s->headers, "\r\nAccept: "))
307         len += av_strlcpy(headers + len, "Accept: */*\r\n",
308                           sizeof(headers) - len);
309     if (!has_header(s->headers, "\r\nRange: "))
310         len += av_strlcatf(headers + len, sizeof(headers) - len,
311                            "Range: bytes=%"PRId64"-\r\n", s->off);
312     if (!has_header(s->headers, "\r\nConnection: "))
313         len += av_strlcpy(headers + len, "Connection: close\r\n",
314                           sizeof(headers)-len);
315     if (!has_header(s->headers, "\r\nHost: "))
316         len += av_strlcatf(headers + len, sizeof(headers) - len,
317                            "Host: %s\r\n", hoststr);
318
319     /* now add in custom headers */
320     av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
321
322     snprintf(s->buffer, sizeof(s->buffer),
323              "%s %s HTTP/1.1\r\n"
324              "%s"
325              "%s"
326              "%s"
327              "\r\n",
328              post ? "POST" : "GET",
329              path,
330              post && s->chunksize >= 0 ? "Transfer-Encoding: chunked\r\n" : "",
331              headers,
332              authstr ? authstr : "");
333
334     av_freep(&authstr);
335     if (url_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
336         return AVERROR(EIO);
337
338     /* init input buffer */
339     s->buf_ptr = s->buffer;
340     s->buf_end = s->buffer;
341     s->line_count = 0;
342     s->off = 0;
343     s->filesize = -1;
344     s->willclose = 0;
345     if (post) {
346         /* Pretend that it did work. We didn't read any header yet, since
347          * we've still to send the POST data, but the code calling this
348          * function will check http_code after we return. */
349         s->http_code = 200;
350         return 0;
351     }
352     s->chunksize = -1;
353
354     /* wait for header */
355     for(;;) {
356         if (http_get_line(s, line, sizeof(line)) < 0)
357             return AVERROR(EIO);
358
359         dprintf(NULL, "header='%s'\n", line);
360
361         err = process_line(h, line, s->line_count, new_location);
362         if (err < 0)
363             return err;
364         if (err == 0)
365             break;
366         s->line_count++;
367     }
368
369     return (off == s->off) ? 0 : -1;
370 }
371
372
373 static int http_read(URLContext *h, uint8_t *buf, int size)
374 {
375     HTTPContext *s = h->priv_data;
376     int len;
377
378     if (s->chunksize >= 0) {
379         if (!s->chunksize) {
380             char line[32];
381
382             for(;;) {
383                 do {
384                     if (http_get_line(s, line, sizeof(line)) < 0)
385                         return AVERROR(EIO);
386                 } while (!*line);    /* skip CR LF from last chunk */
387
388                 s->chunksize = strtoll(line, NULL, 16);
389
390                 dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
391
392                 if (!s->chunksize)
393                     return 0;
394                 break;
395             }
396         }
397         size = FFMIN(size, s->chunksize);
398     }
399     /* read bytes from input buffer first */
400     len = s->buf_end - s->buf_ptr;
401     if (len > 0) {
402         if (len > size)
403             len = size;
404         memcpy(buf, s->buf_ptr, len);
405         s->buf_ptr += len;
406     } else {
407         if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
408             return AVERROR_EOF;
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->chunksize == -1) {
428         /* non-chunked data is sent without any special encoding */
429         return url_write(s->hd, buf, size);
430     }
431
432     /* silently ignore zero-size data since chunk encoding that would
433      * signal EOF */
434     if (size > 0) {
435         /* upload data using chunked encoding */
436         snprintf(temp, sizeof(temp), "%x\r\n", size);
437
438         if ((ret = url_write(s->hd, temp, strlen(temp))) < 0 ||
439             (ret = url_write(s->hd, buf, size)) < 0 ||
440             (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
441             return ret;
442     }
443     return size;
444 }
445
446 static int http_close(URLContext *h)
447 {
448     int ret = 0;
449     char footer[] = "0\r\n\r\n";
450     HTTPContext *s = h->priv_data;
451
452     /* signal end of chunked encoding if used */
453     if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
454         ret = url_write(s->hd, footer, sizeof(footer) - 1);
455         ret = ret > 0 ? 0 : ret;
456     }
457
458     if (s->hd)
459         url_close(s->hd);
460     return ret;
461 }
462
463 static int64_t http_seek(URLContext *h, int64_t off, int whence)
464 {
465     HTTPContext *s = h->priv_data;
466     URLContext *old_hd = s->hd;
467     int64_t old_off = s->off;
468     uint8_t old_buf[BUFFER_SIZE];
469     int old_buf_size;
470
471     if (whence == AVSEEK_SIZE)
472         return s->filesize;
473     else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
474         return -1;
475
476     /* we save the old context in case the seek fails */
477     old_buf_size = s->buf_end - s->buf_ptr;
478     memcpy(old_buf, s->buf_ptr, old_buf_size);
479     s->hd = NULL;
480     if (whence == SEEK_CUR)
481         off += s->off;
482     else if (whence == SEEK_END)
483         off += s->filesize;
484     s->off = off;
485
486     /* if it fails, continue on old connection */
487     if (http_open_cnx(h) < 0) {
488         memcpy(s->buffer, old_buf, old_buf_size);
489         s->buf_ptr = s->buffer;
490         s->buf_end = s->buffer + old_buf_size;
491         s->hd = old_hd;
492         s->off = old_off;
493         return -1;
494     }
495     url_close(old_hd);
496     return off;
497 }
498
499 static int
500 http_get_file_handle(URLContext *h)
501 {
502     HTTPContext *s = h->priv_data;
503     return url_get_file_handle(s->hd);
504 }
505
506 URLProtocol http_protocol = {
507     "http",
508     http_open,
509     http_read,
510     http_write,
511     http_seek,
512     http_close,
513     .url_get_file_handle = http_get_file_handle,
514     .priv_data_size = sizeof(HTTPContext),
515     .priv_data_class = &httpcontext_class,
516 };