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.

818 lines
26KB

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