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.

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