]> git.ipfire.org Git - thirdparty/squid.git/blame - src/comm/TcpAcceptor.cc
SourceFormat Enforcement
[thirdparty/squid.git] / src / comm / TcpAcceptor.cc
CommitLineData
04f55905 1/*
f6e9a3ee 2 * Copyright (C) 1996-2019 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{
cbff89ba 77 debugs(5, 5, HERE << status() << " AsyncCall Subscription: " << theCallSub);
a9870624
AJ
78
79 Must(IsConnOpen(conn));
80
81 setListen();
82
8aec3e1b
CT
83 conn->noteStart();
84
a9870624
AJ
85 // if no error so far start accepting connections.
86 if (errcode == 0)
8bbb16e3 87 SetSelect(conn->fd, COMM_SELECT_READ, doAccept, this, 0);
a9870624
AJ
88}
89
90bool
cbff89ba 91Comm::TcpAcceptor::doneAll() const
a9870624 92{
6f8536c0 93 // stop when FD is closed
a9870624 94 if (!IsConnOpen(conn)) {
a9870624
AJ
95 return AsyncJob::doneAll();
96 }
97
5b67dfa4
AJ
98 // stop when handlers are gone
99 if (theCallSub == NULL) {
a9870624
AJ
100 return AsyncJob::doneAll();
101 }
102
5b67dfa4 103 // open FD with handlers...keep accepting.
a9870624
AJ
104 return false;
105}
106
107void
cbff89ba 108Comm::TcpAcceptor::swanSong()
a9870624
AJ
109{
110 debugs(5,5, HERE);
5b67dfa4 111 unsubscribe("swanSong");
6f09127c
AR
112 if (IsConnOpen(conn)) {
113 if (closer_ != NULL)
114 comm_remove_close_handler(conn->fd, closer_);
115 conn->close();
116 }
117
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')
4dd643d5 131 conn->local.toHostStr(ipbuf, MAX_IPSTRLEN);
cbff89ba
AJ
132
133 static MemBuf buf;
134 buf.reset();
4391cd15 135 buf.appendf(" 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 152{
5dc67d58 153 errcode = errno = 0;
a9870624 154 if (listen(conn->fd, Squid_MaxFD >> 2) < 0) {
0ba55a12 155 errcode = errno;
5dc67d58 156 debugs(50, DBG_CRITICAL, "ERROR: listen(" << status() << ", " << (Squid_MaxFD >> 2) << "): " << xstrerr(errcode));
0ba55a12
AJ
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));
b69e9ffa
AJ
166 if (setsockopt(conn->fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa)) < 0) {
167 int xerrno = errno;
168 debugs(5, DBG_CRITICAL, "WARNING: SO_ACCEPTFILTER '" << Config.accept_filter << "': '" << xstrerr(xerrno));
169 }
0ba55a12
AJ
170#elif defined(TCP_DEFER_ACCEPT)
171 int seconds = 30;
172 if (strncmp(Config.accept_filter, "data=", 5) == 0)
173 seconds = atoi(Config.accept_filter + 5);
b69e9ffa
AJ
174 if (setsockopt(conn->fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &seconds, sizeof(seconds)) < 0) {
175 int xerrno = errno;
176 debugs(5, DBG_CRITICAL, "WARNING: TCP_DEFER_ACCEPT '" << Config.accept_filter << "': '" << xstrerr(xerrno));
177 }
0ba55a12 178#else
5b67dfa4 179 debugs(5, DBG_CRITICAL, "WARNING: accept_filter not supported on your OS");
0ba55a12
AJ
180#endif
181 }
6f09127c 182
c6f168c1
CT
183#if 0
184 // Untested code.
185 // Set TOS if needed.
186 // To correctly implement TOS values on listening sockets, probably requires
187 // more work to inherit TOS values to created connection objects.
4b77ea6b 188 if (conn->tos)
6f9bd9b2 189 Ip::Qos::setSockTos(conn, conn->tos)
c6f168c1 190#if SO_MARK
6f9bd9b2 191 if (conn->nfmark)
4b77ea6b 192 Ip::Qos::setSockNfmark(conn, conn->nfmark);
c6f168c1
CT
193#endif
194#endif
195
6f09127c
AR
196 typedef CommCbMemFunT<Comm::TcpAcceptor, CommCloseCbParams> Dialer;
197 closer_ = JobCallback(5, 4, Dialer, this, Comm::TcpAcceptor::handleClosure);
198 comm_add_close_handler(conn->fd, closer_);
199}
200
201/// called when listening descriptor is closed by an external force
202/// such as clientHttpConnectionsClose()
203void
ced8def3 204Comm::TcpAcceptor::handleClosure(const CommCloseCbParams &)
6f09127c
AR
205{
206 closer_ = NULL;
207 conn = NULL;
208 Must(done());
04f55905
AJ
209}
210
211/**
212 * This private callback is called whenever a filedescriptor is ready
213 * to dupe itself and fob off an accept()ed connection
214 *
215 * It will either do that accept operation. Or if there are not enough FD
216 * available to do the clone safely will push the listening FD into a list
217 * of deferred operations. The list gets kicked and the dupe/accept() actually
218 * done later when enough sockets become available.
219 */
220void
cbff89ba 221Comm::TcpAcceptor::doAccept(int fd, void *data)
04f55905 222{
5b67dfa4
AJ
223 try {
224 debugs(5, 2, HERE << "New connection on FD " << fd);
04f55905 225
5b67dfa4 226 Must(isOpen(fd));
cbff89ba 227 TcpAcceptor *afd = static_cast<TcpAcceptor*>(data);
04f55905 228
5b67dfa4
AJ
229 if (!okToAccept()) {
230 AcceptLimiter::Instance().defer(afd);
231 } else {
232 afd->acceptNext();
233 }
5b67dfa4 234
db98b2bd 235 } catch (const std::exception &e) {
cbff89ba 236 fatalf("FATAL: error while accepting new client connection: %s\n", e.what());
db98b2bd 237 } catch (...) {
fbdf945d 238 fatal("FATAL: error while accepting new client connection: [unknown]\n");
04f55905 239 }
04f55905
AJ
240}
241
242bool
cbff89ba 243Comm::TcpAcceptor::okToAccept()
04f55905
AJ
244{
245 static time_t last_warn = 0;
246
247 if (fdNFree() >= RESERVED_FD)
248 return true;
249
250 if (last_warn + 15 < squid_curtime) {
251 debugs(5, DBG_CRITICAL, "WARNING! Your cache is running out of filedescriptors");
252 last_warn = squid_curtime;
253 }
254
255 return false;
256}
257
da6dbcd1
EB
258static void
259logAcceptError(const Comm::ConnectionPointer &conn)
260{
261 AccessLogEntry::Pointer al = new AccessLogEntry;
262 al->tcpClient = conn;
263 al->url = "error:accept-client-connection";
bec110e4 264 al->setVirginUrlForMissingRequest(al->url);
da6dbcd1
EB
265 ACLFilledChecklist ch(nullptr, nullptr, nullptr);
266 ch.src_addr = conn->remote;
267 ch.my_addr = conn->local;
cb365059 268 ch.al = al;
da6dbcd1
EB
269 accessLogLog(al, &ch);
270}
271
971581ee 272void
cbff89ba 273Comm::TcpAcceptor::acceptOne()
04f55905
AJ
274{
275 /*
276 * We don't worry about running low on FDs here. Instead,
277 * doAccept() will use AcceptLimiter if we reach the limit
278 * there.
279 */
280
281 /* Accept a new connection */
5b67dfa4 282 ConnectionPointer newConnDetails = new Connection();
c8407295 283 const Comm::Flag flag = oldAccept(newConnDetails);
04f55905
AJ
284
285 /* Check for errors */
5b67dfa4 286 if (!newConnDetails->isOpen()) {
04f55905 287
c8407295 288 if (flag == Comm::NOMESSAGE) {
04f55905 289 /* register interest again */
6f8536c0 290 debugs(5, 5, HERE << "try later: " << conn << " handler Subscription: " << theCallSub);
8bbb16e3 291 SetSelect(conn->fd, COMM_SELECT_READ, doAccept, this, 0);
971581ee 292 return;
04f55905
AJ
293 }
294
295 // A non-recoverable error; notify the caller */
cbff89ba 296 debugs(5, 5, HERE << "non-recoverable error:" << status() << " handler Subscription: " << theCallSub);
da6dbcd1
EB
297 if (intendedForUserConnections())
298 logAcceptError(newConnDetails);
8bbb16e3 299 notify(flag, newConnDetails);
5b67dfa4 300 mustStop("Listener socket closed");
971581ee 301 return;
04f55905
AJ
302 }
303
244da4ad 304 newConnDetails->nfConnmark = Ip::Qos::getNfConnmark(newConnDetails, Ip::Qos::dirAccepted);
653d9927 305
5b67dfa4
AJ
306 debugs(5, 5, HERE << "Listener: " << conn <<
307 " accepted new connection " << newConnDetails <<
6f8536c0 308 " handler Subscription: " << theCallSub);
8bbb16e3 309 notify(flag, newConnDetails);
f3b976f7 310 SetSelect(conn->fd, COMM_SELECT_READ, doAccept, this, 0);
04f55905
AJ
311}
312
313void
cbff89ba 314Comm::TcpAcceptor::acceptNext()
04f55905 315{
a9870624 316 Must(IsConnOpen(conn));
5b67dfa4 317 debugs(5, 2, HERE << "connection on " << conn);
971581ee 318 acceptOne();
04f55905
AJ
319}
320
321void
c8407295 322Comm::TcpAcceptor::notify(const Comm::Flag flag, const Comm::ConnectionPointer &newConnDetails) const
04f55905 323{
c8407295 324 // listener socket handlers just abandon the port with Comm::ERR_CLOSING
04f55905 325 // it should only happen when this object is deleted...
c8407295 326 if (flag == Comm::ERR_CLOSING) {
04f55905
AJ
327 return;
328 }
329
5b67dfa4
AJ
330 if (theCallSub != NULL) {
331 AsyncCall::Pointer call = theCallSub->callback();
332 CommAcceptCbParams &params = GetCommParams<CommAcceptCbParams>(call);
5ceaee75 333 params.xaction = new MasterXaction(XactionInitiator::initClient);
fa720bfb 334 params.xaction->squidPort = listenPort_;
a9870624 335 params.fd = conn->fd;
94bfd31f 336 params.conn = params.xaction->tcpClient = newConnDetails;
0ba55a12
AJ
337 params.flag = flag;
338 params.xerrno = errcode;
339 ScheduleCallHere(call);
0ba55a12 340 }
04f55905
AJ
341}
342
343/**
97b8ac39 344 * accept() and process
5b67dfa4
AJ
345 * Wait for an incoming connection on our listener socket.
346 *
61beade2
AJ
347 * \retval Comm::OK success. details parameter filled.
348 * \retval Comm::NOMESSAGE attempted accept() but nothing useful came in.
349 * \retval Comm::COMM_ERROR an outright failure occurred.
350 * Or this client has too many connections already.
273f66c4 351 */
c8407295 352Comm::Flag
8bbb16e3 353Comm::TcpAcceptor::oldAccept(Comm::ConnectionPointer &details)
04f55905
AJ
354{
355 PROF_start(comm_accept);
e4f1fdae 356 ++statCounter.syscalls.sock.accepts;
04f55905
AJ
357 int sock;
358 struct addrinfo *gai = NULL;
851614a8 359 Ip::Address::InitAddr(gai);
04f55905 360
1fc32b95 361 errcode = 0; // reset local errno copy.
a9870624 362 if ((sock = accept(conn->fd, gai->ai_addr, &gai->ai_addrlen)) < 0) {
1fc32b95 363 errcode = errno; // store last accept errno locally.
04f55905 364
851614a8 365 Ip::Address::FreeAddr(gai);
04f55905
AJ
366
367 PROF_stop(comm_accept);
368
b69e9ffa
AJ
369 if (ignoreErrno(errcode)) {
370 debugs(50, 5, status() << ": " << xstrerr(errcode));
c8407295 371 return Comm::NOMESSAGE;
04f55905 372 } else if (ENFILE == errno || EMFILE == errno) {
b69e9ffa 373 debugs(50, 3, status() << ": " << xstrerr(errcode));
4ee57cbe 374 return Comm::COMM_ERROR;
04f55905 375 } else {
b69e9ffa 376 debugs(50, DBG_IMPORTANT, MYNAME << status() << ": " << xstrerr(errcode));
4ee57cbe 377 return Comm::COMM_ERROR;
04f55905
AJ
378 }
379 }
380
a9870624 381 Must(sock >= 0);
5b67dfa4
AJ
382 details->fd = sock;
383 details->remote = *gai;
04f55905 384
5511c78a 385 if ( Config.client_ip_max_connections >= 0) {
5b67dfa4
AJ
386 if (clientdbEstablished(details->remote, 0) > Config.client_ip_max_connections) {
387 debugs(50, DBG_IMPORTANT, "WARNING: " << details->remote << " attempting more than " << Config.client_ip_max_connections << " connections.");
851614a8 388 Ip::Address::FreeAddr(gai);
6558fd54 389 PROF_stop(comm_accept);
4ee57cbe 390 return Comm::COMM_ERROR;
5511c78a
AJ
391 }
392 }
393
903198a7 394 // lookup the local-end details of this new connection
851614a8 395 Ip::Address::InitAddr(gai);
4dd643d5 396 details->local.setEmpty();
e42281f9 397 if (getsockname(sock, gai->ai_addr, &gai->ai_addrlen) != 0) {
b69e9ffa
AJ
398 int xerrno = errno;
399 debugs(50, DBG_IMPORTANT, "ERROR: getsockname() failed to locate local-IP on " << details << ": " << xstrerr(xerrno));
851614a8 400 Ip::Address::FreeAddr(gai);
6558fd54 401 PROF_stop(comm_accept);
4ee57cbe 402 return Comm::COMM_ERROR;
e42281f9 403 }
5b67dfa4 404 details->local = *gai;
851614a8 405 Ip::Address::FreeAddr(gai);
04f55905
AJ
406
407 /* fdstat update */
5b67dfa4 408 // XXX : these are not all HTTP requests. use a note about type and ip:port details->
903198a7 409 // so we end up with a uniform "(HTTP|FTP-data|HTTPS|...) remote-ip:remote-port"
04f55905
AJ
410 fd_open(sock, FD_SOCKET, "HTTP Request");
411
04f55905 412 fde *F = &fd_table[sock];
4dd643d5
AJ
413 details->remote.toStr(F->ipaddr,MAX_IPSTRLEN);
414 F->remote_port = details->remote.port();
5b67dfa4 415 F->local_addr = details->local;
4dd643d5 416 F->sock_family = details->local.isIPv6()?AF_INET6:AF_INET;
04f55905 417
903198a7
AJ
418 // set socket flags
419 commSetCloseOnExec(sock);
04f55905
AJ
420 commSetNonBlocking(sock);
421
422 /* IFF the socket is (tproxy) transparent, pass the flag down to allow spoofing */
40d34a62
AJ
423 F->flags.transparent = fd_table[conn->fd].flags.transparent; // XXX: can we remove this line yet?
424
425 // Perform NAT or TPROXY operations to retrieve the real client/dest IP addresses
426 if (conn->flags&(COMM_TRANSPARENT|COMM_INTERCEPTION) && !Ip::Interceptor.Lookup(details, conn)) {
ae0d2b74 427 debugs(50, DBG_IMPORTANT, "ERROR: NAT/TPROXY lookup failed to locate original IPs on " << details);
40d34a62 428 // Failed.
6558fd54 429 PROF_stop(comm_accept);
4ee57cbe 430 return Comm::COMM_ERROR;
40d34a62 431 }
04f55905 432
83b62d3f
AJ
433#if USE_SQUID_EUI
434 if (Eui::TheConfig.euiLookup) {
68e47c3e
AJ
435 if (details->remote.isIPv4()) {
436 details->remoteEui48.lookup(details->remote);
437 } else if (details->remote.isIPv6()) {
438 details->remoteEui64.lookup(details->remote);
83b62d3f
AJ
439 }
440 }
441#endif
442
04f55905 443 PROF_stop(comm_accept);
c8407295 444 return Comm::OK;
04f55905 445}
f53969cc 446