2
0

connect.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2019, 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 https://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 "curl_setup.h"
  23. #ifdef HAVE_NETINET_IN_H
  24. #include <netinet/in.h> /* <netinet/tcp.h> may need it */
  25. #endif
  26. #ifdef HAVE_SYS_UN_H
  27. #include <sys/un.h> /* for sockaddr_un */
  28. #endif
  29. #ifdef HAVE_LINUX_TCP_H
  30. #include <linux/tcp.h>
  31. #elif defined(HAVE_NETINET_TCP_H)
  32. #include <netinet/tcp.h>
  33. #endif
  34. #ifdef HAVE_SYS_IOCTL_H
  35. #include <sys/ioctl.h>
  36. #endif
  37. #ifdef HAVE_NETDB_H
  38. #include <netdb.h>
  39. #endif
  40. #ifdef HAVE_FCNTL_H
  41. #include <fcntl.h>
  42. #endif
  43. #ifdef HAVE_ARPA_INET_H
  44. #include <arpa/inet.h>
  45. #endif
  46. #if (defined(HAVE_IOCTL_FIONBIO) && defined(NETWARE))
  47. #include <sys/filio.h>
  48. #endif
  49. #ifdef NETWARE
  50. #undef in_addr_t
  51. #define in_addr_t unsigned long
  52. #endif
  53. #ifdef __VMS
  54. #include <in.h>
  55. #include <inet.h>
  56. #endif
  57. #include "urldata.h"
  58. #include "sendf.h"
  59. #include "if2ip.h"
  60. #include "strerror.h"
  61. #include "connect.h"
  62. #include "select.h"
  63. #include "url.h" /* for Curl_safefree() */
  64. #include "multiif.h"
  65. #include "sockaddr.h" /* required for Curl_sockaddr_storage */
  66. #include "inet_ntop.h"
  67. #include "inet_pton.h"
  68. #include "vtls/vtls.h" /* for Curl_ssl_check_cxn() */
  69. #include "progress.h"
  70. #include "warnless.h"
  71. #include "conncache.h"
  72. #include "multihandle.h"
  73. #include "system_win32.h"
  74. /* The last 3 #include files should be in this order */
  75. #include "curl_printf.h"
  76. #include "curl_memory.h"
  77. #include "memdebug.h"
  78. #ifdef __SYMBIAN32__
  79. /* This isn't actually supported under Symbian OS */
  80. #undef SO_NOSIGPIPE
  81. #endif
  82. static bool verifyconnect(curl_socket_t sockfd, int *error);
  83. #if defined(__DragonFly__) || defined(HAVE_WINSOCK_H)
  84. /* DragonFlyBSD and Windows use millisecond units */
  85. #define KEEPALIVE_FACTOR(x) (x *= 1000)
  86. #else
  87. #define KEEPALIVE_FACTOR(x)
  88. #endif
  89. #if defined(HAVE_WINSOCK2_H) && !defined(SIO_KEEPALIVE_VALS)
  90. #define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
  91. struct tcp_keepalive {
  92. u_long onoff;
  93. u_long keepalivetime;
  94. u_long keepaliveinterval;
  95. };
  96. #endif
  97. static void
  98. tcpkeepalive(struct Curl_easy *data,
  99. curl_socket_t sockfd)
  100. {
  101. int optval = data->set.tcp_keepalive?1:0;
  102. /* only set IDLE and INTVL if setting KEEPALIVE is successful */
  103. if(setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE,
  104. (void *)&optval, sizeof(optval)) < 0) {
  105. infof(data, "Failed to set SO_KEEPALIVE on fd %d\n", sockfd);
  106. }
  107. else {
  108. #if defined(SIO_KEEPALIVE_VALS)
  109. struct tcp_keepalive vals;
  110. DWORD dummy;
  111. vals.onoff = 1;
  112. optval = curlx_sltosi(data->set.tcp_keepidle);
  113. KEEPALIVE_FACTOR(optval);
  114. vals.keepalivetime = optval;
  115. optval = curlx_sltosi(data->set.tcp_keepintvl);
  116. KEEPALIVE_FACTOR(optval);
  117. vals.keepaliveinterval = optval;
  118. if(WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, (LPVOID) &vals, sizeof(vals),
  119. NULL, 0, &dummy, NULL, NULL) != 0) {
  120. infof(data, "Failed to set SIO_KEEPALIVE_VALS on fd %d: %d\n",
  121. (int)sockfd, WSAGetLastError());
  122. }
  123. #else
  124. #ifdef TCP_KEEPIDLE
  125. optval = curlx_sltosi(data->set.tcp_keepidle);
  126. KEEPALIVE_FACTOR(optval);
  127. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE,
  128. (void *)&optval, sizeof(optval)) < 0) {
  129. infof(data, "Failed to set TCP_KEEPIDLE on fd %d\n", sockfd);
  130. }
  131. #endif
  132. #ifdef TCP_KEEPINTVL
  133. optval = curlx_sltosi(data->set.tcp_keepintvl);
  134. KEEPALIVE_FACTOR(optval);
  135. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL,
  136. (void *)&optval, sizeof(optval)) < 0) {
  137. infof(data, "Failed to set TCP_KEEPINTVL on fd %d\n", sockfd);
  138. }
  139. #endif
  140. #ifdef TCP_KEEPALIVE
  141. /* Mac OS X style */
  142. optval = curlx_sltosi(data->set.tcp_keepidle);
  143. KEEPALIVE_FACTOR(optval);
  144. if(setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE,
  145. (void *)&optval, sizeof(optval)) < 0) {
  146. infof(data, "Failed to set TCP_KEEPALIVE on fd %d\n", sockfd);
  147. }
  148. #endif
  149. #endif
  150. }
  151. }
  152. static CURLcode
  153. singleipconnect(struct connectdata *conn,
  154. const Curl_addrinfo *ai, /* start connecting to this */
  155. curl_socket_t *sock);
  156. /*
  157. * Curl_timeleft() returns the amount of milliseconds left allowed for the
  158. * transfer/connection. If the value is negative, the timeout time has already
  159. * elapsed.
  160. *
  161. * The start time is stored in progress.t_startsingle - as set with
  162. * Curl_pgrsTime(..., TIMER_STARTSINGLE);
  163. *
  164. * If 'nowp' is non-NULL, it points to the current time.
  165. * 'duringconnect' is FALSE if not during a connect, as then of course the
  166. * connect timeout is not taken into account!
  167. *
  168. * @unittest: 1303
  169. */
  170. timediff_t Curl_timeleft(struct Curl_easy *data,
  171. struct curltime *nowp,
  172. bool duringconnect)
  173. {
  174. int timeout_set = 0;
  175. timediff_t timeout_ms = duringconnect?DEFAULT_CONNECT_TIMEOUT:0;
  176. struct curltime now;
  177. /* if a timeout is set, use the most restrictive one */
  178. if(data->set.timeout > 0)
  179. timeout_set |= 1;
  180. if(duringconnect && (data->set.connecttimeout > 0))
  181. timeout_set |= 2;
  182. switch(timeout_set) {
  183. case 1:
  184. timeout_ms = data->set.timeout;
  185. break;
  186. case 2:
  187. timeout_ms = data->set.connecttimeout;
  188. break;
  189. case 3:
  190. if(data->set.timeout < data->set.connecttimeout)
  191. timeout_ms = data->set.timeout;
  192. else
  193. timeout_ms = data->set.connecttimeout;
  194. break;
  195. default:
  196. /* use the default */
  197. if(!duringconnect)
  198. /* if we're not during connect, there's no default timeout so if we're
  199. at zero we better just return zero and not make it a negative number
  200. by the math below */
  201. return 0;
  202. break;
  203. }
  204. if(!nowp) {
  205. now = Curl_now();
  206. nowp = &now;
  207. }
  208. /* subtract elapsed time */
  209. if(duringconnect)
  210. /* since this most recent connect started */
  211. timeout_ms -= Curl_timediff(*nowp, data->progress.t_startsingle);
  212. else
  213. /* since the entire operation started */
  214. timeout_ms -= Curl_timediff(*nowp, data->progress.t_startop);
  215. if(!timeout_ms)
  216. /* avoid returning 0 as that means no timeout! */
  217. return -1;
  218. return timeout_ms;
  219. }
  220. static CURLcode bindlocal(struct connectdata *conn,
  221. curl_socket_t sockfd, int af, unsigned int scope)
  222. {
  223. struct Curl_easy *data = conn->data;
  224. struct Curl_sockaddr_storage sa;
  225. struct sockaddr *sock = (struct sockaddr *)&sa; /* bind to this address */
  226. curl_socklen_t sizeof_sa = 0; /* size of the data sock points to */
  227. struct sockaddr_in *si4 = (struct sockaddr_in *)&sa;
  228. #ifdef ENABLE_IPV6
  229. struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa;
  230. #endif
  231. struct Curl_dns_entry *h = NULL;
  232. unsigned short port = data->set.localport; /* use this port number, 0 for
  233. "random" */
  234. /* how many port numbers to try to bind to, increasing one at a time */
  235. int portnum = data->set.localportrange;
  236. const char *dev = data->set.str[STRING_DEVICE];
  237. int error;
  238. /*************************************************************
  239. * Select device to bind socket to
  240. *************************************************************/
  241. if(!dev && !port)
  242. /* no local kind of binding was requested */
  243. return CURLE_OK;
  244. memset(&sa, 0, sizeof(struct Curl_sockaddr_storage));
  245. if(dev && (strlen(dev)<255) ) {
  246. char myhost[256] = "";
  247. int done = 0; /* -1 for error, 1 for address found */
  248. bool is_interface = FALSE;
  249. bool is_host = FALSE;
  250. static const char *if_prefix = "if!";
  251. static const char *host_prefix = "host!";
  252. if(strncmp(if_prefix, dev, strlen(if_prefix)) == 0) {
  253. dev += strlen(if_prefix);
  254. is_interface = TRUE;
  255. }
  256. else if(strncmp(host_prefix, dev, strlen(host_prefix)) == 0) {
  257. dev += strlen(host_prefix);
  258. is_host = TRUE;
  259. }
  260. /* interface */
  261. if(!is_host) {
  262. #ifdef SO_BINDTODEVICE
  263. /* I am not sure any other OSs than Linux that provide this feature,
  264. * and at the least I cannot test. --Ben
  265. *
  266. * This feature allows one to tightly bind the local socket to a
  267. * particular interface. This will force even requests to other
  268. * local interfaces to go out the external interface.
  269. *
  270. *
  271. * Only bind to the interface when specified as interface, not just
  272. * as a hostname or ip address.
  273. *
  274. * interface might be a VRF, eg: vrf-blue, which means it cannot be
  275. * converted to an IP address and would fail Curl_if2ip. Simply try
  276. * to use it straight away.
  277. */
  278. if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE,
  279. dev, (curl_socklen_t)strlen(dev) + 1) == 0) {
  280. /* This is typically "errno 1, error: Operation not permitted" if
  281. * you're not running as root or another suitable privileged
  282. * user.
  283. * If it succeeds it means the parameter was a valid interface and
  284. * not an IP address. Return immediately.
  285. */
  286. return CURLE_OK;
  287. }
  288. #endif
  289. switch(Curl_if2ip(af, scope, conn->scope_id, dev,
  290. myhost, sizeof(myhost))) {
  291. case IF2IP_NOT_FOUND:
  292. if(is_interface) {
  293. /* Do not fall back to treating it as a host name */
  294. failf(data, "Couldn't bind to interface '%s'", dev);
  295. return CURLE_INTERFACE_FAILED;
  296. }
  297. break;
  298. case IF2IP_AF_NOT_SUPPORTED:
  299. /* Signal the caller to try another address family if available */
  300. return CURLE_UNSUPPORTED_PROTOCOL;
  301. case IF2IP_FOUND:
  302. is_interface = TRUE;
  303. /*
  304. * We now have the numerical IP address in the 'myhost' buffer
  305. */
  306. infof(data, "Local Interface %s is ip %s using address family %i\n",
  307. dev, myhost, af);
  308. done = 1;
  309. break;
  310. }
  311. }
  312. if(!is_interface) {
  313. /*
  314. * This was not an interface, resolve the name as a host name
  315. * or IP number
  316. *
  317. * Temporarily force name resolution to use only the address type
  318. * of the connection. The resolve functions should really be changed
  319. * to take a type parameter instead.
  320. */
  321. long ipver = conn->ip_version;
  322. int rc;
  323. if(af == AF_INET)
  324. conn->ip_version = CURL_IPRESOLVE_V4;
  325. #ifdef ENABLE_IPV6
  326. else if(af == AF_INET6)
  327. conn->ip_version = CURL_IPRESOLVE_V6;
  328. #endif
  329. rc = Curl_resolv(conn, dev, 0, FALSE, &h);
  330. if(rc == CURLRESOLV_PENDING)
  331. (void)Curl_resolver_wait_resolv(conn, &h);
  332. conn->ip_version = ipver;
  333. if(h) {
  334. /* convert the resolved address, sizeof myhost >= INET_ADDRSTRLEN */
  335. Curl_printable_address(h->addr, myhost, sizeof(myhost));
  336. infof(data, "Name '%s' family %i resolved to '%s' family %i\n",
  337. dev, af, myhost, h->addr->ai_family);
  338. Curl_resolv_unlock(data, h);
  339. done = 1;
  340. }
  341. else {
  342. /*
  343. * provided dev was no interface (or interfaces are not supported
  344. * e.g. solaris) no ip address and no domain we fail here
  345. */
  346. done = -1;
  347. }
  348. }
  349. if(done > 0) {
  350. #ifdef ENABLE_IPV6
  351. /* IPv6 address */
  352. if(af == AF_INET6) {
  353. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  354. char *scope_ptr = strchr(myhost, '%');
  355. if(scope_ptr)
  356. *(scope_ptr++) = 0;
  357. #endif
  358. if(Curl_inet_pton(AF_INET6, myhost, &si6->sin6_addr) > 0) {
  359. si6->sin6_family = AF_INET6;
  360. si6->sin6_port = htons(port);
  361. #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
  362. if(scope_ptr)
  363. /* The "myhost" string either comes from Curl_if2ip or from
  364. Curl_printable_address. The latter returns only numeric scope
  365. IDs and the former returns none at all. So the scope ID, if
  366. present, is known to be numeric */
  367. si6->sin6_scope_id = atoi(scope_ptr);
  368. #endif
  369. }
  370. sizeof_sa = sizeof(struct sockaddr_in6);
  371. }
  372. else
  373. #endif
  374. /* IPv4 address */
  375. if((af == AF_INET) &&
  376. (Curl_inet_pton(AF_INET, myhost, &si4->sin_addr) > 0)) {
  377. si4->sin_family = AF_INET;
  378. si4->sin_port = htons(port);
  379. sizeof_sa = sizeof(struct sockaddr_in);
  380. }
  381. }
  382. if(done < 1) {
  383. /* errorbuf is set false so failf will overwrite any message already in
  384. the error buffer, so the user receives this error message instead of a
  385. generic resolve error. */
  386. data->state.errorbuf = FALSE;
  387. failf(data, "Couldn't bind to '%s'", dev);
  388. return CURLE_INTERFACE_FAILED;
  389. }
  390. }
  391. else {
  392. /* no device was given, prepare sa to match af's needs */
  393. #ifdef ENABLE_IPV6
  394. if(af == AF_INET6) {
  395. si6->sin6_family = AF_INET6;
  396. si6->sin6_port = htons(port);
  397. sizeof_sa = sizeof(struct sockaddr_in6);
  398. }
  399. else
  400. #endif
  401. if(af == AF_INET) {
  402. si4->sin_family = AF_INET;
  403. si4->sin_port = htons(port);
  404. sizeof_sa = sizeof(struct sockaddr_in);
  405. }
  406. }
  407. for(;;) {
  408. if(bind(sockfd, sock, sizeof_sa) >= 0) {
  409. /* we succeeded to bind */
  410. struct Curl_sockaddr_storage add;
  411. curl_socklen_t size = sizeof(add);
  412. memset(&add, 0, sizeof(struct Curl_sockaddr_storage));
  413. if(getsockname(sockfd, (struct sockaddr *) &add, &size) < 0) {
  414. char buffer[STRERROR_LEN];
  415. data->state.os_errno = error = SOCKERRNO;
  416. failf(data, "getsockname() failed with errno %d: %s",
  417. error, Curl_strerror(error, buffer, sizeof(buffer)));
  418. return CURLE_INTERFACE_FAILED;
  419. }
  420. infof(data, "Local port: %hu\n", port);
  421. conn->bits.bound = TRUE;
  422. return CURLE_OK;
  423. }
  424. if(--portnum > 0) {
  425. infof(data, "Bind to local port %hu failed, trying next\n", port);
  426. port++; /* try next port */
  427. /* We re-use/clobber the port variable here below */
  428. if(sock->sa_family == AF_INET)
  429. si4->sin_port = ntohs(port);
  430. #ifdef ENABLE_IPV6
  431. else
  432. si6->sin6_port = ntohs(port);
  433. #endif
  434. }
  435. else
  436. break;
  437. }
  438. {
  439. char buffer[STRERROR_LEN];
  440. data->state.os_errno = error = SOCKERRNO;
  441. failf(data, "bind failed with errno %d: %s",
  442. error, Curl_strerror(error, buffer, sizeof(buffer)));
  443. }
  444. return CURLE_INTERFACE_FAILED;
  445. }
  446. /*
  447. * verifyconnect() returns TRUE if the connect really has happened.
  448. */
  449. static bool verifyconnect(curl_socket_t sockfd, int *error)
  450. {
  451. bool rc = TRUE;
  452. #ifdef SO_ERROR
  453. int err = 0;
  454. curl_socklen_t errSize = sizeof(err);
  455. #ifdef WIN32
  456. /*
  457. * In October 2003 we effectively nullified this function on Windows due to
  458. * problems with it using all CPU in multi-threaded cases.
  459. *
  460. * In May 2004, we bring it back to offer more info back on connect failures.
  461. * Gisle Vanem could reproduce the former problems with this function, but
  462. * could avoid them by adding this SleepEx() call below:
  463. *
  464. * "I don't have Rational Quantify, but the hint from his post was
  465. * ntdll::NtRemoveIoCompletion(). So I'd assume the SleepEx (or maybe
  466. * just Sleep(0) would be enough?) would release whatever
  467. * mutex/critical-section the ntdll call is waiting on.
  468. *
  469. * Someone got to verify this on Win-NT 4.0, 2000."
  470. */
  471. #ifdef _WIN32_WCE
  472. Sleep(0);
  473. #else
  474. SleepEx(0, FALSE);
  475. #endif
  476. #endif
  477. if(0 != getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&err, &errSize))
  478. err = SOCKERRNO;
  479. #ifdef _WIN32_WCE
  480. /* Old WinCE versions don't support SO_ERROR */
  481. if(WSAENOPROTOOPT == err) {
  482. SET_SOCKERRNO(0);
  483. err = 0;
  484. }
  485. #endif
  486. #if defined(EBADIOCTL) && defined(__minix)
  487. /* Minix 3.1.x doesn't support getsockopt on UDP sockets */
  488. if(EBADIOCTL == err) {
  489. SET_SOCKERRNO(0);
  490. err = 0;
  491. }
  492. #endif
  493. if((0 == err) || (EISCONN == err))
  494. /* we are connected, awesome! */
  495. rc = TRUE;
  496. else
  497. /* This wasn't a successful connect */
  498. rc = FALSE;
  499. if(error)
  500. *error = err;
  501. #else
  502. (void)sockfd;
  503. if(error)
  504. *error = SOCKERRNO;
  505. #endif
  506. return rc;
  507. }
  508. /* Used within the multi interface. Try next IP address, return TRUE if no
  509. more address exists or error */
  510. static CURLcode trynextip(struct connectdata *conn,
  511. int sockindex,
  512. int tempindex)
  513. {
  514. const int other = tempindex ^ 1;
  515. CURLcode result = CURLE_COULDNT_CONNECT;
  516. /* First clean up after the failed socket.
  517. Don't close it yet to ensure that the next IP's socket gets a different
  518. file descriptor, which can prevent bugs when the curl_multi_socket_action
  519. interface is used with certain select() replacements such as kqueue. */
  520. curl_socket_t fd_to_close = conn->tempsock[tempindex];
  521. conn->tempsock[tempindex] = CURL_SOCKET_BAD;
  522. if(sockindex == FIRSTSOCKET) {
  523. Curl_addrinfo *ai = NULL;
  524. int family = AF_UNSPEC;
  525. if(conn->tempaddr[tempindex]) {
  526. /* find next address in the same protocol family */
  527. family = conn->tempaddr[tempindex]->ai_family;
  528. ai = conn->tempaddr[tempindex]->ai_next;
  529. }
  530. #ifdef ENABLE_IPV6
  531. else if(conn->tempaddr[0]) {
  532. /* happy eyeballs - try the other protocol family */
  533. int firstfamily = conn->tempaddr[0]->ai_family;
  534. family = (firstfamily == AF_INET) ? AF_INET6 : AF_INET;
  535. ai = conn->tempaddr[0]->ai_next;
  536. }
  537. #endif
  538. while(ai) {
  539. if(conn->tempaddr[other]) {
  540. /* we can safely skip addresses of the other protocol family */
  541. while(ai && ai->ai_family != family)
  542. ai = ai->ai_next;
  543. }
  544. if(ai) {
  545. result = singleipconnect(conn, ai, &conn->tempsock[tempindex]);
  546. if(result == CURLE_COULDNT_CONNECT) {
  547. ai = ai->ai_next;
  548. continue;
  549. }
  550. conn->tempaddr[tempindex] = ai;
  551. }
  552. break;
  553. }
  554. }
  555. if(fd_to_close != CURL_SOCKET_BAD)
  556. Curl_closesocket(conn, fd_to_close);
  557. return result;
  558. }
  559. /* Copies connection info into the session handle to make it available
  560. when the session handle is no longer associated with a connection. */
  561. void Curl_persistconninfo(struct connectdata *conn)
  562. {
  563. memcpy(conn->data->info.conn_primary_ip, conn->primary_ip, MAX_IPADR_LEN);
  564. memcpy(conn->data->info.conn_local_ip, conn->local_ip, MAX_IPADR_LEN);
  565. conn->data->info.conn_scheme = conn->handler->scheme;
  566. conn->data->info.conn_protocol = conn->handler->protocol;
  567. conn->data->info.conn_primary_port = conn->primary_port;
  568. conn->data->info.conn_local_port = conn->local_port;
  569. }
  570. UNITTEST bool getaddressinfo(struct sockaddr *sa, char *addr,
  571. long *port);
  572. /* retrieves ip address and port from a sockaddr structure.
  573. note it calls Curl_inet_ntop which sets errno on fail, not SOCKERRNO. */
  574. UNITTEST bool getaddressinfo(struct sockaddr *sa, char *addr,
  575. long *port)
  576. {
  577. unsigned short us_port;
  578. struct sockaddr_in *si = NULL;
  579. #ifdef ENABLE_IPV6
  580. struct sockaddr_in6 *si6 = NULL;
  581. #endif
  582. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  583. struct sockaddr_un *su = NULL;
  584. #endif
  585. switch(sa->sa_family) {
  586. case AF_INET:
  587. si = (struct sockaddr_in *)(void *) sa;
  588. if(Curl_inet_ntop(sa->sa_family, &si->sin_addr,
  589. addr, MAX_IPADR_LEN)) {
  590. us_port = ntohs(si->sin_port);
  591. *port = us_port;
  592. return TRUE;
  593. }
  594. break;
  595. #ifdef ENABLE_IPV6
  596. case AF_INET6:
  597. si6 = (struct sockaddr_in6 *)(void *) sa;
  598. if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr,
  599. addr, MAX_IPADR_LEN)) {
  600. us_port = ntohs(si6->sin6_port);
  601. *port = us_port;
  602. return TRUE;
  603. }
  604. break;
  605. #endif
  606. #if defined(HAVE_SYS_UN_H) && defined(AF_UNIX)
  607. case AF_UNIX:
  608. su = (struct sockaddr_un*)sa;
  609. msnprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path);
  610. *port = 0;
  611. return TRUE;
  612. #endif
  613. default:
  614. break;
  615. }
  616. addr[0] = '\0';
  617. *port = 0;
  618. errno = EAFNOSUPPORT;
  619. return FALSE;
  620. }
  621. /* retrieves the start/end point information of a socket of an established
  622. connection */
  623. void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
  624. {
  625. curl_socklen_t len;
  626. struct Curl_sockaddr_storage ssrem;
  627. struct Curl_sockaddr_storage ssloc;
  628. struct Curl_easy *data = conn->data;
  629. if(conn->socktype == SOCK_DGRAM)
  630. /* there's no connection! */
  631. return;
  632. if(!conn->bits.reuse && !conn->bits.tcp_fastopen) {
  633. char buffer[STRERROR_LEN];
  634. len = sizeof(struct Curl_sockaddr_storage);
  635. if(getpeername(sockfd, (struct sockaddr*) &ssrem, &len)) {
  636. int error = SOCKERRNO;
  637. failf(data, "getpeername() failed with errno %d: %s",
  638. error, Curl_strerror(error, buffer, sizeof(buffer)));
  639. return;
  640. }
  641. len = sizeof(struct Curl_sockaddr_storage);
  642. memset(&ssloc, 0, sizeof(ssloc));
  643. if(getsockname(sockfd, (struct sockaddr*) &ssloc, &len)) {
  644. int error = SOCKERRNO;
  645. failf(data, "getsockname() failed with errno %d: %s",
  646. error, Curl_strerror(error, buffer, sizeof(buffer)));
  647. return;
  648. }
  649. if(!getaddressinfo((struct sockaddr*)&ssrem,
  650. conn->primary_ip, &conn->primary_port)) {
  651. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  652. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  653. return;
  654. }
  655. memcpy(conn->ip_addr_str, conn->primary_ip, MAX_IPADR_LEN);
  656. if(!getaddressinfo((struct sockaddr*)&ssloc,
  657. conn->local_ip, &conn->local_port)) {
  658. failf(data, "ssloc inet_ntop() failed with errno %d: %s",
  659. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  660. return;
  661. }
  662. }
  663. /* persist connection info in session handle */
  664. Curl_persistconninfo(conn);
  665. }
  666. /*
  667. * Curl_is_connected() checks if the socket has connected.
  668. */
  669. CURLcode Curl_is_connected(struct connectdata *conn,
  670. int sockindex,
  671. bool *connected)
  672. {
  673. struct Curl_easy *data = conn->data;
  674. CURLcode result = CURLE_OK;
  675. timediff_t allow;
  676. int error = 0;
  677. struct curltime now;
  678. int rc;
  679. int i;
  680. DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);
  681. *connected = FALSE; /* a very negative world view is best */
  682. if(conn->bits.tcpconnect[sockindex]) {
  683. /* we are connected already! */
  684. *connected = TRUE;
  685. return CURLE_OK;
  686. }
  687. now = Curl_now();
  688. /* figure out how long time we have left to connect */
  689. allow = Curl_timeleft(data, &now, TRUE);
  690. if(allow < 0) {
  691. /* time-out, bail out, go home */
  692. failf(data, "Connection time-out");
  693. return CURLE_OPERATION_TIMEDOUT;
  694. }
  695. for(i = 0; i<2; i++) {
  696. const int other = i ^ 1;
  697. if(conn->tempsock[i] == CURL_SOCKET_BAD)
  698. continue;
  699. #ifdef mpeix
  700. /* Call this function once now, and ignore the results. We do this to
  701. "clear" the error state on the socket so that we can later read it
  702. reliably. This is reported necessary on the MPE/iX operating system. */
  703. (void)verifyconnect(conn->tempsock[i], NULL);
  704. #endif
  705. /* check socket for connect */
  706. rc = SOCKET_WRITABLE(conn->tempsock[i], 0);
  707. if(rc == 0) { /* no connection yet */
  708. error = 0;
  709. if(Curl_timediff(now, conn->connecttime) >= conn->timeoutms_per_addr) {
  710. infof(data, "After %ldms connect time, move on!\n",
  711. conn->timeoutms_per_addr);
  712. error = ETIMEDOUT;
  713. }
  714. /* should we try another protocol family? */
  715. if(i == 0 && conn->tempaddr[1] == NULL &&
  716. (Curl_timediff(now, conn->connecttime) >=
  717. data->set.happy_eyeballs_timeout)) {
  718. trynextip(conn, sockindex, 1);
  719. }
  720. }
  721. else if(rc == CURL_CSELECT_OUT || conn->bits.tcp_fastopen) {
  722. if(verifyconnect(conn->tempsock[i], &error)) {
  723. /* we are connected with TCP, awesome! */
  724. /* use this socket from now on */
  725. conn->sock[sockindex] = conn->tempsock[i];
  726. conn->ip_addr = conn->tempaddr[i];
  727. conn->tempsock[i] = CURL_SOCKET_BAD;
  728. #ifdef ENABLE_IPV6
  729. conn->bits.ipv6 = (conn->ip_addr->ai_family == AF_INET6)?TRUE:FALSE;
  730. #endif
  731. /* close the other socket, if open */
  732. if(conn->tempsock[other] != CURL_SOCKET_BAD) {
  733. Curl_closesocket(conn, conn->tempsock[other]);
  734. conn->tempsock[other] = CURL_SOCKET_BAD;
  735. }
  736. /* see if we need to do any proxy magic first once we connected */
  737. result = Curl_connected_proxy(conn, sockindex);
  738. if(result)
  739. return result;
  740. conn->bits.tcpconnect[sockindex] = TRUE;
  741. *connected = TRUE;
  742. if(sockindex == FIRSTSOCKET)
  743. Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
  744. Curl_updateconninfo(conn, conn->sock[sockindex]);
  745. Curl_verboseconnect(conn);
  746. return CURLE_OK;
  747. }
  748. infof(data, "Connection failed\n");
  749. }
  750. else if(rc & CURL_CSELECT_ERR)
  751. (void)verifyconnect(conn->tempsock[i], &error);
  752. /*
  753. * The connection failed here, we should attempt to connect to the "next
  754. * address" for the given host. But first remember the latest error.
  755. */
  756. if(error) {
  757. data->state.os_errno = error;
  758. SET_SOCKERRNO(error);
  759. if(conn->tempaddr[i]) {
  760. CURLcode status;
  761. char ipaddress[MAX_IPADR_LEN];
  762. char buffer[STRERROR_LEN];
  763. Curl_printable_address(conn->tempaddr[i], ipaddress, MAX_IPADR_LEN);
  764. infof(data, "connect to %s port %ld failed: %s\n",
  765. ipaddress, conn->port,
  766. Curl_strerror(error, buffer, sizeof(buffer)));
  767. conn->timeoutms_per_addr = conn->tempaddr[i]->ai_next == NULL ?
  768. allow : allow / 2;
  769. status = trynextip(conn, sockindex, i);
  770. if(status != CURLE_COULDNT_CONNECT
  771. || conn->tempsock[other] == CURL_SOCKET_BAD)
  772. /* the last attempt failed and no other sockets remain open */
  773. result = status;
  774. }
  775. }
  776. }
  777. if(result) {
  778. /* no more addresses to try */
  779. const char *hostname;
  780. char buffer[STRERROR_LEN];
  781. /* if the first address family runs out of addresses to try before
  782. the happy eyeball timeout, go ahead and try the next family now */
  783. if(conn->tempaddr[1] == NULL) {
  784. result = trynextip(conn, sockindex, 1);
  785. if(!result)
  786. return result;
  787. }
  788. if(conn->bits.socksproxy)
  789. hostname = conn->socks_proxy.host.name;
  790. else if(conn->bits.httpproxy)
  791. hostname = conn->http_proxy.host.name;
  792. else if(conn->bits.conn_to_host)
  793. hostname = conn->conn_to_host.name;
  794. else
  795. hostname = conn->host.name;
  796. failf(data, "Failed to connect to %s port %ld: %s",
  797. hostname, conn->port,
  798. Curl_strerror(error, buffer, sizeof(buffer)));
  799. }
  800. return result;
  801. }
  802. static void tcpnodelay(struct connectdata *conn, curl_socket_t sockfd)
  803. {
  804. #if defined(TCP_NODELAY)
  805. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  806. struct Curl_easy *data = conn->data;
  807. #endif
  808. curl_socklen_t onoff = (curl_socklen_t) 1;
  809. int level = IPPROTO_TCP;
  810. char buffer[STRERROR_LEN];
  811. #if defined(CURL_DISABLE_VERBOSE_STRINGS)
  812. (void) conn;
  813. #endif
  814. if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
  815. sizeof(onoff)) < 0)
  816. infof(data, "Could not set TCP_NODELAY: %s\n",
  817. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  818. else
  819. infof(data, "TCP_NODELAY set\n");
  820. #else
  821. (void)conn;
  822. (void)sockfd;
  823. #endif
  824. }
  825. #ifdef SO_NOSIGPIPE
  826. /* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
  827. sending data to a dead peer (instead of relying on the 4th argument to send
  828. being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
  829. systems? */
  830. static void nosigpipe(struct connectdata *conn,
  831. curl_socket_t sockfd)
  832. {
  833. struct Curl_easy *data = conn->data;
  834. int onoff = 1;
  835. if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
  836. sizeof(onoff)) < 0) {
  837. char buffer[STRERROR_LEN];
  838. infof(data, "Could not set SO_NOSIGPIPE: %s\n",
  839. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  840. }
  841. }
  842. #else
  843. #define nosigpipe(x,y) Curl_nop_stmt
  844. #endif
  845. #ifdef USE_WINSOCK
  846. /* When you run a program that uses the Windows Sockets API, you may
  847. experience slow performance when you copy data to a TCP server.
  848. https://support.microsoft.com/kb/823764
  849. Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
  850. Buffer Size
  851. The problem described in this knowledge-base is applied only to pre-Vista
  852. Windows. Following function trying to detect OS version and skips
  853. SO_SNDBUF adjustment for Windows Vista and above.
  854. */
  855. #define DETECT_OS_NONE 0
  856. #define DETECT_OS_PREVISTA 1
  857. #define DETECT_OS_VISTA_OR_LATER 2
  858. void Curl_sndbufset(curl_socket_t sockfd)
  859. {
  860. int val = CURL_MAX_WRITE_SIZE + 32;
  861. int curval = 0;
  862. int curlen = sizeof(curval);
  863. static int detectOsState = DETECT_OS_NONE;
  864. if(detectOsState == DETECT_OS_NONE) {
  865. if(Curl_verify_windows_version(6, 0, PLATFORM_WINNT,
  866. VERSION_GREATER_THAN_EQUAL))
  867. detectOsState = DETECT_OS_VISTA_OR_LATER;
  868. else
  869. detectOsState = DETECT_OS_PREVISTA;
  870. }
  871. if(detectOsState == DETECT_OS_VISTA_OR_LATER)
  872. return;
  873. if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
  874. if(curval > val)
  875. return;
  876. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
  877. }
  878. #endif
  879. /*
  880. * singleipconnect()
  881. *
  882. * Note that even on connect fail it returns CURLE_OK, but with 'sock' set to
  883. * CURL_SOCKET_BAD. Other errors will however return proper errors.
  884. *
  885. * singleipconnect() connects to the given IP only, and it may return without
  886. * having connected.
  887. */
  888. static CURLcode singleipconnect(struct connectdata *conn,
  889. const Curl_addrinfo *ai,
  890. curl_socket_t *sockp)
  891. {
  892. struct Curl_sockaddr_ex addr;
  893. int rc = -1;
  894. int error = 0;
  895. bool isconnected = FALSE;
  896. struct Curl_easy *data = conn->data;
  897. curl_socket_t sockfd;
  898. CURLcode result;
  899. char ipaddress[MAX_IPADR_LEN];
  900. long port;
  901. bool is_tcp;
  902. #ifdef TCP_FASTOPEN_CONNECT
  903. int optval = 1;
  904. #endif
  905. char buffer[STRERROR_LEN];
  906. *sockp = CURL_SOCKET_BAD;
  907. result = Curl_socket(conn, ai, &addr, &sockfd);
  908. if(result)
  909. /* Failed to create the socket, but still return OK since we signal the
  910. lack of socket as well. This allows the parent function to keep looping
  911. over alternative addresses/socket families etc. */
  912. return CURLE_OK;
  913. /* store remote address and port used in this connection attempt */
  914. if(!getaddressinfo((struct sockaddr*)&addr.sa_addr,
  915. ipaddress, &port)) {
  916. /* malformed address or bug in inet_ntop, try next address */
  917. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  918. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  919. Curl_closesocket(conn, sockfd);
  920. return CURLE_OK;
  921. }
  922. infof(data, " Trying %s:%ld...\n", ipaddress, port);
  923. #ifdef ENABLE_IPV6
  924. is_tcp = (addr.family == AF_INET || addr.family == AF_INET6) &&
  925. addr.socktype == SOCK_STREAM;
  926. #else
  927. is_tcp = (addr.family == AF_INET) && addr.socktype == SOCK_STREAM;
  928. #endif
  929. if(is_tcp && data->set.tcp_nodelay)
  930. tcpnodelay(conn, sockfd);
  931. nosigpipe(conn, sockfd);
  932. Curl_sndbufset(sockfd);
  933. if(is_tcp && data->set.tcp_keepalive)
  934. tcpkeepalive(data, sockfd);
  935. if(data->set.fsockopt) {
  936. /* activate callback for setting socket options */
  937. Curl_set_in_callback(data, true);
  938. error = data->set.fsockopt(data->set.sockopt_client,
  939. sockfd,
  940. CURLSOCKTYPE_IPCXN);
  941. Curl_set_in_callback(data, false);
  942. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  943. isconnected = TRUE;
  944. else if(error) {
  945. Curl_closesocket(conn, sockfd); /* close the socket and bail out */
  946. return CURLE_ABORTED_BY_CALLBACK;
  947. }
  948. }
  949. /* possibly bind the local end to an IP, interface or port */
  950. if(addr.family == AF_INET
  951. #ifdef ENABLE_IPV6
  952. || addr.family == AF_INET6
  953. #endif
  954. ) {
  955. result = bindlocal(conn, sockfd, addr.family,
  956. Curl_ipv6_scope((struct sockaddr*)&addr.sa_addr));
  957. if(result) {
  958. Curl_closesocket(conn, sockfd); /* close socket and bail out */
  959. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  960. /* The address family is not supported on this interface.
  961. We can continue trying addresses */
  962. return CURLE_COULDNT_CONNECT;
  963. }
  964. return result;
  965. }
  966. }
  967. /* set socket non-blocking */
  968. (void)curlx_nonblock(sockfd, TRUE);
  969. conn->connecttime = Curl_now();
  970. if(conn->num_addr > 1)
  971. Curl_expire(data, conn->timeoutms_per_addr, EXPIRE_DNS_PER_NAME);
  972. /* Connect TCP sockets, bind UDP */
  973. if(!isconnected && (conn->socktype == SOCK_STREAM)) {
  974. if(conn->bits.tcp_fastopen) {
  975. #if defined(CONNECT_DATA_IDEMPOTENT) /* Darwin */
  976. # if defined(HAVE_BUILTIN_AVAILABLE)
  977. /* while connectx function is available since macOS 10.11 / iOS 9,
  978. it did not have the interface declared correctly until
  979. Xcode 9 / macOS SDK 10.13 */
  980. if(__builtin_available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)) {
  981. sa_endpoints_t endpoints;
  982. endpoints.sae_srcif = 0;
  983. endpoints.sae_srcaddr = NULL;
  984. endpoints.sae_srcaddrlen = 0;
  985. endpoints.sae_dstaddr = &addr.sa_addr;
  986. endpoints.sae_dstaddrlen = addr.addrlen;
  987. rc = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY,
  988. CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
  989. NULL, 0, NULL, NULL);
  990. }
  991. else {
  992. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  993. }
  994. # else
  995. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  996. # endif /* HAVE_BUILTIN_AVAILABLE */
  997. #elif defined(TCP_FASTOPEN_CONNECT) /* Linux >= 4.11 */
  998. if(setsockopt(sockfd, IPPROTO_TCP, TCP_FASTOPEN_CONNECT,
  999. (void *)&optval, sizeof(optval)) < 0)
  1000. infof(data, "Failed to enable TCP Fast Open on fd %d\n", sockfd);
  1001. else
  1002. infof(data, "TCP_FASTOPEN_CONNECT set\n");
  1003. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  1004. #elif defined(MSG_FASTOPEN) /* old Linux */
  1005. if(conn->given->flags & PROTOPT_SSL)
  1006. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  1007. else
  1008. rc = 0; /* Do nothing */
  1009. #endif
  1010. }
  1011. else {
  1012. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  1013. }
  1014. if(-1 == rc)
  1015. error = SOCKERRNO;
  1016. }
  1017. else {
  1018. *sockp = sockfd;
  1019. return CURLE_OK;
  1020. }
  1021. if(-1 == rc) {
  1022. switch(error) {
  1023. case EINPROGRESS:
  1024. case EWOULDBLOCK:
  1025. #if defined(EAGAIN)
  1026. #if (EAGAIN) != (EWOULDBLOCK)
  1027. /* On some platforms EAGAIN and EWOULDBLOCK are the
  1028. * same value, and on others they are different, hence
  1029. * the odd #if
  1030. */
  1031. case EAGAIN:
  1032. #endif
  1033. #endif
  1034. result = CURLE_OK;
  1035. break;
  1036. default:
  1037. /* unknown error, fallthrough and try another address! */
  1038. infof(data, "Immediate connect fail for %s: %s\n",
  1039. ipaddress, Curl_strerror(error, buffer, sizeof(buffer)));
  1040. data->state.os_errno = error;
  1041. /* connect failed */
  1042. Curl_closesocket(conn, sockfd);
  1043. result = CURLE_COULDNT_CONNECT;
  1044. }
  1045. }
  1046. if(!result)
  1047. *sockp = sockfd;
  1048. return result;
  1049. }
  1050. /*
  1051. * TCP connect to the given host with timeout, proxy or remote doesn't matter.
  1052. * There might be more than one IP address to try out. Fill in the passed
  1053. * pointer with the connected socket.
  1054. */
  1055. CURLcode Curl_connecthost(struct connectdata *conn, /* context */
  1056. const struct Curl_dns_entry *remotehost)
  1057. {
  1058. struct Curl_easy *data = conn->data;
  1059. struct curltime before = Curl_now();
  1060. CURLcode result = CURLE_COULDNT_CONNECT;
  1061. timediff_t timeout_ms = Curl_timeleft(data, &before, TRUE);
  1062. if(timeout_ms < 0) {
  1063. /* a precaution, no need to continue if time already is up */
  1064. failf(data, "Connection time-out");
  1065. return CURLE_OPERATION_TIMEDOUT;
  1066. }
  1067. conn->num_addr = Curl_num_addresses(remotehost->addr);
  1068. conn->tempaddr[0] = remotehost->addr;
  1069. conn->tempaddr[1] = NULL;
  1070. conn->tempsock[0] = CURL_SOCKET_BAD;
  1071. conn->tempsock[1] = CURL_SOCKET_BAD;
  1072. /* Max time for the next connection attempt */
  1073. conn->timeoutms_per_addr =
  1074. conn->tempaddr[0]->ai_next == NULL ? timeout_ms : timeout_ms / 2;
  1075. /* start connecting to first IP */
  1076. while(conn->tempaddr[0]) {
  1077. result = singleipconnect(conn, conn->tempaddr[0], &(conn->tempsock[0]));
  1078. if(!result)
  1079. break;
  1080. conn->tempaddr[0] = conn->tempaddr[0]->ai_next;
  1081. }
  1082. if(conn->tempsock[0] == CURL_SOCKET_BAD) {
  1083. if(!result)
  1084. result = CURLE_COULDNT_CONNECT;
  1085. return result;
  1086. }
  1087. data->info.numconnects++; /* to track the number of connections made */
  1088. Curl_expire(conn->data, data->set.happy_eyeballs_timeout,
  1089. EXPIRE_HAPPY_EYEBALLS);
  1090. return CURLE_OK;
  1091. }
  1092. struct connfind {
  1093. struct connectdata *tofind;
  1094. bool found;
  1095. };
  1096. static int conn_is_conn(struct connectdata *conn, void *param)
  1097. {
  1098. struct connfind *f = (struct connfind *)param;
  1099. if(conn == f->tofind) {
  1100. f->found = TRUE;
  1101. return 1;
  1102. }
  1103. return 0;
  1104. }
  1105. /*
  1106. * Used to extract socket and connectdata struct for the most recent
  1107. * transfer on the given Curl_easy.
  1108. *
  1109. * The returned socket will be CURL_SOCKET_BAD in case of failure!
  1110. */
  1111. curl_socket_t Curl_getconnectinfo(struct Curl_easy *data,
  1112. struct connectdata **connp)
  1113. {
  1114. DEBUGASSERT(data);
  1115. /* this works for an easy handle:
  1116. * - that has been used for curl_easy_perform()
  1117. * - that is associated with a multi handle, and whose connection
  1118. * was detached with CURLOPT_CONNECT_ONLY
  1119. */
  1120. if(data->state.lastconnect && (data->multi_easy || data->multi)) {
  1121. struct connectdata *c = data->state.lastconnect;
  1122. struct connfind find;
  1123. find.tofind = data->state.lastconnect;
  1124. find.found = FALSE;
  1125. Curl_conncache_foreach(data, data->multi_easy?
  1126. &data->multi_easy->conn_cache:
  1127. &data->multi->conn_cache, &find, conn_is_conn);
  1128. if(!find.found) {
  1129. data->state.lastconnect = NULL;
  1130. return CURL_SOCKET_BAD;
  1131. }
  1132. if(connp) {
  1133. /* only store this if the caller cares for it */
  1134. *connp = c;
  1135. c->data = data;
  1136. }
  1137. return c->sock[FIRSTSOCKET];
  1138. }
  1139. else
  1140. return CURL_SOCKET_BAD;
  1141. }
  1142. /*
  1143. * Check if a connection seems to be alive.
  1144. */
  1145. bool Curl_connalive(struct connectdata *conn)
  1146. {
  1147. /* First determine if ssl */
  1148. if(conn->ssl[FIRSTSOCKET].use) {
  1149. /* use the SSL context */
  1150. if(!Curl_ssl_check_cxn(conn))
  1151. return false; /* FIN received */
  1152. }
  1153. /* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */
  1154. #ifdef MSG_PEEK
  1155. else if(conn->sock[FIRSTSOCKET] == CURL_SOCKET_BAD)
  1156. return false;
  1157. else {
  1158. /* use the socket */
  1159. char buf;
  1160. if(recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
  1161. (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK) == 0) {
  1162. return false; /* FIN received */
  1163. }
  1164. }
  1165. #endif
  1166. return true;
  1167. }
  1168. /*
  1169. * Close a socket.
  1170. *
  1171. * 'conn' can be NULL, beware!
  1172. */
  1173. int Curl_closesocket(struct connectdata *conn,
  1174. curl_socket_t sock)
  1175. {
  1176. if(conn && conn->fclosesocket) {
  1177. if((sock == conn->sock[SECONDARYSOCKET]) &&
  1178. conn->sock_accepted[SECONDARYSOCKET])
  1179. /* if this socket matches the second socket, and that was created with
  1180. accept, then we MUST NOT call the callback but clear the accepted
  1181. status */
  1182. conn->sock_accepted[SECONDARYSOCKET] = FALSE;
  1183. else {
  1184. int rc;
  1185. Curl_multi_closed(conn->data, sock);
  1186. Curl_set_in_callback(conn->data, true);
  1187. rc = conn->fclosesocket(conn->closesocket_client, sock);
  1188. Curl_set_in_callback(conn->data, false);
  1189. return rc;
  1190. }
  1191. }
  1192. if(conn)
  1193. /* tell the multi-socket code about this */
  1194. Curl_multi_closed(conn->data, sock);
  1195. sclose(sock);
  1196. return 0;
  1197. }
  1198. /*
  1199. * Create a socket based on info from 'conn' and 'ai'.
  1200. *
  1201. * 'addr' should be a pointer to the correct struct to get data back, or NULL.
  1202. * 'sockfd' must be a pointer to a socket descriptor.
  1203. *
  1204. * If the open socket callback is set, used that!
  1205. *
  1206. */
  1207. CURLcode Curl_socket(struct connectdata *conn,
  1208. const Curl_addrinfo *ai,
  1209. struct Curl_sockaddr_ex *addr,
  1210. curl_socket_t *sockfd)
  1211. {
  1212. struct Curl_easy *data = conn->data;
  1213. struct Curl_sockaddr_ex dummy;
  1214. if(!addr)
  1215. /* if the caller doesn't want info back, use a local temp copy */
  1216. addr = &dummy;
  1217. /*
  1218. * The Curl_sockaddr_ex structure is basically libcurl's external API
  1219. * curl_sockaddr structure with enough space available to directly hold
  1220. * any protocol-specific address structures. The variable declared here
  1221. * will be used to pass / receive data to/from the fopensocket callback
  1222. * if this has been set, before that, it is initialized from parameters.
  1223. */
  1224. addr->family = ai->ai_family;
  1225. addr->socktype = conn->socktype;
  1226. addr->protocol = conn->socktype == SOCK_DGRAM?IPPROTO_UDP:ai->ai_protocol;
  1227. addr->addrlen = ai->ai_addrlen;
  1228. if(addr->addrlen > sizeof(struct Curl_sockaddr_storage))
  1229. addr->addrlen = sizeof(struct Curl_sockaddr_storage);
  1230. memcpy(&addr->sa_addr, ai->ai_addr, addr->addrlen);
  1231. if(data->set.fopensocket) {
  1232. /*
  1233. * If the opensocket callback is set, all the destination address
  1234. * information is passed to the callback. Depending on this information the
  1235. * callback may opt to abort the connection, this is indicated returning
  1236. * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
  1237. * the callback returns a valid socket the destination address information
  1238. * might have been changed and this 'new' address will actually be used
  1239. * here to connect.
  1240. */
  1241. Curl_set_in_callback(data, true);
  1242. *sockfd = data->set.fopensocket(data->set.opensocket_client,
  1243. CURLSOCKTYPE_IPCXN,
  1244. (struct curl_sockaddr *)addr);
  1245. Curl_set_in_callback(data, false);
  1246. }
  1247. else
  1248. /* opensocket callback not set, so simply create the socket now */
  1249. *sockfd = socket(addr->family, addr->socktype, addr->protocol);
  1250. if(*sockfd == CURL_SOCKET_BAD)
  1251. /* no socket, no connection */
  1252. return CURLE_COULDNT_CONNECT;
  1253. #if defined(ENABLE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
  1254. if(conn->scope_id && (addr->family == AF_INET6)) {
  1255. struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
  1256. sa6->sin6_scope_id = conn->scope_id;
  1257. }
  1258. #endif
  1259. return CURLE_OK;
  1260. }
  1261. /*
  1262. * Curl_conncontrol() marks streams or connection for closure.
  1263. */
  1264. void Curl_conncontrol(struct connectdata *conn,
  1265. int ctrl /* see defines in header */
  1266. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  1267. , const char *reason
  1268. #endif
  1269. )
  1270. {
  1271. /* close if a connection, or a stream that isn't multiplexed */
  1272. bool closeit = (ctrl == CONNCTRL_CONNECTION) ||
  1273. ((ctrl == CONNCTRL_STREAM) && !(conn->handler->flags & PROTOPT_STREAM));
  1274. if((ctrl == CONNCTRL_STREAM) &&
  1275. (conn->handler->flags & PROTOPT_STREAM))
  1276. DEBUGF(infof(conn->data, "Kill stream: %s\n", reason));
  1277. else if((bit)closeit != conn->bits.close) {
  1278. DEBUGF(infof(conn->data, "Marked for [%s]: %s\n",
  1279. closeit?"closure":"keep alive", reason));
  1280. conn->bits.close = closeit; /* the only place in the source code that
  1281. should assign this bit */
  1282. }
  1283. }
  1284. /* Data received can be cached at various levels, so check them all here. */
  1285. bool Curl_conn_data_pending(struct connectdata *conn, int sockindex)
  1286. {
  1287. int readable;
  1288. if(Curl_ssl_data_pending(conn, sockindex) ||
  1289. Curl_recv_has_postponed_data(conn, sockindex))
  1290. return true;
  1291. readable = SOCKET_READABLE(conn->sock[sockindex], 0);
  1292. return (readable > 0 && (readable & CURL_CSELECT_IN));
  1293. }