mirror of
				https://github.com/Telecominfraproject/wlan-cloud-owprov.git
				synced 2025-10-30 18:18:03 +00:00 
			
		
		
		
	Compare commits
	
		
			14 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|   | a63dec7f8b | ||
|   | 9c5ed40d57 | ||
|   | e1ec4d9491 | ||
|   | 0437031d78 | ||
|   | 2242b02f0f | ||
|   | 8287628583 | ||
|   | f925ce12be | ||
|   | 7b3de5d5ef | ||
|   | 6007c1f06f | ||
|   | 74916abdbd | ||
|   | 0899c6f2d9 | ||
|   | f51b2bd11e | ||
|   | 8b21ef16a1 | ||
|   | 7ad4de4960 | 
| @@ -1,5 +1,5 @@ | |||||||
| cmake_minimum_required(VERSION 3.13) | cmake_minimum_required(VERSION 3.13) | ||||||
| project(owprov VERSION 2.9.0) | project(owprov VERSION 2.10.0) | ||||||
|  |  | ||||||
| set(CMAKE_CXX_STANDARD 17) | set(CMAKE_CXX_STANDARD 17) | ||||||
|  |  | ||||||
| @@ -117,6 +117,7 @@ add_executable(owprov | |||||||
|         src/framework/MicroServiceExtra.h |         src/framework/MicroServiceExtra.h | ||||||
|         src/framework/ConfigurationValidator.cpp |         src/framework/ConfigurationValidator.cpp | ||||||
|         src/framework/ConfigurationValidator.h |         src/framework/ConfigurationValidator.h | ||||||
|  |         src/framework/default_device_types.h | ||||||
|         src/UI_Prov_WebSocketNotifications.h |         src/UI_Prov_WebSocketNotifications.h | ||||||
|         src/UI_Prov_WebSocketNotifications.cpp |         src/UI_Prov_WebSocketNotifications.cpp | ||||||
|         src/RESTObjects/RESTAPI_SecurityObjects.h src/RESTObjects/RESTAPI_SecurityObjects.cpp |         src/RESTObjects/RESTAPI_SecurityObjects.h src/RESTObjects/RESTAPI_SecurityObjects.cpp | ||||||
|   | |||||||
| @@ -42,6 +42,7 @@ if [[ "$TEMPLATE_CONFIG" = 'true' ]]; then | |||||||
|   STORAGE_TYPE_MYSQL_PASSWORD=${STORAGE_TYPE_MYSQL_PASSWORD:-"owprov"} \ |   STORAGE_TYPE_MYSQL_PASSWORD=${STORAGE_TYPE_MYSQL_PASSWORD:-"owprov"} \ | ||||||
|   STORAGE_TYPE_MYSQL_DATABASE=${STORAGE_TYPE_MYSQL_DATABASE:-"owprov"} \ |   STORAGE_TYPE_MYSQL_DATABASE=${STORAGE_TYPE_MYSQL_DATABASE:-"owprov"} \ | ||||||
|   STORAGE_TYPE_MYSQL_PORT=${STORAGE_TYPE_MYSQL_PORT:-"3306"} \ |   STORAGE_TYPE_MYSQL_PORT=${STORAGE_TYPE_MYSQL_PORT:-"3306"} \ | ||||||
|  |   RRM_PROVIDERS=${RRM_PROVIDERS:-"owrrm"} \ | ||||||
|   envsubst < /owprov.properties.tmpl > $OWPROV_CONFIG/owprov.properties |   envsubst < /owprov.properties.tmpl > $OWPROV_CONFIG/owprov.properties | ||||||
| fi | fi | ||||||
|  |  | ||||||
|   | |||||||
| @@ -9,7 +9,7 @@ fullnameOverride: "" | |||||||
| images: | images: | ||||||
|   owprov: |   owprov: | ||||||
|     repository: tip-tip-wlan-cloud-ucentral.jfrog.io/owprov |     repository: tip-tip-wlan-cloud-ucentral.jfrog.io/owprov | ||||||
|     tag: v2.9.0 |     tag: v2.10.0 | ||||||
|     pullPolicy: Always |     pullPolicy: Always | ||||||
| #    regcred: | #    regcred: | ||||||
| #      registry: tip-tip-wlan-cloud-ucentral.jfrog.io | #      registry: tip-tip-wlan-cloud-ucentral.jfrog.io | ||||||
|   | |||||||
| @@ -2258,7 +2258,7 @@ paths: | |||||||
|     get: |     get: | ||||||
|       tags: |       tags: | ||||||
|         - Configuration Overrides |         - Configuration Overrides | ||||||
|       operationId: getCponfigurationOverrides |       operationId: getConfigurationOverrides | ||||||
|       summary: retrieve a list of configuration overrides for a given device |       summary: retrieve a list of configuration overrides for a given device | ||||||
|       parameters: |       parameters: | ||||||
|         - in: path |         - in: path | ||||||
| @@ -2282,7 +2282,7 @@ paths: | |||||||
|     delete: |     delete: | ||||||
|       tags: |       tags: | ||||||
|         - Configuration Overrides |         - Configuration Overrides | ||||||
|       operationId: deleteCponfigurationOverrides |       operationId: deleteConfigurationOverrides | ||||||
|       summary: delete all configuration overrides for a given device from a given source |       summary: delete all configuration overrides for a given device from a given source | ||||||
|       parameters: |       parameters: | ||||||
|         - in: path |         - in: path | ||||||
|   | |||||||
| @@ -37,10 +37,12 @@ openwifi.system.data = ${SYSTEM_DATA} | |||||||
| openwifi.system.debug = false | openwifi.system.debug = false | ||||||
| openwifi.system.uri.private = ${SYSTEM_URI_PRIVATE} | openwifi.system.uri.private = ${SYSTEM_URI_PRIVATE} | ||||||
| openwifi.system.uri.public = ${SYSTEM_URI_PUBLIC} | openwifi.system.uri.public = ${SYSTEM_URI_PUBLIC} | ||||||
| openwifi.system.commandchannel = /tmp/app.ucentralfms | openwifi.system.commandchannel = /tmp/app.owprov | ||||||
| openwifi.system.uri.ui = ${SYSTEM_URI_UI} | openwifi.system.uri.ui = ${SYSTEM_URI_UI} | ||||||
| openwifi.security.restapi.disable = ${SECURITY_RESTAPI_DISABLE} | openwifi.security.restapi.disable = ${SECURITY_RESTAPI_DISABLE} | ||||||
|  |  | ||||||
|  | rrm.providers = ${RRM_PROVIDERS} | ||||||
|  |  | ||||||
| ############################# | ############################# | ||||||
| # Generic information for all micro services | # Generic information for all micro services | ||||||
| ############################# | ############################# | ||||||
|   | |||||||
| @@ -41,7 +41,7 @@ namespace OpenWifi { | |||||||
| 		Payload.set("ObjectType", OT); | 		Payload.set("ObjectType", OT); | ||||||
| 		std::ostringstream OS; | 		std::ostringstream OS; | ||||||
| 		Payload.stringify(OS); | 		Payload.stringify(OS); | ||||||
| 		KafkaManager()->PostMessage(KafkaTopics::PROVISIONING_CHANGE, Ops[op], OS.str()); | 		KafkaManager()->PostMessage(KafkaTopics::PROVISIONING_CHANGE, Ops[op], std::make_shared<std::string>(OS.str())); | ||||||
|  |  | ||||||
| 		return true; | 		return true; | ||||||
| 	} | 	} | ||||||
|   | |||||||
| @@ -13,6 +13,7 @@ | |||||||
| #ifdef TIP_GATEWAY_SERVICE | #ifdef TIP_GATEWAY_SERVICE | ||||||
| #include "AP_WS_Server.h" | #include "AP_WS_Server.h" | ||||||
| #include "CapabilitiesCache.h" | #include "CapabilitiesCache.h" | ||||||
|  | #include "RADIUSSessionTracker.h" | ||||||
| #endif | #endif | ||||||
|  |  | ||||||
| #include "RESTAPI_GWobjects.h" | #include "RESTAPI_GWobjects.h" | ||||||
| @@ -29,6 +30,7 @@ namespace OpenWifi::GWObjects { | |||||||
| 		field_to_json(Obj, "serialNumber", SerialNumber); | 		field_to_json(Obj, "serialNumber", SerialNumber); | ||||||
| #ifdef TIP_GATEWAY_SERVICE | #ifdef TIP_GATEWAY_SERVICE | ||||||
| 		field_to_json(Obj, "deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible)); | 		field_to_json(Obj, "deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible)); | ||||||
|  | 		field_to_json(Obj, "hasRADIUSSessions", RADIUSSessionTracker()->HasSessions(SerialNumber)); | ||||||
| #endif | #endif | ||||||
| 		field_to_json(Obj, "macAddress", MACAddress); | 		field_to_json(Obj, "macAddress", MACAddress); | ||||||
| 		field_to_json(Obj, "manufacturer", Manufacturer); | 		field_to_json(Obj, "manufacturer", Manufacturer); | ||||||
| @@ -54,6 +56,9 @@ namespace OpenWifi::GWObjects { | |||||||
| 		field_to_json(Obj, "pendingConfiguration", pendingConfiguration); | 		field_to_json(Obj, "pendingConfiguration", pendingConfiguration); | ||||||
| 		field_to_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd); | 		field_to_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd); | ||||||
| 		field_to_json(Obj, "restrictionDetails", restrictionDetails); | 		field_to_json(Obj, "restrictionDetails", restrictionDetails); | ||||||
|  | 		field_to_json(Obj, "pendingUUID", pendingUUID); | ||||||
|  | 		field_to_json(Obj, "simulated", simulated); | ||||||
|  | 		field_to_json(Obj, "lastRecordedContact", lastRecordedContact); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void Device::to_json_with_status(Poco::JSON::Object &Obj) const { | 	void Device::to_json_with_status(Poco::JSON::Object &Obj) const { | ||||||
| @@ -63,7 +68,7 @@ namespace OpenWifi::GWObjects { | |||||||
| 		ConnectionState ConState; | 		ConnectionState ConState; | ||||||
|  |  | ||||||
| 		if (AP_WS_Server()->GetState(SerialNumber, ConState)) { | 		if (AP_WS_Server()->GetState(SerialNumber, ConState)) { | ||||||
| 			ConState.to_json(Obj); | 			ConState.to_json(SerialNumber,Obj); | ||||||
| 		} else { | 		} else { | ||||||
| 			field_to_json(Obj, "ipAddress", ""); | 			field_to_json(Obj, "ipAddress", ""); | ||||||
| 			field_to_json(Obj, "txBytes", (uint64_t)0); | 			field_to_json(Obj, "txBytes", (uint64_t)0); | ||||||
| @@ -75,6 +80,13 @@ namespace OpenWifi::GWObjects { | |||||||
| 			field_to_json(Obj, "associations_2G", (uint64_t)0); | 			field_to_json(Obj, "associations_2G", (uint64_t)0); | ||||||
| 			field_to_json(Obj, "associations_5G", (uint64_t)0); | 			field_to_json(Obj, "associations_5G", (uint64_t)0); | ||||||
| 			field_to_json(Obj, "associations_6G", (uint64_t)0); | 			field_to_json(Obj, "associations_6G", (uint64_t)0); | ||||||
|  | 			field_to_json(Obj, "hasRADIUSSessions", false); | ||||||
|  | 			field_to_json(Obj, "hasGPS", ConState.hasGPS); | ||||||
|  | 			field_to_json(Obj, "sanity", ConState.sanity); | ||||||
|  | 			field_to_json(Obj, "memoryUsed", ConState.memoryUsed); | ||||||
|  | 			field_to_json(Obj, "sanity", ConState.sanity); | ||||||
|  | 			field_to_json(Obj, "load", ConState.load); | ||||||
|  | 			field_to_json(Obj, "temperature", ConState.temperature); | ||||||
| 		} | 		} | ||||||
| #endif | #endif | ||||||
| 	} | 	} | ||||||
| @@ -84,20 +96,32 @@ namespace OpenWifi::GWObjects { | |||||||
| 			field_from_json(Obj, "serialNumber", SerialNumber); | 			field_from_json(Obj, "serialNumber", SerialNumber); | ||||||
| 			field_from_json(Obj, "deviceType", DeviceType); | 			field_from_json(Obj, "deviceType", DeviceType); | ||||||
| 			field_from_json(Obj, "macAddress", MACAddress); | 			field_from_json(Obj, "macAddress", MACAddress); | ||||||
|  | 			field_from_json(Obj, "manufacturer", Manufacturer); | ||||||
|  | 			field_from_json(Obj, "UUID", UUID); | ||||||
| 			field_from_json(Obj, "configuration", Configuration); | 			field_from_json(Obj, "configuration", Configuration); | ||||||
| 			field_from_json(Obj, "notes", Notes); | 			field_from_json(Obj, "notes", Notes); | ||||||
| 			field_from_json(Obj, "manufacturer", Manufacturer); | 			field_from_json(Obj, "createdTimestamp", CreationTimestamp); | ||||||
|  | 			field_from_json(Obj, "lastConfigurationChange", LastConfigurationChange); | ||||||
|  | 			field_from_json(Obj, "lastConfigurationDownload", LastConfigurationDownload); | ||||||
|  | 			field_from_json(Obj, "lastFWUpdate", LastFWUpdate); | ||||||
| 			field_from_json(Obj, "owner", Owner); | 			field_from_json(Obj, "owner", Owner); | ||||||
| 			field_from_json(Obj, "location", Location); | 			field_from_json(Obj, "location", Location); | ||||||
| 			field_from_json(Obj, "venue", Venue); | 			field_from_json(Obj, "venue", Venue); | ||||||
|  | 			field_from_json(Obj, "firmware", Firmware); | ||||||
| 			field_from_json(Obj, "compatible", Compatible); | 			field_from_json(Obj, "compatible", Compatible); | ||||||
|  | 			field_from_json(Obj, "fwUpdatePolicy", FWUpdatePolicy); | ||||||
|  | 			field_from_json(Obj, "devicePassword", DevicePassword); | ||||||
| 			field_from_json(Obj, "subscriber", subscriber); | 			field_from_json(Obj, "subscriber", subscriber); | ||||||
| 			field_from_json(Obj, "entity", entity); | 			field_from_json(Obj, "entity", entity); | ||||||
|  | 			field_from_json(Obj, "modified", modified); | ||||||
| 			field_from_json(Obj, "locale", locale); | 			field_from_json(Obj, "locale", locale); | ||||||
| 			field_from_json(Obj, "restrictedDevice", restrictedDevice); | 			field_from_json(Obj, "restrictedDevice", restrictedDevice); | ||||||
| 			field_from_json(Obj, "pendingConfiguration", pendingConfiguration); | 			field_from_json(Obj, "pendingConfiguration", pendingConfiguration); | ||||||
| 			field_from_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd); | 			field_from_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd); | ||||||
| 			field_from_json(Obj, "restrictionDetails", restrictionDetails); | 			field_from_json(Obj, "restrictionDetails", restrictionDetails); | ||||||
|  | 			field_from_json(Obj, "pendingUUID", pendingUUID); | ||||||
|  | 			field_from_json(Obj, "simulated", simulated); | ||||||
|  | 			field_from_json(Obj, "lastRecordedContact", lastRecordedContact); | ||||||
| 			return true; | 			return true; | ||||||
| 		} catch (const Poco::Exception &E) { | 		} catch (const Poco::Exception &E) { | ||||||
| 		} | 		} | ||||||
| @@ -165,6 +189,8 @@ namespace OpenWifi::GWObjects { | |||||||
| 		field_to_json(Obj, "waitingForFile", WaitingForFile); | 		field_to_json(Obj, "waitingForFile", WaitingForFile); | ||||||
| 		field_to_json(Obj, "attachFile", AttachDate); | 		field_to_json(Obj, "attachFile", AttachDate); | ||||||
| 		field_to_json(Obj, "executionTime", executionTime); | 		field_to_json(Obj, "executionTime", executionTime); | ||||||
|  | 		field_to_json(Obj, "lastTry", lastTry); | ||||||
|  | 		field_to_json(Obj, "deferred", deferred); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	bool DefaultConfiguration::from_json(const Poco::JSON::Object::Ptr &Obj) { | 	bool DefaultConfiguration::from_json(const Poco::JSON::Object::Ptr &Obj) { | ||||||
| @@ -198,7 +224,7 @@ namespace OpenWifi::GWObjects { | |||||||
| 		return false; | 		return false; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void ConnectionState::to_json(Poco::JSON::Object &Obj) const { | 	void ConnectionState::to_json([[maybe_unused]] const std::string &SerialNumber, Poco::JSON::Object &Obj)  { | ||||||
| 		field_to_json(Obj, "ipAddress", Address); | 		field_to_json(Obj, "ipAddress", Address); | ||||||
| 		field_to_json(Obj, "txBytes", TX); | 		field_to_json(Obj, "txBytes", TX); | ||||||
| 		field_to_json(Obj, "rxBytes", RX); | 		field_to_json(Obj, "rxBytes", RX); | ||||||
| @@ -220,6 +246,20 @@ namespace OpenWifi::GWObjects { | |||||||
| 		field_to_json(Obj, "connectionCompletionTime", connectionCompletionTime); | 		field_to_json(Obj, "connectionCompletionTime", connectionCompletionTime); | ||||||
| 		field_to_json(Obj, "totalConnectionTime", Utils::Now() - started); | 		field_to_json(Obj, "totalConnectionTime", Utils::Now() - started); | ||||||
| 		field_to_json(Obj, "certificateExpiryDate", certificateExpiryDate); | 		field_to_json(Obj, "certificateExpiryDate", certificateExpiryDate); | ||||||
|  | #ifdef TIP_GATEWAY_SERVICE | ||||||
|  | 		hasRADIUSSessions = RADIUSSessionTracker()->HasSessions(SerialNumber); | ||||||
|  | 		AP_WS_Server()->ExtendedAttributes(SerialNumber, hasGPS, sanity, | ||||||
|  | 										   memoryUsed, | ||||||
|  | 										   load, | ||||||
|  | 										   temperature); | ||||||
|  | #endif | ||||||
|  | 		field_to_json(Obj, "hasRADIUSSessions", hasRADIUSSessions ); | ||||||
|  | 		field_to_json(Obj, "hasGPS", hasGPS); | ||||||
|  | 		field_to_json(Obj, "sanity", sanity); | ||||||
|  | 		field_to_json(Obj, "memoryUsed", memoryUsed); | ||||||
|  | 		field_to_json(Obj, "sanity", sanity); | ||||||
|  | 		field_to_json(Obj, "load", load); | ||||||
|  | 		field_to_json(Obj, "temperature", temperature); | ||||||
|  |  | ||||||
| 		switch (VerifiedCertificate) { | 		switch (VerifiedCertificate) { | ||||||
| 		case NO_CERTIFICATE: | 		case NO_CERTIFICATE: | ||||||
| @@ -234,6 +274,9 @@ namespace OpenWifi::GWObjects { | |||||||
| 		case VERIFIED: | 		case VERIFIED: | ||||||
| 			field_to_json(Obj, "verifiedCertificate", "VERIFIED"); | 			field_to_json(Obj, "verifiedCertificate", "VERIFIED"); | ||||||
| 			break; | 			break; | ||||||
|  | 		case SIMULATED: | ||||||
|  | 			field_to_json(Obj, "verifiedCertificate", "SIMULATED"); | ||||||
|  | 			break; | ||||||
| 		default: | 		default: | ||||||
| 			field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE"); | 			field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE"); | ||||||
| 			break; | 			break; | ||||||
| @@ -490,6 +533,29 @@ namespace OpenWifi::GWObjects { | |||||||
| 		return false; | 		return false; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	void RangeOptions::to_json(Poco::JSON::Object &Obj) const { | ||||||
|  | 		field_to_json(Obj, "NO_IR", NO_IR); | ||||||
|  | 		field_to_json(Obj, "AUTO_BW", AUTO_BW); | ||||||
|  | 		field_to_json(Obj, "DFS", DFS); | ||||||
|  | 		field_to_json(Obj, "NO_OUTDOOR", NO_OUTDOOR); | ||||||
|  | 		field_to_json(Obj, "wmmrule_ETSI", wmmrule_ETSI); | ||||||
|  | 		field_to_json(Obj, "NO_OFDM", NO_OFDM); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	void FrequencyRange::to_json(Poco::JSON::Object &Obj) const { | ||||||
|  | 		field_to_json(Obj, "from", from); | ||||||
|  | 		field_to_json(Obj, "to", to); | ||||||
|  | 		field_to_json(Obj, "channelWidth", channelWidth); | ||||||
|  | 		field_to_json(Obj, "powerDb", powerDb); | ||||||
|  | 		field_to_json(Obj, "options", options); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	void RegulatoryCountryInfo::to_json(Poco::JSON::Object &Obj) const { | ||||||
|  | 		field_to_json(Obj, "country", country); | ||||||
|  | 		field_to_json(Obj, "domain", domain); | ||||||
|  | 		field_to_json(Obj, "ranges", ranges); | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	void DeviceRestrictionsKeyInfo::to_json(Poco::JSON::Object &Obj) const { | 	void DeviceRestrictionsKeyInfo::to_json(Poco::JSON::Object &Obj) const { | ||||||
| 		field_to_json(Obj, "vendor", vendor); | 		field_to_json(Obj, "vendor", vendor); | ||||||
| 		field_to_json(Obj, "algo", algo); | 		field_to_json(Obj, "algo", algo); | ||||||
| @@ -544,4 +610,42 @@ namespace OpenWifi::GWObjects { | |||||||
| 				(T.commands != commands) || (T.developer != developer) || (T.ssh != ssh) || | 				(T.commands != commands) || (T.developer != developer) || (T.ssh != ssh) || | ||||||
| 				(T.key_info != key_info) || (T.country != country)); | 				(T.key_info != key_info) || (T.country != country)); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	void RADIUSSession::to_json(Poco::JSON::Object &Obj) const { | ||||||
|  | 		field_to_json(Obj, "started", started); | ||||||
|  | 		field_to_json(Obj, "lastTransaction", lastTransaction); | ||||||
|  | 		field_to_json(Obj, "destination", destination); | ||||||
|  | 		field_to_json(Obj, "serialNumber", serialNumber); | ||||||
|  | 		field_to_json(Obj, "userName", userName); | ||||||
|  | 		field_to_json(Obj, "accountingSessionId", accountingSessionId); | ||||||
|  | 		field_to_json(Obj, "accountingMultiSessionId", accountingMultiSessionId); | ||||||
|  | 		field_to_json(Obj, "inputPackets", inputPackets); | ||||||
|  | 		field_to_json(Obj, "outputPackets", outputPackets); | ||||||
|  | 		field_to_json(Obj, "inputOctets", inputOctets); | ||||||
|  | 		field_to_json(Obj, "outputOctets", outputOctets); | ||||||
|  | 		field_to_json(Obj, "inputGigaWords", inputGigaWords); | ||||||
|  | 		field_to_json(Obj, "outputGigaWords", outputGigaWords); | ||||||
|  | 		field_to_json(Obj, "sessionTime", sessionTime); | ||||||
|  | 		field_to_json(Obj, "callingStationId", callingStationId); | ||||||
|  | 		field_to_json(Obj, "chargeableUserIdentity", chargeableUserIdentity); | ||||||
|  | 		field_to_json(Obj, "interface", interface); | ||||||
|  | 		field_to_json(Obj, "secret", secret); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	void RADIUSSessionList::to_json(Poco::JSON::Object &Obj) const { | ||||||
|  | 		field_to_json(Obj, "sessions", sessions); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	bool RadiusCoADMParameters::from_json(const Poco::JSON::Object::Ptr &Obj) { | ||||||
|  | 		try { | ||||||
|  | 			field_from_json(Obj, "accountingSessionId", accountingSessionId); | ||||||
|  | 			field_from_json(Obj, "accountingMultiSessionId", accountingMultiSessionId); | ||||||
|  | 			field_from_json(Obj, "callingStationId", callingStationId); | ||||||
|  | 			field_from_json(Obj, "chargeableUserIdentity", chargeableUserIdentity); | ||||||
|  | 			return true; | ||||||
|  | 		} catch (const Poco::Exception &E) { | ||||||
|  | 		} | ||||||
|  | 		return false; | ||||||
|  | 	} | ||||||
|  |  | ||||||
| } // namespace OpenWifi::GWObjects | } // namespace OpenWifi::GWObjects | ||||||
|   | |||||||
| @@ -11,9 +11,13 @@ | |||||||
| #include "Poco/JSON/Object.h" | #include "Poco/JSON/Object.h" | ||||||
| #include "RESTAPI_SecurityObjects.h" | #include "RESTAPI_SecurityObjects.h" | ||||||
|  |  | ||||||
|  | #ifdef TIP_GATEWAY_SERVICE | ||||||
|  | #include <RADIUS_helpers.h> | ||||||
|  | #endif | ||||||
|  |  | ||||||
| namespace OpenWifi::GWObjects { | namespace OpenWifi::GWObjects { | ||||||
|  |  | ||||||
| 	enum CertificateValidation { NO_CERTIFICATE, VALID_CERTIFICATE, MISMATCH_SERIAL, VERIFIED }; | 	enum CertificateValidation { NO_CERTIFICATE, VALID_CERTIFICATE, MISMATCH_SERIAL, VERIFIED, SIMULATED }; | ||||||
|  |  | ||||||
| 	struct ConnectionState { | 	struct ConnectionState { | ||||||
| 		uint64_t MessageCount = 0; | 		uint64_t MessageCount = 0; | ||||||
| @@ -38,8 +42,14 @@ namespace OpenWifi::GWObjects { | |||||||
| 		uint64_t sessionId = 0; | 		uint64_t sessionId = 0; | ||||||
| 		double connectionCompletionTime = 0.0; | 		double connectionCompletionTime = 0.0; | ||||||
| 		std::uint64_t certificateExpiryDate = 0; | 		std::uint64_t certificateExpiryDate = 0; | ||||||
|  | 		bool hasRADIUSSessions = false; | ||||||
|  | 		bool hasGPS = false; | ||||||
|  | 		std::uint64_t sanity=0; | ||||||
|  | 		std::double_t memoryUsed=0.0; | ||||||
|  | 		std::double_t load=0.0; | ||||||
|  | 		std::double_t temperature=0.0; | ||||||
|  |  | ||||||
| 		void to_json(Poco::JSON::Object &Obj) const; | 		void to_json(const std::string &SerialNumber, Poco::JSON::Object &Obj) ; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	struct DeviceRestrictionsKeyInfo { | 	struct DeviceRestrictionsKeyInfo { | ||||||
| @@ -96,6 +106,9 @@ namespace OpenWifi::GWObjects { | |||||||
| 		std::string pendingConfiguration; | 		std::string pendingConfiguration; | ||||||
| 		std::string pendingConfigurationCmd; | 		std::string pendingConfigurationCmd; | ||||||
| 		DeviceRestrictions restrictionDetails; | 		DeviceRestrictions restrictionDetails; | ||||||
|  | 		std::uint64_t pendingUUID = 0; | ||||||
|  | 		bool simulated=false; | ||||||
|  | 		std::uint64_t lastRecordedContact=0; | ||||||
|  |  | ||||||
| 		void to_json(Poco::JSON::Object &Obj) const; | 		void to_json(Poco::JSON::Object &Obj) const; | ||||||
| 		void to_json_with_status(Poco::JSON::Object &Obj) const; | 		void to_json_with_status(Poco::JSON::Object &Obj) const; | ||||||
| @@ -188,7 +201,11 @@ namespace OpenWifi::GWObjects { | |||||||
| 		uint64_t AttachSize = 0; | 		uint64_t AttachSize = 0; | ||||||
| 		std::string AttachType; | 		std::string AttachType; | ||||||
| 		double executionTime = 0.0; | 		double executionTime = 0.0; | ||||||
|  | 		std::uint64_t lastTry = 0; | ||||||
|  | 		bool deferred = false; | ||||||
|  |  | ||||||
| 		void to_json(Poco::JSON::Object &Obj) const; | 		void to_json(Poco::JSON::Object &Obj) const; | ||||||
|  | 		bool from_json(const Poco::JSON::Object::Ptr &Obj); | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	struct BlackListedDevice { | 	struct BlackListedDevice { | ||||||
| @@ -334,4 +351,76 @@ namespace OpenWifi::GWObjects { | |||||||
| 		bool from_json(const Poco::JSON::Object::Ptr &Obj); | 		bool from_json(const Poco::JSON::Object::Ptr &Obj); | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
|  | 	struct RangeOptions { | ||||||
|  | 		bool NO_IR=false; | ||||||
|  | 		bool AUTO_BW=false; | ||||||
|  | 		bool DFS=false; | ||||||
|  | 		bool NO_OUTDOOR=false; | ||||||
|  | 		bool wmmrule_ETSI=false; | ||||||
|  | 		bool NO_OFDM=false; | ||||||
|  |  | ||||||
|  | 		void to_json(Poco::JSON::Object &Obj) const; | ||||||
|  | 	}; | ||||||
|  |  | ||||||
|  | 	struct FrequencyRange { | ||||||
|  | 		float from = 0.0; | ||||||
|  | 		float to = 0.0; | ||||||
|  | 		int channelWidth = 0; | ||||||
|  | 		int powerDb = 0; | ||||||
|  | 		RangeOptions    options; | ||||||
|  |  | ||||||
|  | 		void to_json(Poco::JSON::Object &Obj) const; | ||||||
|  | 	}; | ||||||
|  |  | ||||||
|  | 	struct RegulatoryCountryInfo { | ||||||
|  | 		std::string country; | ||||||
|  | 		std::string domain; | ||||||
|  | 		std::vector<FrequencyRange>   ranges; | ||||||
|  |  | ||||||
|  | 		void to_json(Poco::JSON::Object &Obj) const; | ||||||
|  | 	}; | ||||||
|  |  | ||||||
|  | 	using RegulatoryInfoCountryMap = std::map<std::string,RegulatoryCountryInfo>; | ||||||
|  |  | ||||||
|  | 	struct RADIUSSession { | ||||||
|  | 		std::uint64_t 			started=0, | ||||||
|  | 								lastTransaction=0; | ||||||
|  | 		std::string 			serialNumber, | ||||||
|  | 								destination, | ||||||
|  | 								userName, | ||||||
|  | 					 			accountingSessionId, | ||||||
|  | 								accountingMultiSessionId, | ||||||
|  | 					 			callingStationId, | ||||||
|  | 								chargeableUserIdentity, | ||||||
|  | 								secret, | ||||||
|  | 								interface; | ||||||
|  | 		std::uint64_t 			inputPackets = 0, | ||||||
|  | 								outputPackets = 0, | ||||||
|  | 								inputOctets = 0, | ||||||
|  | 								outputOctets = 0, | ||||||
|  | 								inputGigaWords = 0, | ||||||
|  | 								outputGigaWords = 0; | ||||||
|  | 		std::uint32_t 			sessionTime = 0; | ||||||
|  |  | ||||||
|  | #ifdef TIP_GATEWAY_SERVICE | ||||||
|  | 		RADIUS::RadiusPacket	accountingPacket; | ||||||
|  | #endif | ||||||
|  |  | ||||||
|  | 		void to_json(Poco::JSON::Object &Obj) const; | ||||||
|  | 	}; | ||||||
|  |  | ||||||
|  | 	struct RADIUSSessionList { | ||||||
|  | 		std::vector<RADIUSSession>	sessions; | ||||||
|  | 		void to_json(Poco::JSON::Object &Obj) const; | ||||||
|  | 	}; | ||||||
|  |  | ||||||
|  | 	struct RadiusCoADMParameters { | ||||||
|  | 		std::string 			accountingSessionId, | ||||||
|  | 								accountingMultiSessionId, | ||||||
|  | 								callingStationId, | ||||||
|  | 								chargeableUserIdentity; | ||||||
|  |  | ||||||
|  | 		bool from_json(const Poco::JSON::Object::Ptr &Obj); | ||||||
|  | 	}; | ||||||
|  |  | ||||||
| } // namespace OpenWifi::GWObjects | } // namespace OpenWifi::GWObjects | ||||||
|   | |||||||
| @@ -4,17 +4,19 @@ | |||||||
|  |  | ||||||
| #include "ALBserver.h" | #include "ALBserver.h" | ||||||
|  |  | ||||||
| #include "framework/utils.h" |  | ||||||
| #include "framework/MicroServiceFuncs.h" |  | ||||||
| #include "fmt/format.h" | #include "fmt/format.h" | ||||||
|  | #include "framework/MicroServiceFuncs.h" | ||||||
|  | #include "framework/utils.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) { | 	void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request, | ||||||
|  | 										  Poco::Net::HTTPServerResponse &Response) { | ||||||
| 		Utils::SetThreadName("alb-request"); | 		Utils::SetThreadName("alb-request"); | ||||||
| 		try { | 		try { | ||||||
| 			if((id_ % 100) == 0) { | 			if ((id_ % 100) == 0) { | ||||||
| 				Logger_.debug(fmt::format("ALB-REQUEST({}): ALB Request {}.", Request.clientAddress().toString(), id_)); | 				Logger_.debug(fmt::format("ALB-REQUEST({}): ALB Request {}.", | ||||||
|  | 										  Request.clientAddress().toString(), id_)); | ||||||
| 			} | 			} | ||||||
| 			Response.setChunkedTransferEncoding(true); | 			Response.setChunkedTransferEncoding(true); | ||||||
| 			Response.setContentType("text/html"); | 			Response.setContentType("text/html"); | ||||||
| @@ -26,31 +28,27 @@ namespace OpenWifi { | |||||||
| 			std::ostream &Answer = Response.send(); | 			std::ostream &Answer = Response.send(); | ||||||
| 			Answer << "process Alive and kicking!"; | 			Answer << "process Alive and kicking!"; | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger & L): | 	ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger &L) : Logger_(L) {} | ||||||
| 		Logger_(L) { |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	ALBRequestHandler* ALBRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest& request) { | 	ALBRequestHandler * | ||||||
|  | 	ALBRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &request) { | ||||||
| 		if (request.getURI() == "/") | 		if (request.getURI() == "/") | ||||||
| 			return new ALBRequestHandler(Logger_, req_id_++); | 			return new ALBRequestHandler(Logger_, req_id_++); | ||||||
| 		else | 		else | ||||||
| 			return nullptr; | 			return nullptr; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	ALBHealthCheckServer::ALBHealthCheckServer() : | 	ALBHealthCheckServer::ALBHealthCheckServer() | ||||||
| 		  SubSystemServer("ALBHealthCheckServer", "ALB-SVR", "alb") | 		: SubSystemServer("ALBHealthCheckServer", "ALB-SVR", "alb") {} | ||||||
| 	{ |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	int ALBHealthCheckServer::Start() { | 	int ALBHealthCheckServer::Start() { | ||||||
| 		if(MicroServiceConfigGetBool("alb.enable",false)) { | 		if (MicroServiceConfigGetBool("alb.enable", false)) { | ||||||
|             poco_information(Logger(),"Starting..."); | 			poco_information(Logger(), "Starting..."); | ||||||
| 			Running_=true; | 			Running_ = true; | ||||||
| 			Port_ = (int)MicroServiceConfigGetInt("alb.port",15015); | 			Port_ = (int)MicroServiceConfigGetInt("alb.port", 15015); | ||||||
| 			Poco::Net::IPAddress Addr(Poco::Net::IPAddress::wildcard( | 			Poco::Net::IPAddress Addr(Poco::Net::IPAddress::wildcard( | ||||||
| 				Poco::Net::Socket::supportsIPv6() ? Poco::Net::AddressFamily::IPv6 | 				Poco::Net::Socket::supportsIPv6() ? Poco::Net::AddressFamily::IPv6 | ||||||
| 												  : Poco::Net::AddressFamily::IPv4)); | 												  : Poco::Net::AddressFamily::IPv4)); | ||||||
| @@ -60,7 +58,8 @@ namespace OpenWifi { | |||||||
| 			Socket_ = std::make_unique<Poco::Net::ServerSocket>(SockAddr, Port_); | 			Socket_ = std::make_unique<Poco::Net::ServerSocket>(SockAddr, Port_); | ||||||
| 			auto Params = new Poco::Net::HTTPServerParams; | 			auto Params = new Poco::Net::HTTPServerParams; | ||||||
| 			Params->setName("ws:alb"); | 			Params->setName("ws:alb"); | ||||||
| 			Server_ = std::make_unique<Poco::Net::HTTPServer>(new ALBRequestHandlerFactory(Logger()), *Socket_, Params); | 			Server_ = std::make_unique<Poco::Net::HTTPServer>( | ||||||
|  | 				new ALBRequestHandlerFactory(Logger()), *Socket_, Params); | ||||||
| 			Server_->start(); | 			Server_->start(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| @@ -68,10 +67,10 @@ namespace OpenWifi { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void ALBHealthCheckServer::Stop() { | 	void ALBHealthCheckServer::Stop() { | ||||||
| 		poco_information(Logger(),"Stopping..."); | 		poco_information(Logger(), "Stopping..."); | ||||||
| 		if(Running_) | 		if (Running_) | ||||||
| 			Server_->stopAll(true); | 			Server_->stopAll(true); | ||||||
| 		poco_information(Logger(),"Stopped..."); | 		poco_information(Logger(), "Stopped..."); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } // namespace OpenWifi | } // namespace OpenWifi | ||||||
| @@ -7,35 +7,34 @@ | |||||||
| #include "framework/SubSystemServer.h" | #include "framework/SubSystemServer.h" | ||||||
|  |  | ||||||
| #include "Poco/Net/HTTPRequestHandler.h" | #include "Poco/Net/HTTPRequestHandler.h" | ||||||
| #include "Poco/Net/HTTPServerRequest.h" |  | ||||||
| #include "Poco/Net/HTTPServerResponse.h" |  | ||||||
| #include "Poco/Net/HTTPRequestHandlerFactory.h" | #include "Poco/Net/HTTPRequestHandlerFactory.h" | ||||||
| #include "Poco/Net/HTTPServer.h" | #include "Poco/Net/HTTPServer.h" | ||||||
|  | #include "Poco/Net/HTTPServerRequest.h" | ||||||
|  | #include "Poco/Net/HTTPServerResponse.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	class ALBRequestHandler: public Poco::Net::HTTPRequestHandler { | 	class ALBRequestHandler : public Poco::Net::HTTPRequestHandler { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit ALBRequestHandler(Poco::Logger & L, uint64_t id) | 		explicit ALBRequestHandler(Poco::Logger &L, uint64_t id) : Logger_(L), id_(id) {} | ||||||
|                 : Logger_(L), id_(id) { |  | ||||||
|         } |  | ||||||
|  |  | ||||||
| 		void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) override; | 		void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request, | ||||||
|  | 						   Poco::Net::HTTPServerResponse &Response) override; | ||||||
| 	  private: |  | ||||||
| 		Poco::Logger 	& Logger_; |  | ||||||
| 		uint64_t 		id_; |  | ||||||
| 	}; |  | ||||||
|  |  | ||||||
| 	class ALBRequestHandlerFactory: public Poco::Net::HTTPRequestHandlerFactory |  | ||||||
| 	{ |  | ||||||
| 	  public: |  | ||||||
| 		explicit ALBRequestHandlerFactory(Poco::Logger & L); |  | ||||||
| 		ALBRequestHandler* createRequestHandler(const Poco::Net::HTTPServerRequest& request) override; |  | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		Poco::Logger &Logger_; | 		Poco::Logger &Logger_; | ||||||
| 		inline static std::atomic_uint64_t 			req_id_=1; | 		uint64_t id_; | ||||||
|  | 	}; | ||||||
|  |  | ||||||
|  | 	class ALBRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { | ||||||
|  | 	  public: | ||||||
|  | 		explicit ALBRequestHandlerFactory(Poco::Logger &L); | ||||||
|  | 		ALBRequestHandler * | ||||||
|  | 		createRequestHandler(const Poco::Net::HTTPServerRequest &request) override; | ||||||
|  |  | ||||||
|  | 	  private: | ||||||
|  | 		Poco::Logger &Logger_; | ||||||
|  | 		inline static std::atomic_uint64_t req_id_ = 1; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	class ALBHealthCheckServer : public SubSystemServer { | 	class ALBHealthCheckServer : public SubSystemServer { | ||||||
| @@ -54,10 +53,9 @@ namespace OpenWifi { | |||||||
| 		std::unique_ptr<Poco::Net::HTTPServer> Server_; | 		std::unique_ptr<Poco::Net::HTTPServer> Server_; | ||||||
| 		std::unique_ptr<Poco::Net::ServerSocket> Socket_; | 		std::unique_ptr<Poco::Net::ServerSocket> Socket_; | ||||||
| 		int Port_ = 0; | 		int Port_ = 0; | ||||||
| 		mutable std::atomic_bool                    Running_=false; | 		mutable std::atomic_bool Running_ = false; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	inline auto ALBHealthCheckServer() { return ALBHealthCheckServer::instance(); } | 	inline auto ALBHealthCheckServer() { return ALBHealthCheckServer::instance(); } | ||||||
|  |  | ||||||
| } // namespace OpenWifi | } // namespace OpenWifi | ||||||
|  |  | ||||||
|   | |||||||
| @@ -4,25 +4,22 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include "Poco/Logger.h" |  | ||||||
| #include "Poco/JSON/Parser.h" | #include "Poco/JSON/Parser.h" | ||||||
|  | #include "Poco/Logger.h" | ||||||
|  | #include "Poco/Net/HTTPSClientSession.h" | ||||||
| #include "Poco/Net/HTTPServerRequest.h" | #include "Poco/Net/HTTPServerRequest.h" | ||||||
| #include "Poco/Net/HTTPServerResponse.h" | #include "Poco/Net/HTTPServerResponse.h" | ||||||
| #include "Poco/Net/HTTPSClientSession.h" |  | ||||||
| #include "Poco/URI.h" | #include "Poco/URI.h" | ||||||
|  |  | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|     inline void API_Proxy( Poco::Logger &Logger, | 	inline void API_Proxy(Poco::Logger &Logger, Poco::Net::HTTPServerRequest *Request, | ||||||
|                     Poco::Net::HTTPServerRequest *Request, | 						  Poco::Net::HTTPServerResponse *Response, const char *ServiceType, | ||||||
|                     Poco::Net::HTTPServerResponse *Response, | 						  const char *PathRewrite, uint64_t msTimeout_ = 10000) { | ||||||
|                     const char * ServiceType, |  | ||||||
|                     const char * PathRewrite, |  | ||||||
|                     uint64_t msTimeout_ = 10000 ) { |  | ||||||
| 		try { | 		try { | ||||||
| 			auto Services = MicroServiceGetServices(ServiceType); | 			auto Services = MicroServiceGetServices(ServiceType); | ||||||
|             for(auto const &Svc:Services) { | 			for (auto const &Svc : Services) { | ||||||
| 				Poco::URI SourceURI(Request->getURI()); | 				Poco::URI SourceURI(Request->getURI()); | ||||||
| 				Poco::URI DestinationURI(Svc.PrivateEndPoint); | 				Poco::URI DestinationURI(Svc.PrivateEndPoint); | ||||||
| 				DestinationURI.setPath(PathRewrite); | 				DestinationURI.setPath(PathRewrite); | ||||||
| @@ -31,20 +28,21 @@ namespace OpenWifi { | |||||||
| 				// std::cout << "     Source: " << SourceURI.toString() << std::endl; | 				// std::cout << "     Source: " << SourceURI.toString() << std::endl; | ||||||
| 				// std::cout << "Destination: " << DestinationURI.toString() << std::endl; | 				// std::cout << "Destination: " << DestinationURI.toString() << std::endl; | ||||||
|  |  | ||||||
|                 Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(), DestinationURI.getPort()); | 				Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(), | ||||||
|  | 													  DestinationURI.getPort()); | ||||||
| 				Session.setKeepAlive(true); | 				Session.setKeepAlive(true); | ||||||
|                 Session.setTimeout(Poco::Timespan(msTimeout_/1000, msTimeout_ % 1000)); | 				Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); | ||||||
| 				Poco::Net::HTTPRequest ProxyRequest(Request->getMethod(), | 				Poco::Net::HTTPRequest ProxyRequest(Request->getMethod(), | ||||||
| 													DestinationURI.getPathAndQuery(), | 													DestinationURI.getPathAndQuery(), | ||||||
| 													Poco::Net::HTTPMessage::HTTP_1_1); | 													Poco::Net::HTTPMessage::HTTP_1_1); | ||||||
|                 if(Request->has("Authorization")) { | 				if (Request->has("Authorization")) { | ||||||
| 					ProxyRequest.add("Authorization", Request->get("Authorization")); | 					ProxyRequest.add("Authorization", Request->get("Authorization")); | ||||||
| 				} else { | 				} else { | ||||||
| 					ProxyRequest.add("X-API-KEY", Svc.AccessKey); | 					ProxyRequest.add("X-API-KEY", Svc.AccessKey); | ||||||
| 					ProxyRequest.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | 					ProxyRequest.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
|                 if(Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE) { | 				if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE) { | ||||||
| 					Session.sendRequest(ProxyRequest); | 					Session.sendRequest(ProxyRequest); | ||||||
| 					Poco::Net::HTTPResponse ProxyResponse; | 					Poco::Net::HTTPResponse ProxyResponse; | ||||||
| 					Session.receiveResponse(ProxyResponse); | 					Session.receiveResponse(ProxyResponse); | ||||||
| @@ -56,19 +54,19 @@ namespace OpenWifi { | |||||||
| 					std::stringstream SS; | 					std::stringstream SS; | ||||||
| 					try { | 					try { | ||||||
| 						auto Body = P.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>(); | 						auto Body = P.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>(); | ||||||
|                         Poco::JSON::Stringifier::condense(Body,SS); | 						Poco::JSON::Stringifier::condense(Body, SS); | ||||||
| 						SS << "\r\n\r\n"; | 						SS << "\r\n\r\n"; | ||||||
|                     } catch(const Poco::Exception &E) { | 					} catch (const Poco::Exception &E) { | ||||||
| 						Logger.log(E); | 						Logger.log(E); | ||||||
| 					} | 					} | ||||||
|  |  | ||||||
|                     if(SS.str().empty()) { | 					if (SS.str().empty()) { | ||||||
| 						Session.sendRequest(ProxyRequest); | 						Session.sendRequest(ProxyRequest); | ||||||
| 					} else { | 					} else { | ||||||
| 						ProxyRequest.setContentType("application/json"); | 						ProxyRequest.setContentType("application/json"); | ||||||
| 						ProxyRequest.setContentLength(SS.str().size()); | 						ProxyRequest.setContentLength(SS.str().size()); | ||||||
|                         std::ostream & os = Session.sendRequest(ProxyRequest); | 						std::ostream &os = Session.sendRequest(ProxyRequest); | ||||||
|                         os << SS.str() ; | 						os << SS.str(); | ||||||
| 					} | 					} | ||||||
|  |  | ||||||
| 					Poco::Net::HTTPResponse ProxyResponse; | 					Poco::Net::HTTPResponse ProxyResponse; | ||||||
| @@ -76,15 +74,15 @@ namespace OpenWifi { | |||||||
| 					try { | 					try { | ||||||
| 						std::istream &ProxyResponseStream = Session.receiveResponse(ProxyResponse); | 						std::istream &ProxyResponseStream = Session.receiveResponse(ProxyResponse); | ||||||
| 						Poco::JSON::Parser P2; | 						Poco::JSON::Parser P2; | ||||||
|                         auto ProxyResponseBody = P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>(); | 						auto ProxyResponseBody = | ||||||
|                         Poco::JSON::Stringifier::condense(ProxyResponseBody,SSR); | 							P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>(); | ||||||
|  | 						Poco::JSON::Stringifier::condense(ProxyResponseBody, SSR); | ||||||
| 						Response->setContentType("application/json"); | 						Response->setContentType("application/json"); | ||||||
| 						Response->setContentLength(SSR.str().size()); | 						Response->setContentLength(SSR.str().size()); | ||||||
| 						Response->setStatus(ProxyResponse.getStatus()); | 						Response->setStatus(ProxyResponse.getStatus()); | ||||||
|                         Response->sendBuffer(SSR.str().c_str(),SSR.str().size()); | 						Response->sendBuffer(SSR.str().c_str(), SSR.str().size()); | ||||||
| 						return; | 						return; | ||||||
|                     } catch( const Poco::Exception & E) { | 					} catch (const Poco::Exception &E) { | ||||||
|  |  | ||||||
| 					} | 					} | ||||||
| 					Response->setStatus(ProxyResponse.getStatus()); | 					Response->setStatus(ProxyResponse.getStatus()); | ||||||
| 					Response->send(); | 					Response->send(); | ||||||
| @@ -96,4 +94,4 @@ namespace OpenWifi { | |||||||
| 			Logger.log(E); | 			Logger.log(E); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -4,13 +4,13 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include <string> |  | ||||||
| #include <fstream> | #include <fstream> | ||||||
| #include <iomanip> | #include <iomanip> | ||||||
| #include <iostream> | #include <iostream> | ||||||
|  | #include <string> | ||||||
|  |  | ||||||
| #include "Poco/StreamCopier.h" |  | ||||||
| #include "Poco/File.h" | #include "Poco/File.h" | ||||||
|  | #include "Poco/StreamCopier.h" | ||||||
|  |  | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  |  | ||||||
| @@ -18,7 +18,6 @@ | |||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
|  |  | ||||||
| 	class AppServiceRegistry { | 	class AppServiceRegistry { | ||||||
| 	  public: | 	  public: | ||||||
| 		AppServiceRegistry() { | 		AppServiceRegistry() { | ||||||
| @@ -26,7 +25,7 @@ namespace OpenWifi { | |||||||
| 			Poco::File F(FileName); | 			Poco::File F(FileName); | ||||||
|  |  | ||||||
| 			try { | 			try { | ||||||
| 				if(F.exists()) { | 				if (F.exists()) { | ||||||
| 					std::ostringstream OS; | 					std::ostringstream OS; | ||||||
| 					std::ifstream IF(FileName); | 					std::ifstream IF(FileName); | ||||||
| 					Poco::StreamCopier::copyStream(IF, OS); | 					Poco::StreamCopier::copyStream(IF, OS); | ||||||
| @@ -37,55 +36,53 @@ namespace OpenWifi { | |||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		static AppServiceRegistry & instance() { | 		static AppServiceRegistry &instance() { | ||||||
| 			static auto instance_= new AppServiceRegistry; | 			static auto instance_ = new AppServiceRegistry; | ||||||
| 			return *instance_; | 			return *instance_; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline ~AppServiceRegistry() { | 		inline ~AppServiceRegistry() { Save(); } | ||||||
| 			Save(); |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		inline void Save() { | 		inline void Save() { | ||||||
| 			std::istringstream  IS( to_string(Registry_)); | 			std::istringstream IS(to_string(Registry_)); | ||||||
| 			std::ofstream OF; | 			std::ofstream OF; | ||||||
| 			OF.open(FileName,std::ios::binary | std::ios::trunc); | 			OF.open(FileName, std::ios::binary | std::ios::trunc); | ||||||
| 			Poco::StreamCopier::copyStream(IS, OF); | 			Poco::StreamCopier::copyStream(IS, OF); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void Set(const char *Key, uint64_t Value ) { | 		inline void Set(const char *Key, uint64_t Value) { | ||||||
| 			Registry_[Key] = Value; | 			Registry_[Key] = Value; | ||||||
| 			Save(); | 			Save(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void Set(const char *Key, const std::string &Value ) { | 		inline void Set(const char *Key, const std::string &Value) { | ||||||
| 			Registry_[Key] = Value; | 			Registry_[Key] = Value; | ||||||
| 			Save(); | 			Save(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void Set(const char *Key, bool Value ) { | 		inline void Set(const char *Key, bool Value) { | ||||||
| 			Registry_[Key] = Value; | 			Registry_[Key] = Value; | ||||||
| 			Save(); | 			Save(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline bool Get(const char *Key, bool & Value ) { | 		inline bool Get(const char *Key, bool &Value) { | ||||||
| 			if(Registry_[Key].is_boolean()) { | 			if (Registry_[Key].is_boolean()) { | ||||||
| 				Value = Registry_[Key].get<bool>(); | 				Value = Registry_[Key].get<bool>(); | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline bool Get(const char *Key, uint64_t & Value ) { | 		inline bool Get(const char *Key, uint64_t &Value) { | ||||||
| 			if(Registry_[Key].is_number_unsigned()) { | 			if (Registry_[Key].is_number_unsigned()) { | ||||||
| 				Value = Registry_[Key].get<uint64_t>(); | 				Value = Registry_[Key].get<uint64_t>(); | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline bool Get(const char *Key, std::string & Value ) { | 		inline bool Get(const char *Key, std::string &Value) { | ||||||
| 			if(Registry_[Key].is_string()) { | 			if (Registry_[Key].is_string()) { | ||||||
| 				Value = Registry_[Key].get<std::string>(); | 				Value = Registry_[Key].get<std::string>(); | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| @@ -99,4 +96,4 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	inline auto AppServiceRegistry() { return AppServiceRegistry::instance(); } | 	inline auto AppServiceRegistry() { return AppServiceRegistry::instance(); } | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -4,41 +4,40 @@ | |||||||
|  |  | ||||||
| #include "Poco/Net/HTTPServerResponse.h" | #include "Poco/Net/HTTPServerResponse.h" | ||||||
|  |  | ||||||
|  | #include "fmt/format.h" | ||||||
| #include "framework/AuthClient.h" | #include "framework/AuthClient.h" | ||||||
| #include "framework/MicroServiceNames.h" | #include "framework/MicroServiceNames.h" | ||||||
| #include "framework/OpenAPIRequests.h" | #include "framework/OpenAPIRequests.h" | ||||||
| #include "framework/utils.h" | #include "framework/utils.h" | ||||||
| #include "fmt/format.h" |  | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	bool AuthClient::RetrieveTokenInformation(const std::string & SessionToken, | 	bool AuthClient::RetrieveTokenInformation(const std::string &SessionToken, | ||||||
| 										 SecurityObjects::UserInfoAndPolicy & UInfo, | 											  SecurityObjects::UserInfoAndPolicy &UInfo, | ||||||
| 										 std::uint64_t TID, | 											  std::uint64_t TID, bool &Expired, bool &Contacted, | ||||||
| 										 bool & Expired, bool & Contacted, bool Sub) { | 											  bool Sub) { | ||||||
| 		try { | 		try { | ||||||
| 			Types::StringPairVec QueryData; | 			Types::StringPairVec QueryData; | ||||||
| 			QueryData.push_back(std::make_pair("token",SessionToken)); | 			QueryData.push_back(std::make_pair("token", SessionToken)); | ||||||
|             std::string     AlternateURIForLogging = fmt::format("{}?token={}",  Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", Utils::SanitizeToken(SessionToken)); | 			std::string AlternateURIForLogging = fmt::format( | ||||||
| 			OpenAPIRequestGet	Req(    uSERVICE_SECURITY, | 				"{}?token={}", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", | ||||||
|  | 				Utils::SanitizeToken(SessionToken)); | ||||||
|  | 			OpenAPIRequestGet Req(uSERVICE_SECURITY, | ||||||
| 								  Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", | 								  Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", | ||||||
| 								  QueryData, | 								  QueryData, 10000, AlternateURIForLogging); | ||||||
| 								  10000, |  | ||||||
| 								  AlternateURIForLogging |  | ||||||
|                                   ); |  | ||||||
| 			Poco::JSON::Object::Ptr Response; | 			Poco::JSON::Object::Ptr Response; | ||||||
|  |  | ||||||
| 			auto StatusCode = Req.Do(Response); | 			auto StatusCode = Req.Do(Response); | ||||||
| 			if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) { | 			if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) { | ||||||
| 				Contacted = false; | 				Contacted = false; | ||||||
| 				return false; | 				return false; | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			Contacted = true; | 			Contacted = true; | ||||||
| 			if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_OK) { | 			if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) { | ||||||
| 				if(Response->has("tokenInfo") && Response->has("userInfo")) { | 				if (Response->has("tokenInfo") && Response->has("userInfo")) { | ||||||
| 					UInfo.from_json(Response); | 					UInfo.from_json(Response); | ||||||
| 					if(IsTokenExpired(UInfo.webtoken)) { | 					if (IsTokenExpired(UInfo.webtoken)) { | ||||||
| 						Expired = true; | 						Expired = true; | ||||||
| 						return false; | 						return false; | ||||||
| 					} | 					} | ||||||
| @@ -50,18 +49,19 @@ namespace OpenWifi { | |||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
| 			poco_error(Logger(),fmt::format("Failed to retrieve token={} for TID={}", Utils::SanitizeToken(SessionToken), TID)); | 			poco_error(Logger(), fmt::format("Failed to retrieve token={} for TID={}", | ||||||
|  | 											 Utils::SanitizeToken(SessionToken), TID)); | ||||||
| 		} | 		} | ||||||
| 		Expired = false; | 		Expired = false; | ||||||
| 		return false; | 		return false; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	bool AuthClient::IsAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo, | 	bool AuthClient::IsAuthorized(const std::string &SessionToken, | ||||||
| 							 std::uint64_t TID, | 								  SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID, | ||||||
| 							 bool & Expired, bool & Contacted, bool Sub) { | 								  bool &Expired, bool &Contacted, bool Sub) { | ||||||
| 		auto User = Cache_.get(SessionToken); | 		auto User = Cache_.get(SessionToken); | ||||||
| 		if(!User.isNull()) { | 		if (!User.isNull()) { | ||||||
| 			if(IsTokenExpired(User->webtoken)) { | 			if (IsTokenExpired(User->webtoken)) { | ||||||
| 				Expired = true; | 				Expired = true; | ||||||
| 				Cache_.remove(SessionToken); | 				Cache_.remove(SessionToken); | ||||||
| 				return false; | 				return false; | ||||||
| @@ -73,50 +73,53 @@ namespace OpenWifi { | |||||||
| 		return RetrieveTokenInformation(SessionToken, UInfo, TID, Expired, Contacted, Sub); | 		return RetrieveTokenInformation(SessionToken, UInfo, TID, Expired, Contacted, Sub); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     bool AuthClient::RetrieveApiKeyInformation(const std::string & SessionToken, | 	bool AuthClient::RetrieveApiKeyInformation(const std::string &SessionToken, | ||||||
|                                               SecurityObjects::UserInfoAndPolicy & UInfo, | 											   SecurityObjects::UserInfoAndPolicy &UInfo, | ||||||
|                                               std::uint64_t TID, | 											   std::uint64_t TID, bool &Expired, bool &Contacted, | ||||||
|                                               bool & Expired, bool & Contacted, [[maybe_unused]] bool & Suspended) { | 											   [[maybe_unused]] bool &Suspended) { | ||||||
| 		try { | 		try { | ||||||
| 			Types::StringPairVec QueryData; | 			Types::StringPairVec QueryData; | ||||||
|             QueryData.push_back(std::make_pair("apikey",SessionToken)); | 			QueryData.push_back(std::make_pair("apikey", SessionToken)); | ||||||
|             std::string     AlternateURIForLogging = fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken)); | 			std::string AlternateURIForLogging = | ||||||
|             OpenAPIRequestGet	Req(    uSERVICE_SECURITY, | 				fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken)); | ||||||
|                                          "/api/v1/validateApiKey" , | 			OpenAPIRequestGet Req(uSERVICE_SECURITY, "/api/v1/validateApiKey", QueryData, 10000, | ||||||
|                                          QueryData, |  | ||||||
|                                          10000, |  | ||||||
| 								  AlternateURIForLogging); | 								  AlternateURIForLogging); | ||||||
| 			Poco::JSON::Object::Ptr Response; | 			Poco::JSON::Object::Ptr Response; | ||||||
|  |  | ||||||
| 			auto StatusCode = Req.Do(Response); | 			auto StatusCode = Req.Do(Response); | ||||||
|             if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) { | 			if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) { | ||||||
| 				Contacted = false; | 				Contacted = false; | ||||||
| 				return false; | 				return false; | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			Contacted = true; | 			Contacted = true; | ||||||
|             if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_OK) { | 			if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) { | ||||||
|                 if(Response->has("tokenInfo") && Response->has("userInfo") && Response->has("expiresOn")) { | 				if (Response->has("tokenInfo") && Response->has("userInfo") && | ||||||
|  | 					Response->has("expiresOn")) { | ||||||
| 					UInfo.from_json(Response); | 					UInfo.from_json(Response); | ||||||
| 					Expired = false; | 					Expired = false; | ||||||
|                     ApiKeyCache_.update(SessionToken, ApiKeyCacheEntry{ .UserInfo = UInfo, .ExpiresOn = Response->get("expiresOn")}); | 					ApiKeyCache_.update(SessionToken, | ||||||
|  | 										ApiKeyCacheEntry{.UserInfo = UInfo, | ||||||
|  | 														 .ExpiresOn = Response->get("expiresOn")}); | ||||||
| 					return true; | 					return true; | ||||||
| 				} else { | 				} else { | ||||||
| 					return false; | 					return false; | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|             poco_error(Logger(),fmt::format("Failed to retrieve api key={} for TID={}", Utils::SanitizeToken(SessionToken), TID)); | 			poco_error(Logger(), fmt::format("Failed to retrieve api key={} for TID={}", | ||||||
|  | 											 Utils::SanitizeToken(SessionToken), TID)); | ||||||
| 		} | 		} | ||||||
| 		Expired = false; | 		Expired = false; | ||||||
| 		return false; | 		return false; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     bool AuthClient::IsValidApiKey(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy &UInfo, | 	bool AuthClient::IsValidApiKey(const std::string &SessionToken, | ||||||
|                                    std::uint64_t TID, bool &Expired, bool &Contacted, bool & Suspended) { | 								   SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID, | ||||||
|  | 								   bool &Expired, bool &Contacted, bool &Suspended) { | ||||||
| 		auto User = ApiKeyCache_.get(SessionToken); | 		auto User = ApiKeyCache_.get(SessionToken); | ||||||
| 		if (!User.isNull()) { | 		if (!User.isNull()) { | ||||||
|             if(User->ExpiresOn < Utils::Now()) { | 			if (User->ExpiresOn < Utils::Now()) { | ||||||
| 				Expired = false; | 				Expired = false; | ||||||
| 				UInfo = User->UserInfo; | 				UInfo = User->UserInfo; | ||||||
| 				return true; | 				return true; | ||||||
|   | |||||||
| @@ -4,9 +4,9 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include "framework/SubSystemServer.h" |  | ||||||
| #include "RESTObjects/RESTAPI_SecurityObjects.h" |  | ||||||
| #include "Poco/ExpireLRUCache.h" | #include "Poco/ExpireLRUCache.h" | ||||||
|  | #include "RESTObjects/RESTAPI_SecurityObjects.h" | ||||||
|  | #include "framework/SubSystemServer.h" | ||||||
| #include "framework/utils.h" | #include "framework/utils.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| @@ -14,10 +14,8 @@ namespace OpenWifi { | |||||||
| 	class AuthClient : public SubSystemServer { | 	class AuthClient : public SubSystemServer { | ||||||
|  |  | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit AuthClient() noexcept: | 		explicit AuthClient() noexcept | ||||||
| 			 SubSystemServer("Authentication", "AUTH-CLNT", "authentication") | 			: SubSystemServer("Authentication", "AUTH-CLNT", "authentication") {} | ||||||
| 		{ |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		static auto instance() { | 		static auto instance() { | ||||||
| 			static auto instance_ = new AuthClient; | 			static auto instance_ = new AuthClient; | ||||||
| @@ -29,15 +27,13 @@ namespace OpenWifi { | |||||||
| 			std::uint64_t ExpiresOn; | 			std::uint64_t ExpiresOn; | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
|         inline int Start() override { | 		inline int Start() override { return 0; } | ||||||
| 			return 0; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		inline void Stop() override { | 		inline void Stop() override { | ||||||
| 			poco_information(Logger(),"Stopping..."); | 			poco_information(Logger(), "Stopping..."); | ||||||
| 			std::lock_guard G(Mutex_); | 			std::lock_guard G(Mutex_); | ||||||
| 			Cache_.clear(); | 			Cache_.clear(); | ||||||
| 			poco_information(Logger(),"Stopped..."); | 			poco_information(Logger(), "Stopped..."); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void RemovedCachedToken(const std::string &Token) { | 		inline void RemovedCachedToken(const std::string &Token) { | ||||||
| @@ -46,34 +42,31 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline static bool IsTokenExpired(const SecurityObjects::WebToken &T) { | 		inline static bool IsTokenExpired(const SecurityObjects::WebToken &T) { | ||||||
| 			return ((T.expires_in_+T.created_) < Utils::Now()); | 			return ((T.expires_in_ + T.created_) < Utils::Now()); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		bool RetrieveTokenInformation(const std::string & SessionToken, | 		bool RetrieveTokenInformation(const std::string &SessionToken, | ||||||
| 			SecurityObjects::UserInfoAndPolicy & UInfo, | 									  SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID, | ||||||
| 			std::uint64_t TID, | 									  bool &Expired, bool &Contacted, bool Sub = false); | ||||||
| 		bool & Expired, bool & Contacted, bool Sub=false); |  | ||||||
|  |  | ||||||
|         bool RetrieveApiKeyInformation(const std::string & SessionToken, | 		bool RetrieveApiKeyInformation(const std::string &SessionToken, | ||||||
|                                       SecurityObjects::UserInfoAndPolicy & UInfo, | 									   SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID, | ||||||
|                                       std::uint64_t TID, | 									   bool &Expired, bool &Contacted, bool &Suspended); | ||||||
|                                       bool & Expired, bool & Contacted, bool & Suspended); |  | ||||||
|  |  | ||||||
| 		bool IsAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo, | 		bool IsAuthorized(const std::string &SessionToken, | ||||||
| 								 std::uint64_t TID, | 						  SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID, | ||||||
| 								 bool & Expired, bool & Contacted, bool Sub = false); | 						  bool &Expired, bool &Contacted, bool Sub = false); | ||||||
|  |  | ||||||
|         bool IsValidApiKey(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo, | 		bool IsValidApiKey(const std::string &SessionToken, | ||||||
|                           std::uint64_t TID, | 						   SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID, | ||||||
|                           bool & Expired, bool & Contacted, bool & Suspended) ; | 						   bool &Expired, bool &Contacted, bool &Suspended); | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
|  | 		Poco::ExpireLRUCache<std::string, OpenWifi::SecurityObjects::UserInfoAndPolicy> Cache_{ | ||||||
| 		Poco::ExpireLRUCache<std::string,OpenWifi::SecurityObjects::UserInfoAndPolicy>      Cache_{512,1200000 }; | 			512, 1200000}; | ||||||
|         Poco::ExpireLRUCache<std::string,ApiKeyCacheEntry>                                  ApiKeyCache_{512,1200000 }; | 		Poco::ExpireLRUCache<std::string, ApiKeyCacheEntry> ApiKeyCache_{512, 1200000}; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	inline auto AuthClient() { return AuthClient::instance(); } | 	inline auto AuthClient() { return AuthClient::instance(); } | ||||||
|  |  | ||||||
| } // namespace OpenWifi | } // namespace OpenWifi | ||||||
|  |  | ||||||
|   | |||||||
| @@ -21,13 +21,13 @@ namespace OpenWifi::CIDR { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	static bool cidr6_match(const in6_addr &address, const in6_addr &network, uint8_t bits) { | 	static bool cidr6_match(const in6_addr &address, const in6_addr &network, uint8_t bits) { | ||||||
| 	#ifdef __linux__ | #ifdef __linux__ | ||||||
| 		const uint32_t *a = address.s6_addr32; | 		const uint32_t *a = address.s6_addr32; | ||||||
| 		const uint32_t *n = network.s6_addr32; | 		const uint32_t *n = network.s6_addr32; | ||||||
| 	#else | #else | ||||||
| 		const uint32_t *a = address.__u6_addr.__u6_addr32; | 		const uint32_t *a = address.__u6_addr.__u6_addr32; | ||||||
| 		const uint32_t *n = network.__u6_addr.__u6_addr32; | 		const uint32_t *n = network.__u6_addr.__u6_addr32; | ||||||
| 	#endif | #endif | ||||||
| 		int bits_whole, bits_incomplete; | 		int bits_whole, bits_incomplete; | ||||||
| 		bits_whole = bits >> 5;		   // number of whole u32 | 		bits_whole = bits >> 5;		   // number of whole u32 | ||||||
| 		bits_incomplete = bits & 0x1F; // number of bits in incomplete u32 | 		bits_incomplete = bits & 0x1F; // number of bits in incomplete u32 | ||||||
| @@ -152,4 +152,4 @@ namespace OpenWifi::CIDR { | |||||||
| 	[[nodiscard]] inline bool ValidateIpRanges(const Types::StringVec &Ranges) { | 	[[nodiscard]] inline bool ValidateIpRanges(const Types::StringVec &Ranges) { | ||||||
| 		return std::all_of(cbegin(Ranges), cend(Ranges), ValidateRange); | 		return std::all_of(cbegin(Ranges), cend(Ranges), ValidateRange); | ||||||
| 	} | 	} | ||||||
| } | } // namespace OpenWifi::CIDR | ||||||
| @@ -2,8 +2,8 @@ | |||||||
| // Created by stephane bourque on 2021-09-14. | // Created by stephane bourque on 2021-09-14. | ||||||
| // | // | ||||||
|  |  | ||||||
| #include <iostream> |  | ||||||
| #include <fstream> | #include <fstream> | ||||||
|  | #include <iostream> | ||||||
| #include <regex> | #include <regex> | ||||||
|  |  | ||||||
| #include "ConfigurationValidator.h" | #include "ConfigurationValidator.h" | ||||||
| @@ -17,14 +17,15 @@ | |||||||
| #include "fmt/format.h" | #include "fmt/format.h" | ||||||
|  |  | ||||||
| #include <valijson/adapters/poco_json_adapter.hpp> | #include <valijson/adapters/poco_json_adapter.hpp> | ||||||
| #include <valijson/utils/poco_json_utils.hpp> | #include <valijson/constraints/constraint.hpp> | ||||||
| #include <valijson/schema.hpp> | #include <valijson/schema.hpp> | ||||||
| #include <valijson/schema_parser.hpp> | #include <valijson/schema_parser.hpp> | ||||||
|  | #include <valijson/utils/poco_json_utils.hpp> | ||||||
| #include <valijson/validator.hpp> | #include <valijson/validator.hpp> | ||||||
| #include <valijson/constraints/constraint.hpp> |  | ||||||
|  |  | ||||||
| static const std::string GitUCentralJSONSchemaFile{ | static const std::string GitUCentralJSONSchemaFile{ | ||||||
| 	"https://raw.githubusercontent.com/Telecominfraproject/wlan-ucentral-schema/main/ucentral.schema.json"}; | 	"https://raw.githubusercontent.com/Telecominfraproject/wlan-ucentral-schema/main/" | ||||||
|  | 	"ucentral.schema.json"}; | ||||||
|  |  | ||||||
| static std::string DefaultUCentralSchema = R"foo( | static std::string DefaultUCentralSchema = R"foo( | ||||||
|  |  | ||||||
| @@ -36,6 +37,10 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|         "uuid": { |         "uuid": { | ||||||
|             "type": "integer" |             "type": "integer" | ||||||
|         }, |         }, | ||||||
|  |         "public_ip_lookup": { | ||||||
|  |             "type": "string", | ||||||
|  |             "format": "uc-fqdn" | ||||||
|  |         }, | ||||||
|         "unit": { |         "unit": { | ||||||
|             "$ref": "#/$defs/unit" |             "$ref": "#/$defs/unit" | ||||||
|         }, |         }, | ||||||
| @@ -633,26 +638,6 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                     "type": "string", |                     "type": "string", | ||||||
|                     "format": "uc-timeout", |                     "format": "uc-timeout", | ||||||
|                     "default": "6h" |                     "default": "6h" | ||||||
|                 }, |  | ||||||
|                 "relay-server": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "format": "ipv4", |  | ||||||
|                     "example": "192.168.2.1" |  | ||||||
|                 }, |  | ||||||
|                 "circuit-id-format": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "example": [ |  | ||||||
|                         "\\{Interface\\}:\\{VLAN-Id\\}:\\{SSID\\}:\\{Model\\}:\\{Name\\}:\\{AP-MAC\\}:\\{Location\\}", |  | ||||||
|                         "\\{AP-MAC\\};\\{SSID\\};\\{Crypto\\}", |  | ||||||
|                         "\\{Name\\} \\{ESSID\\}" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "remote-id-format": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "example": [ |  | ||||||
|                         "\\{Client-MAC-hex\\} \\{SSID\\}", |  | ||||||
|                         "\\{AP-MAC-hex\\} \\{SSID\\}" |  | ||||||
|                     ] |  | ||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
|         }, |         }, | ||||||
| @@ -1231,6 +1216,32 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                         "secret" |                         "secret" | ||||||
|                     ] |                     ] | ||||||
|                 }, |                 }, | ||||||
|  |                 "secondary": { | ||||||
|  |                     "type": "object", | ||||||
|  |                     "properties": { | ||||||
|  |                         "host": { | ||||||
|  |                             "type": "string", | ||||||
|  |                             "format": "uc-host", | ||||||
|  |                             "examples": [ | ||||||
|  |                                 "192.168.1.10" | ||||||
|  |                             ] | ||||||
|  |                         }, | ||||||
|  |                         "port": { | ||||||
|  |                             "type": "integer", | ||||||
|  |                             "maximum": 65535, | ||||||
|  |                             "minimum": 1024, | ||||||
|  |                             "examples": [ | ||||||
|  |                                 1812 | ||||||
|  |                             ] | ||||||
|  |                         }, | ||||||
|  |                         "secret": { | ||||||
|  |                             "type": "string", | ||||||
|  |                             "examples": [ | ||||||
|  |                                 "secret" | ||||||
|  |                             ] | ||||||
|  |                         } | ||||||
|  |                     } | ||||||
|  |                 }, | ||||||
|                 "request-attribute": { |                 "request-attribute": { | ||||||
|                     "type": "array", |                     "type": "array", | ||||||
|                     "items": { |                     "items": { | ||||||
| @@ -1308,6 +1319,25 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                                         "value": "Example Operator" |                                         "value": "Example Operator" | ||||||
|                                     } |                                     } | ||||||
|                                 ] |                                 ] | ||||||
|  |                             }, | ||||||
|  |                             { | ||||||
|  |                                 "type": "object", | ||||||
|  |                                 "properties": { | ||||||
|  |                                     "id": { | ||||||
|  |                                         "type": "integer", | ||||||
|  |                                         "maximum": 255, | ||||||
|  |                                         "minimum": 1 | ||||||
|  |                                     }, | ||||||
|  |                                     "hex-value": { | ||||||
|  |                                         "type": "string" | ||||||
|  |                                     } | ||||||
|  |                                 }, | ||||||
|  |                                 "examples": [ | ||||||
|  |                                     { | ||||||
|  |                                         "id": 32, | ||||||
|  |                                         "value": "0a0b0c0d" | ||||||
|  |                                     } | ||||||
|  |                                 ] | ||||||
|                             } |                             } | ||||||
|                         ] |                         ] | ||||||
|                     } |                     } | ||||||
| @@ -1657,6 +1687,236 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
|         }, |         }, | ||||||
|  |         "service.captive.click": { | ||||||
|  |             "type": "object", | ||||||
|  |             "properties": { | ||||||
|  |                 "auth-mode": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "const": "click-to-continue" | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |         }, | ||||||
|  |         "service.captive.radius": { | ||||||
|  |             "type": "object", | ||||||
|  |             "properties": { | ||||||
|  |                 "auth-mode": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "const": "radius" | ||||||
|  |                 }, | ||||||
|  |                 "auth-server": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "format": "uc-host", | ||||||
|  |                     "examples": [ | ||||||
|  |                         "192.168.1.10" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "auth-port": { | ||||||
|  |                     "type": "integer", | ||||||
|  |                     "maximum": 65535, | ||||||
|  |                     "minimum": 1024, | ||||||
|  |                     "default": 1812 | ||||||
|  |                 }, | ||||||
|  |                 "auth-secret": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "examples": [ | ||||||
|  |                         "secret" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "acct-server": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "format": "uc-host", | ||||||
|  |                     "examples": [ | ||||||
|  |                         "192.168.1.10" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "acct-port": { | ||||||
|  |                     "type": "integer", | ||||||
|  |                     "maximum": 65535, | ||||||
|  |                     "minimum": 1024, | ||||||
|  |                     "default": 1812 | ||||||
|  |                 }, | ||||||
|  |                 "acct-secret": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "examples": [ | ||||||
|  |                         "secret" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "acct-interval": { | ||||||
|  |                     "type": "integer", | ||||||
|  |                     "default": 600 | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |         }, | ||||||
|  |         "service.captive.credentials": { | ||||||
|  |             "type": "object", | ||||||
|  |             "properties": { | ||||||
|  |                 "auth-mode": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "const": "credentials" | ||||||
|  |                 }, | ||||||
|  |                 "credentials": { | ||||||
|  |                     "type": "array", | ||||||
|  |                     "items": { | ||||||
|  |                         "type": "object", | ||||||
|  |                         "properties": { | ||||||
|  |                             "username": { | ||||||
|  |                                 "type": "string" | ||||||
|  |                             }, | ||||||
|  |                             "password": { | ||||||
|  |                                 "type": "string" | ||||||
|  |                             } | ||||||
|  |                         } | ||||||
|  |                     } | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |         }, | ||||||
|  |         "service.captive.uam": { | ||||||
|  |             "type": "object", | ||||||
|  |             "properties": { | ||||||
|  |                 "auth-mode": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "const": "uam" | ||||||
|  |                 }, | ||||||
|  |                 "uam-port": { | ||||||
|  |                     "type": "integer", | ||||||
|  |                     "maximum": 65535, | ||||||
|  |                     "minimum": 1024, | ||||||
|  |                     "default": 3990 | ||||||
|  |                 }, | ||||||
|  |                 "uam-secret": { | ||||||
|  |                     "type": "string" | ||||||
|  |                 }, | ||||||
|  |                 "uam-server": { | ||||||
|  |                     "type": "string" | ||||||
|  |                 }, | ||||||
|  |                 "nasid": { | ||||||
|  |                     "type": "string" | ||||||
|  |                 }, | ||||||
|  |                 "nasmac": { | ||||||
|  |                     "type": "string" | ||||||
|  |                 }, | ||||||
|  |                 "auth-server": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "format": "uc-host", | ||||||
|  |                     "examples": [ | ||||||
|  |                         "192.168.1.10" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "auth-port": { | ||||||
|  |                     "type": "integer", | ||||||
|  |                     "maximum": 65535, | ||||||
|  |                     "minimum": 1024, | ||||||
|  |                     "default": 1812 | ||||||
|  |                 }, | ||||||
|  |                 "auth-secret": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "examples": [ | ||||||
|  |                         "secret" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "acct-server": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "format": "uc-host", | ||||||
|  |                     "examples": [ | ||||||
|  |                         "192.168.1.10" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "acct-port": { | ||||||
|  |                     "type": "integer", | ||||||
|  |                     "maximum": 65535, | ||||||
|  |                     "minimum": 1024, | ||||||
|  |                     "default": 1812 | ||||||
|  |                 }, | ||||||
|  |                 "acct-secret": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "examples": [ | ||||||
|  |                         "secret" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "acct-interval": { | ||||||
|  |                     "type": "integer", | ||||||
|  |                     "default": 600 | ||||||
|  |                 }, | ||||||
|  |                 "ssid": { | ||||||
|  |                     "type": "string" | ||||||
|  |                 }, | ||||||
|  |                 "mac-format": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "enum": [ | ||||||
|  |                         "aabbccddeeff", | ||||||
|  |                         "aa-bb-cc-dd-ee-ff", | ||||||
|  |                         "aa:bb:cc:dd:ee:ff", | ||||||
|  |                         "AABBCCDDEEFF", | ||||||
|  |                         "AA:BB:CC:DD:EE:FF", | ||||||
|  |                         "AA-BB-CC-DD-EE-FF" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "final-redirect-url": { | ||||||
|  |                     "type": "string", | ||||||
|  |                     "enum": [ | ||||||
|  |                         "default", | ||||||
|  |                         "uam" | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "mac-auth": { | ||||||
|  |                     "type": "boolean", | ||||||
|  |                     "default": "default" | ||||||
|  |                 }, | ||||||
|  |                 "radius-gw-proxy": { | ||||||
|  |                     "type": "boolean", | ||||||
|  |                     "default": false | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |         }, | ||||||
|  |         "service.captive": { | ||||||
|  |             "allOf": [ | ||||||
|  |                 { | ||||||
|  |                     "oneOf": [ | ||||||
|  |                         { | ||||||
|  |                             "$ref": "#/$defs/service.captive.click" | ||||||
|  |                         }, | ||||||
|  |                         { | ||||||
|  |                             "$ref": "#/$defs/service.captive.radius" | ||||||
|  |                         }, | ||||||
|  |                         { | ||||||
|  |                             "$ref": "#/$defs/service.captive.credentials" | ||||||
|  |                         }, | ||||||
|  |                         { | ||||||
|  |                             "$ref": "#/$defs/service.captive.uam" | ||||||
|  |                         } | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|  |                 { | ||||||
|  |                     "type": "object", | ||||||
|  |                     "properties": { | ||||||
|  |                         "walled-garden-fqdn": { | ||||||
|  |                             "type": "array", | ||||||
|  |                             "items": { | ||||||
|  |                                 "type": "string" | ||||||
|  |                             } | ||||||
|  |                         }, | ||||||
|  |                         "walled-garden-ipaddr": { | ||||||
|  |                             "type": "array", | ||||||
|  |                             "items": { | ||||||
|  |                                 "type": "string", | ||||||
|  |                                 "format": "uc-ip" | ||||||
|  |                             } | ||||||
|  |                         }, | ||||||
|  |                         "web-root": { | ||||||
|  |                             "type": "string", | ||||||
|  |                             "format": "uc-base64" | ||||||
|  |                         }, | ||||||
|  |                         "idle-timeout": { | ||||||
|  |                             "type": "integer", | ||||||
|  |                             "default": 600 | ||||||
|  |                         }, | ||||||
|  |                         "session-timeout": { | ||||||
|  |                             "type": "integer" | ||||||
|  |                         } | ||||||
|  |                     } | ||||||
|  |                 } | ||||||
|  |             ] | ||||||
|  |         }, | ||||||
|         "interface.ssid": { |         "interface.ssid": { | ||||||
|             "type": "object", |             "type": "object", | ||||||
|             "properties": { |             "properties": { | ||||||
| @@ -1709,6 +1969,10 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 "isolate-clients": { |                 "isolate-clients": { | ||||||
|                     "type": "boolean" |                     "type": "boolean" | ||||||
|                 }, |                 }, | ||||||
|  |                 "strict-forwarding": { | ||||||
|  |                     "type": "boolean", | ||||||
|  |                     "default": false | ||||||
|  |                 }, | ||||||
|                 "power-save": { |                 "power-save": { | ||||||
|                     "type": "boolean" |                     "type": "boolean" | ||||||
|                 }, |                 }, | ||||||
| @@ -1777,8 +2041,15 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                     "$ref": "#/$defs/interface.ssid.rate-limit" |                     "$ref": "#/$defs/interface.ssid.rate-limit" | ||||||
|                 }, |                 }, | ||||||
|                 "roaming": { |                 "roaming": { | ||||||
|  |                     "anyOf": [ | ||||||
|  |                         { | ||||||
|                             "$ref": "#/$defs/interface.ssid.roaming" |                             "$ref": "#/$defs/interface.ssid.roaming" | ||||||
|                         }, |                         }, | ||||||
|  |                         { | ||||||
|  |                             "type": "boolean" | ||||||
|  |                         } | ||||||
|  |                     ] | ||||||
|  |                 }, | ||||||
|                 "radius": { |                 "radius": { | ||||||
|                     "$ref": "#/$defs/interface.ssid.radius" |                     "$ref": "#/$defs/interface.ssid.radius" | ||||||
|                 }, |                 }, | ||||||
| @@ -1794,6 +2065,9 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 "access-control-list": { |                 "access-control-list": { | ||||||
|                     "$ref": "#/$defs/interface.ssid.acl" |                     "$ref": "#/$defs/interface.ssid.acl" | ||||||
|                 }, |                 }, | ||||||
|  |                 "captive": { | ||||||
|  |                     "$ref": "#/$defs/service.captive" | ||||||
|  |                 }, | ||||||
|                 "hostapd-bss-raw": { |                 "hostapd-bss-raw": { | ||||||
|                     "type": "array", |                     "type": "array", | ||||||
|                     "items": { |                     "items": { | ||||||
| @@ -2083,6 +2357,10 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                     "examples": [ |                     "examples": [ | ||||||
|                         "01234567890123456789012345678901" |                         "01234567890123456789012345678901" | ||||||
|                     ] |                     ] | ||||||
|  |                 }, | ||||||
|  |                 "mutual-tls": { | ||||||
|  |                     "type": "boolean", | ||||||
|  |                     "default": true | ||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
|         }, |         }, | ||||||
| @@ -2692,236 +2970,6 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
|         }, |         }, | ||||||
|         "service.captive.click": { |  | ||||||
|             "type": "object", |  | ||||||
|             "properties": { |  | ||||||
|                 "auth-mode": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "const": "click-to-continue" |  | ||||||
|                 } |  | ||||||
|             } |  | ||||||
|         }, |  | ||||||
|         "service.captive.radius": { |  | ||||||
|             "type": "object", |  | ||||||
|             "properties": { |  | ||||||
|                 "auth-mode": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "const": "radius" |  | ||||||
|                 }, |  | ||||||
|                 "auth-server": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "format": "uc-host", |  | ||||||
|                     "examples": [ |  | ||||||
|                         "192.168.1.10" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "auth-port": { |  | ||||||
|                     "type": "integer", |  | ||||||
|                     "maximum": 65535, |  | ||||||
|                     "minimum": 1024, |  | ||||||
|                     "default": 1812 |  | ||||||
|                 }, |  | ||||||
|                 "auth-secret": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "examples": [ |  | ||||||
|                         "secret" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "acct-server": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "format": "uc-host", |  | ||||||
|                     "examples": [ |  | ||||||
|                         "192.168.1.10" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "acct-port": { |  | ||||||
|                     "type": "integer", |  | ||||||
|                     "maximum": 65535, |  | ||||||
|                     "minimum": 1024, |  | ||||||
|                     "default": 1812 |  | ||||||
|                 }, |  | ||||||
|                 "acct-secret": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "examples": [ |  | ||||||
|                         "secret" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "acct-interval": { |  | ||||||
|                     "type": "integer", |  | ||||||
|                     "default": 600 |  | ||||||
|                 } |  | ||||||
|             } |  | ||||||
|         }, |  | ||||||
|         "service.captive.credentials": { |  | ||||||
|             "type": "object", |  | ||||||
|             "properties": { |  | ||||||
|                 "auth-mode": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "const": "credentials" |  | ||||||
|                 }, |  | ||||||
|                 "credentials": { |  | ||||||
|                     "type": "array", |  | ||||||
|                     "items": { |  | ||||||
|                         "type": "object", |  | ||||||
|                         "properties": { |  | ||||||
|                             "username": { |  | ||||||
|                                 "type": "string" |  | ||||||
|                             }, |  | ||||||
|                             "password": { |  | ||||||
|                                 "type": "string" |  | ||||||
|                             } |  | ||||||
|                         } |  | ||||||
|                     } |  | ||||||
|                 } |  | ||||||
|             } |  | ||||||
|         }, |  | ||||||
|         "service.captive.uam": { |  | ||||||
|             "type": "object", |  | ||||||
|             "properties": { |  | ||||||
|                 "auth-mode": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "const": "uam" |  | ||||||
|                 }, |  | ||||||
|                 "uam-port": { |  | ||||||
|                     "type": "integer", |  | ||||||
|                     "maximum": 65535, |  | ||||||
|                     "minimum": 1024, |  | ||||||
|                     "default": 3990 |  | ||||||
|                 }, |  | ||||||
|                 "uam-secret": { |  | ||||||
|                     "type": "string" |  | ||||||
|                 }, |  | ||||||
|                 "uam-server": { |  | ||||||
|                     "type": "string" |  | ||||||
|                 }, |  | ||||||
|                 "nasid": { |  | ||||||
|                     "type": "string" |  | ||||||
|                 }, |  | ||||||
|                 "nasmac": { |  | ||||||
|                     "type": "string" |  | ||||||
|                 }, |  | ||||||
|                 "auth-server": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "format": "uc-host", |  | ||||||
|                     "examples": [ |  | ||||||
|                         "192.168.1.10" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "auth-port": { |  | ||||||
|                     "type": "integer", |  | ||||||
|                     "maximum": 65535, |  | ||||||
|                     "minimum": 1024, |  | ||||||
|                     "default": 1812 |  | ||||||
|                 }, |  | ||||||
|                 "auth-secret": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "examples": [ |  | ||||||
|                         "secret" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "acct-server": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "format": "uc-host", |  | ||||||
|                     "examples": [ |  | ||||||
|                         "192.168.1.10" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "acct-port": { |  | ||||||
|                     "type": "integer", |  | ||||||
|                     "maximum": 65535, |  | ||||||
|                     "minimum": 1024, |  | ||||||
|                     "default": 1812 |  | ||||||
|                 }, |  | ||||||
|                 "acct-secret": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "examples": [ |  | ||||||
|                         "secret" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "acct-interval": { |  | ||||||
|                     "type": "integer", |  | ||||||
|                     "default": 600 |  | ||||||
|                 }, |  | ||||||
|                 "ssid": { |  | ||||||
|                     "type": "string" |  | ||||||
|                 }, |  | ||||||
|                 "mac-format": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "enum": [ |  | ||||||
|                         "aabbccddeeff", |  | ||||||
|                         "aa-bb-cc-dd-ee-ff", |  | ||||||
|                         "aa:bb:cc:dd:ee:ff", |  | ||||||
|                         "AABBCCDDEEFF", |  | ||||||
|                         "AA:BB:CC:DD:EE:FF", |  | ||||||
|                         "AA-BB-CC-DD-EE-FF" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "final-redirect-url": { |  | ||||||
|                     "type": "string", |  | ||||||
|                     "enum": [ |  | ||||||
|                         "default", |  | ||||||
|                         "uam" |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 "mac-auth": { |  | ||||||
|                     "type": "boolean", |  | ||||||
|                     "default": "default" |  | ||||||
|                 }, |  | ||||||
|                 "radius-gw-proxy": { |  | ||||||
|                     "type": "boolean", |  | ||||||
|                     "default": false |  | ||||||
|                 } |  | ||||||
|             } |  | ||||||
|         }, |  | ||||||
|         "service.captive": { |  | ||||||
|             "allOf": [ |  | ||||||
|                 { |  | ||||||
|                     "oneOf": [ |  | ||||||
|                         { |  | ||||||
|                             "$ref": "#/$defs/service.captive.click" |  | ||||||
|                         }, |  | ||||||
|                         { |  | ||||||
|                             "$ref": "#/$defs/service.captive.radius" |  | ||||||
|                         }, |  | ||||||
|                         { |  | ||||||
|                             "$ref": "#/$defs/service.captive.credentials" |  | ||||||
|                         }, |  | ||||||
|                         { |  | ||||||
|                             "$ref": "#/$defs/service.captive.uam" |  | ||||||
|                         } |  | ||||||
|                     ] |  | ||||||
|                 }, |  | ||||||
|                 { |  | ||||||
|                     "type": "object", |  | ||||||
|                     "properties": { |  | ||||||
|                         "walled-garden-fqdn": { |  | ||||||
|                             "type": "array", |  | ||||||
|                             "items": { |  | ||||||
|                                 "type": "string" |  | ||||||
|                             } |  | ||||||
|                         }, |  | ||||||
|                         "walled-garden-ipaddr": { |  | ||||||
|                             "type": "array", |  | ||||||
|                             "items": { |  | ||||||
|                                 "type": "string", |  | ||||||
|                                 "format": "uc-ip" |  | ||||||
|                             } |  | ||||||
|                         }, |  | ||||||
|                         "web-root": { |  | ||||||
|                             "type": "string", |  | ||||||
|                             "format": "uc-base64" |  | ||||||
|                         }, |  | ||||||
|                         "idle-timeout": { |  | ||||||
|                             "type": "integer", |  | ||||||
|                             "default": 600 |  | ||||||
|                         }, |  | ||||||
|                         "session-timeout": { |  | ||||||
|                             "type": "integer" |  | ||||||
|                         } |  | ||||||
|                     } |  | ||||||
|                 } |  | ||||||
|             ] |  | ||||||
|         }, |  | ||||||
|         "service.gps": { |         "service.gps": { | ||||||
|             "type": "object", |             "type": "object", | ||||||
|             "properties": { |             "properties": { | ||||||
| @@ -2940,6 +2988,32 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
|         }, |         }, | ||||||
|  |         "service.dhcp-relay": { | ||||||
|  |             "type": "object", | ||||||
|  |             "properties": { | ||||||
|  |                 "select-ports": { | ||||||
|  |                     "type": "array", | ||||||
|  |                     "items": { | ||||||
|  |                         "type": "string" | ||||||
|  |                     } | ||||||
|  |                 }, | ||||||
|  |                 "vlans": { | ||||||
|  |                     "type": "array", | ||||||
|  |                     "items": { | ||||||
|  |                         "type": "object", | ||||||
|  |                         "properties": { | ||||||
|  |                             "vlan": { | ||||||
|  |                                 "type": "number" | ||||||
|  |                             }, | ||||||
|  |                             "relay-server": { | ||||||
|  |                                 "type": "string", | ||||||
|  |                                 "format": "uc-ip" | ||||||
|  |                             } | ||||||
|  |                         } | ||||||
|  |                     } | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |         }, | ||||||
|         "service": { |         "service": { | ||||||
|             "type": "object", |             "type": "object", | ||||||
|             "properties": { |             "properties": { | ||||||
| @@ -2999,6 +3073,9 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 }, |                 }, | ||||||
|                 "gps": { |                 "gps": { | ||||||
|                     "$ref": "#/$defs/service.gps" |                     "$ref": "#/$defs/service.gps" | ||||||
|  |                 }, | ||||||
|  |                 "dhcp-relay": { | ||||||
|  |                     "$ref": "#/$defs/service.dhcp-relay" | ||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
|         }, |         }, | ||||||
| @@ -3091,6 +3168,20 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
|         }, |         }, | ||||||
|  |         "metrics.wifi-scan": { | ||||||
|  |             "type": "object", | ||||||
|  |             "properties": { | ||||||
|  |                 "interval": { | ||||||
|  |                     "type": "integer" | ||||||
|  |                 }, | ||||||
|  |                 "verbose": { | ||||||
|  |                     "type": "boolean" | ||||||
|  |                 }, | ||||||
|  |                 "information-elements": { | ||||||
|  |                     "type": "boolean" | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |         }, | ||||||
|         "metrics.telemetry": { |         "metrics.telemetry": { | ||||||
|             "type": "object", |             "type": "object", | ||||||
|             "properties": { |             "properties": { | ||||||
| @@ -3100,7 +3191,27 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 "types": { |                 "types": { | ||||||
|                     "type": "array", |                     "type": "array", | ||||||
|                     "items": { |                     "items": { | ||||||
|                         "type": "string" |                         "type": "string", | ||||||
|  |                         "enum": [ | ||||||
|  |                             "ssh", | ||||||
|  |                             "health", | ||||||
|  |                             "health.dns", | ||||||
|  |                             "health.dhcp", | ||||||
|  |                             "health.radius", | ||||||
|  |                             "health.memory", | ||||||
|  |                             "client", | ||||||
|  |                             "client.join", | ||||||
|  |                             "client.leave", | ||||||
|  |                             "client.key-mismatch", | ||||||
|  |                             "wifi", | ||||||
|  |                             "wifi.start", | ||||||
|  |                             "wifi.stop", | ||||||
|  |                             "wired", | ||||||
|  |                             "wired.carrier-up", | ||||||
|  |                             "wired.carrier-down", | ||||||
|  |                             "unit", | ||||||
|  |                             "unit.boot-up" | ||||||
|  |                         ] | ||||||
|                     } |                     } | ||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
| @@ -3111,7 +3222,27 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 "types": { |                 "types": { | ||||||
|                     "type": "array", |                     "type": "array", | ||||||
|                     "items": { |                     "items": { | ||||||
|                         "type": "string" |                         "type": "string", | ||||||
|  |                         "enum": [ | ||||||
|  |                             "ssh", | ||||||
|  |                             "health", | ||||||
|  |                             "health.dns", | ||||||
|  |                             "health.dhcp", | ||||||
|  |                             "health.radius", | ||||||
|  |                             "health.memory", | ||||||
|  |                             "client", | ||||||
|  |                             "client.join", | ||||||
|  |                             "client.leave", | ||||||
|  |                             "client.key-mismatch", | ||||||
|  |                             "wifi", | ||||||
|  |                             "wifi.start", | ||||||
|  |                             "wifi.stop", | ||||||
|  |                             "wired", | ||||||
|  |                             "wired.carrier-up", | ||||||
|  |                             "wired.carrier-down", | ||||||
|  |                             "unit", | ||||||
|  |                             "unit.boot-up" | ||||||
|  |                         ] | ||||||
|                     } |                     } | ||||||
|                 } |                 } | ||||||
|             } |             } | ||||||
| @@ -3131,6 +3262,9 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|                 "dhcp-snooping": { |                 "dhcp-snooping": { | ||||||
|                     "$ref": "#/$defs/metrics.dhcp-snooping" |                     "$ref": "#/$defs/metrics.dhcp-snooping" | ||||||
|                 }, |                 }, | ||||||
|  |                 "wifi-scan": { | ||||||
|  |                     "$ref": "#/$defs/metrics.wifi-scan" | ||||||
|  |                 }, | ||||||
|                 "telemetry": { |                 "telemetry": { | ||||||
|                     "$ref": "#/$defs/metrics.telemetry" |                     "$ref": "#/$defs/metrics.telemetry" | ||||||
|                 }, |                 }, | ||||||
| @@ -3184,7 +3318,6 @@ static std::string DefaultUCentralSchema = R"foo( | |||||||
|  |  | ||||||
| )foo"; | )foo"; | ||||||
|  |  | ||||||
|  |  | ||||||
| static inline bool IsIPv4(const std::string &value) { | static inline bool IsIPv4(const std::string &value) { | ||||||
| 	Poco::Net::IPAddress A; | 	Poco::Net::IPAddress A; | ||||||
| 	return ((Poco::Net::IPAddress::tryParse(value, A) && A.family() == Poco::Net::IPAddress::IPv4)); | 	return ((Poco::Net::IPAddress::tryParse(value, A) && A.family() == Poco::Net::IPAddress::IPv4)); | ||||||
| @@ -3242,57 +3375,68 @@ bool ExternalValijsonFormatChecker(const std::string &format, const std::string | |||||||
| 	if (format == "uc-cidr4") { | 	if (format == "uc-cidr4") { | ||||||
| 		if (IsCIDRv4(value)) | 		if (IsCIDRv4(value)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid CIDR IPv4 block",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid CIDR IPv4 block", value)); | ||||||
| 	} else if (format == "uc-cidr6") { | 	} else if (format == "uc-cidr6") { | ||||||
| 		if (IsCIDRv6(value)) | 		if (IsCIDRv6(value)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid CIDR IPv6 block",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid CIDR IPv6 block", value)); | ||||||
| 	} else if (format == "uc-cidr") { | 	} else if (format == "uc-cidr") { | ||||||
| 		if (IsCIDR(value)) | 		if (IsCIDR(value)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid CIDR block",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid CIDR block", value)); | ||||||
| 	} else if (format == "uc-mac") { | 	} else if (format == "uc-mac") { | ||||||
| 		if (std::regex_match(value, mac_regex)) | 		if (std::regex_match(value, mac_regex)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid MAC address",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid MAC address", value)); | ||||||
| 	} else if (format == "uc-timeout") { | 	} else if (format == "uc-timeout") { | ||||||
| 		if (std::regex_match(value, uc_timeout_regex)) | 		if (std::regex_match(value, uc_timeout_regex)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid timeout value",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid timeout value", value)); | ||||||
| 	} else if (format == "uc-host") { | 	} else if (format == "uc-host") { | ||||||
| 		if (IsIP(value)) | 		if (IsIP(value)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if (std::regex_match(value, host_regex)) | 		if (std::regex_match(value, host_regex)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid hostname",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid hostname", value)); | ||||||
| 	} else if (format == "fqdn" || format == "uc-fqdn") { | 	} else if (format == "fqdn" || format == "uc-fqdn") { | ||||||
| 		if (std::regex_match(value, host_regex)) | 		if (std::regex_match(value, host_regex)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid FQDN",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid FQDN", value)); | ||||||
| 	} else if (format == "uc-base64") { | 	} else if (format == "uc-base64") { | ||||||
| 		std::string s{value}; | 		std::string s{value}; | ||||||
| 		Poco::trimInPlace(s); | 		Poco::trimInPlace(s); | ||||||
| 		if ((s.size() % 4 == 0) && std::regex_match(s, b64_regex)) | 		if ((s.size() % 4 == 0) && std::regex_match(s, b64_regex)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid base 64 value",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid base 64 value", value)); | ||||||
| 	} else if (format == "uri") { | 	} else if (format == "uri") { | ||||||
| 		try { | 		try { | ||||||
| 			Poco::URI uri(value); | 			Poco::URI uri(value); | ||||||
| 			return true; | 			return true; | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
| 		} | 		} | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid URL",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid URL", value)); | ||||||
| 	} else if (format == "uc-portrange") { | 	} else if (format == "uc-portrange") { | ||||||
| 		try { | 		try { | ||||||
| 			if (IsPortRangeIsValid(value)) | 			if (IsPortRangeIsValid(value)) | ||||||
| 				return true; | 				return true; | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
| 		} | 		} | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid post range",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid post range", value)); | ||||||
| 	} else if (format == "ip") { | 	} else if (format == "ip") { | ||||||
| 		if (IsIP(value)) | 		if (IsIP(value)) | ||||||
| 			return true; | 			return true; | ||||||
| 		if(results) results->pushError(context,fmt::format("{} is not a valid IP address",value)); | 		if (results) | ||||||
|  | 			results->pushError(context, fmt::format("{} is not a valid IP address", value)); | ||||||
| 	} | 	} | ||||||
| 	return true; | 	return true; | ||||||
| } | } | ||||||
| @@ -3304,9 +3448,7 @@ namespace OpenWifi { | |||||||
| 		return 0; | 		return 0; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void ConfigurationValidator::Stop() { | 	void ConfigurationValidator::Stop() {} | ||||||
|  |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	bool ConfigurationValidator::SetSchema(const std::string &SchemaStr) { | 	bool ConfigurationValidator::SetSchema(const std::string &SchemaStr) { | ||||||
| 		try { | 		try { | ||||||
| @@ -3318,9 +3460,9 @@ namespace OpenWifi { | |||||||
| 			SchemaParser_->populateSchema(*PocoJsonAdapter_, *RootSchema_); | 			SchemaParser_->populateSchema(*PocoJsonAdapter_, *RootSchema_); | ||||||
| 			Initialized_ = Working_ = true; | 			Initialized_ = Working_ = true; | ||||||
| 			return true; | 			return true; | ||||||
| 		} catch(const Poco::Exception &E) { | 		} catch (const Poco::Exception &E) { | ||||||
| 			Logger().log(E); | 			Logger().log(E); | ||||||
| 		} catch(...) { | 		} catch (...) { | ||||||
| 			Logger().error("Validation schema is invalid, falling back."); | 			Logger().error("Validation schema is invalid, falling back."); | ||||||
| 		} | 		} | ||||||
| 		return false; | 		return false; | ||||||
| @@ -3331,7 +3473,7 @@ namespace OpenWifi { | |||||||
| 			return; | 			return; | ||||||
|  |  | ||||||
| 		std::string GitSchema; | 		std::string GitSchema; | ||||||
| 		if(MicroServiceConfigGetBool("ucentral.datamodel.internal",true)) { | 		if (MicroServiceConfigGetBool("ucentral.datamodel.internal", true)) { | ||||||
| 			SetSchema(DefaultUCentralSchema); | 			SetSchema(DefaultUCentralSchema); | ||||||
| 			poco_information(Logger(), "Using uCentral validation from built-in default."); | 			poco_information(Logger(), "Using uCentral validation from built-in default."); | ||||||
| 			return; | 			return; | ||||||
| @@ -3339,33 +3481,34 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 		try { | 		try { | ||||||
| 			auto GitURI = | 			auto GitURI = | ||||||
| 			   MicroServiceConfigGetString("ucentral.datamodel.uri",GitUCentralJSONSchemaFile); | 				MicroServiceConfigGetString("ucentral.datamodel.uri", GitUCentralJSONSchemaFile); | ||||||
| 				if(Utils::wgets(GitURI, GitSchema) && SetSchema(GitSchema)) { | 			if (Utils::wgets(GitURI, GitSchema) && SetSchema(GitSchema)) { | ||||||
| 					poco_information(Logger(),"Using uCentral data model validation schema from GIT."); | 				poco_information(Logger(), "Using uCentral data model validation schema from GIT."); | ||||||
| 				return; | 				return; | ||||||
| 			} else { | 			} else { | ||||||
| 					std::string FileName{ MicroServiceDataDirectory() + "/ucentral.schema.json" }; | 				std::string FileName{MicroServiceDataDirectory() + "/ucentral.schema.json"}; | ||||||
| 				std::ifstream input(FileName); | 				std::ifstream input(FileName); | ||||||
| 				std::stringstream schema_file; | 				std::stringstream schema_file; | ||||||
| 				schema_file << input.rdbuf(); | 				schema_file << input.rdbuf(); | ||||||
| 				input.close(); | 				input.close(); | ||||||
| 					if(SetSchema(schema_file.str())) { | 				if (SetSchema(schema_file.str())) { | ||||||
| 						poco_information(Logger(), | 					poco_information( | ||||||
| 										 "Using uCentral data model validation schema from local file."); | 						Logger(), "Using uCentral data model validation schema from local file."); | ||||||
| 					return; | 					return; | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 		} catch (const Poco::Exception &E) { | 		} catch (const Poco::Exception &E) { | ||||||
|  |  | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		SetSchema(DefaultUCentralSchema); | 		SetSchema(DefaultUCentralSchema); | ||||||
| 		poco_information(Logger(),"Using uCentral data model validation schema from built-in default."); | 		poco_information(Logger(), | ||||||
|  | 						 "Using uCentral data model validation schema from built-in default."); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     bool ConfigurationValidator::Validate(const std::string &C, std::vector<std::string> &Errors, bool Strict) { | 	bool ConfigurationValidator::Validate(const std::string &C, std::vector<std::string> &Errors, | ||||||
|         if(Working_) { | 										  bool Strict) { | ||||||
|  | 		if (Working_) { | ||||||
| 			try { | 			try { | ||||||
| 				Poco::JSON::Parser P; | 				Poco::JSON::Parser P; | ||||||
| 				auto Doc = P.parse(C).extract<Poco::JSON::Object::Ptr>(); | 				auto Doc = P.parse(C).extract<Poco::JSON::Object::Ptr>(); | ||||||
| @@ -3375,27 +3518,28 @@ namespace OpenWifi { | |||||||
| 				if (Validator.validate(*RootSchema_, Tester, &Results)) { | 				if (Validator.validate(*RootSchema_, Tester, &Results)) { | ||||||
| 					return true; | 					return true; | ||||||
| 				} | 				} | ||||||
| 				for(const auto &error:Results) { | 				for (const auto &error : Results) { | ||||||
| 					Errors.push_back(error.description); | 					Errors.push_back(error.description); | ||||||
| 				} | 				} | ||||||
| 				return false; | 				return false; | ||||||
| 			} catch(const Poco::Exception &E) { | 			} catch (const Poco::Exception &E) { | ||||||
| 				Logger().log(E); | 				Logger().log(E); | ||||||
|             } catch(const std::exception &E) { | 			} catch (const std::exception &E) { | ||||||
| 				Logger().warning(fmt::format("Error wile validating a configuration (1): {}", E.what())); | 				Logger().warning( | ||||||
|             } catch(...) { | 					fmt::format("Error wile validating a configuration (1): {}", E.what())); | ||||||
|  | 			} catch (...) { | ||||||
| 				Logger().warning("Error wile validating a configuration (2)"); | 				Logger().warning("Error wile validating a configuration (2)"); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		if(Strict) | 		if (Strict) | ||||||
| 			return false; | 			return false; | ||||||
| 		return true; | 		return true; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void ConfigurationValidator::reinitialize([[maybe_unused]] Poco::Util::Application &self) { | 	void ConfigurationValidator::reinitialize([[maybe_unused]] Poco::Util::Application &self) { | ||||||
| 		poco_information(Logger(),"Reinitializing."); | 		poco_information(Logger(), "Reinitializing."); | ||||||
| 		Working_ = Initialized_ = false; | 		Working_ = Initialized_ = false; | ||||||
| 		Init(); | 		Init(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -7,17 +7,16 @@ | |||||||
| #include "framework/SubSystemServer.h" | #include "framework/SubSystemServer.h" | ||||||
|  |  | ||||||
| #include <valijson/adapters/poco_json_adapter.hpp> | #include <valijson/adapters/poco_json_adapter.hpp> | ||||||
| #include <valijson/utils/poco_json_utils.hpp> |  | ||||||
| #include <valijson/schema.hpp> |  | ||||||
| #include <valijson/schema_parser.hpp> |  | ||||||
| #include <valijson/validator.hpp> |  | ||||||
| #include <valijson/constraints/constraint.hpp> | #include <valijson/constraints/constraint.hpp> | ||||||
| #include <valijson/constraints/constraint_visitor.hpp> | #include <valijson/constraints/constraint_visitor.hpp> | ||||||
|  | #include <valijson/schema.hpp> | ||||||
|  | #include <valijson/schema_parser.hpp> | ||||||
|  | #include <valijson/utils/poco_json_utils.hpp> | ||||||
|  | #include <valijson/validator.hpp> | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| 	class ConfigurationValidator : public SubSystemServer { | 	class ConfigurationValidator : public SubSystemServer { | ||||||
| 	  public: | 	  public: | ||||||
|  |  | ||||||
| 		static auto instance() { | 		static auto instance() { | ||||||
| 			static auto instance_ = new ConfigurationValidator; | 			static auto instance_ = new ConfigurationValidator; | ||||||
| 			return instance_; | 			return instance_; | ||||||
| @@ -29,8 +28,8 @@ namespace OpenWifi { | |||||||
| 		void reinitialize(Poco::Util::Application &self) override; | 		void reinitialize(Poco::Util::Application &self) override; | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
|         bool            					Initialized_=false; | 		bool Initialized_ = false; | ||||||
|         bool            					Working_=false; | 		bool Working_ = false; | ||||||
| 		void Init(); | 		void Init(); | ||||||
| 		std::unique_ptr<valijson::Schema> RootSchema_; | 		std::unique_ptr<valijson::Schema> RootSchema_; | ||||||
| 		std::unique_ptr<valijson::SchemaParser> SchemaParser_; | 		std::unique_ptr<valijson::SchemaParser> SchemaParser_; | ||||||
| @@ -38,12 +37,13 @@ namespace OpenWifi { | |||||||
| 		Poco::JSON::Object::Ptr SchemaDocPtr_; | 		Poco::JSON::Object::Ptr SchemaDocPtr_; | ||||||
| 		bool SetSchema(const std::string &SchemaStr); | 		bool SetSchema(const std::string &SchemaStr); | ||||||
|  |  | ||||||
|         ConfigurationValidator(): | 		ConfigurationValidator() | ||||||
|             SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") { | 			: SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") {} | ||||||
|         } |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	inline auto ConfigurationValidator() { return ConfigurationValidator::instance(); } | 	inline auto ConfigurationValidator() { return ConfigurationValidator::instance(); } | ||||||
|     inline bool ValidateUCentralConfiguration(const std::string &C, std::vector<std::string> &Error, bool strict) { return ConfigurationValidator::instance()->Validate(C, Error, strict); } | 	inline bool ValidateUCentralConfiguration(const std::string &C, std::vector<std::string> &Error, | ||||||
| } | 											  bool strict) { | ||||||
|  | 		return ConfigurationValidator::instance()->Validate(C, Error, strict); | ||||||
|  | 	} | ||||||
|  | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -4,9 +4,9 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include <vector> |  | ||||||
| #include <string> | #include <string> | ||||||
| #include <utility> | #include <utility> | ||||||
|  | #include <vector> | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| @@ -15,257 +15,255 @@ namespace OpenWifi { | |||||||
| 		std::string name; | 		std::string name; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
|     inline static const std::vector<CountryInfo> CountryCodes { | 	inline static const std::vector<CountryInfo> CountryCodes{ | ||||||
|         { .code= "US", .name= "United States" }, | 		{.code = "US", .name = "United States"}, | ||||||
|         { .code= "GB", .name= "United Kingdom" }, | 		{.code = "GB", .name = "United Kingdom"}, | ||||||
|         { .code= "CA", .name= "Canada" }, | 		{.code = "CA", .name = "Canada"}, | ||||||
|         { .code= "AF", .name= "Afghanistan" }, | 		{.code = "AF", .name = "Afghanistan"}, | ||||||
|         { .code= "AX", .name= "Aland Islands" }, | 		{.code = "AX", .name = "Aland Islands"}, | ||||||
|         { .code= "AL", .name= "Albania" }, | 		{.code = "AL", .name = "Albania"}, | ||||||
|         { .code= "DZ", .name= "Algeria" }, | 		{.code = "DZ", .name = "Algeria"}, | ||||||
|         { .code= "AS", .name= "American Samoa" }, | 		{.code = "AS", .name = "American Samoa"}, | ||||||
|         { .code= "AD", .name= "Andorra" }, | 		{.code = "AD", .name = "Andorra"}, | ||||||
|         { .code= "AO", .name= "Angola" }, | 		{.code = "AO", .name = "Angola"}, | ||||||
|         { .code= "AI", .name= "Anguilla" }, | 		{.code = "AI", .name = "Anguilla"}, | ||||||
|         { .code= "AQ", .name= "Antarctica" }, | 		{.code = "AQ", .name = "Antarctica"}, | ||||||
|         { .code= "AG", .name= "Antigua And Barbuda" }, | 		{.code = "AG", .name = "Antigua And Barbuda"}, | ||||||
|         { .code= "AR", .name= "Argentina" }, | 		{.code = "AR", .name = "Argentina"}, | ||||||
|         { .code= "AM", .name= "Armenia" }, | 		{.code = "AM", .name = "Armenia"}, | ||||||
|         { .code= "AN", .name= "Netherlands Antilles" }, | 		{.code = "AN", .name = "Netherlands Antilles"}, | ||||||
|         { .code= "AW", .name= "Aruba" }, | 		{.code = "AW", .name = "Aruba"}, | ||||||
|         { .code= "AU", .name= "Australia" }, | 		{.code = "AU", .name = "Australia"}, | ||||||
|         { .code= "AT", .name= "Austria" }, | 		{.code = "AT", .name = "Austria"}, | ||||||
|         { .code= "AZ", .name= "Azerbaijan" }, | 		{.code = "AZ", .name = "Azerbaijan"}, | ||||||
|         { .code= "BS", .name= "Bahamas" }, | 		{.code = "BS", .name = "Bahamas"}, | ||||||
|         { .code= "BH", .name= "Bahrain" }, | 		{.code = "BH", .name = "Bahrain"}, | ||||||
|         { .code= "BD", .name= "Bangladesh" }, | 		{.code = "BD", .name = "Bangladesh"}, | ||||||
|         { .code= "BB", .name= "Barbados" }, | 		{.code = "BB", .name = "Barbados"}, | ||||||
|         { .code= "BY", .name= "Belarus" }, | 		{.code = "BY", .name = "Belarus"}, | ||||||
|         { .code= "BE", .name= "Belgium" }, | 		{.code = "BE", .name = "Belgium"}, | ||||||
|         { .code= "BZ", .name= "Belize" }, | 		{.code = "BZ", .name = "Belize"}, | ||||||
|         { .code= "BJ", .name= "Benin" }, | 		{.code = "BJ", .name = "Benin"}, | ||||||
|         { .code= "BM", .name= "Bermuda" }, | 		{.code = "BM", .name = "Bermuda"}, | ||||||
|         { .code= "BT", .name= "Bhutan" }, | 		{.code = "BT", .name = "Bhutan"}, | ||||||
|         { .code= "BO", .name= "Bolivia" }, | 		{.code = "BO", .name = "Bolivia"}, | ||||||
|         { .code= "BA", .name= "Bosnia And Herzegovina" }, | 		{.code = "BA", .name = "Bosnia And Herzegovina"}, | ||||||
|         { .code= "BW", .name= "Botswana" }, | 		{.code = "BW", .name = "Botswana"}, | ||||||
|         { .code= "BV", .name= "Bouvet Island" }, | 		{.code = "BV", .name = "Bouvet Island"}, | ||||||
|         { .code= "BR", .name= "Brazil" }, | 		{.code = "BR", .name = "Brazil"}, | ||||||
|         { .code= "IO", .name= "British Indian Ocean Territory" }, | 		{.code = "IO", .name = "British Indian Ocean Territory"}, | ||||||
|         { .code= "BN", .name= "Brunei Darussalam" }, | 		{.code = "BN", .name = "Brunei Darussalam"}, | ||||||
|         { .code= "BG", .name= "Bulgaria" }, | 		{.code = "BG", .name = "Bulgaria"}, | ||||||
|         { .code= "BF", .name= "Burkina Faso" }, | 		{.code = "BF", .name = "Burkina Faso"}, | ||||||
|         { .code= "BI", .name= "Burundi" }, | 		{.code = "BI", .name = "Burundi"}, | ||||||
|         { .code= "KH", .name= "Cambodia" }, | 		{.code = "KH", .name = "Cambodia"}, | ||||||
|         { .code= "CM", .name= "Cameroon" }, | 		{.code = "CM", .name = "Cameroon"}, | ||||||
|         { .code= "CA", .name= "Canada" }, | 		{.code = "CA", .name = "Canada"}, | ||||||
|         { .code= "CV", .name= "Cape Verde" }, | 		{.code = "CV", .name = "Cape Verde"}, | ||||||
|         { .code= "KY", .name= "Cayman Islands" }, | 		{.code = "KY", .name = "Cayman Islands"}, | ||||||
|         { .code= "CF", .name= "Central African Republic" }, | 		{.code = "CF", .name = "Central African Republic"}, | ||||||
|         { .code= "TD", .name= "Chad" }, | 		{.code = "TD", .name = "Chad"}, | ||||||
|         { .code= "CL", .name= "Chile" }, | 		{.code = "CL", .name = "Chile"}, | ||||||
|         { .code= "CN", .name= "China" }, | 		{.code = "CN", .name = "China"}, | ||||||
|         { .code= "CX", .name= "Christmas Island" }, | 		{.code = "CX", .name = "Christmas Island"}, | ||||||
|         { .code= "CC", .name= "Cocos (Keeling) Islands" }, | 		{.code = "CC", .name = "Cocos (Keeling) Islands"}, | ||||||
|         { .code= "CO", .name= "Colombia" }, | 		{.code = "CO", .name = "Colombia"}, | ||||||
|         { .code= "KM", .name= "Comoros" }, | 		{.code = "KM", .name = "Comoros"}, | ||||||
|         { .code= "CG", .name= "Congo" }, | 		{.code = "CG", .name = "Congo"}, | ||||||
|         { .code= "CD", .name= "Congo, Democratic Republic" }, | 		{.code = "CD", .name = "Congo, Democratic Republic"}, | ||||||
|         { .code= "CK", .name= "Cook Islands" }, | 		{.code = "CK", .name = "Cook Islands"}, | ||||||
|         { .code= "CR", .name= "Costa Rica" }, | 		{.code = "CR", .name = "Costa Rica"}, | ||||||
|         { .code= "CI", .name= "Cote D\"Ivoire" }, | 		{.code = "CI", .name = "Cote D\"Ivoire"}, | ||||||
|         { .code= "HR", .name= "Croatia" }, | 		{.code = "HR", .name = "Croatia"}, | ||||||
|         { .code= "CU", .name= "Cuba" }, | 		{.code = "CU", .name = "Cuba"}, | ||||||
|         { .code= "CY", .name= "Cyprus" }, | 		{.code = "CY", .name = "Cyprus"}, | ||||||
|         { .code= "CZ", .name= "Czech Republic" }, | 		{.code = "CZ", .name = "Czech Republic"}, | ||||||
|         { .code= "DK", .name= "Denmark" }, | 		{.code = "DK", .name = "Denmark"}, | ||||||
|         { .code= "DJ", .name= "Djibouti" }, | 		{.code = "DJ", .name = "Djibouti"}, | ||||||
|         { .code= "DM", .name= "Dominica" }, | 		{.code = "DM", .name = "Dominica"}, | ||||||
|         { .code= "DO", .name= "Dominican Republic" }, | 		{.code = "DO", .name = "Dominican Republic"}, | ||||||
|         { .code= "EC", .name= "Ecuador" }, | 		{.code = "EC", .name = "Ecuador"}, | ||||||
|         { .code= "EG", .name= "Egypt" }, | 		{.code = "EG", .name = "Egypt"}, | ||||||
|         { .code= "SV", .name= "El Salvador" }, | 		{.code = "SV", .name = "El Salvador"}, | ||||||
|         { .code= "GQ", .name= "Equatorial Guinea" }, | 		{.code = "GQ", .name = "Equatorial Guinea"}, | ||||||
|         { .code= "ER", .name= "Eritrea" }, | 		{.code = "ER", .name = "Eritrea"}, | ||||||
|         { .code= "EE", .name= "Estonia" }, | 		{.code = "EE", .name = "Estonia"}, | ||||||
|         { .code= "ET", .name= "Ethiopia" }, | 		{.code = "ET", .name = "Ethiopia"}, | ||||||
|         { .code= "FK", .name= "Falkland Islands (Malvinas)" }, | 		{.code = "FK", .name = "Falkland Islands (Malvinas)"}, | ||||||
|         { .code= "FO", .name= "Faroe Islands" }, | 		{.code = "FO", .name = "Faroe Islands"}, | ||||||
|         { .code= "FJ", .name= "Fiji" }, | 		{.code = "FJ", .name = "Fiji"}, | ||||||
|         { .code= "FI", .name= "Finland" }, | 		{.code = "FI", .name = "Finland"}, | ||||||
|         { .code= "FR", .name= "France" }, | 		{.code = "FR", .name = "France"}, | ||||||
|         { .code= "GF", .name= "French Guiana" }, | 		{.code = "GF", .name = "French Guiana"}, | ||||||
|         { .code= "PF", .name= "French Polynesia" }, | 		{.code = "PF", .name = "French Polynesia"}, | ||||||
|         { .code= "TF", .name= "French Southern Territories" }, | 		{.code = "TF", .name = "French Southern Territories"}, | ||||||
|         { .code= "GA", .name= "Gabon" }, | 		{.code = "GA", .name = "Gabon"}, | ||||||
|         { .code= "GM", .name= "Gambia" }, | 		{.code = "GM", .name = "Gambia"}, | ||||||
|         { .code= "GE", .name= "Georgia" }, | 		{.code = "GE", .name = "Georgia"}, | ||||||
|         { .code= "DE", .name= "Germany" }, | 		{.code = "DE", .name = "Germany"}, | ||||||
|         { .code= "GH", .name= "Ghana" }, | 		{.code = "GH", .name = "Ghana"}, | ||||||
|         { .code= "GI", .name= "Gibraltar" }, | 		{.code = "GI", .name = "Gibraltar"}, | ||||||
|         { .code= "GR", .name= "Greece" }, | 		{.code = "GR", .name = "Greece"}, | ||||||
|         { .code= "GL", .name= "Greenland" }, | 		{.code = "GL", .name = "Greenland"}, | ||||||
|         { .code= "GD", .name= "Grenada" }, | 		{.code = "GD", .name = "Grenada"}, | ||||||
|         { .code= "GP", .name= "Guadeloupe" }, | 		{.code = "GP", .name = "Guadeloupe"}, | ||||||
|         { .code= "GU", .name= "Guam" }, | 		{.code = "GU", .name = "Guam"}, | ||||||
|         { .code= "GT", .name= "Guatemala" }, | 		{.code = "GT", .name = "Guatemala"}, | ||||||
|         { .code= "GG", .name= "Guernsey" }, | 		{.code = "GG", .name = "Guernsey"}, | ||||||
|         { .code= "GN", .name= "Guinea" }, | 		{.code = "GN", .name = "Guinea"}, | ||||||
|         { .code= "GW", .name= "Guinea-Bissau" }, | 		{.code = "GW", .name = "Guinea-Bissau"}, | ||||||
|         { .code= "GY", .name= "Guyana" }, | 		{.code = "GY", .name = "Guyana"}, | ||||||
|         { .code= "HT", .name= "Haiti" }, | 		{.code = "HT", .name = "Haiti"}, | ||||||
|         { .code= "HM", .name= "Heard Island & Mcdonald Islands" }, | 		{.code = "HM", .name = "Heard Island & Mcdonald Islands"}, | ||||||
|         { .code= "VA", .name= "Holy See (Vatican City State)" }, | 		{.code = "VA", .name = "Holy See (Vatican City State)"}, | ||||||
|         { .code= "HN", .name= "Honduras" }, | 		{.code = "HN", .name = "Honduras"}, | ||||||
|         { .code= "HK", .name= "Hong Kong" }, | 		{.code = "HK", .name = "Hong Kong"}, | ||||||
|         { .code= "HU", .name= "Hungary" }, | 		{.code = "HU", .name = "Hungary"}, | ||||||
|         { .code= "IS", .name= "Iceland" }, | 		{.code = "IS", .name = "Iceland"}, | ||||||
|         { .code= "IN", .name= "India" }, | 		{.code = "IN", .name = "India"}, | ||||||
|         { .code= "ID", .name= "Indonesia" }, | 		{.code = "ID", .name = "Indonesia"}, | ||||||
|         { .code= "IR", .name= "Iran, Islamic Republic Of" }, | 		{.code = "IR", .name = "Iran, Islamic Republic Of"}, | ||||||
|         { .code= "IQ", .name= "Iraq" }, | 		{.code = "IQ", .name = "Iraq"}, | ||||||
|         { .code= "IE", .name= "Ireland" }, | 		{.code = "IE", .name = "Ireland"}, | ||||||
|         { .code= "IM", .name= "Isle Of Man" }, | 		{.code = "IM", .name = "Isle Of Man"}, | ||||||
|         { .code= "IL", .name= "Israel" }, | 		{.code = "IL", .name = "Israel"}, | ||||||
|         { .code= "IT", .name= "Italy" }, | 		{.code = "IT", .name = "Italy"}, | ||||||
|         { .code= "JM", .name= "Jamaica" }, | 		{.code = "JM", .name = "Jamaica"}, | ||||||
|         { .code= "JP", .name= "Japan" }, | 		{.code = "JP", .name = "Japan"}, | ||||||
|         { .code= "JE", .name= "Jersey" }, | 		{.code = "JE", .name = "Jersey"}, | ||||||
|         { .code= "JO", .name= "Jordan" }, | 		{.code = "JO", .name = "Jordan"}, | ||||||
|         { .code= "KZ", .name= "Kazakhstan" }, | 		{.code = "KZ", .name = "Kazakhstan"}, | ||||||
|         { .code= "KE", .name= "Kenya" }, | 		{.code = "KE", .name = "Kenya"}, | ||||||
|         { .code= "KI", .name= "Kiribati" }, | 		{.code = "KI", .name = "Kiribati"}, | ||||||
|         { .code= "KR", .name= "Korea" }, | 		{.code = "KR", .name = "Korea"}, | ||||||
|         { .code= "KW", .name= "Kuwait" }, | 		{.code = "KW", .name = "Kuwait"}, | ||||||
|         { .code= "KG", .name= "Kyrgyzstan" }, | 		{.code = "KG", .name = "Kyrgyzstan"}, | ||||||
|         { .code= "LA", .name= "Lao People\"s Democratic Republic" }, | 		{.code = "LA", .name = "Lao People\"s Democratic Republic"}, | ||||||
|         { .code= "LV", .name= "Latvia" }, | 		{.code = "LV", .name = "Latvia"}, | ||||||
|         { .code= "LB", .name= "Lebanon" }, | 		{.code = "LB", .name = "Lebanon"}, | ||||||
|         { .code= "LS", .name= "Lesotho" }, | 		{.code = "LS", .name = "Lesotho"}, | ||||||
|         { .code= "LR", .name= "Liberia" }, | 		{.code = "LR", .name = "Liberia"}, | ||||||
|         { .code= "LY", .name= "Libyan Arab Jamahiriya" }, | 		{.code = "LY", .name = "Libyan Arab Jamahiriya"}, | ||||||
|         { .code= "LI", .name= "Liechtenstein" }, | 		{.code = "LI", .name = "Liechtenstein"}, | ||||||
|         { .code= "LT", .name= "Lithuania" }, | 		{.code = "LT", .name = "Lithuania"}, | ||||||
|         { .code= "LU", .name= "Luxembourg" }, | 		{.code = "LU", .name = "Luxembourg"}, | ||||||
|         { .code= "MO", .name= "Macao" }, | 		{.code = "MO", .name = "Macao"}, | ||||||
|         { .code= "MK", .name= "Macedonia" }, | 		{.code = "MK", .name = "Macedonia"}, | ||||||
|         { .code= "MG", .name= "Madagascar" }, | 		{.code = "MG", .name = "Madagascar"}, | ||||||
|         { .code= "MW", .name= "Malawi" }, | 		{.code = "MW", .name = "Malawi"}, | ||||||
|         { .code= "MY", .name= "Malaysia" }, | 		{.code = "MY", .name = "Malaysia"}, | ||||||
|         { .code= "MV", .name= "Maldives" }, | 		{.code = "MV", .name = "Maldives"}, | ||||||
|         { .code= "ML", .name= "Mali" }, | 		{.code = "ML", .name = "Mali"}, | ||||||
|         { .code= "MT", .name= "Malta" }, | 		{.code = "MT", .name = "Malta"}, | ||||||
|         { .code= "MH", .name= "Marshall Islands" }, | 		{.code = "MH", .name = "Marshall Islands"}, | ||||||
|         { .code= "MQ", .name= "Martinique" }, | 		{.code = "MQ", .name = "Martinique"}, | ||||||
|         { .code= "MR", .name= "Mauritania" }, | 		{.code = "MR", .name = "Mauritania"}, | ||||||
|         { .code= "MU", .name= "Mauritius" }, | 		{.code = "MU", .name = "Mauritius"}, | ||||||
|         { .code= "YT", .name= "Mayotte" }, | 		{.code = "YT", .name = "Mayotte"}, | ||||||
|         { .code= "MX", .name= "Mexico" }, | 		{.code = "MX", .name = "Mexico"}, | ||||||
|         { .code= "FM", .name= "Micronesia, Federated States Of" }, | 		{.code = "FM", .name = "Micronesia, Federated States Of"}, | ||||||
|         { .code= "MD", .name= "Moldova" }, | 		{.code = "MD", .name = "Moldova"}, | ||||||
|         { .code= "MC", .name= "Monaco" }, | 		{.code = "MC", .name = "Monaco"}, | ||||||
|         { .code= "MN", .name= "Mongolia" }, | 		{.code = "MN", .name = "Mongolia"}, | ||||||
|         { .code= "ME", .name= "Montenegro" }, | 		{.code = "ME", .name = "Montenegro"}, | ||||||
|         { .code= "MS", .name= "Montserrat" }, | 		{.code = "MS", .name = "Montserrat"}, | ||||||
|         { .code= "MA", .name= "Morocco" }, | 		{.code = "MA", .name = "Morocco"}, | ||||||
|         { .code= "MZ", .name= "Mozambique" }, | 		{.code = "MZ", .name = "Mozambique"}, | ||||||
|         { .code= "MM", .name= "Myanmar" }, | 		{.code = "MM", .name = "Myanmar"}, | ||||||
|         { .code= "NA", .name= "Namibia" }, | 		{.code = "NA", .name = "Namibia"}, | ||||||
|         { .code= "NR", .name= "Nauru" }, | 		{.code = "NR", .name = "Nauru"}, | ||||||
|         { .code= "NP", .name= "Nepal" }, | 		{.code = "NP", .name = "Nepal"}, | ||||||
|         { .code= "NL", .name= "Netherlands" }, | 		{.code = "NL", .name = "Netherlands"}, | ||||||
|         { .code= "AN", .name= "Netherlands Antilles" }, | 		{.code = "AN", .name = "Netherlands Antilles"}, | ||||||
|         { .code= "NC", .name= "New Caledonia" }, | 		{.code = "NC", .name = "New Caledonia"}, | ||||||
|         { .code= "NZ", .name= "New Zealand" }, | 		{.code = "NZ", .name = "New Zealand"}, | ||||||
|         { .code= "NI", .name= "Nicaragua" }, | 		{.code = "NI", .name = "Nicaragua"}, | ||||||
|         { .code= "NE", .name= "Niger" }, | 		{.code = "NE", .name = "Niger"}, | ||||||
|         { .code= "NG", .name= "Nigeria" }, | 		{.code = "NG", .name = "Nigeria"}, | ||||||
|         { .code= "NU", .name= "Niue" }, | 		{.code = "NU", .name = "Niue"}, | ||||||
|         { .code= "NF", .name= "Norfolk Island" }, | 		{.code = "NF", .name = "Norfolk Island"}, | ||||||
|         { .code= "MP", .name= "Northern Mariana Islands" }, | 		{.code = "MP", .name = "Northern Mariana Islands"}, | ||||||
|         { .code= "NO", .name= "Norway" }, | 		{.code = "NO", .name = "Norway"}, | ||||||
|         { .code= "OM", .name= "Oman" }, | 		{.code = "OM", .name = "Oman"}, | ||||||
|         { .code= "PK", .name= "Pakistan" }, | 		{.code = "PK", .name = "Pakistan"}, | ||||||
|         { .code= "PW", .name= "Palau" }, | 		{.code = "PW", .name = "Palau"}, | ||||||
|         { .code= "PS", .name= "Palestinian Territory, Occupied" }, | 		{.code = "PS", .name = "Palestinian Territory, Occupied"}, | ||||||
|         { .code= "PA", .name= "Panama" }, | 		{.code = "PA", .name = "Panama"}, | ||||||
|         { .code= "PG", .name= "Papua New Guinea" }, | 		{.code = "PG", .name = "Papua New Guinea"}, | ||||||
|         { .code= "PY", .name= "Paraguay" }, | 		{.code = "PY", .name = "Paraguay"}, | ||||||
|         { .code= "PE", .name= "Peru" }, | 		{.code = "PE", .name = "Peru"}, | ||||||
|         { .code= "PH", .name= "Philippines" }, | 		{.code = "PH", .name = "Philippines"}, | ||||||
|         { .code= "PN", .name= "Pitcairn" }, | 		{.code = "PN", .name = "Pitcairn"}, | ||||||
|         { .code= "PL", .name= "Poland" }, | 		{.code = "PL", .name = "Poland"}, | ||||||
|         { .code= "PT", .name= "Portugal" }, | 		{.code = "PT", .name = "Portugal"}, | ||||||
|         { .code= "PR", .name= "Puerto Rico" }, | 		{.code = "PR", .name = "Puerto Rico"}, | ||||||
|         { .code= "QA", .name= "Qatar" }, | 		{.code = "QA", .name = "Qatar"}, | ||||||
|         { .code= "RE", .name= "Reunion" }, | 		{.code = "RE", .name = "Reunion"}, | ||||||
|         { .code= "RO", .name= "Romania" }, | 		{.code = "RO", .name = "Romania"}, | ||||||
|         { .code= "RU", .name= "Russian Federation" }, | 		{.code = "RU", .name = "Russian Federation"}, | ||||||
|         { .code= "RW", .name= "Rwanda" }, | 		{.code = "RW", .name = "Rwanda"}, | ||||||
|         { .code= "BL", .name= "Saint Barthelemy" }, | 		{.code = "BL", .name = "Saint Barthelemy"}, | ||||||
|         { .code= "SH", .name= "Saint Helena" }, | 		{.code = "SH", .name = "Saint Helena"}, | ||||||
|         { .code= "KN", .name= "Saint Kitts And Nevis" }, | 		{.code = "KN", .name = "Saint Kitts And Nevis"}, | ||||||
|         { .code= "LC", .name= "Saint Lucia" }, | 		{.code = "LC", .name = "Saint Lucia"}, | ||||||
|         { .code= "MF", .name= "Saint Martin" }, | 		{.code = "MF", .name = "Saint Martin"}, | ||||||
|         { .code= "PM", .name= "Saint Pierre And Miquelon" }, | 		{.code = "PM", .name = "Saint Pierre And Miquelon"}, | ||||||
|         { .code= "VC", .name= "Saint Vincent And Grenadines" }, | 		{.code = "VC", .name = "Saint Vincent And Grenadines"}, | ||||||
|         { .code= "WS", .name= "Samoa" }, | 		{.code = "WS", .name = "Samoa"}, | ||||||
|         { .code= "SM", .name= "San Marino" }, | 		{.code = "SM", .name = "San Marino"}, | ||||||
|         { .code= "ST", .name= "Sao Tome And Principe" }, | 		{.code = "ST", .name = "Sao Tome And Principe"}, | ||||||
|         { .code= "SA", .name= "Saudi Arabia" }, | 		{.code = "SA", .name = "Saudi Arabia"}, | ||||||
|         { .code= "SN", .name= "Senegal" }, | 		{.code = "SN", .name = "Senegal"}, | ||||||
|         { .code= "RS", .name= "Serbia" }, | 		{.code = "RS", .name = "Serbia"}, | ||||||
|         { .code= "SC", .name= "Seychelles" }, | 		{.code = "SC", .name = "Seychelles"}, | ||||||
|         { .code= "SL", .name= "Sierra Leone" }, | 		{.code = "SL", .name = "Sierra Leone"}, | ||||||
|         { .code= "SG", .name= "Singapore" }, | 		{.code = "SG", .name = "Singapore"}, | ||||||
|         { .code= "SK", .name= "Slovakia" }, | 		{.code = "SK", .name = "Slovakia"}, | ||||||
|         { .code= "SI", .name= "Slovenia" }, | 		{.code = "SI", .name = "Slovenia"}, | ||||||
|         { .code= "SB", .name= "Solomon Islands" }, | 		{.code = "SB", .name = "Solomon Islands"}, | ||||||
|         { .code= "SO", .name= "Somalia" }, | 		{.code = "SO", .name = "Somalia"}, | ||||||
|         { .code= "ZA", .name= "South Africa" }, | 		{.code = "ZA", .name = "South Africa"}, | ||||||
|         { .code= "GS", .name= "South Georgia And Sandwich Isl." }, | 		{.code = "GS", .name = "South Georgia And Sandwich Isl."}, | ||||||
|         { .code= "ES", .name= "Spain" }, | 		{.code = "ES", .name = "Spain"}, | ||||||
|         { .code= "LK", .name= "Sri Lanka" }, | 		{.code = "LK", .name = "Sri Lanka"}, | ||||||
|         { .code= "SD", .name= "Sudan" }, | 		{.code = "SD", .name = "Sudan"}, | ||||||
|         { .code= "SR", .name= "Suriname" }, | 		{.code = "SR", .name = "Suriname"}, | ||||||
|         { .code= "SJ", .name= "Svalbard And Jan Mayen" }, | 		{.code = "SJ", .name = "Svalbard And Jan Mayen"}, | ||||||
|         { .code= "SZ", .name= "Swaziland" }, | 		{.code = "SZ", .name = "Swaziland"}, | ||||||
|         { .code= "SE", .name= "Sweden" }, | 		{.code = "SE", .name = "Sweden"}, | ||||||
|         { .code= "CH", .name= "Switzerland" }, | 		{.code = "CH", .name = "Switzerland"}, | ||||||
|         { .code= "SY", .name= "Syrian Arab Republic" }, | 		{.code = "SY", .name = "Syrian Arab Republic"}, | ||||||
|         { .code= "TW", .name= "Taiwan" }, | 		{.code = "TW", .name = "Taiwan"}, | ||||||
|         { .code= "TJ", .name= "Tajikistan" }, | 		{.code = "TJ", .name = "Tajikistan"}, | ||||||
|         { .code= "TZ", .name= "Tanzania" }, | 		{.code = "TZ", .name = "Tanzania"}, | ||||||
|         { .code= "TH", .name= "Thailand" }, | 		{.code = "TH", .name = "Thailand"}, | ||||||
|         { .code= "TL", .name= "Timor-Leste" }, | 		{.code = "TL", .name = "Timor-Leste"}, | ||||||
|         { .code= "TG", .name= "Togo" }, | 		{.code = "TG", .name = "Togo"}, | ||||||
|         { .code= "TK", .name= "Tokelau" }, | 		{.code = "TK", .name = "Tokelau"}, | ||||||
|         { .code= "TO", .name= "Tonga" }, | 		{.code = "TO", .name = "Tonga"}, | ||||||
|         { .code= "TT", .name= "Trinidad And Tobago" }, | 		{.code = "TT", .name = "Trinidad And Tobago"}, | ||||||
|         { .code= "TN", .name= "Tunisia" }, | 		{.code = "TN", .name = "Tunisia"}, | ||||||
|         { .code= "TR", .name= "Turkey" }, | 		{.code = "TR", .name = "Turkey"}, | ||||||
|         { .code= "TM", .name= "Turkmenistan" }, | 		{.code = "TM", .name = "Turkmenistan"}, | ||||||
|         { .code= "TC", .name= "Turks And Caicos Islands" }, | 		{.code = "TC", .name = "Turks And Caicos Islands"}, | ||||||
|         { .code= "TV", .name= "Tuvalu" }, | 		{.code = "TV", .name = "Tuvalu"}, | ||||||
|         { .code= "UG", .name= "Uganda" }, | 		{.code = "UG", .name = "Uganda"}, | ||||||
|         { .code= "UA", .name= "Ukraine" }, | 		{.code = "UA", .name = "Ukraine"}, | ||||||
|         { .code= "AE", .name= "United Arab Emirates" }, | 		{.code = "AE", .name = "United Arab Emirates"}, | ||||||
|         { .code= "GB", .name= "United Kingdom" }, | 		{.code = "GB", .name = "United Kingdom"}, | ||||||
|         { .code= "US", .name= "United States" }, | 		{.code = "US", .name = "United States"}, | ||||||
|         { .code= "UM", .name= "United States Outlying Islands" }, | 		{.code = "UM", .name = "United States Outlying Islands"}, | ||||||
|         { .code= "UY", .name= "Uruguay" }, | 		{.code = "UY", .name = "Uruguay"}, | ||||||
|         { .code= "UZ", .name= "Uzbekistan" }, | 		{.code = "UZ", .name = "Uzbekistan"}, | ||||||
|         { .code= "VU", .name= "Vanuatu" }, | 		{.code = "VU", .name = "Vanuatu"}, | ||||||
|         { .code= "VE", .name= "Venezuela" }, | 		{.code = "VE", .name = "Venezuela"}, | ||||||
|         { .code= "VN", .name= "Viet Nam" }, | 		{.code = "VN", .name = "Viet Nam"}, | ||||||
|         { .code= "VG", .name= "Virgin Islands, British" }, | 		{.code = "VG", .name = "Virgin Islands, British"}, | ||||||
|         { .code= "VI", .name= "Virgin Islands, U.S." }, | 		{.code = "VI", .name = "Virgin Islands, U.S."}, | ||||||
|         { .code= "WF", .name= "Wallis And Futuna" }, | 		{.code = "WF", .name = "Wallis And Futuna"}, | ||||||
|         { .code= "EH", .name= "Western Sahara" }, | 		{.code = "EH", .name = "Western Sahara"}, | ||||||
|         { .code= "YE", .name= "Yemen" }, | 		{.code = "YE", .name = "Yemen"}, | ||||||
|         { .code= "ZM", .name= "Zambia" }, | 		{.code = "ZM", .name = "Zambia"}, | ||||||
|         { .code= "ZW", .name= "Zimbabwe" } | 		{.code = "ZW", .name = "Zimbabwe"}}; | ||||||
|     }; |  | ||||||
|  |  | ||||||
| } |  | ||||||
|  |  | ||||||
|  | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -4,45 +4,46 @@ | |||||||
|  |  | ||||||
| #include "framework/EventBusManager.h" | #include "framework/EventBusManager.h" | ||||||
| #include "framework/KafkaManager.h" | #include "framework/KafkaManager.h" | ||||||
| #include "framework/utils.h" |  | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  | #include "framework/utils.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	EventBusManager::EventBusManager(Poco::Logger &L) : | 	EventBusManager::EventBusManager(Poco::Logger &L) : Logger_(L) {} | ||||||
| 		Logger_(L) { |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	void EventBusManager::run() { | 	void EventBusManager::run() { | ||||||
| 		Running_ = true; | 		Running_ = true; | ||||||
| 		Utils::SetThreadName("fmwk:EventMgr"); | 		Utils::SetThreadName("fmwk:EventMgr"); | ||||||
| 		auto Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_JOIN); | 		auto Msg = std::make_shared<std::string>(MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_JOIN)); | ||||||
| 		KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false); | 		KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg, | ||||||
| 		while(Running_) { | 									false); | ||||||
|  | 		while (Running_) { | ||||||
| 			Poco::Thread::trySleep((unsigned long)MicroServiceDaemonBusTimer()); | 			Poco::Thread::trySleep((unsigned long)MicroServiceDaemonBusTimer()); | ||||||
| 			if(!Running_) | 			if (!Running_) | ||||||
| 				break; | 				break; | ||||||
| 			Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE); | 			Msg = std::make_shared<std::string>(MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE)); | ||||||
| 			KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false); | 			KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), | ||||||
|  | 										Msg, false); | ||||||
| 		} | 		} | ||||||
| 		Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE); | 		Msg = std::make_shared<std::string>(MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE)); | ||||||
| 		KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false); | 		KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg, | ||||||
|  | 									false); | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	void EventBusManager::Start() { | 	void EventBusManager::Start() { | ||||||
|         poco_information(Logger(),"Starting..."); | 		poco_information(Logger(), "Starting..."); | ||||||
| 		if(KafkaManager()->Enabled()) { | 		if (KafkaManager()->Enabled()) { | ||||||
| 			Thread_.start(*this); | 			Thread_.start(*this); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void EventBusManager::Stop() { | 	void EventBusManager::Stop() { | ||||||
| 		if(KafkaManager()->Enabled()) { | 		if (KafkaManager()->Enabled()) { | ||||||
| 			poco_information(Logger(),"Stopping..."); | 			poco_information(Logger(), "Stopping..."); | ||||||
| 			Running_ = false; | 			Running_ = false; | ||||||
| 			Thread_.wakeUp(); | 			Thread_.wakeUp(); | ||||||
| 			Thread_.join(); | 			Thread_.join(); | ||||||
| 			poco_information(Logger(),"Stopped..."); | 			poco_information(Logger(), "Stopped..."); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|   | |||||||
| @@ -4,8 +4,8 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include "Poco/Runnable.h" |  | ||||||
| #include "Poco/Logger.h" | #include "Poco/Logger.h" | ||||||
|  | #include "Poco/Runnable.h" | ||||||
| #include "Poco/Thread.h" | #include "Poco/Thread.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| @@ -16,7 +16,7 @@ namespace OpenWifi { | |||||||
| 		void run() final; | 		void run() final; | ||||||
| 		void Start(); | 		void Start(); | ||||||
| 		void Stop(); | 		void Stop(); | ||||||
| 		inline Poco::Logger & Logger() { return Logger_; } | 		inline Poco::Logger &Logger() { return Logger_; } | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		mutable std::atomic_bool Running_ = false; | 		mutable std::atomic_bool Running_ = false; | ||||||
| @@ -25,4 +25,3 @@ namespace OpenWifi { | |||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| } // namespace OpenWifi | } // namespace OpenWifi | ||||||
|  |  | ||||||
|   | |||||||
| @@ -4,251 +4,260 @@ | |||||||
|  |  | ||||||
| #include "KafkaManager.h" | #include "KafkaManager.h" | ||||||
|  |  | ||||||
| #include "framework/MicroServiceFuncs.h" |  | ||||||
| #include "fmt/format.h" | #include "fmt/format.h" | ||||||
|  | #include "framework/MicroServiceFuncs.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int level, const std::string & facility, const std::string &message) { | 	void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int level, | ||||||
| 		switch ((cppkafka::LogLevel) level) { | 						const std::string &facility, const std::string &message) { | ||||||
|  | 		switch ((cppkafka::LogLevel)level) { | ||||||
| 		case cppkafka::LogLevel::LogNotice: { | 		case cppkafka::LogLevel::LogNotice: { | ||||||
| 			poco_notice(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); | 			poco_notice(KafkaManager()->Logger(), | ||||||
| 		} | 						fmt::format("kafka-log: facility: {} message: {}", facility, message)); | ||||||
| 		break; | 		} break; | ||||||
| 		case cppkafka::LogLevel::LogDebug: { | 		case cppkafka::LogLevel::LogDebug: { | ||||||
| 			poco_debug(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); | 			poco_debug(KafkaManager()->Logger(), | ||||||
| 		} | 					   fmt::format("kafka-log: facility: {} message: {}", facility, message)); | ||||||
| 		break; | 		} break; | ||||||
| 		case cppkafka::LogLevel::LogInfo: { | 		case cppkafka::LogLevel::LogInfo: { | ||||||
| 			poco_information(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); | 			poco_information(KafkaManager()->Logger(), | ||||||
| 		} | 							 fmt::format("kafka-log: facility: {} message: {}", facility, message)); | ||||||
| 		break; | 		} break; | ||||||
| 		case cppkafka::LogLevel::LogWarning: { | 		case cppkafka::LogLevel::LogWarning: { | ||||||
| 			poco_warning(KafkaManager()->Logger(), fmt::format("kafka-log: facility: {} message: {}",facility, message)); | 			poco_warning(KafkaManager()->Logger(), | ||||||
| 		} | 						 fmt::format("kafka-log: facility: {} message: {}", facility, message)); | ||||||
| 		break; | 		} break; | ||||||
| 		case cppkafka::LogLevel::LogAlert: | 		case cppkafka::LogLevel::LogAlert: | ||||||
| 		case cppkafka::LogLevel::LogCrit: { | 		case cppkafka::LogLevel::LogCrit: { | ||||||
| 			poco_critical(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); | 			poco_critical(KafkaManager()->Logger(), | ||||||
| 		} | 						  fmt::format("kafka-log: facility: {} message: {}", facility, message)); | ||||||
| 		break; | 		} break; | ||||||
| 		case cppkafka::LogLevel::LogErr: | 		case cppkafka::LogLevel::LogErr: | ||||||
| 		case cppkafka::LogLevel::LogEmerg: | 		case cppkafka::LogLevel::LogEmerg: | ||||||
| 		default: { | 		default: { | ||||||
| 			poco_error(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); | 			poco_error(KafkaManager()->Logger(), | ||||||
| 		} | 					   fmt::format("kafka-log: facility: {} message: {}", facility, message)); | ||||||
| 		break; | 		} break; | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int error, const std::string &reason) { | 	inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int error, | ||||||
| 		poco_error(KafkaManager()->Logger(),fmt::format("kafka-error: {}, reason: {}", error, reason)); | 							  const std::string &reason) { | ||||||
|  | 		poco_error(KafkaManager()->Logger(), | ||||||
|  | 				   fmt::format("kafka-error: {}, reason: {}", error, reason)); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void AddKafkaSecurity(cppkafka::Configuration & Config) { | 	inline void AddKafkaSecurity(cppkafka::Configuration &Config) { | ||||||
| 		auto CA = MicroServiceConfigGetString("openwifi.kafka.ssl.ca.location",""); | 		auto CA = MicroServiceConfigGetString("openwifi.kafka.ssl.ca.location", ""); | ||||||
| 		auto Certificate = MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location",""); | 		auto Certificate = | ||||||
| 		auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location",""); | 			MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location", ""); | ||||||
| 		auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password",""); | 		auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location", ""); | ||||||
|  | 		auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password", ""); | ||||||
|  |  | ||||||
| 		if(CA.empty() || Certificate.empty() || Key.empty()) | 		if (CA.empty() || Certificate.empty() || Key.empty()) | ||||||
| 			return; | 			return; | ||||||
|  |  | ||||||
| 		Config.set("ssl.ca.location", CA); | 		Config.set("ssl.ca.location", CA); | ||||||
| 		Config.set("ssl.certificate.location", Certificate); | 		Config.set("ssl.certificate.location", Certificate); | ||||||
| 		Config.set("ssl.key.location", Key); | 		Config.set("ssl.key.location", Key); | ||||||
| 		if(!Password.empty()) | 		if (!Password.empty()) | ||||||
| 			Config.set("ssl.key.password", Password); | 			Config.set("ssl.key.password", Password); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  | 	void KafkaManager::initialize(Poco::Util::Application &self) { | ||||||
| 	void KafkaManager::initialize(Poco::Util::Application & self) { |  | ||||||
| 		SubSystemServer::initialize(self); | 		SubSystemServer::initialize(self); | ||||||
| 		KafkaEnabled_ = MicroServiceConfigGetBool("openwifi.kafka.enable",false); | 		KafkaEnabled_ = MicroServiceConfigGetBool("openwifi.kafka.enable", false); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void KafkaProducer::run() { | 	inline void KafkaProducer::run() { | ||||||
|         Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel()); | 		Poco::Logger &Logger_ = | ||||||
|         poco_information(Logger_,"Starting..."); | 			Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel()); | ||||||
|  | 		poco_information(Logger_, "Starting..."); | ||||||
|  |  | ||||||
| 		Utils::SetThreadName("Kafka:Prod"); | 		Utils::SetThreadName("Kafka:Prod"); | ||||||
| 		cppkafka::Configuration Config({ | 		cppkafka::Configuration Config( | ||||||
| 			{ "client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "") }, | 			{{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")}, | ||||||
| 			{ "metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist", "") } | 			 {"metadata.broker.list", | ||||||
| 		}); | 			  MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")}}); | ||||||
|  |  | ||||||
| 		AddKafkaSecurity(Config); | 		AddKafkaSecurity(Config); | ||||||
|  |  | ||||||
| 		Config.set_log_callback(KafkaLoggerFun); | 		Config.set_log_callback(KafkaLoggerFun); | ||||||
| 		Config.set_error_callback(KafkaErrorFun); | 		Config.set_error_callback(KafkaErrorFun); | ||||||
|  |  | ||||||
| 		KafkaManager()->SystemInfoWrapper_ = 	R"lit({ "system" : { "id" : )lit" + | 		KafkaManager()->SystemInfoWrapper_ = | ||||||
| 											 std::to_string(MicroServiceID()) + | 			R"lit({ "system" : { "id" : )lit" + std::to_string(MicroServiceID()) + | ||||||
| 			R"lit( , "host" : ")lit" + MicroServicePrivateEndPoint() + | 			R"lit( , "host" : ")lit" + MicroServicePrivateEndPoint() + | ||||||
| 											 R"lit(" } , "payload" : )lit" ; | 			R"lit(" } , "payload" : )lit"; | ||||||
|  |  | ||||||
| 		cppkafka::Producer Producer(Config); | 		cppkafka::Producer Producer(Config); | ||||||
| 		Running_ = true; | 		Running_ = true; | ||||||
|  |  | ||||||
| 		Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification()); | 		Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification()); | ||||||
| 		while(Note && Running_) { | 		while (Note && Running_) { | ||||||
| 			try { | 			try { | ||||||
| 				auto Msg = dynamic_cast<KafkaMessage *>(Note.get()); | 				auto Msg = dynamic_cast<KafkaMessage *>(Note.get()); | ||||||
| 				if (Msg != nullptr) { | 				if (Msg != nullptr) { | ||||||
| 					Producer.produce( | 					Producer.produce(cppkafka::MessageBuilder(Msg->Topic()) | ||||||
| 						cppkafka::MessageBuilder(Msg->Topic()).key(Msg->Key()).payload(Msg->Payload())); | 										 .key(Msg->Key()) | ||||||
|  | 										 .payload(Msg->Payload())); | ||||||
| 				} | 				} | ||||||
| 			} catch (const cppkafka::HandleException &E) { | 			} catch (const cppkafka::HandleException &E) { | ||||||
| 				poco_warning(Logger_,fmt::format("Caught a Kafka exception (producer): {}", E.what())); | 				poco_warning(Logger_, | ||||||
| 			} catch( const Poco::Exception &E) { | 							 fmt::format("Caught a Kafka exception (producer): {}", E.what())); | ||||||
|  | 			} catch (const Poco::Exception &E) { | ||||||
| 				Logger_.log(E); | 				Logger_.log(E); | ||||||
| 			} catch (...) { | 			} catch (...) { | ||||||
| 				poco_error(Logger_,"std::exception"); | 				poco_error(Logger_, "std::exception"); | ||||||
| 			} | 			} | ||||||
| 			Note = Queue_.waitDequeueNotification(); | 			Note = Queue_.waitDequeueNotification(); | ||||||
| 		} | 		} | ||||||
|         poco_information(Logger_,"Stopped..."); | 		poco_information(Logger_, "Stopped..."); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void KafkaConsumer::run() { | 	inline void KafkaConsumer::run() { | ||||||
| 		Utils::SetThreadName("Kafka:Cons"); | 		Utils::SetThreadName("Kafka:Cons"); | ||||||
|  |  | ||||||
|         Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-CONSUMER", KafkaManager()->Logger().getChannel()); | 		Poco::Logger &Logger_ = | ||||||
|  | 			Poco::Logger::create("KAFKA-CONSUMER", KafkaManager()->Logger().getChannel()); | ||||||
|  |  | ||||||
|         poco_information(Logger_,"Starting..."); | 		poco_information(Logger_, "Starting..."); | ||||||
|  |  | ||||||
| 		cppkafka::Configuration Config({ | 		cppkafka::Configuration Config( | ||||||
| 			{ "client.id", MicroServiceConfigGetString("openwifi.kafka.client.id","") }, | 			{{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")}, | ||||||
| 			{ "metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist","") }, | 			 {"metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")}, | ||||||
| 			{ "group.id", MicroServiceConfigGetString("openwifi.kafka.group.id","") }, | 			 {"group.id", MicroServiceConfigGetString("openwifi.kafka.group.id", "")}, | ||||||
| 			{ "enable.auto.commit", MicroServiceConfigGetBool("openwifi.kafka.auto.commit",false) }, | 			 {"enable.auto.commit", MicroServiceConfigGetBool("openwifi.kafka.auto.commit", false)}, | ||||||
| 			{ "auto.offset.reset", "latest" } , | 			 {"auto.offset.reset", "latest"}, | ||||||
| 			{ "enable.partition.eof", false } | 			 {"enable.partition.eof", false}}); | ||||||
| 		}); |  | ||||||
|  |  | ||||||
| 		AddKafkaSecurity(Config); | 		AddKafkaSecurity(Config); | ||||||
|  |  | ||||||
| 		Config.set_log_callback(KafkaLoggerFun); | 		Config.set_log_callback(KafkaLoggerFun); | ||||||
| 		Config.set_error_callback(KafkaErrorFun); | 		Config.set_error_callback(KafkaErrorFun); | ||||||
|  |  | ||||||
| 		cppkafka::TopicConfiguration topic_config = { | 		cppkafka::TopicConfiguration topic_config = {{"auto.offset.reset", "smallest"}}; | ||||||
| 			{ "auto.offset.reset", "smallest" } |  | ||||||
| 		}; |  | ||||||
|  |  | ||||||
| 		// Now configure it to be the default topic config | 		// Now configure it to be the default topic config | ||||||
| 		Config.set_default_topic_configuration(topic_config); | 		Config.set_default_topic_configuration(topic_config); | ||||||
|  |  | ||||||
| 		cppkafka::Consumer Consumer(Config); | 		cppkafka::Consumer Consumer(Config); | ||||||
| 		Consumer.set_assignment_callback([&](cppkafka::TopicPartitionList& partitions) { | 		Consumer.set_assignment_callback([&](cppkafka::TopicPartitionList &partitions) { | ||||||
| 			if(!partitions.empty()) { | 			if (!partitions.empty()) { | ||||||
| 				poco_information(Logger_,fmt::format("Partition assigned: {}...", | 				poco_information(Logger_, fmt::format("Partition assigned: {}...", | ||||||
| 													  partitions.front().get_partition())); | 													  partitions.front().get_partition())); | ||||||
| 			} | 			} | ||||||
| 		}); | 		}); | ||||||
| 		Consumer.set_revocation_callback([&](const cppkafka::TopicPartitionList& partitions) { | 		Consumer.set_revocation_callback([&](const cppkafka::TopicPartitionList &partitions) { | ||||||
| 			if(!partitions.empty()) { | 			if (!partitions.empty()) { | ||||||
|                 poco_information(Logger_,fmt::format("Partition revocation: {}...", | 				poco_information(Logger_, fmt::format("Partition revocation: {}...", | ||||||
| 													  partitions.front().get_partition())); | 													  partitions.front().get_partition())); | ||||||
| 			} | 			} | ||||||
| 		}); | 		}); | ||||||
|  |  | ||||||
| 		bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit",false); | 		bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit", false); | ||||||
| 		auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize",20); | 		auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize", 20); | ||||||
|  |  | ||||||
| 		Types::StringVec Topics; | 		Types::StringVec Topics; | ||||||
| 		KafkaManager()->Topics(Topics); | 		KafkaManager()->Topics(Topics); | ||||||
| 		Consumer.subscribe(Topics); | 		Consumer.subscribe(Topics); | ||||||
|  |  | ||||||
| 		Running_ = true; | 		Running_ = true; | ||||||
| 		while(Running_) { | 		while (Running_) { | ||||||
| 			try { | 			try { | ||||||
| 				std::vector<cppkafka::Message> MsgVec = Consumer.poll_batch(BatchSize, std::chrono::milliseconds(100)); | 				std::vector<cppkafka::Message> MsgVec = | ||||||
| 				for(auto const &Msg:MsgVec) { | 					Consumer.poll_batch(BatchSize, std::chrono::milliseconds(100)); | ||||||
|  | 				for (auto const &Msg : MsgVec) { | ||||||
| 					if (!Msg) | 					if (!Msg) | ||||||
| 						continue; | 						continue; | ||||||
| 					if (Msg.get_error()) { | 					if (Msg.get_error()) { | ||||||
| 						if (!Msg.is_eof()) { | 						if (!Msg.is_eof()) { | ||||||
| 							poco_error(Logger_,fmt::format("Error: {}", Msg.get_error().to_string())); | 							poco_error(Logger_, | ||||||
|  | 									   fmt::format("Error: {}", Msg.get_error().to_string())); | ||||||
| 						} | 						} | ||||||
| 						if(!AutoCommit) | 						if (!AutoCommit) | ||||||
| 							Consumer.async_commit(Msg); | 							Consumer.async_commit(Msg); | ||||||
| 						continue; | 						continue; | ||||||
| 					} | 					} | ||||||
| 					KafkaManager()->Dispatch(Msg.get_topic(), Msg.get_key(),Msg.get_payload() ); | 					KafkaManager()->Dispatch(Msg.get_topic().c_str(), Msg.get_key(), std::make_shared<std::string>(Msg.get_payload())); | ||||||
| 					if (!AutoCommit) | 					if (!AutoCommit) | ||||||
| 						Consumer.async_commit(Msg); | 						Consumer.async_commit(Msg); | ||||||
| 				} | 				} | ||||||
| 			} catch (const cppkafka::HandleException &E) { | 			} catch (const cppkafka::HandleException &E) { | ||||||
| 				poco_warning(Logger_,fmt::format("Caught a Kafka exception (consumer): {}", E.what())); | 				poco_warning(Logger_, | ||||||
|  | 							 fmt::format("Caught a Kafka exception (consumer): {}", E.what())); | ||||||
| 			} catch (const Poco::Exception &E) { | 			} catch (const Poco::Exception &E) { | ||||||
| 				Logger_.log(E); | 				Logger_.log(E); | ||||||
| 			} catch (...) { | 			} catch (...) { | ||||||
| 				poco_error(Logger_,"std::exception"); | 				poco_error(Logger_, "std::exception"); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		Consumer.unsubscribe(); | 		Consumer.unsubscribe(); | ||||||
|         poco_information(Logger_,"Stopped..."); | 		poco_information(Logger_, "Stopped..."); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaProducer::Start() { | 	void KafkaProducer::Start() { | ||||||
| 		if(!Running_) { | 		if (!Running_) { | ||||||
| 			Running_=true; | 			Running_ = true; | ||||||
| 			Worker_.start(*this); | 			Worker_.start(*this); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaProducer::Stop() { | 	void KafkaProducer::Stop() { | ||||||
| 		if(Running_) { | 		if (Running_) { | ||||||
| 			Running_=false; | 			Running_ = false; | ||||||
| 			Queue_.wakeUpAll(); | 			Queue_.wakeUpAll(); | ||||||
| 			Worker_.join(); | 			Worker_.join(); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaProducer::Produce(const std::string &Topic, const std::string &Key, const std::string &Payload) { | 	void KafkaProducer::Produce(const char *Topic, const std::string &Key, | ||||||
|  | 								const std::shared_ptr<std::string> Payload) { | ||||||
| 		std::lock_guard G(Mutex_); | 		std::lock_guard G(Mutex_); | ||||||
| 		Queue_.enqueueNotification( new KafkaMessage(Topic,Key,Payload)); | 		Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload)); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaConsumer::Start() { | 	void KafkaConsumer::Start() { | ||||||
| 		if(!Running_) { | 		if (!Running_) { | ||||||
| 			Running_=true; | 			Running_ = true; | ||||||
| 			Worker_.start(*this); | 			Worker_.start(*this); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaConsumer::Stop() { | 	void KafkaConsumer::Stop() { | ||||||
| 		if(Running_) { | 		if (Running_) { | ||||||
| 			Running_=false; | 			Running_ = false; | ||||||
| 			Worker_.wakeUp(); | 			Worker_.wakeUp(); | ||||||
| 			Worker_.join(); | 			Worker_.join(); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaDispatcher::Start() { | 	void KafkaDispatcher::Start() { | ||||||
| 		if(!Running_) { | 		if (!Running_) { | ||||||
| 			Running_=true; | 			Running_ = true; | ||||||
| 			Worker_.start(*this); | 			Worker_.start(*this); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaDispatcher::Stop() { | 	void KafkaDispatcher::Stop() { | ||||||
| 		if(Running_) { | 		if (Running_) { | ||||||
| 			Running_=false; | 			Running_ = false; | ||||||
| 			Queue_.wakeUpAll(); | 			Queue_.wakeUpAll(); | ||||||
| 			Worker_.join(); | 			Worker_.join(); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	auto KafkaDispatcher::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) { | 	auto KafkaDispatcher::RegisterTopicWatcher(const std::string &Topic, | ||||||
|  | 											   Types::TopicNotifyFunction &F) { | ||||||
| 		std::lock_guard G(Mutex_); | 		std::lock_guard G(Mutex_); | ||||||
| 		auto It = Notifiers_.find(Topic); | 		auto It = Notifiers_.find(Topic); | ||||||
| 		if(It == Notifiers_.end()) { | 		if (It == Notifiers_.end()) { | ||||||
| 			Types::TopicNotifyFunctionList L; | 			Types::TopicNotifyFunctionList L; | ||||||
| 			L.emplace(L.end(),std::make_pair(F,FunctionId_)); | 			L.emplace(L.end(), std::make_pair(F, FunctionId_)); | ||||||
| 			Notifiers_[Topic] = std::move(L); | 			Notifiers_[Topic] = std::move(L); | ||||||
| 		} else { | 		} else { | ||||||
| 			It->second.emplace(It->second.end(),std::make_pair(F,FunctionId_)); | 			It->second.emplace(It->second.end(), std::make_pair(F, FunctionId_)); | ||||||
| 		} | 		} | ||||||
| 		return FunctionId_++; | 		return FunctionId_++; | ||||||
| 	} | 	} | ||||||
| @@ -256,54 +265,55 @@ namespace OpenWifi { | |||||||
| 	void KafkaDispatcher::UnregisterTopicWatcher(const std::string &Topic, int Id) { | 	void KafkaDispatcher::UnregisterTopicWatcher(const std::string &Topic, int Id) { | ||||||
| 		std::lock_guard G(Mutex_); | 		std::lock_guard G(Mutex_); | ||||||
| 		auto It = Notifiers_.find(Topic); | 		auto It = Notifiers_.find(Topic); | ||||||
| 		if(It != Notifiers_.end()) { | 		if (It != Notifiers_.end()) { | ||||||
| 			Types::TopicNotifyFunctionList & L = It->second; | 			Types::TopicNotifyFunctionList &L = It->second; | ||||||
| 			for(auto it=L.begin(); it!=L.end(); it++) | 			for (auto it = L.begin(); it != L.end(); it++) | ||||||
| 				if(it->second == Id) { | 				if (it->second == Id) { | ||||||
| 					L.erase(it); | 					L.erase(it); | ||||||
| 					break; | 					break; | ||||||
| 				} | 				} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaDispatcher::Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload) { | 	void KafkaDispatcher::Dispatch(const char *Topic, const std::string &Key, | ||||||
|  | 								   const std::shared_ptr<std::string> Payload) { | ||||||
| 		std::lock_guard G(Mutex_); | 		std::lock_guard G(Mutex_); | ||||||
| 		auto It = Notifiers_.find(Topic); | 		auto It = Notifiers_.find(Topic); | ||||||
| 		if(It!=Notifiers_.end()) { | 		if (It != Notifiers_.end()) { | ||||||
| 			Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload)); | 			Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload)); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaDispatcher::run() { | 	void KafkaDispatcher::run() { | ||||||
|         Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-DISPATCHER", KafkaManager()->Logger().getChannel()); | 		Poco::Logger &Logger_ = | ||||||
|         poco_information(Logger_,"Starting..."); | 			Poco::Logger::create("KAFKA-DISPATCHER", KafkaManager()->Logger().getChannel()); | ||||||
|  | 		poco_information(Logger_, "Starting..."); | ||||||
| 		Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification()); | 		Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification()); | ||||||
| 		Utils::SetThreadName("kafka:dispatch"); | 		Utils::SetThreadName("kafka:dispatch"); | ||||||
| 		while(Note && Running_) { | 		while (Note && Running_) { | ||||||
| 			auto Msg = dynamic_cast<KafkaMessage*>(Note.get()); | 			auto Msg = dynamic_cast<KafkaMessage *>(Note.get()); | ||||||
| 			if(Msg!= nullptr) { | 			if (Msg != nullptr) { | ||||||
| 				auto It = Notifiers_.find(Msg->Topic()); | 				auto It = Notifiers_.find(Msg->Topic()); | ||||||
| 				if (It != Notifiers_.end()) { | 				if (It != Notifiers_.end()) { | ||||||
| 					const auto & FL = It->second; | 					const auto &FL = It->second; | ||||||
| 					for(const auto &[CallbackFunc,_]:FL) { | 					for (const auto &[CallbackFunc, _] : FL) { | ||||||
| 						CallbackFunc(Msg->Key(), Msg->Payload()); | 						CallbackFunc(Msg->Key(), Msg->Payload()); | ||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 			Note = Queue_.waitDequeueNotification(); | 			Note = Queue_.waitDequeueNotification(); | ||||||
| 		} | 		} | ||||||
|         poco_information(Logger_,"Stopped..."); | 		poco_information(Logger_, "Stopped..."); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaDispatcher::Topics(std::vector<std::string> &T) { | 	void KafkaDispatcher::Topics(std::vector<std::string> &T) { | ||||||
| 		T.clear(); | 		T.clear(); | ||||||
| 		for(const auto &[TopicName,_]:Notifiers_) | 		for (const auto &[TopicName, _] : Notifiers_) | ||||||
| 			T.push_back(TopicName); | 			T.push_back(TopicName); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  |  | ||||||
| 	int KafkaManager::Start() { | 	int KafkaManager::Start() { | ||||||
| 		if(!KafkaEnabled_) | 		if (!KafkaEnabled_) | ||||||
| 			return 0; | 			return 0; | ||||||
| 		ConsumerThr_.Start(); | 		ConsumerThr_.Start(); | ||||||
| 		ProducerThr_.Start(); | 		ProducerThr_.Start(); | ||||||
| @@ -312,54 +322,58 @@ namespace OpenWifi { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaManager::Stop() { | 	void KafkaManager::Stop() { | ||||||
| 		if(KafkaEnabled_) { | 		if (KafkaEnabled_) { | ||||||
| 			poco_information(Logger(),"Stopping..."); | 			poco_information(Logger(), "Stopping..."); | ||||||
| 			Dispatcher_.Stop(); | 			Dispatcher_.Stop(); | ||||||
| 			ProducerThr_.Stop(); | 			ProducerThr_.Stop(); | ||||||
| 			ConsumerThr_.Stop(); | 			ConsumerThr_.Stop(); | ||||||
| 			poco_information(Logger(),"Stopped..."); | 			poco_information(Logger(), "Stopped..."); | ||||||
| 			return; | 			return; | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaManager::PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage ) { | 	void KafkaManager::PostMessage(const char *topic, const std::string &key, | ||||||
| 		if(KafkaEnabled_) { | 								   const std::shared_ptr<std::string> PayLoad, bool WrapMessage) { | ||||||
| 			ProducerThr_.Produce(topic,key,WrapMessage ? WrapSystemId(PayLoad) : PayLoad); | 		if (KafkaEnabled_) { | ||||||
|  | 			ProducerThr_.Produce(topic, key, WrapMessage ? WrapSystemId(PayLoad) : PayLoad); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaManager::Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload) { | 	void KafkaManager::Dispatch(const char *Topic, const std::string &Key, | ||||||
|  | 								const std::shared_ptr<std::string> Payload) { | ||||||
| 		Dispatcher_.Dispatch(Topic, Key, Payload); | 		Dispatcher_.Dispatch(Topic, Key, Payload); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	[[nodiscard]] std::string KafkaManager::WrapSystemId(const std::string & PayLoad) { | 	[[nodiscard]] const std::shared_ptr<std::string> KafkaManager::WrapSystemId(const std::shared_ptr<std::string> PayLoad) { | ||||||
| 		return SystemInfoWrapper_ + PayLoad + "}"; | 		*PayLoad = SystemInfoWrapper_ + *PayLoad + "}"; | ||||||
|  | 		return PayLoad; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	uint64_t KafkaManager::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) { | 	uint64_t KafkaManager::RegisterTopicWatcher(const std::string &Topic, | ||||||
| 		if(KafkaEnabled_) { | 												Types::TopicNotifyFunction &F) { | ||||||
| 			return Dispatcher_.RegisterTopicWatcher(Topic,F); | 		if (KafkaEnabled_) { | ||||||
|  | 			return Dispatcher_.RegisterTopicWatcher(Topic, F); | ||||||
| 		} else { | 		} else { | ||||||
| 			return 0; | 			return 0; | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaManager::UnregisterTopicWatcher(const std::string &Topic, uint64_t Id) { | 	void KafkaManager::UnregisterTopicWatcher(const std::string &Topic, uint64_t Id) { | ||||||
| 		if(KafkaEnabled_) { | 		if (KafkaEnabled_) { | ||||||
| 			Dispatcher_.UnregisterTopicWatcher(Topic, Id); | 			Dispatcher_.UnregisterTopicWatcher(Topic, Id); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaManager::Topics(std::vector<std::string> &T) { | 	void KafkaManager::Topics(std::vector<std::string> &T) { Dispatcher_.Topics(T); } | ||||||
| 		Dispatcher_.Topics(T); |  | ||||||
|  | 	void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList &partitions) { | ||||||
|  | 		poco_information( | ||||||
|  | 			Logger(), fmt::format("Partition assigned: {}...", partitions.front().get_partition())); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList& partitions) { | 	void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList &partitions) { | ||||||
| 		poco_information(Logger(),fmt::format("Partition assigned: {}...", partitions.front().get_partition())); | 		poco_information(Logger(), fmt::format("Partition revocation: {}...", | ||||||
| 	} | 											   partitions.front().get_partition())); | ||||||
|  |  | ||||||
| 	void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList& partitions) { |  | ||||||
| 		poco_information(Logger(),fmt::format("Partition revocation: {}...",partitions.front().get_partition())); |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } // namespace OpenWifi | } // namespace OpenWifi | ||||||
| @@ -7,42 +7,41 @@ | |||||||
| #include "Poco/Notification.h" | #include "Poco/Notification.h" | ||||||
| #include "Poco/NotificationQueue.h" | #include "Poco/NotificationQueue.h" | ||||||
|  |  | ||||||
| #include "framework/SubSystemServer.h" |  | ||||||
| #include "framework/OpenWifiTypes.h" |  | ||||||
| #include "framework/utils.h" |  | ||||||
| #include "framework/KafkaTopics.h" | #include "framework/KafkaTopics.h" | ||||||
|  | #include "framework/OpenWifiTypes.h" | ||||||
|  | #include "framework/SubSystemServer.h" | ||||||
|  | #include "framework/utils.h" | ||||||
|  |  | ||||||
| #include "cppkafka/cppkafka.h" | #include "cppkafka/cppkafka.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	class KafkaMessage: public Poco::Notification { | 	class KafkaMessage : public Poco::Notification { | ||||||
| 	  public: | 	  public: | ||||||
| 		KafkaMessage( const std::string &Topic, const std::string &Key, const std::string & Payload) : | 		KafkaMessage(const char * Topic, const std::string &Key, const std::shared_ptr<std::string> Payload) | ||||||
| 			Topic_(Topic), Key_(Key), Payload_(Payload) { | 			: Topic_(Topic), Key_(Key), Payload_(std::move(Payload)) {} | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		inline const std::string & Topic() { return Topic_; } | 		inline const char * Topic() { return Topic_; } | ||||||
| 		inline const std::string & Key() { return Key_; } | 		inline const std::string &Key() { return Key_; } | ||||||
| 		inline const std::string & Payload() { return Payload_; } | 		inline const std::string &Payload() { return *Payload_; } | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::string	Topic_; | 		const char *Topic_; | ||||||
| 		std::string Key_; | 		std::string Key_; | ||||||
| 		std::string	Payload_; | 		std::shared_ptr<std::string> Payload_; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	class KafkaProducer : public Poco::Runnable { | 	class KafkaProducer : public Poco::Runnable { | ||||||
| 	  public: | 	  public: | ||||||
|             void run () override; | 		void run() override; | ||||||
| 		void Start(); | 		void Start(); | ||||||
| 		void Stop(); | 		void Stop(); | ||||||
|             void Produce(const std::string &Topic, const std::string &Key, const std::string &Payload); | 		void Produce(const char *Topic, const std::string &Key, const std::shared_ptr<std::string> Payload); | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::recursive_mutex Mutex_; | 		std::recursive_mutex Mutex_; | ||||||
| 		Poco::Thread Worker_; | 		Poco::Thread Worker_; | ||||||
|             mutable std::atomic_bool    Running_=false; | 		mutable std::atomic_bool Running_ = false; | ||||||
| 		Poco::NotificationQueue Queue_; | 		Poco::NotificationQueue Queue_; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| @@ -55,7 +54,7 @@ namespace OpenWifi { | |||||||
| 	  private: | 	  private: | ||||||
| 		std::recursive_mutex Mutex_; | 		std::recursive_mutex Mutex_; | ||||||
| 		Poco::Thread Worker_; | 		Poco::Thread Worker_; | ||||||
| 		mutable std::atomic_bool    Running_=false; | 		mutable std::atomic_bool Running_ = false; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	class KafkaDispatcher : public Poco::Runnable { | 	class KafkaDispatcher : public Poco::Runnable { | ||||||
| @@ -64,7 +63,7 @@ namespace OpenWifi { | |||||||
| 		void Stop(); | 		void Stop(); | ||||||
| 		auto RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F); | 		auto RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F); | ||||||
| 		void UnregisterTopicWatcher(const std::string &Topic, int Id); | 		void UnregisterTopicWatcher(const std::string &Topic, int Id); | ||||||
| 		void Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload); | 		void Dispatch(const char *Topic, const std::string &Key, const std::shared_ptr<std::string> Payload); | ||||||
| 		void run() override; | 		void run() override; | ||||||
| 		void Topics(std::vector<std::string> &T); | 		void Topics(std::vector<std::string> &T); | ||||||
|  |  | ||||||
| @@ -72,18 +71,17 @@ namespace OpenWifi { | |||||||
| 		std::recursive_mutex Mutex_; | 		std::recursive_mutex Mutex_; | ||||||
| 		Types::NotifyTable Notifiers_; | 		Types::NotifyTable Notifiers_; | ||||||
| 		Poco::Thread Worker_; | 		Poco::Thread Worker_; | ||||||
| 		mutable std::atomic_bool    Running_=false; | 		mutable std::atomic_bool Running_ = false; | ||||||
| 		uint64_t          			FunctionId_=1; | 		uint64_t FunctionId_ = 1; | ||||||
| 		Poco::NotificationQueue Queue_; | 		Poco::NotificationQueue Queue_; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	class KafkaManager : public SubSystemServer { | 	class KafkaManager : public SubSystemServer { | ||||||
| 	  public: | 	  public: | ||||||
|  |  | ||||||
| 		friend class KafkaConsumer; | 		friend class KafkaConsumer; | ||||||
| 		friend class KafkaProducer; | 		friend class KafkaProducer; | ||||||
|  |  | ||||||
| 		inline void initialize(Poco::Util::Application & self) override; | 		inline void initialize(Poco::Util::Application &self) override; | ||||||
|  |  | ||||||
| 		static auto instance() { | 		static auto instance() { | ||||||
| 			static auto instance_ = new KafkaManager; | 			static auto instance_ = new KafkaManager; | ||||||
| @@ -93,9 +91,10 @@ namespace OpenWifi { | |||||||
| 		int Start() override; | 		int Start() override; | ||||||
| 		void Stop() override; | 		void Stop() override; | ||||||
|  |  | ||||||
| 		void PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage = true  ); | 		void PostMessage(const char *topic, const std::string &key, | ||||||
| 		void Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload); | 						 const std::shared_ptr<std::string> PayLoad, bool WrapMessage = true); | ||||||
| 		[[nodiscard]] std::string WrapSystemId(const std::string & PayLoad); | 		void Dispatch(const char *Topic, const std::string &Key, const std::shared_ptr<std::string> Payload); | ||||||
|  | 		[[nodiscard]] const std::shared_ptr<std::string> WrapSystemId(const std::shared_ptr<std::string> PayLoad); | ||||||
| 		[[nodiscard]] inline bool Enabled() const { return KafkaEnabled_; } | 		[[nodiscard]] inline bool Enabled() const { return KafkaEnabled_; } | ||||||
| 		uint64_t RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F); | 		uint64_t RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F); | ||||||
| 		void UnregisterTopicWatcher(const std::string &Topic, uint64_t Id); | 		void UnregisterTopicWatcher(const std::string &Topic, uint64_t Id); | ||||||
| @@ -108,15 +107,12 @@ namespace OpenWifi { | |||||||
| 		KafkaConsumer ConsumerThr_; | 		KafkaConsumer ConsumerThr_; | ||||||
| 		KafkaDispatcher Dispatcher_; | 		KafkaDispatcher Dispatcher_; | ||||||
|  |  | ||||||
| 		void PartitionAssignment(const cppkafka::TopicPartitionList& partitions); | 		void PartitionAssignment(const cppkafka::TopicPartitionList &partitions); | ||||||
| 		void PartitionRevocation(const cppkafka::TopicPartitionList& partitions); | 		void PartitionRevocation(const cppkafka::TopicPartitionList &partitions); | ||||||
|  |  | ||||||
| 		KafkaManager() noexcept: | 		KafkaManager() noexcept : SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") {} | ||||||
| 			SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") { |  | ||||||
| 		} |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	inline auto KafkaManager() { return KafkaManager::instance(); } | 	inline auto KafkaManager() { return KafkaManager::instance(); } | ||||||
|  |  | ||||||
| } // namespace OpenWifi | } // namespace OpenWifi | ||||||
|  |  | ||||||
|   | |||||||
| @@ -10,33 +10,32 @@ | |||||||
|  |  | ||||||
| #include <string> | #include <string> | ||||||
| namespace OpenWifi::KafkaTopics { | namespace OpenWifi::KafkaTopics { | ||||||
| 	static const std::string HEALTHCHECK{"healthcheck"}; | 	inline const char * HEALTHCHECK = "healthcheck"; | ||||||
| 	static const std::string STATE{"state"}; | 	inline const char * STATE = "state"; | ||||||
| 	static const std::string CONNECTION{"connection"}; | 	inline const char * CONNECTION = "connection"; | ||||||
| 	static const std::string WIFISCAN{"wifiscan"}; | 	inline const char * WIFISCAN = "wifiscan"; | ||||||
| 	static const std::string ALERTS{"alerts"}; | 	inline const char * ALERTS = "alerts"; | ||||||
| 	static const std::string COMMAND{"command"}; | 	inline const char * COMMAND = "command"; | ||||||
| 	static const std::string SERVICE_EVENTS{"service_events"}; | 	inline const char * SERVICE_EVENTS = "service_events"; | ||||||
| 	static const std::string DEVICE_EVENT_QUEUE{"device_event_queue"}; | 	inline const char * DEVICE_EVENT_QUEUE = "device_event_queue"; | ||||||
| 	static const std::string DEVICE_TELEMETRY{"device_telemetry"}; | 	inline const char * DEVICE_TELEMETRY = "device_telemetry"; | ||||||
|     static const std::string PROVISIONING_CHANGE{"provisioning_change"}; | 	inline const char * PROVISIONING_CHANGE = "provisioning_change"; | ||||||
|  |  | ||||||
| 	namespace ServiceEvents { | 	namespace ServiceEvents { | ||||||
| 		static const std::string EVENT_JOIN{"join"}; | 		inline const char * EVENT_JOIN = "join"; | ||||||
| 		static const std::string EVENT_LEAVE{"leave"}; | 		inline const char * EVENT_LEAVE = "leave"; | ||||||
| 		static const std::string EVENT_KEEP_ALIVE{"keep-alive"}; | 		inline const char * EVENT_KEEP_ALIVE = "keep-alive"; | ||||||
| 		static const std::string EVENT_REMOVE_TOKEN{"remove-token"}; | 		inline const char * EVENT_REMOVE_TOKEN = "remove-token"; | ||||||
|  |  | ||||||
| 		namespace Fields { | 		namespace Fields { | ||||||
| 			static const std::string EVENT{"event"}; | 			inline const char * EVENT = "event"; | ||||||
| 			static const std::string ID{"id"}; | 			inline const char * ID = "id"; | ||||||
| 			static const std::string TYPE{"type"}; | 			inline const char * TYPE = "type"; | ||||||
| 			static const std::string PUBLIC{"publicEndPoint"}; | 			inline const char * PUBLIC = "publicEndPoint"; | ||||||
| 			static const std::string PRIVATE{"privateEndPoint"}; | 			inline const char * PRIVATE = "privateEndPoint"; | ||||||
| 			static const std::string KEY{"key"}; | 			inline const char * KEY = "key"; | ||||||
| 			static const std::string VRSN{"version"}; | 			inline const char * VRSN = "version"; | ||||||
| 			static const std::string TOKEN{"token"}; | 			inline const char * TOKEN = "token"; | ||||||
| 		} | 		} // namespace Fields | ||||||
| 	} | 	}	  // namespace ServiceEvents | ||||||
| } | } // namespace OpenWifi::KafkaTopics | ||||||
|  |  | ||||||
|   | |||||||
| @@ -2,40 +2,39 @@ | |||||||
| // Created by stephane bourque on 2022-10-26. | // Created by stephane bourque on 2022-10-26. | ||||||
| // | // | ||||||
|  |  | ||||||
| #include "Poco/FileChannel.h" |  | ||||||
| #include "Poco/ConsoleChannel.h" |  | ||||||
| #include "Poco/PatternFormatter.h" |  | ||||||
| #include "Poco/FormattingChannel.h" |  | ||||||
| #include "Poco/AsyncChannel.h" | #include "Poco/AsyncChannel.h" | ||||||
| #include "Poco/NullChannel.h" | #include "Poco/ConsoleChannel.h" | ||||||
| #include "Poco/SplitterChannel.h" | #include "Poco/FileChannel.h" | ||||||
| #include "Poco/Net/HTTPStreamFactory.h" | #include "Poco/FormattingChannel.h" | ||||||
| #include "Poco/Net/HTTPSStreamFactory.h" | #include "Poco/JSON/JSONException.h" | ||||||
| #include "Poco/Net/FTPSStreamFactory.h" | #include "Poco/Net/FTPSStreamFactory.h" | ||||||
| #include "Poco/Net/FTPStreamFactory.h" | #include "Poco/Net/FTPStreamFactory.h" | ||||||
|  | #include "Poco/Net/HTTPSStreamFactory.h" | ||||||
|  | #include "Poco/Net/HTTPStreamFactory.h" | ||||||
| #include "Poco/Net/SSLManager.h" | #include "Poco/Net/SSLManager.h" | ||||||
| #include "Poco/JSON/JSONException.h" | #include "Poco/NullChannel.h" | ||||||
|  | #include "Poco/PatternFormatter.h" | ||||||
|  | #include "Poco/SplitterChannel.h" | ||||||
|  |  | ||||||
|  | #include "framework/ALBserver.h" | ||||||
|  | #include "framework/AuthClient.h" | ||||||
|  | #include "framework/KafkaManager.h" | ||||||
| #include "framework/MicroService.h" | #include "framework/MicroService.h" | ||||||
| #include "framework/MicroServiceErrorHandler.h" | #include "framework/MicroServiceErrorHandler.h" | ||||||
| #include "framework/UI_WebSocketClientServer.h" |  | ||||||
| #include "framework/MicroServiceNames.h" | #include "framework/MicroServiceNames.h" | ||||||
| #include "framework/AuthClient.h" |  | ||||||
| #include "framework/ALBserver.h" |  | ||||||
| #include "framework/KafkaManager.h" |  | ||||||
| #include "framework/RESTAPI_GenericServerAccounting.h" |  | ||||||
| #include "framework/RESTAPI_ExtServer.h" | #include "framework/RESTAPI_ExtServer.h" | ||||||
|  | #include "framework/RESTAPI_GenericServerAccounting.h" | ||||||
| #include "framework/RESTAPI_IntServer.h" | #include "framework/RESTAPI_IntServer.h" | ||||||
| #include "framework/utils.h" | #include "framework/UI_WebSocketClientServer.h" | ||||||
| #include "framework/WebSocketLogger.h" | #include "framework/WebSocketLogger.h" | ||||||
|  | #include "framework/utils.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	void MicroService::Exit(int Reason) { | 	void MicroService::Exit(int Reason) { std::exit(Reason); } | ||||||
| 		std::exit(Reason); |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key, const std::string & Payload) { | 	void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key, | ||||||
|  | 										  const std::string &Payload) { | ||||||
| 		std::lock_guard G(InfraMutex_); | 		std::lock_guard G(InfraMutex_); | ||||||
| 		try { | 		try { | ||||||
| 			Poco::JSON::Parser P; | 			Poco::JSON::Parser P; | ||||||
| @@ -46,63 +45,96 @@ namespace OpenWifi { | |||||||
| 				uint64_t ID = Object->get(KafkaTopics::ServiceEvents::Fields::ID); | 				uint64_t ID = Object->get(KafkaTopics::ServiceEvents::Fields::ID); | ||||||
| 				auto Event = Object->get(KafkaTopics::ServiceEvents::Fields::EVENT).toString(); | 				auto Event = Object->get(KafkaTopics::ServiceEvents::Fields::EVENT).toString(); | ||||||
| 				if (ID != ID_) { | 				if (ID != ID_) { | ||||||
| 					if(	Event==KafkaTopics::ServiceEvents::EVENT_JOIN || | 					if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN || | ||||||
| 						Event==KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE || | 						Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE || | ||||||
| 						Event==KafkaTopics::ServiceEvents::EVENT_LEAVE ) { | 						Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) { | ||||||
| 						if(	Object->has(KafkaTopics::ServiceEvents::Fields::TYPE) && | 						if (Object->has(KafkaTopics::ServiceEvents::Fields::TYPE) && | ||||||
| 							Object->has(KafkaTopics::ServiceEvents::Fields::PUBLIC) && | 							Object->has(KafkaTopics::ServiceEvents::Fields::PUBLIC) && | ||||||
| 							Object->has(KafkaTopics::ServiceEvents::Fields::PRIVATE) && | 							Object->has(KafkaTopics::ServiceEvents::Fields::PRIVATE) && | ||||||
| 							Object->has(KafkaTopics::ServiceEvents::Fields::VRSN) && | 							Object->has(KafkaTopics::ServiceEvents::Fields::VRSN) && | ||||||
| 							Object->has(KafkaTopics::ServiceEvents::Fields::KEY)) { | 							Object->has(KafkaTopics::ServiceEvents::Fields::KEY)) { | ||||||
| 							auto PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(); | 							auto PrivateEndPoint = | ||||||
| 							if (Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE && Services_.find(PrivateEndPoint) != Services_.end()) { | 								Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(); | ||||||
|  | 							if (Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE && | ||||||
|  | 								Services_.find(PrivateEndPoint) != Services_.end()) { | ||||||
| 								Services_[PrivateEndPoint].LastUpdate = Utils::Now(); | 								Services_[PrivateEndPoint].LastUpdate = Utils::Now(); | ||||||
| 							} else if (Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) { | 							} else if (Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) { | ||||||
| 								Services_.erase(PrivateEndPoint); | 								Services_.erase(PrivateEndPoint); | ||||||
| 								poco_debug(logger(),fmt::format("Service {} ID={} leaving system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID)); | 								poco_debug( | ||||||
| 							} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN || Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) { | 									logger(), | ||||||
| 								poco_debug(logger(),fmt::format("Service {} ID={} joining system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID)); | 									fmt::format( | ||||||
|  | 										"Service {} ID={} leaving system.", | ||||||
|  | 										Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE) | ||||||
|  | 											.toString(), | ||||||
|  | 										ID)); | ||||||
|  | 							} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN || | ||||||
|  | 									   Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) { | ||||||
|  | 								poco_debug( | ||||||
|  | 									logger(), | ||||||
|  | 									fmt::format( | ||||||
|  | 										"Service {} ID={} joining system.", | ||||||
|  | 										Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE) | ||||||
|  | 											.toString(), | ||||||
|  | 										ID)); | ||||||
| 								Services_[PrivateEndPoint] = Types::MicroServiceMeta{ | 								Services_[PrivateEndPoint] = Types::MicroServiceMeta{ | ||||||
| 									.Id = ID, | 									.Id = ID, | ||||||
| 									.Type = Poco::toLower(Object->get(KafkaTopics::ServiceEvents::Fields::TYPE).toString()), | 									.Type = Poco::toLower( | ||||||
| 									.PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(), | 										Object->get(KafkaTopics::ServiceEvents::Fields::TYPE) | ||||||
| 									.PublicEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PUBLIC).toString(), | 											.toString()), | ||||||
| 									.AccessKey = Object->get(KafkaTopics::ServiceEvents::Fields::KEY).toString(), | 									.PrivateEndPoint = | ||||||
| 									.Version = Object->get(KafkaTopics::ServiceEvents::Fields::VRSN).toString(), | 										Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE) | ||||||
| 									.LastUpdate = Utils::Now() }; | 											.toString(), | ||||||
|  | 									.PublicEndPoint = | ||||||
|  | 										Object->get(KafkaTopics::ServiceEvents::Fields::PUBLIC) | ||||||
|  | 											.toString(), | ||||||
|  | 									.AccessKey = | ||||||
|  | 										Object->get(KafkaTopics::ServiceEvents::Fields::KEY) | ||||||
|  | 											.toString(), | ||||||
|  | 									.Version = Object->get(KafkaTopics::ServiceEvents::Fields::VRSN) | ||||||
|  | 												   .toString(), | ||||||
|  | 									.LastUpdate = Utils::Now()}; | ||||||
|  |  | ||||||
| 								std::string SvcList; | 								std::string SvcList; | ||||||
| 								for (const auto &Svc: Services_) { | 								for (const auto &Svc : Services_) { | ||||||
| 									if(SvcList.empty()) | 									if (SvcList.empty()) | ||||||
| 										SvcList = Svc.second.Type; | 										SvcList = Svc.second.Type; | ||||||
| 									else | 									else | ||||||
| 										SvcList += ", " + Svc.second.Type; | 										SvcList += ", " + Svc.second.Type; | ||||||
| 								} | 								} | ||||||
| 								poco_information(logger(),fmt::format("Current list of microservices: {}", SvcList)); | 								poco_information( | ||||||
|  | 									logger(), | ||||||
|  | 									fmt::format("Current list of microservices: {}", SvcList)); | ||||||
| 							} | 							} | ||||||
| 						} else { | 						} else { | ||||||
| 							poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing a field.",Event)); | 							poco_error( | ||||||
|  | 								logger(), | ||||||
|  | 								fmt::format("KAFKA-MSG: invalid event '{}', missing a field.", | ||||||
|  | 											Event)); | ||||||
| 						} | 						} | ||||||
| 					} else if (Event==KafkaTopics::ServiceEvents::EVENT_REMOVE_TOKEN) { | 					} else if (Event == KafkaTopics::ServiceEvents::EVENT_REMOVE_TOKEN) { | ||||||
| 						if(Object->has(KafkaTopics::ServiceEvents::Fields::TOKEN)) { | 						if (Object->has(KafkaTopics::ServiceEvents::Fields::TOKEN)) { | ||||||
| 	#ifndef TIP_SECURITY_SERVICE | #ifndef TIP_SECURITY_SERVICE | ||||||
| 							AuthClient()->RemovedCachedToken(Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString()); | 							AuthClient()->RemovedCachedToken( | ||||||
| 	#endif | 								Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString()); | ||||||
|  | #endif | ||||||
| 						} else { | 						} else { | ||||||
| 							poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing token",Event)); | 							poco_error( | ||||||
|  | 								logger(), | ||||||
|  | 								fmt::format("KAFKA-MSG: invalid event '{}', missing token", Event)); | ||||||
| 						} | 						} | ||||||
| 					} else { | 					} else { | ||||||
| 						poco_error(logger(),fmt::format("Unknown Event: {} Source: {}", Event, ID)); | 						poco_error(logger(), | ||||||
|  | 								   fmt::format("Unknown Event: {} Source: {}", Event, ID)); | ||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
| 			} else { | 			} else { | ||||||
| 				poco_error(logger(),"Bad bus message."); | 				poco_error(logger(), "Bad bus message."); | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			auto i=Services_.begin(); | 			auto i = Services_.begin(); | ||||||
| 			auto now = Utils::Now(); | 			auto now = Utils::Now(); | ||||||
| 			for(;i!=Services_.end();) { | 			for (; i != Services_.end();) { | ||||||
| 				if((now - i->second.LastUpdate)>60) { | 				if ((now - i->second.LastUpdate) > 60) { | ||||||
| 					i = Services_.erase(i); | 					i = Services_.erase(i); | ||||||
| 				} else | 				} else | ||||||
| 					++i; | 					++i; | ||||||
| @@ -113,13 +145,13 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	Types::MicroServiceMetaVec MicroService::GetServices(const std::string & Type) { | 	Types::MicroServiceMetaVec MicroService::GetServices(const std::string &Type) { | ||||||
| 		std::lock_guard G(InfraMutex_); | 		std::lock_guard G(InfraMutex_); | ||||||
|  |  | ||||||
| 		auto T = Poco::toLower(Type); | 		auto T = Poco::toLower(Type); | ||||||
| 		Types::MicroServiceMetaVec Res; | 		Types::MicroServiceMetaVec Res; | ||||||
| 		for(const auto &[_,ServiceRec]:Services_) { | 		for (const auto &[_, ServiceRec] : Services_) { | ||||||
| 			if(ServiceRec.Type==T) | 			if (ServiceRec.Type == T) | ||||||
| 				Res.push_back(ServiceRec); | 				Res.push_back(ServiceRec); | ||||||
| 		} | 		} | ||||||
| 		return Res; | 		return Res; | ||||||
| @@ -129,22 +161,24 @@ namespace OpenWifi { | |||||||
| 		std::lock_guard G(InfraMutex_); | 		std::lock_guard G(InfraMutex_); | ||||||
|  |  | ||||||
| 		Types::MicroServiceMetaVec Res; | 		Types::MicroServiceMetaVec Res; | ||||||
| 		for(const auto &[_,ServiceRec]:Services_) { | 		for (const auto &[_, ServiceRec] : Services_) { | ||||||
| 			Res.push_back(ServiceRec); | 			Res.push_back(ServiceRec); | ||||||
| 		} | 		} | ||||||
| 		return Res; | 		return Res; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::LoadConfigurationFile() { | 	void MicroService::LoadConfigurationFile() { | ||||||
| 		std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR,"."); | 		std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR, "."); | ||||||
| 		ConfigFileName_ = ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_; | 		ConfigFileName_ = | ||||||
|  | 			ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_; | ||||||
| 		Poco::Path ConfigFile(ConfigFileName_); | 		Poco::Path ConfigFile(ConfigFileName_); | ||||||
|  |  | ||||||
| 		if(!ConfigFile.isFile()) | 		if (!ConfigFile.isFile()) { | ||||||
| 		{ | 			std::cerr << DAEMON_APP_NAME << ": Configuration " << ConfigFile.toString() | ||||||
| 			std::cerr << DAEMON_APP_NAME << ": Configuration " | 					  << " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR + | ||||||
| 					  << ConfigFile.toString() << " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR | 							 " env variable the path of the " + DAEMON_PROPERTIES_FILENAME + | ||||||
| 													  + " env variable the path of the " + DAEMON_PROPERTIES_FILENAME + " file." << std::endl; | 							 " file." | ||||||
|  | 					  << std::endl; | ||||||
| 			std::exit(Poco::Util::Application::EXIT_CONFIG); | 			std::exit(Poco::Util::Application::EXIT_CONFIG); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| @@ -159,11 +193,12 @@ namespace OpenWifi { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::LoadMyConfig() { | 	void MicroService::LoadMyConfig() { | ||||||
| 		NoAPISecurity_ = ConfigGetBool("openwifi.security.restapi.disable",false); | 		NoAPISecurity_ = ConfigGetBool("openwifi.security.restapi.disable", false); | ||||||
| 		std::string KeyFile = ConfigPath("openwifi.service.key",""); | 		std::string KeyFile = ConfigPath("openwifi.service.key", ""); | ||||||
| 		if(!KeyFile.empty()) { | 		if (!KeyFile.empty()) { | ||||||
| 			std::string KeyFilePassword = ConfigPath("openwifi.service.key.password", ""); | 			std::string KeyFilePassword = ConfigPath("openwifi.service.key.password", ""); | ||||||
| 			AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword)); | 			AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>( | ||||||
|  | 				new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword)); | ||||||
| 			Cipher_ = CipherFactory_.createCipher(*AppKey_); | 			Cipher_ = CipherFactory_.createCipher(*AppKey_); | ||||||
| 			Signer_.setRSAKey(AppKey_); | 			Signer_.setRSAKey(AppKey_); | ||||||
| 			Signer_.addAllAlgorithms(); | 			Signer_.addAllAlgorithms(); | ||||||
| @@ -173,8 +208,8 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		ID_ = Utils::GetSystemId(); | 		ID_ = Utils::GetSystemId(); | ||||||
| 		if(!DebugMode_) | 		if (!DebugMode_) | ||||||
| 			DebugMode_ = ConfigGetBool("openwifi.system.debug",false); | 			DebugMode_ = ConfigGetBool("openwifi.system.debug", false); | ||||||
| 		MyPrivateEndPoint_ = ConfigGetString("openwifi.system.uri.private"); | 		MyPrivateEndPoint_ = ConfigGetString("openwifi.system.uri.private"); | ||||||
| 		MyPublicEndPoint_ = ConfigGetString("openwifi.system.uri.public"); | 		MyPublicEndPoint_ = ConfigGetString("openwifi.system.uri.public"); | ||||||
| 		UIURI_ = ConfigGetString("openwifi.system.uri.ui"); | 		UIURI_ = ConfigGetString("openwifi.system.uri.ui"); | ||||||
| @@ -184,15 +219,17 @@ namespace OpenWifi { | |||||||
| 	void MicroService::InitializeLoggingSystem() { | 	void MicroService::InitializeLoggingSystem() { | ||||||
| 		static auto initialized = false; | 		static auto initialized = false; | ||||||
|  |  | ||||||
| 		if(!initialized) { | 		if (!initialized) { | ||||||
| 			initialized = true; | 			initialized = true; | ||||||
| 			LoadConfigurationFile(); | 			LoadConfigurationFile(); | ||||||
|  |  | ||||||
| 			auto LoggingDestination = MicroService::instance().ConfigGetString("logging.type", "file"); | 			auto LoggingDestination = | ||||||
| 			auto LoggingFormat = MicroService::instance().ConfigGetString("logging.format", | 				MicroService::instance().ConfigGetString("logging.type", "file"); | ||||||
| 																		  "%Y-%m-%d %H:%M:%S.%i %s: [%p][thr:%I] %t"); | 			auto LoggingFormat = MicroService::instance().ConfigGetString( | ||||||
|  | 				"logging.format", "%Y-%m-%d %H:%M:%S.%i %s: [%p][thr:%I] %t"); | ||||||
| 			auto UseAsyncLogs_ = MicroService::instance().ConfigGetBool("logging.asynch", true); | 			auto UseAsyncLogs_ = MicroService::instance().ConfigGetBool("logging.asynch", true); | ||||||
| 			auto DisableWebSocketLogging = MicroService::instance().ConfigGetBool("logging.websocket",false); | 			auto DisableWebSocketLogging = | ||||||
|  | 				MicroService::instance().ConfigGetBool("logging.websocket", false); | ||||||
|  |  | ||||||
| 			if (LoggingDestination == "null") { | 			if (LoggingDestination == "null") { | ||||||
| 				Poco::AutoPtr<Poco::NullChannel> DevNull(new Poco::NullChannel); | 				Poco::AutoPtr<Poco::NullChannel> DevNull(new Poco::NullChannel); | ||||||
| @@ -206,12 +243,14 @@ namespace OpenWifi { | |||||||
| 			} else if (LoggingDestination == "syslog") { | 			} else if (LoggingDestination == "syslog") { | ||||||
| 				SetSyslogLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat); | 				SetSyslogLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat); | ||||||
| 			} else { | 			} else { | ||||||
|                 SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat, DAEMON_ROOT_ENV_VAR); | 				SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat, | ||||||
|  | 							DAEMON_ROOT_ENV_VAR); | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			auto Level = Poco::Logger::parseLevel(MicroService::instance().ConfigGetString("logging.level", "debug")); | 			auto Level = Poco::Logger::parseLevel( | ||||||
|  | 				MicroService::instance().ConfigGetString("logging.level", "debug")); | ||||||
| 			Poco::Logger::root().setLevel(Level); | 			Poco::Logger::root().setLevel(Level); | ||||||
| 			if(!DisableWebSocketLogging) { | 			if (!DisableWebSocketLogging) { | ||||||
| 				static const UI_WebSocketClientServer::NotificationTypeIdVec Notifications = { | 				static const UI_WebSocketClientServer::NotificationTypeIdVec Notifications = { | ||||||
| 					{1, "log"}}; | 					{1, "log"}}; | ||||||
| 				UI_WebSocketClientServer()->RegisterNotifications(Notifications); | 				UI_WebSocketClientServer()->RegisterNotifications(Notifications); | ||||||
| @@ -219,15 +258,17 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) { | 	void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, | ||||||
|  | 									  const std::string &FormatterPattern) { | ||||||
|  |  | ||||||
| 		Poco::AutoPtr<Poco::ConsoleChannel> Console(new Poco::ConsoleChannel); | 		Poco::AutoPtr<Poco::ConsoleChannel> Console(new Poco::ConsoleChannel); | ||||||
| 		Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); | 		Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); | ||||||
| 		Formatter->setProperty("pattern", FormatterPattern); | 		Formatter->setProperty("pattern", FormatterPattern); | ||||||
|         Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console)); | 		Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel( | ||||||
|  | 			new Poco::FormattingChannel(Formatter, Console)); | ||||||
|  |  | ||||||
|         if(DisableWebSocketLogging) { | 		if (DisableWebSocketLogging) { | ||||||
|             if(UseAsync) { | 			if (UseAsync) { | ||||||
| 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel)); | 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel)); | ||||||
| 				Poco::Logger::root().setChannel(Async); | 				Poco::Logger::root().setChannel(Async); | ||||||
| 			} else { | 			} else { | ||||||
| @@ -238,25 +279,28 @@ namespace OpenWifi { | |||||||
| 			Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel); | 			Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel); | ||||||
| 			Splitter->addChannel(WSLogger); | 			Splitter->addChannel(WSLogger); | ||||||
| 			Splitter->addChannel(FormattingChannel); | 			Splitter->addChannel(FormattingChannel); | ||||||
|             if(UseAsync) { | 			if (UseAsync) { | ||||||
| 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter)); | 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter)); | ||||||
| 				Poco::Logger::root().setChannel(Async); | 				Poco::Logger::root().setChannel(Async); | ||||||
| 			} else { | 			} else { | ||||||
| 				Poco::Logger::root().setChannel(Splitter); | 				Poco::Logger::root().setChannel(Splitter); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging)); | 		Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}", | ||||||
|  | 													 UseAsync, DisableWebSocketLogging)); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) { | 	void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, | ||||||
|  | 										   const std::string &FormatterPattern) { | ||||||
|  |  | ||||||
| 		Poco::AutoPtr<Poco::ColorConsoleChannel> Console(new Poco::ColorConsoleChannel); | 		Poco::AutoPtr<Poco::ColorConsoleChannel> Console(new Poco::ColorConsoleChannel); | ||||||
| 		Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); | 		Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); | ||||||
| 		Formatter->setProperty("pattern", FormatterPattern); | 		Formatter->setProperty("pattern", FormatterPattern); | ||||||
|         Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console)); | 		Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel( | ||||||
|  | 			new Poco::FormattingChannel(Formatter, Console)); | ||||||
|  |  | ||||||
|         if(DisableWebSocketLogging) { | 		if (DisableWebSocketLogging) { | ||||||
|             if(UseAsync) { | 			if (UseAsync) { | ||||||
| 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel)); | 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel)); | ||||||
| 				Poco::Logger::root().setChannel(Async); | 				Poco::Logger::root().setChannel(Async); | ||||||
| 			} else { | 			} else { | ||||||
| @@ -267,33 +311,41 @@ namespace OpenWifi { | |||||||
| 			Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel); | 			Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel); | ||||||
| 			Splitter->addChannel(WSLogger); | 			Splitter->addChannel(WSLogger); | ||||||
| 			Splitter->addChannel(FormattingChannel); | 			Splitter->addChannel(FormattingChannel); | ||||||
|             if(UseAsync) { | 			if (UseAsync) { | ||||||
| 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter)); | 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter)); | ||||||
| 				Poco::Logger::root().setChannel(Async); | 				Poco::Logger::root().setChannel(Async); | ||||||
| 			} else { | 			} else { | ||||||
| 				Poco::Logger::root().setChannel(Splitter); | 				Poco::Logger::root().setChannel(Splitter); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		Poco::Logger::root().information(fmt::format("Enabled color console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging)); | 		Poco::Logger::root().information( | ||||||
|  | 			fmt::format("Enabled color console logs: asynch={} websocket={}", UseAsync, | ||||||
|  | 						DisableWebSocketLogging)); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]]  bool DisableWebSocketLogging,[[maybe_unused]]  const std::string & FormatterPattern) { | 	void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync, | ||||||
|         //"CREATE TABLE T_POCO_LOG (Source VARCHAR, Name VARCHAR, ProcessId INTEGER, Thread VARCHAR, ThreadId INTEGER, Priority INTEGER, Text VARCHAR, DateTime DATE)" | 								  [[maybe_unused]] bool DisableWebSocketLogging, | ||||||
|  | 								  [[maybe_unused]] const std::string &FormatterPattern) { | ||||||
|  | 		//"CREATE TABLE T_POCO_LOG (Source VARCHAR, Name VARCHAR, ProcessId INTEGER, Thread VARCHAR, | ||||||
|  | 		//ThreadId INTEGER, Priority INTEGER, Text VARCHAR, DateTime DATE)" | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     void MicroService::SetSyslogLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]]  bool DisableWebSocketLogging,[[maybe_unused]]  const std::string & FormatterPattern) { | 	void MicroService::SetSyslogLogs([[maybe_unused]] bool UseAsync, | ||||||
|  | 									 [[maybe_unused]] bool DisableWebSocketLogging, | ||||||
|  | 									 [[maybe_unused]] const std::string &FormatterPattern) {} | ||||||
|  |  | ||||||
|     } | 	void MicroService::SetFileLogs(bool UseAsync, bool DisableWebSocketLogging, | ||||||
|  | 								   const std::string &FormatterPattern, | ||||||
|     void MicroService::SetFileLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern, const std::string & root_env_var) { | 								   const std::string &root_env_var) { | ||||||
|         std::string DefaultLogPath = fmt::format("${}/logs",root_env_var); | 		std::string DefaultLogPath = fmt::format("${}/logs", root_env_var); | ||||||
|         auto LoggingLocationDir = MicroService::instance().ConfigPath("logging.path", DefaultLogPath); | 		auto LoggingLocationDir = | ||||||
|  | 			MicroService::instance().ConfigPath("logging.path", DefaultLogPath); | ||||||
| 		Poco::File LD(LoggingLocationDir); | 		Poco::File LD(LoggingLocationDir); | ||||||
| 		try { | 		try { | ||||||
|             if(!LD.exists()) { | 			if (!LD.exists()) { | ||||||
| 				LD.createDirectory(); | 				LD.createDirectory(); | ||||||
| 			} | 			} | ||||||
|         } catch(const Poco::Exception &E) { | 		} catch (const Poco::Exception &E) { | ||||||
| 			std::cout << "Cannot create " << LD.path() << "  Error: " << E.message() << std::endl; | 			std::cout << "Cannot create " << LD.path() << "  Error: " << E.message() << std::endl; | ||||||
| 		} | 		} | ||||||
| 		auto LoggingLocationDirFilePattern = LoggingLocationDir + "/log"; | 		auto LoggingLocationDirFilePattern = LoggingLocationDir + "/log"; | ||||||
| @@ -306,10 +358,11 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 		Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); | 		Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); | ||||||
| 		Formatter->setProperty("pattern", FormatterPattern); | 		Formatter->setProperty("pattern", FormatterPattern); | ||||||
|         Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, FileChannel)); | 		Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel( | ||||||
|  | 			new Poco::FormattingChannel(Formatter, FileChannel)); | ||||||
|  |  | ||||||
|         if(DisableWebSocketLogging) { | 		if (DisableWebSocketLogging) { | ||||||
|             if(UseAsync) { | 			if (UseAsync) { | ||||||
| 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel)); | 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel)); | ||||||
| 				Poco::Logger::root().setChannel(Async); | 				Poco::Logger::root().setChannel(Async); | ||||||
| 			} else { | 			} else { | ||||||
| @@ -320,14 +373,15 @@ namespace OpenWifi { | |||||||
| 			Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel); | 			Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel); | ||||||
| 			Splitter->addChannel(WSLogger); | 			Splitter->addChannel(WSLogger); | ||||||
| 			Splitter->addChannel(FormattingChannel); | 			Splitter->addChannel(FormattingChannel); | ||||||
|             if(UseAsync) { | 			if (UseAsync) { | ||||||
| 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter)); | 				Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter)); | ||||||
| 				Poco::Logger::root().setChannel(Async); | 				Poco::Logger::root().setChannel(Async); | ||||||
| 			} else { | 			} else { | ||||||
| 				Poco::Logger::root().setChannel(Splitter); | 				Poco::Logger::root().setChannel(Splitter); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging)); | 		Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}", | ||||||
|  | 													 UseAsync, DisableWebSocketLogging)); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void DaemonPostInitialization(Poco::Util::Application &self); | 	void DaemonPostInitialization(Poco::Util::Application &self); | ||||||
| @@ -341,9 +395,9 @@ namespace OpenWifi { | |||||||
| 		SubSystems_.push_back(ALBHealthCheckServer()); | 		SubSystems_.push_back(ALBHealthCheckServer()); | ||||||
| 		SubSystems_.push_back(RESTAPI_ExtServer()); | 		SubSystems_.push_back(RESTAPI_ExtServer()); | ||||||
| 		SubSystems_.push_back(RESTAPI_IntServer()); | 		SubSystems_.push_back(RESTAPI_IntServer()); | ||||||
| 	#ifndef TIP_SECURITY_SERVICE | #ifndef TIP_SECURITY_SERVICE | ||||||
| 		SubSystems_.push_back(AuthClient()); | 		SubSystems_.push_back(AuthClient()); | ||||||
| 	#endif | #endif | ||||||
| 		Poco::Net::initializeSSL(); | 		Poco::Net::initializeSSL(); | ||||||
| 		Poco::Net::HTTPStreamFactory::registerFactory(); | 		Poco::Net::HTTPStreamFactory::registerFactory(); | ||||||
| 		Poco::Net::HTTPSStreamFactory::registerFactory(); | 		Poco::Net::HTTPSStreamFactory::registerFactory(); | ||||||
| @@ -352,26 +406,28 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 		Poco::File DataDir(ConfigPath("openwifi.system.data")); | 		Poco::File DataDir(ConfigPath("openwifi.system.data")); | ||||||
| 		DataDir_ = DataDir.path(); | 		DataDir_ = DataDir.path(); | ||||||
| 		if(!DataDir.exists()) { | 		if (!DataDir.exists()) { | ||||||
| 			try { | 			try { | ||||||
| 				DataDir.createDirectory(); | 				DataDir.createDirectory(); | ||||||
| 			} catch (const Poco::Exception &E) { | 			} catch (const Poco::Exception &E) { | ||||||
| 				logger().log(E); | 				logger().log(E); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		WWWAssetsDir_ = ConfigPath("openwifi.restapi.wwwassets",""); | 		WWWAssetsDir_ = ConfigPath("openwifi.restapi.wwwassets", ""); | ||||||
| 		if(WWWAssetsDir_.empty()) | 		if (WWWAssetsDir_.empty()) | ||||||
| 			WWWAssetsDir_ = DataDir_; | 			WWWAssetsDir_ = DataDir_; | ||||||
|  |  | ||||||
| 		LoadMyConfig(); | 		LoadMyConfig(); | ||||||
|  |  | ||||||
|         AllowExternalMicroServices_ = ConfigGetBool("allowexternalmicroservices",true); | 		AllowExternalMicroServices_ = ConfigGetBool("allowexternalmicroservices", true); | ||||||
|  |  | ||||||
| 		InitializeSubSystemServers(); | 		InitializeSubSystemServers(); | ||||||
| 		ServerApplication::initialize(self); | 		ServerApplication::initialize(self); | ||||||
| 		DaemonPostInitialization(self); | 		DaemonPostInitialization(self); | ||||||
|  |  | ||||||
| 		Types::TopicNotifyFunction F = [this](const std::string &Key,const std::string &Payload) { this->BusMessageReceived(Key, Payload); }; | 		Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) { | ||||||
|  | 			this->BusMessageReceived(Key, Payload); | ||||||
|  | 		}; | ||||||
| 		KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F); | 		KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -392,58 +448,64 @@ namespace OpenWifi { | |||||||
| 			Poco::Util::Option("help", "", "display help information on command line arguments") | 			Poco::Util::Option("help", "", "display help information on command line arguments") | ||||||
| 				.required(false) | 				.required(false) | ||||||
| 				.repeatable(false) | 				.repeatable(false) | ||||||
| 				.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp))); | 				.callback( | ||||||
|  | 					Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp))); | ||||||
|  |  | ||||||
| 		options.addOption( | 		options.addOption(Poco::Util::Option("file", "", "specify the configuration file") | ||||||
| 			Poco::Util::Option("file", "", "specify the configuration file") |  | ||||||
| 							  .required(false) | 							  .required(false) | ||||||
| 							  .repeatable(false) | 							  .repeatable(false) | ||||||
| 							  .argument("file") | 							  .argument("file") | ||||||
| 				.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleConfig))); | 							  .callback(Poco::Util::OptionCallback<MicroService>( | ||||||
|  | 								  this, &MicroService::handleConfig))); | ||||||
|  |  | ||||||
| 		options.addOption( | 		options.addOption(Poco::Util::Option("debug", "", "to run in debug, set to true") | ||||||
| 			Poco::Util::Option("debug", "", "to run in debug, set to true") |  | ||||||
| 							  .required(false) | 							  .required(false) | ||||||
| 							  .repeatable(false) | 							  .repeatable(false) | ||||||
| 				.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleDebug))); | 							  .callback(Poco::Util::OptionCallback<MicroService>( | ||||||
|  | 								  this, &MicroService::handleDebug))); | ||||||
|  |  | ||||||
| 		options.addOption( | 		options.addOption( | ||||||
| 			Poco::Util::Option("logs", "", "specify the log directory and file (i.e. dir/file.log)") | 			Poco::Util::Option("logs", "", "specify the log directory and file (i.e. dir/file.log)") | ||||||
| 				.required(false) | 				.required(false) | ||||||
| 				.repeatable(false) | 				.repeatable(false) | ||||||
| 				.argument("dir") | 				.argument("dir") | ||||||
| 				.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs))); | 				.callback( | ||||||
|  | 					Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs))); | ||||||
|  |  | ||||||
| 		options.addOption( | 		options.addOption(Poco::Util::Option("version", "", "get the version and quit.") | ||||||
| 			Poco::Util::Option("version", "", "get the version and quit.") |  | ||||||
| 							  .required(false) | 							  .required(false) | ||||||
| 							  .repeatable(false) | 							  .repeatable(false) | ||||||
| 				.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleVersion))); | 							  .callback(Poco::Util::OptionCallback<MicroService>( | ||||||
|  | 								  this, &MicroService::handleVersion))); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::handleHelp([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) { | 	void MicroService::handleHelp([[maybe_unused]] const std::string &name, | ||||||
|  | 								  [[maybe_unused]] const std::string &value) { | ||||||
| 		HelpRequested_ = true; | 		HelpRequested_ = true; | ||||||
| 		displayHelp(); | 		displayHelp(); | ||||||
| 		stopOptionsProcessing(); | 		stopOptionsProcessing(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::handleVersion([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) { | 	void MicroService::handleVersion([[maybe_unused]] const std::string &name, | ||||||
|  | 									 [[maybe_unused]] const std::string &value) { | ||||||
| 		HelpRequested_ = true; | 		HelpRequested_ = true; | ||||||
| 		std::cout << Version() << std::endl; | 		std::cout << Version() << std::endl; | ||||||
| 		stopOptionsProcessing(); | 		stopOptionsProcessing(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::handleDebug([[maybe_unused]] const std::string &name, const std::string &value) { | 	void MicroService::handleDebug([[maybe_unused]] const std::string &name, | ||||||
| 		if(value == "true") | 								   const std::string &value) { | ||||||
| 			DebugMode_ = true ; | 		if (value == "true") | ||||||
|  | 			DebugMode_ = true; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::handleLogs([[maybe_unused]] const std::string &name, const std::string &value) { | 	void MicroService::handleLogs([[maybe_unused]] const std::string &name, | ||||||
|  | 								  const std::string &value) { | ||||||
| 		LogDir_ = value; | 		LogDir_ = value; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::handleConfig([[maybe_unused]] const std::string &name, const std::string &value) { | 	void MicroService::handleConfig([[maybe_unused]] const std::string &name, | ||||||
|  | 									const std::string &value) { | ||||||
| 		ConfigFileName_ = value; | 		ConfigFileName_ = value; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -456,24 +518,25 @@ namespace OpenWifi { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::InitializeSubSystemServers() { | 	void MicroService::InitializeSubSystemServers() { | ||||||
| 		for(auto i:SubSystems_) { | 		for (auto i : SubSystems_) { | ||||||
| 			addSubsystem(i); | 			addSubsystem(i); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::StartSubSystemServers() { | 	void MicroService::StartSubSystemServers() { | ||||||
| 		AddActivity("Starting"); | 		AddActivity("Starting"); | ||||||
| 		for(auto i:SubSystems_) { | 		for (auto i : SubSystems_) { | ||||||
| 			i->Start(); | 			i->Start(); | ||||||
| 		} | 		} | ||||||
| 		EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create("EventBusManager",Poco::Logger::root().getChannel(),Poco::Logger::root().getLevel())); | 		EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create( | ||||||
|  | 			"EventBusManager", Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel())); | ||||||
| 		EventBusManager_->Start(); | 		EventBusManager_->Start(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::StopSubSystemServers() { | 	void MicroService::StopSubSystemServers() { | ||||||
| 		AddActivity("Stopping"); | 		AddActivity("Stopping"); | ||||||
| 		EventBusManager_->Stop(); | 		EventBusManager_->Stop(); | ||||||
| 		for(auto i=SubSystems_.rbegin(); i!=SubSystems_.rend(); ++i) { | 		for (auto i = SubSystems_.rbegin(); i != SubSystems_.rend(); ++i) { | ||||||
| 			(*i)->Stop(); | 			(*i)->Stop(); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
| @@ -510,7 +573,8 @@ namespace OpenWifi { | |||||||
| 		return ss.str(); | 		return ss.str(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) { | 	bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem, | ||||||
|  | 											const std::string &Level) { | ||||||
| 		try { | 		try { | ||||||
| 			auto P = Poco::Logger::parseLevel(Level); | 			auto P = Poco::Logger::parseLevel(Level); | ||||||
| 			auto Sub = Poco::toLower(SubSystem); | 			auto Sub = Poco::toLower(SubSystem); | ||||||
| @@ -528,7 +592,7 @@ namespace OpenWifi { | |||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 		} catch (const Poco::Exception & E) { | 		} catch (const Poco::Exception &E) { | ||||||
| 			std::cerr << "Exception" << std::endl; | 			std::cerr << "Exception" << std::endl; | ||||||
| 		} | 		} | ||||||
| 		return false; | 		return false; | ||||||
| @@ -545,7 +609,7 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	Types::StringVec MicroService::GetSubSystems() const { | 	Types::StringVec MicroService::GetSubSystems() const { | ||||||
| 		Types::StringVec Result; | 		Types::StringVec Result; | ||||||
| 		for(auto i:SubSystems_) | 		for (auto i : SubSystems_) | ||||||
| 			Result.push_back(Poco::toLower(i->Name())); | 			Result.push_back(Poco::toLower(i->Name())); | ||||||
| 		return Result; | 		return Result; | ||||||
| 	} | 	} | ||||||
| @@ -553,35 +617,32 @@ namespace OpenWifi { | |||||||
| 	Types::StringPairVec MicroService::GetLogLevels() { | 	Types::StringPairVec MicroService::GetLogLevels() { | ||||||
| 		Types::StringPairVec Result; | 		Types::StringPairVec Result; | ||||||
|  |  | ||||||
| 		for(auto &i:SubSystems_) { | 		for (auto &i : SubSystems_) { | ||||||
| 			auto P = std::make_pair( i->Name(), Utils::LogLevelToString(i->GetLoggingLevel())); | 			auto P = std::make_pair(i->Name(), Utils::LogLevelToString(i->GetLoggingLevel())); | ||||||
| 			Result.push_back(P); | 			Result.push_back(P); | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	const Types::StringVec & MicroService::GetLogLevelNames() { | 	const Types::StringVec &MicroService::GetLogLevelNames() { | ||||||
| 		static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning", "notice", "information", "debug", "trace" }; | 		static Types::StringVec LevelNames{"none",	 "fatal",		"critical", "error", "warning", | ||||||
|  | 										   "notice", "information", "debug",	"trace"}; | ||||||
| 		return LevelNames; | 		return LevelNames; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	uint64_t MicroService::ConfigGetInt(const std::string &Key,uint64_t Default) { | 	uint64_t MicroService::ConfigGetInt(const std::string &Key, uint64_t Default) { | ||||||
| 		return (uint64_t) config().getInt64(Key,Default); | 		return (uint64_t)config().getInt64(Key, Default); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	uint64_t MicroService::ConfigGetInt(const std::string &Key) { | 	uint64_t MicroService::ConfigGetInt(const std::string &Key) { return config().getInt(Key); } | ||||||
| 		return config().getInt(Key); |  | ||||||
|  | 	uint64_t MicroService::ConfigGetBool(const std::string &Key, bool Default) { | ||||||
|  | 		return config().getBool(Key, Default); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	uint64_t MicroService::ConfigGetBool(const std::string &Key,bool Default) { | 	uint64_t MicroService::ConfigGetBool(const std::string &Key) { return config().getBool(Key); } | ||||||
| 		return config().getBool(Key,Default); |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	uint64_t MicroService::ConfigGetBool(const std::string &Key) { | 	std::string MicroService::ConfigGetString(const std::string &Key, const std::string &Default) { | ||||||
| 		return config().getBool(Key); |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	std::string MicroService::ConfigGetString(const std::string &Key,const std::string & Default) { |  | ||||||
| 		return config().getString(Key, Default); | 		return config().getString(Key, Default); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -589,7 +650,7 @@ namespace OpenWifi { | |||||||
| 		return config().getString(Key); | 		return config().getString(Key); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	std::string MicroService::ConfigPath(const std::string &Key,const std::string & Default) { | 	std::string MicroService::ConfigPath(const std::string &Key, const std::string &Default) { | ||||||
| 		std::string R = config().getString(Key, Default); | 		std::string R = config().getString(Key, Default); | ||||||
| 		return Poco::Path::expand(R); | 		return Poco::Path::expand(R); | ||||||
| 	} | 	} | ||||||
| @@ -600,28 +661,30 @@ namespace OpenWifi { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	std::string MicroService::Encrypt(const std::string &S) { | 	std::string MicroService::Encrypt(const std::string &S) { | ||||||
| 		if(NoBuiltInCrypto_) { | 		if (NoBuiltInCrypto_) { | ||||||
| 			return S; | 			return S; | ||||||
| 		} | 		} | ||||||
| 		return Cipher_->encryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);; | 		return Cipher_->encryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64); | ||||||
|  | 		; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	std::string MicroService::Decrypt(const std::string &S) { | 	std::string MicroService::Decrypt(const std::string &S) { | ||||||
| 		if(NoBuiltInCrypto_) { | 		if (NoBuiltInCrypto_) { | ||||||
| 			return S; | 			return S; | ||||||
| 		} | 		} | ||||||
| 		return Cipher_->decryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);; | 		return Cipher_->decryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64); | ||||||
|  | 		; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	std::string MicroService::MakeSystemEventMessage( const std::string & Type ) const { | 	std::string MicroService::MakeSystemEventMessage(const std::string &Type) const { | ||||||
| 		Poco::JSON::Object Obj; | 		Poco::JSON::Object Obj; | ||||||
| 		Obj.set(KafkaTopics::ServiceEvents::Fields::EVENT,Type); | 		Obj.set(KafkaTopics::ServiceEvents::Fields::EVENT, Type); | ||||||
| 		Obj.set(KafkaTopics::ServiceEvents::Fields::ID,ID_); | 		Obj.set(KafkaTopics::ServiceEvents::Fields::ID, ID_); | ||||||
| 		Obj.set(KafkaTopics::ServiceEvents::Fields::TYPE,Poco::toLower(DAEMON_APP_NAME)); | 		Obj.set(KafkaTopics::ServiceEvents::Fields::TYPE, Poco::toLower(DAEMON_APP_NAME)); | ||||||
| 		Obj.set(KafkaTopics::ServiceEvents::Fields::PUBLIC,MyPublicEndPoint_); | 		Obj.set(KafkaTopics::ServiceEvents::Fields::PUBLIC, MyPublicEndPoint_); | ||||||
| 		Obj.set(KafkaTopics::ServiceEvents::Fields::PRIVATE,MyPrivateEndPoint_); | 		Obj.set(KafkaTopics::ServiceEvents::Fields::PRIVATE, MyPrivateEndPoint_); | ||||||
| 		Obj.set(KafkaTopics::ServiceEvents::Fields::KEY,MyHash_); | 		Obj.set(KafkaTopics::ServiceEvents::Fields::KEY, MyHash_); | ||||||
| 		Obj.set(KafkaTopics::ServiceEvents::Fields::VRSN,Version_); | 		Obj.set(KafkaTopics::ServiceEvents::Fields::VRSN, Version_); | ||||||
| 		std::stringstream ResultText; | 		std::stringstream ResultText; | ||||||
| 		Poco::JSON::Stringifier::stringify(Obj, ResultText); | 		Poco::JSON::Stringifier::stringify(Obj, ResultText); | ||||||
| 		return ResultText.str(); | 		return ResultText.str(); | ||||||
| @@ -640,11 +703,11 @@ namespace OpenWifi { | |||||||
| 	void MicroService::SavePID() { | 	void MicroService::SavePID() { | ||||||
| 		try { | 		try { | ||||||
| 			std::ofstream O; | 			std::ofstream O; | ||||||
| 			O.open(MicroService::instance().DataDir() + "/pidfile",std::ios::binary | std::ios::trunc); | 			O.open(MicroService::instance().DataDir() + "/pidfile", | ||||||
|  | 				   std::ios::binary | std::ios::trunc); | ||||||
| 			O << Poco::Process::id(); | 			O << Poco::Process::id(); | ||||||
| 			O.close(); | 			O.close(); | ||||||
| 		} catch (...) | 		} catch (...) { | ||||||
| 		{ |  | ||||||
| 			std::cout << "Could not save system ID" << std::endl; | 			std::cout << "Could not save system ID" << std::endl; | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
| @@ -657,46 +720,45 @@ namespace OpenWifi { | |||||||
| 			SavePID(); | 			SavePID(); | ||||||
|  |  | ||||||
| 			Poco::Logger &logger = Poco::Logger::get(DAEMON_APP_NAME); | 			Poco::Logger &logger = Poco::Logger::get(DAEMON_APP_NAME); | ||||||
| 			logger.notice(fmt::format("Starting {} version {}.",DAEMON_APP_NAME, Version())); | 			logger.notice(fmt::format("Starting {} version {}.", DAEMON_APP_NAME, Version())); | ||||||
|  |  | ||||||
| 			if(Poco::Net::Socket::supportsIPv6()) | 			if (Poco::Net::Socket::supportsIPv6()) | ||||||
| 				poco_information(logger,"System supports IPv6."); | 				poco_information(logger, "System supports IPv6."); | ||||||
| 			else | 			else | ||||||
| 				poco_information(logger,"System does NOT support IPv6."); | 				poco_information(logger, "System does NOT support IPv6."); | ||||||
|  |  | ||||||
| 			if (config().getBool("application.runAsDaemon", false)) { | 			if (config().getBool("application.runAsDaemon", false)) { | ||||||
| 				poco_information(logger,"Starting as a daemon."); | 				poco_information(logger, "Starting as a daemon."); | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			poco_information(logger,fmt::format("System ID set to {}",ID_)); | 			poco_information(logger, fmt::format("System ID set to {}", ID_)); | ||||||
| 			StartSubSystemServers(); | 			StartSubSystemServers(); | ||||||
| 			waitForTerminationRequest(); | 			waitForTerminationRequest(); | ||||||
| 			StopSubSystemServers(); | 			StopSubSystemServers(); | ||||||
| 			logger.notice(fmt::format("Stopped {}...",DAEMON_APP_NAME)); | 			logger.notice(fmt::format("Stopped {}...", DAEMON_APP_NAME)); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return Application::EXIT_OK; | 		return Application::EXIT_OK; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void MicroService::AddActivity(const std::string &Activity) { | 	void MicroService::AddActivity(const std::string &Activity) { | ||||||
| 		if(!DataDir_.empty()) { | 		if (!DataDir_.empty()) { | ||||||
| 			std::string ActivityFile{ DataDir_ + "/activity.log"}; | 			std::string ActivityFile{DataDir_ + "/activity.log"}; | ||||||
| 			try { | 			try { | ||||||
| 				std::ofstream of(ActivityFile,std::ios_base::app | std::ios_base::out ); | 				std::ofstream of(ActivityFile, std::ios_base::app | std::ios_base::out); | ||||||
| 				auto t = std::chrono::system_clock::now(); | 				auto t = std::chrono::system_clock::now(); | ||||||
| 				std::time_t now = std::chrono::system_clock::to_time_t(t); | 				std::time_t now = std::chrono::system_clock::to_time_t(t); | ||||||
| 				of << Activity << " at " << std::ctime(&now) ; | 				of << Activity << " at " << std::ctime(&now); | ||||||
| 			} catch (...) { | 			} catch (...) { | ||||||
|  |  | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	[[nodiscard]] std::string MicroService::Sign(Poco::JWT::Token &T, const std::string &Algo) { | 	[[nodiscard]] std::string MicroService::Sign(Poco::JWT::Token &T, const std::string &Algo) { | ||||||
| 		if(NoBuiltInCrypto_) { | 		if (NoBuiltInCrypto_) { | ||||||
| 			return T.toString(); | 			return T.toString(); | ||||||
| 		} else { | 		} else { | ||||||
| 			return Signer_.sign(T,Algo); | 			return Signer_.sign(T, Algo); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -704,11 +766,10 @@ namespace OpenWifi { | |||||||
| 		Poco::File F(DataDir_ + ExtraConfigurationFilename); | 		Poco::File F(DataDir_ + ExtraConfigurationFilename); | ||||||
|  |  | ||||||
| 		try { | 		try { | ||||||
| 			if(F.exists()) | 			if (F.exists()) | ||||||
| 				F.remove(); | 				F.remove(); | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -9,12 +9,11 @@ | |||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include <array> | #include <array> | ||||||
| #include <iostream> |  | ||||||
| #include <vector> |  | ||||||
| #include <fstream> |  | ||||||
| #include <random> |  | ||||||
| #include <ctime> | #include <ctime> | ||||||
|  | #include <fstream> | ||||||
|  | #include <iostream> | ||||||
|  | #include <random> | ||||||
|  | #include <vector> | ||||||
|  |  | ||||||
| // This must be defined for poco_debug and poco_trace macros to function. | // This must be defined for poco_debug and poco_trace macros to function. | ||||||
|  |  | ||||||
| @@ -24,96 +23,93 @@ | |||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| 	inline uint64_t Now() { return std::time(nullptr); }; | 	inline uint64_t Now() { return std::time(nullptr); }; | ||||||
| } | } // namespace OpenWifi | ||||||
|  |  | ||||||
| #include "Poco/Util/Application.h" | #include "Poco/AutoPtr.h" | ||||||
| #include "Poco/Util/ServerApplication.h" |  | ||||||
| #include "Poco/Util/Option.h" |  | ||||||
| #include "Poco/Util/OptionSet.h" |  | ||||||
| #include "Poco/Crypto/RSAKey.h" |  | ||||||
| #include "Poco/Crypto/CipherFactory.h" |  | ||||||
| #include "Poco/Crypto/Cipher.h" | #include "Poco/Crypto/Cipher.h" | ||||||
|  | #include "Poco/Crypto/CipherFactory.h" | ||||||
|  | #include "Poco/Crypto/RSAKey.h" | ||||||
|  | #include "Poco/Environment.h" | ||||||
|  | #include "Poco/JSON/Object.h" | ||||||
|  | #include "Poco/JWT/Signer.h" | ||||||
| #include "Poco/Net/HTTPServerRequest.h" | #include "Poco/Net/HTTPServerRequest.h" | ||||||
| #include "Poco/Process.h" | #include "Poco/Process.h" | ||||||
|  | #include "Poco/Util/Application.h" | ||||||
| #include "Poco/Util/HelpFormatter.h" | #include "Poco/Util/HelpFormatter.h" | ||||||
| #include "Poco/JSON/Object.h" | #include "Poco/Util/Option.h" | ||||||
| #include "Poco/AutoPtr.h" | #include "Poco/Util/OptionSet.h" | ||||||
| #include "Poco/Util/PropertyFileConfiguration.h" | #include "Poco/Util/PropertyFileConfiguration.h" | ||||||
| #include "Poco/JWT/Signer.h" | #include "Poco/Util/ServerApplication.h" | ||||||
| #include "Poco/Environment.h" |  | ||||||
|  |  | ||||||
| #include "framework/OpenWifiTypes.h" | #include "framework/OpenWifiTypes.h" | ||||||
|  |  | ||||||
|  | #include "framework/EventBusManager.h" | ||||||
|  | #include "framework/SubSystemServer.h" | ||||||
| #include "framework/ow_constants.h" | #include "framework/ow_constants.h" | ||||||
| #include "framework/utils.h" | #include "framework/utils.h" | ||||||
| #include "framework/SubSystemServer.h" |  | ||||||
| #include "framework/EventBusManager.h" |  | ||||||
|  |  | ||||||
| #include "RESTObjects/RESTAPI_SecurityObjects.h" | #include "RESTObjects/RESTAPI_SecurityObjects.h" | ||||||
| #include "cppkafka/cppkafka.h" | #include "cppkafka/cppkafka.h" | ||||||
|  |  | ||||||
|  | #include "fmt/core.h" | ||||||
| #include "nlohmann/json.hpp" | #include "nlohmann/json.hpp" | ||||||
| #include "ow_version.h" | #include "ow_version.h" | ||||||
| #include "fmt/core.h" |  | ||||||
|  |  | ||||||
| #define _OWDEBUG_ std::cout<< __FILE__ <<":" << __LINE__ << std::endl; | #define _OWDEBUG_ std::cout << __FILE__ << ":" << __LINE__ << std::endl; | ||||||
| // #define _OWDEBUG_ Logger().debug(Poco::format("%s: %lu",__FILE__,__LINE__)); | // #define _OWDEBUG_ Logger().debug(Poco::format("%s: %lu",__FILE__,__LINE__)); | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	class MicroService : public Poco::Util::ServerApplication { | 	class MicroService : public Poco::Util::ServerApplication { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit MicroService( 	std::string PropFile, | 		explicit MicroService(std::string PropFile, std::string RootEnv, std::string ConfigVar, | ||||||
| 					 	std::string RootEnv, | 							  std::string AppName, uint64_t BusTimer, SubSystemVec Subsystems) | ||||||
| 					 	std::string ConfigVar, | 			: DAEMON_PROPERTIES_FILENAME(std::move(PropFile)), | ||||||
| 					 	std::string AppName, | 			  DAEMON_ROOT_ENV_VAR(std::move(RootEnv)), DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)), | ||||||
| 					  	uint64_t BusTimer, | 			  DAEMON_APP_NAME(std::move(AppName)), DAEMON_BUS_TIMER(BusTimer), | ||||||
| 					  	SubSystemVec Subsystems) : | 			  SubSystems_(std::move(Subsystems)), Logger_(Poco::Logger::get("FRAMEWORK")) { | ||||||
| 				DAEMON_PROPERTIES_FILENAME(std::move(PropFile)), |  | ||||||
| 				DAEMON_ROOT_ENV_VAR(std::move(RootEnv)), |  | ||||||
| 				DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)), |  | ||||||
| 				DAEMON_APP_NAME(std::move(AppName)), |  | ||||||
| 				DAEMON_BUS_TIMER(BusTimer), |  | ||||||
| 				SubSystems_(std::move(Subsystems)), |  | ||||||
| 				Logger_(Poco::Logger::get("FRAMEWORK")) { |  | ||||||
| 			instance_ = this; | 			instance_ = this; | ||||||
| 			RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count()); | 			RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count()); | ||||||
| 			// Logger_ = Poco::Logger::root().get("BASE-SVC"); | 			// Logger_ = Poco::Logger::root().get("BASE-SVC"); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline static const char * ExtraConfigurationFilename = "/configuration_override.json"; | 		inline static const char *ExtraConfigurationFilename = "/configuration_override.json"; | ||||||
|  |  | ||||||
| 		inline void SaveConfig() { PropConfigurationFile_->save(ConfigFileName_); } | 		inline void SaveConfig() { PropConfigurationFile_->save(ConfigFileName_); } | ||||||
| 		inline auto UpdateConfig() { return PropConfigurationFile_; } | 		inline auto UpdateConfig() { return PropConfigurationFile_; } | ||||||
| 		inline bool NoAPISecurity() const { return NoAPISecurity_; } | 		inline bool NoAPISecurity() const { return NoAPISecurity_; } | ||||||
| 		inline Poco::ThreadPool & TimerPool() { return TimerPool_; } | 		inline Poco::ThreadPool &TimerPool() { return TimerPool_; } | ||||||
| 		[[nodiscard]] std::string Version() { return Version_; } | 		[[nodiscard]] std::string Version() { return Version_; } | ||||||
| 		[[nodiscard]] inline const std::string & DataDir() { return DataDir_; } | 		[[nodiscard]] inline const std::string &DataDir() { return DataDir_; } | ||||||
| 		[[nodiscard]] inline const std::string & WWWAssetsDir() { return WWWAssetsDir_; } | 		[[nodiscard]] inline const std::string &WWWAssetsDir() { return WWWAssetsDir_; } | ||||||
| 		[[nodiscard]] bool Debug() const { return DebugMode_; } | 		[[nodiscard]] bool Debug() const { return DebugMode_; } | ||||||
| 		[[nodiscard]] uint64_t ID() const { return ID_; } | 		[[nodiscard]] uint64_t ID() const { return ID_; } | ||||||
| 		[[nodiscard]] std::string Hash() const { return MyHash_; }; | 		[[nodiscard]] std::string Hash() const { return MyHash_; }; | ||||||
| 		[[nodiscard]] std::string ServiceType() const { return DAEMON_APP_NAME; }; | 		[[nodiscard]] std::string ServiceType() const { return DAEMON_APP_NAME; }; | ||||||
| 		[[nodiscard]] std::string PrivateEndPoint() const { return MyPrivateEndPoint_; }; | 		[[nodiscard]] std::string PrivateEndPoint() const { return MyPrivateEndPoint_; }; | ||||||
| 		[[nodiscard]] std::string PublicEndPoint() const { return MyPublicEndPoint_; }; | 		[[nodiscard]] std::string PublicEndPoint() const { return MyPublicEndPoint_; }; | ||||||
| 		[[nodiscard]] const SubSystemVec & GetFullSubSystems() { return SubSystems_; } | 		[[nodiscard]] const SubSystemVec &GetFullSubSystems() { return SubSystems_; } | ||||||
| 		inline uint64_t DaemonBusTimer() const { return DAEMON_BUS_TIMER; }; | 		inline uint64_t DaemonBusTimer() const { return DAEMON_BUS_TIMER; }; | ||||||
|         [[nodiscard]] const std::string & AppName() { return DAEMON_APP_NAME; } | 		[[nodiscard]] const std::string &AppName() { return DAEMON_APP_NAME; } | ||||||
| 		static inline uint64_t GetPID() { return Poco::Process::id(); }; | 		static inline uint64_t GetPID() { return Poco::Process::id(); }; | ||||||
| 		[[nodiscard]] inline const std::string GetPublicAPIEndPoint() { return MyPublicEndPoint_ + "/api/v1"; }; | 		[[nodiscard]] inline const std::string GetPublicAPIEndPoint() { | ||||||
| 		[[nodiscard]] inline const std::string & GetUIURI() const { return UIURI_;}; | 			return MyPublicEndPoint_ + "/api/v1"; | ||||||
| 		[[nodiscard]] inline uint64_t Random(uint64_t ceiling) { return (RandomEngine_() % ceiling); } | 		}; | ||||||
|  | 		[[nodiscard]] inline const std::string &GetUIURI() const { return UIURI_; }; | ||||||
|  | 		[[nodiscard]] inline uint64_t Random(uint64_t ceiling) { | ||||||
|  | 			return (RandomEngine_() % ceiling); | ||||||
|  | 		} | ||||||
| 		[[nodiscard]] inline uint64_t Random(uint64_t min, uint64_t max) { | 		[[nodiscard]] inline uint64_t Random(uint64_t min, uint64_t max) { | ||||||
| 		    return ((RandomEngine_() % (max-min)) + min); | 			return ((RandomEngine_() % (max - min)) + min); | ||||||
| 		} | 		} | ||||||
|         virtual void GetExtraConfiguration(Poco::JSON::Object & Cfg) { | 		virtual void GetExtraConfiguration(Poco::JSON::Object &Cfg) { | ||||||
|             Cfg.set("additionalConfiguration",false); | 			Cfg.set("additionalConfiguration", false); | ||||||
| 		} | 		} | ||||||
| 		static MicroService & instance() { return *instance_; } | 		static MicroService &instance() { return *instance_; } | ||||||
|  |  | ||||||
| 		inline void Exit(int Reason); | 		inline void Exit(int Reason); | ||||||
| 		void BusMessageReceived(const std::string &Key, const std::string & Payload); | 		void BusMessageReceived(const std::string &Key, const std::string &Payload); | ||||||
| 		Types::MicroServiceMetaVec GetServices(const std::string & Type); | 		Types::MicroServiceMetaVec GetServices(const std::string &Type); | ||||||
| 		Types::MicroServiceMetaVec GetServices(); | 		Types::MicroServiceMetaVec GetServices(); | ||||||
| 		void LoadConfigurationFile(); | 		void LoadConfigurationFile(); | ||||||
| 		void Reload(); | 		void Reload(); | ||||||
| @@ -136,18 +132,18 @@ namespace OpenWifi { | |||||||
| 		void Reload(const std::string &Sub); | 		void Reload(const std::string &Sub); | ||||||
| 		Types::StringVec GetSubSystems() const; | 		Types::StringVec GetSubSystems() const; | ||||||
| 		Types::StringPairVec GetLogLevels(); | 		Types::StringPairVec GetLogLevels(); | ||||||
| 		const Types::StringVec & GetLogLevelNames(); | 		const Types::StringVec &GetLogLevelNames(); | ||||||
| 		uint64_t ConfigGetInt(const std::string &Key,uint64_t Default); | 		uint64_t ConfigGetInt(const std::string &Key, uint64_t Default); | ||||||
| 		uint64_t ConfigGetInt(const std::string &Key); | 		uint64_t ConfigGetInt(const std::string &Key); | ||||||
| 		uint64_t ConfigGetBool(const std::string &Key,bool Default); | 		uint64_t ConfigGetBool(const std::string &Key, bool Default); | ||||||
| 		uint64_t ConfigGetBool(const std::string &Key); | 		uint64_t ConfigGetBool(const std::string &Key); | ||||||
| 		std::string ConfigGetString(const std::string &Key,const std::string & Default); | 		std::string ConfigGetString(const std::string &Key, const std::string &Default); | ||||||
| 		std::string ConfigGetString(const std::string &Key); | 		std::string ConfigGetString(const std::string &Key); | ||||||
| 		std::string ConfigPath(const std::string &Key,const std::string & Default); | 		std::string ConfigPath(const std::string &Key, const std::string &Default); | ||||||
| 		std::string ConfigPath(const std::string &Key); | 		std::string ConfigPath(const std::string &Key); | ||||||
| 		std::string Encrypt(const std::string &S); | 		std::string Encrypt(const std::string &S); | ||||||
| 		std::string Decrypt(const std::string &S); | 		std::string Decrypt(const std::string &S); | ||||||
| 		std::string MakeSystemEventMessage( const std::string & Type ) const; | 		std::string MakeSystemEventMessage(const std::string &Type) const; | ||||||
| 		[[nodiscard]] bool IsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request); | 		[[nodiscard]] bool IsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request); | ||||||
| 		static void SavePID(); | 		static void SavePID(); | ||||||
| 		int main(const ArgVec &args) override; | 		int main(const ArgVec &args) override; | ||||||
| @@ -158,15 +154,21 @@ namespace OpenWifi { | |||||||
| 		[[nodiscard]] std::string Sign(Poco::JWT::Token &T, const std::string &Algo); | 		[[nodiscard]] std::string Sign(Poco::JWT::Token &T, const std::string &Algo); | ||||||
| 		void AddActivity(const std::string &Activity); | 		void AddActivity(const std::string &Activity); | ||||||
|  |  | ||||||
|         static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern); | 		static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket, | ||||||
|         static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern); | 								   const std::string &FormatterPattern); | ||||||
|         static void SetSQLLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern); | 		static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket, | ||||||
|         static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern); | 										const std::string &FormatterPattern); | ||||||
|         static void SetFileLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern, const std::string & root_env_var); | 		static void SetSQLLogs(bool UseAsync, bool AllowWebSocket, | ||||||
|  | 							   const std::string &FormatterPattern); | ||||||
|  | 		static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket, | ||||||
|  | 								  const std::string &FormatterPattern); | ||||||
|  | 		static void SetFileLogs(bool UseAsync, bool AllowWebSocket, | ||||||
|  | 								const std::string &FormatterPattern, | ||||||
|  | 								const std::string &root_env_var); | ||||||
| 		inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; } | 		inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; } | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 	    static MicroService         * instance_; | 		static MicroService *instance_; | ||||||
| 		bool HelpRequested_ = false; | 		bool HelpRequested_ = false; | ||||||
| 		std::string LogDir_; | 		std::string LogDir_; | ||||||
| 		std::string ConfigFileName_; | 		std::string ConfigFileName_; | ||||||
| @@ -175,32 +177,33 @@ namespace OpenWifi { | |||||||
| 		bool DebugMode_ = false; | 		bool DebugMode_ = false; | ||||||
| 		std::string DataDir_; | 		std::string DataDir_; | ||||||
| 		std::string WWWAssetsDir_; | 		std::string WWWAssetsDir_; | ||||||
| 		Poco::Crypto::CipherFactory & CipherFactory_ = Poco::Crypto::CipherFactory::defaultFactory(); | 		Poco::Crypto::CipherFactory &CipherFactory_ = Poco::Crypto::CipherFactory::defaultFactory(); | ||||||
| 		Poco::Crypto::Cipher        * Cipher_ = nullptr; | 		Poco::Crypto::Cipher *Cipher_ = nullptr; | ||||||
| 		Types::MicroServiceMetaMap Services_; | 		Types::MicroServiceMetaMap Services_; | ||||||
| 		std::string MyHash_; | 		std::string MyHash_; | ||||||
| 		std::string MyPrivateEndPoint_; | 		std::string MyPrivateEndPoint_; | ||||||
| 		std::string MyPublicEndPoint_; | 		std::string MyPublicEndPoint_; | ||||||
| 		std::string UIURI_; | 		std::string UIURI_; | ||||||
| 		std::string 				Version_{ OW_VERSION::VERSION + "("+ OW_VERSION::BUILD + ")" + " - " + OW_VERSION::HASH }; | 		std::string Version_{OW_VERSION::VERSION + "(" + OW_VERSION::BUILD + ")" + " - " + | ||||||
|  | 							 OW_VERSION::HASH}; | ||||||
| 		std::recursive_mutex InfraMutex_; | 		std::recursive_mutex InfraMutex_; | ||||||
| 		std::default_random_engine RandomEngine_; | 		std::default_random_engine RandomEngine_; | ||||||
|         Poco::Util::PropertyFileConfiguration   * PropConfigurationFile_ = nullptr; | 		Poco::Util::PropertyFileConfiguration *PropConfigurationFile_ = nullptr; | ||||||
| 		std::string DAEMON_PROPERTIES_FILENAME; | 		std::string DAEMON_PROPERTIES_FILENAME; | ||||||
| 		std::string DAEMON_ROOT_ENV_VAR; | 		std::string DAEMON_ROOT_ENV_VAR; | ||||||
| 		std::string DAEMON_CONFIG_ENV_VAR; | 		std::string DAEMON_CONFIG_ENV_VAR; | ||||||
| 		std::string DAEMON_APP_NAME; | 		std::string DAEMON_APP_NAME; | ||||||
| 		uint64_t DAEMON_BUS_TIMER; | 		uint64_t DAEMON_BUS_TIMER; | ||||||
| 		SubSystemVec SubSystems_; | 		SubSystemVec SubSystems_; | ||||||
|         bool                        NoAPISecurity_=false; | 		bool NoAPISecurity_ = false; | ||||||
|         bool                        NoBuiltInCrypto_=false; | 		bool NoBuiltInCrypto_ = false; | ||||||
|         bool                        AllowExternalMicroServices_=false; | 		bool AllowExternalMicroServices_ = false; | ||||||
| 		Poco::JWT::Signer Signer_; | 		Poco::JWT::Signer Signer_; | ||||||
| 		Poco::Logger &Logger_; | 		Poco::Logger &Logger_; | ||||||
| 		Poco::ThreadPool				TimerPool_{"timer:pool",2,32}; | 		Poco::ThreadPool TimerPool_{"timer:pool", 2, 32}; | ||||||
| 		std::unique_ptr<EventBusManager> EventBusManager_; | 		std::unique_ptr<EventBusManager> EventBusManager_; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	inline MicroService * MicroService::instance_ = nullptr; | 	inline MicroService *MicroService::instance_ = nullptr; | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -4,25 +4,24 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include "fmt/format.h" |  | ||||||
| #include "Poco/Util/Application.h" |  | ||||||
| #include "Poco/ErrorHandler.h" | #include "Poco/ErrorHandler.h" | ||||||
|  | #include "Poco/JSON/JSONException.h" | ||||||
|  | #include "Poco/JSON/Template.h" | ||||||
| #include "Poco/Net/NetException.h" | #include "Poco/Net/NetException.h" | ||||||
| #include "Poco/Net/SSLException.h" | #include "Poco/Net/SSLException.h" | ||||||
| #include "Poco/JSON/Template.h" |  | ||||||
| #include "Poco/JSON/JSONException.h" |  | ||||||
| #include "Poco/Thread.h" | #include "Poco/Thread.h" | ||||||
|  | #include "Poco/Util/Application.h" | ||||||
|  | #include "fmt/format.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	class MicroServiceErrorHandler : public Poco::ErrorHandler { | 	class MicroServiceErrorHandler : public Poco::ErrorHandler { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit MicroServiceErrorHandler(Poco::Util::Application &App) : App_(App) { | 		explicit MicroServiceErrorHandler(Poco::Util::Application &App) : App_(App) {} | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		inline void exception(const Poco::Exception & Base) override { | 		inline void exception(const Poco::Exception &Base) override { | ||||||
| 			try { | 			try { | ||||||
| 				if(Poco::Thread::current()!= nullptr) { | 				if (Poco::Thread::current() != nullptr) { | ||||||
| 					t_name = Poco::Thread::current()->getName(); | 					t_name = Poco::Thread::current()->getName(); | ||||||
| 					t_id = Poco::Thread::current()->id(); | 					t_id = Poco::Thread::current()->id(); | ||||||
| 				} else { | 				} else { | ||||||
| @@ -34,179 +33,167 @@ namespace OpenWifi { | |||||||
| 				Base.rethrow(); | 				Base.rethrow(); | ||||||
|  |  | ||||||
| 			} catch (const Poco::Net::InvalidCertificateException &E) { | 			} catch (const Poco::Net::InvalidCertificateException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::InvalidCertificateException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), | ||||||
| 													  t_name, t_id, E.code(), | 						   fmt::format("Poco::Net::InvalidCertificateException thr_name={} " | ||||||
| 													  E.displayText(), | 									   "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.message(), | 									   t_name, t_id, E.code(), E.displayText(), E.message(), | ||||||
| 									   E.what())); | 									   E.what())); | ||||||
| 			} catch (const Poco::Net::InvalidSocketException &E) { | 			} catch (const Poco::Net::InvalidSocketException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::InvalidSocketException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), | ||||||
| 													  t_name, t_id, E.code(), | 						   fmt::format("Poco::Net::InvalidSocketException thr_name={} thr_id={} " | ||||||
| 													  E.displayText(), | 									   "code={} text={} msg={} what={}", | ||||||
| 													  E.message(), | 									   t_name, t_id, E.code(), E.displayText(), E.message(), | ||||||
| 									   E.what())); | 									   E.what())); | ||||||
| 			} catch (const Poco::Net::WebSocketException &E) { | 			} catch (const Poco::Net::WebSocketException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::Net::ConnectionResetException &E) { | 			} catch (const Poco::Net::ConnectionResetException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::ConnectionResetException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), | ||||||
| 													  t_name, t_id, E.code(), | 						   fmt::format("Poco::Net::ConnectionResetException thr_name={} thr_id={} " | ||||||
| 													  E.displayText(), | 									   "code={} text={} msg={} what={}", | ||||||
| 													  E.message(), | 									   t_name, t_id, E.code(), E.displayText(), E.message(), | ||||||
| 									   E.what())); | 									   E.what())); | ||||||
| 			} catch (const Poco::Net::CertificateValidationException &E) { | 			} catch (const Poco::Net::CertificateValidationException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::CertificateValidationException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), | ||||||
| 													  t_name, t_id, E.code(), | 						   fmt::format("Poco::Net::CertificateValidationException thr_name={} " | ||||||
| 													  E.displayText(), | 									   "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.message(), | 									   t_name, t_id, E.code(), E.displayText(), E.message(), | ||||||
| 									   E.what())); | 									   E.what())); | ||||||
| 			} catch (const Poco::Net::SSLConnectionUnexpectedlyClosedException &E) { | 			} catch (const Poco::Net::SSLConnectionUnexpectedlyClosedException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), | ||||||
| 													  t_name, t_id, E.code(), | 						   fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException " | ||||||
| 													  E.displayText(), | 									   "thr_name={} thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.message(), | 									   t_name, t_id, E.code(), E.displayText(), E.message(), | ||||||
| 									   E.what())); | 									   E.what())); | ||||||
| 			} catch (const Poco::Net::SSLContextException &E) { | 			} catch (const Poco::Net::SSLContextException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::Net::SSLException &E) { | 			} catch (const Poco::Net::SSLException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::SSLException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::Net::SSLException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
|  |  | ||||||
| 			} catch (const Poco::Net::InvalidAddressException &E) { | 			} catch (const Poco::Net::InvalidAddressException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::InvalidAddressException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), | ||||||
| 													  t_name, t_id, E.code(), | 						   fmt::format("Poco::Net::InvalidAddressException thr_name={} thr_id={} " | ||||||
| 													  E.displayText(), | 									   "code={} text={} msg={} what={}", | ||||||
| 													  E.message(), | 									   t_name, t_id, E.code(), E.displayText(), E.message(), | ||||||
| 									   E.what())); | 									   E.what())); | ||||||
|  |  | ||||||
| 			} catch (const Poco::Net::NetException &E) { | 			} catch (const Poco::Net::NetException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
|  |  | ||||||
| 			} catch (const Poco::IOException &E) { | 			} catch (const Poco::IOException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::IOException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error( | ||||||
| 													  t_name, t_id, E.code(), | 					App_.logger(), | ||||||
| 													  E.displayText(), | 					fmt::format( | ||||||
| 													  E.message(), | 						"Poco::IOException thr_name={} thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.what())); | 						t_name, t_id, E.code(), E.displayText(), E.message(), E.what())); | ||||||
| 			} catch (const Poco::TimeoutException &E) { | 			} catch (const Poco::TimeoutException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::NoThreadAvailableException &E) { | 			} catch (const Poco::NoThreadAvailableException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::NoThreadAvailableException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), | ||||||
| 													  t_name, t_id, E.code(), | 						   fmt::format("Poco::NoThreadAvailableException thr_name={} thr_id={} " | ||||||
| 													  E.displayText(), | 									   "code={} text={} msg={} what={}", | ||||||
| 													  E.message(), | 									   t_name, t_id, E.code(), E.displayText(), E.message(), | ||||||
| 									   E.what())); | 									   E.what())); | ||||||
| 			} catch (const Poco::OutOfMemoryException &E) { | 			} catch (const Poco::OutOfMemoryException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::BadCastException &E) { | 			} catch (const Poco::BadCastException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::DataException &E) { | 			} catch (const Poco::DataException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::DataException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error( | ||||||
| 													  t_name, t_id, E.code(), | 					App_.logger(), | ||||||
| 													  E.displayText(), | 					fmt::format( | ||||||
| 													  E.message(), | 						"Poco::DataException thr_name={} thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.what())); | 						t_name, t_id, E.code(), E.displayText(), E.message(), E.what())); | ||||||
| 			} catch (const Poco::PoolOverflowException &E) { | 			} catch (const Poco::PoolOverflowException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::SystemException &E) { | 			} catch (const Poco::SystemException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::RuntimeException &E) { | 			} catch (const Poco::RuntimeException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::JSON::JSONTemplateException &E) { | 			} catch (const Poco::JSON::JSONTemplateException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::JSON::JSONTemplateException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), | ||||||
| 													  t_name, t_id, E.code(), | 						   fmt::format("Poco::JSON::JSONTemplateException thr_name={} thr_id={} " | ||||||
| 													  E.displayText(), | 									   "code={} text={} msg={} what={}", | ||||||
| 													  E.message(), | 									   t_name, t_id, E.code(), E.displayText(), E.message(), | ||||||
| 									   E.what())); | 									   E.what())); | ||||||
| 			} catch (const Poco::JSON::JSONException &E) { | 			} catch (const Poco::JSON::JSONException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::ApplicationException &E) { | 			} catch (const Poco::ApplicationException &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} " | ||||||
| 													  t_name, t_id, E.code(), | 													  "thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.displayText(), | 													  t_name, t_id, E.code(), E.displayText(), | ||||||
| 													  E.message(), | 													  E.message(), E.what())); | ||||||
| 													  E.what())); |  | ||||||
| 			} catch (const Poco::Exception &E) { | 			} catch (const Poco::Exception &E) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco::Exception thr_name={} thr_id={} code={} text={} msg={} what={}", | 				poco_error( | ||||||
| 													  t_name, t_id, E.code(), | 					App_.logger(), | ||||||
| 													  E.displayText(), | 					fmt::format( | ||||||
| 													  E.message(), | 						"Poco::Exception thr_name={} thr_id={} code={} text={} msg={} what={}", | ||||||
| 													  E.what())); | 						t_name, t_id, E.code(), E.displayText(), E.message(), E.what())); | ||||||
| 			} catch (...) { | 			} catch (...) { | ||||||
| 				poco_error(App_.logger(), fmt::format("Poco:Generic thr_name={}",t_name, t_id)); | 				poco_error(App_.logger(), fmt::format("Poco:Generic thr_name={}", t_name, t_id)); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void exception(const std::exception & E) override { | 		inline void exception(const std::exception &E) override { | ||||||
| 			if(Poco::Thread::current()!= nullptr) { | 			if (Poco::Thread::current() != nullptr) { | ||||||
| 				t_name = Poco::Thread::current()->getName(); | 				t_name = Poco::Thread::current()->getName(); | ||||||
| 				t_id = Poco::Thread::current()->id(); | 				t_id = Poco::Thread::current()->id(); | ||||||
| 			} else { | 			} else { | ||||||
| 				t_name = "startup_code"; | 				t_name = "startup_code"; | ||||||
| 				t_id = 0; | 				t_id = 0; | ||||||
| 			} | 			} | ||||||
| 			poco_warning(App_.logger(), fmt::format("std::exception in {}: {} thr_id={}", | 			poco_warning(App_.logger(), | ||||||
| 													t_name,E.what(), | 						 fmt::format("std::exception in {}: {} thr_id={}", t_name, E.what(), t_id)); | ||||||
| 													t_id)); |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void exception() override { | 		inline void exception() override { | ||||||
| 			if(Poco::Thread::current()!= nullptr) { | 			if (Poco::Thread::current() != nullptr) { | ||||||
| 				t_name = Poco::Thread::current()->getName(); | 				t_name = Poco::Thread::current()->getName(); | ||||||
| 				t_id = Poco::Thread::current()->id(); | 				t_id = Poco::Thread::current()->id(); | ||||||
| 			} else { | 			} else { | ||||||
| 				t_name = "startup_code"; | 				t_name = "startup_code"; | ||||||
| 				t_id = 0; | 				t_id = 0; | ||||||
| 			} | 			} | ||||||
| 			poco_warning(App_.logger(), fmt::format("generic exception in {} thr_id={}", | 			poco_warning(App_.logger(), | ||||||
| 													t_name, t_id)); | 						 fmt::format("generic exception in {} thr_id={}", t_name, t_id)); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		Poco::Util::Application &App_; | 		Poco::Util::Application &App_; | ||||||
| 		std::string t_name; | 		std::string t_name; | ||||||
| 		int 			t_id=0; | 		int t_id = 0; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -4,8 +4,8 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include <string> |  | ||||||
| #include <map> | #include <map> | ||||||
|  | #include <string> | ||||||
|  |  | ||||||
| #include "Poco/BasicEvent.h" | #include "Poco/BasicEvent.h" | ||||||
| #include "Poco/ExpireLRUCache.h" | #include "Poco/ExpireLRUCache.h" | ||||||
| @@ -13,46 +13,40 @@ | |||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| 	class ConfigurationEntry { | 	class ConfigurationEntry { | ||||||
| 	  public: | 	  public: | ||||||
| 		template <typename T> explicit ConfigurationEntry(T def) : | 		template <typename T> explicit ConfigurationEntry(T def) : Default_(def), Current_(def) {} | ||||||
| 											 Default_(def), |  | ||||||
| 											 Current_(def){ | 		template <typename T> | ||||||
|  | 		explicit ConfigurationEntry(T def, T cur, const std::string &Hint = "") | ||||||
|  | 			: Default_(def), Current_(cur), Hint_(Hint) {} | ||||||
|  |  | ||||||
|  | 		inline ConfigurationEntry() = default; | ||||||
|  | 		inline ~ConfigurationEntry() = default; | ||||||
|  |  | ||||||
|  | 		template <typename T> explicit operator T() const { return std::get<T>(Current_); } | ||||||
|  | 		inline ConfigurationEntry &operator=(const char *v) { | ||||||
|  | 			Current_ = std::string(v); | ||||||
|  | 			return *this; | ||||||
|  | 		} | ||||||
|  | 		template <typename T> ConfigurationEntry &operator=(T v) { | ||||||
|  | 			Current_ = (T)v; | ||||||
|  | 			return *this; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		template <typename T> explicit ConfigurationEntry(T def, T cur, const std::string  &Hint="") : | 		void reset() { Current_ = Default_; } | ||||||
| 																				  Default_(def), |  | ||||||
| 																				  Current_(cur), |  | ||||||
| 																				  Hint_(Hint){ |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		inline ConfigurationEntry()=default; |  | ||||||
| 		inline ~ConfigurationEntry()=default; |  | ||||||
|  |  | ||||||
| 		template <typename T> explicit operator T () const { return std::get<T>(Current_); } |  | ||||||
| 		inline ConfigurationEntry & operator=(const char *v) { Current_ = std::string(v); return *this;} |  | ||||||
| 		template <typename T> ConfigurationEntry &  operator=(T v) { Current_ = (T) v; return *this;} |  | ||||||
|  |  | ||||||
| 		void reset() { |  | ||||||
| 			Current_ = Default_; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::variant<bool,uint64_t,std::string> Default_, Current_; | 		std::variant<bool, uint64_t, std::string> Default_, Current_; | ||||||
| 		std::string Hint_; | 		std::string Hint_; | ||||||
| 	}; | 	}; | ||||||
| 	inline std::string to_string(const ConfigurationEntry &v) { return (std::string) v; } | 	inline std::string to_string(const ConfigurationEntry &v) { return (std::string)v; } | ||||||
|  |  | ||||||
| 	typedef std::map<std::string,ConfigurationEntry>    ConfigurationMap_t; | 	typedef std::map<std::string, ConfigurationEntry> ConfigurationMap_t; | ||||||
|  |  | ||||||
| 	template <typename T> class FIFO { | 	template <typename T> class FIFO { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit FIFO(uint32_t Size) : | 		explicit FIFO(uint32_t Size) : Size_(Size) { Buffer_ = new T[Size_]; } | ||||||
| 									   Size_(Size) { |  | ||||||
| 			Buffer_ = new T [Size_]; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		~FIFO() { | 		~FIFO() { delete[] Buffer_; } | ||||||
| 			delete [] Buffer_; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		mutable Poco::BasicEvent<bool> Writable_; | 		mutable Poco::BasicEvent<bool> Writable_; | ||||||
| 		mutable Poco::BasicEvent<bool> Readable_; | 		mutable Poco::BasicEvent<bool> Readable_; | ||||||
| @@ -84,7 +78,7 @@ namespace OpenWifi { | |||||||
| 					Write_ = 0; | 					Write_ = 0; | ||||||
| 				} | 				} | ||||||
| 				Used_++; | 				Used_++; | ||||||
| 				MaxEverUsed_ = std::max(Used_,MaxEverUsed_); | 				MaxEverUsed_ = std::max(Used_, MaxEverUsed_); | ||||||
| 			} | 			} | ||||||
| 			bool flag = true; | 			bool flag = true; | ||||||
| 			Readable_.notify(this, flag); | 			Readable_.notify(this, flag); | ||||||
| @@ -93,40 +87,32 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 		inline bool isFull() { | 		inline bool isFull() { | ||||||
| 			std::lock_guard M(Mutex_); | 			std::lock_guard M(Mutex_); | ||||||
| 			return Used_==Buffer_->capacity(); | 			return Used_ == Buffer_->capacity(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline auto MaxEverUser() const { return MaxEverUsed_; } | 		inline auto MaxEverUser() const { return MaxEverUsed_; } | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::recursive_mutex Mutex_; | 		std::recursive_mutex Mutex_; | ||||||
| 		uint32_t 				Size_=0; | 		uint32_t Size_ = 0; | ||||||
| 		uint32_t        		Read_=0; | 		uint32_t Read_ = 0; | ||||||
| 		uint32_t        		Write_=0; | 		uint32_t Write_ = 0; | ||||||
| 		uint32_t 				Used_=0; | 		uint32_t Used_ = 0; | ||||||
| 		uint32_t 				MaxEverUsed_=0; | 		uint32_t MaxEverUsed_ = 0; | ||||||
| 		T	  					* Buffer_ = nullptr; | 		T *Buffer_ = nullptr; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	template <class Record, typename KeyType = std::string, int Size=256, int Expiry=60000> class RecordCache { | 	template <class Record, typename KeyType = std::string, int Size = 256, int Expiry = 60000> | ||||||
|  | 	class RecordCache { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit RecordCache( KeyType Record::* Q) : | 		explicit RecordCache(KeyType Record::*Q) : MemberOffset(Q){}; | ||||||
| 												   MemberOffset(Q){ | 		inline auto update(const Record &R) { return Cache_.update(R.*MemberOffset, R); } | ||||||
| 												   }; | 		inline auto get(const KeyType &K) { return Cache_.get(K); } | ||||||
| 		inline auto update(const Record &R) { | 		inline auto remove(const KeyType &K) { return Cache_.remove(K); } | ||||||
| 			return Cache_.update(R.*MemberOffset, R); | 		inline auto remove(const Record &R) { return Cache_.remove(R.*MemberOffset); } | ||||||
| 		} |  | ||||||
| 		inline auto get(const KeyType &K) { |  | ||||||
| 			return Cache_.get(K); |  | ||||||
| 		} |  | ||||||
| 		inline auto remove(const KeyType &K) { |  | ||||||
| 			return Cache_.remove(K); |  | ||||||
| 		} |  | ||||||
| 		inline auto remove(const Record &R) { |  | ||||||
| 			return Cache_.remove(R.*MemberOffset); |  | ||||||
| 		} |  | ||||||
| 	  private: | 	  private: | ||||||
| 		KeyType Record::* MemberOffset; | 		KeyType Record::*MemberOffset; | ||||||
| 		Poco::ExpireLRUCache<KeyType,Record>  Cache_{Size,Expiry}; | 		Poco::ExpireLRUCache<KeyType, Record> Cache_{Size, Expiry}; | ||||||
| 	}; | 	}; | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -2,8 +2,8 @@ | |||||||
| // Created by stephane bourque on 2022-10-25. | // Created by stephane bourque on 2022-10-25. | ||||||
| // | // | ||||||
|  |  | ||||||
| #include "framework/MicroService.h" |  | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  | #include "framework/MicroService.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| 	const std::string &MicroServiceDataDirectory() { return MicroService::instance().DataDir(); } | 	const std::string &MicroServiceDataDirectory() { return MicroService::instance().DataDir(); } | ||||||
| @@ -18,7 +18,8 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	std::string MicroServicePublicEndPoint() { return MicroService::instance().PublicEndPoint(); } | 	std::string MicroServicePublicEndPoint() { return MicroService::instance().PublicEndPoint(); } | ||||||
|  |  | ||||||
|     std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue) { | 	std::string MicroServiceConfigGetString(const std::string &Key, | ||||||
|  | 											const std::string &DefaultValue) { | ||||||
| 		return MicroService::instance().ConfigGetString(Key, DefaultValue); | 		return MicroService::instance().ConfigGetString(Key, DefaultValue); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -46,15 +47,17 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	void MicroServiceReload(const std::string &Type) { MicroService::instance().Reload(Type); } | 	void MicroServiceReload(const std::string &Type) { MicroService::instance().Reload(Type); } | ||||||
|  |  | ||||||
|     const Types::StringVec MicroServiceGetLogLevelNames() { | 	Types::StringVec MicroServiceGetLogLevelNames() { | ||||||
| 		return MicroService::instance().GetLogLevelNames(); | 		return MicroService::instance().GetLogLevelNames(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     const Types::StringVec MicroServiceGetSubSystems() { | 	Types::StringVec MicroServiceGetSubSystems() { | ||||||
| 		return MicroService::instance().GetSubSystems(); | 		return MicroService::instance().GetSubSystems(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     Types::StringPairVec MicroServiceGetLogLevels() { return MicroService::instance().GetLogLevels(); } | 	Types::StringPairVec MicroServiceGetLogLevels() { | ||||||
|  | 		return MicroService::instance().GetLogLevels(); | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) { | 	bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) { | ||||||
| 		return MicroService::instance().SetSubsystemLogLevel(SubSystem, Level); | 		return MicroService::instance().SetSubsystemLogLevel(SubSystem, Level); | ||||||
| @@ -76,7 +79,7 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	std::string MicroServiceGetUIURI() { return MicroService::instance().GetUIURI(); } | 	std::string MicroServiceGetUIURI() { return MicroService::instance().GetUIURI(); } | ||||||
|  |  | ||||||
|     const SubSystemVec MicroServiceGetFullSubSystems() { | 	SubSystemVec MicroServiceGetFullSubSystems() { | ||||||
| 		return MicroService::instance().GetFullSubSystems(); | 		return MicroService::instance().GetFullSubSystems(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -84,22 +87,19 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	std::uint64_t MicroServiceDaemonBusTimer() { return MicroService::instance().DaemonBusTimer(); } | 	std::uint64_t MicroServiceDaemonBusTimer() { return MicroService::instance().DaemonBusTimer(); } | ||||||
|  |  | ||||||
|     std::string MicroServiceMakeSystemEventMessage(const std::string &Type) { | 	std::string MicroServiceMakeSystemEventMessage(const char *Type) { | ||||||
| 		return MicroService::instance().MakeSystemEventMessage(Type); | 		return MicroService::instance().MakeSystemEventMessage(Type); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	Poco::ThreadPool &MicroServiceTimerPool() { return MicroService::instance().TimerPool(); } | 	Poco::ThreadPool &MicroServiceTimerPool() { return MicroService::instance().TimerPool(); } | ||||||
|  |  | ||||||
|     std::string MicroServiceConfigPath(const std::string &Key, | 	std::string MicroServiceConfigPath(const std::string &Key, const std::string &DefaultValue) { | ||||||
|                                        const std::string &DefaultValue) { |  | ||||||
| 		return MicroService::instance().ConfigPath(Key, DefaultValue); | 		return MicroService::instance().ConfigPath(Key, DefaultValue); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     std::string MicroServiceWWWAssetsDir() { | 	std::string MicroServiceWWWAssetsDir() { return MicroService::instance().WWWAssetsDir(); } | ||||||
|         return MicroService::instance().WWWAssetsDir(); |  | ||||||
|     } |  | ||||||
|  |  | ||||||
|     std::uint64_t MicroServiceRandom(std::uint64_t Start,std::uint64_t End) { | 	std::uint64_t MicroServiceRandom(std::uint64_t Start, std::uint64_t End) { | ||||||
| 		return MicroService::instance().Random(Start, End); | 		return MicroService::instance().Random(Start, End); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| @@ -123,4 +123,4 @@ namespace OpenWifi { | |||||||
| 		return MicroService::instance().AllowExternalMicroServices(); | 		return MicroService::instance().AllowExternalMicroServices(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -8,20 +8,20 @@ | |||||||
|  |  | ||||||
| #include "framework/OpenWifiTypes.h" | #include "framework/OpenWifiTypes.h" | ||||||
|  |  | ||||||
| #include "Poco/Net/HTTPServerRequest.h" |  | ||||||
| #include "Poco/JSON/Object.h" | #include "Poco/JSON/Object.h" | ||||||
| #include "Poco/ThreadPool.h" |  | ||||||
| #include "Poco/JWT/Token.h" | #include "Poco/JWT/Token.h" | ||||||
|  | #include "Poco/Net/HTTPServerRequest.h" | ||||||
|  | #include "Poco/ThreadPool.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| 	class SubSystemServer; | 	class SubSystemServer; | ||||||
| 	using SubSystemVec=std::vector<SubSystemServer *>; | 	using SubSystemVec = std::vector<SubSystemServer *>; | ||||||
| 	const std::string & MicroServiceDataDirectory(); | 	const std::string &MicroServiceDataDirectory(); | ||||||
| 	Types::MicroServiceMetaVec MicroServiceGetServices(const std::string & Type); | 	Types::MicroServiceMetaVec MicroServiceGetServices(const std::string &Type); | ||||||
| 	Types::MicroServiceMetaVec MicroServiceGetServices(); | 	Types::MicroServiceMetaVec MicroServiceGetServices(); | ||||||
| 	std::string MicroServicePublicEndPoint(); | 	std::string MicroServicePublicEndPoint(); | ||||||
| 	std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue); | 	std::string MicroServiceConfigGetString(const std::string &Key, | ||||||
|  | 											const std::string &DefaultValue); | ||||||
| 	bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue); | 	bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue); | ||||||
| 	std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue); | 	std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue); | ||||||
| 	std::string MicroServicePrivateEndPoint(); | 	std::string MicroServicePrivateEndPoint(); | ||||||
| @@ -31,8 +31,8 @@ namespace OpenWifi { | |||||||
| 	void MicroServiceLoadConfigurationFile(); | 	void MicroServiceLoadConfigurationFile(); | ||||||
| 	void MicroServiceReload(); | 	void MicroServiceReload(); | ||||||
| 	void MicroServiceReload(const std::string &Type); | 	void MicroServiceReload(const std::string &Type); | ||||||
| 	const Types::StringVec MicroServiceGetLogLevelNames(); | 	Types::StringVec MicroServiceGetLogLevelNames(); | ||||||
| 	const Types::StringVec MicroServiceGetSubSystems(); | 	Types::StringVec MicroServiceGetSubSystems(); | ||||||
| 	Types::StringPairVec MicroServiceGetLogLevels(); | 	Types::StringPairVec MicroServiceGetLogLevels(); | ||||||
| 	bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level); | 	bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level); | ||||||
| 	void MicroServiceGetExtraConfiguration(Poco::JSON::Object &Answer); | 	void MicroServiceGetExtraConfiguration(Poco::JSON::Object &Answer); | ||||||
| @@ -40,18 +40,17 @@ namespace OpenWifi { | |||||||
| 	std::uint64_t MicroServiceUptimeTotalSeconds(); | 	std::uint64_t MicroServiceUptimeTotalSeconds(); | ||||||
| 	std::uint64_t MicroServiceStartTimeEpochTime(); | 	std::uint64_t MicroServiceStartTimeEpochTime(); | ||||||
| 	std::string MicroServiceGetUIURI(); | 	std::string MicroServiceGetUIURI(); | ||||||
| 	const SubSystemVec MicroServiceGetFullSubSystems(); | 	SubSystemVec MicroServiceGetFullSubSystems(); | ||||||
| 	std::string MicroServiceCreateUUID(); | 	std::string MicroServiceCreateUUID(); | ||||||
| 	std::uint64_t MicroServiceDaemonBusTimer(); | 	std::uint64_t MicroServiceDaemonBusTimer(); | ||||||
| 	std::string MicroServiceMakeSystemEventMessage( const std::string & Type ); | 	std::string MicroServiceMakeSystemEventMessage(const char *Type); | ||||||
| 	Poco::ThreadPool & MicroServiceTimerPool(); | 	Poco::ThreadPool &MicroServiceTimerPool(); | ||||||
| 	std::string MicroServiceConfigPath(const std::string &Key, | 	std::string MicroServiceConfigPath(const std::string &Key, const std::string &DefaultValue); | ||||||
| 									   const std::string &DefaultValue); |  | ||||||
| 	std::string MicroServiceWWWAssetsDir(); | 	std::string MicroServiceWWWAssetsDir(); | ||||||
|     std::uint64_t MicroServiceRandom(std::uint64_t Start,std::uint64_t End); | 	std::uint64_t MicroServiceRandom(std::uint64_t Start, std::uint64_t End); | ||||||
| 	std::uint64_t MicroServiceRandom(std::uint64_t Range); | 	std::uint64_t MicroServiceRandom(std::uint64_t Range); | ||||||
| 	std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo); | 	std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo); | ||||||
| 	std::string MicroServiceGetPublicAPIEndPoint(); | 	std::string MicroServiceGetPublicAPIEndPoint(); | ||||||
| 	void MicroServiceDeleteOverrideConfiguration(); | 	void MicroServiceDeleteOverrideConfiguration(); | ||||||
| 	bool AllowExternalMicroServices(); | 	bool AllowExternalMicroServices(); | ||||||
| } | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -10,13 +10,13 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	static const std::string uSERVICE_SECURITY{"owsec"}; | 	static const std::string uSERVICE_SECURITY{"owsec"}; | ||||||
| 	static const std::string uSERVICE_GATEWAY{"owgw"}; | 	static const std::string uSERVICE_GATEWAY{"owgw"}; | ||||||
| 	static const std::string uSERVICE_FIRMWARE{ "owfms"}; | 	static const std::string uSERVICE_FIRMWARE{"owfms"}; | ||||||
| 	static const std::string uSERVICE_TOPOLOGY{ "owtopo"}; | 	static const std::string uSERVICE_TOPOLOGY{"owtopo"}; | ||||||
| 	static const std::string uSERVICE_PROVISIONING{ "owprov"}; | 	static const std::string uSERVICE_PROVISIONING{"owprov"}; | ||||||
| 	static const std::string uSERVICE_OWLS{ "owls"}; | 	static const std::string uSERVICE_OWLS{"owls"}; | ||||||
| 	static const std::string uSERVICE_SUBCRIBER{ "owsub"}; | 	static const std::string uSERVICE_SUBCRIBER{"owsub"}; | ||||||
| 	static const std::string uSERVICE_INSTALLER{ "owinst"}; | 	static const std::string uSERVICE_INSTALLER{"owinst"}; | ||||||
| 	static const std::string uSERVICE_ANALYTICS{ "owanalytics"}; | 	static const std::string uSERVICE_ANALYTICS{"owanalytics"}; | ||||||
| 	static const std::string uSERVICE_OWRRM{ "owrrm"}; | 	static const std::string uSERVICE_OWRRM{"owrrm"}; | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -4,22 +4,23 @@ | |||||||
|  |  | ||||||
| #include "OpenAPIRequests.h" | #include "OpenAPIRequests.h" | ||||||
|  |  | ||||||
|  | #include "Poco/JSON/Parser.h" | ||||||
| #include "Poco/Logger.h" | #include "Poco/Logger.h" | ||||||
| #include "Poco/URI.h" |  | ||||||
| #include "Poco/Net/HTTPRequest.h" | #include "Poco/Net/HTTPRequest.h" | ||||||
| #include "Poco/Net/HTTPSClientSession.h" | #include "Poco/Net/HTTPSClientSession.h" | ||||||
| #include "Poco/JSON/Parser.h" | #include "Poco/URI.h" | ||||||
|  |  | ||||||
| #include "fmt/format.h" | #include "fmt/format.h" | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) { | 	Poco::Net::HTTPServerResponse::HTTPStatus | ||||||
|  | 	OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) { | ||||||
| 		try { | 		try { | ||||||
|  |  | ||||||
| 			auto Services = MicroServiceGetServices(Type_); | 			auto Services = MicroServiceGetServices(Type_); | ||||||
| 		for(auto const &Svc:Services) { | 			for (auto const &Svc : Services) { | ||||||
| 				Poco::URI URI(Svc.PrivateEndPoint); | 				Poco::URI URI(Svc.PrivateEndPoint); | ||||||
|  |  | ||||||
| 				auto Secure = (URI.getScheme() == "https"); | 				auto Secure = (URI.getScheme() == "https"); | ||||||
| @@ -29,13 +30,13 @@ namespace OpenWifi { | |||||||
| 					URI.addQueryParameter(qp.first, qp.second); | 					URI.addQueryParameter(qp.first, qp.second); | ||||||
|  |  | ||||||
| 				std::string Path(URI.getPathAndQuery()); | 				std::string Path(URI.getPathAndQuery()); | ||||||
| 			Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, | 				Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, Path, | ||||||
| 										   Path, |  | ||||||
| 											   Poco::Net::HTTPMessage::HTTP_1_1); | 											   Poco::Net::HTTPMessage::HTTP_1_1); | ||||||
|  |  | ||||||
| 			poco_debug(Poco::Logger::get("REST-CALLER-GET"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) ); | 				poco_debug(Poco::Logger::get("REST-CALLER-GET"), | ||||||
|  | 						   fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_)); | ||||||
|  |  | ||||||
| 			if(BearerToken.empty()) { | 				if (BearerToken.empty()) { | ||||||
| 					Request.add("X-API-KEY", Svc.AccessKey); | 					Request.add("X-API-KEY", Svc.AccessKey); | ||||||
| 					Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | 					Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | ||||||
| 				} else { | 				} else { | ||||||
| @@ -43,7 +44,7 @@ namespace OpenWifi { | |||||||
| 					Request.add("Authorization", "Bearer " + BearerToken); | 					Request.add("Authorization", "Bearer " + BearerToken); | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
| 			if(Secure) { | 				if (Secure) { | ||||||
| 					Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort()); | 					Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort()); | ||||||
| 					Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); | 					Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); | ||||||
|  |  | ||||||
| @@ -71,18 +72,17 @@ namespace OpenWifi { | |||||||
| 					return Response.getStatus(); | 					return Response.getStatus(); | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 	} | 		} catch (const Poco::Exception &E) { | ||||||
| 	catch (const Poco::Exception &E) |  | ||||||
| 	{ |  | ||||||
| 			Poco::Logger::get("REST-CALLER-GET").log(E); | 			Poco::Logger::get("REST-CALLER-GET").log(E); | ||||||
| 		} | 		} | ||||||
| 		return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; | 		return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| 	Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) { | 	Poco::Net::HTTPServerResponse::HTTPStatus | ||||||
|  | 	OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) { | ||||||
| 		try { | 		try { | ||||||
| 			auto Services = MicroServiceGetServices(Type_); | 			auto Services = MicroServiceGetServices(Type_); | ||||||
| 		for(auto const &Svc:Services) { | 			for (auto const &Svc : Services) { | ||||||
| 				Poco::URI URI(Svc.PrivateEndPoint); | 				Poco::URI URI(Svc.PrivateEndPoint); | ||||||
|  |  | ||||||
| 				auto Secure = (URI.getScheme() == "https"); | 				auto Secure = (URI.getScheme() == "https"); | ||||||
| @@ -91,20 +91,20 @@ namespace OpenWifi { | |||||||
| 				for (const auto &qp : QueryData_) | 				for (const auto &qp : QueryData_) | ||||||
| 					URI.addQueryParameter(qp.first, qp.second); | 					URI.addQueryParameter(qp.first, qp.second); | ||||||
|  |  | ||||||
| 			poco_debug(Poco::Logger::get("REST-CALLER-PUT"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) ); | 				poco_debug(Poco::Logger::get("REST-CALLER-PUT"), | ||||||
|  | 						   fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_)); | ||||||
|  |  | ||||||
| 				std::string Path(URI.getPathAndQuery()); | 				std::string Path(URI.getPathAndQuery()); | ||||||
|  |  | ||||||
| 			Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT, | 				Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT, Path, | ||||||
| 										   Path, |  | ||||||
| 											   Poco::Net::HTTPMessage::HTTP_1_1); | 											   Poco::Net::HTTPMessage::HTTP_1_1); | ||||||
| 				std::ostringstream obody; | 				std::ostringstream obody; | ||||||
| 			Poco::JSON::Stringifier::stringify(Body_,obody); | 				Poco::JSON::Stringifier::stringify(Body_, obody); | ||||||
|  |  | ||||||
| 				Request.setContentType("application/json"); | 				Request.setContentType("application/json"); | ||||||
| 				Request.setContentLength(obody.str().size()); | 				Request.setContentLength(obody.str().size()); | ||||||
|  |  | ||||||
| 			if(BearerToken.empty()) { | 				if (BearerToken.empty()) { | ||||||
| 					Request.add("X-API-KEY", Svc.AccessKey); | 					Request.add("X-API-KEY", Svc.AccessKey); | ||||||
| 					Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | 					Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | ||||||
| 				} else { | 				} else { | ||||||
| @@ -112,7 +112,7 @@ namespace OpenWifi { | |||||||
| 					Request.add("Authorization", "Bearer " + BearerToken); | 					Request.add("Authorization", "Bearer " + BearerToken); | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
| 			if(Secure) { | 				if (Secure) { | ||||||
| 					Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort()); | 					Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort()); | ||||||
| 					Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); | 					Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); | ||||||
|  |  | ||||||
| @@ -148,42 +148,41 @@ namespace OpenWifi { | |||||||
| 					return Response.getStatus(); | 					return Response.getStatus(); | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 	} | 		} catch (const Poco::Exception &E) { | ||||||
| 	catch (const Poco::Exception &E) |  | ||||||
| 	{ |  | ||||||
| 			Poco::Logger::get("REST-CALLER-PUT").log(E); | 			Poco::Logger::get("REST-CALLER-PUT").log(E); | ||||||
| 		} | 		} | ||||||
| 		return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; | 		return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| 	Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) { | 	Poco::Net::HTTPServerResponse::HTTPStatus | ||||||
|  | 	OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject, | ||||||
|  | 						   const std::string &BearerToken) { | ||||||
| 		try { | 		try { | ||||||
| 			auto Services = MicroServiceGetServices(Type_); | 			auto Services = MicroServiceGetServices(Type_); | ||||||
|  |  | ||||||
| 		for(auto const &Svc:Services) { | 			for (auto const &Svc : Services) { | ||||||
| 				Poco::URI URI(Svc.PrivateEndPoint); | 				Poco::URI URI(Svc.PrivateEndPoint); | ||||||
|  |  | ||||||
|  |  | ||||||
| 				auto Secure = (URI.getScheme() == "https"); | 				auto Secure = (URI.getScheme() == "https"); | ||||||
|  |  | ||||||
| 				URI.setPath(EndPoint_); | 				URI.setPath(EndPoint_); | ||||||
| 				for (const auto &qp : QueryData_) | 				for (const auto &qp : QueryData_) | ||||||
| 					URI.addQueryParameter(qp.first, qp.second); | 					URI.addQueryParameter(qp.first, qp.second); | ||||||
|  |  | ||||||
| 			poco_debug(Poco::Logger::get("REST-CALLER-POST"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) ); | 				poco_debug(Poco::Logger::get("REST-CALLER-POST"), | ||||||
|  | 						   fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_)); | ||||||
|  |  | ||||||
| 				std::string Path(URI.getPathAndQuery()); | 				std::string Path(URI.getPathAndQuery()); | ||||||
|  |  | ||||||
| 			Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST, | 				Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST, Path, | ||||||
| 										   Path, |  | ||||||
| 											   Poco::Net::HTTPMessage::HTTP_1_1); | 											   Poco::Net::HTTPMessage::HTTP_1_1); | ||||||
| 				std::ostringstream obody; | 				std::ostringstream obody; | ||||||
| 			Poco::JSON::Stringifier::stringify(Body_,obody); | 				Poco::JSON::Stringifier::stringify(Body_, obody); | ||||||
|  |  | ||||||
| 				Request.setContentType("application/json"); | 				Request.setContentType("application/json"); | ||||||
| 				Request.setContentLength(obody.str().size()); | 				Request.setContentLength(obody.str().size()); | ||||||
|  |  | ||||||
| 			if(BearerToken.empty()) { | 				if (BearerToken.empty()) { | ||||||
| 					Request.add("X-API-KEY", Svc.AccessKey); | 					Request.add("X-API-KEY", Svc.AccessKey); | ||||||
| 					Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | 					Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | ||||||
| 				} else { | 				} else { | ||||||
| @@ -191,7 +190,7 @@ namespace OpenWifi { | |||||||
| 					Request.add("Authorization", "Bearer " + BearerToken); | 					Request.add("Authorization", "Bearer " + BearerToken); | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
| 			if(Secure) { | 				if (Secure) { | ||||||
| 					Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort()); | 					Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort()); | ||||||
| 					Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); | 					Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); | ||||||
| 					std::ostream &os = Session.sendRequest(Request); | 					std::ostream &os = Session.sendRequest(Request); | ||||||
| @@ -225,19 +224,18 @@ namespace OpenWifi { | |||||||
| 					return Response.getStatus(); | 					return Response.getStatus(); | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 	} | 		} catch (const Poco::Exception &E) { | ||||||
| 	catch (const Poco::Exception &E) |  | ||||||
| 	{ |  | ||||||
| 			Poco::Logger::get("REST-CALLER-POST").log(E); | 			Poco::Logger::get("REST-CALLER-POST").log(E); | ||||||
| 		} | 		} | ||||||
| 		return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; | 		return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| 	Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestDelete::Do(const std::string & BearerToken) { | 	Poco::Net::HTTPServerResponse::HTTPStatus | ||||||
|  | 	OpenAPIRequestDelete::Do(const std::string &BearerToken) { | ||||||
| 		try { | 		try { | ||||||
| 			auto Services = MicroServiceGetServices(Type_); | 			auto Services = MicroServiceGetServices(Type_); | ||||||
|  |  | ||||||
| 		for(auto const &Svc:Services) { | 			for (auto const &Svc : Services) { | ||||||
| 				Poco::URI URI(Svc.PrivateEndPoint); | 				Poco::URI URI(Svc.PrivateEndPoint); | ||||||
|  |  | ||||||
| 				auto Secure = (URI.getScheme() == "https"); | 				auto Secure = (URI.getScheme() == "https"); | ||||||
| @@ -246,14 +244,14 @@ namespace OpenWifi { | |||||||
| 				for (const auto &qp : QueryData_) | 				for (const auto &qp : QueryData_) | ||||||
| 					URI.addQueryParameter(qp.first, qp.second); | 					URI.addQueryParameter(qp.first, qp.second); | ||||||
|  |  | ||||||
| 			poco_debug(Poco::Logger::get("REST-CALLER-DELETE"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) ); | 				poco_debug(Poco::Logger::get("REST-CALLER-DELETE"), | ||||||
|  | 						   fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_)); | ||||||
|  |  | ||||||
| 				std::string Path(URI.getPathAndQuery()); | 				std::string Path(URI.getPathAndQuery()); | ||||||
|  |  | ||||||
| 			Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_DELETE, | 				Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_DELETE, Path, | ||||||
| 										   Path, |  | ||||||
| 											   Poco::Net::HTTPMessage::HTTP_1_1); | 											   Poco::Net::HTTPMessage::HTTP_1_1); | ||||||
| 			if(BearerToken.empty()) { | 				if (BearerToken.empty()) { | ||||||
| 					Request.add("X-API-KEY", Svc.AccessKey); | 					Request.add("X-API-KEY", Svc.AccessKey); | ||||||
| 					Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | 					Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); | ||||||
| 				} else { | 				} else { | ||||||
| @@ -261,7 +259,7 @@ namespace OpenWifi { | |||||||
| 					Request.add("Authorization", "Bearer " + BearerToken); | 					Request.add("Authorization", "Bearer " + BearerToken); | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
| 			if(Secure) { | 				if (Secure) { | ||||||
| 					Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort()); | 					Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort()); | ||||||
| 					Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); | 					Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); | ||||||
| 					Session.sendRequest(Request); | 					Session.sendRequest(Request); | ||||||
| @@ -277,13 +275,10 @@ namespace OpenWifi { | |||||||
| 					return Response.getStatus(); | 					return Response.getStatus(); | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 	} | 		} catch (const Poco::Exception &E) { | ||||||
| 	catch (const Poco::Exception &E) |  | ||||||
| 	{ |  | ||||||
| 			Poco::Logger::get("REST-CALLER-DELETE").log(E); | 			Poco::Logger::get("REST-CALLER-DELETE").log(E); | ||||||
| 		} | 		} | ||||||
| 		return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; | 		return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; | ||||||
| } | 	} | ||||||
|  |  | ||||||
|  |  | ||||||
| } // namespace OpenWifi | } // namespace OpenWifi | ||||||
| @@ -15,17 +15,14 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	class OpenAPIRequestGet { | 	class OpenAPIRequestGet { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit OpenAPIRequestGet( const std::string & Type, | 		explicit OpenAPIRequestGet(const std::string &Type, const std::string &EndPoint, | ||||||
| 								   const std::string & EndPoint, | 								   const Types::StringPairVec &QueryData, uint64_t msTimeout, | ||||||
| 								   const Types::StringPairVec & QueryData, | 								   const std::string &LoggingStr = "") | ||||||
| 								   uint64_t msTimeout, | 			: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout), | ||||||
|                                    const std::string &LoggingStr=""): |  | ||||||
| 														 Type_(Type), |  | ||||||
| 														 EndPoint_(EndPoint), |  | ||||||
| 														 QueryData_(QueryData), |  | ||||||
| 														 msTimeout_(msTimeout), |  | ||||||
| 			  LoggingStr_(LoggingStr){}; | 			  LoggingStr_(LoggingStr){}; | ||||||
| 		Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = ""); | 		Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, | ||||||
|  | 													 const std::string &BearerToken = ""); | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::string Type_; | 		std::string Type_; | ||||||
| 		std::string EndPoint_; | 		std::string EndPoint_; | ||||||
| @@ -36,20 +33,15 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	class OpenAPIRequestPut { | 	class OpenAPIRequestPut { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit OpenAPIRequestPut( const std::string & Type, | 		explicit OpenAPIRequestPut(const std::string &Type, const std::string &EndPoint, | ||||||
| 								   const std::string & EndPoint, | 								   const Types::StringPairVec &QueryData, | ||||||
| 								   const Types::StringPairVec & QueryData, | 								   const Poco::JSON::Object &Body, uint64_t msTimeout, | ||||||
| 								   const Poco::JSON::Object & Body, | 								   const std::string &LoggingStr = "") | ||||||
| 								   uint64_t msTimeout, | 			: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout), | ||||||
|                                    const std::string &LoggingStr=""): | 			  Body_(Body), LoggingStr_(LoggingStr){}; | ||||||
| 														 Type_(Type), |  | ||||||
| 														 EndPoint_(EndPoint), |  | ||||||
| 														 QueryData_(QueryData), |  | ||||||
| 														 msTimeout_(msTimeout), |  | ||||||
| 														 Body_(Body), |  | ||||||
|                                                          LoggingStr_(LoggingStr){}; |  | ||||||
|  |  | ||||||
| 		Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = ""); | 		Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, | ||||||
|  | 													 const std::string &BearerToken = ""); | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::string Type_; | 		std::string Type_; | ||||||
| @@ -62,19 +54,15 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	class OpenAPIRequestPost { | 	class OpenAPIRequestPost { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit OpenAPIRequestPost( const std::string & Type, | 		explicit OpenAPIRequestPost(const std::string &Type, const std::string &EndPoint, | ||||||
| 									const std::string & EndPoint, | 									const Types::StringPairVec &QueryData, | ||||||
| 									const Types::StringPairVec & QueryData, | 									const Poco::JSON::Object &Body, uint64_t msTimeout, | ||||||
| 									const Poco::JSON::Object & Body, | 									const std::string &LoggingStr = "") | ||||||
| 									uint64_t msTimeout, | 			: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout), | ||||||
|                                    const std::string &LoggingStr=""): | 			  Body_(Body), LoggingStr_(LoggingStr){}; | ||||||
| 														  Type_(Type), | 		Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, | ||||||
| 														  EndPoint_(EndPoint), | 													 const std::string &BearerToken = ""); | ||||||
| 														  QueryData_(QueryData), |  | ||||||
| 														  msTimeout_(msTimeout), |  | ||||||
| 														  Body_(Body), |  | ||||||
|                                                          LoggingStr_(LoggingStr){}; |  | ||||||
| 		Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = ""); |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::string Type_; | 		std::string Type_; | ||||||
| 		std::string EndPoint_; | 		std::string EndPoint_; | ||||||
| @@ -86,17 +74,12 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	class OpenAPIRequestDelete { | 	class OpenAPIRequestDelete { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit OpenAPIRequestDelete(  const std::string & Type, | 		explicit OpenAPIRequestDelete(const std::string &Type, const std::string &EndPoint, | ||||||
| 									    const std::string & EndPoint, | 									  const Types::StringPairVec &QueryData, uint64_t msTimeout, | ||||||
| 									    const Types::StringPairVec & QueryData, | 									  const std::string &LoggingStr = "") | ||||||
| 									    uint64_t msTimeout, | 			: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout), | ||||||
|                                         const std::string &LoggingStr=""): |  | ||||||
|                                             Type_(Type), |  | ||||||
|                                             EndPoint_(EndPoint), |  | ||||||
|                                             QueryData_(QueryData), |  | ||||||
|                                             msTimeout_(msTimeout), |  | ||||||
| 			  LoggingStr_(LoggingStr){}; | 			  LoggingStr_(LoggingStr){}; | ||||||
| 		Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string & BearerToken = ""); | 		Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string &BearerToken = ""); | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::string Type_; | 		std::string Type_; | ||||||
|   | |||||||
| @@ -4,70 +4,71 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
|  | #include <functional> | ||||||
|  | #include <list> | ||||||
| #include <map> | #include <map> | ||||||
|  | #include <queue> | ||||||
|  | #include <set> | ||||||
|  | #include <string> | ||||||
| #include <utility> | #include <utility> | ||||||
| #include <vector> | #include <vector> | ||||||
| #include <functional> |  | ||||||
| #include <string> |  | ||||||
| #include <queue> |  | ||||||
| #include <list> |  | ||||||
| #include <set> |  | ||||||
|  |  | ||||||
| namespace OpenWifi::Types { | namespace OpenWifi::Types { | ||||||
|     typedef std::pair<std::string,std::string>                  StringPair; | 	typedef std::pair<std::string, std::string> StringPair; | ||||||
| 	typedef std::vector<StringPair> StringPairVec; | 	typedef std::vector<StringPair> StringPairVec; | ||||||
| 	typedef std::queue<StringPair> StringPairQueue; | 	typedef std::queue<StringPair> StringPairQueue; | ||||||
| 	typedef std::vector<std::string> StringVec; | 	typedef std::vector<std::string> StringVec; | ||||||
| 	typedef std::set<std::string> StringSet; | 	typedef std::set<std::string> StringSet; | ||||||
|     typedef std::map<std::string,std::set<std::string>>		    StringMapStringSet; | 	typedef std::map<std::string, std::set<std::string>> StringMapStringSet; | ||||||
| 	typedef std::function<void(const std::string &, const std::string &)> TopicNotifyFunction; | 	typedef std::function<void(const std::string &, const std::string &)> TopicNotifyFunction; | ||||||
|     typedef std::list<std::pair<TopicNotifyFunction,int>>       TopicNotifyFunctionList; | 	typedef std::list<std::pair<TopicNotifyFunction, int>> TopicNotifyFunctionList; | ||||||
| 	typedef std::map<std::string, TopicNotifyFunctionList> NotifyTable; | 	typedef std::map<std::string, TopicNotifyFunctionList> NotifyTable; | ||||||
|     typedef std::map<std::string,uint64_t>                      CountedMap; | 	typedef std::map<std::string, uint64_t> CountedMap; | ||||||
| 	typedef std::vector<uint64_t> TagList; | 	typedef std::vector<uint64_t> TagList; | ||||||
| 	typedef std::string UUID_t; | 	typedef std::string UUID_t; | ||||||
| 	typedef std::vector<UUID_t> UUIDvec_t; | 	typedef std::vector<UUID_t> UUIDvec_t; | ||||||
|     typedef std::map<std::string,std::map<uint32_t,uint64_t>>   Counted3DMapSII; | 	typedef std::map<std::string, std::map<uint32_t, uint64_t>> Counted3DMapSII; | ||||||
|  |  | ||||||
| 	struct MicroServiceMeta { | 	struct MicroServiceMeta { | ||||||
| 		uint64_t 		Id=0; | 		uint64_t Id = 0; | ||||||
| 		std::string Type; | 		std::string Type; | ||||||
| 		std::string PrivateEndPoint; | 		std::string PrivateEndPoint; | ||||||
| 		std::string PublicEndPoint; | 		std::string PublicEndPoint; | ||||||
| 		std::string AccessKey; | 		std::string AccessKey; | ||||||
| 		std::string Version; | 		std::string Version; | ||||||
| 		uint64_t 		LastUpdate=0; | 		uint64_t LastUpdate = 0; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	typedef std::map<std::string, MicroServiceMeta> MicroServiceMetaMap; | 	typedef std::map<std::string, MicroServiceMeta> MicroServiceMetaMap; | ||||||
| 	typedef std::vector<MicroServiceMeta> MicroServiceMetaVec; | 	typedef std::vector<MicroServiceMeta> MicroServiceMetaVec; | ||||||
| } | } // namespace OpenWifi::Types | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
|     inline void UpdateCountedMap(OpenWifi::Types::CountedMap &M, const std::string &S, uint64_t Increment=1) { | 	inline void UpdateCountedMap(OpenWifi::Types::CountedMap &M, const std::string &S, | ||||||
|  | 								 uint64_t Increment = 1) { | ||||||
| 		auto it = M.find(S); | 		auto it = M.find(S); | ||||||
|         if(it==M.end()) | 		if (it == M.end()) | ||||||
| 			M[S] = Increment; | 			M[S] = Increment; | ||||||
| 		else | 		else | ||||||
| 			it->second += Increment; | 			it->second += Increment; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S, uint32_t Index, uint64_t Increment=1) { | 	inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S, | ||||||
|  | 								 uint32_t Index, uint64_t Increment = 1) { | ||||||
| 		auto it = M.find(S); | 		auto it = M.find(S); | ||||||
|         if(it==M.end()) { | 		if (it == M.end()) { | ||||||
|             std::map<uint32_t,uint64_t> E; | 			std::map<uint32_t, uint64_t> E; | ||||||
| 			E[Index] = Increment; | 			E[Index] = Increment; | ||||||
| 			M[S] = E; | 			M[S] = E; | ||||||
|         } | 		} else { | ||||||
|         else { | 			std::map<uint32_t, uint64_t> &IndexMap = it->second; | ||||||
|             std::map<uint32_t,uint64_t> & IndexMap = it->second; |  | ||||||
| 			auto it_index = IndexMap.find(Index); | 			auto it_index = IndexMap.find(Index); | ||||||
|             if(it_index == IndexMap.end()) { | 			if (it_index == IndexMap.end()) { | ||||||
| 				IndexMap[Index] = Increment; | 				IndexMap[Index] = Increment; | ||||||
| 			} else { | 			} else { | ||||||
| 				it_index->second += Increment; | 				it_index->second += Increment; | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
| } | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -6,22 +6,23 @@ | |||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	Poco::Net::HTTPRequestHandler *ExtRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &Request) { | 	Poco::Net::HTTPRequestHandler * | ||||||
|  | 	ExtRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &Request) { | ||||||
| 		try { | 		try { | ||||||
| 			Poco::URI uri(Request.getURI()); | 			Poco::URI uri(Request.getURI()); | ||||||
| 			auto TID = NextTransactionId_++; | 			auto TID = NextTransactionId_++; | ||||||
| 			Utils::SetThreadName(fmt::format("x-rest:{}",TID).c_str()); | 			Utils::SetThreadName(fmt::format("x-rest:{}", TID).c_str()); | ||||||
| 			return RESTAPI_ExtServer()->CallServer(uri.getPath(), TID); | 			return RESTAPI_ExtServer()->CallServer(uri.getPath(), TID); | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return nullptr; | 		return nullptr; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	Poco::Net::HTTPRequestHandler *RESTAPI_ExtServer::CallServer(const std::string &Path, uint64_t Id) { | 	Poco::Net::HTTPRequestHandler *RESTAPI_ExtServer::CallServer(const std::string &Path, | ||||||
|  | 																 uint64_t Id) { | ||||||
| 		RESTAPIHandler::BindingMap Bindings; | 		RESTAPIHandler::BindingMap Bindings; | ||||||
| 		Utils::SetThreadName(fmt::format("x-rest:{}",Id).c_str()); | 		Utils::SetThreadName(fmt::format("x-rest:{}", Id).c_str()); | ||||||
| 		return RESTAPI_ExtRouter(Path, Bindings, Logger(), Server_, Id); | 		return RESTAPI_ExtRouter(Path, Bindings, Logger(), Server_, Id); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -6,18 +6,21 @@ | |||||||
|  |  | ||||||
| #include "Poco/Net/HTTPServer.h" | #include "Poco/Net/HTTPServer.h" | ||||||
|  |  | ||||||
| #include "framework/SubSystemServer.h" |  | ||||||
| #include "framework/RESTAPI_Handler.h" | #include "framework/RESTAPI_Handler.h" | ||||||
|  | #include "framework/SubSystemServer.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	Poco::Net::HTTPRequestHandler * RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings, | 	Poco::Net::HTTPRequestHandler * | ||||||
| 													 Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t Id); | 	RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings, | ||||||
|  | 					  Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t Id); | ||||||
|  |  | ||||||
| 	class ExtRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { | 	class ExtRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { | ||||||
| 	  public: | 	  public: | ||||||
| 		ExtRequestHandlerFactory() = default; | 		ExtRequestHandlerFactory() = default; | ||||||
| 		Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override; | 		Poco::Net::HTTPRequestHandler * | ||||||
|  | 		createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override; | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		static inline std::atomic_uint64_t NextTransactionId_ = 1; | 		static inline std::atomic_uint64_t NextTransactionId_ = 1; | ||||||
| 	}; | 	}; | ||||||
| @@ -30,16 +33,21 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline int Start() override { | 		inline int Start() override { | ||||||
| 			poco_information(Logger(),"Starting."); | 			poco_information(Logger(), "Starting."); | ||||||
| 			Server_.InitLogging(); | 			Server_.InitLogging(); | ||||||
|  |  | ||||||
| 			for(const auto & Svr: ConfigServersList_) { | 			for (const auto &Svr : ConfigServersList_) { | ||||||
|  |  | ||||||
| 				if(MicroServiceNoAPISecurity()) { | 				if (MicroServiceNoAPISecurity()) { | ||||||
| 					poco_information(Logger(),fmt::format("Starting: {}:{}. Security has been disabled for APIs.", Svr.Address(), Svr.Port())); | 					poco_information( | ||||||
|  | 						Logger(), | ||||||
|  | 						fmt::format("Starting: {}:{}. Security has been disabled for APIs.", | ||||||
|  | 									Svr.Address(), Svr.Port())); | ||||||
| 				} else { | 				} else { | ||||||
| 					poco_information(Logger(),fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}", Svr.Address(), Svr.Port(), | 					poco_information(Logger(), | ||||||
| 													 Svr.KeyFile(),Svr.CertFile())); | 									 fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}", | ||||||
|  | 												 Svr.Address(), Svr.Port(), Svr.KeyFile(), | ||||||
|  | 												 Svr.CertFile())); | ||||||
| 					Svr.LogCert(Logger()); | 					Svr.LogCert(Logger()); | ||||||
| 					if (!Svr.RootCA().empty()) | 					if (!Svr.RootCA().empty()) | ||||||
| 						Svr.LogCas(Logger()); | 						Svr.LogCas(Logger()); | ||||||
| @@ -50,12 +58,14 @@ namespace OpenWifi { | |||||||
| 				Params->setName("ws:xrest"); | 				Params->setName("ws:xrest"); | ||||||
|  |  | ||||||
| 				std::unique_ptr<Poco::Net::HTTPServer> NewServer; | 				std::unique_ptr<Poco::Net::HTTPServer> NewServer; | ||||||
| 				if(MicroServiceNoAPISecurity()) { | 				if (MicroServiceNoAPISecurity()) { | ||||||
| 					auto Sock{Svr.CreateSocket(Logger())}; | 					auto Sock{Svr.CreateSocket(Logger())}; | ||||||
| 					NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params); | 					NewServer = std::make_unique<Poco::Net::HTTPServer>( | ||||||
|  | 						new ExtRequestHandlerFactory, Pool_, Sock, Params); | ||||||
| 				} else { | 				} else { | ||||||
| 					auto Sock{Svr.CreateSecureSocket(Logger())}; | 					auto Sock{Svr.CreateSecureSocket(Logger())}; | ||||||
| 					NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params); | 					NewServer = std::make_unique<Poco::Net::HTTPServer>( | ||||||
|  | 						new ExtRequestHandlerFactory, Pool_, Sock, Params); | ||||||
| 				}; | 				}; | ||||||
| 				NewServer->start(); | 				NewServer->start(); | ||||||
| 				RESTServers_.push_back(std::move(NewServer)); | 				RESTServers_.push_back(std::move(NewServer)); | ||||||
| @@ -64,36 +74,34 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void Stop() override { | 		inline void Stop() override { | ||||||
| 			poco_information(Logger(),"Stopping..."); | 			poco_information(Logger(), "Stopping..."); | ||||||
| 			for( const auto & svr : RESTServers_ ) | 			for (const auto &svr : RESTServers_) | ||||||
| 				svr->stopAll(true); | 				svr->stopAll(true); | ||||||
| 			Pool_.stopAll(); | 			Pool_.stopAll(); | ||||||
| 			Pool_.joinAll(); | 			Pool_.joinAll(); | ||||||
| 			RESTServers_.clear(); | 			RESTServers_.clear(); | ||||||
| 			poco_information(Logger(),"Stopped..."); | 			poco_information(Logger(), "Stopped..."); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { | 		inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { | ||||||
| 			MicroServiceLoadConfigurationFile(); | 			MicroServiceLoadConfigurationFile(); | ||||||
| 			poco_information(Logger(),"Reinitializing."); | 			poco_information(Logger(), "Reinitializing."); | ||||||
| 			Stop(); | 			Stop(); | ||||||
| 			Start(); | 			Start(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id); | 		Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id); | ||||||
| 		const Poco::ThreadPool & Pool() { return Pool_; } | 		const Poco::ThreadPool &Pool() { return Pool_; } | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_; | 		std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_; | ||||||
| 		Poco::ThreadPool	    Pool_{"x-rest",8,128}; | 		Poco::ThreadPool Pool_{"x-rest", 8, 128}; | ||||||
| 		RESTAPI_GenericServerAccounting Server_; | 		RESTAPI_GenericServerAccounting Server_; | ||||||
|  |  | ||||||
| 		RESTAPI_ExtServer() noexcept: | 		RESTAPI_ExtServer() noexcept | ||||||
| 									   SubSystemServer("RESTAPI_ExtServer", "REST-XSRV", "openwifi.restapi") | 			: SubSystemServer("RESTAPI_ExtServer", "REST-XSRV", "openwifi.restapi") {} | ||||||
| 		{ |  | ||||||
| 		} |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	inline auto RESTAPI_ExtServer() { return RESTAPI_ExtServer::instance(); }; | 	inline auto RESTAPI_ExtServer() { return RESTAPI_ExtServer::instance(); }; | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -4,72 +4,70 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include <string> |  | ||||||
| #include <array> | #include <array> | ||||||
|  | #include <string> | ||||||
|  |  | ||||||
| #include "Poco/StringTokenizer.h" |  | ||||||
| #include "Poco/String.h" |  | ||||||
| #include "Poco/Net/HTTPRequest.h" | #include "Poco/Net/HTTPRequest.h" | ||||||
|  | #include "Poco/String.h" | ||||||
|  | #include "Poco/StringTokenizer.h" | ||||||
|  |  | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| 	class RESTAPI_GenericServerAccounting { | 	class RESTAPI_GenericServerAccounting { | ||||||
| 	  public: | 	  public: | ||||||
|  | 		enum { LOG_GET = 0, LOG_DELETE, LOG_PUT, LOG_POST }; | ||||||
| 		enum { |  | ||||||
| 			LOG_GET=0, |  | ||||||
| 			LOG_DELETE, |  | ||||||
| 			LOG_PUT, |  | ||||||
| 			LOG_POST |  | ||||||
| 		}; |  | ||||||
|  |  | ||||||
| 		void inline SetFlags(bool External, const std::string &Methods) { | 		void inline SetFlags(bool External, const std::string &Methods) { | ||||||
| 			Poco::StringTokenizer   Tokens(Methods,","); | 			Poco::StringTokenizer Tokens(Methods, ","); | ||||||
| 			auto Offset = (External ? 0 : 4); | 			auto Offset = (External ? 0 : 4); | ||||||
| 			for(const auto &i:Tokens) { | 			for (const auto &i : Tokens) { | ||||||
| 				if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_DELETE)==0) | 				if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_DELETE) == 0) | ||||||
| 					LogFlags_[Offset+LOG_DELETE]=true; | 					LogFlags_[Offset + LOG_DELETE] = true; | ||||||
| 				else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_PUT)==0) | 				else if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_PUT) == 0) | ||||||
| 					LogFlags_[Offset+LOG_PUT]=true; | 					LogFlags_[Offset + LOG_PUT] = true; | ||||||
| 				else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_POST)==0) | 				else if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_POST) == 0) | ||||||
| 					LogFlags_[Offset+LOG_POST]=true; | 					LogFlags_[Offset + LOG_POST] = true; | ||||||
| 				else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_GET)==0) | 				else if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_GET) == 0) | ||||||
| 					LogFlags_[Offset+LOG_GET]=true; | 					LogFlags_[Offset + LOG_GET] = true; | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void InitLogging() { | 		inline void InitLogging() { | ||||||
| 			std::string Public = MicroServiceConfigGetString("apilogging.public.methods","PUT,POST,DELETE"); | 			std::string Public = | ||||||
|  | 				MicroServiceConfigGetString("apilogging.public.methods", "PUT,POST,DELETE"); | ||||||
| 			SetFlags(true, Public); | 			SetFlags(true, Public); | ||||||
| 			std::string Private = MicroServiceConfigGetString("apilogging.private.methods","PUT,POST,DELETE"); | 			std::string Private = | ||||||
|  | 				MicroServiceConfigGetString("apilogging.private.methods", "PUT,POST,DELETE"); | ||||||
| 			SetFlags(false, Private); | 			SetFlags(false, Private); | ||||||
|  |  | ||||||
| 			std::string PublicBadTokens = MicroServiceConfigGetString("apilogging.public.badtokens.methods",""); | 			std::string PublicBadTokens = | ||||||
| 			LogBadTokens_[0] = (Poco::icompare(PublicBadTokens,"true")==0); | 				MicroServiceConfigGetString("apilogging.public.badtokens.methods", ""); | ||||||
| 			std::string PrivateBadTokens = MicroServiceConfigGetString("apilogging.private.badtokens.methods",""); | 			LogBadTokens_[0] = (Poco::icompare(PublicBadTokens, "true") == 0); | ||||||
| 			LogBadTokens_[1] = (Poco::icompare(PrivateBadTokens,"true")==0); | 			std::string PrivateBadTokens = | ||||||
|  | 				MicroServiceConfigGetString("apilogging.private.badtokens.methods", ""); | ||||||
|  | 			LogBadTokens_[1] = (Poco::icompare(PrivateBadTokens, "true") == 0); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline bool LogIt(const std::string &Method, bool External) const { | 		[[nodiscard]] inline bool LogIt(const std::string &Method, bool External) const { | ||||||
| 			auto Offset = (External ? 0 : 4); | 			auto Offset = (External ? 0 : 4); | ||||||
| 			if(Method == Poco::Net::HTTPRequest::HTTP_GET) | 			if (Method == Poco::Net::HTTPRequest::HTTP_GET) | ||||||
| 				return LogFlags_[Offset+LOG_GET]; | 				return LogFlags_[Offset + LOG_GET]; | ||||||
| 			if(Method == Poco::Net::HTTPRequest::HTTP_POST) | 			if (Method == Poco::Net::HTTPRequest::HTTP_POST) | ||||||
| 				return LogFlags_[Offset+LOG_POST]; | 				return LogFlags_[Offset + LOG_POST]; | ||||||
| 			if(Method == Poco::Net::HTTPRequest::HTTP_PUT) | 			if (Method == Poco::Net::HTTPRequest::HTTP_PUT) | ||||||
| 				return LogFlags_[Offset+LOG_PUT]; | 				return LogFlags_[Offset + LOG_PUT]; | ||||||
| 			if(Method == Poco::Net::HTTPRequest::HTTP_DELETE) | 			if (Method == Poco::Net::HTTPRequest::HTTP_DELETE) | ||||||
| 				return LogFlags_[Offset+LOG_DELETE]; | 				return LogFlags_[Offset + LOG_DELETE]; | ||||||
| 			return false; | 			return false; | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline bool LogBadTokens(bool External) const { | 		[[nodiscard]] inline bool LogBadTokens(bool External) const { | ||||||
| 			return LogBadTokens_[ (External ? 0 : 1) ]; | 			return LogBadTokens_[(External ? 0 : 1)]; | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::array<bool,8>       LogFlags_{false}; | 		std::array<bool, 8> LogFlags_{false}; | ||||||
| 		std::array<bool,2>       LogBadTokens_{false}; | 		std::array<bool, 2> LogBadTokens_{false}; | ||||||
| 	}; | 	}; | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -4,5 +4,4 @@ | |||||||
|  |  | ||||||
| #include "RESTAPI_Handler.h" | #include "RESTAPI_Handler.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi {} // namespace OpenWifi | ||||||
| } // namespace OpenWifi |  | ||||||
| @@ -4,27 +4,27 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
|  | #include <map> | ||||||
| #include <string> | #include <string> | ||||||
| #include <vector> | #include <vector> | ||||||
| #include <map> |  | ||||||
|  |  | ||||||
| #include "Poco/Net/HTTPRequestHandler.h" | #include "Poco/DeflatingStream.h" | ||||||
| #include "Poco/Logger.h" |  | ||||||
| #include "Poco/JSON/Object.h" | #include "Poco/JSON/Object.h" | ||||||
| #include "Poco/JSON/Parser.h" | #include "Poco/JSON/Parser.h" | ||||||
|  | #include "Poco/Logger.h" | ||||||
|  | #include "Poco/Net/HTTPRequestHandler.h" | ||||||
| #include "Poco/Net/HTTPResponse.h" | #include "Poco/Net/HTTPResponse.h" | ||||||
| #include "Poco/Net/HTTPServerResponse.h" | #include "Poco/Net/HTTPServerResponse.h" | ||||||
| #include "Poco/DeflatingStream.h" |  | ||||||
| #include "Poco/TemporaryFile.h" |  | ||||||
| #include "Poco/Net/OAuth20Credentials.h" | #include "Poco/Net/OAuth20Credentials.h" | ||||||
|  | #include "Poco/TemporaryFile.h" | ||||||
|  |  | ||||||
| #include "framework/ow_constants.h" | #include "RESTObjects/RESTAPI_SecurityObjects.h" | ||||||
|  | #include "framework/AuthClient.h" | ||||||
| #include "framework/RESTAPI_GenericServerAccounting.h" | #include "framework/RESTAPI_GenericServerAccounting.h" | ||||||
| #include "framework/RESTAPI_RateLimiter.h" | #include "framework/RESTAPI_RateLimiter.h" | ||||||
| #include "framework/utils.h" |  | ||||||
| #include "framework/RESTAPI_utils.h" | #include "framework/RESTAPI_utils.h" | ||||||
| #include "framework/AuthClient.h" | #include "framework/ow_constants.h" | ||||||
| #include "RESTObjects/RESTAPI_SecurityObjects.h" | #include "framework/utils.h" | ||||||
|  |  | ||||||
| #if defined(TIP_SECURITY_SERVICE) | #if defined(TIP_SECURITY_SERVICE) | ||||||
| #include "AuthService.h" | #include "AuthService.h" | ||||||
| @@ -37,42 +37,32 @@ namespace OpenWifi { | |||||||
| 	class RESTAPIHandler : public Poco::Net::HTTPRequestHandler { | 	class RESTAPIHandler : public Poco::Net::HTTPRequestHandler { | ||||||
| 	  public: | 	  public: | ||||||
| 		struct QueryBlock { | 		struct QueryBlock { | ||||||
| 			uint64_t StartDate = 0 , EndDate = 0 , Offset = 0 , Limit = 0, LogType = 0 ; | 			uint64_t StartDate = 0, EndDate = 0, Offset = 0, Limit = 0, LogType = 0; | ||||||
| 			std::string SerialNumber, Filter; | 			std::string SerialNumber, Filter; | ||||||
| 			std::vector<std::string> Select; | 			std::vector<std::string> Select; | ||||||
| 			bool Lifetime=false, LastOnly=false, Newest=false, CountOnly=false, AdditionalInfo=false; | 			bool Lifetime = false, LastOnly = false, Newest = false, CountOnly = false, | ||||||
|  | 				 AdditionalInfo = false; | ||||||
| 		}; | 		}; | ||||||
| 		typedef std::map<std::string, std::string> BindingMap; | 		typedef std::map<std::string, std::string> BindingMap; | ||||||
|  |  | ||||||
| 		struct RateLimit { | 		struct RateLimit { | ||||||
| 			int64_t     Interval=1000; | 			int64_t Interval = 1000; | ||||||
| 			int64_t     MaxCalls=10; | 			int64_t MaxCalls = 10; | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
| 		RESTAPIHandler( BindingMap map, | 		RESTAPIHandler(BindingMap map, Poco::Logger &l, std::vector<std::string> Methods, | ||||||
| 					   Poco::Logger &l, | 					   RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, | ||||||
| 					   std::vector<std::string> Methods, | 					   bool Internal, bool AlwaysAuthorize = true, bool RateLimited = false, | ||||||
| 					   RESTAPI_GenericServerAccounting & Server, | 					   const RateLimit &Profile = RateLimit{.Interval = 1000, .MaxCalls = 100}, | ||||||
| 					   uint64_t TransactionId, | 					   bool SubscriberOnly = false) | ||||||
| 					   bool Internal, | 			: Bindings_(std::move(map)), Logger_(l), Methods_(std::move(Methods)), | ||||||
| 					   bool AlwaysAuthorize=true, | 			  Internal_(Internal), RateLimited_(RateLimited), SubOnlyService_(SubscriberOnly), | ||||||
| 					   bool RateLimited=false, | 			  AlwaysAuthorize_(AlwaysAuthorize), Server_(Server), MyRates_(Profile), | ||||||
| 					   const RateLimit & Profile = RateLimit{.Interval=1000,.MaxCalls=100}, | 			  TransactionId_(TransactionId) {} | ||||||
| 					   bool SubscriberOnly=false) |  | ||||||
| 			:   Bindings_(std::move(map)), |  | ||||||
| 			  Logger_(l), |  | ||||||
| 			  Methods_(std::move(Methods)), |  | ||||||
| 			  Internal_(Internal), |  | ||||||
| 			  RateLimited_(RateLimited), |  | ||||||
| 			  SubOnlyService_(SubscriberOnly), |  | ||||||
| 			  AlwaysAuthorize_(AlwaysAuthorize), |  | ||||||
| 			  Server_(Server), |  | ||||||
| 			  MyRates_(Profile), |  | ||||||
| 			  TransactionId_(TransactionId) |  | ||||||
| 		{ |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		inline bool RoleIsAuthorized([[maybe_unused]] const std::string & Path, [[maybe_unused]] const std::string & Method, [[maybe_unused]] std::string & Reason) { | 		inline bool RoleIsAuthorized([[maybe_unused]] const std::string &Path, | ||||||
|  | 									 [[maybe_unused]] const std::string &Method, | ||||||
|  | 									 [[maybe_unused]] std::string &Reason) { | ||||||
| 			return true; | 			return true; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| @@ -85,31 +75,33 @@ namespace OpenWifi { | |||||||
| 				//				std::string th_name = "restsvr_" + std::to_string(TransactionId_); | 				//				std::string th_name = "restsvr_" + std::to_string(TransactionId_); | ||||||
| 				//				Utils::SetThreadName(th_name.c_str()); | 				//				Utils::SetThreadName(th_name.c_str()); | ||||||
|  |  | ||||||
| 				if(Request->getContentLength()>0) { | 				if (Request->getContentLength() > 0) { | ||||||
| 					if(Request->getContentType().find("application/json")!=std::string::npos) { | 					if (Request->getContentType().find("application/json") != std::string::npos) { | ||||||
| 						ParsedBody_ = IncomingParser_.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>(); | 						ParsedBody_ = IncomingParser_.parse(Request->stream()) | ||||||
|  | 										  .extract<Poco::JSON::Object::Ptr>(); | ||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
| 				if(RateLimited_ && RESTAPI_RateLimiter()->IsRateLimited(RequestIn,MyRates_.Interval, MyRates_.MaxCalls)) { | 				if (RateLimited_ && RESTAPI_RateLimiter()->IsRateLimited( | ||||||
|  | 										RequestIn, MyRates_.Interval, MyRates_.MaxCalls)) { | ||||||
| 					return UnAuthorized(RESTAPI::Errors::RATE_LIMIT_EXCEEDED); | 					return UnAuthorized(RESTAPI::Errors::RATE_LIMIT_EXCEEDED); | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
| 				if (!ContinueProcessing()) | 				if (!ContinueProcessing()) | ||||||
| 					return; | 					return; | ||||||
|  |  | ||||||
| 				bool Expired=false, Contacted=false; | 				bool Expired = false, Contacted = false; | ||||||
| 				if (AlwaysAuthorize_ && !IsAuthorized(Expired, Contacted, SubOnlyService_)) { | 				if (AlwaysAuthorize_ && !IsAuthorized(Expired, Contacted, SubOnlyService_)) { | ||||||
| 					if(Expired) | 					if (Expired) | ||||||
| 						return UnAuthorized(RESTAPI::Errors::EXPIRED_TOKEN); | 						return UnAuthorized(RESTAPI::Errors::EXPIRED_TOKEN); | ||||||
| 					if(Contacted) | 					if (Contacted) | ||||||
| 						return UnAuthorized(RESTAPI::Errors::INVALID_TOKEN); | 						return UnAuthorized(RESTAPI::Errors::INVALID_TOKEN); | ||||||
| 					else | 					else | ||||||
| 						return UnAuthorized(RESTAPI::Errors::SECURITY_SERVICE_UNREACHABLE); | 						return UnAuthorized(RESTAPI::Errors::SECURITY_SERVICE_UNREACHABLE); | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
| 				std::string Reason; | 				std::string Reason; | ||||||
| 				if(!RoleIsAuthorized(RequestIn.getURI(), Request->getMethod(), Reason)) { | 				if (!RoleIsAuthorized(RequestIn.getURI(), Request->getMethod(), Reason)) { | ||||||
| 					return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED); | 					return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED); | ||||||
| 				} | 				} | ||||||
|  |  | ||||||
| @@ -130,13 +122,17 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline bool NeedAdditionalInfo() const { return QB_.AdditionalInfo; } | 		[[nodiscard]] inline bool NeedAdditionalInfo() const { return QB_.AdditionalInfo; } | ||||||
| 		[[nodiscard]] inline const std::vector<std::string> & SelectedRecords() const { return QB_.Select; } | 		[[nodiscard]] inline const std::vector<std::string> &SelectedRecords() const { | ||||||
|  | 			return QB_.Select; | ||||||
|  | 		} | ||||||
|  |  | ||||||
| 		inline static bool ParseBindings(const std::string & Request, const std::list<std::string> & EndPoints, BindingMap &bindings) { | 		inline static bool ParseBindings(const std::string &Request, | ||||||
|  | 										 const std::list<std::string> &EndPoints, | ||||||
|  | 										 BindingMap &bindings) { | ||||||
| 			bindings.clear(); | 			bindings.clear(); | ||||||
| 			auto PathItems = Poco::StringTokenizer(Request, "/"); | 			auto PathItems = Poco::StringTokenizer(Request, "/"); | ||||||
|  |  | ||||||
| 			for(const auto &EndPoint:EndPoints) { | 			for (const auto &EndPoint : EndPoints) { | ||||||
| 				auto ParamItems = Poco::StringTokenizer(EndPoint, "/"); | 				auto ParamItems = Poco::StringTokenizer(EndPoint, "/"); | ||||||
| 				if (PathItems.count() != ParamItems.count()) | 				if (PathItems.count() != ParamItems.count()) | ||||||
| 					continue; | 					continue; | ||||||
| @@ -153,7 +149,7 @@ namespace OpenWifi { | |||||||
| 						} | 						} | ||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
| 				if(Matched) | 				if (Matched) | ||||||
| 					return true; | 					return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| @@ -180,44 +176,57 @@ namespace OpenWifi { | |||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline uint64_t GetParameter(const std::string &Name, const uint64_t Default) { | 		[[nodiscard]] inline uint64_t GetParameter(const std::string &Name, | ||||||
| 			auto Hint = std::find_if(Parameters_.begin(),Parameters_.end(),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; }); | 												   const uint64_t Default) { | ||||||
| 			if(Hint==Parameters_.end() || !is_number(Hint->second)) | 			auto Hint = std::find_if( | ||||||
|  | 				Parameters_.begin(), Parameters_.end(), | ||||||
|  | 				[&](const std::pair<std::string, std::string> &S) { return S.first == Name; }); | ||||||
|  | 			if (Hint == Parameters_.end() || !is_number(Hint->second)) | ||||||
| 				return Default; | 				return Default; | ||||||
| 			return std::stoull(Hint->second); | 			return std::stoull(Hint->second); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline bool GetBoolParameter(const std::string &Name, bool Default=false) { | 		[[nodiscard]] inline bool GetBoolParameter(const std::string &Name, bool Default = false) { | ||||||
| 			auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; }); | 			auto Hint = std::find_if( | ||||||
| 			if(Hint==end(Parameters_) || !is_bool(Hint->second)) | 				begin(Parameters_), end(Parameters_), | ||||||
|  | 				[&](const std::pair<std::string, std::string> &S) { return S.first == Name; }); | ||||||
|  | 			if (Hint == end(Parameters_) || !is_bool(Hint->second)) | ||||||
| 				return Default; | 				return Default; | ||||||
| 			return Hint->second=="true"; | 			return Hint->second == "true"; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline std::string GetParameter(const std::string &Name, const std::string &Default="") { | 		[[nodiscard]] inline std::string GetParameter(const std::string &Name, | ||||||
| 			auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; }); | 													  const std::string &Default = "") { | ||||||
| 			if(Hint==end(Parameters_)) | 			auto Hint = std::find_if( | ||||||
|  | 				begin(Parameters_), end(Parameters_), | ||||||
|  | 				[&](const std::pair<std::string, std::string> &S) { return S.first == Name; }); | ||||||
|  | 			if (Hint == end(Parameters_)) | ||||||
| 				return Default; | 				return Default; | ||||||
| 			return Hint->second; | 			return Hint->second; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline bool HasParameter(const std::string &Name, std::string &Value) { | 		[[nodiscard]] inline bool HasParameter(const std::string &Name, std::string &Value) { | ||||||
| 			auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; }); | 			auto Hint = std::find_if( | ||||||
| 			if(Hint==end(Parameters_)) | 				begin(Parameters_), end(Parameters_), | ||||||
|  | 				[&](const std::pair<std::string, std::string> &S) { return S.first == Name; }); | ||||||
|  | 			if (Hint == end(Parameters_)) | ||||||
| 				return false; | 				return false; | ||||||
| 			Value = Hint->second; | 			Value = Hint->second; | ||||||
| 			return true; | 			return true; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline bool HasParameter(const std::string &Name, uint64_t & Value) { | 		[[nodiscard]] inline bool HasParameter(const std::string &Name, uint64_t &Value) { | ||||||
| 			auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; }); | 			auto Hint = std::find_if( | ||||||
| 			if(Hint==end(Parameters_)) | 				begin(Parameters_), end(Parameters_), | ||||||
|  | 				[&](const std::pair<std::string, std::string> &S) { return S.first == Name; }); | ||||||
|  | 			if (Hint == end(Parameters_)) | ||||||
| 				return false; | 				return false; | ||||||
| 			Value = std::stoull(Hint->second); | 			Value = std::stoull(Hint->second); | ||||||
| 			return true; | 			return true; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline const std::string & GetBinding(const std::string &Name, const std::string &Default="") { | 		[[nodiscard]] inline const std::string &GetBinding(const std::string &Name, | ||||||
|  | 														   const std::string &Default = "") { | ||||||
| 			auto E = Bindings_.find(Poco::toLower(Name)); | 			auto E = Bindings_.find(Poco::toLower(Name)); | ||||||
| 			if (E == Bindings_.end()) | 			if (E == Bindings_.end()) | ||||||
| 				return Default; | 				return Default; | ||||||
| @@ -236,68 +245,75 @@ namespace OpenWifi { | |||||||
| 			return Return; | 			return Return; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, Types::UUIDvec_t & Value) { | 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, | ||||||
| 			if(O->has(Field) && O->isArray(Field)) { | 										   const std::string &Field, Types::UUIDvec_t &Value) { | ||||||
|  | 			if (O->has(Field) && O->isArray(Field)) { | ||||||
| 				auto Arr = O->getArray(Field); | 				auto Arr = O->getArray(Field); | ||||||
| 				for(const auto &i:*Arr) | 				for (const auto &i : *Arr) | ||||||
| 					Value.emplace_back(i.toString()); | 					Value.emplace_back(i.toString()); | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, std::string &Value) { | 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, | ||||||
| 			if(O->has(Field)) { | 										   const std::string &Field, std::string &Value) { | ||||||
|  | 			if (O->has(Field)) { | ||||||
| 				Value = O->get(Field).toString(); | 				Value = O->get(Field).toString(); | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, uint64_t &Value) { | 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, | ||||||
| 			if(O->has(Field)) { | 										   const std::string &Field, uint64_t &Value) { | ||||||
|  | 			if (O->has(Field)) { | ||||||
| 				Value = O->get(Field); | 				Value = O->get(Field); | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, bool &Value) { | 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, | ||||||
| 			if(O->has(Field)) { | 										   const std::string &Field, bool &Value) { | ||||||
| 				Value = O->get(Field).toString()=="true"; | 			if (O->has(Field)) { | ||||||
|  | 				Value = O->get(Field).toString() == "true"; | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, double &Value) { | 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, | ||||||
| 			if(O->has(Field)) { | 										   const std::string &Field, double &Value) { | ||||||
| 				Value = (double) O->get(Field); | 			if (O->has(Field)) { | ||||||
|  | 				Value = (double)O->get(Field); | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, Poco::Data::BLOB &Value) { | 		static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, | ||||||
| 			if(O->has(Field)) { | 										   const std::string &Field, Poco::Data::BLOB &Value) { | ||||||
|  | 			if (O->has(Field)) { | ||||||
| 				std::string Content = O->get(Field).toString(); | 				std::string Content = O->get(Field).toString(); | ||||||
| 				auto DecodedBlob = Utils::base64decode(Content); | 				auto DecodedBlob = Utils::base64decode(Content); | ||||||
| 				Value.assignRaw((const unsigned char *)&DecodedBlob[0],DecodedBlob.size()); | 				Value.assignRaw((const unsigned char *)&DecodedBlob[0], DecodedBlob.size()); | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
|  | 		template <typename T> | ||||||
| 		template <typename T> bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, const T &value, T & assignee) { | 		bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, | ||||||
| 			if(O->has(Field)) { | 							 const T &value, T &assignee) { | ||||||
|  | 			if (O->has(Field)) { | ||||||
| 				assignee = value; | 				assignee = value; | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void SetCommonHeaders(bool CloseConnection=false) { | 		inline void SetCommonHeaders(bool CloseConnection = false) { | ||||||
| 			Response->setVersion(Poco::Net::HTTPMessage::HTTP_1_1); | 			Response->setVersion(Poco::Net::HTTPMessage::HTTP_1_1); | ||||||
| 			Response->setChunkedTransferEncoding(true); | 			Response->setChunkedTransferEncoding(true); | ||||||
| 			Response->setContentType("application/json"); | 			Response->setContentType("application/json"); | ||||||
| @@ -308,7 +324,7 @@ namespace OpenWifi { | |||||||
| 				Response->set("Access-Control-Allow-Origin", "*"); | 				Response->set("Access-Control-Allow-Origin", "*"); | ||||||
| 			} | 			} | ||||||
| 			Response->set("Vary", "Origin, Accept-Encoding"); | 			Response->set("Vary", "Origin, Accept-Encoding"); | ||||||
| 			if(CloseConnection) { | 			if (CloseConnection) { | ||||||
| 				Response->set("Connection", "close"); | 				Response->set("Connection", "close"); | ||||||
| 				Response->setKeepAlive(false); | 				Response->setKeepAlive(false); | ||||||
| 			} else { | 			} else { | ||||||
| @@ -329,7 +345,7 @@ namespace OpenWifi { | |||||||
| 			} | 			} | ||||||
| 			Response->set("Access-Control-Allow-Methods", MakeList(Methods_)); | 			Response->set("Access-Control-Allow-Methods", MakeList(Methods_)); | ||||||
| 			auto RequestHeaders = Request->find("Access-Control-Request-Headers"); | 			auto RequestHeaders = Request->find("Access-Control-Request-Headers"); | ||||||
| 			if(RequestHeaders!=Request->end()) | 			if (RequestHeaders != Request->end()) | ||||||
| 				Response->set("Access-Control-Allow-Headers", RequestHeaders->second); | 				Response->set("Access-Control-Allow-Headers", RequestHeaders->second); | ||||||
| 			Response->set("Vary", "Origin, Accept-Encoding"); | 			Response->set("Vary", "Origin, Accept-Encoding"); | ||||||
| 			Response->set("Access-Control-Allow-Credentials", "true"); | 			Response->set("Access-Control-Allow-Credentials", "true"); | ||||||
| @@ -342,21 +358,24 @@ namespace OpenWifi { | |||||||
| 			Response->send(); | 			Response->send(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void PrepareResponse(Poco::Net::HTTPResponse::HTTPStatus Status = Poco::Net::HTTPResponse::HTTP_OK, | 		inline void PrepareResponse( | ||||||
|  | 			Poco::Net::HTTPResponse::HTTPStatus Status = Poco::Net::HTTPResponse::HTTP_OK, | ||||||
| 			bool CloseConnection = false) { | 			bool CloseConnection = false) { | ||||||
| 			Response->setStatus(Status); | 			Response->setStatus(Status); | ||||||
| 			SetCommonHeaders(CloseConnection); | 			SetCommonHeaders(CloseConnection); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void BadRequest(const OpenWifi::RESTAPI::Errors::msg &E, const std::string & Extra="") { | 		inline void BadRequest(const OpenWifi::RESTAPI::Errors::msg &E, | ||||||
|  | 							   const std::string &Extra = "") { | ||||||
| 			PrepareResponse(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); | 			PrepareResponse(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); | ||||||
| 			Poco::JSON::Object ErrorObject; | 			Poco::JSON::Object ErrorObject; | ||||||
| 			ErrorObject.set("ErrorCode",400); | 			ErrorObject.set("ErrorCode", 400); | ||||||
| 			ErrorObject.set("ErrorDetails",Request->getMethod()); | 			ErrorObject.set("ErrorDetails", Request->getMethod()); | ||||||
| 			if(Extra.empty()) | 			if (Extra.empty()) | ||||||
| 				ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ; | 				ErrorObject.set("ErrorDescription", fmt::format("{}: {}", E.err_num, E.err_txt)); | ||||||
| 			else | 			else | ||||||
| 				ErrorObject.set("ErrorDescription",fmt::format("{}: {} ({})",E.err_num,E.err_txt, Extra)) ; | 				ErrorObject.set("ErrorDescription", | ||||||
|  | 								fmt::format("{}: {} ({})", E.err_num, E.err_txt, Extra)); | ||||||
|  |  | ||||||
| 			std::ostream &Answer = Response->send(); | 			std::ostream &Answer = Response->send(); | ||||||
| 			Poco::JSON::Stringifier::stringify(ErrorObject, Answer); | 			Poco::JSON::Stringifier::stringify(ErrorObject, Answer); | ||||||
| @@ -365,9 +384,9 @@ namespace OpenWifi { | |||||||
| 		inline void InternalError(const OpenWifi::RESTAPI::Errors::msg &E) { | 		inline void InternalError(const OpenWifi::RESTAPI::Errors::msg &E) { | ||||||
| 			PrepareResponse(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); | 			PrepareResponse(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); | ||||||
| 			Poco::JSON::Object ErrorObject; | 			Poco::JSON::Object ErrorObject; | ||||||
| 			ErrorObject.set("ErrorCode",500); | 			ErrorObject.set("ErrorCode", 500); | ||||||
| 			ErrorObject.set("ErrorDetails",Request->getMethod()); | 			ErrorObject.set("ErrorDetails", Request->getMethod()); | ||||||
| 			ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ; | 			ErrorObject.set("ErrorDescription", fmt::format("{}: {}", E.err_num, E.err_txt)); | ||||||
| 			std::ostream &Answer = Response->send(); | 			std::ostream &Answer = Response->send(); | ||||||
| 			Poco::JSON::Stringifier::stringify(ErrorObject, Answer); | 			Poco::JSON::Stringifier::stringify(ErrorObject, Answer); | ||||||
| 		} | 		} | ||||||
| @@ -375,9 +394,9 @@ namespace OpenWifi { | |||||||
| 		inline void UnAuthorized(const OpenWifi::RESTAPI::Errors::msg &E) { | 		inline void UnAuthorized(const OpenWifi::RESTAPI::Errors::msg &E) { | ||||||
| 			PrepareResponse(Poco::Net::HTTPResponse::HTTP_FORBIDDEN); | 			PrepareResponse(Poco::Net::HTTPResponse::HTTP_FORBIDDEN); | ||||||
| 			Poco::JSON::Object ErrorObject; | 			Poco::JSON::Object ErrorObject; | ||||||
| 			ErrorObject.set("ErrorCode",E.err_num); | 			ErrorObject.set("ErrorCode", E.err_num); | ||||||
| 			ErrorObject.set("ErrorDetails",Request->getMethod()); | 			ErrorObject.set("ErrorDetails", Request->getMethod()); | ||||||
| 			ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ; | 			ErrorObject.set("ErrorDescription", fmt::format("{}: {}", E.err_num, E.err_txt)); | ||||||
| 			std::ostream &Answer = Response->send(); | 			std::ostream &Answer = Response->send(); | ||||||
| 			Poco::JSON::Stringifier::stringify(ErrorObject, Answer); | 			Poco::JSON::Stringifier::stringify(ErrorObject, Answer); | ||||||
| 		} | 		} | ||||||
| @@ -385,23 +404,22 @@ namespace OpenWifi { | |||||||
| 		inline void NotFound() { | 		inline void NotFound() { | ||||||
| 			PrepareResponse(Poco::Net::HTTPResponse::HTTP_NOT_FOUND); | 			PrepareResponse(Poco::Net::HTTPResponse::HTTP_NOT_FOUND); | ||||||
| 			Poco::JSON::Object ErrorObject; | 			Poco::JSON::Object ErrorObject; | ||||||
| 			ErrorObject.set("ErrorCode",404); | 			ErrorObject.set("ErrorCode", 404); | ||||||
| 			ErrorObject.set("ErrorDetails",Request->getMethod()); | 			ErrorObject.set("ErrorDetails", Request->getMethod()); | ||||||
| 			const auto & E = OpenWifi::RESTAPI::Errors::Error404; | 			const auto &E = OpenWifi::RESTAPI::Errors::Error404; | ||||||
| 			ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ; | 			ErrorObject.set("ErrorDescription", fmt::format("{}: {}", E.err_num, E.err_txt)); | ||||||
| 			std::ostream &Answer = Response->send(); | 			std::ostream &Answer = Response->send(); | ||||||
| 			Poco::JSON::Stringifier::stringify(ErrorObject, Answer); | 			Poco::JSON::Stringifier::stringify(ErrorObject, Answer); | ||||||
| 			poco_debug(Logger_,fmt::format("RES-NOTFOUND: User='{}@{}' Method='{}' Path='{}", | 			poco_debug(Logger_, | ||||||
|                                             Requester(), | 					   fmt::format("RES-NOTFOUND: User='{}@{}' Method='{}' Path='{}", Requester(), | ||||||
| 								   Utils::FormatIPv6(Request->clientAddress().toString()), | 								   Utils::FormatIPv6(Request->clientAddress().toString()), | ||||||
| 											Request->getMethod(), | 								   Request->getMethod(), Request->getURI())); | ||||||
| 											Request->getURI())); |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void OK() { | 		inline void OK() { | ||||||
| 			PrepareResponse(); | 			PrepareResponse(); | ||||||
| 			if(	Request->getMethod()==Poco::Net::HTTPRequest::HTTP_DELETE || | 			if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE || | ||||||
| 				Request->getMethod()==Poco::Net::HTTPRequest::HTTP_OPTIONS) { | 				Request->getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS) { | ||||||
| 				Response->send(); | 				Response->send(); | ||||||
| 			} else { | 			} else { | ||||||
| 				Poco::JSON::Object ErrorObject; | 				Poco::JSON::Object ErrorObject; | ||||||
| @@ -413,85 +431,88 @@ namespace OpenWifi { | |||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void SendCompressedTarFile(const std::string & FileName, const std::string & Content) { | 		inline void SendCompressedTarFile(const std::string &FileName, const std::string &Content) { | ||||||
| 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | ||||||
| 			SetCommonHeaders(); | 			SetCommonHeaders(); | ||||||
| 			Response->set("Content-Type","application/gzip"); | 			Response->set("Content-Type", "application/gzip"); | ||||||
| 			Response->set("Content-Disposition", "attachment; filename=" + FileName ); | 			Response->set("Content-Disposition", "attachment; filename=" + FileName); | ||||||
| 			Response->set("Content-Transfer-Encoding","binary"); | 			Response->set("Content-Transfer-Encoding", "binary"); | ||||||
| 			Response->set("Accept-Ranges", "bytes"); | 			Response->set("Accept-Ranges", "bytes"); | ||||||
| 			Response->set("Cache-Control", "no-store"); | 			Response->set("Cache-Control", "no-store"); | ||||||
| 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | ||||||
| 			Response->setStatus(Poco::Net::HTTPResponse::HTTP_OK); | 			Response->setStatus(Poco::Net::HTTPResponse::HTTP_OK); | ||||||
| 			Response->setContentLength(Content.size()); | 			Response->setContentLength(Content.size()); | ||||||
| 			Response->setChunkedTransferEncoding(true); | 			Response->setChunkedTransferEncoding(true); | ||||||
| 			std::ostream& OutputStream = Response->send(); | 			std::ostream &OutputStream = Response->send(); | ||||||
| 			OutputStream << Content; | 			OutputStream << Content; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void SendFile(Poco::File & File, const std::string & UUID) { | 		inline void SendFile(Poco::File &File, const std::string &UUID) { | ||||||
| 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | ||||||
| 			SetCommonHeaders(); | 			SetCommonHeaders(); | ||||||
| 			Response->set("Content-Type","application/octet-stream"); | 			Response->set("Content-Type", "application/octet-stream"); | ||||||
| 			Response->set("Content-Disposition", "attachment; filename=" + UUID ); | 			Response->set("Content-Disposition", "attachment; filename=" + UUID); | ||||||
| 			Response->set("Content-Transfer-Encoding","binary"); | 			Response->set("Content-Transfer-Encoding", "binary"); | ||||||
| 			Response->set("Accept-Ranges", "bytes"); | 			Response->set("Accept-Ranges", "bytes"); | ||||||
| 			Response->set("Cache-Control", "no-store"); | 			Response->set("Cache-Control", "no-store"); | ||||||
| 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | ||||||
| 			Response->setContentLength(File.getSize()); | 			Response->setContentLength(File.getSize()); | ||||||
| 			Response->sendFile(File.path(),"application/octet-stream"); | 			Response->sendFile(File.path(), "application/octet-stream"); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void SendFile(Poco::File & File) { | 		inline void SendFile(Poco::File &File) { | ||||||
| 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | ||||||
| 			SetCommonHeaders(); | 			SetCommonHeaders(); | ||||||
| 			Poco::Path P(File.path()); | 			Poco::Path P(File.path()); | ||||||
| 			auto MT = Utils::FindMediaType(File); | 			auto MT = Utils::FindMediaType(File); | ||||||
| 			if(MT.Encoding==Utils::BINARY) { | 			if (MT.Encoding == Utils::BINARY) { | ||||||
| 				Response->set("Content-Transfer-Encoding","binary"); | 				Response->set("Content-Transfer-Encoding", "binary"); | ||||||
| 				Response->set("Accept-Ranges", "bytes"); | 				Response->set("Accept-Ranges", "bytes"); | ||||||
| 			} | 			} | ||||||
| 			Response->set("Cache-Control", "no-store"); | 			Response->set("Cache-Control", "no-store"); | ||||||
| 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | ||||||
| 			Response->sendFile(File.path(),MT.ContentType); | 			Response->sendFile(File.path(), MT.ContentType); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void SendFile(Poco::TemporaryFile &TempAvatar, [[maybe_unused]] const std::string &Type, const std::string & Name) { | 		inline void SendFile(Poco::TemporaryFile &TempAvatar, | ||||||
|  | 							 [[maybe_unused]] const std::string &Type, const std::string &Name) { | ||||||
| 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | ||||||
| 			SetCommonHeaders(); | 			SetCommonHeaders(); | ||||||
| 			auto MT = Utils::FindMediaType(Name); | 			auto MT = Utils::FindMediaType(Name); | ||||||
| 			if(MT.Encoding==Utils::BINARY) { | 			if (MT.Encoding == Utils::BINARY) { | ||||||
| 				Response->set("Content-Transfer-Encoding","binary"); | 				Response->set("Content-Transfer-Encoding", "binary"); | ||||||
| 				Response->set("Accept-Ranges", "bytes"); | 				Response->set("Accept-Ranges", "bytes"); | ||||||
| 			} | 			} | ||||||
| 			Response->set("Content-Disposition", "attachment; filename=" + Name ); | 			Response->set("Access-Control-Expose-Headers", "Content-Disposition"); | ||||||
|  | 			Response->set("Content-Disposition", "attachment; filename=" + Name); | ||||||
| 			Response->set("Accept-Ranges", "bytes"); | 			Response->set("Accept-Ranges", "bytes"); | ||||||
| 			Response->set("Cache-Control", "no-store"); | 			Response->set("Cache-Control", "no-store"); | ||||||
| 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | ||||||
| 			Response->setContentLength(TempAvatar.getSize()); | 			Response->setContentLength(TempAvatar.getSize()); | ||||||
| 			Response->sendFile(TempAvatar.path(),MT.ContentType); | 			Response->sendFile(TempAvatar.path(), MT.ContentType); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void SendFileContent(const std::string &Content, const std::string &Type, const std::string & Name) { | 		inline void SendFileContent(const std::string &Content, [[maybe_unused]] const std::string &Type, | ||||||
|  | 									const std::string &Name) { | ||||||
| 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | ||||||
| 			SetCommonHeaders(); | 			SetCommonHeaders(); | ||||||
| 			auto MT = Utils::FindMediaType(Name); | 			auto MT = Utils::FindMediaType(Name); | ||||||
| 			if(MT.Encoding==Utils::BINARY) { | 			if (MT.Encoding == Utils::BINARY) { | ||||||
| 				Response->set("Content-Transfer-Encoding","binary"); | 				Response->set("Content-Transfer-Encoding", "binary"); | ||||||
| 				Response->set("Accept-Ranges", "bytes"); | 				Response->set("Accept-Ranges", "bytes"); | ||||||
| 			} | 			} | ||||||
| 			Response->set("Content-Disposition", "attachment; filename=" + Name ); | 			Response->set("Access-Control-Expose-Headers", "Content-Disposition"); | ||||||
|  | 			Response->set("Content-Disposition", "attachment; filename=" + Name); | ||||||
| 			Response->set("Accept-Ranges", "bytes"); | 			Response->set("Accept-Ranges", "bytes"); | ||||||
| 			Response->set("Cache-Control", "no-store"); | 			Response->set("Cache-Control", "no-store"); | ||||||
| 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | 			Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); | ||||||
| 			Response->setContentLength(Content.size()); | 			Response->setContentLength(Content.size()); | ||||||
| 			Response->setContentType(Type ); | 			Response->setContentType(MT.ContentType); | ||||||
| 			auto & OutputStream = Response->send(); | 			auto &OutputStream = Response->send(); | ||||||
| 			OutputStream << Content ; | 			OutputStream << Content; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void SendHTMLFileBack(Poco::File & File, | 		inline void SendHTMLFileBack(Poco::File &File, const Types::StringPairVec &FormVars) { | ||||||
| 									 const Types::StringPairVec & FormVars) { |  | ||||||
| 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | 			Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); | ||||||
| 			SetCommonHeaders(); | 			SetCommonHeaders(); | ||||||
| 			Response->set("Pragma", "private"); | 			Response->set("Pragma", "private"); | ||||||
| @@ -501,13 +522,14 @@ namespace OpenWifi { | |||||||
| 			Response->setContentLength(FormContent.size()); | 			Response->setContentLength(FormContent.size()); | ||||||
| 			Response->setChunkedTransferEncoding(true); | 			Response->setChunkedTransferEncoding(true); | ||||||
| 			Response->setContentType("text/html"); | 			Response->setContentType("text/html"); | ||||||
| 			std::ostream& ostr = Response->send(); | 			std::ostream &ostr = Response->send(); | ||||||
| 			ostr << FormContent; | 			ostr << FormContent; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void ReturnStatus(Poco::Net::HTTPResponse::HTTPStatus Status, bool CloseConnection=false) { | 		inline void ReturnStatus(Poco::Net::HTTPResponse::HTTPStatus Status, | ||||||
|  | 								 bool CloseConnection = false) { | ||||||
| 			PrepareResponse(Status, CloseConnection); | 			PrepareResponse(Status, CloseConnection); | ||||||
| 			if(Status == Poco::Net::HTTPResponse::HTTP_NO_CONTENT) { | 			if (Status == Poco::Net::HTTPResponse::HTTP_NO_CONTENT) { | ||||||
| 				Response->setContentLength(0); | 				Response->setContentLength(0); | ||||||
| 				Response->erase("Content-Type"); | 				Response->erase("Content-Type"); | ||||||
| 				Response->setChunkedTransferEncoding(false); | 				Response->setChunkedTransferEncoding(false); | ||||||
| @@ -519,7 +541,8 @@ namespace OpenWifi { | |||||||
| 			if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS) { | 			if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS) { | ||||||
| 				ProcessOptions(); | 				ProcessOptions(); | ||||||
| 				return false; | 				return false; | ||||||
| 			} else if (std::find(Methods_.begin(), Methods_.end(), Request->getMethod()) == Methods_.end()) { | 			} else if (std::find(Methods_.begin(), Methods_.end(), Request->getMethod()) == | ||||||
|  | 					   Methods_.end()) { | ||||||
| 				BadRequest(RESTAPI::Errors::UnsupportedHTTPMethod); | 				BadRequest(RESTAPI::Errors::UnsupportedHTTPMethod); | ||||||
| 				return false; | 				return false; | ||||||
| 			} | 			} | ||||||
| @@ -527,19 +550,20 @@ namespace OpenWifi { | |||||||
| 			return true; | 			return true; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline bool IsAuthorized(bool & Expired, bool & Contacted, bool SubOnly = false ); | 		inline bool IsAuthorized(bool &Expired, bool &Contacted, bool SubOnly = false); | ||||||
|  |  | ||||||
| 		inline void ReturnObject(Poco::JSON::Object &Object) { | 		inline void ReturnObject(Poco::JSON::Object &Object) { | ||||||
| 			PrepareResponse(); | 			PrepareResponse(); | ||||||
| 			if(Request!= nullptr) { | 			if (Request != nullptr) { | ||||||
| 				//   can we compress ??? | 				//   can we compress ??? | ||||||
| 				auto AcceptedEncoding = Request->find("Accept-Encoding"); | 				auto AcceptedEncoding = Request->find("Accept-Encoding"); | ||||||
| 				if(AcceptedEncoding!=Request->end()) { | 				if (AcceptedEncoding != Request->end()) { | ||||||
| 					if( AcceptedEncoding->second.find("gzip")!=std::string::npos || | 					if (AcceptedEncoding->second.find("gzip") != std::string::npos || | ||||||
| 						AcceptedEncoding->second.find("compress")!=std::string::npos) { | 						AcceptedEncoding->second.find("compress") != std::string::npos) { | ||||||
| 						Response->set("Content-Encoding", "gzip"); | 						Response->set("Content-Encoding", "gzip"); | ||||||
| 						std::ostream &Answer = Response->send(); | 						std::ostream &Answer = Response->send(); | ||||||
| 						Poco::DeflatingOutputStream deflater(Answer, Poco::DeflatingStreamBuf::STREAM_GZIP); | 						Poco::DeflatingOutputStream deflater(Answer, | ||||||
|  | 															 Poco::DeflatingStreamBuf::STREAM_GZIP); | ||||||
| 						Poco::JSON::Stringifier::stringify(Object, deflater); | 						Poco::JSON::Stringifier::stringify(Object, deflater); | ||||||
| 						deflater.close(); | 						deflater.close(); | ||||||
| 						return; | 						return; | ||||||
| @@ -552,15 +576,16 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 		inline void ReturnRawJSON(const std::string &json_doc) { | 		inline void ReturnRawJSON(const std::string &json_doc) { | ||||||
| 			PrepareResponse(); | 			PrepareResponse(); | ||||||
| 			if(Request!= nullptr) { | 			if (Request != nullptr) { | ||||||
| 				//   can we compress ??? | 				//   can we compress ??? | ||||||
| 				auto AcceptedEncoding = Request->find("Accept-Encoding"); | 				auto AcceptedEncoding = Request->find("Accept-Encoding"); | ||||||
| 				if(AcceptedEncoding!=Request->end()) { | 				if (AcceptedEncoding != Request->end()) { | ||||||
| 					if( AcceptedEncoding->second.find("gzip")!=std::string::npos || | 					if (AcceptedEncoding->second.find("gzip") != std::string::npos || | ||||||
| 						AcceptedEncoding->second.find("compress")!=std::string::npos) { | 						AcceptedEncoding->second.find("compress") != std::string::npos) { | ||||||
| 						Response->set("Content-Encoding", "gzip"); | 						Response->set("Content-Encoding", "gzip"); | ||||||
| 						std::ostream &Answer = Response->send(); | 						std::ostream &Answer = Response->send(); | ||||||
| 						Poco::DeflatingOutputStream deflater(Answer, Poco::DeflatingStreamBuf::STREAM_GZIP); | 						Poco::DeflatingOutputStream deflater(Answer, | ||||||
|  | 															 Poco::DeflatingStreamBuf::STREAM_GZIP); | ||||||
| 						deflater << json_doc; | 						deflater << json_doc; | ||||||
| 						deflater.close(); | 						deflater.close(); | ||||||
| 						return; | 						return; | ||||||
| @@ -578,48 +603,52 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline bool InitQueryBlock() { | 		inline bool InitQueryBlock() { | ||||||
| 			if(QueryBlockInitialized_) | 			if (QueryBlockInitialized_) | ||||||
| 				return true; | 				return true; | ||||||
| 			QueryBlockInitialized_=true; | 			QueryBlockInitialized_ = true; | ||||||
| 			QB_.SerialNumber = GetParameter(RESTAPI::Protocol::SERIALNUMBER, ""); | 			QB_.SerialNumber = GetParameter(RESTAPI::Protocol::SERIALNUMBER, ""); | ||||||
| 			QB_.StartDate = GetParameter(RESTAPI::Protocol::STARTDATE, 0); | 			QB_.StartDate = GetParameter(RESTAPI::Protocol::STARTDATE, 0); | ||||||
| 			QB_.EndDate = GetParameter(RESTAPI::Protocol::ENDDATE, 0); | 			QB_.EndDate = GetParameter(RESTAPI::Protocol::ENDDATE, 0); | ||||||
| 			QB_.Offset = GetParameter(RESTAPI::Protocol::OFFSET, 0); | 			QB_.Offset = GetParameter(RESTAPI::Protocol::OFFSET, 0); | ||||||
| 			QB_.Limit = GetParameter(RESTAPI::Protocol::LIMIT, 100); | 			QB_.Limit = GetParameter(RESTAPI::Protocol::LIMIT, 100); | ||||||
| 			QB_.Filter = GetParameter(RESTAPI::Protocol::FILTER, ""); | 			QB_.Filter = GetParameter(RESTAPI::Protocol::FILTER, ""); | ||||||
| 			QB_.Lifetime = GetBoolParameter(RESTAPI::Protocol::LIFETIME,false); | 			QB_.Lifetime = GetBoolParameter(RESTAPI::Protocol::LIFETIME, false); | ||||||
| 			QB_.LogType = GetParameter(RESTAPI::Protocol::LOGTYPE,0); | 			QB_.LogType = GetParameter(RESTAPI::Protocol::LOGTYPE, 0); | ||||||
| 			QB_.LastOnly = GetBoolParameter(RESTAPI::Protocol::LASTONLY,false); | 			QB_.LastOnly = GetBoolParameter(RESTAPI::Protocol::LASTONLY, false); | ||||||
| 			QB_.Newest = GetBoolParameter(RESTAPI::Protocol::NEWEST,false); | 			QB_.Newest = GetBoolParameter(RESTAPI::Protocol::NEWEST, false); | ||||||
| 			QB_.CountOnly = GetBoolParameter(RESTAPI::Protocol::COUNTONLY,false); | 			QB_.CountOnly = GetBoolParameter(RESTAPI::Protocol::COUNTONLY, false); | ||||||
| 			QB_.AdditionalInfo = GetBoolParameter(RESTAPI::Protocol::WITHEXTENDEDINFO,false); | 			QB_.AdditionalInfo = GetBoolParameter(RESTAPI::Protocol::WITHEXTENDEDINFO, false); | ||||||
|  |  | ||||||
| 			auto RawSelect = GetParameter(RESTAPI::Protocol::SELECT, ""); | 			auto RawSelect = GetParameter(RESTAPI::Protocol::SELECT, ""); | ||||||
|  |  | ||||||
| 			auto Entries = Poco::StringTokenizer(RawSelect,","); | 			auto Entries = Poco::StringTokenizer(RawSelect, ","); | ||||||
| 			for(const auto &i:Entries) { | 			for (const auto &i : Entries) { | ||||||
| 				QB_.Select.emplace_back(i); | 				QB_.Select.emplace_back(i); | ||||||
| 			} | 			} | ||||||
| 			if(QB_.Offset<1) | 			if (QB_.Offset < 1) | ||||||
| 				QB_.Offset=0; | 				QB_.Offset = 0; | ||||||
| 			return true; | 			return true; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline uint64_t Get(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, uint64_t Default=0){ | 		[[nodiscard]] inline uint64_t Get(const char *Parameter, const Poco::JSON::Object::Ptr &Obj, | ||||||
| 			if(Obj->has(Parameter)) | 										  uint64_t Default = 0) { | ||||||
|  | 			if (Obj->has(Parameter)) | ||||||
| 				return Obj->get(Parameter); | 				return Obj->get(Parameter); | ||||||
| 			return Default; | 			return Default; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline std::string GetS(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, const std::string & Default=""){ | 		[[nodiscard]] inline std::string GetS(const char *Parameter, | ||||||
| 			if(Obj->has(Parameter)) | 											  const Poco::JSON::Object::Ptr &Obj, | ||||||
|  | 											  const std::string &Default = "") { | ||||||
|  | 			if (Obj->has(Parameter)) | ||||||
| 				return Obj->get(Parameter).toString(); | 				return Obj->get(Parameter).toString(); | ||||||
| 			return Default; | 			return Default; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline bool GetB(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, bool Default=false){ | 		[[nodiscard]] inline bool GetB(const char *Parameter, const Poco::JSON::Object::Ptr &Obj, | ||||||
| 			if(Obj->has(Parameter)) | 									   bool Default = false) { | ||||||
| 				return Obj->get(Parameter).toString()=="true"; | 			if (Obj->has(Parameter)) | ||||||
|  | 				return Obj->get(Parameter).toString() == "true"; | ||||||
| 			return Default; | 			return Default; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| @@ -627,15 +656,15 @@ namespace OpenWifi { | |||||||
| 			return RESTAPIHandler::Get(RESTAPI::Protocol::WHEN, Obj); | 			return RESTAPIHandler::Get(RESTAPI::Protocol::WHEN, Obj); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		template<typename T> void ReturnObject(const char *Name, const std::vector<T> & Objects) { | 		template <typename T> void ReturnObject(const char *Name, const std::vector<T> &Objects) { | ||||||
| 			Poco::JSON::Object Answer; | 			Poco::JSON::Object Answer; | ||||||
| 			RESTAPI_utils::field_to_json(Answer,Name,Objects); | 			RESTAPI_utils::field_to_json(Answer, Name, Objects); | ||||||
| 			ReturnObject(Answer); | 			ReturnObject(Answer); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		template<typename T> void Object(const char *Name, const std::vector<T> & Objects) { | 		template <typename T> void Object(const char *Name, const std::vector<T> &Objects) { | ||||||
| 			Poco::JSON::Object Answer; | 			Poco::JSON::Object Answer; | ||||||
| 			RESTAPI_utils::field_to_json(Answer,Name,Objects); | 			RESTAPI_utils::field_to_json(Answer, Name, Objects); | ||||||
| 			ReturnObject(Answer); | 			ReturnObject(Answer); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| @@ -645,31 +674,32 @@ namespace OpenWifi { | |||||||
| 			ReturnObject(Answer); | 			ReturnObject(Answer); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		Poco::Logger & Logger() { return Logger_; } | 		Poco::Logger &Logger() { return Logger_; } | ||||||
|  |  | ||||||
| 		virtual void DoGet() = 0 ; | 		virtual void DoGet() = 0; | ||||||
| 		virtual void DoDelete() = 0 ; | 		virtual void DoDelete() = 0; | ||||||
| 		virtual void DoPost() = 0 ; | 		virtual void DoPost() = 0; | ||||||
| 		virtual void DoPut() = 0 ; | 		virtual void DoPut() = 0; | ||||||
|  |  | ||||||
| 		Poco::Net::HTTPServerRequest        *Request= nullptr; | 		Poco::Net::HTTPServerRequest *Request = nullptr; | ||||||
| 		Poco::Net::HTTPServerResponse       *Response= nullptr; | 		Poco::Net::HTTPServerResponse *Response = nullptr; | ||||||
| 		SecurityObjects::UserInfoAndPolicy UserInfo_; | 		SecurityObjects::UserInfoAndPolicy UserInfo_; | ||||||
| 		QueryBlock QB_; | 		QueryBlock QB_; | ||||||
| 		const std::string & Requester() const { return REST_Requester_; } | 		const std::string &Requester() const { return REST_Requester_; } | ||||||
|  |  | ||||||
| 	  protected: | 	  protected: | ||||||
| 		BindingMap Bindings_; | 		BindingMap Bindings_; | ||||||
| 		Poco::URI::QueryParameters Parameters_; | 		Poco::URI::QueryParameters Parameters_; | ||||||
| 		Poco::Logger &Logger_; | 		Poco::Logger &Logger_; | ||||||
| 		std::string SessionToken_; | 		std::string SessionToken_; | ||||||
| 		std::vector<std::string> Methods_; | 		std::vector<std::string> Methods_; | ||||||
| 		bool                        Internal_=false; | 		bool Internal_ = false; | ||||||
| 		bool                        RateLimited_=false; | 		bool RateLimited_ = false; | ||||||
| 		bool                        QueryBlockInitialized_=false; | 		bool QueryBlockInitialized_ = false; | ||||||
| 		bool                        SubOnlyService_=false; | 		bool SubOnlyService_ = false; | ||||||
| 		bool                        AlwaysAuthorize_=true; | 		bool AlwaysAuthorize_ = true; | ||||||
| 		Poco::JSON::Parser IncomingParser_; | 		Poco::JSON::Parser IncomingParser_; | ||||||
| 		RESTAPI_GenericServerAccounting       & Server_; | 		RESTAPI_GenericServerAccounting &Server_; | ||||||
| 		RateLimit MyRates_; | 		RateLimit MyRates_; | ||||||
| 		uint64_t TransactionId_; | 		uint64_t TransactionId_; | ||||||
| 		Poco::JSON::Object::Ptr ParsedBody_; | 		Poco::JSON::Object::Ptr ParsedBody_; | ||||||
| @@ -677,58 +707,64 @@ namespace OpenWifi { | |||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| #ifdef TIP_SECURITY_SERVICE | #ifdef TIP_SECURITY_SERVICE | ||||||
| 	[[nodiscard]] bool AuthServiceIsAuthorized(Poco::Net::HTTPServerRequest & Request,std::string &SessionToken, | 	[[nodiscard]] bool AuthServiceIsAuthorized(Poco::Net::HTTPServerRequest &Request, | ||||||
|                                                SecurityObjects::UserInfoAndPolicy & UInfo, std::uint64_t TID, bool & Expired , bool Sub ); | 											   std::string &SessionToken, | ||||||
|  | 											   SecurityObjects::UserInfoAndPolicy &UInfo, | ||||||
|  | 											   std::uint64_t TID, bool &Expired, bool Sub); | ||||||
| #endif | #endif | ||||||
| 	inline bool RESTAPIHandler::IsAuthorized( bool & Expired , [[maybe_unused]] bool & Contacted , bool Sub ) { | 	inline bool RESTAPIHandler::IsAuthorized(bool &Expired, [[maybe_unused]] bool &Contacted, | ||||||
| 		if(Internal_ && Request->has("X-INTERNAL-NAME")) { | 											 bool Sub) { | ||||||
|  | 		if (Internal_ && Request->has("X-INTERNAL-NAME")) { | ||||||
| 			auto Allowed = MicroServiceIsValidAPIKEY(*Request); | 			auto Allowed = MicroServiceIsValidAPIKEY(*Request); | ||||||
| 			Contacted = true; | 			Contacted = true; | ||||||
| 			if(!Allowed) { | 			if (!Allowed) { | ||||||
| 				if(Server_.LogBadTokens(false)) { | 				if (Server_.LogBadTokens(false)) { | ||||||
| 					poco_debug(Logger_,fmt::format("I-REQ-DENIED({}): TID={} Method={} Path={}", | 					poco_debug(Logger_, | ||||||
|  | 							   fmt::format("I-REQ-DENIED({}): TID={} Method={} Path={}", | ||||||
| 										   Utils::FormatIPv6(Request->clientAddress().toString()), | 										   Utils::FormatIPv6(Request->clientAddress().toString()), | ||||||
| 													TransactionId_, | 										   TransactionId_, Request->getMethod(), | ||||||
| 													Request->getMethod(), Request->getURI())); | 										   Request->getURI())); | ||||||
| 				} | 				} | ||||||
| 			} else { | 			} else { | ||||||
| 				auto Id = Request->get("X-INTERNAL-NAME", "unknown"); | 				auto Id = Request->get("X-INTERNAL-NAME", "unknown"); | ||||||
| 				REST_Requester_ = Id; | 				REST_Requester_ = Id; | ||||||
| 				if(Server_.LogIt(Request->getMethod(),true)) { | 				if (Server_.LogIt(Request->getMethod(), true)) { | ||||||
| 					poco_debug(Logger_,fmt::format("I-REQ-ALLOWED({}): TID={} User='{}' Method={} Path={}", | 					poco_debug(Logger_, | ||||||
|  | 							   fmt::format("I-REQ-ALLOWED({}): TID={} User='{}' Method={} Path={}", | ||||||
| 										   Utils::FormatIPv6(Request->clientAddress().toString()), | 										   Utils::FormatIPv6(Request->clientAddress().toString()), | ||||||
| 													TransactionId_, | 										   TransactionId_, Id, Request->getMethod(), | ||||||
| 													Id, | 										   Request->getURI())); | ||||||
| 													Request->getMethod(), Request->getURI())); |  | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 			return Allowed; | 			return Allowed; | ||||||
| 		} else if(!Internal_ && Request->has("X-API-KEY")) { | 		} else if (!Internal_ && Request->has("X-API-KEY")) { | ||||||
| 			SessionToken_ = Request->get("X-API-KEY", ""); | 			SessionToken_ = Request->get("X-API-KEY", ""); | ||||||
|             bool suspended=false; | 			bool suspended = false; | ||||||
| #ifdef TIP_SECURITY_SERVICE | #ifdef TIP_SECURITY_SERVICE | ||||||
| 			std::uint64_t expiresOn; | 			std::uint64_t expiresOn; | ||||||
|             if (AuthService()->IsValidApiKey(SessionToken_, UserInfo_.webtoken, UserInfo_.userinfo, Expired, expiresOn, suspended)) { | 			if (AuthService()->IsValidApiKey(SessionToken_, UserInfo_.webtoken, UserInfo_.userinfo, | ||||||
|  | 											 Expired, expiresOn, suspended)) { | ||||||
| #else | #else | ||||||
|             if (AuthClient()->IsValidApiKey( SessionToken_, UserInfo_, TransactionId_, Expired, Contacted, suspended)) { | 			if (AuthClient()->IsValidApiKey(SessionToken_, UserInfo_, TransactionId_, Expired, | ||||||
|  | 											Contacted, suspended)) { | ||||||
| #endif | #endif | ||||||
| 				REST_Requester_ = UserInfo_.userinfo.email; | 				REST_Requester_ = UserInfo_.userinfo.email; | ||||||
|                 if(Server_.LogIt(Request->getMethod(),true)) { | 				if (Server_.LogIt(Request->getMethod(), true)) { | ||||||
|                     poco_debug(Logger_,fmt::format("X-REQ-ALLOWED({}): APIKEY-ACCESS TID={} User='{}@{}' Method={} Path={}", | 					poco_debug(Logger_, | ||||||
|                                                    UserInfo_.userinfo.email, | 							   fmt::format("X-REQ-ALLOWED({}): APIKEY-ACCESS TID={} User='{}@{}' " | ||||||
|                                                    TransactionId_, | 										   "Method={} Path={}", | ||||||
|  | 										   UserInfo_.userinfo.email, TransactionId_, | ||||||
| 										   Utils::FormatIPv6(Request->clientAddress().toString()), | 										   Utils::FormatIPv6(Request->clientAddress().toString()), | ||||||
| 										   Request->clientAddress().toString(), | 										   Request->clientAddress().toString(), | ||||||
|                                                    Request->getMethod(), | 										   Request->getMethod(), Request->getURI())); | ||||||
|                                                    Request->getURI())); |  | ||||||
| 				} | 				} | ||||||
| 				return true; | 				return true; | ||||||
| 			} else { | 			} else { | ||||||
|                 if(Server_.LogBadTokens(true)) { | 				if (Server_.LogBadTokens(true)) { | ||||||
|                     poco_debug(Logger_,fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}", | 					poco_debug(Logger_, | ||||||
|  | 							   fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}", | ||||||
| 										   Utils::FormatIPv6(Request->clientAddress().toString()), | 										   Utils::FormatIPv6(Request->clientAddress().toString()), | ||||||
|                                                    TransactionId_, | 										   TransactionId_, Request->getMethod(), | ||||||
|                                                    Request->getMethod(), |  | ||||||
| 										   Request->getURI())); | 										   Request->getURI())); | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| @@ -745,27 +781,29 @@ namespace OpenWifi { | |||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| #ifdef TIP_SECURITY_SERVICE | #ifdef TIP_SECURITY_SERVICE | ||||||
| 			if (AuthServiceIsAuthorized(*Request, SessionToken_, UserInfo_, TransactionId_, Expired, Sub)) { | 			if (AuthServiceIsAuthorized(*Request, SessionToken_, UserInfo_, TransactionId_, Expired, | ||||||
|  | 										Sub)) { | ||||||
| #else | #else | ||||||
| 			if (AuthClient()->IsAuthorized( SessionToken_, UserInfo_, TransactionId_, Expired, Contacted, Sub)) { | 			if (AuthClient()->IsAuthorized(SessionToken_, UserInfo_, TransactionId_, Expired, | ||||||
|  | 										   Contacted, Sub)) { | ||||||
| #endif | #endif | ||||||
| 				REST_Requester_ = UserInfo_.userinfo.email; | 				REST_Requester_ = UserInfo_.userinfo.email; | ||||||
| 				if(Server_.LogIt(Request->getMethod(),true)) { | 				if (Server_.LogIt(Request->getMethod(), true)) { | ||||||
| 					poco_debug(Logger_,fmt::format("X-REQ-ALLOWED({}): TID={} User='{}@{}' Method={} Path={}", | 					poco_debug( | ||||||
| 													UserInfo_.userinfo.email, | 						Logger_, | ||||||
| 													TransactionId_, | 						fmt::format("X-REQ-ALLOWED({}): TID={} User='{}@{}' Method={} Path={}", | ||||||
|  | 									UserInfo_.userinfo.email, TransactionId_, | ||||||
| 									Utils::FormatIPv6(Request->clientAddress().toString()), | 									Utils::FormatIPv6(Request->clientAddress().toString()), | ||||||
| 													Request->clientAddress().toString(), | 									Request->clientAddress().toString(), Request->getMethod(), | ||||||
| 													Request->getMethod(), |  | ||||||
| 									Request->getURI())); | 									Request->getURI())); | ||||||
| 				} | 				} | ||||||
| 				return true; | 				return true; | ||||||
| 			} else { | 			} else { | ||||||
| 				if(Server_.LogBadTokens(true)) { | 				if (Server_.LogBadTokens(true)) { | ||||||
| 					poco_debug(Logger_,fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}", | 					poco_debug(Logger_, | ||||||
|  | 							   fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}", | ||||||
| 										   Utils::FormatIPv6(Request->clientAddress().toString()), | 										   Utils::FormatIPv6(Request->clientAddress().toString()), | ||||||
| 													TransactionId_, | 										   TransactionId_, Request->getMethod(), | ||||||
| 													Request->getMethod(), |  | ||||||
| 										   Request->getURI())); | 										   Request->getURI())); | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| @@ -775,52 +813,58 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	class RESTAPI_UnknownRequestHandler : public RESTAPIHandler { | 	class RESTAPI_UnknownRequestHandler : public RESTAPIHandler { | ||||||
| 	  public: | 	  public: | ||||||
| 		RESTAPI_UnknownRequestHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) | 		RESTAPI_UnknownRequestHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, | ||||||
| 			: RESTAPIHandler(bindings, L, std::vector<std::string>{}, Server, TransactionId, Internal) {} | 									  RESTAPI_GenericServerAccounting &Server, | ||||||
| 		inline void DoGet() override {}; | 									  uint64_t TransactionId, bool Internal) | ||||||
| 		inline void DoPost() override {}; | 			: RESTAPIHandler(bindings, L, std::vector<std::string>{}, Server, TransactionId, | ||||||
| 		inline void DoPut() override {}; | 							 Internal) {} | ||||||
| 		inline void DoDelete() override {}; | 		inline void DoGet() override{}; | ||||||
|  | 		inline void DoPost() override{}; | ||||||
|  | 		inline void DoPut() override{}; | ||||||
|  | 		inline void DoDelete() override{}; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	template<class T> | 	template <class T> | ||||||
| 		constexpr auto test_has_PathName_method(T*) | 	constexpr auto test_has_PathName_method(T *) -> decltype(T::PathName(), std::true_type{}) { | ||||||
| 			-> decltype(  T::PathName() , std::true_type{} ) |  | ||||||
| 		{ |  | ||||||
| 		return std::true_type{}; | 		return std::true_type{}; | ||||||
| 	} | 	} | ||||||
| 		constexpr auto test_has_PathName_method(...) -> std::false_type | 	constexpr auto test_has_PathName_method(...) -> std::false_type { return std::false_type{}; } | ||||||
| 		{ |  | ||||||
| 			return std::false_type{}; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 	template<typename T, typename... Args> | 	template <typename T, typename... Args> | ||||||
| 		RESTAPIHandler * RESTAPI_Router(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings, | 	RESTAPIHandler *RESTAPI_Router(const std::string &RequestedPath, | ||||||
| 									   Poco::Logger & Logger, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId) { | 								   RESTAPIHandler::BindingMap &Bindings, Poco::Logger &Logger, | ||||||
| 			static_assert(test_has_PathName_method((T*)nullptr), "Class must have a static PathName() method."); | 								   RESTAPI_GenericServerAccounting &Server, | ||||||
| 			if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) { | 								   uint64_t TransactionId) { | ||||||
|  | 		static_assert(test_has_PathName_method((T *)nullptr), | ||||||
|  | 					  "Class must have a static PathName() method."); | ||||||
|  | 		if (RESTAPIHandler::ParseBindings(RequestedPath, T::PathName(), Bindings)) { | ||||||
| 			return new T(Bindings, Logger, Server, TransactionId, false); | 			return new T(Bindings, Logger, Server, TransactionId, false); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		if constexpr (sizeof...(Args) == 0) { | 		if constexpr (sizeof...(Args) == 0) { | ||||||
| 				return new RESTAPI_UnknownRequestHandler(Bindings,Logger, Server, TransactionId, false); | 			return new RESTAPI_UnknownRequestHandler(Bindings, Logger, Server, TransactionId, | ||||||
|  | 													 false); | ||||||
| 		} else { | 		} else { | ||||||
| 			return RESTAPI_Router<Args...>(RequestedPath, Bindings, Logger, Server, TransactionId); | 			return RESTAPI_Router<Args...>(RequestedPath, Bindings, Logger, Server, TransactionId); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<typename T, typename... Args> | 	template <typename T, typename... Args> | ||||||
| 		RESTAPIHandler * RESTAPI_Router_I(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings, | 	RESTAPIHandler *RESTAPI_Router_I(const std::string &RequestedPath, | ||||||
| 										 Poco::Logger & Logger, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId) { | 									 RESTAPIHandler::BindingMap &Bindings, Poco::Logger &Logger, | ||||||
| 			static_assert(test_has_PathName_method((T*)nullptr), "Class must have a static PathName() method."); | 									 RESTAPI_GenericServerAccounting &Server, | ||||||
| 			if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) { | 									 uint64_t TransactionId) { | ||||||
| 				return new T(Bindings, Logger, Server, TransactionId, true ); | 		static_assert(test_has_PathName_method((T *)nullptr), | ||||||
|  | 					  "Class must have a static PathName() method."); | ||||||
|  | 		if (RESTAPIHandler::ParseBindings(RequestedPath, T::PathName(), Bindings)) { | ||||||
|  | 			return new T(Bindings, Logger, Server, TransactionId, true); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		if constexpr (sizeof...(Args) == 0) { | 		if constexpr (sizeof...(Args) == 0) { | ||||||
| 				return new RESTAPI_UnknownRequestHandler(Bindings,Logger, Server, TransactionId, true); | 			return new RESTAPI_UnknownRequestHandler(Bindings, Logger, Server, TransactionId, true); | ||||||
| 		} else { | 		} else { | ||||||
| 				return RESTAPI_Router_I<Args...>(RequestedPath, Bindings, Logger, Server, TransactionId); | 			return RESTAPI_Router_I<Args...>(RequestedPath, Bindings, Logger, Server, | ||||||
|  | 											 TransactionId); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|   | |||||||
| @@ -6,18 +6,21 @@ | |||||||
|  |  | ||||||
| #include "Poco/Net/HTTPServer.h" | #include "Poco/Net/HTTPServer.h" | ||||||
|  |  | ||||||
| #include "framework/SubSystemServer.h" |  | ||||||
| #include "framework/RESTAPI_Handler.h" | #include "framework/RESTAPI_Handler.h" | ||||||
|  | #include "framework/SubSystemServer.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	Poco::Net::HTTPRequestHandler * RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings, | 	Poco::Net::HTTPRequestHandler * | ||||||
| 													 Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t Id); | 	RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings, | ||||||
|  | 					  Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t Id); | ||||||
|  |  | ||||||
| 	class IntRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { | 	class IntRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { | ||||||
| 	  public: | 	  public: | ||||||
| 		inline IntRequestHandlerFactory() = default; | 		inline IntRequestHandlerFactory() = default; | ||||||
| 		Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override; | 		Poco::Net::HTTPRequestHandler * | ||||||
|  | 		createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override; | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		static inline std::atomic_uint64_t NextTransactionId_ = 1; | 		static inline std::atomic_uint64_t NextTransactionId_ = 1; | ||||||
| 	}; | 	}; | ||||||
| @@ -30,16 +33,21 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline int Start() override { | 		inline int Start() override { | ||||||
| 			poco_information(Logger(),"Starting."); | 			poco_information(Logger(), "Starting."); | ||||||
| 			Server_.InitLogging(); | 			Server_.InitLogging(); | ||||||
|  |  | ||||||
| 			for(const auto & Svr: ConfigServersList_) { | 			for (const auto &Svr : ConfigServersList_) { | ||||||
|  |  | ||||||
| 				if(MicroServiceNoAPISecurity()) { | 				if (MicroServiceNoAPISecurity()) { | ||||||
| 					poco_information(Logger(),fmt::format("Starting: {}:{}. Security has been disabled for APIs.", Svr.Address(), Svr.Port())); | 					poco_information( | ||||||
|  | 						Logger(), | ||||||
|  | 						fmt::format("Starting: {}:{}. Security has been disabled for APIs.", | ||||||
|  | 									Svr.Address(), Svr.Port())); | ||||||
| 				} else { | 				} else { | ||||||
| 					poco_information(Logger(),fmt::format("Starting: {}:{}. Keyfile:{} CertFile: {}", Svr.Address(), Svr.Port(), | 					poco_information(Logger(), | ||||||
| 													 Svr.KeyFile(),Svr.CertFile())); | 									 fmt::format("Starting: {}:{}. Keyfile:{} CertFile: {}", | ||||||
|  | 												 Svr.Address(), Svr.Port(), Svr.KeyFile(), | ||||||
|  | 												 Svr.CertFile())); | ||||||
| 					Svr.LogCert(Logger()); | 					Svr.LogCert(Logger()); | ||||||
| 					if (!Svr.RootCA().empty()) | 					if (!Svr.RootCA().empty()) | ||||||
| 						Svr.LogCas(Logger()); | 						Svr.LogCas(Logger()); | ||||||
| @@ -50,12 +58,14 @@ namespace OpenWifi { | |||||||
| 				Params->setName("ws:irest"); | 				Params->setName("ws:irest"); | ||||||
|  |  | ||||||
| 				std::unique_ptr<Poco::Net::HTTPServer> NewServer; | 				std::unique_ptr<Poco::Net::HTTPServer> NewServer; | ||||||
| 				if(MicroServiceNoAPISecurity()) { | 				if (MicroServiceNoAPISecurity()) { | ||||||
| 					auto Sock{Svr.CreateSocket(Logger())}; | 					auto Sock{Svr.CreateSocket(Logger())}; | ||||||
| 					NewServer = std::make_unique<Poco::Net::HTTPServer>(new IntRequestHandlerFactory, Pool_, Sock, Params); | 					NewServer = std::make_unique<Poco::Net::HTTPServer>( | ||||||
|  | 						new IntRequestHandlerFactory, Pool_, Sock, Params); | ||||||
| 				} else { | 				} else { | ||||||
| 					auto Sock{Svr.CreateSecureSocket(Logger())}; | 					auto Sock{Svr.CreateSecureSocket(Logger())}; | ||||||
| 					NewServer = std::make_unique<Poco::Net::HTTPServer>(new IntRequestHandlerFactory, Pool_, Sock, Params); | 					NewServer = std::make_unique<Poco::Net::HTTPServer>( | ||||||
|  | 						new IntRequestHandlerFactory, Pool_, Sock, Params); | ||||||
| 				}; | 				}; | ||||||
| 				NewServer->start(); | 				NewServer->start(); | ||||||
| 				RESTServers_.push_back(std::move(NewServer)); | 				RESTServers_.push_back(std::move(NewServer)); | ||||||
| @@ -65,40 +75,37 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void Stop() override { | 		inline void Stop() override { | ||||||
| 			poco_information(Logger(),"Stopping..."); | 			poco_information(Logger(), "Stopping..."); | ||||||
| 			for( const auto & svr : RESTServers_ ) | 			for (const auto &svr : RESTServers_) | ||||||
| 				svr->stopAll(true); | 				svr->stopAll(true); | ||||||
| 			Pool_.stopAll(); | 			Pool_.stopAll(); | ||||||
| 			Pool_.joinAll(); | 			Pool_.joinAll(); | ||||||
| 			poco_information(Logger(),"Stopped..."); | 			poco_information(Logger(), "Stopped..."); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { | 		inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { | ||||||
| 			MicroServiceLoadConfigurationFile(); | 			MicroServiceLoadConfigurationFile(); | ||||||
| 			poco_information(Logger(),"Reinitializing."); | 			poco_information(Logger(), "Reinitializing."); | ||||||
| 			Stop(); | 			Stop(); | ||||||
| 			Start(); | 			Start(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id) { | 		inline Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id) { | ||||||
| 			RESTAPIHandler::BindingMap Bindings; | 			RESTAPIHandler::BindingMap Bindings; | ||||||
| 			Utils::SetThreadName(fmt::format("i-rest:{}",Id).c_str()); | 			Utils::SetThreadName(fmt::format("i-rest:{}", Id).c_str()); | ||||||
| 			return RESTAPI_IntRouter(Path, Bindings, Logger(), Server_, Id); | 			return RESTAPI_IntRouter(Path, Bindings, Logger(), Server_, Id); | ||||||
| 		} | 		} | ||||||
| 		const Poco::ThreadPool & Pool() { return Pool_; } | 		const Poco::ThreadPool &Pool() { return Pool_; } | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_; | 		std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_; | ||||||
| 		Poco::ThreadPool	    Pool_{"i-rest",4,64}; | 		Poco::ThreadPool Pool_{"i-rest", 4, 64}; | ||||||
| 		RESTAPI_GenericServerAccounting Server_; | 		RESTAPI_GenericServerAccounting Server_; | ||||||
|  |  | ||||||
| 		RESTAPI_IntServer() noexcept: | 		RESTAPI_IntServer() noexcept | ||||||
| 									   SubSystemServer("RESTAPI_IntServer", "REST-ISRV", "openwifi.internal.restapi") | 			: SubSystemServer("RESTAPI_IntServer", "REST-ISRV", "openwifi.internal.restapi") {} | ||||||
| 		{ |  | ||||||
| 		} |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	inline auto RESTAPI_IntServer() { return RESTAPI_IntServer::instance(); }; | 	inline auto RESTAPI_IntServer() { return RESTAPI_IntServer::instance(); }; | ||||||
|  |  | ||||||
|  |  | ||||||
| } // namespace OpenWifi | } // namespace OpenWifi | ||||||
|  |  | ||||||
|   | |||||||
| @@ -4,29 +4,26 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include <string> |  | ||||||
| #include "Poco/Net/PartHandler.h" |  | ||||||
| #include "Poco/Net/MessageHeader.h" |  | ||||||
| #include "Poco/CountingStream.h" | #include "Poco/CountingStream.h" | ||||||
|  | #include "Poco/Net/MessageHeader.h" | ||||||
|  | #include "Poco/Net/PartHandler.h" | ||||||
| #include "Poco/NullStream.h" | #include "Poco/NullStream.h" | ||||||
| #include "Poco/StreamCopier.h" | #include "Poco/StreamCopier.h" | ||||||
|  | #include <string> | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| 	class RESTAPI_PartHandler: public Poco::Net::PartHandler { | 	class RESTAPI_PartHandler : public Poco::Net::PartHandler { | ||||||
| 	  public: | 	  public: | ||||||
| 		RESTAPI_PartHandler(): | 		RESTAPI_PartHandler() : _length(0) {} | ||||||
| 								_length(0) |  | ||||||
| 		{ |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		inline void handlePart(const Poco::Net::MessageHeader& header, std::istream& stream) override | 		inline void handlePart(const Poco::Net::MessageHeader &header, | ||||||
| 		{ | 							   std::istream &stream) override { | ||||||
| 			_type = header.get("Content-Type", "(unspecified)"); | 			_type = header.get("Content-Type", "(unspecified)"); | ||||||
| 			if (header.has("Content-Disposition")) | 			if (header.has("Content-Disposition")) { | ||||||
| 			{ |  | ||||||
| 				std::string disp; | 				std::string disp; | ||||||
| 				Poco::Net::NameValueCollection params; | 				Poco::Net::NameValueCollection params; | ||||||
| 				Poco::Net::MessageHeader::splitParameters(header["Content-Disposition"], disp, params); | 				Poco::Net::MessageHeader::splitParameters(header["Content-Disposition"], disp, | ||||||
|  | 														  params); | ||||||
| 				_name = params.get("name", "(unnamed)"); | 				_name = params.get("name", "(unnamed)"); | ||||||
| 				_fileName = params.get("filename", "(unnamed)"); | 				_fileName = params.get("filename", "(unnamed)"); | ||||||
| 			} | 			} | ||||||
| @@ -37,25 +34,13 @@ namespace OpenWifi { | |||||||
| 			_length = (int)istr.chars(); | 			_length = (int)istr.chars(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline int length() const | 		[[nodiscard]] inline int length() const { return _length; } | ||||||
| 		{ |  | ||||||
| 			return _length; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline const std::string& name() const | 		[[nodiscard]] inline const std::string &name() const { return _name; } | ||||||
| 		{ |  | ||||||
| 			return _name; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline const std::string& fileName() const | 		[[nodiscard]] inline const std::string &fileName() const { return _fileName; } | ||||||
| 		{ |  | ||||||
| 			return _fileName; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		[[nodiscard]] inline const std::string& contentType() const | 		[[nodiscard]] inline const std::string &contentType() const { return _type; } | ||||||
| 		{ |  | ||||||
| 			return _type; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		int _length; | 		int _length; | ||||||
| @@ -63,4 +48,4 @@ namespace OpenWifi { | |||||||
| 		std::string _name; | 		std::string _name; | ||||||
| 		std::string _fileName; | 		std::string _fileName; | ||||||
| 	}; | 	}; | ||||||
| } | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -6,9 +6,9 @@ | |||||||
|  |  | ||||||
| #include "framework/SubSystemServer.h" | #include "framework/SubSystemServer.h" | ||||||
|  |  | ||||||
| #include "Poco/URI.h" |  | ||||||
| #include "Poco/Net/HTTPServerRequest.h" |  | ||||||
| #include "Poco/ExpireLRUCache.h" | #include "Poco/ExpireLRUCache.h" | ||||||
|  | #include "Poco/Net/HTTPServerRequest.h" | ||||||
|  | #include "Poco/URI.h" | ||||||
|  |  | ||||||
| #include "fmt/format.h" | #include "fmt/format.h" | ||||||
|  |  | ||||||
| @@ -16,10 +16,9 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	class RESTAPI_RateLimiter : public SubSystemServer { | 	class RESTAPI_RateLimiter : public SubSystemServer { | ||||||
| 	  public: | 	  public: | ||||||
|  |  | ||||||
| 		struct ClientCacheEntry { | 		struct ClientCacheEntry { | ||||||
| 			int64_t  Start=0; | 			int64_t Start = 0; | ||||||
| 			int      Count=0; | 			int Count = 0; | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
| 		static auto instance() { | 		static auto instance() { | ||||||
| @@ -27,49 +26,47 @@ namespace OpenWifi { | |||||||
| 			return instance_; | 			return instance_; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline int Start() final { return 0;}; | 		inline int Start() final { return 0; }; | ||||||
| 		inline void Stop() final { }; | 		inline void Stop() final{}; | ||||||
|  |  | ||||||
| 		inline bool IsRateLimited(const Poco::Net::HTTPServerRequest &R, int64_t Period, int64_t MaxCalls) { | 		inline bool IsRateLimited(const Poco::Net::HTTPServerRequest &R, int64_t Period, | ||||||
|  | 								  int64_t MaxCalls) { | ||||||
| 			Poco::URI uri(R.getURI()); | 			Poco::URI uri(R.getURI()); | ||||||
| 			auto H = str_hash(uri.getPath() + R.clientAddress().host().toString()); | 			auto H = str_hash(uri.getPath() + R.clientAddress().host().toString()); | ||||||
| 			auto E = Cache_.get(H); | 			auto E = Cache_.get(H); | ||||||
| 			auto Now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); | 			auto Now = std::chrono::duration_cast<std::chrono::milliseconds>( | ||||||
| 			if(E.isNull()) { | 						   std::chrono::system_clock::now().time_since_epoch()) | ||||||
| 				Cache_.add(H,ClientCacheEntry{.Start=Now, .Count=1}); | 						   .count(); | ||||||
|  | 			if (E.isNull()) { | ||||||
|  | 				Cache_.add(H, ClientCacheEntry{.Start = Now, .Count = 1}); | ||||||
| 				return false; | 				return false; | ||||||
| 			} | 			} | ||||||
| 			if((Now-E->Start)<Period) { | 			if ((Now - E->Start) < Period) { | ||||||
| 				E->Count++; | 				E->Count++; | ||||||
| 				Cache_.update(H,E); | 				Cache_.update(H, E); | ||||||
| 				if(E->Count > MaxCalls) { | 				if (E->Count > MaxCalls) { | ||||||
| 					poco_warning(Logger(),fmt::format("RATE-LIMIT-EXCEEDED: from '{}'", R.clientAddress().toString())); | 					poco_warning(Logger(), fmt::format("RATE-LIMIT-EXCEEDED: from '{}'", | ||||||
|  | 													   R.clientAddress().toString())); | ||||||
| 					return true; | 					return true; | ||||||
| 				} | 				} | ||||||
| 				return false; | 				return false; | ||||||
| 			} | 			} | ||||||
| 			E->Start = Now; | 			E->Start = Now; | ||||||
| 			E->Count = 1; | 			E->Count = 1; | ||||||
| 			Cache_.update(H,E); | 			Cache_.update(H, E); | ||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void Clear() { | 		inline void Clear() { Cache_.clear(); } | ||||||
| 			Cache_.clear(); |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		Poco::ExpireLRUCache<uint64_t,ClientCacheEntry>      Cache_{2048}; | 		Poco::ExpireLRUCache<uint64_t, ClientCacheEntry> Cache_{2048}; | ||||||
| 		std::hash<std::string> str_hash; | 		std::hash<std::string> str_hash; | ||||||
|  |  | ||||||
| 		RESTAPI_RateLimiter() noexcept: | 		RESTAPI_RateLimiter() noexcept | ||||||
| 										 SubSystemServer("RateLimiter", "RATE-LIMITER", "rate.limiter") | 			: SubSystemServer("RateLimiter", "RATE-LIMITER", "rate.limiter") {} | ||||||
| 		{ |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	inline auto RESTAPI_RateLimiter() { return RESTAPI_RateLimiter::instance(); } | 	inline auto RESTAPI_RateLimiter() { return RESTAPI_RateLimiter::instance(); } | ||||||
|  |  | ||||||
|  | } // namespace OpenWifi | ||||||
| } |  | ||||||
| @@ -14,19 +14,19 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	class RESTAPI_system_command : public RESTAPIHandler { | 	class RESTAPI_system_command : public RESTAPIHandler { | ||||||
| 	  public: | 	  public: | ||||||
| 		RESTAPI_system_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) | 		RESTAPI_system_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, | ||||||
|  | 							   RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, | ||||||
|  | 							   bool Internal) | ||||||
| 			: RESTAPIHandler(bindings, L, | 			: RESTAPIHandler(bindings, L, | ||||||
| 							 std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST, | 							 std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST, | ||||||
| 													  Poco::Net::HTTPRequest::HTTP_GET, | 													  Poco::Net::HTTPRequest::HTTP_GET, | ||||||
| 													  Poco::Net::HTTPRequest::HTTP_OPTIONS}, | 													  Poco::Net::HTTPRequest::HTTP_OPTIONS}, | ||||||
| 							 Server, | 							 Server, TransactionId, Internal) {} | ||||||
| 							 TransactionId, | 		static auto PathName() { return std::list<std::string>{"/api/v1/system"}; } | ||||||
| 							 Internal) {} |  | ||||||
| 		static auto PathName() { return std::list<std::string>{"/api/v1/system"};} |  | ||||||
|  |  | ||||||
| 		inline void DoGet() { | 		inline void DoGet() { | ||||||
| 			std::string Arg; | 			std::string Arg; | ||||||
| 			if(HasParameter("command",Arg) && Arg=="info") { | 			if (HasParameter("command", Arg) && Arg == "info") { | ||||||
| 				Poco::JSON::Object Answer; | 				Poco::JSON::Object Answer; | ||||||
| 				Answer.set(RESTAPI::Protocol::VERSION, MicroServiceVersion()); | 				Answer.set(RESTAPI::Protocol::VERSION, MicroServiceVersion()); | ||||||
| 				Answer.set(RESTAPI::Protocol::UPTIME, MicroServiceUptimeTotalSeconds()); | 				Answer.set(RESTAPI::Protocol::UPTIME, MicroServiceUptimeTotalSeconds()); | ||||||
| @@ -40,15 +40,15 @@ namespace OpenWifi { | |||||||
| 				auto SubSystems = MicroServiceGetFullSubSystems(); | 				auto SubSystems = MicroServiceGetFullSubSystems(); | ||||||
| 				std::set<std::string> CertNames; | 				std::set<std::string> CertNames; | ||||||
|  |  | ||||||
| 				for(const auto &i:SubSystems) { | 				for (const auto &i : SubSystems) { | ||||||
| 					auto Hosts=i->HostSize(); | 					auto Hosts = i->HostSize(); | ||||||
| 					for(uint64_t j=0;j<Hosts;++j) { | 					for (uint64_t j = 0; j < Hosts; ++j) { | ||||||
| 						auto CertFileName = i->Host(j).CertFile(); | 						auto CertFileName = i->Host(j).CertFile(); | ||||||
| 						if(!CertFileName.empty()) { | 						if (!CertFileName.empty()) { | ||||||
| 							Poco::File F1(CertFileName); | 							Poco::File F1(CertFileName); | ||||||
| 							if(F1.exists()) { | 							if (F1.exists()) { | ||||||
| 								auto InsertResult = CertNames.insert(CertFileName); | 								auto InsertResult = CertNames.insert(CertFileName); | ||||||
| 								if(InsertResult.second) { | 								if (InsertResult.second) { | ||||||
| 									Poco::JSON::Object Inner; | 									Poco::JSON::Object Inner; | ||||||
| 									Poco::Path F(CertFileName); | 									Poco::Path F(CertFileName); | ||||||
| 									Inner.set("filename", F.getFileName()); | 									Inner.set("filename", F.getFileName()); | ||||||
| @@ -64,7 +64,7 @@ namespace OpenWifi { | |||||||
| 				Answer.set("certificates", Certificates); | 				Answer.set("certificates", Certificates); | ||||||
| 				return ReturnObject(Answer); | 				return ReturnObject(Answer); | ||||||
| 			} | 			} | ||||||
| 			if(GetBoolParameter("extraConfiguration")) { | 			if (GetBoolParameter("extraConfiguration")) { | ||||||
| 				Poco::JSON::Object Answer; | 				Poco::JSON::Object Answer; | ||||||
| 				MicroServiceGetExtraConfiguration(Answer); | 				MicroServiceGetExtraConfiguration(Answer); | ||||||
| 				return ReturnObject(Answer); | 				return ReturnObject(Answer); | ||||||
| @@ -73,7 +73,7 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		inline void DoPost() final { | 		inline void DoPost() final { | ||||||
| 			const auto & Obj = ParsedBody_; | 			const auto &Obj = ParsedBody_; | ||||||
| 			if (Obj->has(RESTAPI::Protocol::COMMAND)) { | 			if (Obj->has(RESTAPI::Protocol::COMMAND)) { | ||||||
| 				auto Command = Poco::toLower(Obj->get(RESTAPI::Protocol::COMMAND).toString()); | 				auto Command = Poco::toLower(Obj->get(RESTAPI::Protocol::COMMAND).toString()); | ||||||
| 				if (Command == RESTAPI::Protocol::SETLOGLEVEL) { | 				if (Command == RESTAPI::Protocol::SETLOGLEVEL) { | ||||||
| @@ -88,7 +88,8 @@ namespace OpenWifi { | |||||||
| 								auto Name = GetS(RESTAPI::Protocol::TAG, InnerObj); | 								auto Name = GetS(RESTAPI::Protocol::TAG, InnerObj); | ||||||
| 								auto Value = GetS(RESTAPI::Protocol::VALUE, InnerObj); | 								auto Value = GetS(RESTAPI::Protocol::VALUE, InnerObj); | ||||||
| 								MicroServiceSetSubsystemLogLevel(Name, Value); | 								MicroServiceSetSubsystemLogLevel(Name, Value); | ||||||
| 								poco_information(Logger_, | 								poco_information( | ||||||
|  | 									Logger_, | ||||||
| 									fmt::format("Setting log level for {} at {}", Name, Value)); | 									fmt::format("Setting log level for {} at {}", Name, Value)); | ||||||
| 							} | 							} | ||||||
| 						} | 						} | ||||||
| @@ -131,10 +132,10 @@ namespace OpenWifi { | |||||||
| 						std::vector<std::string> Names; | 						std::vector<std::string> Names; | ||||||
| 						for (const auto &i : *SubSystems) | 						for (const auto &i : *SubSystems) | ||||||
| 							Names.push_back(i.toString()); | 							Names.push_back(i.toString()); | ||||||
| 						std::thread	ReloadThread([Names](){ | 						std::thread ReloadThread([Names]() { | ||||||
| 							std::this_thread::sleep_for(10000ms); | 							std::this_thread::sleep_for(10000ms); | ||||||
| 							for(const auto &i:Names) { | 							for (const auto &i : Names) { | ||||||
| 								if(i=="daemon") | 								if (i == "daemon") | ||||||
| 									MicroServiceReload(); | 									MicroServiceReload(); | ||||||
| 								else | 								else | ||||||
| 									MicroServiceReload(i); | 									MicroServiceReload(i); | ||||||
| @@ -150,8 +151,8 @@ namespace OpenWifi { | |||||||
| 			BadRequest(RESTAPI::Errors::MissingOrInvalidParameters); | 			BadRequest(RESTAPI::Errors::MissingOrInvalidParameters); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		void DoPut() final {}; | 		void DoPut() final{}; | ||||||
| 		void DoDelete() final {}; | 		void DoDelete() final{}; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -4,42 +4,44 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include "framework/RESTAPI_Handler.h" |  | ||||||
| #include "Poco/Net/WebSocket.h" | #include "Poco/Net/WebSocket.h" | ||||||
|  | #include "framework/RESTAPI_Handler.h" | ||||||
|  |  | ||||||
| #include "framework/UI_WebSocketClientServer.h" |  | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  | #include "framework/UI_WebSocketClientServer.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
| 	class RESTAPI_webSocketServer : public RESTAPIHandler { | 	class RESTAPI_webSocketServer : public RESTAPIHandler { | ||||||
| 	  public: | 	  public: | ||||||
| 		inline RESTAPI_webSocketServer(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, bool Internal) | 		inline RESTAPI_webSocketServer(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, | ||||||
|  | 									   RESTAPI_GenericServerAccounting &Server, | ||||||
|  | 									   uint64_t TransactionId, bool Internal) | ||||||
| 			: RESTAPIHandler(bindings, L, | 			: RESTAPIHandler(bindings, L, | ||||||
| 							 std::vector<std::string>{	Poco::Net::HTTPRequest::HTTP_GET, | 							 std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET, | ||||||
| 													  Poco::Net::HTTPRequest::HTTP_OPTIONS}, | 													  Poco::Net::HTTPRequest::HTTP_OPTIONS}, | ||||||
| 							 Server, TransactionId, Internal,false) {} | 							 Server, TransactionId, Internal, false) {} | ||||||
| 		static auto PathName() { return std::list<std::string>{"/api/v1/ws"};} | 		static auto PathName() { return std::list<std::string>{"/api/v1/ws"}; } | ||||||
| 		void DoGet() final { | 		void DoGet() final { | ||||||
| 				try | 			try { | ||||||
| 				{ | 				if (Request->find("Upgrade") != Request->end() && | ||||||
| 					if(Request->find("Upgrade") != Request->end() && Poco::icompare((*Request)["Upgrade"], "websocket") == 0) { | 					Poco::icompare((*Request)["Upgrade"], "websocket") == 0) { | ||||||
| 						try | 					try { | ||||||
| 						{ |  | ||||||
| 						Poco::Net::WebSocket WS(*Request, *Response); | 						Poco::Net::WebSocket WS(*Request, *Response); | ||||||
| 						auto Id = MicroServiceCreateUUID(); | 						auto Id = MicroServiceCreateUUID(); | ||||||
| 							UI_WebSocketClientServer()->NewClient(WS,Id,UserInfo_.userinfo.email, TransactionId_); | 						UI_WebSocketClientServer()->NewClient(WS, Id, UserInfo_.userinfo.email, | ||||||
| 						} | 															  TransactionId_); | ||||||
| 						catch (...) { | 					} catch (...) { | ||||||
| 						std::cout << "Cannot create websocket client..." << std::endl; | 						std::cout << "Cannot create websocket client..." << std::endl; | ||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
| 				} catch(...) { | 			} catch (...) { | ||||||
| 				std::cout << "Cannot upgrade connection..." << std::endl; | 				std::cout << "Cannot upgrade connection..." << std::endl; | ||||||
| 			} | 			} | ||||||
| 		}; | 		}; | ||||||
| 		void DoDelete() final {}; | 		void DoDelete() final{}; | ||||||
| 		void DoPost() final {}; | 		void DoPost() final{}; | ||||||
| 		void DoPut() final {}; | 		void DoPut() final{}; | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 	}; | 	}; | ||||||
| } | } // namespace OpenWifi | ||||||
| @@ -6,17 +6,25 @@ | |||||||
|  |  | ||||||
| #include <string> | #include <string> | ||||||
|  |  | ||||||
|  | #include "Poco/Data/LOB.h" | ||||||
| #include "Poco/JSON/Object.h" | #include "Poco/JSON/Object.h" | ||||||
| #include "Poco/JSON/Parser.h" | #include "Poco/JSON/Parser.h" | ||||||
| #include "Poco/Data/LOB.h" |  | ||||||
| #include "Poco/Net/HTTPServerRequest.h" | #include "Poco/Net/HTTPServerRequest.h" | ||||||
|  |  | ||||||
| #include "framework/OpenWifiTypes.h" | #include "framework/OpenWifiTypes.h" | ||||||
| #include "framework/utils.h" | #include "framework/utils.h" | ||||||
|  |  | ||||||
|  | #include <RESTObjects/RESTAPI_SecurityObjects.h> | ||||||
|  |  | ||||||
| namespace OpenWifi::RESTAPI_utils { | namespace OpenWifi::RESTAPI_utils { | ||||||
|  |  | ||||||
| 	inline void EmbedDocument(const std::string & ObjName, Poco::JSON::Object & Obj, const std::string &ObjStr) { | 	inline bool IsRootOrAdmin(const SecurityObjects::UserInfo &UI) { | ||||||
|  | 		return 	UI.userRole==SecurityObjects::ROOT || | ||||||
|  | 				UI.userRole==SecurityObjects::ADMIN; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	inline void EmbedDocument(const std::string &ObjName, Poco::JSON::Object &Obj, | ||||||
|  | 							  const std::string &ObjStr) { | ||||||
| 		std::string D = ObjStr.empty() ? "{}" : ObjStr; | 		std::string D = ObjStr.empty() ? "{}" : ObjStr; | ||||||
| 		Poco::JSON::Parser P; | 		Poco::JSON::Parser P; | ||||||
| 		Poco::Dynamic::Var result = P.parse(D); | 		Poco::Dynamic::Var result = P.parse(D); | ||||||
| @@ -25,23 +33,23 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, bool V) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, bool V) { | ||||||
| 		Obj.set(Field,V); | 		Obj.set(Field, V); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, double V) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, double V) { | ||||||
| 		Obj.set(Field,V); | 		Obj.set(Field, V); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, float V) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, float V) { | ||||||
| 		Obj.set(Field,V); | 		Obj.set(Field, V); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::string & S) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::string &S) { | ||||||
| 		Obj.set(Field,S); | 		Obj.set(Field, S); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const char * S) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const char *S) { | ||||||
| 		Obj.set(Field,S); | 		Obj.set(Field, S); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, int16_t Value) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, int16_t Value) { | ||||||
| @@ -65,78 +73,83 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, uint64_t Value) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, uint64_t Value) { | ||||||
| 		Obj.set(Field,Value); | 		Obj.set(Field, Value); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Poco::Data::BLOB &Value) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, | ||||||
| 		auto Result = Utils::base64encode((const unsigned char *)Value.rawContent(),Value.size()); | 							  const Poco::Data::BLOB &Value) { | ||||||
| 		Obj.set(Field,Result); | 		auto Result = Utils::base64encode((const unsigned char *)Value.rawContent(), Value.size()); | ||||||
|  | 		Obj.set(Field, Result); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::StringPairVec & S) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, | ||||||
|  | 							  const Types::StringPairVec &S) { | ||||||
| 		Poco::JSON::Array Array; | 		Poco::JSON::Array Array; | ||||||
| 		for(const auto &i:S) { | 		for (const auto &i : S) { | ||||||
| 			Poco::JSON::Object O; | 			Poco::JSON::Object O; | ||||||
| 			O.set("tag",i.first); | 			O.set("tag", i.first); | ||||||
| 			O.set("value", i.second); | 			O.set("value", i.second); | ||||||
| 			Array.add(O); | 			Array.add(O); | ||||||
| 		} | 		} | ||||||
| 		Obj.set(Field,Array); | 		Obj.set(Field, Array); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::StringVec &V) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, | ||||||
|  | 							  const Types::StringVec &V) { | ||||||
| 		Poco::JSON::Array A; | 		Poco::JSON::Array A; | ||||||
| 		for(const auto &i:V) | 		for (const auto &i : V) | ||||||
| 			A.add(i); | 			A.add(i); | ||||||
| 		Obj.set(Field,A); | 		Obj.set(Field, A); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::TagList &V) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::TagList &V) { | ||||||
| 		Poco::JSON::Array A; | 		Poco::JSON::Array A; | ||||||
| 		for(const auto &i:V) | 		for (const auto &i : V) | ||||||
| 			A.add(i); | 			A.add(i); | ||||||
| 		Obj.set(Field,A); | 		Obj.set(Field, A); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::CountedMap &M) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, | ||||||
|  | 							  const Types::CountedMap &M) { | ||||||
| 		Poco::JSON::Array A; | 		Poco::JSON::Array A; | ||||||
| 		for(const auto &[Key,Value]:M) { | 		for (const auto &[Key, Value] : M) { | ||||||
| 			Poco::JSON::Object O; | 			Poco::JSON::Object O; | ||||||
| 			O.set("tag",Key); | 			O.set("tag", Key); | ||||||
| 			O.set("value", Value); | 			O.set("value", Value); | ||||||
| 			A.add(O); | 			A.add(O); | ||||||
| 		} | 		} | ||||||
| 		Obj.set(Field,A); | 		Obj.set(Field, A); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::Counted3DMapSII &M) { | 	inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, | ||||||
|  | 							  const Types::Counted3DMapSII &M) { | ||||||
| 		Poco::JSON::Array A; | 		Poco::JSON::Array A; | ||||||
| 		for(const auto &[OrgName,MonthlyNumberMap]:M) { | 		for (const auto &[OrgName, MonthlyNumberMap] : M) { | ||||||
| 			Poco::JSON::Object OrgObject; | 			Poco::JSON::Object OrgObject; | ||||||
| 			OrgObject.set("tag",OrgName); | 			OrgObject.set("tag", OrgName); | ||||||
| 			Poco::JSON::Array MonthlyArray; | 			Poco::JSON::Array MonthlyArray; | ||||||
| 			for(const auto &[Month,Counter]:MonthlyNumberMap) { | 			for (const auto &[Month, Counter] : MonthlyNumberMap) { | ||||||
| 				Poco::JSON::Object Inner; | 				Poco::JSON::Object Inner; | ||||||
| 				Inner.set("value", Month); | 				Inner.set("value", Month); | ||||||
| 				Inner.set("counter", Counter); | 				Inner.set("counter", Counter); | ||||||
| 				MonthlyArray.add(Inner); | 				MonthlyArray.add(Inner); | ||||||
| 			} | 			} | ||||||
| 			OrgObject.set("index",MonthlyArray); | 			OrgObject.set("index", MonthlyArray); | ||||||
| 			A.add(OrgObject); | 			A.add(OrgObject); | ||||||
| 		} | 		} | ||||||
| 		Obj.set(Field, A); | 		Obj.set(Field, A); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<typename T> void field_to_json(Poco::JSON::Object &Obj, | 	template <typename T> | ||||||
| 					   const char *Field, | 	void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &V, | ||||||
| 					   const T &V, |  | ||||||
| 					   std::function<std::string(const T &)> F) { | 					   std::function<std::string(const T &)> F) { | ||||||
| 		Obj.set(Field, F(V)); | 		Obj.set(Field, F(V)); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::vector<T> &Value) { | 	template <class T> | ||||||
|  | 	void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::vector<T> &Value) { | ||||||
| 		Poco::JSON::Array Arr; | 		Poco::JSON::Array Arr; | ||||||
| 		for(const auto &i:Value) { | 		for (const auto &i : Value) { | ||||||
| 			Poco::JSON::Object AO; | 			Poco::JSON::Object AO; | ||||||
| 			i.to_json(AO); | 			i.to_json(AO); | ||||||
| 			Arr.add(AO); | 			Arr.add(AO); | ||||||
| @@ -144,7 +157,8 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 		Obj.set(Field, Arr); | 		Obj.set(Field, Arr); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &Value) { | 	template <class T> | ||||||
|  | 	void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &Value) { | ||||||
| 		Poco::JSON::Object Answer; | 		Poco::JSON::Object Answer; | ||||||
| 		Value.to_json(Answer); | 		Value.to_json(Answer); | ||||||
| 		Obj.set(Field, Answer); | 		Obj.set(Field, Answer); | ||||||
| @@ -155,110 +169,127 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 	/////////////////////////// | 	/////////////////////////// | ||||||
| 	/////////////////////////// | 	/////////////////////////// | ||||||
|  |  | ||||||
| 	template<typename T> bool field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T & V, | 	template <typename T> | ||||||
|  | 	bool field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &V, | ||||||
| 						 std::function<T(const std::string &)> F) { | 						 std::function<T(const std::string &)> F) { | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			V = F(Obj->get(Field).toString()); | 			V = F(Obj->get(Field).toString()); | ||||||
| 		return true; | 		return true; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, std::string &S) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								std::string &S) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			S = Obj->get(Field).toString(); | 			S = Obj->get(Field).toString(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, double & Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								double &Value) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			Value = (double)Obj->get(Field); | 			Value = (double)Obj->get(Field); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, float & Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								float &Value) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			Value = (float)Obj->get(Field); | 			Value = (float)Obj->get(Field); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, bool &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								bool &Value) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			Value = (Obj->get(Field).toString() == "true"); | 			Value = (Obj->get(Field).toString() == "true"); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int16_t &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								int16_t &Value) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			Value = (int16_t)Obj->get(Field); | 			Value = (int16_t)Obj->get(Field); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int32_t &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								int32_t &Value) { | ||||||
| 			Value = (int32_t) Obj->get(Field); | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
|  | 			Value = (int32_t)Obj->get(Field); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int64_t &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								int64_t &Value) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			Value = (int64_t)Obj->get(Field); | 			Value = (int64_t)Obj->get(Field); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint16_t &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								uint16_t &Value) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			Value = (uint16_t)Obj->get(Field); | 			Value = (uint16_t)Obj->get(Field); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint32_t &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								uint32_t &Value) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			Value = (uint32_t)Obj->get(Field); | 			Value = (uint32_t)Obj->get(Field); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint64_t &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) | 								uint64_t &Value) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) | ||||||
| 			Value = (uint64_t)Obj->get(Field); | 			Value = (uint64_t)Obj->get(Field); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Poco::Data::BLOB &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->has(Field) && !Obj->isNull(Field)) { | 								Poco::Data::BLOB &Value) { | ||||||
|  | 		if (Obj->has(Field) && !Obj->isNull(Field)) { | ||||||
| 			auto Result = Utils::base64decode(Obj->get(Field).toString()); | 			auto Result = Utils::base64decode(Obj->get(Field).toString()); | ||||||
| 			Value.assignRaw((const unsigned char *)&Result[0],Result.size()); | 			Value.assignRaw((const unsigned char *)&Result[0], Result.size()); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::StringPairVec &Vec) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->isArray(Field) && !Obj->isNull(Field)) { | 								Types::StringPairVec &Vec) { | ||||||
|  | 		if (Obj->isArray(Field) && !Obj->isNull(Field)) { | ||||||
| 			auto O = Obj->getArray(Field); | 			auto O = Obj->getArray(Field); | ||||||
| 			for(const auto &i:*O) { | 			for (const auto &i : *O) { | ||||||
| 				std::string S1,S2; | 				std::string S1, S2; | ||||||
| 				auto Inner = i.extract<Poco::JSON::Object::Ptr>(); | 				auto Inner = i.extract<Poco::JSON::Object::Ptr>(); | ||||||
| 				if(Inner->has("tag")) | 				if (Inner->has("tag")) | ||||||
| 					S1 = Inner->get("tag").toString(); | 					S1 = Inner->get("tag").toString(); | ||||||
| 				if(Inner->has("value")) | 				if (Inner->has("value")) | ||||||
| 					S2 = Inner->get("value").toString(); | 					S2 = Inner->get("value").toString(); | ||||||
| 				auto P = std::make_pair(S1,S2); | 				auto P = std::make_pair(S1, S2); | ||||||
| 				Vec.push_back(P); | 				Vec.push_back(P); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::StringVec &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->isArray(Field) && !Obj->isNull(Field)) { | 								Types::StringVec &Value) { | ||||||
|  | 		if (Obj->isArray(Field) && !Obj->isNull(Field)) { | ||||||
| 			Value.clear(); | 			Value.clear(); | ||||||
| 			Poco::JSON::Array::Ptr A = Obj->getArray(Field); | 			Poco::JSON::Array::Ptr A = Obj->getArray(Field); | ||||||
| 			for(const auto &i:*A) { | 			for (const auto &i : *A) { | ||||||
| 				Value.push_back(i.toString()); | 				Value.push_back(i.toString()); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::TagList &Value) { | 	inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
| 		if(Obj->isArray(Field) && !Obj->isNull(Field)) { | 								Types::TagList &Value) { | ||||||
|  | 		if (Obj->isArray(Field) && !Obj->isNull(Field)) { | ||||||
| 			Value.clear(); | 			Value.clear(); | ||||||
| 			Poco::JSON::Array::Ptr A = Obj->getArray(Field); | 			Poco::JSON::Array::Ptr A = Obj->getArray(Field); | ||||||
| 			for(const auto &i:*A) { | 			for (const auto &i : *A) { | ||||||
| 				Value.push_back(i); | 				Value.push_back(i); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, std::vector<T> &Value) { | 	template <class T> | ||||||
| 		if(Obj->isArray(Field) && !Obj->isNull(Field)) { | 	void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, | ||||||
|  | 						 std::vector<T> &Value) { | ||||||
|  | 		if (Obj->isArray(Field) && !Obj->isNull(Field)) { | ||||||
| 			Poco::JSON::Array::Ptr Arr = Obj->getArray(Field); | 			Poco::JSON::Array::Ptr Arr = Obj->getArray(Field); | ||||||
| 			for(auto &i:*Arr) { | 			for (auto &i : *Arr) { | ||||||
| 				auto InnerObj = i.extract<Poco::JSON::Object::Ptr>(); | 				auto InnerObj = i.extract<Poco::JSON::Object::Ptr>(); | ||||||
| 				T NewItem; | 				T NewItem; | ||||||
| 				NewItem.from_json(InnerObj); | 				NewItem.from_json(InnerObj); | ||||||
| @@ -267,76 +298,78 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &Value) { | 	template <class T> | ||||||
| 		if(Obj->isObject(Field) && !Obj->isNull(Field)) { | 	void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &Value) { | ||||||
|  | 		if (Obj->isObject(Field) && !Obj->isNull(Field)) { | ||||||
| 			Poco::JSON::Object::Ptr A = Obj->getObject(Field); | 			Poco::JSON::Object::Ptr A = Obj->getObject(Field); | ||||||
| 			Value.from_json(A); | 			Value.from_json(A); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline std::string to_string(const Types::TagList & ObjectArray) { | 	inline std::string to_string(const Types::TagList &ObjectArray) { | ||||||
| 		Poco::JSON::Array OutputArr; | 		Poco::JSON::Array OutputArr; | ||||||
| 		if(ObjectArray.empty()) | 		if (ObjectArray.empty()) | ||||||
| 			return "[]"; | 			return "[]"; | ||||||
| 		for(auto const &i:ObjectArray) { | 		for (auto const &i : ObjectArray) { | ||||||
| 			OutputArr.add(i); | 			OutputArr.add(i); | ||||||
| 		} | 		} | ||||||
| 		std::ostringstream OS; | 		std::ostringstream OS; | ||||||
| 		Poco::JSON::Stringifier::stringify(OutputArr,OS, 0,0, Poco::JSON_PRESERVE_KEY_ORDER ); | 		Poco::JSON::Stringifier::stringify(OutputArr, OS, 0, 0, Poco::JSON_PRESERVE_KEY_ORDER); | ||||||
| 		return OS.str(); | 		return OS.str(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline std::string to_string(const Types::StringVec & ObjectArray) { | 	inline std::string to_string(const Types::StringVec &ObjectArray) { | ||||||
| 		Poco::JSON::Array OutputArr; | 		Poco::JSON::Array OutputArr; | ||||||
| 		if(ObjectArray.empty()) | 		if (ObjectArray.empty()) | ||||||
| 			return "[]"; | 			return "[]"; | ||||||
| 		for(auto const &i:ObjectArray) { | 		for (auto const &i : ObjectArray) { | ||||||
| 			OutputArr.add(i); | 			OutputArr.add(i); | ||||||
| 		} | 		} | ||||||
| 		std::ostringstream OS; | 		std::ostringstream OS; | ||||||
| 		Poco::JSON::Stringifier::condense(OutputArr,OS); | 		Poco::JSON::Stringifier::condense(OutputArr, OS); | ||||||
| 		return OS.str(); | 		return OS.str(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline std::string to_string(const Types::StringPairVec & ObjectArray) { | 	inline std::string to_string(const Types::StringPairVec &ObjectArray) { | ||||||
| 		Poco::JSON::Array OutputArr; | 		Poco::JSON::Array OutputArr; | ||||||
| 		if(ObjectArray.empty()) | 		if (ObjectArray.empty()) | ||||||
| 			return "[]"; | 			return "[]"; | ||||||
| 		for(auto const &i:ObjectArray) { | 		for (auto const &i : ObjectArray) { | ||||||
| 			Poco::JSON::Array InnerArray; | 			Poco::JSON::Array InnerArray; | ||||||
| 			InnerArray.add(i.first); | 			InnerArray.add(i.first); | ||||||
| 			InnerArray.add(i.second); | 			InnerArray.add(i.second); | ||||||
| 			OutputArr.add(InnerArray); | 			OutputArr.add(InnerArray); | ||||||
| 		} | 		} | ||||||
| 		std::ostringstream OS; | 		std::ostringstream OS; | ||||||
| 		Poco::JSON::Stringifier::condense(OutputArr,OS); | 		Poco::JSON::Stringifier::condense(OutputArr, OS); | ||||||
| 		return OS.str(); | 		return OS.str(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> std::string to_string(const std::vector<T> & ObjectArray) { | 	template <class T> std::string to_string(const std::vector<T> &ObjectArray) { | ||||||
| 		Poco::JSON::Array OutputArr; | 		Poco::JSON::Array OutputArr; | ||||||
| 		if(ObjectArray.empty()) | 		if (ObjectArray.empty()) | ||||||
| 			return "[]"; | 			return "[]"; | ||||||
| 		for(auto const &i:ObjectArray) { | 		for (auto const &i : ObjectArray) { | ||||||
| 			Poco::JSON::Object O; | 			Poco::JSON::Object O; | ||||||
| 			i.to_json(O); | 			i.to_json(O); | ||||||
| 			OutputArr.add(O); | 			OutputArr.add(O); | ||||||
| 		} | 		} | ||||||
| 		std::ostringstream OS; | 		std::ostringstream OS; | ||||||
| 		Poco::JSON::Stringifier::condense(OutputArr,OS); | 		Poco::JSON::Stringifier::condense(OutputArr, OS); | ||||||
| 		return OS.str(); | 		return OS.str(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> std::string to_string(const std::vector<std::vector<T>> & ObjectArray) { | 	template <class T> std::string to_string(const std::vector<std::vector<T>> &ObjectArray) { | ||||||
| 		Poco::JSON::Array OutputArr; | 		Poco::JSON::Array OutputArr; | ||||||
| 		if(ObjectArray.empty()) | 		if (ObjectArray.empty()) | ||||||
| 			return "[]"; | 			return "[]"; | ||||||
| 		for(auto const &i:ObjectArray) { | 		for (auto const &i : ObjectArray) { | ||||||
| 			Poco::JSON::Array InnerArr; | 			Poco::JSON::Array InnerArr; | ||||||
| 			for(auto const &j:i) { | 			for (auto const &j : i) { | ||||||
| 				if constexpr(std::is_integral<T>::value) { | 				if constexpr (std::is_integral<T>::value) { | ||||||
| 					InnerArr.add(j); | 					InnerArr.add(j); | ||||||
| 				} if constexpr(std::is_same_v<T,std::string>) { | 				} | ||||||
|  | 				if constexpr (std::is_same_v<T, std::string>) { | ||||||
| 					InnerArr.add(j); | 					InnerArr.add(j); | ||||||
| 				} else { | 				} else { | ||||||
| 					InnerArr.add(j); | 					InnerArr.add(j); | ||||||
| @@ -348,22 +381,22 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 			OutputArr.add(InnerArr); | 			OutputArr.add(InnerArr); | ||||||
| 		} | 		} | ||||||
| 		std::ostringstream OS; | 		std::ostringstream OS; | ||||||
| 		Poco::JSON::Stringifier::condense(OutputArr,OS); | 		Poco::JSON::Stringifier::condense(OutputArr, OS); | ||||||
| 		return OS.str(); | 		return OS.str(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> std::string to_string(const T & Object) { | 	template <class T> std::string to_string(const T &Object) { | ||||||
| 		Poco::JSON::Object OutputObj; | 		Poco::JSON::Object OutputObj; | ||||||
| 		Object.to_json(OutputObj); | 		Object.to_json(OutputObj); | ||||||
| 		std::ostringstream OS; | 		std::ostringstream OS; | ||||||
| 		Poco::JSON::Stringifier::condense(OutputObj,OS); | 		Poco::JSON::Stringifier::condense(OutputObj, OS); | ||||||
| 		return OS.str(); | 		return OS.str(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline Types::StringVec to_object_array(const std::string & ObjectString) { | 	inline Types::StringVec to_object_array(const std::string &ObjectString) { | ||||||
|  |  | ||||||
| 		Types::StringVec Result; | 		Types::StringVec Result; | ||||||
| 		if(ObjectString.empty()) | 		if (ObjectString.empty()) | ||||||
| 			return Result; | 			return Result; | ||||||
|  |  | ||||||
| 		try { | 		try { | ||||||
| @@ -373,14 +406,13 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 				Result.push_back(i.toString()); | 				Result.push_back(i.toString()); | ||||||
| 			} | 			} | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline OpenWifi::Types::TagList to_taglist(const std::string & ObjectString) { | 	inline OpenWifi::Types::TagList to_taglist(const std::string &ObjectString) { | ||||||
| 		Types::TagList Result; | 		Types::TagList Result; | ||||||
| 		if(ObjectString.empty()) | 		if (ObjectString.empty()) | ||||||
| 			return Result; | 			return Result; | ||||||
|  |  | ||||||
| 		try { | 		try { | ||||||
| @@ -390,36 +422,34 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 				Result.push_back(i); | 				Result.push_back(i); | ||||||
| 			} | 			} | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline Types::StringPairVec to_stringpair_array(const std::string &S) { | 	inline Types::StringPairVec to_stringpair_array(const std::string &S) { | ||||||
| 		Types::StringPairVec R; | 		Types::StringPairVec R; | ||||||
| 		if(S.empty()) | 		if (S.empty()) | ||||||
| 			return R; | 			return R; | ||||||
| 		try { | 		try { | ||||||
| 			Poco::JSON::Parser P; | 			Poco::JSON::Parser P; | ||||||
| 			auto Object = P.parse(S).template extract<Poco::JSON::Array::Ptr>(); | 			auto Object = P.parse(S).template extract<Poco::JSON::Array::Ptr>(); | ||||||
| 			for (const auto &i : *Object) { | 			for (const auto &i : *Object) { | ||||||
| 				auto InnerObject = i.template extract<Poco::JSON::Array::Ptr>(); | 				auto InnerObject = i.template extract<Poco::JSON::Array::Ptr>(); | ||||||
| 				if(InnerObject->size()==2) { | 				if (InnerObject->size() == 2) { | ||||||
| 					auto S1 = InnerObject->getElement<std::string>(0); | 					auto S1 = InnerObject->getElement<std::string>(0); | ||||||
| 					auto S2 = InnerObject->getElement<std::string>(1); | 					auto S2 = InnerObject->getElement<std::string>(1); | ||||||
| 					R.push_back(std::make_pair(S1,S2)); | 					R.push_back(std::make_pair(S1, S2)); | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return R; | 		return R; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> std::vector<T> to_object_array(const std::string & ObjectString) { | 	template <class T> std::vector<T> to_object_array(const std::string &ObjectString) { | ||||||
| 		std::vector<T> Result; | 		std::vector<T> Result; | ||||||
| 		if(ObjectString.empty()) | 		if (ObjectString.empty()) | ||||||
| 			return Result; | 			return Result; | ||||||
|  |  | ||||||
| 		try { | 		try { | ||||||
| @@ -432,14 +462,14 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 				Result.push_back(Obj); | 				Result.push_back(Obj); | ||||||
| 			} | 			} | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> std::vector<std::vector<T>> to_array_of_array_of_object(const std::string & ObjectString) { | 	template <class T> | ||||||
|  | 	std::vector<std::vector<T>> to_array_of_array_of_object(const std::string &ObjectString) { | ||||||
| 		std::vector<std::vector<T>> Result; | 		std::vector<std::vector<T>> Result; | ||||||
| 		if(ObjectString.empty()) | 		if (ObjectString.empty()) | ||||||
| 			return Result; | 			return Result; | ||||||
| 		try { | 		try { | ||||||
| 			Poco::JSON::Parser P1; | 			Poco::JSON::Parser P1; | ||||||
| @@ -448,7 +478,7 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 				Poco::JSON::Parser P2; | 				Poco::JSON::Parser P2; | ||||||
| 				auto InnerArray = P2.parse(i).template extract<Poco::JSON::Array::Ptr>(); | 				auto InnerArray = P2.parse(i).template extract<Poco::JSON::Array::Ptr>(); | ||||||
| 				std::vector<T> InnerVector; | 				std::vector<T> InnerVector; | ||||||
| 				for(auto const &j: *InnerArray) { | 				for (auto const &j : *InnerArray) { | ||||||
| 					auto Object = j.template extract<Poco::JSON::Object::Ptr>(); | 					auto Object = j.template extract<Poco::JSON::Object::Ptr>(); | ||||||
| 					T Obj; | 					T Obj; | ||||||
| 					Obj.from_json(Object); | 					Obj.from_json(Object); | ||||||
| @@ -457,15 +487,14 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 				Result.push_back(InnerVector); | 				Result.push_back(InnerVector); | ||||||
| 			} | 			} | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> T to_object(const std::string & ObjectString) { | 	template <class T> T to_object(const std::string &ObjectString) { | ||||||
| 		T Result; | 		T Result; | ||||||
|  |  | ||||||
| 		if(ObjectString.empty()) | 		if (ObjectString.empty()) | ||||||
| 			return Result; | 			return Result; | ||||||
|  |  | ||||||
| 		Poco::JSON::Parser P; | 		Poco::JSON::Parser P; | ||||||
| @@ -475,10 +504,10 @@ namespace OpenWifi::RESTAPI_utils { | |||||||
| 		return Result; | 		return Result; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	template<class T> bool from_request(T & Obj, Poco::Net::HTTPServerRequest &Request) { | 	template <class T> bool from_request(T &Obj, Poco::Net::HTTPServerRequest &Request) { | ||||||
| 		Poco::JSON::Parser IncomingParser; | 		Poco::JSON::Parser IncomingParser; | ||||||
| 		auto RawObject = IncomingParser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>(); | 		auto RawObject = IncomingParser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>(); | ||||||
| 		Obj.from_json(RawObject); | 		Obj.from_json(RawObject); | ||||||
| 		return true; | 		return true; | ||||||
| 	} | 	} | ||||||
| } | } // namespace OpenWifi::RESTAPI_utils | ||||||
|   | |||||||
| @@ -4,38 +4,31 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
|  | #include "Poco/Data/SQLite/Connector.h" | ||||||
| #include "Poco/Data/Session.h" | #include "Poco/Data/Session.h" | ||||||
| #include "Poco/Data/SessionPool.h" | #include "Poco/Data/SessionPool.h" | ||||||
| #include "Poco/Data/SQLite/Connector.h" |  | ||||||
| #include "Poco/JSON/Object.h" | #include "Poco/JSON/Object.h" | ||||||
|  |  | ||||||
| #ifndef SMALL_BUILD | #ifndef SMALL_BUILD | ||||||
| #include "Poco/Data/PostgreSQL/Connector.h" |  | ||||||
| #include "Poco/Data/MySQL/Connector.h" | #include "Poco/Data/MySQL/Connector.h" | ||||||
|  | #include "Poco/Data/PostgreSQL/Connector.h" | ||||||
| #endif | #endif | ||||||
|  |  | ||||||
| #include "framework/SubSystemServer.h" |  | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  | #include "framework/SubSystemServer.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|     enum DBType { | 	enum DBType { sqlite, pgsql, mysql }; | ||||||
|         sqlite, |  | ||||||
|         pgsql, |  | ||||||
|         mysql |  | ||||||
|     }; |  | ||||||
|  |  | ||||||
| 	class StorageClass : public SubSystemServer { | 	class StorageClass : public SubSystemServer { | ||||||
| 	  public: | 	  public: | ||||||
|         StorageClass() noexcept: | 		StorageClass() noexcept : SubSystemServer("StorageClass", "STORAGE-SVR", "storage") {} | ||||||
|             SubSystemServer("StorageClass", "STORAGE-SVR", "storage") |  | ||||||
|         { |  | ||||||
|         } |  | ||||||
|  |  | ||||||
| 		int Start() override { | 		int Start() override { | ||||||
| 			std::lock_guard Guard(Mutex_); | 			std::lock_guard Guard(Mutex_); | ||||||
|  |  | ||||||
| 			Logger().notice("Starting."); | 			Logger().notice("Starting."); | ||||||
|             std::string DBType = MicroServiceConfigGetString("storage.type",""); | 			std::string DBType = MicroServiceConfigGetString("storage.type", ""); | ||||||
|  |  | ||||||
| 			if (DBType == "sqlite") { | 			if (DBType == "sqlite") { | ||||||
| 				Setup_SQLite(); | 				Setup_SQLite(); | ||||||
| @@ -47,11 +40,10 @@ namespace OpenWifi { | |||||||
| 			return 0; | 			return 0; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
|         void Stop() override { | 		void Stop() override { Pool_->shutdown(); } | ||||||
|             Pool_->shutdown(); |  | ||||||
|         } |  | ||||||
|  |  | ||||||
| 		DBType Type() const { return dbType_; }; | 		DBType Type() const { return dbType_; }; | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		inline int Setup_SQLite(); | 		inline int Setup_SQLite(); | ||||||
| 		inline int Setup_MySQL(); | 		inline int Setup_MySQL(); | ||||||
| @@ -66,20 +58,29 @@ namespace OpenWifi { | |||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| #ifdef SMALL_BUILD | #ifdef SMALL_BUILD | ||||||
|     int Service::Setup_MySQL() { Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); return 0; } | 	int Service::Setup_MySQL() { | ||||||
|     int Service::Setup_PostgreSQL() { Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); return 0; } | 		Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); | ||||||
|  | 		return 0; | ||||||
|  | 	} | ||||||
|  | 	int Service::Setup_PostgreSQL() { | ||||||
|  | 		Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); | ||||||
|  | 		return 0; | ||||||
|  | 	} | ||||||
| #else | #else | ||||||
|  |  | ||||||
| 	inline int StorageClass::Setup_SQLite() { | 	inline int StorageClass::Setup_SQLite() { | ||||||
| 		Logger().notice("SQLite StorageClass enabled."); | 		Logger().notice("SQLite StorageClass enabled."); | ||||||
| 		dbType_ = sqlite; | 		dbType_ = sqlite; | ||||||
|         auto DBName = MicroServiceDataDirectory() + "/" + MicroServiceConfigGetString("storage.type.sqlite.db",""); | 		auto DBName = MicroServiceDataDirectory() + "/" + | ||||||
|         int NumSessions = (int) MicroServiceConfigGetInt("storage.type.sqlite.maxsessions", 64); | 					  MicroServiceConfigGetString("storage.type.sqlite.db", ""); | ||||||
|         int IdleTime = (int) MicroServiceConfigGetInt("storage.type.sqlite.idletime", 60); | 		int NumSessions = (int)MicroServiceConfigGetInt("storage.type.sqlite.maxsessions", 64); | ||||||
|  | 		int IdleTime = (int)MicroServiceConfigGetInt("storage.type.sqlite.idletime", 60); | ||||||
|  |  | ||||||
| 		Poco::Data::SQLite::Connector::registerConnector(); | 		Poco::Data::SQLite::Connector::registerConnector(); | ||||||
| //        Pool_ = std::make_unique<Poco::Data::SessionPool>(new Poco::Data::SessionPool(SQLiteConn_.name(), DBName, 8, | 		//        Pool_ = std::make_unique<Poco::Data::SessionPool>(new | ||||||
| //                                                                                     (int)NumSessions, (int)IdleTime)); | 		//        Poco::Data::SessionPool(SQLiteConn_.name(), DBName, 8, | ||||||
|  | 		//                                                                                     (int)NumSessions, | ||||||
|  | 		//                                                                                     (int)IdleTime)); | ||||||
| 		Pool_ = std::make_unique<Poco::Data::SessionPool>(SQLiteConn_.name(), DBName, 8, | 		Pool_ = std::make_unique<Poco::Data::SessionPool>(SQLiteConn_.name(), DBName, 8, | ||||||
| 														  (int)NumSessions, (int)IdleTime); | 														  (int)NumSessions, (int)IdleTime); | ||||||
| 		return 0; | 		return 0; | ||||||
| @@ -88,24 +89,21 @@ namespace OpenWifi { | |||||||
| 	inline int StorageClass::Setup_MySQL() { | 	inline int StorageClass::Setup_MySQL() { | ||||||
| 		Logger().notice("MySQL StorageClass enabled."); | 		Logger().notice("MySQL StorageClass enabled."); | ||||||
| 		dbType_ = mysql; | 		dbType_ = mysql; | ||||||
|         int NumSessions = (int) MicroServiceConfigGetInt("storage.type.mysql.maxsessions", 64); | 		int NumSessions = (int)MicroServiceConfigGetInt("storage.type.mysql.maxsessions", 64); | ||||||
|         int IdleTime = (int) MicroServiceConfigGetInt("storage.type.mysql.idletime", 60); | 		int IdleTime = (int)MicroServiceConfigGetInt("storage.type.mysql.idletime", 60); | ||||||
|         auto Host = MicroServiceConfigGetString("storage.type.mysql.host",""); | 		auto Host = MicroServiceConfigGetString("storage.type.mysql.host", ""); | ||||||
|         auto Username = MicroServiceConfigGetString("storage.type.mysql.username",""); | 		auto Username = MicroServiceConfigGetString("storage.type.mysql.username", ""); | ||||||
|         auto Password = MicroServiceConfigGetString("storage.type.mysql.password",""); | 		auto Password = MicroServiceConfigGetString("storage.type.mysql.password", ""); | ||||||
|         auto Database = MicroServiceConfigGetString("storage.type.mysql.database",""); | 		auto Database = MicroServiceConfigGetString("storage.type.mysql.database", ""); | ||||||
|         auto Port = MicroServiceConfigGetString("storage.type.mysql.port",""); | 		auto Port = MicroServiceConfigGetString("storage.type.mysql.port", ""); | ||||||
|  |  | ||||||
|         std::string ConnectionStr = | 		std::string ConnectionStr = "host=" + Host + ";user=" + Username + ";password=" + Password + | ||||||
|                 "host=" + Host + | 									";db=" + Database + ";port=" + Port + | ||||||
|                 ";user=" + Username + |  | ||||||
|                 ";password=" + Password + |  | ||||||
|                 ";db=" + Database + |  | ||||||
|                 ";port=" + Port + |  | ||||||
| 									";compress=true;auto-reconnect=true"; | 									";compress=true;auto-reconnect=true"; | ||||||
|  |  | ||||||
| 		Poco::Data::MySQL::Connector::registerConnector(); | 		Poco::Data::MySQL::Connector::registerConnector(); | ||||||
|         Pool_ = std::make_unique<Poco::Data::SessionPool>(MySQLConn_.name(), ConnectionStr, 8, NumSessions, IdleTime); | 		Pool_ = std::make_unique<Poco::Data::SessionPool>(MySQLConn_.name(), ConnectionStr, 8, | ||||||
|  | 														  NumSessions, IdleTime); | ||||||
|  |  | ||||||
| 		return 0; | 		return 0; | ||||||
| 	} | 	} | ||||||
| @@ -113,28 +111,26 @@ namespace OpenWifi { | |||||||
| 	inline int StorageClass::Setup_PostgreSQL() { | 	inline int StorageClass::Setup_PostgreSQL() { | ||||||
| 		Logger().notice("PostgreSQL StorageClass enabled."); | 		Logger().notice("PostgreSQL StorageClass enabled."); | ||||||
| 		dbType_ = pgsql; | 		dbType_ = pgsql; | ||||||
|         int NumSessions = (int) MicroServiceConfigGetInt("storage.type.postgresql.maxsessions", 64); | 		int NumSessions = (int)MicroServiceConfigGetInt("storage.type.postgresql.maxsessions", 64); | ||||||
|         int IdleTime = (int) MicroServiceConfigGetInt("storage.type.postgresql.idletime", 60); | 		int IdleTime = (int)MicroServiceConfigGetInt("storage.type.postgresql.idletime", 60); | ||||||
| 		auto Host = MicroServiceConfigGetString("storage.type.postgresql.host", ""); | 		auto Host = MicroServiceConfigGetString("storage.type.postgresql.host", ""); | ||||||
| 		auto Username = MicroServiceConfigGetString("storage.type.postgresql.username", ""); | 		auto Username = MicroServiceConfigGetString("storage.type.postgresql.username", ""); | ||||||
| 		auto Password = MicroServiceConfigGetString("storage.type.postgresql.password", ""); | 		auto Password = MicroServiceConfigGetString("storage.type.postgresql.password", ""); | ||||||
| 		auto Database = MicroServiceConfigGetString("storage.type.postgresql.database", ""); | 		auto Database = MicroServiceConfigGetString("storage.type.postgresql.database", ""); | ||||||
| 		auto Port = MicroServiceConfigGetString("storage.type.postgresql.port", ""); | 		auto Port = MicroServiceConfigGetString("storage.type.postgresql.port", ""); | ||||||
|         auto ConnectionTimeout = MicroServiceConfigGetString("storage.type.postgresql.connectiontimeout", ""); | 		auto ConnectionTimeout = | ||||||
|  | 			MicroServiceConfigGetString("storage.type.postgresql.connectiontimeout", ""); | ||||||
|  |  | ||||||
|         std::string ConnectionStr = | 		std::string ConnectionStr = "host=" + Host + " user=" + Username + " password=" + Password + | ||||||
|                 "host=" + Host + | 									" dbname=" + Database + " port=" + Port + | ||||||
|                 " user=" + Username + |  | ||||||
|                 " password=" + Password + |  | ||||||
|                 " dbname=" + Database + |  | ||||||
|                 " port=" + Port + |  | ||||||
| 									" connect_timeout=" + ConnectionTimeout; | 									" connect_timeout=" + ConnectionTimeout; | ||||||
|  |  | ||||||
| 		Poco::Data::PostgreSQL::Connector::registerConnector(); | 		Poco::Data::PostgreSQL::Connector::registerConnector(); | ||||||
|         Pool_ = std::make_unique<Poco::Data::SessionPool>(PostgresConn_.name(), ConnectionStr, 8, NumSessions, IdleTime); | 		Pool_ = std::make_unique<Poco::Data::SessionPool>(PostgresConn_.name(), ConnectionStr, 8, | ||||||
|  | 														  NumSessions, IdleTime); | ||||||
|  |  | ||||||
| 		return 0; | 		return 0; | ||||||
| 	} | 	} | ||||||
| #endif | #endif | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
|   | |||||||
| @@ -6,36 +6,29 @@ | |||||||
|  |  | ||||||
| #include "framework/SubSystemServer.h" | #include "framework/SubSystemServer.h" | ||||||
|  |  | ||||||
| #include "Poco/Net/SSLManager.h" |  | ||||||
| #include "Poco/DateTimeFormatter.h" |  | ||||||
| #include "Poco/DateTimeFormat.h" | #include "Poco/DateTimeFormat.h" | ||||||
|  | #include "Poco/DateTimeFormatter.h" | ||||||
|  | #include "Poco/Net/SSLManager.h" | ||||||
|  |  | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	PropertiesFileServerEntry::PropertiesFileServerEntry(std::string Address, uint32_t port, std::string Key_file, | 	PropertiesFileServerEntry::PropertiesFileServerEntry( | ||||||
| 							  std::string Cert_file, std::string RootCa, std::string Issuer, | 		std::string Address, uint32_t port, std::string Key_file, std::string Cert_file, | ||||||
| 							  std::string ClientCas, std::string Cas, | 		std::string RootCa, std::string Issuer, std::string ClientCas, std::string Cas, | ||||||
| 							  std::string Key_file_password, std::string Name, | 		std::string Key_file_password, std::string Name, Poco::Net::Context::VerificationMode M, | ||||||
| 							  Poco::Net::Context::VerificationMode M, |  | ||||||
| 		int backlog) | 		int backlog) | ||||||
| 		: address_(std::move(Address)), | 		: address_(std::move(Address)), port_(port), cert_file_(std::move(Cert_file)), | ||||||
| 		  port_(port), | 		  key_file_(std::move(Key_file)), root_ca_(std::move(RootCa)), | ||||||
| 		  cert_file_(std::move(Cert_file)), | 		  key_file_password_(std::move(Key_file_password)), issuer_cert_file_(std::move(Issuer)), | ||||||
| 		  key_file_(std::move(Key_file)), | 		  client_cas_(std::move(ClientCas)), cas_(std::move(Cas)), name_(std::move(Name)), | ||||||
| 		  root_ca_(std::move(RootCa)), | 		  backlog_(backlog), level_(M){ | ||||||
| 		  key_file_password_(std::move(Key_file_password)), |  | ||||||
| 		  issuer_cert_file_(std::move(Issuer)), |  | ||||||
| 		  client_cas_(std::move(ClientCas)), |  | ||||||
| 		  cas_(std::move(Cas)), |  | ||||||
| 		  name_(std::move(Name)), |  | ||||||
| 		  backlog_(backlog), |  | ||||||
| 		  level_(M) { |  | ||||||
|  |  | ||||||
| 							 }; | 							 }; | ||||||
|  |  | ||||||
| 	[[nodiscard]] Poco::Net::SecureServerSocket PropertiesFileServerEntry::CreateSecureSocket(Poco::Logger &L) const { | 	[[nodiscard]] Poco::Net::SecureServerSocket | ||||||
|  | 	PropertiesFileServerEntry::CreateSecureSocket(Poco::Logger &L) const { | ||||||
| 		Poco::Net::Context::Params P; | 		Poco::Net::Context::Params P; | ||||||
|  |  | ||||||
| 		P.verificationMode = level_; | 		P.verificationMode = level_; | ||||||
| @@ -45,11 +38,13 @@ namespace OpenWifi { | |||||||
| 		P.dhUse2048Bits = true; | 		P.dhUse2048Bits = true; | ||||||
| 		P.caLocation = cas_; | 		P.caLocation = cas_; | ||||||
|  |  | ||||||
| 		auto Context = Poco::AutoPtr<Poco::Net::Context>(new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P)); | 		auto Context = Poco::AutoPtr<Poco::Net::Context>( | ||||||
|  | 			new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P)); | ||||||
|  |  | ||||||
| 		if(!key_file_password_.empty()) { | 		if (!key_file_password_.empty()) { | ||||||
| 			auto PassphraseHandler = Poco::SharedPtr<MyPrivateKeyPassphraseHandler>( new MyPrivateKeyPassphraseHandler(key_file_password_,L)); | 			auto PassphraseHandler = Poco::SharedPtr<MyPrivateKeyPassphraseHandler>( | ||||||
| 			Poco::Net::SSLManager::instance().initializeServer(PassphraseHandler, nullptr,Context); | 				new MyPrivateKeyPassphraseHandler(key_file_password_, L)); | ||||||
|  | 			Poco::Net::SSLManager::instance().initializeServer(PassphraseHandler, nullptr, Context); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		if (!cert_file_.empty() && !key_file_.empty()) { | 		if (!cert_file_.empty() && !key_file_.empty()) { | ||||||
| @@ -111,7 +106,8 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	[[nodiscard]] Poco::Net::ServerSocket PropertiesFileServerEntry::CreateSocket([[maybe_unused]] Poco::Logger &L) const { | 	[[nodiscard]] Poco::Net::ServerSocket | ||||||
|  | 	PropertiesFileServerEntry::CreateSocket([[maybe_unused]] Poco::Logger &L) const { | ||||||
| 		Poco::Net::Context::Params P; | 		Poco::Net::Context::Params P; | ||||||
|  |  | ||||||
| 		if (address_ == "*") { | 		if (address_ == "*") { | ||||||
| @@ -127,19 +123,24 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void PropertiesFileServerEntry::LogCertInfo(Poco::Logger &L, const Poco::Crypto::X509Certificate &C) const { | 	void PropertiesFileServerEntry::LogCertInfo(Poco::Logger &L, | ||||||
| 		L.information("============================================================================================="); | 												const Poco::Crypto::X509Certificate &C) const { | ||||||
|  | 		L.information("============================================================================" | ||||||
|  | 					  "================="); | ||||||
| 		L.information(fmt::format(">          Issuer: {}", C.issuerName())); | 		L.information(fmt::format(">          Issuer: {}", C.issuerName())); | ||||||
| 		L.information("---------------------------------------------------------------------------------------------"); | 		L.information("----------------------------------------------------------------------------" | ||||||
|  | 					  "-----------------"); | ||||||
| 		L.information(fmt::format(">     Common Name: {}", | 		L.information(fmt::format(">     Common Name: {}", | ||||||
| 								  C.issuerName(Poco::Crypto::X509Certificate::NID_COMMON_NAME))); | 								  C.issuerName(Poco::Crypto::X509Certificate::NID_COMMON_NAME))); | ||||||
| 		L.information(fmt::format(">         Country: {}", | 		L.information(fmt::format(">         Country: {}", | ||||||
| 								  C.issuerName(Poco::Crypto::X509Certificate::NID_COUNTRY))); | 								  C.issuerName(Poco::Crypto::X509Certificate::NID_COUNTRY))); | ||||||
| 		L.information(fmt::format(">        Locality: {}", | 		L.information(fmt::format(">        Locality: {}", | ||||||
| 								  C.issuerName(Poco::Crypto::X509Certificate::NID_LOCALITY_NAME))); | 								  C.issuerName(Poco::Crypto::X509Certificate::NID_LOCALITY_NAME))); | ||||||
| 		L.information(fmt::format(">      State/Prov: {}", | 		L.information( | ||||||
|  | 			fmt::format(">      State/Prov: {}", | ||||||
| 						C.issuerName(Poco::Crypto::X509Certificate::NID_STATE_OR_PROVINCE))); | 						C.issuerName(Poco::Crypto::X509Certificate::NID_STATE_OR_PROVINCE))); | ||||||
| 		L.information(fmt::format(">        Org name: {}", | 		L.information( | ||||||
|  | 			fmt::format(">        Org name: {}", | ||||||
| 						C.issuerName(Poco::Crypto::X509Certificate::NID_ORGANIZATION_NAME))); | 						C.issuerName(Poco::Crypto::X509Certificate::NID_ORGANIZATION_NAME))); | ||||||
| 		L.information( | 		L.information( | ||||||
| 			fmt::format(">        Org unit: {}", | 			fmt::format(">        Org unit: {}", | ||||||
| @@ -149,9 +150,11 @@ namespace OpenWifi { | |||||||
| 						C.issuerName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS))); | 						C.issuerName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS))); | ||||||
| 		L.information(fmt::format(">         Serial#: {}", | 		L.information(fmt::format(">         Serial#: {}", | ||||||
| 								  C.issuerName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER))); | 								  C.issuerName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER))); | ||||||
| 		L.information("---------------------------------------------------------------------------------------------"); | 		L.information("----------------------------------------------------------------------------" | ||||||
|  | 					  "-----------------"); | ||||||
| 		L.information(fmt::format(">         Subject: {}", C.subjectName())); | 		L.information(fmt::format(">         Subject: {}", C.subjectName())); | ||||||
| 		L.information("---------------------------------------------------------------------------------------------"); | 		L.information("----------------------------------------------------------------------------" | ||||||
|  | 					  "-----------------"); | ||||||
| 		L.information(fmt::format(">     Common Name: {}", | 		L.information(fmt::format(">     Common Name: {}", | ||||||
| 								  C.subjectName(Poco::Crypto::X509Certificate::NID_COMMON_NAME))); | 								  C.subjectName(Poco::Crypto::X509Certificate::NID_COMMON_NAME))); | ||||||
| 		L.information(fmt::format(">         Country: {}", | 		L.information(fmt::format(">         Country: {}", | ||||||
| @@ -172,52 +175,66 @@ namespace OpenWifi { | |||||||
| 						C.subjectName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS))); | 						C.subjectName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS))); | ||||||
| 		L.information(fmt::format(">         Serial#: {}", | 		L.information(fmt::format(">         Serial#: {}", | ||||||
| 								  C.subjectName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER))); | 								  C.subjectName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER))); | ||||||
| 		L.information("---------------------------------------------------------------------------------------------"); | 		L.information("----------------------------------------------------------------------------" | ||||||
|  | 					  "-----------------"); | ||||||
| 		L.information(fmt::format(">  Signature Algo: {}", C.signatureAlgorithm())); | 		L.information(fmt::format(">  Signature Algo: {}", C.signatureAlgorithm())); | ||||||
| 		auto From = Poco::DateTimeFormatter::format(C.validFrom(), Poco::DateTimeFormat::HTTP_FORMAT); | 		auto From = | ||||||
|  | 			Poco::DateTimeFormatter::format(C.validFrom(), Poco::DateTimeFormat::HTTP_FORMAT); | ||||||
| 		L.information(fmt::format(">      Valid from: {}", From)); | 		L.information(fmt::format(">      Valid from: {}", From)); | ||||||
| 		auto Expires = | 		auto Expires = | ||||||
| 			Poco::DateTimeFormatter::format(C.expiresOn(), Poco::DateTimeFormat::HTTP_FORMAT); | 			Poco::DateTimeFormatter::format(C.expiresOn(), Poco::DateTimeFormat::HTTP_FORMAT); | ||||||
| 		L.information(fmt::format(">      Expires on: {}", Expires)); | 		L.information(fmt::format(">      Expires on: {}", Expires)); | ||||||
| 		L.information(fmt::format(">         Version: {}", (int)C.version())); | 		L.information(fmt::format(">         Version: {}", (int)C.version())); | ||||||
| 		L.information(fmt::format(">        Serial #: {}", C.serialNumber())); | 		L.information(fmt::format(">        Serial #: {}", C.serialNumber())); | ||||||
| 		L.information("============================================================================================="); | 		L.information("============================================================================" | ||||||
|  | 					  "================="); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void PropertiesFileServerEntry::LogCert(Poco::Logger &L) const { | 	void PropertiesFileServerEntry::LogCert(Poco::Logger &L) const { | ||||||
| 		try { | 		try { | ||||||
| 			Poco::Crypto::X509Certificate C(cert_file_); | 			Poco::Crypto::X509Certificate C(cert_file_); | ||||||
| 			L.information("============================================================================================="); | 			L.information("========================================================================" | ||||||
| 			L.information("============================================================================================="); | 						  "====================="); | ||||||
|  | 			L.information("========================================================================" | ||||||
|  | 						  "====================="); | ||||||
| 			L.information(fmt::format("Certificate Filename: {}", cert_file_)); | 			L.information(fmt::format("Certificate Filename: {}", cert_file_)); | ||||||
| 			LogCertInfo(L, C); | 			LogCertInfo(L, C); | ||||||
| 			L.information("============================================================================================="); | 			L.information("========================================================================" | ||||||
|  | 						  "====================="); | ||||||
|  |  | ||||||
| 			if (!issuer_cert_file_.empty()) { | 			if (!issuer_cert_file_.empty()) { | ||||||
| 				Poco::Crypto::X509Certificate C1(issuer_cert_file_); | 				Poco::Crypto::X509Certificate C1(issuer_cert_file_); | ||||||
| 				L.information("============================================================================================="); | 				L.information("====================================================================" | ||||||
| 				L.information("============================================================================================="); | 							  "========================="); | ||||||
|  | 				L.information("====================================================================" | ||||||
|  | 							  "========================="); | ||||||
| 				L.information(fmt::format("Issues Certificate Filename: {}", issuer_cert_file_)); | 				L.information(fmt::format("Issues Certificate Filename: {}", issuer_cert_file_)); | ||||||
| 				LogCertInfo(L, C1); | 				LogCertInfo(L, C1); | ||||||
| 				L.information("============================================================================================="); | 				L.information("====================================================================" | ||||||
|  | 							  "========================="); | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			if (!client_cas_.empty()) { | 			if (!client_cas_.empty()) { | ||||||
| 				std::vector<Poco::Crypto::X509Certificate> Certs = | 				std::vector<Poco::Crypto::X509Certificate> Certs = | ||||||
| 					Poco::Net::X509Certificate::readPEM(client_cas_); | 					Poco::Net::X509Certificate::readPEM(client_cas_); | ||||||
|  |  | ||||||
| 				L.information("============================================================================================="); | 				L.information("====================================================================" | ||||||
| 				L.information("============================================================================================="); | 							  "========================="); | ||||||
|  | 				L.information("====================================================================" | ||||||
|  | 							  "========================="); | ||||||
| 				L.information(fmt::format("Client CAs Filename: {}", client_cas_)); | 				L.information(fmt::format("Client CAs Filename: {}", client_cas_)); | ||||||
| 				L.information("============================================================================================="); | 				L.information("====================================================================" | ||||||
|  | 							  "========================="); | ||||||
| 				auto i = 1; | 				auto i = 1; | ||||||
| 				for (const auto &C3 : Certs) { | 				for (const auto &C3 : Certs) { | ||||||
| 					L.information(fmt::format(" Index: {}", i)); | 					L.information(fmt::format(" Index: {}", i)); | ||||||
| 					L.information("============================================================================================="); | 					L.information("================================================================" | ||||||
|  | 								  "============================="); | ||||||
| 					LogCertInfo(L, C3); | 					LogCertInfo(L, C3); | ||||||
| 					i++; | 					i++; | ||||||
| 				} | 				} | ||||||
| 				L.information("============================================================================================="); | 				L.information("====================================================================" | ||||||
|  | 							  "========================="); | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 		} catch (const Poco::Exception &E) { | 		} catch (const Poco::Exception &E) { | ||||||
| @@ -230,28 +247,31 @@ namespace OpenWifi { | |||||||
| 			std::vector<Poco::Crypto::X509Certificate> Certs = | 			std::vector<Poco::Crypto::X509Certificate> Certs = | ||||||
| 				Poco::Net::X509Certificate::readPEM(root_ca_); | 				Poco::Net::X509Certificate::readPEM(root_ca_); | ||||||
|  |  | ||||||
| 			L.information("============================================================================================="); | 			L.information("========================================================================" | ||||||
| 			L.information("============================================================================================="); | 						  "====================="); | ||||||
|  | 			L.information("========================================================================" | ||||||
|  | 						  "====================="); | ||||||
| 			L.information(fmt::format("CA Filename: {}", root_ca_)); | 			L.information(fmt::format("CA Filename: {}", root_ca_)); | ||||||
| 			L.information("============================================================================================="); | 			L.information("========================================================================" | ||||||
|  | 						  "====================="); | ||||||
| 			auto i = 1; | 			auto i = 1; | ||||||
| 			for (const auto &C : Certs) { | 			for (const auto &C : Certs) { | ||||||
| 				L.information(fmt::format(" Index: {}", i)); | 				L.information(fmt::format(" Index: {}", i)); | ||||||
| 				L.information("============================================================================================="); | 				L.information("====================================================================" | ||||||
|  | 							  "========================="); | ||||||
| 				LogCertInfo(L, C); | 				LogCertInfo(L, C); | ||||||
| 				i++; | 				i++; | ||||||
| 			} | 			} | ||||||
| 			L.information("============================================================================================="); | 			L.information("========================================================================" | ||||||
|  | 						  "====================="); | ||||||
| 		} catch (const Poco::Exception &E) { | 		} catch (const Poco::Exception &E) { | ||||||
| 			L.log(E); | 			L.log(E); | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	SubSystemServer::SubSystemServer(const std::string &Name, const std::string &LoggingPrefix, | 	SubSystemServer::SubSystemServer(const std::string &Name, const std::string &LoggingPrefix, | ||||||
| 											const std::string &SubSystemConfigPrefix): | 									 const std::string &SubSystemConfigPrefix) | ||||||
| 		Name_(Name), | 		: Name_(Name), LoggerPrefix_(LoggingPrefix), SubSystemConfigPrefix_(SubSystemConfigPrefix) { | ||||||
| 		LoggerPrefix_(LoggingPrefix), |  | ||||||
| 		SubSystemConfigPrefix_(SubSystemConfigPrefix) { |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void SubSystemServer::initialize([[maybe_unused]] Poco::Util::Application &self) { | 	void SubSystemServer::initialize([[maybe_unused]] Poco::Util::Application &self) { | ||||||
| @@ -259,10 +279,13 @@ namespace OpenWifi { | |||||||
| 		bool good = true; | 		bool good = true; | ||||||
|  |  | ||||||
| 		auto NewLevel = MicroServiceConfigGetString("logging.level." + Name_, ""); | 		auto NewLevel = MicroServiceConfigGetString("logging.level." + Name_, ""); | ||||||
| 		if(NewLevel.empty()) | 		if (NewLevel.empty()) | ||||||
| 			Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel())); | 			Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create( | ||||||
|  | 				LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel())); | ||||||
| 		else | 		else | ||||||
| 			Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::parseLevel(NewLevel))); | 			Logger_ = std::make_unique<LoggerWrapper>( | ||||||
|  | 				Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(), | ||||||
|  | 									 Poco::Logger::parseLevel(NewLevel))); | ||||||
|  |  | ||||||
| 		ConfigServersList_.clear(); | 		ConfigServersList_.clear(); | ||||||
| 		while (good) { | 		while (good) { | ||||||
| @@ -297,14 +320,11 @@ namespace OpenWifi { | |||||||
| 				} else if (L == "once") | 				} else if (L == "once") | ||||||
| 					M = Poco::Net::Context::VERIFY_ONCE; | 					M = Poco::Net::Context::VERIFY_ONCE; | ||||||
|  |  | ||||||
| 				PropertiesFileServerEntry entry(MicroServiceConfigGetString(address, ""), | 				PropertiesFileServerEntry entry( | ||||||
| 												MicroServiceConfigGetInt(port, 0), | 					MicroServiceConfigGetString(address, ""), MicroServiceConfigGetInt(port, 0), | ||||||
| 												MicroServiceConfigPath(key, ""), | 					MicroServiceConfigPath(key, ""), MicroServiceConfigPath(cert, ""), | ||||||
| 												MicroServiceConfigPath(cert, ""), | 					MicroServiceConfigPath(rootca, ""), MicroServiceConfigPath(issuer, ""), | ||||||
| 												MicroServiceConfigPath(rootca, ""), | 					MicroServiceConfigPath(clientcas, ""), MicroServiceConfigPath(cas, ""), | ||||||
| 												MicroServiceConfigPath(issuer, ""), |  | ||||||
| 												MicroServiceConfigPath(clientcas, ""), |  | ||||||
| 												MicroServiceConfigPath(cas, ""), |  | ||||||
| 					MicroServiceConfigGetString(key_password, ""), | 					MicroServiceConfigGetString(key_password, ""), | ||||||
| 					MicroServiceConfigGetString(name, ""), M, | 					MicroServiceConfigGetString(name, ""), M, | ||||||
| 					(int)MicroServiceConfigGetInt(backlog, 64)); | 					(int)MicroServiceConfigGetInt(backlog, 64)); | ||||||
| @@ -314,7 +334,4 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|  |  | ||||||
|  |  | ||||||
|  |  | ||||||
| } // namespace OpenWifi | } // namespace OpenWifi | ||||||
| @@ -4,32 +4,30 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include <string> |  | ||||||
| #include <mutex> | #include <mutex> | ||||||
|  | #include <string> | ||||||
|  |  | ||||||
| #include "Poco/Util/Application.h" |  | ||||||
| #include "Poco/Net/Context.h" | #include "Poco/Net/Context.h" | ||||||
| #include "Poco/Net/SecureServerSocket.h" |  | ||||||
| #include "Poco/Net/PrivateKeyPassphraseHandler.h" | #include "Poco/Net/PrivateKeyPassphraseHandler.h" | ||||||
|  | #include "Poco/Net/SecureServerSocket.h" | ||||||
|  | #include "Poco/Util/Application.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	class MyPrivateKeyPassphraseHandler : public Poco::Net::PrivateKeyPassphraseHandler { | 	class MyPrivateKeyPassphraseHandler : public Poco::Net::PrivateKeyPassphraseHandler { | ||||||
| 	  public: | 	  public: | ||||||
| 		explicit MyPrivateKeyPassphraseHandler(const std::string &Password, Poco::Logger & Logger): | 		explicit MyPrivateKeyPassphraseHandler(const std::string &Password, Poco::Logger &Logger) | ||||||
| 			PrivateKeyPassphraseHandler(true), | 			: PrivateKeyPassphraseHandler(true), Password_(Password), Logger_(Logger) {} | ||||||
| 			Password_(Password), |  | ||||||
| 			Logger_(Logger) { |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		void onPrivateKeyRequested([[maybe_unused]] const void * pSender,std::string & privateKey) { | 		void onPrivateKeyRequested([[maybe_unused]] const void *pSender, std::string &privateKey) { | ||||||
| 			poco_information(Logger_,"Returning key passphrase."); | 			poco_information(Logger_, "Returning key passphrase."); | ||||||
| 			privateKey = Password_; | 			privateKey = Password_; | ||||||
| 		}; | 		}; | ||||||
| 		inline Poco::Logger & Logger() { return Logger_; } | 		inline Poco::Logger &Logger() { return Logger_; } | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		std::string Password_; | 		std::string Password_; | ||||||
| 		Poco::Logger & Logger_; | 		Poco::Logger &Logger_; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	class PropertiesFileServerEntry { | 	class PropertiesFileServerEntry { | ||||||
| @@ -76,24 +74,24 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	class SubSystemServer : public Poco::Util::Application::Subsystem { | 	class SubSystemServer : public Poco::Util::Application::Subsystem { | ||||||
| 	  public: | 	  public: | ||||||
| 		SubSystemServer(const std::string & Name, const std::string &LoggingPrefix, | 		SubSystemServer(const std::string &Name, const std::string &LoggingPrefix, | ||||||
| 						const std::string & SubSystemConfigPrefix); | 						const std::string &SubSystemConfigPrefix); | ||||||
|  |  | ||||||
| 		void initialize(Poco::Util::Application &self) override; | 		void initialize(Poco::Util::Application &self) override; | ||||||
| 		inline void uninitialize() override { | 		inline void uninitialize() override {} | ||||||
| 		} |  | ||||||
| 		inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { | 		inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { | ||||||
| 			poco_information(Logger_->L_,"Reloading of this subsystem is not supported."); | 			poco_information(Logger_->L_, "Reloading of this subsystem is not supported."); | ||||||
| 		} | 		} | ||||||
| 		inline void defineOptions([[maybe_unused]] Poco::Util::OptionSet &options) override { | 		inline void defineOptions([[maybe_unused]] Poco::Util::OptionSet &options) override {} | ||||||
| 		} | 		inline const std::string &Name() const { return Name_; }; | ||||||
| 		inline const std::string & Name() const { return Name_; }; | 		inline const char *name() const override { return Name_.c_str(); } | ||||||
| 		inline const char * name() const override { return Name_.c_str(); } |  | ||||||
|  |  | ||||||
| 		inline const PropertiesFileServerEntry & Host(uint64_t index) { return ConfigServersList_[index]; }; | 		inline const PropertiesFileServerEntry &Host(uint64_t index) { | ||||||
|  | 			return ConfigServersList_[index]; | ||||||
|  | 		}; | ||||||
| 		inline uint64_t HostSize() const { return ConfigServersList_.size(); } | 		inline uint64_t HostSize() const { return ConfigServersList_.size(); } | ||||||
| 		inline Poco::Logger & Logger() const { return Logger_->L_; } | 		inline Poco::Logger &Logger() const { return Logger_->L_; } | ||||||
| 		inline void SetLoggingLevel(const std::string & levelName) { | 		inline void SetLoggingLevel(const std::string &levelName) { | ||||||
| 			Logger_->L_.setLevel(Poco::Logger::parseLevel(levelName)); | 			Logger_->L_.setLevel(Poco::Logger::parseLevel(levelName)); | ||||||
| 		} | 		} | ||||||
| 		inline int GetLoggingLevel() { return Logger_->L_.getLevel(); } | 		inline int GetLoggingLevel() { return Logger_->L_.getLevel(); } | ||||||
| @@ -102,10 +100,8 @@ namespace OpenWifi { | |||||||
| 		virtual void Stop() = 0; | 		virtual void Stop() = 0; | ||||||
|  |  | ||||||
| 		struct LoggerWrapper { | 		struct LoggerWrapper { | ||||||
| 			Poco::Logger & L_; | 			Poco::Logger &L_; | ||||||
| 			LoggerWrapper(Poco::Logger &L) : | 			LoggerWrapper(Poco::Logger &L) : L_(L) {} | ||||||
|  				L_(L) { |  | ||||||
| 			} |  | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
| 	  protected: | 	  protected: | ||||||
|   | |||||||
| @@ -5,7 +5,4 @@ | |||||||
| #include "framework/UI_WebSocketClientNotifications.h" | #include "framework/UI_WebSocketClientNotifications.h" | ||||||
| #include "framework/UI_WebSocketClientServer.h" | #include "framework/UI_WebSocketClientServer.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi {} | ||||||
|  |  | ||||||
| } |  | ||||||
|  |  | ||||||
|   | |||||||
| @@ -9,12 +9,12 @@ | |||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
|     template<typename ContentStruct> | 	template <typename ContentStruct> | ||||||
|  |  | ||||||
| 	struct WebSocketNotification { | 	struct WebSocketNotification { | ||||||
| 		inline static uint64_t xid = 1; | 		inline static uint64_t xid = 1; | ||||||
| 		uint64_t notification_id = ++xid; | 		uint64_t notification_id = ++xid; | ||||||
| 		std::uint64_t 	type_id=0; | 		std::uint64_t type_id = 0; | ||||||
| 		ContentStruct content; | 		ContentStruct content; | ||||||
|  |  | ||||||
| 		void to_json(Poco::JSON::Object &Obj) const; | 		void to_json(Poco::JSON::Object &Obj) const; | ||||||
| @@ -22,14 +22,14 @@ namespace OpenWifi { | |||||||
| 		bool from_json(const Poco::JSON::Object::Ptr &Obj); | 		bool from_json(const Poco::JSON::Object::Ptr &Obj); | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
|     template<typename ContentStruct> | 	template <typename ContentStruct> | ||||||
| 	void WebSocketNotification<ContentStruct>::to_json(Poco::JSON::Object &Obj) const { | 	void WebSocketNotification<ContentStruct>::to_json(Poco::JSON::Object &Obj) const { | ||||||
| 		RESTAPI_utils::field_to_json(Obj, "notification_id", notification_id); | 		RESTAPI_utils::field_to_json(Obj, "notification_id", notification_id); | ||||||
| 		RESTAPI_utils::field_to_json(Obj, "type_id", type_id); | 		RESTAPI_utils::field_to_json(Obj, "type_id", type_id); | ||||||
| 		RESTAPI_utils::field_to_json(Obj, "content", content); | 		RESTAPI_utils::field_to_json(Obj, "content", content); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     template<typename ContentStruct> | 	template <typename ContentStruct> | ||||||
| 	bool WebSocketNotification<ContentStruct>::from_json(const Poco::JSON::Object::Ptr &Obj) { | 	bool WebSocketNotification<ContentStruct>::from_json(const Poco::JSON::Object::Ptr &Obj) { | ||||||
| 		try { | 		try { | ||||||
| 			RESTAPI_utils::field_from_json(Obj, "notification_id", notification_id); | 			RESTAPI_utils::field_from_json(Obj, "notification_id", notification_id); | ||||||
| @@ -37,9 +37,7 @@ namespace OpenWifi { | |||||||
| 			RESTAPI_utils::field_from_json(Obj, "content", content); | 			RESTAPI_utils::field_from_json(Obj, "content", content); | ||||||
| 			return true; | 			return true; | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return false; | 		return false; | ||||||
| 	} | 	} | ||||||
| } | } // namespace OpenWifi | ||||||
|  |  | ||||||
|   | |||||||
| @@ -4,14 +4,14 @@ | |||||||
|  |  | ||||||
| #include <mutex> | #include <mutex> | ||||||
|  |  | ||||||
| #include "Poco/NObserver.h" |  | ||||||
| #include "Poco/JSON/JSONException.h" | #include "Poco/JSON/JSONException.h" | ||||||
| #include "Poco/JSON/Parser.h" | #include "Poco/JSON/Parser.h" | ||||||
| #include "Poco/Logger.h" | #include "Poco/Logger.h" | ||||||
|  | #include "Poco/NObserver.h" | ||||||
|  |  | ||||||
| #include "framework/UI_WebSocketClientServer.h" |  | ||||||
| #include "framework/AuthClient.h" | #include "framework/AuthClient.h" | ||||||
| #include "framework/MicroServiceFuncs.h" | #include "framework/MicroServiceFuncs.h" | ||||||
|  | #include "framework/UI_WebSocketClientServer.h" | ||||||
|  |  | ||||||
| #include "fmt/format.h" | #include "fmt/format.h" | ||||||
|  |  | ||||||
| @@ -19,80 +19,82 @@ | |||||||
| #include "AuthService.h" | #include "AuthService.h" | ||||||
| #endif | #endif | ||||||
|  |  | ||||||
| #define DBG { std::cout << __LINE__ << std::endl; } | #define DBG                                                                                        \ | ||||||
|  | 	{ std::cout << __LINE__ << std::endl; } | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	void UI_WebSocketClientServer::NewClient(Poco::Net::WebSocket & WS, const std::string &Id, const std::string &UserName, std::uint64_t TID ) { | 	void UI_WebSocketClientServer::NewClient(Poco::Net::WebSocket &WS, const std::string &Id, | ||||||
|  | 											 const std::string &UserName, std::uint64_t TID) { | ||||||
|  |  | ||||||
| 		std::lock_guard G(LocalMutex_); | 		std::lock_guard G(LocalMutex_); | ||||||
|         auto Client = std::make_unique<UI_WebSocketClientInfo>(WS,Id, UserName); | 		auto Client = std::make_unique<UI_WebSocketClientInfo>(WS, Id, UserName); | ||||||
| 		auto ClientSocket = Client->WS_->impl()->sockfd(); | 		auto ClientSocket = Client->WS_->impl()->sockfd(); | ||||||
| 		TID_ = TID; | 		TID_ = TID; | ||||||
| 		Client->WS_->setNoDelay(true); | 		Client->WS_->setNoDelay(true); | ||||||
| 		Client->WS_->setKeepAlive(true); | 		Client->WS_->setKeepAlive(true); | ||||||
| 		Client->WS_->setBlocking(false); | 		Client->WS_->setBlocking(false); | ||||||
|         Reactor_.addEventHandler(*Client->WS_, | 		Reactor_.addEventHandler( | ||||||
|  | 			*Client->WS_, | ||||||
| 			Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ReadableNotification>( | 			Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ReadableNotification>( | ||||||
| 				*this, &UI_WebSocketClientServer::OnSocketReadable)); | 				*this, &UI_WebSocketClientServer::OnSocketReadable)); | ||||||
|         Reactor_.addEventHandler(*Client->WS_, | 		Reactor_.addEventHandler( | ||||||
|  | 			*Client->WS_, | ||||||
| 			Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ShutdownNotification>( | 			Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ShutdownNotification>( | ||||||
| 				*this, &UI_WebSocketClientServer::OnSocketShutdown)); | 				*this, &UI_WebSocketClientServer::OnSocketShutdown)); | ||||||
|         Reactor_.addEventHandler(*Client->WS_, | 		Reactor_.addEventHandler( | ||||||
|                                  Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ErrorNotification>( | 			*Client->WS_, Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ErrorNotification>( | ||||||
| 							  *this, &UI_WebSocketClientServer::OnSocketError)); | 							  *this, &UI_WebSocketClientServer::OnSocketError)); | ||||||
| 		Client->SocketRegistered_ = true; | 		Client->SocketRegistered_ = true; | ||||||
| 		Clients_[ClientSocket] = std::move(Client); | 		Clients_[ClientSocket] = std::move(Client); | ||||||
| 		UsersConnected_ = Clients_.size(); | 		UsersConnected_ = Clients_.size(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void UI_WebSocketClientServer::SetProcessor( UI_WebSocketClientProcessor * F) { | 	void UI_WebSocketClientServer::SetProcessor(UI_WebSocketClientProcessor *F) { Processor_ = F; } | ||||||
| 		Processor_ = F; |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	UI_WebSocketClientServer::UI_WebSocketClientServer() noexcept: | 	UI_WebSocketClientServer::UI_WebSocketClientServer() noexcept | ||||||
| 		 SubSystemServer("WebSocketClientServer", "UI-WSCLNT-SVR", "websocketclients") | 		: SubSystemServer("WebSocketClientServer", "UI-WSCLNT-SVR", "websocketclients") {} | ||||||
| 	{ |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	void UI_WebSocketClientServer::run() { | 	void UI_WebSocketClientServer::run() { | ||||||
| 		Running_ = true; | 		Running_ = true; | ||||||
| 		while(Running_) { | 		while (Running_) { | ||||||
| 			Poco::Thread::trySleep(2000); | 			Poco::Thread::trySleep(2000); | ||||||
|  |  | ||||||
| 			if(!Running_) | 			if (!Running_) | ||||||
| 				break; | 				break; | ||||||
|  |  | ||||||
| 			std::lock_guard G(LocalMutex_); | 			std::lock_guard G(LocalMutex_); | ||||||
| 			for(const auto i:ToBeRemoved_) { | 			for (const auto i : ToBeRemoved_) { | ||||||
| 				// std::cout << "Erasing old WS UI connection..." << std::endl; | 				// std::cout << "Erasing old WS UI connection..." << std::endl; | ||||||
| 				Clients_.erase(i); | 				Clients_.erase(i); | ||||||
| 			} | 			} | ||||||
| 			ToBeRemoved_.clear(); | 			ToBeRemoved_.clear(); | ||||||
| 			UsersConnected_ = Clients_.size(); | 			UsersConnected_ = Clients_.size(); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void UI_WebSocketClientServer::EndConnection(ClientList::iterator Client) { | 	void UI_WebSocketClientServer::EndConnection(ClientList::iterator Client) { | ||||||
|         if(Client->second->SocketRegistered_) { | 		if (Client->second->SocketRegistered_) { | ||||||
| 			Client->second->SocketRegistered_ = false; | 			Client->second->SocketRegistered_ = false; | ||||||
|             Reactor_.removeEventHandler(*Client->second->WS_, | 			Reactor_.removeEventHandler( | ||||||
|                                         Poco::NObserver<UI_WebSocketClientServer, | 				*Client->second->WS_, | ||||||
|                                                 Poco::Net::ReadableNotification>(*this,&UI_WebSocketClientServer::OnSocketReadable)); | 				Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ReadableNotification>( | ||||||
|             Reactor_.removeEventHandler(*Client->second->WS_, | 					*this, &UI_WebSocketClientServer::OnSocketReadable)); | ||||||
|                                         Poco::NObserver<UI_WebSocketClientServer, | 			Reactor_.removeEventHandler( | ||||||
|                                                 Poco::Net::ShutdownNotification>(*this,&UI_WebSocketClientServer::OnSocketShutdown)); | 				*Client->second->WS_, | ||||||
|             Reactor_.removeEventHandler(*Client->second->WS_, | 				Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ShutdownNotification>( | ||||||
|                                         Poco::NObserver<UI_WebSocketClientServer, | 					*this, &UI_WebSocketClientServer::OnSocketShutdown)); | ||||||
|                                                 Poco::Net::ErrorNotification>(*this,&UI_WebSocketClientServer::OnSocketError)); | 			Reactor_.removeEventHandler( | ||||||
|  | 				*Client->second->WS_, | ||||||
|  | 				Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ErrorNotification>( | ||||||
|  | 					*this, &UI_WebSocketClientServer::OnSocketError)); | ||||||
| 		} | 		} | ||||||
| 		ToBeRemoved_.push_back(Client); | 		ToBeRemoved_.push_back(Client); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	int UI_WebSocketClientServer::Start() { | 	int UI_WebSocketClientServer::Start() { | ||||||
|         poco_information(Logger(),"Starting..."); | 		poco_information(Logger(), "Starting..."); | ||||||
| 		GoogleApiKey_ = MicroServiceConfigGetString("google.apikey",""); | 		GoogleApiKey_ = MicroServiceConfigGetString("google.apikey", ""); | ||||||
| 		GeoCodeEnabled_ = !GoogleApiKey_.empty(); | 		GeoCodeEnabled_ = !GoogleApiKey_.empty(); | ||||||
| 		ReactorThread_.start(Reactor_); | 		ReactorThread_.start(Reactor_); | ||||||
| 		ReactorThread_.setName("ws:ui-reactor"); | 		ReactorThread_.setName("ws:ui-reactor"); | ||||||
| @@ -102,29 +104,31 @@ namespace OpenWifi { | |||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	void UI_WebSocketClientServer::Stop() { | 	void UI_WebSocketClientServer::Stop() { | ||||||
| 		if(Running_) { | 		if (Running_) { | ||||||
|             poco_information(Logger(),"Stopping..."); | 			poco_information(Logger(), "Stopping..."); | ||||||
| 			Clients_.clear(); | 			Clients_.clear(); | ||||||
| 			Reactor_.stop(); | 			Reactor_.stop(); | ||||||
| 			ReactorThread_.join(); | 			ReactorThread_.join(); | ||||||
| 			Running_ = false; | 			Running_ = false; | ||||||
| 			CleanerThread_.wakeUp(); | 			CleanerThread_.wakeUp(); | ||||||
| 			CleanerThread_.join(); | 			CleanerThread_.join(); | ||||||
|             poco_information(Logger(),"Stopped..."); | 			poco_information(Logger(), "Stopped..."); | ||||||
| 		} | 		} | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	bool UI_WebSocketClientServer::IsFiltered(std::uint64_t id, const OpenWifi::UI_WebSocketClientInfo &Client) { | 	bool UI_WebSocketClientServer::IsFiltered(std::uint64_t id, | ||||||
| 		return std::find(Client.Filter_.begin(), Client.Filter_.end(),id)!=end(Client.Filter_); | 											  const OpenWifi::UI_WebSocketClientInfo &Client) { | ||||||
|  | 		return std::find(Client.Filter_.begin(), Client.Filter_.end(), id) != end(Client.Filter_); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	bool UI_WebSocketClientServer::SendToUser(const std::string &UserName, std::uint64_t id, const std::string &Payload) { | 	bool UI_WebSocketClientServer::SendToUser(const std::string &UserName, std::uint64_t id, | ||||||
|  | 											  const std::string &Payload) { | ||||||
| 		std::lock_guard G(LocalMutex_); | 		std::lock_guard G(LocalMutex_); | ||||||
|  |  | ||||||
| 		for(const auto &Client:Clients_) { | 		for (const auto &Client : Clients_) { | ||||||
| 			if(Client.second->UserName_ == UserName) { | 			if (Client.second->UserName_ == UserName) { | ||||||
| 				try { | 				try { | ||||||
| 					if(!IsFiltered(id,*Client.second) && Client.second->Authenticated_) { | 					if (!IsFiltered(id, *Client.second) && Client.second->Authenticated_) { | ||||||
| 						return Client.second->WS_->sendFrame( | 						return Client.second->WS_->sendFrame( | ||||||
| 								   Payload.c_str(), (int)Payload.size()) == (int)Payload.size(); | 								   Payload.c_str(), (int)Payload.size()) == (int)Payload.size(); | ||||||
| 					} else { | 					} else { | ||||||
| @@ -141,30 +145,31 @@ namespace OpenWifi { | |||||||
| 	void UI_WebSocketClientServer::SendToAll(std::uint64_t id, const std::string &Payload) { | 	void UI_WebSocketClientServer::SendToAll(std::uint64_t id, const std::string &Payload) { | ||||||
| 		std::lock_guard G(LocalMutex_); | 		std::lock_guard G(LocalMutex_); | ||||||
|  |  | ||||||
| 		for(const auto &Client:Clients_) { | 		for (const auto &Client : Clients_) { | ||||||
| 			try { | 			try { | ||||||
| 				if(!IsFiltered(id,*Client.second) && Client.second->Authenticated_) | 				if (!IsFiltered(id, *Client.second) && Client.second->Authenticated_) | ||||||
| 					Client.second->WS_->sendFrame(Payload.c_str(),(int)Payload.size()); | 					Client.second->WS_->sendFrame(Payload.c_str(), (int)Payload.size()); | ||||||
| 			} catch (...) { | 			} catch (...) { | ||||||
|  |  | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     UI_WebSocketClientServer::ClientList::iterator UI_WebSocketClientServer::FindWSClient( [[maybe_unused]]  std::lock_guard<std::recursive_mutex> &G, int ClientSocket) { | 	UI_WebSocketClientServer::ClientList::iterator UI_WebSocketClientServer::FindWSClient( | ||||||
|  | 		[[maybe_unused]] std::lock_guard<std::recursive_mutex> &G, int ClientSocket) { | ||||||
| 		return Clients_.find(ClientSocket); | 		return Clients_.find(ClientSocket); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void UI_WebSocketClientServer::SortNotifications() { | 	void UI_WebSocketClientServer::SortNotifications() { | ||||||
| 		struct { | 		struct { | ||||||
| 			bool operator()(const NotificationEntry &A, const NotificationEntry & B) const { | 			bool operator()(const NotificationEntry &A, const NotificationEntry &B) const { | ||||||
| 				return A.id < B.id; }; | 				return A.id < B.id; | ||||||
|  | 			}; | ||||||
| 		} CompareNotifications; | 		} CompareNotifications; | ||||||
| 		std::sort(NotificationTypes_.begin(), NotificationTypes_.end(), CompareNotifications); | 		std::sort(NotificationTypes_.begin(), NotificationTypes_.end(), CompareNotifications); | ||||||
|  |  | ||||||
| 		NotificationTypesJSON_.clear(); | 		NotificationTypesJSON_.clear(); | ||||||
| 		Poco::JSON::Array AllNotifications; | 		Poco::JSON::Array AllNotifications; | ||||||
| 		for(const auto ¬ification:NotificationTypes_) { | 		for (const auto ¬ification : NotificationTypes_) { | ||||||
| 			Poco::JSON::Object Notification; | 			Poco::JSON::Object Notification; | ||||||
| 			Notification.set("id", notification.id); | 			Notification.set("id", notification.id); | ||||||
| 			Notification.set("helper", notification.helper); | 			Notification.set("helper", notification.helper); | ||||||
| @@ -173,20 +178,24 @@ namespace OpenWifi { | |||||||
| 		NotificationTypesJSON_.set("notificationTypes", AllNotifications); | 		NotificationTypesJSON_.set("notificationTypes", AllNotifications); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void UI_WebSocketClientServer::RegisterNotifications(const OpenWifi::UI_WebSocketClientServer::NotificationTypeIdVec &Notifications) { | 	void UI_WebSocketClientServer::RegisterNotifications( | ||||||
| 		std::copy(Notifications.begin(), Notifications.end(), std::back_inserter(NotificationTypes_)); | 		const OpenWifi::UI_WebSocketClientServer::NotificationTypeIdVec &Notifications) { | ||||||
|  | 		std::copy(Notifications.begin(), Notifications.end(), | ||||||
|  | 				  std::back_inserter(NotificationTypes_)); | ||||||
| 		SortNotifications(); | 		SortNotifications(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|     void UI_WebSocketClientServer::OnSocketError([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf) { | 	void UI_WebSocketClientServer::OnSocketError( | ||||||
|  | 		[[maybe_unused]] const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf) { | ||||||
| 		std::lock_guard G(LocalMutex_); | 		std::lock_guard G(LocalMutex_); | ||||||
| 		auto Client = Clients_.find(pNf->socket().impl()->sockfd()); | 		auto Client = Clients_.find(pNf->socket().impl()->sockfd()); | ||||||
|         if(Client==end(Clients_)) | 		if (Client == end(Clients_)) | ||||||
| 			return; | 			return; | ||||||
| 		EndConnection(Client); | 		EndConnection(Client); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void UI_WebSocketClientServer::OnSocketReadable([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf) { | 	void UI_WebSocketClientServer::OnSocketReadable( | ||||||
|  | 		[[maybe_unused]] const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf) { | ||||||
|  |  | ||||||
| 		UI_WebSocketClientServer::ClientList::iterator Client; | 		UI_WebSocketClientServer::ClientList::iterator Client; | ||||||
| 		std::lock_guard G(LocalMutex_); | 		std::lock_guard G(LocalMutex_); | ||||||
| @@ -194,7 +203,7 @@ namespace OpenWifi { | |||||||
| 		try { | 		try { | ||||||
|  |  | ||||||
| 			Client = Clients_.find(pNf->socket().impl()->sockfd()); | 			Client = Clients_.find(pNf->socket().impl()->sockfd()); | ||||||
|             if( Client == end(Clients_)) | 			if (Client == end(Clients_)) | ||||||
| 				return; | 				return; | ||||||
|  |  | ||||||
| 			Poco::Buffer<char> IncomingFrame(0); | 			Poco::Buffer<char> IncomingFrame(0); | ||||||
| @@ -204,7 +213,9 @@ namespace OpenWifi { | |||||||
| 			auto Op = flags & Poco::Net::WebSocket::FRAME_OP_BITMASK; | 			auto Op = flags & Poco::Net::WebSocket::FRAME_OP_BITMASK; | ||||||
|  |  | ||||||
| 			if (n == 0) { | 			if (n == 0) { | ||||||
| 				poco_debug(Logger(),fmt::format("CLOSE({}): {} UI Client is closing WS connection.", Client->second->Id_, Client->second->UserName_)); | 				poco_debug(Logger(), | ||||||
|  | 						   fmt::format("CLOSE({}): {} UI Client is closing WS connection.", | ||||||
|  | 									   Client->second->Id_, Client->second->UserName_)); | ||||||
| 				return EndConnection(Client); | 				return EndConnection(Client); | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| @@ -217,7 +228,9 @@ namespace OpenWifi { | |||||||
| 			case Poco::Net::WebSocket::FRAME_OP_PONG: { | 			case Poco::Net::WebSocket::FRAME_OP_PONG: { | ||||||
| 			} break; | 			} break; | ||||||
| 			case Poco::Net::WebSocket::FRAME_OP_CLOSE: { | 			case Poco::Net::WebSocket::FRAME_OP_CLOSE: { | ||||||
| 				poco_debug(Logger(),fmt::format("CLOSE({}): {} UI Client is closing WS connection.", Client->second->Id_, Client->second->UserName_)); | 				poco_debug(Logger(), | ||||||
|  | 						   fmt::format("CLOSE({}): {} UI Client is closing WS connection.", | ||||||
|  | 									   Client->second->Id_, Client->second->UserName_)); | ||||||
| 				return EndConnection(Client); | 				return EndConnection(Client); | ||||||
| 			} break; | 			} break; | ||||||
| 			case Poco::Net::WebSocket::FRAME_OP_TEXT: { | 			case Poco::Net::WebSocket::FRAME_OP_TEXT: { | ||||||
| @@ -232,46 +245,50 @@ namespace OpenWifi { | |||||||
| #endif | #endif | ||||||
| 					if (Tokens.size() == 2 && | 					if (Tokens.size() == 2 && | ||||||
| #if defined(TIP_SECURITY_SERVICE) | #if defined(TIP_SECURITY_SERVICE) | ||||||
|         			    AuthService()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_, Expired)) { | 						AuthService()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_, | ||||||
|  | 													Expired)) { | ||||||
| #else | #else | ||||||
|                         AuthClient()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_, Expired, Contacted)) { | 						AuthClient()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_, | ||||||
|  | 												   Expired, Contacted)) { | ||||||
| #endif | #endif | ||||||
| 						Client->second->Authenticated_ = true; | 						Client->second->Authenticated_ = true; | ||||||
| 						Client->second->UserName_ = Client->second->UserInfo_.userinfo.email; | 						Client->second->UserName_ = Client->second->UserInfo_.userinfo.email; | ||||||
| 						poco_debug(Logger(),fmt::format("START({}): {} UI Client is starting WS connection.", Client->second->Id_, Client->second->UserName_)); | 						poco_debug(Logger(), | ||||||
|  | 								   fmt::format("START({}): {} UI Client is starting WS connection.", | ||||||
|  | 											   Client->second->Id_, Client->second->UserName_)); | ||||||
| 						auto WelcomeMessage = NotificationTypesJSON_; | 						auto WelcomeMessage = NotificationTypesJSON_; | ||||||
| 						WelcomeMessage.set("success", "Welcome! Bienvenue! Bienvenidos!"); | 						WelcomeMessage.set("success", "Welcome! Bienvenue! Bienvenidos!"); | ||||||
| 						std::ostringstream OS; | 						std::ostringstream OS; | ||||||
| 						WelcomeMessage.stringify(OS); | 						WelcomeMessage.stringify(OS); | ||||||
| 						Client->second->WS_->sendFrame(OS.str().c_str(), (int) OS.str().size()); | 						Client->second->WS_->sendFrame(OS.str().c_str(), (int)OS.str().size()); | ||||||
| 						Client->second->UserName_ = Client->second->UserInfo_.userinfo.email; | 						Client->second->UserName_ = Client->second->UserInfo_.userinfo.email; | ||||||
| 					} else { | 					} else { | ||||||
| 						Poco::JSON::Object WelcomeMessage; | 						Poco::JSON::Object WelcomeMessage; | ||||||
| 						WelcomeMessage.set("error", "Invalid token. Closing connection."); | 						WelcomeMessage.set("error", "Invalid token. Closing connection."); | ||||||
| 						std::ostringstream OS; | 						std::ostringstream OS; | ||||||
| 						WelcomeMessage.stringify(OS); | 						WelcomeMessage.stringify(OS); | ||||||
| 						Client->second->WS_->sendFrame(OS.str().c_str(), (int) OS.str().size()); | 						Client->second->WS_->sendFrame(OS.str().c_str(), (int)OS.str().size()); | ||||||
| 						return EndConnection(Client); | 						return EndConnection(Client); | ||||||
| 					} | 					} | ||||||
| 				} else { | 				} else { | ||||||
| 					Poco::JSON::Parser P; | 					Poco::JSON::Parser P; | ||||||
|                     auto Obj = | 					auto Obj = P.parse(IncomingFrame.begin()).extract<Poco::JSON::Object::Ptr>(); | ||||||
|                         P.parse(IncomingFrame.begin()).extract<Poco::JSON::Object::Ptr>(); |  | ||||||
|  |  | ||||||
| 					if(Obj->has(DropMessagesCommand) && Obj->isArray(DropMessagesCommand)) { | 					if (Obj->has(DropMessagesCommand) && Obj->isArray(DropMessagesCommand)) { | ||||||
| 						auto Filters = Obj->getArray(DropMessagesCommand); | 						auto Filters = Obj->getArray(DropMessagesCommand); | ||||||
| 						Client->second->Filter_.clear(); | 						Client->second->Filter_.clear(); | ||||||
| 						for(const auto &Filter:*Filters) { | 						for (const auto &Filter : *Filters) { | ||||||
| 							Client->second->Filter_.emplace_back( (std::uint64_t) Filter); | 							Client->second->Filter_.emplace_back((std::uint64_t)Filter); | ||||||
| 						} | 						} | ||||||
| 						std::sort(begin(Client->second->Filter_),end(Client->second->Filter_)); | 						std::sort(begin(Client->second->Filter_), end(Client->second->Filter_)); | ||||||
| 						return; | 						return; | ||||||
| 					} | 					} | ||||||
|  |  | ||||||
| 					std::string Answer; | 					std::string Answer; | ||||||
|                     bool CloseConnection=false; | 					bool CloseConnection = false; | ||||||
| 					if (Processor_ != nullptr) { | 					if (Processor_ != nullptr) { | ||||||
|                         Processor_->Processor(Obj, Answer, CloseConnection,Client->second->UserInfo_.userinfo); | 						Processor_->Processor(Obj, Answer, CloseConnection, | ||||||
|  | 											  Client->second->UserInfo_.userinfo); | ||||||
| 					} | 					} | ||||||
| 					if (!Answer.empty()) | 					if (!Answer.empty()) | ||||||
| 						Client->second->WS_->sendFrame(Answer.c_str(), (int)Answer.size()); | 						Client->second->WS_->sendFrame(Answer.c_str(), (int)Answer.size()); | ||||||
| @@ -279,7 +296,7 @@ namespace OpenWifi { | |||||||
| 						Client->second->WS_->sendFrame("{}", 2); | 						Client->second->WS_->sendFrame("{}", 2); | ||||||
| 					} | 					} | ||||||
|  |  | ||||||
|                     if(CloseConnection) { | 					if (CloseConnection) { | ||||||
| 						return EndConnection(Client); | 						return EndConnection(Client); | ||||||
| 					} | 					} | ||||||
| 				} | 				} | ||||||
| @@ -292,7 +309,8 @@ namespace OpenWifi { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	void UI_WebSocketClientServer::OnSocketShutdown([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf) { | 	void UI_WebSocketClientServer::OnSocketShutdown( | ||||||
|  | 		[[maybe_unused]] const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf) { | ||||||
| 		try { | 		try { | ||||||
| 			std::lock_guard G(LocalMutex_); | 			std::lock_guard G(LocalMutex_); | ||||||
| 			auto Client = Clients_.find(pNf->socket().impl()->sockfd()); | 			auto Client = Clients_.find(pNf->socket().impl()->sockfd()); | ||||||
| @@ -300,7 +318,6 @@ namespace OpenWifi { | |||||||
| 				return; | 				return; | ||||||
| 			EndConnection(Client); | 			EndConnection(Client); | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
|   | |||||||
| @@ -7,11 +7,11 @@ | |||||||
| #include <map> | #include <map> | ||||||
| #include <string> | #include <string> | ||||||
|  |  | ||||||
| #include "Poco/Runnable.h" |  | ||||||
| #include "Poco/Net/SocketReactor.h" |  | ||||||
| #include "Poco/Net/WebSocket.h" |  | ||||||
| #include "Poco/JSON/Object.h" | #include "Poco/JSON/Object.h" | ||||||
| #include "Poco/Net/SocketNotification.h" | #include "Poco/Net/SocketNotification.h" | ||||||
|  | #include "Poco/Net/SocketReactor.h" | ||||||
|  | #include "Poco/Net/WebSocket.h" | ||||||
|  | #include "Poco/Runnable.h" | ||||||
|  |  | ||||||
| #include "RESTObjects/RESTAPI_SecurityObjects.h" | #include "RESTObjects/RESTAPI_SecurityObjects.h" | ||||||
| #include "framework/SubSystemServer.h" | #include "framework/SubSystemServer.h" | ||||||
| @@ -21,7 +21,9 @@ namespace OpenWifi { | |||||||
|  |  | ||||||
| 	class UI_WebSocketClientProcessor { | 	class UI_WebSocketClientProcessor { | ||||||
| 	  public: | 	  public: | ||||||
| 		virtual void Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done , const SecurityObjects::UserInfo & UserInfo) = 0; | 		virtual void Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done, | ||||||
|  | 							   const SecurityObjects::UserInfo &UserInfo) = 0; | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| @@ -30,11 +32,12 @@ namespace OpenWifi { | |||||||
| 		std::string Id_; | 		std::string Id_; | ||||||
| 		std::string UserName_; | 		std::string UserName_; | ||||||
| 		bool Authenticated_ = false; | 		bool Authenticated_ = false; | ||||||
|         bool				                    SocketRegistered_=false; | 		bool SocketRegistered_ = false; | ||||||
| 		std::vector<std::uint64_t> Filter_; | 		std::vector<std::uint64_t> Filter_; | ||||||
| 		SecurityObjects::UserInfoAndPolicy UserInfo_; | 		SecurityObjects::UserInfoAndPolicy UserInfo_; | ||||||
|  |  | ||||||
|         UI_WebSocketClientInfo(Poco::Net::WebSocket &WS, const std::string &Id, const std::string &username) { | 		UI_WebSocketClientInfo(Poco::Net::WebSocket &WS, const std::string &Id, | ||||||
|  | 							   const std::string &username) { | ||||||
| 			WS_ = std::make_unique<Poco::Net::WebSocket>(WS); | 			WS_ = std::make_unique<Poco::Net::WebSocket>(WS); | ||||||
| 			Id_ = Id; | 			Id_ = Id; | ||||||
| 			UserName_ = username; | 			UserName_ = username; | ||||||
| @@ -49,26 +52,26 @@ namespace OpenWifi { | |||||||
| 			return instance_; | 			return instance_; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		bool IsAnyoneConnected() { | 		bool IsAnyoneConnected() { return UsersConnected_; } | ||||||
| 			return UsersConnected_; |  | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		int Start() override; | 		int Start() override; | ||||||
| 		void Stop() override; | 		void Stop() override; | ||||||
| 		void run() override; | 		void run() override; | ||||||
| 		Poco::Net::SocketReactor & Reactor() { return Reactor_; } | 		Poco::Net::SocketReactor &Reactor() { return Reactor_; } | ||||||
| 		void NewClient(Poco::Net::WebSocket &WS, const std::string &Id, const std::string &UserName, std::uint64_t TID); | 		void NewClient(Poco::Net::WebSocket &WS, const std::string &Id, const std::string &UserName, | ||||||
|  | 					   std::uint64_t TID); | ||||||
| 		void SetProcessor(UI_WebSocketClientProcessor *F); | 		void SetProcessor(UI_WebSocketClientProcessor *F); | ||||||
| 		[[nodiscard]] inline bool GeoCodeEnabled() const { return GeoCodeEnabled_; } | 		[[nodiscard]] inline bool GeoCodeEnabled() const { return GeoCodeEnabled_; } | ||||||
| 		[[nodiscard]] inline std::string GoogleApiKey() const { return GoogleApiKey_; } | 		[[nodiscard]] inline std::string GoogleApiKey() const { return GoogleApiKey_; } | ||||||
|  |  | ||||||
| 		template <typename T> bool | 		template <typename T> | ||||||
| 		SendUserNotification(const std::string &userName, const WebSocketNotification<T> &Notification) { | 		bool SendUserNotification(const std::string &userName, | ||||||
|  | 								  const WebSocketNotification<T> &Notification) { | ||||||
|  |  | ||||||
| 			Poco::JSON::Object Payload; | 			Poco::JSON::Object Payload; | ||||||
| 			Notification.to_json(Payload); | 			Notification.to_json(Payload); | ||||||
| 			Poco::JSON::Object Msg; | 			Poco::JSON::Object Msg; | ||||||
| 			Msg.set("notification",Payload); | 			Msg.set("notification", Payload); | ||||||
| 			std::ostringstream OO; | 			std::ostringstream OO; | ||||||
| 			Msg.stringify(OO); | 			Msg.stringify(OO); | ||||||
|  |  | ||||||
| @@ -79,29 +82,30 @@ namespace OpenWifi { | |||||||
| 			Poco::JSON::Object Payload; | 			Poco::JSON::Object Payload; | ||||||
| 			Notification.to_json(Payload); | 			Notification.to_json(Payload); | ||||||
| 			Poco::JSON::Object Msg; | 			Poco::JSON::Object Msg; | ||||||
| 			Msg.set("notification",Payload); | 			Msg.set("notification", Payload); | ||||||
| 			std::ostringstream OO; | 			std::ostringstream OO; | ||||||
| 			Msg.stringify(OO); | 			Msg.stringify(OO); | ||||||
| 			SendToAll(Notification.type_id, OO.str()); | 			SendToAll(Notification.type_id, OO.str()); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		[[nodiscard]] bool SendToUser(const std::string &userName, std::uint64_t id, const std::string &Payload); | 		[[nodiscard]] bool SendToUser(const std::string &userName, std::uint64_t id, | ||||||
|  | 									  const std::string &Payload); | ||||||
| 		void SendToAll(std::uint64_t id, const std::string &Payload); | 		void SendToAll(std::uint64_t id, const std::string &Payload); | ||||||
|  |  | ||||||
| 		struct NotificationEntry { | 		struct NotificationEntry { | ||||||
| 			std::uint64_t 	id=0; | 			std::uint64_t id = 0; | ||||||
| 			std::string helper; | 			std::string helper; | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
|         using ClientList = std::map<int,std::unique_ptr<UI_WebSocketClientInfo>>; | 		using ClientList = std::map<int, std::unique_ptr<UI_WebSocketClientInfo>>; | ||||||
| 		using NotificationTypeIdVec = std::vector<NotificationEntry>; | 		using NotificationTypeIdVec = std::vector<NotificationEntry>; | ||||||
|  |  | ||||||
| 		void RegisterNotifications(const NotificationTypeIdVec & Notifications); | 		void RegisterNotifications(const NotificationTypeIdVec &Notifications); | ||||||
| 		bool IsFiltered(std::uint64_t id, const UI_WebSocketClientInfo &Client); | 		bool IsFiltered(std::uint64_t id, const UI_WebSocketClientInfo &Client); | ||||||
|  |  | ||||||
| 	  private: | 	  private: | ||||||
| 		volatile bool Running_ = false; | 		volatile bool Running_ = false; | ||||||
| 		std::atomic_uint64_t 						UsersConnected_=0; | 		std::atomic_uint64_t UsersConnected_ = 0; | ||||||
| 		Poco::Net::SocketReactor Reactor_; | 		Poco::Net::SocketReactor Reactor_; | ||||||
| 		Poco::Thread ReactorThread_; | 		Poco::Thread ReactorThread_; | ||||||
| 		Poco::Thread CleanerThread_; | 		Poco::Thread CleanerThread_; | ||||||
| @@ -113,7 +117,7 @@ namespace OpenWifi { | |||||||
| 		NotificationTypeIdVec NotificationTypes_; | 		NotificationTypeIdVec NotificationTypes_; | ||||||
| 		Poco::JSON::Object NotificationTypesJSON_; | 		Poco::JSON::Object NotificationTypesJSON_; | ||||||
| 		std::vector<ClientList::iterator> ToBeRemoved_; | 		std::vector<ClientList::iterator> ToBeRemoved_; | ||||||
|         std::uint64_t                               TID_=0; | 		std::uint64_t TID_ = 0; | ||||||
|  |  | ||||||
| 		UI_WebSocketClientServer() noexcept; | 		UI_WebSocketClientServer() noexcept; | ||||||
| 		void EndConnection(ClientList::iterator Client); | 		void EndConnection(ClientList::iterator Client); | ||||||
| @@ -122,12 +126,12 @@ namespace OpenWifi { | |||||||
| 		void OnSocketShutdown(const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf); | 		void OnSocketShutdown(const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf); | ||||||
| 		void OnSocketError(const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf); | 		void OnSocketError(const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf); | ||||||
|  |  | ||||||
|         ClientList::iterator FindWSClient( std::lock_guard<std::recursive_mutex> &G, int ClientSocket); | 		ClientList::iterator FindWSClient(std::lock_guard<std::recursive_mutex> &G, | ||||||
|  | 										  int ClientSocket); | ||||||
|  |  | ||||||
| 		void SortNotifications(); | 		void SortNotifications(); | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	inline auto UI_WebSocketClientServer() { return UI_WebSocketClientServer::instance(); } | 	inline auto UI_WebSocketClientServer() { return UI_WebSocketClientServer::instance(); } | ||||||
|  |  | ||||||
| }; | }; // namespace OpenWifi | ||||||
|  |  | ||||||
|   | |||||||
| @@ -5,43 +5,46 @@ | |||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include "framework/SubSystemServer.h" | #include "framework/SubSystemServer.h" | ||||||
| #include "framework/UI_WebSocketClientServer.h" |  | ||||||
| #include "framework/UI_WebSocketClientNotifications.h" | #include "framework/UI_WebSocketClientNotifications.h" | ||||||
|  | #include "framework/UI_WebSocketClientServer.h" | ||||||
|  |  | ||||||
| namespace OpenWifi { | namespace OpenWifi { | ||||||
|  |  | ||||||
| 	class WebSocketLogger : public Poco::Channel { | 	class WebSocketLogger : public Poco::Channel { | ||||||
| 	  public: | 	  public: | ||||||
|  | 		WebSocketLogger() {} | ||||||
|  |  | ||||||
| 		WebSocketLogger() { | 		~WebSocketLogger() {} | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		~WebSocketLogger() { | 		std::string getProperty([[maybe_unused]] const std::string &p) const { | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		std::string getProperty( [[maybe_unused]] const std::string &p ) const { |  | ||||||
| 			std::cout << "WS getProperty" << std::endl; | 			std::cout << "WS getProperty" << std::endl; | ||||||
| 			return ""; | 			return ""; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		void close() final { | 		void close() final {} | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		void open() final { | 		void open() final {} | ||||||
| 		} |  | ||||||
|  |  | ||||||
| 		static std::string to_string(Poco::Message::Priority p) { | 		static std::string to_string(Poco::Message::Priority p) { | ||||||
| 			switch(p) { | 			switch (p) { | ||||||
| 			case Poco::Message::PRIO_INFORMATION: return "information"; | 			case Poco::Message::PRIO_INFORMATION: | ||||||
| 			case Poco::Message::PRIO_CRITICAL: return "critical"; | 				return "information"; | ||||||
| 			case Poco::Message::PRIO_DEBUG: return "debug"; | 			case Poco::Message::PRIO_CRITICAL: | ||||||
| 			case Poco::Message::PRIO_ERROR: return "error"; | 				return "critical"; | ||||||
| 			case Poco::Message::PRIO_FATAL: return "fatal"; | 			case Poco::Message::PRIO_DEBUG: | ||||||
| 			case Poco::Message::PRIO_NOTICE: return "notice"; | 				return "debug"; | ||||||
| 			case Poco::Message::PRIO_TRACE: return "trace"; | 			case Poco::Message::PRIO_ERROR: | ||||||
| 			case Poco::Message::PRIO_WARNING: return "warning"; | 				return "error"; | ||||||
| 			default: return "none"; | 			case Poco::Message::PRIO_FATAL: | ||||||
|  | 				return "fatal"; | ||||||
|  | 			case Poco::Message::PRIO_NOTICE: | ||||||
|  | 				return "notice"; | ||||||
|  | 			case Poco::Message::PRIO_TRACE: | ||||||
|  | 				return "trace"; | ||||||
|  | 			case Poco::Message::PRIO_WARNING: | ||||||
|  | 				return "warning"; | ||||||
|  | 			default: | ||||||
|  | 				return "none"; | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| @@ -51,15 +54,15 @@ namespace OpenWifi { | |||||||
| 			std::uint64_t timestamp; | 			std::uint64_t timestamp; | ||||||
| 			std::string source; | 			std::string source; | ||||||
| 			std::string thread_name; | 			std::string thread_name; | ||||||
| 			std::uint64_t 		thread_id=0; | 			std::uint64_t thread_id = 0; | ||||||
|  |  | ||||||
| 			inline void to_json(Poco::JSON::Object &Obj) const { | 			inline void to_json(Poco::JSON::Object &Obj) const { | ||||||
| 				RESTAPI_utils::field_to_json(Obj,"msg", msg); | 				RESTAPI_utils::field_to_json(Obj, "msg", msg); | ||||||
| 				RESTAPI_utils::field_to_json(Obj,"level", level); | 				RESTAPI_utils::field_to_json(Obj, "level", level); | ||||||
| 				RESTAPI_utils::field_to_json(Obj,"timestamp", timestamp); | 				RESTAPI_utils::field_to_json(Obj, "timestamp", timestamp); | ||||||
| 				RESTAPI_utils::field_to_json(Obj,"source", source); | 				RESTAPI_utils::field_to_json(Obj, "source", source); | ||||||
| 				RESTAPI_utils::field_to_json(Obj,"thread_name", thread_name); | 				RESTAPI_utils::field_to_json(Obj, "thread_name", thread_name); | ||||||
| 				RESTAPI_utils::field_to_json(Obj,"thread_id", thread_id); | 				RESTAPI_utils::field_to_json(Obj, "thread_id", thread_id); | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			inline bool from_json(const Poco::JSON::Object::Ptr &Obj) { | 			inline bool from_json(const Poco::JSON::Object::Ptr &Obj) { | ||||||
| @@ -71,17 +74,17 @@ namespace OpenWifi { | |||||||
| 					RESTAPI_utils::field_from_json(Obj, "thread_name", thread_name); | 					RESTAPI_utils::field_from_json(Obj, "thread_name", thread_name); | ||||||
| 					RESTAPI_utils::field_from_json(Obj, "thread_id", thread_id); | 					RESTAPI_utils::field_from_json(Obj, "thread_id", thread_id); | ||||||
| 					return true; | 					return true; | ||||||
| 				} catch(...) { | 				} catch (...) { | ||||||
|  |  | ||||||
| 				} | 				} | ||||||
| 				return false; | 				return false; | ||||||
| 			} | 			} | ||||||
| 		}; | 		}; | ||||||
|  |  | ||||||
| 		typedef WebSocketNotification<NotificationLogMessage> WebSocketClientNotificationLogMessage_t; | 		typedef WebSocketNotification<NotificationLogMessage> | ||||||
|  | 			WebSocketClientNotificationLogMessage_t; | ||||||
|  |  | ||||||
| 		void log(const Poco::Message &m) final { | 		void log(const Poco::Message &m) final { | ||||||
| 			if(UI_WebSocketClientServer()->IsAnyoneConnected()) { | 			if (UI_WebSocketClientServer()->IsAnyoneConnected()) { | ||||||
| 				WebSocketClientNotificationLogMessage_t Msg; | 				WebSocketClientNotificationLogMessage_t Msg; | ||||||
| 				Msg.content.msg = m.getText(); | 				Msg.content.msg = m.getText(); | ||||||
| 				Msg.content.level = WebSocketLogger::to_string(m.getPriority()); | 				Msg.content.level = WebSocketLogger::to_string(m.getPriority()); | ||||||
| @@ -94,7 +97,8 @@ namespace OpenWifi { | |||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		void setProperty([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) { | 		void setProperty([[maybe_unused]] const std::string &name, | ||||||
|  | 						 [[maybe_unused]] const std::string &value) { | ||||||
| 			std::cout << "WS setProperty" << std::endl; | 			std::cout << "WS setProperty" << std::endl; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| @@ -102,6 +106,6 @@ namespace OpenWifi { | |||||||
| 		std::recursive_mutex Mutex_; | 		std::recursive_mutex Mutex_; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| //	inline auto WebSocketLogger() { return WebSocketLogger::instance(); } | 	//	inline auto WebSocketLogger() { return WebSocketLogger::instance(); } | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi | ||||||
							
								
								
									
										63
									
								
								src/framework/default_device_types.h
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										63
									
								
								src/framework/default_device_types.h
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,63 @@ | |||||||
|  | // | ||||||
|  | // Created by stephane bourque on 2023-04-19. | ||||||
|  | // | ||||||
|  |  | ||||||
|  | #pragma once | ||||||
|  |  | ||||||
|  | #include <vector> | ||||||
|  | #include <string> | ||||||
|  |  | ||||||
|  | namespace OpenWifi { | ||||||
|  | 	inline  const std::vector<std::pair<std::string, std::string>> DefaultDeviceTypeList{ | ||||||
|  | 		{"actiontec_web7200", "AP"}, | ||||||
|  | 		{"cig_wf186w", "AP"}, | ||||||
|  | 		{"cig_wf188n", "AP"}, | ||||||
|  | 		{"cig_wf194c4", "AP"}, | ||||||
|  | 		{"cig_wf196", "AP"}, | ||||||
|  | 		{"cig_wf196-ca", "AP"}, | ||||||
|  | 		{"cig_wf196-ca-ath12", "AP"}, | ||||||
|  | 		{"cig_wf196-us", "AP"}, | ||||||
|  | 		{"cig_wf610d", "AP"}, | ||||||
|  | 		{"cig_wf660a", "AP"}, | ||||||
|  | 		{"cig_wf808", "AP"}, | ||||||
|  | 		{"cybertan_eww622-a1", "AP"}, | ||||||
|  | 		{"edgecore_eap101", "AP"}, | ||||||
|  | 		{"edgecore_eap101-ath12", "AP"}, | ||||||
|  | 		{"edgecore_eap102", "AP"}, | ||||||
|  | 		{"edgecore_eap104", "AP"}, | ||||||
|  | 		{"edgecore_eap104-ath12", "AP"}, | ||||||
|  | 		{"edgecore_ecs4100-12ph", "AP"}, | ||||||
|  | 		{"edgecore_ecw5211", "AP"}, | ||||||
|  | 		{"edgecore_ecw5410", "AP"}, | ||||||
|  | 		{"edgecore_oap100", "AP"}, | ||||||
|  | 		{"edgecore_spw2ac1200", "SWITCH"}, | ||||||
|  | 		{"edgecore_spw2ac1200-lan-poe", "SWITCH"}, | ||||||
|  | 		{"edgecore_ssw2ac2600", "SWITCH"}, | ||||||
|  | 		{"hfcl_ion4", "AP"}, | ||||||
|  | 		{"hfcl_ion4x", "AP"}, | ||||||
|  | 		{"hfcl_ion4x_2", "AP"}, | ||||||
|  | 		{"hfcl_ion4xe", "AP"}, | ||||||
|  | 		{"hfcl_ion4xi", "AP"}, | ||||||
|  | 		{"indio_um-305ac", "AP"}, | ||||||
|  | 		{"indio_um-305ax", "AP"}, | ||||||
|  | 		{"indio_um-310ax-v1", "AP"}, | ||||||
|  | 		{"indio_um-325ac", "AP"}, | ||||||
|  | 		{"indio_um-510ac-v3", "AP"}, | ||||||
|  | 		{"indio_um-510axm-v1", "AP"}, | ||||||
|  | 		{"indio_um-510axp-v1", "AP"}, | ||||||
|  | 		{"indio_um-550ac", "AP"}, | ||||||
|  | 		{"linksys_e8450-ubi", "AP"}, | ||||||
|  | 		{"linksys_ea6350-v4", "AP"}, | ||||||
|  | 		{"linksys_ea8300", "AP"}, | ||||||
|  | 		{"liteon_wpx8324", "AP"}, | ||||||
|  | 		{"meshpp_s618_cp01", "AP"}, | ||||||
|  | 		{"meshpp_s618_cp03", "AP"}, | ||||||
|  | 		{"udaya_a5-id2", "AP"}, | ||||||
|  | 		{"wallys_dr40x9", "AP"}, | ||||||
|  | 		{"wallys_dr6018", "AP"}, | ||||||
|  | 		{"wallys_dr6018_v4", "AP"}, | ||||||
|  | 		{"x64_vm", "AP"}, | ||||||
|  | 		{"yuncore_ax840", "AP"}, | ||||||
|  | 		{"yuncore_fap640", "AP"}, | ||||||
|  | 		{"yuncore_fap650", "AP"}}; | ||||||
|  | } | ||||||
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							| @@ -4,144 +4,162 @@ | |||||||
|  |  | ||||||
| #include "Poco/Path.h" | #include "Poco/Path.h" | ||||||
|  |  | ||||||
| #include "framework/utils.h" |  | ||||||
| #include "framework/AppServiceRegistry.h" | #include "framework/AppServiceRegistry.h" | ||||||
|  | #include "framework/utils.h" | ||||||
|  |  | ||||||
| namespace OpenWifi::Utils { | namespace OpenWifi::Utils { | ||||||
|  |  | ||||||
| bool NormalizeMac(std::string & Mac) { | 	bool NormalizeMac(std::string &Mac) { | ||||||
| 	Poco::replaceInPlace(Mac,":",""); | 		Poco::replaceInPlace(Mac, ":", ""); | ||||||
| 	Poco::replaceInPlace(Mac,"-",""); | 		Poco::replaceInPlace(Mac, "-", ""); | ||||||
| 	if(Mac.size()!=12) | 		if (Mac.size() != 12) | ||||||
| 			return false; | 			return false; | ||||||
| 	for(const auto &i:Mac) { | 		for (const auto &i : Mac) { | ||||||
| 		if(!std::isxdigit(i)) | 			if (!std::isxdigit(i)) | ||||||
| 				return false; | 				return false; | ||||||
| 		} | 		} | ||||||
| 		Poco::toLowerInPlace(Mac); | 		Poco::toLowerInPlace(Mac); | ||||||
| 		return true; | 		return true; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] bool ValidSerialNumber(const std::string &Serial) { | 	[[nodiscard]] bool ValidSerialNumber(const std::string &Serial) { | ||||||
| 		return ((Serial.size() < uCentralProtocol::SERIAL_NUMBER_LENGTH) && | 		return ((Serial.size() < uCentralProtocol::SERIAL_NUMBER_LENGTH) && | ||||||
| 			std::all_of(Serial.begin(),Serial.end(),[](auto i){return std::isxdigit(i);})); | 				std::all_of(Serial.begin(), Serial.end(), [](auto i) { return std::isxdigit(i); })); | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] bool ValidUUID(const std::string &UUID) { | 	[[nodiscard]] bool ValidSerialNumbers(const std::vector<std::string> &numbers) { | ||||||
| 	if(UUID.size()>36) | 		return std::all_of(numbers.begin(),numbers.end(),[](auto &number) {return ValidSerialNumber(number);}); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	[[nodiscard]] bool ValidUUID(const std::string &UUID) { | ||||||
|  | 		if (UUID.size() > 36) | ||||||
| 			return false; | 			return false; | ||||||
| 	uint dashes=0; | 		uint dashes = 0; | ||||||
| 	return (std::all_of(UUID.begin(),UUID.end(),[&](auto i){ if(i=='-') dashes++; return i=='-' || std::isxdigit(i);})) && (dashes>0); | 		return (std::all_of(UUID.begin(), UUID.end(), | ||||||
| } | 							[&](auto i) { | ||||||
|  | 								if (i == '-') | ||||||
|  | 									dashes++; | ||||||
|  | 								return i == '-' || std::isxdigit(i); | ||||||
|  | 							})) && | ||||||
|  | 			   (dashes > 0); | ||||||
|  | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] std::vector<std::string> Split(const std::string &List, char Delimiter ) { | 	[[nodiscard]] std::vector<std::string> Split(const std::string &List, char Delimiter) { | ||||||
| 		std::vector<std::string> ReturnList; | 		std::vector<std::string> ReturnList; | ||||||
|  |  | ||||||
| 	unsigned long P=0; | 		unsigned long P = 0; | ||||||
|  |  | ||||||
| 	while(P<List.size()) | 		while (P < List.size()) { | ||||||
| 	{ |  | ||||||
| 			unsigned long P2 = List.find_first_of(Delimiter, P); | 			unsigned long P2 = List.find_first_of(Delimiter, P); | ||||||
| 		if(P2==std::string::npos) { | 			if (P2 == std::string::npos) { | ||||||
| 				ReturnList.push_back(List.substr(P)); | 				ReturnList.push_back(List.substr(P)); | ||||||
| 				break; | 				break; | ||||||
| 		} | 			} else | ||||||
| 		else | 				ReturnList.push_back(List.substr(P, P2 - P)); | ||||||
| 			ReturnList.push_back(List.substr(P,P2-P)); | 			P = P2 + 1; | ||||||
| 		P=P2+1; |  | ||||||
| 		} | 		} | ||||||
| 		return ReturnList; | 		return ReturnList; | ||||||
| } | 	} | ||||||
|  |  | ||||||
|  | 	[[nodiscard]] std::string FormatIPv6(const std::string &I) { | ||||||
| [[nodiscard]] std::string FormatIPv6(const std::string & I ) | 		if (I.substr(0, 8) == "[::ffff:") { | ||||||
| { |  | ||||||
| 	if(I.substr(0,8) == "[::ffff:") |  | ||||||
| 	{ |  | ||||||
| 			unsigned long PClosingBracket = I.find_first_of(']'); | 			unsigned long PClosingBracket = I.find_first_of(']'); | ||||||
|  |  | ||||||
| 		std::string ip = I.substr(8, PClosingBracket-8); | 			std::string ip = I.substr(8, PClosingBracket - 8); | ||||||
| 		std::string port = I.substr(PClosingBracket+1); | 			std::string port = I.substr(PClosingBracket + 1); | ||||||
| 			return ip + port; | 			return ip + port; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return I; | 		return I; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| void padTo(std::string& str, size_t num, char paddingChar) { | 	void padTo(std::string &str, size_t num, char paddingChar) { | ||||||
| 		str.append(num - str.length() % num, paddingChar); | 		str.append(num - str.length() % num, paddingChar); | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] std::string SerialToMAC(const std::string &Serial) { | 	[[nodiscard]] std::string SerialToMAC(const std::string &Serial) { | ||||||
| 		std::string R = Serial; | 		std::string R = Serial; | ||||||
|  |  | ||||||
| 	if(R.size()<12) | 		if (R.size() < 12) | ||||||
| 		padTo(R,12,'0'); | 			padTo(R, 12, '0'); | ||||||
| 	else if (R.size()>12) | 		else if (R.size() > 12) | ||||||
| 		R = R.substr(0,12); | 			R = R.substr(0, 12); | ||||||
|  |  | ||||||
| 		char buf[18]; | 		char buf[18]; | ||||||
|  |  | ||||||
| 	buf[0] = R[0]; buf[1] = R[1] ; buf[2] = ':' ; | 		buf[0] = R[0]; | ||||||
| 	buf[3] = R[2] ; buf[4] = R[3]; buf[5] = ':' ; | 		buf[1] = R[1]; | ||||||
| 	buf[6] = R[4]; buf[7] = R[5] ; buf[8] = ':' ; | 		buf[2] = ':'; | ||||||
| 	buf[9] = R[6] ; buf[10]= R[7]; buf[11] = ':'; | 		buf[3] = R[2]; | ||||||
| 	buf[12] = R[8] ; buf[13]= R[9]; buf[14] = ':'; | 		buf[4] = R[3]; | ||||||
| 	buf[15] = R[10] ; buf[16]= R[11];buf[17] = 0; | 		buf[5] = ':'; | ||||||
|  | 		buf[6] = R[4]; | ||||||
|  | 		buf[7] = R[5]; | ||||||
|  | 		buf[8] = ':'; | ||||||
|  | 		buf[9] = R[6]; | ||||||
|  | 		buf[10] = R[7]; | ||||||
|  | 		buf[11] = ':'; | ||||||
|  | 		buf[12] = R[8]; | ||||||
|  | 		buf[13] = R[9]; | ||||||
|  | 		buf[14] = ':'; | ||||||
|  | 		buf[15] = R[10]; | ||||||
|  | 		buf[16] = R[11]; | ||||||
|  | 		buf[17] = 0; | ||||||
|  |  | ||||||
| 		return buf; | 		return buf; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| uint64_t MACToInt(const std::string &MAC) { | 	uint64_t MACToInt(const std::string &MAC) { | ||||||
| 	uint64_t Result = 0 ; | 		uint64_t Result = 0; | ||||||
| 	for(const auto &c:MAC) { | 		for (const auto &c : MAC) { | ||||||
| 		if(c==':') | 			if (c == ':') | ||||||
| 				continue; | 				continue; | ||||||
| 			Result <<= 4; | 			Result <<= 4; | ||||||
| 		if(c>='0' && c<='9') { | 			if (c >= '0' && c <= '9') { | ||||||
| 				Result += (c - '0'); | 				Result += (c - '0'); | ||||||
| 		} else if (c>='a' && c<='f') { | 			} else if (c >= 'a' && c <= 'f') { | ||||||
| 			Result += (c-'a'+10); | 				Result += (c - 'a' + 10); | ||||||
| 		} else if (c>='A' && c<='F') { | 			} else if (c >= 'A' && c <= 'F') { | ||||||
| 			Result += (c-'A'+10); | 				Result += (c - 'A' + 10); | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] bool ValidHostname(const std::string &Hostname) { | 	[[nodiscard]] bool ValidHostname(const std::string &Hostname) { | ||||||
|     static std::regex HostNameRegex("^(?!-)[A-Za-z0-9-]+([\\-\\.]{1}[a-z0-9]+)*\\.[A-Za-z]{2,6}$"); | 		static std::regex HostNameRegex( | ||||||
|     return std::regex_match(Hostname,HostNameRegex); | 			"^(?!-)[A-Za-z0-9-]+([\\-\\.]{1}[a-z0-9]+)*\\.[A-Za-z]{2,6}$"); | ||||||
| } | 		return std::regex_match(Hostname, HostNameRegex); | ||||||
|  | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] std::string ToHex(const std::vector<unsigned char> & B) { | 	[[nodiscard]] std::string ToHex(const std::vector<unsigned char> &B) { | ||||||
| 		std::string R; | 		std::string R; | ||||||
| 	R.reserve(B.size()*2); | 		R.reserve(B.size() * 2); | ||||||
|  |  | ||||||
| 		static const char hex[] = "0123456789abcdef"; | 		static const char hex[] = "0123456789abcdef"; | ||||||
|  |  | ||||||
| 	for(const auto &i:B) | 		for (const auto &i : B) { | ||||||
| 	{ | 			R += (hex[(i & 0xf0) >> 4]); | ||||||
| 		R += (hex[ (i & 0xf0) >> 4]); | 			R += (hex[(i & 0x0f)]); | ||||||
| 		R += (hex[ (i & 0x0f) ]); |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return R; | 		return R; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| inline static const char kEncodeLookup[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | 	inline static const char kEncodeLookup[] = | ||||||
| inline static const char kPadCharacter = '='; | 		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | ||||||
|  | 	inline static const char kPadCharacter = '='; | ||||||
|  |  | ||||||
| using byte = std::uint8_t; | 	using byte = std::uint8_t; | ||||||
|  |  | ||||||
| [[nodiscard]] std::string base64encode(const byte *input, uint32_t size) { | 	[[nodiscard]] std::string base64encode(const byte *input, uint32_t size) { | ||||||
| 		std::string encoded; | 		std::string encoded; | ||||||
| 		encoded.reserve(((size / 3) + (size % 3 > 0)) * 4); | 		encoded.reserve(((size / 3) + (size % 3 > 0)) * 4); | ||||||
|  |  | ||||||
| 	std::uint32_t temp,i,ee; | 		std::uint32_t temp, i, ee; | ||||||
| 	ee = (size/3); | 		ee = (size / 3); | ||||||
|  |  | ||||||
| 	for (i = 0; i < 3*ee; ++i) { | 		for (i = 0; i < 3 * ee; ++i) { | ||||||
| 			temp = input[i++] << 16; | 			temp = input[i++] << 16; | ||||||
| 			temp += input[i++] << 8; | 			temp += input[i++] << 8; | ||||||
| 			temp += input[i]; | 			temp += input[i]; | ||||||
| @@ -169,44 +187,45 @@ using byte = std::uint8_t; | |||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return encoded; | 		return encoded; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] std::vector<byte> base64decode(const std::string& input) | 	[[nodiscard]] std::vector<byte> base64decode(const std::string &input) { | ||||||
| { | 		if (input.length() % 4) | ||||||
| 	if(input.length() % 4) |  | ||||||
| 			throw std::runtime_error("Invalid base64 length!"); | 			throw std::runtime_error("Invalid base64 length!"); | ||||||
|  |  | ||||||
| 	std::size_t padding=0; | 		std::size_t padding = 0; | ||||||
|  |  | ||||||
| 	if(input.length()) | 		if (input.length()) { | ||||||
| 	{ | 			if (input[input.length() - 1] == kPadCharacter) | ||||||
| 		if(input[input.length() - 1] == kPadCharacter) padding++; | 				padding++; | ||||||
| 		if(input[input.length() - 2] == kPadCharacter) padding++; | 			if (input[input.length() - 2] == kPadCharacter) | ||||||
|  | 				padding++; | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		std::vector<byte> decoded; | 		std::vector<byte> decoded; | ||||||
| 		decoded.reserve(((input.length() / 4) * 3) - padding); | 		decoded.reserve(((input.length() / 4) * 3) - padding); | ||||||
|  |  | ||||||
| 	std::uint32_t temp=0; | 		std::uint32_t temp = 0; | ||||||
| 		auto it = input.begin(); | 		auto it = input.begin(); | ||||||
|  |  | ||||||
| 	while(it < input.end()) | 		while (it < input.end()) { | ||||||
| 	{ | 			for (std::size_t i = 0; i < 4; ++i) { | ||||||
| 		for(std::size_t i = 0; i < 4; ++i) |  | ||||||
| 		{ |  | ||||||
| 				temp <<= 6; | 				temp <<= 6; | ||||||
| 			if     (*it >= 0x41 && *it <= 0x5A) temp |= *it - 0x41; | 				if (*it >= 0x41 && *it <= 0x5A) | ||||||
| 			else if(*it >= 0x61 && *it <= 0x7A) temp |= *it - 0x47; | 					temp |= *it - 0x41; | ||||||
| 			else if(*it >= 0x30 && *it <= 0x39) temp |= *it + 0x04; | 				else if (*it >= 0x61 && *it <= 0x7A) | ||||||
| 			else if(*it == 0x2B)                temp |= 0x3E; | 					temp |= *it - 0x47; | ||||||
| 			else if(*it == 0x2F)                temp |= 0x3F; | 				else if (*it >= 0x30 && *it <= 0x39) | ||||||
| 			else if(*it == kPadCharacter) | 					temp |= *it + 0x04; | ||||||
| 			{ | 				else if (*it == 0x2B) | ||||||
| 				switch(input.end() - it) | 					temp |= 0x3E; | ||||||
| 				{ | 				else if (*it == 0x2F) | ||||||
|  | 					temp |= 0x3F; | ||||||
|  | 				else if (*it == kPadCharacter) { | ||||||
|  | 					switch (input.end() - it) { | ||||||
| 					case 1: | 					case 1: | ||||||
| 						decoded.push_back((temp >> 16) & 0x000000FF); | 						decoded.push_back((temp >> 16) & 0x000000FF); | ||||||
| 					decoded.push_back((temp >> 8 ) & 0x000000FF); | 						decoded.push_back((temp >> 8) & 0x000000FF); | ||||||
| 						return decoded; | 						return decoded; | ||||||
| 					case 2: | 					case 2: | ||||||
| 						decoded.push_back((temp >> 10) & 0x000000FF); | 						decoded.push_back((temp >> 10) & 0x000000FF); | ||||||
| @@ -214,135 +233,142 @@ using byte = std::uint8_t; | |||||||
| 					default: | 					default: | ||||||
| 						throw std::runtime_error("Invalid padding in base64!"); | 						throw std::runtime_error("Invalid padding in base64!"); | ||||||
| 					} | 					} | ||||||
| 			} | 				} else | ||||||
| 			else throw std::runtime_error("Invalid character in base64!"); | 					throw std::runtime_error("Invalid character in base64!"); | ||||||
|  |  | ||||||
| 				++it; | 				++it; | ||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			decoded.push_back((temp >> 16) & 0x000000FF); | 			decoded.push_back((temp >> 16) & 0x000000FF); | ||||||
| 		decoded.push_back((temp >> 8 ) & 0x000000FF); | 			decoded.push_back((temp >> 8) & 0x000000FF); | ||||||
| 		decoded.push_back((temp      ) & 0x000000FF); | 			decoded.push_back((temp)&0x000000FF); | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		return decoded; | 		return decoded; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| bool ParseTime(const std::string &Time, int & Hours, int & Minutes, int & Seconds) { | 	bool ParseTime(const std::string &Time, int &Hours, int &Minutes, int &Seconds) { | ||||||
| 	Poco::StringTokenizer	TimeTokens(Time,":",Poco::StringTokenizer::TOK_TRIM); | 		Poco::StringTokenizer TimeTokens(Time, ":", Poco::StringTokenizer::TOK_TRIM); | ||||||
|  |  | ||||||
| 	Hours =  Minutes = Seconds = 0 ; | 		Hours = Minutes = Seconds = 0; | ||||||
| 	if(TimeTokens.count()==1) { | 		if (TimeTokens.count() == 1) { | ||||||
| 			Hours = std::atoi(TimeTokens[0].c_str()); | 			Hours = std::atoi(TimeTokens[0].c_str()); | ||||||
| 	} else if(TimeTokens.count()==2) { | 		} else if (TimeTokens.count() == 2) { | ||||||
| 			Hours = std::atoi(TimeTokens[0].c_str()); | 			Hours = std::atoi(TimeTokens[0].c_str()); | ||||||
| 			Minutes = std::atoi(TimeTokens[1].c_str()); | 			Minutes = std::atoi(TimeTokens[1].c_str()); | ||||||
| 	} else if(TimeTokens.count()==3) { | 		} else if (TimeTokens.count() == 3) { | ||||||
| 			Hours = std::atoi(TimeTokens[0].c_str()); | 			Hours = std::atoi(TimeTokens[0].c_str()); | ||||||
| 			Minutes = std::atoi(TimeTokens[1].c_str()); | 			Minutes = std::atoi(TimeTokens[1].c_str()); | ||||||
| 			Seconds = std::atoi(TimeTokens[2].c_str()); | 			Seconds = std::atoi(TimeTokens[2].c_str()); | ||||||
| 		} else | 		} else | ||||||
| 			return false; | 			return false; | ||||||
| 		return true; | 		return true; | ||||||
| } | 	} | ||||||
|  |  | ||||||
|  | 	bool ParseDate(const std::string &Time, int &Year, int &Month, int &Day) { | ||||||
|  | 		Poco::StringTokenizer DateTokens(Time, "-", Poco::StringTokenizer::TOK_TRIM); | ||||||
|  |  | ||||||
| bool ParseDate(const std::string &Time, int & Year, int & Month, int & Day) { | 		Year = Month = Day = 0; | ||||||
| 	Poco::StringTokenizer	DateTokens(Time,"-",Poco::StringTokenizer::TOK_TRIM); | 		if (DateTokens.count() == 3) { | ||||||
|  |  | ||||||
| 	Year =  Month = Day = 0 ; |  | ||||||
| 	if(DateTokens.count()==3) { |  | ||||||
| 			Year = std::atoi(DateTokens[0].c_str()); | 			Year = std::atoi(DateTokens[0].c_str()); | ||||||
| 			Month = std::atoi(DateTokens[1].c_str()); | 			Month = std::atoi(DateTokens[1].c_str()); | ||||||
| 			Day = std::atoi(DateTokens[2].c_str()); | 			Day = std::atoi(DateTokens[2].c_str()); | ||||||
| 		} else | 		} else | ||||||
| 			return false; | 			return false; | ||||||
| 		return true; | 		return true; | ||||||
| } |  | ||||||
|  |  | ||||||
| bool CompareTime( int H1, int H2, int M1, int M2, int S1, int S2) { |  | ||||||
| 	if(H1<H2) |  | ||||||
| 		return true; |  | ||||||
| 	if(H1>H2) |  | ||||||
| 		return false; |  | ||||||
| 	if(M1<M2) |  | ||||||
| 		return true; |  | ||||||
| 	if(M2>M1) |  | ||||||
| 		return false; |  | ||||||
| 	if(S1<=S2) |  | ||||||
| 		return true; |  | ||||||
| 	return false; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| [[nodiscard]] std::string LogLevelToString(int Level) { |  | ||||||
| 	switch(Level) { |  | ||||||
| 	case Poco::Message::PRIO_DEBUG: return "debug"; |  | ||||||
| 	case Poco::Message::PRIO_INFORMATION: return "information"; |  | ||||||
| 	case Poco::Message::PRIO_FATAL: return "fatal"; |  | ||||||
| 	case Poco::Message::PRIO_WARNING: return "warning"; |  | ||||||
| 	case Poco::Message::PRIO_NOTICE: return "notice"; |  | ||||||
| 	case Poco::Message::PRIO_CRITICAL: return "critical"; |  | ||||||
| 	case Poco::Message::PRIO_ERROR: return "error"; |  | ||||||
| 	case Poco::Message::PRIO_TRACE: return "trace"; |  | ||||||
| 	default: return "none"; |  | ||||||
| 	} | 	} | ||||||
| } |  | ||||||
|  |  | ||||||
| [[nodiscard]] uint64_t SerialNumberToInt(const std::string & S) { | 	bool CompareTime(int H1, int H2, int M1, int M2, int S1, int S2) { | ||||||
| 	return std::stoull(S,nullptr,16); | 		if (H1 < H2) | ||||||
| } | 			return true; | ||||||
|  | 		if (H1 > H2) | ||||||
|  | 			return false; | ||||||
|  | 		if (M1 < M2) | ||||||
|  | 			return true; | ||||||
|  | 		if (M2 > M1) | ||||||
|  | 			return false; | ||||||
|  | 		if (S1 <= S2) | ||||||
|  | 			return true; | ||||||
|  | 		return false; | ||||||
|  | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] std::string IntToSerialNumber(uint64_t S) { | 	[[nodiscard]] std::string LogLevelToString(int Level) { | ||||||
|  | 		switch (Level) { | ||||||
|  | 		case Poco::Message::PRIO_DEBUG: | ||||||
|  | 			return "debug"; | ||||||
|  | 		case Poco::Message::PRIO_INFORMATION: | ||||||
|  | 			return "information"; | ||||||
|  | 		case Poco::Message::PRIO_FATAL: | ||||||
|  | 			return "fatal"; | ||||||
|  | 		case Poco::Message::PRIO_WARNING: | ||||||
|  | 			return "warning"; | ||||||
|  | 		case Poco::Message::PRIO_NOTICE: | ||||||
|  | 			return "notice"; | ||||||
|  | 		case Poco::Message::PRIO_CRITICAL: | ||||||
|  | 			return "critical"; | ||||||
|  | 		case Poco::Message::PRIO_ERROR: | ||||||
|  | 			return "error"; | ||||||
|  | 		case Poco::Message::PRIO_TRACE: | ||||||
|  | 			return "trace"; | ||||||
|  | 		default: | ||||||
|  | 			return "none"; | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	[[nodiscard]] uint64_t SerialNumberToInt(const std::string &S) { | ||||||
|  | 		return std::stoull(S, nullptr, 16); | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	[[nodiscard]] std::string IntToSerialNumber(uint64_t S) { | ||||||
| 		char b[16]; | 		char b[16]; | ||||||
| 	for(int i=0;i<12;++i) { | 		for (int i = 0; i < 12; ++i) { | ||||||
| 			int B = (S & 0x0f); | 			int B = (S & 0x0f); | ||||||
| 		if(B<10) | 			if (B < 10) | ||||||
| 			b[11-i] = B+'0'; | 				b[11 - i] = B + '0'; | ||||||
| 			else | 			else | ||||||
| 			b[11-i] = B - 10 + 'a'; | 				b[11 - i] = B - 10 + 'a'; | ||||||
| 		S >>= 4 ; | 			S >>= 4; | ||||||
| 		} | 		} | ||||||
| 	b[12]=0; | 		b[12] = 0; | ||||||
| 		return b; | 		return b; | ||||||
| } | 	} | ||||||
|  |  | ||||||
|  | 	[[nodiscard]] bool SerialNumberMatch(const std::string &S1, const std::string &S2, int Bits) { | ||||||
| [[nodiscard]] bool SerialNumberMatch(const std::string &S1, const std::string &S2, int Bits) { |  | ||||||
| 		auto S1_i = SerialNumberToInt(S1); | 		auto S1_i = SerialNumberToInt(S1); | ||||||
| 		auto S2_i = SerialNumberToInt(S2); | 		auto S2_i = SerialNumberToInt(S2); | ||||||
| 	return ((S1_i>>Bits)==(S2_i>>Bits)); | 		return ((S1_i >> Bits) == (S2_i >> Bits)); | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] uint64_t SerialNumberToOUI(const std::string & S) { | 	[[nodiscard]] uint64_t SerialNumberToOUI(const std::string &S) { | ||||||
| 	uint64_t Result = 0 ; | 		uint64_t Result = 0; | ||||||
| 	int Digits=0; | 		int Digits = 0; | ||||||
|  |  | ||||||
| 	for(const auto &i:S) { | 		for (const auto &i : S) { | ||||||
| 		if(std::isxdigit(i)) { | 			if (std::isxdigit(i)) { | ||||||
| 			if(i>='0' && i<='9') { | 				if (i >= '0' && i <= '9') { | ||||||
| 				Result <<=4; | 					Result <<= 4; | ||||||
| 				Result += i-'0'; | 					Result += i - '0'; | ||||||
| 			} else if(i>='A' && i<='F') { | 				} else if (i >= 'A' && i <= 'F') { | ||||||
| 				Result <<=4; | 					Result <<= 4; | ||||||
| 				Result += i-'A'+10; | 					Result += i - 'A' + 10; | ||||||
| 			} else if(i>='a' && i<='f') { | 				} else if (i >= 'a' && i <= 'f') { | ||||||
| 				Result <<=4; | 					Result <<= 4; | ||||||
| 				Result += i-'a'+10; | 					Result += i - 'a' + 10; | ||||||
| 				} | 				} | ||||||
| 				Digits++; | 				Digits++; | ||||||
| 			if(Digits==6) | 				if (Digits == 6) | ||||||
| 					break; | 					break; | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] uint64_t GetDefaultMacAsInt64() { | 	[[nodiscard]] uint64_t GetDefaultMacAsInt64() { | ||||||
| 	uint64_t Result=0; | 		uint64_t Result = 0; | ||||||
| 		auto IFaceList = Poco::Net::NetworkInterface::list(); | 		auto IFaceList = Poco::Net::NetworkInterface::list(); | ||||||
|  |  | ||||||
| 	for(const auto &iface:IFaceList) { | 		for (const auto &iface : IFaceList) { | ||||||
| 		if(iface.isRunning() && !iface.isLoopback()) { | 			if (iface.isRunning() && !iface.isLoopback()) { | ||||||
| 				auto MAC = iface.macAddress(); | 				auto MAC = iface.macAddress(); | ||||||
| 				for (auto const &i : MAC) { | 				for (auto const &i : MAC) { | ||||||
| 					Result <<= 8; | 					Result <<= 8; | ||||||
| @@ -353,35 +379,35 @@ bool CompareTime( int H1, int H2, int M1, int M2, int S1, int S2) { | |||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] uint64_t InitializeSystemId() { | 	[[nodiscard]] uint64_t InitializeSystemId() { | ||||||
| 		std::random_device RDev; | 		std::random_device RDev; | ||||||
| 		std::srand(RDev()); | 		std::srand(RDev()); | ||||||
| 		std::chrono::high_resolution_clock Clock; | 		std::chrono::high_resolution_clock Clock; | ||||||
| 		auto Now = Clock.now().time_since_epoch().count(); | 		auto Now = Clock.now().time_since_epoch().count(); | ||||||
| 	auto S = (GetDefaultMacAsInt64() + std::rand() + Now)  ; | 		auto S = (GetDefaultMacAsInt64() + std::rand() + Now); | ||||||
| 	OpenWifi::AppServiceRegistry().Set("systemid",S); | 		OpenWifi::AppServiceRegistry().Set("systemid", S); | ||||||
| 		return S; | 		return S; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] uint64_t GetSystemId() { | 	[[nodiscard]] uint64_t GetSystemId() { | ||||||
| 	uint64_t ID=0; | 		uint64_t ID = 0; | ||||||
| 	if(!AppServiceRegistry().Get("systemid",ID)) { | 		if (!AppServiceRegistry().Get("systemid", ID)) { | ||||||
| 			return InitializeSystemId(); | 			return InitializeSystemId(); | ||||||
| 		} | 		} | ||||||
| 		return ID; | 		return ID; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] bool ValidEMailAddress(const std::string &email) { | 	[[nodiscard]] bool ValidEMailAddress(const std::string &email) { | ||||||
| 		// define a regular expression | 		// define a regular expression | ||||||
| 	static const std::regex pattern | 		static const std::regex pattern( | ||||||
| 		("[_a-z0-9-]+(\\.[_a-z0-9-]+)*(\\+[a-z0-9-]+)?@[a-z0-9-]+(\\.[a-z0-9-]+)*"); | 			"[_a-z0-9-]+(\\.[_a-z0-9-]+)*(\\+[a-z0-9-]+)?@[a-z0-9-]+(\\.[a-z0-9-]+)*"); | ||||||
| 		// try to match the string with the regular expression | 		// try to match the string with the regular expression | ||||||
| 		return std::regex_match(email, pattern); | 		return std::regex_match(email, pattern); | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] std::string LoadFile( const Poco::File & F) { | 	[[nodiscard]] std::string LoadFile(const Poco::File &F) { | ||||||
| 		std::string Result; | 		std::string Result; | ||||||
| 		try { | 		try { | ||||||
| 			std::ostringstream OS; | 			std::ostringstream OS; | ||||||
| @@ -389,45 +415,45 @@ bool CompareTime( int H1, int H2, int M1, int M2, int S1, int S2) { | |||||||
| 			Poco::StreamCopier::copyStream(IF, OS); | 			Poco::StreamCopier::copyStream(IF, OS); | ||||||
| 			Result = OS.str(); | 			Result = OS.str(); | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| } |  | ||||||
|  |  | ||||||
| void ReplaceVariables( std::string & Content , const Types::StringPairVec & P) { |  | ||||||
| 	for(const auto &[Variable,Value]:P) { |  | ||||||
| 		Poco::replaceInPlace(Content,"${" + Variable + "}", Value); |  | ||||||
| 	} | 	} | ||||||
| } |  | ||||||
|  |  | ||||||
| [[nodiscard]] MediaTypeEncoding FindMediaType(const Poco::File &F) { | 	void ReplaceVariables(std::string &Content, const Types::StringPairVec &P) { | ||||||
|  | 		for (const auto &[Variable, Value] : P) { | ||||||
|  | 			Poco::replaceInPlace(Content, "${" + Variable + "}", Value); | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	[[nodiscard]] MediaTypeEncoding FindMediaType(const Poco::File &F) { | ||||||
| 		const auto E = Poco::Path(F.path()).getExtension(); | 		const auto E = Poco::Path(F.path()).getExtension(); | ||||||
| 	if(E=="png") | 		if (E == "png") | ||||||
| 		return MediaTypeEncoding{   .Encoding = BINARY, | 			return MediaTypeEncoding{.Encoding = BINARY, .ContentType = "image/png"}; | ||||||
| 								 .ContentType = "image/png" }; | 		if (E == "gif") | ||||||
| 	if(E=="gif") | 			return MediaTypeEncoding{.Encoding = BINARY, .ContentType = "image/gif"}; | ||||||
| 		return MediaTypeEncoding{   .Encoding = BINARY, | 		if (E == "jpeg" || E == "jpg") | ||||||
| 								 .ContentType = "image/gif" }; | 			return MediaTypeEncoding{.Encoding = BINARY, .ContentType = "image/jpeg"}; | ||||||
| 	if(E=="jpeg" || E=="jpg") | 		if (E == "svg" || E == "svgz") | ||||||
| 		return MediaTypeEncoding{   .Encoding = BINARY, | 			return MediaTypeEncoding{.Encoding = PLAIN, .ContentType = "image/svg+xml"}; | ||||||
| 								 .ContentType = "image/jpeg" }; | 		if (E == "html") | ||||||
| 	if(E=="svg" || E=="svgz") | 			return MediaTypeEncoding{.Encoding = PLAIN, .ContentType = "text/html"}; | ||||||
| 		return MediaTypeEncoding{   .Encoding = PLAIN, | 		if (E == "css") | ||||||
| 								 .ContentType = "image/svg+xml" }; | 			return MediaTypeEncoding{.Encoding = PLAIN, .ContentType = "text/css"}; | ||||||
| 	if(E=="html") | 		if (E == "js") | ||||||
| 		return MediaTypeEncoding{   .Encoding = PLAIN, | 			return MediaTypeEncoding{.Encoding = PLAIN, .ContentType = "application/javascript"}; | ||||||
| 								 .ContentType = "text/html" }; | 		if (E == "pcap") | ||||||
| 	if(E=="css") | 			return MediaTypeEncoding{.Encoding = BINARY, .ContentType = "application/vnd.tcpdump.pcap"}; | ||||||
| 		return MediaTypeEncoding{   .Encoding = PLAIN, | 		if (E == "txt") | ||||||
| 								 .ContentType = "text/css" }; | 			return MediaTypeEncoding{.Encoding = PLAIN, .ContentType = "text/plain"}; | ||||||
| 	if(E=="js") | 		if (E == "tgz") | ||||||
| 		return MediaTypeEncoding{   .Encoding = PLAIN, | 			return MediaTypeEncoding{.Encoding = BINARY, .ContentType = "application/tar+gzip"}; | ||||||
| 								 .ContentType = "application/javascript" }; | 		if (E == "gz" || E=="gzip") | ||||||
| 	return MediaTypeEncoding{       .Encoding = BINARY, | 			return MediaTypeEncoding{.Encoding = BINARY, .ContentType = "application/gzip"}; | ||||||
| 							 .ContentType = "application/octet-stream" }; |  | ||||||
| } |  | ||||||
|  |  | ||||||
| [[nodiscard]] std::string BinaryFileToHexString(const Poco::File &F) { | 		return MediaTypeEncoding{.Encoding = BINARY, .ContentType = "application/octet-stream"}; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	[[nodiscard]] std::string BinaryFileToHexString(const Poco::File &F) { | ||||||
| 		static const char hex[] = "0123456789abcdef"; | 		static const char hex[] = "0123456789abcdef"; | ||||||
| 		std::string Result; | 		std::string Result; | ||||||
| 		try { | 		try { | ||||||
| @@ -442,28 +468,28 @@ void ReplaceVariables( std::string & Content , const Types::StringPairVec & P) { | |||||||
| 				Count++; | 				Count++; | ||||||
| 				unsigned char C = IF.get(); | 				unsigned char C = IF.get(); | ||||||
| 				Result += "0x"; | 				Result += "0x"; | ||||||
| 			Result += (char) (hex[(C & 0xf0) >> 4]); | 				Result += (char)(hex[(C & 0xf0) >> 4]); | ||||||
| 			Result += (char) (hex[(C & 0x0f)]); | 				Result += (char)(hex[(C & 0x0f)]); | ||||||
| 			} | 			} | ||||||
| 	} catch(...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return Result; | 		return Result; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] std::string SecondsToNiceText(uint64_t Seconds) { | 	[[nodiscard]] std::string SecondsToNiceText(uint64_t Seconds) { | ||||||
| 		std::string Result; | 		std::string Result; | ||||||
| 	int Days = Seconds / (24*60*60); | 		int Days = Seconds / (24 * 60 * 60); | ||||||
| 	Seconds -= Days * (24*60*60); | 		Seconds -= Days * (24 * 60 * 60); | ||||||
| 	int Hours= Seconds / (60*60); | 		int Hours = Seconds / (60 * 60); | ||||||
| 	Seconds -= Hours * (60*60); | 		Seconds -= Hours * (60 * 60); | ||||||
| 		int Minutes = Seconds / 60; | 		int Minutes = Seconds / 60; | ||||||
| 		Seconds -= Minutes * 60; | 		Seconds -= Minutes * 60; | ||||||
| 	Result = std::to_string(Days) +" days, " + std::to_string(Hours) + ":" + std::to_string(Minutes) + ":" + std::to_string(Seconds); | 		Result = std::to_string(Days) + " days, " + std::to_string(Hours) + ":" + | ||||||
|  | 				 std::to_string(Minutes) + ":" + std::to_string(Seconds); | ||||||
| 		return Result; | 		return Result; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] bool wgets(const std::string &URL, std::string &Response) { | 	[[nodiscard]] bool wgets(const std::string &URL, std::string &Response) { | ||||||
| 		try { | 		try { | ||||||
| 			Poco::URI uri(URL); | 			Poco::URI uri(URL); | ||||||
| 			Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort()); | 			Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort()); | ||||||
| @@ -475,64 +501,66 @@ void ReplaceVariables( std::string & Content , const Types::StringPairVec & P) { | |||||||
| 			} | 			} | ||||||
|  |  | ||||||
| 			// send request | 			// send request | ||||||
| 		Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1); | 			Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, path, | ||||||
|  | 									   Poco::Net::HTTPMessage::HTTP_1_1); | ||||||
| 			session.sendRequest(req); | 			session.sendRequest(req); | ||||||
|  |  | ||||||
| 			Poco::Net::HTTPResponse res; | 			Poco::Net::HTTPResponse res; | ||||||
| 			std::istream &is = session.receiveResponse(res); | 			std::istream &is = session.receiveResponse(res); | ||||||
| 			std::ostringstream os; | 			std::ostringstream os; | ||||||
|  |  | ||||||
| 		Poco::StreamCopier::copyStream(is,os); | 			Poco::StreamCopier::copyStream(is, os); | ||||||
| 			Response = os.str(); | 			Response = os.str(); | ||||||
|  |  | ||||||
| 			return true; | 			return true; | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return false; | 		return false; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| [[nodiscard]] bool wgetfile(const Poco::URI &uri, const std::string &FileName) { | 	[[nodiscard]] bool wgetfile(const Poco::URI &uri, const std::string &FileName) { | ||||||
| 		try { | 		try { | ||||||
| 			Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort()); | 			Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort()); | ||||||
|  |  | ||||||
| 			// send request | 			// send request | ||||||
| 		Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, uri.getPath(), Poco::Net::HTTPMessage::HTTP_1_1); | 			Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, uri.getPath(), | ||||||
|  | 									   Poco::Net::HTTPMessage::HTTP_1_1); | ||||||
| 			session.sendRequest(req); | 			session.sendRequest(req); | ||||||
|  |  | ||||||
| 			Poco::Net::HTTPResponse res; | 			Poco::Net::HTTPResponse res; | ||||||
| 			std::istream &is = session.receiveResponse(res); | 			std::istream &is = session.receiveResponse(res); | ||||||
| 		std::fstream os(FileName,std::ios_base::trunc | std::ios_base::binary | std::ios_base::out); | 			std::fstream os(FileName, | ||||||
| 		Poco::StreamCopier::copyStream(is,os); | 							std::ios_base::trunc | std::ios_base::binary | std::ios_base::out); | ||||||
|  | 			Poco::StreamCopier::copyStream(is, os); | ||||||
| 			return true; | 			return true; | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return false; | 		return false; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| bool ExtractBase64CompressedData(const std::string &CompressedData, | 	bool ExtractBase64CompressedData(const std::string &CompressedData, | ||||||
| 										std::string &UnCompressedData, uint64_t compress_sz ) { | 									 std::string &UnCompressedData, uint64_t compress_sz) { | ||||||
| 		std::istringstream ifs(CompressedData); | 		std::istringstream ifs(CompressedData); | ||||||
| 		Poco::Base64Decoder b64in(ifs); | 		Poco::Base64Decoder b64in(ifs); | ||||||
| 		std::ostringstream ofs; | 		std::ostringstream ofs; | ||||||
| 		Poco::StreamCopier::copyStream(b64in, ofs); | 		Poco::StreamCopier::copyStream(b64in, ofs); | ||||||
|  |  | ||||||
| 		int factor = 20; | 		int factor = 20; | ||||||
| 	unsigned long MaxSize = compress_sz ? (unsigned long) (compress_sz + 5000) : (unsigned long) (ofs.str().size() * factor); | 		unsigned long MaxSize = compress_sz ? (unsigned long)(compress_sz + 5000) | ||||||
| 	while(true) { | 											: (unsigned long)(ofs.str().size() * factor); | ||||||
|  | 		while (true) { | ||||||
| 			std::vector<uint8_t> UncompressedBuffer(MaxSize); | 			std::vector<uint8_t> UncompressedBuffer(MaxSize); | ||||||
| 			unsigned long FinalSize = MaxSize; | 			unsigned long FinalSize = MaxSize; | ||||||
| 			auto status = uncompress((uint8_t *)&UncompressedBuffer[0], &FinalSize, | 			auto status = uncompress((uint8_t *)&UncompressedBuffer[0], &FinalSize, | ||||||
| 									 (uint8_t *)ofs.str().c_str(), ofs.str().size()); | 									 (uint8_t *)ofs.str().c_str(), ofs.str().size()); | ||||||
| 		if(status==Z_OK) { | 			if (status == Z_OK) { | ||||||
| 				UncompressedBuffer[FinalSize] = 0; | 				UncompressedBuffer[FinalSize] = 0; | ||||||
| 				UnCompressedData = (char *)&UncompressedBuffer[0]; | 				UnCompressedData = (char *)&UncompressedBuffer[0]; | ||||||
| 				return true; | 				return true; | ||||||
| 			} | 			} | ||||||
| 		if(status==Z_BUF_ERROR) { | 			if (status == Z_BUF_ERROR) { | ||||||
| 			if(factor<300) { | 				if (factor < 300) { | ||||||
| 				factor+=10; | 					factor += 10; | ||||||
| 					MaxSize = ofs.str().size() * factor; | 					MaxSize = ofs.str().size() * factor; | ||||||
| 					continue; | 					continue; | ||||||
| 				} else { | 				} else { | ||||||
| @@ -542,15 +570,15 @@ bool ExtractBase64CompressedData(const std::string &CompressedData, | |||||||
| 			return false; | 			return false; | ||||||
| 		} | 		} | ||||||
| 		return false; | 		return false; | ||||||
| } | 	} | ||||||
|  |  | ||||||
| 	bool IsAlphaNumeric(const std::string &s) { | 	bool IsAlphaNumeric(const std::string &s) { | ||||||
|         return std::all_of(s.begin(),s.end(),[](char c) -> bool { return isalnum(c); }); | 		return std::all_of(s.begin(), s.end(), [](char c) -> bool { return isalnum(c); }); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	std::string SanitizeToken(const std::string &Token) { | 	std::string SanitizeToken(const std::string &Token) { | ||||||
|         if(Token.size()>8) { | 		if (Token.size() > 8) { | ||||||
|             return Token.substr(0,4) + "****" + Token.substr(Token.size()-4,4); | 			return Token.substr(0, 4) + "****" + Token.substr(Token.size() - 4, 4); | ||||||
| 		} | 		} | ||||||
| 		return "*******"; | 		return "*******"; | ||||||
| 	} | 	} | ||||||
| @@ -560,7 +588,6 @@ bool ExtractBase64CompressedData(const std::string &CompressedData, | |||||||
| 			Poco::URI u(uri); | 			Poco::URI u(uri); | ||||||
| 			return true; | 			return true; | ||||||
| 		} catch (...) { | 		} catch (...) { | ||||||
|  |  | ||||||
| 		} | 		} | ||||||
| 		return false; | 		return false; | ||||||
| 	} | 	} | ||||||
| @@ -568,8 +595,8 @@ bool ExtractBase64CompressedData(const std::string &CompressedData, | |||||||
| 	[[nodiscard]] std::uint64_t ConvertDate(const std::string &Date) { | 	[[nodiscard]] std::uint64_t ConvertDate(const std::string &Date) { | ||||||
| 		Poco::DateTime DT; | 		Poco::DateTime DT; | ||||||
| 		int TZ; | 		int TZ; | ||||||
|         Poco::DateTimeParser::parse(Poco::DateTimeFormat::ISO8601_FORMAT,Date,DT,TZ); | 		Poco::DateTimeParser::parse(Poco::DateTimeFormat::ISO8601_FORMAT, Date, DT, TZ); | ||||||
| 		return DT.timestamp().epochTime(); | 		return DT.timestamp().epochTime(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| } | } // namespace OpenWifi::Utils | ||||||
|   | |||||||
| @@ -4,115 +4,114 @@ | |||||||
|  |  | ||||||
| #pragma once | #pragma once | ||||||
|  |  | ||||||
| #include <string> |  | ||||||
| #include <fstream> | #include <fstream> | ||||||
| #include <iostream> |  | ||||||
| #include <iomanip> | #include <iomanip> | ||||||
|  | #include <iostream> | ||||||
| #include <random> | #include <random> | ||||||
| #include <regex> | #include <regex> | ||||||
| #include <thread> |  | ||||||
| #include <shared_mutex> | #include <shared_mutex> | ||||||
|  | #include <string> | ||||||
|  | #include <thread> | ||||||
|  |  | ||||||
| #include "Poco/Thread.h" |  | ||||||
| #include "Poco/StringTokenizer.h" |  | ||||||
| #include "Poco/String.h" |  | ||||||
| #include "Poco/SHA2Engine.h" |  | ||||||
| #include "Poco/Message.h" |  | ||||||
| #include "Poco/StreamCopier.h" |  | ||||||
| #include "Poco/File.h" |  | ||||||
| #include "Poco/Net/NetworkInterface.h" |  | ||||||
| #include "Poco/URI.h" |  | ||||||
| #include "Poco/Net/HTTPRequest.h" |  | ||||||
| #include "Poco/Net/HTTPClientSession.h" |  | ||||||
| #include "Poco/Net/HTTPSClientSession.h" |  | ||||||
| #include "Poco/Net/HTTPResponse.h" |  | ||||||
| #include "Poco/Base64Decoder.h" | #include "Poco/Base64Decoder.h" | ||||||
| #include "Poco/Base64Encoder.h" | #include "Poco/Base64Encoder.h" | ||||||
|  | #include "Poco/File.h" | ||||||
|  | #include "Poco/Message.h" | ||||||
|  | #include "Poco/Net/HTTPClientSession.h" | ||||||
|  | #include "Poco/Net/HTTPRequest.h" | ||||||
|  | #include "Poco/Net/HTTPResponse.h" | ||||||
|  | #include "Poco/Net/HTTPSClientSession.h" | ||||||
|  | #include "Poco/Net/NetworkInterface.h" | ||||||
|  | #include "Poco/SHA2Engine.h" | ||||||
|  | #include "Poco/StreamCopier.h" | ||||||
|  | #include "Poco/String.h" | ||||||
|  | #include "Poco/StringTokenizer.h" | ||||||
|  | #include "Poco/Thread.h" | ||||||
|  | #include "Poco/URI.h" | ||||||
| #include "Poco/zlib.h" | #include "Poco/zlib.h" | ||||||
|  |  | ||||||
| #include "framework/ow_constants.h" |  | ||||||
| #include "framework/OpenWifiTypes.h" | #include "framework/OpenWifiTypes.h" | ||||||
|  | #include "framework/ow_constants.h" | ||||||
|  |  | ||||||
| namespace OpenWifi::Utils { | namespace OpenWifi::Utils { | ||||||
|  |  | ||||||
| 	inline uint64_t Now() { return std::time(nullptr); }; | 	inline uint64_t Now() { return std::time(nullptr); }; | ||||||
|  |  | ||||||
| 	bool NormalizeMac(std::string & Mac); | 	bool NormalizeMac(std::string &Mac); | ||||||
|  |  | ||||||
| 	inline void SetThreadName(const char *name) { | 	inline void SetThreadName(const char *name) { | ||||||
| 	#ifdef __linux__ | #ifdef __linux__ | ||||||
| 		Poco::Thread::current()->setName(name); | 		Poco::Thread::current()->setName(name); | ||||||
| 		pthread_setname_np(pthread_self(), name); | 		pthread_setname_np(pthread_self(), name); | ||||||
| 	#endif | #endif | ||||||
| 	#ifdef __APPLE__ | #ifdef __APPLE__ | ||||||
| 		Poco::Thread::current()->setName(name); | 		Poco::Thread::current()->setName(name); | ||||||
| 		pthread_setname_np(name); | 		pthread_setname_np(name); | ||||||
| 	#endif | #endif | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline void SetThreadName(Poco::Thread &thr, const char *name) { | 	inline void SetThreadName(Poco::Thread &thr, const char *name) { | ||||||
| 	#ifdef __linux__ | #ifdef __linux__ | ||||||
| 		thr.setName(name); | 		thr.setName(name); | ||||||
| 		pthread_setname_np(thr.tid(), name); | 		pthread_setname_np(thr.tid(), name); | ||||||
| 	#endif | #endif | ||||||
| 	#ifdef __APPLE__ | #ifdef __APPLE__ | ||||||
| 		thr.setName(name); | 		thr.setName(name); | ||||||
| 	#endif | #endif | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	enum MediaTypeEncodings { | 	enum MediaTypeEncodings { PLAIN, BINARY, BASE64 }; | ||||||
| 		PLAIN, |  | ||||||
| 		BINARY, |  | ||||||
| 		BASE64 |  | ||||||
| 	}; |  | ||||||
|  |  | ||||||
| 	struct MediaTypeEncoding { | 	struct MediaTypeEncoding { | ||||||
| 		MediaTypeEncodings  Encoding=PLAIN; | 		MediaTypeEncodings Encoding = PLAIN; | ||||||
| 		std::string ContentType; | 		std::string ContentType; | ||||||
| 	}; | 	}; | ||||||
|  |  | ||||||
| 	[[nodiscard]] bool ValidSerialNumber(const std::string &Serial); | 	[[nodiscard]] bool ValidSerialNumber(const std::string &Serial); | ||||||
|  | 	[[nodiscard]] bool ValidSerialNumbers(const std::vector<std::string> &Serial); | ||||||
| 	[[nodiscard]] bool ValidUUID(const std::string &UUID); | 	[[nodiscard]] bool ValidUUID(const std::string &UUID); | ||||||
| 	[[nodiscard]] bool ValidHostname(const std::string &hostname); | 	[[nodiscard]] bool ValidHostname(const std::string &hostname); | ||||||
|  |  | ||||||
| 	template <typename ...Args> std::string ComputeHash(Args&&... args) { | 	template <typename... Args> std::string ComputeHash(Args &&...args) { | ||||||
| 		Poco::SHA2Engine E; | 		Poco::SHA2Engine E; | ||||||
| 		auto as_string = [](auto p) { | 		auto as_string = [](auto p) { | ||||||
| 			if constexpr(std::is_arithmetic_v<decltype(p)>) { | 			if constexpr (std::is_arithmetic_v<decltype(p)>) { | ||||||
| 				return std::to_string(p); | 				return std::to_string(p); | ||||||
| 			} else { | 			} else { | ||||||
| 				return p; | 				return p; | ||||||
| 			} | 			} | ||||||
| 		}; | 		}; | ||||||
| 		(E.update(as_string(args)),...); | 		(E.update(as_string(args)), ...); | ||||||
| 		return Poco::SHA2Engine::digestToHex(E.digest()); | 		return Poco::SHA2Engine::digestToHex(E.digest()); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	[[nodiscard]] std::vector<std::string> Split(const std::string &List, char Delimiter=',' ); | 	[[nodiscard]] std::vector<std::string> Split(const std::string &List, char Delimiter = ','); | ||||||
| 	[[nodiscard]] std::string FormatIPv6(const std::string & I ); | 	[[nodiscard]] std::string FormatIPv6(const std::string &I); | ||||||
| 	void padTo(std::string& str, size_t num, char paddingChar = '\0'); | 	void padTo(std::string &str, size_t num, char paddingChar = '\0'); | ||||||
| 	[[nodiscard]] std::string SerialToMAC(const std::string &Serial); | 	[[nodiscard]] std::string SerialToMAC(const std::string &Serial); | ||||||
| 	uint64_t MACToInt(const std::string &MAC); | 	uint64_t MACToInt(const std::string &MAC); | ||||||
| 	[[nodiscard]] std::string ToHex(const std::vector<unsigned char> & B); | 	[[nodiscard]] std::string ToHex(const std::vector<unsigned char> &B); | ||||||
|  |  | ||||||
| 	using byte = std::uint8_t; | 	using byte = std::uint8_t; | ||||||
|  |  | ||||||
| 	[[nodiscard]] std::string base64encode(const byte *input, uint32_t size); | 	[[nodiscard]] std::string base64encode(const byte *input, uint32_t size); | ||||||
| 	[[nodiscard]] std::vector<byte> base64decode(const std::string& input);; | 	[[nodiscard]] std::vector<byte> base64decode(const std::string &input); | ||||||
| 	bool ParseTime(const std::string &Time, int & Hours, int & Minutes, int & Seconds); | 	; | ||||||
| 	bool ParseDate(const std::string &Time, int & Year, int & Month, int & Day); | 	bool ParseTime(const std::string &Time, int &Hours, int &Minutes, int &Seconds); | ||||||
| 	bool CompareTime( int H1, int H2, int M1, int M2, int S1, int S2); | 	bool ParseDate(const std::string &Time, int &Year, int &Month, int &Day); | ||||||
|  | 	bool CompareTime(int H1, int H2, int M1, int M2, int S1, int S2); | ||||||
| 	[[nodiscard]] std::string LogLevelToString(int Level); | 	[[nodiscard]] std::string LogLevelToString(int Level); | ||||||
| 	[[nodiscard]] uint64_t SerialNumberToInt(const std::string & S); | 	[[nodiscard]] uint64_t SerialNumberToInt(const std::string &S); | ||||||
| 	[[nodiscard]] std::string IntToSerialNumber(uint64_t S); | 	[[nodiscard]] std::string IntToSerialNumber(uint64_t S); | ||||||
| 	[[nodiscard]] bool SerialNumberMatch(const std::string &S1, const std::string &S2, int Bits=2); | 	[[nodiscard]] bool SerialNumberMatch(const std::string &S1, const std::string &S2, | ||||||
| 	[[nodiscard]] uint64_t SerialNumberToOUI(const std::string & S); | 										 int Bits = 2); | ||||||
|  | 	[[nodiscard]] uint64_t SerialNumberToOUI(const std::string &S); | ||||||
| 	[[nodiscard]] uint64_t GetDefaultMacAsInt64(); | 	[[nodiscard]] uint64_t GetDefaultMacAsInt64(); | ||||||
| 	[[nodiscard]] uint64_t InitializeSystemId(); | 	[[nodiscard]] uint64_t InitializeSystemId(); | ||||||
| 	[[nodiscard]] uint64_t GetSystemId(); | 	[[nodiscard]] uint64_t GetSystemId(); | ||||||
| 	[[nodiscard]] bool ValidEMailAddress(const std::string &email); | 	[[nodiscard]] bool ValidEMailAddress(const std::string &email); | ||||||
| 	[[nodiscard]] std::string LoadFile( const Poco::File & F); | 	[[nodiscard]] std::string LoadFile(const Poco::File &F); | ||||||
| 	void ReplaceVariables( std::string & Content , const Types::StringPairVec & P); | 	void ReplaceVariables(std::string &Content, const Types::StringPairVec &P); | ||||||
| 	[[nodiscard]] MediaTypeEncoding FindMediaType(const Poco::File &F); | 	[[nodiscard]] MediaTypeEncoding FindMediaType(const Poco::File &F); | ||||||
| 	[[nodiscard]] std::string BinaryFileToHexString(const Poco::File &F); | 	[[nodiscard]] std::string BinaryFileToHexString(const Poco::File &F); | ||||||
| 	[[nodiscard]] std::string SecondsToNiceText(uint64_t Seconds); | 	[[nodiscard]] std::string SecondsToNiceText(uint64_t Seconds); | ||||||
| @@ -124,25 +123,22 @@ namespace OpenWifi::Utils { | |||||||
|  |  | ||||||
| 	[[nodiscard]] std::uint64_t ConvertDate(const std::string &d); | 	[[nodiscard]] std::uint64_t ConvertDate(const std::string &d); | ||||||
|  |  | ||||||
| 	template< typename T > | 	template <typename T> std::string int_to_hex(T i) { | ||||||
| 	std::string int_to_hex( T i ) |  | ||||||
| 	{ |  | ||||||
| 		std::stringstream stream; | 		std::stringstream stream; | ||||||
| 		stream << std::setfill ('0') << std::setw(12) | 		stream << std::setfill('0') << std::setw(12) << std::hex << i; | ||||||
| 			   << std::hex << i; |  | ||||||
| 		return stream.str(); | 		return stream.str(); | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline bool SpinLock_Read(std::shared_mutex &M, volatile bool &Flag, uint64_t wait_ms=100) { | 	inline bool SpinLock_Read(std::shared_mutex &M, volatile bool &Flag, uint64_t wait_ms = 100) { | ||||||
| 		while(!M.try_lock_shared() && Flag) { | 		while (!M.try_lock_shared() && Flag) { | ||||||
| 			Poco::Thread::yield(); | 			Poco::Thread::yield(); | ||||||
| 			Poco::Thread::trySleep((long)wait_ms); | 			Poco::Thread::trySleep((long)wait_ms); | ||||||
| 		} | 		} | ||||||
| 		return Flag; | 		return Flag; | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	inline bool SpinLock_Write(std::shared_mutex &M, volatile bool &Flag, uint64_t wait_ms=100) { | 	inline bool SpinLock_Write(std::shared_mutex &M, volatile bool &Flag, uint64_t wait_ms = 100) { | ||||||
| 		while(!M.try_lock() && Flag) { | 		while (!M.try_lock() && Flag) { | ||||||
| 			Poco::Thread::yield(); | 			Poco::Thread::yield(); | ||||||
| 			Poco::Thread::trySleep(wait_ms); | 			Poco::Thread::trySleep(wait_ms); | ||||||
| 		} | 		} | ||||||
| @@ -150,5 +146,39 @@ namespace OpenWifi::Utils { | |||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	bool ExtractBase64CompressedData(const std::string &CompressedData, | 	bool ExtractBase64CompressedData(const std::string &CompressedData, | ||||||
| 											std::string &UnCompressedData, uint64_t compress_sz ); | 									 std::string &UnCompressedData, uint64_t compress_sz); | ||||||
| } |  | ||||||
|  | 	inline bool match(const char* first, const char* second) | ||||||
|  | 	{ | ||||||
|  | 		// If we reach at the end of both strings, we are done | ||||||
|  | 		if (*first == '\0' && *second == '\0') | ||||||
|  | 			return true; | ||||||
|  |  | ||||||
|  | 		// Make sure to eliminate consecutive '*' | ||||||
|  | 		if (*first == '*') { | ||||||
|  | 			while (*(first + 1) == '*') | ||||||
|  | 				first++; | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		// Make sure that the characters after '*' are present | ||||||
|  | 		// in second string. This function assumes that the | ||||||
|  | 		// first string will not contain two consecutive '*' | ||||||
|  | 		if (*first == '*' && *(first + 1) != '\0' | ||||||
|  | 			&& *second == '\0') | ||||||
|  | 			return false; | ||||||
|  |  | ||||||
|  | 		// If the first string contains '?', or current | ||||||
|  | 		// characters of both strings match | ||||||
|  | 		if (*first == '?' || *first == *second) | ||||||
|  | 			return match(first + 1, second + 1); | ||||||
|  |  | ||||||
|  | 		// If there is *, then there are two possibilities | ||||||
|  | 		// a) We consider current character of second string | ||||||
|  | 		// b) We ignore current character of second string. | ||||||
|  | 		if (*first == '*') | ||||||
|  | 			return match(first + 1, second) | ||||||
|  | 				   || match(first, second + 1); | ||||||
|  | 		return false; | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | } // namespace OpenWifi::Utils | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user