2 * DEBUG: section 5 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 "StoreIOBuffer.h"
42 #include "ConnectionDetail.h"
45 #include "SquidTime.h"
46 #include "CommCalls.h"
47 #include "DescriptorSet.h"
48 #include "icmp/net_db.h"
49 #include "ip/IpAddress.h"
50 #include "ip/IpIntercept.h"
52 #if defined(_SQUID_CYGWIN_)
53 #include <sys/ioctl.h>
55 #ifdef HAVE_NETINET_TCP_H
56 #include <netinet/tcp.h>
60 * New C-like simple comm code. This stuff is a mess and doesn't really buy us anything.
69 static void commStopHalfClosedMonitor(int fd
);
70 static IOCB commHalfClosedReader
;
73 struct comm_io_callback_t
{
76 AsyncCall::Pointer callback
;
84 bool active() const { return callback
!= NULL
; }
89 comm_io_callback_t readcb
;
90 comm_io_callback_t writecb
;
92 typedef struct _comm_fd comm_fd_t
;
93 comm_fd_t
*commfd_table
;
95 // TODO: make this a comm_io_callback_t method?
97 commio_has_callback(int fd
, iocb_type type
, comm_io_callback_t
*ccb
)
99 assert(ccb
->fd
== fd
);
100 assert(ccb
->type
== type
);
101 return ccb
->active();
105 * Configure comm_io_callback_t for I/O
107 * @param fd filedescriptor
108 * @param ccb comm io callback
110 * @param cbdata callback data (must be cbdata'ed)
111 * @param buf buffer, if applicable
112 * @param freefunc freefunc, if applicable
113 * @param size buffer size
116 commio_set_callback(int fd
, iocb_type type
, comm_io_callback_t
*ccb
,
117 AsyncCall::Pointer
&cb
, char *buf
, FREE
*freefunc
, int size
)
119 assert(!ccb
->active());
120 assert(ccb
->type
== type
);
125 ccb
->freefunc
= freefunc
;
131 // Schedule the callback call and clear the callback
133 commio_finish_callback(int fd
, comm_io_callback_t
*ccb
, comm_err_t code
, int xerrno
)
135 debugs(5, 3, "commio_finish_callback: called for FD " << fd
<< " (" <<
136 code
<< ", " << xerrno
<< ")");
137 assert(ccb
->active());
138 assert(ccb
->fd
== fd
);
140 ccb
->xerrno
= xerrno
;
142 comm_io_callback_t cb
= *ccb
;
144 /* We've got a copy; blow away the real one */
145 /* XXX duplicate code from commio_cancel_callback! */
147 ccb
->callback
= NULL
; // cb has it
155 if (cb
.callback
!= NULL
) {
156 typedef CommIoCbParams Params
;
157 Params
¶ms
= GetCommParams
<Params
>(cb
.callback
);
160 params
.size
= cb
.offset
;
161 params
.flag
= cb
.errcode
;
162 params
.xerrno
= cb
.xerrno
;
163 ScheduleCallHere(cb
.callback
);
169 * Cancel the given callback
171 * Remember that the data is cbdataRef'ed.
173 // TODO: make this a comm_io_callback_t method
175 commio_cancel_callback(int fd
, comm_io_callback_t
*ccb
)
177 debugs(5, 3, "commio_cancel_callback: called for FD " << fd
);
178 assert(ccb
->fd
== fd
);
179 assert(ccb
->active());
182 ccb
->callback
= NULL
;
186 * Call the given comm callback; assumes the callback is valid.
188 * @param ccb io completion callback
191 commio_call_callback(comm_io_callback_t
*ccb
)
195 class ConnectStateData
199 void *operator new (size_t);
200 void operator delete (void *);
201 static void Connect (int fd
, void *me
);
203 void callCallback(comm_err_t status
, int xerrno
);
206 // defaults given by client
208 u_short default_port
;
209 IpAddress default_addr
;
210 // NP: CANNOT store the default addr:port together as it gets set/reset differently.
212 DnsLookupDetails dns
; ///< host lookup details
214 AsyncCall::Pointer callback
;
223 int commRetryConnect();
224 CBDATA_CLASS(ConnectStateData
);
229 static DescriptorSet
*TheHalfClosed
= NULL
; /// the set of half-closed FDs
230 static bool WillCheckHalfClosed
= false; /// true if check is scheduled
231 static EVH commHalfClosedCheck
;
232 static void commPlanHalfClosedCheck();
234 static comm_err_t
commBind(int s
, struct addrinfo
&);
235 static void commSetReuseAddr(int);
236 static void commSetNoLinger(int);
238 static void commSetTcpNoDelay(int);
240 static void commSetTcpRcvbuf(int, int);
241 static PF commConnectFree
;
242 static PF commHandleWrite
;
243 static IPH commConnectDnsHandle
;
245 static PF comm_accept_try
;
251 AcceptFD(int aFd
= -1): fd(aFd
), theCallback(0), mayAcceptMore(false) {}
253 void subscribe(AsyncCall::Pointer
&call
);
255 void notify(int newfd
, comm_err_t
, int xerrno
, const ConnectionDetail
&);
262 AsyncCall::Pointer theCallback
;
272 char const *close_file
;
276 typedef struct _fd_debug_t fd_debug_t
;
278 static MemAllocator
*conn_close_pool
= NULL
;
279 AcceptFD
*fdc_table
= NULL
; // TODO: rename. And use Vector<>?
280 fd_debug_t
*fdd_table
= NULL
;
285 return fd_table
[fd
].flags
.open
!= 0;
291 * If the read attempt succeeds or fails, call the callback.
292 * Else, wait for another IO notification.
295 commHandleRead(int fd
, void *data
)
297 comm_io_callback_t
*ccb
= (comm_io_callback_t
*) data
;
299 assert(data
== COMMIO_FD_READCB(fd
));
300 assert(commio_has_callback(fd
, IOCB_READ
, ccb
));
302 statCounter
.syscalls
.sock
.reads
++;
305 retval
= FD_READ_METHOD(fd
, ccb
->buf
, ccb
->size
);
306 debugs(5, 3, "comm_read_try: FD " << fd
<< ", size " << ccb
->size
<< ", retval " << retval
<< ", errno " << errno
);
308 if (retval
< 0 && !ignoreErrno(errno
)) {
309 debugs(5, 3, "comm_read_try: scheduling COMM_ERROR");
311 commio_finish_callback(fd
, ccb
, COMM_ERROR
, errno
);
315 /* See if we read anything */
316 /* Note - read 0 == socket EOF, which is a valid read */
318 fd_bytes(fd
, retval
, FD_READ
);
319 ccb
->offset
= retval
;
320 commio_finish_callback(fd
, ccb
, COMM_OK
, errno
);
324 /* Nope, register for some more IO */
325 commSetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, data
, 0);
329 * Queue a read. handler/handler_data are called when the read
330 * completes, on error, or on file descriptor close.
333 comm_read(int fd
, char *buf
, int size
, IOCB
*handler
, void *handler_data
)
335 AsyncCall::Pointer call
= commCbCall(5,4, "SomeCommReadHandler",
336 CommIoCbPtrFun(handler
, handler_data
));
337 comm_read(fd
, buf
, size
, call
);
341 comm_read(int fd
, char *buf
, int size
, AsyncCall::Pointer
&callback
)
343 debugs(5, 5, "comm_read, queueing read for FD " << fd
<< "; asynCall " << callback
);
345 /* Make sure we are open and not closing */
347 assert(!fd_table
[fd
].closing());
348 comm_io_callback_t
*ccb
= COMMIO_FD_READCB(fd
);
350 // Make sure we are either not reading or just passively monitoring.
351 // Active/passive conflicts are OK and simply cancel passive monitoring.
353 // if the assertion below fails, we have an active comm_read conflict
354 assert(fd_table
[fd
].halfClosedReader
!= NULL
);
355 commStopHalfClosedMonitor(fd
);
356 assert(!ccb
->active());
360 commio_set_callback(fd
, IOCB_READ
, ccb
, callback
, (char *)buf
, NULL
, size
);
361 commSetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, ccb
, 0);
365 * Empty the read buffers
367 * This is a magical routine that empties the read buffers.
368 * Under some platforms (Linux) if a buffer has data in it before
369 * you call close(), the socket will hang and take quite a while
373 comm_empty_os_read_buffers(int fd
)
376 /* prevent those nasty RST packets */
377 char buf
[SQUID_TCP_SO_RCVBUF
];
379 if (fd_table
[fd
].flags
.nonblocking
== 1) {
380 while (FD_READ_METHOD(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0) {};
387 * Return whether the FD has a pending completed callback.
390 comm_has_pending_read_callback(int fd
)
393 // XXX: We do not know whether there is a read callback scheduled.
394 // This is used for pconn management that should probably be more
395 // tightly integrated into comm to minimize the chance that a
396 // closing pconn socket will be used for a new transaction.
400 // Does comm check this fd for read readiness?
401 // Note that when comm is not monitoring, there can be a pending callback
402 // call, which may resume comm monitoring once fired.
404 comm_monitors_read(int fd
)
407 // Being active is usually the same as monitoring because we always
408 // start monitoring the FD when we configure comm_io_callback_t for I/O
409 // and we usually configure comm_io_callback_t for I/O when we starting
410 // monitoring a FD for reading. TODO: replace with commio_has_callback
411 return COMMIO_FD_READCB(fd
)->active();
415 * Cancel a pending read. Assert that we have the right parameters,
416 * and that there are no pending read events!
418 * XXX: We do not assert that there are no pending read events and
419 * with async calls it becomes even more difficult.
420 * The whole interface should be reworked to do callback->cancel()
421 * instead of searching for places where the callback may be stored and
422 * updating the state of those places.
424 * AHC Don't call the comm handlers?
427 comm_read_cancel(int fd
, IOCB
*callback
, void *data
)
430 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
434 comm_io_callback_t
*cb
= COMMIO_FD_READCB(fd
);
435 // TODO: is "active" == "monitors FD"?
437 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
441 typedef CommCbFunPtrCallT
<CommIoCbPtrFun
> Call
;
442 Call
*call
= dynamic_cast<Call
*>(cb
->callback
.getRaw());
444 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " lacks callback");
448 call
->cancel("old comm_read_cancel");
450 typedef CommIoCbParams Params
;
451 const Params
¶ms
= GetCommParams
<Params
>(cb
->callback
);
453 /* Ok, we can be reasonably sure we won't lose any data here! */
454 assert(call
->dialer
.handler
== callback
);
455 assert(params
.data
== data
);
457 /* Delete the callback */
458 commio_cancel_callback(fd
, cb
);
460 /* And the IO event */
461 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
465 comm_read_cancel(int fd
, AsyncCall::Pointer
&callback
)
467 callback
->cancel("comm_read_cancel");
470 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
474 comm_io_callback_t
*cb
= COMMIO_FD_READCB(fd
);
477 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
481 AsyncCall::Pointer call
= cb
->callback
;
482 assert(call
!= NULL
); // XXX: should never fail (active() checks for callback==NULL)
484 /* Ok, we can be reasonably sure we won't lose any data here! */
485 assert(call
== callback
);
487 /* Delete the callback */
488 commio_cancel_callback(fd
, cb
);
490 /* And the IO event */
491 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
496 * synchronous wrapper around udp socket functions
499 comm_udp_recvfrom(int fd
, void *buf
, size_t len
, int flags
, IpAddress
&from
)
501 statCounter
.syscalls
.sock
.recvfroms
++;
503 struct addrinfo
*AI
= NULL
;
505 debugs(5,8, "comm_udp_recvfrom: FD " << fd
<< " from " << from
);
507 assert( NULL
== AI
);
509 from
.InitAddrInfo(AI
);
511 x
= recvfrom(fd
, buf
, len
, flags
, AI
->ai_addr
, &AI
->ai_addrlen
);
515 from
.FreeAddrInfo(AI
);
521 comm_udp_recv(int fd
, void *buf
, size_t len
, int flags
)
524 return comm_udp_recvfrom(fd
, buf
, len
, flags
, nul
);
528 comm_udp_send(int s
, const void *buf
, size_t len
, int flags
)
530 return send(s
, buf
, len
, flags
);
535 comm_has_incomplete_write(int fd
)
538 return COMMIO_FD_WRITECB(fd
)->active();
542 * Queue a write. handler/handler_data are called when the write fully
543 * completes, on error, or on file descriptor close.
546 /* Return the local port associated with fd. */
548 comm_local_port(int fd
)
551 struct addrinfo
*addr
= NULL
;
552 fde
*F
= &fd_table
[fd
];
554 /* If the fd is closed already, just return */
556 if (!F
->flags
.open
) {
557 debugs(5, 0, "comm_local_port: FD " << fd
<< " has been closed.");
561 if (F
->local_addr
.GetPort())
562 return F
->local_addr
.GetPort();
564 temp
.InitAddrInfo(addr
);
566 if (getsockname(fd
, addr
->ai_addr
, &(addr
->ai_addrlen
)) ) {
567 debugs(50, 1, "comm_local_port: Failed to retrieve TCP/UDP port number for socket: FD " << fd
<< ": " << xstrerror());
568 temp
.FreeAddrInfo(addr
);
573 temp
.FreeAddrInfo(addr
);
575 F
->local_addr
.SetPort(temp
.GetPort());
577 // grab default socket information for this address
578 temp
.GetAddrInfo(addr
);
580 F
->sock_family
= addr
->ai_family
;
582 temp
.FreeAddrInfo(addr
);
584 debugs(5, 6, "comm_local_port: FD " << fd
<< ": port " << F
->local_addr
.GetPort());
585 return F
->local_addr
.GetPort();
589 commBind(int s
, struct addrinfo
&inaddr
)
591 statCounter
.syscalls
.sock
.binds
++;
593 if (bind(s
, inaddr
.ai_addr
, inaddr
.ai_addrlen
) == 0)
596 debugs(50, 0, "commBind: Cannot bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
<< ": " << xstrerror());
602 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
603 * is OR of flags specified in comm.h. Defaults TOS
606 comm_open(int sock_type
,
612 return comm_openex(sock_type
, proto
, addr
, flags
, 0, note
);
616 comm_open_listener(int sock_type
,
624 /* attempt native enabled port. */
625 sock
= comm_openex(sock_type
, proto
, addr
, flags
, 0, note
);
628 /* under IPv6 there is the possibility IPv6 is present but disabled. */
629 /* try again as IPv4-native */
630 if ( sock
< 0 && addr
.IsIPv6() && addr
.SetIPv4() ) {
631 /* attempt to open this IPv4-only. */
632 sock
= comm_openex(sock_type
, proto
, addr
, flags
, 0, note
);
633 debugs(50, 2, HERE
<< "attempt open " << note
<< " socket on: " << addr
);
641 limitError(int const anErrno
)
643 return anErrno
== ENFILE
|| anErrno
== EMFILE
;
647 comm_set_tos(int fd
, int tos
)
650 int x
= setsockopt(fd
, IPPROTO_IP
, IP_TOS
, (char *) &tos
, sizeof(int));
652 debugs(50, 1, "comm_set_tos: setsockopt(IP_TOS) on FD " << fd
<< ": " << xstrerror());
655 debugs(50, 0, "WARNING: setsockopt(IP_TOS) not supported on this platform");
661 comm_set_v6only(int fd
, int tos
)
664 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (char *) &tos
, sizeof(int)) < 0) {
665 debugs(50, 1, "comm_open: setsockopt(IPV6_V6ONLY) on FD " << fd
<< ": " << xstrerror());
668 debugs(50, 0, "WARNING: comm_open: setsockopt(IPV6_V6ONLY) not supported on this platform");
673 * Set the socket IP_TRANSPARENT option for Linux TPROXY v4 support.
676 comm_set_transparent(int fd
)
678 #if defined(IP_TRANSPARENT)
680 if (setsockopt(fd
, SOL_IP
, IP_TRANSPARENT
, (char *) &tos
, sizeof(int)) < 0) {
681 debugs(50, DBG_IMPORTANT
, "comm_open: setsockopt(IP_TRANSPARENT) on FD " << fd
<< ": " << xstrerror());
683 /* mark the socket as having transparent options */
684 fd_table
[fd
].flags
.transparent
= 1;
687 debugs(50, DBG_CRITICAL
, "WARNING: comm_open: setsockopt(IP_TRANSPARENT) not supported on this platform");
692 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
693 * is OR of flags specified in defines.h:COMM_*
696 comm_openex(int sock_type
,
706 struct addrinfo
*AI
= NULL
;
708 PROF_start(comm_open
);
709 /* Create socket for accepting new connections. */
710 statCounter
.syscalls
.sock
.sockets
++;
712 /* Setup the socket addrinfo details for use */
713 addr
.GetAddrInfo(AI
);
714 AI
->ai_socktype
= sock_type
;
715 AI
->ai_protocol
= proto
;
717 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr
);
719 if ((new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
)) < 0) {
720 /* Increase the number of reserved fd's if calls to socket()
721 * are failing because the open file table is full. This
722 * limits the number of simultaneous clients */
724 if (limitError(errno
)) {
725 debugs(50, DBG_IMPORTANT
, "comm_open: socket failure: " << xstrerror());
728 debugs(50, DBG_CRITICAL
, "comm_open: socket failure: " << xstrerror());
731 addr
.FreeAddrInfo(AI
);
733 PROF_stop(comm_open
);
737 debugs(50, 3, "comm_openex: Opened socket FD " << new_socket
<< " : family=" << AI
->ai_family
<< ", type=" << AI
->ai_socktype
<< ", protocol=" << AI
->ai_protocol
);
739 /* set TOS if needed */
740 if (TOS
&& comm_set_tos(new_socket
, TOS
) ) {
744 #if IPV6_SPECIAL_SPLITSTACK
747 comm_set_v6only(new_socket
, tos
);
751 #if IPV6_SPECIAL_V4MAPPED
753 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
754 /* Other OS may have this administratively disabled for general use. Same deal. */
756 comm_set_v6only(new_socket
, 0);
761 debugs(5, 5, "comm_open: FD " << new_socket
<< " is a new socket");
763 assert(!isOpen(new_socket
));
764 fd_open(new_socket
, FD_SOCKET
, note
);
766 fdd_table
[new_socket
].close_file
= NULL
;
768 fdd_table
[new_socket
].close_line
= 0;
770 F
= &fd_table
[new_socket
];
772 F
->local_addr
= addr
;
776 F
->sock_family
= AI
->ai_family
;
778 if (!(flags
& COMM_NOCLOEXEC
))
779 commSetCloseOnExec(new_socket
);
781 if ((flags
& COMM_REUSEADDR
))
782 commSetReuseAddr(new_socket
);
784 if (addr
.GetPort() > (u_short
) 0) {
787 if (sock_type
!= SOCK_DGRAM
)
790 commSetNoLinger(new_socket
);
793 commSetReuseAddr(new_socket
);
796 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
797 if ((flags
& COMM_TRANSPARENT
)) {
798 comm_set_transparent(new_socket
);
801 if (!addr
.IsNoAddr()) {
802 if (commBind(new_socket
, *AI
) != COMM_OK
) {
803 comm_close(new_socket
);
804 addr
.FreeAddrInfo(AI
);
806 PROF_stop(comm_open
);
810 addr
.FreeAddrInfo(AI
);
812 if (flags
& COMM_NONBLOCKING
)
813 if (commSetNonBlocking(new_socket
) == COMM_ERROR
) {
815 PROF_stop(comm_open
);
819 if (sock_type
== SOCK_STREAM
)
820 commSetTcpNoDelay(new_socket
);
824 if (Config
.tcpRcvBufsz
> 0 && sock_type
== SOCK_STREAM
)
825 commSetTcpRcvbuf(new_socket
, Config
.tcpRcvBufsz
);
827 PROF_stop(comm_open
);
832 CBDATA_CLASS_INIT(ConnectStateData
);
835 ConnectStateData::operator new (size_t size
)
837 CBDATA_INIT_TYPE(ConnectStateData
);
838 return cbdataAlloc(ConnectStateData
);
842 ConnectStateData::operator delete (void *address
)
850 commConnectStart(int fd
, const char *host
, u_short port
, AsyncCall::Pointer
&cb
)
852 debugs(cb
->debugSection
, cb
->debugLevel
, "commConnectStart: FD " << fd
<<
853 ", cb " << cb
<< ", " << host
<< ":" << port
); // TODO: just print *cb
855 ConnectStateData
*cs
;
856 cs
= new ConnectStateData
;
858 cs
->host
= xstrdup(host
);
859 cs
->default_port
= port
;
862 comm_add_close_handler(fd
, commConnectFree
, cs
);
863 ipcache_nbgethostbyname(host
, commConnectDnsHandle
, cs
);
866 // TODO: Remove this and similar callback registration functions by replacing
867 // (callback,data) parameters with an AsyncCall so that we do not have to use
868 // a generic call name and debug level when creating an AsyncCall. This will
869 // also cut the number of callback registration routines in half.
871 commConnectStart(int fd
, const char *host
, u_short port
, CNCB
* callback
, void *data
)
873 debugs(5, 5, "commConnectStart: FD " << fd
<< ", data " << data
<< ", " << host
<< ":" << port
);
874 AsyncCall::Pointer call
= commCbCall(5,3,
875 "SomeCommConnectHandler", CommConnectCbPtrFun(callback
, data
));
876 commConnectStart(fd
, host
, port
, call
);
880 commConnectDnsHandle(const ipcache_addrs
*ia
, const DnsLookupDetails
&details
, void *data
)
882 ConnectStateData
*cs
= (ConnectStateData
*)data
;
886 debugs(5, 3, "commConnectDnsHandle: Unknown host: " << cs
->host
);
887 cs
->callCallback(COMM_ERR_DNS
, 0);
891 assert(ia
->cur
< ia
->count
);
893 cs
->default_addr
= ia
->in_addrs
[ia
->cur
];
895 if (Config
.onoff
.balance_on_multiple_ip
)
896 ipcacheCycleAddr(cs
->host
, NULL
);
898 cs
->addrcount
= ia
->count
;
900 cs
->connstart
= squid_curtime
;
906 ConnectStateData::callCallback(comm_err_t status
, int xerrno
)
908 debugs(5, 3, "commConnectCallback: FD " << fd
);
910 comm_remove_close_handler(fd
, commConnectFree
, this);
911 commSetTimeout(fd
, -1, NULL
, NULL
);
913 typedef CommConnectCbParams Params
;
914 Params
¶ms
= GetCommParams
<Params
>(callback
);
917 params
.flag
= status
;
918 params
.xerrno
= xerrno
;
919 ScheduleCallHere(callback
);
922 commConnectFree(fd
, this);
926 commConnectFree(int fd
, void *data
)
928 ConnectStateData
*cs
= (ConnectStateData
*)data
;
929 debugs(5, 3, "commConnectFree: FD " << fd
);
930 // delete cs->callback;
937 copyFDFlags(int to
, fde
*F
)
939 if (F
->flags
.close_on_exec
)
940 commSetCloseOnExec(to
);
942 if (F
->flags
.nonblocking
)
943 commSetNonBlocking(to
);
947 if (F
->flags
.nodelay
)
948 commSetTcpNoDelay(to
);
952 if (Config
.tcpRcvBufsz
> 0)
953 commSetTcpRcvbuf(to
, Config
.tcpRcvBufsz
);
956 /* Reset FD so that we can connect() again */
958 ConnectStateData::commResetFD()
960 struct addrinfo
*AI
= NULL
;
962 int new_family
= AF_UNSPEC
;
964 // XXX: do we have to check this?
966 // if (!cbdataReferenceValid(callback.data))
969 statCounter
.syscalls
.sock
.sockets
++;
971 /* setup a bare-bones addrinfo */
972 /* TODO INET6: for WinXP we may need to check the local_addr type and setup the family properly. */
974 new_family
= AI
->ai_family
;
976 int fd2
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
978 nul
.FreeAddrInfo(AI
);
981 debugs(5, DBG_CRITICAL
, HERE
<< "WARNING: FD " << fd2
<< " socket failed to allocate: " << xstrerror());
983 if (ENFILE
== errno
|| EMFILE
== errno
)
991 /* On Windows dup2() can't work correctly on Sockets, the */
992 /* workaround is to close the destination Socket before call them. */
997 if (dup2(fd2
, fd
) < 0) {
998 debugs(5, DBG_CRITICAL
, HERE
<< "WARNING: dup2(FD " << fd2
<< ", FD " << fd
<< ") failed: " << xstrerror());
1000 if (ENFILE
== errno
|| EMFILE
== errno
)
1007 commResetSelect(fd
);
1010 fde
*F
= &fd_table
[fd
];
1012 /* INET6: copy the new sockets family type to the FDE table */
1013 fd_table
[fd
].sock_family
= new_family
;
1015 fd_table
[fd
].flags
.called_connect
= 0;
1017 * yuck, this has assumptions about comm_open() arguments for
1018 * the original socket
1021 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
1022 if ( F
->flags
.transparent
) {
1023 comm_set_transparent(fd
);
1027 F
->local_addr
.GetAddrInfo(AI
);
1029 if (commBind(fd
, *AI
) != COMM_OK
) {
1030 debugs(5, DBG_CRITICAL
, "WARNING: Reset of FD " << fd
<< " for " << F
->local_addr
<< " failed to bind: " << xstrerror());
1031 F
->local_addr
.FreeAddrInfo(AI
);
1034 F
->local_addr
.FreeAddrInfo(AI
);
1037 comm_set_tos(fd
, F
->tos
);
1039 #if IPV6_SPECIAL_SPLITSTACK
1041 if ( F
->local_addr
.IsIPv6() )
1042 comm_set_v6only(fd
, F
->tos
);
1052 ConnectStateData::commRetryConnect()
1054 assert(addrcount
> 0);
1056 if (addrcount
== 1) {
1057 if (tries
>= Config
.retry
.maxtries
)
1060 if (squid_curtime
- connstart
> Config
.Timeout
.connect
)
1063 if (tries
> addrcount
)
1067 return commResetFD();
1071 commReconnect(void *data
)
1073 ConnectStateData
*cs
= (ConnectStateData
*)data
;
1074 ipcache_nbgethostbyname(cs
->host
, commConnectDnsHandle
, cs
);
1077 /** Connect SOCK to specified DEST_PORT at DEST_HOST. */
1079 ConnectStateData::Connect(int fd
, void *me
)
1081 ConnectStateData
*cs
= (ConnectStateData
*)me
;
1082 assert (cs
->fd
== fd
);
1087 ConnectStateData::defaults()
1090 S
.SetPort(default_port
);
1094 ConnectStateData::connect()
1099 debugs(5,5, HERE
<< "to " << S
);
1101 switch (comm_connect_addr(fd
, S
) ) {
1103 case COMM_INPROGRESS
:
1104 debugs(5, 5, HERE
<< "FD " << fd
<< ": COMM_INPROGRESS");
1105 commSetSelect(fd
, COMM_SELECT_WRITE
, ConnectStateData::Connect
, this, 0);
1109 debugs(5, 5, HERE
<< "FD " << fd
<< ": COMM_OK - connected");
1110 ipcacheMarkGoodAddr(host
, S
);
1111 callCallback(COMM_OK
, 0);
1115 case COMM_ERR_PROTOCOL
:
1116 /* problem using the desired protocol over this socket.
1117 * count the connection attempt, reset the socket, and immediately try again */
1125 debugs(5, 5, HERE
"FD " << fd
<< ": * - try again");
1127 ipcacheMarkBadAddr(host
, S
);
1130 if (Config
.onoff
.test_reachability
)
1131 netdbDeleteAddrNetwork(S
);
1134 if (commRetryConnect()) {
1135 eventAdd("commReconnect", commReconnect
, this, this->addrcount
== 1 ? 0.05 : 0.0, 0);
1137 debugs(5, 5, HERE
<< "FD " << fd
<< ": * - ERR tried too many times already.");
1138 callCallback(COMM_ERR_CONNECT
, errno
);
1144 commSetTimeout_old(int fd, int timeout, PF * handler, void *data)
1146 debugs(5, 3, HERE << "FD " << fd << " timeout " << timeout);
1148 assert(fd < Squid_MaxFD);
1149 fde *F = &fd_table[fd];
1150 assert(F->flags.open);
1153 cbdataReferenceDone(F->timeout_data);
1154 F->timeout_handler = NULL;
1158 cbdataReferenceDone(F->timeout_data);
1159 F->timeout_handler = handler;
1160 F->timeout_data = cbdataReference(data);
1163 F->timeout = squid_curtime + (time_t) timeout;
1171 commSetTimeout(int fd
, int timeout
, PF
* handler
, void *data
)
1173 AsyncCall::Pointer call
;
1174 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
1175 if (handler
!= NULL
)
1176 call
=commCbCall(5,4, "SomeTimeoutHandler", CommTimeoutCbPtrFun(handler
, data
));
1179 return commSetTimeout(fd
, timeout
, call
);
1183 int commSetTimeout(int fd
, int timeout
, AsyncCall::Pointer
&callback
)
1185 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
1187 assert(fd
< Squid_MaxFD
);
1188 fde
*F
= &fd_table
[fd
];
1189 assert(F
->flags
.open
);
1192 F
->timeoutHandler
= NULL
;
1195 if (callback
!= NULL
) {
1196 typedef CommTimeoutCbParams Params
;
1197 Params
¶ms
= GetCommParams
<Params
>(callback
);
1199 F
->timeoutHandler
= callback
;
1202 F
->timeout
= squid_curtime
+ (time_t) timeout
;
1210 comm_connect_addr(int sock
, const IpAddress
&address
)
1212 comm_err_t status
= COMM_OK
;
1213 fde
*F
= &fd_table
[sock
];
1217 struct addrinfo
*AI
= NULL
;
1218 PROF_start(comm_connect_addr
);
1220 assert(address
.GetPort() != 0);
1222 debugs(5, 9, "comm_connect_addr: connecting socket " << sock
<< " to " << address
<< " (want family: " << F
->sock_family
<< ")");
1224 /* BUG 2222 FIX: reset the FD when its found to be IPv4 in IPv6 mode */
1225 /* inverse case of IPv4 failing to connect on IPv6 socket is handeld post-connect.
1226 * this case must presently be handled here since the GetAddrInfo asserts on bad mappings.
1227 * eventually we want it to throw a Must() that gets handled there instead of this if.
1228 * NP: because commresetFD is private to ConnStateData we have to return an error and
1229 * trust its handled properly.
1232 if (F
->sock_family
== AF_INET
&& !address
.IsIPv4()) {
1233 return COMM_ERR_PROTOCOL
;
1237 address
.GetAddrInfo(AI
, F
->sock_family
);
1239 /* Establish connection. */
1242 if (!F
->flags
.called_connect
) {
1243 F
->flags
.called_connect
= 1;
1244 statCounter
.syscalls
.sock
.connects
++;
1246 x
= connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
1248 // XXX: ICAP code refuses callbacks during a pending comm_ call
1249 // Async calls development will fix this.
1252 errno
= EINPROGRESS
;
1256 debugs(5,5, "comm_connect_addr: sock=" << sock
<< ", addrinfo( " <<
1257 " flags=" << AI
->ai_flags
<<
1258 ", family=" << AI
->ai_family
<<
1259 ", socktype=" << AI
->ai_socktype
<<
1260 ", protocol=" << AI
->ai_protocol
<<
1261 ", &addr=" << AI
->ai_addr
<<
1262 ", addrlen=" << AI
->ai_addrlen
<<
1264 debugs(5, 9, "connect FD " << sock
<< ": (" << x
<< ") " << xstrerror());
1265 debugs(14,9, "connecting to: " << address
);
1268 #if defined(_SQUID_NEWSOS6_)
1269 /* Makoto MATSUSHITA <matusita@ics.es.osaka-u.ac.jp> */
1271 connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
1273 if (errno
== EINVAL
) {
1274 errlen
= sizeof(err
);
1275 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
1282 errlen
= sizeof(err
);
1284 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
1289 #if defined(_SQUID_SOLARIS_)
1291 * Solaris 2.4's socket emulation doesn't allow you
1292 * to determine the error from a failed non-blocking
1293 * connect and just returns EPIPE. Create a fake
1294 * error message for connect. -- fenner@parc.xerox.com
1296 if (x
< 0 && errno
== EPIPE
)
1304 /* Squid seems to be working fine without this code. With this code,
1305 * we leak memory on many connect requests because of EINPROGRESS.
1306 * If you find that this code is needed, please file a bug report. */
1308 #ifdef _SQUID_LINUX_
1310 * Linux Debian replaces our allocated AI pointer with garbage when
1311 * connect() fails. This leads to segmentation faults deallocating
1312 * the system-allocated memory when we go to clean up our pointer.
1313 * HACK: is to leak the memory returned since we can't deallocate.
1321 address
.FreeAddrInfo(AI
);
1323 PROF_stop(comm_connect_addr
);
1325 if (errno
== 0 || errno
== EISCONN
)
1327 else if (ignoreErrno(errno
))
1328 status
= COMM_INPROGRESS
;
1331 if ( address
.IsIPv4() && F
->sock_family
== AF_INET6
) {
1333 /* failover to trying IPv4-only link if an IPv6 one fails */
1334 /* to catch the edge case of apps listening on IPv4-localhost */
1335 F
->sock_family
= AF_INET
;
1336 int res
= comm_connect_addr(sock
, address
);
1338 /* if that fails too, undo our temporary socktype hack so the repeat works properly. */
1339 if (res
== COMM_ERROR
)
1340 F
->sock_family
= AF_INET6
;
1347 address
.NtoA(F
->ipaddr
, MAX_IPSTRLEN
);
1349 F
->remote_port
= address
.GetPort(); /* remote_port is HS */
1351 if (status
== COMM_OK
) {
1352 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connected to " << address
);
1353 } else if (status
== COMM_INPROGRESS
) {
1354 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connection pending");
1360 /* Wait for an incoming connection on FD. FD should be a socket returned
1361 * from comm_listen. */
1363 comm_old_accept(int fd
, ConnectionDetail
&details
)
1365 PROF_start(comm_accept
);
1366 statCounter
.syscalls
.sock
.accepts
++;
1368 struct addrinfo
*gai
= NULL
;
1369 details
.me
.InitAddrInfo(gai
);
1371 if ((sock
= accept(fd
, gai
->ai_addr
, &gai
->ai_addrlen
)) < 0) {
1373 details
.me
.FreeAddrInfo(gai
);
1375 PROF_stop(comm_accept
);
1377 if (ignoreErrno(errno
)) {
1378 debugs(50, 5, "comm_old_accept: FD " << fd
<< ": " << xstrerror());
1379 return COMM_NOMESSAGE
;
1380 } else if (ENFILE
== errno
|| EMFILE
== errno
) {
1381 debugs(50, 3, "comm_old_accept: FD " << fd
<< ": " << xstrerror());
1384 debugs(50, 1, "comm_old_accept: FD " << fd
<< ": " << xstrerror());
1389 details
.peer
= *gai
;
1391 details
.me
.InitAddrInfo(gai
);
1393 details
.me
.SetEmpty();
1394 getsockname(sock
, gai
->ai_addr
, &gai
->ai_addrlen
);
1397 commSetCloseOnExec(sock
);
1400 fd_open(sock
, FD_SOCKET
, "HTTP Request");
1401 fdd_table
[sock
].close_file
= NULL
;
1402 fdd_table
[sock
].close_line
= 0;
1403 fde
*F
= &fd_table
[sock
];
1404 details
.peer
.NtoA(F
->ipaddr
,MAX_IPSTRLEN
);
1405 F
->remote_port
= details
.peer
.GetPort();
1406 F
->local_addr
.SetPort(details
.me
.GetPort());
1408 F
->sock_family
= AF_INET
;
1410 F
->sock_family
= details
.me
.IsIPv4()?AF_INET
:AF_INET6
;
1412 details
.me
.FreeAddrInfo(gai
);
1414 commSetNonBlocking(sock
);
1416 /* IFF the socket is (tproxy) transparent, pass the flag down to allow spoofing */
1417 F
->flags
.transparent
= fd_table
[fd
].flags
.transparent
;
1419 PROF_stop(comm_accept
);
1424 commCallCloseHandlers(int fd
)
1426 fde
*F
= &fd_table
[fd
];
1427 debugs(5, 5, "commCallCloseHandlers: FD " << fd
);
1429 while (F
->closeHandler
!= NULL
) {
1430 AsyncCall::Pointer call
= F
->closeHandler
;
1431 F
->closeHandler
= call
->Next();
1432 call
->setNext(NULL
);
1433 // If call is not canceled schedule it for execution else ignore it
1434 if (!call
->canceled()) {
1435 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call
);
1436 typedef CommCloseCbParams Params
;
1437 Params
¶ms
= GetCommParams
<Params
>(call
);
1439 ScheduleCallHere(call
);
1446 commLingerClose(int fd
, void *unused
)
1448 LOCAL_ARRAY(char, buf
, 1024);
1450 n
= FD_READ_METHOD(fd
, buf
, 1024);
1453 debugs(5, 3, "commLingerClose: FD " << fd
<< " read: " << xstrerror());
1459 commLingerTimeout(int fd
, void *unused
)
1461 debugs(5, 3, "commLingerTimeout: FD " << fd
);
1466 * Inspired by apache
1469 comm_lingering_close(int fd
)
1473 if (fd_table
[fd
].ssl
)
1474 ssl_shutdown_method(fd
);
1478 if (shutdown(fd
, 1) < 0) {
1483 fd_note(fd
, "lingering close");
1484 commSetTimeout(fd
, 10, commLingerTimeout
, NULL
);
1485 commSetSelect(fd
, COMM_SELECT_READ
, commLingerClose
, NULL
, 0);
1491 * enable linger with time of 0 so that when the socket is
1492 * closed, TCP generates a RESET
1495 comm_reset_close(int fd
)
1502 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1503 debugs(50, 0, "commResetTCPClose: FD " << fd
<< ": " << xstrerror());
1509 comm_close_start(int fd
, void *data
)
1512 fde
*F
= &fd_table
[fd
];
1514 ssl_shutdown_method(fd
);
1522 comm_close_complete(int fd
, void *data
)
1525 fde
*F
= &fd_table
[fd
];
1533 fd_close(fd
); /* update fdstat */
1537 fdc_table
[fd
] = AcceptFD(fd
);
1539 statCounter
.syscalls
.sock
.closes
++;
1541 /* When an fd closes, give accept() a chance, if need be */
1543 if (fdNFree() >= RESERVED_FD
)
1544 AcceptLimiter::Instance().kick();
1549 * Close the socket fd.
1551 * + call write handlers with ERR_CLOSING
1552 * + call read handlers with ERR_CLOSING
1553 * + call closing handlers
1555 * NOTE: COMM_ERR_CLOSING will NOT be called for CommReads' sitting in a
1556 * DeferredReadManager.
1559 _comm_close(int fd
, char const *file
, int line
)
1561 debugs(5, 3, "comm_close: start closing FD " << fd
);
1563 assert(fd
< Squid_MaxFD
);
1565 fde
*F
= &fd_table
[fd
];
1566 fdd_table
[fd
].close_file
= file
;
1567 fdd_table
[fd
].close_line
= line
;
1572 /* XXX: is this obsolete behind F->closing() ? */
1573 if ( (shutting_down
|| reconfiguring
) && (!F
->flags
.open
|| F
->type
== FD_FILE
))
1576 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
1579 assert(F
->type
!= FD_FILE
);
1581 PROF_start(comm_close
);
1583 F
->flags
.close_request
= 1;
1585 AsyncCall::Pointer startCall
=commCbCall(5,4, "comm_close_start",
1586 CommCloseCbPtrFun(comm_close_start
, NULL
));
1587 typedef CommCloseCbParams Params
;
1588 Params
&startParams
= GetCommParams
<Params
>(startCall
);
1589 startParams
.fd
= fd
;
1590 ScheduleCallHere(startCall
);
1592 // a half-closed fd may lack a reader, so we stop monitoring explicitly
1593 if (commHasHalfClosedMonitor(fd
))
1594 commStopHalfClosedMonitor(fd
);
1595 commSetTimeout(fd
, -1, NULL
, NULL
);
1597 // notify read/write handlers
1598 if (commio_has_callback(fd
, IOCB_WRITE
, COMMIO_FD_WRITECB(fd
))) {
1599 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), COMM_ERR_CLOSING
, errno
);
1601 if (commio_has_callback(fd
, IOCB_READ
, COMMIO_FD_READCB(fd
))) {
1602 commio_finish_callback(fd
, COMMIO_FD_READCB(fd
), COMM_ERR_CLOSING
, errno
);
1605 // notify accept handlers
1606 fdc_table
[fd
].notify(-1, COMM_ERR_CLOSING
, 0, ConnectionDetail());
1608 commCallCloseHandlers(fd
);
1611 F
->pconn
.pool
->count(F
->pconn
.uses
);
1613 comm_empty_os_read_buffers(fd
);
1616 AsyncCall::Pointer completeCall
=commCbCall(5,4, "comm_close_complete",
1617 CommCloseCbPtrFun(comm_close_complete
, NULL
));
1618 Params
&completeParams
= GetCommParams
<Params
>(completeCall
);
1619 completeParams
.fd
= fd
;
1620 // must use async call to wait for all callbacks
1621 // scheduled before comm_close() to finish
1622 ScheduleCallHere(completeCall
);
1624 PROF_stop(comm_close
);
1627 /* Send a udp datagram to specified TO_ADDR. */
1629 comm_udp_sendto(int fd
,
1630 const IpAddress
&to_addr
,
1635 struct addrinfo
*AI
= NULL
;
1637 PROF_start(comm_udp_sendto
);
1638 statCounter
.syscalls
.sock
.sendtos
++;
1640 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr
<<
1641 " using FD " << fd
<< " using Port " << comm_local_port(fd
) );
1643 /* BUG: something in the above macro appears to occasionally be setting AI to garbage. */
1644 /* AYJ: 2007-08-27 : or was it because I wasn't then setting 'fd_table[fd].sock_family' to fill properly. */
1645 assert( NULL
== AI
);
1647 to_addr
.GetAddrInfo(AI
, fd_table
[fd
].sock_family
);
1649 x
= sendto(fd
, buf
, len
, 0, AI
->ai_addr
, AI
->ai_addrlen
);
1651 to_addr
.FreeAddrInfo(AI
);
1653 PROF_stop(comm_udp_sendto
);
1658 #ifdef _SQUID_LINUX_
1660 if (ECONNREFUSED
!= errno
)
1663 debugs(50, 1, "comm_udp_sendto: FD " << fd
<< ", (family=" << fd_table
[fd
].sock_family
<< ") " << to_addr
<< ": " << xstrerror());
1669 comm_add_close_handler(int fd
, PF
* handler
, void *data
)
1671 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", handler=" <<
1672 handler
<< ", data=" << data
);
1674 AsyncCall::Pointer call
=commCbCall(5,4, "SomeCloseHandler",
1675 CommCloseCbPtrFun(handler
, data
));
1676 comm_add_close_handler(fd
, call
);
1680 comm_add_close_handler(int fd
, AsyncCall::Pointer
&call
)
1682 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1684 /*TODO:Check for a similar scheduled AsyncCall*/
1685 // for (c = fd_table[fd].closeHandler; c; c = c->next)
1686 // assert(c->handler != handler || c->data != data);
1688 call
->setNext(fd_table
[fd
].closeHandler
);
1690 fd_table
[fd
].closeHandler
= call
;
1694 // remove function-based close handler
1696 comm_remove_close_handler(int fd
, PF
* handler
, void *data
)
1698 assert (isOpen(fd
));
1699 /* Find handler in list */
1700 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", handler=" <<
1701 handler
<< ", data=" << data
);
1703 AsyncCall::Pointer p
;
1704 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
; p
= p
->Next()) {
1705 typedef CommCbFunPtrCallT
<CommCloseCbPtrFun
> Call
;
1706 const Call
*call
= dynamic_cast<const Call
*>(p
.getRaw());
1707 if (!call
) // method callbacks have their own comm_remove_close_handler
1710 typedef CommCloseCbParams Params
;
1711 const Params
¶ms
= GetCommParams
<Params
>(p
);
1712 if (call
->dialer
.handler
== handler
&& params
.data
== data
)
1713 break; /* This is our handler */
1716 // comm_close removes all close handlers so our handler may be gone
1718 p
->cancel("comm_remove_close_handler");
1719 // TODO: should we remove the handler from the close handlers list?
1722 // remove method-based close handler
1724 comm_remove_close_handler(int fd
, AsyncCall::Pointer
&call
)
1726 assert (isOpen(fd
));
1727 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1729 // comm_close removes all close handlers so our handler may be gone
1730 // TODO: should we remove the handler from the close handlers list?
1732 // Check to see if really exist the given AsyncCall in comm_close handlers
1733 // TODO: optimize: this slow code is only needed for the assert() below
1734 AsyncCall::Pointer p
;
1735 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
&& p
!= call
; p
= p
->Next());
1739 call
->cancel("comm_remove_close_handler");
1743 commSetNoLinger(int fd
)
1747 L
.l_onoff
= 0; /* off */
1750 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1751 debugs(50, 0, "commSetNoLinger: FD " << fd
<< ": " << xstrerror());
1753 fd_table
[fd
].flags
.nolinger
= 1;
1757 commSetReuseAddr(int fd
)
1761 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &on
, sizeof(on
)) < 0)
1762 debugs(50, 1, "commSetReuseAddr: FD " << fd
<< ": " << xstrerror());
1766 commSetTcpRcvbuf(int fd
, int size
)
1768 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, (char *) &size
, sizeof(size
)) < 0)
1769 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1770 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, (char *) &size
, sizeof(size
)) < 0)
1771 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1772 #ifdef TCP_WINDOW_CLAMP
1773 if (setsockopt(fd
, SOL_TCP
, TCP_WINDOW_CLAMP
, (char *) &size
, sizeof(size
)) < 0)
1774 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1779 commSetNonBlocking(int fd
)
1781 #ifndef _SQUID_MSWIN_
1785 #ifdef _SQUID_WIN32_
1787 int nonblocking
= TRUE
;
1789 #ifdef _SQUID_CYGWIN_
1791 if (fd_table
[fd
].type
!= FD_PIPE
) {
1794 if (ioctl(fd
, FIONBIO
, &nonblocking
) < 0) {
1795 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror() << " " << fd_table
[fd
].type
);
1799 #ifdef _SQUID_CYGWIN_
1804 #ifndef _SQUID_MSWIN_
1806 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1807 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1811 if (fcntl(fd
, F_SETFL
, flags
| SQUID_NONBLOCK
) < 0) {
1812 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror());
1817 #ifdef _SQUID_CYGWIN_
1822 fd_table
[fd
].flags
.nonblocking
= 1;
1828 commUnsetNonBlocking(int fd
)
1830 #ifdef _SQUID_MSWIN_
1831 int nonblocking
= FALSE
;
1833 if (ioctlsocket(fd
, FIONBIO
, (unsigned long *) &nonblocking
) < 0) {
1838 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1839 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1843 if (fcntl(fd
, F_SETFL
, flags
& (~SQUID_NONBLOCK
)) < 0) {
1845 debugs(50, 0, "commUnsetNonBlocking: FD " << fd
<< ": " << xstrerror());
1849 fd_table
[fd
].flags
.nonblocking
= 0;
1854 commSetCloseOnExec(int fd
) {
1859 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1860 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1864 if (fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) < 0)
1865 debugs(50, 0, "FD " << fd
<< ": set close-on-exec failed: " << xstrerror());
1867 fd_table
[fd
].flags
.close_on_exec
= 1;
1874 commSetTcpNoDelay(int fd
) {
1877 if (setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *) &on
, sizeof(on
)) < 0)
1878 debugs(50, 1, "commSetTcpNoDelay: FD " << fd
<< ": " << xstrerror());
1880 fd_table
[fd
].flags
.nodelay
= 1;
1886 commSetTcpKeepalive(int fd
, int idle
, int interval
, int timeout
) {
1889 if (timeout
&& interval
) {
1890 int count
= (timeout
+ interval
- 1) / interval
;
1891 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPCNT
, &count
, sizeof(on
)) < 0)
1892 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1897 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, &idle
, sizeof(on
)) < 0)
1898 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1901 #ifdef TCP_KEEPINTVL
1903 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, &interval
, sizeof(on
)) < 0)
1904 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1907 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char *) &on
, sizeof(on
)) < 0)
1908 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1913 fd_table
=(fde
*) xcalloc(Squid_MaxFD
, sizeof(fde
));
1914 fdd_table
= (fd_debug_t
*)xcalloc(Squid_MaxFD
, sizeof(fd_debug_t
));
1916 fdc_table
= new AcceptFD
[Squid_MaxFD
];
1917 for (int pos
= 0; pos
< Squid_MaxFD
; ++pos
) {
1918 fdc_table
[pos
] = AcceptFD(pos
);
1921 commfd_table
= (comm_fd_t
*) xcalloc(Squid_MaxFD
, sizeof(comm_fd_t
));
1922 for (int pos
= 0; pos
< Squid_MaxFD
; pos
++) {
1923 commfd_table
[pos
].fd
= pos
;
1924 commfd_table
[pos
].readcb
.fd
= pos
;
1925 commfd_table
[pos
].readcb
.type
= IOCB_READ
;
1926 commfd_table
[pos
].writecb
.fd
= pos
;
1927 commfd_table
[pos
].writecb
.type
= IOCB_WRITE
;
1930 /* XXX account fd_table */
1931 /* Keep a few file descriptors free so that we don't run out of FD's
1932 * after accepting a client but before it opens a socket or a file.
1933 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
1934 RESERVED_FD
= min(100, Squid_MaxFD
/ 4);
1936 conn_close_pool
= memPoolCreate("close_handler", sizeof(close_handler
));
1938 TheHalfClosed
= new DescriptorSet
;
1943 delete TheHalfClosed
;
1944 TheHalfClosed
= NULL
;
1946 safe_free(fd_table
);
1947 safe_free(fdd_table
);
1952 safe_free(commfd_table
);
1957 commHandleWrite(int fd
, void *data
) {
1958 comm_io_callback_t
*state
= (comm_io_callback_t
*)data
;
1962 assert(state
== COMMIO_FD_WRITECB(fd
));
1964 PROF_start(commHandleWrite
);
1965 debugs(5, 5, "commHandleWrite: FD " << fd
<< ": off " <<
1966 (long int) state
->offset
<< ", sz " << (long int) state
->size
<< ".");
1968 nleft
= state
->size
- state
->offset
;
1969 len
= FD_WRITE_METHOD(fd
, state
->buf
+ state
->offset
, nleft
);
1970 debugs(5, 5, "commHandleWrite: write() returns " << len
);
1971 fd_bytes(fd
, len
, FD_WRITE
);
1972 statCounter
.syscalls
.sock
.writes
++;
1975 /* Note we even call write if nleft == 0 */
1979 debugs(5, 1, "commHandleWrite: FD " << fd
<< ": write failure: connection closed with " << nleft
<< " bytes remaining.");
1981 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1982 } else if (len
< 0) {
1985 if (fd_table
[fd
].flags
.socket_eof
) {
1986 debugs(50, 2, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1987 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1988 } else if (ignoreErrno(errno
)) {
1989 debugs(50, 10, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1996 debugs(50, 2, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1997 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
2000 /* A successful write, continue */
2001 state
->offset
+= len
;
2003 if (state
->offset
< state
->size
) {
2004 /* Not done, reinstall the write handler and write some more */
2011 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_OK
: COMM_ERROR
, errno
);
2015 PROF_stop(commHandleWrite
);
2019 * Queue a write. handler/handler_data are called when the write
2020 * completes, on error, or on file descriptor close.
2022 * free_func is used to free the passed buffer when the write has completed.
2025 comm_write(int fd
, const char *buf
, int size
, IOCB
* handler
, void *handler_data
, FREE
* free_func
) {
2026 AsyncCall::Pointer call
= commCbCall(5,5, "SomeCommWriteHander",
2027 CommIoCbPtrFun(handler
, handler_data
));
2029 comm_write(fd
, buf
, size
, call
, free_func
);
2033 comm_write(int fd
, const char *buf
, int size
, AsyncCall::Pointer
&callback
, FREE
* free_func
) {
2034 debugs(5, 5, "comm_write: FD " << fd
<< ": sz " << size
<< ": asynCall " << callback
);
2036 /* Make sure we are open, not closing, and not writing */
2038 assert(!fd_table
[fd
].closing());
2039 comm_io_callback_t
*ccb
= COMMIO_FD_WRITECB(fd
);
2040 assert(!ccb
->active());
2042 /* Queue the write */
2043 commio_set_callback(fd
, IOCB_WRITE
, ccb
, callback
,
2044 (char *)buf
, free_func
, size
);
2045 commSetSelect(fd
, COMM_SELECT_WRITE
, commHandleWrite
, ccb
, 0);
2049 /* a wrapper around comm_write to allow for MemBuf to be comm_written in a snap */
2051 comm_write_mbuf(int fd
, MemBuf
*mb
, IOCB
* handler
, void *handler_data
) {
2052 comm_write(fd
, mb
->buf
, mb
->size
, handler
, handler_data
, mb
->freeFunc());
2056 comm_write_mbuf(int fd
, MemBuf
*mb
, AsyncCall::Pointer
&callback
) {
2057 comm_write(fd
, mb
->buf
, mb
->size
, callback
, mb
->freeFunc());
2062 * hm, this might be too general-purpose for all the places we'd
2066 ignoreErrno(int ierrno
) {
2072 #if EAGAIN != EWOULDBLOCK
2095 commCloseAllSockets(void) {
2099 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
2105 if (F
->type
!= FD_SOCKET
)
2108 if (F
->flags
.ipc
) /* don't close inter-process sockets */
2111 if (F
->timeoutHandler
!= NULL
) {
2112 AsyncCall::Pointer callback
= F
->timeoutHandler
;
2113 F
->timeoutHandler
= NULL
;
2114 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": Calling timeout handler");
2115 ScheduleCallHere(callback
);
2117 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": calling comm_close()");
2124 AlreadyTimedOut(fde
*F
) {
2128 if (F
->timeout
== 0)
2131 if (F
->timeout
> squid_curtime
)
2138 checkTimeouts(void) {
2141 AsyncCall::Pointer callback
;
2143 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
2146 if (AlreadyTimedOut(F
))
2149 debugs(5, 5, "checkTimeouts: FD " << fd
<< " Expired");
2151 if (F
->timeoutHandler
!= NULL
) {
2152 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Call timeout handler");
2153 callback
= F
->timeoutHandler
;
2154 F
->timeoutHandler
= NULL
;
2155 ScheduleCallHere(callback
);
2157 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Forcing comm_close()");
2164 * New-style listen and accept routines
2166 * Listen simply registers our interest in an FD for listening,
2167 * and accept takes a callback to call when an FD has been
2171 comm_listen(int sock
) {
2174 if ((x
= listen(sock
, Squid_MaxFD
>> 2)) < 0) {
2175 debugs(50, 0, "comm_listen: listen(" << (Squid_MaxFD
>> 2) << ", " << sock
<< "): " << xstrerror());
2179 if (Config
.accept_filter
&& strcmp(Config
.accept_filter
, "none") != 0) {
2180 #ifdef SO_ACCEPTFILTER
2181 struct accept_filter_arg afa
;
2182 bzero(&afa
, sizeof(afa
));
2183 debugs(5, DBG_CRITICAL
, "Installing accept filter '" << Config
.accept_filter
<< "' on FD " << sock
);
2184 xstrncpy(afa
.af_name
, Config
.accept_filter
, sizeof(afa
.af_name
));
2185 x
= setsockopt(sock
, SOL_SOCKET
, SO_ACCEPTFILTER
, &afa
, sizeof(afa
));
2187 debugs(5, 0, "SO_ACCEPTFILTER '" << Config
.accept_filter
<< "': '" << xstrerror());
2188 #elif defined(TCP_DEFER_ACCEPT)
2190 if (strncmp(Config
.accept_filter
, "data=", 5) == 0)
2191 seconds
= atoi(Config
.accept_filter
+ 5);
2192 x
= setsockopt(sock
, IPPROTO_TCP
, TCP_DEFER_ACCEPT
, &seconds
, sizeof(seconds
));
2194 debugs(5, 0, "TCP_DEFER_ACCEPT '" << Config
.accept_filter
<< "': '" << xstrerror());
2196 debugs(5, 0, "accept_filter not supported on your OS");
2204 comm_accept(int fd
, IOACB
*handler
, void *handler_data
) {
2205 debugs(5, 5, "comm_accept: FD " << fd
<< " handler: " << (void*)handler
);
2208 AsyncCall::Pointer call
= commCbCall(5,5, "SomeCommAcceptHandler",
2209 CommAcceptCbPtrFun(handler
, handler_data
));
2210 fdc_table
[fd
].subscribe(call
);
2214 comm_accept(int fd
, AsyncCall::Pointer
&call
) {
2215 debugs(5, 5, "comm_accept: FD " << fd
<< " AsyncCall: " << call
);
2218 fdc_table
[fd
].subscribe(call
);
2221 // Called when somebody wants to be notified when our socket accepts new
2222 // connection. We do not probe the FD until there is such interest.
2224 AcceptFD::subscribe(AsyncCall::Pointer
&call
) {
2225 /* make sure we're not pending! */
2226 assert(!theCallback
);
2230 mayAcceptMore
= true; // even if we failed to accept last time
2236 commSetSelect(fd
, COMM_SELECT_READ
, comm_accept_try
, NULL
, 0);
2240 AcceptFD::acceptOne() {
2241 // If there is no callback and we accept, we will leak the accepted FD.
2242 // When we are running out of FDs, there is often no callback.
2244 debugs(5, 5, "AcceptFD::acceptOne orphaned: FD " << fd
);
2245 // XXX: can we remove this and similar "just in case" calls and
2246 // either listen always or listen only when there is a callback?
2247 if (!AcceptLimiter::Instance().deferring())
2248 commSetSelect(fd
, COMM_SELECT_READ
, comm_accept_try
, NULL
, 0);
2253 * We don't worry about running low on FDs here. Instead,
2254 * httpAccept() will use AcceptLimiter if we reach the limit
2258 /* Accept a new connection */
2259 ConnectionDetail connDetails
;
2260 int newfd
= comm_old_accept(fd
, connDetails
);
2262 /* Check for errors */
2265 assert(theCallback
!= NULL
);
2267 if (newfd
== COMM_NOMESSAGE
) {
2268 /* register interest again */
2269 debugs(5, 5, HERE
<< "try later: FD " << fd
<<
2270 " handler: " << *theCallback
);
2271 commSetSelect(fd
, COMM_SELECT_READ
, comm_accept_try
, NULL
, 0);
2275 // A non-recoverable error; notify the caller */
2276 notify(-1, COMM_ERROR
, errno
, connDetails
);
2280 assert(theCallback
!= NULL
);
2281 debugs(5, 5, "AcceptFD::acceptOne accepted: FD " << fd
<<
2282 " newfd: " << newfd
<< " from: " << connDetails
.peer
<<
2283 " handler: " << *theCallback
);
2284 notify(newfd
, COMM_OK
, 0, connDetails
);
2289 AcceptFD::acceptNext() {
2290 mayAcceptMore
= acceptOne();
2294 AcceptFD::notify(int newfd
, comm_err_t errcode
, int xerrno
, const ConnectionDetail
&connDetails
) {
2295 if (theCallback
!= NULL
) {
2296 typedef CommAcceptCbParams Params
;
2297 Params
¶ms
= GetCommParams
<Params
>(theCallback
);
2300 params
.details
= connDetails
;
2301 params
.flag
= errcode
;
2302 params
.xerrno
= xerrno
;
2303 ScheduleCallHere(theCallback
);
2309 * This callback is called whenever a filedescriptor is ready
2310 * to dupe itself and fob off an accept()ed connection
2313 comm_accept_try(int fd
, void *) {
2315 fdc_table
[fd
].acceptNext();
2318 void CommIO::Initialise() {
2319 /* Initialize done pipe signal */
2321 if (pipe(DonePipe
)) {}
2322 DoneFD
= DonePipe
[1];
2323 DoneReadFD
= DonePipe
[0];
2324 fd_open(DoneReadFD
, FD_PIPE
, "async-io completetion event: main");
2325 fd_open(DoneFD
, FD_PIPE
, "async-io completetion event: threads");
2326 commSetNonBlocking(DoneReadFD
);
2327 commSetNonBlocking(DoneFD
);
2328 commSetSelect(DoneReadFD
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
2332 void CommIO::NotifyIOClose() {
2333 /* Close done pipe signal */
2338 fd_close(DoneReadFD
);
2339 Initialised
= false;
2342 bool CommIO::Initialised
= false;
2343 bool CommIO::DoneSignalled
= false;
2344 int CommIO::DoneFD
= -1;
2345 int CommIO::DoneReadFD
= -1;
2348 CommIO::FlushPipe() {
2350 FD_READ_METHOD(DoneReadFD
, buf
, sizeof(buf
));
2354 CommIO::NULLFDHandler(int fd
, void *data
) {
2356 commSetSelect(fd
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
2360 CommIO::ResetNotifications() {
2361 if (DoneSignalled
) {
2363 DoneSignalled
= false;
2367 AcceptLimiter
AcceptLimiter::Instance_
;
2369 AcceptLimiter
&AcceptLimiter::Instance() {
2374 AcceptLimiter::deferring() const {
2375 return deferred
.size() > 0;
2379 AcceptLimiter::defer (int fd
, Acceptor::AcceptorFunction
*aFunc
, void *data
) {
2380 debugs(5, 5, "AcceptLimiter::defer: FD " << fd
<< " handler: " << (void*)aFunc
);
2382 temp
.theFunction
= aFunc
;
2384 temp
.theData
= data
;
2385 deferred
.push_back(temp
);
2389 AcceptLimiter::kick() {
2393 /* Yes, this means the first on is the last off....
2394 * If the list container was a little more friendly, we could sensibly us it.
2396 Acceptor temp
= deferred
.pop_back();
2398 comm_accept (temp
.acceptFD
, temp
.theFunction
, temp
.theData
);
2401 /// Start waiting for a possibly half-closed connection to close
2402 // by scheduling a read callback to a monitoring handler that
2403 // will close the connection on read errors.
2405 commStartHalfClosedMonitor(int fd
) {
2406 debugs(5, 5, HERE
<< "adding FD " << fd
<< " to " << *TheHalfClosed
);
2408 assert(!commHasHalfClosedMonitor(fd
));
2409 (void)TheHalfClosed
->add(fd
); // could also assert the result
2410 commPlanHalfClosedCheck(); // may schedule check if we added the first FD
2415 commPlanHalfClosedCheck() {
2416 if (!WillCheckHalfClosed
&& !TheHalfClosed
->empty()) {
2417 eventAdd("commHalfClosedCheck", &commHalfClosedCheck
, NULL
, 1.0, 1);
2418 WillCheckHalfClosed
= true;
2422 /// iterates over all descriptors that may need half-closed tests and
2423 /// calls comm_read for those that do; re-schedules the check if needed
2426 commHalfClosedCheck(void *) {
2427 debugs(5, 5, HERE
<< "checking " << *TheHalfClosed
);
2429 typedef DescriptorSet::const_iterator DSCI
;
2430 const DSCI end
= TheHalfClosed
->end();
2431 for (DSCI i
= TheHalfClosed
->begin(); i
!= end
; ++i
) {
2433 if (!fd_table
[fd
].halfClosedReader
) { // not reading already
2434 AsyncCall::Pointer call
= commCbCall(5,4, "commHalfClosedReader",
2435 CommIoCbPtrFun(&commHalfClosedReader
, NULL
));
2436 comm_read(fd
, NULL
, 0, call
);
2437 fd_table
[fd
].halfClosedReader
= call
;
2441 WillCheckHalfClosed
= false; // as far as we know
2442 commPlanHalfClosedCheck(); // may need to check again
2445 /// checks whether we are waiting for possibly half-closed connection to close
2446 // We are monitoring if the read handler for the fd is the monitoring handler.
2448 commHasHalfClosedMonitor(int fd
) {
2449 return TheHalfClosed
->has(fd
);
2452 /// stop waiting for possibly half-closed connection to close
2454 commStopHalfClosedMonitor(int const fd
) {
2455 debugs(5, 5, HERE
<< "removing FD " << fd
<< " from " << *TheHalfClosed
);
2457 // cancel the read if one was scheduled
2458 AsyncCall::Pointer reader
= fd_table
[fd
].halfClosedReader
;
2460 comm_read_cancel(fd
, reader
);
2461 fd_table
[fd
].halfClosedReader
= NULL
;
2463 TheHalfClosed
->del(fd
);
2466 /// I/O handler for the possibly half-closed connection monitoring code
2468 commHalfClosedReader(int fd
, char *, size_t size
, comm_err_t flag
, int, void *) {
2469 // there cannot be more data coming in on half-closed connections
2471 assert(commHasHalfClosedMonitor(fd
)); // or we would have canceled the read
2473 fd_table
[fd
].halfClosedReader
= NULL
; // done reading, for now
2475 // nothing to do if fd is being closed
2476 if (flag
== COMM_ERR_CLOSING
)
2479 // if read failed, close the connection
2480 if (flag
!= COMM_OK
) {
2481 debugs(5, 3, "commHalfClosedReader: closing FD " << fd
);
2486 // continue waiting for close or error
2487 commPlanHalfClosedCheck(); // make sure this fd will be checked again
2491 CommRead::CommRead() : fd(-1), buf(NULL
), len(0), callback(NULL
) {}
2493 CommRead::CommRead(int fd_
, char *buf_
, int len_
, AsyncCall::Pointer
&callback_
)
2494 : fd(fd_
), buf(buf_
), len(len_
), callback(callback_
) {}
2496 DeferredRead::DeferredRead () : theReader(NULL
), theContext(NULL
), theRead(), cancelled(false) {}
2498 DeferredRead::DeferredRead (DeferrableRead
*aReader
, void *data
, CommRead
const &aRead
) : theReader(aReader
), theContext (data
), theRead(aRead
), cancelled(false) {}
2500 DeferredReadManager::~DeferredReadManager() {
2502 assert (deferredReads
.empty());
2505 /* explicit instantiation required for some systems */
2507 /// \cond AUTODOCS-IGNORE
2508 template cbdata_type CbDataList
<DeferredRead
>::CBDATA_CbDataList
;
2512 DeferredReadManager::delayRead(DeferredRead
const &aRead
) {
2513 debugs(5, 3, "Adding deferred read on FD " << aRead
.theRead
.fd
);
2514 CbDataList
<DeferredRead
> *temp
= deferredReads
.push_back(aRead
);
2516 // We have to use a global function as a closer and point to temp
2517 // instead of "this" because DeferredReadManager is not a job and
2518 // is not even cbdata protected
2519 AsyncCall::Pointer closer
= commCbCall(5,4,
2520 "DeferredReadManager::CloseHandler",
2521 CommCloseCbPtrFun(&CloseHandler
, temp
));
2522 comm_add_close_handler(aRead
.theRead
.fd
, closer
);
2523 temp
->element
.closer
= closer
; // remeber so that we can cancel
2527 DeferredReadManager::CloseHandler(int fd
, void *thecbdata
) {
2528 if (!cbdataReferenceValid (thecbdata
))
2531 CbDataList
<DeferredRead
> *temp
= (CbDataList
<DeferredRead
> *)thecbdata
;
2533 temp
->element
.closer
= NULL
;
2534 temp
->element
.markCancelled();
2538 DeferredReadManager::popHead(CbDataListContainer
<DeferredRead
> &deferredReads
) {
2539 assert (!deferredReads
.empty());
2541 DeferredRead
&read
= deferredReads
.head
->element
;
2542 if (!read
.cancelled
) {
2543 comm_remove_close_handler(read
.theRead
.fd
, read
.closer
);
2547 DeferredRead result
= deferredReads
.pop_front();
2553 DeferredReadManager::kickReads(int const count
) {
2554 /* if we had CbDataList::size() we could consolidate this and flushReads */
2561 size_t remaining
= count
;
2563 while (!deferredReads
.empty() && remaining
) {
2564 DeferredRead aRead
= popHead(deferredReads
);
2567 if (!aRead
.cancelled
)
2573 DeferredReadManager::flushReads() {
2574 CbDataListContainer
<DeferredRead
> reads
;
2575 reads
= deferredReads
;
2576 deferredReads
= CbDataListContainer
<DeferredRead
>();
2578 // XXX: For fairness this SHOULD randomize the order
2579 while (!reads
.empty()) {
2580 DeferredRead aRead
= popHead(reads
);
2586 DeferredReadManager::kickARead(DeferredRead
const &aRead
) {
2587 if (aRead
.cancelled
)
2590 if (aRead
.theRead
.fd
>=0 && fd_table
[aRead
.theRead
.fd
].closing())
2593 debugs(5, 3, "Kicking deferred read on FD " << aRead
.theRead
.fd
);
2595 aRead
.theReader(aRead
.theContext
, aRead
.theRead
);
2599 DeferredRead::markCancelled() {
2603 ConnectionDetail::ConnectionDetail() : me(), peer() {
2607 CommSelectEngine::checkEvents(int timeout
) {
2608 static time_t last_timeout
= 0;
2610 /* No, this shouldn't be here. But it shouldn't be in each comm handler. -adrian */
2611 if (squid_curtime
> last_timeout
) {
2612 last_timeout
= squid_curtime
;
2616 switch (comm_select(timeout
)) {
2632 fatal_dump("comm.cc: Internal error -- this should never happen.");