connect.cc 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 = AI_ADDRCONFIG;
  145. Hints.ai_protocol = 0;
  146. if(_config->FindB("Acquire::ForceIPv4", false) == true)
  147. Hints.ai_family = AF_INET;
  148. else if(_config->FindB("Acquire::ForceIPv6", false) == true)
  149. Hints.ai_family = AF_INET6;
  150. else
  151. Hints.ai_family = AF_UNSPEC;
  152. // if we couldn't resolve the host before, we don't try now
  153. if(bad_addr.find(Host) != bad_addr.end())
  154. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  155. // Resolve both the host and service simultaneously
  156. while (1)
  157. {
  158. int Res;
  159. if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
  160. LastHostAddr == 0)
  161. {
  162. if (Res == EAI_NONAME || Res == EAI_SERVICE)
  163. {
  164. if (DefPort != 0)
  165. {
  166. snprintf(ServStr, sizeof(ServStr), "%i", DefPort);
  167. DefPort = 0;
  168. continue;
  169. }
  170. bad_addr.insert(bad_addr.begin(), Host);
  171. Owner->SetFailReason("ResolveFailure");
  172. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  173. }
  174. if (Res == EAI_AGAIN)
  175. {
  176. Owner->SetFailReason("TmpResolveFailure");
  177. return _error->Error(_("Temporary failure resolving '%s'"),
  178. Host.c_str());
  179. }
  180. if (Res == EAI_SYSTEM)
  181. return _error->Errno("getaddrinfo", _("System error resolving '%s:%s'"),
  182. Host.c_str(),ServStr);
  183. return _error->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
  184. Host.c_str(),ServStr,Res,gai_strerror(Res));
  185. }
  186. break;
  187. }
  188. LastHost = Host;
  189. LastPort = Port;
  190. }
  191. // When we have an IP rotation stay with the last IP.
  192. struct addrinfo *CurHost = LastHostAddr;
  193. if (LastUsed != 0)
  194. CurHost = LastUsed;
  195. while (CurHost != 0)
  196. {
  197. if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
  198. {
  199. LastUsed = CurHost;
  200. return true;
  201. }
  202. close(Fd);
  203. Fd = -1;
  204. // Ignore UNIX domain sockets
  205. do
  206. {
  207. CurHost = CurHost->ai_next;
  208. }
  209. while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
  210. /* If we reached the end of the search list then wrap around to the
  211. start */
  212. if (CurHost == 0 && LastUsed != 0)
  213. CurHost = LastHostAddr;
  214. // Reached the end of the search cycle
  215. if (CurHost == LastUsed)
  216. break;
  217. if (CurHost != 0)
  218. _error->Discard();
  219. }
  220. if (_error->PendingError() == true)
  221. return false;
  222. return _error->Error(_("Unable to connect to %s:%s:"),Host.c_str(),ServStr);
  223. }
  224. /*}}}*/
  225. // Connect - Connect to a server /*{{{*/
  226. // ---------------------------------------------------------------------
  227. /* Performs a connection to the server (including SRV record lookup) */
  228. bool Connect(std::string Host,int Port,const char *Service,
  229. int DefPort,int &Fd,
  230. unsigned long TimeOut,pkgAcqMethod *Owner)
  231. {
  232. if (_error->PendingError() == true)
  233. return false;
  234. if(LastHost != Host || LastPort != Port)
  235. {
  236. SrvRecords.clear();
  237. if (_config->FindB("Acquire::EnableSrvRecords", true) == true)
  238. GetSrvRecords(Host, DefPort, SrvRecords);
  239. }
  240. // we have no SrvRecords for this host, connect right away
  241. if(SrvRecords.size() == 0)
  242. return ConnectToHostname(Host, Port, Service, DefPort, Fd,
  243. TimeOut, Owner);
  244. // try to connect in the priority order of the srv records
  245. while(SrvRecords.size() > 0)
  246. {
  247. Host = PopFromSrvRecs(SrvRecords).target;
  248. if(ConnectToHostname(Host, Port, Service, DefPort, Fd, TimeOut, Owner))
  249. return true;
  250. // we couldn't connect to this one, use the next
  251. SrvRecords.erase(SrvRecords.begin());
  252. }
  253. return false;
  254. }