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.

1937 lines
64KB

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