connect.cc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. // DoConnect - Attempt a connect operation /*{{{*/
  54. // ---------------------------------------------------------------------
  55. /* This helper function attempts a connection to a single address. */
  56. static bool DoConnect(struct addrinfo *Addr,std::string Host,
  57. unsigned long TimeOut,int &Fd,pkgAcqMethod *Owner)
  58. {
  59. // Show a status indicator
  60. char Name[NI_MAXHOST];
  61. char Service[NI_MAXSERV];
  62. Name[0] = 0;
  63. Service[0] = 0;
  64. getnameinfo(Addr->ai_addr,Addr->ai_addrlen,
  65. Name,sizeof(Name),Service,sizeof(Service),
  66. NI_NUMERICHOST|NI_NUMERICSERV);
  67. Owner->Status(_("Connecting to %s (%s)"),Host.c_str(),Name);
  68. // if that addr did timeout before, we do not try it again
  69. if(bad_addr.find(std::string(Name)) != bad_addr.end())
  70. return false;
  71. /* If this is an IP rotation store the IP we are using.. If something goes
  72. wrong this will get tacked onto the end of the error message */
  73. if (LastHostAddr->ai_next != 0)
  74. {
  75. std::stringstream ss;
  76. ioprintf(ss, _("[IP: %s %s]"),Name,Service);
  77. Owner->SetIP(ss.str());
  78. }
  79. // Get a socket
  80. if ((Fd = socket(Addr->ai_family,Addr->ai_socktype,
  81. Addr->ai_protocol)) < 0)
  82. return _error->Errno("socket",_("Could not create a socket for %s (f=%u t=%u p=%u)"),
  83. Name,Addr->ai_family,Addr->ai_socktype,Addr->ai_protocol);
  84. SetNonBlock(Fd,true);
  85. if (connect(Fd,Addr->ai_addr,Addr->ai_addrlen) < 0 &&
  86. errno != EINPROGRESS)
  87. return _error->Errno("connect",_("Cannot initiate the connection "
  88. "to %s:%s (%s)."),Host.c_str(),Service,Name);
  89. /* This implements a timeout for connect by opening the connection
  90. nonblocking */
  91. if (WaitFd(Fd,true,TimeOut) == false) {
  92. bad_addr.insert(bad_addr.begin(), std::string(Name));
  93. Owner->SetFailReason("Timeout");
  94. return _error->Error(_("Could not connect to %s:%s (%s), "
  95. "connection timed out"),Host.c_str(),Service,Name);
  96. }
  97. // Check the socket for an error condition
  98. unsigned int Err;
  99. unsigned int Len = sizeof(Err);
  100. if (getsockopt(Fd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  101. return _error->Errno("getsockopt",_("Failed"));
  102. if (Err != 0)
  103. {
  104. errno = Err;
  105. if(errno == ECONNREFUSED)
  106. Owner->SetFailReason("ConnectionRefused");
  107. else if (errno == ETIMEDOUT)
  108. Owner->SetFailReason("ConnectionTimedOut");
  109. bad_addr.insert(bad_addr.begin(), std::string(Name));
  110. return _error->Errno("connect",_("Could not connect to %s:%s (%s)."),Host.c_str(),
  111. Service,Name);
  112. }
  113. return true;
  114. }
  115. /*}}}*/
  116. // Connect to a given Hostname /*{{{*/
  117. static bool ConnectToHostname(std::string const &Host, int const Port,
  118. const char * const Service, int DefPort, int &Fd,
  119. unsigned long const TimeOut, pkgAcqMethod * const Owner)
  120. {
  121. // Convert the port name/number
  122. char ServStr[300];
  123. if (Port != 0)
  124. snprintf(ServStr,sizeof(ServStr),"%i", Port);
  125. else
  126. snprintf(ServStr,sizeof(ServStr),"%s", Service);
  127. /* We used a cached address record.. Yes this is against the spec but
  128. the way we have setup our rotating dns suggests that this is more
  129. sensible */
  130. if (LastHost != Host || LastPort != Port)
  131. {
  132. Owner->Status(_("Connecting to %s"),Host.c_str());
  133. // Free the old address structure
  134. if (LastHostAddr != 0)
  135. {
  136. freeaddrinfo(LastHostAddr);
  137. LastHostAddr = 0;
  138. LastUsed = 0;
  139. }
  140. // We only understand SOCK_STREAM sockets.
  141. struct addrinfo Hints;
  142. memset(&Hints,0,sizeof(Hints));
  143. Hints.ai_socktype = SOCK_STREAM;
  144. Hints.ai_flags = 0;
  145. // see getaddrinfo(3): only return address if system has such a address configured
  146. // useful if system is ipv4 only, to not get ipv6, but that fails if the system has
  147. // no address configured: e.g. offline and trying to connect to localhost.
  148. if (_config->FindB("Acquire::Connect::AddrConfig", true) == true)
  149. Hints.ai_flags |= AI_ADDRCONFIG;
  150. Hints.ai_protocol = 0;
  151. if(_config->FindB("Acquire::ForceIPv4", false) == true)
  152. Hints.ai_family = AF_INET;
  153. else if(_config->FindB("Acquire::ForceIPv6", false) == true)
  154. Hints.ai_family = AF_INET6;
  155. else
  156. Hints.ai_family = AF_UNSPEC;
  157. // if we couldn't resolve the host before, we don't try now
  158. if(bad_addr.find(Host) != bad_addr.end())
  159. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  160. // Resolve both the host and service simultaneously
  161. while (1)
  162. {
  163. int Res;
  164. if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
  165. LastHostAddr == 0)
  166. {
  167. if (Res == EAI_NONAME || Res == EAI_SERVICE)
  168. {
  169. if (DefPort != 0)
  170. {
  171. snprintf(ServStr, sizeof(ServStr), "%i", DefPort);
  172. DefPort = 0;
  173. continue;
  174. }
  175. bad_addr.insert(bad_addr.begin(), Host);
  176. Owner->SetFailReason("ResolveFailure");
  177. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  178. }
  179. if (Res == EAI_AGAIN)
  180. {
  181. Owner->SetFailReason("TmpResolveFailure");
  182. return _error->Error(_("Temporary failure resolving '%s'"),
  183. Host.c_str());
  184. }
  185. if (Res == EAI_SYSTEM)
  186. return _error->Errno("getaddrinfo", _("System error resolving '%s:%s'"),
  187. Host.c_str(),ServStr);
  188. return _error->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
  189. Host.c_str(),ServStr,Res,gai_strerror(Res));
  190. }
  191. break;
  192. }
  193. LastHost = Host;
  194. LastPort = Port;
  195. }
  196. // When we have an IP rotation stay with the last IP.
  197. struct addrinfo *CurHost = LastHostAddr;
  198. if (LastUsed != 0)
  199. CurHost = LastUsed;
  200. while (CurHost != 0)
  201. {
  202. if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
  203. {
  204. LastUsed = CurHost;
  205. return true;
  206. }
  207. close(Fd);
  208. Fd = -1;
  209. // Ignore UNIX domain sockets
  210. do
  211. {
  212. CurHost = CurHost->ai_next;
  213. }
  214. while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
  215. /* If we reached the end of the search list then wrap around to the
  216. start */
  217. if (CurHost == 0 && LastUsed != 0)
  218. CurHost = LastHostAddr;
  219. // Reached the end of the search cycle
  220. if (CurHost == LastUsed)
  221. break;
  222. if (CurHost != 0)
  223. _error->Discard();
  224. }
  225. if (_error->PendingError() == true)
  226. return false;
  227. return _error->Error(_("Unable to connect to %s:%s:"),Host.c_str(),ServStr);
  228. }
  229. /*}}}*/
  230. // Connect - Connect to a server /*{{{*/
  231. // ---------------------------------------------------------------------
  232. /* Performs a connection to the server (including SRV record lookup) */
  233. bool Connect(std::string Host,int Port,const char *Service,
  234. int DefPort,int &Fd,
  235. unsigned long TimeOut,pkgAcqMethod *Owner)
  236. {
  237. if (_error->PendingError() == true)
  238. return false;
  239. if(LastHost != Host || LastPort != Port)
  240. {
  241. SrvRecords.clear();
  242. if (_config->FindB("Acquire::EnableSrvRecords", true) == true)
  243. GetSrvRecords(Host, DefPort, SrvRecords);
  244. }
  245. // we have no SrvRecords for this host, connect right away
  246. if(SrvRecords.size() == 0)
  247. return ConnectToHostname(Host, Port, Service, DefPort, Fd,
  248. TimeOut, Owner);
  249. // try to connect in the priority order of the srv records
  250. while(SrvRecords.size() > 0)
  251. {
  252. Host = PopFromSrvRecs(SrvRecords).target;
  253. if(ConnectToHostname(Host, Port, Service, DefPort, Fd, TimeOut, Owner))
  254. return true;
  255. // we couldn't connect to this one, use the next
  256. SrvRecords.erase(SrvRecords.begin());
  257. }
  258. return false;
  259. }