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