From a3cc8482f4037f118bc135cfca191c7cb6250aa6 Mon Sep 17 00:00:00 2001 From: Daniel Golle Date: Fri, 13 Nov 2026 14:10:18 +0000 Subject: [PATCH] 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 --- multimedia/onvif-simple-server/Makefile | 63 + .../onvif-simple-server/files/onvif.cgi | 21 + .../onvif-simple-server/files/onvif.config | 3 + .../onvif-simple-server/files/onvif.defaults | 17 + .../onvif-simple-server/files/onvif.init | 56 + ...-accept-constant-response-parameters.patch | 37 + ...t-CGI-status-headers-for-SOAP-faults.patch | 114 + ...003-feat-allow-CGI-logging-to-stderr.patch | 128 ++ ...file-bitrate-from-JSON-configuration.patch | 41 + ...onfigured-media-profiles-without-a-t.patch | 1933 +++++++++++++++++ ...nfigured-video-encoding-parameters-a.patch | 1320 +++++++++++ ...P-request-elements-without-suffix-un.patch | 627 ++++++ ...ric-external-control-helper-protocol.patch | 548 +++++ ...coder-configuration-to-external-help.patch | 855 ++++++++ ...ra-imaging-through-optional-control-.patch | 1090 ++++++++++ ...ilities-for-every-configured-video-p.patch | 567 +++++ ...dia-and-imaging-responses-through-sc.patch | 285 +++ ...erated-media-responses-and-missing-U.patch | 187 ++ ...sed-templates-for-generated-capabili.patch | 202 ++ ...oder-changes-before-invoking-control.patch | 443 ++++ ...I-connection-address-in-service-URLs.patch | 250 +++ ...-shared-device-UUID-for-CGI-and-disc.patch | 314 +++ ...r-on-all-suitable-network-interfaces.patch | 1458 +++++++++++++ ...covery-debug-levels-before-conversio.patch | 52 + ...scape-device-information-as-XML-text.patch | 240 ++ .../onvif-simple-server/test-version.sh | 17 + 26 files changed, 10868 insertions(+) create mode 100644 multimedia/onvif-simple-server/Makefile create mode 100644 multimedia/onvif-simple-server/files/onvif.cgi create mode 100644 multimedia/onvif-simple-server/files/onvif.config create mode 100644 multimedia/onvif-simple-server/files/onvif.defaults create mode 100644 multimedia/onvif-simple-server/files/onvif.init create mode 100644 multimedia/onvif-simple-server/patches/0001-fix-accept-constant-response-parameters.patch create mode 100644 multimedia/onvif-simple-server/patches/0002-fix-emit-CGI-status-headers-for-SOAP-faults.patch create mode 100644 multimedia/onvif-simple-server/patches/0003-feat-allow-CGI-logging-to-stderr.patch create mode 100644 multimedia/onvif-simple-server/patches/0004-fix-read-profile-bitrate-from-JSON-configuration.patch create mode 100644 multimedia/onvif-simple-server/patches/0005-feat-enumerate-configured-media-profiles-without-a-t.patch create mode 100644 multimedia/onvif-simple-server/patches/0006-feat-describe-configured-video-encoding-parameters-a.patch create mode 100644 multimedia/onvif-simple-server/patches/0007-fix-traverse-SOAP-request-elements-without-suffix-un.patch create mode 100644 multimedia/onvif-simple-server/patches/0008-feat-add-a-generic-external-control-helper-protocol.patch create mode 100644 multimedia/onvif-simple-server/patches/0009-feat-delegate-encoder-configuration-to-external-help.patch create mode 100644 multimedia/onvif-simple-server/patches/0010-feat-expose-camera-imaging-through-optional-control-.patch create mode 100644 multimedia/onvif-simple-server/patches/0011-fix-report-capabilities-for-every-configured-video-p.patch create mode 100644 multimedia/onvif-simple-server/patches/0012-test-validate-media-and-imaging-responses-through-sc.patch create mode 100644 multimedia/onvif-simple-server/patches/0013-fix-validate-generated-media-responses-and-missing-U.patch create mode 100644 multimedia/onvif-simple-server/patches/0014-fix-load-compressed-templates-for-generated-capabili.patch create mode 100644 multimedia/onvif-simple-server/patches/0015-fix-validate-encoder-changes-before-invoking-control.patch create mode 100644 multimedia/onvif-simple-server/patches/0016-fix-use-the-CGI-connection-address-in-service-URLs.patch create mode 100644 multimedia/onvif-simple-server/patches/0017-feat-configure-a-shared-device-UUID-for-CGI-and-disc.patch create mode 100644 multimedia/onvif-simple-server/patches/0018-feat-discover-on-all-suitable-network-interfaces.patch create mode 100644 multimedia/onvif-simple-server/patches/0019-fix-validate-discovery-debug-levels-before-conversio.patch create mode 100644 multimedia/onvif-simple-server/patches/0020-fix-escape-device-information-as-XML-text.patch create mode 100755 multimedia/onvif-simple-server/test-version.sh diff --git a/multimedia/onvif-simple-server/Makefile b/multimedia/onvif-simple-server/Makefile new file mode 100644 index 0000000000..d8aacded41 --- /dev/null +++ b/multimedia/onvif-simple-server/Makefile @@ -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 +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)) diff --git a/multimedia/onvif-simple-server/files/onvif.cgi b/multimedia/onvif-simple-server/files/onvif.cgi new file mode 100644 index 0000000000..8132686280 --- /dev/null +++ b/multimedia/onvif-simple-server/files/onvif.cgi @@ -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" diff --git a/multimedia/onvif-simple-server/files/onvif.config b/multimedia/onvif-simple-server/files/onvif.config new file mode 100644 index 0000000000..96a6263ff3 --- /dev/null +++ b/multimedia/onvif-simple-server/files/onvif.config @@ -0,0 +1,3 @@ +config server 'main' + option enabled '1' + option config_file '/var/run/onvif-simple-server/config.json' diff --git a/multimedia/onvif-simple-server/files/onvif.defaults b/multimedia/onvif-simple-server/files/onvif.defaults new file mode 100644 index 0000000000..3327a4ca93 --- /dev/null +++ b/multimedia/onvif-simple-server/files/onvif.defaults @@ -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 /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 diff --git a/multimedia/onvif-simple-server/files/onvif.init b/multimedia/onvif-simple-server/files/onvif.init new file mode 100644 index 0000000000..a74d78073f --- /dev/null +++ b/multimedia/onvif-simple-server/files/onvif.init @@ -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 +} diff --git a/multimedia/onvif-simple-server/patches/0001-fix-accept-constant-response-parameters.patch b/multimedia/onvif-simple-server/patches/0001-fix-accept-constant-response-parameters.patch new file mode 100644 index 0000000000..344bce90a3 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0001-fix-accept-constant-response-parameters.patch @@ -0,0 +1,37 @@ +From cfa2eac7512a62bf959eeb7e5ac9de8a6e34862a Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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); diff --git a/multimedia/onvif-simple-server/patches/0002-fix-emit-CGI-status-headers-for-SOAP-faults.patch b/multimedia/onvif-simple-server/patches/0002-fix-emit-CGI-status-headers-for-SOAP-faults.patch new file mode 100644 index 0000000000..e7f2f8ebfc --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0002-fix-emit-CGI-status-headers-for-SOAP-faults.patch @@ -0,0 +1,114 @@ +From 2d449074298d8f25df4e46de60a7a5c54582c8f6 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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 ++ ++#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') diff --git a/multimedia/onvif-simple-server/patches/0003-feat-allow-CGI-logging-to-stderr.patch b/multimedia/onvif-simple-server/patches/0003-feat-allow-CGI-logging-to-stderr.patch new file mode 100644 index 0000000000..b38e5b1997 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0003-feat-allow-CGI-logging-to-stderr.patch @@ -0,0 +1,128 @@ +From ca9fca2c14f99a3f4dfbabdf6a78396104dd82e1 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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'' ++ f'' ++ f'{content}').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() diff --git a/multimedia/onvif-simple-server/patches/0004-fix-read-profile-bitrate-from-JSON-configuration.patch b/multimedia/onvif-simple-server/patches/0004-fix-read-profile-bitrate-from-JSON-configuration.patch new file mode 100644 index 0000000000..d0bec0dcc4 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0004-fix-read-profile-bitrate-from-JSON-configuration.patch @@ -0,0 +1,41 @@ +From ea260f377ba06766e26ff2fbfe7d4ef9dd103ca3 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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) diff --git a/multimedia/onvif-simple-server/patches/0005-feat-enumerate-configured-media-profiles-without-a-t.patch b/multimedia/onvif-simple-server/patches/0005-feat-enumerate-configured-media-profiles-without-a-t.patch new file mode 100644 index 0000000000..11016ebf85 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0005-feat-enumerate-configured-media-profiles-without-a-t.patch @@ -0,0 +1,1933 @@ +From 2f098ae69cb6254e163836c8bc772bed4b651520 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +Date: Sun, 18 Oct 2026 10:04:51 +0100 +Subject: [PATCH 05/15] feat: enumerate configured media profiles without a + two-stream limit + +Share Media1 and Media2 profile, encoder configuration and URI handling. +Build responses with ezxml so each configured stream retains its token +and parameters regardless of its index or the number of sibling streams. +Exercise empty configurations and up to twelve streams through CGI. + +Signed-off-by: Daniel Golle +--- + Makefile | 2 +- + Makefile.static | 2 +- + README.md | 4 +- + media2_service.c | 579 ---------------------------------- + media2_service.h | 6 +- + media_profiles.c | 264 ++++++++++++++++ + media_profiles.h | 7 + + media_service.c | 705 ------------------------------------------ + media_service.h | 9 +- + onvif_simple_server.c | 23 +- + soap.c | 67 ++++ + soap.h | 13 + + test/test_cgi.py | 30 ++ + 13 files changed, 400 insertions(+), 1311 deletions(-) + create mode 100644 media_profiles.c + create mode 100644 media_profiles.h + create mode 100644 soap.c + create mode 100644 soap.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 = 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 = 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 = 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 = 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 +@@ -214,7 +214,9 @@ input_file=/tmp/onvif_notify_server/soun + ``` + + Note: +-- you can use 1 or 2 profiles. ++- Profile listings, encoder configuration reads and stream/snapshot URI ++ lookup accept any configured number of video profiles. Profile names ++ identify streams and should remain stable when configuration order changes. + - **Actually only type=h264 is supported on Profile S and both type=h264 and type=h265 are supported in Profile T.** This doesn't mean that if your camera is h265 then it does not work with Profile S. It depends on your onvif client implementation. + - ipc_cmd is just an example of a local binary that handles ptz, use the specific program of your cam + +--- a/media2_service.c ++++ b/media2_service.c +@@ -78,334 +78,6 @@ int media2_get_service_capabilities() + "%CAPABILITIES%", cap); + } + +-int media2_get_profiles() +-{ +- char profiles_num[2]; +- char stmp_w_h[16], stmp_h_h[16]; +- char stmp_w_l[16], stmp_h_l[16]; +- char stmp_fps_h[16], stmp_fps_l[16]; +- char audio_enc_h[16], audio_enc_l[16]; +- char video_enc_h[16], video_enc_l[16]; +- const char *profile_token = get_element("Token", "Body"); +- ezxml_t x_type; +- int n_type; +- char xml_name[MAX_LEN]; +- long size; +- int q, h; +- char *h264profile[] = { "High", "Main" }; +- char *profile[] = { "Profile_0", "Profile_1" }; +- int c; +- char dest_a[] = "stdout"; +- char *dest; +- int typeVSC = 0, typeASC = 0, typeVEC = 0, typeAEC = 0, typePTZ = 0, typeAOC = 0, typeADC = 0; +- char min_x[256], max_x[256], min_y[256], max_y[256], min_z[256], max_z[256]; +- int vsrc = get_video_source_index(); +- +- audio_enc_h[0] = '\0'; +- audio_enc_l[0] = '\0'; +- video_enc_h[0] = '\0'; +- video_enc_l[0] = '\0'; +- snprintf(profiles_num, sizeof(profiles_num), "%d", service_ctx.profiles_num); +- snprintf(min_x, sizeof(min_x), "%.1f", service_ctx.ptz_node.min_step_x); +- snprintf(max_x, sizeof(max_x), "%.1f", service_ctx.ptz_node.max_step_x); +- snprintf(min_y, sizeof(min_y), "%.1f", service_ctx.ptz_node.min_step_y); +- snprintf(max_y, sizeof(max_y), "%.1f", service_ctx.ptz_node.max_step_y); +- snprintf(min_z, sizeof(min_z), "%.1f", service_ctx.ptz_node.min_step_z); +- snprintf(max_z, sizeof(max_z), "%.1f", service_ctx.ptz_node.max_step_z); +- +- x_type = get_element_ptr(NULL, "Type", "Body"); +- n_type = 0; +- do { +- if (x_type != NULL) { +- if (strstr(x_type->txt, "VideoSource") != NULL) typeVSC = 1; +- if (strstr(x_type->txt, "AudioSource") != NULL) typeASC = 1; +- if (strstr(x_type->txt, "VideoEncoder") != NULL) typeVEC = 1; +- if (strstr(x_type->txt, "AudioEncoder") != NULL) typeAEC = 1; +- if (strstr(x_type->txt, "PTZ") != NULL) typePTZ = 1; +- if (strstr(x_type->txt, "AudioOutput") != NULL) typeAOC = 1; +- if (strstr(x_type->txt, "AudioDecoder") != NULL) typeADC = 1; +- if (strstr(x_type->txt, "All") != NULL) { +- typeVSC = 1; +- typeASC = 1; +- typeVEC = 1; +- typeAEC = 1; +- typePTZ = 1; +- typeAOC = 1; +- typeADC = 1; +- } +- n_type++; +- x_type = x_type->next; +- } +- } while (x_type != NULL); +- +- if (service_ctx.profiles_num == 0) { +- q = 0; +- size = cat(NULL, "media2_service_files/GetProfiles_none.xml", 0); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetProfiles_none.xml", 0); +- +- } else if (profile_token == NULL) { +- if (service_ctx.profiles_num == 1) { +- q = 1; +- h = 0; +- } else if (service_ctx.profiles_num == 2) { +- q = 2; +- } +- } else if ((service_ctx.profiles_num > 0) && +- (strcasecmp(service_ctx.profiles[0].name, profile_token) == 0)) { +- q = 1; +- h = 0; +- } else if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, profile_token) == 0)) { +- q = 1; +- h = 1; +- } else { +- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -1; +- } +- +- if (q == 0) { +- size = cat(NULL, "media2_service_files/GetProfiles_none.xml", 0); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetProfiles_none.xml", 0); +- +- } else if (q == 1) { +- // We need 1st step to evaluate content length +- for (c = 0; c < 2; c++) { +- if (c == 0) { +- dest = NULL; +- } else { +- dest = dest_a; +- output_http_headers(size); +- } +- +- size = cat(dest, "media2_service_files/GetProfiles_header.xml", 2, +- "%PROFILE%", profile[h]); +- +- if (n_type > 0) { +- size += cat(dest, "media2_service_files/GetProfiles_confstart.xml", 0); +- +- if (typeVSC) { +- // Get VideoSource from the largest profile +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[vsrc].height); +- size += cat(dest, "media2_service_files/GetProfiles_VSC.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%VSC_WIDTH%", stmp_w_h, +- "%VSC_HEIGHT%", stmp_h_h); +- } +- if (typeASC) { +- if (((service_ctx.profiles_num > 0) && (service_ctx.profiles[0].audio_encoder != AUDIO_NONE)) || +- ((service_ctx.profiles_num == 2) && (service_ctx.profiles[1].audio_encoder != AUDIO_NONE))) { +- +- size += cat(dest, "media2_service_files/GetProfiles_ASC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- } +- if (typeVEC) { +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[h].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[h].height); +- snprintf(stmp_fps_h, sizeof(stmp_fps_h), "%d", service_ctx.profiles[h].framerate > 0 ? service_ctx.profiles[h].framerate : 30); +- set_video_codec(video_enc_h, 16, service_ctx.profiles[h].type, 2); +- size += cat(dest, "media2_service_files/GetProfiles_VEC.xml", 12, +- "%H264PROFILE%", h264profile[h], +- "%PROFILE%", profile[h], +- "%VIDEO_ENCODING%", video_enc_h, +- "%VEC_WIDTH%", stmp_w_h, +- "%VEC_HEIGHT%", stmp_h_h, +- "%FRAMERATE%", stmp_fps_h); +- } +- if (typeAEC) { +- if (service_ctx.profiles[h].audio_encoder != AUDIO_NONE) { +- set_audio_codec(audio_enc_h, 16, service_ctx.profiles[0].audio_encoder, 2); +- size += cat(dest, "media2_service_files/GetProfiles_AEC.xml", 4, +- "%PROFILE%", profile[h], +- "%AUDIO_ENCODING%", audio_enc_h); +- } +- } +- if (typePTZ) { +- if (service_ctx.ptz_node.enable == 1) { +- size += cat(dest, ptz_supports_zoom() ? "media2_service_files/GetProfiles_PTZ.xml" : "media2_service_files/GetProfiles_PTZ_nozoom.xml", 12, +- "%MIN_X%", min_x, +- "%MAX_X%", max_x, +- "%MIN_Y%", min_y, +- "%MAX_Y%", max_y, +- "%MIN_Z%", min_z, +- "%MAX_Z%", max_z); +- } +- } +- if (service_ctx.profiles[h].audio_decoder != AUDIO_NONE) { +- if (typeAOC) { +- size += cat(dest, "media2_service_files/GetProfiles_AOC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- if (typeADC) { +- size += cat(dest, "media2_service_files/GetProfiles_ADC.xml", 2, +- "%PROFILE%", profile[h]); +- } +- } +- +- size += cat(dest, "media2_service_files/GetProfiles_confend.xml", 0); +- } +- size += cat(dest, "media2_service_files/GetProfiles_footer.xml", 0); +- } +- } else if (q == 2) { +- // We need 1st step to evaluate content length +- for (c = 0; c < 2; c++) { +- if (c == 0) { +- dest = NULL; +- } else { +- dest = dest_a; +- output_http_headers(size); +- } +- +- h = 0; +- size = cat(dest, "media2_service_files/GetProfiles_header.xml", 2, +- "%PROFILE%", profile[h]); +- +- if (n_type > 0) { +- size += cat(dest, "media2_service_files/GetProfiles_confstart.xml", 0); +- +- if (typeVSC) { +- // Get VideoSource from the largest profile +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[vsrc].height); +- size += cat(dest, "media2_service_files/GetProfiles_VSC.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%VSC_WIDTH%", stmp_w_h, +- "%VSC_HEIGHT%", stmp_h_h); +- } +- if (typeASC) { +- if (((service_ctx.profiles_num > 0) && (service_ctx.profiles[0].audio_encoder != AUDIO_NONE)) || +- ((service_ctx.profiles_num == 2) && (service_ctx.profiles[1].audio_encoder != AUDIO_NONE))) { +- +- size += cat(dest, "media2_service_files/GetProfiles_ASC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- } +- if (typeVEC) { +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[h].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[h].height); +- snprintf(stmp_fps_h, sizeof(stmp_fps_h), "%d", service_ctx.profiles[h].framerate > 0 ? service_ctx.profiles[h].framerate : 30); +- set_video_codec(video_enc_h, 16, service_ctx.profiles[h].type, 2); +- size += cat(dest, "media2_service_files/GetProfiles_VEC.xml", 12, +- "%H264PROFILE%", h264profile[h], +- "%PROFILE%", profile[h], +- "%VIDEO_ENCODING%", video_enc_h, +- "%VEC_WIDTH%", stmp_w_h, +- "%VEC_HEIGHT%", stmp_h_h, +- "%FRAMERATE%", stmp_fps_h); +- } +- if (typeAEC) { +- if (service_ctx.profiles[h].audio_encoder != AUDIO_NONE) { +- set_audio_codec(audio_enc_h, 16, service_ctx.profiles[h].audio_encoder, 2); +- size += cat(dest, "media2_service_files/GetProfiles_AEC.xml", 4, +- "%PROFILE%", profile[h], +- "%AUDIO_ENCODING%", audio_enc_h); +- } +- } +- if (typePTZ) { +- if (service_ctx.ptz_node.enable == 1) { +- size += cat(dest, ptz_supports_zoom() ? "media2_service_files/GetProfiles_PTZ.xml" : "media2_service_files/GetProfiles_PTZ_nozoom.xml", 12, +- "%MIN_X%", min_x, +- "%MAX_X%", max_x, +- "%MIN_Y%", min_y, +- "%MAX_Y%", max_y, +- "%MIN_Z%", min_z, +- "%MAX_Z%", max_z); +- } +- } +- if (service_ctx.profiles[h].audio_decoder != AUDIO_NONE) { +- if (typeAOC) { +- size += cat(dest, "media2_service_files/GetProfiles_AOC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- if (typeADC) { +- size += cat(dest, "media2_service_files/GetProfiles_ADC.xml", 2, +- "%PROFILE%", profile[h]); +- } +- } +- +- size += cat(dest, "media2_service_files/GetProfiles_confend.xml", 0); +- } +- +- h = 1; +- size += cat(dest, "media2_service_files/GetProfiles_middle.xml", 2, +- "%PROFILE%", profile[h]); +- +- if (n_type > 0) { +- size += cat(dest, "media2_service_files/GetProfiles_confstart.xml", 0); +- +- if (typeVSC) { +- // Get VideoSource from the largest profile +- snprintf(stmp_w_l, sizeof(stmp_w_l), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_h_l, sizeof(stmp_h_l), "%d", service_ctx.profiles[vsrc].height); +- size += cat(dest, "media2_service_files/GetProfiles_VSC.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%VSC_WIDTH%", stmp_w_l, +- "%VSC_HEIGHT%", stmp_h_l); +- } +- if (typeASC) { +- if (((service_ctx.profiles_num > 0) && (service_ctx.profiles[0].audio_encoder != AUDIO_NONE)) || +- ((service_ctx.profiles_num == 2) && (service_ctx.profiles[1].audio_encoder != AUDIO_NONE))) { +- +- size += cat(dest, "media2_service_files/GetProfiles_ASC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- } +- if (typeVEC) { +- snprintf(stmp_w_l, sizeof(stmp_w_l), "%d", service_ctx.profiles[h].width); +- snprintf(stmp_h_l, sizeof(stmp_h_l), "%d", service_ctx.profiles[h].height); +- snprintf(stmp_fps_l, sizeof(stmp_fps_l), "%d", service_ctx.profiles[h].framerate > 0 ? service_ctx.profiles[h].framerate : 30); +- set_video_codec(video_enc_l, 16, service_ctx.profiles[h].type, 2); +- size += cat(dest, "media2_service_files/GetProfiles_VEC.xml", 12, +- "%H264PROFILE%", h264profile[h], +- "%PROFILE%", profile[h], +- "%VIDEO_ENCODING%", video_enc_l, +- "%VEC_WIDTH%", stmp_w_l, +- "%VEC_HEIGHT%", stmp_h_l, +- "%FRAMERATE%", stmp_fps_l); +- } +- if (typeAEC) { +- if (service_ctx.profiles[h].audio_encoder != AUDIO_NONE) { +- set_audio_codec(audio_enc_l, 16, service_ctx.profiles[h].audio_encoder, 2); +- size += cat(dest, "media2_service_files/GetProfiles_AEC.xml", 4, +- "%PROFILE%", profile[h], +- "%AUDIO_ENCODING%", audio_enc_l); +- } +- } +- if (typePTZ) { +- if (service_ctx.ptz_node.enable == 1) { +- size += cat(dest, ptz_supports_zoom() ? "media2_service_files/GetProfiles_PTZ.xml" : "media2_service_files/GetProfiles_PTZ_nozoom.xml", 12, +- "%MIN_X%", min_x, +- "%MAX_X%", max_x, +- "%MIN_Y%", min_y, +- "%MAX_Y%", max_y, +- "%MIN_Z%", min_z, +- "%MAX_Z%", max_z); +- } +- } +- if (service_ctx.profiles[h].audio_decoder != AUDIO_NONE) { +- if (typeAOC) { +- size += cat(dest, "media2_service_files/GetProfiles_AOC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- if (typeADC) { +- size += cat(dest, "media2_service_files/GetProfiles_ADC.xml", 2, +- "%PROFILE%", profile[h]); +- } +- } +- +- size += cat(dest, "media2_service_files/GetProfiles_confend.xml", 0); +- } +- size += cat(dest, "media2_service_files/GetProfiles_footer.xml", 0); +- } +- } +-} + + int media2_get_video_source_modes() + { +@@ -523,134 +195,6 @@ int media2_get_video_source_configuratio + } + } + +-int media2_get_video_encoder_configurations() +-{ +- char stmp_w_l[16], stmp_h_l[16]; +- char stmp_fps_h[16], stmp_fps_l[16]; +- char stmp_w_h[16], stmp_h_h[16]; +- const char *profile_token = get_element("ProfileToken", "Body"); +- const char *configuration_token = get_element("ConfigurationToken", "Body"); +- char token[10]; +- char video_enc_h[16], video_enc_l[16]; +- +- memset(token, '\0', sizeof(token)); +- if (configuration_token != NULL) { +- // Extract "Profile_x" from token Profile_x_VideoEncoderConfig +- strncpy(token, configuration_token, 9); +- } else if (profile_token != NULL) { +- // Extract "Profile_x" from token Profile_x +- strncpy(token, profile_token, 9); +- } +- +- if (token[0] == '\0') { +- if (service_ctx.profiles_num == 1) { +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_fps_h, sizeof(stmp_fps_h), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- set_video_codec(video_enc_h, 16, service_ctx.profiles[0].type, 2); +- long size = cat(NULL, "media2_service_files/GetVideoEncoderConfigurations.xml", 12, +- "%H264PROFILE%", "High", +- "%PROFILE%", "Profile_0", +- "%WIDTH%", stmp_w_h, +- "%HEIGHT%", stmp_h_h, +- "%FRAMERATE%", stmp_fps_h, +- "%VIDEO_ENCODING%", video_enc_h); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetVideoEncoderConfigurations.xml", 12, +- "%H264PROFILE%", "High", +- "%PROFILE%", "Profile_0", +- "%WIDTH%", stmp_w_h, +- "%HEIGHT%", stmp_h_h, +- "%FRAMERATE%", stmp_fps_h, +- "%VIDEO_ENCODING%", video_enc_h); +- +- } else if (service_ctx.profiles_num == 2) { +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_w_l, sizeof(stmp_w_l), "%d", service_ctx.profiles[1].width); +- snprintf(stmp_h_l, sizeof(stmp_h_l), "%d", service_ctx.profiles[1].height); +- snprintf(stmp_fps_h, sizeof(stmp_fps_h), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- snprintf(stmp_fps_l, sizeof(stmp_fps_l), "%d", service_ctx.profiles[1].framerate > 0 ? service_ctx.profiles[1].framerate : 30); +- set_video_codec(video_enc_h, 16, service_ctx.profiles[0].type, 2); +- set_video_codec(video_enc_l, 16, service_ctx.profiles[1].type, 2); +- long size = cat(NULL, "media2_service_files/GetVideoEncoderConfigurations_both.xml", 16, +- "%WIDTH_HIGH%", stmp_w_h, +- "%HEIGHT_HIGH%", stmp_h_h, +- "%WIDTH_LOW%", stmp_w_l, +- "%HEIGHT_LOW%", stmp_h_l, +- "%FRAMERATE_HIGH%", stmp_fps_h, +- "%FRAMERATE_LOW%", stmp_fps_l, +- "%VIDEO_ENCODING_HIGH%", video_enc_h, +- "%VIDEO_ENCODING_LOW%", video_enc_l); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetVideoEncoderConfigurations_both.xml", 16, +- "%WIDTH_HIGH%", stmp_w_h, +- "%HEIGHT_HIGH%", stmp_h_h, +- "%WIDTH_LOW%", stmp_w_l, +- "%HEIGHT_LOW%", stmp_h_l, +- "%FRAMERATE_HIGH%", stmp_fps_h, +- "%FRAMERATE_LOW%", stmp_fps_l, +- "%VIDEO_ENCODING_HIGH%", video_enc_h, +- "%VIDEO_ENCODING_LOW%", video_enc_l); +- } +- } else if ((service_ctx.profiles_num > 0) && +- (strcasecmp(service_ctx.profiles[0].name, token) == 0)) { +- +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_fps_h, sizeof(stmp_fps_h), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- set_video_codec(video_enc_h, 16, service_ctx.profiles[0].type, 2); +- long size = cat(NULL, "media2_service_files/GetVideoEncoderConfigurations.xml", 12, +- "%H264PROFILE%", "High", +- "%PROFILE%", "Profile_0", +- "%WIDTH%", stmp_w_h, +- "%HEIGHT%", stmp_h_h, +- "%FRAMERATE%", stmp_fps_h, +- "%VIDEO_ENCODING%", video_enc_h); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetVideoEncoderConfigurations.xml", 12, +- "%H264PROFILE%", "High", +- "%PROFILE%", "Profile_0", +- "%WIDTH%", stmp_w_h, +- "%HEIGHT%", stmp_h_h, +- "%FRAMERATE%", stmp_fps_h, +- "%VIDEO_ENCODING%", video_enc_h); +- +- } else if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, token) == 0)) { +- +- snprintf(stmp_w_l, sizeof(stmp_w_l), "%d", service_ctx.profiles[1].width); +- snprintf(stmp_h_l, sizeof(stmp_h_l), "%d", service_ctx.profiles[1].height); +- snprintf(stmp_fps_l, sizeof(stmp_fps_l), "%d", service_ctx.profiles[1].framerate > 0 ? service_ctx.profiles[1].framerate : 30); +- set_video_codec(video_enc_l, 16, service_ctx.profiles[1].type, 2); +- long size = cat(NULL, "media2_service_files/GetVideoEncoderConfigurations.xml", 12, +- "%H264PROFILE%", "Main", +- "%PROFILE%", "Profile_1", +- "%WIDTH%", stmp_w_l, +- "%HEIGHT%", stmp_h_l, +- "%FRAMERATE%", stmp_fps_l, +- "%VIDEO_ENCODING%", video_enc_l); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetVideoEncoderConfigurations.xml", 12, +- "%H264PROFILE%", "Main", +- "%PROFILE%", "Profile_1", +- "%WIDTH%", stmp_w_l, +- "%HEIGHT%", stmp_h_l, +- "%FRAMERATE%", stmp_fps_l, +- "%VIDEO_ENCODING%", video_enc_l); +- } else { +- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -1; +- } +-} + + int media2_get_video_encoder_configuration_options() + { +@@ -1298,130 +842,7 @@ int media2_get_audio_decoder_configurati + } + } + +-int media2_get_snapshot_uri() +-{ +- char *s; +- char line[MAX_LEN]; +- const char *profile_token = get_element("ProfileToken", "Body"); +- +- memset(line, '\0', sizeof(line)); +- +- if (profile_token == NULL) { +- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -1; +- } +- +- if ((service_ctx.profiles_num > 0) && +- (strcasecmp(service_ctx.profiles[0].name, profile_token) == 0)) { +- +- if (service_ctx.profiles[0].snapurl == NULL) { +- send_fault("media2_service", "Receiver", "ter:Action", "ter:IncompleteConfiguration", "Incomplete configuration", "The specified media profile does not contain either a reference to a video encoder configuration or a reference to a video source configuration"); +- return -2; +- } +- +- if (snprintf(line, sizeof(line), service_ctx.profiles[0].snapurl, service_ctx.address_url) < 0) { +- snprintf(line, sizeof(line), "%s", service_ctx.profiles[0].snapurl); +- } +- // Escape html chars +- html_escape(line, MAX_LEN); +- +- long size = cat(NULL, "media2_service_files/GetSnapshotUri.xml", 2, +- "%URI%", line); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetSnapshotUri.xml", 2, +- "%URI%", line); +- +- } else if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, profile_token) == 0)) { +- +- if (service_ctx.profiles[1].snapurl == NULL) { +- send_fault("media2_service", "Receiver", "ter:Action", "ter:IncompleteConfiguration", "Incomplete configuration", "The specified media profile does not contain either a reference to a video encoder configuration or a reference to a video source configuration"); +- return -3; +- } +- +- if (snprintf(line, sizeof(line), service_ctx.profiles[1].snapurl, service_ctx.address_url) < 0) { +- snprintf(line, sizeof(line), "%s", service_ctx.profiles[1].snapurl); +- } +- // Escape html chars +- html_escape(line, MAX_LEN); +- +- long size = cat(NULL, "media2_service_files/GetSnapshotUri.xml", 2, +- "%URI%", line); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetSnapshotUri.xml", 2, +- "%URI%", line); +- +- } else { +- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -4; +- } +-} +- +-int media2_get_stream_uri() +-{ +- char *s; +- char line[MAX_LEN]; +- const char *profile_token = get_element("ProfileToken", "Body"); +- +- memset(line, '\0', sizeof(line)); +- +- if (profile_token == NULL) { +- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -1; +- } +- +- if (strcasecmp(service_ctx.profiles[0].name, profile_token) == 0) { +- +- if (service_ctx.profiles[0].url == NULL) { +- send_fault("media2_service", "Receiver", "ter:Action", "ter:IncompleteConfiguration", "Incomplete configuration", "The specified media profile does contain either unused sources or encoder configurations without a corresponding source"); +- return -2; +- } +- +- if (snprintf(line, sizeof(line), service_ctx.profiles[0].url, service_ctx.address_url) < 0) { +- snprintf(line, sizeof(line), "%s", service_ctx.profiles[0].url); +- } +- // Escape html chars +- html_escape(line, MAX_LEN); +- +- long size = cat(NULL, "media2_service_files/GetStreamUri.xml", 2, +- "%URI%", line); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetStreamUri.xml", 2, +- "%URI%", line); +- +- } else if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, profile_token) == 0)) { +- +- if (service_ctx.profiles[1].url == NULL) { +- send_fault("media2_service", "Receiver", "ter:Action", "ter:IncompleteConfiguration", "Incomplete configuration", "The specified media profile does contain either unused sources or encoder configurations without a corresponding source"); +- return -3; +- } +- +- if (snprintf(line, sizeof(line), service_ctx.profiles[1].url, service_ctx.address_url) < 0) { +- snprintf(line, sizeof(line), "%s", service_ctx.profiles[1].url); +- } +- // Escape html chars +- html_escape(line, MAX_LEN); +- +- long size = cat(NULL, "media2_service_files/GetStreamUri.xml", 2, +- "%URI%", line); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetStreamUri.xml", 2, +- "%URI%", line); + +- } else { +- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -4; +- } +-} + + int media2_set_video_source_configuration() + { +--- a/media2_service.h ++++ b/media2_service.h +@@ -18,11 +18,9 @@ + #define MEDIA2_SERVICE_H + + int media2_get_service_capabilities(); +-int media2_get_profiles(); + int media2_get_video_source_modes(); + int media2_get_video_source_configurations(); + int media2_get_video_source_configuration_options(); +-int media2_get_video_encoder_configurations(); + int media2_get_video_encoder_configuration_options(); + int media2_get_audio_source_configurations(); + int media2_get_audio_source_configuration_options(); +@@ -32,8 +30,6 @@ int media2_get_audio_output_configuratio + int media2_get_audio_output_configuration_options(); + int media2_get_audio_decoder_configurations(); + int media2_get_audio_decoder_configuration_options(); +-int media2_get_snapshot_uri(); +-int media2_get_stream_uri(); + + int media2_set_video_source_configuration(); + int media2_set_audio_source_configuration(); +@@ -43,4 +39,4 @@ int media2_set_audio_output_configuratio + + int media2_unsupported(const char *method); + +-#endif //MEDIA2_SERVICE_H +\ No newline at end of file ++#endif //MEDIA2_SERVICE_H +--- /dev/null ++++ b/media_profiles.c +@@ -0,0 +1,264 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#include ++#include ++ ++#include "ezxml_wrapper.h" ++#include "media_profiles.h" ++#include "onvif_simple_server.h" ++#include "fault.h" ++#include "soap.h" ++#include "utils.h" ++ ++extern service_context_t service_ctx; ++ ++static int profile_find(const char *token, const char *suffix) ++{ ++ char name[MAX_LEN]; ++ int i; ++ ++ if (!token) ++ return -1; ++ for (i = 0; i < service_ctx.profiles_num; i++) { ++ snprintf(name, sizeof(name), "%s%s", service_ctx.profiles[i].name, suffix); ++ if (!strcmp(name, token)) ++ return i; ++ } ++ return -1; ++} ++ ++static void multicast_add(ezxml_t parent) ++{ ++ ezxml_t multicast; ++ ezxml_t address; ++ ++ multicast = soap_child_add(parent, "tt:Multicast", NULL); ++ address = soap_child_add(multicast, "tt:Address", NULL); ++ soap_child_add(address, "tt:Type", "IPv4"); ++ soap_child_add(address, "tt:IPv4Address", "0.0.0.0"); ++ soap_number_add(multicast, "tt:Port", 0); ++ soap_number_add(multicast, "tt:TTL", 0); ++ soap_child_add(multicast, "tt:AutoStart", "false"); ++} ++ ++static void source_configuration_add(ezxml_t node) ++{ ++ stream_profile_t *source; ++ char number[MAX_LEN]; ++ ezxml_t bounds; ++ int i; ++ ++ source = NULL; ++ for (i = 0; i < service_ctx.profiles_num; i++) ++ if (!source || (long long)service_ctx.profiles[i].width * service_ctx.profiles[i].height > ++ (long long)source->width * source->height) ++ source = &service_ctx.profiles[i]; ++ ezxml_set_attr(node, "token", "VideoSourceConfigToken"); ++ soap_child_add(node, "tt:Name", "VideoSourceConfig"); ++ soap_number_add(node, "tt:UseCount", service_ctx.profiles_num); ++ soap_child_add(node, "tt:SourceToken", "VideoSourceToken"); ++ bounds = soap_child_add(node, "tt:Bounds", NULL); ++ ezxml_set_attr(bounds, "x", "0"); ++ ezxml_set_attr(bounds, "y", "0"); ++ snprintf(number, sizeof(number), "%d", source ? source->width : 0); ++ ezxml_set_attr_d(bounds, "width", number); ++ snprintf(number, sizeof(number), "%d", source ? source->height : 0); ++ ezxml_set_attr_d(bounds, "height", number); ++} ++ ++static void encoder_configuration_add(ezxml_t node, int index, int version) ++{ ++ stream_profile_t *profile; ++ char name[MAX_LEN]; ++ char codec[MAX_LEN]; ++ ezxml_t resolution; ++ ezxml_t rate; ++ ezxml_t h264; ++ ++ profile = &service_ctx.profiles[index]; ++ snprintf(name, sizeof(name), "%s_VideoEncoderToken", profile->name); ++ ezxml_set_attr_d(node, "token", name); ++ soap_child_add(node, "tt:Name", profile->name); ++ soap_number_add(node, "tt:UseCount", 1); ++ set_video_codec(codec, sizeof(codec), profile->type, version); ++ soap_child_add(node, "tt:Encoding", codec); ++ resolution = soap_child_add(node, "tt:Resolution", NULL); ++ soap_number_add(resolution, "tt:Width", profile->width); ++ soap_number_add(resolution, "tt:Height", profile->height); ++ soap_number_add(node, "tt:Quality", 100); ++ rate = soap_child_add(node, "tt:RateControl", NULL); ++ soap_number_add(rate, "tt:FrameRateLimit", profile->framerate); ++ if (version == 1) ++ soap_number_add(rate, "tt:EncodingInterval", 1); ++ soap_number_add(rate, "tt:BitrateLimit", profile->bitrate); ++ if (version == 1) { ++ h264 = soap_child_add(node, "tt:H264", NULL); ++ soap_number_add(h264, "tt:GovLength", 40); ++ soap_child_add(h264, "tt:H264Profile", index ? "Main" : "High"); ++ } else { ++ ezxml_set_attr(node, "GovLength", "40"); ++ ezxml_set_attr(node, "Profile", index ? "Main" : "High"); ++ } ++ multicast_add(node); ++ if (version == 1) ++ soap_child_add(node, "tt:SessionTimeout", "PT0S"); ++} ++ ++static int type_requested(const char *name) ++{ ++ ezxml_t type; ++ ++ type = get_element_ptr(NULL, "Type", "Body"); ++ for (; type; type = type->next) ++ if (!strcmp(type->txt, "All") || !strcmp(type->txt, name)) ++ return 1; ++ return 0; ++} ++ ++static void profile_add(ezxml_t node, int index, int version) ++{ ++ stream_profile_t *profile; ++ ezxml_t configurations; ++ ezxml_t child; ++ char codec[MAX_LEN]; ++ char name[MAX_LEN]; ++ ++ profile = &service_ctx.profiles[index]; ++ ezxml_set_attr_d(node, "token", profile->name); ++ ezxml_set_attr(node, "fixed", "true"); ++ child = soap_member_add(node, version, "Name"); ++ ezxml_set_txt_d(child, profile->name); ++ configurations = version == 1 ? node : soap_member_add(node, version, "Configurations"); ++ if (version == 1 || type_requested("VideoSource")) { ++ child = soap_child_add(configurations, version == 1 ? ++ "tt:VideoSourceConfiguration" : "tr2:VideoSource", NULL); ++ 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 ? ++ "tt:AudioSourceConfiguration" : "tr2:AudioSource", NULL); ++ ezxml_set_attr(child, "token", "AudioSourceConfigToken"); ++ soap_child_add(child, "tt:Name", "AudioSourceConfig"); ++ soap_number_add(child, "tt:UseCount", service_ctx.profiles_num); ++ soap_child_add(child, "tt:SourceToken", "AudioSourceToken"); ++ } ++ if (profile->audio_encoder != AUDIO_NONE && ++ (version == 1 || type_requested("AudioEncoder"))) { ++ child = soap_child_add(configurations, version == 1 ? ++ "tt:AudioEncoderConfiguration" : "tr2:AudioEncoder", NULL); ++ snprintf(name, sizeof(name), "%s_AudioEncoderToken", profile->name); ++ ezxml_set_attr_d(child, "token", name); ++ soap_child_add(child, "tt:Name", profile->name); ++ soap_number_add(child, "tt:UseCount", 1); ++ set_audio_codec(codec, sizeof(codec), profile->audio_encoder, version); ++ soap_child_add(child, "tt:Encoding", codec); ++ 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 (service_ctx.ptz_node.enable && (version == 1 || type_requested("PTZ"))) { ++ child = soap_child_add(configurations, version == 1 ? ++ "tt:PTZConfiguration" : "tr2:PTZ", NULL); ++ ezxml_set_attr(child, "token", "PTZCfgToken"); ++ soap_child_add(child, "tt:Name", "PTZCfg"); ++ soap_number_add(child, "tt:UseCount", service_ctx.profiles_num); ++ soap_child_add(child, "tt:NodeToken", "PTZNodeToken"); ++ } ++} ++ ++static void uri_add(ezxml_t response, int index, int version, int snapshot) ++{ ++ stream_profile_t *profile; ++ char uri[MAX_LEN]; ++ const char *format; ++ ezxml_t member; ++ ++ profile = &service_ctx.profiles[index]; ++ format = snapshot ? profile->snapurl : profile->url; ++ if (!format) ++ return; ++ snprintf(uri, sizeof(uri), format, service_ctx.address_url); ++ if (version == 2 || snapshot) { ++ member = soap_member_add(response, version, snapshot ? "MediaUri" : "Uri"); ++ if (version == 2) { ++ ezxml_set_txt_d(member, uri); ++ return; ++ } ++ } else { ++ member = soap_member_add(response, version, "MediaUri"); ++ } ++ soap_child_add(member, "tt:Uri", uri); ++ soap_child_add(member, "tt:InvalidAfterConnect", "false"); ++ soap_child_add(member, "tt:InvalidAfterReboot", "false"); ++ soap_child_add(member, "tt:Timeout", "PT0S"); ++} ++ ++int media_profiles_dispatch(const char *operation, int version) ++{ ++ const char *profile_token; ++ const char *configuration_token; ++ const char *service; ++ ezxml_t response; ++ ezxml_t member; ++ int index; ++ int i; ++ int profiles; ++ int uri; ++ ++ profiles = !strcmp(operation, "GetProfiles") || !strcmp(operation, "GetProfile"); ++ uri = !strcmp(operation, "GetStreamUri") || !strcmp(operation, "GetSnapshotUri"); ++ if (!profiles && !uri && strcmp(operation, "GetVideoEncoderConfigurations") && ++ strcmp(operation, "GetVideoEncoderConfiguration") && ++ strcmp(operation, "GetCompatibleVideoEncoderConfigurations")) ++ return 0; ++ service = version == 1 ? "media_service" : "media2_service"; ++ profile_token = get_element("ProfileToken", "Body"); ++ if (version == 2 && profiles) ++ profile_token = get_element("Token", "Body"); ++ configuration_token = get_element("ConfigurationToken", "Body"); ++ index = profile_token ? profile_find(profile_token, "") : -1; ++ if (profile_token && index < 0) { ++ send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoProfile", ++ "No profile", "The requested profile does not exist"); ++ return 1; ++ } ++ if (configuration_token) ++ index = profile_find(configuration_token, "_VideoEncoderToken"); ++ if (configuration_token && index < 0) { ++ send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoConfig", ++ "No configuration", "The requested configuration does not exist"); ++ return 1; ++ } ++ if ((uri || !strcmp(operation, "GetProfile") || ++ !strcmp(operation, "GetVideoEncoderConfiguration")) && index < 0) { ++ send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoProfile", ++ "Missing token", "A valid token is required"); ++ return 1; ++ } ++ response = soap_response_create(version, operation); ++ if (uri) { ++ uri_add(response, index, version, !strcmp(operation, "GetSnapshotUri")); ++ soap_response_send(response); ++ return 1; ++ } ++ for (i = 0; i < service_ctx.profiles_num; i++) { ++ if (index >= 0 && index != i) ++ continue; ++ member = soap_member_add(response, version, profiles ? ++ (!strcmp(operation, "GetProfile") ? "Profile" : "Profiles") : ++ (!strcmp(operation, "GetVideoEncoderConfiguration") ? ++ "Configuration" : "Configurations")); ++ if (profiles) ++ profile_add(member, i, version); ++ else ++ encoder_configuration_add(member, i, version); ++ } ++ soap_response_send(response); ++ return 1; ++} +--- /dev/null ++++ b/media_profiles.h +@@ -0,0 +1,7 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#ifndef MEDIA_PROFILES_H ++#define MEDIA_PROFILES_H ++ ++int media_profiles_dispatch(const char *operation, int version); ++ ++#endif +--- a/media_service.c ++++ b/media_service.c +@@ -201,370 +201,7 @@ int media_get_video_source_configuration + } + } + +-int media_get_profiles() +-{ +- char profiles_num[2]; +- char stmp_vsc_w[16], stmp_vsc_h[16]; +- char stmp_w[16], stmp_h[16], stmp_br[16], stmp_fps[16]; +- char audio_enc_h[16], audio_enc_l[16]; +- char video_enc_h[16], video_enc_l[16]; +- long size; +- int c; +- char dest_a[] = "stdout"; +- char *dest; +- char min_x[256], max_x[256], min_y[256], max_y[256], min_z[256], max_z[256]; +- int vsrc = get_video_source_index(); +- +- audio_enc_h[0] = '\0'; +- audio_enc_l[0] = '\0'; +- snprintf(profiles_num, sizeof(profiles_num), "%d", service_ctx.profiles_num); +- snprintf(min_x, sizeof(min_x), "%.1f", service_ctx.ptz_node.min_step_x); +- snprintf(max_x, sizeof(max_x), "%.1f", service_ctx.ptz_node.max_step_x); +- snprintf(min_y, sizeof(min_y), "%.1f", service_ctx.ptz_node.min_step_y); +- snprintf(max_y, sizeof(max_y), "%.1f", service_ctx.ptz_node.max_step_y); +- snprintf(min_z, sizeof(min_z), "%.1f", service_ctx.ptz_node.min_step_z); +- snprintf(max_z, sizeof(max_z), "%.1f", service_ctx.ptz_node.max_step_z); +- +- if (service_ctx.profiles_num == 1) { +- +- // We need 1st step to evaluate content length +- for (c = 0; c < 2; c++) { +- if (c == 0) { +- dest = NULL; +- } else { +- dest = dest_a; +- output_http_headers(size); +- } +- +- size = cat(dest, "media_service_files/GetProfiles_header.xml", 2, +- "%PROFILE0%", service_ctx.profiles[0].name); +- +- // Get the video source configuration from the 1st profile +- snprintf(stmp_vsc_w, sizeof(stmp_vsc_w), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_vsc_h, sizeof(stmp_vsc_h), "%d", service_ctx.profiles[vsrc].height); +- size += cat(dest, "media_service_files/GetProfile_VSC.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%VSC_WIDTH%", stmp_vsc_w, +- "%VSC_HEIGHT%", stmp_vsc_h); +- +- if (service_ctx.profiles[0].audio_encoder != AUDIO_NONE) { +- size += cat(dest, "media_service_files/GetProfile_ASC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_br, sizeof(stmp_br), "%d", service_ctx.profiles[0].bitrate > 0 ? service_ctx.profiles[0].bitrate : 5000); +- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- set_video_codec(video_enc_h, 16, service_ctx.profiles[0].type, 1); +- size += cat(dest, "media_service_files/GetProfile_VEC.xml", 14, +- "%PROFILE%", service_ctx.profiles[0].name, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%H264PROFILE%", "High", +- "%BITRATE%", stmp_br, +- "%FRAMERATE%", stmp_fps, +- "%ENCODING%", video_enc_h); +- +- if (service_ctx.profiles[0].audio_encoder != AUDIO_NONE) { +- set_audio_codec(audio_enc_h, 16, service_ctx.profiles[0].audio_encoder, 1); +- size += cat(dest, "media_service_files/GetProfile_AEC.xml", 4, +- "%PROFILE%", service_ctx.profiles[0].name, +- "%AUDIO_ENCODING%", audio_enc_h); +- } +- +- if (service_ctx.ptz_node.enable == 1) { +- size += cat(dest, ptz_supports_zoom() ? "media_service_files/GetProfile_PTZ.xml" : "media_service_files/GetProfile_PTZ_nozoom.xml", 12, +- "%MIN_X%", min_x, +- "%MAX_X%", max_x, +- "%MIN_Y%", min_y, +- "%MAX_Y%", max_y, +- "%MIN_Z%", min_z, +- "%MAX_Z%", max_z); +- } +- +- size += cat(dest, "media_service_files/GetProfiles_footer.xml", 0); +- } +- +- } else if (service_ctx.profiles_num == 2) { +- +- // We need 1st step to evaluate content length +- for (c = 0; c < 2; c++) { +- if (c == 0) { +- dest = NULL; +- } else { +- dest = dest_a; +- output_http_headers(size); +- } +- +- size = cat(dest, "media_service_files/GetProfiles_header.xml", 2, +- "%PROFILE0%", service_ctx.profiles[0].name); +- +- // Get the video source configuration from the 1st profile +- snprintf(stmp_vsc_w, sizeof(stmp_vsc_w), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_vsc_h, sizeof(stmp_vsc_h), "%d", service_ctx.profiles[vsrc].height); +- size += cat(dest, "media_service_files/GetProfile_VSC.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%VSC_WIDTH%", stmp_vsc_w, +- "%VSC_HEIGHT%", stmp_vsc_h); +- +- if (service_ctx.profiles[0].audio_encoder != AUDIO_NONE) { +- size += cat(dest, "media_service_files/GetProfile_ASC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_br, sizeof(stmp_br), "%d", service_ctx.profiles[0].bitrate > 0 ? service_ctx.profiles[0].bitrate : 5000); +- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- set_video_codec(video_enc_h, 16, service_ctx.profiles[0].type, 1); +- size += cat(dest, "media_service_files/GetProfile_VEC.xml", 14, +- "%PROFILE%", service_ctx.profiles[0].name, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%H264PROFILE%", "High", +- "%BITRATE%", stmp_br, +- "%FRAMERATE%", stmp_fps, +- "%ENCODING%", video_enc_h); +- +- if (service_ctx.profiles[0].audio_encoder != AUDIO_NONE) { +- +- set_audio_codec(audio_enc_h, 16, service_ctx.profiles[0].audio_encoder, 1); +- size += cat(dest, "media_service_files/GetProfile_AEC.xml", 4, +- "%PROFILE%", service_ctx.profiles[0].name, +- "%AUDIO_ENCODING%", audio_enc_h); +- } +- +- if (service_ctx.ptz_node.enable == 1) { +- size += cat(dest, ptz_supports_zoom() ? "media_service_files/GetProfile_PTZ.xml" : "media_service_files/GetProfile_PTZ_nozoom.xml", 12, +- "%MIN_X%", min_x, +- "%MAX_X%", max_x, +- "%MIN_Y%", min_y, +- "%MAX_Y%", max_y, +- "%MIN_Z%", min_z, +- "%MAX_Z%", max_z); +- } +- +- size += cat(dest, "media_service_files/GetProfiles_middle.xml", 2, +- "%PROFILE1%", service_ctx.profiles[1].name); +- +- // Get the video source configuration from the 1st profile +- snprintf(stmp_vsc_w, sizeof(stmp_vsc_w), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_vsc_h, sizeof(stmp_vsc_h), "%d", service_ctx.profiles[vsrc].height); +- size += cat(dest, "media_service_files/GetProfile_VSC.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%VSC_WIDTH%", stmp_vsc_w, +- "%VSC_HEIGHT%", stmp_vsc_h); +- +- if (service_ctx.profiles[1].audio_encoder != AUDIO_NONE) { +- size += cat(dest, "media_service_files/GetProfile_ASC.xml", 4, +- "%USE_COUNT%", "2", +- "%PROFILES_NUM%", profiles_num); +- } +- +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[1].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[1].height); +- snprintf(stmp_br, sizeof(stmp_br), "%d", service_ctx.profiles[1].bitrate > 0 ? service_ctx.profiles[1].bitrate : 5000); +- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[1].framerate > 0 ? service_ctx.profiles[1].framerate : 30); +- set_video_codec(video_enc_l, 16, service_ctx.profiles[1].type, 1); +- size += cat(dest, "media_service_files/GetProfile_VEC.xml", 14, +- "%PROFILE%", service_ctx.profiles[1].name, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%H264PROFILE%", "Main", +- "%BITRATE%", stmp_br, +- "%FRAMERATE%", stmp_fps, +- "%ENCODING%", video_enc_l); +- +- if (service_ctx.profiles[1].audio_encoder != AUDIO_NONE) { +- +- set_audio_codec(audio_enc_l, 16, service_ctx.profiles[1].audio_encoder, 1); +- size += cat(dest, "media_service_files/GetProfile_AEC.xml", 4, +- "%PROFILE%", service_ctx.profiles[1].name, +- "%AUDIO_ENCODING%", audio_enc_l); +- } +- +- if (service_ctx.ptz_node.enable == 1) { +- size += cat(dest, ptz_supports_zoom() ? "media_service_files/GetProfile_PTZ.xml" : "media_service_files/GetProfile_PTZ_nozoom.xml", 12, +- "%MIN_X%", min_x, +- "%MAX_X%", max_x, +- "%MIN_Y%", min_y, +- "%MAX_Y%", max_y, +- "%MIN_Z%", min_z, +- "%MAX_Z%", max_z); +- } +- +- size += cat(dest, "media_service_files/GetProfiles_footer.xml", 0); +- } +- +- } else { +- long size = cat(NULL, "media_service_files/GetProfiles_none.xml", 0); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetProfiles_none.xml", 0); +- } +-} +- +-int media_get_profile() +-{ +- char profiles_num[2]; +- char stmp_vsc_w[16], stmp_vsc_h[16]; +- char stmp_w[16], stmp_h[16], stmp_br[16], stmp_fps[16]; +- const char *profile_token = get_element("ProfileToken", "Body"); +- char audio_enc_h[16], audio_enc_l[16]; +- char video_enc_h[16], video_enc_l[16]; +- long size; +- int c; +- char dest_a[] = "stdout"; +- char *dest; +- char min_x[256], max_x[256], min_y[256], max_y[256], min_z[256], max_z[256]; +- int vsrc = get_video_source_index(); +- +- if (profile_token == NULL) { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile token does not exist"); +- return -1; +- } +- +- snprintf(profiles_num, sizeof(profiles_num), "%d", service_ctx.profiles_num); +- snprintf(min_x, sizeof(min_x), "%.1f", service_ctx.ptz_node.min_step_x); +- snprintf(max_x, sizeof(max_x), "%.1f", service_ctx.ptz_node.max_step_x); +- snprintf(min_y, sizeof(min_y), "%.1f", service_ctx.ptz_node.min_step_y); +- snprintf(max_y, sizeof(max_y), "%.1f", service_ctx.ptz_node.max_step_y); +- snprintf(min_z, sizeof(min_z), "%.1f", service_ctx.ptz_node.min_step_z); +- snprintf(max_z, sizeof(max_z), "%.1f", service_ctx.ptz_node.max_step_z); +- +- if ((service_ctx.profiles_num > 0) && +- (strcasecmp(service_ctx.profiles[0].name, profile_token) == 0)) { +- +- // We need 1st step to evaluate content length +- for (c = 0; c < 2; c++) { +- if (c == 0) { +- dest = NULL; +- } else { +- dest = dest_a; +- output_http_headers(size); +- } +- +- size = cat(dest, "media_service_files/GetProfile_header.xml", 2, +- "%PROFILE%", profile_token); +- +- // Get the video source configuration from the 1st profile +- snprintf(stmp_vsc_w, sizeof(stmp_vsc_w), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_vsc_h, sizeof(stmp_vsc_h), "%d", service_ctx.profiles[vsrc].height); +- size += cat(dest, "media_service_files/GetProfile_VSC.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%VSC_WIDTH%", stmp_vsc_w, +- "%VSC_HEIGHT%", stmp_vsc_h); +- +- if (service_ctx.profiles[0].audio_encoder != AUDIO_NONE) { +- size += cat(dest, "media_service_files/GetProfile_ASC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_br, sizeof(stmp_br), "%d", service_ctx.profiles[0].bitrate > 0 ? service_ctx.profiles[0].bitrate : 5000); +- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- set_video_codec(video_enc_h, 16, service_ctx.profiles[0].type, 1); +- size += cat(dest, "media_service_files/GetProfile_VEC.xml", 14, +- "%PROFILE%", profile_token, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%H264PROFILE%", "High", +- "%BITRATE%", stmp_br, +- "%FRAMERATE%", stmp_fps, +- "%ENCODING%", video_enc_h); +- +- if (service_ctx.profiles[0].audio_encoder != AUDIO_NONE) { +- +- set_audio_codec(audio_enc_h, 16, service_ctx.profiles[0].audio_encoder, 1); +- size += cat(dest, "media_service_files/GetProfile_AEC.xml", 4, +- "%PROFILE%", service_ctx.profiles[0].name, +- "%AUDIO_ENCODING%", audio_enc_h); +- } +- +- if (service_ctx.ptz_node.enable == 1) { +- size += cat(dest, ptz_supports_zoom() ? "media_service_files/GetProfile_PTZ.xml" : "media_service_files/GetProfile_PTZ_nozoom.xml", 12, +- "%MIN_X%", min_x, +- "%MAX_X%", max_x, +- "%MIN_Y%", min_y, +- "%MAX_Y%", max_y, +- "%MIN_Z%", min_z, +- "%MAX_Z%", max_z); +- } +- +- size += cat(dest, "media_service_files/GetProfile_footer.xml", 0); +- } +- +- } else if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, profile_token) == 0)) { +- +- // We need 1st step to evaluate content length +- for (c = 0; c < 2; c++) { +- if (c == 0) { +- dest = NULL; +- } else { +- dest = dest_a; +- output_http_headers(size); +- } +- +- size = cat(dest, "media_service_files/GetProfile_header.xml", 2, +- "%PROFILE%", profile_token); +- +- // Get the video source configuration from the 1st profile +- snprintf(stmp_vsc_w, sizeof(stmp_vsc_w), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_vsc_h, sizeof(stmp_vsc_h), "%d", service_ctx.profiles[vsrc].height); +- size += cat(dest, "media_service_files/GetProfile_VSC.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%VSC_WIDTH%", stmp_vsc_w, +- "%VSC_HEIGHT%", stmp_vsc_h); +- +- if (service_ctx.profiles[1].audio_encoder != AUDIO_NONE) { +- size += cat(dest, "media_service_files/GetProfile_ASC.xml", 2, +- "%PROFILES_NUM%", profiles_num); +- } +- +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[1].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[1].height); +- snprintf(stmp_br, sizeof(stmp_br), "%d", service_ctx.profiles[1].bitrate > 0 ? service_ctx.profiles[1].bitrate : 5000); +- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[1].framerate > 0 ? service_ctx.profiles[1].framerate : 30); +- set_video_codec(video_enc_l, 16, service_ctx.profiles[1].type, 1); +- size += cat(dest, "media_service_files/GetProfile_VEC.xml", 14, +- "%PROFILE%", profile_token, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%H264PROFILE%", "Main", +- "%BITRATE%", stmp_br, +- "%FRAMERATE%", stmp_fps, +- "%ENCODING%", video_enc_l); +- +- if (service_ctx.profiles[1].audio_encoder != AUDIO_NONE) { +- +- set_audio_codec(audio_enc_h, 16, service_ctx.profiles[1].audio_encoder, 1); +- size += cat(dest, "media_service_files/GetProfile_AEC.xml", 4, +- "%PROFILE%", service_ctx.profiles[1].name, +- "%AUDIO_ENCODING%", audio_enc_h); +- } +- +- if (service_ctx.ptz_node.enable == 1) { +- size += cat(dest, ptz_supports_zoom() ? "media_service_files/GetProfile_PTZ.xml" : "media_service_files/GetProfile_PTZ_nozoom.xml", 12, +- "%MIN_X%", min_x, +- "%MAX_X%", max_x, +- "%MIN_Y%", min_y, +- "%MAX_Y%", max_y, +- "%MIN_Z%", min_z, +- "%MAX_Z%", max_z); +- } +- +- size += cat(dest, "media_service_files/GetProfile_footer.xml", 0); +- } + +- } else { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile token does not exist"); +- return -2; +- } +-} + + int media_create_profile() + { +@@ -577,228 +214,8 @@ int media_create_profile() + return -1; + } + +-int media_get_video_encoder_configurations() +-{ +- char stmp_w_l[16], stmp_h_l[16]; +- char stmp_w_h[16], stmp_h_h[16]; +- char stmp_br_h[16], stmp_br_l[16]; +- char stmp_fps_h[16], stmp_fps_l[16]; +- +- if (service_ctx.profiles_num == 1) { +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_br_h, sizeof(stmp_br_h), "%d", service_ctx.profiles[0].bitrate > 0 ? service_ctx.profiles[0].bitrate : 5000); +- snprintf(stmp_fps_h, sizeof(stmp_fps_h), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- char enc_h[16]; +- set_video_codec(enc_h, 16, service_ctx.profiles[0].type, 1); +- char *tmpl = "media_service_files/GetVideoEncoderConfigurations_high.xml"; +- long size = cat(NULL, tmpl, 12, +- "%PROFILE0%", service_ctx.profiles[0].name, +- "%WIDTH_HIGH%", stmp_w_h, +- "%HEIGHT_HIGH%", stmp_h_h, +- "%BITRATE%", stmp_br_h, +- "%FRAMERATE%", stmp_fps_h, +- "%ENCODING%", enc_h); + +- output_http_headers(size); +- +- return cat("stdout", tmpl, 12, +- "%PROFILE0%", service_ctx.profiles[0].name, +- "%WIDTH_HIGH%", stmp_w_h, +- "%HEIGHT_HIGH%", stmp_h_h, +- "%BITRATE%", stmp_br_h, +- "%FRAMERATE%", stmp_fps_h, +- "%ENCODING%", enc_h); +- +- } else if (service_ctx.profiles_num == 2) { +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_w_l, sizeof(stmp_w_l), "%d", service_ctx.profiles[1].width); +- snprintf(stmp_h_l, sizeof(stmp_h_l), "%d", service_ctx.profiles[1].height); +- snprintf(stmp_br_h, sizeof(stmp_br_h), "%d", service_ctx.profiles[0].bitrate > 0 ? service_ctx.profiles[0].bitrate : 5000); +- snprintf(stmp_br_l, sizeof(stmp_br_l), "%d", service_ctx.profiles[1].bitrate > 0 ? service_ctx.profiles[1].bitrate : 5000); +- snprintf(stmp_fps_h, sizeof(stmp_fps_h), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- snprintf(stmp_fps_l, sizeof(stmp_fps_l), "%d", service_ctx.profiles[1].framerate > 0 ? service_ctx.profiles[1].framerate : 30); +- char enc_h[16]; +- char enc_l[16]; +- set_video_codec(enc_h, 16, service_ctx.profiles[0].type, 1); +- set_video_codec(enc_l, 16, service_ctx.profiles[1].type, 1); +- char *tmpl = "media_service_files/GetVideoEncoderConfigurations_both.xml"; +- long size = cat(NULL, tmpl, 24, +- "%PROFILE0%", service_ctx.profiles[0].name, +- "%PROFILE1%", service_ctx.profiles[1].name, +- "%WIDTH_HIGH%", stmp_w_h, +- "%HEIGHT_HIGH%", stmp_h_h, +- "%WIDTH_LOW%", stmp_w_l, +- "%HEIGHT_LOW%", stmp_h_l, +- "%BITRATE_HIGH%", stmp_br_h, +- "%BITRATE_LOW%", stmp_br_l, +- "%FRAMERATE_HIGH%", stmp_fps_h, +- "%FRAMERATE_LOW%", stmp_fps_l, +- "%ENCODING_HIGH%", enc_h, +- "%ENCODING_LOW%", enc_l); + +- output_http_headers(size); +- +- return cat("stdout", tmpl, 24, +- "%PROFILE0%", service_ctx.profiles[0].name, +- "%PROFILE1%", service_ctx.profiles[1].name, +- "%WIDTH_HIGH%", stmp_w_h, +- "%HEIGHT_HIGH%", stmp_h_h, +- "%WIDTH_LOW%", stmp_w_l, +- "%HEIGHT_LOW%", stmp_h_l, +- "%BITRATE_HIGH%", stmp_br_h, +- "%BITRATE_LOW%", stmp_br_l, +- "%FRAMERATE_HIGH%", stmp_fps_h, +- "%FRAMERATE_LOW%", stmp_fps_l, +- "%ENCODING_HIGH%", enc_h, +- "%ENCODING_LOW%", enc_l); +- } +-} +- +-int media_get_video_encoder_configuration() +-{ +- char stmp_w_l[16], stmp_h_l[16]; +- char stmp_w_h[16], stmp_h_h[16]; +- char stmp_br[16]; +- char stmp_fps[16]; +- char vec_token[128]; +- const char *configuration_token = get_element("ConfigurationToken", "Body"); +- +- if (configuration_token == NULL) { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoConfig", "No config", "The requested configuration indicated does not exist"); +- return -1; +- } +- +- snprintf(vec_token, sizeof(vec_token), "%s_VideoEncoderToken", service_ctx.profiles[0].name); +- if (strcasecmp(configuration_token, vec_token) == 0) { +- +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_br, sizeof(stmp_br), "%d", service_ctx.profiles[0].bitrate > 0 ? service_ctx.profiles[0].bitrate : 5000); +- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- char enc0[16]; +- set_video_codec(enc0, 16, service_ctx.profiles[0].type, 1); +- char *tmpl = "media_service_files/GetVideoEncoderConfiguration.xml"; +- long size = cat(NULL, tmpl, 14, +- "%PROFILE%", service_ctx.profiles[0].name, +- "%WIDTH%", stmp_w_h, +- "%HEIGHT%", stmp_h_h, +- "%PROFILE_TYPE%", "High", +- "%BITRATE%", stmp_br, +- "%FRAMERATE%", stmp_fps, +- "%ENCODING%", enc0); +- +- output_http_headers(size); +- +- return cat("stdout", tmpl, 14, +- "%PROFILE%", service_ctx.profiles[0].name, +- "%WIDTH%", stmp_w_h, +- "%HEIGHT%", stmp_h_h, +- "%PROFILE_TYPE%", "High", +- "%BITRATE%", stmp_br, +- "%FRAMERATE%", stmp_fps, +- "%ENCODING%", enc0); +- +- } +- if (service_ctx.profiles_num == 2) { +- snprintf(vec_token, sizeof(vec_token), "%s_VideoEncoderToken", service_ctx.profiles[1].name); +- if (strcasecmp(configuration_token, vec_token) == 0) { +- +- snprintf(stmp_w_l, sizeof(stmp_w_l), "%d", service_ctx.profiles[1].width); +- snprintf(stmp_h_l, sizeof(stmp_h_l), "%d", service_ctx.profiles[1].height); +- snprintf(stmp_br, sizeof(stmp_br), "%d", service_ctx.profiles[1].bitrate > 0 ? service_ctx.profiles[1].bitrate : 5000); +- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[1].framerate > 0 ? service_ctx.profiles[1].framerate : 30); +- char enc1[16]; +- set_video_codec(enc1, 16, service_ctx.profiles[1].type, 1); +- char *tmpl = "media_service_files/GetVideoEncoderConfiguration.xml"; +- long size = cat(NULL, tmpl, 14, +- "%PROFILE%", service_ctx.profiles[1].name, +- "%WIDTH%", stmp_w_l, +- "%HEIGHT%", stmp_h_l, +- "%PROFILE_TYPE%", "Main", +- "%BITRATE%", stmp_br, +- "%FRAMERATE%", stmp_fps, +- "%ENCODING%", enc1); +- +- output_http_headers(size); +- +- return cat("stdout", tmpl, 14, +- "%PROFILE%", service_ctx.profiles[1].name, +- "%WIDTH%", stmp_w_l, +- "%HEIGHT%", stmp_h_l, +- "%PROFILE_TYPE%", "Main", +- "%BITRATE%", stmp_br, +- "%FRAMERATE%", stmp_fps, +- "%ENCODING%", enc1); +- } +- } +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoConfig", "No config", "The requested configuration indicated does not exist"); +- return -2; +-} +- +-int media_get_compatible_video_encoder_configurations() +-{ +- char stmp_w_l[16], stmp_h_l[16]; +- char stmp_w_h[16], stmp_h_h[16]; +- const char *profile_token = get_element("ProfileToken", "Body"); +- +- if (profile_token == NULL) { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -1; +- } +- +- if (strcasecmp(service_ctx.profiles[0].name, profile_token) == 0) { +- +- snprintf(stmp_w_h, sizeof(stmp_w_h), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h_h, sizeof(stmp_h_h), "%d", service_ctx.profiles[0].height); +- char cenc0[16]; +- set_video_codec(cenc0, 16, service_ctx.profiles[0].type, 1); +- char *tmpl = "media_service_files/GetCompatibleVideoEncoderConfigurations.xml"; +- long size = cat(NULL, tmpl, 10, +- "%PROFILE%", profile_token, +- "%WIDTH%", stmp_w_h, +- "%HEIGHT%", stmp_h_h, +- "%PROFILE_TYPE%", "High", +- "%ENCODING%", cenc0); +- +- output_http_headers(size); +- +- return cat("stdout", tmpl, 10, +- "%PROFILE%", profile_token, +- "%WIDTH%", stmp_w_h, +- "%HEIGHT%", stmp_h_h, +- "%PROFILE_TYPE%", "High", +- "%ENCODING%", cenc0); +- +- } else if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, profile_token) == 0)) { +- +- snprintf(stmp_w_l, sizeof(stmp_w_l), "%d", service_ctx.profiles[1].width); +- snprintf(stmp_h_l, sizeof(stmp_h_l), "%d", service_ctx.profiles[1].height); +- char cenc1[16]; +- set_video_codec(cenc1, 16, service_ctx.profiles[1].type, 1); +- char *tmpl = "media_service_files/GetCompatibleVideoEncoderConfigurations.xml"; +- long size = cat(NULL, tmpl, 10, +- "%PROFILE%", profile_token, +- "%WIDTH%", stmp_w_l, +- "%HEIGHT%", stmp_h_l, +- "%PROFILE_TYPE%", "Main", +- "%ENCODING%", cenc1); +- +- output_http_headers(size); +- +- return cat("stdout", tmpl, 10, +- "%PROFILE%", profile_token, +- "%WIDTH%", stmp_w_l, +- "%HEIGHT%", stmp_h_l, +- "%PROFILE_TYPE%", "Main", +- "%ENCODING%", cenc1); +- } else { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -2; +- } +-} + + int media_get_video_encoder_configuration_options() + { +@@ -898,129 +315,7 @@ int media_get_guaranteed_number_of_video + } + } + +-int media_get_snapshot_uri() +-{ +- char *s; +- char line[MAX_LEN]; +- const char *profile_token = get_element("ProfileToken", "Body"); +- +- memset(line, '\0', sizeof(line)); +- +- if (profile_token == NULL) { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -1; +- } +- +- if (strcasecmp(service_ctx.profiles[0].name, profile_token) == 0) { +- +- if (service_ctx.profiles[0].snapurl == NULL) { +- send_fault("media_service", "Receiver", "ter:Action", "ter:IncompleteConfiguration", "Incomplete configuration", "The specified media profile does not contain either a reference to a video encoder configuration or a reference to a video source configuration"); +- return -2; +- } +- +- if (snprintf(line, sizeof(line), service_ctx.profiles[0].snapurl, service_ctx.address_url) < 0) { +- snprintf(line, sizeof(line), "%s", service_ctx.profiles[0].snapurl); +- } +- // Escape html chars +- html_escape(line, MAX_LEN); +- +- long size = cat(NULL, "media_service_files/GetSnapshotUri.xml", 2, +- "%URI%", line); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetSnapshotUri.xml", 2, +- "%URI%", line); +- +- } else if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, profile_token) == 0)) { +- +- if (service_ctx.profiles[1].snapurl == NULL) { +- send_fault("media_service", "Receiver", "ter:Action", "ter:IncompleteConfiguration", "Incomplete configuration", "The specified media profile does not contain either a reference to a video encoder configuration or a reference to a video source configuration"); +- return -3; +- } +- +- if (snprintf(line, sizeof(line), service_ctx.profiles[1].snapurl, service_ctx.address_url) < 0) { +- snprintf(line, sizeof(line), "%s", service_ctx.profiles[1].snapurl); +- } +- // Escape html chars +- html_escape(line, MAX_LEN); +- +- long size = cat(NULL, "media_service_files/GetSnapshotUri.xml", 2, +- "%URI%", line); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetSnapshotUri.xml", 2, +- "%URI%", line); +- +- } else { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -4; +- } +-} +- +-int media_get_stream_uri() +-{ +- char *s; +- char line[MAX_LEN]; +- const char *profile_token = get_element("ProfileToken", "Body"); +- +- memset(line, '\0', sizeof(line)); +- +- if (profile_token == NULL) { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -1; +- } +- +- if (strcasecmp(service_ctx.profiles[0].name, profile_token) == 0) { +- +- if (service_ctx.profiles[0].url == NULL) { +- send_fault("media_service", "Receiver", "ter:Action", "ter:IncompleteConfiguration", "Incomplete configuration", "The specified media profile does contain either unused sources or encoder configurations without a corresponding source"); +- return -2; +- } +- +- if (snprintf(line, sizeof(line), service_ctx.profiles[0].url, service_ctx.address_url) < 0) { +- snprintf(line, sizeof(line), "%s", service_ctx.profiles[0].url); +- } +- // Escape html chars +- html_escape(line, MAX_LEN); + +- long size = cat(NULL, "media_service_files/GetStreamUri.xml", 2, +- "%URI%", line); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetStreamUri.xml", 2, +- "%URI%", line); +- +- } else if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, profile_token) == 0)) { +- +- if (service_ctx.profiles[1].url == NULL) { +- send_fault("media_service", "Receiver", "ter:Action", "ter:IncompleteConfiguration", "Incomplete configuration", "The specified media profile does contain either unused sources or encoder configurations without a corresponding source"); +- return -3; +- } +- +- if (snprintf(line, sizeof(line), service_ctx.profiles[1].url, service_ctx.address_url) < 0) { +- snprintf(line, sizeof(line), "%s", service_ctx.profiles[1].url); +- } +- // Escape html chars +- html_escape(line, MAX_LEN); +- +- long size = cat(NULL, "media_service_files/GetStreamUri.xml", 2, +- "%URI%", line); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetStreamUri.xml", 2, +- "%URI%", line); +- +- } else { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -4; +- } +-} + + int media_get_audio_sources() + { +--- a/media_service.h ++++ b/media_service.h +@@ -23,16 +23,9 @@ int media_get_video_source_configuration + int media_get_video_source_configuration(); + int media_get_compatible_video_source_configurations(); + int media_get_video_source_configuration_options(); +-int media_get_profiles(); +-int media_get_profile(); + int media_create_profile(); +-int media_get_video_encoder_configurations(); +-int media_get_video_encoder_configuration(); +-int media_get_compatible_video_encoder_configurations(); + int media_get_guaranteed_number_of_video_encoder_instances(); + int media_get_video_encoder_configuration_options(); +-int media_get_snapshot_uri(); +-int media_get_stream_uri(); + int media_get_audio_sources(); + int media_get_audio_source_configurations(); + int media_get_audio_source_configuration(); +@@ -60,4 +53,4 @@ int media_set_audio_output_configuration + + int media_unsupported(const char *method); + +-#endif //MEDIA_SERVICE_H +\ No newline at end of file ++#endif //MEDIA_SERVICE_H +--- 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 "media_profiles.h" + #include "media2_service.h" + #include "ptz_service.h" + #include "events_service.h" +@@ -526,25 +527,25 @@ int main(int argc, char ** argv) + } else if (strcasecmp(method, "GetVideoSourceConfigurationOptions") == 0) { + media_get_video_source_configuration_options(); + } else if (strcasecmp(method, "GetProfiles") == 0) { +- media_get_profiles(); ++ media_profiles_dispatch("GetProfiles", 1); + } else if (strcasecmp(method, "GetProfile") == 0) { +- media_get_profile(); ++ media_profiles_dispatch("GetProfile", 1); + } else if (strcasecmp(method, "CreateProfile") == 0) { + media_create_profile(); + } else if (strcasecmp(method, "GetVideoEncoderConfigurations") == 0) { +- media_get_video_encoder_configurations(); ++ media_profiles_dispatch("GetVideoEncoderConfigurations", 1); + } else if (strcasecmp(method, "GetVideoEncoderConfiguration") == 0) { +- media_get_video_encoder_configuration(); ++ media_profiles_dispatch("GetVideoEncoderConfiguration", 1); + } else if (strcasecmp(method, "GetCompatibleVideoEncoderConfigurations") == 0) { +- media_get_compatible_video_encoder_configurations(); ++ media_profiles_dispatch("GetCompatibleVideoEncoderConfigurations", 1); + } else if (strcasecmp(method, "GetVideoEncoderConfigurationOptions") == 0) { + media_get_video_encoder_configuration_options(); + } else if (strcasecmp(method, "GetGuaranteedNumberOfVideoEncoderInstances") == 0) { + media_get_guaranteed_number_of_video_encoder_instances(); + } else if (strcasecmp(method, "GetSnapshotUri") == 0) { +- media_get_snapshot_uri(); ++ media_profiles_dispatch("GetSnapshotUri", 1); + } else if (strcasecmp(method, "GetStreamUri") == 0) { +- media_get_stream_uri(); ++ media_profiles_dispatch("GetStreamUri", 1); + } else if (strcasecmp(method, "GetAudioSources") == 0) { + media_get_audio_sources(); + } else if (strcasecmp(method, "GetAudioSourceConfigurations") == 0) { +@@ -602,7 +603,7 @@ int main(int argc, char ** argv) + if (strcasecmp(method, "GetServiceCapabilities") == 0) { + media2_get_service_capabilities(); + } else if (strcasecmp(method, "GetProfiles") == 0) { +- media2_get_profiles(); ++ media_profiles_dispatch("GetProfiles", 2); + } else if (strcasecmp(method, "GetVideoSourceModes") == 0) { + media2_get_video_source_modes(); + } else if (strcasecmp(method, "GetVideoSourceConfigurations") == 0) { +@@ -610,7 +611,7 @@ int main(int argc, char ** argv) + } else if (strcasecmp(method, "GetVideoSourceConfigurationOptions") == 0) { + media2_get_video_source_configuration_options(); + } else if (strcasecmp(method, "GetVideoEncoderConfigurations") == 0) { +- media2_get_video_encoder_configurations(); ++ media_profiles_dispatch("GetVideoEncoderConfigurations", 2); + } else if (strcasecmp(method, "GetVideoEncoderConfigurationOptions") == 0) { + media2_get_video_encoder_configuration_options(); + } else if (strcasecmp(method, "GetAudioSourceConfigurations") == 0) { +@@ -630,9 +631,9 @@ int main(int argc, char ** argv) + } else if (strcasecmp(method, "GetAudioDecoderConfigurationOptions") == 0) { + media2_get_audio_decoder_configuration_options(); + } else if (strcasecmp(method, "GetSnapshotUri") == 0) { +- media2_get_snapshot_uri(); ++ media_profiles_dispatch("GetSnapshotUri", 2); + } else if (strcasecmp(method, "GetStreamUri") == 0) { +- media2_get_stream_uri(); ++ media_profiles_dispatch("GetStreamUri", 2); + } else { + if (service_ctx.adv_empty_if_unknown == 1) { + send_empty_response("tr2", method); +--- /dev/null ++++ b/soap.c +@@ -0,0 +1,67 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#include ++#include ++ ++#include "soap.h" ++#include "utils.h" ++ ++ezxml_t soap_child_add(ezxml_t parent, const char *name, const char *text) ++{ ++ ezxml_t child; ++ ++ child = ezxml_add_child_d(parent, name, 0); ++ if (text) ++ ezxml_set_txt_d(child, text); ++ return child; ++} ++ ++ezxml_t soap_number_add(ezxml_t parent, const char *name, double value) ++{ ++ char number[MAX_LEN]; ++ ++ snprintf(number, sizeof(number), "%.9g", value); ++ return soap_child_add(parent, name, number); ++} ++ ++ezxml_t soap_member_add(ezxml_t parent, int version, const char *name) ++{ ++ char qualified[MAX_LEN]; ++ ++ snprintf(qualified, sizeof(qualified), "%s:%s", ++ version == 1 ? "trt" : "tr2", name); ++ return soap_child_add(parent, qualified, NULL); ++} ++ ++ezxml_t soap_response_create(int version, const char *operation) ++{ ++ char name[MAX_LEN]; ++ ezxml_t envelope; ++ ezxml_t body; ++ ++ envelope = ezxml_new("s:Envelope"); ++ ezxml_set_attr(envelope, "xmlns:s", "http://www.w3.org/2003/05/soap-envelope"); ++ ezxml_set_attr(envelope, "xmlns:tt", "http://www.onvif.org/ver10/schema"); ++ ezxml_set_attr(envelope, "xmlns:trt", "http://www.onvif.org/ver10/media/wsdl"); ++ ezxml_set_attr(envelope, "xmlns:tr2", "http://www.onvif.org/ver20/media/wsdl"); ++ ezxml_set_attr(envelope, "xmlns:timg", "http://www.onvif.org/ver20/imaging/wsdl"); ++ body = soap_child_add(envelope, "s:Body", NULL); ++ snprintf(name, sizeof(name), "%sResponse", operation); ++ return soap_member_add(body, version, name); ++} ++ ++int soap_response_send(ezxml_t response) ++{ ++ ezxml_t envelope; ++ char *xml; ++ int result; ++ ++ envelope = response; ++ while (envelope->parent) ++ envelope = envelope->parent; ++ xml = ezxml_toxml(envelope); ++ output_http_headers(strlen(xml)); ++ result = fputs(xml, stdout); ++ free(xml); ++ ezxml_free(envelope); ++ return result; ++} +--- /dev/null ++++ b/soap.h +@@ -0,0 +1,13 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#ifndef SOAP_H ++#define SOAP_H ++ ++#include "ezxml/ezxml.h" ++ ++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); ++ezxml_t soap_member_add(ezxml_t parent, int version, const char *name); ++ezxml_t soap_response_create(int version, const char *operation); ++int soap_response_send(ezxml_t response); ++ ++#endif +--- a/test/test_cgi.py ++++ b/test/test_cgi.py +@@ -52,6 +52,36 @@ def request(service, operation, content= + + + class CGITests(unittest.TestCase): ++ def test_multiple_profiles(self): ++ for count in [0, 1, 2, 4, 12]: ++ config = configuration(count) ++ for service in ['media', 'media2']: ++ status, root = request(service, 'GetProfiles', ++ 'All', config) ++ self.assertEqual(status, 200) ++ profiles = root.findall('.//{*}Profiles') ++ self.assertEqual([p.get('token') for p in profiles], ++ [p['name'] for p in config['profiles']]) ++ status, root = request(service, 'GetVideoEncoderConfigurations', ++ config=config) ++ self.assertEqual(status, 200) ++ self.assertEqual(len(root.findall('.//{*}Configurations')), count) ++ ++ def test_profile_lookup(self): ++ config = configuration(4) ++ config['profiles'][3]['name'] = 'Entrance_preview' ++ for service in ['media', 'media2']: ++ status, root = request(service, 'GetStreamUri', ++ 'Entrance_preview', config) ++ self.assertEqual(status, 200) ++ self.assertEqual(root.findtext('.//{*}Uri'), ++ 'rtsp://127.0.0.1:8554/camera/3') ++ status, root = request(service, 'GetVideoEncoderConfigurations', ++ 'Entrance_preview_VideoEncoderToken' ++ '', config) ++ self.assertEqual(status, 200) ++ self.assertEqual(len(root.findall('.//{*}Configurations')), 1) ++ + def test_json_bitrate(self): + status, root = request('media', 'GetProfiles') + self.assertEqual(status, 200) diff --git a/multimedia/onvif-simple-server/patches/0006-feat-describe-configured-video-encoding-parameters-a.patch b/multimedia/onvif-simple-server/patches/0006-feat-describe-configured-video-encoding-parameters-a.patch new file mode 100644 index 0000000000..12e4daef79 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0006-feat-describe-configured-video-encoding-parameters-a.patch @@ -0,0 +1,1320 @@ +From 4c87faf36913489ce993828c30101bf2a96ac2c0 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +Date: Sun, 18 Oct 2026 10:18:45 +0100 +Subject: [PATCH 06/15] feat: describe configured video encoding parameters + accurately + +Configure codec profile, GOP, quality, encoding interval and fractional +frame rate in both input formats. Share source and encoder options with +configuration responses and allow explicit sensor dimensions. + +Expose H265 through Media2, omit H264 members from JPEG configurations, +and preserve literal percent escapes when formatting stream URLs. +Media1 uses an integer upper bound for fractional frame-rate limits. + +Signed-off-by: Daniel Golle +--- + Makefile | 7 +- + Makefile.static | 2 +- + README.md | 21 ++++ + conf.c | 114 ++++++++++++++++----- + media2_service.c | 144 --------------------------- + media2_service.h | 3 - + media_options.c | 158 +++++++++++++++++++++++++++++ + media_options.h | 7 ++ + media_profiles.c | 84 +++++++++++----- + media_profiles.h | 5 + + media_service.c | 225 ------------------------------------------ + media_service.h | 6 -- + onvif_simple_server.c | 19 ++-- + onvif_simple_server.h | 9 ++ + soap.c | 9 ++ + soap.h | 1 + + test/test_cgi.py | 69 ++++++++++++- + 17 files changed, 442 insertions(+), 441 deletions(-) + create mode 100644 media_options.c + create mode 100644 media_options.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 = 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_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 +@@ -52,7 +52,10 @@ wsd_simple_server: $(OBJECTS_W) + $(CC) $(OBJECTS_W) $(LIBS_W) -fPIC -Os -o $@ + $(STRIP) $@ + +-.PHONY: all clean test ++.PHONY: all clean test test-cgi ++ ++test-cgi: onvif_simple_server ++ python3 test/test_cgi.py + + # Build and run unit tests using the native host compiler. + # Uses stub mbedTLS headers from test/ so no crypto library is required. +--- 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 = 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_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 +@@ -66,6 +66,27 @@ diff -Naur busybox-1.36.1.ori/networking + ``` + + ## Configuration ++### Video parameters ++ ++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 ++JSON configurations use the same field names. Profile names must be unique. ++Set these fields to the actual encoder configuration. Compatibility defaults ++are 30 fps, GOP 40, quality 100, encoding interval 1 and H264 High/H265 Main. ++A bitrate of zero denotes an unspecified limit; no bandwidth is invented. ++ ++Media2 reports fractional frame rates. Media1 requires an integer upper ++frame-rate limit, so a fractional rate is rounded upwards for that field. ++H265 streams are exposed through Media2 and excluded from Media1. JPEG ++descriptions omit inter-frame codec settings. Static configuration options ++describe current settings. ++ ++Optional global `source_width`, `source_height`, `source_framerate` and ++`source_framerate_den` describe the sensor independently of encoded outputs. ++Without source dimensions, the largest configured output provides the legacy ++fallback. The source token remains stable when profiles change. ++ + 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. +--- a/conf.c ++++ b/conf.c +@@ -24,6 +24,7 @@ + #include + #include + #include ++#include + + #include + #include "conf.h" +@@ -33,6 +34,54 @@ + + extern service_context_t service_ctx; + ++#define DEFAULT_GOV_LENGTH 40 ++#define DEFAULT_VIDEO_QUALITY 100 ++#define DEFAULT_FRAME_RATE 30 ++ ++static void profile_init(stream_profile_t *profile) ++{ ++ memset(profile, 0, sizeof(*profile)); ++ profile->type = H264; ++ profile->framerate = DEFAULT_FRAME_RATE; ++ profile->framerate_den = 1; ++ profile->gov_length = DEFAULT_GOV_LENGTH; ++ profile->encoding_interval = 1; ++ profile->quality = DEFAULT_VIDEO_QUALITY; ++ profile->audio_encoder = AAC; ++} ++ ++static int profiles_validate(void) ++{ ++ stream_profile_t *profile; ++ int i; ++ int j; ++ ++ 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)) ++ return -2; ++ for (i = 0; i < service_ctx.profiles_num; i++) { ++ profile = &service_ctx.profiles[i]; ++ if (!profile->name || !*profile->name || 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) ++ return -2; ++ for (j = 0; j < i; j++) ++ if (!strcmp(profile->name, service_ctx.profiles[j].name)) ++ return -2; ++ if (!profile->encoding_profile) ++ profile->encoding_profile = strdup(profile->type == H265 ? "Main" : "High"); ++ if (profile->type == H264 && strcmp(profile->encoding_profile, "Baseline") && ++ strcmp(profile->encoding_profile, "Main") && ++ strcmp(profile->encoding_profile, "Extended") && ++ strcmp(profile->encoding_profile, "High")) ++ return -2; ++ } ++ return 0; ++} ++ + int process_conf_file(char *file) + { + FILE *fF; +@@ -65,6 +114,10 @@ int process_conf_file(char *file) + service_ctx.adv_synology_nvr = 0; + service_ctx.profiles = NULL; + service_ctx.profiles_num = 0; ++ service_ctx.source_width = 0; ++ service_ctx.source_height = 0; ++ service_ctx.source_framerate = 0; ++ service_ctx.source_framerate_den = 1; + service_ctx.scopes = NULL; + service_ctx.scopes_num = 0; + service_ctx.ptz_node.enable = 0; +@@ -202,10 +255,20 @@ 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, "source_width") == 0) { ++ service_ctx.source_width = atoi(value); ++ } else if (strcasecmp(param, "source_height") == 0) { ++ service_ctx.source_height = atoi(value); ++ } else if (strcasecmp(param, "source_framerate") == 0) { ++ service_ctx.source_framerate = atoi(value); ++ } else if (strcasecmp(param, "source_framerate_den") == 0) { ++ service_ctx.source_framerate_den = atoi(value); ++ + //Media Profile for ONVIF Media Service + } else if (strcasecmp(param, "name") == 0) { + service_ctx.profiles_num++; + service_ctx.profiles = (stream_profile_t *) realloc(service_ctx.profiles, service_ctx.profiles_num * sizeof(stream_profile_t)); ++ profile_init(&service_ctx.profiles[service_ctx.profiles_num - 1]); + + size_t vlen = strlen(value); + while (vlen > 0 && value[vlen - 1] == '_') value[--vlen] = '\0'; +@@ -221,15 +284,6 @@ int process_conf_file(char *file) + } + service_ctx.profiles[service_ctx.profiles_num - 1].name = (char *) malloc(strlen(value) + 1); + snprintf(service_ctx.profiles[service_ctx.profiles_num - 1].name, strlen(value) + 1, "%s", value); +- service_ctx.profiles[service_ctx.profiles_num - 1].width = 0; +- service_ctx.profiles[service_ctx.profiles_num - 1].height = 0; +- service_ctx.profiles[service_ctx.profiles_num - 1].url = NULL; +- service_ctx.profiles[service_ctx.profiles_num - 1].snapurl = NULL; +- service_ctx.profiles[service_ctx.profiles_num - 1].type = H264; +- service_ctx.profiles[service_ctx.profiles_num - 1].bitrate = 0; +- service_ctx.profiles[service_ctx.profiles_num - 1].framerate = 30; +- service_ctx.profiles[service_ctx.profiles_num - 1].audio_encoder = AAC; +- service_ctx.profiles[service_ctx.profiles_num - 1].audio_decoder = AUDIO_NONE; + } else if (strcasecmp(param, "width") == 0) { + errno = 0; + service_ctx.profiles[service_ctx.profiles_num - 1].width = strtol(value, &endptr, 10); +@@ -275,6 +329,16 @@ int process_conf_file(char *file) + service_ctx.profiles[service_ctx.profiles_num - 1].bitrate = atoi(value); + } else if (strcasecmp(param, "framerate") == 0) { + service_ctx.profiles[service_ctx.profiles_num - 1].framerate = atoi(value); ++ } else if (strcasecmp(param, "framerate_den") == 0) { ++ service_ctx.profiles[service_ctx.profiles_num - 1].framerate_den = atoi(value); ++ } else if (strcasecmp(param, "gov_length") == 0) { ++ service_ctx.profiles[service_ctx.profiles_num - 1].gov_length = atoi(value); ++ } else if (strcasecmp(param, "encoding_interval") == 0) { ++ service_ctx.profiles[service_ctx.profiles_num - 1].encoding_interval = atoi(value); ++ } else if (strcasecmp(param, "quality") == 0) { ++ service_ctx.profiles[service_ctx.profiles_num - 1].quality = strtod(value, NULL); ++ } else if (strcasecmp(param, "encoding_profile") == 0) { ++ service_ctx.profiles[service_ctx.profiles_num - 1].encoding_profile = strdup(value); + } else if (strcasecmp(param, "audio_encoder") == 0) { + if (strcasecmp(value, "NONE") == 0) + service_ctx.profiles[service_ctx.profiles_num - 1].audio_encoder = AUDIO_NONE; +@@ -699,7 +763,7 @@ int process_conf_file(char *file) + log_info("Device UUID: %s", service_ctx.device_uuid); + } + +- return 0; ++ return profiles_validate(); + } + + // Remember to free the string +@@ -734,7 +798,7 @@ void get_double_from_json(double* var, j + json_object* d = NULL; + + if (json_object_object_get_ex(j, name, &d)) { +- if (json_object_is_type(d, json_type_double)) { ++ if (json_object_is_type(d, json_type_double) || json_object_is_type(d, json_type_int)) { + *var = json_object_get_double(d); + } + } +@@ -818,6 +882,10 @@ int process_json_conf_file(char *file) + service_ctx.adv_synology_nvr = 0; + service_ctx.profiles = NULL; + service_ctx.profiles_num = 0; ++ service_ctx.source_width = 0; ++ service_ctx.source_height = 0; ++ service_ctx.source_framerate = 0; ++ service_ctx.source_framerate_den = 1; + service_ctx.scopes = NULL; + service_ctx.scopes_num = 0; + service_ctx.ptz_node.enable = 0; +@@ -881,6 +949,10 @@ 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_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"); ++ get_int_from_json(&service_ctx.source_framerate_den, json_file, "source_framerate_den"); + get_bool_from_json(&(service_ctx.adv_synology_nvr), json_file, "adv_synology_nvr"); + + // Apply sane defaults for required fields if not provided in config +@@ -988,18 +1060,8 @@ int process_json_conf_file(char *file) + + service_ctx.profiles_num++; + service_ctx.profiles = (stream_profile_t *) realloc(service_ctx.profiles, service_ctx.profiles_num * sizeof(stream_profile_t)); ++ profile_init(&service_ctx.profiles[service_ctx.profiles_num - 1]); + +- // Init defaults +- service_ctx.profiles[service_ctx.profiles_num - 1].name = NULL; +- service_ctx.profiles[service_ctx.profiles_num - 1].width = 0; +- service_ctx.profiles[service_ctx.profiles_num - 1].height = 0; +- service_ctx.profiles[service_ctx.profiles_num - 1].url = NULL; +- service_ctx.profiles[service_ctx.profiles_num - 1].snapurl = NULL; +- service_ctx.profiles[service_ctx.profiles_num - 1].type = H264; +- service_ctx.profiles[service_ctx.profiles_num - 1].bitrate = 0; +- service_ctx.profiles[service_ctx.profiles_num - 1].framerate = 30; +- service_ctx.profiles[service_ctx.profiles_num - 1].audio_encoder = AAC; +- service_ctx.profiles[service_ctx.profiles_num - 1].audio_decoder = AUDIO_NONE; + + get_string_from_json(&(service_ctx.profiles[service_ctx.profiles_num - 1].name), item, "name"); + char *n = service_ctx.profiles[service_ctx.profiles_num - 1].name; +@@ -1020,6 +1082,11 @@ int process_json_conf_file(char *file) + 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_int_from_json(&service_ctx.profiles[i].framerate_den, item, "framerate_den"); ++ get_int_from_json(&service_ctx.profiles[i].gov_length, item, "gov_length"); ++ get_int_from_json(&service_ctx.profiles[i].encoding_interval, item, "encoding_interval"); ++ get_double_from_json(&service_ctx.profiles[i].quality, item, "quality"); ++ get_string_from_json(&service_ctx.profiles[i].encoding_profile, item, "encoding_profile"); + 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"); + tmp = NULL; +@@ -1275,7 +1342,7 @@ int process_json_conf_file(char *file) + json_object_put(json_file); + free(buffer); + +- return 0; ++ return profiles_validate(); + } + + void free_conf_file() +@@ -1321,6 +1388,7 @@ void free_conf_file() + if (service_ctx.profiles[i].snapurl != NULL) free(service_ctx.profiles[i].snapurl); + if (service_ctx.profiles[i].url != NULL) free(service_ctx.profiles[i].url); + if (service_ctx.profiles[i].name != NULL) free(service_ctx.profiles[i].name); ++ free(service_ctx.profiles[i].encoding_profile); + } + if (service_ctx.profiles != NULL) free(service_ctx.profiles); + +--- a/media2_service.c ++++ b/media2_service.c +@@ -113,153 +113,9 @@ int media2_get_video_source_modes() + } + } + +-int media2_get_video_source_configurations() +-{ +- const char *configuration_token = get_element("ConfigurationToken", "Body"); +- const char *profile_token = get_element("ProfileToken", "Body"); +- char token[23]; +- char profiles_num[2], stmp_w[16], stmp_h[16]; +- +- memset(token, '\0', sizeof(token)); +- if (profile_token != NULL) { +- // Extract "Profile_x" from token Profile_x +- strncpy(token, profile_token, 9); +- } else if (configuration_token != NULL) { +- strncpy(token, configuration_token, 22); +- } else if (service_ctx.profiles_num > 0) { +- strncpy(token, service_ctx.profiles[0].name, 9); +- } +- +- if ((strcasecmp(service_ctx.profiles[0].name, token) == 0) || +- (strcasecmp(service_ctx.profiles[1].name, token) == 0) || +- (strcasecmp("VideoSourceConfigToken", token) == 0)) { +- +- int vsrc = get_video_source_index(); +- snprintf(profiles_num, sizeof(profiles_num), "%d", service_ctx.profiles_num); +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[vsrc].height); +- long size = cat(NULL, "media2_service_files/GetVideoSourceConfigurations.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); + +- output_http_headers(size); + +- return cat("stdout", "media2_service_files/GetVideoSourceConfigurations.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); +- } else { +- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoConfig", "No config", "The requested configuration indicated does not exist"); +- return -1; +- } +-} +- +-int media2_get_video_source_configuration_options() +-{ +- const char *configuration_token = get_element("ConfigurationToken", "Body"); +- const char *profile_token = get_element("ProfileToken", "Body"); +- char token[23]; +- char stmp_w[16], stmp_h[16]; + +- memset(token, '\0', sizeof(token)); +- if (profile_token != NULL) { +- // Extract "Profile_x" from token Profile_x +- strncpy(token, profile_token, 9); +- } else if (configuration_token != NULL) { +- strncpy(token, configuration_token, 22); +- } else if (service_ctx.profiles_num > 0) { +- strncpy(token, service_ctx.profiles[0].name, 9); +- } +- +- if ((strcasecmp(service_ctx.profiles[0].name, token) == 0) || +- (strcasecmp(service_ctx.profiles[1].name, token) == 0) || +- (strcasecmp("VideoSourceConfigToken", token) == 0)) { +- +- 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); +- long size = cat(NULL, "media2_service_files/GetVideoSourceConfigurationOptions.xml", 4, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetVideoSourceConfigurationOptions.xml", 4, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); +- +- } else { +- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoConfig", "No config", "The requested configuration indicated does not exist"); +- return -1; +- } +-} +- +- +-int media2_get_video_encoder_configuration_options() +-{ +- char stmp_w[16], stmp_h[16]; +- const char *configuration_token = get_element("ConfigurationToken", "Body"); +- const char *profile_token = get_element("ProfileToken", "Body"); +- char token[10]; +- char video_enc[16]; +- +- memset(token, '\0', sizeof(token)); +- if (configuration_token != NULL) { +- // Extract "Profile_x" from token Profile_x_VideoEncoderConfig +- strncpy(token, configuration_token, 9); +- } else if (profile_token != NULL) { +- // Extract "Profile_x" from token Profile_x +- strncpy(token, profile_token, 9); +- } else if (service_ctx.profiles_num > 0) { +- strncpy(token, service_ctx.profiles[0].name, 9); +- } +- +- if ((service_ctx.profiles_num > 0) && +- (strcasecmp(service_ctx.profiles[0].name, token) == 0)) { +- +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[0].height); +- set_video_codec(video_enc, 16, service_ctx.profiles[0].type, 2); +- long size = cat(NULL, "media2_service_files/GetVideoEncoderConfigurationOptions.xml", 8, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%H264PROFILE%", "High", +- "%VIDEO_ENCODING%", video_enc); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetVideoEncoderConfigurationOptions.xml", 8, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%H264PROFILE%", "High", +- "%VIDEO_ENCODING%", video_enc); +- +- } else if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, token) == 0)) { +- +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[1].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[1].height); +- set_video_codec(video_enc, 16, service_ctx.profiles[1].type, 2); +- long size = cat(NULL, "media2_service_files/GetVideoEncoderConfigurationOptions.xml", 8, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%H264PROFILE%", "Main", +- "%VIDEO_ENCODING%", video_enc); +- +- output_http_headers(size); +- +- return cat("stdout", "media2_service_files/GetVideoEncoderConfigurationOptions.xml", 8, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%H264PROFILE%", "Main", +- "%VIDEO_ENCODING%", video_enc); +- +- } else { +- send_fault("media2_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -1; +- } +-} + + int media2_get_audio_source_configurations() + { +--- a/media2_service.h ++++ b/media2_service.h +@@ -19,9 +19,6 @@ + + int media2_get_service_capabilities(); + int media2_get_video_source_modes(); +-int media2_get_video_source_configurations(); +-int media2_get_video_source_configuration_options(); +-int media2_get_video_encoder_configuration_options(); + int media2_get_audio_source_configurations(); + int media2_get_audio_source_configuration_options(); + int media2_get_audio_encoder_configurations(); +--- /dev/null ++++ b/media_options.c +@@ -0,0 +1,158 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#include ++#include ++ ++#include "ezxml_wrapper.h" ++#include "media_options.h" ++#include "media_profiles.h" ++#include "onvif_simple_server.h" ++#include "fault.h" ++#include "soap.h" ++#include "utils.h" ++ ++extern service_context_t service_ctx; ++ ++static int source_operation(const char *operation) ++{ ++ return !strcmp(operation, "GetVideoSources") || ++ !strcmp(operation, "GetVideoSourceConfigurations") || ++ !strcmp(operation, "GetVideoSourceConfiguration") || ++ !strcmp(operation, "GetCompatibleVideoSourceConfigurations") || ++ !strcmp(operation, "GetVideoSourceConfigurationOptions"); ++} ++ ++static void source_add(ezxml_t response, const char *operation, int version) ++{ ++ double framerate; ++ ezxml_t member; ++ ezxml_t bounds; ++ int height; ++ int width; ++ ++ media_source_info(&width, &height, &framerate); ++ if (!strcmp(operation, "GetVideoSources")) { ++ member = soap_member_add(response, version, "VideoSources"); ++ ezxml_set_attr(member, "token", "VideoSourceToken"); ++ soap_number_add(member, "tt:Framerate", framerate); ++ bounds = soap_child_add(member, "tt:Resolution", NULL); ++ soap_number_add(bounds, "tt:Width", width); ++ soap_number_add(bounds, "tt:Height", height); ++ return; ++ } ++ if (!strcmp(operation, "GetVideoSourceConfigurationOptions")) { ++ member = soap_member_add(response, version, "Options"); ++ bounds = soap_child_add(member, "tt:BoundsRange", NULL); ++ soap_range_add(bounds, "tt:XRange", 0, 0); ++ soap_range_add(bounds, "tt:YRange", 0, 0); ++ soap_range_add(bounds, "tt:WidthRange", width, width); ++ soap_range_add(bounds, "tt:HeightRange", height, height); ++ soap_child_add(member, "tt:VideoSourceTokensAvailable", "VideoSourceToken"); ++ return; ++ } ++ member = soap_member_add(response, version, ++ !strcmp(operation, "GetVideoSourceConfiguration") ? ++ "Configuration" : "Configurations"); ++ media_source_configuration_add(member); ++} ++ ++static void encoder_options_add(ezxml_t response, stream_profile_t *profile, int version) ++{ ++ char number[MAX_LEN]; ++ char codec[MAX_LEN]; ++ ezxml_t resolution; ++ ezxml_t options; ++ ezxml_t encoder; ++ double framerate; ++ ++ framerate = (double)profile->framerate / profile->framerate_den; ++ set_video_codec(codec, sizeof(codec), profile->type, version); ++ options = soap_member_add(response, version, "Options"); ++ if (version == 2) { ++ snprintf(number, sizeof(number), "%.9g", framerate); ++ ezxml_set_attr_d(options, "FrameRatesSupported", number); ++ if (profile->type == H264 || profile->type == H265) { ++ snprintf(number, sizeof(number), "%d %d", profile->gov_length, profile->gov_length); ++ ezxml_set_attr_d(options, "GovLengthRange", number); ++ ezxml_set_attr_d(options, "ProfilesSupported", profile->encoding_profile); ++ } ++ soap_child_add(options, "tt:Encoding", codec); ++ } ++ soap_range_add(options, "tt:QualityRange", profile->quality, profile->quality); ++ encoder = options; ++ if (version == 1) { ++ snprintf(number, sizeof(number), "tt:%s", codec); ++ encoder = soap_child_add(options, number, 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 (version == 2) { ++ soap_range_add(encoder, "tt:BitrateRange", profile->bitrate, profile->bitrate); ++ return; ++ } ++ 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; ++ soap_range_add(encoder, "tt:FrameRateRange", framerate, framerate); ++ soap_range_add(encoder, "tt:EncodingIntervalRange", profile->encoding_interval, ++ profile->encoding_interval); ++ if (profile->type == H264) ++ soap_child_add(encoder, "tt:H264ProfilesSupported", profile->encoding_profile); ++ if (profile->type == MPEG4) ++ soap_child_add(encoder, "tt:Mpeg4ProfilesSupported", "SP"); ++} ++ ++int media_options_dispatch(const char *operation, int version) ++{ ++ const char *configuration_token; ++ const char *profile_token; ++ const char *service; ++ ezxml_t response; ++ int source; ++ int index; ++ int i; ++ ++ source = source_operation(operation); ++ if (!source && strcmp(operation, "GetVideoEncoderConfigurationOptions")) ++ return 0; ++ service = version == 1 ? "media_service" : "media2_service"; ++ configuration_token = get_element("ConfigurationToken", "Body"); ++ profile_token = get_element("ProfileToken", "Body"); ++ index = profile_token ? media_profile_find(profile_token, "") : -1; ++ if (profile_token && index < 0) { ++ send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoProfile", ++ "No profile", "The requested profile does not exist"); ++ return 1; ++ } ++ if (configuration_token && source && strcmp(configuration_token, "VideoSourceConfigToken")) { ++ send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoConfig", ++ "No configuration", "The requested source configuration does not exist"); ++ return 1; ++ } ++ if (configuration_token && !source) { ++ index = media_profile_find(configuration_token, "_VideoEncoderToken"); ++ if (index < 0) { ++ send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoConfig", ++ "No configuration", "The requested encoder configuration does not exist"); ++ return 1; ++ } ++ } ++ response = soap_response_create(version, operation); ++ if (source) { ++ source_add(response, operation, version); ++ 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; ++} +--- /dev/null ++++ b/media_options.h +@@ -0,0 +1,7 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#ifndef MEDIA_OPTIONS_H ++#define MEDIA_OPTIONS_H ++ ++int media_options_dispatch(const char *operation, int version); ++ ++#endif +--- a/media_profiles.c ++++ b/media_profiles.c +@@ -11,7 +11,7 @@ + + extern service_context_t service_ctx; + +-static int profile_find(const char *token, const char *suffix) ++int media_profile_find(const char *token, const char *suffix) + { + char name[MAX_LEN]; + int i; +@@ -40,11 +40,9 @@ static void multicast_add(ezxml_t parent + soap_child_add(multicast, "tt:AutoStart", "false"); + } + +-static void source_configuration_add(ezxml_t node) ++void media_source_info(int *width, int *height, double *framerate) + { + stream_profile_t *source; +- char number[MAX_LEN]; +- ezxml_t bounds; + int i; + + source = NULL; +@@ -52,6 +50,22 @@ static void source_configuration_add(ezx + if (!source || (long long)service_ctx.profiles[i].width * service_ctx.profiles[i].height > + (long long)source->width * source->height) + source = &service_ctx.profiles[i]; ++ *width = service_ctx.source_width ? service_ctx.source_width : source ? source->width : 0; ++ *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; ++} ++ ++void media_source_configuration_add(ezxml_t node) ++{ ++ char number[MAX_LEN]; ++ double framerate; ++ ezxml_t bounds; ++ int height; ++ int width; ++ ++ media_source_info(&width, &height, &framerate); + ezxml_set_attr(node, "token", "VideoSourceConfigToken"); + soap_child_add(node, "tt:Name", "VideoSourceConfig"); + soap_number_add(node, "tt:UseCount", service_ctx.profiles_num); +@@ -59,9 +73,9 @@ static void source_configuration_add(ezx + bounds = soap_child_add(node, "tt:Bounds", NULL); + ezxml_set_attr(bounds, "x", "0"); + ezxml_set_attr(bounds, "y", "0"); +- snprintf(number, sizeof(number), "%d", source ? source->width : 0); ++ snprintf(number, sizeof(number), "%d", width); + ezxml_set_attr_d(bounds, "width", number); +- snprintf(number, sizeof(number), "%d", source ? source->height : 0); ++ snprintf(number, sizeof(number), "%d", height); + ezxml_set_attr_d(bounds, "height", number); + } + +@@ -84,23 +98,30 @@ static void encoder_configuration_add(ez + resolution = soap_child_add(node, "tt:Resolution", NULL); + soap_number_add(resolution, "tt:Width", profile->width); + soap_number_add(resolution, "tt:Height", profile->height); +- soap_number_add(node, "tt:Quality", 100); ++ if (version == 1) ++ soap_number_add(node, "tt:Quality", profile->quality); + rate = soap_child_add(node, "tt:RateControl", NULL); +- soap_number_add(rate, "tt:FrameRateLimit", profile->framerate); ++ 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); + if (version == 1) +- soap_number_add(rate, "tt:EncodingInterval", 1); ++ soap_number_add(rate, "tt:EncodingInterval", profile->encoding_interval); + soap_number_add(rate, "tt:BitrateLimit", profile->bitrate); +- if (version == 1) { ++ if (version == 1 && profile->type == H264) { + h264 = soap_child_add(node, "tt:H264", NULL); +- soap_number_add(h264, "tt:GovLength", 40); +- soap_child_add(h264, "tt:H264Profile", index ? "Main" : "High"); +- } else { +- ezxml_set_attr(node, "GovLength", "40"); +- ezxml_set_attr(node, "Profile", index ? "Main" : "High"); ++ soap_number_add(h264, "tt:GovLength", profile->gov_length); ++ soap_child_add(h264, "tt:H264Profile", profile->encoding_profile); ++ } else if (version == 2 && (profile->type == H264 || profile->type == H265)) { ++ snprintf(name, sizeof(name), "%d", profile->gov_length); ++ ezxml_set_attr_d(node, "GovLength", name); ++ ezxml_set_attr_d(node, "Profile", profile->encoding_profile); + } + multicast_add(node); + if (version == 1) + soap_child_add(node, "tt:SessionTimeout", "PT0S"); ++ else ++ soap_number_add(node, "tt:Quality", profile->quality); + } + + static int type_requested(const char *name) +@@ -125,13 +146,13 @@ static void profile_add(ezxml_t node, in + profile = &service_ctx.profiles[index]; + ezxml_set_attr_d(node, "token", profile->name); + ezxml_set_attr(node, "fixed", "true"); +- child = soap_member_add(node, version, "Name"); ++ child = soap_child_add(node, version == 1 ? "tt:Name" : "tr2:Name", NULL); + ezxml_set_txt_d(child, profile->name); + configurations = version == 1 ? node : soap_member_add(node, version, "Configurations"); + if (version == 1 || type_requested("VideoSource")) { + child = soap_child_add(configurations, version == 1 ? + "tt:VideoSourceConfiguration" : "tr2:VideoSource", NULL); +- source_configuration_add(child); ++ media_source_configuration_add(child); + } + if (version == 1 || type_requested("VideoEncoder")) { + child = soap_child_add(configurations, version == 1 ? +@@ -176,6 +197,7 @@ static void uri_add(ezxml_t response, in + { + stream_profile_t *profile; + char uri[MAX_LEN]; ++ const char *placeholder; + const char *format; + ezxml_t member; + +@@ -183,13 +205,16 @@ static void uri_add(ezxml_t response, in + format = snapshot ? profile->snapurl : profile->url; + if (!format) + return; +- snprintf(uri, sizeof(uri), format, service_ctx.address_url); +- if (version == 2 || snapshot) { +- member = soap_member_add(response, version, snapshot ? "MediaUri" : "Uri"); +- if (version == 2) { +- ezxml_set_txt_d(member, uri); +- return; +- } ++ placeholder = strstr(format, "%s"); ++ if (placeholder) ++ snprintf(uri, sizeof(uri), "%.*s%s%s", (int)(placeholder - format), format, ++ service_ctx.address_url, placeholder + strlen("%s")); ++ else ++ snprintf(uri, sizeof(uri), "%s", format); ++ if (version == 2) { ++ member = soap_member_add(response, version, "Uri"); ++ ezxml_set_txt_d(member, uri); ++ return; + } else { + member = soap_member_add(response, version, "MediaUri"); + } +@@ -222,19 +247,24 @@ int media_profiles_dispatch(const char * + if (version == 2 && profiles) + profile_token = get_element("Token", "Body"); + configuration_token = get_element("ConfigurationToken", "Body"); +- index = profile_token ? profile_find(profile_token, "") : -1; ++ index = profile_token ? media_profile_find(profile_token, "") : -1; + if (profile_token && index < 0) { + send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoProfile", + "No profile", "The requested profile does not exist"); + return 1; + } + if (configuration_token) +- index = profile_find(configuration_token, "_VideoEncoderToken"); ++ index = media_profile_find(configuration_token, "_VideoEncoderToken"); + if (configuration_token && index < 0) { + send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoConfig", + "No configuration", "The requested configuration does not exist"); + return 1; + } ++ if (index >= 0 && version == 1 && service_ctx.profiles[index].type == H265) { ++ send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoProfile", ++ "No profile", "H265 profiles are available through Media2"); ++ return 1; ++ } + if ((uri || !strcmp(operation, "GetProfile") || + !strcmp(operation, "GetVideoEncoderConfiguration")) && index < 0) { + send_fault((char *)service, "Sender", "ter:InvalidArgVal", "ter:NoProfile", +@@ -248,6 +278,8 @@ int media_profiles_dispatch(const char * + return 1; + } + for (i = 0; i < service_ctx.profiles_num; i++) { ++ if (version == 1 && service_ctx.profiles[i].type == H265) ++ continue; + if (index >= 0 && index != i) + continue; + member = soap_member_add(response, version, profiles ? +--- a/media_profiles.h ++++ b/media_profiles.h +@@ -2,6 +2,11 @@ + #ifndef MEDIA_PROFILES_H + #define MEDIA_PROFILES_H + ++#include "ezxml/ezxml.h" ++ + int media_profiles_dispatch(const char *operation, int version); ++int media_profile_find(const char *token, const char *suffix); ++void media_source_info(int *width, int *height, double *framerate); ++void media_source_configuration_add(ezxml_t node); + + #endif +--- a/media_service.c ++++ b/media_service.c +@@ -28,26 +28,6 @@ + + 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 media_get_service_capabilities() + { +@@ -58,148 +38,10 @@ int media_get_service_capabilities() + return cat("stdout", "media_service_files/GetServiceCapabilities.xml", 0); + } + +-int media_get_video_sources() +-{ +- // Get the video source from the profile with the largest frame area +- char stmp_w[16], stmp_h[16], 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); +- long size = cat(NULL, "media_service_files/GetVideoSources.xml", 6, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%FRAMERATE%", stmp_fps); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetVideoSources.xml", 6, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%FRAMERATE%", stmp_fps); +-} + +-int media_get_video_source_configurations() +-{ +- char profiles_num[2], stmp_w[16], stmp_h[16]; +- int vsrc = get_video_source_index(); + +- snprintf(profiles_num, sizeof(profiles_num), "%d", service_ctx.profiles_num); +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[vsrc].height); +- long size = cat(NULL, "media_service_files/GetVideoSourceConfigurations.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); + +- output_http_headers(size); + +- return cat("stdout", "media_service_files/GetVideoSourceConfigurations.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); +-} +- +-int media_get_video_source_configuration() +-{ +- const char *configuration_token = get_element("ConfigurationToken", "Body"); +- char profiles_num[2], stmp_w[16], stmp_h[16]; +- +- if (configuration_token == NULL) { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoConfig", "No config", "The requested configuration indicated does not exist"); +- return -1; +- } +- +- if (strncasecmp("VideoSourceConfigToken", configuration_token, 22) == 0) { +- +- int vsrc = get_video_source_index(); +- snprintf(profiles_num, sizeof(profiles_num), "%d", service_ctx.profiles_num); +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[vsrc].height); +- long size = cat(NULL, "media_service_files/GetVideoSourceConfiguration.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetVideoSourceConfiguration.xml", 6, +- "%PROFILES_NUM%", profiles_num, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); +- +- } else { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoConfig", "No config", "The requested configuration indicated does not exist"); +- return -2; +- } +-} +- +-int media_get_compatible_video_source_configurations() +-{ +- // Get the video source configuration from the 1st profile +- // Ignore the requested token +- char profiles_num[2]; +- char stmp_w[16], stmp_h[16]; +- int vsrc = get_video_source_index(); +- +- snprintf(profiles_num, sizeof(profiles_num), "%d", service_ctx.profiles_num); +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[vsrc].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[vsrc].height); +- long size = cat(NULL, "media_service_files/GetCompatibleVideoSourceConfigurations.xml", 8, +- "%PROFILES_NUM%", profiles_num, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%PROFILE_TYPE", "High"); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetCompatibleVideoSourceConfigurations.xml", 8, +- "%PROFILES_NUM%", profiles_num, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%PROFILE_TYPE", "High"); +-} +- +-int media_get_video_source_configuration_options() +-{ +- const char *configuration_token = get_element("ConfigurationToken", "Body"); +- const char *profile_token = get_element("ProfileToken", "Body"); +- char token[23]; +- char stmp_w[16], stmp_h[16]; +- +- memset(token, '\0', sizeof(token)); +- if (profile_token != NULL) { +- // Extract "Profile_x" from token Profile_x +- strncpy(token, profile_token, 9); +- } else if (configuration_token != NULL) { +- strncpy(token, configuration_token, 22); +- } else { +- strncpy(token, service_ctx.profiles[0].name, 9); +- } +- +- if ((strcasecmp(service_ctx.profiles[0].name, token) == 0) || +- (strcasecmp(service_ctx.profiles[1].name, token) == 0) || +- (strcasecmp("VideoSourceConfigToken", token) == 0)) { +- +- 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); +- long size = cat(NULL, "media_service_files/GetVideoSourceConfigurationOptions.xml", 4, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetVideoSourceConfigurationOptions.xml", 4, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h); +- +- } else { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoConfig", "No config", "The requested configuration indicated does not exist"); +- return -1; +- } +-} + + + +@@ -217,73 +59,6 @@ int media_create_profile() + + + +-int media_get_video_encoder_configuration_options() +-{ +- char stmp_w[16], stmp_h[16], stmp_fps[16]; +- const char *configuration_token = get_element("ConfigurationToken", "Body"); +- const char *profile_token = get_element("ProfileToken", "Body"); +- char vec_token[128]; +- int profile_idx = 0; +- +- if (configuration_token != NULL) { +- snprintf(vec_token, sizeof(vec_token), "%s_VideoEncoderToken", +- service_ctx.profiles[0].name); +- if (strcasecmp(configuration_token, vec_token) == 0) { +- profile_idx = 0; +- } else if (service_ctx.profiles_num == 2) { +- snprintf(vec_token, sizeof(vec_token), "%s_VideoEncoderToken", +- service_ctx.profiles[1].name); +- profile_idx = (strcasecmp(configuration_token, vec_token) == 0) ? 1 : 0; +- } +- } else if (profile_token != NULL) { +- if ((service_ctx.profiles_num == 2) && +- (strcasecmp(service_ctx.profiles[1].name, profile_token) == 0)) +- profile_idx = 1; +- } +- +- if ((service_ctx.profiles_num > 0) && profile_idx == 0) { +- +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[0].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[0].height); +- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[0].framerate > 0 ? service_ctx.profiles[0].framerate : 30); +- long size = cat(NULL, "media_service_files/GetVideoEncoderConfigurationOptions.xml", 8, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%FRAMERATE%", stmp_fps, +- "%PROFILE%", "High"); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetVideoEncoderConfigurationOptions.xml", 8, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%FRAMERATE%", stmp_fps, +- "%PROFILE%", "High"); +- +- } else if ((service_ctx.profiles_num == 2) && profile_idx == 1) { +- +- snprintf(stmp_w, sizeof(stmp_w), "%d", service_ctx.profiles[1].width); +- snprintf(stmp_h, sizeof(stmp_h), "%d", service_ctx.profiles[1].height); +- snprintf(stmp_fps, sizeof(stmp_fps), "%d", service_ctx.profiles[1].framerate > 0 ? service_ctx.profiles[1].framerate : 30); +- long size = cat(NULL, "media_service_files/GetVideoEncoderConfigurationOptions.xml", 8, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%FRAMERATE%", stmp_fps, +- "%PROFILE%", "Main"); +- +- output_http_headers(size); +- +- return cat("stdout", "media_service_files/GetVideoEncoderConfigurationOptions.xml", 8, +- "%WIDTH%", stmp_w, +- "%HEIGHT%", stmp_h, +- "%FRAMERATE%", stmp_fps, +- "%PROFILE%", "Main"); +- +- } else { +- send_fault("media_service", "Sender", "ter:InvalidArgVal", "ter:NoProfile", "No profile", "The requested profile does not exist"); +- return -1; +- } +-} + + int media_get_guaranteed_number_of_video_encoder_instances() + { +--- a/media_service.h ++++ b/media_service.h +@@ -18,14 +18,8 @@ + #define MEDIA_SERVICE_H + + int media_get_service_capabilities(); +-int media_get_video_sources(); +-int media_get_video_source_configurations(); +-int media_get_video_source_configuration(); +-int media_get_compatible_video_source_configurations(); +-int media_get_video_source_configuration_options(); + int media_create_profile(); + int media_get_guaranteed_number_of_video_encoder_instances(); +-int media_get_video_encoder_configuration_options(); + int media_get_audio_sources(); + int media_get_audio_source_configurations(); + int media_get_audio_source_configuration(); +--- a/onvif_simple_server.c ++++ b/onvif_simple_server.c +@@ -29,6 +29,7 @@ + #include "device_service.h" + #include "media_service.h" + #include "media_profiles.h" ++#include "media_options.h" + #include "media2_service.h" + #include "ptz_service.h" + #include "events_service.h" +@@ -517,15 +518,15 @@ int main(int argc, char ** argv) + if (strcasecmp(method, "GetServiceCapabilities") == 0) { + media_get_service_capabilities(); + } else if (strcasecmp(method, "GetVideoSources") == 0) { +- media_get_video_sources(); ++ media_options_dispatch("GetVideoSources", 1); + } else if (strcasecmp(method, "GetVideoSourceConfigurations") == 0) { +- media_get_video_source_configurations(); ++ media_options_dispatch("GetVideoSourceConfigurations", 1); + } else if (strcasecmp(method, "GetVideoSourceConfiguration") == 0) { +- media_get_video_source_configuration(); ++ media_options_dispatch("GetVideoSourceConfiguration", 1); + } else if (strcasecmp(method, "GetCompatibleVideoSourceConfigurations") == 0) { +- media_get_compatible_video_source_configurations(); ++ media_options_dispatch("GetCompatibleVideoSourceConfigurations", 1); + } else if (strcasecmp(method, "GetVideoSourceConfigurationOptions") == 0) { +- media_get_video_source_configuration_options(); ++ media_options_dispatch("GetVideoSourceConfigurationOptions", 1); + } else if (strcasecmp(method, "GetProfiles") == 0) { + media_profiles_dispatch("GetProfiles", 1); + } else if (strcasecmp(method, "GetProfile") == 0) { +@@ -539,7 +540,7 @@ int main(int argc, char ** argv) + } else if (strcasecmp(method, "GetCompatibleVideoEncoderConfigurations") == 0) { + media_profiles_dispatch("GetCompatibleVideoEncoderConfigurations", 1); + } else if (strcasecmp(method, "GetVideoEncoderConfigurationOptions") == 0) { +- media_get_video_encoder_configuration_options(); ++ media_options_dispatch("GetVideoEncoderConfigurationOptions", 1); + } else if (strcasecmp(method, "GetGuaranteedNumberOfVideoEncoderInstances") == 0) { + media_get_guaranteed_number_of_video_encoder_instances(); + } else if (strcasecmp(method, "GetSnapshotUri") == 0) { +@@ -607,13 +608,13 @@ int main(int argc, char ** argv) + } else if (strcasecmp(method, "GetVideoSourceModes") == 0) { + media2_get_video_source_modes(); + } else if (strcasecmp(method, "GetVideoSourceConfigurations") == 0) { +- media2_get_video_source_configurations(); ++ media_options_dispatch("GetVideoSourceConfigurations", 2); + } else if (strcasecmp(method, "GetVideoSourceConfigurationOptions") == 0) { +- media2_get_video_source_configuration_options(); ++ media_options_dispatch("GetVideoSourceConfigurationOptions", 2); + } else if (strcasecmp(method, "GetVideoEncoderConfigurations") == 0) { + media_profiles_dispatch("GetVideoEncoderConfigurations", 2); + } else if (strcasecmp(method, "GetVideoEncoderConfigurationOptions") == 0) { +- media2_get_video_encoder_configuration_options(); ++ media_options_dispatch("GetVideoEncoderConfigurationOptions", 2); + } else if (strcasecmp(method, "GetAudioSourceConfigurations") == 0) { + media2_get_audio_source_configurations(); + } else if (strcasecmp(method, "GetAudioSourceConfigurationOptions") == 0) { +--- a/onvif_simple_server.h ++++ b/onvif_simple_server.h +@@ -61,6 +61,11 @@ typedef struct { + int type; + int bitrate; /* kbps, 0 = unknown */ + int framerate; /* fps, 0 = unknown */ ++ int framerate_den; ++ int gov_length; ++ int encoding_interval; ++ double quality; ++ char *encoding_profile; + int audio_encoder; + int audio_decoder; + } stream_profile_t; +@@ -135,6 +140,10 @@ typedef struct { + + stream_profile_t *profiles; + int profiles_num; ++ int source_width; ++ int source_height; ++ int source_framerate; ++ int source_framerate_den; + + char **scopes; + int scopes_num; +--- a/soap.c ++++ b/soap.c +@@ -32,6 +32,15 @@ ezxml_t soap_member_add(ezxml_t parent, + return soap_child_add(parent, qualified, NULL); + } + ++void soap_range_add(ezxml_t parent, const char *name, double minimum, double maximum) ++{ ++ ezxml_t range; ++ ++ range = soap_child_add(parent, name, NULL); ++ soap_number_add(range, "tt:Min", minimum); ++ soap_number_add(range, "tt:Max", maximum); ++} ++ + ezxml_t soap_response_create(int version, const char *operation) + { + char name[MAX_LEN]; +--- a/soap.h ++++ b/soap.h +@@ -6,6 +6,7 @@ + + 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); + int soap_response_send(ezxml_t response); +--- a/test/test_cgi.py ++++ b/test/test_cgi.py +@@ -34,8 +34,8 @@ def request(service, operation, content= + f'' + f'{content}').encode() + with tempfile.TemporaryDirectory() as directory: +- path = Path(directory) / 'config.json' +- path.write_text(json.dumps(config)) ++ path = Path(directory) / ('config.conf' if isinstance(config, str) else 'config.json') ++ 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))) + result = subprocess.run([str(ROOT / 'onvif_simple_server'), +@@ -52,6 +52,71 @@ def request(service, operation, content= + + + class CGITests(unittest.TestCase): ++ 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' ++ 'quality=42\nbitrate=1234\nframerate=25\naudio_encoder=NONE\n') ++ status, root = request('media', 'GetProfiles', config=config) ++ self.assertEqual(status, 200) ++ self.assertEqual(root.findtext('.//tt:H264Profile', namespaces=NS), 'Baseline') ++ self.assertEqual(root.findtext('.//tt:GovLength', namespaces=NS), '61') ++ self.assertEqual(root.findtext('.//tt:BitrateLimit', namespaces=NS), '1234') ++ ++ def test_encoder_parameters(self): ++ config = configuration(5) ++ encodings = ['H264', 'H264', 'H264', 'H265', 'JPEG'] ++ profiles = ['Baseline', 'Main', 'High', 'Main', 'High'] ++ for i, profile in enumerate(config['profiles']): ++ profile.update(type=encodings[i], encoding_profile=profiles[i], ++ gov_length=31 + i, quality=20 + i) ++ config['profiles'][3].update(framerate=30000, framerate_den=1001) ++ for service, count in [('media', 4), ('media2', 5)]: ++ status, root = request(service, 'GetVideoEncoderConfigurations', config=config) ++ self.assertEqual(status, 200) ++ entries = root.findall('.//{*}Configurations') ++ self.assertEqual(len(entries), count) ++ for entry in entries: ++ token = entry.get('token') ++ index = int(token.split('_')[1]) ++ self.assertEqual(entry.findtext('tt:Encoding', namespaces=NS), encodings[index]) ++ self.assertEqual(float(entry.findtext('tt:Quality', namespaces=NS)), 20 + index) ++ if service == 'media2' and index < 4: ++ self.assertEqual(entry.get('Profile'), profiles[index]) ++ self.assertEqual(entry.get('GovLength'), str(31 + index)) ++ elif index < 3: ++ self.assertEqual(entry.findtext('tt:H264/tt:H264Profile', namespaces=NS), ++ profiles[index]) ++ if encodings[index] == 'JPEG': ++ self.assertIsNone(entry.find('tt:H264', NS)) ++ if service == 'media2': ++ self.assertAlmostEqual(float(entries[3].findtext('tt:RateControl/tt:FrameRateLimit', ++ namespaces=NS)), 30000 / 1001, ++ places=6) ++ ++ def test_source_and_options(self): ++ config = configuration(12) ++ config.update(source_width=3840, source_height=2160, source_framerate=30) ++ status, root = request('media', 'GetVideoSources', config=config) ++ self.assertEqual(root.findtext('.//tt:Width', namespaces=NS), '3840') ++ for service in ['media', 'media2']: ++ status, root = request(service, 'GetVideoSourceConfigurations', config=config) ++ self.assertEqual(status, 200) ++ self.assertEqual(root.findtext('.//tt:UseCount', namespaces=NS), '12') ++ status, root = request(service, 'GetVideoEncoderConfigurationOptions', ++ 'Profile_11_VideoEncoderToken' ++ '', config) ++ self.assertEqual(status, 200) ++ self.assertEqual(root.findtext('.//tt:ResolutionsAvailable/tt:Width', ++ namespaces=NS), '160') ++ ++ def test_uri_percent_escape(self): ++ config = configuration() ++ config['profiles'][0]['url'] = 'rtsp://%s:8554/a%20b?n=1&x=2' ++ status, root = request('media', 'GetStreamUri', ++ 'Profile_0', config) ++ self.assertEqual(status, 200) ++ self.assertEqual(root.findtext('.//{*}Uri'), 'rtsp://127.0.0.1:8554/a%20b?n=1&x=2') ++ + def test_multiple_profiles(self): + for count in [0, 1, 2, 4, 12]: + config = configuration(count) diff --git a/multimedia/onvif-simple-server/patches/0007-fix-traverse-SOAP-request-elements-without-suffix-un.patch b/multimedia/onvif-simple-server/patches/0007-fix-traverse-SOAP-request-elements-without-suffix-un.patch new file mode 100644 index 0000000000..da819e7e86 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0007-fix-traverse-SOAP-request-elements-without-suffix-un.patch @@ -0,0 +1,627 @@ +From 8b9126c995558885a2ffd1e922bde12002a6a595 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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 . + */ + +-#include "string.h" ++#include + + #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 ) +- * @param skip_prefix 1 to skip the prefix of the element () +- * @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 "" +- if (strcmp(name, xml->name) == 0) { +- return xml->txt; +- } +- +- // Check if this node is "" +- 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[] = "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 "" +- if (strcmp(name, xml->name) == 0) { +- return xml; +- } +- +- // Check if this node is "" +- 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 "" +- if (strcmp(name, child->name) == 0) { +- return child->txt; +- } +- +- // Check if this node is "" +- 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 "" +- if (strcmp(name, pk->name) == 0) { +- return pk->txt; +- } +- +- // Check if this node is "" +- 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 "" +- if (strcmp(name, child->name) == 0) { +- return child; +- } +- +- // Check if this node is "" +- 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 "" +- if (strcmp(name, pk->name) == 0) { +- return pk; +- } +- +- // Check if this node is "" +- 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'' +@@ -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 ++#include ++#include ++ ++#include "ezxml_wrapper.h" ++ ++int main(void) ++{ ++ char request[] = "" ++ "" ++ "4243" ++ ""; ++ char malformed[] = ""; ++ 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; ++} diff --git a/multimedia/onvif-simple-server/patches/0008-feat-add-a-generic-external-control-helper-protocol.patch b/multimedia/onvif-simple-server/patches/0008-feat-add-a-generic-external-control-helper-protocol.patch new file mode 100644 index 0000000000..1a43c75c92 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0008-feat-add-a-generic-external-control-helper-protocol.patch @@ -0,0 +1,548 @@ +From e374d53671c85ec96e6c6f06d053cb99fad4447c Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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 ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#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 ++ ++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 ++#include ++ ++#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') diff --git a/multimedia/onvif-simple-server/patches/0009-feat-delegate-encoder-configuration-to-external-help.patch b/multimedia/onvif-simple-server/patches/0009-feat-delegate-encoder-configuration-to-external-help.patch new file mode 100644 index 0000000000..c9337a6311 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0009-feat-delegate-encoder-configuration-to-external-help.patch @@ -0,0 +1,855 @@ +From 135cec8b6b04670f0c533150d35eee0a267721bd Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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 ++#include ++#include ++#include ++ ++#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 ++#include + #include + + #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', 'All', 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', ++ 'Profile_3_VideoEncoderToken' ++ '', 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', ++ 'Profile_3_VideoEncoderToken' ++ '', 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', ++ '', config)[0], 500) + def test_operation_namespace(self): + status, root = request('media', 'GetProfiles', namespace='urn:unrelated') + self.assertEqual(status, 500) diff --git a/multimedia/onvif-simple-server/patches/0010-feat-expose-camera-imaging-through-optional-control-.patch b/multimedia/onvif-simple-server/patches/0010-feat-expose-camera-imaging-through-optional-control-.patch new file mode 100644 index 0000000000..8183c52ed2 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0010-feat-expose-camera-imaging-through-optional-control-.patch @@ -0,0 +1,1090 @@ +From b3028a5c57d958576a10858a3ad68df2bb21cf2a Mon Sep 17 00:00:00 2001 +From: Daniel Golle +Date: Sun, 18 Oct 2026 11:00:59 +0100 +Subject: [PATCH 10/15] feat: expose camera imaging through optional control + helpers + +Signed-off-by: Daniel Golle +--- + CONTROL_HELPERS.md | 29 +++ + Makefile | 2 +- + Makefile.static | 2 +- + device_advertisement.c | 164 +++++++++++++++++ + device_advertisement.h | 7 + + device_service.c | 398 +--------------------------------------- + imaging_service.c | 273 +++++++++++++++++++++++++++ + imaging_service.h | 7 + + onvif_simple_server.c | 4 + + soap.c | 2 +- + test/control_fixture.py | 8 +- + test/test_cgi.py | 50 +++++ + 12 files changed, 547 insertions(+), 399 deletions(-) + create mode 100644 device_advertisement.c + create mode 100644 device_advertisement.h + create mode 100644 imaging_service.c + create mode 100644 imaging_service.h + +--- a/CONTROL_HELPERS.md ++++ b/CONTROL_HELPERS.md +@@ -56,3 +56,32 @@ 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. ++ ++## Imaging operations ++ ++An `imaging_helper` enables the Imaging service at `/onvif/imaging_service` ++and advertises it through Device GetServices and GetCapabilities. Install a ++CGI wrapper selecting that service, as for the existing media endpoints. ++All operations receive `token: "VideoSourceToken"`, the sole camera source. ++ ++`get` returns `revision` and a `settings` object. `options` returns `revision` ++and an `options` object. Supported top-level keys, in either object, are ++`brightness`, `colour_saturation`, `contrast`, `exposure`, `sharpness` and ++`white_balance`. Omit controls the camera does not support. ++ ++Exposure contains `mode` and optional `min_exposure_time`, `max_exposure_time`, ++`min_gain`, `max_gain`, `min_iris`, `max_iris`, `exposure_time`, `gain`, `iris`. ++Exposure times are microseconds; gain and iris attenuation are dB. White ++balance contains `mode` and optional unitless `cr_gain` (red) and `cb_gain` ++(blue). Settings use a single `AUTO` or `MANUAL` mode and numeric values. ++Options use an array of supported modes and numeric `{min, max}` ranges. ++The adapter uses the ONVIF schema's `YrGain`/`YbGain` names for white-balance ++options, and `CrGain`/`CbGain` for settings. ++ ++`set` receives `settings`, a partial object of changes, and the caller's ++`force_persistence` boolean, false when omitted. Each exposure/white-balance ++object includes its mode. Apply the whole request as one transaction. Return ++`revision` and the effective `settings` after application. The helper must ++reject unsupported controls or values, honour persistence and preserve ++unchanged controls. Unknown XML controls are rejected rather than ignored. ++Focus, presets, IR-cut, WDR and exposure masks are outside this interface. +--- 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 = 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 = 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 = 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 = 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 +--- /dev/null ++++ b/device_advertisement.c +@@ -0,0 +1,164 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#include ++#include ++ ++#include "device_advertisement.h" ++#include "ezxml_wrapper.h" ++#include "fault.h" ++#include "onvif_simple_server.h" ++#include "soap.h" ++#include "utils.h" ++ ++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; ++ ezxml_t version; ++ ezxml_t capabilities; ++ ++ service = ezxml_add_child_d(response, "tds:Service", strlen(response->txt)); ++ soap_child_add(service, "tds:Namespace", "http://www.onvif.org/ver20/imaging/wsdl"); ++ soap_child_add(service, "tds:XAddr", address); ++ if (include) { ++ capabilities = soap_child_add(service, "tds:Capabilities", NULL); ++ soap_child_add(capabilities, "timg:Capabilities", NULL); ++ } ++ version = soap_child_add(service, "tds:Version", NULL); ++ soap_number_add(version, "tt:Major", 2); ++ soap_number_add(version, "tt:Minor", 0); ++} ++ ++static void imaging_capabilities_add(ezxml_t response, const char *address) ++{ ++ ezxml_t capabilities; ++ ezxml_t imaging; ++ ezxml_t media; ++ ++ capabilities = get_element_in_element_ptr("Capabilities", response); ++ media = get_element_in_element_ptr("Media", capabilities); ++ imaging = ezxml_add_child_d(capabilities, "tt:Imaging", ++ media && media->off ? media->off - 1 : 0); ++ soap_child_add(imaging, "tt:XAddr", address); ++} ++ ++int device_advertisement_send(int services) ++{ ++ char device[MAX_LEN], media[MAX_LEN], media2[MAX_LEN], ptz[MAX_LEN]; ++ char events[MAX_LEN], deviceio[MAX_LEN], imaging[MAX_LEN]; ++ char audio_sources[16], audio_outputs[16], relay_outputs[16]; ++ char filename[MAX_LEN]; ++ char port[8]; ++ const char *category; ++ const char *cap; ++ ezxml_t envelope; ++ ezxml_t response; ++ int audio_input; ++ int audio_output; ++ int include; ++ int i; ++ struct template_value values[] = { ++ { "%DEVICE_SERVICE_ADDRESS%", device }, ++ { "%MEDIA_SERVICE_ADDRESS%", media }, ++ { "%MEDIA2_SERVICE_ADDRESS%", media2 }, ++ { "%PTZ_SERVICE_ADDRESS%", ptz }, ++ { "%EVENTS_SERVICE_ADDRESS%", events }, ++ { "%DEVICEIO_SERVICE_ADDRESS%", deviceio }, ++ { "%EVENTS_BASESUBSCRIPTION%", "false" }, ++ { "%EVENTS_PULLPOINT%", "false" }, ++ { "%AUDIO_SOURCES%", audio_sources }, ++ { "%AUDIO_OUTPUTS%", audio_outputs }, ++ { "%RELAY_OUTPUTS%", relay_outputs }, ++ { NULL, NULL } ++ }; ++ ++ 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(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); ++ audio_input = 0; ++ audio_output = 0; ++ for (i = 0; i < service_ctx.profiles_num; i++) { ++ audio_input |= service_ctx.profiles[i].audio_encoder != AUDIO_NONE; ++ audio_output |= service_ctx.profiles[i].audio_decoder != AUDIO_NONE; ++ } ++ 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) ++ values[6].value = "true"; ++ if (service_ctx.events_enable == EVENTS_PULLPOINT || service_ctx.events_enable == EVENTS_BOTH) ++ values[7].value = "true"; ++ category = get_element("Category", "Body"); ++ cap = get_element("IncludeCapability", "Body"); ++ include = cap && (!strcmp(cap, "true") || !strcmp(cap, "1")); ++ if (services) ++ snprintf(filename, sizeof(filename), "device_service_files/GetServices_%s%s_%s.xml", ++ include ? "with_capabilities_" : "", ++ service_ctx.ptz_node.enable ? "ptz" : "no_ptz", ++ service_ctx.adv_enable_media2 ? "media2" : "no_media2"); ++ else if (!category || !strcmp(category, "All")) ++ snprintf(filename, sizeof(filename), "device_service_files/GetCapabilities_%s.xml", ++ service_ctx.ptz_node.enable ? "ptz" : "no_ptz"); ++ else if (!strcmp(category, "Imaging") && service_ctx.imaging_helper) { ++ envelope = ezxml_new("SOAP-ENV:Envelope"); ++ ezxml_set_attr(envelope, "xmlns:SOAP-ENV", "http://www.w3.org/2003/05/soap-envelope"); ++ ezxml_set_attr(envelope, "xmlns:tds", "http://www.onvif.org/ver10/device/wsdl"); ++ ezxml_set_attr(envelope, "xmlns:tt", "http://www.onvif.org/ver10/schema"); ++ response = soap_child_add(envelope, "SOAP-ENV:Body", NULL); ++ response = soap_child_add(response, "tds:GetCapabilitiesResponse", NULL); ++ soap_child_add(response, "tds:Capabilities", NULL); ++ imaging_capabilities_add(response, imaging); ++ return soap_response_send(response); ++ } 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); ++ } else { ++ return send_fault("device_service", "Receiver", "ter:ActionNotSupported", "ter:NoSuchService", ++ "No such service", "The requested service category is unavailable"); ++ } ++ envelope = ezxml_parse_file(filename); ++ if (!envelope || *ezxml_error(envelope)) { ++ ezxml_free(envelope); ++ return send_action_failed_fault("device_service", -1); ++ } ++ template_fill(envelope, values); ++ response = envelope->child->child; ++ if (service_ctx.imaging_helper) { ++ ezxml_set_attr(envelope, "xmlns:timg", "http://www.onvif.org/ver20/imaging/wsdl"); ++ if (services) ++ imaging_service_add(response, imaging, include); ++ else if (!category || !strcmp(category, "All")) ++ imaging_capabilities_add(response, imaging); ++ } ++ return soap_response_send(response); ++} +--- /dev/null ++++ b/device_advertisement.h +@@ -0,0 +1,7 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#ifndef DEVICE_ADVERTISEMENT_H ++#define DEVICE_ADVERTISEMENT_H ++ ++int device_advertisement_send(int services); ++ ++#endif +--- a/device_service.c ++++ b/device_service.c +@@ -23,6 +23,7 @@ + #include + + #include "device_service.h" ++#include "device_advertisement.h" + #include "fault.h" + #include "utils.h" + #include "log.h" +@@ -33,237 +34,7 @@ extern service_context_t service_ctx; + + int device_get_services() + { +- char device_service_address[MAX_LEN]; +- char media_service_address[MAX_LEN]; +- char media2_service_address[MAX_LEN]; +- char ptz_service_address[MAX_LEN]; +- char events_service_address[MAX_LEN]; +- char deviceio_service_address[MAX_LEN]; +- char port[8]; +- const char *cap; +- +- char ebasesubscription[8], epullpoint[8]; +- +- char audio_sources[2], audio_outputs[2], relay_outputs[2]; +- +- port[0] = '\0'; +- if (service_ctx.port != 80) +- snprintf(port, sizeof(port), ":%d", service_ctx.port); +- snprintf(device_service_address, sizeof(device_service_address), "http://%s%s/onvif/device_service", service_ctx.address_url, port); +- snprintf(media_service_address, sizeof(media_service_address), "http://%s%s/onvif/media_service", service_ctx.address_url, port); +- snprintf(media2_service_address, sizeof(media2_service_address), "http://%s%s/onvif/media2_service", service_ctx.address_url, port); +- snprintf(ptz_service_address, sizeof(ptz_service_address), "http://%s%s/onvif/ptz_service", service_ctx.address_url, port); +- snprintf(events_service_address, sizeof(events_service_address), "http://%s%s/onvif/events_service", service_ctx.address_url, port); +- snprintf(deviceio_service_address, sizeof(deviceio_service_address), "http://%s%s/onvif/deviceio_service", service_ctx.address_url, port); +- +- if ((service_ctx.events_enable == EVENTS_PULLPOINT) || (service_ctx.events_enable == EVENTS_BOTH)) { +- snprintf(epullpoint, sizeof(epullpoint), "%s", "true"); +- } else { +- snprintf(epullpoint, sizeof(epullpoint), "%s", "false"); +- } +- if ((service_ctx.events_enable == EVENTS_BASESUBSCRIPTION) || (service_ctx.events_enable == EVENTS_BOTH)) { +- snprintf(ebasesubscription, sizeof(ebasesubscription), "%s", "true"); +- } else { +- snprintf(ebasesubscription, sizeof(ebasesubscription), "%s", "false"); +- } +- +- if ((service_ctx.profiles[0].audio_encoder != AUDIO_NONE) || +- ((service_ctx.profiles_num == 2) && (service_ctx.profiles[1].audio_encoder != AUDIO_NONE))) { +- +- snprintf(audio_sources, sizeof(audio_sources), "%d", 1); +- } else { +- snprintf(audio_sources, sizeof(audio_sources), "%d", 0); +- } +- if ((service_ctx.profiles[0].audio_decoder != AUDIO_NONE) || +- ((service_ctx.profiles_num == 2) && (service_ctx.profiles[1].audio_decoder != AUDIO_NONE))) { +- +- snprintf(audio_outputs, sizeof(audio_outputs), "%d", 1); +- } else { +- snprintf(audio_outputs, sizeof(audio_outputs), "%d", 0); +- } +- +- snprintf(relay_outputs, sizeof(relay_outputs), "%d", service_ctx.relay_outputs_num); +- +- cap = get_element("IncludeCapability", "Body"); +- if ((cap != NULL) && (strcasecmp(cap, "true")) == 0) { +- if ((service_ctx.ptz_node.enable == 0) && (service_ctx.adv_enable_media2 == 0)) { +- long size = cat(NULL, "device_service_files/GetServices_with_capabilities_no_ptz_no_media2.xml", 18, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetServices_with_capabilities_no_ptz_no_media2.xml", 18, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- +- } else if ((service_ctx.ptz_node.enable == 0) && (service_ctx.adv_enable_media2 == 1)) { +- long size = cat(NULL, "device_service_files/GetServices_with_capabilities_no_ptz_media2.xml", 20, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%MEDIA2_SERVICE_ADDRESS%", media2_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetServices_with_capabilities_no_ptz_media2.xml", 20, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%MEDIA2_SERVICE_ADDRESS%", media2_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- +- } else if ((service_ctx.ptz_node.enable == 1) && (service_ctx.adv_enable_media2 == 0)) { +- long size = cat(NULL, "device_service_files/GetServices_with_capabilities_ptz_no_media2.xml", 20, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetServices_with_capabilities_ptz_no_media2.xml", 20, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- +- } else if ((service_ctx.ptz_node.enable == 1) && (service_ctx.adv_enable_media2 == 1)) { +- long size = cat(NULL, "device_service_files/GetServices_with_capabilities_ptz_media2.xml", 22, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%MEDIA2_SERVICE_ADDRESS%", media2_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetServices_with_capabilities_ptz_media2.xml", 22, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%MEDIA2_SERVICE_ADDRESS%", media2_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- } +- } else { +- if ((service_ctx.ptz_node.enable == 0) && (service_ctx.adv_enable_media2 == 0)) { +- long size = cat(NULL, "device_service_files/GetServices_no_ptz_no_media2.xml", 8, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetServices_no_ptz_no_media2.xml", 8, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address); +- +- } else if ((service_ctx.ptz_node.enable == 0) && (service_ctx.adv_enable_media2 == 1)) { +- long size = cat(NULL, "device_service_files/GetServices_no_ptz_media2.xml", 10, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%MEDIA2_SERVICE_ADDRESS%", media2_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetServices_no_ptz_media2.xml", 10, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%MEDIA2_SERVICE_ADDRESS%", media2_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address); +- +- } else if ((service_ctx.ptz_node.enable == 1) && (service_ctx.adv_enable_media2 == 0)) { +- long size = cat(NULL, "device_service_files/GetServices_ptz_no_media2.xml", 10, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetServices_ptz_no_media2.xml", 10, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address); +- +- } else if ((service_ctx.ptz_node.enable == 1) && (service_ctx.adv_enable_media2 == 1)) { +- long size = cat(NULL, "device_service_files/GetServices_ptz_media2.xml", 12, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%MEDIA2_SERVICE_ADDRESS%", media2_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetServices_ptz_media2.xml", 12, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%MEDIA2_SERVICE_ADDRESS%", media2_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address); +- } +- } ++ return device_advertisement_send(1); + } + + int device_get_service_capabilities() +@@ -478,170 +249,7 @@ int device_get_wsdl_url() + + int device_get_capabilities() + { +- char device_service_address[MAX_LEN]; +- char media_service_address[MAX_LEN]; +- char ptz_service_address[MAX_LEN]; +- char events_service_address[MAX_LEN]; +- char deviceio_service_address[MAX_LEN]; +- char port[8]; +- int icategory; +- const char *category; +- +- char ebasesubscription[8], epullpoint[8]; +- +- char audio_sources[2], audio_outputs[2], relay_outputs[2]; +- +- category = get_element("Category", "Body"); +- if (category != NULL) { +- if (strcasecmp(category, "Device") == 0) { +- icategory = 1; +- } else if (strcasecmp(category, "Media") == 0) { +- icategory = 2; +- } else if (strcasecmp(category, "PTZ") == 0) { +- icategory = 4; +- } else if (strcasecmp(category, "Events") == 0) { +- icategory = 8; +- } else if (strcasecmp(category, "All") == 0) { +- icategory = 15; +- } else { +- send_fault("device_service", "Receiver", "ter:ActionNotSupported", "ter:NoSuchService", "No such service", "The requested WSDL service category is not supported by the device"); +- return -2; +- } +- } else { +- icategory = 15; +- } +- +- port[0] = '\0'; +- if (service_ctx.port != 80) +- snprintf(port, sizeof(port), ":%d", service_ctx.port); +- snprintf(device_service_address, sizeof(device_service_address), "http://%s%s/onvif/device_service", service_ctx.address_url, port); +- snprintf(media_service_address, sizeof(media_service_address), "http://%s%s/onvif/media_service", service_ctx.address_url, port); +- snprintf(ptz_service_address, sizeof(ptz_service_address), "http://%s%s/onvif/ptz_service", service_ctx.address_url, port); +- snprintf(events_service_address, sizeof(events_service_address), "http://%s%s/onvif/events_service", service_ctx.address_url, port); +- snprintf(deviceio_service_address, sizeof(deviceio_service_address), "http://%s%s/onvif/deviceio_service", service_ctx.address_url, port); +- +- if ((service_ctx.events_enable == EVENTS_PULLPOINT) || (service_ctx.events_enable == EVENTS_BOTH)) { +- snprintf(epullpoint, sizeof(epullpoint), "%s", "true"); +- } else { +- snprintf(epullpoint, sizeof(epullpoint), "%s", "false"); +- } +- if ((service_ctx.events_enable == EVENTS_BASESUBSCRIPTION) || (service_ctx.events_enable == EVENTS_BOTH)) { +- snprintf(ebasesubscription, sizeof(ebasesubscription), "%s", "true"); +- } else { +- snprintf(ebasesubscription, sizeof(ebasesubscription), "%s", "false"); +- } +- +- if ((service_ctx.profiles[0].audio_encoder != AUDIO_NONE) || +- ((service_ctx.profiles_num == 2) && (service_ctx.profiles[1].audio_encoder != AUDIO_NONE))) { +- +- snprintf(audio_sources, sizeof(audio_sources), "%d", 1); +- } else { +- snprintf(audio_sources, sizeof(audio_sources), "%d", 0); +- } +- if ((service_ctx.profiles[0].audio_decoder != AUDIO_NONE) || +- ((service_ctx.profiles_num == 2) && (service_ctx.profiles[1].audio_decoder != AUDIO_NONE))) { +- +- snprintf(audio_outputs, sizeof(audio_outputs), "%d", 1); +- } else { +- snprintf(audio_outputs, sizeof(audio_outputs), "%d", 0); +- } +- +- snprintf(relay_outputs, sizeof(relay_outputs), "%d", service_ctx.relay_outputs_num); +- +- if (icategory == 1) { +- long size = cat(NULL, "device_service_files/GetDeviceCapabilities.xml", 2, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetDeviceCapabilities.xml", 2, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address); +- } else if (icategory == 2) { +- long size = cat(NULL, "device_service_files/GetMediaCapabilities.xml", 2, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetMediaCapabilities.xml", 2, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address); +- } else if (icategory == 4) { +- if (service_ctx.ptz_node.enable == 1) { +- long size = cat(NULL, "device_service_files/GetPTZCapabilities.xml", 2, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetPTZCapabilities.xml", 2, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address); +- } else { +- send_fault("device_service", "Receiver", "ter:ActionNotSupported", "ter:NoSuchService", "No such service", "The requested WSDL service category is not supported by the device"); +- return -3; +- } +- } else if (icategory == 8) { +- long size = cat(NULL, "device_service_files/GetEventsCapabilities.xml", 6, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetEventsCapabilities.xml", 6, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint); +- } else { +- if (service_ctx.ptz_node.enable == 0) { +- long size = cat(NULL, "device_service_files/GetCapabilities_no_ptz.xml", 18, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetCapabilities_no_ptz.xml", 18, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- } else { +- long size = cat(NULL, "device_service_files/GetCapabilities_ptz.xml", 20, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- +- output_http_headers(size); +- +- return cat("stdout", "device_service_files/GetCapabilities_ptz.xml", 20, +- "%DEVICE_SERVICE_ADDRESS%", device_service_address, +- "%MEDIA_SERVICE_ADDRESS%", media_service_address, +- "%PTZ_SERVICE_ADDRESS%", ptz_service_address, +- "%EVENTS_SERVICE_ADDRESS%", events_service_address, +- "%EVENTS_BASESUBSCRIPTION%", ebasesubscription, +- "%EVENTS_PULLPOINT%", epullpoint, +- "%DEVICEIO_SERVICE_ADDRESS%", deviceio_service_address, +- "%AUDIO_SOURCES%", audio_sources, +- "%AUDIO_OUTPUTS%", audio_outputs, +- "%RELAY_OUTPUTS%", relay_outputs); +- } +- } ++ return device_advertisement_send(0); + } + + int device_get_network_interfaces() +--- /dev/null ++++ b/imaging_service.c +@@ -0,0 +1,273 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#include ++#include ++#include ++#include ++ ++#include "control_helper.h" ++#include "ezxml_wrapper.h" ++#include "fault.h" ++#include "imaging_service.h" ++#include "onvif_simple_server.h" ++#include "soap.h" ++ ++extern service_context_t service_ctx; ++ ++struct imaging_field { ++ const char *key; ++ const char *name; ++ const struct imaging_field *children; ++}; ++ ++static const struct imaging_field exposure_fields[] = { ++ { "mode", "Mode", NULL }, ++ { "min_exposure_time", "MinExposureTime", NULL }, ++ { "max_exposure_time", "MaxExposureTime", NULL }, ++ { "min_gain", "MinGain", NULL }, ++ { "max_gain", "MaxGain", NULL }, ++ { "min_iris", "MinIris", NULL }, ++ { "max_iris", "MaxIris", NULL }, ++ { "exposure_time", "ExposureTime", NULL }, ++ { "gain", "Gain", NULL }, ++ { "iris", "Iris", NULL }, ++ { NULL, NULL, NULL } ++}; ++ ++static const struct imaging_field white_balance_fields[] = { ++ { "mode", "Mode", NULL }, ++ { "cr_gain", "CrGain", NULL }, ++ { "cb_gain", "CbGain", NULL }, ++ { NULL, NULL, NULL } ++}; ++ ++static const struct imaging_field imaging_fields[] = { ++ { "brightness", "Brightness", NULL }, ++ { "colour_saturation", "ColorSaturation", NULL }, ++ { "contrast", "Contrast", NULL }, ++ { "exposure", "Exposure", exposure_fields }, ++ { "sharpness", "Sharpness", NULL }, ++ { "white_balance", "WhiteBalance", white_balance_fields }, ++ { NULL, NULL, NULL } ++}; ++ ++static int number_read(json_object *value, double *number) ++{ ++ if (!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) && fabs(*number) <= FLT_MAX ? 0 : -1; ++} ++ ++static int mode_add(ezxml_t parent, json_object *value, int options) ++{ ++ json_object *entry; ++ const char *mode; ++ size_t count; ++ size_t i; ++ ++ if (options && !json_object_is_type(value, json_type_array)) ++ return -1; ++ count = options ? json_object_array_length(value) : 1; ++ if (!count || count > 2) ++ return -1; ++ for (i = 0; i < count; i++) { ++ entry = options ? json_object_array_get_idx(value, i) : value; ++ if (!json_object_is_type(entry, json_type_string)) ++ return -1; ++ mode = json_object_get_string(entry); ++ if (strcmp(mode, "AUTO") && strcmp(mode, "MANUAL")) ++ return -1; ++ soap_child_add(parent, "tt:Mode", mode); ++ } ++ return 0; ++} ++ ++static int numeric_add(ezxml_t parent, const char *name, json_object *value, int options) ++{ ++ json_object *minimum_value; ++ json_object *maximum_value; ++ double minimum; ++ double maximum; ++ ++ if (!options) { ++ if (number_read(value, &minimum)) ++ return -1; ++ soap_number_add(parent, name, minimum); ++ return 0; ++ } ++ if (!json_object_is_type(value, json_type_object) || ++ !json_object_object_get_ex(value, "min", &minimum_value) || ++ !json_object_object_get_ex(value, "max", &maximum_value) || ++ number_read(minimum_value, &minimum) || number_read(maximum_value, &maximum) || ++ maximum < minimum) ++ return -1; ++ soap_range_add(parent, name, minimum, maximum); ++ return 0; ++} ++ ++static int fields_add(ezxml_t parent, json_object *object, ++ const struct imaging_field *fields, int options) ++{ ++ const struct imaging_field *field; ++ json_object *value; ++ char name[64]; ++ int found; ++ ++ if (!json_object_is_type(object, json_type_object)) ++ return -1; ++ found = 0; ++ for (field = fields; field->key; field++) { ++ if (!json_object_object_get_ex(object, field->key, &value)) ++ continue; ++ found++; ++ snprintf(name, sizeof(name), "tt:%s", field->name); ++ if (options && fields == white_balance_fields && !strcmp(field->key, "cr_gain")) ++ snprintf(name, sizeof(name), "tt:YrGain"); ++ if (options && fields == white_balance_fields && !strcmp(field->key, "cb_gain")) ++ snprintf(name, sizeof(name), "tt:YbGain"); ++ if (field->children) { ++ if (fields_add(soap_child_add(parent, name, NULL), value, field->children, options)) ++ return -1; ++ } else if (!strcmp(field->key, "mode")) { ++ if (mode_add(parent, value, options)) ++ return -1; ++ } else if (numeric_add(parent, name, value, options)) { ++ return -1; ++ } ++ } ++ if (found != json_object_object_length(object)) ++ return -1; ++ if (fields != imaging_fields && !json_object_object_get_ex(object, "mode", &value)) ++ return -1; ++ return 0; ++} ++ ++static json_object *fields_parse(ezxml_t node, const struct imaging_field *fields) ++{ ++ const struct imaging_field *field; ++ const char *namespace; ++ const char *name; ++ json_object *object; ++ json_object *value; ++ ezxml_t child; ++ char *end; ++ double number; ++ ++ if (!node) ++ return NULL; ++ object = json_object_new_object(); ++ for (child = node->child; child; child = child->ordered) { ++ namespace = xml_namespace_get(child); ++ if (!namespace || strcmp(namespace, "http://www.onvif.org/ver10/schema")) ++ goto invalid; ++ name = strchr(child->name, ':'); ++ name = name ? name + 1 : child->name; ++ for (field = fields; field->key && strcmp(field->name, name); field++) ++ ; ++ if (!field->key || json_object_object_get_ex(object, field->key, &value)) ++ goto invalid; ++ if (field->children) ++ value = fields_parse(child, field->children); ++ else if (!strcmp(field->key, "mode")) ++ value = json_object_new_string(child->txt); ++ else { ++ number = strtod(child->txt, &end); ++ if (!*child->txt || *end || !isfinite(number)) ++ goto invalid; ++ value = json_object_new_double(number); ++ } ++ if (!value) ++ goto invalid; ++ json_object_object_add(object, field->key, value); ++ } ++ return object; ++invalid: ++ json_object_put(object); ++ return NULL; ++} ++ ++static enum helper_status imaging_call(const char *operation, json_object **reply) ++{ ++ enum helper_status status; ++ const char *persistence; ++ json_object *request; ++ json_object *settings; ++ ezxml_t validation; ++ ++ request = json_object_new_object(); ++ json_object_object_add(request, "token", json_object_new_string("VideoSourceToken")); ++ if (!strcmp(operation, "set")) { ++ settings = fields_parse(get_element_ptr(NULL, "ImagingSettings", "Body"), imaging_fields); ++ validation = ezxml_new("settings"); ++ if (!settings || !json_object_object_length(settings) || ++ fields_add(validation, settings, imaging_fields, 0)) { ++ json_object_put(settings); ++ json_object_put(request); ++ ezxml_free(validation); ++ return HELPER_INVALID; ++ } ++ ezxml_free(validation); ++ json_object_object_add(request, "settings", settings); ++ 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( ++ persistence && (!strcmp(persistence, "true") || !strcmp(persistence, "1")))); ++ } ++ status = helper_call(service_ctx.imaging_helper, operation, request, reply); ++ json_object_put(request); ++ return status; ++} ++ ++int imaging_dispatch(const char *operation) ++{ ++ enum helper_status status; ++ const char *token; ++ const char *action; ++ json_object *reply; ++ json_object *value; ++ ezxml_t response; ++ ezxml_t member; ++ int options; ++ int setter; ++ ++ if (!service_ctx.imaging_helper) ++ return send_action_not_supported_fault("imaging_service"); ++ if (!strcmp(operation, "GetServiceCapabilities")) { ++ response = soap_response_create(3, operation); ++ soap_member_add(response, 3, "Capabilities"); ++ return soap_response_send(response); ++ } ++ options = !strcmp(operation, "GetOptions"); ++ setter = !strcmp(operation, "SetImagingSettings"); ++ if (!options && !setter && strcmp(operation, "GetImagingSettings")) ++ return send_action_not_supported_fault("imaging_service"); ++ token = get_element("VideoSourceToken", "Body"); ++ if (!token || strcmp(token, "VideoSourceToken")) ++ return send_fault("imaging_service", "Sender", "ter:InvalidArgVal", "ter:NoSource", ++ "Unknown source", "The requested video source does not exist"); ++ action = options ? "options" : setter ? "set" : "get"; ++ status = imaging_call(action, &reply); ++ if (status != HELPER_OK) ++ return helper_fault("imaging_service", status); ++ response = soap_response_create(3, operation); ++ member = setter ? ezxml_new("settings") : soap_member_add(response, 3, ++ options ? "ImagingOptions" : "ImagingSettings"); ++ status = HELPER_FAILED; ++ if (json_object_object_get_ex(reply, "revision", &value) && ++ json_object_is_type(value, json_type_string) && *json_object_get_string(value) && ++ json_object_object_get_ex(reply, options ? "options" : "settings", &value) && ++ !fields_add(member, value, imaging_fields, options)) ++ status = HELPER_OK; ++ json_object_put(reply); ++ if (setter) ++ ezxml_free(member); ++ if (status == HELPER_OK) ++ return soap_response_send(response); ++ ezxml_free(response->parent->parent); ++ return helper_fault("imaging_service", status); ++} +--- /dev/null ++++ b/imaging_service.h +@@ -0,0 +1,7 @@ ++/* SPDX-License-Identifier: GPL-3.0-only */ ++#ifndef IMAGING_SERVICE_H ++#define IMAGING_SERVICE_H ++ ++int imaging_dispatch(const char *operation); ++ ++#endif +--- a/onvif_simple_server.c ++++ b/onvif_simple_server.c +@@ -29,6 +29,7 @@ + #include "device_service.h" + #include "media_service.h" + #include "encoder_control.h" ++#include "imaging_service.h" + #include "media_profiles.h" + #include "media_options.h" + #include "media2_service.h" +@@ -297,6 +298,7 @@ int main(int argc, char ** argv) + if ((strstr(tmp, "device_service") != NULL) || + (strstr(tmp, "media_service") != NULL) || + (strstr(tmp, "media2_service") != NULL) || ++ (strstr(tmp, "imaging_service") != NULL) || + (strstr(tmp, "ptz_service") != NULL) || + (strstr(tmp, "events_service") != NULL) || + (strstr(tmp, "deviceio_service") != NULL)) { +@@ -636,6 +638,8 @@ int main(int argc, char ** argv) + media_unsupported(method); + } + } ++ } else if (strcasecmp("imaging_service", prog_name) == 0) { ++ imaging_dispatch(method); + } else if ((service_ctx.adv_enable_media2 == 1) && (strcasecmp("media2_service", prog_name) == 0)) { + if (encoder_control_dispatch(method, 2)) + goto response_done; +--- a/soap.c ++++ b/soap.c +@@ -28,7 +28,7 @@ ezxml_t soap_member_add(ezxml_t parent, + char qualified[MAX_LEN]; + + snprintf(qualified, sizeof(qualified), "%s:%s", +- version == 1 ? "trt" : "tr2", name); ++ version == 1 ? "trt" : version == 2 ? "tr2" : "timg", name); + return soap_child_add(parent, qualified, NULL); + } + +--- a/test/control_fixture.py ++++ b/test/control_fixture.py +@@ -14,16 +14,22 @@ status = state.get('status', 'ok') + result = {'revision': state.get('revision', 'test-revision')} + if operation == 'get': + result['profiles'] = state.get('profiles', []) ++ if 'settings' in state: ++ result['settings'] = state['settings'] + elif operation == 'options': + result['options'] = state.get('options', []) + elif operation == 'set': + state['last_set'] = data +- configuration = data['configuration'] ++ configuration = data.get('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 'settings' in data: ++ state['settings'].update(data['settings']) ++ path.write_text(json.dumps(state)) ++ result['settings'] = state['settings'] + 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 +@@ -79,6 +79,56 @@ def helper_configuration(): + + + class CGITests(unittest.TestCase): ++ def test_imaging(self): ++ with helper_configuration() as (config, path): ++ config['imaging_helper'] = config.pop('encoder_helper') ++ state = {'settings': {'brightness': 40, 'colour_saturation': 30, ++ 'exposure': {'mode': 'AUTO', 'gain': 12}, ++ 'white_balance': {'mode': 'AUTO'}}, ++ 'options': {'brightness': {'min': 0, 'max': 100}, ++ 'exposure': {'mode': ['AUTO', 'MANUAL'], ++ 'exposure_time': {'min': 50, 'max': 30000}, ++ 'gain': {'min': 0, 'max': 48}}, ++ 'white_balance': {'mode': ['AUTO', 'MANUAL'], ++ 'cr_gain': {'min': 0.1, 'max': 4}, ++ 'cb_gain': {'min': 0.1, 'max': 4}}}} ++ path.write_text(json.dumps(state)) ++ source = 'VideoSourceToken' ++ status, root = request('imaging', 'GetOptions', source, config) ++ self.assertEqual(status, 200) ++ self.assertEqual(root.findtext('.//tt:WhiteBalance/tt:YrGain/tt:Max', namespaces=NS), '4') ++ status, root = request('imaging', 'GetImagingSettings', source, config) ++ self.assertEqual(status, 200) ++ self.assertEqual(root.findtext('.//tt:Exposure/tt:Mode', namespaces=NS), 'AUTO') ++ settings = ('MANUAL' ++ '100006' ++ 'MANUAL' ++ '1.21.5' ++ '') ++ status, root = request('imaging', 'SetImagingSettings', source + settings + ++ 'false', config) ++ self.assertEqual(status, 200) ++ applied = json.loads(path.read_text()) ++ self.assertFalse(applied['last_set']['force_persistence']) ++ self.assertEqual(applied['settings']['exposure']['exposure_time'], 10000) ++ status, root = request('imaging', 'GetImagingSettings', source, config) ++ self.assertEqual(root.findtext('.//tt:WhiteBalance/tt:CrGain', namespaces=NS), '1.2') ++ for settings in ['BAD', ++ '2', ++ 'NaN', ++ '1']: ++ status, root = request('imaging', 'SetImagingSettings', source + ++ f'{settings}', config) ++ self.assertEqual(status, 500) ++ self.assertEqual(request('imaging', 'GetOptions', ++ 'missing', config)[0], 500) ++ for operation in ['GetServices', 'GetCapabilities']: ++ status, root = request('device', operation, config=config) ++ self.assertEqual(status, 200) ++ self.assertIn('http://127.0.0.1:8080/onvif/imaging_service', ++ [n.text for n in root.findall('.//{*}XAddr')]) ++ self.assertEqual(request('imaging', 'GetImagingSettings', source)[0], 500) ++ + def test_encoder_helper_get_options_set(self): + with helper_configuration() as (config, path): + for service in ['media', 'media2']: diff --git a/multimedia/onvif-simple-server/patches/0011-fix-report-capabilities-for-every-configured-video-p.patch b/multimedia/onvif-simple-server/patches/0011-fix-report-capabilities-for-every-configured-video-p.patch new file mode 100644 index 0000000000..7330761a8b --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0011-fix-report-capabilities-for-every-configured-video-p.patch @@ -0,0 +1,567 @@ +From c4a92068a398c4e8dd8890d8db9b79b74cbe255e Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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 ++#include ++ ++#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 ++#include + #include + + #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', 'true', 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', ++ 'VideoSourceConfigToken', 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', 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') diff --git a/multimedia/onvif-simple-server/patches/0012-test-validate-media-and-imaging-responses-through-sc.patch b/multimedia/onvif-simple-server/patches/0012-test-validate-media-and-imaging-responses-through-sc.patch new file mode 100644 index 0000000000..a53385c845 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0012-test-validate-media-and-imaging-responses-through-sc.patch @@ -0,0 +1,285 @@ +From 6ff93ddc47d711af945fa8d8da4f1e69bb15fc75 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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'' ++ f'All' ++ f'') ++ 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', 'All'), ++ ('GetVideoEncoderConfigurations', ''), ++ ('GetVideoEncoderConfigurationOptions', ''), ++ ('GetVideoSourceConfigurations', ''), ++ ('GetVideoSourceConfigurationOptions', ''), ++ ('GetServiceCapabilities', ''), ++ ('GetStreamUri', 'Profile_0'), ++ ('GetSnapshotUri', 'Profile_0')]: ++ with self.subTest(service=service, operation=operation): ++ self.validate(service, operation, content, config) ++ self.validate('media', 'GetVideoSources', config=config) ++ self.validate('media2', 'GetVideoSourceModes', ++ 'VideoSourceToken', config) ++ ++ def test_encoder_helper(self): ++ with helper_configuration() as (config, path): ++ for service in ['media', 'media2']: ++ self.validate(service, 'GetProfiles', 'All', 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' ++ self.validate('imaging', 'GetImagingSettings', source, config) ++ self.validate('imaging', 'GetOptions', source, config) ++ self.validate('imaging', 'GetServiceCapabilities', config=config) ++ ++ ++if __name__ == '__main__': ++ unittest.main() diff --git a/multimedia/onvif-simple-server/patches/0013-fix-validate-generated-media-responses-and-missing-U.patch b/multimedia/onvif-simple-server/patches/0013-fix-validate-generated-media-responses-and-missing-U.patch new file mode 100644 index 0000000000..f54dd53d28 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0013-fix-validate-generated-media-responses-and-missing-U.patch @@ -0,0 +1,187 @@ +From e645356997a6fb327522cb4f47708ef94bd04bda Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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 ++#include + #include + + #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', + '', 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, ++ 'Profile_3_VideoEncoderToken', 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', ++ 'Profile_0')[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', 'All', 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', 'All', config) ++ + def test_imaging_helper(self): + with helper_configuration() as (config, path): + config['imaging_helper'] = config.pop('encoder_helper') diff --git a/multimedia/onvif-simple-server/patches/0014-fix-load-compressed-templates-for-generated-capabili.patch b/multimedia/onvif-simple-server/patches/0014-fix-load-compressed-templates-for-generated-capabili.patch new file mode 100644 index 0000000000..81de1040a3 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0014-fix-load-compressed-templates-for-generated-capabili.patch @@ -0,0 +1,202 @@ +From 50e936982397939701fe7a5422729aa6793662c2 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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', 'true'), ++ ('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); diff --git a/multimedia/onvif-simple-server/patches/0015-fix-validate-encoder-changes-before-invoking-control.patch b/multimedia/onvif-simple-server/patches/0015-fix-validate-encoder-changes-before-invoking-control.patch new file mode 100644 index 0000000000..38b56a7d53 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0015-fix-validate-encoder-changes-before-invoking-control.patch @@ -0,0 +1,443 @@ +From 973144da3b43ce26330899a58f22050c76009802 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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 + #include + #include ++#include + + #include + #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 ++#include + #include + #include + #include +@@ -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', + 'Profile_0')[0], 500) ++ ++ def test_encoder_rejects_unsupported_changes(self): ++ with helper_configuration() as (config, path): ++ status, root = request('media2', 'GetVideoEncoderConfigurations', ++ 'Profile_0_VideoEncoderToken', 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_0false', 'AutoStart>true'), ++ original.replace('', '')]: ++ 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) diff --git a/multimedia/onvif-simple-server/patches/0016-fix-use-the-CGI-connection-address-in-service-URLs.patch b/multimedia/onvif-simple-server/patches/0016-fix-use-the-CGI-connection-address-in-service-URLs.patch new file mode 100644 index 0000000000..ec0912cc5b --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0016-fix-use-the-CGI-connection-address-in-service-URLs.patch @@ -0,0 +1,250 @@ +From 06d96723d0a5aaf8a36daa4576670e347d94e4f5 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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 + #include + #include ++#include + + #include + #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', ++ 'Profile_0', ++ 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='All'): + body = (f'' +- f'All' ++ f'{content}' + f'') +- 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, ++ 'Profile_0') ++ self.assertEqual(status, 200) ++ self.assertEqual(root.findtext('.//{*}Uri'), f'rtsp://{host}:8554/camera/0') ++ + + if __name__ == '__main__': + unittest.main() diff --git a/multimedia/onvif-simple-server/patches/0017-feat-configure-a-shared-device-UUID-for-CGI-and-disc.patch b/multimedia/onvif-simple-server/patches/0017-feat-configure-a-shared-device-UUID-for-CGI-and-disc.patch new file mode 100644 index 0000000000..92cc7f8b00 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0017-feat-configure-a-shared-device-UUID-for-CGI-and-disc.patch @@ -0,0 +1,314 @@ +From 60adcc31208a3eb29d2b7c6346b1908aa4f10bbd Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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) { diff --git a/multimedia/onvif-simple-server/patches/0018-feat-discover-on-all-suitable-network-interfaces.patch b/multimedia/onvif-simple-server/patches/0018-feat-discover-on-all-suitable-network-interfaces.patch new file mode 100644 index 0000000000..0c0edb59c6 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0018-feat-discover-on-all-suitable-network-interfaces.patch @@ -0,0 +1,1458 @@ +From 1c8c946367f85387610ed9e0a9fb08f760d31566 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +Date: Sun, 18 Oct 2026 17:24:53 +0100 +Subject: [PATCH 18/19] feat: discover on all suitable network interfaces + +Join discovery groups on active multicast-capable interfaces and send +announcements from each usable IPv4 and IPv6 address. Track Linux link +and address notifications to maintain memberships after network changes. +Use packet metadata for probe replies so the selected interface and +advertised address match the path through which the device was reached. + +Signed-off-by: Daniel Golle +--- + Makefile | 8 +- + Makefile.static | 2 +- + README.md | 27 +- + discovery_net.c | 495 +++++++++++++++++++++++++++++++++++ + discovery_net.h | 36 +++ + test/README.md | 5 + + test/test_discovery.py | 89 +++++++ + test/test_discovery_netns.py | 94 +++++++ + wsd_simple_server.c | 469 ++++++++++----------------------- + 9 files changed, 875 insertions(+), 350 deletions(-) + create mode 100644 discovery_net.c + create mode 100644 discovery_net.h + create mode 100644 test/test_discovery.py + create mode 100644 test/test_discovery_netns.py + +--- a/Makefile ++++ b/Makefile +@@ -3,7 +3,7 @@ + + 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 ++OBJECTS_W = wsd_simple_server.o discovery_net.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o + ifdef HAVE_WOLFSSL + INCLUDE = -DHAVE_WOLFSSL -ffunction-sections -fdata-sections + LIBS_O = -Wl,--gc-sections -lwolfssl -lz -ljson-c -lpthread -lrt +@@ -53,7 +53,11 @@ wsd_simple_server: $(OBJECTS_W) + $(CC) $(OBJECTS_W) $(LIBS_W) -fPIC -Os -o $@ + $(STRIP) $@ + +-.PHONY: all clean test test-cgi ++.PHONY: all clean test test-cgi test-discovery ++ ++test-discovery: wsd_simple_server ++ python3 test/test_discovery.py ++ unshare -Urn python3 test/test_discovery_netns.py + + test-cgi: onvif_simple_server + python3 test/test_cgi.py +--- a/Makefile.static ++++ b/Makefile.static +@@ -3,7 +3,7 @@ + + 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 ++OBJECTS_W = wsd_simple_server.o discovery_net.o utils.o log.o ezxml_wrapper.o ezxml/ezxml.o + ifdef HAVE_WOLFSSL + INCLUDE = -DHAVE_WOLFSSL -Iextras/wolfssl -Iextras/zlib -Iextras/json-c/build/_install/include -Iextras -ffunction-sections -fdata-sections -lrt + LIBS_O = -Wl,--gc-sections extras/wolfssl/src/.libs/libwolfssl.a extras/zlib/libz.a extras/json-c/build/libjson-c.a -lpthread -lrt +--- a/README.md ++++ b/README.md +@@ -323,7 +323,7 @@ each device instance. Omitting it retain + 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) ++ network interface restriction (default: all suitable interfaces) + -x, --xaddr + resource address template (use %s as placeholder for the detected IP; + IPv6 is auto-detected and the address is bracketed automatically) +@@ -346,7 +346,7 @@ Usage: /tmp/sd/yi-hack/bin/wsd_simple_se + ``` + | Option | Description | Example | + | --- | --- | --- | +-| if_name | network interface (optional; auto-detected if omitted) | eth0 | ++| if_name | optional restriction to one kernel network interface | eth0 | + | xaddr | resource address for the ONVIF server | http://%s/onvif/device_service | + | pid_file | is the pid file created by the daemon | /var/run/wsd_simple_server.pid | + | template_dir | the folder containing template files | /etc/wsd_simple_server | +@@ -357,18 +357,17 @@ Usage: /tmp/sd/yi-hack/bin/wsd_simple_se + + #### IPv6 / dual-stack WS-Discovery + +-IPv6 is auto-detected. +- +-- Uses a single `AF_INET6` dual-stack UDP socket (`IPV6_V6ONLY=0`) bound to `:::3702` +-- Joins the IPv4 WSD multicast group `239.255.255.250:3702` via `MCAST_JOIN_GROUP` (RFC 3678) +-- Joins the IPv6 WSD multicast group `FF02::C:3702` (WS-Discovery 1.1) +-- Each incoming Probe is dispatched by address family: IPv4-mapped senders (`::ffff:x.x.x.x`) get the IPv4 xaddr; native IPv6 senders get the IPv6 xaddr6 +- +-IPv6 is gracefully degraded: if the IPv6 multicast join fails, the server continues in IPv4-only mode. +- +-Auto-detection for IPv6 scans interfaces via `getifaddrs`, preferring a global unicast address over link-local. The routing-table connect trick used for IPv4 does not work here: Linux requires `sin6_scope_id != 0` for link-local multicast destinations such as `FF02::C`. On multi-homed systems use `-i`. +- +-Note: `onvif_simple_server` IPv6 advertising is tracked separately. ++Discovery joins the IPv4 and IPv6 multicast groups on every active, ++multicast-capable interface, excluding loopback. Each usable address sends ++an announcement with the shared device UUID. Linux routing notifications ++update memberships and announce newly usable addresses, including addresses ++that complete IPv6 duplicate-address detection after startup. ++ ++Probe replies use packet metadata to select the receiving interface and ++local address. Unicast probes retain their destination address; multicast ++probes use a local address on the receiving interface. IPv6 addresses in ++service URLs are bracketed. CGI service URLs use the HTTP connection's ++`SERVER_ADDR`, supplied by the web server. + + ### onvif_notify_server + onvif_notify_server checks the files related to the events and sends the notify message when an event is fired. +--- /dev/null ++++ b/discovery_net.c +@@ -0,0 +1,495 @@ ++#define _GNU_SOURCE ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include "discovery_net.h" ++ ++#define DISCOVERY_PORT 3702 ++#define DISCOVERY_IPV4 "239.255.255.250" ++#define DISCOVERY_IPV6 "ff02::c" ++ ++struct discovery_network { ++ struct discovery_address *addresses; ++ char *interface; ++ int ipv4; ++ int ipv6; ++ int events; ++}; ++ ++static void addresses_free(struct discovery_address *address) ++{ ++ struct discovery_address *next; ++ ++ while (address) { ++ next = address->next; ++ free(address); ++ address = next; ++ } ++} ++ ++void discovery_network_close(struct discovery_network *network) ++{ ++ if (network->ipv4 >= 0) ++ close(network->ipv4); ++ if (network->ipv6 >= 0) ++ close(network->ipv6); ++ if (network->events >= 0) ++ close(network->events); ++ addresses_free(network->addresses); ++ free(network->interface); ++ free(network); ++} ++ ++static int socket_open(int family) ++{ ++ const struct sockaddr *address; ++ struct sockaddr_in6 ipv6; ++ struct sockaddr_in ipv4; ++ socklen_t length; ++ int enabled = 1; ++ int descriptor; ++ int saved; ++ ++ descriptor = socket(family, SOCK_DGRAM | SOCK_CLOEXEC, 0); ++ if (descriptor < 0) ++ return -1; ++ if (setsockopt(descriptor, SOL_SOCKET, SO_REUSEADDR, &enabled, sizeof(enabled))) ++ goto error; ++ if (family == AF_INET) { ++ memset(&ipv4, 0, sizeof(ipv4)); ++ ipv4.sin_family = AF_INET; ++ ipv4.sin_port = htons(DISCOVERY_PORT); ++ address = (struct sockaddr *)&ipv4; ++ length = sizeof(ipv4); ++ if (setsockopt(descriptor, IPPROTO_IP, IP_PKTINFO, &enabled, sizeof(enabled))) ++ goto error; ++ } else { ++ memset(&ipv6, 0, sizeof(ipv6)); ++ ipv6.sin6_family = AF_INET6; ++ ipv6.sin6_port = htons(DISCOVERY_PORT); ++ address = (struct sockaddr *)&ipv6; ++ length = sizeof(ipv6); ++ if (setsockopt(descriptor, IPPROTO_IPV6, IPV6_V6ONLY, &enabled, sizeof(enabled)) || ++ setsockopt(descriptor, IPPROTO_IPV6, IPV6_RECVPKTINFO, &enabled, sizeof(enabled))) ++ goto error; ++ } ++ if (bind(descriptor, address, length)) ++ goto error; ++ return descriptor; ++ ++error: ++ saved = errno; ++ close(descriptor); ++ errno = saved; ++ return -1; ++} ++ ++struct discovery_network *discovery_network_open(const char *interface) ++{ ++ struct discovery_network *network; ++ struct sockaddr_nl address; ++ int saved; ++ ++ network = calloc(1, sizeof(*network)); ++ if (!network) ++ return NULL; ++ network->ipv4 = -1; ++ network->ipv6 = -1; ++ network->events = -1; ++ if (interface) { ++ network->interface = strdup(interface); ++ if (!network->interface) ++ goto error; ++ } ++ network->ipv4 = socket_open(AF_INET); ++ if (network->ipv4 < 0 && errno != EAFNOSUPPORT && errno != EPROTONOSUPPORT) ++ goto error; ++ network->ipv6 = socket_open(AF_INET6); ++ if (network->ipv6 < 0 && errno != EAFNOSUPPORT && errno != EPROTONOSUPPORT) ++ goto error; ++ if (network->ipv4 < 0 && network->ipv6 < 0) ++ goto error; ++ network->events = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE); ++ if (network->events < 0) ++ goto error; ++ memset(&address, 0, sizeof(address)); ++ address.nl_family = AF_NETLINK; ++ address.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; ++ if (bind(network->events, (struct sockaddr *)&address, sizeof(address))) ++ goto error; ++ return network; ++ ++error: ++ saved = errno; ++ discovery_network_close(network); ++ errno = saved; ++ return NULL; ++} ++ ++static int address_present(const struct discovery_address *list, ++ const struct discovery_address *address, int membership) ++{ ++ const struct sockaddr_in6 *ipv6; ++ const struct sockaddr_in *ipv4; ++ const void *candidate; ++ const void *wanted; ++ size_t length; ++ ++ if (address->address.ss_family == AF_INET) { ++ ipv4 = (const struct sockaddr_in *)&address->address; ++ wanted = &ipv4->sin_addr; ++ length = sizeof(ipv4->sin_addr); ++ } else { ++ ipv6 = (const struct sockaddr_in6 *)&address->address; ++ wanted = &ipv6->sin6_addr; ++ length = sizeof(ipv6->sin6_addr); ++ } ++ for (; list; list = list->next) { ++ if (list->interface != address->interface || ++ list->address.ss_family != address->address.ss_family) ++ continue; ++ if (membership) ++ return 1; ++ if (list->address.ss_family == AF_INET) { ++ ipv4 = (const struct sockaddr_in *)&list->address; ++ candidate = &ipv4->sin_addr; ++ } else { ++ ipv6 = (const struct sockaddr_in6 *)&list->address; ++ candidate = &ipv6->sin6_addr; ++ } ++ if (!memcmp(wanted, candidate, length)) ++ return 1; ++ } ++ return 0; ++} ++ ++static int address_ready(const struct sockaddr *address) ++{ ++ const struct sockaddr_in6 *ipv6; ++ const struct sockaddr_in *ipv4; ++ int descriptor; ++ int status; ++ int saved; ++ ++ if (address->sa_family == AF_INET) { ++ ipv4 = (const struct sockaddr_in *)address; ++ return ipv4->sin_addr.s_addr != INADDR_ANY && ++ ipv4->sin_addr.s_addr != INADDR_BROADCAST && ++ !IN_MULTICAST(ntohl(ipv4->sin_addr.s_addr)); ++ } ++ ipv6 = (const struct sockaddr_in6 *)address; ++ if (IN6_IS_ADDR_UNSPECIFIED(&ipv6->sin6_addr) || IN6_IS_ADDR_MULTICAST(&ipv6->sin6_addr)) ++ return 0; ++ descriptor = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0); ++ if (descriptor < 0) ++ return -1; ++ status = bind(descriptor, address, sizeof(*ipv6)); ++ saved = errno; ++ close(descriptor); ++ errno = saved; ++ if (!status) ++ return 1; ++ return errno == EADDRNOTAVAIL || errno == ENODEV ? 0 : -1; ++} ++ ++static int addresses_read(struct discovery_network *network, struct discovery_address **result) ++{ ++ struct discovery_address *address; ++ struct discovery_address *list; ++ struct ifaddrs *interfaces; ++ struct ifaddrs *interface; ++ int family; ++ int ready; ++ int saved; ++ ++ if (getifaddrs(&interfaces)) ++ return -1; ++ list = NULL; ++ for (interface = interfaces; interface; interface = interface->ifa_next) { ++ if (!interface->ifa_addr || !(interface->ifa_flags & IFF_UP) || ++ !(interface->ifa_flags & IFF_MULTICAST) || (interface->ifa_flags & IFF_LOOPBACK)) ++ continue; ++ if (network->interface && strcmp(network->interface, interface->ifa_name)) ++ continue; ++ family = interface->ifa_addr->sa_family; ++ if ((family != AF_INET && family != AF_INET6) || ++ (family == AF_INET && network->ipv4 < 0) || ++ (family == AF_INET6 && network->ipv6 < 0)) ++ continue; ++ ready = address_ready(interface->ifa_addr); ++ if (ready < 0) ++ goto error; ++ if (!ready) ++ continue; ++ address = calloc(1, sizeof(*address)); ++ if (!address) ++ goto error; ++ memcpy(&address->address, interface->ifa_addr, ++ family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6)); ++ address->interface = if_nametoindex(interface->ifa_name); ++ if (!address->interface) { ++ free(address); ++ continue; ++ } ++ address->next = list; ++ list = address; ++ } ++ freeifaddrs(interfaces); ++ *result = list; ++ return 0; ++ ++error: ++ saved = errno; ++ freeifaddrs(interfaces); ++ addresses_free(list); ++ errno = saved; ++ return -1; ++} ++ ++static int membership_set(struct discovery_network *network, ++ const struct discovery_address *address, int join) ++{ ++ struct ipv6_mreq ipv6; ++ struct ip_mreqn ipv4; ++ ++ if (address->address.ss_family == AF_INET) { ++ memset(&ipv4, 0, sizeof(ipv4)); ++ inet_pton(AF_INET, DISCOVERY_IPV4, &ipv4.imr_multiaddr); ++ ipv4.imr_ifindex = address->interface; ++ return setsockopt(network->ipv4, IPPROTO_IP, ++ join ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, &ipv4, sizeof(ipv4)); ++ } ++ memset(&ipv6, 0, sizeof(ipv6)); ++ inet_pton(AF_INET6, DISCOVERY_IPV6, &ipv6.ipv6mr_multiaddr); ++ ipv6.ipv6mr_interface = address->interface; ++ return setsockopt(network->ipv6, IPPROTO_IPV6, ++ join ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP, &ipv6, sizeof(ipv6)); ++} ++ ++int discovery_network_refresh(struct discovery_network *network, ++ discovery_announce_fn announce, void *data) ++{ ++ struct discovery_address *addresses; ++ struct discovery_address *address; ++ struct discovery_address *old; ++ ++ if (addresses_read(network, &addresses)) ++ return -1; ++ old = network->addresses; ++ for (address = old; address; address = address->next) { ++ if (address_present(address->next, address, 1) || address_present(addresses, address, 1)) ++ continue; ++ if (membership_set(network, address, 0) && errno != ENODEV && errno != EADDRNOTAVAIL) { ++ addresses_free(addresses); ++ return -1; ++ } ++ } ++ for (address = addresses; address; address = address->next) { ++ if (address_present(address->next, address, 1) || address_present(old, address, 1)) ++ continue; ++ if (membership_set(network, address, 1)) { ++ addresses_free(addresses); ++ return -1; ++ } ++ } ++ network->addresses = addresses; ++ for (address = addresses; address; address = address->next) ++ if (!address_present(old, address, 0)) ++ announce(network, address, data); ++ addresses_free(old); ++ return 0; ++} ++ ++void discovery_network_announce(struct discovery_network *network, ++ discovery_announce_fn announce, void *data) ++{ ++ const struct discovery_address *address; ++ ++ for (address = network->addresses; address; address = address->next) ++ announce(network, address, data); ++} ++ ++int discovery_network_send(struct discovery_network *network, ++ const struct discovery_address *local, ++ const struct sockaddr *destination, socklen_t length, ++ const char *buffer, size_t size) ++{ ++ union { ++ char data[CMSG_SPACE(sizeof(struct in6_pktinfo)) + CMSG_SPACE(sizeof(struct in_pktinfo))]; ++ struct cmsghdr alignment; ++ } control; ++ const struct sockaddr_in6 *ipv6; ++ const struct sockaddr_in *ipv4; ++ struct in6_pktinfo *info6; ++ struct in_pktinfo *info4; ++ struct cmsghdr *header; ++ struct msghdr message; ++ struct iovec vector; ++ int descriptor; ++ ++ memset(&message, 0, sizeof(message)); ++ memset(&control, 0, sizeof(control)); ++ vector.iov_base = (void *)buffer; ++ vector.iov_len = size; ++ message.msg_name = (void *)destination; ++ message.msg_namelen = length; ++ message.msg_iov = &vector; ++ message.msg_iovlen = 1; ++ message.msg_control = control.data; ++ if (local->address.ss_family == AF_INET) { ++ descriptor = network->ipv4; ++ message.msg_controllen = CMSG_SPACE(sizeof(*info4)); ++ header = CMSG_FIRSTHDR(&message); ++ header->cmsg_level = IPPROTO_IP; ++ header->cmsg_type = IP_PKTINFO; ++ header->cmsg_len = CMSG_LEN(sizeof(*info4)); ++ info4 = (struct in_pktinfo *)CMSG_DATA(header); ++ ipv4 = (const struct sockaddr_in *)&local->address; ++ info4->ipi_ifindex = local->interface; ++ info4->ipi_spec_dst = ipv4->sin_addr; ++ } else { ++ descriptor = network->ipv6; ++ message.msg_controllen = CMSG_SPACE(sizeof(*info6)); ++ header = CMSG_FIRSTHDR(&message); ++ header->cmsg_level = IPPROTO_IPV6; ++ header->cmsg_type = IPV6_PKTINFO; ++ header->cmsg_len = CMSG_LEN(sizeof(*info6)); ++ info6 = (struct in6_pktinfo *)CMSG_DATA(header); ++ ipv6 = (const struct sockaddr_in6 *)&local->address; ++ info6->ipi6_ifindex = local->interface; ++ info6->ipi6_addr = ipv6->sin6_addr; ++ } ++ return sendmsg(descriptor, &message, 0) < 0 ? -1 : 0; ++} ++ ++static int packet_address_set(struct discovery_network *network, ++ struct discovery_packet *packet, const struct msghdr *message) ++{ ++ const struct discovery_address *candidate; ++ const struct discovery_address *selected; ++ const struct sockaddr_in6 *peer; ++ struct sockaddr_in6 *ipv6; ++ struct sockaddr_in *ipv4; ++ const struct in6_pktinfo *info6; ++ const struct in_pktinfo *info4; ++ struct cmsghdr *header; ++ ++ for (header = CMSG_FIRSTHDR(message); header; ++ header = CMSG_NXTHDR((struct msghdr *)message, header)) { ++ if (header->cmsg_level == IPPROTO_IP && header->cmsg_type == IP_PKTINFO && ++ header->cmsg_len >= CMSG_LEN(sizeof(*info4))) { ++ info4 = (const struct in_pktinfo *)CMSG_DATA(header); ++ ipv4 = (struct sockaddr_in *)&packet->local.address; ++ ipv4->sin_family = AF_INET; ++ ipv4->sin_addr = IN_MULTICAST(ntohl(info4->ipi_addr.s_addr)) ? ++ info4->ipi_spec_dst : info4->ipi_addr; ++ packet->local.interface = info4->ipi_ifindex; ++ return 0; ++ } ++ if (header->cmsg_level != IPPROTO_IPV6 || header->cmsg_type != IPV6_PKTINFO || ++ header->cmsg_len < CMSG_LEN(sizeof(*info6))) ++ continue; ++ info6 = (const struct in6_pktinfo *)CMSG_DATA(header); ++ ipv6 = (struct sockaddr_in6 *)&packet->local.address; ++ ipv6->sin6_family = AF_INET6; ++ ipv6->sin6_addr = info6->ipi6_addr; ++ packet->local.interface = info6->ipi6_ifindex; ++ if (!IN6_IS_ADDR_MULTICAST(&ipv6->sin6_addr)) ++ return 0; ++ peer = (const struct sockaddr_in6 *)&packet->peer; ++ selected = NULL; ++ for (candidate = network->addresses; candidate; candidate = candidate->next) { ++ if (candidate->interface != packet->local.interface || ++ candidate->address.ss_family != AF_INET6) ++ continue; ++ if (!selected) ++ selected = candidate; ++ ipv6 = (struct sockaddr_in6 *)&candidate->address; ++ if (!!IN6_IS_ADDR_LINKLOCAL(&ipv6->sin6_addr) == ++ !!IN6_IS_ADDR_LINKLOCAL(&peer->sin6_addr)) { ++ selected = candidate; ++ break; ++ } ++ } ++ if (!selected) ++ return -1; ++ packet->local = *selected; ++ packet->local.next = NULL; ++ return 0; ++ } ++ return -1; ++} ++ ++int discovery_network_receive(struct discovery_network *network, char *buffer, ++ size_t length, struct discovery_packet *packet) ++{ ++ union { ++ char data[CMSG_SPACE(sizeof(struct in6_pktinfo)) + CMSG_SPACE(sizeof(struct in_pktinfo))]; ++ struct cmsghdr alignment; ++ } control; ++ struct msghdr message; ++ struct iovec vector; ++ ssize_t received; ++ fd_set descriptors; ++ int descriptor; ++ int maximum; ++ int status; ++ ++ FD_ZERO(&descriptors); ++ FD_SET(network->events, &descriptors); ++ maximum = network->events; ++ if (network->ipv4 >= 0) { ++ FD_SET(network->ipv4, &descriptors); ++ if (network->ipv4 > maximum) ++ maximum = network->ipv4; ++ } ++ if (network->ipv6 >= 0) { ++ FD_SET(network->ipv6, &descriptors); ++ if (network->ipv6 > maximum) ++ maximum = network->ipv6; ++ } ++ status = select(maximum + 1, &descriptors, NULL, NULL, NULL); ++ if (status < 0) ++ return -1; ++ if (FD_ISSET(network->events, &descriptors)) { ++ received = recv(network->events, buffer, length, 0); ++ if (received < 0 && errno != ENOBUFS) ++ return -1; ++ return 0; ++ } ++ descriptor = network->ipv4 >= 0 && FD_ISSET(network->ipv4, &descriptors) ? ++ network->ipv4 : network->ipv6; ++ memset(packet, 0, sizeof(*packet)); ++ memset(&message, 0, sizeof(message)); ++ vector.iov_base = buffer; ++ vector.iov_len = length - 1; ++ message.msg_name = &packet->peer; ++ message.msg_namelen = sizeof(packet->peer); ++ message.msg_iov = &vector; ++ message.msg_iovlen = 1; ++ message.msg_control = control.data; ++ message.msg_controllen = sizeof(control); ++ received = recvmsg(descriptor, &message, 0); ++ if (received < 0) ++ return -1; ++ if (message.msg_flags & (MSG_TRUNC | MSG_CTRUNC)) { ++ errno = EMSGSIZE; ++ return -1; ++ } ++ buffer[received] = '\0'; ++ packet->peer_length = message.msg_namelen; ++ if (packet_address_set(network, packet, &message)) { ++ errno = EADDRNOTAVAIL; ++ return -1; ++ } ++ return 1; ++} +--- /dev/null ++++ b/discovery_net.h +@@ -0,0 +1,36 @@ ++#ifndef DISCOVERY_NET_H ++#define DISCOVERY_NET_H ++ ++#include ++ ++struct discovery_network; ++ ++struct discovery_address { ++ struct sockaddr_storage address; ++ unsigned int interface; ++ struct discovery_address *next; ++}; ++ ++struct discovery_packet { ++ struct sockaddr_storage peer; ++ struct discovery_address local; ++ socklen_t peer_length; ++}; ++ ++typedef void (*discovery_announce_fn)(struct discovery_network *, ++ const struct discovery_address *, void *); ++ ++void discovery_network_close(struct discovery_network *network); ++struct discovery_network *discovery_network_open(const char *interface); ++int discovery_network_refresh(struct discovery_network *network, ++ discovery_announce_fn announce, void *data); ++void discovery_network_announce(struct discovery_network *network, ++ discovery_announce_fn announce, void *data); ++int discovery_network_receive(struct discovery_network *network, char *buffer, ++ size_t length, struct discovery_packet *packet); ++int discovery_network_send(struct discovery_network *network, ++ const struct discovery_address *local, ++ const struct sockaddr *destination, socklen_t length, ++ const char *buffer, size_t size); ++ ++#endif +--- a/test/README.md ++++ b/test/README.md +@@ -33,5 +33,10 @@ The test starts an isolated server on a + CGI wrappers and checks profile enumeration and SOAP HTTP fault status. + No camera or RTSP server is required by these protocol tests. + ++Run `make test-discovery` for IPv4 and IPv6 discovery checks. The network ++tests require Linux user/network namespaces and iproute2. They create ++multicast-capable dummy interfaces inside an isolated namespace and verify ++announcements, probe replies and dynamic interface/address changes. ++ + After building with `USE_ZLIB=1`, run `python3 test/test_compressed.py` to + check capability responses with only gzip-compressed templates available. +--- /dev/null ++++ b/test/test_discovery.py +@@ -0,0 +1,89 @@ ++from collections import deque ++from pathlib import Path ++import socket ++import subprocess ++import tempfile ++import threading ++import unittest ++import uuid ++import xml.etree.ElementTree as ET ++ ++ROOT = Path(__file__).resolve().parent.parent ++IDENTITY = 'b47bd8ea-7b8b-58c7-8354-88dbaddf57aa' ++ ++ ++class DiscoveryTests(unittest.TestCase): ++ @classmethod ++ def setUpClass(cls): ++ cls.directory = tempfile.TemporaryDirectory() ++ cls.addClassCleanup(cls.directory.cleanup) ++ cls.messages = deque(maxlen=100) ++ cls.ready = threading.Event() ++ cls.server = subprocess.Popen( ++ [str(ROOT / 'wsd_simple_server'), '-f', '-d', '5', '-u', IDENTITY, ++ '-p', str(Path(cls.directory.name) / 'pid'), '-t', str(ROOT / 'wsd_files'), ++ '-x', 'http://%s:8080/onvif/device_service'], ++ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True) ++ cls.addClassCleanup(cls.stop_server) ++ cls.reader = threading.Thread(target=cls.messages_read, daemon=True) ++ cls.reader.start() ++ cls.ready.wait() ++ if cls.server.poll() is not None: ++ raise AssertionError(list(cls.messages)) ++ ++ @classmethod ++ def messages_read(cls): ++ for message in cls.server.stderr: ++ cls.messages.append(message) ++ if 'Starting main loop.' in message: ++ cls.ready.set() ++ cls.ready.set() ++ ++ @classmethod ++ def stop_server(cls): ++ cls.server.terminate() ++ cls.server.wait() ++ cls.reader.join() ++ cls.server.stderr.close() ++ ++ def probe(self, family, address, host, group=None, interface=None): ++ identifier = 'urn:uuid:' + str(uuid.uuid4()) ++ body = ( ++ '' ++ f'{identifier}' ++ 'urn:schemas-xmlsoap-org:ws:2005:04:discovery' ++ 'http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe' ++ '') ++ with socket.socket(family, socket.SOCK_DGRAM) as client: ++ destination = (address, 3702) ++ if group is not None: ++ client.bind((address, 0)) ++ if family == socket.AF_INET: ++ client.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, ++ socket.inet_aton(address)) ++ destination = (group, 3702) ++ else: ++ client.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, interface) ++ destination = (group, 3702, 0, interface) ++ client.sendto(body.encode(), destination) ++ data, peer = client.recvfrom(65535) ++ root = ET.fromstring(data) ++ self.assertEqual(peer[0], address) ++ self.assertEqual(root.findtext('.//{*}RelatesTo'), identifier) ++ self.assertEqual(root.findtext('.//{*}XAddrs'), ++ f'http://{host}:8080/onvif/device_service') ++ self.assertEqual(root.findtext('.//{*}EndpointReference/{*}Address'), ++ 'urn:uuid:' + IDENTITY) ++ ++ def test_ipv4_connection_addresses(self): ++ for address in ['127.0.0.1', '127.0.0.2']: ++ self.probe(socket.AF_INET, address, address) ++ ++ def test_ipv6_connection_address(self): ++ self.probe(socket.AF_INET6, '::1', '[::1]') ++ ++ ++if __name__ == '__main__': ++ unittest.main() +--- /dev/null ++++ b/test/test_discovery_netns.py +@@ -0,0 +1,94 @@ ++from pathlib import Path ++import os ++import select ++import socket ++import struct ++import subprocess ++import unittest ++import xml.etree.ElementTree as ET ++ ++import test_discovery ++ ++ ++class NetworkDiscoveryTests(test_discovery.DiscoveryTests): ++ @classmethod ++ def command(cls, *arguments): ++ subprocess.run(['ip', *arguments], check=True, capture_output=True) ++ ++ @classmethod ++ def interface_add(cls, name, ipv4, ipv6): ++ cls.command('link', 'add', name, 'type', 'dummy') ++ cls.command('link', 'set', name, 'multicast', 'on') ++ cls.command('address', 'add', ipv4 + '/24', 'dev', name) ++ cls.command('-6', 'address', 'add', ipv6 + '/64', 'dev', name, 'nodad') ++ cls.membership_add(name) ++ cls.command('link', 'set', name, 'up') ++ ++ @classmethod ++ def membership_add(cls, name): ++ index = socket.if_nametoindex(name) ++ cls.observer4.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, ++ struct.pack('=4s4si', socket.inet_aton('239.255.255.250'), ++ socket.inet_aton('0.0.0.0'), index)) ++ cls.observer6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, ++ struct.pack('=16sI', socket.inet_pton(socket.AF_INET6, 'ff02::c'), ++ index)) ++ ++ @classmethod ++ def setUpClass(cls): ++ mapping = Path('/proc/self/uid_map').read_text().split() ++ assert os.getuid() == 0 and int(mapping[1]) != 0, 'Run inside unshare -Urn' ++ cls.command('link', 'set', 'lo', 'up') ++ cls.observer4 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ++ cls.observer6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) ++ cls.addClassCleanup(cls.observer4.close) ++ cls.addClassCleanup(cls.observer6.close) ++ for observer in [cls.observer4, cls.observer6]: ++ observer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ++ cls.observer6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) ++ cls.observer4.bind(('0.0.0.0', 3702)) ++ cls.observer6.bind(('::', 3702)) ++ cls.interface_add('camera_one', '192.0.2.1', '2001:db8:1::1') ++ cls.interface_add('camera_two', '198.51.100.1', '2001:db8:2::1') ++ super().setUpClass() ++ ++ def announcements_receive(self, addresses): ++ remaining = set(addresses) ++ while remaining: ++ ready, _, _ = select.select([self.observer4, self.observer6], [], []) ++ for observer in ready: ++ data, peer = observer.recvfrom(65535) ++ root = ET.fromstring(data) ++ if root.find('.//{*}Hello') is None: ++ continue ++ self.assertEqual(root.findtext('.//{*}EndpointReference/{*}Address'), ++ 'urn:uuid:' + test_discovery.IDENTITY) ++ address = peer[0] ++ host = f'[{address}]' if ':' in address else address ++ self.assertEqual(root.findtext('.//{*}XAddrs'), ++ f'http://{host}:8080/onvif/device_service') ++ remaining.discard(address) ++ ++ def test_all_interfaces_announced(self): ++ self.announcements_receive(['192.0.2.1', '198.51.100.1', ++ '2001:db8:1::1', '2001:db8:2::1']) ++ ++ def test_dynamic_addresses_and_interfaces(self): ++ self.interface_add('camera_three', '203.0.113.1', '2001:db8:3::1') ++ self.announcements_receive(['203.0.113.1', '2001:db8:3::1']) ++ self.command('-6', 'address', 'add', '2001:db8:1::2/64', 'dev', 'camera_one') ++ self.announcements_receive(['2001:db8:1::2']) ++ self.command('link', 'delete', 'camera_three') ++ self.probe(socket.AF_INET, '192.0.2.1', '192.0.2.1') ++ ++ def test_multicast_probe_ingress(self): ++ for name, ipv4, ipv6 in [('camera_one', '192.0.2.1', '2001:db8:1::1'), ++ ('camera_two', '198.51.100.1', '2001:db8:2::1')]: ++ self.probe(socket.AF_INET, ipv4, ipv4, '239.255.255.250', ++ socket.if_nametoindex(name)) ++ self.probe(socket.AF_INET6, ipv6, f'[{ipv6}]', 'ff02::c', ++ socket.if_nametoindex(name)) ++ ++ ++if __name__ == '__main__': ++ unittest.main() +--- a/wsd_simple_server.c ++++ b/wsd_simple_server.c +@@ -36,6 +36,7 @@ + #include "utils.h" + #include "log.h" + #include "ezxml_wrapper.h" ++#include "discovery_net.h" + + #define MULTICAST_ADDRESS "239.255.255.250" + #define MULTICAST_ADDRESS_V6 "FF02::C" +@@ -60,24 +61,13 @@ + int debug; + FILE *fLog; + char template_file[1024]; +-/* Service socket: dual-stack AF_INET6 (IPV6_V6ONLY=0) when an IPv6 address is +- * present, else a plain AF_INET socket (IPv4-only, e.g. kernels without IPv6). */ +-int sock; +-int sock_family; +-/* IPv4 */ +-char address[16], netmask[16]; +-struct sockaddr_storage addr_mcast4; /* IPv4 WSD mcast dest; family per sock_family */ +-socklen_t addr_mcast4_len; +-char xaddr[1024]; +-/* IPv6 (auto-detected at startup) */ +-char address6[INET6_ADDRSTRLEN]; +-struct sockaddr_in6 addr_mcast6; /* [FF02::C]:3702 */ +-char xaddr6[1024]; ++struct discovery_network *network; ++const char *xaddr_format; + + char *message; + char *message_loop; + char template_dir[1024]; +-int exit_main; ++volatile sig_atomic_t exit_main; + int msg_number; + char uuid[UUID_LEN + 1]; + char msg_uuid[UUID_LEN + 1]; +@@ -86,38 +76,6 @@ char model[64]; + char hardware[64]; + + /* ------------------------------------------------------------------------- +- * IPv4 interface auto-detection: connect a UDP socket (no packet sent) to +- * the WSD multicast group and read back the kernel's chosen source address. +- * Returns 0 on success, -1 on failure. +- * ---------------------------------------------------------------------- */ +-static int detect_outbound_address(char *addr_str) +-{ +- int fd; +- struct sockaddr_in dst, src; +- socklen_t src_len = sizeof(src); +- +- fd = socket(AF_INET, SOCK_DGRAM, 0); +- if (fd < 0) return -1; +- +- memset(&dst, 0, sizeof(dst)); +- dst.sin_family = AF_INET; +- inet_pton(AF_INET, MULTICAST_ADDRESS, &dst.sin_addr); +- dst.sin_port = htons(PORT); +- +- if (connect(fd, (struct sockaddr *)&dst, sizeof(dst)) < 0) { close(fd); return -1; } +- +- memset(&src, 0, sizeof(src)); +- if (getsockname(fd, (struct sockaddr *)&src, &src_len) < 0) { close(fd); return -1; } +- close(fd); +- +- if (src.sin_addr.s_addr == htonl(INADDR_ANY)) return -1; +- +- strncpy(addr_str, inet_ntoa(src.sin_addr), 15); +- addr_str[15] = 0; +- return 0; +-} +- +-/* ------------------------------------------------------------------------- + * Daemon / PID helpers + * ---------------------------------------------------------------------- */ + int daemonize(int flags) +@@ -171,48 +129,101 @@ int create_pid(char *file_name) + /* ------------------------------------------------------------------------- + * WSD message helpers + * ---------------------------------------------------------------------- */ +-static int send_wsd_msg(int s, const char *buf, size_t len, +- const struct sockaddr *dst, socklen_t dst_len) ++static void identity_resolve(const struct discovery_address *local) ++{ ++ char interface[IFNAMSIZ]; ++ uint8_t mac[6]; ++ ++ if (uuid[0]) ++ return; ++ if (if_indextoname(local->interface, interface) && !get_mac_by_ifname(interface, mac)) ++ gen_uuid_v5_mac(uuid, mac); ++ else ++ gen_uuid(uuid); ++} ++ ++static int local_url(const struct discovery_address *local, char *url, size_t length) + { +- return (sendto(s, buf, len, 0, dst, dst_len) < 0) ? -1 : 0; ++ char host[INET6_ADDRSTRLEN + sizeof("[]")]; ++ char address[INET6_ADDRSTRLEN]; ++ const struct sockaddr_in6 *ipv6; ++ const struct sockaddr_in *ipv4; ++ int size; ++ ++ if (local->address.ss_family == AF_INET) { ++ ipv4 = (const struct sockaddr_in *)&local->address; ++ if (!inet_ntop(AF_INET, &ipv4->sin_addr, address, sizeof(address))) ++ return -1; ++ snprintf(host, sizeof(host), "%s", address); ++ } else { ++ ipv6 = (const struct sockaddr_in6 *)&local->address; ++ if (!inet_ntop(AF_INET6, &ipv6->sin6_addr, address, sizeof(address))) ++ return -1; ++ snprintf(host, sizeof(host), "[%s]", address); ++ } ++ size = snprintf(url, length, xaddr_format, host); ++ return size < 0 || (size_t)size >= length ? -1 : 0; + } + +-static void send_bye(int s, const struct sockaddr *dst, socklen_t dst_len, +- const char *xaddr_str) ++static void announcement_send(struct discovery_network *context, ++ const struct discovery_address *local, void *data) + { ++ struct sockaddr_in6 destination6; ++ struct sockaddr_in destination4; ++ const struct sockaddr *destination; ++ char xaddr_str[1024]; + char s_tmp[32]; ++ socklen_t destination_length; ++ const char *kind = data; + long size; + ++ if (local_url(local, xaddr_str, sizeof(xaddr_str))) ++ return; ++ identity_resolve(local); ++ if (local->address.ss_family == AF_INET) { ++ memset(&destination4, 0, sizeof(destination4)); ++ destination4.sin_family = AF_INET; ++ destination4.sin_port = htons(PORT); ++ inet_pton(AF_INET, MULTICAST_ADDRESS, &destination4.sin_addr); ++ destination = (struct sockaddr *)&destination4; ++ destination_length = sizeof(destination4); ++ } else { ++ memset(&destination6, 0, sizeof(destination6)); ++ destination6.sin6_family = AF_INET6; ++ destination6.sin6_port = htons(PORT); ++ destination6.sin6_scope_id = local->interface; ++ inet_pton(AF_INET6, MULTICAST_ADDRESS_V6, &destination6.sin6_addr); ++ destination = (struct sockaddr *)&destination6; ++ destination_length = sizeof(destination6); ++ } + msg_number++; + snprintf(s_tmp, sizeof(s_tmp), "%d", msg_number); + gen_uuid(msg_uuid); +- +- snprintf(template_file, sizeof(template_file), "%s/Bye.xml", template_dir); ++ snprintf(template_file, sizeof(template_file), "%s/%s.xml", template_dir, kind); + size = cat(NULL, template_file, 12, + "%MSG_UUID%", msg_uuid, "%MSG_NUMBER%", s_tmp, "%UUID%", uuid, + "%HARDWARE%", hardware, "%NAME%", model, "%ADDRESS%", xaddr_str); +- message = (char *) malloc((size + 1) * sizeof(char)); +- if (!message) { log_fatal("Malloc error."); return; } ++ if (size < 0) ++ return; ++ message = malloc(size + 1); ++ if (!message) { ++ log_error("Cannot allocate announcement."); ++ return; ++ } + cat(message, template_file, 12, + "%MSG_UUID%", msg_uuid, "%MSG_NUMBER%", s_tmp, "%UUID%", uuid, + "%HARDWARE%", hardware, "%NAME%", model, "%ADDRESS%", xaddr_str); +- +- if (send_wsd_msg(s, message, strlen(message), dst, dst_len) < 0) +- log_fatal("Error sending Bye message."); ++ if (discovery_network_send(context, local, destination, destination_length, ++ message, strlen(message))) ++ log_error("Cannot send %s: %s", kind, strerror(errno)); + else +- log_info("Bye sent."); ++ log_info("%s sent on interface %u: %s", kind, local->interface, xaddr_str); + free(message); + } + + void signal_handler(int signal) + { +- log_info("Sending Bye message(s)."); +- if (sock >= 0) { +- send_bye(sock, (struct sockaddr *)&addr_mcast4, sizeof(addr_mcast4), xaddr); +- if (xaddr6[0]) +- send_bye(sock, (struct sockaddr *)&addr_mcast6, sizeof(addr_mcast6), xaddr6); +- shutdown(sock, SHUT_RDWR); close(sock); sock = -1; +- } ++ (void)signal; + exit_main = 1; + } + +@@ -221,10 +232,10 @@ void print_usage(char *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\tnetwork interface restriction (default: all suitable interfaces)\n"); + fprintf(stderr, "\t-x, --xaddr\n"); + fprintf(stderr, "\t\tresource address template (use %%s as placeholder for the detected IP;\n"); +- fprintf(stderr, "\t\tIPv6 is auto-detected and the address is bracketed automatically)\n"); ++ fprintf(stderr, "\t\tIPv6 addresses are bracketed automatically)\n"); + fprintf(stderr, "\t-m, --model\n"); + fprintf(stderr, "\t\tmodel name\n"); + fprintf(stderr, "\t-n, --hardware\n"); +@@ -243,18 +254,22 @@ void print_usage(char *progname) + fprintf(stderr, "\t\tprint this help\n"); + } + +-static void handle_probe(int s, struct sockaddr *dst, socklen_t dst_len, +- char *buf, const char *xaddr_str) ++static void handle_probe(struct discovery_network *context, ++ const struct discovery_packet *packet, char *buf) + { + const char *relates_to_uuid; ++ const char *method; ++ char xaddr_str[1024]; + char s_tmp[32]; + long size; + +- if (strstr(buf, "XAddrs") != NULL) return; ++ if (strstr(buf, "XAddrs") != NULL || local_url(&packet->local, xaddr_str, sizeof(xaddr_str))) ++ return; ++ identity_resolve(&packet->local); + + log_debug("%s", buf); + init_xml(buf, strlen(buf)); +- const char *method = get_method(1); ++ method = get_method(1); + if (!method || strcasecmp("Probe", method) != 0) { + log_debug("This is not a Probe message"); + close_xml(); return; +@@ -267,7 +282,6 @@ static void handle_probe(int s, struct s + + relates_to_uuid = get_element("MessageID", "Header"); + if (!relates_to_uuid) { log_error("Cannot find MessageID."); close_xml(); return; } +- close_xml(); + + log_info("Sending ProbeMatches message."); + snprintf(template_file, sizeof(template_file), "%s/ProbeMatches.xml", template_dir); +@@ -276,17 +290,20 @@ static void handle_probe(int s, struct s + "%MSG_NUMBER%", s_tmp, "%UUID%", uuid, + "%HARDWARE%", hardware, "%NAME%", model, "%ADDRESS%", xaddr_str); + message_loop = (char *) malloc((size + 1) * sizeof(char)); +- if (!message_loop) { log_error("Malloc error."); return; } ++ if (!message_loop) { log_error("Malloc error."); close_xml(); return; } + cat(message_loop, template_file, 14, + "%MSG_UUID%", msg_uuid, "%REL_TO_UUID%", relates_to_uuid, + "%MSG_NUMBER%", s_tmp, "%UUID%", uuid, + "%HARDWARE%", hardware, "%NAME%", model, "%ADDRESS%", xaddr_str); + +- if (send_wsd_msg(s, message_loop, strlen(message_loop), dst, dst_len) < 0) ++ if (discovery_network_send(context, &packet->local, ++ (const struct sockaddr *)&packet->peer, packet->peer_length, ++ message_loop, strlen(message_loop)) < 0) + log_error("Error sending ProbeMatches message."); + else + log_info("Sent."); + free(message_loop); ++ close_xml(); + } + + /* ------------------------------------------------------------------------- +@@ -298,11 +315,9 @@ int main(int argc, char **argv) + char *endptr; + int c, ret; + char *if_name, *pid_file, *xaddr_s; +- unsigned int if6_idx = 0; +- int have_v4 = 0; +- int foreground, no = 0; +- char s_tmp[32]; +- long size; ++ struct discovery_packet packet; ++ const char *log_file; ++ int foreground; + char recv_buffer[RECV_BUFFER_LEN]; + + if_name = pid_file = xaddr_s = NULL; +@@ -311,7 +326,6 @@ int main(int argc, char **argv) + snprintf(template_dir, sizeof(template_dir), "%s", DEFAULT_TEMPLATE_DIR); + foreground = 0; + debug = 5; +- sock = -1; + + while (1) { + static struct option long_options[] = { +@@ -381,7 +395,12 @@ int main(int argc, char **argv) + if (ret) { fprintf(stderr, "Error starting daemon.\n"); exit(EXIT_FAILURE); } + } + +- fLog = fopen(DEFAULT_LOG_FILE, "w"); ++ log_file = foreground ? "-" : DEFAULT_LOG_FILE; ++ fLog = strcmp(log_file, "-") == 0 ? stderr : fopen(log_file, "w"); ++ if (!fLog) { ++ fprintf(stderr, "Cannot open log file %s\n", log_file); ++ exit(EXIT_FAILURE); ++ } + log_add_fp(fLog, debug); + log_set_level(debug); + log_set_quiet(1); +@@ -410,263 +429,47 @@ int main(int argc, char **argv) + closedir(dirptr); + } + +- srand((unsigned int) time(NULL)); +- +- /* ---- IPv4 address detection ---------------------------------------- */ +- if (if_name) { +- get_ip_address(address, netmask, if_name); +- have_v4 = (address[0] != '\0'); +- } else { +- if (detect_outbound_address(address) == 0) { +- have_v4 = 1; +- log_info("Auto-detected outbound IPv4 address: %s", address); +- } else { +- log_warn("Cannot auto-detect outbound IPv4 address; will try IPv6."); +- } +- } +- if (have_v4) log_debug("IPv4 address = %s", address); +- +- /* ---- IPv6 address detection (always attempted) --------------------- */ +- memset(address6, 0, sizeof(address6)); +- xaddr6[0] = '\0'; +- { +- int v6_ok; +- if (if_name) +- v6_ok = (get_ip6_address(address6, sizeof(address6), if_name) == 0); +- else +- v6_ok = (detect_outbound_address_v6(address6, sizeof(address6), &if6_idx) == 0); +- if (v6_ok) { +- char tmp6[INET6_ADDRSTRLEN + 4]; +- log_info("IPv6 address: %s", address6); +- snprintf(tmp6, sizeof(tmp6), "[%s]", address6); +- snprintf(xaddr6, sizeof(xaddr6), xaddr_s, tmp6); +- } else { +- log_debug("No global IPv6 address found; IPv6 WSD disabled."); +- } ++ xaddr_format = xaddr_s; ++ network = discovery_network_open(if_name); ++ if (!network) { ++ log_error("Cannot open discovery sockets: %s", strerror(errno)); ++ unlink(pid_file); ++ return EXIT_FAILURE; + } +- +- if (!have_v4 && !xaddr6[0]) { +- log_fatal("No usable IPv4 or IPv6 address found. Use -i or check network."); +- fclose(fLog); exit(EXIT_FAILURE); +- } +- +- if (!uuid[0]) { +- uint8_t mac[6] = {0}; +- int mac_ok; +- if (if_name) { +- mac_ok = (get_mac_by_ifname(if_name, mac) == 0); +- } else if (have_v4) { +- mac_ok = (get_mac_by_ip(address, mac) == 0); +- } else { +- /* IPv6-only: derive interface name from if6_idx */ +- char if6_name[IF_NAMESIZE] = {0}; +- mac_ok = (if6_idx && if_indextoname(if6_idx, if6_name) && +- get_mac_by_ifname(if6_name, mac) == 0); +- } +- if (mac_ok) { +- gen_uuid_v5_mac(uuid, mac); +- log_info("Device UUID (stable, MAC-based): %s", uuid); +- } else { +- gen_uuid(uuid); +- log_info("Device UUID (random, MAC unavailable): %s", uuid); +- } ++ exit_main = 0; ++ if (discovery_network_refresh(network, announcement_send, "Hello")) { ++ log_error("Cannot initialise discovery interfaces: %s", strerror(errno)); ++ discovery_network_close(network); ++ unlink(pid_file); ++ return EXIT_FAILURE; + } +- +- /* ---- Service socket: dual-stack AF_INET6, or AF_INET (IPv4-only) ------- */ +- /* Family follows the IPv6 detection result: dual-stack only when there is +- * an IPv6 address to serve, else plain AF_INET -- so WSD still runs on +- * kernels built without IPv6, where socket(AF_INET6) fails. */ +- { +- int yes = 1; +- sock_family = xaddr6[0] ? AF_INET6 : AF_INET; +- +- if ((sock = socket(sock_family, SOCK_DGRAM, 0)) < 0) { +- /* v6 detected but AF_INET6 unavailable: drop to IPv4-only. */ +- if (sock_family == AF_INET6) { +- log_warn("AF_INET6 socket unavailable (%s); falling back to IPv4-only.", strerror(errno)); +- sock_family = AF_INET; +- xaddr6[0] = '\0'; +- sock = socket(AF_INET, SOCK_DGRAM, 0); +- } +- if (sock < 0) { +- log_fatal("Unable to create socket: %s", strerror(errno)); +- fclose(fLog); exit(EXIT_FAILURE); +- } +- } +- +- /* IPV6_V6ONLY=0: the dual-stack socket also receives IPv4 (::ffff:x.x.x.x). */ +- if (sock_family == AF_INET6) +- setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &no, sizeof(no)); +- setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); +- +- if (sock_family == AF_INET6) { +- struct sockaddr_in6 bind6; +- memset(&bind6, 0, sizeof(bind6)); +- bind6.sin6_family = AF_INET6; bind6.sin6_port = htons(PORT); +- bind6.sin6_addr = in6addr_any; +- if (bind(sock, (struct sockaddr *)&bind6, sizeof(bind6)) < 0) { +- log_fatal("Unable to bind socket: %s", strerror(errno)); +- close(sock); fclose(fLog); exit(EXIT_FAILURE); +- } +- } else { +- struct sockaddr_in bind4; +- memset(&bind4, 0, sizeof(bind4)); +- bind4.sin_family = AF_INET; bind4.sin_port = htons(PORT); +- bind4.sin_addr.s_addr = INADDR_ANY; +- if (bind(sock, (struct sockaddr *)&bind4, sizeof(bind4)) < 0) { +- log_fatal("Unable to bind socket: %s", strerror(errno)); +- close(sock); fclose(fLog); exit(EXIT_FAILURE); +- } +- } +- +- /* Join the IPv4 WSD multicast group. IP_ADD_MEMBERSHIP with ip_mreq +- * works on a plain AF_INET socket and, via IPV6_V6ONLY=0, on the +- * dual-stack AF_INET6 socket too (MCAST_JOIN_GROUP with IPPROTO_IPV6 +- * does not, because the kernel IPv6 mc path rejects AF_INET groups). */ +- if (have_v4) { +- struct ip_mreq mreq4; +- memset(&mreq4, 0, sizeof(mreq4)); +- inet_pton(AF_INET, MULTICAST_ADDRESS, &mreq4.imr_multiaddr); +- mreq4.imr_interface.s_addr = INADDR_ANY; +- if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq4, sizeof(mreq4)) < 0) { +- log_fatal("Error joining IPv4 multicast group: %s", strerror(errno)); +- close(sock); fclose(fLog); exit(EXIT_FAILURE); ++ log_info("Starting main loop."); ++ while (!exit_main) { ++ ret = discovery_network_receive(network, recv_buffer, sizeof(recv_buffer), &packet); ++ if (ret < 0) { ++ if (errno == EINTR) ++ continue; ++ if (errno == EMSGSIZE || errno == EADDRNOTAVAIL) { ++ log_warn("Discarded discovery datagram: %s", strerror(errno)); ++ continue; + } ++ log_error("Cannot receive discovery messages: %s", strerror(errno)); ++ break; + } +- +- /* IPv4 mcast destination: IPv4-mapped on the dual-stack socket, real IPv4 on AF_INET. */ +- memset(&addr_mcast4, 0, sizeof(addr_mcast4)); +- if (sock_family == AF_INET6) { +- struct sockaddr_in6 *m = (struct sockaddr_in6 *)&addr_mcast4; +- m->sin6_family = AF_INET6; m->sin6_port = htons(PORT); +- inet_pton(AF_INET6, "::ffff:" MULTICAST_ADDRESS, &m->sin6_addr); +- addr_mcast4_len = sizeof(struct sockaddr_in6); +- } else { +- struct sockaddr_in *m = (struct sockaddr_in *)&addr_mcast4; +- m->sin_family = AF_INET; m->sin_port = htons(PORT); +- inet_pton(AF_INET, MULTICAST_ADDRESS, &m->sin_addr); +- addr_mcast4_len = sizeof(struct sockaddr_in); +- } +- } +- +- /* ---- IPv6 multicast (when IPv6 address was detected) ----------------- */ +- if (xaddr6[0]) { +- struct ipv6_mreq mr6; +- unsigned int if_idx = if_name ? if_nametoindex(if_name) : if6_idx; +- +- /* if_idx must be non-zero for link-local multicast (FF02::). */ +- memset(&mr6, 0, sizeof(mr6)); +- inet_pton(AF_INET6, MULTICAST_ADDRESS_V6, &mr6.ipv6mr_multiaddr); +- mr6.ipv6mr_interface = if_idx; +- if (setsockopt(sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mr6, sizeof(mr6)) < 0) { +- log_warn("Cannot join IPv6 multicast group; IPv6 WSD disabled: %s", strerror(errno)); +- xaddr6[0] = '\0'; +- } else { +- if (if_idx) setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, &if_idx, sizeof(if_idx)); +- memset(&addr_mcast6, 0, sizeof(addr_mcast6)); +- addr_mcast6.sin6_family = AF_INET6; addr_mcast6.sin6_port = htons(PORT); +- inet_pton(AF_INET6, MULTICAST_ADDRESS_V6, &addr_mcast6.sin6_addr); +- addr_mcast6.sin6_scope_id = if_idx; +- log_info("IPv6 WSD multicast joined (FF02::C, if_idx=%u).", if_idx); +- } +- } +- +- /* ---- Build xaddr strings ------------------------------------------- */ +- if (have_v4) snprintf(xaddr, sizeof(xaddr), xaddr_s, address); +- +- /* ---- Send Hello ---------------------------------------------------- */ +- msg_number = 1; +- snprintf(s_tmp, sizeof(s_tmp), "%d", msg_number); +- gen_uuid(msg_uuid); +- +- if (have_v4) { +- snprintf(template_file, sizeof(template_file), "%s/Hello.xml", template_dir); +- size = cat(NULL, template_file, 12, +- "%MSG_UUID%", msg_uuid, "%MSG_NUMBER%", s_tmp, "%UUID%", uuid, +- "%HARDWARE%", hardware, "%NAME%", model, "%ADDRESS%", xaddr); +- message = (char *) malloc((size + 1) * sizeof(char)); +- if (!message) { +- log_fatal("Malloc error."); close(sock); fclose(fLog); exit(EXIT_FAILURE); +- } +- cat(message, template_file, 12, +- "%MSG_UUID%", msg_uuid, "%MSG_NUMBER%", s_tmp, "%UUID%", uuid, +- "%HARDWARE%", hardware, "%NAME%", model, "%ADDRESS%", xaddr); +- if (send_wsd_msg(sock, message, strlen(message), +- (struct sockaddr *)&addr_mcast4, addr_mcast4_len) < 0) { +- log_fatal("Error sending Hello (IPv4)."); +- free(message); close(sock); fclose(fLog); exit(EXIT_FAILURE); +- } +- free(message); +- log_info("Hello (IPv4) sent."); +- } +- +- if (xaddr6[0]) { +- msg_number++; +- snprintf(s_tmp, sizeof(s_tmp), "%d", msg_number); +- gen_uuid(msg_uuid); +- snprintf(template_file, sizeof(template_file), "%s/Hello.xml", template_dir); +- size = cat(NULL, template_file, 12, +- "%MSG_UUID%", msg_uuid, "%MSG_NUMBER%", s_tmp, "%UUID%", uuid, +- "%HARDWARE%", hardware, "%NAME%", model, "%ADDRESS%", xaddr6); +- message = (char *) malloc((size + 1) * sizeof(char)); +- if (message) { +- cat(message, template_file, 12, +- "%MSG_UUID%", msg_uuid, "%MSG_NUMBER%", s_tmp, "%UUID%", uuid, +- "%HARDWARE%", hardware, "%NAME%", model, "%ADDRESS%", xaddr6); +- if (send_wsd_msg(sock, message, strlen(message), +- (struct sockaddr *)&addr_mcast6, sizeof(addr_mcast6)) < 0) +- log_warn("Error sending Hello (IPv6)."); +- else +- log_info("Hello (IPv6) sent."); +- free(message); +- } +- } +- +- sleep(1); +- +- /* ---- Main loop ----------------------------------------------------- */ +- if (have_v4 && xaddr6[0]) +- log_info("Starting main loop (IPv4 + IPv6)."); +- else if (have_v4) +- log_info("Starting main loop (IPv4 only)."); +- else +- log_info("Starting main loop (IPv6 only)."); +- exit_main = 0; +- +- while (!exit_main) { +- struct sockaddr_storage sender; +- socklen_t slen = sizeof(sender); +- const char *probe_xaddr; +- int is_v4; +- fd_set rfds; +- FD_ZERO(&rfds); +- FD_SET(sock, &rfds); +- if (select(sock + 1, &rfds, NULL, NULL, NULL) <= 0) continue; +- +- memset(recv_buffer, 0, RECV_BUFFER_LEN); +- if (recvfrom(sock, recv_buffer, RECV_BUFFER_LEN, 0, +- (struct sockaddr *)&sender, &slen) <= 0) continue; +- +- /* Native IPv4 (AF_INET socket) or IPv4-mapped IPv6 (dual-stack socket). */ +- is_v4 = (sender.ss_family == AF_INET) || +- ((sender.ss_family == AF_INET6) && +- IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)&sender)->sin6_addr)); +- if (is_v4) { +- if (!have_v4) { log_debug("IPv4 probe received but IPv4 WSD not active; ignoring."); continue; } +- probe_xaddr = xaddr; +- } else if (xaddr6[0]) { +- probe_xaddr = xaddr6; +- } else { +- log_debug("IPv6 probe received but IPv6 WSD not configured; ignoring."); ++ if (ret > 0) { ++ handle_probe(network, &packet, recv_buffer); + continue; + } +- handle_probe(sock, (struct sockaddr *)&sender, slen, recv_buffer, probe_xaddr); ++ if (discovery_network_refresh(network, announcement_send, "Hello")) { ++ log_error("Cannot update discovery interfaces: %s", strerror(errno)); ++ break; ++ } + } +- +- if (sock >= 0) { shutdown(sock, SHUT_RDWR); close(sock); } +- +- log_info("Terminating program."); +- fclose(fLog); ++ discovery_network_announce(network, announcement_send, "Bye"); ++ discovery_network_close(network); + unlink(pid_file); +- return 0; ++ log_info("Terminating program."); ++ if (fLog != stderr) ++ fclose(fLog); ++ return exit_main ? EXIT_SUCCESS : EXIT_FAILURE; + } diff --git a/multimedia/onvif-simple-server/patches/0019-fix-validate-discovery-debug-levels-before-conversio.patch b/multimedia/onvif-simple-server/patches/0019-fix-validate-discovery-debug-levels-before-conversio.patch new file mode 100644 index 0000000000..d21921bc0e --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0019-fix-validate-discovery-debug-levels-before-conversio.patch @@ -0,0 +1,52 @@ +From d5e3c45c758d84c23bbcde1affbb45b81aa3c5d3 Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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; diff --git a/multimedia/onvif-simple-server/patches/0020-fix-escape-device-information-as-XML-text.patch b/multimedia/onvif-simple-server/patches/0020-fix-escape-device-information-as-XML-text.patch new file mode 100644 index 0000000000..9de9101515 --- /dev/null +++ b/multimedia/onvif-simple-server/patches/0020-fix-escape-device-information-as-XML-text.patch @@ -0,0 +1,240 @@ +From 629527e5ff80139230b0909f48da9a0a0417f2ee Mon Sep 17 00:00:00 2001 +From: Daniel Golle +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 +--- + 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 "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', 'true'), + ('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 & ' ++ 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__': diff --git a/multimedia/onvif-simple-server/test-version.sh b/multimedia/onvif-simple-server/test-version.sh new file mode 100755 index 0000000000..27a61adec5 --- /dev/null +++ b/multimedia/onvif-simple-server/test-version.sh @@ -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