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