#include "ponvif.h" #include #include #include #include #include #include #include #include /* See NOTES */ #include // http://dspace.nplg.gov.ge/handle/1234/3051 // http://dspace.nplg.gov.ge/handle/1234/3057 // http://dspace.nplg.gov.ge/handle/1234/3061 #define LOG(X) m_pLog->Log("PONVIF", this, X) #define TLOG(X) basicLogCollection::getInstance()->Log("PONVIF_T", NULL, X) #ifdef DEBUG #define LOG_ERROR(X) \ { \ char _tBfrErrMSG2w34[512]; \ sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \ m_pLog->Log("PONVIF", this, _LOG_ERROR, _tBfrErrMSG2w34); \ } #else #define LOG_ERROR(X) m_pLog->Log("PONVIF", this, _LOG_ERROR, X); #endif inline bool checkBool(const char * A) { if (A == NULL) { return false; } 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 (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 (strcasecmp(A, "ON") == 0 || strcmp(A, "1") == 0) { return ON; } 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() { m_pLog = basicLogCollection::getInstance(); m_pIpAddress = NULL; m_pUsername = NULL; m_pPassword = NULL; m_pMediaURI = NULL; m_pSnapshotURI = NULL; m_pDeviceURI = NULL; m_pPTZURI = NULL; m_pBaseURI = NULL; m_nDeltaTime = 0; m_pCURL = NULL; m_pProxyHost = NULL; m_nProxyPort = 0; m_pProxyUsername = NULL; m_pProxyPassword = NULL; m_pLastResponse = NULL; m_bIntransingent = true; m_nDiscoveryTimeout = PONVIF_DEFAULT_DISCOVERYTIMEOUT; m_pDiscoveryBindIP = NULL; // PONVIF_DEFAULT_DISCOVERYBINDIP; m_pDiscoveryMCastIP = NULL; // PONVIF_DEFAULT_DISCOVERYMCASTIP; m_nDiscoveryMCastPort = PONVIF_DEFAULT_DISCOVERYMCASTPORT; m_bDiscoveryHideDuplicates = true; m_pHttpAccessManager = NULL; memset( &m_sCapabilities, 0, sizeof( nodeCapability ) ); 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!"); } void pOnvif::cleanNodeCapability( nodeCapability *ptr ){ LOG("A"); if ( ptr->Analytics ) free( ptr->Analytics ); LOG("B"); if ( ptr->Device ){ LOG("1"); if ( ptr->Device->Network ){ LOG("1a"); if ( ptr->Device->Network->Extension) { if ( ptr->Device->Network->Extension->Extension ) free ( ptr->Device->Network->Extension->Extension ); free( ptr->Device->Network->Extension ); }; free( ptr->Device->Network ); }; LOG("2"); if ( ptr->Device->System ){ LOG("2a"); if( ptr->Device->System->SupportedVersions ) free( ptr->Device->System->SupportedVersions ); if ( ptr->Device->System->Extension) { if ( ptr->Device->System->Extension->Extension ) free ( ptr->Device->System->Extension->Extension ); free( ptr->Device->System->Extension ); }; free( ptr->Device->System ); }; LOG("3"); if ( ptr->Device->IO ){ LOG("3a"); if ( ptr->Device->IO->Extension) { if( ptr->Device->IO->Extension->AuxiliaryCommands ) free( ptr->Device->IO->Extension->AuxiliaryCommands ); if ( ptr->Device->IO->Extension->Extension ) free ( ptr->Device->IO->Extension->Extension ); free( ptr->Device->IO->Extension ); }; free( ptr->Device->IO ); }; LOG("4"); if ( ptr->Device->Security ){ LOG("4a"); if ( ptr->Device->Security->Extension) { if ( ptr->Device->Security->Extension->Extension ) free ( ptr->Device->Security->Extension->Extension ); free( ptr->Device->Security->Extension ); }; free( ptr->Device->Security ); }; LOG("5"); if ( ptr->Device->Extension ) { LOG("5a"); free( ptr->Device->Extension ); } LOG("6"); free( ptr->Device ); LOG("62"); }; LOG("C"); if ( ptr->Events ) free( ptr->Events ); LOG("D"); if ( ptr->Imaging ) free( ptr->Imaging ); LOG("E"); if ( ptr->Media ){ if ( ptr->Media->StreamingCapabilities ) { if ( ptr->Media->StreamingCapabilities->Extension ) free( ptr->Media->StreamingCapabilities->Extension ); free( ptr->Media->StreamingCapabilities ); }; if ( ptr->Media->Extension ) { if ( ptr->Media->Extension->ProfileCapabilities ) free( ptr->Media->Extension->ProfileCapabilities ); free( ptr->Media->Extension ); }; }; LOG("F"); if ( ptr->PTZ ) free( ptr->PTZ ); LOG("G"); if ( ptr->Extension ){ if ( ptr->Extension->DeviceIO ) free( ptr->Extension->DeviceIO ); if ( ptr->Extension->Display ) free( ptr->Extension->Display ); if ( ptr->Extension->Recording ) free( ptr->Extension->Recording ); if ( ptr->Extension->Search ) free( ptr->Extension->Search ); if ( ptr->Extension->Replay ) free( ptr->Extension->Replay ); if ( ptr->Extension->Receiver ) free( ptr->Extension->Receiver ); if ( ptr->Extension->AnalyticsDevice ) { if ( ptr->Extension->AnalyticsDevice->Extension ) free( ptr->Extension->AnalyticsDevice->Extension ); free(ptr->Extension->AnalyticsDevice); }; if ( ptr->Extension->Extensions ) free( ptr->Extension->Extensions ); free(ptr->Extension); }; }; pOnvif::~pOnvif() { #ifdef DEBUG LOG("Destructor begin"); #endif if (m_pIpAddress) { LOG("1"); free(m_pIpAddress); } if (m_pUsername) { LOG("2"); free(m_pUsername); } if (m_pPassword) { LOG("3"); free(m_pPassword); } //if (m_pMediaURI) //{ // LOG("4"); // free(m_pMediaURI); //} if (m_pSnapshotURI) { LOG("5"); free(m_pSnapshotURI); } //if (m_pDeviceURI) //{ // LOG("6"); // free(m_pDeviceURI); //} //if (m_pPTZURI) //{ // LOG("7"); // free(m_pPTZURI); //} if (m_pBaseURI) { LOG("8"); free(m_pBaseURI); } if (m_pProxyHost) { LOG("9"); free(m_pProxyHost); } if (m_pProxyUsername) { LOG("10"); free(m_pProxyUsername); } if (m_pProxyPassword) { LOG("11"); free(m_pProxyPassword); } if (m_pLastResponse) { LOG("12"); free(m_pLastResponse); } if (m_pDiscoveryBindIP) { LOG("13"); free(m_pDiscoveryBindIP); } if (m_pDiscoveryMCastIP) { LOG("14"); free(m_pDiscoveryMCastIP); } cleanNodeCapability( &m_sCapabilities ); LOG("CNC Done!"); if (m_pCURL) { #ifdef DEBUG LOG("Try Cleanup CURL!"); #endif curl_easy_cleanup(m_pCURL); m_pCURL = NULL; }; #ifdef DEBUG LOG("Destructor Done!"); #endif } bool pOnvif::setProxyHost(CSTR proxyHost) { if (m_pProxyHost != NULL) { free(m_pProxyHost); } if (proxyHost == NULL || strlen(proxyHost) == 0) { m_pProxyHost = NULL; return true; }; m_pProxyHost = (CSTR) malloc(strlen(proxyHost) + 1); if (m_pProxyHost == NULL) { return false; } memcpy(m_pProxyHost, proxyHost, strlen(proxyHost) + 1); return true; } CSTR pOnvif::getProxyHost() { return m_pProxyHost; } bool pOnvif::setProxyPort(int proxyPort) { m_nProxyPort = proxyPort; return true; } int pOnvif::getProxyPort(void) { return m_nProxyPort; } bool pOnvif::setProxyUsername(CSTR proxyUsername) { if (m_pProxyUsername != NULL) { free(m_pProxyUsername); } if (proxyUsername == NULL || strlen(proxyUsername) == 0) { m_pProxyUsername = NULL; return true; }; m_pProxyUsername = (CSTR) malloc(strlen(proxyUsername) + 1); if (m_pProxyUsername == NULL) { return false; } memcpy(m_pProxyUsername, proxyUsername, strlen(proxyUsername) + 1); return true; } CSTR pOnvif::getProxyUsername(void) { return m_pProxyUsername; } bool pOnvif::setProxyPassword(CSTR proxyPassword) { if (m_pProxyPassword != NULL) { free(m_pProxyPassword); } if (proxyPassword == NULL || strlen(proxyPassword) == 0) { m_pProxyPassword = NULL; return true; }; m_pProxyPassword = (CSTR) malloc(strlen(proxyPassword) + 1); if (m_pProxyPassword == NULL) { return false; } memcpy(m_pProxyPassword, proxyPassword, strlen(proxyPassword) + 1); return true; } CSTR pOnvif::getProxyPassword() { return m_pProxyPassword; } bool pOnvif::setUsername(CSTR username) { if (m_pUsername != NULL) { free(m_pUsername); } if (username == NULL || strlen(username) == 0) { m_pUsername = NULL; return true; }; m_pUsername = (CSTR) malloc(strlen(username) + 1); if (m_pUsername == NULL) { return false; } memcpy(m_pUsername, username, strlen(username) + 1); return true; } CSTR pOnvif::getUsername(void) { return m_pUsername; } bool pOnvif::setPassword(CSTR password) { if (m_pPassword != NULL) { free(m_pPassword); } if (password == NULL || strlen(password) == 0) { m_pPassword = NULL; return true; }; m_pPassword = (CSTR) malloc(strlen(password) + 1); if (m_pPassword == NULL) { return false; } memcpy(m_pPassword, password, strlen(password) + 1); return true; } CSTR pOnvif::getPassword(void) { return m_pPassword; } CSTR pOnvif::getDeviceUri(void) { return m_pDeviceURI; } bool pOnvif::setDeviceUri(CSTR deviceUri) { if (deviceUri == NULL || strlen(deviceUri) == 0) { m_pDeviceURI = NULL; return false; }; if (strstr(deviceUri, "http") == NULL) { LOG_ERROR("Malformed device URI"); return false; }; if (m_pDeviceURI != NULL) { free(m_pDeviceURI); } m_pDeviceURI = (CSTR) malloc(strlen(deviceUri) + 1); if (m_pDeviceURI == NULL) { return false; } memcpy(m_pDeviceURI, deviceUri, strlen(deviceUri)); m_pDeviceURI[strlen(deviceUri)] = (char) 0; // toDo: Must parsed Host/IP char * tT = strstr(m_pDeviceURI, "/"); if (tT) { tT += 2; char * tB = strstr(tT, "/"); int len = tB - tT + 1; m_pIpAddress = (CSTR) malloc(len); if (m_pIpAddress) { len--; memcpy(m_pIpAddress, tT, len); m_pIpAddress[len] = (char) 0; LOG(m_pIpAddress); }; }; return true; } CSTR pOnvif::getIPAddress(void) { return m_pIpAddress; } bool pOnvif::setIPAddress(CSTR ipAddress) { if (ipAddress == NULL || strlen(ipAddress) == 0) { m_pIpAddress = NULL; return false; }; if (m_pIpAddress != NULL) { free(m_pIpAddress); } m_pIpAddress = (CSTR) malloc(strlen(ipAddress) + 1); if (m_pIpAddress == NULL) { return false; } memcpy(m_pIpAddress, ipAddress, strlen(ipAddress)); m_pIpAddress[strlen(ipAddress)] = (char) 0; // ToDo: Must be created URI ... sprintf(tURL, "http://%s/onvif/device_service", m_pIpAddress); int len = strlen(ipAddress) + 28; m_pDeviceURI = (CSTR) malloc(len + 1); if (m_pDeviceURI) { sprintf(m_pDeviceURI, "http://%s/onvif/device_service", m_pIpAddress); LOG(m_pDeviceURI); }; return true; } videoSources * pOnvif::getSources(void) { return &m_vVideoSources; } videoSourceProfiles * pOnvif::getProfiles(void) { return &m_vVideoProfiles; } videoSourceProfiles * pOnvif::getActiveProfiles(void) { return &m_vActiveSources; } CSTR pOnvif::getMediaUri(void) { return m_pMediaURI; } CSTR pOnvif::getPTZUri(void) { return m_pPTZURI; } CSTR pOnvif::getBaseUrl(void) { return m_pBaseURI; } void pOnvif::getSupportedVersion(void) {} nodeCapability * pOnvif::getCapabilities(void) { return &m_sCapabilities; } bool pOnvif::setBreakOnError(bool intransingent) { m_bIntransingent = intransingent; return true; } CSTR pOnvif::getLastResponse(void) { return m_pLastResponse; } bool pOnvif::setDiscoveryTimeout(int discoverytimeout) { m_nDiscoveryTimeout = discoverytimeout; return true; } bool pOnvif::setDiscoveryBindIp(CSTR discoverybindip) { if (m_pDiscoveryBindIP != NULL) { free(m_pDiscoveryBindIP); } if (discoverybindip == NULL || strlen(discoverybindip) == 0) { m_pDiscoveryBindIP = NULL; return true; }; m_pDiscoveryBindIP = (CSTR) malloc(strlen(discoverybindip) + 1); if (m_pDiscoveryBindIP == NULL) { return false; } memcpy(m_pDiscoveryBindIP, discoverybindip, strlen(discoverybindip) + 1); return true; } bool pOnvif::setDiscoveryMcastIp(CSTR discoverymcastip) { if (m_pDiscoveryMCastIP != NULL) { free(m_pDiscoveryMCastIP); } if (discoverymcastip == NULL || strlen(discoverymcastip) == 0) { m_pDiscoveryMCastIP = NULL; return true; }; m_pDiscoveryMCastIP = (CSTR) malloc(strlen(discoverymcastip) + 1); if (m_pDiscoveryMCastIP == NULL) { return false; } memcpy(m_pDiscoveryMCastIP, discoverymcastip, strlen(discoverymcastip) + 1); return true; } bool pOnvif::setDiscoveryMcastPort(int discoverymcastport) { m_nDiscoveryMCastPort = discoverymcastport; return true; } bool pOnvif::setDiscoveryHideDuplicates(bool discoveryhideduplicates) { m_bDiscoveryHideDuplicates = discoveryhideduplicates; return true; } CSTR pOnvif::getSnapshotUri(void) { return m_pSnapshotURI; } /* WS-Discovery https://www.geeksforgeeks.org/udp-server-client-implementation-c/ */ discoveryResults pOnvif::discover(void) { discoveryResults RetVal; time_t tTimeout = time(NULL) + m_nDiscoveryTimeout; CSTR tPostString = PONVIF_PACK_DISCOVERY; struct sockaddr_in tSockAddr; struct hostent * h_info; #ifdef __linux__ int tSocket; #else int tSocket; #endif int RetCode; char Response[DEFAULT_BUFFER_SIZE]; try { // SOL_UDP = 17 tSocket = socket(AF_INET, SOCK_DGRAM, 0); if (tSocket < 0) { LOG_ERROR("ERROR creating socket"); return RetVal; }; LOG("Socket Created!"); memset(&tSockAddr, 0, sizeof(struct sockaddr_in)); h_info = gethostbyname(m_pDiscoveryBindIP); if (h_info == NULL) { LOG_ERROR("Some throuble with networking on this machine (Cannot Get Hostname)!"); return RetVal; }; LOG("Host Found!"); //***************************************** //* there we building our network address * //***************************************** memcpy(h_info->h_addr, &(tSockAddr.sin_addr), h_info->h_length); tSockAddr.sin_family = h_info->h_addrtype; tSockAddr.sin_port = htons(20000 + (20000 * rand()) / RAND_MAX); RetCode = bind(tSocket, (const sockaddr *) &tSockAddr, sizeof(struct sockaddr_in)); if (RetCode != 0) { LOG_ERROR("Error Binding to Port/Address"); return RetVal; }; LOG("Binding Done!"); #ifdef __linux__ // setsockopt( tSocket, IPPROTO_IP, MCAST_JOIN_GROUP, ); int tVal = 1; setsockopt(tSocket, SOL_SOCKET, SO_BROADCAST, &tVal, sizeof(int)); // socket_sendto($sock, $post_string, strlen(tPostString), 0, $this->discoverymcastip, $this->discoverymcastport); sendto(tSocket, tPostString, strlen(tPostString), 0, (const sockaddr *) &tSockAddr, sizeof(struct sockaddr_in)); LOG("Broadcast Ping Sent!"); fcntl(tSocket, F_SETFL, fcntl(tSocket, F_GETFL, 0) | O_NONBLOCK); LOG("Socket Set Not Bloking Mode!"); #else // setsockopt( tSocket, IPPROTO_IP, MCAST_JOIN_GROUP, ); bool tVal = 1; setsockopt(tSocket, SOL_SOCKET, SO_BROADCAST, (const char *) &tVal, sizeof(bool)); // socket_sendto($sock, $post_string, strlen(tPostString), 0, $this->discoverymcastip, $this->discoverymcastport); sendto(tSocket, tPostString, strlen(tPostString), 0, (const sockaddr *) &tSockAddr, sizeof(struct sockaddr_in)); LOG("Broadcast Ping Sent!"); u_long arg = 1; if (ioctlsocket(tSocket, FIONBIO, &arg) < 0) { char tBuf[128]; sprintf(tBuf, "Error ioctlsocket(..., FIONBIO) (%s)", strerror(errno)); LOG_ERROR(tBuf); return RetVal; }; #endif while (time(NULL) < tTimeout) { // n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL, (struct sockaddr *) &servaddr, &len); tVal = recvfrom(tSocket, Response, DEFAULT_BUFFER_SIZE, 0, NULL, NULL); if (tVal > 0) { Response[tVal] = '\0'; // if( FALSE !== socket_recvfrom( $sock, $response, 9999, 0, $from, $this->discoverymcastport )){ // if( Response != NULL && $response != $post_string){ LOG(Response); XMLNode node = XMLNode::parseString(Response, "root"); //$response = $this->_xml2array($response); // if(!isFault( node )){ //$response['Envelope']['Body']['ProbeMatches']['ProbeMatch']['IPAddr'] = $from; if (m_bDiscoveryHideDuplicates) { // $result[$from] = $response['Envelope']['Body']['ProbeMatches']['ProbeMatch']; } else { // $result[] = $response['Envelope']['Body']['ProbeMatches']['ProbeMatch']; }; // }; //}; //}; }; }; #ifdef __linux__ close(tSocket); #else closesocket(tSocket); #endif } catch ( const std::exception& e) { LOG_ERROR("Communication at Discovery Exception Catched!"); }; return RetVal; } /* Public functions (basic initialization method and other collaterals) */ bool pOnvif::create(void){ #ifdef DEBUG_EXTRA LOG("Get Instance m_pHttpAccessManager"); #endif m_pHttpAccessManager = curlRequestsManager::getInstance(); if (m_pHttpAccessManager == NULL) { return false; } // 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 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 { LOG_ERROR("Device UTC time not available, using local clock for WS-Security timestamps"); }; if (! core_GetCapabilities()) { LOG_ERROR("Error Getting Caps!"); return false; }; _getOnvifVersion(m_sCapabilities); if (media_GetVideoSources()){ if (media_GetProfiles()){ if (m_vVideoProfiles.empty()) { LOG_ERROR("Device has no media profiles!"); return false; }; return true; }; }; 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) { char tURL[CTEXT]; if (m_pDeviceURI != NULL) { snprintf(tURL, sizeof(tURL), "%s", m_pDeviceURI); } else if (m_pIpAddress != NULL) { snprintf(tURL, sizeof(tURL), "http://%s/onvif/device_service", m_pIpAddress); } else { return NULL; }; 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)) { LOG_ERROR("GetSystemDateAndTime: no valid answer"); return NULL; } XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); if (tParseResults.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; } 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 bool pOnvif::core_GetCapabilities(void) { char tBuffer[DEFAULT_BUFFER_SIZE]; char tURL[CTEXT]; if (m_pDeviceURI != NULL) { snprintf(tURL, sizeof(tURL), "%s", m_pDeviceURI); } else { if (m_pIpAddress != NULL) { sprintf(tURL, "http://%s/onvif/device_service", m_pIpAddress); } else { return NULL; }; }; // char tSTR[CTEXT]; _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)) { XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); #ifdef DEBUG_ONVIF_PRINTOUT_MESSAGES LOG("RCPT:"); printf("%s\n", m_pLastResponse); #endif if (tParseResults.error != eXMLErrorNone) { char tBuf[CTEXT]; sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); LOG_ERROR(tBuf); } else { XMLNode zNode = response.getChildNode("Body", 0); if (zNode.isEmpty()) { return false; } XMLNode tNode = zNode.getChildNode("GetCapabilitiesResponse", 0); if (! tNode.isEmpty()) { XMLNode tCaps = tNode.getChildNode("Capabilities", 0); if (! tCaps.isEmpty()) { { XMLNode t = tCaps.getChildNode("Analytics", 0); if (! t.isEmpty()) { m_sCapabilities.Analytics = (onvifAnalyticsCapabilities *) malloc(sizeof(onvifAnalyticsCapabilities)); if (m_sCapabilities.Analytics != NULL) { memset(m_sCapabilities.Analytics, 0, sizeof(onvifAnalyticsCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Analytics->XAddr, sizeof(m_sCapabilities.Analytics->XAddr), c.getText(0)); } { XMLNode c = t.getChildNode("RuleSupport", 0); m_sCapabilities.Analytics->RuleSupport = checkBool(c.getText(0)); } { XMLNode c = t.getChildNode("AnalyticsModuleSupport", 0); m_sCapabilities.Analytics->AnalyticsModuleSupport = checkBool(c.getText(0)); } }; }; } { XMLNode t = tCaps.getChildNode("Device", 0); if (! t.isEmpty()) { m_sCapabilities.Device = (onvifDeviceCapabilities *) malloc(sizeof(onvifDeviceCapabilities)); if (m_sCapabilities.Device != NULL) { memset(m_sCapabilities.Device, 0, sizeof(onvifDeviceCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Device->XAddr, sizeof(m_sCapabilities.Device->XAddr), c.getText(0)); } { XMLNode c = t.getChildNode("Network", 0); if (! c.isEmpty()) { m_sCapabilities.Device->Network = (onvifNetworkCapabilities *) malloc(sizeof(onvifNetworkCapabilities)); if (m_sCapabilities.Device->Network != NULL) { memset(m_sCapabilities.Device->Network, 0, sizeof(onvifNetworkCapabilities)); { XMLNode n = c.getChildNode("IPFilter", 0); m_sCapabilities.Device->Network->IPFilter = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("ZeroConfiguration", 0); m_sCapabilities.Device->Network->ZeroConfiguration = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("IPVersion6", 0); m_sCapabilities.Device->Network->IPVersion6 = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("DynDNS", 0); m_sCapabilities.Device->Network->DynDNS = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("Extension", 0); if (! n.isEmpty()) { m_sCapabilities.Device->Network->Extension = (onvifNetworkCapabilitiesExtension *) malloc(sizeof(onvifNetworkCapabilitiesExtension)); if (m_sCapabilities.Device->Network->Extension != NULL) { memset(m_sCapabilities.Device->Network->Extension, 0, sizeof(onvifNetworkCapabilitiesExtension)); { XMLNode x = n.getChildNode("Dot11Configuration", 0); m_sCapabilities.Device->Network->Extension->Dot11Configuration = checkBool(x.getText(0)); } }; }; } }; }; } { XMLNode c = t.getChildNode("System", 0); if (! c.isEmpty()) { m_sCapabilities.Device->System = (onvifSystemCapabilities *) malloc(sizeof(onvifSystemCapabilities)); if (m_sCapabilities.Device->System != NULL) { memset(m_sCapabilities.Device->System, 0, sizeof(onvifSystemCapabilities)); { XMLNode n = c.getChildNode("DiscoveryResolve", 0); m_sCapabilities.Device->System->DiscoveryResolve = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("DiscoveryBye", 0); m_sCapabilities.Device->System->DiscoveryBye = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("RemoteDiscovery", 0); m_sCapabilities.Device->System->RemoteDiscovery = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("SystemBackup", 0); m_sCapabilities.Device->System->SystemBackup = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("SystemLogging", 0); m_sCapabilities.Device->System->SystemLogging = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("FirmwareUpgrade", 0); m_sCapabilities.Device->System->FirmwareUpgrade = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("SupportedVersions", 0); if (! n.isEmpty()) { m_sCapabilities.Device->System->SupportedVersions = (onvifSupportedVersions *) malloc(sizeof(onvifSupportedVersions)); if (m_sCapabilities.Device->System->SupportedVersions != NULL) { memset(m_sCapabilities.Device->System->SupportedVersions, 0, sizeof(onvifSupportedVersions)); { XMLNode x = n.getChildNode("Major", 0); m_sCapabilities.Device->System->SupportedVersions->Major = safeAtoi(x.getText(0)); } { XMLNode x = n.getChildNode("Minor", 0); m_sCapabilities.Device->System->SupportedVersions->Minor = safeAtoi(x.getText(0)); } }; }; } { XMLNode n = c.getChildNode("Extension", 0); if (! n.isEmpty()) { m_sCapabilities.Device->System->Extension = (onvifSystemCapabilitiesExtension *) malloc(sizeof(onvifSystemCapabilitiesExtension)); if (m_sCapabilities.Device->System->Extension != NULL) { memset(m_sCapabilities.Device->System->Extension, 0, sizeof(onvifSystemCapabilitiesExtension)); { XMLNode x = n.getChildNode("HttpFirmwareUpgrade", 0); m_sCapabilities.Device->System->Extension->HttpFirmwareUpgrade = checkBool(x.getText(0)); } { XMLNode x = n.getChildNode("HttpSystemBackup", 0); m_sCapabilities.Device->System->Extension->HttpSystemBackup = checkBool(x.getText(0)); } { XMLNode x = n.getChildNode("HttpSystemLogging", 0); m_sCapabilities.Device->System->Extension->HttpSystemLogging = checkBool(x.getText(0)); } { XMLNode x = n.getChildNode("HttpSupportInformation", 0); m_sCapabilities.Device->System->Extension->HttpSupportInformation = checkBool(x.getText(0)); } }; }; } }; }; } { XMLNode c = t.getChildNode("IO", 0); if (! c.isEmpty()) { m_sCapabilities.Device->IO = (onvifIOCapabilities *) malloc(sizeof(onvifIOCapabilities)); if (m_sCapabilities.Device->IO != NULL) { memset(m_sCapabilities.Device->IO, 0, sizeof(onvifIOCapabilities)); { XMLNode n = c.getChildNode("InputConnectors", 0); m_sCapabilities.Device->IO->InputConnectors = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("RelayOutputs", 0); m_sCapabilities.Device->IO->RelayOutputs = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("Extension", 0); if (! n.isEmpty()) { m_sCapabilities.Device->IO->Extension = (onvifIOCapabilitiesExtension *) malloc(sizeof(onvifIOCapabilitiesExtension)); if (m_sCapabilities.Device->IO->Extension != NULL) { memset(m_sCapabilities.Device->IO->Extension, 0, sizeof(onvifIOCapabilitiesExtension)); { XMLNode x = n.getChildNode("Auxiliary", 0); m_sCapabilities.Device->IO->Extension->Auxiliary = checkBool(x.getText(0)); } }; }; } }; }; } { XMLNode c = t.getChildNode("Security", 0); if (! c.isEmpty()) { m_sCapabilities.Device->Security = (onvifSecurityCapabilities *) malloc(sizeof(onvifSecurityCapabilities)); if (m_sCapabilities.Device->Security != NULL) { memset(m_sCapabilities.Device->Security, 0, sizeof(onvifSecurityCapabilities)); { XMLNode n = c.getChildNode("TLS1.1", 0); m_sCapabilities.Device->Security->TLS1_1 = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("TLS1.2", 0); m_sCapabilities.Device->Security->TLS1_2 = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("OnboardKeyGeneration", 0); m_sCapabilities.Device->Security->OnboardKeyGeneration = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("AccessPolicyConfig", 0); m_sCapabilities.Device->Security->AccessPolicyConfig = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("X.509Token", 0); m_sCapabilities.Device->Security->X_509Token = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("SAMLToken", 0); m_sCapabilities.Device->Security->SAMLToken = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("KerberosToken", 0); m_sCapabilities.Device->Security->KerberosToken = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("RELToken", 0); m_sCapabilities.Device->Security->RELToken = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("Extension", 0); if (! n.isEmpty()) { m_sCapabilities.Device->Security->Extension = (onvifSecurityCapabilitiesExtension *) malloc(sizeof(onvifSecurityCapabilitiesExtension)); if (m_sCapabilities.Device->Security->Extension != NULL) { memset(m_sCapabilities.Device->Security->Extension, 0, sizeof(onvifSecurityCapabilitiesExtension)); { XMLNode x = n.getChildNode("TLS1.0", 0); m_sCapabilities.Device->Security->Extension->TLS1_0 = checkBool(x.getText(0)); } }; }; } }; }; } }; }; } { XMLNode t = tCaps.getChildNode("Events", 0); if (! t.isEmpty()) { m_sCapabilities.Events = (onvifEventCapabilities *) malloc(sizeof(onvifEventCapabilities)); if (m_sCapabilities.Events != NULL) { memset(m_sCapabilities.Events, 0, sizeof(onvifEventCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Events->XAddr, sizeof(m_sCapabilities.Events->XAddr), c.getText(0)); } { XMLNode c = t.getChildNode("WSSubscriptionPolicySupport", 0); m_sCapabilities.Events->WSSubscriptionPolicySupport = checkBool(c.getText(0)); } { XMLNode c = t.getChildNode("WSPullPointSupport", 0); m_sCapabilities.Events->WSPullPointSupport = checkBool(c.getText(0)); } { XMLNode c = t.getChildNode("WSPausableSubscriptionManagerInterfaceSupport", 0); m_sCapabilities.Events->WSPausableSubscriptionManagerInterfaceSupport = checkBool(c.getText(0)); } }; }; } { XMLNode t = tCaps.getChildNode("Imaging", 0); if (! t.isEmpty()) { m_sCapabilities.Imaging = (onvifImagingCapabilities *) malloc(sizeof(onvifImagingCapabilities)); if (m_sCapabilities.Imaging != NULL) { memset(m_sCapabilities.Imaging, 0, sizeof(onvifImagingCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Imaging->XAddr, sizeof(m_sCapabilities.Imaging->XAddr), c.getText(0)); } }; }; } { XMLNode t = tCaps.getChildNode("Media", 0); if (! t.isEmpty()) { m_sCapabilities.Media = (onvifMediaCapabilities *) malloc(sizeof(onvifMediaCapabilities)); if (m_sCapabilities.Media != NULL) { memset(m_sCapabilities.Media, 0, sizeof(onvifMediaCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Media->XAddr, sizeof(m_sCapabilities.Media->XAddr), c.getText(0)); } { XMLNode c = t.getChildNode("StreamingCapabilities", 0); if (! c.isEmpty()) { m_sCapabilities.Media->StreamingCapabilities = (onvifRealTimeStreamingCapabilities *) malloc(sizeof(onvifRealTimeStreamingCapabilities)); if (m_sCapabilities.Media->StreamingCapabilities != NULL) { memset(m_sCapabilities.Media->StreamingCapabilities, 0, sizeof(onvifRealTimeStreamingCapabilities)); { XMLNode n = c.getChildNode("RTPMulticast", 0); m_sCapabilities.Media->StreamingCapabilities->RTPMulticast = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("RTP_TCP", 0); m_sCapabilities.Media->StreamingCapabilities->RTP_TCP = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("RTP_RTSP_TCP", 0); m_sCapabilities.Media->StreamingCapabilities->RTP_RTSP_TCP = checkBool(n.getText(0)); } }; }; } { XMLNode c = t.getChildNode("Extension", 0); if (! c.isEmpty()) { m_sCapabilities.Media->Extension = (onvifMediaCapabilitiesExtension *) malloc(sizeof(onvifMediaCapabilitiesExtension)); if (m_sCapabilities.Media->Extension != NULL) { memset(m_sCapabilities.Media->Extension, 0, sizeof(onvifMediaCapabilitiesExtension)); { XMLNode n = c.getChildNode("ProfileCapabilities", 0); if (! n.isEmpty()) { m_sCapabilities.Media->Extension->ProfileCapabilities = (onvifProfileCapabilities *) malloc(sizeof(onvifProfileCapabilities)); if (m_sCapabilities.Media->Extension->ProfileCapabilities != NULL) { memset(m_sCapabilities.Media->Extension->ProfileCapabilities, 0, sizeof(onvifProfileCapabilities)); { XMLNode x = n.getChildNode("MaximumNumberOfProfiles", 0); m_sCapabilities.Media->Extension->ProfileCapabilities->MaximumNumberOfProfiles = safeAtoi(x.getText(0)); } }; }; } }; }; } }; }; } { XMLNode t = tCaps.getChildNode("PTZ", 0); if (! t.isEmpty()) { m_sCapabilities.PTZ = (onvifPTZCapabilities *) malloc(sizeof(onvifPTZCapabilities)); if (m_sCapabilities.PTZ != NULL) { memset(m_sCapabilities.PTZ, 0, sizeof(onvifPTZCapabilities)); { XMLNode c = t.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.PTZ->XAddr, sizeof(m_sCapabilities.PTZ->XAddr), c.getText(0)); } }; }; } { XMLNode t = tCaps.getChildNode("Extension", 0); if (! t.isEmpty()) { m_sCapabilities.Extension = (onvifCapabilitiesExtension *) malloc(sizeof(onvifCapabilitiesExtension)); if (m_sCapabilities.Extension != NULL) { memset(m_sCapabilities.Extension, 0, sizeof(onvifCapabilitiesExtension)); { XMLNode c = t.getChildNode("DeviceIO", 0); if (! c.isEmpty()) { m_sCapabilities.Extension->DeviceIO = (onvifDeviceIOCapabilities *) malloc(sizeof(onvifDeviceIOCapabilities)); if (m_sCapabilities.Extension->DeviceIO != NULL) { memset(m_sCapabilities.Extension->DeviceIO, 0, sizeof(onvifDeviceIOCapabilities)); { XMLNode n = c.getChildNode("XAddr", 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 = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("VideoOutputs", 0); m_sCapabilities.Extension->DeviceIO->VideoOutputs = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("AudioSources", 0); m_sCapabilities.Extension->DeviceIO->AudioSources = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("AudioOutputs", 0); m_sCapabilities.Extension->DeviceIO->AudioOutputs = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("RelayOutputs", 0); m_sCapabilities.Extension->DeviceIO->RelayOutputs = safeAtoi(n.getText(0)); } }; }; } { XMLNode c = t.getChildNode("Display", 0); if (! c.isEmpty()) { m_sCapabilities.Extension->Display = (onvifDisplayCapabilities *) malloc(sizeof(onvifDisplayCapabilities)); if (m_sCapabilities.Extension->Display != NULL) { memset(m_sCapabilities.Extension->Display, 0, sizeof(onvifDisplayCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Extension->Display->XAddr, sizeof(m_sCapabilities.Extension->Display->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("FixedLayout", 0); m_sCapabilities.Extension->Display->FixedLayout = checkBool(n.getText(0)); } }; }; } { XMLNode c = t.getChildNode("Recording", 0); if (! c.isEmpty()) { m_sCapabilities.Extension->Recording = (onvifRecordingCapabilities *) malloc(sizeof(onvifRecordingCapabilities)); if (m_sCapabilities.Extension->Recording != NULL) { memset(m_sCapabilities.Extension->Recording, 0, sizeof(onvifRecordingCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Extension->Recording->XAddr, sizeof(m_sCapabilities.Extension->Recording->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("ReceiverSource", 0); m_sCapabilities.Extension->Recording->ReceiverSource = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("MediaProfileSource", 0); m_sCapabilities.Extension->Recording->MediaProfileSource = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("DynamicRecordings", 0); m_sCapabilities.Extension->Recording->DynamicRecordings = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("DynamicTracks", 0); m_sCapabilities.Extension->Recording->DynamicTracks = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("MaxStringLength", 0); m_sCapabilities.Extension->Recording->MaxStringLength = safeAtoi(n.getText(0)); } }; }; } { XMLNode c = t.getChildNode("Search", 0); if (! c.isEmpty()) { m_sCapabilities.Extension->Search = (onvifSearchCapabilities *) malloc(sizeof(onvifSearchCapabilities)); if (m_sCapabilities.Extension->Search != NULL) { memset(m_sCapabilities.Extension->Search, 0, sizeof(onvifSearchCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Extension->Search->XAddr, sizeof(m_sCapabilities.Extension->Search->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("MetadataSearch", 0); m_sCapabilities.Extension->Search->MetadataSearch = checkBool(n.getText(0)); } }; }; } { XMLNode c = t.getChildNode("Replay", 0); if (! c.isEmpty()) { m_sCapabilities.Extension->Replay = (onvifReplayCapabilities *) malloc(sizeof(onvifReplayCapabilities)); if (m_sCapabilities.Extension->Replay != NULL) { memset(m_sCapabilities.Extension->Replay, 0, sizeof(onvifReplayCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Extension->Replay->XAddr, sizeof(m_sCapabilities.Extension->Replay->XAddr), n.getText(0)); } }; }; } { XMLNode c = t.getChildNode("Receiver", 0); if (! c.isEmpty()) { m_sCapabilities.Extension->Receiver = (onvifReceiverCapabilities *) malloc(sizeof(onvifReceiverCapabilities)); if (m_sCapabilities.Extension->Receiver != NULL) { memset(m_sCapabilities.Extension->Receiver, 0, sizeof(onvifReceiverCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Extension->Receiver->XAddr, sizeof(m_sCapabilities.Extension->Receiver->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("RTP_Multicast", 0); m_sCapabilities.Extension->Receiver->RTP_Multicast = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("RTP_TCP", 0); m_sCapabilities.Extension->Receiver->RTP_TCP = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("RTP_RTSP_TCP", 0); m_sCapabilities.Extension->Receiver->RTP_RTSP_TCP = checkBool(n.getText(0)); } { XMLNode n = c.getChildNode("SupportedReceivers", 0); m_sCapabilities.Extension->Receiver->SupportedReceivers = safeAtoi(n.getText(0)); } { XMLNode n = c.getChildNode("MaximumRTSPURILength", 0); m_sCapabilities.Extension->Receiver->MaximumRTSPURILength = safeAtoi(n.getText(0)); } }; }; } { XMLNode c = t.getChildNode("AnalyticsDevice", 0); if (! c.isEmpty()) { m_sCapabilities.Extension->AnalyticsDevice = (onvifAnalyticsDeviceCapabilities *) malloc(sizeof(onvifAnalyticsDeviceCapabilities)); if (m_sCapabilities.Extension->AnalyticsDevice != NULL) { memset(m_sCapabilities.Extension->AnalyticsDevice, 0, sizeof(onvifAnalyticsDeviceCapabilities)); { XMLNode n = c.getChildNode("XAddr", 0); safeCopy(m_sCapabilities.Extension->AnalyticsDevice->XAddr, sizeof(m_sCapabilities.Extension->AnalyticsDevice->XAddr), n.getText(0)); } { XMLNode n = c.getChildNode("RuleSupport", 0); m_sCapabilities.Extension->AnalyticsDevice->RuleSupport = checkBool(n.getText(0)); } }; }; } }; }; } return true; } else { LOG("Capabilities is Empty!"); }; } else { LOG("GetCapabilitiesResponse is Empty!"); }; }; } return false; } // based on https://www.onvif.org/ver20/imaging/wsdl/imaging.wsdl bool pOnvif::media_GetVideoSources(void) { if (m_pMediaURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _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("%s\n", m_pLastResponse); #endif if (tParseResults.error) { char tBuf[CTEXT]; sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); LOG_ERROR(tBuf); } else { XMLNode zNode = response.getChildNode("Body", 0); if (zNode.isEmpty()) { return false; } XMLNode tNode = zNode.getChildNode("GetVideoSourcesResponse", 0); if (! tNode.isEmpty()) { for (int index = 0; index < tNode.nChildNode(); index++) { XMLNode cNode = tNode.getChildNode("VideoSources", index); if (! cNode.isEmpty()) { videoSource * tPtr; tPtr = (videoSource *) malloc(sizeof(videoSource)); if (tPtr != NULL) { // 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 = safeAtof(nNode.getText(0)); } { XMLNode nNode = cNode.getChildNode("Resolution", 0); if (! nNode.isEmpty()) { { XMLNode xNode = nNode.getChildNode("Width", 0); tPtr->Resolution.Width = safeAtoi(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("Height", 0); tPtr->Resolution.Height = safeAtoi(xNode.getText(0)); } }; } { XMLNode nNode = cNode.getChildNode("Imaging", 0); if (! nNode.isEmpty()) { tPtr->Imaging = (onvifImagingSettings *) malloc(sizeof(onvifImagingSettings)); if (tPtr->Imaging != NULL) { memset(tPtr->Imaging, 0, sizeof(onvifImagingSettings)); { XMLNode xNode = nNode.getChildNode("BacklightCompensation", 0); if (! xNode.isEmpty()) { tPtr->Imaging->BacklightCompensation = (onvifBacklightCompensation *) malloc(sizeof(onvifBacklightCompensation)); if (tPtr->Imaging->BacklightCompensation != NULL) { memset(tPtr->Imaging->BacklightCompensation, 0, sizeof(onvifBacklightCompensation)); { XMLNode rNode = xNode.getChildNode("Mode", 0); tPtr->Imaging->BacklightCompensation->Mode = checkOnOff(rNode.getText(0)); } { XMLNode rNode = xNode.getChildNode("Level", 0); tPtr->Imaging->BacklightCompensation->Level = safeAtof(rNode.getText(0)); } }; }; } { XMLNode xNode = nNode.getChildNode("Brightness", 0); tPtr->Imaging->Brightness = safeAtof(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("ColorSaturation", 0); tPtr->Imaging->ColorSaturation = safeAtof(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("Contrast", 0); tPtr->Imaging->Contrast = safeAtof(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("Sharpness", 0); tPtr->Imaging->Sharpness = safeAtof(xNode.getText(0)); } { XMLNode xNode = nNode.getChildNode("IrCutFilter", 0); tPtr->Imaging->IrCutFilter = checkOnOffAuto(xNode.getText(0)); } }; }; } m_vVideoSources.push_back(tPtr); }; }; }; return true; } else { LOG_ERROR("GetVideoSourcesResponse EMPTY!"); }; }; } else { LOG_ERROR("_send_request Failure!"); }; return false; } bool pOnvif::media_GetProfiles(void) { char tBuffer[DEFAULT_BUFFER_SIZE]; _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("%s\n", m_pLastResponse); #endif if (tParseResults.error) { char tBuf[CTEXT]; sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); LOG_ERROR(tBuf); } else { XMLNode zNode = response.getChildNode("Body", 0); if (zNode.isEmpty()) { return false; } XMLNode tNode = zNode.getChildNode("GetProfilesResponse", 0); if (! tNode.isEmpty()) { for (int index = 0; index < tNode.nChildNode(); index++) { XMLNode cNode = tNode.getChildNode("Profiles", index); if (! cNode.isEmpty()) { videoSourceProfile * tPtr; tPtr = (videoSourceProfile *) malloc(sizeof(videoSourceProfile)); if (tPtr != NULL) { memset(tPtr, 0, sizeof(videoSourceProfile)); safeCopy(tPtr->profiletoken, sizeof(tPtr->profiletoken), cNode.getAttribute("token", 0)); { XMLNode nNode = cNode.getChildNode("Name", 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); safeCopy(tPtr->sourcetoken, sizeof(tPtr->sourcetoken), zNode.getText(0)); }; } { XMLNode nNode = cNode.getChildNode("VideoEncoderConfiguration", 0); if (! nNode.isEmpty()) { { XMLNode zNode = nNode.getChildNode("Encoding", 0); safeCopy(tPtr->encoding, sizeof(tPtr->encoding), zNode.getText(0)); } { XMLNode zNode = nNode.getChildNode("Resolution", 0); { XMLNode jNode = zNode.getChildNode("Width", 0); tPtr->width = safeAtoi(jNode.getText(0)); } { XMLNode jNode = zNode.getChildNode("Height", 0); tPtr->height = safeAtoi(jNode.getText(0)); } } { XMLNode zNode = nNode.getChildNode("RateControl", 0); { XMLNode jNode = zNode.getChildNode("FrameRateLimit", 0); tPtr->fps = safeAtoi(jNode.getText(0)); } { XMLNode jNode = zNode.getChildNode("BitrateLimit", 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); }; }; }; return true; }; }; }; return false; } bool pOnvif::media_GetServices(void) { char tBuffer[DEFAULT_BUFFER_SIZE]; _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("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); LOG_ERROR(tBuf); } else { }; }; return false; } bool pOnvif::core_GetDeviceInformation() { char tBuffer[DEFAULT_BUFFER_SIZE]; _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("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); LOG_ERROR(tBuf); } else { // return $response['Envelope']['Body']['GetDeviceInformationResponse']; }; }; return false; } CSTR pOnvif::media_GetStreamUri(CSTR profileToken, CSTR stream, CSTR protocol) { char tBuffer[DEFAULT_BUFFER_SIZE]; _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("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); LOG_ERROR(tBuf); } else { // Parse // return $response['Envelope']['Body']['GetStreamUriResponse']['MediaUri']['Uri']; }; }; return NULL; } CSTR pOnvif::media_GetSnapshotUri(CSTR profileToken) { char tBuffer[DEFAULT_BUFFER_SIZE]; _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("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); LOG_ERROR(tBuf); } else { // Parse // return $response['Envelope']['Body']['GetSnapshotUriResponse']['MediaUri']['Uri']; }; }; return NULL; } /* Parses a tt:MoveStatus axis value. Returns 1 = MOVING, 0 = IDLE, -1 = UNKNOWN / not reported. */ static int parseMoveStatusValue(XMLNode & node) { if (node.isEmpty()) { return -1; } LPCTSTR tText = node.getText(0); if (tText == NULL) { return -1; } if (strstr(tText, "MOVING") != NULL) { return 1; } if (strstr(tText, "IDLE") != NULL) { return 0; } return -1; } /* ONVIF PTZ GetStatus. Position and MoveStatus are both optional in tt:PTZStatus, and inside them every axis is optional, so every element is checked before it is read; tStatus->has* tells the caller what the camera reported. An axis whose MoveStatus is not reported is counted as idle. */ bool pOnvif::ptz_GetStatus(CSTR profileToken, ptzStatus * tStatus) { if (m_pPTZURI == NULL) { return false; } if (tStatus == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; memset(tStatus, 0, sizeof(ptzStatus)); _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_PTZ_STATUS, xesc(profileToken).c_str()); if (! _send_request(m_pPTZURI, tBuffer, true)) { return false; } XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); if (tParseResults.error) { char tBuf[CTEXT]; sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); LOG_ERROR(tBuf); return false; } XMLNode aNode = response.getChildNode("Body", 0); if (aNode.isEmpty()) { return false; } XMLNode bNode = aNode.getChildNode("GetStatusResponse", 0); if (bNode.isEmpty()) { // SOAP Fault or unexpected answer return false; } XMLNode cNode = bNode.getChildNode("PTZStatus", 0); if (cNode.isEmpty()) { return false; } XMLNode dNode = cNode.getChildNode("Position", 0); if (! dNode.isEmpty()) { XMLNode eNode = dNode.getChildNode("PanTilt", 0); if (! eNode.isEmpty()) { LPCTSTR tX = eNode.getAttribute("x"); LPCTSTR tY = eNode.getAttribute("y"); if (tX != NULL && tY != NULL) { tStatus->pan = (float) atof(tX); tStatus->tilt = (float) atof(tY); tStatus->hasPosition = true; }; }; XMLNode fNode = dNode.getChildNode("Zoom", 0); if (! fNode.isEmpty()) { LPCTSTR tX = fNode.getAttribute("x"); if (tX != NULL) { tStatus->zoom = (float) atof(tX); tStatus->hasZoomPosition = true; }; }; }; XMLNode gNode = cNode.getChildNode("MoveStatus", 0); if (! gNode.isEmpty()) { XMLNode hNode = gNode.getChildNode("PanTilt", 0); XMLNode iNode = gNode.getChildNode("Zoom", 0); int tPT = parseMoveStatusValue(hNode); int tZM = parseMoveStatusValue(iNode); // Only a real IDLE / MOVING value counts as "reported" tStatus->hasMoveStatus = (tPT >= 0 || tZM >= 0); tStatus->PanTiltIdle = (tPT != 1); tStatus->ZoomIdle = (tZM != 1); tStatus->isMoving = (tPT == 1 || tZM == 1); }; return true; } bool pOnvif::ptz_GetServiceCapabilities(int8_t * moveStatus, int8_t * statusPosition) { if (moveStatus) { *moveStatus = -1; } if (statusPosition) { *statusPosition = -1; } if (m_pPTZURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_PTZ_GET_SERVICE_CAPS); if (! _send_request(m_pPTZURI, tBuffer, true)) { return false; } XMLResults tParseResults; XMLNode response = XMLNode::parseString(m_pLastResponse, "root", &tParseResults); if (tParseResults.error) { return false; } XMLNode aNode = response.getChildNode("Body", 0); if (aNode.isEmpty()) { return false; } XMLNode bNode = aNode.getChildNode("GetServiceCapabilitiesResponse", 0); if (bNode.isEmpty()) { // Older devices (PTZ service < 2.x) answer with a SOAP Fault return false; } XMLNode cNode = bNode.getChildNode("Capabilities", 0); if (cNode.isEmpty()) { return false; } LPCTSTR tMS = cNode.getAttribute("MoveStatus"); LPCTSTR tSP = cNode.getAttribute("StatusPosition"); if (moveStatus && tMS != NULL) { *moveStatus = checkBool(tMS) ? 1 : 0; } if (statusPosition && tSP != NULL) { *statusPosition = checkBool(tSP) ? 1 : 0; } return true; } bool pOnvif::ptz_GetPresets(CSTR profileToken) { if (m_pPTZURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_GET_PRESETS, xesc(profileToken).c_str()); if (_send_request(m_pPTZURI, tBuffer)) { // XMLResults tParseResults; // XMLNode response = XMLNode::parseString( m_pLastResponse, "root", &tParseResults ); // LOG("RCPT:"); // LOG( m_pLastResponse ); // if( tParseResults.error ){ // char tBuf[CTEXT]; // sprintf( tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn ); // LOG_ERROR( tBuf ); // } else { //$getpresetsresponse=$response['Envelope']['Body']['GetPresetsResponse']['Preset']; //$presets=array(); // foreach ($getpresetsresponse as $preset) { // $presets[]=array('Token'=>$preset['@attributes']['token'], // 'Name'=>$preset['Name'], // 'PTZPosition'=>$preset['PTZPosition']); // } // return $presets; return true; //}; }; return false; } bool pOnvif::ptz_GetNode(CSTR ptzNodeToken) { if (m_pPTZURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _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("%s\n", m_pLastResponse); if (tParseResults.error) { char tBuf[CTEXT]; sprintf(tBuf, "XML Parse Error %d at %d:%d", tParseResults.error, tParseResults.nLine, tParseResults.nColumn); LOG_ERROR(tBuf); } else { // return $response['Envelope']['Body']['GetNodeResponse']; }; }; return false; } bool pOnvif::ptz_GotoPreset(CSTR profileToken, CSTR presetToken, float speed_pantilt_x, float speed_pantilt_y, float speed_zoom_x) { if (m_pPTZURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _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); } bool pOnvif::ptz_RemovePreset(CSTR profileToken, CSTR presetToken) { if (m_pPTZURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_REMOVE_PRESET, xesc(profileToken).c_str(), xesc(presetToken).c_str()); return _send_request(m_pPTZURI, tBuffer, true); } bool pOnvif::ptz_SetPreset(CSTR profileToken, CSTR presetName) { if (m_pPTZURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_SET_PRESET, xesc(profileToken).c_str(), xesc(presetName).c_str()); return _send_request(m_pPTZURI, tBuffer, true); } bool pOnvif::ptz_RelativeMove(CSTR profileToken, float translation_pantilt_x, float translation_pantilt_y, float speed_pantilt_x, float speed_pantilt_y) { if (m_pPTZURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _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); } bool pOnvif::ptz_RelativeMoveZoom(CSTR profileToken, float zoom, float speedZoom) { if (m_pPTZURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_RELATIVE_ZOOM, xesc(profileToken).c_str(), zoom, speedZoom); return _send_request(m_pPTZURI, tBuffer, true); } bool pOnvif::ptz_AbsoluteMove(CSTR profileToken, float position_pantilt_x, float position_pantilt_y, float zoom) { if (m_pPTZURI == NULL) { return false; } char tBuffer[DEFAULT_BUFFER_SIZE]; _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) { 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; } 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 (m_pPTZURI == NULL) { return false; } 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); } /* Internal functions */ accessToken pOnvif::_makeToken(void) { time_t tTS = time(NULL) - m_nDeltaTime; return _passwordDigest(m_pUsername, m_pPassword, tTS); } void pOnvif::_getOnvifVersion(nodeCapability & caps) { if (caps.Device != NULL) { if (caps.Device->System != NULL) { if (caps.Device->System->SupportedVersions != NULL) { m_sOnvifVersion.Major = caps.Device->System->SupportedVersions->Major; m_sOnvifVersion.Minor = caps.Device->System->SupportedVersions->Minor; }; }; }; // 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 && caps.Media->XAddr[0] != (char) 0) { m_pMediaURI = caps.Media->XAddr; }; if (caps.Device != NULL && caps.Device->XAddr[0] != (char) 0) { m_pDeviceURI = caps.Device->XAddr; }; } /* protected function _getActiveSources($videoSources,$profiles) { $sources=array(); if (isset($videoSources['@attributes'])) { // NVT is a camera $sources[0]['sourcetoken']=$videoSources['@attributes']['token']; $this->_getProfileData($sources,0,$profiles); } else { // NVT is an encoder for ($i=0;$i_getProfileData($sources,$i,$profiles); } } // for } return $sources; } void pOnvif::_getProfileData( sources,$i, XMLNode profiles ){ //$inprofile=0; videoSourceProfile *tPtr; for( $y=0; $y < count($profiles); $y++ ){ if ($profiles[$y]['VideoSourceConfiguration']['SourceToken']==$sources[$i]['sourcetoken']) { $sources[$i][$inprofile]['profilename']=$profiles[$y]['Name']; $sources[$i][$inprofile]['profiletoken']=$profiles[$y]['@attributes']['token']; if ( isset($profiles[$y]['VideoEncoderConfiguration'])) { $sources[$i][$inprofile]['encoding']=$profiles[$y]['VideoEncoderConfiguration']['Encoding']; $sources[$i][$inprofile]['width']=$profiles[$y]['VideoEncoderConfiguration']['Resolution']['Width']; $sources[$i][$inprofile]['height']=$profiles[$y]['VideoEncoderConfiguration']['Resolution']['Height']; $sources[$i][$inprofile]['fps']=$profiles[$y]['VideoEncoderConfiguration']['RateControl']['FrameRateLimit']; $sources[$i][$inprofile]['bitrate']=$profiles[$y]['VideoEncoderConfiguration']['RateControl']['BitrateLimit']; } if ( isset($profiles[$y]['PTZConfiguration'])) { $sources[$i][$inprofile]['ptz']['name']=$profiles[$y]['PTZConfiguration']['Name']; $sources[$i][$inprofile]['ptz']['nodetoken']=$profiles[$y]['PTZConfiguration']['NodeToken']; } $inprofile++; } } }; */ /* protected function _xml2array($response) { $sxe = new SimpleXMLElement($response); $dom_sxe = dom_import_simplexml($sxe); $dom = new DOMDocument('1.0'); $dom_sxe = $dom->importNode($dom_sxe, true); $dom_sxe = $dom->appendChild($dom_sxe); $element = $dom->childNodes->item(0); foreach ($sxe->getDocNamespaces() as $name => $uri) { $element->removeAttributeNS($uri, $name); } $xmldata=$dom->saveXML(); $xmldata=substr($xmldata,strpos($xmldata,"")); $xmldata=substr($xmldata,0,strpos($xmldata,"")+strlen("")); $xml=simplexml_load_string($xmldata); $data=json_decode(json_encode((array)$xml),1); $data=array($xml->getName()=>$data); return $data; } */ /* 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; memset(&RetVal, 0, sizeof(RetVal)); if (timestamp == 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++) { 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); } tB64 = base64_encode(tNonce, sizeof(tNonce), &baseOutLen); if (tB64) { 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) { case '&' : rep = "&"; break; case '<' : rep = "<"; break; case '>' : rep = ">"; break; case '"' : rep = """; break; case '\'': rep = "'"; break; default : break; }; size_t l = (rep != NULL) ? strlen(rep) : 1; if (o + l >= dstSize) { break; // truncate, never split an entity } if (rep != NULL) { memcpy(dst + o, rep, l); } else { dst[o] = *c; } o += l; }; 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) { return false; } out[0] = (char) 0; int tLen = snprintf(out, outSize, ""); if (_hasCredentials() && tLen > 0 && tLen < (int) outSize) { 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; }; }; if (tHttp != 200 && tHttp != 0) { 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; }; 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++) { if ((*idx)->ptz) { return *idx; } }; return NULL; } void * pOnvif::parser(void * obj, void * ptr) { pOnvif * ME = (pOnvif *) obj; curlRequest * RQ = (curlRequest *) ptr; if (ME) { ME->m_mParserLock.lock(); if (RQ != ME->m_pPendingRequest) { // Late reply to a request that already timed out: ignore it, so it cannot be // taken as the answer to the request that is waiting now. 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); } ME->m_pLastResponse = (CSTR) malloc(RQ->getSize() + 1); if (ME->m_pLastResponse) { memcpy(ME->m_pLastResponse, RQ->getBuffer(), RQ->getSize()); ME->m_pLastResponse[RQ->getSize()] = (char) 0; #ifdef DEBUG_ONVIF_TRAFFIC FILE * tf; tf = fopen("Traffic.txt", "a+"); fprintf(tf, "~~~~~~~~~~~~~~~~~~~~\r\n"); fprintf(tf, "<<<<< [%d] %s\n", RQ->getSize(), ME->m_pLastResponse); fprintf(tf, "~~~~~~~~~~~~~~~~~~~~\r\n"); fclose(tf); #endif }; ME->parser_done = true; ME->m_mParserLock.unlock(); }; return NULL; } bool pOnvif::_send_request(CSTR url, CSTR post_string, bool mustReturnData) { #ifdef CURL_MANAGER 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; tRC = new curlRequest(url, (CSTR) "application/soap+xml; charset=utf-8"); if (tRC != NULL) { #ifdef DEBUG_ONVIF_TRAFFIC FILE * tf; tf = fopen("Traffic.txt", "a+"); fprintf(tf, "--------------------\r\n"); fprintf(tf, "REQ: %s (%d)\n", url, strlen(post_string)); fprintf(tf, ">>>>> %s\n", post_string); fprintf(tf, "--------------------\r\n"); fclose(tf); mustReturnData = true; // In Debug Allways Read Return #endif // 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) { tRC->setHandler((void *) this, pOnvif::parser, (void *) tRC); // Arm before the request is queued: the reply can arrive before accomplish() returns. m_mParserLock.lock(); parser_done = false; m_pPendingRequest = (void *) tRC; m_mParserLock.unlock(); if (m_pHttpAccessManager->accomplish(tRC)) { uint8_t cnt = 200; // TO = 2 second while (! RetVal && cnt--) { m_mParserLock.lock(); RetVal = parser_done; m_mParserLock.unlock(); if (! RetVal) { SLEEP(10); } }; }; // From here on any reply to tRC is stale (tRC may already be deleted by the manager) m_mParserLock.lock(); m_pPendingRequest = NULL; m_mParserLock.unlock(); if (RetVal) { RetVal = _checkReply(); } else { m_eLastError = PONVIF_ERR_COMM; }; } else { RetVal = m_pHttpAccessManager->accomplish(tRC); }; } else { LOG_ERROR("Cannot Create curlRequest!"); } m_mResponseProtector.unlock(); }; return RetVal; #else char tBuffer[CTEXT]; if (m_pCURL == NULL) { if (m_pLastResponse == NULL) { m_pLastResponse = (CSTR) malloc(DEFAULT_BUFFER_SIZE); }; m_pCURL = curl_easy_init(); if (m_pProxyHost != NULL && m_nProxyPort != 0) { curl_easy_setopt(m_pCURL, CURLOPT_PROXY, m_pProxyHost); curl_easy_setopt(m_pCURL, CURLOPT_PROXYPORT, m_nProxyPort); if (m_pProxyUsername != NULL && m_pProxyPassword != NULL) { sprintf(tBuffer, "%s:%s", m_pProxyUsername, m_pProxyPassword); curl_easy_setopt(m_pCURL, CURLOPT_PROXYUSERPWD, tBuffer); }; }; curl_easy_setopt(m_pCURL, CURLOPT_CONNECTTIMEOUT, 1); curl_easy_setopt(m_pCURL, CURLOPT_TIMEOUT, 2); curl_easy_setopt(m_pCURL, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(m_pCURL, CURLOPT_SSL_VERIFYHOST, 0); curl_easy_setopt(m_pCURL, CURLOPT_VERBOSE, 0); curl_easy_setopt(m_pCURL, CURLOPT_POST, 1); // curl_easy_setopt( m_pCURL, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, 0 ); // curl_easy_setopt( m_pCURL, CURLOPT_NOPROGRESS, 1 ); // curl_easy_setopt( m_pCURL, CURLOPT_NOSIGNAL, 1 ); curl_easy_setopt(m_pCURL, CURLOPT_TCP_FASTOPEN, 1); curl_easy_setopt(m_pCURL, CURLOPT_TCP_NODELAY, 1); // curl_easy_setopt( m_pCURL, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); curl_easy_setopt(m_pCURL, CURLOPT_WRITEFUNCTION, pOnvif::_writer); curl_easy_setopt(m_pCURL, CURLOPT_WRITEDATA, this); }; if (m_pCURL != NULL) { curl_easy_setopt(m_pCURL, CURLOPT_URL, url); struct curl_slist * sList = NULL; // Content-Type: application/soap+xml; charset=utf-8; action="http://www.onvif.org/ver20/ptz/wsdl/ContinuousMove" // Connection: Close sList = curl_slist_append(sList, "Content-Type: text/xml; charset=utf-8"); sprintf(tBuffer, "Content-Length: %d", strlen(post_string)); sList = curl_slist_append(sList, tBuffer); curl_easy_setopt(m_pCURL, CURLOPT_HTTPHEADER, sList); curl_easy_setopt(m_pCURL, CURLOPT_POSTFIELDS, post_string); sprintf(tBuffer, "%s:%s", m_pUsername, m_pPassword); curl_easy_setopt(m_pCURL, CURLOPT_USERPWD, tBuffer); switch (m_bAuthMode) { case 0: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); break; case 1: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); break; case 2: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST_IE); break; case 3: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_BEARER); break; case 4: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_NEGOTIATE); break; case 5: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); break; case 6: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_NTLM_WB); break; case 7: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_ANY); break; case 8: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE); break; case 9: curl_easy_setopt(m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_ONLY); break; // case 10: curl_easy_setopt( m_pCURL, CURLOPT_HTTPAUTH, CURLAUTH_AWS_SIGV4 ); break; }; #ifdef DEBUG char tErrorBuffer[CURL_ERROR_SIZE]; curl_easy_setopt(m_pCURL, CURLOPT_ERRORBUFFER, tErrorBuffer); #endif m_pLastIndex = 0; if (curl_easy_perform(m_pCURL)) { LOG_ERROR("CURL Failure!"); #ifdef DEBUG LOG_ERROR(tErrorBuffer); #endif } else { m_pLastResponse[m_pLastIndex] = (char) 0; return true; }; m_pLastIndex = 0; }; return false; #endif } #ifndef CURL_MANAGER int pOnvif::_writer(char * data, size_t size, size_t nmemb, pOnvif * Ptr) { if (Ptr == NULL) { return 0; } // TLOG("*"); memcpy(Ptr->m_pLastResponse + Ptr->m_pLastIndex, data, size * nmemb); Ptr->m_pLastIndex += size * nmemb; return size * nmemb; } #endif bool pOnvif::setAuthMode(uint8_t Mode) { m_bAuthMode = Mode; #ifdef DEBUG switch (m_bAuthMode) { 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; case 4 : LOG("Set Auth CURLAUTH_NEGOTIATE"); break; case 5 : LOG("Set Auth CURLAUTH_NTLM"); break; case 6 : LOG("Set Auth CURLAUTH_NTLM_WB"); break; case 7 : LOG("Set Auth CURLAUTH_ANY"); break; case 8 : LOG("Set Auth CURLAUTH_ANYSAFE"); break; case 9 : LOG("Set Auth CURLAUTH_ONLY"); break; case 10: LOG("Set Auth CURLAUTH_AWS_SIGV4"); break; }; #endif return true; } #undef LOG #undef TLOG #undef LOG_ERROR