connect.c 48 KB

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