]> git.ipfire.org Git - thirdparty/squid.git/blame - src/comm/TcpAcceptor.cc
Moved wordlist prototypes from protos.h to wordlist.h
[thirdparty/squid.git] / src / comm / TcpAcceptor.cc
CommitLineData
04f55905 1/*
b510f3a1 2 * DEBUG: section 05 Listener Socket Handler
04f55905
AJ
3 * AUTHOR: Harvest Derived
4 *
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
7 *
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.
16 *
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.
21 *
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.
26 *
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.
30 *
31 *
32 * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org>
33 */
34
582c2af2 35#include "squid.h"
a9870624 36#include "base/TextException.h"
04f55905 37#include "comm/AcceptLimiter.h"
582c2af2 38#include "CommCalls.h"
04f55905 39#include "comm/comm_internal.h"
5b67dfa4 40#include "comm/Connection.h"
d841c88d 41#include "comm/Loops.h"
cbff89ba 42#include "comm/TcpAcceptor.h"
04f55905 43#include "fde.h"
40d34a62 44#include "ip/Intercept.h"
582c2af2 45#include "profiler/Profiler.h"
5511c78a 46#include "protos.h"
04f55905 47#include "SquidTime.h"
e4f1fdae 48#include "StatCounters.h"
04f55905 49
21d845b1
FC
50#if HAVE_ERRNO_H
51#include <errno.h>
52#endif
53
db98b2bd
A
54namespace Comm
55{
56CBDATA_CLASS_INIT(TcpAcceptor);
a9870624
AJ
57};
58
8bbb16e3 59Comm::TcpAcceptor::TcpAcceptor(const Comm::ConnectionPointer &newConn, const char *note, const Subscription::Pointer &aSub) :
cbff89ba 60 AsyncJob("Comm::TcpAcceptor"),
0ba55a12
AJ
61 errcode(0),
62 isLimited(0),
5b67dfa4
AJ
63 theCallSub(aSub),
64 conn(newConn)
cbff89ba 65{}
0ba55a12
AJ
66
67void
cbff89ba 68Comm::TcpAcceptor::subscribe(const Subscription::Pointer &aSub)
0ba55a12 69{
cbff89ba 70 debugs(5, 5, HERE << status() << " AsyncCall Subscription: " << aSub);
5b67dfa4
AJ
71 unsubscribe("subscription change");
72 theCallSub = aSub;
4c5518e5
AJ
73}
74
0ba55a12 75void
cbff89ba 76Comm::TcpAcceptor::unsubscribe(const char *reason)
0ba55a12 77{
cbff89ba 78 debugs(5, 5, HERE << status() << " AsyncCall Subscription " << theCallSub << " removed: " << reason);
5b67dfa4 79 theCallSub = NULL;
0ba55a12
AJ
80}
81
a9870624 82void
cbff89ba 83Comm::TcpAcceptor::start()
a9870624 84{
cbff89ba 85 debugs(5, 5, HERE << status() << " AsyncCall Subscription: " << theCallSub);
a9870624
AJ
86
87 Must(IsConnOpen(conn));
88
89 setListen();
90
91 // if no error so far start accepting connections.
92 if (errcode == 0)
8bbb16e3 93 SetSelect(conn->fd, COMM_SELECT_READ, doAccept, this, 0);
a9870624
AJ
94}
95
96bool
cbff89ba 97Comm::TcpAcceptor::doneAll() const
a9870624 98{
6f8536c0 99 // stop when FD is closed
a9870624 100 if (!IsConnOpen(conn)) {
a9870624
AJ
101 return AsyncJob::doneAll();
102 }
103
5b67dfa4
AJ
104 // stop when handlers are gone
105 if (theCallSub == NULL) {
a9870624
AJ
106 return AsyncJob::doneAll();
107 }
108
5b67dfa4 109 // open FD with handlers...keep accepting.
a9870624
AJ
110 return false;
111}
112
113void
cbff89ba 114Comm::TcpAcceptor::swanSong()
a9870624
AJ
115{
116 debugs(5,5, HERE);
5b67dfa4 117 unsubscribe("swanSong");
a9870624 118 conn = NULL;
5b67dfa4 119 AcceptLimiter::Instance().removeDead(this);
a9870624
AJ
120 AsyncJob::swanSong();
121}
122
cbff89ba
AJ
123const char *
124Comm::TcpAcceptor::status() const
125{
8bbb16e3
AJ
126 if (conn == NULL)
127 return "[nil connection]";
128
cbff89ba
AJ
129 static char ipbuf[MAX_IPSTRLEN] = {'\0'};
130 if (ipbuf[0] == '\0')
8bbb16e3 131 conn->local.ToHostname(ipbuf, MAX_IPSTRLEN);
cbff89ba
AJ
132
133 static MemBuf buf;
134 buf.reset();
8bbb16e3 135 buf.Printf(" FD %d, %s",conn->fd, ipbuf);
cbff89ba
AJ
136
137 const char *jobStatus = AsyncJob::status();
138 buf.append(jobStatus, strlen(jobStatus));
139
140 return buf.content();
141}
142
0ba55a12
AJ
143/**
144 * New-style listen and accept routines
145 *
146 * setListen simply registers our interest in an FD for listening.
147 * The constructor takes a callback to call when an FD has been
148 * accept()ed some time later.
149 */
150void
cbff89ba 151Comm::TcpAcceptor::setListen()
0ba55a12
AJ
152{
153 errcode = 0; // reset local errno copy.
a9870624 154 if (listen(conn->fd, Squid_MaxFD >> 2) < 0) {
cbff89ba 155 debugs(50, DBG_CRITICAL, "ERROR: listen(" << status() << ", " << (Squid_MaxFD >> 2) << "): " << xstrerror());
0ba55a12
AJ
156 errcode = errno;
157 return;
158 }
159
160 if (Config.accept_filter && strcmp(Config.accept_filter, "none") != 0) {
161#ifdef SO_ACCEPTFILTER
162 struct accept_filter_arg afa;
163 bzero(&afa, sizeof(afa));
5b67dfa4 164 debugs(5, DBG_IMPORTANT, "Installing accept filter '" << Config.accept_filter << "' on " << conn);
0ba55a12 165 xstrncpy(afa.af_name, Config.accept_filter, sizeof(afa.af_name));
a9870624 166 if (setsockopt(conn->fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa)) < 0)
5b67dfa4 167 debugs(5, DBG_CRITICAL, "WARNING: SO_ACCEPTFILTER '" << Config.accept_filter << "': '" << xstrerror());
0ba55a12
AJ
168#elif defined(TCP_DEFER_ACCEPT)
169 int seconds = 30;
170 if (strncmp(Config.accept_filter, "data=", 5) == 0)
171 seconds = atoi(Config.accept_filter + 5);
a9870624 172 if (setsockopt(conn->fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &seconds, sizeof(seconds)) < 0)
5b67dfa4 173 debugs(5, DBG_CRITICAL, "WARNING: TCP_DEFER_ACCEPT '" << Config.accept_filter << "': '" << xstrerror());
0ba55a12 174#else
5b67dfa4 175 debugs(5, DBG_CRITICAL, "WARNING: accept_filter not supported on your OS");
0ba55a12
AJ
176#endif
177 }
04f55905
AJ
178}
179
180/**
181 * This private callback is called whenever a filedescriptor is ready
182 * to dupe itself and fob off an accept()ed connection
183 *
184 * It will either do that accept operation. Or if there are not enough FD
185 * available to do the clone safely will push the listening FD into a list
186 * of deferred operations. The list gets kicked and the dupe/accept() actually
187 * done later when enough sockets become available.
188 */
189void
cbff89ba 190Comm::TcpAcceptor::doAccept(int fd, void *data)
04f55905 191{
5b67dfa4
AJ
192 try {
193 debugs(5, 2, HERE << "New connection on FD " << fd);
04f55905 194
5b67dfa4 195 Must(isOpen(fd));
cbff89ba 196 TcpAcceptor *afd = static_cast<TcpAcceptor*>(data);
04f55905 197
5b67dfa4
AJ
198 if (!okToAccept()) {
199 AcceptLimiter::Instance().defer(afd);
200 } else {
201 afd->acceptNext();
202 }
cbff89ba 203 SetSelect(fd, COMM_SELECT_READ, Comm::TcpAcceptor::doAccept, afd, 0);
5b67dfa4 204
db98b2bd 205 } catch (const std::exception &e) {
cbff89ba 206 fatalf("FATAL: error while accepting new client connection: %s\n", e.what());
db98b2bd 207 } catch (...) {
5b67dfa4 208 fatal("FATAL: error while accepting new client connection: [unkown]\n");
04f55905 209 }
04f55905
AJ
210}
211
212bool
cbff89ba 213Comm::TcpAcceptor::okToAccept()
04f55905
AJ
214{
215 static time_t last_warn = 0;
216
217 if (fdNFree() >= RESERVED_FD)
218 return true;
219
220 if (last_warn + 15 < squid_curtime) {
221 debugs(5, DBG_CRITICAL, "WARNING! Your cache is running out of filedescriptors");
222 last_warn = squid_curtime;
223 }
224
225 return false;
226}
227
971581ee 228void
cbff89ba 229Comm::TcpAcceptor::acceptOne()
04f55905
AJ
230{
231 /*
232 * We don't worry about running low on FDs here. Instead,
233 * doAccept() will use AcceptLimiter if we reach the limit
234 * there.
235 */
236
237 /* Accept a new connection */
5b67dfa4 238 ConnectionPointer newConnDetails = new Connection();
8bbb16e3 239 const comm_err_t flag = oldAccept(newConnDetails);
04f55905
AJ
240
241 /* Check for errors */
5b67dfa4 242 if (!newConnDetails->isOpen()) {
04f55905 243
cbff89ba 244 if (flag == COMM_NOMESSAGE) {
04f55905 245 /* register interest again */
6f8536c0 246 debugs(5, 5, HERE << "try later: " << conn << " handler Subscription: " << theCallSub);
8bbb16e3 247 SetSelect(conn->fd, COMM_SELECT_READ, doAccept, this, 0);
971581ee 248 return;
04f55905
AJ
249 }
250
251 // A non-recoverable error; notify the caller */
cbff89ba 252 debugs(5, 5, HERE << "non-recoverable error:" << status() << " handler Subscription: " << theCallSub);
8bbb16e3 253 notify(flag, newConnDetails);
5b67dfa4 254 mustStop("Listener socket closed");
971581ee 255 return;
04f55905
AJ
256 }
257
5b67dfa4
AJ
258 debugs(5, 5, HERE << "Listener: " << conn <<
259 " accepted new connection " << newConnDetails <<
6f8536c0 260 " handler Subscription: " << theCallSub);
8bbb16e3 261 notify(flag, newConnDetails);
04f55905
AJ
262}
263
264void
cbff89ba 265Comm::TcpAcceptor::acceptNext()
04f55905 266{
a9870624 267 Must(IsConnOpen(conn));
5b67dfa4 268 debugs(5, 2, HERE << "connection on " << conn);
971581ee 269 acceptOne();
04f55905
AJ
270}
271
272void
8bbb16e3 273Comm::TcpAcceptor::notify(const comm_err_t flag, const Comm::ConnectionPointer &newConnDetails) const
04f55905
AJ
274{
275 // listener socket handlers just abandon the port with COMM_ERR_CLOSING
276 // it should only happen when this object is deleted...
1fc32b95 277 if (flag == COMM_ERR_CLOSING) {
04f55905
AJ
278 return;
279 }
280
5b67dfa4
AJ
281 if (theCallSub != NULL) {
282 AsyncCall::Pointer call = theCallSub->callback();
283 CommAcceptCbParams &params = GetCommParams<CommAcceptCbParams>(call);
a9870624 284 params.fd = conn->fd;
5b67dfa4 285 params.conn = newConnDetails;
0ba55a12
AJ
286 params.flag = flag;
287 params.xerrno = errcode;
288 ScheduleCallHere(call);
0ba55a12 289 }
04f55905
AJ
290}
291
292/**
97b8ac39 293 * accept() and process
5b67dfa4
AJ
294 * Wait for an incoming connection on our listener socket.
295 *
296 * \retval COMM_OK success. details parameter filled.
297 * \retval COMM_NOMESSAGE attempted accept() but nothing useful came in.
298 * \retval COMM_ERROR an outright failure occured.
299 * Or if this client has too many connections already.
273f66c4 300 */
5b67dfa4 301comm_err_t
8bbb16e3 302Comm::TcpAcceptor::oldAccept(Comm::ConnectionPointer &details)
04f55905
AJ
303{
304 PROF_start(comm_accept);
e4f1fdae 305 ++statCounter.syscalls.sock.accepts;
04f55905
AJ
306 int sock;
307 struct addrinfo *gai = NULL;
5b67dfa4 308 details->local.InitAddrInfo(gai);
04f55905 309
1fc32b95 310 errcode = 0; // reset local errno copy.
a9870624 311 if ((sock = accept(conn->fd, gai->ai_addr, &gai->ai_addrlen)) < 0) {
1fc32b95 312 errcode = errno; // store last accept errno locally.
04f55905 313
5b67dfa4 314 details->local.FreeAddrInfo(gai);
04f55905
AJ
315
316 PROF_stop(comm_accept);
317
318 if (ignoreErrno(errno)) {
cbff89ba 319 debugs(50, 5, HERE << status() << ": " << xstrerror());
04f55905
AJ
320 return COMM_NOMESSAGE;
321 } else if (ENFILE == errno || EMFILE == errno) {
cbff89ba 322 debugs(50, 3, HERE << status() << ": " << xstrerror());
04f55905
AJ
323 return COMM_ERROR;
324 } else {
e0236918 325 debugs(50, DBG_IMPORTANT, HERE << status() << ": " << xstrerror());
04f55905
AJ
326 return COMM_ERROR;
327 }
328 }
329
a9870624 330 Must(sock >= 0);
5b67dfa4
AJ
331 details->fd = sock;
332 details->remote = *gai;
04f55905 333
5511c78a 334 if ( Config.client_ip_max_connections >= 0) {
5b67dfa4
AJ
335 if (clientdbEstablished(details->remote, 0) > Config.client_ip_max_connections) {
336 debugs(50, DBG_IMPORTANT, "WARNING: " << details->remote << " attempting more than " << Config.client_ip_max_connections << " connections.");
337 details->local.FreeAddrInfo(gai);
5511c78a
AJ
338 return COMM_ERROR;
339 }
340 }
341
903198a7 342 // lookup the local-end details of this new connection
5b67dfa4
AJ
343 details->local.InitAddrInfo(gai);
344 details->local.SetEmpty();
04f55905 345 getsockname(sock, gai->ai_addr, &gai->ai_addrlen);
5b67dfa4
AJ
346 details->local = *gai;
347 details->local.FreeAddrInfo(gai);
04f55905
AJ
348
349 /* fdstat update */
5b67dfa4 350 // XXX : these are not all HTTP requests. use a note about type and ip:port details->
903198a7 351 // so we end up with a uniform "(HTTP|FTP-data|HTTPS|...) remote-ip:remote-port"
04f55905
AJ
352 fd_open(sock, FD_SOCKET, "HTTP Request");
353
354 fdd_table[sock].close_file = NULL;
355 fdd_table[sock].close_line = 0;
356
357 fde *F = &fd_table[sock];
5b67dfa4
AJ
358 details->remote.NtoA(F->ipaddr,MAX_IPSTRLEN);
359 F->remote_port = details->remote.GetPort();
360 F->local_addr = details->local;
361 F->sock_family = details->local.IsIPv6()?AF_INET6:AF_INET;
04f55905 362
903198a7
AJ
363 // set socket flags
364 commSetCloseOnExec(sock);
04f55905
AJ
365 commSetNonBlocking(sock);
366
367 /* IFF the socket is (tproxy) transparent, pass the flag down to allow spoofing */
40d34a62
AJ
368 F->flags.transparent = fd_table[conn->fd].flags.transparent; // XXX: can we remove this line yet?
369
370 // Perform NAT or TPROXY operations to retrieve the real client/dest IP addresses
371 if (conn->flags&(COMM_TRANSPARENT|COMM_INTERCEPTION) && !Ip::Interceptor.Lookup(details, conn)) {
372 // Failed.
373 return COMM_ERROR;
374 }
04f55905
AJ
375
376 PROF_stop(comm_accept);
5b67dfa4 377 return COMM_OK;
04f55905 378}