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.

1374 lines
45KB

  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 "config.h"
  22. #if CONFIG_ZLIB
  23. #include <zlib.h>
  24. #endif /* CONFIG_ZLIB */
  25. #include "libavutil/avstring.h"
  26. #include "libavutil/opt.h"
  27. #include "avformat.h"
  28. #include "http.h"
  29. #include "httpauth.h"
  30. #include "internal.h"
  31. #include "network.h"
  32. #include "os_support.h"
  33. #include "url.h"
  34. /* XXX: POST protocol is not completely implemented because ffmpeg uses
  35. * only a subset of it. */
  36. /* The IO buffer size is unrelated to the max URL size in itself, but needs
  37. * to be large enough to fit the full request headers (including long
  38. * path names). */
  39. #define BUFFER_SIZE MAX_URL_SIZE
  40. #define MAX_REDIRECTS 8
  41. typedef struct HTTPContext {
  42. const AVClass *class;
  43. URLContext *hd;
  44. unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
  45. int line_count;
  46. int http_code;
  47. /* Used if "Transfer-Encoding: chunked" otherwise -1. */
  48. int64_t chunksize;
  49. int64_t off, end_off, filesize;
  50. char *location;
  51. HTTPAuthState auth_state;
  52. HTTPAuthState proxy_auth_state;
  53. char *headers;
  54. char *mime_type;
  55. char *user_agent;
  56. char *content_type;
  57. /* Set if the server correctly handles Connection: close and will close
  58. * the connection after feeding us the content. */
  59. int willclose;
  60. int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
  61. int chunked_post;
  62. /* A flag which indicates if the end of chunked encoding has been sent. */
  63. int end_chunked_post;
  64. /* A flag which indicates we have finished to read POST reply. */
  65. int end_header;
  66. /* A flag which indicates if we use persistent connections. */
  67. int multiple_requests;
  68. uint8_t *post_data;
  69. int post_datalen;
  70. int is_akamai;
  71. int is_mediagateway;
  72. char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
  73. /* A dictionary containing cookies keyed by cookie name */
  74. AVDictionary *cookie_dict;
  75. int icy;
  76. /* how much data was read since the last ICY metadata packet */
  77. int icy_data_read;
  78. /* after how many bytes of read data a new metadata packet will be found */
  79. int icy_metaint;
  80. char *icy_metadata_headers;
  81. char *icy_metadata_packet;
  82. AVDictionary *metadata;
  83. #if CONFIG_ZLIB
  84. int compressed;
  85. z_stream inflate_stream;
  86. uint8_t *inflate_buffer;
  87. #endif /* CONFIG_ZLIB */
  88. AVDictionary *chained_options;
  89. int send_expect_100;
  90. char *method;
  91. int reconnect;
  92. } HTTPContext;
  93. #define OFFSET(x) offsetof(HTTPContext, x)
  94. #define D AV_OPT_FLAG_DECODING_PARAM
  95. #define E AV_OPT_FLAG_ENCODING_PARAM
  96. #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
  97. static const AVOption options[] = {
  98. { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
  99. { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  100. { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
  101. { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
  102. { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
  103. { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
  104. { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
  105. { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
  106. { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
  107. { "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, D },
  108. { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
  109. { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
  110. { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
  111. { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
  112. { "auth_type", "HTTP authentication type", OFFSET(auth_state.auth_type), AV_OPT_TYPE_INT, { .i64 = HTTP_AUTH_NONE }, HTTP_AUTH_NONE, HTTP_AUTH_BASIC, D | E, "auth_type"},
  113. { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
  114. { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
  115. { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  116. { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
  117. { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
  118. { "end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
  119. { "method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
  120. { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
  121. { NULL }
  122. };
  123. static int http_connect(URLContext *h, const char *path, const char *local_path,
  124. const char *hoststr, const char *auth,
  125. const char *proxyauth, int *new_location);
  126. void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
  127. {
  128. memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
  129. &((HTTPContext *)src->priv_data)->auth_state,
  130. sizeof(HTTPAuthState));
  131. memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
  132. &((HTTPContext *)src->priv_data)->proxy_auth_state,
  133. sizeof(HTTPAuthState));
  134. }
  135. static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
  136. {
  137. const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
  138. char hostname[1024], hoststr[1024], proto[10];
  139. char auth[1024], proxyauth[1024] = "";
  140. char path1[MAX_URL_SIZE];
  141. char buf[1024], urlbuf[MAX_URL_SIZE];
  142. int port, use_proxy, err, location_changed = 0;
  143. HTTPContext *s = h->priv_data;
  144. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  145. hostname, sizeof(hostname), &port,
  146. path1, sizeof(path1), s->location);
  147. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  148. proxy_path = getenv("http_proxy");
  149. use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
  150. proxy_path && av_strstart(proxy_path, "http://", NULL);
  151. if (!strcmp(proto, "https")) {
  152. lower_proto = "tls";
  153. use_proxy = 0;
  154. if (port < 0)
  155. port = 443;
  156. }
  157. if (port < 0)
  158. port = 80;
  159. if (path1[0] == '\0')
  160. path = "/";
  161. else
  162. path = path1;
  163. local_path = path;
  164. if (use_proxy) {
  165. /* Reassemble the request URL without auth string - we don't
  166. * want to leak the auth to the proxy. */
  167. ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
  168. path1);
  169. path = urlbuf;
  170. av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
  171. hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
  172. }
  173. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  174. if (!s->hd) {
  175. err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
  176. &h->interrupt_callback, options);
  177. if (err < 0)
  178. return err;
  179. }
  180. err = http_connect(h, path, local_path, hoststr,
  181. auth, proxyauth, &location_changed);
  182. if (err < 0)
  183. return err;
  184. return location_changed;
  185. }
  186. /* return non zero if error */
  187. static int http_open_cnx(URLContext *h, AVDictionary **options)
  188. {
  189. HTTPAuthType cur_auth_type, cur_proxy_auth_type;
  190. HTTPContext *s = h->priv_data;
  191. int location_changed, attempts = 0, redirects = 0;
  192. redo:
  193. av_dict_copy(options, s->chained_options, 0);
  194. cur_auth_type = s->auth_state.auth_type;
  195. cur_proxy_auth_type = s->auth_state.auth_type;
  196. location_changed = http_open_cnx_internal(h, options);
  197. if (location_changed < 0)
  198. goto fail;
  199. attempts++;
  200. if (s->http_code == 401) {
  201. if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
  202. s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  203. ffurl_closep(&s->hd);
  204. goto redo;
  205. } else
  206. goto fail;
  207. }
  208. if (s->http_code == 407) {
  209. if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  210. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  211. ffurl_closep(&s->hd);
  212. goto redo;
  213. } else
  214. goto fail;
  215. }
  216. if ((s->http_code == 301 || s->http_code == 302 ||
  217. s->http_code == 303 || s->http_code == 307) &&
  218. location_changed == 1) {
  219. /* url moved, get next */
  220. ffurl_closep(&s->hd);
  221. if (redirects++ >= MAX_REDIRECTS)
  222. return AVERROR(EIO);
  223. /* Restart the authentication process with the new target, which
  224. * might use a different auth mechanism. */
  225. memset(&s->auth_state, 0, sizeof(s->auth_state));
  226. attempts = 0;
  227. location_changed = 0;
  228. goto redo;
  229. }
  230. return 0;
  231. fail:
  232. if (s->hd)
  233. ffurl_closep(&s->hd);
  234. if (location_changed < 0)
  235. return location_changed;
  236. return ff_http_averror(s->http_code, AVERROR(EIO));
  237. }
  238. int ff_http_do_new_request(URLContext *h, const char *uri)
  239. {
  240. HTTPContext *s = h->priv_data;
  241. AVDictionary *options = NULL;
  242. int ret;
  243. s->off = 0;
  244. s->icy_data_read = 0;
  245. av_free(s->location);
  246. s->location = av_strdup(uri);
  247. if (!s->location)
  248. return AVERROR(ENOMEM);
  249. ret = http_open_cnx(h, &options);
  250. av_dict_free(&options);
  251. return ret;
  252. }
  253. int ff_http_averror(int status_code, int default_averror)
  254. {
  255. switch (status_code) {
  256. case 400: return AVERROR_HTTP_BAD_REQUEST;
  257. case 401: return AVERROR_HTTP_UNAUTHORIZED;
  258. case 403: return AVERROR_HTTP_FORBIDDEN;
  259. case 404: return AVERROR_HTTP_NOT_FOUND;
  260. default: break;
  261. }
  262. if (status_code >= 400 && status_code <= 499)
  263. return AVERROR_HTTP_OTHER_4XX;
  264. else if (status_code >= 500)
  265. return AVERROR_HTTP_SERVER_ERROR;
  266. else
  267. return default_averror;
  268. }
  269. static int http_open(URLContext *h, const char *uri, int flags,
  270. AVDictionary **options)
  271. {
  272. HTTPContext *s = h->priv_data;
  273. int ret;
  274. if( s->seekable == 1 )
  275. h->is_streamed = 0;
  276. else
  277. h->is_streamed = 1;
  278. s->filesize = -1;
  279. s->location = av_strdup(uri);
  280. if (!s->location)
  281. return AVERROR(ENOMEM);
  282. if (options)
  283. av_dict_copy(&s->chained_options, *options, 0);
  284. if (s->headers) {
  285. int len = strlen(s->headers);
  286. if (len < 2 || strcmp("\r\n", s->headers + len - 2))
  287. av_log(h, AV_LOG_WARNING,
  288. "No trailing CRLF found in HTTP header.\n");
  289. }
  290. ret = http_open_cnx(h, options);
  291. if (ret < 0)
  292. av_dict_free(&s->chained_options);
  293. return ret;
  294. }
  295. static int http_getc(HTTPContext *s)
  296. {
  297. int len;
  298. if (s->buf_ptr >= s->buf_end) {
  299. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  300. if (len < 0) {
  301. return len;
  302. } else if (len == 0) {
  303. return AVERROR_EOF;
  304. } else {
  305. s->buf_ptr = s->buffer;
  306. s->buf_end = s->buffer + len;
  307. }
  308. }
  309. return *s->buf_ptr++;
  310. }
  311. static int http_get_line(HTTPContext *s, char *line, int line_size)
  312. {
  313. int ch;
  314. char *q;
  315. q = line;
  316. for (;;) {
  317. ch = http_getc(s);
  318. if (ch < 0)
  319. return ch;
  320. if (ch == '\n') {
  321. /* process line */
  322. if (q > line && q[-1] == '\r')
  323. q--;
  324. *q = '\0';
  325. return 0;
  326. } else {
  327. if ((q - line) < line_size - 1)
  328. *q++ = ch;
  329. }
  330. }
  331. }
  332. static int check_http_code(URLContext *h, int http_code, const char *end)
  333. {
  334. HTTPContext *s = h->priv_data;
  335. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  336. * don't abort until all headers have been parsed. */
  337. if (http_code >= 400 && http_code < 600 &&
  338. (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  339. (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  340. end += strspn(end, SPACE_CHARS);
  341. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
  342. return ff_http_averror(http_code, AVERROR(EIO));
  343. }
  344. return 0;
  345. }
  346. static int parse_location(HTTPContext *s, const char *p)
  347. {
  348. char redirected_location[MAX_URL_SIZE], *new_loc;
  349. ff_make_absolute_url(redirected_location, sizeof(redirected_location),
  350. s->location, p);
  351. new_loc = av_strdup(redirected_location);
  352. if (!new_loc)
  353. return AVERROR(ENOMEM);
  354. av_free(s->location);
  355. s->location = new_loc;
  356. return 0;
  357. }
  358. /* "bytes $from-$to/$document_size" */
  359. static void parse_content_range(URLContext *h, const char *p)
  360. {
  361. HTTPContext *s = h->priv_data;
  362. const char *slash;
  363. if (!strncmp(p, "bytes ", 6)) {
  364. p += 6;
  365. s->off = strtoll(p, NULL, 10);
  366. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  367. s->filesize = strtoll(slash + 1, NULL, 10);
  368. }
  369. if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
  370. h->is_streamed = 0; /* we _can_ in fact seek */
  371. }
  372. static int parse_content_encoding(URLContext *h, const char *p)
  373. {
  374. if (!av_strncasecmp(p, "gzip", 4) ||
  375. !av_strncasecmp(p, "deflate", 7)) {
  376. #if CONFIG_ZLIB
  377. HTTPContext *s = h->priv_data;
  378. s->compressed = 1;
  379. inflateEnd(&s->inflate_stream);
  380. if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
  381. av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
  382. s->inflate_stream.msg);
  383. return AVERROR(ENOSYS);
  384. }
  385. if (zlibCompileFlags() & (1 << 17)) {
  386. av_log(h, AV_LOG_WARNING,
  387. "Your zlib was compiled without gzip support.\n");
  388. return AVERROR(ENOSYS);
  389. }
  390. #else
  391. av_log(h, AV_LOG_WARNING,
  392. "Compressed (%s) content, need zlib with gzip support\n", p);
  393. return AVERROR(ENOSYS);
  394. #endif /* CONFIG_ZLIB */
  395. } else if (!av_strncasecmp(p, "identity", 8)) {
  396. // The normal, no-encoding case (although servers shouldn't include
  397. // the header at all if this is the case).
  398. } else {
  399. av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
  400. }
  401. return 0;
  402. }
  403. // Concat all Icy- header lines
  404. static int parse_icy(HTTPContext *s, const char *tag, const char *p)
  405. {
  406. int len = 4 + strlen(p) + strlen(tag);
  407. int is_first = !s->icy_metadata_headers;
  408. int ret;
  409. av_dict_set(&s->metadata, tag, p, 0);
  410. if (s->icy_metadata_headers)
  411. len += strlen(s->icy_metadata_headers);
  412. if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
  413. return ret;
  414. if (is_first)
  415. *s->icy_metadata_headers = '\0';
  416. av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
  417. return 0;
  418. }
  419. static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
  420. {
  421. char *eql, *name;
  422. // duplicate the cookie name (dict will dupe the value)
  423. if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
  424. if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
  425. // add the cookie to the dictionary
  426. av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
  427. return 0;
  428. }
  429. static int cookie_string(AVDictionary *dict, char **cookies)
  430. {
  431. AVDictionaryEntry *e = NULL;
  432. int len = 1;
  433. // determine how much memory is needed for the cookies string
  434. while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
  435. len += strlen(e->key) + strlen(e->value) + 1;
  436. // reallocate the cookies
  437. e = NULL;
  438. if (*cookies) av_free(*cookies);
  439. *cookies = av_malloc(len);
  440. if (!cookies) return AVERROR(ENOMEM);
  441. *cookies[0] = '\0';
  442. // write out the cookies
  443. while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
  444. av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
  445. return 0;
  446. }
  447. static int process_line(URLContext *h, char *line, int line_count,
  448. int *new_location)
  449. {
  450. HTTPContext *s = h->priv_data;
  451. char *tag, *p, *end;
  452. int ret;
  453. /* end of header */
  454. if (line[0] == '\0') {
  455. s->end_header = 1;
  456. return 0;
  457. }
  458. p = line;
  459. if (line_count == 0) {
  460. while (!av_isspace(*p) && *p != '\0')
  461. p++;
  462. while (av_isspace(*p))
  463. p++;
  464. s->http_code = strtol(p, &end, 10);
  465. av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
  466. if ((ret = check_http_code(h, s->http_code, end)) < 0)
  467. return ret;
  468. } else {
  469. while (*p != '\0' && *p != ':')
  470. p++;
  471. if (*p != ':')
  472. return 1;
  473. *p = '\0';
  474. tag = line;
  475. p++;
  476. while (av_isspace(*p))
  477. p++;
  478. if (!av_strcasecmp(tag, "Location")) {
  479. if ((ret = parse_location(s, p)) < 0)
  480. return ret;
  481. *new_location = 1;
  482. } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
  483. s->filesize = strtoll(p, NULL, 10);
  484. } else if (!av_strcasecmp(tag, "Content-Range")) {
  485. parse_content_range(h, p);
  486. } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
  487. !strncmp(p, "bytes", 5) &&
  488. s->seekable == -1) {
  489. h->is_streamed = 0;
  490. } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
  491. !av_strncasecmp(p, "chunked", 7)) {
  492. s->filesize = -1;
  493. s->chunksize = 0;
  494. } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
  495. ff_http_auth_handle_header(&s->auth_state, tag, p);
  496. } else if (!av_strcasecmp(tag, "Authentication-Info")) {
  497. ff_http_auth_handle_header(&s->auth_state, tag, p);
  498. } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
  499. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  500. } else if (!av_strcasecmp(tag, "Connection")) {
  501. if (!strcmp(p, "close"))
  502. s->willclose = 1;
  503. } else if (!av_strcasecmp(tag, "Server")) {
  504. if (!av_strcasecmp(p, "AkamaiGHost")) {
  505. s->is_akamai = 1;
  506. } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
  507. s->is_mediagateway = 1;
  508. }
  509. } else if (!av_strcasecmp(tag, "Content-Type")) {
  510. av_free(s->mime_type);
  511. s->mime_type = av_strdup(p);
  512. } else if (!av_strcasecmp(tag, "Set-Cookie")) {
  513. if (parse_cookie(s, p, &s->cookie_dict))
  514. av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
  515. } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
  516. s->icy_metaint = strtoll(p, NULL, 10);
  517. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  518. if ((ret = parse_icy(s, tag, p)) < 0)
  519. return ret;
  520. } else if (!av_strcasecmp(tag, "Content-Encoding")) {
  521. if ((ret = parse_content_encoding(h, p)) < 0)
  522. return ret;
  523. }
  524. }
  525. return 1;
  526. }
  527. /**
  528. * Create a string containing cookie values for use as a HTTP cookie header
  529. * field value for a particular path and domain from the cookie values stored in
  530. * the HTTP protocol context. The cookie string is stored in *cookies.
  531. *
  532. * @return a negative value if an error condition occurred, 0 otherwise
  533. */
  534. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  535. const char *domain)
  536. {
  537. // cookie strings will look like Set-Cookie header field values. Multiple
  538. // Set-Cookie fields will result in multiple values delimited by a newline
  539. int ret = 0;
  540. char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
  541. if (!set_cookies) return AVERROR(EINVAL);
  542. // destroy any cookies in the dictionary.
  543. av_dict_free(&s->cookie_dict);
  544. *cookies = NULL;
  545. while ((cookie = av_strtok(set_cookies, "\n", &next))) {
  546. int domain_offset = 0;
  547. char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
  548. set_cookies = NULL;
  549. // store the cookie in a dict in case it is updated in the response
  550. if (parse_cookie(s, cookie, &s->cookie_dict))
  551. av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
  552. while ((param = av_strtok(cookie, "; ", &next_param))) {
  553. if (cookie) {
  554. // first key-value pair is the actual cookie value
  555. cvalue = av_strdup(param);
  556. cookie = NULL;
  557. } else if (!av_strncasecmp("path=", param, 5)) {
  558. av_free(cpath);
  559. cpath = av_strdup(&param[5]);
  560. } else if (!av_strncasecmp("domain=", param, 7)) {
  561. // if the cookie specifies a sub-domain, skip the leading dot thereby
  562. // supporting URLs that point to sub-domains and the master domain
  563. int leading_dot = (param[7] == '.');
  564. av_free(cdomain);
  565. cdomain = av_strdup(&param[7+leading_dot]);
  566. } else {
  567. // ignore unknown attributes
  568. }
  569. }
  570. if (!cdomain)
  571. cdomain = av_strdup(domain);
  572. // ensure all of the necessary values are valid
  573. if (!cdomain || !cpath || !cvalue) {
  574. av_log(s, AV_LOG_WARNING,
  575. "Invalid cookie found, no value, path or domain specified\n");
  576. goto done_cookie;
  577. }
  578. // check if the request path matches the cookie path
  579. if (av_strncasecmp(path, cpath, strlen(cpath)))
  580. goto done_cookie;
  581. // the domain should be at least the size of our cookie domain
  582. domain_offset = strlen(domain) - strlen(cdomain);
  583. if (domain_offset < 0)
  584. goto done_cookie;
  585. // match the cookie domain
  586. if (av_strcasecmp(&domain[domain_offset], cdomain))
  587. goto done_cookie;
  588. // cookie parameters match, so copy the value
  589. if (!*cookies) {
  590. if (!(*cookies = av_strdup(cvalue))) {
  591. ret = AVERROR(ENOMEM);
  592. goto done_cookie;
  593. }
  594. } else {
  595. char *tmp = *cookies;
  596. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  597. if (!(*cookies = av_malloc(str_size))) {
  598. ret = AVERROR(ENOMEM);
  599. goto done_cookie;
  600. }
  601. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  602. av_free(tmp);
  603. }
  604. done_cookie:
  605. av_freep(&cdomain);
  606. av_freep(&cpath);
  607. av_freep(&cvalue);
  608. if (ret < 0) {
  609. if (*cookies) av_freep(cookies);
  610. av_free(cset_cookies);
  611. return ret;
  612. }
  613. }
  614. av_free(cset_cookies);
  615. return 0;
  616. }
  617. static inline int has_header(const char *str, const char *header)
  618. {
  619. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  620. if (!str)
  621. return 0;
  622. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  623. }
  624. static int http_read_header(URLContext *h, int *new_location)
  625. {
  626. HTTPContext *s = h->priv_data;
  627. char line[MAX_URL_SIZE];
  628. int err = 0;
  629. s->chunksize = -1;
  630. for (;;) {
  631. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  632. return err;
  633. av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
  634. err = process_line(h, line, s->line_count, new_location);
  635. if (err < 0)
  636. return err;
  637. if (err == 0)
  638. break;
  639. s->line_count++;
  640. }
  641. if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
  642. h->is_streamed = 1; /* we can in fact _not_ seek */
  643. // add any new cookies into the existing cookie string
  644. cookie_string(s->cookie_dict, &s->cookies);
  645. av_dict_free(&s->cookie_dict);
  646. return err;
  647. }
  648. static int http_connect(URLContext *h, const char *path, const char *local_path,
  649. const char *hoststr, const char *auth,
  650. const char *proxyauth, int *new_location)
  651. {
  652. HTTPContext *s = h->priv_data;
  653. int post, err;
  654. char headers[HTTP_HEADERS_SIZE] = "";
  655. char *authstr = NULL, *proxyauthstr = NULL;
  656. int64_t off = s->off;
  657. int len = 0;
  658. const char *method;
  659. int send_expect_100 = 0;
  660. /* send http header */
  661. post = h->flags & AVIO_FLAG_WRITE;
  662. if (s->post_data) {
  663. /* force POST method and disable chunked encoding when
  664. * custom HTTP post data is set */
  665. post = 1;
  666. s->chunked_post = 0;
  667. }
  668. if (s->method)
  669. method = s->method;
  670. else
  671. method = post ? "POST" : "GET";
  672. authstr = ff_http_auth_create_response(&s->auth_state, auth,
  673. local_path, method);
  674. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  675. local_path, method);
  676. if (post && !s->post_data) {
  677. send_expect_100 = s->send_expect_100;
  678. /* The user has supplied authentication but we don't know the auth type,
  679. * send Expect: 100-continue to get the 401 response including the
  680. * WWW-Authenticate header, or an 100 continue if no auth actually
  681. * is needed. */
  682. if (auth && *auth &&
  683. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  684. s->http_code != 401)
  685. send_expect_100 = 1;
  686. }
  687. /* set default headers if needed */
  688. if (!has_header(s->headers, "\r\nUser-Agent: "))
  689. len += av_strlcatf(headers + len, sizeof(headers) - len,
  690. "User-Agent: %s\r\n", s->user_agent);
  691. if (!has_header(s->headers, "\r\nAccept: "))
  692. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  693. sizeof(headers) - len);
  694. // Note: we send this on purpose even when s->off is 0 when we're probing,
  695. // since it allows us to detect more reliably if a (non-conforming)
  696. // server supports seeking by analysing the reply headers.
  697. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
  698. len += av_strlcatf(headers + len, sizeof(headers) - len,
  699. "Range: bytes=%"PRId64"-", s->off);
  700. if (s->end_off)
  701. len += av_strlcatf(headers + len, sizeof(headers) - len,
  702. "%"PRId64, s->end_off - 1);
  703. len += av_strlcpy(headers + len, "\r\n",
  704. sizeof(headers) - len);
  705. }
  706. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  707. len += av_strlcatf(headers + len, sizeof(headers) - len,
  708. "Expect: 100-continue\r\n");
  709. if (!has_header(s->headers, "\r\nConnection: ")) {
  710. if (s->multiple_requests)
  711. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  712. sizeof(headers) - len);
  713. else
  714. len += av_strlcpy(headers + len, "Connection: close\r\n",
  715. sizeof(headers) - len);
  716. }
  717. if (!has_header(s->headers, "\r\nHost: "))
  718. len += av_strlcatf(headers + len, sizeof(headers) - len,
  719. "Host: %s\r\n", hoststr);
  720. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  721. len += av_strlcatf(headers + len, sizeof(headers) - len,
  722. "Content-Length: %d\r\n", s->post_datalen);
  723. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  724. len += av_strlcatf(headers + len, sizeof(headers) - len,
  725. "Content-Type: %s\r\n", s->content_type);
  726. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  727. char *cookies = NULL;
  728. if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
  729. len += av_strlcatf(headers + len, sizeof(headers) - len,
  730. "Cookie: %s\r\n", cookies);
  731. av_free(cookies);
  732. }
  733. }
  734. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
  735. len += av_strlcatf(headers + len, sizeof(headers) - len,
  736. "Icy-MetaData: %d\r\n", 1);
  737. /* now add in custom headers */
  738. if (s->headers)
  739. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  740. snprintf(s->buffer, sizeof(s->buffer),
  741. "%s %s HTTP/1.1\r\n"
  742. "%s"
  743. "%s"
  744. "%s"
  745. "%s%s"
  746. "\r\n",
  747. method,
  748. path,
  749. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  750. headers,
  751. authstr ? authstr : "",
  752. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  753. av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
  754. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  755. goto done;
  756. if (s->post_data)
  757. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  758. goto done;
  759. /* init input buffer */
  760. s->buf_ptr = s->buffer;
  761. s->buf_end = s->buffer;
  762. s->line_count = 0;
  763. s->off = 0;
  764. s->icy_data_read = 0;
  765. s->filesize = -1;
  766. s->willclose = 0;
  767. s->end_chunked_post = 0;
  768. s->end_header = 0;
  769. if (post && !s->post_data && !send_expect_100) {
  770. /* Pretend that it did work. We didn't read any header yet, since
  771. * we've still to send the POST data, but the code calling this
  772. * function will check http_code after we return. */
  773. s->http_code = 200;
  774. err = 0;
  775. goto done;
  776. }
  777. /* wait for header */
  778. err = http_read_header(h, new_location);
  779. if (err < 0)
  780. goto done;
  781. err = (off == s->off) ? 0 : -1;
  782. done:
  783. av_freep(&authstr);
  784. av_freep(&proxyauthstr);
  785. return err;
  786. }
  787. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  788. {
  789. HTTPContext *s = h->priv_data;
  790. int len;
  791. /* read bytes from input buffer first */
  792. len = s->buf_end - s->buf_ptr;
  793. if (len > 0) {
  794. if (len > size)
  795. len = size;
  796. memcpy(buf, s->buf_ptr, len);
  797. s->buf_ptr += len;
  798. } else {
  799. if ((!s->willclose || s->chunksize < 0) &&
  800. s->filesize >= 0 && s->off >= s->filesize)
  801. return AVERROR_EOF;
  802. len = ffurl_read(s->hd, buf, size);
  803. }
  804. if (len > 0) {
  805. s->off += len;
  806. if (s->chunksize > 0)
  807. s->chunksize -= len;
  808. }
  809. return len;
  810. }
  811. #if CONFIG_ZLIB
  812. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  813. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  814. {
  815. HTTPContext *s = h->priv_data;
  816. int ret;
  817. if (!s->inflate_buffer) {
  818. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  819. if (!s->inflate_buffer)
  820. return AVERROR(ENOMEM);
  821. }
  822. if (s->inflate_stream.avail_in == 0) {
  823. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  824. if (read <= 0)
  825. return read;
  826. s->inflate_stream.next_in = s->inflate_buffer;
  827. s->inflate_stream.avail_in = read;
  828. }
  829. s->inflate_stream.avail_out = size;
  830. s->inflate_stream.next_out = buf;
  831. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  832. if (ret != Z_OK && ret != Z_STREAM_END)
  833. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
  834. ret, s->inflate_stream.msg);
  835. return size - s->inflate_stream.avail_out;
  836. }
  837. #endif /* CONFIG_ZLIB */
  838. static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
  839. static int http_read_stream(URLContext *h, uint8_t *buf, int size)
  840. {
  841. HTTPContext *s = h->priv_data;
  842. int err, new_location, read_ret, seek_ret;
  843. if (!s->hd)
  844. return AVERROR_EOF;
  845. if (s->end_chunked_post && !s->end_header) {
  846. err = http_read_header(h, &new_location);
  847. if (err < 0)
  848. return err;
  849. }
  850. if (s->chunksize >= 0) {
  851. if (!s->chunksize) {
  852. char line[32];
  853. do {
  854. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  855. return err;
  856. } while (!*line); /* skip CR LF from last chunk */
  857. s->chunksize = strtoll(line, NULL, 16);
  858. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
  859. s->chunksize);
  860. if (!s->chunksize)
  861. return 0;
  862. }
  863. size = FFMIN(size, s->chunksize);
  864. }
  865. #if CONFIG_ZLIB
  866. if (s->compressed)
  867. return http_buf_read_compressed(h, buf, size);
  868. #endif /* CONFIG_ZLIB */
  869. read_ret = http_buf_read(h, buf, size);
  870. if (read_ret < 0 && s->reconnect && !h->is_streamed && s->filesize > 0 && s->off < s->filesize) {
  871. av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64".\n", s->off);
  872. seek_ret = http_seek_internal(h, s->off, SEEK_SET, 1);
  873. if (seek_ret != s->off) {
  874. av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", s->off);
  875. return read_ret;
  876. }
  877. read_ret = http_buf_read(h, buf, size);
  878. }
  879. return read_ret;
  880. }
  881. // Like http_read_stream(), but no short reads.
  882. // Assumes partial reads are an error.
  883. static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
  884. {
  885. int pos = 0;
  886. while (pos < size) {
  887. int len = http_read_stream(h, buf + pos, size - pos);
  888. if (len < 0)
  889. return len;
  890. pos += len;
  891. }
  892. return pos;
  893. }
  894. static void update_metadata(HTTPContext *s, char *data)
  895. {
  896. char *key;
  897. char *val;
  898. char *end;
  899. char *next = data;
  900. while (*next) {
  901. key = next;
  902. val = strstr(key, "='");
  903. if (!val)
  904. break;
  905. end = strstr(val, "';");
  906. if (!end)
  907. break;
  908. *val = '\0';
  909. *end = '\0';
  910. val += 2;
  911. av_dict_set(&s->metadata, key, val, 0);
  912. next = end + 2;
  913. }
  914. }
  915. static int store_icy(URLContext *h, int size)
  916. {
  917. HTTPContext *s = h->priv_data;
  918. /* until next metadata packet */
  919. int remaining = s->icy_metaint - s->icy_data_read;
  920. if (remaining < 0)
  921. return AVERROR_INVALIDDATA;
  922. if (!remaining) {
  923. /* The metadata packet is variable sized. It has a 1 byte header
  924. * which sets the length of the packet (divided by 16). If it's 0,
  925. * the metadata doesn't change. After the packet, icy_metaint bytes
  926. * of normal data follows. */
  927. uint8_t ch;
  928. int len = http_read_stream_all(h, &ch, 1);
  929. if (len < 0)
  930. return len;
  931. if (ch > 0) {
  932. char data[255 * 16 + 1];
  933. int ret;
  934. len = ch * 16;
  935. ret = http_read_stream_all(h, data, len);
  936. if (ret < 0)
  937. return ret;
  938. data[len + 1] = 0;
  939. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  940. return ret;
  941. update_metadata(s, data);
  942. }
  943. s->icy_data_read = 0;
  944. remaining = s->icy_metaint;
  945. }
  946. return FFMIN(size, remaining);
  947. }
  948. static int http_read(URLContext *h, uint8_t *buf, int size)
  949. {
  950. HTTPContext *s = h->priv_data;
  951. if (s->icy_metaint > 0) {
  952. size = store_icy(h, size);
  953. if (size < 0)
  954. return size;
  955. }
  956. size = http_read_stream(h, buf, size);
  957. if (size > 0)
  958. s->icy_data_read += size;
  959. return size;
  960. }
  961. /* used only when posting data */
  962. static int http_write(URLContext *h, const uint8_t *buf, int size)
  963. {
  964. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  965. int ret;
  966. char crlf[] = "\r\n";
  967. HTTPContext *s = h->priv_data;
  968. if (!s->chunked_post) {
  969. /* non-chunked data is sent without any special encoding */
  970. return ffurl_write(s->hd, buf, size);
  971. }
  972. /* silently ignore zero-size data since chunk encoding that would
  973. * signal EOF */
  974. if (size > 0) {
  975. /* upload data using chunked encoding */
  976. snprintf(temp, sizeof(temp), "%x\r\n", size);
  977. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  978. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  979. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  980. return ret;
  981. }
  982. return size;
  983. }
  984. static int http_shutdown(URLContext *h, int flags)
  985. {
  986. int ret = 0;
  987. char footer[] = "0\r\n\r\n";
  988. HTTPContext *s = h->priv_data;
  989. /* signal end of chunked encoding if used */
  990. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  991. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  992. ret = ret > 0 ? 0 : ret;
  993. s->end_chunked_post = 1;
  994. }
  995. return ret;
  996. }
  997. static int http_close(URLContext *h)
  998. {
  999. int ret = 0;
  1000. HTTPContext *s = h->priv_data;
  1001. #if CONFIG_ZLIB
  1002. inflateEnd(&s->inflate_stream);
  1003. av_freep(&s->inflate_buffer);
  1004. #endif /* CONFIG_ZLIB */
  1005. if (!s->end_chunked_post)
  1006. /* Close the write direction by sending the end of chunked encoding. */
  1007. ret = http_shutdown(h, h->flags);
  1008. if (s->hd)
  1009. ffurl_closep(&s->hd);
  1010. av_dict_free(&s->chained_options);
  1011. return ret;
  1012. }
  1013. static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
  1014. {
  1015. HTTPContext *s = h->priv_data;
  1016. URLContext *old_hd = s->hd;
  1017. int64_t old_off = s->off;
  1018. uint8_t old_buf[BUFFER_SIZE];
  1019. int old_buf_size, ret;
  1020. AVDictionary *options = NULL;
  1021. if (whence == AVSEEK_SIZE)
  1022. return s->filesize;
  1023. else if (!force_reconnect &&
  1024. ((whence == SEEK_CUR && off == 0) ||
  1025. (whence == SEEK_SET && off == s->off)))
  1026. return s->off;
  1027. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  1028. return AVERROR(ENOSYS);
  1029. if (whence == SEEK_CUR)
  1030. off += s->off;
  1031. else if (whence == SEEK_END)
  1032. off += s->filesize;
  1033. else if (whence != SEEK_SET)
  1034. return AVERROR(EINVAL);
  1035. if (off < 0)
  1036. return AVERROR(EINVAL);
  1037. s->off = off;
  1038. /* we save the old context in case the seek fails */
  1039. old_buf_size = s->buf_end - s->buf_ptr;
  1040. memcpy(old_buf, s->buf_ptr, old_buf_size);
  1041. s->hd = NULL;
  1042. /* if it fails, continue on old connection */
  1043. if ((ret = http_open_cnx(h, &options)) < 0) {
  1044. av_dict_free(&options);
  1045. memcpy(s->buffer, old_buf, old_buf_size);
  1046. s->buf_ptr = s->buffer;
  1047. s->buf_end = s->buffer + old_buf_size;
  1048. s->hd = old_hd;
  1049. s->off = old_off;
  1050. return ret;
  1051. }
  1052. av_dict_free(&options);
  1053. ffurl_close(old_hd);
  1054. return off;
  1055. }
  1056. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  1057. {
  1058. return http_seek_internal(h, off, whence, 0);
  1059. }
  1060. static int http_get_file_handle(URLContext *h)
  1061. {
  1062. HTTPContext *s = h->priv_data;
  1063. return ffurl_get_file_handle(s->hd);
  1064. }
  1065. #define HTTP_CLASS(flavor) \
  1066. static const AVClass flavor ## _context_class = { \
  1067. .class_name = # flavor, \
  1068. .item_name = av_default_item_name, \
  1069. .option = options, \
  1070. .version = LIBAVUTIL_VERSION_INT, \
  1071. }
  1072. #if CONFIG_HTTP_PROTOCOL
  1073. HTTP_CLASS(http);
  1074. URLProtocol ff_http_protocol = {
  1075. .name = "http",
  1076. .url_open2 = http_open,
  1077. .url_read = http_read,
  1078. .url_write = http_write,
  1079. .url_seek = http_seek,
  1080. .url_close = http_close,
  1081. .url_get_file_handle = http_get_file_handle,
  1082. .url_shutdown = http_shutdown,
  1083. .priv_data_size = sizeof(HTTPContext),
  1084. .priv_data_class = &http_context_class,
  1085. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1086. };
  1087. #endif /* CONFIG_HTTP_PROTOCOL */
  1088. #if CONFIG_HTTPS_PROTOCOL
  1089. HTTP_CLASS(https);
  1090. URLProtocol ff_https_protocol = {
  1091. .name = "https",
  1092. .url_open2 = http_open,
  1093. .url_read = http_read,
  1094. .url_write = http_write,
  1095. .url_seek = http_seek,
  1096. .url_close = http_close,
  1097. .url_get_file_handle = http_get_file_handle,
  1098. .url_shutdown = http_shutdown,
  1099. .priv_data_size = sizeof(HTTPContext),
  1100. .priv_data_class = &https_context_class,
  1101. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1102. };
  1103. #endif /* CONFIG_HTTPS_PROTOCOL */
  1104. #if CONFIG_HTTPPROXY_PROTOCOL
  1105. static int http_proxy_close(URLContext *h)
  1106. {
  1107. HTTPContext *s = h->priv_data;
  1108. if (s->hd)
  1109. ffurl_closep(&s->hd);
  1110. return 0;
  1111. }
  1112. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  1113. {
  1114. HTTPContext *s = h->priv_data;
  1115. char hostname[1024], hoststr[1024];
  1116. char auth[1024], pathbuf[1024], *path;
  1117. char lower_url[100];
  1118. int port, ret = 0, attempts = 0;
  1119. HTTPAuthType cur_auth_type;
  1120. char *authstr;
  1121. int new_loc;
  1122. if( s->seekable == 1 )
  1123. h->is_streamed = 0;
  1124. else
  1125. h->is_streamed = 1;
  1126. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  1127. pathbuf, sizeof(pathbuf), uri);
  1128. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  1129. path = pathbuf;
  1130. if (*path == '/')
  1131. path++;
  1132. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  1133. NULL);
  1134. redo:
  1135. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  1136. &h->interrupt_callback, NULL);
  1137. if (ret < 0)
  1138. return ret;
  1139. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  1140. path, "CONNECT");
  1141. snprintf(s->buffer, sizeof(s->buffer),
  1142. "CONNECT %s HTTP/1.1\r\n"
  1143. "Host: %s\r\n"
  1144. "Connection: close\r\n"
  1145. "%s%s"
  1146. "\r\n",
  1147. path,
  1148. hoststr,
  1149. authstr ? "Proxy-" : "", authstr ? authstr : "");
  1150. av_freep(&authstr);
  1151. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  1152. goto fail;
  1153. s->buf_ptr = s->buffer;
  1154. s->buf_end = s->buffer;
  1155. s->line_count = 0;
  1156. s->filesize = -1;
  1157. cur_auth_type = s->proxy_auth_state.auth_type;
  1158. /* Note: This uses buffering, potentially reading more than the
  1159. * HTTP header. If tunneling a protocol where the server starts
  1160. * the conversation, we might buffer part of that here, too.
  1161. * Reading that requires using the proper ffurl_read() function
  1162. * on this URLContext, not using the fd directly (as the tls
  1163. * protocol does). This shouldn't be an issue for tls though,
  1164. * since the client starts the conversation there, so there
  1165. * is no extra data that we might buffer up here.
  1166. */
  1167. ret = http_read_header(h, &new_loc);
  1168. if (ret < 0)
  1169. goto fail;
  1170. attempts++;
  1171. if (s->http_code == 407 &&
  1172. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  1173. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  1174. ffurl_closep(&s->hd);
  1175. goto redo;
  1176. }
  1177. if (s->http_code < 400)
  1178. return 0;
  1179. ret = ff_http_averror(s->http_code, AVERROR(EIO));
  1180. fail:
  1181. http_proxy_close(h);
  1182. return ret;
  1183. }
  1184. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  1185. {
  1186. HTTPContext *s = h->priv_data;
  1187. return ffurl_write(s->hd, buf, size);
  1188. }
  1189. URLProtocol ff_httpproxy_protocol = {
  1190. .name = "httpproxy",
  1191. .url_open = http_proxy_open,
  1192. .url_read = http_buf_read,
  1193. .url_write = http_proxy_write,
  1194. .url_close = http_proxy_close,
  1195. .url_get_file_handle = http_get_file_handle,
  1196. .priv_data_size = sizeof(HTTPContext),
  1197. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1198. };
  1199. #endif /* CONFIG_HTTPPROXY_PROTOCOL */