2 * DEBUG: section 05 Socket Functions
3 * AUTHOR: Harvest Derived
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
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.
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.
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.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
32 * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org>
36 #include "base/AsyncCall.h"
37 #include "StoreIOBuffer.h"
41 #include "comm/AcceptLimiter.h"
42 #include "comm/comm_internal.h"
43 #include "comm/Connection.h"
44 #include "comm/IoCallback.h"
45 #include "comm/Loops.h"
46 #include "comm/Write.h"
47 #include "comm/TcpAcceptor.h"
52 #include "SquidTime.h"
53 #include "CommCalls.h"
54 #include "DescriptorSet.h"
55 #include "icmp/net_db.h"
56 #include "ip/Address.h"
57 #include "ip/Intercept.h"
58 #include "ip/QosConfig.h"
60 #include "ClientInfo.h"
62 #include "ssl/support.h"
67 #include <sys/ioctl.h>
69 #ifdef HAVE_NETINET_TCP_H
70 #include <netinet/tcp.h>
74 * New C-like simple comm code. This stuff is a mess and doesn't really buy us anything.
77 static void commStopHalfClosedMonitor(int fd
);
78 static IOCB commHalfClosedReader
;
79 static void comm_init_opened(const Comm::ConnectionPointer
&conn
, tos_t tos
, nfmark_t nfmark
, const char *note
, struct addrinfo
*AI
);
80 static int comm_apply_flags(int new_socket
, Ip::Address
&addr
, int flags
, struct addrinfo
*AI
);
83 CBDATA_CLASS_INIT(CommQuotaQueue
);
85 static void commHandleWriteHelper(void * data
);
90 static DescriptorSet
*TheHalfClosed
= NULL
; /// the set of half-closed FDs
91 static bool WillCheckHalfClosed
= false; /// true if check is scheduled
92 static EVH commHalfClosedCheck
;
93 static void commPlanHalfClosedCheck();
95 static comm_err_t
commBind(int s
, struct addrinfo
&);
96 static void commSetReuseAddr(int);
97 static void commSetNoLinger(int);
99 static void commSetTcpNoDelay(int);
101 static void commSetTcpRcvbuf(int, int);
103 static MemAllocator
*conn_close_pool
= NULL
;
104 fd_debug_t
*fdd_table
= NULL
;
109 return fd
>= 0 && fd_table
&& fd_table
[fd
].flags
.open
!= 0;
115 * If the read attempt succeeds or fails, call the callback.
116 * Else, wait for another IO notification.
119 commHandleRead(int fd
, void *data
)
121 Comm::IoCallback
*ccb
= (Comm::IoCallback
*) data
;
123 assert(data
== COMMIO_FD_READCB(fd
));
124 assert(ccb
->active());
126 statCounter
.syscalls
.sock
.reads
++;
129 retval
= FD_READ_METHOD(fd
, ccb
->buf
, ccb
->size
);
130 debugs(5, 3, "comm_read_try: FD " << fd
<< ", size " << ccb
->size
<< ", retval " << retval
<< ", errno " << errno
);
132 if (retval
< 0 && !ignoreErrno(errno
)) {
133 debugs(5, 3, "comm_read_try: scheduling COMM_ERROR");
135 ccb
->finish(COMM_ERROR
, errno
);
139 /* See if we read anything */
140 /* Note - read 0 == socket EOF, which is a valid read */
142 fd_bytes(fd
, retval
, FD_READ
);
143 ccb
->offset
= retval
;
144 ccb
->finish(COMM_OK
, errno
);
148 /* Nope, register for some more IO */
149 Comm::SetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, data
, 0);
153 * Queue a read. handler/handler_data are called when the read
154 * completes, on error, or on file descriptor close.
157 comm_read(const Comm::ConnectionPointer
&conn
, char *buf
, int size
, AsyncCall::Pointer
&callback
)
159 debugs(5, 5, "comm_read, queueing read for " << conn
<< "; asynCall " << callback
);
161 /* Make sure we are open and not closing */
162 assert(Comm::IsConnOpen(conn
));
163 assert(!fd_table
[conn
->fd
].closing());
164 Comm::IoCallback
*ccb
= COMMIO_FD_READCB(conn
->fd
);
166 // Make sure we are either not reading or just passively monitoring.
167 // Active/passive conflicts are OK and simply cancel passive monitoring.
169 // if the assertion below fails, we have an active comm_read conflict
170 assert(fd_table
[conn
->fd
].halfClosedReader
!= NULL
);
171 commStopHalfClosedMonitor(conn
->fd
);
172 assert(!ccb
->active());
177 ccb
->setCallback(Comm::IOCB_READ
, callback
, (char *)buf
, NULL
, size
);
178 Comm::SetSelect(conn
->fd
, COMM_SELECT_READ
, commHandleRead
, ccb
, 0);
182 * Empty the read buffers
184 * This is a magical routine that empties the read buffers.
185 * Under some platforms (Linux) if a buffer has data in it before
186 * you call close(), the socket will hang and take quite a while
190 comm_empty_os_read_buffers(int fd
)
193 /* prevent those nasty RST packets */
194 char buf
[SQUID_TCP_SO_RCVBUF
];
196 if (fd_table
[fd
].flags
.nonblocking
== 1) {
197 while (FD_READ_METHOD(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0) {};
204 * Return whether the FD has a pending completed callback.
208 comm_has_pending_read_callback(int fd
)
211 // XXX: We do not know whether there is a read callback scheduled.
212 // This is used for pconn management that should probably be more
213 // tightly integrated into comm to minimize the chance that a
214 // closing pconn socket will be used for a new transaction.
218 // Does comm check this fd for read readiness?
219 // Note that when comm is not monitoring, there can be a pending callback
220 // call, which may resume comm monitoring once fired.
222 comm_monitors_read(int fd
)
225 // Being active is usually the same as monitoring because we always
226 // start monitoring the FD when we configure Comm::IoCallback for I/O
227 // and we usually configure Comm::IoCallback for I/O when we starting
228 // monitoring a FD for reading.
229 return COMMIO_FD_READCB(fd
)->active();
233 * Cancel a pending read. Assert that we have the right parameters,
234 * and that there are no pending read events!
236 * XXX: We do not assert that there are no pending read events and
237 * with async calls it becomes even more difficult.
238 * The whole interface should be reworked to do callback->cancel()
239 * instead of searching for places where the callback may be stored and
240 * updating the state of those places.
242 * AHC Don't call the comm handlers?
245 comm_read_cancel(int fd
, IOCB
*callback
, void *data
)
248 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
252 Comm::IoCallback
*cb
= COMMIO_FD_READCB(fd
);
253 // TODO: is "active" == "monitors FD"?
255 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
259 typedef CommCbFunPtrCallT
<CommIoCbPtrFun
> Call
;
260 Call
*call
= dynamic_cast<Call
*>(cb
->callback
.getRaw());
262 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " lacks callback");
266 call
->cancel("old comm_read_cancel");
268 typedef CommIoCbParams Params
;
269 const Params
¶ms
= GetCommParams
<Params
>(cb
->callback
);
271 /* Ok, we can be reasonably sure we won't lose any data here! */
272 assert(call
->dialer
.handler
== callback
);
273 assert(params
.data
== data
);
275 /* Delete the callback */
276 cb
->cancel("old comm_read_cancel");
278 /* And the IO event */
279 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
283 comm_read_cancel(int fd
, AsyncCall::Pointer
&callback
)
285 callback
->cancel("comm_read_cancel");
288 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
292 Comm::IoCallback
*cb
= COMMIO_FD_READCB(fd
);
295 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
299 AsyncCall::Pointer call
= cb
->callback
;
300 assert(call
!= NULL
); // XXX: should never fail (active() checks for callback==NULL)
302 /* Ok, we can be reasonably sure we won't lose any data here! */
303 assert(call
== callback
);
305 /* Delete the callback */
306 cb
->cancel("comm_read_cancel");
308 /* And the IO event */
309 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
314 * synchronous wrapper around udp socket functions
317 comm_udp_recvfrom(int fd
, void *buf
, size_t len
, int flags
, Ip::Address
&from
)
319 statCounter
.syscalls
.sock
.recvfroms
++;
321 struct addrinfo
*AI
= NULL
;
323 debugs(5,8, "comm_udp_recvfrom: FD " << fd
<< " from " << from
);
325 assert( NULL
== AI
);
327 from
.InitAddrInfo(AI
);
329 x
= recvfrom(fd
, buf
, len
, flags
, AI
->ai_addr
, &AI
->ai_addrlen
);
333 from
.FreeAddrInfo(AI
);
339 comm_udp_recv(int fd
, void *buf
, size_t len
, int flags
)
342 return comm_udp_recvfrom(fd
, buf
, len
, flags
, nul
);
346 comm_udp_send(int s
, const void *buf
, size_t len
, int flags
)
348 return send(s
, buf
, len
, flags
);
353 comm_has_incomplete_write(int fd
)
356 return COMMIO_FD_WRITECB(fd
)->active();
360 * Queue a write. handler/handler_data are called when the write fully
361 * completes, on error, or on file descriptor close.
364 /* Return the local port associated with fd. */
366 comm_local_port(int fd
)
369 struct addrinfo
*addr
= NULL
;
370 fde
*F
= &fd_table
[fd
];
372 /* If the fd is closed already, just return */
374 if (!F
->flags
.open
) {
375 debugs(5, 0, "comm_local_port: FD " << fd
<< " has been closed.");
379 if (F
->local_addr
.GetPort())
380 return F
->local_addr
.GetPort();
382 if (F
->sock_family
== AF_INET
)
385 temp
.InitAddrInfo(addr
);
387 if (getsockname(fd
, addr
->ai_addr
, &(addr
->ai_addrlen
)) ) {
388 debugs(50, 1, "comm_local_port: Failed to retrieve TCP/UDP port number for socket: FD " << fd
<< ": " << xstrerror());
389 temp
.FreeAddrInfo(addr
);
394 temp
.FreeAddrInfo(addr
);
396 if (F
->local_addr
.IsAnyAddr()) {
397 /* save the whole local address, not just the port. */
398 F
->local_addr
= temp
;
400 F
->local_addr
.SetPort(temp
.GetPort());
403 debugs(5, 6, "comm_local_port: FD " << fd
<< ": port " << F
->local_addr
.GetPort() << "(family=" << F
->sock_family
<< ")");
404 return F
->local_addr
.GetPort();
408 commBind(int s
, struct addrinfo
&inaddr
)
410 statCounter
.syscalls
.sock
.binds
++;
412 if (bind(s
, inaddr
.ai_addr
, inaddr
.ai_addrlen
) == 0) {
413 debugs(50, 6, "commBind: bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
);
417 debugs(50, 0, "commBind: Cannot bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
<< ": " << xstrerror());
423 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
424 * is OR of flags specified in comm.h. Defaults TOS
427 comm_open(int sock_type
,
433 return comm_openex(sock_type
, proto
, addr
, flags
, 0, 0, note
);
437 comm_open_listener(int sock_type
,
439 Comm::ConnectionPointer
&conn
,
442 /* all listener sockets require bind() */
443 conn
->flags
|= COMM_DOBIND
;
445 /* attempt native enabled port. */
446 conn
->fd
= comm_openex(sock_type
, proto
, conn
->local
, conn
->flags
, 0, 0, note
);
450 comm_open_listener(int sock_type
,
458 /* all listener sockets require bind() */
459 flags
|= COMM_DOBIND
;
461 /* attempt native enabled port. */
462 sock
= comm_openex(sock_type
, proto
, addr
, flags
, 0, 0, note
);
468 limitError(int const anErrno
)
470 return anErrno
== ENFILE
|| anErrno
== EMFILE
;
474 comm_set_v6only(int fd
, int tos
)
477 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (char *) &tos
, sizeof(int)) < 0) {
478 debugs(50, 1, "comm_open: setsockopt(IPV6_V6ONLY) " << (tos
?"ON":"OFF") << " for FD " << fd
<< ": " << xstrerror());
481 debugs(50, 0, "WARNING: comm_open: setsockopt(IPV6_V6ONLY) not supported on this platform");
486 * Set the socket IP_TRANSPARENT option for Linux TPROXY v4 support.
489 comm_set_transparent(int fd
)
491 #if defined(IP_TRANSPARENT)
493 if (setsockopt(fd
, SOL_IP
, IP_TRANSPARENT
, (char *) &tos
, sizeof(int)) < 0) {
494 debugs(50, DBG_IMPORTANT
, "comm_open: setsockopt(IP_TRANSPARENT) on FD " << fd
<< ": " << xstrerror());
496 /* mark the socket as having transparent options */
497 fd_table
[fd
].flags
.transparent
= 1;
500 debugs(50, DBG_CRITICAL
, "WARNING: comm_open: setsockopt(IP_TRANSPARENT) not supported on this platform");
505 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
506 * is OR of flags specified in defines.h:COMM_*
509 comm_openex(int sock_type
,
518 struct addrinfo
*AI
= NULL
;
520 PROF_start(comm_open
);
521 /* Create socket for accepting new connections. */
522 statCounter
.syscalls
.sock
.sockets
++;
524 /* Setup the socket addrinfo details for use */
525 addr
.GetAddrInfo(AI
);
526 AI
->ai_socktype
= sock_type
;
527 AI
->ai_protocol
= proto
;
529 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr
);
531 new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
533 /* under IPv6 there is the possibility IPv6 is present but disabled. */
534 /* try again as IPv4-native if possible */
535 if ( new_socket
< 0 && Ip::EnableIpv6
&& addr
.IsIPv6() && addr
.SetIPv4() ) {
536 /* attempt to open this IPv4-only. */
537 addr
.FreeAddrInfo(AI
);
538 /* Setup the socket addrinfo details for use */
539 addr
.GetAddrInfo(AI
);
540 AI
->ai_socktype
= sock_type
;
541 AI
->ai_protocol
= proto
;
542 debugs(50, 3, "comm_openex: Attempt fallback open socket for: " << addr
);
543 new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
544 debugs(50, 2, HERE
<< "attempt open " << note
<< " socket on: " << addr
);
547 if (new_socket
< 0) {
548 /* Increase the number of reserved fd's if calls to socket()
549 * are failing because the open file table is full. This
550 * limits the number of simultaneous clients */
552 if (limitError(errno
)) {
553 debugs(50, DBG_IMPORTANT
, "comm_open: socket failure: " << xstrerror());
556 debugs(50, DBG_CRITICAL
, "comm_open: socket failure: " << xstrerror());
559 addr
.FreeAddrInfo(AI
);
561 PROF_stop(comm_open
);
565 // XXX: temporary for the transition. comm_openex will eventually have a conn to play with.
566 Comm::ConnectionPointer conn
= new Comm::Connection
;
568 conn
->fd
= new_socket
;
570 debugs(50, 3, "comm_openex: Opened socket " << conn
<< " : family=" << AI
->ai_family
<< ", type=" << AI
->ai_socktype
<< ", protocol=" << AI
->ai_protocol
);
572 /* set TOS if needed */
574 Ip::Qos::setSockTos(conn
, tos
);
576 /* set netfilter mark if needed */
578 Ip::Qos::setSockNfmark(conn
, nfmark
);
580 if ( Ip::EnableIpv6
&IPV6_SPECIAL_SPLITSTACK
&& addr
.IsIPv6() )
581 comm_set_v6only(conn
->fd
, 1);
583 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
584 /* Other OS may have this administratively disabled for general use. Same deal. */
585 if ( Ip::EnableIpv6
&IPV6_SPECIAL_V4MAPPING
&& addr
.IsIPv6() )
586 comm_set_v6only(conn
->fd
, 0);
588 comm_init_opened(conn
, tos
, nfmark
, note
, AI
);
589 new_socket
= comm_apply_flags(conn
->fd
, addr
, flags
, AI
);
591 addr
.FreeAddrInfo(AI
);
593 PROF_stop(comm_open
);
595 // XXX transition only. prevent conn from closing the new FD on function exit.
600 /// update FD tables after a local or remote (IPC) comm_openex();
602 comm_init_opened(const Comm::ConnectionPointer
&conn
,
608 assert(Comm::IsConnOpen(conn
));
612 debugs(5, 5, HERE
<< conn
<< " is a new socket");
614 assert(!isOpen(conn
->fd
)); // NP: global isOpen checks the fde entry for openness not the Comm::Connection
615 fd_open(conn
->fd
, FD_SOCKET
, note
);
617 fdd_table
[conn
->fd
].close_file
= NULL
;
618 fdd_table
[conn
->fd
].close_line
= 0;
620 fde
*F
= &fd_table
[conn
->fd
];
621 F
->local_addr
= conn
->local
;
622 F
->tosToServer
= tos
;
624 F
->nfmarkToServer
= nfmark
;
626 F
->sock_family
= AI
->ai_family
;
629 /// apply flags after a local comm_open*() call;
630 /// returns new_socket or -1 on error
632 comm_apply_flags(int new_socket
,
637 assert(new_socket
>= 0);
639 const int sock_type
= AI
->ai_socktype
;
641 if (!(flags
& COMM_NOCLOEXEC
))
642 commSetCloseOnExec(new_socket
);
644 if ((flags
& COMM_REUSEADDR
))
645 commSetReuseAddr(new_socket
);
647 if (addr
.GetPort() > (unsigned short) 0) {
649 if (sock_type
!= SOCK_DGRAM
)
651 commSetNoLinger(new_socket
);
654 commSetReuseAddr(new_socket
);
657 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
658 if ((flags
& COMM_TRANSPARENT
)) {
659 comm_set_transparent(new_socket
);
662 if ( (flags
& COMM_DOBIND
) || addr
.GetPort() > 0 || !addr
.IsAnyAddr() ) {
663 if ( !(flags
& COMM_DOBIND
) && addr
.IsAnyAddr() )
664 debugs(5,1,"WARNING: Squid is attempting to bind() port " << addr
<< " without being a listener.");
665 if ( addr
.IsNoAddr() )
666 debugs(5,0,"CRITICAL: Squid is attempting to bind() port " << addr
<< "!!");
668 if (commBind(new_socket
, *AI
) != COMM_OK
) {
669 comm_close(new_socket
);
674 if (flags
& COMM_NONBLOCKING
)
675 if (commSetNonBlocking(new_socket
) == COMM_ERROR
) {
676 comm_close(new_socket
);
681 if (sock_type
== SOCK_STREAM
)
682 commSetTcpNoDelay(new_socket
);
686 if (Config
.tcpRcvBufsz
> 0 && sock_type
== SOCK_STREAM
)
687 commSetTcpRcvbuf(new_socket
, Config
.tcpRcvBufsz
);
693 comm_import_opened(const Comm::ConnectionPointer
&conn
,
697 debugs(5, 2, HERE
<< conn
);
698 assert(Comm::IsConnOpen(conn
));
701 comm_init_opened(conn
, 0, 0, note
, AI
);
703 if (!(conn
->flags
& COMM_NOCLOEXEC
))
704 fd_table
[conn
->fd
].flags
.close_on_exec
= 1;
706 if (conn
->local
.GetPort() > (unsigned short) 0) {
708 if (AI
->ai_socktype
!= SOCK_DGRAM
)
710 fd_table
[conn
->fd
].flags
.nolinger
= 1;
713 if ((conn
->flags
& COMM_TRANSPARENT
))
714 fd_table
[conn
->fd
].flags
.transparent
= 1;
716 if (conn
->flags
& COMM_NONBLOCKING
)
717 fd_table
[conn
->fd
].flags
.nonblocking
= 1;
720 if (AI
->ai_socktype
== SOCK_STREAM
)
721 fd_table
[conn
->fd
].flags
.nodelay
= 1;
724 /* no fd_table[fd].flags. updates needed for these conditions:
725 * if ((flags & COMM_REUSEADDR)) ...
726 * if ((flags & COMM_DOBIND) ...) ...
730 // Legacy pre-AsyncCalls API for FD timeouts.
732 commSetTimeout(int fd
, int timeout
, CTCB
* handler
, void *data
)
734 AsyncCall::Pointer call
;
735 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
737 call
=commCbCall(5,4, "SomeTimeoutHandler", CommTimeoutCbPtrFun(handler
, data
));
740 return commSetTimeout(fd
, timeout
, call
);
743 // Legacy pre-Comm::Connection API for FD timeouts
744 // still used by non-socket FD code dealing with pipes and IPC sockets.
746 commSetTimeout(int fd
, int timeout
, AsyncCall::Pointer
&callback
)
748 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
750 assert(fd
< Squid_MaxFD
);
751 fde
*F
= &fd_table
[fd
];
752 assert(F
->flags
.open
);
755 F
->timeoutHandler
= NULL
;
758 if (callback
!= NULL
) {
759 typedef CommTimeoutCbParams Params
;
760 Params
¶ms
= GetCommParams
<Params
>(callback
);
762 F
->timeoutHandler
= callback
;
765 F
->timeout
= squid_curtime
+ (time_t) timeout
;
772 commSetConnTimeout(const Comm::ConnectionPointer
&conn
, int timeout
, AsyncCall::Pointer
&callback
)
774 debugs(5, 3, HERE
<< conn
<< " timeout " << timeout
);
775 assert(Comm::IsConnOpen(conn
));
776 assert(conn
->fd
< Squid_MaxFD
);
777 fde
*F
= &fd_table
[conn
->fd
];
778 assert(F
->flags
.open
);
781 F
->timeoutHandler
= NULL
;
784 if (callback
!= NULL
) {
785 typedef CommTimeoutCbParams Params
;
786 Params
¶ms
= GetCommParams
<Params
>(callback
);
788 F
->timeoutHandler
= callback
;
791 F
->timeout
= squid_curtime
+ (time_t) timeout
;
798 commUnsetConnTimeout(const Comm::ConnectionPointer
&conn
)
800 debugs(5, 3, HERE
<< "Remove timeout for " << conn
);
801 AsyncCall::Pointer nil
;
802 return commSetConnTimeout(conn
, -1, nil
);
806 comm_connect_addr(int sock
, const Ip::Address
&address
)
808 comm_err_t status
= COMM_OK
;
809 fde
*F
= &fd_table
[sock
];
813 struct addrinfo
*AI
= NULL
;
814 PROF_start(comm_connect_addr
);
816 assert(address
.GetPort() != 0);
818 debugs(5, 9, HERE
<< "connecting socket FD " << sock
<< " to " << address
<< " (want family: " << F
->sock_family
<< ")");
820 /* Handle IPv6 over IPv4-only socket case.
821 * this case must presently be handled here since the GetAddrInfo asserts on bad mappings.
822 * NP: because commResetFD is private to ConnStateData we have to return an error and
823 * trust its handled properly.
825 if (F
->sock_family
== AF_INET
&& !address
.IsIPv4()) {
827 return COMM_ERR_PROTOCOL
;
830 /* Handle IPv4 over IPv6-only socket case.
831 * This case is presently handled here as it's both a known case and it's
832 * uncertain what error will be returned by the IPv6 stack in such case. It's
833 * possible this will also be handled by the errno checks below after connect()
834 * but needs carefull cross-platform verification, and verifying the address
835 * condition here is simple.
837 if (!F
->local_addr
.IsIPv4() && address
.IsIPv4()) {
839 return COMM_ERR_PROTOCOL
;
842 address
.GetAddrInfo(AI
, F
->sock_family
);
844 /* Establish connection. */
847 if (!F
->flags
.called_connect
) {
848 F
->flags
.called_connect
= 1;
849 statCounter
.syscalls
.sock
.connects
++;
851 x
= connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
853 // XXX: ICAP code refuses callbacks during a pending comm_ call
854 // Async calls development will fix this.
861 debugs(5,5, "comm_connect_addr: sock=" << sock
<< ", addrinfo( " <<
862 " flags=" << AI
->ai_flags
<<
863 ", family=" << AI
->ai_family
<<
864 ", socktype=" << AI
->ai_socktype
<<
865 ", protocol=" << AI
->ai_protocol
<<
866 ", &addr=" << AI
->ai_addr
<<
867 ", addrlen=" << AI
->ai_addrlen
<<
869 debugs(5, 9, "connect FD " << sock
<< ": (" << x
<< ") " << xstrerror());
870 debugs(14,9, "connecting to: " << address
);
873 #if defined(_SQUID_NEWSOS6_)
874 /* Makoto MATSUSHITA <matusita@ics.es.osaka-u.ac.jp> */
876 connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
878 if (errno
== EINVAL
) {
879 errlen
= sizeof(err
);
880 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
887 errlen
= sizeof(err
);
889 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
894 #if defined(_SQUID_SOLARIS_)
896 * Solaris 2.4's socket emulation doesn't allow you
897 * to determine the error from a failed non-blocking
898 * connect and just returns EPIPE. Create a fake
899 * error message for connect. -- fenner@parc.xerox.com
901 if (x
< 0 && errno
== EPIPE
)
909 /* Squid seems to be working fine without this code. With this code,
910 * we leak memory on many connect requests because of EINPROGRESS.
911 * If you find that this code is needed, please file a bug report. */
915 * Linux Debian replaces our allocated AI pointer with garbage when
916 * connect() fails. This leads to segmentation faults deallocating
917 * the system-allocated memory when we go to clean up our pointer.
918 * HACK: is to leak the memory returned since we can't deallocate.
926 address
.FreeAddrInfo(AI
);
928 PROF_stop(comm_connect_addr
);
930 if (errno
== 0 || errno
== EISCONN
)
932 else if (ignoreErrno(errno
))
933 status
= COMM_INPROGRESS
;
934 else if (errno
== EAFNOSUPPORT
|| errno
== EINVAL
)
935 return COMM_ERR_PROTOCOL
;
939 address
.NtoA(F
->ipaddr
, MAX_IPSTRLEN
);
941 F
->remote_port
= address
.GetPort(); /* remote_port is HS */
943 if (status
== COMM_OK
) {
944 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connected to " << address
);
945 } else if (status
== COMM_INPROGRESS
) {
946 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connection pending");
953 commCallCloseHandlers(int fd
)
955 fde
*F
= &fd_table
[fd
];
956 debugs(5, 5, "commCallCloseHandlers: FD " << fd
);
958 while (F
->closeHandler
!= NULL
) {
959 AsyncCall::Pointer call
= F
->closeHandler
;
960 F
->closeHandler
= call
->Next();
962 // If call is not canceled schedule it for execution else ignore it
963 if (!call
->canceled()) {
964 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call
);
965 typedef CommCloseCbParams Params
;
966 Params
¶ms
= GetCommParams
<Params
>(call
);
968 ScheduleCallHere(call
);
975 commLingerClose(int fd
, void *unused
)
977 LOCAL_ARRAY(char, buf
, 1024);
979 n
= FD_READ_METHOD(fd
, buf
, 1024);
982 debugs(5, 3, "commLingerClose: FD " << fd
<< " read: " << xstrerror());
988 commLingerTimeout(int fd
, void *unused
)
990 debugs(5, 3, "commLingerTimeout: FD " << fd
);
998 comm_lingering_close(int fd
)
1002 if (fd_table
[fd
].ssl
)
1003 ssl_shutdown_method(fd
);
1007 if (shutdown(fd
, 1) < 0) {
1012 fd_note(fd
, "lingering close");
1013 commSetTimeout(fd
, 10, commLingerTimeout
, NULL
);
1014 Comm::SetSelect(fd
, COMM_SELECT_READ
, commLingerClose
, NULL
, 0);
1020 * enable linger with time of 0 so that when the socket is
1021 * closed, TCP generates a RESET
1024 comm_reset_close(const Comm::ConnectionPointer
&conn
)
1030 if (setsockopt(conn
->fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1031 debugs(50, DBG_CRITICAL
, "ERROR: Closing " << conn
<< " with TCP RST: " << xstrerror());
1036 // Legacy close function.
1038 old_comm_reset_close(int fd
)
1044 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1045 debugs(50, DBG_CRITICAL
, "ERROR: Closing FD " << fd
<< " with TCP RST: " << xstrerror());
1051 comm_close_start(int fd
, void *data
)
1054 fde
*F
= &fd_table
[fd
];
1056 ssl_shutdown_method(fd
);
1063 comm_close_complete(int fd
, void *data
)
1066 fde
*F
= &fd_table
[fd
];
1073 if (F
->dynamicSslContext
) {
1074 SSL_CTX_free(F
->dynamicSslContext
);
1075 F
->dynamicSslContext
= NULL
;
1078 fd_close(fd
); /* update fdstat */
1082 statCounter
.syscalls
.sock
.closes
++;
1084 /* When an fd closes, give accept() a chance, if need be */
1085 Comm::AcceptLimiter::Instance().kick();
1089 * Close the socket fd.
1091 * + call write handlers with ERR_CLOSING
1092 * + call read handlers with ERR_CLOSING
1093 * + call closing handlers
1095 * NOTE: COMM_ERR_CLOSING will NOT be called for CommReads' sitting in a
1096 * DeferredReadManager.
1099 _comm_close(int fd
, char const *file
, int line
)
1101 debugs(5, 3, "comm_close: start closing FD " << fd
);
1103 assert(fd
< Squid_MaxFD
);
1105 fde
*F
= &fd_table
[fd
];
1106 fdd_table
[fd
].close_file
= file
;
1107 fdd_table
[fd
].close_line
= line
;
1112 /* XXX: is this obsolete behind F->closing() ? */
1113 if ( (shutting_down
|| reconfiguring
) && (!F
->flags
.open
|| F
->type
== FD_FILE
))
1116 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
1119 assert(F
->type
!= FD_FILE
);
1121 PROF_start(comm_close
);
1123 F
->flags
.close_request
= 1;
1125 AsyncCall::Pointer startCall
=commCbCall(5,4, "comm_close_start",
1126 CommCloseCbPtrFun(comm_close_start
, NULL
));
1127 typedef CommCloseCbParams Params
;
1128 Params
&startParams
= GetCommParams
<Params
>(startCall
);
1129 startParams
.fd
= fd
;
1130 ScheduleCallHere(startCall
);
1132 // a half-closed fd may lack a reader, so we stop monitoring explicitly
1133 if (commHasHalfClosedMonitor(fd
))
1134 commStopHalfClosedMonitor(fd
);
1135 commSetTimeout(fd
, -1, NULL
, NULL
);
1137 // notify read/write handlers after canceling select reservations, if any
1138 if (COMMIO_FD_WRITECB(fd
)->active()) {
1139 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
1140 COMMIO_FD_WRITECB(fd
)->finish(COMM_ERR_CLOSING
, errno
);
1142 if (COMMIO_FD_READCB(fd
)->active()) {
1143 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
1144 COMMIO_FD_READCB(fd
)->finish(COMM_ERR_CLOSING
, errno
);
1148 if (ClientInfo
*clientInfo
= F
->clientInfo
) {
1149 if (clientInfo
->selectWaiting
) {
1150 clientInfo
->selectWaiting
= false;
1151 // kick queue or it will get stuck as commWriteHandle is not called
1152 clientInfo
->kickQuotaQueue();
1157 commCallCloseHandlers(fd
);
1159 if (F
->pconn
.uses
&& F
->pconn
.pool
)
1160 F
->pconn
.pool
->noteUses(F
->pconn
.uses
);
1162 comm_empty_os_read_buffers(fd
);
1165 AsyncCall::Pointer completeCall
=commCbCall(5,4, "comm_close_complete",
1166 CommCloseCbPtrFun(comm_close_complete
, NULL
));
1167 Params
&completeParams
= GetCommParams
<Params
>(completeCall
);
1168 completeParams
.fd
= fd
;
1169 // must use async call to wait for all callbacks
1170 // scheduled before comm_close() to finish
1171 ScheduleCallHere(completeCall
);
1173 PROF_stop(comm_close
);
1176 /* Send a udp datagram to specified TO_ADDR. */
1178 comm_udp_sendto(int fd
,
1179 const Ip::Address
&to_addr
,
1184 struct addrinfo
*AI
= NULL
;
1186 PROF_start(comm_udp_sendto
);
1187 statCounter
.syscalls
.sock
.sendtos
++;
1189 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr
<<
1190 " using FD " << fd
<< " using Port " << comm_local_port(fd
) );
1192 /* BUG: something in the above macro appears to occasionally be setting AI to garbage. */
1193 /* AYJ: 2007-08-27 : or was it because I wasn't then setting 'fd_table[fd].sock_family' to fill properly. */
1194 assert( NULL
== AI
);
1196 to_addr
.GetAddrInfo(AI
, fd_table
[fd
].sock_family
);
1198 x
= sendto(fd
, buf
, len
, 0, AI
->ai_addr
, AI
->ai_addrlen
);
1200 to_addr
.FreeAddrInfo(AI
);
1202 PROF_stop(comm_udp_sendto
);
1209 if (ECONNREFUSED
!= errno
)
1212 debugs(50, 1, "comm_udp_sendto: FD " << fd
<< ", (family=" << fd_table
[fd
].sock_family
<< ") " << to_addr
<< ": " << xstrerror());
1218 comm_add_close_handler(int fd
, PF
* handler
, void *data
)
1220 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", handler=" <<
1221 handler
<< ", data=" << data
);
1223 AsyncCall::Pointer call
=commCbCall(5,4, "SomeCloseHandler",
1224 CommCloseCbPtrFun(handler
, data
));
1225 comm_add_close_handler(fd
, call
);
1229 comm_add_close_handler(int fd
, AsyncCall::Pointer
&call
)
1231 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1233 /*TODO:Check for a similar scheduled AsyncCall*/
1234 // for (c = fd_table[fd].closeHandler; c; c = c->next)
1235 // assert(c->handler != handler || c->data != data);
1237 call
->setNext(fd_table
[fd
].closeHandler
);
1239 fd_table
[fd
].closeHandler
= call
;
1243 // remove function-based close handler
1245 comm_remove_close_handler(int fd
, PF
* handler
, void *data
)
1247 assert (isOpen(fd
));
1248 /* Find handler in list */
1249 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", handler=" <<
1250 handler
<< ", data=" << data
);
1252 AsyncCall::Pointer p
, prev
= NULL
;
1253 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
; prev
= p
, p
= p
->Next()) {
1254 typedef CommCbFunPtrCallT
<CommCloseCbPtrFun
> Call
;
1255 const Call
*call
= dynamic_cast<const Call
*>(p
.getRaw());
1256 if (!call
) // method callbacks have their own comm_remove_close_handler
1259 typedef CommCloseCbParams Params
;
1260 const Params
¶ms
= GetCommParams
<Params
>(p
);
1261 if (call
->dialer
.handler
== handler
&& params
.data
== data
)
1262 break; /* This is our handler */
1265 // comm_close removes all close handlers so our handler may be gone
1267 p
->dequeue(fd_table
[fd
].closeHandler
, prev
);
1268 p
->cancel("comm_remove_close_handler");
1272 // remove method-based close handler
1274 comm_remove_close_handler(int fd
, AsyncCall::Pointer
&call
)
1276 assert (isOpen(fd
));
1277 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1279 // comm_close removes all close handlers so our handler may be gone
1280 AsyncCall::Pointer p
, prev
= NULL
;
1281 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
&& p
!= call
; prev
= p
, p
= p
->Next());
1284 p
->dequeue(fd_table
[fd
].closeHandler
, prev
);
1285 call
->cancel("comm_remove_close_handler");
1289 commSetNoLinger(int fd
)
1293 L
.l_onoff
= 0; /* off */
1296 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1297 debugs(50, 0, "commSetNoLinger: FD " << fd
<< ": " << xstrerror());
1299 fd_table
[fd
].flags
.nolinger
= 1;
1303 commSetReuseAddr(int fd
)
1307 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &on
, sizeof(on
)) < 0)
1308 debugs(50, 1, "commSetReuseAddr: FD " << fd
<< ": " << xstrerror());
1312 commSetTcpRcvbuf(int fd
, int size
)
1314 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, (char *) &size
, sizeof(size
)) < 0)
1315 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1316 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, (char *) &size
, sizeof(size
)) < 0)
1317 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1318 #ifdef TCP_WINDOW_CLAMP
1319 if (setsockopt(fd
, SOL_TCP
, TCP_WINDOW_CLAMP
, (char *) &size
, sizeof(size
)) < 0)
1320 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1325 commSetNonBlocking(int fd
)
1332 int nonblocking
= TRUE
;
1335 if (fd_table
[fd
].type
!= FD_PIPE
) {
1338 if (ioctl(fd
, FIONBIO
, &nonblocking
) < 0) {
1339 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror() << " " << fd_table
[fd
].type
);
1349 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1350 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1354 if (fcntl(fd
, F_SETFL
, flags
| SQUID_NONBLOCK
) < 0) {
1355 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror());
1363 fd_table
[fd
].flags
.nonblocking
= 1;
1369 commUnsetNonBlocking(int fd
)
1372 int nonblocking
= FALSE
;
1374 if (ioctlsocket(fd
, FIONBIO
, (unsigned long *) &nonblocking
) < 0) {
1379 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1380 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1384 if (fcntl(fd
, F_SETFL
, flags
& (~SQUID_NONBLOCK
)) < 0) {
1386 debugs(50, 0, "commUnsetNonBlocking: FD " << fd
<< ": " << xstrerror());
1390 fd_table
[fd
].flags
.nonblocking
= 0;
1395 commSetCloseOnExec(int fd
)
1401 if ((flags
= fcntl(fd
, F_GETFD
, dummy
)) < 0) {
1402 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFD: " << xstrerror());
1406 if (fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) < 0)
1407 debugs(50, 0, "FD " << fd
<< ": set close-on-exec failed: " << xstrerror());
1409 fd_table
[fd
].flags
.close_on_exec
= 1;
1416 commSetTcpNoDelay(int fd
)
1420 if (setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *) &on
, sizeof(on
)) < 0)
1421 debugs(50, 1, "commSetTcpNoDelay: FD " << fd
<< ": " << xstrerror());
1423 fd_table
[fd
].flags
.nodelay
= 1;
1429 commSetTcpKeepalive(int fd
, int idle
, int interval
, int timeout
)
1433 if (timeout
&& interval
) {
1434 int count
= (timeout
+ interval
- 1) / interval
;
1435 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPCNT
, &count
, sizeof(on
)) < 0)
1436 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1441 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, &idle
, sizeof(on
)) < 0)
1442 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1445 #ifdef TCP_KEEPINTVL
1447 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, &interval
, sizeof(on
)) < 0)
1448 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1451 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char *) &on
, sizeof(on
)) < 0)
1452 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1458 fd_table
=(fde
*) xcalloc(Squid_MaxFD
, sizeof(fde
));
1459 fdd_table
= (fd_debug_t
*)xcalloc(Squid_MaxFD
, sizeof(fd_debug_t
));
1461 /* make sure the accept() socket FIFO delay queue exists */
1462 Comm::AcceptLimiter::Instance();
1464 // make sure the IO pending callback table exists
1465 Comm::CallbackTableInit();
1467 /* XXX account fd_table */
1468 /* Keep a few file descriptors free so that we don't run out of FD's
1469 * after accepting a client but before it opens a socket or a file.
1470 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
1471 RESERVED_FD
= min(100, Squid_MaxFD
/ 4);
1473 conn_close_pool
= memPoolCreate("close_handler", sizeof(close_handler
));
1475 TheHalfClosed
= new DescriptorSet
;
1477 /* setup the select loop module */
1478 Comm::SelectLoopInit();
1484 delete TheHalfClosed
;
1485 TheHalfClosed
= NULL
;
1487 safe_free(fd_table
);
1488 safe_free(fdd_table
);
1489 Comm::CallbackTableDestruct();
1493 // called when the queue is done waiting for the client bucket to fill
1495 commHandleWriteHelper(void * data
)
1497 CommQuotaQueue
*queue
= static_cast<CommQuotaQueue
*>(data
);
1500 ClientInfo
*clientInfo
= queue
->clientInfo
;
1501 // ClientInfo invalidates queue if freed, so if we got here through,
1502 // evenAdd cbdata protections, everything should be valid and consistent
1504 assert(clientInfo
->hasQueue());
1505 assert(clientInfo
->hasQueue(queue
));
1506 assert(!clientInfo
->selectWaiting
);
1507 assert(clientInfo
->eventWaiting
);
1508 clientInfo
->eventWaiting
= false;
1511 // check that the head descriptor is still relevant
1512 const int head
= clientInfo
->quotaPeekFd();
1513 Comm::IoCallback
*ccb
= COMMIO_FD_WRITECB(head
);
1515 if (fd_table
[head
].clientInfo
== clientInfo
&&
1516 clientInfo
->quotaPeekReserv() == ccb
->quotaQueueReserv
&&
1517 !fd_table
[head
].closing()) {
1519 // wait for the head descriptor to become ready for writing
1520 Comm::SetSelect(head
, COMM_SELECT_WRITE
, Comm::HandleWrite
, ccb
, 0);
1521 clientInfo
->selectWaiting
= true;
1525 clientInfo
->quotaDequeue(); // remove the no longer relevant descriptor
1526 // and continue looking for a relevant one
1527 } while (clientInfo
->hasQueue());
1529 debugs(77,3, HERE
<< "emptied queue");
1533 ClientInfo::hasQueue() const
1536 return !quotaQueue
->empty();
1540 ClientInfo::hasQueue(const CommQuotaQueue
*q
) const
1543 return quotaQueue
== q
;
1546 /// returns the first descriptor to be dequeued
1548 ClientInfo::quotaPeekFd() const
1551 return quotaQueue
->front();
1554 /// returns the reservation ID of the first descriptor to be dequeued
1556 ClientInfo::quotaPeekReserv() const
1559 return quotaQueue
->outs
+ 1;
1562 /// queues a given fd, creating the queue if necessary; returns reservation ID
1564 ClientInfo::quotaEnqueue(int fd
)
1567 return quotaQueue
->enqueue(fd
);
1570 /// removes queue head
1572 ClientInfo::quotaDequeue()
1575 quotaQueue
->dequeue();
1579 ClientInfo::kickQuotaQueue()
1581 if (!eventWaiting
&& !selectWaiting
&& hasQueue()) {
1582 // wait at least a second if the bucket is empty
1583 const double delay
= (bucketSize
< 1.0) ? 1.0 : 0.0;
1584 eventAdd("commHandleWriteHelper", &commHandleWriteHelper
,
1585 quotaQueue
, delay
, 0, true);
1586 eventWaiting
= true;
1590 /// calculates how much to write for a single dequeued client
1592 ClientInfo::quotaForDequed()
1594 /* If we have multiple clients and give full bucketSize to each client then
1595 * clt1 may often get a lot more because clt1->clt2 time distance in the
1596 * select(2) callback order may be a lot smaller than cltN->clt1 distance.
1597 * We divide quota evenly to be more fair. */
1599 if (!rationedCount
) {
1600 rationedCount
= quotaQueue
->size() + 1;
1602 // The delay in ration recalculation _temporary_ deprives clients from
1603 // bytes that should have trickled in while rationedCount was positive.
1606 // Rounding errors do not accumulate here, but we round down to avoid
1607 // negative bucket sizes after write with rationedCount=1.
1608 rationedQuota
= static_cast<int>(floor(bucketSize
/rationedCount
));
1609 debugs(77,5, HERE
<< "new rationedQuota: " << rationedQuota
<<
1610 '*' << rationedCount
);
1614 debugs(77,7, HERE
<< "rationedQuota: " << rationedQuota
<<
1615 " rations remaining: " << rationedCount
);
1617 // update 'last seen' time to prevent clientdb GC from dropping us
1618 last_seen
= squid_curtime
;
1619 return rationedQuota
;
1622 ///< adds bytes to the quota bucket based on the rate and passed time
1624 ClientInfo::refillBucket()
1626 // all these times are in seconds, with double precision
1627 const double currTime
= current_dtime
;
1628 const double timePassed
= currTime
- prevTime
;
1630 // Calculate allowance for the time passed. Use double to avoid
1631 // accumulating rounding errors for small intervals. For example, always
1632 // adding 1 byte instead of 1.4 results in 29% bandwidth allocation error.
1633 const double gain
= timePassed
* writeSpeedLimit
;
1635 debugs(77,5, HERE
<< currTime
<< " clt" << (const char*)hash
.key
<< ": " <<
1636 bucketSize
<< " + (" << timePassed
<< " * " << writeSpeedLimit
<<
1637 " = " << gain
<< ')');
1639 // to further combat error accumulation during micro updates,
1640 // quit before updating time if we cannot add at least one byte
1644 prevTime
= currTime
;
1646 // for "first" connections, drain initial fat before refilling but keep
1647 // updating prevTime to avoid bursts after the fat is gone
1648 if (bucketSize
> bucketSizeLimit
) {
1649 debugs(77,4, HERE
<< "not refilling while draining initial fat");
1655 // obey quota limits
1656 if (bucketSize
> bucketSizeLimit
)
1657 bucketSize
= bucketSizeLimit
;
1661 ClientInfo::setWriteLimiter(const int aWriteSpeedLimit
, const double anInitialBurst
, const double aHighWatermark
)
1663 debugs(77,5, HERE
<< "Write limits for " << (const char*)hash
.key
<<
1664 " speed=" << aWriteSpeedLimit
<< " burst=" << anInitialBurst
<<
1665 " highwatermark=" << aHighWatermark
);
1667 // set or possibly update traffic shaping parameters
1668 writeLimitingActive
= true;
1669 writeSpeedLimit
= aWriteSpeedLimit
;
1670 bucketSizeLimit
= aHighWatermark
;
1672 // but some members should only be set once for a newly activated bucket
1673 if (firstTimeConnection
) {
1674 firstTimeConnection
= false;
1676 assert(!selectWaiting
);
1677 assert(!quotaQueue
);
1678 quotaQueue
= new CommQuotaQueue(this);
1680 bucketSize
= anInitialBurst
;
1681 prevTime
= current_dtime
;
1685 CommQuotaQueue::CommQuotaQueue(ClientInfo
*info
): clientInfo(info
),
1691 CommQuotaQueue::~CommQuotaQueue()
1693 assert(!clientInfo
); // ClientInfo should clear this before destroying us
1696 /// places the given fd at the end of the queue; returns reservation ID
1698 CommQuotaQueue::enqueue(int fd
)
1700 debugs(77,5, HERE
<< "clt" << (const char*)clientInfo
->hash
.key
<<
1701 ": FD " << fd
<< " with qqid" << (ins
+1) << ' ' << fds
.size());
1706 /// removes queue head
1708 CommQuotaQueue::dequeue()
1710 assert(!fds
.empty());
1711 debugs(77,5, HERE
<< "clt" << (const char*)clientInfo
->hash
.key
<<
1712 ": FD " << fds
.front() << " with qqid" << (outs
+1) << ' ' <<
1720 * hm, this might be too general-purpose for all the places we'd
1724 ignoreErrno(int ierrno
)
1731 #if EAGAIN != EWOULDBLOCK
1754 commCloseAllSockets(void)
1759 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
1765 if (F
->type
!= FD_SOCKET
)
1768 if (F
->flags
.ipc
) /* don't close inter-process sockets */
1771 if (F
->timeoutHandler
!= NULL
) {
1772 AsyncCall::Pointer callback
= F
->timeoutHandler
;
1773 F
->timeoutHandler
= NULL
;
1774 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": Calling timeout handler");
1775 ScheduleCallHere(callback
);
1777 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": calling comm_reset_close()");
1778 old_comm_reset_close(fd
);
1784 AlreadyTimedOut(fde
*F
)
1789 if (F
->timeout
== 0)
1792 if (F
->timeout
> squid_curtime
)
1799 writeTimedOut(int fd
)
1801 if (!COMMIO_FD_WRITECB(fd
)->active())
1804 if ((squid_curtime
- fd_table
[fd
].writeStart
) < Config
.Timeout
.write
)
1815 AsyncCall::Pointer callback
;
1817 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
1820 if (writeTimedOut(fd
)) {
1821 // We have an active write callback and we are timed out
1822 debugs(5, 5, "checkTimeouts: FD " << fd
<< " auto write timeout");
1823 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
1824 COMMIO_FD_WRITECB(fd
)->finish(COMM_ERROR
, ETIMEDOUT
);
1825 } else if (AlreadyTimedOut(F
))
1828 debugs(5, 5, "checkTimeouts: FD " << fd
<< " Expired");
1830 if (F
->timeoutHandler
!= NULL
) {
1831 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Call timeout handler");
1832 callback
= F
->timeoutHandler
;
1833 F
->timeoutHandler
= NULL
;
1834 ScheduleCallHere(callback
);
1836 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Forcing comm_close()");
1842 void CommIO::Initialise()
1844 /* Initialize done pipe signal */
1846 if (pipe(DonePipe
)) {}
1847 DoneFD
= DonePipe
[1];
1848 DoneReadFD
= DonePipe
[0];
1849 fd_open(DoneReadFD
, FD_PIPE
, "async-io completetion event: main");
1850 fd_open(DoneFD
, FD_PIPE
, "async-io completetion event: threads");
1851 commSetNonBlocking(DoneReadFD
);
1852 commSetNonBlocking(DoneFD
);
1853 Comm::SetSelect(DoneReadFD
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
1857 void CommIO::NotifyIOClose()
1859 /* Close done pipe signal */
1864 fd_close(DoneReadFD
);
1865 Initialised
= false;
1868 bool CommIO::Initialised
= false;
1869 bool CommIO::DoneSignalled
= false;
1870 int CommIO::DoneFD
= -1;
1871 int CommIO::DoneReadFD
= -1;
1877 FD_READ_METHOD(DoneReadFD
, buf
, sizeof(buf
));
1881 CommIO::NULLFDHandler(int fd
, void *data
)
1884 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
1888 CommIO::ResetNotifications()
1890 if (DoneSignalled
) {
1892 DoneSignalled
= false;
1896 /// Start waiting for a possibly half-closed connection to close
1897 // by scheduling a read callback to a monitoring handler that
1898 // will close the connection on read errors.
1900 commStartHalfClosedMonitor(int fd
)
1902 debugs(5, 5, HERE
<< "adding FD " << fd
<< " to " << *TheHalfClosed
);
1904 assert(!commHasHalfClosedMonitor(fd
));
1905 (void)TheHalfClosed
->add(fd
); // could also assert the result
1906 commPlanHalfClosedCheck(); // may schedule check if we added the first FD
1911 commPlanHalfClosedCheck()
1913 if (!WillCheckHalfClosed
&& !TheHalfClosed
->empty()) {
1914 eventAdd("commHalfClosedCheck", &commHalfClosedCheck
, NULL
, 1.0, 1);
1915 WillCheckHalfClosed
= true;
1919 /// iterates over all descriptors that may need half-closed tests and
1920 /// calls comm_read for those that do; re-schedules the check if needed
1923 commHalfClosedCheck(void *)
1925 debugs(5, 5, HERE
<< "checking " << *TheHalfClosed
);
1927 typedef DescriptorSet::const_iterator DSCI
;
1928 const DSCI end
= TheHalfClosed
->end();
1929 for (DSCI i
= TheHalfClosed
->begin(); i
!= end
; ++i
) {
1930 Comm::ConnectionPointer c
= new Comm::Connection
; // XXX: temporary. make HalfClosed a list of these.
1932 if (!fd_table
[c
->fd
].halfClosedReader
) { // not reading already
1933 AsyncCall::Pointer call
= commCbCall(5,4, "commHalfClosedReader",
1934 CommIoCbPtrFun(&commHalfClosedReader
, NULL
));
1935 comm_read(c
, NULL
, 0, call
);
1936 fd_table
[c
->fd
].halfClosedReader
= call
;
1938 c
->fd
= -1; // XXX: temporary. prevent c replacement erase closing listed FD
1941 WillCheckHalfClosed
= false; // as far as we know
1942 commPlanHalfClosedCheck(); // may need to check again
1945 /// checks whether we are waiting for possibly half-closed connection to close
1946 // We are monitoring if the read handler for the fd is the monitoring handler.
1948 commHasHalfClosedMonitor(int fd
)
1950 return TheHalfClosed
->has(fd
);
1953 /// stop waiting for possibly half-closed connection to close
1955 commStopHalfClosedMonitor(int const fd
)
1957 debugs(5, 5, HERE
<< "removing FD " << fd
<< " from " << *TheHalfClosed
);
1959 // cancel the read if one was scheduled
1960 AsyncCall::Pointer reader
= fd_table
[fd
].halfClosedReader
;
1962 comm_read_cancel(fd
, reader
);
1963 fd_table
[fd
].halfClosedReader
= NULL
;
1965 TheHalfClosed
->del(fd
);
1968 /// I/O handler for the possibly half-closed connection monitoring code
1970 commHalfClosedReader(const Comm::ConnectionPointer
&conn
, char *, size_t size
, comm_err_t flag
, int, void *)
1972 // there cannot be more data coming in on half-closed connections
1974 assert(conn
!= NULL
);
1975 assert(commHasHalfClosedMonitor(conn
->fd
)); // or we would have canceled the read
1977 fd_table
[conn
->fd
].halfClosedReader
= NULL
; // done reading, for now
1979 // nothing to do if fd is being closed
1980 if (flag
== COMM_ERR_CLOSING
)
1983 // if read failed, close the connection
1984 if (flag
!= COMM_OK
) {
1985 debugs(5, 3, HERE
<< "closing " << conn
);
1990 // continue waiting for close or error
1991 commPlanHalfClosedCheck(); // make sure this fd will be checked again
1995 CommRead::CommRead() : conn(NULL
), buf(NULL
), len(0), callback(NULL
) {}
1997 CommRead::CommRead(const Comm::ConnectionPointer
&c
, char *buf_
, int len_
, AsyncCall::Pointer
&callback_
)
1998 : conn(c
), buf(buf_
), len(len_
), callback(callback_
) {}
2000 DeferredRead::DeferredRead () : theReader(NULL
), theContext(NULL
), theRead(), cancelled(false) {}
2002 DeferredRead::DeferredRead (DeferrableRead
*aReader
, void *data
, CommRead
const &aRead
) : theReader(aReader
), theContext (data
), theRead(aRead
), cancelled(false) {}
2004 DeferredReadManager::~DeferredReadManager()
2007 assert (deferredReads
.empty());
2010 /* explicit instantiation required for some systems */
2012 /// \cond AUTODOCS-IGNORE
2013 template cbdata_type CbDataList
<DeferredRead
>::CBDATA_CbDataList
;
2017 DeferredReadManager::delayRead(DeferredRead
const &aRead
)
2019 debugs(5, 3, "Adding deferred read on " << aRead
.theRead
.conn
);
2020 CbDataList
<DeferredRead
> *temp
= deferredReads
.push_back(aRead
);
2022 // We have to use a global function as a closer and point to temp
2023 // instead of "this" because DeferredReadManager is not a job and
2024 // is not even cbdata protected
2025 AsyncCall::Pointer closer
= commCbCall(5,4,
2026 "DeferredReadManager::CloseHandler",
2027 CommCloseCbPtrFun(&CloseHandler
, temp
));
2028 comm_add_close_handler(aRead
.theRead
.conn
->fd
, closer
);
2029 temp
->element
.closer
= closer
; // remeber so that we can cancel
2033 DeferredReadManager::CloseHandler(int fd
, void *thecbdata
)
2035 if (!cbdataReferenceValid (thecbdata
))
2038 CbDataList
<DeferredRead
> *temp
= (CbDataList
<DeferredRead
> *)thecbdata
;
2040 temp
->element
.closer
= NULL
;
2041 temp
->element
.markCancelled();
2045 DeferredReadManager::popHead(CbDataListContainer
<DeferredRead
> &deferredReads
)
2047 assert (!deferredReads
.empty());
2049 DeferredRead
&read
= deferredReads
.head
->element
;
2050 if (!read
.cancelled
) {
2051 comm_remove_close_handler(read
.theRead
.conn
->fd
, read
.closer
);
2055 DeferredRead result
= deferredReads
.pop_front();
2061 DeferredReadManager::kickReads(int const count
)
2063 /* if we had CbDataList::size() we could consolidate this and flushReads */
2070 size_t remaining
= count
;
2072 while (!deferredReads
.empty() && remaining
) {
2073 DeferredRead aRead
= popHead(deferredReads
);
2076 if (!aRead
.cancelled
)
2082 DeferredReadManager::flushReads()
2084 CbDataListContainer
<DeferredRead
> reads
;
2085 reads
= deferredReads
;
2086 deferredReads
= CbDataListContainer
<DeferredRead
>();
2088 // XXX: For fairness this SHOULD randomize the order
2089 while (!reads
.empty()) {
2090 DeferredRead aRead
= popHead(reads
);
2096 DeferredReadManager::kickARead(DeferredRead
const &aRead
)
2098 if (aRead
.cancelled
)
2101 if (Comm::IsConnOpen(aRead
.theRead
.conn
) && fd_table
[aRead
.theRead
.conn
->fd
].closing())
2104 debugs(5, 3, "Kicking deferred read on " << aRead
.theRead
.conn
);
2106 aRead
.theReader(aRead
.theContext
, aRead
.theRead
);
2110 DeferredRead::markCancelled()
2116 CommSelectEngine::checkEvents(int timeout
)
2118 static time_t last_timeout
= 0;
2120 /* No, this shouldn't be here. But it shouldn't be in each comm handler. -adrian */
2121 if (squid_curtime
> last_timeout
) {
2122 last_timeout
= squid_curtime
;
2126 switch (Comm::DoSelect(timeout
)) {
2142 fatal_dump("comm.cc: Internal error -- this should never happen.");
2147 /// Create a unix-domain socket (UDS) that only supports FD_MSGHDR I/O.
2149 comm_open_uds(int sock_type
,
2151 struct sockaddr_un
* addr
,
2154 // TODO: merge with comm_openex() when Ip::Address becomes NetAddress
2158 PROF_start(comm_open
);
2159 /* Create socket for accepting new connections. */
2160 statCounter
.syscalls
.sock
.sockets
++;
2162 /* Setup the socket addrinfo details for use */
2165 AI
.ai_family
= PF_UNIX
;
2166 AI
.ai_socktype
= sock_type
;
2167 AI
.ai_protocol
= proto
;
2168 AI
.ai_addrlen
= SUN_LEN(addr
);
2169 AI
.ai_addr
= (sockaddr
*)addr
;
2170 AI
.ai_canonname
= NULL
;
2173 debugs(50, 3, HERE
<< "Attempt open socket for: " << addr
->sun_path
);
2175 if ((new_socket
= socket(AI
.ai_family
, AI
.ai_socktype
, AI
.ai_protocol
)) < 0) {
2176 /* Increase the number of reserved fd's if calls to socket()
2177 * are failing because the open file table is full. This
2178 * limits the number of simultaneous clients */
2180 if (limitError(errno
)) {
2181 debugs(50, DBG_IMPORTANT
, HERE
<< "socket failure: " << xstrerror());
2184 debugs(50, DBG_CRITICAL
, HERE
<< "socket failure: " << xstrerror());
2187 PROF_stop(comm_open
);
2191 debugs(50, 3, HERE
"Opened UDS FD " << new_socket
<< " : family=" << AI
.ai_family
<< ", type=" << AI
.ai_socktype
<< ", protocol=" << AI
.ai_protocol
);
2194 debugs(50, 5, HERE
<< "FD " << new_socket
<< " is a new socket");
2196 assert(!isOpen(new_socket
));
2197 fd_open(new_socket
, FD_MSGHDR
, NULL
);
2199 fdd_table
[new_socket
].close_file
= NULL
;
2201 fdd_table
[new_socket
].close_line
= 0;
2203 fd_table
[new_socket
].sock_family
= AI
.ai_family
;
2205 if (!(flags
& COMM_NOCLOEXEC
))
2206 commSetCloseOnExec(new_socket
);
2208 if (flags
& COMM_REUSEADDR
)
2209 commSetReuseAddr(new_socket
);
2211 if (flags
& COMM_NONBLOCKING
) {
2212 if (commSetNonBlocking(new_socket
) != COMM_OK
) {
2213 comm_close(new_socket
);
2214 PROF_stop(comm_open
);
2219 if (flags
& COMM_DOBIND
) {
2220 if (commBind(new_socket
, AI
) != COMM_OK
) {
2221 comm_close(new_socket
);
2222 PROF_stop(comm_open
);
2228 if (sock_type
== SOCK_STREAM
)
2229 commSetTcpNoDelay(new_socket
);
2233 if (Config
.tcpRcvBufsz
> 0 && sock_type
== SOCK_STREAM
)
2234 commSetTcpRcvbuf(new_socket
, Config
.tcpRcvBufsz
);
2236 PROF_stop(comm_open
);