connect.c 49 KB

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