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.

945 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 "Mozilla/5.0 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. // ensure all of the necessary values are valid
  388. if (!cdomain || !cpath || !cvalue) {
  389. av_log(s, AV_LOG_WARNING,
  390. "Invalid cookie found, no value, path or domain specified\n");
  391. goto done_cookie;
  392. }
  393. // check if the request path matches the cookie path
  394. if (av_strncasecmp(path, cpath, strlen(cpath)))
  395. goto done_cookie;
  396. // the domain should be at least the size of our cookie domain
  397. domain_offset = strlen(domain) - strlen(cdomain);
  398. if (domain_offset < 0)
  399. goto done_cookie;
  400. // match the cookie domain
  401. if (av_strcasecmp(&domain[domain_offset], cdomain))
  402. goto done_cookie;
  403. // cookie parameters match, so copy the value
  404. if (!*cookies) {
  405. if (!(*cookies = av_strdup(cvalue))) {
  406. ret = AVERROR(ENOMEM);
  407. goto done_cookie;
  408. }
  409. } else {
  410. char *tmp = *cookies;
  411. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  412. if (!(*cookies = av_malloc(str_size))) {
  413. ret = AVERROR(ENOMEM);
  414. goto done_cookie;
  415. }
  416. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  417. av_free(tmp);
  418. }
  419. done_cookie:
  420. av_free(cdomain);
  421. av_free(cpath);
  422. av_free(cvalue);
  423. if (ret < 0) {
  424. if (*cookies) av_freep(cookies);
  425. av_free(cset_cookies);
  426. return ret;
  427. }
  428. }
  429. av_free(cset_cookies);
  430. return 0;
  431. }
  432. static inline int has_header(const char *str, const char *header)
  433. {
  434. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  435. if (!str)
  436. return 0;
  437. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  438. }
  439. static int http_read_header(URLContext *h, int *new_location)
  440. {
  441. HTTPContext *s = h->priv_data;
  442. char line[MAX_URL_SIZE];
  443. int err = 0;
  444. s->chunksize = -1;
  445. for (;;) {
  446. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  447. return err;
  448. av_dlog(NULL, "header='%s'\n", line);
  449. err = process_line(h, line, s->line_count, new_location);
  450. if (err < 0)
  451. return err;
  452. if (err == 0)
  453. break;
  454. s->line_count++;
  455. }
  456. return err;
  457. }
  458. static int http_connect(URLContext *h, const char *path, const char *local_path,
  459. const char *hoststr, const char *auth,
  460. const char *proxyauth, int *new_location)
  461. {
  462. HTTPContext *s = h->priv_data;
  463. int post, err;
  464. char headers[4096] = "";
  465. char *authstr = NULL, *proxyauthstr = NULL;
  466. int64_t off = s->off;
  467. int len = 0;
  468. const char *method;
  469. /* send http header */
  470. post = h->flags & AVIO_FLAG_WRITE;
  471. if (s->post_data) {
  472. /* force POST method and disable chunked encoding when
  473. * custom HTTP post data is set */
  474. post = 1;
  475. s->chunked_post = 0;
  476. }
  477. method = post ? "POST" : "GET";
  478. authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
  479. method);
  480. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  481. local_path, method);
  482. /* set default headers if needed */
  483. if (!has_header(s->headers, "\r\nUser-Agent: "))
  484. len += av_strlcatf(headers + len, sizeof(headers) - len,
  485. "User-Agent: %s\r\n", s->user_agent);
  486. if (!has_header(s->headers, "\r\nAccept: "))
  487. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  488. sizeof(headers) - len);
  489. // Note: we send this on purpose even when s->off is 0 when we're probing,
  490. // since it allows us to detect more reliably if a (non-conforming)
  491. // server supports seeking by analysing the reply headers.
  492. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
  493. len += av_strlcatf(headers + len, sizeof(headers) - len,
  494. "Range: bytes=%"PRId64"-\r\n", s->off);
  495. if (!has_header(s->headers, "\r\nConnection: ")) {
  496. if (s->multiple_requests) {
  497. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  498. sizeof(headers) - len);
  499. } else {
  500. len += av_strlcpy(headers + len, "Connection: close\r\n",
  501. sizeof(headers) - len);
  502. }
  503. }
  504. if (!has_header(s->headers, "\r\nHost: "))
  505. len += av_strlcatf(headers + len, sizeof(headers) - len,
  506. "Host: %s\r\n", hoststr);
  507. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  508. len += av_strlcatf(headers + len, sizeof(headers) - len,
  509. "Content-Length: %d\r\n", s->post_datalen);
  510. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  511. len += av_strlcatf(headers + len, sizeof(headers) - len,
  512. "Content-Type: %s\r\n", s->content_type);
  513. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  514. char *cookies = NULL;
  515. if (!get_cookies(s, &cookies, path, hoststr)) {
  516. len += av_strlcatf(headers + len, sizeof(headers) - len,
  517. "Cookie: %s\r\n", cookies);
  518. av_free(cookies);
  519. }
  520. }
  521. /* now add in custom headers */
  522. if (s->headers)
  523. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  524. snprintf(s->buffer, sizeof(s->buffer),
  525. "%s %s HTTP/1.1\r\n"
  526. "%s"
  527. "%s"
  528. "%s"
  529. "%s%s"
  530. "\r\n",
  531. method,
  532. path,
  533. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  534. headers,
  535. authstr ? authstr : "",
  536. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  537. av_freep(&authstr);
  538. av_freep(&proxyauthstr);
  539. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  540. return err;
  541. if (s->post_data)
  542. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  543. return err;
  544. /* init input buffer */
  545. s->buf_ptr = s->buffer;
  546. s->buf_end = s->buffer;
  547. s->line_count = 0;
  548. s->off = 0;
  549. s->filesize = -1;
  550. s->willclose = 0;
  551. s->end_chunked_post = 0;
  552. s->end_header = 0;
  553. if (post && !s->post_data) {
  554. /* Pretend that it did work. We didn't read any header yet, since
  555. * we've still to send the POST data, but the code calling this
  556. * function will check http_code after we return. */
  557. s->http_code = 200;
  558. return 0;
  559. }
  560. /* wait for header */
  561. err = http_read_header(h, new_location);
  562. if (err < 0)
  563. return err;
  564. return (off == s->off) ? 0 : -1;
  565. }
  566. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  567. {
  568. HTTPContext *s = h->priv_data;
  569. int len;
  570. /* read bytes from input buffer first */
  571. len = s->buf_end - s->buf_ptr;
  572. if (len > 0) {
  573. if (len > size)
  574. len = size;
  575. memcpy(buf, s->buf_ptr, len);
  576. s->buf_ptr += len;
  577. } else {
  578. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  579. return AVERROR_EOF;
  580. len = ffurl_read(s->hd, buf, size);
  581. }
  582. if (len > 0) {
  583. s->off += len;
  584. if (s->chunksize > 0)
  585. s->chunksize -= len;
  586. }
  587. return len;
  588. }
  589. static int http_read(URLContext *h, uint8_t *buf, int size)
  590. {
  591. HTTPContext *s = h->priv_data;
  592. int err, new_location;
  593. if (!s->hd)
  594. return AVERROR_EOF;
  595. if (s->end_chunked_post && !s->end_header) {
  596. err = http_read_header(h, &new_location);
  597. if (err < 0)
  598. return err;
  599. }
  600. if (s->chunksize >= 0) {
  601. if (!s->chunksize) {
  602. char line[32];
  603. for(;;) {
  604. do {
  605. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  606. return err;
  607. } while (!*line); /* skip CR LF from last chunk */
  608. s->chunksize = strtoll(line, NULL, 16);
  609. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  610. if (!s->chunksize)
  611. return 0;
  612. break;
  613. }
  614. }
  615. size = FFMIN(size, s->chunksize);
  616. }
  617. return http_buf_read(h, buf, size);
  618. }
  619. /* used only when posting data */
  620. static int http_write(URLContext *h, const uint8_t *buf, int size)
  621. {
  622. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  623. int ret;
  624. char crlf[] = "\r\n";
  625. HTTPContext *s = h->priv_data;
  626. if (!s->chunked_post) {
  627. /* non-chunked data is sent without any special encoding */
  628. return ffurl_write(s->hd, buf, size);
  629. }
  630. /* silently ignore zero-size data since chunk encoding that would
  631. * signal EOF */
  632. if (size > 0) {
  633. /* upload data using chunked encoding */
  634. snprintf(temp, sizeof(temp), "%x\r\n", size);
  635. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  636. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  637. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  638. return ret;
  639. }
  640. return size;
  641. }
  642. static int http_shutdown(URLContext *h, int flags)
  643. {
  644. int ret = 0;
  645. char footer[] = "0\r\n\r\n";
  646. HTTPContext *s = h->priv_data;
  647. /* signal end of chunked encoding if used */
  648. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  649. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  650. ret = ret > 0 ? 0 : ret;
  651. s->end_chunked_post = 1;
  652. }
  653. return ret;
  654. }
  655. static int http_close(URLContext *h)
  656. {
  657. int ret = 0;
  658. HTTPContext *s = h->priv_data;
  659. if (!s->end_chunked_post) {
  660. /* Close the write direction by sending the end of chunked encoding. */
  661. ret = http_shutdown(h, h->flags);
  662. }
  663. if (s->hd)
  664. ffurl_closep(&s->hd);
  665. return ret;
  666. }
  667. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  668. {
  669. HTTPContext *s = h->priv_data;
  670. URLContext *old_hd = s->hd;
  671. int64_t old_off = s->off;
  672. uint8_t old_buf[BUFFER_SIZE];
  673. int old_buf_size;
  674. if (whence == AVSEEK_SIZE)
  675. return s->filesize;
  676. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  677. return -1;
  678. /* we save the old context in case the seek fails */
  679. old_buf_size = s->buf_end - s->buf_ptr;
  680. memcpy(old_buf, s->buf_ptr, old_buf_size);
  681. s->hd = NULL;
  682. if (whence == SEEK_CUR)
  683. off += s->off;
  684. else if (whence == SEEK_END)
  685. off += s->filesize;
  686. s->off = off;
  687. /* if it fails, continue on old connection */
  688. if (http_open_cnx(h) < 0) {
  689. memcpy(s->buffer, old_buf, old_buf_size);
  690. s->buf_ptr = s->buffer;
  691. s->buf_end = s->buffer + old_buf_size;
  692. s->hd = old_hd;
  693. s->off = old_off;
  694. return -1;
  695. }
  696. ffurl_close(old_hd);
  697. return off;
  698. }
  699. static int
  700. http_get_file_handle(URLContext *h)
  701. {
  702. HTTPContext *s = h->priv_data;
  703. return ffurl_get_file_handle(s->hd);
  704. }
  705. #if CONFIG_HTTP_PROTOCOL
  706. URLProtocol ff_http_protocol = {
  707. .name = "http",
  708. .url_open = http_open,
  709. .url_read = http_read,
  710. .url_write = http_write,
  711. .url_seek = http_seek,
  712. .url_close = http_close,
  713. .url_get_file_handle = http_get_file_handle,
  714. .url_shutdown = http_shutdown,
  715. .priv_data_size = sizeof(HTTPContext),
  716. .priv_data_class = &http_context_class,
  717. .flags = URL_PROTOCOL_FLAG_NETWORK,
  718. };
  719. #endif
  720. #if CONFIG_HTTPS_PROTOCOL
  721. URLProtocol ff_https_protocol = {
  722. .name = "https",
  723. .url_open = http_open,
  724. .url_read = http_read,
  725. .url_write = http_write,
  726. .url_seek = http_seek,
  727. .url_close = http_close,
  728. .url_get_file_handle = http_get_file_handle,
  729. .url_shutdown = http_shutdown,
  730. .priv_data_size = sizeof(HTTPContext),
  731. .priv_data_class = &https_context_class,
  732. .flags = URL_PROTOCOL_FLAG_NETWORK,
  733. };
  734. #endif
  735. #if CONFIG_HTTPPROXY_PROTOCOL
  736. static int http_proxy_close(URLContext *h)
  737. {
  738. HTTPContext *s = h->priv_data;
  739. if (s->hd)
  740. ffurl_closep(&s->hd);
  741. return 0;
  742. }
  743. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  744. {
  745. HTTPContext *s = h->priv_data;
  746. char hostname[1024], hoststr[1024];
  747. char auth[1024], pathbuf[1024], *path;
  748. char lower_url[100];
  749. int port, ret = 0, attempts = 0;
  750. HTTPAuthType cur_auth_type;
  751. char *authstr;
  752. int new_loc;
  753. AVDictionary *opts = NULL;
  754. char opts_format[20];
  755. if( s->seekable == 1 )
  756. h->is_streamed = 0;
  757. else
  758. h->is_streamed = 1;
  759. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  760. pathbuf, sizeof(pathbuf), uri);
  761. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  762. path = pathbuf;
  763. if (*path == '/')
  764. path++;
  765. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  766. NULL);
  767. redo:
  768. if (s->rw_timeout != -1) {
  769. snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
  770. av_dict_set(&opts, "timeout", opts_format, 0);
  771. } /* if option is not given, don't pass it and let tcp use its own default */
  772. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  773. &h->interrupt_callback, &opts);
  774. av_dict_free(&opts);
  775. if (ret < 0)
  776. return ret;
  777. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  778. path, "CONNECT");
  779. snprintf(s->buffer, sizeof(s->buffer),
  780. "CONNECT %s HTTP/1.1\r\n"
  781. "Host: %s\r\n"
  782. "Connection: close\r\n"
  783. "%s%s"
  784. "\r\n",
  785. path,
  786. hoststr,
  787. authstr ? "Proxy-" : "", authstr ? authstr : "");
  788. av_freep(&authstr);
  789. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  790. goto fail;
  791. s->buf_ptr = s->buffer;
  792. s->buf_end = s->buffer;
  793. s->line_count = 0;
  794. s->filesize = -1;
  795. cur_auth_type = s->proxy_auth_state.auth_type;
  796. /* Note: This uses buffering, potentially reading more than the
  797. * HTTP header. If tunneling a protocol where the server starts
  798. * the conversation, we might buffer part of that here, too.
  799. * Reading that requires using the proper ffurl_read() function
  800. * on this URLContext, not using the fd directly (as the tls
  801. * protocol does). This shouldn't be an issue for tls though,
  802. * since the client starts the conversation there, so there
  803. * is no extra data that we might buffer up here.
  804. */
  805. ret = http_read_header(h, &new_loc);
  806. if (ret < 0)
  807. goto fail;
  808. attempts++;
  809. if (s->http_code == 407 &&
  810. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  811. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  812. ffurl_closep(&s->hd);
  813. goto redo;
  814. }
  815. if (s->http_code < 400)
  816. return 0;
  817. ret = AVERROR(EIO);
  818. fail:
  819. http_proxy_close(h);
  820. return ret;
  821. }
  822. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  823. {
  824. HTTPContext *s = h->priv_data;
  825. return ffurl_write(s->hd, buf, size);
  826. }
  827. URLProtocol ff_httpproxy_protocol = {
  828. .name = "httpproxy",
  829. .url_open = http_proxy_open,
  830. .url_read = http_buf_read,
  831. .url_write = http_proxy_write,
  832. .url_close = http_proxy_close,
  833. .url_get_file_handle = http_get_file_handle,
  834. .priv_data_size = sizeof(HTTPContext),
  835. .flags = URL_PROTOCOL_FLAG_NETWORK,
  836. };
  837. #endif