zmc drops the Options field when av_dict_parse_string() fails, so the
camera runs without them. Raise the message from Warning to Error and say
that options are key=value pairs, not command line flags.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When camera->Capture() failed, Monitor::Capture() painted a frame of the
signal check colour into the shared image ring and moved
last_write_index, while the decoder thread could still be writing the
same ring. Capture picked its slot from image_count and the decoder from
last_write_index + 1, so the two could write one slot, giving a viewer a
torn frame, or move last_write_index backwards.
With a decoder thread running, the failure path now only sets
signal = false and leaves the ring to the decoder. Viewers keep its last
frame until the reconnect. That frame was short-lived anyway: zmc closes
the monitor and reconnects straight after the failure, and connect()
clears the ring. The decoder still runs CheckSignal on every decoded
frame, so a capture card's no-signal colour is still detected. With
decoding off nothing else writes the ring, so the signal colour frame is
still written there.
The test drives Capture() with a camera that always fails: with a
decoder the ring, last_write_index and image_count are unchanged;
without one the frame goes into image_count's slot as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zmc's capture, decoder and analysis threads, zms, zmu and the web
interface read and write Monitor::SharedData while the others run, but
its scalar fields were plain members. ThreadSanitizer reported races on
capture_fps, state and analysing, and the action word was worse: zmu
sets bits with |= while zmc clears others with &=, and as plain
read-modify-writes either side could write back a word read before the
other's change and drop its bit.
Wrap every scalar SharedData field in SharedValue<T>, which holds only
the value and does each access as a relaxed __atomic builtin (C++17 has
no std::atomic_ref). Loads and stores keep their meaning, |=, &= and ++
become single atomic operations, and copying one field to another is
deleted because it would not be atomic. The layout Memory.pm and
Monitor.php read is unchanged: the 8-byte fields are aligned to 8 so
clang on i386 doesn't call libatomic, and they already sat on 8-byte
offsets. Values passed through printf-style varargs now call load(),
which -Wformat found. MonitorLink's SharedData pointer drops volatile,
which the atomics replace.
The test checks every field offset against Monitor.php, that the
wrapper reads and writes the plain value, and that setting and clearing
action bits from two threads loses none (plain fields lost 3 to 33 of
200000 rounds here).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A Remote monitor on the HTTP protocol logs every request it sends to the
camera at debug level 2: with a user and password that includes
"Authorization: Basic <base64 of user:password>", and the path's query
string, which for many cameras carries user= and pwd=. When the camera
asks for Digest, Authenticator::computeDigestResponse() logged
"<user>:<realm>:<password>" in clear and the HA1 hash, which is all a
client needs to answer that realm's challenges.
Add request_for_log(), which passes the request target through
url_for_log() and replaces the value of Authorization and
Proxy-Authorization headers, and log the requests through it. Drop the
two Digest lines that held the password and HA1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When nph-zms cannot authenticate a request it logs a Warning with the
request's REQUEST_URI and HTTP_REFERER. The URI carries the credentials
the client sent: pass=/password= in clear (the plain relay, or any
client that streams with user and password), the full auth= hash, whose
first 8 characters the same line is careful to truncate, or a token=
JWT. Warnings reach the Logs table at the default database log level,
where every user with System=View can read them, and a JWT or an auth
hash still valid from another address or until its TTL lets the reader
stream, or use the API, as that user.
Log the uri and referer through url_for_log(), which drops the query
string, and add the monitor and event ids, which the query string was
the only place to find.
The same file's debug lines logged the whole environment (QUERY_STRING,
REQUEST_URI, HTTP_REFERER, the session cookie), the query string, the
JWT and the password at level 1. Log the environment without those
values (URLs through url_for_log()), drop the query string line, which
the "zms request" line already summarises, log the JWT as a fingerprint
(zm::crypto::LogFingerprint()), and say only that a password was given.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
remove_authentication() and mask_authentication() ended the userinfo at
the first '@' of the URL. ffmpeg and cameras split the authority at its
last '@', so a camera password with an unencoded '@' works, and
everything after its first '@' was left in the "masked" path that zmc
logs, at Error level when the camera cannot be opened (the Logs table
at default settings). An '@' in the path or query was also taken for
userinfo.
End the userinfo at the last '@' before the path, query or fragment.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The go2rtc, Janus and RTSP2Web managers logged the stream URLs and the
request bodies they send: camera user:password@, the RTSP restream's
?auth= hash, ZM_JANUS_SECRET and the Janus stream pin. The Janus line
with ZM_JANUS_SECRET is a Warning, so it reaches the Logs table at the
default database log level whenever Janus is unreachable.
Log URLs through a new url_for_log() (no credentials, no query string),
the pin as a fingerprint, and the request bodies not at all.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The previous commit stopped zmLoadAuthUser() logging the presented auth
hash, which also took away the only way to tell which hash a failed
attempt carried. Log "fp:" plus the first 8 hex digits of the hash's
SHA-256 instead: enough to match a zms or zm_rtsp_server line with the
web side's (ZM\logFingerprint() gives the same tag) or with a client's
own copy, and of no use for replaying or recovering the hash.
Adds SHA-256 to zm::crypto for both the OpenSSL and the GnuTLS backend.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zmLoadAuthUser() logged, at debug level 1, the auth_key it builds for each
candidate user and hour. That string starts with ZM_AUTH_HASH_SECRET, the
key that also signs JWT access tokens, followed by the username and the
stored password hash. User::getAuthHash() logged the same string, and the
presented ?auth= hash was logged as well. verifyPassword() logged the stored
and computed MySQL-style SHA1 password hashes.
Any daemon that checks an ?auth= hash (zms, zm_rtsp_server) with debug
enabled wrote these to its log file, and to the Logs table when database
logging is at Debug.
Log the username being checked instead, and drop the hash values.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The RTSP server authenticator wrote the request URL, its query string and
the username and password it checks to the debug log at level 1. A client
authenticating with ?username=&password= left its password in clear in
zm_rtsp_server.log, and in the Logs table when database logging is at
Debug; ?auth= hashes and ?token= JWTs were logged the same way.
Log the URL without its query string, drop the query string line, and log
only the username when checking a password.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Passthrough recording keeps every packet back to a video keyframe. When
the camera's keyframe interval is longer than MaxImageBufferCount,
queuePacket() has no later keyframe to trim to, so the packet queue holds
the whole GOP whatever MaxImageBufferCount says. #5359 bounds the decoded
copies in that case, which keeps memory down, but the queue still isn't
working as configured and nothing said so specifically: the existing
"queue is full" Warning also covers analysis falling behind.
Log an Error naming MaxImageBufferCount and the fix (raise it above the
keyframe interval, or shorten the camera's GOP) as soon as a GOP passes
the limit with keep_keyframes on. Report it once; setMaxVideoPackets(),
setKeepKeyframes() (a RELOAD) and clear() reset it.
setKeepKeyframes() now takes the queue mutex, like the other setters.
refs #5358
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When Decode() flushes the codec because decoder_queue is full (#5363),
the next packet it sent was usually not a keyframe. The flushed codec has
no reference frames to decode it against, so until the next keyframe it
returned errors or smeared pictures, which motion detection can score as
an alarm.
After the flush, hold packets back from the codec until a keyframe, as
the KEYFRAMES decoding modes already do. The held packets take the
existing path for packets that are not decoded, so last_write_time keeps
moving and zmwatch does not restart zmc.
refs #5362
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Decode() flushes the codec once decoder_queue holds more than 2 x the
keyframe interval while the codec still wants input (#5363). The codec
legitimately holds frames back before returning one: has_b_frames for
reordering, and one per extra thread with frame threading. For an
all-intra stream (keyframe interval 1, so a limit of 2) decoded with a
raised thread_count that delay alone passes the limit, and the codec was
flushed every few frames with a Warning each time.
Add the delay to the limit in DecoderQueueLimit().
refs #5362
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ajax/stream.php sends stream commands (query, pause, seek, zoom, quit)
to the zms whose unix socket matches a connkey, with no permission
check. Connkeys are six random digits chosen when the stream starts,
so any logged-in user who guessed or saw one could read the status of
another user's stream, of a monitor they may not view included, and
pause or end it. A second zms started with the same connkey also waited
on the first one's lock and then took over its socket.
zms already authenticates the user and checks their access to the
monitor or event before it streams. Keep that user's id and put it in
the lock, command socket and reply socket names
(zms-<connkey>-<user id>s.sock); stream.php builds the names from the
caller's own id through zmsSocketPath(), so a request reaches only the
caller's streams. Without authentication the id is 0 on both sides.
Adds a StreamBase test in tests/zm_stream.cpp and
tests/php/test_zms_socket_path.php, which pin the same names. The
existing command-socket-teardown test is updated for the owner-suffixed
names (it postdates the reporter's base commit).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The packet guard was commented out, so a packet skipped because it
belongs to another stream (audio in an event video) stayed referenced
when the next av_read_frame() reset it, which leaks it before FFmpeg 7.
avcodec_send_packet() takes its own reference, so unreferencing after
it is safe.
refs #4860fixes#5371
Capture() returned early for packets of streams it doesn't use and for
pts/dts jumps before arming av_packet_guard. Before FFmpeg 7,
av_read_frame() resets the packet it is given without unreferencing it,
so each of those packets leaked. A camera that sends a track ZoneMinder
doesn't use (a second audio track, ONVIF metadata) leaked every packet
of it.
refs #4860
The throttle in Decode() returned before sending once decoder_queue held
more than 2 x the keyframe interval. It is only reached after
receive_frame() returned EAGAIN, so the codec was waiting for exactly the
input the throttle held back: no frame ever came, last_write_time froze
and zmwatch restarted zmc 45-55 s later. Flush the codec and release the
queued packets (as on decoder thread exit) and carry on with the next
packet; a Warning says it happened.
refs #4860fixes#5362
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The codec can consume packets without returning a frame for them; H.264
does after lost or corrupt slices (RTSP over UDP). Decode() paired each
frame with the oldest decoder_queue entry, so those entries stayed queued
for good: every later frame went to an older packet, and once the queue
passed 2 x the keyframe interval the throttle stopped sending while the
codec waited for input, so decoding stopped until zmwatch restarted zmc.
Match the frame to the entry with its pts and release the entries before
it with an earlier pts (decoded, no image), as the flush paths do. A frame
older than every entry is dropped; without a usable pts the oldest entry
is used, as before.
refs #4860
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
that already exist -- lights on, lights off, play a sound -- at set times.
MonitorActions already says what to do and to which device, with triggers for
EventStart, Alarm, Manual and so on. So this adds a trigger rather than a
subsystem: an action whose TriggerOn is 'Schedule' carries a five field cron
spec, and cron runs it.
Cron, rather than a daemon of our own, because the web user owns a crontab it
can rewrite without privilege, and because the line cron runs,
30 22 * * * /usr/bin/zmcontrol.pl --id 24 --command=lightOff
is the same invocation web/includes/Monitor.php already falls back to when no
zmcontrol daemon is listening. A scheduled action therefore takes the path a
manual one does rather than a parallel one of its own. It also means no new
code runs as root, nothing new has to be supervised, and the feature is a
table column plus a crontab block.
Nothing a form can set reaches a shell. The schedule is refused unless
cronScheduleIsValid() accepts it -- five fields, numbers and the usual
*/,-/ only, with newline, carriage return and % rejected outright because
each would end the line or the command. The command itself comes from
MonitorAction::commandFor()'s fixed list and the ids are integers, so the
whole line is assembled from constrained parts. That is a narrower surface
than Filters.AutoExecuteCmd, which has taken an arbitrary command for years.
The crontab is not ours to own, so ZoneMinder rewrites only a block between
two markers and leaves every other line byte for byte. A block whose end
marker is missing, which is what an interrupted write leaves, is treated as
no block at all rather than swallowing everything after it: losing our own
stale block is the safe failure, losing the admin's entries is not. The block
is rebuilt from the table on every save, so the crontab is a projection of
the database rather than a second place to keep the truth.
zmc recognises the new trigger and skips it, so having one does not warn on
every reload, and nothing fires a scheduled action from the capture process.
An action targeting a monitor on another server is left out and logged: cron
runs zmcontrol.pl locally, and the web ui's proxy through the API has no cron
equivalent. Single server installs are unaffected.
The two pieces that can lose data or run the wrong thing are pure, and
tests/php/test_crontab.php covers them: schedule validation including the
injection cases, and splicing a block in, out and over without disturbing the
lines around it.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A camera that keeps rebooting repeatedly fails avformat_find_stream_info
or reports a video stream with no width/height. Log both at a level
adjusted by the monitor's Importance so Less/Not important monitors
stop flooding the logs with errors and warnings.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With passthrough recording the packet queue keeps every packet back to a
video keyframe. When the camera's keyframe interval is longer than
MaxImageBufferCount, queuePacket() finds no later keyframe to trim to, so
the queue holds the whole GOP and releaseDecoded() keeps the decoded frame
and image of each packet back to that keyframe: about 7.4 MB per 5MP
frame, 2 GB and more per monitor.
releaseDecoded() now also frees the decoded data of all but the newest
MaxImageBufferCount video packets, never inside the pre-event window and
only behind every iterator. The compressed packets stay, so an event
still starts on the keyframe and records all of its video; it writes no
capture JPEGs for the frames that lost their image.
fixes#5358
Monitor::Decode scales the Y-channel image when the camera's resolution
differs from the monitor's. That image is get_y_image()'s zero-copy wrap of
the decoder's Y plane, whose stride is the decoder's linesize[0], not the
FFALIGN(width,32) that Scale assumed when it handed the buffer to
SWScale::Convert at align 32. Each row was read from the wrong offset, so
the scaled analysis image, and the alarm pixels drawn from it, came out
sheared.
Set up the source and destination frames in Scale, override plane 0's
stride with the Image's linesize as Rotate and Flip already do, and convert
through SWScale::Convert(AVFrame*, AVFrame*). The output layout is
unchanged (align 32).
tests/zm_image_linesize.cpp: scale a 40 wide GRAY8 plane with a 48 byte
stride and check that every output row is still flat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-DWITH_OPENSSL -DWITH_DOM were only appended to CMAKE_CXX_FLAGS, but
smdevp.c, mecevp.c and logging.c are compiled as C. Without WITH_OPENSSL,
stdsoap2.h does not include <openssl/rand.h>, so mecevp.c calls RAND_bytes
with no declaration. -Wno-implicit-function-declaration hid this until
ubuntu-latest moved to 26.04 (GCC 15), where the CodeQL autobuild fails
with "implicit declaration of function 'RAND_bytes'".
Append the same defines to CMAKE_C_FLAGS and drop the
-Wno-implicit-function-declaration workaround from mecevp.c.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The command socket stayed bound until ~StreamBase(), which runs only after
the stream thread has finished. A zms that was shutting down but still busy
in the stream thread (blocked writing to a client that had gone away, for
instance) kept accepting commands it would never read. web/ajax/stream.php
then waited out its whole MSG_TIMEOUT on each one and logged "Timed out
waiting for msg ... after waiting 5000 milliseconds", where a missing socket
would have been reported as no_socket at once.
Call closeComms() when checkCommandQueue() leaves its loop. sd is only used
from the command thread, and closeComms() clears sd and lock_fd, so the
destructor's later call does nothing and cannot remove a socket bound by a
successor zms on the same connkey.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zmu -a always recorded "Forced Web" as the event's cause. --cause <text>
sets it instead; without it, or with an empty value, the cause stays
"Forced Web". ForceAlarmOn keeps the first 31 bytes, as for zmtrigger.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Add a helper to add or update Go2RTC URL parameters without overwriting existing options or appending duplicate parameters.
- Allow enabling or disabling RTSP backchannel handling for cameras, including both primary and secondary stream paths.
The DeviceClass=Camera backchannel handling appended "#backchannel=0"
unconditionally. A url that already carried a go2rtc option fragment,
e.g. a user-set "#backchannel=0" or "#media="/"#video=", then became
"...#backchannel=0#backchannel=0", which go2rtc rejects.
Only append when the path has no "#" fragment yet, deciding the primary
and secondary paths independently.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
AVCodecID values are renumbered between FFmpeg major versions (HEVC is
173 in libavcodec 61 and 172 in libavcodec 63, where 173 is fic), so a
consumer linked against a different FFmpeg than zmc misidentifies the
codec. Add HELLO TLV 0x0B with avcodec_get_name(), keep sending the
numeric id for older consumers, and have ParseHello resolve the id from
the name whenever this FFmpeg knows it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Authenticator::authHandleHeader() splits each comma-separated directive of a
Digest challenge on "=" and then reads kvPair[0] and kvPair[1] without checking
how many parts Split() returned. A directive with no "=" (or an empty one)
yields a vector with fewer than two elements, so kvPair[1] -- and, for an empty
subpart, kvPair[0] -- reads past the end of the vector.
The header is taken from a camera's 401 response. For an HTTP source
(RemoteCameraHttp) that response is processed before any authentication, so a
malicious or spoofed server can send a crafted WWW-Authenticate line and crash
the capture daemon (an unauthenticated denial of service).
Skip any directive that is not a key=value pair instead of indexing past the
end.
Addresses GHSA-r8cq-jgx6-gr5p.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
VideoStore created and destroyed a VAAPI hardware device context for every
event, opening /dev/dri/renderD128 on open and closing it on close. On some
VAAPI drivers the teardown did not actually close the render-node fd, so a
continuously recording monitor leaked one fd per event (one per section, about
every ten minutes for the reporter). After ~1024 fds the process hit its
open-file limit and VideoStore could no longer open, falling back to jpegs.
Cache the device context on the Monitor and hand VideoStore a borrowed
reference through Monitor::GetEncoderHWDeviceContext(). The render node is now
opened once for the monitor's lifetime and reused by every event, so there is
no per-event device teardown to leak, and encoder setup is cheaper. The
contexts are released in ~Monitor once no VideoStore can be borrowing them.
The cache keys one context per (hwdevice type, device) and never evicts,
because the auto encoder list interleaves VAAPI and QSV: a single cached slot
would be dropped when a failed probe of the other type ran between two probes
of the type actually used, recreating the device every event and preserving
the leak. Keying per type keeps each device for the monitor's life regardless
of probe order.
setup_hwaccel() now reuses a device context the caller supplies and only
creates its own when none is given, so the decoder path and the fallback (when
the monitor cannot provide one) are unchanged.
Validated with a standalone reproduction against VAAPI (ffmpeg 9, Intel iHD):
creating and freeing a device per iteration keeps the renderD128 fd count flat
on this driver, while the shared-device model holds it at one for the lifetime
regardless. A Catch2 test is not added because it requires a GPU and CI runs
with the test suite disabled.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The latch was released in Analyse() at the isAlarmed() sample, before the
packet was committed. Two paths then spent a momentary DetectedSound pulse
without recording it:
- A video packet not yet decoded makes Analyse() return at the decode gate
before packet->score is set, and the same packet is retried. The sample --
and the release -- ran on every retry, so the pulse was gone by the time the
packet was decoded and scored, and the event recorded no alarm frame. This is
why raising AlarmFrameCount or the earlier hold did not help: the retries of
one undecoded packet consumed the latch.
- An audio packet (these cameras alarm on AudioAnalytics/DetectedSound, so audio
packets are present) could sample and release the latch, but alarm_frames
counts video frames, so the pulse was again recorded on no counted frame.
Defer the release to the point where a video packet is committed with its
score, so the latch is spent only on a frame the event actually writes.
Also keep the topic/value of the last activation and report it from
SetNoteSet() when the alarms map has already been cleared, so a momentary
pulse's event note still names the cause (e.g. AudioAnalytics/Audio/
DetectedSound/true) instead of a bare "ONVIF".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
In the ENCODE path of VideoStore::open(), attempt_open_encoders() looked up
each candidate with avcodec_find_encoder_by_name() but never checked the
result. When the named encoder is absent from the installed ffmpeg -- common
for a hardware encoder on a box that lacks it -- the lookup returns null,
avcodec_alloc_context3(null) still yields a context, and avcodec_open2() later
fails, so the error branch dereferenced video_out_codec->name and zmc crashed
in Event::Run() -> VideoStore::open().
Skip a candidate whose encoder is null, mirroring the guard the transcode path
already has. If every candidate is missing, video_out_codec stays null and the
existing passthrough fallback takes over, so the event still records.
Verified with g++ -fsyntax-only against the generated headers; a focused unit
test is impractical here as the path needs a live ffmpeg encoder context.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The ONVIF alarm was a plain atomic bool that the poll thread set and the
analysis thread sampled once per frame. A momentary alarm -- a DetectedSound
pulse the camera reports active then inactive between two analysis frames --
was raised and cleared on the raw level before any frame sampled it, so the
recorded event had no alarm frames. A motion alarm stays active for seconds
and so was always sampled, which is why MotionAlarm never showed the problem.
Replace the bool with an AlarmLatch: raise() marks the level active and that
an activation is waiting to be seen, clear() drops the level, and the analysis
thread calls observeAlarm() once it has sampled the alarm. isAlarmed() stays
true from a raise until the level is down and the activation has been observed,
so a pulse is reported on at least one frame however short it was. A
still-active alarm is unaffected. The latch is released only on a frame that
scored, so a pulse arriving just after the isAlarmed() check is kept for the
next frame rather than lost.
The activation guards in WaitForMessage() now test the raw level (alarm_.active())
instead of isAlarmed(), so a new topic still raises the level while an earlier
pulse's latch is still pending.
Add Catch2 coverage for AlarmLatch (tests/zm_onvif_alarm_latch.cpp), testable
without a gSOAP context like the other ONVIF free-function tests.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>