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.

1861 lines
62KB

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