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.

947 lines
31KB

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