]> git.saurik.com Git - apt.git/blame - methods/connect.cc
Merge branch 'portability/freebsd'
[apt.git] / methods / connect.cc
CommitLineData
0837bd25
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
7db98ffc 3// $Id: connect.cc,v 1.10.2.1 2004/01/16 18:58:50 mdz Exp $
0837bd25
AL
4/* ######################################################################
5
6 Connect - Replacement connect call
7da2b375
AL
7
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.
10
0837bd25
AL
11 ##################################################################### */
12 /*}}}*/
13// Include Files /*{{{*/
ea542140
DK
14#include <config.h>
15
0837bd25
AL
16#include <apt-pkg/error.h>
17#include <apt-pkg/fileutl.h>
472ff00e
DK
18#include <apt-pkg/strutl.h>
19#include <apt-pkg/acquire-method.h>
45d02095 20#include <apt-pkg/configuration.h>
a01695e8 21#include <apt-pkg/srvrec.h>
0837bd25
AL
22
23#include <stdio.h>
24#include <errno.h>
25#include <unistd.h>
36280399 26#include <sstream>
453b82a3 27#include <string.h>
654881fb
MV
28#include<set>
29#include<string>
30
0837bd25
AL
31// Internet stuff
32#include <netinet/in.h>
33#include <sys/socket.h>
34#include <arpa/inet.h>
35#include <netdb.h>
36
ea542140 37#include "connect.h"
0837bd25 38#include "rfc2553emu.h"
d77559ac 39#include <apti18n.h>
0837bd25
AL
40 /*}}}*/
41
8f3ba4e8 42static std::string LastHost;
0837bd25
AL
43static int LastPort = 0;
44static struct addrinfo *LastHostAddr = 0;
45static struct addrinfo *LastUsed = 0;
46
a01695e8 47static std::vector<SrvRec> SrvRecords;
a01695e8 48
654881fb 49// Set of IP/hostnames that we timed out before or couldn't resolve
8f3ba4e8 50static std::set<std::string> bad_addr;
654881fb 51
b2e465d6
AL
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
55 new server */
56void RotateDNS()
57{
58 if (LastUsed != 0 && LastUsed->ai_next != 0)
59 LastUsed = LastUsed->ai_next;
60 else
61 LastUsed = LastHostAddr;
62}
63 /*}}}*/
8665dceb
DK
64static bool ConnectionAllowed(char const * const Service, std::string const &Host)/*{{{*/
65{
66 if (APT::String::Endswith(Host, ".onion") && _config->FindB("Acquire::BlockDotOnion", true))
67 {
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");
72 return false;
73 }
74 return true;
75}
76 /*}}}*/
0837bd25
AL
77// DoConnect - Attempt a connect operation /*{{{*/
78// ---------------------------------------------------------------------
79/* This helper function attempts a connection to a single address. */
8665dceb 80static bool DoConnect(struct addrinfo *Addr,std::string const &Host,
0837bd25
AL
81 unsigned long TimeOut,int &Fd,pkgAcqMethod *Owner)
82{
83 // Show a status indicator
84 char Name[NI_MAXHOST];
28006885 85 char Service[NI_MAXSERV];
b2e465d6
AL
86
87 Name[0] = 0;
28006885 88 Service[0] = 0;
0837bd25 89 getnameinfo(Addr->ai_addr,Addr->ai_addrlen,
28006885
AL
90 Name,sizeof(Name),Service,sizeof(Service),
91 NI_NUMERICHOST|NI_NUMERICSERV);
dc738e7a 92 Owner->Status(_("Connecting to %s (%s)"),Host.c_str(),Name);
b2e465d6 93
654881fb 94 // if that addr did timeout before, we do not try it again
8f3ba4e8 95 if(bad_addr.find(std::string(Name)) != bad_addr.end())
654881fb
MV
96 return false;
97
b2e465d6
AL
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)
101 {
36280399
MV
102 std::stringstream ss;
103 ioprintf(ss, _("[IP: %s %s]"),Name,Service);
104 Owner->SetIP(ss.str());
105 }
b2e465d6 106
0837bd25
AL
107 // Get a socket
108 if ((Fd = socket(Addr->ai_family,Addr->ai_socktype,
109 Addr->ai_protocol)) < 0)
dc738e7a 110 return _error->Errno("socket",_("Could not create a socket for %s (f=%u t=%u p=%u)"),
b2e465d6 111 Name,Addr->ai_family,Addr->ai_socktype,Addr->ai_protocol);
0837bd25
AL
112
113 SetNonBlock(Fd,true);
114 if (connect(Fd,Addr->ai_addr,Addr->ai_addrlen) < 0 &&
115 errno != EINPROGRESS)
dc738e7a
AL
116 return _error->Errno("connect",_("Cannot initiate the connection "
117 "to %s:%s (%s)."),Host.c_str(),Service,Name);
0837bd25
AL
118
119 /* This implements a timeout for connect by opening the connection
120 nonblocking */
24057ad6 121 if (WaitFd(Fd,true,TimeOut) == false) {
8f3ba4e8 122 bad_addr.insert(bad_addr.begin(), std::string(Name));
36280399 123 Owner->SetFailReason("Timeout");
dc738e7a
AL
124 return _error->Error(_("Could not connect to %s:%s (%s), "
125 "connection timed out"),Host.c_str(),Service,Name);
24057ad6 126 }
b2e465d6 127
0837bd25
AL
128 // Check the socket for an error condition
129 unsigned int Err;
130 unsigned int Len = sizeof(Err);
131 if (getsockopt(Fd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
dc738e7a 132 return _error->Errno("getsockopt",_("Failed"));
0837bd25
AL
133
134 if (Err != 0)
28006885
AL
135 {
136 errno = Err;
75dd8af1 137 if(errno == ECONNREFUSED)
36280399 138 Owner->SetFailReason("ConnectionRefused");
785b920b 139 else if (errno == ETIMEDOUT)
df3226c1 140 Owner->SetFailReason("ConnectionTimedOut");
8f3ba4e8 141 bad_addr.insert(bad_addr.begin(), std::string(Name));
dc738e7a 142 return _error->Errno("connect",_("Could not connect to %s:%s (%s)."),Host.c_str(),
28006885
AL
143 Service,Name);
144 }
145
0837bd25
AL
146 return true;
147}
148 /*}}}*/
b830f576
DK
149// Connect to a given Hostname /*{{{*/
150static 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)
cc480014 153{
8665dceb
DK
154 if (ConnectionAllowed(Service, Host) == false)
155 return false;
28006885
AL
156 // Convert the port name/number
157 char ServStr[300];
158 if (Port != 0)
9ce3cfc9 159 snprintf(ServStr,sizeof(ServStr),"%i", Port);
28006885 160 else
9ce3cfc9 161 snprintf(ServStr,sizeof(ServStr),"%s", Service);
0837bd25
AL
162
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
165 sensible */
166 if (LastHost != Host || LastPort != Port)
167 {
dc738e7a 168 Owner->Status(_("Connecting to %s"),Host.c_str());
0837bd25 169
0837bd25
AL
170 // Free the old address structure
171 if (LastHostAddr != 0)
172 {
173 freeaddrinfo(LastHostAddr);
174 LastHostAddr = 0;
28006885 175 LastUsed = 0;
0837bd25
AL
176 }
177
178 // We only understand SOCK_STREAM sockets.
179 struct addrinfo Hints;
180 memset(&Hints,0,sizeof(Hints));
181 Hints.ai_socktype = SOCK_STREAM;
23d35ec1 182 Hints.ai_flags = 0;
8265d6c8 183#ifdef AI_IDN
920c3672
DK
184 if (_config->FindB("Acquire::Connect::IDN", true) == true)
185 Hints.ai_flags |= AI_IDN;
8265d6c8 186#endif
23d35ec1
DK
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;
28006885 192 Hints.ai_protocol = 0;
0837bd25 193
45d02095
MV
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;
198 else
199 Hints.ai_family = AF_UNSPEC;
200
654881fb
MV
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());
204
0837bd25 205 // Resolve both the host and service simultaneously
9505213b 206 while (1)
c141b9a9 207 {
9505213b 208 int Res;
28006885 209 if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
9505213b
AL
210 LastHostAddr == 0)
211 {
72472b95 212 if (Res == EAI_NONAME || Res == EAI_SERVICE)
9505213b
AL
213 {
214 if (DefPort != 0)
215 {
9ce3cfc9 216 snprintf(ServStr, sizeof(ServStr), "%i", DefPort);
9505213b
AL
217 DefPort = 0;
218 continue;
219 }
654881fb 220 bad_addr.insert(bad_addr.begin(), Host);
59271f62 221 Owner->SetFailReason("ResolveFailure");
dc738e7a 222 return _error->Error(_("Could not resolve '%s'"),Host.c_str());
9505213b
AL
223 }
224
4fe6e0c2 225 if (Res == EAI_AGAIN)
25182152 226 {
36280399 227 Owner->SetFailReason("TmpResolveFailure");
dc738e7a 228 return _error->Error(_("Temporary failure resolving '%s'"),
4fe6e0c2 229 Host.c_str());
25182152 230 }
945d2a8a 231 if (Res == EAI_SYSTEM)
5cf466f4
MV
232 return _error->Errno("getaddrinfo", _("System error resolving '%s:%s'"),
233 Host.c_str(),ServStr);
ce26dee7
DK
234 return _error->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
235 Host.c_str(),ServStr,Res,gai_strerror(Res));
9505213b
AL
236 }
237 break;
c141b9a9
AL
238 }
239
0837bd25
AL
240 LastHost = Host;
241 LastPort = Port;
0837bd25
AL
242 }
243
28006885 244 // When we have an IP rotation stay with the last IP.
0837bd25
AL
245 struct addrinfo *CurHost = LastHostAddr;
246 if (LastUsed != 0)
247 CurHost = LastUsed;
248
249 while (CurHost != 0)
250 {
251 if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
252 {
253 LastUsed = CurHost;
254 return true;
255 }
256 close(Fd);
257 Fd = -1;
258
28006885
AL
259 // Ignore UNIX domain sockets
260 do
261 {
262 CurHost = CurHost->ai_next;
263 }
264 while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
b2e465d6
AL
265
266 /* If we reached the end of the search list then wrap around to the
267 start */
268 if (CurHost == 0 && LastUsed != 0)
269 CurHost = LastHostAddr;
270
271 // Reached the end of the search cycle
272 if (CurHost == LastUsed)
273 break;
274
0837bd25
AL
275 if (CurHost != 0)
276 _error->Discard();
b2e465d6 277 }
28006885 278
dd1fd92b 279 if (_error->PendingError() == true)
b2e465d6 280 return false;
cdd5a135 281 return _error->Error(_("Unable to connect to %s:%s:"),Host.c_str(),ServStr);
0837bd25
AL
282}
283 /*}}}*/
cc480014
MV
284// Connect - Connect to a server /*{{{*/
285// ---------------------------------------------------------------------
cdeb54d4 286/* Performs a connection to the server (including SRV record lookup) */
cc480014
MV
287bool Connect(std::string Host,int Port,const char *Service,
288 int DefPort,int &Fd,
289 unsigned long TimeOut,pkgAcqMethod *Owner)
290{
cc480014
MV
291 if (_error->PendingError() == true)
292 return false;
cc480014 293
8665dceb
DK
294 if (ConnectionAllowed(Service, Host) == false)
295 return false;
296
cc480014
MV
297 if(LastHost != Host || LastPort != Port)
298 {
299 SrvRecords.clear();
c8ec5ab7 300 if (_config->FindB("Acquire::EnableSrvRecords", true) == true)
c29dbdff 301 GetSrvRecords(Host, DefPort, SrvRecords);
cc480014 302 }
cc480014 303
3af3ac2f 304 size_t stackSize = 0;
cdeb54d4 305 // try to connect in the priority order of the srv records
3af3ac2f
DK
306 std::string initialHost{std::move(Host)};
307 while(SrvRecords.empty() == false)
cc480014 308 {
3af3ac2f
DK
309 _error->PushToStack();
310 ++stackSize;
0b7d34ee 311 // PopFromSrvRecs will also remove the server
c29dbdff 312 Host = PopFromSrvRecs(SrvRecords).target;
3af3ac2f
DK
313 auto const ret = ConnectToHostname(Host, Port, Service, DefPort, Fd, TimeOut, Owner);
314 if (ret)
315 {
316 while(stackSize--)
317 _error->RevertToStack();
cc480014 318 return true;
3af3ac2f 319 }
cdeb54d4 320 }
3af3ac2f 321 Host = std::move(initialHost);
cdeb54d4 322
3af3ac2f
DK
323 // we have no (good) SrvRecords for this host, connect right away
324 _error->PushToStack();
325 ++stackSize;
326 auto const ret = ConnectToHostname(Host, Port, Service, DefPort, Fd,
327 TimeOut, Owner);
328 while(stackSize--)
329 if (ret)
330 _error->RevertToStack();
331 else
332 _error->MergeWithStack();
333 return ret;
cc480014 334}