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.

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