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