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.

1478 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. char *tag, *p, *end, *method, *resource, *version;
  503. int ret;
  504. /* end of header */
  505. if (line[0] == '\0') {
  506. s->end_header = 1;
  507. return 0;
  508. }
  509. p = line;
  510. if (line_count == 0) {
  511. if (s->listen) {
  512. // HTTP method
  513. method = p;
  514. while (!av_isspace(*p))
  515. p++;
  516. *(p++) = '\0';
  517. av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
  518. if (s->method) {
  519. if (av_strcasecmp(s->method, method)) {
  520. av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
  521. s->method, method);
  522. return ff_http_averror(400, AVERROR(EIO));
  523. }
  524. }
  525. // HTTP resource
  526. while (av_isspace(*p))
  527. p++;
  528. resource = p;
  529. while (!av_isspace(*p))
  530. p++;
  531. *(p++) = '\0';
  532. av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
  533. // HTTP version
  534. while (av_isspace(*p))
  535. p++;
  536. version = p;
  537. while (!av_isspace(*p))
  538. p++;
  539. *p = '\0';
  540. if (av_strncasecmp(version, "HTTP/", 5)) {
  541. av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
  542. return ff_http_averror(400, AVERROR(EIO));
  543. }
  544. av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
  545. } else {
  546. /* TODO: reindent */
  547. while (!av_isspace(*p) && *p != '\0')
  548. p++;
  549. while (av_isspace(*p))
  550. p++;
  551. s->http_code = strtol(p, &end, 10);
  552. av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
  553. if ((ret = check_http_code(h, s->http_code, end)) < 0)
  554. return ret;
  555. }
  556. } else {
  557. while (*p != '\0' && *p != ':')
  558. p++;
  559. if (*p != ':')
  560. return 1;
  561. *p = '\0';
  562. tag = line;
  563. p++;
  564. while (av_isspace(*p))
  565. p++;
  566. if (!av_strcasecmp(tag, "Location")) {
  567. if ((ret = parse_location(s, p)) < 0)
  568. return ret;
  569. *new_location = 1;
  570. } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
  571. s->filesize = strtoll(p, NULL, 10);
  572. } else if (!av_strcasecmp(tag, "Content-Range")) {
  573. parse_content_range(h, p);
  574. } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
  575. !strncmp(p, "bytes", 5) &&
  576. s->seekable == -1) {
  577. h->is_streamed = 0;
  578. } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
  579. !av_strncasecmp(p, "chunked", 7)) {
  580. s->filesize = -1;
  581. s->chunksize = 0;
  582. } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
  583. ff_http_auth_handle_header(&s->auth_state, tag, p);
  584. } else if (!av_strcasecmp(tag, "Authentication-Info")) {
  585. ff_http_auth_handle_header(&s->auth_state, tag, p);
  586. } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
  587. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  588. } else if (!av_strcasecmp(tag, "Connection")) {
  589. if (!strcmp(p, "close"))
  590. s->willclose = 1;
  591. } else if (!av_strcasecmp(tag, "Server")) {
  592. if (!av_strcasecmp(p, "AkamaiGHost")) {
  593. s->is_akamai = 1;
  594. } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
  595. s->is_mediagateway = 1;
  596. }
  597. } else if (!av_strcasecmp(tag, "Content-Type")) {
  598. av_free(s->mime_type);
  599. s->mime_type = av_strdup(p);
  600. } else if (!av_strcasecmp(tag, "Set-Cookie")) {
  601. if (parse_cookie(s, p, &s->cookie_dict))
  602. av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
  603. } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
  604. s->icy_metaint = strtoll(p, NULL, 10);
  605. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  606. if ((ret = parse_icy(s, tag, p)) < 0)
  607. return ret;
  608. } else if (!av_strcasecmp(tag, "Content-Encoding")) {
  609. if ((ret = parse_content_encoding(h, p)) < 0)
  610. return ret;
  611. }
  612. }
  613. return 1;
  614. }
  615. /**
  616. * Create a string containing cookie values for use as a HTTP cookie header
  617. * field value for a particular path and domain from the cookie values stored in
  618. * the HTTP protocol context. The cookie string is stored in *cookies.
  619. *
  620. * @return a negative value if an error condition occurred, 0 otherwise
  621. */
  622. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  623. const char *domain)
  624. {
  625. // cookie strings will look like Set-Cookie header field values. Multiple
  626. // Set-Cookie fields will result in multiple values delimited by a newline
  627. int ret = 0;
  628. char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
  629. if (!set_cookies) return AVERROR(EINVAL);
  630. // destroy any cookies in the dictionary.
  631. av_dict_free(&s->cookie_dict);
  632. *cookies = NULL;
  633. while ((cookie = av_strtok(set_cookies, "\n", &next))) {
  634. int domain_offset = 0;
  635. char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
  636. set_cookies = NULL;
  637. // store the cookie in a dict in case it is updated in the response
  638. if (parse_cookie(s, cookie, &s->cookie_dict))
  639. av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
  640. while ((param = av_strtok(cookie, "; ", &next_param))) {
  641. if (cookie) {
  642. // first key-value pair is the actual cookie value
  643. cvalue = av_strdup(param);
  644. cookie = NULL;
  645. } else if (!av_strncasecmp("path=", param, 5)) {
  646. av_free(cpath);
  647. cpath = av_strdup(&param[5]);
  648. } else if (!av_strncasecmp("domain=", param, 7)) {
  649. // if the cookie specifies a sub-domain, skip the leading dot thereby
  650. // supporting URLs that point to sub-domains and the master domain
  651. int leading_dot = (param[7] == '.');
  652. av_free(cdomain);
  653. cdomain = av_strdup(&param[7+leading_dot]);
  654. } else {
  655. // ignore unknown attributes
  656. }
  657. }
  658. if (!cdomain)
  659. cdomain = av_strdup(domain);
  660. // ensure all of the necessary values are valid
  661. if (!cdomain || !cpath || !cvalue) {
  662. av_log(s, AV_LOG_WARNING,
  663. "Invalid cookie found, no value, path or domain specified\n");
  664. goto done_cookie;
  665. }
  666. // check if the request path matches the cookie path
  667. if (av_strncasecmp(path, cpath, strlen(cpath)))
  668. goto done_cookie;
  669. // the domain should be at least the size of our cookie domain
  670. domain_offset = strlen(domain) - strlen(cdomain);
  671. if (domain_offset < 0)
  672. goto done_cookie;
  673. // match the cookie domain
  674. if (av_strcasecmp(&domain[domain_offset], cdomain))
  675. goto done_cookie;
  676. // cookie parameters match, so copy the value
  677. if (!*cookies) {
  678. if (!(*cookies = av_strdup(cvalue))) {
  679. ret = AVERROR(ENOMEM);
  680. goto done_cookie;
  681. }
  682. } else {
  683. char *tmp = *cookies;
  684. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  685. if (!(*cookies = av_malloc(str_size))) {
  686. ret = AVERROR(ENOMEM);
  687. goto done_cookie;
  688. }
  689. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  690. av_free(tmp);
  691. }
  692. done_cookie:
  693. av_freep(&cdomain);
  694. av_freep(&cpath);
  695. av_freep(&cvalue);
  696. if (ret < 0) {
  697. if (*cookies) av_freep(cookies);
  698. av_free(cset_cookies);
  699. return ret;
  700. }
  701. }
  702. av_free(cset_cookies);
  703. return 0;
  704. }
  705. static inline int has_header(const char *str, const char *header)
  706. {
  707. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  708. if (!str)
  709. return 0;
  710. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  711. }
  712. static int http_read_header(URLContext *h, int *new_location)
  713. {
  714. HTTPContext *s = h->priv_data;
  715. char line[MAX_URL_SIZE];
  716. int err = 0;
  717. s->chunksize = -1;
  718. for (;;) {
  719. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  720. return err;
  721. av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
  722. err = process_line(h, line, s->line_count, new_location);
  723. if (err < 0)
  724. return err;
  725. if (err == 0)
  726. break;
  727. s->line_count++;
  728. }
  729. if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
  730. h->is_streamed = 1; /* we can in fact _not_ seek */
  731. // add any new cookies into the existing cookie string
  732. cookie_string(s->cookie_dict, &s->cookies);
  733. av_dict_free(&s->cookie_dict);
  734. return err;
  735. }
  736. static int http_connect(URLContext *h, const char *path, const char *local_path,
  737. const char *hoststr, const char *auth,
  738. const char *proxyauth, int *new_location)
  739. {
  740. HTTPContext *s = h->priv_data;
  741. int post, err;
  742. char headers[HTTP_HEADERS_SIZE] = "";
  743. char *authstr = NULL, *proxyauthstr = NULL;
  744. int64_t off = s->off;
  745. int len = 0;
  746. const char *method;
  747. int send_expect_100 = 0;
  748. /* send http header */
  749. post = h->flags & AVIO_FLAG_WRITE;
  750. if (s->post_data) {
  751. /* force POST method and disable chunked encoding when
  752. * custom HTTP post data is set */
  753. post = 1;
  754. s->chunked_post = 0;
  755. }
  756. if (s->method)
  757. method = s->method;
  758. else
  759. method = post ? "POST" : "GET";
  760. authstr = ff_http_auth_create_response(&s->auth_state, auth,
  761. local_path, method);
  762. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  763. local_path, method);
  764. if (post && !s->post_data) {
  765. send_expect_100 = s->send_expect_100;
  766. /* The user has supplied authentication but we don't know the auth type,
  767. * send Expect: 100-continue to get the 401 response including the
  768. * WWW-Authenticate header, or an 100 continue if no auth actually
  769. * is needed. */
  770. if (auth && *auth &&
  771. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  772. s->http_code != 401)
  773. send_expect_100 = 1;
  774. }
  775. /* set default headers if needed */
  776. if (!has_header(s->headers, "\r\nUser-Agent: "))
  777. len += av_strlcatf(headers + len, sizeof(headers) - len,
  778. "User-Agent: %s\r\n", s->user_agent);
  779. if (!has_header(s->headers, "\r\nAccept: "))
  780. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  781. sizeof(headers) - len);
  782. // Note: we send this on purpose even when s->off is 0 when we're probing,
  783. // since it allows us to detect more reliably if a (non-conforming)
  784. // server supports seeking by analysing the reply headers.
  785. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
  786. len += av_strlcatf(headers + len, sizeof(headers) - len,
  787. "Range: bytes=%"PRId64"-", s->off);
  788. if (s->end_off)
  789. len += av_strlcatf(headers + len, sizeof(headers) - len,
  790. "%"PRId64, s->end_off - 1);
  791. len += av_strlcpy(headers + len, "\r\n",
  792. sizeof(headers) - len);
  793. }
  794. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  795. len += av_strlcatf(headers + len, sizeof(headers) - len,
  796. "Expect: 100-continue\r\n");
  797. if (!has_header(s->headers, "\r\nConnection: ")) {
  798. if (s->multiple_requests)
  799. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  800. sizeof(headers) - len);
  801. else
  802. len += av_strlcpy(headers + len, "Connection: close\r\n",
  803. sizeof(headers) - len);
  804. }
  805. if (!has_header(s->headers, "\r\nHost: "))
  806. len += av_strlcatf(headers + len, sizeof(headers) - len,
  807. "Host: %s\r\n", hoststr);
  808. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  809. len += av_strlcatf(headers + len, sizeof(headers) - len,
  810. "Content-Length: %d\r\n", s->post_datalen);
  811. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  812. len += av_strlcatf(headers + len, sizeof(headers) - len,
  813. "Content-Type: %s\r\n", s->content_type);
  814. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  815. char *cookies = NULL;
  816. if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
  817. len += av_strlcatf(headers + len, sizeof(headers) - len,
  818. "Cookie: %s\r\n", cookies);
  819. av_free(cookies);
  820. }
  821. }
  822. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
  823. len += av_strlcatf(headers + len, sizeof(headers) - len,
  824. "Icy-MetaData: %d\r\n", 1);
  825. /* now add in custom headers */
  826. if (s->headers)
  827. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  828. snprintf(s->buffer, sizeof(s->buffer),
  829. "%s %s HTTP/1.1\r\n"
  830. "%s"
  831. "%s"
  832. "%s"
  833. "%s%s"
  834. "\r\n",
  835. method,
  836. path,
  837. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  838. headers,
  839. authstr ? authstr : "",
  840. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  841. av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
  842. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  843. goto done;
  844. if (s->post_data)
  845. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  846. goto done;
  847. /* init input buffer */
  848. s->buf_ptr = s->buffer;
  849. s->buf_end = s->buffer;
  850. s->line_count = 0;
  851. s->off = 0;
  852. s->icy_data_read = 0;
  853. s->filesize = -1;
  854. s->willclose = 0;
  855. s->end_chunked_post = 0;
  856. s->end_header = 0;
  857. if (post && !s->post_data && !send_expect_100) {
  858. /* Pretend that it did work. We didn't read any header yet, since
  859. * we've still to send the POST data, but the code calling this
  860. * function will check http_code after we return. */
  861. s->http_code = 200;
  862. err = 0;
  863. goto done;
  864. }
  865. /* wait for header */
  866. err = http_read_header(h, new_location);
  867. if (err < 0)
  868. goto done;
  869. if (*new_location)
  870. s->off = off;
  871. err = (off == s->off) ? 0 : -1;
  872. done:
  873. av_freep(&authstr);
  874. av_freep(&proxyauthstr);
  875. return err;
  876. }
  877. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  878. {
  879. HTTPContext *s = h->priv_data;
  880. int len;
  881. /* read bytes from input buffer first */
  882. len = s->buf_end - s->buf_ptr;
  883. if (len > 0) {
  884. if (len > size)
  885. len = size;
  886. memcpy(buf, s->buf_ptr, len);
  887. s->buf_ptr += len;
  888. } else {
  889. if ((!s->willclose || s->chunksize < 0) &&
  890. s->filesize >= 0 && s->off >= s->filesize)
  891. return AVERROR_EOF;
  892. len = ffurl_read(s->hd, buf, size);
  893. if (!len && (!s->willclose || s->chunksize < 0) &&
  894. s->filesize >= 0 && s->off < s->filesize) {
  895. av_log(h, AV_LOG_ERROR,
  896. "Stream ends prematurely at %"PRId64", should be %"PRId64"\n",
  897. s->off, s->filesize
  898. );
  899. return AVERROR(EIO);
  900. }
  901. }
  902. if (len > 0) {
  903. s->off += len;
  904. if (s->chunksize > 0)
  905. s->chunksize -= len;
  906. }
  907. return len;
  908. }
  909. #if CONFIG_ZLIB
  910. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  911. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  912. {
  913. HTTPContext *s = h->priv_data;
  914. int ret;
  915. if (!s->inflate_buffer) {
  916. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  917. if (!s->inflate_buffer)
  918. return AVERROR(ENOMEM);
  919. }
  920. if (s->inflate_stream.avail_in == 0) {
  921. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  922. if (read <= 0)
  923. return read;
  924. s->inflate_stream.next_in = s->inflate_buffer;
  925. s->inflate_stream.avail_in = read;
  926. }
  927. s->inflate_stream.avail_out = size;
  928. s->inflate_stream.next_out = buf;
  929. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  930. if (ret != Z_OK && ret != Z_STREAM_END)
  931. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
  932. ret, s->inflate_stream.msg);
  933. return size - s->inflate_stream.avail_out;
  934. }
  935. #endif /* CONFIG_ZLIB */
  936. static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
  937. static int http_read_stream(URLContext *h, uint8_t *buf, int size)
  938. {
  939. HTTPContext *s = h->priv_data;
  940. int err, new_location, read_ret, seek_ret;
  941. if (!s->hd)
  942. return AVERROR_EOF;
  943. if (s->end_chunked_post && !s->end_header) {
  944. err = http_read_header(h, &new_location);
  945. if (err < 0)
  946. return err;
  947. }
  948. if (s->chunksize >= 0) {
  949. if (!s->chunksize) {
  950. char line[32];
  951. do {
  952. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  953. return err;
  954. } while (!*line); /* skip CR LF from last chunk */
  955. s->chunksize = strtoll(line, NULL, 16);
  956. av_log(NULL, AV_LOG_TRACE, "Chunked encoding data size: %"PRId64"'\n",
  957. s->chunksize);
  958. if (!s->chunksize)
  959. return 0;
  960. }
  961. size = FFMIN(size, s->chunksize);
  962. }
  963. #if CONFIG_ZLIB
  964. if (s->compressed)
  965. return http_buf_read_compressed(h, buf, size);
  966. #endif /* CONFIG_ZLIB */
  967. read_ret = http_buf_read(h, buf, size);
  968. if (read_ret < 0 && s->reconnect && !h->is_streamed && s->filesize > 0 && s->off < s->filesize) {
  969. av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64".\n", s->off);
  970. seek_ret = http_seek_internal(h, s->off, SEEK_SET, 1);
  971. if (seek_ret != s->off) {
  972. av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", s->off);
  973. return read_ret;
  974. }
  975. read_ret = http_buf_read(h, buf, size);
  976. }
  977. return read_ret;
  978. }
  979. // Like http_read_stream(), but no short reads.
  980. // Assumes partial reads are an error.
  981. static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
  982. {
  983. int pos = 0;
  984. while (pos < size) {
  985. int len = http_read_stream(h, buf + pos, size - pos);
  986. if (len < 0)
  987. return len;
  988. pos += len;
  989. }
  990. return pos;
  991. }
  992. static void update_metadata(HTTPContext *s, char *data)
  993. {
  994. char *key;
  995. char *val;
  996. char *end;
  997. char *next = data;
  998. while (*next) {
  999. key = next;
  1000. val = strstr(key, "='");
  1001. if (!val)
  1002. break;
  1003. end = strstr(val, "';");
  1004. if (!end)
  1005. break;
  1006. *val = '\0';
  1007. *end = '\0';
  1008. val += 2;
  1009. av_dict_set(&s->metadata, key, val, 0);
  1010. next = end + 2;
  1011. }
  1012. }
  1013. static int store_icy(URLContext *h, int size)
  1014. {
  1015. HTTPContext *s = h->priv_data;
  1016. /* until next metadata packet */
  1017. int remaining = s->icy_metaint - s->icy_data_read;
  1018. if (remaining < 0)
  1019. return AVERROR_INVALIDDATA;
  1020. if (!remaining) {
  1021. /* The metadata packet is variable sized. It has a 1 byte header
  1022. * which sets the length of the packet (divided by 16). If it's 0,
  1023. * the metadata doesn't change. After the packet, icy_metaint bytes
  1024. * of normal data follows. */
  1025. uint8_t ch;
  1026. int len = http_read_stream_all(h, &ch, 1);
  1027. if (len < 0)
  1028. return len;
  1029. if (ch > 0) {
  1030. char data[255 * 16 + 1];
  1031. int ret;
  1032. len = ch * 16;
  1033. ret = http_read_stream_all(h, data, len);
  1034. if (ret < 0)
  1035. return ret;
  1036. data[len + 1] = 0;
  1037. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  1038. return ret;
  1039. update_metadata(s, data);
  1040. }
  1041. s->icy_data_read = 0;
  1042. remaining = s->icy_metaint;
  1043. }
  1044. return FFMIN(size, remaining);
  1045. }
  1046. static int http_read(URLContext *h, uint8_t *buf, int size)
  1047. {
  1048. HTTPContext *s = h->priv_data;
  1049. if (s->icy_metaint > 0) {
  1050. size = store_icy(h, size);
  1051. if (size < 0)
  1052. return size;
  1053. }
  1054. size = http_read_stream(h, buf, size);
  1055. if (size > 0)
  1056. s->icy_data_read += size;
  1057. return size;
  1058. }
  1059. /* used only when posting data */
  1060. static int http_write(URLContext *h, const uint8_t *buf, int size)
  1061. {
  1062. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  1063. int ret;
  1064. char crlf[] = "\r\n";
  1065. HTTPContext *s = h->priv_data;
  1066. if (!s->chunked_post) {
  1067. /* non-chunked data is sent without any special encoding */
  1068. return ffurl_write(s->hd, buf, size);
  1069. }
  1070. /* silently ignore zero-size data since chunk encoding that would
  1071. * signal EOF */
  1072. if (size > 0) {
  1073. /* upload data using chunked encoding */
  1074. snprintf(temp, sizeof(temp), "%x\r\n", size);
  1075. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  1076. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  1077. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  1078. return ret;
  1079. }
  1080. return size;
  1081. }
  1082. static int http_shutdown(URLContext *h, int flags)
  1083. {
  1084. int ret = 0;
  1085. char footer[] = "0\r\n\r\n";
  1086. HTTPContext *s = h->priv_data;
  1087. /* signal end of chunked encoding if used */
  1088. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  1089. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  1090. ret = ret > 0 ? 0 : ret;
  1091. s->end_chunked_post = 1;
  1092. }
  1093. return ret;
  1094. }
  1095. static int http_close(URLContext *h)
  1096. {
  1097. int ret = 0;
  1098. HTTPContext *s = h->priv_data;
  1099. #if CONFIG_ZLIB
  1100. inflateEnd(&s->inflate_stream);
  1101. av_freep(&s->inflate_buffer);
  1102. #endif /* CONFIG_ZLIB */
  1103. if (!s->end_chunked_post)
  1104. /* Close the write direction by sending the end of chunked encoding. */
  1105. ret = http_shutdown(h, h->flags);
  1106. if (s->hd)
  1107. ffurl_closep(&s->hd);
  1108. av_dict_free(&s->chained_options);
  1109. return ret;
  1110. }
  1111. static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
  1112. {
  1113. HTTPContext *s = h->priv_data;
  1114. URLContext *old_hd = s->hd;
  1115. int64_t old_off = s->off;
  1116. uint8_t old_buf[BUFFER_SIZE];
  1117. int old_buf_size, ret;
  1118. AVDictionary *options = NULL;
  1119. if (whence == AVSEEK_SIZE)
  1120. return s->filesize;
  1121. else if (!force_reconnect &&
  1122. ((whence == SEEK_CUR && off == 0) ||
  1123. (whence == SEEK_SET && off == s->off)))
  1124. return s->off;
  1125. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  1126. return AVERROR(ENOSYS);
  1127. if (whence == SEEK_CUR)
  1128. off += s->off;
  1129. else if (whence == SEEK_END)
  1130. off += s->filesize;
  1131. else if (whence != SEEK_SET)
  1132. return AVERROR(EINVAL);
  1133. if (off < 0)
  1134. return AVERROR(EINVAL);
  1135. s->off = off;
  1136. /* we save the old context in case the seek fails */
  1137. old_buf_size = s->buf_end - s->buf_ptr;
  1138. memcpy(old_buf, s->buf_ptr, old_buf_size);
  1139. s->hd = NULL;
  1140. /* if it fails, continue on old connection */
  1141. if ((ret = http_open_cnx(h, &options)) < 0) {
  1142. av_dict_free(&options);
  1143. memcpy(s->buffer, old_buf, old_buf_size);
  1144. s->buf_ptr = s->buffer;
  1145. s->buf_end = s->buffer + old_buf_size;
  1146. s->hd = old_hd;
  1147. s->off = old_off;
  1148. return ret;
  1149. }
  1150. av_dict_free(&options);
  1151. ffurl_close(old_hd);
  1152. return off;
  1153. }
  1154. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  1155. {
  1156. return http_seek_internal(h, off, whence, 0);
  1157. }
  1158. static int http_get_file_handle(URLContext *h)
  1159. {
  1160. HTTPContext *s = h->priv_data;
  1161. return ffurl_get_file_handle(s->hd);
  1162. }
  1163. #define HTTP_CLASS(flavor) \
  1164. static const AVClass flavor ## _context_class = { \
  1165. .class_name = # flavor, \
  1166. .item_name = av_default_item_name, \
  1167. .option = options, \
  1168. .version = LIBAVUTIL_VERSION_INT, \
  1169. }
  1170. #if CONFIG_HTTP_PROTOCOL
  1171. HTTP_CLASS(http);
  1172. URLProtocol ff_http_protocol = {
  1173. .name = "http",
  1174. .url_open2 = http_open,
  1175. .url_read = http_read,
  1176. .url_write = http_write,
  1177. .url_seek = http_seek,
  1178. .url_close = http_close,
  1179. .url_get_file_handle = http_get_file_handle,
  1180. .url_shutdown = http_shutdown,
  1181. .priv_data_size = sizeof(HTTPContext),
  1182. .priv_data_class = &http_context_class,
  1183. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1184. };
  1185. #endif /* CONFIG_HTTP_PROTOCOL */
  1186. #if CONFIG_HTTPS_PROTOCOL
  1187. HTTP_CLASS(https);
  1188. URLProtocol ff_https_protocol = {
  1189. .name = "https",
  1190. .url_open2 = http_open,
  1191. .url_read = http_read,
  1192. .url_write = http_write,
  1193. .url_seek = http_seek,
  1194. .url_close = http_close,
  1195. .url_get_file_handle = http_get_file_handle,
  1196. .url_shutdown = http_shutdown,
  1197. .priv_data_size = sizeof(HTTPContext),
  1198. .priv_data_class = &https_context_class,
  1199. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1200. };
  1201. #endif /* CONFIG_HTTPS_PROTOCOL */
  1202. #if CONFIG_HTTPPROXY_PROTOCOL
  1203. static int http_proxy_close(URLContext *h)
  1204. {
  1205. HTTPContext *s = h->priv_data;
  1206. if (s->hd)
  1207. ffurl_closep(&s->hd);
  1208. return 0;
  1209. }
  1210. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  1211. {
  1212. HTTPContext *s = h->priv_data;
  1213. char hostname[1024], hoststr[1024];
  1214. char auth[1024], pathbuf[1024], *path;
  1215. char lower_url[100];
  1216. int port, ret = 0, attempts = 0;
  1217. HTTPAuthType cur_auth_type;
  1218. char *authstr;
  1219. int new_loc;
  1220. if( s->seekable == 1 )
  1221. h->is_streamed = 0;
  1222. else
  1223. h->is_streamed = 1;
  1224. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  1225. pathbuf, sizeof(pathbuf), uri);
  1226. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  1227. path = pathbuf;
  1228. if (*path == '/')
  1229. path++;
  1230. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  1231. NULL);
  1232. redo:
  1233. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  1234. &h->interrupt_callback, NULL);
  1235. if (ret < 0)
  1236. return ret;
  1237. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  1238. path, "CONNECT");
  1239. snprintf(s->buffer, sizeof(s->buffer),
  1240. "CONNECT %s HTTP/1.1\r\n"
  1241. "Host: %s\r\n"
  1242. "Connection: close\r\n"
  1243. "%s%s"
  1244. "\r\n",
  1245. path,
  1246. hoststr,
  1247. authstr ? "Proxy-" : "", authstr ? authstr : "");
  1248. av_freep(&authstr);
  1249. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  1250. goto fail;
  1251. s->buf_ptr = s->buffer;
  1252. s->buf_end = s->buffer;
  1253. s->line_count = 0;
  1254. s->filesize = -1;
  1255. cur_auth_type = s->proxy_auth_state.auth_type;
  1256. /* Note: This uses buffering, potentially reading more than the
  1257. * HTTP header. If tunneling a protocol where the server starts
  1258. * the conversation, we might buffer part of that here, too.
  1259. * Reading that requires using the proper ffurl_read() function
  1260. * on this URLContext, not using the fd directly (as the tls
  1261. * protocol does). This shouldn't be an issue for tls though,
  1262. * since the client starts the conversation there, so there
  1263. * is no extra data that we might buffer up here.
  1264. */
  1265. ret = http_read_header(h, &new_loc);
  1266. if (ret < 0)
  1267. goto fail;
  1268. attempts++;
  1269. if (s->http_code == 407 &&
  1270. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  1271. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  1272. ffurl_closep(&s->hd);
  1273. goto redo;
  1274. }
  1275. if (s->http_code < 400)
  1276. return 0;
  1277. ret = ff_http_averror(s->http_code, AVERROR(EIO));
  1278. fail:
  1279. http_proxy_close(h);
  1280. return ret;
  1281. }
  1282. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  1283. {
  1284. HTTPContext *s = h->priv_data;
  1285. return ffurl_write(s->hd, buf, size);
  1286. }
  1287. URLProtocol ff_httpproxy_protocol = {
  1288. .name = "httpproxy",
  1289. .url_open = http_proxy_open,
  1290. .url_read = http_buf_read,
  1291. .url_write = http_proxy_write,
  1292. .url_close = http_proxy_close,
  1293. .url_get_file_handle = http_get_file_handle,
  1294. .priv_data_size = sizeof(HTTPContext),
  1295. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1296. };
  1297. #endif /* CONFIG_HTTPPROXY_PROTOCOL */