connect.cc 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. else if (errno == ETIMEDOUT)
  101. Owner->SetFailReason("ConnectionTimedOut");
  102. bad_addr.insert(bad_addr.begin(), string(Name));
  103. return _error->Errno("connect",_("Could not connect to %s:%s (%s)."),Host.c_str(),
  104. Service,Name);
  105. }
  106. return true;
  107. }
  108. /*}}}*/
  109. // Connect - Connect to a server /*{{{*/
  110. // ---------------------------------------------------------------------
  111. /* Performs a connection to the server */
  112. bool Connect(string Host,int Port,const char *Service,int DefPort,int &Fd,
  113. unsigned long TimeOut,pkgAcqMethod *Owner)
  114. {
  115. if (_error->PendingError() == true)
  116. return false;
  117. // Convert the port name/number
  118. char ServStr[300];
  119. if (Port != 0)
  120. snprintf(ServStr,sizeof(ServStr),"%u",Port);
  121. else
  122. snprintf(ServStr,sizeof(ServStr),"%s",Service);
  123. /* We used a cached address record.. Yes this is against the spec but
  124. the way we have setup our rotating dns suggests that this is more
  125. sensible */
  126. if (LastHost != Host || LastPort != Port)
  127. {
  128. Owner->Status(_("Connecting to %s"),Host.c_str());
  129. // Free the old address structure
  130. if (LastHostAddr != 0)
  131. {
  132. freeaddrinfo(LastHostAddr);
  133. LastHostAddr = 0;
  134. LastUsed = 0;
  135. }
  136. // We only understand SOCK_STREAM sockets.
  137. struct addrinfo Hints;
  138. memset(&Hints,0,sizeof(Hints));
  139. Hints.ai_socktype = SOCK_STREAM;
  140. Hints.ai_flags = AI_ADDRCONFIG;
  141. Hints.ai_protocol = 0;
  142. // if we couldn't resolve the host before, we don't try now
  143. if(bad_addr.find(Host) != bad_addr.end())
  144. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  145. // Resolve both the host and service simultaneously
  146. while (1)
  147. {
  148. int Res;
  149. if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
  150. LastHostAddr == 0)
  151. {
  152. if (Res == EAI_NONAME || Res == EAI_SERVICE)
  153. {
  154. if (DefPort != 0)
  155. {
  156. snprintf(ServStr,sizeof(ServStr),"%u",DefPort);
  157. DefPort = 0;
  158. continue;
  159. }
  160. bad_addr.insert(bad_addr.begin(), Host);
  161. Owner->SetFailReason("ResolveFailure");
  162. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  163. }
  164. if (Res == EAI_AGAIN)
  165. {
  166. Owner->SetFailReason("TmpResolveFailure");
  167. return _error->Error(_("Temporary failure resolving '%s'"),
  168. Host.c_str());
  169. }
  170. return _error->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
  171. Host.c_str(),ServStr,Res,gai_strerror(Res));
  172. }
  173. break;
  174. }
  175. LastHost = Host;
  176. LastPort = Port;
  177. }
  178. // When we have an IP rotation stay with the last IP.
  179. struct addrinfo *CurHost = LastHostAddr;
  180. if (LastUsed != 0)
  181. CurHost = LastUsed;
  182. while (CurHost != 0)
  183. {
  184. if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
  185. {
  186. LastUsed = CurHost;
  187. return true;
  188. }
  189. close(Fd);
  190. Fd = -1;
  191. // Ignore UNIX domain sockets
  192. do
  193. {
  194. CurHost = CurHost->ai_next;
  195. }
  196. while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
  197. /* If we reached the end of the search list then wrap around to the
  198. start */
  199. if (CurHost == 0 && LastUsed != 0)
  200. CurHost = LastHostAddr;
  201. // Reached the end of the search cycle
  202. if (CurHost == LastUsed)
  203. break;
  204. if (CurHost != 0)
  205. _error->Discard();
  206. }
  207. if (_error->PendingError() == true)
  208. return false;
  209. return _error->Error(_("Unable to connect to %s:%s:"),Host.c_str(),ServStr);
  210. }
  211. /*}}}*/