connect.c 48 KB

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