connect.c 49 KB

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