connect.c 36 KB

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