connect.cc 6.3 KB

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