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