connect.cc 7.3 KB

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