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