connect.cc 6.5 KB

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