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