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.

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