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.

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