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.

545 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. || s->auth_state.auth_type != HTTP_AUTH_NONE)) {
  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 (!av_strcasecmp(tag, "Location")) {
  230. strcpy(s->location, p);
  231. *new_location = 1;
  232. } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
  233. s->filesize = atoll(p);
  234. } else if (!av_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 (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) {
  245. h->is_streamed = 0;
  246. } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
  247. s->filesize = -1;
  248. s->chunksize = 0;
  249. } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
  250. ff_http_auth_handle_header(&s->auth_state, tag, p);
  251. } else if (!av_strcasecmp (tag, "Authentication-Info")) {
  252. ff_http_auth_handle_header(&s->auth_state, tag, p);
  253. } else if (!av_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. if (!str)
  264. return 0;
  265. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  266. }
  267. static int http_connect(URLContext *h, const char *path, const char *hoststr,
  268. const char *auth, int *new_location)
  269. {
  270. HTTPContext *s = h->priv_data;
  271. int post, err;
  272. char line[1024];
  273. char headers[1024] = "";
  274. char *authstr = NULL;
  275. int64_t off = s->off;
  276. int len = 0;
  277. /* send http header */
  278. post = h->flags & AVIO_FLAG_WRITE;
  279. authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
  280. post ? "POST" : "GET");
  281. /* set default headers if needed */
  282. if (!has_header(s->headers, "\r\nUser-Agent: "))
  283. len += av_strlcatf(headers + len, sizeof(headers) - len,
  284. "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
  285. if (!has_header(s->headers, "\r\nAccept: "))
  286. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  287. sizeof(headers) - len);
  288. if (!has_header(s->headers, "\r\nRange: ") && !post)
  289. len += av_strlcatf(headers + len, sizeof(headers) - len,
  290. "Range: bytes=%"PRId64"-\r\n", s->off);
  291. if (!has_header(s->headers, "\r\nConnection: "))
  292. len += av_strlcpy(headers + len, "Connection: close\r\n",
  293. sizeof(headers)-len);
  294. if (!has_header(s->headers, "\r\nHost: "))
  295. len += av_strlcatf(headers + len, sizeof(headers) - len,
  296. "Host: %s\r\n", hoststr);
  297. /* now add in custom headers */
  298. if (s->headers)
  299. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  300. snprintf(s->buffer, sizeof(s->buffer),
  301. "%s %s HTTP/1.1\r\n"
  302. "%s"
  303. "%s"
  304. "%s"
  305. "\r\n",
  306. post ? "POST" : "GET",
  307. path,
  308. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  309. headers,
  310. authstr ? authstr : "");
  311. av_freep(&authstr);
  312. if (ffurl_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
  313. return AVERROR(EIO);
  314. /* init input buffer */
  315. s->buf_ptr = s->buffer;
  316. s->buf_end = s->buffer;
  317. s->line_count = 0;
  318. s->off = 0;
  319. s->filesize = -1;
  320. s->willclose = 0;
  321. if (post) {
  322. /* Pretend that it did work. We didn't read any header yet, since
  323. * we've still to send the POST data, but the code calling this
  324. * function will check http_code after we return. */
  325. s->http_code = 200;
  326. return 0;
  327. }
  328. s->chunksize = -1;
  329. /* wait for header */
  330. for(;;) {
  331. if (http_get_line(s, line, sizeof(line)) < 0)
  332. return AVERROR(EIO);
  333. av_dlog(NULL, "header='%s'\n", line);
  334. err = process_line(h, line, s->line_count, new_location);
  335. if (err < 0)
  336. return err;
  337. if (err == 0)
  338. break;
  339. s->line_count++;
  340. }
  341. return (off == s->off) ? 0 : -1;
  342. }
  343. static int http_read(URLContext *h, uint8_t *buf, int size)
  344. {
  345. HTTPContext *s = h->priv_data;
  346. int len;
  347. if (s->chunksize >= 0) {
  348. if (!s->chunksize) {
  349. char line[32];
  350. for(;;) {
  351. do {
  352. if (http_get_line(s, line, sizeof(line)) < 0)
  353. return AVERROR(EIO);
  354. } while (!*line); /* skip CR LF from last chunk */
  355. s->chunksize = strtoll(line, NULL, 16);
  356. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  357. if (!s->chunksize)
  358. return 0;
  359. break;
  360. }
  361. }
  362. size = FFMIN(size, s->chunksize);
  363. }
  364. /* read bytes from input buffer first */
  365. len = s->buf_end - s->buf_ptr;
  366. if (len > 0) {
  367. if (len > size)
  368. len = size;
  369. memcpy(buf, s->buf_ptr, len);
  370. s->buf_ptr += len;
  371. } else {
  372. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  373. return AVERROR_EOF;
  374. len = ffurl_read(s->hd, buf, size);
  375. }
  376. if (len > 0) {
  377. s->off += len;
  378. if (s->chunksize > 0)
  379. s->chunksize -= len;
  380. }
  381. return len;
  382. }
  383. /* used only when posting data */
  384. static int http_write(URLContext *h, const uint8_t *buf, int size)
  385. {
  386. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  387. int ret;
  388. char crlf[] = "\r\n";
  389. HTTPContext *s = h->priv_data;
  390. if (!s->chunked_post) {
  391. /* non-chunked data is sent without any special encoding */
  392. return ffurl_write(s->hd, buf, size);
  393. }
  394. /* silently ignore zero-size data since chunk encoding that would
  395. * signal EOF */
  396. if (size > 0) {
  397. /* upload data using chunked encoding */
  398. snprintf(temp, sizeof(temp), "%x\r\n", size);
  399. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  400. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  401. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  402. return ret;
  403. }
  404. return size;
  405. }
  406. static int http_close(URLContext *h)
  407. {
  408. int ret = 0;
  409. char footer[] = "0\r\n\r\n";
  410. HTTPContext *s = h->priv_data;
  411. /* signal end of chunked encoding if used */
  412. if ((h->flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  413. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  414. ret = ret > 0 ? 0 : ret;
  415. }
  416. if (s->hd)
  417. ffurl_close(s->hd);
  418. return ret;
  419. }
  420. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  421. {
  422. HTTPContext *s = h->priv_data;
  423. URLContext *old_hd = s->hd;
  424. int64_t old_off = s->off;
  425. uint8_t old_buf[BUFFER_SIZE];
  426. int old_buf_size;
  427. if (whence == AVSEEK_SIZE)
  428. return s->filesize;
  429. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  430. return -1;
  431. /* we save the old context in case the seek fails */
  432. old_buf_size = s->buf_end - s->buf_ptr;
  433. memcpy(old_buf, s->buf_ptr, old_buf_size);
  434. s->hd = NULL;
  435. if (whence == SEEK_CUR)
  436. off += s->off;
  437. else if (whence == SEEK_END)
  438. off += s->filesize;
  439. s->off = off;
  440. /* if it fails, continue on old connection */
  441. if (http_open_cnx(h) < 0) {
  442. memcpy(s->buffer, old_buf, old_buf_size);
  443. s->buf_ptr = s->buffer;
  444. s->buf_end = s->buffer + old_buf_size;
  445. s->hd = old_hd;
  446. s->off = old_off;
  447. return -1;
  448. }
  449. ffurl_close(old_hd);
  450. return off;
  451. }
  452. static int
  453. http_get_file_handle(URLContext *h)
  454. {
  455. HTTPContext *s = h->priv_data;
  456. return ffurl_get_file_handle(s->hd);
  457. }
  458. #if CONFIG_HTTP_PROTOCOL
  459. URLProtocol ff_http_protocol = {
  460. .name = "http",
  461. .url_open = http_open,
  462. .url_read = http_read,
  463. .url_write = http_write,
  464. .url_seek = http_seek,
  465. .url_close = http_close,
  466. .url_get_file_handle = http_get_file_handle,
  467. .priv_data_size = sizeof(HTTPContext),
  468. .priv_data_class = &http_context_class,
  469. };
  470. #endif
  471. #if CONFIG_HTTPS_PROTOCOL
  472. URLProtocol ff_https_protocol = {
  473. .name = "https",
  474. .url_open = http_open,
  475. .url_read = http_read,
  476. .url_write = http_write,
  477. .url_seek = http_seek,
  478. .url_close = http_close,
  479. .url_get_file_handle = http_get_file_handle,
  480. .priv_data_size = sizeof(HTTPContext),
  481. .priv_data_class = &https_context_class,
  482. };
  483. #endif