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.

539 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_init_auth_state(URLContext *dest, const URLContext *src)
  72. {
  73. memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
  74. &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
  75. }
  76. /* return non zero if error */
  77. static int http_open_cnx(URLContext *h)
  78. {
  79. const char *path, *proxy_path, *lower_proto = "tcp";
  80. char hostname[1024], hoststr[1024], proto[10];
  81. char auth[1024];
  82. char path1[1024];
  83. char buf[1024];
  84. int port, use_proxy, err, location_changed = 0, redirects = 0;
  85. HTTPAuthType cur_auth_type;
  86. HTTPContext *s = h->priv_data;
  87. URLContext *hd = NULL;
  88. proxy_path = getenv("http_proxy");
  89. use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
  90. av_strstart(proxy_path, "http://", NULL);
  91. /* fill the dest addr */
  92. redo:
  93. /* needed in any case to build the host string */
  94. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  95. 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 (!strcmp(proto, "https")) {
  109. lower_proto = "tls";
  110. if (port < 0)
  111. port = 443;
  112. }
  113. if (port < 0)
  114. port = 80;
  115. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  116. err = ffurl_open(&hd, buf, AVIO_FLAG_READ_WRITE);
  117. if (err < 0)
  118. goto fail;
  119. s->hd = hd;
  120. cur_auth_type = s->auth_state.auth_type;
  121. if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
  122. goto fail;
  123. if (s->http_code == 401) {
  124. if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
  125. ffurl_close(hd);
  126. goto redo;
  127. } else
  128. goto fail;
  129. }
  130. if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
  131. && location_changed == 1) {
  132. /* url moved, get next */
  133. ffurl_close(hd);
  134. if (redirects++ >= MAX_REDIRECTS)
  135. return AVERROR(EIO);
  136. location_changed = 0;
  137. goto redo;
  138. }
  139. return 0;
  140. fail:
  141. if (hd)
  142. ffurl_close(hd);
  143. s->hd = NULL;
  144. return AVERROR(EIO);
  145. }
  146. static int http_open(URLContext *h, const char *uri, int flags)
  147. {
  148. HTTPContext *s = h->priv_data;
  149. h->is_streamed = 1;
  150. s->filesize = -1;
  151. av_strlcpy(s->location, uri, sizeof(s->location));
  152. return http_open_cnx(h);
  153. }
  154. static int http_getc(HTTPContext *s)
  155. {
  156. int len;
  157. if (s->buf_ptr >= s->buf_end) {
  158. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  159. if (len < 0) {
  160. return AVERROR(EIO);
  161. } else if (len == 0) {
  162. return -1;
  163. } else {
  164. s->buf_ptr = s->buffer;
  165. s->buf_end = s->buffer + len;
  166. }
  167. }
  168. return *s->buf_ptr++;
  169. }
  170. static int http_get_line(HTTPContext *s, char *line, int line_size)
  171. {
  172. int ch;
  173. char *q;
  174. q = line;
  175. for(;;) {
  176. ch = http_getc(s);
  177. if (ch < 0)
  178. return AVERROR(EIO);
  179. if (ch == '\n') {
  180. /* process line */
  181. if (q > line && q[-1] == '\r')
  182. q--;
  183. *q = '\0';
  184. return 0;
  185. } else {
  186. if ((q - line) < line_size - 1)
  187. *q++ = ch;
  188. }
  189. }
  190. }
  191. static int process_line(URLContext *h, char *line, int line_count,
  192. int *new_location)
  193. {
  194. HTTPContext *s = h->priv_data;
  195. char *tag, *p, *end;
  196. /* end of header */
  197. if (line[0] == '\0')
  198. return 0;
  199. p = line;
  200. if (line_count == 0) {
  201. while (!isspace(*p) && *p != '\0')
  202. p++;
  203. while (isspace(*p))
  204. p++;
  205. s->http_code = strtol(p, &end, 10);
  206. av_dlog(NULL, "http_code=%d\n", s->http_code);
  207. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  208. * don't abort until all headers have been parsed. */
  209. if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401) {
  210. end += strspn(end, SPACE_CHARS);
  211. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
  212. s->http_code, end);
  213. return -1;
  214. }
  215. } else {
  216. while (*p != '\0' && *p != ':')
  217. p++;
  218. if (*p != ':')
  219. return 1;
  220. *p = '\0';
  221. tag = line;
  222. p++;
  223. while (isspace(*p))
  224. p++;
  225. if (!strcasecmp(tag, "Location")) {
  226. strcpy(s->location, p);
  227. *new_location = 1;
  228. } else if (!strcasecmp (tag, "Content-Length") && s->filesize == -1) {
  229. s->filesize = atoll(p);
  230. } else if (!strcasecmp (tag, "Content-Range")) {
  231. /* "bytes $from-$to/$document_size" */
  232. const char *slash;
  233. if (!strncmp (p, "bytes ", 6)) {
  234. p += 6;
  235. s->off = atoll(p);
  236. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  237. s->filesize = atoll(slash+1);
  238. }
  239. h->is_streamed = 0; /* we _can_ in fact seek */
  240. } else if (!strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) {
  241. h->is_streamed = 0;
  242. } else if (!strcasecmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
  243. s->filesize = -1;
  244. s->chunksize = 0;
  245. } else if (!strcasecmp (tag, "WWW-Authenticate")) {
  246. ff_http_auth_handle_header(&s->auth_state, tag, p);
  247. } else if (!strcasecmp (tag, "Authentication-Info")) {
  248. ff_http_auth_handle_header(&s->auth_state, tag, p);
  249. } else if (!strcasecmp (tag, "Connection")) {
  250. if (!strcmp(p, "close"))
  251. s->willclose = 1;
  252. }
  253. }
  254. return 1;
  255. }
  256. static inline int has_header(const char *str, const char *header)
  257. {
  258. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  259. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  260. }
  261. static int http_connect(URLContext *h, const char *path, const char *hoststr,
  262. const char *auth, int *new_location)
  263. {
  264. HTTPContext *s = h->priv_data;
  265. int post, err;
  266. char line[1024];
  267. char headers[1024] = "";
  268. char *authstr = NULL;
  269. int64_t off = s->off;
  270. int len = 0;
  271. /* send http header */
  272. post = h->flags & AVIO_FLAG_WRITE;
  273. authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
  274. post ? "POST" : "GET");
  275. /* set default headers if needed */
  276. if (!has_header(s->headers, "\r\nUser-Agent: "))
  277. len += av_strlcatf(headers + len, sizeof(headers) - len,
  278. "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
  279. if (!has_header(s->headers, "\r\nAccept: "))
  280. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  281. sizeof(headers) - len);
  282. if (!has_header(s->headers, "\r\nRange: "))
  283. len += av_strlcatf(headers + len, sizeof(headers) - len,
  284. "Range: bytes=%"PRId64"-\r\n", s->off);
  285. if (!has_header(s->headers, "\r\nConnection: "))
  286. len += av_strlcpy(headers + len, "Connection: close\r\n",
  287. sizeof(headers)-len);
  288. if (!has_header(s->headers, "\r\nHost: "))
  289. len += av_strlcatf(headers + len, sizeof(headers) - len,
  290. "Host: %s\r\n", hoststr);
  291. /* now add in custom 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