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.

544 lines
16KB

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