Files
zoneminder/tests/zm_utils.cpp
T
fec0999425 feat: ONVIF event notes and tags from what the camera detected (#7712)
* feat: name what an ONVIF camera detected in the event note refs #7688

The ONVIF event note was the raw topic plus the value of the first Data
SimpleItem, e.g. "tns1:RuleEngine/MyRuleDetector/PeopleDetect/true".
parse_event_message() dropped every other item, the item names and the
Source Rule, so cameras that name the detection in an item (Tapo
IsPeople=true under a generic TPSmartEvent topic) or in a value (Ajax
ClassTypes="Human Vehicle") produced notes that did not say what was
detected.

parse_event_message() now also returns every Data SimpleItem and the
Source Rule, and ONVIFEventNote() builds the note from them with rules
that hold across vendors rather than a per-camera list:

- strip the namespace prefix of every topic segment (tns1:, tnsajax:)
- drop a leading RuleEngine/, the root of every analytics topic
- leave out items that are empty or inactive, by the same words
  interpret_alarm_value() uses for the alarm state, and per-object ids,
  which would otherwise add a note per object as notes only accumulate
- leave out the value of items that say active, and State/LogicalState
  items that say active
- add the Rule in parentheses when the camera names one

  Reolink  MyRuleDetector/PeopleDetect
  Tapo     TPSmartEventDetector/TPSmartEvent IsPeople (MyTPSmartEventDetectorRule)
  Ajax     ObjectDetection/Object ClassTypes=Human Vehicle (AjaxObjectRule)

The word lists that drive this sit together, so a camera with other
vocabulary is handled by extending them. The inactive words move from
interpret_alarm_value() into that shared list unchanged. A value found
outside the Data SimpleItems (ElementItem, fallback search) still goes in
the note, and a topic that reduces to nothing is used as it is.

Alarm on/off decisions, the value they use, ONVIF_Alarm_Text matching and
the alarms map keys are unchanged; a test pins interpret_alarm_value() to
its previous results. parse_event_message() and interpret_alarm_value()
are now static, as they use no member state, so they can be tested.

Notes change format: filters matching the old text (e.g. Notes LIKE
"tns1:RuleEngine" or "/true") need updating.

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

* fix: link existing tags to events and stop logging new ones as errors refs #7688

Event::AddPacket_ tagged events from object detections, but when the tag
name was already in Tags it neither linked it to the event nor cached it,
and leaked the Tag that Tag::find returned. Only a tag name created for the
first time was ever linked, so detections of person, car, ... after the
first never reached Events_Tags.

Move the tagging into Event::AddTag, which finds or creates the tag, links
it once per event and caches it. A mutex guards the cache so the analysis
thread can tag the event too. Event_Tag::save uses INSERT IGNORE so a link
another writer made first (zm_detect via pyzm) is not an error, and
Tag::find returns nullptr without logging two errors when the name is not
there yet, which is how callers learn a tag is new.

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

* feat: tag events with the objects an ONVIF camera reports refs #7688

Add a per-monitor "Tag Events From ONVIF" checkbox (Monitors.ONVIF_Event_Tags,
off by default). When set, events raised by the ONVIF event listener are
tagged with what the camera detected, through the existing Tags and
Events_Tags tables.

ONVIFEventTags() reads the object from wherever the camera puts it, using
the items parse_event_message() already collects for the note: the topic
(Reolink PeopleDetect), an active item name without its "Is" (Tapo
IsPeople) or the classes in an item value (Ajax ClassTypes="Human
Vehicle"). Camera names map to the names object detection uses, so one tag
means one thing: person, vehicle, animal, package, face, and doorbell for
a Visitor press. An alarm that names no object (motion, tamper, line
crossing, an unknown detector) is tagged with its last topic segment, e.g.
MotionAlarm. The names are a table next to the note vocabulary; items are
judged by the same helper the note uses (inactive, per-object id, generic
state).

Each alarm entry keeps its tags beside its note, SetTagSet() returns them
as SetNoteSet() returns notes, including for a pulse that has already
cleared, and Monitor::Analyse() hands them to Event::AddTag().

Schema: zm_update-1.39.55.sql adds the column, zm_create.sql.in matches,
version 1.39.55. Web: checkbox and help text next to ONVIF Event Listener,
unticked default for the save action. Perl: Monitor field list.

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

* feat: map camera object names to AI object classes for ONVIF tags refs #7688

ONVIF event tags were mapped from a word list compiled into zmc, so a
camera using another word for an object needed a code change. Move the
mapping into the database, on the object classes ZM already has.

- Add AI_Object_Classes.Aliases, a comma separated list of what cameras
  call the class, editable in Options, AI Classes.
- Seed aliases on the COCO person class and add a Camera dataset for
  the objects COCO has no class for: vehicle, animal, package, face and
  doorbell. Aliases already set are kept when the migration reruns.
- zmc loads the class names and aliases when the ONVIF listener starts
  on a monitor with ONVIF_Event_Tags set. A class name maps to itself,
  so a camera reporting Car is tagged car, as object detection would.
- Without the classes (an older database) alarms are tagged with their
  topic, as for an alarm that names no object.

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

* fix: address review of the ONVIF event tags refs #7688

- Event::AddTag tries each name once per event, so a tag that can't be
  saved is not looked up and logged on every frame, and cuts names to
  the 64 characters of Tags.Name. It no longer holds tags_mutex_ over
  the database work, and the Events_Tags row goes through dbQueue, so
  the analysis thread waits on at most the tag lookup.
- Tag::save returns the existing Id when another process created the
  same tag first, instead of failing on the unique Name.
- Event_Tag::save ignores only the duplicate key, not other errors.
- An ONVIF message whose first state item is inactive and a later one
  active (Tapo IsVehicle=false, IsPeople=true) raises the alarm.
- The Is prefix of an item name is matched in any case.
- load_tag_names leaves the error to zmDbFetch, which has logged it.
- The help text says to restart the monitor after changing aliases.
- Re-indent two lines in ProcessPullResponse.

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

* feat: restart ONVIF tagging monitors when an AI class changes refs #7688

zmc reads the object class names and aliases when it starts listening
for ONVIF events, so an alias saved in Options, AI Classes did nothing
until the monitor was restarted by hand. Saving or deleting a class now
restarts the zmc of each monitor with ONVIF_Event_Listener and
ONVIF_Event_Tags set, as saving zones does for their monitor.

Add the Aliases label to en_gb so it can be translated like the other
strings, and say in the help text that saving restarts those monitors.

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

* fix: address Copilot review of the ONVIF event tags refs #7688

- Only a later alarm-state item (IsX, State, Alarm, ...) overrides an
  inactive first one. A later ObjectId or Count describes the object,
  so IsInside=false followed by ObjectId=3 stays an alarm-off.
- 1 is true for a flag item such as IsPeople, as it already was for
  State, so IsPeople=1 is tagged person rather than the topic.
- Cut tag names at 64 UTF-8 characters, the size of Tags.Name, without
  splitting a character, using a new Utf8Truncate helper.

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

* feat: leave ONVIF detections out of the note when they are tagged refs #7688

With ONVIF_Event_Tags on, the tags already say what the camera
detected, and name the topic when no object is named, so the note
repeated them: "Motion: MyRuleDetector/PeopleDetect, ONVIF" next to a
person tag. Such a monitor's note now just says ONVIF. With tags off
the note still names the detection.

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

* feat: edit AI class aliases as tags refs #7688

A plain text field gave no hint that aliases are a comma list. Edit
them like an event's tags instead, with the same tag styles: each alias
is a removable tag, and Enter, space or comma adds the one typed. They
are still saved as the comma list zmc reads, so nothing else changes.

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

* fix: split ONVIF class values on commas and drop the DogCat alias refs #7688

A camera listing its classes as ClassTypes="Human,Vehicle" was tagged
with neither, as values were split on spaces only. Split on commas too.

Drop DogCat from the animal aliases: no camera is known to send it,
Reolink sends DogCatDetect. Say in the seed where the starter aliases
come from, which of them have been seen from a camera, and that more
are added in Options, AI Classes.

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

* feat: give a new AI class the next free index and refuse a taken one refs #7688

A class's index is the number its dataset's model gives it, which a
dataset with no model behind it (Camera) has no use for, yet the form
required one and took any number, so a second class could get 0.

Leave the index empty on a new class to get the next one in its
dataset, and refuse an index another class of the dataset already has,
naming that class.

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

* fix: number the placeholders of ClassIndexInUse so translations can reorder them refs #7688

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

* refactor: source the camera class seed from the 1.39.55 migration refs #7688

The migration carried a copy of db/camera_classes.sql, so the starter
aliases lived in two places. Make it a .sql.in that sources the seed
file, as zm_update-1.39.26.sql.in does with triggers.sql, so fresh
installs and upgrades share one copy. Note in the seed that it must
keep working on a 1.39.55 database.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Isaac Connor <isaac@zoneminder.com>
2026-11-27 21:11:06 -05:00

725 lines
26 KiB
C++

/*
* This file is part of the ZoneMinder Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "zm_catch2.h"
#include "zm_utils.h"
#include <sstream>
TEST_CASE("Trim") {
REQUIRE(Trim("", "") == "");
REQUIRE(Trim("test", "") == "test");
REQUIRE(Trim(" ", "") == " ");
REQUIRE(Trim("\"test", "\"") == "test");
REQUIRE(Trim("test\"", "\"") == "test");
REQUIRE(Trim("\"test\"", "\"") == "test");
REQUIRE(Trim("te\"st", "\"") == "te\"st");
REQUIRE(Trim("\"te\"st\"", "\"") == "te\"st");
}
TEST_CASE("Utf8Truncate") {
REQUIRE(Utf8Truncate("", 2) == "");
REQUIRE(Utf8Truncate("abc", 3) == "abc");
REQUIRE(Utf8Truncate("abcd", 3) == "abc");
REQUIRE(Utf8Truncate("abc", 0) == "");
// \xc3\xa9 is one character (e acute), \xe4\xba\xba another (person)
REQUIRE(Utf8Truncate("\xc3\xa9\xc3\xa9\xc3\xa9", 2) == "\xc3\xa9\xc3\xa9");
REQUIRE(Utf8Truncate("a\xe4\xba\xba", 2) == "a\xe4\xba\xba");
REQUIRE(Utf8Truncate("a\xe4\xba\xba" "b", 2) == "a\xe4\xba\xba");
}
TEST_CASE("TrimSpaces") {
REQUIRE(TrimSpaces(" ") == "");
REQUIRE(TrimSpaces("test") == "test");
REQUIRE(TrimSpaces(" test ") == "test");
REQUIRE(TrimSpaces(" test ") == "test");
REQUIRE(TrimSpaces(" test ") == "test");
REQUIRE(TrimSpaces(" test") == "test");
REQUIRE(TrimSpaces("\ttest") == "test");
REQUIRE(TrimSpaces("test\t") == "test");
REQUIRE(TrimSpaces("\ttest\t") == "test");
REQUIRE(TrimSpaces(" test\t") == "test");
REQUIRE(TrimSpaces("\ttest ") == "test");
REQUIRE(TrimSpaces("\t test \t") == "test");
REQUIRE(TrimSpaces("\t te st \t") == "te st");
}
TEST_CASE("ReplaceAll") {
REQUIRE(ReplaceAll("", "", "") == "");
REQUIRE(ReplaceAll("a", "", "b") == "a");
REQUIRE(ReplaceAll("a", "a", "b") == "b");
REQUIRE(ReplaceAll("a", "b", "c") == "a");
REQUIRE(ReplaceAll("aa", "a", "b") == "bb");
REQUIRE(ReplaceAll("aba", "a", "c") == "cbc");
REQUIRE(ReplaceAll("aTOKENa", "TOKEN", "VAL") == "aVALa");
REQUIRE(ReplaceAll("aTOKENaTOKEN", "TOKEN", "VAL") == "aVALaVAL");
}
TEST_CASE("StartsWith") {
REQUIRE(StartsWith("", "") == true);
REQUIRE(StartsWith("test", "test") == true);
REQUIRE(StartsWith("test=abc", "test") == true);
REQUIRE(StartsWith(" test=abc", "test") == false);
}
TEST_CASE("Split (char delimiter)") {
std::vector<std::string> items = Split("", ' ');
REQUIRE(items == std::vector<std::string>{""});
items = Split("abc def ghi", ' ');
REQUIRE(items == std::vector<std::string>{"abc", "def", "ghi"});
items = Split("abc,def,,ghi", ',');
REQUIRE(items == std::vector<std::string>{"abc", "def", "", "ghi"});
}
TEST_CASE("Split (string delimiter)") {
std::vector<std::string> items;
items = Split("", "");
REQUIRE(items == std::vector<std::string>{""});
items = Split("", " ");
REQUIRE(items == std::vector<std::string>{""});
items = Split("", " \t");
REQUIRE(items == std::vector<std::string>{""});
items = Split("", " \t");
REQUIRE(items == std::vector<std::string>{""});
items = Split(" ", " ");
REQUIRE(items.size() == 0);
items = Split(" ", " ");
REQUIRE(items.size() == 0);
items = Split(" ", " \t");
REQUIRE(items.size() == 0);
items = Split("a b", "");
REQUIRE(items == std::vector<std::string>{"a b"});
items = Split("a b", " ");
REQUIRE(items == std::vector<std::string>{"a", "b"});
items = Split("a \tb", " \t");
REQUIRE(items == std::vector<std::string>{"a", "b"});
items = Split(" a \tb ", " \t");
REQUIRE(items == std::vector<std::string>{"a", "b"});
items = Split(" a=b ", "=");
REQUIRE(items == std::vector<std::string>{" a", "b "});
items = Split(" a=b ", " =");
REQUIRE(items == std::vector<std::string>{"a", "b"});
items = Split("a b c", " ", 2);
REQUIRE(items == std::vector<std::string>{"a", "b c"});
// A monitor's Options field is a textarea, so an entry may be on its own
// line rather than after a comma, and runs of separators (a blank line, or
// crlf) must not become empty entries. Split() is no longer the reader of
// that field, but this is the contract kOptionSeparators is chosen for.
items = Split("--rate=1\n--no-audio", kOptionSeparators);
REQUIRE(items == std::vector<std::string>{"--rate=1", "--no-audio"});
items = Split("--rate=1,--no-audio", kOptionSeparators);
REQUIRE(items == std::vector<std::string>{"--rate=1", "--no-audio"});
items = Split("--rate=1\r\n\r\n--no-audio\n", kOptionSeparators);
REQUIRE(items == std::vector<std::string>{"--rate=1", "--no-audio"});
}
TEST_CASE("Join") {
REQUIRE(Join({}, "") == "");
REQUIRE(Join({}, " ") == "");
REQUIRE(Join({""}, "") == "");
REQUIRE(Join({"a"}, "") == "a");
REQUIRE(Join({"a"}, ",") == "a");
REQUIRE(Join({"a", "b"}, ",") == "a,b");
REQUIRE(Join({"a", "b"}, "") == "ab");
}
TEST_CASE("ByteArrayToHexString") {
std::vector<uint8> bytes;
REQUIRE(ByteArrayToHexString(bytes) == "");
bytes = {0x00};
REQUIRE(ByteArrayToHexString(bytes) == "00");
bytes = {0x00, 0x01, 0x02, 0xff};
REQUIRE(ByteArrayToHexString(bytes) == "000102ff");
}
TEST_CASE("Base64Encode") {
REQUIRE(Base64Encode("") == "");
REQUIRE(Base64Encode("f") == "Zg==");
REQUIRE(Base64Encode("fo") == "Zm8=");
REQUIRE(Base64Encode("foo") == "Zm9v");
REQUIRE(Base64Encode("foob") == "Zm9vYg==");
REQUIRE(Base64Encode("fooba") == "Zm9vYmE=");
REQUIRE(Base64Encode("foobar") == "Zm9vYmFy");
REQUIRE(Base64Encode("\xc3\xa9") == "w6k=");
REQUIRE(Base64Encode("\xff\xfe\xfd") == "//79");
}
TEST_CASE("ZM::clamp") {
REQUIRE(zm::clamp(1, 0, 2) == 1);
REQUIRE(zm::clamp(3, 0, 2) == 2);
REQUIRE(zm::clamp(-1, 0, 2) == 0);
}
TEST_CASE("UriDecode") {
REQUIRE(UriDecode("abcABC123-_.~%21%28%29%26%3d%20") == "abcABC123-_.~!()&= ");
REQUIRE(UriDecode("abcABC123-_.~%21%28%29%26%3d+") == "abcABC123-_.~!()&= ");
}
TEST_CASE("UriEncode") {
// Basic alphanumeric and safe characters should not be encoded
REQUIRE(UriEncode("abcABC123") == "abcABC123");
REQUIRE(UriEncode("-_.~") == "-_.~");
// Space should be encoded as %20
REQUIRE(UriEncode(" ") == "%20");
REQUIRE(UriEncode("hello world") == "hello%20world");
REQUIRE(UriEncode("a b c") == "a%20b%20c");
// Special characters should be percent-encoded
REQUIRE(UriEncode("!") == "%21");
REQUIRE(UriEncode("&") == "%26");
REQUIRE(UriEncode("=") == "%3D");
REQUIRE(UriEncode("?") == "%3F");
// Empty string
REQUIRE(UriEncode("") == "");
// Round-trip test: encode then decode should return original
std::string original = "hello world!";
REQUIRE(UriDecode(UriEncode(original)) == original);
// Non-ASCII bytes must each be escaped as a single %XX pair. A signed char
// sign-extends here and yields "%FF" (truncated from "FFFFFFD0") instead.
REQUIRE(UriEncode("\xD0\xB2") == "%D0%B2");
REQUIRE(UriEncode("\xFF") == "%FF");
REQUIRE(UriEncode("\x80") == "%80");
// A Cyrillic name (U+0432 U+0445 U+043E U+0434) - the kind of name the
// utf8mb4 switch made storable. Written as bytes so this file stays ASCII.
REQUIRE(UriEncode("\xD0\xB2\xD1\x85\xD0\xBE\xD0\xB4") == "%D0%B2%D1%85%D0%BE%D0%B4");
// Mixed ASCII and UTF-8, and a multi-byte round trip.
REQUIRE(UriEncode("Cam \xC3\xA9") == "Cam%20%C3%A9");
REQUIRE(UriDecode(UriEncode("\xD0\xB2\xD1\x85")) == "\xD0\xB2\xD1\x85");
}
TEST_CASE("escape_json_string") {
// Nothing to do.
REQUIRE(escape_json_string("") == "");
REQUIRE(escape_json_string("Front Door") == "Front Door");
// A quote must come out as one backslash then a quote. The previous
// implementation escaped quotes before backslashes, so it emitted \\" here:
// an escaped backslash followed by a bare quote, which closed the JSON
// string it was embedded in.
REQUIRE(escape_json_string("\"") == "\\\"");
REQUIRE(escape_json_string("Front \"Door\"") == "Front \\\"Door\\\"");
// A backslash doubles, and that doubling must not itself be re-doubled.
REQUIRE(escape_json_string("\\") == "\\\\");
REQUIRE(escape_json_string("back\\slash") == "back\\\\slash");
// A backslash adjacent to a quote is where ordering errors surface.
REQUIRE(escape_json_string("\\\"") == "\\\\\\\"");
// Named control character escapes.
REQUIRE(escape_json_string("\n") == "\\n");
REQUIRE(escape_json_string("\r") == "\\r");
REQUIRE(escape_json_string("\t") == "\\t");
REQUIRE(escape_json_string("\b") == "\\b");
REQUIRE(escape_json_string("\f") == "\\f");
REQUIRE(escape_json_string("line\nbreak") == "line\\nbreak");
// Control characters without a short form must still be escaped.
REQUIRE(escape_json_string(std::string(1, '\a')) == "\\u0007");
REQUIRE(escape_json_string(std::string(1, '\x01')) == "\\u0001");
REQUIRE(escape_json_string(std::string(1, '\x1f')) == "\\u001f");
// An embedded NUL is a control character like any other and must survive.
REQUIRE(escape_json_string(std::string("a\0b", 3)) == "a\\u0000b");
// 0x7f is not a JSON control character, and UTF-8 passes through intact.
REQUIRE(escape_json_string(std::string(1, '\x7f')) == std::string(1, '\x7f'));
REQUIRE(escape_json_string("\xD0\xB2\xD1\x85") == "\xD0\xB2\xD1\x85");
// Escaping twice is not the same as escaping once. This is the double
// escape the go2rtc credential path was hitting.
const std::string once = escape_json_string("pa\\ss");
REQUIRE(once == "pa\\\\ss");
REQUIRE(escape_json_string(once) == "pa\\\\\\\\ss");
}
TEST_CASE("QueryString") {
SECTION("no value") {
std::stringstream str("name1=");
QueryString qs(str);
REQUIRE(qs.size() == 1);
REQUIRE(qs.has("name1") == true);
const QueryParameter *p = qs.get("name1");
REQUIRE(p != nullptr);
REQUIRE(p->name() == "name1");
REQUIRE(p->size() == 0);
}
SECTION("no value and ampersand") {
std::stringstream str("name1=&");
QueryString qs(str);
REQUIRE(qs.size() == 1);
REQUIRE(qs.has("name1") == true);
const QueryParameter *p = qs.get("name1");
REQUIRE(p != nullptr);
REQUIRE(p->name() == "name1");
REQUIRE(p->size() == 0);
}
SECTION("one parameter, one value") {
std::stringstream str("name1=value1");
QueryString qs(str);
REQUIRE(qs.size() == 1);
REQUIRE(qs.has("name1") == true);
const QueryParameter *p = qs.get("name1");
REQUIRE(p != nullptr);
REQUIRE(p->name() == "name1");
REQUIRE(p->size() == 1);
REQUIRE(p->values()[0] == "value1");
}
SECTION("one parameter, multiple values") {
std::stringstream str("name1=value1&name1=value2");
QueryString qs(str);
REQUIRE(qs.size() == 1);
REQUIRE(qs.has("name1") == true);
const QueryParameter *p = qs.get("name1");
REQUIRE(p != nullptr);
REQUIRE(p->name() == "name1");
REQUIRE(p->size() == 2);
REQUIRE(p->values()[0] == "value1");
REQUIRE(p->values()[1] == "value2");
}
SECTION("multiple parameters, multiple values") {
std::stringstream str("name1=value1&name2=value2");
QueryString qs(str);
REQUIRE(qs.size() == 2);
REQUIRE(qs.has("name1") == true);
REQUIRE(qs.has("name2") == true);
const QueryParameter *p1 = qs.get("name1");
REQUIRE(p1 != nullptr);
REQUIRE(p1->name() == "name1");
REQUIRE(p1->size() == 1);
REQUIRE(p1->values()[0] == "value1");
const QueryParameter *p2 = qs.get("name2");
REQUIRE(p2 != nullptr);
REQUIRE(p2->name() == "name2");
REQUIRE(p2->size() == 1);
REQUIRE(p2->values()[0] == "value2");
}
}
TEST_CASE("mask_authentication") {
SECTION("no authentication") {
std::string url("http://192.168.1.1");
std::string result = mask_authentication(url);
REQUIRE(url == result);
}
SECTION("has username no password has scheme") {
std::string url("http://username@192.168.1.1");
std::string result = mask_authentication(url);
REQUIRE(result == "http://********@192.168.1.1");
}
SECTION("has username no password no scheme") {
std::string url("username@192.168.1.1");
std::string result = mask_authentication(url);
REQUIRE(result == "********@192.168.1.1");
}
SECTION("has username has password no scheme") {
std::string url("username:password@192.168.1.1");
std::string result = mask_authentication(url);
REQUIRE(result == "********:********@192.168.1.1");
}
SECTION("has username has password has scheme") {
std::string url("http://username:password@192.168.1.1");
std::string result = mask_authentication(url);
REQUIRE(result == "http://********:********@192.168.1.1");
}
}
TEST_CASE("remove_authentication") {
SECTION("no authentication") {
std::string url("http://192.168.1.1");
std::string result = remove_authentication(url);
REQUIRE(url == result);
}
SECTION("has username no password has scheme") {
std::string url("http://username@192.168.1.1");
std::string result = remove_authentication(url);
REQUIRE(result == "http://192.168.1.1");
}
SECTION("has username no password no scheme") {
std::string url("username@192.168.1.1");
std::string result = remove_authentication(url);
REQUIRE(result == "192.168.1.1");
}
SECTION("has username has password no scheme") {
std::string url("username:password@192.168.1.1");
std::string result = remove_authentication(url);
REQUIRE(result == "192.168.1.1");
}
SECTION("has username has password has scheme") {
std::string url("http://username:password@192.168.1.1");
std::string result = remove_authentication(url);
REQUIRE(result == "http://192.168.1.1");
}
}
TEST_CASE("zm_strncpy") {
char buf[8];
SECTION("fits, null-terminated") {
zm_strncpy(buf, "abc", sizeof(buf));
REQUIRE(std::string(buf) == "abc");
}
SECTION("oversize truncated to size-1 and terminated") {
zm_strncpy(buf, "abcdefghijkl", sizeof(buf));
REQUIRE(std::string(buf) == "abcdefg"); // 7 chars + '\0'
REQUIRE(buf[7] == '\0');
}
SECTION("delimiter length n limits copy") {
zm_strncpy(buf, "abcdef", sizeof(buf), 3); // src not null-terminated at field end
REQUIRE(std::string(buf) == "abc");
}
SECTION("delimiter length also capped to buffer") {
zm_strncpy(buf, "abcdefghij", sizeof(buf), 20);
REQUIRE(std::string(buf) == "abcdefg");
REQUIRE(buf[7] == '\0');
}
SECTION("empty source") {
zm_strncpy(buf, "", sizeof(buf));
REQUIRE(buf[0] == '\0');
}
}
TEST_CASE("TimevalToString") {
// tv_usec used to go to the format string as %ld. Under glibc's 64 bit time
// ABI on a 32 bit platform (Debian trixie on armhf) tv_usec is
// __suseconds64_t while long is still 32 bits, so %ld consumed half the
// argument and every vararg after it was read from the wrong offset. zmc
// crashed on armhf because this result is written into a buffer and then
// used. See #4580 and Debian bug 1120447.
//
// amd64 cannot reproduce the mismatch (long is already 64 bits), so what
// this pins is the rendering: six zero padded digits of microseconds, which
// is what a wrong conversion would disturb.
const char *tz = getenv("TZ");
std::string saved_tz = tz ? tz : "";
setenv("TZ", "UTC", 1);
tzset();
SECTION("pads microseconds to six digits") {
REQUIRE(TimevalToString(timeval{0, 0}) == "1970-01-01 00:00:00.000000");
REQUIRE(TimevalToString(timeval{0, 1}) == "1970-01-01 00:00:00.000001");
REQUIRE(TimevalToString(timeval{0, 999999}) == "1970-01-01 00:00:00.999999");
}
SECTION("does not truncate or reorder the arguments") {
// A conversion that mis-reads tv_usec tends to show up either as a wrong
// number here or as the seconds field being wrong, since the bad read
// shifts everything after it.
REQUIRE(TimevalToString(timeval{1700000000, 123456}) == "2023-11-14 22:13:20.123456");
}
if (saved_tz.empty()) {
unsetenv("TZ");
} else {
setenv("TZ", saved_tz.c_str(), 1);
}
tzset();
}
TEST_CASE("ClientAddress") {
SECTION("X-Forwarded-For is ignored unless the peer is a trusted proxy") {
REQUIRE(ClientAddress("203.0.113.9", "192.168.1.55", "") == "203.0.113.9");
REQUIRE(ClientAddress("203.0.113.9", "192.168.1.55", "10.0.0.1") == "203.0.113.9");
REQUIRE(ClientAddress("", "192.168.1.55", "").empty());
}
SECTION("a trusted proxy's X-Forwarded-For is used") {
REQUIRE(ClientAddress("10.0.0.1", "192.168.1.55", "10.0.0.1") == "192.168.1.55");
REQUIRE(ClientAddress("10.0.0.1", "", "10.0.0.1") == "10.0.0.1");
REQUIRE(ClientAddress("10.0.0.1", " , ", "10.0.0.1") == "10.0.0.1");
}
SECTION("the right-most untrusted hop wins, not a spoofed left-most one") {
REQUIRE(ClientAddress("10.0.0.1", "1.2.3.4, 192.168.1.55", "10.0.0.1") == "192.168.1.55");
REQUIRE(ClientAddress("10.0.0.1", "1.2.3.4, 192.168.1.55 , 10.0.0.9 ", "10.0.0.1, 10.0.0.9")
== "192.168.1.55");
REQUIRE(ClientAddress("10.0.0.1", "1.2.3.4, 192.168.1.55, 10.0.0.9", "10.0.0.1 10.0.0.9")
== "192.168.1.55");
}
SECTION("when every hop is trusted the left-most is the origin") {
REQUIRE(ClientAddress("10.0.0.1", "10.0.0.9, 10.0.0.1", "10.0.0.1,10.0.0.9") == "10.0.0.9");
}
}
// ZM_GO2RTC_PATH is the go2rtc API base. Its API lives under /api, but the
// natural thing to enter is the server address, so either form is accepted.
TEST_CASE("Go2RTCApiEndpoint", "[utils]") {
REQUIRE(Go2RTCApiEndpoint("http://localhost:1984") == "http://localhost:1984/api");
REQUIRE(Go2RTCApiEndpoint("http://localhost:1984/") == "http://localhost:1984/api");
REQUIRE(Go2RTCApiEndpoint("http://localhost:1984/api") == "http://localhost:1984/api");
REQUIRE(Go2RTCApiEndpoint("http://localhost:1984/api/") == "http://localhost:1984/api");
REQUIRE(Go2RTCApiEndpoint("https://host/go2rtc") == "https://host/go2rtc/api");
REQUIRE(Go2RTCApiEndpoint("https://host/go2rtc/api") == "https://host/go2rtc/api");
REQUIRE(Go2RTCApiEndpoint("http://user:pass@cam:1984") == "http://user:pass@cam:1984/api");
REQUIRE(Go2RTCApiEndpoint("") == "");
}
TEST_CASE("authentication with a raw @ in the password") {
// ffmpeg splits the authority at its last '@', so such a password works;
// all of it must be removed, not just the part before the first '@'.
SECTION("remove_authentication") {
REQUIRE(remove_authentication("rtsp://admin:p@ss@192.168.1.1:554/s") == "rtsp://192.168.1.1:554/s");
REQUIRE(remove_authentication("admin:p@ss@192.168.1.1") == "192.168.1.1");
}
SECTION("mask_authentication") {
std::string masked = mask_authentication("rtsp://admin:p@ss@192.168.1.1:554/s");
REQUIRE(masked.find("ss") == std::string::npos);
REQUIRE(masked.find("@192.168.1.1:554/s") != std::string::npos);
}
SECTION("url_for_log") {
REQUIRE(url_for_log("rtsp://admin:p@ss@192.168.1.1/s?x=1") == "rtsp://192.168.1.1/s?...");
}
SECTION("an @ in the path or query is not userinfo") {
REQUIRE(remove_authentication("http://192.168.1.1/a@b") == "http://192.168.1.1/a@b");
REQUIRE(remove_authentication("http://192.168.1.1/x?mail=a@b") == "http://192.168.1.1/x?mail=a@b");
REQUIRE(mask_authentication("http://192.168.1.1/x?mail=a@b") == "http://192.168.1.1/x?mail=a@b");
}
}
TEST_CASE("request_for_log") {
SECTION("Basic credentials and the query string are removed") {
std::string req = "GET /snap.cgi?user=admin&pwd=CamPw1 HTTP/1.0\r\n"
"User-Agent: ZoneMinder\r\n"
"Host: 192.168.1.10\r\n"
"Authorization: Basic YWRtaW46Q2FtUHcx\r\n\r\n";
REQUIRE(request_for_log(req) == "GET /snap.cgi?... HTTP/1.0\r\n"
"User-Agent: ZoneMinder\r\n"
"Host: 192.168.1.10\r\n"
"Authorization: <not logged>\r\n\r\n");
}
SECTION("a Digest header and an RTSP request with userinfo") {
std::string req = "DESCRIBE rtsp://u:pw@10.0.0.2:554/s RTSP/1.0\r\n"
"CSeq: 2\r\n"
"authorization: Digest username=\"u\", response=\"0123abcd\"\r\n\r\n";
std::string out = request_for_log(req);
REQUIRE(out == "DESCRIBE rtsp://10.0.0.2:554/s RTSP/1.0\r\nCSeq: 2\r\nauthorization: <not logged>\r\n\r\n");
}
SECTION("a request without credentials is unchanged") {
std::string req = "GET /video.mjpg HTTP/1.1\r\nHost: cam\r\n\r\n";
REQUIRE(request_for_log(req) == req);
REQUIRE(request_for_log("") == "");
}
}
TEST_CASE("options_for_log") {
SECTION("a headers value is removed") {
REQUIRE(options_for_log("headers=Authorization: Basic dXNlcjpwYXNz") == "headers=<not logged>");
}
SECTION("the separators around a removed value are kept") {
REQUIRE(options_for_log("tls_verify=0,headers=Authorization: Bearer abc,timeout=5")
== "tls_verify=0,headers=<not logged>,timeout=5");
}
SECTION("a newline separated options string") {
REQUIRE(options_for_log("cookies=sid=abc\ntimeout=5000000")
== "cookies=<not logged>\ntimeout=5000000");
}
SECTION("a proxy url carrying credentials is removed") {
REQUIRE(options_for_log("http_proxy=http://u:p@host:3128") == "http_proxy=<not logged>");
}
SECTION("a command-line style authorization value without '=' is removed") {
REQUIRE(options_for_log("-headers Authorization: Basic xyz") == "<not logged>");
}
SECTION("options without credentials are unchanged") {
std::string opts = "tls_verify=0,rw_timeout=5000000";
REQUIRE(options_for_log(opts) == opts);
}
SECTION("the empty string") {
REQUIRE(options_for_log("") == "");
}
}
TEST_CASE("url_for_log") {
SECTION("plain url is unchanged") {
REQUIRE(url_for_log("rtsp://127.0.0.1:8554/cam") == "rtsp://127.0.0.1:8554/cam");
}
SECTION("credentials are removed") {
REQUIRE(url_for_log("rtsp://admin:secret@192.168.1.1/stream") == "rtsp://192.168.1.1/stream");
}
SECTION("the query string is removed") {
REQUIRE(url_for_log("rtsp://127.0.0.1:8554/cam?auth=0123456789abcdef") == "rtsp://127.0.0.1:8554/cam?...");
REQUIRE(url_for_log("rtsp://127.0.0.1:8554/cam?username=u&password=p") == "rtsp://127.0.0.1:8554/cam?...");
}
SECTION("a streaming server API endpoint (go2rtc, Janus, RTSP2Web)") {
REQUIRE(url_for_log("http://admin:pa!ss@10.0.0.2:1984/api/streams?src=29")
== "http://10.0.0.2:1984/api/streams?...");
REQUIRE(url_for_log("http://admin:pa!ss@10.0.0.2:1984/api/streams?name=29&src=rtsp%3A%2F%2Fu%3Apw%4010.0.0.3")
== "http://10.0.0.2:1984/api/streams?...");
// The default go2rtc endpoint has no scheme.
REQUIRE(url_for_log("demo:demo@127.0.0.1:1984/streams?src=1") == "127.0.0.1:1984/streams?...");
}
SECTION("an @ in the query does not cut the host") {
REQUIRE(url_for_log("http://host/x?token=a@b") == "http://host/x?...");
}
SECTION("a request URI without scheme or host (zms REQUEST_URI)") {
REQUIRE(url_for_log("/zm/cgi-bin/nph-zms?mode=single&monitor=1&user=u&pass=p")
== "/zm/cgi-bin/nph-zms?...");
REQUIRE(url_for_log("/zm/cgi-bin/nph-zms?monitor=1&auth=0123456789abcdef&user=a@b")
== "/zm/cgi-bin/nph-zms?...");
REQUIRE(url_for_log("/zm/cgi-bin/nph-zms") == "/zm/cgi-bin/nph-zms");
}
SECTION("both") {
std::string out = url_for_log("rtsp://u:pw@10.0.0.2/s?token=eyJabc");
REQUIRE(out == "rtsp://10.0.0.2/s?...");
REQUIRE(out.find("pw") == std::string::npos);
REQUIRE(out.find("eyJ") == std::string::npos);
}
}
TEST_CASE("zm_parse_leb128", "[utils]") {
uint32_t value;
size_t n;
SECTION("single byte") {
static const unsigned char data[] = {0x05};
n = zm_parse_leb128(data, sizeof(data), value);
REQUIRE(n == 1);
REQUIRE(value == 5);
}
SECTION("two bytes, 128") {
static const unsigned char data[] = {0x80, 0x01};
n = zm_parse_leb128(data, sizeof(data), value);
REQUIRE(n == 2);
REQUIRE(value == 128);
}
SECTION("max 5-byte 32-bit value") {
static const unsigned char data[] = {0xFF, 0xFF, 0xFF, 0xFF, 0x0F};
n = zm_parse_leb128(data, sizeof(data), value);
REQUIRE(n == 5);
REQUIRE(value == 4294967295u);
}
SECTION("padded 8-byte encoding of 1") {
static const unsigned char data[] = {
0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00};
n = zm_parse_leb128(data, sizeof(data), value);
REQUIRE(n == 8);
REQUIRE(value == 1);
}
SECTION("max_size truncation") {
static const unsigned char data[] = {0xFF, 0xFF, 0xFF, 0xFF, 0x0F};
// Only 3 bytes available: 0x7F | (0x7F << 7) | (0x7F << 14) = 0x1FFFFF,
// and the third byte still has the continuation bit set, so it stops
// without a terminator but still returns the bytes it consumed.
n = zm_parse_leb128(data, 3, value);
REQUIRE(n == 3);
REQUIRE(value == 0x1FFFFFu);
}
SECTION("empty input") {
static const unsigned char data[] = {0x05};
n = zm_parse_leb128(data, 0, value);
REQUIRE(n == 0);
}
}
TEST_CASE("QueryString names", "[utils]") {
SECTION("a name without a value ends at the ampersand") {
std::stringstream str("flag&token=abc");
QueryString qs(str);
REQUIRE(qs.has("flag"));
REQUIRE(qs.has("token"));
REQUIRE(qs.get("token")->firstValue() == "abc");
}
SECTION("a url encoded name is decoded") {
std::stringstream str("a%5B%5D=1");
QueryString qs(str);
REQUIRE(qs.has("a[]"));
REQUIRE(qs.get("a[]")->firstValue() == "1");
}
}
TEST_CASE("UrlHost") {
REQUIRE(UrlHost("fd00::5") == "[fd00::5]");
REQUIRE(UrlHost("[fd00::5]") == "[fd00::5]");
REQUIRE(UrlHost("192.168.1.5") == "192.168.1.5");
REQUIRE(UrlHost("zm.example.com") == "zm.example.com");
REQUIRE(UrlHost("") == "");
}
TEST_CASE("Utf8Sanitize") {
REQUIRE(Utf8Sanitize(std::string("")) == std::string(""));
REQUIRE(Utf8Sanitize(std::string("abc")) == std::string("abc"));
REQUIRE(Utf8Sanitize(std::string("caf" "\xC3\xA9")) == std::string("caf" "\xC3\xA9"));
REQUIRE(Utf8Sanitize(std::string("\xE2\x82\xAC")) == std::string("\xE2\x82\xAC"));
REQUIRE(Utf8Sanitize(std::string("\xF0\x9F\x98\x80")) == std::string("\xF0\x9F\x98\x80"));
REQUIRE(Utf8Sanitize(std::string("ab\xE2\x82")) == std::string("ab??"));
REQUIRE(Utf8Sanitize(std::string("ab\xE2")) == std::string("ab?"));
REQUIRE(Utf8Sanitize(std::string("a\x80" "z")) == std::string("a?z"));
REQUIRE(Utf8Sanitize(std::string("caf\xE9")) == std::string("caf?"));
REQUIRE(Utf8Sanitize(std::string("\xC0\x80")) == std::string("??"));
REQUIRE(Utf8Sanitize(std::string("\xED\xA0\x80")) == std::string("???"));
REQUIRE(Utf8Sanitize(std::string("\xFF")) == std::string("?"));
}