connect.cc 7.0 KB

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