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.

541 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. #define HTTP_CLASS(flavor)\
  56. static const AVClass flavor ## _context_class = {\
  57. .class_name = #flavor,\
  58. .item_name = av_default_item_name,\
  59. .option = options,\
  60. .version = LIBAVUTIL_VERSION_INT,\
  61. };
  62. HTTP_CLASS(http);
  63. HTTP_CLASS(https);
  64. static int http_connect(URLContext *h, const char *path, const char *hoststr,
  65. const char *auth, int *new_location);
  66. void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
  67. {
  68. memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
  69. &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
  70. }
  71. /* return non zero if error */
  72. static int http_open_cnx(URLContext *h)
  73. {
  74. const char *path, *proxy_path, *lower_proto = "tcp";
  75. char hostname[1024], hoststr[1024], proto[10];
  76. char auth[1024];
  77. char path1[1024];
  78. char buf[1024];
  79. int port, use_proxy, err, location_changed = 0, redirects = 0;
  80. HTTPAuthType cur_auth_type;
  81. HTTPContext *s = h->priv_data;
  82. URLContext *hd = NULL;
  83. proxy_path = getenv("http_proxy");
  84. use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
  85. av_strstart(proxy_path, "http://", NULL);
  86. /* fill the dest addr */
  87. redo:
  88. /* needed in any case to build the host string */
  89. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  90. hostname, sizeof(hostname), &port,
  91. path1, sizeof(path1), s->location);
  92. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  93. if (use_proxy) {
  94. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  95. NULL, 0, proxy_path);
  96. path = s->location;
  97. } else {
  98. if (path1[0] == '\0')
  99. path = "/";
  100. else
  101. path = path1;
  102. }
  103. if (!strcmp(proto, "https")) {
  104. lower_proto = "tls";
  105. if (port < 0)
  106. port = 443;
  107. }
  108. if (port < 0)
  109. port = 80;
  110. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  111. err = ffurl_open(&hd, buf, AVIO_FLAG_READ_WRITE);
  112. if (err < 0)
  113. goto fail;
  114. s->hd = hd;
  115. cur_auth_type = s->auth_state.auth_type;
  116. if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
  117. goto fail;
  118. if (s->http_code == 401) {
  119. if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
  120. ffurl_close(hd);
  121. goto redo;
  122. } else
  123. goto fail;
  124. }
  125. if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
  126. && location_changed == 1) {
  127. /* url moved, get next */
  128. ffurl_close(hd);
  129. if (redirects++ >= MAX_REDIRECTS)
  130. return AVERROR(EIO);
  131. location_changed = 0;
  132. goto redo;
  133. }
  134. return 0;
  135. fail:
  136. if (hd)
  137. ffurl_close(hd);
  138. s->hd = NULL;
  139. return AVERROR(EIO);
  140. }
  141. static int http_open(URLContext *h, const char *uri, int flags)
  142. {
  143. HTTPContext *s = h->priv_data;
  144. h->is_streamed = 1;
  145. s->filesize = -1;
  146. av_strlcpy(s->location, uri, sizeof(s->location));
  147. if (s->headers) {
  148. int len = strlen(s->headers);
  149. if (len < 2 || strcmp("\r\n", s->headers + len - 2))
  150. av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
  151. }
  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 (!av_strcasecmp(tag, "Location")) {
  226. strcpy(s->location, p);
  227. *new_location = 1;
  228. } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
  229. s->filesize = atoll(p);
  230. } else if (!av_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 (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) {
  241. h->is_streamed = 0;
  242. } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
  243. s->filesize = -1;
  244. s->chunksize = 0;
  245. } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
  246. ff_http_auth_handle_header(&s->auth_state, tag, p);
  247. } else if (!av_strcasecmp (tag, "Authentication-Info")) {
  248. ff_http_auth_handle_header(&s->auth_state, tag, p);
  249. } else if (!av_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. if (!str)
  260. return 0;
  261. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  262. }
  263. static int http_connect(URLContext *h, const char *path, const char *hoststr,
  264. const char *auth, int *new_location)
  265. {
  266. HTTPContext *s = h->priv_data;
  267. int post, err;
  268. char line[1024];
  269. char headers[1024] = "";
  270. char *authstr = NULL;
  271. int64_t off = s->off;
  272. int len = 0;
  273. /* send http header */
  274. post = h->flags & AVIO_FLAG_WRITE;
  275. authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
  276. post ? "POST" : "GET");
  277. /* set default headers if needed */
  278. if (!has_header(s->headers, "\r\nUser-Agent: "))
  279. len += av_strlcatf(headers + len, sizeof(headers) - len,
  280. "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
  281. if (!has_header(s->headers, "\r\nAccept: "))
  282. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  283. sizeof(headers) - len);
  284. if (!has_header(s->headers, "\r\nRange: "))
  285. len += av_strlcatf(headers + len, sizeof(headers) - len,
  286. "Range: bytes=%"PRId64"-\r\n", s->off);
  287. if (!has_header(s->headers, "\r\nConnection: "))
  288. len += av_strlcpy(headers + len, "Connection: close\r\n",
  289. sizeof(headers)-len);
  290. if (!has_header(s->headers, "\r\nHost: "))
  291. len += av_strlcatf(headers + len, sizeof(headers) - len,
  292. "Host: %s\r\n", hoststr);
  293. /* now add in custom headers */
  294. if (s->headers)
  295. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  296. snprintf(s->buffer, sizeof(s->buffer),
  297. "%s %s HTTP/1.1\r\n"
  298. "%s"
  299. "%s"
  300. "%s"
  301. "\r\n",
  302. post ? "POST" : "GET",
  303. path,
  304. post && s->chunksize >= 0 ? "Transfer-Encoding: chunked\r\n" : "",
  305. headers,
  306. authstr ? authstr : "");
  307. av_freep(&authstr);
  308. if (ffurl_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
  309. return AVERROR(EIO);
  310. /* init input buffer */
  311. s->buf_ptr = s->buffer;
  312. s->buf_end = s->buffer;
  313. s->line_count = 0;
  314. s->off = 0;
  315. s->filesize = -1;
  316. s->willclose = 0;
  317. if (post) {
  318. /* Pretend that it did work. We didn't read any header yet, since
  319. * we've still to send the POST data, but the code calling this
  320. * function will check http_code after we return. */
  321. s->http_code = 200;
  322. return 0;
  323. }
  324. s->chunksize = -1;
  325. /* wait for header */
  326. for(;;) {
  327. if (http_get_line(s, line, sizeof(line)) < 0)
  328. return AVERROR(EIO);
  329. av_dlog(NULL, "header='%s'\n", line);
  330. err = process_line(h, line, s->line_count, new_location);
  331. if (err < 0)
  332. return err;
  333. if (err == 0)
  334. break;
  335. s->line_count++;
  336. }
  337. return (off == s->off) ? 0 : -1;
  338. }
  339. static int http_read(URLContext *h, uint8_t *buf, int size)
  340. {
  341. HTTPContext *s = h->priv_data;
  342. int len;
  343. if (s->chunksize >= 0) {
  344. if (!s->chunksize) {
  345. char line[32];
  346. for(;;) {
  347. do {
  348. if (http_get_line(s, line, sizeof(line)) < 0)
  349. return AVERROR(EIO);
  350. } while (!*line); /* skip CR LF from last chunk */
  351. s->chunksize = strtoll(line, NULL, 16);
  352. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  353. if (!s->chunksize)
  354. return 0;
  355. break;
  356. }
  357. }
  358. size = FFMIN(size, s->chunksize);
  359. }
  360. /* read bytes from input buffer first */
  361. len = s->buf_end - s->buf_ptr;
  362. if (len > 0) {
  363. if (len > size)
  364. len = size;
  365. memcpy(buf, s->buf_ptr, len);
  366. s->buf_ptr += len;
  367. } else {
  368. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  369. return AVERROR_EOF;
  370. len = ffurl_read(s->hd, buf, size);
  371. }
  372. if (len > 0) {
  373. s->off += len;
  374. if (s->chunksize > 0)
  375. s->chunksize -= len;
  376. }
  377. return len;
  378. }
  379. /* used only when posting data */
  380. static int http_write(URLContext *h, const uint8_t *buf, int size)
  381. {
  382. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  383. int ret;
  384. char crlf[] = "\r\n";
  385. HTTPContext *s = h->priv_data;
  386. if (s->chunksize == -1) {
  387. /* non-chunked data is sent without any special encoding */
  388. return ffurl_write(s->hd, buf, size);
  389. }
  390. /* silently ignore zero-size data since chunk encoding that would
  391. * signal EOF */
  392. if (size > 0) {
  393. /* upload data using chunked encoding */
  394. snprintf(temp, sizeof(temp), "%x\r\n", size);
  395. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  396. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  397. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  398. return ret;
  399. }
  400. return size;
  401. }
  402. static int http_close(URLContext *h)
  403. {
  404. int ret = 0;
  405. char footer[] = "0\r\n\r\n";
  406. HTTPContext *s = h->priv_data;
  407. /* signal end of chunked encoding if used */
  408. if ((h->flags & AVIO_FLAG_WRITE) && s->chunksize != -1) {
  409. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  410. ret = ret > 0 ? 0 : ret;
  411. }
  412. if (s->hd)
  413. ffurl_close(s->hd);
  414. return ret;
  415. }
  416. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  417. {
  418. HTTPContext *s = h->priv_data;
  419. URLContext *old_hd = s->hd;
  420. int64_t old_off = s->off;
  421. uint8_t old_buf[BUFFER_SIZE];
  422. int old_buf_size;
  423. if (whence == AVSEEK_SIZE)
  424. return s->filesize;
  425. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  426. return -1;
  427. /* we save the old context in case the seek fails */
  428. old_buf_size = s->buf_end - s->buf_ptr;
  429. memcpy(old_buf, s->buf_ptr, old_buf_size);
  430. s->hd = NULL;
  431. if (whence == SEEK_CUR)
  432. off += s->off;
  433. else if (whence == SEEK_END)
  434. off += s->filesize;
  435. s->off = off;
  436. /* if it fails, continue on old connection */
  437. if (http_open_cnx(h) < 0) {
  438. memcpy(s->buffer, old_buf, old_buf_size);
  439. s->buf_ptr = s->buffer;
  440. s->buf_end = s->buffer + old_buf_size;
  441. s->hd = old_hd;
  442. s->off = old_off;
  443. return -1;
  444. }
  445. ffurl_close(old_hd);
  446. return off;
  447. }
  448. static int
  449. http_get_file_handle(URLContext *h)
  450. {
  451. HTTPContext *s = h->priv_data;
  452. return ffurl_get_file_handle(s->hd);
  453. }
  454. #if CONFIG_HTTP_PROTOCOL
  455. URLProtocol ff_http_protocol = {
  456. .name = "http",
  457. .url_open = http_open,
  458. .url_read = http_read,
  459. .url_write = http_write,
  460. .url_seek = http_seek,
  461. .url_close = http_close,
  462. .url_get_file_handle = http_get_file_handle,
  463. .priv_data_size = sizeof(HTTPContext),
  464. .priv_data_class = &http_context_class,
  465. };
  466. #endif
  467. #if CONFIG_HTTPS_PROTOCOL
  468. URLProtocol ff_https_protocol = {
  469. .name = "https",
  470. .url_open = http_open,
  471. .url_read = http_read,
  472. .url_write = http_write,
  473. .url_seek = http_seek,
  474. .url_close = http_close,
  475. .url_get_file_handle = http_get_file_handle,
  476. .priv_data_size = sizeof(HTTPContext),
  477. .priv_data_class = &https_context_class,
  478. };
  479. #endif