http.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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 "libavutil/avstring.h"
  22. #include "avformat.h"
  23. #include "internal.h"
  24. #include "network.h"
  25. #include "http.h"
  26. #include "os_support.h"
  27. #include "httpauth.h"
  28. #include "url.h"
  29. #include "libavutil/opt.h"
  30. /* XXX: POST protocol is not completely implemented because ffmpeg uses
  31. only a subset of it. */
  32. /* used for protocol handling */
  33. #define BUFFER_SIZE 4096
  34. #define MAX_REDIRECTS 8
  35. typedef struct {
  36. const AVClass *class;
  37. URLContext *hd;
  38. unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
  39. int line_count;
  40. int http_code;
  41. int64_t chunksize; /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
  42. char *user_agent;
  43. int64_t off, filesize;
  44. char location[MAX_URL_SIZE];
  45. HTTPAuthState auth_state;
  46. HTTPAuthState proxy_auth_state;
  47. char *headers;
  48. int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
  49. int chunked_post;
  50. int end_chunked_post; /**< A flag which indicates if the end of chunked encoding has been sent. */
  51. int end_header; /**< A flag which indicates we have finished to read POST reply. */
  52. int multiple_requests; /**< A flag which indicates if we use persistent connections. */
  53. uint8_t *post_data;
  54. int post_datalen;
  55. int is_akamai;
  56. } HTTPContext;
  57. #define OFFSET(x) offsetof(HTTPContext, x)
  58. #define D AV_OPT_FLAG_DECODING_PARAM
  59. #define E AV_OPT_FLAG_ENCODING_PARAM
  60. #define DEC AV_OPT_FLAG_DECODING_PARAM
  61. static const AVOption options[] = {
  62. {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
  63. {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  64. {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
  65. {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
  66. {"post_data", "custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
  67. {NULL}
  68. };
  69. #define HTTP_CLASS(flavor)\
  70. static const AVClass flavor ## _context_class = {\
  71. .class_name = #flavor,\
  72. .item_name = av_default_item_name,\
  73. .option = options,\
  74. .version = LIBAVUTIL_VERSION_INT,\
  75. }
  76. HTTP_CLASS(http);
  77. HTTP_CLASS(https);
  78. static int http_connect(URLContext *h, const char *path, const char *local_path,
  79. const char *hoststr, const char *auth,
  80. const char *proxyauth, int *new_location);
  81. void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
  82. {
  83. memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
  84. &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
  85. memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
  86. &((HTTPContext*)src->priv_data)->proxy_auth_state,
  87. sizeof(HTTPAuthState));
  88. }
  89. /* return non zero if error */
  90. static int http_open_cnx(URLContext *h)
  91. {
  92. const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
  93. char hostname[1024], hoststr[1024], proto[10];
  94. char auth[1024], proxyauth[1024] = "";
  95. char path1[1024];
  96. char buf[1024], urlbuf[1024];
  97. int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
  98. HTTPAuthType cur_auth_type, cur_proxy_auth_type;
  99. HTTPContext *s = h->priv_data;
  100. proxy_path = getenv("http_proxy");
  101. use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
  102. av_strstart(proxy_path, "http://", NULL);
  103. /* fill the dest addr */
  104. redo:
  105. /* needed in any case to build the host string */
  106. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  107. hostname, sizeof(hostname), &port,
  108. path1, sizeof(path1), s->location);
  109. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  110. if (!strcmp(proto, "https")) {
  111. lower_proto = "tls";
  112. use_proxy = 0;
  113. if (port < 0)
  114. port = 443;
  115. }
  116. if (port < 0)
  117. port = 80;
  118. if (path1[0] == '\0')
  119. path = "/";
  120. else
  121. path = path1;
  122. local_path = path;
  123. if (use_proxy) {
  124. /* Reassemble the request URL without auth string - we don't
  125. * want to leak the auth to the proxy. */
  126. ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
  127. path1);
  128. path = urlbuf;
  129. av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
  130. hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
  131. }
  132. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  133. if (!s->hd) {
  134. err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
  135. &h->interrupt_callback, NULL);
  136. if (err < 0)
  137. goto fail;
  138. }
  139. cur_auth_type = s->auth_state.auth_type;
  140. cur_proxy_auth_type = s->auth_state.auth_type;
  141. if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
  142. goto fail;
  143. attempts++;
  144. if (s->http_code == 401) {
  145. if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
  146. s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  147. ffurl_closep(&s->hd);
  148. goto redo;
  149. } else
  150. goto fail;
  151. }
  152. if (s->http_code == 407) {
  153. if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  154. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  155. ffurl_closep(&s->hd);
  156. goto redo;
  157. } else
  158. goto fail;
  159. }
  160. if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
  161. && location_changed == 1) {
  162. /* url moved, get next */
  163. ffurl_closep(&s->hd);
  164. if (redirects++ >= MAX_REDIRECTS)
  165. return AVERROR(EIO);
  166. /* Restart the authentication process with the new target, which
  167. * might use a different auth mechanism. */
  168. memset(&s->auth_state, 0, sizeof(s->auth_state));
  169. attempts = 0;
  170. location_changed = 0;
  171. goto redo;
  172. }
  173. return 0;
  174. fail:
  175. if (s->hd)
  176. ffurl_closep(&s->hd);
  177. return AVERROR(EIO);
  178. }
  179. int ff_http_do_new_request(URLContext *h, const char *uri)
  180. {
  181. HTTPContext *s = h->priv_data;
  182. s->off = 0;
  183. av_strlcpy(s->location, uri, sizeof(s->location));
  184. return http_open_cnx(h);
  185. }
  186. static int http_open(URLContext *h, const char *uri, int flags)
  187. {
  188. HTTPContext *s = h->priv_data;
  189. h->is_streamed = 1;
  190. s->filesize = -1;
  191. av_strlcpy(s->location, uri, sizeof(s->location));
  192. if (s->headers) {
  193. int len = strlen(s->headers);
  194. if (len < 2 || strcmp("\r\n", s->headers + len - 2))
  195. av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
  196. }
  197. return http_open_cnx(h);
  198. }
  199. static int http_getc(HTTPContext *s)
  200. {
  201. int len;
  202. if (s->buf_ptr >= s->buf_end) {
  203. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  204. if (len < 0) {
  205. return len;
  206. } else if (len == 0) {
  207. return -1;
  208. } else {
  209. s->buf_ptr = s->buffer;
  210. s->buf_end = s->buffer + len;
  211. }
  212. }
  213. return *s->buf_ptr++;
  214. }
  215. static int http_get_line(HTTPContext *s, char *line, int line_size)
  216. {
  217. int ch;
  218. char *q;
  219. q = line;
  220. for(;;) {
  221. ch = http_getc(s);
  222. if (ch < 0)
  223. return ch;
  224. if (ch == '\n') {
  225. /* process line */
  226. if (q > line && q[-1] == '\r')
  227. q--;
  228. *q = '\0';
  229. return 0;
  230. } else {
  231. if ((q - line) < line_size - 1)
  232. *q++ = ch;
  233. }
  234. }
  235. }
  236. static int process_line(URLContext *h, char *line, int line_count,
  237. int *new_location)
  238. {
  239. HTTPContext *s = h->priv_data;
  240. char *tag, *p, *end;
  241. /* end of header */
  242. if (line[0] == '\0') {
  243. s->end_header = 1;
  244. return 0;
  245. }
  246. p = line;
  247. if (line_count == 0) {
  248. while (!isspace(*p) && *p != '\0')
  249. p++;
  250. while (isspace(*p))
  251. p++;
  252. s->http_code = strtol(p, &end, 10);
  253. av_dlog(NULL, "http_code=%d\n", s->http_code);
  254. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  255. * don't abort until all headers have been parsed. */
  256. if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
  257. || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  258. (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  259. end += strspn(end, SPACE_CHARS);
  260. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
  261. s->http_code, end);
  262. return -1;
  263. }
  264. } else {
  265. while (*p != '\0' && *p != ':')
  266. p++;
  267. if (*p != ':')
  268. return 1;
  269. *p = '\0';
  270. tag = line;
  271. p++;
  272. while (isspace(*p))
  273. p++;
  274. if (!av_strcasecmp(tag, "Location")) {
  275. strcpy(s->location, p);
  276. *new_location = 1;
  277. } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
  278. s->filesize = strtoll(p, NULL, 10);
  279. } else if (!av_strcasecmp (tag, "Content-Range")) {
  280. /* "bytes $from-$to/$document_size" */
  281. const char *slash;
  282. if (!strncmp (p, "bytes ", 6)) {
  283. p += 6;
  284. s->off = strtoll(p, NULL, 10);
  285. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  286. s->filesize = strtoll(slash+1, NULL, 10);
  287. }
  288. if (!s->is_akamai || s->filesize != 2147483647)
  289. h->is_streamed = 0; /* we _can_ in fact seek */
  290. } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) {
  291. h->is_streamed = 0;
  292. } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
  293. s->filesize = -1;
  294. s->chunksize = 0;
  295. } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
  296. ff_http_auth_handle_header(&s->auth_state, tag, p);
  297. } else if (!av_strcasecmp (tag, "Authentication-Info")) {
  298. ff_http_auth_handle_header(&s->auth_state, tag, p);
  299. } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
  300. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  301. } else if (!av_strcasecmp (tag, "Connection")) {
  302. if (!strcmp(p, "close"))
  303. s->willclose = 1;
  304. } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
  305. s->is_akamai = 1;
  306. }
  307. }
  308. return 1;
  309. }
  310. static inline int has_header(const char *str, const char *header)
  311. {
  312. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  313. if (!str)
  314. return 0;
  315. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  316. }
  317. static int http_read_header(URLContext *h, int *new_location)
  318. {
  319. HTTPContext *s = h->priv_data;
  320. char line[1024];
  321. int err = 0;
  322. s->chunksize = -1;
  323. for (;;) {
  324. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  325. return err;
  326. av_dlog(NULL, "header='%s'\n", line);
  327. err = process_line(h, line, s->line_count, new_location);
  328. if (err < 0)
  329. return err;
  330. if (err == 0)
  331. break;
  332. s->line_count++;
  333. }
  334. return err;
  335. }
  336. static int http_connect(URLContext *h, const char *path, const char *local_path,
  337. const char *hoststr, const char *auth,
  338. const char *proxyauth, int *new_location)
  339. {
  340. HTTPContext *s = h->priv_data;
  341. int post, err;
  342. char headers[4096] = "";
  343. char *authstr = NULL, *proxyauthstr = NULL;
  344. int64_t off = s->off;
  345. int len = 0;
  346. const char *method;
  347. /* send http header */
  348. post = h->flags & AVIO_FLAG_WRITE;
  349. if (s->post_data) {
  350. /* force POST method and disable chunked encoding when
  351. * custom HTTP post data is set */
  352. post = 1;
  353. s->chunked_post = 0;
  354. }
  355. method = post ? "POST" : "GET";
  356. authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
  357. method);
  358. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  359. local_path, method);
  360. /* set default headers if needed */
  361. if (!has_header(s->headers, "\r\nUser-Agent: "))
  362. len += av_strlcatf(headers + len, sizeof(headers) - len,
  363. "User-Agent: %s\r\n",
  364. s->user_agent ? s->user_agent : LIBAVFORMAT_IDENT);
  365. if (!has_header(s->headers, "\r\nAccept: "))
  366. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  367. sizeof(headers) - len);
  368. // Note: we send this on purpose even when s->off is 0,
  369. // since it allows us to detect more reliably if a (non-conforming)
  370. // server supports seeking by analysing the reply headers.
  371. if (!has_header(s->headers, "\r\nRange: ") && !post)
  372. len += av_strlcatf(headers + len, sizeof(headers) - len,
  373. "Range: bytes=%"PRId64"-\r\n", s->off);
  374. if (!has_header(s->headers, "\r\nConnection: ")) {
  375. if (s->multiple_requests) {
  376. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  377. sizeof(headers) - len);
  378. } else {
  379. len += av_strlcpy(headers + len, "Connection: close\r\n",
  380. sizeof(headers) - len);
  381. }
  382. }
  383. if (!has_header(s->headers, "\r\nHost: "))
  384. len += av_strlcatf(headers + len, sizeof(headers) - len,
  385. "Host: %s\r\n", hoststr);
  386. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  387. len += av_strlcatf(headers + len, sizeof(headers) - len,
  388. "Content-Length: %d\r\n", s->post_datalen);
  389. /* now add in custom headers */
  390. if (s->headers)
  391. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  392. snprintf(s->buffer, sizeof(s->buffer),
  393. "%s %s HTTP/1.1\r\n"
  394. "%s"
  395. "%s"
  396. "%s"
  397. "%s%s"
  398. "\r\n",
  399. method,
  400. path,
  401. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  402. headers,
  403. authstr ? authstr : "",
  404. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  405. av_freep(&authstr);
  406. av_freep(&proxyauthstr);
  407. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  408. return err;
  409. if (s->post_data)
  410. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  411. return err;
  412. /* init input buffer */
  413. s->buf_ptr = s->buffer;
  414. s->buf_end = s->buffer;
  415. s->line_count = 0;
  416. s->off = 0;
  417. s->filesize = -1;
  418. s->willclose = 0;
  419. s->end_chunked_post = 0;
  420. s->end_header = 0;
  421. if (post && !s->post_data) {
  422. /* Pretend that it did work. We didn't read any header yet, since
  423. * we've still to send the POST data, but the code calling this
  424. * function will check http_code after we return. */
  425. s->http_code = 200;
  426. return 0;
  427. }
  428. /* wait for header */
  429. err = http_read_header(h, new_location);
  430. if (err < 0)
  431. return err;
  432. return (off == s->off) ? 0 : -1;
  433. }
  434. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  435. {
  436. HTTPContext *s = h->priv_data;
  437. int len;
  438. /* read bytes from input buffer first */
  439. len = s->buf_end - s->buf_ptr;
  440. if (len > 0) {
  441. if (len > size)
  442. len = size;
  443. memcpy(buf, s->buf_ptr, len);
  444. s->buf_ptr += len;
  445. } else {
  446. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  447. return AVERROR_EOF;
  448. len = ffurl_read(s->hd, buf, size);
  449. }
  450. if (len > 0) {
  451. s->off += len;
  452. if (s->chunksize > 0)
  453. s->chunksize -= len;
  454. }
  455. return len;
  456. }
  457. static int http_read(URLContext *h, uint8_t *buf, int size)
  458. {
  459. HTTPContext *s = h->priv_data;
  460. int err, new_location;
  461. if (!s->hd)
  462. return AVERROR_EOF;
  463. if (s->end_chunked_post && !s->end_header) {
  464. err = http_read_header(h, &new_location);
  465. if (err < 0)
  466. return err;
  467. }
  468. if (s->chunksize >= 0) {
  469. if (!s->chunksize) {
  470. char line[32];
  471. for(;;) {
  472. do {
  473. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  474. return err;
  475. } while (!*line); /* skip CR LF from last chunk */
  476. s->chunksize = strtoll(line, NULL, 16);
  477. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  478. if (!s->chunksize)
  479. return 0;
  480. break;
  481. }
  482. }
  483. size = FFMIN(size, s->chunksize);
  484. }
  485. return http_buf_read(h, buf, size);
  486. }
  487. /* used only when posting data */
  488. static int http_write(URLContext *h, const uint8_t *buf, int size)
  489. {
  490. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  491. int ret;
  492. char crlf[] = "\r\n";
  493. HTTPContext *s = h->priv_data;
  494. if (!s->chunked_post) {
  495. /* non-chunked data is sent without any special encoding */
  496. return ffurl_write(s->hd, buf, size);
  497. }
  498. /* silently ignore zero-size data since chunk encoding that would
  499. * signal EOF */
  500. if (size > 0) {
  501. /* upload data using chunked encoding */
  502. snprintf(temp, sizeof(temp), "%x\r\n", size);
  503. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  504. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  505. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  506. return ret;
  507. }
  508. return size;
  509. }
  510. static int http_shutdown(URLContext *h, int flags)
  511. {
  512. int ret = 0;
  513. char footer[] = "0\r\n\r\n";
  514. HTTPContext *s = h->priv_data;
  515. /* signal end of chunked encoding if used */
  516. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  517. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  518. ret = ret > 0 ? 0 : ret;
  519. s->end_chunked_post = 1;
  520. }
  521. return ret;
  522. }
  523. static int http_close(URLContext *h)
  524. {
  525. int ret = 0;
  526. HTTPContext *s = h->priv_data;
  527. if (!s->end_chunked_post) {
  528. /* Close the write direction by sending the end of chunked encoding. */
  529. ret = http_shutdown(h, h->flags);
  530. }
  531. if (s->hd)
  532. ffurl_closep(&s->hd);
  533. return ret;
  534. }
  535. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  536. {
  537. HTTPContext *s = h->priv_data;
  538. URLContext *old_hd = s->hd;
  539. int64_t old_off = s->off;
  540. uint8_t old_buf[BUFFER_SIZE];
  541. int old_buf_size;
  542. if (whence == AVSEEK_SIZE)
  543. return s->filesize;
  544. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  545. return -1;
  546. /* we save the old context in case the seek fails */
  547. old_buf_size = s->buf_end - s->buf_ptr;
  548. memcpy(old_buf, s->buf_ptr, old_buf_size);
  549. s->hd = NULL;
  550. if (whence == SEEK_CUR)
  551. off += s->off;
  552. else if (whence == SEEK_END)
  553. off += s->filesize;
  554. s->off = off;
  555. /* if it fails, continue on old connection */
  556. if (http_open_cnx(h) < 0) {
  557. memcpy(s->buffer, old_buf, old_buf_size);
  558. s->buf_ptr = s->buffer;
  559. s->buf_end = s->buffer + old_buf_size;
  560. s->hd = old_hd;
  561. s->off = old_off;
  562. return -1;
  563. }
  564. ffurl_close(old_hd);
  565. return off;
  566. }
  567. static int
  568. http_get_file_handle(URLContext *h)
  569. {
  570. HTTPContext *s = h->priv_data;
  571. return ffurl_get_file_handle(s->hd);
  572. }
  573. #if CONFIG_HTTP_PROTOCOL
  574. URLProtocol ff_http_protocol = {
  575. .name = "http",
  576. .url_open = http_open,
  577. .url_read = http_read,
  578. .url_write = http_write,
  579. .url_seek = http_seek,
  580. .url_close = http_close,
  581. .url_get_file_handle = http_get_file_handle,
  582. .url_shutdown = http_shutdown,
  583. .priv_data_size = sizeof(HTTPContext),
  584. .priv_data_class = &http_context_class,
  585. .flags = URL_PROTOCOL_FLAG_NETWORK,
  586. };
  587. #endif
  588. #if CONFIG_HTTPS_PROTOCOL
  589. URLProtocol ff_https_protocol = {
  590. .name = "https",
  591. .url_open = http_open,
  592. .url_read = http_read,
  593. .url_write = http_write,
  594. .url_seek = http_seek,
  595. .url_close = http_close,
  596. .url_get_file_handle = http_get_file_handle,
  597. .url_shutdown = http_shutdown,
  598. .priv_data_size = sizeof(HTTPContext),
  599. .priv_data_class = &https_context_class,
  600. .flags = URL_PROTOCOL_FLAG_NETWORK,
  601. };
  602. #endif
  603. #if CONFIG_HTTPPROXY_PROTOCOL
  604. static int http_proxy_close(URLContext *h)
  605. {
  606. HTTPContext *s = h->priv_data;
  607. if (s->hd)
  608. ffurl_closep(&s->hd);
  609. return 0;
  610. }
  611. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  612. {
  613. HTTPContext *s = h->priv_data;
  614. char hostname[1024], hoststr[1024];
  615. char auth[1024], pathbuf[1024], *path;
  616. char lower_url[100];
  617. int port, ret = 0, attempts = 0;
  618. HTTPAuthType cur_auth_type;
  619. char *authstr;
  620. int new_loc;
  621. h->is_streamed = 1;
  622. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  623. pathbuf, sizeof(pathbuf), uri);
  624. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  625. path = pathbuf;
  626. if (*path == '/')
  627. path++;
  628. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  629. NULL);
  630. redo:
  631. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  632. &h->interrupt_callback, NULL);
  633. if (ret < 0)
  634. return ret;
  635. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  636. path, "CONNECT");
  637. snprintf(s->buffer, sizeof(s->buffer),
  638. "CONNECT %s HTTP/1.1\r\n"
  639. "Host: %s\r\n"
  640. "Connection: close\r\n"
  641. "%s%s"
  642. "\r\n",
  643. path,
  644. hoststr,
  645. authstr ? "Proxy-" : "", authstr ? authstr : "");
  646. av_freep(&authstr);
  647. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  648. goto fail;
  649. s->buf_ptr = s->buffer;
  650. s->buf_end = s->buffer;
  651. s->line_count = 0;
  652. s->filesize = -1;
  653. cur_auth_type = s->proxy_auth_state.auth_type;
  654. /* Note: This uses buffering, potentially reading more than the
  655. * HTTP header. If tunneling a protocol where the server starts
  656. * the conversation, we might buffer part of that here, too.
  657. * Reading that requires using the proper ffurl_read() function
  658. * on this URLContext, not using the fd directly (as the tls
  659. * protocol does). This shouldn't be an issue for tls though,
  660. * since the client starts the conversation there, so there
  661. * is no extra data that we might buffer up here.
  662. */
  663. ret = http_read_header(h, &new_loc);
  664. if (ret < 0)
  665. goto fail;
  666. attempts++;
  667. if (s->http_code == 407 &&
  668. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  669. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  670. ffurl_closep(&s->hd);
  671. goto redo;
  672. }
  673. if (s->http_code < 400)
  674. return 0;
  675. ret = AVERROR(EIO);
  676. fail:
  677. http_proxy_close(h);
  678. return ret;
  679. }
  680. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  681. {
  682. HTTPContext *s = h->priv_data;
  683. return ffurl_write(s->hd, buf, size);
  684. }
  685. URLProtocol ff_httpproxy_protocol = {
  686. .name = "httpproxy",
  687. .url_open = http_proxy_open,
  688. .url_read = http_buf_read,
  689. .url_write = http_proxy_write,
  690. .url_close = http_proxy_close,
  691. .url_get_file_handle = http_get_file_handle,
  692. .priv_data_size = sizeof(HTTPContext),
  693. .flags = URL_PROTOCOL_FLAG_NETWORK,
  694. };
  695. #endif