]>
git.saurik.com Git - apt.git/blob - methods/connect.cc
1 // -*- mode: cpp; mode: fold -*-
3 // $Id: connect.cc,v 1.10.2.1 2004/01/16 18:58:50 mdz Exp $
4 /* ######################################################################
6 Connect - Replacement connect call
8 This was originally authored by Jason Gunthorpe <jgg@debian.org>
9 and is placed in the Public Domain, do with it what you will.
11 ##################################################################### */
13 // Include Files /*{{{*/
16 #include <apt-pkg/error.h>
17 #include <apt-pkg/fileutl.h>
18 #include <apt-pkg/strutl.h>
19 #include <apt-pkg/acquire-method.h>
20 #include <apt-pkg/configuration.h>
21 #include <apt-pkg/srvrec.h>
32 #include <netinet/in.h>
33 #include <sys/socket.h>
34 #include <arpa/inet.h>
38 #include "rfc2553emu.h"
42 static std::string LastHost
;
43 static int LastPort
= 0;
44 static struct addrinfo
*LastHostAddr
= 0;
45 static struct addrinfo
*LastUsed
= 0;
47 static std::vector
<SrvRec
> SrvRecords
;
49 // Set of IP/hostnames that we timed out before or couldn't resolve
50 static std::set
<std::string
> bad_addr
;
52 // RotateDNS - Select a new server from a DNS rotation /*{{{*/
53 // ---------------------------------------------------------------------
54 /* This is called during certain errors in order to recover by selecting a
58 if (LastUsed
!= 0 && LastUsed
->ai_next
!= 0)
59 LastUsed
= LastUsed
->ai_next
;
61 LastUsed
= LastHostAddr
;
64 static bool ConnectionAllowed(char const * const Service
, std::string
const &Host
)/*{{{*/
66 if (APT::String::Endswith(Host
, ".onion") && _config
->FindB("Acquire::BlockDotOnion", true))
68 // TRANSLATOR: %s is e.g. Tor's ".onion" which would likely fail or leak info (RFC7686)
69 _error
->Error(_("Direct connection to %s domains is blocked by default."), ".onion");
70 if (strcmp(Service
, "http") == 0)
71 _error
->Error(_("If you meant to use Tor remember to use %s instead of %s."), "tor+http", "http");
77 // DoConnect - Attempt a connect operation /*{{{*/
78 // ---------------------------------------------------------------------
79 /* This helper function attempts a connection to a single address. */
80 static bool DoConnect(struct addrinfo
*Addr
,std::string
const &Host
,
81 unsigned long TimeOut
,int &Fd
,pkgAcqMethod
*Owner
)
83 // Show a status indicator
84 char Name
[NI_MAXHOST
];
85 char Service
[NI_MAXSERV
];
89 getnameinfo(Addr
->ai_addr
,Addr
->ai_addrlen
,
90 Name
,sizeof(Name
),Service
,sizeof(Service
),
91 NI_NUMERICHOST
|NI_NUMERICSERV
);
92 Owner
->Status(_("Connecting to %s (%s)"),Host
.c_str(),Name
);
94 // if that addr did timeout before, we do not try it again
95 if(bad_addr
.find(std::string(Name
)) != bad_addr
.end())
98 /* If this is an IP rotation store the IP we are using.. If something goes
99 wrong this will get tacked onto the end of the error message */
100 if (LastHostAddr
->ai_next
!= 0)
102 std::stringstream ss
;
103 ioprintf(ss
, _("[IP: %s %s]"),Name
,Service
);
104 Owner
->SetIP(ss
.str());
108 if ((Fd
= socket(Addr
->ai_family
,Addr
->ai_socktype
,
109 Addr
->ai_protocol
)) < 0)
110 return _error
->Errno("socket",_("Could not create a socket for %s (f=%u t=%u p=%u)"),
111 Name
,Addr
->ai_family
,Addr
->ai_socktype
,Addr
->ai_protocol
);
113 SetNonBlock(Fd
,true);
114 if (connect(Fd
,Addr
->ai_addr
,Addr
->ai_addrlen
) < 0 &&
115 errno
!= EINPROGRESS
)
116 return _error
->Errno("connect",_("Cannot initiate the connection "
117 "to %s:%s (%s)."),Host
.c_str(),Service
,Name
);
119 /* This implements a timeout for connect by opening the connection
121 if (WaitFd(Fd
,true,TimeOut
) == false) {
122 bad_addr
.insert(bad_addr
.begin(), std::string(Name
));
123 Owner
->SetFailReason("Timeout");
124 return _error
->Error(_("Could not connect to %s:%s (%s), "
125 "connection timed out"),Host
.c_str(),Service
,Name
);
128 // Check the socket for an error condition
130 unsigned int Len
= sizeof(Err
);
131 if (getsockopt(Fd
,SOL_SOCKET
,SO_ERROR
,&Err
,&Len
) != 0)
132 return _error
->Errno("getsockopt",_("Failed"));
137 if(errno
== ECONNREFUSED
)
138 Owner
->SetFailReason("ConnectionRefused");
139 else if (errno
== ETIMEDOUT
)
140 Owner
->SetFailReason("ConnectionTimedOut");
141 bad_addr
.insert(bad_addr
.begin(), std::string(Name
));
142 return _error
->Errno("connect",_("Could not connect to %s:%s (%s)."),Host
.c_str(),
149 // Connect to a given Hostname /*{{{*/
150 static bool ConnectToHostname(std::string
const &Host
, int const Port
,
151 const char * const Service
, int DefPort
, int &Fd
,
152 unsigned long const TimeOut
, pkgAcqMethod
* const Owner
)
154 if (ConnectionAllowed(Service
, Host
) == false)
156 // Convert the port name/number
159 snprintf(ServStr
,sizeof(ServStr
),"%i", Port
);
161 snprintf(ServStr
,sizeof(ServStr
),"%s", Service
);
163 /* We used a cached address record.. Yes this is against the spec but
164 the way we have setup our rotating dns suggests that this is more
166 if (LastHost
!= Host
|| LastPort
!= Port
)
168 Owner
->Status(_("Connecting to %s"),Host
.c_str());
170 // Free the old address structure
171 if (LastHostAddr
!= 0)
173 freeaddrinfo(LastHostAddr
);
178 // We only understand SOCK_STREAM sockets.
179 struct addrinfo Hints
;
180 memset(&Hints
,0,sizeof(Hints
));
181 Hints
.ai_socktype
= SOCK_STREAM
;
184 if (_config
->FindB("Acquire::Connect::IDN", true) == true)
185 Hints
.ai_flags
|= AI_IDN
;
187 // see getaddrinfo(3): only return address if system has such a address configured
188 // useful if system is ipv4 only, to not get ipv6, but that fails if the system has
189 // no address configured: e.g. offline and trying to connect to localhost.
190 if (_config
->FindB("Acquire::Connect::AddrConfig", true) == true)
191 Hints
.ai_flags
|= AI_ADDRCONFIG
;
192 Hints
.ai_protocol
= 0;
194 if(_config
->FindB("Acquire::ForceIPv4", false) == true)
195 Hints
.ai_family
= AF_INET
;
196 else if(_config
->FindB("Acquire::ForceIPv6", false) == true)
197 Hints
.ai_family
= AF_INET6
;
199 Hints
.ai_family
= AF_UNSPEC
;
201 // if we couldn't resolve the host before, we don't try now
202 if(bad_addr
.find(Host
) != bad_addr
.end())
203 return _error
->Error(_("Could not resolve '%s'"),Host
.c_str());
205 // Resolve both the host and service simultaneously
209 if ((Res
= getaddrinfo(Host
.c_str(),ServStr
,&Hints
,&LastHostAddr
)) != 0 ||
212 if (Res
== EAI_NONAME
|| Res
== EAI_SERVICE
)
216 snprintf(ServStr
, sizeof(ServStr
), "%i", DefPort
);
220 bad_addr
.insert(bad_addr
.begin(), Host
);
221 Owner
->SetFailReason("ResolveFailure");
222 return _error
->Error(_("Could not resolve '%s'"),Host
.c_str());
225 if (Res
== EAI_AGAIN
)
227 Owner
->SetFailReason("TmpResolveFailure");
228 return _error
->Error(_("Temporary failure resolving '%s'"),
231 if (Res
== EAI_SYSTEM
)
232 return _error
->Errno("getaddrinfo", _("System error resolving '%s:%s'"),
233 Host
.c_str(),ServStr
);
234 return _error
->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
235 Host
.c_str(),ServStr
,Res
,gai_strerror(Res
));
244 // When we have an IP rotation stay with the last IP.
245 struct addrinfo
*CurHost
= LastHostAddr
;
251 if (DoConnect(CurHost
,Host
,TimeOut
,Fd
,Owner
) == true)
259 // Ignore UNIX domain sockets
262 CurHost
= CurHost
->ai_next
;
264 while (CurHost
!= 0 && CurHost
->ai_family
== AF_UNIX
);
266 /* If we reached the end of the search list then wrap around to the
268 if (CurHost
== 0 && LastUsed
!= 0)
269 CurHost
= LastHostAddr
;
271 // Reached the end of the search cycle
272 if (CurHost
== LastUsed
)
279 if (_error
->PendingError() == true)
281 return _error
->Error(_("Unable to connect to %s:%s:"),Host
.c_str(),ServStr
);
284 // Connect - Connect to a server /*{{{*/
285 // ---------------------------------------------------------------------
286 /* Performs a connection to the server (including SRV record lookup) */
287 bool Connect(std::string Host
,int Port
,const char *Service
,
289 unsigned long TimeOut
,pkgAcqMethod
*Owner
)
291 if (_error
->PendingError() == true)
294 if (ConnectionAllowed(Service
, Host
) == false)
297 if(LastHost
!= Host
|| LastPort
!= Port
)
300 if (_config
->FindB("Acquire::EnableSrvRecords", true) == true)
301 GetSrvRecords(Host
, DefPort
, SrvRecords
);
304 size_t stackSize
= 0;
305 // try to connect in the priority order of the srv records
306 std::string initialHost
{std::move(Host
)};
307 while(SrvRecords
.empty() == false)
309 _error
->PushToStack();
311 // PopFromSrvRecs will also remove the server
312 Host
= PopFromSrvRecs(SrvRecords
).target
;
313 auto const ret
= ConnectToHostname(Host
, Port
, Service
, DefPort
, Fd
, TimeOut
, Owner
);
317 _error
->RevertToStack();
321 Host
= std::move(initialHost
);
323 // we have no (good) SrvRecords for this host, connect right away
324 _error
->PushToStack();
326 auto const ret
= ConnectToHostname(Host
, Port
, Service
, DefPort
, Fd
,
330 _error
->RevertToStack();
332 _error
->MergeWithStack();