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.

1316 lines
43KB

  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/avstring.h"
  26. #include "libavutil/opt.h"
  27. #include "avformat.h"
  28. #include "http.h"
  29. #include "httpauth.h"
  30. #include "internal.h"
  31. #include "network.h"
  32. #include "os_support.h"
  33. #include "url.h"
  34. /* XXX: POST protocol is not completely implemented because ffmpeg uses
  35. * only a subset of it. */
  36. /* The IO buffer size is unrelated to the max URL size in itself, but needs
  37. * to be large enough to fit the full request headers (including long
  38. * path names). */
  39. #define BUFFER_SIZE MAX_URL_SIZE
  40. #define MAX_REDIRECTS 8
  41. typedef struct {
  42. const AVClass *class;
  43. URLContext *hd;
  44. unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
  45. int line_count;
  46. int http_code;
  47. /* Used if "Transfer-Encoding: chunked" otherwise -1. */
  48. int64_t chunksize;
  49. int64_t off, end_off, filesize;
  50. char *location;
  51. HTTPAuthState auth_state;
  52. HTTPAuthState proxy_auth_state;
  53. char *headers;
  54. char *mime_type;
  55. char *user_agent;
  56. char *content_type;
  57. /* Set if the server correctly handles Connection: close and will close
  58. * the connection after feeding us the content. */
  59. int willclose;
  60. int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
  61. int chunked_post;
  62. /* A flag which indicates if the end of chunked encoding has been sent. */
  63. int end_chunked_post;
  64. /* A flag which indicates we have finished to read POST reply. */
  65. int end_header;
  66. /* A flag which indicates if we use persistent connections. */
  67. int multiple_requests;
  68. uint8_t *post_data;
  69. int post_datalen;
  70. int is_akamai;
  71. int is_mediagateway;
  72. char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
  73. int icy;
  74. /* how much data was read since the last ICY metadata packet */
  75. int icy_data_read;
  76. /* after how many bytes of read data a new metadata packet will be found */
  77. int icy_metaint;
  78. char *icy_metadata_headers;
  79. char *icy_metadata_packet;
  80. AVDictionary *metadata;
  81. #if CONFIG_ZLIB
  82. int compressed;
  83. z_stream inflate_stream;
  84. uint8_t *inflate_buffer;
  85. #endif /* CONFIG_ZLIB */
  86. AVDictionary *chained_options;
  87. int send_expect_100;
  88. char *method;
  89. } HTTPContext;
  90. #define OFFSET(x) offsetof(HTTPContext, x)
  91. #define D AV_OPT_FLAG_DECODING_PARAM
  92. #define E AV_OPT_FLAG_ENCODING_PARAM
  93. #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
  94. static const AVOption options[] = {
  95. { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
  96. { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  97. { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
  98. { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
  99. { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
  100. { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
  101. { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
  102. { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
  103. { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
  104. { "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, { 0 }, 0, 0, D },
  105. { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
  106. { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
  107. { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
  108. { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
  109. { "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"},
  110. { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
  111. { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
  112. { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
  113. { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
  114. { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
  115. { "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 },
  116. { "method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
  117. { NULL }
  118. };
  119. static int http_connect(URLContext *h, const char *path, const char *local_path,
  120. const char *hoststr, const char *auth,
  121. const char *proxyauth, int *new_location);
  122. void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
  123. {
  124. memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
  125. &((HTTPContext *)src->priv_data)->auth_state,
  126. sizeof(HTTPAuthState));
  127. memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
  128. &((HTTPContext *)src->priv_data)->proxy_auth_state,
  129. sizeof(HTTPAuthState));
  130. }
  131. static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
  132. {
  133. const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
  134. char hostname[1024], hoststr[1024], proto[10];
  135. char auth[1024], proxyauth[1024] = "";
  136. char path1[MAX_URL_SIZE];
  137. char buf[1024], urlbuf[MAX_URL_SIZE];
  138. int port, use_proxy, err, location_changed = 0;
  139. HTTPContext *s = h->priv_data;
  140. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  141. hostname, sizeof(hostname), &port,
  142. path1, sizeof(path1), s->location);
  143. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  144. proxy_path = getenv("http_proxy");
  145. use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
  146. proxy_path && av_strstart(proxy_path, "http://", NULL);
  147. if (!strcmp(proto, "https")) {
  148. lower_proto = "tls";
  149. use_proxy = 0;
  150. if (port < 0)
  151. port = 443;
  152. }
  153. if (port < 0)
  154. port = 80;
  155. if (path1[0] == '\0')
  156. path = "/";
  157. else
  158. path = path1;
  159. local_path = path;
  160. if (use_proxy) {
  161. /* Reassemble the request URL without auth string - we don't
  162. * want to leak the auth to the proxy. */
  163. ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
  164. path1);
  165. path = urlbuf;
  166. av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
  167. hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
  168. }
  169. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  170. if (!s->hd) {
  171. err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
  172. &h->interrupt_callback, options);
  173. if (err < 0)
  174. return err;
  175. }
  176. err = http_connect(h, path, local_path, hoststr,
  177. auth, proxyauth, &location_changed);
  178. if (err < 0)
  179. return err;
  180. return location_changed;
  181. }
  182. /* return non zero if error */
  183. static int http_open_cnx(URLContext *h, AVDictionary **options)
  184. {
  185. HTTPAuthType cur_auth_type, cur_proxy_auth_type;
  186. HTTPContext *s = h->priv_data;
  187. int location_changed, attempts = 0, redirects = 0;
  188. redo:
  189. if (attempts > 0)
  190. av_dict_copy(options, s->chained_options, 0);
  191. cur_auth_type = s->auth_state.auth_type;
  192. cur_proxy_auth_type = s->auth_state.auth_type;
  193. location_changed = http_open_cnx_internal(h, options);
  194. if (location_changed < 0)
  195. goto fail;
  196. attempts++;
  197. if (s->http_code == 401) {
  198. if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
  199. s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  200. ffurl_closep(&s->hd);
  201. goto redo;
  202. } else
  203. goto fail;
  204. }
  205. if (s->http_code == 407) {
  206. if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  207. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  208. ffurl_closep(&s->hd);
  209. goto redo;
  210. } else
  211. goto fail;
  212. }
  213. if ((s->http_code == 301 || s->http_code == 302 ||
  214. s->http_code == 303 || s->http_code == 307) &&
  215. location_changed == 1) {
  216. /* url moved, get next */
  217. ffurl_closep(&s->hd);
  218. if (redirects++ >= MAX_REDIRECTS)
  219. return AVERROR(EIO);
  220. /* Restart the authentication process with the new target, which
  221. * might use a different auth mechanism. */
  222. memset(&s->auth_state, 0, sizeof(s->auth_state));
  223. attempts = 0;
  224. location_changed = 0;
  225. goto redo;
  226. }
  227. return 0;
  228. fail:
  229. if (s->hd)
  230. ffurl_closep(&s->hd);
  231. if (location_changed < 0)
  232. return location_changed;
  233. return ff_http_averror(s->http_code, AVERROR(EIO));
  234. }
  235. int ff_http_do_new_request(URLContext *h, const char *uri)
  236. {
  237. HTTPContext *s = h->priv_data;
  238. AVDictionary *options = NULL;
  239. int ret;
  240. s->off = 0;
  241. s->icy_data_read = 0;
  242. av_free(s->location);
  243. s->location = av_strdup(uri);
  244. if (!s->location)
  245. return AVERROR(ENOMEM);
  246. av_dict_copy(&options, s->chained_options, 0);
  247. ret = http_open_cnx(h, &options);
  248. av_dict_free(&options);
  249. return ret;
  250. }
  251. int ff_http_averror(int status_code, int default_averror)
  252. {
  253. switch (status_code) {
  254. case 400: return AVERROR_HTTP_BAD_REQUEST;
  255. case 401: return AVERROR_HTTP_UNAUTHORIZED;
  256. case 403: return AVERROR_HTTP_FORBIDDEN;
  257. case 404: return AVERROR_HTTP_NOT_FOUND;
  258. default: break;
  259. }
  260. if (status_code >= 400 && status_code <= 499)
  261. return AVERROR_HTTP_OTHER_4XX;
  262. else if (status_code >= 500)
  263. return AVERROR_HTTP_SERVER_ERROR;
  264. else
  265. return default_averror;
  266. }
  267. static int http_open(URLContext *h, const char *uri, int flags,
  268. AVDictionary **options)
  269. {
  270. HTTPContext *s = h->priv_data;
  271. int ret;
  272. if( s->seekable == 1 )
  273. h->is_streamed = 0;
  274. else
  275. h->is_streamed = 1;
  276. s->filesize = -1;
  277. s->location = av_strdup(uri);
  278. if (!s->location)
  279. return AVERROR(ENOMEM);
  280. if (options)
  281. av_dict_copy(&s->chained_options, *options, 0);
  282. if (s->headers) {
  283. int len = strlen(s->headers);
  284. if (len < 2 || strcmp("\r\n", s->headers + len - 2))
  285. av_log(h, AV_LOG_WARNING,
  286. "No trailing CRLF found in HTTP header.\n");
  287. }
  288. ret = http_open_cnx(h, options);
  289. if (ret < 0)
  290. av_dict_free(&s->chained_options);
  291. return ret;
  292. }
  293. static int http_getc(HTTPContext *s)
  294. {
  295. int len;
  296. if (s->buf_ptr >= s->buf_end) {
  297. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  298. if (len < 0) {
  299. return len;
  300. } else if (len == 0) {
  301. return AVERROR_EOF;
  302. } else {
  303. s->buf_ptr = s->buffer;
  304. s->buf_end = s->buffer + len;
  305. }
  306. }
  307. return *s->buf_ptr++;
  308. }
  309. static int http_get_line(HTTPContext *s, char *line, int line_size)
  310. {
  311. int ch;
  312. char *q;
  313. q = line;
  314. for (;;) {
  315. ch = http_getc(s);
  316. if (ch < 0)
  317. return ch;
  318. if (ch == '\n') {
  319. /* process line */
  320. if (q > line && q[-1] == '\r')
  321. q--;
  322. *q = '\0';
  323. return 0;
  324. } else {
  325. if ((q - line) < line_size - 1)
  326. *q++ = ch;
  327. }
  328. }
  329. }
  330. static int check_http_code(URLContext *h, int http_code, const char *end)
  331. {
  332. HTTPContext *s = h->priv_data;
  333. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  334. * don't abort until all headers have been parsed. */
  335. if (http_code >= 400 && http_code < 600 &&
  336. (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  337. (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  338. end += strspn(end, SPACE_CHARS);
  339. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
  340. return ff_http_averror(http_code, AVERROR(EIO));
  341. }
  342. return 0;
  343. }
  344. static int parse_location(HTTPContext *s, const char *p)
  345. {
  346. char redirected_location[MAX_URL_SIZE], *new_loc;
  347. ff_make_absolute_url(redirected_location, sizeof(redirected_location),
  348. s->location, p);
  349. new_loc = av_strdup(redirected_location);
  350. if (!new_loc)
  351. return AVERROR(ENOMEM);
  352. av_free(s->location);
  353. s->location = new_loc;
  354. return 0;
  355. }
  356. /* "bytes $from-$to/$document_size" */
  357. static void parse_content_range(URLContext *h, const char *p)
  358. {
  359. HTTPContext *s = h->priv_data;
  360. const char *slash;
  361. if (!strncmp(p, "bytes ", 6)) {
  362. p += 6;
  363. s->off = strtoll(p, NULL, 10);
  364. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  365. s->filesize = strtoll(slash + 1, NULL, 10);
  366. }
  367. if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
  368. h->is_streamed = 0; /* we _can_ in fact seek */
  369. }
  370. static int parse_content_encoding(URLContext *h, const char *p)
  371. {
  372. if (!av_strncasecmp(p, "gzip", 4) ||
  373. !av_strncasecmp(p, "deflate", 7)) {
  374. #if CONFIG_ZLIB
  375. HTTPContext *s = h->priv_data;
  376. s->compressed = 1;
  377. inflateEnd(&s->inflate_stream);
  378. if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
  379. av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
  380. s->inflate_stream.msg);
  381. return AVERROR(ENOSYS);
  382. }
  383. if (zlibCompileFlags() & (1 << 17)) {
  384. av_log(h, AV_LOG_WARNING,
  385. "Your zlib was compiled without gzip support.\n");
  386. return AVERROR(ENOSYS);
  387. }
  388. #else
  389. av_log(h, AV_LOG_WARNING,
  390. "Compressed (%s) content, need zlib with gzip support\n", p);
  391. return AVERROR(ENOSYS);
  392. #endif /* CONFIG_ZLIB */
  393. } else if (!av_strncasecmp(p, "identity", 8)) {
  394. // The normal, no-encoding case (although servers shouldn't include
  395. // the header at all if this is the case).
  396. } else {
  397. av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
  398. }
  399. return 0;
  400. }
  401. // Concat all Icy- header lines
  402. static int parse_icy(HTTPContext *s, const char *tag, const char *p)
  403. {
  404. int len = 4 + strlen(p) + strlen(tag);
  405. int is_first = !s->icy_metadata_headers;
  406. int ret;
  407. av_dict_set(&s->metadata, tag, p, 0);
  408. if (s->icy_metadata_headers)
  409. len += strlen(s->icy_metadata_headers);
  410. if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
  411. return ret;
  412. if (is_first)
  413. *s->icy_metadata_headers = '\0';
  414. av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
  415. return 0;
  416. }
  417. static int process_line(URLContext *h, char *line, int line_count,
  418. int *new_location)
  419. {
  420. HTTPContext *s = h->priv_data;
  421. char *tag, *p, *end;
  422. int ret;
  423. /* end of header */
  424. if (line[0] == '\0') {
  425. s->end_header = 1;
  426. return 0;
  427. }
  428. p = line;
  429. if (line_count == 0) {
  430. while (!av_isspace(*p) && *p != '\0')
  431. p++;
  432. while (av_isspace(*p))
  433. p++;
  434. s->http_code = strtol(p, &end, 10);
  435. av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
  436. if ((ret = check_http_code(h, s->http_code, end)) < 0)
  437. return ret;
  438. } else {
  439. while (*p != '\0' && *p != ':')
  440. p++;
  441. if (*p != ':')
  442. return 1;
  443. *p = '\0';
  444. tag = line;
  445. p++;
  446. while (av_isspace(*p))
  447. p++;
  448. if (!av_strcasecmp(tag, "Location")) {
  449. if ((ret = parse_location(s, p)) < 0)
  450. return ret;
  451. *new_location = 1;
  452. } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
  453. s->filesize = strtoll(p, NULL, 10);
  454. } else if (!av_strcasecmp(tag, "Content-Range")) {
  455. parse_content_range(h, p);
  456. } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
  457. !strncmp(p, "bytes", 5) &&
  458. s->seekable == -1) {
  459. h->is_streamed = 0;
  460. } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
  461. !av_strncasecmp(p, "chunked", 7)) {
  462. s->filesize = -1;
  463. s->chunksize = 0;
  464. } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
  465. ff_http_auth_handle_header(&s->auth_state, tag, p);
  466. } else if (!av_strcasecmp(tag, "Authentication-Info")) {
  467. ff_http_auth_handle_header(&s->auth_state, tag, p);
  468. } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
  469. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  470. } else if (!av_strcasecmp(tag, "Connection")) {
  471. if (!strcmp(p, "close"))
  472. s->willclose = 1;
  473. } else if (!av_strcasecmp(tag, "Server")) {
  474. if (!av_strcasecmp(p, "AkamaiGHost")) {
  475. s->is_akamai = 1;
  476. } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
  477. s->is_mediagateway = 1;
  478. }
  479. } else if (!av_strcasecmp(tag, "Content-Type")) {
  480. av_free(s->mime_type);
  481. s->mime_type = av_strdup(p);
  482. } else if (!av_strcasecmp(tag, "Set-Cookie")) {
  483. if (!s->cookies) {
  484. if (!(s->cookies = av_strdup(p)))
  485. return AVERROR(ENOMEM);
  486. } else {
  487. char *tmp = s->cookies;
  488. size_t str_size = strlen(tmp) + strlen(p) + 2;
  489. if (!(s->cookies = av_malloc(str_size))) {
  490. s->cookies = tmp;
  491. return AVERROR(ENOMEM);
  492. }
  493. snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
  494. av_free(tmp);
  495. }
  496. } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
  497. s->icy_metaint = strtoll(p, NULL, 10);
  498. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  499. if ((ret = parse_icy(s, tag, p)) < 0)
  500. return ret;
  501. } else if (!av_strcasecmp(tag, "Content-Encoding")) {
  502. if ((ret = parse_content_encoding(h, p)) < 0)
  503. return ret;
  504. }
  505. }
  506. return 1;
  507. }
  508. /**
  509. * Create a string containing cookie values for use as a HTTP cookie header
  510. * field value for a particular path and domain from the cookie values stored in
  511. * the HTTP protocol context. The cookie string is stored in *cookies.
  512. *
  513. * @return a negative value if an error condition occurred, 0 otherwise
  514. */
  515. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  516. const char *domain)
  517. {
  518. // cookie strings will look like Set-Cookie header field values. Multiple
  519. // Set-Cookie fields will result in multiple values delimited by a newline
  520. int ret = 0;
  521. char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
  522. if (!set_cookies) return AVERROR(EINVAL);
  523. *cookies = NULL;
  524. while ((cookie = av_strtok(set_cookies, "\n", &next))) {
  525. int domain_offset = 0;
  526. char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
  527. set_cookies = NULL;
  528. while ((param = av_strtok(cookie, "; ", &next_param))) {
  529. if (cookie) {
  530. // first key-value pair is the actual cookie value
  531. cvalue = av_strdup(param);
  532. cookie = NULL;
  533. } else if (!av_strncasecmp("path=", param, 5)) {
  534. av_free(cpath);
  535. cpath = av_strdup(&param[5]);
  536. } else if (!av_strncasecmp("domain=", param, 7)) {
  537. // if the cookie specifies a sub-domain, skip the leading dot thereby
  538. // supporting URLs that point to sub-domains and the master domain
  539. int leading_dot = (param[7] == '.');
  540. av_free(cdomain);
  541. cdomain = av_strdup(&param[7+leading_dot]);
  542. } else {
  543. // ignore unknown attributes
  544. }
  545. }
  546. if (!cdomain)
  547. cdomain = av_strdup(domain);
  548. // ensure all of the necessary values are valid
  549. if (!cdomain || !cpath || !cvalue) {
  550. av_log(s, AV_LOG_WARNING,
  551. "Invalid cookie found, no value, path or domain specified\n");
  552. goto done_cookie;
  553. }
  554. // check if the request path matches the cookie path
  555. if (av_strncasecmp(path, cpath, strlen(cpath)))
  556. goto done_cookie;
  557. // the domain should be at least the size of our cookie domain
  558. domain_offset = strlen(domain) - strlen(cdomain);
  559. if (domain_offset < 0)
  560. goto done_cookie;
  561. // match the cookie domain
  562. if (av_strcasecmp(&domain[domain_offset], cdomain))
  563. goto done_cookie;
  564. // cookie parameters match, so copy the value
  565. if (!*cookies) {
  566. if (!(*cookies = av_strdup(cvalue))) {
  567. ret = AVERROR(ENOMEM);
  568. goto done_cookie;
  569. }
  570. } else {
  571. char *tmp = *cookies;
  572. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  573. if (!(*cookies = av_malloc(str_size))) {
  574. ret = AVERROR(ENOMEM);
  575. goto done_cookie;
  576. }
  577. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  578. av_free(tmp);
  579. }
  580. done_cookie:
  581. av_free(cdomain);
  582. av_free(cpath);
  583. av_free(cvalue);
  584. if (ret < 0) {
  585. if (*cookies) av_freep(cookies);
  586. av_free(cset_cookies);
  587. return ret;
  588. }
  589. }
  590. av_free(cset_cookies);
  591. return 0;
  592. }
  593. static inline int has_header(const char *str, const char *header)
  594. {
  595. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  596. if (!str)
  597. return 0;
  598. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  599. }
  600. static int http_read_header(URLContext *h, int *new_location)
  601. {
  602. HTTPContext *s = h->priv_data;
  603. char line[MAX_URL_SIZE];
  604. int err = 0;
  605. s->chunksize = -1;
  606. for (;;) {
  607. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  608. return err;
  609. av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
  610. err = process_line(h, line, s->line_count, new_location);
  611. if (err < 0)
  612. return err;
  613. if (err == 0)
  614. break;
  615. s->line_count++;
  616. }
  617. if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
  618. h->is_streamed = 1; /* we can in fact _not_ seek */
  619. return err;
  620. }
  621. static int http_connect(URLContext *h, const char *path, const char *local_path,
  622. const char *hoststr, const char *auth,
  623. const char *proxyauth, int *new_location)
  624. {
  625. HTTPContext *s = h->priv_data;
  626. int post, err;
  627. char headers[HTTP_HEADERS_SIZE] = "";
  628. char *authstr = NULL, *proxyauthstr = NULL;
  629. int64_t off = s->off;
  630. int len = 0;
  631. const char *method;
  632. int send_expect_100 = 0;
  633. /* send http header */
  634. post = h->flags & AVIO_FLAG_WRITE;
  635. if (s->post_data) {
  636. /* force POST method and disable chunked encoding when
  637. * custom HTTP post data is set */
  638. post = 1;
  639. s->chunked_post = 0;
  640. }
  641. if (s->method)
  642. method = s->method;
  643. else
  644. method = post ? "POST" : "GET";
  645. authstr = ff_http_auth_create_response(&s->auth_state, auth,
  646. local_path, method);
  647. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  648. local_path, method);
  649. if (post && !s->post_data) {
  650. send_expect_100 = s->send_expect_100;
  651. /* The user has supplied authentication but we don't know the auth type,
  652. * send Expect: 100-continue to get the 401 response including the
  653. * WWW-Authenticate header, or an 100 continue if no auth actually
  654. * is needed. */
  655. if (auth && *auth &&
  656. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  657. s->http_code != 401)
  658. send_expect_100 = 1;
  659. }
  660. /* set default headers if needed */
  661. if (!has_header(s->headers, "\r\nUser-Agent: "))
  662. len += av_strlcatf(headers + len, sizeof(headers) - len,
  663. "User-Agent: %s\r\n", s->user_agent);
  664. if (!has_header(s->headers, "\r\nAccept: "))
  665. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  666. sizeof(headers) - len);
  667. // Note: we send this on purpose even when s->off is 0 when we're probing,
  668. // since it allows us to detect more reliably if a (non-conforming)
  669. // server supports seeking by analysing the reply headers.
  670. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
  671. len += av_strlcatf(headers + len, sizeof(headers) - len,
  672. "Range: bytes=%"PRId64"-", s->off);
  673. if (s->end_off)
  674. len += av_strlcatf(headers + len, sizeof(headers) - len,
  675. "%"PRId64, s->end_off - 1);
  676. len += av_strlcpy(headers + len, "\r\n",
  677. sizeof(headers) - len);
  678. }
  679. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  680. len += av_strlcatf(headers + len, sizeof(headers) - len,
  681. "Expect: 100-continue\r\n");
  682. if (!has_header(s->headers, "\r\nConnection: ")) {
  683. if (s->multiple_requests)
  684. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  685. sizeof(headers) - len);
  686. else
  687. len += av_strlcpy(headers + len, "Connection: close\r\n",
  688. sizeof(headers) - len);
  689. }
  690. if (!has_header(s->headers, "\r\nHost: "))
  691. len += av_strlcatf(headers + len, sizeof(headers) - len,
  692. "Host: %s\r\n", hoststr);
  693. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  694. len += av_strlcatf(headers + len, sizeof(headers) - len,
  695. "Content-Length: %d\r\n", s->post_datalen);
  696. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  697. len += av_strlcatf(headers + len, sizeof(headers) - len,
  698. "Content-Type: %s\r\n", s->content_type);
  699. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  700. char *cookies = NULL;
  701. if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
  702. len += av_strlcatf(headers + len, sizeof(headers) - len,
  703. "Cookie: %s\r\n", cookies);
  704. av_free(cookies);
  705. }
  706. }
  707. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
  708. len += av_strlcatf(headers + len, sizeof(headers) - len,
  709. "Icy-MetaData: %d\r\n", 1);
  710. /* now add in custom headers */
  711. if (s->headers)
  712. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  713. snprintf(s->buffer, sizeof(s->buffer),
  714. "%s %s HTTP/1.1\r\n"
  715. "%s"
  716. "%s"
  717. "%s"
  718. "%s%s"
  719. "\r\n",
  720. method,
  721. path,
  722. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  723. headers,
  724. authstr ? authstr : "",
  725. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  726. av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
  727. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  728. goto done;
  729. if (s->post_data)
  730. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  731. goto done;
  732. /* init input buffer */
  733. s->buf_ptr = s->buffer;
  734. s->buf_end = s->buffer;
  735. s->line_count = 0;
  736. s->off = 0;
  737. s->icy_data_read = 0;
  738. s->filesize = -1;
  739. s->willclose = 0;
  740. s->end_chunked_post = 0;
  741. s->end_header = 0;
  742. if (post && !s->post_data && !send_expect_100) {
  743. /* Pretend that it did work. We didn't read any header yet, since
  744. * we've still to send the POST data, but the code calling this
  745. * function will check http_code after we return. */
  746. s->http_code = 200;
  747. err = 0;
  748. goto done;
  749. }
  750. /* wait for header */
  751. err = http_read_header(h, new_location);
  752. if (err < 0)
  753. goto done;
  754. err = (off == s->off) ? 0 : -1;
  755. done:
  756. av_freep(&authstr);
  757. av_freep(&proxyauthstr);
  758. return err;
  759. }
  760. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  761. {
  762. HTTPContext *s = h->priv_data;
  763. int len;
  764. /* read bytes from input buffer first */
  765. len = s->buf_end - s->buf_ptr;
  766. if (len > 0) {
  767. if (len > size)
  768. len = size;
  769. memcpy(buf, s->buf_ptr, len);
  770. s->buf_ptr += len;
  771. } else {
  772. if ((!s->willclose || s->chunksize < 0) &&
  773. s->filesize >= 0 && s->off >= s->filesize)
  774. return AVERROR_EOF;
  775. len = ffurl_read(s->hd, buf, size);
  776. }
  777. if (len > 0) {
  778. s->off += len;
  779. if (s->chunksize > 0)
  780. s->chunksize -= len;
  781. }
  782. return len;
  783. }
  784. #if CONFIG_ZLIB
  785. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  786. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  787. {
  788. HTTPContext *s = h->priv_data;
  789. int ret;
  790. if (!s->inflate_buffer) {
  791. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  792. if (!s->inflate_buffer)
  793. return AVERROR(ENOMEM);
  794. }
  795. if (s->inflate_stream.avail_in == 0) {
  796. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  797. if (read <= 0)
  798. return read;
  799. s->inflate_stream.next_in = s->inflate_buffer;
  800. s->inflate_stream.avail_in = read;
  801. }
  802. s->inflate_stream.avail_out = size;
  803. s->inflate_stream.next_out = buf;
  804. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  805. if (ret != Z_OK && ret != Z_STREAM_END)
  806. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
  807. ret, s->inflate_stream.msg);
  808. return size - s->inflate_stream.avail_out;
  809. }
  810. #endif /* CONFIG_ZLIB */
  811. static int http_read_stream(URLContext *h, uint8_t *buf, int size)
  812. {
  813. HTTPContext *s = h->priv_data;
  814. int err, new_location;
  815. if (!s->hd)
  816. return AVERROR_EOF;
  817. if (s->end_chunked_post && !s->end_header) {
  818. err = http_read_header(h, &new_location);
  819. if (err < 0)
  820. return err;
  821. }
  822. if (s->chunksize >= 0) {
  823. if (!s->chunksize) {
  824. char line[32];
  825. do {
  826. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  827. return err;
  828. } while (!*line); /* skip CR LF from last chunk */
  829. s->chunksize = strtoll(line, NULL, 16);
  830. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
  831. s->chunksize);
  832. if (!s->chunksize)
  833. return 0;
  834. }
  835. size = FFMIN(size, s->chunksize);
  836. }
  837. #if CONFIG_ZLIB
  838. if (s->compressed)
  839. return http_buf_read_compressed(h, buf, size);
  840. #endif /* CONFIG_ZLIB */
  841. return http_buf_read(h, buf, size);
  842. }
  843. // Like http_read_stream(), but no short reads.
  844. // Assumes partial reads are an error.
  845. static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
  846. {
  847. int pos = 0;
  848. while (pos < size) {
  849. int len = http_read_stream(h, buf + pos, size - pos);
  850. if (len < 0)
  851. return len;
  852. pos += len;
  853. }
  854. return pos;
  855. }
  856. static void update_metadata(HTTPContext *s, char *data)
  857. {
  858. char *key;
  859. char *val;
  860. char *end;
  861. char *next = data;
  862. while (*next) {
  863. key = next;
  864. val = strstr(key, "='");
  865. if (!val)
  866. break;
  867. end = strstr(val, "';");
  868. if (!end)
  869. break;
  870. *val = '\0';
  871. *end = '\0';
  872. val += 2;
  873. av_dict_set(&s->metadata, key, val, 0);
  874. next = end + 2;
  875. }
  876. }
  877. static int store_icy(URLContext *h, int size)
  878. {
  879. HTTPContext *s = h->priv_data;
  880. /* until next metadata packet */
  881. int remaining = s->icy_metaint - s->icy_data_read;
  882. if (remaining < 0)
  883. return AVERROR_INVALIDDATA;
  884. if (!remaining) {
  885. /* The metadata packet is variable sized. It has a 1 byte header
  886. * which sets the length of the packet (divided by 16). If it's 0,
  887. * the metadata doesn't change. After the packet, icy_metaint bytes
  888. * of normal data follows. */
  889. uint8_t ch;
  890. int len = http_read_stream_all(h, &ch, 1);
  891. if (len < 0)
  892. return len;
  893. if (ch > 0) {
  894. char data[255 * 16 + 1];
  895. int ret;
  896. len = ch * 16;
  897. ret = http_read_stream_all(h, data, len);
  898. if (ret < 0)
  899. return ret;
  900. data[len + 1] = 0;
  901. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  902. return ret;
  903. update_metadata(s, data);
  904. }
  905. s->icy_data_read = 0;
  906. remaining = s->icy_metaint;
  907. }
  908. return FFMIN(size, remaining);
  909. }
  910. static int http_read(URLContext *h, uint8_t *buf, int size)
  911. {
  912. HTTPContext *s = h->priv_data;
  913. if (s->icy_metaint > 0) {
  914. size = store_icy(h, size);
  915. if (size < 0)
  916. return size;
  917. }
  918. size = http_read_stream(h, buf, size);
  919. if (size > 0)
  920. s->icy_data_read += size;
  921. return size;
  922. }
  923. /* used only when posting data */
  924. static int http_write(URLContext *h, const uint8_t *buf, int size)
  925. {
  926. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  927. int ret;
  928. char crlf[] = "\r\n";
  929. HTTPContext *s = h->priv_data;
  930. if (!s->chunked_post) {
  931. /* non-chunked data is sent without any special encoding */
  932. return ffurl_write(s->hd, buf, size);
  933. }
  934. /* silently ignore zero-size data since chunk encoding that would
  935. * signal EOF */
  936. if (size > 0) {
  937. /* upload data using chunked encoding */
  938. snprintf(temp, sizeof(temp), "%x\r\n", size);
  939. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  940. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  941. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  942. return ret;
  943. }
  944. return size;
  945. }
  946. static int http_shutdown(URLContext *h, int flags)
  947. {
  948. int ret = 0;
  949. char footer[] = "0\r\n\r\n";
  950. HTTPContext *s = h->priv_data;
  951. /* signal end of chunked encoding if used */
  952. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  953. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  954. ret = ret > 0 ? 0 : ret;
  955. s->end_chunked_post = 1;
  956. }
  957. return ret;
  958. }
  959. static int http_close(URLContext *h)
  960. {
  961. int ret = 0;
  962. HTTPContext *s = h->priv_data;
  963. #if CONFIG_ZLIB
  964. inflateEnd(&s->inflate_stream);
  965. av_freep(&s->inflate_buffer);
  966. #endif /* CONFIG_ZLIB */
  967. if (!s->end_chunked_post)
  968. /* Close the write direction by sending the end of chunked encoding. */
  969. ret = http_shutdown(h, h->flags);
  970. if (s->hd)
  971. ffurl_closep(&s->hd);
  972. av_dict_free(&s->chained_options);
  973. return ret;
  974. }
  975. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  976. {
  977. HTTPContext *s = h->priv_data;
  978. URLContext *old_hd = s->hd;
  979. int64_t old_off = s->off;
  980. uint8_t old_buf[BUFFER_SIZE];
  981. int old_buf_size, ret;
  982. AVDictionary *options = NULL;
  983. if (whence == AVSEEK_SIZE)
  984. return s->filesize;
  985. else if ((whence == SEEK_CUR && off == 0) ||
  986. (whence == SEEK_SET && off == s->off))
  987. return s->off;
  988. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  989. return AVERROR(ENOSYS);
  990. if (whence == SEEK_CUR)
  991. off += s->off;
  992. else if (whence == SEEK_END)
  993. off += s->filesize;
  994. else if (whence != SEEK_SET)
  995. return AVERROR(EINVAL);
  996. if (off < 0)
  997. return AVERROR(EINVAL);
  998. s->off = off;
  999. /* we save the old context in case the seek fails */
  1000. old_buf_size = s->buf_end - s->buf_ptr;
  1001. memcpy(old_buf, s->buf_ptr, old_buf_size);
  1002. s->hd = NULL;
  1003. /* if it fails, continue on old connection */
  1004. av_dict_copy(&options, s->chained_options, 0);
  1005. if ((ret = http_open_cnx(h, &options)) < 0) {
  1006. av_dict_free(&options);
  1007. memcpy(s->buffer, old_buf, old_buf_size);
  1008. s->buf_ptr = s->buffer;
  1009. s->buf_end = s->buffer + old_buf_size;
  1010. s->hd = old_hd;
  1011. s->off = old_off;
  1012. return ret;
  1013. }
  1014. av_dict_free(&options);
  1015. ffurl_close(old_hd);
  1016. return off;
  1017. }
  1018. static int http_get_file_handle(URLContext *h)
  1019. {
  1020. HTTPContext *s = h->priv_data;
  1021. return ffurl_get_file_handle(s->hd);
  1022. }
  1023. #define HTTP_CLASS(flavor) \
  1024. static const AVClass flavor ## _context_class = { \
  1025. .class_name = # flavor, \
  1026. .item_name = av_default_item_name, \
  1027. .option = options, \
  1028. .version = LIBAVUTIL_VERSION_INT, \
  1029. }
  1030. #if CONFIG_HTTP_PROTOCOL
  1031. HTTP_CLASS(http);
  1032. URLProtocol ff_http_protocol = {
  1033. .name = "http",
  1034. .url_open2 = http_open,
  1035. .url_read = http_read,
  1036. .url_write = http_write,
  1037. .url_seek = http_seek,
  1038. .url_close = http_close,
  1039. .url_get_file_handle = http_get_file_handle,
  1040. .url_shutdown = http_shutdown,
  1041. .priv_data_size = sizeof(HTTPContext),
  1042. .priv_data_class = &http_context_class,
  1043. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1044. };
  1045. #endif /* CONFIG_HTTP_PROTOCOL */
  1046. #if CONFIG_HTTPS_PROTOCOL
  1047. HTTP_CLASS(https);
  1048. URLProtocol ff_https_protocol = {
  1049. .name = "https",
  1050. .url_open2 = http_open,
  1051. .url_read = http_read,
  1052. .url_write = http_write,
  1053. .url_seek = http_seek,
  1054. .url_close = http_close,
  1055. .url_get_file_handle = http_get_file_handle,
  1056. .url_shutdown = http_shutdown,
  1057. .priv_data_size = sizeof(HTTPContext),
  1058. .priv_data_class = &https_context_class,
  1059. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1060. };
  1061. #endif /* CONFIG_HTTPS_PROTOCOL */
  1062. #if CONFIG_HTTPPROXY_PROTOCOL
  1063. static int http_proxy_close(URLContext *h)
  1064. {
  1065. HTTPContext *s = h->priv_data;
  1066. if (s->hd)
  1067. ffurl_closep(&s->hd);
  1068. return 0;
  1069. }
  1070. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  1071. {
  1072. HTTPContext *s = h->priv_data;
  1073. char hostname[1024], hoststr[1024];
  1074. char auth[1024], pathbuf[1024], *path;
  1075. char lower_url[100];
  1076. int port, ret = 0, attempts = 0;
  1077. HTTPAuthType cur_auth_type;
  1078. char *authstr;
  1079. int new_loc;
  1080. if( s->seekable == 1 )
  1081. h->is_streamed = 0;
  1082. else
  1083. h->is_streamed = 1;
  1084. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  1085. pathbuf, sizeof(pathbuf), uri);
  1086. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  1087. path = pathbuf;
  1088. if (*path == '/')
  1089. path++;
  1090. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  1091. NULL);
  1092. redo:
  1093. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  1094. &h->interrupt_callback, NULL);
  1095. if (ret < 0)
  1096. return ret;
  1097. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  1098. path, "CONNECT");
  1099. snprintf(s->buffer, sizeof(s->buffer),
  1100. "CONNECT %s HTTP/1.1\r\n"
  1101. "Host: %s\r\n"
  1102. "Connection: close\r\n"
  1103. "%s%s"
  1104. "\r\n",
  1105. path,
  1106. hoststr,
  1107. authstr ? "Proxy-" : "", authstr ? authstr : "");
  1108. av_freep(&authstr);
  1109. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  1110. goto fail;
  1111. s->buf_ptr = s->buffer;
  1112. s->buf_end = s->buffer;
  1113. s->line_count = 0;
  1114. s->filesize = -1;
  1115. cur_auth_type = s->proxy_auth_state.auth_type;
  1116. /* Note: This uses buffering, potentially reading more than the
  1117. * HTTP header. If tunneling a protocol where the server starts
  1118. * the conversation, we might buffer part of that here, too.
  1119. * Reading that requires using the proper ffurl_read() function
  1120. * on this URLContext, not using the fd directly (as the tls
  1121. * protocol does). This shouldn't be an issue for tls though,
  1122. * since the client starts the conversation there, so there
  1123. * is no extra data that we might buffer up here.
  1124. */
  1125. ret = http_read_header(h, &new_loc);
  1126. if (ret < 0)
  1127. goto fail;
  1128. attempts++;
  1129. if (s->http_code == 407 &&
  1130. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  1131. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  1132. ffurl_closep(&s->hd);
  1133. goto redo;
  1134. }
  1135. if (s->http_code < 400)
  1136. return 0;
  1137. ret = ff_http_averror(s->http_code, AVERROR(EIO));
  1138. fail:
  1139. http_proxy_close(h);
  1140. return ret;
  1141. }
  1142. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  1143. {
  1144. HTTPContext *s = h->priv_data;
  1145. return ffurl_write(s->hd, buf, size);
  1146. }
  1147. URLProtocol ff_httpproxy_protocol = {
  1148. .name = "httpproxy",
  1149. .url_open = http_proxy_open,
  1150. .url_read = http_buf_read,
  1151. .url_write = http_proxy_write,
  1152. .url_close = http_proxy_close,
  1153. .url_get_file_handle = http_get_file_handle,
  1154. .priv_data_size = sizeof(HTTPContext),
  1155. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1156. };
  1157. #endif /* CONFIG_HTTPPROXY_PROTOCOL */