connect.cc 6.6 KB

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