connect.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2008, 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 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. * $Id$
  22. ***************************************************************************/
  23. #include "setup.h"
  24. #ifndef WIN32
  25. /* headers for non-win32 */
  26. #ifdef HAVE_SYS_TIME_H
  27. #include <sys/time.h>
  28. #endif
  29. #ifdef HAVE_SYS_SOCKET_H
  30. #include <sys/socket.h>
  31. #endif
  32. #ifdef HAVE_NETINET_IN_H
  33. #include <netinet/in.h> /* <netinet/tcp.h> may need it */
  34. #endif
  35. #ifdef HAVE_SYS_UN_H
  36. #include <sys/un.h> /* for sockaddr_un */
  37. #endif
  38. #ifdef HAVE_NETINET_TCP_H
  39. #include <netinet/tcp.h> /* for TCP_NODELAY */
  40. #endif
  41. #ifdef HAVE_SYS_IOCTL_H
  42. #include <sys/ioctl.h>
  43. #endif
  44. #ifdef HAVE_UNISTD_H
  45. #include <unistd.h>
  46. #endif
  47. #ifdef HAVE_NETDB_H
  48. #include <netdb.h>
  49. #endif
  50. #ifdef HAVE_FCNTL_H
  51. #include <fcntl.h>
  52. #endif
  53. #ifdef HAVE_ARPA_INET_H
  54. #include <arpa/inet.h>
  55. #endif
  56. #ifdef HAVE_STDLIB_H
  57. #include <stdlib.h> /* required for free() prototype, without it, this crashes */
  58. #endif /* on macos 68K */
  59. #if (defined(HAVE_FIONBIO) && defined(NETWARE))
  60. #include <sys/filio.h>
  61. #endif
  62. #ifdef NETWARE
  63. #undef in_addr_t
  64. #define in_addr_t unsigned long
  65. #endif
  66. #ifdef VMS
  67. #include <in.h>
  68. #include <inet.h>
  69. #endif
  70. #endif /* !WIN32 */
  71. #include <stdio.h>
  72. #include <errno.h>
  73. #include <string.h>
  74. #define _MPRINTF_REPLACE /* use our functions only */
  75. #include <curl/mprintf.h>
  76. #include "urldata.h"
  77. #include "sendf.h"
  78. #include "if2ip.h"
  79. #include "strerror.h"
  80. #include "connect.h"
  81. #include "memory.h"
  82. #include "select.h"
  83. #include "url.h" /* for Curl_safefree() */
  84. #include "multiif.h"
  85. #include "sockaddr.h" /* required for Curl_sockaddr_storage */
  86. #include "inet_ntop.h"
  87. #include "inet_pton.h"
  88. #include "sslgen.h" /* for Curl_ssl_check_cxn() */
  89. /* The last #include file should be: */
  90. #include "memdebug.h"
  91. #ifdef __SYMBIAN32__
  92. /* This isn't actually supported under Symbian OS */
  93. #undef SO_NOSIGPIPE
  94. #endif
  95. static bool verifyconnect(curl_socket_t sockfd, int *error);
  96. static curl_socket_t
  97. singleipconnect(struct connectdata *conn,
  98. const Curl_addrinfo *ai, /* start connecting to this */
  99. long timeout_ms,
  100. bool *connected);
  101. /*
  102. * Curl_timeleft() returns the amount of milliseconds left allowed for the
  103. * transfer/connection. If the value is negative, the timeout time has already
  104. * elapsed.
  105. *
  106. * If 'nowp' is non-NULL, it points to the current time.
  107. * 'duringconnect' is FALSE if not during a connect, as then of course the
  108. * connect timeout is not taken into account!
  109. */
  110. long Curl_timeleft(struct connectdata *conn,
  111. struct timeval *nowp,
  112. bool duringconnect)
  113. {
  114. struct SessionHandle *data = conn->data;
  115. int timeout_set = 0;
  116. long timeout_ms = duringconnect?DEFAULT_CONNECT_TIMEOUT:0;
  117. struct timeval now;
  118. /* if a timeout is set, use the most restrictive one */
  119. if(data->set.timeout > 0)
  120. timeout_set |= 1;
  121. if(duringconnect && (data->set.connecttimeout > 0))
  122. timeout_set |= 2;
  123. switch (timeout_set) {
  124. case 1:
  125. timeout_ms = data->set.timeout;
  126. break;
  127. case 2:
  128. timeout_ms = data->set.connecttimeout;
  129. break;
  130. case 3:
  131. if(data->set.timeout < data->set.connecttimeout)
  132. timeout_ms = data->set.timeout;
  133. else
  134. timeout_ms = data->set.connecttimeout;
  135. break;
  136. default:
  137. /* use the default */
  138. if(!duringconnect)
  139. /* if we're not during connect, there's no default timeout so if we're
  140. at zero we better just return zero and not make it a negative number
  141. by the math below */
  142. return 0;
  143. break;
  144. }
  145. if(!nowp) {
  146. now = Curl_tvnow();
  147. nowp = &now;
  148. }
  149. /* substract elapsed time */
  150. timeout_ms -= Curl_tvdiff(*nowp, data->progress.t_startsingle);
  151. return timeout_ms;
  152. }
  153. /*
  154. * Curl_nonblock() set the given socket to either blocking or non-blocking
  155. * mode based on the 'nonblock' boolean argument. This function is highly
  156. * portable.
  157. */
  158. int Curl_nonblock(curl_socket_t sockfd, /* operate on this */
  159. int nonblock /* TRUE or FALSE */)
  160. {
  161. #undef SETBLOCK
  162. #define SETBLOCK 0
  163. #ifdef HAVE_O_NONBLOCK
  164. /* most recent unix versions */
  165. int flags;
  166. flags = fcntl(sockfd, F_GETFL, 0);
  167. if(FALSE != nonblock)
  168. return fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
  169. else
  170. return fcntl(sockfd, F_SETFL, flags & (~O_NONBLOCK));
  171. #undef SETBLOCK
  172. #define SETBLOCK 1
  173. #endif
  174. #if defined(HAVE_FIONBIO) && (SETBLOCK == 0)
  175. /* older unix versions */
  176. int flags;
  177. flags = nonblock;
  178. return ioctl(sockfd, FIONBIO, &flags);
  179. #undef SETBLOCK
  180. #define SETBLOCK 2
  181. #endif
  182. #if defined(HAVE_IOCTLSOCKET) && (SETBLOCK == 0)
  183. /* Windows? */
  184. unsigned long flags;
  185. flags = nonblock;
  186. return ioctlsocket(sockfd, FIONBIO, &flags);
  187. #undef SETBLOCK
  188. #define SETBLOCK 3
  189. #endif
  190. #if defined(HAVE_IOCTLSOCKET_CASE) && (SETBLOCK == 0)
  191. /* presumably for Amiga */
  192. return IoctlSocket(sockfd, FIONBIO, (long)nonblock);
  193. #undef SETBLOCK
  194. #define SETBLOCK 4
  195. #endif
  196. #if defined(HAVE_SO_NONBLOCK) && (SETBLOCK == 0)
  197. /* BeOS */
  198. long b = nonblock ? 1 : 0;
  199. return setsockopt(sockfd, SOL_SOCKET, SO_NONBLOCK, &b, sizeof(b));
  200. #undef SETBLOCK
  201. #define SETBLOCK 5
  202. #endif
  203. #ifdef HAVE_DISABLED_NONBLOCKING
  204. return 0; /* returns success */
  205. #undef SETBLOCK
  206. #define SETBLOCK 6
  207. #endif
  208. #if(SETBLOCK == 0)
  209. #error "no non-blocking method was found/used/set"
  210. #endif
  211. }
  212. /*
  213. * waitconnect() waits for a TCP connect on the given socket for the specified
  214. * number if milliseconds. It returns:
  215. * 0 fine connect
  216. * -1 select() error
  217. * 1 select() timeout
  218. * 2 select() returned with an error condition fd_set
  219. */
  220. #define WAITCONN_CONNECTED 0
  221. #define WAITCONN_SELECT_ERROR -1
  222. #define WAITCONN_TIMEOUT 1
  223. #define WAITCONN_FDSET_ERROR 2
  224. static
  225. int waitconnect(curl_socket_t sockfd, /* socket */
  226. long timeout_msec)
  227. {
  228. int rc;
  229. #ifdef mpeix
  230. /* Call this function once now, and ignore the results. We do this to
  231. "clear" the error state on the socket so that we can later read it
  232. reliably. This is reported necessary on the MPE/iX operating system. */
  233. (void)verifyconnect(sockfd, NULL);
  234. #endif
  235. /* now select() until we get connect or timeout */
  236. rc = Curl_socket_ready(CURL_SOCKET_BAD, sockfd, (int)timeout_msec);
  237. if(-1 == rc)
  238. /* error, no connect here, try next */
  239. return WAITCONN_SELECT_ERROR;
  240. else if(0 == rc)
  241. /* timeout, no connect today */
  242. return WAITCONN_TIMEOUT;
  243. if(rc & CURL_CSELECT_ERR)
  244. /* error condition caught */
  245. return WAITCONN_FDSET_ERROR;
  246. /* we have a connect! */
  247. return WAITCONN_CONNECTED;
  248. }
  249. static CURLcode bindlocal(struct connectdata *conn,
  250. curl_socket_t sockfd)
  251. {
  252. #ifdef ENABLE_IPV6
  253. char ipv6_addr[16];
  254. #endif
  255. struct SessionHandle *data = conn->data;
  256. struct sockaddr_in me;
  257. struct sockaddr *sock = NULL; /* bind to this address */
  258. socklen_t socksize; /* size of the data sock points to */
  259. unsigned short port = data->set.localport; /* use this port number, 0 for
  260. "random" */
  261. /* how many port numbers to try to bind to, increasing one at a time */
  262. int portnum = data->set.localportrange;
  263. const char *dev = data->set.str[STRING_DEVICE];
  264. /*************************************************************
  265. * Select device to bind socket to
  266. *************************************************************/
  267. if(dev && (strlen(dev)<255) ) {
  268. struct Curl_dns_entry *h=NULL;
  269. char myhost[256] = "";
  270. in_addr_t in;
  271. int rc;
  272. bool was_iface = FALSE;
  273. int in6 = -1;
  274. /* First check if the given name is an IP address */
  275. in=inet_addr((char *) dev);
  276. if((in == CURL_INADDR_NONE) &&
  277. Curl_if2ip(dev, myhost, sizeof(myhost))) {
  278. /*
  279. * We now have the numerical IPv4-style x.y.z.w in the 'myhost' buffer
  280. */
  281. rc = Curl_resolv(conn, myhost, 0, &h);
  282. if(rc == CURLRESOLV_PENDING)
  283. (void)Curl_wait_for_resolv(conn, &h);
  284. if(h) {
  285. was_iface = TRUE;
  286. Curl_resolv_unlock(data, h);
  287. }
  288. }
  289. if(!was_iface) {
  290. /*
  291. * This was not an interface, resolve the name as a host name
  292. * or IP number
  293. */
  294. rc = Curl_resolv(conn, dev, 0, &h);
  295. if(rc == CURLRESOLV_PENDING)
  296. (void)Curl_wait_for_resolv(conn, &h);
  297. if(h) {
  298. if(in == CURL_INADDR_NONE)
  299. /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
  300. Curl_printable_address(h->addr, myhost, sizeof myhost);
  301. else
  302. /* we know data->set.device is shorter than the myhost array */
  303. strcpy(myhost, dev);
  304. Curl_resolv_unlock(data, h);
  305. }
  306. }
  307. if(! *myhost) {
  308. /* need to fix this
  309. h=Curl_gethost(data,
  310. getmyhost(*myhost,sizeof(myhost)),
  311. hostent_buf,
  312. sizeof(hostent_buf));
  313. */
  314. failf(data, "Couldn't bind to '%s'", dev);
  315. return CURLE_INTERFACE_FAILED;
  316. }
  317. infof(data, "Bind local address to %s\n", myhost);
  318. #ifdef SO_BINDTODEVICE
  319. /* I am not sure any other OSs than Linux that provide this feature, and
  320. * at the least I cannot test. --Ben
  321. *
  322. * This feature allows one to tightly bind the local socket to a
  323. * particular interface. This will force even requests to other local
  324. * interfaces to go out the external interface.
  325. *
  326. */
  327. if(was_iface) {
  328. /* Only bind to the interface when specified as interface, not just as a
  329. * hostname or ip address.
  330. */
  331. if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE,
  332. dev, strlen(dev)+1) != 0) {
  333. /* printf("Failed to BINDTODEVICE, socket: %d device: %s error: %s\n",
  334. sockfd, dev, Curl_strerror(SOCKERRNO)); */
  335. infof(data, "SO_BINDTODEVICE %s failed\n", dev);
  336. /* This is typically "errno 1, error: Operation not permitted" if
  337. you're not running as root or another suitable privileged user */
  338. }
  339. }
  340. #endif
  341. in=inet_addr(myhost);
  342. #ifdef ENABLE_IPV6
  343. in6 = Curl_inet_pton (AF_INET6, myhost, (void *)&ipv6_addr);
  344. #endif
  345. if(CURL_INADDR_NONE == in && -1 == in6) {
  346. failf(data,"couldn't find my own IP address (%s)", myhost);
  347. return CURLE_INTERFACE_FAILED;
  348. } /* end of inet_addr */
  349. if( h ) {
  350. Curl_addrinfo *addr = h->addr;
  351. sock = addr->ai_addr;
  352. socksize = addr->ai_addrlen;
  353. }
  354. else
  355. return CURLE_INTERFACE_FAILED;
  356. }
  357. else if(port) {
  358. /* if a local port number is requested but no local IP, extract the
  359. address from the socket */
  360. memset(&me, 0, sizeof(struct sockaddr));
  361. me.sin_family = AF_INET;
  362. me.sin_addr.s_addr = INADDR_ANY;
  363. sock = (struct sockaddr *)&me;
  364. socksize = sizeof(struct sockaddr);
  365. }
  366. else
  367. /* no local kind of binding was requested */
  368. return CURLE_OK;
  369. do {
  370. /* Set port number to bind to, 0 makes the system pick one */
  371. if(sock->sa_family == AF_INET)
  372. ((struct sockaddr_in *)sock)->sin_port = htons(port);
  373. #ifdef ENABLE_IPV6
  374. else
  375. ((struct sockaddr_in6 *)sock)->sin6_port = htons(port);
  376. #endif
  377. if( bind(sockfd, sock, socksize) >= 0) {
  378. /* we succeeded to bind */
  379. struct Curl_sockaddr_storage add;
  380. socklen_t size;
  381. size = sizeof(add);
  382. if(getsockname(sockfd, (struct sockaddr *) &add, &size) < 0) {
  383. failf(data, "getsockname() failed");
  384. return CURLE_INTERFACE_FAILED;
  385. }
  386. /* We re-use/clobber the port variable here below */
  387. if(((struct sockaddr *)&add)->sa_family == AF_INET)
  388. port = ntohs(((struct sockaddr_in *)&add)->sin_port);
  389. #ifdef ENABLE_IPV6
  390. else
  391. port = ntohs(((struct sockaddr_in6 *)&add)->sin6_port);
  392. #endif
  393. infof(data, "Local port: %d\n", port);
  394. conn->bits.bound = TRUE;
  395. return CURLE_OK;
  396. }
  397. if(--portnum > 0) {
  398. infof(data, "Bind to local port %d failed, trying next\n", port);
  399. port++; /* try next port */
  400. }
  401. else
  402. break;
  403. } while(1);
  404. data->state.os_errno = SOCKERRNO;
  405. failf(data, "bind failure: %s",
  406. Curl_strerror(conn, data->state.os_errno));
  407. return CURLE_INTERFACE_FAILED;
  408. }
  409. /*
  410. * verifyconnect() returns TRUE if the connect really has happened.
  411. */
  412. static bool verifyconnect(curl_socket_t sockfd, int *error)
  413. {
  414. bool rc = TRUE;
  415. #ifdef SO_ERROR
  416. int err = 0;
  417. socklen_t errSize = sizeof(err);
  418. #ifdef WIN32
  419. /*
  420. * In October 2003 we effectively nullified this function on Windows due to
  421. * problems with it using all CPU in multi-threaded cases.
  422. *
  423. * In May 2004, we bring it back to offer more info back on connect failures.
  424. * Gisle Vanem could reproduce the former problems with this function, but
  425. * could avoid them by adding this SleepEx() call below:
  426. *
  427. * "I don't have Rational Quantify, but the hint from his post was
  428. * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
  429. * just Sleep(0) would be enough?) would release whatever
  430. * mutex/critical-section the ntdll call is waiting on.
  431. *
  432. * Someone got to verify this on Win-NT 4.0, 2000."
  433. */
  434. #ifdef _WIN32_WCE
  435. Sleep(0);
  436. #else
  437. SleepEx(0, FALSE);
  438. #endif
  439. #endif
  440. if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
  441. err = SOCKERRNO;
  442. #ifdef _WIN32_WCE
  443. /* Old WinCE versions don't support SO_ERROR */
  444. if(WSAENOPROTOOPT == err) {
  445. SET_SOCKERRNO(0);
  446. err = 0;
  447. }
  448. #endif
  449. #ifdef __minix
  450. /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
  451. if(EBADIOCTL == err) {
  452. SET_SOCKERRNO(0);
  453. err = 0;
  454. }
  455. #endif
  456. if((0 == err) || (EISCONN == err))
  457. /* we are connected, awesome! */
  458. rc = TRUE;
  459. else
  460. /* This wasn't a successful connect */
  461. rc = FALSE;
  462. if(error)
  463. *error = err;
  464. #else
  465. (void)sockfd;
  466. if(error)
  467. *error = SOCKERRNO;
  468. #endif
  469. return rc;
  470. }
  471. CURLcode Curl_store_ip_addr(struct connectdata *conn)
  472. {
  473. char addrbuf[256];
  474. Curl_printable_address(conn->ip_addr, addrbuf, sizeof(addrbuf));
  475. /* save the string */
  476. Curl_safefree(conn->ip_addr_str);
  477. conn->ip_addr_str = strdup(addrbuf);
  478. if(!conn->ip_addr_str)
  479. return CURLE_OUT_OF_MEMORY; /* FAIL */
  480. #ifdef PF_INET6
  481. if(conn->ip_addr->ai_family == PF_INET6)
  482. conn->bits.ipv6 = TRUE;
  483. #endif
  484. return CURLE_OK;
  485. }
  486. /* Used within the multi interface. Try next IP address, return TRUE if no
  487. more address exists or error */
  488. static bool trynextip(struct connectdata *conn,
  489. int sockindex,
  490. bool *connected)
  491. {
  492. curl_socket_t sockfd;
  493. Curl_addrinfo *ai;
  494. /* first close the failed socket */
  495. sclose(conn->sock[sockindex]);
  496. conn->sock[sockindex] = CURL_SOCKET_BAD;
  497. *connected = FALSE;
  498. if(sockindex != FIRSTSOCKET)
  499. return TRUE; /* no next */
  500. /* try the next address */
  501. ai = conn->ip_addr->ai_next;
  502. while(ai) {
  503. sockfd = singleipconnect(conn, ai, 0L, connected);
  504. if(sockfd != CURL_SOCKET_BAD) {
  505. /* store the new socket descriptor */
  506. conn->sock[sockindex] = sockfd;
  507. conn->ip_addr = ai;
  508. return Curl_store_ip_addr(conn) != CURLE_OK;
  509. }
  510. ai = ai->ai_next;
  511. }
  512. return TRUE;
  513. }
  514. /*
  515. * Curl_is_connected() is used from the multi interface to check if the
  516. * firstsocket has connected.
  517. */
  518. CURLcode Curl_is_connected(struct connectdata *conn,
  519. int sockindex,
  520. bool *connected)
  521. {
  522. int rc;
  523. struct SessionHandle *data = conn->data;
  524. CURLcode code = CURLE_OK;
  525. curl_socket_t sockfd = conn->sock[sockindex];
  526. long allow = DEFAULT_CONNECT_TIMEOUT;
  527. DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);
  528. *connected = FALSE; /* a very negative world view is best */
  529. if(conn->bits.tcpconnect) {
  530. /* we are connected already! */
  531. long allow_total = 0;
  532. /* subtract the most strict timeout of the ones */
  533. if(data->set.timeout)
  534. allow_total = data->set.timeout;
  535. Curl_expire(data, allow_total);
  536. *connected = TRUE;
  537. return CURLE_OK;
  538. }
  539. /* figure out how long time we have left to connect */
  540. allow = Curl_timeleft(conn, NULL, TRUE);
  541. if(allow < 0) {
  542. /* time-out, bail out, go home */
  543. failf(data, "Connection time-out");
  544. return CURLE_OPERATION_TIMEDOUT;
  545. }
  546. Curl_expire(data, allow);
  547. /* check for connect without timeout as we want to return immediately */
  548. rc = waitconnect(sockfd, 0);
  549. if(WAITCONN_CONNECTED == rc) {
  550. int error;
  551. if(verifyconnect(sockfd, &error)) {
  552. /* we are connected, awesome! */
  553. *connected = TRUE;
  554. return CURLE_OK;
  555. }
  556. /* nope, not connected for real */
  557. data->state.os_errno = error;
  558. infof(data, "Connection failed\n");
  559. if(trynextip(conn, sockindex, connected)) {
  560. failf(data, "Failed connect to %s:%d; %s",
  561. conn->host.name, conn->port, Curl_strerror(conn, error));
  562. code = CURLE_COULDNT_CONNECT;
  563. }
  564. }
  565. else if(WAITCONN_TIMEOUT != rc) {
  566. int error = 0;
  567. /* nope, not connected */
  568. if(WAITCONN_FDSET_ERROR == rc) {
  569. (void)verifyconnect(sockfd, &error);
  570. data->state.os_errno = error;
  571. infof(data, "%s\n",Curl_strerror(conn,error));
  572. }
  573. else
  574. infof(data, "Connection failed\n");
  575. if(trynextip(conn, sockindex, connected)) {
  576. error = SOCKERRNO;
  577. data->state.os_errno = error;
  578. failf(data, "Failed connect to %s:%d; %s",
  579. conn->host.name, conn->port, Curl_strerror(conn, error));
  580. code = CURLE_COULDNT_CONNECT;
  581. }
  582. }
  583. /*
  584. * If the connection failed here, we should attempt to connect to the "next
  585. * address" for the given host.
  586. */
  587. return code;
  588. }
  589. static void tcpnodelay(struct connectdata *conn,
  590. curl_socket_t sockfd)
  591. {
  592. #ifdef TCP_NODELAY
  593. struct SessionHandle *data= conn->data;
  594. socklen_t onoff = (socklen_t) data->set.tcp_nodelay;
  595. int proto = IPPROTO_TCP;
  596. #if 0
  597. /* The use of getprotobyname() is disabled since it isn't thread-safe on
  598. numerous systems. On these getprotobyname_r() should be used instead, but
  599. that exists in at least one 4 arg version and one 5 arg version, and
  600. since the proto number rarely changes anyway we now just use the hard
  601. coded number. The "proper" fix would need a configure check for the
  602. correct function much in the same style the gethostbyname_r versions are
  603. detected. */
  604. struct protoent *pe = getprotobyname("tcp");
  605. if(pe)
  606. proto = pe->p_proto;
  607. #endif
  608. if(setsockopt(sockfd, proto, TCP_NODELAY, (void *)&onoff,
  609. sizeof(onoff)) < 0)
  610. infof(data, "Could not set TCP_NODELAY: %s\n",
  611. Curl_strerror(conn, SOCKERRNO));
  612. else
  613. infof(data,"TCP_NODELAY set\n");
  614. #else
  615. (void)conn;
  616. (void)sockfd;
  617. #endif
  618. }
  619. #ifdef SO_NOSIGPIPE
  620. /* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
  621. sending data to a dead peer (instead of relying on the 4th argument to send
  622. being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
  623. systems? */
  624. static void nosigpipe(struct connectdata *conn,
  625. curl_socket_t sockfd)
  626. {
  627. struct SessionHandle *data= conn->data;
  628. int onoff = 1;
  629. if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
  630. sizeof(onoff)) < 0)
  631. infof(data, "Could not set SO_NOSIGPIPE: %s\n",
  632. Curl_strerror(conn, SOCKERRNO));
  633. }
  634. #else
  635. #define nosigpipe(x,y)
  636. #endif
  637. /* singleipconnect() connects to the given IP only, and it may return without
  638. having connected if used from the multi interface. */
  639. static curl_socket_t
  640. singleipconnect(struct connectdata *conn,
  641. const Curl_addrinfo *ai,
  642. long timeout_ms,
  643. bool *connected)
  644. {
  645. char addr_buf[128];
  646. int rc;
  647. int error;
  648. bool isconnected;
  649. struct SessionHandle *data = conn->data;
  650. curl_socket_t sockfd;
  651. CURLcode res;
  652. /*
  653. * Curl_sockaddr_storage, which is basically sockaddr_storage has a space
  654. * for a largest possible struct sockaddr only. We should add some space for
  655. * the other fields we are using. Hence the addr_storage size math.
  656. */
  657. char addr_storage[sizeof(struct curl_sockaddr)-
  658. sizeof(struct sockaddr)+
  659. sizeof(struct Curl_sockaddr_storage)];
  660. struct curl_sockaddr *addr=(struct curl_sockaddr*)&addr_storage;
  661. const void *iptoprint;
  662. addr->family=ai->ai_family;
  663. addr->socktype=conn->socktype;
  664. addr->protocol=ai->ai_protocol;
  665. addr->addrlen =
  666. (ai->ai_addrlen < (socklen_t)sizeof(struct Curl_sockaddr_storage)) ?
  667. (unsigned int)ai->ai_addrlen : sizeof(struct Curl_sockaddr_storage);
  668. memcpy(&addr->addr, ai->ai_addr, addr->addrlen);
  669. /* If set, use opensocket callback to get the socket */
  670. if(data->set.fopensocket)
  671. sockfd = data->set.fopensocket(data->set.opensocket_client,
  672. CURLSOCKTYPE_IPCXN, addr);
  673. else
  674. sockfd = socket(addr->family, addr->socktype, addr->protocol);
  675. if(sockfd == CURL_SOCKET_BAD)
  676. return CURL_SOCKET_BAD;
  677. *connected = FALSE; /* default is not connected */
  678. #ifdef CURLRES_IPV6
  679. if (conn->scope && (addr->family == AF_INET6)) {
  680. struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&addr->addr;
  681. in6->sin6_scope_id = conn->scope;
  682. }
  683. #endif
  684. /* FIXME: do we have Curl_printable_address-like with struct sockaddr* as
  685. argument? */
  686. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  687. if(addr->family==AF_UNIX) {
  688. infof(data, " Trying %s... ",
  689. ((const struct sockaddr_un*)(&addr->addr))->sun_path);
  690. snprintf(data->info.ip, MAX_IPADR_LEN, "%s",
  691. ((const struct sockaddr_un*)(&addr->addr))->sun_path);
  692. }
  693. else
  694. #endif
  695. {
  696. #ifdef ENABLE_IPV6
  697. if(addr->family==AF_INET6)
  698. iptoprint= &((const struct sockaddr_in6*)(&addr->addr))->sin6_addr;
  699. else
  700. #endif
  701. iptoprint = &((const struct sockaddr_in*)(&addr->addr))->sin_addr;
  702. if(Curl_inet_ntop(addr->family, iptoprint, addr_buf,
  703. sizeof(addr_buf)) != NULL) {
  704. infof(data, " Trying %s... ", addr_buf);
  705. snprintf(data->info.ip, MAX_IPADR_LEN, "%s", addr_buf);
  706. }
  707. }
  708. if(data->set.tcp_nodelay)
  709. tcpnodelay(conn, sockfd);
  710. nosigpipe(conn, sockfd);
  711. if(data->set.fsockopt) {
  712. /* activate callback for setting socket options */
  713. error = data->set.fsockopt(data->set.sockopt_client,
  714. sockfd,
  715. CURLSOCKTYPE_IPCXN);
  716. if(error) {
  717. sclose(sockfd); /* close the socket and bail out */
  718. return CURL_SOCKET_BAD;
  719. }
  720. }
  721. /* possibly bind the local end to an IP, interface or port */
  722. res = bindlocal(conn, sockfd);
  723. if(res) {
  724. sclose(sockfd); /* close socket and bail out */
  725. return CURL_SOCKET_BAD;
  726. }
  727. /* set socket non-blocking */
  728. Curl_nonblock(sockfd, TRUE);
  729. /* Connect TCP sockets, bind UDP */
  730. if(conn->socktype == SOCK_STREAM)
  731. rc = connect(sockfd, &addr->addr, addr->addrlen);
  732. else
  733. rc = 0;
  734. if(-1 == rc) {
  735. error = SOCKERRNO;
  736. switch (error) {
  737. case EINPROGRESS:
  738. case EWOULDBLOCK:
  739. #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
  740. /* On some platforms EAGAIN and EWOULDBLOCK are the
  741. * same value, and on others they are different, hence
  742. * the odd #if
  743. */
  744. case EAGAIN:
  745. #endif
  746. rc = waitconnect(sockfd, timeout_ms);
  747. break;
  748. default:
  749. /* unknown error, fallthrough and try another address! */
  750. failf(data, "Failed to connect to %s: %s",
  751. addr_buf, Curl_strerror(conn,error));
  752. data->state.os_errno = error;
  753. break;
  754. }
  755. }
  756. /* The 'WAITCONN_TIMEOUT == rc' comes from the waitconnect(), and not from
  757. connect(). We can be sure of this since connect() cannot return 1. */
  758. if((WAITCONN_TIMEOUT == rc) &&
  759. (data->state.used_interface == Curl_if_multi)) {
  760. /* Timeout when running the multi interface */
  761. return sockfd;
  762. }
  763. isconnected = verifyconnect(sockfd, &error);
  764. if(!rc && isconnected) {
  765. /* we are connected, awesome! */
  766. *connected = TRUE; /* this is a true connect */
  767. infof(data, "connected\n");
  768. return sockfd;
  769. }
  770. else if(WAITCONN_TIMEOUT == rc)
  771. infof(data, "Timeout\n");
  772. else {
  773. data->state.os_errno = error;
  774. infof(data, "%s\n", Curl_strerror(conn, error));
  775. }
  776. /* connect failed or timed out */
  777. sclose(sockfd);
  778. return CURL_SOCKET_BAD;
  779. }
  780. /*
  781. * TCP connect to the given host with timeout, proxy or remote doesn't matter.
  782. * There might be more than one IP address to try out. Fill in the passed
  783. * pointer with the connected socket.
  784. */
  785. CURLcode Curl_connecthost(struct connectdata *conn, /* context */
  786. const struct Curl_dns_entry *remotehost,
  787. curl_socket_t *sockconn, /* the connected socket */
  788. Curl_addrinfo **addr, /* the one we used */
  789. bool *connected) /* really connected? */
  790. {
  791. struct SessionHandle *data = conn->data;
  792. curl_socket_t sockfd = CURL_SOCKET_BAD;
  793. int aliasindex;
  794. int num_addr;
  795. Curl_addrinfo *ai;
  796. Curl_addrinfo *curr_addr;
  797. struct timeval after;
  798. struct timeval before = Curl_tvnow();
  799. /*************************************************************
  800. * Figure out what maximum time we have left
  801. *************************************************************/
  802. long timeout_ms;
  803. long timeout_per_addr;
  804. DEBUGASSERT(sockconn);
  805. *connected = FALSE; /* default to not connected */
  806. /* get the timeout left */
  807. timeout_ms = Curl_timeleft(conn, &before, TRUE);
  808. if(timeout_ms < 0) {
  809. /* a precaution, no need to continue if time already is up */
  810. failf(data, "Connection time-out");
  811. return CURLE_OPERATION_TIMEDOUT;
  812. }
  813. Curl_expire(data, timeout_ms);
  814. /* Max time for each address */
  815. num_addr = Curl_num_addresses(remotehost->addr);
  816. timeout_per_addr = timeout_ms / num_addr;
  817. ai = remotehost->addr;
  818. /* Below is the loop that attempts to connect to all IP-addresses we
  819. * know for the given host. One by one until one IP succeeds.
  820. */
  821. if(data->state.used_interface == Curl_if_multi)
  822. /* don't hang when doing multi */
  823. timeout_per_addr = 0;
  824. /*
  825. * Connecting with a Curl_addrinfo chain
  826. */
  827. for (curr_addr = ai, aliasindex=0; curr_addr;
  828. curr_addr = curr_addr->ai_next, aliasindex++) {
  829. /* start connecting to the IP curr_addr points to */
  830. sockfd = singleipconnect(conn, curr_addr, timeout_per_addr, connected);
  831. if(sockfd != CURL_SOCKET_BAD)
  832. break;
  833. /* get a new timeout for next attempt */
  834. after = Curl_tvnow();
  835. timeout_ms -= Curl_tvdiff(after, before);
  836. if(timeout_ms < 0) {
  837. failf(data, "connect() timed out!");
  838. return CURLE_OPERATION_TIMEDOUT;
  839. }
  840. before = after;
  841. } /* end of connect-to-each-address loop */
  842. *sockconn = sockfd; /* the socket descriptor we've connected */
  843. if(sockfd == CURL_SOCKET_BAD) {
  844. /* no good connect was made */
  845. failf(data, "couldn't connect to host");
  846. return CURLE_COULDNT_CONNECT;
  847. }
  848. /* leave the socket in non-blocking mode */
  849. /* store the address we use */
  850. if(addr)
  851. *addr = curr_addr;
  852. data->info.numconnects++; /* to track the number of connections made */
  853. return CURLE_OK;
  854. }
  855. /*
  856. * Used to extract socket and connectdata struct for the most recent
  857. * transfer on the given SessionHandle.
  858. *
  859. * The socket 'long' will be -1 in case of failure!
  860. */
  861. CURLcode Curl_getconnectinfo(struct SessionHandle *data,
  862. long *param_longp,
  863. struct connectdata **connp)
  864. {
  865. if((data->state.lastconnect != -1) &&
  866. (data->state.connc->connects[data->state.lastconnect] != NULL)) {
  867. struct connectdata *c =
  868. data->state.connc->connects[data->state.lastconnect];
  869. if(connp)
  870. /* only store this if the caller cares for it */
  871. *connp = c;
  872. *param_longp = c->sock[FIRSTSOCKET];
  873. /* we have a socket connected, let's determine if the server shut down */
  874. /* determine if ssl */
  875. if(c->ssl[FIRSTSOCKET].use) {
  876. /* use the SSL context */
  877. if(!Curl_ssl_check_cxn(c))
  878. *param_longp = -1; /* FIN received */
  879. }
  880. /* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */
  881. #ifdef MSG_PEEK
  882. else {
  883. /* use the socket */
  884. char buf;
  885. if(recv((RECV_TYPE_ARG1)c->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
  886. (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK) == 0) {
  887. *param_longp = -1; /* FIN received */
  888. }
  889. }
  890. #endif
  891. }
  892. else
  893. *param_longp = -1;
  894. return CURLE_OK;
  895. }