diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index b5fe943fc3c..e0286bd78c7 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -95,7 +95,7 @@ jobs: # Runs every pytest-based test suite via `make check-all-pytest`. # See TEST_PYTEST/TEST_MD in test/travis_run_linux.sh. - name: Python pytest test suites - config: --enable-mods-shared=reallyall --with-mpm=event --enable-mpms-shared=all + config: --enable-mods-shared=reallyall --with-mpm=event --enable-mpms-shared=all --enable-proxy-beacon pkgs: nghttp2-client env: | APR_VERSION=1.7.6 diff --git a/changes-entries/proxy-balancer-add-worker.txt b/changes-entries/proxy-balancer-add-worker.txt new file mode 100644 index 00000000000..d2bd8207b24 --- /dev/null +++ b/changes-entries/proxy-balancer-add-worker.txt @@ -0,0 +1,3 @@ + *) mod_proxy_balancer: Add a worker to a balancer at run time under the + balancer's lock and only once it is complete, so that request threads + cannot find a half-built worker. [Jim Jagielski] diff --git a/changes-entries/proxy-define-worker-rollback.txt b/changes-entries/proxy-define-worker-rollback.txt new file mode 100644 index 00000000000..4ab764052a1 --- /dev/null +++ b/changes-entries/proxy-define-worker-rollback.txt @@ -0,0 +1,4 @@ + *) mod_proxy: Don't leave a half-initialized worker in the balancer (or + server config) worker array when ap_proxy_define_worker() fails, e.g. for + a too long hostname or Unix domain socket path, which crashed the child + on a later walk of the array. [Jim Jagielski] diff --git a/changes-entries/proxy-set-wstatus-atomic.txt b/changes-entries/proxy-set-wstatus-atomic.txt new file mode 100644 index 00000000000..577d628436d --- /dev/null +++ b/changes-entries/proxy-set-wstatus-atomic.txt @@ -0,0 +1,3 @@ + *) mod_proxy: Update the shared worker status atomically, so that the + balancer-manager, health checks and mod_proxy_beacon changing different + bits at the same time cannot undo each other's change. [Jim Jagielski] diff --git a/changes-entries/proxy-worker-beacon-status.txt b/changes-entries/proxy-worker-beacon-status.txt new file mode 100644 index 00000000000..4717bbdf996 --- /dev/null +++ b/changes-entries/proxy-worker-beacon-status.txt @@ -0,0 +1,3 @@ + *) mod_proxy: Add the PROXY_WORKER_BEACON worker status bit (flag 'B', + shown as "Bcn" in the balancer-manager) to mark workers created and + managed by mod_proxy_beacon. [Jim Jagielski] diff --git a/changes-entries/proxy_beacon.txt b/changes-entries/proxy_beacon.txt new file mode 100644 index 00000000000..3dd457be33f --- /dev/null +++ b/changes-entries/proxy_beacon.txt @@ -0,0 +1,3 @@ + *) mod_proxy_beacon: Back-end reverse proxy servers can announce + themselves and be auto-added to their front-end proxy balancer. + [Jim Jagielski] diff --git a/docs/manual/mod/allmodules.xml b/docs/manual/mod/allmodules.xml index 8fdd483eaa5..19e907d766c 100644 --- a/docs/manual/mod/allmodules.xml +++ b/docs/manual/mod/allmodules.xml @@ -81,6 +81,7 @@ mod_proxy.xml mod_proxy_ajp.xml mod_proxy_balancer.xml + mod_proxy_beacon.xml mod_proxy_connect.xml mod_proxy_express.xml mod_proxy_fcgi.xml diff --git a/docs/manual/mod/mod_proxy_beacon.xml b/docs/manual/mod/mod_proxy_beacon.xml new file mode 100644 index 00000000000..762ab7ab35b --- /dev/null +++ b/docs/manual/mod/mod_proxy_beacon.xml @@ -0,0 +1,608 @@ + + + + + + + + + +mod_proxy_beacon +Dynamic Balancer membership where backends announce themselves +to the reverse proxy over unicast UDP datagrams +Extension +mod_proxy_beacon.c +proxy_beacon_module +Available in version 2.4.71 and later + + +

This module lets backend servers announce themselves to a + front-end reverse proxy, which then adds each announcing backend as a live + member (worker) of a mod_proxy_balancer balancer. When a + backend stops announcing, the proxy takes it out of rotation. This provides + self-registering, self-healing balancer membership without editing the proxy + configuration or driving the balancer-manager by hand.

+ +

Communication uses plain unicast UDP datagrams (not + multicast, which is filtered on most networks and does not traverse the + public Internet). The data flows from backend to proxy:

+ + + +

Datagrams are fire-and-forget: a lost announcement is recovered by the + next periodic one, and reordering is rejected by a per-backend timestamp + check, so no connection, reconnect, or framing layer is needed.

+ +

On the proxy, ProxyBeaconBalancer names the balancer + that announced backends are added to. Membership changes are applied using + the same internal mechanism as the balancer-manager web + interface, so a backend added this way behaves exactly like a statically + configured or manually added + BalancerMember, and is visible and + editable in the balancer-manager.

+ +

This module requires the service of + mod_watchdog and mod_proxy_balancer. The + background work (listening, publishing, adding and evicting members) runs in + a single mod_watchdog child process, so it is not available + under the prefork MPM behavior where that singleton cannot + run.

+ +Authentication +

Any host that can reach the proxy's receive port could otherwise announce + an arbitrary backend URL and cause the proxy to send client traffic to it + (and a UDP source address is trivially spoofable). + ProxyBeaconSecret is therefore required: + it must be set to the same value on the proxy and on every backend, and the + server fails to start if any participating server omits it. Announcements are + authenticated with a keyed message-authentication code (MAC) and a timestamp, + and the proxy drops any announcement that is not validly signed and recent. + There is no unauthenticated mode.

+
+ +Confidentiality +

Announcements are authenticated but not encrypted; the payload is + operational metadata (backend URLs), not secret data. Transport + confidentiality (e.g. DTLS) is not currently provided and would be a separate + future layer.

+
+ +
+mod_proxy +mod_proxy_balancer +mod_proxy_hcheck +mod_watchdog + +
+ Usage example + +

The following pair of configurations sets up a self-registering balancer. + The backends require no knowledge of each other and the proxy needs no + pre-declared BalancerMember + entries — only an empty balancer with room to grow.

+ +

On the reverse proxy:

+ +# Receive backend announcements on the cluster network interface (UDP). +ProxyBeaconListen 0.0.0.0:5555 +ProxyBeaconSecret "hex:00112233445566778899aabbccddeeff" +ProxyBeaconBalancer cluster + +# A backend is dropped from rotation if it does not announce for 30 seconds. +ProxyBeaconTimeout 30 + +# An initially-empty balancer with spare slots for the dynamic members. +<Proxy balancer://cluster> + ProxySet growth=16 +</Proxy> +ProxyPass "/" "balancer://cluster/" +ProxyPassReverse "/" "balancer://cluster/" + + +

On each backend server:

+ +# Announce this backend's routable origin to the proxy every 10 seconds (UDP). +ProxyBeaconAddress proxy.example.com:5555 +ProxyBeaconAdvertise http://10.0.0.5:8080 +ProxyBeaconSecret "hex:00112233445566778899aabbccddeeff" +ProxyBeaconInterval 10 + + +

When a backend starts it begins sending announcements. The proxy + verifies each announcement against the shared secret, adds + http://10.0.0.5:8080 as a member of + balancer://cluster, and enables it. If that backend later stops + announcing for longer than ProxyBeaconTimeout, the proxy + disables the member (taking it out of rotation); a subsequent announcement + re-enables it.

+ + +

A backend added at runtime occupies one of the balancer's growth slots + for the lifetime of the server process; it is disabled rather than removed + when it stops announcing, matching the behavior of the + balancer-manager (which can add, but not remove, workers at + runtime). Size growth for the maximum number of backends you + expect to register.

+
+ +
+ +
Member identity + +

An announced URL identifies a backend origin: + scheme://host[:port], and nothing more. The proxy uses the same + string as the member's identity everywhere: as the key under which it tracks + the backend's lease and replay state, and as the worker name it creates in + the balancer. To keep those identities equal, the proxy:

+ + +

Mistakes that no later change in the network can cure are reported by + httpd -t as well as at startup: a missing + ProxyBeaconSecret, a + ProxyBeaconAddress that is not host:port, + a malformed ProxyBeaconListen address, and a + ProxyBeaconBalancer that is not defined for the + server. Whether an address resolves or a port can be bound is not checked + then; the proxy keeps retrying those.

+ +

Paths are refused because the balancer finds a member by longest prefix + match. Announcements for http://10.0.0.5:8080/one and + http://10.0.0.5:8080/one/two would be tracked as two members + with separate leases but resolve to a single worker, so the lapse of one + lease could disable a worker whose other lease was still current. Choose + request paths on the proxy with ProxyPass, + not through the advertised URL.

+ +

A backend that is announced successfully is confirmed to exist in the + balancer before it is reported as added, enabled or evicted; an announcement + that the proxy cannot turn into a member is logged and retried after a + back-off rather than reported as a success.

+ +
+ +
Ownership and watchdog hand-off + +

Every worker that mod_proxy_beacon creates is marked with + the Bcn status (flag B), which is stored in the + worker's shared state and shown by the balancer-manager. The + module only enables or evicts workers that carry this mark. A worker of the + same name that does not — a + BalancerMember from the + configuration, or one added by an administrator — is left alone; an + announcement for it is dropped and logged as + member not managed by beacon.

+ +

The announcements are received and the leases kept by a single + mod_watchdog child process. If that process exits or is + killed, the watchdog singleton moves to another child, which starts with no + record of the members it did not add itself. When a child becomes the owner + it therefore takes over every worker in the balancer carrying the + Bcn mark (logged as took over N existing + member(s)):

+ + + +

A dead backend can therefore stay in rotation for up to one + ProxyBeaconTimeout after a hand-off. The per-member + replay high-water mark is not carried over either: during the hand-off a + captured announcement that is still inside the + ProxyBeaconMaxSkew freshness window can be replayed + once per member, which refreshes that member's lease for one timeout. It + does not allow a new member to be added without the shared secret.

+
+ +

A new owner can only start once the watchdog's callback mutex has been + released by the process that held it. Whether the default mutex mechanism is + released when its holder is killed depends on the platform; if prompt + hand-off after a crash matters, select a mechanism that is released on + process death for the watchdog-callback mutex with the + Mutex directive (for example + Mutex sysvsem watchdog-callback).

+ +
+ +
Administrator control of members + +

Beacon uses the Disabled status flag to take a member out of + rotation when its lease expires, and clears it when the member announces + again; it owns that flag for the members it manages. An administrator who + disables such a member in the balancer-manager is therefore + overridden by the next announcement after an eviction.

+ +

To hold a member out of rotation regardless of what it announces, set it + to Stopped or Drain instead. Beacon never changes + those flags, nor the flag set by an active health check + (mod_proxy_hcheck); they combine with the lease state, so a + stopped member stays stopped through any number of evictions and + re-enablements.

+ +

Beacon enables members through the same code as the + balancer-manager, and like it does not wait for requests that + are being balanced at that moment. A member re-enabled while that happens + can miss the reset of the load-balancing counters that normally follows, + and requests may then be spread unevenly between members until the + counters settle.

+ +
+ +
Message validation and limits + +

The receiver validates every datagram before acting on it:

+ + +

The proxy tracks at most 256 announced URLs. A record is released once it + belongs to an evicted member, or to an add that failed, and has been silent + for more than twice ProxyBeaconMaxSkew (by then a + replay of its last message would be stale anyway, so no replay protection is + lost). Until then a flood of distinct URLs from a holder of the secret can + fill the table and keep new backends out; the members themselves remain in + the balancer, and a backend that announces again after its record was + released is re-adopted. A balancer's own limit (growth, at most + 100) caps how many members can ever be added.

+ +

If the UDP socket cannot be opened (an unresolvable address, a port in + use), opening is retried with a delay that starts at 30 seconds and doubles + up to 10 minutes. The same happens after five failed sends or receives in a + row. A backend looks up the address of the proxy again every five minutes, + keeping the one it has if that fails, so a proxy that moved is found without + a restart. Name lookups are synchronous and run on the single + mod_watchdog thread that serves every beacon + configuration of the server, so a name that fails to resolve can stall them + for as long as the resolver takes to give up. Prefer an IP address in + ProxyBeaconAddress and + ProxyBeaconListen.

+ +

Each time the watchdog runs, the proxy reads datagrams for at most 50 + milliseconds (and at most 1024 of them), so that a flood cannot keep it from + evicting members; what it does not read in time waits in the socket buffer + or is dropped by the operating system. At most twenty + received: lines per second are logged for each configuration; + the number left out is logged when the next announcement arrives after that + second.

+ +
+ +
What this module is for + +

The module provides liveness-based membership for a set of + backends that you control. Use it within these limits, which are properties + of the design and not defects to be worked around:

+ + + +
+ + +ProxyBeaconListen +Address on which the reverse proxy receives backend +beacons +ProxyBeaconListen [address][:port] +server configvirtual host + + + +

The ProxyBeaconListen directive marks a server as + the beacon receiver (the reverse proxy). It binds a UDP socket to + the given address, e.g. 0.0.0.0:5555 to receive on all + interfaces. A leading scheme (such as tcp://) is accepted and + ignored.

+ +

The address and port are both optional and, when omitted, are inherited + from this server's own address and port (its Listen/ServerName). With no argument at all, the beacon + listener binds the server's own address and port; given just an address it + inherits the port, and so on. Because UDP and TCP are independent port + spaces, binding the beacon socket to the server's port does not + collide with the server's TCP listener — letting the beacon channel + share the service endpoint, which also identifies the proxy to backends by + its real address. (The listener binds in an unprivileged child, so a + privileged port such as 80 or 443 cannot be shared this way; use the + server's port only when it is non-privileged.)

+ +

Backends send to this address via + ProxyBeaconAddress. The directive should be used + together with ProxyBeaconBalancer; without it, + announcements are received and logged but no members are added. + ProxyBeaconListen and + ProxyBeaconAddress are mutually exclusive on the same + server.

+
+
+ + +ProxyBeaconAddress +Address of the reverse proxy to which a backend sends its +announcements +ProxyBeaconAddress address:port +server configvirtual host + + + +

The ProxyBeaconAddress directive marks a server as an + announcement sender (a backend). It sends UDP datagrams to the + proxy's ProxyBeaconListen address given by + address:port, e.g. proxy.example.com:5555 (a leading + scheme such as tcp:// is accepted and ignored). Because UDP is + connectionless, a backend may be started before the proxy is available: + early datagrams are simply dropped and the next interval retries.

+ +

Use ProxyBeaconAdvertise to specify the routable URL + the backend announces. ProxyBeaconAddress and + ProxyBeaconListen are mutually exclusive on the same + server.

+
+
+ + +ProxyBeaconAdvertise +The routable URL a backend announces to the reverse proxy +ProxyBeaconAdvertise url +server configvirtual host + + + +

The ProxyBeaconAdvertise directive sets the backend's + own reachable origin (for example http://10.0.0.5:8080) that the + proxy will add as a BalancerMember. + It must be a full scheme://host[:port] URL that the proxy can + reach — not the local listen address — and is validated when the + configuration is parsed. The URL names an origin only: a path, + query string, fragment or user information is rejected with a configuration + error (see Member identity). The URL is announced in + its canonical form.

+ +

This directive is used on a backend, alongside + ProxyBeaconAddress. If it is omitted, the backend still + sends a heartbeat but advertises no URL, so the proxy logs the + announcement without adding a member.

+
+
+ + +ProxyBeaconBalancer +Name of the balancer that announced backends are added to +ProxyBeaconBalancer name +server configvirtual host + + + +

The ProxyBeaconBalancer directive names the balancer, + on the reverse proxy, into which announced backends are inserted as members. + Give the bare balancer name (for example cluster for + balancer://cluster); a leading balancer:// is + accepted and stripped.

+ +

The named balancer must exist and have spare capacity. Declare it with a + <Proxy> block and a + growth setting (or rely on + BalancerGrowth) so there are free + slots for the dynamically added members. This directive is used together + with ProxyBeaconListen.

+
+
+ + +ProxyBeaconInterval +How often a backend publishes its announcement +ProxyBeaconInterval interval +ProxyBeaconInterval 5 +server configvirtual host + + + +

The ProxyBeaconInterval directive sets how frequently + a backend (a ProxyBeaconAddress server) publishes its + announcement. It uses the + time-interval directive syntax and + defaults to seconds; the default is 5 seconds.

+ +

The interval must be meaningfully smaller than the proxy's + ProxyBeaconTimeout, so that the occasional lost or + delayed announcement does not cause a healthy backend to be evicted.

+
+
+ + +ProxyBeaconTimeout +How long the proxy waits, without an announcement, before a backend +is taken out of rotation +ProxyBeaconTimeout interval +ProxyBeaconTimeout 0 +server configvirtual host + + + +

The ProxyBeaconTimeout directive sets how long the + reverse proxy will wait for an announcement from a backend before disabling + that backend's balancer member (taking it out of rotation). A later + announcement from the same backend re-enables it. It uses the + time-interval directive syntax and + defaults to seconds.

+ +

The default, 0, disables eviction entirely: backends are + added when they announce but are never automatically removed. Set this to a + small multiple of the backends' ProxyBeaconInterval to + enable self-healing membership. This directive is used on the proxy.

+
+
+ + +ProxyBeaconSecret +Pre-shared secret used to authenticate announcements +ProxyBeaconSecret secret|hex:key +server configvirtual host + + + +

The ProxyBeaconSecret directive sets a pre-shared + cluster secret. It must be configured with the same value on the + reverse proxy and on every backend. The backend (sender) signs each + announcement with a keyed message-authentication code (a SipHash MAC) derived + from the secret, together with a timestamp; the proxy (receiver) recomputes the MAC and + checks the timestamp, dropping any announcement that is forged, tampered + with, or replayed. Replayed messages are caught two ways: a freshness window + (ProxyBeaconMaxSkew) rejects old timestamps, and a + per-backend check rejects any announcement whose timestamp does not strictly + advance, so a captured-and-resent message (for example, one replayed to keep + a dead backend from being evicted) is dropped.

+ +

This directive is required on every server that + participates in the beacon channel — the proxy + (ProxyBeaconListen) and every backend + (ProxyBeaconAddress). If any such server omits it, the + server fails to start; there is no unauthenticated mode.

+ +

Every announcement must carry a valid, recent MAC or it is rejected. If the + secrets on the proxy and a backend differ, that backend's announcements are + silently rejected (and logged), which appears as the backend never joining + the balancer.

+ +

Use a random key. Generate one with openssl rand -hex 16 + and configure it as hex: followed by the 32 hex digits; that + value is used directly as the 128-bit MAC key, so there is nothing to guess. + Any other value is treated as a passphrase: it must be at least 16 + characters, and the MAC key is derived from it with a fast hash. Because the + authentication tag is 64 bits, anyone who captures a single announcement can + test passphrase guesses offline at full speed, so a passphrase protects only + as well as it is random and long. A value that begins with hex: + is always read as a key and is rejected if it is not exactly 32 hex + digits.

+ + The secret is a membership credential +

A valid MAC proves only that the sender holds the secret. It does not + prove that the sender owns the URL it announces, may speak for another + backend, or is ready to serve. Every holder can therefore register any + backend origin the proxy can reach, announce on behalf of other members + (keeping their leases alive), and use up the balancer's growth slots and the + tracking table. Treat the secret as an administrator credential for the + balancer, and share it only among hosts that you would trust with that. It + is not a boundary between partially trusted workloads.

+
+ +

Because the secret is stored in the configuration file, restrict that + file's permissions as you would for a private key.

+ + Clock synchronization +

The timestamp-based replay protection compares the announcement's time + against the proxy's clock, so the proxy and backends must have reasonably + synchronized clocks (for example via NTP). See + ProxyBeaconMaxSkew.

+
+
+
+ + +ProxyBeaconMaxSkew +Maximum allowed age of a signed announcement +ProxyBeaconMaxSkew interval +server configvirtual host + + + +

The ProxyBeaconMaxSkew directive sets the anti-replay + window used when ProxyBeaconSecret is configured: the + proxy rejects any announcement whose signed timestamp differs from the + current time by more than this amount, in either direction. It uses the + time-interval directive syntax and + defaults to seconds.

+ +

If unset, the default is 30 seconds. Sub-second values are honored + (for example 500ms). A larger window tolerates greater + clock skew between hosts; a smaller window bounds the freshness check. Note + that the per-backend strictly-increasing-timestamp check (see + ProxyBeaconSecret) blocks replays regardless of this + window. This directive is used on the proxy.

+
+
+ +
diff --git a/docs/manual/mod/mod_proxy_beacon.xml.meta b/docs/manual/mod/mod_proxy_beacon.xml.meta new file mode 100644 index 00000000000..3f37efddb01 --- /dev/null +++ b/docs/manual/mod/mod_proxy_beacon.xml.meta @@ -0,0 +1,12 @@ + + + + + mod_proxy_beacon + /mod/ + .. + + + en + + diff --git a/docs/manual/new_features_2_4.xml b/docs/manual/new_features_2_4.xml index b8b83fac247..3798996a9d2 100644 --- a/docs/manual/new_features_2_4.xml +++ b/docs/manual/new_features_2_4.xml @@ -206,6 +206,10 @@
systemd integration. It allows httpd to be used in a service with the systemd Type=notify.
+
mod_proxy_beacon (available since 2.4.71)
+
Backends announce themselves over UDP and are added to a + mod_proxy_balancer balancer automatically.
+ diff --git a/include/ap_mmn.h b/include/ap_mmn.h index d00c6d1ec9c..95cadbaa348 100644 --- a/include/ap_mmn.h +++ b/include/ap_mmn.h @@ -612,6 +612,7 @@ * 20120211.140 (2.4.64-dev) Add ap_set_time_process_request() to scoreboard.h * 20120211.141 (2.4.64-dev) add ap_stat_check() to httpd.h * 20120211.142 (2.4.64-dev) Add ap_*_timingsafe() to httpd.h + * 20120211.143 (2.4.71-dev) Add PROXY_WORKER_BEACON status bit to mod_proxy.h */ #define MODULE_MAGIC_COOKIE 0x41503234UL /* "AP24" */ @@ -619,7 +620,7 @@ #ifndef MODULE_MAGIC_NUMBER_MAJOR #define MODULE_MAGIC_NUMBER_MAJOR 20120211 #endif -#define MODULE_MAGIC_NUMBER_MINOR 142 /* 0...n */ +#define MODULE_MAGIC_NUMBER_MINOR 143 /* 0...n */ /** * Determine if the server's current MODULE_MAGIC_NUMBER is at least a diff --git a/modules/proxy/README.beacon b/modules/proxy/README.beacon new file mode 100644 index 00000000000..a3d57b69d6f --- /dev/null +++ b/modules/proxy/README.beacon @@ -0,0 +1,221 @@ +mod_proxy_beacon + +Self-registering reverse-proxy balancer membership: backend servers announce +themselves to a front-end proxy over UDP datagrams, and the proxy adds, enables, +and evicts them as live balancer members. See +docs/manual/mod/mod_proxy_beacon.xml for the user-facing directive reference; +this file describes the architecture. + +The transport is plain APR UDP sockets -- small, periodic, fire-and-forget +announcements with no third-party dependency. + + +Dependencies: + Requires mod_watchdog and mod_proxy_balancer. No external library: the UDP + transport uses APR sockets and authentication uses SipHash from APR-util (no + OpenSSL dependency). + + +Transport (unicast UDP, not multicast): + Each backend sends a point-to-point UDP datagram (apr_socket_sendto) to the + proxy's configured address. This is deliberately UNICAST -- unlike + mod_heartbeat, which multicasts to a group. Multicast is filtered on most + networks and does not traverse the public Internet, so a cross-host control + plane must be unicast. The socket-handling pattern is adapted from + mod_heartmonitor's unicast receive path. + + Datagrams are fire-and-forget. The design tolerates UDP loss and reordering + without a reconnect or framing layer: a lost announcement just delays an update + by one interval (announcements are periodic and idempotent), and an out-of-order + datagram is rejected by the per-url monotonic timestamp (see Authentication). + + +Roles: + Backend = sender (ProxyBeaconAddress): sends to the proxy, advertising its + own routable URL (ProxyBeaconAdvertise) periodically. + Proxy = receiver (ProxyBeaconListen): binds a stable address, receives + announcements, and manages balancer:// (ProxyBeaconBalancer). + + The proxy is the fixed unicast rendezvous; each backend is configured with its + address. One proxy receiver serves many backend senders. A leading scheme in + an address (e.g. tcp://) is accepted and ignored. + + ProxyBeaconListen's host and port are both optional: an omitted host/port (or + no argument at all) is inherited from the server's own address/port. Since UDP + and TCP are independent port spaces, the beacon socket can share the server's + service port without colliding with its TCP listener -- so a backend can beacon + to the proxy at its real service endpoint. (The listener binds in an + unprivileged watchdog child, so privileged ports like 80/443 cannot be shared + this way.) The sender's ProxyBeaconAddress targets the proxy and must be given + in full. + + +Where it runs: + All background work runs in a single mod_watchdog SINGLETON callback -- exactly + one child process owns the socket (so only one process binds the receive port + and performs membership changes). The watchdog fires every ~100ms: + + STARTING open the UDP socket; receiver binds, sender resolves its dest. + RUNNING sender: send a throttled announcement (ProxyBeaconInterval). + receiver: drain the socket, then run a throttled (~1s) eviction + sweep. + STOPPING close the socket. + + Because this relies on a singleton watchdog child, it is inactive under the + prefork MPM. + + +Adding/removing members (reuses the balancer-manager path): + Runtime worker *removal* does not exist in httpd, so membership is managed + entirely as status-flag changes via mod_proxy_balancer's exported + balancer_manage() optional function -- the same code the balancer-manager web + UI calls. The receiver synthesizes a minimal request_rec (no real client + request exists in the watchdog thread; see beacon_make_fake_request) and calls: + + add b= b_nwrkr= b_wyes=1 b_nwrkr_flags=B + (worker created, disabled, marked) + enable b= w= w_status_D=0 (cleared -> serves traffic) + evict b= w= w_status_D=1 (disabled -> out of rotation) + + Adds bump the balancer's shm "updated" timestamp, so every other child picks + up the new worker through the normal ap_proxy_sync_balancer() path -- the + change made in the singleton propagates fleet-wide. The target balancer must + have spare slots (ProxySet growth / BalancerGrowth). + + Per-backend state (last-seen time, added/evicted flags) is kept in a hash in + the singleton's own pool -- no shared memory is needed, since the singleton is + the only process that adds or evicts. A re-announcement after eviction + re-enables the worker; the flags make these transitions idempotent. + + +Message format: + Plain ASCII, space-separated key=value tokens, one datagram per announcement: + + BEACON url=http://host:port host= pid= seq= ts= mac= + + url= is the routable backend origin the proxy adds as a BalancerMember. ts= + (microseconds since the epoch) and mac= authenticate the message and are always + present, since a shared secret is required (see below). host=/pid=/seq= are + informational. + +Member identity: + url= names an ORIGIN -- scheme://host[:port] -- and nothing else. The receiver + canonicalizes it (lower-case scheme and host, the scheme's default port dropped, + one trailing "/" ignored) and uses that single string as the member's identity: + the key of its lease/replay record in ctx->seen, the worker name handed to + balancer_manage(), and the name used for every later enable/evict. Keeping + those equal matters because the balancer finds a worker by LONGEST-PREFIX match + (ap_proxy_get_worker) while ap_proxy_define_worker() stores a normalized name: + tracking the raw announced string made "http://h:80" never find its worker + "http://h" (member added but left disabled, add still logged as a success), and + let "http://h/one" and "http://h/one/two" hold two leases over one worker. + + Anything that is not an origin -- a path other than "/", query, fragment, + userinfo, a bad port, or the "unix:/path|url" worker syntax (no host part) -- is + dropped with a rate-limited "unacceptable url" log. ProxyBeaconAdvertise applies + the same rule at config time and announces the canonical form. After an add, + and before any enable/evict, the worker is looked up again and the operation is + reported as failed if it is not there, since balancer_manage() returns success + when it finds no such worker. Path-based routing belongs in ProxyPass on the + proxy, not in the advertised URL. + + A UDP datagram is delivered whole, so the receiver reads each message into a + fixed stack buffer and NUL-terminates it (buf[len] = '\0') before parsing. + The sender transmits strlen(msg) bytes (no trailing NUL on the wire). + + +Ownership and watchdog hand-off: + Every worker beacon creates is marked PROXY_WORKER_BEACON (status 'B', "Bcn" in + the balancer-manager) in the worker's SHARED state. Beacon enables/evicts only + marked workers; a same-named worker without the mark (configured, or added by + an administrator) is left alone and the announcement is dropped ("member not + managed by beacon"). + + The leases (ctx->seen) are private to the process that owns the watchdog + singleton, but the members they describe live in shared memory and outlive that + process. When ownership moves (owner crashed, was recycled, or the server was + restarted), the new owner starts with an empty table and would never evict a + member that has since gone silent. So, once at the start of ownership + (beacon_reconcile(), first RUNNING tick of a listener), it syncs the balancer + (ap_proxy_sync_balancer()) and adopts every marked member: last_seen = now, so + a silent member is evicted one ProxyBeaconTimeout later; a member that is + already DISABLED is recorded as evicted, so its next announcement re-enables it. + + Not recovered: the per-member replay high-water mark (last_ts restarts at 0). + The global freshness window (ProxyBeaconMaxSkew) still applies, so a captured + announcement can be replayed once per member after a hand-off, refreshing that + one lease for one timeout. Keeping that state across hand-off would need a + shared lease table; the marker + reconcile design was chosen as the smaller, + ABI-safe change (the status field is existing shared state, bit 0x1000 is new). + + A new owner can only start once the watchdog-callback mutex is released by the + dead one. If the default mechanism is not released when its holder is killed on + a platform, use e.g. "Mutex sysvsem watchdog-callback". + +Operator control: + Beacon owns the DISABLED flag of its members (lease expiry sets it, a new + announcement clears it). It never touches STOPPED, DRAIN or the hcheck + failure flag, so an administrator who needs a member held out of rotation uses + Stopped/Drain; a manual "Disable" is overridden by the next announcement after + an eviction. (After a hand-off a DISABLED beacon member is assumed to have been + evicted, for the same reason.) + +Receiver validation: + Datagrams > BEACON_MAX_MSG_LEN (2048) are dropped, not truncated (recvfrom is + asked for one byte more to tell); a datagram containing a NUL is dropped. The + MAC is verified on every path, including log-only (no ProxyBeaconBalancer). + After the MAC: strict grammar (beacon_frame_check(): "BEACON " marker, + single-space key=value tokens, known fields not repeated), ts= strictly 1-18 + decimal digits (beacon_parse_ts()), freshness compared in microseconds so a + sub-second ProxyBeaconMaxSkew is honoured. The url must be printable ASCII + and an origin (see Member identity). + +Capacity: + At most BEACON_MAX_MEMBERS (256) urls are tracked. beacon_sweep() also frees + records that are evicted or whose add failed once they have been silent for + 2 * max_skew + 1s: the record doubles as the replay high-water mark, and a + message accepted at time A carries ts within max_skew of A, so it is stale after + A + 2 * max_skew; nothing is lost by forgetting it then. A reclaimed member that + announces again is re-adopted from the balancer (try_add finds the marked worker). + Records come from a free list: memory is bounded by the cap however often they + are recycled. A flood of distinct urls from a secret holder can still fill the + table until it falls silent. + +Socket open: + A failed open/bind/resolve is retried with back-off (30s doubling to 10min), + not on every tick and not never. The address lookup is synchronous on the one + watchdog thread shared by all beacon contexts; prefer IP literals. + +Authentication (ProxyBeaconSecret, REQUIRED): + ProxyBeaconSecret must be set on every participating server (the receiver and + every sender); startup fails otherwise. There is no unauthenticated mode: + without a MAC, anyone who can reach the receiver port could announce a URL and + hijack client traffic, and a UDP source address is trivially spoofable, so + authentication matters at least as much here as it would over a connection. + + With ProxyBeaconSecret set identically on the proxy and all backends, each + announcement is signed with a SipHash-2-4 MAC over the message prefix (the key + is derived from the passphrase via apr_md5, as in mod_session_crypto). The + receiver recomputes the MAC (constant-time compare) and rejects anything that + does not match -- before the URL is parsed or acted on. Replay protection has + two parts, both keyed on the signed ts= (microseconds): (1) a freshness window + (ProxyBeaconMaxSkew) rejects messages whose timestamp is too far from now, + which assumes proxy and backend clocks are roughly synchronized (NTP); (2) a + per-url high-water mark rejects any ts= that does not strictly exceed the last + one accepted for that url, so a byte-identical replay (same ts, same MAC) -- + e.g. replaying a dead backend's last announcement to keep it from being evicted + -- is dropped even within the freshness window. Microsecond granularity ensures + genuine sub-second announcements always advance. seq= is NOT used for replay + (it resets when a backend restarts); the wall-clock ts= does not. + + "hex:<32 hex digits>" is the 128-bit SipHash key itself (openssl rand -hex 16): + no passphrase, nothing to guess. Any other value is a passphrase of at least 16 + characters; the key is then MD5(passphrase) and the tag is 64 bits, so a + captured announcement permits offline guessing at full speed. A valid MAC shows possession of the + secret, nothing more: every holder can register any reachable origin, speak for + other members and consume slots/records. The secret is a membership- + administrator credential, not a boundary between partially trusted workloads. + + Announcements are authenticated, not encrypted -- the payload is operational + metadata, not secret. For transport confidentiality, DTLS would be a separate, + orthogonal future layer. diff --git a/modules/proxy/config.m4 b/modules/proxy/config.m4 index 01f09fab1d4..941f74c7630 100644 --- a/modules/proxy/config.m4 +++ b/modules/proxy/config.m4 @@ -70,6 +70,19 @@ APACHE_MODULE(proxy_balancer, Apache proxy BALANCER module. Requires --enable-p APACHE_MODULE(proxy_express, mass reverse-proxy module. Requires --enable-proxy., , , most, , proxy) APACHE_MODULE(proxy_hcheck, [reverse-proxy health-check module. Requires --enable-proxy and --enable-watchdog.], , , most, , [proxy,watchdog]) +proxy_beacon_objs="mod_proxy_beacon.lo" +APACHE_MODULE(proxy_beacon, [reverse-proxy UDP member announcement; backends self-register as balancer members. Requires --enable-proxy, --enable-proxy-balancer and --enable-watchdog.], $proxy_beacon_objs, , no, [ + dnl apr_siphash.h is in APR-util 1.6 and later (and APR 2.x) + saved_CPPFLAGS="$CPPFLAGS" + CPPFLAGS="$CPPFLAGS $APR_INCLUDES $APU_INCLUDES" + AC_TRY_COMPILE([#include ], [], [ap_have_apr_siphash=yes], [ap_have_apr_siphash=no]) + CPPFLAGS="$saved_CPPFLAGS" + if test "$ap_have_apr_siphash" = "no"; then + AC_MSG_WARN([mod_proxy_beacon needs apr_siphash.h, from APR-util 1.6 or later]) + enable_proxy_beacon=no + fi +], [proxy,watchdog,proxy_balancer]) + APR_ADDTO(INCLUDES, [-I\$(top_srcdir)/$modpath_current -I\$(top_srcdir)/modules/http2]) module_selection=$save_module_selection diff --git a/modules/proxy/mod_proxy.c b/modules/proxy/mod_proxy.c index 521e8f21837..89b070719cd 100644 --- a/modules/proxy/mod_proxy.c +++ b/modules/proxy/mod_proxy.c @@ -71,6 +71,7 @@ proxy_wstat_t PROXY_DECLARE_DATA proxy_wstat_tbl[] = { {PROXY_WORKER_HOT_SPARE, PROXY_WORKER_HOT_SPARE_FLAG, "Spar "}, {PROXY_WORKER_FREE, PROXY_WORKER_FREE_FLAG, "Free "}, {PROXY_WORKER_HC_FAIL, PROXY_WORKER_HC_FAIL_FLAG, "HcFl "}, + {PROXY_WORKER_BEACON, PROXY_WORKER_BEACON_FLAG, "Bcn "}, {0x0, '\0', NULL} }; @@ -1480,7 +1481,7 @@ static int proxy_handler(request_rec *r) */ if (balancer && !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) { - worker->s->status |= PROXY_WORKER_IN_ERROR; + ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker); worker->s->error_time = apr_time_now(); } break; @@ -1492,7 +1493,7 @@ static int proxy_handler(request_rec *r) */ if (balancer && !(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) { - worker->s->status |= PROXY_WORKER_IN_ERROR; + ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker); worker->s->error_time = apr_time_now(); } } diff --git a/modules/proxy/mod_proxy.h b/modules/proxy/mod_proxy.h index 329d10fdaa9..fa077b87683 100644 --- a/modules/proxy/mod_proxy.h +++ b/modules/proxy/mod_proxy.h @@ -329,6 +329,7 @@ struct proxy_conn_pool { #define PROXY_WORKER_FREE 0x0200 #define PROXY_WORKER_HC_FAIL 0x0400 #define PROXY_WORKER_HOT_SPARE 0x0800 +#define PROXY_WORKER_BEACON 0x1000 /* created and managed by mod_proxy_beacon */ /* worker status flags */ #define PROXY_WORKER_INITIALIZED_FLAG 'O' @@ -343,6 +344,7 @@ struct proxy_conn_pool { #define PROXY_WORKER_FREE_FLAG 'F' #define PROXY_WORKER_HC_FAIL_FLAG 'C' #define PROXY_WORKER_HOT_SPARE_FLAG 'R' +#define PROXY_WORKER_BEACON_FLAG 'B' #define PROXY_WORKER_NOT_USABLE_BITMAP ( PROXY_WORKER_IN_SHUTDOWN | \ PROXY_WORKER_DISABLED | PROXY_WORKER_STOPPED | PROXY_WORKER_IN_ERROR | \ diff --git a/modules/proxy/mod_proxy_balancer.c b/modules/proxy/mod_proxy_balancer.c index aa2c195e005..a1d4fdf94a6 100644 --- a/modules/proxy/mod_proxy_balancer.c +++ b/modules/proxy/mod_proxy_balancer.c @@ -450,7 +450,7 @@ static void force_recovery(proxy_balancer *balancer, server_rec *s) worker = (proxy_worker **)balancer->workers->elts; for (i = 0; i < balancer->workers->nelts; i++, worker++) { ++(*worker)->s->retries; - (*worker)->s->status &= ~PROXY_WORKER_IN_ERROR; + ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 0, *worker); ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01165) "%s: Forcing recovery for worker (%s:%d)", balancer->s->name, (*worker)->s->hostname_ex, @@ -676,7 +676,7 @@ static int proxy_balancer_post_request(proxy_worker *worker, "balancer parameter", balancer->s->name, ap_proxy_worker_name(r->pool, worker), val); - worker->s->status |= PROXY_WORKER_IN_ERROR; + ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker); worker->s->error_time = apr_time_now(); break; } @@ -690,7 +690,7 @@ static int proxy_balancer_post_request(proxy_worker *worker, "%s: Forcing worker (%s) into error state " "due to timeout and 'failontimeout' parameter being set", balancer->s->name, ap_proxy_worker_name(r->pool, worker)); - worker->s->status |= PROXY_WORKER_IN_ERROR; + ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker); worker->s->error_time = apr_time_now(); } @@ -1121,6 +1121,122 @@ static int safe_referer(request_rec *r, const char *ref) return strcasecmp(uri.hostname, ap_get_server_name(r)) == 0; } +/* + * Add the worker `url` to `bsel` at runtime. Returns APR_SUCCESS, or + * HTTP_BAD_REQUEST if it could not be added. The worker is created disabled. + * + * The global lock is taken first, so that no other process adds a worker + * between the check that it is not there yet and its slot being taken. The + * balancer's thread lock follows, for the part that changes this process's + * worker array: request threads walk it holding that lock, so they never see a + * worker that is not complete, and they do not wait for the global lock. Both + * come before proxy_mutex, which sync and initialization take inside. A worker + * whose sharing fails is taken out of the array again and its slot given back. + */ +static int balancer_add_worker(request_rec *r, proxy_balancer *bsel, + proxy_server_conf *conf, const char *url, + const char *flags) +{ + proxy_worker *nworker; + proxy_worker_shared *shm; + unsigned int index = 0; + apr_status_t rv; + char *ret; + int status = HTTP_BAD_REQUEST; +#if APR_HAS_THREADS + int thread_locked = 0; + + if ((rv = PROXY_GLOBAL_LOCK(bsel)) != APR_SUCCESS) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01194) + "%s: Lock failed for adding worker", bsel->s->name); + return HTTP_BAD_REQUEST; + } + if ((rv = PROXY_THREAD_LOCK(bsel)) != APR_SUCCESS) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(10658) + "%s: Thread lock failed for adding worker", + bsel->s->name); + goto done; + } + thread_locked = 1; +#endif + + /* Another child may have added it since this one last synced. */ + ap_proxy_sync_balancer(bsel, r->server, conf); + if (ap_proxy_get_worker(r->pool, bsel, conf, url) + || !storage->num_free_slots(bsel->wslot)) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10164) + "%s: failed to add worker %s", bsel->s->name, url); + goto done; + } + + ret = ap_proxy_define_worker(conf->pool, &nworker, bsel, conf, url, 0); + if (ret) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10163) + "%s: failed to add worker %s", bsel->s->name, url); + goto done; + } + /* nworker is now the last element of bsel->workers. */ + PROXY_COPY_CONF_PARAMS(nworker, conf); + /* Optional status flags to create the worker with, and DISABLED always: + * set before ap_proxy_share_worker() copies the worker to shm, so that no + * child can ever find it there without them (a creator such as + * mod_proxy_beacon leaves no window in which the worker exists without its + * mark, or is enabled before it has been told to). */ + ap_proxy_set_wstatus(PROXY_WORKER_DISABLED_FLAG, 1, nworker); + if (flags) { + for (; *flags; flags++) { + ap_proxy_set_wstatus(*flags, 1, nworker); + } + } + if ((rv = storage->grab(bsel->wslot, &index)) != APR_SUCCESS) { + ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01195) + "worker slotmem_grab failed"); + apr_array_pop(bsel->workers); + goto done; + } + if ((rv = storage->dptr(bsel->wslot, index, (void *)&shm)) != APR_SUCCESS) { + ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01197) + "worker slotmem_dptr failed"); + storage->release(bsel->wslot, index); + apr_array_pop(bsel->workers); + goto done; + } + if ((rv = ap_proxy_share_worker(nworker, shm, index)) != APR_SUCCESS) { + ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01199) + "Cannot share worker"); + storage->release(bsel->wslot, index); + apr_array_pop(bsel->workers); + goto done; + } + if ((rv = ap_proxy_initialize_worker(nworker, r->server, conf->pool)) != APR_SUCCESS) { + ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01201) + "Cannot init worker"); + /* Other children find slots by their hash: empty it. */ + memset(shm, 0, sizeof(*shm)); + storage->release(bsel->wslot, index); + apr_array_pop(bsel->workers); + goto done; + } + /* sync all timestamps */ + bsel->wupdated = bsel->s->wupdated = nworker->s->updated = apr_time_now(); + status = APR_SUCCESS; + +done: +#if APR_HAS_THREADS + if (thread_locked + && (rv = PROXY_THREAD_UNLOCK(bsel)) != APR_SUCCESS) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(10659) + "%s: Thread unlock failed for adding worker", + bsel->s->name); + } + if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01203) + "%s: Unlock failed for adding worker", bsel->s->name); + } +#endif + return status; +} + /* * Process the paramters and add or update the worker of the * balancer. Must only be called if the nonce has been validated to @@ -1132,7 +1248,6 @@ static int balancer_process_balancer_worker(request_rec *r, proxy_server_conf *c apr_table_t *params) { - apr_status_t rv; /* First set the params */ if (wsel) { const char *val; @@ -1296,97 +1411,11 @@ static int balancer_process_balancer_worker(request_rec *r, proxy_server_conf *c if ((val = apr_table_get(params, "b_wyes")) && (*val == '1' && *(val+1) == '\0') && (val = apr_table_get(params, "b_nwrkr"))) { - char *ret; - proxy_worker *nworker; - nworker = ap_proxy_get_worker(r->pool, bsel, conf, val); - if (!nworker && storage->num_free_slots(bsel->wslot)) { -#if APR_HAS_THREADS - if ((rv = PROXY_GLOBAL_LOCK(bsel)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01194) - "%s: Lock failed for adding worker", - bsel->s->name); - } -#endif - ret = ap_proxy_define_worker(conf->pool, &nworker, bsel, conf, val, 0); - if (!ret) { - unsigned int index; - proxy_worker_shared *shm; - PROXY_COPY_CONF_PARAMS(nworker, conf); - if ((rv = storage->grab(bsel->wslot, &index)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01195) - "worker slotmem_grab failed"); -#if APR_HAS_THREADS - if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01196) - "%s: Unlock failed for adding worker", - bsel->s->name); - } -#endif - return HTTP_BAD_REQUEST; - } - if ((rv = storage->dptr(bsel->wslot, index, (void *)&shm)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01197) - "worker slotmem_dptr failed"); -#if APR_HAS_THREADS - if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01198) - "%s: Unlock failed for adding worker", - bsel->s->name); - } -#endif - return HTTP_BAD_REQUEST; - } - if ((rv = ap_proxy_share_worker(nworker, shm, index)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01199) - "Cannot share worker"); -#if APR_HAS_THREADS - if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01200) - "%s: Unlock failed for adding worker", - bsel->s->name); - } -#endif - return HTTP_BAD_REQUEST; - } - if ((rv = ap_proxy_initialize_worker(nworker, r->server, conf->pool)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_EMERG, rv, r, APLOGNO(01201) - "Cannot init worker"); -#if APR_HAS_THREADS - if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01202) - "%s: Unlock failed for adding worker", - bsel->s->name); - } -#endif - return HTTP_BAD_REQUEST; - } - /* sync all timestamps */ - bsel->wupdated = bsel->s->wupdated = nworker->s->updated = apr_time_now(); - /* by default, all new workers are disabled */ - ap_proxy_set_wstatus(PROXY_WORKER_DISABLED_FLAG, 1, nworker); - } else { - ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10163) - "%s: failed to add worker %s", - bsel->s->name, val); -#if APR_HAS_THREADS - PROXY_GLOBAL_UNLOCK(bsel); -#endif - return HTTP_BAD_REQUEST; - } -#if APR_HAS_THREADS - if ((rv = PROXY_GLOBAL_UNLOCK(bsel)) != APR_SUCCESS) { - ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01203) - "%s: Unlock failed for adding worker", - bsel->s->name); - } -#endif - } else { - ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(10164) - "%s: failed to add worker %s", - bsel->s->name, val); - return HTTP_BAD_REQUEST; + int rc = balancer_add_worker(r, bsel, conf, val, + apr_table_get(params, "b_nwrkr_flags")); + if (rc != APR_SUCCESS) { + return rc; } - } } diff --git a/modules/proxy/mod_proxy_beacon-guide.md b/modules/proxy/mod_proxy_beacon-guide.md new file mode 100644 index 00000000000..a7b4670f6f2 --- /dev/null +++ b/modules/proxy/mod_proxy_beacon-guide.md @@ -0,0 +1,369 @@ +# A Practical Guide to `mod_proxy_beacon` + +*Self-registering, self-healing reverse-proxy balancer membership over UDP.* + +--- + +## 1. What it does + +Normally, adding a backend to an httpd reverse-proxy load balancer means editing +the proxy config (or clicking around in `balancer-manager`) every time the fleet +changes. `mod_proxy_beacon` flips that around: **each backend announces itself** +to the proxy, and the proxy automatically: + +- **adds and enables** the backend as a live `BalancerMember` when it first + announces, and +- **disables it** (takes it out of rotation) when it stops announcing — then + **re-enables it** when it comes back. + +The result is a balancer whose membership tracks the running fleet with no +operator action. A backend added this way is a normal balancer member: it shows +up in `balancer-manager` and behaves exactly like a statically configured +`BalancerMember`. + +``` + backend-1 ──┐ (periodic UDP "BEACON" datagrams, + backend-2 ──┤ each advertising its own URL) + backend-3 ──┘ │ + ▼ + ┌──────────────┐ + │ reverse proxy│ ProxyBeaconListen :5555 + │ balancer:// │ → add / enable / evict members + │ cluster │ + └──────────────┘ + │ + clients +``` + +--- + +## 2. How it works (the short version) + +- **Transport:** plain **unicast UDP** datagrams (not multicast — multicast is + filtered on most networks and never crosses the public Internet). Backends + `sendto` the proxy; the proxy binds one socket and receives. No external + library — APR sockets for transport, APR-util SipHash for auth. +- **Fire-and-forget:** a lost datagram is simply recovered by the next periodic + announcement; reordered/replayed datagrams are rejected by a per-backend + timestamp check. No connection, reconnect, or framing layer. +- **Where it runs:** all the work happens in a single `mod_watchdog` **singleton** + child process, which owns the socket and applies membership changes. The change + propagates fleet-wide through the balancer's shared-memory “updated” timestamp, + the same way `balancer-manager` edits do. + +--- + +## 3. Requirements + +| Need | Why | +|------|-----| +| `mod_proxy` + `mod_proxy_balancer` | the balancer the members are added to | +| `mod_watchdog` | runs the background send/receive/evict loop | +| A **non-prefork** MPM (`event`, `worker`, …) | the watchdog singleton can't run under `prefork`; the module is silently inactive there | +| `mod_proxy_http` (or your backend protocol module) | to actually proxy the traffic | + +Build it with `--enable-proxy-beacon`; no `--enable-mods-*` selection includes it. Confirm +it's present: + +```sh +httpd -M 2>&1 | grep proxy_beacon # shared build +# or +httpd -l | grep mod_proxy_beacon # static build +``` + +--- + +## 4. Quick start + +### On the reverse proxy + +```apache +# Receive backend announcements on the cluster-facing interface (UDP/5555). +ProxyBeaconListen 0.0.0.0:5555 +ProxyBeaconSecret "hex:00112233445566778899aabbccddeeff" +ProxyBeaconBalancer cluster + +# Drop a backend from rotation if it goes silent for 30s; re-add on next beacon. +ProxyBeaconTimeout 30 + +# An initially EMPTY balancer with spare slots for the dynamic members. + + ProxySet growth=16 + + +ProxyPass "/" "balancer://cluster/" +ProxyPassReverse "/" "balancer://cluster/" +``` + +### On each backend + +```apache +# Announce this backend's routable origin to the proxy every 10s (UDP). +ProxyBeaconAddress proxy.example.com:5555 +ProxyBeaconAdvertise http://10.0.0.5:8080 +ProxyBeaconSecret "hex:00112233445566778899aabbccddeeff" +ProxyBeaconInterval 10 +``` + +That's it. Start the backends; within one announcement interval each one appears +as an enabled member of `balancer://cluster` on the proxy. Stop one, and after +`ProxyBeaconTimeout` it drops out of rotation; start it again and it returns. + +> **`ProxyBeaconAdvertise` must be the URL the *proxy* can reach** — the +> backend's routable origin, not `127.0.0.1`. It's validated at config-parse +> time and must be a full `scheme://host[:port]` **with no path** (see +> [Member identity](#member-identity)). + +--- + +## 5. Directive reference + +### Proxy side (the receiver) + +| Directive | Default | Meaning | +|-----------|---------|---------| +| `ProxyBeaconListen [addr][:port]` | — | **Marks this server as the receiver.** Binds a UDP socket. `addr`/`port` are optional and inherited from the server's own `Listen`/`ServerName` when omitted (see note below). | +| `ProxyBeaconBalancer name` | — | Balancer that announced backends are added to. Bare name (`cluster`); a leading `balancer://` is stripped. Must already exist with spare `growth`. | +| `ProxyBeaconTimeout interval` | `0` (no eviction) | Seconds of silence before a member is disabled. `0` = add-only, never auto-remove. Set to a small multiple of the backends' interval to get self-healing. | +| `ProxyBeaconSecret secret` | — (**required**) | Shared cluster secret; **same value on proxy and all backends**, either `hex:` + 32 hex digits (a random key: `openssl rand -hex 16`) or a passphrase of at least 16 characters (weaker: guessable offline from one captured packet). The server fails to start if a participating server omits it or it is invalid. | +| `ProxyBeaconMaxSkew interval` | `30` | Anti-replay freshness window: reject announcements whose signed timestamp is more than this far from now (either direction). Sub-second values (`500ms`) are honoured. | + +**Inheriting the listen address:** because UDP and TCP are separate port spaces, +`ProxyBeaconListen` can share the server's own service port without colliding +with the TCP listener. With no argument it binds the server's own address:port; +given just an address it inherits the port; etc. (The socket binds in an +unprivileged watchdog child, so you **can't** share a privileged port like 80/443 +this way — use an explicit high port there.) + +### Backend side (the sender) + +| Directive | Default | Meaning | +|-----------|---------|---------| +| `ProxyBeaconAddress addr:port` | — | **Marks this server as a sender.** UDP target = the proxy's `ProxyBeaconListen` address. | +| `ProxyBeaconAdvertise url` | — | The routable `scheme://host[:port]` origin the proxy adds as a member — no path, query, fragment or userinfo (rejected at config time). Omit it and the backend beacons but advertises nothing (logged, never added). | +| `ProxyBeaconInterval interval` | `5` | How often this backend announces. Must be **meaningfully smaller** than the proxy's `ProxyBeaconTimeout`. | +| `ProxyBeaconSecret secret` | — (**required**) | Same shared secret as the proxy. | + +> `ProxyBeaconListen` and `ProxyBeaconAddress` are **mutually exclusive** on the +> same server — a server is either a receiver or a sender, not both. + +All directives accept `server config` and `virtual host` context. Interval-style +directives use the standard httpd +[time-interval syntax](../../docs/manual/mod/directive-dict.html#Syntax) and +default to seconds (e.g. `ProxyBeaconInterval 10` or `... 500ms`). + +### Member identity + +An announced URL names a backend **origin** — `scheme://host[:port]`, nothing +more. The proxy canonicalizes it and uses that one string as the member's +identity everywhere: the key for its lease and replay state, the worker name it +creates, and the name used for every later enable or evict. + +- **Canonical form:** scheme and host lower-cased, the scheme's default port + dropped, a single trailing `/` ignored. `HTTP://App.Example.com:80`, + `http://app.example.com/` and `http://app.example.com` are **one** member. +- **Rejected:** a path (other than `/`), query, fragment, userinfo, an invalid + port, or the `unix:/path|http://…` socket form. These are dropped and logged as + `unacceptable url`; the backend is not added. `ProxyBeaconAdvertise` enforces + the same rule when the config is parsed, so a backend can't be misconfigured + into announcing one. + +**Why no paths?** The balancer finds a member by *longest-prefix* match. +`http://10.0.0.5:8080/one` and `http://10.0.0.5:8080/one/two` would be tracked as +two members with separate leases but resolve to one worker — so when one lease +lapsed, the proxy would disable a worker whose other lease was still current. If +you need different paths to go to different places, do that on the proxy with +`ProxyPass`; advertise only where the backend lives. + +### Ownership and hand-off + +Beacon marks every worker it creates with the **`Bcn`** status (flag `B`, visible +in the balancer-manager). It only ever enables or evicts workers carrying that +mark: a `BalancerMember` from your configuration, or one an administrator added, +is never touched, even if a backend announces exactly its URL. + +The announcements and leases are handled by **one** watchdog child. If that child +dies, the watchdog moves to another child, which starts with no memory of the +members. On taking over it **adopts every `Bcn` member** in the balancer and +starts their leases afresh: + +- a member that has since gone silent is evicted `ProxyBeaconTimeout` after the + hand-off, instead of staying enabled forever; +- a member that was already disabled is treated as evicted and is re-enabled by + its next announcement. + +Two things to know: a dead backend can stay in rotation for up to one +`ProxyBeaconTimeout` after a hand-off, and the per-member replay high-water mark +is not carried over — during a hand-off a captured announcement still inside +`ProxyBeaconMaxSkew` can be replayed once per member, refreshing that lease for one +timeout (it cannot add a member without the secret). + +**Holding a member out of rotation.** Beacon owns a member's **Disabled** flag +(lease expiry sets it, the next announcement clears it), so a manual "Disable" in +the balancer-manager is overridden. To keep a member out regardless of what it +announces, set it **Stopped** or **Drain** — beacon never touches those, nor the +health-check failure flag. + +**Capacity.** At most 256 announced URLs are tracked. Records of evicted members +and of failed adds are released after being silent for more than twice +`ProxyBeaconMaxSkew` (a replay of their last message would be stale by then), so +they don't lock out new backends; a member that comes back is re-adopted. A +balancer itself accepts at most 100 runtime members (`growth`). A holder of the +secret can still fill the table with distinct URLs until they fall silent. + +**Socket problems.** If the UDP socket can't be opened (unresolvable address, port +in use) it is retried with back-off, 30 s doubling to 10 min. Name lookups are +synchronous on the single watchdog thread shared by every beacon configuration of +the server, so an unresolvable name can stall them all for as long as the resolver +takes to give up — **use IP addresses** in `ProxyBeaconAddress` / `ProxyBeaconListen`. + +> A new owner can only start once the old one's `watchdog-callback` mutex is +> released. If the default mechanism isn't released when its holder is killed on +> your platform, pick one that is: `Mutex sysvsem watchdog-callback`. + +--- + +## 6. Security — read this before production + +The control channel decides where the proxy sends client traffic, so an +unauthenticated channel is a route-hijack / SSRF risk: anyone who can reach the +receive port could announce an arbitrary backend URL, and **UDP source addresses +are trivially spoofable.** + +`ProxyBeaconSecret` is therefore **required** (identical on proxy and every +backend) — `httpd -t` and startup both fail if a participating server omits it, so +there is no unauthenticated mode to fall into. With it: + +- Each announcement is signed with a **SipHash-2-4 MAC** plus a timestamp; the + proxy recomputes the MAC (constant-time compare) and drops anything forged or + tampered **before parsing the URL**. +- **Replay protection is two-layered:** (1) the `ProxyBeaconMaxSkew` freshness + window rejects stale timestamps, and (2) a per-backend high-water mark rejects + any timestamp that doesn't strictly advance — so capturing and re-sending a + dead backend's last datagram (to keep it from being evicted) is rejected even + inside the freshness window. + +**What the secret is.** A valid MAC proves only that the sender holds the +secret — not that it owns the URL it announces, may speak for another backend, or +is ready to serve. Every holder can register any origin the proxy can reach, +keep other members' leases alive, and use up growth slots and tracking records. +Treat the secret as an **administrator credential for the balancer** and share it +only among hosts you'd trust with that; it is not a boundary between partially +trusted workloads. Because the key is derived from the passphrase with a fast +hash (and the tag is 64 bits), a captured announcement allows offline guessing: +**use a long random secret** (at least 16 characters is enforced). + +**What is checked.** Every datagram is dropped unless it is ≤ 2048 bytes with no +NUL, carries a valid MAC (even when no `ProxyBeaconBalancer` is set, so log-only +mode logs only authenticated announcements), has the exact `BEACON key=value … mac=…` +shape with no repeated field and a plain decimal `ts=`, and names a printable-ASCII +origin. + +Operational notes: + +- **Clocks must be roughly in sync** (NTP). The timestamp check compares the + announcement's time against the proxy's clock; widen `ProxyBeaconMaxSkew` if + your hosts drift. +- The secret lives in your config file — **restrict its permissions like a + private key.** +- Announcements are **authenticated, not encrypted.** The payload is operational + metadata (URLs), not secrets. There's no transport confidentiality (DTLS would + be a separate future layer). + +--- + +## 7. Tuning + +- **Interval vs. timeout.** Keep `ProxyBeaconInterval` well under + `ProxyBeaconTimeout` so an occasional dropped datagram doesn't evict a healthy + backend. A common ratio is timeout ≈ 3–6× interval (e.g. interval 10s, timeout + 30–60s). +- **Size `growth` for your peak fleet.** A runtime-added member occupies one + growth slot **for the life of the proxy process** — it's *disabled* on + eviction, not removed (httpd can't remove workers at runtime, mirroring + `balancer-manager`). So `growth` must cover the maximum number of distinct + backend URLs you ever expect, not just the count live at one moment. +- **One proxy, many backends.** A single receiver serves the whole fleet. For + multiple proxies, run `ProxyBeaconListen` on each and point backends at all of + them (one `ProxyBeaconAddress` server per proxy, or accept that only the + configured proxy learns about the backend). + +--- + +## 8. Verifying & troubleshooting + +**See members appear:** enable `balancer-manager` on the proxy and watch the +worker list: + +```apache + + SetHandler balancer-manager + Require host localhost + +``` + +**Watch the log.** Bump verbosity for the module and tail the error log: + +```apache +LogLevel proxy_beacon:info +``` + +Useful log signals (grep the error log): + +| Log fragment | Means | +|--------------|-------| +| `received: BEACON ... url=...` | proxy is receiving announcements | +| `added backend ... balancer://cluster` | member created + enabled | +| `evicted backend ...` | a backend went silent past the timeout | +| `re-enabled backend ...` | a previously-evicted backend came back | +| `dropped ... mac mismatch` | wrong/missing secret on a sender (or a forged datagram) | +| `replayed/reordered ts` | a stale/duplicate datagram was rejected | +| `dropped ... oversize datagram` / `embedded NUL` / `bad frame` / `duplicate field` / `bad ts` | a datagram that isn't a well-formed announcement (see "What is checked") | +| `dropped ... member table full` | 256 urls are already tracked; records free up as silent ones age out (see Capacity) | +| `dropped ... unacceptable url` | an announcement's `url=` is not a plain origin (it has a path, query, userinfo, a bad port, or is a `unix:` URL) | +| `took over N existing member(s)` | a new watchdog owner adopted the beacon-created members already in the balancer (see [Ownership and hand-off](#ownership-and-hand-off)) | +| `dropped ... member not managed by beacon` | a backend announced the URL of a worker beacon did not create (configured or admin-added); it is left alone | +| `dropped ... balancer add not confirmed` | the balancer reported success but no such member exists; retried after the back-off | +| `ProxyBeaconSecret is required` (startup) | a participating server has no `ProxyBeaconSecret` — startup aborts | + +**Common gotchas:** + +- *Backend never joins.* Usually a **secret mismatch** (look for `mac mismatch`) + or a firewall blocking **UDP** on the beacon port (it's UDP, not TCP — separate + rule). Confirm the proxy is logging `received: BEACON` at all. +- *Nothing happens, no errors.* You're probably on the **prefork MPM** — the + watchdog singleton doesn't run there, so the module is inactive. Switch to + `event`/`worker`. +- *Traffic 503s to a backend that's “up”.* Check that `ProxyBeaconAdvertise` is + the URL the **proxy** can reach (not the backend's loopback) and that the + balancer has free `growth` slots. +- *Healthy backend keeps getting evicted.* Interval too close to timeout, or + clock skew larger than `ProxyBeaconMaxSkew`. Widen the timeout/skew or sync + clocks. + +--- + +## 9. The wire format (for the curious) + +One ASCII, space-separated, key=value datagram per announcement: + +``` +BEACON url=http://host:port host= pid= seq= ts= mac= +``` + +- `url=` — the routable origin added as a `BalancerMember`; `scheme://host[:port]` + only (see [Member identity](#member-identity)). +- `ts=` (microseconds since epoch) and `mac=` — present only when a secret is set; + `ts` drives replay protection, `mac` is the SipHash signature. +- `host=` / `pid=` / `seq=` — informational. (`seq` resets on backend restart, so + it's *not* used for replay detection — the wall-clock `ts` is.) + +--- + +## 10. See also + +- `mod_proxy`, `mod_proxy_balancer` — the balancer these members live in +- `mod_proxy_hcheck` — active health checking, complementary to beacon liveness +- `mod_watchdog` — the background runner this module rides on +- `modules/proxy/README.beacon` — the architecture/internals companion to this guide +- `docs/manual/mod/mod_proxy_beacon.xml` — the formal directive reference diff --git a/modules/proxy/mod_proxy_beacon.c b/modules/proxy/mod_proxy_beacon.c new file mode 100644 index 00000000000..a94df22a7b3 --- /dev/null +++ b/modules/proxy/mod_proxy_beacon.c @@ -0,0 +1,2083 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * mod_proxy_beacon -- a UDP datagram announcement channel between backend + * servers and a front-end reverse proxy, by which backends self-register as + * balancer members. + * + * This module uses plain APR UDP sockets, adapting the socket-handling pattern + * of mod_heartmonitor. UDP datagrams are a natural fit for small, periodic, + * fire-and-forget announcements, and avoid a third-party dependency. + * + * UNICAST, not multicast: unlike mod_heartbeat (which multicasts to a group), + * each backend sends a point-to-point datagram to the proxy's configured address + * (apr_socket_sendto to a single resolved unicast sockaddr). Multicast is + * filtered on most networks and does not traverse the public Internet, so a + * cross-host control plane must be unicast. The proxy is a fixed unicast + * rendezvous; each backend is configured with its address. + * + * Direction: backends announce themselves to the proxy. The proxy binds a + * stable UDP port (the rendezvous) and receives; each backend sends to it: + * + * - Reverse proxy: ProxyBeaconListen 0.0.0.0:5555 (receiver, binds) + * - Backend server: ProxyBeaconAddress proxy-host:5555 (sender, sendto) + * + * A leading scheme (e.g. tcp://) in the address is accepted and ignored, so + * addresses written with a transport scheme keep working. Each backend sends + * a "BEACON" datagram every interval. Datagrams are fire-and-forget: a lost + * packet just delays an update by one interval, and reordering is rejected by + * the per-url monotonic timestamp (Phase 4), so the design tolerates UDP's lack + * of delivery/ordering guarantees without a reconnect or framing layer. + * + * Phase 1 (the channel): the proxy simply logged each announcement, proving the + * channel works between separate, remote servers. + * + * Phase 2: when the proxy receives an announcement that carries a backend + * URL, it ADDS that backend as a member (worker) of a configured balancer and + * ENABLES it -- the dynamic equivalent of "Add Worker" in the balancer-manager + * web UI, but driven by the backend announcing itself. We reuse + * mod_proxy_balancer's exported balancer_manage() optional function (the same + * core balancer_handler calls), so the add path is identical to the proven + * manager flow. The backend advertises its routable URL via ProxyBeaconAdvertise; + * the proxy names the target balancer via ProxyBeaconBalancer. + * + * Phase 3: the inverse -- when a backend STOPS announcing for longer than + * ProxyBeaconTimeout, the proxy takes it out of rotation by setting the worker's + * DISABLED flag (again via balancer_manage), and re-enables it if the backend + * starts announcing again. This gives the cluster automatic liveness without + * operator action. The timeout is a config directive (0 = disabled = pure + * Phase-2 behavior). All of this runs in the watchdog singleton that already + * owns the socket, so the per-URL last-seen table lives in this process's + * ctx -- no shared memory. + * + * Phase 4: authenticate the channel. Without this, anyone who can reach the + * proxy's bound port can announce an arbitrary url and the proxy will route real + * client traffic to it (SSRF / hijack) -- and a UDP source address is trivially + * spoofable, so authentication matters as much here as on any control plane. With + * a pre-shared cluster secret (ProxyBeaconSecret) on both ends, the sender appends + * a keyed MAC (SipHash-2-4 via APR-util -- the same primitive mod_session_crypto + * uses) plus a timestamp; the receiver recomputes the MAC and checks timestamp + * freshness (anti-replay), dropping any forged, tampered, or stale message + * before it is parsed/acted on. Authentication is REQUIRED: ProxyBeaconSecret + * must be set on every server that participates in the channel (sender or + * listener), or startup fails -- there is no unauthenticated mode. We + * authenticate, not encrypt -- the payload (backend URLs) is not secret; for + * transport confidentiality DTLS would be a separate, orthogonal future layer. + * + * The background work runs on a mod_watchdog SINGLETON instance (exactly one + * child process owns the socket), mirroring mod_proxy_hcheck.c. That child has + * no request_rec, so the receiver synthesizes a minimal one for balancer_manage() + * (see beacon_make_fake_request -- adapted from mod_proxy_hcheck's + * create_request_rec, plus a fake conn_rec that ap_log_rerror requires). + */ + +#include "httpd.h" +#include "http_config.h" +#include "http_core.h" +#include "http_log.h" +#include "http_protocol.h" +#include "ap_provider.h" +#include "ap_listen.h" +#include "mod_watchdog.h" +#include "mod_proxy.h" + +#include "apr_strings.h" +#include "apr_time.h" +#include "apr_hash.h" +#include "apr_uri.h" +#include "apr_network_io.h" +#include "apr_siphash.h" +#include "apr_md5.h" + +#if APR_HAVE_PROCESS_H +#include /* for getpid() on Windows */ +#endif +#if APR_HAVE_UNISTD_H +#include /* for getpid() */ +#endif + +module AP_MODULE_DECLARE_DATA proxy_beacon_module; + +#define BEACON_WATCHDOG_NAME "_proxy_beacon_" +#define BEACON_DEFAULT_INTERVAL apr_time_from_sec(5) + +typedef enum { + BEACON_ROLE_NONE = 0, + BEACON_ROLE_SEND, /* backend: dials the proxy and announces itself */ + BEACON_ROLE_LISTEN /* reverse proxy: listens and receives announcements */ +} beacon_role_e; + +/* Longest announced url we handle (including the NUL). */ +#define BEACON_URL_MAX 512 + +/* listener-side per-backend state, keyed by url in ctx->seen. */ +typedef struct beacon_member_t { + apr_time_t last_seen; /* updated on every beacon for this url */ + apr_time_t last_attempt; /* last add attempt (throttles retry when full) */ + apr_int64_t last_ts; /* highest signed ts= accepted (replay guard) */ + int added; /* worker exists in the balancer (add dedup) */ + int evicted; /* WE set DISABLED on timeout (guards flip churn) */ + char url[BEACON_URL_MAX]; /* the key in ctx->seen (the hash keeps no copy) */ + struct beacon_member_t *next_free; /* free list link while unused */ +} beacon_member_t; + +typedef struct { + apr_pool_t *p; /* subpool for this context */ + server_rec *s; /* canonical server identity */ + char *pub_url; /* ProxyBeaconAddress (backend dial url) */ + char *sub_url; /* ProxyBeaconListen (proxy listen url) */ + char *advertise_url;/* ProxyBeaconAdvertise (sender: routable url) */ + char *balancer_name;/* ProxyBeaconBalancer (listener: bare bal name) */ + apr_interval_time_t interval; /* ProxyBeaconInterval (announce period) */ + apr_interval_time_t evict_timeout;/* ProxyBeaconTimeout (0 = no eviction) */ + beacon_role_e role; + apr_socket_t *sock; /* live UDP socket; valid only when opened */ + apr_sockaddr_t *addr; /* listener: bind addr; sender: destination addr */ + int opened; /* guard double-open / stop-without-start */ + apr_time_t last_publish; /* sender throttle */ + apr_time_t last_sweep; /* listener eviction-scan throttle */ + apr_uint64_t seq; /* announcement counter */ + apr_hash_t *seen; /* listener: url -> beacon_member_t* */ + beacon_member_t *free_members; /* listener: reclaimed records, for reuse */ + APR_OPTIONAL_FN_TYPE(balancer_manage) *manage_fn; /* listener: cached, lazy */ + /* Phase 4: channel authentication. */ + int has_secret; /* ProxyBeaconSecret was set */ + unsigned char mac_key[APR_MD5_DIGESTSIZE]; /* siphash key (16 bytes) */ + apr_interval_time_t max_skew; /* ProxyBeaconMaxSkew (replay window); 0 = default */ + apr_uint64_t reject_count; /* listener: dropped-since-last-log counter */ + apr_time_t last_reject_log; /* listener: reject-log rate limiter */ + int open_failed; /* socket open failed; retried with back-off */ + int reconciled; /* listener: adopted pre-existing members as owner */ + apr_pool_t *open_pool; /* socket + address of the current open attempt */ + apr_time_t next_open_try; /* when to retry a failed open (0 = not scheduled) */ + apr_interval_time_t open_delay; /* current retry back-off (0 = no failure yet) */ + int io_errors; /* failed sends/receives in a row */ + apr_time_t last_io_error_log; + apr_time_t next_refresh; /* sender: when to resolve the destination again */ + apr_pool_t *addr_pool; /* sender: a refreshed destination, if any */ + apr_time_t recv_log_window; /* start of the second counted below */ + unsigned int recv_log_count; /* "received:" lines logged in it */ + apr_uint64_t recv_log_suppressed; /* ...and those it left out */ +} beacon_ctx_t; + +/* SipHash-2-4 output is 8 bytes -> 16 hex chars (+ NUL). */ +#define BEACON_MAC_HEXLEN (APR_SIPHASH_DSIZE * 2) +/* Shortest ProxyBeaconSecret accepted. */ +#define BEACON_MIN_SECRET_LEN 16 +/* A secret of this form is used directly as the MAC key (no passphrase). */ +#define BEACON_HEXKEY_PREFIX "hex:" +#define BEACON_MAXSKEW_DEFAULT apr_time_from_sec(30) + +/* Max announcement datagram we accept. Our messages are a few hundred bytes; + * anything larger is not one of ours and is dropped. */ +#define BEACON_MAX_MSG_LEN 2048 + +/* When an add fails (e.g. the balancer is full), don't retry on every + * announcement -- back off this long between attempts for a given url. */ +#define BEACON_RETRY_BACKOFF apr_time_from_sec(60) + +/* Cap on tracked backend urls, to bound memory against a buggy or compromised + * (authenticated) backend announcing unboundedly many distinct urls. Once + * reached, unknown urls are dropped (rate-limited log) rather than tracked/added. */ +#define BEACON_MAX_MEMBERS 256 + +/* A failed socket open (unresolvable address, port in use, ...) is retried: the + * cause may be transient (a name server that is not up yet). The delay starts + * at BEACON_OPEN_RETRY and doubles up to BEACON_OPEN_RETRY_MAX. Retrying every + * watchdog tick would flood the error log, and an address lookup blocks the + * (single, shared) watchdog thread for as long as the resolver takes to give + * up, so a failing name must not be retried often. */ +#define BEACON_OPEN_RETRY apr_time_from_sec(30) +#define BEACON_OPEN_RETRY_MAX apr_time_from_sec(600) + +/* Cap on datagrams handled per watchdog tick, so a flood can't hold the + * watchdog thread in the receive loop; the rest wait for the next tick. */ +#define BEACON_MAX_DRAIN 1024 +/* ...and no more than this much time per tick, so that a flood of datagrams + * cannot keep the watchdog thread from the eviction sweep and the other + * contexts that share it. */ +#define BEACON_DRAIN_BUDGET apr_time_from_msec(50) +/* After this many failed sends or receives in a row the socket is closed and + * reopened (re-resolving the address) under the open back-off. */ +#define BEACON_IO_ERRORS_MAX 5 +/* A sender looks its destination up again this often, so that a proxy which + * moved to another address is found. */ +#define BEACON_REFRESH apr_time_from_sec(300) +/* The "received:" lines, at most this many per second and context. */ +#define BEACON_RECV_LOG_PER_SEC 20 + +/* Process-wide watchdog handle, like mod_proxy_hcheck's static watchdog. */ +static ap_watchdog_t *beacon_watchdog; + +/* + * Per-server config. No socket calls here -- the role may not even be known yet, + * and this runs in the parent at config-parse time (possibly more than once). + */ +static void *beacon_create_server_config(apr_pool_t *p, server_rec *s) +{ + beacon_ctx_t *ctx = apr_pcalloc(p, sizeof(beacon_ctx_t)); + + ctx->s = s; + apr_pool_create(&ctx->p, p); + apr_pool_tag(ctx->p, "proxy_beacon"); + ctx->interval = BEACON_DEFAULT_INTERVAL; + ctx->role = BEACON_ROLE_NONE; + ctx->seen = apr_hash_make(ctx->p); + + return ctx; +} + +static const char *beacon_set_sub_url(cmd_parms *cmd, void *dummy, + int argc, char *const argv[]) +{ + beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config, + &proxy_beacon_module); + const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); + if (err) { + return err; + } + if (argc > 1) { + return "ProxyBeaconListen takes at most one argument: [host][:port]"; + } + if (ctx->pub_url) { + return "ProxyBeaconListen and ProxyBeaconAddress are mutually exclusive " + "on the same server"; + } + /* No argument -> inherit both host and port from this server; one argument + * -> "[host][:port]", an omitted host or port being inherited from the + * server too. Store "" for the no-argument case (resolved against the + * server's own address at startup). */ + ctx->sub_url = (argc == 1) ? apr_pstrdup(cmd->pool, argv[0]) : ""; + ctx->role = BEACON_ROLE_LISTEN; + return NULL; +} + +static const char *beacon_set_pub_url(cmd_parms *cmd, void *dummy, const char *arg) +{ + beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config, + &proxy_beacon_module); + const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); + if (err) { + return err; + } + if (ctx->sub_url) { + return "ProxyBeaconListen and ProxyBeaconAddress are mutually exclusive " + "on the same server"; + } + ctx->pub_url = apr_pstrdup(cmd->pool, arg); + ctx->role = BEACON_ROLE_SEND; + return NULL; +} + +/* + * Canonical member identity. An announced url names a backend *origin*: + * scheme://host[:port], nothing more. Returns that origin in the exact form the + * proxy's worker-definition code stores it as the worker name -- lower-case + * scheme and host, the scheme's default port dropped, no trailing slash -- or + * NULL if url is not an origin (no scheme or host, a non-empty path, a query, + * a fragment, userinfo, or a port that is not a valid number). + * + * The announced string is used both as the key beacon tracks a member under and + * as the name handed to balancer_manage(), whose worker lookup is a + * longest-prefix match. Using one canonical origin for all of them keeps those + * identities equal; accepting paths would let /one and /one/two name the same + * worker while holding separate leases. + */ +static const char *beacon_canonical_url(apr_pool_t *pool, const char *url) +{ + apr_uri_t uri; + const char *host, *port = "", *c, *canon; + + /* Printable ASCII only: the url is logged and becomes a worker name. */ + for (c = url; *c; c++) { + if (!apr_isgraph(*c) || !apr_isascii(*c)) { + return NULL; + } + } + if (apr_uri_parse(pool, url, &uri) != APR_SUCCESS + || !uri.scheme || !*uri.scheme + || !uri.hostname || !*uri.hostname) { + return NULL; + } + if (uri.user || uri.password || uri.query || uri.fragment + || (uri.path && *uri.path && strcmp(uri.path, "/"))) { + return NULL; + } + /* apr_uri_parse() runs strtol() and truncates to 16 bits, so "-80" would + * otherwise come out as port 65456 and "99999" as 34463. */ + if (uri.port_str && *uri.port_str) { + const char *d; + unsigned long port_val = 0; + for (d = uri.port_str; *d; d++) { + if (!apr_isdigit(*d)) { + return NULL; + } + port_val = port_val * 10 + (*d - '0'); + if (port_val > 65535) { + return NULL; + } + } + if (!port_val) { + return NULL; + } + } + + /* The proxy truncates a scheme or worker name that does not fit its shared + * storage, which would give the member another identity than the one + * announced. */ + if (strlen(uri.scheme) >= PROXY_WORKER_MAX_SCHEME_SIZE + || strlen(uri.hostname) >= PROXY_RFC1035_HOSTNAME_SIZE) { + return NULL; + } + + ap_str_tolower(uri.scheme); + ap_str_tolower(uri.hostname); + host = ap_strchr_c(uri.hostname, ':') + ? apr_pstrcat(pool, "[", uri.hostname, "]", NULL) + : uri.hostname; + if (uri.port && uri.port != ap_proxy_port_of_scheme(uri.scheme)) { + port = apr_psprintf(pool, ":%u", (unsigned)uri.port); + } + canon = apr_pstrcat(pool, uri.scheme, "://", host, port, NULL); + return strlen(canon) < PROXY_WORKER_MAX_NAME_SIZE ? canon : NULL; +} + +static const char *beacon_set_advertise(cmd_parms *cmd, void *dummy, + const char *arg) +{ + beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config, + &proxy_beacon_module); + const char *canon; + const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); + if (err) { + return err; + } + /* Must be a routable backend origin (scheme://host[:port], no path); it + * becomes a BalancerMember on the proxy. Announce its canonical form, so + * sender and receiver agree on the member's identity. */ + canon = beacon_canonical_url(cmd->pool, arg); + if (!canon) { + return apr_psprintf(cmd->pool, + "ProxyBeaconAdvertise: '%s' is not a valid " + "scheme://host[:port] URL (no path, query, " + "fragment or userinfo; short enough to be a " + "worker name)", arg); + } + ctx->advertise_url = (char *)canon; + return NULL; +} + +static const char *beacon_set_balancer(cmd_parms *cmd, void *dummy, + const char *arg) +{ + beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config, + &proxy_beacon_module); + const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); + if (err) { + return err; + } + /* Store the bare name; balancer_manage() prepends BALANCER_PREFIX itself. + * Be forgiving if the admin wrote the full "balancer://name". */ + if (!strncasecmp(arg, BALANCER_PREFIX, sizeof(BALANCER_PREFIX) - 1)) { + arg += sizeof(BALANCER_PREFIX) - 1; + } + if (!*arg) { + return "ProxyBeaconBalancer: empty balancer name"; + } + ctx->balancer_name = apr_pstrdup(cmd->pool, arg); + return NULL; +} + +static const char *beacon_set_interval(cmd_parms *cmd, void *dummy, + const char *arg) +{ + beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config, + &proxy_beacon_module); + apr_interval_time_t iv; + apr_status_t rv; + const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); + if (err) { + return err; + } + rv = ap_timeout_parameter_parse(arg, &iv, "s"); + if (rv != APR_SUCCESS) { + return "Unparse-able ProxyBeaconInterval setting"; + } + if (iv < AP_WD_TM_SLICE) { + return apr_psprintf(cmd->pool, + "ProxyBeaconInterval must be greater than %" + APR_TIME_T_FMT "ms", + apr_time_as_msec(AP_WD_TM_SLICE)); + } + ctx->interval = iv; + return NULL; +} + +static const char *beacon_set_timeout(cmd_parms *cmd, void *dummy, + const char *arg) +{ + beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config, + &proxy_beacon_module); + apr_interval_time_t iv; + apr_status_t rv; + const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); + if (err) { + return err; + } + rv = ap_timeout_parameter_parse(arg, &iv, "s"); + if (rv != APR_SUCCESS || iv < 0) { + return "ProxyBeaconTimeout must be a non-negative time (0 disables " + "eviction)"; + } + /* 0 = eviction disabled (pure announce-and-add behavior). */ + ctx->evict_timeout = iv; + return NULL; +} + +static int beacon_hexval(char c) +{ + return apr_isdigit(c) ? c - '0' : apr_tolower(c) - 'a' + 10; +} + +static const char *beacon_set_secret(cmd_parms *cmd, void *dummy, const char *arg) +{ + beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config, + &proxy_beacon_module); + const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); + if (err) { + return err; + } + if (!*arg) { + return "ProxyBeaconSecret: empty secret"; + } + /* hex:<32 hex digits> is the key itself: a random 128-bit key has no + * passphrase to guess, so it needs no key derivation. */ + if (!strncmp(arg, BEACON_HEXKEY_PREFIX, sizeof(BEACON_HEXKEY_PREFIX) - 1)) { + const char *h = arg + sizeof(BEACON_HEXKEY_PREFIX) - 1; + int i; + + if (strlen(h) != 2 * sizeof(ctx->mac_key)) { + return apr_psprintf(cmd->pool, + "ProxyBeaconSecret: hex: needs exactly %d hex " + "digits (e.g. from 'openssl rand -hex %d')", + (int)(2 * sizeof(ctx->mac_key)), + (int)sizeof(ctx->mac_key)); + } + for (i = 0; i < (int)sizeof(ctx->mac_key); i++) { + if (!apr_isxdigit(h[2 * i]) || !apr_isxdigit(h[2 * i + 1])) { + return "ProxyBeaconSecret: hex: value has a non-hex digit"; + } + ctx->mac_key[i] = (unsigned char) + ((beacon_hexval(h[2 * i]) << 4) | beacon_hexval(h[2 * i + 1])); + } + ctx->has_secret = 1; + return NULL; + } + /* The MAC key is derived from the passphrase with a fast hash, so anyone who + * captures one announcement can test guesses offline at full speed; only a + * long random secret resists that. */ + if (strlen(arg) < BEACON_MIN_SECRET_LEN) { + return apr_psprintf(cmd->pool, + "ProxyBeaconSecret: the secret must be at least %d " + "characters (use a long random value)", + BEACON_MIN_SECRET_LEN); + } + /* Derive a 16-byte SipHash key from the passphrase. This is key + * derivation (spreading the shared secret to the key size both ends use), + * not message hashing, so MD5 is fine here -- same approach as + * mod_session_crypto.c's compute_auth(). */ + apr_md5(ctx->mac_key, arg, strlen(arg)); + ctx->has_secret = 1; + return NULL; +} + +static const char *beacon_set_maxskew(cmd_parms *cmd, void *dummy, const char *arg) +{ + beacon_ctx_t *ctx = ap_get_module_config(cmd->server->module_config, + &proxy_beacon_module); + apr_interval_time_t iv; + apr_status_t rv; + const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); + if (err) { + return err; + } + rv = ap_timeout_parameter_parse(arg, &iv, "s"); + if (rv != APR_SUCCESS || iv <= 0) { + return "ProxyBeaconMaxSkew must be a positive time (replay window)"; + } + ctx->max_skew = iv; + return NULL; +} + +static const command_rec beacon_cmds[] = { + AP_INIT_TAKE_ARGV("ProxyBeaconListen", beacon_set_sub_url, NULL, RSRC_CONF, + "reverse proxy: UDP address [host][:port] to receive beacons " + "on. An omitted host or port (or no argument at all) is " + "inherited from this server's own address and port, so the " + "beacon channel can share the service endpoint. " + "e.g. 0.0.0.0:5555"), + AP_INIT_TAKE1("ProxyBeaconAddress", beacon_set_pub_url, NULL, RSRC_CONF, + "backend: UDP address host:port of the proxy to send beacons " + "to, e.g. proxy-host:5555"), + AP_INIT_TAKE1("ProxyBeaconInterval", beacon_set_interval, NULL, RSRC_CONF, + "backend announcement interval in seconds (default 5)"), + AP_INIT_TAKE1("ProxyBeaconAdvertise", beacon_set_advertise, NULL, RSRC_CONF, + "backend: routable URL to advertise to the proxy, " + "e.g. http://10.0.0.5:8080 (added as a BalancerMember)"), + AP_INIT_TAKE1("ProxyBeaconBalancer", beacon_set_balancer, NULL, RSRC_CONF, + "proxy: name of the balancer that announced backends are " + "added to, e.g. mycluster (for balancer://mycluster)"), + AP_INIT_TAKE1("ProxyBeaconTimeout", beacon_set_timeout, NULL, RSRC_CONF, + "proxy: seconds without an announcement after which a backend " + "is disabled (taken out of rotation); 0 disables eviction"), + AP_INIT_TAKE1("ProxyBeaconSecret", beacon_set_secret, NULL, RSRC_CONF, + "pre-shared cluster secret (REQUIRED); set to the same value on " + "the proxy and all backends to authenticate announcements " + "(SipHash MAC). Keep the conf file readable only by the server " + "user."), + AP_INIT_TAKE1("ProxyBeaconMaxSkew", beacon_set_maxskew, NULL, RSRC_CONF, + "proxy: max allowed seconds between an announcement's timestamp " + "and now (anti-replay window; requires NTP-synced clocks). " + "Default 30 seconds."), + { NULL } +}; + +/* + * Resolve a "[scheme://][host][:port]" address string to a UDP sockaddr. Any + * leading scheme (e.g. tcp://) is accepted and ignored, so addresses written + * with a transport scheme keep working. A NULL/empty url, or an omitted host + * or port, is filled from the caller-supplied defaults: + * - default_host NULL -> bind/resolve the wildcard address (all interfaces); + * - default_port 0 -> the port is then required (APR_EINVAL if missing). + * Letting the host/port be inherited lets the beacon channel share the server's + * own address:port; UDP and TCP are independent port spaces, so binding UDP:N + * does not collide with the server's TCP listener. *addr_out is from p. + */ +/* + * Split "[host][:port]". apr_parse_addr_port() refuses a string that starts + * with ':', which the directive syntax allows to mean "this server's host". + */ +static apr_status_t beacon_parse_hostport(apr_pool_t *p, const char *hostport, + char **host, apr_port_t *port) +{ + char *scope; + + if (*hostport == ':') { + apr_off_t val; + char *end; + + if (apr_isdigit(hostport[1]) == 0 + || apr_strtoff(&val, hostport + 1, &end, 10) != APR_SUCCESS + || *end || val < 1 || val > 65535) { + return APR_EINVAL; + } + *host = NULL; + *port = (apr_port_t)val; + return APR_SUCCESS; + } + return apr_parse_addr_port(host, &scope, port, hostport, p); +} + +static apr_status_t beacon_resolve(apr_pool_t *p, const char *url, + const char *default_host, + apr_port_t default_port, + apr_sockaddr_t **addr_out) +{ + char *host = NULL; + apr_port_t port = 0; + apr_status_t rv; + + if (url && *url) { + const char *hostport = url, *sep; + if ((sep = ap_strstr_c(url, "://")) != NULL) { + hostport = sep + 3; + } + rv = beacon_parse_hostport(p, hostport, &host, &port); + if (rv != APR_SUCCESS) { + return rv; + } + } + if (!host || !*host) { + host = (char *)default_host; /* NULL -> wildcard (any address) */ + } + if (!port) { + port = default_port; + } + if (!port) { + return APR_EINVAL; /* no port given and none to inherit */ + } + return apr_sockaddr_info_get(addr_out, host, APR_UNSPEC, port, 0, p); +} + +/* + * The listener may inherit its bind host/port from this server (so the beacon + * channel can share the server's own endpoint). Derive a concrete address/port + * from the server's actual bound listeners (ap_listeners) -- this reflects the + * real Listen socket (e.g. 0.0.0.0), which is what the beacon should match, and + * avoids leaving the host NULL (which resolves to the IPv6 wildcard and could + * miss IPv4 senders on a v6-only-strict host). The port is the server's own + * (ServerName/Listen) port; the host is taken from the listener on that port, + * else the first listener. Either output may remain unset (host NULL / port 0) + * if no listeners are configured. + */ +static void beacon_server_default_addr(server_rec *s, const char **host_out, + apr_port_t *port_out) +{ + const char *host = NULL; + apr_port_t port = s->port; + ap_listen_rec *lr, *match = NULL; + + for (lr = ap_listeners; lr; lr = lr->next) { + if (!lr->bind_addr) { + continue; + } + if (!match) { + match = lr; /* first, as a fallback */ + } + if (port && lr->bind_addr->port == port) { + match = lr; /* prefer the server's own port */ + break; + } + } + if (match && match->bind_addr) { + char *ip = NULL; + if (!port) { + port = match->bind_addr->port; + } + if (apr_sockaddr_ip_get(&ip, match->bind_addr) == APR_SUCCESS) { + host = ip; + } + } + + *host_out = host; + *port_out = port; +} + +/* STARTING: open the UDP socket; listener binds to receive, sender resolves + * its destination. */ +static void beacon_cb_starting(beacon_ctx_t *ctx) +{ + server_rec *s = ctx->s; + apr_status_t rv; + + /* After an open/bind failure, wait for the retry in beacon_cb_running() + * (BEACON_OPEN_RETRY): retrying on every ~100ms watchdog tick would fill + * the error log. */ + if (ctx->opened || ctx->open_failed) { + return; + } + + /* The address and socket of an attempt live in their own pool, cleared + * before each retry so a persistent failure does not grow ctx->p. */ + if (ctx->addr_pool) { + apr_pool_destroy(ctx->addr_pool); + ctx->addr_pool = NULL; + } + if (ctx->open_pool) { + apr_pool_clear(ctx->open_pool); + } + else { + apr_pool_create(&ctx->open_pool, ctx->p); + } + + if (ctx->role == BEACON_ROLE_LISTEN) { + /* An omitted host and/or port in ProxyBeaconListen is inherited from + * this server's own address/port (ServerName/Listen), so the beacon + * channel can share the server's service endpoint. UDP and TCP are + * independent, so binding UDP: does not collide with the server's + * TCP listener. (A privileged port still cannot be bound here -- this + * callback runs in an unprivileged watchdog child -- so endpoint sharing + * is for non-privileged service ports.) */ + const char *defhost; + apr_port_t defport; + beacon_server_default_addr(s, &defhost, &defport); + if ((rv = beacon_resolve(ctx->open_pool, ctx->sub_url, defhost, defport, + &ctx->addr)) != APR_SUCCESS) { + ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, + APLOGNO(10567) "mod_proxy_beacon: cannot resolve " + "ProxyBeaconListen address '%s' (an omitted port " + "requires a known server port)", + *ctx->sub_url ? ctx->sub_url : "(inherit)"); + ctx->open_failed = 1; + return; + } + if ((rv = apr_socket_create(&ctx->sock, ctx->addr->family, SOCK_DGRAM, + APR_PROTO_UDP, ctx->open_pool)) != APR_SUCCESS) { + ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, + APLOGNO(10568) "mod_proxy_beacon: apr_socket_create failed"); + ctx->open_failed = 1; + return; + } + apr_socket_opt_set(ctx->sock, APR_SO_REUSEADDR, 1); + /* Receiving must never block: it happens on the watchdog thread. */ + if ((rv = apr_socket_opt_set(ctx->sock, APR_SO_NONBLOCK, 1)) + != APR_SUCCESS) { + ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, + APLOGNO(10637) "mod_proxy_beacon: cannot make the " + "listening socket non-blocking"); + apr_socket_close(ctx->sock); + ctx->open_failed = 1; + return; + } + if ((rv = apr_socket_bind(ctx->sock, ctx->addr)) != APR_SUCCESS) { + ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, + APLOGNO(10569) "mod_proxy_beacon: bind to %pI failed", + ctx->addr); + apr_socket_close(ctx->sock); + ctx->open_failed = 1; + return; + } + ctx->opened = 1; + ctx->io_errors = 0; + { + /* Nothing could have been received while the socket was closed: + * do not evict members for that silence. */ + apr_hash_index_t *hi; + apr_time_t t = apr_time_now(); + + for (hi = apr_hash_first(ctx->open_pool, ctx->seen); hi; + hi = apr_hash_next(hi)) { + void *val; + + apr_hash_this(hi, NULL, NULL, &val); + ((beacon_member_t *)val)->last_seen = t; + } + } + ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, + APLOGNO(10570) "mod_proxy_beacon: listening for beacons on %pI", + ctx->addr); + /* Warn if no balancer is configured: beacons will be logged but no + * backend workers will be added (Phase-1 log-only behavior). */ + if (!ctx->balancer_name) { + ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, + APLOGNO(10571) "mod_proxy_beacon: listener on %pI has no " + "ProxyBeaconBalancer; beacons will be logged only. " + "Set ProxyBeaconBalancer to add announced backends.", + ctx->addr); + } + } + else if (ctx->role == BEACON_ROLE_SEND) { + /* Sender: the destination host:port targets the proxy and cannot be + * inferred from this backend's own address, so both must be given + * explicitly (no defaults). */ + if ((rv = beacon_resolve(ctx->open_pool, ctx->pub_url, NULL, 0, &ctx->addr)) + != APR_SUCCESS) { + ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, + APLOGNO(10573) "mod_proxy_beacon: cannot resolve " + "ProxyBeaconAddress '%s' (must be host:port)", + ctx->pub_url); + ctx->open_failed = 1; + return; + } + if ((rv = apr_socket_create(&ctx->sock, ctx->addr->family, SOCK_DGRAM, + APR_PROTO_UDP, ctx->open_pool)) != APR_SUCCESS) { + ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, + APLOGNO(10574) "mod_proxy_beacon: apr_socket_create failed"); + ctx->open_failed = 1; + return; + } + /* UDP is connectionless: no dial, no reconnect. Datagrams are sent to + * ctx->addr each interval; if the proxy isn't up yet they are simply + * dropped and the next interval tries again. */ + if ((rv = apr_socket_opt_set(ctx->sock, APR_SO_NONBLOCK, 1)) + != APR_SUCCESS) { + ap_log_error(APLOG_MARK, APLOG_ERR, rv, s, + APLOGNO(10638) "mod_proxy_beacon: cannot make the " + "sending socket non-blocking"); + apr_socket_close(ctx->sock); + ctx->open_failed = 1; + return; + } + ctx->opened = 1; + ctx->io_errors = 0; + ctx->next_refresh = apr_time_now() + BEACON_REFRESH; + ctx->last_publish = 0; /* beacon on the first running tick */ + ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, + APLOGNO(10575) "mod_proxy_beacon: beaconing to %pI", ctx->addr); + } +} + +/* + * Synthesize a minimal request_rec for balancer_manage(), which runs here in + * the watchdog thread with no real client request. Adapted from + * mod_proxy_hcheck.c's create_request_rec (same watchdog context), but that one + * attaches a real backend conn_rec before logging; we have none, so we fabricate + * a minimal conn_rec too. + * + * balancer_manage()/balancer_process_balancer_worker() touch only r->pool, + * r->server, and ap_log_rerror(). ap_log_rerror is the trap: log_error_core() + * asserts r->connection != NULL and do_errorlog_default() unconditionally reads + * r->connection->outgoing, while add_log_id()->core_generate_log_id() reads + * c->current_thread. So we (a) give r a non-NULL conn_rec with ->outgoing set, + * and (b) pre-set r->log_id / c->log_id so the log-id generation path is skipped + * entirely. + */ +static request_rec *beacon_make_fake_request(apr_pool_t *p, server_rec *s) +{ + conn_rec *c = apr_pcalloc(p, sizeof(*c)); + request_rec *r = apr_pcalloc(p, sizeof(*r)); + + c->pool = p; + c->base_server = s; + c->log = &s->log; + c->log_id = "beacon"; /* non-NULL -> skip add_log_id/log-id gen */ + c->outgoing = 1; /* read by do_errorlog_default() */ + c->client_ip = "-"; + c->notes = apr_table_make(p, 1); + + r->pool = p; + r->server = s; + r->connection = c; + r->log = &s->log; + r->log_id = "beacon"; + r->per_dir_config = s->lookup_defaults; + r->request_config = ap_create_request_config(p); + r->notes = apr_table_make(p, 4); + r->subprocess_env = apr_table_make(p, 4); + r->headers_in = apr_table_make(p, 1); + r->headers_out = apr_table_make(p, 1); + r->err_headers_out = apr_table_make(p, 1); + r->useragent_ip = "-"; + r->useragent_addr = NULL; + r->proxyreq = PROXYREQ_PROXY; + r->status = HTTP_OK; + + return r; +} + +/* + * Resolve mod_proxy_balancer's balancer_manage() optional fn (lazily, cached). + * Registered at hook-registration time, so available by the time we run. + */ +static int beacon_have_manage_fn(beacon_ctx_t *ctx) +{ + if (!ctx->manage_fn) { + ctx->manage_fn = APR_RETRIEVE_OPTIONAL_FN(balancer_manage); + if (!ctx->manage_fn) { + ap_log_error(APLOG_MARK, APLOG_ERR, 0, ctx->s, + APLOGNO(10576) "mod_proxy_beacon: balancer_manage unavailable " + "(is mod_proxy_balancer loaded?)"); + return 0; + } + } + return 1; +} + +/* Status flags a beacon worker is created with (see b_nwrkr_flags). */ +static const char beacon_new_flags[] = { PROXY_WORKER_BEACON_FLAG, '\0' }; + +/* + * Look up url among the members of the configured balancer. Beacon only ever + * deals in canonical origins (see beacon_canonical_url()), for which the + * balancer's longest-prefix lookup can only match the worker of that exact name. + * balancer_manage()/balancer_process_balancer_worker() silently succeed on an + * operation on a worker they cannot find, so callers use this to learn what + * really happened. Returns NULL if there is no such member. + */ +static proxy_worker *beacon_find_worker(beacon_ctx_t *ctx, apr_pool_t *pool, + const char *url) +{ + proxy_server_conf *conf = + ap_get_module_config(ctx->s->module_config, &proxy_module); + proxy_balancer *bsel = ap_proxy_get_balancer(pool, conf, + apr_pstrcat(pool, BALANCER_PREFIX, ctx->balancer_name, NULL), 0); + proxy_worker *w; + + if (!bsel) { + return NULL; + } + /* A worker added through another child's balancer-manager is not in this + * process's view until synced; without it the ownership check is blind. */ + PROXY_THREAD_LOCK(bsel); + ap_proxy_sync_balancer(bsel, ctx->s, conf); + w = ap_proxy_get_worker(pool, bsel, conf, url); + PROXY_THREAD_UNLOCK(bsel); + return w; +} + +static int beacon_worker_exists(beacon_ctx_t *ctx, apr_pool_t *pool, + const char *url) +{ + return beacon_find_worker(ctx, pool, url) != NULL; +} + +/* + * Set (or clear) a worker's DISABLED flag via balancer_manage -- the exact path + * the balancer-manager UI uses (params { b, w, w_status_D }). This is how both + * "enable" (disabled=0) and "evict" (disabled=1) are performed. Returns + * APR_SUCCESS on success. + */ +static apr_status_t beacon_set_worker_disabled(beacon_ctx_t *ctx, apr_pool_t *pool, + const char *url, int disabled) +{ + apr_pool_t *subp; + request_rec *r; + apr_table_t *params; + apr_status_t rv; + + /* ctx->manage_fn is resolved lazily; a status change can be the first + * balancer operation this process performs (e.g. re-enabling a member + * adopted from the previous watchdog owner). */ + if (!beacon_have_manage_fn(ctx)) { + return APR_EGENERAL; + } + + /* balancer_manage() reports success when it finds no such worker, which + * would let us record a status change that never happened. */ + if (!beacon_worker_exists(ctx, pool, url)) { + return APR_ENOENT; + } + + apr_pool_create(&subp, pool); + r = beacon_make_fake_request(subp, ctx->s); + + params = apr_table_make(subp, 4); + apr_table_setn(params, "b", ctx->balancer_name); + apr_table_setn(params, "w", url); + apr_table_setn(params, "w_status_D", disabled ? "1" : "0"); + rv = ctx->manage_fn(r, params); + + apr_pool_destroy(subp); + return rv; +} + +/* + * Emit a rate-limited (~1/s) message about dropped/failed announcements, so a + * full balancer or a flood of bad urls can't flood the error log. Shares the + * counter/timer with the Phase-4 rejection logging. + */ +static void beacon_log_throttled(beacon_ctx_t *ctx, apr_time_t now, const char *what) +{ + ctx->reject_count++; + if (ctx->last_reject_log == 0 + || now - ctx->last_reject_log >= apr_time_from_sec(1)) { + ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ctx->s, + APLOGNO(10577) "mod_proxy_beacon: dropped %" APR_UINT64_T_FMT + " announcement(s) (last: %s)", ctx->reject_count, what); + ctx->reject_count = 0; + ctx->last_reject_log = now; + } +} + +/* + * Attempt to add (and enable) url as a member of the configured balancer, + * reusing balancer_manage(). Two calls: add (the worker is created DISABLED by + * default), then clear the DISABLED flag so it serves traffic. Updates the + * caller-owned member entry m: m->added is set on success. Returns APR_SUCCESS + * on success. A failure here (e.g. the balancer is full) is expected and + * handled by the caller via backoff, not retried every announcement. + * + * Beacon only manages workers it created: a worker it adds is marked with + * PROXY_WORKER_BEACON, which lives in the worker's shared state and so outlives + * both this process and the watchdog owner that set it. A same-named worker + * that is not so marked (a BalancerMember from the configuration, or one an + * administrator added) is left alone. + */ +static apr_status_t beacon_try_add(beacon_ctx_t *ctx, apr_pool_t *pool, + const char *url, beacon_member_t *m, + apr_time_t now) +{ + server_rec *s = ctx->s; + apr_pool_t *subp; + request_rec *r; + apr_table_t *params; + apr_status_t rv; + proxy_worker *w; + + m->last_attempt = now; + + if (!beacon_have_manage_fn(ctx)) { + return APR_EGENERAL; + } + + w = beacon_find_worker(ctx, pool, url); + if (w) { + /* The normal case after a graceful restart, when the balancer's + * members (persisted in shared memory) outlive this process's empty + * ctx->seen: balancer_manage() refuses to re-add an existing worker, + * so recover it -- otherwise a previously-evicted member would stay + * DISABLED forever -- but only if it is ours. */ + if (!(w->s->status & PROXY_WORKER_BEACON)) { + beacon_log_throttled(ctx, now, "member not managed by beacon"); + return APR_EEXIST; + } + ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, + APLOGNO(10589) "mod_proxy_beacon: backend %s already in " + "balancer://%s (re-adopted)", + url, ctx->balancer_name); + } + else { + /* Step 1: add the worker (created DISABLED). A genuinely full + * balancer fails here; that is throttled and retried only after the + * backoff window, not on every announcement. */ + apr_pool_create(&subp, pool); + r = beacon_make_fake_request(subp, s); + params = apr_table_make(subp, 4); + apr_table_setn(params, "b", ctx->balancer_name); + apr_table_setn(params, "b_nwrkr", url); + apr_table_setn(params, "b_wyes", "1"); + apr_table_setn(params, "b_nwrkr_flags", beacon_new_flags); + rv = ctx->manage_fn(r, params); + apr_pool_destroy(subp); + if (rv != APR_SUCCESS) { + beacon_log_throttled(ctx, now, "balancer add failed (full?)"); + return rv; + } + w = beacon_find_worker(ctx, pool, url); + if (!w) { + /* balancer_manage() said yes but there is no such member: don't + * claim a registration that did not happen. */ + beacon_log_throttled(ctx, now, "balancer add not confirmed"); + return APR_ENOENT; + } + if (!(w->s->status & PROXY_WORKER_BEACON)) { + /* Whatever this is, balancer_manage() did not create it with our + * mark, so it is not ours to manage (and to evict). */ + beacon_log_throttled(ctx, now, "member not created by beacon"); + return APR_EEXIST; + } + } + + /* Step 2: enable it (clear the DISABLED flag) so it serves traffic. + * beacon_set_worker_disabled is self-contained -- it creates its own subpool + * from `pool`. */ + rv = beacon_set_worker_disabled(ctx, pool, url, 0); + if (rv != APR_SUCCESS) { + ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, + APLOGNO(10578) "mod_proxy_beacon: added but failed to enable worker %s " + "in balancer://%s; will retry on its next announcement", + url, ctx->balancer_name); + /* Still a member, but disabled: recorded as evicted, so that the next + * announcement enables it (beacon_handle_announce). */ + m->added = 1; + m->evicted = 1; + return rv; + } + + m->added = 1; + m->evicted = 0; + ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, + APLOGNO(10579) "mod_proxy_beacon: added backend %s to balancer://%s", + url, ctx->balancer_name); + return APR_SUCCESS; +} + +/* + * Member records come from a free list, so the memory used for tracking is + * bounded by BEACON_MAX_MEMBERS records however many are reclaimed and + * recreated. Returns NULL if url does not fit. + */ +static beacon_member_t *beacon_member_new(beacon_ctx_t *ctx, const char *url, + apr_time_t now) +{ + beacon_member_t *m; + + if (strlen(url) >= BEACON_URL_MAX) { + return NULL; + } + if (ctx->free_members) { + m = ctx->free_members; + ctx->free_members = m->next_free; + } + else { + m = apr_palloc(ctx->p, sizeof(*m)); + } + memset(m, 0, sizeof(*m)); + strcpy(m->url, url); + m->last_seen = now; + apr_hash_set(ctx->seen, m->url, APR_HASH_KEY_STRING, m); + return m; +} + +static void beacon_member_free(beacon_ctx_t *ctx, beacon_member_t *m) +{ + apr_hash_set(ctx->seen, m->url, APR_HASH_KEY_STRING, NULL); + m->next_free = ctx->free_members; + ctx->free_members = m; +} + +/* + * Handle one announced url. Tracks every url in ctx->seen (capped) so that: + * - a successful member is deduplicated and its last_seen refreshed; + * - a previously-evicted member is re-enabled when it announces again; + * - an add that failed (e.g. balancer full) is retried only after a backoff, + * not on every announcement. + * msg_ts is the signed timestamp (microseconds) from the verified message; this + * path is only reached on the authenticated balancer path, so it is always set. + */ +static void beacon_handle_announce(beacon_ctx_t *ctx, apr_pool_t *pool, + const char *url, apr_time_t now, + apr_int64_t msg_ts) +{ + beacon_member_t *m = apr_hash_get(ctx->seen, url, APR_HASH_KEY_STRING); + + if (!m) { + /* Bound memory: don't track unboundedly many distinct urls (defense in + * depth against a buggy or compromised authenticated backend). */ + if (apr_hash_count(ctx->seen) >= BEACON_MAX_MEMBERS) { + beacon_log_throttled(ctx, now, "member table full"); + return; + } + m = beacon_member_new(ctx, url, now); + if (!m) { + return; + } + m->last_ts = msg_ts; + beacon_try_add(ctx, pool, m->url, m, now); + return; + } + + /* Anti-replay (2): each url's signed ts must strictly increase. A replayed + * (byte-identical) announcement carries a ts we've already accepted, so + * reject it -- this closes the in-window replay the freshness check alone + * allows (e.g. replaying a dead backend's last announcement to keep it from + * being evicted). */ + if (msg_ts <= m->last_ts) { + beacon_log_throttled(ctx, now, "replayed/reordered ts"); + return; + } + m->last_ts = msg_ts; + m->last_seen = now; + + if (!m->added) { + /* A prior add failed; retry, but only after the backoff window. */ + if (now - m->last_attempt >= BEACON_RETRY_BACKOFF) { + beacon_try_add(ctx, pool, url, m, now); + } + return; + } + + if (m->evicted) { + if (beacon_set_worker_disabled(ctx, pool, url, 0) == APR_SUCCESS) { + m->evicted = 0; + ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ctx->s, + APLOGNO(10580) "mod_proxy_beacon: re-enabled backend %s in " + "balancer://%s (announcing again)", + url, ctx->balancer_name); + } + } +} + +/* + * Take over the beacon members already in the balancer. + * + * The leases (ctx->seen) are private to the watchdog-owning process, but the + * members they describe are not: they live in the balancer's shared memory and + * outlive that process. When the watchdog singleton moves to another child -- + * after a crash, a recycle, or a restart -- the new owner starts with an empty + * table and would never evict a member that has since fallen silent, leaving it + * enabled for good. + * + * So, once, at the start of ownership, adopt every member carrying + * PROXY_WORKER_BEACON and start its lease now: it is evicted after the usual + * ProxyBeaconTimeout unless it announces again. A member that is already + * disabled is recorded as evicted, so that its next announcement re-enables it. + * Members without the mark (configured or added by an administrator) are not + * ours and are left alone. + * + * The per-member replay high-water mark is not recovered (last_ts starts at 0); + * see the replay notes in the documentation. + */ +static int beacon_reconcile(beacon_ctx_t *ctx, apr_pool_t *pool, apr_time_t now) +{ + proxy_server_conf *conf = + ap_get_module_config(ctx->s->module_config, &proxy_module); + proxy_balancer *bsel = ap_proxy_get_balancer(pool, conf, + apr_pstrcat(pool, BALANCER_PREFIX, ctx->balancer_name, NULL), 0); + proxy_worker **workers; + int i, adopted = 0, untracked = 0; + + if (!bsel) { + return 0; + } + + PROXY_THREAD_LOCK(bsel); + /* Pick up the members the previous owner added: this process's own view of + * the balancer only knows the ones that existed at configuration time. + * Without that the picture is incomplete: try again on the next tick. */ + if (ap_proxy_sync_balancer(bsel, ctx->s, conf) != APR_SUCCESS) { + PROXY_THREAD_UNLOCK(bsel); + beacon_log_throttled(ctx, now, "takeover: balancer sync failed"); + return 0; + } + + workers = (proxy_worker **)bsel->workers->elts; + for (i = 0; i < bsel->workers->nelts; i++) { + proxy_worker *w = workers[i]; + beacon_member_t *m; + + if (!w->s || !(w->s->status & PROXY_WORKER_BEACON) + || apr_hash_get(ctx->seen, w->s->name, APR_HASH_KEY_STRING)) { + continue; + } + if (apr_hash_count(ctx->seen) >= BEACON_MAX_MEMBERS) { + /* No lease can be kept for it, so it would never be evicted: take + * it out of rotation until it announces again and is adopted. */ + if (!(w->s->status & PROXY_WORKER_DISABLED)) { + ap_proxy_set_wstatus(PROXY_WORKER_DISABLED_FLAG, 1, w); + untracked++; + } + continue; + } + m = beacon_member_new(ctx, w->s->name, now); + if (!m) { + continue; + } + m->added = 1; + m->evicted = (w->s->status & PROXY_WORKER_DISABLED) != 0; + adopted++; + } + PROXY_THREAD_UNLOCK(bsel); + + if (adopted) { + ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ctx->s, + APLOGNO(10636) "mod_proxy_beacon: took over %d existing " + "member(s) of balancer://%s; their leases restart now", + adopted, ctx->balancer_name); + } + if (untracked) { + ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ctx->s, + APLOGNO(10660) "mod_proxy_beacon: balancer://%s has more " + "members than the %d beacon can track; disabled %d of " + "them until they announce again", + ctx->balancer_name, BEACON_MAX_MEMBERS, untracked); + } + return 1; +} + +/* + * Periodic sweep (watchdog singleton, throttled by the caller): + * + * - eviction: disable any member that has not announced within evict_timeout + * (no-op when eviction is disabled, timeout 0); + * - reclamation: forget members that are evicted, or whose add failed, once + * they have been silent long enough. Without this, failed registrations and + * departed backends would fill the BEACON_MAX_MEMBERS table for good and lock + * out new members. + * + * A record also carries the replay high-water mark, so it must outlive any + * replay of the member's last accepted message. That message was accepted at + * last_seen with a timestamp within max_skew of it, so it is stale (rejected by + * the freshness check) after last_seen + 2 * max_skew; reclaiming only after that + * loses no replay protection. A reclaimed member that announces again is simply + * recreated: its worker is still in the balancer and is re-adopted. + */ +static void beacon_sweep(beacon_ctx_t *ctx, apr_pool_t *pool, apr_time_t now) +{ + apr_hash_index_t *hi; + apr_time_t skew = ctx->max_skew > 0 ? ctx->max_skew : BEACON_MAXSKEW_DEFAULT; + /* Saturate: MaxSkew is any positive time the administrator wrote. */ + apr_time_t reclaim_after = + skew > (APR_INT64_MAX - apr_time_from_sec(1)) / 2 + ? APR_INT64_MAX : 2 * skew + apr_time_from_sec(1); + + for (hi = apr_hash_first(pool, ctx->seen); hi; hi = apr_hash_next(hi)) { + void *val; + beacon_member_t *m; + + apr_hash_this(hi, NULL, NULL, &val); + m = val; + if (ctx->evict_timeout > 0 && m->added && !m->evicted + && now - m->last_seen > ctx->evict_timeout + && beacon_have_manage_fn(ctx)) { + if (beacon_set_worker_disabled(ctx, pool, m->url, 1) == APR_SUCCESS) { + m->evicted = 1; + ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ctx->s, + APLOGNO(10581) "mod_proxy_beacon: evicted backend %s from " + "balancer://%s (no announcement for %" + APR_TIME_T_FMT "s)", + m->url, ctx->balancer_name, + apr_time_sec(now - m->last_seen)); + } + } + else if ((!m->added || m->evicted) + && now - m->last_seen > reclaim_after) { + /* Safe while iterating: only the current entry is removed. */ + beacon_member_free(ctx, m); + } + } +} + +/* + * Extract the value of the "url=" token from a beacon message into buf. + * Returns 1 on success. The payload is untrusted network input, so parse + * defensively: the token is "url=" followed by non-space characters. + */ +static int beacon_parse_url(const char *msg, char *buf, apr_size_t buflen) +{ + const char *p = msg; + + while (p && *p) { + if (!strncmp(p, "url=", 4)) { + apr_size_t i = 0; + p += 4; + while (*p && *p != ' ' && i + 1 < buflen) { + buf[i++] = *p++; + } + buf[i] = '\0'; + /* A token that does not fit is rejected, not silently cut short: + * the truncated prefix could be a different, valid-looking url. */ + if (*p && *p != ' ') { + return 0; + } + return (i > 0); + } + /* advance to the next space-separated token */ + p = ap_strchr_c(p, ' '); + if (p) { + p++; + } + } + return 0; +} + +/* ----- Phase 4: channel authentication (SipHash MAC + timestamp) ----- */ + +/* Constant-time buffer compare (time depends only on size, not contents) -- + * avoids a timing oracle on the MAC. apr_crypto_equals() would do this but is + * gated behind APU_HAVE_CRYPTO, which isn't always built; this is the same + * branchless idiom. */ +static int beacon_const_time_eq(const void *a, const void *b, apr_size_t n) +{ + const unsigned char *p1 = a, *p2 = b; + volatile unsigned char diff = 0; + apr_size_t i; + for (i = 0; i < n; i++) { + diff |= p1[i] ^ p2[i]; + } + return diff == 0; +} + +/* Hex-encode the SipHash-2-4 MAC of [base, base+len) into out (BEACON_MAC_HEXLEN+1 + * bytes). */ +static void beacon_mac_hex(const beacon_ctx_t *ctx, const char *base, + apr_size_t len, char *out) +{ + unsigned char mac[APR_SIPHASH_DSIZE]; + apr_siphash24_auth(mac, base, len, ctx->mac_key); + ap_bin2hex(mac, sizeof(mac), out); /* writes BEACON_MAC_HEXLEN + NUL */ +} + +/* sender: return " mac=", appending the keyed MAC. A secret is + * required on every participating server (enforced at config time), so this + * always signs. */ +static const char *beacon_sign(beacon_ctx_t *ctx, apr_pool_t *pool, const char *base) +{ + char hex[BEACON_MAC_HEXLEN + 1]; + + beacon_mac_hex(ctx, base, strlen(base), hex); + return apr_psprintf(pool, "%s mac=%s", base, hex); +} + +/* + * Parse a timestamp token value strictly: 1 to 18 decimal digits, ending at a + * space or the end of the string. apr_atoi64() would also accept a sign, + * leading space, trailing garbage and out-of-range values, and arithmetic on an + * extreme timestamp could overflow. + */ +static int beacon_parse_ts(const char *p, apr_int64_t *out) +{ + apr_int64_t v = 0; + int n = 0; + + for (; apr_isdigit(*p); p++, n++) { + if (n >= 18) { + return 0; + } + v = v * 10 + (*p - '0'); + } + if (!n || (*p && *p != ' ')) { + return 0; + } + *out = v; + return 1; +} + +/* + * Check the wire grammar of a message whose MAC has already been verified: + * + * BEACON = = ... mac= + * + * one leading BEACON marker, single-space-separated key=value tokens with a + * lower-case key and a non-empty value, and no repeated field among the ones we + * know. Without this the receiver reads fields by searching the string (the + * last "ts=" wins, a leading marker is never checked, a repeated field is + * silently resolved one way), so two parties can read the same signed bytes + * differently. Returns the ts= value via *tsp (NULL if absent). + */ +static const char *beacon_frame_check(const char *msg, const char **tsp, + const char **reason) +{ + static const char * const known[] = { + "url", "host", "pid", "seq", "ts", "mac" + }; + unsigned seen = 0; + const char *p = msg; + + *tsp = NULL; + if (strncmp(p, "BEACON ", 7)) { + return *reason = "bad frame", NULL; + } + p += 7; + + while (*p) { + const char *key = p, *eq; + apr_size_t klen; + unsigned i; + + while (*p && *p != ' ') { + p++; + } + eq = memchr(key, '=', p - key); + if (p == key || !eq || eq == key || eq + 1 == p) { + return *reason = "bad frame", NULL; + } + for (klen = 0; key + klen < eq; klen++) { + if (!apr_islower(key[klen])) { + return *reason = "bad frame", NULL; + } + } + for (i = 0; i < sizeof(known) / sizeof(known[0]); i++) { + if (strlen(known[i]) == klen && !strncmp(key, known[i], klen)) { + if (seen & (1u << i)) { + return *reason = "duplicate field", NULL; + } + seen |= 1u << i; + if (!strcmp(known[i], "ts")) { + *tsp = eq + 1; + } + break; + } + } + if (*p == ' ') { + p++; + if (!*p) { + return *reason = "bad frame", NULL; /* trailing space */ + } + } + } + return msg; +} + +/* + * listener: verify a received, NUL-terminated message. Returns 1 if the MAC matches + * the pre-shared key, the message is well-formed, AND the ts= timestamp is within + * ctx->max_skew of now. + * Only called when ctx->has_secret. Constant-time MAC compare. On success the + * parsed ts= (microseconds since the epoch) is written to *ts_out for the + * caller's per-url monotonic replay check. reason (out) is set on failure. + */ +static int beacon_verify(beacon_ctx_t *ctx, const char *msg, apr_time_t now, + apr_int64_t *ts_out, const char **reason) +{ + const char *macp = NULL, *p, *tsp; + char expected[BEACON_MAC_HEXLEN + 1]; + apr_size_t prefix_len; + apr_int64_t ts, skew, delta; + + /* Locate the last " mac=" -- the MAC covers everything before it. */ + for (p = msg; (p = ap_strstr_c(p, " mac=")) != NULL; p += 5) { + macp = p; + } + if (!macp) { + *reason = "no mac"; + return 0; + } + /* mac= must be the final field: exactly BEACON_MAC_HEXLEN chars followed by + * end-of-string. strlen is NUL-safe here -- the caller hands us a + * NUL-terminated copy with no embedded NUL -- so a short or garbled payload + * cannot make the constant-time compare below over-read past the buffer. + * The compare itself validates the hex content; we deliberately do not + * pre-scan for hex digits, which would leak MAC bytes through an early + * exit (timing oracle). */ + if (strlen(macp + 5) != BEACON_MAC_HEXLEN) { + *reason = "bad mac length"; + return 0; + } + + prefix_len = (apr_size_t)(macp - msg); + beacon_mac_hex(ctx, msg, prefix_len, expected); + if (!beacon_const_time_eq(expected, macp + 5, BEACON_MAC_HEXLEN)) { + *reason = "mac mismatch"; + return 0; + } + + /* Authentic. Now insist it is also well-formed, so that every reader of + * these bytes sees the same fields. */ + if (!beacon_frame_check(msg, &tsp, reason)) { + return 0; + } + + /* Anti-replay (1): ts= must be present and within the freshness window. + * ts is in microseconds (raw apr_time_now()) so that announcements made + * less than a second apart still have strictly-increasing timestamps for + * the caller's per-url check. */ + if (!tsp) { + *reason = "no ts"; + return 0; + } + if (!beacon_parse_ts(tsp, &ts)) { + *reason = "bad ts"; + return 0; + } + skew = ctx->max_skew > 0 ? ctx->max_skew : BEACON_MAXSKEW_DEFAULT; + delta = (apr_int64_t)now - ts; /* both well below 2^62: no overflow */ + if (delta < 0) { + delta = -delta; + } + if (delta > skew) { + *reason = "stale timestamp"; + return 0; + } + + *ts_out = ts; + return 1; +} + +/* RUNNING: sender sends a throttled beacon; listener drains its receive socket. */ +/* + * Count a failed send or receive. Returns true if it should be logged, which is + * at most once in 10 seconds. After BEACON_IO_ERRORS_MAX in a row the socket + * is closed: the open back-off in beacon_cb_running() opens it again, looking + * the address up again. + */ +static int beacon_io_failed(beacon_ctx_t *ctx, apr_time_t now) +{ + int log_it = now - ctx->last_io_error_log >= apr_time_from_sec(10); + + if (log_it) { + ctx->last_io_error_log = now; + } + if (++ctx->io_errors >= BEACON_IO_ERRORS_MAX) { + ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ctx->s, APLOGNO(10672) + "mod_proxy_beacon: closing the socket after repeated " + "errors; it will be opened again"); + apr_socket_close(ctx->sock); + ctx->opened = 0; + ctx->open_failed = 1; + ctx->io_errors = 0; + } + return log_it; +} + +/* + * Sender: look the destination up again. The address in use is kept if that + * fails. This runs on the watchdog thread, so a slow resolver delays the other + * contexts for as long as the lookup takes: ProxyBeaconAddress should be an IP + * address, or a name that resolves quickly. + */ +static void beacon_refresh_destination(beacon_ctx_t *ctx, apr_time_t now) +{ + apr_pool_t *np; + apr_pool_t *old; + apr_sockaddr_t *na = NULL; + apr_status_t rv; + + ctx->next_refresh = now + BEACON_REFRESH; + apr_pool_create(&np, ctx->p); + rv = beacon_resolve(np, ctx->pub_url, NULL, 0, &na); + if (rv != APR_SUCCESS) { + apr_pool_destroy(np); + ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ctx->s, APLOGNO(10673) + "mod_proxy_beacon: cannot resolve ProxyBeaconAddress '%s' " + "again; keeping the address in use", ctx->pub_url); + return; + } + if (na->family != ctx->addr->family) { + /* The socket belongs to the old family: open a new one. */ + apr_pool_destroy(np); + apr_socket_close(ctx->sock); + ctx->opened = 0; + beacon_cb_starting(ctx); + return; + } + if (!apr_sockaddr_equal(na, ctx->addr)) { + ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ctx->s, APLOGNO(10674) + "mod_proxy_beacon: beaconing to %pI now", na); + } + old = ctx->addr_pool; + ctx->addr_pool = np; + ctx->addr = na; + if (old) { + apr_pool_destroy(old); + } +} + +static void beacon_cb_running(beacon_ctx_t *ctx, apr_pool_t *pool) +{ + server_rec *s = ctx->s; + apr_status_t rv; + + if (ctx->open_failed) { + /* Retry a failed open, at a pace that cannot flood the log. */ + apr_time_t t = apr_time_now(); + if (!ctx->next_open_try) { + ctx->open_delay = ctx->open_delay + ? ctx->open_delay * 2 : BEACON_OPEN_RETRY; + if (ctx->open_delay > BEACON_OPEN_RETRY_MAX) { + ctx->open_delay = BEACON_OPEN_RETRY_MAX; + } + ctx->next_open_try = t + ctx->open_delay; + } + else if (t >= ctx->next_open_try) { + ctx->open_failed = 0; + ctx->next_open_try = 0; + beacon_cb_starting(ctx); + } + } + if (!ctx->opened) { + return; + } + ctx->open_delay = 0; + + if (ctx->role == BEACON_ROLE_LISTEN && ctx->balancer_name + && !ctx->reconciled) { + ctx->reconciled = beacon_reconcile(ctx, pool, apr_time_now()); + } + + if (ctx->role == BEACON_ROLE_SEND) { + apr_time_t now = apr_time_now(); + + if (now >= ctx->next_refresh) { + beacon_refresh_destination(ctx, now); + if (!ctx->opened) { + return; + } + } + if (now >= ctx->last_publish + ctx->interval) { + const char *host = ctx->s->server_hostname + ? ctx->s->server_hostname : "(unknown)"; + const char *msg; + char *base; + apr_size_t len; + /* Carry the routable URL so the proxy can add us as a member. + * Without ProxyBeaconAdvertise, fall back to the Phase-1 payload + * (channel proof only; the listener just logs it). ts= is the signing + * timestamp in microseconds (Phase 4 anti-replay): the proxy checks + * both a freshness window and that it strictly increases per url, so + * a byte-identical replay (same ts) is rejected. Harmless when + * unsigned. */ + if (ctx->advertise_url) { + base = apr_psprintf(pool, + "BEACON url=%s host=%s pid=%" APR_PID_T_FMT + " seq=%" APR_UINT64_T_FMT " ts=%" APR_INT64_T_FMT, + ctx->advertise_url, host, getpid(), ctx->seq++, + (apr_int64_t)now); + } + else { + base = apr_psprintf(pool, + "BEACON host=%s pid=%" APR_PID_T_FMT + " seq=%" APR_UINT64_T_FMT " ts=%" APR_INT64_T_FMT, + host, getpid(), ctx->seq++, + (apr_int64_t)now); + } + /* Phase 4: append a keyed MAC when a shared secret is configured. */ + msg = beacon_sign(ctx, pool, base); + /* Send strlen(msg) bytes (no trailing NUL on the wire) as a single + * UDP datagram to the proxy. Fire-and-forget; a failure here just + * means this announcement is lost and the next interval retries. */ + len = strlen(msg); + if ((rv = apr_socket_sendto(ctx->sock, ctx->addr, 0, msg, &len)) + != APR_SUCCESS) { + if (beacon_io_failed(ctx, now)) { + ap_log_error(APLOG_MARK, APLOG_WARNING, rv, s, + APLOGNO(10582) "mod_proxy_beacon: sendto %s " + "failed", ctx->pub_url); + } + } + else { + ctx->io_errors = 0; + } + ctx->last_publish = now; + } + } + else if (ctx->role == BEACON_ROLE_LISTEN) { + apr_time_t now; + apr_pool_t *ptemp; + apr_time_t started = apr_time_now(); + int n; + + apr_pool_create(&ptemp, pool); + apr_pool_tag(ptemp, "beacon_recv"); + + /* Drain the socket every tick (re-enable latency matters), up to + * BEACON_MAX_DRAIN datagrams and BEACON_DRAIN_BUDGET of time. */ + for (n = 0; n < BEACON_MAX_DRAIN; n++) { + char buf[BEACON_MAX_MSG_LEN + 2]; + apr_sockaddr_t from; + /* Ask for one byte more than we accept: recvfrom() silently + * truncates a longer datagram to the buffer size, so receiving + * the extra byte is how an oversize datagram is told from one + * that exactly fits. */ + apr_size_t sz = BEACON_MAX_MSG_LEN + 1; + apr_time_t msg_now; + const char *msg_str; + char url[BEACON_URL_MAX]; + apr_int64_t msg_ts = 0; + + if (n && apr_time_now() - started > BEACON_DRAIN_BUDGET) { + break; + } + apr_pool_clear(ptemp); + from.pool = ptemp; + rv = apr_socket_recvfrom(&from, ctx->sock, 0, buf, &sz); + if (APR_STATUS_IS_EAGAIN(rv)) { + ctx->io_errors = 0; + break; /* socket drained */ + } + if (rv != APR_SUCCESS) { + if (beacon_io_failed(ctx, apr_time_now())) { + ap_log_error(APLOG_MARK, APLOG_WARNING, rv, s, + APLOGNO(10583) "mod_proxy_beacon: recvfrom " + "failed"); + } + break; + } + ctx->io_errors = 0; + if (sz == 0) { + continue; /* empty datagram */ + } + + /* Capture a single wall-clock snapshot for this message so that + * MAC verification, throttle logging, and last-seen recording all + * share the same time base (no TOCTOU drift across calls). */ + msg_now = apr_time_now(); + + if (sz > BEACON_MAX_MSG_LEN) { + beacon_log_throttled(ctx, msg_now, "oversize datagram"); + continue; + } + /* Our messages are text. A NUL would end the string every parser + * below works on while the datagram goes on, so what is verified + * and what was sent would differ. */ + if (memchr(buf, '\0', sz)) { + beacon_log_throttled(ctx, msg_now, "embedded NUL"); + continue; + } + buf[sz] = '\0'; + msg_str = buf; + + /* Phase 4: verify the MAC and freshness BEFORE logging or acting on + * the payload, so forged/tampered content is dropped (throttled) and + * never reaches the INFO log. A secret is required (enforced at + * config time) on every participating server, with or without a + * ProxyBeaconBalancer. msg_ts (microseconds) is the signed + * timestamp, used below for the per-url monotonic replay check. */ + { + const char *reason = "?"; + if (!beacon_verify(ctx, msg_str, msg_now, &msg_ts, &reason)) { + beacon_log_throttled(ctx, msg_now, reason); + continue; + } + } + + /* Escape the payload before it reaches the log, so even an + * authenticated sender cannot embed newline/control/ANSI sequences + * to forge or corrupt error-log lines. Done only after + * verification so a rejected datagram allocates nothing. */ + if (APLOGinfo(s)) { + /* An authentic message can be replayed within the freshness + * window as often as the sender likes: bound the log. */ + if (msg_now - ctx->recv_log_window >= apr_time_from_sec(1)) { + if (ctx->recv_log_suppressed) { + ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, + APLOGNO(10675) "mod_proxy_beacon: %" + APR_UINT64_T_FMT " received: lines left " + "out in the last second", + ctx->recv_log_suppressed); + } + ctx->recv_log_window = msg_now; + ctx->recv_log_count = 0; + ctx->recv_log_suppressed = 0; + } + if (ctx->recv_log_count < BEACON_RECV_LOG_PER_SEC) { + ctx->recv_log_count++; + ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, + APLOGNO(10584) "mod_proxy_beacon: received: %s", + ap_escape_logitem(ptemp, msg_str)); + } + else { + ctx->recv_log_suppressed++; + } + } + + if (!ctx->balancer_name) { + continue; + } + + /* Phase 2/3: carries a routable url= -> add the backend (or + * refresh last-seen / re-enable if previously evicted). */ + if (beacon_parse_url(msg_str, url, sizeof(url))) { + /* A valid MAC only shows the sender holds the secret, not + * that it used the bundled sender: apply the sender's rule + * here too, and track the member by its canonical origin. */ + const char *canon = beacon_canonical_url(ptemp, url); + if (!canon) { + beacon_log_throttled(ctx, msg_now, "unacceptable url"); + continue; + } + beacon_handle_announce(ctx, ptemp, canon, msg_now, msg_ts); + } + } + apr_pool_destroy(ptemp); + + /* Phase 3: evict backends that stopped announcing. Throttle the scan + * to ~1s (the recv drain above already runs every tick). */ + now = apr_time_now(); + if (ctx->balancer_name + && now - ctx->last_sweep >= apr_time_from_sec(1)) { + beacon_sweep(ctx, pool, now); + ctx->last_sweep = now; + } + } +} + +/* STOPPING: close the socket if we opened it. */ +static void beacon_cb_stopping(beacon_ctx_t *ctx) +{ + if (ctx->opened) { + apr_socket_close(ctx->sock); + ctx->opened = 0; + ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ctx->s, + APLOGNO(10585) "mod_proxy_beacon: socket closed"); + } +} + +/* + * Watchdog callback. Always returns APR_SUCCESS: a non-success return would + * unregister the callback and permanently stop the channel, which we never + * want for a transient socket error. + */ +static apr_status_t beacon_watchdog_callback(int state, void *data, + apr_pool_t *pool) +{ + beacon_ctx_t *ctx = (beacon_ctx_t *)data; + + switch (state) { + case AP_WATCHDOG_STATE_STARTING: + beacon_cb_starting(ctx); + break; + case AP_WATCHDOG_STATE_RUNNING: + beacon_cb_running(ctx, pool); + break; + case AP_WATCHDOG_STATE_STOPPING: + beacon_cb_stopping(ctx); + break; + } + + return APR_SUCCESS; +} + +static int beacon_post_config(apr_pool_t *pconf, apr_pool_t *plog, + apr_pool_t *ptemp, server_rec *main_s) +{ + apr_status_t rv; + server_rec *s; + APR_OPTIONAL_FN_TYPE(ap_watchdog_get_instance) *beacon_get_instance; + APR_OPTIONAL_FN_TYPE(ap_watchdog_register_callback) *beacon_register_callback; + + /* post_config runs twice; skip the initial config-test pass. */ + if (ap_state_query(AP_SQ_MAIN_STATE) == AP_SQ_MS_CREATE_PRE_CONFIG) { + return OK; + } + + beacon_get_instance = APR_RETRIEVE_OPTIONAL_FN(ap_watchdog_get_instance); + beacon_register_callback = + APR_RETRIEVE_OPTIONAL_FN(ap_watchdog_register_callback); + if (!beacon_get_instance || !beacon_register_callback) { + ap_log_error(APLOG_MARK, APLOG_CRIT, 0, main_s, + APLOGNO(10586) "mod_proxy_beacon: mod_watchdog is required"); + return !OK; + } + + rv = beacon_get_instance(&beacon_watchdog, BEACON_WATCHDOG_NAME, 0, 1, pconf); + if (rv) { + ap_log_error(APLOG_MARK, APLOG_CRIT, rv, main_s, + APLOGNO(10587) "mod_proxy_beacon: failed to create watchdog instance (%s)", + BEACON_WATCHDOG_NAME); + return !OK; + } + + for (s = main_s; s; s = s->next) { + beacon_ctx_t *ctx = ap_get_module_config(s->module_config, + &proxy_beacon_module); + /* Skip non-canonical server contexts (shared across vhosts). */ + if (s != ctx->s) { + continue; + } + /* Only servers with a directive participate. */ + if (ctx->role == BEACON_ROLE_NONE) { + continue; + } + /* ProxyBeaconSecret is required on every participating server (sender or + * listener): the channel is authenticated, with no unauthenticated mode. + * A UDP source address is trivially spoofable, so an unsigned channel + * would let anyone who can reach the listen port announce an arbitrary + * backend url and hijack client traffic. Fail startup rather than run + * insecurely. */ + if (!ctx->has_secret) { + ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s, + APLOGNO(10572) "mod_proxy_beacon: ProxyBeaconSecret is " + "required but not set; the beacon channel must be " + "authenticated. Set ProxyBeaconSecret to the same value " + "on the proxy and all backends."); + return !OK; + } + rv = beacon_register_callback(beacon_watchdog, AP_WD_TM_SLICE, ctx, + beacon_watchdog_callback); + if (rv) { + ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s, + APLOGNO(10588) "mod_proxy_beacon: failed to register watchdog callback"); + return !OK; + } + } + + return OK; +} + +/* + * "[scheme://][host][:port]" syntax only, with no lookup: a name that does not + * resolve yet may be fine once the network is up, but a malformed address never + * is. A sender needs both host and port; a listener inherits what is omitted. + */ +static int beacon_addr_syntax_ok(apr_pool_t *p, const char *url, + int need_host_port) +{ + char *host = NULL; + apr_port_t port = 0; + const char *hostport = url, *sep; + + if (url && (sep = ap_strstr_c(url, "://")) != NULL) { + hostport = sep + 3; + } + if (!hostport || !*hostport) { + return !need_host_port; + } + if (beacon_parse_hostport(p, hostport, &host, &port) != APR_SUCCESS) { + return 0; + } + return !need_host_port || (host && *host && port); +} + +/* + * Everything that is wrong with the configuration for good, however the + * network is when the server starts, so that "httpd -t" says so and a start + * does not go ahead only to fail in a child. What can change (the address + * resolving, the port binding) is left to the retries in the watchdog callback. + */ +static int beacon_check_config(apr_pool_t *pconf, apr_pool_t *plog, + apr_pool_t *ptemp, server_rec *main_s) +{ + server_rec *s, *t; + int errs = 0, participating = 0; + + for (s = main_s; s; s = s->next) { + beacon_ctx_t *ctx = ap_get_module_config(s->module_config, + &proxy_beacon_module); + if (s != ctx->s || ctx->role == BEACON_ROLE_NONE) { + continue; + } + participating++; + + if (!ctx->has_secret) { + ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s, + APLOGNO(10661) "mod_proxy_beacon: ProxyBeaconSecret " + "is required but not set; the beacon channel must be " + "authenticated"); + errs++; + } + + if (ctx->role == BEACON_ROLE_SEND) { + if (!beacon_addr_syntax_ok(ptemp, ctx->pub_url, 1)) { + ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s, + APLOGNO(10662) "mod_proxy_beacon: " + "ProxyBeaconAddress '%s' must be host:port", + ctx->pub_url); + errs++; + } + continue; + } + + if (!beacon_addr_syntax_ok(ptemp, ctx->sub_url, 0)) { + ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s, + APLOGNO(10663) "mod_proxy_beacon: ProxyBeaconListen " + "'%s' must be [host][:port]", ctx->sub_url); + errs++; + } + if (ctx->balancer_name) { + proxy_server_conf *conf = ap_get_module_config(s->module_config, + &proxy_module); + if (!conf || !ap_proxy_get_balancer(ptemp, conf, + apr_pstrcat(ptemp, BALANCER_PREFIX, ctx->balancer_name, + NULL), 0)) { + ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s, + APLOGNO(10664) "mod_proxy_beacon: " + "ProxyBeaconBalancer: balancer://%s is not " + "defined for this server", ctx->balancer_name); + errs++; + } + if (!APR_RETRIEVE_OPTIONAL_FN(balancer_manage)) { + ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, s, + APLOGNO(10665) "mod_proxy_beacon: " + "ProxyBeaconBalancer needs mod_proxy_balancer"); + errs++; + } + } + /* Two listeners on one address: only one of them would receive. */ + for (t = main_s; t != s; t = t->next) { + beacon_ctx_t *other = ap_get_module_config(t->module_config, + &proxy_beacon_module); + if (t == other->s && other->role == BEACON_ROLE_LISTEN + && !strcmp(other->sub_url, ctx->sub_url)) { + ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_WARNING, 0, s, + APLOGNO(10667) "mod_proxy_beacon: ProxyBeaconListen " + "'%s' is also written for another server; if " + "both resolve to the same address, only one of " + "them will receive the beacons", ctx->sub_url); + } + } + } + + if (participating + && !APR_RETRIEVE_OPTIONAL_FN(ap_watchdog_get_instance)) { + ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, 0, main_s, + APLOGNO(10666) "mod_proxy_beacon: mod_watchdog is " + "required"); + errs++; + } + + return errs ? !OK : OK; +} + +static void beacon_register_hooks(apr_pool_t *p) +{ + static const char *const aszSucc[] = { "mod_watchdog.c", + "mod_proxy_balancer.c", NULL }; + ap_hook_check_config(beacon_check_config, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_post_config(beacon_post_config, NULL, aszSucc, APR_HOOK_LAST); +} + +AP_DECLARE_MODULE(proxy_beacon) = +{ + STANDARD20_MODULE_STUFF, + NULL, /* create per-dir config */ + NULL, /* merge per-dir config */ + beacon_create_server_config, /* create per-server config */ + NULL, /* merge per-server config */ + beacon_cmds, /* command table */ + beacon_register_hooks /* register hooks */ +}; diff --git a/modules/proxy/proxy_util.c b/modules/proxy/proxy_util.c index 81b7de2a695..262f64763c4 100644 --- a/modules/proxy/proxy_util.c +++ b/modules/proxy/proxy_util.c @@ -2074,31 +2074,18 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p, } ptr = apr_uri_unparse(p, &uri, APR_URI_UNP_REVEALPASSWORD); - /* - * Workers can be associated w/ balancers or on their - * own; ie: the generic reverse-proxy or a worker - * in a simple ProxyPass statement. eg: - * - * ProxyPass / http://www.example.com - * - * in which case the worker goes in the conf slot. - */ - if (balancer) { - proxy_worker **runtime; - /* recall that we get a ptr to the ptr here */ - runtime = apr_array_push(balancer->workers); - *worker = *runtime = apr_palloc(p, sizeof(proxy_worker)); /* right to left baby */ - /* we've updated the list of workers associated with - * this balancer *locally* */ - balancer->wupdated = apr_time_now(); - } else if (conf) { - *worker = apr_array_push(conf->workers); - } else { - /* we need to allocate space here */ - *worker = apr_palloc(p, sizeof(proxy_worker)); + /* Reject names that cannot be stored before allocating anything for them: + * the allocation below is from p, which for runtime workers is the + * long-lived configuration pool, so a failed definition must not leave a + * proxy_worker_shared behind. (These are the same limits PROXY_STRNCPY() + * enforces below.) */ + if (strlen(uri.hostname) >= PROXY_RFC1035_HOSTNAME_SIZE) { + return apr_psprintf(p, "worker hostname (%s) too long", uri.hostname); } - memset(*worker, 0, sizeof(proxy_worker)); - + if (sockpath && strlen(sockpath) >= PROXY_WORKER_MAX_NAME_SIZE) { + return apr_psprintf(p, "worker uds path (%s) too long", sockpath); + } + /* right here we just want to tuck away the worker info. * if called during config, we don't have shm setup yet, * so just note the info for later. */ @@ -2121,7 +2108,16 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p, ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(010117) "Alert! worker scheme (%s) too long; truncated to: %s", uri.scheme, wshared->scheme); } + /* + * Everything that can fail is checked before the worker is added to the + * balancer's (or conf's) worker array below: an entry appended here and then + * abandoned on error would stay in the array with no shared data (->s is + * NULL) for every later walk of the array to trip over. + */ if (PROXY_STRNCPY(wshared->hostname_ex, uri.hostname) != APR_SUCCESS) { + if (mask & AP_PROXY_WORKER_IS_MALLOCED) { + free(wshared); + } return apr_psprintf(p, "worker hostname (%s) too long", uri.hostname); } if (PROXY_STRNCPY(wshared->hostname, uri.hostname) != APR_SUCCESS) { @@ -2170,6 +2166,9 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p, } if (sockpath) { if (PROXY_STRNCPY(wshared->uds_path, sockpath) != APR_SUCCESS) { + if (mask & AP_PROXY_WORKER_IS_MALLOCED) { + free(wshared); + } return apr_psprintf(p, "worker uds path (%s) too long", sockpath); } @@ -2177,6 +2176,26 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p, else { *wshared->uds_path = '\0'; } + + /* + * Workers can be associated w/ balancers or on their + * own; ie: the generic reverse-proxy or a worker + * in a simple ProxyPass statement. eg: + * + * ProxyPass / http://www.example.com + * + * in which case the worker goes in the conf slot. + */ + if (balancer) { + /* Added to the balancer's array only once it is complete (below). */ + *worker = apr_palloc(p, sizeof(proxy_worker)); + } else if (conf) { + *worker = apr_array_push(conf->workers); + } else { + /* we need to allocate space here */ + *worker = apr_palloc(p, sizeof(proxy_worker)); + } + memset(*worker, 0, sizeof(proxy_worker)); if (!balancer) { wshared->status |= PROXY_WORKER_IGNORE_ERRORS; } @@ -2187,6 +2206,14 @@ PROXY_DECLARE(char *) ap_proxy_define_worker_ex(apr_pool_t *p, (*worker)->balancer = balancer; (*worker)->s = wshared; + if (balancer) { + proxy_worker **runtime = apr_array_push(balancer->workers); + *runtime = *worker; + /* we've updated the list of workers associated with + * this balancer *locally* */ + balancer->wupdated = apr_time_now(); + } + return NULL; } @@ -2397,7 +2424,7 @@ PROXY_DECLARE(apr_status_t) ap_proxy_initialize_worker(proxy_worker *worker, ser } if (rv == APR_SUCCESS) { - worker->s->status |= (PROXY_WORKER_INITIALIZED); + ap_proxy_set_wstatus(PROXY_WORKER_INITIALIZED_FLAG, 1, worker); } return rv; } @@ -2416,7 +2443,7 @@ static int ap_proxy_retry_worker(const char *proxy_function, proxy_worker *worke if ((worker->s->status & PROXY_WORKER_IGNORE_ERRORS) || apr_time_now() > worker->s->error_time + worker->s->retry) { ++worker->s->retries; - worker->s->status &= ~PROXY_WORKER_IN_ERROR; + ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 0, worker); ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(00932) "%s: worker for (%s:%d) has been marked for retry", proxy_function, worker->s->hostname_ex, @@ -4034,7 +4061,7 @@ PROXY_DECLARE(int) ap_proxy_connect_backend(const char *proxy_function, if (rv != APR_SUCCESS) { if (!(worker->s->status & PROXY_WORKER_IGNORE_ERRORS)) { worker->s->error_time = apr_time_now(); - worker->s->status |= PROXY_WORKER_IN_ERROR; + ap_proxy_set_wstatus(PROXY_WORKER_IN_ERROR_FLAG, 1, worker); ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(00959) "ap_proxy_connect_backend disabling worker for (%s:%d) " "for %" APR_TIME_T_FMT "s", @@ -4321,15 +4348,23 @@ ap_proxy_hashfunc(const char *str, proxy_hash_t method) PROXY_DECLARE(apr_status_t) ap_proxy_set_wstatus(char c, int set, proxy_worker *w) { - unsigned int *status = &w->s->status; + volatile apr_uint32_t *status = (volatile apr_uint32_t *)&w->s->status; char flag = toupper(c); proxy_wstat_t *pwt = proxy_wstat_tbl; while (pwt->bit) { if (flag == pwt->flag) { - if (set) - *status |= pwt->bit; - else - *status &= ~(pwt->bit); + /* + * The status word is shared by every process and thread, and is + * changed from several places at once (balancer-manager, health + * checks, ...), each setting only its own bit. + * A plain |= / &= can lose another one's change in between its + * read and its write. + */ + apr_uint32_t old, upd; + do { + old = *status; + upd = set ? (old | pwt->bit) : (old & ~(apr_uint32_t)pwt->bit); + } while (apr_atomic_cas32(status, upd, old) != old); return APR_SUCCESS; } pwt++;