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