2 * DEBUG: section 05 Socket Functions
3 * AUTHOR: Harvest Derived
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
32 * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org>
36 #include "base/AsyncCall.h"
37 #include "StoreIOBuffer.h"
41 #include "comm/AcceptLimiter.h"
42 #include "comm/comm_internal.h"
43 #include "comm/Connection.h"
44 #include "comm/ListenStateData.h"
49 #include "SquidTime.h"
50 #include "CommCalls.h"
51 #include "DescriptorSet.h"
52 #include "icmp/net_db.h"
53 #include "ip/Address.h"
54 #include "ip/Intercept.h"
57 #if defined(_SQUID_CYGWIN_)
58 #include <sys/ioctl.h>
60 #ifdef HAVE_NETINET_TCP_H
61 #include <netinet/tcp.h>
65 * New C-like simple comm code. This stuff is a mess and doesn't really buy us anything.
74 static void commStopHalfClosedMonitor(int fd
);
75 static IOCB commHalfClosedReader
;
76 static void comm_init_opened(int new_socket
, Ip::Address
&addr
, unsigned char TOS
, const char *note
, struct addrinfo
*AI
);
77 static int comm_apply_flags(int new_socket
, Ip::Address
&addr
, int flags
, struct addrinfo
*AI
);
80 struct comm_io_callback_t
{
83 AsyncCall::Pointer callback
;
91 bool active() const { return callback
!= NULL
; }
96 comm_io_callback_t readcb
;
97 comm_io_callback_t writecb
;
99 typedef struct _comm_fd comm_fd_t
;
100 comm_fd_t
*commfd_table
;
102 // TODO: make this a comm_io_callback_t method?
104 commio_has_callback(int fd
, iocb_type type
, comm_io_callback_t
*ccb
)
106 assert(ccb
->fd
== fd
);
107 assert(ccb
->type
== type
);
108 return ccb
->active();
112 * Configure comm_io_callback_t for I/O
114 * @param fd filedescriptor
115 * @param ccb comm io callback
117 * @param cbdata callback data (must be cbdata'ed)
118 * @param buf buffer, if applicable
119 * @param freefunc freefunc, if applicable
120 * @param size buffer size
123 commio_set_callback(int fd
, iocb_type type
, comm_io_callback_t
*ccb
,
124 AsyncCall::Pointer
&cb
, char *buf
, FREE
*freefunc
, int size
)
126 assert(!ccb
->active());
127 assert(ccb
->type
== type
);
132 ccb
->freefunc
= freefunc
;
138 // Schedule the callback call and clear the callback
140 commio_finish_callback(int fd
, comm_io_callback_t
*ccb
, comm_err_t code
, int xerrno
)
142 debugs(5, 3, "commio_finish_callback: called for FD " << fd
<< " (" <<
143 code
<< ", " << xerrno
<< ")");
144 assert(ccb
->active());
145 assert(ccb
->fd
== fd
);
147 ccb
->xerrno
= xerrno
;
149 comm_io_callback_t cb
= *ccb
;
151 /* We've got a copy; blow away the real one */
152 /* XXX duplicate code from commio_cancel_callback! */
154 ccb
->callback
= NULL
; // cb has it
162 if (cb
.callback
!= NULL
) {
163 typedef CommIoCbParams Params
;
164 Params
¶ms
= GetCommParams
<Params
>(cb
.callback
);
167 params
.size
= cb
.offset
;
168 params
.flag
= cb
.errcode
;
169 params
.xerrno
= cb
.xerrno
;
170 ScheduleCallHere(cb
.callback
);
176 * Cancel the given callback
178 * Remember that the data is cbdataRef'ed.
180 // TODO: make this a comm_io_callback_t method
182 commio_cancel_callback(int fd
, comm_io_callback_t
*ccb
)
184 debugs(5, 3, "commio_cancel_callback: called for FD " << fd
);
185 assert(ccb
->fd
== fd
);
186 assert(ccb
->active());
189 ccb
->callback
= NULL
;
193 * Call the given comm callback; assumes the callback is valid.
195 * @param ccb io completion callback
198 commio_call_callback(comm_io_callback_t
*ccb
)
204 static DescriptorSet
*TheHalfClosed
= NULL
; /// the set of half-closed FDs
205 static bool WillCheckHalfClosed
= false; /// true if check is scheduled
206 static EVH commHalfClosedCheck
;
207 static void commPlanHalfClosedCheck();
209 static comm_err_t
commBind(int s
, struct addrinfo
&);
210 static void commSetReuseAddr(int);
211 static void commSetNoLinger(int);
213 static void commSetTcpNoDelay(int);
215 static void commSetTcpRcvbuf(int, int);
216 static PF commHandleWrite
;
223 static MemAllocator
*conn_close_pool
= NULL
;
224 fd_debug_t
*fdd_table
= NULL
;
229 return fd_table
[fd
].flags
.open
!= 0;
235 * If the read attempt succeeds or fails, call the callback.
236 * Else, wait for another IO notification.
239 commHandleRead(int fd
, void *data
)
241 comm_io_callback_t
*ccb
= (comm_io_callback_t
*) data
;
243 assert(data
== COMMIO_FD_READCB(fd
));
244 assert(commio_has_callback(fd
, IOCB_READ
, ccb
));
246 statCounter
.syscalls
.sock
.reads
++;
249 retval
= FD_READ_METHOD(fd
, ccb
->buf
, ccb
->size
);
250 debugs(5, 3, "comm_read_try: FD " << fd
<< ", size " << ccb
->size
<< ", retval " << retval
<< ", errno " << errno
);
252 if (retval
< 0 && !ignoreErrno(errno
)) {
253 debugs(5, 3, "comm_read_try: scheduling COMM_ERROR");
255 commio_finish_callback(fd
, ccb
, COMM_ERROR
, errno
);
259 /* See if we read anything */
260 /* Note - read 0 == socket EOF, which is a valid read */
262 fd_bytes(fd
, retval
, FD_READ
);
263 ccb
->offset
= retval
;
264 commio_finish_callback(fd
, ccb
, COMM_OK
, errno
);
268 /* Nope, register for some more IO */
269 commSetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, data
, 0);
273 * Queue a read. handler/handler_data are called when the read
274 * completes, on error, or on file descriptor close.
277 comm_read(int fd
, char *buf
, int size
, IOCB
*handler
, void *handler_data
)
279 AsyncCall::Pointer call
= commCbCall(5,4, "SomeCommReadHandler",
280 CommIoCbPtrFun(handler
, handler_data
));
281 comm_read(fd
, buf
, size
, call
);
285 comm_read(int fd
, char *buf
, int size
, AsyncCall::Pointer
&callback
)
287 debugs(5, 5, "comm_read, queueing read for FD " << fd
<< "; asynCall " << callback
);
289 /* Make sure we are open and not closing */
291 assert(!fd_table
[fd
].closing());
292 comm_io_callback_t
*ccb
= COMMIO_FD_READCB(fd
);
294 // Make sure we are either not reading or just passively monitoring.
295 // Active/passive conflicts are OK and simply cancel passive monitoring.
297 // if the assertion below fails, we have an active comm_read conflict
298 assert(fd_table
[fd
].halfClosedReader
!= NULL
);
299 commStopHalfClosedMonitor(fd
);
300 assert(!ccb
->active());
304 commio_set_callback(fd
, IOCB_READ
, ccb
, callback
, (char *)buf
, NULL
, size
);
305 commSetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, ccb
, 0);
309 * Empty the read buffers
311 * This is a magical routine that empties the read buffers.
312 * Under some platforms (Linux) if a buffer has data in it before
313 * you call close(), the socket will hang and take quite a while
317 comm_empty_os_read_buffers(int fd
)
320 /* prevent those nasty RST packets */
321 char buf
[SQUID_TCP_SO_RCVBUF
];
323 if (fd_table
[fd
].flags
.nonblocking
== 1) {
324 while (FD_READ_METHOD(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0) {};
331 * Return whether the FD has a pending completed callback.
334 comm_has_pending_read_callback(int fd
)
337 // XXX: We do not know whether there is a read callback scheduled.
338 // This is used for pconn management that should probably be more
339 // tightly integrated into comm to minimize the chance that a
340 // closing pconn socket will be used for a new transaction.
344 // Does comm check this fd for read readiness?
345 // Note that when comm is not monitoring, there can be a pending callback
346 // call, which may resume comm monitoring once fired.
348 comm_monitors_read(int fd
)
351 // Being active is usually the same as monitoring because we always
352 // start monitoring the FD when we configure comm_io_callback_t for I/O
353 // and we usually configure comm_io_callback_t for I/O when we starting
354 // monitoring a FD for reading. TODO: replace with commio_has_callback
355 return COMMIO_FD_READCB(fd
)->active();
359 * Cancel a pending read. Assert that we have the right parameters,
360 * and that there are no pending read events!
362 * XXX: We do not assert that there are no pending read events and
363 * with async calls it becomes even more difficult.
364 * The whole interface should be reworked to do callback->cancel()
365 * instead of searching for places where the callback may be stored and
366 * updating the state of those places.
368 * AHC Don't call the comm handlers?
371 comm_read_cancel(int fd
, IOCB
*callback
, void *data
)
374 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
378 comm_io_callback_t
*cb
= COMMIO_FD_READCB(fd
);
379 // TODO: is "active" == "monitors FD"?
381 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
385 typedef CommCbFunPtrCallT
<CommIoCbPtrFun
> Call
;
386 Call
*call
= dynamic_cast<Call
*>(cb
->callback
.getRaw());
388 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " lacks callback");
392 call
->cancel("old comm_read_cancel");
394 typedef CommIoCbParams Params
;
395 const Params
¶ms
= GetCommParams
<Params
>(cb
->callback
);
397 /* Ok, we can be reasonably sure we won't lose any data here! */
398 assert(call
->dialer
.handler
== callback
);
399 assert(params
.data
== data
);
401 /* Delete the callback */
402 commio_cancel_callback(fd
, cb
);
404 /* And the IO event */
405 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
409 comm_read_cancel(int fd
, AsyncCall::Pointer
&callback
)
411 callback
->cancel("comm_read_cancel");
414 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
418 comm_io_callback_t
*cb
= COMMIO_FD_READCB(fd
);
421 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
425 AsyncCall::Pointer call
= cb
->callback
;
426 assert(call
!= NULL
); // XXX: should never fail (active() checks for callback==NULL)
428 /* Ok, we can be reasonably sure we won't lose any data here! */
429 assert(call
== callback
);
431 /* Delete the callback */
432 commio_cancel_callback(fd
, cb
);
434 /* And the IO event */
435 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
440 * synchronous wrapper around udp socket functions
443 comm_udp_recvfrom(int fd
, void *buf
, size_t len
, int flags
, Ip::Address
&from
)
445 statCounter
.syscalls
.sock
.recvfroms
++;
447 struct addrinfo
*AI
= NULL
;
449 debugs(5,8, "comm_udp_recvfrom: FD " << fd
<< " from " << from
);
451 assert( NULL
== AI
);
453 from
.InitAddrInfo(AI
);
455 x
= recvfrom(fd
, buf
, len
, flags
, AI
->ai_addr
, &AI
->ai_addrlen
);
459 from
.FreeAddrInfo(AI
);
465 comm_udp_recv(int fd
, void *buf
, size_t len
, int flags
)
468 return comm_udp_recvfrom(fd
, buf
, len
, flags
, nul
);
472 comm_udp_send(int s
, const void *buf
, size_t len
, int flags
)
474 return send(s
, buf
, len
, flags
);
479 comm_has_incomplete_write(int fd
)
482 return COMMIO_FD_WRITECB(fd
)->active();
486 * Queue a write. handler/handler_data are called when the write fully
487 * completes, on error, or on file descriptor close.
490 /* Return the local port associated with fd. */
492 comm_local_port(int fd
)
495 struct addrinfo
*addr
= NULL
;
496 fde
*F
= &fd_table
[fd
];
498 /* If the fd is closed already, just return */
500 if (!F
->flags
.open
) {
501 debugs(5, 0, "comm_local_port: FD " << fd
<< " has been closed.");
505 if (F
->local_addr
.GetPort())
506 return F
->local_addr
.GetPort();
508 if (F
->sock_family
== AF_INET
)
511 temp
.InitAddrInfo(addr
);
513 if (getsockname(fd
, addr
->ai_addr
, &(addr
->ai_addrlen
)) ) {
514 debugs(50, 1, "comm_local_port: Failed to retrieve TCP/UDP port number for socket: FD " << fd
<< ": " << xstrerror());
515 temp
.FreeAddrInfo(addr
);
520 temp
.FreeAddrInfo(addr
);
522 if (F
->local_addr
.IsAnyAddr()) {
523 /* save the whole local address, not just the port. */
524 F
->local_addr
= temp
;
526 F
->local_addr
.SetPort(temp
.GetPort());
529 debugs(5, 6, "comm_local_port: FD " << fd
<< ": port " << F
->local_addr
.GetPort() << "(family=" << F
->sock_family
<< ")");
530 return F
->local_addr
.GetPort();
534 commBind(int s
, struct addrinfo
&inaddr
)
536 statCounter
.syscalls
.sock
.binds
++;
538 if (bind(s
, inaddr
.ai_addr
, inaddr
.ai_addrlen
) == 0) {
539 debugs(50, 6, "commBind: bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
);
543 debugs(50, 0, "commBind: Cannot bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
<< ": " << xstrerror());
549 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
550 * is OR of flags specified in comm.h. Defaults TOS
553 comm_open(int sock_type
,
559 return comm_openex(sock_type
, proto
, addr
, flags
, 0, note
);
563 comm_open_listener(int sock_type
,
571 /* all listener sockets require bind() */
572 flags
|= COMM_DOBIND
;
574 /* attempt native enabled port. */
575 sock
= comm_openex(sock_type
, proto
, addr
, flags
, 0, note
);
581 limitError(int const anErrno
)
583 return anErrno
== ENFILE
|| anErrno
== EMFILE
;
587 comm_set_tos(int fd
, int tos
)
590 int x
= setsockopt(fd
, IPPROTO_IP
, IP_TOS
, (char *) &tos
, sizeof(int));
592 debugs(50, 1, "comm_set_tos: setsockopt(IP_TOS) on FD " << fd
<< ": " << xstrerror());
595 debugs(50, 0, "WARNING: setsockopt(IP_TOS) not supported on this platform");
601 comm_set_v6only(int fd
, int tos
)
604 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (char *) &tos
, sizeof(int)) < 0) {
605 debugs(50, 1, "comm_open: setsockopt(IPV6_V6ONLY) " << (tos
?"ON":"OFF") << " for FD " << fd
<< ": " << xstrerror());
608 debugs(50, 0, "WARNING: comm_open: setsockopt(IPV6_V6ONLY) not supported on this platform");
613 * Set the socket IP_TRANSPARENT option for Linux TPROXY v4 support.
616 comm_set_transparent(int fd
)
618 #if defined(IP_TRANSPARENT)
620 if (setsockopt(fd
, SOL_IP
, IP_TRANSPARENT
, (char *) &tos
, sizeof(int)) < 0) {
621 debugs(50, DBG_IMPORTANT
, "comm_open: setsockopt(IP_TRANSPARENT) on FD " << fd
<< ": " << xstrerror());
623 /* mark the socket as having transparent options */
624 fd_table
[fd
].flags
.transparent
= 1;
627 debugs(50, DBG_CRITICAL
, "WARNING: comm_open: setsockopt(IP_TRANSPARENT) not supported on this platform");
632 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
633 * is OR of flags specified in defines.h:COMM_*
636 comm_openex(int sock_type
,
645 struct addrinfo
*AI
= NULL
;
647 PROF_start(comm_open
);
648 /* Create socket for accepting new connections. */
649 statCounter
.syscalls
.sock
.sockets
++;
651 /* Setup the socket addrinfo details for use */
652 addr
.GetAddrInfo(AI
);
653 AI
->ai_socktype
= sock_type
;
654 AI
->ai_protocol
= proto
;
656 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr
);
658 new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
660 /* under IPv6 there is the possibility IPv6 is present but disabled. */
661 /* try again as IPv4-native if possible */
662 if ( new_socket
< 0 && Ip::EnableIpv6
&& addr
.IsIPv6() && addr
.SetIPv4() ) {
663 /* attempt to open this IPv4-only. */
664 addr
.FreeAddrInfo(AI
);
665 /* Setup the socket addrinfo details for use */
666 addr
.GetAddrInfo(AI
);
667 AI
->ai_socktype
= sock_type
;
668 AI
->ai_protocol
= proto
;
669 debugs(50, 3, "comm_openex: Attempt fallback open socket for: " << addr
);
670 new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
671 debugs(50, 2, HERE
<< "attempt open " << note
<< " socket on: " << addr
);
674 if (new_socket
< 0) {
675 /* Increase the number of reserved fd's if calls to socket()
676 * are failing because the open file table is full. This
677 * limits the number of simultaneous clients */
679 if (limitError(errno
)) {
680 debugs(50, DBG_IMPORTANT
, "comm_open: socket failure: " << xstrerror());
683 debugs(50, DBG_CRITICAL
, "comm_open: socket failure: " << xstrerror());
686 addr
.FreeAddrInfo(AI
);
688 PROF_stop(comm_open
);
692 debugs(50, 3, "comm_openex: Opened socket FD " << new_socket
<< " : family=" << AI
->ai_family
<< ", type=" << AI
->ai_socktype
<< ", protocol=" << AI
->ai_protocol
);
694 /* set TOS if needed */
695 if (TOS
&& comm_set_tos(new_socket
, TOS
) ) {
699 if ( Ip::EnableIpv6
&IPV6_SPECIAL_SPLITSTACK
&& addr
.IsIPv6() )
700 comm_set_v6only(new_socket
, 1);
702 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
703 /* Other OS may have this administratively disabled for general use. Same deal. */
704 if ( Ip::EnableIpv6
&IPV6_SPECIAL_V4MAPPING
&& addr
.IsIPv6() )
705 comm_set_v6only(new_socket
, 0);
707 comm_init_opened(new_socket
, addr
, TOS
, note
, AI
);
708 new_socket
= comm_apply_flags(new_socket
, addr
, flags
, AI
);
710 addr
.FreeAddrInfo(AI
);
712 PROF_stop(comm_open
);
717 /// update FD tables after a local or remote (IPC) comm_openex();
719 comm_init_opened(int new_socket
,
725 assert(new_socket
>= 0);
731 debugs(5, 5, "comm_open: FD " << new_socket
<< " is a new socket");
733 assert(!isOpen(new_socket
));
734 fd_open(new_socket
, FD_SOCKET
, note
);
736 fdd_table
[new_socket
].close_file
= NULL
;
738 fdd_table
[new_socket
].close_line
= 0;
740 F
= &fd_table
[new_socket
];
742 F
->local_addr
= addr
;
746 F
->sock_family
= AI
->ai_family
;
749 /// apply flags after a local comm_open*() call;
750 /// returns new_socket or -1 on error
752 comm_apply_flags(int new_socket
,
757 assert(new_socket
>= 0);
759 const int sock_type
= AI
->ai_socktype
;
761 if (!(flags
& COMM_NOCLOEXEC
))
762 commSetCloseOnExec(new_socket
);
764 if ((flags
& COMM_REUSEADDR
))
765 commSetReuseAddr(new_socket
);
767 if (addr
.GetPort() > (u_short
) 0) {
769 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 ( (flags
& COMM_DOBIND
) || addr
.GetPort() > 0 || !addr
.IsAnyAddr() ) {
783 if ( !(flags
& COMM_DOBIND
) && addr
.IsAnyAddr() )
784 debugs(5,1,"WARNING: Squid is attempting to bind() port " << addr
<< " without being a listener.");
785 if ( addr
.IsNoAddr() )
786 debugs(5,0,"CRITICAL: Squid is attempting to bind() port " << addr
<< "!!");
788 if (commBind(new_socket
, *AI
) != COMM_OK
) {
789 comm_close(new_socket
);
794 if (flags
& COMM_NONBLOCKING
)
795 if (commSetNonBlocking(new_socket
) == COMM_ERROR
) {
796 comm_close(new_socket
);
801 if (sock_type
== SOCK_STREAM
)
802 commSetTcpNoDelay(new_socket
);
806 if (Config
.tcpRcvBufsz
> 0 && sock_type
== SOCK_STREAM
)
807 commSetTcpRcvbuf(new_socket
, Config
.tcpRcvBufsz
);
813 comm_import_opened(int fd
,
819 debugs(5, 2, HERE
<< " FD " << fd
<< " at " << addr
);
823 comm_init_opened(fd
, addr
, 0, note
, AI
);
825 if (!(flags
& COMM_NOCLOEXEC
))
826 fd_table
[fd
].flags
.close_on_exec
= 1;
828 if (addr
.GetPort() > (u_short
) 0) {
830 if (sock_type
!= SOCK_DGRAM
)
832 fd_table
[fd
].flags
.nolinger
= 1;
835 if ((flags
& COMM_TRANSPARENT
))
836 fd_table
[fd
].flags
.transparent
= 1;
838 if (flags
& COMM_NONBLOCKING
)
839 fd_table
[fd
].flags
.nonblocking
= 1;
842 if (AI
->ai_socktype
== SOCK_STREAM
)
843 fd_table
[fd
].flags
.nodelay
= 1;
846 /* no fd_table[fd].flags. updates needed for these conditions:
847 * if ((flags & COMM_REUSEADDR)) ...
848 * if ((flags & COMM_DOBIND) ...) ...
854 commSetTimeout_old(int fd
, int timeout
, PF
* handler
, void *data
)
856 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
858 assert(fd
< Squid_MaxFD
);
859 fde
*F
= &fd_table
[fd
];
860 assert(F
->flags
.open
);
863 cbdataReferenceDone(F
->timeout_data
);
864 F
->timeout_handler
= NULL
;
868 cbdataReferenceDone(F
->timeout_data
);
869 F
->timeout_handler
= handler
;
870 F
->timeout_data
= cbdataReference(data
);
873 F
->timeout
= squid_curtime
+ (time_t) timeout
;
881 commSetTimeout(int fd
, int timeout
, PF
* handler
, void *data
)
883 AsyncCall::Pointer call
;
884 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
886 call
=commCbCall(5,4, "SomeTimeoutHandler", CommTimeoutCbPtrFun(handler
, data
));
889 return commSetTimeout(fd
, timeout
, call
);
894 commSetTimeout(int fd
, int timeout
, AsyncCall::Pointer
&callback
)
896 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
898 assert(fd
< Squid_MaxFD
);
899 fde
*F
= &fd_table
[fd
];
900 assert(F
->flags
.open
);
903 F
->timeoutHandler
= NULL
;
906 if (callback
!= NULL
) {
907 typedef CommTimeoutCbParams Params
;
908 Params
¶ms
= GetCommParams
<Params
>(callback
);
910 F
->timeoutHandler
= callback
;
913 F
->timeout
= squid_curtime
+ (time_t) timeout
;
921 comm_connect_addr(int sock
, const Ip::Address
&address
)
923 comm_err_t status
= COMM_OK
;
924 fde
*F
= &fd_table
[sock
];
928 struct addrinfo
*AI
= NULL
;
929 PROF_start(comm_connect_addr
);
931 assert(address
.GetPort() != 0);
933 debugs(5, 9, HERE
<< "connecting socket FD " << sock
<< " to " << address
<< " (want family: " << F
->sock_family
<< ")");
935 /* Handle IPv6 over IPv4-only socket case.
936 * this case must presently be handled here since the GetAddrInfo asserts on bad mappings.
937 * NP: because commResetFD is private to ConnStateData we have to return an error and
938 * trust its handled properly.
940 if (F
->sock_family
== AF_INET
&& !address
.IsIPv4()) {
942 return COMM_ERR_PROTOCOL
;
945 /* Handle IPv4 over IPv6-only socket case.
946 * This case is presently handled here as it's both a known case and it's
947 * uncertain what error will be returned by the IPv6 stack in such case. It's
948 * possible this will also be handled by the errno checks below after connect()
949 * but needs carefull cross-platform verification, and verifying the address
950 * condition here is simple.
952 if (!F
->local_addr
.IsIPv4() && address
.IsIPv4()) {
954 return COMM_ERR_PROTOCOL
;
957 address
.GetAddrInfo(AI
, F
->sock_family
);
959 /* Establish connection. */
962 if (!F
->flags
.called_connect
) {
963 F
->flags
.called_connect
= 1;
964 statCounter
.syscalls
.sock
.connects
++;
966 x
= connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
968 // XXX: ICAP code refuses callbacks during a pending comm_ call
969 // Async calls development will fix this.
976 debugs(5,5, "comm_connect_addr: sock=" << sock
<< ", addrinfo( " <<
977 " flags=" << AI
->ai_flags
<<
978 ", family=" << AI
->ai_family
<<
979 ", socktype=" << AI
->ai_socktype
<<
980 ", protocol=" << AI
->ai_protocol
<<
981 ", &addr=" << AI
->ai_addr
<<
982 ", addrlen=" << AI
->ai_addrlen
<<
984 debugs(5, 9, "connect FD " << sock
<< ": (" << x
<< ") " << xstrerror());
985 debugs(14,9, "connecting to: " << address
);
988 #if defined(_SQUID_NEWSOS6_)
989 /* Makoto MATSUSHITA <matusita@ics.es.osaka-u.ac.jp> */
991 connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
993 if (errno
== EINVAL
) {
994 errlen
= sizeof(err
);
995 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
1002 errlen
= sizeof(err
);
1004 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
1009 #if defined(_SQUID_SOLARIS_)
1011 * Solaris 2.4's socket emulation doesn't allow you
1012 * to determine the error from a failed non-blocking
1013 * connect and just returns EPIPE. Create a fake
1014 * error message for connect. -- fenner@parc.xerox.com
1016 if (x
< 0 && errno
== EPIPE
)
1024 /* Squid seems to be working fine without this code. With this code,
1025 * we leak memory on many connect requests because of EINPROGRESS.
1026 * If you find that this code is needed, please file a bug report. */
1028 #ifdef _SQUID_LINUX_
1030 * Linux Debian replaces our allocated AI pointer with garbage when
1031 * connect() fails. This leads to segmentation faults deallocating
1032 * the system-allocated memory when we go to clean up our pointer.
1033 * HACK: is to leak the memory returned since we can't deallocate.
1041 address
.FreeAddrInfo(AI
);
1043 PROF_stop(comm_connect_addr
);
1045 if (errno
== 0 || errno
== EISCONN
)
1047 else if (ignoreErrno(errno
))
1048 status
= COMM_INPROGRESS
;
1049 else if (errno
== EAFNOSUPPORT
|| errno
== EINVAL
)
1050 return COMM_ERR_PROTOCOL
;
1054 address
.NtoA(F
->ipaddr
, MAX_IPSTRLEN
);
1056 F
->remote_port
= address
.GetPort(); /* remote_port is HS */
1058 if (status
== COMM_OK
) {
1059 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connected to " << address
);
1060 } else if (status
== COMM_INPROGRESS
) {
1061 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connection pending");
1068 commCallCloseHandlers(int fd
)
1070 fde
*F
= &fd_table
[fd
];
1071 debugs(5, 5, "commCallCloseHandlers: FD " << fd
);
1073 while (F
->closeHandler
!= NULL
) {
1074 AsyncCall::Pointer call
= F
->closeHandler
;
1075 F
->closeHandler
= call
->Next();
1076 call
->setNext(NULL
);
1077 // If call is not canceled schedule it for execution else ignore it
1078 if (!call
->canceled()) {
1079 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call
);
1080 typedef CommCloseCbParams Params
;
1081 Params
¶ms
= GetCommParams
<Params
>(call
);
1083 ScheduleCallHere(call
);
1090 commLingerClose(int fd
, void *unused
)
1092 LOCAL_ARRAY(char, buf
, 1024);
1094 n
= FD_READ_METHOD(fd
, buf
, 1024);
1097 debugs(5, 3, "commLingerClose: FD " << fd
<< " read: " << xstrerror());
1103 commLingerTimeout(int fd
, void *unused
)
1105 debugs(5, 3, "commLingerTimeout: FD " << fd
);
1110 * Inspired by apache
1113 comm_lingering_close(int fd
)
1117 if (fd_table
[fd
].ssl
)
1118 ssl_shutdown_method(fd
);
1122 if (shutdown(fd
, 1) < 0) {
1127 fd_note(fd
, "lingering close");
1128 commSetTimeout(fd
, 10, commLingerTimeout
, NULL
);
1129 commSetSelect(fd
, COMM_SELECT_READ
, commLingerClose
, NULL
, 0);
1135 * enable linger with time of 0 so that when the socket is
1136 * closed, TCP generates a RESET
1139 comm_reset_close(int fd
)
1146 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1147 debugs(50, DBG_CRITICAL
, "ERROR: Closing FD " << fd
<< " with TCP RST: " << xstrerror());
1153 comm_close_start(int fd
, void *data
)
1156 fde
*F
= &fd_table
[fd
];
1158 ssl_shutdown_method(fd
);
1165 comm_close_complete(int fd
, void *data
)
1168 fde
*F
= &fd_table
[fd
];
1176 fd_close(fd
); /* update fdstat */
1180 statCounter
.syscalls
.sock
.closes
++;
1182 /* When an fd closes, give accept() a chance, if need be */
1183 Comm::AcceptLimiter::Instance().kick();
1187 * Close the socket fd.
1189 * + call write handlers with ERR_CLOSING
1190 * + call read handlers with ERR_CLOSING
1191 * + call closing handlers
1193 * NOTE: COMM_ERR_CLOSING will NOT be called for CommReads' sitting in a
1194 * DeferredReadManager.
1197 _comm_close(int fd
, char const *file
, int line
)
1199 debugs(5, 3, "comm_close: start closing FD " << fd
);
1201 assert(fd
< Squid_MaxFD
);
1203 fde
*F
= &fd_table
[fd
];
1204 fdd_table
[fd
].close_file
= file
;
1205 fdd_table
[fd
].close_line
= line
;
1210 /* XXX: is this obsolete behind F->closing() ? */
1211 if ( (shutting_down
|| reconfiguring
) && (!F
->flags
.open
|| F
->type
== FD_FILE
))
1214 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
1217 assert(F
->type
!= FD_FILE
);
1219 PROF_start(comm_close
);
1221 F
->flags
.close_request
= 1;
1223 AsyncCall::Pointer startCall
=commCbCall(5,4, "comm_close_start",
1224 CommCloseCbPtrFun(comm_close_start
, NULL
));
1225 typedef CommCloseCbParams Params
;
1226 Params
&startParams
= GetCommParams
<Params
>(startCall
);
1227 startParams
.fd
= fd
;
1228 ScheduleCallHere(startCall
);
1230 // a half-closed fd may lack a reader, so we stop monitoring explicitly
1231 if (commHasHalfClosedMonitor(fd
))
1232 commStopHalfClosedMonitor(fd
);
1233 commSetTimeout(fd
, -1, NULL
, NULL
);
1235 // notify read/write handlers
1236 if (commio_has_callback(fd
, IOCB_WRITE
, COMMIO_FD_WRITECB(fd
))) {
1237 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), COMM_ERR_CLOSING
, errno
);
1239 if (commio_has_callback(fd
, IOCB_READ
, COMMIO_FD_READCB(fd
))) {
1240 commio_finish_callback(fd
, COMMIO_FD_READCB(fd
), COMM_ERR_CLOSING
, errno
);
1243 commCallCloseHandlers(fd
);
1246 F
->pconn
.pool
->count(F
->pconn
.uses
);
1248 comm_empty_os_read_buffers(fd
);
1251 AsyncCall::Pointer completeCall
=commCbCall(5,4, "comm_close_complete",
1252 CommCloseCbPtrFun(comm_close_complete
, NULL
));
1253 Params
&completeParams
= GetCommParams
<Params
>(completeCall
);
1254 completeParams
.fd
= fd
;
1255 // must use async call to wait for all callbacks
1256 // scheduled before comm_close() to finish
1257 ScheduleCallHere(completeCall
);
1259 PROF_stop(comm_close
);
1262 /* Send a udp datagram to specified TO_ADDR. */
1264 comm_udp_sendto(int fd
,
1265 const Ip::Address
&to_addr
,
1270 struct addrinfo
*AI
= NULL
;
1272 PROF_start(comm_udp_sendto
);
1273 statCounter
.syscalls
.sock
.sendtos
++;
1275 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr
<<
1276 " using FD " << fd
<< " using Port " << comm_local_port(fd
) );
1278 /* BUG: something in the above macro appears to occasionally be setting AI to garbage. */
1279 /* AYJ: 2007-08-27 : or was it because I wasn't then setting 'fd_table[fd].sock_family' to fill properly. */
1280 assert( NULL
== AI
);
1282 to_addr
.GetAddrInfo(AI
, fd_table
[fd
].sock_family
);
1284 x
= sendto(fd
, buf
, len
, 0, AI
->ai_addr
, AI
->ai_addrlen
);
1286 to_addr
.FreeAddrInfo(AI
);
1288 PROF_stop(comm_udp_sendto
);
1293 #ifdef _SQUID_LINUX_
1295 if (ECONNREFUSED
!= errno
)
1298 debugs(50, 1, "comm_udp_sendto: FD " << fd
<< ", (family=" << fd_table
[fd
].sock_family
<< ") " << to_addr
<< ": " << xstrerror());
1304 comm_add_close_handler(int fd
, PF
* handler
, void *data
)
1306 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", handler=" <<
1307 handler
<< ", data=" << data
);
1309 AsyncCall::Pointer call
=commCbCall(5,4, "SomeCloseHandler",
1310 CommCloseCbPtrFun(handler
, data
));
1311 comm_add_close_handler(fd
, call
);
1315 comm_add_close_handler(int fd
, AsyncCall::Pointer
&call
)
1317 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1319 /*TODO:Check for a similar scheduled AsyncCall*/
1320 // for (c = fd_table[fd].closeHandler; c; c = c->next)
1321 // assert(c->handler != handler || c->data != data);
1323 call
->setNext(fd_table
[fd
].closeHandler
);
1325 fd_table
[fd
].closeHandler
= call
;
1329 // remove function-based close handler
1331 comm_remove_close_handler(int fd
, PF
* handler
, void *data
)
1333 assert (isOpen(fd
));
1334 /* Find handler in list */
1335 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", handler=" <<
1336 handler
<< ", data=" << data
);
1338 AsyncCall::Pointer p
;
1339 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
; p
= p
->Next()) {
1340 typedef CommCbFunPtrCallT
<CommCloseCbPtrFun
> Call
;
1341 const Call
*call
= dynamic_cast<const Call
*>(p
.getRaw());
1342 if (!call
) // method callbacks have their own comm_remove_close_handler
1345 typedef CommCloseCbParams Params
;
1346 const Params
¶ms
= GetCommParams
<Params
>(p
);
1347 if (call
->dialer
.handler
== handler
&& params
.data
== data
)
1348 break; /* This is our handler */
1351 // comm_close removes all close handlers so our handler may be gone
1353 p
->cancel("comm_remove_close_handler");
1354 // TODO: should we remove the handler from the close handlers list?
1357 // remove method-based close handler
1359 comm_remove_close_handler(int fd
, AsyncCall::Pointer
&call
)
1361 assert (isOpen(fd
));
1362 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1364 // comm_close removes all close handlers so our handler may be gone
1365 // TODO: should we remove the handler from the close handlers list?
1367 // Check to see if really exist the given AsyncCall in comm_close handlers
1368 // TODO: optimize: this slow code is only needed for the assert() below
1369 AsyncCall::Pointer p
;
1370 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
&& p
!= call
; p
= p
->Next());
1374 call
->cancel("comm_remove_close_handler");
1378 commSetNoLinger(int fd
)
1382 L
.l_onoff
= 0; /* off */
1385 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1386 debugs(50, 0, "commSetNoLinger: FD " << fd
<< ": " << xstrerror());
1388 fd_table
[fd
].flags
.nolinger
= 1;
1392 commSetReuseAddr(int fd
)
1396 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &on
, sizeof(on
)) < 0)
1397 debugs(50, 1, "commSetReuseAddr: FD " << fd
<< ": " << xstrerror());
1401 commSetTcpRcvbuf(int fd
, int size
)
1403 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, (char *) &size
, sizeof(size
)) < 0)
1404 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1405 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, (char *) &size
, sizeof(size
)) < 0)
1406 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1407 #ifdef TCP_WINDOW_CLAMP
1408 if (setsockopt(fd
, SOL_TCP
, TCP_WINDOW_CLAMP
, (char *) &size
, sizeof(size
)) < 0)
1409 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1414 commSetNonBlocking(int fd
)
1416 #ifndef _SQUID_MSWIN_
1420 #ifdef _SQUID_WIN32_
1422 int nonblocking
= TRUE
;
1424 #ifdef _SQUID_CYGWIN_
1426 if (fd_table
[fd
].type
!= FD_PIPE
) {
1429 if (ioctl(fd
, FIONBIO
, &nonblocking
) < 0) {
1430 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror() << " " << fd_table
[fd
].type
);
1434 #ifdef _SQUID_CYGWIN_
1439 #ifndef _SQUID_MSWIN_
1441 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1442 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1446 if (fcntl(fd
, F_SETFL
, flags
| SQUID_NONBLOCK
) < 0) {
1447 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror());
1452 #ifdef _SQUID_CYGWIN_
1457 fd_table
[fd
].flags
.nonblocking
= 1;
1463 commUnsetNonBlocking(int fd
)
1465 #ifdef _SQUID_MSWIN_
1466 int nonblocking
= FALSE
;
1468 if (ioctlsocket(fd
, FIONBIO
, (unsigned long *) &nonblocking
) < 0) {
1473 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1474 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1478 if (fcntl(fd
, F_SETFL
, flags
& (~SQUID_NONBLOCK
)) < 0) {
1480 debugs(50, 0, "commUnsetNonBlocking: FD " << fd
<< ": " << xstrerror());
1484 fd_table
[fd
].flags
.nonblocking
= 0;
1489 commSetCloseOnExec(int fd
)
1495 if ((flags
= fcntl(fd
, F_GETFD
, dummy
)) < 0) {
1496 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFD: " << xstrerror());
1500 if (fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) < 0)
1501 debugs(50, 0, "FD " << fd
<< ": set close-on-exec failed: " << xstrerror());
1503 fd_table
[fd
].flags
.close_on_exec
= 1;
1510 commSetTcpNoDelay(int fd
)
1514 if (setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *) &on
, sizeof(on
)) < 0)
1515 debugs(50, 1, "commSetTcpNoDelay: FD " << fd
<< ": " << xstrerror());
1517 fd_table
[fd
].flags
.nodelay
= 1;
1523 commSetTcpKeepalive(int fd
, int idle
, int interval
, int timeout
)
1527 if (timeout
&& interval
) {
1528 int count
= (timeout
+ interval
- 1) / interval
;
1529 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPCNT
, &count
, sizeof(on
)) < 0)
1530 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1535 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, &idle
, sizeof(on
)) < 0)
1536 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1539 #ifdef TCP_KEEPINTVL
1541 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, &interval
, sizeof(on
)) < 0)
1542 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1545 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char *) &on
, sizeof(on
)) < 0)
1546 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1552 fd_table
=(fde
*) xcalloc(Squid_MaxFD
, sizeof(fde
));
1553 fdd_table
= (fd_debug_t
*)xcalloc(Squid_MaxFD
, sizeof(fd_debug_t
));
1555 /* make sure the accept() socket FIFO delay queue exists */
1556 Comm::AcceptLimiter::Instance();
1558 commfd_table
= (comm_fd_t
*) xcalloc(Squid_MaxFD
, sizeof(comm_fd_t
));
1559 for (int pos
= 0; pos
< Squid_MaxFD
; pos
++) {
1560 commfd_table
[pos
].fd
= pos
;
1561 commfd_table
[pos
].readcb
.fd
= pos
;
1562 commfd_table
[pos
].readcb
.type
= IOCB_READ
;
1563 commfd_table
[pos
].writecb
.fd
= pos
;
1564 commfd_table
[pos
].writecb
.type
= IOCB_WRITE
;
1567 /* XXX account fd_table */
1568 /* Keep a few file descriptors free so that we don't run out of FD's
1569 * after accepting a client but before it opens a socket or a file.
1570 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
1571 RESERVED_FD
= min(100, Squid_MaxFD
/ 4);
1573 conn_close_pool
= memPoolCreate("close_handler", sizeof(close_handler
));
1575 TheHalfClosed
= new DescriptorSet
;
1581 delete TheHalfClosed
;
1582 TheHalfClosed
= NULL
;
1584 safe_free(fd_table
);
1585 safe_free(fdd_table
);
1586 safe_free(commfd_table
);
1591 commHandleWrite(int fd
, void *data
)
1593 comm_io_callback_t
*state
= (comm_io_callback_t
*)data
;
1597 assert(state
== COMMIO_FD_WRITECB(fd
));
1599 PROF_start(commHandleWrite
);
1600 debugs(5, 5, "commHandleWrite: FD " << fd
<< ": off " <<
1601 (long int) state
->offset
<< ", sz " << (long int) state
->size
<< ".");
1603 nleft
= state
->size
- state
->offset
;
1604 len
= FD_WRITE_METHOD(fd
, state
->buf
+ state
->offset
, nleft
);
1605 debugs(5, 5, "commHandleWrite: write() returns " << len
);
1606 fd_bytes(fd
, len
, FD_WRITE
);
1607 statCounter
.syscalls
.sock
.writes
++;
1608 // After each successful partial write,
1609 // reset fde::writeStart to the current time.
1610 fd_table
[fd
].writeStart
= squid_curtime
;
1613 /* Note we even call write if nleft == 0 */
1617 debugs(5, 1, "commHandleWrite: FD " << fd
<< ": write failure: connection closed with " << nleft
<< " bytes remaining.");
1619 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1620 } else if (len
< 0) {
1623 if (fd_table
[fd
].flags
.socket_eof
) {
1624 debugs(50, 2, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1625 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1626 } else if (ignoreErrno(errno
)) {
1627 debugs(50, 10, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1634 debugs(50, 2, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1635 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1638 /* A successful write, continue */
1639 state
->offset
+= len
;
1641 if (state
->offset
< state
->size
) {
1642 /* Not done, reinstall the write handler and write some more */
1649 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_OK
: COMM_ERROR
, errno
);
1653 PROF_stop(commHandleWrite
);
1657 * Queue a write. handler/handler_data are called when the write
1658 * completes, on error, or on file descriptor close.
1660 * free_func is used to free the passed buffer when the write has completed.
1663 comm_write(int fd
, const char *buf
, int size
, IOCB
* handler
, void *handler_data
, FREE
* free_func
)
1665 AsyncCall::Pointer call
= commCbCall(5,5, "SomeCommWriteHander",
1666 CommIoCbPtrFun(handler
, handler_data
));
1668 comm_write(fd
, buf
, size
, call
, free_func
);
1672 comm_write(int fd
, const char *buf
, int size
, AsyncCall::Pointer
&callback
, FREE
* free_func
)
1674 debugs(5, 5, "comm_write: FD " << fd
<< ": sz " << size
<< ": asynCall " << callback
);
1676 /* Make sure we are open, not closing, and not writing */
1678 assert(!fd_table
[fd
].closing());
1679 comm_io_callback_t
*ccb
= COMMIO_FD_WRITECB(fd
);
1680 assert(!ccb
->active());
1682 fd_table
[fd
].writeStart
= squid_curtime
;
1683 /* Queue the write */
1684 commio_set_callback(fd
, IOCB_WRITE
, ccb
, callback
,
1685 (char *)buf
, free_func
, size
);
1686 commSetSelect(fd
, COMM_SELECT_WRITE
, commHandleWrite
, ccb
, 0);
1690 /* a wrapper around comm_write to allow for MemBuf to be comm_written in a snap */
1692 comm_write_mbuf(int fd
, MemBuf
*mb
, IOCB
* handler
, void *handler_data
)
1694 comm_write(fd
, mb
->buf
, mb
->size
, handler
, handler_data
, mb
->freeFunc());
1698 comm_write_mbuf(int fd
, MemBuf
*mb
, AsyncCall::Pointer
&callback
)
1700 comm_write(fd
, mb
->buf
, mb
->size
, callback
, mb
->freeFunc());
1705 * hm, this might be too general-purpose for all the places we'd
1709 ignoreErrno(int ierrno
)
1716 #if EAGAIN != EWOULDBLOCK
1739 commCloseAllSockets(void)
1744 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
1750 if (F
->type
!= FD_SOCKET
)
1753 if (F
->flags
.ipc
) /* don't close inter-process sockets */
1756 if (F
->timeoutHandler
!= NULL
) {
1757 AsyncCall::Pointer callback
= F
->timeoutHandler
;
1758 F
->timeoutHandler
= NULL
;
1759 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": Calling timeout handler");
1760 ScheduleCallHere(callback
);
1762 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": calling comm_reset_close()");
1763 comm_reset_close(fd
);
1769 AlreadyTimedOut(fde
*F
)
1774 if (F
->timeout
== 0)
1777 if (F
->timeout
> squid_curtime
)
1784 writeTimedOut(int fd
)
1786 if (!commio_has_callback(fd
, IOCB_WRITE
, COMMIO_FD_WRITECB(fd
)))
1789 if ((squid_curtime
- fd_table
[fd
].writeStart
) < Config
.Timeout
.write
)
1800 AsyncCall::Pointer callback
;
1802 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
1805 if (writeTimedOut(fd
)) {
1806 // We have an active write callback and we are timed out
1807 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), COMM_ERROR
, ETIMEDOUT
);
1808 } else if (AlreadyTimedOut(F
))
1811 debugs(5, 5, "checkTimeouts: FD " << fd
<< " Expired");
1813 if (F
->timeoutHandler
!= NULL
) {
1814 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Call timeout handler");
1815 callback
= F
->timeoutHandler
;
1816 F
->timeoutHandler
= NULL
;
1817 ScheduleCallHere(callback
);
1819 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Forcing comm_close()");
1825 void CommIO::Initialise()
1827 /* Initialize done pipe signal */
1829 if (pipe(DonePipe
)) {}
1830 DoneFD
= DonePipe
[1];
1831 DoneReadFD
= DonePipe
[0];
1832 fd_open(DoneReadFD
, FD_PIPE
, "async-io completetion event: main");
1833 fd_open(DoneFD
, FD_PIPE
, "async-io completetion event: threads");
1834 commSetNonBlocking(DoneReadFD
);
1835 commSetNonBlocking(DoneFD
);
1836 commSetSelect(DoneReadFD
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
1840 void CommIO::NotifyIOClose()
1842 /* Close done pipe signal */
1847 fd_close(DoneReadFD
);
1848 Initialised
= false;
1851 bool CommIO::Initialised
= false;
1852 bool CommIO::DoneSignalled
= false;
1853 int CommIO::DoneFD
= -1;
1854 int CommIO::DoneReadFD
= -1;
1860 FD_READ_METHOD(DoneReadFD
, buf
, sizeof(buf
));
1864 CommIO::NULLFDHandler(int fd
, void *data
)
1867 commSetSelect(fd
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
1871 CommIO::ResetNotifications()
1873 if (DoneSignalled
) {
1875 DoneSignalled
= false;
1879 /// Start waiting for a possibly half-closed connection to close
1880 // by scheduling a read callback to a monitoring handler that
1881 // will close the connection on read errors.
1883 commStartHalfClosedMonitor(int fd
)
1885 debugs(5, 5, HERE
<< "adding FD " << fd
<< " to " << *TheHalfClosed
);
1887 assert(!commHasHalfClosedMonitor(fd
));
1888 (void)TheHalfClosed
->add(fd
); // could also assert the result
1889 commPlanHalfClosedCheck(); // may schedule check if we added the first FD
1894 commPlanHalfClosedCheck()
1896 if (!WillCheckHalfClosed
&& !TheHalfClosed
->empty()) {
1897 eventAdd("commHalfClosedCheck", &commHalfClosedCheck
, NULL
, 1.0, 1);
1898 WillCheckHalfClosed
= true;
1902 /// iterates over all descriptors that may need half-closed tests and
1903 /// calls comm_read for those that do; re-schedules the check if needed
1906 commHalfClosedCheck(void *)
1908 debugs(5, 5, HERE
<< "checking " << *TheHalfClosed
);
1910 typedef DescriptorSet::const_iterator DSCI
;
1911 const DSCI end
= TheHalfClosed
->end();
1912 for (DSCI i
= TheHalfClosed
->begin(); i
!= end
; ++i
) {
1914 if (!fd_table
[fd
].halfClosedReader
) { // not reading already
1915 AsyncCall::Pointer call
= commCbCall(5,4, "commHalfClosedReader",
1916 CommIoCbPtrFun(&commHalfClosedReader
, NULL
));
1917 comm_read(fd
, NULL
, 0, call
);
1918 fd_table
[fd
].halfClosedReader
= call
;
1922 WillCheckHalfClosed
= false; // as far as we know
1923 commPlanHalfClosedCheck(); // may need to check again
1926 /// checks whether we are waiting for possibly half-closed connection to close
1927 // We are monitoring if the read handler for the fd is the monitoring handler.
1929 commHasHalfClosedMonitor(int fd
)
1931 return TheHalfClosed
->has(fd
);
1934 /// stop waiting for possibly half-closed connection to close
1936 commStopHalfClosedMonitor(int const fd
)
1938 debugs(5, 5, HERE
<< "removing FD " << fd
<< " from " << *TheHalfClosed
);
1940 // cancel the read if one was scheduled
1941 AsyncCall::Pointer reader
= fd_table
[fd
].halfClosedReader
;
1943 comm_read_cancel(fd
, reader
);
1944 fd_table
[fd
].halfClosedReader
= NULL
;
1946 TheHalfClosed
->del(fd
);
1949 /// I/O handler for the possibly half-closed connection monitoring code
1951 commHalfClosedReader(int fd
, char *, size_t size
, comm_err_t flag
, int, void *)
1953 // there cannot be more data coming in on half-closed connections
1955 assert(commHasHalfClosedMonitor(fd
)); // or we would have canceled the read
1957 fd_table
[fd
].halfClosedReader
= NULL
; // done reading, for now
1959 // nothing to do if fd is being closed
1960 if (flag
== COMM_ERR_CLOSING
)
1963 // if read failed, close the connection
1964 if (flag
!= COMM_OK
) {
1965 debugs(5, 3, "commHalfClosedReader: closing FD " << fd
);
1970 // continue waiting for close or error
1971 commPlanHalfClosedCheck(); // make sure this fd will be checked again
1975 CommRead::CommRead() : fd(-1), buf(NULL
), len(0), callback(NULL
) {}
1977 CommRead::CommRead(int fd_
, char *buf_
, int len_
, AsyncCall::Pointer
&callback_
)
1978 : fd(fd_
), buf(buf_
), len(len_
), callback(callback_
) {}
1980 DeferredRead::DeferredRead () : theReader(NULL
), theContext(NULL
), theRead(), cancelled(false) {}
1982 DeferredRead::DeferredRead (DeferrableRead
*aReader
, void *data
, CommRead
const &aRead
) : theReader(aReader
), theContext (data
), theRead(aRead
), cancelled(false) {}
1984 DeferredReadManager::~DeferredReadManager()
1987 assert (deferredReads
.empty());
1990 /* explicit instantiation required for some systems */
1992 /// \cond AUTODOCS-IGNORE
1993 template cbdata_type CbDataList
<DeferredRead
>::CBDATA_CbDataList
;
1997 DeferredReadManager::delayRead(DeferredRead
const &aRead
)
1999 debugs(5, 3, "Adding deferred read on FD " << aRead
.theRead
.fd
);
2000 CbDataList
<DeferredRead
> *temp
= deferredReads
.push_back(aRead
);
2002 // We have to use a global function as a closer and point to temp
2003 // instead of "this" because DeferredReadManager is not a job and
2004 // is not even cbdata protected
2005 AsyncCall::Pointer closer
= commCbCall(5,4,
2006 "DeferredReadManager::CloseHandler",
2007 CommCloseCbPtrFun(&CloseHandler
, temp
));
2008 comm_add_close_handler(aRead
.theRead
.fd
, closer
);
2009 temp
->element
.closer
= closer
; // remeber so that we can cancel
2013 DeferredReadManager::CloseHandler(int fd
, void *thecbdata
)
2015 if (!cbdataReferenceValid (thecbdata
))
2018 CbDataList
<DeferredRead
> *temp
= (CbDataList
<DeferredRead
> *)thecbdata
;
2020 temp
->element
.closer
= NULL
;
2021 temp
->element
.markCancelled();
2025 DeferredReadManager::popHead(CbDataListContainer
<DeferredRead
> &deferredReads
)
2027 assert (!deferredReads
.empty());
2029 DeferredRead
&read
= deferredReads
.head
->element
;
2030 if (!read
.cancelled
) {
2031 comm_remove_close_handler(read
.theRead
.fd
, read
.closer
);
2035 DeferredRead result
= deferredReads
.pop_front();
2041 DeferredReadManager::kickReads(int const count
)
2043 /* if we had CbDataList::size() we could consolidate this and flushReads */
2050 size_t remaining
= count
;
2052 while (!deferredReads
.empty() && remaining
) {
2053 DeferredRead aRead
= popHead(deferredReads
);
2056 if (!aRead
.cancelled
)
2062 DeferredReadManager::flushReads()
2064 CbDataListContainer
<DeferredRead
> reads
;
2065 reads
= deferredReads
;
2066 deferredReads
= CbDataListContainer
<DeferredRead
>();
2068 // XXX: For fairness this SHOULD randomize the order
2069 while (!reads
.empty()) {
2070 DeferredRead aRead
= popHead(reads
);
2076 DeferredReadManager::kickARead(DeferredRead
const &aRead
)
2078 if (aRead
.cancelled
)
2081 if (aRead
.theRead
.fd
>=0 && fd_table
[aRead
.theRead
.fd
].closing())
2084 debugs(5, 3, "Kicking deferred read on FD " << aRead
.theRead
.fd
);
2086 aRead
.theReader(aRead
.theContext
, aRead
.theRead
);
2090 DeferredRead::markCancelled()
2096 CommSelectEngine::checkEvents(int timeout
)
2098 static time_t last_timeout
= 0;
2100 /* No, this shouldn't be here. But it shouldn't be in each comm handler. -adrian */
2101 if (squid_curtime
> last_timeout
) {
2102 last_timeout
= squid_curtime
;
2106 switch (comm_select(timeout
)) {
2122 fatal_dump("comm.cc: Internal error -- this should never happen.");
2127 /// Create a unix-domain socket (UDS) that only supports FD_MSGHDR I/O.
2129 comm_open_uds(int sock_type
,
2131 struct sockaddr_un
* addr
,
2134 // TODO: merge with comm_openex() when Ip::Address becomes NetAddress
2138 PROF_start(comm_open
);
2139 /* Create socket for accepting new connections. */
2140 statCounter
.syscalls
.sock
.sockets
++;
2142 /* Setup the socket addrinfo details for use */
2145 AI
.ai_family
= PF_UNIX
;
2146 AI
.ai_socktype
= sock_type
;
2147 AI
.ai_protocol
= proto
;
2148 AI
.ai_addrlen
= SUN_LEN(addr
);
2149 AI
.ai_addr
= (sockaddr
*)addr
;
2150 AI
.ai_canonname
= NULL
;
2153 debugs(50, 3, HERE
<< "Attempt open socket for: " << addr
->sun_path
);
2155 if ((new_socket
= socket(AI
.ai_family
, AI
.ai_socktype
, AI
.ai_protocol
)) < 0) {
2156 /* Increase the number of reserved fd's if calls to socket()
2157 * are failing because the open file table is full. This
2158 * limits the number of simultaneous clients */
2160 if (limitError(errno
)) {
2161 debugs(50, DBG_IMPORTANT
, HERE
<< "socket failure: " << xstrerror());
2164 debugs(50, DBG_CRITICAL
, HERE
<< "socket failure: " << xstrerror());
2167 PROF_stop(comm_open
);
2171 debugs(50, 3, HERE
"Opened UDS FD " << new_socket
<< " : family=" << AI
.ai_family
<< ", type=" << AI
.ai_socktype
<< ", protocol=" << AI
.ai_protocol
);
2174 debugs(50, 5, HERE
<< "FD " << new_socket
<< " is a new socket");
2176 assert(!isOpen(new_socket
));
2177 fd_open(new_socket
, FD_MSGHDR
, NULL
);
2179 fdd_table
[new_socket
].close_file
= NULL
;
2181 fdd_table
[new_socket
].close_line
= 0;
2183 fd_table
[new_socket
].sock_family
= AI
.ai_family
;
2185 if (!(flags
& COMM_NOCLOEXEC
))
2186 commSetCloseOnExec(new_socket
);
2188 if (flags
& COMM_REUSEADDR
)
2189 commSetReuseAddr(new_socket
);
2191 if (flags
& COMM_NONBLOCKING
) {
2192 if (commSetNonBlocking(new_socket
) != COMM_OK
) {
2193 comm_close(new_socket
);
2194 PROF_stop(comm_open
);
2199 if (flags
& COMM_DOBIND
) {
2200 if (commBind(new_socket
, AI
) != COMM_OK
) {
2201 comm_close(new_socket
);
2202 PROF_stop(comm_open
);
2208 if (sock_type
== SOCK_STREAM
)
2209 commSetTcpNoDelay(new_socket
);
2213 if (Config
.tcpRcvBufsz
> 0 && sock_type
== SOCK_STREAM
)
2214 commSetTcpRcvbuf(new_socket
, Config
.tcpRcvBufsz
);
2216 PROF_stop(comm_open
);