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.

998 lines
33KB

  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. /* end of header */
  274. if (line[0] == '\0') {
  275. s->end_header = 1;
  276. return 0;
  277. }
  278. p = line;
  279. if (line_count == 0) {
  280. while (!av_isspace(*p) && *p != '\0')
  281. p++;
  282. while (av_isspace(*p))
  283. p++;
  284. s->http_code = strtol(p, &end, 10);
  285. av_dlog(NULL, "http_code=%d\n", s->http_code);
  286. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  287. * don't abort until all headers have been parsed. */
  288. if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
  289. || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  290. (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  291. end += strspn(end, SPACE_CHARS);
  292. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
  293. s->http_code, end);
  294. return -1;
  295. }
  296. } else {
  297. while (*p != '\0' && *p != ':')
  298. p++;
  299. if (*p != ':')
  300. return 1;
  301. *p = '\0';
  302. tag = line;
  303. p++;
  304. while (av_isspace(*p))
  305. p++;
  306. if (!av_strcasecmp(tag, "Location")) {
  307. av_strlcpy(s->location, p, sizeof(s->location));
  308. *new_location = 1;
  309. } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
  310. s->filesize = strtoll(p, NULL, 10);
  311. } else if (!av_strcasecmp (tag, "Content-Range")) {
  312. /* "bytes $from-$to/$document_size" */
  313. const char *slash;
  314. if (!strncmp (p, "bytes ", 6)) {
  315. p += 6;
  316. s->off = strtoll(p, NULL, 10);
  317. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  318. s->filesize = strtoll(slash+1, NULL, 10);
  319. }
  320. if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
  321. h->is_streamed = 0; /* we _can_ in fact seek */
  322. } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
  323. h->is_streamed = 0;
  324. } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
  325. s->filesize = -1;
  326. s->chunksize = 0;
  327. } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
  328. ff_http_auth_handle_header(&s->auth_state, tag, p);
  329. } else if (!av_strcasecmp (tag, "Authentication-Info")) {
  330. ff_http_auth_handle_header(&s->auth_state, tag, p);
  331. } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
  332. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  333. } else if (!av_strcasecmp (tag, "Connection")) {
  334. if (!strcmp(p, "close"))
  335. s->willclose = 1;
  336. } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
  337. s->is_akamai = 1;
  338. } else if (!av_strcasecmp (tag, "Content-Type")) {
  339. av_free(s->mime_type); s->mime_type = av_strdup(p);
  340. } else if (!av_strcasecmp (tag, "Set-Cookie")) {
  341. if (!s->cookies) {
  342. if (!(s->cookies = av_strdup(p)))
  343. return AVERROR(ENOMEM);
  344. } else {
  345. char *tmp = s->cookies;
  346. size_t str_size = strlen(tmp) + strlen(p) + 2;
  347. if (!(s->cookies = av_malloc(str_size))) {
  348. s->cookies = tmp;
  349. return AVERROR(ENOMEM);
  350. }
  351. snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
  352. av_free(tmp);
  353. }
  354. } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
  355. s->icy_metaint = strtoll(p, NULL, 10);
  356. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  357. // Concat all Icy- header lines
  358. char *buf = av_asprintf("%s%s: %s\n",
  359. s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
  360. if (!buf)
  361. return AVERROR(ENOMEM);
  362. av_freep(&s->icy_metadata_headers);
  363. s->icy_metadata_headers = buf;
  364. }
  365. }
  366. return 1;
  367. }
  368. /**
  369. * Create a string containing cookie values for use as a HTTP cookie header
  370. * field value for a particular path and domain from the cookie values stored in
  371. * the HTTP protocol context. The cookie string is stored in *cookies.
  372. *
  373. * @return a negative value if an error condition occurred, 0 otherwise
  374. */
  375. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  376. const char *domain)
  377. {
  378. // cookie strings will look like Set-Cookie header field values. Multiple
  379. // Set-Cookie fields will result in multiple values delimited by a newline
  380. int ret = 0;
  381. char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
  382. if (!set_cookies) return AVERROR(EINVAL);
  383. *cookies = NULL;
  384. while ((cookie = av_strtok(set_cookies, "\n", &next))) {
  385. int domain_offset = 0;
  386. char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
  387. set_cookies = NULL;
  388. while ((param = av_strtok(cookie, "; ", &next_param))) {
  389. cookie = NULL;
  390. if (!av_strncasecmp("path=", param, 5)) {
  391. av_free(cpath);
  392. cpath = av_strdup(&param[5]);
  393. } else if (!av_strncasecmp("domain=", param, 7)) {
  394. av_free(cdomain);
  395. cdomain = av_strdup(&param[7]);
  396. } else if (!av_strncasecmp("secure", param, 6) ||
  397. !av_strncasecmp("comment", param, 7) ||
  398. !av_strncasecmp("max-age", param, 7) ||
  399. !av_strncasecmp("version", param, 7)) {
  400. // ignore Comment, Max-Age, Secure and Version
  401. } else {
  402. av_free(cvalue);
  403. cvalue = av_strdup(param);
  404. }
  405. }
  406. if (!cdomain)
  407. cdomain = av_strdup(domain);
  408. // ensure all of the necessary values are valid
  409. if (!cdomain || !cpath || !cvalue) {
  410. av_log(s, AV_LOG_WARNING,
  411. "Invalid cookie found, no value, path or domain specified\n");
  412. goto done_cookie;
  413. }
  414. // check if the request path matches the cookie path
  415. if (av_strncasecmp(path, cpath, strlen(cpath)))
  416. goto done_cookie;
  417. // the domain should be at least the size of our cookie domain
  418. domain_offset = strlen(domain) - strlen(cdomain);
  419. if (domain_offset < 0)
  420. goto done_cookie;
  421. // match the cookie domain
  422. if (av_strcasecmp(&domain[domain_offset], cdomain))
  423. goto done_cookie;
  424. // cookie parameters match, so copy the value
  425. if (!*cookies) {
  426. if (!(*cookies = av_strdup(cvalue))) {
  427. ret = AVERROR(ENOMEM);
  428. goto done_cookie;
  429. }
  430. } else {
  431. char *tmp = *cookies;
  432. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  433. if (!(*cookies = av_malloc(str_size))) {
  434. ret = AVERROR(ENOMEM);
  435. goto done_cookie;
  436. }
  437. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  438. av_free(tmp);
  439. }
  440. done_cookie:
  441. av_free(cdomain);
  442. av_free(cpath);
  443. av_free(cvalue);
  444. if (ret < 0) {
  445. if (*cookies) av_freep(cookies);
  446. av_free(cset_cookies);
  447. return ret;
  448. }
  449. }
  450. av_free(cset_cookies);
  451. return 0;
  452. }
  453. static inline int has_header(const char *str, const char *header)
  454. {
  455. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  456. if (!str)
  457. return 0;
  458. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  459. }
  460. static int http_read_header(URLContext *h, int *new_location)
  461. {
  462. HTTPContext *s = h->priv_data;
  463. char line[MAX_URL_SIZE];
  464. int err = 0;
  465. s->chunksize = -1;
  466. for (;;) {
  467. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  468. return err;
  469. av_dlog(NULL, "header='%s'\n", line);
  470. err = process_line(h, line, s->line_count, new_location);
  471. if (err < 0)
  472. return err;
  473. if (err == 0)
  474. break;
  475. s->line_count++;
  476. }
  477. return err;
  478. }
  479. static int http_connect(URLContext *h, const char *path, const char *local_path,
  480. const char *hoststr, const char *auth,
  481. const char *proxyauth, int *new_location)
  482. {
  483. HTTPContext *s = h->priv_data;
  484. int post, err;
  485. char headers[4096] = "";
  486. char *authstr = NULL, *proxyauthstr = NULL;
  487. int64_t off = s->off;
  488. int len = 0;
  489. const char *method;
  490. /* send http header */
  491. post = h->flags & AVIO_FLAG_WRITE;
  492. if (s->post_data) {
  493. /* force POST method and disable chunked encoding when
  494. * custom HTTP post data is set */
  495. post = 1;
  496. s->chunked_post = 0;
  497. }
  498. method = post ? "POST" : "GET";
  499. authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
  500. method);
  501. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  502. local_path, method);
  503. /* set default headers if needed */
  504. if (!has_header(s->headers, "\r\nUser-Agent: "))
  505. len += av_strlcatf(headers + len, sizeof(headers) - len,
  506. "User-Agent: %s\r\n", s->user_agent);
  507. if (!has_header(s->headers, "\r\nAccept: "))
  508. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  509. sizeof(headers) - len);
  510. // Note: we send this on purpose even when s->off is 0 when we're probing,
  511. // since it allows us to detect more reliably if a (non-conforming)
  512. // server supports seeking by analysing the reply headers.
  513. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
  514. len += av_strlcatf(headers + len, sizeof(headers) - len,
  515. "Range: bytes=%"PRId64"-\r\n", s->off);
  516. if (!has_header(s->headers, "\r\nConnection: ")) {
  517. if (s->multiple_requests) {
  518. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  519. sizeof(headers) - len);
  520. } else {
  521. len += av_strlcpy(headers + len, "Connection: close\r\n",
  522. sizeof(headers) - len);
  523. }
  524. }
  525. if (!has_header(s->headers, "\r\nHost: "))
  526. len += av_strlcatf(headers + len, sizeof(headers) - len,
  527. "Host: %s\r\n", hoststr);
  528. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  529. len += av_strlcatf(headers + len, sizeof(headers) - len,
  530. "Content-Length: %d\r\n", s->post_datalen);
  531. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  532. len += av_strlcatf(headers + len, sizeof(headers) - len,
  533. "Content-Type: %s\r\n", s->content_type);
  534. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  535. char *cookies = NULL;
  536. if (!get_cookies(s, &cookies, path, hoststr)) {
  537. len += av_strlcatf(headers + len, sizeof(headers) - len,
  538. "Cookie: %s\r\n", cookies);
  539. av_free(cookies);
  540. }
  541. }
  542. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
  543. len += av_strlcatf(headers + len, sizeof(headers) - len,
  544. "Icy-MetaData: %d\r\n", 1);
  545. }
  546. /* now add in custom headers */
  547. if (s->headers)
  548. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  549. snprintf(s->buffer, sizeof(s->buffer),
  550. "%s %s HTTP/1.1\r\n"
  551. "%s"
  552. "%s"
  553. "%s"
  554. "%s%s"
  555. "\r\n",
  556. method,
  557. path,
  558. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  559. headers,
  560. authstr ? authstr : "",
  561. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  562. av_freep(&authstr);
  563. av_freep(&proxyauthstr);
  564. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  565. return err;
  566. if (s->post_data)
  567. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  568. return err;
  569. /* init input buffer */
  570. s->buf_ptr = s->buffer;
  571. s->buf_end = s->buffer;
  572. s->line_count = 0;
  573. s->off = 0;
  574. s->icy_data_read = 0;
  575. s->filesize = -1;
  576. s->willclose = 0;
  577. s->end_chunked_post = 0;
  578. s->end_header = 0;
  579. if (post && !s->post_data) {
  580. /* Pretend that it did work. We didn't read any header yet, since
  581. * we've still to send the POST data, but the code calling this
  582. * function will check http_code after we return. */
  583. s->http_code = 200;
  584. return 0;
  585. }
  586. /* wait for header */
  587. err = http_read_header(h, new_location);
  588. if (err < 0)
  589. return err;
  590. return (off == s->off) ? 0 : -1;
  591. }
  592. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  593. {
  594. HTTPContext *s = h->priv_data;
  595. int len;
  596. /* read bytes from input buffer first */
  597. len = s->buf_end - s->buf_ptr;
  598. if (len > 0) {
  599. if (len > size)
  600. len = size;
  601. memcpy(buf, s->buf_ptr, len);
  602. s->buf_ptr += len;
  603. } else {
  604. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  605. return AVERROR_EOF;
  606. len = ffurl_read(s->hd, buf, size);
  607. }
  608. if (len > 0) {
  609. s->off += len;
  610. s->icy_data_read += len;
  611. if (s->chunksize > 0)
  612. s->chunksize -= len;
  613. }
  614. return len;
  615. }
  616. static int http_read(URLContext *h, uint8_t *buf, int size)
  617. {
  618. HTTPContext *s = h->priv_data;
  619. int err, new_location;
  620. if (!s->hd)
  621. return AVERROR_EOF;
  622. if (s->end_chunked_post && !s->end_header) {
  623. err = http_read_header(h, &new_location);
  624. if (err < 0)
  625. return err;
  626. }
  627. if (s->chunksize >= 0) {
  628. if (!s->chunksize) {
  629. char line[32];
  630. for(;;) {
  631. do {
  632. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  633. return err;
  634. } while (!*line); /* skip CR LF from last chunk */
  635. s->chunksize = strtoll(line, NULL, 16);
  636. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  637. if (!s->chunksize)
  638. return 0;
  639. break;
  640. }
  641. }
  642. size = FFMIN(size, s->chunksize);
  643. }
  644. if (s->icy_metaint > 0) {
  645. int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
  646. if (!remaining) {
  647. // The metadata packet is variable sized. It has a 1 byte header
  648. // which sets the length of the packet (divided by 16). If it's 0,
  649. // the metadata doesn't change. After the packet, icy_metaint bytes
  650. // of normal data follow.
  651. int ch = http_getc(s);
  652. if (ch < 0)
  653. return ch;
  654. if (ch > 0) {
  655. char data[255 * 16 + 1];
  656. int n;
  657. int ret;
  658. ch *= 16;
  659. for (n = 0; n < ch; n++)
  660. data[n] = http_getc(s);
  661. data[ch + 1] = 0;
  662. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  663. return ret;
  664. }
  665. s->icy_data_read = 0;
  666. remaining = s->icy_metaint;
  667. }
  668. size = FFMIN(size, remaining);
  669. }
  670. return http_buf_read(h, buf, size);
  671. }
  672. /* used only when posting data */
  673. static int http_write(URLContext *h, const uint8_t *buf, int size)
  674. {
  675. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  676. int ret;
  677. char crlf[] = "\r\n";
  678. HTTPContext *s = h->priv_data;
  679. if (!s->chunked_post) {
  680. /* non-chunked data is sent without any special encoding */
  681. return ffurl_write(s->hd, buf, size);
  682. }
  683. /* silently ignore zero-size data since chunk encoding that would
  684. * signal EOF */
  685. if (size > 0) {
  686. /* upload data using chunked encoding */
  687. snprintf(temp, sizeof(temp), "%x\r\n", size);
  688. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  689. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  690. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  691. return ret;
  692. }
  693. return size;
  694. }
  695. static int http_shutdown(URLContext *h, int flags)
  696. {
  697. int ret = 0;
  698. char footer[] = "0\r\n\r\n";
  699. HTTPContext *s = h->priv_data;
  700. /* signal end of chunked encoding if used */
  701. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  702. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  703. ret = ret > 0 ? 0 : ret;
  704. s->end_chunked_post = 1;
  705. }
  706. return ret;
  707. }
  708. static int http_close(URLContext *h)
  709. {
  710. int ret = 0;
  711. HTTPContext *s = h->priv_data;
  712. if (!s->end_chunked_post) {
  713. /* Close the write direction by sending the end of chunked encoding. */
  714. ret = http_shutdown(h, h->flags);
  715. }
  716. if (s->hd)
  717. ffurl_closep(&s->hd);
  718. return ret;
  719. }
  720. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  721. {
  722. HTTPContext *s = h->priv_data;
  723. URLContext *old_hd = s->hd;
  724. int64_t old_off = s->off;
  725. uint8_t old_buf[BUFFER_SIZE];
  726. int old_buf_size;
  727. if (whence == AVSEEK_SIZE)
  728. return s->filesize;
  729. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  730. return -1;
  731. /* we save the old context in case the seek fails */
  732. old_buf_size = s->buf_end - s->buf_ptr;
  733. memcpy(old_buf, s->buf_ptr, old_buf_size);
  734. s->hd = NULL;
  735. if (whence == SEEK_CUR)
  736. off += s->off;
  737. else if (whence == SEEK_END)
  738. off += s->filesize;
  739. s->off = off;
  740. /* if it fails, continue on old connection */
  741. if (http_open_cnx(h) < 0) {
  742. memcpy(s->buffer, old_buf, old_buf_size);
  743. s->buf_ptr = s->buffer;
  744. s->buf_end = s->buffer + old_buf_size;
  745. s->hd = old_hd;
  746. s->off = old_off;
  747. return -1;
  748. }
  749. ffurl_close(old_hd);
  750. return off;
  751. }
  752. static int
  753. http_get_file_handle(URLContext *h)
  754. {
  755. HTTPContext *s = h->priv_data;
  756. return ffurl_get_file_handle(s->hd);
  757. }
  758. #if CONFIG_HTTP_PROTOCOL
  759. URLProtocol ff_http_protocol = {
  760. .name = "http",
  761. .url_open = http_open,
  762. .url_read = http_read,
  763. .url_write = http_write,
  764. .url_seek = http_seek,
  765. .url_close = http_close,
  766. .url_get_file_handle = http_get_file_handle,
  767. .url_shutdown = http_shutdown,
  768. .priv_data_size = sizeof(HTTPContext),
  769. .priv_data_class = &http_context_class,
  770. .flags = URL_PROTOCOL_FLAG_NETWORK,
  771. };
  772. #endif
  773. #if CONFIG_HTTPS_PROTOCOL
  774. URLProtocol ff_https_protocol = {
  775. .name = "https",
  776. .url_open = http_open,
  777. .url_read = http_read,
  778. .url_write = http_write,
  779. .url_seek = http_seek,
  780. .url_close = http_close,
  781. .url_get_file_handle = http_get_file_handle,
  782. .url_shutdown = http_shutdown,
  783. .priv_data_size = sizeof(HTTPContext),
  784. .priv_data_class = &https_context_class,
  785. .flags = URL_PROTOCOL_FLAG_NETWORK,
  786. };
  787. #endif
  788. #if CONFIG_HTTPPROXY_PROTOCOL
  789. static int http_proxy_close(URLContext *h)
  790. {
  791. HTTPContext *s = h->priv_data;
  792. if (s->hd)
  793. ffurl_closep(&s->hd);
  794. return 0;
  795. }
  796. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  797. {
  798. HTTPContext *s = h->priv_data;
  799. char hostname[1024], hoststr[1024];
  800. char auth[1024], pathbuf[1024], *path;
  801. char lower_url[100];
  802. int port, ret = 0, attempts = 0;
  803. HTTPAuthType cur_auth_type;
  804. char *authstr;
  805. int new_loc;
  806. AVDictionary *opts = NULL;
  807. char opts_format[20];
  808. if( s->seekable == 1 )
  809. h->is_streamed = 0;
  810. else
  811. h->is_streamed = 1;
  812. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  813. pathbuf, sizeof(pathbuf), uri);
  814. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  815. path = pathbuf;
  816. if (*path == '/')
  817. path++;
  818. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  819. NULL);
  820. redo:
  821. if (s->rw_timeout != -1) {
  822. snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
  823. av_dict_set(&opts, "timeout", opts_format, 0);
  824. } /* if option is not given, don't pass it and let tcp use its own default */
  825. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  826. &h->interrupt_callback, &opts);
  827. av_dict_free(&opts);
  828. if (ret < 0)
  829. return ret;
  830. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  831. path, "CONNECT");
  832. snprintf(s->buffer, sizeof(s->buffer),
  833. "CONNECT %s HTTP/1.1\r\n"
  834. "Host: %s\r\n"
  835. "Connection: close\r\n"
  836. "%s%s"
  837. "\r\n",
  838. path,
  839. hoststr,
  840. authstr ? "Proxy-" : "", authstr ? authstr : "");
  841. av_freep(&authstr);
  842. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  843. goto fail;
  844. s->buf_ptr = s->buffer;
  845. s->buf_end = s->buffer;
  846. s->line_count = 0;
  847. s->filesize = -1;
  848. cur_auth_type = s->proxy_auth_state.auth_type;
  849. /* Note: This uses buffering, potentially reading more than the
  850. * HTTP header. If tunneling a protocol where the server starts
  851. * the conversation, we might buffer part of that here, too.
  852. * Reading that requires using the proper ffurl_read() function
  853. * on this URLContext, not using the fd directly (as the tls
  854. * protocol does). This shouldn't be an issue for tls though,
  855. * since the client starts the conversation there, so there
  856. * is no extra data that we might buffer up here.
  857. */
  858. ret = http_read_header(h, &new_loc);
  859. if (ret < 0)
  860. goto fail;
  861. attempts++;
  862. if (s->http_code == 407 &&
  863. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  864. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  865. ffurl_closep(&s->hd);
  866. goto redo;
  867. }
  868. if (s->http_code < 400)
  869. return 0;
  870. ret = AVERROR(EIO);
  871. fail:
  872. http_proxy_close(h);
  873. return ret;
  874. }
  875. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  876. {
  877. HTTPContext *s = h->priv_data;
  878. return ffurl_write(s->hd, buf, size);
  879. }
  880. URLProtocol ff_httpproxy_protocol = {
  881. .name = "httpproxy",
  882. .url_open = http_proxy_open,
  883. .url_read = http_buf_read,
  884. .url_write = http_proxy_write,
  885. .url_close = http_proxy_close,
  886. .url_get_file_handle = http_get_file_handle,
  887. .priv_data_size = sizeof(HTTPContext),
  888. .flags = URL_PROTOCOL_FLAG_NETWORK,
  889. };
  890. #endif