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.

746 lines
23KB

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