connect.c 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  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. data->info.conn_protocol = conn->handler->protocol;
  578. data->info.conn_primary_port = conn->port;
  579. data->info.conn_remote_port = conn->remote_port;
  580. data->info.conn_local_port = local_port;
  581. }
  582. /* retrieves ip address and port from a sockaddr structure.
  583. note it calls Curl_inet_ntop which sets errno on fail, not SOCKERRNO. */
  584. bool Curl_addr2string(struct sockaddr *sa, curl_socklen_t salen,
  585. char *addr, int *port)
  586. {
  587. struct sockaddr_in *si = NULL;
  588. #ifdef ENABLE_IPV6
  589. struct sockaddr_in6 *si6 = NULL;
  590. #endif
  591. #if (defined(HAVE_SYS_UN_H) || defined(WIN32_SOCKADDR_UN)) && defined(AF_UNIX)
  592. struct sockaddr_un *su = NULL;
  593. #else
  594. (void)salen;
  595. #endif
  596. switch(sa->sa_family) {
  597. case AF_INET:
  598. si = (struct sockaddr_in *)(void *) sa;
  599. if(Curl_inet_ntop(sa->sa_family, &si->sin_addr,
  600. addr, MAX_IPADR_LEN)) {
  601. unsigned short us_port = ntohs(si->sin_port);
  602. *port = us_port;
  603. return TRUE;
  604. }
  605. break;
  606. #ifdef ENABLE_IPV6
  607. case AF_INET6:
  608. si6 = (struct sockaddr_in6 *)(void *) sa;
  609. if(Curl_inet_ntop(sa->sa_family, &si6->sin6_addr,
  610. addr, MAX_IPADR_LEN)) {
  611. unsigned short us_port = ntohs(si6->sin6_port);
  612. *port = us_port;
  613. return TRUE;
  614. }
  615. break;
  616. #endif
  617. #if (defined(HAVE_SYS_UN_H) || defined(WIN32_SOCKADDR_UN)) && defined(AF_UNIX)
  618. case AF_UNIX:
  619. if(salen > (curl_socklen_t)sizeof(CURL_SA_FAMILY_T)) {
  620. su = (struct sockaddr_un*)sa;
  621. msnprintf(addr, MAX_IPADR_LEN, "%s", su->sun_path);
  622. }
  623. else
  624. addr[0] = 0; /* socket with no name */
  625. *port = 0;
  626. return TRUE;
  627. #endif
  628. default:
  629. break;
  630. }
  631. addr[0] = '\0';
  632. *port = 0;
  633. errno = EAFNOSUPPORT;
  634. return FALSE;
  635. }
  636. /* retrieves the start/end point information of a socket of an established
  637. connection */
  638. void Curl_conninfo_remote(struct Curl_easy *data,
  639. struct connectdata *conn, curl_socket_t sockfd)
  640. {
  641. #ifdef HAVE_GETPEERNAME
  642. char buffer[STRERROR_LEN];
  643. struct Curl_sockaddr_storage ssrem;
  644. curl_socklen_t plen;
  645. int port;
  646. plen = sizeof(struct Curl_sockaddr_storage);
  647. memset(&ssrem, 0, sizeof(ssrem));
  648. if(getpeername(sockfd, (struct sockaddr*) &ssrem, &plen)) {
  649. int error = SOCKERRNO;
  650. failf(data, "getpeername() failed with errno %d: %s",
  651. error, Curl_strerror(error, buffer, sizeof(buffer)));
  652. return;
  653. }
  654. if(!Curl_addr2string((struct sockaddr*)&ssrem, plen,
  655. conn->primary_ip, &port)) {
  656. failf(data, "ssrem inet_ntop() failed with errno %d: %s",
  657. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  658. return;
  659. }
  660. #else
  661. (void)data;
  662. (void)conn;
  663. (void)sockfd;
  664. #endif
  665. }
  666. /* retrieves the start/end point information of a socket of an established
  667. connection */
  668. void Curl_conninfo_local(struct Curl_easy *data, curl_socket_t sockfd,
  669. char *local_ip, int *local_port)
  670. {
  671. #ifdef HAVE_GETSOCKNAME
  672. char buffer[STRERROR_LEN];
  673. struct Curl_sockaddr_storage ssloc;
  674. curl_socklen_t slen;
  675. slen = sizeof(struct Curl_sockaddr_storage);
  676. memset(&ssloc, 0, sizeof(ssloc));
  677. if(getsockname(sockfd, (struct sockaddr*) &ssloc, &slen)) {
  678. int error = SOCKERRNO;
  679. failf(data, "getsockname() failed with errno %d: %s",
  680. error, Curl_strerror(error, buffer, sizeof(buffer)));
  681. return;
  682. }
  683. if(!Curl_addr2string((struct sockaddr*)&ssloc, slen,
  684. local_ip, local_port)) {
  685. failf(data, "ssloc inet_ntop() failed with errno %d: %s",
  686. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  687. return;
  688. }
  689. #else
  690. (void)data;
  691. (void)sockfd;
  692. (void)local_ip;
  693. (void)local_port;
  694. #endif
  695. }
  696. /* retrieves the start/end point information of a socket of an established
  697. connection */
  698. void Curl_updateconninfo(struct Curl_easy *data, struct connectdata *conn,
  699. curl_socket_t sockfd)
  700. {
  701. /* 'local_ip' and 'local_port' get filled with local's numerical
  702. ip address and port number whenever an outgoing connection is
  703. **established** from the primary socket to a remote address. */
  704. char local_ip[MAX_IPADR_LEN] = "";
  705. int local_port = -1;
  706. if(conn->transport == TRNSPRT_TCP) {
  707. if(!conn->bits.reuse && !conn->bits.tcp_fastopen)
  708. Curl_conninfo_remote(data, conn, sockfd);
  709. Curl_conninfo_local(data, sockfd, local_ip, &local_port);
  710. } /* end of TCP-only section */
  711. #ifdef ENABLE_QUIC
  712. else if(conn->transport == TRNSPRT_QUIC) {
  713. if(!conn->bits.reuse)
  714. Curl_conninfo_remote(data, conn, sockfd);
  715. Curl_conninfo_local(data, sockfd, local_ip, &local_port);
  716. }
  717. #endif
  718. /* persist connection info in session handle */
  719. Curl_persistconninfo(data, conn, local_ip, local_port);
  720. }
  721. /* After a TCP connection to the proxy has been verified, this function does
  722. the next magic steps. If 'done' isn't set TRUE, it is not done yet and
  723. must be called again.
  724. Note: this function's sub-functions call failf()
  725. */
  726. static CURLcode connect_SOCKS(struct Curl_easy *data, int sockindex,
  727. bool *done)
  728. {
  729. CURLcode result = CURLE_OK;
  730. #ifndef CURL_DISABLE_PROXY
  731. CURLproxycode pxresult = CURLPX_OK;
  732. struct connectdata *conn = data->conn;
  733. if(conn->bits.socksproxy) {
  734. /* for the secondary socket (FTP), use the "connect to host"
  735. * but ignore the "connect to port" (use the secondary port)
  736. */
  737. const char * const host =
  738. conn->bits.httpproxy ?
  739. conn->http_proxy.host.name :
  740. conn->bits.conn_to_host ?
  741. conn->conn_to_host.name :
  742. sockindex == SECONDARYSOCKET ?
  743. conn->secondaryhostname : conn->host.name;
  744. const int port =
  745. conn->bits.httpproxy ? (int)conn->http_proxy.port :
  746. sockindex == SECONDARYSOCKET ? conn->secondary_port :
  747. conn->bits.conn_to_port ? conn->conn_to_port :
  748. conn->remote_port;
  749. switch(conn->socks_proxy.proxytype) {
  750. case CURLPROXY_SOCKS5:
  751. case CURLPROXY_SOCKS5_HOSTNAME:
  752. pxresult = Curl_SOCKS5(conn->socks_proxy.user, conn->socks_proxy.passwd,
  753. host, port, sockindex, data, done);
  754. break;
  755. case CURLPROXY_SOCKS4:
  756. case CURLPROXY_SOCKS4A:
  757. pxresult = Curl_SOCKS4(conn->socks_proxy.user, host, port, sockindex,
  758. data, done);
  759. break;
  760. default:
  761. failf(data, "unknown proxytype option given");
  762. result = CURLE_COULDNT_CONNECT;
  763. } /* switch proxytype */
  764. if(pxresult) {
  765. result = CURLE_PROXY;
  766. data->info.pxcode = pxresult;
  767. }
  768. }
  769. else
  770. #else
  771. (void)data;
  772. (void)sockindex;
  773. #endif /* CURL_DISABLE_PROXY */
  774. *done = TRUE; /* no SOCKS proxy, so consider us connected */
  775. return result;
  776. }
  777. /*
  778. * post_SOCKS() is called after a successful connect to the peer, which
  779. * *could* be a SOCKS proxy
  780. */
  781. static void post_SOCKS(struct Curl_easy *data,
  782. struct connectdata *conn,
  783. int sockindex,
  784. bool *connected)
  785. {
  786. conn->bits.tcpconnect[sockindex] = TRUE;
  787. *connected = TRUE;
  788. if(sockindex == FIRSTSOCKET)
  789. Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
  790. Curl_updateconninfo(data, conn, conn->sock[sockindex]);
  791. Curl_verboseconnect(data, conn);
  792. data->info.numconnects++; /* to track the number of connections made */
  793. }
  794. /*
  795. * Curl_is_connected() checks if the socket has connected.
  796. */
  797. CURLcode Curl_is_connected(struct Curl_easy *data,
  798. struct connectdata *conn,
  799. int sockindex,
  800. bool *connected)
  801. {
  802. CURLcode result = CURLE_OK;
  803. timediff_t allow;
  804. int error = 0;
  805. struct curltime now;
  806. int rc = 0;
  807. unsigned int i;
  808. DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET);
  809. *connected = FALSE; /* a very negative world view is best */
  810. if(conn->bits.tcpconnect[sockindex]) {
  811. /* we are connected already! */
  812. *connected = TRUE;
  813. return CURLE_OK;
  814. }
  815. now = Curl_now();
  816. if(SOCKS_STATE(conn->cnnct.state)) {
  817. /* still doing SOCKS */
  818. result = connect_SOCKS(data, sockindex, connected);
  819. if(!result && *connected)
  820. post_SOCKS(data, conn, sockindex, connected);
  821. return result;
  822. }
  823. for(i = 0; i<2; i++) {
  824. const int other = i ^ 1;
  825. if(conn->tempsock[i] == CURL_SOCKET_BAD)
  826. continue;
  827. error = 0;
  828. #ifdef ENABLE_QUIC
  829. if(conn->transport == TRNSPRT_QUIC) {
  830. result = Curl_quic_is_connected(data, conn, i, connected);
  831. if(!result && *connected) {
  832. /* use this socket from now on */
  833. conn->sock[sockindex] = conn->tempsock[i];
  834. conn->ip_addr = conn->tempaddr[i];
  835. conn->tempsock[i] = CURL_SOCKET_BAD;
  836. post_SOCKS(data, conn, sockindex, connected);
  837. connkeep(conn, "HTTP/3 default");
  838. if(conn->tempsock[other] != CURL_SOCKET_BAD)
  839. Curl_quic_disconnect(data, conn, other);
  840. return CURLE_OK;
  841. }
  842. /* When a QUIC connect attempt fails, the better error explanation is in
  843. 'result' and not in errno */
  844. if(result) {
  845. conn->tempsock[i] = CURL_SOCKET_BAD;
  846. error = SOCKERRNO;
  847. }
  848. }
  849. else
  850. #endif
  851. {
  852. #ifdef mpeix
  853. /* Call this function once now, and ignore the results. We do this to
  854. "clear" the error state on the socket so that we can later read it
  855. reliably. This is reported necessary on the MPE/iX operating
  856. system. */
  857. (void)verifyconnect(conn->tempsock[i], NULL);
  858. #endif
  859. /* check socket for connect */
  860. rc = SOCKET_WRITABLE(conn->tempsock[i], 0);
  861. }
  862. if(rc == 0) { /* no connection yet */
  863. if(Curl_timediff(now, conn->connecttime) >=
  864. conn->timeoutms_per_addr[i]) {
  865. infof(data, "After %" CURL_FORMAT_TIMEDIFF_T
  866. "ms connect time, move on!", conn->timeoutms_per_addr[i]);
  867. error = ETIMEDOUT;
  868. }
  869. /* should we try another protocol family? */
  870. if(i == 0 && !conn->bits.parallel_connect &&
  871. (Curl_timediff(now, conn->connecttime) >=
  872. data->set.happy_eyeballs_timeout)) {
  873. conn->bits.parallel_connect = TRUE; /* starting now */
  874. trynextip(data, conn, sockindex, 1);
  875. }
  876. }
  877. else if(rc == CURL_CSELECT_OUT || conn->bits.tcp_fastopen) {
  878. if(verifyconnect(conn->tempsock[i], &error)) {
  879. /* we are connected with TCP, awesome! */
  880. /* use this socket from now on */
  881. conn->sock[sockindex] = conn->tempsock[i];
  882. conn->ip_addr = conn->tempaddr[i];
  883. conn->tempsock[i] = CURL_SOCKET_BAD;
  884. #ifdef ENABLE_IPV6
  885. conn->bits.ipv6 = (conn->ip_addr->ai_family == AF_INET6)?TRUE:FALSE;
  886. #endif
  887. /* close the other socket, if open */
  888. if(conn->tempsock[other] != CURL_SOCKET_BAD) {
  889. Curl_closesocket(data, conn, conn->tempsock[other]);
  890. conn->tempsock[other] = CURL_SOCKET_BAD;
  891. }
  892. /* see if we need to kick off any SOCKS proxy magic once we
  893. connected */
  894. result = connect_SOCKS(data, sockindex, connected);
  895. if(result || !*connected)
  896. return result;
  897. post_SOCKS(data, conn, sockindex, connected);
  898. return CURLE_OK;
  899. }
  900. }
  901. else if(rc & CURL_CSELECT_ERR) {
  902. (void)verifyconnect(conn->tempsock[i], &error);
  903. }
  904. /*
  905. * The connection failed here, we should attempt to connect to the "next
  906. * address" for the given host. But first remember the latest error.
  907. */
  908. if(error) {
  909. data->state.os_errno = error;
  910. SET_SOCKERRNO(error);
  911. if(conn->tempaddr[i]) {
  912. CURLcode status;
  913. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  914. char ipaddress[MAX_IPADR_LEN];
  915. char buffer[STRERROR_LEN];
  916. Curl_printable_address(conn->tempaddr[i], ipaddress,
  917. sizeof(ipaddress));
  918. #ifdef ENABLE_QUIC
  919. if(conn->transport == TRNSPRT_QUIC) {
  920. infof(data, "connect to %s port %u failed: %s",
  921. ipaddress, conn->port, curl_easy_strerror(result));
  922. }
  923. else
  924. #endif
  925. infof(data, "connect to %s port %u failed: %s",
  926. ipaddress, conn->port,
  927. Curl_strerror(error, buffer, sizeof(buffer)));
  928. #endif
  929. allow = Curl_timeleft(data, &now, TRUE);
  930. conn->timeoutms_per_addr[i] = conn->tempaddr[i]->ai_next == NULL ?
  931. allow : allow / 2;
  932. ainext(conn, i, TRUE);
  933. status = trynextip(data, conn, sockindex, i);
  934. if((status != CURLE_COULDNT_CONNECT) ||
  935. conn->tempsock[other] == CURL_SOCKET_BAD) {
  936. /* the last attempt failed and no other sockets remain open */
  937. if(!result)
  938. result = status;
  939. }
  940. }
  941. }
  942. }
  943. /*
  944. * Now that we've checked whether we are connected, check whether we've
  945. * already timed out.
  946. *
  947. * First figure out how long time we have left to connect */
  948. allow = Curl_timeleft(data, &now, TRUE);
  949. if(allow < 0) {
  950. /* time-out, bail out, go home */
  951. failf(data, "Connection timeout after %ld ms",
  952. Curl_timediff(now, data->progress.t_startsingle));
  953. return CURLE_OPERATION_TIMEDOUT;
  954. }
  955. if(result &&
  956. (conn->tempsock[0] == CURL_SOCKET_BAD) &&
  957. (conn->tempsock[1] == CURL_SOCKET_BAD)) {
  958. /* no more addresses to try */
  959. const char *hostname;
  960. char buffer[STRERROR_LEN];
  961. CURLcode failreason = result;
  962. /* if the first address family runs out of addresses to try before the
  963. happy eyeball timeout, go ahead and try the next family now */
  964. result = trynextip(data, conn, sockindex, 1);
  965. if(!result)
  966. return result;
  967. result = failreason;
  968. #ifndef CURL_DISABLE_PROXY
  969. if(conn->bits.socksproxy)
  970. hostname = conn->socks_proxy.host.name;
  971. else if(conn->bits.httpproxy)
  972. hostname = conn->http_proxy.host.name;
  973. else
  974. #endif
  975. if(conn->bits.conn_to_host)
  976. hostname = conn->conn_to_host.name;
  977. else
  978. hostname = conn->host.name;
  979. failf(data, "Failed to connect to %s port %u after "
  980. "%" CURL_FORMAT_TIMEDIFF_T " ms: %s",
  981. hostname, conn->port,
  982. Curl_timediff(now, data->progress.t_startsingle),
  983. #ifdef ENABLE_QUIC
  984. (conn->transport == TRNSPRT_QUIC) ?
  985. curl_easy_strerror(result) :
  986. #endif
  987. Curl_strerror(error, buffer, sizeof(buffer)));
  988. Curl_quic_disconnect(data, conn, 0);
  989. Curl_quic_disconnect(data, conn, 1);
  990. #ifdef WSAETIMEDOUT
  991. if(WSAETIMEDOUT == data->state.os_errno)
  992. result = CURLE_OPERATION_TIMEDOUT;
  993. #elif defined(ETIMEDOUT)
  994. if(ETIMEDOUT == data->state.os_errno)
  995. result = CURLE_OPERATION_TIMEDOUT;
  996. #endif
  997. }
  998. else
  999. result = CURLE_OK; /* still trying */
  1000. return result;
  1001. }
  1002. static void tcpnodelay(struct Curl_easy *data, curl_socket_t sockfd)
  1003. {
  1004. #if defined(TCP_NODELAY)
  1005. curl_socklen_t onoff = (curl_socklen_t) 1;
  1006. int level = IPPROTO_TCP;
  1007. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  1008. char buffer[STRERROR_LEN];
  1009. #else
  1010. (void) data;
  1011. #endif
  1012. if(setsockopt(sockfd, level, TCP_NODELAY, (void *)&onoff,
  1013. sizeof(onoff)) < 0)
  1014. infof(data, "Could not set TCP_NODELAY: %s",
  1015. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  1016. #else
  1017. (void)data;
  1018. (void)sockfd;
  1019. #endif
  1020. }
  1021. #ifdef SO_NOSIGPIPE
  1022. /* The preferred method on Mac OS X (10.2 and later) to prevent SIGPIPEs when
  1023. sending data to a dead peer (instead of relying on the 4th argument to send
  1024. being MSG_NOSIGNAL). Possibly also existing and in use on other BSD
  1025. systems? */
  1026. static void nosigpipe(struct Curl_easy *data,
  1027. curl_socket_t sockfd)
  1028. {
  1029. int onoff = 1;
  1030. if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
  1031. sizeof(onoff)) < 0) {
  1032. #if !defined(CURL_DISABLE_VERBOSE_STRINGS)
  1033. char buffer[STRERROR_LEN];
  1034. infof(data, "Could not set SO_NOSIGPIPE: %s",
  1035. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  1036. #endif
  1037. }
  1038. }
  1039. #else
  1040. #define nosigpipe(x,y) Curl_nop_stmt
  1041. #endif
  1042. #ifdef USE_WINSOCK
  1043. /* When you run a program that uses the Windows Sockets API, you may
  1044. experience slow performance when you copy data to a TCP server.
  1045. https://support.microsoft.com/kb/823764
  1046. Work-around: Make the Socket Send Buffer Size Larger Than the Program Send
  1047. Buffer Size
  1048. The problem described in this knowledge-base is applied only to pre-Vista
  1049. Windows. Following function trying to detect OS version and skips
  1050. SO_SNDBUF adjustment for Windows Vista and above.
  1051. */
  1052. #define DETECT_OS_NONE 0
  1053. #define DETECT_OS_PREVISTA 1
  1054. #define DETECT_OS_VISTA_OR_LATER 2
  1055. void Curl_sndbufset(curl_socket_t sockfd)
  1056. {
  1057. int val = CURL_MAX_WRITE_SIZE + 32;
  1058. int curval = 0;
  1059. int curlen = sizeof(curval);
  1060. static int detectOsState = DETECT_OS_NONE;
  1061. if(detectOsState == DETECT_OS_NONE) {
  1062. if(curlx_verify_windows_version(6, 0, 0, PLATFORM_WINNT,
  1063. VERSION_GREATER_THAN_EQUAL))
  1064. detectOsState = DETECT_OS_VISTA_OR_LATER;
  1065. else
  1066. detectOsState = DETECT_OS_PREVISTA;
  1067. }
  1068. if(detectOsState == DETECT_OS_VISTA_OR_LATER)
  1069. return;
  1070. if(getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (char *)&curval, &curlen) == 0)
  1071. if(curval > val)
  1072. return;
  1073. setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char *)&val, sizeof(val));
  1074. }
  1075. #endif
  1076. /*
  1077. * singleipconnect()
  1078. *
  1079. * Note that even on connect fail it returns CURLE_OK, but with 'sock' set to
  1080. * CURL_SOCKET_BAD. Other errors will however return proper errors.
  1081. *
  1082. * singleipconnect() connects to the given IP only, and it may return without
  1083. * having connected.
  1084. */
  1085. static CURLcode singleipconnect(struct Curl_easy *data,
  1086. struct connectdata *conn,
  1087. const struct Curl_addrinfo *ai,
  1088. int tempindex)
  1089. {
  1090. struct Curl_sockaddr_ex addr;
  1091. int rc = -1;
  1092. int error = 0;
  1093. bool isconnected = FALSE;
  1094. curl_socket_t sockfd;
  1095. CURLcode result;
  1096. char ipaddress[MAX_IPADR_LEN];
  1097. int port;
  1098. bool is_tcp;
  1099. #ifdef TCP_FASTOPEN_CONNECT
  1100. int optval = 1;
  1101. #endif
  1102. char buffer[STRERROR_LEN];
  1103. curl_socket_t *sockp = &conn->tempsock[tempindex];
  1104. *sockp = CURL_SOCKET_BAD;
  1105. result = Curl_socket(data, ai, &addr, &sockfd);
  1106. if(result)
  1107. return result;
  1108. /* store remote address and port used in this connection attempt */
  1109. if(!Curl_addr2string((struct sockaddr*)&addr.sa_addr, addr.addrlen,
  1110. ipaddress, &port)) {
  1111. /* malformed address or bug in inet_ntop, try next address */
  1112. failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
  1113. errno, Curl_strerror(errno, buffer, sizeof(buffer)));
  1114. Curl_closesocket(data, conn, sockfd);
  1115. return CURLE_OK;
  1116. }
  1117. infof(data, " Trying %s:%d...", ipaddress, port);
  1118. #ifdef ENABLE_IPV6
  1119. is_tcp = (addr.family == AF_INET || addr.family == AF_INET6) &&
  1120. addr.socktype == SOCK_STREAM;
  1121. #else
  1122. is_tcp = (addr.family == AF_INET) && addr.socktype == SOCK_STREAM;
  1123. #endif
  1124. if(is_tcp && data->set.tcp_nodelay)
  1125. tcpnodelay(data, sockfd);
  1126. nosigpipe(data, sockfd);
  1127. Curl_sndbufset(sockfd);
  1128. if(is_tcp && data->set.tcp_keepalive)
  1129. tcpkeepalive(data, sockfd);
  1130. if(data->set.fsockopt) {
  1131. /* activate callback for setting socket options */
  1132. Curl_set_in_callback(data, true);
  1133. error = data->set.fsockopt(data->set.sockopt_client,
  1134. sockfd,
  1135. CURLSOCKTYPE_IPCXN);
  1136. Curl_set_in_callback(data, false);
  1137. if(error == CURL_SOCKOPT_ALREADY_CONNECTED)
  1138. isconnected = TRUE;
  1139. else if(error) {
  1140. Curl_closesocket(data, conn, sockfd); /* close the socket and bail out */
  1141. return CURLE_ABORTED_BY_CALLBACK;
  1142. }
  1143. }
  1144. /* possibly bind the local end to an IP, interface or port */
  1145. if(addr.family == AF_INET
  1146. #ifdef ENABLE_IPV6
  1147. || addr.family == AF_INET6
  1148. #endif
  1149. ) {
  1150. result = bindlocal(data, sockfd, addr.family,
  1151. Curl_ipv6_scope((struct sockaddr*)&addr.sa_addr));
  1152. if(result) {
  1153. Curl_closesocket(data, conn, sockfd); /* close socket and bail out */
  1154. if(result == CURLE_UNSUPPORTED_PROTOCOL) {
  1155. /* The address family is not supported on this interface.
  1156. We can continue trying addresses */
  1157. return CURLE_COULDNT_CONNECT;
  1158. }
  1159. return result;
  1160. }
  1161. }
  1162. /* set socket non-blocking */
  1163. (void)curlx_nonblock(sockfd, TRUE);
  1164. conn->connecttime = Curl_now();
  1165. if(conn->num_addr > 1) {
  1166. Curl_expire(data, conn->timeoutms_per_addr[0], EXPIRE_DNS_PER_NAME);
  1167. Curl_expire(data, conn->timeoutms_per_addr[1], EXPIRE_DNS_PER_NAME2);
  1168. }
  1169. /* Connect TCP and QUIC sockets */
  1170. if(!isconnected && (conn->transport != TRNSPRT_UDP)) {
  1171. if(conn->bits.tcp_fastopen) {
  1172. #if defined(CONNECT_DATA_IDEMPOTENT) /* Darwin */
  1173. # if defined(HAVE_BUILTIN_AVAILABLE)
  1174. /* while connectx function is available since macOS 10.11 / iOS 9,
  1175. it did not have the interface declared correctly until
  1176. Xcode 9 / macOS SDK 10.13 */
  1177. if(__builtin_available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)) {
  1178. sa_endpoints_t endpoints;
  1179. endpoints.sae_srcif = 0;
  1180. endpoints.sae_srcaddr = NULL;
  1181. endpoints.sae_srcaddrlen = 0;
  1182. endpoints.sae_dstaddr = &addr.sa_addr;
  1183. endpoints.sae_dstaddrlen = addr.addrlen;
  1184. rc = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY,
  1185. CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
  1186. NULL, 0, NULL, NULL);
  1187. }
  1188. else {
  1189. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  1190. }
  1191. # else
  1192. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  1193. # endif /* HAVE_BUILTIN_AVAILABLE */
  1194. #elif defined(TCP_FASTOPEN_CONNECT) /* Linux >= 4.11 */
  1195. if(setsockopt(sockfd, IPPROTO_TCP, TCP_FASTOPEN_CONNECT,
  1196. (void *)&optval, sizeof(optval)) < 0)
  1197. infof(data, "Failed to enable TCP Fast Open on fd %d", sockfd);
  1198. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  1199. #elif defined(MSG_FASTOPEN) /* old Linux */
  1200. if(conn->given->flags & PROTOPT_SSL)
  1201. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  1202. else
  1203. rc = 0; /* Do nothing */
  1204. #endif
  1205. }
  1206. else {
  1207. rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
  1208. }
  1209. if(-1 == rc)
  1210. error = SOCKERRNO;
  1211. #ifdef ENABLE_QUIC
  1212. else if(conn->transport == TRNSPRT_QUIC) {
  1213. /* pass in 'sockfd' separately since it hasn't been put into the
  1214. tempsock array at this point */
  1215. result = Curl_quic_connect(data, conn, sockfd, tempindex,
  1216. &addr.sa_addr, addr.addrlen);
  1217. if(result)
  1218. error = SOCKERRNO;
  1219. }
  1220. #endif
  1221. }
  1222. else {
  1223. *sockp = sockfd;
  1224. return CURLE_OK;
  1225. }
  1226. if(-1 == rc) {
  1227. switch(error) {
  1228. case EINPROGRESS:
  1229. case EWOULDBLOCK:
  1230. #if defined(EAGAIN)
  1231. #if (EAGAIN) != (EWOULDBLOCK)
  1232. /* On some platforms EAGAIN and EWOULDBLOCK are the
  1233. * same value, and on others they are different, hence
  1234. * the odd #if
  1235. */
  1236. case EAGAIN:
  1237. #endif
  1238. #endif
  1239. result = CURLE_OK;
  1240. break;
  1241. default:
  1242. /* unknown error, fallthrough and try another address! */
  1243. infof(data, "Immediate connect fail for %s: %s",
  1244. ipaddress, Curl_strerror(error, buffer, sizeof(buffer)));
  1245. data->state.os_errno = error;
  1246. /* connect failed */
  1247. Curl_closesocket(data, conn, sockfd);
  1248. result = CURLE_COULDNT_CONNECT;
  1249. }
  1250. }
  1251. if(!result)
  1252. *sockp = sockfd;
  1253. return result;
  1254. }
  1255. /*
  1256. * TCP connect to the given host with timeout, proxy or remote doesn't matter.
  1257. * There might be more than one IP address to try out. Fill in the passed
  1258. * pointer with the connected socket.
  1259. */
  1260. CURLcode Curl_connecthost(struct Curl_easy *data,
  1261. struct connectdata *conn, /* context */
  1262. const struct Curl_dns_entry *remotehost)
  1263. {
  1264. CURLcode result = CURLE_COULDNT_CONNECT;
  1265. int i;
  1266. timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1267. if(timeout_ms < 0) {
  1268. /* a precaution, no need to continue if time already is up */
  1269. failf(data, "Connection time-out");
  1270. return CURLE_OPERATION_TIMEDOUT;
  1271. }
  1272. conn->num_addr = Curl_num_addresses(remotehost->addr);
  1273. conn->tempaddr[0] = conn->tempaddr[1] = remotehost->addr;
  1274. conn->tempsock[0] = conn->tempsock[1] = CURL_SOCKET_BAD;
  1275. /* Max time for the next connection attempt */
  1276. conn->timeoutms_per_addr[0] =
  1277. conn->tempaddr[0]->ai_next == NULL ? timeout_ms : timeout_ms / 2;
  1278. conn->timeoutms_per_addr[1] =
  1279. conn->tempaddr[1]->ai_next == NULL ? timeout_ms : timeout_ms / 2;
  1280. if(conn->ip_version == CURL_IPRESOLVE_WHATEVER) {
  1281. /* any IP version is allowed */
  1282. conn->tempfamily[0] = conn->tempaddr[0]?
  1283. conn->tempaddr[0]->ai_family:0;
  1284. #ifdef ENABLE_IPV6
  1285. conn->tempfamily[1] = conn->tempfamily[0] == AF_INET6 ?
  1286. AF_INET : AF_INET6;
  1287. #else
  1288. conn->tempfamily[1] = AF_UNSPEC;
  1289. #endif
  1290. }
  1291. else {
  1292. /* only one IP version is allowed */
  1293. conn->tempfamily[0] = (conn->ip_version == CURL_IPRESOLVE_V4) ?
  1294. AF_INET :
  1295. #ifdef ENABLE_IPV6
  1296. AF_INET6;
  1297. #else
  1298. AF_UNSPEC;
  1299. #endif
  1300. conn->tempfamily[1] = AF_UNSPEC;
  1301. ainext(conn, 0, FALSE); /* find first address of the right type */
  1302. }
  1303. ainext(conn, 1, FALSE); /* assigns conn->tempaddr[1] accordingly */
  1304. DEBUGF(infof(data, "family0 == %s, family1 == %s",
  1305. conn->tempfamily[0] == AF_INET ? "v4" : "v6",
  1306. conn->tempfamily[1] == AF_INET ? "v4" : "v6"));
  1307. /* get through the list in family order in case of quick failures */
  1308. for(i = 0; (i < 2) && result; i++) {
  1309. while(conn->tempaddr[i]) {
  1310. result = singleipconnect(data, conn, conn->tempaddr[i], i);
  1311. if(!result)
  1312. break;
  1313. ainext(conn, i, TRUE);
  1314. }
  1315. }
  1316. if(result)
  1317. return result;
  1318. Curl_expire(data, data->set.happy_eyeballs_timeout,
  1319. EXPIRE_HAPPY_EYEBALLS);
  1320. return CURLE_OK;
  1321. }
  1322. struct connfind {
  1323. long id_tofind;
  1324. struct connectdata *found;
  1325. };
  1326. static int conn_is_conn(struct Curl_easy *data,
  1327. struct connectdata *conn, void *param)
  1328. {
  1329. struct connfind *f = (struct connfind *)param;
  1330. (void)data;
  1331. if(conn->connection_id == f->id_tofind) {
  1332. f->found = conn;
  1333. return 1;
  1334. }
  1335. return 0;
  1336. }
  1337. /*
  1338. * Used to extract socket and connectdata struct for the most recent
  1339. * transfer on the given Curl_easy.
  1340. *
  1341. * The returned socket will be CURL_SOCKET_BAD in case of failure!
  1342. */
  1343. curl_socket_t Curl_getconnectinfo(struct Curl_easy *data,
  1344. struct connectdata **connp)
  1345. {
  1346. DEBUGASSERT(data);
  1347. /* this works for an easy handle:
  1348. * - that has been used for curl_easy_perform()
  1349. * - that is associated with a multi handle, and whose connection
  1350. * was detached with CURLOPT_CONNECT_ONLY
  1351. */
  1352. if((data->state.lastconnect_id != -1) && (data->multi_easy || data->multi)) {
  1353. struct connectdata *c;
  1354. struct connfind find;
  1355. find.id_tofind = data->state.lastconnect_id;
  1356. find.found = NULL;
  1357. Curl_conncache_foreach(data,
  1358. data->share && (data->share->specifier
  1359. & (1<< CURL_LOCK_DATA_CONNECT))?
  1360. &data->share->conn_cache:
  1361. data->multi_easy?
  1362. &data->multi_easy->conn_cache:
  1363. &data->multi->conn_cache, &find, conn_is_conn);
  1364. if(!find.found) {
  1365. data->state.lastconnect_id = -1;
  1366. return CURL_SOCKET_BAD;
  1367. }
  1368. c = find.found;
  1369. if(connp)
  1370. /* only store this if the caller cares for it */
  1371. *connp = c;
  1372. return c->sock[FIRSTSOCKET];
  1373. }
  1374. return CURL_SOCKET_BAD;
  1375. }
  1376. /*
  1377. * Check if a connection seems to be alive.
  1378. */
  1379. bool Curl_connalive(struct connectdata *conn)
  1380. {
  1381. /* First determine if ssl */
  1382. if(conn->ssl[FIRSTSOCKET].use) {
  1383. /* use the SSL context */
  1384. if(!Curl_ssl_check_cxn(conn))
  1385. return false; /* FIN received */
  1386. }
  1387. /* Minix 3.1 doesn't support any flags on recv; just assume socket is OK */
  1388. #ifdef MSG_PEEK
  1389. else if(conn->sock[FIRSTSOCKET] == CURL_SOCKET_BAD)
  1390. return false;
  1391. else {
  1392. /* use the socket */
  1393. char buf;
  1394. if(recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
  1395. (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK) == 0) {
  1396. return false; /* FIN received */
  1397. }
  1398. }
  1399. #endif
  1400. return true;
  1401. }
  1402. /*
  1403. * Close a socket.
  1404. *
  1405. * 'conn' can be NULL, beware!
  1406. */
  1407. int Curl_closesocket(struct Curl_easy *data, struct connectdata *conn,
  1408. curl_socket_t sock)
  1409. {
  1410. if(conn && conn->fclosesocket) {
  1411. if((sock == conn->sock[SECONDARYSOCKET]) && conn->bits.sock_accepted)
  1412. /* if this socket matches the second socket, and that was created with
  1413. accept, then we MUST NOT call the callback but clear the accepted
  1414. status */
  1415. conn->bits.sock_accepted = FALSE;
  1416. else {
  1417. int rc;
  1418. Curl_multi_closed(data, sock);
  1419. Curl_set_in_callback(data, true);
  1420. rc = conn->fclosesocket(conn->closesocket_client, sock);
  1421. Curl_set_in_callback(data, false);
  1422. return rc;
  1423. }
  1424. }
  1425. if(conn)
  1426. /* tell the multi-socket code about this */
  1427. Curl_multi_closed(data, sock);
  1428. sclose(sock);
  1429. return 0;
  1430. }
  1431. /*
  1432. * Create a socket based on info from 'conn' and 'ai'.
  1433. *
  1434. * 'addr' should be a pointer to the correct struct to get data back, or NULL.
  1435. * 'sockfd' must be a pointer to a socket descriptor.
  1436. *
  1437. * If the open socket callback is set, used that!
  1438. *
  1439. */
  1440. CURLcode Curl_socket(struct Curl_easy *data,
  1441. const struct Curl_addrinfo *ai,
  1442. struct Curl_sockaddr_ex *addr,
  1443. curl_socket_t *sockfd)
  1444. {
  1445. struct connectdata *conn = data->conn;
  1446. struct Curl_sockaddr_ex dummy;
  1447. if(!addr)
  1448. /* if the caller doesn't want info back, use a local temp copy */
  1449. addr = &dummy;
  1450. /*
  1451. * The Curl_sockaddr_ex structure is basically libcurl's external API
  1452. * curl_sockaddr structure with enough space available to directly hold
  1453. * any protocol-specific address structures. The variable declared here
  1454. * will be used to pass / receive data to/from the fopensocket callback
  1455. * if this has been set, before that, it is initialized from parameters.
  1456. */
  1457. addr->family = ai->ai_family;
  1458. switch(conn->transport) {
  1459. case TRNSPRT_TCP:
  1460. addr->socktype = SOCK_STREAM;
  1461. addr->protocol = IPPROTO_TCP;
  1462. break;
  1463. case TRNSPRT_UNIX:
  1464. addr->socktype = SOCK_STREAM;
  1465. addr->protocol = IPPROTO_IP;
  1466. break;
  1467. default: /* UDP and QUIC */
  1468. addr->socktype = SOCK_DGRAM;
  1469. addr->protocol = IPPROTO_UDP;
  1470. break;
  1471. }
  1472. addr->addrlen = ai->ai_addrlen;
  1473. if(addr->addrlen > sizeof(struct Curl_sockaddr_storage))
  1474. addr->addrlen = sizeof(struct Curl_sockaddr_storage);
  1475. memcpy(&addr->sa_addr, ai->ai_addr, addr->addrlen);
  1476. if(data->set.fopensocket) {
  1477. /*
  1478. * If the opensocket callback is set, all the destination address
  1479. * information is passed to the callback. Depending on this information the
  1480. * callback may opt to abort the connection, this is indicated returning
  1481. * CURL_SOCKET_BAD; otherwise it will return a not-connected socket. When
  1482. * the callback returns a valid socket the destination address information
  1483. * might have been changed and this 'new' address will actually be used
  1484. * here to connect.
  1485. */
  1486. Curl_set_in_callback(data, true);
  1487. *sockfd = data->set.fopensocket(data->set.opensocket_client,
  1488. CURLSOCKTYPE_IPCXN,
  1489. (struct curl_sockaddr *)addr);
  1490. Curl_set_in_callback(data, false);
  1491. }
  1492. else
  1493. /* opensocket callback not set, so simply create the socket now */
  1494. *sockfd = socket(addr->family, addr->socktype, addr->protocol);
  1495. if(*sockfd == CURL_SOCKET_BAD)
  1496. /* no socket, no connection */
  1497. return CURLE_COULDNT_CONNECT;
  1498. if(conn->transport == TRNSPRT_QUIC) {
  1499. /* QUIC sockets need to be nonblocking */
  1500. (void)curlx_nonblock(*sockfd, TRUE);
  1501. switch(addr->family) {
  1502. #if defined(__linux__) && defined(IP_MTU_DISCOVER)
  1503. case AF_INET: {
  1504. int val = IP_PMTUDISC_DO;
  1505. (void)setsockopt(*sockfd, IPPROTO_IP, IP_MTU_DISCOVER, &val,
  1506. sizeof(val));
  1507. break;
  1508. }
  1509. #endif
  1510. #if defined(__linux__) && defined(IPV6_MTU_DISCOVER)
  1511. case AF_INET6: {
  1512. int val = IPV6_PMTUDISC_DO;
  1513. (void)setsockopt(*sockfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &val,
  1514. sizeof(val));
  1515. break;
  1516. }
  1517. #endif
  1518. }
  1519. }
  1520. #if defined(ENABLE_IPV6) && defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID)
  1521. if(conn->scope_id && (addr->family == AF_INET6)) {
  1522. struct sockaddr_in6 * const sa6 = (void *)&addr->sa_addr;
  1523. sa6->sin6_scope_id = conn->scope_id;
  1524. }
  1525. #endif
  1526. return CURLE_OK;
  1527. }
  1528. /*
  1529. * Curl_conncontrol() marks streams or connection for closure.
  1530. */
  1531. void Curl_conncontrol(struct connectdata *conn,
  1532. int ctrl /* see defines in header */
  1533. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  1534. , const char *reason
  1535. #endif
  1536. )
  1537. {
  1538. /* close if a connection, or a stream that isn't multiplexed. */
  1539. /* This function will be called both before and after this connection is
  1540. associated with a transfer. */
  1541. bool closeit;
  1542. DEBUGASSERT(conn);
  1543. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  1544. (void)reason; /* useful for debugging */
  1545. #endif
  1546. closeit = (ctrl == CONNCTRL_CONNECTION) ||
  1547. ((ctrl == CONNCTRL_STREAM) && !(conn->handler->flags & PROTOPT_STREAM));
  1548. if((ctrl == CONNCTRL_STREAM) &&
  1549. (conn->handler->flags & PROTOPT_STREAM))
  1550. ;
  1551. else if((bit)closeit != conn->bits.close) {
  1552. conn->bits.close = closeit; /* the only place in the source code that
  1553. should assign this bit */
  1554. }
  1555. }
  1556. /* Data received can be cached at various levels, so check them all here. */
  1557. bool Curl_conn_data_pending(struct connectdata *conn, int sockindex)
  1558. {
  1559. int readable;
  1560. DEBUGASSERT(conn);
  1561. if(Curl_ssl_data_pending(conn, sockindex) ||
  1562. Curl_recv_has_postponed_data(conn, sockindex))
  1563. return true;
  1564. readable = SOCKET_READABLE(conn->sock[sockindex], 0);
  1565. return (readable > 0 && (readable & CURL_CSELECT_IN));
  1566. }