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.

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