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.

1906 lines
63KB

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