onvif-simple-server: add package

Package ONVIF Device, Media, Media2 and optional Imaging services with
generic external control helpers. Serve CGI requests through a dedicated
uhttpd section and announce on suitable IPv4 and IPv6 interfaces.

Apply the media parameter, connection address, persistent identity and
XML escaping changes for integration with the UCI camera service.

Signed-off-by: Daniel Golle <daniel@makrotopia.org>
This commit is contained in:
Daniel Golle committed 2026-11-26 01:17:40 +00:00
1 parent 818a306b3f
commit a3cc8482f4
26 files changed
+10868

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: GPL-2.0-only
include $(TOPDIR)/rules.mk
PKG_NAME:=onvif-simple-server
PKG_VERSION:=2026.10.17
PKG_RELEASE:=1
PKG_SOURCE_PROTO:=git
PKG_SOURCE_URL:=https://github.com/roleoroleo/onvif_simple_server.git
PKG_SOURCE_DATE:=2026-10-17
PKG_SOURCE_VERSION:=40fd1086f2e32ac91aff58647aeb21ed2a8a76b7
PKG_MIRROR_HASH:=53e14bed1d28ffecec3da0e26e722309ddd43ca97bbc49b448a30abcfb6cfe7c
PKG_MAINTAINER:=Daniel Golle <daniel@makrotopia.org>
PKG_LICENSE:=GPL-3.0-only
PKG_LICENSE_FILES:=LICENSE
PKG_BUILD_PARALLEL:=1
include $(INCLUDE_DIR)/package.mk
define Package/onvif-simple-server
SECTION:=multimedia
CATEGORY:=Multimedia
TITLE:=ONVIF CGI services and WS-Discovery
URL:=https://github.com/roleoroleo/onvif_simple_server
DEPENDS:=+libmbedtls +libjson-c +zlib +uhttpd +ucode +ucode-mod-fs +ucode-mod-uci
endef
define Package/onvif-simple-server/description
ONVIF Device, Media, Media2 and optional Imaging services served as CGI
through uhttpd. Includes WS-Discovery and generic external control helpers.
endef
define Package/onvif-simple-server/conffiles
/etc/config/onvif-simple-server
endef
MAKE_FLAGS += \
HAVE_MBEDTLS=1 \
CC="$(TARGET_CC) $(TARGET_CFLAGS) $(TARGET_CPPFLAGS) $(TARGET_LDFLAGS)" \
STRIP=true
define Build/Configure
endef
define Package/onvif-simple-server/install
$(INSTALL_DIR) $(1)/usr/bin $(1)/usr/share/onvif-simple-server
$(INSTALL_BIN) $(PKG_BUILD_DIR)/onvif_simple_server $(1)/usr/bin/
$(INSTALL_BIN) $(PKG_BUILD_DIR)/wsd_simple_server $(1)/usr/bin/
$(CP) $(PKG_BUILD_DIR)/*_files $(1)/usr/share/onvif-simple-server/
$(INSTALL_DATA) $(PKG_BUILD_DIR)/CONTROL_HELPERS.md $(1)/usr/share/onvif-simple-server/
$(INSTALL_DIR) $(1)/etc/config $(1)/etc/init.d $(1)/etc/uci-defaults
$(INSTALL_CONF) ./files/onvif.config $(1)/etc/config/onvif-simple-server
$(INSTALL_BIN) ./files/onvif.init $(1)/etc/init.d/onvif-simple-server
$(INSTALL_BIN) ./files/onvif.defaults $(1)/etc/uci-defaults/80-onvif-simple-server
$(INSTALL_DIR) $(1)/www/onvif/onvif
$(INSTALL_BIN) ./files/onvif.cgi $(1)/www/onvif/onvif/device_service
$(foreach service,media media2 imaging deviceio events ptz, \
$(LN) device_service $(1)/www/onvif/onvif/$(service)_service;)
endef
$(eval $(call BuildPackage,onvif-simple-server))
@@ -0,0 +1,21 @@
#!/bin/sh
. /lib/functions.sh
config_load onvif-simple-server
config_get config main config_file /var/run/onvif-simple-server/config.json
config_get_bool enabled main enabled 1
if [ "$enabled" != 1 ] || [ ! -r "$config" ]; then
printf 'Status: 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n'
exit 0
fi
service="${SCRIPT_NAME##*/}"
case "$service" in
device_service|media_service|media2_service|imaging_service|deviceio_service|events_service|ptz_service) ;;
*) printf 'Status: 404 Not Found\r\nContent-Length: 0\r\n\r\n'; exit 0 ;;
esac
export ONVIF_LOG_FILE=-
cd /usr/share/onvif-simple-server || exit 1
exec /usr/bin/onvif_simple_server -c "$config" "$service"
@@ -0,0 +1,3 @@
config server 'main'
option enabled '1'
option config_file '/var/run/onvif-simple-server/config.json'
@@ -0,0 +1,17 @@
#!/bin/sh
[ -n "$IPKG_INSTROOT" ] && exit 0
if ! uci -q get onvif-simple-server.main.uuid >/dev/null; then
read -r uuid </proc/sys/kernel/random/uuid || exit 1
uci set onvif-simple-server.main.uuid="$uuid" || exit 1
uci commit onvif-simple-server || exit 1
fi
uci -q get uhttpd.onvif >/dev/null && exit 0
uci -q batch <<'EOF'
set uhttpd.onvif=uhttpd
add_list uhttpd.onvif.listen_http='0.0.0.0:8080'
add_list uhttpd.onvif.listen_http='[::]:8080'
set uhttpd.onvif.home='/www/onvif'
set uhttpd.onvif.cgi_prefix='/onvif'
commit uhttpd
EOF
@@ -0,0 +1,56 @@
#!/bin/sh /etc/rc.common
START=99
USE_PROCD=1
start_service() {
local enabled config uuid listen port namespace keys key scope name hardware
config_load onvif-simple-server
config_get_bool enabled main enabled 1
config_get uuid main uuid
config_get config main config_file /var/run/onvif-simple-server/config.json
[ "$enabled" = 1 ] && [ -r "$config" ] || return 0
[ -n "$uuid" ] || return 1
json_set_namespace onvif_identity_ namespace
json_load_file "$config"
if json_select scopes; then
json_get_keys keys
for key in $keys; do
json_get_var scope "$key"
case "$scope" in
onvif://www.onvif.org/name/*)
name="${scope#onvif://www.onvif.org/name/}" ;;
onvif://www.onvif.org/hardware/*)
hardware="${scope#onvif://www.onvif.org/hardware/}" ;;
esac
done
fi
json_cleanup
json_set_namespace "$namespace"
config_load uhttpd
config_get listen onvif listen_http
listen="${listen%% *}"
port="${listen##*:}"
case "$port" in
''|*[!0-9]*) return 1 ;;
esac
[ "$port" -ge 1 ] && [ "$port" -le 65535 ] || return 1
mkdir -p /var/run/onvif-simple-server || return 1
procd_open_instance discovery
procd_set_param command /usr/bin/wsd_simple_server -f -u "$uuid" \
-p /var/run/onvif-simple-server/wsd.pid \
-t /usr/share/onvif-simple-server/wsd_files \
-x "http://%s:$port/onvif/device_service"
[ -z "$name" ] || procd_append_param command -m "$name"
[ -z "$hardware" ] || procd_append_param command -n "$hardware"
procd_set_param file "$config"
procd_set_param stderr 1
procd_set_param respawn
procd_close_instance
}
service_triggers() {
procd_add_reload_trigger onvif-simple-server uhttpd
}
@@ -0,0 +1,37 @@
From cfa2eac7512a62bf959eeb7e5ac9de8a6e34862a Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 00:51:02 +0100
Subject: [PATCH 01/15] fix: accept constant response parameters
The dispatcher passes constant method names. Mark the response namespace
and method arguments read-only to preserve their qualifiers.
Fixes: 68661430fcdb ("Replace error with empty message when method is not supported")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
fault.c | 2 +-
fault.h | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
--- a/fault.c
+++ b/fault.c
@@ -25,7 +25,7 @@
extern service_context_t service_ctx;
-int send_empty_response(char *ns, char *method)
+int send_empty_response(const char *ns, const char *method)
{
int ret;
char *response = (char *) malloc(strlen(ns) + strlen(method) + 10);
--- a/fault.h
+++ b/fault.h
@@ -17,7 +17,7 @@
#ifndef FAULT_H
#define FAULT_H
-int send_empty_response(char *ns, char *method);
+int send_empty_response(const char *ns, const char *method);
int send_fault(char *service, char *rec_send, char *subcode, char *subcode_ex, char *reason, char *detail);
int send_pull_messages_fault(char *timeout, char *message_limit);
int send_action_failed_fault(char *service, int code);
@@ -0,0 +1,114 @@
From 2d449074298d8f25df4e46de60a7a5c54582c8f6 Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 00:51:38 +0100
Subject: [PATCH 02/15] fix: emit CGI status headers for SOAP faults
CGI servers consume Status headers rather than HTTP response lines.
Return the intended failure status through the CGI interface so uhttpd
and other CGI hosts can relay SOAP faults correctly.
Fixes: 041f9ba8a189 ("Change template Error.xml to Fault.xml")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
Makefile | 9 ++++++++-
fault.c | 9 +++------
test/test_faults.c | 19 +++++++++++++++++++
test/test_faults.py | 11 +++++++++++
4 files changed, 41 insertions(+), 7 deletions(-)
create mode 100644 test/test_faults.c
create mode 100644 test/test_faults.py
--- a/Makefile
+++ b/Makefile
@@ -56,8 +56,14 @@ wsd_simple_server: $(OBJECTS_W)
# Build and run unit tests using the native host compiler.
# Uses stub mbedTLS headers from test/ so no crypto library is required.
-test: test/test_utils
+test: test/test_utils test/test_faults
./test/test_utils
+ python3 test/test_faults.py
+
+test/test_faults: test/test_faults.c test/stubs.c fault.c utils.c log.c
+ cc -I. -Itest -DHAVE_MBEDTLS -D_GNU_SOURCE -std=c99 \
+ test/test_faults.c test/stubs.c fault.c utils.c log.c \
+ -lz -lpthread -lrt -o test/test_faults
test/test_utils: test/test_utils.c test/stubs.c utils.c log.c
cc -I. -Itest -DHAVE_MBEDTLS -D_GNU_SOURCE -std=c99 \
@@ -69,6 +75,7 @@ clean:
rm -f onvif_notify_server
rm -f wsd_simple_server
rm -f test/test_utils
+ rm -f test/test_faults
rm -f $(OBJECTS_O)
rm -f $(OBJECTS_N)
rm -f $(OBJECTS_W)
--- a/fault.c
+++ b/fault.c
@@ -70,8 +70,7 @@ int send_fault(char *service, char *rec_
"%REASON%", reason,
"%DETAIL%", detail);
-// fprintf(stdout, "Status: 500 Internal Server Error\r\n");
- fprintf(stdout, "HTTP/1.1 500 Internal Server Error\r\n");
+ fprintf(stdout, "Status: 500 Internal Server Error\r\n");
fprintf(stdout, "Content-type: application/soap+xml\r\n");
fprintf(stdout, "Content-Length: %ld\r\n", size);
fprintf(stdout, "\r\n");
@@ -93,8 +92,7 @@ int send_pull_messages_fault(char *timeo
"%MAX_TIMEOUT%", timeout,
"%MAX_MESSAGE_LIMIT%", message_limit);
-// fprintf(stdout, "Status: 500 Internal Server Error\r\n");
- fprintf(stdout, "HTTP/1.1 500 Internal Server Error\r\n");
+ fprintf(stdout, "Status: 500 Internal Server Error\r\n");
fprintf(stdout, "Content-type: application/soap+xml\r\n");
fprintf(stdout, "Content-Length: %ld\r\n\r\n", size);
@@ -121,8 +119,7 @@ int send_authentication_error()
{
long size = cat(NULL, "generic_files/AuthenticationError.xml", 0);
-// fprintf(stdout, "Status: 400 Bad request\r\n");
- fprintf(stdout, "HTTP/1.1 400 Bad request\r\n");
+ fprintf(stdout, "Status: 400 Bad request\r\n");
fprintf(stdout, "Content-type: application/soap+xml\r\n");
fprintf(stdout, "Content-Length: %ld\r\n\r\n", size);
--- /dev/null
+++ b/test/test_faults.c
@@ -0,0 +1,19 @@
+#include <string.h>
+
+#include "onvif_simple_server.h"
+#include "fault.h"
+
+service_context_t service_ctx;
+
+int main(int argc, char **argv)
+{
+ service_ctx.port = 80;
+ strcpy(service_ctx.address_url, "127.0.0.1");
+ if (argc != 2)
+ return 1;
+ if (!strcmp(argv[1], "authentication"))
+ return send_authentication_error() < 0;
+ if (!strcmp(argv[1], "pull"))
+ return send_pull_messages_fault("PT1S", "1") < 0;
+ return send_action_not_supported_fault("media_service") < 0;
+}
--- /dev/null
+++ b/test/test_faults.py
@@ -0,0 +1,11 @@
+import subprocess
+import xml.etree.ElementTree as ET
+
+for operation, status in [('action', 500), ('pull', 500), ('authentication', 400)]:
+ response = subprocess.check_output(['./test/test_faults', operation])
+ headers, body = response.split(b'\r\n\r\n', 1)
+ fields = dict(line.split(b': ', 1) for line in headers.split(b'\r\n'))
+ assert int(fields[b'Status'].split()[0]) == status
+ assert int(fields[b'Content-Length']) == len(body)
+ ET.fromstring(body)
+print('CGI fault status, length and XML: 3 passed')
@@ -0,0 +1,128 @@
From ca9fca2c14f99a3f4dfbabdf6a78396104dd82e1 Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 00:52:25 +0100
Subject: [PATCH 03/15] feat: allow CGI logging to stderr
Accept ONVIF_LOG_FILE in the CGI environment. The value - routes logs
to stderr so the HTTP host can manage them; a pathname selects an
append-only file. Preserve the existing default log rotation.
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
README.md | 4 +++
onvif_simple_server.c | 11 +++++--
test/test_cgi.py | 67 +++++++++++++++++++++++++++++++++++++++++++
3 files changed, 79 insertions(+), 3 deletions(-)
create mode 100644 test/test_cgi.py
--- a/README.md
+++ b/README.md
@@ -66,6 +66,10 @@ diff -Naur busybox-1.36.1.ori/networking
```
## Configuration
+Set `ONVIF_LOG_FILE=-` in the CGI environment to log to stderr. A pathname
+selects an append-only log managed by the HTTP host. With the variable unset,
+the existing log file and rotation behaviour are retained.
+
### onvif_simple_server
onvif_simple server supports the following options but you should use them just for debugging purpose
--- a/onvif_simple_server.c
+++ b/onvif_simple_server.c
@@ -154,6 +154,7 @@ int main(int argc, char ** argv)
int c, ret, i, itmp;
char *conf_file;
char *prog_name;
+ char *log_file;
const char *method;
username_token_t security;
int auth_error = 0;
@@ -163,10 +164,14 @@ int main(int argc, char ** argv)
static char conf_file_buffer[256];
// Set default log file and conf file
- rotate_log();
- fLog = fopen(DEFAULT_LOG_FILE, "w");
+ log_file = getenv("ONVIF_LOG_FILE");
+ if (log_file == NULL) {
+ log_file = DEFAULT_LOG_FILE;
+ rotate_log();
+ }
+ fLog = strcmp(log_file, "-") == 0 ? stderr : fopen(log_file, "a");
if (fLog == NULL) {
- fprintf(stderr, "Unable to open log file %s\n", DEFAULT_LOG_FILE);
+ fprintf(stderr, "Unable to open log file %s\n", log_file);
exit(EXIT_FAILURE);
}
conf_file = conf_file_buffer;
--- /dev/null
+++ b/test/test_cgi.py
@@ -0,0 +1,67 @@
+import json
+import os
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+import xml.etree.ElementTree as ET
+
+ROOT = Path(__file__).resolve().parent.parent
+NS = {'s': 'http://www.w3.org/2003/05/soap-envelope',
+ 'tt': 'http://www.onvif.org/ver10/schema',
+ 'trt': 'http://www.onvif.org/ver10/media/wsdl',
+ 'tr2': 'http://www.onvif.org/ver20/media/wsdl',
+ 'timg': 'http://www.onvif.org/ver20/imaging/wsdl'}
+
+
+def configuration(count=2):
+ return {'ifs': 'lo', 'port': 8080, 'adv_enable_media2': True,
+ 'model': 'CGI test', 'profiles': [
+ {'name': f'Profile_{i}', 'width': 1920 // (i + 1),
+ 'height': 1080 // (i + 1), 'type': 'H264',
+ 'bitrate': 12000 // (i + 1), 'framerate': 30 - i,
+ 'url': f'rtsp://%s:8554/camera/{i}',
+ 'audio_encoder': 'NONE', 'audio_decoder': 'NONE'}
+ for i in range(count)]}
+
+
+def request(service, operation, content='', config=None):
+ config = configuration() if config is None else config
+ namespace = {'device': 'http://www.onvif.org/ver10/device/wsdl',
+ 'media': NS['trt'], 'media2': NS['tr2'],
+ 'imaging': NS['timg']}[service]
+ body = (f'<s:Envelope xmlns:s="{NS["s"]}" xmlns:tt="{NS["tt"]}">'
+ f'<s:Body><op:{operation} xmlns:op="{namespace}">'
+ f'{content}</op:{operation}></s:Body></s:Envelope>').encode()
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / 'config.json'
+ path.write_text(json.dumps(config))
+ env = dict(os.environ, ONVIF_LOG_FILE='-', REQUEST_METHOD='POST',
+ REMOTE_ADDR='127.0.0.1', CONTENT_LENGTH=str(len(body)))
+ result = subprocess.run([str(ROOT / 'onvif_simple_server'),
+ '-c', str(path), f'{service}_service'],
+ input=body, capture_output=True, cwd=ROOT,
+ env=env, timeout=10)
+ if result.returncode:
+ raise AssertionError(result.stderr.decode())
+ headers, xml = result.stdout.split(b'\r\n\r\n', 1)
+ fields = dict(line.split(b': ', 1) for line in headers.split(b'\r\n'))
+ assert int(fields[b'Content-Length']) == len(xml)
+ status = int(fields.get(b'Status', b'200').split()[0])
+ return status, ET.fromstring(xml)
+
+
+class CGITests(unittest.TestCase):
+ def test_device(self):
+ status, root = request('device', 'GetDeviceInformation')
+ self.assertEqual(status, 200)
+ self.assertEqual(root.findtext('.//{*}Model'), 'CGI test')
+
+ def test_fault(self):
+ status, root = request('media', 'NotImplemented')
+ self.assertEqual(status, 500)
+ self.assertIsNotNone(root.find('.//s:Fault', NS))
+
+
+if __name__ == '__main__':
+ unittest.main()
@@ -0,0 +1,41 @@
From ea260f377ba06766e26ff2fbfe7d4ef9dd103ca3 Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 09:57:24 +0100
Subject: [PATCH 04/15] fix: read profile bitrate from JSON configuration
JSON profiles initialise bitrate to zero but never load the configured
value. Read it alongside dimensions and frame rate so CGI responses
report the configured limit instead of the template fallback.
Fixes: 74ab3f7586cf ("feat: report live encoding type and bitrate in video encoder config responses")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
conf.c | 1 +
test/test_cgi.py | 6 ++++++
2 files changed, 7 insertions(+)
--- a/conf.c
+++ b/conf.c
@@ -1018,6 +1018,7 @@ int process_json_conf_file(char *file)
}
get_int_from_json(&(service_ctx.profiles[service_ctx.profiles_num - 1].width), item, "width");
get_int_from_json(&(service_ctx.profiles[service_ctx.profiles_num - 1].height), item, "height");
+ get_int_from_json(&(service_ctx.profiles[service_ctx.profiles_num - 1].bitrate), item, "bitrate");
get_int_from_json(&(service_ctx.profiles[service_ctx.profiles_num - 1].framerate), item, "framerate");
get_string_from_json(&(service_ctx.profiles[service_ctx.profiles_num - 1].url), item, "url");
get_string_from_json(&(service_ctx.profiles[service_ctx.profiles_num - 1].snapurl), item, "snapurl");
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -52,6 +52,12 @@ def request(service, operation, content=
class CGITests(unittest.TestCase):
+ def test_json_bitrate(self):
+ status, root = request('media', 'GetProfiles')
+ self.assertEqual(status, 200)
+ self.assertEqual([n.text for n in root.findall('.//tt:BitrateLimit', NS)],
+ ['12000', '6000'])
+
def test_device(self):
status, root = request('device', 'GetDeviceInformation')
self.assertEqual(status, 200)
@@ -0,0 +1,627 @@
From 8b9126c995558885a2ffd1e922bde12002a6a595 Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 10:46:00 +0100
Subject: [PATCH 07/15] fix: traverse SOAP request elements without suffix
underflow
Match local names without subtracting unchecked lengths and advance
through every sibling. Keep searches within their requested subtree,
reject malformed envelopes and DTD input, and verify the operation
namespace against its service endpoint. Terminate the CGI input buffer.
Fixes: d2f362bdb0dc ("Add new functions to ezxml_wrapper")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
Makefile | 9 +-
ezxml_wrapper.c | 385 +++++++++++-------------------------------
ezxml_wrapper.h | 2 +
onvif_simple_server.c | 37 +++-
test/test_cgi.py | 9 +-
test/test_xml.c | 33 ++++
6 files changed, 182 insertions(+), 293 deletions(-)
create mode 100644 test/test_xml.c
--- a/Makefile
+++ b/Makefile
@@ -59,9 +59,15 @@ test-cgi: onvif_simple_server
# Build and run unit tests using the native host compiler.
# Uses stub mbedTLS headers from test/ so no crypto library is required.
-test: test/test_utils test/test_faults
+test: test/test_utils test/test_faults test/test_xml
./test/test_utils
python3 test/test_faults.py
+ ./test/test_xml
+
+test/test_xml: test/test_xml.c test/stubs.c ezxml_wrapper.c ezxml/ezxml.c utils.c log.c
+ cc -I. -Itest -DHAVE_MBEDTLS -D_GNU_SOURCE -std=c99 \
+ test/test_xml.c test/stubs.c ezxml_wrapper.c ezxml/ezxml.c utils.c log.c \
+ -lz -lpthread -lrt -o test/test_xml
test/test_faults: test/test_faults.c test/stubs.c fault.c utils.c log.c
cc -I. -Itest -DHAVE_MBEDTLS -D_GNU_SOURCE -std=c99 \
@@ -79,6 +85,7 @@ clean:
rm -f wsd_simple_server
rm -f test/test_utils
rm -f test/test_faults
+ rm -f test/test_xml
rm -f $(OBJECTS_O)
rm -f $(OBJECTS_N)
rm -f $(OBJECTS_W)
--- a/ezxml_wrapper.c
+++ b/ezxml_wrapper.c
@@ -14,340 +14,149 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "string.h"
+#include <string.h>
#include "ezxml_wrapper.h"
#include "utils.h"
-#include "log.h"
-ezxml_t root_xml;
+static ezxml_t root_xml;
-/**
- * Init xml parser
- * @param buffer The buffer contaning the xml file
- * @param buffer_size The size of the buffer
- */
-void init_xml(char *buffer, int buffer_size)
+static const char *local_name(ezxml_t node)
{
- root_xml = ezxml_parse_str(buffer, buffer_size);
-}
+ const char *colon;
-/**
- * Close xml parser
- */
-void close_xml()
-{
- ezxml_free(root_xml);
+ if (!node)
+ return "";
+ colon = strchr(node->name, ':');
+ return colon ? colon + 1 : node->name;
}
-/**
- * Get the method (the 1st element after <Body>)
- * @param skip_prefix 1 to skip the prefix of the element (<prefix:method>)
- * @return A pointer to the name of the method, NULL if not found
- */
-const char *get_method(int skip_prefix)
+const char *xml_namespace_get(ezxml_t node)
{
- ezxml_t xml;
- char first_node[256];
- int len;
- char *c;
-
- // Check if "Body" element exists
- snprintf(first_node, sizeof(first_node), "%s", "Body");
- xml = root_xml->child;
- while (xml && strcmp(first_node, xml->name)) xml = xml->ordered;
- if ((xml) && (xml->child)) {
- if (skip_prefix) {
- c = strchr(xml->child->name, ':');
- if (c == NULL) {
- return xml->child->name;
- } else {
- c++;
- return c;
- }
- }
- }
+ char attribute[MAX_LEN];
+ const char *namespace;
+ const char *colon;
- // Check if "something:Body" element exists
- xml = root_xml->child;
- snprintf(first_node, sizeof(first_node), "%s", ":Body");
- while (xml) {
- len = strlen(xml->name);
- if (strcmp(first_node, &(xml->name)[len - 5]) == 0) break;
- xml = xml->ordered;
- }
- if ((xml) && (xml->child)) {
- if (skip_prefix) {
- c = strchr(xml->child->name, ':');
- if (c == NULL) {
- return xml->child->name;
- } else {
- c++;
- return c;
- }
- }
+ if (!node)
+ return NULL;
+ colon = strchr(node->name, ':');
+ if (colon && colon - node->name >= MAX_LEN - (int)sizeof("xmlns:"))
+ return NULL;
+ if (colon)
+ snprintf(attribute, sizeof(attribute), "xmlns:%.*s",
+ (int)(colon - node->name), node->name);
+ else
+ snprintf(attribute, sizeof(attribute), "xmlns");
+ for (; node; node = node->parent) {
+ namespace = ezxml_attr(node, attribute);
+ if (namespace)
+ return namespace;
}
-
return NULL;
}
-int go_to_parent;
+static ezxml_t child_find(ezxml_t node, const char *name)
+{
+ ezxml_t child;
+
+ for (child = node ? node->child : NULL; child; child = child->ordered)
+ if (!strcmp(local_name(child), name))
+ return child;
+ return NULL;
+}
-/**
- * Internal recursive function: get the 1st element with name "name" starting from "first_node"
- * @param xml The xml structure
- * @param name The name of the element to find
- * @param first_node The node where to find the element
- * @return A pointer to the value of the element, NULL if not found
- */
-const char *get_element_rec(ezxml_t xml, char *name, char *first_node)
+static ezxml_t descendant_find(ezxml_t node, const char *name)
{
- const char *ret;
- char name_copy[256];
- ezxml_t px, pk;
-
- if (go_to_parent) return NULL;
-
- // If it's the root of the document choose the first node ("Header" or "Body")
- if (xml->parent == NULL) {
- px = xml->child;
- snprintf(name_copy, sizeof(name_copy), "%s", first_node);
- while (px) {
- if (strcmp(first_node, &(px->name)[strlen(px->name) - strlen(first_node)]) == 0) {
- ret = get_element_rec(px, name, first_node);
- return ret;
- } else {
- px = px->ordered;
- }
- }
- // 1st node not found, exit
- } else {
- // Check if this node is "<name>"
- if (strcmp(name, xml->name) == 0) {
- return xml->txt;
- }
-
- // Check if this node is "<something:name>"
- name_copy[0] = ':';
- snprintf(&name_copy[1], sizeof(name_copy) - 1, "%s", name);
- if (strcmp(name_copy, &(xml->name)[strlen(xml->name) - strlen(name_copy)]) == 0) {
- return xml->txt;
- }
-
- // Check children
- if (xml->child) {
- ret = get_element_rec(xml->child, name, first_node);
- go_to_parent = 0;
- if (ret != NULL) return ret;
- }
-
- // Check brothers
- if((pk = xml->ordered)) {
- ret = get_element_rec(pk, name, first_node);
- if (go_to_parent) return NULL;
- if (ret != NULL) return ret;
- }
+ ezxml_t found;
+ ezxml_t child;
- go_to_parent = 1;
+ if (!node)
+ return NULL;
+ if (!strcmp(local_name(node), name))
+ return node;
+ for (child = node->child; child; child = child->ordered) {
+ found = descendant_find(child, name);
+ if (found)
+ return found;
}
-
return NULL;
}
-/**
- * Get the 1st element with name "name" starting from "first_node"
- * @param name The name of the element to find
- * @param first_node The node where to find the element
- * @return A pointer to the value of the element, NULL if not found
- */
-const char *get_element(char *name, char *first_node)
+void init_xml(char *buffer, int buffer_size)
{
- char *ret;
+ static const char declaration[] = "<!DOCTYPE";
+ const char *namespace;
+ int i;
+
+ root_xml = NULL;
+ if (buffer_size <= 0)
+ return;
+ for (i = 0; i + sizeof(declaration) - 1 <= (size_t)buffer_size; i++)
+ if (!memcmp(buffer + i, declaration, sizeof(declaration) - 1))
+ return;
+ root_xml = ezxml_parse_str(buffer, buffer_size);
+ namespace = xml_namespace_get(root_xml);
+ if (!root_xml || *ezxml_error(root_xml) ||
+ strcmp(local_name(root_xml), "Envelope") || !namespace ||
+ strcmp(namespace, "http://www.w3.org/2003/05/soap-envelope")) {
+ ezxml_free(root_xml);
+ root_xml = NULL;
+ }
+}
- go_to_parent = 0;
- ret = (char *) get_element_rec(root_xml, name, first_node);
- if (ret == NULL) return NULL;
- else return trim_mf(ret);
- // Warning: the line above change the xml content
- // ret should be a (const char *)
-}
-
-/**
- * Internal recursive function: get the 1st element with name "name" starting from "start_from"
- * @param xml The xml structure
- * @param name The name of the element to find
- * @param first_node The node where to find the element
- * @return ezxml_t type pointing to the element, NULL if not found
- */
-ezxml_t get_element_rec_ptr(ezxml_t xml, char *name, char *first_node)
+void close_xml(void)
{
- ezxml_t ret;
- char name_copy[256];
- ezxml_t px, pk;
-
- if (go_to_parent) return NULL;
-
- // If it's the root of the document choose the first node ("Header" or "Body")
- if (xml->parent == NULL) {
- px = xml->child;
- snprintf(name_copy, sizeof(name_copy), "%s", first_node);
- while (px) {
- if (strcmp(first_node, &(px->name)[strlen(px->name) - strlen(first_node)]) == 0) {
- ret = get_element_rec_ptr(px, name, first_node);
- return ret;
- } else {
- px = px->ordered;
- }
- }
- // 1st node not found, exit
- } else {
- // Check if this node is "<name>"
- if (strcmp(name, xml->name) == 0) {
- return xml;
- }
-
- // Check if this node is "<something:name>"
- name_copy[0] = ':';
- snprintf(&name_copy[1], sizeof(name_copy) - 1, "%s", name);
- if (strcmp(name_copy, &(xml->name)[strlen(xml->name) - strlen(name_copy)]) == 0) {
- return xml;
- }
-
- // Check children
- if (xml->child) {
- ret = get_element_rec_ptr(xml->child, name, first_node);
- go_to_parent = 0;
- if (ret != NULL) return ret;
- }
-
- // Check brothers
- if((pk = xml->ordered)) {
- ret = get_element_rec_ptr(pk, name, first_node);
- if (go_to_parent) return NULL;
- if (ret != NULL) return ret;
- }
+ ezxml_free(root_xml);
+ root_xml = NULL;
+}
- go_to_parent = 1;
- }
+const char *get_method(int skip_prefix)
+{
+ ezxml_t body;
- return NULL;
+ body = child_find(root_xml, "Body");
+ if (!body || !body->child)
+ return NULL;
+ return skip_prefix ? local_name(body->child) : body->child->name;
+}
+
+const char *get_method_namespace(void)
+{
+ ezxml_t body;
+
+ body = child_find(root_xml, "Body");
+ return body ? xml_namespace_get(body->child) : NULL;
}
-/**
- * Get the 1st element with name "name" starting from "start_from"
- * @param start_from The element where to start
- * @param name The name of the element to find
- * @param first_node The 1st level node where to find the element
- * @return ezxml_t type pointing to the element, NULL if not found
- */
ezxml_t get_element_ptr(ezxml_t start_from, char *name, char *first_node)
{
- ezxml_t ret;
+ if (!start_from)
+ start_from = child_find(root_xml, first_node);
+ return descendant_find(start_from, name);
+}
- go_to_parent = 0;
- if (start_from == NULL)
- ret = get_element_rec_ptr(root_xml, name, first_node);
- else
- ret = get_element_rec_ptr(start_from, name, first_node);
+const char *get_element(char *name, char *first_node)
+{
+ ezxml_t node;
- return ret;
+ node = get_element_ptr(NULL, name, first_node);
+ return node ? trim_mf(node->txt) : NULL;
}
-/**
- * Get the child element with name "name" starting from node "father"
- * @param name The name of the element to find
- * @param father The node where to find the element
- * @return A pointer to the value of the element, NULL if not found
- */
const char *get_element_in_element(const char *name, ezxml_t father)
{
- char name_copy[256];
- ezxml_t child = father->child;
- ezxml_t pk;
-
- if (child != NULL) {
- // Check if this node is "<name>"
- if (strcmp(name, child->name) == 0) {
- return child->txt;
- }
-
- // Check if this node is "<something:name>"
- name_copy[0] = ':';
- snprintf(&name_copy[1], sizeof(name_copy) - 1, "%s", name);
- if (strcmp(name_copy, &(child->name)[strlen(child->name) - strlen(name_copy)]) == 0) {
- return child->txt;
- }
-
- // Check brothers
- while((pk = child->ordered)) {
- // Check if this node is "<name>"
- if (strcmp(name, pk->name) == 0) {
- return pk->txt;
- }
-
- // Check if this node is "<something:name>"
- name_copy[0] = ':';
- snprintf(&name_copy[1], sizeof(name_copy) - 1, "%s", name);
- if (strcmp(name_copy, &(pk->name)[strlen(pk->name) - strlen(name_copy)]) == 0) {
- return pk->txt;
- }
- }
- }
+ ezxml_t node;
- return NULL;
+ node = child_find(father, name);
+ return node ? node->txt : NULL;
}
-/**
- * Get the child element with name "name" starting from node "father"
- * @param name The name of the element to find
- * @param father The node where to find the element
- * @return ezxml_t type pointing to the element, NULL if not found
- */
ezxml_t get_element_in_element_ptr(const char *name, ezxml_t father)
{
- char name_copy[256];
- ezxml_t child = father->child;
- ezxml_t pk;
-
- if (child != NULL) {
- // Check if this node is "<name>"
- if (strcmp(name, child->name) == 0) {
- return child;
- }
-
- // Check if this node is "<something:name>"
- name_copy[0] = ':';
- snprintf(&name_copy[1], sizeof(name_copy) - 1, "%s", name);
- if (strcmp(name_copy, &(child->name)[strlen(child->name) - strlen(name_copy)]) == 0) {
- return child;
- }
-
- // Check brothers
- while((pk = child->ordered)) {
- // Check if this node is "<name>"
- if (strcmp(name, pk->name) == 0) {
- return pk;
- }
-
- // Check if this node is "<something:name>"
- name_copy[0] = ':';
- snprintf(&name_copy[1], sizeof(name_copy) - 1, "%s", name);
- if (strcmp(name_copy, &(pk->name)[strlen(pk->name) - strlen(name_copy)]) == 0) {
- return pk;
- }
- }
- }
-
- return NULL;
+ return child_find(father, name);
}
-/**
- * Get the attribute of a node with name "name"
- * @param node The node where to find the attribute
- * @param name The name of the attribute to find
- * @return A pointer to the value of the attribute, NULL if not found
- */
const char *get_attribute(ezxml_t node, char *name)
{
- return ezxml_attr(node, name);
+ return node ? ezxml_attr(node, name) : NULL;
}
--- a/ezxml_wrapper.h
+++ b/ezxml_wrapper.h
@@ -22,6 +22,8 @@
void init_xml(char *buffer, int buffer_size);
void close_xml();
const char *get_method(int skip_prefix);
+const char *get_method_namespace(void);
+const char *xml_namespace_get(ezxml_t node);
const char *get_element(char *name, char *first_node);
ezxml_t get_element_ptr(ezxml_t start_from, char *name, char *first_node);
const char *get_element_in_element(const char *name, ezxml_t father);
--- a/onvif_simple_server.c
+++ b/onvif_simple_server.c
@@ -148,6 +148,30 @@ void print_usage(char *progname)
fprintf(stderr, "\t\tprint this help\n");
}
+static int service_namespace_matches(const char *service, const char *namespace)
+{
+ static const struct {
+ const char *service;
+ const char *namespace;
+ } services[] = {
+ { "device_service", "http://www.onvif.org/ver10/device/wsdl" },
+ { "media_service", "http://www.onvif.org/ver10/media/wsdl" },
+ { "media2_service", "http://www.onvif.org/ver20/media/wsdl" },
+ { "ptz_service", "http://www.onvif.org/ver20/ptz/wsdl" },
+ { "events_service", "http://www.onvif.org/ver10/events/wsdl" },
+ { "deviceio_service", "http://www.onvif.org/ver10/deviceIO/wsdl" },
+ { "imaging_service", "http://www.onvif.org/ver20/imaging/wsdl" }
+ };
+ size_t i;
+
+ if (!namespace)
+ return 0;
+ for (i = 0; i < sizeof(services) / sizeof(services[0]); i++)
+ if (!strcmp(service, services[i].service))
+ return !strcmp(namespace, services[i].namespace);
+ return 0;
+}
+
int main(int argc, char ** argv)
{
char *tmp;
@@ -342,10 +366,11 @@ int main(int argc, char ** argv)
}
int input_size;
// Use static buffer instead of malloc to avoid heap issues
- static char input_buffer[16 * 1024];
+ static char input_buffer[16 * 1024 + 1];
char* input = input_buffer;
log_debug("Static buffer allocated, input pointer points to %p", input);
- input_size = fread(input, 1, 16 * 1024 * sizeof(char), stdin);
+ input_size = fread(input, 1, sizeof(input_buffer) - 1, stdin);
+ input[input_size] = '\0';
if (input_size == 0) {
log_fatal("Error: input is empty");
fclose(fLog);
@@ -371,6 +396,14 @@ int main(int argc, char ** argv)
log_debug("Method: %s", method);
+ if (!service_namespace_matches(prog_name, get_method_namespace())) {
+ send_action_not_supported_fault(prog_name);
+ close_xml();
+ free_conf_file();
+ fclose(fLog);
+ return 0;
+ }
+
if (service_ctx.user != NULL) {
if ((get_element("Security", "Header") != NULL) && (get_element("UsernameToken", "Header") != NULL)) {
unsigned long nonce_size = 128;
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -25,9 +25,9 @@ def configuration(count=2):
for i in range(count)]}
-def request(service, operation, content='', config=None):
+def request(service, operation, content='', config=None, namespace=None):
config = configuration() if config is None else config
- namespace = {'device': 'http://www.onvif.org/ver10/device/wsdl',
+ namespace = namespace or {'device': 'http://www.onvif.org/ver10/device/wsdl',
'media': NS['trt'], 'media2': NS['tr2'],
'imaging': NS['timg']}[service]
body = (f'<s:Envelope xmlns:s="{NS["s"]}" xmlns:tt="{NS["tt"]}">'
@@ -52,6 +52,11 @@ def request(service, operation, content=
class CGITests(unittest.TestCase):
+ def test_operation_namespace(self):
+ status, root = request('media', 'GetProfiles', namespace='urn:unrelated')
+ self.assertEqual(status, 500)
+ self.assertIsNotNone(root.find('.//s:Fault', NS))
+
def test_text_encoder_parameters(self):
config = ('ifs=lo\nname=Profile_0\nwidth=640\nheight=480\n'
'type=H264\nencoding_profile=Baseline\ngov_length=61\n'
--- /dev/null
+++ b/test/test_xml.c
@@ -0,0 +1,33 @@
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "ezxml_wrapper.h"
+
+int main(void)
+{
+ char request[] = "<s:Envelope xmlns:s='http://www.w3.org/2003/05/soap-envelope'>"
+ "<s:Header><a/></s:Header><s:Body><m:Set xmlns:m='urn:test'>"
+ "<a/><b/><m:Value>42</m:Value><m:Next>43</m:Next>"
+ "</m:Set></s:Body></s:Envelope>";
+ char malformed[] = "<x>";
+ ezxml_t operation;
+
+ init_xml(request, strlen(request));
+ assert(!strcmp(get_method(1), "Set"));
+ assert(!strcmp(get_method_namespace(), "urn:test"));
+ operation = get_element_ptr(NULL, "Set", "Body");
+ assert(operation);
+ assert(!strcmp(get_element_in_element("Value", operation), "42"));
+ assert(!strcmp(get_element_in_element("Next", operation), "43"));
+ assert(get_element_in_element_ptr("Next", operation));
+ assert(!get_element_in_element("Missing", operation));
+ assert(!get_element("Value", "Header"));
+ close_xml();
+ init_xml(malformed, strlen(malformed));
+ assert(!get_method(1));
+ assert(!get_element("Value", "Body"));
+ close_xml();
+ puts("XML navigation: passed");
+ return 0;
+}
@@ -0,0 +1,548 @@
From e374d53671c85ec96e6c6f06d053cb99fad4447c Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 10:50:28 +0100
Subject: [PATCH 08/15] feat: add a generic external control helper protocol
Exchange versioned JSON with configured executables over stdin/stdout
without a shell. Drain both directions concurrently, validate replies,
and map backend failures to SOAP faults. Support an optional uptime
based deadline and reap failed, cancelled and timed-out children.
Test literal executable paths and data, malformed and oversized output,
backend errors, premature exit and child completion after stdout closes.
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
CONTROL_HELPERS.md | 28 +++++
Makefile | 11 +-
Makefile.static | 2 +-
README.md | 3 +
conf.c | 21 ++++
control_helper.c | 249 ++++++++++++++++++++++++++++++++++++++++++
control_helper.h | 20 ++++
onvif_simple_server.h | 3 +
test/test_helper.c | 27 +++++
test/test_helper.py | 40 +++++++
10 files changed, 401 insertions(+), 3 deletions(-)
create mode 100644 CONTROL_HELPERS.md
create mode 100644 control_helper.c
create mode 100644 control_helper.h
create mode 100644 test/test_helper.c
create mode 100644 test/test_helper.py
--- /dev/null
+++ b/CONTROL_HELPERS.md
@@ -0,0 +1,28 @@
+# External control helpers
+
+Optional global `encoder_helper` and `imaging_helper` settings select absolute
+executable paths. They are independent of the operating system's camera
+framework. The server invokes the executable directly, with one operation
+argument, a JSON request on stdin and a JSON response on stdout. It does not
+interpret command strings. Helpers may be compiled programs or executable
+scripts. Diagnostics belong on stderr.
+
+The request envelope contains `version: 1`, `operation` and an object `data`.
+The response contains `version: 1`, `status` and, on success, an object `data`.
+Status values are `ok`, `unsupported`, `not_found`, `invalid`, `busy`, `failed`.
+A protocol response, including an error status, uses process exit status zero.
+Non-zero exit, malformed output, unsupported protocol versions and output
+exceeding the CGI message size of 16 KiB are application failures. Return
+exactly one JSON object. Child output is drained while request input is sent.
+
+`helper_timeout_ms` is an optional positive deadline. Its default is zero,
+which leaves the deadline to the CGI host. Configure it below the HTTP
+server's script limit when helpers may block. The deadline uses uptime and
+includes both communication and child completion. Failed/timed-out children
+are terminated and reaped. Helpers must remain synchronous and must not
+daemonise or leave background work behind.
+
+Operation-specific encoder and imaging contracts are described alongside
+their service implementations. A helper is responsible for serialising
+changes to shared camera resources and for returning success only after a
+change is applied. The server does not commit its generated configuration.
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
# Set HAVE_WOLFSSL or HAVE_MBEDTLS variable if you want to use WOLFSSL or
# MBEDTLS instead of LIBTOMCRYPT
-OBJECTS_O = media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
+OBJECTS_O = control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_N = onvif_notify_server.o conf.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_W = wsd_simple_server.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
ifdef HAVE_WOLFSSL
@@ -59,10 +59,16 @@ test-cgi: onvif_simple_server
# Build and run unit tests using the native host compiler.
# Uses stub mbedTLS headers from test/ so no crypto library is required.
-test: test/test_utils test/test_faults test/test_xml
+test: test/test_utils test/test_faults test/test_xml test/test_helper
./test/test_utils
python3 test/test_faults.py
./test/test_xml
+ python3 test/test_helper.py
+
+test/test_helper: test/test_helper.c test/stubs.c control_helper.c fault.c utils.c log.c
+ cc -I. -Itest -DHAVE_MBEDTLS -D_GNU_SOURCE -std=c99 \
+ test/test_helper.c test/stubs.c control_helper.c fault.c utils.c log.c \
+ -ljson-c -lz -lpthread -lrt -o test/test_helper
test/test_xml: test/test_xml.c test/stubs.c ezxml_wrapper.c ezxml/ezxml.c utils.c log.c
cc -I. -Itest -DHAVE_MBEDTLS -D_GNU_SOURCE -std=c99 \
@@ -86,6 +92,7 @@ clean:
rm -f test/test_utils
rm -f test/test_faults
rm -f test/test_xml
+ rm -f test/test_helper
rm -f $(OBJECTS_O)
rm -f $(OBJECTS_N)
rm -f $(OBJECTS_W)
--- a/Makefile.static
+++ b/Makefile.static
@@ -1,7 +1,7 @@
# Set HAVE_WOLFSSL or HAVE_MBEDTLS variable if you want to use WOLFSSL or
# MBEDTLS instead of LIBTOMCRYPT
-OBJECTS_O = media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
+OBJECTS_O = control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_N = onvif_notify_server.o conf.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_W = wsd_simple_server.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
ifdef HAVE_WOLFSSL
--- a/README.md
+++ b/README.md
@@ -68,6 +68,9 @@ diff -Naur busybox-1.36.1.ori/networking
## Configuration
### Video parameters
+The optional external control protocol is documented in
+[CONTROL_HELPERS.md](CONTROL_HELPERS.md).
+
Each profile accepts `bitrate` (kbps), `framerate` (numerator),
`framerate_den` (default 1), `gov_length`, `encoding_interval`, `quality`
and `encoding_profile` (for example `Baseline`, `Main` or `High`). Text and
--- a/conf.c
+++ b/conf.c
@@ -56,6 +56,10 @@ static int profiles_validate(void)
int i;
int j;
+ if (service_ctx.helper_timeout_ms < 0 ||
+ (service_ctx.encoder_helper && service_ctx.encoder_helper[0] != '/') ||
+ (service_ctx.imaging_helper && service_ctx.imaging_helper[0] != '/'))
+ return -2;
if (service_ctx.source_width < 0 || service_ctx.source_height < 0 ||
service_ctx.source_framerate < 0 || service_ctx.source_framerate_den <= 0 ||
(!!service_ctx.source_width != !!service_ctx.source_height))
@@ -118,6 +122,9 @@ int process_conf_file(char *file)
service_ctx.source_height = 0;
service_ctx.source_framerate = 0;
service_ctx.source_framerate_den = 1;
+ service_ctx.helper_timeout_ms = 0;
+ service_ctx.encoder_helper = NULL;
+ service_ctx.imaging_helper = NULL;
service_ctx.scopes = NULL;
service_ctx.scopes_num = 0;
service_ctx.ptz_node.enable = 0;
@@ -255,6 +262,12 @@ int process_conf_file(char *file)
service_ctx.factory_default_command = (char *) malloc(strlen(value) + 1);
snprintf(service_ctx.factory_default_command, strlen(value) + 1, "%s", value);
+ } else if (strcasecmp(param, "encoder_helper") == 0) {
+ service_ctx.encoder_helper = strdup(value);
+ } else if (strcasecmp(param, "imaging_helper") == 0) {
+ service_ctx.imaging_helper = strdup(value);
+ } else if (strcasecmp(param, "helper_timeout_ms") == 0) {
+ service_ctx.helper_timeout_ms = atoi(value);
} else if (strcasecmp(param, "source_width") == 0) {
service_ctx.source_width = atoi(value);
} else if (strcasecmp(param, "source_height") == 0) {
@@ -886,6 +899,9 @@ int process_json_conf_file(char *file)
service_ctx.source_height = 0;
service_ctx.source_framerate = 0;
service_ctx.source_framerate_den = 1;
+ service_ctx.helper_timeout_ms = 0;
+ service_ctx.encoder_helper = NULL;
+ service_ctx.imaging_helper = NULL;
service_ctx.scopes = NULL;
service_ctx.scopes_num = 0;
service_ctx.ptz_node.enable = 0;
@@ -949,6 +965,9 @@ int process_json_conf_file(char *file)
get_bool_from_json(&(service_ctx.adv_empty_if_unknown), json_file, "adv_empty_if_unknown");
get_bool_from_json(&(service_ctx.adv_fault_if_unknown), json_file, "adv_fault_if_unknown");
get_bool_from_json(&(service_ctx.adv_fault_if_set), json_file, "adv_fault_if_set");
+ get_string_from_json(&service_ctx.encoder_helper, json_file, "encoder_helper");
+ get_string_from_json(&service_ctx.imaging_helper, json_file, "imaging_helper");
+ get_int_from_json(&service_ctx.helper_timeout_ms, json_file, "helper_timeout_ms");
get_int_from_json(&service_ctx.source_width, json_file, "source_width");
get_int_from_json(&service_ctx.source_height, json_file, "source_height");
get_int_from_json(&service_ctx.source_framerate, json_file, "source_framerate");
@@ -1347,6 +1366,8 @@ int process_json_conf_file(char *file)
void free_conf_file()
{
+ free(service_ctx.encoder_helper);
+ free(service_ctx.imaging_helper);
int i;
if (service_ctx.events_enable == 1) {
--- /dev/null
+++ b/control_helper.c
@@ -0,0 +1,249 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include <sys/wait.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <signal.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "control_helper.h"
+#include "onvif_simple_server.h"
+#include "fault.h"
+
+#define HELPER_MESSAGE_SIZE (16 * 1024)
+#define MSEC_PER_SEC 1000
+#define NSEC_PER_MSEC 1000000
+
+extern service_context_t service_ctx;
+
+static volatile sig_atomic_t notify_fd = -1;
+static volatile sig_atomic_t cancelled;
+
+static void child_notify(int signo)
+{
+ int saved_errno;
+ char event;
+
+ saved_errno = errno;
+ event = 0;
+ if (signo == SIGTERM)
+ cancelled = 1;
+ if (notify_fd >= 0)
+ (void)write(notify_fd, &event, sizeof(event));
+ errno = saved_errno;
+}
+
+static long long uptime_ms(void)
+{
+ struct timespec now;
+
+#ifdef CLOCK_BOOTTIME
+ clock_gettime(CLOCK_BOOTTIME, &now);
+#else
+ clock_gettime(CLOCK_MONOTONIC, &now);
+#endif
+ return (long long)now.tv_sec * MSEC_PER_SEC + now.tv_nsec / NSEC_PER_MSEC;
+}
+
+static int pipe_create(int descriptors[2])
+{
+ int i;
+
+ if (pipe(descriptors))
+ return -1;
+ for (i = 0; i < 2; i++) {
+ if (fcntl(descriptors[i], F_SETFD, FD_CLOEXEC) < 0 ||
+ fcntl(descriptors[i], F_SETFL, O_NONBLOCK) < 0) {
+ close(descriptors[0]);
+ close(descriptors[1]);
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static int helper_exchange(const char *path, const char *operation,
+ const char *request, char *response)
+{
+ struct sigaction action, old_child, old_term, old_pipe;
+ struct pollfd descriptors[3];
+ int input[2], output[2], notification[2];
+ size_t written, received, request_length;
+ long long deadline, remaining;
+ int finished, status, timeout, ok;
+ char events[HELPER_MESSAGE_SIZE];
+ ssize_t count;
+ pid_t child;
+
+ if (pipe_create(input))
+ return -1;
+ if (pipe_create(output)) {
+ close(input[0]);
+ close(input[1]);
+ return -1;
+ }
+ if (pipe_create(notification)) {
+ close(input[0]);
+ close(input[1]);
+ close(output[0]);
+ close(output[1]);
+ return -1;
+ }
+ memset(&action, 0, sizeof(action));
+ sigemptyset(&action.sa_mask);
+ action.sa_handler = child_notify;
+ notify_fd = notification[1];
+ cancelled = 0;
+ sigaction(SIGCHLD, &action, &old_child);
+ sigaction(SIGTERM, &action, &old_term);
+ action.sa_handler = SIG_IGN;
+ sigaction(SIGPIPE, &action, &old_pipe);
+ child = fork();
+ if (child == 0) {
+ dup2(input[0], STDIN_FILENO);
+ dup2(output[1], STDOUT_FILENO);
+ fcntl(STDIN_FILENO, F_SETFL, 0);
+ fcntl(STDOUT_FILENO, F_SETFL, 0);
+ execl(path, path, operation, (char *)NULL);
+ _exit(127);
+ }
+ close(input[0]);
+ close(output[1]);
+ descriptors[0].fd = input[1];
+ descriptors[0].events = POLLOUT;
+ descriptors[1].fd = output[0];
+ descriptors[1].events = POLLIN;
+ descriptors[2].fd = notification[0];
+ descriptors[2].events = POLLIN;
+ request_length = strlen(request);
+ deadline = service_ctx.helper_timeout_ms ? uptime_ms() + service_ctx.helper_timeout_ms : 0;
+ written = received = 0;
+ finished = status = ok = 0;
+ while (child > 0 && !cancelled) {
+ if (!finished && waitpid(child, &status, WNOHANG) == child)
+ finished = 1;
+ if (finished && descriptors[1].fd < 0) {
+ ok = WIFEXITED(status) && WEXITSTATUS(status) == 0;
+ break;
+ }
+ remaining = deadline ? deadline - uptime_ms() : -1;
+ if (deadline && remaining <= 0)
+ break;
+ timeout = remaining;
+ if (poll(descriptors, sizeof(descriptors) / sizeof(descriptors[0]), timeout) < 0) {
+ if (errno == EINTR)
+ continue;
+ break;
+ }
+ if (descriptors[2].revents)
+ (void)read(notification[0], events, sizeof(events));
+ if (descriptors[0].fd >= 0 && descriptors[0].revents) {
+ count = write(descriptors[0].fd, request + written, request_length - written);
+ if (count > 0)
+ written += count;
+ if (written == request_length || (count < 0 && errno != EAGAIN && errno != EINTR)) {
+ close(descriptors[0].fd);
+ descriptors[0].fd = -1;
+ }
+ }
+ if (descriptors[1].fd < 0 || !descriptors[1].revents)
+ continue;
+ count = read(descriptors[1].fd, response + received, HELPER_MESSAGE_SIZE - received);
+ if (count > 0) {
+ received += count;
+ if (received == HELPER_MESSAGE_SIZE)
+ break;
+ } else if (count == 0) {
+ close(descriptors[1].fd);
+ descriptors[1].fd = -1;
+ } else if (errno != EAGAIN && errno != EINTR) {
+ break;
+ }
+ }
+ if (child > 0 && !finished) {
+ kill(child, SIGKILL);
+ while (waitpid(child, &status, 0) < 0 && errno == EINTR)
+ ;
+ }
+ if (descriptors[0].fd >= 0)
+ close(descriptors[0].fd);
+ if (descriptors[1].fd >= 0)
+ close(descriptors[1].fd);
+ notify_fd = -1;
+ close(notification[0]);
+ close(notification[1]);
+ sigaction(SIGCHLD, &old_child, NULL);
+ sigaction(SIGTERM, &old_term, NULL);
+ sigaction(SIGPIPE, &old_pipe, NULL);
+ response[received] = '\0';
+ return ok ? 0 : -1;
+}
+
+enum helper_status helper_call(const char *path, const char *operation,
+ json_object *data, json_object **result)
+{
+ static const char *statuses[] = { "ok", "unsupported", "not_found", "invalid", "busy", "failed" };
+ char response[HELPER_MESSAGE_SIZE + 1];
+ struct json_tokener *tokener;
+ json_object *request, *reply, *value;
+ const char *request_text;
+ enum helper_status status;
+ size_t i;
+
+ *result = NULL;
+ if (!path || !*path)
+ return HELPER_UNSUPPORTED;
+ request = json_object_new_object();
+ json_object_object_add(request, "version", json_object_new_int(1));
+ json_object_object_add(request, "operation", json_object_new_string(operation));
+ json_object_object_add(request, "data", json_object_get(data));
+ request_text = json_object_to_json_string_ext(request, JSON_C_TO_STRING_PLAIN);
+ status = HELPER_FAILED;
+ if (strlen(request_text) >= HELPER_MESSAGE_SIZE ||
+ helper_exchange(path, operation, request_text, response)) {
+ json_object_put(request);
+ return status;
+ }
+ json_object_put(request);
+ tokener = json_tokener_new();
+ json_tokener_set_flags(tokener, JSON_TOKENER_STRICT);
+ reply = json_tokener_parse_ex(tokener, response, strlen(response) + 1);
+ if (json_tokener_get_error(tokener) != json_tokener_success ||
+ !json_object_is_type(reply, json_type_object))
+ goto out;
+ if (!json_object_object_get_ex(reply, "version", &value) ||
+ !json_object_is_type(value, json_type_int) || json_object_get_int(value) != 1)
+ goto out;
+ if (!json_object_object_get_ex(reply, "status", &value) ||
+ !json_object_is_type(value, json_type_string))
+ goto out;
+ for (i = 0; i < sizeof(statuses) / sizeof(statuses[0]); i++)
+ if (!strcmp(json_object_get_string(value), statuses[i]))
+ status = i;
+ if (status == HELPER_OK) {
+ if (!json_object_object_get_ex(reply, "data", &value) ||
+ !json_object_is_type(value, json_type_object))
+ status = HELPER_FAILED;
+ else
+ *result = json_object_get(value);
+ }
+out:
+ json_object_put(reply);
+ json_tokener_free(tokener);
+ return status;
+}
+
+int helper_fault(const char *service, enum helper_status status)
+{
+ if (status == HELPER_UNSUPPORTED)
+ return send_action_not_supported_fault((char *)service);
+ if (status == HELPER_NOT_FOUND)
+ return send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoConfig",
+ "Unknown token", "The requested configuration does not exist");
+ if (status == HELPER_INVALID)
+ return send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:ConfigModify",
+ "Invalid settings", "The requested settings are not supported");
+ return send_action_failed_fault((char *)service, status);
+}
--- /dev/null
+++ b/control_helper.h
@@ -0,0 +1,20 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#ifndef CONTROL_HELPER_H
+#define CONTROL_HELPER_H
+
+#include <json-c/json.h>
+
+enum helper_status {
+ HELPER_OK,
+ HELPER_UNSUPPORTED,
+ HELPER_NOT_FOUND,
+ HELPER_INVALID,
+ HELPER_BUSY,
+ HELPER_FAILED
+};
+
+enum helper_status helper_call(const char *path, const char *operation,
+ json_object *data, json_object **result);
+int helper_fault(const char *service, enum helper_status status);
+
+#endif
--- a/onvif_simple_server.h
+++ b/onvif_simple_server.h
@@ -144,6 +144,9 @@ typedef struct {
int source_height;
int source_framerate;
int source_framerate_den;
+ int helper_timeout_ms;
+ char *encoder_helper;
+ char *imaging_helper;
char **scopes;
int scopes_num;
--- /dev/null
+++ b/test/test_helper.c
@@ -0,0 +1,27 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "control_helper.h"
+#include "onvif_simple_server.h"
+
+service_context_t service_ctx;
+
+int main(int argc, char **argv)
+{
+ json_object *data;
+ json_object *result;
+ enum helper_status status;
+
+ if (argc != 4)
+ return 1;
+ service_ctx.helper_timeout_ms = atoi(argv[3]);
+ data = json_object_new_object();
+ json_object_object_add(data, "value", json_object_new_string(";$(false) & quoted ' data"));
+ status = helper_call(argv[1], argv[2], data, &result);
+ printf("%d\n", status);
+ if (result)
+ puts(json_object_to_json_string_ext(result, JSON_C_TO_STRING_PLAIN));
+ json_object_put(data);
+ json_object_put(result);
+ return 0;
+}
--- /dev/null
+++ b/test/test_helper.py
@@ -0,0 +1,40 @@
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+
+with tempfile.TemporaryDirectory() as directory:
+ helper = Path(directory) / 'control helper; literal'
+ helper.write_text('''#!/usr/bin/env python3
+import json, os, sys, time
+request = json.load(sys.stdin)
+assert request['version'] == 1
+assert request['operation'] == sys.argv[1]
+operation = sys.argv[1]
+if operation == 'oversized':
+ print('x' * 20000)
+elif operation == 'malformed':
+ print('{} trailing')
+elif operation == 'timeout':
+ time.sleep(60)
+elif operation == 'exit':
+ sys.exit(1)
+else:
+ status = 'invalid' if operation == 'invalid' else 'ok'
+ print(json.dumps({'version': 1, 'status': status, 'data': request['data']}))
+ if operation == 'close':
+ sys.stdout.flush()
+ os.close(1)
+ time.sleep(0.01)
+''')
+ helper.chmod(0o700)
+ for operation, expected in [('echo', 0), ('invalid', 3), ('malformed', 5),
+ ('oversized', 5), ('timeout', 5), ('exit', 5),
+ ('close', 0)]:
+ timeout = '50' if operation == 'timeout' else '1000'
+ result = subprocess.check_output(['./test/test_helper', str(helper), operation,
+ timeout], timeout=3).decode().splitlines()
+ assert int(result[0]) == expected, (operation, result)
+ if expected == 0:
+ assert json.loads(result[1])['value'] == ";$(false) & quoted ' data"
+print('External helper transport: 7 passed')
@@ -0,0 +1,855 @@
From 135cec8b6b04670f0c533150d35eee0a267721bd Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 10:57:48 +0100
Subject: [PATCH 09/15] feat: delegate encoder configuration to external
helpers
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
CONTROL_HELPERS.md | 30 +++
Makefile | 3 +-
Makefile.static | 3 +-
encoder_control.c | 522 ++++++++++++++++++++++++++++++++++++++++
encoder_control.h | 7 +
media_profiles.c | 14 +-
media_profiles.h | 2 +
onvif_simple_server.c | 6 +
onvif_simple_server.h | 1 +
test/control_fixture.py | 29 +++
test/test_cgi.py | 72 ++++++
11 files changed, 683 insertions(+), 6 deletions(-)
create mode 100644 encoder_control.c
create mode 100644 encoder_control.h
create mode 100644 test/control_fixture.py
--- a/CONTROL_HELPERS.md
+++ b/CONTROL_HELPERS.md
@@ -26,3 +26,33 @@ Operation-specific encoder and imaging c
their service implementations. A helper is responsible for serialising
changes to shared camera resources and for returning success only after a
change is applied. The server does not commit its generated configuration.
+
+## Encoder operations
+
+`get` receives `tokens`, an array of configured encoder tokens. Return
+`revision` and `profiles`, exactly one full configuration per requested token.
+Each entry contains `token`, `type` (`JPEG`, `H264`, `H265`), integer `width`,
+`height`, `bitrate` (kbps), numeric `frame_rate` (fps) and `quality`.
+Interframe codecs also require `gov_length` and `encoding_profile`.
+`encoding_interval` is optional and defaults to the configured interval.
+These live values replace metadata for the current request only. An
+`unsupported` get retains static metadata; other errors produce SOAP faults.
+
+`options` receives optional `token` and `profile_token` filters. Return
+`revision` and an `options` array. Each codec entry contains `type`,
+`resolutions` (objects with `width` and `height`), `frame_rates` (descending
+positive fps), `quality`, `bitrate`, `encoding_interval` and, for interframe
+codecs, `gov_length` and `encoding_profiles`. Ranges are objects with `min`
+and `max`. Integer ONVIF ranges require integral endpoints. Encoding profiles
+use ONVIF spelling, such as `Baseline`, `Main`, `High`, `Main10`.
+Media1 accepts one entry per codec, in JPEG then H264 order, with the same
+integer quality range. Media2 accepts multiple entries per codec. Options
+must account for shared resources and the requested profile. `unsupported`
+retains the static, current-settings-only options.
+
+`set` receives `token`, `configuration` and `force_persistence`. Configuration
+uses the same fields as get, without token. Return `revision` and the complete
+effective `configuration` after applying it. Media1 persistence is always
+true, as required by the current Media specification; Media2 also persists
+encoder changes. Rejected changes must leave the camera unchanged. Setters
+remain unavailable when no encoder helper is configured.
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
# Set HAVE_WOLFSSL or HAVE_MBEDTLS variable if you want to use WOLFSSL or
# MBEDTLS instead of LIBTOMCRYPT
-OBJECTS_O = control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
+OBJECTS_O = encoder_control.o control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_N = onvif_notify_server.o conf.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_W = wsd_simple_server.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
ifdef HAVE_WOLFSSL
@@ -20,6 +20,7 @@ LIBS_N = -Wl,--gc-sections -ltomcrypt -l
endif
endif
LIBS_W = -Wl,--gc-sections
+LIBS_O += -lm
ifdef USE_ZLIB
DUSE_ZLIB = -DUSE_ZLIB
--- a/Makefile.static
+++ b/Makefile.static
@@ -1,7 +1,7 @@
# Set HAVE_WOLFSSL or HAVE_MBEDTLS variable if you want to use WOLFSSL or
# MBEDTLS instead of LIBTOMCRYPT
-OBJECTS_O = control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
+OBJECTS_O = encoder_control.o control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_N = onvif_notify_server.o conf.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_W = wsd_simple_server.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
ifdef HAVE_WOLFSSL
@@ -20,6 +20,7 @@ LIBS_N = -Wl,--gc-sections extras/libtom
endif
endif
LIBS_W = -Wl,--gc-sections
+LIBS_O += -lm
ifdef USE_ZLIB
DUSE_ZLIB = -DUSE_ZLIB
--- /dev/null
+++ b/encoder_control.c
@@ -0,0 +1,522 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include <limits.h>
+#include <math.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "control_helper.h"
+#include "encoder_control.h"
+#include "ezxml_wrapper.h"
+#include "media_profiles.h"
+#include "onvif_simple_server.h"
+#include "soap.h"
+#include "utils.h"
+
+extern service_context_t service_ctx;
+
+static int integer_get(json_object *object, const char *key, int *number, int minimum)
+{
+ json_object *value;
+ int64_t integer;
+
+ if (!json_object_object_get_ex(object, key, &value) ||
+ !json_object_is_type(value, json_type_int))
+ return -1;
+ integer = json_object_get_int64(value);
+ if (integer < minimum || integer > INT_MAX)
+ return -1;
+ *number = integer;
+ return 0;
+}
+
+static int number_get(json_object *object, const char *key, double *number)
+{
+ json_object *value;
+
+ if (!json_object_object_get_ex(object, key, &value) ||
+ (!json_object_is_type(value, json_type_double) &&
+ !json_object_is_type(value, json_type_int)))
+ return -1;
+ *number = json_object_get_double(value);
+ return isfinite(*number) ? 0 : -1;
+}
+
+static int profile_update(stream_profile_t *profile, json_object *object)
+{
+ stream_profile_t candidate;
+ json_object *value;
+ const char *codec;
+ const char *encoding_profile;
+
+ candidate = *profile;
+ if (!json_object_object_get_ex(object, "type", &value) ||
+ !json_object_is_type(value, json_type_string))
+ return -1;
+ codec = json_object_get_string(value);
+ if (!strcmp(codec, "H264"))
+ candidate.type = H264;
+ else if (!strcmp(codec, "H265"))
+ candidate.type = H265;
+ else if (!strcmp(codec, "JPEG"))
+ candidate.type = JPEG;
+ else
+ return -1;
+ if (integer_get(object, "width", &candidate.width, 1) ||
+ integer_get(object, "height", &candidate.height, 1) ||
+ integer_get(object, "bitrate", &candidate.bitrate, 0) ||
+ number_get(object, "frame_rate", &candidate.frame_rate) ||
+ candidate.frame_rate <= 0 || candidate.frame_rate > INT_MAX ||
+ number_get(object, "quality", &candidate.quality) || candidate.quality < 0)
+ return -1;
+ encoding_profile = profile->encoding_profile;
+ if (candidate.type != JPEG) {
+ if (integer_get(object, "gov_length", &candidate.gov_length, 1) ||
+ !json_object_object_get_ex(object, "encoding_profile", &value) ||
+ !json_object_is_type(value, json_type_string))
+ return -1;
+ encoding_profile = json_object_get_string(value);
+ if (candidate.type == H264 && strcmp(encoding_profile, "Baseline") &&
+ strcmp(encoding_profile, "Main") && strcmp(encoding_profile, "High") &&
+ strcmp(encoding_profile, "Extended"))
+ return -1;
+ if (candidate.type == H265 && strcmp(encoding_profile, "Main") &&
+ strcmp(encoding_profile, "Main10"))
+ return -1;
+ }
+ if (json_object_object_get_ex(object, "encoding_interval", &value) &&
+ integer_get(object, "encoding_interval", &candidate.encoding_interval, 1))
+ return -1;
+ candidate.encoding_profile = strdup(encoding_profile);
+ if (!candidate.encoding_profile)
+ return -1;
+ free(profile->encoding_profile);
+ *profile = candidate;
+ return 0;
+}
+
+static int revision_valid(json_object *data)
+{
+ json_object *value;
+
+ return json_object_object_get_ex(data, "revision", &value) &&
+ json_object_is_type(value, json_type_string) && *json_object_get_string(value);
+}
+
+static int range_get(json_object *object, const char *key, double *minimum,
+ double *maximum, int integer)
+{
+ json_object *range;
+
+ if (!json_object_object_get_ex(object, key, &range) ||
+ number_get(range, "min", minimum) || number_get(range, "max", maximum) ||
+ *minimum < 0 || *maximum < *minimum || *maximum > INT_MAX ||
+ (integer && (*minimum != (int)*minimum || *maximum != (int)*maximum)))
+ return -1;
+ return 0;
+}
+
+static int option_add(ezxml_t response, ezxml_t common, json_object *object, int version)
+{
+ json_object *value, *entries, *entry;
+ const char *codec;
+ const char *profile;
+ char numbers[MAX_LEN];
+ char profiles[MAX_LEN];
+ ezxml_t options;
+ ezxml_t encoder;
+ ezxml_t resolution;
+ double minimum;
+ double maximum;
+ double rate;
+ double previous;
+ size_t used;
+ size_t i;
+ int width;
+ int height;
+ int written;
+
+ if (!json_object_object_get_ex(object, "type", &value) ||
+ !json_object_is_type(value, json_type_string))
+ return -1;
+ codec = json_object_get_string(value);
+ if (strcmp(codec, "JPEG") && strcmp(codec, "H264") && strcmp(codec, "H265"))
+ return -1;
+ if (version == 1 && !strcmp(codec, "H265"))
+ return 0;
+ options = version == 1 ? common : soap_member_add(response, version, "Options");
+ if (range_get(object, "quality", &minimum, &maximum, version == 1))
+ return -1;
+ if (version == 2)
+ soap_child_add(options, "tt:Encoding", codec);
+ if (version == 2 || !options->child)
+ soap_range_add(options, "tt:QualityRange", minimum, maximum);
+ else {
+ snprintf(numbers, sizeof(numbers), "%.9g", minimum);
+ if (strcmp(get_element_in_element("Min", options->child), numbers))
+ return -1;
+ snprintf(numbers, sizeof(numbers), "%.9g", maximum);
+ if (strcmp(get_element_in_element("Max", options->child), numbers))
+ return -1;
+ }
+ encoder = options;
+ if (version == 1) {
+ snprintf(numbers, sizeof(numbers), "tt:%s", codec);
+ if (get_element_in_element_ptr(codec, options))
+ return -1;
+ encoder = soap_child_add(options, numbers, NULL);
+ }
+ if (!json_object_object_get_ex(object, "resolutions", &entries) ||
+ !json_object_is_type(entries, json_type_array) || !json_object_array_length(entries))
+ return -1;
+ for (i = 0; i < json_object_array_length(entries); i++) {
+ entry = json_object_array_get_idx(entries, i);
+ if (integer_get(entry, "width", &width, 1) || integer_get(entry, "height", &height, 1))
+ return -1;
+ resolution = soap_child_add(encoder, "tt:ResolutionsAvailable", NULL);
+ soap_number_add(resolution, "tt:Width", width);
+ soap_number_add(resolution, "tt:Height", height);
+ }
+ if (strcmp(codec, "JPEG")) {
+ if (range_get(object, "gov_length", &minimum, &maximum, 1) || minimum < 1)
+ return -1;
+ if (version == 1)
+ soap_range_add(encoder, "tt:GovLengthRange", minimum, maximum);
+ else {
+ snprintf(numbers, sizeof(numbers), "%.0f %.0f", minimum, maximum);
+ ezxml_set_attr_d(options, "GovLengthRange", numbers);
+ }
+ }
+ if (!json_object_object_get_ex(object, "frame_rates", &entries) ||
+ !json_object_is_type(entries, json_type_array) || !json_object_array_length(entries))
+ return -1;
+ used = 0;
+ previous = INT_MAX;
+ maximum = 0;
+ minimum = INT_MAX;
+ for (i = 0; i < json_object_array_length(entries); i++) {
+ entry = json_object_array_get_idx(entries, i);
+ if (!json_object_is_type(entry, json_type_int) &&
+ !json_object_is_type(entry, json_type_double))
+ return -1;
+ rate = json_object_get_double(entry);
+ if (!isfinite(rate) || rate <= 0 || rate > previous)
+ return -1;
+ previous = rate;
+ if (ceil(rate) > maximum)
+ maximum = ceil(rate);
+ if (ceil(rate) < minimum)
+ minimum = ceil(rate);
+ written = snprintf(numbers + used, sizeof(numbers) - used, "%s%.9g", i ? " " : "", rate);
+ if (written < 0 || (size_t)written >= sizeof(numbers) - used)
+ return -1;
+ used += written;
+ }
+ if (version == 1) {
+ soap_range_add(encoder, "tt:FrameRateRange", minimum, maximum);
+ if (range_get(object, "encoding_interval", &minimum, &maximum, 1) || minimum < 1)
+ return -1;
+ soap_range_add(encoder, "tt:EncodingIntervalRange", minimum, maximum);
+ } else {
+ ezxml_set_attr_d(options, "FrameRatesSupported", numbers);
+ if (range_get(object, "bitrate", &minimum, &maximum, 1))
+ return -1;
+ soap_range_add(encoder, "tt:BitrateRange", minimum, maximum);
+ }
+ if (!strcmp(codec, "JPEG"))
+ return 0;
+ if (!json_object_object_get_ex(object, "encoding_profiles", &entries) ||
+ !json_object_is_type(entries, json_type_array) || !json_object_array_length(entries))
+ return -1;
+ used = 0;
+ for (i = 0; i < json_object_array_length(entries); i++) {
+ entry = json_object_array_get_idx(entries, i);
+ if (!json_object_is_type(entry, json_type_string))
+ return -1;
+ profile = json_object_get_string(entry);
+ if (!strcmp(codec, "H264") && strcmp(profile, "Baseline") &&
+ strcmp(profile, "Main") && strcmp(profile, "High") && strcmp(profile, "Extended"))
+ return -1;
+ if (!strcmp(codec, "H265") && strcmp(profile, "Main") && strcmp(profile, "Main10"))
+ return -1;
+ if (version == 1)
+ soap_child_add(encoder, "tt:H264ProfilesSupported", profile);
+ written = snprintf(profiles + used, sizeof(profiles) - used, "%s%s", i ? " " : "", profile);
+ if (written < 0 || (size_t)written >= sizeof(profiles) - used)
+ return -1;
+ used += written;
+ }
+ if (version == 2)
+ ezxml_set_attr_d(options, "ProfilesSupported", profiles);
+ return 0;
+}
+
+static enum helper_status encoder_options(int version)
+{
+ json_object *request, *reply, *entries;
+ const char *configuration_token;
+ const char *profile_token;
+ enum helper_status status;
+ ezxml_t response;
+ ezxml_t common;
+ size_t i;
+
+ configuration_token = get_element("ConfigurationToken", "Body");
+ profile_token = get_element("ProfileToken", "Body");
+ if ((configuration_token && media_profile_find(configuration_token, "_VideoEncoderToken") < 0) ||
+ (profile_token && media_profile_find(profile_token, "") < 0))
+ return HELPER_NOT_FOUND;
+ request = json_object_new_object();
+ if (configuration_token)
+ json_object_object_add(request, "token", json_object_new_string(configuration_token));
+ if (profile_token)
+ json_object_object_add(request, "profile_token", json_object_new_string(profile_token));
+ status = helper_call(service_ctx.encoder_helper, "options", request, &reply);
+ json_object_put(request);
+ if (status != HELPER_OK)
+ return status;
+ response = soap_response_create(version, "GetVideoEncoderConfigurationOptions");
+ common = version == 1 ? soap_member_add(response, version, "Options") : NULL;
+ status = HELPER_FAILED;
+ if (!revision_valid(reply) || !json_object_object_get_ex(reply, "options", &entries) ||
+ !json_object_is_type(entries, json_type_array) || !json_object_array_length(entries))
+ goto out;
+ for (i = 0; i < json_object_array_length(entries); i++)
+ if (option_add(response, common, json_object_array_get_idx(entries, i), version))
+ goto out;
+ if (common && !common->child) {
+ status = HELPER_UNSUPPORTED;
+ goto out;
+ }
+ soap_response_send(response);
+ response = NULL;
+ status = HELPER_OK;
+out:
+ if (response)
+ ezxml_free(response->parent->parent);
+ json_object_put(reply);
+ return status;
+}
+
+static enum helper_status encoder_refresh(void)
+{
+ stream_profile_t *profiles;
+ json_object *request, *tokens, *reply, *entries, *entry, *token;
+ enum helper_status status;
+ char name[MAX_LEN];
+ unsigned char *seen;
+ size_t i;
+ int index;
+
+ request = json_object_new_object();
+ tokens = json_object_new_array();
+ for (i = 0; i < (size_t)service_ctx.profiles_num; i++) {
+ snprintf(name, sizeof(name), "%s_VideoEncoderToken", service_ctx.profiles[i].name);
+ json_object_array_add(tokens, json_object_new_string(name));
+ }
+ json_object_object_add(request, "tokens", tokens);
+ status = helper_call(service_ctx.encoder_helper, "get", request, &reply);
+ json_object_put(request);
+ if (status != HELPER_OK)
+ return status;
+ profiles = NULL;
+ seen = NULL;
+ status = HELPER_FAILED;
+ if (!revision_valid(reply) || !json_object_object_get_ex(reply, "profiles", &entries) ||
+ !json_object_is_type(entries, json_type_array) ||
+ json_object_array_length(entries) != (size_t)service_ctx.profiles_num)
+ goto out;
+ profiles = calloc(service_ctx.profiles_num, sizeof(*profiles));
+ seen = calloc(service_ctx.profiles_num, sizeof(*seen));
+ if (service_ctx.profiles_num && (!profiles || !seen))
+ goto out;
+ for (i = 0; i < (size_t)service_ctx.profiles_num; i++) {
+ profiles[i] = service_ctx.profiles[i];
+ profiles[i].encoding_profile = strdup(service_ctx.profiles[i].encoding_profile);
+ if (!profiles[i].encoding_profile)
+ goto out;
+ }
+ for (i = 0; i < json_object_array_length(entries); i++) {
+ entry = json_object_array_get_idx(entries, i);
+ if (!json_object_object_get_ex(entry, "token", &token) ||
+ !json_object_is_type(token, json_type_string))
+ goto out;
+ index = media_profile_find(json_object_get_string(token), "_VideoEncoderToken");
+ if (index < 0 || seen[index] || profile_update(&profiles[index], entry))
+ goto out;
+ seen[index] = 1;
+ }
+ for (i = 0; i < (size_t)service_ctx.profiles_num; i++)
+ free(service_ctx.profiles[i].encoding_profile);
+ free(service_ctx.profiles);
+ service_ctx.profiles = profiles;
+ profiles = NULL;
+ status = HELPER_OK;
+out:
+ if (profiles)
+ for (i = 0; i < (size_t)service_ctx.profiles_num; i++)
+ free(profiles[i].encoding_profile);
+ free(profiles);
+ free(seen);
+ json_object_put(reply);
+ return status;
+}
+
+static int xml_number_add(json_object *object, const char *key,
+ ezxml_t node, const char *name, int integer)
+{
+ const char *text;
+ char *end;
+ double value;
+
+ text = get_element_in_element(name, node);
+ if (!text || !*text)
+ return -1;
+ value = strtod(text, &end);
+ if (*end || !isfinite(value) || value < 0 || value > INT_MAX ||
+ (integer && value != (int)value))
+ return -1;
+ json_object_object_add(object, key, integer ? json_object_new_int(value) :
+ json_object_new_double(value));
+ return 0;
+}
+
+static json_object *configuration_parse(ezxml_t node, int version)
+{
+ const char *encoding_profile;
+ const char *codec;
+ const char *gov;
+ json_object *object;
+ ezxml_t resolution;
+ ezxml_t rate;
+ ezxml_t h264;
+ char *end;
+ long length;
+
+ codec = get_element_in_element("Encoding", node);
+ resolution = get_element_in_element_ptr("Resolution", node);
+ rate = get_element_in_element_ptr("RateControl", node);
+ if (!codec || !resolution || !rate)
+ return NULL;
+ object = json_object_new_object();
+ json_object_object_add(object, "type", json_object_new_string(codec));
+ if (xml_number_add(object, "width", resolution, "Width", 1) ||
+ xml_number_add(object, "height", resolution, "Height", 1) ||
+ xml_number_add(object, "bitrate", rate, "BitrateLimit", 1) ||
+ xml_number_add(object, "frame_rate", rate, "FrameRateLimit", version == 1) ||
+ xml_number_add(object, "quality", node, "Quality", 0))
+ goto invalid;
+ if (version == 1 && xml_number_add(object, "encoding_interval", rate,
+ "EncodingInterval", 1))
+ goto invalid;
+ if (!strcmp(codec, "JPEG"))
+ return object;
+ h264 = get_element_in_element_ptr("H264", node);
+ if (version == 1) {
+ encoding_profile = get_element_in_element("H264Profile", h264);
+ if (strcmp(codec, "H264") || !encoding_profile ||
+ xml_number_add(object, "gov_length", h264, "GovLength", 1))
+ goto invalid;
+ } else {
+ encoding_profile = get_attribute(node, "Profile");
+ gov = get_attribute(node, "GovLength");
+ if (!gov || !*gov)
+ goto invalid;
+ length = strtol(gov, &end, 10);
+ if (*end || length < 1 || length > INT_MAX)
+ goto invalid;
+ json_object_object_add(object, "gov_length", json_object_new_int(length));
+ }
+ if (!encoding_profile)
+ goto invalid;
+ json_object_object_add(object, "encoding_profile", json_object_new_string(encoding_profile));
+ return object;
+invalid:
+ json_object_put(object);
+ return NULL;
+}
+
+static enum helper_status encoder_set(int version)
+{
+ stream_profile_t candidate;
+ json_object *request, *configuration, *reply, *effective;
+ const char *persistence;
+ const char *token;
+ enum helper_status status;
+ ezxml_t node;
+ int index;
+
+ node = get_element_ptr(NULL, "Configuration", "Body");
+ token = get_attribute(node, "token");
+ index = media_profile_find(token, "_VideoEncoderToken");
+ if (index < 0)
+ return HELPER_NOT_FOUND;
+ configuration = configuration_parse(node, version);
+ if (!configuration)
+ return HELPER_INVALID;
+ candidate = service_ctx.profiles[index];
+ candidate.encoding_profile = strdup(candidate.encoding_profile);
+ if (!candidate.encoding_profile) {
+ json_object_put(configuration);
+ return HELPER_FAILED;
+ }
+ if (profile_update(&candidate, configuration)) {
+ free(candidate.encoding_profile);
+ json_object_put(configuration);
+ return HELPER_INVALID;
+ }
+ free(candidate.encoding_profile);
+ request = json_object_new_object();
+ json_object_object_add(request, "token", json_object_new_string(token));
+ json_object_object_add(request, "configuration", configuration);
+ persistence = get_element("ForcePersistence", "Body");
+ if (persistence && strcmp(persistence, "true") && strcmp(persistence, "1") &&
+ strcmp(persistence, "false") && strcmp(persistence, "0")) {
+ json_object_put(request);
+ return HELPER_INVALID;
+ }
+ json_object_object_add(request, "force_persistence", json_object_new_boolean(1));
+ status = helper_call(service_ctx.encoder_helper, "set", request, &reply);
+ json_object_put(request);
+ if (status != HELPER_OK)
+ return status;
+ if (!revision_valid(reply) || !json_object_object_get_ex(reply, "configuration", &effective) ||
+ profile_update(&service_ctx.profiles[index], effective))
+ status = HELPER_FAILED;
+ json_object_put(reply);
+ return status;
+}
+
+int encoder_control_dispatch(const char *operation, int version)
+{
+ enum helper_status status;
+ const char *service;
+ int setter;
+
+ if (!service_ctx.encoder_helper)
+ return 0;
+ setter = !strcmp(operation, "SetVideoEncoderConfiguration");
+ if (!setter && strncmp(operation, "Get", strlen("Get")))
+ return 0;
+ service = version == 1 ? "media_service" : "media2_service";
+ if (!strcmp(operation, "GetVideoEncoderConfigurationOptions")) {
+ status = encoder_options(version);
+ if (status == HELPER_UNSUPPORTED)
+ return 0;
+ if (status != HELPER_OK)
+ helper_fault(service, status);
+ return 1;
+ }
+ if (setter) {
+ status = encoder_set(version);
+ if (status == HELPER_OK)
+ soap_response_send(soap_response_create(version, operation));
+ else
+ helper_fault(service, status);
+ return 1;
+ }
+ status = encoder_refresh();
+ if (status == HELPER_OK || status == HELPER_UNSUPPORTED)
+ return 0;
+ helper_fault(service, status);
+ return 1;
+}
--- /dev/null
+++ b/encoder_control.h
@@ -0,0 +1,7 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#ifndef ENCODER_CONTROL_H
+#define ENCODER_CONTROL_H
+
+int encoder_control_dispatch(const char *operation, int version);
+
+#endif
--- a/media_profiles.c
+++ b/media_profiles.c
@@ -1,5 +1,6 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include <stdio.h>
+#include <math.h>
#include <string.h>
#include "ezxml_wrapper.h"
@@ -11,6 +12,12 @@
extern service_context_t service_ctx;
+double media_profile_framerate(const stream_profile_t *profile)
+{
+ return profile->frame_rate > 0 ? profile->frame_rate :
+ (double)profile->framerate / profile->framerate_den;
+}
+
int media_profile_find(const char *token, const char *suffix)
{
char name[MAX_LEN];
@@ -54,7 +61,7 @@ void media_source_info(int *width, int *
*height = service_ctx.source_height ? service_ctx.source_height : source ? source->height : 0;
*framerate = service_ctx.source_framerate ?
(double)service_ctx.source_framerate / service_ctx.source_framerate_den :
- source ? (double)source->framerate / source->framerate_den : 0;
+ source ? media_profile_framerate(source) : 0;
}
void media_source_configuration_add(ezxml_t node)
@@ -102,9 +109,8 @@ static void encoder_configuration_add(ez
soap_number_add(node, "tt:Quality", profile->quality);
rate = soap_child_add(node, "tt:RateControl", NULL);
soap_number_add(rate, "tt:FrameRateLimit", version == 1 ?
- ((long long)profile->framerate + profile->framerate_den - 1) /
- profile->framerate_den :
- (double)profile->framerate / profile->framerate_den);
+ ceil(media_profile_framerate(profile)) :
+ media_profile_framerate(profile));
if (version == 1)
soap_number_add(rate, "tt:EncodingInterval", profile->encoding_interval);
soap_number_add(rate, "tt:BitrateLimit", profile->bitrate);
--- a/media_profiles.h
+++ b/media_profiles.h
@@ -3,9 +3,11 @@
#define MEDIA_PROFILES_H
#include "ezxml/ezxml.h"
+#include "onvif_simple_server.h"
int media_profiles_dispatch(const char *operation, int version);
int media_profile_find(const char *token, const char *suffix);
+double media_profile_framerate(const stream_profile_t *profile);
void media_source_info(int *width, int *height, double *framerate);
void media_source_configuration_add(ezxml_t node);
--- a/onvif_simple_server.c
+++ b/onvif_simple_server.c
@@ -28,6 +28,7 @@
#include "onvif_simple_server.h"
#include "device_service.h"
#include "media_service.h"
+#include "encoder_control.h"
#include "media_profiles.h"
#include "media_options.h"
#include "media2_service.h"
@@ -548,6 +549,8 @@ int main(int argc, char ** argv)
}
}
} else if (strcasecmp("media_service", prog_name) == 0) {
+ if (encoder_control_dispatch(method, 1))
+ goto response_done;
if (strcasecmp(method, "GetServiceCapabilities") == 0) {
media_get_service_capabilities();
} else if (strcasecmp(method, "GetVideoSources") == 0) {
@@ -634,6 +637,8 @@ int main(int argc, char ** argv)
}
}
} else if ((service_ctx.adv_enable_media2 == 1) && (strcasecmp("media2_service", prog_name) == 0)) {
+ if (encoder_control_dispatch(method, 2))
+ goto response_done;
if (strcasecmp(method, "GetServiceCapabilities") == 0) {
media2_get_service_capabilities();
} else if (strcasecmp(method, "GetProfiles") == 0) {
@@ -778,6 +783,7 @@ int main(int argc, char ** argv)
}
}
+response_done:
close_xml();
free_conf_file();
--- a/onvif_simple_server.h
+++ b/onvif_simple_server.h
@@ -62,6 +62,7 @@ typedef struct {
int bitrate; /* kbps, 0 = unknown */
int framerate; /* fps, 0 = unknown */
int framerate_den;
+ double frame_rate;
int gov_length;
int encoding_interval;
double quality;
--- /dev/null
+++ b/test/control_fixture.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python3
+import json
+from pathlib import Path
+import sys
+
+path = Path(__file__).with_suffix('.json')
+state = json.loads(path.read_text())
+request = json.load(sys.stdin)
+assert request['version'] == 1
+assert request['operation'] == sys.argv[1]
+data = request['data']
+operation = request['operation']
+status = state.get('status', 'ok')
+result = {'revision': state.get('revision', 'test-revision')}
+if operation == 'get':
+ result['profiles'] = state.get('profiles', [])
+elif operation == 'options':
+ result['options'] = state.get('options', [])
+elif operation == 'set':
+ state['last_set'] = data
+ configuration = data['configuration']
+ for profile in state.get('profiles', []):
+ if profile['token'] == data['token']:
+ profile.update(configuration)
+ path.write_text(json.dumps(state))
+ result['configuration'] = configuration
+if state.get('bad_reply'):
+ result = {}
+print(json.dumps({'version': 1, 'status': status, 'data': result}))
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -1,4 +1,5 @@
import json
+from contextlib import contextmanager
import os
from pathlib import Path
import subprocess
@@ -51,7 +52,78 @@ def request(service, operation, content=
return status, ET.fromstring(xml)
+@contextmanager
+def helper_configuration():
+ with tempfile.TemporaryDirectory() as directory:
+ helper = Path(directory) / 'helper.py'
+ helper.write_text((ROOT / 'test/control_fixture.py').read_text())
+ helper.chmod(0o755)
+ config = configuration(4)
+ config['encoder_helper'] = str(helper)
+ state = {'profiles': [dict(token=f'Profile_{i}_VideoEncoderToken',
+ type='H264', width=640, height=480,
+ frame_rate=29.97, bitrate=4567, quality=37,
+ gov_length=57, encoding_profile='Baseline')
+ for i in range(4)],
+ 'options': [dict(type='H264', quality={'min': 1, 'max': 100},
+ resolutions=[{'width': 640, 'height': 480},
+ {'width': 1920, 'height': 1080}],
+ frame_rates=[30, 25, 15],
+ encoding_profiles=['Baseline', 'Main', 'High'],
+ encoding_interval={'min': 1, 'max': 1},
+ gov_length={'min': 1, 'max': 120},
+ bitrate={'min': 100, 'max': 16000})]}
+ path = helper.with_suffix('.json')
+ path.write_text(json.dumps(state))
+ yield config, path
+
+
class CGITests(unittest.TestCase):
+ def test_encoder_helper_get_options_set(self):
+ with helper_configuration() as (config, path):
+ for service in ['media', 'media2']:
+ status, root = request(service, 'GetProfiles', '<Type>All</Type>', config)
+ self.assertEqual(status, 200)
+ self.assertEqual(root.findtext('.//tt:BitrateLimit', namespaces=NS), '4567')
+ expected = 30 if service == 'media' else 29.97
+ self.assertEqual(float(root.findtext('.//tt:FrameRateLimit', namespaces=NS)), expected)
+ status, root = request(service, 'GetVideoEncoderConfigurationOptions', config=config)
+ self.assertEqual(status, 200)
+ self.assertEqual(len(root.findall('.//tt:ResolutionsAvailable', NS)), 2)
+ status, root = request('media2', 'GetVideoEncoderConfigurations',
+ '<ConfigurationToken>Profile_3_VideoEncoderToken'
+ '</ConfigurationToken>', config)
+ node = root.find('.//tr2:Configurations', NS)
+ node.tag = 'Configuration'
+ node.find('tt:Resolution/tt:Width', NS).text = '1280'
+ status, root = request('media2', 'SetVideoEncoderConfiguration', ET.tostring(node).decode(), config)
+ self.assertEqual(status, 200)
+ state = json.loads(path.read_text())
+ self.assertEqual(state['last_set']['token'], 'Profile_3_VideoEncoderToken')
+ self.assertEqual(state['last_set']['configuration']['width'], 1280)
+ self.assertEqual(state['profiles'][0]['width'], 640)
+ status, root = request('media2', 'GetVideoEncoderConfigurations',
+ '<ConfigurationToken>Profile_3_VideoEncoderToken'
+ '</ConfigurationToken>', config)
+ self.assertEqual(root.findtext('.//tt:Width', namespaces=NS), '1280')
+
+ def test_encoder_helper_failures(self):
+ with helper_configuration() as (config, path):
+ original = path.read_text()
+ for status in ['invalid', 'busy', 'failed', 'not_found']:
+ state = json.loads(original)
+ state['status'] = status
+ path.write_text(json.dumps(state))
+ code, root = request('media2', 'GetProfiles', config=config)
+ self.assertEqual(code, 500)
+ self.assertIsNotNone(root.find('.//s:Fault', NS))
+ state = json.loads(original)
+ state['bad_reply'] = True
+ path.write_text(json.dumps(state))
+ self.assertEqual(request('media2', 'GetProfiles', config=config)[0], 500)
+ path.write_text(original)
+ self.assertEqual(request('media2', 'SetVideoEncoderConfiguration',
+ '<Configuration token="missing"/>', config)[0], 500)
def test_operation_namespace(self):
status, root = request('media', 'GetProfiles', namespace='urn:unrelated')
self.assertEqual(status, 500)
@@ -0,0 +1,567 @@
From c4a92068a398c4e8dd8890d8db9b79b74cbe255e Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 11:09:38 +0100
Subject: [PATCH 11/15] fix: report capabilities for every configured video
profile
Keep profile limits, codec instance counts, options and sensor modes consistent with the configured streams and physical source.
Fixes: 2f098ae69cb6 ("feat: enumerate configured media profiles without a two-stream limit")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
Makefile | 2 +-
Makefile.static | 2 +-
device_advertisement.c | 2 +
media2_service.c | 78 +---------------------
media_capabilities.c | 143 +++++++++++++++++++++++++++++++++++++++++
media_capabilities.h | 11 ++++
media_options.c | 101 +++++++++++++++++++++++++++--
media_service.c | 34 +---------
test/test_cgi.py | 32 +++++++++
9 files changed, 292 insertions(+), 113 deletions(-)
create mode 100644 media_capabilities.c
create mode 100644 media_capabilities.h
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
# Set HAVE_WOLFSSL or HAVE_MBEDTLS variable if you want to use WOLFSSL or
# MBEDTLS instead of LIBTOMCRYPT
-OBJECTS_O = device_advertisement.o imaging_service.o encoder_control.o control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
+OBJECTS_O = media_capabilities.o device_advertisement.o imaging_service.o encoder_control.o control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_N = onvif_notify_server.o conf.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_W = wsd_simple_server.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
ifdef HAVE_WOLFSSL
--- a/Makefile.static
+++ b/Makefile.static
@@ -1,7 +1,7 @@
# Set HAVE_WOLFSSL or HAVE_MBEDTLS variable if you want to use WOLFSSL or
# MBEDTLS instead of LIBTOMCRYPT
-OBJECTS_O = device_advertisement.o imaging_service.o encoder_control.o control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
+OBJECTS_O = media_capabilities.o device_advertisement.o imaging_service.o encoder_control.o control_helper.o media_options.o soap.o media_profiles.o onvif_simple_server.o device_service.o media_service.o media2_service.o ptz_service.o events_service.o deviceio_service.o fault.o conf.o utils_zlib.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_N = onvif_notify_server.o conf.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
OBJECTS_W = wsd_simple_server.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o
ifdef HAVE_WOLFSSL
--- a/device_advertisement.c
+++ b/device_advertisement.c
@@ -5,6 +5,7 @@
#include "device_advertisement.h"
#include "ezxml_wrapper.h"
#include "fault.h"
+#include "media_capabilities.h"
#include "onvif_simple_server.h"
#include "soap.h"
#include "utils.h"
@@ -152,6 +153,7 @@ int device_advertisement_send(int servic
return send_action_failed_fault("device_service", -1);
}
template_fill(envelope, values);
+ media_capabilities_update(envelope);
response = envelope->child->child;
if (service_ctx.imaging_helper) {
ezxml_set_attr(envelope, "xmlns:timg", "http://www.onvif.org/ver20/imaging/wsdl");
--- a/media2_service.c
+++ b/media2_service.c
@@ -19,6 +19,7 @@
#include "media2_service.h"
#include "conf.h"
+#include "media_capabilities.h"
#include "fault.h"
#include "utils.h"
#include "log.h"
@@ -28,89 +29,16 @@
extern service_context_t service_ctx;
-/*
- * The ONVIF VideoSource models the physical sensor, which is independent of any
- * single encoder profile. Report it from the profile with the largest frame area
- * so a low resolution sub stream never shrinks the advertised source dimensions.
- */
-static int get_video_source_index()
-{
- int i, idx = 0;
- long best = -1;
-
- for (i = 0; i < service_ctx.profiles_num; i++) {
- long area = (long) service_ctx.profiles[i].width * service_ctx.profiles[i].height;
- if (area > best) {
- best = area;
- idx = i;
- }
- }
-
- return idx;
-}
int media2_get_service_capabilities()
{
- char cap[256];
-
- cap[0] = '\0';
- snprintf(cap + strlen(cap), sizeof(cap) - strlen(cap), "%s", "VideoSource VideoEncoder");
- if ((service_ctx.profiles[0].audio_encoder != AUDIO_NONE) ||
- ((service_ctx.profiles_num == 2) && (service_ctx.profiles[1].audio_encoder != AUDIO_NONE))) {
-
- snprintf(cap + strlen(cap), sizeof(cap) - strlen(cap), "%s", " AudioSource AudioEncoder");
- }
- if ((service_ctx.profiles[0].audio_decoder != AUDIO_NONE) ||
- ((service_ctx.profiles_num == 2) && (service_ctx.profiles[1].audio_decoder != AUDIO_NONE))) {
-
- snprintf(cap + strlen(cap), sizeof(cap) - strlen(cap), "%s", " AudioOutput AudioDecoder");
- }
- if (service_ctx.ptz_node.enable == 1) {
- snprintf(cap + strlen(cap), sizeof(cap) - strlen(cap), "%s", " PTZ");
- }
-
- long size = cat(NULL, "media2_service_files/GetServiceCapabilities.xml", 2,
- "%CAPABILITIES%", cap);
-
- output_http_headers(size);
-
- return cat("stdout", "media2_service_files/GetServiceCapabilities.xml", 2,
- "%CAPABILITIES%", cap);
+ return media_capabilities_send(2);
}
int media2_get_video_source_modes()
{
- const char *token = get_element("VideoSourceToken", "Body");
- char stmp_w[16], stmp_h[16], video_enc[16];
-
- if (strcasecmp("VideoSourceToken", token) == 0) {
-
- // Get data from the largest profile (the physical source)
- char stmp_fps[8];
- int vsrc = get_video_source_index();
- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[vsrc].width);
- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[vsrc].height);
- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[vsrc].framerate);
- set_video_codec(video_enc, 16, service_ctx.profiles[vsrc].type, 2);
- long size = cat(NULL, "media2_service_files/GetVideoSourceModes.xml", 8,
- "%WIDTH%", stmp_w,
- "%HEIGHT%", stmp_h,
- "%VIDEO_ENCODING%", video_enc,
- "%FRAMERATE%", stmp_fps);
-
- output_http_headers(size);
-
- return cat("stdout", "media2_service_files/GetVideoSourceModes.xml", 8,
- "%WIDTH%", stmp_w,
- "%HEIGHT%", stmp_h,
- "%VIDEO_ENCODING%", video_enc,
- "%FRAMERATE%", stmp_fps);
-
- } else {
- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoVideoSource", "No video source", "The requested video source does not exist");
- return -1;
- }
+ return media_source_modes_send();
}
--- /dev/null
+++ b/media_capabilities.c
@@ -0,0 +1,143 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#include <stdio.h>
+#include <string.h>
+
+#include "ezxml_wrapper.h"
+#include "fault.h"
+#include "media_capabilities.h"
+#include "media_profiles.h"
+#include "onvif_simple_server.h"
+#include "soap.h"
+#include "utils.h"
+
+extern service_context_t service_ctx;
+
+void media_capabilities_update(ezxml_t node)
+{
+ char configurations[MAX_LEN];
+ char number[32];
+ const char *namespace;
+ ezxml_t child;
+ int snapshot;
+ int input;
+ int output;
+ int count;
+ int i;
+
+ namespace = xml_namespace_get(node);
+ snapshot = 0;
+ input = 0;
+ output = 0;
+ count = 0;
+ for (i = 0; i < service_ctx.profiles_num; i++) {
+ snapshot |= service_ctx.profiles[i].snapurl && *service_ctx.profiles[i].snapurl;
+ input |= service_ctx.profiles[i].audio_encoder != AUDIO_NONE;
+ output |= service_ctx.profiles[i].audio_decoder != AUDIO_NONE;
+ count += !namespace || strcmp(namespace, "http://www.onvif.org/ver10/media/wsdl") ||
+ service_ctx.profiles[i].type != H265;
+ }
+ if (ezxml_attr(node, "MaximumNumberOfProfiles")) {
+ snprintf(number, sizeof(number), "%d", count);
+ ezxml_set_attr_d(node, "MaximumNumberOfProfiles", number);
+ }
+ if (ezxml_attr(node, "ConfigurationsSupported")) {
+ snprintf(configurations, sizeof(configurations), "VideoSource VideoEncoder%s%s%s",
+ input ? " AudioSource AudioEncoder" : "",
+ output ? " AudioOutput AudioDecoder" : "",
+ service_ctx.ptz_node.enable ? " PTZ" : "");
+ ezxml_set_attr_d(node, "ConfigurationsSupported", configurations);
+ }
+ if (ezxml_attr(node, "SnapshotUri"))
+ ezxml_set_attr(node, "SnapshotUri", snapshot ? "true" : "false");
+ if (ezxml_attr(node, "WebRTC"))
+ ezxml_set_attr(node, "WebRTC", "0");
+ for (child = node->child; child; child = child->ordered)
+ media_capabilities_update(child);
+}
+
+int media_capabilities_send(int version)
+{
+ ezxml_t envelope;
+
+ envelope = ezxml_parse_file(version == 1 ? "media_service_files/GetServiceCapabilities.xml" :
+ "media2_service_files/GetServiceCapabilities.xml");
+ if (!envelope || *ezxml_error(envelope)) {
+ ezxml_free(envelope);
+ return send_action_failed_fault(version == 1 ? "media_service" : "media2_service", -1);
+ }
+ media_capabilities_update(envelope);
+ return soap_response_send(envelope);
+}
+
+int media_guaranteed_instances_send(void)
+{
+ const char *token;
+ ezxml_t response;
+ int jpeg;
+ int h264;
+ int mpeg4;
+ int i;
+
+ token = get_element("ConfigurationToken", "Body");
+ if (!token || strcmp(token, "VideoSourceConfigToken"))
+ return send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoConfig",
+ "Unknown configuration", "The source configuration does not exist");
+ jpeg = 0;
+ h264 = 0;
+ mpeg4 = 0;
+ for (i = 0; i < service_ctx.profiles_num; i++) {
+ jpeg += service_ctx.profiles[i].type == JPEG;
+ h264 += service_ctx.profiles[i].type == H264;
+ mpeg4 += service_ctx.profiles[i].type == MPEG4;
+ }
+ response = soap_response_create(1, "GetGuaranteedNumberOfVideoEncoderInstances");
+ soap_number_add(response, "trt:TotalNumber", jpeg + h264 + mpeg4);
+ soap_number_add(response, "trt:JPEG", jpeg);
+ soap_number_add(response, "trt:H264", h264);
+ soap_number_add(response, "trt:MPEG4", mpeg4);
+ return soap_response_send(response);
+}
+
+int media_source_modes_send(void)
+{
+ const char *token;
+ ezxml_t response;
+ ezxml_t mode;
+ ezxml_t resolution;
+ char encodings[MAX_LEN];
+ char codec[16];
+ double framerate;
+ int height;
+ int width;
+ int type;
+ int found;
+ int i;
+
+ token = get_element("VideoSourceToken", "Body");
+ if (!token || strcmp(token, "VideoSourceToken"))
+ return send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoVideoSource",
+ "Unknown source", "The requested video source does not exist");
+ media_source_info(&width, &height, &framerate);
+ response = soap_response_create(2, "GetVideoSourceModes");
+ mode = soap_member_add(response, 2, "VideoSourceModes");
+ ezxml_set_attr(mode, "Enabled", "true");
+ ezxml_set_attr(mode, "token", "VideoSourceModeToken");
+ soap_number_add(mode, "tr2:MaxFramerate", framerate);
+ resolution = soap_child_add(mode, "tr2:MaxResolution", NULL);
+ soap_number_add(resolution, "tt:Width", width);
+ soap_number_add(resolution, "tt:Height", height);
+ encodings[0] = '\0';
+ for (type = JPEG; type <= H265; type++) {
+ found = 0;
+ for (i = 0; i < service_ctx.profiles_num; i++)
+ found |= service_ctx.profiles[i].type == type;
+ if (!found)
+ continue;
+ set_video_codec(codec, sizeof(codec), type, 2);
+ snprintf(encodings + strlen(encodings), sizeof(encodings) - strlen(encodings),
+ "%s%s", *encodings ? " " : "", codec);
+ }
+ soap_child_add(mode, "tr2:Encodings", encodings);
+ soap_child_add(mode, "tr2:Reboot", "false");
+ return soap_response_send(response);
+}
--- /dev/null
+++ b/media_capabilities.h
@@ -0,0 +1,11 @@
+/* SPDX-License-Identifier: GPL-3.0-only */
+#ifndef MEDIA_CAPABILITIES_H
+#define MEDIA_CAPABILITIES_H
+#include "ezxml/ezxml.h"
+
+void media_capabilities_update(ezxml_t node);
+int media_capabilities_send(int version);
+int media_guaranteed_instances_send(void);
+int media_source_modes_send(void);
+
+#endif
--- a/media_options.c
+++ b/media_options.c
@@ -1,5 +1,6 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include <stdio.h>
+#include <math.h>
#include <string.h>
#include "ezxml_wrapper.h"
@@ -64,7 +65,7 @@ static void encoder_options_add(ezxml_t
ezxml_t encoder;
double framerate;
- framerate = (double)profile->framerate / profile->framerate_den;
+ framerate = media_profile_framerate(profile);
set_video_codec(codec, sizeof(codec), profile->type, version);
options = soap_member_add(response, version, "Options");
if (version == 2) {
@@ -92,8 +93,7 @@ static void encoder_options_add(ezxml_t
}
if (profile->type == H264 || profile->type == MPEG4)
soap_range_add(encoder, "tt:GovLengthRange", profile->gov_length, profile->gov_length);
- framerate = ((long long)profile->framerate + profile->framerate_den - 1) /
- profile->framerate_den;
+ framerate = ceil(media_profile_framerate(profile));
soap_range_add(encoder, "tt:FrameRateRange", framerate, framerate);
soap_range_add(encoder, "tt:EncodingIntervalRange", profile->encoding_interval,
profile->encoding_interval);
@@ -103,6 +103,94 @@ static void encoder_options_add(ezxml_t
soap_child_add(encoder, "tt:Mpeg4ProfilesSupported", "SP");
}
+static void media1_options_add(ezxml_t response, int index)
+{
+ stream_profile_t *profile;
+ ezxml_t options;
+ ezxml_t encoder;
+ ezxml_t resolution;
+ char codec[16];
+ char name[32];
+ double quality_min;
+ double quality_max;
+ double rate_min;
+ double rate_max;
+ int interval_min;
+ int interval_max;
+ int gov_min;
+ int gov_max;
+ int type;
+ int i;
+ int j;
+
+ quality_min = 0;
+ quality_max = 0;
+ for (i = 0; i < service_ctx.profiles_num; i++) {
+ profile = &service_ctx.profiles[i];
+ if ((index >= 0 && index != i) || profile->type == H265)
+ continue;
+ if (quality_max == 0 || floor(profile->quality) < quality_min)
+ quality_min = floor(profile->quality);
+ if (ceil(profile->quality) > quality_max)
+ quality_max = ceil(profile->quality);
+ }
+ options = soap_member_add(response, 1, "Options");
+ soap_range_add(options, "tt:QualityRange", quality_min, quality_max);
+ for (type = JPEG; type <= H264; type++) {
+ encoder = NULL;
+ rate_min = 0;
+ rate_max = 0;
+ interval_min = 0;
+ interval_max = 0;
+ gov_min = 0;
+ gov_max = 0;
+ for (i = 0; i < service_ctx.profiles_num; i++) {
+ profile = &service_ctx.profiles[i];
+ if ((index >= 0 && index != i) || profile->type != type)
+ continue;
+ if (!encoder) {
+ set_video_codec(codec, sizeof(codec), type, 1);
+ snprintf(name, sizeof(name), "tt:%s", codec);
+ encoder = soap_child_add(options, name, NULL);
+ }
+ resolution = soap_child_add(encoder, "tt:ResolutionsAvailable", NULL);
+ soap_number_add(resolution, "tt:Width", profile->width);
+ soap_number_add(resolution, "tt:Height", profile->height);
+ if (!rate_min || ceil(media_profile_framerate(profile)) < rate_min)
+ rate_min = ceil(media_profile_framerate(profile));
+ if (ceil(media_profile_framerate(profile)) > rate_max)
+ rate_max = ceil(media_profile_framerate(profile));
+ if (!interval_min || profile->encoding_interval < interval_min)
+ interval_min = profile->encoding_interval;
+ if (profile->encoding_interval > interval_max)
+ interval_max = profile->encoding_interval;
+ if (!gov_min || profile->gov_length < gov_min)
+ gov_min = profile->gov_length;
+ if (profile->gov_length > gov_max)
+ gov_max = profile->gov_length;
+ }
+ if (!encoder)
+ continue;
+ if (type != JPEG)
+ soap_range_add(encoder, "tt:GovLengthRange", gov_min, gov_max);
+ soap_range_add(encoder, "tt:FrameRateRange", rate_min, rate_max);
+ soap_range_add(encoder, "tt:EncodingIntervalRange", interval_min, interval_max);
+ for (i = 0; i < service_ctx.profiles_num && type != JPEG; i++) {
+ profile = &service_ctx.profiles[i];
+ if ((index >= 0 && index != i) || profile->type != type)
+ continue;
+ for (j = 0; j < i; j++)
+ if ((index < 0 || index == j) && service_ctx.profiles[j].type == type &&
+ !strcmp(service_ctx.profiles[j].encoding_profile, profile->encoding_profile))
+ break;
+ if (j == i)
+ soap_child_add(encoder, type == H264 ? "tt:H264ProfilesSupported" :
+ "tt:Mpeg4ProfilesSupported", type == H264 ?
+ profile->encoding_profile : "SP");
+ }
+ }
+}
+
int media_options_dispatch(const char *operation, int version)
{
const char *configuration_token;
@@ -144,14 +232,17 @@ int media_options_dispatch(const char *o
soap_response_send(response);
return 1;
}
+ if (version == 1) {
+ media1_options_add(response, index);
+ soap_response_send(response);
+ return 1;
+ }
for (i = 0; i < service_ctx.profiles_num; i++) {
if (index >= 0 && index != i)
continue;
if (version == 1 && service_ctx.profiles[i].type == H265)
continue;
encoder_options_add(response, &service_ctx.profiles[i], version);
- if (version == 1)
- break;
}
soap_response_send(response);
return 1;
--- a/media_service.c
+++ b/media_service.c
@@ -19,6 +19,7 @@
#include "media_service.h"
#include "conf.h"
+#include "media_capabilities.h"
#include "fault.h"
#include "utils.h"
#include "log.h"
@@ -31,11 +32,7 @@ extern service_context_t service_ctx;
int media_get_service_capabilities()
{
- long size = cat(NULL, "media_service_files/GetServiceCapabilities.xml", 0);
-
- output_http_headers(size);
-
- return cat("stdout", "media_service_files/GetServiceCapabilities.xml", 0);
+ return media_capabilities_send(1);
}
@@ -62,32 +59,7 @@ int media_create_profile()
int media_get_guaranteed_number_of_video_encoder_instances()
{
- char stmp[8];
- const char *configuration_token = get_element("ConfigurationToken", "Body");
-
- if ((service_ctx.profiles_num >= 0) && (service_ctx.profiles_num <= 2)) {
- snprintf(stmp, sizeof(stmp), "%d", service_ctx.profiles_num);
- } else {
- send_action_failed_fault("media_service", -1);
- return -1;
- }
-
- if (strncasecmp("VideoSourceConfigToken", configuration_token, 22) == 0) {
-
- long size = cat(NULL, "media_service_files/GetGuaranteedNumberOfVideoEncoderInstances.xml", 4,
- "%TOTAL_NUMBER%", stmp,
- "%NUMBER_H264%", stmp);
-
- output_http_headers(size);
-
- return cat("stdout", "media_service_files/GetGuaranteedNumberOfVideoEncoderInstances.xml", 4,
- "%TOTAL_NUMBER%", stmp,
- "%NUMBER_H264%", stmp);
-
- } else {
- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoConfig", "No config", "The requested configuration indicated does not exist");
- return -2;
- }
+ return media_guaranteed_instances_send();
}
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -79,6 +79,38 @@ def helper_configuration():
class CGITests(unittest.TestCase):
+ def test_capabilities_and_modes(self):
+ for count in [0, 1, 4, 12]:
+ config = configuration(count)
+ for service in ['media', 'media2']:
+ status, root = request(service, 'GetServiceCapabilities', config=config)
+ self.assertEqual(status, 200)
+ self.assertEqual(root.find('.//{*}ProfileCapabilities').get('MaximumNumberOfProfiles'),
+ str(count))
+ status, root = request('device', 'GetServices', '<IncludeCapability>true</IncludeCapability>', config)
+ self.assertEqual(status, 200)
+ self.assertEqual([n.get('MaximumNumberOfProfiles') for n in root.findall('.//{*}ProfileCapabilities')],
+ [str(count), str(count)])
+ config = configuration(4)
+ config['profiles'][1]['type'] = 'JPEG'
+ config['profiles'][2]['type'] = 'H265'
+ status, root = request('media', 'GetGuaranteedNumberOfVideoEncoderInstances',
+ '<ConfigurationToken>VideoSourceConfigToken</ConfigurationToken>', config)
+ self.assertEqual(status, 200)
+ self.assertEqual(root.findtext('.//trt:TotalNumber', namespaces=NS), '3')
+ self.assertEqual(root.findtext('.//trt:H264', namespaces=NS), '2')
+ self.assertEqual(root.findtext('.//trt:JPEG', namespaces=NS), '1')
+ config.update(source_width=3840, source_height=2160, source_framerate=30)
+ status, root = request('media2', 'GetVideoSourceModes',
+ '<VideoSourceToken>VideoSourceToken</VideoSourceToken>', config)
+ self.assertEqual(status, 200)
+ self.assertEqual(root.findtext('.//tt:Width', namespaces=NS), '3840')
+ status, root = request('media', 'GetVideoEncoderConfigurationOptions', config=config)
+ self.assertEqual(status, 200)
+ self.assertIsNotNone(root.find('.//tt:JPEG', NS))
+ self.assertIsNotNone(root.find('.//tt:H264', NS))
+ self.assertEqual(len(root.findall('.//tt:H264/tt:ResolutionsAvailable', NS)), 2)
+
def test_imaging(self):
with helper_configuration() as (config, path):
config['imaging_helper'] = config.pop('encoder_helper')
@@ -0,0 +1,285 @@
From 6ff93ddc47d711af945fa8d8da4f1e69bb15fc75 Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 11:44:47 +0100
Subject: [PATCH 12/15] test: validate media and imaging responses through
schemas and uhttpd
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
test/README.md | 34 +++++++++++++++++
test/fetch_schemas.py | 50 ++++++++++++++++++++++++
test/test_http.py | 83 ++++++++++++++++++++++++++++++++++++++++
test/test_schema.py | 88 +++++++++++++++++++++++++++++++++++++++++++
4 files changed, 255 insertions(+)
create mode 100644 test/README.md
create mode 100644 test/fetch_schemas.py
create mode 100644 test/test_http.py
create mode 100644 test/test_schema.py
--- /dev/null
+++ b/test/README.md
@@ -0,0 +1,34 @@
+# Host integration tests
+
+Build with an installed crypto backend, for example
+`make HAVE_WOLFSSL=1 STRIP=true`. Run `make test` for native unit tests and
+`make test-cgi HAVE_WOLFSSL=1` for real CGI requests on the loopback interface.
+CGI tests use a synchronous JSON helper fixture and exercise live encoder
+settings, supported options, persistence, imaging transactions and faults.
+
+Schema checks require Python packages `lxml` and `xmlschema` (tested with
+6.1.3 and 4.3.2). Fetch the official definitions once:
+
+```
+python3 test/fetch_schemas.py /tmp/onvif-schemas
+ONVIF_SCHEMA_DIR=/tmp/onvif-schemas python3 test/test_schema.py
+```
+
+ONVIF files are pinned to `68ee1b540a40f848c9599eba2c55b87547c588d6`
+of `onvif/specs`. External W3C/OASIS dependencies retain their published
+locations; the downloaded manifest records their SHA-256 hashes. Definitions
+remain unchanged. Validation runs offline using XSD 1.1 because recent ONVIF
+content models contain optional elements followed by `##any` wildcards.
+The tests validate complete service responses for JPEG, H264, H265, source
+configuration, URI, capabilities and helper-backed encoder/imaging reads.
+
+HTTP checks require a host-runnable uhttpd executable. Supply its command as
+a JSON argument array, including any loader arguments needed on the host:
+
+```
+UHTTPD_COMMAND='["/usr/sbin/uhttpd"]' python3 test/test_http.py
+```
+
+The test starts an isolated server on a temporary loopback port, installs
+CGI wrappers and checks profile enumeration and SOAP HTTP fault status.
+No camera or RTSP server is required by these protocol tests.
--- /dev/null
+++ b/test/fetch_schemas.py
@@ -0,0 +1,50 @@
+import hashlib
+import json
+from pathlib import Path
+import sys
+from urllib.parse import urljoin
+from urllib.request import urlopen
+import xml.etree.ElementTree as ET
+
+REVISION = '68ee1b540a40f848c9599eba2c55b87547c588d6'
+root = Path(sys.argv[1]).resolve()
+sources = {
+ 'https://www.w3.org/2005/05/xmlmime': root / 'external/xmlmime.xsd',
+ 'https://www.w3.org/2003/05/soap-envelope': root / 'external/soap-envelope.xsd',
+ 'http://docs.oasis-open.org/wsn/b-2.xsd': root / 'external/b-2.xsd',
+ 'https://www.w3.org/2004/08/xop/include': root / 'external/xop.xsd',
+}
+for name in ['ver10/schema/onvif.xsd', 'ver10/schema/common.xsd',
+ 'ver10/media/wsdl/media.wsdl', 'ver20/media/wsdl/media.wsdl',
+ 'ver20/imaging/wsdl/imaging.wsdl']:
+ url = f'https://raw.githubusercontent.com/onvif/specs/{REVISION}/wsdl/{name}'
+ sources[url] = root / 'wsdl' / name
+pending = list(sources)
+seen = set()
+while pending:
+ url = pending.pop(0)
+ if url in seen:
+ continue
+ seen.add(url)
+ path = sources[url]
+ if not path.exists():
+ data = urlopen(url.replace('http://', 'https://'), timeout=20).read()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ document = ET.parse(path)
+ schemas = [document.getroot(), *document.findall('.//{http://www.w3.org/2001/XMLSchema}schema')]
+ for schema in schemas:
+ for node in schema:
+ location = node.get('schemaLocation')
+ if not location:
+ continue
+ dependency = urljoin(url, location)
+ if dependency not in sources:
+ sources[dependency] = root / 'external' / dependency.split('/')[-1]
+ pending.append(dependency)
+ print(path)
+(root / 'catalogue.json').write_text(json.dumps({u: str(p) for u, p in sources.items()}))
+(root / 'manifest.json').write_text(json.dumps({
+ 'revision': REVISION,
+ 'sha256': {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in sources.values()}}, indent=2))
--- /dev/null
+++ b/test/test_http.py
@@ -0,0 +1,83 @@
+import http.client
+import json
+import os
+from pathlib import Path
+import shlex
+import socket
+import subprocess
+import tempfile
+import time
+import unittest
+import xml.etree.ElementTree as ET
+
+from test_cgi import configuration, NS, ROOT
+
+
+class HTTPTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.directory = tempfile.TemporaryDirectory()
+ cls.addClassCleanup(cls.directory.cleanup)
+ directory = Path(cls.directory.name)
+ config = directory / 'config.json'
+ config.write_text(json.dumps(configuration(4)))
+ endpoints = directory / 'onvif'
+ endpoints.mkdir()
+ for service in ['device', 'media', 'media2', 'imaging']:
+ script = endpoints / f'{service}_service'
+ command = [str(ROOT / 'onvif_simple_server'), '-c', str(config),
+ f'{service}_service']
+ script.write_text('#!/bin/sh\nexport ONVIF_LOG_FILE=-\ncd ' +
+ shlex.quote(str(ROOT)) + '\nexec ' + shlex.join(command) + '\n')
+ script.chmod(0o755)
+ with socket.socket() as listener:
+ listener.bind(('127.0.0.1', 0))
+ cls.port = listener.getsockname()[1]
+ command = json.loads(os.environ['UHTTPD_COMMAND'])
+ command += ['-f', '-p', f'127.0.0.1:{cls.port}', '-h', str(directory), '-x', '/onvif']
+ cls.server = subprocess.Popen(command, env=dict(os.environ, ONVIF_LOG_FILE='-'),
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ cls.addClassCleanup(cls.stop_server)
+ deadline = time.monotonic() + 5
+ while time.monotonic() < deadline:
+ try:
+ with socket.create_connection(('127.0.0.1', cls.port), timeout=0.1):
+ return
+ except OSError:
+ time.sleep(0.01)
+ raise AssertionError('uhttpd did not start')
+
+ @classmethod
+ def stop_server(cls):
+ cls.server.terminate()
+ cls.server.wait(timeout=5)
+
+ def post(self, operation):
+ body = (f'<s:Envelope xmlns:s="{NS["s"]}"><s:Body>'
+ f'<tr2:{operation} xmlns:tr2="{NS["tr2"]}"><tr2:Type>All</tr2:Type>'
+ f'</tr2:{operation}></s:Body></s:Envelope>')
+ connection = http.client.HTTPConnection('127.0.0.1', self.port, timeout=5)
+ self.addCleanup(connection.close)
+ connection.request('POST', '/onvif/media2_service', body.encode(),
+ {'Content-Type': 'application/soap+xml; charset=utf-8'})
+ response = connection.getresponse()
+ data = response.read()
+ try:
+ root = ET.fromstring(data)
+ except ET.ParseError:
+ self.fail((response.status, data.decode(errors='replace')))
+ return response.status, root
+
+ def test_profiles(self):
+ status, root = self.post('GetProfiles')
+ self.assertEqual(status, 200)
+ self.assertEqual(len(root.findall('.//tr2:Profiles', NS)), 4)
+
+ def test_fault(self):
+ status, root = self.post('UnknownOperation')
+ self.assertEqual(status, 500)
+ self.assertIsNotNone(root.find('.//s:Fault', NS))
+
+
+if __name__ == '__main__':
+ unittest.main()
--- /dev/null
+++ b/test/test_schema.py
@@ -0,0 +1,88 @@
+import json
+import os
+from pathlib import Path
+import unittest
+import xml.etree.ElementTree as ET
+
+from lxml import etree
+import xmlschema
+
+from test_cgi import configuration, helper_configuration, request, NS
+
+XS = '{http://www.w3.org/2001/XMLSchema}'
+SCHEMA_DIR = Path(os.environ['ONVIF_SCHEMA_DIR'])
+
+
+def schema_load(service):
+ paths = {'media': 'ver10/media/wsdl/media.wsdl',
+ 'media2': 'ver20/media/wsdl/media.wsdl',
+ 'imaging': 'ver20/imaging/wsdl/imaging.wsdl'}
+ path = SCHEMA_DIR / 'wsdl' / paths[service]
+ parser = etree.XMLParser(no_network=True)
+ document = etree.parse(str(path), parser)
+ node = document.find('.//' + XS + 'schema')
+ catalogue = json.loads((SCHEMA_DIR / 'catalogue.json').read_text())
+ return xmlschema.XMLSchema11(etree.tostring(node), base_url=str(path.parent),
+ uri_mapper=catalogue, allow='local')
+
+
+class SchemaTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.schemas = {service: schema_load(service) for service in ['media', 'media2', 'imaging']}
+
+ def validate(self, service, operation, content='', config=None):
+ status, root = request(service, operation, content, config)
+ self.assertEqual(status, 200)
+ payload = root.find('s:Body', NS)[0]
+ self.schemas[service].validate(ET.tostring(payload))
+ return root
+
+ def test_media(self):
+ config = configuration(5)
+ config.update(source_width=3840, source_height=2160, source_framerate=30)
+ for i, codec in enumerate(['JPEG', 'H264', 'H264', 'H265', 'H264']):
+ config['profiles'][i]['type'] = codec
+ config['profiles'][i]['encoding_profile'] = 'Main' if codec == 'H265' else 'High'
+ config['profiles'][0]['snapurl'] = 'http://%s/snapshot.jpg'
+ for service in ['media', 'media2']:
+ for operation, content in [
+ ('GetProfiles', '<Type>All</Type>'),
+ ('GetVideoEncoderConfigurations', ''),
+ ('GetVideoEncoderConfigurationOptions', ''),
+ ('GetVideoSourceConfigurations', ''),
+ ('GetVideoSourceConfigurationOptions', ''),
+ ('GetServiceCapabilities', ''),
+ ('GetStreamUri', '<ProfileToken>Profile_0</ProfileToken>'),
+ ('GetSnapshotUri', '<ProfileToken>Profile_0</ProfileToken>')]:
+ with self.subTest(service=service, operation=operation):
+ self.validate(service, operation, content, config)
+ self.validate('media', 'GetVideoSources', config=config)
+ self.validate('media2', 'GetVideoSourceModes',
+ '<VideoSourceToken>VideoSourceToken</VideoSourceToken>', config)
+
+ def test_encoder_helper(self):
+ with helper_configuration() as (config, path):
+ for service in ['media', 'media2']:
+ self.validate(service, 'GetProfiles', '<Type>All</Type>', config)
+ self.validate(service, 'GetVideoEncoderConfigurationOptions', config=config)
+
+ def test_imaging_helper(self):
+ with helper_configuration() as (config, path):
+ config['imaging_helper'] = config.pop('encoder_helper')
+ path.write_text(json.dumps({'settings': {'brightness': 45,
+ 'exposure': {'mode': 'MANUAL', 'gain': 12,
+ 'exposure_time': 10000},
+ 'white_balance': {'mode': 'AUTO'}},
+ 'options': {'exposure': {'mode': ['AUTO', 'MANUAL'],
+ 'gain': {'min': 0, 'max': 40}},
+ 'white_balance': {'mode': ['AUTO', 'MANUAL'],
+ 'cr_gain': {'min': 0.1, 'max': 4}}}}))
+ source = '<VideoSourceToken>VideoSourceToken</VideoSourceToken>'
+ self.validate('imaging', 'GetImagingSettings', source, config)
+ self.validate('imaging', 'GetOptions', source, config)
+ self.validate('imaging', 'GetServiceCapabilities', config=config)
+
+
+if __name__ == '__main__':
+ unittest.main()
@@ -0,0 +1,187 @@
From e645356997a6fb327522cb4f47708ef94bd04bda Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 11:53:13 +0100
Subject: [PATCH 13/15] fix: validate generated media responses and missing
URIs
Preserve audio configuration ordering and backchannel entries while generating profiles. Format integral SOAP values without scientific notation and reject URI requests without a configured endpoint.
Fixes: 2f098ae69cb6 ("feat: enumerate configured media profiles without a two-stream limit")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
conf.c | 3 ++-
media_profiles.c | 43 ++++++++++++++++++++++++++++++++++++-------
soap.c | 3 ++-
test/test_cgi.py | 29 +++++++++++++++++++++++++++++
test/test_schema.py | 8 ++++++++
5 files changed, 77 insertions(+), 9 deletions(-)
--- a/conf.c
+++ b/conf.c
@@ -1366,9 +1366,10 @@ int process_json_conf_file(char *file)
void free_conf_file()
{
+ int i;
+
free(service_ctx.encoder_helper);
free(service_ctx.imaging_helper);
- int i;
if (service_ctx.events_enable == 1) {
for (i = service_ctx.events_num - 1; i >= 0; i--) {
--- a/media_profiles.c
+++ b/media_profiles.c
@@ -160,11 +160,6 @@ static void profile_add(ezxml_t node, in
"tt:VideoSourceConfiguration" : "tr2:VideoSource", NULL);
media_source_configuration_add(child);
}
- if (version == 1 || type_requested("VideoEncoder")) {
- child = soap_child_add(configurations, version == 1 ?
- "tt:VideoEncoderConfiguration" : "tr2:VideoEncoder", NULL);
- encoder_configuration_add(child, index, version);
- }
if (profile->audio_encoder != AUDIO_NONE &&
(version == 1 || type_requested("AudioSource"))) {
child = soap_child_add(configurations, version == 1 ?
@@ -174,6 +169,11 @@ static void profile_add(ezxml_t node, in
soap_number_add(child, "tt:UseCount", service_ctx.profiles_num);
soap_child_add(child, "tt:SourceToken", "AudioSourceToken");
}
+ if (version == 1 || type_requested("VideoEncoder")) {
+ child = soap_child_add(configurations, version == 1 ?
+ "tt:VideoEncoderConfiguration" : "tr2:VideoEncoder", NULL);
+ encoder_configuration_add(child, index, version);
+ }
if (profile->audio_encoder != AUDIO_NONE &&
(version == 1 || type_requested("AudioEncoder"))) {
child = soap_child_add(configurations, version == 1 ?
@@ -184,10 +184,14 @@ static void profile_add(ezxml_t node, in
soap_number_add(child, "tt:UseCount", 1);
set_audio_codec(codec, sizeof(codec), profile->audio_encoder, version);
soap_child_add(child, "tt:Encoding", codec);
+ if (version == 2)
+ multicast_add(child);
soap_number_add(child, "tt:Bitrate", 50);
soap_number_add(child, "tt:SampleRate", 16);
- multicast_add(child);
- soap_child_add(child, "tt:SessionTimeout", "PT0S");
+ if (version == 1) {
+ multicast_add(child);
+ soap_child_add(child, "tt:SessionTimeout", "PT0S");
+ }
}
if (service_ctx.ptz_node.enable && (version == 1 || type_requested("PTZ"))) {
child = soap_child_add(configurations, version == 1 ?
@@ -197,6 +201,22 @@ static void profile_add(ezxml_t node, in
soap_number_add(child, "tt:UseCount", service_ctx.profiles_num);
soap_child_add(child, "tt:NodeToken", "PTZNodeToken");
}
+ if (version == 2 && profile->audio_decoder != AUDIO_NONE && type_requested("AudioOutput")) {
+ child = soap_child_add(configurations, "tr2:AudioOutput", NULL);
+ ezxml_set_attr(child, "token", "AudioOutputConfigToken");
+ soap_child_add(child, "tt:Name", "AudioOutputConfig");
+ soap_number_add(child, "tt:UseCount", service_ctx.profiles_num);
+ soap_child_add(child, "tt:OutputToken", "AudioOutputToken");
+ soap_child_add(child, "tt:SendPrimacy", "www.onvif.org/ver20/HalfDuplex/Client");
+ soap_number_add(child, "tt:OutputLevel", 1);
+ }
+ if (version == 2 && profile->audio_decoder != AUDIO_NONE && type_requested("AudioDecoder")) {
+ child = soap_child_add(configurations, "tr2:AudioDecoder", NULL);
+ snprintf(name, sizeof(name), "%s_AudioDecoderToken", profile->name);
+ ezxml_set_attr_d(child, "token", name);
+ soap_child_add(child, "tt:Name", profile->name);
+ soap_number_add(child, "tt:UseCount", 1);
+ }
}
static void uri_add(ezxml_t response, int index, int version, int snapshot)
@@ -279,6 +299,15 @@ int media_profiles_dispatch(const char *
}
response = soap_response_create(version, operation);
if (uri) {
+ if ((!strcmp(operation, "GetSnapshotUri") &&
+ (!service_ctx.profiles[index].snapurl || !*service_ctx.profiles[index].snapurl)) ||
+ (!strcmp(operation, "GetStreamUri") &&
+ (!service_ctx.profiles[index].url || !*service_ctx.profiles[index].url))) {
+ ezxml_free(response->parent->parent);
+ send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:IncompleteConfiguration",
+ "Missing URI", "The requested profile has no configured URI");
+ return 1;
+ }
uri_add(response, index, version, !strcmp(operation, "GetSnapshotUri"));
soap_response_send(response);
return 1;
--- a/soap.c
+++ b/soap.c
@@ -1,5 +1,6 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include <stdio.h>
+#include <math.h>
#include <string.h>
#include "soap.h"
@@ -19,7 +20,7 @@ ezxml_t soap_number_add(ezxml_t parent,
{
char number[MAX_LEN];
- snprintf(number, sizeof(number), "%.9g", value);
+ snprintf(number, sizeof(number), value == trunc(value) ? "%.0f" : "%.9g", value);
return soap_child_add(parent, name, number);
}
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -206,6 +206,35 @@ class CGITests(unittest.TestCase):
path.write_text(original)
self.assertEqual(request('media2', 'SetVideoEncoderConfiguration',
'<Configuration token="missing"/>', config)[0], 500)
+
+ def test_encoder_setter_codecs(self):
+ with helper_configuration() as (config, path):
+ original = path.read_text()
+ for service, codec in [('media', 'H264'), ('media', 'JPEG'),
+ ('media2', 'H264'), ('media2', 'H265'), ('media2', 'JPEG')]:
+ state = json.loads(original)
+ state['profiles'][3].update(type=codec, encoding_profile='Main')
+ path.write_text(json.dumps(state))
+ operation = 'GetVideoEncoderConfiguration' if service == 'media' else 'GetVideoEncoderConfigurations'
+ status, root = request(service, operation,
+ '<ConfigurationToken>Profile_3_VideoEncoderToken</ConfigurationToken>', config)
+ self.assertEqual(status, 200)
+ node = root.find('.//{*}Configuration') if service == 'media' else root.find('.//{*}Configurations')
+ node.tag = 'Configuration'
+ node.find('tt:RateControl/tt:BitrateLimit', NS).text = '2345'
+ content = ET.tostring(node).decode()
+ status, root = request(service, 'SetVideoEncoderConfiguration', content, config)
+ self.assertEqual(status, 200, (service, codec))
+ self.assertEqual(json.loads(path.read_text())['last_set']['configuration']['bitrate'], 2345)
+ state = json.loads(path.read_text())
+ state['bad_reply'] = True
+ path.write_text(json.dumps(state))
+ self.assertEqual(request(service, 'SetVideoEncoderConfiguration', content, config)[0], 500)
+
+ def test_missing_snapshot(self):
+ for service in ['media', 'media2']:
+ self.assertEqual(request(service, 'GetSnapshotUri',
+ '<ProfileToken>Profile_0</ProfileToken>')[0], 500)
def test_operation_namespace(self):
status, root = request('media', 'GetProfiles', namespace='urn:unrelated')
self.assertEqual(status, 500)
--- a/test/test_schema.py
+++ b/test/test_schema.py
@@ -67,6 +67,14 @@ class SchemaTests(unittest.TestCase):
self.validate(service, 'GetProfiles', '<Type>All</Type>', config)
self.validate(service, 'GetVideoEncoderConfigurationOptions', config=config)
+ def test_audio_profile_order(self):
+ config = configuration(4)
+ for profile in config['profiles']:
+ profile['audio_encoder'] = 'AAC'
+ profile['audio_decoder'] = 'AAC'
+ for service in ['media', 'media2']:
+ self.validate(service, 'GetProfiles', '<Type>All</Type>', config)
+
def test_imaging_helper(self):
with helper_configuration() as (config, path):
config['imaging_helper'] = config.pop('encoder_helper')
@@ -0,0 +1,202 @@
From 50e936982397939701fe7a5422729aa6793662c2 Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 11:57:08 +0100
Subject: [PATCH 14/15] fix: load compressed templates for generated
capabilities
Share template opening between text substitution and XML generation so USE_ZLIB deployments continue to work with compressed templates alone.
Fixes: b3028a5c57d9 ("feat: expose camera imaging through optional control helpers")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
device_advertisement.c | 2 +-
media_capabilities.c | 2 +-
soap.c | 13 +++++++++++++
soap.h | 1 +
test/README.md | 3 +++
test/test_cgi.py | 4 ++--
test/test_compressed.py | 27 +++++++++++++++++++++++++++
utils.c | 40 ++++++++++++++++++++--------------------
utils.h | 1 +
9 files changed, 69 insertions(+), 24 deletions(-)
create mode 100644 test/test_compressed.py
--- a/device_advertisement.c
+++ b/device_advertisement.c
@@ -147,7 +147,7 @@ int device_advertisement_send(int servic
return send_fault("device_service", "Receiver", "ter:ActionNotSupported", "ter:NoSuchService",
"No such service", "The requested service category is unavailable");
}
- envelope = ezxml_parse_file(filename);
+ envelope = soap_template_load(filename);
if (!envelope || *ezxml_error(envelope)) {
ezxml_free(envelope);
return send_action_failed_fault("device_service", -1);
--- a/media_capabilities.c
+++ b/media_capabilities.c
@@ -59,7 +59,7 @@ int media_capabilities_send(int version)
{
ezxml_t envelope;
- envelope = ezxml_parse_file(version == 1 ? "media_service_files/GetServiceCapabilities.xml" :
+ envelope = soap_template_load(version == 1 ? "media_service_files/GetServiceCapabilities.xml" :
"media2_service_files/GetServiceCapabilities.xml");
if (!envelope || *ezxml_error(envelope)) {
ezxml_free(envelope);
--- a/soap.c
+++ b/soap.c
@@ -59,6 +59,19 @@ ezxml_t soap_response_create(int version
return soap_member_add(body, version, name);
}
+ezxml_t soap_template_load(char *filename)
+{
+ ezxml_t document;
+ FILE *file;
+
+ file = template_open(filename);
+ if (!file)
+ return NULL;
+ document = ezxml_parse_fp(file);
+ fclose(file);
+ return document;
+}
+
int soap_response_send(ezxml_t response)
{
ezxml_t envelope;
--- a/soap.h
+++ b/soap.h
@@ -9,6 +9,7 @@ ezxml_t soap_number_add(ezxml_t parent,
void soap_range_add(ezxml_t parent, const char *name, double minimum, double maximum);
ezxml_t soap_member_add(ezxml_t parent, int version, const char *name);
ezxml_t soap_response_create(int version, const char *operation);
+ezxml_t soap_template_load(char *filename);
int soap_response_send(ezxml_t response);
#endif
--- a/test/README.md
+++ b/test/README.md
@@ -32,3 +32,6 @@ UHTTPD_COMMAND='["/usr/sbin/uhttpd"]' py
The test starts an isolated server on a temporary loopback port, installs
CGI wrappers and checks profile enumeration and SOAP HTTP fault status.
No camera or RTSP server is required by these protocol tests.
+
+After building with `USE_ZLIB=1`, run `python3 test/test_compressed.py` to
+check capability responses with only gzip-compressed templates available.
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -26,7 +26,7 @@ def configuration(count=2):
for i in range(count)]}
-def request(service, operation, content='', config=None, namespace=None):
+def request(service, operation, content='', config=None, namespace=None, template_dir=ROOT):
config = configuration() if config is None else config
namespace = namespace or {'device': 'http://www.onvif.org/ver10/device/wsdl',
'media': NS['trt'], 'media2': NS['tr2'],
@@ -41,7 +41,7 @@ def request(service, operation, content=
REMOTE_ADDR='127.0.0.1', CONTENT_LENGTH=str(len(body)))
result = subprocess.run([str(ROOT / 'onvif_simple_server'),
'-c', str(path), f'{service}_service'],
- input=body, capture_output=True, cwd=ROOT,
+ input=body, capture_output=True, cwd=template_dir,
env=env, timeout=10)
if result.returncode:
raise AssertionError(result.stderr.decode())
--- /dev/null
+++ b/test/test_compressed.py
@@ -0,0 +1,27 @@
+import gzip
+from pathlib import Path
+import tempfile
+import unittest
+
+from test_cgi import request, ROOT
+
+
+class CompressedTests(unittest.TestCase):
+ def test_capability_templates(self):
+ with tempfile.TemporaryDirectory() as directory:
+ for source in ROOT.glob('*_files/*.xml'):
+ target = Path(directory) / source.relative_to(ROOT)
+ target.parent.mkdir(exist_ok=True)
+ target.with_suffix('.xml.gz').write_bytes(gzip.compress(source.read_bytes()))
+ for service, operation, content in [
+ ('device', 'GetServices', '<IncludeCapability>true</IncludeCapability>'),
+ ('device', 'GetCapabilities', ''),
+ ('media', 'GetServiceCapabilities', ''),
+ ('media2', 'GetServiceCapabilities', '')]:
+ with self.subTest(service=service, operation=operation):
+ self.assertEqual(request(service, operation, content,
+ template_dir=directory)[0], 200)
+
+
+if __name__ == '__main__':
+ unittest.main()
--- a/utils.c
+++ b/utils.c
@@ -346,6 +346,25 @@ long cat_soap_fault(char* out, const cha
* @param ... The argument list to replace: src1, dst1, src2, dst2, etc...
* @return the number of processed bytes
*/
+FILE *template_open(char *filename)
+{
+ FILE *file;
+
+#ifdef USE_ZLIB
+ file = tmpfile();
+ if (!file)
+ return NULL;
+ if (gzip_d(file, filename)) {
+ fclose(file);
+ return NULL;
+ }
+ rewind(file);
+#else
+ file = fopen(filename, "r");
+#endif
+ return file;
+}
+
long cat(char *out, char *filename, int num, ...)
{
va_list valist;
@@ -360,26 +379,7 @@ long cat(char *out, char *filename, int
// Reset SOAP fault flag for normal file operations
g_last_response_was_soap_fault = 0;
-#ifdef USE_ZLIB
- file = tmpfile();
- if (file == NULL) {
- log_error("Unable to open file %s", filename);
- return -1;
- }
- if (gzip_d(file, filename) != 0) {
- log_error("Unable to decompress file %s", filename);
- fclose(file);
- return -2;
- }
- rewind(file);
-#else
- file = fopen(filename, "r");
- if (!file) {
- log_error("Unable to open file %s", filename);
- return -3;
- }
-#endif
-
+ file = template_open(filename);
if (!file) {
log_error("Unable to open file %s", filename);
// Return ONVIF-compliant SOAP fault instead of empty response
--- a/utils.h
+++ b/utils.h
@@ -79,6 +79,7 @@ void *create_shared_memory(int create);
void destroy_shared_memory(void *shared_area, int destroy_all);
int sem_memory_wait();
int sem_memory_post();
+FILE *template_open(char *filename);
long cat(char *out, char *filename, int num, ...);
long cat_soap_fault(char* out, const char* fault_subcode, const char* fault_reason, const char* fault_detail);
void output_http_headers(long content_length);
@@ -0,0 +1,443 @@
From 973144da3b43ce26330899a58f22050c76009802 Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 11:59:44 +0100
Subject: [PATCH 15/15] fix: validate encoder changes before invoking control
helpers
Reject unsupported metadata and coding changes, validate token and scalar limits, and preserve live settings when optional fields are omitted.
Fixes: 135cec8b6b04 ("feat: delegate encoder configuration to external helpers")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
CONTROL_HELPERS.md | 3 +
README.md | 7 ++
conf.c | 10 ++-
control_helper.c | 4 +-
device_advertisement.c | 27 +++++---
encoder_control.c | 148 ++++++++++++++++++++++++++++++++++++-----
media_profiles.c | 3 +-
onvif_simple_server.h | 1 +
test/test_cgi.py | 32 +++++++++
9 files changed, 207 insertions(+), 28 deletions(-)
--- a/CONTROL_HELPERS.md
+++ b/CONTROL_HELPERS.md
@@ -56,6 +56,9 @@ effective `configuration` after applying
true, as required by the current Media specification; Media2 also persists
encoder changes. Rejected changes must leave the camera unchanged. Setters
remain unavailable when no encoder helper is configured.
+Omitted optional rate-control and GOP/profile members retain live values.
+Name, use count, multicast and session metadata remain read-only. Requests
+to change these or unsupported coding features return a fault.
## Imaging operations
--- a/README.md
+++ b/README.md
@@ -396,6 +396,13 @@ Usage: /tmp/sd/yi-hack/bin/onvif_notify_
| debug | debug level from 0 to 5 | 0 |
## Compatibility
+Profile names derive encoder tokens by appending `_VideoEncoderToken`.
+Keep names within 46 UTF-8 bytes so the generated token fits ONVIF's
+64-character ReferenceToken limit. H265 profiles use `Main` or `Main10`.
+Optional camera controls and their generic helper protocol are described in
+[CONTROL_HELPERS.md](CONTROL_HELPERS.md). Host protocol tests are described in
+[test/README.md](test/README.md).
+
I tested this program with the following clients:
- Onvif Device Manager (Windows)
- Synology Surveillance Station (DSM 6.x and 7.x)
--- a/conf.c
+++ b/conf.c
@@ -25,6 +25,7 @@
#include <errno.h>
#include <net/if.h>
#include <math.h>
+#include <float.h>
#include <json-c/json.h>
#include "conf.h"
@@ -66,11 +67,13 @@ static int profiles_validate(void)
return -2;
for (i = 0; i < service_ctx.profiles_num; i++) {
profile = &service_ctx.profiles[i];
- if (!profile->name || !*profile->name || profile->width <= 0 ||
+ if (!profile->name || !*profile->name ||
+ strlen(profile->name) + strlen("_VideoEncoderToken") > ONVIF_TOKEN_MAX_LENGTH ||
+ profile->width <= 0 ||
profile->height <= 0 || profile->framerate <= 0 ||
profile->framerate_den <= 0 || profile->bitrate < 0 ||
profile->gov_length <= 0 || profile->encoding_interval <= 0 ||
- !isfinite(profile->quality) || profile->quality < 0)
+ !isfinite(profile->quality) || profile->quality < 0 || profile->quality > FLT_MAX)
return -2;
for (j = 0; j < i; j++)
if (!strcmp(profile->name, service_ctx.profiles[j].name))
@@ -82,6 +85,9 @@ static int profiles_validate(void)
strcmp(profile->encoding_profile, "Extended") &&
strcmp(profile->encoding_profile, "High"))
return -2;
+ if (profile->type == H265 && strcmp(profile->encoding_profile, "Main") &&
+ strcmp(profile->encoding_profile, "Main10"))
+ return -2;
}
return 0;
}
--- a/control_helper.c
+++ b/control_helper.c
@@ -184,7 +184,9 @@ static int helper_exchange(const char *p
enum helper_status helper_call(const char *path, const char *operation,
json_object *data, json_object **result)
{
- static const char *statuses[] = { "ok", "unsupported", "not_found", "invalid", "busy", "failed" };
+ static const char *statuses[] = {
+ "ok", "unsupported", "not_found", "invalid", "busy", "failed"
+ };
char response[HELPER_MESSAGE_SIZE + 1];
struct json_tokener *tokener;
json_object *request, *reply, *value;
--- a/device_advertisement.c
+++ b/device_advertisement.c
@@ -98,13 +98,19 @@ int device_advertisement_send(int servic
port[0] = '\0';
if (service_ctx.port != 80)
snprintf(port, sizeof(port), ":%d", service_ctx.port);
- snprintf(device, sizeof(device), "http://%s%s/onvif/device_service", service_ctx.address_url, port);
- snprintf(media, sizeof(media), "http://%s%s/onvif/media_service", service_ctx.address_url, port);
- snprintf(media2, sizeof(media2), "http://%s%s/onvif/media2_service", service_ctx.address_url, port);
+ snprintf(device, sizeof(device), "http://%s%s/onvif/device_service",
+ service_ctx.address_url, port);
+ snprintf(media, sizeof(media), "http://%s%s/onvif/media_service",
+ service_ctx.address_url, port);
+ snprintf(media2, sizeof(media2), "http://%s%s/onvif/media2_service",
+ service_ctx.address_url, port);
snprintf(ptz, sizeof(ptz), "http://%s%s/onvif/ptz_service", service_ctx.address_url, port);
- snprintf(events, sizeof(events), "http://%s%s/onvif/events_service", service_ctx.address_url, port);
- snprintf(deviceio, sizeof(deviceio), "http://%s%s/onvif/deviceio_service", service_ctx.address_url, port);
- snprintf(imaging, sizeof(imaging), "http://%s%s/onvif/imaging_service", service_ctx.address_url, port);
+ snprintf(events, sizeof(events), "http://%s%s/onvif/events_service",
+ service_ctx.address_url, port);
+ snprintf(deviceio, sizeof(deviceio), "http://%s%s/onvif/deviceio_service",
+ service_ctx.address_url, port);
+ snprintf(imaging, sizeof(imaging), "http://%s%s/onvif/imaging_service",
+ service_ctx.address_url, port);
audio_input = 0;
audio_output = 0;
for (i = 0; i < service_ctx.profiles_num; i++) {
@@ -114,7 +120,8 @@ int device_advertisement_send(int servic
snprintf(audio_sources, sizeof(audio_sources), "%d", audio_input);
snprintf(audio_outputs, sizeof(audio_outputs), "%d", audio_output);
snprintf(relay_outputs, sizeof(relay_outputs), "%d", service_ctx.relay_outputs_num);
- if (service_ctx.events_enable == EVENTS_BASESUBSCRIPTION || service_ctx.events_enable == EVENTS_BOTH)
+ if (service_ctx.events_enable == EVENTS_BASESUBSCRIPTION ||
+ service_ctx.events_enable == EVENTS_BOTH)
values[6].value = "true";
if (service_ctx.events_enable == EVENTS_PULLPOINT || service_ctx.events_enable == EVENTS_BOTH)
values[7].value = "true";
@@ -142,9 +149,11 @@ int device_advertisement_send(int servic
} else if (!strcmp(category, "Device") || !strcmp(category, "Media") ||
!strcmp(category, "Events") ||
(!strcmp(category, "PTZ") && service_ctx.ptz_node.enable)) {
- snprintf(filename, sizeof(filename), "device_service_files/Get%sCapabilities.xml", category);
+ snprintf(filename, sizeof(filename), "device_service_files/Get%sCapabilities.xml",
+ category);
} else {
- return send_fault("device_service", "Receiver", "ter:ActionNotSupported", "ter:NoSuchService",
+ return send_fault("device_service", "Receiver", "ter:ActionNotSupported",
+ "ter:NoSuchService",
"No such service", "The requested service category is unavailable");
}
envelope = soap_template_load(filename);
--- a/encoder_control.c
+++ b/encoder_control.c
@@ -1,5 +1,6 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include <limits.h>
+#include <float.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
@@ -66,7 +67,8 @@ static int profile_update(stream_profile
integer_get(object, "bitrate", &candidate.bitrate, 0) ||
number_get(object, "frame_rate", &candidate.frame_rate) ||
candidate.frame_rate <= 0 || candidate.frame_rate > INT_MAX ||
- number_get(object, "quality", &candidate.quality) || candidate.quality < 0)
+ number_get(object, "quality", &candidate.quality) || candidate.quality < 0 ||
+ candidate.quality > FLT_MAX)
return -1;
encoding_profile = profile->encoding_profile;
if (candidate.type != JPEG) {
@@ -143,6 +145,9 @@ static int option_add(ezxml_t response,
return -1;
if (version == 1 && !strcmp(codec, "H265"))
return 0;
+ if (version == 1 && !strcmp(codec, "JPEG") &&
+ get_element_in_element_ptr("H264", common))
+ return -1;
options = version == 1 ? common : soap_member_add(response, version, "Options");
if (range_get(object, "quality", &minimum, &maximum, version == 1))
return -1;
@@ -262,7 +267,8 @@ static enum helper_status encoder_option
configuration_token = get_element("ConfigurationToken", "Body");
profile_token = get_element("ProfileToken", "Body");
- if ((configuration_token && media_profile_find(configuration_token, "_VideoEncoderToken") < 0) ||
+ if ((configuration_token &&
+ media_profile_find(configuration_token, "_VideoEncoderToken") < 0) ||
(profile_token && media_profile_find(profile_token, "") < 0))
return HELPER_NOT_FOUND;
request = json_object_new_object();
@@ -380,7 +386,7 @@ static int xml_number_add(json_object *o
return 0;
}
-static json_object *configuration_parse(ezxml_t node, int version)
+static json_object *configuration_parse(ezxml_t node, int version, stream_profile_t *profile)
{
const char *encoding_profile;
const char *codec;
@@ -395,34 +401,46 @@ static json_object *configuration_parse(
codec = get_element_in_element("Encoding", node);
resolution = get_element_in_element_ptr("Resolution", node);
rate = get_element_in_element_ptr("RateControl", node);
- if (!codec || !resolution || !rate)
+ if (!codec || !resolution)
return NULL;
object = json_object_new_object();
json_object_object_add(object, "type", json_object_new_string(codec));
if (xml_number_add(object, "width", resolution, "Width", 1) ||
xml_number_add(object, "height", resolution, "Height", 1) ||
- xml_number_add(object, "bitrate", rate, "BitrateLimit", 1) ||
- xml_number_add(object, "frame_rate", rate, "FrameRateLimit", version == 1) ||
xml_number_add(object, "quality", node, "Quality", 0))
goto invalid;
- if (version == 1 && xml_number_add(object, "encoding_interval", rate,
- "EncodingInterval", 1))
+ if (rate && (xml_number_add(object, "bitrate", rate, "BitrateLimit", 1) ||
+ xml_number_add(object, "frame_rate", rate, "FrameRateLimit", version == 1)))
+ goto invalid;
+ if (!rate) {
+ json_object_object_add(object, "bitrate", json_object_new_int(profile->bitrate));
+ json_object_object_add(object, "frame_rate",
+ json_object_new_double(media_profile_framerate(profile)));
+ }
+ if (version == 1 && rate && xml_number_add(object, "encoding_interval", rate,
+ "EncodingInterval", 1))
goto invalid;
if (!strcmp(codec, "JPEG"))
return object;
h264 = get_element_in_element_ptr("H264", node);
if (version == 1) {
- encoding_profile = get_element_in_element("H264Profile", h264);
- if (strcmp(codec, "H264") || !encoding_profile ||
- xml_number_add(object, "gov_length", h264, "GovLength", 1))
+ if (strcmp(codec, "H264"))
goto invalid;
+ encoding_profile = h264 ? get_element_in_element("H264Profile", h264) :
+ profile->encoding_profile;
+ if (h264 && xml_number_add(object, "gov_length", h264, "GovLength", 1))
+ goto invalid;
+ if (!h264)
+ json_object_object_add(object, "gov_length", json_object_new_int(profile->gov_length));
} else {
encoding_profile = get_attribute(node, "Profile");
+ if (!encoding_profile)
+ encoding_profile = profile->encoding_profile;
gov = get_attribute(node, "GovLength");
- if (!gov || !*gov)
+ if (gov && !*gov)
goto invalid;
- length = strtol(gov, &end, 10);
- if (*end || length < 1 || length > INT_MAX)
+ length = gov ? strtol(gov, &end, 10) : profile->gov_length;
+ if ((gov && *end) || length < 1 || length > INT_MAX)
goto invalid;
json_object_object_add(object, "gov_length", json_object_new_int(length));
}
@@ -435,6 +453,99 @@ invalid:
return NULL;
}
+static int children_supported(ezxml_t node, const char *const *names)
+{
+ const char *namespace;
+ const char *name;
+ ezxml_t child;
+ ezxml_t sibling;
+ int i;
+
+ for (child = node ? node->child : NULL; child; child = child->ordered) {
+ namespace = xml_namespace_get(child);
+ if (!namespace || strcmp(namespace, "http://www.onvif.org/ver10/schema"))
+ return 0;
+ name = strchr(child->name, ':');
+ name = name ? name + 1 : child->name;
+ for (i = 0; names[i] && strcmp(names[i], name); i++)
+ ;
+ if (!names[i])
+ return 0;
+ for (sibling = child->ordered; sibling; sibling = sibling->ordered) {
+ name = strchr(sibling->name, ':');
+ name = name ? name + 1 : sibling->name;
+ if (!strcmp(names[i], name))
+ return 0;
+ }
+ }
+ return 1;
+}
+
+static int configuration_supported(ezxml_t node, int index, int version)
+{
+ static const char *const names[] = {
+ "Name", "UseCount", "Encoding", "Resolution", "Quality", "RateControl",
+ "H264", "Multicast", "SessionTimeout", NULL
+ };
+ static const char *const rate_names[] = {
+ "FrameRateLimit", "EncodingInterval", "BitrateLimit", NULL
+ };
+ static const char *const resolution_names[] = { "Width", "Height", NULL };
+ static const char *const h264_names[] = { "GovLength", "H264Profile", NULL };
+ const char *value;
+ const char *attribute;
+ ezxml_t multicast;
+ ezxml_t rate;
+ int i;
+
+ if (version == 1 && service_ctx.profiles[index].type == H265)
+ return 0;
+ if (!children_supported(node, names) ||
+ !children_supported(get_element_in_element_ptr("Resolution", node), resolution_names) ||
+ !children_supported(get_element_in_element_ptr("H264", node), h264_names))
+ return 0;
+ for (i = 0; node->attr[i]; i += 2) {
+ attribute = node->attr[i];
+ if (!strcmp(attribute, "token") || !strncmp(attribute, "xmlns", strlen("xmlns")) ||
+ (version == 2 && (!strcmp(attribute, "GovLength") || !strcmp(attribute, "Profile"))))
+ continue;
+ return 0;
+ }
+ value = get_element_in_element("Name", node);
+ if (value && strcmp(value, service_ctx.profiles[index].name))
+ return 0;
+ value = get_element_in_element("UseCount", node);
+ if (value && strcmp(value, "1"))
+ return 0;
+ value = get_element_in_element("SessionTimeout", node);
+ if (value && strcmp(value, "PT0S"))
+ return 0;
+ rate = get_element_in_element_ptr("RateControl", node);
+ if (!children_supported(rate, rate_names))
+ return 0;
+ for (i = 0; rate && rate->attr[i]; i += 2)
+ if (strncmp(rate->attr[i], "xmlns", strlen("xmlns")))
+ return 0;
+ multicast = get_element_in_element_ptr("Multicast", node);
+ if (!multicast)
+ return 1;
+ value = get_element_in_element("AutoStart", multicast);
+ if (!value || (strcmp(value, "false") && strcmp(value, "0")))
+ return 0;
+ value = get_element_in_element("Port", multicast);
+ if (!value || strcmp(value, "0"))
+ return 0;
+ value = get_element_in_element("TTL", multicast);
+ if (!value || strcmp(value, "0"))
+ return 0;
+ multicast = get_element_in_element_ptr("Address", multicast);
+ value = get_element_in_element("Type", multicast);
+ if (!value || strcmp(value, "IPv4"))
+ return 0;
+ value = get_element_in_element("IPv4Address", multicast);
+ return value && !strcmp(value, "0.0.0.0");
+}
+
static enum helper_status encoder_set(int version)
{
stream_profile_t candidate;
@@ -450,7 +561,9 @@ static enum helper_status encoder_set(in
index = media_profile_find(token, "_VideoEncoderToken");
if (index < 0)
return HELPER_NOT_FOUND;
- configuration = configuration_parse(node, version);
+ if (!configuration_supported(node, index, version))
+ return HELPER_INVALID;
+ configuration = configuration_parse(node, version, &service_ctx.profiles[index]);
if (!configuration)
return HELPER_INVALID;
candidate = service_ctx.profiles[index];
@@ -507,6 +620,11 @@ int encoder_control_dispatch(const char
return 1;
}
if (setter) {
+ status = encoder_refresh();
+ if (status != HELPER_OK && status != HELPER_UNSUPPORTED) {
+ helper_fault(service, status);
+ return 1;
+ }
status = encoder_set(version);
if (status == HELPER_OK)
soap_response_send(soap_response_create(version, operation));
--- a/media_profiles.c
+++ b/media_profiles.c
@@ -304,7 +304,8 @@ int media_profiles_dispatch(const char *
(!strcmp(operation, "GetStreamUri") &&
(!service_ctx.profiles[index].url || !*service_ctx.profiles[index].url))) {
ezxml_free(response->parent->parent);
- send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:IncompleteConfiguration",
+ send_fault((char *)service, "Sender", "ter:InvalidArgVal",
+ "ter:IncompleteConfiguration",
"Missing URI", "The requested profile has no configured URI");
return 1;
}
--- a/onvif_simple_server.h
+++ b/onvif_simple_server.h
@@ -16,6 +16,7 @@
#ifndef ONVIF_SIMPLE_SERVER_H
#define ONVIF_SIMPLE_SERVER_H
+#define ONVIF_TOKEN_MAX_LENGTH 64
#define DAEMON_NO_CHDIR 01 /* Don't chdir ("/") */
#define DAEMON_NO_CLOSE_FILES 02 /* Don't close all open files */
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -235,6 +235,38 @@ class CGITests(unittest.TestCase):
for service in ['media', 'media2']:
self.assertEqual(request(service, 'GetSnapshotUri',
'<ProfileToken>Profile_0</ProfileToken>')[0], 500)
+
+ def test_encoder_rejects_unsupported_changes(self):
+ with helper_configuration() as (config, path):
+ status, root = request('media2', 'GetVideoEncoderConfigurations',
+ '<ConfigurationToken>Profile_0_VideoEncoderToken</ConfigurationToken>', config)
+ self.assertEqual(status, 200)
+ node = root.find('.//tr2:Configurations', NS)
+ node.tag = 'Configuration'
+ original = ET.tostring(node).decode()
+ for content in [original.replace('Profile_0</', 'Renamed</'),
+ original.replace('AutoStart>false', 'AutoStart>true'),
+ original.replace('<Configuration ', '<Configuration Signed="true" '),
+ original.replace('</Configuration>', '<tt:Unknown/></Configuration>')]:
+ self.assertEqual(request('media2', 'SetVideoEncoderConfiguration', content, config)[0], 500)
+ self.assertNotIn('last_set', json.loads(path.read_text()))
+ node.remove(node.find('tt:RateControl', NS))
+ del node.attrib['GovLength']
+ del node.attrib['Profile']
+ self.assertEqual(request('media2', 'SetVideoEncoderConfiguration',
+ ET.tostring(node).decode(), config)[0], 200)
+ applied = json.loads(path.read_text())['last_set']['configuration']
+ self.assertEqual(applied['bitrate'], 4567)
+ self.assertEqual(applied['frame_rate'], 29.97)
+ self.assertEqual(applied['gov_length'], 57)
+
+ def test_encoder_option_failure(self):
+ with helper_configuration() as (config, path):
+ state = json.loads(path.read_text())
+ state['options'][0]['frame_rates'] = [15, 30]
+ path.write_text(json.dumps(state))
+ for service in ['media', 'media2']:
+ self.assertEqual(request(service, 'GetVideoEncoderConfigurationOptions', config=config)[0], 500)
def test_operation_namespace(self):
status, root = request('media', 'GetProfiles', namespace='urn:unrelated')
self.assertEqual(status, 500)
@@ -0,0 +1,250 @@
From 06d96723d0a5aaf8a36daa4576670e347d94e4f5 Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 17:02:50 +0100
Subject: [PATCH 16/19] fix: use the CGI connection address in service URLs
Address selection from a configured interface or a route to the client
can advertise a different local endpoint on a multihomed device. Prefer
the web server CGI SERVER_ADDR value and share address resolution between
text and JSON configuration readers.
Fixes: cdc5939bbe97 ("feat: auto-detect local address from REMOTE_ADDR; ifs= now optional override")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
conf.c | 114 ++++++++++++++++++++--------------------------
test/test_cgi.py | 23 +++++++++-
test/test_http.py | 17 +++++--
3 files changed, 85 insertions(+), 69 deletions(-)
--- a/conf.c
+++ b/conf.c
@@ -26,6 +26,7 @@
#include <net/if.h>
#include <math.h>
#include <float.h>
+#include <arpa/inet.h>
#include <json-c/json.h>
#include "conf.h"
@@ -92,6 +93,51 @@ static int profiles_validate(void)
return 0;
}
+static int service_address_resolve(void)
+{
+ unsigned char binary[sizeof(struct in6_addr)];
+ char netmask[INET_ADDRSTRLEN];
+ char interface[IFNAMSIZ];
+ const char *remote;
+ const char *local;
+
+ local = getenv("SERVER_ADDR");
+ if (local && *local) {
+ if (inet_pton(AF_INET, local, binary) != 1 &&
+ inet_pton(AF_INET6, local, binary) != 1) {
+ log_error("Invalid SERVER_ADDR.");
+ return -2;
+ }
+ snprintf(service_ctx.address, sizeof(service_ctx.address), "%s", local);
+ } else if (service_ctx.ifs) {
+ if (get_ip_address(service_ctx.address, netmask, service_ctx.ifs) < 0) {
+ log_error("Cannot get IP address from interface %s.", service_ctx.ifs);
+ return -2;
+ }
+ } else {
+ remote = getenv("REMOTE_ADDR");
+ if (!remote || detect_local_address(remote, service_ctx.address,
+ sizeof(service_ctx.address))) {
+ log_error("Cannot determine local address.");
+ return -2;
+ }
+ }
+ if (!service_ctx.ifs) {
+ if (get_ifname_by_addr(service_ctx.address, interface, sizeof(interface)))
+ snprintf(interface, sizeof(interface), "%s", DEFAULT_IFS);
+ service_ctx.ifs = strdup(interface);
+ if (!service_ctx.ifs)
+ return -2;
+ }
+ if (strchr(service_ctx.address, ':'))
+ snprintf(service_ctx.address_url, sizeof(service_ctx.address_url),
+ "[%s]", service_ctx.address);
+ else
+ snprintf(service_ctx.address_url, sizeof(service_ctx.address_url),
+ "%s", service_ctx.address);
+ return 0;
+}
+
int process_conf_file(char *file)
{
FILE *fF;
@@ -739,38 +785,8 @@ int process_conf_file(char *file)
service_ctx.hardware_id = (char *) malloc(strlen(DEFAULT_HW_ID) + 1);
snprintf(service_ctx.hardware_id, strlen(DEFAULT_HW_ID) + 1, "%s", DEFAULT_HW_ID);
}
- /* Address and interface resolution */
- if (service_ctx.ifs != NULL) {
- /* Interface explicitly configured: derive address from it */
- char netmask[16];
- if (get_ip_address(service_ctx.address, netmask, service_ctx.ifs) < 0) {
- log_fatal("Cannot get IP address from interface %s.", service_ctx.ifs);
- exit(EXIT_FAILURE);
- }
- } else {
- /* Auto-detect: derive address from REMOTE_ADDR, then detect interface */
- const char *remote = getenv("REMOTE_ADDR");
- if (!remote || detect_local_address(remote, service_ctx.address,
- sizeof(service_ctx.address)) != 0) {
- log_fatal("Cannot determine local address: REMOTE_ADDR not available.");
- exit(EXIT_FAILURE);
- }
- char auto_ifs[IFNAMSIZ];
- if (get_ifname_by_addr(service_ctx.address, auto_ifs, sizeof(auto_ifs)) == 0) {
- service_ctx.ifs = (char *) malloc(strlen(auto_ifs) + 1);
- snprintf(service_ctx.ifs, strlen(auto_ifs) + 1, "%s", auto_ifs);
- } else {
- service_ctx.ifs = (char *) malloc(strlen(DEFAULT_IFS) + 1);
- snprintf(service_ctx.ifs, strlen(DEFAULT_IFS) + 1, "%s", DEFAULT_IFS);
- }
- }
- if (strchr(service_ctx.address, ':'))
- snprintf(service_ctx.address_url, sizeof(service_ctx.address_url),
- "[%s]", service_ctx.address);
- else
- strncpy(service_ctx.address_url, service_ctx.address,
- sizeof(service_ctx.address_url) - 1);
- service_ctx.address_url[sizeof(service_ctx.address_url) - 1] = '\0';
+ if (service_address_resolve())
+ return -2;
/* Stable device UUID from MAC */
{
@@ -1006,38 +1022,8 @@ int process_json_conf_file(char *file)
if (service_ctx.hardware_id)
snprintf(service_ctx.hardware_id, strlen(DEFAULT_HW_ID) + 1, "%s", DEFAULT_HW_ID);
}
- /* Address and interface resolution */
- if (service_ctx.ifs != NULL) {
- /* Interface explicitly configured: derive address from it */
- char netmask[16];
- if (get_ip_address(service_ctx.address, netmask, service_ctx.ifs) < 0) {
- log_fatal("Cannot get IP address from interface %s.", service_ctx.ifs);
- exit(EXIT_FAILURE);
- }
- } else {
- /* Auto-detect: derive address from REMOTE_ADDR, then detect interface */
- const char *remote = getenv("REMOTE_ADDR");
- if (!remote || detect_local_address(remote, service_ctx.address,
- sizeof(service_ctx.address)) != 0) {
- log_fatal("Cannot determine local address: REMOTE_ADDR not available.");
- exit(EXIT_FAILURE);
- }
- char auto_ifs[IFNAMSIZ];
- if (get_ifname_by_addr(service_ctx.address, auto_ifs, sizeof(auto_ifs)) == 0) {
- service_ctx.ifs = (char*) malloc(strlen(auto_ifs) + 1);
- if (service_ctx.ifs) snprintf(service_ctx.ifs, strlen(auto_ifs) + 1, "%s", auto_ifs);
- } else {
- service_ctx.ifs = (char*) malloc(strlen(DEFAULT_IFS) + 1);
- if (service_ctx.ifs) snprintf(service_ctx.ifs, strlen(DEFAULT_IFS) + 1, "%s", DEFAULT_IFS);
- }
- }
- if (strchr(service_ctx.address, ':'))
- snprintf(service_ctx.address_url, sizeof(service_ctx.address_url),
- "[%s]", service_ctx.address);
- else
- strncpy(service_ctx.address_url, service_ctx.address,
- sizeof(service_ctx.address_url) - 1);
- service_ctx.address_url[sizeof(service_ctx.address_url) - 1] = '\0';
+ if (service_address_resolve())
+ return -2;
/* Stable device UUID from MAC */
{
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -26,7 +26,8 @@ def configuration(count=2):
for i in range(count)]}
-def request(service, operation, content='', config=None, namespace=None, template_dir=ROOT):
+def request(service, operation, content='', config=None, namespace=None, template_dir=ROOT,
+ server_address=None):
config = configuration() if config is None else config
namespace = namespace or {'device': 'http://www.onvif.org/ver10/device/wsdl',
'media': NS['trt'], 'media2': NS['tr2'],
@@ -39,6 +40,9 @@ def request(service, operation, content=
path.write_text(config if isinstance(config, str) else json.dumps(config))
env = dict(os.environ, ONVIF_LOG_FILE='-', REQUEST_METHOD='POST',
REMOTE_ADDR='127.0.0.1', CONTENT_LENGTH=str(len(body)))
+ env.pop('SERVER_ADDR', None)
+ if server_address is not None:
+ env['SERVER_ADDR'] = server_address
result = subprocess.run([str(ROOT / 'onvif_simple_server'),
'-c', str(path), f'{service}_service'],
input=body, capture_output=True, cwd=template_dir,
@@ -79,6 +83,23 @@ def helper_configuration():
class CGITests(unittest.TestCase):
+ def test_socket_local_addresses(self):
+ text = ('ifs=lo\nname=Profile_0\nwidth=640\nheight=480\ntype=H264\n'
+ 'url=rtsp://%s:8554/test\naudio_encoder=NONE\n')
+ for config in [configuration(1), text]:
+ for address, host in [('192.0.2.10', '192.0.2.10'),
+ ('2001:db8::10', '[2001:db8::10]')]:
+ status, root = request('media', 'GetStreamUri',
+ '<ProfileToken>Profile_0</ProfileToken>',
+ config, server_address=address)
+ self.assertEqual(status, 200)
+ self.assertTrue(root.findtext('.//{*}Uri').startswith(f'rtsp://{host}:8554/'))
+ status, root = request('device', 'GetServices', config=config,
+ server_address=address)
+ self.assertEqual(status, 200)
+ self.assertTrue(all(f'://{host}' in node.text
+ for node in root.findall('.//{*}XAddr')))
+
def test_capabilities_and_modes(self):
for count in [0, 1, 4, 12]:
config = configuration(count)
--- a/test/test_http.py
+++ b/test/test_http.py
@@ -34,7 +34,8 @@ class HTTPTests(unittest.TestCase):
listener.bind(('127.0.0.1', 0))
cls.port = listener.getsockname()[1]
command = json.loads(os.environ['UHTTPD_COMMAND'])
- command += ['-f', '-p', f'127.0.0.1:{cls.port}', '-h', str(directory), '-x', '/onvif']
+ command += ['-f', '-p', f'0.0.0.0:{cls.port}', '-p', f'[::1]:{cls.port}',
+ '-h', str(directory), '-x', '/onvif']
cls.server = subprocess.Popen(command, env=dict(os.environ, ONVIF_LOG_FILE='-'),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
cls.addClassCleanup(cls.stop_server)
@@ -52,11 +53,11 @@ class HTTPTests(unittest.TestCase):
cls.server.terminate()
cls.server.wait(timeout=5)
- def post(self, operation):
+ def post(self, operation, address='127.0.0.1', content='<tr2:Type>All</tr2:Type>'):
body = (f'<s:Envelope xmlns:s="{NS["s"]}"><s:Body>'
- f'<tr2:{operation} xmlns:tr2="{NS["tr2"]}"><tr2:Type>All</tr2:Type>'
+ f'<tr2:{operation} xmlns:tr2="{NS["tr2"]}">{content}'
f'</tr2:{operation}></s:Body></s:Envelope>')
- connection = http.client.HTTPConnection('127.0.0.1', self.port, timeout=5)
+ connection = http.client.HTTPConnection(address, self.port, timeout=5)
self.addCleanup(connection.close)
connection.request('POST', '/onvif/media2_service', body.encode(),
{'Content-Type': 'application/soap+xml; charset=utf-8'})
@@ -78,6 +79,14 @@ class HTTPTests(unittest.TestCase):
self.assertEqual(status, 500)
self.assertIsNotNone(root.find('.//s:Fault', NS))
+ def test_socket_local_stream_uris(self):
+ for address, host in [('127.0.0.1', '127.0.0.1'),
+ ('127.0.0.2', '127.0.0.2'), ('::1', '[::1]')]:
+ status, root = self.post('GetStreamUri', address,
+ '<tr2:ProfileToken>Profile_0</tr2:ProfileToken>')
+ self.assertEqual(status, 200)
+ self.assertEqual(root.findtext('.//{*}Uri'), f'rtsp://{host}:8554/camera/0')
+
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,314 @@
From 60adcc31208a3eb29d2b7c6346b1908aa4f10bbd Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 17:05:10 +0100
Subject: [PATCH 17/19] feat: configure a shared device UUID for CGI and
discovery
A device reached through several interfaces needs one endpoint identity.
Accept a configured UUID in text and JSON configurations and through the
discovery command line. Validate and canonicalise the shared value while
retaining MAC-derived identities for existing configurations.
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
README.md | 10 +++++++-
conf.c | 42 ++++++++++++++++++--------------
onvif_simple_server.conf.example | 1 +
test/test_cgi.py | 13 ++++++++++
test/test_utils.c | 18 ++++++++++++++
utils.c | 20 +++++++++++++++
utils.h | 1 +
wsd_simple_server.c | 17 ++++++++++---
8 files changed, 99 insertions(+), 23 deletions(-)
--- a/README.md
+++ b/README.md
@@ -123,6 +123,7 @@ manufacturer=Yi
firmware_ver=x.y.z
hardware_id=AFUS
serial_num=AFUSY12ABCDE3F456789
+device_uuid=b47bd8ea-7b8b-58c7-8354-88dbaddf57aa
#ifs=wlan0 # optional: override interface (auto-detected from client address if omitted)
port=80
scope=onvif://www.onvif.org/Profile/Streaming
@@ -313,8 +314,13 @@ Check the code for information.
### wsd_simple_server
wsd_simple server supports the following options
+Set `device_uuid` in the CGI configuration and pass the same UUID through
+`--uuid` to discovery. This keeps one device identity across network
+interfaces and address families. Generate and persist a distinct UUID for
+each device instance. Omitting it retains MAC-derived identity selection.
+
```
-Usage: /tmp/sd/yi-hack/bin/wsd_simple_server [-i INTERFACE] -x XADDR [-m MODEL] [-n MANUFACTURER] -p PID_FILE [-t TEMPLATE_DIR] [-f] [-d LEVEL]
+Usage: /tmp/sd/yi-hack/bin/wsd_simple_server [-i INTERFACE] -x XADDR [-m MODEL] [-n MANUFACTURER] -p PID_FILE [-u UUID] [-t TEMPLATE_DIR] [-f] [-d LEVEL]
-i, --if_name
network interface (auto-detected; use -i to force a specific interface)
@@ -327,6 +333,8 @@ Usage: /tmp/sd/yi-hack/bin/wsd_simple_se
hardware manufacturer
-p, --pid_file
pid file
+ -u, --uuid
+ configured device UUID
-t, --template_dir
template directory (default: /etc/wsd_simple_server)
-f, --foreground
--- a/conf.c
+++ b/conf.c
@@ -138,6 +138,19 @@ static int service_address_resolve(void)
return 0;
}
+static void service_identity_resolve(void)
+{
+ uint8_t mac[6] = {0};
+
+ if (service_ctx.device_uuid[0])
+ return;
+ if (get_mac_by_ifname(service_ctx.ifs, mac) == 0)
+ gen_uuid_v5_mac(service_ctx.device_uuid, mac);
+ else
+ gen_uuid(service_ctx.device_uuid);
+ log_info("Device UUID: %s", service_ctx.device_uuid);
+}
+
int process_conf_file(char *file)
{
FILE *fF;
@@ -162,6 +175,7 @@ int process_conf_file(char *file)
service_ctx.serial_num = NULL;
service_ctx.hardware_id = NULL;
service_ctx.ifs = NULL;
+ service_ctx.device_uuid[0] = '\0';
service_ctx.factory_default_command = NULL;
service_ctx.adv_enable_media2 = 0;
service_ctx.adv_empty_if_unknown = 0;
@@ -287,6 +301,9 @@ int process_conf_file(char *file)
} else if (strcasecmp(param, "hardware_id") == 0) {
service_ctx.hardware_id = (char *) malloc(strlen(value) + 1);
snprintf(service_ctx.hardware_id, strlen(value) + 1, "%s", value);
+ } else if (strcasecmp(param, "device_uuid") == 0) {
+ if (uuid_string_set(service_ctx.device_uuid, value))
+ return -2;
} else if (strcasecmp(param, "scope") == 0) {
service_ctx.scopes_num++;
service_ctx.scopes = (char **) realloc(service_ctx.scopes, service_ctx.scopes_num * sizeof(char *));
@@ -788,15 +805,7 @@ int process_conf_file(char *file)
if (service_address_resolve())
return -2;
- /* Stable device UUID from MAC */
- {
- uint8_t mac[6] = {0};
- if (get_mac_by_ifname(service_ctx.ifs, mac) == 0)
- gen_uuid_v5_mac(service_ctx.device_uuid, mac);
- else
- gen_uuid(service_ctx.device_uuid);
- log_info("Device UUID: %s", service_ctx.device_uuid);
- }
+ service_identity_resolve();
return profiles_validate();
}
@@ -909,6 +918,7 @@ int process_json_conf_file(char *file)
service_ctx.serial_num = NULL;
service_ctx.hardware_id = NULL;
service_ctx.ifs = NULL;
+ service_ctx.device_uuid[0] = '\0';
service_ctx.factory_default_command = NULL;
service_ctx.adv_enable_media2 = 0;
service_ctx.adv_empty_if_unknown = 0;
@@ -964,6 +974,10 @@ int process_json_conf_file(char *file)
get_string_from_json(&(service_ctx.serial_num), json_file, "serial_num");
get_string_from_json(&(service_ctx.factory_default_command), json_file, "factory_default_command");
get_string_from_json(&(service_ctx.ifs), json_file, "ifs");
+ if (json_object_object_get_ex(json_file, "device_uuid", &value) &&
+ (!json_object_is_type(value, json_type_string) ||
+ uuid_string_set(service_ctx.device_uuid, json_object_get_string(value))))
+ return -2;
get_int_from_json(&(service_ctx.port), json_file, "port");
if (json_object_object_get_ex(json_file, "scopes", &value)) {
@@ -1025,15 +1039,7 @@ int process_json_conf_file(char *file)
if (service_address_resolve())
return -2;
- /* Stable device UUID from MAC */
- {
- uint8_t mac[6] = {0};
- if (get_mac_by_ifname(service_ctx.ifs, mac) == 0)
- gen_uuid_v5_mac(service_ctx.device_uuid, mac);
- else
- gen_uuid(service_ctx.device_uuid);
- log_info("Device UUID: %s", service_ctx.device_uuid);
- }
+ service_identity_resolve();
// Print debug
log_debug("model: %s", service_ctx.model);
--- a/onvif_simple_server.conf.example
+++ b/onvif_simple_server.conf.example
@@ -4,6 +4,7 @@ firmware_ver=0.0.1
hardware_id=HWID
serial_num=SN1234567890
#ifs=wlan0 # optional: override interface (auto-detected from client address if omitted)
+#device_uuid=b47bd8ea-7b8b-58c7-8354-88dbaddf57aa
port=8080
scope=onvif://www.onvif.org/Profile/Streaming
scope=onvif://www.onvif.org/Profile/T
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -83,6 +83,19 @@ def helper_configuration():
class CGITests(unittest.TestCase):
+ def test_configured_device_identity(self):
+ identifier = 'b47bd8ea-7b8b-58c7-8354-88dbaddf57aa'
+ config = configuration(1)
+ config['device_uuid'] = identifier
+ text = ('ifs=lo\ndevice_uuid=' + identifier + '\nname=Profile_0\n'
+ 'width=640\nheight=480\ntype=H264\naudio_encoder=NONE\n')
+ for settings in [config, text]:
+ for address in ['192.0.2.10', '2001:db8::10']:
+ status, root = request('device', 'GetEndpointReference', config=settings,
+ server_address=address)
+ self.assertEqual(status, 200)
+ self.assertEqual(root.findtext('.//{*}GUID'), 'urn:uuid:' + identifier)
+
def test_socket_local_addresses(self):
text = ('ifs=lo\nname=Profile_0\nwidth=640\nheight=480\ntype=H264\n'
'url=rtsp://%s:8554/test\naudio_encoder=NONE\n')
--- a/test/test_utils.c
+++ b/test/test_utils.c
@@ -124,6 +124,23 @@ static void test_determinism(void)
/* -------------------------------------------------------------------------
* main
* ---------------------------------------------------------------------- */
+static void test_configured_uuid(void)
+{
+ char uuid[UUID_LEN + 2];
+
+ uuid[UUID_LEN + 1] = 'x';
+ CHECK("configured UUID accepted",
+ uuid_string_set(uuid, "B47BD8EA-7B8B-58C7-8354-88DBADDF57AA") == 0);
+ CHECK("configured UUID canonicalised",
+ !strcmp(uuid, "b47bd8ea-7b8b-58c7-8354-88dbaddf57aa"));
+ CHECK("configured UUID canary preserved", uuid[UUID_LEN + 1] == 'x');
+ CHECK("short UUID rejected", uuid_string_set(uuid, "1234") < 0);
+ CHECK("UUID separators checked",
+ uuid_string_set(uuid, "b47bd8ea_7b8b-58c7-8354-88dbaddf57aa") < 0);
+ CHECK("UUID hexadecimal checked",
+ uuid_string_set(uuid, "z47bd8ea-7b8b-58c7-8354-88dbaddf57aa") < 0);
+}
+
int main(void)
{
printf("=== test_utils: gen_uuid_v5_mac ===\n");
@@ -131,6 +148,7 @@ int main(void)
test_output_format();
test_determinism();
test_buffer_canary();
+ test_configured_uuid();
printf("---\n%d/%d passed", g_pass, g_tests);
if (g_fail)
printf(" (%d FAILED)", g_fail);
--- a/utils.c
+++ b/utils.c
@@ -1473,6 +1473,26 @@ int detect_local_address(const char *rem
return connect_trick_v4(clean, local_addr, len);
}
+int uuid_string_set(char *destination, const char *value)
+{
+ int i;
+
+ if (!value || strlen(value) != UUID_LEN)
+ return -1;
+ for (i = 0; i < UUID_LEN; i++) {
+ if (i == 8 || i == 13 || i == 18 || i == 23) {
+ if (value[i] != '-')
+ return -1;
+ } else if (!isxdigit((unsigned char)value[i])) {
+ return -1;
+ }
+ }
+ for (i = 0; i < UUID_LEN; i++)
+ destination[i] = tolower((unsigned char)value[i]);
+ destination[UUID_LEN] = '\0';
+ return 0;
+}
+
void gen_uuid_v5_mac(char *uuid_str, const uint8_t mac[6])
{
char name[32];
--- a/utils.h
+++ b/utils.h
@@ -110,6 +110,7 @@ int detect_outbound_address_v6(char *add
int get_ip6_address(char *addr_str, size_t len, const char *if_name);
int detect_local_address(const char *remote_addr, char *local_addr, size_t len);
void gen_uuid_v5_mac(char *uuid_str, const uint8_t mac[6]);
+int uuid_string_set(char *destination, const char *value);
int get_from_query_string(char **ret, int *ret_size, char *par);
int set_video_codec(char *buffer, int buffer_len, int codec, int ver);
int set_audio_codec(char *buffer, int buffer_len, int codec, int ver);
--- a/wsd_simple_server.c
+++ b/wsd_simple_server.c
@@ -218,7 +218,8 @@ void signal_handler(int signal)
void print_usage(char *progname)
{
- fprintf(stderr, "\nUsage: %s [-i INTERFACE] -x XADDR [-m MODEL] [-n MANUFACTURER] -p PID_FILE [-t TEMPLATE_DIR] [-f] [-d LEVEL]\n\n", progname);
+ fprintf(stderr, "\nUsage: %s [-i INTERFACE] -x XADDR [-m MODEL] [-n MANUFACTURER] "
+ "-p PID_FILE [-u UUID] [-t TEMPLATE_DIR] [-f] [-d LEVEL]\n\n", progname);
fprintf(stderr, "\t-i, --if_name\n");
fprintf(stderr, "\t\tnetwork interface (auto-detected; use -i to force a specific interface)\n");
fprintf(stderr, "\t-x, --xaddr\n");
@@ -230,6 +231,8 @@ void print_usage(char *progname)
fprintf(stderr, "\t\thardware manufacturer\n");
fprintf(stderr, "\t-p, --pid_file\n");
fprintf(stderr, "\t\tpid file\n");
+ fprintf(stderr, "\t-u, --uuid\n");
+ fprintf(stderr, "\t\tconfigured device UUID\n");
fprintf(stderr, "\t-t, --template_dir\n");
fprintf(stderr, "\t\ttemplate directory (default: %s)\n", DEFAULT_TEMPLATE_DIR);
fprintf(stderr, "\t-f, --foreground\n");
@@ -315,6 +318,7 @@ int main(int argc, char **argv)
{"if_name", required_argument, 0, 'i'},
{"pid_file", required_argument, 0, 'p'},
{"xaddr", required_argument, 0, 'x'},
+ {"uuid", required_argument, 0, 'u'},
{"model", required_argument, 0, 'm'},
{"hardware", required_argument, 0, 'n'},
@@ -325,12 +329,18 @@ int main(int argc, char **argv)
{0, 0, 0, 0}
};
int option_index = 0;
- c = getopt_long(argc, argv, "i:p:x:m:n:t:fd:h", long_options, &option_index);
+ c = getopt_long(argc, argv, "i:p:x:u:m:n:t:fd:h", long_options, &option_index);
if (c == -1) break;
switch (c) {
case 'i': if_name = optarg; break;
case 'x': xaddr_s = optarg; break;
+ case 'u':
+ if (uuid_string_set(uuid, optarg)) {
+ print_usage(argv[0]);
+ exit(EXIT_FAILURE);
+ }
+ break;
case 'm':
if (strlen(optarg) < sizeof(model)) snprintf(model, sizeof(model), "%s", optarg);
@@ -440,8 +450,7 @@ int main(int argc, char **argv)
fclose(fLog); exit(EXIT_FAILURE);
}
- /* ---- Stable UUID from MAC (WS-Discovery 1.1 EPR stability req.) ---- */
- {
+ if (!uuid[0]) {
uint8_t mac[6] = {0};
int mac_ok;
if (if_name) {
@@ -0,0 +1,52 @@
From d5e3c45c758d84c23bbcde1affbb45b81aa3c5d3 Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 17:25:26 +0100
Subject: [PATCH 19/19] fix: validate discovery debug levels before conversion
The debug argument was narrowed to int before checking its range,
allowing large values to wrap into accepted levels. Validate strtol
errors, the complete input and the long result before assigning the
logging level.
Fixes: e1c34ca6dd91 ("First commit")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
wsd_simple_server.c | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
--- a/wsd_simple_server.c
+++ b/wsd_simple_server.c
@@ -311,13 +311,13 @@ static void handle_probe(struct discover
* ---------------------------------------------------------------------- */
int main(int argc, char **argv)
{
- int errno;
char *endptr;
int c, ret;
char *if_name, *pid_file, *xaddr_s;
struct discovery_packet packet;
const char *log_file;
int foreground;
+ long debug_level;
char recv_buffer[RECV_BUFFER_LEN];
if_name = pid_file = xaddr_s = NULL;
@@ -371,13 +371,13 @@ int main(int argc, char **argv)
break;
case 'f': foreground = 1; break;
case 'd':
- debug = strtol(optarg, &endptr, 10);
- if ((errno == ERANGE && (debug == LONG_MAX || debug == LONG_MIN)) ||
- (errno != 0 && debug == 0) || endptr == optarg ||
- debug < LOG_TRACE || debug > LOG_FATAL) {
+ errno = 0;
+ debug_level = strtol(optarg, &endptr, 10);
+ if (errno || endptr == optarg || *endptr ||
+ debug_level < LOG_TRACE || debug_level > LOG_FATAL) {
print_usage(argv[0]); exit(EXIT_FAILURE);
}
- debug = 5 - debug;
+ debug = LOG_FATAL - debug_level;
break;
case 'h': print_usage(argv[0]); exit(EXIT_SUCCESS);
case '?': break;
@@ -0,0 +1,240 @@
From 629527e5ff80139230b0909f48da9a0a0417f2ee Mon Sep 17 00:00:00 2001
From: Daniel Golle <daniel@makrotopia.org>
Date: Sun, 18 Oct 2026 23:38:45 +0100
Subject: [PATCH] fix: escape device information as XML text
Identity values containing XML metacharacters produce malformed device
information responses. Render identity templates through the shared XML
substitution helper so values retain their literal text and the renderer
escapes them during serialisation. Preserve compressed template support
and literal placeholder strings in identity values.
Fixes: e1c34ca6dd91 ("First commit")
Signed-off-by: Daniel Golle <daniel@makrotopia.org>
---
device_advertisement.c | 26 ++------------------------
device_service.c | 33 ++++++++++++++++++---------------
soap.c | 24 ++++++++++++++++++++++++
soap.h | 6 ++++++
test/test_cgi.py | 24 ++++++++++++++++++++++++
test/test_compressed.py | 12 +++++++++---
6 files changed, 83 insertions(+), 42 deletions(-)
--- a/device_advertisement.c
+++ b/device_advertisement.c
@@ -12,28 +12,6 @@
extern service_context_t service_ctx;
-struct template_value {
- const char *key;
- const char *value;
-};
-
-static void template_fill(ezxml_t node, const struct template_value *values)
-{
- ezxml_t child;
- int i;
- int j;
-
- for (i = 0; values[i].key; i++) {
- if (!strcmp(node->txt, values[i].key))
- ezxml_set_txt_d(node, values[i].value);
- for (j = 0; node->attr[j]; j += 2)
- if (!strcmp(node->attr[j + 1], values[i].key))
- ezxml_set_attr_d(node, node->attr[j], values[i].value);
- }
- for (child = node->child; child; child = child->ordered)
- template_fill(child, values);
-}
-
static void imaging_service_add(ezxml_t response, const char *address, int include)
{
ezxml_t service;
@@ -80,7 +58,7 @@ int device_advertisement_send(int servic
int audio_output;
int include;
int i;
- struct template_value values[] = {
+ struct soap_template_value values[] = {
{ "%DEVICE_SERVICE_ADDRESS%", device },
{ "%MEDIA_SERVICE_ADDRESS%", media },
{ "%MEDIA2_SERVICE_ADDRESS%", media2 },
@@ -161,7 +139,7 @@ int device_advertisement_send(int servic
ezxml_free(envelope);
return send_action_failed_fault("device_service", -1);
}
- template_fill(envelope, values);
+ soap_template_fill(envelope, values);
media_capabilities_update(envelope);
response = envelope->child->child;
if (service_ctx.imaging_helper) {
--- a/device_service.c
+++ b/device_service.c
@@ -24,6 +24,7 @@
#include "device_service.h"
#include "device_advertisement.h"
+#include "soap.h"
#include "fault.h"
#include "utils.h"
#include "log.h"
@@ -48,21 +49,23 @@ int device_get_service_capabilities()
int device_get_device_information()
{
- long size = cat(NULL, "device_service_files/GetDeviceInformation.xml", 10,
- "%MANUFACTURER%", service_ctx.manufacturer,
- "%MODEL%", service_ctx.model,
- "%FIRMWARE_VERSION%", service_ctx.firmware_ver,
- "%SERIAL_NUMBER%", service_ctx.serial_num,
- "%HARDWARE_ID%", service_ctx.hardware_id);
-
- output_http_headers(size);
-
- return cat("stdout", "device_service_files/GetDeviceInformation.xml", 10,
- "%MANUFACTURER%", service_ctx.manufacturer,
- "%MODEL%", service_ctx.model,
- "%FIRMWARE_VERSION%", service_ctx.firmware_ver,
- "%SERIAL_NUMBER%", service_ctx.serial_num,
- "%HARDWARE_ID%", service_ctx.hardware_id);
+ struct soap_template_value values[] = {
+ { "%MANUFACTURER%", service_ctx.manufacturer },
+ { "%MODEL%", service_ctx.model },
+ { "%FIRMWARE_VERSION%", service_ctx.firmware_ver },
+ { "%SERIAL_NUMBER%", service_ctx.serial_num },
+ { "%HARDWARE_ID%", service_ctx.hardware_id },
+ { NULL, NULL }
+ };
+ ezxml_t envelope;
+
+ envelope = soap_template_load("device_service_files/GetDeviceInformation.xml");
+ if (!envelope || *ezxml_error(envelope)) {
+ ezxml_free(envelope);
+ return send_action_failed_fault("device_service", -1);
+ }
+ soap_template_fill(envelope, values);
+ return soap_response_send(envelope);
}
int device_get_system_date_and_time()
--- a/soap.c
+++ b/soap.c
@@ -59,6 +59,30 @@ ezxml_t soap_response_create(int version
return soap_member_add(body, version, name);
}
+void soap_template_fill(ezxml_t node, const struct soap_template_value *values)
+{
+ ezxml_t child;
+ int i;
+ int j;
+
+ for (i = 0; values[i].key; i++) {
+ if (strcmp(node->txt, values[i].key))
+ continue;
+ ezxml_set_txt_d(node, values[i].value);
+ break;
+ }
+ for (j = 0; node->attr[j]; j += 2) {
+ for (i = 0; values[i].key; i++) {
+ if (strcmp(node->attr[j + 1], values[i].key))
+ continue;
+ ezxml_set_attr_d(node, node->attr[j], values[i].value);
+ break;
+ }
+ }
+ for (child = node->child; child; child = child->ordered)
+ soap_template_fill(child, values);
+}
+
ezxml_t soap_template_load(char *filename)
{
ezxml_t document;
--- a/soap.h
+++ b/soap.h
@@ -4,12 +4,18 @@
#include "ezxml/ezxml.h"
+struct soap_template_value {
+ const char *key;
+ const char *value;
+};
+
ezxml_t soap_child_add(ezxml_t parent, const char *name, const char *text);
ezxml_t soap_number_add(ezxml_t parent, const char *name, double value);
void soap_range_add(ezxml_t parent, const char *name, double minimum, double maximum);
ezxml_t soap_member_add(ezxml_t parent, int version, const char *name);
ezxml_t soap_response_create(int version, const char *operation);
ezxml_t soap_template_load(char *filename);
+void soap_template_fill(ezxml_t node, const struct soap_template_value *values);
int soap_response_send(ezxml_t response);
#endif
--- a/test/test_cgi.py
+++ b/test/test_cgi.py
@@ -83,6 +83,30 @@ def helper_configuration():
class CGITests(unittest.TestCase):
+ def test_device_information_xml_text(self):
+ fields = {
+ 'manufacturer': ('Manufacturer', 'Vendor & Partners'),
+ 'model': ('Model', 'Camera <one> "special"'),
+ 'firmware_ver': ('FirmwareVersion', 'OS > 1 & < 2'),
+ 'serial_num': ('SerialNumber', 'serial&<123>'),
+ 'hardware_id': ('HardwareId', 'board_%MODEL% & "revision"'),
+ }
+ config = configuration(1)
+ config.update({key: value for key, (name, value) in fields.items()})
+ text = ('ifs=lo\nname=Profile_0\nwidth=640\nheight=480\ntype=H264\n'
+ 'audio_encoder=NONE\n' +
+ ''.join(f'{key}={value}\n' for key, (name, value) in fields.items()))
+ for settings in [config, text]:
+ status, root = request('device', 'GetDeviceInformation', config=settings)
+ self.assertEqual(status, 200)
+ for name, value in fields.values():
+ self.assertEqual(root.findtext('.//{*}' + name), value)
+ config.update(manufacturer='%MODEL%', model='%HARDWARE_ID%')
+ status, root = request('device', 'GetDeviceInformation', config=config)
+ self.assertEqual(status, 200)
+ self.assertEqual(root.findtext('.//{*}Manufacturer'), '%MODEL%')
+ self.assertEqual(root.findtext('.//{*}Model'), '%HARDWARE_ID%')
+
def test_configured_device_identity(self):
identifier = 'b47bd8ea-7b8b-58c7-8354-88dbaddf57aa'
config = configuration(1)
--- a/test/test_compressed.py
+++ b/test/test_compressed.py
@@ -3,7 +3,7 @@ from pathlib import Path
import tempfile
import unittest
-from test_cgi import request, ROOT
+from test_cgi import configuration, request, ROOT
class CompressedTests(unittest.TestCase):
@@ -14,13 +14,19 @@ class CompressedTests(unittest.TestCase)
target.parent.mkdir(exist_ok=True)
target.with_suffix('.xml.gz').write_bytes(gzip.compress(source.read_bytes()))
for service, operation, content in [
+ ('device', 'GetDeviceInformation', ''),
('device', 'GetServices', '<IncludeCapability>true</IncludeCapability>'),
('device', 'GetCapabilities', ''),
('media', 'GetServiceCapabilities', ''),
('media2', 'GetServiceCapabilities', '')]:
with self.subTest(service=service, operation=operation):
- self.assertEqual(request(service, operation, content,
- template_dir=directory)[0], 200)
+ config = configuration()
+ config['model'] = 'Camera & <node>'
+ status, root = request(service, operation, content,
+ config=config, template_dir=directory)
+ self.assertEqual(status, 200)
+ if operation == 'GetDeviceInformation':
+ self.assertEqual(root.findtext('.//{*}Model'), config['model'])
if __name__ == '__main__':
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
#
# SPDX-License-Identifier: GPL-2.0-only
# shellcheck shell=busybox
case "$PKG_NAME" in
onvif-simple-server)
# The executables do not report a version
exit 0
;;
*)
echo "Untested package: $PKG_NAME" >&2
exit 1
;;
esac