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.

1486 lines
49KB

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