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