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.

2001 lines
66KB

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