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.

1805 lines
60KB

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