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.

1663 lines
55KB

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