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.

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