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.

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