releasing version 0.8.16~exp3
[ntk/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 /*{{{*/
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>
36280399 21#include <sstream>
0837bd25 22
654881fb
MV
23#include<set>
24#include<string>
25
0837bd25
AL
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"
d77559ac 33#include <apti18n.h>
0837bd25
AL
34 /*}}}*/
35
36static string LastHost;
37static int LastPort = 0;
38static struct addrinfo *LastHostAddr = 0;
39static struct addrinfo *LastUsed = 0;
40
654881fb
MV
41// Set of IP/hostnames that we timed out before or couldn't resolve
42static std::set<string> bad_addr;
43
b2e465d6
AL
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 */
48void RotateDNS()
49{
50 if (LastUsed != 0 && LastUsed->ai_next != 0)
51 LastUsed = LastUsed->ai_next;
52 else
53 LastUsed = LastHostAddr;
54}
55 /*}}}*/
0837bd25
AL
56// DoConnect - Attempt a connect operation /*{{{*/
57// ---------------------------------------------------------------------
58/* This helper function attempts a connection to a single address. */
59static 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];
28006885 64 char Service[NI_MAXSERV];
b2e465d6
AL
65
66 Name[0] = 0;
28006885 67 Service[0] = 0;
0837bd25 68 getnameinfo(Addr->ai_addr,Addr->ai_addrlen,
28006885
AL
69 Name,sizeof(Name),Service,sizeof(Service),
70 NI_NUMERICHOST|NI_NUMERICSERV);
dc738e7a 71 Owner->Status(_("Connecting to %s (%s)"),Host.c_str(),Name);
b2e465d6 72
654881fb 73 // if that addr did timeout before, we do not try it again
1b7fe0e1 74 if(bad_addr.find(string(Name)) != bad_addr.end())
654881fb
MV
75 return false;
76
b2e465d6
AL
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 {
36280399
MV
81 std::stringstream ss;
82 ioprintf(ss, _("[IP: %s %s]"),Name,Service);
83 Owner->SetIP(ss.str());
84 }
b2e465d6 85
0837bd25
AL
86 // Get a socket
87 if ((Fd = socket(Addr->ai_family,Addr->ai_socktype,
88 Addr->ai_protocol)) < 0)
dc738e7a 89 return _error->Errno("socket",_("Could not create a socket for %s (f=%u t=%u p=%u)"),
b2e465d6 90 Name,Addr->ai_family,Addr->ai_socktype,Addr->ai_protocol);
0837bd25
AL
91
92 SetNonBlock(Fd,true);
93 if (connect(Fd,Addr->ai_addr,Addr->ai_addrlen) < 0 &&
94 errno != EINPROGRESS)
dc738e7a
AL
95 return _error->Errno("connect",_("Cannot initiate the connection "
96 "to %s:%s (%s)."),Host.c_str(),Service,Name);
0837bd25
AL
97
98 /* This implements a timeout for connect by opening the connection
99 nonblocking */
24057ad6 100 if (WaitFd(Fd,true,TimeOut) == false) {
654881fb 101 bad_addr.insert(bad_addr.begin(), string(Name));
36280399 102 Owner->SetFailReason("Timeout");
dc738e7a
AL
103 return _error->Error(_("Could not connect to %s:%s (%s), "
104 "connection timed out"),Host.c_str(),Service,Name);
24057ad6 105 }
b2e465d6 106
0837bd25
AL
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)
dc738e7a 111 return _error->Errno("getsockopt",_("Failed"));
0837bd25
AL
112
113 if (Err != 0)
28006885
AL
114 {
115 errno = Err;
75dd8af1 116 if(errno == ECONNREFUSED)
36280399 117 Owner->SetFailReason("ConnectionRefused");
785b920b 118 else if (errno == ETIMEDOUT)
df3226c1 119 Owner->SetFailReason("ConnectionTimedOut");
785b920b 120 bad_addr.insert(bad_addr.begin(), string(Name));
dc738e7a 121 return _error->Errno("connect",_("Could not connect to %s:%s (%s)."),Host.c_str(),
28006885
AL
122 Service,Name);
123 }
124
0837bd25
AL
125 return true;
126}
127 /*}}}*/
c141b9a9 128// Connect - Connect to a server /*{{{*/
0837bd25
AL
129// ---------------------------------------------------------------------
130/* Performs a connection to the server */
9505213b 131bool Connect(string Host,int Port,const char *Service,int DefPort,int &Fd,
0837bd25
AL
132 unsigned long TimeOut,pkgAcqMethod *Owner)
133{
134 if (_error->PendingError() == true)
135 return false;
28006885
AL
136
137 // Convert the port name/number
138 char ServStr[300];
139 if (Port != 0)
140 snprintf(ServStr,sizeof(ServStr),"%u",Port);
141 else
142 snprintf(ServStr,sizeof(ServStr),"%s",Service);
0837bd25
AL
143
144 /* We used a cached address record.. Yes this is against the spec but
145 the way we have setup our rotating dns suggests that this is more
146 sensible */
147 if (LastHost != Host || LastPort != Port)
148 {
dc738e7a 149 Owner->Status(_("Connecting to %s"),Host.c_str());
0837bd25 150
0837bd25
AL
151 // Free the old address structure
152 if (LastHostAddr != 0)
153 {
154 freeaddrinfo(LastHostAddr);
155 LastHostAddr = 0;
28006885 156 LastUsed = 0;
0837bd25
AL
157 }
158
159 // We only understand SOCK_STREAM sockets.
160 struct addrinfo Hints;
161 memset(&Hints,0,sizeof(Hints));
162 Hints.ai_socktype = SOCK_STREAM;
d746ad6e 163 Hints.ai_flags = AI_ADDRCONFIG;
28006885 164 Hints.ai_protocol = 0;
0837bd25 165
654881fb
MV
166 // if we couldn't resolve the host before, we don't try now
167 if(bad_addr.find(Host) != bad_addr.end())
168 return _error->Error(_("Could not resolve '%s'"),Host.c_str());
169
0837bd25 170 // Resolve both the host and service simultaneously
9505213b 171 while (1)
c141b9a9 172 {
9505213b 173 int Res;
28006885 174 if ((Res = getaddrinfo(Host.c_str(),ServStr,&Hints,&LastHostAddr)) != 0 ||
9505213b
AL
175 LastHostAddr == 0)
176 {
72472b95 177 if (Res == EAI_NONAME || Res == EAI_SERVICE)
9505213b
AL
178 {
179 if (DefPort != 0)
180 {
28006885 181 snprintf(ServStr,sizeof(ServStr),"%u",DefPort);
9505213b
AL
182 DefPort = 0;
183 continue;
184 }
654881fb 185 bad_addr.insert(bad_addr.begin(), Host);
59271f62 186 Owner->SetFailReason("ResolveFailure");
dc738e7a 187 return _error->Error(_("Could not resolve '%s'"),Host.c_str());
9505213b
AL
188 }
189
4fe6e0c2 190 if (Res == EAI_AGAIN)
25182152 191 {
36280399 192 Owner->SetFailReason("TmpResolveFailure");
dc738e7a 193 return _error->Error(_("Temporary failure resolving '%s'"),
4fe6e0c2 194 Host.c_str());
25182152 195 }
ce26dee7
DK
196 return _error->Error(_("Something wicked happened resolving '%s:%s' (%i - %s)"),
197 Host.c_str(),ServStr,Res,gai_strerror(Res));
9505213b
AL
198 }
199 break;
c141b9a9
AL
200 }
201
0837bd25
AL
202 LastHost = Host;
203 LastPort = Port;
0837bd25
AL
204 }
205
28006885 206 // When we have an IP rotation stay with the last IP.
0837bd25
AL
207 struct addrinfo *CurHost = LastHostAddr;
208 if (LastUsed != 0)
209 CurHost = LastUsed;
210
211 while (CurHost != 0)
212 {
213 if (DoConnect(CurHost,Host,TimeOut,Fd,Owner) == true)
214 {
215 LastUsed = CurHost;
216 return true;
217 }
218 close(Fd);
219 Fd = -1;
220
28006885
AL
221 // Ignore UNIX domain sockets
222 do
223 {
224 CurHost = CurHost->ai_next;
225 }
226 while (CurHost != 0 && CurHost->ai_family == AF_UNIX);
b2e465d6
AL
227
228 /* If we reached the end of the search list then wrap around to the
229 start */
230 if (CurHost == 0 && LastUsed != 0)
231 CurHost = LastHostAddr;
232
233 // Reached the end of the search cycle
234 if (CurHost == LastUsed)
235 break;
236
0837bd25
AL
237 if (CurHost != 0)
238 _error->Discard();
b2e465d6 239 }
28006885 240
dd1fd92b 241 if (_error->PendingError() == true)
b2e465d6 242 return false;
cdd5a135 243 return _error->Error(_("Unable to connect to %s:%s:"),Host.c_str(),ServStr);
0837bd25
AL
244}
245 /*}}}*/