connect.c 52 KB

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