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