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.

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