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.

1421 lines
46KB

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