http_proxy.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2016, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
  24. #include "urldata.h"
  25. #include <curl/curl.h>
  26. #include "http_proxy.h"
  27. #include "sendf.h"
  28. #include "http.h"
  29. #include "url.h"
  30. #include "select.h"
  31. #include "progress.h"
  32. #include "non-ascii.h"
  33. #include "connect.h"
  34. #include "curlx.h"
  35. /* The last 3 #include files should be in this order */
  36. #include "curl_printf.h"
  37. #include "curl_memory.h"
  38. #include "memdebug.h"
  39. CURLcode Curl_proxy_connect(struct connectdata *conn)
  40. {
  41. if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
  42. #ifndef CURL_DISABLE_PROXY
  43. /* for [protocol] tunneled through HTTP proxy */
  44. struct HTTP http_proxy;
  45. void *prot_save;
  46. const char *hostname;
  47. int remote_port;
  48. CURLcode result;
  49. /* BLOCKING */
  50. /* We want "seamless" operations through HTTP proxy tunnel */
  51. /* Curl_proxyCONNECT is based on a pointer to a struct HTTP at the
  52. * member conn->proto.http; we want [protocol] through HTTP and we have
  53. * to change the member temporarily for connecting to the HTTP
  54. * proxy. After Curl_proxyCONNECT we have to set back the member to the
  55. * original pointer
  56. *
  57. * This function might be called several times in the multi interface case
  58. * if the proxy's CONNTECT response is not instant.
  59. */
  60. prot_save = conn->data->req.protop;
  61. memset(&http_proxy, 0, sizeof(http_proxy));
  62. conn->data->req.protop = &http_proxy;
  63. connkeep(conn, "HTTP proxy CONNECT");
  64. if(conn->bits.conn_to_host)
  65. hostname = conn->conn_to_host.name;
  66. else
  67. hostname = conn->host.name;
  68. if(conn->bits.conn_to_port)
  69. remote_port = conn->conn_to_port;
  70. else
  71. remote_port = conn->remote_port;
  72. result = Curl_proxyCONNECT(conn, FIRSTSOCKET, hostname,
  73. remote_port, FALSE);
  74. conn->data->req.protop = prot_save;
  75. if(CURLE_OK != result)
  76. return result;
  77. Curl_safefree(conn->allocptr.proxyuserpwd);
  78. #else
  79. return CURLE_NOT_BUILT_IN;
  80. #endif
  81. }
  82. /* no HTTP tunnel proxy, just return */
  83. return CURLE_OK;
  84. }
  85. /*
  86. * Curl_proxyCONNECT() requires that we're connected to a HTTP proxy. This
  87. * function will issue the necessary commands to get a seamless tunnel through
  88. * this proxy. After that, the socket can be used just as a normal socket.
  89. *
  90. * 'blocking' set to TRUE means that this function will do the entire CONNECT
  91. * + response in a blocking fashion. Should be avoided!
  92. */
  93. CURLcode Curl_proxyCONNECT(struct connectdata *conn,
  94. int sockindex,
  95. const char *hostname,
  96. int remote_port,
  97. bool blocking)
  98. {
  99. int subversion=0;
  100. struct Curl_easy *data=conn->data;
  101. struct SingleRequest *k = &data->req;
  102. CURLcode result;
  103. curl_socket_t tunnelsocket = conn->sock[sockindex];
  104. curl_off_t cl=0;
  105. bool closeConnection = FALSE;
  106. bool chunked_encoding = FALSE;
  107. long check;
  108. #define SELECT_OK 0
  109. #define SELECT_ERROR 1
  110. #define SELECT_TIMEOUT 2
  111. int error = SELECT_OK;
  112. if(conn->tunnel_state[sockindex] == TUNNEL_COMPLETE)
  113. return CURLE_OK; /* CONNECT is already completed */
  114. conn->bits.proxy_connect_closed = FALSE;
  115. do {
  116. if(TUNNEL_INIT == conn->tunnel_state[sockindex]) {
  117. /* BEGIN CONNECT PHASE */
  118. char *host_port;
  119. Curl_send_buffer *req_buffer;
  120. infof(data, "Establish HTTP proxy tunnel to %s:%hu\n",
  121. hostname, remote_port);
  122. /* This only happens if we've looped here due to authentication
  123. reasons, and we don't really use the newly cloned URL here
  124. then. Just free() it. */
  125. free(data->req.newurl);
  126. data->req.newurl = NULL;
  127. /* initialize a dynamic send-buffer */
  128. req_buffer = Curl_add_buffer_init();
  129. if(!req_buffer)
  130. return CURLE_OUT_OF_MEMORY;
  131. host_port = aprintf("%s:%hu", hostname, remote_port);
  132. if(!host_port) {
  133. Curl_add_buffer_free(req_buffer);
  134. return CURLE_OUT_OF_MEMORY;
  135. }
  136. /* Setup the proxy-authorization header, if any */
  137. result = Curl_http_output_auth(conn, "CONNECT", host_port, TRUE);
  138. free(host_port);
  139. if(!result) {
  140. char *host=(char *)"";
  141. const char *proxyconn="";
  142. const char *useragent="";
  143. const char *http = (conn->proxytype == CURLPROXY_HTTP_1_0) ?
  144. "1.0" : "1.1";
  145. bool ipv6_ip = conn->bits.ipv6_ip;
  146. char *hostheader;
  147. /* the hostname may be different */
  148. if(hostname != conn->host.name)
  149. ipv6_ip = (strchr(hostname, ':') != NULL);
  150. hostheader= /* host:port with IPv6 support */
  151. aprintf("%s%s%s:%hu", ipv6_ip?"[":"", hostname, ipv6_ip?"]":"",
  152. remote_port);
  153. if(!hostheader) {
  154. Curl_add_buffer_free(req_buffer);
  155. return CURLE_OUT_OF_MEMORY;
  156. }
  157. if(!Curl_checkProxyheaders(conn, "Host:")) {
  158. host = aprintf("Host: %s\r\n", hostheader);
  159. if(!host) {
  160. free(hostheader);
  161. Curl_add_buffer_free(req_buffer);
  162. return CURLE_OUT_OF_MEMORY;
  163. }
  164. }
  165. if(!Curl_checkProxyheaders(conn, "Proxy-Connection:"))
  166. proxyconn = "Proxy-Connection: Keep-Alive\r\n";
  167. if(!Curl_checkProxyheaders(conn, "User-Agent:") &&
  168. data->set.str[STRING_USERAGENT])
  169. useragent = conn->allocptr.uagent;
  170. result =
  171. Curl_add_bufferf(req_buffer,
  172. "CONNECT %s HTTP/%s\r\n"
  173. "%s" /* Host: */
  174. "%s" /* Proxy-Authorization */
  175. "%s" /* User-Agent */
  176. "%s", /* Proxy-Connection */
  177. hostheader,
  178. http,
  179. host,
  180. conn->allocptr.proxyuserpwd?
  181. conn->allocptr.proxyuserpwd:"",
  182. useragent,
  183. proxyconn);
  184. if(host && *host)
  185. free(host);
  186. free(hostheader);
  187. if(!result)
  188. result = Curl_add_custom_headers(conn, TRUE, req_buffer);
  189. if(!result)
  190. /* CRLF terminate the request */
  191. result = Curl_add_bufferf(req_buffer, "\r\n");
  192. if(!result) {
  193. /* Send the connect request to the proxy */
  194. /* BLOCKING */
  195. result =
  196. Curl_add_buffer_send(req_buffer, conn,
  197. &data->info.request_size, 0, sockindex);
  198. }
  199. req_buffer = NULL;
  200. if(result)
  201. failf(data, "Failed sending CONNECT to proxy");
  202. }
  203. Curl_add_buffer_free(req_buffer);
  204. if(result)
  205. return result;
  206. conn->tunnel_state[sockindex] = TUNNEL_CONNECT;
  207. } /* END CONNECT PHASE */
  208. check = Curl_timeleft(data, NULL, TRUE);
  209. if(check <= 0) {
  210. failf(data, "Proxy CONNECT aborted due to timeout");
  211. return CURLE_RECV_ERROR;
  212. }
  213. if(!blocking) {
  214. if(0 == SOCKET_READABLE(tunnelsocket, 0))
  215. /* return so we'll be called again polling-style */
  216. return CURLE_OK;
  217. else {
  218. DEBUGF(infof(data,
  219. "Read response immediately from proxy CONNECT\n"));
  220. }
  221. }
  222. /* at this point, the tunnel_connecting phase is over. */
  223. { /* READING RESPONSE PHASE */
  224. size_t nread; /* total size read */
  225. int perline; /* count bytes per line */
  226. int keepon=TRUE;
  227. ssize_t gotbytes;
  228. char *ptr;
  229. char *line_start;
  230. ptr=data->state.buffer;
  231. line_start = ptr;
  232. nread=0;
  233. perline=0;
  234. while((nread<BUFSIZE) && (keepon && !error)) {
  235. check = Curl_timeleft(data, NULL, TRUE);
  236. if(check <= 0) {
  237. failf(data, "Proxy CONNECT aborted due to timeout");
  238. error = SELECT_TIMEOUT; /* already too little time */
  239. break;
  240. }
  241. /* loop every second at least, less if the timeout is near */
  242. switch (SOCKET_READABLE(tunnelsocket, check<1000L?check:1000)) {
  243. case -1: /* select() error, stop reading */
  244. error = SELECT_ERROR;
  245. failf(data, "Proxy CONNECT aborted due to select/poll error");
  246. break;
  247. case 0: /* timeout */
  248. break;
  249. default:
  250. DEBUGASSERT(ptr+BUFSIZE-nread <= data->state.buffer+BUFSIZE+1);
  251. result = Curl_read(conn, tunnelsocket, ptr, BUFSIZE-nread,
  252. &gotbytes);
  253. if(result==CURLE_AGAIN)
  254. continue; /* go loop yourself */
  255. else if(result)
  256. keepon = FALSE;
  257. else if(gotbytes <= 0) {
  258. keepon = FALSE;
  259. if(data->set.proxyauth && data->state.authproxy.avail) {
  260. /* proxy auth was requested and there was proxy auth available,
  261. then deem this as "mere" proxy disconnect */
  262. conn->bits.proxy_connect_closed = TRUE;
  263. infof(data, "Proxy CONNECT connection closed\n");
  264. }
  265. else {
  266. error = SELECT_ERROR;
  267. failf(data, "Proxy CONNECT aborted");
  268. }
  269. }
  270. else {
  271. /*
  272. * We got a whole chunk of data, which can be anything from one
  273. * byte to a set of lines and possibly just a piece of the last
  274. * line.
  275. */
  276. int i;
  277. nread += gotbytes;
  278. if(keepon > TRUE) {
  279. /* This means we are currently ignoring a response-body */
  280. nread = 0; /* make next read start over in the read buffer */
  281. ptr=data->state.buffer;
  282. if(cl) {
  283. /* A Content-Length based body: simply count down the counter
  284. and make sure to break out of the loop when we're done! */
  285. cl -= gotbytes;
  286. if(cl<=0) {
  287. keepon = FALSE;
  288. break;
  289. }
  290. }
  291. else {
  292. /* chunked-encoded body, so we need to do the chunked dance
  293. properly to know when the end of the body is reached */
  294. CHUNKcode r;
  295. ssize_t tookcareof=0;
  296. /* now parse the chunked piece of data so that we can
  297. properly tell when the stream ends */
  298. r = Curl_httpchunk_read(conn, ptr, gotbytes, &tookcareof);
  299. if(r == CHUNKE_STOP) {
  300. /* we're done reading chunks! */
  301. infof(data, "chunk reading DONE\n");
  302. keepon = FALSE;
  303. /* we did the full CONNECT treatment, go COMPLETE */
  304. conn->tunnel_state[sockindex] = TUNNEL_COMPLETE;
  305. }
  306. else
  307. infof(data, "Read %zd bytes of chunk, continue\n",
  308. tookcareof);
  309. }
  310. }
  311. else
  312. for(i = 0; i < gotbytes; ptr++, i++) {
  313. perline++; /* amount of bytes in this line so far */
  314. if(*ptr == 0x0a) {
  315. char letter;
  316. int writetype;
  317. /* convert from the network encoding */
  318. result = Curl_convert_from_network(data, line_start,
  319. perline);
  320. /* Curl_convert_from_network calls failf if unsuccessful */
  321. if(result)
  322. return result;
  323. /* output debug if that is requested */
  324. if(data->set.verbose)
  325. Curl_debug(data, CURLINFO_HEADER_IN,
  326. line_start, (size_t)perline, conn);
  327. /* send the header to the callback */
  328. writetype = CLIENTWRITE_HEADER;
  329. if(data->set.include_header)
  330. writetype |= CLIENTWRITE_BODY;
  331. result = Curl_client_write(conn, writetype, line_start,
  332. perline);
  333. data->info.header_size += (long)perline;
  334. data->req.headerbytecount += (long)perline;
  335. if(result)
  336. return result;
  337. /* Newlines are CRLF, so the CR is ignored as the line isn't
  338. really terminated until the LF comes. Treat a following CR
  339. as end-of-headers as well.*/
  340. if(('\r' == line_start[0]) ||
  341. ('\n' == line_start[0])) {
  342. /* end of response-headers from the proxy */
  343. nread = 0; /* make next read start over in the read
  344. buffer */
  345. ptr=data->state.buffer;
  346. if((407 == k->httpcode) && !data->state.authproblem) {
  347. /* If we get a 407 response code with content length
  348. when we have no auth problem, we must ignore the
  349. whole response-body */
  350. keepon = 2;
  351. if(cl) {
  352. infof(data, "Ignore %" CURL_FORMAT_CURL_OFF_T
  353. " bytes of response-body\n", cl);
  354. /* remove the remaining chunk of what we already
  355. read */
  356. cl -= (gotbytes - i);
  357. if(cl<=0)
  358. /* if the whole thing was already read, we are done!
  359. */
  360. keepon=FALSE;
  361. }
  362. else if(chunked_encoding) {
  363. CHUNKcode r;
  364. /* We set ignorebody true here since the chunked
  365. decoder function will acknowledge that. Pay
  366. attention so that this is cleared again when this
  367. function returns! */
  368. k->ignorebody = TRUE;
  369. infof(data, "%zd bytes of chunk left\n", gotbytes-i);
  370. if(line_start[1] == '\n') {
  371. /* this can only be a LF if the letter at index 0
  372. was a CR */
  373. line_start++;
  374. i++;
  375. }
  376. /* now parse the chunked piece of data so that we can
  377. properly tell when the stream ends */
  378. r = Curl_httpchunk_read(conn, line_start+1,
  379. gotbytes -i, &gotbytes);
  380. if(r == CHUNKE_STOP) {
  381. /* we're done reading chunks! */
  382. infof(data, "chunk reading DONE\n");
  383. keepon = FALSE;
  384. /* we did the full CONNECT treatment, go to
  385. COMPLETE */
  386. conn->tunnel_state[sockindex] = TUNNEL_COMPLETE;
  387. }
  388. else
  389. infof(data, "Read %zd bytes of chunk, continue\n",
  390. gotbytes);
  391. }
  392. else {
  393. /* without content-length or chunked encoding, we
  394. can't keep the connection alive since the close is
  395. the end signal so we bail out at once instead */
  396. keepon=FALSE;
  397. }
  398. }
  399. else {
  400. keepon = FALSE;
  401. if(200 == data->info.httpproxycode) {
  402. if(gotbytes - (i+1))
  403. failf(data, "Proxy CONNECT followed by %zd bytes "
  404. "of opaque data. Data ignored (known bug #39)",
  405. gotbytes - (i+1));
  406. }
  407. }
  408. /* we did the full CONNECT treatment, go to COMPLETE */
  409. conn->tunnel_state[sockindex] = TUNNEL_COMPLETE;
  410. break; /* breaks out of for-loop, not switch() */
  411. }
  412. /* keep a backup of the position we are about to blank */
  413. letter = line_start[perline];
  414. line_start[perline]=0; /* zero terminate the buffer */
  415. if((checkprefix("WWW-Authenticate:", line_start) &&
  416. (401 == k->httpcode)) ||
  417. (checkprefix("Proxy-authenticate:", line_start) &&
  418. (407 == k->httpcode))) {
  419. bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
  420. char *auth = Curl_copy_header_value(line_start);
  421. if(!auth)
  422. return CURLE_OUT_OF_MEMORY;
  423. result = Curl_http_input_auth(conn, proxy, auth);
  424. free(auth);
  425. if(result)
  426. return result;
  427. }
  428. else if(checkprefix("Content-Length:", line_start)) {
  429. cl = curlx_strtoofft(line_start +
  430. strlen("Content-Length:"), NULL, 10);
  431. }
  432. else if(Curl_compareheader(line_start,
  433. "Connection:", "close"))
  434. closeConnection = TRUE;
  435. else if(Curl_compareheader(line_start,
  436. "Transfer-Encoding:",
  437. "chunked")) {
  438. infof(data, "CONNECT responded chunked\n");
  439. chunked_encoding = TRUE;
  440. /* init our chunky engine */
  441. Curl_httpchunk_init(conn);
  442. }
  443. else if(Curl_compareheader(line_start,
  444. "Proxy-Connection:", "close"))
  445. closeConnection = TRUE;
  446. else if(2 == sscanf(line_start, "HTTP/1.%d %d",
  447. &subversion,
  448. &k->httpcode)) {
  449. /* store the HTTP code from the proxy */
  450. data->info.httpproxycode = k->httpcode;
  451. }
  452. /* put back the letter we blanked out before */
  453. line_start[perline]= letter;
  454. perline=0; /* line starts over here */
  455. line_start = ptr+1; /* this skips the zero byte we wrote */
  456. }
  457. }
  458. }
  459. break;
  460. } /* switch */
  461. if(Curl_pgrsUpdate(conn))
  462. return CURLE_ABORTED_BY_CALLBACK;
  463. } /* while there's buffer left and loop is requested */
  464. if(error)
  465. return CURLE_RECV_ERROR;
  466. if(data->info.httpproxycode != 200) {
  467. /* Deal with the possibly already received authenticate
  468. headers. 'newurl' is set to a new URL if we must loop. */
  469. result = Curl_http_auth_act(conn);
  470. if(result)
  471. return result;
  472. if(conn->bits.close)
  473. /* the connection has been marked for closure, most likely in the
  474. Curl_http_auth_act() function and thus we can kill it at once
  475. below
  476. */
  477. closeConnection = TRUE;
  478. }
  479. if(closeConnection && data->req.newurl) {
  480. /* Connection closed by server. Don't use it anymore */
  481. Curl_closesocket(conn, conn->sock[sockindex]);
  482. conn->sock[sockindex] = CURL_SOCKET_BAD;
  483. break;
  484. }
  485. } /* END READING RESPONSE PHASE */
  486. /* If we are supposed to continue and request a new URL, which basically
  487. * means the HTTP authentication is still going on so if the tunnel
  488. * is complete we start over in INIT state */
  489. if(data->req.newurl &&
  490. (TUNNEL_COMPLETE == conn->tunnel_state[sockindex])) {
  491. conn->tunnel_state[sockindex] = TUNNEL_INIT;
  492. infof(data, "TUNNEL_STATE switched to: %d\n",
  493. conn->tunnel_state[sockindex]);
  494. }
  495. } while(data->req.newurl);
  496. if(200 != data->req.httpcode) {
  497. if(closeConnection && data->req.newurl) {
  498. conn->bits.proxy_connect_closed = TRUE;
  499. infof(data, "Connect me again please\n");
  500. }
  501. else {
  502. free(data->req.newurl);
  503. data->req.newurl = NULL;
  504. /* failure, close this connection to avoid re-use */
  505. streamclose(conn, "proxy CONNECT failure");
  506. Curl_closesocket(conn, conn->sock[sockindex]);
  507. conn->sock[sockindex] = CURL_SOCKET_BAD;
  508. }
  509. /* to back to init state */
  510. conn->tunnel_state[sockindex] = TUNNEL_INIT;
  511. if(conn->bits.proxy_connect_closed)
  512. /* this is not an error, just part of the connection negotiation */
  513. return CURLE_OK;
  514. else {
  515. failf(data, "Received HTTP code %d from proxy after CONNECT",
  516. data->req.httpcode);
  517. return CURLE_RECV_ERROR;
  518. }
  519. }
  520. conn->tunnel_state[sockindex] = TUNNEL_COMPLETE;
  521. /* If a proxy-authorization header was used for the proxy, then we should
  522. make sure that it isn't accidentally used for the document request
  523. after we've connected. So let's free and clear it here. */
  524. Curl_safefree(conn->allocptr.proxyuserpwd);
  525. conn->allocptr.proxyuserpwd = NULL;
  526. data->state.authproxy.done = TRUE;
  527. infof (data, "Proxy replied OK to CONNECT request\n");
  528. data->req.ignorebody = FALSE; /* put it (back) to non-ignore state */
  529. conn->bits.rewindaftersend = FALSE; /* make sure this isn't set for the
  530. document request */
  531. return CURLE_OK;
  532. }
  533. #endif /* CURL_DISABLE_PROXY */