]> git.ipfire.org Git - thirdparty/squid.git/blame - src/comm.cc
Release Notes: document squid-3.1 libecap known issue
[thirdparty/squid.git] / src / comm.cc
CommitLineData
30a4f2a8 1/*
b510f3a1 2 * DEBUG: section 05 Socket Functions
30a4f2a8 3 * AUTHOR: Harvest Derived
4 *
2b6662ba 5 * SQUID Web Proxy Cache http://www.squid-cache.org/
e25c139f 6 * ----------------------------------------------------------
30a4f2a8 7 *
2b6662ba 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.
30a4f2a8 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.
9e008dda 21 *
30a4f2a8 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.
9e008dda 26 *
30a4f2a8 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
cbdec147 29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
e25c139f 30 *
2d8c0b1a 31 *
32 * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org>
30a4f2a8 33 */
090089c4 34
f7f3304a 35#include "squid-old.h"
cfd66529 36#include "base/AsyncCall.h"
c4b7a5a9 37#include "StoreIOBuffer.h"
38#include "comm.h"
a553a5a3 39#include "event.h"
528b2c61 40#include "fde.h"
04f55905
AJ
41#include "comm/AcceptLimiter.h"
42#include "comm/comm_internal.h"
cfd66529 43#include "comm/Connection.h"
ec41b64c 44#include "comm/IoCallback.h"
d841c88d 45#include "comm/Loops.h"
ec41b64c 46#include "comm/Write.h"
cbff89ba 47#include "comm/TcpAcceptor.h"
a553a5a3 48#include "CommRead.h"
0eb49b6d 49#include "MemBuf.h"
781ce8ff 50#include "pconn.h"
985c86bc 51#include "SquidTime.h"
b0469965 52#include "CommCalls.h"
74257126 53#include "DescriptorSet.h"
9b5c4a9a 54#include "icmp/net_db.h"
96d89ea0
HN
55#include "ip/Address.h"
56#include "ip/Intercept.h"
425de4c8 57#include "ip/QosConfig.h"
055421ee 58#include "ip/tools.h"
b4cd430a 59#include "ClientInfo.h"
e4f1fdae 60#include "StatCounters.h"
4db984be
CT
61#if USE_SSL
62#include "ssl/support.h"
63#endif
090089c4 64
b4cd430a 65#include "cbdata.h"
be266cb2 66#if _SQUID_CYGWIN_
b671cc68 67#include <sys/ioctl.h>
68#endif
30a4f2a8 69#ifdef HAVE_NETINET_TCP_H
70#include <netinet/tcp.h>
71#endif
090089c4 72
2b663917 73/*
74 * New C-like simple comm code. This stuff is a mess and doesn't really buy us anything.
75 */
76
82ec8dfc
AR
77static void commStopHalfClosedMonitor(int fd);
78static IOCB commHalfClosedReader;
9c8a6c3b 79static void comm_init_opened(const Comm::ConnectionPointer &conn, tos_t tos, nfmark_t nfmark, const char *note, struct addrinfo *AI);
a67d2b2e 80static int comm_apply_flags(int new_socket, Ip::Address &addr, int flags, struct addrinfo *AI);
82ec8dfc 81
9a0a18de 82#if USE_DELAY_POOLS
b4cd430a
CT
83CBDATA_CLASS_INIT(CommQuotaQueue);
84
85static void commHandleWriteHelper(void * data);
86#endif
87
090089c4 88/* STATIC */
62e76326 89
74257126
AR
90static DescriptorSet *TheHalfClosed = NULL; /// the set of half-closed FDs
91static bool WillCheckHalfClosed = false; /// true if check is scheduled
92static EVH commHalfClosedCheck;
93static void commPlanHalfClosedCheck();
94
cc192b50 95static comm_err_t commBind(int s, struct addrinfo &);
f5b8bbc4 96static void commSetReuseAddr(int);
97static void commSetNoLinger(int);
30a4f2a8 98#ifdef TCP_NODELAY
f5b8bbc4 99static void commSetTcpNoDelay(int);
30a4f2a8 100#endif
f5b8bbc4 101static void commSetTcpRcvbuf(int, int);
723123a9 102
b001e822 103static MemAllocator *conn_close_pool = NULL;
c4b7a5a9 104fd_debug_t *fdd_table = NULL;
62e76326 105
04f55905 106bool
b0469965 107isOpen(const int fd)
b300c36d 108{
9a5ac93d 109 return fd >= 0 && fd_table && fd_table[fd].flags.open != 0;
b300c36d 110}
111
e1a88700 112/**
c4b7a5a9 113 * Attempt a read
114 *
115 * If the read attempt succeeds or fails, call the callback.
116 * Else, wait for another IO notification.
117 */
2d8c0b1a 118void
2b663917 119commHandleRead(int fd, void *data)
2d8c0b1a 120{
ec41b64c 121 Comm::IoCallback *ccb = (Comm::IoCallback *) data;
9e008dda 122
2b663917 123 assert(data == COMMIO_FD_READCB(fd));
ec41b64c 124 assert(ccb->active());
62e76326 125 /* Attempt a read */
126 statCounter.syscalls.sock.reads++;
127 errno = 0;
2d8c0b1a 128 int retval;
2b663917 129 retval = FD_READ_METHOD(fd, ccb->buf, ccb->size);
bf8fe701 130 debugs(5, 3, "comm_read_try: FD " << fd << ", size " << ccb->size << ", retval " << retval << ", errno " << errno);
62e76326 131
132 if (retval < 0 && !ignoreErrno(errno)) {
bf8fe701 133 debugs(5, 3, "comm_read_try: scheduling COMM_ERROR");
9e008dda 134 ccb->offset = 0;
ec41b64c 135 ccb->finish(COMM_ERROR, errno);
62e76326 136 return;
137 };
138
139 /* See if we read anything */
140 /* Note - read 0 == socket EOF, which is a valid read */
141 if (retval >= 0) {
142 fd_bytes(fd, retval, FD_READ);
9e008dda 143 ccb->offset = retval;
ec41b64c 144 ccb->finish(COMM_OK, errno);
62e76326 145 return;
146 }
c4b7a5a9 147
62e76326 148 /* Nope, register for some more IO */
d841c88d 149 Comm::SetSelect(fd, COMM_SELECT_READ, commHandleRead, data, 0);
c4b7a5a9 150}
151
abd8f140
AJ
152/**
153 * Queue a read. handler/handler_data are called when the read
154 * completes, on error, or on file descriptor close.
155 */
b0469965 156void
ec20038e 157comm_read(const Comm::ConnectionPointer &conn, char *buf, int size, AsyncCall::Pointer &callback)
c4b7a5a9 158{
ec20038e 159 debugs(5, 5, "comm_read, queueing read for " << conn << "; asynCall " << callback);
c4b7a5a9 160
82ec8dfc 161 /* Make sure we are open and not closing */
ec20038e
AJ
162 assert(Comm::IsConnOpen(conn));
163 assert(!fd_table[conn->fd].closing());
b0388924 164 Comm::IoCallback *ccb = COMMIO_FD_READCB(conn->fd);
82ec8dfc
AR
165
166 // Make sure we are either not reading or just passively monitoring.
167 // Active/passive conflicts are OK and simply cancel passive monitoring.
168 if (ccb->active()) {
169 // if the assertion below fails, we have an active comm_read conflict
ec20038e
AJ
170 assert(fd_table[conn->fd].halfClosedReader != NULL);
171 commStopHalfClosedMonitor(conn->fd);
82ec8dfc
AR
172 assert(!ccb->active());
173 }
b0388924 174 ccb->conn = conn;
528b2c61 175
2b663917 176 /* Queue the read */
ec41b64c 177 ccb->setCallback(Comm::IOCB_READ, callback, (char *)buf, NULL, size);
8bbb16e3 178 Comm::SetSelect(conn->fd, COMM_SELECT_READ, commHandleRead, ccb, 0);
c4b7a5a9 179}
180
e1a88700 181/**
c4b7a5a9 182 * Empty the read buffers
183 *
184 * This is a magical routine that empties the read buffers.
185 * Under some platforms (Linux) if a buffer has data in it before
186 * you call close(), the socket will hang and take quite a while
187 * to timeout.
188 */
189static void
190comm_empty_os_read_buffers(int fd)
191{
1191b93b 192#if _SQUID_LINUX_
c4b7a5a9 193 /* prevent those nasty RST packets */
194 char buf[SQUID_TCP_SO_RCVBUF];
62e76326 195
cc192b50 196 if (fd_table[fd].flags.nonblocking == 1) {
197 while (FD_READ_METHOD(fd, buf, SQUID_TCP_SO_RCVBUF) > 0) {};
198 }
c4b7a5a9 199#endif
200}
201
202
e1a88700 203/**
2b663917 204 * Return whether the FD has a pending completed callback.
e884bbde 205 * NP: does not work.
c4b7a5a9 206 */
207int
208comm_has_pending_read_callback(int fd)
209{
b0469965 210 assert(isOpen(fd));
211 // XXX: We do not know whether there is a read callback scheduled.
212 // This is used for pconn management that should probably be more
213 // tightly integrated into comm to minimize the chance that a
214 // closing pconn socket will be used for a new transaction.
545d554b 215 return false;
c4b7a5a9 216}
217
b0469965 218// Does comm check this fd for read readiness?
219// Note that when comm is not monitoring, there can be a pending callback
220// call, which may resume comm monitoring once fired.
528b2c61 221bool
b0469965 222comm_monitors_read(int fd)
c4b7a5a9 223{
b0469965 224 assert(isOpen(fd));
225 // Being active is usually the same as monitoring because we always
ec41b64c
AJ
226 // start monitoring the FD when we configure Comm::IoCallback for I/O
227 // and we usually configure Comm::IoCallback for I/O when we starting
228 // monitoring a FD for reading.
b0469965 229 return COMMIO_FD_READCB(fd)->active();
c4b7a5a9 230}
231
e1a88700 232/**
c4b7a5a9 233 * Cancel a pending read. Assert that we have the right parameters,
234 * and that there are no pending read events!
2b663917 235 *
b0469965 236 * XXX: We do not assert that there are no pending read events and
237 * with async calls it becomes even more difficult.
238 * The whole interface should be reworked to do callback->cancel()
239 * instead of searching for places where the callback may be stored and
240 * updating the state of those places.
241 *
2b663917 242 * AHC Don't call the comm handlers?
c4b7a5a9 243 */
244void
245comm_read_cancel(int fd, IOCB *callback, void *data)
246{
b0469965 247 if (!isOpen(fd)) {
248 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " closed");
249 return;
9e008dda 250 }
b0469965 251
ec41b64c 252 Comm::IoCallback *cb = COMMIO_FD_READCB(fd);
b0469965 253 // TODO: is "active" == "monitors FD"?
254 if (!cb->active()) {
255 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " inactive");
256 return;
9e008dda 257 }
b0469965 258
259 typedef CommCbFunPtrCallT<CommIoCbPtrFun> Call;
260 Call *call = dynamic_cast<Call*>(cb->callback.getRaw());
261 if (!call) {
262 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " lacks callback");
263 return;
9e008dda 264 }
b0469965 265
82ec8dfc
AR
266 call->cancel("old comm_read_cancel");
267
b0469965 268 typedef CommIoCbParams Params;
269 const Params &params = GetCommParams<Params>(cb->callback);
c4b7a5a9 270
c4b7a5a9 271 /* Ok, we can be reasonably sure we won't lose any data here! */
b0469965 272 assert(call->dialer.handler == callback);
273 assert(params.data == data);
c4b7a5a9 274
275 /* Delete the callback */
ec41b64c 276 cb->cancel("old comm_read_cancel");
420f2ac8 277
278 /* And the IO event */
d841c88d 279 Comm::SetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
c4b7a5a9 280}
281
c4b7a5a9 282void
b0469965 283comm_read_cancel(int fd, AsyncCall::Pointer &callback)
c4b7a5a9 284{
b0469965 285 callback->cancel("comm_read_cancel");
9e008dda 286
b0469965 287 if (!isOpen(fd)) {
288 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " closed");
289 return;
290 }
291
ec41b64c 292 Comm::IoCallback *cb = COMMIO_FD_READCB(fd);
b0469965 293
294 if (!cb->active()) {
295 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " inactive");
296 return;
297 }
298
299 AsyncCall::Pointer call = cb->callback;
82ec8dfc 300 assert(call != NULL); // XXX: should never fail (active() checks for callback==NULL)
9e008dda 301
b0469965 302 /* Ok, we can be reasonably sure we won't lose any data here! */
303 assert(call == callback);
c4b7a5a9 304
b0469965 305 /* Delete the callback */
ec41b64c 306 cb->cancel("comm_read_cancel");
b0469965 307
308 /* And the IO event */
d841c88d 309 Comm::SetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
c4b7a5a9 310}
311
312
e1a88700 313/**
ce767c23 314 * synchronous wrapper around udp socket functions
315 */
ce767c23 316int
b7ac5457 317comm_udp_recvfrom(int fd, void *buf, size_t len, int flags, Ip::Address &from)
ce767c23 318{
62e76326 319 statCounter.syscalls.sock.recvfroms++;
cc192b50 320 int x = 0;
321 struct addrinfo *AI = NULL;
322
323 debugs(5,8, "comm_udp_recvfrom: FD " << fd << " from " << from);
324
325 assert( NULL == AI );
326
327 from.InitAddrInfo(AI);
328
329 x = recvfrom(fd, buf, len, flags, AI->ai_addr, &AI->ai_addrlen);
330
331 from = *AI;
332
333 from.FreeAddrInfo(AI);
334
335 return x;
ce767c23 336}
337
365f12a9 338int
7d21986b 339comm_udp_recv(int fd, void *buf, size_t len, int flags)
365f12a9 340{
b7ac5457 341 Ip::Address nul;
cc192b50 342 return comm_udp_recvfrom(fd, buf, len, flags, nul);
365f12a9 343}
344
f71da12c 345ssize_t
7d21986b 346comm_udp_send(int s, const void *buf, size_t len, int flags)
f71da12c 347{
62e76326 348 return send(s, buf, len, flags);
f71da12c 349}
ce767c23 350
351
545d554b 352bool
353comm_has_incomplete_write(int fd)
354{
b0469965 355 assert(isOpen(fd));
356 return COMMIO_FD_WRITECB(fd)->active();
d4cb310b 357}
358
e1a88700 359/**
cf3c0ee3 360 * Queue a write. handler/handler_data are called when the write fully
361 * completes, on error, or on file descriptor close.
362 */
9864ee44 363
090089c4 364/* Return the local port associated with fd. */
f45dd259 365unsigned short
b8d8561b 366comm_local_port(int fd)
090089c4 367{
b7ac5457 368 Ip::Address temp;
cc192b50 369 struct addrinfo *addr = NULL;
76f87348 370 fde *F = &fd_table[fd];
090089c4 371
090089c4 372 /* If the fd is closed already, just return */
62e76326 373
60c0b5a2 374 if (!F->flags.open) {
bf8fe701 375 debugs(5, 0, "comm_local_port: FD " << fd << " has been closed.");
62e76326 376 return 0;
090089c4 377 }
62e76326 378
cc192b50 379 if (F->local_addr.GetPort())
380 return F->local_addr.GetPort();
62e76326 381
6084c0b6
AJ
382 if (F->sock_family == AF_INET)
383 temp.SetIPv4();
6084c0b6 384
cc192b50 385 temp.InitAddrInfo(addr);
62e76326 386
cc192b50 387 if (getsockname(fd, addr->ai_addr, &(addr->ai_addrlen)) ) {
bf8fe701 388 debugs(50, 1, "comm_local_port: Failed to retrieve TCP/UDP port number for socket: FD " << fd << ": " << xstrerror());
cc192b50 389 temp.FreeAddrInfo(addr);
62e76326 390 return 0;
090089c4 391 }
cc192b50 392 temp = *addr;
393
394 temp.FreeAddrInfo(addr);
395
3d031c35
AJ
396 if (F->local_addr.IsAnyAddr()) {
397 /* save the whole local address, not just the port. */
398 F->local_addr = temp;
399 } else {
400 F->local_addr.SetPort(temp.GetPort());
401 }
62e76326 402
6084c0b6 403 debugs(5, 6, "comm_local_port: FD " << fd << ": port " << F->local_addr.GetPort() << "(family=" << F->sock_family << ")");
cc192b50 404 return F->local_addr.GetPort();
090089c4 405}
406
3d7e9d7c 407static comm_err_t
cc192b50 408commBind(int s, struct addrinfo &inaddr)
090089c4 409{
83704487 410 statCounter.syscalls.sock.binds++;
62e76326 411
ac760b5e
AJ
412 if (bind(s, inaddr.ai_addr, inaddr.ai_addrlen) == 0) {
413 debugs(50, 6, "commBind: bind socket FD " << s << " to " << fd_table[s].local_addr);
62e76326 414 return COMM_OK;
ac760b5e 415 }
62e76326 416
cc192b50 417 debugs(50, 0, "commBind: Cannot bind socket FD " << s << " to " << fd_table[s].local_addr << ": " << xstrerror());
62e76326 418
090089c4 419 return COMM_ERROR;
420}
421
e1a88700 422/**
423 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
424 * is OR of flags specified in comm.h. Defaults TOS
425 */
b8d8561b 426int
16b204c4 427comm_open(int sock_type,
62e76326 428 int proto,
b7ac5457 429 Ip::Address &addr,
62e76326 430 int flags,
431 const char *note)
d6827718 432{
425de4c8 433 return comm_openex(sock_type, proto, addr, flags, 0, 0, note);
d6827718 434}
435
e0d28505
AJ
436void
437comm_open_listener(int sock_type,
438 int proto,
439 Comm::ConnectionPointer &conn,
440 const char *note)
441{
442 /* all listener sockets require bind() */
443 conn->flags |= COMM_DOBIND;
444
445 /* attempt native enabled port. */
b5523edc 446 conn->fd = comm_openex(sock_type, proto, conn->local, conn->flags, 0, 0, note);
e0d28505
AJ
447}
448
31be869c
AJ
449int
450comm_open_listener(int sock_type,
04f7fd38 451 int proto,
b7ac5457 452 Ip::Address &addr,
04f7fd38
AJ
453 int flags,
454 const char *note)
31be869c
AJ
455{
456 int sock = -1;
457
ac760b5e
AJ
458 /* all listener sockets require bind() */
459 flags |= COMM_DOBIND;
460
31be869c 461 /* attempt native enabled port. */
425de4c8 462 sock = comm_openex(sock_type, proto, addr, flags, 0, 0, note);
31be869c 463
31be869c
AJ
464 return sock;
465}
466
2d8c0b1a 467static bool
468limitError(int const anErrno)
469{
470 return anErrno == ENFILE || anErrno == EMFILE;
471}
d6827718 472
cc192b50 473void
474comm_set_v6only(int fd, int tos)
475{
476#ifdef IPV6_V6ONLY
477 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &tos, sizeof(int)) < 0) {
7e07ced1 478 debugs(50, 1, "comm_open: setsockopt(IPV6_V6ONLY) " << (tos?"ON":"OFF") << " for FD " << fd << ": " << xstrerror());
cc192b50 479 }
480#else
481 debugs(50, 0, "WARNING: comm_open: setsockopt(IPV6_V6ONLY) not supported on this platform");
482#endif /* sockopt */
483}
057f5854 484
40d6264d
AJ
485/**
486 * Set the socket IP_TRANSPARENT option for Linux TPROXY v4 support.
487 */
f1e0717c 488void
e950e673 489comm_set_transparent(int fd)
f1e0717c 490{
2ad20b4f 491#if defined(IP_TRANSPARENT)
e950e673 492 int tos = 1;
ef88b51d
AJ
493 if (setsockopt(fd, SOL_IP, IP_TRANSPARENT, (char *) &tos, sizeof(int)) < 0) {
494 debugs(50, DBG_IMPORTANT, "comm_open: setsockopt(IP_TRANSPARENT) on FD " << fd << ": " << xstrerror());
9e008dda 495 } else {
3949d8b7
AJ
496 /* mark the socket as having transparent options */
497 fd_table[fd].flags.transparent = 1;
498 }
f1e0717c 499#else
ef88b51d 500 debugs(50, DBG_CRITICAL, "WARNING: comm_open: setsockopt(IP_TRANSPARENT) not supported on this platform");
f1e0717c
AJ
501#endif /* sockopt */
502}
503
e1a88700 504/**
505 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
506 * is OR of flags specified in defines.h:COMM_*
507 */
d6827718 508int
509comm_openex(int sock_type,
62e76326 510 int proto,
b7ac5457 511 Ip::Address &addr,
62e76326 512 int flags,
425de4c8
AJ
513 tos_t tos,
514 nfmark_t nfmark,
62e76326 515 const char *note)
090089c4 516{
517 int new_socket;
cc192b50 518 struct addrinfo *AI = NULL;
090089c4 519
88bfe092 520 PROF_start(comm_open);
090089c4 521 /* Create socket for accepting new connections. */
83704487 522 statCounter.syscalls.sock.sockets++;
62e76326 523
cc192b50 524 /* Setup the socket addrinfo details for use */
525 addr.GetAddrInfo(AI);
526 AI->ai_socktype = sock_type;
527 AI->ai_protocol = proto;
cc192b50 528
e884bbde 529 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr );
cc192b50 530
0eb08770 531 new_socket = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
055421ee 532
0eb08770
HN
533 /* under IPv6 there is the possibility IPv6 is present but disabled. */
534 /* try again as IPv4-native if possible */
055421ee 535 if ( new_socket < 0 && Ip::EnableIpv6 && addr.IsIPv6() && addr.SetIPv4() ) {
0eb08770
HN
536 /* attempt to open this IPv4-only. */
537 addr.FreeAddrInfo(AI);
538 /* Setup the socket addrinfo details for use */
539 addr.GetAddrInfo(AI);
540 AI->ai_socktype = sock_type;
541 AI->ai_protocol = proto;
542 debugs(50, 3, "comm_openex: Attempt fallback open socket for: " << addr );
ec505200 543 new_socket = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
0eb08770
HN
544 debugs(50, 2, HERE << "attempt open " << note << " socket on: " << addr);
545 }
0eb08770
HN
546
547 if (new_socket < 0) {
62e76326 548 /* Increase the number of reserved fd's if calls to socket()
549 * are failing because the open file table is full. This
550 * limits the number of simultaneous clients */
551
2d8c0b1a 552 if (limitError(errno)) {
dd4e714f 553 debugs(50, DBG_IMPORTANT, "comm_open: socket failure: " << xstrerror());
62e76326 554 fdAdjustReserved();
2d8c0b1a 555 } else {
8ca8bd92 556 debugs(50, DBG_CRITICAL, "comm_open: socket failure: " << xstrerror());
62e76326 557 }
558
cc192b50 559 addr.FreeAddrInfo(AI);
560
62e76326 561 PROF_stop(comm_open);
562 return -1;
090089c4 563 }
62e76326 564
1b76e6c1 565 // XXX: temporary for the transition. comm_openex will eventually have a conn to play with.
e884bbde
AJ
566 Comm::ConnectionPointer conn = new Comm::Connection;
567 conn->local = addr;
b5523edc
AJ
568 conn->fd = new_socket;
569
570 debugs(50, 3, "comm_openex: Opened socket " << conn << " : family=" << AI->ai_family << ", type=" << AI->ai_socktype << ", protocol=" << AI->ai_protocol );
cc192b50 571
d6827718 572 /* set TOS if needed */
425de4c8 573 if (tos)
b5523edc 574 Ip::Qos::setSockTos(conn, tos);
425de4c8
AJ
575
576 /* set netfilter mark if needed */
577 if (nfmark)
b5523edc 578 Ip::Qos::setSockNfmark(conn, nfmark);
62e76326 579
055421ee 580 if ( Ip::EnableIpv6&IPV6_SPECIAL_SPLITSTACK && addr.IsIPv6() )
b5523edc 581 comm_set_v6only(conn->fd, 1);
62e76326 582
cc192b50 583 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
9b1f7ee8 584 /* Other OS may have this administratively disabled for general use. Same deal. */
055421ee 585 if ( Ip::EnableIpv6&IPV6_SPECIAL_V4MAPPING && addr.IsIPv6() )
b5523edc 586 comm_set_v6only(conn->fd, 0);
cc192b50 587
b5523edc
AJ
588 comm_init_opened(conn, tos, nfmark, note, AI);
589 new_socket = comm_apply_flags(conn->fd, addr, flags, AI);
38344a8e
AR
590
591 addr.FreeAddrInfo(AI);
592
593 PROF_stop(comm_open);
594
1b76e6c1 595 // XXX transition only. prevent conn from closing the new FD on function exit.
b5523edc 596 conn->fd = -1;
38344a8e
AR
597 return new_socket;
598}
599
600/// update FD tables after a local or remote (IPC) comm_openex();
601void
e0d28505 602comm_init_opened(const Comm::ConnectionPointer &conn,
425de4c8
AJ
603 tos_t tos,
604 nfmark_t nfmark,
5667a628
AR
605 const char *note,
606 struct addrinfo *AI)
38344a8e 607{
e0d28505 608 assert(Comm::IsConnOpen(conn));
38344a8e
AR
609 assert(AI);
610
090089c4 611 /* update fdstat */
e0d28505 612 debugs(5, 5, HERE << conn << " is a new socket");
62e76326 613
e0d28505
AJ
614 assert(!isOpen(conn->fd)); // NP: global isOpen checks the fde entry for openness not the Comm::Connection
615 fd_open(conn->fd, FD_SOCKET, note);
62e76326 616
e0d28505
AJ
617 fdd_table[conn->fd].close_file = NULL;
618 fdd_table[conn->fd].close_line = 0;
62e76326 619
e0d28505
AJ
620 fde *F = &fd_table[conn->fd];
621 F->local_addr = conn->local;
425de4c8
AJ
622 F->tosToServer = tos;
623
624 F->nfmarkToServer = nfmark;
cc192b50 625
626 F->sock_family = AI->ai_family;
38344a8e
AR
627}
628
629/// apply flags after a local comm_open*() call;
630/// returns new_socket or -1 on error
631static int
632comm_apply_flags(int new_socket,
a67d2b2e 633 Ip::Address &addr,
5667a628
AR
634 int flags,
635 struct addrinfo *AI)
38344a8e
AR
636{
637 assert(new_socket >= 0);
638 assert(AI);
639 const int sock_type = AI->ai_socktype;
62e76326 640
79a15e0a 641 if (!(flags & COMM_NOCLOEXEC))
62e76326 642 commSetCloseOnExec(new_socket);
643
cdc33f35 644 if ((flags & COMM_REUSEADDR))
62e76326 645 commSetReuseAddr(new_socket);
646
f45dd259 647 if (addr.GetPort() > (unsigned short) 0) {
1191b93b 648#if _SQUID_MSWIN_
a50bfe93 649 if (sock_type != SOCK_DGRAM)
650#endif
a50bfe93 651 commSetNoLinger(new_socket);
62e76326 652
653 if (opt_reuseaddr)
654 commSetReuseAddr(new_socket);
090089c4 655 }
62e76326 656
a35595cd 657 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
9e008dda 658 if ((flags & COMM_TRANSPARENT)) {
a35595cd
AJ
659 comm_set_transparent(new_socket);
660 }
a35595cd 661
ac760b5e
AJ
662 if ( (flags & COMM_DOBIND) || addr.GetPort() > 0 || !addr.IsAnyAddr() ) {
663 if ( !(flags & COMM_DOBIND) && addr.IsAnyAddr() )
664 debugs(5,1,"WARNING: Squid is attempting to bind() port " << addr << " without being a listener.");
665 if ( addr.IsNoAddr() )
666 debugs(5,0,"CRITICAL: Squid is attempting to bind() port " << addr << "!!");
667
cc192b50 668 if (commBind(new_socket, *AI) != COMM_OK) {
62e76326 669 comm_close(new_socket);
670 return -1;
62e76326 671 }
23ff6968 672 }
62e76326 673
79a15e0a 674 if (flags & COMM_NONBLOCKING)
9e008dda 675 if (commSetNonBlocking(new_socket) == COMM_ERROR) {
38344a8e 676 comm_close(new_socket);
62e76326 677 return -1;
62e76326 678 }
679
30a4f2a8 680#ifdef TCP_NODELAY
681 if (sock_type == SOCK_STREAM)
62e76326 682 commSetTcpNoDelay(new_socket);
683
30a4f2a8 684#endif
62e76326 685
1241e63e 686 if (Config.tcpRcvBufsz > 0 && sock_type == SOCK_STREAM)
62e76326 687 commSetTcpRcvbuf(new_socket, Config.tcpRcvBufsz);
688
090089c4 689 return new_socket;
690}
691
a4c0f9c6 692void
e0d28505 693comm_import_opened(const Comm::ConnectionPointer &conn,
5667a628
AR
694 const char *note,
695 struct addrinfo *AI)
a4c0f9c6 696{
e0d28505
AJ
697 debugs(5, 2, HERE << conn);
698 assert(Comm::IsConnOpen(conn));
a4c0f9c6
AR
699 assert(AI);
700
9c8a6c3b 701 comm_init_opened(conn, 0, 0, note, AI);
a4c0f9c6 702
e0d28505
AJ
703 if (!(conn->flags & COMM_NOCLOEXEC))
704 fd_table[conn->fd].flags.close_on_exec = 1;
a4c0f9c6 705
f45dd259 706 if (conn->local.GetPort() > (unsigned short) 0) {
1191b93b 707#if _SQUID_MSWIN_
e0d28505 708 if (AI->ai_socktype != SOCK_DGRAM)
a4c0f9c6 709#endif
e0d28505 710 fd_table[conn->fd].flags.nolinger = 1;
a4c0f9c6
AR
711 }
712
e0d28505
AJ
713 if ((conn->flags & COMM_TRANSPARENT))
714 fd_table[conn->fd].flags.transparent = 1;
a4c0f9c6 715
e0d28505
AJ
716 if (conn->flags & COMM_NONBLOCKING)
717 fd_table[conn->fd].flags.nonblocking = 1;
a4c0f9c6
AR
718
719#ifdef TCP_NODELAY
720 if (AI->ai_socktype == SOCK_STREAM)
e0d28505 721 fd_table[conn->fd].flags.nodelay = 1;
a4c0f9c6
AR
722#endif
723
724 /* no fd_table[fd].flags. updates needed for these conditions:
725 * if ((flags & COMM_REUSEADDR)) ...
726 * if ((flags & COMM_DOBIND) ...) ...
727 */
728}
729
933dd095
AJ
730// XXX: now that raw-FD timeouts are only unset for pipes and files this SHOULD be a no-op.
731// With handler already unset. Leaving this present until that can be verified for all code paths.
732void
733commUnsetFdTimeout(int fd)
b0469965 734{
933dd095 735 debugs(5, 3, HERE << "Remove timeout for FD " << fd);
b0469965 736 assert(fd >= 0);
737 assert(fd < Squid_MaxFD);
738 fde *F = &fd_table[fd];
739 assert(F->flags.open);
740
933dd095
AJ
741 F->timeoutHandler = NULL;
742 F->timeout = 0;
7957e704
AJ
743}
744
745int
746commSetConnTimeout(const Comm::ConnectionPointer &conn, int timeout, AsyncCall::Pointer &callback)
747{
748 debugs(5, 3, HERE << conn << " timeout " << timeout);
749 assert(Comm::IsConnOpen(conn));
750 assert(conn->fd < Squid_MaxFD);
751 fde *F = &fd_table[conn->fd];
752 assert(F->flags.open);
753
754 if (timeout < 0) {
755 F->timeoutHandler = NULL;
756 F->timeout = 0;
757 } else {
758 if (callback != NULL) {
759 typedef CommTimeoutCbParams Params;
760 Params &params = GetCommParams<Params>(callback);
761 params.conn = conn;
762 F->timeoutHandler = callback;
763 }
b0469965 764
7957e704
AJ
765 F->timeout = squid_curtime + (time_t) timeout;
766 }
767
768 return F->timeout;
b0469965 769}
090089c4 770
8d77a37c
AJ
771int
772commUnsetConnTimeout(const Comm::ConnectionPointer &conn)
773{
774 debugs(5, 3, HERE << "Remove timeout for " << conn);
775 AsyncCall::Pointer nil;
776 return commSetConnTimeout(conn, -1, nil);
777}
778
b8d8561b 779int
b7ac5457 780comm_connect_addr(int sock, const Ip::Address &address)
090089c4 781{
3d7e9d7c 782 comm_err_t status = COMM_OK;
76f87348 783 fde *F = &fd_table[sock];
cc192b50 784 int x = 0;
b5568a61 785 int err = 0;
9689d97c 786 socklen_t errlen;
feca3b9a 787 struct addrinfo *AI = NULL;
88bfe092 788 PROF_start(comm_connect_addr);
cc192b50 789
790 assert(address.GetPort() != 0);
791
fa6a39d7 792 debugs(5, 9, HERE << "connecting socket FD " << sock << " to " << address << " (want family: " << F->sock_family << ")");
cc192b50 793
3d98ff81 794 /* Handle IPv6 over IPv4-only socket case.
9d92af86 795 * this case must presently be handled here since the GetAddrInfo asserts on bad mappings.
3d98ff81 796 * NP: because commResetFD is private to ConnStateData we have to return an error and
9d92af86
AJ
797 * trust its handled properly.
798 */
9e008dda 799 if (F->sock_family == AF_INET && !address.IsIPv4()) {
3d98ff81
HN
800 errno = ENETUNREACH;
801 return COMM_ERR_PROTOCOL;
802 }
803
804 /* Handle IPv4 over IPv6-only socket case.
805 * This case is presently handled here as it's both a known case and it's
806 * uncertain what error will be returned by the IPv6 stack in such case. It's
807 * possible this will also be handled by the errno checks below after connect()
808 * but needs carefull cross-platform verification, and verifying the address
809 * condition here is simple.
810 */
811 if (!F->local_addr.IsIPv4() && address.IsIPv4()) {
812 errno = ENETUNREACH;
9d92af86
AJ
813 return COMM_ERR_PROTOCOL;
814 }
9d92af86 815
feca3b9a 816 address.GetAddrInfo(AI, F->sock_family);
cc192b50 817
090089c4 818 /* Establish connection. */
b5568a61 819 errno = 0;
62e76326 820
9e008dda 821 if (!F->flags.called_connect) {
62e76326 822 F->flags.called_connect = 1;
823 statCounter.syscalls.sock.connects++;
824
feca3b9a 825 x = connect(sock, AI->ai_addr, AI->ai_addrlen);
62e76326 826
5a33a66a 827 // XXX: ICAP code refuses callbacks during a pending comm_ call
828 // Async calls development will fix this.
829 if (x == 0) {
830 x = -1;
831 errno = EINPROGRESS;
832 }
833
9e008dda 834 if (x < 0) {
cc192b50 835 debugs(5,5, "comm_connect_addr: sock=" << sock << ", addrinfo( " <<
9e008dda
AJ
836 " flags=" << AI->ai_flags <<
837 ", family=" << AI->ai_family <<
838 ", socktype=" << AI->ai_socktype <<
839 ", protocol=" << AI->ai_protocol <<
840 ", &addr=" << AI->ai_addr <<
841 ", addrlen=" << AI->ai_addrlen <<
842 " )" );
cc192b50 843 debugs(5, 9, "connect FD " << sock << ": (" << x << ") " << xstrerror());
844 debugs(14,9, "connecting to: " << address );
845 }
9e008dda 846 } else {
8a09e810 847#if _SQUID_NEWSOS6_
62e76326 848 /* Makoto MATSUSHITA <matusita@ics.es.osaka-u.ac.jp> */
849
feca3b9a 850 connect(sock, AI->ai_addr, AI->ai_addrlen);
62e76326 851
852 if (errno == EINVAL) {
853 errlen = sizeof(err);
854 x = getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &errlen);
855
856 if (x >= 0)
857 errno = x;
858 }
859
33ac9442 860#else
62e76326 861 errlen = sizeof(err);
862
863 x = getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &errlen);
864
865 if (x == 0)
866 errno = err;
867
8a09e810 868#if _SQUID_SOLARIS_
62e76326 869 /*
870 * Solaris 2.4's socket emulation doesn't allow you
871 * to determine the error from a failed non-blocking
872 * connect and just returns EPIPE. Create a fake
873 * error message for connect. -- fenner@parc.xerox.com
874 */
875 if (x < 0 && errno == EPIPE)
876 errno = ENOTCONN;
877
33ac9442 878#endif
30a4f2a8 879#endif
62e76326 880
e5f6c5c2 881 }
62e76326 882
9e008dda
AJ
883 /* Squid seems to be working fine without this code. With this code,
884 * we leak memory on many connect requests because of EINPROGRESS.
885 * If you find that this code is needed, please file a bug report. */
82ec8dfc 886#if 0
1191b93b 887#if _SQUID_LINUX_
feca3b9a 888 /* 2007-11-27:
9e008dda 889 * Linux Debian replaces our allocated AI pointer with garbage when
feca3b9a
AJ
890 * connect() fails. This leads to segmentation faults deallocating
891 * the system-allocated memory when we go to clean up our pointer.
892 * HACK: is to leak the memory returned since we can't deallocate.
893 */
9e008dda 894 if (errno != 0) {
feca3b9a
AJ
895 AI = NULL;
896 }
82ec8dfc 897#endif
feca3b9a
AJ
898#endif
899
900 address.FreeAddrInfo(AI);
901
88bfe092 902 PROF_stop(comm_connect_addr);
62e76326 903
b5568a61 904 if (errno == 0 || errno == EISCONN)
62e76326 905 status = COMM_OK;
b5568a61 906 else if (ignoreErrno(errno))
62e76326 907 status = COMM_INPROGRESS;
3d98ff81
HN
908 else if (errno == EAFNOSUPPORT || errno == EINVAL)
909 return COMM_ERR_PROTOCOL;
b5568a61 910 else
3d98ff81 911 return COMM_ERROR;
62e76326 912
cc192b50 913 address.NtoA(F->ipaddr, MAX_IPSTRLEN);
62e76326 914
cc192b50 915 F->remote_port = address.GetPort(); /* remote_port is HS */
62e76326 916
9e008dda 917 if (status == COMM_OK) {
cc192b50 918 debugs(5, 10, "comm_connect_addr: FD " << sock << " connected to " << address);
9e008dda 919 } else if (status == COMM_INPROGRESS) {
bf8fe701 920 debugs(5, 10, "comm_connect_addr: FD " << sock << " connection pending");
090089c4 921 }
62e76326 922
090089c4 923 return status;
924}
925
cb201b7e 926void
927commCallCloseHandlers(int fd)
928{
76f87348 929 fde *F = &fd_table[fd];
bf8fe701 930 debugs(5, 5, "commCallCloseHandlers: FD " << fd);
62e76326 931
8000a965 932 while (F->closeHandler != NULL) {
b0469965 933 AsyncCall::Pointer call = F->closeHandler;
9e008dda
AJ
934 F->closeHandler = call->Next();
935 call->setNext(NULL);
936 // If call is not canceled schedule it for execution else ignore it
937 if (!call->canceled()) {
938 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call);
9e008dda
AJ
939 ScheduleCallHere(call);
940 }
cb201b7e 941 }
942}
943
5492ad1d 944#if LINGERING_CLOSE
945static void
946commLingerClose(int fd, void *unused)
947{
948 LOCAL_ARRAY(char, buf, 1024);
949 int n;
1f7c9178 950 n = FD_READ_METHOD(fd, buf, 1024);
62e76326 951
5492ad1d 952 if (n < 0)
bf8fe701 953 debugs(5, 3, "commLingerClose: FD " << fd << " read: " << xstrerror());
62e76326 954
5492ad1d 955 comm_close(fd);
956}
957
958static void
933dd095 959commLingerTimeout(const FdeCbParams &params)
5492ad1d 960{
933dd095
AJ
961 debugs(5, 3, "commLingerTimeout: FD " << params.fd);
962 comm_close(params.fd);
5492ad1d 963}
964
965/*
966 * Inspired by apache
967 */
968void
969comm_lingering_close(int fd)
970{
d4c19b39 971#if USE_SSL
972 if (fd_table[fd].ssl)
575d05c4 973 ssl_shutdown_method(fd_table[fd].ssl);
d4c19b39 974#endif
62e76326 975
5492ad1d 976 if (shutdown(fd, 1) < 0) {
62e76326 977 comm_close(fd);
978 return;
5492ad1d 979 }
62e76326 980
5492ad1d 981 fd_note(fd, "lingering close");
933dd095
AJ
982 AsyncCall::Pointer call = commCbCall(5,4, "commLingerTimeout", FdeCbPtrFun(commLingerTimeout, NULL));
983
984 debugs(5, 3, HERE << "FD " << fd << " timeout " << timeout);
985 assert(fd_table[fd].flags.open);
986 if (callback != NULL) {
987 typedef FdeCbParams Params;
988 Params &params = GetCommParams<Params>(callback);
989 params.fd = fd;
990 fd_table[fd].timeoutHandler = callback;
991 fd_table[fd].timeout = squid_curtime + static_cast<time_t>(10);
992 }
993
d841c88d 994 Comm::SetSelect(fd, COMM_SELECT_READ, commLingerClose, NULL, 0);
5492ad1d 995}
62e76326 996
5492ad1d 997#endif
998
27774cee 999/**
98264874 1000 * enable linger with time of 0 so that when the socket is
1001 * closed, TCP generates a RESET
1002 */
1003void
8ace824c 1004comm_reset_close(const Comm::ConnectionPointer &conn)
98264874 1005{
5c336a3b
AJ
1006 struct linger L;
1007 L.l_onoff = 1;
1008 L.l_linger = 0;
62e76326 1009
5c336a3b 1010 if (setsockopt(conn->fd, SOL_SOCKET, SO_LINGER, (char *) &L, sizeof(L)) < 0)
1b76e6c1 1011 debugs(50, DBG_CRITICAL, "ERROR: Closing " << conn << " with TCP RST: " << xstrerror());
5c336a3b
AJ
1012
1013 conn->close();
1014}
1015
1016// Legacy close function.
1017void
1018old_comm_reset_close(int fd)
1019{
98264874 1020 struct linger L;
1021 L.l_onoff = 1;
1022 L.l_linger = 0;
62e76326 1023
98264874 1024 if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &L, sizeof(L)) < 0)
468fe1b5 1025 debugs(50, DBG_CRITICAL, "ERROR: Closing FD " << fd << " with TCP RST: " << xstrerror());
62e76326 1026
98264874 1027 comm_close(fd);
1028}
1029
575d05c4 1030#if USE_SSL
9e008dda 1031void
a17bf806 1032commStartSslClose(const FdeCbParams &params)
10b06767 1033{
575d05c4
AJ
1034 assert(&fd_table[params.fd].ssl);
1035 ssl_shutdown_method(fd_table[params.fd].ssl);
10b06767 1036}
575d05c4 1037#endif
10b06767 1038
9e008dda 1039void
a17bf806 1040comm_close_complete(const FdeCbParams &params)
2d8c0b1a 1041{
b0469965 1042#if USE_SSL
575d05c4 1043 fde *F = &fd_table[params.fd];
2d8c0b1a 1044
b0469965 1045 if (F->ssl) {
1046 SSL_free(F->ssl);
1047 F->ssl = NULL;
1048 }
2d8c0b1a 1049
95d2589c
CT
1050 if (F->dynamicSslContext) {
1051 SSL_CTX_free(F->dynamicSslContext);
1052 F->dynamicSslContext = NULL;
1053 }
b0469965 1054#endif
575d05c4
AJ
1055 fd_close(params.fd); /* update fdstat */
1056 close(params.fd);
b0469965 1057
b0469965 1058 statCounter.syscalls.sock.closes++;
1059
575d05c4 1060 /* When one connection closes, give accept() a chance, if need be */
04f55905 1061 Comm::AcceptLimiter::Instance().kick();
2d8c0b1a 1062}
c4b7a5a9 1063
1064/*
1065 * Close the socket fd.
1066 *
1067 * + call write handlers with ERR_CLOSING
1068 * + call read handlers with ERR_CLOSING
1069 * + call closing handlers
a46d2c0e 1070 *
9e008dda 1071 * NOTE: COMM_ERR_CLOSING will NOT be called for CommReads' sitting in a
a46d2c0e 1072 * DeferredReadManager.
c4b7a5a9 1073 */
b8d8561b 1074void
43ae1d95 1075_comm_close(int fd, char const *file, int line)
090089c4 1076{
82ec8dfc 1077 debugs(5, 3, "comm_close: start closing FD " << fd);
03eb2f01 1078 assert(fd >= 0);
1079 assert(fd < Squid_MaxFD);
82ec8dfc
AR
1080
1081 fde *F = &fd_table[fd];
c4b7a5a9 1082 fdd_table[fd].close_file = file;
1083 fdd_table[fd].close_line = line;
1f7c9178 1084
82ec8dfc 1085 if (F->closing())
62e76326 1086 return;
1087
36afac26 1088 /* XXX: is this obsolete behind F->closing() ? */
b8869bcf 1089 if ( (shutting_down || reconfiguring) && (!F->flags.open || F->type == FD_FILE))
62e76326 1090 return;
1091
c4b7a5a9 1092 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
b0469965 1093 assert(isOpen(fd));
62e76326 1094
76f87348 1095 assert(F->type != FD_FILE);
62e76326 1096
88bfe092 1097 PROF_start(comm_close);
62e76326 1098
10b06767 1099 F->flags.close_request = 1;
62e76326 1100
575d05c4
AJ
1101#if USE_SSL
1102 if (F->ssl) {
575d05c4 1103 AsyncCall::Pointer startCall=commCbCall(5,4, "commStartSslClose",
a17bf806
AJ
1104 FdeCbPtrFun(commStartSslClose, NULL));
1105 FdeCbParams &startParams = GetCommParams<FdeCbParams>(startCall);
575d05c4
AJ
1106 startParams.fd = fd;
1107 ScheduleCallHere(startCall);
1108 }
1109#endif
62e76326 1110
74257126
AR
1111 // a half-closed fd may lack a reader, so we stop monitoring explicitly
1112 if (commHasHalfClosedMonitor(fd))
1113 commStopHalfClosedMonitor(fd);
933dd095 1114 commUnsetFdTimeout(fd);
62e76326 1115
a6351f16 1116 // notify read/write handlers after canceling select reservations, if any
ec41b64c 1117 if (COMMIO_FD_WRITECB(fd)->active()) {
d841c88d 1118 Comm::SetSelect(fd, COMM_SELECT_WRITE, NULL, NULL, 0);
ec41b64c 1119 COMMIO_FD_WRITECB(fd)->finish(COMM_ERR_CLOSING, errno);
2b663917 1120 }
ec41b64c 1121 if (COMMIO_FD_READCB(fd)->active()) {
d841c88d 1122 Comm::SetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
ec41b64c 1123 COMMIO_FD_READCB(fd)->finish(COMM_ERR_CLOSING, errno);
2b663917 1124 }
2d8c0b1a 1125
9a0a18de 1126#if USE_DELAY_POOLS
b4cd430a
CT
1127 if (ClientInfo *clientInfo = F->clientInfo) {
1128 if (clientInfo->selectWaiting) {
1129 clientInfo->selectWaiting = false;
1130 // kick queue or it will get stuck as commWriteHandle is not called
1131 clientInfo->kickQuotaQueue();
1132 }
f33d34a8 1133 }
b4cd430a
CT
1134#endif
1135
cb201b7e 1136 commCallCloseHandlers(fd);
62e76326 1137
fb505fa1 1138 if (F->pconn.uses && F->pconn.pool)
2dba5b8e 1139 F->pconn.pool->noteUses(F->pconn.uses);
62e76326 1140
a7ad6e4e 1141 comm_empty_os_read_buffers(fd);
9e008dda 1142
62e76326 1143
10b06767 1144 AsyncCall::Pointer completeCall=commCbCall(5,4, "comm_close_complete",
a17bf806
AJ
1145 FdeCbPtrFun(comm_close_complete, NULL));
1146 FdeCbParams &completeParams = GetCommParams<FdeCbParams>(completeCall);
10b06767 1147 completeParams.fd = fd;
9e008dda 1148 // must use async call to wait for all callbacks
82ec8dfc 1149 // scheduled before comm_close() to finish
10b06767 1150 ScheduleCallHere(completeCall);
62e76326 1151
88bfe092 1152 PROF_stop(comm_close);
090089c4 1153}
1154
090089c4 1155/* Send a udp datagram to specified TO_ADDR. */
b8d8561b 1156int
5df61230 1157comm_udp_sendto(int fd,
b7ac5457 1158 const Ip::Address &to_addr,
62e76326 1159 const void *buf,
1160 int len)
090089c4 1161{
cc192b50 1162 int x = 0;
1163 struct addrinfo *AI = NULL;
1164
88bfe092 1165 PROF_start(comm_udp_sendto);
83704487 1166 statCounter.syscalls.sock.sendtos++;
62e76326 1167
cc192b50 1168 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr <<
9e008dda 1169 " using FD " << fd << " using Port " << comm_local_port(fd) );
cc192b50 1170
1171 /* BUG: something in the above macro appears to occasionally be setting AI to garbage. */
1172 /* AYJ: 2007-08-27 : or was it because I wasn't then setting 'fd_table[fd].sock_family' to fill properly. */
1173 assert( NULL == AI );
1174
1175 to_addr.GetAddrInfo(AI, fd_table[fd].sock_family);
1176
1177 x = sendto(fd, buf, len, 0, AI->ai_addr, AI->ai_addrlen);
1178
1179 to_addr.FreeAddrInfo(AI);
1180
88bfe092 1181 PROF_stop(comm_udp_sendto);
62e76326 1182
2d8c0b1a 1183 if (x >= 0)
1184 return x;
1185
1191b93b 1186#if _SQUID_LINUX_
62e76326 1187
2d8c0b1a 1188 if (ECONNREFUSED != errno)
17d51783 1189#endif
62e76326 1190
cc192b50 1191 debugs(50, 1, "comm_udp_sendto: FD " << fd << ", (family=" << fd_table[fd].sock_family << ") " << to_addr << ": " << xstrerror());
62e76326 1192
2d8c0b1a 1193 return COMM_ERROR;
090089c4 1194}
1195
b8d8561b 1196void
575d05c4 1197comm_add_close_handler(int fd, CLCB * handler, void *data)
30a4f2a8 1198{
bf8fe701 1199 debugs(5, 5, "comm_add_close_handler: FD " << fd << ", handler=" <<
1200 handler << ", data=" << data);
62e76326 1201
b0469965 1202 AsyncCall::Pointer call=commCbCall(5,4, "SomeCloseHandler",
9e008dda 1203 CommCloseCbPtrFun(handler, data));
b0469965 1204 comm_add_close_handler(fd, call);
1205}
62e76326 1206
b0469965 1207void
1208comm_add_close_handler(int fd, AsyncCall::Pointer &call)
1209{
1210 debugs(5, 5, "comm_add_close_handler: FD " << fd << ", AsyncCall=" << call);
62e76326 1211
b0469965 1212 /*TODO:Check for a similar scheduled AsyncCall*/
1213// for (c = fd_table[fd].closeHandler; c; c = c->next)
1214// assert(c->handler != handler || c->data != data);
62e76326 1215
b0469965 1216 call->setNext(fd_table[fd].closeHandler);
62e76326 1217
b0469965 1218 fd_table[fd].closeHandler = call;
30a4f2a8 1219}
1220
b0469965 1221
1222// remove function-based close handler
b8d8561b 1223void
575d05c4 1224comm_remove_close_handler(int fd, CLCB * handler, void *data)
090089c4 1225{
b0469965 1226 assert (isOpen(fd));
30a4f2a8 1227 /* Find handler in list */
bf8fe701 1228 debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", handler=" <<
1229 handler << ", data=" << data);
62e76326 1230
37cba319
AR
1231 AsyncCall::Pointer p, prev = NULL;
1232 for (p = fd_table[fd].closeHandler; p != NULL; prev = p, p = p->Next()) {
b0469965 1233 typedef CommCbFunPtrCallT<CommCloseCbPtrFun> Call;
1234 const Call *call = dynamic_cast<const Call*>(p.getRaw());
1235 if (!call) // method callbacks have their own comm_remove_close_handler
1236 continue;
62e76326 1237
b0469965 1238 typedef CommCloseCbParams Params;
1239 const Params &params = GetCommParams<Params>(p);
1240 if (call->dialer.handler == handler && params.data == data)
1241 break; /* This is our handler */
1242 }
7828df5b
CT
1243
1244 // comm_close removes all close handlers so our handler may be gone
37cba319
AR
1245 if (p != NULL) {
1246 p->dequeue(fd_table[fd].closeHandler, prev);
7828df5b 1247 p->cancel("comm_remove_close_handler");
37cba319 1248 }
b0469965 1249}
62e76326 1250
b0469965 1251// remove method-based close handler
1252void
1253comm_remove_close_handler(int fd, AsyncCall::Pointer &call)
1254{
1255 assert (isOpen(fd));
b0469965 1256 debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", AsyncCall=" << call);
62e76326 1257
7828df5b 1258 // comm_close removes all close handlers so our handler may be gone
37cba319
AR
1259 AsyncCall::Pointer p, prev = NULL;
1260 for (p = fd_table[fd].closeHandler; p != NULL && p != call; prev = p, p = p->Next());
62e76326 1261
37cba319
AR
1262 if (p != NULL)
1263 p->dequeue(fd_table[fd].closeHandler, prev);
b0469965 1264 call->cancel("comm_remove_close_handler");
30a4f2a8 1265}
090089c4 1266
b8d8561b 1267static void
1268commSetNoLinger(int fd)
30a4f2a8 1269{
62e76326 1270
30a4f2a8 1271 struct linger L;
090089c4 1272 L.l_onoff = 0; /* off */
1273 L.l_linger = 0;
62e76326 1274
30a4f2a8 1275 if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &L, sizeof(L)) < 0)
bf8fe701 1276 debugs(50, 0, "commSetNoLinger: FD " << fd << ": " << xstrerror());
62e76326 1277
58a6c186 1278 fd_table[fd].flags.nolinger = 1;
090089c4 1279}
1280
b8d8561b 1281static void
1282commSetReuseAddr(int fd)
090089c4 1283{
1284 int on = 1;
62e76326 1285
30a4f2a8 1286 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)) < 0)
bf8fe701 1287 debugs(50, 1, "commSetReuseAddr: FD " << fd << ": " << xstrerror());
090089c4 1288}
1289
b8d8561b 1290static void
1291commSetTcpRcvbuf(int fd, int size)
f868539a 1292{
1293 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &size, sizeof(size)) < 0)
bf8fe701 1294 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd << ", SIZE " << size << ": " << xstrerror());
8f0d53ef 1295 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &size, sizeof(size)) < 0)
1296 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd << ", SIZE " << size << ": " << xstrerror());
1297#ifdef TCP_WINDOW_CLAMP
1298 if (setsockopt(fd, SOL_TCP, TCP_WINDOW_CLAMP, (char *) &size, sizeof(size)) < 0)
1299 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd << ", SIZE " << size << ": " << xstrerror());
1300#endif
f868539a 1301}
1302
b8d8561b 1303int
1304commSetNonBlocking(int fd)
30a4f2a8 1305{
1191b93b 1306#if !_SQUID_MSWIN_
731e4d49 1307 int flags;
9e205701 1308 int dummy = 0;
a50bfe93 1309#endif
be266cb2 1310#if _SQUID_WINDOWS_
b05490a8 1311 int nonblocking = TRUE;
62e76326 1312
be266cb2 1313#if _SQUID_CYGWIN_
7f6ffd15 1314 if (fd_table[fd].type != FD_PIPE) {
629b5f75 1315#endif
1316
62e76326 1317 if (ioctl(fd, FIONBIO, &nonblocking) < 0) {
bf8fe701 1318 debugs(50, 0, "commSetNonBlocking: FD " << fd << ": " << xstrerror() << " " << fd_table[fd].type);
62e76326 1319 return COMM_ERROR;
1320 }
629b5f75 1321
be266cb2 1322#if _SQUID_CYGWIN_
7f6ffd15 1323 } else {
1324#endif
629b5f75 1325#endif
1191b93b 1326#if !_SQUID_MSWIN_
62e76326 1327
1328 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
bf8fe701 1329 debugs(50, 0, "FD " << fd << ": fcntl F_GETFL: " << xstrerror());
62e76326 1330 return COMM_ERROR;
1331 }
1332
1333 if (fcntl(fd, F_SETFL, flags | SQUID_NONBLOCK) < 0) {
bf8fe701 1334 debugs(50, 0, "commSetNonBlocking: FD " << fd << ": " << xstrerror());
62e76326 1335 return COMM_ERROR;
1336 }
1337
a50bfe93 1338#endif
be266cb2 1339#if _SQUID_CYGWIN_
090089c4 1340 }
7f6ffd15 1341#endif
58a6c186 1342 fd_table[fd].flags.nonblocking = 1;
62e76326 1343
090089c4 1344 return 0;
1345}
1346
7e3ce7b9 1347int
1348commUnsetNonBlocking(int fd)
1349{
1191b93b 1350#if _SQUID_MSWIN_
a50bfe93 1351 int nonblocking = FALSE;
1352
1353 if (ioctlsocket(fd, FIONBIO, (unsigned long *) &nonblocking) < 0) {
1354#else
7e3ce7b9 1355 int flags;
1356 int dummy = 0;
62e76326 1357
7e3ce7b9 1358 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
bf8fe701 1359 debugs(50, 0, "FD " << fd << ": fcntl F_GETFL: " << xstrerror());
62e76326 1360 return COMM_ERROR;
7e3ce7b9 1361 }
62e76326 1362
7e3ce7b9 1363 if (fcntl(fd, F_SETFL, flags & (~SQUID_NONBLOCK)) < 0) {
a50bfe93 1364#endif
bf8fe701 1365 debugs(50, 0, "commUnsetNonBlocking: FD " << fd << ": " << xstrerror());
62e76326 1366 return COMM_ERROR;
7e3ce7b9 1367 }
62e76326 1368
7e3ce7b9 1369 fd_table[fd].flags.nonblocking = 0;
1370 return 0;
1371}
1372
b8d8561b 1373void
e1381638
AJ
1374commSetCloseOnExec(int fd)
1375{
3ca60c86 1376#ifdef FD_CLOEXEC
731e4d49 1377 int flags;
7a18b487 1378 int dummy = 0;
62e76326 1379
2209fe19
AJ
1380 if ((flags = fcntl(fd, F_GETFD, dummy)) < 0) {
1381 debugs(50, 0, "FD " << fd << ": fcntl F_GETFD: " << xstrerror());
62e76326 1382 return;
3ca60c86 1383 }
62e76326 1384
24382924 1385 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
bf8fe701 1386 debugs(50, 0, "FD " << fd << ": set close-on-exec failed: " << xstrerror());
62e76326 1387
d6827718 1388 fd_table[fd].flags.close_on_exec = 1;
62e76326 1389
3ca60c86 1390#endif
1391}
1392
e90100aa 1393#ifdef TCP_NODELAY
1394static void
e1381638
AJ
1395commSetTcpNoDelay(int fd)
1396{
e90100aa 1397 int on = 1;
62e76326 1398
e90100aa 1399 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) < 0)
bf8fe701 1400 debugs(50, 1, "commSetTcpNoDelay: FD " << fd << ": " << xstrerror());
62e76326 1401
d6827718 1402 fd_table[fd].flags.nodelay = 1;
e90100aa 1403}
62e76326 1404
e90100aa 1405#endif
1406
b2130d58 1407void
e1381638
AJ
1408commSetTcpKeepalive(int fd, int idle, int interval, int timeout)
1409{
b2130d58 1410 int on = 1;
1411#ifdef TCP_KEEPCNT
1412 if (timeout && interval) {
9e008dda
AJ
1413 int count = (timeout + interval - 1) / interval;
1414 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(on)) < 0)
1415 debugs(5, 1, "commSetKeepalive: FD " << fd << ": " << xstrerror());
b2130d58 1416 }
1417#endif
1418#ifdef TCP_KEEPIDLE
1419 if (idle) {
9e008dda
AJ
1420 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(on)) < 0)
1421 debugs(5, 1, "commSetKeepalive: FD " << fd << ": " << xstrerror());
b2130d58 1422 }
1423#endif
1424#ifdef TCP_KEEPINTVL
1425 if (interval) {
9e008dda
AJ
1426 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(on)) < 0)
1427 debugs(5, 1, "commSetKeepalive: FD " << fd << ": " << xstrerror());
b2130d58 1428 }
1429#endif
1430 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) < 0)
9e008dda 1431 debugs(5, 1, "commSetKeepalive: FD " << fd << ": " << xstrerror());
b2130d58 1432}
6a988308 1433
d86b3703 1434void
e1381638
AJ
1435comm_init(void)
1436{
c4b7a5a9 1437 fd_table =(fde *) xcalloc(Squid_MaxFD, sizeof(fde));
1438 fdd_table = (fd_debug_t *)xcalloc(Squid_MaxFD, sizeof(fd_debug_t));
2d8c0b1a 1439
04f55905
AJ
1440 /* make sure the accept() socket FIFO delay queue exists */
1441 Comm::AcceptLimiter::Instance();
b0469965 1442
ec41b64c
AJ
1443 // make sure the IO pending callback table exists
1444 Comm::CallbackTableInit();
2d8c0b1a 1445
59c4d35b 1446 /* XXX account fd_table */
090089c4 1447 /* Keep a few file descriptors free so that we don't run out of FD's
1448 * after accepting a client but before it opens a socket or a file.
e83892e9 1449 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
d85c3078 1450 RESERVED_FD = min(100, Squid_MaxFD / 4);
2d8c0b1a 1451
04eb0689 1452 conn_close_pool = memPoolCreate("close_handler", sizeof(close_handler));
74257126
AR
1453
1454 TheHalfClosed = new DescriptorSet;
d841c88d
AJ
1455
1456 /* setup the select loop module */
1457 Comm::SelectLoopInit();
090089c4 1458}
1459
236d1779 1460void
e1381638
AJ
1461comm_exit(void)
1462{
74257126
AR
1463 delete TheHalfClosed;
1464 TheHalfClosed = NULL;
1465
236d1779 1466 safe_free(fd_table);
1467 safe_free(fdd_table);
ec41b64c 1468 Comm::CallbackTableDestruct();
236d1779 1469}
1470
9a0a18de 1471#if USE_DELAY_POOLS
b4cd430a 1472// called when the queue is done waiting for the client bucket to fill
ec41b64c 1473void
b4cd430a
CT
1474commHandleWriteHelper(void * data)
1475{
1476 CommQuotaQueue *queue = static_cast<CommQuotaQueue*>(data);
1477 assert(queue);
1478
1479 ClientInfo *clientInfo = queue->clientInfo;
1480 // ClientInfo invalidates queue if freed, so if we got here through,
1481 // evenAdd cbdata protections, everything should be valid and consistent
f33d34a8 1482 assert(clientInfo);
b4cd430a
CT
1483 assert(clientInfo->hasQueue());
1484 assert(clientInfo->hasQueue(queue));
1485 assert(!clientInfo->selectWaiting);
1486 assert(clientInfo->eventWaiting);
1487 clientInfo->eventWaiting = false;
1488
1489 do {
1490 // check that the head descriptor is still relevant
1491 const int head = clientInfo->quotaPeekFd();
ec41b64c 1492 Comm::IoCallback *ccb = COMMIO_FD_WRITECB(head);
b4cd430a
CT
1493
1494 if (fd_table[head].clientInfo == clientInfo &&
f33d34a8
A
1495 clientInfo->quotaPeekReserv() == ccb->quotaQueueReserv &&
1496 !fd_table[head].closing()) {
b4cd430a
CT
1497
1498 // wait for the head descriptor to become ready for writing
d841c88d 1499 Comm::SetSelect(head, COMM_SELECT_WRITE, Comm::HandleWrite, ccb, 0);
b4cd430a
CT
1500 clientInfo->selectWaiting = true;
1501 return;
f33d34a8 1502 }
b4cd430a 1503
f33d34a8
A
1504 clientInfo->quotaDequeue(); // remove the no longer relevant descriptor
1505 // and continue looking for a relevant one
b4cd430a
CT
1506 } while (clientInfo->hasQueue());
1507
1508 debugs(77,3, HERE << "emptied queue");
1509}
1510
1511bool
1512ClientInfo::hasQueue() const
1513{
1514 assert(quotaQueue);
1515 return !quotaQueue->empty();
1516}
1517
1518bool
1519ClientInfo::hasQueue(const CommQuotaQueue *q) const
1520{
1521 assert(quotaQueue);
1522 return quotaQueue == q;
1523}
1524
1525/// returns the first descriptor to be dequeued
1526int
1527ClientInfo::quotaPeekFd() const
1528{
1529 assert(quotaQueue);
1530 return quotaQueue->front();
1531}
1532
1533/// returns the reservation ID of the first descriptor to be dequeued
1534unsigned int
1535ClientInfo::quotaPeekReserv() const
1536{
1537 assert(quotaQueue);
1538 return quotaQueue->outs + 1;
1539}
1540
1541/// queues a given fd, creating the queue if necessary; returns reservation ID
1542unsigned int
1543ClientInfo::quotaEnqueue(int fd)
1544{
1545 assert(quotaQueue);
1546 return quotaQueue->enqueue(fd);
1547}
1548
1549/// removes queue head
1550void
1551ClientInfo::quotaDequeue()
1552{
1553 assert(quotaQueue);
1554 quotaQueue->dequeue();
1555}
1556
1557void
1558ClientInfo::kickQuotaQueue()
1559{
1560 if (!eventWaiting && !selectWaiting && hasQueue()) {
1561 // wait at least a second if the bucket is empty
1562 const double delay = (bucketSize < 1.0) ? 1.0 : 0.0;
1563 eventAdd("commHandleWriteHelper", &commHandleWriteHelper,
f33d34a8 1564 quotaQueue, delay, 0, true);
b4cd430a
CT
1565 eventWaiting = true;
1566 }
1567}
1568
1569/// calculates how much to write for a single dequeued client
1570int
1571ClientInfo::quotaForDequed()
1572{
1573 /* If we have multiple clients and give full bucketSize to each client then
1574 * clt1 may often get a lot more because clt1->clt2 time distance in the
1575 * select(2) callback order may be a lot smaller than cltN->clt1 distance.
1576 * We divide quota evenly to be more fair. */
1577
1578 if (!rationedCount) {
1579 rationedCount = quotaQueue->size() + 1;
1580
1581 // The delay in ration recalculation _temporary_ deprives clients from
1582 // bytes that should have trickled in while rationedCount was positive.
1583 refillBucket();
1584
1585 // Rounding errors do not accumulate here, but we round down to avoid
1586 // negative bucket sizes after write with rationedCount=1.
1587 rationedQuota = static_cast<int>(floor(bucketSize/rationedCount));
1588 debugs(77,5, HERE << "new rationedQuota: " << rationedQuota <<
f33d34a8 1589 '*' << rationedCount);
b4cd430a
CT
1590 }
1591
1592 --rationedCount;
1593 debugs(77,7, HERE << "rationedQuota: " << rationedQuota <<
f33d34a8 1594 " rations remaining: " << rationedCount);
b4cd430a
CT
1595
1596 // update 'last seen' time to prevent clientdb GC from dropping us
1597 last_seen = squid_curtime;
1598 return rationedQuota;
1599}
1600
1601///< adds bytes to the quota bucket based on the rate and passed time
1602void
1603ClientInfo::refillBucket()
1604{
1605 // all these times are in seconds, with double precision
1606 const double currTime = current_dtime;
1607 const double timePassed = currTime - prevTime;
1608
f33d34a8 1609 // Calculate allowance for the time passed. Use double to avoid
b4cd430a
CT
1610 // accumulating rounding errors for small intervals. For example, always
1611 // adding 1 byte instead of 1.4 results in 29% bandwidth allocation error.
1612 const double gain = timePassed * writeSpeedLimit;
1613
1614 debugs(77,5, HERE << currTime << " clt" << (const char*)hash.key << ": " <<
f33d34a8
A
1615 bucketSize << " + (" << timePassed << " * " << writeSpeedLimit <<
1616 " = " << gain << ')');
b4cd430a
CT
1617
1618 // to further combat error accumulation during micro updates,
1619 // quit before updating time if we cannot add at least one byte
1620 if (gain < 1.0)
f33d34a8 1621 return;
b4cd430a
CT
1622
1623 prevTime = currTime;
1624
1625 // for "first" connections, drain initial fat before refilling but keep
1626 // updating prevTime to avoid bursts after the fat is gone
1627 if (bucketSize > bucketSizeLimit) {
f33d34a8
A
1628 debugs(77,4, HERE << "not refilling while draining initial fat");
1629 return;
b4cd430a
CT
1630 }
1631
1632 bucketSize += gain;
1633
1634 // obey quota limits
1635 if (bucketSize > bucketSizeLimit)
1636 bucketSize = bucketSizeLimit;
1637}
1638
f33d34a8 1639void
b4cd430a
CT
1640ClientInfo::setWriteLimiter(const int aWriteSpeedLimit, const double anInitialBurst, const double aHighWatermark)
1641{
f33d34a8
A
1642 debugs(77,5, HERE << "Write limits for " << (const char*)hash.key <<
1643 " speed=" << aWriteSpeedLimit << " burst=" << anInitialBurst <<
1644 " highwatermark=" << aHighWatermark);
b4cd430a
CT
1645
1646 // set or possibly update traffic shaping parameters
1647 writeLimitingActive = true;
1648 writeSpeedLimit = aWriteSpeedLimit;
1649 bucketSizeLimit = aHighWatermark;
1650
1651 // but some members should only be set once for a newly activated bucket
1652 if (firstTimeConnection) {
1653 firstTimeConnection = false;
1654
1655 assert(!selectWaiting);
1656 assert(!quotaQueue);
e9dadd7d 1657 quotaQueue = new CommQuotaQueue(this);
b4cd430a
CT
1658
1659 bucketSize = anInitialBurst;
1660 prevTime = current_dtime;
1661 }
1662}
1663
1664CommQuotaQueue::CommQuotaQueue(ClientInfo *info): clientInfo(info),
f33d34a8 1665 ins(0), outs(0)
b4cd430a
CT
1666{
1667 assert(clientInfo);
1668}
1669
1670CommQuotaQueue::~CommQuotaQueue()
1671{
1672 assert(!clientInfo); // ClientInfo should clear this before destroying us
1673}
1674
1675/// places the given fd at the end of the queue; returns reservation ID
1676unsigned int
1677CommQuotaQueue::enqueue(int fd)
1678{
1679 debugs(77,5, HERE << "clt" << (const char*)clientInfo->hash.key <<
f33d34a8 1680 ": FD " << fd << " with qqid" << (ins+1) << ' ' << fds.size());
b4cd430a
CT
1681 fds.push_back(fd);
1682 return ++ins;
1683}
1684
1685/// removes queue head
1686void
1687CommQuotaQueue::dequeue()
1688{
1689 assert(!fds.empty());
1690 debugs(77,5, HERE << "clt" << (const char*)clientInfo->hash.key <<
f33d34a8
A
1691 ": FD " << fds.front() << " with qqid" << (outs+1) << ' ' <<
1692 fds.size());
b4cd430a
CT
1693 fds.pop_front();
1694 ++outs;
1695}
b4cd430a
CT
1696#endif
1697
89924214 1698/*
1699 * hm, this might be too general-purpose for all the places we'd
1700 * like to use it.
1701 */
b224ea98 1702int
e1381638
AJ
1703ignoreErrno(int ierrno)
1704{
603500e7 1705 switch (ierrno) {
62e76326 1706
89924214 1707 case EINPROGRESS:
62e76326 1708
603500e7 1709 case EWOULDBLOCK:
26a880e2 1710#if EAGAIN != EWOULDBLOCK
62e76326 1711
603500e7 1712 case EAGAIN:
26a880e2 1713#endif
62e76326 1714
603500e7 1715 case EALREADY:
62e76326 1716
603500e7 1717 case EINTR:
db494ab8 1718#ifdef ERESTART
62e76326 1719
db494ab8 1720 case ERESTART:
1721#endif
62e76326 1722
1723 return 1;
1724
603500e7 1725 default:
62e76326 1726 return 0;
603500e7 1727 }
62e76326 1728
603500e7 1729 /* NOTREACHED */
26a880e2 1730}
d723bf6b 1731
1732void
e1381638
AJ
1733commCloseAllSockets(void)
1734{
d723bf6b 1735 int fd;
1736 fde *F = NULL;
62e76326 1737
d723bf6b 1738 for (fd = 0; fd <= Biggest_FD; fd++) {
62e76326 1739 F = &fd_table[fd];
1740
1741 if (!F->flags.open)
1742 continue;
1743
1744 if (F->type != FD_SOCKET)
1745 continue;
1746
1747 if (F->flags.ipc) /* don't close inter-process sockets */
1748 continue;
1749
b0469965 1750 if (F->timeoutHandler != NULL) {
1751 AsyncCall::Pointer callback = F->timeoutHandler;
1752 F->timeoutHandler = NULL;
bf8fe701 1753 debugs(5, 5, "commCloseAllSockets: FD " << fd << ": Calling timeout handler");
9e008dda 1754 ScheduleCallHere(callback);
62e76326 1755 } else {
468fe1b5 1756 debugs(5, 5, "commCloseAllSockets: FD " << fd << ": calling comm_reset_close()");
5c336a3b 1757 old_comm_reset_close(fd);
62e76326 1758 }
d723bf6b 1759 }
1760}
1b3db6d9 1761
2d8c0b1a 1762static bool
e1381638
AJ
1763AlreadyTimedOut(fde *F)
1764{
2d8c0b1a 1765 if (!F->flags.open)
1766 return true;
1767
1768 if (F->timeout == 0)
1769 return true;
1770
1771 if (F->timeout > squid_curtime)
1772 return true;
1773
1774 return false;
1775}
1776
5ef5e5cc
AJ
1777static bool
1778writeTimedOut(int fd)
1779{
ec41b64c 1780 if (!COMMIO_FD_WRITECB(fd)->active())
5ef5e5cc
AJ
1781 return false;
1782
1783 if ((squid_curtime - fd_table[fd].writeStart) < Config.Timeout.write)
1784 return false;
1785
1786 return true;
1787}
1788
1b3db6d9 1789void
e1381638
AJ
1790checkTimeouts(void)
1791{
1b3db6d9 1792 int fd;
1793 fde *F = NULL;
b0469965 1794 AsyncCall::Pointer callback;
62e76326 1795
1b3db6d9 1796 for (fd = 0; fd <= Biggest_FD; fd++) {
62e76326 1797 F = &fd_table[fd];
1798
5ef5e5cc
AJ
1799 if (writeTimedOut(fd)) {
1800 // We have an active write callback and we are timed out
52f6ea9e 1801 debugs(5, 5, "checkTimeouts: FD " << fd << " auto write timeout");
d841c88d 1802 Comm::SetSelect(fd, COMM_SELECT_WRITE, NULL, NULL, 0);
ec41b64c 1803 COMMIO_FD_WRITECB(fd)->finish(COMM_ERROR, ETIMEDOUT);
307b696e 1804 } else if (AlreadyTimedOut(F))
62e76326 1805 continue;
1806
9e008dda 1807 debugs(5, 5, "checkTimeouts: FD " << fd << " Expired");
62e76326 1808
b0469965 1809 if (F->timeoutHandler != NULL) {
bf8fe701 1810 debugs(5, 5, "checkTimeouts: FD " << fd << ": Call timeout handler");
b0469965 1811 callback = F->timeoutHandler;
1812 F->timeoutHandler = NULL;
9e008dda 1813 ScheduleCallHere(callback);
62e76326 1814 } else {
bf8fe701 1815 debugs(5, 5, "checkTimeouts: FD " << fd << ": Forcing comm_close()");
62e76326 1816 comm_close(fd);
1817 }
b5443c04 1818 }
1819}
1820
9e008dda
AJ
1821/// Start waiting for a possibly half-closed connection to close
1822// by scheduling a read callback to a monitoring handler that
82ec8dfc 1823// will close the connection on read errors.
a46d2c0e 1824void
e1381638
AJ
1825commStartHalfClosedMonitor(int fd)
1826{
74257126 1827 debugs(5, 5, HERE << "adding FD " << fd << " to " << *TheHalfClosed);
82ec8dfc
AR
1828 assert(isOpen(fd));
1829 assert(!commHasHalfClosedMonitor(fd));
74257126
AR
1830 (void)TheHalfClosed->add(fd); // could also assert the result
1831 commPlanHalfClosedCheck(); // may schedule check if we added the first FD
1832}
1833
1834static
1835void
e1381638
AJ
1836commPlanHalfClosedCheck()
1837{
74257126
AR
1838 if (!WillCheckHalfClosed && !TheHalfClosed->empty()) {
1839 eventAdd("commHalfClosedCheck", &commHalfClosedCheck, NULL, 1.0, 1);
1840 WillCheckHalfClosed = true;
1841 }
1842}
1843
1844/// iterates over all descriptors that may need half-closed tests and
1845/// calls comm_read for those that do; re-schedules the check if needed
1846static
1847void
e1381638
AJ
1848commHalfClosedCheck(void *)
1849{
74257126
AR
1850 debugs(5, 5, HERE << "checking " << *TheHalfClosed);
1851
1852 typedef DescriptorSet::const_iterator DSCI;
1853 const DSCI end = TheHalfClosed->end();
1854 for (DSCI i = TheHalfClosed->begin(); i != end; ++i) {
ec20038e
AJ
1855 Comm::ConnectionPointer c = new Comm::Connection; // XXX: temporary. make HalfClosed a list of these.
1856 c->fd = *i;
1857 if (!fd_table[c->fd].halfClosedReader) { // not reading already
74257126 1858 AsyncCall::Pointer call = commCbCall(5,4, "commHalfClosedReader",
9e008dda 1859 CommIoCbPtrFun(&commHalfClosedReader, NULL));
ec20038e
AJ
1860 comm_read(c, NULL, 0, call);
1861 fd_table[c->fd].halfClosedReader = call;
1862 } else
1863 c->fd = -1; // XXX: temporary. prevent c replacement erase closing listed FD
74257126 1864 }
f900210a 1865
74257126
AR
1866 WillCheckHalfClosed = false; // as far as we know
1867 commPlanHalfClosedCheck(); // may need to check again
f900210a 1868}
1869
82ec8dfc
AR
1870/// checks whether we are waiting for possibly half-closed connection to close
1871// We are monitoring if the read handler for the fd is the monitoring handler.
1872bool
e1381638
AJ
1873commHasHalfClosedMonitor(int fd)
1874{
74257126 1875 return TheHalfClosed->has(fd);
a46d2c0e 1876}
1877
82ec8dfc
AR
1878/// stop waiting for possibly half-closed connection to close
1879static void
e1381638
AJ
1880commStopHalfClosedMonitor(int const fd)
1881{
74257126
AR
1882 debugs(5, 5, HERE << "removing FD " << fd << " from " << *TheHalfClosed);
1883
1884 // cancel the read if one was scheduled
1885 AsyncCall::Pointer reader = fd_table[fd].halfClosedReader;
1886 if (reader != NULL)
1887 comm_read_cancel(fd, reader);
1888 fd_table[fd].halfClosedReader = NULL;
1889
1890 TheHalfClosed->del(fd);
a46d2c0e 1891}
1892
82ec8dfc
AR
1893/// I/O handler for the possibly half-closed connection monitoring code
1894static void
e0d28505 1895commHalfClosedReader(const Comm::ConnectionPointer &conn, char *, size_t size, comm_err_t flag, int, void *)
e1381638 1896{
82ec8dfc 1897 // there cannot be more data coming in on half-closed connections
9e008dda 1898 assert(size == 0);
e0d28505
AJ
1899 assert(conn != NULL);
1900 assert(commHasHalfClosedMonitor(conn->fd)); // or we would have canceled the read
74257126 1901
e0d28505 1902 fd_table[conn->fd].halfClosedReader = NULL; // done reading, for now
a46d2c0e 1903
82ec8dfc
AR
1904 // nothing to do if fd is being closed
1905 if (flag == COMM_ERR_CLOSING)
1906 return;
a46d2c0e 1907
82ec8dfc
AR
1908 // if read failed, close the connection
1909 if (flag != COMM_OK) {
e0d28505 1910 debugs(5, 3, HERE << "closing " << conn);
80463bb4 1911 conn->close();
82ec8dfc
AR
1912 return;
1913 }
a46d2c0e 1914
82ec8dfc 1915 // continue waiting for close or error
74257126 1916 commPlanHalfClosedCheck(); // make sure this fd will be checked again
a46d2c0e 1917}
1918
a46d2c0e 1919
3e4bebf8 1920CommRead::CommRead() : conn(NULL), buf(NULL), len(0), callback(NULL) {}
a46d2c0e 1921
3e4bebf8
AJ
1922CommRead::CommRead(const Comm::ConnectionPointer &c, char *buf_, int len_, AsyncCall::Pointer &callback_)
1923 : conn(c), buf(buf_), len(len_), callback(callback_) {}
a46d2c0e 1924
a50bfe93 1925DeferredRead::DeferredRead () : theReader(NULL), theContext(NULL), theRead(), cancelled(false) {}
a46d2c0e 1926
a50bfe93 1927DeferredRead::DeferredRead (DeferrableRead *aReader, void *data, CommRead const &aRead) : theReader(aReader), theContext (data), theRead(aRead), cancelled(false) {}
a46d2c0e 1928
e1381638
AJ
1929DeferredReadManager::~DeferredReadManager()
1930{
a46d2c0e 1931 flushReads();
1932 assert (deferredReads.empty());
1933}
1934
97427e90 1935/* explicit instantiation required for some systems */
1936
63be0a78 1937/// \cond AUTODOCS-IGNORE
2236466c 1938template cbdata_type CbDataList<DeferredRead>::CBDATA_CbDataList;
63be0a78 1939/// \endcond
97427e90 1940
a46d2c0e 1941void
e1381638
AJ
1942DeferredReadManager::delayRead(DeferredRead const &aRead)
1943{
3e4bebf8 1944 debugs(5, 3, "Adding deferred read on " << aRead.theRead.conn);
2236466c 1945 CbDataList<DeferredRead> *temp = deferredReads.push_back(aRead);
2796c0d7 1946
9e008dda 1947 // We have to use a global function as a closer and point to temp
2796c0d7
AR
1948 // instead of "this" because DeferredReadManager is not a job and
1949 // is not even cbdata protected
575d05c4 1950 // XXX: and yet we use cbdata protection functions on it??
2796c0d7 1951 AsyncCall::Pointer closer = commCbCall(5,4,
9e008dda
AJ
1952 "DeferredReadManager::CloseHandler",
1953 CommCloseCbPtrFun(&CloseHandler, temp));
3e4bebf8 1954 comm_add_close_handler(aRead.theRead.conn->fd, closer);
2796c0d7 1955 temp->element.closer = closer; // remeber so that we can cancel
a46d2c0e 1956}
1957
1958void
575d05c4 1959DeferredReadManager::CloseHandler(const CommCloseCbParams &params)
e1381638 1960{
575d05c4 1961 if (!cbdataReferenceValid(params.data))
a46d2c0e 1962 return;
1963
575d05c4 1964 CbDataList<DeferredRead> *temp = (CbDataList<DeferredRead> *)params.data;
a46d2c0e 1965
2796c0d7 1966 temp->element.closer = NULL;
a46d2c0e 1967 temp->element.markCancelled();
1968}
1969
1970DeferredRead
e1381638
AJ
1971DeferredReadManager::popHead(CbDataListContainer<DeferredRead> &deferredReads)
1972{
a46d2c0e 1973 assert (!deferredReads.empty());
1974
2796c0d7 1975 DeferredRead &read = deferredReads.head->element;
e7e8ebdb
AJ
1976
1977 // NOTE: at this point the connection has been paused/stalled for an unknown
1978 // amount of time. We must re-validate that it is active and usable.
1979
1980 // If the connection has been closed already. Cancel this read.
1981 if (!Comm::IsConnOpen(read.theRead.conn)) {
1982 if (read.closer != NULL) {
1983 read.closer->cancel("Connection closed before.");
1984 read.closer = NULL;
1985 }
1986 read.markCancelled();
1987 }
1988
2796c0d7 1989 if (!read.cancelled) {
3e4bebf8 1990 comm_remove_close_handler(read.theRead.conn->fd, read.closer);
2796c0d7
AR
1991 read.closer = NULL;
1992 }
a46d2c0e 1993
1994 DeferredRead result = deferredReads.pop_front();
1995
1996 return result;
1997}
1998
1999void
e1381638
AJ
2000DeferredReadManager::kickReads(int const count)
2001{
2236466c 2002 /* if we had CbDataList::size() we could consolidate this and flushReads */
a46d2c0e 2003
33cea91c 2004 if (count < 1) {
a46d2c0e 2005 flushReads();
33cea91c 2006 return;
2007 }
a46d2c0e 2008
2009 size_t remaining = count;
2010
2011 while (!deferredReads.empty() && remaining) {
2012 DeferredRead aRead = popHead(deferredReads);
2013 kickARead(aRead);
2014
2015 if (!aRead.cancelled)
2016 --remaining;
2017 }
2018}
2019
2020void
e1381638
AJ
2021DeferredReadManager::flushReads()
2022{
2236466c 2023 CbDataListContainer<DeferredRead> reads;
a46d2c0e 2024 reads = deferredReads;
2236466c 2025 deferredReads = CbDataListContainer<DeferredRead>();
a46d2c0e 2026
27b24462 2027 // XXX: For fairness this SHOULD randomize the order
a46d2c0e 2028 while (!reads.empty()) {
2029 DeferredRead aRead = popHead(reads);
2030 kickARead(aRead);
2031 }
2032}
2033
2034void
e1381638
AJ
2035DeferredReadManager::kickARead(DeferredRead const &aRead)
2036{
a46d2c0e 2037 if (aRead.cancelled)
2038 return;
2039
3e4bebf8 2040 if (Comm::IsConnOpen(aRead.theRead.conn) && fd_table[aRead.theRead.conn->fd].closing())
af6a12ee 2041 return;
ed2c738b 2042
3e4bebf8 2043 debugs(5, 3, "Kicking deferred read on " << aRead.theRead.conn);
a46d2c0e 2044
2045 aRead.theReader(aRead.theContext, aRead.theRead);
2046}
2047
2048void
e1381638
AJ
2049DeferredRead::markCancelled()
2050{
a46d2c0e 2051 cancelled = true;
2052}
2d8c0b1a 2053
8ff3fa2e 2054int
e1381638
AJ
2055CommSelectEngine::checkEvents(int timeout)
2056{
fa3f745b 2057 static time_t last_timeout = 0;
2058
2059 /* No, this shouldn't be here. But it shouldn't be in each comm handler. -adrian */
2060 if (squid_curtime > last_timeout) {
2061 last_timeout = squid_curtime;
2062 checkTimeouts();
2063 }
2064
d841c88d 2065 switch (Comm::DoSelect(timeout)) {
8ff3fa2e 2066
2067 case COMM_OK:
2068
2069 case COMM_TIMEOUT:
2070 return 0;
2071
2072 case COMM_IDLE:
2073
2074 case COMM_SHUTDOWN:
2075 return EVENT_IDLE;
2076
2077 case COMM_ERROR:
2078 return EVENT_ERROR;
2079
2080 default:
2081 fatal_dump("comm.cc: Internal error -- this should never happen.");
2082 return EVENT_ERROR;
2083 };
2084}
10cefb7b 2085
0ffda73c 2086/// Create a unix-domain socket (UDS) that only supports FD_MSGHDR I/O.
10cefb7b 2087int
2088comm_open_uds(int sock_type,
2089 int proto,
2090 struct sockaddr_un* addr,
2091 int flags)
2092{
a67d2b2e 2093 // TODO: merge with comm_openex() when Ip::Address becomes NetAddress
ba568924 2094
10cefb7b 2095 int new_socket;
10cefb7b 2096
2097 PROF_start(comm_open);
10cefb7b 2098 /* Create socket for accepting new connections. */
2099 statCounter.syscalls.sock.sockets++;
2100
2101 /* Setup the socket addrinfo details for use */
ba568924 2102 struct addrinfo AI;
10cefb7b 2103 AI.ai_flags = 0;
2104 AI.ai_family = PF_UNIX;
2105 AI.ai_socktype = sock_type;
2106 AI.ai_protocol = proto;
2107 AI.ai_addrlen = SUN_LEN(addr);
2108 AI.ai_addr = (sockaddr*)addr;
2109 AI.ai_canonname = NULL;
2110 AI.ai_next = NULL;
2111
ba568924 2112 debugs(50, 3, HERE << "Attempt open socket for: " << addr->sun_path);
10cefb7b 2113
2114 if ((new_socket = socket(AI.ai_family, AI.ai_socktype, AI.ai_protocol)) < 0) {
2115 /* Increase the number of reserved fd's if calls to socket()
2116 * are failing because the open file table is full. This
2117 * limits the number of simultaneous clients */
2118
2119 if (limitError(errno)) {
ba568924 2120 debugs(50, DBG_IMPORTANT, HERE << "socket failure: " << xstrerror());
10cefb7b 2121 fdAdjustReserved();
2122 } else {
ba568924 2123 debugs(50, DBG_CRITICAL, HERE << "socket failure: " << xstrerror());
10cefb7b 2124 }
2125
2126 PROF_stop(comm_open);
2127 return -1;
2128 }
2129
ba568924 2130 debugs(50, 3, HERE "Opened UDS FD " << new_socket << " : family=" << AI.ai_family << ", type=" << AI.ai_socktype << ", protocol=" << AI.ai_protocol);
10cefb7b 2131
2132 /* update fdstat */
ba568924 2133 debugs(50, 5, HERE << "FD " << new_socket << " is a new socket");
10cefb7b 2134
2135 assert(!isOpen(new_socket));
1bac0258 2136 fd_open(new_socket, FD_MSGHDR, NULL);
10cefb7b 2137
2138 fdd_table[new_socket].close_file = NULL;
ba568924 2139
10cefb7b 2140 fdd_table[new_socket].close_line = 0;
2141
ba568924
AR
2142 fd_table[new_socket].sock_family = AI.ai_family;
2143
10cefb7b 2144 if (!(flags & COMM_NOCLOEXEC))
2145 commSetCloseOnExec(new_socket);
2146
2147 if (flags & COMM_REUSEADDR)
2148 commSetReuseAddr(new_socket);
2149
2150 if (flags & COMM_NONBLOCKING) {
2151 if (commSetNonBlocking(new_socket) != COMM_OK) {
2152 comm_close(new_socket);
2153 PROF_stop(comm_open);
2154 return -1;
2155 }
2156 }
2157
2158 if (flags & COMM_DOBIND) {
2159 if (commBind(new_socket, AI) != COMM_OK) {
2160 comm_close(new_socket);
2161 PROF_stop(comm_open);
2162 return -1;
2163 }
2164 }
2165
2166#ifdef TCP_NODELAY
2167 if (sock_type == SOCK_STREAM)
2168 commSetTcpNoDelay(new_socket);
2169
2170#endif
2171
2172 if (Config.tcpRcvBufsz > 0 && sock_type == SOCK_STREAM)
2173 commSetTcpRcvbuf(new_socket, Config.tcpRcvBufsz);
2174
2175 PROF_stop(comm_open);
2176
2177 return new_socket;
2178}