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.

1640 lines
53KB

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