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.

767 lines
23KB

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