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