From 3af199eba8c32869edf6d30f40b267fa7d05b82b Mon Sep 17 00:00:00 2001 From: Jash Date: Mon, 16 Nov 2026 01:07:04 +0530 Subject: [PATCH] fix: parse Amcrest event parts after their headers and keep partial reads refs #6047 --- src/zm_amcrest_parse.h | 38 +++++++++ src/zm_monitor_amcrest.cpp | 159 +++++++++++++++++++++++++---------- tests/CMakeLists.txt | 1 + tests/zm_monitor_amcrest.cpp | 96 +++++++++++++++++++++ 4 files changed, 249 insertions(+), 45 deletions(-) create mode 100644 src/zm_amcrest_parse.h create mode 100644 tests/zm_monitor_amcrest.cpp diff --git a/src/zm_amcrest_parse.h b/src/zm_amcrest_parse.h new file mode 100644 index 0000000000..65e30930b1 --- /dev/null +++ b/src/zm_amcrest_parse.h @@ -0,0 +1,38 @@ +// +// ZoneMinder Amcrest/Dahua event stream parsing +// +// 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, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// + +#ifndef ZM_AMCREST_PARSE_H +#define ZM_AMCREST_PARSE_H + +#include + +namespace zm { +namespace amcrest { + +// The message in one part of the eventManager.cgi stream: "Heartbeat", a +// "Code=...;action=...;index=..." line, or failing those the first body line. +std::string GetCommand(const std::string &content); + +// Takes the next message off the front of the stream buffer. Returns false +// when the buffer does not hold a complete message yet; the rest is kept. +bool NextEvent(std::string &buffer, std::string &command); + +} // namespace amcrest +} // namespace zm + +#endif // ZM_AMCREST_PARSE_H diff --git a/src/zm_monitor_amcrest.cpp b/src/zm_monitor_amcrest.cpp index ff6da1be86..690d50d73a 100644 --- a/src/zm_monitor_amcrest.cpp +++ b/src/zm_monitor_amcrest.cpp @@ -20,6 +20,85 @@ #include "zm_monitor.h" #include "zm_signal.h" #include "url.hpp" +#include "zm_amcrest_parse.h" +#include "zm_utils.h" + +// Parsing of the eventManager.cgi multipart stream. Kept out of the libcurl +// guard so it can be tested without a camera. +namespace zm { +namespace amcrest { + +static const std::string kBoundary = "--myboundary"; +static const std::string kCrLf = "\r\n"; + +static bool IsMessage(const std::string &line) { + return line == "Heartbeat" or line.compare(0, 5, "Code=") == 0; +} + +std::string GetCommand(const std::string &content) { + StringVector lines = Split(content, kCrLf); + // A part carries Content-Type/Content-Length headers, a blank line, then the message. + for (const std::string &line : lines) { + if (IsMessage(line)) return line; + } + bool in_body = false; + for (const std::string &line : lines) { + if (line.empty()) { + in_body = true; + } else if (in_body) { + return line; + } + } + return ""; +} + +bool NextEvent(std::string &buffer, std::string &command) { + command.clear(); + size_t start = buffer.find(kBoundary); + if (start == std::string::npos) { + // Nothing to act on; keep only a tail that may be the start of a boundary. + size_t keep = 0; + for (size_t len = std::min(buffer.size(), kBoundary.size() - 1); len > 0; len--) { + if (buffer.compare(buffer.size() - len, len, kBoundary, 0, len) == 0) { + keep = len; + break; + } + } + buffer.erase(0, buffer.size() - keep); + return false; + } + buffer.erase(0, start); + + size_t content_start = buffer.find(kCrLf); + if (content_start == std::string::npos) return false; + content_start += kCrLf.size(); + size_t next = buffer.find(kBoundary, content_start); + size_t end = (next == std::string::npos) ? buffer.size() : next; + + // The camera sends the next boundary only with the next part, so act on a + // part as soon as its message line is complete instead of waiting for it. + size_t pos = content_start; + while (pos < end) { + size_t eol = buffer.find(kCrLf, pos); + if (eol == std::string::npos or eol > end) break; + std::string line = buffer.substr(pos, eol - pos); + if (IsMessage(line)) { + command = line; + buffer.erase(0, eol + kCrLf.size()); + return true; + } + pos = eol + kCrLf.size(); + } + if (next == std::string::npos) return false; + + // A complete part with no message we know. + command = GetCommand(buffer.substr(content_start, next - content_start)); + buffer.erase(0, next); + return true; +} + +} // namespace amcrest +} // namespace zm #if HAVE_LIBCURL @@ -34,19 +113,37 @@ Monitor::AmcrestAPI::AmcrestAPI(Monitor *parent_) : Monitor::AmcrestAPI::~AmcrestAPI() { if (Amcrest_handle != nullptr) { // potentially clean up the old handle - curl_multi_remove_handle(curl_multi, Amcrest_handle); + if (curl_multi != nullptr) { + curl_multi_remove_handle(curl_multi, Amcrest_handle); + } curl_easy_cleanup(Amcrest_handle); + Amcrest_handle = nullptr; + } + if (curl_multi != nullptr) { + curl_multi_cleanup(curl_multi); + curl_multi = nullptr; } - if (curl_multi != nullptr) curl_multi_cleanup(curl_multi); } int Monitor::AmcrestAPI::start() { + healthy = false; + alarmed = false; + response.clear(); + // init the transfer and start it in multi-handle - int running_handles; + int running_handles = 0; CURLMcode curl_error; if (Amcrest_handle != nullptr) { // potentially clean up the old handle - curl_multi_remove_handle(curl_multi, Amcrest_handle); + if (curl_multi != nullptr) { + curl_multi_remove_handle(curl_multi, Amcrest_handle); + } curl_easy_cleanup(Amcrest_handle); + Amcrest_handle = nullptr; + } + + if (curl_multi == nullptr) { + Warning("AMCREST curl_multi is null"); + return -1; } Url full_url(parent->onvif_url.empty() ? parent->path : parent->onvif_url); @@ -70,6 +167,9 @@ int Monitor::AmcrestAPI::start() { curl_error = curl_multi_add_handle(curl_multi, Amcrest_handle); if (curl_error != CURLM_OK) { Warning("AMCREST error of %i", curl_error); + curl_easy_cleanup(Amcrest_handle); + Amcrest_handle = nullptr; + return -1; } curl_error = curl_multi_perform(curl_multi, &running_handles); if (curl_error == CURLM_OK) { @@ -93,6 +193,7 @@ int Monitor::AmcrestAPI::start() { healthy = true; Debug(1, "AMCREST Healthy"); } else { + healthy = false; Warning("AMCREST Response: %s", response.c_str()); Warning("AMCREST Seeing %i streams, and error of %i, url: %s", running_handles, curl_error, full_url.str().c_str()); @@ -101,33 +202,18 @@ int Monitor::AmcrestAPI::start() { Warning("AMCREST Response code: %lu", response_code); } - return 0; -} - -std::string get_command(const std::string &content) { - StringVector lines = Split(content, "\r\n"); - std::string command; - - for (auto line_it = lines.begin(); line_it != lines.end(); line_it++) { - std::string line = *line_it; - - if (line == "Heartbeat") return line; - if (line.empty() and !command.empty()) break; - //if (line.substr(0,4) == "Code") { - //} - command += line; - } - return command; + return healthy ? 0 : -1; } void Monitor::AmcrestAPI::WaitForMessage() { - int open_handles; - int transfers; + int open_handles = 0; + int transfers = 0; CURLMcode curl_error; // Tells us how many handles are open curl_error = curl_multi_perform(curl_multi, &open_handles); - if (open_handles == 0) { + if (curl_error != CURLM_OK || open_handles == 0) { + healthy = false; start(); // http transfer ended, need to restart. return; } @@ -138,31 +224,20 @@ void Monitor::AmcrestAPI::WaitForMessage() { if (curl_error != CURLM_OK) { healthy = false; Debug(1, "Error code %d", curl_error); + return; } Debug(2, "AMCREST: response: %s", response.c_str()); - // FIXME need to implement proper parsing - std::string boundary = "--myboundary"; - std::string br = "\r\n"; - while (!response.empty() and !zm_terminate) { - auto boundary_it = response.find(boundary); - Debug(1, "AMCREST: boundary %zu", boundary_it); - if (boundary_it == std::string::npos) { - // Might not be a boundary, might just hit the end - boundary_it = response.size(); - } - - std::string content = response.substr(0, boundary_it); - Debug(1, "AMCREST: content (%s) ending at %zu", content.c_str(), boundary_it); - std::string command = get_command(content); + std::string command; + while (!zm_terminate && zm::amcrest::NextEvent(response, command)) { Debug(1, "AMCREST: command: %s", command.c_str()); if (command.empty()) { } else if (command == "Heartbeat") { } else if (command.find("action=Start") != std::string::npos) { // Event Start - Debug(1, "AMCREST Triggered on with %s", response.c_str()); + Debug(1, "AMCREST Triggered on with %s", command.c_str()); if (!alarmed) { Debug(1, "AMCREST Triggered Event"); alarmed = true; @@ -173,12 +248,6 @@ void Monitor::AmcrestAPI::WaitForMessage() { } else { Debug(1, "AMCREST unhandled message: %s", command.c_str()); } - boundary_it = response.find(br, boundary_it); - Debug(1, "AMCREST Found br at %zu", boundary_it); - boundary_it += 2; - Debug(1, "AMCREST Remainder: %s", response.c_str()); - response = response.substr(boundary_it, response.size()); - Debug(1, "AMCREST Remainder: %s", response.c_str()); } // end while } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 67baba10a0..51c907e5b7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -105,6 +105,7 @@ set(TEST_SOURCES zm_ffmpeg_option_number.cpp zm_ffmpeg_encoder_choices.cpp zm_ffmpeg_input.cpp + zm_monitor_amcrest.cpp zm_go2rtc_check.cpp zm_janus_ids.cpp zm_janus_refresh.cpp diff --git a/tests/zm_monitor_amcrest.cpp b/tests/zm_monitor_amcrest.cpp new file mode 100644 index 0000000000..4ec9d0a28f --- /dev/null +++ b/tests/zm_monitor_amcrest.cpp @@ -0,0 +1,96 @@ +/* + * 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 . + */ + +#include "zm_catch2.h" +#include "zm_amcrest_parse.h" + +// What /cgi-bin/eventManager.cgi?action=attach sends: each part has headers, +// a blank line and the message. The next boundary only comes with the next part. +static const std::string kStart = + "--myboundary\r\n" + "Content-Type: text/plain\r\n" + "Content-Length:37\r\n" + "\r\n" + "Code=VideoMotion;action=Start;index=0\r\n" + "\r\n"; +static const std::string kStop = + "--myboundary\r\n" + "Content-Type: text/plain\r\n" + "Content-Length:36\r\n" + "\r\n" + "Code=VideoMotion;action=Stop;index=0\r\n" + "\r\n"; +static const std::string kHeartbeat = + "--myboundary\r\n" + "Content-Type: text/plain\r\n" + "Content-Length:9\r\n" + "\r\n" + "Heartbeat\r\n" + "\r\n"; + +TEST_CASE("Amcrest: the message is found after the part headers", "[Amcrest]") { + REQUIRE(zm::amcrest::GetCommand( + "Content-Type: text/plain\r\nContent-Length:37\r\n\r\nCode=VideoMotion;action=Start;index=0\r\n") + == "Code=VideoMotion;action=Start;index=0"); + REQUIRE(zm::amcrest::GetCommand("Content-Type: text/plain\r\n\r\nHeartbeat\r\n") == "Heartbeat"); + REQUIRE(zm::amcrest::GetCommand("Code=VideoMotion;action=Stop;index=0") == "Code=VideoMotion;action=Stop;index=0"); +} + +TEST_CASE("Amcrest: an event is reported before the next boundary arrives", "[Amcrest]") { + std::string buffer = kStart; + std::string command; + REQUIRE(zm::amcrest::NextEvent(buffer, command)); + REQUIRE(command == "Code=VideoMotion;action=Start;index=0"); + REQUIRE_FALSE(zm::amcrest::NextEvent(buffer, command)); +} + +TEST_CASE("Amcrest: several parts in one read come out in order", "[Amcrest]") { + std::string buffer = kHeartbeat + kStart + kStop; + std::string command; + REQUIRE(zm::amcrest::NextEvent(buffer, command)); + REQUIRE(command == "Heartbeat"); + REQUIRE(zm::amcrest::NextEvent(buffer, command)); + REQUIRE(command == "Code=VideoMotion;action=Start;index=0"); + REQUIRE(zm::amcrest::NextEvent(buffer, command)); + REQUIRE(command == "Code=VideoMotion;action=Stop;index=0"); + REQUIRE_FALSE(zm::amcrest::NextEvent(buffer, command)); +} + +TEST_CASE("Amcrest: a part split across reads is kept until it is complete", "[Amcrest]") { + std::string stream = kStart + kStop; + // Split at every position: the two events must come out exactly once each. + for (size_t cut = 1; cut < stream.size(); cut++) { + std::string buffer; + std::string command; + std::vector got; + buffer += stream.substr(0, cut); + while (zm::amcrest::NextEvent(buffer, command)) got.push_back(command); + buffer += stream.substr(cut); + while (zm::amcrest::NextEvent(buffer, command)) got.push_back(command); + INFO("cut at " << cut); + REQUIRE(got.size() == 2); + REQUIRE(got[0] == "Code=VideoMotion;action=Start;index=0"); + REQUIRE(got[1] == "Code=VideoMotion;action=Stop;index=0"); + } +} + +TEST_CASE("Amcrest: data without a boundary is dropped", "[Amcrest]") { + std::string buffer = "garbage"; + std::string command; + REQUIRE_FALSE(zm::amcrest::NextEvent(buffer, command)); + REQUIRE(buffer.empty()); +}