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.

574 lines
18KB

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