http.c 22 KB

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