connect.c 32 KB

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