]> git.ipfire.org Git - thirdparty/squid.git/blame - src/comm.cc
Fix SQUID_YESNO 'syntax error near unexpected token' (#2117)
[thirdparty/squid.git] / src / comm.cc
CommitLineData
30a4f2a8 1/*
1f7b830e 2 * Copyright (C) 1996-2025 The Squid Software Foundation and contributors
30a4f2a8 3 *
bbc27441
AJ
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
30a4f2a8 7 */
090089c4 8
bbc27441
AJ
9/* DEBUG: section 05 Socket Functions */
10
582c2af2 11#include "squid.h"
2949dd02 12#include "base/AsyncFunCalls.h"
a2ddc0b7 13#include "base/OnOff.h"
582c2af2 14#include "ClientInfo.h"
04f55905
AJ
15#include "comm/AcceptLimiter.h"
16#include "comm/comm_internal.h"
cfd66529 17#include "comm/Connection.h"
ec41b64c 18#include "comm/IoCallback.h"
d841c88d 19#include "comm/Loops.h"
7e66d5e2 20#include "comm/Read.h"
cbff89ba 21#include "comm/TcpAcceptor.h"
602d9612 22#include "comm/Write.h"
582c2af2 23#include "compat/cmsg.h"
74257126 24#include "DescriptorSet.h"
582c2af2 25#include "event.h"
c4ad1349 26#include "fd.h"
582c2af2
FC
27#include "fde.h"
28#include "globals.h"
9b5c4a9a 29#include "icmp/net_db.h"
96d89ea0 30#include "ip/Intercept.h"
425de4c8 31#include "ip/QosConfig.h"
055421ee 32#include "ip/tools.h"
582c2af2 33#include "pconn.h"
65e41a45 34#include "sbuf/SBuf.h"
7d17a6a6 35#include "sbuf/Stream.h"
4d5904f7 36#include "SquidConfig.h"
e4f1fdae 37#include "StatCounters.h"
582c2af2 38#include "StoreIOBuffer.h"
1125ea7b
MM
39#include "tools.h"
40
cb4f4424 41#if USE_OPENSSL
4db984be
CT
42#include "ssl/support.h"
43#endif
090089c4 44
074d6a40
AJ
45#include <cerrno>
46#include <cmath>
be266cb2 47#if _SQUID_CYGWIN_
b671cc68 48#include <sys/ioctl.h>
49#endif
30a4f2a8 50#ifdef HAVE_NETINET_TCP_H
51#include <netinet/tcp.h>
52#endif
582c2af2
FC
53#if HAVE_SYS_UN_H
54#include <sys/un.h>
55#endif
090089c4 56
2b663917 57/*
58 * New C-like simple comm code. This stuff is a mess and doesn't really buy us anything.
59 */
60
82ec8dfc 61static IOCB commHalfClosedReader;
74d7d196 62static int comm_openex(int sock_type, int proto, Ip::Address &, int flags, const char *note);
c6f168c1 63static void comm_init_opened(const Comm::ConnectionPointer &conn, const char *note, struct addrinfo *AI);
a67d2b2e 64static int comm_apply_flags(int new_socket, Ip::Address &addr, int flags, struct addrinfo *AI);
82ec8dfc 65
9a0a18de 66#if USE_DELAY_POOLS
b4cd430a
CT
67CBDATA_CLASS_INIT(CommQuotaQueue);
68
69static void commHandleWriteHelper(void * data);
70#endif
71
090089c4 72/* STATIC */
62e76326 73
aee3523a 74static DescriptorSet *TheHalfClosed = nullptr; /// the set of half-closed FDs
74257126
AR
75static bool WillCheckHalfClosed = false; /// true if check is scheduled
76static EVH commHalfClosedCheck;
77static void commPlanHalfClosedCheck();
78
c8407295 79static Comm::Flag commBind(int s, struct addrinfo &);
74d7d196 80static void commSetBindAddressNoPort(int);
f5b8bbc4 81static void commSetReuseAddr(int);
a2ddc0b7 82static void commConfigureLinger(int fd, OnOff);
30a4f2a8 83#ifdef TCP_NODELAY
f5b8bbc4 84static void commSetTcpNoDelay(int);
30a4f2a8 85#endif
f5b8bbc4 86static void commSetTcpRcvbuf(int, int);
723123a9 87
04f55905 88bool
b0469965 89isOpen(const int fd)
b300c36d 90{
9a5ac93d 91 return fd >= 0 && fd_table && fd_table[fd].flags.open != 0;
b300c36d 92}
93
e1a88700 94/**
c4b7a5a9 95 * Empty the read buffers
96 *
97 * This is a magical routine that empties the read buffers.
98 * Under some platforms (Linux) if a buffer has data in it before
99 * you call close(), the socket will hang and take quite a while
100 * to timeout.
101 */
102static void
103comm_empty_os_read_buffers(int fd)
104{
1191b93b 105#if _SQUID_LINUX_
b41a5a1b
AJ
106#if USE_OPENSSL
107 // Bug 4146: SSL-Bump BIO does not release sockets on close.
108 if (fd_table[fd].ssl)
109 return;
110#endif
111
c4b7a5a9 112 /* prevent those nasty RST packets */
113 char buf[SQUID_TCP_SO_RCVBUF];
e3c37fc2 114 if (fd_table[fd].flags.nonblocking && fd_table[fd].type != FD_MSGHDR) {
cc192b50 115 while (FD_READ_METHOD(fd, buf, SQUID_TCP_SO_RCVBUF) > 0) {};
116 }
2081cefa
FC
117#else
118 (void)fd;
c4b7a5a9 119#endif
120}
121
e1a88700 122/**
ce767c23 123 * synchronous wrapper around udp socket functions
124 */
ce767c23 125int
b7ac5457 126comm_udp_recvfrom(int fd, void *buf, size_t len, int flags, Ip::Address &from)
ce767c23 127{
95dc7ff4 128 ++ statCounter.syscalls.sock.recvfroms;
cc192b50 129 debugs(5,8, "comm_udp_recvfrom: FD " << fd << " from " << from);
aee3523a 130 struct addrinfo *AI = nullptr;
851614a8 131 Ip::Address::InitAddr(AI);
4dd643d5 132 int x = recvfrom(fd, buf, len, flags, AI->ai_addr, &AI->ai_addrlen);
cc192b50 133 from = *AI;
851614a8 134 Ip::Address::FreeAddr(AI);
cc192b50 135 return x;
ce767c23 136}
137
365f12a9 138int
7d21986b 139comm_udp_recv(int fd, void *buf, size_t len, int flags)
365f12a9 140{
b7ac5457 141 Ip::Address nul;
cc192b50 142 return comm_udp_recvfrom(fd, buf, len, flags, nul);
365f12a9 143}
144
f71da12c 145ssize_t
7d21986b 146comm_udp_send(int s, const void *buf, size_t len, int flags)
f71da12c 147{
62e76326 148 return send(s, buf, len, flags);
f71da12c 149}
ce767c23 150
545d554b 151bool
152comm_has_incomplete_write(int fd)
153{
aee3523a 154 assert(isOpen(fd) && COMMIO_FD_WRITECB(fd) != nullptr);
b0469965 155 return COMMIO_FD_WRITECB(fd)->active();
d4cb310b 156}
157
e1a88700 158/**
cf3c0ee3 159 * Queue a write. handler/handler_data are called when the write fully
160 * completes, on error, or on file descriptor close.
161 */
9864ee44 162
090089c4 163/* Return the local port associated with fd. */
f45dd259 164unsigned short
b8d8561b 165comm_local_port(int fd)
090089c4 166{
b7ac5457 167 Ip::Address temp;
aee3523a 168 struct addrinfo *addr = nullptr;
76f87348 169 fde *F = &fd_table[fd];
090089c4 170
090089c4 171 /* If the fd is closed already, just return */
62e76326 172
60c0b5a2 173 if (!F->flags.open) {
bf8fe701 174 debugs(5, 0, "comm_local_port: FD " << fd << " has been closed.");
62e76326 175 return 0;
090089c4 176 }
62e76326 177
4dd643d5
AJ
178 if (F->local_addr.port())
179 return F->local_addr.port();
62e76326 180
6084c0b6 181 if (F->sock_family == AF_INET)
4dd643d5 182 temp.setIPv4();
6084c0b6 183
851614a8 184 Ip::Address::InitAddr(addr);
62e76326 185
cc192b50 186 if (getsockname(fd, addr->ai_addr, &(addr->ai_addrlen)) ) {
b69e9ffa 187 int xerrno = errno;
d816f28d 188 debugs(50, DBG_IMPORTANT, "ERROR: " << MYNAME << "Failed to retrieve TCP/UDP port number for socket: FD " << fd << ": " << xstrerr(xerrno));
851614a8 189 Ip::Address::FreeAddr(addr);
62e76326 190 return 0;
090089c4 191 }
cc192b50 192 temp = *addr;
193
851614a8 194 Ip::Address::FreeAddr(addr);
cc192b50 195
4dd643d5 196 if (F->local_addr.isAnyAddr()) {
3d031c35
AJ
197 /* save the whole local address, not just the port. */
198 F->local_addr = temp;
199 } else {
4dd643d5 200 F->local_addr.port(temp.port());
3d031c35 201 }
62e76326 202
4dd643d5
AJ
203 debugs(5, 6, "comm_local_port: FD " << fd << ": port " << F->local_addr.port() << "(family=" << F->sock_family << ")");
204 return F->local_addr.port();
090089c4 205}
206
74d7d196 207/// sets the IP_BIND_ADDRESS_NO_PORT socket option to optimize ephemeral port
208/// reuse by outgoing TCP connections that must bind(2) to a source IP address
209static void
210commSetBindAddressNoPort(const int fd)
211{
212#if defined(IP_BIND_ADDRESS_NO_PORT)
213 int flag = 1;
214 if (setsockopt(fd, IPPROTO_IP, IP_BIND_ADDRESS_NO_PORT, reinterpret_cast<char*>(&flag), sizeof(flag)) < 0) {
215 const auto savedErrno = errno;
216 debugs(50, DBG_IMPORTANT, "ERROR: setsockopt(IP_BIND_ADDRESS_NO_PORT) failure: " << xstrerr(savedErrno));
217 }
218#else
219 (void)fd;
220#endif
221}
222
c8407295 223static Comm::Flag
cc192b50 224commBind(int s, struct addrinfo &inaddr)
090089c4 225{
95dc7ff4 226 ++ statCounter.syscalls.sock.binds;
62e76326 227
ac760b5e 228 if (bind(s, inaddr.ai_addr, inaddr.ai_addrlen) == 0) {
b69e9ffa 229 debugs(50, 6, "bind socket FD " << s << " to " << fd_table[s].local_addr);
c8407295 230 return Comm::OK;
ac760b5e 231 }
b69e9ffa 232 int xerrno = errno;
d816f28d 233 debugs(50, DBG_CRITICAL, "ERROR: " << MYNAME << "Cannot bind socket FD " << s << " to " << fd_table[s].local_addr << ": " << xstrerr(xerrno));
62e76326 234
4ee57cbe 235 return Comm::COMM_ERROR;
090089c4 236}
237
e1a88700 238/**
239 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
240 * is OR of flags specified in comm.h. Defaults TOS
241 */
b8d8561b 242int
16b204c4 243comm_open(int sock_type,
62e76326 244 int proto,
b7ac5457 245 Ip::Address &addr,
62e76326 246 int flags,
247 const char *note)
d6827718 248{
74d7d196 249 // assume zero-port callers do not need to know the assigned port right away
250 if (sock_type == SOCK_STREAM && addr.port() == 0 && ((flags & COMM_DOBIND) || !addr.isAnyAddr()))
251 flags |= COMM_DOBIND_PORT_LATER;
252
c6f168c1 253 return comm_openex(sock_type, proto, addr, flags, note);
d6827718 254}
255
e0d28505
AJ
256void
257comm_open_listener(int sock_type,
258 int proto,
e02ed2e3 259 Comm::ConnectionPointer &conn,
e0d28505
AJ
260 const char *note)
261{
262 /* all listener sockets require bind() */
263 conn->flags |= COMM_DOBIND;
264
265 /* attempt native enabled port. */
c6f168c1 266 conn->fd = comm_openex(sock_type, proto, conn->local, conn->flags, note);
e0d28505
AJ
267}
268
31be869c
AJ
269int
270comm_open_listener(int sock_type,
04f7fd38 271 int proto,
b7ac5457 272 Ip::Address &addr,
04f7fd38
AJ
273 int flags,
274 const char *note)
31be869c 275{
e02ed2e3
AJ
276 int sock = -1;
277
ac760b5e
AJ
278 /* all listener sockets require bind() */
279 flags |= COMM_DOBIND;
280
e02ed2e3 281 /* attempt native enabled port. */
c6f168c1 282 sock = comm_openex(sock_type, proto, addr, flags, note);
e02ed2e3 283
31be869c
AJ
284 return sock;
285}
286
2d8c0b1a 287static bool
288limitError(int const anErrno)
289{
290 return anErrno == ENFILE || anErrno == EMFILE;
291}
d6827718 292
8b082ed9 293static void
cc192b50 294comm_set_v6only(int fd, int tos)
295{
296#ifdef IPV6_V6ONLY
297 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &tos, sizeof(int)) < 0) {
b69e9ffa
AJ
298 int xerrno = errno;
299 debugs(50, DBG_IMPORTANT, MYNAME << "setsockopt(IPV6_V6ONLY) " << (tos?"ON":"OFF") << " for FD " << fd << ": " << xstrerr(xerrno));
cc192b50 300 }
301#else
b69e9ffa 302 debugs(50, DBG_CRITICAL, MYNAME << "WARNING: setsockopt(IPV6_V6ONLY) not supported on this platform");
cc192b50 303#endif /* sockopt */
304}
057f5854 305
40d6264d 306/**
b2192042
AJ
307 * Set the socket option required for TPROXY spoofing for:
308 * - Linux TPROXY v4 support,
309 * - OpenBSD divert-to support,
310 * - FreeBSD IPFW TPROXY v4 support.
40d6264d 311 */
8b082ed9 312static void
e950e673 313comm_set_transparent(int fd)
f1e0717c 314{
b2192042
AJ
315#if _SQUID_LINUX_ && defined(IP_TRANSPARENT) // Linux
316# define soLevel SOL_IP
317# define soFlag IP_TRANSPARENT
d0e6f578 318 bool doneSuid = false;
b2192042
AJ
319
320#elif defined(SO_BINDANY) // OpenBSD 4.7+ and NetBSD with PF
321# define soLevel SOL_SOCKET
322# define soFlag SO_BINDANY
323 enter_suid();
d0e6f578 324 bool doneSuid = true;
1125ea7b 325
b2192042
AJ
326#elif defined(IP_BINDANY) // FreeBSD with IPFW
327# define soLevel IPPROTO_IP
328# define soFlag IP_BINDANY
1125ea7b 329 enter_suid();
d0e6f578 330 bool doneSuid = true;
b2192042
AJ
331
332#else
333 debugs(50, DBG_CRITICAL, "WARNING: comm_open: setsockopt(TPROXY) not supported on this platform");
c46e7feb 334 (void)fd;
b2192042
AJ
335#endif /* sockopt */
336
337#if defined(soLevel) && defined(soFlag)
338 int tos = 1;
339 if (setsockopt(fd, soLevel, soFlag, (char *) &tos, sizeof(int)) < 0) {
b69e9ffa
AJ
340 int xerrno = errno;
341 debugs(50, DBG_IMPORTANT, MYNAME << "setsockopt(TPROXY) on FD " << fd << ": " << xstrerr(xerrno));
1125ea7b
MM
342 } else {
343 /* mark the socket as having transparent options */
344 fd_table[fd].flags.transparent = true;
345 }
b2192042
AJ
346 if (doneSuid)
347 leave_suid();
348#endif
f1e0717c
AJ
349}
350
e1a88700 351/**
352 * Create a socket. Default is blocking, stream (TCP) socket. IO_TYPE
353 * is OR of flags specified in defines.h:COMM_*
354 */
74d7d196 355static int
d6827718 356comm_openex(int sock_type,
62e76326 357 int proto,
e02ed2e3 358 Ip::Address &addr,
62e76326 359 int flags,
62e76326 360 const char *note)
090089c4 361{
e02ed2e3 362 int new_socket;
aee3523a 363 struct addrinfo *AI = nullptr;
090089c4 364
365 /* Create socket for accepting new connections. */
95dc7ff4 366 ++ statCounter.syscalls.sock.sockets;
62e76326 367
97bbba61
AR
368 if (!Ip::EnableIpv6 && addr.isIPv6()) {
369 debugs(50, 2, "refusing to open an IPv6 socket when IPv6 support is disabled: " << addr);
370 errno = ENOTSUP;
371 return -1;
372 }
373
cc192b50 374 /* Setup the socket addrinfo details for use */
e02ed2e3 375 addr.getAddrInfo(AI);
cc192b50 376 AI->ai_socktype = sock_type;
377 AI->ai_protocol = proto;
cc192b50 378
e02ed2e3 379 debugs(50, 3, "comm_openex: Attempt open socket for: " << addr );
cc192b50 380
e02ed2e3 381 new_socket = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
c3d6a21b 382 const auto firstErrNo = errno;
055421ee 383
0eb08770
HN
384 /* under IPv6 there is the possibility IPv6 is present but disabled. */
385 /* try again as IPv4-native if possible */
e02ed2e3 386 if ( new_socket < 0 && Ip::EnableIpv6 && addr.isIPv6() && addr.setIPv4() ) {
0eb08770 387 /* attempt to open this IPv4-only. */
851614a8 388 Ip::Address::FreeAddr(AI);
0eb08770 389 /* Setup the socket addrinfo details for use */
e02ed2e3 390 addr.getAddrInfo(AI);
0eb08770
HN
391 AI->ai_socktype = sock_type;
392 AI->ai_protocol = proto;
b69e9ffa 393 debugs(50, 3, "Attempt fallback open socket for: " << addr );
e02ed2e3 394 new_socket = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
c3d6a21b
AR
395 // TODO: Report failures of this second socket() call.
396 // if both socket() calls fail, we use firstErrNo
b69e9ffa 397 debugs(50, 2, "attempt open " << note << " socket on: " << addr);
0eb08770 398 }
0eb08770 399
e02ed2e3 400 if (new_socket < 0) {
62e76326 401 /* Increase the number of reserved fd's if calls to socket()
402 * are failing because the open file table is full. This
403 * limits the number of simultaneous clients */
404
c3d6a21b
AR
405 if (limitError(firstErrNo)) {
406 debugs(50, DBG_IMPORTANT, MYNAME << "socket failure: " << xstrerr(firstErrNo));
62e76326 407 fdAdjustReserved();
2d8c0b1a 408 } else {
c3d6a21b 409 debugs(50, DBG_CRITICAL, MYNAME << "socket failure: " << xstrerr(firstErrNo));
62e76326 410 }
411
851614a8 412 Ip::Address::FreeAddr(AI);
cc192b50 413
c3d6a21b 414 errno = firstErrNo; // restore for caller
62e76326 415 return -1;
090089c4 416 }
62e76326 417
e02ed2e3
AJ
418 // XXX: temporary for the transition. comm_openex will eventually have a conn to play with.
419 Comm::ConnectionPointer conn = new Comm::Connection;
420 conn->local = addr;
421 conn->fd = new_socket;
422
423 debugs(50, 3, "comm_openex: Opened socket " << conn << " : family=" << AI->ai_family << ", type=" << AI->ai_socktype << ", protocol=" << AI->ai_protocol );
cc192b50 424
e02ed2e3 425 if ( Ip::EnableIpv6&IPV6_SPECIAL_SPLITSTACK && addr.isIPv6() )
b5523edc 426 comm_set_v6only(conn->fd, 1);
62e76326 427
cc192b50 428 /* Windows Vista supports Dual-Sockets. BUT defaults them to V6ONLY. Turn it OFF. */
9b1f7ee8 429 /* Other OS may have this administratively disabled for general use. Same deal. */
e02ed2e3 430 if ( Ip::EnableIpv6&IPV6_SPECIAL_V4MAPPING && addr.isIPv6() )
b5523edc 431 comm_set_v6only(conn->fd, 0);
cc192b50 432
c6f168c1 433 comm_init_opened(conn, note, AI);
e02ed2e3 434 new_socket = comm_apply_flags(conn->fd, addr, flags, AI);
38344a8e 435
851614a8 436 Ip::Address::FreeAddr(AI);
38344a8e 437
e02ed2e3
AJ
438 // XXX transition only. prevent conn from closing the new FD on function exit.
439 conn->fd = -1;
c3d6a21b
AR
440 // XXX: firstErrNo is not applicable here -- socket() calls succeeded above!
441 // TODO: Stop reporting error codes via errno.
442 errno = firstErrNo;
e02ed2e3 443 return new_socket;
38344a8e
AR
444}
445
446/// update FD tables after a local or remote (IPC) comm_openex();
447void
e0d28505 448comm_init_opened(const Comm::ConnectionPointer &conn,
5667a628
AR
449 const char *note,
450 struct addrinfo *AI)
38344a8e 451{
e0d28505 452 assert(Comm::IsConnOpen(conn));
38344a8e
AR
453 assert(AI);
454
090089c4 455 /* update fdstat */
bf95c10a 456 debugs(5, 5, conn << " is a new socket");
62e76326 457
e0d28505
AJ
458 assert(!isOpen(conn->fd)); // NP: global isOpen checks the fde entry for openness not the Comm::Connection
459 fd_open(conn->fd, FD_SOCKET, note);
62e76326 460
e0d28505
AJ
461 fde *F = &fd_table[conn->fd];
462 F->local_addr = conn->local;
cc192b50 463
464 F->sock_family = AI->ai_family;
38344a8e
AR
465}
466
467/// apply flags after a local comm_open*() call;
468/// returns new_socket or -1 on error
469static int
470comm_apply_flags(int new_socket,
a67d2b2e 471 Ip::Address &addr,
5667a628
AR
472 int flags,
473 struct addrinfo *AI)
38344a8e
AR
474{
475 assert(new_socket >= 0);
476 assert(AI);
477 const int sock_type = AI->ai_socktype;
62e76326 478
79a15e0a 479 if (!(flags & COMM_NOCLOEXEC))
62e76326 480 commSetCloseOnExec(new_socket);
481
cdc33f35 482 if ((flags & COMM_REUSEADDR))
62e76326 483 commSetReuseAddr(new_socket);
484
4dd643d5 485 if (addr.port() > (unsigned short) 0) {
7aa9bb3e 486#if _SQUID_WINDOWS_
a50bfe93 487 if (sock_type != SOCK_DGRAM)
488#endif
a2ddc0b7 489 commConfigureLinger(new_socket, OnOff::off);
62e76326 490
491 if (opt_reuseaddr)
492 commSetReuseAddr(new_socket);
090089c4 493 }
62e76326 494
a35595cd 495 /* MUST be done before binding or face OS Error: "(99) Cannot assign requested address"... */
9e008dda 496 if ((flags & COMM_TRANSPARENT)) {
a35595cd
AJ
497 comm_set_transparent(new_socket);
498 }
a35595cd 499
4dd643d5
AJ
500 if ( (flags & COMM_DOBIND) || addr.port() > 0 || !addr.isAnyAddr() ) {
501 if ( !(flags & COMM_DOBIND) && addr.isAnyAddr() )
e0236918 502 debugs(5, DBG_IMPORTANT,"WARNING: Squid is attempting to bind() port " << addr << " without being a listener.");
4dd643d5 503 if ( addr.isNoAddr() )
d816f28d 504 debugs(5, DBG_CRITICAL, "ERROR: Squid is attempting to bind() port " << addr << "!!");
ac760b5e 505
7d17a6a6
EB
506#if defined(SO_REUSEPORT)
507 if (flags & COMM_REUSEPORT) {
508 int on = 1;
509 if (setsockopt(new_socket, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<char*>(&on), sizeof(on)) < 0) {
510 const auto savedErrno = errno;
511 const auto errorMessage = ToSBuf("cannot enable SO_REUSEPORT socket option when binding to ",
512 addr, ": ", xstrerr(savedErrno));
513 if (reconfiguring)
514 debugs(5, DBG_IMPORTANT, "ERROR: " << errorMessage);
515 else
516 throw TexcHere(errorMessage);
517 }
518 }
519#endif
74d7d196 520
521 if ((flags & COMM_DOBIND_PORT_LATER))
522 commSetBindAddressNoPort(new_socket);
523
c8407295 524 if (commBind(new_socket, *AI) != Comm::OK) {
62e76326 525 comm_close(new_socket);
526 return -1;
62e76326 527 }
23ff6968 528 }
62e76326 529
79a15e0a 530 if (flags & COMM_NONBLOCKING)
4ee57cbe 531 if (commSetNonBlocking(new_socket) == Comm::COMM_ERROR) {
38344a8e 532 comm_close(new_socket);
62e76326 533 return -1;
62e76326 534 }
535
30a4f2a8 536#ifdef TCP_NODELAY
537 if (sock_type == SOCK_STREAM)
62e76326 538 commSetTcpNoDelay(new_socket);
539
30a4f2a8 540#endif
62e76326 541
1241e63e 542 if (Config.tcpRcvBufsz > 0 && sock_type == SOCK_STREAM)
62e76326 543 commSetTcpRcvbuf(new_socket, Config.tcpRcvBufsz);
544
090089c4 545 return new_socket;
546}
547
a4c0f9c6 548void
e0d28505 549comm_import_opened(const Comm::ConnectionPointer &conn,
5667a628
AR
550 const char *note,
551 struct addrinfo *AI)
a4c0f9c6 552{
bf95c10a 553 debugs(5, 2, conn);
e0d28505 554 assert(Comm::IsConnOpen(conn));
a4c0f9c6
AR
555 assert(AI);
556
c6f168c1 557 comm_init_opened(conn, note, AI);
a4c0f9c6 558
e0d28505 559 if ((conn->flags & COMM_TRANSPARENT))
be4d35dc 560 fd_table[conn->fd].flags.transparent = true;
a4c0f9c6 561
e0d28505 562 if (conn->flags & COMM_NONBLOCKING)
be4d35dc 563 fd_table[conn->fd].flags.nonblocking = true;
a4c0f9c6
AR
564
565#ifdef TCP_NODELAY
566 if (AI->ai_socktype == SOCK_STREAM)
be4d35dc 567 fd_table[conn->fd].flags.nodelay = true;
a4c0f9c6
AR
568#endif
569
570 /* no fd_table[fd].flags. updates needed for these conditions:
571 * if ((flags & COMM_REUSEADDR)) ...
572 * if ((flags & COMM_DOBIND) ...) ...
573 */
574}
575
933dd095
AJ
576// XXX: now that raw-FD timeouts are only unset for pipes and files this SHOULD be a no-op.
577// With handler already unset. Leaving this present until that can be verified for all code paths.
578void
579commUnsetFdTimeout(int fd)
b0469965 580{
bf95c10a 581 debugs(5, 3, "Remove timeout for FD " << fd);
b0469965 582 assert(fd >= 0);
583 assert(fd < Squid_MaxFD);
584 fde *F = &fd_table[fd];
585 assert(F->flags.open);
586
aee3523a 587 F->timeoutHandler = nullptr;
933dd095 588 F->timeout = 0;
7957e704
AJ
589}
590
9685cb72 591void
4650a4fa 592commSetConnTimeout(const Comm::ConnectionPointer &conn, time_t timeout, AsyncCall::Pointer &callback)
7957e704 593{
bf95c10a 594 debugs(5, 3, conn << " timeout " << timeout);
7957e704
AJ
595 assert(Comm::IsConnOpen(conn));
596 assert(conn->fd < Squid_MaxFD);
597 fde *F = &fd_table[conn->fd];
598 assert(F->flags.open);
599
600 if (timeout < 0) {
aee3523a 601 F->timeoutHandler = nullptr;
7957e704
AJ
602 F->timeout = 0;
603 } else {
aee3523a 604 if (callback != nullptr) {
7957e704
AJ
605 typedef CommTimeoutCbParams Params;
606 Params &params = GetCommParams<Params>(callback);
607 params.conn = conn;
608 F->timeoutHandler = callback;
609 }
b0469965 610
9685cb72 611 F->timeout = squid_curtime + timeout;
7957e704 612 }
b0469965 613}
090089c4 614
9685cb72 615void
8d77a37c
AJ
616commUnsetConnTimeout(const Comm::ConnectionPointer &conn)
617{
bf95c10a 618 debugs(5, 3, "Remove timeout for " << conn);
8d77a37c 619 AsyncCall::Pointer nil;
9685cb72 620 commSetConnTimeout(conn, -1, nil);
8d77a37c
AJ
621}
622
8630961c
AD
623/**
624 * Connect socket FD to given remote address.
625 * If return value is an error flag (COMM_ERROR, ERR_CONNECT, ERR_PROTOCOL, etc.),
626 * then error code will also be returned in errno.
627 */
b8d8561b 628int
b7ac5457 629comm_connect_addr(int sock, const Ip::Address &address)
090089c4 630{
c8407295 631 Comm::Flag status = Comm::OK;
76f87348 632 fde *F = &fd_table[sock];
cc192b50 633 int x = 0;
b5568a61 634 int err = 0;
9689d97c 635 socklen_t errlen;
aee3523a 636 struct addrinfo *AI = nullptr;
cc192b50 637
4dd643d5 638 assert(address.port() != 0);
cc192b50 639
bf95c10a 640 debugs(5, 9, "connecting socket FD " << sock << " to " << address << " (want family: " << F->sock_family << ")");
cc192b50 641
3d98ff81 642 /* Handle IPv6 over IPv4-only socket case.
4dd643d5 643 * this case must presently be handled here since the getAddrInfo asserts on bad mappings.
3d98ff81 644 * NP: because commResetFD is private to ConnStateData we have to return an error and
9d92af86
AJ
645 * trust its handled properly.
646 */
4dd643d5 647 if (F->sock_family == AF_INET && !address.isIPv4()) {
3d98ff81 648 errno = ENETUNREACH;
c8407295 649 return Comm::ERR_PROTOCOL;
3d98ff81
HN
650 }
651
652 /* Handle IPv4 over IPv6-only socket case.
653 * This case is presently handled here as it's both a known case and it's
654 * uncertain what error will be returned by the IPv6 stack in such case. It's
655 * possible this will also be handled by the errno checks below after connect()
2f8abb64 656 * but needs careful cross-platform verification, and verifying the address
3d98ff81
HN
657 * condition here is simple.
658 */
4dd643d5 659 if (!F->local_addr.isIPv4() && address.isIPv4()) {
3d98ff81 660 errno = ENETUNREACH;
c8407295 661 return Comm::ERR_PROTOCOL;
9d92af86 662 }
9d92af86 663
4dd643d5 664 address.getAddrInfo(AI, F->sock_family);
cc192b50 665
090089c4 666 /* Establish connection. */
8630961c 667 int xerrno = 0;
62e76326 668
9e008dda 669 if (!F->flags.called_connect) {
be4d35dc 670 F->flags.called_connect = true;
95dc7ff4 671 ++ statCounter.syscalls.sock.connects;
62e76326 672
07383e11
CT
673 errno = 0;
674 if ((x = connect(sock, AI->ai_addr, AI->ai_addrlen)) < 0) {
675 xerrno = errno;
676 debugs(5,5, "sock=" << sock << ", addrinfo(" <<
9e008dda
AJ
677 " flags=" << AI->ai_flags <<
678 ", family=" << AI->ai_family <<
679 ", socktype=" << AI->ai_socktype <<
680 ", protocol=" << AI->ai_protocol <<
681 ", &addr=" << AI->ai_addr <<
07383e11 682 ", addrlen=" << AI->ai_addrlen << " )");
8630961c 683 debugs(5, 9, "connect FD " << sock << ": (" << x << ") " << xstrerr(xerrno));
07383e11
CT
684 debugs(14,9, "connecting to: " << address);
685
686 } else if (x == 0) {
687 // XXX: ICAP code refuses callbacks during a pending comm_ call
688 // Async calls development will fix this.
689 x = -1;
690 xerrno = EINPROGRESS;
cc192b50 691 }
8630961c 692
9e008dda 693 } else {
8630961c 694 errno = 0;
62e76326 695 errlen = sizeof(err);
62e76326 696 x = getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &errlen);
62e76326 697 if (x == 0)
8630961c 698 xerrno = err;
62e76326 699
8a09e810 700#if _SQUID_SOLARIS_
62e76326 701 /*
702 * Solaris 2.4's socket emulation doesn't allow you
703 * to determine the error from a failed non-blocking
704 * connect and just returns EPIPE. Create a fake
705 * error message for connect. -- fenner@parc.xerox.com
706 */
8630961c
AD
707 if (x < 0 && xerrno == EPIPE)
708 xerrno = ENOTCONN;
709 else
710 xerrno = errno;
30a4f2a8 711#endif
e5f6c5c2 712 }
62e76326 713
851614a8 714 Ip::Address::FreeAddr(AI);
feca3b9a 715
8630961c
AD
716 errno = xerrno;
717 if (xerrno == 0 || xerrno == EISCONN)
c8407295 718 status = Comm::OK;
8630961c 719 else if (ignoreErrno(xerrno))
c8407295 720 status = Comm::INPROGRESS;
8630961c 721 else if (xerrno == EAFNOSUPPORT || xerrno == EINVAL)
c8407295 722 return Comm::ERR_PROTOCOL;
b5568a61 723 else
4ee57cbe 724 return Comm::COMM_ERROR;
62e76326 725
4dd643d5 726 address.toStr(F->ipaddr, MAX_IPSTRLEN);
62e76326 727
4dd643d5 728 F->remote_port = address.port(); /* remote_port is HS */
62e76326 729
c8407295 730 if (status == Comm::OK) {
e0236918 731 debugs(5, DBG_DATA, "comm_connect_addr: FD " << sock << " connected to " << address);
c8407295 732 } else if (status == Comm::INPROGRESS) {
e0236918 733 debugs(5, DBG_DATA, "comm_connect_addr: FD " << sock << " connection pending");
090089c4 734 }
62e76326 735
8630961c 736 errno = xerrno;
090089c4 737 return status;
738}
739
cb201b7e 740void
741commCallCloseHandlers(int fd)
742{
76f87348 743 fde *F = &fd_table[fd];
bf8fe701 744 debugs(5, 5, "commCallCloseHandlers: FD " << fd);
62e76326 745
aee3523a 746 while (F->closeHandler != nullptr) {
b0469965 747 AsyncCall::Pointer call = F->closeHandler;
9e008dda 748 F->closeHandler = call->Next();
aee3523a 749 call->setNext(nullptr);
9e008dda
AJ
750 // If call is not canceled schedule it for execution else ignore it
751 if (!call->canceled()) {
752 debugs(5, 5, "commCallCloseHandlers: ch->handler=" << call);
2b6b1bcb
AR
753 // XXX: Without the following code, callback fd may be -1.
754 // typedef CommCloseCbParams Params;
755 // auto &params = GetCommParams<Params>(call);
756 // params.fd = fd;
9e008dda
AJ
757 ScheduleCallHere(call);
758 }
cb201b7e 759 }
760}
761
a2ddc0b7
EB
762/// sets SO_LINGER socket(7) option
763/// \param enabled -- whether linger will be active (sets linger::l_onoff)
764static void
765commConfigureLinger(const int fd, const OnOff enabled)
766{
767 struct linger l = {};
768 l.l_onoff = (enabled == OnOff::on ? 1 : 0);
769 l.l_linger = 0; // how long to linger for, in seconds
770
6bd74111
EB
771 fd_table[fd].flags.harshClosureRequested = (l.l_onoff && !l.l_linger); // close(2) sends TCP RST if true
772
a2ddc0b7
EB
773 if (setsockopt(fd, SOL_SOCKET, SO_LINGER, reinterpret_cast<char*>(&l), sizeof(l)) < 0) {
774 const auto xerrno = errno;
775 debugs(50, DBG_CRITICAL, "ERROR: Failed to set closure behavior (SO_LINGER) for FD " << fd << ": " << xstrerr(xerrno));
776 }
777}
778
27774cee 779/**
98264874 780 * enable linger with time of 0 so that when the socket is
781 * closed, TCP generates a RESET
782 */
783void
8ace824c 784comm_reset_close(const Comm::ConnectionPointer &conn)
98264874 785{
a2ddc0b7
EB
786 if (Comm::IsConnOpen(conn)) {
787 commConfigureLinger(conn->fd, OnOff::on);
788 debugs(5, 7, conn->id);
789 conn->close();
b69e9ffa 790 }
5c336a3b
AJ
791}
792
793// Legacy close function.
794void
795old_comm_reset_close(int fd)
796{
a2ddc0b7
EB
797 if (fd >= 0) {
798 commConfigureLinger(fd, OnOff::on);
799 comm_close(fd);
b69e9ffa 800 }
98264874 801}
802
8b082ed9 803static void
2949dd02 804commStartTlsClose(const int fd)
10b06767 805{
2949dd02 806 Security::SessionSendGoodbye(fd_table[fd].ssl);
10b06767
AJ
807}
808
8b082ed9 809static void
2949dd02 810comm_close_complete(const int fd)
2d8c0b1a 811{
2949dd02 812 auto F = &fd_table[fd];
1ca8bbfb 813 F->ssl.reset();
0476ec45 814 F->dynamicTlsContext.reset();
2949dd02
EB
815 fd_close(fd); /* update fdstat */
816 close(fd);
b0469965 817
95dc7ff4 818 ++ statCounter.syscalls.sock.closes;
b0469965 819
575d05c4 820 /* When one connection closes, give accept() a chance, if need be */
ccfbe8f4 821 CodeContext::Reset(); // exit FD-specific context
04f55905 822 Comm::AcceptLimiter::Instance().kick();
2d8c0b1a 823}
c4b7a5a9 824
825/*
826 * Close the socket fd.
827 *
828 * + call write handlers with ERR_CLOSING
829 * + call read handlers with ERR_CLOSING
830 * + call closing handlers
a46d2c0e 831 *
a928fdfd
EB
832 * A deferred reader has no Comm read handler mentioned above. To stay in sync,
833 * such a reader must register a Comm closing handler.
c4b7a5a9 834 */
b8d8561b 835void
43ae1d95 836_comm_close(int fd, char const *file, int line)
090089c4 837{
4a5d9ea5 838 debugs(5, 3, "start closing FD " << fd << " by " << file << ":" << line);
03eb2f01 839 assert(fd >= 0);
840 assert(fd < Squid_MaxFD);
82ec8dfc
AR
841
842 fde *F = &fd_table[fd];
1f7c9178 843
82ec8dfc 844 if (F->closing())
62e76326 845 return;
846
36afac26 847 /* XXX: is this obsolete behind F->closing() ? */
b8869bcf 848 if ( (shutting_down || reconfiguring) && (!F->flags.open || F->type == FD_FILE))
62e76326 849 return;
850
c4b7a5a9 851 /* The following fails because ipc.c is doing calls to pipe() to create sockets! */
c7e637d7 852 if (!isOpen(fd)) {
d816f28d 853 debugs(50, DBG_IMPORTANT, "ERROR: Squid BUG #3556: FD " << fd << " is not an open socket.");
c7e637d7
AJ
854 // XXX: do we need to run close(fd) or fd_close(fd) here?
855 return;
856 }
62e76326 857
76f87348 858 assert(F->type != FD_FILE);
62e76326 859
be4d35dc 860 F->flags.close_request = true;
62e76326 861
ccfbe8f4
AR
862 // We have caller's context and fde::codeContext. In the unlikely event they
863 // differ, it is not clear which context is more applicable to this closure.
864 // For simplicity sake, we remain in the caller's context while still
865 // allowing individual advanced callbacks to overwrite it.
866
6bd74111 867 if (F->ssl && !F->flags.harshClosureRequested) {
2949dd02
EB
868 const auto startCall = asyncCall(5, 4, "commStartTlsClose",
869 callDialer(commStartTlsClose, fd));
575d05c4
AJ
870 ScheduleCallHere(startCall);
871 }
62e76326 872
74257126
AR
873 // a half-closed fd may lack a reader, so we stop monitoring explicitly
874 if (commHasHalfClosedMonitor(fd))
875 commStopHalfClosedMonitor(fd);
933dd095 876 commUnsetFdTimeout(fd);
62e76326 877
a6351f16 878 // notify read/write handlers after canceling select reservations, if any
ec41b64c 879 if (COMMIO_FD_WRITECB(fd)->active()) {
aee3523a 880 Comm::SetSelect(fd, COMM_SELECT_WRITE, nullptr, nullptr, 0);
c3d6a21b 881 COMMIO_FD_WRITECB(fd)->finish(Comm::ERR_CLOSING, 0);
2b663917 882 }
ec41b64c 883 if (COMMIO_FD_READCB(fd)->active()) {
aee3523a 884 Comm::SetSelect(fd, COMM_SELECT_READ, nullptr, nullptr, 0);
c3d6a21b 885 COMMIO_FD_READCB(fd)->finish(Comm::ERR_CLOSING, 0);
2b663917 886 }
2d8c0b1a 887
9a0a18de 888#if USE_DELAY_POOLS
b27668ec
EB
889 if (BandwidthBucket *bucket = BandwidthBucket::SelectBucket(F)) {
890 if (bucket->selectWaiting)
891 bucket->onFdClosed();
f33d34a8 892 }
b4cd430a
CT
893#endif
894
cb201b7e 895 commCallCloseHandlers(fd);
62e76326 896
a7ad6e4e 897 comm_empty_os_read_buffers(fd);
9e008dda 898
9e008dda 899 // must use async call to wait for all callbacks
82ec8dfc 900 // scheduled before comm_close() to finish
2949dd02
EB
901 const auto completeCall = asyncCall(5, 4, "comm_close_complete",
902 callDialer(comm_close_complete, fd));
10b06767 903 ScheduleCallHere(completeCall);
090089c4 904}
905
090089c4 906/* Send a udp datagram to specified TO_ADDR. */
b8d8561b 907int
5df61230 908comm_udp_sendto(int fd,
b7ac5457 909 const Ip::Address &to_addr,
62e76326 910 const void *buf,
911 int len)
090089c4 912{
95dc7ff4 913 ++ statCounter.syscalls.sock.sendtos;
62e76326 914
cc192b50 915 debugs(50, 3, "comm_udp_sendto: Attempt to send UDP packet to " << to_addr <<
9e008dda 916 " using FD " << fd << " using Port " << comm_local_port(fd) );
cc192b50 917
aee3523a 918 struct addrinfo *AI = nullptr;
4dd643d5
AJ
919 to_addr.getAddrInfo(AI, fd_table[fd].sock_family);
920 int x = sendto(fd, buf, len, 0, AI->ai_addr, AI->ai_addrlen);
b69e9ffa 921 int xerrno = errno;
851614a8 922 Ip::Address::FreeAddr(AI);
cc192b50 923
b69e9ffa
AJ
924 if (x >= 0) {
925 errno = xerrno; // restore for caller to use
2d8c0b1a 926 return x;
b69e9ffa 927 }
2d8c0b1a 928
1191b93b 929#if _SQUID_LINUX_
b69e9ffa 930 if (ECONNREFUSED != xerrno)
17d51783 931#endif
b69e9ffa 932 debugs(50, DBG_IMPORTANT, MYNAME << "FD " << fd << ", (family=" << fd_table[fd].sock_family << ") " << to_addr << ": " << xstrerr(xerrno));
62e76326 933
b69e9ffa 934 errno = xerrno; // restore for caller to use
4ee57cbe 935 return Comm::COMM_ERROR;
090089c4 936}
937
398bc066 938AsyncCall::Pointer
575d05c4 939comm_add_close_handler(int fd, CLCB * handler, void *data)
30a4f2a8 940{
bf8fe701 941 debugs(5, 5, "comm_add_close_handler: FD " << fd << ", handler=" <<
942 handler << ", data=" << data);
62e76326 943
b0469965 944 AsyncCall::Pointer call=commCbCall(5,4, "SomeCloseHandler",
9e008dda 945 CommCloseCbPtrFun(handler, data));
b0469965 946 comm_add_close_handler(fd, call);
398bc066 947 return call;
b0469965 948}
62e76326 949
b0469965 950void
951comm_add_close_handler(int fd, AsyncCall::Pointer &call)
952{
953 debugs(5, 5, "comm_add_close_handler: FD " << fd << ", AsyncCall=" << call);
62e76326 954
b0469965 955 /*TODO:Check for a similar scheduled AsyncCall*/
956// for (c = fd_table[fd].closeHandler; c; c = c->next)
957// assert(c->handler != handler || c->data != data);
62e76326 958
a928fdfd
EB
959 // TODO: Consider enhancing AsyncCallList to support random-access close
960 // handlers, perhaps after upgrading the remaining legacy CLCB handlers.
b0469965 961 call->setNext(fd_table[fd].closeHandler);
62e76326 962
b0469965 963 fd_table[fd].closeHandler = call;
30a4f2a8 964}
965
b0469965 966// remove function-based close handler
b8d8561b 967void
575d05c4 968comm_remove_close_handler(int fd, CLCB * handler, void *data)
090089c4 969{
8ebef9e0 970 assert(isOpen(fd));
30a4f2a8 971 /* Find handler in list */
bf8fe701 972 debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", handler=" <<
973 handler << ", data=" << data);
62e76326 974
aee3523a
AR
975 AsyncCall::Pointer p, prev = nullptr;
976 for (p = fd_table[fd].closeHandler; p != nullptr; prev = p, p = p->Next()) {
b0469965 977 typedef CommCbFunPtrCallT<CommCloseCbPtrFun> Call;
978 const Call *call = dynamic_cast<const Call*>(p.getRaw());
979 if (!call) // method callbacks have their own comm_remove_close_handler
980 continue;
62e76326 981
b0469965 982 typedef CommCloseCbParams Params;
983 const Params &params = GetCommParams<Params>(p);
984 if (call->dialer.handler == handler && params.data == data)
f53969cc 985 break; /* This is our handler */
b0469965 986 }
7828df5b
CT
987
988 // comm_close removes all close handlers so our handler may be gone
aee3523a 989 if (p != nullptr) {
37cba319 990 p->dequeue(fd_table[fd].closeHandler, prev);
7828df5b 991 p->cancel("comm_remove_close_handler");
37cba319 992 }
b0469965 993}
62e76326 994
b0469965 995// remove method-based close handler
996void
997comm_remove_close_handler(int fd, AsyncCall::Pointer &call)
998{
8ebef9e0 999 assert(isOpen(fd));
b0469965 1000 debugs(5, 5, "comm_remove_close_handler: FD " << fd << ", AsyncCall=" << call);
62e76326 1001
7828df5b 1002 // comm_close removes all close handlers so our handler may be gone
aee3523a
AR
1003 AsyncCall::Pointer p, prev = nullptr;
1004 for (p = fd_table[fd].closeHandler; p != nullptr && p != call; prev = p, p = p->Next());
62e76326 1005
aee3523a 1006 if (p != nullptr)
37cba319 1007 p->dequeue(fd_table[fd].closeHandler, prev);
b0469965 1008 call->cancel("comm_remove_close_handler");
30a4f2a8 1009}
090089c4 1010
b8d8561b 1011static void
1012commSetReuseAddr(int fd)
090089c4 1013{
1014 int on = 1;
b69e9ffa
AJ
1015 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on)) < 0) {
1016 int xerrno = errno;
1017 debugs(50, DBG_IMPORTANT, MYNAME << "FD " << fd << ": " << xstrerr(xerrno));
1018 }
090089c4 1019}
1020
b8d8561b 1021static void
1022commSetTcpRcvbuf(int fd, int size)
f868539a 1023{
b69e9ffa
AJ
1024 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char *) &size, sizeof(size)) < 0) {
1025 int xerrno = errno;
1026 debugs(50, DBG_IMPORTANT, MYNAME << "FD " << fd << ", SIZE " << size << ": " << xstrerr(xerrno));
1027 }
1028 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char *) &size, sizeof(size)) < 0) {
1029 int xerrno = errno;
1030 debugs(50, DBG_IMPORTANT, MYNAME << "FD " << fd << ", SIZE " << size << ": " << xstrerr(xerrno));
1031 }
8f0d53ef 1032#ifdef TCP_WINDOW_CLAMP
b69e9ffa
AJ
1033 if (setsockopt(fd, SOL_TCP, TCP_WINDOW_CLAMP, (char *) &size, sizeof(size)) < 0) {
1034 int xerrno = errno;
1035 debugs(50, DBG_IMPORTANT, MYNAME << "FD " << fd << ", SIZE " << size << ": " << xstrerr(xerrno));
1036 }
8f0d53ef 1037#endif
f868539a 1038}
1039
b8d8561b 1040int
1041commSetNonBlocking(int fd)
30a4f2a8 1042{
be266cb2 1043#if _SQUID_WINDOWS_
b05490a8 1044 int nonblocking = TRUE;
62e76326 1045
a396d1f8 1046 if (ioctl(fd, FIONBIO, &nonblocking) < 0) {
b69e9ffa
AJ
1047 int xerrno = errno;
1048 debugs(50, DBG_CRITICAL, MYNAME << "FD " << fd << ": " << xstrerr(xerrno) << " " << fd_table[fd].type);
a396d1f8
EA
1049 return Comm::COMM_ERROR;
1050 }
62e76326 1051
a396d1f8
EA
1052#else
1053 int flags;
1054 int dummy = 0;
62e76326 1055
a396d1f8 1056 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
b69e9ffa
AJ
1057 int xerrno = errno;
1058 debugs(50, DBG_CRITICAL, MYNAME << "FD " << fd << ": fcntl F_GETFL: " << xstrerr(xerrno));
a396d1f8
EA
1059 return Comm::COMM_ERROR;
1060 }
62e76326 1061
a396d1f8 1062 if (fcntl(fd, F_SETFL, flags | SQUID_NONBLOCK) < 0) {
b69e9ffa
AJ
1063 int xerrno = errno;
1064 debugs(50, DBG_CRITICAL, MYNAME << "FD " << fd << ": " << xstrerr(xerrno));
a396d1f8 1065 return Comm::COMM_ERROR;
090089c4 1066 }
7f6ffd15 1067#endif
62e76326 1068
a396d1f8 1069 fd_table[fd].flags.nonblocking = true;
090089c4 1070 return 0;
1071}
1072
7e3ce7b9 1073int
1074commUnsetNonBlocking(int fd)
1075{
7aa9bb3e 1076#if _SQUID_WINDOWS_
a50bfe93 1077 int nonblocking = FALSE;
1078
1079 if (ioctlsocket(fd, FIONBIO, (unsigned long *) &nonblocking) < 0) {
1080#else
7e3ce7b9 1081 int flags;
1082 int dummy = 0;
62e76326 1083
7e3ce7b9 1084 if ((flags = fcntl(fd, F_GETFL, dummy)) < 0) {
b69e9ffa
AJ
1085 int xerrno = errno;
1086 debugs(50, DBG_CRITICAL, MYNAME << "FD " << fd << ": fcntl F_GETFL: " << xstrerr(xerrno));
4ee57cbe 1087 return Comm::COMM_ERROR;
7e3ce7b9 1088 }
62e76326 1089
7e3ce7b9 1090 if (fcntl(fd, F_SETFL, flags & (~SQUID_NONBLOCK)) < 0) {
a50bfe93 1091#endif
b69e9ffa
AJ
1092 int xerrno = errno;
1093 debugs(50, DBG_CRITICAL, MYNAME << "FD " << fd << ": " << xstrerr(xerrno));
4ee57cbe 1094 return Comm::COMM_ERROR;
7e3ce7b9 1095 }
62e76326 1096
be4d35dc 1097 fd_table[fd].flags.nonblocking = false;
7e3ce7b9 1098 return 0;
1099}
1100
b8d8561b 1101void
e1381638
AJ
1102commSetCloseOnExec(int fd)
1103{
3ca60c86 1104#ifdef FD_CLOEXEC
731e4d49 1105 int flags;
7a18b487 1106 int dummy = 0;
62e76326 1107
2209fe19 1108 if ((flags = fcntl(fd, F_GETFD, dummy)) < 0) {
b69e9ffa
AJ
1109 int xerrno = errno;
1110 debugs(50, DBG_CRITICAL, MYNAME << "FD " << fd << ": fcntl F_GETFD: " << xstrerr(xerrno));
62e76326 1111 return;
3ca60c86 1112 }
62e76326 1113
b69e9ffa
AJ
1114 if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0) {
1115 int xerrno = errno;
d816f28d 1116 debugs(50, DBG_CRITICAL, "ERROR: " << MYNAME << "FD " << fd << ": set close-on-exec failed: " << xstrerr(xerrno));
b69e9ffa 1117 }
3ca60c86 1118#endif
1119}
1120
e90100aa 1121#ifdef TCP_NODELAY
1122static void
e1381638
AJ
1123commSetTcpNoDelay(int fd)
1124{
e90100aa 1125 int on = 1;
62e76326 1126
b69e9ffa
AJ
1127 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) < 0) {
1128 int xerrno = errno;
1129 debugs(50, DBG_IMPORTANT, MYNAME << "FD " << fd << ": " << xstrerr(xerrno));
1130 }
62e76326 1131
be4d35dc 1132 fd_table[fd].flags.nodelay = true;
e90100aa 1133}
62e76326 1134
e90100aa 1135#endif
1136
d86b3703 1137void
e1381638
AJ
1138comm_init(void)
1139{
d7ca82e6 1140 assert(fd_table);
2d8c0b1a 1141
59c4d35b 1142 /* XXX account fd_table */
090089c4 1143 /* Keep a few file descriptors free so that we don't run out of FD's
1144 * after accepting a client but before it opens a socket or a file.
e83892e9 1145 * Since Squid_MaxFD can be as high as several thousand, don't waste them */
d85c3078 1146 RESERVED_FD = min(100, Squid_MaxFD / 4);
2d8c0b1a 1147
74257126 1148 TheHalfClosed = new DescriptorSet;
d841c88d
AJ
1149
1150 /* setup the select loop module */
1151 Comm::SelectLoopInit();
090089c4 1152}
1153
236d1779 1154void
e1381638
AJ
1155comm_exit(void)
1156{
74257126 1157 delete TheHalfClosed;
aee3523a 1158 TheHalfClosed = nullptr;
236d1779 1159}
1160
9a0a18de 1161#if USE_DELAY_POOLS
b4cd430a 1162// called when the queue is done waiting for the client bucket to fill
ec41b64c 1163void
b4cd430a
CT
1164commHandleWriteHelper(void * data)
1165{
1166 CommQuotaQueue *queue = static_cast<CommQuotaQueue*>(data);
1167 assert(queue);
1168
1169 ClientInfo *clientInfo = queue->clientInfo;
1170 // ClientInfo invalidates queue if freed, so if we got here through,
1171 // evenAdd cbdata protections, everything should be valid and consistent
f33d34a8 1172 assert(clientInfo);
b4cd430a
CT
1173 assert(clientInfo->hasQueue());
1174 assert(clientInfo->hasQueue(queue));
b4cd430a
CT
1175 assert(clientInfo->eventWaiting);
1176 clientInfo->eventWaiting = false;
1177
1178 do {
b90a3414
EB
1179 clientInfo->writeOrDequeue();
1180 if (clientInfo->selectWaiting)
1181 return;
1182 } while (clientInfo->hasQueue());
b4cd430a 1183
b90a3414
EB
1184 debugs(77, 3, "emptied queue");
1185}
1186
1187void
1188ClientInfo::writeOrDequeue()
1189{
1190 assert(!selectWaiting);
1191 const auto head = quotaPeekFd();
1192 const auto &headFde = fd_table[head];
1193 CallBack(headFde.codeContext, [&] {
1194 const auto ccb = COMMIO_FD_WRITECB(head);
1195 // check that the head descriptor is still relevant
1196 if (headFde.clientInfo == this &&
b6388dfd
AJ
1197 quotaPeekReserv() == ccb->quotaQueueReserv &&
1198 !headFde.closing()) {
b4cd430a
CT
1199
1200 // wait for the head descriptor to become ready for writing
d841c88d 1201 Comm::SetSelect(head, COMM_SELECT_WRITE, Comm::HandleWrite, ccb, 0);
b90a3414
EB
1202 selectWaiting = true;
1203 } else {
1204 quotaDequeue(); // remove the no longer relevant descriptor
f33d34a8 1205 }
b90a3414 1206 });
b4cd430a
CT
1207}
1208
1209bool
1210ClientInfo::hasQueue() const
1211{
1212 assert(quotaQueue);
1213 return !quotaQueue->empty();
1214}
1215
1216bool
1217ClientInfo::hasQueue(const CommQuotaQueue *q) const
1218{
1219 assert(quotaQueue);
1220 return quotaQueue == q;
1221}
1222
1223/// returns the first descriptor to be dequeued
1224int
1225ClientInfo::quotaPeekFd() const
1226{
1227 assert(quotaQueue);
1228 return quotaQueue->front();
1229}
1230
1231/// returns the reservation ID of the first descriptor to be dequeued
1232unsigned int
1233ClientInfo::quotaPeekReserv() const
1234{
1235 assert(quotaQueue);
1236 return quotaQueue->outs + 1;
1237}
1238
1239/// queues a given fd, creating the queue if necessary; returns reservation ID
1240unsigned int
1241ClientInfo::quotaEnqueue(int fd)
1242{
1243 assert(quotaQueue);
1244 return quotaQueue->enqueue(fd);
1245}
1246
1247/// removes queue head
1248void
1249ClientInfo::quotaDequeue()
1250{
1251 assert(quotaQueue);
1252 quotaQueue->dequeue();
1253}
1254
1255void
1256ClientInfo::kickQuotaQueue()
1257{
1258 if (!eventWaiting && !selectWaiting && hasQueue()) {
1259 // wait at least a second if the bucket is empty
b27668ec 1260 const double delay = (bucketLevel < 1.0) ? 1.0 : 0.0;
b4cd430a 1261 eventAdd("commHandleWriteHelper", &commHandleWriteHelper,
f33d34a8 1262 quotaQueue, delay, 0, true);
b4cd430a
CT
1263 eventWaiting = true;
1264 }
1265}
1266
1267/// calculates how much to write for a single dequeued client
1268int
b27668ec 1269ClientInfo::quota()
b4cd430a
CT
1270{
1271 /* If we have multiple clients and give full bucketSize to each client then
1272 * clt1 may often get a lot more because clt1->clt2 time distance in the
1273 * select(2) callback order may be a lot smaller than cltN->clt1 distance.
1274 * We divide quota evenly to be more fair. */
1275
1276 if (!rationedCount) {
1277 rationedCount = quotaQueue->size() + 1;
1278
1279 // The delay in ration recalculation _temporary_ deprives clients from
1280 // bytes that should have trickled in while rationedCount was positive.
1281 refillBucket();
1282
1283 // Rounding errors do not accumulate here, but we round down to avoid
1284 // negative bucket sizes after write with rationedCount=1.
b27668ec 1285 rationedQuota = static_cast<int>(floor(bucketLevel/rationedCount));
bf95c10a 1286 debugs(77,5, "new rationedQuota: " << rationedQuota <<
f33d34a8 1287 '*' << rationedCount);
b4cd430a
CT
1288 }
1289
1290 --rationedCount;
bf95c10a 1291 debugs(77,7, "rationedQuota: " << rationedQuota <<
f33d34a8 1292 " rations remaining: " << rationedCount);
b4cd430a
CT
1293
1294 // update 'last seen' time to prevent clientdb GC from dropping us
1295 last_seen = squid_curtime;
1296 return rationedQuota;
1297}
1298
b27668ec
EB
1299bool
1300ClientInfo::applyQuota(int &nleft, Comm::IoCallback *state)
1301{
1302 assert(hasQueue());
1303 assert(quotaPeekFd() == state->conn->fd);
1304 quotaDequeue(); // we will write or requeue below
1305 if (nleft > 0 && !BandwidthBucket::applyQuota(nleft, state)) {
1306 state->quotaQueueReserv = quotaEnqueue(state->conn->fd);
1307 kickQuotaQueue();
1308 return false;
1309 }
1310 return true;
1311}
1312
b4cd430a 1313void
b27668ec 1314ClientInfo::scheduleWrite(Comm::IoCallback *state)
b4cd430a 1315{
b27668ec
EB
1316 if (writeLimitingActive) {
1317 state->quotaQueueReserv = quotaEnqueue(state->conn->fd);
1318 kickQuotaQueue();
b4cd430a 1319 }
b27668ec 1320}
b4cd430a 1321
b27668ec
EB
1322void
1323ClientInfo::onFdClosed()
1324{
1325 BandwidthBucket::onFdClosed();
1326 // kick queue or it will get stuck as commWriteHandle is not called
1327 kickQuotaQueue();
1328}
b4cd430a 1329
b27668ec
EB
1330void
1331ClientInfo::reduceBucket(const int len)
1332{
1333 if (len > 0)
1334 BandwidthBucket::reduceBucket(len);
1335 // even if we wrote nothing, we were served; give others a chance
1336 kickQuotaQueue();
b4cd430a
CT
1337}
1338
f33d34a8 1339void
b4cd430a
CT
1340ClientInfo::setWriteLimiter(const int aWriteSpeedLimit, const double anInitialBurst, const double aHighWatermark)
1341{
b27668ec 1342 debugs(77,5, "Write limits for " << (const char*)key <<
f33d34a8
A
1343 " speed=" << aWriteSpeedLimit << " burst=" << anInitialBurst <<
1344 " highwatermark=" << aHighWatermark);
b4cd430a
CT
1345
1346 // set or possibly update traffic shaping parameters
1347 writeLimitingActive = true;
1348 writeSpeedLimit = aWriteSpeedLimit;
1349 bucketSizeLimit = aHighWatermark;
1350
1351 // but some members should only be set once for a newly activated bucket
1352 if (firstTimeConnection) {
1353 firstTimeConnection = false;
1354
1355 assert(!selectWaiting);
1356 assert(!quotaQueue);
e9dadd7d 1357 quotaQueue = new CommQuotaQueue(this);
b4cd430a 1358
b27668ec 1359 bucketLevel = anInitialBurst;
b4cd430a
CT
1360 prevTime = current_dtime;
1361 }
1362}
1363
1364CommQuotaQueue::CommQuotaQueue(ClientInfo *info): clientInfo(info),
f53969cc 1365 ins(0), outs(0)
b4cd430a
CT
1366{
1367 assert(clientInfo);
1368}
1369
1370CommQuotaQueue::~CommQuotaQueue()
1371{
1372 assert(!clientInfo); // ClientInfo should clear this before destroying us
1373}
1374
1375/// places the given fd at the end of the queue; returns reservation ID
1376unsigned int
1377CommQuotaQueue::enqueue(int fd)
1378{
b27668ec 1379 debugs(77,5, "clt" << (const char*)clientInfo->key <<
f33d34a8 1380 ": FD " << fd << " with qqid" << (ins+1) << ' ' << fds.size());
b4cd430a 1381 fds.push_back(fd);
b90a3414 1382 fd_table[fd].codeContext = CodeContext::Current();
b4cd430a
CT
1383 return ++ins;
1384}
1385
1386/// removes queue head
1387void
1388CommQuotaQueue::dequeue()
1389{
1390 assert(!fds.empty());
b27668ec 1391 debugs(77,5, "clt" << (const char*)clientInfo->key <<
f33d34a8
A
1392 ": FD " << fds.front() << " with qqid" << (outs+1) << ' ' <<
1393 fds.size());
b4cd430a
CT
1394 fds.pop_front();
1395 ++outs;
1396}
b27668ec 1397#endif /* USE_DELAY_POOLS */
b4cd430a 1398
89924214 1399/*
1400 * hm, this might be too general-purpose for all the places we'd
1401 * like to use it.
1402 */
b224ea98 1403int
e1381638
AJ
1404ignoreErrno(int ierrno)
1405{
603500e7 1406 switch (ierrno) {
62e76326 1407
89924214 1408 case EINPROGRESS:
62e76326 1409
603500e7 1410 case EWOULDBLOCK:
26a880e2 1411#if EAGAIN != EWOULDBLOCK
62e76326 1412
603500e7 1413 case EAGAIN:
26a880e2 1414#endif
62e76326 1415
603500e7 1416 case EALREADY:
62e76326 1417
603500e7 1418 case EINTR:
db494ab8 1419#ifdef ERESTART
62e76326 1420
db494ab8 1421 case ERESTART:
1422#endif
62e76326 1423
1424 return 1;
1425
603500e7 1426 default:
62e76326 1427 return 0;
603500e7 1428 }
62e76326 1429
603500e7 1430 /* NOTREACHED */
26a880e2 1431}
d723bf6b 1432
1433void
e1381638
AJ
1434commCloseAllSockets(void)
1435{
d723bf6b 1436 int fd;
aee3523a 1437 fde *F = nullptr;
62e76326 1438
95dc7ff4 1439 for (fd = 0; fd <= Biggest_FD; ++fd) {
62e76326 1440 F = &fd_table[fd];
1441
1442 if (!F->flags.open)
1443 continue;
1444
1445 if (F->type != FD_SOCKET)
1446 continue;
1447
f53969cc 1448 if (F->flags.ipc) /* don't close inter-process sockets */
62e76326 1449 continue;
1450
aee3523a 1451 if (F->timeoutHandler != nullptr) {
b0469965 1452 AsyncCall::Pointer callback = F->timeoutHandler;
aee3523a 1453 F->timeoutHandler = nullptr;
bf8fe701 1454 debugs(5, 5, "commCloseAllSockets: FD " << fd << ": Calling timeout handler");
9e008dda 1455 ScheduleCallHere(callback);
62e76326 1456 } else {
468fe1b5 1457 debugs(5, 5, "commCloseAllSockets: FD " << fd << ": calling comm_reset_close()");
5c336a3b 1458 old_comm_reset_close(fd);
62e76326 1459 }
d723bf6b 1460 }
1461}
1b3db6d9 1462
2d8c0b1a 1463static bool
e1381638
AJ
1464AlreadyTimedOut(fde *F)
1465{
2d8c0b1a 1466 if (!F->flags.open)
1467 return true;
1468
1469 if (F->timeout == 0)
1470 return true;
1471
1472 if (F->timeout > squid_curtime)
1473 return true;
1474
1475 return false;
1476}
1477
5ef5e5cc
AJ
1478static bool
1479writeTimedOut(int fd)
1480{
ec41b64c 1481 if (!COMMIO_FD_WRITECB(fd)->active())
5ef5e5cc
AJ
1482 return false;
1483
1484 if ((squid_curtime - fd_table[fd].writeStart) < Config.Timeout.write)
1485 return false;
1486
1487 return true;
1488}
1489
1b3db6d9 1490void
e1381638
AJ
1491checkTimeouts(void)
1492{
1b3db6d9 1493 int fd;
aee3523a 1494 fde *F = nullptr;
b0469965 1495 AsyncCall::Pointer callback;
62e76326 1496
95dc7ff4 1497 for (fd = 0; fd <= Biggest_FD; ++fd) {
62e76326 1498 F = &fd_table[fd];
1499
5ef5e5cc
AJ
1500 if (writeTimedOut(fd)) {
1501 // We have an active write callback and we are timed out
ccfbe8f4 1502 CodeContext::Reset(F->codeContext);
52f6ea9e 1503 debugs(5, 5, "checkTimeouts: FD " << fd << " auto write timeout");
aee3523a 1504 Comm::SetSelect(fd, COMM_SELECT_WRITE, nullptr, nullptr, 0);
4ee57cbe 1505 COMMIO_FD_WRITECB(fd)->finish(Comm::COMM_ERROR, ETIMEDOUT);
ccfbe8f4 1506 CodeContext::Reset();
db43f179 1507 continue;
b27668ec
EB
1508#if USE_DELAY_POOLS
1509 } else if (F->writeQuotaHandler != nullptr && COMMIO_FD_WRITECB(fd)->conn != nullptr) {
ccfbe8f4 1510 // TODO: Move and extract quota() call to place it inside F->codeContext.
b27668ec 1511 if (!F->writeQuotaHandler->selectWaiting && F->writeQuotaHandler->quota() && !F->closing()) {
ccfbe8f4 1512 CodeContext::Reset(F->codeContext);
b27668ec
EB
1513 F->writeQuotaHandler->selectWaiting = true;
1514 Comm::SetSelect(fd, COMM_SELECT_WRITE, Comm::HandleWrite, COMMIO_FD_WRITECB(fd), 0);
ccfbe8f4 1515 CodeContext::Reset();
b27668ec
EB
1516 }
1517 continue;
1518#endif
1519 }
1520 else if (AlreadyTimedOut(F))
62e76326 1521 continue;
1522
ccfbe8f4 1523 CodeContext::Reset(F->codeContext);
9e008dda 1524 debugs(5, 5, "checkTimeouts: FD " << fd << " Expired");
62e76326 1525
aee3523a 1526 if (F->timeoutHandler != nullptr) {
bf8fe701 1527 debugs(5, 5, "checkTimeouts: FD " << fd << ": Call timeout handler");
b0469965 1528 callback = F->timeoutHandler;
aee3523a 1529 F->timeoutHandler = nullptr;
9e008dda 1530 ScheduleCallHere(callback);
62e76326 1531 } else {
bf8fe701 1532 debugs(5, 5, "checkTimeouts: FD " << fd << ": Forcing comm_close()");
62e76326 1533 comm_close(fd);
1534 }
ccfbe8f4
AR
1535
1536 CodeContext::Reset();
b5443c04 1537 }
1538}
1539
9e008dda
AJ
1540/// Start waiting for a possibly half-closed connection to close
1541// by scheduling a read callback to a monitoring handler that
82ec8dfc 1542// will close the connection on read errors.
a46d2c0e 1543void
e1381638
AJ
1544commStartHalfClosedMonitor(int fd)
1545{
bf95c10a 1546 debugs(5, 5, "adding FD " << fd << " to " << *TheHalfClosed);
8ebef9e0 1547 assert(isOpen(fd) && !commHasHalfClosedMonitor(fd));
74257126 1548 (void)TheHalfClosed->add(fd); // could also assert the result
1f9077c2 1549 fd_table[fd].codeContext = CodeContext::Current();
74257126
AR
1550 commPlanHalfClosedCheck(); // may schedule check if we added the first FD
1551}
1552
1553static
1554void
e1381638
AJ
1555commPlanHalfClosedCheck()
1556{
74257126 1557 if (!WillCheckHalfClosed && !TheHalfClosed->empty()) {
aee3523a 1558 eventAdd("commHalfClosedCheck", &commHalfClosedCheck, nullptr, 1.0, 1);
74257126
AR
1559 WillCheckHalfClosed = true;
1560 }
1561}
1562
1563/// iterates over all descriptors that may need half-closed tests and
1564/// calls comm_read for those that do; re-schedules the check if needed
1565static
1566void
e1381638
AJ
1567commHalfClosedCheck(void *)
1568{
bf95c10a 1569 debugs(5, 5, "checking " << *TheHalfClosed);
74257126
AR
1570
1571 typedef DescriptorSet::const_iterator DSCI;
1572 const DSCI end = TheHalfClosed->end();
1573 for (DSCI i = TheHalfClosed->begin(); i != end; ++i) {
ec20038e
AJ
1574 Comm::ConnectionPointer c = new Comm::Connection; // XXX: temporary. make HalfClosed a list of these.
1575 c->fd = *i;
1576 if (!fd_table[c->fd].halfClosedReader) { // not reading already
1f9077c2
EB
1577 CallBack(fd_table[c->fd].codeContext, [&c] {
1578 AsyncCall::Pointer call = commCbCall(5,4, "commHalfClosedReader",
b6388dfd 1579 CommIoCbPtrFun(&commHalfClosedReader, nullptr));
1f9077c2
EB
1580 Comm::Read(c, call);
1581 fd_table[c->fd].halfClosedReader = call;
1582 });
ec20038e
AJ
1583 } else
1584 c->fd = -1; // XXX: temporary. prevent c replacement erase closing listed FD
74257126 1585 }
f900210a 1586
74257126
AR
1587 WillCheckHalfClosed = false; // as far as we know
1588 commPlanHalfClosedCheck(); // may need to check again
f900210a 1589}
1590
82ec8dfc
AR
1591/// checks whether we are waiting for possibly half-closed connection to close
1592// We are monitoring if the read handler for the fd is the monitoring handler.
1593bool
e1381638
AJ
1594commHasHalfClosedMonitor(int fd)
1595{
74257126 1596 return TheHalfClosed->has(fd);
a46d2c0e 1597}
1598
82ec8dfc 1599/// stop waiting for possibly half-closed connection to close
7e66d5e2 1600void
e1381638
AJ
1601commStopHalfClosedMonitor(int const fd)
1602{
bf95c10a 1603 debugs(5, 5, "removing FD " << fd << " from " << *TheHalfClosed);
74257126
AR
1604
1605 // cancel the read if one was scheduled
1606 AsyncCall::Pointer reader = fd_table[fd].halfClosedReader;
aee3523a 1607 if (reader != nullptr)
0d4e382b 1608 Comm::ReadCancel(fd, reader);
aee3523a 1609 fd_table[fd].halfClosedReader = nullptr;
74257126
AR
1610
1611 TheHalfClosed->del(fd);
a46d2c0e 1612}
1613
82ec8dfc
AR
1614/// I/O handler for the possibly half-closed connection monitoring code
1615static void
c8407295 1616commHalfClosedReader(const Comm::ConnectionPointer &conn, char *, size_t size, Comm::Flag flag, int, void *)
e1381638 1617{
82ec8dfc 1618 // there cannot be more data coming in on half-closed connections
9e008dda 1619 assert(size == 0);
aee3523a 1620 assert(conn != nullptr);
e0d28505 1621 assert(commHasHalfClosedMonitor(conn->fd)); // or we would have canceled the read
74257126 1622
aee3523a 1623 fd_table[conn->fd].halfClosedReader = nullptr; // done reading, for now
a46d2c0e 1624
82ec8dfc 1625 // nothing to do if fd is being closed
c8407295 1626 if (flag == Comm::ERR_CLOSING)
82ec8dfc 1627 return;
a46d2c0e 1628
82ec8dfc 1629 // if read failed, close the connection
c8407295 1630 if (flag != Comm::OK) {
bf95c10a 1631 debugs(5, 3, "closing " << conn);
80463bb4 1632 conn->close();
82ec8dfc
AR
1633 return;
1634 }
a46d2c0e 1635
82ec8dfc 1636 // continue waiting for close or error
74257126 1637 commPlanHalfClosedCheck(); // make sure this fd will be checked again
a46d2c0e 1638}
a46d2c0e 1639
8ff3fa2e 1640int
e1381638
AJ
1641CommSelectEngine::checkEvents(int timeout)
1642{
fa3f745b 1643 static time_t last_timeout = 0;
1644
1645 /* No, this shouldn't be here. But it shouldn't be in each comm handler. -adrian */
1646 if (squid_curtime > last_timeout) {
1647 last_timeout = squid_curtime;
1648 checkTimeouts();
1649 }
1650
d841c88d 1651 switch (Comm::DoSelect(timeout)) {
8ff3fa2e 1652
c8407295 1653 case Comm::OK:
8ff3fa2e 1654
c8407295 1655 case Comm::TIMEOUT:
8ff3fa2e 1656 return 0;
1657
c8407295 1658 case Comm::IDLE:
8ff3fa2e 1659
c8407295 1660 case Comm::SHUTDOWN:
8ff3fa2e 1661 return EVENT_IDLE;
1662
4ee57cbe 1663 case Comm::COMM_ERROR:
8ff3fa2e 1664 return EVENT_ERROR;
1665
1666 default:
1667 fatal_dump("comm.cc: Internal error -- this should never happen.");
1668 return EVENT_ERROR;
1669 };
1670}
10cefb7b 1671
0ffda73c 1672/// Create a unix-domain socket (UDS) that only supports FD_MSGHDR I/O.
10cefb7b 1673int
1674comm_open_uds(int sock_type,
1675 int proto,
1676 struct sockaddr_un* addr,
1677 int flags)
1678{
a67d2b2e 1679 // TODO: merge with comm_openex() when Ip::Address becomes NetAddress
ba568924 1680
10cefb7b 1681 int new_socket;
10cefb7b 1682
10cefb7b 1683 /* Create socket for accepting new connections. */
95dc7ff4 1684 ++ statCounter.syscalls.sock.sockets;
10cefb7b 1685
1686 /* Setup the socket addrinfo details for use */
ba568924 1687 struct addrinfo AI;
10cefb7b 1688 AI.ai_flags = 0;
1689 AI.ai_family = PF_UNIX;
1690 AI.ai_socktype = sock_type;
1691 AI.ai_protocol = proto;
1692 AI.ai_addrlen = SUN_LEN(addr);
1693 AI.ai_addr = (sockaddr*)addr;
aee3523a
AR
1694 AI.ai_canonname = nullptr;
1695 AI.ai_next = nullptr;
10cefb7b 1696
bf95c10a 1697 debugs(50, 3, "Attempt open socket for: " << addr->sun_path);
10cefb7b 1698
1699 if ((new_socket = socket(AI.ai_family, AI.ai_socktype, AI.ai_protocol)) < 0) {
b69e9ffa 1700 int xerrno = errno;
10cefb7b 1701 /* Increase the number of reserved fd's if calls to socket()
1702 * are failing because the open file table is full. This
1703 * limits the number of simultaneous clients */
1704
b69e9ffa
AJ
1705 if (limitError(xerrno)) {
1706 debugs(50, DBG_IMPORTANT, MYNAME << "socket failure: " << xstrerr(xerrno));
10cefb7b 1707 fdAdjustReserved();
1708 } else {
b69e9ffa 1709 debugs(50, DBG_CRITICAL, MYNAME << "socket failure: " << xstrerr(xerrno));
10cefb7b 1710 }
10cefb7b 1711 return -1;
1712 }
1713
fc9d2eb0 1714 debugs(50, 3, "Opened UDS FD " << new_socket << " : family=" << AI.ai_family << ", type=" << AI.ai_socktype << ", protocol=" << AI.ai_protocol);
10cefb7b 1715
1716 /* update fdstat */
bf95c10a 1717 debugs(50, 5, "FD " << new_socket << " is a new socket");
10cefb7b 1718
1719 assert(!isOpen(new_socket));
04efe9dd 1720 fd_open(new_socket, FD_MSGHDR, addr->sun_path);
10cefb7b 1721
ba568924
AR
1722 fd_table[new_socket].sock_family = AI.ai_family;
1723
10cefb7b 1724 if (!(flags & COMM_NOCLOEXEC))
1725 commSetCloseOnExec(new_socket);
1726
1727 if (flags & COMM_REUSEADDR)
1728 commSetReuseAddr(new_socket);
1729
1730 if (flags & COMM_NONBLOCKING) {
c8407295 1731 if (commSetNonBlocking(new_socket) != Comm::OK) {
10cefb7b 1732 comm_close(new_socket);
10cefb7b 1733 return -1;
1734 }
1735 }
1736
1737 if (flags & COMM_DOBIND) {
c8407295 1738 if (commBind(new_socket, AI) != Comm::OK) {
10cefb7b 1739 comm_close(new_socket);
10cefb7b 1740 return -1;
1741 }
1742 }
1743
1744#ifdef TCP_NODELAY
1745 if (sock_type == SOCK_STREAM)
1746 commSetTcpNoDelay(new_socket);
1747
1748#endif
1749
1750 if (Config.tcpRcvBufsz > 0 && sock_type == SOCK_STREAM)
1751 commSetTcpRcvbuf(new_socket, Config.tcpRcvBufsz);
1752
10cefb7b 1753 return new_socket;
1754}
f53969cc 1755