http.c 15 KB

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