]> git.sesse.net Git - ffmpeg/blob - libavformat/http.c
Make RTSP use the generic http authentication code
[ffmpeg] / 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 "os_support.h"
29 #include "httpauth.h"
30
31 /* XXX: POST protocol is not completely implemented because ffmpeg uses
32    only a subset of it. */
33
34 /* used for protocol handling */
35 #define BUFFER_SIZE 1024
36 #define URL_SIZE    4096
37 #define MAX_REDIRECTS 8
38
39 typedef struct {
40     URLContext *hd;
41     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
42     int line_count;
43     int http_code;
44     int64_t chunksize;      /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
45     int64_t off, filesize;
46     char location[URL_SIZE];
47     HTTPAuthState auth_state;
48 } HTTPContext;
49
50 static int http_connect(URLContext *h, const char *path, const char *hoststr,
51                         const char *auth, int *new_location);
52 static int http_write(URLContext *h, uint8_t *buf, int size);
53
54
55 /* return non zero if error */
56 static int http_open_cnx(URLContext *h)
57 {
58     const char *path, *proxy_path;
59     char hostname[1024], hoststr[1024];
60     char auth[1024];
61     char path1[1024];
62     char buf[1024];
63     int port, use_proxy, err, location_changed = 0, redirects = 0;
64     HTTPAuthType cur_auth_type;
65     HTTPContext *s = h->priv_data;
66     URLContext *hd = NULL;
67
68     proxy_path = getenv("http_proxy");
69     use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
70         av_strstart(proxy_path, "http://", NULL);
71
72     /* fill the dest addr */
73  redo:
74     /* needed in any case to build the host string */
75     ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
76                  path1, sizeof(path1), s->location);
77     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
78
79     if (use_proxy) {
80         ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
81                      NULL, 0, proxy_path);
82         path = s->location;
83     } else {
84         if (path1[0] == '\0')
85             path = "/";
86         else
87             path = path1;
88     }
89     if (port < 0)
90         port = 80;
91
92     ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
93     err = url_open(&hd, buf, URL_RDWR);
94     if (err < 0)
95         goto fail;
96
97     s->hd = hd;
98     cur_auth_type = s->auth_state.auth_type;
99     if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
100         goto fail;
101     if (s->http_code == 401) {
102         if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
103             url_close(hd);
104             goto redo;
105         } else
106             goto fail;
107     }
108     if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
109         /* url moved, get next */
110         url_close(hd);
111         if (redirects++ >= MAX_REDIRECTS)
112             return AVERROR(EIO);
113         location_changed = 0;
114         goto redo;
115     }
116     return 0;
117  fail:
118     if (hd)
119         url_close(hd);
120     return AVERROR(EIO);
121 }
122
123 static int http_open(URLContext *h, const char *uri, int flags)
124 {
125     HTTPContext *s;
126     int ret;
127
128     h->is_streamed = 1;
129
130     s = av_malloc(sizeof(HTTPContext));
131     if (!s) {
132         return AVERROR(ENOMEM);
133     }
134     h->priv_data = s;
135     s->filesize = -1;
136     s->chunksize = -1;
137     s->off = 0;
138     memset(&s->auth_state, 0, sizeof(s->auth_state));
139     av_strlcpy(s->location, uri, URL_SIZE);
140
141     ret = http_open_cnx(h);
142     if (ret != 0)
143         av_free (s);
144     return ret;
145 }
146 static int http_getc(HTTPContext *s)
147 {
148     int len;
149     if (s->buf_ptr >= s->buf_end) {
150         len = url_read(s->hd, s->buffer, BUFFER_SIZE);
151         if (len < 0) {
152             return AVERROR(EIO);
153         } else if (len == 0) {
154             return -1;
155         } else {
156             s->buf_ptr = s->buffer;
157             s->buf_end = s->buffer + len;
158         }
159     }
160     return *s->buf_ptr++;
161 }
162
163 static int http_get_line(HTTPContext *s, char *line, int line_size)
164 {
165     int ch;
166     char *q;
167
168     q = line;
169     for(;;) {
170         ch = http_getc(s);
171         if (ch < 0)
172             return AVERROR(EIO);
173         if (ch == '\n') {
174             /* process line */
175             if (q > line && q[-1] == '\r')
176                 q--;
177             *q = '\0';
178
179             return 0;
180         } else {
181             if ((q - line) < line_size - 1)
182                 *q++ = ch;
183         }
184     }
185 }
186
187 static int process_line(URLContext *h, char *line, int line_count,
188                         int *new_location)
189 {
190     HTTPContext *s = h->priv_data;
191     char *tag, *p;
192
193     /* end of header */
194     if (line[0] == '\0')
195         return 0;
196
197     p = line;
198     if (line_count == 0) {
199         while (!isspace(*p) && *p != '\0')
200             p++;
201         while (isspace(*p))
202             p++;
203         s->http_code = strtol(p, NULL, 10);
204
205         dprintf(NULL, "http_code=%d\n", s->http_code);
206
207         /* error codes are 4xx and 5xx, but regard 401 as a success, so we
208          * don't abort until all headers have been parsed. */
209         if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401)
210             return -1;
211     } else {
212         while (*p != '\0' && *p != ':')
213             p++;
214         if (*p != ':')
215             return 1;
216
217         *p = '\0';
218         tag = line;
219         p++;
220         while (isspace(*p))
221             p++;
222         if (!strcmp(tag, "Location")) {
223             strcpy(s->location, p);
224             *new_location = 1;
225         } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
226             s->filesize = atoll(p);
227         } else if (!strcmp (tag, "Content-Range")) {
228             /* "bytes $from-$to/$document_size" */
229             const char *slash;
230             if (!strncmp (p, "bytes ", 6)) {
231                 p += 6;
232                 s->off = atoll(p);
233                 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
234                     s->filesize = atoll(slash+1);
235             }
236             h->is_streamed = 0; /* we _can_ in fact seek */
237         } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
238             s->filesize = -1;
239             s->chunksize = 0;
240         } else if (!strcmp (tag, "WWW-Authenticate")) {
241             ff_http_auth_handle_header(&s->auth_state, tag, p);
242         } else if (!strcmp (tag, "Authentication-Info")) {
243             ff_http_auth_handle_header(&s->auth_state, tag, p);
244         }
245     }
246     return 1;
247 }
248
249 static int http_connect(URLContext *h, const char *path, const char *hoststr,
250                         const char *auth, int *new_location)
251 {
252     HTTPContext *s = h->priv_data;
253     int post, err;
254     char line[1024];
255     char *authstr = NULL;
256     int64_t off = s->off;
257
258
259     /* send http header */
260     post = h->flags & URL_WRONLY;
261     authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
262                                         post ? "POST" : "GET");
263     snprintf(s->buffer, sizeof(s->buffer),
264              "%s %s HTTP/1.1\r\n"
265              "User-Agent: %s\r\n"
266              "Accept: */*\r\n"
267              "Range: bytes=%"PRId64"-\r\n"
268              "Host: %s\r\n"
269              "%s"
270              "Connection: close\r\n"
271              "%s"
272              "\r\n",
273              post ? "POST" : "GET",
274              path,
275              LIBAVFORMAT_IDENT,
276              s->off,
277              hoststr,
278              authstr ? authstr : "",
279              post ? "Transfer-Encoding: chunked\r\n" : "");
280
281     av_freep(&authstr);
282     if (http_write(h, s->buffer, strlen(s->buffer)) < 0)
283         return AVERROR(EIO);
284
285     /* init input buffer */
286     s->buf_ptr = s->buffer;
287     s->buf_end = s->buffer;
288     s->line_count = 0;
289     s->off = 0;
290     s->filesize = -1;
291     if (post) {
292         /* always use chunked encoding for upload data */
293         s->chunksize = 0;
294         return 0;
295     }
296
297     /* wait for header */
298     for(;;) {
299         if (http_get_line(s, line, sizeof(line)) < 0)
300             return AVERROR(EIO);
301
302         dprintf(NULL, "header='%s'\n", line);
303
304         err = process_line(h, line, s->line_count, new_location);
305         if (err < 0)
306             return err;
307         if (err == 0)
308             break;
309         s->line_count++;
310     }
311
312     return (off == s->off) ? 0 : -1;
313 }
314
315
316 static int http_read(URLContext *h, uint8_t *buf, int size)
317 {
318     HTTPContext *s = h->priv_data;
319     int len;
320
321     if (s->chunksize >= 0) {
322         if (!s->chunksize) {
323             char line[32];
324
325             for(;;) {
326                 do {
327                     if (http_get_line(s, line, sizeof(line)) < 0)
328                         return AVERROR(EIO);
329                 } while (!*line);    /* skip CR LF from last chunk */
330
331                 s->chunksize = strtoll(line, NULL, 16);
332
333                 dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
334
335                 if (!s->chunksize)
336                     return 0;
337                 break;
338             }
339         }
340         size = FFMIN(size, s->chunksize);
341     }
342     /* read bytes from input buffer first */
343     len = s->buf_end - s->buf_ptr;
344     if (len > 0) {
345         if (len > size)
346             len = size;
347         memcpy(buf, s->buf_ptr, len);
348         s->buf_ptr += len;
349     } else {
350         len = url_read(s->hd, buf, size);
351     }
352     if (len > 0) {
353         s->off += len;
354         if (s->chunksize > 0)
355             s->chunksize -= len;
356     }
357     return len;
358 }
359
360 /* used only when posting data */
361 static int http_write(URLContext *h, uint8_t *buf, int size)
362 {
363     char temp[11];  /* 32-bit hex + CRLF + nul */
364     int ret;
365     char crlf[] = "\r\n";
366     HTTPContext *s = h->priv_data;
367
368     if (s->chunksize == -1) {
369         /* headers are sent without any special encoding */
370         return url_write(s->hd, buf, size);
371     }
372
373     /* silently ignore zero-size data since chunk encoding that would
374      * signal EOF */
375     if (size > 0) {
376         /* upload data using chunked encoding */
377         snprintf(temp, sizeof(temp), "%x\r\n", size);
378
379         if ((ret = url_write(s->hd, temp, strlen(temp))) < 0 ||
380             (ret = url_write(s->hd, buf, size)) < 0 ||
381             (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
382             return ret;
383     }
384     return size;
385 }
386
387 static int http_close(URLContext *h)
388 {
389     int ret = 0;
390     char footer[] = "0\r\n\r\n";
391     HTTPContext *s = h->priv_data;
392
393     /* signal end of chunked encoding if used */
394     if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
395         ret = url_write(s->hd, footer, sizeof(footer) - 1);
396         ret = ret > 0 ? 0 : ret;
397     }
398
399     url_close(s->hd);
400     av_free(s);
401     return ret;
402 }
403
404 static int64_t http_seek(URLContext *h, int64_t off, int whence)
405 {
406     HTTPContext *s = h->priv_data;
407     URLContext *old_hd = s->hd;
408     int64_t old_off = s->off;
409     uint8_t old_buf[BUFFER_SIZE];
410     int old_buf_size;
411
412     if (whence == AVSEEK_SIZE)
413         return s->filesize;
414     else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
415         return -1;
416
417     /* we save the old context in case the seek fails */
418     old_buf_size = s->buf_end - s->buf_ptr;
419     memcpy(old_buf, s->buf_ptr, old_buf_size);
420     s->hd = NULL;
421     if (whence == SEEK_CUR)
422         off += s->off;
423     else if (whence == SEEK_END)
424         off += s->filesize;
425     s->off = off;
426
427     /* if it fails, continue on old connection */
428     if (http_open_cnx(h) < 0) {
429         memcpy(s->buffer, old_buf, old_buf_size);
430         s->buf_ptr = s->buffer;
431         s->buf_end = s->buffer + old_buf_size;
432         s->hd = old_hd;
433         s->off = old_off;
434         return -1;
435     }
436     url_close(old_hd);
437     return off;
438 }
439
440 static int
441 http_get_file_handle(URLContext *h)
442 {
443     HTTPContext *s = h->priv_data;
444     return url_get_file_handle(s->hd);
445 }
446
447 URLProtocol http_protocol = {
448     "http",
449     http_open,
450     http_read,
451     http_write,
452     http_seek,
453     http_close,
454     .url_get_file_handle = http_get_file_handle,
455 };