3 * $Id: comm.cc,v 1.447 2008/02/26 21:49:34 amosjeffries Exp $
5 * DEBUG: section 5 Socket Functions
6 * AUTHOR: Harvest Derived
8 * SQUID Web Proxy Cache http://www.squid-cache.org/
9 * ----------------------------------------------------------
11 * Squid is the result of efforts by numerous individuals from
12 * the Internet community; see the CONTRIBUTORS file for full
13 * details. Many organizations have provided support for Squid's
14 * development; see the SPONSORS file for full details. Squid is
15 * Copyrighted (C) 2001 by the Regents of the University of
16 * California; see the COPYRIGHT file for full details. Squid
17 * incorporates software developed and/or copyrighted by other
18 * sources; see the CREDITS file for full details.
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
35 * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org>
39 #include "StoreIOBuffer.h"
45 #include "ConnectionDetail.h"
48 #include "SquidTime.h"
49 #include "CommCalls.h"
50 #include "IPAddress.h"
51 #include "IPInterception.h"
52 #include "DescriptorSet.h"
53 #include "icmp/net_db.h"
55 #if defined(_SQUID_CYGWIN_)
56 #include <sys/ioctl.h>
58 #ifdef HAVE_NETINET_TCP_H
59 #include <netinet/tcp.h>
63 * New C-like simple comm code. This stuff is a mess and doesn't really buy us anything.
72 static void commStopHalfClosedMonitor(int fd
);
73 static IOCB commHalfClosedReader
;
76 struct comm_io_callback_t
{
79 AsyncCall::Pointer callback
;
87 bool active() const { return callback
!= NULL
; }
92 comm_io_callback_t readcb
;
93 comm_io_callback_t writecb
;
95 typedef struct _comm_fd comm_fd_t
;
96 comm_fd_t
*commfd_table
;
98 // TODO: make this a comm_io_callback_t method?
100 commio_has_callback(int fd
, iocb_type type
, comm_io_callback_t
*ccb
)
102 assert(ccb
->fd
== fd
);
103 assert(ccb
->type
== type
);
104 return ccb
->active();
108 * Configure comm_io_callback_t for I/O
110 * @param fd filedescriptor
111 * @param ccb comm io callback
113 * @param cbdata callback data (must be cbdata'ed)
114 * @param buf buffer, if applicable
115 * @param freefunc freefunc, if applicable
116 * @param size buffer size
119 commio_set_callback(int fd
, iocb_type type
, comm_io_callback_t
*ccb
,
120 AsyncCall::Pointer
&cb
, char *buf
, FREE
*freefunc
, int size
)
122 assert(!ccb
->active());
123 assert(ccb
->type
== type
);
128 ccb
->freefunc
= freefunc
;
134 // Schedule the callback call and clear the callback
136 commio_finish_callback(int fd
, comm_io_callback_t
*ccb
, comm_err_t code
, int xerrno
)
138 debugs(5, 3, "commio_finish_callback: called for FD " << fd
<< " (" <<
139 code
<< ", " << xerrno
<< ")");
140 assert(ccb
->active());
141 assert(ccb
->fd
== fd
);
143 ccb
->xerrno
= xerrno
;
145 comm_io_callback_t cb
= *ccb
;
147 /* We've got a copy; blow away the real one */
148 /* XXX duplicate code from commio_cancel_callback! */
150 ccb
->callback
= NULL
; // cb has it
158 if (cb
.callback
!= NULL
) {
159 typedef CommIoCbParams Params
;
160 Params
¶ms
= GetCommParams
<Params
>(cb
.callback
);
163 params
.size
= cb
.offset
;
164 params
.flag
= cb
.errcode
;
165 params
.xerrno
= cb
.xerrno
;
166 ScheduleCallHere(cb
.callback
);
172 * Cancel the given callback
174 * Remember that the data is cbdataRef'ed.
176 // TODO: make this a comm_io_callback_t method
178 commio_cancel_callback(int fd
, comm_io_callback_t
*ccb
)
180 debugs(5, 3, "commio_cancel_callback: called for FD " << fd
);
181 assert(ccb
->fd
== fd
);
182 assert(ccb
->active());
185 ccb
->callback
= NULL
;
189 * Call the given comm callback; assumes the callback is valid.
191 * @param ccb io completion callback
194 commio_call_callback(comm_io_callback_t
*ccb
)
198 class ConnectStateData
202 void *operator new (size_t);
203 void operator delete (void *);
204 static void Connect (int fd
, void *me
);
206 void callCallback(comm_err_t status
, int xerrno
);
209 // defaults given by client
211 u_short default_port
;
212 IPAddress default_addr
;
213 // NP: CANNOT store the default addr:port together as it gets set/reset differently.
216 AsyncCall::Pointer callback
;
225 int commRetryConnect();
226 CBDATA_CLASS(ConnectStateData
);
231 static DescriptorSet
*TheHalfClosed
= NULL
; /// the set of half-closed FDs
232 static bool WillCheckHalfClosed
= false; /// true if check is scheduled
233 static EVH commHalfClosedCheck
;
234 static void commPlanHalfClosedCheck();
236 static comm_err_t
commBind(int s
, struct addrinfo
&);
237 static void commSetReuseAddr(int);
238 static void commSetNoLinger(int);
240 static void commSetTcpNoDelay(int);
242 static void commSetTcpRcvbuf(int, int);
243 static PF commConnectFree
;
244 static PF commHandleWrite
;
245 static IPH commConnectDnsHandle
;
247 static PF comm_accept_try
;
253 AcceptFD(int aFd
= -1): fd(aFd
), theCallback(0), mayAcceptMore(false) {}
255 void subscribe(AsyncCall::Pointer
&call
);
257 void notify(int newfd
, comm_err_t
, int xerrno
, const ConnectionDetail
&);
264 AsyncCall::Pointer theCallback
;
275 char const *close_file
;
279 typedef struct _fd_debug_t fd_debug_t
;
281 static MemAllocator
*conn_close_pool
= NULL
;
282 AcceptFD
*fdc_table
= NULL
; // TODO: rename. And use Vector<>?
283 fd_debug_t
*fdd_table
= NULL
;
288 return fd_table
[fd
].flags
.open
!= 0;
294 * If the read attempt succeeds or fails, call the callback.
295 * Else, wait for another IO notification.
298 commHandleRead(int fd
, void *data
)
300 comm_io_callback_t
*ccb
= (comm_io_callback_t
*) data
;
302 assert(data
== COMMIO_FD_READCB(fd
));
303 assert(commio_has_callback(fd
, IOCB_READ
, ccb
));
305 statCounter
.syscalls
.sock
.reads
++;
308 retval
= FD_READ_METHOD(fd
, ccb
->buf
, ccb
->size
);
309 debugs(5, 3, "comm_read_try: FD " << fd
<< ", size " << ccb
->size
<< ", retval " << retval
<< ", errno " << errno
);
311 if (retval
< 0 && !ignoreErrno(errno
)) {
312 debugs(5, 3, "comm_read_try: scheduling COMM_ERROR");
314 commio_finish_callback(fd
, ccb
, COMM_ERROR
, errno
);
318 /* See if we read anything */
319 /* Note - read 0 == socket EOF, which is a valid read */
321 fd_bytes(fd
, retval
, FD_READ
);
322 ccb
->offset
= retval
;
323 commio_finish_callback(fd
, ccb
, COMM_OK
, errno
);
327 /* Nope, register for some more IO */
328 commSetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, data
, 0);
332 * Queue a read. handler/handler_data are called when the read
333 * completes, on error, or on file descriptor close.
336 comm_read(int fd
, char *buf
, int size
, IOCB
*handler
, void *handler_data
)
338 AsyncCall::Pointer call
= commCbCall(5,4, "SomeCommReadHandler",
339 CommIoCbPtrFun(handler
, handler_data
));
340 comm_read(fd
, buf
, size
, call
);
344 comm_read(int fd
, char *buf
, int size
, AsyncCall::Pointer
&callback
)
346 debugs(5, 5, "comm_read, queueing read for FD " << fd
<< "; asynCall " << callback
);
348 /* Make sure we are open and not closing */
350 assert(!fd_table
[fd
].closing());
351 comm_io_callback_t
*ccb
= COMMIO_FD_READCB(fd
);
353 // Make sure we are either not reading or just passively monitoring.
354 // Active/passive conflicts are OK and simply cancel passive monitoring.
356 // if the assertion below fails, we have an active comm_read conflict
357 assert(fd_table
[fd
].halfClosedReader
!= NULL
);
358 commStopHalfClosedMonitor(fd
);
359 assert(!ccb
->active());
363 commio_set_callback(fd
, IOCB_READ
, ccb
, callback
, (char *)buf
, NULL
, size
);
364 commSetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, ccb
, 0);
368 * Empty the read buffers
370 * This is a magical routine that empties the read buffers.
371 * Under some platforms (Linux) if a buffer has data in it before
372 * you call close(), the socket will hang and take quite a while
376 comm_empty_os_read_buffers(int fd
)
379 /* prevent those nasty RST packets */
380 char buf
[SQUID_TCP_SO_RCVBUF
];
382 if (fd_table
[fd
].flags
.nonblocking
== 1) {
383 while (FD_READ_METHOD(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0) {};
390 * Return whether the FD has a pending completed callback.
393 comm_has_pending_read_callback(int fd
)
396 // XXX: We do not know whether there is a read callback scheduled.
397 // This is used for pconn management that should probably be more
398 // tightly integrated into comm to minimize the chance that a
399 // closing pconn socket will be used for a new transaction.
403 // Does comm check this fd for read readiness?
404 // Note that when comm is not monitoring, there can be a pending callback
405 // call, which may resume comm monitoring once fired.
407 comm_monitors_read(int fd
)
410 // Being active is usually the same as monitoring because we always
411 // start monitoring the FD when we configure comm_io_callback_t for I/O
412 // and we usually configure comm_io_callback_t for I/O when we starting
413 // monitoring a FD for reading. TODO: replace with commio_has_callback
414 return COMMIO_FD_READCB(fd
)->active();
418 * Cancel a pending read. Assert that we have the right parameters,
419 * and that there are no pending read events!
421 * XXX: We do not assert that there are no pending read events and
422 * with async calls it becomes even more difficult.
423 * The whole interface should be reworked to do callback->cancel()
424 * instead of searching for places where the callback may be stored and
425 * updating the state of those places.
427 * AHC Don't call the comm handlers?
430 comm_read_cancel(int fd
, IOCB
*callback
, void *data
)
433 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
437 comm_io_callback_t
*cb
= COMMIO_FD_READCB(fd
);
438 // TODO: is "active" == "monitors FD"?
440 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
444 typedef CommCbFunPtrCallT
<CommIoCbPtrFun
> Call
;
445 Call
*call
= dynamic_cast<Call
*>(cb
->callback
.getRaw());
447 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " lacks callback");
451 call
->cancel("old comm_read_cancel");
453 typedef CommIoCbParams Params
;
454 const Params
¶ms
= GetCommParams
<Params
>(cb
->callback
);
456 /* Ok, we can be reasonably sure we won't lose any data here! */
457 assert(call
->dialer
.handler
== callback
);
458 assert(params
.data
== data
);
460 /* Delete the callback */
461 commio_cancel_callback(fd
, cb
);
463 /* And the IO event */
464 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
468 comm_read_cancel(int fd
, AsyncCall::Pointer
&callback
)
470 callback
->cancel("comm_read_cancel");
473 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
477 comm_io_callback_t
*cb
= COMMIO_FD_READCB(fd
);
480 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
484 AsyncCall::Pointer call
= cb
->callback
;
485 assert(call
!= NULL
); // XXX: should never fail (active() checks for callback==NULL)
487 /* Ok, we can be reasonably sure we won't lose any data here! */
488 assert(call
== callback
);
490 /* Delete the callback */
491 commio_cancel_callback(fd
, cb
);
493 /* And the IO event */
494 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
499 * synchronous wrapper around udp socket functions
502 comm_udp_recvfrom(int fd
, void *buf
, size_t len
, int flags
, IPAddress
&from
)
504 statCounter
.syscalls
.sock
.recvfroms
++;
506 struct addrinfo
*AI
= NULL
;
508 debugs(5,8, "comm_udp_recvfrom: FD " << fd
<< " from " << from
);
510 assert( NULL
== AI
);
512 from
.InitAddrInfo(AI
);
514 x
= recvfrom(fd
, buf
, len
, flags
, AI
->ai_addr
, &AI
->ai_addrlen
);
518 from
.FreeAddrInfo(AI
);
524 comm_udp_recv(int fd
, void *buf
, size_t len
, int flags
)
527 return comm_udp_recvfrom(fd
, buf
, len
, flags
, nul
);
531 comm_udp_send(int s
, const void *buf
, size_t len
, int flags
)
533 return send(s
, buf
, len
, flags
);
538 comm_has_incomplete_write(int fd
)
541 return COMMIO_FD_WRITECB(fd
)->active();
545 * Queue a write. handler/handler_data are called when the write fully
546 * completes, on error, or on file descriptor close.
549 /* Return the local port associated with fd. */
551 comm_local_port(int fd
)
554 struct addrinfo
*addr
= NULL
;
555 fde
*F
= &fd_table
[fd
];
557 /* If the fd is closed already, just return */
559 if (!F
->flags
.open
) {
560 debugs(5, 0, "comm_local_port: FD " << fd
<< " has been closed.");
564 if (F
->local_addr
.GetPort())
565 return F
->local_addr
.GetPort();
567 temp
.InitAddrInfo(addr
);
569 if (getsockname(fd
, addr
->ai_addr
, &(addr
->ai_addrlen
)) ) {
570 debugs(50, 1, "comm_local_port: Failed to retrieve TCP/UDP port number for socket: FD " << fd
<< ": " << xstrerror());
571 temp
.FreeAddrInfo(addr
);
576 temp
.FreeAddrInfo(addr
);
578 F
->local_addr
.SetPort(temp
.GetPort());
580 // grab default socket information for this address
581 temp
.GetAddrInfo(addr
);
583 F
->sock_family
= addr
->ai_family
;
585 temp
.FreeAddrInfo(addr
);
587 debugs(5, 6, "comm_local_port: FD " << fd
<< ": port " << F
->local_addr
.GetPort());
588 return F
->local_addr
.GetPort();
592 commBind(int s
, struct addrinfo
&inaddr
)
594 statCounter
.syscalls
.sock
.binds
++;
596 if (bind(s
, inaddr
.ai_addr
, inaddr
.ai_addrlen
) == 0)
599 debugs(50, 0, "commBind: Cannot bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
<< ": " << xstrerror());
605 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
606 * is OR of flags specified in comm.h. Defaults TOS
609 comm_open(int sock_type
,
615 return comm_openex(sock_type
, proto
, addr
, flags
, 0, note
);
619 limitError(int const anErrno
)
621 return anErrno
== ENFILE
|| anErrno
== EMFILE
;
625 comm_set_tos(int fd
, int tos
)
628 int x
= setsockopt(fd
, IPPROTO_IP
, IP_TOS
, (char *) &tos
, sizeof(int));
630 debugs(50, 1, "comm_set_tos: setsockopt(IP_TOS) on FD " << fd
<< ": " << xstrerror());
633 debugs(50, 0, "WARNING: setsockopt(IP_TOS) not supported on this platform");
639 comm_set_v6only(int fd
, int tos
)
642 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (char *) &tos
, sizeof(int)) < 0) {
643 debugs(50, 1, "comm_open: setsockopt(IPV6_V6ONLY) on FD " << fd
<< ": " << xstrerror());
646 debugs(50, 0, "WARNING: comm_open: setsockopt(IPV6_V6ONLY) not supported on this platform");
651 * Set the socket IP_TRANSPARENT option for Linux TPROXY v4 support.
654 comm_set_transparent(int fd
)
656 #if defined(IP_TRANSPARENT)
658 if (setsockopt(fd
, SOL_IP
, IP_TRANSPARENT
, (char *) &tos
, sizeof(int)) < 0) {
659 debugs(50, DBG_IMPORTANT
, "comm_open: setsockopt(IP_TRANSPARENT) on FD " << fd
<< ": " << xstrerror());
662 /* mark the socket as having transparent options */
663 fd_table
[fd
].flags
.transparent
= 1;
666 debugs(50, DBG_CRITICAL
, "WARNING: comm_open: setsockopt(IP_TRANSPARENT) not supported on this platform");
671 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
672 * is OR of flags specified in defines.h:COMM_*
675 comm_openex(int sock_type
,
685 struct addrinfo
*AI
= NULL
;
687 PROF_start(comm_open
);
688 /* Create socket for accepting new connections. */
689 statCounter
.syscalls
.sock
.sockets
++;
691 /* Setup the socket addrinfo details for use */
692 addr
.GetAddrInfo(AI
);
693 AI
->ai_socktype
= sock_type
;
694 AI
->ai_protocol
= proto
;
696 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr
);
698 if ((new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
)) < 0)
700 /* Increase the number of reserved fd's if calls to socket()
701 * are failing because the open file table is full. This
702 * limits the number of simultaneous clients */
704 if (limitError(errno
)) {
705 debugs(50, DBG_IMPORTANT
, "comm_open: socket failure: " << xstrerror());
708 debugs(50, DBG_CRITICAL
, "comm_open: socket failure: " << xstrerror());
711 addr
.FreeAddrInfo(AI
);
713 PROF_stop(comm_open
);
717 debugs(50, 3, "comm_openex: Opened socket FD " << new_socket
<< " : family=" << AI
->ai_family
<< ", type=" << AI
->ai_socktype
<< ", protocol=" << AI
->ai_protocol
);
719 /* set TOS if needed */
720 if (TOS
&& comm_set_tos(new_socket
, TOS
) ) {
724 #if IPV6_SPECIAL_SPLITSTACK
727 comm_set_v6only(new_socket
, tos
);
731 #if IPV6_SPECIAL_V4MAPPED
733 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
734 /* Other OS may have this administratively disabled for general use. Same deal. */
736 comm_set_v6only(new_socket
, 0);
741 debugs(5, 5, "comm_open: FD " << new_socket
<< " is a new socket");
743 assert(!isOpen(new_socket
));
744 fd_open(new_socket
, FD_SOCKET
, note
);
746 fdd_table
[new_socket
].close_file
= NULL
;
748 fdd_table
[new_socket
].close_line
= 0;
750 F
= &fd_table
[new_socket
];
752 F
->local_addr
= addr
;
756 F
->sock_family
= AI
->ai_family
;
758 if (!(flags
& COMM_NOCLOEXEC
))
759 commSetCloseOnExec(new_socket
);
761 if ((flags
& COMM_REUSEADDR
))
762 commSetReuseAddr(new_socket
);
764 if (addr
.GetPort() > (u_short
) 0)
768 if (sock_type
!= SOCK_DGRAM
)
771 commSetNoLinger(new_socket
);
774 commSetReuseAddr(new_socket
);
777 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
778 if((flags
& COMM_TRANSPARENT
)) {
779 comm_set_transparent(new_socket
);
782 if (!addr
.IsNoAddr())
784 if (commBind(new_socket
, *AI
) != COMM_OK
) {
785 comm_close(new_socket
);
786 addr
.FreeAddrInfo(AI
);
788 PROF_stop(comm_open
);
792 addr
.FreeAddrInfo(AI
);
794 if (flags
& COMM_NONBLOCKING
)
795 if (commSetNonBlocking(new_socket
) == COMM_ERROR
)
798 PROF_stop(comm_open
);
802 if (sock_type
== SOCK_STREAM
)
803 commSetTcpNoDelay(new_socket
);
807 if (Config
.tcpRcvBufsz
> 0 && sock_type
== SOCK_STREAM
)
808 commSetTcpRcvbuf(new_socket
, Config
.tcpRcvBufsz
);
810 PROF_stop(comm_open
);
815 CBDATA_CLASS_INIT(ConnectStateData
);
818 ConnectStateData::operator new (size_t size
)
820 CBDATA_INIT_TYPE(ConnectStateData
);
821 return cbdataAlloc(ConnectStateData
);
825 ConnectStateData::operator delete (void *address
)
833 commConnectStart(int fd
, const char *host
, u_short port
, AsyncCall::Pointer
&cb
)
835 debugs(cb
->debugSection
, cb
->debugLevel
, "commConnectStart: FD " << fd
<<
836 ", cb " << cb
<< ", " << host
<< ":" << port
); // TODO: just print *cb
838 ConnectStateData
*cs
;
839 cs
= new ConnectStateData
;
841 cs
->host
= xstrdup(host
);
842 cs
->default_port
= port
;
845 comm_add_close_handler(fd
, commConnectFree
, cs
);
846 ipcache_nbgethostbyname(host
, commConnectDnsHandle
, cs
);
849 // TODO: Remove this and similar callback registration functions by replacing
850 // (callback,data) parameters with an AsyncCall so that we do not have to use
851 // a generic call name and debug level when creating an AsyncCall. This will
852 // also cut the number of callback registration routines in half.
854 commConnectStart(int fd
, const char *host
, u_short port
, CNCB
* callback
, void *data
)
856 debugs(5, 5, "commConnectStart: FD " << fd
<< ", data " << data
<< ", " << host
<< ":" << port
);
857 AsyncCall::Pointer call
= commCbCall(5,3,
858 "SomeCommConnectHandler", CommConnectCbPtrFun(callback
, data
));
859 commConnectStart(fd
, host
, port
, call
);
863 commConnectDnsHandle(const ipcache_addrs
* ia
, void *data
)
865 ConnectStateData
*cs
= (ConnectStateData
*)data
;
868 debugs(5, 3, "commConnectDnsHandle: Unknown host: " << cs
->host
);
870 if (!dns_error_message
) {
871 dns_error_message
= "Unknown DNS error";
872 debugs(5, 1, "commConnectDnsHandle: Bad dns_error_message");
875 assert(dns_error_message
!= NULL
);
876 cs
->callCallback(COMM_ERR_DNS
, 0);
880 assert(ia
->cur
< ia
->count
);
882 cs
->default_addr
= ia
->in_addrs
[ia
->cur
];
884 if (Config
.onoff
.balance_on_multiple_ip
)
885 ipcacheCycleAddr(cs
->host
, NULL
);
887 cs
->addrcount
= ia
->count
;
889 cs
->connstart
= squid_curtime
;
895 ConnectStateData::callCallback(comm_err_t status
, int xerrno
)
897 debugs(5, 3, "commConnectCallback: FD " << fd
);
899 comm_remove_close_handler(fd
, commConnectFree
, this);
900 commSetTimeout(fd
, -1, NULL
, NULL
);
902 typedef CommConnectCbParams Params
;
903 Params
¶ms
= GetCommParams
<Params
>(callback
);
905 params
.flag
= status
;
906 params
.xerrno
= xerrno
;
907 ScheduleCallHere(callback
);
910 commConnectFree(fd
, this);
914 commConnectFree(int fd
, void *data
)
916 ConnectStateData
*cs
= (ConnectStateData
*)data
;
917 debugs(5, 3, "commConnectFree: FD " << fd
);
918 // delete cs->callback;
925 copyFDFlags(int to
, fde
*F
)
927 if (F
->flags
.close_on_exec
)
928 commSetCloseOnExec(to
);
930 if (F
->flags
.nonblocking
)
931 commSetNonBlocking(to
);
935 if (F
->flags
.nodelay
)
936 commSetTcpNoDelay(to
);
940 if (Config
.tcpRcvBufsz
> 0)
941 commSetTcpRcvbuf(to
, Config
.tcpRcvBufsz
);
944 /* Reset FD so that we can connect() again */
946 ConnectStateData::commResetFD()
948 struct addrinfo
*AI
= NULL
;
950 int new_family
= AF_UNSPEC
;
952 // XXX: do we have to check this?
954 // if (!cbdataReferenceValid(callback.data))
957 statCounter
.syscalls
.sock
.sockets
++;
959 /* setup a bare-bones addrinfo */
960 /* TODO INET6: for WinXP we may need to check the local_addr type and setup the family properly. */
962 new_family
= AI
->ai_family
;
964 int fd2
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
966 nul
.FreeAddrInfo(AI
);
969 debugs(5, DBG_CRITICAL
, HERE
<< "WARNING: FD " << fd2
<< " socket failed to allocate: " << xstrerror());
971 if (ENFILE
== errno
|| EMFILE
== errno
)
979 /* On Windows dup2() can't work correctly on Sockets, the */
980 /* workaround is to close the destination Socket before call them. */
985 if (dup2(fd2
, fd
) < 0) {
986 debugs(5, DBG_CRITICAL
, HERE
<< "WARNING: dup2(FD " << fd2
<< ", FD " << fd
<< ") failed: " << xstrerror());
988 if (ENFILE
== errno
|| EMFILE
== errno
)
998 fde
*F
= &fd_table
[fd
];
1000 /* INET6: copy the new sockets family type to the FDE table */
1001 fd_table
[fd
].sock_family
= new_family
;
1003 fd_table
[fd
].flags
.called_connect
= 0;
1005 * yuck, this has assumptions about comm_open() arguments for
1006 * the original socket
1009 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
1010 if( F
->flags
.transparent
) {
1011 comm_set_transparent(fd
);
1015 F
->local_addr
.GetAddrInfo(AI
);
1017 if (commBind(fd
, *AI
) != COMM_OK
) {
1018 debugs(5, DBG_CRITICAL
, "WARNING: Reset of FD " << fd
<< " for " << F
->local_addr
<< " failed to bind: " << xstrerror());
1019 F
->local_addr
.FreeAddrInfo(AI
);
1022 F
->local_addr
.FreeAddrInfo(AI
);
1025 comm_set_tos(fd
, F
->tos
);
1027 #if IPV6_SPECIAL_SPLITSTACK
1029 if( F
->local_addr
.IsIPv6() )
1030 comm_set_v6only(fd
, F
->tos
);
1040 ConnectStateData::commRetryConnect()
1042 assert(addrcount
> 0);
1044 if (addrcount
== 1) {
1045 if (tries
>= Config
.retry
.maxtries
)
1048 if (squid_curtime
- connstart
> Config
.Timeout
.connect
)
1051 if (tries
> addrcount
)
1055 return commResetFD();
1059 commReconnect(void *data
)
1061 ConnectStateData
*cs
= (ConnectStateData
*)data
;
1062 ipcache_nbgethostbyname(cs
->host
, commConnectDnsHandle
, cs
);
1065 /** Connect SOCK to specified DEST_PORT at DEST_HOST. */
1067 ConnectStateData::Connect(int fd
, void *me
)
1069 ConnectStateData
*cs
= (ConnectStateData
*)me
;
1070 assert (cs
->fd
== fd
);
1075 ConnectStateData::defaults()
1078 S
.SetPort(default_port
);
1082 ConnectStateData::connect()
1087 debugs(5,5, HERE
<< "to " << S
);
1089 switch (comm_connect_addr(fd
, S
) ) {
1091 case COMM_INPROGRESS
:
1092 debugs(5, 5, HERE
<< "FD " << fd
<< ": COMM_INPROGRESS");
1093 commSetSelect(fd
, COMM_SELECT_WRITE
, ConnectStateData::Connect
, this, 0);
1097 debugs(5, 5, HERE
<< "FD " << fd
<< ": COMM_OK - connected");
1098 ipcacheMarkGoodAddr(host
, S
);
1099 callCallback(COMM_OK
, 0);
1103 case COMM_ERR_PROTOCOL
:
1104 /* problem using the desired protocol over this socket.
1105 * count the connection attempt, reset the socket, and immediately try again */
1113 debugs(5, 5, HERE
"FD " << fd
<< ": * - try again");
1115 ipcacheMarkBadAddr(host
, S
);
1118 if (Config
.onoff
.test_reachability
)
1119 netdbDeleteAddrNetwork(S
);
1122 if (commRetryConnect()) {
1123 eventAdd("commReconnect", commReconnect
, this, this->addrcount
== 1 ? 0.05 : 0.0, 0);
1125 debugs(5, 5, HERE
<< "FD " << fd
<< ": * - ERR tried too many times already.");
1126 callCallback(COMM_ERR_CONNECT
, errno
);
1132 commSetTimeout_old(int fd, int timeout, PF * handler, void *data)
1134 debugs(5, 3, HERE << "FD " << fd << " timeout " << timeout);
1136 assert(fd < Squid_MaxFD);
1137 fde *F = &fd_table[fd];
1138 assert(F->flags.open);
1141 cbdataReferenceDone(F->timeout_data);
1142 F->timeout_handler = NULL;
1146 cbdataReferenceDone(F->timeout_data);
1147 F->timeout_handler = handler;
1148 F->timeout_data = cbdataReference(data);
1151 F->timeout = squid_curtime + (time_t) timeout;
1159 commSetTimeout(int fd
, int timeout
, PF
* handler
, void *data
)
1161 AsyncCall::Pointer call
;
1162 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
1164 call
=commCbCall(5,4, "SomeTimeoutHandler", CommTimeoutCbPtrFun(handler
, data
));
1167 return commSetTimeout(fd
, timeout
, call
);
1171 int commSetTimeout(int fd
, int timeout
, AsyncCall::Pointer
&callback
)
1173 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
1175 assert(fd
< Squid_MaxFD
);
1176 fde
*F
= &fd_table
[fd
];
1177 assert(F
->flags
.open
);
1180 F
->timeoutHandler
= NULL
;
1183 if (callback
!= NULL
) {
1184 typedef CommTimeoutCbParams Params
;
1185 Params
¶ms
= GetCommParams
<Params
>(callback
);
1187 F
->timeoutHandler
= callback
;
1190 F
->timeout
= squid_curtime
+ (time_t) timeout
;
1198 comm_connect_addr(int sock
, const IPAddress
&address
)
1200 comm_err_t status
= COMM_OK
;
1201 fde
*F
= &fd_table
[sock
];
1205 struct addrinfo
*AI
= NULL
;
1206 PROF_start(comm_connect_addr
);
1208 assert(address
.GetPort() != 0);
1210 debugs(5, 9, "comm_connect_addr: connecting socket " << sock
<< " to " << address
<< " (want family: " << F
->sock_family
<< ")");
1212 /* BUG 2222 FIX: reset the FD when its found to be IPv4 in IPv6 mode */
1213 /* inverse case of IPv4 failing to connect on IPv6 socket is handeld post-connect.
1214 * this case must presently be handled here since the GetAddrInfo asserts on bad mappings.
1215 * eventually we want it to throw a Must() that gets handled there instead of this if.
1216 * NP: because commresetFD is private to ConnStateData we have to return an error and
1217 * trust its handled properly.
1220 if(F
->sock_family
== AF_INET
&& !address
.IsIPv4()) {
1221 return COMM_ERR_PROTOCOL
;
1225 address
.GetAddrInfo(AI
, F
->sock_family
);
1227 /* Establish connection. */
1230 if (!F
->flags
.called_connect
)
1232 F
->flags
.called_connect
= 1;
1233 statCounter
.syscalls
.sock
.connects
++;
1235 x
= connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
1237 // XXX: ICAP code refuses callbacks during a pending comm_ call
1238 // Async calls development will fix this.
1241 errno
= EINPROGRESS
;
1246 debugs(5,5, "comm_connect_addr: sock=" << sock
<< ", addrinfo( " <<
1247 " flags=" << AI
->ai_flags
<<
1248 ", family=" << AI
->ai_family
<<
1249 ", socktype=" << AI
->ai_socktype
<<
1250 ", protocol=" << AI
->ai_protocol
<<
1251 ", &addr=" << AI
->ai_addr
<<
1252 ", addrlen=" << AI
->ai_addrlen
<<
1254 debugs(5, 9, "connect FD " << sock
<< ": (" << x
<< ") " << xstrerror());
1255 debugs(14,9, "connecting to: " << address
);
1259 #if defined(_SQUID_NEWSOS6_)
1260 /* Makoto MATSUSHITA <matusita@ics.es.osaka-u.ac.jp> */
1262 connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
1264 if (errno
== EINVAL
) {
1265 errlen
= sizeof(err
);
1266 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
1273 errlen
= sizeof(err
);
1275 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
1280 #if defined(_SQUID_SOLARIS_)
1282 * Solaris 2.4's socket emulation doesn't allow you
1283 * to determine the error from a failed non-blocking
1284 * connect and just returns EPIPE. Create a fake
1285 * error message for connect. -- fenner@parc.xerox.com
1287 if (x
< 0 && errno
== EPIPE
)
1295 /* Squid seems to be working fine without this code. With this code,
1296 * we leak memory on many connect requests because of EINPROGRESS.
1297 * If you find that this code is needed, please file a bug report. */
1299 #ifdef _SQUID_LINUX_
1301 * Linux Debian replaces our allocated AI pointer with garbage when
1302 * connect() fails. This leads to segmentation faults deallocating
1303 * the system-allocated memory when we go to clean up our pointer.
1304 * HACK: is to leak the memory returned since we can't deallocate.
1312 address
.FreeAddrInfo(AI
);
1314 PROF_stop(comm_connect_addr
);
1316 if (errno
== 0 || errno
== EISCONN
)
1318 else if (ignoreErrno(errno
))
1319 status
= COMM_INPROGRESS
;
1322 if( address
.IsIPv4() && F
->sock_family
== AF_INET6
) {
1324 /* failover to trying IPv4-only link if an IPv6 one fails */
1325 /* to catch the edge case of apps listening on IPv4-localhost */
1326 F
->sock_family
= AF_INET
;
1327 int res
= comm_connect_addr(sock
, address
);
1329 /* if that fails too, undo our temporary socktype hack so the repeat works properly. */
1330 if(res
== COMM_ERROR
)
1331 F
->sock_family
= AF_INET6
;
1339 address
.NtoA(F
->ipaddr
, MAX_IPSTRLEN
);
1341 F
->remote_port
= address
.GetPort(); /* remote_port is HS */
1343 if (status
== COMM_OK
)
1345 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connected to " << address
);
1346 } else if (status
== COMM_INPROGRESS
)
1348 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connection pending");
1354 /* Wait for an incoming connection on FD. FD should be a socket returned
1355 * from comm_listen. */
1357 comm_old_accept(int fd
, ConnectionDetail
&details
)
1359 PROF_start(comm_accept
);
1360 statCounter
.syscalls
.sock
.accepts
++;
1362 struct addrinfo
*gai
= NULL
;
1363 details
.me
.InitAddrInfo(gai
);
1365 if ((sock
= accept(fd
, gai
->ai_addr
, &gai
->ai_addrlen
)) < 0) {
1367 details
.me
.FreeAddrInfo(gai
);
1369 PROF_stop(comm_accept
);
1371 if (ignoreErrno(errno
))
1373 debugs(50, 5, "comm_old_accept: FD " << fd
<< ": " << xstrerror());
1374 return COMM_NOMESSAGE
;
1375 } else if (ENFILE
== errno
|| EMFILE
== errno
)
1377 debugs(50, 3, "comm_old_accept: FD " << fd
<< ": " << xstrerror());
1381 debugs(50, 1, "comm_old_accept: FD " << fd
<< ": " << xstrerror());
1386 details
.peer
= *gai
;
1388 details
.me
.InitAddrInfo(gai
);
1390 details
.me
.SetEmpty();
1391 getsockname(sock
, gai
->ai_addr
, &gai
->ai_addrlen
);
1394 commSetCloseOnExec(sock
);
1397 fd_open(sock
, FD_SOCKET
, "HTTP Request");
1398 fdd_table
[sock
].close_file
= NULL
;
1399 fdd_table
[sock
].close_line
= 0;
1400 fde
*F
= &fd_table
[sock
];
1401 details
.peer
.NtoA(F
->ipaddr
,MAX_IPSTRLEN
);
1402 F
->remote_port
= details
.peer
.GetPort();
1403 F
->local_addr
.SetPort(details
.me
.GetPort());
1405 F
->sock_family
= AF_INET
;
1407 F
->sock_family
= details
.me
.IsIPv4()?AF_INET
:AF_INET6
;
1409 details
.me
.FreeAddrInfo(gai
);
1411 commSetNonBlocking(sock
);
1413 /* IFF the socket is (tproxy) transparent, pass the flag down to allow spoofing */
1414 F
->flags
.transparent
= fd_table
[fd
].flags
.transparent
;
1416 PROF_stop(comm_accept
);
1421 commCallCloseHandlers(int fd
)
1423 fde
*F
= &fd_table
[fd
];
1424 debugs(5, 5, "commCallCloseHandlers: FD " << fd
);
1426 while (F
->closeHandler
!= NULL
) {
1427 AsyncCall::Pointer call
= F
->closeHandler
;
1428 F
->closeHandler
= call
->Next();
1429 call
->setNext(NULL
);
1430 // If call is not canceled schedule it for execution else ignore it
1431 if(!call
->canceled()){
1432 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call
);
1433 typedef CommCloseCbParams Params
;
1434 Params
¶ms
= GetCommParams
<Params
>(call
);
1436 ScheduleCallHere(call
);
1443 commLingerClose(int fd
, void *unused
)
1445 LOCAL_ARRAY(char, buf
, 1024);
1447 n
= FD_READ_METHOD(fd
, buf
, 1024);
1450 debugs(5, 3, "commLingerClose: FD " << fd
<< " read: " << xstrerror());
1456 commLingerTimeout(int fd
, void *unused
)
1458 debugs(5, 3, "commLingerTimeout: FD " << fd
);
1463 * Inspired by apache
1466 comm_lingering_close(int fd
)
1470 if (fd_table
[fd
].ssl
)
1471 ssl_shutdown_method(fd
);
1475 if (shutdown(fd
, 1) < 0) {
1480 fd_note(fd
, "lingering close");
1481 commSetTimeout(fd
, 10, commLingerTimeout
, NULL
);
1482 commSetSelect(fd
, COMM_SELECT_READ
, commLingerClose
, NULL
, 0);
1488 * enable linger with time of 0 so that when the socket is
1489 * closed, TCP generates a RESET
1492 comm_reset_close(int fd
)
1499 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1500 debugs(50, 0, "commResetTCPClose: FD " << fd
<< ": " << xstrerror());
1506 comm_close_start(int fd
, void *data
)
1509 fde
*F
= &fd_table
[fd
];
1511 ssl_shutdown_method(fd
);
1519 comm_close_complete(int fd
, void *data
)
1522 fde
*F
= &fd_table
[fd
];
1530 fd_close(fd
); /* update fdstat */
1534 fdc_table
[fd
] = AcceptFD(fd
);
1536 statCounter
.syscalls
.sock
.closes
++;
1538 /* When an fd closes, give accept() a chance, if need be */
1540 if (fdNFree() >= RESERVED_FD
)
1541 AcceptLimiter::Instance().kick();
1546 * Close the socket fd.
1548 * + call write handlers with ERR_CLOSING
1549 * + call read handlers with ERR_CLOSING
1550 * + call closing handlers
1552 * NOTE: COMM_ERR_CLOSING will NOT be called for CommReads' sitting in a
1553 * DeferredReadManager.
1556 _comm_close(int fd
, char const *file
, int line
)
1558 debugs(5, 3, "comm_close: start closing FD " << fd
);
1560 assert(fd
< Squid_MaxFD
);
1562 fde
*F
= &fd_table
[fd
];
1563 fdd_table
[fd
].close_file
= file
;
1564 fdd_table
[fd
].close_line
= line
;
1569 if (shutting_down
&& (!F
->flags
.open
|| F
->type
== FD_FILE
))
1572 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
1575 assert(F
->type
!= FD_FILE
);
1577 PROF_start(comm_close
);
1579 F
->flags
.close_request
= 1;
1581 AsyncCall::Pointer startCall
=commCbCall(5,4, "comm_close_start",
1582 CommCloseCbPtrFun(comm_close_start
, NULL
));
1583 typedef CommCloseCbParams Params
;
1584 Params
&startParams
= GetCommParams
<Params
>(startCall
);
1585 startParams
.fd
= fd
;
1586 ScheduleCallHere(startCall
);
1588 // a half-closed fd may lack a reader, so we stop monitoring explicitly
1589 if (commHasHalfClosedMonitor(fd
))
1590 commStopHalfClosedMonitor(fd
);
1591 commSetTimeout(fd
, -1, NULL
, NULL
);
1593 // notify read/write handlers
1594 if (commio_has_callback(fd
, IOCB_WRITE
, COMMIO_FD_WRITECB(fd
))) {
1595 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), COMM_ERR_CLOSING
, errno
);
1597 if (commio_has_callback(fd
, IOCB_READ
, COMMIO_FD_READCB(fd
))) {
1598 commio_finish_callback(fd
, COMMIO_FD_READCB(fd
), COMM_ERR_CLOSING
, errno
);
1601 // notify accept handlers
1602 fdc_table
[fd
].notify(-1, COMM_ERR_CLOSING
, 0, ConnectionDetail());
1604 commCallCloseHandlers(fd
);
1607 F
->pconn
.pool
->count(F
->pconn
.uses
);
1609 comm_empty_os_read_buffers(fd
);
1612 AsyncCall::Pointer completeCall
=commCbCall(5,4, "comm_close_complete",
1613 CommCloseCbPtrFun(comm_close_complete
, NULL
));
1614 Params
&completeParams
= GetCommParams
<Params
>(completeCall
);
1615 completeParams
.fd
= fd
;
1616 // must use async call to wait for all callbacks
1617 // scheduled before comm_close() to finish
1618 ScheduleCallHere(completeCall
);
1620 PROF_stop(comm_close
);
1623 /* Send a udp datagram to specified TO_ADDR. */
1625 comm_udp_sendto(int fd
,
1626 const IPAddress
&to_addr
,
1631 struct addrinfo
*AI
= NULL
;
1633 PROF_start(comm_udp_sendto
);
1634 statCounter
.syscalls
.sock
.sendtos
++;
1636 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr
<<
1637 " using FD " << fd
<< " using Port " << comm_local_port(fd
) );
1639 /* BUG: something in the above macro appears to occasionally be setting AI to garbage. */
1640 /* AYJ: 2007-08-27 : or was it because I wasn't then setting 'fd_table[fd].sock_family' to fill properly. */
1641 assert( NULL
== AI
);
1643 to_addr
.GetAddrInfo(AI
, fd_table
[fd
].sock_family
);
1645 x
= sendto(fd
, buf
, len
, 0, AI
->ai_addr
, AI
->ai_addrlen
);
1647 to_addr
.FreeAddrInfo(AI
);
1649 PROF_stop(comm_udp_sendto
);
1654 #ifdef _SQUID_LINUX_
1656 if (ECONNREFUSED
!= errno
)
1659 debugs(50, 1, "comm_udp_sendto: FD " << fd
<< ", (family=" << fd_table
[fd
].sock_family
<< ") " << to_addr
<< ": " << xstrerror());
1665 comm_add_close_handler(int fd
, PF
* handler
, void *data
)
1667 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", handler=" <<
1668 handler
<< ", data=" << data
);
1670 AsyncCall::Pointer call
=commCbCall(5,4, "SomeCloseHandler",
1671 CommCloseCbPtrFun(handler
, data
));
1672 comm_add_close_handler(fd
, call
);
1676 comm_add_close_handler(int fd
, AsyncCall::Pointer
&call
)
1678 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1680 /*TODO:Check for a similar scheduled AsyncCall*/
1681 // for (c = fd_table[fd].closeHandler; c; c = c->next)
1682 // assert(c->handler != handler || c->data != data);
1684 call
->setNext(fd_table
[fd
].closeHandler
);
1686 fd_table
[fd
].closeHandler
= call
;
1690 // remove function-based close handler
1692 comm_remove_close_handler(int fd
, PF
* handler
, void *data
)
1694 assert (isOpen(fd
));
1695 /* Find handler in list */
1696 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", handler=" <<
1697 handler
<< ", data=" << data
);
1699 AsyncCall::Pointer p
;
1700 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
; p
= p
->Next()){
1701 typedef CommCbFunPtrCallT
<CommCloseCbPtrFun
> Call
;
1702 const Call
*call
= dynamic_cast<const Call
*>(p
.getRaw());
1703 if (!call
) // method callbacks have their own comm_remove_close_handler
1706 typedef CommCloseCbParams Params
;
1707 const Params
¶ms
= GetCommParams
<Params
>(p
);
1708 if (call
->dialer
.handler
== handler
&& params
.data
== data
)
1709 break; /* This is our handler */
1712 p
->cancel("comm_remove_close_handler");
1715 // remove method-based close handler
1717 comm_remove_close_handler(int fd
, AsyncCall::Pointer
&call
)
1719 assert (isOpen(fd
));
1720 /* Find handler in list */
1721 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1723 // Check to see if really exist the given AsyncCall in comm_close handlers
1724 // TODO: optimize: this slow code is only needed for the assert() below
1725 AsyncCall::Pointer p
;
1726 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
&& p
!= call
; p
= p
->Next());
1729 call
->cancel("comm_remove_close_handler");
1733 commSetNoLinger(int fd
)
1737 L
.l_onoff
= 0; /* off */
1740 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1741 debugs(50, 0, "commSetNoLinger: FD " << fd
<< ": " << xstrerror());
1743 fd_table
[fd
].flags
.nolinger
= 1;
1747 commSetReuseAddr(int fd
)
1751 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &on
, sizeof(on
)) < 0)
1752 debugs(50, 1, "commSetReuseAddr: FD " << fd
<< ": " << xstrerror());
1756 commSetTcpRcvbuf(int fd
, int size
)
1758 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, (char *) &size
, sizeof(size
)) < 0)
1759 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1760 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, (char *) &size
, sizeof(size
)) < 0)
1761 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1762 #ifdef TCP_WINDOW_CLAMP
1763 if (setsockopt(fd
, SOL_TCP
, TCP_WINDOW_CLAMP
, (char *) &size
, sizeof(size
)) < 0)
1764 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1769 commSetNonBlocking(int fd
)
1771 #ifndef _SQUID_MSWIN_
1775 #ifdef _SQUID_WIN32_
1777 int nonblocking
= TRUE
;
1779 #ifdef _SQUID_CYGWIN_
1781 if (fd_table
[fd
].type
!= FD_PIPE
) {
1784 if (ioctl(fd
, FIONBIO
, &nonblocking
) < 0) {
1785 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror() << " " << fd_table
[fd
].type
);
1789 #ifdef _SQUID_CYGWIN_
1794 #ifndef _SQUID_MSWIN_
1796 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1797 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1801 if (fcntl(fd
, F_SETFL
, flags
| SQUID_NONBLOCK
) < 0) {
1802 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror());
1807 #ifdef _SQUID_CYGWIN_
1812 fd_table
[fd
].flags
.nonblocking
= 1;
1818 commUnsetNonBlocking(int fd
)
1820 #ifdef _SQUID_MSWIN_
1821 int nonblocking
= FALSE
;
1823 if (ioctlsocket(fd
, FIONBIO
, (unsigned long *) &nonblocking
) < 0) {
1828 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1829 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1833 if (fcntl(fd
, F_SETFL
, flags
& (~SQUID_NONBLOCK
)) < 0) {
1835 debugs(50, 0, "commUnsetNonBlocking: FD " << fd
<< ": " << xstrerror());
1839 fd_table
[fd
].flags
.nonblocking
= 0;
1844 commSetCloseOnExec(int fd
) {
1849 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1850 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1854 if (fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) < 0)
1855 debugs(50, 0, "FD " << fd
<< ": set close-on-exec failed: " << xstrerror());
1857 fd_table
[fd
].flags
.close_on_exec
= 1;
1864 commSetTcpNoDelay(int fd
) {
1867 if (setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *) &on
, sizeof(on
)) < 0)
1868 debugs(50, 1, "commSetTcpNoDelay: FD " << fd
<< ": " << xstrerror());
1870 fd_table
[fd
].flags
.nodelay
= 1;
1876 commSetTcpKeepalive(int fd
, int idle
, int interval
, int timeout
)
1880 if (timeout
&& interval
) {
1881 int count
= (timeout
+ interval
- 1) / interval
;
1882 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPCNT
, &count
, sizeof(on
)) < 0)
1883 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1888 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, &idle
, sizeof(on
)) < 0)
1889 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1892 #ifdef TCP_KEEPINTVL
1894 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, &interval
, sizeof(on
)) < 0)
1895 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1898 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char *) &on
, sizeof(on
)) < 0)
1899 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1904 fd_table
=(fde
*) xcalloc(Squid_MaxFD
, sizeof(fde
));
1905 fdd_table
= (fd_debug_t
*)xcalloc(Squid_MaxFD
, sizeof(fd_debug_t
));
1907 fdc_table
= new AcceptFD
[Squid_MaxFD
];
1908 for (int pos
= 0; pos
< Squid_MaxFD
; ++pos
) {
1909 fdc_table
[pos
] = AcceptFD(pos
);
1912 commfd_table
= (comm_fd_t
*) xcalloc(Squid_MaxFD
, sizeof(comm_fd_t
));
1913 for (int pos
= 0; pos
< Squid_MaxFD
; pos
++) {
1914 commfd_table
[pos
].fd
= pos
;
1915 commfd_table
[pos
].readcb
.fd
= pos
;
1916 commfd_table
[pos
].readcb
.type
= IOCB_READ
;
1917 commfd_table
[pos
].writecb
.fd
= pos
;
1918 commfd_table
[pos
].writecb
.type
= IOCB_WRITE
;
1921 /* XXX account fd_table */
1922 /* Keep a few file descriptors free so that we don't run out of FD's
1923 * after accepting a client but before it opens a socket or a file.
1924 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
1925 RESERVED_FD
= XMIN(100, Squid_MaxFD
/ 4);
1927 conn_close_pool
= memPoolCreate("close_handler", sizeof(close_handler
));
1929 TheHalfClosed
= new DescriptorSet
;
1934 delete TheHalfClosed
;
1935 TheHalfClosed
= NULL
;
1937 safe_free(fd_table
);
1938 safe_free(fdd_table
);
1943 safe_free(commfd_table
);
1948 commHandleWrite(int fd
, void *data
) {
1949 comm_io_callback_t
*state
= (comm_io_callback_t
*)data
;
1953 assert(state
== COMMIO_FD_WRITECB(fd
));
1955 PROF_start(commHandleWrite
);
1956 debugs(5, 5, "commHandleWrite: FD " << fd
<< ": off " <<
1957 (long int) state
->offset
<< ", sz " << (long int) state
->size
<< ".");
1959 nleft
= state
->size
- state
->offset
;
1960 len
= FD_WRITE_METHOD(fd
, state
->buf
+ state
->offset
, nleft
);
1961 debugs(5, 5, "commHandleWrite: write() returns " << len
);
1962 fd_bytes(fd
, len
, FD_WRITE
);
1963 statCounter
.syscalls
.sock
.writes
++;
1966 /* Note we even call write if nleft == 0 */
1970 debugs(5, 1, "commHandleWrite: FD " << fd
<< ": write failure: connection closed with " << nleft
<< " bytes remaining.");
1972 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1973 } else if (len
< 0) {
1976 if (fd_table
[fd
].flags
.socket_eof
) {
1977 debugs(50, 2, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1978 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1979 } else if (ignoreErrno(errno
)) {
1980 debugs(50, 10, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1987 debugs(50, 2, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1988 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1991 /* A successful write, continue */
1992 state
->offset
+= len
;
1994 if (state
->offset
< state
->size
) {
1995 /* Not done, reinstall the write handler and write some more */
2002 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_OK
: COMM_ERROR
, errno
);
2006 PROF_stop(commHandleWrite
);
2010 * Queue a write. handler/handler_data are called when the write
2011 * completes, on error, or on file descriptor close.
2013 * free_func is used to free the passed buffer when the write has completed.
2016 comm_write(int fd
, const char *buf
, int size
, IOCB
* handler
, void *handler_data
, FREE
* free_func
)
2018 AsyncCall::Pointer call
= commCbCall(5,5, "SomeCommWriteHander",
2019 CommIoCbPtrFun(handler
, handler_data
));
2021 comm_write(fd
, buf
, size
, call
, free_func
);
2025 comm_write(int fd
, const char *buf
, int size
, AsyncCall::Pointer
&callback
, FREE
* free_func
)
2027 debugs(5, 5, "comm_write: FD " << fd
<< ": sz " << size
<< ": asynCall " << callback
);
2029 /* Make sure we are open, not closing, and not writing */
2031 assert(!fd_table
[fd
].closing());
2032 comm_io_callback_t
*ccb
= COMMIO_FD_WRITECB(fd
);
2033 assert(!ccb
->active());
2035 /* Queue the write */
2036 commio_set_callback(fd
, IOCB_WRITE
, ccb
, callback
,
2037 (char *)buf
, free_func
, size
);
2038 commSetSelect(fd
, COMM_SELECT_WRITE
, commHandleWrite
, ccb
, 0);
2042 /* a wrapper around comm_write to allow for MemBuf to be comm_written in a snap */
2044 comm_write_mbuf(int fd
, MemBuf
*mb
, IOCB
* handler
, void *handler_data
) {
2045 comm_write(fd
, mb
->buf
, mb
->size
, handler
, handler_data
, mb
->freeFunc());
2049 comm_write_mbuf(int fd
, MemBuf
*mb
, AsyncCall::Pointer
&callback
) {
2050 comm_write(fd
, mb
->buf
, mb
->size
, callback
, mb
->freeFunc());
2055 * hm, this might be too general-purpose for all the places we'd
2059 ignoreErrno(int ierrno
) {
2065 #if EAGAIN != EWOULDBLOCK
2088 commCloseAllSockets(void) {
2092 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
2098 if (F
->type
!= FD_SOCKET
)
2101 if (F
->flags
.ipc
) /* don't close inter-process sockets */
2104 if (F
->timeoutHandler
!= NULL
) {
2105 AsyncCall::Pointer callback
= F
->timeoutHandler
;
2106 F
->timeoutHandler
= NULL
;
2107 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": Calling timeout handler");
2108 ScheduleCallHere(callback
);
2110 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": calling comm_close()");
2117 AlreadyTimedOut(fde
*F
) {
2121 if (F
->timeout
== 0)
2124 if (F
->timeout
> squid_curtime
)
2131 checkTimeouts(void) {
2134 AsyncCall::Pointer callback
;
2136 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
2139 if (AlreadyTimedOut(F
))
2142 debugs(5, 5, "checkTimeouts: FD " << fd
<< " Expired");
2144 if (F
->timeoutHandler
!= NULL
) {
2145 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Call timeout handler");
2146 callback
= F
->timeoutHandler
;
2147 F
->timeoutHandler
= NULL
;
2148 ScheduleCallHere(callback
);
2150 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Forcing comm_close()");
2157 * New-style listen and accept routines
2159 * Listen simply registers our interest in an FD for listening,
2160 * and accept takes a callback to call when an FD has been
2164 comm_listen(int sock
) {
2167 if ((x
= listen(sock
, Squid_MaxFD
>> 2)) < 0) {
2168 debugs(50, 0, "comm_listen: listen(" << (Squid_MaxFD
>> 2) << ", " << sock
<< "): " << xstrerror());
2172 if (Config
.accept_filter
&& strcmp(Config
.accept_filter
, "none") != 0) {
2173 #ifdef SO_ACCEPTFILTER
2174 struct accept_filter_arg afa
;
2175 bzero(&afa
, sizeof(afa
));
2176 debugs(5, DBG_CRITICAL
, "Installing accept filter '" << Config
.accept_filter
<< "' on FD " << sock
);
2177 xstrncpy(afa
.af_name
, Config
.accept_filter
, sizeof(afa
.af_name
));
2178 x
= setsockopt(sock
, SOL_SOCKET
, SO_ACCEPTFILTER
, &afa
, sizeof(afa
));
2180 debugs(5, 0, "SO_ACCEPTFILTER '" << Config
.accept_filter
<< "': '" << xstrerror());
2181 #elif defined(TCP_DEFER_ACCEPT)
2183 if (strncmp(Config
.accept_filter
, "data=", 5) == 0)
2184 seconds
= atoi(Config
.accept_filter
+ 5);
2185 x
= setsockopt(sock
, IPPROTO_TCP
, TCP_DEFER_ACCEPT
, &seconds
, sizeof(seconds
));
2187 debugs(5, 0, "TCP_DEFER_ACCEPT '" << Config
.accept_filter
<< "': '" << xstrerror());
2189 debugs(5, 0, "accept_filter not supported on your OS");
2197 comm_accept(int fd
, IOACB
*handler
, void *handler_data
) {
2198 debugs(5, 5, "comm_accept: FD " << fd
<< " handler: " << (void*)handler
);
2201 AsyncCall::Pointer call
= commCbCall(5,5, "SomeCommAcceptHandler",
2202 CommAcceptCbPtrFun(handler
, handler_data
));
2203 fdc_table
[fd
].subscribe(call
);
2207 comm_accept(int fd
, AsyncCall::Pointer
&call
) {
2208 debugs(5, 5, "comm_accept: FD " << fd
<< " AsyncCall: " << call
);
2211 fdc_table
[fd
].subscribe(call
);
2214 // Called when somebody wants to be notified when our socket accepts new
2215 // connection. We do not probe the FD until there is such interest.
2217 AcceptFD::subscribe(AsyncCall::Pointer
&call
) {
2218 /* make sure we're not pending! */
2219 assert(!theCallback
);
2223 mayAcceptMore
= true; // even if we failed to accept last time
2229 commSetSelect(fd
, COMM_SELECT_READ
, comm_accept_try
, NULL
, 0);
2233 AcceptFD::acceptOne() {
2234 // If there is no callback and we accept, we will leak the accepted FD.
2235 // When we are running out of FDs, there is often no callback.
2237 debugs(5, 5, "AcceptFD::acceptOne orphaned: FD " << fd
);
2238 // XXX: can we remove this and similar "just in case" calls and
2239 // either listen always or listen only when there is a callback?
2240 if (!AcceptLimiter::Instance().deferring())
2241 commSetSelect(fd
, COMM_SELECT_READ
, comm_accept_try
, NULL
, 0);
2246 * We don't worry about running low on FDs here. Instead,
2247 * httpAccept() will use AcceptLimiter if we reach the limit
2251 /* Accept a new connection */
2252 ConnectionDetail connDetails
;
2253 int newfd
= comm_old_accept(fd
, connDetails
);
2255 /* Check for errors */
2258 assert(theCallback
!= NULL
);
2260 if (newfd
== COMM_NOMESSAGE
) {
2261 /* register interest again */
2262 debugs(5, 5, HERE
<< "try later: FD " << fd
<<
2263 " handler: " << *theCallback
);
2264 commSetSelect(fd
, COMM_SELECT_READ
, comm_accept_try
, NULL
, 0);
2268 // A non-recoverable error; notify the caller */
2269 notify(-1, COMM_ERROR
, errno
, connDetails
);
2273 assert(theCallback
!= NULL
);
2274 debugs(5, 5, "AcceptFD::acceptOne accepted: FD " << fd
<<
2275 " newfd: " << newfd
<< " from: " << connDetails
.peer
<<
2276 " handler: " << *theCallback
);
2277 notify(newfd
, COMM_OK
, 0, connDetails
);
2282 AcceptFD::acceptNext() {
2283 mayAcceptMore
= acceptOne();
2287 AcceptFD::notify(int newfd
, comm_err_t errcode
, int xerrno
, const ConnectionDetail
&connDetails
)
2289 if (theCallback
!= NULL
) {
2290 typedef CommAcceptCbParams Params
;
2291 Params
¶ms
= GetCommParams
<Params
>(theCallback
);
2294 params
.details
= connDetails
;
2295 params
.flag
= errcode
;
2296 params
.xerrno
= xerrno
;
2297 ScheduleCallHere(theCallback
);
2303 * This callback is called whenever a filedescriptor is ready
2304 * to dupe itself and fob off an accept()ed connection
2307 comm_accept_try(int fd
, void *) {
2309 fdc_table
[fd
].acceptNext();
2312 void CommIO::Initialise() {
2313 /* Initialize done pipe signal */
2315 if(pipe(DonePipe
)) {}
2316 DoneFD
= DonePipe
[1];
2317 DoneReadFD
= DonePipe
[0];
2318 fd_open(DoneReadFD
, FD_PIPE
, "async-io completetion event: main");
2319 fd_open(DoneFD
, FD_PIPE
, "async-io completetion event: threads");
2320 commSetNonBlocking(DoneReadFD
);
2321 commSetNonBlocking(DoneFD
);
2322 commSetSelect(DoneReadFD
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
2326 void CommIO::NotifyIOClose() {
2327 /* Close done pipe signal */
2332 fd_close(DoneReadFD
);
2333 Initialised
= false;
2336 bool CommIO::Initialised
= false;
2337 bool CommIO::DoneSignalled
= false;
2338 int CommIO::DoneFD
= -1;
2339 int CommIO::DoneReadFD
= -1;
2342 CommIO::FlushPipe() {
2344 FD_READ_METHOD(DoneReadFD
, buf
, sizeof(buf
));
2348 CommIO::NULLFDHandler(int fd
, void *data
) {
2350 commSetSelect(fd
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
2354 CommIO::ResetNotifications() {
2355 if (DoneSignalled
) {
2357 DoneSignalled
= false;
2361 AcceptLimiter
AcceptLimiter::Instance_
;
2363 AcceptLimiter
&AcceptLimiter::Instance() {
2368 AcceptLimiter::deferring() const {
2369 return deferred
.size() > 0;
2373 AcceptLimiter::defer (int fd
, Acceptor::AcceptorFunction
*aFunc
, void *data
) {
2374 debugs(5, 5, "AcceptLimiter::defer: FD " << fd
<< " handler: " << (void*)aFunc
);
2376 temp
.theFunction
= aFunc
;
2378 temp
.theData
= data
;
2379 deferred
.push_back(temp
);
2383 AcceptLimiter::kick() {
2387 /* Yes, this means the first on is the last off....
2388 * If the list container was a little more friendly, we could sensibly us it.
2390 Acceptor temp
= deferred
.pop_back();
2392 comm_accept (temp
.acceptFD
, temp
.theFunction
, temp
.theData
);
2395 /// Start waiting for a possibly half-closed connection to close
2396 // by scheduling a read callback to a monitoring handler that
2397 // will close the connection on read errors.
2399 commStartHalfClosedMonitor(int fd
) {
2400 debugs(5, 5, HERE
<< "adding FD " << fd
<< " to " << *TheHalfClosed
);
2402 assert(!commHasHalfClosedMonitor(fd
));
2403 (void)TheHalfClosed
->add(fd
); // could also assert the result
2404 commPlanHalfClosedCheck(); // may schedule check if we added the first FD
2409 commPlanHalfClosedCheck()
2411 if (!WillCheckHalfClosed
&& !TheHalfClosed
->empty()) {
2412 eventAdd("commHalfClosedCheck", &commHalfClosedCheck
, NULL
, 1.0, 1);
2413 WillCheckHalfClosed
= true;
2417 /// iterates over all descriptors that may need half-closed tests and
2418 /// calls comm_read for those that do; re-schedules the check if needed
2421 commHalfClosedCheck(void *) {
2422 debugs(5, 5, HERE
<< "checking " << *TheHalfClosed
);
2424 typedef DescriptorSet::const_iterator DSCI
;
2425 const DSCI end
= TheHalfClosed
->end();
2426 for (DSCI i
= TheHalfClosed
->begin(); i
!= end
; ++i
) {
2428 if (!fd_table
[fd
].halfClosedReader
) { // not reading already
2429 AsyncCall::Pointer call
= commCbCall(5,4, "commHalfClosedReader",
2430 CommIoCbPtrFun(&commHalfClosedReader
, NULL
));
2431 comm_read(fd
, NULL
, 0, call
);
2432 fd_table
[fd
].halfClosedReader
= call
;
2436 WillCheckHalfClosed
= false; // as far as we know
2437 commPlanHalfClosedCheck(); // may need to check again
2440 /// checks whether we are waiting for possibly half-closed connection to close
2441 // We are monitoring if the read handler for the fd is the monitoring handler.
2443 commHasHalfClosedMonitor(int fd
) {
2444 return TheHalfClosed
->has(fd
);
2447 /// stop waiting for possibly half-closed connection to close
2449 commStopHalfClosedMonitor(int const fd
) {
2450 debugs(5, 5, HERE
<< "removing FD " << fd
<< " from " << *TheHalfClosed
);
2452 // cancel the read if one was scheduled
2453 AsyncCall::Pointer reader
= fd_table
[fd
].halfClosedReader
;
2455 comm_read_cancel(fd
, reader
);
2456 fd_table
[fd
].halfClosedReader
= NULL
;
2458 TheHalfClosed
->del(fd
);
2461 /// I/O handler for the possibly half-closed connection monitoring code
2463 commHalfClosedReader(int fd
, char *, size_t size
, comm_err_t flag
, int, void *) {
2464 // there cannot be more data coming in on half-closed connections
2466 assert(commHasHalfClosedMonitor(fd
)); // or we would have canceled the read
2468 fd_table
[fd
].halfClosedReader
= NULL
; // done reading, for now
2470 // nothing to do if fd is being closed
2471 if (flag
== COMM_ERR_CLOSING
)
2474 // if read failed, close the connection
2475 if (flag
!= COMM_OK
) {
2476 debugs(5, 3, "commHalfClosedReader: closing FD " << fd
);
2481 // continue waiting for close or error
2482 commPlanHalfClosedCheck(); // make sure this fd will be checked again
2486 CommRead::CommRead() : fd(-1), buf(NULL
), len(0), callback(NULL
) {}
2488 CommRead::CommRead(int fd_
, char *buf_
, int len_
, AsyncCall::Pointer
&callback_
)
2489 : fd(fd_
), buf(buf_
), len(len_
), callback(callback_
) {}
2491 DeferredRead::DeferredRead () : theReader(NULL
), theContext(NULL
), theRead(), cancelled(false) {}
2493 DeferredRead::DeferredRead (DeferrableRead
*aReader
, void *data
, CommRead
const &aRead
) : theReader(aReader
), theContext (data
), theRead(aRead
), cancelled(false) {}
2495 DeferredReadManager::~DeferredReadManager() {
2497 assert (deferredReads
.empty());
2500 /* explicit instantiation required for some systems */
2502 /// \cond AUTODOCS-IGNORE
2503 template cbdata_type CbDataList
<DeferredRead
>::CBDATA_CbDataList
;
2507 DeferredReadManager::delayRead(DeferredRead
const &aRead
) {
2508 debugs(5, 3, "Adding deferred read on FD " << aRead
.theRead
.fd
);
2509 CbDataList
<DeferredRead
> *temp
= deferredReads
.push_back(aRead
);
2511 // We have to use a global function as a closer and point to temp
2512 // instead of "this" because DeferredReadManager is not a job and
2513 // is not even cbdata protected
2514 AsyncCall::Pointer closer
= commCbCall(5,4,
2515 "DeferredReadManager::CloseHandler",
2516 CommCloseCbPtrFun(&CloseHandler
, temp
));
2517 comm_add_close_handler(aRead
.theRead
.fd
, closer
);
2518 temp
->element
.closer
= closer
; // remeber so that we can cancel
2522 DeferredReadManager::CloseHandler(int fd
, void *thecbdata
) {
2523 if (!cbdataReferenceValid (thecbdata
))
2526 CbDataList
<DeferredRead
> *temp
= (CbDataList
<DeferredRead
> *)thecbdata
;
2528 temp
->element
.closer
= NULL
;
2529 temp
->element
.markCancelled();
2533 DeferredReadManager::popHead(CbDataListContainer
<DeferredRead
> &deferredReads
) {
2534 assert (!deferredReads
.empty());
2536 DeferredRead
&read
= deferredReads
.head
->element
;
2537 if (!read
.cancelled
) {
2538 comm_remove_close_handler(read
.theRead
.fd
, read
.closer
);
2542 DeferredRead result
= deferredReads
.pop_front();
2548 DeferredReadManager::kickReads(int const count
) {
2549 /* if we had CbDataList::size() we could consolidate this and flushReads */
2556 size_t remaining
= count
;
2558 while (!deferredReads
.empty() && remaining
) {
2559 DeferredRead aRead
= popHead(deferredReads
);
2562 if (!aRead
.cancelled
)
2568 DeferredReadManager::flushReads() {
2569 CbDataListContainer
<DeferredRead
> reads
;
2570 reads
= deferredReads
;
2571 deferredReads
= CbDataListContainer
<DeferredRead
>();
2573 while (!reads
.empty()) {
2574 DeferredRead aRead
= popHead(reads
);
2580 DeferredReadManager::kickARead(DeferredRead
const &aRead
) {
2581 if (aRead
.cancelled
)
2584 debugs(5, 3, "Kicking deferred read on FD " << aRead
.theRead
.fd
);
2586 aRead
.theReader(aRead
.theContext
, aRead
.theRead
);
2590 DeferredRead::markCancelled() {
2594 ConnectionDetail::ConnectionDetail() : me(), peer() {
2598 CommSelectEngine::checkEvents(int timeout
) {
2599 static time_t last_timeout
= 0;
2601 /* No, this shouldn't be here. But it shouldn't be in each comm handler. -adrian */
2602 if (squid_curtime
> last_timeout
) {
2603 last_timeout
= squid_curtime
;
2607 switch (comm_select(timeout
)) {
2623 fatal_dump("comm.cc: Internal error -- this should never happen.");