]> git.saurik.com Git - apt.git/blob - methods/connect.cc
drop privileges in copy:// method as we do for file://
[apt.git] / methods / connect.cc
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
6 Connect - Replacement connect call
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
11 ##################################################################### */
12 /*}}}*/
13 // Include Files /*{{{*/
14 #include <config.h>
15
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>
22
23 #include <stdio.h>
24 #include <errno.h>
25 #include <unistd.h>
26 #include <sstream>
27 #include <string.h>
28 #include<set>
29 #include<string>
30
31 // Internet stuff
32 #include <netinet/in.h>
33 #include <sys/socket.h>
34 #include <arpa/inet.h>
35 #include <netdb.h>
36
37 #include "connect.h"
38 #include "rfc2553emu.h"
39 #include <apti18n.h>
40 /*}}}*/
41
42 static std::string LastHost;
43 static int LastPort = 0;
44 static struct addrinfo *LastHostAddr = 0;
45 static struct addrinfo *LastUsed = 0;
46
47 static std::vector<SrvRec> SrvRecords;
48
49 // Set of IP/hostnames that we timed out before or couldn't resolve
50 static std::set<std::string> bad_addr;
51
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 */
56 void RotateDNS()
57 {
58 if (LastUsed != 0 && LastUsed->ai_next != 0)
59 LastUsed = LastUsed->ai_next;
60 else
61 LastUsed = LastHostAddr;
62 }
63 /*}}}*/
64 // DoConnect - Attempt a connect operation /*{{{*/
65 // ---------------------------------------------------------------------
66 /* This helper function attempts a connection to a single address. */
67 static bool DoConnect(struct addrinfo *Addr,std::string Host,
68 unsigned long TimeOut,int &Fd,pkgAcqMethod *Owner)
69 {
70 // Show a status indicator
71 char Name[NI_MAXHOST];
72 char Service[NI_MAXSERV];
73
74 Name[0] = 0;
75 Service[0] = 0;
76 getnameinfo(Addr->ai_addr,Addr->ai_addrlen,
77 Name,sizeof(Name),Service,sizeof(Service),
78 NI_NUMERICHOST|NI_NUMERICSERV);
79 Owner->Status(_("Connecting to %s (%s)"),Host.c_str(),Name);
80
81 // if that addr did timeout before, we do not try it again
82 if(bad_addr.find(std::string(Name)) != bad_addr.end())
83 return false;
84
85 /* If this is an IP rotation store the IP we are using.. If something goes
86 wrong this will get tacked onto the end of the error message */
87 if (LastHostAddr->ai_next != 0)
88 {
89 std::stringstream ss;
90 ioprintf(ss, _("[IP: %s %s]"),Name,Service);
91 Owner->SetIP(ss.str());
92 }
93
94 // Get a socket
95 if ((Fd = socket(Addr->ai_family,Addr->ai_socktype,
96 Addr->ai_protocol)) < 0)
97 return _error->Errno("socket",_("Could not create a socket for %s (f=%u t=%u p=%u)"),
98 Name,Addr->ai_family,Addr->ai_socktype,Addr->ai_protocol);
99
100 SetNonBlock(Fd,true);
101 if (connect(Fd,Addr->ai_addr,Addr->ai_addrlen) < 0 &&
102 errno != EINPROGRESS)
103 return _error->Errno("connect",_("Cannot initiate the connection "
104 "to %s:%s (%s)."),Host.c_str(),Service,Name);
105
106 /* This implements a timeout for connect by opening the connection
107 nonblocking */
108 if (WaitFd(Fd,true,TimeOut) == false) {
109 bad_addr.insert(bad_addr.begin(), std::string(Name));
110 Owner->SetFailReason("Timeout");
111 return _error->Error(_("Could not connect to %s:%s (%s), "
112 "connection timed out"),Host.c_str(),Service,Name);
113 }
114
115 // Check the socket for an error condition
116 unsigned int Err;
117 unsigned int Len = sizeof(Err);
118 if (getsockopt(Fd,SOL_SOCKET,SO_ERROR,&Err,&Len) != 0)
119 return _error->Errno("getsockopt",_("Failed"));
120
121 if (Err != 0)
122 {
123 errno = Err;
124 if(errno == ECONNREFUSED)
125 Owner->SetFailReason("ConnectionRefused");
126 else if (errno == ETIMEDOUT)
127 Owner->SetFailReason("ConnectionTimedOut");
128 bad_addr.insert(bad_addr.begin(), std::string(Name));
129 return _error->Errno("connect",_("Could not connect to %s:%s (%s)."),Host.c_str(),
130 Service,Name);
131 }
132
133 return true;
134 }
135 /*}}}*/
136 // Connect to a given Hostname /*{{{*/
137 static bool ConnectToHostname(std::string const &Host, int const Port,
138 const char * const Service, int DefPort, int &Fd,
139 unsigned long const TimeOut, pkgAcqMethod * const Owner)
140 {
141 // Convert the port name/number
142 char ServStr[300];
143 if (Port != 0)
144 snprintf(ServStr,sizeof(ServStr),"%i", Port);
145 else
146 snprintf(ServStr,sizeof(ServStr),"%s", Service);
147
148 /* We used a cached address record.. Yes this is against the spec but
149 the way we have setup our rotating dns suggests that this is more
150 sensible */
151 if (LastHost != Host || LastPort != Port)
152 {
153 Owner->Status(_("Connecting to %s"),Host.c_str());
154
155 // Free the old address structure
156 if (LastHostAddr != 0)
157 {
158 freeaddrinfo(LastHostAddr);
159 LastHostAddr = 0;
160 LastUsed = 0;
161 }
162
163 // We only understand SOCK_STREAM sockets.
164 struct addrinfo Hints;
165 memset(&Hints,0,sizeof(Hints));
166 Hints.ai_socktype = SOCK_STREAM;
167 Hints.ai_flags = 0;
168 // see getaddrinfo(3): only return address if system has such a address configured
169 // useful if system is ipv4 only, to not get ipv6, but that fails if the system has
170 // no address configured: e.g. offline and trying to connect to localhost.
171 if (_config->FindB("Acquire::Connect::AddrConfig", true) == true)
172 Hints.ai_flags |= AI_ADDRCONFIG;
173 Hints.ai_protocol = 0;
174
175 if(_config->FindB("Acquire::ForceIPv4", false) == true)
176 Hints.ai_family = AF_INET;
177 else if(_config->FindB("Acquire::ForceIPv6", false) == true)
178 Hints.ai_family = AF_INET6;
179 else
180 Hints.ai_family = AF_UNSPEC;
181
182 // if we couldn't resolve the host before, we don't try now
183 if(bad_addr.find(Host) != bad_addr.end())
184 return _error->Error(_("Could not resolve '%s'"),Host.c_str());
185
186 // Resolve both the host and service simultaneously
187 while (1)
188 {
189 int Res;
190 if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
191 LastHostAddr == 0)
192 {
193 if (Res == EAI_NONAME || Res == EAI_SERVICE)
194 {
195 if (DefPort != 0)
196 {
197 snprintf(ServStr, sizeof(ServStr), "%i", DefPort);
198 DefPort = 0;
199 continue;
200 }
201 bad_addr.insert(bad_addr.begin(), Host);
202 Owner->SetFailReason("ResolveFailure");
203 return _error->Error(_("Could not resolve '%s'"),Host.c_str());
204 }
205
206 if (Res == EAI_AGAIN)
207 {
208 Owner->SetFailReason("TmpResolveFailure");
209 return _error->Error(_("Temporary failure resolving '%s'"),
210 Host.c_str());
211 }
212 if (Res == EAI_SYSTEM)
213 return _error->Errno("getaddrinfo", _("System error resolving '%s:%s'"),
214 Host.c_str(),ServStr);
215 return _error->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
216 Host.c_str(),ServStr,Res,gai_strerror(Res));
217 }
218 break;
219 }
220
221 LastHost = Host;
222 LastPort = Port;
223 }
224
225 // When we have an IP rotation stay with the last IP.
226 struct addrinfo *CurHost = LastHostAddr;
227 if (LastUsed != 0)
228 CurHost = LastUsed;
229
230 while (CurHost != 0)
231 {
232 if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
233 {
234 LastUsed = CurHost;
235 return true;
236 }
237 close(Fd);
238 Fd = -1;
239
240 // Ignore UNIX domain sockets
241 do
242 {
243 CurHost = CurHost->ai_next;
244 }
245 while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
246
247 /* If we reached the end of the search list then wrap around to the
248 start */
249 if (CurHost == 0 && LastUsed != 0)
250 CurHost = LastHostAddr;
251
252 // Reached the end of the search cycle
253 if (CurHost == LastUsed)
254 break;
255
256 if (CurHost != 0)
257 _error->Discard();
258 }
259
260 if (_error->PendingError() == true)
261 return false;
262 return _error->Error(_("Unable to connect to %s:%s:"),Host.c_str(),ServStr);
263 }
264 /*}}}*/
265 // Connect - Connect to a server /*{{{*/
266 // ---------------------------------------------------------------------
267 /* Performs a connection to the server (including SRV record lookup) */
268 bool Connect(std::string Host,int Port,const char *Service,
269 int DefPort,int &Fd,
270 unsigned long TimeOut,pkgAcqMethod *Owner)
271 {
272 if (_error->PendingError() == true)
273 return false;
274
275 if(LastHost != Host || LastPort != Port)
276 {
277 SrvRecords.clear();
278 if (_config->FindB("Acquire::EnableSrvRecords", true) == true)
279 GetSrvRecords(Host, DefPort, SrvRecords);
280 }
281 // we have no SrvRecords for this host, connect right away
282 if(SrvRecords.size() == 0)
283 return ConnectToHostname(Host, Port, Service, DefPort, Fd,
284 TimeOut, Owner);
285
286 // try to connect in the priority order of the srv records
287 while(SrvRecords.size() > 0)
288 {
289 Host = PopFromSrvRecs(SrvRecords).target;
290 if(ConnectToHostname(Host, Port, Service, DefPort, Fd, TimeOut, Owner))
291 return true;
292
293 // we couldn't connect to this one, use the next
294 SrvRecords.erase(SrvRecords.begin());
295 }
296
297 return false;
298 }