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