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"
48 #include "SquidTime.h"
49 #include "CommCalls.h"
50 #include "DescriptorSet.h"
51 #include "icmp/net_db.h"
52 #include "ip/Address.h"
53 #include "ip/Intercept.h"
56 #if defined(_SQUID_CYGWIN_)
57 #include <sys/ioctl.h>
59 #ifdef HAVE_NETINET_TCP_H
60 #include <netinet/tcp.h>
64 * New C-like simple comm code. This stuff is a mess and doesn't really buy us anything.
73 static void commStopHalfClosedMonitor(int fd
);
74 static IOCB commHalfClosedReader
;
75 static void comm_init_opened(int new_socket
, Ip::Address
&addr
, unsigned char TOS
, const char *note
, struct addrinfo
*AI
);
76 static int comm_apply_flags(int new_socket
, Ip::Address
&addr
, int flags
, struct addrinfo
*AI
);
79 struct comm_io_callback_t
{
82 AsyncCall::Pointer callback
;
90 bool active() const { return callback
!= NULL
; }
95 comm_io_callback_t readcb
;
96 comm_io_callback_t writecb
;
98 typedef struct _comm_fd comm_fd_t
;
99 comm_fd_t
*commfd_table
;
101 // TODO: make this a comm_io_callback_t method?
103 commio_has_callback(int fd
, iocb_type type
, comm_io_callback_t
*ccb
)
105 assert(ccb
->fd
== fd
);
106 assert(ccb
->type
== type
);
107 return ccb
->active();
111 * Configure comm_io_callback_t for I/O
113 * @param fd filedescriptor
114 * @param ccb comm io callback
116 * @param cbdata callback data (must be cbdata'ed)
117 * @param buf buffer, if applicable
118 * @param freefunc freefunc, if applicable
119 * @param size buffer size
122 commio_set_callback(int fd
, iocb_type type
, comm_io_callback_t
*ccb
,
123 AsyncCall::Pointer
&cb
, char *buf
, FREE
*freefunc
, int size
)
125 assert(!ccb
->active());
126 assert(ccb
->type
== type
);
131 ccb
->freefunc
= freefunc
;
137 // Schedule the callback call and clear the callback
139 commio_finish_callback(int fd
, comm_io_callback_t
*ccb
, comm_err_t code
, int xerrno
)
141 debugs(5, 3, "commio_finish_callback: called for FD " << fd
<< " (" <<
142 code
<< ", " << xerrno
<< ")");
143 assert(ccb
->active());
144 assert(ccb
->fd
== fd
);
146 ccb
->xerrno
= xerrno
;
148 comm_io_callback_t cb
= *ccb
;
150 /* We've got a copy; blow away the real one */
151 /* XXX duplicate code from commio_cancel_callback! */
153 ccb
->callback
= NULL
; // cb has it
161 if (cb
.callback
!= NULL
) {
162 typedef CommIoCbParams Params
;
163 Params
¶ms
= GetCommParams
<Params
>(cb
.callback
);
166 params
.size
= cb
.offset
;
167 params
.flag
= cb
.errcode
;
168 params
.xerrno
= cb
.xerrno
;
169 ScheduleCallHere(cb
.callback
);
175 * Cancel the given callback
177 * Remember that the data is cbdataRef'ed.
179 // TODO: make this a comm_io_callback_t method
181 commio_cancel_callback(int fd
, comm_io_callback_t
*ccb
)
183 debugs(5, 3, "commio_cancel_callback: called for FD " << fd
);
184 assert(ccb
->fd
== fd
);
185 assert(ccb
->active());
188 ccb
->callback
= NULL
;
192 * Call the given comm callback; assumes the callback is valid.
194 * @param ccb io completion callback
197 commio_call_callback(comm_io_callback_t
*ccb
)
203 static DescriptorSet
*TheHalfClosed
= NULL
; /// the set of half-closed FDs
204 static bool WillCheckHalfClosed
= false; /// true if check is scheduled
205 static EVH commHalfClosedCheck
;
206 static void commPlanHalfClosedCheck();
208 static comm_err_t
commBind(int s
, struct addrinfo
&);
209 static void commSetReuseAddr(int);
210 static void commSetNoLinger(int);
212 static void commSetTcpNoDelay(int);
214 static void commSetTcpRcvbuf(int, int);
215 static PF commHandleWrite
;
222 static MemAllocator
*conn_close_pool
= NULL
;
223 fd_debug_t
*fdd_table
= NULL
;
228 return fd_table
[fd
].flags
.open
!= 0;
234 * If the read attempt succeeds or fails, call the callback.
235 * Else, wait for another IO notification.
238 commHandleRead(int fd
, void *data
)
240 comm_io_callback_t
*ccb
= (comm_io_callback_t
*) data
;
242 assert(data
== COMMIO_FD_READCB(fd
));
243 assert(commio_has_callback(fd
, IOCB_READ
, ccb
));
245 statCounter
.syscalls
.sock
.reads
++;
248 retval
= FD_READ_METHOD(fd
, ccb
->buf
, ccb
->size
);
249 debugs(5, 3, "comm_read_try: FD " << fd
<< ", size " << ccb
->size
<< ", retval " << retval
<< ", errno " << errno
);
251 if (retval
< 0 && !ignoreErrno(errno
)) {
252 debugs(5, 3, "comm_read_try: scheduling COMM_ERROR");
254 commio_finish_callback(fd
, ccb
, COMM_ERROR
, errno
);
258 /* See if we read anything */
259 /* Note - read 0 == socket EOF, which is a valid read */
261 fd_bytes(fd
, retval
, FD_READ
);
262 ccb
->offset
= retval
;
263 commio_finish_callback(fd
, ccb
, COMM_OK
, errno
);
267 /* Nope, register for some more IO */
268 commSetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, data
, 0);
272 * Queue a read. handler/handler_data are called when the read
273 * completes, on error, or on file descriptor close.
276 comm_read(int fd
, char *buf
, int size
, IOCB
*handler
, void *handler_data
)
278 AsyncCall::Pointer call
= commCbCall(5,4, "SomeCommReadHandler",
279 CommIoCbPtrFun(handler
, handler_data
));
280 comm_read(fd
, buf
, size
, call
);
284 comm_read(int fd
, char *buf
, int size
, AsyncCall::Pointer
&callback
)
286 debugs(5, 5, "comm_read, queueing read for FD " << fd
<< "; asynCall " << callback
);
288 /* Make sure we are open and not closing */
290 assert(!fd_table
[fd
].closing());
291 comm_io_callback_t
*ccb
= COMMIO_FD_READCB(fd
);
293 // Make sure we are either not reading or just passively monitoring.
294 // Active/passive conflicts are OK and simply cancel passive monitoring.
296 // if the assertion below fails, we have an active comm_read conflict
297 assert(fd_table
[fd
].halfClosedReader
!= NULL
);
298 commStopHalfClosedMonitor(fd
);
299 assert(!ccb
->active());
303 commio_set_callback(fd
, IOCB_READ
, ccb
, callback
, (char *)buf
, NULL
, size
);
304 commSetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, ccb
, 0);
308 * Empty the read buffers
310 * This is a magical routine that empties the read buffers.
311 * Under some platforms (Linux) if a buffer has data in it before
312 * you call close(), the socket will hang and take quite a while
316 comm_empty_os_read_buffers(int fd
)
319 /* prevent those nasty RST packets */
320 char buf
[SQUID_TCP_SO_RCVBUF
];
322 if (fd_table
[fd
].flags
.nonblocking
== 1) {
323 while (FD_READ_METHOD(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0) {};
330 * Return whether the FD has a pending completed callback.
333 comm_has_pending_read_callback(int fd
)
336 // XXX: We do not know whether there is a read callback scheduled.
337 // This is used for pconn management that should probably be more
338 // tightly integrated into comm to minimize the chance that a
339 // closing pconn socket will be used for a new transaction.
343 // Does comm check this fd for read readiness?
344 // Note that when comm is not monitoring, there can be a pending callback
345 // call, which may resume comm monitoring once fired.
347 comm_monitors_read(int fd
)
350 // Being active is usually the same as monitoring because we always
351 // start monitoring the FD when we configure comm_io_callback_t for I/O
352 // and we usually configure comm_io_callback_t for I/O when we starting
353 // monitoring a FD for reading. TODO: replace with commio_has_callback
354 return COMMIO_FD_READCB(fd
)->active();
358 * Cancel a pending read. Assert that we have the right parameters,
359 * and that there are no pending read events!
361 * XXX: We do not assert that there are no pending read events and
362 * with async calls it becomes even more difficult.
363 * The whole interface should be reworked to do callback->cancel()
364 * instead of searching for places where the callback may be stored and
365 * updating the state of those places.
367 * AHC Don't call the comm handlers?
370 comm_read_cancel(int fd
, IOCB
*callback
, void *data
)
373 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
377 comm_io_callback_t
*cb
= COMMIO_FD_READCB(fd
);
378 // TODO: is "active" == "monitors FD"?
380 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
384 typedef CommCbFunPtrCallT
<CommIoCbPtrFun
> Call
;
385 Call
*call
= dynamic_cast<Call
*>(cb
->callback
.getRaw());
387 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " lacks callback");
391 call
->cancel("old comm_read_cancel");
393 typedef CommIoCbParams Params
;
394 const Params
¶ms
= GetCommParams
<Params
>(cb
->callback
);
396 /* Ok, we can be reasonably sure we won't lose any data here! */
397 assert(call
->dialer
.handler
== callback
);
398 assert(params
.data
== data
);
400 /* Delete the callback */
401 commio_cancel_callback(fd
, cb
);
403 /* And the IO event */
404 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
408 comm_read_cancel(int fd
, AsyncCall::Pointer
&callback
)
410 callback
->cancel("comm_read_cancel");
413 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
417 comm_io_callback_t
*cb
= COMMIO_FD_READCB(fd
);
420 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
424 AsyncCall::Pointer call
= cb
->callback
;
425 assert(call
!= NULL
); // XXX: should never fail (active() checks for callback==NULL)
427 /* Ok, we can be reasonably sure we won't lose any data here! */
428 assert(call
== callback
);
430 /* Delete the callback */
431 commio_cancel_callback(fd
, cb
);
433 /* And the IO event */
434 commSetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
439 * synchronous wrapper around udp socket functions
442 comm_udp_recvfrom(int fd
, void *buf
, size_t len
, int flags
, Ip::Address
&from
)
444 statCounter
.syscalls
.sock
.recvfroms
++;
446 struct addrinfo
*AI
= NULL
;
448 debugs(5,8, "comm_udp_recvfrom: FD " << fd
<< " from " << from
);
450 assert( NULL
== AI
);
452 from
.InitAddrInfo(AI
);
454 x
= recvfrom(fd
, buf
, len
, flags
, AI
->ai_addr
, &AI
->ai_addrlen
);
458 from
.FreeAddrInfo(AI
);
464 comm_udp_recv(int fd
, void *buf
, size_t len
, int flags
)
467 return comm_udp_recvfrom(fd
, buf
, len
, flags
, nul
);
471 comm_udp_send(int s
, const void *buf
, size_t len
, int flags
)
473 return send(s
, buf
, len
, flags
);
478 comm_has_incomplete_write(int fd
)
481 return COMMIO_FD_WRITECB(fd
)->active();
485 * Queue a write. handler/handler_data are called when the write fully
486 * completes, on error, or on file descriptor close.
489 /* Return the local port associated with fd. */
491 comm_local_port(int fd
)
494 struct addrinfo
*addr
= NULL
;
495 fde
*F
= &fd_table
[fd
];
497 /* If the fd is closed already, just return */
499 if (!F
->flags
.open
) {
500 debugs(5, 0, "comm_local_port: FD " << fd
<< " has been closed.");
504 if (F
->local_addr
.GetPort())
505 return F
->local_addr
.GetPort();
507 if (F
->sock_family
== AF_INET
)
510 temp
.InitAddrInfo(addr
);
512 if (getsockname(fd
, addr
->ai_addr
, &(addr
->ai_addrlen
)) ) {
513 debugs(50, 1, "comm_local_port: Failed to retrieve TCP/UDP port number for socket: FD " << fd
<< ": " << xstrerror());
514 temp
.FreeAddrInfo(addr
);
519 temp
.FreeAddrInfo(addr
);
521 if (F
->local_addr
.IsAnyAddr()) {
522 /* save the whole local address, not just the port. */
523 F
->local_addr
= temp
;
525 F
->local_addr
.SetPort(temp
.GetPort());
528 debugs(5, 6, "comm_local_port: FD " << fd
<< ": port " << F
->local_addr
.GetPort() << "(family=" << F
->sock_family
<< ")");
529 return F
->local_addr
.GetPort();
533 commBind(int s
, struct addrinfo
&inaddr
)
535 statCounter
.syscalls
.sock
.binds
++;
537 if (bind(s
, inaddr
.ai_addr
, inaddr
.ai_addrlen
) == 0) {
538 debugs(50, 6, "commBind: bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
);
542 debugs(50, 0, "commBind: Cannot bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
<< ": " << xstrerror());
548 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
549 * is OR of flags specified in comm.h. Defaults TOS
552 comm_open(int sock_type
,
558 return comm_openex(sock_type
, proto
, addr
, flags
, 0, note
);
562 comm_open_listener(int sock_type
,
570 /* all listener sockets require bind() */
571 flags
|= COMM_DOBIND
;
573 /* attempt native enabled port. */
574 sock
= comm_openex(sock_type
, proto
, addr
, flags
, 0, note
);
580 limitError(int const anErrno
)
582 return anErrno
== ENFILE
|| anErrno
== EMFILE
;
586 comm_set_tos(int fd
, int tos
)
589 int x
= setsockopt(fd
, IPPROTO_IP
, IP_TOS
, (char *) &tos
, sizeof(int));
591 debugs(50, 1, "comm_set_tos: setsockopt(IP_TOS) on FD " << fd
<< ": " << xstrerror());
594 debugs(50, 0, "WARNING: setsockopt(IP_TOS) not supported on this platform");
600 comm_set_v6only(int fd
, int tos
)
603 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (char *) &tos
, sizeof(int)) < 0) {
604 debugs(50, 1, "comm_open: setsockopt(IPV6_V6ONLY) " << (tos
?"ON":"OFF") << " for FD " << fd
<< ": " << xstrerror());
607 debugs(50, 0, "WARNING: comm_open: setsockopt(IPV6_V6ONLY) not supported on this platform");
612 * Set the socket IP_TRANSPARENT option for Linux TPROXY v4 support.
615 comm_set_transparent(int fd
)
617 #if defined(IP_TRANSPARENT)
619 if (setsockopt(fd
, SOL_IP
, IP_TRANSPARENT
, (char *) &tos
, sizeof(int)) < 0) {
620 debugs(50, DBG_IMPORTANT
, "comm_open: setsockopt(IP_TRANSPARENT) on FD " << fd
<< ": " << xstrerror());
622 /* mark the socket as having transparent options */
623 fd_table
[fd
].flags
.transparent
= 1;
626 debugs(50, DBG_CRITICAL
, "WARNING: comm_open: setsockopt(IP_TRANSPARENT) not supported on this platform");
631 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
632 * is OR of flags specified in defines.h:COMM_*
635 comm_openex(int sock_type
,
644 struct addrinfo
*AI
= NULL
;
646 PROF_start(comm_open
);
647 /* Create socket for accepting new connections. */
648 statCounter
.syscalls
.sock
.sockets
++;
650 /* Setup the socket addrinfo details for use */
651 addr
.GetAddrInfo(AI
);
652 AI
->ai_socktype
= sock_type
;
653 AI
->ai_protocol
= proto
;
655 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr
);
657 new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
659 /* under IPv6 there is the possibility IPv6 is present but disabled. */
660 /* try again as IPv4-native if possible */
661 if ( new_socket
< 0 && Ip::EnableIpv6
&& addr
.IsIPv6() && addr
.SetIPv4() ) {
662 /* attempt to open this IPv4-only. */
663 addr
.FreeAddrInfo(AI
);
664 /* Setup the socket addrinfo details for use */
665 addr
.GetAddrInfo(AI
);
666 AI
->ai_socktype
= sock_type
;
667 AI
->ai_protocol
= proto
;
668 debugs(50, 3, "comm_openex: Attempt fallback open socket for: " << addr
);
669 new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
670 debugs(50, 2, HERE
<< "attempt open " << note
<< " socket on: " << addr
);
673 if (new_socket
< 0) {
674 /* Increase the number of reserved fd's if calls to socket()
675 * are failing because the open file table is full. This
676 * limits the number of simultaneous clients */
678 if (limitError(errno
)) {
679 debugs(50, DBG_IMPORTANT
, "comm_open: socket failure: " << xstrerror());
682 debugs(50, DBG_CRITICAL
, "comm_open: socket failure: " << xstrerror());
685 addr
.FreeAddrInfo(AI
);
687 PROF_stop(comm_open
);
691 debugs(50, 3, "comm_openex: Opened socket FD " << new_socket
<< " : family=" << AI
->ai_family
<< ", type=" << AI
->ai_socktype
<< ", protocol=" << AI
->ai_protocol
);
693 /* set TOS if needed */
694 if (TOS
&& comm_set_tos(new_socket
, TOS
) ) {
698 if ( Ip::EnableIpv6
&IPV6_SPECIAL_SPLITSTACK
&& addr
.IsIPv6() )
699 comm_set_v6only(new_socket
, 1);
701 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
702 /* Other OS may have this administratively disabled for general use. Same deal. */
703 if ( Ip::EnableIpv6
&IPV6_SPECIAL_V4MAPPING
&& addr
.IsIPv6() )
704 comm_set_v6only(new_socket
, 0);
706 comm_init_opened(new_socket
, addr
, TOS
, note
, AI
);
707 new_socket
= comm_apply_flags(new_socket
, addr
, flags
, AI
);
709 addr
.FreeAddrInfo(AI
);
711 PROF_stop(comm_open
);
716 /// update FD tables after a local or remote (IPC) comm_openex();
718 comm_init_opened(int new_socket
,
724 assert(new_socket
>= 0);
730 debugs(5, 5, "comm_open: FD " << new_socket
<< " is a new socket");
732 assert(!isOpen(new_socket
));
733 fd_open(new_socket
, FD_SOCKET
, note
);
735 fdd_table
[new_socket
].close_file
= NULL
;
737 fdd_table
[new_socket
].close_line
= 0;
739 F
= &fd_table
[new_socket
];
741 F
->local_addr
= addr
;
745 F
->sock_family
= AI
->ai_family
;
748 /// apply flags after a local comm_open*() call;
749 /// returns new_socket or -1 on error
751 comm_apply_flags(int new_socket
,
756 assert(new_socket
>= 0);
758 const int sock_type
= AI
->ai_socktype
;
760 if (!(flags
& COMM_NOCLOEXEC
))
761 commSetCloseOnExec(new_socket
);
763 if ((flags
& COMM_REUSEADDR
))
764 commSetReuseAddr(new_socket
);
766 if (addr
.GetPort() > (u_short
) 0) {
768 if (sock_type
!= SOCK_DGRAM
)
770 commSetNoLinger(new_socket
);
773 commSetReuseAddr(new_socket
);
776 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
777 if ((flags
& COMM_TRANSPARENT
)) {
778 comm_set_transparent(new_socket
);
781 if ( (flags
& COMM_DOBIND
) || addr
.GetPort() > 0 || !addr
.IsAnyAddr() ) {
782 if ( !(flags
& COMM_DOBIND
) && addr
.IsAnyAddr() )
783 debugs(5,1,"WARNING: Squid is attempting to bind() port " << addr
<< " without being a listener.");
784 if ( addr
.IsNoAddr() )
785 debugs(5,0,"CRITICAL: Squid is attempting to bind() port " << addr
<< "!!");
787 if (commBind(new_socket
, *AI
) != COMM_OK
) {
788 comm_close(new_socket
);
793 if (flags
& COMM_NONBLOCKING
)
794 if (commSetNonBlocking(new_socket
) == COMM_ERROR
) {
795 comm_close(new_socket
);
800 if (sock_type
== SOCK_STREAM
)
801 commSetTcpNoDelay(new_socket
);
805 if (Config
.tcpRcvBufsz
> 0 && sock_type
== SOCK_STREAM
)
806 commSetTcpRcvbuf(new_socket
, Config
.tcpRcvBufsz
);
812 comm_import_opened(int fd
,
818 debugs(5, 2, HERE
<< " FD " << fd
<< " at " << addr
);
822 comm_init_opened(fd
, addr
, 0, note
, AI
);
824 if (!(flags
& COMM_NOCLOEXEC
))
825 fd_table
[fd
].flags
.close_on_exec
= 1;
827 if (addr
.GetPort() > (u_short
) 0) {
829 if (sock_type
!= SOCK_DGRAM
)
831 fd_table
[fd
].flags
.nolinger
= 1;
834 if ((flags
& COMM_TRANSPARENT
))
835 fd_table
[fd
].flags
.transparent
= 1;
837 if (flags
& COMM_NONBLOCKING
)
838 fd_table
[fd
].flags
.nonblocking
= 1;
841 if (AI
->ai_socktype
== SOCK_STREAM
)
842 fd_table
[fd
].flags
.nodelay
= 1;
845 /* no fd_table[fd].flags. updates needed for these conditions:
846 * if ((flags & COMM_REUSEADDR)) ...
847 * if ((flags & COMM_DOBIND) ...) ...
853 commSetTimeout_old(int fd
, int timeout
, PF
* handler
, void *data
)
855 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
857 assert(fd
< Squid_MaxFD
);
858 fde
*F
= &fd_table
[fd
];
859 assert(F
->flags
.open
);
862 cbdataReferenceDone(F
->timeout_data
);
863 F
->timeout_handler
= NULL
;
867 cbdataReferenceDone(F
->timeout_data
);
868 F
->timeout_handler
= handler
;
869 F
->timeout_data
= cbdataReference(data
);
872 F
->timeout
= squid_curtime
+ (time_t) timeout
;
880 commSetTimeout(int fd
, int timeout
, PF
* handler
, void *data
)
882 AsyncCall::Pointer call
;
883 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
885 call
=commCbCall(5,4, "SomeTimeoutHandler", CommTimeoutCbPtrFun(handler
, data
));
888 return commSetTimeout(fd
, timeout
, call
);
893 commSetTimeout(int fd
, int timeout
, AsyncCall::Pointer
&callback
)
895 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
897 assert(fd
< Squid_MaxFD
);
898 fde
*F
= &fd_table
[fd
];
899 assert(F
->flags
.open
);
902 F
->timeoutHandler
= NULL
;
905 if (callback
!= NULL
) {
906 typedef CommTimeoutCbParams Params
;
907 Params
¶ms
= GetCommParams
<Params
>(callback
);
909 F
->timeoutHandler
= callback
;
912 F
->timeout
= squid_curtime
+ (time_t) timeout
;
920 comm_connect_addr(int sock
, const Ip::Address
&address
)
922 comm_err_t status
= COMM_OK
;
923 fde
*F
= &fd_table
[sock
];
927 struct addrinfo
*AI
= NULL
;
928 PROF_start(comm_connect_addr
);
930 assert(address
.GetPort() != 0);
932 debugs(5, 9, HERE
<< "connecting socket FD " << sock
<< " to " << address
<< " (want family: " << F
->sock_family
<< ")");
934 /* Handle IPv6 over IPv4-only socket case.
935 * this case must presently be handled here since the GetAddrInfo asserts on bad mappings.
936 * NP: because commResetFD is private to ConnStateData we have to return an error and
937 * trust its handled properly.
939 if (F
->sock_family
== AF_INET
&& !address
.IsIPv4()) {
941 return COMM_ERR_PROTOCOL
;
944 /* Handle IPv4 over IPv6-only socket case.
945 * This case is presently handled here as it's both a known case and it's
946 * uncertain what error will be returned by the IPv6 stack in such case. It's
947 * possible this will also be handled by the errno checks below after connect()
948 * but needs carefull cross-platform verification, and verifying the address
949 * condition here is simple.
951 if (!F
->local_addr
.IsIPv4() && address
.IsIPv4()) {
953 return COMM_ERR_PROTOCOL
;
956 address
.GetAddrInfo(AI
, F
->sock_family
);
958 /* Establish connection. */
961 if (!F
->flags
.called_connect
) {
962 F
->flags
.called_connect
= 1;
963 statCounter
.syscalls
.sock
.connects
++;
965 x
= connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
967 // XXX: ICAP code refuses callbacks during a pending comm_ call
968 // Async calls development will fix this.
975 debugs(5,5, "comm_connect_addr: sock=" << sock
<< ", addrinfo( " <<
976 " flags=" << AI
->ai_flags
<<
977 ", family=" << AI
->ai_family
<<
978 ", socktype=" << AI
->ai_socktype
<<
979 ", protocol=" << AI
->ai_protocol
<<
980 ", &addr=" << AI
->ai_addr
<<
981 ", addrlen=" << AI
->ai_addrlen
<<
983 debugs(5, 9, "connect FD " << sock
<< ": (" << x
<< ") " << xstrerror());
984 debugs(14,9, "connecting to: " << address
);
987 #if defined(_SQUID_NEWSOS6_)
988 /* Makoto MATSUSHITA <matusita@ics.es.osaka-u.ac.jp> */
990 connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
992 if (errno
== EINVAL
) {
993 errlen
= sizeof(err
);
994 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
1001 errlen
= sizeof(err
);
1003 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
1008 #if defined(_SQUID_SOLARIS_)
1010 * Solaris 2.4's socket emulation doesn't allow you
1011 * to determine the error from a failed non-blocking
1012 * connect and just returns EPIPE. Create a fake
1013 * error message for connect. -- fenner@parc.xerox.com
1015 if (x
< 0 && errno
== EPIPE
)
1023 /* Squid seems to be working fine without this code. With this code,
1024 * we leak memory on many connect requests because of EINPROGRESS.
1025 * If you find that this code is needed, please file a bug report. */
1027 #ifdef _SQUID_LINUX_
1029 * Linux Debian replaces our allocated AI pointer with garbage when
1030 * connect() fails. This leads to segmentation faults deallocating
1031 * the system-allocated memory when we go to clean up our pointer.
1032 * HACK: is to leak the memory returned since we can't deallocate.
1040 address
.FreeAddrInfo(AI
);
1042 PROF_stop(comm_connect_addr
);
1044 if (errno
== 0 || errno
== EISCONN
)
1046 else if (ignoreErrno(errno
))
1047 status
= COMM_INPROGRESS
;
1048 else if (errno
== EAFNOSUPPORT
|| errno
== EINVAL
)
1049 return COMM_ERR_PROTOCOL
;
1053 address
.NtoA(F
->ipaddr
, MAX_IPSTRLEN
);
1055 F
->remote_port
= address
.GetPort(); /* remote_port is HS */
1057 if (status
== COMM_OK
) {
1058 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connected to " << address
);
1059 } else if (status
== COMM_INPROGRESS
) {
1060 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connection pending");
1067 commCallCloseHandlers(int fd
)
1069 fde
*F
= &fd_table
[fd
];
1070 debugs(5, 5, "commCallCloseHandlers: FD " << fd
);
1072 while (F
->closeHandler
!= NULL
) {
1073 AsyncCall::Pointer call
= F
->closeHandler
;
1074 F
->closeHandler
= call
->Next();
1075 call
->setNext(NULL
);
1076 // If call is not canceled schedule it for execution else ignore it
1077 if (!call
->canceled()) {
1078 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call
);
1079 typedef CommCloseCbParams Params
;
1080 Params
¶ms
= GetCommParams
<Params
>(call
);
1082 ScheduleCallHere(call
);
1089 commLingerClose(int fd
, void *unused
)
1091 LOCAL_ARRAY(char, buf
, 1024);
1093 n
= FD_READ_METHOD(fd
, buf
, 1024);
1096 debugs(5, 3, "commLingerClose: FD " << fd
<< " read: " << xstrerror());
1102 commLingerTimeout(int fd
, void *unused
)
1104 debugs(5, 3, "commLingerTimeout: FD " << fd
);
1109 * Inspired by apache
1112 comm_lingering_close(int fd
)
1116 if (fd_table
[fd
].ssl
)
1117 ssl_shutdown_method(fd
);
1121 if (shutdown(fd
, 1) < 0) {
1126 fd_note(fd
, "lingering close");
1127 commSetTimeout(fd
, 10, commLingerTimeout
, NULL
);
1128 commSetSelect(fd
, COMM_SELECT_READ
, commLingerClose
, NULL
, 0);
1134 * enable linger with time of 0 so that when the socket is
1135 * closed, TCP generates a RESET
1138 comm_reset_close(Comm::ConnectionPointer
&conn
)
1144 if (setsockopt(conn
->fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1145 debugs(50, DBG_CRITICAL
, "ERROR: Closing FD " << conn
->fd
<< " with TCP RST: " << xstrerror());
1150 // Legacy close function.
1152 old_comm_reset_close(int fd
)
1158 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1159 debugs(50, DBG_CRITICAL
, "ERROR: Closing FD " << fd
<< " with TCP RST: " << xstrerror());
1165 comm_close_start(int fd
, void *data
)
1168 fde
*F
= &fd_table
[fd
];
1170 ssl_shutdown_method(fd
);
1177 comm_close_complete(int fd
, void *data
)
1180 fde
*F
= &fd_table
[fd
];
1188 fd_close(fd
); /* update fdstat */
1192 statCounter
.syscalls
.sock
.closes
++;
1194 /* When an fd closes, give accept() a chance, if need be */
1195 Comm::AcceptLimiter::Instance().kick();
1199 * Close the socket fd.
1201 * + call write handlers with ERR_CLOSING
1202 * + call read handlers with ERR_CLOSING
1203 * + call closing handlers
1205 * NOTE: COMM_ERR_CLOSING will NOT be called for CommReads' sitting in a
1206 * DeferredReadManager.
1209 _comm_close(int fd
, char const *file
, int line
)
1211 debugs(5, 3, "comm_close: start closing FD " << fd
);
1213 assert(fd
< Squid_MaxFD
);
1215 fde
*F
= &fd_table
[fd
];
1216 fdd_table
[fd
].close_file
= file
;
1217 fdd_table
[fd
].close_line
= line
;
1222 /* XXX: is this obsolete behind F->closing() ? */
1223 if ( (shutting_down
|| reconfiguring
) && (!F
->flags
.open
|| F
->type
== FD_FILE
))
1226 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
1229 assert(F
->type
!= FD_FILE
);
1231 PROF_start(comm_close
);
1233 F
->flags
.close_request
= 1;
1235 AsyncCall::Pointer startCall
=commCbCall(5,4, "comm_close_start",
1236 CommCloseCbPtrFun(comm_close_start
, NULL
));
1237 typedef CommCloseCbParams Params
;
1238 Params
&startParams
= GetCommParams
<Params
>(startCall
);
1239 startParams
.fd
= fd
;
1240 ScheduleCallHere(startCall
);
1242 // a half-closed fd may lack a reader, so we stop monitoring explicitly
1243 if (commHasHalfClosedMonitor(fd
))
1244 commStopHalfClosedMonitor(fd
);
1245 commSetTimeout(fd
, -1, NULL
, NULL
);
1247 // notify read/write handlers
1248 if (commio_has_callback(fd
, IOCB_WRITE
, COMMIO_FD_WRITECB(fd
))) {
1249 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), COMM_ERR_CLOSING
, errno
);
1251 if (commio_has_callback(fd
, IOCB_READ
, COMMIO_FD_READCB(fd
))) {
1252 commio_finish_callback(fd
, COMMIO_FD_READCB(fd
), COMM_ERR_CLOSING
, errno
);
1255 commCallCloseHandlers(fd
);
1258 F
->pconn
.pool
->count(F
->pconn
.uses
);
1260 comm_empty_os_read_buffers(fd
);
1263 AsyncCall::Pointer completeCall
=commCbCall(5,4, "comm_close_complete",
1264 CommCloseCbPtrFun(comm_close_complete
, NULL
));
1265 Params
&completeParams
= GetCommParams
<Params
>(completeCall
);
1266 completeParams
.fd
= fd
;
1267 // must use async call to wait for all callbacks
1268 // scheduled before comm_close() to finish
1269 ScheduleCallHere(completeCall
);
1271 PROF_stop(comm_close
);
1274 /* Send a udp datagram to specified TO_ADDR. */
1276 comm_udp_sendto(int fd
,
1277 const Ip::Address
&to_addr
,
1282 struct addrinfo
*AI
= NULL
;
1284 PROF_start(comm_udp_sendto
);
1285 statCounter
.syscalls
.sock
.sendtos
++;
1287 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr
<<
1288 " using FD " << fd
<< " using Port " << comm_local_port(fd
) );
1290 /* BUG: something in the above macro appears to occasionally be setting AI to garbage. */
1291 /* AYJ: 2007-08-27 : or was it because I wasn't then setting 'fd_table[fd].sock_family' to fill properly. */
1292 assert( NULL
== AI
);
1294 to_addr
.GetAddrInfo(AI
, fd_table
[fd
].sock_family
);
1296 x
= sendto(fd
, buf
, len
, 0, AI
->ai_addr
, AI
->ai_addrlen
);
1298 to_addr
.FreeAddrInfo(AI
);
1300 PROF_stop(comm_udp_sendto
);
1305 #ifdef _SQUID_LINUX_
1307 if (ECONNREFUSED
!= errno
)
1310 debugs(50, 1, "comm_udp_sendto: FD " << fd
<< ", (family=" << fd_table
[fd
].sock_family
<< ") " << to_addr
<< ": " << xstrerror());
1316 comm_add_close_handler(int fd
, PF
* handler
, void *data
)
1318 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", handler=" <<
1319 handler
<< ", data=" << data
);
1321 AsyncCall::Pointer call
=commCbCall(5,4, "SomeCloseHandler",
1322 CommCloseCbPtrFun(handler
, data
));
1323 comm_add_close_handler(fd
, call
);
1327 comm_add_close_handler(int fd
, AsyncCall::Pointer
&call
)
1329 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1331 /*TODO:Check for a similar scheduled AsyncCall*/
1332 // for (c = fd_table[fd].closeHandler; c; c = c->next)
1333 // assert(c->handler != handler || c->data != data);
1335 call
->setNext(fd_table
[fd
].closeHandler
);
1337 fd_table
[fd
].closeHandler
= call
;
1341 // remove function-based close handler
1343 comm_remove_close_handler(int fd
, PF
* handler
, void *data
)
1345 assert (isOpen(fd
));
1346 /* Find handler in list */
1347 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", handler=" <<
1348 handler
<< ", data=" << data
);
1350 AsyncCall::Pointer p
;
1351 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
; p
= p
->Next()) {
1352 typedef CommCbFunPtrCallT
<CommCloseCbPtrFun
> Call
;
1353 const Call
*call
= dynamic_cast<const Call
*>(p
.getRaw());
1354 if (!call
) // method callbacks have their own comm_remove_close_handler
1357 typedef CommCloseCbParams Params
;
1358 const Params
¶ms
= GetCommParams
<Params
>(p
);
1359 if (call
->dialer
.handler
== handler
&& params
.data
== data
)
1360 break; /* This is our handler */
1363 // comm_close removes all close handlers so our handler may be gone
1365 p
->cancel("comm_remove_close_handler");
1366 // TODO: should we remove the handler from the close handlers list?
1369 // remove method-based close handler
1371 comm_remove_close_handler(int fd
, AsyncCall::Pointer
&call
)
1373 assert (isOpen(fd
));
1374 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1376 // comm_close removes all close handlers so our handler may be gone
1377 // TODO: should we remove the handler from the close handlers list?
1379 // Check to see if really exist the given AsyncCall in comm_close handlers
1380 // TODO: optimize: this slow code is only needed for the assert() below
1381 AsyncCall::Pointer p
;
1382 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
&& p
!= call
; p
= p
->Next());
1386 call
->cancel("comm_remove_close_handler");
1390 commSetNoLinger(int fd
)
1394 L
.l_onoff
= 0; /* off */
1397 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1398 debugs(50, 0, "commSetNoLinger: FD " << fd
<< ": " << xstrerror());
1400 fd_table
[fd
].flags
.nolinger
= 1;
1404 commSetReuseAddr(int fd
)
1408 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &on
, sizeof(on
)) < 0)
1409 debugs(50, 1, "commSetReuseAddr: FD " << fd
<< ": " << xstrerror());
1413 commSetTcpRcvbuf(int fd
, int size
)
1415 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, (char *) &size
, sizeof(size
)) < 0)
1416 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1417 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, (char *) &size
, sizeof(size
)) < 0)
1418 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1419 #ifdef TCP_WINDOW_CLAMP
1420 if (setsockopt(fd
, SOL_TCP
, TCP_WINDOW_CLAMP
, (char *) &size
, sizeof(size
)) < 0)
1421 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1426 commSetNonBlocking(int fd
)
1428 #ifndef _SQUID_MSWIN_
1432 #ifdef _SQUID_WIN32_
1434 int nonblocking
= TRUE
;
1436 #ifdef _SQUID_CYGWIN_
1438 if (fd_table
[fd
].type
!= FD_PIPE
) {
1441 if (ioctl(fd
, FIONBIO
, &nonblocking
) < 0) {
1442 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror() << " " << fd_table
[fd
].type
);
1446 #ifdef _SQUID_CYGWIN_
1451 #ifndef _SQUID_MSWIN_
1453 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1454 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1458 if (fcntl(fd
, F_SETFL
, flags
| SQUID_NONBLOCK
) < 0) {
1459 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror());
1464 #ifdef _SQUID_CYGWIN_
1469 fd_table
[fd
].flags
.nonblocking
= 1;
1475 commUnsetNonBlocking(int fd
)
1477 #ifdef _SQUID_MSWIN_
1478 int nonblocking
= FALSE
;
1480 if (ioctlsocket(fd
, FIONBIO
, (unsigned long *) &nonblocking
) < 0) {
1485 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1486 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1490 if (fcntl(fd
, F_SETFL
, flags
& (~SQUID_NONBLOCK
)) < 0) {
1492 debugs(50, 0, "commUnsetNonBlocking: FD " << fd
<< ": " << xstrerror());
1496 fd_table
[fd
].flags
.nonblocking
= 0;
1501 commSetCloseOnExec(int fd
)
1507 if ((flags
= fcntl(fd
, F_GETFD
, dummy
)) < 0) {
1508 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFD: " << xstrerror());
1512 if (fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) < 0)
1513 debugs(50, 0, "FD " << fd
<< ": set close-on-exec failed: " << xstrerror());
1515 fd_table
[fd
].flags
.close_on_exec
= 1;
1522 commSetTcpNoDelay(int fd
)
1526 if (setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *) &on
, sizeof(on
)) < 0)
1527 debugs(50, 1, "commSetTcpNoDelay: FD " << fd
<< ": " << xstrerror());
1529 fd_table
[fd
].flags
.nodelay
= 1;
1535 commSetTcpKeepalive(int fd
, int idle
, int interval
, int timeout
)
1539 if (timeout
&& interval
) {
1540 int count
= (timeout
+ interval
- 1) / interval
;
1541 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPCNT
, &count
, sizeof(on
)) < 0)
1542 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1547 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, &idle
, sizeof(on
)) < 0)
1548 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1551 #ifdef TCP_KEEPINTVL
1553 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, &interval
, sizeof(on
)) < 0)
1554 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1557 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char *) &on
, sizeof(on
)) < 0)
1558 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1564 fd_table
=(fde
*) xcalloc(Squid_MaxFD
, sizeof(fde
));
1565 fdd_table
= (fd_debug_t
*)xcalloc(Squid_MaxFD
, sizeof(fd_debug_t
));
1567 /* make sure the accept() socket FIFO delay queue exists */
1568 Comm::AcceptLimiter::Instance();
1570 commfd_table
= (comm_fd_t
*) xcalloc(Squid_MaxFD
, sizeof(comm_fd_t
));
1571 for (int pos
= 0; pos
< Squid_MaxFD
; pos
++) {
1572 commfd_table
[pos
].fd
= pos
;
1573 commfd_table
[pos
].readcb
.fd
= pos
;
1574 commfd_table
[pos
].readcb
.type
= IOCB_READ
;
1575 commfd_table
[pos
].writecb
.fd
= pos
;
1576 commfd_table
[pos
].writecb
.type
= IOCB_WRITE
;
1579 /* XXX account fd_table */
1580 /* Keep a few file descriptors free so that we don't run out of FD's
1581 * after accepting a client but before it opens a socket or a file.
1582 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
1583 RESERVED_FD
= min(100, Squid_MaxFD
/ 4);
1585 conn_close_pool
= memPoolCreate("close_handler", sizeof(close_handler
));
1587 TheHalfClosed
= new DescriptorSet
;
1593 delete TheHalfClosed
;
1594 TheHalfClosed
= NULL
;
1596 safe_free(fd_table
);
1597 safe_free(fdd_table
);
1598 safe_free(commfd_table
);
1603 commHandleWrite(int fd
, void *data
)
1605 comm_io_callback_t
*state
= (comm_io_callback_t
*)data
;
1609 assert(state
== COMMIO_FD_WRITECB(fd
));
1611 PROF_start(commHandleWrite
);
1612 debugs(5, 5, "commHandleWrite: FD " << fd
<< ": off " <<
1613 (long int) state
->offset
<< ", sz " << (long int) state
->size
<< ".");
1615 nleft
= state
->size
- state
->offset
;
1616 len
= FD_WRITE_METHOD(fd
, state
->buf
+ state
->offset
, nleft
);
1617 debugs(5, 5, "commHandleWrite: write() returns " << len
);
1618 fd_bytes(fd
, len
, FD_WRITE
);
1619 statCounter
.syscalls
.sock
.writes
++;
1620 // After each successful partial write,
1621 // reset fde::writeStart to the current time.
1622 fd_table
[fd
].writeStart
= squid_curtime
;
1625 /* Note we even call write if nleft == 0 */
1629 debugs(5, 1, "commHandleWrite: FD " << fd
<< ": write failure: connection closed with " << nleft
<< " bytes remaining.");
1631 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1632 } else if (len
< 0) {
1635 if (fd_table
[fd
].flags
.socket_eof
) {
1636 debugs(50, 2, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1637 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1638 } else if (ignoreErrno(errno
)) {
1639 debugs(50, 10, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1646 debugs(50, 2, "commHandleWrite: FD " << fd
<< ": write failure: " << xstrerror() << ".");
1647 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_ERROR
: COMM_OK
, errno
);
1650 /* A successful write, continue */
1651 state
->offset
+= len
;
1653 if (state
->offset
< state
->size
) {
1654 /* Not done, reinstall the write handler and write some more */
1661 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), nleft
? COMM_OK
: COMM_ERROR
, errno
);
1665 PROF_stop(commHandleWrite
);
1669 * Queue a write. handler/handler_data are called when the write
1670 * completes, on error, or on file descriptor close.
1672 * free_func is used to free the passed buffer when the write has completed.
1675 comm_write(int fd
, const char *buf
, int size
, IOCB
* handler
, void *handler_data
, FREE
* free_func
)
1677 AsyncCall::Pointer call
= commCbCall(5,5, "SomeCommWriteHander",
1678 CommIoCbPtrFun(handler
, handler_data
));
1680 comm_write(fd
, buf
, size
, call
, free_func
);
1684 comm_write(int fd
, const char *buf
, int size
, AsyncCall::Pointer
&callback
, FREE
* free_func
)
1686 debugs(5, 5, "comm_write: FD " << fd
<< ": sz " << size
<< ": asynCall " << callback
);
1688 /* Make sure we are open, not closing, and not writing */
1690 assert(!fd_table
[fd
].closing());
1691 comm_io_callback_t
*ccb
= COMMIO_FD_WRITECB(fd
);
1692 assert(!ccb
->active());
1694 fd_table
[fd
].writeStart
= squid_curtime
;
1695 /* Queue the write */
1696 commio_set_callback(fd
, IOCB_WRITE
, ccb
, callback
,
1697 (char *)buf
, free_func
, size
);
1698 commSetSelect(fd
, COMM_SELECT_WRITE
, commHandleWrite
, ccb
, 0);
1702 /* a wrapper around comm_write to allow for MemBuf to be comm_written in a snap */
1704 comm_write_mbuf(int fd
, MemBuf
*mb
, IOCB
* handler
, void *handler_data
)
1706 comm_write(fd
, mb
->buf
, mb
->size
, handler
, handler_data
, mb
->freeFunc());
1710 comm_write_mbuf(int fd
, MemBuf
*mb
, AsyncCall::Pointer
&callback
)
1712 comm_write(fd
, mb
->buf
, mb
->size
, callback
, mb
->freeFunc());
1717 * hm, this might be too general-purpose for all the places we'd
1721 ignoreErrno(int ierrno
)
1728 #if EAGAIN != EWOULDBLOCK
1751 commCloseAllSockets(void)
1756 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
1762 if (F
->type
!= FD_SOCKET
)
1765 if (F
->flags
.ipc
) /* don't close inter-process sockets */
1768 if (F
->timeoutHandler
!= NULL
) {
1769 AsyncCall::Pointer callback
= F
->timeoutHandler
;
1770 F
->timeoutHandler
= NULL
;
1771 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": Calling timeout handler");
1772 ScheduleCallHere(callback
);
1774 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": calling comm_reset_close()");
1775 old_comm_reset_close(fd
);
1781 AlreadyTimedOut(fde
*F
)
1786 if (F
->timeout
== 0)
1789 if (F
->timeout
> squid_curtime
)
1796 writeTimedOut(int fd
)
1798 if (!commio_has_callback(fd
, IOCB_WRITE
, COMMIO_FD_WRITECB(fd
)))
1801 if ((squid_curtime
- fd_table
[fd
].writeStart
) < Config
.Timeout
.write
)
1812 AsyncCall::Pointer callback
;
1814 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
1817 if (writeTimedOut(fd
)) {
1818 // We have an active write callback and we are timed out
1819 debugs(5, 5, "checkTimeouts: FD " << fd
<< " auto write timeout");
1820 commSetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
1821 commio_finish_callback(fd
, COMMIO_FD_WRITECB(fd
), COMM_ERROR
, ETIMEDOUT
);
1822 } else if (AlreadyTimedOut(F
))
1825 debugs(5, 5, "checkTimeouts: FD " << fd
<< " Expired");
1827 if (F
->timeoutHandler
!= NULL
) {
1828 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Call timeout handler");
1829 callback
= F
->timeoutHandler
;
1830 F
->timeoutHandler
= NULL
;
1831 ScheduleCallHere(callback
);
1833 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Forcing comm_close()");
1839 void CommIO::Initialise()
1841 /* Initialize done pipe signal */
1843 if (pipe(DonePipe
)) {}
1844 DoneFD
= DonePipe
[1];
1845 DoneReadFD
= DonePipe
[0];
1846 fd_open(DoneReadFD
, FD_PIPE
, "async-io completetion event: main");
1847 fd_open(DoneFD
, FD_PIPE
, "async-io completetion event: threads");
1848 commSetNonBlocking(DoneReadFD
);
1849 commSetNonBlocking(DoneFD
);
1850 commSetSelect(DoneReadFD
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
1854 void CommIO::NotifyIOClose()
1856 /* Close done pipe signal */
1861 fd_close(DoneReadFD
);
1862 Initialised
= false;
1865 bool CommIO::Initialised
= false;
1866 bool CommIO::DoneSignalled
= false;
1867 int CommIO::DoneFD
= -1;
1868 int CommIO::DoneReadFD
= -1;
1874 FD_READ_METHOD(DoneReadFD
, buf
, sizeof(buf
));
1878 CommIO::NULLFDHandler(int fd
, void *data
)
1881 commSetSelect(fd
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
1885 CommIO::ResetNotifications()
1887 if (DoneSignalled
) {
1889 DoneSignalled
= false;
1893 /// Start waiting for a possibly half-closed connection to close
1894 // by scheduling a read callback to a monitoring handler that
1895 // will close the connection on read errors.
1897 commStartHalfClosedMonitor(int fd
)
1899 debugs(5, 5, HERE
<< "adding FD " << fd
<< " to " << *TheHalfClosed
);
1901 assert(!commHasHalfClosedMonitor(fd
));
1902 (void)TheHalfClosed
->add(fd
); // could also assert the result
1903 commPlanHalfClosedCheck(); // may schedule check if we added the first FD
1908 commPlanHalfClosedCheck()
1910 if (!WillCheckHalfClosed
&& !TheHalfClosed
->empty()) {
1911 eventAdd("commHalfClosedCheck", &commHalfClosedCheck
, NULL
, 1.0, 1);
1912 WillCheckHalfClosed
= true;
1916 /// iterates over all descriptors that may need half-closed tests and
1917 /// calls comm_read for those that do; re-schedules the check if needed
1920 commHalfClosedCheck(void *)
1922 debugs(5, 5, HERE
<< "checking " << *TheHalfClosed
);
1924 typedef DescriptorSet::const_iterator DSCI
;
1925 const DSCI end
= TheHalfClosed
->end();
1926 for (DSCI i
= TheHalfClosed
->begin(); i
!= end
; ++i
) {
1928 if (!fd_table
[fd
].halfClosedReader
) { // not reading already
1929 AsyncCall::Pointer call
= commCbCall(5,4, "commHalfClosedReader",
1930 CommIoCbPtrFun(&commHalfClosedReader
, NULL
));
1931 comm_read(fd
, NULL
, 0, call
);
1932 fd_table
[fd
].halfClosedReader
= call
;
1936 WillCheckHalfClosed
= false; // as far as we know
1937 commPlanHalfClosedCheck(); // may need to check again
1940 /// checks whether we are waiting for possibly half-closed connection to close
1941 // We are monitoring if the read handler for the fd is the monitoring handler.
1943 commHasHalfClosedMonitor(int fd
)
1945 return TheHalfClosed
->has(fd
);
1948 /// stop waiting for possibly half-closed connection to close
1950 commStopHalfClosedMonitor(int const fd
)
1952 debugs(5, 5, HERE
<< "removing FD " << fd
<< " from " << *TheHalfClosed
);
1954 // cancel the read if one was scheduled
1955 AsyncCall::Pointer reader
= fd_table
[fd
].halfClosedReader
;
1957 comm_read_cancel(fd
, reader
);
1958 fd_table
[fd
].halfClosedReader
= NULL
;
1960 TheHalfClosed
->del(fd
);
1963 /// I/O handler for the possibly half-closed connection monitoring code
1965 commHalfClosedReader(int fd
, char *, size_t size
, comm_err_t flag
, int, void *)
1967 // there cannot be more data coming in on half-closed connections
1969 assert(commHasHalfClosedMonitor(fd
)); // or we would have canceled the read
1971 fd_table
[fd
].halfClosedReader
= NULL
; // done reading, for now
1973 // nothing to do if fd is being closed
1974 if (flag
== COMM_ERR_CLOSING
)
1977 // if read failed, close the connection
1978 if (flag
!= COMM_OK
) {
1979 debugs(5, 3, "commHalfClosedReader: closing FD " << fd
);
1984 // continue waiting for close or error
1985 commPlanHalfClosedCheck(); // make sure this fd will be checked again
1989 CommRead::CommRead() : fd(-1), buf(NULL
), len(0), callback(NULL
) {}
1991 CommRead::CommRead(int fd_
, char *buf_
, int len_
, AsyncCall::Pointer
&callback_
)
1992 : fd(fd_
), buf(buf_
), len(len_
), callback(callback_
) {}
1994 DeferredRead::DeferredRead () : theReader(NULL
), theContext(NULL
), theRead(), cancelled(false) {}
1996 DeferredRead::DeferredRead (DeferrableRead
*aReader
, void *data
, CommRead
const &aRead
) : theReader(aReader
), theContext (data
), theRead(aRead
), cancelled(false) {}
1998 DeferredReadManager::~DeferredReadManager()
2001 assert (deferredReads
.empty());
2004 /* explicit instantiation required for some systems */
2006 /// \cond AUTODOCS-IGNORE
2007 template cbdata_type CbDataList
<DeferredRead
>::CBDATA_CbDataList
;
2011 DeferredReadManager::delayRead(DeferredRead
const &aRead
)
2013 debugs(5, 3, "Adding deferred read on FD " << aRead
.theRead
.fd
);
2014 CbDataList
<DeferredRead
> *temp
= deferredReads
.push_back(aRead
);
2016 // We have to use a global function as a closer and point to temp
2017 // instead of "this" because DeferredReadManager is not a job and
2018 // is not even cbdata protected
2019 AsyncCall::Pointer closer
= commCbCall(5,4,
2020 "DeferredReadManager::CloseHandler",
2021 CommCloseCbPtrFun(&CloseHandler
, temp
));
2022 comm_add_close_handler(aRead
.theRead
.fd
, closer
);
2023 temp
->element
.closer
= closer
; // remeber so that we can cancel
2027 DeferredReadManager::CloseHandler(int fd
, void *thecbdata
)
2029 if (!cbdataReferenceValid (thecbdata
))
2032 CbDataList
<DeferredRead
> *temp
= (CbDataList
<DeferredRead
> *)thecbdata
;
2034 temp
->element
.closer
= NULL
;
2035 temp
->element
.markCancelled();
2039 DeferredReadManager::popHead(CbDataListContainer
<DeferredRead
> &deferredReads
)
2041 assert (!deferredReads
.empty());
2043 DeferredRead
&read
= deferredReads
.head
->element
;
2044 if (!read
.cancelled
) {
2045 comm_remove_close_handler(read
.theRead
.fd
, read
.closer
);
2049 DeferredRead result
= deferredReads
.pop_front();
2055 DeferredReadManager::kickReads(int const count
)
2057 /* if we had CbDataList::size() we could consolidate this and flushReads */
2064 size_t remaining
= count
;
2066 while (!deferredReads
.empty() && remaining
) {
2067 DeferredRead aRead
= popHead(deferredReads
);
2070 if (!aRead
.cancelled
)
2076 DeferredReadManager::flushReads()
2078 CbDataListContainer
<DeferredRead
> reads
;
2079 reads
= deferredReads
;
2080 deferredReads
= CbDataListContainer
<DeferredRead
>();
2082 // XXX: For fairness this SHOULD randomize the order
2083 while (!reads
.empty()) {
2084 DeferredRead aRead
= popHead(reads
);
2090 DeferredReadManager::kickARead(DeferredRead
const &aRead
)
2092 if (aRead
.cancelled
)
2095 if (aRead
.theRead
.fd
>=0 && fd_table
[aRead
.theRead
.fd
].closing())
2098 debugs(5, 3, "Kicking deferred read on FD " << aRead
.theRead
.fd
);
2100 aRead
.theReader(aRead
.theContext
, aRead
.theRead
);
2104 DeferredRead::markCancelled()
2110 CommSelectEngine::checkEvents(int timeout
)
2112 static time_t last_timeout
= 0;
2114 /* No, this shouldn't be here. But it shouldn't be in each comm handler. -adrian */
2115 if (squid_curtime
> last_timeout
) {
2116 last_timeout
= squid_curtime
;
2120 switch (comm_select(timeout
)) {
2136 fatal_dump("comm.cc: Internal error -- this should never happen.");
2141 /// Create a unix-domain socket (UDS) that only supports FD_MSGHDR I/O.
2143 comm_open_uds(int sock_type
,
2145 struct sockaddr_un
* addr
,
2148 // TODO: merge with comm_openex() when Ip::Address becomes NetAddress
2152 PROF_start(comm_open
);
2153 /* Create socket for accepting new connections. */
2154 statCounter
.syscalls
.sock
.sockets
++;
2156 /* Setup the socket addrinfo details for use */
2159 AI
.ai_family
= PF_UNIX
;
2160 AI
.ai_socktype
= sock_type
;
2161 AI
.ai_protocol
= proto
;
2162 AI
.ai_addrlen
= SUN_LEN(addr
);
2163 AI
.ai_addr
= (sockaddr
*)addr
;
2164 AI
.ai_canonname
= NULL
;
2167 debugs(50, 3, HERE
<< "Attempt open socket for: " << addr
->sun_path
);
2169 if ((new_socket
= socket(AI
.ai_family
, AI
.ai_socktype
, AI
.ai_protocol
)) < 0) {
2170 /* Increase the number of reserved fd's if calls to socket()
2171 * are failing because the open file table is full. This
2172 * limits the number of simultaneous clients */
2174 if (limitError(errno
)) {
2175 debugs(50, DBG_IMPORTANT
, HERE
<< "socket failure: " << xstrerror());
2178 debugs(50, DBG_CRITICAL
, HERE
<< "socket failure: " << xstrerror());
2181 PROF_stop(comm_open
);
2185 debugs(50, 3, HERE
"Opened UDS FD " << new_socket
<< " : family=" << AI
.ai_family
<< ", type=" << AI
.ai_socktype
<< ", protocol=" << AI
.ai_protocol
);
2188 debugs(50, 5, HERE
<< "FD " << new_socket
<< " is a new socket");
2190 assert(!isOpen(new_socket
));
2191 fd_open(new_socket
, FD_MSGHDR
, NULL
);
2193 fdd_table
[new_socket
].close_file
= NULL
;
2195 fdd_table
[new_socket
].close_line
= 0;
2197 fd_table
[new_socket
].sock_family
= AI
.ai_family
;
2199 if (!(flags
& COMM_NOCLOEXEC
))
2200 commSetCloseOnExec(new_socket
);
2202 if (flags
& COMM_REUSEADDR
)
2203 commSetReuseAddr(new_socket
);
2205 if (flags
& COMM_NONBLOCKING
) {
2206 if (commSetNonBlocking(new_socket
) != COMM_OK
) {
2207 comm_close(new_socket
);
2208 PROF_stop(comm_open
);
2213 if (flags
& COMM_DOBIND
) {
2214 if (commBind(new_socket
, AI
) != COMM_OK
) {
2215 comm_close(new_socket
);
2216 PROF_stop(comm_open
);
2222 if (sock_type
== SOCK_STREAM
)
2223 commSetTcpNoDelay(new_socket
);
2227 if (Config
.tcpRcvBufsz
> 0 && sock_type
== SOCK_STREAM
)
2228 commSetTcpRcvbuf(new_socket
, Config
.tcpRcvBufsz
);
2230 PROF_stop(comm_open
);