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