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