http.c 15 KB

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