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