2 * DEBUG: section 05 Listener Socket Handler
3 * AUTHOR: Harvest Derived
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
32 * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org>
36 #include "base/TextException.h"
37 #include "client_db.h"
38 #include "comm/AcceptLimiter.h"
39 #include "CommCalls.h"
40 #include "comm/comm_internal.h"
41 #include "comm/Connection.h"
42 #include "comm/Loops.h"
43 #include "comm/TcpAcceptor.h"
47 #include "ip/Intercept.h"
48 #include "profiler/Profiler.h"
49 #include "SquidConfig.h"
50 #include "SquidTime.h"
51 #include "StatCounters.h"
56 #ifdef HAVE_NETINET_TCP_H
57 // required for accept_filter to build.
58 #include <netinet/tcp.h>
61 CBDATA_NAMESPACED_CLASS_INIT(Comm
, TcpAcceptor
);
63 Comm::TcpAcceptor::TcpAcceptor(const Comm::ConnectionPointer
&newConn
, const char *note
, const Subscription::Pointer
&aSub
) :
64 AsyncJob("Comm::TcpAcceptor"),
72 Comm::TcpAcceptor::subscribe(const Subscription::Pointer
&aSub
)
74 debugs(5, 5, HERE
<< status() << " AsyncCall Subscription: " << aSub
);
75 unsubscribe("subscription change");
80 Comm::TcpAcceptor::unsubscribe(const char *reason
)
82 debugs(5, 5, HERE
<< status() << " AsyncCall Subscription " << theCallSub
<< " removed: " << reason
);
87 Comm::TcpAcceptor::start()
89 debugs(5, 5, HERE
<< status() << " AsyncCall Subscription: " << theCallSub
);
91 Must(IsConnOpen(conn
));
95 // if no error so far start accepting connections.
97 SetSelect(conn
->fd
, COMM_SELECT_READ
, doAccept
, this, 0);
101 Comm::TcpAcceptor::doneAll() const
103 // stop when FD is closed
104 if (!IsConnOpen(conn
)) {
105 return AsyncJob::doneAll();
108 // stop when handlers are gone
109 if (theCallSub
== NULL
) {
110 return AsyncJob::doneAll();
113 // open FD with handlers...keep accepting.
118 Comm::TcpAcceptor::swanSong()
121 unsubscribe("swanSong");
123 AcceptLimiter::Instance().removeDead(this);
124 AsyncJob::swanSong();
128 Comm::TcpAcceptor::status() const
131 return "[nil connection]";
133 static char ipbuf
[MAX_IPSTRLEN
] = {'\0'};
134 if (ipbuf
[0] == '\0')
135 conn
->local
.ToHostname(ipbuf
, MAX_IPSTRLEN
);
139 buf
.Printf(" FD %d, %s",conn
->fd
, ipbuf
);
141 const char *jobStatus
= AsyncJob::status();
142 buf
.append(jobStatus
, strlen(jobStatus
));
144 return buf
.content();
148 * New-style listen and accept routines
150 * setListen simply registers our interest in an FD for listening.
151 * The constructor takes a callback to call when an FD has been
152 * accept()ed some time later.
155 Comm::TcpAcceptor::setListen()
157 errcode
= 0; // reset local errno copy.
158 if (listen(conn
->fd
, Squid_MaxFD
>> 2) < 0) {
159 debugs(50, DBG_CRITICAL
, "ERROR: listen(" << status() << ", " << (Squid_MaxFD
>> 2) << "): " << xstrerror());
164 if (Config
.accept_filter
&& strcmp(Config
.accept_filter
, "none") != 0) {
165 #ifdef SO_ACCEPTFILTER
166 struct accept_filter_arg afa
;
167 bzero(&afa
, sizeof(afa
));
168 debugs(5, DBG_IMPORTANT
, "Installing accept filter '" << Config
.accept_filter
<< "' on " << conn
);
169 xstrncpy(afa
.af_name
, Config
.accept_filter
, sizeof(afa
.af_name
));
170 if (setsockopt(conn
->fd
, SOL_SOCKET
, SO_ACCEPTFILTER
, &afa
, sizeof(afa
)) < 0)
171 debugs(5, DBG_CRITICAL
, "WARNING: SO_ACCEPTFILTER '" << Config
.accept_filter
<< "': '" << xstrerror());
172 #elif defined(TCP_DEFER_ACCEPT)
174 if (strncmp(Config
.accept_filter
, "data=", 5) == 0)
175 seconds
= atoi(Config
.accept_filter
+ 5);
176 if (setsockopt(conn
->fd
, IPPROTO_TCP
, TCP_DEFER_ACCEPT
, &seconds
, sizeof(seconds
)) < 0)
177 debugs(5, DBG_CRITICAL
, "WARNING: TCP_DEFER_ACCEPT '" << Config
.accept_filter
<< "': '" << xstrerror());
179 debugs(5, DBG_CRITICAL
, "WARNING: accept_filter not supported on your OS");
185 * This private callback is called whenever a filedescriptor is ready
186 * to dupe itself and fob off an accept()ed connection
188 * It will either do that accept operation. Or if there are not enough FD
189 * available to do the clone safely will push the listening FD into a list
190 * of deferred operations. The list gets kicked and the dupe/accept() actually
191 * done later when enough sockets become available.
194 Comm::TcpAcceptor::doAccept(int fd
, void *data
)
197 debugs(5, 2, HERE
<< "New connection on FD " << fd
);
200 TcpAcceptor
*afd
= static_cast<TcpAcceptor
*>(data
);
203 AcceptLimiter::Instance().defer(afd
);
207 SetSelect(fd
, COMM_SELECT_READ
, Comm::TcpAcceptor::doAccept
, afd
, 0);
209 } catch (const std::exception
&e
) {
210 fatalf("FATAL: error while accepting new client connection: %s\n", e
.what());
212 fatal("FATAL: error while accepting new client connection: [unkown]\n");
217 Comm::TcpAcceptor::okToAccept()
219 static time_t last_warn
= 0;
221 if (fdNFree() >= RESERVED_FD
)
224 if (last_warn
+ 15 < squid_curtime
) {
225 debugs(5, DBG_CRITICAL
, "WARNING! Your cache is running out of filedescriptors");
226 last_warn
= squid_curtime
;
233 Comm::TcpAcceptor::acceptOne()
236 * We don't worry about running low on FDs here. Instead,
237 * doAccept() will use AcceptLimiter if we reach the limit
241 /* Accept a new connection */
242 ConnectionPointer newConnDetails
= new Connection();
243 const comm_err_t flag
= oldAccept(newConnDetails
);
245 /* Check for errors */
246 if (!newConnDetails
->isOpen()) {
248 if (flag
== COMM_NOMESSAGE
) {
249 /* register interest again */
250 debugs(5, 5, HERE
<< "try later: " << conn
<< " handler Subscription: " << theCallSub
);
251 SetSelect(conn
->fd
, COMM_SELECT_READ
, doAccept
, this, 0);
255 // A non-recoverable error; notify the caller */
256 debugs(5, 5, HERE
<< "non-recoverable error:" << status() << " handler Subscription: " << theCallSub
);
257 notify(flag
, newConnDetails
);
258 mustStop("Listener socket closed");
262 debugs(5, 5, HERE
<< "Listener: " << conn
<<
263 " accepted new connection " << newConnDetails
<<
264 " handler Subscription: " << theCallSub
);
265 notify(flag
, newConnDetails
);
269 Comm::TcpAcceptor::acceptNext()
271 Must(IsConnOpen(conn
));
272 debugs(5, 2, HERE
<< "connection on " << conn
);
277 Comm::TcpAcceptor::notify(const comm_err_t flag
, const Comm::ConnectionPointer
&newConnDetails
) const
279 // listener socket handlers just abandon the port with COMM_ERR_CLOSING
280 // it should only happen when this object is deleted...
281 if (flag
== COMM_ERR_CLOSING
) {
285 if (theCallSub
!= NULL
) {
286 AsyncCall::Pointer call
= theCallSub
->callback();
287 CommAcceptCbParams
¶ms
= GetCommParams
<CommAcceptCbParams
>(call
);
288 params
.fd
= conn
->fd
;
289 params
.conn
= newConnDetails
;
291 params
.xerrno
= errcode
;
292 ScheduleCallHere(call
);
297 * accept() and process
298 * Wait for an incoming connection on our listener socket.
300 * \retval COMM_OK success. details parameter filled.
301 * \retval COMM_NOMESSAGE attempted accept() but nothing useful came in.
302 * \retval COMM_ERROR an outright failure occured.
303 * Or if this client has too many connections already.
306 Comm::TcpAcceptor::oldAccept(Comm::ConnectionPointer
&details
)
308 PROF_start(comm_accept
);
309 ++statCounter
.syscalls
.sock
.accepts
;
311 struct addrinfo
*gai
= NULL
;
312 details
->local
.InitAddrInfo(gai
);
314 errcode
= 0; // reset local errno copy.
315 if ((sock
= accept(conn
->fd
, gai
->ai_addr
, &gai
->ai_addrlen
)) < 0) {
316 errcode
= errno
; // store last accept errno locally.
318 details
->local
.FreeAddrInfo(gai
);
320 PROF_stop(comm_accept
);
322 if (ignoreErrno(errno
)) {
323 debugs(50, 5, HERE
<< status() << ": " << xstrerror());
324 return COMM_NOMESSAGE
;
325 } else if (ENFILE
== errno
|| EMFILE
== errno
) {
326 debugs(50, 3, HERE
<< status() << ": " << xstrerror());
329 debugs(50, DBG_IMPORTANT
, HERE
<< status() << ": " << xstrerror());
336 details
->remote
= *gai
;
338 if ( Config
.client_ip_max_connections
>= 0) {
339 if (clientdbEstablished(details
->remote
, 0) > Config
.client_ip_max_connections
) {
340 debugs(50, DBG_IMPORTANT
, "WARNING: " << details
->remote
<< " attempting more than " << Config
.client_ip_max_connections
<< " connections.");
341 details
->local
.FreeAddrInfo(gai
);
346 // lookup the local-end details of this new connection
347 details
->local
.InitAddrInfo(gai
);
348 details
->local
.SetEmpty();
349 getsockname(sock
, gai
->ai_addr
, &gai
->ai_addrlen
);
350 details
->local
= *gai
;
351 details
->local
.FreeAddrInfo(gai
);
354 // XXX : these are not all HTTP requests. use a note about type and ip:port details->
355 // so we end up with a uniform "(HTTP|FTP-data|HTTPS|...) remote-ip:remote-port"
356 fd_open(sock
, FD_SOCKET
, "HTTP Request");
358 fdd_table
[sock
].close_file
= NULL
;
359 fdd_table
[sock
].close_line
= 0;
361 fde
*F
= &fd_table
[sock
];
362 details
->remote
.NtoA(F
->ipaddr
,MAX_IPSTRLEN
);
363 F
->remote_port
= details
->remote
.GetPort();
364 F
->local_addr
= details
->local
;
365 F
->sock_family
= details
->local
.IsIPv6()?AF_INET6
:AF_INET
;
368 commSetCloseOnExec(sock
);
369 commSetNonBlocking(sock
);
371 /* IFF the socket is (tproxy) transparent, pass the flag down to allow spoofing */
372 F
->flags
.transparent
= fd_table
[conn
->fd
].flags
.transparent
; // XXX: can we remove this line yet?
374 // Perform NAT or TPROXY operations to retrieve the real client/dest IP addresses
375 if (conn
->flags
&(COMM_TRANSPARENT
|COMM_INTERCEPTION
) && !Ip::Interceptor
.Lookup(details
, conn
)) {
380 PROF_stop(comm_accept
);