http_proxy.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, 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 http://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 "setup.h"
  23. #if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
  24. #ifdef HAVE_UNISTD_H
  25. #include <unistd.h>
  26. #endif
  27. #include "urldata.h"
  28. #include <curl/curl.h>
  29. #include "http_proxy.h"
  30. #include "sendf.h"
  31. #include "http.h"
  32. #include "url.h"
  33. #include "select.h"
  34. #include "rawstr.h"
  35. #include "progress.h"
  36. #include "non-ascii.h"
  37. #include "connect.h"
  38. #define _MPRINTF_REPLACE /* use our functions only */
  39. #include <curl/mprintf.h>
  40. #include "curlx.h"
  41. /* The last #include file should be: */
  42. #include "memdebug.h"
  43. /*
  44. * Curl_proxyCONNECT() requires that we're connected to a HTTP proxy. This
  45. * function will issue the necessary commands to get a seamless tunnel through
  46. * this proxy. After that, the socket can be used just as a normal socket.
  47. *
  48. * This badly needs to be rewritten. CONNECT should be sent and dealt with
  49. * like any ordinary HTTP request, and not specially crafted like this. This
  50. * function only remains here like this for now since the rewrite is a bit too
  51. * much work to do at the moment.
  52. *
  53. * This function is BLOCKING which is nasty for all multi interface using apps.
  54. */
  55. CURLcode Curl_proxyCONNECT(struct connectdata *conn,
  56. int sockindex,
  57. const char *hostname,
  58. unsigned short remote_port)
  59. {
  60. int subversion=0;
  61. struct SessionHandle *data=conn->data;
  62. struct SingleRequest *k = &data->req;
  63. CURLcode result;
  64. long timeout =
  65. data->set.timeout?data->set.timeout:PROXY_TIMEOUT; /* in milliseconds */
  66. curl_socket_t tunnelsocket = conn->sock[sockindex];
  67. curl_off_t cl=0;
  68. bool closeConnection = FALSE;
  69. bool chunked_encoding = FALSE;
  70. long check;
  71. #define SELECT_OK 0
  72. #define SELECT_ERROR 1
  73. #define SELECT_TIMEOUT 2
  74. int error = SELECT_OK;
  75. conn->bits.proxy_connect_closed = FALSE;
  76. do {
  77. if(!conn->bits.tunnel_connecting) { /* BEGIN CONNECT PHASE */
  78. char *host_port;
  79. Curl_send_buffer *req_buffer;
  80. infof(data, "Establish HTTP proxy tunnel to %s:%hu\n",
  81. hostname, remote_port);
  82. if(data->req.newurl) {
  83. /* This only happens if we've looped here due to authentication
  84. reasons, and we don't really use the newly cloned URL here
  85. then. Just free() it. */
  86. free(data->req.newurl);
  87. data->req.newurl = NULL;
  88. }
  89. /* initialize a dynamic send-buffer */
  90. req_buffer = Curl_add_buffer_init();
  91. if(!req_buffer)
  92. return CURLE_OUT_OF_MEMORY;
  93. host_port = aprintf("%s:%hu", hostname, remote_port);
  94. if(!host_port) {
  95. free(req_buffer);
  96. return CURLE_OUT_OF_MEMORY;
  97. }
  98. /* Setup the proxy-authorization header, if any */
  99. result = Curl_http_output_auth(conn, "CONNECT", host_port, TRUE);
  100. if(CURLE_OK == result) {
  101. char *host=(char *)"";
  102. const char *proxyconn="";
  103. const char *useragent="";
  104. const char *http = (conn->proxytype == CURLPROXY_HTTP_1_0) ?
  105. "1.0" : "1.1";
  106. if(!Curl_checkheaders(data, "Host:")) {
  107. host = aprintf("Host: %s\r\n", host_port);
  108. if(!host) {
  109. free(req_buffer);
  110. free(host_port);
  111. return CURLE_OUT_OF_MEMORY;
  112. }
  113. }
  114. if(!Curl_checkheaders(data, "Proxy-Connection:"))
  115. proxyconn = "Proxy-Connection: Keep-Alive\r\n";
  116. if(!Curl_checkheaders(data, "User-Agent:") &&
  117. data->set.str[STRING_USERAGENT])
  118. useragent = conn->allocptr.uagent;
  119. /* Send the connect request to the proxy */
  120. /* BLOCKING */
  121. result =
  122. Curl_add_bufferf(req_buffer,
  123. "CONNECT %s:%hu HTTP/%s\r\n"
  124. "%s" /* Host: */
  125. "%s" /* Proxy-Authorization */
  126. "%s" /* User-Agent */
  127. "%s", /* Proxy-Connection */
  128. hostname, remote_port, http,
  129. host,
  130. conn->allocptr.proxyuserpwd?
  131. conn->allocptr.proxyuserpwd:"",
  132. useragent,
  133. proxyconn);
  134. if(host && *host)
  135. free(host);
  136. if(CURLE_OK == result)
  137. result = Curl_add_custom_headers(conn, req_buffer);
  138. if(CURLE_OK == result)
  139. /* CRLF terminate the request */
  140. result = Curl_add_bufferf(req_buffer, "\r\n");
  141. if(CURLE_OK == result) {
  142. /* Now send off the request */
  143. result =
  144. Curl_add_buffer_send(req_buffer, conn,
  145. &data->info.request_size, 0, sockindex);
  146. }
  147. req_buffer = NULL;
  148. if(result)
  149. failf(data, "Failed sending CONNECT to proxy");
  150. }
  151. free(host_port);
  152. Curl_safefree(req_buffer);
  153. if(result)
  154. return result;
  155. conn->bits.tunnel_connecting = TRUE;
  156. } /* END CONNECT PHASE */
  157. /* now we've issued the CONNECT and we're waiting to hear back -
  158. we try not to block here in multi-mode because that might be a LONG
  159. wait if the proxy cannot connect-through to the remote host. */
  160. /* if timeout is requested, find out how much remaining time we have */
  161. check = timeout - /* timeout time */
  162. Curl_tvdiff(Curl_tvnow(), conn->now); /* spent time */
  163. if(check <= 0) {
  164. failf(data, "Proxy CONNECT aborted due to timeout");
  165. return CURLE_RECV_ERROR;
  166. }
  167. /* if we're in multi-mode and we would block, return instead for a retry */
  168. if(Curl_if_multi == data->state.used_interface) {
  169. if(0 == Curl_socket_ready(tunnelsocket, CURL_SOCKET_BAD, 0))
  170. /* return so we'll be called again polling-style */
  171. return CURLE_OK;
  172. else {
  173. DEBUGF(infof(data,
  174. "Multi mode finished polling for response from "
  175. "proxy CONNECT."));
  176. }
  177. }
  178. else {
  179. DEBUGF(infof(data, "Easy mode waiting response from proxy CONNECT."));
  180. }
  181. /* at this point, either:
  182. 1) we're in easy-mode and so it's okay to block waiting for a CONNECT
  183. response
  184. 2) we're in multi-mode and we didn't block - it's either an error or we
  185. now have some data waiting.
  186. In any case, the tunnel_connecting phase is over. */
  187. conn->bits.tunnel_connecting = FALSE;
  188. { /* BEGIN NEGOTIATION PHASE */
  189. size_t nread; /* total size read */
  190. int perline; /* count bytes per line */
  191. int keepon=TRUE;
  192. ssize_t gotbytes;
  193. char *ptr;
  194. char *line_start;
  195. ptr=data->state.buffer;
  196. line_start = ptr;
  197. nread=0;
  198. perline=0;
  199. keepon=TRUE;
  200. while((nread<BUFSIZE) && (keepon && !error)) {
  201. /* if timeout is requested, find out how much remaining time we have */
  202. check = timeout - /* timeout time */
  203. Curl_tvdiff(Curl_tvnow(), conn->now); /* spent time */
  204. if(check <= 0) {
  205. failf(data, "Proxy CONNECT aborted due to timeout");
  206. error = SELECT_TIMEOUT; /* already too little time */
  207. break;
  208. }
  209. /* loop every second at least, less if the timeout is near */
  210. switch (Curl_socket_ready(tunnelsocket, CURL_SOCKET_BAD,
  211. check<1000L?check:1000)) {
  212. case -1: /* select() error, stop reading */
  213. error = SELECT_ERROR;
  214. failf(data, "Proxy CONNECT aborted due to select/poll error");
  215. break;
  216. case 0: /* timeout */
  217. break;
  218. default:
  219. DEBUGASSERT(ptr+BUFSIZE-nread <= data->state.buffer+BUFSIZE+1);
  220. result = Curl_read(conn, tunnelsocket, ptr, BUFSIZE-nread,
  221. &gotbytes);
  222. if(result==CURLE_AGAIN)
  223. continue; /* go loop yourself */
  224. else if(result)
  225. keepon = FALSE;
  226. else if(gotbytes <= 0) {
  227. keepon = FALSE;
  228. if(data->set.proxyauth && data->state.authproxy.avail) {
  229. /* proxy auth was requested and there was proxy auth available,
  230. then deem this as "mere" proxy disconnect */
  231. conn->bits.proxy_connect_closed = TRUE;
  232. }
  233. else {
  234. error = SELECT_ERROR;
  235. failf(data, "Proxy CONNECT aborted");
  236. }
  237. }
  238. else {
  239. /*
  240. * We got a whole chunk of data, which can be anything from one
  241. * byte to a set of lines and possibly just a piece of the last
  242. * line.
  243. */
  244. int i;
  245. nread += gotbytes;
  246. if(keepon > TRUE) {
  247. /* This means we are currently ignoring a response-body */
  248. nread = 0; /* make next read start over in the read buffer */
  249. ptr=data->state.buffer;
  250. if(cl) {
  251. /* A Content-Length based body: simply count down the counter
  252. and make sure to break out of the loop when we're done! */
  253. cl -= gotbytes;
  254. if(cl<=0) {
  255. keepon = FALSE;
  256. break;
  257. }
  258. }
  259. else {
  260. /* chunked-encoded body, so we need to do the chunked dance
  261. properly to know when the end of the body is reached */
  262. CHUNKcode r;
  263. ssize_t tookcareof=0;
  264. /* now parse the chunked piece of data so that we can
  265. properly tell when the stream ends */
  266. r = Curl_httpchunk_read(conn, ptr, gotbytes, &tookcareof);
  267. if(r == CHUNKE_STOP) {
  268. /* we're done reading chunks! */
  269. infof(data, "chunk reading DONE\n");
  270. keepon = FALSE;
  271. }
  272. else
  273. infof(data, "Read %zd bytes of chunk, continue\n",
  274. tookcareof);
  275. }
  276. }
  277. else
  278. for(i = 0; i < gotbytes; ptr++, i++) {
  279. perline++; /* amount of bytes in this line so far */
  280. if(*ptr == 0x0a) {
  281. char letter;
  282. int writetype;
  283. /* convert from the network encoding */
  284. result = Curl_convert_from_network(data, line_start,
  285. perline);
  286. /* Curl_convert_from_network calls failf if unsuccessful */
  287. if(result)
  288. return result;
  289. /* output debug if that is requested */
  290. if(data->set.verbose)
  291. Curl_debug(data, CURLINFO_HEADER_IN,
  292. line_start, (size_t)perline, conn);
  293. /* send the header to the callback */
  294. writetype = CLIENTWRITE_HEADER;
  295. if(data->set.include_header)
  296. writetype |= CLIENTWRITE_BODY;
  297. result = Curl_client_write(conn, writetype, line_start,
  298. perline);
  299. if(result)
  300. return result;
  301. /* Newlines are CRLF, so the CR is ignored as the line isn't
  302. really terminated until the LF comes. Treat a following CR
  303. as end-of-headers as well.*/
  304. if(('\r' == line_start[0]) ||
  305. ('\n' == line_start[0])) {
  306. /* end of response-headers from the proxy */
  307. nread = 0; /* make next read start over in the read
  308. buffer */
  309. ptr=data->state.buffer;
  310. if((407 == k->httpcode) && !data->state.authproblem) {
  311. /* If we get a 407 response code with content length
  312. when we have no auth problem, we must ignore the
  313. whole response-body */
  314. keepon = 2;
  315. if(cl) {
  316. infof(data, "Ignore %" FORMAT_OFF_T
  317. " bytes of response-body\n", cl);
  318. /* remove the remaining chunk of what we already
  319. read */
  320. cl -= (gotbytes - i);
  321. if(cl<=0)
  322. /* if the whole thing was already read, we are done!
  323. */
  324. keepon=FALSE;
  325. }
  326. else if(chunked_encoding) {
  327. CHUNKcode r;
  328. /* We set ignorebody true here since the chunked
  329. decoder function will acknowledge that. Pay
  330. attention so that this is cleared again when this
  331. function returns! */
  332. k->ignorebody = TRUE;
  333. infof(data, "%zd bytes of chunk left\n", gotbytes-i);
  334. if(line_start[1] == '\n') {
  335. /* this can only be a LF if the letter at index 0
  336. was a CR */
  337. line_start++;
  338. i++;
  339. }
  340. /* now parse the chunked piece of data so that we can
  341. properly tell when the stream ends */
  342. r = Curl_httpchunk_read(conn, line_start+1,
  343. gotbytes -i, &gotbytes);
  344. if(r == CHUNKE_STOP) {
  345. /* we're done reading chunks! */
  346. infof(data, "chunk reading DONE\n");
  347. keepon = FALSE;
  348. }
  349. else
  350. infof(data, "Read %zd bytes of chunk, continue\n",
  351. gotbytes);
  352. }
  353. else {
  354. /* without content-length or chunked encoding, we
  355. can't keep the connection alive since the close is
  356. the end signal so we bail out at once instead */
  357. keepon=FALSE;
  358. }
  359. }
  360. else
  361. keepon = FALSE;
  362. break; /* breaks out of for-loop, not switch() */
  363. }
  364. /* keep a backup of the position we are about to blank */
  365. letter = line_start[perline];
  366. line_start[perline]=0; /* zero terminate the buffer */
  367. if((checkprefix("WWW-Authenticate:", line_start) &&
  368. (401 == k->httpcode)) ||
  369. (checkprefix("Proxy-authenticate:", line_start) &&
  370. (407 == k->httpcode))) {
  371. result = Curl_http_input_auth(conn, k->httpcode,
  372. line_start);
  373. if(result)
  374. return result;
  375. }
  376. else if(checkprefix("Content-Length:", line_start)) {
  377. cl = curlx_strtoofft(line_start +
  378. strlen("Content-Length:"), NULL, 10);
  379. }
  380. else if(Curl_compareheader(line_start,
  381. "Connection:", "close"))
  382. closeConnection = TRUE;
  383. else if(Curl_compareheader(line_start,
  384. "Transfer-Encoding:",
  385. "chunked")) {
  386. infof(data, "CONNECT responded chunked\n");
  387. chunked_encoding = TRUE;
  388. /* init our chunky engine */
  389. Curl_httpchunk_init(conn);
  390. }
  391. else if(Curl_compareheader(line_start,
  392. "Proxy-Connection:", "close"))
  393. closeConnection = TRUE;
  394. else if(2 == sscanf(line_start, "HTTP/1.%d %d",
  395. &subversion,
  396. &k->httpcode)) {
  397. /* store the HTTP code from the proxy */
  398. data->info.httpproxycode = k->httpcode;
  399. }
  400. /* put back the letter we blanked out before */
  401. line_start[perline]= letter;
  402. perline=0; /* line starts over here */
  403. line_start = ptr+1; /* this skips the zero byte we wrote */
  404. }
  405. }
  406. }
  407. break;
  408. } /* switch */
  409. if(Curl_pgrsUpdate(conn))
  410. return CURLE_ABORTED_BY_CALLBACK;
  411. } /* while there's buffer left and loop is requested */
  412. if(error)
  413. return CURLE_RECV_ERROR;
  414. if(data->info.httpproxycode != 200) {
  415. /* Deal with the possibly already received authenticate
  416. headers. 'newurl' is set to a new URL if we must loop. */
  417. result = Curl_http_auth_act(conn);
  418. if(result)
  419. return result;
  420. if(conn->bits.close)
  421. /* the connection has been marked for closure, most likely in the
  422. Curl_http_auth_act() function and thus we can kill it at once
  423. below
  424. */
  425. closeConnection = TRUE;
  426. }
  427. if(closeConnection && data->req.newurl) {
  428. /* Connection closed by server. Don't use it anymore */
  429. Curl_closesocket(conn, conn->sock[sockindex]);
  430. conn->sock[sockindex] = CURL_SOCKET_BAD;
  431. break;
  432. }
  433. } /* END NEGOTIATION PHASE */
  434. } while(data->req.newurl);
  435. if(200 != data->req.httpcode) {
  436. failf(data, "Received HTTP code %d from proxy after CONNECT",
  437. data->req.httpcode);
  438. if(closeConnection && data->req.newurl)
  439. conn->bits.proxy_connect_closed = TRUE;
  440. return CURLE_RECV_ERROR;
  441. }
  442. /* If a proxy-authorization header was used for the proxy, then we should
  443. make sure that it isn't accidentally used for the document request
  444. after we've connected. So let's free and clear it here. */
  445. Curl_safefree(conn->allocptr.proxyuserpwd);
  446. conn->allocptr.proxyuserpwd = NULL;
  447. data->state.authproxy.done = TRUE;
  448. infof (data, "Proxy replied OK to CONNECT request\n");
  449. data->req.ignorebody = FALSE; /* put it (back) to non-ignore state */
  450. return CURLE_OK;
  451. }
  452. #endif /* CURL_DISABLE_PROXY */