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.

1629 lines
53KB

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