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