connect.c 35 KB

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