connect.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: connect.cc,v 1.10.2.1 2004/01/16 18:58:50 mdz Exp $
  4. /* ######################################################################
  5. Connect - Replacement connect call
  6. This was originally authored by Jason Gunthorpe <jgg@debian.org>
  7. and is placed in the Public Domain, do with it what you will.
  8. ##################################################################### */
  9. /*}}}*/
  10. // Include Files /*{{{*/
  11. #include <config.h>
  12. #include <apt-pkg/error.h>
  13. #include <apt-pkg/fileutl.h>
  14. #include <apt-pkg/strutl.h>
  15. #include <apt-pkg/acquire-method.h>
  16. #include <apt-pkg/configuration.h>
  17. #include <apt-pkg/srvrec.h>
  18. #include <stdio.h>
  19. #include <errno.h>
  20. #include <unistd.h>
  21. #include <sstream>
  22. #include <string.h>
  23. #include<set>
  24. #include<string>
  25. // Internet stuff
  26. #include <netinet/in.h>
  27. #include <sys/socket.h>
  28. #include <arpa/inet.h>
  29. #include <netdb.h>
  30. #include "connect.h"
  31. #include "rfc2553emu.h"
  32. #include <apti18n.h>
  33. /*}}}*/
  34. static std::string LastHost;
  35. static int LastPort = 0;
  36. static struct addrinfo *LastHostAddr = 0;
  37. static struct addrinfo *LastUsed = 0;
  38. static std::vector<SrvRec> SrvRecords;
  39. // Set of IP/hostnames that we timed out before or couldn't resolve
  40. static std::set<std::string> bad_addr;
  41. // RotateDNS - Select a new server from a DNS rotation /*{{{*/
  42. // ---------------------------------------------------------------------
  43. /* This is called during certain errors in order to recover by selecting a
  44. new server */
  45. void RotateDNS()
  46. {
  47. if (LastUsed != 0 && LastUsed->ai_next != 0)
  48. LastUsed = LastUsed->ai_next;
  49. else
  50. LastUsed = LastHostAddr;
  51. }
  52. /*}}}*/
  53. static bool ConnectionAllowed(char const * const Service, std::string const &Host)/*{{{*/
  54. {
  55. if (APT::String::Endswith(Host, ".onion") && _config->FindB("Acquire::BlockDotOnion", true))
  56. {
  57. // TRANSLATOR: %s is e.g. Tor's ".onion" which would likely fail or leak info (RFC7686)
  58. _error->Error(_("Direct connection to %s domains is blocked by default."), ".onion");
  59. if (strcmp(Service, "http") == 0)
  60. _error->Error(_("If you meant to use Tor remember to use %s instead of %s."), "tor+http", "http");
  61. return false;
  62. }
  63. return true;
  64. }
  65. /*}}}*/
  66. // DoConnect - Attempt a connect operation /*{{{*/
  67. // ---------------------------------------------------------------------
  68. /* This helper function attempts a connection to a single address. */
  69. static bool DoConnect(struct addrinfo *Addr,std::string const &Host,
  70. unsigned long TimeOut,int &Fd,pkgAcqMethod *Owner)
  71. {
  72. // Show a status indicator
  73. char Name[NI_MAXHOST];
  74. char Service[NI_MAXSERV];
  75. Name[0] = 0;
  76. Service[0] = 0;
  77. getnameinfo(Addr->ai_addr,Addr->ai_addrlen,
  78. Name,sizeof(Name),Service,sizeof(Service),
  79. NI_NUMERICHOST|NI_NUMERICSERV);
  80. Owner->Status(_("Connecting to %s (%s)"),Host.c_str(),Name);
  81. // if that addr did timeout before, we do not try it again
  82. if(bad_addr.find(std::string(Name)) != bad_addr.end())
  83. return false;
  84. /* If this is an IP rotation store the IP we are using.. If something goes
  85. wrong this will get tacked onto the end of the error message */
  86. if (LastHostAddr->ai_next != 0)
  87. {
  88. std::stringstream ss;
  89. ioprintf(ss, _("[IP: %s %s]"),Name,Service);
  90. Owner->SetIP(ss.str());
  91. }
  92. // Get a socket
  93. if ((Fd = socket(Addr->ai_family,Addr->ai_socktype,
  94. Addr->ai_protocol)) < 0)
  95. return _error->Errno("socket",_("Could not create a socket for %s (f=%u t=%u p=%u)"),
  96. Name,Addr->ai_family,Addr->ai_socktype,Addr->ai_protocol);
  97. SetNonBlock(Fd,true);
  98. if (connect(Fd,Addr->ai_addr,Addr->ai_addrlen) < 0 &&
  99. errno != EINPROGRESS)
  100. return _error->Errno("connect",_("Cannot initiate the connection "
  101. "to %s:%s (%s)."),Host.c_str(),Service,Name);
  102. /* This implements a timeout for connect by opening the connection
  103. nonblocking */
  104. if (WaitFd(Fd,true,TimeOut) == false) {
  105. bad_addr.insert(bad_addr.begin(), std::string(Name));
  106. Owner->SetFailReason("Timeout");
  107. return _error->Error(_("Could not connect to %s:%s (%s), "
  108. "connection timed out"),Host.c_str(),Service,Name);
  109. }
  110. // Check the socket for an error condition
  111. unsigned int Err;
  112. unsigned int Len = sizeof(Err);
  113. if (getsockopt(Fd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  114. return _error->Errno("getsockopt",_("Failed"));
  115. if (Err != 0)
  116. {
  117. errno = Err;
  118. if(errno == ECONNREFUSED)
  119. Owner->SetFailReason("ConnectionRefused");
  120. else if (errno == ETIMEDOUT)
  121. Owner->SetFailReason("ConnectionTimedOut");
  122. bad_addr.insert(bad_addr.begin(), std::string(Name));
  123. return _error->Errno("connect",_("Could not connect to %s:%s (%s)."),Host.c_str(),
  124. Service,Name);
  125. }
  126. return true;
  127. }
  128. /*}}}*/
  129. // Connect to a given Hostname /*{{{*/
  130. static bool ConnectToHostname(std::string const &Host, int const Port,
  131. const char * const Service, int DefPort, int &Fd,
  132. unsigned long const TimeOut, pkgAcqMethod * const Owner)
  133. {
  134. if (ConnectionAllowed(Service, Host) == false)
  135. return false;
  136. // Convert the port name/number
  137. char ServStr[300];
  138. if (Port != 0)
  139. snprintf(ServStr,sizeof(ServStr),"%i", Port);
  140. else
  141. snprintf(ServStr,sizeof(ServStr),"%s", Service);
  142. /* We used a cached address record.. Yes this is against the spec but
  143. the way we have setup our rotating dns suggests that this is more
  144. sensible */
  145. if (LastHost != Host || LastPort != Port)
  146. {
  147. Owner->Status(_("Connecting to %s"),Host.c_str());
  148. // Free the old address structure
  149. if (LastHostAddr != 0)
  150. {
  151. freeaddrinfo(LastHostAddr);
  152. LastHostAddr = 0;
  153. LastUsed = 0;
  154. }
  155. // We only understand SOCK_STREAM sockets.
  156. struct addrinfo Hints;
  157. memset(&Hints,0,sizeof(Hints));
  158. Hints.ai_socktype = SOCK_STREAM;
  159. Hints.ai_flags = 0;
  160. if (_config->FindB("Acquire::Connect::IDN", true) == true)
  161. Hints.ai_flags |= AI_IDN;
  162. // see getaddrinfo(3): only return address if system has such a address configured
  163. // useful if system is ipv4 only, to not get ipv6, but that fails if the system has
  164. // no address configured: e.g. offline and trying to connect to localhost.
  165. if (_config->FindB("Acquire::Connect::AddrConfig", true) == true)
  166. Hints.ai_flags |= AI_ADDRCONFIG;
  167. Hints.ai_protocol = 0;
  168. if(_config->FindB("Acquire::ForceIPv4", false) == true)
  169. Hints.ai_family = AF_INET;
  170. else if(_config->FindB("Acquire::ForceIPv6", false) == true)
  171. Hints.ai_family = AF_INET6;
  172. else
  173. Hints.ai_family = AF_UNSPEC;
  174. // if we couldn't resolve the host before, we don't try now
  175. if(bad_addr.find(Host) != bad_addr.end())
  176. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  177. // Resolve both the host and service simultaneously
  178. while (1)
  179. {
  180. int Res;
  181. if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
  182. LastHostAddr == 0)
  183. {
  184. if (Res == EAI_NONAME || Res == EAI_SERVICE)
  185. {
  186. if (DefPort != 0)
  187. {
  188. snprintf(ServStr, sizeof(ServStr), "%i", DefPort);
  189. DefPort = 0;
  190. continue;
  191. }
  192. bad_addr.insert(bad_addr.begin(), Host);
  193. Owner->SetFailReason("ResolveFailure");
  194. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  195. }
  196. if (Res == EAI_AGAIN)
  197. {
  198. Owner->SetFailReason("TmpResolveFailure");
  199. return _error->Error(_("Temporary failure resolving '%s'"),
  200. Host.c_str());
  201. }
  202. if (Res == EAI_SYSTEM)
  203. return _error->Errno("getaddrinfo", _("System error resolving '%s:%s'"),
  204. Host.c_str(),ServStr);
  205. return _error->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
  206. Host.c_str(),ServStr,Res,gai_strerror(Res));
  207. }
  208. break;
  209. }
  210. LastHost = Host;
  211. LastPort = Port;
  212. }
  213. // When we have an IP rotation stay with the last IP.
  214. struct addrinfo *CurHost = LastHostAddr;
  215. if (LastUsed != 0)
  216. CurHost = LastUsed;
  217. while (CurHost != 0)
  218. {
  219. if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
  220. {
  221. LastUsed = CurHost;
  222. return true;
  223. }
  224. close(Fd);
  225. Fd = -1;
  226. // Ignore UNIX domain sockets
  227. do
  228. {
  229. CurHost = CurHost->ai_next;
  230. }
  231. while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
  232. /* If we reached the end of the search list then wrap around to the
  233. start */
  234. if (CurHost == 0 && LastUsed != 0)
  235. CurHost = LastHostAddr;
  236. // Reached the end of the search cycle
  237. if (CurHost == LastUsed)
  238. break;
  239. if (CurHost != 0)
  240. _error->Discard();
  241. }
  242. if (_error->PendingError() == true)
  243. return false;
  244. return _error->Error(_("Unable to connect to %s:%s:"),Host.c_str(),ServStr);
  245. }
  246. /*}}}*/
  247. // Connect - Connect to a server /*{{{*/
  248. // ---------------------------------------------------------------------
  249. /* Performs a connection to the server (including SRV record lookup) */
  250. bool Connect(std::string Host,int Port,const char *Service,
  251. int DefPort,int &Fd,
  252. unsigned long TimeOut,pkgAcqMethod *Owner)
  253. {
  254. if (_error->PendingError() == true)
  255. return false;
  256. if (ConnectionAllowed(Service, Host) == false)
  257. return false;
  258. if(LastHost != Host || LastPort != Port)
  259. {
  260. SrvRecords.clear();
  261. if (_config->FindB("Acquire::EnableSrvRecords", true) == true)
  262. GetSrvRecords(Host, DefPort, SrvRecords);
  263. }
  264. size_t stackSize = 0;
  265. // try to connect in the priority order of the srv records
  266. std::string initialHost{std::move(Host)};
  267. while(SrvRecords.empty() == false)
  268. {
  269. _error->PushToStack();
  270. ++stackSize;
  271. // PopFromSrvRecs will also remove the server
  272. Host = PopFromSrvRecs(SrvRecords).target;
  273. auto const ret = ConnectToHostname(Host, Port, Service, DefPort, Fd, TimeOut, Owner);
  274. if (ret)
  275. {
  276. while(stackSize--)
  277. _error->RevertToStack();
  278. return true;
  279. }
  280. }
  281. Host = std::move(initialHost);
  282. // we have no (good) SrvRecords for this host, connect right away
  283. _error->PushToStack();
  284. ++stackSize;
  285. auto const ret = ConnectToHostname(Host, Port, Service, DefPort, Fd,
  286. TimeOut, Owner);
  287. while(stackSize--)
  288. if (ret)
  289. _error->RevertToStack();
  290. else
  291. _error->MergeWithStack();
  292. return ret;
  293. }