diff --git a/lib/data/ponvif/ponvif.cpp b/lib/data/ponvif/ponvif.cpp index 094e92bf..865c674a 100644 --- a/lib/data/ponvif/ponvif.cpp +++ b/lib/data/ponvif/ponvif.cpp @@ -1,7 +1,10 @@ #include "ponvif.h" #include +#include +#include #include +#include #include #include #include /* See NOTES */ @@ -33,26 +36,74 @@ inline bool checkBool(const char * A) return (A[0] == 'T' || A[0] == 't' || A[0] == '1'); } +// IrCutFilter / BacklightCompensation etc.: "ON" / "OFF" (also accepts 1 / 0) inline bool checkOnOff(const char * A) { if (A == NULL) { return false; } - return (A[1] == 'N' || A[1] == 'n' || A[0] == '1'); + return (strcasecmp(A, "ON") == 0 || strcmp(A, "1") == 0); } +// tt:IrCutFilterMode: ON / OFF / AUTO inline onvifOnOffAuto checkOnOffAuto(const char * A) { if (A == NULL) { return AUTO; } - if (A[1] == 'N' || A[1] == 'n' || A[0] == '1') + if (strcasecmp(A, "ON") == 0 || strcmp(A, "1") == 0) { return ON; } - return OFF; + if (strcasecmp(A, "OFF") == 0 || strcmp(A, "0") == 0) + { + return OFF; + } + return AUTO; +} + +/* + NULL-safe readers: most ONVIF elements/attributes are optional, XMLNode::getText()/getAttribute() + return NULL when they are missing. +*/ +inline void safeCopy(char * dst, size_t dstSize, const char * src) +{ + if (dst == NULL || dstSize == 0) + { + return; + } + snprintf(dst, dstSize, "%s", (src != NULL) ? src : ""); +} + +inline int safeAtoi(const char * A, int def = 0) +{ + return (A != NULL) ? atoi(A) : def; +} + +inline float safeAtof(const char * A, float def = 0.0f) +{ + return (A != NULL) ? (float) atof(A) : def; +} + +// XML-escaped copy as std::string, for printf arguments (the temporary lives until the end of the full expression) +static std::string xesc(const char * src) +{ + if (src == NULL) + { + return std::string(); + } + size_t len = strlen(src) * 6 + 1; + char * tB = (char *) malloc(len); + if (tB == NULL) + { + return std::string(); + } + pOnvif::_xmlEscape(src, tB, len); + std::string rVal(tB); + free(tB); + return rVal; } pOnvif::pOnvif() @@ -84,6 +135,11 @@ pOnvif::pOnvif() m_bAuthMode = 0; parser_done = false; m_pPendingRequest = NULL; + m_nLastHttpCode = 0; + m_eLastError = PONVIF_OK; + m_cLastFault[0] = (char) 0; + m_sOnvifVersion.Major = 0; + m_sOnvifVersion.Minor = 0; LOG("Constructor Done!"); } @@ -721,173 +777,109 @@ bool pOnvif::create(void){ if (m_pHttpAccessManager == NULL) { return false; } -#ifdef DEBUG_EXTRA - LOG("CURL MANAGER OK"); -#endif - try { - struct tm * tTS; - tTS = core_GetSystemDateAndTime(); - // This is UTS DTS - - if (tTS != NULL) { -#ifdef DEBUG - char tB[128]; - sprintf(tB, "TS from dev: %04d-%02d-%02d %02d:%02d:%02d", tTS->tm_year, tTS->tm_mon, tTS->tm_mday, tTS->tm_hour, tTS->tm_min, tTS->tm_sec); - LOG(tB); -#endif - // WTF ??!! - tTS->tm_year -= 1900; - tTS->tm_mon -= 1; - - time_t tTimeStamp = timegm(tTS); // mktime( tTS ); - - m_nDeltaTime = time(NULL) - tTimeStamp; + // Device clock offset for the WS-Security Created timestamp (GetSystemDateAndTime needs no authentication). + // If the device does not report UTC time, use our own clock (offset 0) instead of failing. + m_nDeltaTime = 0; + struct tm * tTS = core_GetSystemDateAndTime(); + if (tTS != NULL) { + time_t tTimeStamp = timegm(tTS); + m_nDeltaTime = time(NULL) - tTimeStamp; #ifdef DEBUG - sprintf(tB, "TS:[%ld] D:[%ld]", tTimeStamp, m_nDeltaTime); - LOG(tB); + char tB[128]; + snprintf(tB, sizeof(tB), "Device UTC %04d-%02d-%02d %02d:%02d:%02d, offset %ld s", tTS->tm_year + 1900, tTS->tm_mon + 1, tTS->tm_mday, tTS->tm_hour, tTS->tm_min, + tTS->tm_sec, (long) m_nDeltaTime); + LOG(tB); #endif - free(tTS); - } else { - return false; - }; - } catch (const std::exception& e) { - LOG_ERROR("Catched Exception!"); - return false; + free(tTS); + } else { + LOG_ERROR("Device UTC time not available, using local clock for WS-Security timestamps"); }; -// Are we need that all at beginning? - if (! core_GetCapabilities()) { LOG_ERROR("Error Getting Caps!"); return false; }; _getOnvifVersion(m_sCapabilities); - // Update some Vars Online! - // preg_match("/^http(.*)onvif\//",$this->mediauri,$matches); - // m_pBaseURI = $matches[0]; if (media_GetVideoSources()){ if (media_GetProfiles()){ - //_getActiveSources( m_vVideoSources, m_vVideoProfiles); + if (m_vVideoProfiles.empty()) { + LOG_ERROR("Device has no media profiles!"); + return false; + }; return true; }; }; - LOG_ERROR("Error Profiles!"); + LOG_ERROR("Error Profiles!"); return false; } /* Public wrappers for a subset of ONVIF primitives */ +// Returns the device UTC time (malloc'ed, caller frees) or NULL if not available. +// UTCDateTime is optional in tt:SystemDateAndTime. struct tm * pOnvif::core_GetSystemDateAndTime(void) { - struct tm * RetVal = NULL; - char tURL[CTEXT]; + char tURL[CTEXT]; if (m_pDeviceURI != NULL) { - sprintf(tURL, m_pDeviceURI); + snprintf(tURL, sizeof(tURL), "%s", m_pDeviceURI); + } + else if (m_pIpAddress != NULL) + { + snprintf(tURL, sizeof(tURL), "http://%s/onvif/device_service", m_pIpAddress); } else { - if (m_pIpAddress != NULL) - { - sprintf(tURL, "http://%s/onvif/device_service", m_pIpAddress); - } - else - { - return NULL; - }; + return NULL; }; -#ifdef DEBUG_EXTRA - LOG("Before REQ"); -#endif - if (_send_request(tURL, PONVIF_PACK_GET_SYS_DTS, true)) + char tBuffer[DEFAULT_BUFFER_SIZE]; + // Pre-auth operation: never send a security header + snprintf(tBuffer, sizeof(tBuffer), "%s", PONVIF_PACK_GET_SYS_DTS); + if (! _send_request(tURL, tBuffer, true)) { - XMLResults tParseResults; - XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); -#ifdef DEBUG_EXTRA - LOG("core_GetSystemDateAndTime"); -#endif - if (tParseResults.error) - { - char tBuffer[CTEXT]; - sprintf(tBuffer, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); - LOG_ERROR(tBuffer); - } - else - { - RetVal = (struct tm *) malloc(sizeof(struct tm)); - if (RetVal != NULL) - { - memset(RetVal, 0, sizeof(struct tm)); - XMLNode zNode = response.getChildNode("Body", 0); - if (! zNode.isEmpty()) - { - XMLNode fNode = zNode.getChildNode("GetSystemDateAndTimeResponse", 0); - if (! fNode.isEmpty()) - { - XMLNode hNode = fNode.getChildNode("SystemDateAndTime", 0); - if (! hNode.isEmpty()) - { - XMLNode tNode = hNode.getChildNode("UTCDateTime", 0); - if (! tNode.isEmpty()) - { - RetVal->tm_isdst = 0; - XMLNode ttNode = tNode.getChildNode("Time", 0); - XMLNode dtNode = tNode.getChildNode("Date", 0); - { - XMLNode t = ttNode.getChildNode("Hour", 0); - RetVal->tm_hour = atoi(t.getText(0)); - } - { - XMLNode t = ttNode.getChildNode("Minute", 0); - RetVal->tm_min = atoi(t.getText(0)); - } - { - XMLNode t = ttNode.getChildNode("Second", 0); - RetVal->tm_sec = atoi(t.getText(0)); - } - { - XMLNode t = dtNode.getChildNode("Year", 0); - RetVal->tm_year = atoi(t.getText(0)); - } - { - XMLNode t = dtNode.getChildNode("Month", 0); - RetVal->tm_mon = atoi(t.getText(0)); - } - { - XMLNode t = dtNode.getChildNode("Day", 0); - RetVal->tm_mday = atoi(t.getText(0)); - } - } - else - { - LOG_ERROR("UTCDateTime is Not Found!"); - }; - } - else - { - LOG_ERROR("SystemDateAndTime is Not Found!"); - }; - } - else - { - LOG_ERROR("GetSystemDateAndTimeResponse is Not Found!"); - }; - } - else - { - LOG_ERROR("Body is Not Found!"); - LOG(m_pLastResponse); - }; - }; - return RetVal; - }; + LOG_ERROR("GetSystemDateAndTime: no valid answer"); + return NULL; } - else + XMLResults tParseResults; + XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); + if (tParseResults.error) { - LOG_ERROR("GetSystemDateAndTime: Communication error"); + char tBuf[CTEXT]; + snprintf(tBuf, sizeof(tBuf), "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); + LOG_ERROR(tBuf); + return NULL; } - return NULL; + XMLNode tNode = response.getChildNode("Body", 0).getChildNode("GetSystemDateAndTimeResponse", 0).getChildNode("SystemDateAndTime", 0).getChildNode("UTCDateTime", 0); + if (tNode.isEmpty()) + { + LOG_ERROR("UTCDateTime is Not Found!"); + return NULL; + } + XMLNode ttNode = tNode.getChildNode("Time", 0); + XMLNode dtNode = tNode.getChildNode("Date", 0); + int tYear = safeAtoi(dtNode.getChildNode("Year", 0).getText(0)); + int tMonth = safeAtoi(dtNode.getChildNode("Month", 0).getText(0)); + int tDay = safeAtoi(dtNode.getChildNode("Day", 0).getText(0)); + if (tYear < 1970 || tMonth < 1 || tMonth > 12 || tDay < 1 || tDay > 31) + { + LOG_ERROR("UTCDateTime is invalid!"); + return NULL; + } + struct tm * RetVal = (struct tm *) malloc(sizeof(struct tm)); + if (RetVal == NULL) + { + return NULL; + } + memset(RetVal, 0, sizeof(struct tm)); + RetVal->tm_year = tYear - 1900; + RetVal->tm_mon = tMonth - 1; + RetVal->tm_mday = tDay; + RetVal->tm_hour = safeAtoi(ttNode.getChildNode("Hour", 0).getText(0)); + RetVal->tm_min = safeAtoi(ttNode.getChildNode("Minute", 0).getText(0)); + RetVal->tm_sec = safeAtoi(ttNode.getChildNode("Second", 0).getText(0)); + RetVal->tm_isdst = 0; + return RetVal; } // Based on https://www.onvif.org/ver10/device/wsdl/devicemgmt.wsdl @@ -895,12 +887,10 @@ struct tm * pOnvif::core_GetSystemDateAndTime(void) bool pOnvif::core_GetCapabilities(void) { char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); char tURL[CTEXT]; if (m_pDeviceURI != NULL) { - sprintf(tURL, m_pDeviceURI); + snprintf(tURL, sizeof(tURL), "%s", m_pDeviceURI); } else { @@ -914,7 +904,7 @@ bool pOnvif::core_GetCapabilities(void) }; }; // char tSTR[CTEXT]; - sprintf(tBuffer, PONVIF_PACK_GET_CAPABILITIES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_CAPABILITIES); // sprintf( tSTR, PONVIF_PCK_GET_CAPABILITIES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP ); // build_package( tBuffer, PONVIF_ENVELOPE_SIM, tSTR ); if (_send_request(tURL, tBuffer)) @@ -923,7 +913,7 @@ bool pOnvif::core_GetCapabilities(void) XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); #ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES LOG("RCPT:"); - printf(m_pLastResponse); + printf("%s\n", m_pLastResponse); #endif if (tParseResults.error != eXMLErrorNone) { @@ -954,7 +944,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Analytics, 0, sizeof(onvifAnalyticsCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Analytics->XAddr, "%s", c.getText(0)); + safeCopy(m_sCapabilities.Analytics->XAddr, sizeof(m_sCapabilities.Analytics->XAddr), c.getText(0)); } { XMLNode c = t.getChildNode("RuleSupport", 0); @@ -977,7 +967,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Device, 0, sizeof(onvifDeviceCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Device->XAddr, "%s", c.getText(0)); + safeCopy(m_sCapabilities.Device->XAddr, sizeof(m_sCapabilities.Device->XAddr), c.getText(0)); } { XMLNode c = t.getChildNode("Network", 0); @@ -1063,11 +1053,11 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Device->System->SupportedVersions, 0, sizeof(onvifSupportedVersions)); { XMLNode x = n.getChildNode("Major", 0); - m_sCapabilities.Device->System->SupportedVersions->Major = atoi(x.getText(0)); + m_sCapabilities.Device->System->SupportedVersions->Major = safeAtoi(x.getText(0)); } { XMLNode x = n.getChildNode("Minor", 0); - m_sCapabilities.Device->System->SupportedVersions->Minor = atoi(x.getText(0)); + m_sCapabilities.Device->System->SupportedVersions->Minor = safeAtoi(x.getText(0)); } }; }; @@ -1112,11 +1102,11 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Device->IO, 0, sizeof(onvifIOCapabilities)); { XMLNode n = c.getChildNode("InputConnectors", 0); - m_sCapabilities.Device->IO->InputConnectors = atoi(n.getText(0)); + m_sCapabilities.Device->IO->InputConnectors = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("RelayOutputs", 0); - m_sCapabilities.Device->IO->RelayOutputs = atoi(n.getText(0)); + m_sCapabilities.Device->IO->RelayOutputs = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("Extension", 0); @@ -1207,7 +1197,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Events, 0, sizeof(onvifEventCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Events->XAddr, "%s", c.getText(0)); + safeCopy(m_sCapabilities.Events->XAddr, sizeof(m_sCapabilities.Events->XAddr), c.getText(0)); } { XMLNode c = t.getChildNode("WSSubscriptionPolicySupport", 0); @@ -1234,7 +1224,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Imaging, 0, sizeof(onvifImagingCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Imaging->XAddr, "%s", c.getText(0)); + safeCopy(m_sCapabilities.Imaging->XAddr, sizeof(m_sCapabilities.Imaging->XAddr), c.getText(0)); } }; }; @@ -1249,7 +1239,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Media, 0, sizeof(onvifMediaCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Media->XAddr, "%s", c.getText(0)); + safeCopy(m_sCapabilities.Media->XAddr, sizeof(m_sCapabilities.Media->XAddr), c.getText(0)); } { XMLNode c = t.getChildNode("StreamingCapabilities", 0); @@ -1292,7 +1282,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Media->Extension->ProfileCapabilities, 0, sizeof(onvifProfileCapabilities)); { XMLNode x = n.getChildNode("MaximumNumberOfProfiles", 0); - m_sCapabilities.Media->Extension->ProfileCapabilities->MaximumNumberOfProfiles = atoi(x.getText(0)); + m_sCapabilities.Media->Extension->ProfileCapabilities->MaximumNumberOfProfiles = safeAtoi(x.getText(0)); } }; }; @@ -1313,7 +1303,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.PTZ, 0, sizeof(onvifPTZCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.PTZ->XAddr, "%s", c.getText(0)); + safeCopy(m_sCapabilities.PTZ->XAddr, sizeof(m_sCapabilities.PTZ->XAddr), c.getText(0)); } }; }; @@ -1336,27 +1326,27 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Extension->DeviceIO, 0, sizeof(onvifDeviceIOCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Extension->DeviceIO->XAddr, "%s", n.getText(0)); + safeCopy(m_sCapabilities.Extension->DeviceIO->XAddr, sizeof(m_sCapabilities.Extension->DeviceIO->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("VideoSources", 0); - m_sCapabilities.Extension->DeviceIO->VideoSources = atoi(n.getText(0)); + m_sCapabilities.Extension->DeviceIO->VideoSources = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("VideoOutputs", 0); - m_sCapabilities.Extension->DeviceIO->VideoOutputs = atoi(n.getText(0)); + m_sCapabilities.Extension->DeviceIO->VideoOutputs = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("AudioSources", 0); - m_sCapabilities.Extension->DeviceIO->AudioSources = atoi(n.getText(0)); + m_sCapabilities.Extension->DeviceIO->AudioSources = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("AudioOutputs", 0); - m_sCapabilities.Extension->DeviceIO->AudioOutputs = atoi(n.getText(0)); + m_sCapabilities.Extension->DeviceIO->AudioOutputs = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("RelayOutputs", 0); - m_sCapabilities.Extension->DeviceIO->RelayOutputs = atoi(n.getText(0)); + m_sCapabilities.Extension->DeviceIO->RelayOutputs = safeAtoi(n.getText(0)); } }; }; @@ -1371,7 +1361,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Extension->Display, 0, sizeof(onvifDisplayCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Extension->Display->XAddr, "%s", n.getText(0)); + safeCopy(m_sCapabilities.Extension->Display->XAddr, sizeof(m_sCapabilities.Extension->Display->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("FixedLayout", 0); @@ -1390,7 +1380,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Extension->Recording, 0, sizeof(onvifRecordingCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Extension->Recording->XAddr, "%s", n.getText(0)); + safeCopy(m_sCapabilities.Extension->Recording->XAddr, sizeof(m_sCapabilities.Extension->Recording->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("ReceiverSource", 0); @@ -1410,7 +1400,7 @@ bool pOnvif::core_GetCapabilities(void) } { XMLNode n = c.getChildNode("MaxStringLength", 0); - m_sCapabilities.Extension->Recording->MaxStringLength = atoi(n.getText(0)); + m_sCapabilities.Extension->Recording->MaxStringLength = safeAtoi(n.getText(0)); } }; }; @@ -1425,7 +1415,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Extension->Search, 0, sizeof(onvifSearchCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Extension->Search->XAddr, "%s", n.getText(0)); + safeCopy(m_sCapabilities.Extension->Search->XAddr, sizeof(m_sCapabilities.Extension->Search->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("MetadataSearch", 0); @@ -1444,7 +1434,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Extension->Replay, 0, sizeof(onvifReplayCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Extension->Replay->XAddr, "%s", n.getText(0)); + safeCopy(m_sCapabilities.Extension->Replay->XAddr, sizeof(m_sCapabilities.Extension->Replay->XAddr), n.getText(0)); } }; }; @@ -1459,7 +1449,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Extension->Receiver, 0, sizeof(onvifReceiverCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Extension->Receiver->XAddr, "%s", n.getText(0)); + safeCopy(m_sCapabilities.Extension->Receiver->XAddr, sizeof(m_sCapabilities.Extension->Receiver->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("RTP_Multicast", 0); @@ -1475,11 +1465,11 @@ bool pOnvif::core_GetCapabilities(void) } { XMLNode n = c.getChildNode("SupportedReceivers", 0); - m_sCapabilities.Extension->Receiver->SupportedReceivers = atoi(n.getText(0)); + m_sCapabilities.Extension->Receiver->SupportedReceivers = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("MaximumRTSPURILength", 0); - m_sCapabilities.Extension->Receiver->MaximumRTSPURILength = atoi(n.getText(0)); + m_sCapabilities.Extension->Receiver->MaximumRTSPURILength = safeAtoi(n.getText(0)); } }; }; @@ -1494,7 +1484,7 @@ bool pOnvif::core_GetCapabilities(void) memset(m_sCapabilities.Extension->AnalyticsDevice, 0, sizeof(onvifAnalyticsDeviceCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); - sprintf(m_sCapabilities.Extension->AnalyticsDevice->XAddr, "%s", n.getText(0)); + safeCopy(m_sCapabilities.Extension->AnalyticsDevice->XAddr, sizeof(m_sCapabilities.Extension->AnalyticsDevice->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("RuleSupport", 0); @@ -1531,16 +1521,14 @@ bool pOnvif::media_GetVideoSources(void) return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_GET_VIDEO_SOURCES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_VIDEO_SOURCES); if (_send_request(m_pMediaURI, tBuffer)) { XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); #ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES LOG("RCPT:"); - printf(m_pLastResponse); + printf("%s\n", m_pLastResponse); #endif if (tParseResults.error) { @@ -1567,10 +1555,12 @@ bool pOnvif::media_GetVideoSources(void) tPtr = (videoSource *) malloc(sizeof(videoSource)); if (tPtr != NULL) { - sprintf(tPtr->token, "%s", cNode.getAttribute("token", 0)); + // Imaging / Extension are optional: must be NULL when the device leaves them out + memset(tPtr, 0, sizeof(videoSource)); + safeCopy(tPtr->token, sizeof(tPtr->token), cNode.getAttribute("token", 0)); { XMLNode nNode = cNode.getChildNode("Framerate", 0); - tPtr->Framerate = (float) atof(nNode.getText(0)); + tPtr->Framerate = safeAtof(nNode.getText(0)); } { XMLNode nNode = cNode.getChildNode("Resolution", 0); @@ -1578,11 +1568,11 @@ bool pOnvif::media_GetVideoSources(void) { { XMLNode xNode = nNode.getChildNode("Width", 0); - tPtr->Resolution.Width = atoi(xNode.getText(0)); + tPtr->Resolution.Width = safeAtoi(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("Height", 0); - tPtr->Resolution.Height = atoi(xNode.getText(0)); + tPtr->Resolution.Height = safeAtoi(xNode.getText(0)); } }; } @@ -1608,26 +1598,26 @@ bool pOnvif::media_GetVideoSources(void) } { XMLNode rNode = xNode.getChildNode("Level", 0); - tPtr->Imaging->BacklightCompensation->Level = (float) atof(rNode.getText(0)); + tPtr->Imaging->BacklightCompensation->Level = safeAtof(rNode.getText(0)); } }; }; } { XMLNode xNode = nNode.getChildNode("Brightness", 0); - tPtr->Imaging->Brightness = (float) atoi(xNode.getText(0)); + tPtr->Imaging->Brightness = safeAtof(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("ColorSaturation", 0); - tPtr->Imaging->ColorSaturation = (float) atoi(xNode.getText(0)); + tPtr->Imaging->ColorSaturation = safeAtof(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("Contrast", 0); - tPtr->Imaging->Contrast = (float) atoi(xNode.getText(0)); + tPtr->Imaging->Contrast = safeAtof(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("Sharpness", 0); - tPtr->Imaging->Sharpness = (float) atoi(xNode.getText(0)); + tPtr->Imaging->Sharpness = safeAtof(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("IrCutFilter", 0); @@ -1658,16 +1648,14 @@ bool pOnvif::media_GetVideoSources(void) bool pOnvif::media_GetProfiles(void) { char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_GET_PROFILES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_PROFILES); if (_send_request(m_pMediaURI, tBuffer)) { XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); #ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES LOG("RCPT:"); - printf(m_pLastResponse); + printf("%s\n", m_pLastResponse); #endif if (tParseResults.error) { @@ -1695,17 +1683,17 @@ bool pOnvif::media_GetProfiles(void) if (tPtr != NULL) { memset(tPtr, 0, sizeof(videoSourceProfile)); - sprintf(tPtr->profiletoken, "%s", cNode.getAttribute("token", 0)); + safeCopy(tPtr->profiletoken, sizeof(tPtr->profiletoken), cNode.getAttribute("token", 0)); { XMLNode nNode = cNode.getChildNode("Name", 0); - sprintf(tPtr->profilename, "%s", nNode.getText(0)); + safeCopy(tPtr->profilename, sizeof(tPtr->profilename), nNode.getText(0)); } { XMLNode nNode = cNode.getChildNode("VideoSourceConfiguration", 0); if (! nNode.isEmpty()) { XMLNode zNode = nNode.getChildNode("SourceToken", 0); - sprintf(tPtr->sourcetoken, "%s", zNode.getText(0)); + safeCopy(tPtr->sourcetoken, sizeof(tPtr->sourcetoken), zNode.getText(0)); }; } { @@ -1714,32 +1702,41 @@ bool pOnvif::media_GetProfiles(void) { { XMLNode zNode = nNode.getChildNode("Encoding", 0); - sprintf(tPtr->encoding, "%s", zNode.getText(0)); + safeCopy(tPtr->encoding, sizeof(tPtr->encoding), zNode.getText(0)); } { XMLNode zNode = nNode.getChildNode("Resolution", 0); { XMLNode jNode = zNode.getChildNode("Width", 0); - tPtr->width = atoi(jNode.getText(0)); + tPtr->width = safeAtoi(jNode.getText(0)); } { XMLNode jNode = zNode.getChildNode("Height", 0); - tPtr->height = atoi(jNode.getText(0)); + tPtr->height = safeAtoi(jNode.getText(0)); } } { XMLNode zNode = nNode.getChildNode("RateControl", 0); { XMLNode jNode = zNode.getChildNode("FrameRateLimit", 0); - tPtr->fps = atoi(jNode.getText(0)); + tPtr->fps = safeAtoi(jNode.getText(0)); } { XMLNode jNode = zNode.getChildNode("BitrateLimit", 0); - tPtr->bitrate = atoi(jNode.getText(0)); + tPtr->bitrate = safeAtoi(jNode.getText(0)); } } }; } + { + // PTZ operations need a profile that contains a PTZConfiguration + XMLNode nNode = cNode.getChildNode("PTZConfiguration", 0); + if (! nNode.isEmpty()) + { + tPtr->ptz = true; + safeCopy(tPtr->ptznodetoken, sizeof(tPtr->ptznodetoken), nNode.getChildNode("NodeToken", 0).getText(0)); + }; + } m_vVideoProfiles.push_back(tPtr); }; }; @@ -1754,15 +1751,14 @@ bool pOnvif::media_GetProfiles(void) bool pOnvif::media_GetServices(void) { char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_GET_SERVICES, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); - if (_send_request(m_pMediaURI, tBuffer)) + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_SERVICES); + // Device service operation: goes to the device service, not to the media service + if (_send_request(m_pDeviceURI, tBuffer)) { XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); LOG("RCPT:"); - printf(m_pLastResponse); + printf("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; @@ -1779,15 +1775,14 @@ bool pOnvif::media_GetServices(void) bool pOnvif::core_GetDeviceInformation() { char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_GET_DEV_INFO, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); - if (_send_request(m_pMediaURI, tBuffer)) + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_DEV_INFO); + // Device service operation: goes to the device service, not to the media service + if (_send_request(m_pDeviceURI, tBuffer)) { XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); LOG("RCPT:"); - printf(m_pLastResponse); + printf("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; @@ -1805,15 +1800,13 @@ bool pOnvif::core_GetDeviceInformation() CSTR pOnvif::media_GetStreamUri(CSTR profileToken, CSTR stream, CSTR protocol) { char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_GET_STREAM_URI, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, stream, protocol, profileToken); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_STREAM_URI, xesc(stream).c_str(), xesc(protocol).c_str(), xesc(profileToken).c_str()); if (_send_request(m_pMediaURI, tBuffer)) { XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); LOG("RCPT:"); - printf(m_pLastResponse); + printf("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; @@ -1832,15 +1825,13 @@ CSTR pOnvif::media_GetStreamUri(CSTR profileToken, CSTR stream, CSTR protocol) CSTR pOnvif::media_GetSnapshotUri(CSTR profileToken) { char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_GET_PICTURE_URI, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_SNAPSHOT_URI, xesc(profileToken).c_str()); if (_send_request(m_pMediaURI, tBuffer)) { XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); LOG("RCPT:"); - printf(m_pLastResponse); + printf("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; @@ -1898,10 +1889,8 @@ bool pOnvif::ptz_GetStatus(CSTR profileToken, ptzStatus * tStatus) return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); memset(tStatus, 0, sizeof(ptzStatus)); - sprintf(tBuffer, PONVIF_PACK_GET_PTZ_STATUS, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_PTZ_STATUS, xesc(profileToken).c_str()); if (! _send_request(m_pPTZURI, tBuffer, true)) { return false; @@ -1988,9 +1977,7 @@ bool pOnvif::ptz_GetServiceCapabilities(int8_t * moveStatus, int8_t * statusPosi return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_PTZ_GET_SERVICE_CAPS, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_PTZ_GET_SERVICE_CAPS); if (! _send_request(m_pPTZURI, tBuffer, true)) { return false; @@ -2037,9 +2024,7 @@ bool pOnvif::ptz_GetPresets(CSTR profileToken) return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_GET_PRESETS, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_PRESETS, xesc(profileToken).c_str()); if (_send_request(m_pPTZURI, tBuffer)) { // XMLResults tParseResults; @@ -2072,15 +2057,13 @@ bool pOnvif::ptz_GetNode(CSTR ptzNodeToken) return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_GET_PTZ_NODE, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, ptzNodeToken); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_PTZ_NODE, xesc(ptzNodeToken).c_str()); if (_send_request(m_pPTZURI, tBuffer)) { XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); LOG("RCPT:"); - printf(m_pLastResponse); + printf("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; @@ -2102,9 +2085,7 @@ bool pOnvif::ptz_GotoPreset(CSTR profileToken, CSTR presetToken, float speed_pan return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_GOTO_PRESET, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, presetToken, speed_pantilt_x, speed_pantilt_y, speed_zoom_x); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GOTO_PRESET, xesc(profileToken).c_str(), xesc(presetToken).c_str(), speed_pantilt_x, speed_pantilt_y, speed_zoom_x); return _send_request(m_pPTZURI, tBuffer, true); } @@ -2115,9 +2096,7 @@ bool pOnvif::ptz_RemovePreset(CSTR profileToken, CSTR presetToken) return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_REMOVE_PRESET, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, presetToken); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_REMOVE_PRESET, xesc(profileToken).c_str(), xesc(presetToken).c_str()); return _send_request(m_pPTZURI, tBuffer, true); } @@ -2128,9 +2107,7 @@ bool pOnvif::ptz_SetPreset(CSTR profileToken, CSTR presetName) return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_SET_PRESET, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, presetName); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_SET_PRESET, xesc(profileToken).c_str(), xesc(presetName).c_str()); return _send_request(m_pPTZURI, tBuffer, true); } @@ -2141,9 +2118,7 @@ bool pOnvif::ptz_RelativeMove(CSTR profileToken, float translation_pantilt_x, fl return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_RELATIVE_MOVE, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, translation_pantilt_x, translation_pantilt_y, speed_pantilt_x, speed_pantilt_y); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_RELATIVE_MOVE, xesc(profileToken).c_str(), translation_pantilt_x, translation_pantilt_y, speed_pantilt_x, speed_pantilt_y); return _send_request(m_pPTZURI, tBuffer, true); } @@ -2154,9 +2129,7 @@ bool pOnvif::ptz_RelativeMoveZoom(CSTR profileToken, float zoom, float speedZoom return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_RELATIVE_ZOOM, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, zoom, speedZoom); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_RELATIVE_ZOOM, xesc(profileToken).c_str(), zoom, speedZoom); return _send_request(m_pPTZURI, tBuffer, true); } @@ -2167,49 +2140,72 @@ bool pOnvif::ptz_AbsoluteMove(CSTR profileToken, float position_pantilt_x, float return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_ABSOLUTE_MOVE, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, position_pantilt_x, position_pantilt_y, zoom); - return _send_request(m_pPTZURI, tBuffer, false); + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_ABSOLUTE_MOVE, xesc(profileToken).c_str(), position_pantilt_x, position_pantilt_y, zoom); + // Wait for the answer so that a SOAP Fault (e.g. position out of range) is detected + return _send_request(m_pPTZURI, tBuffer, true); } bool pOnvif::ptz_ContinuousMove(CSTR profileToken, float velocity_pantilt_x, float velocity_pantilt_y) { - if (m_pPTZURI == NULL) - { - return false; - } - char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_CONTINUOUS_MOVE, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, velocity_pantilt_x, velocity_pantilt_y); - return _send_request(m_pPTZURI, tBuffer, true); + return ptz_ContinuousMoveAll(profileToken, true, velocity_pantilt_x, velocity_pantilt_y, false, 0.0f); } bool pOnvif::ptz_ContinuousMoveZoom(CSTR profileToken, float zoom) +{ + return ptz_ContinuousMoveAll(profileToken, false, 0.0f, 0.0f, true, zoom); +} + +/* + One ContinuousMove for all requested axes. Sending pan/tilt and zoom as two requests is not safe: the + spec does not say that a second ContinuousMove keeps the motion of the axis it leaves out. + The Timeout makes the camera stop by itself if the Stop request is lost. +*/ +bool pOnvif::ptz_ContinuousMoveAll(CSTR profileToken, bool hasPanTilt, float velocity_pantilt_x, float velocity_pantilt_y, bool hasZoom, float velocity_zoom, + int timeoutSec) { if (m_pPTZURI == NULL) { return false; } - char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_CONTINUOUS_ZOOM, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken, zoom); + if (! hasPanTilt && ! hasZoom) + { + return true; + } + char tBody[1024]; + int tLen = snprintf(tBody, sizeof(tBody), PONVIF_BODY_CONTINUOUS_MOVE_BEGIN, xesc(profileToken).c_str()); + if (hasPanTilt && tLen > 0 && tLen < (int) sizeof(tBody)) + { + tLen += snprintf(tBody + tLen, sizeof(tBody) - tLen, PONVIF_BODY_CONTINUOUS_MOVE_PT, velocity_pantilt_x, velocity_pantilt_y); + } + if (hasZoom && tLen > 0 && tLen < (int) sizeof(tBody)) + { + tLen += snprintf(tBody + tLen, sizeof(tBody) - tLen, PONVIF_BODY_CONTINUOUS_MOVE_ZOOM, velocity_zoom); + } + if (tLen > 0 && tLen < (int) sizeof(tBody)) + { + tLen += snprintf(tBody + tLen, sizeof(tBody) - tLen, PONVIF_BODY_CONTINUOUS_MOVE_END, (timeoutSec > 0) ? timeoutSec : PONVIF_CONTINUOUS_MOVE_TIMEOUT_S); + } + if (tLen <= 0 || tLen >= (int) sizeof(tBody)) + { + LOG_ERROR("ContinuousMove request too long!"); + return false; + } + char tBuffer[DEFAULT_BUFFER_SIZE]; + if (! _buildRequest(tBuffer, sizeof(tBuffer), "%s", tBody)) + { + return false; + } return _send_request(m_pPTZURI, tBuffer, true); } bool pOnvif::ptz_Stop(CSTR profileToken, bool pantilt, bool zoom) { - if ( pantilt || zoom ) profileToken = profileToken; - if (m_pPTZURI == NULL) + if (m_pPTZURI == NULL) { return false; } - char tBuffer[DEFAULT_BUFFER_SIZE]; - accessToken tTOKEN; - tTOKEN = _makeToken(); - sprintf(tBuffer, PONVIF_PACK_PTZ_STOP, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP, profileToken); //, pantilt, zoom ); + char tBuffer[DEFAULT_BUFFER_SIZE]; + _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_PTZ_STOP, xesc(profileToken).c_str(), pantilt ? "true" : "false", zoom ? "true" : "false"); return _send_request(m_pPTZURI, tBuffer, true); } @@ -2235,15 +2231,16 @@ void pOnvif::_getOnvifVersion(nodeCapability & caps) }; }; }; - if (caps.PTZ != NULL) + // Only use service addresses the device actually reported + if (caps.PTZ != NULL && caps.PTZ->XAddr[0] != (char) 0) { m_pPTZURI = caps.PTZ->XAddr; }; - if (caps.Media != NULL) + if (caps.Media != NULL && caps.Media->XAddr[0] != (char) 0) { m_pMediaURI = caps.Media->XAddr; }; - if (caps.Device != NULL) + if (caps.Device != NULL && caps.Device->XAddr[0] != (char) 0) { m_pDeviceURI = caps.Device->XAddr; }; @@ -2315,79 +2312,217 @@ protected function _xml2array($response) { } */ -accessToken pOnvif::_passwordDigest(CSTR username, CSTR password, time_t timestamp, uint32_t nonce) +/* + WS-Security UsernameToken (OASIS UsernameToken Profile 1.0, PasswordDigest): + Digest = Base64( SHA1( nonce_bytes + Created + password ) ) + The nonce is PONVIF_NONCE_LEN random bytes (OpenSSL RAND_bytes): a short or repeating nonce can be + rejected by devices that keep a nonce cache against replays. +*/ +accessToken pOnvif::_passwordDigest(CSTR username, CSTR password, time_t timestamp) { - accessToken RetVal; - char tTS[CTEXT]; - unsigned char * tPDIGEST; + accessToken RetVal; + memset(&RetVal, 0, sizeof(RetVal)); if (timestamp == 0) { - time_t t; - struct tm * tmp; - t = time(NULL); - tmp = gmtime(&t); - if (tmp == NULL) - { - LOG_ERROR("gmtime Error!"); - }; - if (strftime(tTS, 200, "%FT%TZ", tmp) == 0) + timestamp = time(NULL); + } + struct tm tTM; + if (gmtime_r(×tamp, &tTM) == NULL || strftime(RetVal.TIMESTAMP, sizeof(RetVal.TIMESTAMP), "%Y-%m-%dT%H:%M:%SZ", &tTM) == 0) + { + LOG_ERROR("Cannot format the WS-Security timestamp!"); + RetVal.TIMESTAMP[0] = (char) 0; + }; + unsigned char tNonce[PONVIF_NONCE_LEN]; + if (RAND_bytes(tNonce, sizeof(tNonce)) != 1) + { + // Should not happen; keep going with a weaker nonce rather than not authenticating at all + for (size_t i = 0; i < sizeof(tNonce); i++) { - LOG_ERROR("strftime returned 0!"); - }; + tNonce[i] = (unsigned char) (rand() & 0xFF); + } + }; + const char * tPass = (password != NULL) ? password : ""; + size_t tTSLen = strlen(RetVal.TIMESTAMP); + size_t tPWLen = strlen(tPass); + size_t tLen = sizeof(tNonce) + tTSLen + tPWLen; + unsigned char * tBuff = (unsigned char *) malloc(tLen); + if (tBuff == NULL) + { + LOG_ERROR("Memory Allocation Error!"); + return RetVal; + } + memcpy(tBuff, tNonce, sizeof(tNonce)); + memcpy(tBuff + sizeof(tNonce), RetVal.TIMESTAMP, tTSLen); + memcpy(tBuff + sizeof(tNonce) + tTSLen, tPass, tPWLen); + unsigned char tSHA[SHA_DIGEST_LENGTH]; + SHA1(tBuff, tLen, tSHA); + memset(tBuff, 0, tLen); // contains the password + free(tBuff); + + size_t baseOutLen = 0; + unsigned char * tB64 = base64_encode(tSHA, SHA_DIGEST_LENGTH, &baseOutLen); + if (tB64) + { + snprintf(RetVal.PASSDIGEST, sizeof(RetVal.PASSDIGEST), "%.*s", (int) baseOutLen, (const char *) tB64); + free(tB64); } - else + tB64 = base64_encode(tNonce, sizeof(tNonce), &baseOutLen); + if (tB64) { - struct tm * tmp; - tmp = gmtime(×tamp); - if (tmp == NULL) + snprintf(RetVal.NONCE, sizeof(RetVal.NONCE), "%.*s", (int) baseOutLen, (const char *) tB64); + free(tB64); + } + // The user name goes into the XML header: escape it + _xmlEscape((username != NULL) ? username : "", RetVal.USERNAME, sizeof(RetVal.USERNAME)); + return RetVal; +} + +bool pOnvif::_hasCredentials(void) +{ + return (m_pUsername != NULL && m_pUsername[0] != (char) 0); +} + +char * pOnvif::_xmlEscape(const char * src, char * dst, size_t dstSize) +{ + if (dst == NULL || dstSize == 0) + { + return dst; + } + size_t o = 0; + for (const char * c = (src != NULL) ? src : ""; *c; c++) + { + const char * rep = NULL; + switch (*c) { - LOG_ERROR("gmtime Error!"); + case '&' : rep = "&"; break; + case '<' : rep = "<"; break; + case '>' : rep = ">"; break; + case '"' : rep = """; break; + case '\'': rep = "'"; break; + default : break; }; - if (strftime(tTS, 200, "%FT%TZ", tmp) == 0) + size_t l = (rep != NULL) ? strlen(rep) : 1; + if (o + l >= dstSize) { - LOG_ERROR("strftime returned 0!"); - }; + break; // truncate, never split an entity + } + if (rep != NULL) + { + memcpy(dst + o, rep, l); + } + else + { + dst[o] = *c; + } + o += l; }; - if (nonce == 0) + dst[o] = (char) 0; + return dst; +} + +/* + SOAP 1.2 envelope + WS-Security UsernameToken header (only when a user name is set: ONVIF allows + anonymous access, and an empty token would be rejected) + body. +*/ +bool pOnvif::_buildRequest(char * out, size_t outSize, const char * bodyFmt, ...) +{ + if (out == NULL || outSize == 0) { - nonce = (uint32_t) rand(); - }; - unsigned char tBuff[CTEXT]; - int cp = 0; - int index = 0; - for (; index < 4; index++) + return false; + } + out[0] = (char) 0; + int tLen = snprintf(out, outSize, ""); + if (_hasCredentials() && tLen > 0 && tLen < (int) outSize) { - tBuff[cp++] = ((unsigned char *) (&nonce))[index]; + accessToken tTOKEN = _makeToken(); + tLen += snprintf(out + tLen, outSize - tLen, PONVIF_HEADER_SECUR, tTOKEN.USERNAME, tTOKEN.PASSDIGEST, tTOKEN.NONCE, tTOKEN.TIMESTAMP); + } + if (tLen > 0 && tLen < (int) outSize) + { + tLen += snprintf(out + tLen, outSize - tLen, ""); + } + if (tLen > 0 && tLen < (int) outSize) + { + va_list ap; + va_start(ap, bodyFmt); + tLen += vsnprintf(out + tLen, outSize - tLen, bodyFmt, ap); + va_end(ap); + } + if (tLen > 0 && tLen < (int) outSize) + { + tLen += snprintf(out + tLen, outSize - tLen, ""); + } + if (tLen <= 0 || tLen >= (int) outSize) + { + LOG_ERROR("Request does not fit into the buffer!"); + out[0] = (char) 0; + return false; + } + return true; +} + +/* + A reply was received: check HTTP status and SOAP Fault. Devices answer a failed operation with a + SOAP Fault (normally HTTP 400/500), e.g. ter:NotAuthorized, ter:InvalidArgVal, ter:NoProfile. +*/ +bool pOnvif::_checkReply(void) +{ + m_cLastFault[0] = (char) 0; + long tHttp = m_nLastHttpCode; + if (m_pLastResponse != NULL && strstr(m_pLastResponse, "Fault") != NULL) + { + XMLResults tParseResults; + XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); + XMLNode tFault = response.getChildNode("Body", 0).getChildNode("Fault", 0); + if (! tFault.isEmpty()) + { + XMLNode tCode = tFault.getChildNode("Code", 0); + const char * tValue = tCode.getChildNode("Value", 0).getText(0); + const char * tSubcode = tCode.getChildNode("Subcode", 0).getChildNode("Value", 0).getText(0); + const char * tSubSub = tCode.getChildNode("Subcode", 0).getChildNode("Subcode", 0).getChildNode("Value", 0).getText(0); + const char * tReason = tFault.getChildNode("Reason", 0).getChildNode("Text", 0).getText(0); + snprintf(m_cLastFault, sizeof(m_cLastFault), "%s%s%s%s%s: %s", tValue ? tValue : "?", tSubcode ? " / " : "", tSubcode ? tSubcode : "", tSubSub ? " / " : "", + tSubSub ? tSubSub : "", tReason ? tReason : ""); + m_eLastError = PONVIF_ERR_FAULT; + char tB[CTEXT + 64]; + snprintf(tB, sizeof(tB), "SOAP Fault [HTTP %ld] %s", tHttp, m_cLastFault); + LOG_ERROR(tB); + return false; + }; }; - index = 0; - while (tTS[index] != '\0') + if (tHttp != 200 && tHttp != 0) { - tBuff[cp++] = (unsigned char) tTS[index]; - index++; + m_eLastError = PONVIF_ERR_HTTP; + snprintf(m_cLastFault, sizeof(m_cLastFault), "HTTP %ld", tHttp); + char tB[64]; + snprintf(tB, sizeof(tB), "HTTP error %ld", tHttp); + LOG_ERROR(tB); + return false; }; - index = 0; - while (password[index] != '\0') + m_eLastError = PONVIF_OK; + return true; +} + +onvifError pOnvif::getLastError(void) +{ + return m_eLastError; +} + +CSTR pOnvif::getLastFault(void) +{ + return m_cLastFault; +} + +videoSourceProfile * pOnvif::getPTZProfile(void) +{ + for (videoSourceProfiles::iterator idx = m_vVideoProfiles.begin(); idx != m_vVideoProfiles.end(); idx++) { - tBuff[cp++] = (unsigned char) password[index]; - index++; + if ((*idx)->ptz) + { + return *idx; + } }; - size_t baseOutLen; - unsigned char tSHA[SHA_DIGEST_LENGTH]; - SHA1(tBuff, cp, tSHA); - // tPDIGEST = base64_encode(pack('H*', sha1(pack('H*', $nonce) . pack('a*',$timestamp).pack('a*',$password)))); - tPDIGEST = base64_encode(tSHA, SHA_DIGEST_LENGTH, &baseOutLen); - // free( tSHA ); - //$passdigest=base64_encode(sha1($nonce.$timestamp.$password,true)); // alternative - strncpy(RetVal.USERNAME, username, CTEXT); - strncpy(RetVal.TIMESTAMP, tTS, CTEXT); - strncpy(RetVal.PASSDIGEST, (const char *) tPDIGEST, CTEXT); - free(tPDIGEST); - tPDIGEST = base64_encode((unsigned char *) &nonce, 4, &baseOutLen); - strncpy(RetVal.NONCE, (const char *) tPDIGEST, baseOutLen); - RetVal.NONCE[baseOutLen] = '\0'; - free(tPDIGEST); - //$REQ['NONCE']=base64_encode($nonce); // alternative - return RetVal; + return NULL; } void * pOnvif::parser(void * obj, void * ptr) @@ -2405,6 +2540,12 @@ void * pOnvif::parser(void * obj, void * ptr) ME->m_mParserLock.unlock(); return NULL; }; + long tHttp = 0; + if (RQ->getEH() != NULL) + { + curl_easy_getinfo(RQ->getEH(), CURLINFO_RESPONSE_CODE, &tHttp); + } + ME->m_nLastHttpCode = tHttp; if (ME->m_pLastResponse) { free(ME->m_pLastResponse); @@ -2432,12 +2573,18 @@ void * pOnvif::parser(void * obj, void * ptr) bool pOnvif::_send_request(CSTR url, CSTR post_string, bool mustReturnData) { #ifdef CURL_MANAGER - bool RetVal = false; + bool RetVal = false; + m_eLastError = PONVIF_ERR_COMM; + if (url == NULL || url[0] == (char) 0 || post_string == NULL) + { + LOG_ERROR("No service URL!"); + return false; + } if (m_pHttpAccessManager) { m_mResponseProtector.lock(); - curlRequest * tRC; // application/soap+xml; charset=utf-8; action="http://www.onvif.org/ver10/device/wsdl/GetSystemDateAndTime" - tRC = new curlRequest(url, (CSTR) "application/soap+xml; charset=utf-8;"); + curlRequest * tRC; + tRC = new curlRequest(url, (CSTR) "application/soap+xml; charset=utf-8"); if (tRC != NULL) { #ifdef DEBUG_ONVIF_TRAFFIC @@ -2450,7 +2597,14 @@ bool pOnvif::_send_request(CSTR url, CSTR post_string, bool mustReturnData) fclose(tf); mustReturnData = true; // In Debug Allways Read Return #endif - tRC->setCredentials(m_pUsername, m_pPassword, m_bAuthMode); + // HTTP authentication only if credentials are set (anonymous devices are allowed by ONVIF). + // Mode 0 (default): CURLAUTH_ANY - the request is sent without credentials first and curl answers + // the challenge the device sends (Digest preferred, Basic only if the device asks for it), + // so the password is never sent in clear unless the device requires Basic. + if (_hasCredentials() && m_pPassword != NULL && m_pPassword[0] != (char) 0) + { + tRC->setCredentials(m_pUsername, m_pPassword, (m_bAuthMode == 0) ? 7 : m_bAuthMode); + } tRC->setPOST(post_string, strlen(post_string)); if (mustReturnData) { @@ -2478,6 +2632,14 @@ bool pOnvif::_send_request(CSTR url, CSTR post_string, bool mustReturnData) m_mParserLock.lock(); m_pPendingRequest = NULL; m_mParserLock.unlock(); + if (RetVal) + { + RetVal = _checkReply(); + } + else + { + m_eLastError = PONVIF_ERR_COMM; + }; } else { @@ -2597,7 +2759,7 @@ bool pOnvif::setAuthMode(uint8_t Mode) #ifdef DEBUG switch (m_bAuthMode) { - case 0 : LOG("Set Auth CURLAUTH_BASIC"); break; + case 0 : LOG("Set Auth default (CURLAUTH_ANY: answer the device's challenge)"); break; case 1 : LOG("Set Auth CURLAUTH_DIGEST"); break; case 2 : LOG("Set Auth CURLAUTH_DIGEST_IE"); break; case 3 : LOG("Set Auth CURLAUTH_BEARER"); break; diff --git a/lib/data/ponvif/ponvif.h b/lib/data/ponvif/ponvif.h index c83fc99c..91e569ce 100644 --- a/lib/data/ponvif/ponvif.h +++ b/lib/data/ponvif/ponvif.h @@ -34,49 +34,59 @@ (CSTR)"uuid:84ede3de-7dec-11d0-c360-f01234567890urn:schemas-xmlsoap-org:ws:2005:04:discoveryhttp://schemas.xmlsoap.org/ws/2005/04/discovery/Probedn:NetworkVideoTransmitter" #define PONVIF_PACK_GET_SYS_DTS \ (CSTR)"" -#define PONVIF_PACK_GET_CAPABILITIES \ - (CSTR)"%s%s%s%sAll" -#define PONVIF_PACK_GET_VIDEO_SOURCES \ - (CSTR)"%s%s%s%s" -#define PONVIF_PACK_GET_PROFILES \ - (CSTR)"%s%s%s%s" -#define PONVIF_PACK_GET_SERVICES \ - (CSTR)"%s%s%s%sfalse" -#define PONVIF_PACK_GET_DEV_INFO \ - (CSTR)"%s%s%s%s" -#define PONVIF_PACK_GET_STREAM_URI \ - (CSTR)"%s%s%s%s%s%s%s" -#define PONVIF_PACK_GET_PICTURE_URI \ - (CSTR)"%s%s%s%s%s" -#define PONVIF_PACK_GET_PRESETS \ - (CSTR)"%s%s%s%s%s" -#define PONVIF_PACK_GET_PTZ_NODE \ - (CSTR)"%s%s%s%s%s" -#define PONVIF_PACK_GET_PTZ_STATUS \ - (CSTR)"%s%s%s%s%s" -#define PONVIF_PACK_PTZ_GET_SERVICE_CAPS \ - (CSTR)"%s%s%s%s" -#define PONVIF_PACK_GOTO_PRESET \ - (CSTR)"%s%s%s%s%s%s" -#define PONVIF_PACK_REMOVE_PRESET \ - (CSTR)"%s%s%s%s%s%s" -#define PONVIF_PACK_SET_PRESET \ - (CSTR)"%s%s%s%s%s%s" -#define PONVIF_PACK_RELATIVE_MOVE \ - (CSTR)"%s%s%s%s%s" -#define PONVIF_PACK_RELATIVE_ZOOM \ - (CSTR)"%s%s%s%s%s" -#define PONVIF_PACK_ABSOLUTE_MOVE \ - (CSTR)"%s%s%s%s%s" -#define PONVIF_PACK_CONTINUOUS_MOVE \ - (CSTR)"%s%s%s%s%s" -// #define PONVIF_PACK_CONTINUOUS_MOVE_A (CSTR)"Profile_1" -#define PONVIF_PACK_CONTINUOUS_ZOOM \ - (CSTR)"%s%s%s%s%s" -#define PONVIF_PACK_PTZ_STOP \ - (CSTR)"%s%s%s%s%struetrue" +/* + Request bodies (the SOAP envelope and the optional WS-Security header are added by pOnvif::_buildRequest). + String arguments must be XML-escaped by the caller (pOnvif::_xmlEscape). +*/ +#define PONVIF_NS_DEVICE "http://www.onvif.org/ver10/device/wsdl" +#define PONVIF_NS_MEDIA "http://www.onvif.org/ver10/media/wsdl" +#define PONVIF_NS_PTZ "http://www.onvif.org/ver20/ptz/wsdl" +#define PONVIF_NS_SCHEMA "http://www.onvif.org/ver10/schema" + +#define PONVIF_BODY_GET_CAPABILITIES "All" +#define PONVIF_BODY_GET_SERVICES "false" +#define PONVIF_BODY_GET_DEV_INFO "" +#define PONVIF_BODY_GET_VIDEO_SOURCES "" +#define PONVIF_BODY_GET_PROFILES "" +#define PONVIF_BODY_GET_STREAM_URI \ + "%s%s%s" +#define PONVIF_BODY_GET_SNAPSHOT_URI "%s" +#define PONVIF_BODY_PTZ_GET_SERVICE_CAPS "" +#define PONVIF_BODY_GET_PRESETS "%s" +#define PONVIF_BODY_GET_PTZ_NODE "%s" +#define PONVIF_BODY_GET_PTZ_STATUS "%s" +#define PONVIF_BODY_GOTO_PRESET \ + "%s%s" +#define PONVIF_BODY_REMOVE_PRESET "%s%s" +#define PONVIF_BODY_SET_PRESET "%s%s" +#define PONVIF_BODY_RELATIVE_MOVE \ + "%s" +#define PONVIF_BODY_RELATIVE_ZOOM \ + "%s" +#define PONVIF_BODY_ABSOLUTE_MOVE \ + "%s" +// ContinuousMove is assembled from these parts (pan/tilt and zoom in one request) +#define PONVIF_BODY_CONTINUOUS_MOVE_BEGIN "%s" +#define PONVIF_BODY_CONTINUOUS_MOVE_PT \ + "" +#define PONVIF_BODY_CONTINUOUS_MOVE_ZOOM \ + "" +#define PONVIF_BODY_CONTINUOUS_MOVE_END "PT%dS" +#define PONVIF_BODY_PTZ_STOP "%s%s%s" + +// Default ContinuousMove timeout: the camera stops by itself if the Stop request is lost +#define PONVIF_CONTINUOUS_MOVE_TIMEOUT_S 10 +// WS-Security nonce length (bytes before Base64) +#define PONVIF_NONCE_LEN 16 #define PONVIF_ENVELOPE_EXT \ (CSTR)"%s%s" @@ -100,8 +110,20 @@ typedef struct S_videoSourceProfile int height; int fps; int bitrate; + bool ptz; // profile has a PTZConfiguration (PTZ commands need such a profile) + char ptznodetoken[CTEXT]; // PTZConfiguration/NodeToken } videoSourceProfile; +// Result of the last request (pOnvif::getLastError) +typedef enum E_onvifError +{ + PONVIF_OK = 0, + PONVIF_ERR_COMM, // no answer: connection error, timeout, request could not be queued + PONVIF_ERR_HTTP, // HTTP status other than 200 without a SOAP Fault (e.g. 401 HTML page) + PONVIF_ERR_FAULT, // the device answered with a SOAP Fault (see getLastFault) + PONVIF_ERR_PARSE // reply is not the expected XML +} onvifError; + typedef struct S_onvifVideoResolution { int Width; @@ -516,6 +538,9 @@ class pOnvif void * volatile m_pPendingRequest; // reply that _send_request is waiting for basicMutex m_mParserLock; // parser() vs. _send_request bookkeeping uint8_t m_bAuthMode; + volatile long m_nLastHttpCode; // HTTP status of the last reply (set by parser()) + onvifError m_eLastError; + char m_cLastFault[CTEXT]; #ifndef CURL_MANAGER static int _writer(char * data, size_t size, size_t nmemb, pOnvif * Ptr); #endif @@ -558,6 +583,10 @@ class pOnvif bool setDiscoveryMcastPort(int discoverymcastport); bool setDiscoveryHideDuplicates(bool discoveryhideduplicates); CSTR getSnapshotUri(void); + onvifError getLastError(void); + CSTR getLastFault(void); + // First profile that has a PTZConfiguration, NULL if none + videoSourceProfile * getPTZProfile(void); discoveryResults discover(void); bool create(void); @@ -586,10 +615,18 @@ class pOnvif bool ptz_AbsoluteMove(CSTR profileToken, float position_pantilt_x, float position_pantilt_y, float zoom); bool ptz_ContinuousMove(CSTR profileToken, float velocity_pantilt_x, float velocity_pantilt_y); bool ptz_ContinuousMoveZoom(CSTR profileToken, float zoom); + // One ContinuousMove for pan/tilt and zoom; axes with has* == false are left out of the request + bool ptz_ContinuousMoveAll(CSTR profileToken, bool hasPanTilt, float velocity_pantilt_x, float velocity_pantilt_y, bool hasZoom, float velocity_zoom, + int timeoutSec = PONVIF_CONTINUOUS_MOVE_TIMEOUT_S); bool ptz_Stop(CSTR profileToken, bool pantilt, bool zoom); /* Internal functions */ + public: + + // XML-escape src into dst (&, <, >, ", '); always NUL-terminates + static char * _xmlEscape(const char * src, char * dst, size_t dstSize); + private: accessToken _makeToken(void); @@ -597,7 +634,11 @@ class pOnvif void _getActiveSources(videoSourceProfiles & videoSources, videoSourceProfiles profiles); void _getProfileData(videoSourceProfiles & videoSources, videoSourceProfiles profiles); // protected function _xml2array($response); - accessToken _passwordDigest(CSTR username, CSTR password, time_t timestamp = 0, uint32_t nonce = 0); + accessToken _passwordDigest(CSTR username, CSTR password, time_t timestamp = 0); + bool _hasCredentials(void); + // Envelope + (WS-Security header if credentials are set) + body built from bodyFmt + bool _buildRequest(char * out, size_t outSize, const char * bodyFmt, ...) __attribute__((format(printf, 4, 5))); + bool _checkReply(void); bool _send_request(CSTR url, CSTR post_string, bool mr = true); bool _post_request(CSTR url, CSTR post_string); }; diff --git a/lib/data/protocol/protocolPTZ_ONVIF.cpp b/lib/data/protocol/protocolPTZ_ONVIF.cpp index 8f015402..35f43cf8 100644 --- a/lib/data/protocol/protocolPTZ_ONVIF.cpp +++ b/lib/data/protocol/protocolPTZ_ONVIF.cpp @@ -203,7 +203,19 @@ bool protocolPTZ_ONVIF::create(void) LOG("PROTOCREATE"); if (m_pOnVif->create()) { - m_pProfile = m_pOnVif->getProfiles()->at(0); + // PTZ commands need a profile with a PTZConfiguration + m_pProfile = m_pOnVif->getPTZProfile(); + if (m_pProfile == NULL) + { + // Non-conformant devices sometimes accept PTZ on a profile without PTZConfiguration: keep the old behaviour + m_pProfile = m_pOnVif->getProfiles()->at(0); + LOG_ERROR("No media profile with a PTZConfiguration, using the first profile"); + } + { + char tB[CTEXT * 2]; + snprintf(tB, sizeof(tB), "PTZ profile: %s (%s)", m_pProfile->profiletoken, m_pProfile->profilename); + LOG(tB); + } detectStatusSupport(); LOG("DONE"); m_bStatus = 1; @@ -315,26 +327,12 @@ bool protocolPTZ_ONVIF::move(uint32_t MoveMatrix) { Speed_z = -m_dZoomSpeed; }; - bool res = true; - if ((MoveMatrix & (PTZ_DRIVE_PAN_MASK | PTZ_DRIVE_TILT_MASK)) != 0) - { - res = m_pOnVif->ptz_ContinuousMove(m_pProfile->profiletoken, Speed_x, Speed_y); - }; - if (res) - { - if ((MoveMatrix & PTZ_DRIVE_ZOOM_MASK) != 0) - { - res = m_pOnVif->ptz_ContinuousMoveZoom(m_pProfile->profiletoken, Speed_z); - }; - }; - m_bStatus = (res) ? 1 : 0; + // One request for all axes (two separate ContinuousMoves may stop each other) + bool hasPT = ((MoveMatrix & (PTZ_DRIVE_PAN_MASK | PTZ_DRIVE_TILT_MASK)) != 0); + bool hasZ = ((MoveMatrix & PTZ_DRIVE_ZOOM_MASK) != 0); + return commandResult(m_pOnVif->ptz_ContinuousMoveAll(m_pProfile->profiletoken, hasPT, Speed_x, Speed_y, hasZ, Speed_z)); } - else - { - - m_bStatus = (m_pOnVif->ptz_Stop(m_pProfile->profiletoken, true, true)) ? 1 : 0; - }; - return (m_bStatus > 0); + return commandResult(m_pOnVif->ptz_Stop(m_pProfile->profiletoken, true, true)); #else if (m_bStatus == 0) { @@ -398,6 +396,25 @@ bool protocolPTZ_ONVIF::move(uint32_t MoveMatrix) #include #ifdef USE_PONVIF +/* + Maps a pOnvif command result to the connection status: only a communication error means the camera is + lost (m_bStatus = 0 -> validate() fails -> reconnect). A SOAP Fault / HTTP error is an answer from a + reachable camera: the command failed, the connection is fine. +*/ +bool protocolPTZ_ONVIF::commandResult(bool ok) +{ + if (ok) + { + m_bStatus = 1; + return true; + } + if (m_pOnVif == NULL || m_pOnVif->getLastError() == PONVIF_ERR_COMM) + { + m_bStatus = 0; + } + return false; +} + static long ptzOnvifNowMs(void) { struct timespec tTS; @@ -587,9 +604,9 @@ bool protocolPTZ_ONVIF::goAbsolute(float dPan, float dTilt, float dZoom) m_fTargetTilt = dTilt; m_fTargetZoom = dZoom; m_bTargetValid = true; - if (m_pOnVif->ptz_AbsoluteMove(m_pProfile->profiletoken, dPan, dTilt, dZoom)) - { - }; + // A SOAP Fault (e.g. position out of range) is logged by pOnvif; like before, the camera node is not + // restarted because of it. Only a lost connection clears m_bStatus (validate() -> reconnect). + commandResult(m_pOnVif->ptz_AbsoluteMove(m_pProfile->profiletoken, dPan, dTilt, dZoom)); return true; #else if (m_bStatus == 0) @@ -642,11 +659,7 @@ bool protocolPTZ_ONVIF::goPreset(char * PresetToken) }; // A preset move has no known target: waitMoveIsDone() must not compare with an old AbsoluteMove target m_bTargetValid = false; - if (! m_pOnVif->ptz_GotoPreset(m_pProfile->profiletoken, PresetToken, 1.0f, 1.0f, 1.0f)) - { - m_bStatus = 0; - } - return (m_bStatus > 0); + return commandResult(m_pOnVif->ptz_GotoPreset(m_pProfile->profiletoken, PresetToken, 1.0f, 1.0f, 1.0f)); #else if (m_bStatus == 0) { diff --git a/lib/data/protocol/protocolPTZ_ONVIF.h b/lib/data/protocol/protocolPTZ_ONVIF.h index 5ce1bf00..ff161723 100644 --- a/lib/data/protocol/protocolPTZ_ONVIF.h +++ b/lib/data/protocol/protocolPTZ_ONVIF.h @@ -55,6 +55,7 @@ class protocolPTZ_ONVIF : public protocolPTZ float m_fTargetZoom; void detectStatusSupport(void); + bool commandResult(bool ok); bool fixedMoveWait(long alreadyWaitedMs); #endif