Commit Graph
1658 Commits
Author SHA1 Message Date
Isaac ConnorandClaude Opus 5.5 9e3885e8fd refactor: remove ZM_OPT_FAST_DELETE
With fast deletes on, deleting an event in the web interface removed only
its Events row and left its Frames and Stats rows and its files for
zmaudit, and deleting a monitor left all of its events. zmaudit only runs
when ZM_RUN_AUDIT is on, and both options default to off independently,
so with fast deletes on and the audit off nothing ever removed them and
the Frames table grew without bound. In the Perl Event::delete the option
also kept zmfilter from removing the files of the events it purged.

Remove the option. ZM\Event::delete() always removes the Stats and Frames
rows and the files in one transaction with the Events row,
ZM\Monitor::destroy() always deletes the monitor's events, and the Perl
Event::delete deletes the files unless the storage area has DoDelete off.
zmupdate.pl rebuilds the Config table from ConfigData, so the option's row
goes away on upgrade without a migration. Drop the option from the docs,
from the zmaudit option help, and from the es_la, ro_ro and ru_ru
translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:50:01 -05:00
Isaac ConnorandClaude Opus 5.5 960d8feef7 fix: make Current Weekday filter terms run in the web UI and zmfilter.pl refs #5418
FilterTerm::sql_attr() returned 'weekday(NOW()' without its closing
parenthesis, so any filter with a Current Weekday term failed with
"Database query failed". FilterTerm::valid() treated the value 0 (Monday) as
missing, so a Monday term was dropped and the filter matched every event.

ZoneMinder::Filter had no CurrentWeekday case at all and emitted
E.CurrentWeekday, a column Events does not have, so zmfilter.pl could not run
such a filter either. Emit weekday(NOW()) there as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:29:02 -05:00
Nic BoetandClaude Opus 5.5 2625b53108 fix: let the PSIA control module compile
PSIA.pm has not compiled since it was added: move() built an unused
command string from undeclared $panSteps/$tiltSteps, and the PUT and
DELETE error paths logged an undeclared $cmd. zmcontrol.pl loads the
module when a PSIA camera is moved, so every PSIA PTZ command died.

Drop the unused line and log the request path on failure. A new test
compiles every control module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:27:39 -05:00
Nic BoetandClaude Opus 5.5 6beb62c9ee fix: stop logging camera passwords in the PTZ control modules
Control.pm's get(), put() and credential parsing, and the HikVision,
Netcat, PSIA, Serial_HEX_PelcoD, TapoC520WS_ONVIF, Instar720p,
Vivotek_ePTZ, Keekoon, M8640, FI8908W, IPCC7210W, DericamP2,
WanscamHW0025, Dahua and Grandstream modules logged the camera's
password: as a separate field ("username X password Y", which no
pattern in the logger can recognise), or inside the ControlAddress, Path
or request URL. Some of these are Info or Error lines, which reach the
Logs table at the default settings (Instar720p, IPCC7210W, DericamP2,
WanscamHW0025 on every command; FI8908W, M8640, Vivotek_ePTZ,
Grandstream on failures). Reolink_HTTP logged its API session token.

Log the user name without the password, URLs through urlForLog() (host,
port and path kept), and the Reolink token as a fingerprint. The test
scans the Perl modules for log calls that interpolate a password.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:27:39 -05:00
Nic BoetandClaude Opus 5.5 9a1fab7514 fix: stop logging the S3 secret key when parsing a storage URL
ZoneMinder::Storage::s3() logged the parsed S3 access key id, secret
key, host and bucket, and the URL they came from, at Debug level 1 in
every process that deletes or uploads events (zmfilter, zmaudit). Log
the key id, host, bucket and subpath, and the URL through urlForLog().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:27:39 -05:00
Nic BoetandClaude Opus 5.5 2db3d24d62 fix: redact credentials from every line the Perl logger writes
The PTZ control modules build camera URLs with user:password@ from the
ControlAddress or Path, or pwd= from the ControlDevice, and log them at
Debug, Info or Error. Info and Error reach the Logs table at the default
settings, which every System=View user can read. There are over fifty
modules, most written for one camera and not testable here.

ZoneMinder::Logger gets redactCredentials(), urlForLog() and
logFingerprint() (the same fp: tag as the web and C++ logs), and
logPrint() passes every message through redactCredentials(): userinfo is
removed from URLs and from scheme-less host specs, pass/pwd/secret
parameters are replaced, token= and auth= are fingerprinted, WS-Security
password digests and JSON password fields are replaced. Host, port, path
and the other parameters stay in the line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:27:39 -05:00
Isaac Connor 9b3caa20b0 Merge branch '5395-xml-libxml-dep' 2026-10-31 18:09:34 -04:00
Isaac ConnorandClaude Opus 5.5 21d2c26127 fix: load XML::LibXML explicitly in HikVision control module refs #5395
HikVision.pm calls XML::LibXML->load_xml and XML::LibXML::Element->new but
never loaded the module, so it only worked when another module had already
pulled it in. Add the missing use line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 18:06:50 -04:00
Isaac Connor ac1e167e6e Merge pull request #5382 from connortechnology/fix/ghsa-2pgc-session-fixation
fix: reject client-chosen session ids and regenerate on auth= / stateful API login (GHSA-2pgc)
2026-10-31 09:34:50 -04:00
Nic Boet b7f9c7631c chore: deprecate ZM_AUTH_RELAY=plain with a warning at start
The plain relay keeps the user's password in the web session and puts
user= and pass= in every stream, video and HLS URL the web UI builds,
in multi-server requests and in zmu command lines. hashed has been the
default for a long time and does none of that.

Mark plain as deprecated in the option's description and help, and
have zmpkg.pl log one Warning at start when authentication is on and
the relay is plain, pointing at hashed with ZM_AUTH_HASH_SECRET set.
The warning is logged once per start rather than per web request so it
does not flood the log. The option's values and behaviour are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 9ccb904bca)
2026-10-31 09:04:37 -04:00
Isaac Connor 2e50bdc431 Merge pull request #5360 from connortechnology/8g63-config-secret-oracle
fix: stop the Config API leaking secret values (GHSA-8g63-hqg8-82cv)
2026-10-30 08:51:27 -04:00
Isaac ConnorandClaude Opus 4.8 5f702842a5 fix: stop the Config API leaking secret values refs GHSA-8g63-hqg8-82cv
Two ways a System=View account could read secrets through the Config API.

The oracle: ConfigsController::index() passed the caller's named filter to
buildFilter() and returned the matched rows. redactSecret() blanked a secret
Value in the response but not in the WHERE clause, so a filter such as
Name:ZM_AUTH_HASH_SECRET/Value LIKE:a% returned the row for a correct prefix
and nothing otherwise - the row count leaked the secret a character at a time,
and that secret signs auth tokens. index() now detects a filter on the Value
column and drops the secret rows from the result, so their presence reveals
nothing; a filter on any other column is unaffected.

The flags: ZM_JANUS_SECRET, ZM_UPLOAD_PASS and ZM_MQTT_PASSWORD held secrets
but were not marked Private, so the API returned them to System=View and
skin.js.php wrote them into every page as JavaScript constants. Mark them
private in ConfigData.pm.in (fresh installs) and add a Config UPDATE to the
untagged 1.39.41 migration (existing installs). No web page reads the three;
zmfilter, zmc and the Janus integration read them server side.

Tested: tests/php/test_config_value_filter.php (11 cases) covers the Value
detection, including Model.Value, case, and the DefaultValue non-match.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-28 19:20:54 -04:00
Isaac ConnorandClaude Opus 5 0e19f4fb4c feat: set the ntp server, timezone and daylight saving rules on Herospeed cameras
Both cameras found on this network kept accurate UTC with no timezone set, so
their clocks were five hours out on the overlay while the recordings
themselves were correctly stamped. The factory daylight saving rule was also
nonsense everywhere: thirty minutes, March to September.

set_time points the camera at an ntp server and sets its timezone, with
optional summer time rules. The timezone is derived from a UTC offset rather
than hardcoded: the vendor's list starts at GMT-12:00 and steps every thirty
minutes, so -6 becomes index 12, which its own language pack labels
"(GMT-06:00) Central Time (US&Canada)". An offset with no index, a quarter
hour zone say, is refused instead of silently rounded.

These settings live in flash and set_time is meant to be safe to re-run, so
nothing is written unless it differs. Verified against a camera: an unchanged
call issues no write at all, a changed server issues exactly one, and
restoring it issues one more. The comparison recurses into the nested start
and end rules, which would otherwise always differ as hash references, and
compares as strings because the camera returns numbers and JSON booleans
interchangeably.

dstType is deliberately not sent. Supplying week based rules makes the camera
set it itself, and it rewrote the value we sent, so sending one would mean a
read back that never matches what was written.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-10-28 18:01:26 -05:00
Isaac ConnorandClaude Opus 5 4be5ca4744 feat: drive Herospeed cameras entirely through their own web api
Replaces the ONVIF subclass with a standalone protocol. ONVIF stays as it is
and remains the right choice for these cameras when only pan, tilt, zoom and
imaging are wanted; this exists for what ONVIF cannot reach on them.

The full ptz surface now goes through /api/image/ptz-ctrl, whose optType
values are taken from the web ui's PTZ_CONTROL_CMD_* constants: the eight
move directions and stop, zoom, focus including one-key autofocus, iris, auto
pan, lens initialisation, and presets by index and name. /api/image/ptz-info
adds pan, tilt and zoom position read-back, which ONVIF does not offer here.

The white supplement floodlight is dayNightMode.ledMode in
/api/image/image-param, switched between Warm Light and IR Light. ONVIF
exposes no light at all on this hardware - both GetRelayOutputs and the PTZ
auxiliary Wiper command are accepted and neither does anything measurable.

Login is the camera's five round handshake, with the session cookie returned
in the response body rather than a Set-Cookie header. The rounds are pure
functions and a captured exchange is replayed by a test: each one hashes the
raw bytes the previous hex digest names rather than its text, and getting
that wrong produces an equally plausible digest whose only symptom is a
refused login. Code 101 means the session expired, so every call re-logins
once and retries rather than dropping an operator's keypress.

Speed is clamped: the device advertises no range anywhere in its api or ui.
Preset indexes are validated before being sent for the same reason.

Standing alone also means no imports are inherited. Missing ones are invisible
to perl -c and only fail on the path that uses them, so the tests assert the
required modules are actually loaded.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-10-28 18:01:26 -05:00
Isaac ConnorandClaude Opus 5 bcb0fa85a5 feat: add a control module for Herospeed / LS Vision cameras
These identify themselves as Manufacturer "NONE", Model "IPCamera" over
ONVIF; the real name is in the ONVIF scope (name/L5TW), in the vendor api's
/system/device-info, and in the 2C:6F:51 OUI.

PTZ, presets and imaging are inherited from the ONVIF module, which the
camera implements well - absolute, relative and continuous move, 256 presets,
brightness through sharpness, and motion and tamper events.

What ONVIF does not expose is the white supplement floodlight the deterrence
feature uses. GetRelayOutputs and the PTZ auxiliary Wiper command are both
accepted by the camera and both do nothing measurable. The light lives in the
vendor REST api at /api/image/image-param, as dayNightMode.ledMode, switched
between Warm Light and IR Light.

Reaching that api needs its login handshake: sha256 over
username+salt+base64(timestamp)+password, rehashed over the raw digest bytes
with the challenge appended, optionally iterated, with the session cookie
returned in the response body rather than a Set-Cookie header. The rounds are
pure functions so the captured exchange is replayed by a test; the raw-bytes
versus hex-text distinction in particular produces an equally plausible digest
when wrong, so it is pinned rather than trusted.

The section write echoes every field back, since a partial write makes the
camera drop what it was not sent.

Note the supplement light only engages while the camera is in night mode, so
setting it during the day reads back correctly but produces no light.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-10-28 18:01:26 -05:00
Isaac ConnorandClaude Opus 5 aed16db997 fix: ignore a control command the protocol does not implement instead of dying
zmcontrol dispatches straight onto the control object with
$control->$command(...). A monitor's actions and ui buttons are configured
independently of its control protocol, so nothing stops a LightOn action
pointing at a protocol with no lightOn, and Perl kills the control server with
"Can't locate object method".

Swapping a camera for a different make produces exactly that. A monitor whose
AMLink camera was replaced by an ONVIF one kept its LightOn and LightOff
actions, and ONVIF has neither, so the first alarm after the protocol change
would have taken the control server down for that monitor.

Check can() before dispatching, log which monitor and command need attention,
and answer a caller that asked for a response rather than leaving it hanging.
Direct protocol mode gets the same check, as a Fatal, since there the command
came from the command line and is a typo worth reporting.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-10-28 18:01:26 -05:00
Isaac ConnorandClaude Opus 5 78f389cdea feat: add ZM_ALLOWED_COMMANDS to restrict what filters and tasks may run refs #4957
Two places in ZoneMinder run a command the operator typed: a filter with
"Execute command", and the scheduled tasks added for #4957. Both run it as the
web user through a shell, which is close to shell access on the server. Until
now the only control over that was who may edit, and the answer was anyone
with System rights.

ZM_ALLOWED_COMMANDS names the programs that may be run, comma separated.
Empty is the default and places no restriction, so an upgrade changes nothing
and the filters people already have keep working; setting it narrows both
features at once.

Only the program is matched, because an exact whole-command match could never
work for filters: zmfilter.pl appends the event path to whatever the filter
stored, so no two runs have the same command line. Arguments are therefore
free, which means the program being on the list has to be the whole of the
guarantee -- so while a list is in force a command may not contain the
characters that start another program: semicolon, pipe, ampersand, backtick
and dollar-paren. Without that, "/usr/local/bin/backup.sh; anything" would
pass on the strength of its first word. Redirection is deliberately allowed;
it starts no program, and refusing it would break the ordinary
"... >> /var/log/mine.log".

Refused in three places, because each answers a different question. The
filter and scheduled task editors refuse on save, so the operator is told at
the time rather than by a log line days later. zmfilter.pl refuses at the
moment it runs, because a row can reach the database without passing through
the web ui and because the setting may have been narrowed since. And
cronRebuild leaves a newly disallowed task out of the crontab, so tightening
the setting takes jobs away rather than waiting for somebody to edit each one.

The rule exists twice, in web/includes/Command.php and ZoneMinder::General,
since one is PHP and the other Perl. Rather than hope they stay in step,
tests/php/test_allowed_commands.php puts every case to both and fails if they
disagree. That earned itself immediately: both split the command on
whitespace before handling quotes, so a program path containing a space was
cut in half and compared as the wrong string. The cross-check found it in
both at once.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-28 18:01:25 -05:00
Isaac Connor b7405c58c5 Merge pull request #5288 from nabbi/hard/auth-default
Ask at first run whether to require a login, and refuse the password admin
2026-10-16 19:03:06 -04:00
Isaac ConnorandClaude Opus 5.5 cbc2eaa334 fix: set the Private and System flags of options on fresh installs and on update
zmconfgen.pl wrote zm_create.sql's Config rows without the Private and System
columns, so a database created from it had both at 0 for every option until
zmupdate.pl -f rewrote the table from ConfigData. The web UI relies on Private
to keep a secret out of the browser: skin.js.php exports every option that
isn't Private as a JavaScript constant on every page, the login page
included, and the Options page shows a Private value only to users who can
edit System settings (GHSA-7g3f-93q8-fhwj). So on such a database
ZM_AUTH_HASH_SECRET, which is enough to sign an admin token, was sent to
anyone who loaded the login page. A fresh RPM install is one: the spec runs
zmupdate.pl -f only on upgrade. Debian packages run -f on install.

- zmconfgen.pl writes Private and System like saveConfigToDB() does.
- ZoneMinder::Config::syncConfigFlags() sets each row's Private and System
  flags from ConfigData without touching its value, and zmupdate.pl calls it
  on every update, so an existing database is repaired the next time it is
  updated without needing -f.
- skin.js.php never exports a password option, whatever its flag says.

Tested with zm_create.sql generated from this tree, loaded into a scratch
database: the fresh install has the 3 Private options and 1 System option
ConfigData marks. With every flag zeroed, syncConfigFlags() set those 4 rows
and on a second run changed none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 11:50:30 -04:00
Nic Boet b631d2efc9 feat: add a minimum length for new passwords refs #5287
Add ZM_PASSWORD_MIN_LENGTH (Options, System; default 8, 0 turns it off).
passwordProblem() refuses a shorter password, so the user page, the API
and both login-page forms apply it alike. Existing passwords keep
working; only a password being set is checked. The length counts
characters, not bytes.

There is no setting for character classes: they push people to
predictable variations (Password1!) and add less than length does.

A database whose Config table doesn't have the option yet (an upgrade
not run with zmupdate.pl -f) gets no minimum. The password inputs carry
minlength so the browser says so before the form is sent; the server
check is the one that counts. The API answers with the English text, as
for the other reasons.

Tests: tests/php/test_default_password.php.
2026-10-16 10:13:53 -05:00
Nic Boet 9ee0e91819 feat: turn authentication on by default for new installs refs #5287
ZM_OPT_USE_AUTH shipped as 0, so a new install accepted every request as
the default user with System=Edit. That includes requests a browser sends
on behalf of any web page a user on the same network opens, so a server
that is never exposed to the internet could still be driven from it.

Default it to 1. zm_create.sql (generated from ConfigData) gives new
installs authentication on. Existing installs keep their value:
zmupdate.pl -f loads Value from the database and writes it back, and only
DefaultValue changes. zm_update-1.39.41.sql also sets DefaultValue to 1
for the row, so that an upgrade run without -f doesn't leave
Value = DefaultValue = 0, which the C++ config loader would skip in favour
of its compiled-in default (on) while the web UI read off.

Update the option help and the user guide (getting started, FAQ, system
options) to say authentication is on for new installs and kept on
upgrade. tests/perl/test_auth_default.pl checks the default, the stored
value and that no update script sets the row's Value; tests/zm_config.cpp
now expects the compiled-in default (opt_use_auth) to be on.
2026-10-16 09:40:37 -05:00
Isaac ConnorandClaude Opus 5.5 7603a7458f fix: read yes/no, true/false and on/off in config files as booleans in PHP and Perl
A boolean option set in zm.conf or conf.d wins over the Config table, and a
person editing a file writes yes or off rather than 1 or 0. The C++ daemons
now read those words (ConfigFileValue, 4d7609d36), but PHP and Perl took the
value as written, and a non-empty string is true in both. So
ZM_STRICT_VIDEO_CONFIG=off in conf.d left the option on in the web UI and the
Perl scripts while zmc turned it off.

Read a file value for a boolean option the same way in all three: yes, true
and on are 1; no, false and off are 0; anything else stays as written. Only
booleans are read this way, so a string option such as a title keeps "Yes".

PHP defines the file values as constants before it reads the Config table,
since it needs the database settings to connect, and only the table says
which options are booleans. So a word now waits until the table has been
read, apart from ZM_DB_* settings, whose words database.php reads itself.
Perl reads the type with each row.

Tested on 1.38's zm138 database with a conf.d file setting
ZM_OPT_FAST_DELETE=yes (0 in the table), ZM_STRICT_VIDEO_CONFIG=off (1)
and ZM_WEB_TITLE=Yes. The installed PHP and Perl gave 'yes', 'off' and
'Yes'; these give '1', '0' and 'Yes'. tests/php/test_config_file_booleans.php
checks the rule.

refs #5289

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 22:37:07 -04:00
Isaac Connor 4581360cf7 Merge pull request #5201 from nabbi/fix/b53-close-orphaned-events
fix-high: close events left open by a capture daemon that died
2026-10-13 18:17:38 -04:00
Nic BoetandClaude Opus 5.5 e472cd1533 fix: keep a name the user gave an event that zmwatch closes
Event::Close() renamed the event to <prefix><Id>(r) every time. That
was fine while only zmeventtool.pl close and zmaudit called it, by hand
or a day later; with zmwatch closing events left open by a zmc that
died, it would overwrite a name the user set while the event recorded.

Rename only when the name is still the placeholder 'New Event', as
zmc's own close does (~Event: Name = IF(Name='New Event', ...)). The
'Recovered.' note still marks the event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:37:20 -05:00
Nic BoetandClaude Opus 5.5 fb534131f8 fix: load JSON through JSON::MaybeXS in Reolink_HTTP, Uniview and jsonLoad
Reolink_HTTP.pm and Uniview.pm said `use JSON`, and
ZoneMinder::General::jsonLoad required JSON. The Debian and Ubuntu
packages depend on libjson-maybexs-perl, not libjson-perl, so on a
packaged install neither control module loads ("Can't locate JSON.pm in
@INC") and jsonLoad, which reads MacVendors.json for the network scan,
logs that error and returns nothing.

Use JSON::MaybeXS as the other control modules (AMLink, Dahua_RPC,
IPSpeaker) and the rest of ZoneMinder::General already do. encode_json
and decode_json behave the same; JSON::MaybeXS picks Cpanel::JSON::XS,
JSON::XS or the core JSON::PP.

tests/perl/test_json_maybexs.pl hides JSON.pm from @INC and loads both
modules and runs jsonLoad.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:24:24 -05:00
Nic BoetandClaude Opus 5.5 dc09122eb3 fix: close a recovered event from its row when it has no Frames rows
Event::Close() (zmeventtool.pl close) took the end of an event only from
its Frames rows and refused events that had none. zmc writes Frames rows
in batches and updates the event row's Length, Frames and scores with
each batch, so an event whose zmc was killed in its first seconds has no
Frames rows, and either side can be ahead of the other.

Take Length, Frames, AlarmFrames, TotScore and MaxScore as the larger of
the event row and the Frames rows; EndDateTime follows the Length that
was used. The name and Notes are written as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:36:14 -05:00
Isaac ConnorandClaude Opus 5 6c0f976c22 refactor: move the presentation settings to the Display tab
The skin and css, the language and locale, the date, time and datetime
formats, the default bandwidth and the snapshots feature switch all
decide how the interface looks or what it offers, which is what that tab
is for, but they sat under System among the shutdown command, the shm
key and the audit intervals. System drops from 42 entries to 33 and
Display goes from 32 to 41.

The snapshots switch is read only by the skin: it gates a button in
montage and montage review, a menu item, and the snapshot views and
their permission checkboxes. Nothing in the daemons or the perl scripts
looks at it.

The category key is still 'web'. That is the tab now labelled Display;
the tab whose key is 'display' holds the per-session cookie settings and
stores no configuration at all, so a stored default does not belong
there. The hint setup for the moved entries -- the installed skin list,
the css list for the current skin, the bandwidth options, and the
language and locale lists -- moves to the same branch.

ZM_TIMEZONE stays under System. It reads like a presentation setting,
but Filter.pm uses it for date arithmetic when evaluating filters, so it
changes behaviour and not just what is displayed.

A migration, 1.39.40, is needed as well as the ConfigData change, because a
version upgrade does not rewrite Config: zmupdate only reloads it from
ConfigData under --freshen, which is mutually exclusive with an upgrade
run. Fresh installs take the new category from the generated
zm_create.sql.

Verified both paths converge on 33 system and 41 display entries with
identical membership: a fresh install of this branch, and a copy of a
real pre-change Config table with the migration applied. On the running
install the bandwidth, language and locale entries still render as their
pickers on the new tab, css as its list of choices, and the timezone
picker is still on System with its full list.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
2026-10-10 09:32:17 -04:00
Isaac ConnorandClaude Opus 5 1043273495 refactor: drop the unused Type column from Controls
Controls.Type looks like the monitor type a control applies to, and has
been kept in step with the Monitors enum since 1.27, but nothing has
ever read it. The control dropdown on the monitor page lists every row
by Name, no query filters on it, and no code compares it to the
monitor's own Type. It was a field the edit form asked for and the
control list displayed back.

The column appears to be MonitorPresets.Type copied by analogy, where
the idea is real: that one decides what a preset creates. That also
explains why every migration altering one altered the other.

Removes the column from the schema, adds the 1.39.39 migration, the edit form row
and its type list, the control list column, the defaults in Control.php
and Control.pm, and the value from all 53 shipped rows in controls.sql.
This supersedes the 1.39.38 retyping of three libvlc controls to Ffmpeg:
the column they were being retyped into is gone.

zmcamtool needs no change -- its import regex rewrites the Id and
captures the Name, so it is not positional past that, and its export is
a mysqldump that follows the live schema.

Dropping Type left the two shipped Pelco rows byte-identical to their
twins, which existed only as a Local and an Ffmpeg copy of the same
control, so the redundant copies are removed: 53 shipped rows become
51, with both Pelco-D and Pelco-P still present once.

Existing installs are deliberately left with their duplicates. The same
pair collapses there too, but deleting rows a monitor's ControlId may
point at, to tidy a repeated name in a dropdown, is not a trade a
migration should make silently.

Verified by loading the old and rewritten controls.sql into scratch
databases and diffing every remaining column across all 53 rows: no
value shifted, which is the failure mode when a positional INSERT loses
a field. The file mixes positional and explicit-column INSERTs, so both
forms were handled. Fresh-install and migrated Controls schemas compare
equal, the shipped data loads into both, and Monitors and MonitorPresets
keep their Type. Build clean, 147 test cases pass, php -l and perl -c
clean on the edited files.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
2026-10-10 09:32:17 -04:00
Isaac ConnorandClaude Opus 5 bf8a73e9fb feat: remove Libvlc from the web ui, api and config help
Follows the daemons: no monitor can be type Libvlc any more, so the ui
should not offer it or carry text describing it.

Drops the source-type option and its deprecation notice, the Libvlc arm
of the Source Path and console source-column branches, the entry in the
control-capability type list, and the value from the api's Type
validation list. The OPTIONS_LIBVLC help block goes from all 25 language
files: monitor.php builds that key as OPTIONS_ plus the monitor type, so
it became unreachable the moment the type did. The Libvlc source-type
label goes from the 22 files that carried it.

SourceTypeDeprecated and Deprecated lose their last caller and are
removed. RemoteRtspDeprecated and Removed stay -- the rtsp protocol
option is still shown to monitors already set to it.

The WEB_FILTER_SOURCE help listed the affected source types; corrected
in ConfigData.pm.in and in the one translation that had localised it.

All 25 language files and the four edited php files parse clean under
php -l, and the config module parses under perl -c. No javascript
changed, so eslint has nothing to say here -- it cannot run in this
worktree anyway, which has no node_modules.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
2026-10-10 09:32:17 -04:00
Isaac ConnorandClaude Opus 5 af0d6ddc32 refactor: remove RTSPDescribe, which lost its reader with the rtsp client
RTSPDescribe chose whether to take the media url from the DESCRIBE
response rather than the configured path. That was a quirk of
ZoneMinder's own rtsp implementation; ffmpeg decides it itself. Removing
that client left the setting with nothing behind it -- the monitor form
still drew the checkbox and the save path still wrote the column, but no
code read it, so the only thing it could do was mislead whoever ticked
it.

Drops the form row and the Remote-only block that existed to hold it,
the javascript that showed and hid it as the protocol changed, the field
in the php and perl monitor models, the default in the save action, the
column from the schema, and the label and help text from all the
language files carrying them.

The 1.39.37 migration drops the column behind an information_schema
guard scoped to DATABASE(), so the file stays re-runnable.

Verified by building a pre-upgrade database from upstream/master's own
schema and applying the migration: the column goes, and Monitors matches a fresh install of this
branch column for column. Migration applied three times with no error.
php -l clean on the four edited files and all 28 language files, perl -c
clean, build clean, 154 test cases pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015Y6FieTwEXuLhhR4e2yiax
2026-10-10 09:32:17 -04:00
Isaac ConnorandClaude Opus 5.5 0e9f82513c fix: bind the FOSCAMR2C preset and require Control permission for PTZ refs GHSA-qcm7-vq92-f86f
FOSCAMR2C presetGoto and presetSet interpolated the preset into
"SELECT Label FROM ControlPresets WHERE Preset = $preset" and sent the selected
Label to the camera as name=. For presetGoto the preset came straight from the
web request, so any user who could see the monitor could run a SELECT against
the ZoneMinder database and have the value (the auth hash secret, password
hashes) delivered to the camera link, or use it as a boolean oracle.

- FOSCAMR2C: bind the preset in every statement, refuse a preset that is not a
  number, and look ControlPresets up by MonitorId as Dahua and PSIA do.
- buildControlCommand(): refuse a non-numeric presetGoto preset, and a control
  name that is not a plain method name. zmcontrol calls the name as a method and
  the options are split back out of the command string on spaces.
- zmcontrol.pl: refuse a command that is not a plain method name, so a qualified
  Package::sub name can't call a sub outside the control module.
- canView()/canEdit() with a monitor id returned only the monitor check and
  ignored the area, so canView('Control', $mid) passed for anyone who could see
  the monitor. Require the area permission as well; Monitors stays decided by
  visibleMonitor()/editableMonitor().

tests/php/test_control_command.php covers buildControlCommand() and the
monitor-scoped canView()/canEdit(); tests/perl/test_foscamr2c_preset_sql.pl
checks the statements FOSCAMR2C prepares and what it sends to the camera.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 18:21:32 -04:00
Isaac ConnorandClaude Opus 5.5 0d6ebcd42c fix: accept ZM_GO2RTC_PATH with or without its /api suffix
go2rtc serves its API under /api, and its websocket at /api/ws. zmc
appends /streams to ZM_GO2RTC_PATH and the browser appends /ws, so the
setting only worked if it ended in /api. The natural value to enter is
the server address, http://host:1984, and with that zmc reached
/streams, which is go2rtc's RTSPtoWeb compatibility endpoint, so no
stream was ever registered, and the browser's /ws was a 404. Where
another player was available the failure went unnoticed.

Normalise the setting where URLs are built from it: a trailing slash is
dropped and /api is added unless the path already ends in it, which also
covers go2rtc behind a reverse proxy at a sub-path.

- Go2RTCApiEndpoint() in zm_utils, used by zmc's Go2RTCManager.
- go2rtcApiUrl() in skin.js, used by MonitorStream and the console
  thumbnail stream. It assigns the path once, since stripping the slash
  from a bare host's "/" and appending gave "//api", as the old
  pathname += '/ws' gave "//ws".
- The option's help says the suffix is optional.

Catch2 and node tests cover bare hosts, trailing slashes, an existing
/api, a proxy sub-path and credentials in the URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 18:34:04 -04:00
Isaac ConnorandClaude Opus 5.5 c4ef3fdd62 feat: key Frames by (EventId, FrameId) and drop the surrogate Id refs #5164
Every query on Frames filters on EventId and orders or ranges by FrameId,
and nothing needs a frame by Id. The Id primary key was a clustered index
nothing read, and EventId_FrameId_idx was a secondary index every query
used. On a copy of a local table that secondary index was half the
table's size. With (EventId, FrameId) as the primary key the index is
gone, and an event's rows are stored together, so deleting an event is a
range delete.

zm_update-1.39.36.sql:
- converts AI_Detections.FrameId from Frames.Id to the per-event frame
  number, drops its foreign key to Frames and indexes (EventId, FrameId).
  A composite foreign key cannot replace it: ON DELETE SET NULL would
  have to null the NOT NULL EventId, and Frames rows are written in
  batches, so a detection can be recorded before its frame row.
- removes duplicate (EventId, FrameId) rows, keeping the earliest.
- rebuilds Frames with the new primary key.
- removes ON UPDATE CURRENT_TIMESTAMP from Frames.TimeStamp. Any UPDATE
  of a frame row was overwriting its capture time.
Each step checks the current schema first, so the migration can be
re-run.

REST API: view, edit and delete take /frames/<action>/<EventId>/<FrameId>.json.
The old single-Id URLs return 404. CakePHP 2 has no composite keys, so
the model's primaryKey is EventId. That keeps Event's dependent cascade
delete limited to the event's own frames. The controller writes with
explicit (EventId, FrameId) conditions instead of save(), which would
match rows on EventId alone. Edit no longer changes EventId or FrameId.

view=image with fid but no eid used to look up Frames.Id. It now returns
404.

The Perl Frame class is identified by (EventId, FrameId).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:48:26 -04:00
Isaac ConnorandClaude Opus 5.5 e99a0531a1 fix: replace and refuse the shipped ZM_AUTH_HASH_SECRET refs GHSA-wmcc-x64g-jr84 GHSA-p2c6-jw8f-ffjc
ZM_AUTH_HASH_SECRET signs the JWT access and refresh tokens, and its
default is a fixed string in the public source. Nothing generated a
per-install value and tokens signed with the default verified normally,
so on an install with auth on and the secret untouched anyone could sign
an admin token and be accepted by the web UI, the API and zms.

- ZoneMinder::Config::saveConfigToDB() now replaces an empty or default
  secret with 32 random bytes from /dev/urandom, hex encoded. Package
  installs and upgrades run zmupdate.pl -f, which saves the config, so
  existing installs get a secret on upgrade. A secret the admin set is
  left alone.
- validateToken() in PHP and zmLoadTokenUser() in C++ refuse to verify
  tokens while the secret is empty or the default, and the API refuses to
  issue them, as it already did for an empty secret.
- zmLoadTokenUser() no longer writes the signing key to the debug log.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 19:47:22 -04:00
Isaac Connor 84967e9b52 fix: treat event DefaultVideo and Name as filenames in the perl scripts
GenerateVideo used DefaultVideo as the ffmpeg input relative to the event
directory and built the output file from Name with only whitespace
replaced, so an Events=Edit user could make zmvideo read or write any
path the account can reach. zmfilter's generateImage passed
event_path/DefaultVideo to ffmpeg -i, and the %EV% email tag attached
event_path/DefaultVideo, which could mail out any readable file.

Strip everything up to the last path separator from DefaultVideo in all
three places, and reduce Name to [-A-Za-z0-9_.] with no leading dot
before using it as the video filename.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 5904023f13448e557dc205edb9440972e4a6482d)
2026-09-24 23:16:11 -04:00
Isaac Connor 9f3f6c6770 fix: only trust X-Forwarded-For from configured proxies for auth hash IPs
With ZM_AUTH_HASH_IPS on, the client address bound into the auth hash was
taken from the left-most X-Forwarded-For value whenever the header was
present, both when PHP generated the hash (getRemoteAddr()) and when PHP or
zms validated it (getAuthUser(), zmLoadAuthUser()). The header is client
controlled, so anyone holding a leaked hash could replay it from anywhere by
sending the address it was bound to.

Add ZM_AUTH_TRUSTED_PROXIES, a list of exact reverse proxy addresses.
X-Forwarded-For is now used only when REMOTE_ADDR is one of them, and is read
from the right, skipping hops that are themselves listed proxies, so values a
client prepends are never chosen. With the option empty, the default, the
header is ignored and REMOTE_ADDR is used.

PHP (web/includes/Network.php getRemoteAddr()) and C++ (ClientAddress() in
zm_utils, used by zmLoadAuthUser()) implement the same rule so generation and
validation continue to agree. Every PHP caller already routes through
getRemoteAddr(), so session.php and auth.php need no change.

Reverse proxy users who enable ZM_AUTH_HASH_IPS must list their proxy in the
new option; until they do, hashes bind to the proxy address, which still
validates but no longer distinguishes clients. This is the behaviour change
that the #4921 work avoided by trusting the header.

The option is added through ConfigData only, like other recent options;
zmupdate.pl --freshen inserts it, zms falls back to the compiled-in default and
PHP treats an undefined constant as empty, so no schema migration is needed.

Tests: ClientAddress Catch2 case; tests/php/test_remote_addr.php updated for
the trusted-proxy rule.

refs GHSA-72rf-54rm-798c

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit acea5889dec0826f595cb736147a5fdc9c94a2a9)
2026-09-24 19:51:27 -04:00
Isaac Connor ce485022d2 fix: validate filter attributes and operators and quote their values
zmfilter.pl rebuilds SQL from the JSON the web tier stores verbatim in
Filters.Query_json, so a saved filter's attribute, operator and value all
arrive at the statement exactly as they were written. None of the three were
checked here, while web/includes/FilterTerm.php checks all three: values were
wrapped in quotes by hand, which a value containing one closes; the final
attribute branch concatenated 'E.'.$attr; and the generic operator branch
emitted the operator as written.

Any account that can save a filter could therefore have the daemon run SQL of
their choosing with its own credentials, against a table set that includes
Users. The daemon also deletes and moves events, so this is not only a read.

Confirmed against the module before the change, building SQL from stored terms
and checking whether the payload landed outside a string literal:

  val  = "x' OR 1=1 -- "        -> outside, injected
  attr = "Id=1 OR 1=1 -- "      -> outside, injected
  op   = "= 1 OR 1=1 -- "       -> outside, injected

Attributes now have to match what the PHP accepts, operators have to be one of
the sixteen the UI can produce, and a filter carrying anything else is refused
rather than run. Values go through DBI's quote().

Numbers are left unquoted so the statements the existing filters produce are
unchanged: a bare number cannot carry SQL, and quoting it would have altered
every numeric comparison in the file for no gain. Verified by generating the
SQL for seven representative filters before and after -- purge-when-full,
delete-after-a-day, LIKE on a name, IN on monitors, a monitor name, a score
range and an IS NULL -- and diffing: identical apart from the timestamp a
relative date resolves to.

After the change the three payloads above are contained in a literal, or the
filter is refused.

See GHSA-p8h3-4x5c-cv7p.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WBHBB95RBX7D9p8ge2WDZb
(cherry picked from commit bc11642fea844bc86bac0080da42e4514d5a4d76)
2026-09-24 19:44:16 -04:00
Isaac Connor 279e467b95 fix: run the event video encoder without a shell
Event::GenerateVideo built an ffmpeg command line as a string and ran it
through qx(), and two of the values in it are event fields an operator with
Events=Edit can set through the API. DefaultVideo was interpolated with no
quoting at all. The name behind the output filename only has its whitespace
replaced, so a single quote in it closed the quoting that was there. Either one
gave arbitrary command execution as the account the daemons run as.

Both confirmed against the module before the change, driving GenerateVideo
directly:

  DefaultVideo = "x.mp4; touch <marker>; echo"     -> marker created
  Name         = "evt';touch${IFS}<marker>;echo'"  -> marker created

The second needs ${IFS} rather than spaces because the name has whitespace
substituted before it is used, which is the whole of the sanitising that was
being relied on.

The command is now a list passed to exec, so there is no shell to escape from
whatever those fields hold; ffmpeg's own output still lands in the event's
ffmpeg.log. The two configured option strings are admin-set and hold several
options each, so they are split on whitespace to become separate arguments;
shell quoting inside them is no longer honoured.

After the change both payloads run ffmpeg with the injection as a literal
argument and create no marker.

See GHSA-pfph-4j9j-7cv7.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WBHBB95RBX7D9p8ge2WDZb
(cherry picked from commit 5fc491728c679bc7a8ff4b51183983e7fe184200)
2026-09-24 19:44:16 -04:00
Isaac Connor 6442f404dc Merge branch 'openbsd-support' 2026-09-24 19:34:18 -04:00
ovi-vansidandClaude Opus 5.5 276eba92e6 fix: use su -s /bin/sh USER -c for running as the web user refs #5152
The long options --shell/--command are util-linux only. OpenBSD su takes
-s for the shell and passes arguments after the login name to it, and
util-linux su accepts the same form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 17:01:21 -04:00
Isaac Connor 8f5a0af862 Merge pull request #5143 from SteveGilvarry/feature/stream-socket-events
Replace the per-monitor media FIFOs with a unix stream socket
2026-09-23 18:17:50 -04:00
Isaac ConnorandClaude Opus 5 428c048bac feat: measure the audio level on demand, with a meter in the editor
Reverts the previous commit's always-on measurement. Decoding audio for every
monitor that has it spends CPU on a number almost nothing reads, which is the
wrong trade even though it did solve the chicken and egg of picking a
threshold without ever seeing a level.

Measure when something is actually going to use the reading instead:

 - AudioDetection is on, as before, so nothing changes for a monitor that
   scores on audio; or
 - somebody asked. SharedData gains audio_level_until, a wall clock second
   the capture thread keeps measuring up to. The monitor editor's new level
   meter pushes it forward while it is on screen and the measurement lapses a
   few seconds after the page is left, so nothing has to send a stop and a
   crashed browser cannot leave a monitor decoding forever.

When the reading stops being wanted the decoder is released and the published
level and peak are cleared, so a stale number is not left looking current and
an old peak does not land on the next frame row written.

audio_level_until is carved out of analysis_pad rather than appended, so
SharedData stays 888 bytes and no existing offset moves; the static_asserts,
Memory.pm and Monitor.php are updated together and all three now agree the
field is at +880.

The meter itself is on the audio settings, shown whether or not
AudioDetection is checked, because the level is what you need in order to
choose a threshold. It draws the threshold currently in the input as a mark on
the bar so a reading can be judged against it before saving, and a monitor
whose zmc is not running reads "no reading" rather than a confident 0, which
would be indistinguishable from silence.

Frames.AudioLevel is therefore 0 again on monitors that do not score on audio.
That is what the graph already treats as "no audio data", so it draws no line
rather than a flat one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JpiSWBmtQkR5bcgpHWY4ME
2026-09-20 18:17:44 -05:00
Isaac ConnorandClaude Opus 5 16a2831fe6 fix: weigh a monitor's Importance when logging that a device is unreachable
A speaker that has dropped off the network fails on every command until
somebody fixes it, so that is the one error in IPSpeaker that repeats forever
rather than once. On a monitor deliberately marked unimportant it is noise,
and it buries the failures worth acting on.

Nothing about that is specific to speakers, so the policy goes in Logger as
importanceLevel, with ErrorImportance and WarningImportance alongside the
plain Error and Warning for callers to use. It takes the importance value
itself rather than a monitor, so Logger needs to know nothing about monitors
and callers that have some other notion of how much something matters can
still use it.

zmwatch.pl has been open coding the same idea as
WARNING+$monitor->ImportanceNumber() in three places; it now calls
WarningImportance instead, which is the same arithmetic and so leaves its
levels exactly as they were, including the Not important case that lands in
DEBUG1. That case is pinned by a test rather than quietly corrected: it is
long standing behaviour and not this change's business. zmwatch no longer
needs the logger object it was keeping for logPrint, so logInit() is called
bare there as it is in every other script.

Anything that is not a number counts as Normal, so a caller with no monitor
to ask still reports in full: not knowing how much a monitor matters is no
reason to hide its faults.

IPSpeaker is then a one line change at the call site. Only the failure to
reach the device is weighed; a refusal or unparseable content means the device
answered and something is really wrong, which is worth an error however
unimportant the monitor is, and does not repeat the same way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JpiSWBmtQkR5bcgpHWY4ME
2026-09-20 18:17:43 -05:00
Isaac ConnorandClaude Opus 5 8b14fba2db fix: bound the IPSpeaker http timeout instead of leaving it at LWP's default
LWP::UserAgent defaults to 180 seconds. Actions for a monitor are serialised
through one control daemon, so a speaker that has dropped off the network holds
that daemon for three minutes per attempt and every command queued behind it
waits. AMLink already sets a timeout; this did not.

Ten seconds, matching AMLink. The speaker answers in milliseconds when it is
reachable at all, so this only ever bounds the case where it is not - which is
the case right now.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-20 18:17:43 -05:00
Isaac ConnorandClaude Opus 5 70836e7c83 fix: recognise the AMLink plain-text reply that means the session expired
The camera does not report an expired session as a JSON error. It answers with
a bare printable string, "Invalid session in request", where a masked base64
payload belongs. Unmasking that and base64 decoding it produces noise, so a
routine timeout was logged as "malformed JSON string ... at character offset
0" - which named neither the session nor the camera's own explanation.

Detect it before unmasking, log what the camera actually said, and treat it as
a lost session so the existing recovery re-establishes it. session_error is
pure so the wording seen on the wire is pinned by a test rather than by a
camera happening to be in the right state.

refs #4423

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-20 18:17:43 -05:00
Isaac ConnorandClaude Opus 5 b4599c16f2 fix: keep the control session alive while a monitor is busy, not only while idle
zmcontrol sent keepAlive only from the branch that runs when select() times
out. A monitor taking a steady stream of commands never reaches that branch,
so it never pinged at all, and cameras that expire a session on a timer
refresh it on the keepAlive rather than on ordinary requests. The monitors
with the most traffic were therefore the ones that lost their session.

Measured on monitor 1: it pinged twice while idle, then took a command every
three seconds for three minutes and the camera rejected the next one 181
seconds after the last ping. Its light commands were being dropped for as long
as the motion kept coming, which is exactly when they matter.

Move the decision into Control::keepAliveDue, timed from the last ping, and
check it at the top of the loop so the 'next' paths in the command handling
cannot skip it. A clock step backwards resets the baseline rather than holding
the ping off until real time catches up.

refs #4423

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-20 18:17:43 -05:00
Isaac ConnorandClaude Opus 5 78ed0fee3c fix: re-establish the AMLink session when a reply cannot be decoded
An undecodable reply means the camera and this module no longer agree about
the session, but nothing put that right. Dahua_RPC re-logs-in only when it gets
a parseable error back, so rpc_call returning undef left the session poisoned:
in the logs a CoaxialControlIO.control failure is followed by every later
keepAlive and logout on that session failing the same way, until something else
forces a login. A light switched on by an alarm stays on for that whole period.

Split the single attempt out as rpc_once, recording why it failed, and have
rpc_call re-login and retry once when the failure was a decode failure on a
masked Request.

The guards matter more than the retry:
- bootstrap channels never recover, since login() issues them
- login() calls logout(), a Request on the dead session, so a re-entrancy guard
  stops its own decode failure starting another recovery
- one retry only, and a 5 second backoff, so a camera that always answers
  unreadably is not met with a login per command

refs #4423

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-20 18:17:43 -05:00
Isaac ConnorandClaude Opus 5 c27f905470 fix: keep the AMLink decode diagnosis out of the part of the message that is discarded
The decode failure diagnostic appended its fields after $@, which ends in a
newline, so the payload length, alignment, unmasked-decode result and leading
bytes were pushed onto a second line where nothing looked for them.

$@ was also read after the unmasked-decode eval had already reset it, so the
error reported was that eval's outcome rather than the failure being described.

Add log_safe to flatten a message before logging, use it for the three places
that interpolate $@, capture the real error before running another eval, and
report the decoded byte count and the decoded leading bytes - the base64 alone
does not say whether what failed to parse was truncated or simply not ours.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UvTCzCbvGt8xKQRNCSA7o8
2026-09-20 18:17:43 -05:00
Claude d5012d5bc0 docs: document the shm field retirement convention for reserved_path2
The audio_fifo_path field was retired alongside video_fifo_path when the
media FIFOs were replaced by the stream socket. video_fifo_path was
repurposed as stream_socket_path, but a single socket carries both
streams so there is no separate audio path to publish; reserved_path2
stays reserved.

Spell out the convention where the field is defined, so a future reader
does not remove or reorder it (which would shift every later field for
out-of-tree shm readers) and knows the slot is free to reuse at the same
64-byte width. Align the PHP Monitor object and ZoneMinder::Memory notes.

refs #5143

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T4UcdJLt1bxwdpcigGxZRD
2026-09-19 23:03:14 +00:00
Claude 89837a6b40 fix: start the monitor stream socket before capture connects
Address monitor-side stream socket review findings:

- zmc starts the stream socket before the first connect attempt, and
  SendStreamHealthEvent records the health state even when the socket is
  not up yet, so connection/prime faults during startup are observable to
  a consumer instead of being lost until the first successful prime.
- PrimeCapture announces audio whenever the camera has a decodable audio
  stream (Capture forwards audio packets unconditionally), and clears a
  previously announced stream when a re-prime no longer sees it.
- Publish the media stream socket path in the monitor shared-memory
  block (reusing the retired video_fifo_path field as stream_socket_path,
  same offset and size) so consumers discover it without hard-coding the
  convention or reading the producer's zm.conf; the PHP Monitor object
  and the ZoneMinder::Memory Perl module expose the renamed field.
- Move the wall-clock microseconds helper out of zm_monitor.cpp into
  zm_time.h as SystemClockMicros(), where time helpers belong.

refs #5143

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T4UcdJLt1bxwdpcigGxZRD
2026-09-19 23:00:14 +00:00