connect.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. #ifdef AI_IDN
  161. if (_config->FindB("Acquire::Connect::IDN", true) == true)
  162. Hints.ai_flags |= AI_IDN;
  163. #endif
  164. // see getaddrinfo(3): only return address if system has such a address configured
  165. // useful if system is ipv4 only, to not get ipv6, but that fails if the system has
  166. // no address configured: e.g. offline and trying to connect to localhost.
  167. if (_config->FindB("Acquire::Connect::AddrConfig", true) == true)
  168. Hints.ai_flags |= AI_ADDRCONFIG;
  169. Hints.ai_protocol = 0;
  170. if(_config->FindB("Acquire::ForceIPv4", false) == true)
  171. Hints.ai_family = AF_INET;
  172. else if(_config->FindB("Acquire::ForceIPv6", false) == true)
  173. Hints.ai_family = AF_INET6;
  174. else
  175. Hints.ai_family = AF_UNSPEC;
  176. // if we couldn't resolve the host before, we don't try now
  177. if(bad_addr.find(Host) != bad_addr.end())
  178. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  179. // Resolve both the host and service simultaneously
  180. while (1)
  181. {
  182. int Res;
  183. if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
  184. LastHostAddr == 0)
  185. {
  186. if (Res == EAI_NONAME || Res == EAI_SERVICE)
  187. {
  188. if (DefPort != 0)
  189. {
  190. snprintf(ServStr, sizeof(ServStr), "%i", DefPort);
  191. DefPort = 0;
  192. continue;
  193. }
  194. bad_addr.insert(bad_addr.begin(), Host);
  195. Owner->SetFailReason("ResolveFailure");
  196. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  197. }
  198. if (Res == EAI_AGAIN)
  199. {
  200. Owner->SetFailReason("TmpResolveFailure");
  201. return _error->Error(_("Temporary failure resolving '%s'"),
  202. Host.c_str());
  203. }
  204. if (Res == EAI_SYSTEM)
  205. return _error->Errno("getaddrinfo", _("System error resolving '%s:%s'"),
  206. Host.c_str(),ServStr);
  207. return _error->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
  208. Host.c_str(),ServStr,Res,gai_strerror(Res));
  209. }
  210. break;
  211. }
  212. LastHost = Host;
  213. LastPort = Port;
  214. }
  215. // When we have an IP rotation stay with the last IP.
  216. struct addrinfo *CurHost = LastHostAddr;
  217. if (LastUsed != 0)
  218. CurHost = LastUsed;
  219. while (CurHost != 0)
  220. {
  221. if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
  222. {
  223. LastUsed = CurHost;
  224. return true;
  225. }
  226. close(Fd);
  227. Fd = -1;
  228. // Ignore UNIX domain sockets
  229. do
  230. {
  231. CurHost = CurHost->ai_next;
  232. }
  233. while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
  234. /* If we reached the end of the search list then wrap around to the
  235. start */
  236. if (CurHost == 0 && LastUsed != 0)
  237. CurHost = LastHostAddr;
  238. // Reached the end of the search cycle
  239. if (CurHost == LastUsed)
  240. break;
  241. if (CurHost != 0)
  242. _error->Discard();
  243. }
  244. if (_error->PendingError() == true)
  245. return false;
  246. return _error->Error(_("Unable to connect to %s:%s:"),Host.c_str(),ServStr);
  247. }
  248. /*}}}*/
  249. // Connect - Connect to a server /*{{{*/
  250. // ---------------------------------------------------------------------
  251. /* Performs a connection to the server (including SRV record lookup) */
  252. bool Connect(std::string Host,int Port,const char *Service,
  253. int DefPort,int &Fd,
  254. unsigned long TimeOut,pkgAcqMethod *Owner)
  255. {
  256. if (_error->PendingError() == true)
  257. return false;
  258. if (ConnectionAllowed(Service, Host) == false)
  259. return false;
  260. if(LastHost != Host || LastPort != Port)
  261. {
  262. SrvRecords.clear();
  263. if (_config->FindB("Acquire::EnableSrvRecords", true) == true)
  264. GetSrvRecords(Host, DefPort, SrvRecords);
  265. }
  266. size_t stackSize = 0;
  267. // try to connect in the priority order of the srv records
  268. std::string initialHost{std::move(Host)};
  269. while(SrvRecords.empty() == false)
  270. {
  271. _error->PushToStack();
  272. ++stackSize;
  273. // PopFromSrvRecs will also remove the server
  274. Host = PopFromSrvRecs(SrvRecords).target;
  275. auto const ret = ConnectToHostname(Host, Port, Service, DefPort, Fd, TimeOut, Owner);
  276. if (ret)
  277. {
  278. while(stackSize--)
  279. _error->RevertToStack();
  280. return true;
  281. }
  282. }
  283. Host = std::move(initialHost);
  284. // we have no (good) SrvRecords for this host, connect right away
  285. _error->PushToStack();
  286. ++stackSize;
  287. auto const ret = ConnectToHostname(Host, Port, Service, DefPort, Fd,
  288. TimeOut, Owner);
  289. while(stackSize--)
  290. if (ret)
  291. _error->RevertToStack();
  292. else
  293. _error->MergeWithStack();
  294. return ret;
  295. }