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