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.

1000 lines
34KB

  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 "internal.h"
  24. #include "network.h"
  25. #include "http.h"
  26. #include "os_support.h"
  27. #include "httpauth.h"
  28. #include "url.h"
  29. #include "libavutil/opt.h"
  30. /* XXX: POST protocol is not completely implemented because ffmpeg uses
  31. only a subset of it. */
  32. /* The IO buffer size is unrelated to the max URL size in itself, but needs
  33. * to be large enough to fit the full request headers (including long
  34. * path names).
  35. */
  36. #define BUFFER_SIZE MAX_URL_SIZE
  37. #define MAX_REDIRECTS 8
  38. typedef struct {
  39. const AVClass *class;
  40. URLContext *hd;
  41. unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
  42. int line_count;
  43. int http_code;
  44. int64_t chunksize; /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
  45. char *content_type;
  46. char *user_agent;
  47. int64_t off, filesize;
  48. int icy_data_read; ///< how much data was read since last ICY metadata packet
  49. int icy_metaint; ///< after how many bytes of read data a new metadata packet will be found
  50. char location[MAX_URL_SIZE];
  51. HTTPAuthState auth_state;
  52. HTTPAuthState proxy_auth_state;
  53. char *headers;
  54. int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
  55. int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
  56. int chunked_post;
  57. int end_chunked_post; /**< A flag which indicates if the end of chunked encoding has been sent. */
  58. int end_header; /**< A flag which indicates we have finished to read POST reply. */
  59. int multiple_requests; /**< A flag which indicates if we use persistent connections. */
  60. uint8_t *post_data;
  61. int post_datalen;
  62. int is_akamai;
  63. int rw_timeout;
  64. char *mime_type;
  65. char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
  66. int icy;
  67. char *icy_metadata_headers;
  68. char *icy_metadata_packet;
  69. } HTTPContext;
  70. #define OFFSET(x) offsetof(HTTPContext, x)
  71. #define D AV_OPT_FLAG_DECODING_PARAM
  72. #define E AV_OPT_FLAG_ENCODING_PARAM
  73. #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
  74. static const AVOption options[] = {
  75. {"seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
  76. {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
  77. {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  78. {"content_type", "force a content type", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  79. {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
  80. {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
  81. {"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
  82. {"timeout", "set timeout of socket I/O operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
  83. {"mime_type", "set MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
  84. {"cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
  85. {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
  86. {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
  87. {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
  88. {NULL}
  89. };
  90. #define HTTP_CLASS(flavor)\
  91. static const AVClass flavor ## _context_class = {\
  92. .class_name = #flavor,\
  93. .item_name = av_default_item_name,\
  94. .option = options,\
  95. .version = LIBAVUTIL_VERSION_INT,\
  96. }
  97. HTTP_CLASS(http);
  98. HTTP_CLASS(https);
  99. static int http_connect(URLContext *h, const char *path, const char *local_path,
  100. const char *hoststr, const char *auth,
  101. const char *proxyauth, int *new_location);
  102. void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
  103. {
  104. memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
  105. &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
  106. memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
  107. &((HTTPContext*)src->priv_data)->proxy_auth_state,
  108. sizeof(HTTPAuthState));
  109. }
  110. /* return non zero if error */
  111. static int http_open_cnx(URLContext *h)
  112. {
  113. const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
  114. char hostname[1024], hoststr[1024], proto[10];
  115. char auth[1024], proxyauth[1024] = "";
  116. char path1[MAX_URL_SIZE];
  117. char buf[1024], urlbuf[MAX_URL_SIZE];
  118. int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
  119. HTTPAuthType cur_auth_type, cur_proxy_auth_type;
  120. HTTPContext *s = h->priv_data;
  121. /* fill the dest addr */
  122. redo:
  123. /* needed in any case to build the host string */
  124. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  125. hostname, sizeof(hostname), &port,
  126. path1, sizeof(path1), s->location);
  127. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  128. proxy_path = getenv("http_proxy");
  129. use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
  130. proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
  131. if (!strcmp(proto, "https")) {
  132. lower_proto = "tls";
  133. use_proxy = 0;
  134. if (port < 0)
  135. port = 443;
  136. }
  137. if (port < 0)
  138. port = 80;
  139. if (path1[0] == '\0')
  140. path = "/";
  141. else
  142. path = path1;
  143. local_path = path;
  144. if (use_proxy) {
  145. /* Reassemble the request URL without auth string - we don't
  146. * want to leak the auth to the proxy. */
  147. ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
  148. path1);
  149. path = urlbuf;
  150. av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
  151. hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
  152. }
  153. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  154. if (!s->hd) {
  155. AVDictionary *opts = NULL;
  156. char opts_format[20];
  157. if (s->rw_timeout != -1) {
  158. snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
  159. av_dict_set(&opts, "timeout", opts_format, 0);
  160. } /* if option is not given, don't pass it and let tcp use its own default */
  161. err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
  162. &h->interrupt_callback, &opts);
  163. av_dict_free(&opts);
  164. if (err < 0)
  165. goto fail;
  166. }
  167. cur_auth_type = s->auth_state.auth_type;
  168. cur_proxy_auth_type = s->auth_state.auth_type;
  169. if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
  170. goto fail;
  171. attempts++;
  172. if (s->http_code == 401) {
  173. if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
  174. s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  175. ffurl_closep(&s->hd);
  176. goto redo;
  177. } else
  178. goto fail;
  179. }
  180. if (s->http_code == 407) {
  181. if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  182. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  183. ffurl_closep(&s->hd);
  184. goto redo;
  185. } else
  186. goto fail;
  187. }
  188. if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
  189. && location_changed == 1) {
  190. /* url moved, get next */
  191. ffurl_closep(&s->hd);
  192. if (redirects++ >= MAX_REDIRECTS)
  193. return AVERROR(EIO);
  194. /* Restart the authentication process with the new target, which
  195. * might use a different auth mechanism. */
  196. memset(&s->auth_state, 0, sizeof(s->auth_state));
  197. attempts = 0;
  198. location_changed = 0;
  199. goto redo;
  200. }
  201. return 0;
  202. fail:
  203. if (s->hd)
  204. ffurl_closep(&s->hd);
  205. return AVERROR(EIO);
  206. }
  207. int ff_http_do_new_request(URLContext *h, const char *uri)
  208. {
  209. HTTPContext *s = h->priv_data;
  210. s->off = 0;
  211. s->icy_data_read = 0;
  212. av_strlcpy(s->location, uri, sizeof(s->location));
  213. return http_open_cnx(h);
  214. }
  215. static int http_open(URLContext *h, const char *uri, int flags)
  216. {
  217. HTTPContext *s = h->priv_data;
  218. if( s->seekable == 1 )
  219. h->is_streamed = 0;
  220. else
  221. h->is_streamed = 1;
  222. s->filesize = -1;
  223. av_strlcpy(s->location, uri, sizeof(s->location));
  224. if (s->headers) {
  225. int len = strlen(s->headers);
  226. if (len < 2 || strcmp("\r\n", s->headers + len - 2))
  227. av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
  228. }
  229. return http_open_cnx(h);
  230. }
  231. static int http_getc(HTTPContext *s)
  232. {
  233. int len;
  234. if (s->buf_ptr >= s->buf_end) {
  235. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  236. if (len < 0) {
  237. return len;
  238. } else if (len == 0) {
  239. return -1;
  240. } else {
  241. s->buf_ptr = s->buffer;
  242. s->buf_end = s->buffer + len;
  243. }
  244. }
  245. return *s->buf_ptr++;
  246. }
  247. static int http_get_line(HTTPContext *s, char *line, int line_size)
  248. {
  249. int ch;
  250. char *q;
  251. q = line;
  252. for(;;) {
  253. ch = http_getc(s);
  254. if (ch < 0)
  255. return ch;
  256. if (ch == '\n') {
  257. /* process line */
  258. if (q > line && q[-1] == '\r')
  259. q--;
  260. *q = '\0';
  261. return 0;
  262. } else {
  263. if ((q - line) < line_size - 1)
  264. *q++ = ch;
  265. }
  266. }
  267. }
  268. static int process_line(URLContext *h, char *line, int line_count,
  269. int *new_location)
  270. {
  271. HTTPContext *s = h->priv_data;
  272. char *tag, *p, *end;
  273. char redirected_location[MAX_URL_SIZE];
  274. /* end of header */
  275. if (line[0] == '\0') {
  276. s->end_header = 1;
  277. return 0;
  278. }
  279. p = line;
  280. if (line_count == 0) {
  281. while (!av_isspace(*p) && *p != '\0')
  282. p++;
  283. while (av_isspace(*p))
  284. p++;
  285. s->http_code = strtol(p, &end, 10);
  286. av_dlog(NULL, "http_code=%d\n", s->http_code);
  287. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  288. * don't abort until all headers have been parsed. */
  289. if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
  290. || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  291. (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  292. end += strspn(end, SPACE_CHARS);
  293. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
  294. s->http_code, end);
  295. return -1;
  296. }
  297. } else {
  298. while (*p != '\0' && *p != ':')
  299. p++;
  300. if (*p != ':')
  301. return 1;
  302. *p = '\0';
  303. tag = line;
  304. p++;
  305. while (av_isspace(*p))
  306. p++;
  307. if (!av_strcasecmp(tag, "Location")) {
  308. ff_make_absolute_url(redirected_location, sizeof(redirected_location), s->location, p);
  309. av_strlcpy(s->location, redirected_location, sizeof(s->location));
  310. *new_location = 1;
  311. } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
  312. s->filesize = strtoll(p, NULL, 10);
  313. } else if (!av_strcasecmp (tag, "Content-Range")) {
  314. /* "bytes $from-$to/$document_size" */
  315. const char *slash;
  316. if (!strncmp (p, "bytes ", 6)) {
  317. p += 6;
  318. s->off = strtoll(p, NULL, 10);
  319. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  320. s->filesize = strtoll(slash+1, NULL, 10);
  321. }
  322. if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
  323. h->is_streamed = 0; /* we _can_ in fact seek */
  324. } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
  325. h->is_streamed = 0;
  326. } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
  327. s->filesize = -1;
  328. s->chunksize = 0;
  329. } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
  330. ff_http_auth_handle_header(&s->auth_state, tag, p);
  331. } else if (!av_strcasecmp (tag, "Authentication-Info")) {
  332. ff_http_auth_handle_header(&s->auth_state, tag, p);
  333. } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
  334. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  335. } else if (!av_strcasecmp (tag, "Connection")) {
  336. if (!strcmp(p, "close"))
  337. s->willclose = 1;
  338. } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
  339. s->is_akamai = 1;
  340. } else if (!av_strcasecmp (tag, "Content-Type")) {
  341. av_free(s->mime_type); s->mime_type = av_strdup(p);
  342. } else if (!av_strcasecmp (tag, "Set-Cookie")) {
  343. if (!s->cookies) {
  344. if (!(s->cookies = av_strdup(p)))
  345. return AVERROR(ENOMEM);
  346. } else {
  347. char *tmp = s->cookies;
  348. size_t str_size = strlen(tmp) + strlen(p) + 2;
  349. if (!(s->cookies = av_malloc(str_size))) {
  350. s->cookies = tmp;
  351. return AVERROR(ENOMEM);
  352. }
  353. snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
  354. av_free(tmp);
  355. }
  356. } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
  357. s->icy_metaint = strtoll(p, NULL, 10);
  358. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  359. // Concat all Icy- header lines
  360. char *buf = av_asprintf("%s%s: %s\n",
  361. s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
  362. if (!buf)
  363. return AVERROR(ENOMEM);
  364. av_freep(&s->icy_metadata_headers);
  365. s->icy_metadata_headers = buf;
  366. }
  367. }
  368. return 1;
  369. }
  370. /**
  371. * Create a string containing cookie values for use as a HTTP cookie header
  372. * field value for a particular path and domain from the cookie values stored in
  373. * the HTTP protocol context. The cookie string is stored in *cookies.
  374. *
  375. * @return a negative value if an error condition occurred, 0 otherwise
  376. */
  377. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  378. const char *domain)
  379. {
  380. // cookie strings will look like Set-Cookie header field values. Multiple
  381. // Set-Cookie fields will result in multiple values delimited by a newline
  382. int ret = 0;
  383. char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
  384. if (!set_cookies) return AVERROR(EINVAL);
  385. *cookies = NULL;
  386. while ((cookie = av_strtok(set_cookies, "\n", &next))) {
  387. int domain_offset = 0;
  388. char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
  389. set_cookies = NULL;
  390. while ((param = av_strtok(cookie, "; ", &next_param))) {
  391. cookie = NULL;
  392. if (!av_strncasecmp("path=", param, 5)) {
  393. av_free(cpath);
  394. cpath = av_strdup(&param[5]);
  395. } else if (!av_strncasecmp("domain=", param, 7)) {
  396. av_free(cdomain);
  397. cdomain = av_strdup(&param[7]);
  398. } else if (!av_strncasecmp("secure", param, 6) ||
  399. !av_strncasecmp("comment", param, 7) ||
  400. !av_strncasecmp("max-age", param, 7) ||
  401. !av_strncasecmp("version", param, 7)) {
  402. // ignore Comment, Max-Age, Secure and Version
  403. } else {
  404. av_free(cvalue);
  405. cvalue = av_strdup(param);
  406. }
  407. }
  408. if (!cdomain)
  409. cdomain = av_strdup(domain);
  410. // ensure all of the necessary values are valid
  411. if (!cdomain || !cpath || !cvalue) {
  412. av_log(s, AV_LOG_WARNING,
  413. "Invalid cookie found, no value, path or domain specified\n");
  414. goto done_cookie;
  415. }
  416. // check if the request path matches the cookie path
  417. if (av_strncasecmp(path, cpath, strlen(cpath)))
  418. goto done_cookie;
  419. // the domain should be at least the size of our cookie domain
  420. domain_offset = strlen(domain) - strlen(cdomain);
  421. if (domain_offset < 0)
  422. goto done_cookie;
  423. // match the cookie domain
  424. if (av_strcasecmp(&domain[domain_offset], cdomain))
  425. goto done_cookie;
  426. // cookie parameters match, so copy the value
  427. if (!*cookies) {
  428. if (!(*cookies = av_strdup(cvalue))) {
  429. ret = AVERROR(ENOMEM);
  430. goto done_cookie;
  431. }
  432. } else {
  433. char *tmp = *cookies;
  434. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  435. if (!(*cookies = av_malloc(str_size))) {
  436. ret = AVERROR(ENOMEM);
  437. goto done_cookie;
  438. }
  439. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  440. av_free(tmp);
  441. }
  442. done_cookie:
  443. av_free(cdomain);
  444. av_free(cpath);
  445. av_free(cvalue);
  446. if (ret < 0) {
  447. if (*cookies) av_freep(cookies);
  448. av_free(cset_cookies);
  449. return ret;
  450. }
  451. }
  452. av_free(cset_cookies);
  453. return 0;
  454. }
  455. static inline int has_header(const char *str, const char *header)
  456. {
  457. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  458. if (!str)
  459. return 0;
  460. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  461. }
  462. static int http_read_header(URLContext *h, int *new_location)
  463. {
  464. HTTPContext *s = h->priv_data;
  465. char line[MAX_URL_SIZE];
  466. int err = 0;
  467. s->chunksize = -1;
  468. for (;;) {
  469. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  470. return err;
  471. av_dlog(NULL, "header='%s'\n", line);
  472. err = process_line(h, line, s->line_count, new_location);
  473. if (err < 0)
  474. return err;
  475. if (err == 0)
  476. break;
  477. s->line_count++;
  478. }
  479. return err;
  480. }
  481. static int http_connect(URLContext *h, const char *path, const char *local_path,
  482. const char *hoststr, const char *auth,
  483. const char *proxyauth, int *new_location)
  484. {
  485. HTTPContext *s = h->priv_data;
  486. int post, err;
  487. char headers[4096] = "";
  488. char *authstr = NULL, *proxyauthstr = NULL;
  489. int64_t off = s->off;
  490. int len = 0;
  491. const char *method;
  492. /* send http header */
  493. post = h->flags & AVIO_FLAG_WRITE;
  494. if (s->post_data) {
  495. /* force POST method and disable chunked encoding when
  496. * custom HTTP post data is set */
  497. post = 1;
  498. s->chunked_post = 0;
  499. }
  500. method = post ? "POST" : "GET";
  501. authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
  502. method);
  503. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  504. local_path, method);
  505. /* set default headers if needed */
  506. if (!has_header(s->headers, "\r\nUser-Agent: "))
  507. len += av_strlcatf(headers + len, sizeof(headers) - len,
  508. "User-Agent: %s\r\n", s->user_agent);
  509. if (!has_header(s->headers, "\r\nAccept: "))
  510. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  511. sizeof(headers) - len);
  512. // Note: we send this on purpose even when s->off is 0 when we're probing,
  513. // since it allows us to detect more reliably if a (non-conforming)
  514. // server supports seeking by analysing the reply headers.
  515. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
  516. len += av_strlcatf(headers + len, sizeof(headers) - len,
  517. "Range: bytes=%"PRId64"-\r\n", s->off);
  518. if (!has_header(s->headers, "\r\nConnection: ")) {
  519. if (s->multiple_requests) {
  520. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  521. sizeof(headers) - len);
  522. } else {
  523. len += av_strlcpy(headers + len, "Connection: close\r\n",
  524. sizeof(headers) - len);
  525. }
  526. }
  527. if (!has_header(s->headers, "\r\nHost: "))
  528. len += av_strlcatf(headers + len, sizeof(headers) - len,
  529. "Host: %s\r\n", hoststr);
  530. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  531. len += av_strlcatf(headers + len, sizeof(headers) - len,
  532. "Content-Length: %d\r\n", s->post_datalen);
  533. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  534. len += av_strlcatf(headers + len, sizeof(headers) - len,
  535. "Content-Type: %s\r\n", s->content_type);
  536. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  537. char *cookies = NULL;
  538. if (!get_cookies(s, &cookies, path, hoststr)) {
  539. len += av_strlcatf(headers + len, sizeof(headers) - len,
  540. "Cookie: %s\r\n", cookies);
  541. av_free(cookies);
  542. }
  543. }
  544. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
  545. len += av_strlcatf(headers + len, sizeof(headers) - len,
  546. "Icy-MetaData: %d\r\n", 1);
  547. }
  548. /* now add in custom headers */
  549. if (s->headers)
  550. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  551. snprintf(s->buffer, sizeof(s->buffer),
  552. "%s %s HTTP/1.1\r\n"
  553. "%s"
  554. "%s"
  555. "%s"
  556. "%s%s"
  557. "\r\n",
  558. method,
  559. path,
  560. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  561. headers,
  562. authstr ? authstr : "",
  563. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  564. av_freep(&authstr);
  565. av_freep(&proxyauthstr);
  566. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  567. return err;
  568. if (s->post_data)
  569. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  570. return err;
  571. /* init input buffer */
  572. s->buf_ptr = s->buffer;
  573. s->buf_end = s->buffer;
  574. s->line_count = 0;
  575. s->off = 0;
  576. s->icy_data_read = 0;
  577. s->filesize = -1;
  578. s->willclose = 0;
  579. s->end_chunked_post = 0;
  580. s->end_header = 0;
  581. if (post && !s->post_data) {
  582. /* Pretend that it did work. We didn't read any header yet, since
  583. * we've still to send the POST data, but the code calling this
  584. * function will check http_code after we return. */
  585. s->http_code = 200;
  586. return 0;
  587. }
  588. /* wait for header */
  589. err = http_read_header(h, new_location);
  590. if (err < 0)
  591. return err;
  592. return (off == s->off) ? 0 : -1;
  593. }
  594. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  595. {
  596. HTTPContext *s = h->priv_data;
  597. int len;
  598. /* read bytes from input buffer first */
  599. len = s->buf_end - s->buf_ptr;
  600. if (len > 0) {
  601. if (len > size)
  602. len = size;
  603. memcpy(buf, s->buf_ptr, len);
  604. s->buf_ptr += len;
  605. } else {
  606. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  607. return AVERROR_EOF;
  608. len = ffurl_read(s->hd, buf, size);
  609. }
  610. if (len > 0) {
  611. s->off += len;
  612. s->icy_data_read += len;
  613. if (s->chunksize > 0)
  614. s->chunksize -= len;
  615. }
  616. return len;
  617. }
  618. static int http_read(URLContext *h, uint8_t *buf, int size)
  619. {
  620. HTTPContext *s = h->priv_data;
  621. int err, new_location;
  622. if (!s->hd)
  623. return AVERROR_EOF;
  624. if (s->end_chunked_post && !s->end_header) {
  625. err = http_read_header(h, &new_location);
  626. if (err < 0)
  627. return err;
  628. }
  629. if (s->chunksize >= 0) {
  630. if (!s->chunksize) {
  631. char line[32];
  632. for(;;) {
  633. do {
  634. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  635. return err;
  636. } while (!*line); /* skip CR LF from last chunk */
  637. s->chunksize = strtoll(line, NULL, 16);
  638. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  639. if (!s->chunksize)
  640. return 0;
  641. break;
  642. }
  643. }
  644. size = FFMIN(size, s->chunksize);
  645. }
  646. if (s->icy_metaint > 0) {
  647. int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
  648. if (!remaining) {
  649. // The metadata packet is variable sized. It has a 1 byte header
  650. // which sets the length of the packet (divided by 16). If it's 0,
  651. // the metadata doesn't change. After the packet, icy_metaint bytes
  652. // of normal data follow.
  653. int ch = http_getc(s);
  654. if (ch < 0)
  655. return ch;
  656. if (ch > 0) {
  657. char data[255 * 16 + 1];
  658. int n;
  659. int ret;
  660. ch *= 16;
  661. for (n = 0; n < ch; n++)
  662. data[n] = http_getc(s);
  663. data[ch + 1] = 0;
  664. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  665. return ret;
  666. }
  667. s->icy_data_read = 0;
  668. remaining = s->icy_metaint;
  669. }
  670. size = FFMIN(size, remaining);
  671. }
  672. return http_buf_read(h, buf, size);
  673. }
  674. /* used only when posting data */
  675. static int http_write(URLContext *h, const uint8_t *buf, int size)
  676. {
  677. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  678. int ret;
  679. char crlf[] = "\r\n";
  680. HTTPContext *s = h->priv_data;
  681. if (!s->chunked_post) {
  682. /* non-chunked data is sent without any special encoding */
  683. return ffurl_write(s->hd, buf, size);
  684. }
  685. /* silently ignore zero-size data since chunk encoding that would
  686. * signal EOF */
  687. if (size > 0) {
  688. /* upload data using chunked encoding */
  689. snprintf(temp, sizeof(temp), "%x\r\n", size);
  690. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  691. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  692. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  693. return ret;
  694. }
  695. return size;
  696. }
  697. static int http_shutdown(URLContext *h, int flags)
  698. {
  699. int ret = 0;
  700. char footer[] = "0\r\n\r\n";
  701. HTTPContext *s = h->priv_data;
  702. /* signal end of chunked encoding if used */
  703. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  704. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  705. ret = ret > 0 ? 0 : ret;
  706. s->end_chunked_post = 1;
  707. }
  708. return ret;
  709. }
  710. static int http_close(URLContext *h)
  711. {
  712. int ret = 0;
  713. HTTPContext *s = h->priv_data;
  714. if (!s->end_chunked_post) {
  715. /* Close the write direction by sending the end of chunked encoding. */
  716. ret = http_shutdown(h, h->flags);
  717. }
  718. if (s->hd)
  719. ffurl_closep(&s->hd);
  720. return ret;
  721. }
  722. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  723. {
  724. HTTPContext *s = h->priv_data;
  725. URLContext *old_hd = s->hd;
  726. int64_t old_off = s->off;
  727. uint8_t old_buf[BUFFER_SIZE];
  728. int old_buf_size;
  729. if (whence == AVSEEK_SIZE)
  730. return s->filesize;
  731. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  732. return -1;
  733. /* we save the old context in case the seek fails */
  734. old_buf_size = s->buf_end - s->buf_ptr;
  735. memcpy(old_buf, s->buf_ptr, old_buf_size);
  736. s->hd = NULL;
  737. if (whence == SEEK_CUR)
  738. off += s->off;
  739. else if (whence == SEEK_END)
  740. off += s->filesize;
  741. s->off = off;
  742. /* if it fails, continue on old connection */
  743. if (http_open_cnx(h) < 0) {
  744. memcpy(s->buffer, old_buf, old_buf_size);
  745. s->buf_ptr = s->buffer;
  746. s->buf_end = s->buffer + old_buf_size;
  747. s->hd = old_hd;
  748. s->off = old_off;
  749. return -1;
  750. }
  751. ffurl_close(old_hd);
  752. return off;
  753. }
  754. static int
  755. http_get_file_handle(URLContext *h)
  756. {
  757. HTTPContext *s = h->priv_data;
  758. return ffurl_get_file_handle(s->hd);
  759. }
  760. #if CONFIG_HTTP_PROTOCOL
  761. URLProtocol ff_http_protocol = {
  762. .name = "http",
  763. .url_open = http_open,
  764. .url_read = http_read,
  765. .url_write = http_write,
  766. .url_seek = http_seek,
  767. .url_close = http_close,
  768. .url_get_file_handle = http_get_file_handle,
  769. .url_shutdown = http_shutdown,
  770. .priv_data_size = sizeof(HTTPContext),
  771. .priv_data_class = &http_context_class,
  772. .flags = URL_PROTOCOL_FLAG_NETWORK,
  773. };
  774. #endif
  775. #if CONFIG_HTTPS_PROTOCOL
  776. URLProtocol ff_https_protocol = {
  777. .name = "https",
  778. .url_open = http_open,
  779. .url_read = http_read,
  780. .url_write = http_write,
  781. .url_seek = http_seek,
  782. .url_close = http_close,
  783. .url_get_file_handle = http_get_file_handle,
  784. .url_shutdown = http_shutdown,
  785. .priv_data_size = sizeof(HTTPContext),
  786. .priv_data_class = &https_context_class,
  787. .flags = URL_PROTOCOL_FLAG_NETWORK,
  788. };
  789. #endif
  790. #if CONFIG_HTTPPROXY_PROTOCOL
  791. static int http_proxy_close(URLContext *h)
  792. {
  793. HTTPContext *s = h->priv_data;
  794. if (s->hd)
  795. ffurl_closep(&s->hd);
  796. return 0;
  797. }
  798. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  799. {
  800. HTTPContext *s = h->priv_data;
  801. char hostname[1024], hoststr[1024];
  802. char auth[1024], pathbuf[1024], *path;
  803. char lower_url[100];
  804. int port, ret = 0, attempts = 0;
  805. HTTPAuthType cur_auth_type;
  806. char *authstr;
  807. int new_loc;
  808. AVDictionary *opts = NULL;
  809. char opts_format[20];
  810. if( s->seekable == 1 )
  811. h->is_streamed = 0;
  812. else
  813. h->is_streamed = 1;
  814. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  815. pathbuf, sizeof(pathbuf), uri);
  816. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  817. path = pathbuf;
  818. if (*path == '/')
  819. path++;
  820. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  821. NULL);
  822. redo:
  823. if (s->rw_timeout != -1) {
  824. snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
  825. av_dict_set(&opts, "timeout", opts_format, 0);
  826. } /* if option is not given, don't pass it and let tcp use its own default */
  827. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  828. &h->interrupt_callback, &opts);
  829. av_dict_free(&opts);
  830. if (ret < 0)
  831. return ret;
  832. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  833. path, "CONNECT");
  834. snprintf(s->buffer, sizeof(s->buffer),
  835. "CONNECT %s HTTP/1.1\r\n"
  836. "Host: %s\r\n"
  837. "Connection: close\r\n"
  838. "%s%s"
  839. "\r\n",
  840. path,
  841. hoststr,
  842. authstr ? "Proxy-" : "", authstr ? authstr : "");
  843. av_freep(&authstr);
  844. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  845. goto fail;
  846. s->buf_ptr = s->buffer;
  847. s->buf_end = s->buffer;
  848. s->line_count = 0;
  849. s->filesize = -1;
  850. cur_auth_type = s->proxy_auth_state.auth_type;
  851. /* Note: This uses buffering, potentially reading more than the
  852. * HTTP header. If tunneling a protocol where the server starts
  853. * the conversation, we might buffer part of that here, too.
  854. * Reading that requires using the proper ffurl_read() function
  855. * on this URLContext, not using the fd directly (as the tls
  856. * protocol does). This shouldn't be an issue for tls though,
  857. * since the client starts the conversation there, so there
  858. * is no extra data that we might buffer up here.
  859. */
  860. ret = http_read_header(h, &new_loc);
  861. if (ret < 0)
  862. goto fail;
  863. attempts++;
  864. if (s->http_code == 407 &&
  865. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  866. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  867. ffurl_closep(&s->hd);
  868. goto redo;
  869. }
  870. if (s->http_code < 400)
  871. return 0;
  872. ret = AVERROR(EIO);
  873. fail:
  874. http_proxy_close(h);
  875. return ret;
  876. }
  877. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  878. {
  879. HTTPContext *s = h->priv_data;
  880. return ffurl_write(s->hd, buf, size);
  881. }
  882. URLProtocol ff_httpproxy_protocol = {
  883. .name = "httpproxy",
  884. .url_open = http_proxy_open,
  885. .url_read = http_buf_read,
  886. .url_write = http_proxy_write,
  887. .url_close = http_proxy_close,
  888. .url_get_file_handle = http_get_file_handle,
  889. .priv_data_size = sizeof(HTTPContext),
  890. .flags = URL_PROTOCOL_FLAG_NETWORK,
  891. };
  892. #endif