]> git.ipfire.org Git - thirdparty/squid.git/blame - src/comm/TcpAcceptor.cc
Bug 5055: FATAL FwdState::noteDestinationsEnd exception: opening (#877)
[thirdparty/squid.git] / src / comm / TcpAcceptor.cc
CommitLineData
04f55905 1/*
f70aedc4 2 * Copyright (C) 1996-2021 The Squid Software Foundation and contributors
04f55905 3 *
bbc27441
AJ
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
04f55905
AJ
7 */
8
bbc27441
AJ
9/* DEBUG: section 05 Listener Socket Handler */
10
582c2af2 11#include "squid.h"
da6dbcd1 12#include "acl/FilledChecklist.h"
94bfd31f 13#include "anyp/PortCfg.h"
a9870624 14#include "base/TextException.h"
95e6d864 15#include "client_db.h"
04f55905
AJ
16#include "comm/AcceptLimiter.h"
17#include "comm/comm_internal.h"
5b67dfa4 18#include "comm/Connection.h"
d841c88d 19#include "comm/Loops.h"
cbff89ba 20#include "comm/TcpAcceptor.h"
602d9612 21#include "CommCalls.h"
83b62d3f 22#include "eui/Config.h"
c4ad1349 23#include "fd.h"
04f55905 24#include "fde.h"
67679543 25#include "globals.h"
40d34a62 26#include "ip/Intercept.h"
c6f168c1 27#include "ip/QosConfig.h"
da6dbcd1 28#include "log/access_log.h"
94bfd31f 29#include "MasterXaction.h"
582c2af2 30#include "profiler/Profiler.h"
4d5904f7 31#include "SquidConfig.h"
04f55905 32#include "SquidTime.h"
e4f1fdae 33#include "StatCounters.h"
04f55905 34
1a30fdf5 35#include <cerrno>
f842580f
AJ
36#ifdef HAVE_NETINET_TCP_H
37// required for accept_filter to build.
38#include <netinet/tcp.h>
39#endif
21d845b1 40
f842580f 41CBDATA_NAMESPACED_CLASS_INIT(Comm, TcpAcceptor);
a9870624 42
ced8def3 43Comm::TcpAcceptor::TcpAcceptor(const Comm::ConnectionPointer &newConn, const char *, const Subscription::Pointer &aSub) :
f53969cc
SM
44 AsyncJob("Comm::TcpAcceptor"),
45 errcode(0),
f53969cc
SM
46 theCallSub(aSub),
47 conn(newConn),
48 listenPort_()
fa720bfb
AJ
49{}
50
ced8def3 51Comm::TcpAcceptor::TcpAcceptor(const AnyP::PortCfgPointer &p, const char *, const Subscription::Pointer &aSub) :
f53969cc
SM
52 AsyncJob("Comm::TcpAcceptor"),
53 errcode(0),
f53969cc
SM
54 theCallSub(aSub),
55 conn(p->listenConn),
56 listenPort_(p)
cbff89ba 57{}
0ba55a12
AJ
58
59void
cbff89ba 60Comm::TcpAcceptor::subscribe(const Subscription::Pointer &aSub)
0ba55a12 61{
cbff89ba 62 debugs(5, 5, HERE << status() << " AsyncCall Subscription: " << aSub);
5b67dfa4
AJ
63 unsubscribe("subscription change");
64 theCallSub = aSub;
4c5518e5
AJ
65}
66
0ba55a12 67void
cbff89ba 68Comm::TcpAcceptor::unsubscribe(const char *reason)
0ba55a12 69{
cbff89ba 70 debugs(5, 5, HERE << status() << " AsyncCall Subscription " << theCallSub << " removed: " << reason);
5b67dfa4 71 theCallSub = NULL;
0ba55a12
AJ
72}
73
a9870624 74void
cbff89ba 75Comm::TcpAcceptor::start()
a9870624 76{
ccfbe8f4
AR
77 if (listenPort_)
78 CodeContext::Reset(listenPort_);
cbff89ba 79 debugs(5, 5, HERE << status() << " AsyncCall Subscription: " << theCallSub);
a9870624
AJ
80
81 Must(IsConnOpen(conn));
82
83 setListen();
84
8aec3e1b
CT
85 conn->noteStart();
86
a9870624
AJ
87 // if no error so far start accepting connections.
88 if (errcode == 0)
8bbb16e3 89 SetSelect(conn->fd, COMM_SELECT_READ, doAccept, this, 0);
a9870624
AJ
90}
91
92bool
cbff89ba 93Comm::TcpAcceptor::doneAll() const
a9870624 94{
6f8536c0 95 // stop when FD is closed
a9870624 96 if (!IsConnOpen(conn)) {
a9870624
AJ
97 return AsyncJob::doneAll();
98 }
99
5b67dfa4
AJ
100 // stop when handlers are gone
101 if (theCallSub == NULL) {
a9870624
AJ
102 return AsyncJob::doneAll();
103 }
104
5b67dfa4 105 // open FD with handlers...keep accepting.
a9870624
AJ
106 return false;
107}
108
109void
cbff89ba 110Comm::TcpAcceptor::swanSong()
a9870624
AJ
111{
112 debugs(5,5, HERE);
5b67dfa4 113 unsubscribe("swanSong");
6f09127c
AR
114 if (IsConnOpen(conn)) {
115 if (closer_ != NULL)
116 comm_remove_close_handler(conn->fd, closer_);
117 conn->close();
118 }
119
a9870624 120 conn = NULL;
5b67dfa4 121 AcceptLimiter::Instance().removeDead(this);
a9870624
AJ
122 AsyncJob::swanSong();
123}
124
cbff89ba
AJ
125const char *
126Comm::TcpAcceptor::status() const
127{
8bbb16e3
AJ
128 if (conn == NULL)
129 return "[nil connection]";
130
cbff89ba
AJ
131 static char ipbuf[MAX_IPSTRLEN] = {'\0'};
132 if (ipbuf[0] == '\0')
4dd643d5 133 conn->local.toHostStr(ipbuf, MAX_IPSTRLEN);
cbff89ba
AJ
134
135 static MemBuf buf;
136 buf.reset();
4391cd15 137 buf.appendf(" FD %d, %s",conn->fd, ipbuf);
cbff89ba
AJ
138
139 const char *jobStatus = AsyncJob::status();
140 buf.append(jobStatus, strlen(jobStatus));
141
142 return buf.content();
143}
144
0ba55a12
AJ
145/**
146 * New-style listen and accept routines
147 *
148 * setListen simply registers our interest in an FD for listening.
149 * The constructor takes a callback to call when an FD has been
150 * accept()ed some time later.
151 */
152void
cbff89ba 153Comm::TcpAcceptor::setListen()
0ba55a12 154{
5dc67d58 155 errcode = errno = 0;
a9870624 156 if (listen(conn->fd, Squid_MaxFD >> 2) < 0) {
0ba55a12 157 errcode = errno;
ccfbe8f4 158 debugs(50, DBG_CRITICAL, "ERROR: listen(..., " << (Squid_MaxFD >> 2) << ") system call failed: " << xstrerr(errcode));
0ba55a12
AJ
159 return;
160 }
161
162 if (Config.accept_filter && strcmp(Config.accept_filter, "none") != 0) {
163#ifdef SO_ACCEPTFILTER
164 struct accept_filter_arg afa;
165 bzero(&afa, sizeof(afa));
5b67dfa4 166 debugs(5, DBG_IMPORTANT, "Installing accept filter '" << Config.accept_filter << "' on " << conn);
0ba55a12 167 xstrncpy(afa.af_name, Config.accept_filter, sizeof(afa.af_name));
b69e9ffa
AJ
168 if (setsockopt(conn->fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa)) < 0) {
169 int xerrno = errno;
170 debugs(5, DBG_CRITICAL, "WARNING: SO_ACCEPTFILTER '" << Config.accept_filter << "': '" << xstrerr(xerrno));
171 }
0ba55a12
AJ
172#elif defined(TCP_DEFER_ACCEPT)
173 int seconds = 30;
174 if (strncmp(Config.accept_filter, "data=", 5) == 0)
175 seconds = atoi(Config.accept_filter + 5);
b69e9ffa
AJ
176 if (setsockopt(conn->fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &seconds, sizeof(seconds)) < 0) {
177 int xerrno = errno;
178 debugs(5, DBG_CRITICAL, "WARNING: TCP_DEFER_ACCEPT '" << Config.accept_filter << "': '" << xstrerr(xerrno));
179 }
0ba55a12 180#else
5b67dfa4 181 debugs(5, DBG_CRITICAL, "WARNING: accept_filter not supported on your OS");
0ba55a12
AJ
182#endif
183 }
6f09127c
AR
184
185 typedef CommCbMemFunT<Comm::TcpAcceptor, CommCloseCbParams> Dialer;
186 closer_ = JobCallback(5, 4, Dialer, this, Comm::TcpAcceptor::handleClosure);
187 comm_add_close_handler(conn->fd, closer_);
188}
189
190/// called when listening descriptor is closed by an external force
191/// such as clientHttpConnectionsClose()
192void
ced8def3 193Comm::TcpAcceptor::handleClosure(const CommCloseCbParams &)
6f09127c
AR
194{
195 closer_ = NULL;
2b6b1bcb
AR
196 if (conn) {
197 conn->noteClosure();
198 conn = nullptr;
199 }
6f09127c 200 Must(done());
04f55905
AJ
201}
202
203/**
204 * This private callback is called whenever a filedescriptor is ready
205 * to dupe itself and fob off an accept()ed connection
206 *
207 * It will either do that accept operation. Or if there are not enough FD
208 * available to do the clone safely will push the listening FD into a list
209 * of deferred operations. The list gets kicked and the dupe/accept() actually
210 * done later when enough sockets become available.
211 */
212void
cbff89ba 213Comm::TcpAcceptor::doAccept(int fd, void *data)
04f55905 214{
5b67dfa4
AJ
215 try {
216 debugs(5, 2, HERE << "New connection on FD " << fd);
04f55905 217
5b67dfa4 218 Must(isOpen(fd));
cbff89ba 219 TcpAcceptor *afd = static_cast<TcpAcceptor*>(data);
04f55905 220
5b67dfa4
AJ
221 if (!okToAccept()) {
222 AcceptLimiter::Instance().defer(afd);
223 } else {
224 afd->acceptNext();
225 }
5b67dfa4 226
db98b2bd 227 } catch (const std::exception &e) {
cbff89ba 228 fatalf("FATAL: error while accepting new client connection: %s\n", e.what());
db98b2bd 229 } catch (...) {
fbdf945d 230 fatal("FATAL: error while accepting new client connection: [unknown]\n");
04f55905 231 }
04f55905
AJ
232}
233
234bool
cbff89ba 235Comm::TcpAcceptor::okToAccept()
04f55905
AJ
236{
237 static time_t last_warn = 0;
238
239 if (fdNFree() >= RESERVED_FD)
240 return true;
241
242 if (last_warn + 15 < squid_curtime) {
243 debugs(5, DBG_CRITICAL, "WARNING! Your cache is running out of filedescriptors");
244 last_warn = squid_curtime;
245 }
246
247 return false;
248}
249
ccfbe8f4
AR
250void
251Comm::TcpAcceptor::logAcceptError(const ConnectionPointer &tcpClient) const
da6dbcd1
EB
252{
253 AccessLogEntry::Pointer al = new AccessLogEntry;
ccfbe8f4
AR
254 CodeContext::Reset(al);
255 al->tcpClient = tcpClient;
da6dbcd1 256 al->url = "error:accept-client-connection";
bec110e4 257 al->setVirginUrlForMissingRequest(al->url);
da6dbcd1 258 ACLFilledChecklist ch(nullptr, nullptr, nullptr);
ccfbe8f4
AR
259 ch.src_addr = tcpClient->remote;
260 ch.my_addr = tcpClient->local;
cb365059 261 ch.al = al;
da6dbcd1 262 accessLogLog(al, &ch);
ccfbe8f4
AR
263
264 CodeContext::Reset(listenPort_);
da6dbcd1
EB
265}
266
971581ee 267void
cbff89ba 268Comm::TcpAcceptor::acceptOne()
04f55905
AJ
269{
270 /*
271 * We don't worry about running low on FDs here. Instead,
272 * doAccept() will use AcceptLimiter if we reach the limit
273 * there.
274 */
275
276 /* Accept a new connection */
5b67dfa4 277 ConnectionPointer newConnDetails = new Connection();
c8407295 278 const Comm::Flag flag = oldAccept(newConnDetails);
04f55905 279
29a0bb6a 280 if (flag == Comm::COMM_ERROR) {
04f55905 281 // A non-recoverable error; notify the caller */
cbff89ba 282 debugs(5, 5, HERE << "non-recoverable error:" << status() << " handler Subscription: " << theCallSub);
da6dbcd1
EB
283 if (intendedForUserConnections())
284 logAcceptError(newConnDetails);
8bbb16e3 285 notify(flag, newConnDetails);
5b67dfa4 286 mustStop("Listener socket closed");
971581ee 287 return;
04f55905
AJ
288 }
289
29a0bb6a
AJ
290 if (flag == Comm::NOMESSAGE) {
291 /* register interest again */
292 debugs(5, 5, "try later: " << conn << " handler Subscription: " << theCallSub);
293 } else {
ccfbe8f4
AR
294 // TODO: When ALE, MasterXaction merge, use them or ClientConn instead.
295 CodeContext::Reset(newConnDetails);
29a0bb6a
AJ
296 debugs(5, 5, "Listener: " << conn <<
297 " accepted new connection " << newConnDetails <<
298 " handler Subscription: " << theCallSub);
299 notify(flag, newConnDetails);
ccfbe8f4 300 CodeContext::Reset(listenPort_);
29a0bb6a 301 }
653d9927 302
f3b976f7 303 SetSelect(conn->fd, COMM_SELECT_READ, doAccept, this, 0);
04f55905
AJ
304}
305
306void
cbff89ba 307Comm::TcpAcceptor::acceptNext()
04f55905 308{
a9870624 309 Must(IsConnOpen(conn));
5b67dfa4 310 debugs(5, 2, HERE << "connection on " << conn);
971581ee 311 acceptOne();
04f55905
AJ
312}
313
314void
c8407295 315Comm::TcpAcceptor::notify(const Comm::Flag flag, const Comm::ConnectionPointer &newConnDetails) const
04f55905 316{
c8407295 317 // listener socket handlers just abandon the port with Comm::ERR_CLOSING
04f55905 318 // it should only happen when this object is deleted...
c8407295 319 if (flag == Comm::ERR_CLOSING) {
04f55905
AJ
320 return;
321 }
322
5b67dfa4
AJ
323 if (theCallSub != NULL) {
324 AsyncCall::Pointer call = theCallSub->callback();
325 CommAcceptCbParams &params = GetCommParams<CommAcceptCbParams>(call);
5ceaee75 326 params.xaction = new MasterXaction(XactionInitiator::initClient);
fa720bfb 327 params.xaction->squidPort = listenPort_;
a9870624 328 params.fd = conn->fd;
94bfd31f 329 params.conn = params.xaction->tcpClient = newConnDetails;
0ba55a12
AJ
330 params.flag = flag;
331 params.xerrno = errcode;
332 ScheduleCallHere(call);
0ba55a12 333 }
04f55905
AJ
334}
335
336/**
97b8ac39 337 * accept() and process
5b67dfa4
AJ
338 * Wait for an incoming connection on our listener socket.
339 *
61beade2
AJ
340 * \retval Comm::OK success. details parameter filled.
341 * \retval Comm::NOMESSAGE attempted accept() but nothing useful came in.
61beade2 342 * Or this client has too many connections already.
29a0bb6a 343 * \retval Comm::COMM_ERROR an outright failure occurred.
273f66c4 344 */
c8407295 345Comm::Flag
8bbb16e3 346Comm::TcpAcceptor::oldAccept(Comm::ConnectionPointer &details)
04f55905
AJ
347{
348 PROF_start(comm_accept);
e4f1fdae 349 ++statCounter.syscalls.sock.accepts;
04f55905
AJ
350 int sock;
351 struct addrinfo *gai = NULL;
851614a8 352 Ip::Address::InitAddr(gai);
04f55905 353
1fc32b95 354 errcode = 0; // reset local errno copy.
a9870624 355 if ((sock = accept(conn->fd, gai->ai_addr, &gai->ai_addrlen)) < 0) {
1fc32b95 356 errcode = errno; // store last accept errno locally.
04f55905 357
851614a8 358 Ip::Address::FreeAddr(gai);
04f55905
AJ
359
360 PROF_stop(comm_accept);
361
fb730aad 362 if (ignoreErrno(errcode) || errcode == ECONNABORTED) {
b69e9ffa 363 debugs(50, 5, status() << ": " << xstrerr(errcode));
c8407295 364 return Comm::NOMESSAGE;
fb730aad 365 } else if (errcode == ENFILE || errcode == EMFILE) {
b69e9ffa 366 debugs(50, 3, status() << ": " << xstrerr(errcode));
4ee57cbe 367 return Comm::COMM_ERROR;
04f55905 368 } else {
ccfbe8f4 369 debugs(50, DBG_IMPORTANT, "ERROR: failed to accept an incoming connection: " << xstrerr(errcode));
4ee57cbe 370 return Comm::COMM_ERROR;
04f55905
AJ
371 }
372 }
373
a9870624 374 Must(sock >= 0);
72bfd2f2 375 ++incoming_sockets_accepted;
9205b24a
AR
376
377 // Sync with Comm ASAP so that abandoned details can properly close().
378 // XXX : these are not all HTTP requests. use a note about type and ip:port details->
379 // so we end up with a uniform "(HTTP|FTP-data|HTTPS|...) remote-ip:remote-port"
380 fd_open(sock, FD_SOCKET, "HTTP Request");
5b67dfa4 381 details->fd = sock;
4831b46c 382 details->enterOrphanage();
9205b24a 383
5b67dfa4 384 details->remote = *gai;
04f55905 385
903198a7 386 // lookup the local-end details of this new connection
851614a8 387 Ip::Address::InitAddr(gai);
4dd643d5 388 details->local.setEmpty();
e42281f9 389 if (getsockname(sock, gai->ai_addr, &gai->ai_addrlen) != 0) {
b69e9ffa
AJ
390 int xerrno = errno;
391 debugs(50, DBG_IMPORTANT, "ERROR: getsockname() failed to locate local-IP on " << details << ": " << xstrerr(xerrno));
851614a8 392 Ip::Address::FreeAddr(gai);
6558fd54 393 PROF_stop(comm_accept);
4ee57cbe 394 return Comm::COMM_ERROR;
e42281f9 395 }
5b67dfa4 396 details->local = *gai;
851614a8 397 Ip::Address::FreeAddr(gai);
04f55905 398
40d34a62
AJ
399 // Perform NAT or TPROXY operations to retrieve the real client/dest IP addresses
400 if (conn->flags&(COMM_TRANSPARENT|COMM_INTERCEPTION) && !Ip::Interceptor.Lookup(details, conn)) {
ae0d2b74 401 debugs(50, DBG_IMPORTANT, "ERROR: NAT/TPROXY lookup failed to locate original IPs on " << details);
40d34a62 402 // Failed.
6558fd54 403 PROF_stop(comm_accept);
4ee57cbe 404 return Comm::COMM_ERROR;
40d34a62 405 }
04f55905 406
83b62d3f
AJ
407#if USE_SQUID_EUI
408 if (Eui::TheConfig.euiLookup) {
68e47c3e
AJ
409 if (details->remote.isIPv4()) {
410 details->remoteEui48.lookup(details->remote);
411 } else if (details->remote.isIPv6()) {
412 details->remoteEui64.lookup(details->remote);
83b62d3f
AJ
413 }
414 }
415#endif
416
29a0bb6a
AJ
417 details->nfConnmark = Ip::Qos::getNfConnmark(details, Ip::Qos::dirAccepted);
418
419 if (Config.client_ip_max_connections >= 0) {
420 if (clientdbEstablished(details->remote, 0) > Config.client_ip_max_connections) {
421 debugs(50, DBG_IMPORTANT, "WARNING: " << details->remote << " attempting more than " << Config.client_ip_max_connections << " connections.");
422 PROF_stop(comm_accept);
423 return Comm::NOMESSAGE;
424 }
425 }
426
29a0bb6a
AJ
427 fde *F = &fd_table[sock];
428 details->remote.toStr(F->ipaddr,MAX_IPSTRLEN);
429 F->remote_port = details->remote.port();
430 F->local_addr = details->local;
431 F->sock_family = details->local.isIPv6()?AF_INET6:AF_INET;
432
433 // set socket flags
434 commSetCloseOnExec(sock);
435 commSetNonBlocking(sock);
1dde4660 436 Comm::ApplyTcpKeepAlive(sock, listenPort_->tcp_keepalive);
29a0bb6a
AJ
437
438 /* IFF the socket is (tproxy) transparent, pass the flag down to allow spoofing */
439 F->flags.transparent = fd_table[conn->fd].flags.transparent; // XXX: can we remove this line yet?
440
04f55905 441 PROF_stop(comm_accept);
c8407295 442 return Comm::OK;
04f55905 443}
f53969cc 444