connect.c 48 KB

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