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.

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