]> git.ipfire.org Git - thirdparty/squid.git/log
thirdparty/squid.git
16 months ago%busy_time: Time spent in transaction-related code (#1216)
Alex Rousskov [Tue, 3 Jan 2023 12:20:27 +0000 (12:20 +0000)] 
%busy_time: Time spent in transaction-related code (#1216)

Configuration tuning, problems triage, and performance optimization
often benefit from knowing how much time Squid spent on a particular
transaction (or a typical transaction in a category like "cache hits").

We already log total transaction response time (%tr), but that time
includes transaction queuing time (i.e. the time when Squid could
advance our transaction but was advancing other transactions) and
various waiting periods (e.g., waiting for a helper response). The new
measurement focuses on time periods when Squid was actively working on
(as in "was blocked on") our transaction.

CodeContext coverage problems do affect this measurement, but the
existing coverage is already good enough for usable measurements in some
cases, and it is getting better. It will take us a long time to cover
all cases; we should not wait for that to happen (as long as we warn
admins about these problems).

16 months agoMaintenance: source maintenance script improvements (#1220)
gkinkie@gmail.com [Fri, 30 Dec 2022 18:07:12 +0000 (18:07 +0000)] 
Maintenance: source maintenance script improvements (#1220)

- Allow passing astyle program name via ASTYLE environment variable.
- By default, use "astyle-3.1" if present or "astyle" otherwise.
- Add an option to format changed source files only.

No changes to the default behavior except for environments where a
program named "astyle-3.1" is present but a program named "astyle" was
previously used.

16 months agoFix errorpage.cc build on MacOS (#1219)
gkinkie@gmail.com [Wed, 28 Dec 2022 13:38:35 +0000 (13:38 +0000)] 
Fix errorpage.cc build on MacOS (#1219)

    errorpage.cc:153:44: error: implicit instantiation of undefined
    template std::array<HardCodedError, 7> HardCodedErrors

16 months agoFix ./configure --with-filedescriptors=NUMBER (#1217)
Alex Rousskov [Sat, 24 Dec 2022 17:00:32 +0000 (17:00 +0000)] 
Fix ./configure --with-filedescriptors=NUMBER (#1217)

Commit a1c2236 forgot to quote AS_CASE argument of AC_ARG_WITH(),
resulting in the following ./configure-time errors:

    error: --with-filedescriptors expects a numeric argument

We now quote AS_CASE argument of AC_ARG_WITH(), as recommended by
Autoconf and for consistency sake. More (hopefully automated) work is
needed to quote all function call arguments (that should be quoted).

Also use m4 quadrigraphs for quoting safety sake and to attract readers
attention to a risky (from writing in m4 point of view) expression. This
particular improvement is not required to fix the bug.

The other two AC_ARG_WITH() are modified for consistency sake but they
were not broken and their compiled versions have not changed.

17 months agoFix GCC v12 build errors related to ADL in "printing" code (#1215)
Alex Rousskov [Thu, 22 Dec 2022 02:12:12 +0000 (02:12 +0000)] 
Fix GCC v12 build errors related to ADL in "printing" code (#1215)

This change contains three fixes/adjustments described below.

### Fix Store::SwapMetaView printing

    src/sbuf/Stream.h:66:20: error: no match for 'operator<<' (operand
    types are 'std::basic_ostream<char>' and 'const
    Store::SwapMetaView'): (out << ... << args);

Disclaimer: This explanation omits many details that become important in
some other contexts. Most Argument-Dependent Lookup details are
documented at https://en.cppreference.com/w/cpp/language/adl

    // In some printer.h, we define a printing function for any type A.
    // This is similar to an ToSBuf() declaration in sbuf/Stream.h.
    template <typename A>
    void print(ostream &os, const A &argument) { os << argument; }

    // In some n/t.h, we define how to print objects of type N::T.
    // This is similar to store/SwapMetaView.h.
    operator <<(ostream &os, const N::T &argument);

    // In some caller1.cc, we include both headers and call print():
    #include "printer.h"
    #include "n/t.h"
    void caller1(const N::T &argument) { print(std::cout, argument); }

    // In some caller2.cc, we do the same but change #include order:
    #include "n/t.h"
    #include "printer.h"
    void caller2(const N::T &argument) { print(std::cout, argument); }

When looking at "os << argument", the compiler considers two sets of
argument printing operators, formed by the following two sources:

* The usual unqualified name lookup. This set includes N::T printing
  operator if that operator is declared in global namespace somewhere
  above the print() _template declaration_. In the example above, only
  caller2() will have that printing operator in this set, provided that
  operator is declared in global namespace (as it used to be). None of
  the callers will have that printing operator in this set otherwise.

* ADL. This set is computed from the caller point of view. It includes
  N::T printing operator if that operator is declared inside namespace N
  somewhere above the print() _caller_. In the example above, both
  caller1() and caller2() will have that printing operator in this set,
  provided that operator is declared in namespace N (as it is now). None
  of the callers will have that printing operator in this set otherwise.

For code to compile, one of the sets must contain the printing operator.
Given the above outcomes, there is only one sane solution that allows
any caller to instantiate print() with an N::T argument: The argument
printing operator must be declared inside namaspace N! Declaring in
global namespace would require maintaining certain #include order (that
will cause headaches and, eventually, circular dependencies).

In other words, we must rely on ADL, and that means declaring operators
in the namespace of one of their argument types.

### Fix std::optional<Ip::Address> printing (in src/icap/Xaction.cc)

    src/base/AsyncJobCalls.h:115:61: error: no match for 'operator<<'
    (operand types are 'std::basic_ostream<char>' and 'const
    std::optional<Ip::Address>'):
    void print(std::ostream &os) const { os << '(' << arg1 << ')'; }

In this context, both printing operator argument types are in std, but
ADL also looks at template parameters of argument types (if an argument
type is a template). That recursion adds the Ip namespace to the search.

This is a minimal fix. We should move both Ip::Address printers into
ip/print.h or similar, away from Ip::Address users that print nothing.

### Do not declare an overly general std::optional printer

The removed declaration:

* evidently became unused (after the other changes described above);
* places std::optional<N::T> printers in the wrong namespace (global
  instead of N), where ADL cannot find them;
* exposes all I/O manipulators to a, technically, unrelated
  std::optional interface.

Co-authored-by: Amos Jeffries <squid3@treenet.co.nz>
17 months agoSupport "negative" squid-conf-tests (#1214)
Alex Rousskov [Tue, 20 Dec 2022 15:41:40 +0000 (15:41 +0000)] 
Support "negative" squid-conf-tests (#1214)

The test suite can now check that Squid rejects a given malformed
configuration file and that the rejection reason matches the expected
one. The latter reduces the probability that a successful "negative"
test outcome would hide a bug (because Squid has rejected a malformed
file but for a reason unrelated to what the test was trying to verify).

For now, enable just one acl regex test case, addressing an old TODO.

To improve "negative" test coverage, we would need to generate test
configurations using a configuration template and a list of problematic
expressions (with corresponding failure messages), but this hard-coded
approach is already better than nothing.

17 months agoRequire C++17 (#1212)
Alex Rousskov [Tue, 13 Dec 2022 23:17:48 +0000 (23:17 +0000)] 
Require C++17 (#1212)

Modern environments support C++17 well. We are wasting significant
amounts of time on emulating such basic C++17 features as std::optional.
We are writing worse code than we can because we lack access to such
C++14 and C++17 features like std::make_unique and std::byte.

The following language-standard-dependent TODOs were completed:

* Switched to [[fallthrough]] attributes.
* Replaced Optional with std::optional.
* Replaced EnableIfType with std::enable_if_t.
* Removed old C++11 type replacements (e.g., xuniform_int_distribution).
* Removed std::allocator declarations deprecated in C++17.
* Made ToSBuf() readable using a fold expression.
* Simplified compile-time "natural type" assertions.
* Used std::container::emplace*() return value where warranted.

Moved BUILDCXX-setting code after AX_CXX_COMPILE_STDCXX adds -std=c++17
to CXX (rather than CXXFLAGS!). Our cf_gen was built with compiler's
default C++ standard version! Ideally, BUILDCXX block should be lowered
further -- other macros might alter CXX -- but its CXXFLAGS adjustment
may affect subsequent code, warranting a careful/dedicated change.

17 months agoBan acl key changes in req_header, rep_header, and note ACLs (#1210)
Alex Rousskov [Mon, 12 Dec 2022 13:34:12 +0000 (13:34 +0000)] 
Ban acl key changes in req_header, rep_header, and note ACLs (#1210)

* req_header and rep_header ACLs; the key is the header-name argument:

    acl barred req_header X-1 bar
    acl barred req_header X-2 bar # never matches since commit a0b240c
    http_access deny barred

* the "note" ACL; the key is the annotation name argument:

    acl banned note color green  # never matches since commit 39baccc
    acl banned note weight heavy
    http_access deny banned

Squid did write a cache.log ERROR for req_header/rep_header key changes
but was silent about the preceding "note" ACL rules being ineffective
after a key change (e.g., Squid was not denying "green" requests above).

Now, Squid rejects configurations containing such ACL key changes.

Also significantly reduced the corresponding parsing code duplication.

17 months agoFix ACL type typo in req_header, rep_header key-changing ERRORs (#1208)
Alex Rousskov [Sat, 10 Dec 2022 14:18:18 +0000 (14:18 +0000)] 
Fix ACL type typo in req_header, rep_header key-changing ERRORs (#1208)

17 months agoext_kerberos_ldap_group_acl: Support -b with -D (#1207)
Alexander Bokovoy [Sat, 10 Dec 2022 11:50:27 +0000 (11:50 +0000)] 
ext_kerberos_ldap_group_acl: Support -b with -D (#1207)

When both '-b' (i.e. bind DN) and '-D' (i.e. Kerberos domain) options
are specified, '-b' is ignored completely. This breaks the helper when a
search subtree has to be limited (e.g., when using FreeIPA).

Fix it to take '-b' into account if it was specified with '-D'.

17 months agoUpdate LruNode to MEMPROXY_CLASS (#1206)
Amos Jeffries [Fri, 9 Dec 2022 21:54:31 +0000 (21:54 +0000)] 
Update LruNode to MEMPROXY_CLASS (#1206)

17 months agosquid-conf-tests should test installed Squid (#1204)
Alex Rousskov [Fri, 9 Dec 2022 11:51:39 +0000 (11:51 +0000)] 
squid-conf-tests should test installed Squid (#1204)

    FATAL: ..._inst/etc/mime.conf: (2) No such file or directory
    FATAL: ..._inst/share/icons: (2) No such file or directory

Our squid-conf-tests are running "squid -k parse" that requires icons
and other supplementary files to be _installed_. Thus, squid-conf-tests
must run during "make installcheck" rather than during "make check".

With this change, "make distcheck" triggers squid-conf-tests at the
right time, after "all", "check", and "install" targets are built.
Also, we are now testing installed Squid binaries, as we should.

17 months agoUpdate Host, Via, and other headers in-place when possible (#1203)
Eric Walters [Fri, 9 Dec 2022 05:58:43 +0000 (05:58 +0000)] 
Update Host, Via, and other headers in-place when possible (#1203)

This change optimizes Host header synchronization code that usually does
not need to change the Host header field but was always deleting the old
field and generating/appending a new one. Appending Host also violated
an RFC 9110 section 7.2 rule (on behalf of the user agent whose Host we
were rewriting): "A user agent that sends Host SHOULD send it as the
first field in the header section".

Also, removing old header fields and appending new ones introduced HTTP
header changes that broke otherwise working peers. For example, some
origins denied Squid-proxied messages exclusively due to an unusual
(from those origins point of view) Host header position. This change
reduces (but does not eliminate) such unnecessary and risky changes.

17 months agoFix helper module auto-detection algorithm (#1194)
Amos Jeffries [Fri, 9 Dec 2022 01:08:03 +0000 (01:08 +0000)] 
Fix helper module auto-detection algorithm (#1194)

Two issues here causing no helpers to be detected as buildable when
./configure parameters are missing entirely (eg "./configure ").
These were not detected by our build farm because missing helpers
is not an error, they are optional, and we lack tests validating
optional helpers.

1) Over-escaping of "$" variable prefix (M4 "$$" expands to "$")
   prevented the path string being expanded to correct value for
   the helper directory test. Causing it to always fail.

2) The $ac_top_srcdir variable internal to autoconf may not be set
   at the time AC_DEFUN macros are expanded. Making it unreliable.
   The $top_srcdir variable which should be used instead has the
   same problem with "top" not yet being determined. As such we
   use $srcdir instead and hope it expands correctly at ./configure
   run time.

17 months agoDo not overwrite caching bans (#1189)
Alex Rousskov [Thu, 8 Dec 2022 08:25:44 +0000 (08:25 +0000)] 
Do not overwrite caching bans (#1189)

To ban caching, Squid made RequestFlags::cachable false in several
places (e.g., when a "cache deny" rule matched). To permit caching,
Squid also made the flag true in several places (e.g., when
maybeCacheable() was true). That combination worked as intended only
when the cachable=false veto always came after all the cachable=true
support votes. The code did not (and should not) enforce such a
complicated/fragile timing invariant.

Squid now correctly honors caching bans regardless of the updates order.

This change addresses an old XXX, but we are not aware of any specific
bugs fixed by this change. The primary purpose of this change is to make
the existing baseline ban-honoring functionality easy to maintain.

Also reduced code duplication across cachable=false,noCache=true code.

17 months agoSource Format Enforcement (#1201)
squidadm [Thu, 8 Dec 2022 02:50:15 +0000 (02:50 +0000)] 
Source Format Enforcement (#1201)

17 months agoFix regression test configuration (#1198)
Eduard Bagdasaryan [Wed, 7 Dec 2022 20:15:17 +0000 (20:15 +0000)] 
Fix regression test configuration (#1198)

The regressions-3.4.0.1 configuration produces an error message:

    ERROR: Can not open file empty for reading

Broken since commit 6c9a5e8 that renamed "empty" to "empty.conf".

17 months agoOptimize RefCount comparison with raw pointers (#1200)
sameer-here [Wed, 7 Dec 2022 17:27:47 +0000 (17:27 +0000)] 
Optimize RefCount comparison with raw pointers (#1200)

GCC v12 and Clang v12 tests show that compilers cannot avoid creating
temporaries when comparing RefCount objects with arbitrary pointers.

Also fixes (not yet supported) C++20 build. C++20 automatically reverses
equality comparisons, triggering an ambiguity:

    src/esi/Esi.cc:1920:26: error: ambiguous overload for 'operator=='
        (operand types are 'ESISegment::Pointer' {aka
        'RefCount<ESISegment>'} and std::nullptr_t)
        assert (output->next == nullptr);

    src/esi/Esi.cc:77:6: note: candidate: 'bool operator==(const
        ESIElement*, const Pointer&)' (reversed)

    src/base/RefCount.h:82:10: note: candidate: 'bool
        RefCount<C>::operator==(const RefCount<C>&) const [with C =
        ESISegment]'

17 months agoDrop CBDATA debugging (#1199)
Amos Jeffries [Mon, 5 Dec 2022 15:52:26 +0000 (15:52 +0000)] 
Drop CBDATA debugging (#1199)

This was occasionally (but still rare) useful when CBDATA was the
only method of passing callback parameters. Much of that has now
been replaced with AsyncJob/AsyncCall logic. Making this debug
much less useful.

Remove the --enable-debug-cbdata build option and two cache manager
reports only enabled when that option is built. Greatly reducing
the cbdata logic complexity and removing one of its five APIs
permutations entirely.

17 months agoAvoid level-3 "failed to find or read error text file" WARNINGs (#1176)
Eduard Bagdasaryan [Sun, 4 Dec 2022 22:00:20 +0000 (22:00 +0000)] 
Avoid level-3 "failed to find or read error text file" WARNINGs (#1176)

... when (re)configuring ERR_REQUEST_PARSE_TIMEOUT and ERR_RELAY_REMOTE
error templates. These errors cannot be customized externally and should
have been listed as such in commits 9ce4a1e and f5e1794, respectively.

Also polished hard-coded error storage code.

17 months agobasic_ncsa_auth: Fix missing libnettle dependency (#1193)
Amos Jeffries [Fri, 2 Dec 2022 14:11:22 +0000 (14:11 +0000)] 
basic_ncsa_auth: Fix missing libnettle dependency (#1193)

Broken since b12b66cdd75835c6fb92bf25c2f68272f55d21cd

17 months agokerberos_ldap_group: fix unused variable warnings (#1192)
Amos Jeffries [Fri, 2 Dec 2022 09:11:39 +0000 (09:11 +0000)] 
kerberos_ldap_group: fix unused variable warnings (#1192)

When built with disabled LDAP support.

17 months agoRefactor memory pools statistics gathering (#1186)
Amos Jeffries [Fri, 2 Dec 2022 05:02:44 +0000 (05:02 +0000)] 
Refactor memory pools statistics gathering (#1186)

17 months agoBug 5162: mgr:index URL do not produce MGR_INDEX template (#1191)
Eduard Bagdasaryan [Thu, 1 Dec 2022 18:50:37 +0000 (18:50 +0000)] 
Bug 5162: mgr:index URL do not produce MGR_INDEX template (#1191)

Satisfy mgr:index requests using

* a 200 OK response with a body derived from the MGR_INDEX template (if
  that template file was found during (re)configuration) or
* a 404 (Not Found) error response (otherwise).

Broken in 2019 commit 7e6eabb, when Squid started replying using a 200
OK response with a hard-coded "mgr_index" text as a body, ignoring any
configured MGR_INDEX template.

17 months agoMake Optional<bool> trivially copyable (#1188)
Alex Rousskov [Thu, 1 Dec 2022 05:49:57 +0000 (05:49 +0000)] 
Make Optional<bool> trivially copyable (#1188)

    ipc/TypedMsgHdr.h: static assertion failed: putPod() used for a POD
    ActionParams.cc:44: required from here [with Pod = RequestFlags]

The known XXX in Optional destructor has started to bite us because
pending changes expose memcpy(3)-based IPC serialization code to
Optional<bool> flags. It is possible to mimic standard std::optional
implementations, avoiding that XXX, but that requires rather
sophisticated C++ tricks with placement new() and such. Specializing the
whole Optional is a better alternative for this _temporary_ class IMO.

17 months agoMaintenance: Missing squid.h include (#1190)
Alex Rousskov [Wed, 30 Nov 2022 18:09:02 +0000 (18:09 +0000)] 
Maintenance: Missing squid.h include (#1190)

Broken since inception (i.e. master/v6 commit 4a28fc5).
Detected by scripts/source-maintenance.sh.

17 months agoCI: Test handling of truncated responses (#1187)
Alex Rousskov [Tue, 29 Nov 2022 02:57:15 +0000 (02:57 +0000)] 
CI: Test handling of truncated responses (#1187)

Use Daft truncated-responses test to monitor for bugs like those fixed
by master/v6 commit ba3fe8d.

17 months agoShuffle MemAllocator to Mem namespace (#1181)
Amos Jeffries [Mon, 28 Nov 2022 14:46:51 +0000 (14:46 +0000)] 
Shuffle MemAllocator to Mem namespace (#1181)

Update and add missing documentation for class members.

Update syntax to latest standard compliance and Squid
coding guideline style.

17 months agoMove MemPoolMeter into Mem namespace (#1183)
Amos Jeffries [Thu, 24 Nov 2022 00:17:11 +0000 (00:17 +0000)] 
Move MemPoolMeter into Mem namespace (#1183)

Simplified PoolMeter::flush() implementation
and inlined it for performance.

Convert mgb_t type to a sub-struct and inline
C++11 initialization for performance.

Also update Mem::Meter initialization.

18 months agoRemove Mem::Report() and polish memory_pools_limit storage (#1184)
Amos Jeffries [Mon, 21 Nov 2022 05:20:32 +0000 (05:20 +0000)] 
Remove Mem::Report() and polish memory_pools_limit storage (#1184)

The official code should not call Mem::Report(). There is no
justification for main.cc treating memory module in such a
special way. The reporting code itself has problems.
Removing all this code is better than leaving or polishing it.

18 months agoDo not blame cache_peer for 4xx CONNECT responses (#1166)
Eduard Bagdasaryan [Sun, 13 Nov 2022 16:00:21 +0000 (16:00 +0000)] 
Do not blame cache_peer for 4xx CONNECT responses (#1166)

To avoid using a problematic cache_peer, Squid penalizes cache_peers for
a variety of problems. However, a problem like an HTTP 403 Forbidden
response may be caused by the client or other factors unrelated to the
cache_peer that sent the response to Squid. In those cases, the
cache_peer is not at fault and should not be marked dead, even after
many such responses.

This change stops blaming cache_peers for HTTP 4xx outcomes of Squid
CONNECT requests. Currently, such outcomes only happen when a cache_peer
responds with a 4xx reply, but the new code also treats Squid-generated
4xx error responses (while trying to establish a connection to the
cache_peer) the same way.

This hard-coded logic covers known use cases. If different use cases
surface, we can make Squid behavior configurable.

Co-authored-by: Amos Jeffries <squid3@treenet.co.nz>
18 months agoRemove --enable-kill-parent-hack (#1178)
Amos Jeffries [Thu, 10 Nov 2022 05:56:30 +0000 (05:56 +0000)] 
Remove --enable-kill-parent-hack (#1178)

This feature has been deprecated for some time.

The useful functionality can more safely be implemented in the parent
script by using the --foreground command line option and waiting for
the Squid process to exit.

It has always been labeled dangerous as the parent process can be
PID 1 or some other vital system process than the intended
RunCache script. Currently it breaks SMP support for manually
killing a single worker or disker process.

18 months agoSort CA certificates in tls-cert=bundle (#1177)
Alex Rousskov [Thu, 10 Nov 2022 02:01:29 +0000 (02:01 +0000)] 
Sort CA certificates in tls-cert=bundle (#1177)

... as opposed to requiring the bundle to contain CA certificates in the
correct on-the-wire/issuing order and warning about (and then ignoring)
out-of-order bundled certificates.

This enhancement makes it easier to configure Squid to send the right
intermediate certificates, especially during certificate upgrades when
intermediate certificates (which may be obtained from a source not
tightly coordinated with the signing certificate source) is likely to
contain a mix of old and new intermediate certificates.

Squid has to (and did) check the certificate issuing order anyway. The
new code uses very similar checks to sort intermediate certificates.

No on-the-wire changes expected for Squid configurations that have
correctly ordered certificate bundles. Other configurations may start
sending the previously missing intermediate certificates.

18 months agoImprove cache_peer reporting and NetDB cache_peer search (#1174)
Alex Rousskov [Wed, 9 Nov 2022 21:29:33 +0000 (21:29 +0000)] 
Improve cache_peer reporting and NetDB cache_peer search (#1174)

Squid used several cache_peer configuration components and CachePeer
fields to identify cache peers in code and cache.log messages: (the
lowercase version of) cache_peer hostname, cache_peer (hostname,
http_port) tuple, and cache_peer name=value (which uses cache_peer
hostname by default).

Inconsistent identification led to admin confusion (e.g., a message
about cache_peer A was misinterpreted as being about cache_peer B) and
bugs (e.g., indexing storage by component X, but searching using
component Y). This change cements a single component as a unique
cache_peer identifier: CachePeer::name.

Also reject configurations with cache_peer naming errors in
cache_peer_access and neighbor_type_domain directives (instead of
reporting but otherwise ignoring the problematic configuration lines).

The following CachePeer reporting principles were used:

* To identify a specific cache_peer p (among all the configured ones) in
  a cache.log message, print that peer (i.e. use `os << *p` or
  equivalent). CachePeer printing code will print that peer name, which
  is guaranteed to be unique across all configured cache_peers.

* After identifying a cache_peer, do not dump its various details like
  ICP port numbers, especially when they are not relevant to the message
  (i.e. provide no useful context-related information going beyond that
  cache_peer identification).

The following bugs were fixed:

* NetDB code is storing cache_peer hostname[1] but was searching for a
  cache_peer with a matching name[2] and, hence, usually failing to find
  explicitly named cache_peers. Probably broken since 2003 commit
  be75332 that added name=value support and updated peerFindByName() to
  use CachePeer::name but left storage code[1] unchanged.

    [1] netdbPeerAdd(): p->peername = netdbPeerName(e->host);
    [2] netdbClosestParent(): p = peerFindByName(h->peername);

* netdbClosestParent() could not find the closest cache_peer in certain
  cases involving multiple cache_peers with the same hostname because
  the code incorrectly stopped looking for eligible same-hostname
  cache_peers after correctly discarding the first one.

  The above NetDB problems may imply that NetDB code needs to be
  refactored to store CachePeer pointers instead of CachePeer hostnames,
  but that serious change deserves more analysis (and a dedicated PR).

* cache_peer name=value configurations with empty/missing name value
  could dereference a null name pointer while misleading developers into
  thinking that a previously set name could be erased/forgotten. Squid
  now rejects such configurations.

* neighborIgnoreNonPeer() was allocating CachePeer::host using new() but
  ~CachePeer is freeing its host data member using xfree().

Also removed peerFindByNameAndPort() unused since inception at db1cd23.

18 months agoCI: Assume recent CI fixes make busy-restart test stable (#1172)
Alex Rousskov [Sat, 29 Oct 2022 20:09:53 +0000 (20:09 +0000)] 
CI: Assume recent CI fixes make busy-restart test stable (#1172)

18 months agoCI: Fix support for running a subset of GitHub Actions tests (#1171)
Alex Rousskov [Mon, 24 Oct 2022 03:18:06 +0000 (03:18 +0000)] 
CI: Fix support for running a subset of GitHub Actions tests (#1171)

The scripts were always running all/default tests instead of those named
on the command line (if any). Broken since inception in commit 2ed8cc4.

19 months agoMimic GET reforwarding decisions when our CONNECT fails (#1168)
Eduard Bagdasaryan [Sat, 22 Oct 2022 19:44:50 +0000 (19:44 +0000)] 
Mimic GET reforwarding decisions when our CONNECT fails (#1168)

Use FwdState::reforwardableStatus() logic when deciding whether to
reforward our CONNECT request after a failed tunneling attempt.

Also honor forward_max_tries limit when retrying tunneling attempts.

These TunnelStateData fixes deal with ordinary CONNECT traffic (no
SslBump). FwdState also handles CONNECT requests (with SslBump). We make
that CONNECT handling more consistent across these classes (in addition
to making it more consistent across CONNECT and GET/etc. methods).

Co-authored-by: Alex Rousskov <rousskov@measurement-factory.com>
19 months agoMaintenance: Drop an unused, misleading condition (#1169)
Alex Rousskov [Fri, 21 Oct 2022 15:57:49 +0000 (15:57 +0000)] 
Maintenance: Drop an unused, misleading condition (#1169)

According to Autoconf NEWS, AC_USE_SYSTEM_EXTENSIONS is defined with
AC_DEFUN_ONCE since Autoconf v2.63b: "This means a subtle change in
semantics; previously, an AC_DEFUN macro could expand [this macro]
multiple times or surround the macro inside shell conditional text to
bypass [its] effects, but now the macro will expand exactly once, and
prior to the start of any enclosing AC_DEFUN macro".

In the generated ./configure script, the if statement no longer had any
code inside it, and AC_USE_SYSTEM_EXTENSIONS was unconditionally
expanded above the if statement.

19 months agoFix milliseconds in certain cache.log messages (#1167)
Eduard Bagdasaryan [Wed, 19 Oct 2022 12:52:47 +0000 (12:52 +0000)] 
Fix milliseconds in certain cache.log messages (#1167)

This change fixes two bugs:

1. The milliseconds part of an early message time was wrong because
   debugLogTime() got it from the current_time global instead of the
   saved message timestamp. This problem probably affected only early
   saved messages in rare situations where current_time was updated
   between message creation and message writing. This fix adjusts
   DebugMessageHeader::timestamp to store message time with microsecond
   precision.

2. Level-0/1 messages that followed same-second level-2+ messages were
   logged with an unwanted (and stale) milliseconds value. This fix
   forces a reset of the message line format buffer in relevant cases.

19 months agoCI: Install all known dependencies for test-builds.sh on GitHub (#1162)
Amos Jeffries [Mon, 17 Oct 2022 17:27:07 +0000 (17:27 +0000)] 
CI: Install all known dependencies for test-builds.sh on GitHub (#1162)

The apt-get build-dep trick makes us dependent on Ubuntu decisions, but
it saves us work, and we can always add more dependencies manually if we
discover holes in the Ubuntu-maintained list.

Co-authored-by: Alex Rousskov <rousskov@measurement-factory.com>
19 months agoBug 5241: Block all non-localhost requests by default (#1164)
Alex Rousskov [Mon, 17 Oct 2022 13:22:34 +0000 (13:22 +0000)] 
Bug 5241: Block all non-localhost requests by default (#1164)

This change goes one step further than commit 6d2f8ed in satisfying the
same "by default, introduce no new attack vectors" principle.

Commit 6d2f8ed blocked access to localhost and to-link-local services
but still allowed access to potentially vulnerable popular cloud
instance metadata services running on site-local IPv6 addresses. It also
still allowed external access to localnet services that could be
completely unprepared for such dangers! This change closes those holes.

This default configuration has two extra deny rules. These rules become
necessary only when the admin adds an "http_access allow" rule below
them. We enabled these rules despite their overheads, including more DNS
queries in some environments, so that the admin does not have to
remember to enable them when following our "INSERT...HERE" instructions.

19 months agoFix ./configure detection of various LDAP functions (#1163)
Alex Rousskov [Sun, 16 Oct 2022 21:59:28 +0000 (21:59 +0000)] 
Fix ./configure detection of various LDAP functions (#1163)

Commit 0d57ed2 started using $LIBLDAP_LIBS as AC_CHECK_LIB() argument,
but that does not work because AC_CHECK_LIB() expects a library name (X)
rather than a linker option (-lX). The macro adds a "-l" prefix itself:

    checking for ldap_url_desc2str in -l-lldap -llber... no
    checking for ldap_url_parse in -l-lldap -llber... no
    checking for ldap_start_tls_s in -l-lldap -llber... no

19 months agoAvoid negative test-builds.sh results due to lack of LDAP (#1158)
Alex Rousskov [Tue, 11 Oct 2022 15:29:42 +0000 (15:29 +0000)] 
Avoid negative test-builds.sh results due to lack of LDAP (#1158)

    TESTING: layer-02-maximus
    BUILD: test-suite/buildtests/layer-02-maximus.opts
    configure: error: Required library ldap not found

Broken by commit 0d57ed2.

19 months agoBug 5241: Block to-localhost, to-link-local requests by default (#1161)
Alex Rousskov [Mon, 10 Oct 2022 23:07:02 +0000 (23:07 +0000)] 
Bug 5241: Block to-localhost, to-link-local requests by default (#1161)

Squid suggested blocking to-localhost access since 2001 commit 4cc6eb1.
At that time, the default was not adjusted because some use cases were
known to require to-localhost access. However, the existence of special
cases should not affect defaults! The _default_ configuration should
either block all traffic or only allow traffic that is unlikely to
introduce new attack vectors into the network.

Also block to-link-local traffic (by default), for very similar reasons:
Popular cloud services use well-known IPv4 link-local (i.e. RFC 3927)
addresses (a.k.a. APIPA), to provide sensitive instance metadata
information, via HTTP, to instance users and scripts. Given cloud
popularity, those special addresses become nearly as ubiquitous as
127.0.0.1. Cloud provider networks shield metadata services from
external accesses, but proxies like Squid that forward external HTTP
requests may circumvent that protection.

19 months agoStart using Github Actions for CI tests (#1160)
Alex Rousskov [Mon, 10 Oct 2022 04:24:22 +0000 (04:24 +0000)] 
Start using Github Actions for CI tests (#1160)

This change imports existing Sempaphore CI functionality test harness
and migrates it to Github Actions. Using a stand-alone harness offered
many advantages, but that approach goes against the current custom of
importing CI configurations into being-tested repositories. Semaphore CI
itself switched to such invasive configurations since v2. We have to
start using invasive CI configurations to be able to evolve Squid CI and
solve known CI problems.

While importing the test harness, we made basic CI functionality tests
available from the command line so that developers can run them even
before submitting a PR and while addressing reviewer concerns. They do
require internet access because the tests are downloaded from GitHub,
but they avoid permanent service installations in developer environment.
The tests do create/overwrite logs and start services like Squid. A lot
more work is still required to make these tests user friendly.

The new test configuration/harness consists of two primary parts:

* Github Actions "workflow" configuration, including embedded scripts.
* Various test scripts used by the "workflow" configuration above.

There are many ways to split the test harness among those two parts.
This particular split is based on these split-specific principles/ideas:

1. When running tests locally, developers do not want to risk
   disruptive, permanent, potentially dangerous actions such as globally
   installing new packages or overwriting checked out Squid sources.
   These actions belong to the workflow configuration file that is only
   interpreted by Github Actions, on Github virtual machines. The test
   scripts have only one sudo command (to start a Squid manipulating
   agent as nobody) which is bypassed of the agent is already running.

2. Developers should be able to repeat basic tests from the command
   line, against their version of Squid sources, their Squid builds, and
   without learning the ever-changing testing details. If their PR has
   failed a CI test, they may simple want to run the corresponding
   script locally to reproduce the issue. This means that nearly all
   testing logic belongs to the test scripts, not the Actions
   configuration file (that developers cannot easily interpret/apply).

We also thought that some developers would want to separate
functionality from code quality tests (because those are often applied
at different development stages) and to repeat (many times) just the
failed test case (because that often helps when triaging and fixing
bugs). These considerations resulted in the creation of two scripts,
each accepting individual test case names as optional parameters:

* test-suite/test-functionality.sh
* test-suite/test-sources.sh

19 months agoFix GCC build on macos-11: -Wunused-parameter (#1159)
Alex Rousskov [Tue, 4 Oct 2022 13:26:08 +0000 (13:26 +0000)] 
Fix GCC build on macos-11: -Wunused-parameter (#1159)

19 months agoReport (problems with) DEAD-at-start cache_peers (#1155)
Alex Rousskov [Thu, 29 Sep 2022 21:03:06 +0000 (21:03 +0000)] 
Report (problems with) DEAD-at-start cache_peers (#1155)

When a cache_peer is (re)configured, Squid probes its address using a
throw-away TCP connection. If and only if that TCP probe succeeds, peer
selection algorithms may pick the peer. Until then, the cache_peer is
treated as if it was DEAD.

This change preserves the logic summarized above but starts _reporting_
the initial probe failure and the fact that it marks the cache_peer
DEAD. Without these reports, admins often naturally assume that the
cache_peer is alive, especially if traffic can be served without it.

19 months agoFix 'warning: stray \ before white space' (#1150)
Amos Jeffries [Wed, 28 Sep 2022 18:17:35 +0000 (18:17 +0000)] 
Fix 'warning: stray \ before white space' (#1150)

grep 3.8 started detecting overly-escaped regex patterns

19 months agoRedux broken krb5.h handling (#1156)
Amos Jeffries [Tue, 27 Sep 2022 21:05:14 +0000 (21:05 +0000)] 
Redux broken krb5.h handling (#1156)

De-duplicate the #include sequence into a libcompat header to
ensure all uses of the hack(s) including autoconf test macros
are using the same logic. This fixes some macros which were
using inconsistent logic for Solaris.

Simplify the if-elif use of __cplusplus detection. All the
extern C hacks apply only when C++ is used.

Wrapping the entire file peer_proxy_negotiate_auth.cc with
'extern C {...}' is unnecessary (it is a .cc) and breaks the
Solaris workaround.

19 months agoImprove LDAP library detection (#1148)
Amos Jeffries [Sat, 24 Sep 2022 11:52:35 +0000 (11:52 +0000)] 
Improve LDAP library detection (#1148)

Add --with-ldap and pkg-config support to speed up Squid builds
where LDAP is not to be used. This also adds support for custom
LDAP library locations like other --with-foo options.

'pkg-config --libs ldap' finds both -lldap and -llber. Stop using
different variables for them in Makefile.am.

Extract LDAP API tests into simpler dedicated macros and stop
polluting LIBS when running LDAP tests.

20 months agoRename ./configure option --with-libcap to --with-cap (#1140)
Amos Jeffries [Fri, 23 Sep 2022 13:26:23 +0000 (13:26 +0000)] 
Rename ./configure option --with-libcap to --with-cap (#1140)

The 'lib' prefix is supposed to be omitted from --with/--without
names but libcap was not correctly named.

Also, add support for pkg-config library auto-detection.

20 months agoFix ./configure detection of libxml2 headers (#1153)
Alex Rousskov [Thu, 22 Sep 2022 03:41:10 +0000 (03:41 +0000)] 
Fix ./configure detection of libxml2 headers (#1153)

    checking for LIBXML2... yes
    checking libxml/parser.h usability... yes
    checking libxml/parser.h presence... no
    configure: WARNING: libxml/parser.h: accepted by the compiler,
               rejected by the preprocessor!
    configure: WARNING: libxml/parser.h: proceeding with the compiler's
               result

PKG_CHECK_MODULES() documentation warns that it uses a "misleading" name
for the foo_CFLAGS variable it sets: "the variable provides the flags to
pass to the preprocessor, rather than the compiler". Lots of Squid code
has been mislead by that macro, but this fix is specific to a recent
regression introduced in commit 866a092. TODO: Fix all others.

20 months agoFix ./configure tests (#1151)
Alex Rousskov [Wed, 21 Sep 2022 23:53:12 +0000 (23:53 +0000)] 
Fix ./configure tests (#1151)

Many tests broken by recent commit a1c2236 supplying empty input to
AC_LINK_IFELSE() macro in SQUID_CC_CHECK_ARGUMENT. Empty input results
in no test file created by the macro (and, presumably, a failed linking
test). Observable symptoms (in some environments) include many repeated
errors on ./configure stderr:

    sed: can't read conftest.cpp: No such file or directory

Also fixed a similar SQUID_SEARCH_LIBS() bug. That macro was broken
since inception (commit 391f0ba). It is currently only used for the
mingw-specific SQUID_CHECK_WINSOCK_LIB check. This change is untested.

20 months agoFix escaping leading regex dashes in ./configure sources (#1152)
Alex Rousskov [Wed, 21 Sep 2022 13:53:22 +0000 (13:53 +0000)] 
Fix escaping leading regex dashes in ./configure sources (#1152)

    grep: invalid option -- 't'
    Usage: grep [OPTION]... PATTERNS [FILE]...
    Try 'grep --help' for more information.

    Usage: grep [OPTION]... PATTERNS [FILE]...
    Try 'grep --help' for more information.
    ./configure: line 27524: test: too many arguments

    Usage: grep [OPTION]... PATTERNS [FILE]...
    Try 'grep --help' for more information.
    ./configure: line 27698: test: too many arguments

Configure scripts are written in m4, not shell. M4 treats [square
brackets] specially. We could use quadrigraphs instead (as documented in
autoconf manual) but `(-)` looks a lot simpler than `@<:@-@:>@`!

20 months agoFixed comm.cc:644: "address.port() != 0" assertion (#1149)
Alex Rousskov [Mon, 19 Sep 2022 14:07:47 +0000 (14:07 +0000)] 
Fixed comm.cc:644: "address.port() != 0" assertion (#1149)

IPC code creating a TCP socket pair for communication with helpers used
comm_open() to create a _listening_ socket, misleading Comm into
applying IP_BIND_ADDRESS_NO_PORT optimization that delays port
assignment until connect(2) (which is never called for listening
sockets). Listening sockets must be opened using comm_open_listener(),
but the IPC use case was missed in 2009 commit 31be869 that introduced
comm_open_listener(). IP_BIND_ADDRESS_NO_PORT changes in recent commit
74d7d19 hit that bug.

Disclaimer: Windows-specific code adjusted without testing.

20 months agoCleanup libsystemd variables (#1147)
Amos Jeffries [Mon, 19 Sep 2022 12:14:39 +0000 (12:14 +0000)] 
Cleanup libsystemd variables (#1147)

Rename SYSTEMD_LIBS and related `*_CFLAGS` / `*_PATH` variables to
`LIBSYSTEMD_*` prefix in line with other libraries naming style.

Polish detection log outputs in line with other libraries.

Fix pollution of global LDFLAGS variable.

Also, expand possible -lsystemd builds beyond Linux. Some OS provide a
library for compatibility. Cross-builds can also need to link against
systemd.

20 months agoDo not check unused RECV_ARG_TYPE (#1146)
gkinkie@gmail.com [Sun, 18 Sep 2022 23:58:37 +0000 (23:58 +0000)] 
Do not check unused RECV_ARG_TYPE (#1146)

The check and corresponding defined preprocessor value
are not used anywhere in the code; remove the check

20 months agoCleanup libexpat variables (#1143)
Amos Jeffries [Sun, 18 Sep 2022 19:19:21 +0000 (19:19 +0000)] 
Cleanup libexpat variables (#1143)

... to use pkg-config compatible naming and take advantage of
squid provided macros better.

Also, add support for pkg-config library auto-detection.

20 months agoCleanup libxml2 variables (#1145)
Amos Jeffries [Sun, 18 Sep 2022 05:40:09 +0000 (05:40 +0000)] 
Cleanup libxml2 variables (#1145)

... to use pkg-config compatible naming and take advantage of
squid provided macros better.

Remove unnecessary path detection of /usr vs /usr/local
locations. Admin can use --with-foo=PATH to provide any needed
customization of those from whichever is standard for the build
environment.

20 months agoCleanup libnettle detection (#1144)
Amos Jeffries [Sat, 17 Sep 2022 11:01:26 +0000 (11:01 +0000)] 
Cleanup libnettle detection (#1144)

... to use pkg-config compatible variable naming and break out
the code test to a dedicated macro per the style used by other
libraries.

Also, add support for pkg-config library auto-detection.

Also, our libcompat provides local replacement for Base64 on
builds with older libnettle. Fix the library link order to
ensure our functions get linked properly.

20 months agoDo not lock an SMP hit twice for the same transaction (#1134)
Alex Rousskov [Thu, 15 Sep 2022 07:16:50 +0000 (07:16 +0000)] 
Do not lock an SMP hit twice for the same transaction (#1134)

Before commit 4310f8b, anchorToCache() (known then as anchorCollapsed())
was only called for not-yet-anchored entries. For anchored entries, we
called updateCollapsed(). In that commit, a new anchorToCache() caller
(i.e. allowSharing() after peek()) started calling anchorToCache() for
all entries, but anchorToCache() code was not updated to skip anchoring
of anchored entries, leading to an extra read lock placed on a peek()ed
hit entry. The extra lock prevented the entry slot from being reused for
other entries when the entry was later purged (i.e. marked for removal),
drastically decreasing hit ratio in some environments.

Fixed anchorToCache() no longer anchors anchored entries. To make sure
we covered all callers/cases, especially in patches, we changed the call
parameters, addressing an old code simplification TODO.

20 months agoFix 'warning: stray \ before -' (#1141)
Amos Jeffries [Thu, 15 Sep 2022 01:14:17 +0000 (01:14 +0000)] 
Fix 'warning: stray \ before -' (#1141)

grep 3.8 started detecting overly-escaped regex patterns

20 months agoBug 5232: Fix GCC v12 build [-Wuse-after-free] (#1136)
Eduard Bagdasaryan [Wed, 14 Sep 2022 06:47:52 +0000 (06:47 +0000)] 
Bug 5232: Fix GCC v12 build [-Wuse-after-free] (#1136)

This warning is a false positive. Introduced in GCC v12, use-after-free
checks have attracted dozens of bug reports, with several reports still
open as of GCC v12.2, including one that looks very similar to our case:
https://gcc.gnu.org/bugzilla//show_bug.cgi?id=106776

Removing (excessive) "inline" works around this GCC bug. We do not have
a better workaround right now. If we see more false positives like this,
we may disable -Wuse-after-free until its support matures.

20 months agoFix cppunit version detection (#1142)
Amos Jeffries [Tue, 13 Sep 2022 12:19:16 +0000 (12:19 +0000)] 
Fix cppunit version detection (#1142)

20 months agoFix 'AC_LINK_IFELSE was called before AC_USE_SYSTEM_EXTENSIONS' (#1139)
Amos Jeffries [Tue, 13 Sep 2022 07:25:36 +0000 (07:25 +0000)] 
Fix 'AC_LINK_IFELSE was called before AC_USE_SYSTEM_EXTENSIONS' (#1139)

... produced during bootstrap.sh by autoconf 2.71

AC_USE_SYSTEM_EXTENSIONS needs to be placed after detecting
which OS and compiler are being used. But before any of the
checks detecting capabilities of those OS and compilers.

AC_CANONICAL_HOST is a prerequisite of the simple_host_os logic.
Attach it to that code block instead of the compiler detection
block.

Replace deprecated '$GCC' variable with autoconf cached
'$ac_cv_c_compiler_gnu' variable used as the real source for the
yes/no value of GCC usability after AC_PROG_CC.

20 months agoImprove SQUID_YESNO error messages (#1137)
Amos Jeffries [Sun, 11 Sep 2022 23:27:18 +0000 (23:27 +0000)] 
Improve SQUID_YESNO error messages (#1137)

This macro performs a very specific validation check but was
passed a mix of different error messages to display on failure.
Many of which were unclear or wrong.

Move the text of the error inside the macro to enforce
consistency and accuracy about what failed. It actually only
needs to be passed the name of the ./configure options which
was configured badly.

Also, the options configured can only take the positive form
when they fail '--with-foo=X' or 'enable-foo=X' so update the
second argment to always show that form regardless of whether
the configure.ac logic has it default enabled or disabled.

Also, fixed a bug in --with-nat-devpf validation which was
testing the wrong variable (enableval). This bug only affects
the errors displayed so no builds were significantly affected.

20 months agoReplaced FDECB callback with a basic async call (#1135)
Eduard Bagdasaryan [Sun, 11 Sep 2022 17:24:48 +0000 (17:24 +0000)] 
Replaced FDECB callback with a basic async call (#1135)

The "FD passing callback" was misleading because it was not used as a
callback. We just need an async call with a known-to-the-caller
parameter instead. Simplifying CommCalls (by removing this "special
callback") helps improve that API.

20 months agoRename ./configure option --with-libxml2 to --with-xml2 (#1138)
Amos Jeffries [Fri, 9 Sep 2022 11:41:21 +0000 (11:41 +0000)] 
Rename ./configure option --with-libxml2 to --with-xml2 (#1138)

The 'lib' prefix is supposed to be omitted from
--with/--without names but libxml2 was not
correctly implemented from inception.

20 months agoUpdate configure.ac scripts (#937)
Amos Jeffries [Wed, 7 Sep 2022 19:02:11 +0000 (19:02 +0000)] 
Update configure.ac scripts (#937)

Various cleanup changes to reduce the size of autoconf scripts and
remove deprecated macros causing build warnings with autoconf v2.71.

20 months agoSource Format Enforcement (#1132)
squidadm [Tue, 6 Sep 2022 02:59:32 +0000 (02:59 +0000)] 
Source Format Enforcement (#1132)

20 months agoReplaced most custom high-level callbacks with a unified API (#1094)
Alex Rousskov [Sun, 4 Sep 2022 23:40:41 +0000 (23:40 +0000)] 
Replaced most custom high-level callbacks with a unified API (#1094)

Regular asynchronous calls remember call arguments at call creation
time, when the type of the call is well known. Service callbacks do not
know call arguments until it is time for the service to (asynchronously)
call the previously supplied callback. Thus, the service has to get
access to call parameters inside the stored generic (from service
p.o.v.) async call pointer. Services got that access by declaring a
custom callback dialer class and expecting the service user code to use
that dialer when creating an async call object. That was problematic:

1. Each service class had to create nearly identical dialer classes, at
   least one for each unique answer type. Code duplication was rampant.
2. Each service dialer class was specific to one service user type
   (e.g., HappyConnOpener answer dialer did not support AsyncJob users).
3. A compiler could not check whether the service got the right
   callback: A dynamic_cast operation converted a generic dialer to the
   service-declared dialer class, asserting the right type at runtime.

This change replaces all but one custom service callback with three
general service-independent dialers, one for each callback style: a job
call, a call to a cbdata-protected class method, and a stand-alone
function call. This unified API solves problem 1 mentioned above. A new
Callback template supports all three dialers (addressing problem 2) and
checks the callback answer type at compile time (addressing problem 3).

Replaced custom HappyConnOpener, Security::PeerConnector, Downloader,
CertValidationHelper, Http::Tunneler, Ipc::Inquirer, and most
Ipc::StartListening() callbacks (and more such callbacks would have been
added by upcoming PRs!). Kept ListeningStartedDialer as detailed below.

Replaced Ipc::Inquirer callback with a regular call: The class does not
need a callback mechanism because it can (and should and now does)
create an async call from scratch when the call arguments become known.

Kept ListeningStartedDialer because client_side.cc relies on delivering
additional, non-answer parameters with the callback. Normally, this
additional information is stored inside the job object. In this case, no
job awaits the port opening, so we use a custom dialer hack to keep that
information during the wait. Improving that code is out of scope. This
may be the only custom high-level callback left in the code!

The asyncCall() return type improvement preserves the exact AsyncCall
type for the Callback constructor to pick up. It will also remove
explicit/imprecise AsyncCall::Pointer uses throughout the code.

Also fixed reporting of small responses received by Downloader.

Unfortunately, we cannot easily unify the old JobCallback() with the new
asyncCallback() because we do not yet know how to detect that we need to
use one of the Comm-specific dialers (e.g., CommCbMemFunT) that feed the
job pointer to the CommCommonCbParams constructor. CommCommonCbParams do
not have a default constructor because they require, probably
incorrectly, that the recipient (e.g., job) pointer is stored together
with the future callback argument(s). This is why JobCallback() requires
a Dialer as a parameter -- it does not know how to guess it either. Comm
callback improvements will need a dedicated PR.

20 months agoStop (ab)using Transient entry flags for CF requirement mngmt (#1127)
Alex Rousskov [Fri, 2 Sep 2022 17:14:12 +0000 (17:14 +0000)] 
Stop (ab)using Transient entry flags for CF requirement mngmt (#1127)

The ENTRY_REQUIRES_COLLAPSING flag was used for relaying "hitting this
entry carries Collapsed Forwarding risks right now" info to other
workers. That flag is not necessary to relay that info because remote
workers already know whether the entry is attached to one of the shared
cache stores. Moreover, relaying that flag correctly is difficult and
would require a different implementation:

* The flag is changed in relatively high-level Store code, possibly
  _after_ we stopped writing, when the transients entry is already
  read-only. This bug leads to an isWriter() assertion in
  Transients::clearCollapsingRequirement() called via a quick or aborted
  StoreEntry::startWriting().

* Basics.flags is not an atomic field. It lacks an "[app]" mark -- its
  readers will not get a reliable value due to race conditions when
  Squid will need to update the Transient entry flags in "append" mode.

* The flag is changed assuming that simply sending stuff to disk is
  sufficient for other workers to read it. Since 18102f7, this is
  inaccurate because the store index is updated only after the slot is
  written to disk.

Remote workers now use Store attachment info to set the local StoreEntry
object flag, ignoring the no-longer-used Transients entry flags.

The ENTRY_REQUIRES_COLLAPSING flag is still used to tell transactions
which StoreEntry objects are subject to CF risks. It would be nice to
use the presence of MemObject::reply_ to relay the same info for
store-unattached entries (and attachment info for others), but we could
not find a way to do that (during commit d2a6dcb work and then again
during this project) without a lot of essentially out of scope rewrites.

Also removed misleading Ipc::StoreMapAnchor::exportInto() debugging.

20 months agoPrep for 5.7 (#1131)
Amos Jeffries [Fri, 2 Sep 2022 14:16:56 +0000 (14:16 +0000)] 
Prep for 5.7 (#1131)

20 months agoFix printing Security::ErrorDetail (#1129)
Alex Rousskov [Fri, 2 Sep 2022 11:08:48 +0000 (11:08 +0000)] 
Fix printing Security::ErrorDetail (#1129)

Squid dumps RefCount pointer details instead of the intended TLS error
details like "SQUID_TLS_ERR_ACCEPT+TLS_LIB_ERR=14094418":

    ERROR: failure while accepting a TLS connection...: 0x564017165ef0*1

We overload operator "<<" for ErrorDetail::Pointer to report errors, but
the compiler picks our generic operator "<<" overload for RefCount<C>
instead. I believe this happens because the actual type of the
being-printed handshakeResult.errorDetail object (i.e.
Security::IoResult::ErrorDetailPointer) is not ErrorDetail::Pointer but
Security::ErrorDetail::Pointer; there is no overload for the latter.

This simple solution "works" but it does not solve the underlying
problem: Other ErrorDetail kids (existing and future) and other similar
class hierarchies using RefCount pointers (e.g., Http::Message) are or
will be mishandled because of missing kid-specific overloads.

To properly address this XXX, we probably should add traits/interfaces
to all RefCountable classes that want their Pointers to be printed
specially (e.g., ErrorDetail) _and_ teach our generic operator "<<"
overload for RefCount<C> to honor those. Also, an InstanceId data member
might be recognized/printed by default instead of the memory address; it
may even be added to RefCountable.

20 months agoFewer "busy shutdown" crashes; simpler shutdown cleanup (#1128)
Alex Rousskov [Thu, 1 Sep 2022 02:34:26 +0000 (02:34 +0000)] 
Fewer "busy shutdown" crashes; simpler shutdown cleanup (#1128)

    Preparing for shutdown after 186724 requests
    Waiting 1 seconds for active connections to finish
    Closing HTTP(S) port [::]:3128
    FATAL: assertion failed: Transients.cc:192:
        "oldE->mem_obj && oldE->mem_obj->xitTable.index == index"

This change removes two steps at the end of the manual shutdown sequence
(FreeAllFs() and Store::FreeMemory()) and associated deadly Store hacks,
adjusting a few Store checks as needed. Also, StoreFileSystem hierarchy
declarations were slightly updated when half of its virtual methods were
removed. Key changes are detailed below.

### Do not disable Store [by dropping Store::Root()] during shutdown

Disabling Store (i.e. calling Store::FreeMemory()) resulted in "do not
use Root() during shutdown" assertion-avoiding hacks that bypassed code
maintaining key invariants. Those hacks were probably accommodating
Store-using destruction sequences triggered by SquidShutdown() or later
code, _but_ the hacks also ran during the graceful shutdown period!
Violating those invariants in MemObject destructor led to the quoted
assertions when CollapsedForwarding::HandleNotification() ran during
graceful shutdown.

We could add more state to narrow down hacks scope, or we could disable
IPC notifications that triggered the known deadly shutdown sequence, but

* We should not disable assertions during shutdown because many are
  about essential (e.g., preventing data corruption) invariants and
  because it is not practical to disable all assertions that should be
  disabled (and keep disabling the new ones correctly). The idea leads
  to unsafe code that is also more difficult to write and maintain.

* We should not disable kid-to-kid notifications because some are
  required for finishing transactions (that can still be successfully
  finished) during graceful shutdown. Increasing successful completion
  chances is the whole idea behind that graceful shutdown feature!

Instead, Store should provide (essential) services during shutdown.

TODO: Update those unit test cases that use Store::FreeMemory() but
should not. That requires careful analysis because the next test cases
may rely on the previous case removing its Store object/statistics/etc.
The same dedicated project might (help) address commit 27685ef TODO
about unwanted Store unit test order dependencies.

### Do not disable StoreFileSystem service during shutdown

Similar to the Store service, manually killing FS service is a bad idea.
The underlying code was also essentially unused and buggy:

* Nobody called RegisterAllFsWithCacheManager(). A caller would assert.
* Nobody called Fs::Clean(). A call could crash Squid because deleted
  objects could still be in use by others (they are not refcounted).
* SetupAllFs() was called but did essentially nothing.
* FreeAllFs() was called but had only harmful effects: It leaked memory
  and removed usable FS registrations, increasing shutdown dangers.

See also: Commit 3a85184 documents why we should avoid explicit "delete
essentialService" calls (and why some crashes may still occur if we do).

20 months agoRemove unused/disabled/broken LEAK_CHECK_MODE code (#1130)
Alex Rousskov [Wed, 31 Aug 2022 17:15:31 +0000 (17:15 +0000)] 
Remove unused/disabled/broken LEAK_CHECK_MODE code (#1130)

LEAK_CHECK_MODE had not worked since before 2006 commit afec404. The
disabled code does not compile since 2012 commit b65ce00 and would crash
current Squids during shutdown. We should not fix it because the
underlying "delete essentialService" idea is deeply flawed.

Writing correct code that uses essential modules/services that may
"suddenly" disappear or crash is nearly impossible. The trickle of
assertions due to missing Store::Root() is a case in point. These risks
and efforts are also unnecessary: We can and should build APIs that
provide essential services without disappearing or crashing. Keeping
heap-allocated service objects during shutdown helps with that.

Valgrind and other modern leak detection tools are capable of
distinguishing still-reachable at-exit memory from runtime memory leaks.
We do not need to delete all still-reachable at-exit objects to enable
that leak detection functionality.

The OS will reclaim allocated heap memory anyway.

N.B. Despite the legacy code implications, we should distinguish
low-level new/delete (a.k.a. fooInit() and fooFree()) memory management
code (which is an internal service matter that essential service users
should not be exposed to!) with configure-reconfigure-reconfigure-sync
events. There is value in notifying services about configuration
(changes) and various shutdown stages, of course. We already have the
RunnersRegistry API for handling such notifications.

Even without explicit "delete essentialService" calls, we may still have
problems during C++ post-exit() cleanup where destructors of various
globals are called "concurrently", with few order guarantees. We should
avoid non-heap-allocated globals with "complicated" destructors, but
their elimination is out of scope here.

20 months agoFixed "make check" in a --disable-auth-basic build (#1125)
Alex Rousskov [Tue, 30 Aug 2022 15:07:49 +0000 (15:07 +0000)] 
Fixed "make check" in a --disable-auth-basic build (#1125)

    FATAL: Bungled squidconf/bug4832 line 1: auth_param basic /dev/null
    FAIL: squid.conf test: squidconf/bug4832

Also added initial support for test-suite/squidconf/ tests that depend
on ./configure options/results. This framework will be extended to
support testing with invalid configuration files that Squid must reject.

Existing Squid configuration files in test-suite/squidconf/ were given a
.conf filename extension for ease of auto-distinguishing them from
.instructions files that contain testing "rules". The customary .conf
extension also improves handling of those files by humans.

20 months agoMaintenance: Remove an always-false condition (#1122)
Alex Rousskov [Tue, 23 Aug 2022 03:13:29 +0000 (03:13 +0000)] 
Maintenance: Remove an always-false condition (#1122)

The being-removed condition was added by beae59b, likely to compensate
for another bug that was later discovered and fixed in 619da1e. That fix
made the condition unnecessary and always false.

There are other problems in this code, including the misleading comment
describing the affected if statement. They will be fixed separately, and
the removal of this effectively unused code may simplify that work.

21 months agoOptimize ephemeral port reuse with IP_BIND_ADDRESS_NO_PORT (#1115)
pponakan [Mon, 22 Aug 2022 22:28:34 +0000 (22:28 +0000)] 
Optimize ephemeral port reuse with IP_BIND_ADDRESS_NO_PORT (#1115)

    commBind: Cannot bind socket ... : (98) Address already in use

When opening a TCP connection from a specific IP address (e.g., set by
tcp_outgoing_address), Squid usually lets the OS select the source port
by performing the traditional bind(2)+connect(2) sequence with zero
source port. This sequence consumes ephemeral ports at the connection
opening rate even if many destinations are unique (and, hence, could
reuse the same source port) because the OS must pick a source port at
bind(2) time, before connect(2) supplies the destination address.

Starting with v4.2, Linux supports IP_BIND_ADDRESS_NO_PORT socket option
designed to decrease ephemeral port consumption by delaying port binding
until connect(2) time. If available, Squid now uses that option when
opening any outgoing TCP connection bound to a source IP address.

21 months agoFixed StoreMap.cc "anchorAt(anchorId).reading()" assertions (#1117)
Alex Rousskov [Sun, 21 Aug 2022 05:30:25 +0000 (05:30 +0000)] 
Fixed StoreMap.cc "anchorAt(anchorId).reading()" assertions (#1117)

Squid asserted because the code could switch a transient entry from
writing to reading while the corresponding store entry was still being
(or could still be) written to the shared memory cache. For example:

1. We start as a collapsed writer.
2. We get a response and start writing to disk and shared memory caches.
3. Disk swapout fails (for any reason, including out-of-slots errors).
4. storeSwapOutFileClosed() calls transientsCompleteWriting().
5. transientsCompleteWriting() switches the entry into reading mode
   ... but we are still writing to the memory cache!

There was a somewhat related XXX in transientsCompleteWriting(), but
what that comment did not say is that if we are writing to two stores in
parallel, then the first transientsCompleteWriting() call (made when one
of the two swapouts ends) makes us a reader prematurely.

An incorrect reader status allows a Controller::syncCollapsed()
notification (to, say, a shared memory cache writer) slip past the
transients->isWriter() guard, eventually reaching the reading()
assertion.

Properly detecting the end of all store writing is difficult because the
two mostly independent writing "threads" may start/finish at seemingly
random times, in many code places, and even in different workers. To
simplify this task, Squid now limits cache writing to the worker
transaction that made the StoreEntry object public. That transaction
creates a writing Transients entry. Other transactions start as
Transients readers. The writer switches to reader when neither memory
nor disk caching can start or continue.

Also simplified Transients entry state. Squid relayed swapout errors via
the Transient entries themselves, but that is not necessary (and it
prevented the cache entry from recovering by writing to another store).
Each store entry can take care of its own swapout status/results. The
readers just need to know whether somebody may start (or is still)
writing, and we relay that info by keeping the Transients entry locked
for writing (appending, to be precise) while that condition is true.

Also fixed shared caches to recognize that no more data will be coming
in because the remote entry writer is gone. Readers still try to deliver
what they have, even if they know that the response will be truncated.

Also tried to follow the "broadcast after change, in the same context as
the change" principle in the modified code instead of relying on the
caller to broadcast after all changes. This approach may increase the
number of broadcasts, but it reduces the probability that we will miss
an important Broadcast() call. We can (and should) optimize repeated,
useless broadcasts, but that work is outside this project scope.

Also improved StoreEntry::swapOut() shutdown safety and
mayStartSwapOut() checks descriptions/order.

Also added an out-of-scope XXX.

21 months agoHonor httpd_suppress_version_string in more contexts (#1121)
Alex Rousskov [Fri, 19 Aug 2022 18:57:50 +0000 (18:57 +0000)] 
Honor httpd_suppress_version_string in more contexts (#1121)

* HTML "signature" part of generated HTTP responses to URN requests
* Server header in generated HTTP redirect responses
* boundary strings in generated HTTP 206 multipart/byteranges responses

Also document known contexts outside the configuration directive reach.
We may assert that all of them are outside the current "httpd" scope
(implied by the directive name), but admins may not know how we define
that "httpd" scope; being more explicit may reduce surprises.

21 months agoMatch ./configure --help parameter names with their defaults (#1120)
Alex Rousskov [Fri, 19 Aug 2022 15:44:09 +0000 (15:44 +0000)] 
Match ./configure --help parameter names with their defaults (#1120)

It is customary[^1] for "./configure --help" to use "--enable-foo"
spelling for default-disabled features and "--disable-foo" spelling for
default-enabled features. This custom allows admins to quickly discover
defaults without developers painstakingly documenting that default for
every parameter.

These changes are limited to "./configure --help" output. They do not
alter any defaults and do not alter non-help ./configure run outcomes.

[^1]: Example 1.1 at https://autotools.info/autoconf/arguments.html

21 months agoMake COMM_ORPHANED and COMM_REUSEPORT values distinct (#1116)
Alex Rousskov [Thu, 18 Aug 2022 23:28:05 +0000 (23:28 +0000)] 
Make COMM_ORPHANED and COMM_REUSEPORT values distinct (#1116)

Broken since inception (commit 1c2b446). The exact runtime effects (if
any) of this bug are difficult to ascertain, but it is possible that
some COMM_REUSEPORT (i.e. worker-queues port) listening connections were
not reported as incorrectly orphaned when they should have been.

21 months agoFix typo in manager ACL (#1113)
Amos Jeffries [Wed, 17 Aug 2022 23:32:43 +0000 (23:32 +0000)] 
Fix typo in manager ACL (#1113)

21 months agoAsyncJob-protect and reduce ICAP DNS lookup call chain (#1112)
Eduard Bagdasaryan [Wed, 17 Aug 2022 17:34:55 +0000 (17:34 +0000)] 
AsyncJob-protect and reduce ICAP DNS lookup call chain (#1112)

Co-authored-by: Alex Rousskov <rousskov@measurement-factory.com>
21 months agoDo not tell admins that we are replacing their .* with our .* (#1119)
Alex Rousskov [Fri, 12 Aug 2022 16:06:12 +0000 (16:06 +0000)] 
Do not tell admins that we are replacing their .* with our .* (#1119)

    acl hasHeaderFoo req_header Foo .*

    2022/08/12 11:43:27| WARNING: regular expression '.*' has only
    wildcards and matches all strings. Using '.*' instead.

Broken since RE optimization inception (commit 6564dae), but the
excessive WARNING was "invisible" to many admins until 61be1d8 started
saving early level-0/1 messages to cache.log.

21 months agoBug 3193 pt2: NTLM decoder truncating strings (#1114)
Amos Jeffries [Tue, 9 Aug 2022 23:34:54 +0000 (23:34 +0000)] 
Bug 3193 pt2: NTLM decoder truncating strings (#1114)

The initial bug fix overlooked large 'offset' causing integer
wrap to extract a too-short length string.

Improve debugs and checks sequence to clarify cases and ensure
that all are handled correctly.

21 months agoRemove send-announce (#1110)
Amos Jeffries [Tue, 9 Aug 2022 21:23:07 +0000 (21:23 +0000)] 
Remove send-announce (#1110)

This is another feature which is very much outdated and unused.

21 months agoDo not "open" Comm::Connection on oldAccept() errors (#1103)
Alex Rousskov [Tue, 9 Aug 2022 03:22:48 +0000 (03:22 +0000)] 
Do not "open" Comm::Connection on oldAccept() errors (#1103)

When Comm::TcpAcceptor::oldAccept() discovers an error, it should close
the socket it just accepted. We should use RAII to avoid leaking the
open socket, especially in the presence of multiple error detection
areas and C++ exceptions. Using the available Connection object for
controlling socket lifetime does not work well because that Connection
object often lingers well past oldAccept() -- the object delivers
various low-level error details (e.g., the remote HTTP client address of
the failed attempt) to TcpAcceptor users.

Instead of "opening" the Connection object ASAP to avoid FD leaks and
then struggling to find the right time to close it, we now delay that
opening until oldAccept() succeeds. Meanwhile, the socket lifetime and
Comm registration are controlled by a simple RAII Descriptor object.

Eventually, we will reuse Comm::Descriptor in Connection and other
descriptor-owning code. One known prerequisite for those improvements is
Optional<> support for non-trivial types (a work in progress).

21 months agoUnify r.n.g. seed generation (#1109)
Alex Rousskov [Mon, 8 Aug 2022 16:10:06 +0000 (16:10 +0000)] 
Unify r.n.g. seed generation (#1109)

Using time-based expressions for seeding pseudo random number generators
often results in multiple SMP workers getting the same seed. That, in
turn, may result in unwanted correlation of supposed-to-be-independent
worker activities: making artificially similar decisions (that are
supposed to be "random") and/or concentrating rather than
spreading/sharing load.

The recently added RandomUuid code did not use time-based seeds in
anticipation of this unification.

This change converts all std::mt19937 users in src/ except the random
ACL code (that probably deserves a dedicated change).

C++ standard does not guarantee that std::random_device does not force
users to wait while more entropy is accumulated. Based on public
comments and source code analysis of popular STL implementations, we
should be getting the desired no-wait behavior from popular STLs, in
popular environments. If Squid encounters a special environment where
the default std::random_device waits for entropy, more code and/or
configuration options will be needed to accommodate that special case.
The biggest drawback with this approach is that it may be difficult for
the admins to discover that std::random_device is waiting in their
environment. This is mitigated by the low probability of that happening.

21 months agoMaintenance: Improve stability of generated debug-sections.txt (#1101)
Alex Rousskov [Sun, 7 Aug 2022 14:59:20 +0000 (14:59 +0000)] 
Maintenance: Improve stability of generated debug-sections.txt (#1101)

Pure "sort" may not produce stable results across different locales.
This may explain why the official order changed in commit 502bcc7 and
why current runs in some unofficial environments reorder sections.

Also fixed two minor problems:
* "sort -n" (i.e. numeric sort) was applied to non-numeric fields
* "sort -u" (i.e. unique sort) was pointlessly applied multiple times

21 months agoMaintenance: Improve stability of gperf-generated sources (#1099)
Alex Rousskov [Tue, 2 Aug 2022 23:24:40 +0000 (23:24 +0000)] 
Maintenance: Improve stability of gperf-generated sources (#1099)

Control gperf from source-maintenance.sh: Existing Makefile rule did not
use (and should not use) primary "make" functionality -- we do not want
to automatically trigger RegisteredHeadersHash.cci regeneration based on
file timestamps alone because most users will not have (the right
version of) gperf and (the right version of) astyle available. The rule
did use Makefile variables, but that resulted in unstable gperf output
because variables like $src change depending on the developer build
environment. This change finishes the move started by commit 3d50bea.

Simplify formater.pl, making its interface similar to other formatting
tools used by source-maintenance.sh: The script now sends its results to
stdout. Renamed the script to reduce surprises, fix the old naming typo,
and to improve consistency with format-makefile-am.pl. The script needs
more polishing; we avoided otherwise unmodified lines except removing an
unused buggy $pfx line that triggered warnings.

Move "astyle did not corrupt code" checks from source-maintenance.sh to
formater.pl, where they belong and are easier to implement. This move
simplifies reuse of the Perl script inside source-maintenance.sh. It
also removes dependency on md5sum/etc. $CppFormatter now contains the
exact command to (re)use.

Fix "Generated by.." marker. Its old location in .cci was hard to
notice. The marker was also present in hand-edited .gperf file!

Report RegisteredHeadersHash.cci changes.

Also stopped stripping "register" from gperf output. Gperf v3.1 stopped
adding "register" to C++ output. We (should) use that gperf version.
Removing "register" complicated gperf error handling because a pipe to
sed ate gperf exit code.

21 months agoFix build on arm32 (#1108)
Francesco Chemolli [Sun, 31 Jul 2022 21:32:19 +0000 (21:32 +0000)] 
Fix build on arm32 (#1108)

On arm32, size_t and long are 32 bits in size, exposing these bugs.

21 months agoSupport non-trivial Optional values (#1106)
Alex Rousskov [Sat, 30 Jul 2022 01:12:17 +0000 (01:12 +0000)] 
Support non-trivial Optional values (#1106)

Commit 7224761 skipped this std::optional feature when adding initial
Optional implementation because that feature is difficult to support.
However, several in-progress projects now need to make non-trivial
objects Optional. This implementation maintains key Optional invariants,
matching those of std::optional:

* A valueless Optional object does not construct or destruct the value.
* A valued Optional object supports move/copy ops supported by value.

Maintaining the first invariant is tricky:

* Union prevents value construction/destruction in a valueless Optional.
* Explicit destructor call destructs the value in a _valued_ Optional.
* A dummy union member works around a C++ requirement for constexpr
  unions to have at least one active (i.e. initialized) member. Since a
  valueless Optional cannot initialize the value, we need another union
  member that we can initialize.
* We use an _anonymous_ union because C++ places more requirements on
  named unions, triggering a more complex implementation with
  placement-new and to-be-deprecated std::aligned_storage_t tricks!

XXX: This simplified implementation violates the following std::optional
invariant. We believe that this violation does not hurt the current and
foreseeable Squid code. In our tests, optimizing compilers still
optimize Optional<Trivial> destructors away.

* std::optional<Value> is trivially destructible if Value is.

21 months agoUse ThisCache2 buffer size when filling ThisCache2 buffer (#1102)
Roie Rachamim [Fri, 29 Jul 2022 23:16:33 +0000 (23:16 +0000)] 
Use ThisCache2 buffer size when filling ThisCache2 buffer (#1102)

21 months agoMaintenance: Trigger -Wswitch in more build environments (#1104)
Alex Rousskov [Wed, 27 Jul 2022 18:11:52 +0000 (18:11 +0000)] 
Maintenance: Trigger -Wswitch in more build environments (#1104)

When a developer forgets to update RawSwapMetaTypeTop() after adding a
new SwapMetaType item, the function should produce a -Wswitch compiler
warning (at least). However, we discovered that many compilers remain
silent, apparently confused by the constant switch expression:

* GCC warns only starting with v9.1;
* clang does not warn at all (up to v14, inclusive).

Adding a non-constant variable triggers the expected -Wswitch warnings
in clang and earlier GCC versions. Optimizing compilers (-O1) remove the
otherwise unused variable so adding it has no runtime cost.

Declaring the variable outside the switch statement is required to avoid
an unwanted -Wunused-variable warning with GCC v4.8 and clang v3.0.0.

A post-switch return statement is required to avoid an unwanted
-Wreturn-type warning with GCC v4.9.

Tests: https://gcc.godbolt.org/z/d1czs4c8e

21 months agoRemove support for Gopher protocol (#1092)
Alex Rousskov [Tue, 26 Jul 2022 15:05:54 +0000 (15:05 +0000)] 
Remove support for Gopher protocol (#1092)

Gopher code quality remains too low for production use in most
environments. The code is a persistent source of vulnerabilities and
fixing it requires significant effort. We should not be spending scarce
Project resources on improving that code, especially given the lack of
strong demand for Gopher support.

With this change, Gopher requests will be handled like any other request
with an unknown (to Squid) protocol. For example, HTTP requests with
Gopher URI scheme result in ERR_UNSUP_REQ.

Default Squid configuration still considers TCP port 70 "safe". The
corresponding Safe_ports ACL rule has not been removed for consistency
sake: We consider WAIS port safe even though Squid refuses to forward
WAIS requests:

    acl Safe_ports port 70          # gopher
    acl Safe_ports port 210         # wais

22 months agoFix handling of bad SNMP variable type when parsing IP_* vars (#1097)
Alex Rousskov [Sun, 24 Jul 2022 18:56:53 +0000 (18:56 +0000)] 
Fix handling of bad SNMP variable type when parsing IP_* vars (#1097)

AFAICT, we never associate snmp_netIpFn() with the wrong variable type,
so we may be dealing with a bug in an effectively unreachable code here.

1999 commit 736eb6a correctly removed snmp_var_free() call from most
refactored SNMP functions but missed snmp_netIpFn() and
snmp_meshCtblFn() cases. The latter was fixed in 2000 commit d20b1cd.

Detected by static analyzer Svace v3.2.1.

22 months agoRFC 9111: Stop treating Warning specially (#1072)
Amos Jeffries [Sat, 23 Jul 2022 23:14:23 +0000 (23:14 +0000)] 
RFC 9111: Stop treating Warning specially (#1072)

RFC 9111 obsoletes the Warning header, removing all specification
requirements about it. Likewise, this update changes Squid behaviour in
regards to that header:

1) Squid no longer adds Warning headers to generated or forwarded
   messages. Miss responses from servers/peers and hits cached by an
   older version of Squid may still have Warning headers.

2) On 304 revalidation, Warning header are treated the same as any
   other/generic header. They are added or replaced according to their
   presence in the 304 reply. Absent any Warning update by a 304, Squid
   may still deliver cached content with old Warning headers.

3) Squid no longer validates received Warning headers. RFC 7234 placed
   syntax requirements and limits on how old some Warning values could
   be (when dated). Those checks are no longer being performed. The
   header value is now treated as an opaque string.

4) Warning header usage and types are no longer tracked in message
   statistics available through cache manager.

Updated documentation references to reflect RFC 7234 becoming obsolete.

22 months agoRefactored Ip::Intercept::Lookup() (#1062)
Eduard Bagdasaryan [Sat, 23 Jul 2022 03:27:08 +0000 (03:27 +0000)] 
Refactored Ip::Intercept::Lookup() (#1062)

The TPROXY lookup part was misleading -- the method only checked that
TPROXY was enabled by the configuration and did not change the accepted
connection settings.

Also do not assume that a listening port can have both COMM_TRANSPARENT
and COMM_INTERCEPTION flags set. Squid treats TPROXY and NAT modes as
mutually exclusive and rejects such configurations.

Also forbid invalid port configurations with tproxy mode where TPROXY is
prohibited by ./configure.

Also removed unused Ip::Intercept::StopInterception().