connect.c 52 KB

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