connect.cc 7.3 KB

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