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.

1488 lines
49KB

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