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