connect.cc 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: connect.cc,v 1.11 2004/01/07 20:39:38 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. return _error->Error(_("Could not connect to %s:%s (%s), "
  80. "connection timed out"),Host.c_str(),Service,Name);
  81. // Check the socket for an error condition
  82. unsigned int Err;
  83. unsigned int Len = sizeof(Err);
  84. if (getsockopt(Fd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  85. return _error->Errno("getsockopt",_("Failed"));
  86. if (Err != 0)
  87. {
  88. errno = Err;
  89. return _error->Errno("connect",_("Could not connect to %s:%s (%s)."),Host.c_str(),
  90. Service,Name);
  91. }
  92. return true;
  93. }
  94. /*}}}*/
  95. // Connect - Connect to a server /*{{{*/
  96. // ---------------------------------------------------------------------
  97. /* Performs a connection to the server */
  98. bool Connect(string Host,int Port,const char *Service,int DefPort,int &Fd,
  99. unsigned long TimeOut,pkgAcqMethod *Owner)
  100. {
  101. if (_error->PendingError() == true)
  102. return false;
  103. // Convert the port name/number
  104. char ServStr[300];
  105. if (Port != 0)
  106. snprintf(ServStr,sizeof(ServStr),"%u",Port);
  107. else
  108. snprintf(ServStr,sizeof(ServStr),"%s",Service);
  109. /* We used a cached address record.. Yes this is against the spec but
  110. the way we have setup our rotating dns suggests that this is more
  111. sensible */
  112. if (LastHost != Host || LastPort != Port)
  113. {
  114. Owner->Status(_("Connecting to %s"),Host.c_str());
  115. // Free the old address structure
  116. if (LastHostAddr != 0)
  117. {
  118. freeaddrinfo(LastHostAddr);
  119. LastHostAddr = 0;
  120. LastUsed = 0;
  121. }
  122. // We only understand SOCK_STREAM sockets.
  123. struct addrinfo Hints;
  124. memset(&Hints,0,sizeof(Hints));
  125. Hints.ai_socktype = SOCK_STREAM;
  126. Hints.ai_protocol = 0;
  127. // Resolve both the host and service simultaneously
  128. while (1)
  129. {
  130. int Res;
  131. if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
  132. LastHostAddr == 0)
  133. {
  134. if (Res == EAI_NONAME || Res == EAI_SERVICE)
  135. {
  136. if (DefPort != 0)
  137. {
  138. snprintf(ServStr,sizeof(ServStr),"%u",DefPort);
  139. DefPort = 0;
  140. continue;
  141. }
  142. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  143. }
  144. if (Res == EAI_AGAIN)
  145. return _error->Error(_("Temporary failure resolving '%s'"),
  146. Host.c_str());
  147. return _error->Error(_("Something wicked happened resolving '%s:%s' (%i)"),
  148. Host.c_str(),ServStr,Res);
  149. }
  150. break;
  151. }
  152. LastHost = Host;
  153. LastPort = Port;
  154. }
  155. // When we have an IP rotation stay with the last IP.
  156. struct addrinfo *CurHost = LastHostAddr;
  157. if (LastUsed != 0)
  158. CurHost = LastUsed;
  159. while (CurHost != 0)
  160. {
  161. if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
  162. {
  163. LastUsed = CurHost;
  164. return true;
  165. }
  166. close(Fd);
  167. Fd = -1;
  168. // Ignore UNIX domain sockets
  169. do
  170. {
  171. CurHost = CurHost->ai_next;
  172. }
  173. while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
  174. /* If we reached the end of the search list then wrap around to the
  175. start */
  176. if (CurHost == 0 && LastUsed != 0)
  177. CurHost = LastHostAddr;
  178. // Reached the end of the search cycle
  179. if (CurHost == LastUsed)
  180. break;
  181. if (CurHost != 0)
  182. _error->Discard();
  183. }
  184. if (_error->PendingError() == true)
  185. return false;
  186. return _error->Error(_("Unable to connect to %s %s:"),Host.c_str(),ServStr);
  187. }
  188. /*}}}*/