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.

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