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.

1674 lines
56KB

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