2
0

connect.c 51 KB

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