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