connect.c 49 KB

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