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.

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