Commit Graph
162 Commits
Author SHA1 Message Date
Jash 8b8c0c8b64 fix: read hexadecimal int options from config files and ignore an empty LOG_FILE refs #6439 2026-11-16 16:30:45 +05:30
Isaac Connor 4810e25903 Merge pull request #5068 from AJ0070/fix/4242-dts-log-spam
fix: rate limit the non increasing dts warning
2026-11-15 23:28:43 -05:00
Isaac Connor 03e2b49d12 Merge pull request #5644 from AJ0070/fatal-db-hang
fix: stop a hung database from blocking Fatal and Panic from exiting
2026-11-15 10:51:05 -05:00
Isaac Connor 3e0f801749 Merge pull request #5520 from AJ0070/5519-logger-fast-path
perf: keep the log level check inline when a statement is not logged
2026-11-15 10:34:33 -05:00
Jash 6dcef45fb6 fix: stop a hung database from blocking Fatal and Panic from exiting fixes #5643 2026-11-15 10:47:45 +05:30
Jash 70d43e103d refactor: build the dts warning rate limit into the logger instead of a separate class, refs #4242 2026-11-15 03:52:52 +05:30
Jash a049f8fd66 fix: cap queued database log rows so a log flood can't grow memory without bound fixes #5674 2026-11-13 13:06:26 +05:30
Jash 12aad4741c perf: keep the log level check inline when a statement is not logged fixes #5519 2026-11-11 12:12:26 +05:30
Isaac ConnorandClaude Opus 5.5 894c0a5189 fix: keep the crash report signal-safe across rotation, threads and syslog refs #5215
Review follow-ups to the async-signal-safe die handler:

- The log file descriptor the handler wrote to could be closed by a log
  rotation after the handler loaded it, and its number reused by an
  unrelated file or socket. zmSetCrashLogFile() now keeps one descriptor
  that is never closed and dup2()s each new log file onto it, so it only
  ever refers to a log file.
- Lines were formatted with snprintf(), which is not async-signal-safe. A
  small fixed-buffer CrashLine appends strings, decimals and hex instead.
- glibc backtrace() loads libgcc_s on first use, which allocates. It is now
  called once when the handler is installed, and the comment that called it
  safe is corrected.
- zmdc points daemons' stderr at /dev/null, so with file logging off the
  report went nowhere. The handler now also sends each line to syslog over
  its own datagram socket, connected by zmSetCrashSyslog() when the Logger
  opens syslog, without calling syslog(3).
- A second signal arriving during the report was blocked when re-raised, so
  the process exited 255 instead of dying of it. Both paths now go through
  die_of(), which unblocks the signal.
- The shared volatile flag did not stop two threads that fault together from
  both reporting. A lock-free atomic_flag picks the reporting thread; a fault
  on another thread waits for it to end the process, and a fault inside the
  handler on the same thread dies at once.
- sigaltstack() only covers the calling thread. zmSetThreadAltStack() gives
  a thread its own stack, freed when it exits; main, the decoder and the
  analysis threads call it.

Tests fork a child per case: report formatting, the rotated log file, the
syslog datagram, a second signal mid-report, a fault on another thread
mid-report, and a stack overflow on a worker thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 23:29:29 -05:00
Isaac ConnorandClaude Opus 4.8 d071d9948a fix: make the crash signal handler async-signal-safe fixes #5215
zm_die_handler logged through Error()/Fatal() and, on the second signal,
called Fatal() -> logPrint(), which from inside the handler stopped the
database queue, closed the MySQL handle, deleted the Logger and called
exit(): it joined and freed objects the decoder, analysis and stream
threads were still using, ran atexit handlers and static destructors (the
libcrypto/MariaDB signal-unsafe-call floods seen under ThreadSanitizer),
and could deadlock on the log mutex. The crash report it wrote to the Logs
table was sometimes cut short or lost, and the process could hang instead
of exiting.

Emit the crash report (signal, fault reason, fault and instruction
address, backtrace) with async-signal-safe write(2) only, to stderr and,
when open, the per-process log file, then restore the default disposition
and re-raise the signal so the process dies of the actual fault and can
leave a core dump. Nothing touches the database, the log queue or the
Logger from the handler.

- The Logger publishes its log-file descriptor in zm_crash_log_fd when it
  opens the file and clears it on close, so the handler can write to the
  log file without going through the Logger.
- The glibc path uses backtrace_symbols_fd(), which does not allocate,
  instead of backtrace_symbols(); the libunwind path writes fixed buffers.
- Install the handler on a dedicated sigaltstack so a stack-overflow fault
  can still be reported, and guard against faulting again while handling.

The crash detail now lands in the log file and syslog rather than the Logs
table; zmdc restarts the daemon and records the abnormal exit.

tests/zm_signal.cpp forks a child, installs the handler, raises SIGSEGV
and checks the process dies of the signal rather than exiting from the
handler, and that the report reached stderr and the published log fd.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-08 17:57:05 -05:00
Isaac Connor a7b8d3a075 Merge pull request #5208 from ZoneMinder/db-log-pause-queue-only
fix: keep only the database queue thread out of database logging
2026-10-13 18:18:58 -04:00
Isaac Connor 6e06dc31ab Merge pull request #5203 from nabbi/fix/b52-logger-reload
fix-medium: re-initialise the logger in place on reload instead of deleting it
2026-10-13 18:18:15 -04:00
Nic BoetandClaude Opus 5.5 9705654593 docs: name the threads logReload() keeps the logger for
The comment still said zmDbDo() holds the Logger pointer across its
query, which #5197 removed; the test comment was updated in 6d3e86994.
Comment only, no behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 20:37:57 -05:00
Nic BoetandClaude Opus 5.5 367e19d4f6 fix: apply SIGUSR1/SIGUSR2 log level changes outside the signal handler
Logger::usrHandler changed the level and called Info() from the handler.
Info() takes log_mutex, glibc's syslog and tzset locks (syslog,
localtime_r) and the database queue's mutex, and allocates. A SIGUSR1 or
SIGUSR2 delivered to a thread already inside one of those waits on
itself, and the process hangs until zmwatch/zmdc kill it.

The handler now only adds +1/-1 to a lock-free atomic, as the SIGWINCH
branch already sets a flag. Logger::fetch(), which every log macro calls
before its level check, applies a pending change under log_mutex and logs
"Level changed" from normal context, so the new level is in effect at the
next log call on any thread. Several signals before that add up to one
change, clamped to NOLOG..DEBUG9. logInit() drops a change still pending
for the logger it replaces.

fixes #5216

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 10:34:23 -05:00
Isaac ConnorandClaude Opus 5.5 4bc4c6e4e0 fix: pause database logging only around the queue's inserts into Logs
Holding a DatabaseLogPause on the dbQueue thread for its whole life kept the
errors of every queued write out of Logs too: Monitor_Status updates, Events,
Frames and Stats rows. Under lock contention most "Giving up on query" errors
were only in the log files.

Mark each queued row with whether the logger queued it, and pause database
logging only around those inserts into Logs and the backlog warning. The loop
stays closed: a line about a queued write queues one Logs insert, which logs
nothing to the database.

Test: an error from a queued write reaches Logs.

From review by @nabbi on #5208.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 22:12:11 -04:00
nicandClaude Opus 5.5 378b774c12 fix: stop dropping other threads' database log lines during queries (#5197)
* test: cover lines logged to the database while a query runs

Live-database tests ([notCI][dblive]) for how the logger and zmDbDo
interact:

- a line logged on one thread while another thread is inside zmDbDo
  reaches the Logs table
- zmDbDo's own debug lines stay out of Logs when the database level is
  debug, so inserting a Logs row cannot log another one without end
- a dbQueue backlog over 40 rows does not deadlock threads that log

The first fails on master: zmDbDo sets the process-wide database log
level to NOLOG for the whole query, so the line is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: stop dropping other threads' database log lines during queries

zmDbDo lowered the logger's database level to NOLOG for as long as its
query ran, so that its own lines (and, at a debug database level, the line
about every insert into Logs) could not queue more inserts into Logs. The
level is shared by the whole process, so every line any other thread
logged in that window never reached the Logs table or the web log view,
while the log file and syslog still had it. The save and restore of that
shared level from several threads is also a data race: a thread can
restore a stale NOLOG and leave database logging off.

Replace the toggle with Logger::DatabaseLogPause, a thread_local count
that keeps only the current thread's lines out of the database. zmDbDo
and the queue's backlog warning use it; mDatabaseLevel is no longer
written outside of initialise().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: warn about the database queue backlog outside the queue's lock

zmDbQueue::process logged its "db queue size has grown larger" warning
while holding the queue mutex. logPrint holds the logger's mutex while it
pushes a Logs row, which takes the queue mutex. With more than 40 rows
waiting, a thread logging to the database and the queue thread could each
hold one of the two locks and wait for the other, stopping every thread
that logs.

Take the backlog size under the lock and warn after releasing it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 10:52:18 -04:00
Nic BoetandClaude Opus 5.5 c1856bb2b3 fix: re-initialise the logger in place on zmc's reload instead of deleting it
zmc's SIGHUP reload ran logTerm(); logInit(), which deletes the Logger
and creates a new one. The dbQueue thread and the stream socket threads
keep running through the reload, and zmDbDo() holds the Logger pointer
across its query to restore the database log level afterwards, so the
reload freed the object under them (heap use-after-free under ASan).

Add logReload(), which re-initialises the existing instance under
log_mutex: syslog is closed and reopened and the log file closed, as with
a new instance, but the pointer stays valid. Only the reload calls it;
logInit() and logTerm() are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:27:40 -05:00
Isaac Connor 88591b4168 fix: let SIGUSR1 raise logging to debug without ZM_LOG_DEBUG
With ZM_LOG_DEBUG off, Logger::initialise() clamped every target level
(file, database, syslog, terminal) to INFO as well as the overall level.
SIGUSR1 raises the overall level, but the effective level is the lower of
that and the highest target level, so it stayed at INFO and the signal
did nothing.

Only cap the overall level. Targets keep their configured levels, so
SIGUSR1 behaves as if ZM_LOG_DEBUG_LEVEL had been incremented: targets
configured for debug start receiving it, targets at INFO stay at INFO.
Startup behaviour is unchanged since the effective level is still INFO.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
(cherry picked from commit af970628c3fe5fe76d163a30747cf534babbb8a6)
2026-10-10 09:08:19 -04:00
Isaac ConnorandClaude Opus 5 bde61e7af6 fix: rotate logs on SIGWINCH instead of SIGHUP fixes #5063
SIGHUP means reload. zmc responds by closing its events, disconnecting the
camera and reconnecting; the perl daemons respond by exiting so zmdc restarts
them. zmdc.pl logrot hupped every managed process, so the nightly logrotate
run cost about 8 seconds of capture on a default install.

Rotating a log file only needs the daemon to drop its file handle, so use a
separate signal for it. SIGWINCH is otherwise unused, is ignored by default and
exists on every supported platform.

- Logger (C++) installs a SIGWINCH handler beside its USR1/USR2 handler. The
  handler only sets a flag; the next logPrint closes the file and the write
  reopens it at the original path. This covers every C++ binary without
  touching any daemon's main loop.
- Logger.pm registers WINCH alongside HUP in logSetSignal, which logInit
  already calls, so the scripts that install their own HUP handler still
  rotate.
- zmdc.pl logrot sends WINCH. The logrotate config is unchanged - it still
  calls zmpkg.pl logrot.

Filter.pm and FilterTerm.php justified MAX_EVENT_DAYS by events not outliving
the nightly HUP, which is no longer what bounds them; cite SectionLength.

Tests: tests/zm_logger_rotate.cpp and tests/perl/test_log_rotate_signal.pl both
log, rename the file out from under the process, confirm writes still land in
the renamed file, signal WINCH and confirm the original path is written again.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NDhTBPj9xEaT52pRmAufaP
2026-08-22 15:30:46 -04:00
Isaac ConnorandClaude Opus 4.6 e6ace6fcf4 feat: add AUDIT logging level for tracking administrative changes
Add a new AUDIT logging level (-5) between PANIC (-4) and NOLOG (shifted
to -6) across C++, PHP, and Perl loggers. AUDIT entries use code 'AUD'
and syslog priority LOG_NOTICE. They record who changed what, from where,
for monitors, filters, users, config, roles, groups, zones, states,
servers, storage, events, snapshots, control caps, and login/logout.

AUDIT entries have their own retention period (ZM_LOG_AUDIT_DATABASE_LIMIT,
default 1 year) separate from regular log pruning. The log pruning in
zmstats.pl and zmaudit.pl now excludes AUDIT rows from regular pruning
and prunes them independently.

Critical safety: the C++ termination logic is changed from
'if (level <= FATAL)' to 'if (level == FATAL || level == PANIC)' to
prevent AUDIT-level log calls from killing the process.

Includes db migration zm_update-1.39.1.sql to shift any stored NOLOG
config values from -5 to -6.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 18:19:20 -05:00
Isaac Connor 94a33b2716 Merge pull request #4518 from ZoneMinder/copilot/fix-time-t-format-specifier
Fix time_t format specifiers for ILP32 platforms with 64-bit time_t
2026-01-05 18:30:08 -05:00
Isaac Connor 4a121dcdb4 Fix hang on Fatal 2026-01-05 16:37:50 -05:00
copilot-swe-agent[bot]andSteveGilvarry 2c2047c343 Replace C-style casts with C++ static_cast for intmax_t
Co-authored-by: SteveGilvarry <7613276+SteveGilvarry@users.noreply.github.com>
2026-01-05 13:36:16 +00:00
copilot-swe-agent[bot]andSteveGilvarry 89e0a4918c Fix %ld format specifiers for time_t on ILP32 platforms
Co-authored-by: SteveGilvarry <7613276+SteveGilvarry@users.noreply.github.com>
2026-01-05 10:36:23 +00:00
Isaac Connor 4f3bad3e75 Add Options for TERM log out 2025-02-25 14:31:19 -05:00
Isaac Connor 4af6e6eee0 Do not output anything to stdout when logging is happening when the db is closed. 2024-09-23 11:43:55 -04:00
Aaron Kling c4683d90a9 Format code using astyle google format
Commands used:
astyle --style=google --indent=spaces=2 --keep-one-line-blocks src/*.cpp
astyle --style=google --indent=spaces=2 --keep-one-line-blocks src/*.h
2024-03-26 13:43:58 -05:00
Alejandro Criado-Pérez 543683aa4c Corrections on cpp and h files 2023-08-13 01:27:19 +02:00
Isaac Connor 35c55a79e0 Use correct format, fix build warnings 2022-08-26 09:54:05 -04:00
Isaac Connor fa39983b69 Merge branch 'master' into add_mqtt 2022-08-25 18:41:59 -04:00
Isaac Connor 29750a56e7 Merge branch 'master' into add_mqtt 2022-08-25 18:37:54 -04:00
Doug Nazar 8c37846c6c Check result of snprintf for errors and truncation. 2022-07-31 16:38:23 -04:00
Doug Nazar 3b69a51ff8 Try to fix warning again that printf might exceed buffer.
The last fix worked on GCC 11 & 12 but broke GCC 8.
2022-07-22 12:00:42 -04:00
Doug Nazar 0db4a18ff6 Switch to unsigned int for loop to restrict size of printf.
GCC 12 incorrectly detects a format truncation.

src/zm_logger.cpp:86:39: warning: ‘%d’ directive output may be truncated writing between 1 and 11 bytes into a region of size 2 [-Wformat-truncation=]
   86 |       snprintf(code, sizeof(code), "DB%d", i);
      |                                       ^~
src/zm_logger.cpp:86:36: note: directive argument in the range [-2147483647, 9]
   86 |       snprintf(code, sizeof(code), "DB%d", i);
      |                                    ^~~~~~
2022-07-16 03:21:25 -04:00
Isaac Connor 64e930e7f4 Print out mLogFile.size as well hopefully to figure out why it tries to open an empty file 2022-03-21 16:12:49 -04:00
Isaac Connor 133553e630 Revert "Merge pull request #3119 from Carbenium/fmt"
This reverts commit 90d930c7c3, reversing
changes made to 0bcb9d276f.
2022-02-27 14:05:14 -05:00
Isaac Connor a2ae63cefe Merge branch 'master' into fmt 2021-11-16 15:10:45 -05:00
Isaac Connor 883772295d spacing and log the new log level string as well as number 2021-11-11 13:51:17 -05:00
Isaac Connor b0cf3a4732 Merge pull request #3314 from Carbenium/path-max
Fix Wformat for stringtf and convert path buffers depending on PATH_MAX to std::string
2021-07-07 11:34:03 -04:00
Peter Keresztes Schmidt eaf2e51b0c utils: Make sure the compiler can emit format warnings for stringtf
Unfortunately the compilers can't emit Wformat warnings for variadic templates
and those can't be annotated with the format attribute.
Use a variadic function which can be annotated and thus warns on format string-args mismatches.

Ref 0796a2262e
2021-07-06 10:33:17 +02:00
Peter Keresztes Schmidt cf9c47149f db: Add helper for escaping strings and use it 2021-07-06 10:20:45 +02:00
Peter Keresztes Schmidt b0b2f5fc16 Logger: Convert internals to std::chrono 2021-06-08 19:45:23 +02:00
Peter Keresztes Schmidt e881e97c06 Logger: Fix DB log messages not being populated
We need to `resize` the buffer string since `reserve` does not guarantee that the buffer is
actually available.

Follow-up on 298415fff3
2021-05-22 10:52:57 +02:00
Peter Keresztes Schmidt 298415fff3 Remove remaining usages of VLAs 2021-05-17 22:12:04 +02:00
Isaac Connor 8f27db5d6f Do not stop dbQueue in logTerm. dbQueue is not just for logging. 2021-05-04 14:22:02 -04:00
Isaac Connor 59b1927ad6 do dbQUeue.stop in logTerm so we don't have to have an extra line in every executable 2021-05-01 14:49:33 -04:00
Peter Keresztes Schmidt c3dd8d8a47 Logger: Annotate logPrint with format attribute
This allows the compiler to check for mismatches in the format string and the passed parameters.
2021-04-29 17:12:44 +02:00
Isaac Connor c0c5c07ecf Quiet cppcheck issues 2021-04-20 12:59:59 -04:00
Peter Keresztes Schmidt e330f8553d utils: cleanup Split and Join 2021-04-04 00:30:18 +02:00
Peter Keresztes Schmidt 4e8c7d1f7c Eliminate non-thread-safe calls to localtime
localtime uses an internal static storage to which a pointer is given as return value.
Due to this it is not safe to call localtime from multiple threads since the same static storage is used.

Use localtime_r instead which allows to pass in a tm struct.

Fixes:
https://github.com/ZoneMinder/zoneminder/security/code-scanning/24
https://github.com/ZoneMinder/zoneminder/security/code-scanning/25
https://github.com/ZoneMinder/zoneminder/security/code-scanning/26
https://github.com/ZoneMinder/zoneminder/security/code-scanning/27
https://github.com/ZoneMinder/zoneminder/security/code-scanning/28
https://github.com/ZoneMinder/zoneminder/security/code-scanning/30
https://github.com/ZoneMinder/zoneminder/security/code-scanning/31
https://github.com/ZoneMinder/zoneminder/security/code-scanning/33
https://github.com/ZoneMinder/zoneminder/security/code-scanning/58
https://github.com/ZoneMinder/zoneminder/security/code-scanning/59
https://github.com/ZoneMinder/zoneminder/security/code-scanning/63
https://github.com/ZoneMinder/zoneminder/security/code-scanning/64
https://github.com/ZoneMinder/zoneminder/security/code-scanning/65
2021-03-21 21:42:02 +01:00