]> git.ipfire.org Git - thirdparty/squid.git/blame - src/comm.cc
Compile errors with --enable-linux-tproxy4 set
[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
f1e0717c
AJ
631void
632comm_set_transparent(int fd, int tos)
633{
634#if LINUX_TPROXY4
ef88b51d
AJ
635 if (setsockopt(fd, SOL_IP, IP_TRANSPARENT, (char *) &tos, sizeof(int)) < 0) {
636 debugs(50, DBG_IMPORTANT, "comm_open: setsockopt(IP_TRANSPARENT) on FD " << fd << ": " << xstrerror());
f1e0717c 637 }
3949d8b7
AJ
638 else {
639 /* mark the socket as having transparent options */
640 fd_table[fd].flags.transparent = 1;
641 }
f1e0717c 642#else
ef88b51d 643 debugs(50, DBG_CRITICAL, "WARNING: comm_open: setsockopt(IP_TRANSPARENT) not supported on this platform");
f1e0717c
AJ
644#endif /* sockopt */
645}
646
e1a88700 647/**
648 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
649 * is OR of flags specified in defines.h:COMM_*
650 */
d6827718 651int
652comm_openex(int sock_type,
62e76326 653 int proto,
cc192b50 654 IPAddress &addr,
62e76326 655 int flags,
656 unsigned char TOS,
657 const char *note)
090089c4 658{
659 int new_socket;
76f87348 660 fde *F = NULL;
cc192b50 661 int tos = 0;
662 struct addrinfo *AI = NULL;
090089c4 663
88bfe092 664 PROF_start(comm_open);
090089c4 665 /* Create socket for accepting new connections. */
83704487 666 statCounter.syscalls.sock.sockets++;
62e76326 667
cc192b50 668 /* Setup the socket addrinfo details for use */
669 addr.GetAddrInfo(AI);
670 AI->ai_socktype = sock_type;
671 AI->ai_protocol = proto;
672 AI->ai_flags = flags;
673
674 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr );
675
676 if ((new_socket = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol)) < 0)
62e76326 677 {
678 /* Increase the number of reserved fd's if calls to socket()
679 * are failing because the open file table is full. This
680 * limits the number of simultaneous clients */
681
2d8c0b1a 682 if (limitError(errno)) {
bf8fe701 683 debugs(50, 1, "comm_open: socket failure: " << xstrerror());
62e76326 684 fdAdjustReserved();
2d8c0b1a 685 } else {
bf8fe701 686 debugs(50, 0, "comm_open: socket failure: " << xstrerror());
62e76326 687 }
688
cc192b50 689 addr.FreeAddrInfo(AI);
690
62e76326 691 PROF_stop(comm_open);
692 return -1;
090089c4 693 }
62e76326 694
cc192b50 695 debugs(50, 3, "comm_openex: Opened socket FD " << new_socket << " : family=" << AI->ai_family << ", type=" << AI->ai_socktype << ", protocol=" << AI->ai_protocol );
696
d6827718 697 /* set TOS if needed */
cc192b50 698 if (TOS && comm_set_tos(new_socket, TOS) ) {
62e76326 699 tos = TOS;
cc192b50 700 }
62e76326 701
cc192b50 702#if IPV6_SPECIAL_SPLITSTACK
62e76326 703
cc192b50 704 if( addr.IsIPv6() )
705 comm_set_v6only(new_socket, tos);
62e76326 706
d6827718 707#endif
62e76326 708
cc192b50 709#if IPV6_SPECIAL_V4MAPPED && defined(_SQUID_MSWIN_)
710
711 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
712 if( addr.IsIPv6() )
713 comm_set_v6only(new_socket, 0);
714
715#endif
62e76326 716
090089c4 717 /* update fdstat */
bf8fe701 718 debugs(5, 5, "comm_open: FD " << new_socket << " is a new socket");
62e76326 719
b0469965 720 assert(!isOpen(new_socket));
5c5783a2 721 fd_open(new_socket, FD_SOCKET, note);
62e76326 722
c4b7a5a9 723 fdd_table[new_socket].close_file = NULL;
62e76326 724
c4b7a5a9 725 fdd_table[new_socket].close_line = 0;
62e76326 726
76f87348 727 F = &fd_table[new_socket];
62e76326 728
d6827718 729 F->local_addr = addr;
62e76326 730
cc192b50 731 F->tos = TOS;
732
733 F->sock_family = AI->ai_family;
62e76326 734
79a15e0a 735 if (!(flags & COMM_NOCLOEXEC))
62e76326 736 commSetCloseOnExec(new_socket);
737
cdc33f35 738 if ((flags & COMM_REUSEADDR))
62e76326 739 commSetReuseAddr(new_socket);
740
cc192b50 741 if (addr.GetPort() > (u_short) 0)
62e76326 742 {
a50bfe93 743#ifdef _SQUID_MSWIN_
744
745 if (sock_type != SOCK_DGRAM)
746#endif
747
748 commSetNoLinger(new_socket);
62e76326 749
750 if (opt_reuseaddr)
751 commSetReuseAddr(new_socket);
090089c4 752 }
62e76326 753
cc192b50 754 if (!addr.IsNoAddr())
62e76326 755 {
cc192b50 756 if (commBind(new_socket, *AI) != COMM_OK) {
62e76326 757 comm_close(new_socket);
cc192b50 758 addr.FreeAddrInfo(AI);
62e76326 759 return -1;
760 PROF_stop(comm_open);
761 }
23ff6968 762 }
62e76326 763
cc192b50 764 addr.FreeAddrInfo(AI);
090089c4 765
79a15e0a 766 if (flags & COMM_NONBLOCKING)
62e76326 767 if (commSetNonBlocking(new_socket) == COMM_ERROR)
768 {
769 return -1;
770 PROF_stop(comm_open);
771 }
772
30a4f2a8 773#ifdef TCP_NODELAY
774 if (sock_type == SOCK_STREAM)
62e76326 775 commSetTcpNoDelay(new_socket);
776
30a4f2a8 777#endif
62e76326 778
1241e63e 779 if (Config.tcpRcvBufsz > 0 && sock_type == SOCK_STREAM)
62e76326 780 commSetTcpRcvbuf(new_socket, Config.tcpRcvBufsz);
781
88bfe092 782 PROF_stop(comm_open);
62e76326 783
090089c4 784 return new_socket;
785}
786
d2d59a68 787CBDATA_CLASS_INIT(ConnectStateData);
788
789void *
790ConnectStateData::operator new (size_t size)
791{
792 CBDATA_INIT_TYPE(ConnectStateData);
793 return cbdataAlloc(ConnectStateData);
794}
795
796void
797ConnectStateData::operator delete (void *address)
798{
799 cbdataFree(address);
800}
801
b0469965 802
803
e5f6c5c2 804void
b0469965 805commConnectStart(int fd, const char *host, u_short port, AsyncCall::Pointer &cb)
e924600d 806{
b0469965 807 debugs(cb->debugSection, cb->debugLevel, "commConnectStart: FD " << fd <<
808 ", cb " << cb << ", " << host << ":" << port); // TODO: just print *cb
809
28c60158 810 ConnectStateData *cs;
d2d59a68 811 cs = new ConnectStateData;
03a1ee42 812 cs->fd = fd;
e924600d 813 cs->host = xstrdup(host);
cc192b50 814 cs->default_port = port;
b0469965 815 cs->callback = cb;
816
e924600d 817 comm_add_close_handler(fd, commConnectFree, cs);
8407afee 818 ipcache_nbgethostbyname(host, commConnectDnsHandle, cs);
edeb28fd 819}
820
b0469965 821// TODO: Remove this and similar callback registration functions by replacing
822// (callback,data) parameters with an AsyncCall so that we do not have to use
823// a generic call name and debug level when creating an AsyncCall. This will
824// also cut the number of callback registration routines in half.
825void
826commConnectStart(int fd, const char *host, u_short port, CNCB * callback, void *data)
827{
828 debugs(5, 5, "commConnectStart: FD " << fd << ", data " << data << ", " << host << ":" << port);
829 AsyncCall::Pointer call = commCbCall(5,3,
830 "SomeCommConnectHandler", CommConnectCbPtrFun(callback, data));
831 commConnectStart(fd, host, port, call);
832}
833
edeb28fd 834static void
03a1ee42 835commConnectDnsHandle(const ipcache_addrs * ia, void *data)
edeb28fd 836{
e6ccf245 837 ConnectStateData *cs = (ConnectStateData *)data;
62e76326 838
edeb28fd 839 if (ia == NULL) {
bf8fe701 840 debugs(5, 3, "commConnectDnsHandle: Unknown host: " << cs->host);
62e76326 841
842 if (!dns_error_message) {
843 dns_error_message = "Unknown DNS error";
bf8fe701 844 debugs(5, 1, "commConnectDnsHandle: Bad dns_error_message");
62e76326 845 }
846
847 assert(dns_error_message != NULL);
2d8c0b1a 848 cs->callCallback(COMM_ERR_DNS, 0);
62e76326 849 return;
edeb28fd 850 }
62e76326 851
f076b37b 852 assert(ia->cur < ia->count);
cc192b50 853
854 cs->default_addr = ia->in_addrs[ia->cur];
a12a049a 855
856 if (Config.onoff.balance_on_multiple_ip)
857 ipcacheCycleAddr(cs->host, NULL);
858
22c653cd 859 cs->addrcount = ia->count;
a12a049a 860
22c653cd 861 cs->connstart = squid_curtime;
a12a049a 862
2d8c0b1a 863 cs->connect();
e924600d 864}
865
2d8c0b1a 866void
867ConnectStateData::callCallback(comm_err_t status, int xerrno)
868{
b0469965 869 debugs(5, 3, "commConnectCallback: FD " << fd);
bf8fe701 870
2d8c0b1a 871 comm_remove_close_handler(fd, commConnectFree, this);
e1b16349 872 commSetTimeout(fd, -1, NULL, NULL);
62e76326 873
b0469965 874 typedef CommConnectCbParams Params;
875 Params &params = GetCommParams<Params>(callback);
876 params.fd = fd;
877 params.flag = status;
878 params.xerrno = xerrno;
879 ScheduleCallHere(callback);
880 callback = NULL;
62e76326 881
744c68f5 882 commConnectFree(fd, this);
f88211e8 883}
884
e924600d 885static void
9daca08e 886commConnectFree(int fd, void *data)
e924600d 887{
e6ccf245 888 ConnectStateData *cs = (ConnectStateData *)data;
bf8fe701 889 debugs(5, 3, "commConnectFree: FD " << fd);
b0469965 890// delete cs->callback;
891 cs->callback = NULL;
8407afee 892 safe_free(cs->host);
00d77d6b 893 delete cs;
e924600d 894}
895
2d8c0b1a 896static void
897copyFDFlags(int to, fde *F)
898{
899 if (F->flags.close_on_exec)
900 commSetCloseOnExec(to);
901
902 if (F->flags.nonblocking)
903 commSetNonBlocking(to);
904
905#ifdef TCP_NODELAY
906
907 if (F->flags.nodelay)
908 commSetTcpNoDelay(to);
909
910#endif
911
912 if (Config.tcpRcvBufsz > 0)
913 commSetTcpRcvbuf(to, Config.tcpRcvBufsz);
914}
915
22c653cd 916/* Reset FD so that we can connect() again */
0b77ecd8 917int
918ConnectStateData::commResetFD()
edeb28fd 919{
cc192b50 920 struct addrinfo *AI = NULL;
921 IPAddress nul;
922
b0469965 923// XXX: do we have to check this?
924//
925// if (!cbdataReferenceValid(callback.data))
926// return 0;
62e76326 927
83704487 928 statCounter.syscalls.sock.sockets++;
62e76326 929
cc192b50 930 /* setup a bare-bones addrinfo */
931 nul.GetAddrInfo(AI);
932
933 int fd2 = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
934
935 nul.FreeAddrInfo(AI);
62e76326 936
edeb28fd 937 if (fd2 < 0) {
bf8fe701 938 debugs(5, 0, "commResetFD: socket: " << xstrerror());
62e76326 939
940 if (ENFILE == errno || EMFILE == errno)
941 fdAdjustReserved();
942
943 return 0;
edeb28fd 944 }
62e76326 945
68aa4272 946#ifdef _SQUID_MSWIN_
947
948 /* On Windows dup2() can't work correctly on Sockets, the */
949 /* workaround is to close the destination Socket before call them. */
0b77ecd8 950 close(fd);
68aa4272 951
952#endif
953
0b77ecd8 954 if (dup2(fd2, fd) < 0) {
bf8fe701 955 debugs(5, 0, "commResetFD: dup2: " << xstrerror());
62e76326 956
957 if (ENFILE == errno || EMFILE == errno)
958 fdAdjustReserved();
959
960 close(fd2);
961
962 return 0;
edeb28fd 963 }
3a5a4930 964 commResetSelect(fd);
62e76326 965
edeb28fd 966 close(fd2);
0b77ecd8 967 fde *F = &fd_table[fd];
968 fd_table[fd].flags.called_connect = 0;
09544acc 969 /*
970 * yuck, this has assumptions about comm_open() arguments for
971 * the original socket
972 */
62e76326 973
cc192b50 974 AI = NULL;
975 F->local_addr.GetAddrInfo(AI);
976
977 if (commBind(fd, *AI) != COMM_OK) {
bf8fe701 978 debugs(5, 0, "commResetFD: bind: " << xstrerror());
cc192b50 979 F->local_addr.FreeAddrInfo(AI);
62e76326 980 return 0;
09544acc 981 }
cc192b50 982 F->local_addr.FreeAddrInfo(AI);
62e76326 983
cc192b50 984 if (F->tos)
985 comm_set_tos(fd, F->tos);
986
987#if IPV6_SPECIAL_SPLITSTACK
988
989 if( F->local_addr.IsIPv6() )
990 comm_set_v6only(fd, F->tos);
62e76326 991
d6827718 992#endif
cc192b50 993
0b77ecd8 994 copyFDFlags (fd, F);
62e76326 995
edeb28fd 996 return 1;
997}
998
0b77ecd8 999int
1000ConnectStateData::commRetryConnect()
22c653cd 1001{
0b77ecd8 1002 assert(addrcount > 0);
62e76326 1003
0b77ecd8 1004 if (addrcount == 1) {
1005 if (tries >= Config.retry.maxtries)
62e76326 1006 return 0;
1007
0b77ecd8 1008 if (squid_curtime - connstart > Config.Timeout.connect)
62e76326 1009 return 0;
22c653cd 1010 } else {
0b77ecd8 1011 if (tries > addrcount)
62e76326 1012 return 0;
22c653cd 1013 }
62e76326 1014
0b77ecd8 1015 return commResetFD();
22c653cd 1016}
1017
4ed0e075 1018static void
1019commReconnect(void *data)
1020{
1021 ConnectStateData *cs = (ConnectStateData *)data;
1022 ipcache_nbgethostbyname(cs->host, commConnectDnsHandle, cs);
1023}
1024
e924600d 1025/* Connect SOCK to specified DEST_PORT at DEST_HOST. */
2d8c0b1a 1026void
1027ConnectStateData::Connect (int fd, void *me)
090089c4 1028{
2d8c0b1a 1029 ConnectStateData *cs = (ConnectStateData *)me;
1030 assert (cs->fd == fd);
1031 cs->connect();
1032}
1033
1034void
1035ConnectStateData::defaults()
1036{
cc192b50 1037 S = default_addr;
1038 S.SetPort(default_port);
2d8c0b1a 1039}
62e76326 1040
2d8c0b1a 1041void
1042ConnectStateData::connect()
1043{
cc192b50 1044 if (S.IsAnyAddr())
2d8c0b1a 1045 defaults();
62e76326 1046
cc192b50 1047 debugs(5,5, "ConnectSateData::connect: to " << S);
1048
1049 switch (comm_connect_addr(fd, S) ) {
62e76326 1050
e5f6c5c2 1051 case COMM_INPROGRESS:
bf8fe701 1052 debugs(5, 5, "ConnectStateData::connect: FD " << fd << ": COMM_INPROGRESS");
2d8c0b1a 1053 commSetSelect(fd, COMM_SELECT_WRITE, ConnectStateData::Connect, this, 0);
62e76326 1054 break;
1055
e5f6c5c2 1056 case COMM_OK:
cc192b50 1057 debugs(5, 5, "ConnectStateData::connect: FD " << fd << ": COMM_OK - connected");
1058 ipcacheMarkGoodAddr(host, S);
2d8c0b1a 1059 callCallback(COMM_OK, 0);
62e76326 1060 break;
1061
e5f6c5c2 1062 default:
cc192b50 1063 debugs(5, 5, "ConnectStateData::connect: FD " << fd << ": * - try again");
2d8c0b1a 1064 tries++;
cc192b50 1065 ipcacheMarkBadAddr(host, S);
62e76326 1066
1067 if (Config.onoff.test_reachability)
cc192b50 1068 netdbDeleteAddrNetwork(S);
62e76326 1069
0b77ecd8 1070 if (commRetryConnect()) {
4ed0e075 1071 eventAdd("commReconnect", commReconnect, this, this->addrcount == 1 ? 0.05 : 0.0, 0);
62e76326 1072 } else {
cc192b50 1073 debugs(5, 5, "ConnectStateData::connect: FD " << fd << ": * - ERR tried too many times already.");
2d8c0b1a 1074 callCallback(COMM_ERR_CONNECT, errno);
62e76326 1075 }
090089c4 1076 }
090089c4 1077}
b0469965 1078/*
b8d8561b 1079int
b0469965 1080commSetTimeout_old(int fd, int timeout, PF * handler, void *data)
090089c4 1081{
bf8fe701 1082 debugs(5, 3, "commSetTimeout: FD " << fd << " timeout " << timeout);
03eb2f01 1083 assert(fd >= 0);
1084 assert(fd < Squid_MaxFD);
2d8c0b1a 1085 fde *F = &fd_table[fd];
60c0b5a2 1086 assert(F->flags.open);
62e76326 1087
5c5783a2 1088 if (timeout < 0) {
62e76326 1089 cbdataReferenceDone(F->timeout_data);
1090 F->timeout_handler = NULL;
1091 F->timeout = 0;
5849612f 1092 } else {
62e76326 1093 if (handler) {
1094 cbdataReferenceDone(F->timeout_data);
1095 F->timeout_handler = handler;
1096 F->timeout_data = cbdataReference(data);
1097 }
1098
1099 F->timeout = squid_curtime + (time_t) timeout;
30a4f2a8 1100 }
62e76326 1101
a3fa14bf 1102 return F->timeout;
090089c4 1103}
b0469965 1104*/
1105
1106int
1107commSetTimeout(int fd, int timeout, PF * handler, void *data)
1108{
1109 AsyncCall::Pointer call;
1110 debugs(5, 3, "commSetTimeout: FD " << fd << " timeout " << timeout);
1111 if(handler != NULL)
1112 call=commCbCall(5,4, "SomeTimeoutHandler", CommTimeoutCbPtrFun(handler, data));
1113 else
1114 call = NULL;
1115 return commSetTimeout(fd, timeout, call);
1116}
1117
1118
1119int commSetTimeout(int fd, int timeout, AsyncCall::Pointer &callback)
1120{
1121 debugs(5, 3, "commSetTimeout: FD " << fd << " timeout " << timeout);
1122 assert(fd >= 0);
1123 assert(fd < Squid_MaxFD);
1124 fde *F = &fd_table[fd];
1125 assert(F->flags.open);
1126
1127 if (timeout < 0) {
1128 F->timeoutHandler = NULL;
1129 F->timeout = 0;
1130 } else {
1131 if (callback != NULL) {
1132 typedef CommTimeoutCbParams Params;
1133 Params &params = GetCommParams<Params>(callback);
1134 params.fd = fd;
1135 F->timeoutHandler = callback;
1136 }
1137
1138 F->timeout = squid_curtime + (time_t) timeout;
1139 }
1140
1141 return F->timeout;
1142
1143}
090089c4 1144
b8d8561b 1145int
cc192b50 1146comm_connect_addr(int sock, const IPAddress &address)
090089c4 1147{
3d7e9d7c 1148 comm_err_t status = COMM_OK;
76f87348 1149 fde *F = &fd_table[sock];
cc192b50 1150 int x = 0;
b5568a61 1151 int err = 0;
9689d97c 1152 socklen_t errlen;
0e1a47f0
AJ
1153 struct sockaddr_storage sas;
1154 socklen_t slen = sizeof(struct sockaddr_storage);
88bfe092 1155 PROF_start(comm_connect_addr);
cc192b50 1156
1157 assert(address.GetPort() != 0);
1158
b0469965 1159 debugs(5, 9, "comm_connect_addr: connecting socket " << sock << " to " << address << " (want family: " << F->sock_family << ")");
cc192b50 1160
fa2d8a61 1161 memset(&sas, 0, slen);
0e1a47f0 1162 address.GetSockAddr(sas, F->sock_family);
cc192b50 1163
090089c4 1164 /* Establish connection. */
b5568a61 1165 errno = 0;
62e76326 1166
1167 if (!F->flags.called_connect)
1168 {
1169 F->flags.called_connect = 1;
1170 statCounter.syscalls.sock.connects++;
1171
0e1a47f0 1172 x = connect(sock, (struct sockaddr*)&sas, slen);
62e76326 1173
5a33a66a 1174 // XXX: ICAP code refuses callbacks during a pending comm_ call
1175 // Async calls development will fix this.
1176 if (x == 0) {
1177 x = -1;
1178 errno = EINPROGRESS;
1179 }
1180
62e76326 1181 if (x < 0)
cc192b50 1182 {
1183 debugs(5,5, "comm_connect_addr: sock=" << sock << ", addrinfo( " <<
0e1a47f0
AJ
1184 ", family=" << sas.ss_family <<
1185 ", addrlen=" << slen <<
cc192b50 1186 " )" );
1187 debugs(5, 9, "connect FD " << sock << ": (" << x << ") " << xstrerror());
1188 debugs(14,9, "connecting to: " << address );
1189 }
62e76326 1190 } else
1191 {
140e2c0b 1192#if defined(_SQUID_NEWSOS6_)
62e76326 1193 /* Makoto MATSUSHITA <matusita@ics.es.osaka-u.ac.jp> */
1194
0e1a47f0 1195 connect(sock, (struct sockaddr*)&sas, slen);
62e76326 1196
1197 if (errno == EINVAL) {
1198 errlen = sizeof(err);
1199 x = getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &errlen);
1200
1201 if (x >= 0)
1202 errno = x;
1203 }
1204
33ac9442 1205#else
62e76326 1206 errlen = sizeof(err);
1207
1208 x = getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &errlen);
1209
1210 if (x == 0)
1211 errno = err;
1212
b5568a61 1213#if defined(_SQUID_SOLARIS_)
62e76326 1214 /*
1215 * Solaris 2.4's socket emulation doesn't allow you
1216 * to determine the error from a failed non-blocking
1217 * connect and just returns EPIPE. Create a fake
1218 * error message for connect. -- fenner@parc.xerox.com
1219 */
1220 if (x < 0 && errno == EPIPE)
1221 errno = ENOTCONN;
1222
33ac9442 1223#endif
30a4f2a8 1224#endif
62e76326 1225
e5f6c5c2 1226 }
62e76326 1227
88bfe092 1228 PROF_stop(comm_connect_addr);
62e76326 1229
b5568a61 1230 if (errno == 0 || errno == EISCONN)
62e76326 1231 status = COMM_OK;
b5568a61 1232 else if (ignoreErrno(errno))
62e76326 1233 status = COMM_INPROGRESS;
b5568a61 1234 else
cc192b50 1235#if USE_IPV6
1236 if( address.IsIPv4() && F->sock_family == AF_INET6 ) {
1237
1238 /* failover to trying IPv4-only link if an IPv6 one fails */
1239 /* to catch the edge case of apps listening on IPv4-localhost */
1240 F->sock_family = AF_INET;
1241 int res = comm_connect_addr(sock, address);
1242
1243 /* if that fails too, undo our temporary socktype hack so the repeat works properly. */
1244 if(res == COMM_ERROR)
1245 F->sock_family = AF_INET6;
1246
1247 return res;
1248 }
1249 else
1250#endif
62e76326 1251 return COMM_ERROR;
1252
cc192b50 1253 address.NtoA(F->ipaddr, MAX_IPSTRLEN);
62e76326 1254
cc192b50 1255 F->remote_port = address.GetPort(); /* remote_port is HS */
62e76326 1256
1257 if (status == COMM_OK)
1258 {
cc192b50 1259 debugs(5, 10, "comm_connect_addr: FD " << sock << " connected to " << address);
62e76326 1260 } else if (status == COMM_INPROGRESS)
1261 {
bf8fe701 1262 debugs(5, 10, "comm_connect_addr: FD " << sock << " connection pending");
090089c4 1263 }
62e76326 1264
090089c4 1265 return status;
1266}
1267
1268/* Wait for an incoming connection on FD. FD should be a socket returned
1269 * from comm_listen. */
ee0989f2 1270static int
1271comm_old_accept(int fd, ConnectionDetail &details)
090089c4 1272{
88bfe092 1273 PROF_start(comm_accept);
ee0989f2 1274 statCounter.syscalls.sock.accepts++;
1275 int sock;
cc192b50 1276 struct addrinfo *gai = NULL;
1277 details.me.InitAddrInfo(gai);
1278
1279 if ((sock = accept(fd, gai->ai_addr, &gai->ai_addrlen)) < 0) {
1280
1281 details.me.FreeAddrInfo(gai);
62e76326 1282
62e76326 1283 PROF_stop(comm_accept);
1284
1285 if (ignoreErrno(errno))
1286 {
bf8fe701 1287 debugs(50, 5, "comm_old_accept: FD " << fd << ": " << xstrerror());
62e76326 1288 return COMM_NOMESSAGE;
1289 } else if (ENFILE == errno || EMFILE == errno)
1290 {
bf8fe701 1291 debugs(50, 3, "comm_old_accept: FD " << fd << ": " << xstrerror());
62e76326 1292 return COMM_ERROR;
1293 } else
1294 {
bf8fe701 1295 debugs(50, 1, "comm_old_accept: FD " << fd << ": " << xstrerror());
62e76326 1296 return COMM_ERROR;
1297 }
090089c4 1298 }
62e76326 1299
cc192b50 1300 details.peer = *gai;
1301
3be4d5d1 1302 details.me.InitAddrInfo(gai);
1303
cc192b50 1304 details.me.SetEmpty();
1305 getsockname(sock, gai->ai_addr, &gai->ai_addrlen);
1306 details.me = *gai;
62e76326 1307
3ca60c86 1308 commSetCloseOnExec(sock);
cc192b50 1309
090089c4 1310 /* fdstat update */
5c5783a2 1311 fd_open(sock, FD_SOCKET, "HTTP Request");
c4b7a5a9 1312 fdd_table[sock].close_file = NULL;
1313 fdd_table[sock].close_line = 0;
ee0989f2 1314 fde *F = &fd_table[sock];
cc192b50 1315 details.peer.NtoA(F->ipaddr,MAX_IPSTRLEN);
1316 F->remote_port = details.peer.GetPort();
1317 F->local_addr.SetPort(details.me.GetPort());
3be4d5d1 1318#if USE_IPV6
1319 F->sock_family = AF_INET;
1320#else
1321 F->sock_family = details.me.IsIPv4()?AF_INET:AF_INET6;
1322#endif
1323 details.me.FreeAddrInfo(gai);
cc192b50 1324
090089c4 1325 commSetNonBlocking(sock);
cc192b50 1326
72d57dea
AJ
1327#if LINUX_TPROXY4
1328 /* AYJ: do we need to set this again on every accept? */
3949d8b7 1329 if(fd_table[fd].flags.transparent == 1) {
41c477f5 1330 comm_set_transparent(sock, 0);
3949d8b7 1331 F->flags.transparent = 1;
41c477f5 1332 }
72d57dea
AJ
1333#endif
1334
88bfe092 1335 PROF_stop(comm_accept);
090089c4 1336 return sock;
1337}
1338
cb201b7e 1339void
1340commCallCloseHandlers(int fd)
1341{
76f87348 1342 fde *F = &fd_table[fd];
bf8fe701 1343 debugs(5, 5, "commCallCloseHandlers: FD " << fd);
62e76326 1344
8000a965 1345 while (F->closeHandler != NULL) {
b0469965 1346 AsyncCall::Pointer call = F->closeHandler;
1347 F->closeHandler = call->Next();
1348 call->setNext(NULL);
1349 // If call is not canceled schedule it for execution else ignore it
1350 if(!call->canceled()){
1351 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call);
1352 typedef CommCloseCbParams Params;
1353 Params &params = GetCommParams<Params>(call);
1354 params.fd = fd;
1355 ScheduleCallHere(call);
1356 }
cb201b7e 1357 }
1358}
1359
5492ad1d 1360#if LINGERING_CLOSE
1361static void
1362commLingerClose(int fd, void *unused)
1363{
1364 LOCAL_ARRAY(char, buf, 1024);
1365 int n;
1f7c9178 1366 n = FD_READ_METHOD(fd, buf, 1024);
62e76326 1367
5492ad1d 1368 if (n < 0)
bf8fe701 1369 debugs(5, 3, "commLingerClose: FD " << fd << " read: " << xstrerror());
62e76326 1370
5492ad1d 1371 comm_close(fd);
1372}
1373
1374static void
1375commLingerTimeout(int fd, void *unused)
1376{
bf8fe701 1377 debugs(5, 3, "commLingerTimeout: FD " << fd);
5492ad1d 1378 comm_close(fd);
1379}
1380
1381/*
1382 * Inspired by apache
1383 */
1384void
1385comm_lingering_close(int fd)
1386{
d4c19b39 1387#if USE_SSL
62e76326 1388
d4c19b39 1389 if (fd_table[fd].ssl)
62e76326 1390 ssl_shutdown_method(fd);
1391
d4c19b39 1392#endif
62e76326 1393
5492ad1d 1394 if (shutdown(fd, 1) < 0) {
62e76326 1395 comm_close(fd);
1396 return;
5492ad1d 1397 }
62e76326 1398
5492ad1d 1399 fd_note(fd, "lingering close");
1400 commSetTimeout(fd, 10, commLingerTimeout, NULL);
1401 commSetSelect(fd, COMM_SELECT_READ, commLingerClose, NULL, 0);
1402}
62e76326 1403
5492ad1d 1404#endif
1405
98264874 1406/*
1407 * enable linger with time of 0 so that when the socket is
1408 * closed, TCP generates a RESET
1409 */
1410void
1411comm_reset_close(int fd)
1412{
62e76326 1413
98264874 1414 struct linger L;
1415 L.l_onoff = 1;
1416 L.l_linger = 0;
62e76326 1417
98264874 1418 if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &L, sizeof(L)) < 0)
bf8fe701 1419 debugs(50, 0, "commResetTCPClose: FD " << fd << ": " << xstrerror());
62e76326 1420
98264874 1421 comm_close(fd);
1422}
1423
2d8c0b1a 1424void
b0469965 1425CommRead::doCallback(comm_err_t errcode, int xerrno)
2d8c0b1a 1426{
b0469965 1427 if (callback != NULL) {
1428 typedef CommIoCbParams Params;
1429 Params &params = GetCommParams<Params>(callback);
1430 params.fd = fd;
1431 params.size = 0;
1432 params.flag = errcode;
1433 params.xerrno = xerrno;
1434 ScheduleCallHere(callback);
1435 callback = NULL;
1436 }
2d8c0b1a 1437}
1438
b0469965 1439void
1440comm_close_complete(int fd, void *data)
2d8c0b1a 1441{
b0469965 1442#if USE_SSL
1443 fde *F = &fd_table[fd];
2d8c0b1a 1444
b0469965 1445 if (F->ssl) {
1446 SSL_free(F->ssl);
1447 F->ssl = NULL;
1448 }
2d8c0b1a 1449
b0469965 1450#endif
1451 fd_close(fd); /* update fdstat */
1452
1453 close(fd);
1454
1455 if (AbortChecker::Instance().isMonitoring(fd))
1456 AbortChecker::Instance().stopMonitoring(fd);
1457
1458 fdc_table[fd] = AcceptFD(fd);
1459
1460 statCounter.syscalls.sock.closes++;
1461
1462 /* When an fd closes, give accept() a chance, if need be */
1463
1464 if (fdNFree() >= RESERVED_FD)
1465 AcceptLimiter::Instance().kick();
2d8c0b1a 1466
2d8c0b1a 1467}
c4b7a5a9 1468
1469/*
1470 * Close the socket fd.
1471 *
1472 * + call write handlers with ERR_CLOSING
1473 * + call read handlers with ERR_CLOSING
1474 * + call closing handlers
a46d2c0e 1475 *
1476 * NOTE: COMM_ERR_CLOSING will NOT be called for CommReads' sitting in a
1477 * DeferredReadManager.
c4b7a5a9 1478 */
b8d8561b 1479void
43ae1d95 1480_comm_close(int fd, char const *file, int line)
090089c4 1481{
76f87348 1482 fde *F = NULL;
1f7c9178 1483
bf8fe701 1484 debugs(5, 5, "comm_close: FD " << fd);
03eb2f01 1485 assert(fd >= 0);
1486 assert(fd < Squid_MaxFD);
76f87348 1487 F = &fd_table[fd];
c4b7a5a9 1488 fdd_table[fd].close_file = file;
1489 fdd_table[fd].close_line = line;
1f7c9178 1490
58a6c186 1491 if (F->flags.closing)
62e76326 1492 return;
1493
60c0b5a2 1494 if (shutting_down && (!F->flags.open || F->type == FD_FILE))
62e76326 1495 return;
1496
60c0b5a2 1497 assert(F->flags.open);
62e76326 1498
c4b7a5a9 1499 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
b0469965 1500 assert(isOpen(fd));
62e76326 1501
76f87348 1502 assert(F->type != FD_FILE);
62e76326 1503
88bfe092 1504 PROF_start(comm_close);
62e76326 1505
58a6c186 1506 F->flags.closing = 1;
62e76326 1507
d4c19b39 1508#if USE_SSL
62e76326 1509
d4c19b39 1510 if (F->ssl)
62e76326 1511 ssl_shutdown_method(fd);
1512
d4c19b39 1513#endif
62e76326 1514
fa80a8ef 1515 commSetTimeout(fd, -1, NULL, NULL);
62e76326 1516
2b663917 1517 /* new-style read/write handler stuff */
1518 if (commio_has_callback(fd, IOCB_WRITE, COMMIO_FD_WRITECB(fd))) {
b0469965 1519 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), COMM_ERR_CLOSING, errno);
2b663917 1520 }
1521 if (commio_has_callback(fd, IOCB_READ, COMMIO_FD_READCB(fd))) {
b0469965 1522 commio_finish_callback(fd, COMMIO_FD_READCB(fd), COMM_ERR_CLOSING, errno);
2b663917 1523 }
2d8c0b1a 1524
2b663917 1525 /* Do callbacks for read/accept routines, if any */
b0469965 1526 fdc_table[fd].notify(-1, COMM_ERR_CLOSING, 0, ConnectionDetail());
c4b7a5a9 1527
cb201b7e 1528 commCallCloseHandlers(fd);
62e76326 1529
781ce8ff 1530 if (F->pconn.uses)
1531 F->pconn.pool->count(F->pconn.uses);
62e76326 1532
a7ad6e4e 1533 comm_empty_os_read_buffers(fd);
b0469965 1534
62e76326 1535
b0469965 1536 AsyncCall::Pointer call=commCbCall(5,4, "comm_close_complete",
1537 CommCloseCbPtrFun(comm_close_complete, NULL));
1538 typedef CommCloseCbParams Params;
1539 Params &params = GetCommParams<Params>(call);
1540 params.fd = fd;
1541 ScheduleCallHere(call);
62e76326 1542
88bfe092 1543 PROF_stop(comm_close);
090089c4 1544}
1545
090089c4 1546/* Send a udp datagram to specified TO_ADDR. */
b8d8561b 1547int
5df61230 1548comm_udp_sendto(int fd,
cc192b50 1549 const IPAddress &to_addr,
62e76326 1550 const void *buf,
1551 int len)
090089c4 1552{
cc192b50 1553 int x = 0;
1554 struct addrinfo *AI = NULL;
1555
88bfe092 1556 PROF_start(comm_udp_sendto);
83704487 1557 statCounter.syscalls.sock.sendtos++;
62e76326 1558
cc192b50 1559 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr <<
1560 " using FD " << fd << " using Port " << comm_local_port(fd) );
1561
1562 /* BUG: something in the above macro appears to occasionally be setting AI to garbage. */
1563 /* AYJ: 2007-08-27 : or was it because I wasn't then setting 'fd_table[fd].sock_family' to fill properly. */
1564 assert( NULL == AI );
1565
1566 to_addr.GetAddrInfo(AI, fd_table[fd].sock_family);
1567
1568 x = sendto(fd, buf, len, 0, AI->ai_addr, AI->ai_addrlen);
1569
1570 to_addr.FreeAddrInfo(AI);
1571
88bfe092 1572 PROF_stop(comm_udp_sendto);
62e76326 1573
2d8c0b1a 1574 if (x >= 0)
1575 return x;
1576
17d51783 1577#ifdef _SQUID_LINUX_
62e76326 1578
2d8c0b1a 1579 if (ECONNREFUSED != errno)
17d51783 1580#endif
62e76326 1581
cc192b50 1582 debugs(50, 1, "comm_udp_sendto: FD " << fd << ", (family=" << fd_table[fd].sock_family << ") " << to_addr << ": " << xstrerror());
62e76326 1583
2d8c0b1a 1584 return COMM_ERROR;
090089c4 1585}
1586
b8d8561b 1587void
582b6456 1588comm_add_close_handler(int fd, PF * handler, void *data)
30a4f2a8 1589{
bf8fe701 1590 debugs(5, 5, "comm_add_close_handler: FD " << fd << ", handler=" <<
1591 handler << ", data=" << data);
62e76326 1592
b0469965 1593 AsyncCall::Pointer call=commCbCall(5,4, "SomeCloseHandler",
1594 CommCloseCbPtrFun(handler, data));
1595 comm_add_close_handler(fd, call);
1596}
62e76326 1597
b0469965 1598void
1599comm_add_close_handler(int fd, AsyncCall::Pointer &call)
1600{
1601 debugs(5, 5, "comm_add_close_handler: FD " << fd << ", AsyncCall=" << call);
62e76326 1602
b0469965 1603 /*TODO:Check for a similar scheduled AsyncCall*/
1604// for (c = fd_table[fd].closeHandler; c; c = c->next)
1605// assert(c->handler != handler || c->data != data);
62e76326 1606
b0469965 1607 call->setNext(fd_table[fd].closeHandler);
62e76326 1608
b0469965 1609 fd_table[fd].closeHandler = call;
30a4f2a8 1610}
1611
b0469965 1612
1613// remove function-based close handler
b8d8561b 1614void
582b6456 1615comm_remove_close_handler(int fd, PF * handler, void *data)
090089c4 1616{
b0469965 1617 assert (isOpen(fd));
30a4f2a8 1618 /* Find handler in list */
bf8fe701 1619 debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", handler=" <<
1620 handler << ", data=" << data);
62e76326 1621
b0469965 1622 AsyncCall::Pointer p;
1623 for (p = fd_table[fd].closeHandler; p != NULL; p = p->Next()){
1624 typedef CommCbFunPtrCallT<CommCloseCbPtrFun> Call;
1625 const Call *call = dynamic_cast<const Call*>(p.getRaw());
1626 if (!call) // method callbacks have their own comm_remove_close_handler
1627 continue;
62e76326 1628
b0469965 1629 typedef CommCloseCbParams Params;
1630 const Params &params = GetCommParams<Params>(p);
1631 if (call->dialer.handler == handler && params.data == data)
1632 break; /* This is our handler */
1633 }
f88211e8 1634 assert(p != NULL);
b0469965 1635 p->cancel("comm_remove_close_handler");
1636}
62e76326 1637
b0469965 1638// remove method-based close handler
1639void
1640comm_remove_close_handler(int fd, AsyncCall::Pointer &call)
1641{
1642 assert (isOpen(fd));
1643 /* Find handler in list */
1644 debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", AsyncCall=" << call);
62e76326 1645
b0469965 1646 // Check to see if really exist the given AsyncCall in comm_close handlers
1647 // TODO: optimize: this slow code is only needed for the assert() below
1648 AsyncCall::Pointer p;
1649 for (p = fd_table[fd].closeHandler; p != NULL && p != call; p = p->Next());
1650 assert(p == call);
62e76326 1651
b0469965 1652 call->cancel("comm_remove_close_handler");
30a4f2a8 1653}
090089c4 1654
b8d8561b 1655static void
1656commSetNoLinger(int fd)
30a4f2a8 1657{
62e76326 1658
30a4f2a8 1659 struct linger L;
090089c4 1660 L.l_onoff = 0; /* off */
1661 L.l_linger = 0;
62e76326 1662
30a4f2a8 1663 if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char *) &L, sizeof(L)) < 0)
bf8fe701 1664 debugs(50, 0, "commSetNoLinger: FD " << fd << ": " << xstrerror());
62e76326 1665
58a6c186 1666 fd_table[fd].flags.nolinger = 1;
090089c4 1667}
1668
b8d8561b 1669static void
1670commSetReuseAddr(int fd)
090089c4 1671{
1672 int on = 1;
62e76326 1673
30a4f2a8 1674 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)) < 0)
bf8fe701 1675 debugs(50, 1, "commSetReuseAddr: FD " << fd << ": " << xstrerror());
090089c4 1676}
1677
b8d8561b 1678static void
1679commSetTcpRcvbuf(int fd, int size)
f868539a 1680{
1681 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &size, sizeof(size)) < 0)
bf8fe701 1682 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd << ", SIZE " << size << ": " << xstrerror());
8f0d53ef 1683 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &size, sizeof(size)) < 0)
1684 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd << ", SIZE " << size << ": " << xstrerror());
1685#ifdef TCP_WINDOW_CLAMP
1686 if (setsockopt(fd, SOL_TCP, TCP_WINDOW_CLAMP, (char *) &size, sizeof(size)) < 0)
1687 debugs(50, 1, "commSetTcpRcvbuf: FD " << fd << ", SIZE " << size << ": " << xstrerror());
1688#endif
f868539a 1689}
1690
b8d8561b 1691int
1692commSetNonBlocking(int fd)
30a4f2a8 1693{
a50bfe93 1694#ifndef _SQUID_MSWIN_
731e4d49 1695 int flags;
9e205701 1696 int dummy = 0;
a50bfe93 1697#endif
ec4daaa5 1698#ifdef _SQUID_WIN32_
62e76326 1699
b05490a8 1700 int nonblocking = TRUE;
62e76326 1701
629b5f75 1702#ifdef _SQUID_CYGWIN_
1703
7f6ffd15 1704 if (fd_table[fd].type != FD_PIPE) {
629b5f75 1705#endif
1706
62e76326 1707 if (ioctl(fd, FIONBIO, &nonblocking) < 0) {
bf8fe701 1708 debugs(50, 0, "commSetNonBlocking: FD " << fd << ": " << xstrerror() << " " << fd_table[fd].type);
62e76326 1709 return COMM_ERROR;
1710 }
629b5f75 1711
1712#ifdef _SQUID_CYGWIN_
1713
7f6ffd15 1714 } else {
1715#endif
629b5f75 1716#endif
a50bfe93 1717#ifndef _SQUID_MSWIN_
62e76326 1718
1719 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
bf8fe701 1720 debugs(50, 0, "FD " << fd << ": fcntl F_GETFL: " << xstrerror());
62e76326 1721 return COMM_ERROR;
1722 }
1723
1724 if (fcntl(fd, F_SETFL, flags | SQUID_NONBLOCK) < 0) {
bf8fe701 1725 debugs(50, 0, "commSetNonBlocking: FD " << fd << ": " << xstrerror());
62e76326 1726 return COMM_ERROR;
1727 }
1728
a50bfe93 1729#endif
629b5f75 1730#ifdef _SQUID_CYGWIN_
62e76326 1731
090089c4 1732 }
62e76326 1733
7f6ffd15 1734#endif
58a6c186 1735 fd_table[fd].flags.nonblocking = 1;
62e76326 1736
090089c4 1737 return 0;
1738}
1739
7e3ce7b9 1740int
1741commUnsetNonBlocking(int fd)
1742{
a50bfe93 1743#ifdef _SQUID_MSWIN_
1744 int nonblocking = FALSE;
1745
1746 if (ioctlsocket(fd, FIONBIO, (unsigned long *) &nonblocking) < 0) {
1747#else
7e3ce7b9 1748 int flags;
1749 int dummy = 0;
62e76326 1750
7e3ce7b9 1751 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
bf8fe701 1752 debugs(50, 0, "FD " << fd << ": fcntl F_GETFL: " << xstrerror());
62e76326 1753 return COMM_ERROR;
7e3ce7b9 1754 }
62e76326 1755
7e3ce7b9 1756 if (fcntl(fd, F_SETFL, flags & (~SQUID_NONBLOCK)) < 0) {
a50bfe93 1757#endif
bf8fe701 1758 debugs(50, 0, "commUnsetNonBlocking: FD " << fd << ": " << xstrerror());
62e76326 1759 return COMM_ERROR;
7e3ce7b9 1760 }
62e76326 1761
7e3ce7b9 1762 fd_table[fd].flags.nonblocking = 0;
1763 return 0;
1764}
1765
b8d8561b 1766void
a50bfe93 1767commSetCloseOnExec(int fd) {
3ca60c86 1768#ifdef FD_CLOEXEC
731e4d49 1769 int flags;
7a18b487 1770 int dummy = 0;
62e76326 1771
c7989865 1772 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
bf8fe701 1773 debugs(50, 0, "FD " << fd << ": fcntl F_GETFL: " << xstrerror());
62e76326 1774 return;
3ca60c86 1775 }
62e76326 1776
24382924 1777 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
bf8fe701 1778 debugs(50, 0, "FD " << fd << ": set close-on-exec failed: " << xstrerror());
62e76326 1779
d6827718 1780 fd_table[fd].flags.close_on_exec = 1;
62e76326 1781
3ca60c86 1782#endif
1783}
1784
e90100aa 1785#ifdef TCP_NODELAY
1786static void
a50bfe93 1787commSetTcpNoDelay(int fd) {
e90100aa 1788 int on = 1;
62e76326 1789
e90100aa 1790 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) < 0)
bf8fe701 1791 debugs(50, 1, "commSetTcpNoDelay: FD " << fd << ": " << xstrerror());
62e76326 1792
d6827718 1793 fd_table[fd].flags.nodelay = 1;
e90100aa 1794}
62e76326 1795
e90100aa 1796#endif
1797
b2130d58 1798void
1799commSetTcpKeepalive(int fd, int idle, int interval, int timeout)
1800{
1801 int on = 1;
1802#ifdef TCP_KEEPCNT
1803 if (timeout && interval) {
1804 int count = (timeout + interval - 1) / interval;
1805 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(on)) < 0)
1806 debug(5, 1) ("commSetKeepalive: FD %d: %s\n", fd, xstrerror());
1807 }
1808#endif
1809#ifdef TCP_KEEPIDLE
1810 if (idle) {
1811 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(on)) < 0)
1812 debug(5, 1) ("commSetKeepalive: FD %d: %s\n", fd, xstrerror());
1813 }
1814#endif
1815#ifdef TCP_KEEPINTVL
1816 if (interval) {
1817 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &interval, sizeof(on)) < 0)
1818 debug(5, 1) ("commSetKeepalive: FD %d: %s\n", fd, xstrerror());
1819 }
1820#endif
1821 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) < 0)
1822 debug(5, 1) ("commSetKeepalive: FD %d: %s\n", fd, xstrerror());
1823}
6a988308 1824
d86b3703 1825void
a50bfe93 1826comm_init(void) {
c4b7a5a9 1827 fd_table =(fde *) xcalloc(Squid_MaxFD, sizeof(fde));
1828 fdd_table = (fd_debug_t *)xcalloc(Squid_MaxFD, sizeof(fd_debug_t));
2d8c0b1a 1829
b0469965 1830 fdc_table = new AcceptFD[Squid_MaxFD];
2b663917 1831 for (int pos = 0; pos < Squid_MaxFD; ++pos) {
b0469965 1832 fdc_table[pos] = AcceptFD(pos);
2b663917 1833 }
b0469965 1834
1835 commfd_table = (comm_fd_t *) xcalloc(Squid_MaxFD, sizeof(comm_fd_t));
2b663917 1836 for (int pos = 0; pos < Squid_MaxFD; pos++) {
1837 commfd_table[pos].fd = pos;
1838 commfd_table[pos].readcb.fd = pos;
1839 commfd_table[pos].readcb.type = IOCB_READ;
1840 commfd_table[pos].writecb.fd = pos;
1841 commfd_table[pos].writecb.type = IOCB_WRITE;
1842 }
2d8c0b1a 1843
59c4d35b 1844 /* XXX account fd_table */
090089c4 1845 /* Keep a few file descriptors free so that we don't run out of FD's
1846 * after accepting a client but before it opens a socket or a file.
e83892e9 1847 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
0254ee29 1848 RESERVED_FD = XMIN(100, Squid_MaxFD / 4);
2d8c0b1a 1849
04eb0689 1850 conn_close_pool = memPoolCreate("close_handler", sizeof(close_handler));
090089c4 1851}
1852
236d1779 1853void
1854comm_exit(void) {
1855 safe_free(fd_table);
1856 safe_free(fdd_table);
1857 if (fdc_table) {
1858 delete[] fdc_table;
1859 fdc_table = NULL;
1860 }
1861 safe_free(commfd_table);
1862}
1863
30a4f2a8 1864/* Write to FD. */
b8d8561b 1865static void
a50bfe93 1866commHandleWrite(int fd, void *data) {
2b663917 1867 comm_io_callback_t *state = (comm_io_callback_t *)data;
30a4f2a8 1868 int len = 0;
1869 int nleft;
1870
2b663917 1871 assert(state == COMMIO_FD_WRITECB(fd));
1872
88bfe092 1873 PROF_start(commHandleWrite);
bf8fe701 1874 debugs(5, 5, "commHandleWrite: FD " << fd << ": off " <<
1875 (long int) state->offset << ", sz " << (long int) state->size << ".");
30a4f2a8 1876
1877 nleft = state->size - state->offset;
1f7c9178 1878 len = FD_WRITE_METHOD(fd, state->buf + state->offset, nleft);
bf8fe701 1879 debugs(5, 5, "commHandleWrite: write() returns " << len);
b69f7771 1880 fd_bytes(fd, len, FD_WRITE);
83704487 1881 statCounter.syscalls.sock.writes++;
30a4f2a8 1882
1883 if (len == 0) {
62e76326 1884 /* Note we even call write if nleft == 0 */
1885 /* We're done */
1886
1887 if (nleft != 0)
bf8fe701 1888 debugs(5, 1, "commHandleWrite: FD " << fd << ": write failure: connection closed with " << nleft << " bytes remaining.");
62e76326 1889
b0469965 1890 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), nleft ? COMM_ERROR : COMM_OK, errno);
30a4f2a8 1891 } else if (len < 0) {
62e76326 1892 /* An error */
1893
1894 if (fd_table[fd].flags.socket_eof) {
bf8fe701 1895 debugs(50, 2, "commHandleWrite: FD " << fd << ": write failure: " << xstrerror() << ".");
b0469965 1896 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), nleft ? COMM_ERROR : COMM_OK, errno);
62e76326 1897 } else if (ignoreErrno(errno)) {
bf8fe701 1898 debugs(50, 10, "commHandleWrite: FD " << fd << ": write failure: " << xstrerror() << ".");
62e76326 1899 commSetSelect(fd,
1900 COMM_SELECT_WRITE,
1901 commHandleWrite,
1902 state,
1903 0);
1904 } else {
bf8fe701 1905 debugs(50, 2, "commHandleWrite: FD " << fd << ": write failure: " << xstrerror() << ".");
b0469965 1906 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), nleft ? COMM_ERROR : COMM_OK, errno);
62e76326 1907 }
30a4f2a8 1908 } else {
62e76326 1909 /* A successful write, continue */
1910 state->offset += len;
1911
57d55dfa 1912 if (state->offset < state->size) {
62e76326 1913 /* Not done, reinstall the write handler and write some more */
1914 commSetSelect(fd,
1915 COMM_SELECT_WRITE,
1916 commHandleWrite,
1917 state,
1918 0);
1919 } else {
b0469965 1920 commio_finish_callback(fd, COMMIO_FD_WRITECB(fd), nleft ? COMM_OK : COMM_ERROR, errno);
62e76326 1921 }
30a4f2a8 1922 }
62e76326 1923
88bfe092 1924 PROF_stop(commHandleWrite);
30a4f2a8 1925}
1926
7cd8c414 1927/*
1928 * Queue a write. handler/handler_data are called when the write
1929 * completes, on error, or on file descriptor close.
1930 *
1931 * free_func is used to free the passed buffer when the write has completed.
1932 */
b8d8561b 1933void
2b663917 1934comm_write(int fd, const char *buf, int size, IOCB * handler, void *handler_data, FREE * free_func)
b0469965 1935{
1936 AsyncCall::Pointer call = commCbCall(5,5, "SomeCommWriteHander",
1937 CommIoCbPtrFun(handler, handler_data));
1938
1939 comm_write(fd, buf, size, call, free_func);
1940}
1941
1942void
1943comm_write(int fd, const char *buf, int size, AsyncCall::Pointer &callback, FREE * free_func)
2b663917 1944{
c4b7a5a9 1945 assert(!fd_table[fd].flags.closing);
1946
b0469965 1947 debugs(5, 5, "comm_write: FD " << fd << ": sz " << size << ": asynCall " << callback << ".");
62e76326 1948
2b663917 1949 if (commio_has_callback(fd, IOCB_WRITE, COMMIO_FD_WRITECB(fd))) {
dec5db5d 1950 /* This means that the write has been scheduled, but has not
1951 * triggered yet
1952 */
2b663917 1953 fatalf ("comm_write: fd %d: pending callback!\n", fd);
6cf028ab 1954 }
b0469965 1955
1956 commio_set_callback(fd, IOCB_WRITE, COMMIO_FD_WRITECB(fd),
1957 callback, (char *)buf, free_func, size);
2b663917 1958 commSetSelect(fd, COMM_SELECT_WRITE, commHandleWrite, COMMIO_FD_WRITECB(fd), 0);
30a4f2a8 1959}
26a880e2 1960
b0469965 1961
137ee196 1962/* a wrapper around comm_write to allow for MemBuf to be comm_written in a snap */
cb69b4c7 1963void
2b663917 1964comm_write_mbuf(int fd, MemBuf *mb, IOCB * handler, void *handler_data) {
1965 comm_write(fd, mb->buf, mb->size, handler, handler_data, mb->freeFunc());
cb69b4c7 1966}
1967
b0469965 1968void
1969comm_write_mbuf(int fd, MemBuf *mb, AsyncCall::Pointer &callback) {
1970 comm_write(fd, mb->buf, mb->size, callback, mb->freeFunc());
1971}
1972
c4b7a5a9 1973
89924214 1974/*
1975 * hm, this might be too general-purpose for all the places we'd
1976 * like to use it.
1977 */
b224ea98 1978int
a50bfe93 1979ignoreErrno(int ierrno) {
603500e7 1980 switch (ierrno) {
62e76326 1981
89924214 1982 case EINPROGRESS:
62e76326 1983
603500e7 1984 case EWOULDBLOCK:
26a880e2 1985#if EAGAIN != EWOULDBLOCK
62e76326 1986
603500e7 1987 case EAGAIN:
26a880e2 1988#endif
62e76326 1989
603500e7 1990 case EALREADY:
62e76326 1991
603500e7 1992 case EINTR:
db494ab8 1993#ifdef ERESTART
62e76326 1994
db494ab8 1995 case ERESTART:
1996#endif
62e76326 1997
1998 return 1;
1999
603500e7 2000 default:
62e76326 2001 return 0;
603500e7 2002 }
62e76326 2003
603500e7 2004 /* NOTREACHED */
26a880e2 2005}
d723bf6b 2006
2007void
a50bfe93 2008commCloseAllSockets(void) {
d723bf6b 2009 int fd;
2010 fde *F = NULL;
62e76326 2011
d723bf6b 2012 for (fd = 0; fd <= Biggest_FD; fd++) {
62e76326 2013 F = &fd_table[fd];
2014
2015 if (!F->flags.open)
2016 continue;
2017
2018 if (F->type != FD_SOCKET)
2019 continue;
2020
2021 if (F->flags.ipc) /* don't close inter-process sockets */
2022 continue;
2023
b0469965 2024 if (F->timeoutHandler != NULL) {
2025 AsyncCall::Pointer callback = F->timeoutHandler;
2026 F->timeoutHandler = NULL;
bf8fe701 2027 debugs(5, 5, "commCloseAllSockets: FD " << fd << ": Calling timeout handler");
b0469965 2028 ScheduleCallHere(callback);
62e76326 2029 } else {
bf8fe701 2030 debugs(5, 5, "commCloseAllSockets: FD " << fd << ": calling comm_close()");
62e76326 2031 comm_close(fd);
2032 }
d723bf6b 2033 }
2034}
1b3db6d9 2035
2d8c0b1a 2036static bool
a50bfe93 2037AlreadyTimedOut(fde *F) {
2d8c0b1a 2038 if (!F->flags.open)
2039 return true;
2040
2041 if (F->timeout == 0)
2042 return true;
2043
2044 if (F->timeout > squid_curtime)
2045 return true;
2046
2047 return false;
2048}
2049
1b3db6d9 2050void
a50bfe93 2051checkTimeouts(void) {
1b3db6d9 2052 int fd;
2053 fde *F = NULL;
b0469965 2054 AsyncCall::Pointer callback;
62e76326 2055
1b3db6d9 2056 for (fd = 0; fd <= Biggest_FD; fd++) {
62e76326 2057 F = &fd_table[fd];
2058
2d8c0b1a 2059 if (AlreadyTimedOut(F))
62e76326 2060 continue;
2061
bf8fe701 2062 debugs(5, 5, "checkTimeouts: FD " << fd << " Expired");
62e76326 2063
b0469965 2064 if (F->timeoutHandler != NULL) {
bf8fe701 2065 debugs(5, 5, "checkTimeouts: FD " << fd << ": Call timeout handler");
b0469965 2066 callback = F->timeoutHandler;
2067 F->timeoutHandler = NULL;
2068 ScheduleCallHere(callback);
62e76326 2069 } else {
bf8fe701 2070 debugs(5, 5, "checkTimeouts: FD " << fd << ": Forcing comm_close()");
62e76326 2071 comm_close(fd);
2072 }
b5443c04 2073 }
2074}
2075
c4b7a5a9 2076/*
2077 * New-style listen and accept routines
2078 *
2079 * Listen simply registers our interest in an FD for listening,
2080 * and accept takes a callback to call when an FD has been
2081 * accept()ed.
2082 */
2083int
a50bfe93 2084comm_listen(int sock) {
c4b7a5a9 2085 int x;
62e76326 2086
c4b7a5a9 2087 if ((x = listen(sock, Squid_MaxFD >> 2)) < 0) {
bf8fe701 2088 debugs(50, 0, "comm_listen: listen(" << (Squid_MaxFD >> 2) << ", " << sock << "): " << xstrerror());
62e76326 2089 return x;
c4b7a5a9 2090 }
62e76326 2091
0b4d4be5 2092 if (Config.accept_filter && strcmp(Config.accept_filter, "none") != 0) {
cc9f92d4 2093#ifdef SO_ACCEPTFILTER
cc9f92d4 2094 struct accept_filter_arg afa;
2095 bzero(&afa, sizeof(afa));
2096 debug(5, 0) ("Installing accept filter '%s' on FD %d\n",
2097 Config.accept_filter, sock);
2098 xstrncpy(afa.af_name, Config.accept_filter, sizeof(afa.af_name));
2099 x = setsockopt(sock, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa));
2100 if (x < 0)
0b4d4be5 2101 debugs(5, 0, "SO_ACCEPTFILTER '" << Config.accept_filter << "': '" << xstrerror());
2102#elif defined(TCP_DEFER_ACCEPT)
2103 int seconds = 30;
2104 if (strncmp(Config.accept_filter, "data=", 5) == 0)
2105 seconds = atoi(Config.accept_filter + 5);
2106 x = setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &seconds, sizeof(seconds));
2107 if (x < 0)
2108 debugs(5, 0, "TCP_DEFER_ACCEPT '" << Config.accept_filter << "': '" << xstrerror());
2109#else
2110 debugs(5, 0, "accept_filter not supported on your OS");
cc9f92d4 2111#endif
0b4d4be5 2112 }
cc9f92d4 2113
c4b7a5a9 2114 return sock;
2115}
2116
b0469965 2117// AcceptFD::callback() wrapper
2d8c0b1a 2118void
b0469965 2119comm_accept(int fd, IOACB *handler, void *handler_data) {
2120 debugs(5, 5, "comm_accept: FD " << fd << " handler: " << (void*)handler);
2121 assert(isOpen(fd));
2122
2123 AsyncCall::Pointer call = commCbCall(5,5, "SomeCommAcceptHandler",
2124 CommAcceptCbPtrFun(handler, handler_data));
2125 fdc_table[fd].subscribe(call);
2d8c0b1a 2126}
c4b7a5a9 2127
b0469965 2128void
2129comm_accept(int fd, AsyncCall::Pointer &call) {
2130 debugs(5, 5, "comm_accept: FD " << fd << " AsyncCall: " << call);
2131 assert(isOpen(fd));
2132
2133 fdc_table[fd].subscribe(call);
2d8c0b1a 2134}
62e76326 2135
b0469965 2136// Called when somebody wants to be notified when our socket accepts new
2137// connection. We do not probe the FD until there is such interest.
2d8c0b1a 2138void
b0469965 2139AcceptFD::subscribe(AsyncCall::Pointer &call) {
2140 /* make sure we're not pending! */
2141 assert(!theCallback);
2142 theCallback = call;
2143
2144#if OPTIMISTIC_IO
2145 mayAcceptMore = true; // even if we failed to accept last time
2146#endif
2147
2148 if (mayAcceptMore)
2149 acceptNext();
2150 else
2151 commSetSelect(fd, COMM_SELECT_READ, comm_accept_try, NULL, 0);
2152}
2153
2154bool
2155AcceptFD::acceptOne() {
c99de607 2156 // If there is no callback and we accept, we will leak the accepted FD.
2157 // When we are running out of FDs, there is often no callback.
b0469965 2158 if (!theCallback) {
2159 debugs(5, 5, "AcceptFD::acceptOne orphaned: FD " << fd);
c99de607 2160 // XXX: can we remove this and similar "just in case" calls and
2161 // either listen always or listen only when there is a callback?
2162 if (!AcceptLimiter::Instance().deferring())
2163 commSetSelect(fd, COMM_SELECT_READ, comm_accept_try, NULL, 0);
b0469965 2164 return false;
c99de607 2165 }
2166
bdd8c442 2167 /*
2168 * We don't worry about running low on FDs here. Instead,
2169 * httpAccept() will use AcceptLimiter if we reach the limit
2170 * there.
2171 */
62e76326 2172
2d8c0b1a 2173 /* Accept a new connection */
b0469965 2174 ConnectionDetail connDetails;
2175 int newfd = comm_old_accept(fd, connDetails);
62e76326 2176
2d8c0b1a 2177 /* Check for errors */
bdd8c442 2178
2d8c0b1a 2179 if (newfd < 0) {
b0469965 2180 assert(theCallback != NULL);
2181
2d8c0b1a 2182 if (newfd == COMM_NOMESSAGE) {
2183 /* register interest again */
b0469965 2184 debugs(5, 5, "AcceptFD::acceptOne eof: FD " << fd <<
2185 " handler: " << *theCallback);
2d8c0b1a 2186 commSetSelect(fd, COMM_SELECT_READ, comm_accept_try, NULL, 0);
b0469965 2187 return false;
62e76326 2188 }
2189
b0469965 2190 // A non-recoverable error; notify the caller */
2191 notify(-1, COMM_ERROR, errno, connDetails);
2192 return false;
2d8c0b1a 2193 }
62e76326 2194
b0469965 2195 assert(theCallback != NULL);
2196 debugs(5, 5, "AcceptFD::acceptOne accepted: FD " << fd <<
2197 " newfd: " << newfd << " from: " << connDetails.peer <<
2198 " handler: " << *theCallback);
2199 notify(newfd, COMM_OK, 0, connDetails);
2200 return true;
2d8c0b1a 2201}
62e76326 2202
2d8c0b1a 2203void
b0469965 2204AcceptFD::acceptNext() {
2205 mayAcceptMore = acceptOne();
2d8c0b1a 2206}
62e76326 2207
b0469965 2208void
2209AcceptFD::notify(int newfd, comm_err_t errcode, int xerrno, const ConnectionDetail &connDetails)
2210{
2211 if (theCallback != NULL) {
2212 typedef CommAcceptCbParams Params;
2213 Params &params = GetCommParams<Params>(theCallback);
2214 params.fd = fd;
2215 params.nfd = newfd;
2216 params.details = connDetails;
2217 params.flag = errcode;
2218 params.xerrno = xerrno;
2219 ScheduleCallHere(theCallback);
2220 theCallback = NULL;
2221 }
c4b7a5a9 2222}
2223
2d8c0b1a 2224/*
2225 * This callback is called whenever a filedescriptor is ready
2226 * to dupe itself and fob off an accept()ed connection
2227 */
2228static void
b0469965 2229comm_accept_try(int fd, void *) {
2230 assert(isOpen(fd));
2231 fdc_table[fd].acceptNext();
c4b7a5a9 2232}
6cce2334 2233
a50bfe93 2234void CommIO::Initialise() {
6cce2334 2235 /* Initialize done pipe signal */
2236 int DonePipe[2];
2237 pipe(DonePipe);
2238 DoneFD = DonePipe[1];
2239 DoneReadFD = DonePipe[0];
d06925a4 2240 fd_open(DoneReadFD, FD_PIPE, "async-io completetion event: main");
2241 fd_open(DoneFD, FD_PIPE, "async-io completetion event: threads");
2242 commSetNonBlocking(DoneReadFD);
2243 commSetNonBlocking(DoneFD);
2244 commSetSelect(DoneReadFD, COMM_SELECT_READ, NULLFDHandler, NULL, 0);
6cce2334 2245 Initialised = true;
2246}
2247
d06925a4 2248void CommIO::NotifyIOClose() {
2249 /* Close done pipe signal */
2250 FlushPipe();
2251 close(DoneFD);
2252 close(DoneReadFD);
2253 fd_close(DoneFD);
2254 fd_close(DoneReadFD);
2255 Initialised = false;
2256}
2257
6cce2334 2258bool CommIO::Initialised = false;
2259bool CommIO::DoneSignalled = false;
2260int CommIO::DoneFD = -1;
2261int CommIO::DoneReadFD = -1;
2262
2263void
a50bfe93 2264CommIO::FlushPipe() {
6cce2334 2265 char buf[256];
56410c89 2266 FD_READ_METHOD(DoneReadFD, buf, sizeof(buf));
6cce2334 2267}
2268
2269void
a50bfe93 2270CommIO::NULLFDHandler(int fd, void *data) {
6cce2334 2271 FlushPipe();
2272 commSetSelect(fd, COMM_SELECT_READ, NULLFDHandler, NULL, 0);
2273}
2274
2275void
a50bfe93 2276CommIO::ResetNotifications() {
6cce2334 2277 if (DoneSignalled) {
62e76326 2278 FlushPipe();
2279 DoneSignalled = false;
6cce2334 2280 }
2281}
a46d2c0e 2282
2283AcceptLimiter AcceptLimiter::Instance_;
2284
a50bfe93 2285AcceptLimiter &AcceptLimiter::Instance() {
a46d2c0e 2286 return Instance_;
2287}
2288
c99de607 2289bool
2290AcceptLimiter::deferring() const {
2291 return deferred.size() > 0;
2292}
2293
a46d2c0e 2294void
a50bfe93 2295AcceptLimiter::defer (int fd, Acceptor::AcceptorFunction *aFunc, void *data) {
bf8fe701 2296 debugs(5, 5, "AcceptLimiter::defer: FD " << fd << " handler: " << (void*)aFunc);
a46d2c0e 2297 Acceptor temp;
2298 temp.theFunction = aFunc;
2299 temp.acceptFD = fd;
2300 temp.theData = data;
2301 deferred.push_back(temp);
2302}
2303
2304void
a50bfe93 2305AcceptLimiter::kick() {
c99de607 2306 if (!deferring())
a46d2c0e 2307 return;
2308
2309 /* Yes, this means the first on is the last off....
2310 * If the list container was a little more friendly, we could sensibly us it.
2311 */
2312 Acceptor temp = deferred.pop_back();
2313
2314 comm_accept (temp.acceptFD, temp.theFunction, temp.theData);
2315}
2316
2317void
a50bfe93 2318commMarkHalfClosed(int fd) {
b0469965 2319 assert (isOpen(fd));
a46d2c0e 2320 AbortChecker::Instance().monitor(fd);
a46d2c0e 2321}
2322
f900210a 2323int commIsHalfClosed(int fd) {
b0469965 2324 assert (isOpen(fd));
f900210a 2325
b0469965 2326 return AbortChecker::Instance().isMonitoring(fd);
f900210a 2327}
2328
2329void
2330commCheckHalfClosed(void *data) {
2331 AbortChecker::Instance().doIOLoop();
2332 eventAdd("commCheckHalfClosed", commCheckHalfClosed, NULL, 1.0, false);
2333}
2334
a46d2c0e 2335AbortChecker &AbortChecker::Instance() {return Instance_;}
2336
2337AbortChecker AbortChecker::Instance_;
2338
2339void
a50bfe93 2340AbortChecker::AbortCheckReader(int fd, char *, size_t size, comm_err_t flag, int xerrno, void *data) {
a46d2c0e 2341 assert (size == 0);
2342 /* sketch:
2343 * if the read is ok and 0, the conn is still open.
2344 * if the read is a fail, close the conn
2345 */
2346
2347 if (flag != COMM_OK && flag != COMM_ERR_CLOSING) {
bf8fe701 2348 debugs(5, 3, "AbortChecker::AbortCheckReader: FD " << fd << " aborted");
a46d2c0e 2349 comm_close(fd);
2350 }
2351}
2352
2353void
a50bfe93 2354AbortChecker::monitor(int fd) {
a46d2c0e 2355 assert (!contains(fd));
2356
2357 add
2358 (fd);
2359
bf8fe701 2360 debugs(5, 3, "AbortChecker::monitor: monitoring half closed FD " << fd << " for aborts");
a46d2c0e 2361}
2362
2363void
a50bfe93 2364AbortChecker::stopMonitoring (int fd) {
a46d2c0e 2365 assert (contains (fd));
2366
2367 remove
2368 (fd);
2369
bf8fe701 2370 debugs(5, 3, "AbortChecker::stopMonitoring: stopped monitoring half closed FD " << fd << " for aborts");
a46d2c0e 2371}
2372
2373#include "splay.h"
2374void
a50bfe93 2375AbortChecker::doIOLoop() {
f900210a 2376 fds->walk(RemoveCheck, this);
a46d2c0e 2377 fds->walk(AddCheck, this);
a46d2c0e 2378}
2379
2380void
a50bfe93 2381AbortChecker::AddCheck (int const &fd, void *data) {
a46d2c0e 2382 AbortChecker *me = (AbortChecker *)data;
2383 me->addCheck(fd);
2384}
2385
2386void
a50bfe93 2387AbortChecker::RemoveCheck (int const &fd, void *data) {
a46d2c0e 2388 AbortChecker *me = (AbortChecker *)data;
2389 me->removeCheck(fd);
2390}
2391
2392
2393int
a50bfe93 2394AbortChecker::IntCompare (int const &lhs, int const &rhs) {
a46d2c0e 2395 return lhs - rhs;
2396}
2397
b0469965 2398bool
2399AbortChecker::isMonitoring(int fd) const {
2400 return contains(fd);
2401}
2402
a46d2c0e 2403bool
a50bfe93 2404AbortChecker::contains (int const fd) const {
a46d2c0e 2405 fds = fds->splay(fd, IntCompare);
2406
2407 if (splayLastResult != 0)
2408 return false;
2409
2410 return true;
2411}
2412
2413void
2414
2415AbortChecker::remove
a50bfe93 2416 (int const fd) {
a46d2c0e 2417
2418 fds = fds->remove
2419 (fd, IntCompare);
2420}
2421
2422void
2423
2424AbortChecker::add
a50bfe93 2425 (int const fd) {
a46d2c0e 2426 fds = fds->insert (fd, IntCompare);
2427}
2428
2429void
a50bfe93 2430AbortChecker::addCheck (int const fd) {
a46d2c0e 2431 /* assert comm_is_open (fd); */
2432 comm_read(fd, NULL, 0, AbortCheckReader, NULL);
2433}
2434
2435void
a50bfe93 2436AbortChecker::removeCheck (int const fd) {
a46d2c0e 2437 /*
2438 comm_read_cancel(fd, AbortCheckReader, NULL);
2439 */
2440}
2441
b0469965 2442CommRead::CommRead() : fd(-1), buf(NULL), len(0), callback(NULL) {}
a46d2c0e 2443
b0469965 2444CommRead::CommRead(int fd_, char *buf_, int len_, AsyncCall::Pointer &callback_)
2445 : fd(fd_), buf(buf_), len(len_), callback(callback_) {}
a46d2c0e 2446
a50bfe93 2447DeferredRead::DeferredRead () : theReader(NULL), theContext(NULL), theRead(), cancelled(false) {}
a46d2c0e 2448
a50bfe93 2449DeferredRead::DeferredRead (DeferrableRead *aReader, void *data, CommRead const &aRead) : theReader(aReader), theContext (data), theRead(aRead), cancelled(false) {}
a46d2c0e 2450
a50bfe93 2451DeferredReadManager::~DeferredReadManager() {
a46d2c0e 2452 flushReads();
2453 assert (deferredReads.empty());
2454}
2455
97427e90 2456/* explicit instantiation required for some systems */
2457
63be0a78 2458/// \cond AUTODOCS-IGNORE
2459template cbdata_type List<DeferredRead>::CBDATA_List;
2460/// \endcond
97427e90 2461
a46d2c0e 2462void
a50bfe93 2463DeferredReadManager::delayRead(DeferredRead const &aRead) {
bf8fe701 2464 debugs(5, 3, "Adding deferred read on FD " << aRead.theRead.fd);
a46d2c0e 2465 List<DeferredRead> *temp = deferredReads.push_back(aRead);
2466 comm_add_close_handler (aRead.theRead.fd, CloseHandler, temp);
2467}
2468
2469void
a50bfe93 2470DeferredReadManager::CloseHandler(int fd, void *thecbdata) {
a46d2c0e 2471 if (!cbdataReferenceValid (thecbdata))
2472 return;
2473
2474 List<DeferredRead> *temp = (List<DeferredRead> *)thecbdata;
2475
2476 temp->element.markCancelled();
2477}
2478
2479DeferredRead
a50bfe93 2480DeferredReadManager::popHead(ListContainer<DeferredRead> &deferredReads) {
a46d2c0e 2481 assert (!deferredReads.empty());
2482
2483 if (!deferredReads.head->element.cancelled)
2484 comm_remove_close_handler(deferredReads.head->element.theRead.fd, CloseHandler, deferredReads.head);
2485
2486 DeferredRead result = deferredReads.pop_front();
2487
2488 return result;
2489}
2490
2491void
a50bfe93 2492DeferredReadManager::kickReads(int const count) {
a46d2c0e 2493 /* if we had List::size() we could consolidate this and flushReads */
2494
33cea91c 2495 if (count < 1) {
a46d2c0e 2496 flushReads();
33cea91c 2497 return;
2498 }
a46d2c0e 2499
2500 size_t remaining = count;
2501
2502 while (!deferredReads.empty() && remaining) {
2503 DeferredRead aRead = popHead(deferredReads);
2504 kickARead(aRead);
2505
2506 if (!aRead.cancelled)
2507 --remaining;
2508 }
2509}
2510
2511void
a50bfe93 2512DeferredReadManager::flushReads() {
a46d2c0e 2513 ListContainer<DeferredRead> reads;
2514 reads = deferredReads;
2515 deferredReads = ListContainer<DeferredRead>();
2516
2517 while (!reads.empty()) {
2518 DeferredRead aRead = popHead(reads);
2519 kickARead(aRead);
2520 }
2521}
2522
2523void
a50bfe93 2524DeferredReadManager::kickARead(DeferredRead const &aRead) {
a46d2c0e 2525 if (aRead.cancelled)
2526 return;
2527
bf8fe701 2528 debugs(5, 3, "Kicking deferred read on FD " << aRead.theRead.fd);
a46d2c0e 2529
2530 aRead.theReader(aRead.theContext, aRead.theRead);
2531}
2532
2533void
a50bfe93 2534DeferredRead::markCancelled() {
a46d2c0e 2535 cancelled = true;
2536}
2d8c0b1a 2537
cc192b50 2538ConnectionDetail::ConnectionDetail() : me(), peer() {
2d8c0b1a 2539}
8ff3fa2e 2540
8ff3fa2e 2541int
2542CommSelectEngine::checkEvents(int timeout) {
fa3f745b 2543 static time_t last_timeout = 0;
2544
2545 /* No, this shouldn't be here. But it shouldn't be in each comm handler. -adrian */
2546 if (squid_curtime > last_timeout) {
2547 last_timeout = squid_curtime;
2548 checkTimeouts();
2549 }
2550
8ff3fa2e 2551 switch (comm_select(timeout)) {
2552
2553 case COMM_OK:
2554
2555 case COMM_TIMEOUT:
2556 return 0;
2557
2558 case COMM_IDLE:
2559
2560 case COMM_SHUTDOWN:
2561 return EVENT_IDLE;
2562
2563 case COMM_ERROR:
2564 return EVENT_ERROR;
2565
2566 default:
2567 fatal_dump("comm.cc: Internal error -- this should never happen.");
2568 return EVENT_ERROR;
2569 };
2570}