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.

1650 lines
54KB

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