connect.cc 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 <config.h>
  12. #include <apt-pkg/error.h>
  13. #include <apt-pkg/fileutl.h>
  14. #include <apt-pkg/strutl.h>
  15. #include <apt-pkg/acquire-method.h>
  16. #include <apt-pkg/configuration.h>
  17. #include <apt-pkg/srvrec.h>
  18. #include <stdio.h>
  19. #include <errno.h>
  20. #include <unistd.h>
  21. #include <sstream>
  22. #include <string.h>
  23. #include<set>
  24. #include<string>
  25. // Internet stuff
  26. #include <netinet/in.h>
  27. #include <sys/socket.h>
  28. #include <arpa/inet.h>
  29. #include <netdb.h>
  30. #include "connect.h"
  31. #include "rfc2553emu.h"
  32. #include <apti18n.h>
  33. /*}}}*/
  34. static std::string LastHost;
  35. static int LastPort = 0;
  36. static struct addrinfo *LastHostAddr = 0;
  37. static struct addrinfo *LastUsed = 0;
  38. static std::vector<SrvRec> SrvRecords;
  39. static int LastSrvRecord = 0;
  40. // Set of IP/hostnames that we timed out before or couldn't resolve
  41. static std::set<std::string> bad_addr;
  42. // RotateDNS - Select a new server from a DNS rotation /*{{{*/
  43. // ---------------------------------------------------------------------
  44. /* This is called during certain errors in order to recover by selecting a
  45. new server */
  46. void RotateDNS()
  47. {
  48. if (LastUsed != 0 && LastUsed->ai_next != 0)
  49. LastUsed = LastUsed->ai_next;
  50. else
  51. LastUsed = LastHostAddr;
  52. }
  53. /*}}}*/
  54. // DoConnect - Attempt a connect operation /*{{{*/
  55. // ---------------------------------------------------------------------
  56. /* This helper function attempts a connection to a single address. */
  57. static bool DoConnect(struct addrinfo *Addr,std::string Host,
  58. unsigned long TimeOut,int &Fd,pkgAcqMethod *Owner)
  59. {
  60. // Show a status indicator
  61. char Name[NI_MAXHOST];
  62. char Service[NI_MAXSERV];
  63. Name[0] = 0;
  64. Service[0] = 0;
  65. getnameinfo(Addr->ai_addr,Addr->ai_addrlen,
  66. Name,sizeof(Name),Service,sizeof(Service),
  67. NI_NUMERICHOST|NI_NUMERICSERV);
  68. Owner->Status(_("Connecting to %s (%s)"),Host.c_str(),Name);
  69. // if that addr did timeout before, we do not try it again
  70. if(bad_addr.find(std::string(Name)) != bad_addr.end())
  71. return false;
  72. /* If this is an IP rotation store the IP we are using.. If something goes
  73. wrong this will get tacked onto the end of the error message */
  74. if (LastHostAddr->ai_next != 0)
  75. {
  76. std::stringstream ss;
  77. ioprintf(ss, _("[IP: %s %s]"),Name,Service);
  78. Owner->SetIP(ss.str());
  79. }
  80. // Get a socket
  81. if ((Fd = socket(Addr->ai_family,Addr->ai_socktype,
  82. Addr->ai_protocol)) < 0)
  83. return _error->Errno("socket",_("Could not create a socket for %s (f=%u t=%u p=%u)"),
  84. Name,Addr->ai_family,Addr->ai_socktype,Addr->ai_protocol);
  85. SetNonBlock(Fd,true);
  86. if (connect(Fd,Addr->ai_addr,Addr->ai_addrlen) < 0 &&
  87. errno != EINPROGRESS)
  88. return _error->Errno("connect",_("Cannot initiate the connection "
  89. "to %s:%s (%s)."),Host.c_str(),Service,Name);
  90. /* This implements a timeout for connect by opening the connection
  91. nonblocking */
  92. if (WaitFd(Fd,true,TimeOut) == false) {
  93. bad_addr.insert(bad_addr.begin(), std::string(Name));
  94. Owner->SetFailReason("Timeout");
  95. return _error->Error(_("Could not connect to %s:%s (%s), "
  96. "connection timed out"),Host.c_str(),Service,Name);
  97. }
  98. // Check the socket for an error condition
  99. unsigned int Err;
  100. unsigned int Len = sizeof(Err);
  101. if (getsockopt(Fd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
  102. return _error->Errno("getsockopt",_("Failed"));
  103. if (Err != 0)
  104. {
  105. errno = Err;
  106. if(errno == ECONNREFUSED)
  107. Owner->SetFailReason("ConnectionRefused");
  108. else if (errno == ETIMEDOUT)
  109. Owner->SetFailReason("ConnectionTimedOut");
  110. bad_addr.insert(bad_addr.begin(), std::string(Name));
  111. return _error->Errno("connect",_("Could not connect to %s:%s (%s)."),Host.c_str(),
  112. Service,Name);
  113. }
  114. return true;
  115. }
  116. /*}}}*/
  117. // Connect - Connect to a server /*{{{*/
  118. // ---------------------------------------------------------------------
  119. /* Performs a connection to the server */
  120. bool Connect(std::string Host,int Port,const char *Service,int DefPort,int &Fd,
  121. unsigned long TimeOut,pkgAcqMethod *Owner)
  122. {
  123. if (_error->PendingError() == true)
  124. return false;
  125. // Convert the port name/number
  126. char ServStr[300];
  127. if (Port != 0)
  128. snprintf(ServStr,sizeof(ServStr),"%i", Port);
  129. else
  130. snprintf(ServStr,sizeof(ServStr),"%s", Service);
  131. /* We used a cached address record.. Yes this is against the spec but
  132. the way we have setup our rotating dns suggests that this is more
  133. sensible */
  134. if (LastHost != Host || LastPort != Port)
  135. {
  136. // FIXME: NOT READY FOR MERGING IN THIS FORM
  137. // we need to first check SRV, then round-robin DNS
  138. // this code will only ever use the first srv record
  139. // FIXME: ensure we cycle over the SrvRecords first before
  140. // we do round-robin IP
  141. if(GetSrvRecords(Host, Port, SrvRecords) && SrvRecords.size() > 0)
  142. Host = SrvRecords[0].target;
  143. Owner->Status(_("Connecting to %s"),Host.c_str());
  144. // Free the old address structure
  145. if (LastHostAddr != 0)
  146. {
  147. freeaddrinfo(LastHostAddr);
  148. LastHostAddr = 0;
  149. LastUsed = 0;
  150. }
  151. // We only understand SOCK_STREAM sockets.
  152. struct addrinfo Hints;
  153. memset(&Hints,0,sizeof(Hints));
  154. Hints.ai_socktype = SOCK_STREAM;
  155. Hints.ai_flags = AI_ADDRCONFIG;
  156. Hints.ai_protocol = 0;
  157. if(_config->FindB("Acquire::ForceIPv4", false) == true)
  158. Hints.ai_family = AF_INET;
  159. else if(_config->FindB("Acquire::ForceIPv6", false) == true)
  160. Hints.ai_family = AF_INET6;
  161. else
  162. Hints.ai_family = AF_UNSPEC;
  163. // if we couldn't resolve the host before, we don't try now
  164. if(bad_addr.find(Host) != bad_addr.end())
  165. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  166. // Resolve both the host and service simultaneously
  167. while (1)
  168. {
  169. int Res;
  170. if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
  171. LastHostAddr == 0)
  172. {
  173. if (Res == EAI_NONAME || Res == EAI_SERVICE)
  174. {
  175. if (DefPort != 0)
  176. {
  177. snprintf(ServStr, sizeof(ServStr), "%i", DefPort);
  178. DefPort = 0;
  179. continue;
  180. }
  181. bad_addr.insert(bad_addr.begin(), Host);
  182. Owner->SetFailReason("ResolveFailure");
  183. return _error->Error(_("Could not resolve '%s'"),Host.c_str());
  184. }
  185. if (Res == EAI_AGAIN)
  186. {
  187. Owner->SetFailReason("TmpResolveFailure");
  188. return _error->Error(_("Temporary failure resolving '%s'"),
  189. Host.c_str());
  190. }
  191. if (Res == EAI_SYSTEM)
  192. return _error->Errno("getaddrinfo", _("System error resolving '%s:%s'"),
  193. Host.c_str(),ServStr);
  194. return _error->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
  195. Host.c_str(),ServStr,Res,gai_strerror(Res));
  196. }
  197. break;
  198. }
  199. LastHost = Host;
  200. LastPort = Port;
  201. }
  202. // When we have an IP rotation stay with the last IP.
  203. struct addrinfo *CurHost = LastHostAddr;
  204. if (LastUsed != 0)
  205. CurHost = LastUsed;
  206. while (CurHost != 0)
  207. {
  208. if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
  209. {
  210. LastUsed = CurHost;
  211. return true;
  212. }
  213. close(Fd);
  214. Fd = -1;
  215. // Ignore UNIX domain sockets
  216. do
  217. {
  218. CurHost = CurHost->ai_next;
  219. }
  220. while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
  221. /* If we reached the end of the search list then wrap around to the
  222. start */
  223. if (CurHost == 0 && LastUsed != 0)
  224. CurHost = LastHostAddr;
  225. // Reached the end of the search cycle
  226. if (CurHost == LastUsed)
  227. break;
  228. if (CurHost != 0)
  229. _error->Discard();
  230. }
  231. if (_error->PendingError() == true)
  232. return false;
  233. return _error->Error(_("Unable to connect to %s:%s:"),Host.c_str(),ServStr);
  234. }
  235. /*}}}*/