connect.cc 8.9 KB

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