connect.cc 7.2 KB

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