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>
35 #include "squid-old.h"
36 #include "base/AsyncCall.h"
37 #include "StoreIOBuffer.h"
41 #include "comm/AcceptLimiter.h"
42 #include "comm/comm_internal.h"
43 #include "comm/Connection.h"
44 #include "comm/IoCallback.h"
45 #include "comm/Loops.h"
46 #include "comm/Write.h"
47 #include "comm/TcpAcceptor.h"
52 #include "SquidTime.h"
53 #include "CommCalls.h"
54 #include "DescriptorSet.h"
55 #include "icmp/net_db.h"
56 #include "ip/Address.h"
57 #include "ip/Intercept.h"
58 #include "ip/QosConfig.h"
60 #include "ClientInfo.h"
61 #include "StatCounters.h"
63 #include "ssl/support.h"
68 #include <sys/ioctl.h>
70 #ifdef HAVE_NETINET_TCP_H
71 #include <netinet/tcp.h>
75 * New C-like simple comm code. This stuff is a mess and doesn't really buy us anything.
78 static void commStopHalfClosedMonitor(int fd
);
79 static IOCB commHalfClosedReader
;
80 static void comm_init_opened(const Comm::ConnectionPointer
&conn
, tos_t tos
, nfmark_t nfmark
, const char *note
, struct addrinfo
*AI
);
81 static int comm_apply_flags(int new_socket
, Ip::Address
&addr
, int flags
, struct addrinfo
*AI
);
84 CBDATA_CLASS_INIT(CommQuotaQueue
);
86 static void commHandleWriteHelper(void * data
);
91 static DescriptorSet
*TheHalfClosed
= NULL
; /// the set of half-closed FDs
92 static bool WillCheckHalfClosed
= false; /// true if check is scheduled
93 static EVH commHalfClosedCheck
;
94 static void commPlanHalfClosedCheck();
96 static comm_err_t
commBind(int s
, struct addrinfo
&);
97 static void commSetReuseAddr(int);
98 static void commSetNoLinger(int);
100 static void commSetTcpNoDelay(int);
102 static void commSetTcpRcvbuf(int, int);
104 static MemAllocator
*conn_close_pool
= NULL
;
105 fd_debug_t
*fdd_table
= NULL
;
110 return fd
>= 0 && fd_table
&& fd_table
[fd
].flags
.open
!= 0;
116 * If the read attempt succeeds or fails, call the callback.
117 * Else, wait for another IO notification.
120 commHandleRead(int fd
, void *data
)
122 Comm::IoCallback
*ccb
= (Comm::IoCallback
*) data
;
124 assert(data
== COMMIO_FD_READCB(fd
));
125 assert(ccb
->active());
127 statCounter
.syscalls
.sock
.reads
++;
130 retval
= FD_READ_METHOD(fd
, ccb
->buf
, ccb
->size
);
131 debugs(5, 3, "comm_read_try: FD " << fd
<< ", size " << ccb
->size
<< ", retval " << retval
<< ", errno " << errno
);
133 if (retval
< 0 && !ignoreErrno(errno
)) {
134 debugs(5, 3, "comm_read_try: scheduling COMM_ERROR");
136 ccb
->finish(COMM_ERROR
, errno
);
140 /* See if we read anything */
141 /* Note - read 0 == socket EOF, which is a valid read */
143 fd_bytes(fd
, retval
, FD_READ
);
144 ccb
->offset
= retval
;
145 ccb
->finish(COMM_OK
, errno
);
149 /* Nope, register for some more IO */
150 Comm::SetSelect(fd
, COMM_SELECT_READ
, commHandleRead
, data
, 0);
154 * Queue a read. handler/handler_data are called when the read
155 * completes, on error, or on file descriptor close.
158 comm_read(const Comm::ConnectionPointer
&conn
, char *buf
, int size
, AsyncCall::Pointer
&callback
)
160 debugs(5, 5, "comm_read, queueing read for " << conn
<< "; asynCall " << callback
);
162 /* Make sure we are open and not closing */
163 assert(Comm::IsConnOpen(conn
));
164 assert(!fd_table
[conn
->fd
].closing());
165 Comm::IoCallback
*ccb
= COMMIO_FD_READCB(conn
->fd
);
167 // Make sure we are either not reading or just passively monitoring.
168 // Active/passive conflicts are OK and simply cancel passive monitoring.
170 // if the assertion below fails, we have an active comm_read conflict
171 assert(fd_table
[conn
->fd
].halfClosedReader
!= NULL
);
172 commStopHalfClosedMonitor(conn
->fd
);
173 assert(!ccb
->active());
178 ccb
->setCallback(Comm::IOCB_READ
, callback
, (char *)buf
, NULL
, size
);
179 Comm::SetSelect(conn
->fd
, COMM_SELECT_READ
, commHandleRead
, ccb
, 0);
183 * Empty the read buffers
185 * This is a magical routine that empties the read buffers.
186 * Under some platforms (Linux) if a buffer has data in it before
187 * you call close(), the socket will hang and take quite a while
191 comm_empty_os_read_buffers(int fd
)
194 /* prevent those nasty RST packets */
195 char buf
[SQUID_TCP_SO_RCVBUF
];
197 if (fd_table
[fd
].flags
.nonblocking
== 1) {
198 while (FD_READ_METHOD(fd
, buf
, SQUID_TCP_SO_RCVBUF
) > 0) {};
205 * Return whether the FD has a pending completed callback.
209 comm_has_pending_read_callback(int fd
)
212 // XXX: We do not know whether there is a read callback scheduled.
213 // This is used for pconn management that should probably be more
214 // tightly integrated into comm to minimize the chance that a
215 // closing pconn socket will be used for a new transaction.
219 // Does comm check this fd for read readiness?
220 // Note that when comm is not monitoring, there can be a pending callback
221 // call, which may resume comm monitoring once fired.
223 comm_monitors_read(int fd
)
226 // Being active is usually the same as monitoring because we always
227 // start monitoring the FD when we configure Comm::IoCallback for I/O
228 // and we usually configure Comm::IoCallback for I/O when we starting
229 // monitoring a FD for reading.
230 return COMMIO_FD_READCB(fd
)->active();
234 * Cancel a pending read. Assert that we have the right parameters,
235 * and that there are no pending read events!
237 * XXX: We do not assert that there are no pending read events and
238 * with async calls it becomes even more difficult.
239 * The whole interface should be reworked to do callback->cancel()
240 * instead of searching for places where the callback may be stored and
241 * updating the state of those places.
243 * AHC Don't call the comm handlers?
246 comm_read_cancel(int fd
, IOCB
*callback
, void *data
)
249 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
253 Comm::IoCallback
*cb
= COMMIO_FD_READCB(fd
);
254 // TODO: is "active" == "monitors FD"?
256 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
260 typedef CommCbFunPtrCallT
<CommIoCbPtrFun
> Call
;
261 Call
*call
= dynamic_cast<Call
*>(cb
->callback
.getRaw());
263 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " lacks callback");
267 call
->cancel("old comm_read_cancel");
269 typedef CommIoCbParams Params
;
270 const Params
¶ms
= GetCommParams
<Params
>(cb
->callback
);
272 /* Ok, we can be reasonably sure we won't lose any data here! */
273 assert(call
->dialer
.handler
== callback
);
274 assert(params
.data
== data
);
276 /* Delete the callback */
277 cb
->cancel("old comm_read_cancel");
279 /* And the IO event */
280 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
284 comm_read_cancel(int fd
, AsyncCall::Pointer
&callback
)
286 callback
->cancel("comm_read_cancel");
289 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " closed");
293 Comm::IoCallback
*cb
= COMMIO_FD_READCB(fd
);
296 debugs(5, 4, "comm_read_cancel fails: FD " << fd
<< " inactive");
300 AsyncCall::Pointer call
= cb
->callback
;
301 assert(call
!= NULL
); // XXX: should never fail (active() checks for callback==NULL)
303 /* Ok, we can be reasonably sure we won't lose any data here! */
304 assert(call
== callback
);
306 /* Delete the callback */
307 cb
->cancel("comm_read_cancel");
309 /* And the IO event */
310 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
315 * synchronous wrapper around udp socket functions
318 comm_udp_recvfrom(int fd
, void *buf
, size_t len
, int flags
, Ip::Address
&from
)
320 statCounter
.syscalls
.sock
.recvfroms
++;
322 struct addrinfo
*AI
= NULL
;
324 debugs(5,8, "comm_udp_recvfrom: FD " << fd
<< " from " << from
);
326 assert( NULL
== AI
);
328 from
.InitAddrInfo(AI
);
330 x
= recvfrom(fd
, buf
, len
, flags
, AI
->ai_addr
, &AI
->ai_addrlen
);
334 from
.FreeAddrInfo(AI
);
340 comm_udp_recv(int fd
, void *buf
, size_t len
, int flags
)
343 return comm_udp_recvfrom(fd
, buf
, len
, flags
, nul
);
347 comm_udp_send(int s
, const void *buf
, size_t len
, int flags
)
349 return send(s
, buf
, len
, flags
);
354 comm_has_incomplete_write(int fd
)
357 return COMMIO_FD_WRITECB(fd
)->active();
361 * Queue a write. handler/handler_data are called when the write fully
362 * completes, on error, or on file descriptor close.
365 /* Return the local port associated with fd. */
367 comm_local_port(int fd
)
370 struct addrinfo
*addr
= NULL
;
371 fde
*F
= &fd_table
[fd
];
373 /* If the fd is closed already, just return */
375 if (!F
->flags
.open
) {
376 debugs(5, 0, "comm_local_port: FD " << fd
<< " has been closed.");
380 if (F
->local_addr
.GetPort())
381 return F
->local_addr
.GetPort();
383 if (F
->sock_family
== AF_INET
)
386 temp
.InitAddrInfo(addr
);
388 if (getsockname(fd
, addr
->ai_addr
, &(addr
->ai_addrlen
)) ) {
389 debugs(50, 1, "comm_local_port: Failed to retrieve TCP/UDP port number for socket: FD " << fd
<< ": " << xstrerror());
390 temp
.FreeAddrInfo(addr
);
395 temp
.FreeAddrInfo(addr
);
397 if (F
->local_addr
.IsAnyAddr()) {
398 /* save the whole local address, not just the port. */
399 F
->local_addr
= temp
;
401 F
->local_addr
.SetPort(temp
.GetPort());
404 debugs(5, 6, "comm_local_port: FD " << fd
<< ": port " << F
->local_addr
.GetPort() << "(family=" << F
->sock_family
<< ")");
405 return F
->local_addr
.GetPort();
409 commBind(int s
, struct addrinfo
&inaddr
)
411 statCounter
.syscalls
.sock
.binds
++;
413 if (bind(s
, inaddr
.ai_addr
, inaddr
.ai_addrlen
) == 0) {
414 debugs(50, 6, "commBind: bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
);
418 debugs(50, 0, "commBind: Cannot bind socket FD " << s
<< " to " << fd_table
[s
].local_addr
<< ": " << xstrerror());
424 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
425 * is OR of flags specified in comm.h. Defaults TOS
428 comm_open(int sock_type
,
434 return comm_openex(sock_type
, proto
, addr
, flags
, 0, 0, note
);
438 comm_open_listener(int sock_type
,
440 Comm::ConnectionPointer
&conn
,
443 /* all listener sockets require bind() */
444 conn
->flags
|= COMM_DOBIND
;
446 /* attempt native enabled port. */
447 conn
->fd
= comm_openex(sock_type
, proto
, conn
->local
, conn
->flags
, 0, 0, note
);
451 comm_open_listener(int sock_type
,
459 /* all listener sockets require bind() */
460 flags
|= COMM_DOBIND
;
462 /* attempt native enabled port. */
463 sock
= comm_openex(sock_type
, proto
, addr
, flags
, 0, 0, note
);
469 limitError(int const anErrno
)
471 return anErrno
== ENFILE
|| anErrno
== EMFILE
;
475 comm_set_v6only(int fd
, int tos
)
478 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
, (char *) &tos
, sizeof(int)) < 0) {
479 debugs(50, 1, "comm_open: setsockopt(IPV6_V6ONLY) " << (tos
?"ON":"OFF") << " for FD " << fd
<< ": " << xstrerror());
482 debugs(50, 0, "WARNING: comm_open: setsockopt(IPV6_V6ONLY) not supported on this platform");
487 * Set the socket IP_TRANSPARENT option for Linux TPROXY v4 support.
490 comm_set_transparent(int fd
)
492 #if defined(IP_TRANSPARENT)
494 if (setsockopt(fd
, SOL_IP
, IP_TRANSPARENT
, (char *) &tos
, sizeof(int)) < 0) {
495 debugs(50, DBG_IMPORTANT
, "comm_open: setsockopt(IP_TRANSPARENT) on FD " << fd
<< ": " << xstrerror());
497 /* mark the socket as having transparent options */
498 fd_table
[fd
].flags
.transparent
= 1;
501 debugs(50, DBG_CRITICAL
, "WARNING: comm_open: setsockopt(IP_TRANSPARENT) not supported on this platform");
506 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
507 * is OR of flags specified in defines.h:COMM_*
510 comm_openex(int sock_type
,
519 struct addrinfo
*AI
= NULL
;
521 PROF_start(comm_open
);
522 /* Create socket for accepting new connections. */
523 statCounter
.syscalls
.sock
.sockets
++;
525 /* Setup the socket addrinfo details for use */
526 addr
.GetAddrInfo(AI
);
527 AI
->ai_socktype
= sock_type
;
528 AI
->ai_protocol
= proto
;
530 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr
);
532 new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
534 /* under IPv6 there is the possibility IPv6 is present but disabled. */
535 /* try again as IPv4-native if possible */
536 if ( new_socket
< 0 && Ip::EnableIpv6
&& addr
.IsIPv6() && addr
.SetIPv4() ) {
537 /* attempt to open this IPv4-only. */
538 addr
.FreeAddrInfo(AI
);
539 /* Setup the socket addrinfo details for use */
540 addr
.GetAddrInfo(AI
);
541 AI
->ai_socktype
= sock_type
;
542 AI
->ai_protocol
= proto
;
543 debugs(50, 3, "comm_openex: Attempt fallback open socket for: " << addr
);
544 new_socket
= socket(AI
->ai_family
, AI
->ai_socktype
, AI
->ai_protocol
);
545 debugs(50, 2, HERE
<< "attempt open " << note
<< " socket on: " << addr
);
548 if (new_socket
< 0) {
549 /* Increase the number of reserved fd's if calls to socket()
550 * are failing because the open file table is full. This
551 * limits the number of simultaneous clients */
553 if (limitError(errno
)) {
554 debugs(50, DBG_IMPORTANT
, "comm_open: socket failure: " << xstrerror());
557 debugs(50, DBG_CRITICAL
, "comm_open: socket failure: " << xstrerror());
560 addr
.FreeAddrInfo(AI
);
562 PROF_stop(comm_open
);
566 // XXX: temporary for the transition. comm_openex will eventually have a conn to play with.
567 Comm::ConnectionPointer conn
= new Comm::Connection
;
569 conn
->fd
= new_socket
;
571 debugs(50, 3, "comm_openex: Opened socket " << conn
<< " : family=" << AI
->ai_family
<< ", type=" << AI
->ai_socktype
<< ", protocol=" << AI
->ai_protocol
);
573 /* set TOS if needed */
575 Ip::Qos::setSockTos(conn
, tos
);
577 /* set netfilter mark if needed */
579 Ip::Qos::setSockNfmark(conn
, nfmark
);
581 if ( Ip::EnableIpv6
&IPV6_SPECIAL_SPLITSTACK
&& addr
.IsIPv6() )
582 comm_set_v6only(conn
->fd
, 1);
584 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
585 /* Other OS may have this administratively disabled for general use. Same deal. */
586 if ( Ip::EnableIpv6
&IPV6_SPECIAL_V4MAPPING
&& addr
.IsIPv6() )
587 comm_set_v6only(conn
->fd
, 0);
589 comm_init_opened(conn
, tos
, nfmark
, note
, AI
);
590 new_socket
= comm_apply_flags(conn
->fd
, addr
, flags
, AI
);
592 addr
.FreeAddrInfo(AI
);
594 PROF_stop(comm_open
);
596 // XXX transition only. prevent conn from closing the new FD on function exit.
601 /// update FD tables after a local or remote (IPC) comm_openex();
603 comm_init_opened(const Comm::ConnectionPointer
&conn
,
609 assert(Comm::IsConnOpen(conn
));
613 debugs(5, 5, HERE
<< conn
<< " is a new socket");
615 assert(!isOpen(conn
->fd
)); // NP: global isOpen checks the fde entry for openness not the Comm::Connection
616 fd_open(conn
->fd
, FD_SOCKET
, note
);
618 fdd_table
[conn
->fd
].close_file
= NULL
;
619 fdd_table
[conn
->fd
].close_line
= 0;
621 fde
*F
= &fd_table
[conn
->fd
];
622 F
->local_addr
= conn
->local
;
623 F
->tosToServer
= tos
;
625 F
->nfmarkToServer
= nfmark
;
627 F
->sock_family
= AI
->ai_family
;
630 /// apply flags after a local comm_open*() call;
631 /// returns new_socket or -1 on error
633 comm_apply_flags(int new_socket
,
638 assert(new_socket
>= 0);
640 const int sock_type
= AI
->ai_socktype
;
642 if (!(flags
& COMM_NOCLOEXEC
))
643 commSetCloseOnExec(new_socket
);
645 if ((flags
& COMM_REUSEADDR
))
646 commSetReuseAddr(new_socket
);
648 if (addr
.GetPort() > (unsigned short) 0) {
650 if (sock_type
!= SOCK_DGRAM
)
652 commSetNoLinger(new_socket
);
655 commSetReuseAddr(new_socket
);
658 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
659 if ((flags
& COMM_TRANSPARENT
)) {
660 comm_set_transparent(new_socket
);
663 if ( (flags
& COMM_DOBIND
) || addr
.GetPort() > 0 || !addr
.IsAnyAddr() ) {
664 if ( !(flags
& COMM_DOBIND
) && addr
.IsAnyAddr() )
665 debugs(5,1,"WARNING: Squid is attempting to bind() port " << addr
<< " without being a listener.");
666 if ( addr
.IsNoAddr() )
667 debugs(5,0,"CRITICAL: Squid is attempting to bind() port " << addr
<< "!!");
669 if (commBind(new_socket
, *AI
) != COMM_OK
) {
670 comm_close(new_socket
);
675 if (flags
& COMM_NONBLOCKING
)
676 if (commSetNonBlocking(new_socket
) == COMM_ERROR
) {
677 comm_close(new_socket
);
682 if (sock_type
== SOCK_STREAM
)
683 commSetTcpNoDelay(new_socket
);
687 if (Config
.tcpRcvBufsz
> 0 && sock_type
== SOCK_STREAM
)
688 commSetTcpRcvbuf(new_socket
, Config
.tcpRcvBufsz
);
694 comm_import_opened(const Comm::ConnectionPointer
&conn
,
698 debugs(5, 2, HERE
<< conn
);
699 assert(Comm::IsConnOpen(conn
));
702 comm_init_opened(conn
, 0, 0, note
, AI
);
704 if (!(conn
->flags
& COMM_NOCLOEXEC
))
705 fd_table
[conn
->fd
].flags
.close_on_exec
= 1;
707 if (conn
->local
.GetPort() > (unsigned short) 0) {
709 if (AI
->ai_socktype
!= SOCK_DGRAM
)
711 fd_table
[conn
->fd
].flags
.nolinger
= 1;
714 if ((conn
->flags
& COMM_TRANSPARENT
))
715 fd_table
[conn
->fd
].flags
.transparent
= 1;
717 if (conn
->flags
& COMM_NONBLOCKING
)
718 fd_table
[conn
->fd
].flags
.nonblocking
= 1;
721 if (AI
->ai_socktype
== SOCK_STREAM
)
722 fd_table
[conn
->fd
].flags
.nodelay
= 1;
725 /* no fd_table[fd].flags. updates needed for these conditions:
726 * if ((flags & COMM_REUSEADDR)) ...
727 * if ((flags & COMM_DOBIND) ...) ...
731 // XXX: now that raw-FD timeouts are only unset for pipes and files this SHOULD be a no-op.
732 // With handler already unset. Leaving this present until that can be verified for all code paths.
734 commUnsetFdTimeout(int fd
)
736 debugs(5, 3, HERE
<< "Remove timeout for FD " << fd
);
738 assert(fd
< Squid_MaxFD
);
739 fde
*F
= &fd_table
[fd
];
740 assert(F
->flags
.open
);
742 F
->timeoutHandler
= NULL
;
747 commSetConnTimeout(const Comm::ConnectionPointer
&conn
, int timeout
, AsyncCall::Pointer
&callback
)
749 debugs(5, 3, HERE
<< conn
<< " timeout " << timeout
);
750 assert(Comm::IsConnOpen(conn
));
751 assert(conn
->fd
< Squid_MaxFD
);
752 fde
*F
= &fd_table
[conn
->fd
];
753 assert(F
->flags
.open
);
756 F
->timeoutHandler
= NULL
;
759 if (callback
!= NULL
) {
760 typedef CommTimeoutCbParams Params
;
761 Params
¶ms
= GetCommParams
<Params
>(callback
);
763 F
->timeoutHandler
= callback
;
766 F
->timeout
= squid_curtime
+ (time_t) timeout
;
773 commUnsetConnTimeout(const Comm::ConnectionPointer
&conn
)
775 debugs(5, 3, HERE
<< "Remove timeout for " << conn
);
776 AsyncCall::Pointer nil
;
777 return commSetConnTimeout(conn
, -1, nil
);
781 comm_connect_addr(int sock
, const Ip::Address
&address
)
783 comm_err_t status
= COMM_OK
;
784 fde
*F
= &fd_table
[sock
];
788 struct addrinfo
*AI
= NULL
;
789 PROF_start(comm_connect_addr
);
791 assert(address
.GetPort() != 0);
793 debugs(5, 9, HERE
<< "connecting socket FD " << sock
<< " to " << address
<< " (want family: " << F
->sock_family
<< ")");
795 /* Handle IPv6 over IPv4-only socket case.
796 * this case must presently be handled here since the GetAddrInfo asserts on bad mappings.
797 * NP: because commResetFD is private to ConnStateData we have to return an error and
798 * trust its handled properly.
800 if (F
->sock_family
== AF_INET
&& !address
.IsIPv4()) {
802 return COMM_ERR_PROTOCOL
;
805 /* Handle IPv4 over IPv6-only socket case.
806 * This case is presently handled here as it's both a known case and it's
807 * uncertain what error will be returned by the IPv6 stack in such case. It's
808 * possible this will also be handled by the errno checks below after connect()
809 * but needs carefull cross-platform verification, and verifying the address
810 * condition here is simple.
812 if (!F
->local_addr
.IsIPv4() && address
.IsIPv4()) {
814 return COMM_ERR_PROTOCOL
;
817 address
.GetAddrInfo(AI
, F
->sock_family
);
819 /* Establish connection. */
822 if (!F
->flags
.called_connect
) {
823 F
->flags
.called_connect
= 1;
824 statCounter
.syscalls
.sock
.connects
++;
826 x
= connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
828 // XXX: ICAP code refuses callbacks during a pending comm_ call
829 // Async calls development will fix this.
836 debugs(5,5, "comm_connect_addr: sock=" << sock
<< ", addrinfo( " <<
837 " flags=" << AI
->ai_flags
<<
838 ", family=" << AI
->ai_family
<<
839 ", socktype=" << AI
->ai_socktype
<<
840 ", protocol=" << AI
->ai_protocol
<<
841 ", &addr=" << AI
->ai_addr
<<
842 ", addrlen=" << AI
->ai_addrlen
<<
844 debugs(5, 9, "connect FD " << sock
<< ": (" << x
<< ") " << xstrerror());
845 debugs(14,9, "connecting to: " << address
);
849 /* Makoto MATSUSHITA <matusita@ics.es.osaka-u.ac.jp> */
851 connect(sock
, AI
->ai_addr
, AI
->ai_addrlen
);
853 if (errno
== EINVAL
) {
854 errlen
= sizeof(err
);
855 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
862 errlen
= sizeof(err
);
864 x
= getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
);
871 * Solaris 2.4's socket emulation doesn't allow you
872 * to determine the error from a failed non-blocking
873 * connect and just returns EPIPE. Create a fake
874 * error message for connect. -- fenner@parc.xerox.com
876 if (x
< 0 && errno
== EPIPE
)
884 /* Squid seems to be working fine without this code. With this code,
885 * we leak memory on many connect requests because of EINPROGRESS.
886 * If you find that this code is needed, please file a bug report. */
890 * Linux Debian replaces our allocated AI pointer with garbage when
891 * connect() fails. This leads to segmentation faults deallocating
892 * the system-allocated memory when we go to clean up our pointer.
893 * HACK: is to leak the memory returned since we can't deallocate.
901 address
.FreeAddrInfo(AI
);
903 PROF_stop(comm_connect_addr
);
905 if (errno
== 0 || errno
== EISCONN
)
907 else if (ignoreErrno(errno
))
908 status
= COMM_INPROGRESS
;
909 else if (errno
== EAFNOSUPPORT
|| errno
== EINVAL
)
910 return COMM_ERR_PROTOCOL
;
914 address
.NtoA(F
->ipaddr
, MAX_IPSTRLEN
);
916 F
->remote_port
= address
.GetPort(); /* remote_port is HS */
918 if (status
== COMM_OK
) {
919 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connected to " << address
);
920 } else if (status
== COMM_INPROGRESS
) {
921 debugs(5, 10, "comm_connect_addr: FD " << sock
<< " connection pending");
928 commCallCloseHandlers(int fd
)
930 fde
*F
= &fd_table
[fd
];
931 debugs(5, 5, "commCallCloseHandlers: FD " << fd
);
933 while (F
->closeHandler
!= NULL
) {
934 AsyncCall::Pointer call
= F
->closeHandler
;
935 F
->closeHandler
= call
->Next();
937 // If call is not canceled schedule it for execution else ignore it
938 if (!call
->canceled()) {
939 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call
);
940 ScheduleCallHere(call
);
947 commLingerClose(int fd
, void *unused
)
949 LOCAL_ARRAY(char, buf
, 1024);
951 n
= FD_READ_METHOD(fd
, buf
, 1024);
954 debugs(5, 3, "commLingerClose: FD " << fd
<< " read: " << xstrerror());
960 commLingerTimeout(const FdeCbParams
¶ms
)
962 debugs(5, 3, "commLingerTimeout: FD " << params
.fd
);
963 comm_close(params
.fd
);
970 comm_lingering_close(int fd
)
973 if (fd_table
[fd
].ssl
)
974 ssl_shutdown_method(fd_table
[fd
].ssl
);
977 if (shutdown(fd
, 1) < 0) {
982 fd_note(fd
, "lingering close");
983 AsyncCall::Pointer call
= commCbCall(5,4, "commLingerTimeout", FdeCbPtrFun(commLingerTimeout
, NULL
));
985 debugs(5, 3, HERE
<< "FD " << fd
<< " timeout " << timeout
);
986 assert(fd_table
[fd
].flags
.open
);
987 if (callback
!= NULL
) {
988 typedef FdeCbParams Params
;
989 Params
¶ms
= GetCommParams
<Params
>(callback
);
991 fd_table
[fd
].timeoutHandler
= callback
;
992 fd_table
[fd
].timeout
= squid_curtime
+ static_cast<time_t>(10);
995 Comm::SetSelect(fd
, COMM_SELECT_READ
, commLingerClose
, NULL
, 0);
1001 * enable linger with time of 0 so that when the socket is
1002 * closed, TCP generates a RESET
1005 comm_reset_close(const Comm::ConnectionPointer
&conn
)
1011 if (setsockopt(conn
->fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1012 debugs(50, DBG_CRITICAL
, "ERROR: Closing " << conn
<< " with TCP RST: " << xstrerror());
1017 // Legacy close function.
1019 old_comm_reset_close(int fd
)
1025 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1026 debugs(50, DBG_CRITICAL
, "ERROR: Closing FD " << fd
<< " with TCP RST: " << xstrerror());
1033 commStartSslClose(const FdeCbParams
¶ms
)
1035 assert(&fd_table
[params
.fd
].ssl
);
1036 ssl_shutdown_method(fd_table
[params
.fd
].ssl
);
1041 comm_close_complete(const FdeCbParams
¶ms
)
1044 fde
*F
= &fd_table
[params
.fd
];
1051 if (F
->dynamicSslContext
) {
1052 SSL_CTX_free(F
->dynamicSslContext
);
1053 F
->dynamicSslContext
= NULL
;
1056 fd_close(params
.fd
); /* update fdstat */
1059 statCounter
.syscalls
.sock
.closes
++;
1061 /* When one connection closes, give accept() a chance, if need be */
1062 Comm::AcceptLimiter::Instance().kick();
1066 * Close the socket fd.
1068 * + call write handlers with ERR_CLOSING
1069 * + call read handlers with ERR_CLOSING
1070 * + call closing handlers
1072 * NOTE: COMM_ERR_CLOSING will NOT be called for CommReads' sitting in a
1073 * DeferredReadManager.
1076 _comm_close(int fd
, char const *file
, int line
)
1078 debugs(5, 3, "comm_close: start closing FD " << fd
);
1080 assert(fd
< Squid_MaxFD
);
1082 fde
*F
= &fd_table
[fd
];
1083 fdd_table
[fd
].close_file
= file
;
1084 fdd_table
[fd
].close_line
= line
;
1089 /* XXX: is this obsolete behind F->closing() ? */
1090 if ( (shutting_down
|| reconfiguring
) && (!F
->flags
.open
|| F
->type
== FD_FILE
))
1093 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
1096 assert(F
->type
!= FD_FILE
);
1098 PROF_start(comm_close
);
1100 F
->flags
.close_request
= 1;
1104 AsyncCall::Pointer startCall
=commCbCall(5,4, "commStartSslClose",
1105 FdeCbPtrFun(commStartSslClose
, NULL
));
1106 FdeCbParams
&startParams
= GetCommParams
<FdeCbParams
>(startCall
);
1107 startParams
.fd
= fd
;
1108 ScheduleCallHere(startCall
);
1112 // a half-closed fd may lack a reader, so we stop monitoring explicitly
1113 if (commHasHalfClosedMonitor(fd
))
1114 commStopHalfClosedMonitor(fd
);
1115 commUnsetFdTimeout(fd
);
1117 // notify read/write handlers after canceling select reservations, if any
1118 if (COMMIO_FD_WRITECB(fd
)->active()) {
1119 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
1120 COMMIO_FD_WRITECB(fd
)->finish(COMM_ERR_CLOSING
, errno
);
1122 if (COMMIO_FD_READCB(fd
)->active()) {
1123 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULL
, NULL
, 0);
1124 COMMIO_FD_READCB(fd
)->finish(COMM_ERR_CLOSING
, errno
);
1128 if (ClientInfo
*clientInfo
= F
->clientInfo
) {
1129 if (clientInfo
->selectWaiting
) {
1130 clientInfo
->selectWaiting
= false;
1131 // kick queue or it will get stuck as commWriteHandle is not called
1132 clientInfo
->kickQuotaQueue();
1137 commCallCloseHandlers(fd
);
1139 if (F
->pconn
.uses
&& F
->pconn
.pool
)
1140 F
->pconn
.pool
->noteUses(F
->pconn
.uses
);
1142 comm_empty_os_read_buffers(fd
);
1145 AsyncCall::Pointer completeCall
=commCbCall(5,4, "comm_close_complete",
1146 FdeCbPtrFun(comm_close_complete
, NULL
));
1147 FdeCbParams
&completeParams
= GetCommParams
<FdeCbParams
>(completeCall
);
1148 completeParams
.fd
= fd
;
1149 // must use async call to wait for all callbacks
1150 // scheduled before comm_close() to finish
1151 ScheduleCallHere(completeCall
);
1153 PROF_stop(comm_close
);
1156 /* Send a udp datagram to specified TO_ADDR. */
1158 comm_udp_sendto(int fd
,
1159 const Ip::Address
&to_addr
,
1164 struct addrinfo
*AI
= NULL
;
1166 PROF_start(comm_udp_sendto
);
1167 statCounter
.syscalls
.sock
.sendtos
++;
1169 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr
<<
1170 " using FD " << fd
<< " using Port " << comm_local_port(fd
) );
1172 /* BUG: something in the above macro appears to occasionally be setting AI to garbage. */
1173 /* AYJ: 2007-08-27 : or was it because I wasn't then setting 'fd_table[fd].sock_family' to fill properly. */
1174 assert( NULL
== AI
);
1176 to_addr
.GetAddrInfo(AI
, fd_table
[fd
].sock_family
);
1178 x
= sendto(fd
, buf
, len
, 0, AI
->ai_addr
, AI
->ai_addrlen
);
1180 to_addr
.FreeAddrInfo(AI
);
1182 PROF_stop(comm_udp_sendto
);
1189 if (ECONNREFUSED
!= errno
)
1192 debugs(50, 1, "comm_udp_sendto: FD " << fd
<< ", (family=" << fd_table
[fd
].sock_family
<< ") " << to_addr
<< ": " << xstrerror());
1198 comm_add_close_handler(int fd
, CLCB
* handler
, void *data
)
1200 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", handler=" <<
1201 handler
<< ", data=" << data
);
1203 AsyncCall::Pointer call
=commCbCall(5,4, "SomeCloseHandler",
1204 CommCloseCbPtrFun(handler
, data
));
1205 comm_add_close_handler(fd
, call
);
1209 comm_add_close_handler(int fd
, AsyncCall::Pointer
&call
)
1211 debugs(5, 5, "comm_add_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1213 /*TODO:Check for a similar scheduled AsyncCall*/
1214 // for (c = fd_table[fd].closeHandler; c; c = c->next)
1215 // assert(c->handler != handler || c->data != data);
1217 call
->setNext(fd_table
[fd
].closeHandler
);
1219 fd_table
[fd
].closeHandler
= call
;
1223 // remove function-based close handler
1225 comm_remove_close_handler(int fd
, CLCB
* handler
, void *data
)
1227 assert (isOpen(fd
));
1228 /* Find handler in list */
1229 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", handler=" <<
1230 handler
<< ", data=" << data
);
1232 AsyncCall::Pointer p
, prev
= NULL
;
1233 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
; prev
= p
, p
= p
->Next()) {
1234 typedef CommCbFunPtrCallT
<CommCloseCbPtrFun
> Call
;
1235 const Call
*call
= dynamic_cast<const Call
*>(p
.getRaw());
1236 if (!call
) // method callbacks have their own comm_remove_close_handler
1239 typedef CommCloseCbParams Params
;
1240 const Params
¶ms
= GetCommParams
<Params
>(p
);
1241 if (call
->dialer
.handler
== handler
&& params
.data
== data
)
1242 break; /* This is our handler */
1245 // comm_close removes all close handlers so our handler may be gone
1247 p
->dequeue(fd_table
[fd
].closeHandler
, prev
);
1248 p
->cancel("comm_remove_close_handler");
1252 // remove method-based close handler
1254 comm_remove_close_handler(int fd
, AsyncCall::Pointer
&call
)
1256 assert (isOpen(fd
));
1257 debugs(5, 5, "comm_remove_close_handler: FD " << fd
<< ", AsyncCall=" << call
);
1259 // comm_close removes all close handlers so our handler may be gone
1260 AsyncCall::Pointer p
, prev
= NULL
;
1261 for (p
= fd_table
[fd
].closeHandler
; p
!= NULL
&& p
!= call
; prev
= p
, p
= p
->Next());
1264 p
->dequeue(fd_table
[fd
].closeHandler
, prev
);
1265 call
->cancel("comm_remove_close_handler");
1269 commSetNoLinger(int fd
)
1273 L
.l_onoff
= 0; /* off */
1276 if (setsockopt(fd
, SOL_SOCKET
, SO_LINGER
, (char *) &L
, sizeof(L
)) < 0)
1277 debugs(50, 0, "commSetNoLinger: FD " << fd
<< ": " << xstrerror());
1279 fd_table
[fd
].flags
.nolinger
= 1;
1283 commSetReuseAddr(int fd
)
1287 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (char *) &on
, sizeof(on
)) < 0)
1288 debugs(50, 1, "commSetReuseAddr: FD " << fd
<< ": " << xstrerror());
1292 commSetTcpRcvbuf(int fd
, int size
)
1294 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, (char *) &size
, sizeof(size
)) < 0)
1295 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1296 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, (char *) &size
, sizeof(size
)) < 0)
1297 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1298 #ifdef TCP_WINDOW_CLAMP
1299 if (setsockopt(fd
, SOL_TCP
, TCP_WINDOW_CLAMP
, (char *) &size
, sizeof(size
)) < 0)
1300 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd
<< ", SIZE " << size
<< ": " << xstrerror());
1305 commSetNonBlocking(int fd
)
1312 int nonblocking
= TRUE
;
1315 if (fd_table
[fd
].type
!= FD_PIPE
) {
1318 if (ioctl(fd
, FIONBIO
, &nonblocking
) < 0) {
1319 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror() << " " << fd_table
[fd
].type
);
1329 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1330 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1334 if (fcntl(fd
, F_SETFL
, flags
| SQUID_NONBLOCK
) < 0) {
1335 debugs(50, 0, "commSetNonBlocking: FD " << fd
<< ": " << xstrerror());
1343 fd_table
[fd
].flags
.nonblocking
= 1;
1349 commUnsetNonBlocking(int fd
)
1352 int nonblocking
= FALSE
;
1354 if (ioctlsocket(fd
, FIONBIO
, (unsigned long *) &nonblocking
) < 0) {
1359 if ((flags
= fcntl(fd
, F_GETFL
, dummy
)) < 0) {
1360 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFL: " << xstrerror());
1364 if (fcntl(fd
, F_SETFL
, flags
& (~SQUID_NONBLOCK
)) < 0) {
1366 debugs(50, 0, "commUnsetNonBlocking: FD " << fd
<< ": " << xstrerror());
1370 fd_table
[fd
].flags
.nonblocking
= 0;
1375 commSetCloseOnExec(int fd
)
1381 if ((flags
= fcntl(fd
, F_GETFD
, dummy
)) < 0) {
1382 debugs(50, 0, "FD " << fd
<< ": fcntl F_GETFD: " << xstrerror());
1386 if (fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) < 0)
1387 debugs(50, 0, "FD " << fd
<< ": set close-on-exec failed: " << xstrerror());
1389 fd_table
[fd
].flags
.close_on_exec
= 1;
1396 commSetTcpNoDelay(int fd
)
1400 if (setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *) &on
, sizeof(on
)) < 0)
1401 debugs(50, 1, "commSetTcpNoDelay: FD " << fd
<< ": " << xstrerror());
1403 fd_table
[fd
].flags
.nodelay
= 1;
1409 commSetTcpKeepalive(int fd
, int idle
, int interval
, int timeout
)
1413 if (timeout
&& interval
) {
1414 int count
= (timeout
+ interval
- 1) / interval
;
1415 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPCNT
, &count
, sizeof(on
)) < 0)
1416 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1421 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPIDLE
, &idle
, sizeof(on
)) < 0)
1422 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1425 #ifdef TCP_KEEPINTVL
1427 if (setsockopt(fd
, IPPROTO_TCP
, TCP_KEEPINTVL
, &interval
, sizeof(on
)) < 0)
1428 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1431 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (char *) &on
, sizeof(on
)) < 0)
1432 debugs(5, 1, "commSetKeepalive: FD " << fd
<< ": " << xstrerror());
1438 fd_table
=(fde
*) xcalloc(Squid_MaxFD
, sizeof(fde
));
1439 fdd_table
= (fd_debug_t
*)xcalloc(Squid_MaxFD
, sizeof(fd_debug_t
));
1441 /* make sure the accept() socket FIFO delay queue exists */
1442 Comm::AcceptLimiter::Instance();
1444 // make sure the IO pending callback table exists
1445 Comm::CallbackTableInit();
1447 /* XXX account fd_table */
1448 /* Keep a few file descriptors free so that we don't run out of FD's
1449 * after accepting a client but before it opens a socket or a file.
1450 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
1451 RESERVED_FD
= min(100, Squid_MaxFD
/ 4);
1453 conn_close_pool
= memPoolCreate("close_handler", sizeof(close_handler
));
1455 TheHalfClosed
= new DescriptorSet
;
1457 /* setup the select loop module */
1458 Comm::SelectLoopInit();
1464 delete TheHalfClosed
;
1465 TheHalfClosed
= NULL
;
1467 safe_free(fd_table
);
1468 safe_free(fdd_table
);
1469 Comm::CallbackTableDestruct();
1473 // called when the queue is done waiting for the client bucket to fill
1475 commHandleWriteHelper(void * data
)
1477 CommQuotaQueue
*queue
= static_cast<CommQuotaQueue
*>(data
);
1480 ClientInfo
*clientInfo
= queue
->clientInfo
;
1481 // ClientInfo invalidates queue if freed, so if we got here through,
1482 // evenAdd cbdata protections, everything should be valid and consistent
1484 assert(clientInfo
->hasQueue());
1485 assert(clientInfo
->hasQueue(queue
));
1486 assert(!clientInfo
->selectWaiting
);
1487 assert(clientInfo
->eventWaiting
);
1488 clientInfo
->eventWaiting
= false;
1491 // check that the head descriptor is still relevant
1492 const int head
= clientInfo
->quotaPeekFd();
1493 Comm::IoCallback
*ccb
= COMMIO_FD_WRITECB(head
);
1495 if (fd_table
[head
].clientInfo
== clientInfo
&&
1496 clientInfo
->quotaPeekReserv() == ccb
->quotaQueueReserv
&&
1497 !fd_table
[head
].closing()) {
1499 // wait for the head descriptor to become ready for writing
1500 Comm::SetSelect(head
, COMM_SELECT_WRITE
, Comm::HandleWrite
, ccb
, 0);
1501 clientInfo
->selectWaiting
= true;
1505 clientInfo
->quotaDequeue(); // remove the no longer relevant descriptor
1506 // and continue looking for a relevant one
1507 } while (clientInfo
->hasQueue());
1509 debugs(77,3, HERE
<< "emptied queue");
1513 ClientInfo::hasQueue() const
1516 return !quotaQueue
->empty();
1520 ClientInfo::hasQueue(const CommQuotaQueue
*q
) const
1523 return quotaQueue
== q
;
1526 /// returns the first descriptor to be dequeued
1528 ClientInfo::quotaPeekFd() const
1531 return quotaQueue
->front();
1534 /// returns the reservation ID of the first descriptor to be dequeued
1536 ClientInfo::quotaPeekReserv() const
1539 return quotaQueue
->outs
+ 1;
1542 /// queues a given fd, creating the queue if necessary; returns reservation ID
1544 ClientInfo::quotaEnqueue(int fd
)
1547 return quotaQueue
->enqueue(fd
);
1550 /// removes queue head
1552 ClientInfo::quotaDequeue()
1555 quotaQueue
->dequeue();
1559 ClientInfo::kickQuotaQueue()
1561 if (!eventWaiting
&& !selectWaiting
&& hasQueue()) {
1562 // wait at least a second if the bucket is empty
1563 const double delay
= (bucketSize
< 1.0) ? 1.0 : 0.0;
1564 eventAdd("commHandleWriteHelper", &commHandleWriteHelper
,
1565 quotaQueue
, delay
, 0, true);
1566 eventWaiting
= true;
1570 /// calculates how much to write for a single dequeued client
1572 ClientInfo::quotaForDequed()
1574 /* If we have multiple clients and give full bucketSize to each client then
1575 * clt1 may often get a lot more because clt1->clt2 time distance in the
1576 * select(2) callback order may be a lot smaller than cltN->clt1 distance.
1577 * We divide quota evenly to be more fair. */
1579 if (!rationedCount
) {
1580 rationedCount
= quotaQueue
->size() + 1;
1582 // The delay in ration recalculation _temporary_ deprives clients from
1583 // bytes that should have trickled in while rationedCount was positive.
1586 // Rounding errors do not accumulate here, but we round down to avoid
1587 // negative bucket sizes after write with rationedCount=1.
1588 rationedQuota
= static_cast<int>(floor(bucketSize
/rationedCount
));
1589 debugs(77,5, HERE
<< "new rationedQuota: " << rationedQuota
<<
1590 '*' << rationedCount
);
1594 debugs(77,7, HERE
<< "rationedQuota: " << rationedQuota
<<
1595 " rations remaining: " << rationedCount
);
1597 // update 'last seen' time to prevent clientdb GC from dropping us
1598 last_seen
= squid_curtime
;
1599 return rationedQuota
;
1602 ///< adds bytes to the quota bucket based on the rate and passed time
1604 ClientInfo::refillBucket()
1606 // all these times are in seconds, with double precision
1607 const double currTime
= current_dtime
;
1608 const double timePassed
= currTime
- prevTime
;
1610 // Calculate allowance for the time passed. Use double to avoid
1611 // accumulating rounding errors for small intervals. For example, always
1612 // adding 1 byte instead of 1.4 results in 29% bandwidth allocation error.
1613 const double gain
= timePassed
* writeSpeedLimit
;
1615 debugs(77,5, HERE
<< currTime
<< " clt" << (const char*)hash
.key
<< ": " <<
1616 bucketSize
<< " + (" << timePassed
<< " * " << writeSpeedLimit
<<
1617 " = " << gain
<< ')');
1619 // to further combat error accumulation during micro updates,
1620 // quit before updating time if we cannot add at least one byte
1624 prevTime
= currTime
;
1626 // for "first" connections, drain initial fat before refilling but keep
1627 // updating prevTime to avoid bursts after the fat is gone
1628 if (bucketSize
> bucketSizeLimit
) {
1629 debugs(77,4, HERE
<< "not refilling while draining initial fat");
1635 // obey quota limits
1636 if (bucketSize
> bucketSizeLimit
)
1637 bucketSize
= bucketSizeLimit
;
1641 ClientInfo::setWriteLimiter(const int aWriteSpeedLimit
, const double anInitialBurst
, const double aHighWatermark
)
1643 debugs(77,5, HERE
<< "Write limits for " << (const char*)hash
.key
<<
1644 " speed=" << aWriteSpeedLimit
<< " burst=" << anInitialBurst
<<
1645 " highwatermark=" << aHighWatermark
);
1647 // set or possibly update traffic shaping parameters
1648 writeLimitingActive
= true;
1649 writeSpeedLimit
= aWriteSpeedLimit
;
1650 bucketSizeLimit
= aHighWatermark
;
1652 // but some members should only be set once for a newly activated bucket
1653 if (firstTimeConnection
) {
1654 firstTimeConnection
= false;
1656 assert(!selectWaiting
);
1657 assert(!quotaQueue
);
1658 quotaQueue
= new CommQuotaQueue(this);
1660 bucketSize
= anInitialBurst
;
1661 prevTime
= current_dtime
;
1665 CommQuotaQueue::CommQuotaQueue(ClientInfo
*info
): clientInfo(info
),
1671 CommQuotaQueue::~CommQuotaQueue()
1673 assert(!clientInfo
); // ClientInfo should clear this before destroying us
1676 /// places the given fd at the end of the queue; returns reservation ID
1678 CommQuotaQueue::enqueue(int fd
)
1680 debugs(77,5, HERE
<< "clt" << (const char*)clientInfo
->hash
.key
<<
1681 ": FD " << fd
<< " with qqid" << (ins
+1) << ' ' << fds
.size());
1686 /// removes queue head
1688 CommQuotaQueue::dequeue()
1690 assert(!fds
.empty());
1691 debugs(77,5, HERE
<< "clt" << (const char*)clientInfo
->hash
.key
<<
1692 ": FD " << fds
.front() << " with qqid" << (outs
+1) << ' ' <<
1700 * hm, this might be too general-purpose for all the places we'd
1704 ignoreErrno(int ierrno
)
1711 #if EAGAIN != EWOULDBLOCK
1734 commCloseAllSockets(void)
1739 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
1745 if (F
->type
!= FD_SOCKET
)
1748 if (F
->flags
.ipc
) /* don't close inter-process sockets */
1751 if (F
->timeoutHandler
!= NULL
) {
1752 AsyncCall::Pointer callback
= F
->timeoutHandler
;
1753 F
->timeoutHandler
= NULL
;
1754 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": Calling timeout handler");
1755 ScheduleCallHere(callback
);
1757 debugs(5, 5, "commCloseAllSockets: FD " << fd
<< ": calling comm_reset_close()");
1758 old_comm_reset_close(fd
);
1764 AlreadyTimedOut(fde
*F
)
1769 if (F
->timeout
== 0)
1772 if (F
->timeout
> squid_curtime
)
1779 writeTimedOut(int fd
)
1781 if (!COMMIO_FD_WRITECB(fd
)->active())
1784 if ((squid_curtime
- fd_table
[fd
].writeStart
) < Config
.Timeout
.write
)
1795 AsyncCall::Pointer callback
;
1797 for (fd
= 0; fd
<= Biggest_FD
; fd
++) {
1800 if (writeTimedOut(fd
)) {
1801 // We have an active write callback and we are timed out
1802 debugs(5, 5, "checkTimeouts: FD " << fd
<< " auto write timeout");
1803 Comm::SetSelect(fd
, COMM_SELECT_WRITE
, NULL
, NULL
, 0);
1804 COMMIO_FD_WRITECB(fd
)->finish(COMM_ERROR
, ETIMEDOUT
);
1805 } else if (AlreadyTimedOut(F
))
1808 debugs(5, 5, "checkTimeouts: FD " << fd
<< " Expired");
1810 if (F
->timeoutHandler
!= NULL
) {
1811 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Call timeout handler");
1812 callback
= F
->timeoutHandler
;
1813 F
->timeoutHandler
= NULL
;
1814 ScheduleCallHere(callback
);
1816 debugs(5, 5, "checkTimeouts: FD " << fd
<< ": Forcing comm_close()");
1822 void CommIO::Initialise()
1824 /* Initialize done pipe signal */
1826 if (pipe(DonePipe
)) {}
1827 DoneFD
= DonePipe
[1];
1828 DoneReadFD
= DonePipe
[0];
1829 fd_open(DoneReadFD
, FD_PIPE
, "async-io completetion event: main");
1830 fd_open(DoneFD
, FD_PIPE
, "async-io completetion event: threads");
1831 commSetNonBlocking(DoneReadFD
);
1832 commSetNonBlocking(DoneFD
);
1833 Comm::SetSelect(DoneReadFD
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
1837 void CommIO::NotifyIOClose()
1839 /* Close done pipe signal */
1844 fd_close(DoneReadFD
);
1845 Initialised
= false;
1848 bool CommIO::Initialised
= false;
1849 bool CommIO::DoneSignalled
= false;
1850 int CommIO::DoneFD
= -1;
1851 int CommIO::DoneReadFD
= -1;
1857 FD_READ_METHOD(DoneReadFD
, buf
, sizeof(buf
));
1861 CommIO::NULLFDHandler(int fd
, void *data
)
1864 Comm::SetSelect(fd
, COMM_SELECT_READ
, NULLFDHandler
, NULL
, 0);
1868 CommIO::ResetNotifications()
1870 if (DoneSignalled
) {
1872 DoneSignalled
= false;
1876 /// Start waiting for a possibly half-closed connection to close
1877 // by scheduling a read callback to a monitoring handler that
1878 // will close the connection on read errors.
1880 commStartHalfClosedMonitor(int fd
)
1882 debugs(5, 5, HERE
<< "adding FD " << fd
<< " to " << *TheHalfClosed
);
1884 assert(!commHasHalfClosedMonitor(fd
));
1885 (void)TheHalfClosed
->add(fd
); // could also assert the result
1886 commPlanHalfClosedCheck(); // may schedule check if we added the first FD
1891 commPlanHalfClosedCheck()
1893 if (!WillCheckHalfClosed
&& !TheHalfClosed
->empty()) {
1894 eventAdd("commHalfClosedCheck", &commHalfClosedCheck
, NULL
, 1.0, 1);
1895 WillCheckHalfClosed
= true;
1899 /// iterates over all descriptors that may need half-closed tests and
1900 /// calls comm_read for those that do; re-schedules the check if needed
1903 commHalfClosedCheck(void *)
1905 debugs(5, 5, HERE
<< "checking " << *TheHalfClosed
);
1907 typedef DescriptorSet::const_iterator DSCI
;
1908 const DSCI end
= TheHalfClosed
->end();
1909 for (DSCI i
= TheHalfClosed
->begin(); i
!= end
; ++i
) {
1910 Comm::ConnectionPointer c
= new Comm::Connection
; // XXX: temporary. make HalfClosed a list of these.
1912 if (!fd_table
[c
->fd
].halfClosedReader
) { // not reading already
1913 AsyncCall::Pointer call
= commCbCall(5,4, "commHalfClosedReader",
1914 CommIoCbPtrFun(&commHalfClosedReader
, NULL
));
1915 comm_read(c
, NULL
, 0, call
);
1916 fd_table
[c
->fd
].halfClosedReader
= call
;
1918 c
->fd
= -1; // XXX: temporary. prevent c replacement erase closing listed FD
1921 WillCheckHalfClosed
= false; // as far as we know
1922 commPlanHalfClosedCheck(); // may need to check again
1925 /// checks whether we are waiting for possibly half-closed connection to close
1926 // We are monitoring if the read handler for the fd is the monitoring handler.
1928 commHasHalfClosedMonitor(int fd
)
1930 return TheHalfClosed
->has(fd
);
1933 /// stop waiting for possibly half-closed connection to close
1935 commStopHalfClosedMonitor(int const fd
)
1937 debugs(5, 5, HERE
<< "removing FD " << fd
<< " from " << *TheHalfClosed
);
1939 // cancel the read if one was scheduled
1940 AsyncCall::Pointer reader
= fd_table
[fd
].halfClosedReader
;
1942 comm_read_cancel(fd
, reader
);
1943 fd_table
[fd
].halfClosedReader
= NULL
;
1945 TheHalfClosed
->del(fd
);
1948 /// I/O handler for the possibly half-closed connection monitoring code
1950 commHalfClosedReader(const Comm::ConnectionPointer
&conn
, char *, size_t size
, comm_err_t flag
, int, void *)
1952 // there cannot be more data coming in on half-closed connections
1954 assert(conn
!= NULL
);
1955 assert(commHasHalfClosedMonitor(conn
->fd
)); // or we would have canceled the read
1957 fd_table
[conn
->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, HERE
<< "closing " << conn
);
1970 // continue waiting for close or error
1971 commPlanHalfClosedCheck(); // make sure this fd will be checked again
1975 CommRead::CommRead() : conn(NULL
), buf(NULL
), len(0), callback(NULL
) {}
1977 CommRead::CommRead(const Comm::ConnectionPointer
&c
, char *buf_
, int len_
, AsyncCall::Pointer
&callback_
)
1978 : conn(c
), 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 " << aRead
.theRead
.conn
);
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 // XXX: and yet we use cbdata protection functions on it??
2006 AsyncCall::Pointer closer
= commCbCall(5,4,
2007 "DeferredReadManager::CloseHandler",
2008 CommCloseCbPtrFun(&CloseHandler
, temp
));
2009 comm_add_close_handler(aRead
.theRead
.conn
->fd
, closer
);
2010 temp
->element
.closer
= closer
; // remeber so that we can cancel
2014 DeferredReadManager::CloseHandler(const CommCloseCbParams
¶ms
)
2016 if (!cbdataReferenceValid(params
.data
))
2019 CbDataList
<DeferredRead
> *temp
= (CbDataList
<DeferredRead
> *)params
.data
;
2021 temp
->element
.closer
= NULL
;
2022 temp
->element
.markCancelled();
2026 DeferredReadManager::popHead(CbDataListContainer
<DeferredRead
> &deferredReads
)
2028 assert (!deferredReads
.empty());
2030 DeferredRead
&read
= deferredReads
.head
->element
;
2032 // NOTE: at this point the connection has been paused/stalled for an unknown
2033 // amount of time. We must re-validate that it is active and usable.
2035 // If the connection has been closed already. Cancel this read.
2036 if (!Comm::IsConnOpen(read
.theRead
.conn
)) {
2037 if (read
.closer
!= NULL
) {
2038 read
.closer
->cancel("Connection closed before.");
2041 read
.markCancelled();
2044 if (!read
.cancelled
) {
2045 comm_remove_close_handler(read
.theRead
.conn
->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 (Comm::IsConnOpen(aRead
.theRead
.conn
) && fd_table
[aRead
.theRead
.conn
->fd
].closing())
2098 debugs(5, 3, "Kicking deferred read on " << aRead
.theRead
.conn
);
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::DoSelect(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
);