http.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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 "libavutil/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 MAX_REDIRECTS 8
  36. typedef struct {
  37. const AVClass *class;
  38. URLContext *hd;
  39. unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
  40. int line_count;
  41. int http_code;
  42. int64_t chunksize; /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
  43. int64_t off, filesize;
  44. char location[MAX_URL_SIZE];
  45. HTTPAuthState auth_state;
  46. unsigned char headers[BUFFER_SIZE];
  47. int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
  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 == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
  125. && location_changed == 1) {
  126. /* url moved, get next */
  127. url_close(hd);
  128. if (redirects++ >= MAX_REDIRECTS)
  129. return AVERROR(EIO);
  130. location_changed = 0;
  131. goto redo;
  132. }
  133. return 0;
  134. fail:
  135. if (hd)
  136. url_close(hd);
  137. s->hd = NULL;
  138. return AVERROR(EIO);
  139. }
  140. static int http_open(URLContext *h, const char *uri, int flags)
  141. {
  142. HTTPContext *s = h->priv_data;
  143. h->is_streamed = 1;
  144. s->filesize = -1;
  145. av_strlcpy(s->location, uri, sizeof(s->location));
  146. return http_open_cnx(h);
  147. }
  148. static int http_getc(HTTPContext *s)
  149. {
  150. int len;
  151. if (s->buf_ptr >= s->buf_end) {
  152. len = url_read(s->hd, s->buffer, BUFFER_SIZE);
  153. if (len < 0) {
  154. return AVERROR(EIO);
  155. } else if (len == 0) {
  156. return -1;
  157. } else {
  158. s->buf_ptr = s->buffer;
  159. s->buf_end = s->buffer + len;
  160. }
  161. }
  162. return *s->buf_ptr++;
  163. }
  164. static int http_get_line(HTTPContext *s, char *line, int line_size)
  165. {
  166. int ch;
  167. char *q;
  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. return 0;
  179. } else {
  180. if ((q - line) < line_size - 1)
  181. *q++ = ch;
  182. }
  183. }
  184. }
  185. static int process_line(URLContext *h, char *line, int line_count,
  186. int *new_location)
  187. {
  188. HTTPContext *s = h->priv_data;
  189. char *tag, *p, *end;
  190. /* end of header */
  191. if (line[0] == '\0')
  192. return 0;
  193. p = line;
  194. if (line_count == 0) {
  195. while (!isspace(*p) && *p != '\0')
  196. p++;
  197. while (isspace(*p))
  198. p++;
  199. s->http_code = strtol(p, &end, 10);
  200. dprintf(NULL, "http_code=%d\n", s->http_code);
  201. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  202. * don't abort until all headers have been parsed. */
  203. if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401) {
  204. end += strspn(end, SPACE_CHARS);
  205. av_log(NULL, AV_LOG_WARNING, "HTTP error %d %s\n",
  206. s->http_code, end);
  207. return -1;
  208. }
  209. } else {
  210. while (*p != '\0' && *p != ':')
  211. p++;
  212. if (*p != ':')
  213. return 1;
  214. *p = '\0';
  215. tag = line;
  216. p++;
  217. while (isspace(*p))
  218. p++;
  219. if (!strcmp(tag, "Location")) {
  220. strcpy(s->location, p);
  221. *new_location = 1;
  222. } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
  223. s->filesize = atoll(p);
  224. } else if (!strcmp (tag, "Content-Range")) {
  225. /* "bytes $from-$to/$document_size" */
  226. const char *slash;
  227. if (!strncmp (p, "bytes ", 6)) {
  228. p += 6;
  229. s->off = atoll(p);
  230. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  231. s->filesize = atoll(slash+1);
  232. }
  233. h->is_streamed = 0; /* we _can_ in fact seek */
  234. } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
  235. s->filesize = -1;
  236. s->chunksize = 0;
  237. } else if (!strcmp (tag, "WWW-Authenticate")) {
  238. ff_http_auth_handle_header(&s->auth_state, tag, p);
  239. } else if (!strcmp (tag, "Authentication-Info")) {
  240. ff_http_auth_handle_header(&s->auth_state, tag, p);
  241. } else if (!strcmp (tag, "Connection")) {
  242. if (!strcmp(p, "close"))
  243. s->willclose = 1;
  244. }
  245. }
  246. return 1;
  247. }
  248. static inline int has_header(const char *str, const char *header)
  249. {
  250. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  251. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  252. }
  253. static int http_connect(URLContext *h, const char *path, const char *hoststr,
  254. const char *auth, int *new_location)
  255. {
  256. HTTPContext *s = h->priv_data;
  257. int post, err;
  258. char line[1024];
  259. char headers[1024] = "";
  260. char *authstr = NULL;
  261. int64_t off = s->off;
  262. int len = 0;
  263. /* send http header */
  264. post = h->flags & URL_WRONLY;
  265. authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
  266. post ? "POST" : "GET");
  267. /* set default headers if needed */
  268. if (!has_header(s->headers, "\r\nUser-Agent: "))
  269. len += av_strlcatf(headers + len, sizeof(headers) - len,
  270. "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
  271. if (!has_header(s->headers, "\r\nAccept: "))
  272. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  273. sizeof(headers) - len);
  274. if (!has_header(s->headers, "\r\nRange: "))
  275. len += av_strlcatf(headers + len, sizeof(headers) - len,
  276. "Range: bytes=%"PRId64"-\r\n", s->off);
  277. if (!has_header(s->headers, "\r\nConnection: "))
  278. len += av_strlcpy(headers + len, "Connection: close\r\n",
  279. sizeof(headers)-len);
  280. if (!has_header(s->headers, "\r\nHost: "))
  281. len += av_strlcatf(headers + len, sizeof(headers) - len,
  282. "Host: %s\r\n", hoststr);
  283. /* now add in custom headers */
  284. av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
  285. snprintf(s->buffer, sizeof(s->buffer),
  286. "%s %s HTTP/1.1\r\n"
  287. "%s"
  288. "%s"
  289. "%s"
  290. "\r\n",
  291. post ? "POST" : "GET",
  292. path,
  293. post && s->chunksize >= 0 ? "Transfer-Encoding: chunked\r\n" : "",
  294. headers,
  295. authstr ? authstr : "");
  296. av_freep(&authstr);
  297. if (url_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
  298. return AVERROR(EIO);
  299. /* init input buffer */
  300. s->buf_ptr = s->buffer;
  301. s->buf_end = s->buffer;
  302. s->line_count = 0;
  303. s->off = 0;
  304. s->filesize = -1;
  305. s->willclose = 0;
  306. if (post) {
  307. /* Pretend that it did work. We didn't read any header yet, since
  308. * we've still to send the POST data, but the code calling this
  309. * function will check http_code after we return. */
  310. s->http_code = 200;
  311. return 0;
  312. }
  313. s->chunksize = -1;
  314. /* wait for header */
  315. for(;;) {
  316. if (http_get_line(s, line, sizeof(line)) < 0)
  317. return AVERROR(EIO);
  318. dprintf(NULL, "header='%s'\n", line);
  319. err = process_line(h, line, s->line_count, new_location);
  320. if (err < 0)
  321. return err;
  322. if (err == 0)
  323. break;
  324. s->line_count++;
  325. }
  326. return (off == s->off) ? 0 : -1;
  327. }
  328. static int http_read(URLContext *h, uint8_t *buf, int size)
  329. {
  330. HTTPContext *s = h->priv_data;
  331. int len;
  332. if (s->chunksize >= 0) {
  333. if (!s->chunksize) {
  334. char line[32];
  335. for(;;) {
  336. do {
  337. if (http_get_line(s, line, sizeof(line)) < 0)
  338. return AVERROR(EIO);
  339. } while (!*line); /* skip CR LF from last chunk */
  340. s->chunksize = strtoll(line, NULL, 16);
  341. dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  342. if (!s->chunksize)
  343. return 0;
  344. break;
  345. }
  346. }
  347. size = FFMIN(size, s->chunksize);
  348. }
  349. /* read bytes from input buffer first */
  350. len = s->buf_end - s->buf_ptr;
  351. if (len > 0) {
  352. if (len > size)
  353. len = size;
  354. memcpy(buf, s->buf_ptr, len);
  355. s->buf_ptr += len;
  356. } else {
  357. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  358. return AVERROR_EOF;
  359. len = url_read(s->hd, buf, size);
  360. }
  361. if (len > 0) {
  362. s->off += len;
  363. if (s->chunksize > 0)
  364. s->chunksize -= len;
  365. }
  366. return len;
  367. }
  368. /* used only when posting data */
  369. static int http_write(URLContext *h, const uint8_t *buf, int size)
  370. {
  371. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  372. int ret;
  373. char crlf[] = "\r\n";
  374. HTTPContext *s = h->priv_data;
  375. if (s->chunksize == -1) {
  376. /* non-chunked data is sent without any special encoding */
  377. return url_write(s->hd, buf, size);
  378. }
  379. /* silently ignore zero-size data since chunk encoding that would
  380. * signal EOF */
  381. if (size > 0) {
  382. /* upload data using chunked encoding */
  383. snprintf(temp, sizeof(temp), "%x\r\n", size);
  384. if ((ret = url_write(s->hd, temp, strlen(temp))) < 0 ||
  385. (ret = url_write(s->hd, buf, size)) < 0 ||
  386. (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  387. return ret;
  388. }
  389. return size;
  390. }
  391. static int http_close(URLContext *h)
  392. {
  393. int ret = 0;
  394. char footer[] = "0\r\n\r\n";
  395. HTTPContext *s = h->priv_data;
  396. /* signal end of chunked encoding if used */
  397. if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
  398. ret = url_write(s->hd, footer, sizeof(footer) - 1);
  399. ret = ret > 0 ? 0 : ret;
  400. }
  401. if (s->hd)
  402. url_close(s->hd);
  403. return ret;
  404. }
  405. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  406. {
  407. HTTPContext *s = h->priv_data;
  408. URLContext *old_hd = s->hd;
  409. int64_t old_off = s->off;
  410. uint8_t old_buf[BUFFER_SIZE];
  411. int old_buf_size;
  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. /* we save the old context in case the seek fails */
  417. old_buf_size = s->buf_end - s->buf_ptr;
  418. memcpy(old_buf, s->buf_ptr, old_buf_size);
  419. s->hd = NULL;
  420. if (whence == SEEK_CUR)
  421. off += s->off;
  422. else if (whence == SEEK_END)
  423. off += s->filesize;
  424. s->off = off;
  425. /* if it fails, continue on old connection */
  426. if (http_open_cnx(h) < 0) {
  427. memcpy(s->buffer, old_buf, old_buf_size);
  428. s->buf_ptr = s->buffer;
  429. s->buf_end = s->buffer + old_buf_size;
  430. s->hd = old_hd;
  431. s->off = old_off;
  432. return -1;
  433. }
  434. url_close(old_hd);
  435. return off;
  436. }
  437. static int
  438. http_get_file_handle(URLContext *h)
  439. {
  440. HTTPContext *s = h->priv_data;
  441. return url_get_file_handle(s->hd);
  442. }
  443. URLProtocol ff_http_protocol = {
  444. "http",
  445. http_open,
  446. http_read,
  447. http_write,
  448. http_seek,
  449. http_close,
  450. .url_get_file_handle = http_get_file_handle,
  451. .priv_data_size = sizeof(HTTPContext),
  452. .priv_data_class = &httpcontext_class,
  453. };