]> git.ipfire.org Git - thirdparty/squid.git/blob - src/comm.cc
Merged from trunk
[thirdparty/squid.git] / src / comm.cc
1 /*
2 * DEBUG: section 5 Socket Functions
3 * AUTHOR: Harvest Derived
4 *
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
7 *
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.
16 *
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.
21 *
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.
26 *
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.
30 *
31 *
32 * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org>
33 */
34
35 #include "squid.h"
36 #include "StoreIOBuffer.h"
37 #include "comm.h"
38 #include "event.h"
39 #include "fde.h"
40 #include "comm/AcceptLimiter.h"
41 #include "comm/comm_internal.h"
42 #include "comm/ListenStateData.h"
43 #include "CommIO.h"
44 #include "CommRead.h"
45 #include "ConnectionDetail.h"
46 #include "MemBuf.h"
47 #include "pconn.h"
48 #include "SquidTime.h"
49 #include "CommCalls.h"
50 #include "DescriptorSet.h"
51 #include "icmp/net_db.h"
52 #include "ip/IpAddress.h"
53 #include "ip/IpIntercept.h"
54
55 #if defined(_SQUID_CYGWIN_)
56 #include <sys/ioctl.h>
57 #endif
58 #ifdef HAVE_NETINET_TCP_H
59 #include <netinet/tcp.h>
60 #endif
61
62 /*
63 * New C-like simple comm code. This stuff is a mess and doesn't really buy us anything.
64 */
65
66 typedef enum {
67 IOCB_NONE,
68 IOCB_READ,
69 IOCB_WRITE
70 } iocb_type;
71
72 static void commStopHalfClosedMonitor(int fd);
73 static IOCB commHalfClosedReader;
74
75
76 struct comm_io_callback_t {
77 iocb_type type;
78 int fd;
79 AsyncCall::Pointer callback;
80 char *buf;
81 FREE *freefunc;
82 int size;
83 int offset;
84 comm_err_t errcode;
85 int xerrno;
86
87 bool active() const { return callback != NULL; }
88 };
89
90 struct _comm_fd {
91 int fd;
92 comm_io_callback_t readcb;
93 comm_io_callback_t writecb;
94 };
95 typedef struct _comm_fd comm_fd_t;
96 comm_fd_t *commfd_table;
97
98 // TODO: make this a comm_io_callback_t method?
99 bool
100 commio_has_callback(int fd, iocb_type type, comm_io_callback_t *ccb)
101 {
102 assert(ccb->fd == fd);
103 assert(ccb->type == type);
104 return ccb->active();
105 }
106
107 /*
108 * Configure comm_io_callback_t for I/O
109 *
110 * @param fd filedescriptor
111 * @param ccb comm io callback
112 * @param cb callback
113 * @param cbdata callback data (must be cbdata'ed)
114 * @param buf buffer, if applicable
115 * @param freefunc freefunc, if applicable
116 * @param size buffer size
117 */
118 static void
119 commio_set_callback(int fd, iocb_type type, comm_io_callback_t *ccb,
120 AsyncCall::Pointer &cb, char *buf, FREE *freefunc, int size)
121 {
122 assert(!ccb->active());
123 assert(ccb->type == type);
124 assert(cb != NULL);
125 ccb->fd = fd;
126 ccb->callback = cb;
127 ccb->buf = buf;
128 ccb->freefunc = freefunc;
129 ccb->size = size;
130 ccb->offset = 0;
131 }
132
133
134 // Schedule the callback call and clear the callback
135 static void
136 commio_finish_callback(int fd, comm_io_callback_t *ccb, comm_err_t code, int xerrno)
137 {
138 debugs(5, 3, "commio_finish_callback: called for FD " << fd << " (" <<
139 code << ", " << xerrno << ")");
140 assert(ccb->active());
141 assert(ccb->fd == fd);
142 ccb->errcode = code;
143 ccb->xerrno = xerrno;
144
145 comm_io_callback_t cb = *ccb;
146
147 /* We've got a copy; blow away the real one */
148 /* XXX duplicate code from commio_cancel_callback! */
149 ccb->xerrno = 0;
150 ccb->callback = NULL; // cb has it
151
152 /* free data */
153 if (cb.freefunc) {
154 cb.freefunc(cb.buf);
155 cb.buf = NULL;
156 }
157
158 if (cb.callback != NULL) {
159 typedef CommIoCbParams Params;
160 Params &params = GetCommParams<Params>(cb.callback);
161 params.fd = cb.fd;
162 params.buf = cb.buf;
163 params.size = cb.offset;
164 params.flag = cb.errcode;
165 params.xerrno = cb.xerrno;
166 ScheduleCallHere(cb.callback);
167 }
168 }
169
170
171 /*
172 * Cancel the given callback
173 *
174 * Remember that the data is cbdataRef'ed.
175 */
176 // TODO: make this a comm_io_callback_t method
177 static void
178 commio_cancel_callback(int fd, comm_io_callback_t *ccb)
179 {
180 debugs(5, 3, "commio_cancel_callback: called for FD " << fd);
181 assert(ccb->fd == fd);
182 assert(ccb->active());
183
184 ccb->xerrno = 0;
185 ccb->callback = NULL;
186 }
187
188 /*
189 * Call the given comm callback; assumes the callback is valid.
190 *
191 * @param ccb io completion callback
192 */
193 void
194 commio_call_callback(comm_io_callback_t *ccb)
195 {
196 }
197
198 class ConnectStateData
199 {
200
201 public:
202 void *operator new (size_t);
203 void operator delete (void *);
204 static void Connect (int fd, void *me);
205 void connect();
206 void callCallback(comm_err_t status, int xerrno);
207 void defaults();
208
209 // defaults given by client
210 char *host;
211 u_short default_port;
212 IpAddress default_addr;
213 // NP: CANNOT store the default addr:port together as it gets set/reset differently.
214
215 DnsLookupDetails dns; ///< host lookup details
216 IpAddress S;
217 AsyncCall::Pointer callback;
218
219 int fd;
220 int tries;
221 int addrcount;
222 int connstart;
223
224 private:
225 int commResetFD();
226 int commRetryConnect();
227 CBDATA_CLASS(ConnectStateData);
228 };
229
230 /* STATIC */
231
232 static DescriptorSet *TheHalfClosed = NULL; /// the set of half-closed FDs
233 static bool WillCheckHalfClosed = false; /// true if check is scheduled
234 static EVH commHalfClosedCheck;
235 static void commPlanHalfClosedCheck();
236
237 static comm_err_t commBind(int s, struct addrinfo &);
238 static void commSetReuseAddr(int);
239 static void commSetNoLinger(int);
240 #ifdef TCP_NODELAY
241 static void commSetTcpNoDelay(int);
242 #endif
243 static void commSetTcpRcvbuf(int, int);
244 static PF commConnectFree;
245 static PF commHandleWrite;
246 static IPH commConnectDnsHandle;
247
248 typedef enum {
249 COMM_CB_READ = 1,
250 COMM_CB_DERIVED
251 } comm_callback_t;
252
253 static MemAllocator *conn_close_pool = NULL;
254 fd_debug_t *fdd_table = NULL;
255
256 bool
257 isOpen(const int fd)
258 {
259 return fd_table[fd].flags.open != 0;
260 }
261
262 /**
263 * Attempt a read
264 *
265 * If the read attempt succeeds or fails, call the callback.
266 * Else, wait for another IO notification.
267 */
268 void
269 commHandleRead(int fd, void *data)
270 {
271 comm_io_callback_t *ccb = (comm_io_callback_t *) data;
272
273 assert(data == COMMIO_FD_READCB(fd));
274 assert(commio_has_callback(fd, IOCB_READ, ccb));
275 /* Attempt a read */
276 statCounter.syscalls.sock.reads++;
277 errno = 0;
278 int retval;
279 retval = FD_READ_METHOD(fd, ccb->buf, ccb->size);
280 debugs(5, 3, "comm_read_try: FD " << fd << ", size " << ccb->size << ", retval " << retval << ", errno " << errno);
281
282 if (retval < 0 && !ignoreErrno(errno)) {
283 debugs(5, 3, "comm_read_try: scheduling COMM_ERROR");
284 ccb->offset = 0;
285 commio_finish_callback(fd, ccb, COMM_ERROR, errno);
286 return;
287 };
288
289 /* See if we read anything */
290 /* Note - read 0 == socket EOF, which is a valid read */
291 if (retval >= 0) {
292 fd_bytes(fd, retval, FD_READ);
293 ccb->offset = retval;
294 commio_finish_callback(fd, ccb, COMM_OK, errno);
295 return;
296 }
297
298 /* Nope, register for some more IO */
299 commSetSelect(fd, COMM_SELECT_READ, commHandleRead, data, 0);
300 }
301
302 /**
303 * Queue a read. handler/handler_data are called when the read
304 * completes, on error, or on file descriptor close.
305 */
306 void
307 comm_read(int fd, char *buf, int size, IOCB *handler, void *handler_data)
308 {
309 AsyncCall::Pointer call = commCbCall(5,4, "SomeCommReadHandler",
310 CommIoCbPtrFun(handler, handler_data));
311 comm_read(fd, buf, size, call);
312 }
313
314 void
315 comm_read(int fd, char *buf, int size, AsyncCall::Pointer &callback)
316 {
317 debugs(5, 5, "comm_read, queueing read for FD " << fd << "; asynCall " << callback);
318
319 /* Make sure we are open and not closing */
320 assert(isOpen(fd));
321 assert(!fd_table[fd].closing());
322 comm_io_callback_t *ccb = COMMIO_FD_READCB(fd);
323
324 // Make sure we are either not reading or just passively monitoring.
325 // Active/passive conflicts are OK and simply cancel passive monitoring.
326 if (ccb->active()) {
327 // if the assertion below fails, we have an active comm_read conflict
328 assert(fd_table[fd].halfClosedReader != NULL);
329 commStopHalfClosedMonitor(fd);
330 assert(!ccb->active());
331 }
332
333 /* Queue the read */
334 commio_set_callback(fd, IOCB_READ, ccb, callback, (char *)buf, NULL, size);
335 commSetSelect(fd, COMM_SELECT_READ, commHandleRead, ccb, 0);
336 }
337
338 /**
339 * Empty the read buffers
340 *
341 * This is a magical routine that empties the read buffers.
342 * Under some platforms (Linux) if a buffer has data in it before
343 * you call close(), the socket will hang and take quite a while
344 * to timeout.
345 */
346 static void
347 comm_empty_os_read_buffers(int fd)
348 {
349 #ifdef _SQUID_LINUX_
350 /* prevent those nasty RST packets */
351 char buf[SQUID_TCP_SO_RCVBUF];
352
353 if (fd_table[fd].flags.nonblocking == 1) {
354 while (FD_READ_METHOD(fd, buf, SQUID_TCP_SO_RCVBUF) > 0) {};
355 }
356 #endif
357 }
358
359
360 /**
361 * Return whether the FD has a pending completed callback.
362 */
363 int
364 comm_has_pending_read_callback(int fd)
365 {
366 assert(isOpen(fd));
367 // XXX: We do not know whether there is a read callback scheduled.
368 // This is used for pconn management that should probably be more
369 // tightly integrated into comm to minimize the chance that a
370 // closing pconn socket will be used for a new transaction.
371 return false;
372 }
373
374 // Does comm check this fd for read readiness?
375 // Note that when comm is not monitoring, there can be a pending callback
376 // call, which may resume comm monitoring once fired.
377 bool
378 comm_monitors_read(int fd)
379 {
380 assert(isOpen(fd));
381 // Being active is usually the same as monitoring because we always
382 // start monitoring the FD when we configure comm_io_callback_t for I/O
383 // and we usually configure comm_io_callback_t for I/O when we starting
384 // monitoring a FD for reading. TODO: replace with commio_has_callback
385 return COMMIO_FD_READCB(fd)->active();
386 }
387
388 /**
389 * Cancel a pending read. Assert that we have the right parameters,
390 * and that there are no pending read events!
391 *
392 * XXX: We do not assert that there are no pending read events and
393 * with async calls it becomes even more difficult.
394 * The whole interface should be reworked to do callback->cancel()
395 * instead of searching for places where the callback may be stored and
396 * updating the state of those places.
397 *
398 * AHC Don't call the comm handlers?
399 */
400 void
401 comm_read_cancel(int fd, IOCB *callback, void *data)
402 {
403 if (!isOpen(fd)) {
404 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " closed");
405 return;
406 }
407
408 comm_io_callback_t *cb = COMMIO_FD_READCB(fd);
409 // TODO: is "active" == "monitors FD"?
410 if (!cb->active()) {
411 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " inactive");
412 return;
413 }
414
415 typedef CommCbFunPtrCallT<CommIoCbPtrFun> Call;
416 Call *call = dynamic_cast<Call*>(cb->callback.getRaw());
417 if (!call) {
418 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " lacks callback");
419 return;
420 }
421
422 call->cancel("old comm_read_cancel");
423
424 typedef CommIoCbParams Params;
425 const Params &params = GetCommParams<Params>(cb->callback);
426
427 /* Ok, we can be reasonably sure we won't lose any data here! */
428 assert(call->dialer.handler == callback);
429 assert(params.data == data);
430
431 /* Delete the callback */
432 commio_cancel_callback(fd, cb);
433
434 /* And the IO event */
435 commSetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
436 }
437
438 void
439 comm_read_cancel(int fd, AsyncCall::Pointer &callback)
440 {
441 callback->cancel("comm_read_cancel");
442
443 if (!isOpen(fd)) {
444 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " closed");
445 return;
446 }
447
448 comm_io_callback_t *cb = COMMIO_FD_READCB(fd);
449
450 if (!cb->active()) {
451 debugs(5, 4, "comm_read_cancel fails: FD " << fd << " inactive");
452 return;
453 }
454
455 AsyncCall::Pointer call = cb->callback;
456 assert(call != NULL); // XXX: should never fail (active() checks for callback==NULL)
457
458 /* Ok, we can be reasonably sure we won't lose any data here! */
459 assert(call == callback);
460
461 /* Delete the callback */
462 commio_cancel_callback(fd, cb);
463
464 /* And the IO event */
465 commSetSelect(fd, COMM_SELECT_READ, NULL, NULL, 0);
466 }
467
468
469 /**
470 * synchronous wrapper around udp socket functions
471 */
472 int
473 comm_udp_recvfrom(int fd, void *buf, size_t len, int flags, IpAddress &from)
474 {
475 statCounter.syscalls.sock.recvfroms++;
476 int x = 0;
477 struct addrinfo *AI = NULL;
478
479 debugs(5,8, "comm_udp_recvfrom: FD " << fd << " from " << from);
480
481 assert( NULL == AI );
482
483 from.InitAddrInfo(AI);
484
485 x = recvfrom(fd, buf, len, flags, AI->ai_addr, &AI->ai_addrlen);
486
487 from = *AI;
488
489 from.FreeAddrInfo(AI);
490
491 return x;
492 }
493
494 int
495 comm_udp_recv(int fd, void *buf, size_t len, int flags)
496 {
497 IpAddress nul;
498 return comm_udp_recvfrom(fd, buf, len, flags, nul);
499 }
500
501 ssize_t
502 comm_udp_send(int s, const void *buf, size_t len, int flags)
503 {
504 return send(s, buf, len, flags);
505 }
506
507
508 bool
509 comm_has_incomplete_write(int fd)
510 {
511 assert(isOpen(fd));
512 return COMMIO_FD_WRITECB(fd)->active();
513 }
514
515 /**
516 * Queue a write. handler/handler_data are called when the write fully
517 * completes, on error, or on file descriptor close.
518 */
519
520 /* Return the local port associated with fd. */
521 u_short
522 comm_local_port(int fd)
523 {
524 IpAddress temp;
525 struct addrinfo *addr = NULL;
526 fde *F = &fd_table[fd];
527
528 /* If the fd is closed already, just return */
529
530 if (!F->flags.open) {
531 debugs(5, 0, "comm_local_port: FD " << fd << " has been closed.");
532 return 0;
533 }
534
535 if (F->local_addr.GetPort())
536 return F->local_addr.GetPort();
537
538 #if USE_IPV6
539 if (F->sock_family == AF_INET)
540 temp.SetIPv4();
541 #endif
542
543 temp.InitAddrInfo(addr);
544
545 if (getsockname(fd, addr->ai_addr, &(addr->ai_addrlen)) ) {
546 debugs(50, 1, "comm_local_port: Failed to retrieve TCP/UDP port number for socket: FD " << fd << ": " << xstrerror());
547 temp.FreeAddrInfo(addr);
548 return 0;
549 }
550 temp = *addr;
551
552 temp.FreeAddrInfo(addr);
553
554 F->local_addr.SetPort(temp.GetPort());
555
556 #if 0 // seems to undo comm_open actions on the FD ...
557 // grab default socket information for this address
558 temp.GetAddrInfo(addr);
559
560 F->sock_family = addr->ai_family;
561
562 temp.FreeAddrInfo(addr);
563 #endif
564
565 debugs(5, 6, "comm_local_port: FD " << fd << ": port " << F->local_addr.GetPort() << "(family=" << F->sock_family << ")");
566 return F->local_addr.GetPort();
567 }
568
569 static comm_err_t
570 commBind(int s, struct addrinfo &inaddr)
571 {
572 statCounter.syscalls.sock.binds++;
573
574 if (bind(s, inaddr.ai_addr, inaddr.ai_addrlen) == 0) {
575 debugs(50, 6, "commBind: bind socket FD " << s << " to " << fd_table[s].local_addr);
576 return COMM_OK;
577 }
578
579 debugs(50, 0, "commBind: Cannot bind socket FD " << s << " to " << fd_table[s].local_addr << ": " << xstrerror());
580
581 return COMM_ERROR;
582 }
583
584 /**
585 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
586 * is OR of flags specified in comm.h. Defaults TOS
587 */
588 int
589 comm_open(int sock_type,
590 int proto,
591 IpAddress &addr,
592 int flags,
593 const char *note)
594 {
595 return comm_openex(sock_type, proto, addr, flags, 0, note);
596 }
597
598 int
599 comm_open_listener(int sock_type,
600 int proto,
601 IpAddress &addr,
602 int flags,
603 const char *note)
604 {
605 int sock = -1;
606
607 /* all listener sockets require bind() */
608 flags |= COMM_DOBIND;
609
610 /* attempt native enabled port. */
611 sock = comm_openex(sock_type, proto, addr, flags, 0, note);
612
613 #if USE_IPV6
614 /* under IPv6 there is the possibility IPv6 is present but disabled. */
615 /* try again as IPv4-native */
616 if ( sock < 0 && addr.IsIPv6() && addr.SetIPv4() ) {
617 /* attempt to open this IPv4-only. */
618 sock = comm_openex(sock_type, proto, addr, flags, 0, note);
619 debugs(50, 2, HERE << "attempt open " << note << " socket on: " << addr);
620 }
621 #endif
622
623 return sock;
624 }
625
626 static bool
627 limitError(int const anErrno)
628 {
629 return anErrno == ENFILE || anErrno == EMFILE;
630 }
631
632 int
633 comm_set_tos(int fd, int tos)
634 {
635 #ifdef IP_TOS
636 int x = setsockopt(fd, IPPROTO_IP, IP_TOS, (char *) &tos, sizeof(int));
637 if (x < 0)
638 debugs(50, 1, "comm_set_tos: setsockopt(IP_TOS) on FD " << fd << ": " << xstrerror());
639 return x;
640 #else
641 debugs(50, 0, "WARNING: setsockopt(IP_TOS) not supported on this platform");
642 return -1;
643 #endif
644 }
645
646 void
647 comm_set_v6only(int fd, int tos)
648 {
649 #ifdef IPV6_V6ONLY
650 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &tos, sizeof(int)) < 0) {
651 debugs(50, 1, "comm_open: setsockopt(IPV6_V6ONLY) " << (tos?"ON":"OFF") << " for FD " << fd << ": " << xstrerror());
652 }
653 #else
654 debugs(50, 0, "WARNING: comm_open: setsockopt(IPV6_V6ONLY) not supported on this platform");
655 #endif /* sockopt */
656 }
657
658 /**
659 * Set the socket IP_TRANSPARENT option for Linux TPROXY v4 support.
660 */
661 void
662 comm_set_transparent(int fd)
663 {
664 #if defined(IP_TRANSPARENT)
665 int tos = 1;
666 if (setsockopt(fd, SOL_IP, IP_TRANSPARENT, (char *) &tos, sizeof(int)) < 0) {
667 debugs(50, DBG_IMPORTANT, "comm_open: setsockopt(IP_TRANSPARENT) on FD " << fd << ": " << xstrerror());
668 } else {
669 /* mark the socket as having transparent options */
670 fd_table[fd].flags.transparent = 1;
671 }
672 #else
673 debugs(50, DBG_CRITICAL, "WARNING: comm_open: setsockopt(IP_TRANSPARENT) not supported on this platform");
674 #endif /* sockopt */
675 }
676
677 /**
678 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
679 * is OR of flags specified in defines.h:COMM_*
680 */
681 int
682 comm_openex(int sock_type,
683 int proto,
684 IpAddress &addr,
685 int flags,
686 unsigned char TOS,
687 const char *note)
688 {
689 int new_socket;
690 fde *F = NULL;
691 int tos = 0;
692 struct addrinfo *AI = NULL;
693
694 PROF_start(comm_open);
695 /* Create socket for accepting new connections. */
696 statCounter.syscalls.sock.sockets++;
697
698 /* Setup the socket addrinfo details for use */
699 addr.GetAddrInfo(AI);
700 AI->ai_socktype = sock_type;
701 AI->ai_protocol = proto;
702
703 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr );
704
705 if ((new_socket = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol)) < 0) {
706 /* Increase the number of reserved fd's if calls to socket()
707 * are failing because the open file table is full. This
708 * limits the number of simultaneous clients */
709
710 if (limitError(errno)) {
711 debugs(50, DBG_IMPORTANT, "comm_open: socket failure: " << xstrerror());
712 fdAdjustReserved();
713 } else {
714 debugs(50, DBG_CRITICAL, "comm_open: socket failure: " << xstrerror());
715 }
716
717 addr.FreeAddrInfo(AI);
718
719 PROF_stop(comm_open);
720 return -1;
721 }
722
723 debugs(50, 3, "comm_openex: Opened socket FD " << new_socket << " : family=" << AI->ai_family << ", type=" << AI->ai_socktype << ", protocol=" << AI->ai_protocol );
724
725 /* set TOS if needed */
726 if (TOS && comm_set_tos(new_socket, TOS) ) {
727 tos = TOS;
728 }
729
730 #if IPV6_SPECIAL_SPLITSTACK
731
732 if ( addr.IsIPv6() )
733 comm_set_v6only(new_socket, 1);
734
735 #endif
736
737 #if IPV6_SPECIAL_V4MAPPED
738
739 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
740 /* Other OS may have this administratively disabled for general use. Same deal. */
741 if ( addr.IsIPv6() )
742 comm_set_v6only(new_socket, 0);
743
744 #endif
745
746 /* update fdstat */
747 debugs(5, 5, "comm_open: FD " << new_socket << " is a new socket");
748
749 assert(!isOpen(new_socket));
750 fd_open(new_socket, FD_SOCKET, note);
751
752 fdd_table[new_socket].close_file = NULL;
753
754 fdd_table[new_socket].close_line = 0;
755
756 F = &fd_table[new_socket];
757
758 F->local_addr = addr;
759
760 F->tos = TOS;
761
762 F->sock_family = AI->ai_family;
763
764 if (!(flags & COMM_NOCLOEXEC))
765 commSetCloseOnExec(new_socket);
766
767 if ((flags & COMM_REUSEADDR))
768 commSetReuseAddr(new_socket);
769
770 if (addr.GetPort() > (u_short) 0) {
771 #ifdef _SQUID_MSWIN_
772 if (sock_type != SOCK_DGRAM)
773 #endif
774 commSetNoLinger(new_socket);
775
776 if (opt_reuseaddr)
777 commSetReuseAddr(new_socket);
778 }
779
780 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
781 if ((flags & COMM_TRANSPARENT)) {
782 comm_set_transparent(new_socket);
783 }
784
785 if ( (flags & COMM_DOBIND) || addr.GetPort() > 0 || !addr.IsAnyAddr() ) {
786 if ( !(flags & COMM_DOBIND) && addr.IsAnyAddr() )
787 debugs(5,1,"WARNING: Squid is attempting to bind() port " << addr << " without being a listener.");
788 if ( addr.IsNoAddr() )
789 debugs(5,0,"CRITICAL: Squid is attempting to bind() port " << addr << "!!");
790
791 if (commBind(new_socket, *AI) != COMM_OK) {
792 comm_close(new_socket);
793 addr.FreeAddrInfo(AI);
794 return -1;
795 PROF_stop(comm_open);
796 }
797 }
798
799 addr.FreeAddrInfo(AI);
800
801 if (flags & COMM_NONBLOCKING)
802 if (commSetNonBlocking(new_socket) == COMM_ERROR) {
803 return -1;
804 PROF_stop(comm_open);
805 }
806
807 #ifdef TCP_NODELAY
808 if (sock_type == SOCK_STREAM)
809 commSetTcpNoDelay(new_socket);
810
811 #endif
812
813 if (Config.tcpRcvBufsz > 0 && sock_type == SOCK_STREAM)
814 commSetTcpRcvbuf(new_socket, Config.tcpRcvBufsz);
815
816 PROF_stop(comm_open);
817
818 return new_socket;
819 }
820
821 CBDATA_CLASS_INIT(ConnectStateData);
822
823 void *
824 ConnectStateData::operator new (size_t size)
825 {
826 CBDATA_INIT_TYPE(ConnectStateData);
827 return cbdataAlloc(ConnectStateData);
828 }
829
830 void
831 ConnectStateData::operator delete (void *address)
832 {
833 cbdataFree(address);
834 }
835
836
837
838 void
839 commConnectStart(int fd, const char *host, u_short port, AsyncCall::Pointer &cb)
840 {
841 debugs(cb->debugSection, cb->debugLevel, "commConnectStart: FD " << fd <<
842 ", cb " << cb << ", " << host << ":" << port); // TODO: just print *cb
843
844 ConnectStateData *cs;
845 cs = new ConnectStateData;
846 cs->fd = fd;
847 cs->host = xstrdup(host);
848 cs->default_port = port;
849 cs->callback = cb;
850
851 comm_add_close_handler(fd, commConnectFree, cs);
852 ipcache_nbgethostbyname(host, commConnectDnsHandle, cs);
853 }
854
855 // TODO: Remove this and similar callback registration functions by replacing
856 // (callback,data) parameters with an AsyncCall so that we do not have to use
857 // a generic call name and debug level when creating an AsyncCall. This will
858 // also cut the number of callback registration routines in half.
859 void
860 commConnectStart(int fd, const char *host, u_short port, CNCB * callback, void *data)
861 {
862 debugs(5, 5, "commConnectStart: FD " << fd << ", data " << data << ", " << host << ":" << port);
863 AsyncCall::Pointer call = commCbCall(5,3,
864 "SomeCommConnectHandler", CommConnectCbPtrFun(callback, data));
865 commConnectStart(fd, host, port, call);
866 }
867
868 static void
869 commConnectDnsHandle(const ipcache_addrs *ia, const DnsLookupDetails &details, void *data)
870 {
871 ConnectStateData *cs = (ConnectStateData *)data;
872 cs->dns = details;
873
874 if (ia == NULL) {
875 debugs(5, 3, "commConnectDnsHandle: Unknown host: " << cs->host);
876 cs->callCallback(COMM_ERR_DNS, 0);
877 return;
878 }
879
880 assert(ia->cur < ia->count);
881
882 cs->default_addr = ia->in_addrs[ia->cur];
883
884 if (Config.onoff.balance_on_multiple_ip)
885 ipcacheCycleAddr(cs->host, NULL);
886
887 cs->addrcount = ia->count;
888
889 cs->connstart = squid_curtime;
890
891 cs->connect();
892 }
893
894 void
895 ConnectStateData::callCallback(comm_err_t status, int xerrno)
896 {
897 debugs(5, 3, "commConnectCallback: FD " << fd);
898
899 comm_remove_close_handler(fd, commConnectFree, this);
900 commSetTimeout(fd, -1, NULL, NULL);
901
902 typedef CommConnectCbParams Params;
903 Params &params = GetCommParams<Params>(callback);
904 params.fd = fd;
905 params.dns = dns;
906 params.flag = status;
907 params.xerrno = xerrno;
908 ScheduleCallHere(callback);
909 callback = NULL;
910
911 commConnectFree(fd, this);
912 }
913
914 static void
915 commConnectFree(int fd, void *data)
916 {
917 ConnectStateData *cs = (ConnectStateData *)data;
918 debugs(5, 3, "commConnectFree: FD " << fd);
919 // delete cs->callback;
920 cs->callback = NULL;
921 safe_free(cs->host);
922 delete cs;
923 }
924
925 static void
926 copyFDFlags(int to, fde *F)
927 {
928 if (F->flags.close_on_exec)
929 commSetCloseOnExec(to);
930
931 if (F->flags.nonblocking)
932 commSetNonBlocking(to);
933
934 #ifdef TCP_NODELAY
935
936 if (F->flags.nodelay)
937 commSetTcpNoDelay(to);
938
939 #endif
940
941 if (Config.tcpRcvBufsz > 0)
942 commSetTcpRcvbuf(to, Config.tcpRcvBufsz);
943 }
944
945 /* Reset FD so that we can connect() again */
946 int
947 ConnectStateData::commResetFD()
948 {
949 struct addrinfo *AI = NULL;
950 IpAddress nul;
951 int new_family = AF_UNSPEC;
952
953 // XXX: do we have to check this?
954 //
955 // if (!cbdataReferenceValid(callback.data))
956 // return 0;
957
958 statCounter.syscalls.sock.sockets++;
959
960 /* setup a bare-bones addrinfo */
961 /* TODO INET6: for WinXP we may need to check the local_addr type and setup the family properly. */
962 nul.GetAddrInfo(AI);
963 new_family = AI->ai_family;
964
965 int fd2 = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
966
967 nul.FreeAddrInfo(AI);
968
969 if (fd2 < 0) {
970 debugs(5, DBG_CRITICAL, HERE << "WARNING: FD " << fd2 << " socket failed to allocate: " << xstrerror());
971
972 if (ENFILE == errno || EMFILE == errno)
973 fdAdjustReserved();
974
975 return 0;
976 }
977
978 #ifdef _SQUID_MSWIN_
979
980 /* On Windows dup2() can't work correctly on Sockets, the */
981 /* workaround is to close the destination Socket before call them. */
982 close(fd);
983
984 #endif
985
986 if (dup2(fd2, fd) < 0) {
987 debugs(5, DBG_CRITICAL, HERE << "WARNING: dup2(FD " << fd2 << ", FD " << fd << ") failed: " << xstrerror());
988
989 if (ENFILE == errno || EMFILE == errno)
990 fdAdjustReserved();
991
992 close(fd2);
993
994 return 0;
995 }
996 commResetSelect(fd);
997
998 close(fd2);
999 fde *F = &fd_table[fd];
1000
1001 debugs(50, 3, "commResetFD: Reset socket FD " << fd << "->" << fd2 << " : family=" << new_family );
1002
1003 /* INET6: copy the new sockets family type to the FDE table */
1004 fd_table[fd].sock_family = new_family;
1005
1006 fd_table[fd].flags.called_connect = 0;
1007 /*
1008 * yuck, this has assumptions about comm_open() arguments for
1009 * the original socket
1010 */
1011
1012 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
1013 if ( F->flags.transparent ) {
1014 comm_set_transparent(fd);
1015 }
1016
1017 AI = NULL;
1018 F->local_addr.GetAddrInfo(AI);
1019
1020 if (commBind(fd, *AI) != COMM_OK) {
1021 debugs(5, DBG_CRITICAL, "WARNING: Reset of FD " << fd << " for " << F->local_addr << " failed to bind: " << xstrerror());
1022 F->local_addr.FreeAddrInfo(AI);
1023 return 0;
1024 }
1025 F->local_addr.FreeAddrInfo(AI);
1026
1027 if (F->tos)
1028 comm_set_tos(fd, F->tos);
1029
1030 #if IPV6_SPECIAL_SPLITSTACK
1031 if ( F->local_addr.IsIPv6() )
1032 comm_set_v6only(fd, 1);
1033 #endif
1034
1035 copyFDFlags(fd, F);
1036
1037 return 1;
1038 }
1039
1040 int
1041 ConnectStateData::commRetryConnect()
1042 {
1043 assert(addrcount > 0);
1044
1045 if (addrcount == 1) {
1046 if (tries >= Config.retry.maxtries)
1047 return 0;
1048
1049 if (squid_curtime - connstart > Config.Timeout.connect)
1050 return 0;
1051 } else {
1052 if (tries > addrcount)
1053 return 0;
1054 }
1055
1056 return commResetFD();
1057 }
1058
1059 static void
1060 commReconnect(void *data)
1061 {
1062 ConnectStateData *cs = (ConnectStateData *)data;
1063 ipcache_nbgethostbyname(cs->host, commConnectDnsHandle, cs);
1064 }
1065
1066 /** Connect SOCK to specified DEST_PORT at DEST_HOST. */
1067 void
1068 ConnectStateData::Connect(int fd, void *me)
1069 {
1070 ConnectStateData *cs = (ConnectStateData *)me;
1071 assert (cs->fd == fd);
1072 cs->connect();
1073 }
1074
1075 void
1076 ConnectStateData::defaults()
1077 {
1078 S = default_addr;
1079 S.SetPort(default_port);
1080 }
1081
1082 void
1083 ConnectStateData::connect()
1084 {
1085 if (S.IsAnyAddr())
1086 defaults();
1087
1088 debugs(5,5, HERE << "to " << S);
1089
1090 switch (comm_connect_addr(fd, S) ) {
1091
1092 case COMM_INPROGRESS:
1093 debugs(5, 5, HERE << "FD " << fd << ": COMM_INPROGRESS");
1094 commSetSelect(fd, COMM_SELECT_WRITE, ConnectStateData::Connect, this, 0);
1095 break;
1096
1097 case COMM_OK:
1098 debugs(5, 5, HERE << "FD " << fd << ": COMM_OK - connected");
1099 ipcacheMarkGoodAddr(host, S);
1100 callCallback(COMM_OK, 0);
1101 break;
1102
1103 #if USE_IPV6
1104 case COMM_ERR_PROTOCOL:
1105 /* problem using the desired protocol over this socket.
1106 * count the connection attempt, reset the socket, and immediately try again */
1107 tries++;
1108 commResetFD();
1109 connect();
1110 break;
1111 #endif
1112
1113 default:
1114 debugs(5, 5, HERE "FD " << fd << ": * - try again");
1115 tries++;
1116 ipcacheMarkBadAddr(host, S);
1117
1118 #if USE_ICMP
1119 if (Config.onoff.test_reachability)
1120 netdbDeleteAddrNetwork(S);
1121 #endif
1122
1123 if (commRetryConnect()) {
1124 eventAdd("commReconnect", commReconnect, this, this->addrcount == 1 ? 0.05 : 0.0, 0);
1125 } else {
1126 debugs(5, 5, HERE << "FD " << fd << ": * - ERR tried too many times already.");
1127 callCallback(COMM_ERR_CONNECT, errno);
1128 }
1129 }
1130 }
1131 /*
1132 int
1133 commSetTimeout_old(int fd, int timeout, PF * handler, void *data)
1134 {
1135 debugs(5, 3, HERE << "FD " << fd << " timeout " << timeout);
1136 assert(fd >= 0);
1137 assert(fd < Squid_MaxFD);
1138 fde *F = &fd_table[fd];
1139 assert(F->flags.open);
1140
1141 if (timeout < 0) {
1142 cbdataReferenceDone(F->timeout_data);
1143 F->timeout_handler = NULL;
1144 F->timeout = 0;
1145 } else {
1146 if (handler) {
1147 cbdataReferenceDone(F->timeout_data);
1148 F->timeout_handler = handler;
1149 F->timeout_data = cbdataReference(data);
1150 }
1151
1152 F->timeout = squid_curtime + (time_t) timeout;
1153 }
1154
1155 return F->timeout;
1156 }
1157 */
1158
1159 int
1160 commSetTimeout(int fd, int timeout, PF * handler, void *data)
1161 {
1162 AsyncCall::Pointer call;
1163 debugs(5, 3, HERE << "FD " << fd << " timeout " << timeout);
1164 if (handler != NULL)
1165 call=commCbCall(5,4, "SomeTimeoutHandler", CommTimeoutCbPtrFun(handler, data));
1166 else
1167 call = NULL;
1168 return commSetTimeout(fd, timeout, call);
1169 }
1170
1171
1172 int commSetTimeout(int fd, int timeout, AsyncCall::Pointer &callback)
1173 {
1174 debugs(5, 3, HERE << "FD " << fd << " timeout " << timeout);
1175 assert(fd >= 0);
1176 assert(fd < Squid_MaxFD);
1177 fde *F = &fd_table[fd];
1178 assert(F->flags.open);
1179
1180 if (timeout < 0) {
1181 F->timeoutHandler = NULL;
1182 F->timeout = 0;
1183 } else {
1184 if (callback != NULL) {
1185 typedef CommTimeoutCbParams Params;
1186 Params &params = GetCommParams<Params>(callback);
1187 params.fd = fd;
1188 F->timeoutHandler = callback;
1189 }
1190
1191 F->timeout = squid_curtime + (time_t) timeout;
1192 }
1193
1194 return F->timeout;
1195
1196 }
1197
1198 int
1199 comm_connect_addr(int sock, const IpAddress &address)
1200 {
1201 comm_err_t status = COMM_OK;
1202 fde *F = &fd_table[sock];
1203 int x = 0;
1204 int err = 0;
1205 socklen_t errlen;
1206 struct addrinfo *AI = NULL;
1207 PROF_start(comm_connect_addr);
1208
1209 assert(address.GetPort() != 0);
1210
1211 debugs(5, 9, "comm_connect_addr: connecting socket " << sock << " to " << address << " (want family: " << F->sock_family << ")");
1212
1213 /* BUG 2222 FIX: reset the FD when its found to be IPv4 in IPv6 mode */
1214 /* inverse case of IPv4 failing to connect on IPv6 socket is handeld post-connect.
1215 * this case must presently be handled here since the GetAddrInfo asserts on bad mappings.
1216 * eventually we want it to throw a Must() that gets handled there instead of this if.
1217 * NP: because commresetFD is private to ConnStateData we have to return an error and
1218 * trust its handled properly.
1219 */
1220 #if USE_IPV6
1221 if (F->sock_family == AF_INET && !address.IsIPv4()) {
1222 return COMM_ERR_PROTOCOL;
1223 }
1224 #endif
1225
1226 address.GetAddrInfo(AI, F->sock_family);
1227
1228 /* Establish connection. */
1229 errno = 0;
1230
1231 if (!F->flags.called_connect) {
1232 F->flags.called_connect = 1;
1233 statCounter.syscalls.sock.connects++;
1234
1235 x = connect(sock, AI->ai_addr, AI->ai_addrlen);
1236
1237 // XXX: ICAP code refuses callbacks during a pending comm_ call
1238 // Async calls development will fix this.
1239 if (x == 0) {
1240 x = -1;
1241 errno = EINPROGRESS;
1242 }
1243
1244 if (x < 0) {
1245 debugs(5,5, "comm_connect_addr: sock=" << sock << ", addrinfo( " <<
1246 " flags=" << AI->ai_flags <<
1247 ", family=" << AI->ai_family <<
1248 ", socktype=" << AI->ai_socktype <<
1249 ", protocol=" << AI->ai_protocol <<
1250 ", &addr=" << AI->ai_addr <<
1251 ", addrlen=" << AI->ai_addrlen <<
1252 " )" );
1253 debugs(5, 9, "connect FD " << sock << ": (" << x << ") " << xstrerror());
1254 debugs(14,9, "connecting to: " << address );
1255 }
1256 } else {
1257 #if defined(_SQUID_NEWSOS6_)
1258 /* Makoto MATSUSHITA <matusita@ics.es.osaka-u.ac.jp> */
1259
1260 connect(sock, AI->ai_addr, AI->ai_addrlen);
1261
1262 if (errno == EINVAL) {
1263 errlen = sizeof(err);
1264 x = getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &errlen);
1265
1266 if (x >= 0)
1267 errno = x;
1268 }
1269
1270 #else
1271 errlen = sizeof(err);
1272
1273 x = getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &errlen);
1274
1275 if (x == 0)
1276 errno = err;
1277
1278 #if defined(_SQUID_SOLARIS_)
1279 /*
1280 * Solaris 2.4's socket emulation doesn't allow you
1281 * to determine the error from a failed non-blocking
1282 * connect and just returns EPIPE. Create a fake
1283 * error message for connect. -- fenner@parc.xerox.com
1284 */
1285 if (x < 0 && errno == EPIPE)
1286 errno = ENOTCONN;
1287
1288 #endif
1289 #endif
1290
1291 }
1292
1293 /* Squid seems to be working fine without this code. With this code,
1294 * we leak memory on many connect requests because of EINPROGRESS.
1295 * If you find that this code is needed, please file a bug report. */
1296 #if 0
1297 #ifdef _SQUID_LINUX_
1298 /* 2007-11-27:
1299 * Linux Debian replaces our allocated AI pointer with garbage when
1300 * connect() fails. This leads to segmentation faults deallocating
1301 * the system-allocated memory when we go to clean up our pointer.
1302 * HACK: is to leak the memory returned since we can't deallocate.
1303 */
1304 if (errno != 0) {
1305 AI = NULL;
1306 }
1307 #endif
1308 #endif
1309
1310 address.FreeAddrInfo(AI);
1311
1312 PROF_stop(comm_connect_addr);
1313
1314 if (errno == 0 || errno == EISCONN)
1315 status = COMM_OK;
1316 else if (ignoreErrno(errno))
1317 status = COMM_INPROGRESS;
1318 else
1319 #if USE_IPV6
1320 if ( F->sock_family == AF_INET6 && address.IsIPv4() ) {
1321
1322 /* failover to trying IPv4-only link if an IPv6 one fails */
1323 /* to catch the edge case of apps listening on IPv4-localhost */
1324 F->sock_family = AF_INET;
1325 int res = comm_connect_addr(sock, address);
1326
1327 /* if that fails too, undo our temporary socktype hack so the repeat works properly. */
1328 if (res == COMM_ERROR)
1329 F->sock_family = AF_INET6;
1330
1331 return res;
1332 } else
1333 #endif
1334 return COMM_ERROR;
1335
1336 address.NtoA(F->ipaddr, MAX_IPSTRLEN);
1337
1338 F->remote_port = address.GetPort(); /* remote_port is HS */
1339
1340 if (status == COMM_OK) {
1341 debugs(5, 10, "comm_connect_addr: FD " << sock << " connected to " << address);
1342 } else if (status == COMM_INPROGRESS) {
1343 debugs(5, 10, "comm_connect_addr: FD " << sock << " connection pending");
1344 }
1345
1346 return status;
1347 }
1348
1349 void
1350 commCallCloseHandlers(int fd)
1351 {
1352 fde *F = &fd_table[fd];
1353 debugs(5, 5, "commCallCloseHandlers: FD " << fd);
1354
1355 while (F->closeHandler != NULL) {
1356 AsyncCall::Pointer call = F->closeHandler;
1357 F->closeHandler = call->Next();
1358 call->setNext(NULL);
1359 // If call is not canceled schedule it for execution else ignore it
1360 if (!call->canceled()) {
1361 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call);
1362 typedef CommCloseCbParams Params;
1363 Params &params = GetCommParams<Params>(call);
1364 params.fd = fd;
1365 ScheduleCallHere(call);
1366 }
1367 }
1368 }
1369
1370 #if LINGERING_CLOSE
1371 static void
1372 commLingerClose(int fd, void *unused)
1373 {
1374 LOCAL_ARRAY(char, buf, 1024);
1375 int n;
1376 n = FD_READ_METHOD(fd, buf, 1024);
1377
1378 if (n < 0)
1379 debugs(5, 3, "commLingerClose: FD " << fd << " read: " << xstrerror());
1380
1381 comm_close(fd);
1382 }
1383
1384 static void
1385 commLingerTimeout(int fd, void *unused)
1386 {
1387 debugs(5, 3, "commLingerTimeout: FD " << fd);
1388 comm_close(fd);
1389 }
1390
1391 /*
1392 * Inspired by apache
1393 */
1394 void
1395 comm_lingering_close(int fd)
1396 {
1397 #if USE_SSL
1398
1399 if (fd_table[fd].ssl)
1400 ssl_shutdown_method(fd);
1401
1402 #endif
1403
1404 if (shutdown(fd, 1) < 0) {
1405 comm_close(fd);
1406 return;
1407 }
1408
1409 fd_note(fd, "lingering close");
1410 commSetTimeout(fd, 10, commLingerTimeout, NULL);
1411 commSetSelect(fd, COMM_SELECT_READ, commLingerClose, NULL, 0);
1412 }
1413
1414 #endif
1415
1416 /*
1417 * enable linger with time of 0 so that when the socket is
1418 * closed, TCP generates a RESET
1419 */
1420 void
1421 comm_reset_close(int fd)
1422 {
1423
1424 struct linger L;
1425 L.l_onoff = 1;
1426 L.l_linger = 0;
1427
1428 if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &L, sizeof(L)) < 0)
1429 debugs(50, DBG_CRITICAL, "ERROR: Closing FD " << fd << " with TCP RST: " << xstrerror());
1430
1431 comm_close(fd);
1432 }
1433
1434 void
1435 comm_close_start(int fd, void *data)
1436 {
1437 #if USE_SSL
1438 fde *F = &fd_table[fd];
1439 if (F->ssl)
1440 ssl_shutdown_method(fd);
1441
1442 #endif
1443
1444 }
1445
1446 void
1447 comm_close_complete(int fd, void *data)
1448 {
1449 #if USE_SSL
1450 fde *F = &fd_table[fd];
1451
1452 if (F->ssl) {
1453 SSL_free(F->ssl);
1454 F->ssl = NULL;
1455 }
1456
1457 #endif
1458 fd_close(fd); /* update fdstat */
1459
1460 close(fd);
1461
1462 statCounter.syscalls.sock.closes++;
1463
1464 /* When an fd closes, give accept() a chance, if need be */
1465 Comm::AcceptLimiter::Instance().kick();
1466 }
1467
1468 /*
1469 * Close the socket fd.
1470 *
1471 * + call write handlers with ERR_CLOSING
1472 * + call read handlers with ERR_CLOSING
1473 * + call closing handlers
1474 *
1475 * NOTE: COMM_ERR_CLOSING will NOT be called for CommReads' sitting in a
1476 * DeferredReadManager.
1477 */
1478 void
1479 _comm_close(int fd, char const *file, int line)
1480 {
1481 debugs(5, 3, "comm_close: start closing FD " << fd);
1482 assert(fd >= 0);
1483 assert(fd < Squid_MaxFD);
1484
1485 fde *F = &fd_table[fd];
1486 fdd_table[fd].close_file = file;
1487 fdd_table[fd].close_line = line;
1488
1489 if (F->closing())
1490 return;
1491
1492 /* XXX: is this obsolete behind F->closing() ? */
1493 if ( (shutting_down || reconfiguring) && (!F->flags.open || F->type == FD_FILE))
1494 return;
1495
1496 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
1497 assert(isOpen(fd));
1498
1499 assert(F->type != FD_FILE);
1500
1501 PROF_start(comm_close);
1502
1503 F->flags.close_request = 1;
1504
1505 AsyncCall::Pointer startCall=commCbCall(5,4, "comm_close_start",
1506 CommCloseCbPtrFun(comm_close_start, NULL));
1507 typedef CommCloseCbParams Params;
1508 Params &startParams = GetCommParams<Params>(startCall);
1509 startParams.fd = fd;
1510 ScheduleCallHere(startCall);
1511
1512 // a half-closed fd may lack a reader, so we stop monitoring explicitly
1513 if (commHasHalfClosedMonitor(fd))
1514 commStopHalfClosedMonitor(fd);
1515 commSetTimeout(fd, -1, NULL, NULL);
1516
1517 // notify read/write handlers
1518 if (commio_has_callback(fd, IOCB_WRITE, COMMIO_FD_WRITECB(fd))) {
1519 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), COMM_ERR_CLOSING, errno);
1520 }
1521 if (commio_has_callback(fd, IOCB_READ, COMMIO_FD_READCB(fd))) {
1522 commio_finish_callback(fd, COMMIO_FD_READCB(fd), COMM_ERR_CLOSING, errno);
1523 }
1524
1525 commCallCloseHandlers(fd);
1526
1527 if (F->pconn.uses)
1528 F->pconn.pool->count(F->pconn.uses);
1529
1530 comm_empty_os_read_buffers(fd);
1531
1532
1533 AsyncCall::Pointer completeCall=commCbCall(5,4, "comm_close_complete",
1534 CommCloseCbPtrFun(comm_close_complete, NULL));
1535 Params &completeParams = GetCommParams<Params>(completeCall);
1536 completeParams.fd = fd;
1537 // must use async call to wait for all callbacks
1538 // scheduled before comm_close() to finish
1539 ScheduleCallHere(completeCall);
1540
1541 PROF_stop(comm_close);
1542 }
1543
1544 /* Send a udp datagram to specified TO_ADDR. */
1545 int
1546 comm_udp_sendto(int fd,
1547 const IpAddress &to_addr,
1548 const void *buf,
1549 int len)
1550 {
1551 int x = 0;
1552 struct addrinfo *AI = NULL;
1553
1554 PROF_start(comm_udp_sendto);
1555 statCounter.syscalls.sock.sendtos++;
1556
1557 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr <<
1558 " using FD " << fd << " using Port " << comm_local_port(fd) );
1559
1560 /* BUG: something in the above macro appears to occasionally be setting AI to garbage. */
1561 /* AYJ: 2007-08-27 : or was it because I wasn't then setting 'fd_table[fd].sock_family' to fill properly. */
1562 assert( NULL == AI );
1563
1564 to_addr.GetAddrInfo(AI, fd_table[fd].sock_family);
1565
1566 x = sendto(fd, buf, len, 0, AI->ai_addr, AI->ai_addrlen);
1567
1568 to_addr.FreeAddrInfo(AI);
1569
1570 PROF_stop(comm_udp_sendto);
1571
1572 if (x >= 0)
1573 return x;
1574
1575 #ifdef _SQUID_LINUX_
1576
1577 if (ECONNREFUSED != errno)
1578 #endif
1579
1580 debugs(50, 1, "comm_udp_sendto: FD " << fd << ", (family=" << fd_table[fd].sock_family << ") " << to_addr << ": " << xstrerror());
1581
1582 return COMM_ERROR;
1583 }
1584
1585 void
1586 comm_add_close_handler(int fd, PF * handler, void *data)
1587 {
1588 debugs(5, 5, "comm_add_close_handler: FD " << fd << ", handler=" <<
1589 handler << ", data=" << data);
1590
1591 AsyncCall::Pointer call=commCbCall(5,4, "SomeCloseHandler",
1592 CommCloseCbPtrFun(handler, data));
1593 comm_add_close_handler(fd, call);
1594 }
1595
1596 void
1597 comm_add_close_handler(int fd, AsyncCall::Pointer &call)
1598 {
1599 debugs(5, 5, "comm_add_close_handler: FD " << fd << ", AsyncCall=" << call);
1600
1601 /*TODO:Check for a similar scheduled AsyncCall*/
1602 // for (c = fd_table[fd].closeHandler; c; c = c->next)
1603 // assert(c->handler != handler || c->data != data);
1604
1605 call->setNext(fd_table[fd].closeHandler);
1606
1607 fd_table[fd].closeHandler = call;
1608 }
1609
1610
1611 // remove function-based close handler
1612 void
1613 comm_remove_close_handler(int fd, PF * handler, void *data)
1614 {
1615 assert (isOpen(fd));
1616 /* Find handler in list */
1617 debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", handler=" <<
1618 handler << ", data=" << data);
1619
1620 AsyncCall::Pointer p;
1621 for (p = fd_table[fd].closeHandler; p != NULL; p = p->Next()) {
1622 typedef CommCbFunPtrCallT<CommCloseCbPtrFun> Call;
1623 const Call *call = dynamic_cast<const Call*>(p.getRaw());
1624 if (!call) // method callbacks have their own comm_remove_close_handler
1625 continue;
1626
1627 typedef CommCloseCbParams Params;
1628 const Params &params = GetCommParams<Params>(p);
1629 if (call->dialer.handler == handler && params.data == data)
1630 break; /* This is our handler */
1631 }
1632
1633 // comm_close removes all close handlers so our handler may be gone
1634 if (p != NULL)
1635 p->cancel("comm_remove_close_handler");
1636 // TODO: should we remove the handler from the close handlers list?
1637 }
1638
1639 // remove method-based close handler
1640 void
1641 comm_remove_close_handler(int fd, AsyncCall::Pointer &call)
1642 {
1643 assert (isOpen(fd));
1644 debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", AsyncCall=" << call);
1645
1646 // comm_close removes all close handlers so our handler may be gone
1647 // TODO: should we remove the handler from the close handlers list?
1648 #if 0
1649 // Check to see if really exist the given AsyncCall in comm_close handlers
1650 // TODO: optimize: this slow code is only needed for the assert() below
1651 AsyncCall::Pointer p;
1652 for (p = fd_table[fd].closeHandler; p != NULL && p != call; p = p->Next());
1653 assert(p == call);
1654 #endif
1655
1656 call->cancel("comm_remove_close_handler");
1657 }
1658
1659 static void
1660 commSetNoLinger(int fd)
1661 {
1662
1663 struct linger L;
1664 L.l_onoff = 0; /* off */
1665 L.l_linger = 0;
1666
1667 if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &L, sizeof(L)) < 0)
1668 debugs(50, 0, "commSetNoLinger: FD " << fd << ": " << xstrerror());
1669
1670 fd_table[fd].flags.nolinger = 1;
1671 }
1672
1673 static void
1674 commSetReuseAddr(int fd)
1675 {
1676 int on = 1;
1677
1678 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)) < 0)
1679 debugs(50, 1, "commSetReuseAddr: FD " << fd << ": " << xstrerror());
1680 }
1681
1682 static void
1683 commSetTcpRcvbuf(int fd, int size)
1684 {
1685 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &size, sizeof(size)) < 0)
1686 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd << ", SIZE " << size << ": " << xstrerror());
1687 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &size, sizeof(size)) < 0)
1688 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd << ", SIZE " << size << ": " << xstrerror());
1689 #ifdef TCP_WINDOW_CLAMP
1690 if (setsockopt(fd, SOL_TCP, TCP_WINDOW_CLAMP, (char *) &size, sizeof(size)) < 0)
1691 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd << ", SIZE " << size << ": " << xstrerror());
1692 #endif
1693 }
1694
1695 int
1696 commSetNonBlocking(int fd)
1697 {
1698 #ifndef _SQUID_MSWIN_
1699 int flags;
1700 int dummy = 0;
1701 #endif
1702 #ifdef _SQUID_WIN32_
1703
1704 int nonblocking = TRUE;
1705
1706 #ifdef _SQUID_CYGWIN_
1707
1708 if (fd_table[fd].type != FD_PIPE) {
1709 #endif
1710
1711 if (ioctl(fd, FIONBIO, &nonblocking) < 0) {
1712 debugs(50, 0, "commSetNonBlocking: FD " << fd << ": " << xstrerror() << " " << fd_table[fd].type);
1713 return COMM_ERROR;
1714 }
1715
1716 #ifdef _SQUID_CYGWIN_
1717
1718 } else {
1719 #endif
1720 #endif
1721 #ifndef _SQUID_MSWIN_
1722
1723 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
1724 debugs(50, 0, "FD " << fd << ": fcntl F_GETFL: " << xstrerror());
1725 return COMM_ERROR;
1726 }
1727
1728 if (fcntl(fd, F_SETFL, flags | SQUID_NONBLOCK) < 0) {
1729 debugs(50, 0, "commSetNonBlocking: FD " << fd << ": " << xstrerror());
1730 return COMM_ERROR;
1731 }
1732
1733 #endif
1734 #ifdef _SQUID_CYGWIN_
1735
1736 }
1737
1738 #endif
1739 fd_table[fd].flags.nonblocking = 1;
1740
1741 return 0;
1742 }
1743
1744 int
1745 commUnsetNonBlocking(int fd)
1746 {
1747 #ifdef _SQUID_MSWIN_
1748 int nonblocking = FALSE;
1749
1750 if (ioctlsocket(fd, FIONBIO, (unsigned long *) &nonblocking) < 0) {
1751 #else
1752 int flags;
1753 int dummy = 0;
1754
1755 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
1756 debugs(50, 0, "FD " << fd << ": fcntl F_GETFL: " << xstrerror());
1757 return COMM_ERROR;
1758 }
1759
1760 if (fcntl(fd, F_SETFL, flags & (~SQUID_NONBLOCK)) < 0) {
1761 #endif
1762 debugs(50, 0, "commUnsetNonBlocking: FD " << fd << ": " << xstrerror());
1763 return COMM_ERROR;
1764 }
1765
1766 fd_table[fd].flags.nonblocking = 0;
1767 return 0;
1768 }
1769
1770 void
1771 commSetCloseOnExec(int fd)
1772 {
1773 #ifdef FD_CLOEXEC
1774 int flags;
1775 int dummy = 0;
1776
1777 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
1778 debugs(50, 0, "FD " << fd << ": fcntl F_GETFL: " << xstrerror());
1779 return;
1780 }
1781
1782 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
1783 debugs(50, 0, "FD " << fd << ": set close-on-exec failed: " << xstrerror());
1784
1785 fd_table[fd].flags.close_on_exec = 1;
1786
1787 #endif
1788 }
1789
1790 #ifdef TCP_NODELAY
1791 static void
1792 commSetTcpNoDelay(int fd)
1793 {
1794 int on = 1;
1795
1796 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) < 0)
1797 debugs(50, 1, "commSetTcpNoDelay: FD " << fd << ": " << xstrerror());
1798
1799 fd_table[fd].flags.nodelay = 1;
1800 }
1801
1802 #endif
1803
1804 void
1805 commSetTcpKeepalive(int fd, int idle, int interval, int timeout)
1806 {
1807 int on = 1;
1808 #ifdef TCP_KEEPCNT
1809 if (timeout && interval) {
1810 int count = (timeout + interval - 1) / interval;
1811 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(on)) < 0)
1812 debugs(5, 1, "commSetKeepalive: FD " << fd << ": " << xstrerror());
1813 }
1814 #endif
1815 #ifdef TCP_KEEPIDLE
1816 if (idle) {
1817 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(on)) < 0)
1818 debugs(5, 1, "commSetKeepalive: FD " << fd << ": " << xstrerror());
1819 }
1820 #endif
1821 #ifdef TCP_KEEPINTVL
1822 if (interval) {
1823 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(on)) < 0)
1824 debugs(5, 1, "commSetKeepalive: FD " << fd << ": " << xstrerror());
1825 }
1826 #endif
1827 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) < 0)
1828 debugs(5, 1, "commSetKeepalive: FD " << fd << ": " << xstrerror());
1829 }
1830
1831 void
1832 comm_init(void)
1833 {
1834 fd_table =(fde *) xcalloc(Squid_MaxFD, sizeof(fde));
1835 fdd_table = (fd_debug_t *)xcalloc(Squid_MaxFD, sizeof(fd_debug_t));
1836
1837 /* make sure the accept() socket FIFO delay queue exists */
1838 Comm::AcceptLimiter::Instance();
1839
1840 commfd_table = (comm_fd_t *) xcalloc(Squid_MaxFD, sizeof(comm_fd_t));
1841 for (int pos = 0; pos < Squid_MaxFD; pos++) {
1842 commfd_table[pos].fd = pos;
1843 commfd_table[pos].readcb.fd = pos;
1844 commfd_table[pos].readcb.type = IOCB_READ;
1845 commfd_table[pos].writecb.fd = pos;
1846 commfd_table[pos].writecb.type = IOCB_WRITE;
1847 }
1848
1849 /* XXX account fd_table */
1850 /* Keep a few file descriptors free so that we don't run out of FD's
1851 * after accepting a client but before it opens a socket or a file.
1852 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
1853 RESERVED_FD = min(100, Squid_MaxFD / 4);
1854
1855 conn_close_pool = memPoolCreate("close_handler", sizeof(close_handler));
1856
1857 TheHalfClosed = new DescriptorSet;
1858 }
1859
1860 void
1861 comm_exit(void)
1862 {
1863 delete TheHalfClosed;
1864 TheHalfClosed = NULL;
1865
1866 safe_free(fd_table);
1867 safe_free(fdd_table);
1868 safe_free(commfd_table);
1869 }
1870
1871 /* Write to FD. */
1872 static void
1873 commHandleWrite(int fd, void *data)
1874 {
1875 comm_io_callback_t *state = (comm_io_callback_t *)data;
1876 int len = 0;
1877 int nleft;
1878
1879 assert(state == COMMIO_FD_WRITECB(fd));
1880
1881 PROF_start(commHandleWrite);
1882 debugs(5, 5, "commHandleWrite: FD " << fd << ": off " <<
1883 (long int) state->offset << ", sz " << (long int) state->size << ".");
1884
1885 nleft = state->size - state->offset;
1886 len = FD_WRITE_METHOD(fd, state->buf + state->offset, nleft);
1887 debugs(5, 5, "commHandleWrite: write() returns " << len);
1888 fd_bytes(fd, len, FD_WRITE);
1889 statCounter.syscalls.sock.writes++;
1890 // After each successful partial write,
1891 // reset fde::writeStart to the current time.
1892 fd_table[fd].writeStart = squid_curtime;
1893
1894 if (len == 0) {
1895 /* Note we even call write if nleft == 0 */
1896 /* We're done */
1897
1898 if (nleft != 0)
1899 debugs(5, 1, "commHandleWrite: FD " << fd << ": write failure: connection closed with " << nleft << " bytes remaining.");
1900
1901 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), nleft ? COMM_ERROR : COMM_OK, errno);
1902 } else if (len < 0) {
1903 /* An error */
1904
1905 if (fd_table[fd].flags.socket_eof) {
1906 debugs(50, 2, "commHandleWrite: FD " << fd << ": write failure: " << xstrerror() << ".");
1907 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), nleft ? COMM_ERROR : COMM_OK, errno);
1908 } else if (ignoreErrno(errno)) {
1909 debugs(50, 10, "commHandleWrite: FD " << fd << ": write failure: " << xstrerror() << ".");
1910 commSetSelect(fd,
1911 COMM_SELECT_WRITE,
1912 commHandleWrite,
1913 state,
1914 0);
1915 } else {
1916 debugs(50, 2, "commHandleWrite: FD " << fd << ": write failure: " << xstrerror() << ".");
1917 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), nleft ? COMM_ERROR : COMM_OK, errno);
1918 }
1919 } else {
1920 /* A successful write, continue */
1921 state->offset += len;
1922
1923 if (state->offset < state->size) {
1924 /* Not done, reinstall the write handler and write some more */
1925 commSetSelect(fd,
1926 COMM_SELECT_WRITE,
1927 commHandleWrite,
1928 state,
1929 0);
1930 } else {
1931 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), nleft ? COMM_OK : COMM_ERROR, errno);
1932 }
1933 }
1934
1935 PROF_stop(commHandleWrite);
1936 }
1937
1938 /*
1939 * Queue a write. handler/handler_data are called when the write
1940 * completes, on error, or on file descriptor close.
1941 *
1942 * free_func is used to free the passed buffer when the write has completed.
1943 */
1944 void
1945 comm_write(int fd, const char *buf, int size, IOCB * handler, void *handler_data, FREE * free_func)
1946 {
1947 AsyncCall::Pointer call = commCbCall(5,5, "SomeCommWriteHander",
1948 CommIoCbPtrFun(handler, handler_data));
1949
1950 comm_write(fd, buf, size, call, free_func);
1951 }
1952
1953 void
1954 comm_write(int fd, const char *buf, int size, AsyncCall::Pointer &callback, FREE * free_func)
1955 {
1956 debugs(5, 5, "comm_write: FD " << fd << ": sz " << size << ": asynCall " << callback);
1957
1958 /* Make sure we are open, not closing, and not writing */
1959 assert(isOpen(fd));
1960 assert(!fd_table[fd].closing());
1961 comm_io_callback_t *ccb = COMMIO_FD_WRITECB(fd);
1962 assert(!ccb->active());
1963
1964 fd_table[fd].writeStart = squid_curtime;
1965 /* Queue the write */
1966 commio_set_callback(fd, IOCB_WRITE, ccb, callback,
1967 (char *)buf, free_func, size);
1968 commSetSelect(fd, COMM_SELECT_WRITE, commHandleWrite, ccb, 0);
1969 }
1970
1971
1972 /* a wrapper around comm_write to allow for MemBuf to be comm_written in a snap */
1973 void
1974 comm_write_mbuf(int fd, MemBuf *mb, IOCB * handler, void *handler_data)
1975 {
1976 comm_write(fd, mb->buf, mb->size, handler, handler_data, mb->freeFunc());
1977 }
1978
1979 void
1980 comm_write_mbuf(int fd, MemBuf *mb, AsyncCall::Pointer &callback)
1981 {
1982 comm_write(fd, mb->buf, mb->size, callback, mb->freeFunc());
1983 }
1984
1985
1986 /*
1987 * hm, this might be too general-purpose for all the places we'd
1988 * like to use it.
1989 */
1990 int
1991 ignoreErrno(int ierrno)
1992 {
1993 switch (ierrno) {
1994
1995 case EINPROGRESS:
1996
1997 case EWOULDBLOCK:
1998 #if EAGAIN != EWOULDBLOCK
1999
2000 case EAGAIN:
2001 #endif
2002
2003 case EALREADY:
2004
2005 case EINTR:
2006 #ifdef ERESTART
2007
2008 case ERESTART:
2009 #endif
2010
2011 return 1;
2012
2013 default:
2014 return 0;
2015 }
2016
2017 /* NOTREACHED */
2018 }
2019
2020 void
2021 commCloseAllSockets(void)
2022 {
2023 int fd;
2024 fde *F = NULL;
2025
2026 for (fd = 0; fd <= Biggest_FD; fd++) {
2027 F = &fd_table[fd];
2028
2029 if (!F->flags.open)
2030 continue;
2031
2032 if (F->type != FD_SOCKET)
2033 continue;
2034
2035 if (F->flags.ipc) /* don't close inter-process sockets */
2036 continue;
2037
2038 if (F->timeoutHandler != NULL) {
2039 AsyncCall::Pointer callback = F->timeoutHandler;
2040 F->timeoutHandler = NULL;
2041 debugs(5, 5, "commCloseAllSockets: FD " << fd << ": Calling timeout handler");
2042 ScheduleCallHere(callback);
2043 } else {
2044 debugs(5, 5, "commCloseAllSockets: FD " << fd << ": calling comm_reset_close()");
2045 comm_reset_close(fd);
2046 }
2047 }
2048 }
2049
2050 static bool
2051 AlreadyTimedOut(fde *F)
2052 {
2053 if (!F->flags.open)
2054 return true;
2055
2056 if (F->timeout == 0)
2057 return true;
2058
2059 if (F->timeout > squid_curtime)
2060 return true;
2061
2062 return false;
2063 }
2064
2065 static bool
2066 writeTimedOut(int fd)
2067 {
2068 if (!commio_has_callback(fd, IOCB_WRITE, COMMIO_FD_WRITECB(fd)))
2069 return false;
2070
2071 if ((squid_curtime - fd_table[fd].writeStart) < Config.Timeout.write)
2072 return false;
2073
2074 return true;
2075 }
2076
2077 void
2078 checkTimeouts(void)
2079 {
2080 int fd;
2081 fde *F = NULL;
2082 AsyncCall::Pointer callback;
2083
2084 for (fd = 0; fd <= Biggest_FD; fd++) {
2085 F = &fd_table[fd];
2086
2087 if (writeTimedOut(fd)) {
2088 // We have an active write callback and we are timed out
2089 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), COMM_ERROR, ETIMEDOUT);
2090 } else if (AlreadyTimedOut(F))
2091 continue;
2092
2093 debugs(5, 5, "checkTimeouts: FD " << fd << " Expired");
2094
2095 if (F->timeoutHandler != NULL) {
2096 debugs(5, 5, "checkTimeouts: FD " << fd << ": Call timeout handler");
2097 callback = F->timeoutHandler;
2098 F->timeoutHandler = NULL;
2099 ScheduleCallHere(callback);
2100 } else {
2101 debugs(5, 5, "checkTimeouts: FD " << fd << ": Forcing comm_close()");
2102 comm_close(fd);
2103 }
2104 }
2105 }
2106
2107 void CommIO::Initialise()
2108 {
2109 /* Initialize done pipe signal */
2110 int DonePipe[2];
2111 if (pipe(DonePipe)) {}
2112 DoneFD = DonePipe[1];
2113 DoneReadFD = DonePipe[0];
2114 fd_open(DoneReadFD, FD_PIPE, "async-io completetion event: main");
2115 fd_open(DoneFD, FD_PIPE, "async-io completetion event: threads");
2116 commSetNonBlocking(DoneReadFD);
2117 commSetNonBlocking(DoneFD);
2118 commSetSelect(DoneReadFD, COMM_SELECT_READ, NULLFDHandler, NULL, 0);
2119 Initialised = true;
2120 }
2121
2122 void CommIO::NotifyIOClose()
2123 {
2124 /* Close done pipe signal */
2125 FlushPipe();
2126 close(DoneFD);
2127 close(DoneReadFD);
2128 fd_close(DoneFD);
2129 fd_close(DoneReadFD);
2130 Initialised = false;
2131 }
2132
2133 bool CommIO::Initialised = false;
2134 bool CommIO::DoneSignalled = false;
2135 int CommIO::DoneFD = -1;
2136 int CommIO::DoneReadFD = -1;
2137
2138 void
2139 CommIO::FlushPipe()
2140 {
2141 char buf[256];
2142 FD_READ_METHOD(DoneReadFD, buf, sizeof(buf));
2143 }
2144
2145 void
2146 CommIO::NULLFDHandler(int fd, void *data)
2147 {
2148 FlushPipe();
2149 commSetSelect(fd, COMM_SELECT_READ, NULLFDHandler, NULL, 0);
2150 }
2151
2152 void
2153 CommIO::ResetNotifications()
2154 {
2155 if (DoneSignalled) {
2156 FlushPipe();
2157 DoneSignalled = false;
2158 }
2159 }
2160
2161 /// Start waiting for a possibly half-closed connection to close
2162 // by scheduling a read callback to a monitoring handler that
2163 // will close the connection on read errors.
2164 void
2165 commStartHalfClosedMonitor(int fd)
2166 {
2167 debugs(5, 5, HERE << "adding FD " << fd << " to " << *TheHalfClosed);
2168 assert(isOpen(fd));
2169 assert(!commHasHalfClosedMonitor(fd));
2170 (void)TheHalfClosed->add(fd); // could also assert the result
2171 commPlanHalfClosedCheck(); // may schedule check if we added the first FD
2172 }
2173
2174 static
2175 void
2176 commPlanHalfClosedCheck()
2177 {
2178 if (!WillCheckHalfClosed && !TheHalfClosed->empty()) {
2179 eventAdd("commHalfClosedCheck", &commHalfClosedCheck, NULL, 1.0, 1);
2180 WillCheckHalfClosed = true;
2181 }
2182 }
2183
2184 /// iterates over all descriptors that may need half-closed tests and
2185 /// calls comm_read for those that do; re-schedules the check if needed
2186 static
2187 void
2188 commHalfClosedCheck(void *)
2189 {
2190 debugs(5, 5, HERE << "checking " << *TheHalfClosed);
2191
2192 typedef DescriptorSet::const_iterator DSCI;
2193 const DSCI end = TheHalfClosed->end();
2194 for (DSCI i = TheHalfClosed->begin(); i != end; ++i) {
2195 const int fd = *i;
2196 if (!fd_table[fd].halfClosedReader) { // not reading already
2197 AsyncCall::Pointer call = commCbCall(5,4, "commHalfClosedReader",
2198 CommIoCbPtrFun(&commHalfClosedReader, NULL));
2199 comm_read(fd, NULL, 0, call);
2200 fd_table[fd].halfClosedReader = call;
2201 }
2202 }
2203
2204 WillCheckHalfClosed = false; // as far as we know
2205 commPlanHalfClosedCheck(); // may need to check again
2206 }
2207
2208 /// checks whether we are waiting for possibly half-closed connection to close
2209 // We are monitoring if the read handler for the fd is the monitoring handler.
2210 bool
2211 commHasHalfClosedMonitor(int fd)
2212 {
2213 return TheHalfClosed->has(fd);
2214 }
2215
2216 /// stop waiting for possibly half-closed connection to close
2217 static void
2218 commStopHalfClosedMonitor(int const fd)
2219 {
2220 debugs(5, 5, HERE << "removing FD " << fd << " from " << *TheHalfClosed);
2221
2222 // cancel the read if one was scheduled
2223 AsyncCall::Pointer reader = fd_table[fd].halfClosedReader;
2224 if (reader != NULL)
2225 comm_read_cancel(fd, reader);
2226 fd_table[fd].halfClosedReader = NULL;
2227
2228 TheHalfClosed->del(fd);
2229 }
2230
2231 /// I/O handler for the possibly half-closed connection monitoring code
2232 static void
2233 commHalfClosedReader(int fd, char *, size_t size, comm_err_t flag, int, void *)
2234 {
2235 // there cannot be more data coming in on half-closed connections
2236 assert(size == 0);
2237 assert(commHasHalfClosedMonitor(fd)); // or we would have canceled the read
2238
2239 fd_table[fd].halfClosedReader = NULL; // done reading, for now
2240
2241 // nothing to do if fd is being closed
2242 if (flag == COMM_ERR_CLOSING)
2243 return;
2244
2245 // if read failed, close the connection
2246 if (flag != COMM_OK) {
2247 debugs(5, 3, "commHalfClosedReader: closing FD " << fd);
2248 comm_close(fd);
2249 return;
2250 }
2251
2252 // continue waiting for close or error
2253 commPlanHalfClosedCheck(); // make sure this fd will be checked again
2254 }
2255
2256
2257 CommRead::CommRead() : fd(-1), buf(NULL), len(0), callback(NULL) {}
2258
2259 CommRead::CommRead(int fd_, char *buf_, int len_, AsyncCall::Pointer &callback_)
2260 : fd(fd_), buf(buf_), len(len_), callback(callback_) {}
2261
2262 DeferredRead::DeferredRead () : theReader(NULL), theContext(NULL), theRead(), cancelled(false) {}
2263
2264 DeferredRead::DeferredRead (DeferrableRead *aReader, void *data, CommRead const &aRead) : theReader(aReader), theContext (data), theRead(aRead), cancelled(false) {}
2265
2266 DeferredReadManager::~DeferredReadManager()
2267 {
2268 flushReads();
2269 assert (deferredReads.empty());
2270 }
2271
2272 /* explicit instantiation required for some systems */
2273
2274 /// \cond AUTODOCS-IGNORE
2275 template cbdata_type CbDataList<DeferredRead>::CBDATA_CbDataList;
2276 /// \endcond
2277
2278 void
2279 DeferredReadManager::delayRead(DeferredRead const &aRead)
2280 {
2281 debugs(5, 3, "Adding deferred read on FD " << aRead.theRead.fd);
2282 CbDataList<DeferredRead> *temp = deferredReads.push_back(aRead);
2283
2284 // We have to use a global function as a closer and point to temp
2285 // instead of "this" because DeferredReadManager is not a job and
2286 // is not even cbdata protected
2287 AsyncCall::Pointer closer = commCbCall(5,4,
2288 "DeferredReadManager::CloseHandler",
2289 CommCloseCbPtrFun(&CloseHandler, temp));
2290 comm_add_close_handler(aRead.theRead.fd, closer);
2291 temp->element.closer = closer; // remeber so that we can cancel
2292 }
2293
2294 void
2295 DeferredReadManager::CloseHandler(int fd, void *thecbdata)
2296 {
2297 if (!cbdataReferenceValid (thecbdata))
2298 return;
2299
2300 CbDataList<DeferredRead> *temp = (CbDataList<DeferredRead> *)thecbdata;
2301
2302 temp->element.closer = NULL;
2303 temp->element.markCancelled();
2304 }
2305
2306 DeferredRead
2307 DeferredReadManager::popHead(CbDataListContainer<DeferredRead> &deferredReads)
2308 {
2309 assert (!deferredReads.empty());
2310
2311 DeferredRead &read = deferredReads.head->element;
2312 if (!read.cancelled) {
2313 comm_remove_close_handler(read.theRead.fd, read.closer);
2314 read.closer = NULL;
2315 }
2316
2317 DeferredRead result = deferredReads.pop_front();
2318
2319 return result;
2320 }
2321
2322 void
2323 DeferredReadManager::kickReads(int const count)
2324 {
2325 /* if we had CbDataList::size() we could consolidate this and flushReads */
2326
2327 if (count < 1) {
2328 flushReads();
2329 return;
2330 }
2331
2332 size_t remaining = count;
2333
2334 while (!deferredReads.empty() && remaining) {
2335 DeferredRead aRead = popHead(deferredReads);
2336 kickARead(aRead);
2337
2338 if (!aRead.cancelled)
2339 --remaining;
2340 }
2341 }
2342
2343 void
2344 DeferredReadManager::flushReads()
2345 {
2346 CbDataListContainer<DeferredRead> reads;
2347 reads = deferredReads;
2348 deferredReads = CbDataListContainer<DeferredRead>();
2349
2350 // XXX: For fairness this SHOULD randomize the order
2351 while (!reads.empty()) {
2352 DeferredRead aRead = popHead(reads);
2353 kickARead(aRead);
2354 }
2355 }
2356
2357 void
2358 DeferredReadManager::kickARead(DeferredRead const &aRead)
2359 {
2360 if (aRead.cancelled)
2361 return;
2362
2363 if (aRead.theRead.fd>=0 && fd_table[aRead.theRead.fd].closing())
2364 return;
2365
2366 debugs(5, 3, "Kicking deferred read on FD " << aRead.theRead.fd);
2367
2368 aRead.theReader(aRead.theContext, aRead.theRead);
2369 }
2370
2371 void
2372 DeferredRead::markCancelled()
2373 {
2374 cancelled = true;
2375 }
2376
2377 ConnectionDetail::ConnectionDetail() : me(), peer()
2378 {
2379 }
2380
2381 int
2382 CommSelectEngine::checkEvents(int timeout)
2383 {
2384 static time_t last_timeout = 0;
2385
2386 /* No, this shouldn't be here. But it shouldn't be in each comm handler. -adrian */
2387 if (squid_curtime > last_timeout) {
2388 last_timeout = squid_curtime;
2389 checkTimeouts();
2390 }
2391
2392 switch (comm_select(timeout)) {
2393
2394 case COMM_OK:
2395
2396 case COMM_TIMEOUT:
2397 return 0;
2398
2399 case COMM_IDLE:
2400
2401 case COMM_SHUTDOWN:
2402 return EVENT_IDLE;
2403
2404 case COMM_ERROR:
2405 return EVENT_ERROR;
2406
2407 default:
2408 fatal_dump("comm.cc: Internal error -- this should never happen.");
2409 return EVENT_ERROR;
2410 };
2411 }