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.

1698 lines
56KB

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