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