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