connect.cc 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 <stdio.h>
  18. #include <errno.h>
  19. #include <unistd.h>
  20. #include <sstream>
  21. #include<set>
  22. #include<string>
  23. // Internet stuff
  24. #include <netinet/in.h>
  25. #include <sys/socket.h>
  26. #include <arpa/inet.h>
  27. #include <netdb.h>
  28. #include "connect.h"
  29. #include "rfc2553emu.h"
  30. #include <apti18n.h>
  31. /*}}}*/
  32. static std::string LastHost;
  33. static int LastPort = 0;
  34. static struct addrinfo *LastHostAddr = 0;
  35. static struct addrinfo *LastUsed = 0;
  36. // Set of IP/hostnames that we timed out before or couldn't resolve
  37. static std::set<std::string> bad_addr;
  38. // RotateDNS - Select a new server from a DNS rotation /*{{{*/
  39. // ---------------------------------------------------------------------
  40. /* This is called during certain errors in order to recover by selecting a
  41. new server */
  42. void RotateDNS()
  43. {
  44. if (LastUsed != 0 && LastUsed->ai_next != 0)
  45. LastUsed = LastUsed->ai_next;
  46. else
  47. LastUsed = LastHostAddr;
  48. }
  49. /*}}}*/
  50. // DoConnect - Attempt a connect operation /*{{{*/
  51. // ---------------------------------------------------------------------
  52. /* This helper function attempts a connection to a single address. */
  53. static bool DoConnect(struct addrinfo *Addr,std::string Host,
  54. unsigned long TimeOut,int &Fd,pkgAcqMethod *Owner)
  55. {
  56. // Show a status indicator
  57. char Name[NI_MAXHOST];
  58. char Service[NI_MAXSERV];
  59. Name[0] = 0;
  60. Service[0] = 0;
  61. getnameinfo(Addr->ai_addr,Addr->ai_addrlen,
  62. Name,sizeof(Name),Service,sizeof(Service),
  63. NI_NUMERICHOST|NI_NUMERICSERV);
  64. Owner->Status(_("Connecting to %s (%s)"),Host.c_str(),Name);
  65. // if that addr did timeout before, we do not try it again
  66. if(bad_addr.find(std::string(Name)) != bad_addr.end())
  67. return false;
  68. /* If this is an IP rotation store the IP we are using.. If something goes
  69. wrong this will get tacked onto the end of the error message */
  70. if (LastHostAddr->ai_next != 0)
  71. {
  72. std::stringstream ss;
  73. ioprintf(ss, _("[IP: %s %s]"),Name,Service);
  74. Owner->SetIP(ss.str());
  75. }
  76. // Get a socket
  77. if ((Fd = socket(Addr->ai_family,Addr->ai_socktype,
  78. Addr->ai_protocol)) < 0)
  79. return _error->Errno("socket",_("Could not create a socket for %s (f=%u t=%u p=%u)"),
  80. Name,Addr->ai_family,Addr->ai_socktype,Addr->ai_protocol);
  81. SetNonBlock(Fd,true);
  82. if (connect(Fd,Addr->ai_addr,Addr->ai_addrlen) < 0 &&
  83. errno != EINPROGRESS)
  84. return _error->Errno("connect",_("Cannot initiate the connection "
  85. "to %s:%s (%s)."),Host.c_str(),Service,Name);
  86. /* This implements a timeout for connect by opening the connection
  87. nonblocking */
  88. if (WaitFd(Fd,true,TimeOut) == false) {
  89. bad_addr.insert(bad_addr.begin(), std::string(Name));
  90. Owner->SetFailReason("Timeout");
  91. return _error->Error(_("Could not connect to %s:%s (%s), "
  92. "connection timed out"),Host.c_str(),Service,Name);
  93. }
  94. // Check the socket for an error condition
  95. unsigned int Err;
  96. unsigned int Len = sizeof(Err);
  97. if (getsockopt(Fd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  98. return _error->Errno("getsockopt",_("Failed"));
  99. if (Err != 0)
  100. {
  101. errno = Err;
  102. if(errno == ECONNREFUSED)
  103. Owner->SetFailReason("ConnectionRefused");
  104. else if (errno == ETIMEDOUT)
  105. Owner->SetFailReason("ConnectionTimedOut");
  106. bad_addr.insert(bad_addr.begin(), std::string(Name));
  107. return _error->Errno("connect",_("Could not connect to %s:%s (%s)."),Host.c_str(),
  108. Service,Name);
  109. }
  110. return true;
  111. }
  112. /*}}}*/
  113. // Connect - Connect to a server /*{{{*/
  114. // ---------------------------------------------------------------------
  115. /* Performs a connection to the server */
  116. bool Connect(std::string Host,int Port,const char *Service,int DefPort,int &Fd,
  117. unsigned long TimeOut,pkgAcqMethod *Owner)
  118. {
  119. if (_error->PendingError() == true)
  120. return false;
  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. /*}}}*/