You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

518 lines
15KB

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