From c0e3303e4925cbf5b48bbe4fcaf53b78de83fbab Mon Sep 17 00:00:00 2001 From: stephb9959 Date: Tue, 21 Feb 2023 08:31:20 -0800 Subject: [PATCH] https://telecominfraproject.atlassian.net/browse/WIFI-12068 Signed-off-by: stephb9959 --- .clang-format | 183 ++- CMakeLists.txt | 2 +- build | 2 +- src/AP_WS_Connection.cpp | 683 ++++++----- src/AP_WS_Connection.h | 136 ++- src/AP_WS_Process_alarm.cpp | 10 +- src/AP_WS_Process_cfgpending.cpp | 10 +- src/AP_WS_Process_connect.cpp | 119 +- src/AP_WS_Process_crashlog.cpp | 4 +- src/AP_WS_Process_deviceupdate.cpp | 14 +- src/AP_WS_Process_event.cpp | 15 +- src/AP_WS_Process_healthcheck.cpp | 19 +- src/AP_WS_Process_log.cpp | 10 +- src/AP_WS_Process_ping.cpp | 2 +- src/AP_WS_Process_recovery.cpp | 29 +- src/AP_WS_Process_state.cpp | 27 +- src/AP_WS_Process_telemetry.cpp | 30 +- src/AP_WS_Process_venuebroadcast.cpp | 11 +- src/AP_WS_Process_wifiscan.cpp | 10 +- src/AP_WS_ReactorPool.h | 26 +- src/AP_WS_Server.cpp | 221 ++-- src/AP_WS_Server.h | 190 +-- src/CapabilitiesCache.h | 88 +- src/CentralConfig.cpp | 152 ++- src/CentralConfig.h | 67 +- src/CommandManager.cpp | 296 ++--- src/CommandManager.h | 328 +++-- src/ConfigurationCache.h | 19 +- src/Daemon.cpp | 136 +-- src/Daemon.h | 61 +- src/Dashboard.cpp | 23 +- src/Dashboard.h | 20 +- src/FileUploader.cpp | 242 ++-- src/FileUploader.h | 72 +- src/FindCountry.h | 93 +- src/GWKafkaEvents.cpp | 2 +- src/GWKafkaEvents.h | 61 +- src/GwWebSocketClient.cpp | 27 +- src/GwWebSocketClient.h | 16 +- src/OUIServer.cpp | 95 +- src/OUIServer.h | 33 +- src/ParseWifiScan.h | 1673 +++++++++++++------------- src/RADIUS_helpers.h | 790 ++++++------ src/RADIUS_proxy_server.cpp | 504 ++++---- src/RADIUS_proxy_server.h | 117 +- src/RADSEC_server.h | 171 +-- src/SDKcalls.cpp | 18 +- src/SDKcalls.h | 7 +- src/ScriptManager.cpp | 11 +- src/ScriptManager.h | 10 +- src/SerialNumberCache.cpp | 46 +- src/SerialNumberCache.h | 29 +- src/SignatureMgr.cpp | 7 - src/SignatureMgr.h | 87 +- src/StateUtils.cpp | 72 +- src/StateUtils.h | 2 +- src/StorageArchiver.cpp | 83 +- src/StorageArchiver.h | 70 +- src/StorageService.cpp | 25 +- src/StorageService.h | 233 ++-- src/TelemetryClient.cpp | 133 +- src/TelemetryClient.h | 44 +- src/TelemetryStream.cpp | 125 +- src/TelemetryStream.h | 78 +- src/UI_GW_WebSocketNotifications.cpp | 107 +- src/UI_GW_WebSocketNotifications.h | 43 +- src/VenueBroadcaster.h | 119 +- 67 files changed, 4291 insertions(+), 3897 deletions(-) delete mode 100644 src/SignatureMgr.cpp diff --git a/.clang-format b/.clang-format index 4f7c1744..631f8b9f 100644 --- a/.clang-format +++ b/.clang-format @@ -1,7 +1,178 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveMacros: None +AlignConsecutiveAssignments: None +AlignConsecutiveBitFields: None +AlignConsecutiveDeclarations: None +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: true +AllowAllConstructorInitializersOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortEnumsOnASingleLine: true +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortLambdasOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeConceptDeclarations: true +BreakBeforeBraces: Attach +BreakBeforeInheritanceComma: false +BreakInheritanceList: BeforeColon +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 100 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DeriveLineEnding: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseLabels: false +IndentCaseBlocks: false +IndentGotoLabels: true +IndentPPDirectives: None +IndentExternBlock: AfterExternBlock +IndentRequires: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertTrailingCommas: None +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +LambdaBodyIndentation: Signature +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: All +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PenaltyIndentedWhitespace: 0 +PointerAlignment: Right +PPIndentWidth: -1 +ReferenceAlignment: Pointer +ReflowComments: true +ShortNamespaceLines: 1 +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatements +SpaceAroundPointerQualifiers: Default +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyBlock: false +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInConditionalStatement: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParentheses: false +SpacesInSquareBrackets: false +SpaceBeforeSquareBrackets: false +BitFieldColonSpacing: Both +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 4 +UseCRLF: false +UseTab: Always +WhitespaceSensitiveMacros: + - STRINGIZE + - PP_STRINGIZE + - BOOST_PP_STRINGIZE + - NS_SWIFT_NAME + - CF_SWIFT_NAME +... -BasedOnStyle: LLVM -TabWidth: 4 -IndentWidth: 4 -UseTab: Always -ColumnLimit: 100 -Language: Cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 90fe6e27..83e7c859 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -195,7 +195,7 @@ add_executable( owgw src/AP_WS_Process_telemetry.cpp src/AP_WS_Process_venuebroadcast.cpp src/RADSEC_server.h - src/UI_GW_WebSocketNotifications.cpp src/UI_GW_WebSocketNotifications.h src/framework/RESTAPI_SystemConfiguration.h src/ScriptManager.cpp src/ScriptManager.h src/RESTAPI/RESTAPI_scripts_handler.cpp src/RESTAPI/RESTAPI_scripts_handler.h src/RESTAPI/RESTAPI_script_handler.cpp src/RESTAPI/RESTAPI_script_handler.h src/storage/storage_scripts.cpp src/storage/storage_scripts.h src/SignatureMgr.cpp src/SignatureMgr.h src/AP_WS_Process_event.cpp src/AP_WS_Process_wifiscan.cpp src/AP_WS_Process_alarm.cpp src/GWKafkaEvents.cpp src/GWKafkaEvents.h) + src/UI_GW_WebSocketNotifications.cpp src/UI_GW_WebSocketNotifications.h src/framework/RESTAPI_SystemConfiguration.h src/ScriptManager.cpp src/ScriptManager.h src/RESTAPI/RESTAPI_scripts_handler.cpp src/RESTAPI/RESTAPI_scripts_handler.h src/RESTAPI/RESTAPI_script_handler.cpp src/RESTAPI/RESTAPI_script_handler.h src/storage/storage_scripts.cpp src/storage/storage_scripts.h src/SignatureMgr.h src/AP_WS_Process_event.cpp src/AP_WS_Process_wifiscan.cpp src/AP_WS_Process_alarm.cpp src/GWKafkaEvents.cpp src/GWKafkaEvents.h) if(NOT SMALL_BUILD) diff --git a/build b/build index 597975b4..dce6588c 100644 --- a/build +++ b/build @@ -1 +1 @@ -35 \ No newline at end of file +36 \ No newline at end of file diff --git a/src/AP_WS_Connection.cpp b/src/AP_WS_Connection.cpp index cacd1903..444e782c 100644 --- a/src/AP_WS_Connection.cpp +++ b/src/AP_WS_Connection.cpp @@ -4,13 +4,13 @@ #include "AP_WS_Connection.h" -#include "Poco/Net/SecureStreamSocketImpl.h" -#include "Poco/Net/HTTPServerResponseImpl.h" +#include "Poco/Base64Decoder.h" +#include "Poco/Net/Context.h" #include "Poco/Net/HTTPServerRequestImpl.h" +#include "Poco/Net/HTTPServerResponseImpl.h" #include "Poco/Net/NetException.h" #include "Poco/Net/SSLException.h" -#include "Poco/Net/Context.h" -#include "Poco/Base64Decoder.h" +#include "Poco/Net/SecureStreamSocketImpl.h" #include "Poco/Net/WebSocketImpl.h" #include "Poco/zlib.h" @@ -21,37 +21,37 @@ #include "StorageService.h" #include "TelemetryStream.h" +#include "GWKafkaEvents.h" +#include "UI_GW_WebSocketNotifications.h" #include "framework/KafkaManager.h" #include "framework/MicroServiceFuncs.h" #include "framework/utils.h" -#include "UI_GW_WebSocketNotifications.h" -#include "GWKafkaEvents.h" #include "fmt/format.h" #include "framework/ow_constants.h" - #include "RADIUS_proxy_server.h" namespace OpenWifi { -#define DBL { std::cout << __LINE__ << " ID: " << ConnectionId_ << " Ser: " << SerialNumber_ << std::endl; } +#define DBL \ + { \ + std::cout << __LINE__ << " ID: " << ConnectionId_ << " Ser: " << SerialNumber_ \ + << std::endl; \ + } void AP_WS_Connection::LogException(const Poco::Exception &E) { - poco_information(Logger_,fmt::format("EXCEPTION({}): {}", CId_, E.displayText())); + poco_information(Logger_, fmt::format("EXCEPTION({}): {}", CId_, E.displayText())); } AP_WS_Connection::AP_WS_Connection(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response, - uint64_t connection_id, - Poco::Logger &L, + uint64_t connection_id, Poco::Logger &L, Poco::Net::SocketReactor &R) - : Logger_(L) , - Reactor_(R) - { + : Logger_(L), Reactor_(R) { State_.sessionId = connection_id; - WS_ = std::make_unique(request,response); + WS_ = std::make_unique(request, response); auto TS = Poco::Timespan(360, 0); @@ -61,30 +61,31 @@ namespace OpenWifi { WS_->setKeepAlive(true); WS_->setBlocking(false); - Reactor_.addEventHandler( - *WS_, Poco::NObserver( - *this, &AP_WS_Connection::OnSocketReadable)); - Reactor_.addEventHandler( - *WS_, Poco::NObserver( - *this, &AP_WS_Connection::OnSocketShutdown)); - Reactor_.addEventHandler( - *WS_, Poco::NObserver( - *this, &AP_WS_Connection::OnSocketError)); + Reactor_.addEventHandler(*WS_, + Poco::NObserver( + *this, &AP_WS_Connection::OnSocketReadable)); + Reactor_.addEventHandler(*WS_, + Poco::NObserver( + *this, &AP_WS_Connection::OnSocketShutdown)); + Reactor_.addEventHandler(*WS_, + Poco::NObserver( + *this, &AP_WS_Connection::OnSocketError)); Registered_ = true; Valid_ = true; } bool AP_WS_Connection::ValidatedDevice() { - if(DeviceValidated_) + if (DeviceValidated_) return true; - if(!Valid_) + if (!Valid_) return false; - std::lock_guard Lock(ConnectionMutex_); + std::lock_guard Lock(ConnectionMutex_); try { auto SockImpl = dynamic_cast(WS_->impl()); - auto SS = dynamic_cast(SockImpl->streamSocketImpl()); + auto SS = + dynamic_cast(SockImpl->streamSocketImpl()); PeerAddress_ = SS->peerAddress().host(); CId_ = Utils::FormatIPv6(SS->peerAddress().toString()); @@ -92,16 +93,22 @@ namespace OpenWifi { State_.started = Utils::Now(); if (!SS->secure()) { - poco_warning(Logger_,fmt::format("TLS-CONNECTION({}): Session={} Connection is NOT secure. Device is not allowed.", CId_, State_.sessionId )); + poco_warning(Logger_, fmt::format("TLS-CONNECTION({}): Session={} Connection is " + "NOT secure. Device is not allowed.", + CId_, State_.sessionId)); EndConnection(); return false; } - poco_debug(Logger_,fmt::format("TLS-CONNECTION({}): Session={} Connection is secure.", CId_, State_.sessionId )); + poco_debug(Logger_, fmt::format("TLS-CONNECTION({}): Session={} Connection is secure.", + CId_, State_.sessionId)); if (!SS->havePeerCertificate()) { State_.VerifiedCertificate = GWObjects::NO_CERTIFICATE; - poco_warning(Logger_,fmt::format("TLS-CONNECTION({}): Session={} No certificates available..", CId_, State_.sessionId )); + poco_warning( + Logger_, + fmt::format("TLS-CONNECTION({}): Session={} No certificates available..", CId_, + State_.sessionId)); EndConnection(); return false; } @@ -109,8 +116,10 @@ namespace OpenWifi { Poco::Crypto::X509Certificate PeerCert(SS->peerCertificate()); if (!AP_WS_Server()->ValidateCertificate(CId_, PeerCert)) { State_.VerifiedCertificate = GWObjects::NO_CERTIFICATE; - poco_warning(Logger_, fmt::format("TLS-CONNECTION({}): Session={} Device certificate is not valid. Device is not allowed.", - CId_, State_.sessionId )); + poco_warning(Logger_, + fmt::format("TLS-CONNECTION({}): Session={} Device certificate is not " + "valid. Device is not allowed.", + CId_, State_.sessionId)); EndConnection(); return false; } @@ -118,13 +127,13 @@ namespace OpenWifi { CN_ = Poco::trim(Poco::toLower(PeerCert.commonName())); State_.VerifiedCertificate = GWObjects::VALID_CERTIFICATE; poco_debug(Logger_, - fmt::format("TLS-CONNECTION({}): Session={} Valid certificate: CN={}", CId_, State_.sessionId , CN_)); + fmt::format("TLS-CONNECTION({}): Session={} Valid certificate: CN={}", CId_, + State_.sessionId, CN_)); if (AP_WS_Server::IsSim(CN_) && !AP_WS_Server()->IsSimEnabled()) { - poco_warning( - Logger_, - fmt::format("TLS-CONNECTION({}): Session={} Sim Device {} is not allowed. Disconnecting.", - CId_, State_.sessionId , CN_)); + poco_warning(Logger_, fmt::format("TLS-CONNECTION({}): Session={} Sim Device {} is " + "not allowed. Disconnecting.", + CId_, State_.sessionId, CN_)); EndConnection(); return false; } @@ -132,11 +141,12 @@ namespace OpenWifi { std::string reason, author; std::uint64_t created; if (!CN_.empty() && StorageService()->IsBlackListed(CN_, reason, author, created)) { - DeviceBlacklistedKafkaEvent KE(CN_,Utils::Now(),reason,author,created,CId_); + DeviceBlacklistedKafkaEvent KE(CN_, Utils::Now(), reason, author, created, CId_); poco_warning( Logger_, - fmt::format("TLS-CONNECTION({}): Session={} Device {} is black listed. Disconnecting.", - CId_, State_.sessionId , CN_)); + fmt::format( + "TLS-CONNECTION({}): Session={} Device {} is black listed. Disconnecting.", + CId_, State_.sessionId, CN_)); EndConnection(); return false; } @@ -145,48 +155,69 @@ namespace OpenWifi { SerialNumber_ = CN_; SerialNumberInt_ = Utils::SerialNumberToInt(SerialNumber_); - poco_debug(Logger_, fmt::format("TLS-CONNECTION({}): Session={} CN={} Completed. (t={})", CId_, State_.sessionId , CN_, ConcurrentStartingDevices_)); + poco_debug(Logger_, + fmt::format("TLS-CONNECTION({}): Session={} CN={} Completed. (t={})", CId_, + State_.sessionId, CN_, ConcurrentStartingDevices_)); DeviceValidated_ = true; return true; } catch (const Poco::Net::CertificateValidationException &E) { - poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::CertificateValidationException Certificate Validation failed during connection. Device will have to retry.", - CId_, State_.sessionId )); + poco_error( + Logger_, + fmt::format( + "CONNECTION({}): Session:{} Poco::CertificateValidationException Certificate " + "Validation failed during connection. Device will have to retry.", + CId_, State_.sessionId)); Logger_.log(E); } catch (const Poco::Net::WebSocketException &E) { - poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::WebSocketException WebSocket error during connection. Device will have to retry.", - CId_, State_.sessionId )); + poco_error(Logger_, + fmt::format("CONNECTION({}): Session:{} Poco::WebSocketException WebSocket " + "error during connection. Device will have to retry.", + CId_, State_.sessionId)); Logger_.log(E); } catch (const Poco::Net::ConnectionAbortedException &E) { - poco_error(Logger_,fmt::format("CONNECTION({}):Session:{} Poco::ConnectionAbortedException Connection was aborted during connection. Device will have to retry.", - CId_, State_.sessionId )); + poco_error( + Logger_, + fmt::format("CONNECTION({}):Session:{} Poco::ConnectionAbortedException " + "Connection was aborted during connection. Device will have to retry.", + CId_, State_.sessionId)); Logger_.log(E); } catch (const Poco::Net::ConnectionResetException &E) { - poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::ConnectionResetException Connection was reset during connection. Device will have to retry.", - CId_, State_.sessionId )); + poco_error( + Logger_, + fmt::format("CONNECTION({}): Session:{} Poco::ConnectionResetException Connection " + "was reset during connection. Device will have to retry.", + CId_, State_.sessionId)); Logger_.log(E); } catch (const Poco::Net::InvalidCertificateException &E) { - poco_error(Logger_,fmt::format( - "CONNECTION({}): Session:{} Poco::InvalidCertificateException Invalid certificate. Device will have to retry.", - CId_, State_.sessionId )); + poco_error(Logger_, + fmt::format("CONNECTION({}): Session:{} Poco::InvalidCertificateException " + "Invalid certificate. Device will have to retry.", + CId_, State_.sessionId)); Logger_.log(E); } catch (const Poco::Net::SSLException &E) { - poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::SSLException SSL Exception during connection. Device will have to retry.", - CId_, State_.sessionId )); + poco_error(Logger_, + fmt::format("CONNECTION({}): Session:{} Poco::SSLException SSL Exception " + "during connection. Device will have to retry.", + CId_, State_.sessionId)); Logger_.log(E); } catch (const Poco::Exception &E) { - poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::Exception caught during device connection. Device will have to retry.", - CId_, State_.sessionId )); + poco_error(Logger_, fmt::format("CONNECTION({}): Session:{} Poco::Exception caught " + "during device connection. Device will have to retry.", + CId_, State_.sessionId)); Logger_.log(E); } catch (...) { - poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Exception caught during device connection. Device will have to retry. Unsecure connect denied.", - CId_, State_.sessionId )); + poco_error( + Logger_, + fmt::format("CONNECTION({}): Session:{} Exception caught during device connection. " + "Device will have to retry. Unsecure connect denied.", + CId_, State_.sessionId)); } EndConnection(); return false; } - static void NotifyKafkaDisconnect(const std::string & SerialNumber) { + static void NotifyKafkaDisconnect(const std::string &SerialNumber) { try { Poco::JSON::Object Disconnect; Poco::JSON::Object Details; @@ -202,13 +233,13 @@ namespace OpenWifi { } AP_WS_Connection::~AP_WS_Connection() { - Valid_=false; + Valid_ = false; EndConnection(); } void AP_WS_Connection::EndConnection() { - Valid_=false; - if(!Dead_.test_and_set()) { + Valid_ = false; + if (!Dead_.test_and_set()) { if (Registered_) { Registered_ = false; @@ -232,14 +263,14 @@ namespace OpenWifi { auto SessionDeleted = AP_WS_Server()->EndSession(State_.sessionId, SerialNumberInt_); if (SessionDeleted) { - GWWebSocketNotifications::SingleDevice_t N; + GWWebSocketNotifications::SingleDevice_t N; N.content.serialNumber = SerialNumber_; GWWebSocketNotifications::DeviceDisconnected(N); } } } - bool AP_WS_Connection::LookForUpgrade(const uint64_t UUID, uint64_t & UpgradedUUID) { + bool AP_WS_Connection::LookForUpgrade(const uint64_t UUID, uint64_t &UpgradedUUID) { // A UUID of zero means ignore updates for that connection. if (UUID == 0) @@ -254,18 +285,19 @@ namespace OpenWifi { GWObjects::Device D; if (StorageService()->GetDevice(SerialNumber_, D)) { - // This is the case where the cache is empty after a restart. So GoodConfig will 0. If the device already has the right UUID, we just return. + // This is the case where the cache is empty after a restart. So GoodConfig will 0. If + //the device already has the right UUID, we just return. if (D.UUID == UUID) { UpgradedUUID = UUID; ConfigurationCache().Add(SerialNumberInt_, UUID); return false; } - if(UUID>D.UUID) { - // so we have a problem, the device has a newer config than we have. So we need to make sure our config - // is newer. - Config::Config Cfg(D.Configuration); - D.UUID = UUID+2; + if (UUID > D.UUID) { + // so we have a problem, the device has a newer config than we have. So we need to + //make sure our config is newer. + Config::Config Cfg(D.Configuration); + D.UUID = UUID + 2; UpgradedUUID = D.UUID; Cfg.SetUUID(D.UUID); D.Configuration = Cfg.get(); @@ -291,14 +323,18 @@ namespace OpenWifi { std::ostringstream O; Poco::JSON::Stringifier::stringify(Params, O); Cmd.Details = O.str(); - poco_information(Logger_,fmt::format("CFG-UPGRADE({}): Current ID: {}, newer configuration {}.", - CId_, UUID, D.UUID)); + poco_information(Logger_, + fmt::format("CFG-UPGRADE({}): Current ID: {}, newer configuration {}.", + CId_, UUID, D.UUID)); bool Sent; - StorageService()->AddCommand(SerialNumber_, Cmd, Storage::CommandExecutionType::COMMAND_EXECUTED); - CommandManager()->PostCommand(CommandManager()->Next_RPC_ID(), APCommands::to_apcommand(Cmd.Command.c_str()),SerialNumber_, Cmd.Command, Params, Cmd.UUID, Sent, false, false); + StorageService()->AddCommand(SerialNumber_, Cmd, + Storage::CommandExecutionType::COMMAND_EXECUTED); + CommandManager()->PostCommand( + CommandManager()->Next_RPC_ID(), APCommands::to_apcommand(Cmd.Command.c_str()), + SerialNumber_, Cmd.Command, Params, Cmd.UUID, Sent, false, false); - GWWebSocketNotifications::SingleDeviceConfigurationChange_t Notification; + GWWebSocketNotifications::SingleDeviceConfigurationChange_t Notification; Notification.content.serialNumber = D.SerialNumber; Notification.content.oldUUID = UUID; Notification.content.newUUID = UpgradedUUID; @@ -310,7 +346,8 @@ namespace OpenWifi { } void AP_WS_Connection::ProcessJSONRPCResult(Poco::JSON::Object::Ptr Doc) { - poco_debug(Logger_,fmt::format("RECEIVED-RPC({}): {}.", CId_, Doc->get(uCentralProtocol::ID).toString())); + poco_debug(Logger_, fmt::format("RECEIVED-RPC({}): {}.", CId_, + Doc->get(uCentralProtocol::ID).toString())); CommandManager()->PostCommandResult(SerialNumber_, Doc); } @@ -318,13 +355,15 @@ namespace OpenWifi { auto Method = Doc->get(uCentralProtocol::METHOD).toString(); auto EventType = uCentralProtocol::Events::EventFromString(Method); if (EventType == uCentralProtocol::Events::ET_UNKNOWN) { - poco_warning(Logger_,fmt::format("ILLEGAL-PROTOCOL({}): Unknown message type '{}'", CId_, Method)); + poco_warning(Logger_, fmt::format("ILLEGAL-PROTOCOL({}): Unknown message type '{}'", + CId_, Method)); Errors_++; return; } if (!Doc->isObject(uCentralProtocol::PARAMS)) { - poco_warning(Logger_,fmt::format("MISSING-PARAMS({}): params must be an object.", CId_)); + poco_warning(Logger_, + fmt::format("MISSING-PARAMS({}): params must be an object.", CId_)); Errors_++; return; } @@ -335,36 +374,44 @@ namespace OpenWifi { std::string UncompressedData; try { auto CompressedData = ParamsObj->get(uCentralProtocol::COMPRESS_64).toString(); - uint64_t compress_sz = 0 ; - if(ParamsObj->has("compress_sz")) { + uint64_t compress_sz = 0; + if (ParamsObj->has("compress_sz")) { compress_sz = ParamsObj->get("compress_sz"); } - if (Utils::ExtractBase64CompressedData(CompressedData, UncompressedData, compress_sz)) { - poco_trace(Logger_,fmt::format("EVENT({}): Found compressed payload expanded to '{}'.", - CId_, UncompressedData)); + if (Utils::ExtractBase64CompressedData(CompressedData, UncompressedData, + compress_sz)) { + poco_trace(Logger_, + fmt::format("EVENT({}): Found compressed payload expanded to '{}'.", + CId_, UncompressedData)); Poco::JSON::Parser Parser; ParamsObj = Parser.parse(UncompressedData).extract(); } else { - poco_warning(Logger_,fmt::format("INVALID-COMPRESSED-DATA({}): Compressed cannot be uncompressed - content must be corrupt..: size={}", - CId_, CompressedData.size())); + poco_warning(Logger_, + fmt::format("INVALID-COMPRESSED-DATA({}): Compressed cannot be " + "uncompressed - content must be corrupt..: size={}", + CId_, CompressedData.size())); Errors_++; return; } } catch (const Poco::Exception &E) { - poco_warning(Logger_,fmt::format("INVALID-COMPRESSED-JSON-DATA({}): Compressed cannot be parsed - JSON must be corrupt..", - CId_)); + poco_warning(Logger_, fmt::format("INVALID-COMPRESSED-JSON-DATA({}): Compressed " + "cannot be parsed - JSON must be corrupt..", + CId_)); Logger_.log(E); return; } } if (!ParamsObj->has(uCentralProtocol::SERIAL)) { - poco_warning(Logger_,fmt::format("MISSING-PARAMS({}): Serial number is missing in message.", CId_)); + poco_warning( + Logger_, + fmt::format("MISSING-PARAMS({}): Serial number is missing in message.", CId_)); return; } - auto Serial = Poco::trim(Poco::toLower(ParamsObj->get(uCentralProtocol::SERIAL).toString())); + auto Serial = + Poco::trim(Poco::toLower(ParamsObj->get(uCentralProtocol::SERIAL).toString())); if (!Utils::ValidSerialNumber(Serial)) { Poco::Exception E( fmt::format( @@ -377,81 +424,83 @@ namespace OpenWifi { std::string reason, author; std::uint64_t created; if (StorageService()->IsBlackListed(Serial, reason, author, created)) { - DeviceBlacklistedKafkaEvent KE(CN_,Utils::Now(),reason,author,created,CId_); + DeviceBlacklistedKafkaEvent KE(CN_, Utils::Now(), reason, author, created, CId_); Poco::Exception E( fmt::format("BLACKLIST({}): device is blacklisted and not allowed to connect.", - Serial), + Serial), EACCES); E.rethrow(); } switch (EventType) { - case uCentralProtocol::Events::ET_CONNECT: { - Process_connect(ParamsObj, Serial); - } break; + case uCentralProtocol::Events::ET_CONNECT: { + Process_connect(ParamsObj, Serial); + } break; - case uCentralProtocol::Events::ET_STATE: { - Process_state(ParamsObj); - } break; + case uCentralProtocol::Events::ET_STATE: { + Process_state(ParamsObj); + } break; - case uCentralProtocol::Events::ET_HEALTHCHECK: { - Process_healthcheck(ParamsObj); - } break; + case uCentralProtocol::Events::ET_HEALTHCHECK: { + Process_healthcheck(ParamsObj); + } break; - case uCentralProtocol::Events::ET_LOG: { - Process_log(ParamsObj); - } break; + case uCentralProtocol::Events::ET_LOG: { + Process_log(ParamsObj); + } break; - case uCentralProtocol::Events::ET_CRASHLOG: { - Process_crashlog(ParamsObj); - } break; + case uCentralProtocol::Events::ET_CRASHLOG: { + Process_crashlog(ParamsObj); + } break; - case uCentralProtocol::Events::ET_PING: { - Process_ping(ParamsObj); - } break; + case uCentralProtocol::Events::ET_PING: { + Process_ping(ParamsObj); + } break; - case uCentralProtocol::Events::ET_CFGPENDING: { - Process_cfgpending(ParamsObj); - } break; + case uCentralProtocol::Events::ET_CFGPENDING: { + Process_cfgpending(ParamsObj); + } break; - case uCentralProtocol::Events::ET_RECOVERY: { - Process_recovery(ParamsObj); - } break; + case uCentralProtocol::Events::ET_RECOVERY: { + Process_recovery(ParamsObj); + } break; - case uCentralProtocol::Events::ET_DEVICEUPDATE: { - Process_deviceupdate(ParamsObj, Serial); - } break; + case uCentralProtocol::Events::ET_DEVICEUPDATE: { + Process_deviceupdate(ParamsObj, Serial); + } break; - case uCentralProtocol::Events::ET_TELEMETRY: { - Process_telemetry(ParamsObj); - } break; + case uCentralProtocol::Events::ET_TELEMETRY: { + Process_telemetry(ParamsObj); + } break; - case uCentralProtocol::Events::ET_VENUEBROADCAST: { - Process_venuebroadcast(ParamsObj); - } break; + case uCentralProtocol::Events::ET_VENUEBROADCAST: { + Process_venuebroadcast(ParamsObj); + } break; - case uCentralProtocol::Events::ET_EVENT: { - Process_event(ParamsObj); - } break; + case uCentralProtocol::Events::ET_EVENT: { + Process_event(ParamsObj); + } break; - case uCentralProtocol::Events::ET_ALARM: { - Process_alarm(ParamsObj); - } break; + case uCentralProtocol::Events::ET_ALARM: { + Process_alarm(ParamsObj); + } break; - case uCentralProtocol::Events::ET_WIFISCAN: { - Process_wifiscan(ParamsObj); - } break; + case uCentralProtocol::Events::ET_WIFISCAN: { + Process_wifiscan(ParamsObj); + } break; - // this will never be called but some compilers will complain if we do not have a case for - // every single values of an enum - case uCentralProtocol::Events::ET_UNKNOWN: { - poco_warning(Logger_, fmt::format("ILLEGAL-EVENT({}): Event '{}' unknown. CN={}", CId_, Method, CN_)); - Errors_++; - } + // this will never be called but some compilers will complain if we do not have a case for + // every single values of an enum + case uCentralProtocol::Events::ET_UNKNOWN: { + poco_warning(Logger_, fmt::format("ILLEGAL-EVENT({}): Event '{}' unknown. CN={}", CId_, + Method, CN_)); + Errors_++; + } } } - bool AP_WS_Connection::StartTelemetry(uint64_t RPCID, const std::vector & TelemetryTypes) { + bool AP_WS_Connection::StartTelemetry(uint64_t RPCID, + const std::vector &TelemetryTypes) { poco_information(Logger_, fmt::format("TELEMETRY({}): Starting.", CId_)); Poco::JSON::Object StartMessage; StartMessage.set("jsonrpc", "2.0"); @@ -460,12 +509,12 @@ namespace OpenWifi { Params.set("serial", SerialNumber_); Params.set("interval", (uint64_t)TelemetryInterval_); Poco::JSON::Array Types; - if(TelemetryTypes.empty()) { + if (TelemetryTypes.empty()) { Types.add("wifi-frames"); Types.add("dhcp-snooping"); Types.add("state"); } else { - for(const auto &type:TelemetryTypes) + for (const auto &type : TelemetryTypes) Types.add(type); } Params.set(RESTAPI::Protocol::TYPES, Types); @@ -500,13 +549,18 @@ namespace OpenWifi { State_.webSocketClients = TelemetryWebSocketRefCount_; } - bool AP_WS_Connection::SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t Interval, - uint64_t LifeTime, const std::vector & TelemetryTypes) { + bool AP_WS_Connection::SetWebSocketTelemetryReporting( + uint64_t RPCID, uint64_t Interval, uint64_t LifeTime, + const std::vector &TelemetryTypes) { std::unique_lock Lock(TelemetryMutex_); TelemetryWebSocketRefCount_++; - TelemetryInterval_ = TelemetryInterval_ ? ( Interval< TelemetryInterval_ ? Interval : TelemetryInterval_) : Interval; + TelemetryInterval_ = TelemetryInterval_ + ? (Interval < TelemetryInterval_ ? Interval : TelemetryInterval_) + : Interval; auto TelemetryWebSocketTimer = LifeTime + Utils::Now(); - TelemetryWebSocketTimer_ = TelemetryWebSocketTimer > TelemetryWebSocketTimer_ ? TelemetryWebSocketTimer : TelemetryWebSocketTimer_; + TelemetryWebSocketTimer_ = TelemetryWebSocketTimer > TelemetryWebSocketTimer_ + ? TelemetryWebSocketTimer + : TelemetryWebSocketTimer_; UpdateCounts(); if (!TelemetryReporting_) { TelemetryReporting_ = true; @@ -515,12 +569,18 @@ namespace OpenWifi { return true; } - bool AP_WS_Connection::SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t Interval, uint64_t LifeTime, const std::vector & TelemetryTypes) { + bool + AP_WS_Connection::SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t Interval, + uint64_t LifeTime, + const std::vector &TelemetryTypes) { std::unique_lock Lock(TelemetryMutex_); TelemetryKafkaRefCount_++; - TelemetryInterval_ = TelemetryInterval_ ? ( Interval TelemetryKafkaTimer_ ? TelemetryKafkaTimer : TelemetryKafkaTimer_; + TelemetryKafkaTimer_ = + TelemetryKafkaTimer > TelemetryKafkaTimer_ ? TelemetryKafkaTimer : TelemetryKafkaTimer_; UpdateCounts(); if (!TelemetryReporting_) { TelemetryReporting_ = true; @@ -553,25 +613,28 @@ namespace OpenWifi { return true; } - void AP_WS_Connection::OnSocketShutdown([[maybe_unused]] const Poco::AutoPtr &pNf) { + void AP_WS_Connection::OnSocketShutdown( + [[maybe_unused]] const Poco::AutoPtr &pNf) { poco_trace(Logger_, fmt::format("SOCKET-SHUTDOWN({}): Closing.", CId_)); return EndConnection(); } - void AP_WS_Connection::OnSocketError([[maybe_unused]] const Poco::AutoPtr &pNf) { + void AP_WS_Connection::OnSocketError( + [[maybe_unused]] const Poco::AutoPtr &pNf) { poco_trace(Logger_, fmt::format("SOCKET-ERROR({}): Closing.", CId_)); return EndConnection(); } - void AP_WS_Connection::OnSocketReadable([[maybe_unused]] const Poco::AutoPtr &pNf) { + void AP_WS_Connection::OnSocketReadable( + [[maybe_unused]] const Poco::AutoPtr &pNf) { - if(!Valid_) + if (!Valid_) return; - if(!AP_WS_Server()->Running()) + if (!AP_WS_Server()->Running()) return EndConnection(); - if(!ValidatedDevice()) + if (!ValidatedDevice()) return; try { @@ -581,10 +644,13 @@ namespace OpenWifi { return EndConnection(); } catch (const std::exception &E) { std::string W = E.what(); - poco_information(Logger_, fmt::format("std::exception caught: {}. Connection terminated with {}", W, CId_)); + poco_information( + Logger_, + fmt::format("std::exception caught: {}. Connection terminated with {}", W, CId_)); return EndConnection(); } catch (...) { - poco_information(Logger_, fmt::format("Unknown exception for {}. Connection terminated.", CId_)); + poco_information(Logger_, + fmt::format("Unknown exception for {}. Connection terminated.", CId_)); return EndConnection(); } } @@ -598,7 +664,9 @@ namespace OpenWifi { Op = flags & Poco::Net::WebSocket::FRAME_OP_BITMASK; if (IncomingSize == 0 && flags == 0 && Op == 0) { - poco_information(Logger_, fmt::format("DISCONNECT({}): device has disconnected. Session={}", CId_, State_.sessionId)); + poco_information(Logger_, + fmt::format("DISCONNECT({}): device has disconnected. Session={}", + CId_, State_.sessionId)); return EndConnection(); } @@ -609,145 +677,154 @@ namespace OpenWifi { State_.LastContact = Utils::Now(); switch (Op) { - case Poco::Net::WebSocket::FRAME_OP_PING: { - poco_trace(Logger_, fmt::format("WS-PING({}): received. PONG sent back.", CId_)); - WS_->sendFrame("", 0, - (int)Poco::Net::WebSocket::FRAME_OP_PONG | - (int)Poco::Net::WebSocket::FRAME_FLAG_FIN); + case Poco::Net::WebSocket::FRAME_OP_PING: { + poco_trace(Logger_, fmt::format("WS-PING({}): received. PONG sent back.", CId_)); + WS_->sendFrame("", 0, + (int)Poco::Net::WebSocket::FRAME_OP_PONG | + (int)Poco::Net::WebSocket::FRAME_FLAG_FIN); - if (KafkaManager()->Enabled()) { - Poco::JSON::Object PingObject; - Poco::JSON::Object PingDetails; - PingDetails.set(uCentralProtocol::FIRMWARE, State_.Firmware); - PingDetails.set(uCentralProtocol::SERIALNUMBER, SerialNumber_); - PingDetails.set(uCentralProtocol::COMPATIBLE, Compatible_); - PingDetails.set(uCentralProtocol::CONNECTIONIP, CId_); - PingDetails.set(uCentralProtocol::TIMESTAMP, Utils::Now()); - PingDetails.set("locale", State_.locale ); - PingObject.set(uCentralProtocol::PING, PingDetails); - Poco::JSON::Stringifier Stringify; - std::ostringstream OS; - Stringify.condense(PingObject, OS); - KafkaManager()->PostMessage(KafkaTopics::CONNECTION, SerialNumber_, OS.str()); - } - return; - } break; + if (KafkaManager()->Enabled()) { + Poco::JSON::Object PingObject; + Poco::JSON::Object PingDetails; + PingDetails.set(uCentralProtocol::FIRMWARE, State_.Firmware); + PingDetails.set(uCentralProtocol::SERIALNUMBER, SerialNumber_); + PingDetails.set(uCentralProtocol::COMPATIBLE, Compatible_); + PingDetails.set(uCentralProtocol::CONNECTIONIP, CId_); + PingDetails.set(uCentralProtocol::TIMESTAMP, Utils::Now()); + PingDetails.set("locale", State_.locale); + PingObject.set(uCentralProtocol::PING, PingDetails); + Poco::JSON::Stringifier Stringify; + std::ostringstream OS; + Stringify.condense(PingObject, OS); + KafkaManager()->PostMessage(KafkaTopics::CONNECTION, SerialNumber_, OS.str()); + } + return; + } break; - case Poco::Net::WebSocket::FRAME_OP_PONG: { - poco_trace(Logger_, fmt::format("PONG({}): received and ignored.", CId_)); - return; - } break; + case Poco::Net::WebSocket::FRAME_OP_PONG: { + poco_trace(Logger_, fmt::format("PONG({}): received and ignored.", CId_)); + return; + } break; - case Poco::Net::WebSocket::FRAME_OP_TEXT: { - poco_trace(Logger_, fmt::format("FRAME({}): Frame received (length={}, flags={}). Msg={}", CId_, - IncomingSize, flags, IncomingFrame.begin())); + case Poco::Net::WebSocket::FRAME_OP_TEXT: { + poco_trace(Logger_, + fmt::format("FRAME({}): Frame received (length={}, flags={}). Msg={}", + CId_, IncomingSize, flags, IncomingFrame.begin())); - Poco::JSON::Parser parser; - auto ParsedMessage = parser.parse(IncomingFrame.begin()); - auto IncomingJSON = ParsedMessage.extract(); + Poco::JSON::Parser parser; + auto ParsedMessage = parser.parse(IncomingFrame.begin()); + auto IncomingJSON = ParsedMessage.extract(); - if (IncomingJSON->has(uCentralProtocol::JSONRPC)) { - if (IncomingJSON->has(uCentralProtocol::METHOD) && - IncomingJSON->has(uCentralProtocol::PARAMS)) { - ProcessJSONRPCEvent(IncomingJSON); - } else if (IncomingJSON->has(uCentralProtocol::RESULT) && - IncomingJSON->has(uCentralProtocol::ID)) { - poco_trace(Logger_, fmt::format("RPC-RESULT({}): payload: {}", CId_, IncomingFrame.begin())); - ProcessJSONRPCResult(IncomingJSON); - } else { - poco_warning(Logger_, - fmt::format("INVALID-PAYLOAD({}): Payload is not JSON-RPC 2.0: {}", - CId_, IncomingFrame.begin())); - } - } else if (IncomingJSON->has(uCentralProtocol::RADIUS)) { - ProcessIncomingRadiusData(IncomingJSON); + if (IncomingJSON->has(uCentralProtocol::JSONRPC)) { + if (IncomingJSON->has(uCentralProtocol::METHOD) && + IncomingJSON->has(uCentralProtocol::PARAMS)) { + ProcessJSONRPCEvent(IncomingJSON); + } else if (IncomingJSON->has(uCentralProtocol::RESULT) && + IncomingJSON->has(uCentralProtocol::ID)) { + poco_trace(Logger_, fmt::format("RPC-RESULT({}): payload: {}", CId_, + IncomingFrame.begin())); + ProcessJSONRPCResult(IncomingJSON); } else { - std::ostringstream iS; - IncomingJSON->stringify(iS); - std::cout << iS.str() << std::endl; - poco_warning(Logger_, fmt::format( - "FRAME({}): illegal transaction header, missing 'jsonrpc'", CId_)); - Errors_++; + poco_warning( + Logger_, + fmt::format("INVALID-PAYLOAD({}): Payload is not JSON-RPC 2.0: {}", + CId_, IncomingFrame.begin())); } - return; - } break; + } else if (IncomingJSON->has(uCentralProtocol::RADIUS)) { + ProcessIncomingRadiusData(IncomingJSON); + } else { + std::ostringstream iS; + IncomingJSON->stringify(iS); + std::cout << iS.str() << std::endl; + poco_warning( + Logger_, + fmt::format("FRAME({}): illegal transaction header, missing 'jsonrpc'", + CId_)); + Errors_++; + } + return; + } break; - case Poco::Net::WebSocket::FRAME_OP_CLOSE: { - poco_information(Logger_, - fmt::format("CLOSE({}): Device is closing its connection.", CId_)); - return EndConnection(); - } break; + case Poco::Net::WebSocket::FRAME_OP_CLOSE: { + poco_information(Logger_, + fmt::format("CLOSE({}): Device is closing its connection.", CId_)); + return EndConnection(); + } break; - default: { - poco_warning(Logger_, fmt::format("UNKNOWN({}): unknown WS Frame operation: {}", CId_, - std::to_string(Op))); - } break; + default: { + poco_warning(Logger_, fmt::format("UNKNOWN({}): unknown WS Frame operation: {}", + CId_, std::to_string(Op))); + } break; } } catch (const Poco::Net::ConnectionResetException &E) { - poco_warning(Logger_, fmt::format("ConnectionResetException({}): Text:{} Payload:{} Session:{}", - CId_, - E.displayText(), - IncomingFrame.begin()==nullptr ? "" : IncomingFrame.begin(), - State_.sessionId)); + poco_warning(Logger_, + fmt::format("ConnectionResetException({}): Text:{} Payload:{} Session:{}", + CId_, E.displayText(), + IncomingFrame.begin() == nullptr ? "" : IncomingFrame.begin(), + State_.sessionId)); return EndConnection(); } catch (const Poco::JSON::JSONException &E) { - poco_warning(Logger_, fmt::format("JSONException({}): Text:{} Payload:{} Session:{}", - CId_, - E.displayText(), - IncomingFrame.begin()==nullptr ? "" : IncomingFrame.begin(), - State_.sessionId)); + poco_warning(Logger_, + fmt::format("JSONException({}): Text:{} Payload:{} Session:{}", CId_, + E.displayText(), + IncomingFrame.begin() == nullptr ? "" : IncomingFrame.begin(), + State_.sessionId)); return EndConnection(); } catch (const Poco::Net::WebSocketException &E) { - poco_warning(Logger_, fmt::format("WebSocketException({}): Text:{} Payload:{} Session:{}", - CId_, - E.displayText(), - IncomingFrame.begin()==nullptr ? "" : IncomingFrame.begin(), - State_.sessionId)); + poco_warning(Logger_, + fmt::format("WebSocketException({}): Text:{} Payload:{} Session:{}", CId_, + E.displayText(), + IncomingFrame.begin() == nullptr ? "" : IncomingFrame.begin(), + State_.sessionId)); return EndConnection(); } catch (const Poco::Net::SSLConnectionUnexpectedlyClosedException &E) { - poco_warning(Logger_, fmt::format("SSLConnectionUnexpectedlyClosedException({}): Text:{} Payload:{} Session:{}", - CId_, - E.displayText(), - IncomingFrame.begin()==nullptr ? "" : IncomingFrame.begin(), - State_.sessionId)); + poco_warning( + Logger_, + fmt::format( + "SSLConnectionUnexpectedlyClosedException({}): Text:{} Payload:{} Session:{}", + CId_, E.displayText(), + IncomingFrame.begin() == nullptr ? "" : IncomingFrame.begin(), + State_.sessionId)); return EndConnection(); } catch (const Poco::Net::SSLException &E) { - poco_warning(Logger_, fmt::format("SSLException({}): Text:{} Payload:{} Session:{}", - CId_, - E.displayText(), - IncomingFrame.begin()==nullptr ? "" : IncomingFrame.begin(), - State_.sessionId)); + poco_warning(Logger_, + fmt::format("SSLException({}): Text:{} Payload:{} Session:{}", CId_, + E.displayText(), + IncomingFrame.begin() == nullptr ? "" : IncomingFrame.begin(), + State_.sessionId)); return EndConnection(); } catch (const Poco::Net::NetException &E) { - poco_warning(Logger_, fmt::format("NetException({}): Text:{} Payload:{} Session:{}", - CId_, - E.displayText(), - IncomingFrame.begin()==nullptr ? "" : IncomingFrame.begin(), - State_.sessionId)); + poco_warning(Logger_, + fmt::format("NetException({}): Text:{} Payload:{} Session:{}", CId_, + E.displayText(), + IncomingFrame.begin() == nullptr ? "" : IncomingFrame.begin(), + State_.sessionId)); return EndConnection(); } catch (const Poco::IOException &E) { - poco_warning(Logger_, fmt::format("IOException({}): Text:{} Payload:{} Session:{}", - CId_, - E.displayText(), - IncomingFrame.begin()==nullptr ? "" : IncomingFrame.begin(), - State_.sessionId)); + poco_warning(Logger_, + fmt::format("IOException({}): Text:{} Payload:{} Session:{}", CId_, + E.displayText(), + IncomingFrame.begin() == nullptr ? "" : IncomingFrame.begin(), + State_.sessionId)); return EndConnection(); } catch (const Poco::Exception &E) { - poco_warning(Logger_, fmt::format("Exception({}): Text:{} Payload:{} Session:{}", - CId_, - E.displayText(), - IncomingFrame.begin()==nullptr ? "" : IncomingFrame.begin(), - State_.sessionId)); + poco_warning(Logger_, + fmt::format("Exception({}): Text:{} Payload:{} Session:{}", CId_, + E.displayText(), + IncomingFrame.begin() == nullptr ? "" : IncomingFrame.begin(), + State_.sessionId)); return EndConnection(); } catch (const std::exception &E) { - poco_warning(Logger_, fmt::format("std::exception({}): Text:{} Payload:{} Session:{}", - CId_, - E.what(), - IncomingFrame.begin()==nullptr ? "" : IncomingFrame.begin(), - State_.sessionId)); + poco_warning(Logger_, + fmt::format("std::exception({}): Text:{} Payload:{} Session:{}", CId_, + E.what(), + IncomingFrame.begin() == nullptr ? "" : IncomingFrame.begin(), + State_.sessionId)); return EndConnection(); } catch (...) { - poco_error(Logger_,fmt::format("UnknownException({}): Device must be disconnected. Unknown exception. Session:{}", CId_, State_.sessionId)); + poco_error(Logger_, fmt::format("UnknownException({}): Device must be disconnected. " + "Unknown exception. Session:{}", + CId_, State_.sessionId)); return EndConnection(); } @@ -763,45 +840,47 @@ namespace OpenWifi { size_t BytesSent = WS_->sendFrame(Payload.c_str(), (int)Payload.size()); /* - * There is a possibility to actually try and send data but the device is no longer listening. - * This code attempts to wait 5 seconds to see if the device is actually still listening. - * if the data is not acked under 5 seconds, then we consider that the data never made it or the device is disconnected somehow. + * There is a possibility to actually try and send data but the device is no longer + * listening. This code attempts to wait 5 seconds to see if the device is actually + * still listening. if the data is not acked under 5 seconds, then we consider that the + * data never made it or the device is disconnected somehow. */ #if defined(__APPLE__) tcp_connection_info info; - int timeout=4000; + int timeout = 4000; auto expireAt = std::chrono::system_clock::now() + std::chrono::milliseconds(timeout); do { std::this_thread::sleep_for(std::chrono::milliseconds(50)); socklen_t opt_len = sizeof(info); - getsockopt(WS_->impl()->sockfd(),SOL_SOCKET,TCP_CONNECTION_INFO,(void *)&info,&opt_len); + getsockopt(WS_->impl()->sockfd(), SOL_SOCKET, TCP_CONNECTION_INFO, (void *)&info, + &opt_len); } while (!info.tcpi_tfo_syn_data_acked && expireAt > std::chrono::system_clock::now()); - if(!info.tcpi_tfo_syn_data_acked) + if (!info.tcpi_tfo_syn_data_acked) return false; #else tcp_info info; - int timeout=4000; + int timeout = 4000; auto expireAt = std::chrono::system_clock::now() + std::chrono::milliseconds(timeout); do { std::this_thread::sleep_for(std::chrono::milliseconds(20)); socklen_t opt_len = sizeof(info); - getsockopt(WS_->impl()->sockfd(),SOL_TCP, TCP_INFO, (void *) &info, &opt_len); + getsockopt(WS_->impl()->sockfd(), SOL_TCP, TCP_INFO, (void *)&info, &opt_len); } while (info.tcpi_unacked > 0 && expireAt > std::chrono::system_clock::now()); - if(info.tcpi_unacked>0) { + if (info.tcpi_unacked > 0) { return false; } #endif State_.TX += BytesSent; return BytesSent == Payload.size(); - } catch(const Poco::Exception &E) { + } catch (const Poco::Exception &E) { Logger_.log(E); } return false; } std::string Base64Encode(const unsigned char *buffer, std::size_t size) { - return Utils::base64encode(buffer,size); + return Utils::base64encode(buffer, size); } std::string Base64Decode(const std::string &F) { @@ -812,30 +891,31 @@ namespace OpenWifi { return ofs.str(); } - bool AP_WS_Connection::SendRadiusAuthenticationData(const unsigned char * buffer, std::size_t size) { - Poco::JSON::Object Answer; - Answer.set(uCentralProtocol::RADIUS,uCentralProtocol::RADIUSAUTH); - Answer.set(uCentralProtocol::RADIUSDATA, Base64Encode(buffer,size)); + bool AP_WS_Connection::SendRadiusAuthenticationData(const unsigned char *buffer, + std::size_t size) { + Poco::JSON::Object Answer; + Answer.set(uCentralProtocol::RADIUS, uCentralProtocol::RADIUSAUTH); + Answer.set(uCentralProtocol::RADIUSDATA, Base64Encode(buffer, size)); std::ostringstream Payload; Answer.stringify(Payload); return Send(Payload.str()); } - bool AP_WS_Connection::SendRadiusAccountingData(const unsigned char * buffer, std::size_t size) { - Poco::JSON::Object Answer; - Answer.set(uCentralProtocol::RADIUS,uCentralProtocol::RADIUSACCT); - Answer.set(uCentralProtocol::RADIUSDATA, Base64Encode(buffer,size)); + bool AP_WS_Connection::SendRadiusAccountingData(const unsigned char *buffer, std::size_t size) { + Poco::JSON::Object Answer; + Answer.set(uCentralProtocol::RADIUS, uCentralProtocol::RADIUSACCT); + Answer.set(uCentralProtocol::RADIUSDATA, Base64Encode(buffer, size)); std::ostringstream Payload; Answer.stringify(Payload); return Send(Payload.str()); } - bool AP_WS_Connection::SendRadiusCoAData(const unsigned char * buffer, std::size_t size) { - Poco::JSON::Object Answer; - Answer.set(uCentralProtocol::RADIUS,uCentralProtocol::RADIUSCOA); - Answer.set(uCentralProtocol::RADIUSDATA, Base64Encode(buffer,size)); + bool AP_WS_Connection::SendRadiusCoAData(const unsigned char *buffer, std::size_t size) { + Poco::JSON::Object Answer; + Answer.set(uCentralProtocol::RADIUS, uCentralProtocol::RADIUSCOA); + Answer.set(uCentralProtocol::RADIUSDATA, Base64Encode(buffer, size)); std::ostringstream Payload; Answer.stringify(Payload); @@ -843,21 +923,24 @@ namespace OpenWifi { } void AP_WS_Connection::ProcessIncomingRadiusData(const Poco::JSON::Object::Ptr &Doc) { - if( Doc->has(uCentralProtocol::RADIUSDATA)) { + if (Doc->has(uCentralProtocol::RADIUSDATA)) { auto Type = Doc->get(uCentralProtocol::RADIUS).toString(); - if(Type==uCentralProtocol::RADIUSACCT) { + if (Type == uCentralProtocol::RADIUSACCT) { auto Data = Doc->get(uCentralProtocol::RADIUSDATA).toString(); auto DecodedData = Base64Decode(Data); - RADIUS_proxy_server()->SendAccountingData(SerialNumber_,DecodedData.c_str(),DecodedData.size()); - } else if(Type==uCentralProtocol::RADIUSAUTH) { + RADIUS_proxy_server()->SendAccountingData(SerialNumber_, DecodedData.c_str(), + DecodedData.size()); + } else if (Type == uCentralProtocol::RADIUSAUTH) { auto Data = Doc->get(uCentralProtocol::RADIUSDATA).toString(); auto DecodedData = Base64Decode(Data); - RADIUS_proxy_server()->SendAuthenticationData(SerialNumber_,DecodedData.c_str(),DecodedData.size()); - } else if(Type==uCentralProtocol::RADIUSCOA) { + RADIUS_proxy_server()->SendAuthenticationData(SerialNumber_, DecodedData.c_str(), + DecodedData.size()); + } else if (Type == uCentralProtocol::RADIUSCOA) { auto Data = Doc->get(uCentralProtocol::RADIUSDATA).toString(); auto DecodedData = Base64Decode(Data); - RADIUS_proxy_server()->SendCoAData(SerialNumber_,DecodedData.c_str(),DecodedData.size()); + RADIUS_proxy_server()->SendCoAData(SerialNumber_, DecodedData.c_str(), + DecodedData.size()); } } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Connection.h b/src/AP_WS_Connection.h index 48b592ae..f55482e9 100644 --- a/src/AP_WS_Connection.h +++ b/src/AP_WS_Connection.h @@ -4,14 +4,14 @@ #pragma once -#include #include +#include +#include "Poco/JSON/Object.h" +#include "Poco/Logger.h" +#include "Poco/Net/SocketNotification.h" #include "Poco/Net/SocketReactor.h" #include "Poco/Net/StreamSocket.h" -#include "Poco/JSON/Object.h" -#include "Poco/Net/SocketNotification.h" -#include "Poco/Logger.h" #include "Poco/Net/WebSocket.h" #include "RESTObjects/RESTAPI_GWobjects.h" @@ -20,65 +20,70 @@ namespace OpenWifi { class AP_WS_Connection { static constexpr int BufSize = 256000; + public: - explicit AP_WS_Connection( Poco::Net::HTTPServerRequest &request, - Poco::Net::HTTPServerResponse &response, - uint64_t connection_id, - Poco::Logger &L, - Poco::Net::SocketReactor &R); + explicit AP_WS_Connection(Poco::Net::HTTPServerRequest &request, + Poco::Net::HTTPServerResponse &response, uint64_t connection_id, + Poco::Logger &L, Poco::Net::SocketReactor &R); ~AP_WS_Connection(); void EndConnection(); - void ProcessJSONRPCEvent(Poco::JSON::Object::Ptr & Doc); + void ProcessJSONRPCEvent(Poco::JSON::Object::Ptr &Doc); void ProcessJSONRPCResult(Poco::JSON::Object::Ptr Doc); void ProcessIncomingFrame(); void ProcessIncomingRadiusData(const Poco::JSON::Object::Ptr &Doc); [[nodiscard]] bool Send(const std::string &Payload); - bool SendRadiusAuthenticationData(const unsigned char * buffer, std::size_t size); - bool SendRadiusAccountingData(const unsigned char * buffer, std::size_t size); - bool SendRadiusCoAData(const unsigned char * buffer, std::size_t size); + bool SendRadiusAuthenticationData(const unsigned char *buffer, std::size_t size); + bool SendRadiusAccountingData(const unsigned char *buffer, std::size_t size); + bool SendRadiusCoAData(const unsigned char *buffer, std::size_t size); - void OnSocketReadable(const Poco::AutoPtr& pNf); - void OnSocketShutdown(const Poco::AutoPtr& pNf); - void OnSocketError(const Poco::AutoPtr& pNf); - bool LookForUpgrade(uint64_t UUID, uint64_t & UpgradedUUID); - static bool ExtractBase64CompressedData(const std::string & CompressedData, std::string & UnCompressedData, uint64_t compress_sz); + void OnSocketReadable(const Poco::AutoPtr &pNf); + void OnSocketShutdown(const Poco::AutoPtr &pNf); + void OnSocketError(const Poco::AutoPtr &pNf); + bool LookForUpgrade(uint64_t UUID, uint64_t &UpgradedUUID); + static bool ExtractBase64CompressedData(const std::string &CompressedData, + std::string &UnCompressedData, + uint64_t compress_sz); void LogException(const Poco::Exception &E); - inline Poco::Logger & Logger() { return Logger_; } - bool SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t interval, uint64_t TelemetryWebSocketTimer, const std::vector & TelemetryTypes); - bool SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t interval, uint64_t TelemetryKafkaTimer, const std::vector & TelemetryTypes); + inline Poco::Logger &Logger() { return Logger_; } + bool SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t interval, + uint64_t TelemetryWebSocketTimer, + const std::vector &TelemetryTypes); + bool SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t interval, + uint64_t TelemetryKafkaTimer, + const std::vector &TelemetryTypes); bool StopWebSocketTelemetry(uint64_t RPCID); bool StopKafkaTelemetry(uint64_t RPCID); inline void GetLastStats(std::string &LastStats) const { - std::shared_lock G(ConnectionMutex_); + std::shared_lock G(ConnectionMutex_); LastStats = RawLastStats_; } inline void SetLastStats(const std::string &LastStats) { - std::unique_lock G(ConnectionMutex_); + std::unique_lock G(ConnectionMutex_); RawLastStats_ = LastStats; } inline void SetLastHealthCheck(const GWObjects::HealthCheck &H) { - std::unique_lock G(ConnectionMutex_); + std::unique_lock G(ConnectionMutex_); RawLastHealthcheck_ = H; } inline void GetLastHealthCheck(GWObjects::HealthCheck &H) { - std::shared_lock G(ConnectionMutex_); + std::shared_lock G(ConnectionMutex_); H = RawLastHealthcheck_; } inline void GetState(GWObjects::ConnectionState &State) const { - std::shared_lock G(ConnectionMutex_); + std::shared_lock G(ConnectionMutex_); State = State_; } - inline void GetRestrictions(GWObjects::DeviceRestrictions & R) const { - std::shared_lock G(ConnectionMutex_); + inline void GetRestrictions(GWObjects::DeviceRestrictions &R) const { + std::shared_lock G(ConnectionMutex_); R = Restrictions_; } @@ -99,11 +104,11 @@ namespace OpenWifi { bool ValidatedDevice(); - inline bool GetTelemetryParameters(bool & Reporting, uint64_t & Interval, - uint64_t & WebSocketTimer, uint64_t & KafkaTimer, - uint64_t &WebSocketCount, uint64_t & KafkaCount, + inline bool GetTelemetryParameters(bool &Reporting, uint64_t &Interval, + uint64_t &WebSocketTimer, uint64_t &KafkaTimer, + uint64_t &WebSocketCount, uint64_t &KafkaCount, uint64_t &WebSocketPackets, - uint64_t &KafkaPackets ) const { + uint64_t &KafkaPackets) const { Reporting = TelemetryReporting_; WebSocketTimer = TelemetryWebSocketTimer_; KafkaTimer = TelemetryKafkaTimer_; @@ -117,48 +122,49 @@ namespace OpenWifi { friend class AP_WS_Server; - inline GWObjects::DeviceRestrictions Restrictions() const { - std::shared_lock G(ConnectionMutex_); + inline GWObjects::DeviceRestrictions Restrictions() const { + std::shared_lock G(ConnectionMutex_); return Restrictions_; } private: - mutable std::shared_mutex ConnectionMutex_; - std::shared_mutex TelemetryMutex_; - Poco::Logger &Logger_; - Poco::Net::SocketReactor &Reactor_; + mutable std::shared_mutex ConnectionMutex_; + std::shared_mutex TelemetryMutex_; + Poco::Logger &Logger_; + Poco::Net::SocketReactor &Reactor_; std::unique_ptr WS_; - std::string SerialNumber_; - uint64_t SerialNumberInt_=0; - std::string Compatible_; - std::atomic_bool Registered_ = false ; - std::string CId_; - std::string CN_; - uint64_t Errors_=0; - Poco::Net::IPAddress PeerAddress_; - volatile bool TelemetryReporting_ = false; - volatile uint64_t TelemetryWebSocketRefCount_ = 0; - volatile uint64_t TelemetryKafkaRefCount_ = 0; - volatile uint64_t TelemetryWebSocketTimer_ = 0; - volatile uint64_t TelemetryKafkaTimer_ = 0 ; - volatile uint64_t TelemetryInterval_ = 0; - volatile uint64_t TelemetryWebSocketPackets_=0; - volatile uint64_t TelemetryKafkaPackets_=0; - GWObjects::ConnectionState State_; - std::string RawLastStats_; - GWObjects::HealthCheck RawLastHealthcheck_; - std::chrono::time_point ConnectionStart_ = std::chrono::high_resolution_clock::now(); + std::string SerialNumber_; + uint64_t SerialNumberInt_ = 0; + std::string Compatible_; + std::atomic_bool Registered_ = false; + std::string CId_; + std::string CN_; + uint64_t Errors_ = 0; + Poco::Net::IPAddress PeerAddress_; + volatile bool TelemetryReporting_ = false; + volatile uint64_t TelemetryWebSocketRefCount_ = 0; + volatile uint64_t TelemetryKafkaRefCount_ = 0; + volatile uint64_t TelemetryWebSocketTimer_ = 0; + volatile uint64_t TelemetryKafkaTimer_ = 0; + volatile uint64_t TelemetryInterval_ = 0; + volatile uint64_t TelemetryWebSocketPackets_ = 0; + volatile uint64_t TelemetryKafkaPackets_ = 0; + GWObjects::ConnectionState State_; + std::string RawLastStats_; + GWObjects::HealthCheck RawLastHealthcheck_; + std::chrono::time_point ConnectionStart_ = + std::chrono::high_resolution_clock::now(); std::chrono::duration ConnectionCompletionTime_{0.0}; - std::atomic_flag Dead_=false; - std::atomic_bool DeviceValidated_=false; - std::atomic_bool Valid_=false; - OpenWifi::GWObjects::DeviceRestrictions Restrictions_; + std::atomic_flag Dead_ = false; + std::atomic_bool DeviceValidated_ = false; + std::atomic_bool Valid_ = false; + OpenWifi::GWObjects::DeviceRestrictions Restrictions_; - static inline std::atomic_uint64_t ConcurrentStartingDevices_=0; + static inline std::atomic_uint64_t ConcurrentStartingDevices_ = 0; - bool StartTelemetry(uint64_t RPCID, const std::vector & TelemetryTypes); + bool StartTelemetry(uint64_t RPCID, const std::vector &TelemetryTypes); bool StopTelemetry(uint64_t RPCID); void UpdateCounts(); }; -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_alarm.cpp b/src/AP_WS_Process_alarm.cpp index e5959eae..2609bd9d 100644 --- a/src/AP_WS_Process_alarm.cpp +++ b/src/AP_WS_Process_alarm.cpp @@ -4,16 +4,16 @@ #include "AP_WS_Connection.h" #include "StorageService.h" -#include "framework/ow_constants.h" #include "fmt/format.h" #include "framework/KafkaManager.h" +#include "framework/ow_constants.h" namespace OpenWifi { void AP_WS_Connection::Process_alarm(Poco::JSON::Object::Ptr ParamsObj) { if (!State_.Connected) { - poco_warning( - Logger_, - fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", CId_, CN_)); + poco_warning(Logger_, + fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", + CId_, CN_)); Errors_++; return; } @@ -29,4 +29,4 @@ namespace OpenWifi { } } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_cfgpending.cpp b/src/AP_WS_Process_cfgpending.cpp index e7dec116..5dddaa72 100644 --- a/src/AP_WS_Process_cfgpending.cpp +++ b/src/AP_WS_Process_cfgpending.cpp @@ -9,8 +9,9 @@ namespace OpenWifi { void AP_WS_Connection::Process_cfgpending(Poco::JSON::Object::Ptr ParamsObj) { if (!State_.Connected) { - poco_warning(Logger_, fmt::format( - "INVALID-PROTOCOL({}): Device '{}' is not following protocol", CId_, CN_)); + poco_warning(Logger_, + fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", + CId_, CN_)); Errors_++; return; } @@ -18,9 +19,10 @@ namespace OpenWifi { [[maybe_unused]] uint64_t UUID = ParamsObj->get(uCentralProtocol::UUID); [[maybe_unused]] uint64_t Active = ParamsObj->get(uCentralProtocol::ACTIVE); - poco_trace(Logger_, fmt::format("CFG-PENDING({}): Active: {} Target: {}", CId_, Active, UUID)); + poco_trace(Logger_, + fmt::format("CFG-PENDING({}): Active: {} Target: {}", CId_, Active, UUID)); } else { poco_warning(Logger_, fmt::format("CFG-PENDING({}): Missing some parameters", CId_)); } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_connect.cpp b/src/AP_WS_Process_connect.cpp index 50927f72..a06d2961 100644 --- a/src/AP_WS_Process_connect.cpp +++ b/src/AP_WS_Process_connect.cpp @@ -4,10 +4,10 @@ #include "AP_WS_Connection.h" #include "AP_WS_Server.h" -#include "StorageService.h" -#include "FindCountry.h" -#include "Daemon.h" #include "CentralConfig.h" +#include "Daemon.h" +#include "FindCountry.h" +#include "StorageService.h" #include "CommandManager.h" @@ -19,13 +19,15 @@ namespace OpenWifi { - [[maybe_unused]] static void SendKafkaFirmwareUpdate(const std::string &SerialNumber, const std::string &OldFirmware, const std::string &NewFirmware) { - if(KafkaManager()->Enabled()) { + [[maybe_unused]] static void SendKafkaFirmwareUpdate(const std::string &SerialNumber, + const std::string &OldFirmware, + const std::string &NewFirmware) { + if (KafkaManager()->Enabled()) { Poco::JSON::Object EventDetails; EventDetails.set("oldFirmware", OldFirmware); - EventDetails.set("newFirmware",NewFirmware); - Poco::JSON::Object Event; - Event.set("type","device.firmware_change"); + EventDetails.set("newFirmware", NewFirmware); + Poco::JSON::Object Event; + Event.set("type", "device.firmware_change"); Event.set("timestamp", Utils::Now()); Event.set("payload", EventDetails); std::ostringstream OS; @@ -34,9 +36,9 @@ namespace OpenWifi { } } - void AP_WS_Connection::Process_connect(Poco::JSON::Object::Ptr ParamsObj, const std::string &Serial) { - if (ParamsObj->has(uCentralProtocol::UUID) && - ParamsObj->has(uCentralProtocol::FIRMWARE) && + void AP_WS_Connection::Process_connect(Poco::JSON::Object::Ptr ParamsObj, + const std::string &Serial) { + if (ParamsObj->has(uCentralProtocol::UUID) && ParamsObj->has(uCentralProtocol::FIRMWARE) && ParamsObj->has(uCentralProtocol::CAPABILITIES)) { uint64_t UUID = ParamsObj->get(uCentralProtocol::UUID); auto Firmware = ParamsObj->get(uCentralProtocol::FIRMWARE).toString(); @@ -47,10 +49,10 @@ namespace OpenWifi { CommandManager()->ClearQueue(SerialNumberInt_); - AP_WS_Server()->SetSessionDetails(State_.sessionId,SerialNumberInt_); + AP_WS_Server()->SetSessionDetails(State_.sessionId, SerialNumberInt_); - std::lock_guard Lock(ConnectionMutex_); - Config::Capabilities Caps(Capabilities); + std::lock_guard Lock(ConnectionMutex_); + Config::Capabilities Caps(Capabilities); Compatible_ = Caps.Compatible(); @@ -61,120 +63,131 @@ namespace OpenWifi { CId_ = SerialNumber_ + "@" + CId_; auto IP = PeerAddress_.toString(); - if(IP.substr(0,7)=="::ffff:") { + if (IP.substr(0, 7) == "::ffff:") { IP = IP.substr(7); } bool RestrictedDevice = false; - if(Capabilities->has("restrictions")){ - RestrictedDevice = true; + if (Capabilities->has("restrictions")) { + RestrictedDevice = true; Poco::JSON::Object::Ptr RestrictionObject = Capabilities->getObject("restrictions"); Restrictions_.from_json(RestrictionObject); } State_.locale = FindCountryFromIP()->Get(IP); - GWObjects::Device DeviceInfo; - auto DeviceExists = StorageService()->GetDevice(SerialNumber_,DeviceInfo); + GWObjects::Device DeviceInfo; + auto DeviceExists = StorageService()->GetDevice(SerialNumber_, DeviceInfo); if (Daemon()->AutoProvisioning() && !DeviceExists) { StorageService()->CreateDefaultDevice(SerialNumber_, Caps, Firmware, PeerAddress_); } else if (DeviceExists) { - StorageService()->UpdateDeviceCapabilities(SerialNumber_, Caps ); + StorageService()->UpdateDeviceCapabilities(SerialNumber_, Caps); int Updated{0}; - if(!Firmware.empty()) { - if(Firmware!=DeviceInfo.Firmware) { - DeviceFirmwareChangeKafkaEvent KEvent(SerialNumber_, Utils::Now(),DeviceInfo.Firmware, Firmware ); + if (!Firmware.empty()) { + if (Firmware != DeviceInfo.Firmware) { + DeviceFirmwareChangeKafkaEvent KEvent(SerialNumber_, Utils::Now(), + DeviceInfo.Firmware, Firmware); DeviceInfo.Firmware = Firmware; DeviceInfo.LastFWUpdate = Utils::Now(); ++Updated; - GWWebSocketNotifications::SingleDeviceFirmwareChange_t Notification; + GWWebSocketNotifications::SingleDeviceFirmwareChange_t Notification; Notification.content.serialNumber = SerialNumber_; Notification.content.newFirmware = Firmware; GWWebSocketNotifications::DeviceFirmwareUpdated(Notification); - } else if(DeviceInfo.LastFWUpdate==0) { + } else if (DeviceInfo.LastFWUpdate == 0) { DeviceInfo.LastFWUpdate = Utils::Now(); ++Updated; } } - if(DeviceInfo.locale != State_.locale) { + if (DeviceInfo.locale != State_.locale) { DeviceInfo.locale = State_.locale; - ++Updated; + ++Updated; } - if(Compatible_ != DeviceInfo.DeviceType) { + if (Compatible_ != DeviceInfo.DeviceType) { DeviceInfo.DeviceType = Compatible_; - ++Updated; + ++Updated; } - if(RestrictedDevice != DeviceInfo.restrictedDevice) { + if (RestrictedDevice != DeviceInfo.restrictedDevice) { DeviceInfo.restrictedDevice = RestrictedDevice; - ++Updated; + ++Updated; } - if(Restrictions_ != DeviceInfo.restrictionDetails) { + if (Restrictions_ != DeviceInfo.restrictionDetails) { DeviceInfo.restrictionDetails = Restrictions_; ++Updated; } - if(Updated) { + if (Updated) { StorageService()->UpdateDevice(DeviceInfo); } - uint64_t UpgradedUUID=0; - LookForUpgrade(UUID,UpgradedUUID); + uint64_t UpgradedUUID = 0; + LookForUpgrade(UUID, UpgradedUUID); State_.UUID = UpgradedUUID; } State_.Compatible = Compatible_; State_.Connected = true; - ConnectionCompletionTime_ = std::chrono::high_resolution_clock::now() - ConnectionStart_; + ConnectionCompletionTime_ = + std::chrono::high_resolution_clock::now() - ConnectionStart_; State_.connectionCompletionTime = ConnectionCompletionTime_.count(); - if(State_.VerifiedCertificate == GWObjects::VALID_CERTIFICATE) { - if (( Utils::SerialNumberMatch(CN_, SerialNumber_, (int)AP_WS_Server()->MismatchDepth())) || - AP_WS_Server()->IsSimSerialNumber(CN_)) { + if (State_.VerifiedCertificate == GWObjects::VALID_CERTIFICATE) { + if ((Utils::SerialNumberMatch(CN_, SerialNumber_, + (int)AP_WS_Server()->MismatchDepth())) || + AP_WS_Server()->IsSimSerialNumber(CN_)) { State_.VerifiedCertificate = GWObjects::VERIFIED; - poco_information(Logger_, fmt::format("CONNECT({}): Fully validated and authenticated device. Session={} ConnectionCompletion Time={}", - CId_, - State_.sessionId, - State_.connectionCompletionTime )); + poco_information(Logger_, + fmt::format("CONNECT({}): Fully validated and authenticated " + "device. Session={} ConnectionCompletion Time={}", + CId_, State_.sessionId, + State_.connectionCompletionTime)); } else { State_.VerifiedCertificate = GWObjects::MISMATCH_SERIAL; - if(AP_WS_Server()->AllowSerialNumberMismatch()) { + if (AP_WS_Server()->AllowSerialNumberMismatch()) { poco_information( - Logger_, fmt::format("CONNECT({}): Serial number mismatch allowed. CN={} Serial={} Session={} ConnectionCompletion Time={}", - CId_, CN_, SerialNumber_, State_.sessionId, - State_.connectionCompletionTime)); + Logger_, + fmt::format("CONNECT({}): Serial number mismatch allowed. CN={} " + "Serial={} Session={} ConnectionCompletion Time={}", + CId_, CN_, SerialNumber_, State_.sessionId, + State_.connectionCompletionTime)); } else { poco_information( - Logger_, fmt::format("CONNECT({}): Serial number mismatch disallowed. Device rejected. CN={} Serial={} Session={}", + Logger_, fmt::format("CONNECT({}): Serial number mismatch disallowed. " + "Device rejected. CN={} Serial={} Session={}", CId_, CN_, SerialNumber_, State_.sessionId)); return EndConnection(); } } } - GWWebSocketNotifications::SingleDevice_t Notification; + GWWebSocketNotifications::SingleDevice_t Notification; Notification.content.serialNumber = SerialNumber_; GWWebSocketNotifications::DeviceConnected(Notification); - // std::cout << "Serial: " << SerialNumber_ << "Session: " << State_.sessionId << std::endl; + // std::cout << "Serial: " << SerialNumber_ << "Session: " << State_.sessionId << + // std::endl; if (KafkaManager()->Enabled()) { Poco::JSON::Stringifier Stringify; ParamsObj->set(uCentralProtocol::CONNECTIONIP, CId_); - ParamsObj->set("locale", State_.locale ); + ParamsObj->set("locale", State_.locale); ParamsObj->set(uCentralProtocol::TIMESTAMP, Utils::Now()); std::ostringstream OS; Stringify.condense(ParamsObj, OS); KafkaManager()->PostMessage(KafkaTopics::CONNECTION, SerialNumber_, OS.str()); } } else { - poco_warning(Logger_,fmt::format("INVALID-PROTOCOL({}): Missing one of uuid, firmware, or capabilities", CId_)); + poco_warning( + Logger_, + fmt::format("INVALID-PROTOCOL({}): Missing one of uuid, firmware, or capabilities", + CId_)); Errors_++; } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_crashlog.cpp b/src/AP_WS_Process_crashlog.cpp index 37880238..6ea92b3f 100644 --- a/src/AP_WS_Process_crashlog.cpp +++ b/src/AP_WS_Process_crashlog.cpp @@ -5,8 +5,8 @@ #include "AP_WS_Connection.h" #include "StorageService.h" -#include "framework/ow_constants.h" #include "fmt/format.h" +#include "framework/ow_constants.h" namespace OpenWifi { void AP_WS_Connection::Process_crashlog(Poco::JSON::Object::Ptr ParamsObj) { @@ -34,4 +34,4 @@ namespace OpenWifi { return; } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_deviceupdate.cpp b/src/AP_WS_Process_deviceupdate.cpp index 830cad76..5130e15b 100644 --- a/src/AP_WS_Process_deviceupdate.cpp +++ b/src/AP_WS_Process_deviceupdate.cpp @@ -9,10 +9,12 @@ namespace OpenWifi { - void AP_WS_Connection::Process_deviceupdate(Poco::JSON::Object::Ptr ParamsObj, std::string &Serial) { + void AP_WS_Connection::Process_deviceupdate(Poco::JSON::Object::Ptr ParamsObj, + std::string &Serial) { if (!State_.Connected) { - poco_warning(Logger_, fmt::format( - "INVALID-PROTOCOL({}): Device '{}' is not following protocol", CId_, CN_)); + poco_warning(Logger_, + fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", + CId_, CN_)); Errors_++; return; } @@ -20,8 +22,10 @@ namespace OpenWifi { auto Password = ParamsObj->get("currentPassword").toString(); StorageService()->SetDevicePassword(Serial, Password); - poco_trace(Logger_, fmt::format("DEVICEUPDATE({}): Device is updating its login password.", Serial)); + poco_trace( + Logger_, + fmt::format("DEVICEUPDATE({}): Device is updating its login password.", Serial)); } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_event.cpp b/src/AP_WS_Process_event.cpp index 866fd393..da4eafb6 100644 --- a/src/AP_WS_Process_event.cpp +++ b/src/AP_WS_Process_event.cpp @@ -4,16 +4,16 @@ #include "AP_WS_Connection.h" #include "StorageService.h" -#include "framework/ow_constants.h" #include "fmt/format.h" #include "framework/KafkaManager.h" +#include "framework/ow_constants.h" namespace OpenWifi { void AP_WS_Connection::Process_event(Poco::JSON::Object::Ptr ParamsObj) { if (!State_.Connected) { - poco_warning( - Logger_, - fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", CId_, CN_)); + poco_warning(Logger_, + fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", + CId_, CN_)); Errors_++; return; } @@ -41,10 +41,9 @@ namespace OpenWifi { OS.str()); } } - } catch(const Poco::Exception &E) { + } catch (const Poco::Exception &E) { Logger_.log(E); - } catch(...) { - + } catch (...) { } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_healthcheck.cpp b/src/AP_WS_Process_healthcheck.cpp index 88360872..450dea2e 100644 --- a/src/AP_WS_Process_healthcheck.cpp +++ b/src/AP_WS_Process_healthcheck.cpp @@ -5,16 +5,17 @@ #include "AP_WS_Connection.h" #include "StorageService.h" +#include "fmt/format.h" #include "framework/KafkaManager.h" #include "framework/utils.h" -#include "fmt/format.h" namespace OpenWifi { void AP_WS_Connection::Process_healthcheck(Poco::JSON::Object::Ptr ParamsObj) { if (!State_.Connected) { - poco_warning(Logger_, fmt::format( - "INVALID-PROTOCOL({}): Device '{}' is not following protocol", CId_, CN_)); + poco_warning(Logger_, + fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", + CId_, CN_)); Errors_++; return; } @@ -31,16 +32,14 @@ namespace OpenWifi { request_uuid = ParamsObj->get(uCentralProtocol::REQUEST_UUID).toString(); if (request_uuid.empty()) { - poco_trace(Logger_, - fmt::format("HEALTHCHECK({}): UUID={} Updating.", CId_, UUID)); + poco_trace(Logger_, fmt::format("HEALTHCHECK({}): UUID={} Updating.", CId_, UUID)); } else { - poco_trace(Logger_, - fmt::format("HEALTHCHECK({}): UUID={} Updating for CMD={}.", CId_, - UUID, request_uuid)); + poco_trace(Logger_, fmt::format("HEALTHCHECK({}): UUID={} Updating for CMD={}.", + CId_, UUID, request_uuid)); } uint64_t UpgradedUUID; - LookForUpgrade(UUID,UpgradedUUID); + LookForUpgrade(UUID, UpgradedUUID); State_.UUID = UpgradedUUID; GWObjects::HealthCheck Check; @@ -71,4 +70,4 @@ namespace OpenWifi { } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_log.cpp b/src/AP_WS_Process_log.cpp index fe0e87fe..a7e0c3a4 100644 --- a/src/AP_WS_Process_log.cpp +++ b/src/AP_WS_Process_log.cpp @@ -5,15 +5,15 @@ #include "AP_WS_Connection.h" #include "StorageService.h" -#include "framework/ow_constants.h" #include "fmt/format.h" +#include "framework/ow_constants.h" namespace OpenWifi { void AP_WS_Connection::Process_log(Poco::JSON::Object::Ptr ParamsObj) { if (!State_.Connected) { - poco_warning( - Logger_, - fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", CId_, CN_)); + poco_warning(Logger_, + fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", + CId_, CN_)); Errors_++; return; } @@ -41,4 +41,4 @@ namespace OpenWifi { return; } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_ping.cpp b/src/AP_WS_Process_ping.cpp index 2d00da80..a9244e60 100644 --- a/src/AP_WS_Process_ping.cpp +++ b/src/AP_WS_Process_ping.cpp @@ -15,4 +15,4 @@ namespace OpenWifi { poco_warning(Logger_, fmt::format("PING({}): Missing parameter.", CId_)); } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_recovery.cpp b/src/AP_WS_Process_recovery.cpp index 729d408f..a9100b2c 100644 --- a/src/AP_WS_Process_recovery.cpp +++ b/src/AP_WS_Process_recovery.cpp @@ -3,12 +3,11 @@ // #include "AP_WS_Connection.h" -#include "StorageService.h" #include "CommandManager.h" +#include "StorageService.h" -#include "framework/ow_constants.h" -#include "framework/MicroServiceFuncs.h" #include "fmt/format.h" +#include "framework/MicroServiceFuncs.h" #include "framework/ow_constants.h" namespace OpenWifi { @@ -52,16 +51,24 @@ namespace OpenWifi { Poco::JSON::Stringifier::stringify(Params, O); Cmd.Details = O.str(); bool Sent; - CommandManager()->PostCommand(CommandManager()->Next_RPC_ID(), APCommands::Commands::reboot, SerialNumber_, Cmd.Command, Params, Cmd.UUID, Sent, false, false); - StorageService()->AddCommand(SerialNumber_, Cmd, Storage::CommandExecutionType::COMMAND_EXECUTED); - poco_information(Logger_, fmt::format("RECOVERY({}): Recovery mode received, need for a reboot.", CId_)); + CommandManager()->PostCommand(CommandManager()->Next_RPC_ID(), + APCommands::Commands::reboot, SerialNumber_, + Cmd.Command, Params, Cmd.UUID, Sent, false, false); + StorageService()->AddCommand(SerialNumber_, Cmd, + Storage::CommandExecutionType::COMMAND_EXECUTED); + poco_information( + Logger_, + fmt::format("RECOVERY({}): Recovery mode received, need for a reboot.", CId_)); } else { - poco_information(Logger_, fmt::format( - "RECOVERY({}): Recovery mode received, no need for a reboot.", CId_)); + poco_information( + Logger_, + fmt::format("RECOVERY({}): Recovery mode received, no need for a reboot.", + CId_)); } } else { - poco_warning(Logger_, fmt::format("RECOVERY({}): Recovery missing one of serialnumber, firmware, uuid, loglines, reboot", - CId_)); + poco_warning(Logger_, fmt::format("RECOVERY({}): Recovery missing one of serialnumber, " + "firmware, uuid, loglines, reboot", + CId_)); } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_state.cpp b/src/AP_WS_Process_state.cpp index 7e0a4c1b..22035c5c 100644 --- a/src/AP_WS_Process_state.cpp +++ b/src/AP_WS_Process_state.cpp @@ -3,8 +3,8 @@ // #include "AP_WS_Connection.h" -#include "StorageService.h" #include "StateUtils.h" +#include "StorageService.h" #include "UI_GW_WebSocketNotifications.h" @@ -16,8 +16,9 @@ namespace OpenWifi { void AP_WS_Connection::Process_state(Poco::JSON::Object::Ptr ParamsObj) { if (!State_.Connected) { - poco_warning(Logger_, fmt::format( - "INVALID-PROTOCOL({}): Device '{}' is not following protocol", CId_, CN_)); + poco_warning(Logger_, + fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", + CId_, CN_)); Errors_++; return; } @@ -34,12 +35,12 @@ namespace OpenWifi { if (request_uuid.empty()) { poco_trace(Logger_, fmt::format("STATE({}): UUID={} Updating.", CId_, UUID)); } else { - poco_trace(Logger_, fmt::format("STATE({}): UUID={} Updating for CMD={}.", - CId_, UUID, request_uuid)); + poco_trace(Logger_, fmt::format("STATE({}): UUID={} Updating for CMD={}.", CId_, + UUID, request_uuid)); } uint64_t UpgradedUUID; - LookForUpgrade(UUID,UpgradedUUID); + LookForUpgrade(UUID, UpgradedUUID); State_.UUID = UpgradedUUID; SetLastStats(StateStr); @@ -51,10 +52,8 @@ namespace OpenWifi { StorageService()->SetCommandResult(request_uuid, StateStr); } - StateUtils::ComputeAssociations(StateObj, State_.Associations_2G, - State_.Associations_5G, - State_.Associations_6G - ); + StateUtils::ComputeAssociations(StateObj, State_.Associations_2G, + State_.Associations_5G, State_.Associations_6G); if (KafkaManager()->Enabled()) { Poco::JSON::Stringifier Stringify; @@ -63,12 +62,14 @@ namespace OpenWifi { KafkaManager()->PostMessage(KafkaTopics::STATE, SerialNumber_, OS.str()); } - GWWebSocketNotifications::SingleDevice_t N; + GWWebSocketNotifications::SingleDevice_t N; N.content.serialNumber = SerialNumber_; GWWebSocketNotifications::DeviceStatistics(N); } else { - poco_warning(Logger_, fmt::format("STATE({}): Invalid request. Missing serial, uuid, or state", CId_)); + poco_warning( + Logger_, + fmt::format("STATE({}): Invalid request. Missing serial, uuid, or state", CId_)); } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_telemetry.cpp b/src/AP_WS_Process_telemetry.cpp index 7df542cf..fa7dd1c4 100644 --- a/src/AP_WS_Process_telemetry.cpp +++ b/src/AP_WS_Process_telemetry.cpp @@ -3,37 +3,39 @@ // #include "AP_WS_Connection.h" -#include "TelemetryStream.h" #include "CommandManager.h" +#include "TelemetryStream.h" +#include "fmt/format.h" #include "framework/KafkaManager.h" #include "framework/utils.h" -#include "fmt/format.h" namespace OpenWifi { void AP_WS_Connection::Process_telemetry(Poco::JSON::Object::Ptr ParamsObj) { if (!State_.Connected) { - poco_warning(Logger_, fmt::format( - "INVALID-PROTOCOL({}): Device '{}' is not following protocol", CId_, CN_)); + poco_warning(Logger_, + fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", + CId_, CN_)); Errors_++; return; } - poco_trace(Logger_,fmt::format("Telemetry data received for {}", SerialNumber_)); + poco_trace(Logger_, fmt::format("Telemetry data received for {}", SerialNumber_)); if (TelemetryReporting_ || ParamsObj->has("adhoc")) { if (ParamsObj->has("data")) { auto Payload = ParamsObj->get("data").extract(); Payload->set("timestamp", Utils::Now()); std::ostringstream SS; Payload->stringify(SS); - auto now=Utils::Now(); - if(ParamsObj->has("adhoc")) { + auto now = Utils::Now(); + if (ParamsObj->has("adhoc")) { KafkaManager()->PostMessage(KafkaTopics::DEVICE_TELEMETRY, SerialNumber_, SS.str()); return; } if (TelemetryWebSocketRefCount_) { - if(nowNotifyEndPoint(SerialNumberInt_, SS.str()); @@ -42,7 +44,7 @@ namespace OpenWifi { } } if (TelemetryKafkaRefCount_) { - if(KafkaManager()->Enabled() && nowEnabled() && now < TelemetryKafkaTimer_) { // std::cout << SerialNumber_ << ": Updating Kafka telemetry" << std::endl; TelemetryKafkaPackets_++; State_.kafkaPackets = TelemetryKafkaPackets_; @@ -53,12 +55,14 @@ namespace OpenWifi { } } } else { - poco_debug(Logger_,fmt::format("TELEMETRY({}): Invalid telemetry packet.",SerialNumber_)); + poco_debug(Logger_, + fmt::format("TELEMETRY({}): Invalid telemetry packet.", SerialNumber_)); } } else { // if we are ignoring telemetry, then close it down on the device. - poco_debug(Logger_,fmt::format("TELEMETRY({}): Stopping runaway telemetry.",SerialNumber_)); + poco_debug(Logger_, + fmt::format("TELEMETRY({}): Stopping runaway telemetry.", SerialNumber_)); StopTelemetry(CommandManager()->Next_RPC_ID()); } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_venuebroadcast.cpp b/src/AP_WS_Process_venuebroadcast.cpp index b95d9eac..0752d100 100644 --- a/src/AP_WS_Process_venuebroadcast.cpp +++ b/src/AP_WS_Process_venuebroadcast.cpp @@ -7,11 +7,10 @@ namespace OpenWifi { void AP_WS_Connection::Process_venuebroadcast(Poco::JSON::Object::Ptr ParamsObj) { - if(ParamsObj->has("data") && ParamsObj->has("serial") && ParamsObj->has("timestamp")) { - VenueBroadcaster()->Broadcast( - ParamsObj->get("serial").toString(), - ParamsObj->get("data").toString(), - ParamsObj->get("timestamp")); + if (ParamsObj->has("data") && ParamsObj->has("serial") && ParamsObj->has("timestamp")) { + VenueBroadcaster()->Broadcast(ParamsObj->get("serial").toString(), + ParamsObj->get("data").toString(), + ParamsObj->get("timestamp")); } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Process_wifiscan.cpp b/src/AP_WS_Process_wifiscan.cpp index bf1b4da8..8f9add8f 100644 --- a/src/AP_WS_Process_wifiscan.cpp +++ b/src/AP_WS_Process_wifiscan.cpp @@ -4,16 +4,16 @@ #include "AP_WS_Connection.h" #include "StorageService.h" -#include "framework/ow_constants.h" #include "fmt/format.h" #include "framework/KafkaManager.h" +#include "framework/ow_constants.h" namespace OpenWifi { void AP_WS_Connection::Process_wifiscan(Poco::JSON::Object::Ptr ParamsObj) { if (!State_.Connected) { - poco_warning( - Logger_, - fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", CId_, CN_)); + poco_warning(Logger_, + fmt::format("INVALID-PROTOCOL({}): Device '{}' is not following protocol", + CId_, CN_)); Errors_++; return; } @@ -29,4 +29,4 @@ namespace OpenWifi { } } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_ReactorPool.h b/src/AP_WS_ReactorPool.h index 1d08504d..21f580b3 100644 --- a/src/AP_WS_ReactorPool.h +++ b/src/AP_WS_ReactorPool.h @@ -4,11 +4,11 @@ #pragma once -#include #include +#include -#include "Poco/Net/SocketAcceptor.h" #include "Poco/Environment.h" +#include "Poco/Net/SocketAcceptor.h" #include "framework/utils.h" @@ -16,14 +16,12 @@ namespace OpenWifi { class AP_WS_ReactorThreadPool { public: explicit AP_WS_ReactorThreadPool() { - NumberOfThreads_ = Poco::Environment::processorCount()*2; - if(NumberOfThreads_==0) - NumberOfThreads_=4; + NumberOfThreads_ = Poco::Environment::processorCount() * 2; + if (NumberOfThreads_ == 0) + NumberOfThreads_ = 4; } - ~ AP_WS_ReactorThreadPool() { - Stop(); - } + ~AP_WS_ReactorThreadPool() { Stop(); } void Start() { for (uint64_t i = 0; i < NumberOfThreads_; ++i) { @@ -31,7 +29,7 @@ namespace OpenWifi { auto NewThread = std::make_unique(); NewThread->start(*NewReactor); std::string ThreadName{"ap:react:" + std::to_string(i)}; - Utils::SetThreadName(*NewThread,ThreadName.c_str()); + Utils::SetThreadName(*NewThread, ThreadName.c_str()); Reactors_.emplace_back(std::move(NewReactor)); Threads_.emplace_back(std::move(NewThread)); } @@ -48,17 +46,17 @@ namespace OpenWifi { } Poco::Net::SocketReactor &NextReactor() { - std::shared_lock Lock(Mutex_); + std::shared_lock Lock(Mutex_); NextReactor_++; NextReactor_ %= NumberOfThreads_; return *Reactors_[NextReactor_]; } private: - std::shared_mutex Mutex_; - uint64_t NumberOfThreads_; - uint64_t NextReactor_ = 0; + std::shared_mutex Mutex_; + uint64_t NumberOfThreads_; + uint64_t NextReactor_ = 0; std::vector> Reactors_; std::vector> Threads_; }; -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Server.cpp b/src/AP_WS_Server.cpp index 828e85b2..3b5e842d 100644 --- a/src/AP_WS_Server.cpp +++ b/src/AP_WS_Server.cpp @@ -6,35 +6,41 @@ // Arilia Wireless Inc. // -#include "Poco/Net/HTTPHeaderStream.h" #include "Poco/Net/Context.h" +#include "Poco/Net/HTTPHeaderStream.h" #include "Poco/Net/HTTPServerRequest.h" -#include "AP_WS_Server.h" #include "AP_WS_Connection.h" +#include "AP_WS_Server.h" #include "ConfigurationCache.h" #include "TelemetryStream.h" -#include "framework/MicroServiceFuncs.h" -#include "framework/utils.h" #include "UI_GW_WebSocketNotifications.h" #include "fmt/format.h" +#include "framework/MicroServiceFuncs.h" +#include "framework/utils.h" namespace OpenWifi { void AP_WS_RequestHandler::handleRequest(Poco::Net::HTTPServerRequest &request, - Poco::Net::HTTPServerResponse &response) { + Poco::Net::HTTPServerResponse &response) { try { - AP_WS_Server()->AddConnection(id_,std::make_shared(request,response,id_, Logger_, AP_WS_Server()->NextReactor())); + AP_WS_Server()->AddConnection( + id_, std::make_shared(request, response, id_, Logger_, + AP_WS_Server()->NextReactor())); } catch (...) { - poco_warning(Logger_,"Exception during WS creation"); + poco_warning(Logger_, "Exception during WS creation"); } }; - bool AP_WS_Server::ValidateCertificate(const std::string & ConnectionId, const Poco::Crypto::X509Certificate & Certificate) { - if(IsCertOk()) { - if(!Certificate.issuedBy(*IssuerCert_)) { - poco_warning(Logger(),fmt::format("CERTIFICATE({}): issuer mismatch. Local='{}' Incoming='{}'", ConnectionId, IssuerCert_->issuerName(), Certificate.issuerName())); + bool AP_WS_Server::ValidateCertificate(const std::string &ConnectionId, + const Poco::Crypto::X509Certificate &Certificate) { + if (IsCertOk()) { + if (!Certificate.issuedBy(*IssuerCert_)) { + poco_warning( + Logger(), + fmt::format("CERTIFICATE({}): issuer mismatch. Local='{}' Incoming='{}'", + ConnectionId, IssuerCert_->issuerName(), Certificate.issuerName())); return false; } return true; @@ -44,16 +50,18 @@ namespace OpenWifi { int AP_WS_Server::Start() { - AllowSerialNumberMismatch_ = MicroServiceConfigGetBool("openwifi.certificates.allowmismatch",true); - MismatchDepth_ = MicroServiceConfigGetInt("openwifi.certificates.mismatchdepth",2); + AllowSerialNumberMismatch_ = + MicroServiceConfigGetBool("openwifi.certificates.allowmismatch", true); + MismatchDepth_ = MicroServiceConfigGetInt("openwifi.certificates.mismatchdepth", 2); Reactor_pool_ = std::make_unique(); Reactor_pool_->Start(); - for(const auto & Svr : ConfigServersList_ ) { + for (const auto &Svr : ConfigServersList_) { - poco_notice(Logger(),fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}", Svr.Address(), - Svr.Port(), Svr.KeyFile(), Svr.CertFile())); + poco_notice(Logger(), + fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}", Svr.Address(), + Svr.Port(), Svr.KeyFile(), Svr.CertFile())); Svr.LogCert(Logger()); if (!Svr.RootCA().empty()) @@ -61,8 +69,8 @@ namespace OpenWifi { if (!IsCertOk()) { IssuerCert_ = std::make_unique(Svr.IssuerCertFile()); - poco_information(Logger(), - fmt::format("Certificate Issuer Name:{}", IssuerCert_->issuerName())); + poco_information( + Logger(), fmt::format("Certificate Issuer Name:{}", IssuerCert_->issuerName())); } Poco::Net::Context::Params P; @@ -74,7 +82,8 @@ namespace OpenWifi { P.dhUse2048Bits = true; P.caLocation = Svr.Cas(); - auto Context = Poco::AutoPtr(new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P)); + auto Context = Poco::AutoPtr( + new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P)); Poco::Crypto::X509Certificate Cert(Svr.CertFile()); Poco::Crypto::X509Certificate Root(Svr.RootCA()); @@ -96,7 +105,8 @@ namespace OpenWifi { Context->enableSessionCache(true); Context->enableExtendedCertificateVerification(false); // Context->disableStatelessSessionResumption(); - Context->disableProtocols(Poco::Net::Context::PROTO_TLSV1 | Poco::Net::Context::PROTO_TLSV1_1); + Context->disableProtocols(Poco::Net::Context::PROTO_TLSV1 | + Poco::Net::Context::PROTO_TLSV1_1); auto WebServerHttpParams = new Poco::Net::HTTPServerParams; WebServerHttpParams->setMaxThreads(50); @@ -110,25 +120,29 @@ namespace OpenWifi { : Poco::Net::AddressFamily::IPv4)); Poco::Net::SocketAddress SockAddr(Addr, Svr.Port()); auto NewWebServer = std::make_unique( - new AP_WS_RequestHandlerFactory(Logger()), DeviceConnectionPool_, Poco::Net::SecureServerSocket(SockAddr, Svr.Backlog(), Context), WebServerHttpParams); + new AP_WS_RequestHandlerFactory(Logger()), DeviceConnectionPool_, + Poco::Net::SecureServerSocket(SockAddr, Svr.Backlog(), Context), + WebServerHttpParams); WebServers_.push_back(std::move(NewWebServer)); } else { Poco::Net::IPAddress Addr(Svr.Address()); Poco::Net::SocketAddress SockAddr(Addr, Svr.Port()); auto NewWebServer = std::make_unique( - new AP_WS_RequestHandlerFactory(Logger()), DeviceConnectionPool_, Poco::Net::SecureServerSocket(SockAddr, Svr.Backlog(), Context), WebServerHttpParams); + new AP_WS_RequestHandlerFactory(Logger()), DeviceConnectionPool_, + Poco::Net::SecureServerSocket(SockAddr, Svr.Backlog(), Context), + WebServerHttpParams); WebServers_.push_back(std::move(NewWebServer)); } } - for(auto &server:WebServers_) { + for (auto &server : WebServers_) { server->start(); } ReactorThread_.start(Reactor_); - auto ProvString = MicroServiceConfigGetString("autoprovisioning.process","default"); - if(ProvString!="default") { + auto ProvString = MicroServiceConfigGetString("autoprovisioning.process", "default"); + if (ProvString != "default") { auto Tokens = Poco::StringTokenizer(ProvString, ","); for (const auto &i : Tokens) { if (i == "prov") @@ -140,11 +154,12 @@ namespace OpenWifi { UseDefaultConfig_ = true; } - SimulatorId_ = MicroServiceConfigGetString("simulatorid",""); + SimulatorId_ = MicroServiceConfigGetString("simulatorid", ""); SimulatorEnabled_ = !SimulatorId_.empty(); - Utils::SetThreadName(ReactorThread_,"dev:react:head"); + Utils::SetThreadName(ReactorThread_, "dev:react:head"); - GarbageCollectorCallback_ = std::make_unique>(*this,&AP_WS_Server::onGarbageCollecting); + GarbageCollectorCallback_ = std::make_unique>( + *this, &AP_WS_Server::onGarbageCollecting); Timer_.setStartInterval(10 * 1000); Timer_.setPeriodicInterval(5 * 1000); // every minute Timer_.start(*GarbageCollectorCallback_, MicroServiceTimerPool()); @@ -154,8 +169,8 @@ namespace OpenWifi { } void AP_WS_Server::onGarbageCollecting([[maybe_unused]] Poco::Timer &timer) { - std::lock_guard Lock(WSServerMutex_); - if(!Garbage_.empty()) { + std::lock_guard Lock(WSServerMutex_); + if (!Garbage_.empty()) { Garbage_.clear(); } @@ -164,11 +179,11 @@ namespace OpenWifi { NumberOfConnectedDevices_ = 0; NumberOfConnectingDevices_ = 0; AverageDeviceConnectionTime_ = 0; - uint64_t total_connected_time=0; + uint64_t total_connected_time = 0; auto now = Utils::Now(); - for (const auto & connection:SerialNumbers_) { - if(connection.second.second == nullptr) { + for (const auto &connection : SerialNumbers_) { + if (connection.second.second == nullptr) { continue; } if (connection.second.second->State_.Connected) { @@ -179,15 +194,19 @@ namespace OpenWifi { } } - AverageDeviceConnectionTime_ = (NumberOfConnectedDevices_!=0) ? total_connected_time/NumberOfConnectedDevices_ : 0; - if((now-last_log)>120) { + AverageDeviceConnectionTime_ = + (NumberOfConnectedDevices_ != 0) ? total_connected_time / NumberOfConnectedDevices_ : 0; + if ((now - last_log) > 120) { last_log = now; - poco_information(Logger(), - fmt::format("Active AP connections: {} Connecting: {} Average connection time: {} seconds", - NumberOfConnectedDevices_, NumberOfConnectingDevices_, AverageDeviceConnectionTime_)); + poco_information( + Logger(), + fmt::format( + "Active AP connections: {} Connecting: {} Average connection time: {} seconds", + NumberOfConnectedDevices_, NumberOfConnectingDevices_, + AverageDeviceConnectionTime_)); } - GWWebSocketNotifications::NumberOfConnection_t Notification; + GWWebSocketNotifications::NumberOfConnection_t Notification; Notification.content.numberOfConnectingDevices = NumberOfConnectingDevices_; Notification.content.numberOfDevices = NumberOfConnectedDevices_; Notification.content.averageConnectedTime = AverageDeviceConnectionTime_; @@ -195,22 +214,22 @@ namespace OpenWifi { } void AP_WS_Server::Stop() { - poco_information(Logger(),"Stopping..."); + poco_information(Logger(), "Stopping..."); Running_ = false; Timer_.stop(); - for(auto &server:WebServers_) { + for (auto &server : WebServers_) { server->stopAll(); } Reactor_pool_->Stop(); Reactor_.stop(); ReactorThread_.join(); - poco_information(Logger(),"Stopped..."); + poco_information(Logger(), "Stopped..."); } bool AP_WS_Server::GetStatistics(uint64_t SerialNumber, std::string &Statistics) const { - std::shared_ptr DevicePtr; + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -223,8 +242,8 @@ namespace OpenWifi { return true; } - bool AP_WS_Server::GetState(uint64_t SerialNumber, GWObjects::ConnectionState & State) const { - std::shared_ptr DevicePtr; + bool AP_WS_Server::GetState(uint64_t SerialNumber, GWObjects::ConnectionState &State) const { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -237,8 +256,9 @@ namespace OpenWifi { return true; } - bool AP_WS_Server::GetHealthcheck(uint64_t SerialNumber, GWObjects::HealthCheck & CheckData) const { - std::shared_ptr DevicePtr; + bool AP_WS_Server::GetHealthcheck(uint64_t SerialNumber, + GWObjects::HealthCheck &CheckData) const { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -252,15 +272,15 @@ namespace OpenWifi { } void AP_WS_Server::SetSessionDetails(uint64_t connection_id, uint64_t SerialNumber) { - std::lock_guard Lock(WSServerMutex_); + std::lock_guard Lock(WSServerMutex_); auto Conn = Sessions_.find(connection_id); - if(Conn == end(Sessions_)) + if (Conn == end(Sessions_)) return; auto CurrentSerialNumber = SerialNumbers_.find(SerialNumber); - if( (CurrentSerialNumber==SerialNumbers_.end()) || - (CurrentSerialNumber->second.firstsecond.first < connection_id)) { SerialNumbers_[SerialNumber] = std::make_pair(connection_id, Conn->second); return; } @@ -270,7 +290,7 @@ namespace OpenWifi { std::lock_guard G(WSServerMutex_); auto Session = Sessions_.find(session_id); - if(Session==end(Sessions_)) + if (Session == end(Sessions_)) return false; Garbage_.push_back(Session->second); @@ -281,7 +301,7 @@ namespace OpenWifi { return false; } - if(Device->second.first==session_id) { + if (Device->second.first == session_id) { Sessions_.erase(Session); SerialNumbers_.erase(Device); return true; @@ -291,8 +311,9 @@ namespace OpenWifi { return false; } - bool AP_WS_Server::Connected(uint64_t SerialNumber, GWObjects::DeviceRestrictions & Restrictions) const { - std::shared_ptr DevicePtr; + bool AP_WS_Server::Connected(uint64_t SerialNumber, + GWObjects::DeviceRestrictions &Restrictions) const { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -302,11 +323,11 @@ namespace OpenWifi { DevicePtr = Device->second.second; } DevicePtr->GetRestrictions(Restrictions); - return DevicePtr->State_.Connected; + return DevicePtr->State_.Connected; } bool AP_WS_Server::Connected(uint64_t SerialNumber) const { - std::shared_ptr DevicePtr; + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -315,11 +336,11 @@ namespace OpenWifi { } DevicePtr = Device->second.second; } - return DevicePtr->State_.Connected; + return DevicePtr->State_.Connected; } - bool AP_WS_Server::SendFrame(uint64_t SerialNumber, const std::string & Payload) const { - std::shared_ptr DevicePtr; + bool AP_WS_Server::SendFrame(uint64_t SerialNumber, const std::string &Payload) const { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -331,13 +352,14 @@ namespace OpenWifi { try { return DevicePtr->Send(Payload); } catch (...) { - poco_debug(Logger(),fmt::format(": SendFrame: Could not send data to device '{}'", Utils::IntToSerialNumber(SerialNumber))); + poco_debug(Logger(), fmt::format(": SendFrame: Could not send data to device '{}'", + Utils::IntToSerialNumber(SerialNumber))); } return false; } void AP_WS_Server::StopWebSocketTelemetry(uint64_t RPCID, uint64_t SerialNumber) { - std::shared_ptr DevicePtr; + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); @@ -350,8 +372,11 @@ namespace OpenWifi { DevicePtr->StopWebSocketTelemetry(RPCID); } - void AP_WS_Server::SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime, const std::vector & TelemetryTypes) { - std::shared_ptr DevicePtr; + void + AP_WS_Server::SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, + uint64_t Interval, uint64_t Lifetime, + const std::vector &TelemetryTypes) { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -363,8 +388,10 @@ namespace OpenWifi { DevicePtr->SetWebSocketTelemetryReporting(RPCID, Interval, Lifetime, TelemetryTypes); } - void AP_WS_Server::SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime, const std::vector & TelemetryTypes) { - std::shared_ptr DevicePtr; + void AP_WS_Server::SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, + uint64_t Interval, uint64_t Lifetime, + const std::vector &TelemetryTypes) { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -377,7 +404,7 @@ namespace OpenWifi { } void AP_WS_Server::StopKafkaTelemetry(uint64_t RPCID, uint64_t SerialNumber) { - std::shared_ptr DevicePtr; + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -389,15 +416,12 @@ namespace OpenWifi { DevicePtr->StopKafkaTelemetry(RPCID); } - void AP_WS_Server::GetTelemetryParameters(uint64_t SerialNumber , bool & TelemetryRunning, - uint64_t & TelemetryInterval, - uint64_t & TelemetryWebSocketTimer, - uint64_t & TelemetryKafkaTimer, - uint64_t & TelemetryWebSocketCount, - uint64_t & TelemetryKafkaCount, - uint64_t & TelemetryWebSocketPackets, - uint64_t & TelemetryKafkaPackets) { - std::shared_ptr DevicePtr; + void AP_WS_Server::GetTelemetryParameters( + uint64_t SerialNumber, bool &TelemetryRunning, uint64_t &TelemetryInterval, + uint64_t &TelemetryWebSocketTimer, uint64_t &TelemetryKafkaTimer, + uint64_t &TelemetryWebSocketCount, uint64_t &TelemetryKafkaCount, + uint64_t &TelemetryWebSocketPackets, uint64_t &TelemetryKafkaPackets) { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(SerialNumber); @@ -406,14 +430,15 @@ namespace OpenWifi { } DevicePtr = Device->second.second; } - DevicePtr->GetTelemetryParameters( - TelemetryRunning, TelemetryInterval, TelemetryWebSocketTimer, TelemetryKafkaTimer, - TelemetryWebSocketCount, TelemetryKafkaCount, TelemetryWebSocketPackets, - TelemetryKafkaPackets); + DevicePtr->GetTelemetryParameters(TelemetryRunning, TelemetryInterval, + TelemetryWebSocketTimer, TelemetryKafkaTimer, + TelemetryWebSocketCount, TelemetryKafkaCount, + TelemetryWebSocketPackets, TelemetryKafkaPackets); } - bool AP_WS_Server::SendRadiusAccountingData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size) { - std::shared_ptr DevicePtr; + bool AP_WS_Server::SendRadiusAccountingData(const std::string &SerialNumber, + const unsigned char *buffer, std::size_t size) { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(Utils::SerialNumberToInt(SerialNumber)); @@ -424,15 +449,19 @@ namespace OpenWifi { } try { - return DevicePtr->SendRadiusAccountingData(buffer,size); + return DevicePtr->SendRadiusAccountingData(buffer, size); } catch (...) { - poco_debug(Logger(),fmt::format(": SendRadiusAuthenticationData: Could not send data to device '{}'", SerialNumber)); + poco_debug( + Logger(), + fmt::format(": SendRadiusAuthenticationData: Could not send data to device '{}'", + SerialNumber)); } return false; } - bool AP_WS_Server::SendRadiusAuthenticationData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size) { - std::shared_ptr DevicePtr; + bool AP_WS_Server::SendRadiusAuthenticationData(const std::string &SerialNumber, + const unsigned char *buffer, std::size_t size) { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(Utils::SerialNumberToInt(SerialNumber)); @@ -443,15 +472,19 @@ namespace OpenWifi { } try { - return DevicePtr->SendRadiusAuthenticationData(buffer,size); + return DevicePtr->SendRadiusAuthenticationData(buffer, size); } catch (...) { - poco_debug(Logger(),fmt::format(": SendRadiusAuthenticationData: Could not send data to device '{}'", SerialNumber)); + poco_debug( + Logger(), + fmt::format(": SendRadiusAuthenticationData: Could not send data to device '{}'", + SerialNumber)); } return false; } - bool AP_WS_Server::SendRadiusCoAData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size) { - std::shared_ptr DevicePtr; + bool AP_WS_Server::SendRadiusCoAData(const std::string &SerialNumber, + const unsigned char *buffer, std::size_t size) { + std::shared_ptr DevicePtr; { std::lock_guard Lock(WSServerMutex_); auto Device = SerialNumbers_.find(Utils::SerialNumberToInt(SerialNumber)); @@ -462,11 +495,13 @@ namespace OpenWifi { } try { - return DevicePtr->SendRadiusCoAData(buffer,size); + return DevicePtr->SendRadiusCoAData(buffer, size); } catch (...) { - poco_debug(Logger(),fmt::format(": SendRadiusCoAData: Could not send data to device '{}'", SerialNumber)); + poco_debug(Logger(), + fmt::format(": SendRadiusCoAData: Could not send data to device '{}'", + SerialNumber)); } return false; } -} //namespace \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/AP_WS_Server.h b/src/AP_WS_Server.h index 88a5c0c3..9acdbcaf 100644 --- a/src/AP_WS_Server.h +++ b/src/AP_WS_Server.h @@ -8,62 +8,59 @@ #pragma once -#include -#include #include #include +#include +#include #include "Poco/AutoPtr.h" -#include "Poco/Net/SocketReactor.h" -#include "Poco/Net/ParallelSocketAcceptor.h" -#include "Poco/Net/SocketAcceptor.h" -#include "Poco/Timer.h" #include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPRequestHandlerFactory.h" #include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPServerRequest.h" +#include "Poco/Net/ParallelSocketAcceptor.h" +#include "Poco/Net/SocketAcceptor.h" +#include "Poco/Net/SocketReactor.h" +#include "Poco/Timer.h" #include "AP_WS_Connection.h" #include "AP_WS_ReactorPool.h" -#include "framework/utils.h" #include "framework/SubSystemServer.h" +#include "framework/utils.h" namespace OpenWifi { class AP_WS_RequestHandler : public Poco::Net::HTTPRequestHandler { public: - explicit AP_WS_RequestHandler(Poco::Logger &L, uint64_t id) - : Logger_(L), - id_(id){ - }; + explicit AP_WS_RequestHandler(Poco::Logger &L, uint64_t id) : Logger_(L), id_(id){}; void handleRequest(Poco::Net::HTTPServerRequest &request, Poco::Net::HTTPServerResponse &response) override; + private: - Poco::Logger &Logger_; - uint64_t id_=0; + Poco::Logger &Logger_; + uint64_t id_ = 0; }; class AP_WS_RequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { public: - inline explicit AP_WS_RequestHandlerFactory(Poco::Logger &L) - : Logger_(L) { - } + inline explicit AP_WS_RequestHandlerFactory(Poco::Logger &L) : Logger_(L) {} inline Poco::Net::HTTPRequestHandler * createRequestHandler(const Poco::Net::HTTPServerRequest &request) override { if (request.find("Upgrade") != request.end() && Poco::icompare(request["Upgrade"], "websocket") == 0) { Utils::SetThreadName("ws:conn-init"); - return new AP_WS_RequestHandler(Logger_,id_++); + return new AP_WS_RequestHandler(Logger_, id_++); } else { return nullptr; } } + private: - Poco::Logger &Logger_; - inline static uint64_t id_=1; + Poco::Logger &Logger_; + inline static uint64_t id_ = 1; }; class AP_WS_Server : public SubSystemServer { @@ -75,136 +72,143 @@ namespace OpenWifi { int Start() override; void Stop() override; - bool IsCertOk() { return IssuerCert_!= nullptr; } - bool ValidateCertificate(const std::string & ConnectionId, const Poco::Crypto::X509Certificate & Certificate); + bool IsCertOk() { return IssuerCert_ != nullptr; } + bool ValidateCertificate(const std::string &ConnectionId, + const Poco::Crypto::X509Certificate &Certificate); // Poco::Net::SocketReactor & GetNextReactor() { return ReactorPool_.NextReactor(); } - inline bool IsSimSerialNumber(const std::string & SerialNumber) const { - return IsSim(Poco::toLower(SerialNumber)) && Poco::toLower(SerialNumber) == Poco::toLower(SimulatorId_); + inline bool IsSimSerialNumber(const std::string &SerialNumber) const { + return IsSim(Poco::toLower(SerialNumber)) && + Poco::toLower(SerialNumber) == Poco::toLower(SimulatorId_); } - inline static bool IsSim(const std::string & SerialNumber) { - return SerialNumber.substr(0,6) == "53494d"; + inline static bool IsSim(const std::string &SerialNumber) { + return SerialNumber.substr(0, 6) == "53494d"; } - inline bool IsSimEnabled() const { - return SimulatorEnabled_; - } + inline bool IsSimEnabled() const { return SimulatorEnabled_; } - inline bool AllowSerialNumberMismatch() const { - return AllowSerialNumberMismatch_; - } + inline bool AllowSerialNumberMismatch() const { return AllowSerialNumberMismatch_; } - inline uint64_t MismatchDepth() const { - return MismatchDepth_; - } + inline uint64_t MismatchDepth() const { return MismatchDepth_; } inline bool UseProvisioning() const { return LookAtProvisioning_; } inline bool UseDefaults() const { return UseDefaultConfig_; } - [[nodiscard]] inline Poco::Net::SocketReactor & NextReactor() { return Reactor_pool_->NextReactor(); } + [[nodiscard]] inline Poco::Net::SocketReactor &NextReactor() { + return Reactor_pool_->NextReactor(); + } [[nodiscard]] inline bool Running() const { return Running_; } - inline void AddConnection(uint64_t session_id, std::shared_ptr Connection ) { - std::lock_guard Lock(WSServerMutex_); + inline void AddConnection(uint64_t session_id, + std::shared_ptr Connection) { + std::lock_guard Lock(WSServerMutex_); Sessions_[session_id] = std::move(Connection); } inline std::shared_ptr FindConnection(uint64_t session_id) const { - std::lock_guard Lock(WSServerMutex_); + std::lock_guard Lock(WSServerMutex_); auto Connection = Sessions_.find(session_id); - if(Connection!=end(Sessions_)) + if (Connection != end(Sessions_)) return Connection->second; return nullptr; } - inline bool GetStatistics(const std::string &SerialNumber, std::string & Statistics) const { - return GetStatistics(Utils::SerialNumberToInt(SerialNumber),Statistics); + inline bool GetStatistics(const std::string &SerialNumber, std::string &Statistics) const { + return GetStatistics(Utils::SerialNumberToInt(SerialNumber), Statistics); } - bool GetStatistics(uint64_t SerialNumber, std::string & Statistics) const ; + bool GetStatistics(uint64_t SerialNumber, std::string &Statistics) const; - inline bool GetState(const std::string & SerialNumber, GWObjects::ConnectionState & State) const { + inline bool GetState(const std::string &SerialNumber, + GWObjects::ConnectionState &State) const { return GetState(Utils::SerialNumberToInt(SerialNumber), State); } - bool GetState(uint64_t SerialNumber, GWObjects::ConnectionState & State) const; + bool GetState(uint64_t SerialNumber, GWObjects::ConnectionState &State) const; - inline bool GetHealthcheck(const std::string &SerialNumber, GWObjects::HealthCheck & CheckData) const { + inline bool GetHealthcheck(const std::string &SerialNumber, + GWObjects::HealthCheck &CheckData) const { return GetHealthcheck(Utils::SerialNumberToInt(SerialNumber), CheckData); } - bool GetHealthcheck(uint64_t SerialNumber, GWObjects::HealthCheck & CheckData) const ; + bool GetHealthcheck(uint64_t SerialNumber, GWObjects::HealthCheck &CheckData) const; - bool Connected(uint64_t SerialNumber, GWObjects::DeviceRestrictions & Restrictions) const ; - bool Connected(uint64_t SerialNumber) const ; + bool Connected(uint64_t SerialNumber, GWObjects::DeviceRestrictions &Restrictions) const; + bool Connected(uint64_t SerialNumber) const; - inline bool SendFrame(const std::string & SerialNumber, const std::string & Payload) const { + inline bool SendFrame(const std::string &SerialNumber, const std::string &Payload) const { return SendFrame(Utils::SerialNumberToInt(SerialNumber), Payload); } - bool SendFrame(uint64_t SerialNumber, const std::string & Payload) const ; + bool SendFrame(uint64_t SerialNumber, const std::string &Payload) const; - bool SendRadiusAuthenticationData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size); - bool SendRadiusAccountingData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size); - bool SendRadiusCoAData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size); + bool SendRadiusAuthenticationData(const std::string &SerialNumber, + const unsigned char *buffer, std::size_t size); + bool SendRadiusAccountingData(const std::string &SerialNumber, const unsigned char *buffer, + std::size_t size); + bool SendRadiusCoAData(const std::string &SerialNumber, const unsigned char *buffer, + std::size_t size); void SetSessionDetails(uint64_t connection_id, uint64_t SerialNumber); bool EndSession(uint64_t connection_id, uint64_t serial_number); - void SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime, const std::vector & TelemetryTypes); + void SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, + uint64_t Interval, uint64_t Lifetime, + const std::vector &TelemetryTypes); void StopWebSocketTelemetry(uint64_t RPCID, uint64_t SerialNumber); - void SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime, const std::vector & TelemetryTypes); + void SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, + uint64_t Lifetime, + const std::vector &TelemetryTypes); void StopKafkaTelemetry(uint64_t RPCID, uint64_t SerialNumber); - void GetTelemetryParameters(uint64_t SerialNumber , bool & TelemetryRunning, - uint64_t & TelemetryInterval, - uint64_t & TelemetryWebSocketTimer, - uint64_t & TelemetryKafkaTimer, - uint64_t & TelemetryWebSocketCount, - uint64_t & TelemetryKafkaCount, - uint64_t & TelemetryWebSocketPackets, - uint64_t & TelemetryKafkaPackets); + void GetTelemetryParameters(uint64_t SerialNumber, bool &TelemetryRunning, + uint64_t &TelemetryInterval, uint64_t &TelemetryWebSocketTimer, + uint64_t &TelemetryKafkaTimer, + uint64_t &TelemetryWebSocketCount, + uint64_t &TelemetryKafkaCount, + uint64_t &TelemetryWebSocketPackets, + uint64_t &TelemetryKafkaPackets); - void onGarbageCollecting(Poco::Timer & timer); + void onGarbageCollecting(Poco::Timer &timer); - inline void AverageDeviceStatistics( uint64_t & Connections, uint64_t & AverageConnectionTime, uint64_t & NumberOfConnectingDevices) const { + inline void AverageDeviceStatistics(uint64_t &Connections, uint64_t &AverageConnectionTime, + uint64_t &NumberOfConnectingDevices) const { Connections = NumberOfConnectedDevices_; AverageConnectionTime = AverageDeviceConnectionTime_; NumberOfConnectingDevices = NumberOfConnectingDevices_; } - private: - mutable std::recursive_mutex WSServerMutex_; - std::unique_ptr IssuerCert_; - std::list> WebServers_; - Poco::Net::SocketReactor Reactor_; - Poco::Thread ReactorThread_; - std::string SimulatorId_; - Poco::ThreadPool DeviceConnectionPool_{"ws:dev-pool", 2, 64}; - bool LookAtProvisioning_ = false; - bool UseDefaultConfig_ = true; - bool SimulatorEnabled_=false; - std::unique_ptr Reactor_pool_; - std::atomic_bool Running_=false; + private: + mutable std::recursive_mutex WSServerMutex_; + std::unique_ptr IssuerCert_; + std::list> WebServers_; + Poco::Net::SocketReactor Reactor_; + Poco::Thread ReactorThread_; + std::string SimulatorId_; + Poco::ThreadPool DeviceConnectionPool_{"ws:dev-pool", 2, 64}; + bool LookAtProvisioning_ = false; + bool UseDefaultConfig_ = true; + bool SimulatorEnabled_ = false; + std::unique_ptr Reactor_pool_; + std::atomic_bool Running_ = false; // std::map,bool>> Sessions_; - std::map> Sessions_; - std::map>> SerialNumbers_; - std::atomic_bool AllowSerialNumberMismatch_=true; - std::atomic_uint64_t MismatchDepth_=2; + std::map> Sessions_; + std::map>> SerialNumbers_; + std::atomic_bool AllowSerialNumberMismatch_ = true; + std::atomic_uint64_t MismatchDepth_ = 2; - std::atomic_uint64_t NumberOfConnectedDevices_=0; - std::atomic_uint64_t AverageDeviceConnectionTime_=0; - std::atomic_uint64_t NumberOfConnectingDevices_=0; + std::atomic_uint64_t NumberOfConnectedDevices_ = 0; + std::atomic_uint64_t AverageDeviceConnectionTime_ = 0; + std::atomic_uint64_t NumberOfConnectingDevices_ = 0; - std::vector> Garbage_; + std::vector> Garbage_; - std::unique_ptr> GarbageCollectorCallback_; - Poco::Timer Timer_; - Poco::Thread GarbageCollector_; + std::unique_ptr> GarbageCollectorCallback_; + Poco::Timer Timer_; + Poco::Thread GarbageCollector_; - AP_WS_Server() noexcept: - SubSystemServer("WebSocketServer", "WS-SVR", "ucentral.websocket") { - } + AP_WS_Server() noexcept + : SubSystemServer("WebSocketServer", "WS-SVR", "ucentral.websocket") {} }; inline auto AP_WS_Server() { return AP_WS_Server::instance(); } -} //namespace \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/CapabilitiesCache.h b/src/CapabilitiesCache.h index 779918eb..866a8efb 100644 --- a/src/CapabilitiesCache.h +++ b/src/CapabilitiesCache.h @@ -4,54 +4,53 @@ #pragma once -#include +#include #include #include -#include +#include #include "framework/MicroServiceFuncs.h" -#include "nlohmann/json.hpp" #include "CentralConfig.h" +#include "nlohmann/json.hpp" namespace OpenWifi { const std::string PlatformCacheFileName{"/plat_cache.json"}; const std::string CapabilitiesCacheFileName{"/caps_cache.json"}; - typedef std::map CapabilitiesCache_t; + typedef std::map CapabilitiesCache_t; class CapabilitiesCache { public: - static auto instance() { static auto instance = new CapabilitiesCache; return instance; } inline void Add(const Config::Capabilities &Caps) { - if(Caps.Compatible().empty() || Caps.Platform().empty()) + if (Caps.Compatible().empty() || Caps.Platform().empty()) return; - std::lock_guard G(Mutex_); - if(!PlatformsLoaded_) + std::lock_guard G(Mutex_); + if (!PlatformsLoaded_) LoadPlatforms(); auto P = Poco::toUpper(Caps.Platform()); auto Hint = Platforms_.find(Caps.Compatible()); - if(Hint==Platforms_.end()) { - Platforms_.insert(std::make_pair(Caps.Compatible(),P)); + if (Hint == Platforms_.end()) { + Platforms_.insert(std::make_pair(Caps.Compatible(), P)); SavePlatforms(); - } else if(Hint->second != P) { + } else if (Hint->second != P) { Hint->second = P; SavePlatforms(); } - if(!CapabilitiesLoaded_) + if (!CapabilitiesLoaded_) LoadCapabilities(); auto CapHint = Capabilities_.find(Caps.Compatible()); - if(CapHint==Capabilities_.end()) { - auto C = nlohmann::json::parse(Caps.AsString()); - C.erase("restrictions"); + if (CapHint == Capabilities_.end()) { + auto C = nlohmann::json::parse(Caps.AsString()); + C.erase("restrictions"); Capabilities_[Caps.Compatible()] = nlohmann::json::parse(Caps.AsString()); SaveCapabilities(); } else { @@ -60,48 +59,49 @@ namespace OpenWifi { } } - inline std::string GetPlatform(const std::string & DeviceType) { - std::lock_guard G(Mutex_); + inline std::string GetPlatform(const std::string &DeviceType) { + std::lock_guard G(Mutex_); - if(!PlatformsLoaded_) { + if (!PlatformsLoaded_) { LoadPlatforms(); } auto Hint = Platforms_.find(DeviceType); - if(Hint==Platforms_.end()) + if (Hint == Platforms_.end()) return "AP"; return Hint->second; } - inline nlohmann::json GetCapabilities(const std::string & DeviceType) { - std::lock_guard G(Mutex_); + inline nlohmann::json GetCapabilities(const std::string &DeviceType) { + std::lock_guard G(Mutex_); - if(!CapabilitiesLoaded_) { + if (!CapabilitiesLoaded_) { LoadCapabilities(); } auto Hint = Capabilities_.find(DeviceType); - if(Hint==Capabilities_.end()) + if (Hint == Capabilities_.end()) return nlohmann::json{}; return Hint->second; } - inline const CapabilitiesCache_t & AllCapabilities() { - std::lock_guard G(Mutex_); - if(!CapabilitiesLoaded_) { + inline const CapabilitiesCache_t &AllCapabilities() { + std::lock_guard G(Mutex_); + if (!CapabilitiesLoaded_) { LoadCapabilities(); } return Capabilities_; } private: - std::recursive_mutex Mutex_; - std::atomic_bool PlatformsLoaded_=false; - std::atomic_bool CapabilitiesLoaded_=false; - std::map Platforms_; - CapabilitiesCache_t Capabilities_; - std::string PlatformCacheFileName_{ MicroServiceDataDirectory()+PlatformCacheFileName }; - std::string CapabilitiesCacheFileName_{ MicroServiceDataDirectory()+CapabilitiesCacheFileName }; + std::recursive_mutex Mutex_; + std::atomic_bool PlatformsLoaded_ = false; + std::atomic_bool CapabilitiesLoaded_ = false; + std::map Platforms_; + CapabilitiesCache_t Capabilities_; + std::string PlatformCacheFileName_{MicroServiceDataDirectory() + PlatformCacheFileName}; + std::string CapabilitiesCacheFileName_{MicroServiceDataDirectory() + + CapabilitiesCacheFileName}; inline void LoadPlatforms() { try { @@ -109,11 +109,10 @@ namespace OpenWifi { nlohmann::json cache; i >> cache; - for(const auto &[Type,Platform]:cache.items()) { + for (const auto &[Type, Platform] : cache.items()) { Platforms_[Type] = Platform; } - } catch(...) { - + } catch (...) { } PlatformsLoaded_ = true; } @@ -124,36 +123,35 @@ namespace OpenWifi { nlohmann::json cache(Platforms_); i << cache; } catch (...) { - } } inline void LoadCapabilities() { try { - std::ifstream i(CapabilitiesCacheFileName_, std::ios_base::binary|std::ios_base::in); + std::ifstream i(CapabilitiesCacheFileName_, + std::ios_base::binary | std::ios_base::in); nlohmann::json cache; i >> cache; - for(const auto &[Type,Caps]:cache.items()) { + for (const auto &[Type, Caps] : cache.items()) { Capabilities_[Type] = Caps; } - } catch(...) { - + } catch (...) { } CapabilitiesLoaded_ = true; } inline void SaveCapabilities() { try { - std::ofstream i(CapabilitiesCacheFileName_, std::ios_base::trunc | std::ios_base::out | std::ios_base::binary ); + std::ofstream i(CapabilitiesCacheFileName_, + std::ios_base::trunc | std::ios_base::out | std::ios_base::binary); nlohmann::json cache(Capabilities_); i << cache; } catch (...) { - } } }; - inline auto CapabilitiesCache() { return CapabilitiesCache::instance(); }; + inline auto CapabilitiesCache() { return CapabilitiesCache::instance(); }; -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/CentralConfig.cpp b/src/CentralConfig.cpp index 47538982..ffab6b51 100644 --- a/src/CentralConfig.cpp +++ b/src/CentralConfig.cpp @@ -7,17 +7,17 @@ // #include +#include "Poco/File.h" #include "Poco/JSON/Object.h" #include "Poco/JSON/Parser.h" -#include "Poco/File.h" #include "CentralConfig.h" #include "Daemon.h" namespace OpenWifi::Config { - const static std::string BasicConfig { -R"lit( + const static std::string BasicConfig{ + R"lit( { "interfaces": [ { @@ -150,10 +150,11 @@ R"lit( void Config::SetBasicConfigFile() { try { - Poco::File DefaultConfigFileName{MicroService::instance().DataDir() + "/default_config.json"}; + Poco::File DefaultConfigFileName{MicroService::instance().DataDir() + + "/default_config.json"}; DefaultConfiguration_ = BasicConfig; - std::ofstream OS(DefaultConfigFileName.path(), std::ios::binary | std::ios::trunc ); - std::istringstream IS(DefaultConfiguration_); + std::ofstream OS(DefaultConfigFileName.path(), std::ios::binary | std::ios::trunc); + std::istringstream IS(DefaultConfiguration_); Poco::StreamCopier::copyStream(IS, OS); } catch (...) { DefaultConfiguration_ = BasicConfig; @@ -161,22 +162,23 @@ R"lit( } Config::Config() { - if(DefaultConfiguration_.empty()) + if (DefaultConfiguration_.empty()) Init(); Config_ = DefaultConfiguration_; } void Config::Init() { - if(DefaultConfiguration_.empty()) { + if (DefaultConfiguration_.empty()) { // open the file try { - Poco::File DefaultConfigFileName{MicroService::instance().DataDir()+"/default_config.json"}; + Poco::File DefaultConfigFileName{MicroService::instance().DataDir() + + "/default_config.json"}; if (!DefaultConfigFileName.exists()) { SetBasicConfigFile(); } else { - std::ifstream F(DefaultConfigFileName.path(),std::ios::binary | std::ios::in); + std::ifstream F(DefaultConfigFileName.path(), std::ios::binary | std::ios::in); std::ostringstream C; - Poco::StreamCopier::copyStream(F,C); + Poco::StreamCopier::copyStream(F, C); DefaultConfiguration_ = C.str(); } } catch (...) { @@ -185,101 +187,89 @@ R"lit( } } - bool Config::SetUUID(uint64_t UUID) { - try { - Poco::JSON::Parser Parser; - auto Object = Parser.parse(Config_).extract(); + bool Config::SetUUID(uint64_t UUID) { + try { + Poco::JSON::Parser Parser; + auto Object = Parser.parse(Config_).extract(); Object->set("uuid", UUID); std::ostringstream NewConfig; - Poco::JSON::Stringifier Stringifier; + Poco::JSON::Stringifier Stringifier; Stringifier.condense(Object, NewConfig); Config_ = NewConfig.str(); return true; - } - catch(const Poco::Exception &E) - { - std::cout << __func__ << ": new Configuration failed with " << E.displayText() << std::endl; - } - return false; - } + } catch (const Poco::Exception &E) { + std::cout << __func__ << ": new Configuration failed with " << E.displayText() + << std::endl; + } + return false; + } - bool Config::Valid() { - try { - Poco::JSON::Parser Parser; - auto object = Parser.parse(Config_).extract(); - if(object->has("uuid")) - return true; - return false; - } - catch (...) - { + bool Config::Valid() { + try { + Poco::JSON::Parser Parser; + auto object = Parser.parse(Config_).extract(); + if (object->has("uuid")) + return true; return false; - } - } + } catch (...) { + return false; + } + } Poco::JSON::Object::Ptr Config::to_json() { - Poco::JSON::Parser Parser; - return Parser.parse(Config_).extract(); - } + Poco::JSON::Parser Parser; + return Parser.parse(Config_).extract(); + } std::string Config::Default() { - if(DefaultConfiguration_.empty()) + if (DefaultConfiguration_.empty()) Init(); return DefaultConfiguration_; } -/* std::string Capabilities::Default() { - return std::string(R"lit({"model":{"id":"linksys,ea8300","name":"Linksys EA8300 (Dallas)"}, - "network":{"lan":{"ifname":"eth0","protocol":"static"},"wan":{"ifname":"eth1","protocol":"dhcp"}}, - "switch":{"switch0":{"enable":true,"reset":true,"ports":[{"num":0,"device":"eth0","need_tag":false, - "want_untag":true},{"num":1,"role":"lan"},{"num":2,"role":"lan"},{"num":3,"role":"lan"},{"num":4,"role":"lan"}], - "roles":[{"role":"lan","ports":"1 2 3 4 0","device":"eth0"}]}}, - "wifi":{"soc/40000000.pci/pci0000:00/0000:00:00.0/0000:01:00.0":{"band":["5u"],"ht_capa":6639, - "vht_capa":865696178,"htmode":["HT20","HT40","VHT20","VHT40","VHT80"],"tx_ant":3,"rx_ant":3, - "channels":[100,104,108,112,116,120,124,128,132,136,140,144,149,153,157,161,165]}, - "platform/soc/a000000.wifi":{"band":["2"],"ht_capa":6639,"vht_capa":865687986, - "htmode":["HT20","HT40","VHT20","VHT40","VHT80"],"tx_ant":3,"rx_ant":3,"channels":[1,2,3,4,5,6,7,8,9,10,11]}, - "platform/soc/a800000.wifi":{"band":["5l"],"ht_capa":6639,"vht_capa":865687986,"htmode":["HT20","HT40","VHT20","VHT40","VHT80"], - "tx_ant":3,"rx_ant":3,"channels":[36,40,44,48,52,56,60,64]}}})lit"); - } -*/ + /* std::string Capabilities::Default() { + return std::string(R"lit({"model":{"id":"linksys,ea8300","name":"Linksys EA8300 + (Dallas)"}, + "network":{"lan":{"ifname":"eth0","protocol":"static"},"wan":{"ifname":"eth1","protocol":"dhcp"}}, + "switch":{"switch0":{"enable":true,"reset":true,"ports":[{"num":0,"device":"eth0","need_tag":false, + "want_untag":true},{"num":1,"role":"lan"},{"num":2,"role":"lan"},{"num":3,"role":"lan"},{"num":4,"role":"lan"}], + "roles":[{"role":"lan","ports":"1 2 3 4 0","device":"eth0"}]}}, + "wifi":{"soc/40000000.pci/pci0000:00/0000:00:00.0/0000:01:00.0":{"band":["5u"],"ht_capa":6639, + "vht_capa":865696178,"htmode":["HT20","HT40","VHT20","VHT40","VHT80"],"tx_ant":3,"rx_ant":3, + "channels":[100,104,108,112,116,120,124,128,132,136,140,144,149,153,157,161,165]}, + "platform/soc/a000000.wifi":{"band":["2"],"ht_capa":6639,"vht_capa":865687986, + "htmode":["HT20","HT40","VHT20","VHT40","VHT80"],"tx_ant":3,"rx_ant":3,"channels":[1,2,3,4,5,6,7,8,9,10,11]}, + "platform/soc/a800000.wifi":{"band":["5l"],"ht_capa":6639,"vht_capa":865687986,"htmode":["HT20","HT40","VHT20","VHT40","VHT80"], + "tx_ant":3,"rx_ant":3,"channels":[36,40,44,48,52,56,60,64]}}})lit"); + } + */ - Capabilities::Capabilities(const Poco::JSON::Object::Ptr &Caps) { - try { + Capabilities::Capabilities(const Poco::JSON::Object::Ptr &Caps) { + try { - if(Caps->has("compatible")) + if (Caps->has("compatible")) Compatible_ = Caps->get("compatible").toString(); - if(Caps->has("model")) + if (Caps->has("model")) Model_ = Caps->get("model").toString(); - if(Caps->has("platform")) + if (Caps->has("platform")) Platform_ = Caps->get("platform").toString(); - std::ostringstream OS; - Caps->stringify(OS); - AsString_ = OS.str(); - } - catch ( const Poco::Exception & E ) - { - Daemon()->logger().log(E); - } - } - - const std::string & Capabilities::Compatible() const { - return Compatible_; + std::ostringstream OS; + Caps->stringify(OS); + AsString_ = OS.str(); + } catch (const Poco::Exception &E) { + Daemon()->logger().log(E); + } } - const std::string & Capabilities::Model() const { - return Model_; - } + const std::string &Capabilities::Compatible() const { return Compatible_; } - const std::string & Capabilities::Platform() const { - return Platform_; - } + const std::string &Capabilities::Model() const { return Model_; } - const std::string & Capabilities::AsString() const { - return AsString_; - } + const std::string &Capabilities::Platform() const { return Platform_; } -} // namespace + const std::string &Capabilities::AsString() const { return AsString_; } + +} // namespace OpenWifi::Config diff --git a/src/CentralConfig.h b/src/CentralConfig.h index 1f8e9657..56ae2e4c 100644 --- a/src/CentralConfig.h +++ b/src/CentralConfig.h @@ -8,58 +8,55 @@ #pragma once -#include #include "Poco/JSON/Object.h" +#include namespace OpenWifi::Config { class Config { - public: - explicit Config(const std::string &Config) - :Config_(Config) { - } + public: + explicit Config(const std::string &Config) : Config_(Config) {} - Config(); - bool SetUUID(uint64_t UUID); - [[nodiscard]] bool Valid(); + Config(); + bool SetUUID(uint64_t UUID); + [[nodiscard]] bool Valid(); [[nodiscard]] std::string get() { return Config_; }; [[nodiscard]] std::string Default(); [[nodiscard]] Poco::JSON::Object::Ptr to_json(); - private: - void Init(); - void SetBasicConfigFile(); - inline static std::string DefaultConfiguration_ = ""; - std::string Config_; - }; + private: + void Init(); + void SetBasicConfigFile(); + inline static std::string DefaultConfiguration_ = ""; + std::string Config_; + }; - class Capabilities { - public: - explicit Capabilities(const Poco::JSON::Object::Ptr &Caps); + class Capabilities { + public: + explicit Capabilities(const Poco::JSON::Object::Ptr &Caps); -/* Capabilities() - { - Capabilities_ = Default(); - } + /* Capabilities() + { + Capabilities_ = Default(); + } - static std::string Default(); + static std::string Default(); - [[nodiscard]] const std::string & Get() const { return Capabilities_; }; -*/ + [[nodiscard]] const std::string & Get() const { return Capabilities_; }; + */ - [[nodiscard]] const std::string & Compatible() const; - [[nodiscard]] const std::string & Model() const; - [[nodiscard]] const std::string & Platform() const; - [[nodiscard]] const std::string & AsString() const; + [[nodiscard]] const std::string &Compatible() const; + [[nodiscard]] const std::string &Model() const; + [[nodiscard]] const std::string &Platform() const; + [[nodiscard]] const std::string &AsString() const; - private: - std::string Compatible_; - std::string Model_; + private: + std::string Compatible_; + std::string Model_; std::string Platform_; - std::string AsString_; + std::string AsString_; void Parse(); - }; - -} // namespace + }; +} // namespace OpenWifi::Config diff --git a/src/CommandManager.cpp b/src/CommandManager.cpp index 376db64d..db544052 100644 --- a/src/CommandManager.cpp +++ b/src/CommandManager.cpp @@ -10,11 +10,11 @@ #include "Poco/JSON/Parser.h" -#include "CommandManager.h" #include "AP_WS_Server.h" +#include "CommandManager.h" #include "StorageService.h" -#include "framework/ow_constants.h" #include "framework/MicroServiceFuncs.h" +#include "framework/ow_constants.h" #include "framework/utils.h" using namespace std::chrono_literals; @@ -35,43 +35,50 @@ namespace OpenWifi { std::string SerialNumberStr = Utils::IntToSerialNumber(Resp->SerialNumber_); if (!Payload->has(uCentralProtocol::ID)) { - poco_error(Logger(), fmt::format("({}): Invalid RPC response.", SerialNumberStr)); + poco_error(Logger(), + fmt::format("({}): Invalid RPC response.", SerialNumberStr)); } else { uint64_t ID = Payload->get(uCentralProtocol::ID); - poco_debug(Logger(),fmt::format("({}): Processing {} response.", SerialNumberStr, ID)); + poco_debug(Logger(), fmt::format("({}): Processing {} response.", + SerialNumberStr, ID)); if (ID > 1) { - std::lock_guard Lock(LocalMutex_); + std::lock_guard Lock(LocalMutex_); auto RPC = OutStandingRequests_.find(ID); if (RPC == OutStandingRequests_.end()) { -// std::cout << __LINE__ << std::endl; - poco_debug(Logger(), - fmt::format("({}): RPC {} cannot be found.", SerialNumberStr, ID)); - } else if(RPC->second.SerialNumber != Resp->SerialNumber_) { -// std::cout << __LINE__ << std::endl; - poco_debug(Logger(), - fmt::format("({}): RPC {} serial number mismatch {}!={}.", SerialNumberStr, ID, RPC->second.SerialNumber, Resp->SerialNumber_)); + // std::cout << __LINE__ << std::endl; + poco_debug(Logger(), fmt::format("({}): RPC {} cannot be found.", + SerialNumberStr, ID)); + } else if (RPC->second.SerialNumber != Resp->SerialNumber_) { + // std::cout << __LINE__ << std::endl; + poco_debug( + Logger(), + fmt::format("({}): RPC {} serial number mismatch {}!={}.", + SerialNumberStr, ID, RPC->second.SerialNumber, + Resp->SerialNumber_)); } else { std::shared_ptr TmpRpcEntry; std::chrono::duration rpc_execution_time = std::chrono::high_resolution_clock::now() - RPC->second.submitted; -// std::cout << __LINE__ << std::endl; + // std::cout << __LINE__ << std::endl; poco_debug(Logger(), - fmt::format("({}): Received RPC answer {}. Command={}", - SerialNumberStr, ID, APCommands::to_string(RPC->second.Command))); - if(RPC->second.Command==APCommands::Commands::script) { + fmt::format("({}): Received RPC answer {}. Command={}", + SerialNumberStr, ID, + APCommands::to_string(RPC->second.Command))); + if (RPC->second.Command == APCommands::Commands::script) { CompleteScriptCommand(RPC->second, Payload, rpc_execution_time); - } else if(RPC->second.Command!=APCommands::Commands::telemetry) { - CompleteTelemetryCommand(RPC->second, Payload, rpc_execution_time); + } else if (RPC->second.Command != APCommands::Commands::telemetry) { + CompleteTelemetryCommand(RPC->second, Payload, + rpc_execution_time); } else { - StorageService()->CommandCompleted( - RPC->second.UUID, Payload, rpc_execution_time, true); + StorageService()->CommandCompleted(RPC->second.UUID, Payload, + rpc_execution_time, true); if (RPC->second.rpc_entry) { TmpRpcEntry = RPC->second.rpc_entry; } - RPC->second.State = 0 ; + RPC->second.State = 0; OutStandingRequests_.erase(ID); - if(TmpRpcEntry != nullptr) + if (TmpRpcEntry != nullptr) TmpRpcEntry->set_value(Payload); } } @@ -81,14 +88,16 @@ namespace OpenWifi { } catch (const Poco::Exception &E) { Logger().log(E); } catch (...) { - poco_warning(Logger(),"Exception occurred during run."); + poco_warning(Logger(), "Exception occurred during run."); } NextMsg = ResponseQueue_.waitDequeueNotification(); } - poco_information(Logger(),"RPC Command processor stopping."); - } + poco_information(Logger(), "RPC Command processor stopping."); + } - bool CommandManager::CompleteTelemetryCommand(CommandInfo &Command, [[maybe_unused]] const Poco::JSON::Object::Ptr &Payload, std::chrono::duration rpc_execution_time ) { + bool CommandManager::CompleteTelemetryCommand( + CommandInfo &Command, [[maybe_unused]] const Poco::JSON::Object::Ptr &Payload, + std::chrono::duration rpc_execution_time) { std::shared_ptr TmpRpcEntry; StorageService()->CommandCompleted(Command.UUID, Payload, rpc_execution_time, true); @@ -96,23 +105,25 @@ namespace OpenWifi { if (Command.rpc_entry) { TmpRpcEntry = Command.rpc_entry; } - Command.State = 0 ; + Command.State = 0; OutStandingRequests_.erase(Command.Id); - if(TmpRpcEntry != nullptr) + if (TmpRpcEntry != nullptr) TmpRpcEntry->set_value(Payload); return true; } - bool CommandManager::CompleteScriptCommand(CommandInfo &Command, const Poco::JSON::Object::Ptr &Payload, std::chrono::duration rpc_execution_time) { + bool CommandManager::CompleteScriptCommand( + CommandInfo &Command, const Poco::JSON::Object::Ptr &Payload, + std::chrono::duration rpc_execution_time) { bool Reply = true; std::shared_ptr TmpRpcEntry; if (Command.rpc_entry) { TmpRpcEntry = Command.rpc_entry; } -// std::cout << __LINE__ << " State=" << Command.State << std::endl; - if(Command.State==2) { + // std::cout << __LINE__ << " State=" << Command.State << std::endl; + if (Command.State == 2) { // look at the payload to see if we should continue or not... if (Payload->has("result")) { auto Result = Payload->getObject("result"); @@ -120,45 +131,47 @@ namespace OpenWifi { auto Status = Result->getObject("status"); std::uint64_t Error = Status->get("error"); - if(Error==0) { -// std::cout << __LINE__ << std::endl; - StorageService()->CommandCompleted(Command.UUID, Payload, rpc_execution_time, true); - Command.State = 1 ; + if (Error == 0) { + // std::cout << __LINE__ << std::endl; + StorageService()->CommandCompleted(Command.UUID, Payload, + rpc_execution_time, true); + Command.State = 1; } else { -// std::cout << __LINE__ << std::endl; - StorageService()->CommandCompleted(Command.UUID, Payload, rpc_execution_time, true); + // std::cout << __LINE__ << std::endl; + StorageService()->CommandCompleted(Command.UUID, Payload, + rpc_execution_time, true); std::string ErrorTxt = Status->get("result"); StorageService()->CancelWaitFile(Command.UUID, ErrorTxt); - Command.State = 0 ; + Command.State = 0; } } else { -// std::cout << __LINE__ << std::endl; + // std::cout << __LINE__ << std::endl; } } else { -// std::cout << __LINE__ << std::endl; - Command.State=0; + // std::cout << __LINE__ << std::endl; + Command.State = 0; } - } else if (Command.State==1) { -// std::cout << "Completing script 2 phase commit." << std::endl; + } else if (Command.State == 1) { + // std::cout << "Completing script 2 phase commit." << std::endl; StorageService()->CommandCompleted(Command.UUID, Payload, rpc_execution_time, true); - if(Command.Deferred) { + if (Command.Deferred) { Reply = false; } - Command.State=0; + Command.State = 0; } - if(Command.State==0) { -// std::cout << __LINE__ << " State=" << Command.State << std::endl; + if (Command.State == 0) { + // std::cout << __LINE__ << " State=" << Command.State << std::endl; OutStandingRequests_.erase(Command.Id); } - if(Reply && TmpRpcEntry != nullptr) + if (Reply && TmpRpcEntry != nullptr) TmpRpcEntry->set_value(Payload); return true; } - int CommandManager::Start() { - poco_notice(Logger(),"Starting..."); + int CommandManager::Start() { + poco_notice(Logger(), "Starting..."); commandTimeOut_ = MicroServiceConfigGetInt("command.timeout", 4 * 60 * 60); commandRetry_ = MicroServiceConfigGetInt("command.retry", 120); @@ -167,76 +180,81 @@ namespace OpenWifi { ManagerThread.start(*this); - JanitorCallback_ = std::make_unique>(*this,&CommandManager::onJanitorTimer); - JanitorTimer_.setStartInterval( 10000 ); - JanitorTimer_.setPeriodicInterval(janitorInterval_* 1000); // 1 hours + JanitorCallback_ = std::make_unique>( + *this, &CommandManager::onJanitorTimer); + JanitorTimer_.setStartInterval(10000); + JanitorTimer_.setPeriodicInterval(janitorInterval_ * 1000); // 1 hours JanitorTimer_.start(*JanitorCallback_, MicroServiceTimerPool()); - CommandRunnerCallback_ = std::make_unique>(*this,&CommandManager::onCommandRunnerTimer); - CommandRunnerTimer_.setStartInterval( 10000 ); + CommandRunnerCallback_ = std::make_unique>( + *this, &CommandManager::onCommandRunnerTimer); + CommandRunnerTimer_.setStartInterval(10000); CommandRunnerTimer_.setPeriodicInterval(queueInterval_ * 1000); // 1 hours CommandRunnerTimer_.start(*CommandRunnerCallback_, MicroServiceTimerPool()); - return 0; - } + return 0; + } - void CommandManager::Stop() { - poco_notice(Logger(),"Stopping..."); + void CommandManager::Stop() { + poco_notice(Logger(), "Stopping..."); Running_ = false; JanitorTimer_.stop(); CommandRunnerTimer_.stop(); ResponseQueue_.wakeUpAll(); ManagerThread.wakeUp(); - ManagerThread.join(); - poco_notice(Logger(),"Stopped..."); - } + ManagerThread.join(); + poco_notice(Logger(), "Stopped..."); + } - void CommandManager::WakeUp() { - poco_notice(Logger(),"Waking up..."); - ManagerThread.wakeUp(); - } + void CommandManager::WakeUp() { + poco_notice(Logger(), "Waking up..."); + ManagerThread.wakeUp(); + } - void CommandManager::onJanitorTimer([[maybe_unused]] Poco::Timer & timer) { - std::lock_guard Lock(LocalMutex_); + void CommandManager::onJanitorTimer([[maybe_unused]] Poco::Timer &timer) { + std::lock_guard Lock(LocalMutex_); Utils::SetThreadName("cmd:janitor"); - Poco::Logger & MyLogger = Poco::Logger::get("CMD-MGR-JANITOR"); - std::string TimeOutError("No response."); + Poco::Logger &MyLogger = Poco::Logger::get("CMD-MGR-JANITOR"); + std::string TimeOutError("No response."); auto now = std::chrono::high_resolution_clock::now(); - for(auto request=OutStandingRequests_.begin();request!=OutStandingRequests_.end();) { + for (auto request = OutStandingRequests_.begin(); request != OutStandingRequests_.end();) { std::chrono::duration delta = now - request->second.submitted; - if(delta > 10min) { -// std::cout << __LINE__ << " -->> " << request->second.Id << std::endl; - MyLogger.debug(fmt::format("{}: Command={} for {} Timed out.", - request->second.UUID, + if (delta > 10min) { + // std::cout << __LINE__ << " -->> " << request->second.Id << + //std::endl; + MyLogger.debug(fmt::format("{}: Command={} for {} Timed out.", request->second.UUID, APCommands::to_string(request->second.Command), Utils::IntToSerialNumber(request->second.SerialNumber))); - if( (request->second.Command == APCommands::Commands::script && request->second.Deferred) || + if ((request->second.Command == APCommands::Commands::script && + request->second.Deferred) || (request->second.Command == APCommands::Commands::trace)) { - StorageService()->CancelWaitFile(request->second.UUID, TimeOutError); + StorageService()->CancelWaitFile(request->second.UUID, TimeOutError); } StorageService()->SetCommandTimedOut(request->second.UUID); request = OutStandingRequests_.erase(request); } else { -// std::cout << __LINE__ << " -->> " << request->second.Id << std::endl; + // std::cout << __LINE__ << " -->> " << request->second.Id << + //std::endl; ++request; } } poco_information(MyLogger, - fmt::format("Outstanding-requests {}", OutStandingRequests_.size())); + fmt::format("Outstanding-requests {}", OutStandingRequests_.size())); } bool CommandManager::IsCommandRunning(const std::string &C) { - std::lock_guard Lock(LocalMutex_); - return std::any_of(OutStandingRequests_.begin(),OutStandingRequests_.end(), - [C](const std::pair &r) { return r.second.UUID==C;}); + std::lock_guard Lock(LocalMutex_); + return std::any_of( + OutStandingRequests_.begin(), OutStandingRequests_.end(), + [C](const std::pair &r) { return r.second.UUID == C; }); } void CommandManager::onCommandRunnerTimer([[maybe_unused]] Poco::Timer &timer) { Utils::SetThreadName("cmd:schdlr"); Poco::Logger &MyLogger = Poco::Logger::get("CMD-MGR-SCHEDULER"); - poco_trace(MyLogger,"Scheduler starting."); + poco_trace(MyLogger, "Scheduler starting."); try { @@ -245,28 +263,29 @@ namespace OpenWifi { std::vector Commands; if (StorageService()->GetReadyToExecuteCommands(0, 200, Commands)) { - poco_trace(MyLogger,fmt::format("Scheduler about to process {} commands.", Commands.size())); + poco_trace(MyLogger, + fmt::format("Scheduler about to process {} commands.", Commands.size())); for (auto &Cmd : Commands) { if (!Running_) { - poco_warning(MyLogger,"Scheduler quitting because service is stopping."); + poco_warning(MyLogger, "Scheduler quitting because service is stopping."); break; } - poco_trace( - MyLogger, fmt::format("{}: Serial={} Command={} Starting processing.", - Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); + poco_trace(MyLogger, + fmt::format("{}: Serial={} Command={} Starting processing.", + Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); try { // Skip an already running command - if(IsCommandRunning(Cmd.UUID)) { + if (IsCommandRunning(Cmd.UUID)) { continue; } auto now = Utils::Now(); // 2 hour timeout for commands if ((now - Cmd.Submitted) > commandTimeOut_) { - poco_information( - MyLogger, fmt::format("{}: Serial={} Command={} has expired.", - Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); + poco_information(MyLogger, + fmt::format("{}: Serial={} Command={} has expired.", + Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); StorageService()->SetCommandTimedOut(Cmd.UUID); continue; } @@ -275,53 +294,57 @@ namespace OpenWifi { if (!AP_WS_Server()->Connected(SerialNumberInt)) { poco_trace( MyLogger, - fmt::format( - "{}: Serial={} Command={} Device is not connected.", - Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); + fmt::format("{}: Serial={} Command={} Device is not connected.", + Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); StorageService()->SetCommandLastTry(Cmd.UUID); continue; } - std::string ExecutingUUID; - APCommands::Commands ExecutingCommand=APCommands::Commands::unknown; - if (CommandRunningForDevice(SerialNumberInt, - ExecutingUUID, ExecutingCommand)) { + std::string ExecutingUUID; + APCommands::Commands ExecutingCommand = APCommands::Commands::unknown; + if (CommandRunningForDevice(SerialNumberInt, ExecutingUUID, + ExecutingCommand)) { poco_trace( MyLogger, - fmt::format( - "{}: Serial={} Command={} Device is already busy with command {} (Command={})." - , Cmd.UUID, Cmd.SerialNumber, Cmd.Command, ExecutingUUID, APCommands::to_string(ExecutingCommand))); + fmt::format("{}: Serial={} Command={} Device is already busy " + "with command {} (Command={}).", + Cmd.UUID, Cmd.SerialNumber, Cmd.Command, ExecutingUUID, + APCommands::to_string(ExecutingCommand))); continue; } Poco::JSON::Parser P; bool Sent; - poco_information(MyLogger, fmt::format("{}: Serial={} Command={} Preparing execution.", - Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); + poco_information( + MyLogger, fmt::format("{}: Serial={} Command={} Preparing execution.", + Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); auto Params = P.parse(Cmd.Details).extract(); - auto Result = PostCommandDisk(Next_RPC_ID(), APCommands::to_apcommand(Cmd.Command.c_str()), Cmd.SerialNumber, Cmd.Command, - *Params, Cmd.UUID, Sent); + auto Result = PostCommandDisk( + Next_RPC_ID(), APCommands::to_apcommand(Cmd.Command.c_str()), + Cmd.SerialNumber, Cmd.Command, *Params, Cmd.UUID, Sent); if (Sent) { StorageService()->SetCommandExecuted(Cmd.UUID); poco_debug(MyLogger, - fmt::format("{}: Serial={} Command={} Sent.", - Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); + fmt::format("{}: Serial={} Command={} Sent.", Cmd.UUID, + Cmd.SerialNumber, Cmd.Command)); } else { poco_debug(MyLogger, - fmt::format("{}: Serial={} Command={} Re-queued command.", - Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); + fmt::format("{}: Serial={} Command={} Re-queued command.", + Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); StorageService()->SetCommandLastTry(Cmd.UUID); } } catch (const Poco::Exception &E) { - poco_debug(MyLogger, - fmt::format("{}: Serial={} Command={} Failed. Command marked as completed.", - Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); + poco_debug( + MyLogger, + fmt::format( + "{}: Serial={} Command={} Failed. Command marked as completed.", + Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); MyLogger.log(E); StorageService()->SetCommandExecuted(Cmd.UUID); } catch (...) { - poco_debug(MyLogger, - fmt::format("{}: Serial={} Command={} Hard failure. Command marked as completed.", - Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); + poco_debug(MyLogger, fmt::format("{}: Serial={} Command={} Hard failure. " + "Command marked as completed.", + Cmd.UUID, Cmd.SerialNumber, Cmd.Command)); StorageService()->SetCommandExecuted(Cmd.UUID); } } @@ -329,36 +352,28 @@ namespace OpenWifi { } catch (Poco::Exception &E) { MyLogger.log(E); } catch (...) { - poco_warning(MyLogger,"Exception during command processing."); + poco_warning(MyLogger, "Exception during command processing."); } - poco_trace(MyLogger,"Scheduler done."); + poco_trace(MyLogger, "Scheduler done."); } std::shared_ptr CommandManager::PostCommand( - uint64_t RPC_ID, - APCommands::Commands Command, - const std::string &SerialNumber, - const std::string &CommandStr, - const Poco::JSON::Object &Params, - const std::string &UUID, - bool oneway_rpc, - [[maybe_unused]] bool disk_only, - bool & Sent, - bool rpc, - bool Deferred) { + uint64_t RPC_ID, APCommands::Commands Command, const std::string &SerialNumber, + const std::string &CommandStr, const Poco::JSON::Object &Params, const std::string &UUID, + bool oneway_rpc, [[maybe_unused]] bool disk_only, bool &Sent, bool rpc, bool Deferred) { auto SerialNumberInt = Utils::SerialNumberToInt(SerialNumber); - Sent=false; + Sent = false; - std::stringstream ToSend; + std::stringstream ToSend; - CommandInfo CInfo; + CommandInfo CInfo; CInfo.Id = oneway_rpc ? 1 : RPC_ID; CInfo.SerialNumber = SerialNumberInt; CInfo.Command = Command; CInfo.Deferred = Deferred; CInfo.UUID = UUID; - if(Command == APCommands::Commands::script && Deferred) { + if (Command == APCommands::Commands::script && Deferred) { CInfo.State = 2; } else { CInfo.State = 1; @@ -372,16 +387,17 @@ namespace OpenWifi { Poco::JSON::Stringifier::stringify(CompleteRPC, ToSend); CInfo.rpc_entry = rpc ? std::make_shared() : nullptr; - poco_debug(Logger(), fmt::format("{}: Sending command {} to {}. ID: {}", UUID, CommandStr, SerialNumber, RPC_ID)); - // Do not change the order. It is possible that an RPC completes before it is entered in the map. So we insert it - // first, even if we may need to remove it later upon failure. - if(!oneway_rpc) { + poco_debug(Logger(), fmt::format("{}: Sending command {} to {}. ID: {}", UUID, CommandStr, + SerialNumber, RPC_ID)); + // Do not change the order. It is possible that an RPC completes before it is entered in + //the map. So we insert it first, even if we may need to remove it later upon failure. + if (!oneway_rpc) { std::lock_guard M(Mutex_); OutStandingRequests_[RPC_ID] = CInfo; } - if(AP_WS_Server()->SendFrame(SerialNumber, ToSend.str())) { + if (AP_WS_Server()->SendFrame(SerialNumber, ToSend.str())) { poco_debug(Logger(), fmt::format("{}: Sent command. ID: {}", UUID, RPC_ID)); - Sent=true; + Sent = true; return CInfo.rpc_entry; } else if (!oneway_rpc) { std::lock_guard M(Mutex_); @@ -391,4 +407,4 @@ namespace OpenWifi { poco_warning(Logger(), fmt::format("{}: Failed to send command. ID: {}", UUID, RPC_ID)); return nullptr; } -} // namespace \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/CommandManager.h b/src/CommandManager.h index a63b8eae..b38d308b 100644 --- a/src/CommandManager.h +++ b/src/CommandManager.h @@ -9,242 +9,190 @@ #pragma once #include +#include #include #include -#include -#include #include +#include #include "Poco/JSON/Object.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" -#include "Poco/Timer.h" #include "Poco/Notification.h" #include "Poco/NotificationQueue.h" +#include "Poco/Timer.h" -#include "framework/SubSystemServer.h" #include "fmt/format.h" +#include "framework/SubSystemServer.h" #include "RESTObjects/RESTAPI_GWobjects.h" namespace OpenWifi { - class RPCResponseNotification: public Poco::Notification { + class RPCResponseNotification : public Poco::Notification { public: - RPCResponseNotification(std::uint64_t ser, - Poco::JSON::Object::Ptr pl) : - SerialNumber_(ser), - Payload_(std::move(pl)) - { - - } - std::uint64_t SerialNumber_; - Poco::JSON::Object::Ptr Payload_; + RPCResponseNotification(std::uint64_t ser, Poco::JSON::Object::Ptr pl) + : SerialNumber_(ser), Payload_(std::move(pl)) {} + std::uint64_t SerialNumber_; + Poco::JSON::Object::Ptr Payload_; }; - class CommandManager : public SubSystemServer, Poco::Runnable { - public: - using objtype_t = Poco::JSON::Object::Ptr; - using promise_type_t = std::promise; + public: + using objtype_t = Poco::JSON::Object::Ptr; + using promise_type_t = std::promise; - struct CommandInfo { - std::uint64_t Id=0; - std::uint64_t SerialNumber=0; - APCommands::Commands Command; - std::string UUID; - std::uint64_t State=1; - std::chrono::time_point submitted = std::chrono::high_resolution_clock::now(); - std::shared_ptr rpc_entry; - bool Deferred=false; - }; + struct CommandInfo { + std::uint64_t Id = 0; + std::uint64_t SerialNumber = 0; + APCommands::Commands Command; + std::string UUID; + std::uint64_t State = 1; + std::chrono::time_point submitted = + std::chrono::high_resolution_clock::now(); + std::shared_ptr rpc_entry; + bool Deferred = false; + }; - struct RPCResponse { - std::uint64_t serialNumber; - Poco::JSON::Object::Ptr payload; + struct RPCResponse { + std::uint64_t serialNumber; + Poco::JSON::Object::Ptr payload; - explicit RPCResponse(std::uint64_t ser, Poco::JSON::Object::Ptr pl) - : - serialNumber(ser), - payload(std::move(pl)) { - } - }; + explicit RPCResponse(std::uint64_t ser, Poco::JSON::Object::Ptr pl) + : serialNumber(ser), payload(std::move(pl)) {} + }; - int Start() override; - void Stop() override; - void WakeUp(); - inline void PostCommandResult(const std::string &SerialNumber, Poco::JSON::Object::Ptr Obj) { - ResponseQueue_.enqueueNotification(new RPCResponseNotification(Utils::SerialNumberToInt(SerialNumber),std::move(Obj))); - } + int Start() override; + void Stop() override; + void WakeUp(); + inline void PostCommandResult(const std::string &SerialNumber, + Poco::JSON::Object::Ptr Obj) { + ResponseQueue_.enqueueNotification(new RPCResponseNotification( + Utils::SerialNumberToInt(SerialNumber), std::move(Obj))); + } - std::shared_ptr PostCommandOneWayDisk(uint64_t RPC_ID, - APCommands::Commands Command, - const std::string &SerialNumber, - const std::string &Method, - const Poco::JSON::Object &Params, - const std::string &UUID, - bool & Sent) { - return PostCommand(RPC_ID, - Command, - SerialNumber, - Method, - Params, - UUID, - true, true, Sent , false); - } + std::shared_ptr PostCommandOneWayDisk(uint64_t RPC_ID, + APCommands::Commands Command, + const std::string &SerialNumber, + const std::string &Method, + const Poco::JSON::Object &Params, + const std::string &UUID, bool &Sent) { + return PostCommand(RPC_ID, Command, SerialNumber, Method, Params, UUID, true, true, + Sent, false); + } - std::shared_ptr PostCommandDisk( - uint64_t RPC_ID, - APCommands::Commands Command, - const std::string &SerialNumber, - const std::string &Method, - const Poco::JSON::Object &Params, - const std::string &UUID, - bool & Sent) { - return PostCommand(RPC_ID, - Command, - SerialNumber, - Method, - Params, - UUID, - false, true, Sent, - false ); - } + std::shared_ptr + PostCommandDisk(uint64_t RPC_ID, APCommands::Commands Command, + const std::string &SerialNumber, const std::string &Method, + const Poco::JSON::Object &Params, const std::string &UUID, bool &Sent) { + return PostCommand(RPC_ID, Command, SerialNumber, Method, Params, UUID, false, true, + Sent, false); + } - std::shared_ptr PostCommand( - uint64_t RPC_ID, - APCommands::Commands Command, - const std::string &SerialNumber, - const std::string &Method, - const Poco::JSON::Object &Params, - const std::string &UUID, - bool & Sent, - bool rpc, - bool Deferred) { - return PostCommand(RPC_ID, - Command, - SerialNumber, - Method, - Params, - UUID, - false, - false, Sent, - rpc, - Deferred); - } + std::shared_ptr + PostCommand(uint64_t RPC_ID, APCommands::Commands Command, const std::string &SerialNumber, + const std::string &Method, const Poco::JSON::Object &Params, + const std::string &UUID, bool &Sent, bool rpc, bool Deferred) { + return PostCommand(RPC_ID, Command, SerialNumber, Method, Params, UUID, false, false, + Sent, rpc, Deferred); + } - std::shared_ptr PostCommandOneWay( - uint64_t RPC_ID, - APCommands::Commands Command, - const std::string &SerialNumber, - const std::string &Method, - const Poco::JSON::Object &Params, - const std::string &UUID, - bool & Sent) { - return PostCommand(RPC_ID, - Command, - SerialNumber, - Method, - Params, - UUID, - true, - false, Sent, - false); - } + std::shared_ptr + PostCommandOneWay(uint64_t RPC_ID, APCommands::Commands Command, + const std::string &SerialNumber, const std::string &Method, + const Poco::JSON::Object &Params, const std::string &UUID, bool &Sent) { + return PostCommand(RPC_ID, Command, SerialNumber, Method, Params, UUID, true, false, + Sent, false); + } - bool IsCommandRunning(const std::string &C); + bool IsCommandRunning(const std::string &C); - void run() override; + void run() override; - static auto instance() { - static auto instance_ = new CommandManager; - return instance_; - } + static auto instance() { + static auto instance_ = new CommandManager; + return instance_; + } - inline bool Running() const { return Running_; } - void onJanitorTimer(Poco::Timer & timer); - void onCommandRunnerTimer(Poco::Timer & timer); - inline uint64_t Next_RPC_ID() { return ++Id_; } + inline bool Running() const { return Running_; } + void onJanitorTimer(Poco::Timer &timer); + void onCommandRunnerTimer(Poco::Timer &timer); + inline uint64_t Next_RPC_ID() { return ++Id_; } - void RemovePendingCommand(std::uint64_t Id) { - std::unique_lock Lock(LocalMutex_); - OutStandingRequests_.erase(Id); - } + void RemovePendingCommand(std::uint64_t Id) { + std::unique_lock Lock(LocalMutex_); + OutStandingRequests_.erase(Id); + } - inline bool CommandRunningForDevice(std::uint64_t SerialNumber, std::string & uuid, APCommands::Commands &command) { - std::lock_guard Lock(LocalMutex_); + inline bool CommandRunningForDevice(std::uint64_t SerialNumber, std::string &uuid, + APCommands::Commands &command) { + std::lock_guard Lock(LocalMutex_); - for(const auto &[Request,Command]:OutStandingRequests_) { - if(Command.SerialNumber==SerialNumber) { - uuid = Command.UUID; - command = Command.Command; - return true; - } - } - return false; - } - - inline void ClearQueue(std::uint64_t SerialNumber) { - std::lock_guard Lock(LocalMutex_); - for(auto Request = OutStandingRequests_.begin(); Request != OutStandingRequests_.end() ; ) { - if(Request->second.SerialNumber==SerialNumber) - Request = OutStandingRequests_.erase(Request); - else - ++Request; + for (const auto &[Request, Command] : OutStandingRequests_) { + if (Command.SerialNumber == SerialNumber) { + uuid = Command.UUID; + command = Command.Command; + return true; } } + return false; + } - inline void RemoveCommand(const std::string &UUID) { - std::lock_guard Lock(LocalMutex_); - for(const auto &[Id,Cmd]:OutStandingRequests_) { - if(Cmd.UUID==UUID) { - OutStandingRequests_.erase(Id); - return; - } + inline void ClearQueue(std::uint64_t SerialNumber) { + std::lock_guard Lock(LocalMutex_); + for (auto Request = OutStandingRequests_.begin(); + Request != OutStandingRequests_.end();) { + if (Request->second.SerialNumber == SerialNumber) + Request = OutStandingRequests_.erase(Request); + else + ++Request; + } + } + + inline void RemoveCommand(const std::string &UUID) { + std::lock_guard Lock(LocalMutex_); + for (const auto &[Id, Cmd] : OutStandingRequests_) { + if (Cmd.UUID == UUID) { + OutStandingRequests_.erase(Id); + return; } } + } - inline auto CommandTimeout() const { return commandTimeOut_; } - inline auto CommandRetry() const { return commandRetry_; } + inline auto CommandTimeout() const { return commandTimeOut_; } + inline auto CommandRetry() const { return commandRetry_; } - private: - mutable std::recursive_mutex LocalMutex_; - std::atomic_bool Running_ = false; - Poco::Thread ManagerThread; - std::atomic_uint64_t Id_=3; // do not start @1. We ignore ID=1 & 0 is illegal.. - std::map OutStandingRequests_; - Poco::Timer JanitorTimer_; - std::unique_ptr> JanitorCallback_; - Poco::Timer CommandRunnerTimer_; - std::unique_ptr> CommandRunnerCallback_; - Poco::NotificationQueue ResponseQueue_; - std::uint64_t commandTimeOut_=0; - std::uint64_t commandRetry_=0; - std::uint64_t janitorInterval_=0; - std::uint64_t queueInterval_=0; + private: + mutable std::recursive_mutex LocalMutex_; + std::atomic_bool Running_ = false; + Poco::Thread ManagerThread; + std::atomic_uint64_t Id_ = 3; // do not start @1. We ignore ID=1 & 0 is illegal.. + std::map OutStandingRequests_; + Poco::Timer JanitorTimer_; + std::unique_ptr> JanitorCallback_; + Poco::Timer CommandRunnerTimer_; + std::unique_ptr> CommandRunnerCallback_; + Poco::NotificationQueue ResponseQueue_; + std::uint64_t commandTimeOut_ = 0; + std::uint64_t commandRetry_ = 0; + std::uint64_t janitorInterval_ = 0; + std::uint64_t queueInterval_ = 0; - std::shared_ptr PostCommand( - uint64_t RPCID, - APCommands::Commands Command, - const std::string &SerialNumber, - const std::string &Method, - const Poco::JSON::Object &Params, - const std::string &UUID, - bool oneway_rpc, - bool disk_only, - bool & Sent, - bool rpc_call, - bool Deferred=false); + std::shared_ptr + PostCommand(uint64_t RPCID, APCommands::Commands Command, const std::string &SerialNumber, + const std::string &Method, const Poco::JSON::Object &Params, + const std::string &UUID, bool oneway_rpc, bool disk_only, bool &Sent, + bool rpc_call, bool Deferred = false); - bool CompleteScriptCommand(CommandInfo &Command, const Poco::JSON::Object::Ptr &Payload, std::chrono::duration rpc_execution_time); - bool CompleteTelemetryCommand(CommandInfo &Command, const Poco::JSON::Object::Ptr &Payload, std::chrono::duration rpc_execution_time); + bool CompleteScriptCommand(CommandInfo &Command, const Poco::JSON::Object::Ptr &Payload, + std::chrono::duration rpc_execution_time); + bool CompleteTelemetryCommand(CommandInfo &Command, const Poco::JSON::Object::Ptr &Payload, + std::chrono::duration rpc_execution_time); - CommandManager() noexcept: - SubSystemServer("CommandManager", "CMD-MGR", "command.manager") { - } + CommandManager() noexcept + : SubSystemServer("CommandManager", "CMD-MGR", "command.manager") {} }; inline auto CommandManager() { return CommandManager::instance(); } -} // namespace - +} // namespace OpenWifi diff --git a/src/ConfigurationCache.h b/src/ConfigurationCache.h index 4f6af0a1..f9717487 100644 --- a/src/ConfigurationCache.h +++ b/src/ConfigurationCache.h @@ -5,14 +5,13 @@ #pragma once #include -#include #include +#include namespace OpenWifi { class ConfigurationCache { public: - - static ConfigurationCache & instance() { + static ConfigurationCache &instance() { static ConfigurationCache instance; return instance; } @@ -20,30 +19,30 @@ namespace OpenWifi { inline uint64_t CurrentConfig(uint64_t SerialNumber) { std::lock_guard G(Mutex_); const auto Hint = Cache_.find(SerialNumber); - if(Hint==end(Cache_)) + if (Hint == end(Cache_)) return 0; return Hint->second; } inline void Add(uint64_t SerialNumber, uint64_t Id) { - std::lock_guard G(Mutex_); - Cache_[SerialNumber]=Id; + std::lock_guard G(Mutex_); + Cache_[SerialNumber] = Id; } private: - std::recursive_mutex Mutex_; - std::map Cache_; + std::recursive_mutex Mutex_; + std::map Cache_; }; inline uint64_t GetCurrentConfigurationID(uint64_t SerialNumber) { return ConfigurationCache::instance().CurrentConfig(SerialNumber); } - inline void SetCurrentConfigurationID(const std::string & SerialNumber, uint64_t ID) { + inline void SetCurrentConfigurationID(const std::string &SerialNumber, uint64_t ID) { return ConfigurationCache::instance().Add(Utils::SerialNumberToInt(SerialNumber), ID); } inline void SetCurrentConfigurationID(uint64_t SerialNumber, uint64_t ID) { return ConfigurationCache::instance().Add(SerialNumber, ID); } -} +} // namespace OpenWifi diff --git a/src/Daemon.cpp b/src/Daemon.cpp index 71155d31..bfa41856 100644 --- a/src/Daemon.cpp +++ b/src/Daemon.cpp @@ -6,11 +6,10 @@ // Arilia Wireless Inc. // -#include "Poco/Util/Application.h" -#include "Poco/Util/Option.h" #include "Poco/Environment.h" #include "Poco/Net/SSLManager.h" - +#include "Poco/Util/Application.h" +#include "Poco/Util/Option.h" #include "AP_WS_Server.h" #include "CommandManager.h" @@ -19,107 +18,90 @@ #include "FindCountry.h" #include "OUIServer.h" #include "RADIUS_proxy_server.h" +#include "ScriptManager.h" #include "SerialNumberCache.h" +#include "SignatureMgr.h" #include "StorageArchiver.h" #include "StorageService.h" #include "TelemetryStream.h" +#include "UI_GW_WebSocketNotifications.h" #include "VenueBroadcaster.h" #include "framework/ConfigurationValidator.h" -#include "rttys/RTTYS_server.h" #include "framework/UI_WebSocketClientServer.h" -#include "UI_GW_WebSocketNotifications.h" -#include "ScriptManager.h" -#include "SignatureMgr.h" +#include "rttys/RTTYS_server.h" namespace OpenWifi { class Daemon *Daemon::instance() { - static Daemon instance(vDAEMON_PROPERTIES_FILENAME, - vDAEMON_ROOT_ENV_VAR, - vDAEMON_CONFIG_ENV_VAR, - vDAEMON_APP_NAME, - vDAEMON_BUS_TIMER, - SubSystemVec{ - StorageService(), - SerialNumberCache(), - ConfigurationValidator(), - UI_WebSocketClientServer(), - OUIServer(), - FindCountryFromIP(), - CommandManager(), - FileUploader(), - StorageArchiver(), - TelemetryStream(), - RTTYS_server(), - RADIUS_proxy_server(), - VenueBroadcaster(), - ScriptManager(), - SignatureManager(), - AP_WS_Server() - }); - return &instance; + static Daemon instance( + vDAEMON_PROPERTIES_FILENAME, vDAEMON_ROOT_ENV_VAR, vDAEMON_CONFIG_ENV_VAR, + vDAEMON_APP_NAME, vDAEMON_BUS_TIMER, + SubSystemVec{StorageService(), SerialNumberCache(), ConfigurationValidator(), + UI_WebSocketClientServer(), OUIServer(), FindCountryFromIP(), + CommandManager(), FileUploader(), StorageArchiver(), TelemetryStream(), + RTTYS_server(), RADIUS_proxy_server(), VenueBroadcaster(), ScriptManager(), + SignatureManager(), AP_WS_Server()}); + return &instance; } - static const std::vector> DefaultDeviceTypes{ - {"cig_wf160d","AP"}, - {"cig_wf188","AP"}, - {"cig_wf188n","AP"}, - {"cig_wf194c","AP"}, - {"cig_wf194c4","AP"}, - {"edgecore_eap101","AP"}, - {"edgecore_eap102","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"}, - {"indio_um-305ac","AP"}, - {"linksys_e8450-ubi","AP"}, - {"linksys_ea6350","AP"}, - {"linksys_ea6350-v4","AP"}, - {"linksys_ea8300","AP"}, - {"mikrotik_nand","AP"}, - {"tp-link_ec420-g1","AP"}, - {"tplink_cpe210_v3","AP"}, - {"tplink_cpe510_v3","AP"}, - {"tplink_eap225_outdoor_v1","AP"}, - {"tplink_ec420","AP"}, - {"tplink_ex227","AP"}, - {"tplink_ex228","AP"}, - {"tplink_ex447","AP"}, - {"wallys_dr40x9","AP"} - }; - + static const std::vector> DefaultDeviceTypes{ + {"cig_wf160d", "AP"}, + {"cig_wf188", "AP"}, + {"cig_wf188n", "AP"}, + {"cig_wf194c", "AP"}, + {"cig_wf194c4", "AP"}, + {"edgecore_eap101", "AP"}, + {"edgecore_eap102", "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"}, + {"indio_um-305ac", "AP"}, + {"linksys_e8450-ubi", "AP"}, + {"linksys_ea6350", "AP"}, + {"linksys_ea6350-v4", "AP"}, + {"linksys_ea8300", "AP"}, + {"mikrotik_nand", "AP"}, + {"tp-link_ec420-g1", "AP"}, + {"tplink_cpe210_v3", "AP"}, + {"tplink_cpe510_v3", "AP"}, + {"tplink_eap225_outdoor_v1", "AP"}, + {"tplink_ec420", "AP"}, + {"tplink_ex227", "AP"}, + {"tplink_ex228", "AP"}, + {"tplink_ex447", "AP"}, + {"wallys_dr40x9", "AP"}}; + void Daemon::PostInitialization([[maybe_unused]] Poco::Util::Application &self) { - AutoProvisioning_ = config().getBool("openwifi.autoprovisioning",false); - DeviceTypes_ = DefaultDeviceTypes; + AutoProvisioning_ = config().getBool("openwifi.autoprovisioning", false); + DeviceTypes_ = DefaultDeviceTypes; WebSocketProcessor_ = std::make_unique(logger()); - } + } - [[nodiscard]] std::string Daemon::IdentifyDevice(const std::string & Id ) const { - for(const auto &[DeviceType,Type]:DeviceTypes_) - { - if(Id == DeviceType) - return Type; - } - return "AP"; - } + [[nodiscard]] std::string Daemon::IdentifyDevice(const std::string &Id) const { + for (const auto &[DeviceType, Type] : DeviceTypes_) { + if (Id == DeviceType) + return Type; + } + return "AP"; + } void DaemonPostInitialization(Poco::Util::Application &self) { Daemon()->PostInitialization(self); GWWebSocketNotifications::Register(); } -} +} // namespace OpenWifi int main(int argc, char **argv) { int ExitCode; try { Poco::Net::SSLManager::instance().initializeServer(nullptr, nullptr, nullptr); auto App = OpenWifi::Daemon::instance(); - ExitCode = App->run(argc, argv); + ExitCode = App->run(argc, argv); Poco::Net::SSLManager::instance().shutdown(); } catch (Poco::Exception &exc) { ExitCode = Poco::Util::Application::EXIT_SOFTWARE; diff --git a/src/Daemon.h b/src/Daemon.h index 2a62d1b7..4da6677c 100644 --- a/src/Daemon.h +++ b/src/Daemon.h @@ -9,50 +9,47 @@ #pragma once #include -#include #include -#include +#include #include +#include -#include "framework/MicroServiceNames.h" #include "framework/MicroService.h" +#include "framework/MicroServiceNames.h" #include "Dashboard.h" -#include "framework/OpenWifiTypes.h" #include "GwWebSocketClient.h" +#include "framework/OpenWifiTypes.h" namespace OpenWifi { - [[maybe_unused]] static const char * vDAEMON_PROPERTIES_FILENAME = "owgw.properties"; - [[maybe_unused]] static const char * vDAEMON_ROOT_ENV_VAR = "OWGW_ROOT"; - [[maybe_unused]] static const char * vDAEMON_CONFIG_ENV_VAR = "OWGW_CONFIG"; - [[maybe_unused]] static const char * vDAEMON_APP_NAME = uSERVICE_GATEWAY.c_str(); + [[maybe_unused]] static const char *vDAEMON_PROPERTIES_FILENAME = "owgw.properties"; + [[maybe_unused]] static const char *vDAEMON_ROOT_ENV_VAR = "OWGW_ROOT"; + [[maybe_unused]] static const char *vDAEMON_CONFIG_ENV_VAR = "OWGW_CONFIG"; + [[maybe_unused]] static const char *vDAEMON_APP_NAME = uSERVICE_GATEWAY.c_str(); [[maybe_unused]] static const uint64_t vDAEMON_BUS_TIMER = 10000; - class Daemon : public MicroService { - public: - explicit Daemon(const std::string & PropFile, - const std::string & RootEnv, - const std::string & ConfigEnv, - const std::string & AppName, - uint64_t BusTimer, - const SubSystemVec & SubSystems) : - MicroService( PropFile, RootEnv, ConfigEnv, AppName, BusTimer, SubSystems) {}; + class Daemon : public MicroService { + public: + explicit Daemon(const std::string &PropFile, const std::string &RootEnv, + const std::string &ConfigEnv, const std::string &AppName, uint64_t BusTimer, + const SubSystemVec &SubSystems) + : MicroService(PropFile, RootEnv, ConfigEnv, AppName, BusTimer, SubSystems){}; - bool AutoProvisioning() const { return AutoProvisioning_ ; } - [[nodiscard]] std::string IdentifyDevice(const std::string & Compatible) const; - static Daemon *instance(); - inline DeviceDashboard & GetDashboard() { return DB_; } - Poco::Logger & Log() { return Poco::Logger::get(AppName()); } - void PostInitialization(Poco::Util::Application &self); - private: - bool AutoProvisioning_ = false; - std::vector> DeviceTypes_; - DeviceDashboard DB_; - std::unique_ptr WebSocketProcessor_; - }; + bool AutoProvisioning() const { return AutoProvisioning_; } + [[nodiscard]] std::string IdentifyDevice(const std::string &Compatible) const; + static Daemon *instance(); + inline DeviceDashboard &GetDashboard() { return DB_; } + Poco::Logger &Log() { return Poco::Logger::get(AppName()); } + void PostInitialization(Poco::Util::Application &self); - inline Daemon * Daemon() { return Daemon::instance(); } + private: + bool AutoProvisioning_ = false; + std::vector> DeviceTypes_; + DeviceDashboard DB_; + std::unique_ptr WebSocketProcessor_; + }; + + inline Daemon *Daemon() { return Daemon::instance(); } void DaemonPostInitialization(Poco::Util::Application &self); -} - +} // namespace OpenWifi diff --git a/src/Dashboard.cpp b/src/Dashboard.cpp index fea83b86..43cff93e 100644 --- a/src/Dashboard.cpp +++ b/src/Dashboard.cpp @@ -8,24 +8,24 @@ namespace OpenWifi { - bool DeviceDashboard::Get(GWObjects::Dashboard &D, Poco::Logger & Logger) { + bool DeviceDashboard::Get(GWObjects::Dashboard &D, Poco::Logger &Logger) { uint64_t Now = Utils::Now(); - if(!ValidDashboard_ || LastRun_==0 || (Now-LastRun_)>120) { + if (!ValidDashboard_ || LastRun_ == 0 || (Now - LastRun_) > 120) { Generate(D, Logger); } else { - std::lock_guard G(DataMutex_); + std::lock_guard G(DataMutex_); D = DB_; } return ValidDashboard_; }; - void DeviceDashboard::Generate(GWObjects::Dashboard &D, Poco::Logger & Logger ) { + void DeviceDashboard::Generate(GWObjects::Dashboard &D, Poco::Logger &Logger) { if (GeneratingDashboard_.load()) { // std::cout << "Trying to generate dashboard but already being generated" << std::endl; - while(GeneratingDashboard_.load()) { + while (GeneratingDashboard_.load()) { Poco::Thread::trySleep(100); } - std::lock_guard G(DataMutex_); + std::lock_guard G(DataMutex_); D = DB_; } else { GeneratingDashboard_ = true; @@ -33,19 +33,18 @@ namespace OpenWifi { try { // std::cout << "Generating dashboard." << std::endl; poco_information(Logger, "DASHBOARD: Generating a new dashboard."); - GWObjects::Dashboard NewData; + GWObjects::Dashboard NewData; StorageService()->AnalyzeCommands(NewData.commands); StorageService()->AnalyzeDevices(NewData); LastRun_ = Utils::Now(); NewData.snapshot = LastRun_; D = NewData; - std::lock_guard G(DataMutex_); + std::lock_guard G(DataMutex_); DB_ = NewData; - ValidDashboard_=true; - } catch(...) { - + ValidDashboard_ = true; + } catch (...) { } GeneratingDashboard_ = false; } } -} +} // namespace OpenWifi diff --git a/src/Dashboard.h b/src/Dashboard.h index 238fea53..fbb865a0 100644 --- a/src/Dashboard.h +++ b/src/Dashboard.h @@ -6,22 +6,22 @@ #include +#include "Poco/Logger.h" #include "RESTObjects//RESTAPI_GWobjects.h" #include "framework/OpenWifiTypes.h" -#include "Poco/Logger.h" namespace OpenWifi { class DeviceDashboard { public: - bool Get(GWObjects::Dashboard &D, Poco::Logger & Logger); + bool Get(GWObjects::Dashboard &D, Poco::Logger &Logger); + private: - std::mutex DataMutex_; - volatile std::atomic_bool GeneratingDashboard_=false; - volatile bool ValidDashboard_=false; - GWObjects::Dashboard DB_; - uint64_t LastRun_=0; + std::mutex DataMutex_; + volatile std::atomic_bool GeneratingDashboard_ = false; + volatile bool ValidDashboard_ = false; + GWObjects::Dashboard DB_; + uint64_t LastRun_ = 0; - void Generate(GWObjects::Dashboard &D, Poco::Logger & Logger); + void Generate(GWObjects::Dashboard &D, Poco::Logger &Logger); }; -} - +} // namespace OpenWifi diff --git a/src/FileUploader.cpp b/src/FileUploader.cpp index 2b703f3a..26a61874 100644 --- a/src/FileUploader.cpp +++ b/src/FileUploader.cpp @@ -8,16 +8,16 @@ #include -#include "Poco/Net/HTTPServerParams.h" -#include "Poco/Net/HTTPServerResponse.h" -#include "Poco/DynamicAny.h" -#include "Poco/Net/PartHandler.h" -#include "Poco/Net/MessageHeader.h" -#include "Poco/Net/MultipartReader.h" #include "Poco/CountingStream.h" -#include "Poco/StreamCopier.h" +#include "Poco/DynamicAny.h" #include "Poco/Exception.h" #include "Poco/File.h" +#include "Poco/Net/HTTPServerParams.h" +#include "Poco/Net/HTTPServerResponse.h" +#include "Poco/Net/MessageHeader.h" +#include "Poco/Net/MultipartReader.h" +#include "Poco/Net/PartHandler.h" +#include "Poco/StreamCopier.h" #include "Poco/StringTokenizer.h" #include "framework/MicroServiceFuncs.h" @@ -30,25 +30,25 @@ namespace OpenWifi { - static const std::string URI_BASE{"/v1/upload/"}; + static const std::string URI_BASE{"/v1/upload/"}; - int FileUploader::Start() { - poco_notice(Logger(),"Starting."); + int FileUploader::Start() { + poco_notice(Logger(), "Starting."); - Poco::File UploadsDir(MicroServiceConfigPath("openwifi.fileuploader.path","/tmp")); - Path_ = UploadsDir.path(); - if(!UploadsDir.exists()) { - try { - UploadsDir.createDirectory(); - } catch (const Poco::Exception &E) { - Logger().log(E); - Path_ = "/tmp"; - } - } + Poco::File UploadsDir(MicroServiceConfigPath("openwifi.fileuploader.path", "/tmp")); + Path_ = UploadsDir.path(); + if (!UploadsDir.exists()) { + try { + UploadsDir.createDirectory(); + } catch (const Poco::Exception &E) { + Logger().log(E); + Path_ = "/tmp"; + } + } - for(const auto & Svr: ConfigServersList_) { - if(MicroServiceNoAPISecurity()) { - poco_notice(Logger(), fmt::format("Starting: {}:{}",Svr.Address(),Svr.Port())); + for (const auto &Svr : ConfigServersList_) { + if (MicroServiceNoAPISecurity()) { + poco_notice(Logger(), fmt::format("Starting: {}:{}", Svr.Address(), Svr.Port())); auto Sock{Svr.CreateSocket(Logger())}; @@ -66,7 +66,7 @@ namespace OpenWifi { } else { FullName_ = TmpName + URI_BASE; } - poco_information(Logger(),fmt::format("Uploader URI base is '{}'", FullName_)); + poco_information(Logger(), fmt::format("Uploader URI base is '{}'", FullName_)); } auto NewServer = std::make_unique( @@ -77,7 +77,7 @@ namespace OpenWifi { } else { std::string l{"Starting: " + Svr.Address() + ":" + std::to_string(Svr.Port()) + " key:" + Svr.KeyFile() + " cert:" + Svr.CertFile()}; - poco_information(Logger(),l); + poco_information(Logger(), l); auto Sock{Svr.CreateSecureSocket(Logger())}; @@ -107,66 +107,62 @@ namespace OpenWifi { NewServer->start(); Servers_.push_back(std::move(NewServer)); } - } + } - MaxSize_ = 1000 * MicroServiceConfigGetInt("openwifi.fileuploader.maxsize", 10000); + MaxSize_ = 1000 * MicroServiceConfigGetInt("openwifi.fileuploader.maxsize", 10000); - return 0; - } + return 0; + } void FileUploader::reinitialize([[maybe_unused]] Poco::Util::Application &self) { MicroServiceLoadConfigurationFile(); - poco_information(Logger(),"Reinitializing."); + poco_information(Logger(), "Reinitializing."); Stop(); Start(); } - const std::string & FileUploader::FullName() { - return FullName_; - } + const std::string &FileUploader::FullName() { return FullName_; } - // if you pass in an empty UUID, it will just clean the list and not add it. - bool FileUploader::AddUUID( const std::string & UUID, std::chrono::seconds WaitTimeInSeconds, const std::string &Type) { - std::lock_guard Guard(Mutex_); + // if you pass in an empty UUID, it will just clean the list and not add it. + bool FileUploader::AddUUID(const std::string &UUID, std::chrono::seconds WaitTimeInSeconds, + const std::string &Type) { + std::lock_guard Guard(Mutex_); - uint64_t now = Utils::Now(); - auto Func=[now](const UploadId &I) -> bool { - return (now > I.Expires); - }; - OutStandingUploads_.erase(std::remove_if(OutStandingUploads_.begin(),OutStandingUploads_.end(),Func),OutStandingUploads_.end()); + uint64_t now = Utils::Now(); + auto Func = [now](const UploadId &I) -> bool { return (now > I.Expires); }; + OutStandingUploads_.erase( + std::remove_if(OutStandingUploads_.begin(), OutStandingUploads_.end(), Func), + OutStandingUploads_.end()); OutStandingUploads_.emplace_back(UploadId{UUID, now + WaitTimeInSeconds.count(), Type}); - return true; - } + return true; + } - bool FileUploader::ValidRequest(const std::string &UUID) { - std::lock_guard Guard(Mutex_); - auto Func = [UUID](const UploadId &P) -> bool { - return (P.UUID==UUID); - }; - return std::find_if(OutStandingUploads_.begin(), OutStandingUploads_.end(), Func) != end(OutStandingUploads_); - } + bool FileUploader::ValidRequest(const std::string &UUID) { + std::lock_guard Guard(Mutex_); + auto Func = [UUID](const UploadId &P) -> bool { return (P.UUID == UUID); }; + return std::find_if(OutStandingUploads_.begin(), OutStandingUploads_.end(), Func) != + end(OutStandingUploads_); + } - void FileUploader::RemoveRequest(const std::string &UUID) { - std::lock_guard Guard(Mutex_); - auto Func = [UUID](const UploadId &P) -> bool { - return (P.UUID==UUID); - }; - OutStandingUploads_.erase(std::remove_if(OutStandingUploads_.begin(),OutStandingUploads_.end(),Func),OutStandingUploads_.end()); - } + void FileUploader::RemoveRequest(const std::string &UUID) { + std::lock_guard Guard(Mutex_); + auto Func = [UUID](const UploadId &P) -> bool { return (P.UUID == UUID); }; + OutStandingUploads_.erase( + std::remove_if(OutStandingUploads_.begin(), OutStandingUploads_.end(), Func), + OutStandingUploads_.end()); + } class FileUploaderPartHandler2 : public Poco::Net::PartHandler { public: - FileUploaderPartHandler2(std::string Id, Poco::Logger &Logger, std::stringstream & ofs) : - Id_(std::move(Id)), - Logger_(Logger), - OutputStream_(ofs){ - } + FileUploaderPartHandler2(std::string Id, Poco::Logger &Logger, std::stringstream &ofs) + : Id_(std::move(Id)), Logger_(Logger), OutputStream_(ofs) {} void handlePart(const Poco::Net::MessageHeader &Header, std::istream &Stream) { FileType_ = Header.get(RESTAPI::Protocol::CONTENTTYPE, RESTAPI::Protocol::UNSPECIFIED); if (Header.has(RESTAPI::Protocol::CONTENTDISPOSITION)) { std::string Disposition; Poco::Net::NameValueCollection Parameters; - Poco::Net::MessageHeader::splitParameters(Header[RESTAPI::Protocol::CONTENTDISPOSITION], Disposition, Parameters); + Poco::Net::MessageHeader::splitParameters( + Header[RESTAPI::Protocol::CONTENTDISPOSITION], Disposition, Parameters); Name_ = Parameters.get(RESTAPI::Protocol::NAME, RESTAPI::Protocol::UNNAMED); } Poco::CountingInputStream InputStream(Stream); @@ -178,33 +174,30 @@ namespace OpenWifi { [[nodiscard]] std::string &ContentType() { return FileType_; } private: - uint64_t Length_ = 0; - std::string FileType_; - std::string Name_; - std::string Id_; - Poco::Logger &Logger_; + uint64_t Length_ = 0; + std::string FileType_; + std::string Name_; + std::string Id_; + Poco::Logger &Logger_; std::stringstream &OutputStream_; - inline Poco::Logger & Logger() { return Logger_; }; + inline Poco::Logger &Logger() { return Logger_; }; }; - class FormRequestHandler: public Poco::Net::HTTPRequestHandler - { - public: - explicit FormRequestHandler(std::string UUID, Poco::Logger & L, const std::string &Type): - UUID_(std::move(UUID)), - Logger_(L), - Type_(Type) - { - } + class FormRequestHandler : public Poco::Net::HTTPRequestHandler { + public: + explicit FormRequestHandler(std::string UUID, Poco::Logger &L, const std::string &Type) + : UUID_(std::move(UUID)), Logger_(L), Type_(Type) {} - void handleRequest(Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) final { + void handleRequest(Poco::Net::HTTPServerRequest &Request, + Poco::Net::HTTPServerResponse &Response) final { Utils::SetThreadName("FileUploader"); const auto ContentType = Request.getContentType(); - const auto Tokens = Poco::StringTokenizer(ContentType,";",Poco::StringTokenizer::TOK_TRIM); + const auto Tokens = + Poco::StringTokenizer(ContentType, ";", Poco::StringTokenizer::TOK_TRIM); - poco_debug(Logger(),fmt::format("{}: Preparing to upload trace file.",UUID_)); + poco_debug(Logger(), fmt::format("{}: Preparing to upload trace file.", UUID_)); Poco::JSON::Object Answer; try { @@ -229,8 +222,9 @@ namespace OpenWifi { Poco::StreamCopier::copyStream(Reader.stream(), FileContent); Answer.set("filename", UUID_); Answer.set("error", 0); - poco_debug(Logger(),fmt::format("{}: File uploaded.", UUID_)); - StorageService()->AttachFileDataToCommand(UUID_, FileContent, Type_); + poco_debug(Logger(), fmt::format("{}: File uploaded.", UUID_)); + StorageService()->AttachFileDataToCommand(UUID_, FileContent, + Type_); std::ostream &ResponseStream = Response.send(); Poco::JSON::Stringifier::stringify(Answer, ResponseStream); return; @@ -247,10 +241,10 @@ namespace OpenWifi { } catch (const Poco::Exception &E) { Logger().log(E); } catch (...) { - poco_debug(Logger(),"Exception while receiving trace file."); + poco_debug(Logger(), "Exception while receiving trace file."); } - poco_debug(Logger(),fmt::format("{}: Failed to upload trace file.",UUID_)); + poco_debug(Logger(), fmt::format("{}: Failed to upload trace file.", UUID_)); std::string Error{"Trace file rejected"}; StorageService()->CancelWaitFile(UUID_, Error); Answer.set("filename", UUID_); @@ -261,48 +255,50 @@ namespace OpenWifi { Poco::JSON::Stringifier::stringify(Answer, ResponseStream); } - inline Poco::Logger & Logger() { return Logger_; } + inline Poco::Logger &Logger() { return Logger_; } - private: - std::string UUID_; - Poco::Logger & Logger_; - std::string Type_; - }; + private: + std::string UUID_; + Poco::Logger &Logger_; + std::string Type_; + }; - Poco::Net::HTTPRequestHandler *FileUpLoaderRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest & Request) { + Poco::Net::HTTPRequestHandler *FileUpLoaderRequestHandlerFactory::createRequestHandler( + const Poco::Net::HTTPServerRequest &Request) { - poco_debug(Logger(),fmt::format("REQUEST({}): {} {}", Utils::FormatIPv6(Request.clientAddress().toString()), Request.getMethod(), Request.getURI())); + poco_debug(Logger(), fmt::format("REQUEST({}): {} {}", + Utils::FormatIPv6(Request.clientAddress().toString()), + Request.getMethod(), Request.getURI())); - if(Request.getMethod()!=Poco::Net::HTTPRequest::HTTP_POST || - Request.getURI().size()<(URI_BASE.size()+36)) { - poco_warning(Logger(),fmt::format("ILLEGAL-REQUEST({}): {} {}. Dropped.", Utils::FormatIPv6(Request.clientAddress().toString()), Request.getMethod(), Request.getURI())); + if (Request.getMethod() != Poco::Net::HTTPRequest::HTTP_POST || + Request.getURI().size() < (URI_BASE.size() + 36)) { + poco_warning(Logger(), + fmt::format("ILLEGAL-REQUEST({}): {} {}. Dropped.", + Utils::FormatIPv6(Request.clientAddress().toString()), + Request.getMethod(), Request.getURI())); return nullptr; } - // The UUID should be after the /v1/upload/ part... - auto UUIDLocation = Request.getURI().find_first_of(URI_BASE); + // The UUID should be after the /v1/upload/ part... + auto UUIDLocation = Request.getURI().find_first_of(URI_BASE); - if( UUIDLocation != std::string::npos ) - { - auto UUID = Request.getURI().substr(UUIDLocation+URI_BASE.size()); + if (UUIDLocation != std::string::npos) { + auto UUID = Request.getURI().substr(UUIDLocation + URI_BASE.size()); - FileUploader::UploadId E; - if(FileUploader()->Find(UUID,E)) - { + FileUploader::UploadId E; + if (FileUploader()->Find(UUID, E)) { FileUploader()->RemoveRequest(UUID); - return new FormRequestHandler(UUID,Logger(),E.Type); - } - else - { - poco_warning(Logger(),fmt::format("Unknown UUID={}",UUID)); - } - } - return nullptr; - } + return new FormRequestHandler(UUID, Logger(), E.Type); + } else { + poco_warning(Logger(), fmt::format("Unknown UUID={}", UUID)); + } + } + return nullptr; + } - bool FileUploader::Find(const std::string &UUID, UploadId &V) { - std::lock_guard G(Mutex_); - for(const auto &E:OutStandingUploads_) { + bool FileUploader::Find(const std::string &UUID, UploadId &V) { + std::lock_guard G(Mutex_); + for (const auto &E : OutStandingUploads_) { if (E.UUID == UUID) { V = E; return true; @@ -311,12 +307,12 @@ namespace OpenWifi { return false; } - void FileUploader::Stop() { - poco_notice(Logger(),"Stopping..."); - for( const auto & svr : Servers_ ) - svr->stopAll(true); + void FileUploader::Stop() { + poco_notice(Logger(), "Stopping..."); + for (const auto &svr : Servers_) + svr->stopAll(true); Servers_.clear(); - poco_notice(Logger(),"Stopped..."); - } + poco_notice(Logger(), "Stopped..."); + } -} // Namespace \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/FileUploader.h b/src/FileUploader.h index 99b4737f..8cb3566a 100644 --- a/src/FileUploader.h +++ b/src/FileUploader.h @@ -17,59 +17,55 @@ namespace OpenWifi { - class FileUploader : public SubSystemServer { - public: - + class FileUploader : public SubSystemServer { + public: struct UploadId { - std::string UUID; - std::uint64_t Expires; - std::string Type; + std::string UUID; + std::uint64_t Expires; + std::string Type; }; int Start() override; void Stop() override; void reinitialize(Poco::Util::Application &self) override; - const std::string & FullName(); - bool AddUUID( const std::string & UUID, std::chrono::seconds WaitTimeInSecond, const std::string &Type); - bool ValidRequest(const std::string & UUID); + const std::string &FullName(); + bool AddUUID(const std::string &UUID, std::chrono::seconds WaitTimeInSecond, + const std::string &Type); + bool ValidRequest(const std::string &UUID); void RemoveRequest(const std::string &UUID); - const std::string & Path() { return Path_; }; + const std::string &Path() { return Path_; }; - static auto instance() { - static auto instance_ = new FileUploader; + static auto instance() { + static auto instance_ = new FileUploader; return instance_; - } + } [[nodiscard]] inline uint64_t MaxSize() const { return MaxSize_; } bool Find(const std::string &UUID, UploadId &V); - private: - std::vector> Servers_; - std::string FullName_; - std::list OutStandingUploads_; - std::string Path_; - uint64_t MaxSize_=10000000; - explicit FileUploader() noexcept: - SubSystemServer("FileUploader", "FILE-UPLOAD", "openwifi.fileuploader") - { - } - }; + private: + std::vector> Servers_; + std::string FullName_; + std::list OutStandingUploads_; + std::string Path_; + uint64_t MaxSize_ = 10000000; - class FileUpLoaderRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { - public: - explicit FileUpLoaderRequestHandlerFactory(Poco::Logger &L) : - Logger_(L) { - } + explicit FileUploader() noexcept + : SubSystemServer("FileUploader", "FILE-UPLOAD", "openwifi.fileuploader") {} + }; - Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &request) override; - inline Poco::Logger & Logger() { - return Logger_; - } - private: - Poco::Logger & Logger_; - }; + class FileUpLoaderRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { + public: + explicit FileUpLoaderRequestHandlerFactory(Poco::Logger &L) : Logger_(L) {} + + Poco::Net::HTTPRequestHandler * + createRequestHandler(const Poco::Net::HTTPServerRequest &request) override; + inline Poco::Logger &Logger() { return Logger_; } + + private: + Poco::Logger &Logger_; + }; inline auto FileUploader() { return FileUploader::instance(); } -} // namespace - +} // namespace OpenWifi diff --git a/src/FindCountry.h b/src/FindCountry.h index 090d944d..06ad7c41 100644 --- a/src/FindCountry.h +++ b/src/FindCountry.h @@ -6,8 +6,8 @@ #include "Poco/Net/IPAddress.h" -#include "framework/SubSystemServer.h" #include "framework/MicroServiceFuncs.h" +#include "framework/SubSystemServer.h" #include "nlohmann/json.hpp" @@ -15,11 +15,10 @@ namespace OpenWifi { class IPToCountryProvider { public: - virtual bool Init() = 0 ; - virtual Poco::URI URI(const std::string & IPAddress) = 0; - virtual std::string Country( const std::string & Response ) = 0 ; - virtual ~IPToCountryProvider() { - }; + virtual bool Init() = 0; + virtual Poco::URI URI(const std::string &IPAddress) = 0; + virtual std::string Country(const std::string &Response) = 0; + virtual ~IPToCountryProvider(){}; }; class IPInfo : public IPToCountryProvider { @@ -30,28 +29,26 @@ namespace OpenWifi { return !Key_.empty(); } - [[nodiscard]] inline Poco::URI URI(const std::string & IPAddress) override { - Poco::URI U("https://ipinfo.io"); + [[nodiscard]] inline Poco::URI URI(const std::string &IPAddress) override { + Poco::URI U("https://ipinfo.io"); U.setPath("/" + IPAddress); - U.addQueryParameter("token",Key_); + U.addQueryParameter("token", Key_); return U; } - inline std::string Country( const std::string & Response ) override { + inline std::string Country(const std::string &Response) override { try { nlohmann::json IPInfo = nlohmann::json::parse(Response); if (IPInfo.contains("country") && IPInfo["country"].is_string()) { return IPInfo["country"]; } } catch (...) { - } return ""; } private: std::string Key_; - }; class IPData : public IPToCountryProvider { @@ -62,24 +59,24 @@ namespace OpenWifi { return !Key_.empty(); } - [[nodiscard]] inline Poco::URI URI(const std::string & IPAddress) override { - Poco::URI U("https://api.ipdata.co"); + [[nodiscard]] inline Poco::URI URI(const std::string &IPAddress) override { + Poco::URI U("https://api.ipdata.co"); U.setPath("/" + IPAddress); - U.addQueryParameter("api-key",Key_); + U.addQueryParameter("api-key", Key_); return U; } - inline std::string Country( const std::string & Response ) override { + inline std::string Country(const std::string &Response) override { try { nlohmann::json IPInfo = nlohmann::json::parse(Response); if (IPInfo.contains("country_code") && IPInfo["country_code"].is_string()) { return IPInfo["country_code"]; } } catch (...) { - } return ""; } + private: std::string Key_; }; @@ -92,33 +89,33 @@ namespace OpenWifi { return !Key_.empty(); } - [[nodiscard]] inline Poco::URI URI(const std::string & IPAddress) override { - Poco::URI U("https://api.ip2location.com/v2"); + [[nodiscard]] inline Poco::URI URI(const std::string &IPAddress) override { + Poco::URI U("https://api.ip2location.com/v2"); U.setPath("/"); U.addQueryParameter("ip", IPAddress); U.addQueryParameter("package", "WS1"); - U.addQueryParameter("key",Key_); + U.addQueryParameter("key", Key_); return U; } - inline std::string Country( const std::string & Response ) override { + inline std::string Country(const std::string &Response) override { try { nlohmann::json IPInfo = nlohmann::json::parse(Response); if (IPInfo.contains("country_code") && IPInfo["country_code"].is_string()) { return IPInfo["country_code"]; } } catch (...) { - } return ""; } + private: std::string Key_; }; - template - std::unique_ptr IPLocationProvider(const std::string & RequestProvider ) { - if(T::Name()==RequestProvider) { + template + std::unique_ptr IPLocationProvider(const std::string &RequestProvider) { + if (T::Name() == RequestProvider) { return std::make_unique(); } if constexpr (sizeof...(Args) == 0) { @@ -136,11 +133,12 @@ namespace OpenWifi { } inline int Start() final { - poco_notice(Logger(),"Starting..."); - ProviderName_ = MicroServiceConfigGetString("iptocountry.provider",""); - if(!ProviderName_.empty()) { - Provider_ = IPLocationProvider(ProviderName_); - if(Provider_!= nullptr) { + poco_notice(Logger(), "Starting..."); + ProviderName_ = MicroServiceConfigGetString("iptocountry.provider", ""); + if (!ProviderName_.empty()) { + Provider_ = IPLocationProvider( + ProviderName_); + if (Provider_ != nullptr) { Enabled_ = Provider_->Init(); } } @@ -149,28 +147,26 @@ namespace OpenWifi { } inline void Stop() final { - poco_notice(Logger(),"Stopping..."); + poco_notice(Logger(), "Stopping..."); // Nothing to do - just to provide the same look at the others. - poco_notice(Logger(),"Stopped..."); + poco_notice(Logger(), "Stopped..."); } - [[nodiscard]] static inline std::string ReformatAddress(const std::string & I ) - { - if(I.substr(0,7) == "::ffff:") - { - std::string ip = I.substr(7 ); + [[nodiscard]] static inline std::string ReformatAddress(const std::string &I) { + if (I.substr(0, 7) == "::ffff:") { + std::string ip = I.substr(7); return ip; } return I; } - inline std::string Get(const Poco::Net::IPAddress & IP) { + inline std::string Get(const Poco::Net::IPAddress &IP) { if (!Enabled_) return Default_; return Get(ReformatAddress(IP.toString())); } - inline std::string Get(const std::string & IP) { + inline std::string Get(const std::string &IP) { if (!Enabled_) return Default_; try { @@ -178,10 +174,10 @@ namespace OpenWifi { std::string Response; if (Utils::wgets(URL, Response)) { auto Answer = Provider_->Country(Response); - if(!Answer.empty()) + if (!Answer.empty()) return Answer; } - } catch(...) { + } catch (...) { } return Default_; } @@ -189,17 +185,14 @@ namespace OpenWifi { inline auto Enabled() const { return Enabled_; } private: - bool Enabled_=false; - std::string Default_; - std::unique_ptr Provider_; - std::string ProviderName_; + bool Enabled_ = false; + std::string Default_; + std::unique_ptr Provider_; + std::string ProviderName_; - FindCountryFromIP() noexcept: - SubSystemServer("IpToCountry", "IPTOC-SVR", "iptocountry") - { - } + FindCountryFromIP() noexcept : SubSystemServer("IpToCountry", "IPTOC-SVR", "iptocountry") {} }; inline auto FindCountryFromIP() { return FindCountryFromIP::instance(); } -} +} // namespace OpenWifi diff --git a/src/GWKafkaEvents.cpp b/src/GWKafkaEvents.cpp index 53cfbe9b..9f370f52 100644 --- a/src/GWKafkaEvents.cpp +++ b/src/GWKafkaEvents.cpp @@ -7,7 +7,7 @@ namespace OpenWifi { void GWKafkaEvents::Send() { - if(KafkaManager()->Enabled()) { + if (KafkaManager()->Enabled()) { Poco::JSON::Object Event; Event.set("type", type_); Event.set("timestamp", timestamp_); diff --git a/src/GWKafkaEvents.h b/src/GWKafkaEvents.h index a2315918..790d8edc 100644 --- a/src/GWKafkaEvents.h +++ b/src/GWKafkaEvents.h @@ -4,57 +4,53 @@ #pragma once -#include #include #include +#include namespace OpenWifi { class GWKafkaEvents { public: - GWKafkaEvents(const std::string &serialNumber, const std::string &type, std::uint64_t timestamp) : - serialNumber_(serialNumber), - type_(type), - timestamp_(timestamp) { - } + GWKafkaEvents(const std::string &serialNumber, const std::string &type, + std::uint64_t timestamp) + : serialNumber_(serialNumber), type_(type), timestamp_(timestamp) {} - inline void SetPayload(Poco::JSON::Object::Ptr payload) { - payload_ = std::move(payload); - } + inline void SetPayload(Poco::JSON::Object::Ptr payload) { payload_ = std::move(payload); } void Send(); private: - std::string serialNumber_; - std::string type_; - std::uint64_t timestamp_=0; + std::string serialNumber_; + std::string type_; + std::uint64_t timestamp_ = 0; Poco::JSON::Object::Ptr payload_; }; class DeviceFirmwareChangeKafkaEvent : public GWKafkaEvents { public: - DeviceFirmwareChangeKafkaEvent( const std::string &serialNumber, std::uint64_t timestamp, const std::string &oldFirmware, const std::string &newFirmware) : - GWKafkaEvents(serialNumber,"unit.firmware_change", timestamp), - oldFirmware_(oldFirmware), - newFirmware_(newFirmware) { - } + DeviceFirmwareChangeKafkaEvent(const std::string &serialNumber, std::uint64_t timestamp, + const std::string &oldFirmware, + const std::string &newFirmware) + : GWKafkaEvents(serialNumber, "unit.firmware_change", timestamp), + oldFirmware_(oldFirmware), newFirmware_(newFirmware) {} ~DeviceFirmwareChangeKafkaEvent() { Poco::JSON::Object::Ptr payload = new Poco::JSON::Object; payload->set("oldFirmware", oldFirmware_); - payload->set("newFirmware",newFirmware_); + payload->set("newFirmware", newFirmware_); SetPayload(payload); Send(); } - private: - std::string oldFirmware_, newFirmware_; + private: + std::string oldFirmware_, newFirmware_; }; class DeviceConfigurationChangeKafkaEvent : public GWKafkaEvents { public: - DeviceConfigurationChangeKafkaEvent( const std::string &serialNumber, std::uint64_t timestamp, const std::string config) : - GWKafkaEvents(serialNumber,"unit.configuration_change", timestamp), - config_(config) { + DeviceConfigurationChangeKafkaEvent(const std::string &serialNumber, + std::uint64_t timestamp, const std::string config) + : GWKafkaEvents(serialNumber, "unit.configuration_change", timestamp), config_(config) { } ~DeviceConfigurationChangeKafkaEvent() { @@ -70,11 +66,12 @@ namespace OpenWifi { class DeviceBlacklistedKafkaEvent : public GWKafkaEvents { public: - explicit DeviceBlacklistedKafkaEvent( const std::string &serialNumber, std::uint64_t timestamp, const std::string &reason, const std::string &author, std::uint64_t created, std::string &IP) : - GWKafkaEvents(serialNumber,"blacklisted_device", timestamp), - reason_(reason), author_(author), created_(created), IP_(IP) - { - } + explicit DeviceBlacklistedKafkaEvent(const std::string &serialNumber, + std::uint64_t timestamp, const std::string &reason, + const std::string &author, std::uint64_t created, + std::string &IP) + : GWKafkaEvents(serialNumber, "blacklisted_device", timestamp), reason_(reason), + author_(author), created_(created), IP_(IP) {} ~DeviceBlacklistedKafkaEvent() { Poco::JSON::Object::Ptr payload = new Poco::JSON::Object; @@ -87,11 +84,9 @@ namespace OpenWifi { } private: - std::string reason_,author_; - std::uint64_t created_; - std::string IP_; + std::string reason_, author_; + std::uint64_t created_; + std::string IP_; }; } // namespace OpenWifi - - diff --git a/src/GwWebSocketClient.cpp b/src/GwWebSocketClient.cpp index 1e4b6071..d80d7662 100644 --- a/src/GwWebSocketClient.cpp +++ b/src/GwWebSocketClient.cpp @@ -7,23 +7,22 @@ namespace OpenWifi { - GwWebSocketClient::GwWebSocketClient(Poco::Logger &Logger): - Logger_(Logger){ + GwWebSocketClient::GwWebSocketClient(Poco::Logger &Logger) : Logger_(Logger) { UI_WebSocketClientServer()->SetProcessor(this); } - GwWebSocketClient::~GwWebSocketClient() { - UI_WebSocketClientServer()->SetProcessor(nullptr); - } + GwWebSocketClient::~GwWebSocketClient() { UI_WebSocketClientServer()->SetProcessor(nullptr); } - void GwWebSocketClient::Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done, [[maybe_unused]] const SecurityObjects::UserInfo &UserInfo) { + void GwWebSocketClient::Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, + bool &Done, + [[maybe_unused]] const SecurityObjects::UserInfo &UserInfo) { try { if (O->has("command")) { auto Command = O->get("command").toString(); if (Command == "serial_number_search" && O->has("serial_prefix")) { - ws_command_serial_number_search(O,Done,Answer); - } else if (Command=="exit") { - ws_command_exit(O,Done,Answer); + ws_command_serial_number_search(O, Done, Answer); + } else if (Command == "exit") { + ws_command_exit(O, Done, Answer); } else { ws_command_invalid(O, Done, Answer); } @@ -34,7 +33,7 @@ namespace OpenWifi { } void GwWebSocketClient::ws_command_serial_number_search(const Poco::JSON::Object::Ptr &O, - bool &Done, std::string &Answer) { + bool &Done, std::string &Answer) { Done = false; auto Prefix = O->get("serial_prefix").toString(); if (!Prefix.empty() && Prefix.length() < 13) { @@ -51,13 +50,15 @@ namespace OpenWifi { } } - void GwWebSocketClient::ws_command_exit([[maybe_unused]] const Poco::JSON::Object::Ptr &O, bool &Done, std::string &Answer) { + void GwWebSocketClient::ws_command_exit([[maybe_unused]] const Poco::JSON::Object::Ptr &O, + bool &Done, std::string &Answer) { Done = true; Answer = R"lit({ "closing" : "Goodbye! Aurevoir! Hasta la vista!" })lit"; } - void GwWebSocketClient::ws_command_invalid([[maybe_unused]] const Poco::JSON::Object::Ptr &O, bool &Done, std::string &Answer) { + void GwWebSocketClient::ws_command_invalid([[maybe_unused]] const Poco::JSON::Object::Ptr &O, + bool &Done, std::string &Answer) { Done = false; Answer = std::string{R"lit({ "error" : "invalid command" })lit"}; } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/GwWebSocketClient.h b/src/GwWebSocketClient.h index e9c328c0..260a4b6f 100644 --- a/src/GwWebSocketClient.h +++ b/src/GwWebSocketClient.h @@ -11,13 +11,15 @@ namespace OpenWifi { public: explicit GwWebSocketClient(Poco::Logger &Logger); virtual ~GwWebSocketClient(); - virtual void Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done, const SecurityObjects::UserInfo &UserInfo); - void ws_command_serial_number_search( const Poco::JSON::Object::Ptr &O, bool &Done, std::string &Answer); - void ws_command_exit( const Poco::JSON::Object::Ptr &O, bool &Done, std::string &Answer); - void ws_command_invalid( const Poco::JSON::Object::Ptr &O, bool &Done, std::string &Answer); + virtual void Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done, + const SecurityObjects::UserInfo &UserInfo); + void ws_command_serial_number_search(const Poco::JSON::Object::Ptr &O, bool &Done, + std::string &Answer); + void ws_command_exit(const Poco::JSON::Object::Ptr &O, bool &Done, std::string &Answer); + void ws_command_invalid(const Poco::JSON::Object::Ptr &O, bool &Done, std::string &Answer); private: - Poco::Logger & Logger_; - inline Poco::Logger & Logger() { return Logger_; } + Poco::Logger &Logger_; + inline Poco::Logger &Logger() { return Logger_; } }; -} +} // namespace OpenWifi diff --git a/src/OUIServer.cpp b/src/OUIServer.cpp index c176b111..aed6e6b3 100644 --- a/src/OUIServer.cpp +++ b/src/OUIServer.cpp @@ -1,15 +1,15 @@ // // Created by stephane bourque on 2021-06-17. // -#include #include +#include #include +#include "Poco/File.h" +#include "Poco/StreamCopier.h" #include "Poco/String.h" #include "Poco/StringTokenizer.h" #include "Poco/URIStreamOpener.h" -#include "Poco/StreamCopier.h" -#include "Poco/File.h" #include "framework/MicroServiceFuncs.h" #include "framework/utils.h" @@ -22,25 +22,25 @@ namespace OpenWifi { int OUIServer::Start() { Running_ = true; - LatestOUIFileName_ = MicroServiceDataDirectory() + "/newOUIFile.txt"; + LatestOUIFileName_ = MicroServiceDataDirectory() + "/newOUIFile.txt"; CurrentOUIFileName_ = MicroServiceDataDirectory() + "/current_oui.txt"; bool Recovered = false; - Poco::File OuiFile(CurrentOUIFileName_); - if(OuiFile.exists()) { - std::unique_lock Lock(LocalMutex_); - Recovered = ProcessFile(CurrentOUIFileName_,OUIs_); - if(Recovered) { + Poco::File OuiFile(CurrentOUIFileName_); + if (OuiFile.exists()) { + std::unique_lock Lock(LocalMutex_); + Recovered = ProcessFile(CurrentOUIFileName_, OUIs_); + if (Recovered) { poco_notice(Logger(), - fmt::format("Recovered last OUI file - {}", CurrentOUIFileName_)); + fmt::format("Recovered last OUI file - {}", CurrentOUIFileName_)); } } else { - poco_notice(Logger(), - fmt::format("No existing OUIFile.", CurrentOUIFileName_)); + poco_notice(Logger(), fmt::format("No existing OUIFile.", CurrentOUIFileName_)); } - UpdaterCallBack_ = std::make_unique>(*this, &OUIServer::onTimer); - if(Recovered) { + UpdaterCallBack_ = + std::make_unique>(*this, &OUIServer::onTimer); + if (Recovered) { Timer_.setStartInterval(60 * 60 * 1000); // first run in 1 hour } else { Timer_.setStartInterval(30 * 1000); // first run in 5 minutes @@ -51,15 +51,15 @@ namespace OpenWifi { } void OUIServer::Stop() { - poco_notice(Logger(),"Stopping..."); - Running_=false; + poco_notice(Logger(), "Stopping..."); + Running_ = false; Timer_.stop(); - poco_notice(Logger(),"Stopped..."); + poco_notice(Logger(), "Stopped..."); } void OUIServer::reinitialize([[maybe_unused]] Poco::Util::Application &self) { MicroServiceLoadConfigurationFile(); - poco_information(Logger(),"Reinitializing."); + poco_information(Logger(), "Reinitializing."); Stop(); Start(); } @@ -67,14 +67,18 @@ namespace OpenWifi { bool OUIServer::GetFile(const std::string &FileName) { try { LastUpdate_ = Utils::Now(); - poco_information(Logger(), fmt::format("Start: Retrieving OUI file: {}",MicroServiceConfigGetString("oui.download.uri",""))); - std::unique_ptr pStr( - Poco::URIStreamOpener::defaultOpener().open(MicroServiceConfigGetString("oui.download.uri",""))); + poco_information(Logger(), + fmt::format("Start: Retrieving OUI file: {}", + MicroServiceConfigGetString("oui.download.uri", ""))); + std::unique_ptr pStr(Poco::URIStreamOpener::defaultOpener().open( + MicroServiceConfigGetString("oui.download.uri", ""))); std::ofstream OS; OS.open(FileName); Poco::StreamCopier::copyStream(*pStr, OS); OS.close(); - poco_information(Logger(), fmt::format("Done: Retrieving OUI file: {}",MicroServiceConfigGetString("oui.download.uri",""))); + poco_information(Logger(), + fmt::format("Done: Retrieving OUI file: {}", + MicroServiceConfigGetString("oui.download.uri", ""))); return true; } catch (const Poco::Exception &E) { Logger().log(E); @@ -82,13 +86,13 @@ namespace OpenWifi { return false; } - bool OUIServer::ProcessFile( const std::string &FileName, OUIMap &Map) { + bool OUIServer::ProcessFile(const std::string &FileName, OUIMap &Map) { try { std::ifstream Input; Input.open(FileName, std::ios::binary); while (!Input.eof()) { - if(!Running_) + if (!Running_) return false; char buf[1024]; Input.getline(buf, sizeof(buf)); @@ -112,67 +116,68 @@ namespace OpenWifi { } } return true; - } catch ( const Poco::Exception &E) { + } catch (const Poco::Exception &E) { Logger().log(E); } return false; } - void OUIServer::onTimer([[maybe_unused]] Poco::Timer & timer) { + void OUIServer::onTimer([[maybe_unused]] Poco::Timer &timer) { Utils::SetThreadName("ouisvr-timer"); - if(Updating_) + if (Updating_) return; Updating_ = true; - poco_information(Logger(),"Starting to process OUI file..."); + poco_information(Logger(), "Starting to process OUI file..."); // fetch data from server, if not available, just use the file we already have. - Poco::File Current(CurrentOUIFileName_); - if(Current.exists()) { - if((Utils::Now()-Current.getLastModified().epochTime()) < (7*24*60*60)) { - if(!Initialized_) { - if(ProcessFile(CurrentOUIFileName_, OUIs_)) { + Poco::File Current(CurrentOUIFileName_); + if (Current.exists()) { + if ((Utils::Now() - Current.getLastModified().epochTime()) < (7 * 24 * 60 * 60)) { + if (!Initialized_) { + if (ProcessFile(CurrentOUIFileName_, OUIs_)) { Initialized_ = true; - Updating_=false; + Updating_ = false; poco_information(Logger(), "Using cached file."); return; } } else { - Updating_=false; + Updating_ = false; return; } } } OUIMap TmpOUIs; - if(GetFile(LatestOUIFileName_) && ProcessFile(LatestOUIFileName_, TmpOUIs)) { + if (GetFile(LatestOUIFileName_) && ProcessFile(LatestOUIFileName_, TmpOUIs)) { std::unique_lock G(LocalMutex_); OUIs_ = std::move(TmpOUIs); LastUpdate_ = Utils::Now(); Poco::File F1(CurrentOUIFileName_); - if(F1.exists()) + if (F1.exists()) F1.remove(); Poco::File F2(LatestOUIFileName_); F2.renameTo(CurrentOUIFileName_); - poco_information(Logger(), fmt::format("New OUI file {} downloaded.",LatestOUIFileName_)); - } else if(OUIs_.empty()) { - if(ProcessFile(CurrentOUIFileName_, TmpOUIs)) { + poco_information(Logger(), + fmt::format("New OUI file {} downloaded.", LatestOUIFileName_)); + } else if (OUIs_.empty()) { + if (ProcessFile(CurrentOUIFileName_, TmpOUIs)) { LastUpdate_ = Utils::Now(); std::unique_lock G(LocalMutex_); OUIs_ = std::move(TmpOUIs); } } - Initialized_=true; + Initialized_ = true; Updating_ = false; - poco_information(Logger(),"Done processing OUI file..."); + poco_information(Logger(), "Done processing OUI file..."); } std::string OUIServer::GetManufacturer(const std::string &MAC) { - std::shared_lock Lock(LocalMutex_); + std::shared_lock Lock(LocalMutex_); auto Manufacturer = OUIs_.find(Utils::SerialNumberToOUI(MAC)); - if(Manufacturer != OUIs_.end()) + if (Manufacturer != OUIs_.end()) return Manufacturer->second; return ""; } -}; +}; // namespace OpenWifi diff --git a/src/OUIServer.h b/src/OUIServer.h index 10971da8..730cca4c 100644 --- a/src/OUIServer.h +++ b/src/OUIServer.h @@ -14,18 +14,17 @@ namespace OpenWifi { class OUIServer : public SubSystemServer { public: - - typedef std::map OUIMap; + typedef std::map OUIMap; static auto instance() { - static auto instance_ = new OUIServer; + static auto instance_ = new OUIServer; return instance_; } int Start() override; void Stop() override; - void onTimer(Poco::Timer & timer); + void onTimer(Poco::Timer &timer); void reinitialize(Poco::Util::Application &self) override; [[nodiscard]] std::string GetManufacturer(const std::string &MAC); @@ -33,23 +32,19 @@ namespace OpenWifi { [[nodiscard]] bool ProcessFile(const std::string &FileName, OUIMap &Map); private: - std::shared_mutex LocalMutex_; - uint64_t LastUpdate_ = 0 ; - bool Initialized_ = false; - OUIMap OUIs_; - volatile std::atomic_bool Updating_=false; - volatile std::atomic_bool Running_=false; - Poco::Timer Timer_; - std::unique_ptr> UpdaterCallBack_; - std::string LatestOUIFileName_,CurrentOUIFileName_; + std::shared_mutex LocalMutex_; + uint64_t LastUpdate_ = 0; + bool Initialized_ = false; + OUIMap OUIs_; + volatile std::atomic_bool Updating_ = false; + volatile std::atomic_bool Running_ = false; + Poco::Timer Timer_; + std::unique_ptr> UpdaterCallBack_; + std::string LatestOUIFileName_, CurrentOUIFileName_; - OUIServer() noexcept: - SubSystemServer("OUIServer", "OUI-SVR", "ouiserver") - { - } + OUIServer() noexcept : SubSystemServer("OUIServer", "OUI-SVR", "ouiserver") {} }; inline auto OUIServer() { return OUIServer::instance(); } -} - +} // namespace OpenWifi diff --git a/src/ParseWifiScan.h b/src/ParseWifiScan.h index 5ca5a661..67df6e78 100644 --- a/src/ParseWifiScan.h +++ b/src/ParseWifiScan.h @@ -4,104 +4,109 @@ #pragma once -#include -#include #include +#include #include +#include #include "nlohmann/json.hpp" namespace OpenWifi { -#define OUI_ENCAP_ETHER 0x000000 /* encapsulated Ethernet */ -#define OUI_XEROX 0x000006 /* Xerox */ -#define OUI_CISCO 0x00000C /* Cisco (future use) */ -#define OUI_IANA 0x00005E /* the IANA */ -#define OUI_NORTEL 0x000081 /* Nortel SONMP */ -#define OUI_CISCO_90 0x0000F8 /* Cisco (IOS 9.0 and above?) */ -#define OUI_CISCO_2 0x000142 /* Cisco */ -#define OUI_CISCO_3 0x000143 /* Cisco */ -#define OUI_FORCE10 0x0001E8 /* Force10 */ -#define OUI_ERICSSON 0x0001EC /* Ericsson Group */ -#define OUI_CATENA 0x00025A /* Catena Networks */ -#define OUI_ATHEROS 0x00037F /* Atheros Communications */ -#define OUI_ORACLE 0x0003BA /* Oracle */ -#define OUI_AVAYA_EXTREME 0x00040D /* Avaya Extreme access point */ -#define OUI_EXTREME_MESH 0x000512 /* Extreme MESH */ -#define OUI_SONY_ERICSSON 0x000AD9 /* Sony Ericsson Mobile Communications AB */ -#define OUI_ARUBA 0x000B86 /* Aruba Networks */ -#define OUI_ROUTERBOARD 0x000C42 /* Formerly listed as Mikrotik, however this OUI is owned by Routerboard*/ -#define OUI_MERU 0x000CE6 /* Meru Network (Fortinet) */ -#define OUI_SONY_ERICSSON_2 0x000E07 /* Sony Ericsson Mobile Communications AB */ -#define OUI_PROFINET 0x000ECF /* PROFIBUS Nutzerorganisation e.V. */ -#define OUI_RSN 0x000FAC /* Wi-Fi : RSN */ -#define OUI_SONY_ERICSSON_3 0x000FDE /* Sony Ericsson Mobile Communications AB */ -#define OUI_FORTINET 0x00090F /* Fortinet */ -#define OUI_CIMETRICS 0x001090 /* Cimetrics, Inc. */ -#define OUI_IEEE_802_3 0x00120F /* IEEE 802.3 */ -#define OUI_MEDIA_ENDPOINT 0x0012BB /* Media (TIA TR-41 Committee) */ -#define OUI_SONY_ERICSSON_4 0x0012EE /* Sony Ericsson Mobile Communications AB */ -#define OUI_ERICSSON_MOBILE 0x0015E0 /* Ericsson Mobile Platforms */ -#define OUI_SONY_ERICSSON_5 0x001620 /* Sony Ericsson Mobile Communications AB */ -#define OUI_SONY_ERICSSON_6 0x0016B8 /* Sony Ericsson Mobile Communications AB */ -#define OUI_APPLE_AWDL 0x0017F2 /* Apple AWDL */ -#define OUI_SONY_ERICSSON_7 0x001813 /* Sony Ericsson Mobile Communications AB */ -#define OUI_BLUETOOTH 0x001958 /* Bluetooth SIG */ -#define OUI_SONY_ERICSSON_8 0x001963 /* Sony Ericsson Mobile Communications AB */ -#define OUI_AEROHIVE 0x001977 /* Aerohive AP to AP communication */ -#define OUI_ITU_T 0x0019a7 /* International Telecommunication Union (ITU) Telecommunication Standardization Sector */ -#define OUI_DCBX 0x001B21 /* Data Center Bridging Capabilities Exchange Protocol */ -#define OUI_CISCO_UBI 0x001B67 /* Cisco/Ubiquisys */ -#define OUI_IEEE_802_1QBG 0x001B3F /* IEEE 802.1 Qbg */ -#define OUI_NINTENDO 0x001F32 -#define OUI_TURBOCELL 0x0020F6 /* KarlNet, who brought you Turbocell */ -#define OUI_AVAYA 0x00400D /* Avaya */ -#define OUI_CISCOWL 0x004096 /* Cisco Wireless (Aironet) */ -#define OUI_MARVELL 0x005043 /* Marvell Semiconductor */ -#define OUI_WPAWME 0x0050F2 /* Wi-Fi : WPA / WME */ -#define OUI_ERICSSON_2 0x008037 /* Ericsson Group */ -#define OUI_HP_2 0x00805F /* Hewlett-Packard */ -#define OUI_IEEE_802_1 0x0080C2 /* IEEE 802.1 Committee */ -#define OUI_PRE11N 0x00904C /* Wi-Fi : 802.11 Pre-N */ -#define OUI_ATM_FORUM 0x00A03E /* ATM Forum */ -#define OUI_ZEBRA_EXTREME 0x00A0F8 /* Extreme/WING (Zebra) */ -#define OUI_EXTREME 0x00E02B /* Extreme EDP/ESRP */ -#define OUI_CABLE_BPDU 0x00E02F /* DOCSIS spanning tree BPDU */ -#define OUI_FOUNDRY 0x00E052 /* Foundry */ -#define OUI_SIEMENS 0x080006 /* Siemens AG */ -#define OUI_APPLE_ATALK 0x080007 /* Appletalk */ -#define OUI_HP 0x080009 /* Hewlett-Packard */ -#define OUI_CERN 0x080030 /* CERN, The European Organization for Nuclear Research */ -#define OUI_IEEE_C37_238 0x1C129D /* IEEE PES PSRC/SUB Working Group H7/Sub C7 (IEEE PC37.238) */ -#define OUI_HYTEC_GER 0x30B216 /* Hytec Geraetebau GmbH */ -#define OUI_ZIGBEE 0x4A191B /* ZigBee Alliance */ -#define OUI_WFA 0x506F9A /* Wi-Fi Alliance */ -#define OUI_MIST 0x5C5B35 /* Mist Systems */ -#define OUI_RUCKUS 0x001392 /* Ruckus Networks */ -#define OUI_SMPTE 0x6897E8 /* Society of Motion Picture and Television Engineers */ -#define OUI_SGDSN 0x6A5C35 /* Secrétariat Général de la Défense et de la Sécurité Nationale http://www.sgdsn.gouv.fr */ -#define OUI_ONOS 0xA42305 /* Open Networking Laboratory (ONOS) */ -#define OUI_3GPP2 0xCF0002 /* 3GPP2 */ -#define OUI_AVAYA_EXTREME2 0xD88466 /* Avaya Extreme Fabric */ +#define OUI_ENCAP_ETHER 0x000000 /* encapsulated Ethernet */ +#define OUI_XEROX 0x000006 /* Xerox */ +#define OUI_CISCO 0x00000C /* Cisco (future use) */ +#define OUI_IANA 0x00005E /* the IANA */ +#define OUI_NORTEL 0x000081 /* Nortel SONMP */ +#define OUI_CISCO_90 0x0000F8 /* Cisco (IOS 9.0 and above?) */ +#define OUI_CISCO_2 0x000142 /* Cisco */ +#define OUI_CISCO_3 0x000143 /* Cisco */ +#define OUI_FORCE10 0x0001E8 /* Force10 */ +#define OUI_ERICSSON 0x0001EC /* Ericsson Group */ +#define OUI_CATENA 0x00025A /* Catena Networks */ +#define OUI_ATHEROS 0x00037F /* Atheros Communications */ +#define OUI_ORACLE 0x0003BA /* Oracle */ +#define OUI_AVAYA_EXTREME 0x00040D /* Avaya Extreme access point */ +#define OUI_EXTREME_MESH 0x000512 /* Extreme MESH */ +#define OUI_SONY_ERICSSON 0x000AD9 /* Sony Ericsson Mobile Communications AB */ +#define OUI_ARUBA 0x000B86 /* Aruba Networks */ +#define OUI_ROUTERBOARD \ + 0x000C42 /* Formerly listed as Mikrotik, however this OUI is owned by Routerboard*/ +#define OUI_MERU 0x000CE6 /* Meru Network (Fortinet) */ +#define OUI_SONY_ERICSSON_2 0x000E07 /* Sony Ericsson Mobile Communications AB */ +#define OUI_PROFINET 0x000ECF /* PROFIBUS Nutzerorganisation e.V. */ +#define OUI_RSN 0x000FAC /* Wi-Fi : RSN */ +#define OUI_SONY_ERICSSON_3 0x000FDE /* Sony Ericsson Mobile Communications AB */ +#define OUI_FORTINET 0x00090F /* Fortinet */ +#define OUI_CIMETRICS 0x001090 /* Cimetrics, Inc. */ +#define OUI_IEEE_802_3 0x00120F /* IEEE 802.3 */ +#define OUI_MEDIA_ENDPOINT 0x0012BB /* Media (TIA TR-41 Committee) */ +#define OUI_SONY_ERICSSON_4 0x0012EE /* Sony Ericsson Mobile Communications AB */ +#define OUI_ERICSSON_MOBILE 0x0015E0 /* Ericsson Mobile Platforms */ +#define OUI_SONY_ERICSSON_5 0x001620 /* Sony Ericsson Mobile Communications AB */ +#define OUI_SONY_ERICSSON_6 0x0016B8 /* Sony Ericsson Mobile Communications AB */ +#define OUI_APPLE_AWDL 0x0017F2 /* Apple AWDL */ +#define OUI_SONY_ERICSSON_7 0x001813 /* Sony Ericsson Mobile Communications AB */ +#define OUI_BLUETOOTH 0x001958 /* Bluetooth SIG */ +#define OUI_SONY_ERICSSON_8 0x001963 /* Sony Ericsson Mobile Communications AB */ +#define OUI_AEROHIVE 0x001977 /* Aerohive AP to AP communication */ +#define OUI_ITU_T \ + 0x0019a7 /* International Telecommunication Union (ITU) Telecommunication Standardization \ + Sector */ +#define OUI_DCBX 0x001B21 /* Data Center Bridging Capabilities Exchange Protocol */ +#define OUI_CISCO_UBI 0x001B67 /* Cisco/Ubiquisys */ +#define OUI_IEEE_802_1QBG 0x001B3F /* IEEE 802.1 Qbg */ +#define OUI_NINTENDO 0x001F32 +#define OUI_TURBOCELL 0x0020F6 /* KarlNet, who brought you Turbocell */ +#define OUI_AVAYA 0x00400D /* Avaya */ +#define OUI_CISCOWL 0x004096 /* Cisco Wireless (Aironet) */ +#define OUI_MARVELL 0x005043 /* Marvell Semiconductor */ +#define OUI_WPAWME 0x0050F2 /* Wi-Fi : WPA / WME */ +#define OUI_ERICSSON_2 0x008037 /* Ericsson Group */ +#define OUI_HP_2 0x00805F /* Hewlett-Packard */ +#define OUI_IEEE_802_1 0x0080C2 /* IEEE 802.1 Committee */ +#define OUI_PRE11N 0x00904C /* Wi-Fi : 802.11 Pre-N */ +#define OUI_ATM_FORUM 0x00A03E /* ATM Forum */ +#define OUI_ZEBRA_EXTREME 0x00A0F8 /* Extreme/WING (Zebra) */ +#define OUI_EXTREME 0x00E02B /* Extreme EDP/ESRP */ +#define OUI_CABLE_BPDU 0x00E02F /* DOCSIS spanning tree BPDU */ +#define OUI_FOUNDRY 0x00E052 /* Foundry */ +#define OUI_SIEMENS 0x080006 /* Siemens AG */ +#define OUI_APPLE_ATALK 0x080007 /* Appletalk */ +#define OUI_HP 0x080009 /* Hewlett-Packard */ +#define OUI_CERN 0x080030 /* CERN, The European Organization for Nuclear Research */ +#define OUI_IEEE_C37_238 0x1C129D /* IEEE PES PSRC/SUB Working Group H7/Sub C7 (IEEE PC37.238) */ +#define OUI_HYTEC_GER 0x30B216 /* Hytec Geraetebau GmbH */ +#define OUI_ZIGBEE 0x4A191B /* ZigBee Alliance */ +#define OUI_WFA 0x506F9A /* Wi-Fi Alliance */ +#define OUI_MIST 0x5C5B35 /* Mist Systems */ +#define OUI_RUCKUS 0x001392 /* Ruckus Networks */ +#define OUI_SMPTE 0x6897E8 /* Society of Motion Picture and Television Engineers */ +#define OUI_SGDSN \ + 0x6A5C35 /* Secrétariat Général de la Défense et de la Sécurité Nationale \ + http://www.sgdsn.gouv.fr */ +#define OUI_ONOS 0xA42305 /* Open Networking Laboratory (ONOS) */ +#define OUI_3GPP2 0xCF0002 /* 3GPP2 */ +#define OUI_AVAYA_EXTREME2 0xD88466 /* Avaya Extreme Fabric */ /* -* COMPOSE_FRAME_TYPE() values for management frames. + * COMPOSE_FRAME_TYPE() values for management frames. */ -#define MGT_ASSOC_REQ 0x00 /* association request */ -#define MGT_ASSOC_RESP 0x01 /* association response */ -#define MGT_REASSOC_REQ 0x02 /* reassociation request */ -#define MGT_REASSOC_RESP 0x03 /* reassociation response */ -#define MGT_PROBE_REQ 0x04 /* Probe request */ -#define MGT_PROBE_RESP 0x05 /* Probe response */ -#define MGT_MEASUREMENT_PILOT 0x06 /* Measurement Pilot */ -#define MGT_BEACON 0x08 /* Beacon frame */ -#define MGT_ATIM 0x09 /* ATIM */ -#define MGT_DISASS 0x0A /* Disassociation */ -#define MGT_AUTHENTICATION 0x0B /* Authentication */ -#define MGT_DEAUTHENTICATION 0x0C /* Deauthentication */ -#define MGT_ACTION 0x0D /* Action */ -#define MGT_ACTION_NO_ACK 0x0E /* Action No Ack */ -#define MGT_ARUBA_WLAN 0x0F /* Aruba WLAN Specific */ +#define MGT_ASSOC_REQ 0x00 /* association request */ +#define MGT_ASSOC_RESP 0x01 /* association response */ +#define MGT_REASSOC_REQ 0x02 /* reassociation request */ +#define MGT_REASSOC_RESP 0x03 /* reassociation response */ +#define MGT_PROBE_REQ 0x04 /* Probe request */ +#define MGT_PROBE_RESP 0x05 /* Probe response */ +#define MGT_MEASUREMENT_PILOT 0x06 /* Measurement Pilot */ +#define MGT_BEACON 0x08 /* Beacon frame */ +#define MGT_ATIM 0x09 /* ATIM */ +#define MGT_DISASS 0x0A /* Disassociation */ +#define MGT_AUTHENTICATION 0x0B /* Authentication */ +#define MGT_DEAUTHENTICATION 0x0C /* Deauthentication */ +#define MGT_ACTION 0x0D /* Action */ +#define MGT_ACTION_NO_ACK 0x0E /* Action No Ack */ +#define MGT_ARUBA_WLAN 0x0F /* Aruba WLAN Specific */ /* WFA vendor specific subtypes */ #define WFA_SUBTYPE_P2P 9 @@ -178,7 +183,7 @@ namespace OpenWifi { WLAN_EID_DIAGNOSTIC_REQUEST = 80, WLAN_EID_DIAGNOSTIC_REPORT = 81, WLAN_EID_LOCATION_PARAMS = 82, - WLAN_EID_NON_TX_BSSID_CAP = 83, + WLAN_EID_NON_TX_BSSID_CAP = 83, WLAN_EID_SSID_LIST = 84, WLAN_EID_MULTI_BSSID_IDX = 85, WLAN_EID_FMS_DESCRIPTOR = 86, @@ -345,7 +350,6 @@ namespace OpenWifi { WLAN_EID_EXT_EHT_CAPABILITY = 108, }; - inline std::vector Base64Decode2Vec(const std::string &F) { std::istringstream ifs(F); Poco::Base64Decoder b64in(ifs); @@ -359,332 +363,234 @@ namespace OpenWifi { return r; } - using value_string = std::vector>; + using value_string = std::vector>; - static const value_string txbf_antenna_flags = { - {0x00, "1 TX antenna sounding"}, - {0x01, "2 TX antenna sounding"}, - {0x02, "3 TX antenna sounding"}, - {0x03, "4 TX antenna sounding"}, - {0x00, NULL} - }; + static const value_string txbf_antenna_flags = {{0x00, "1 TX antenna sounding"}, + {0x01, "2 TX antenna sounding"}, + {0x02, "3 TX antenna sounding"}, + {0x03, "4 TX antenna sounding"}, + {0x00, NULL}}; static const value_string txbf_feedback_flags = { {0x00, "not supported"}, {0x01, "delayed feedback capable"}, {0x02, "immediate feedback capable"}, {0x03, "delayed and immediate feedback capable"}, - {0x00, NULL} - }; + {0x00, NULL}}; - static const value_string txbf_calib_flag = { - {0x00, "incapable"}, - {0x01, "Limited involvement, cannot initiate"}, - {0x02, "Limited involvement, can initiate"}, - {0x03, "Fully capable"}, - {0x00, NULL} - }; + static const value_string txbf_calib_flag = {{0x00, "incapable"}, + {0x01, "Limited involvement, cannot initiate"}, + {0x02, "Limited involvement, can initiate"}, + {0x03, "Fully capable"}, + {0x00, NULL}}; - static const value_string txbf_csi_max_rows_bf_flags = { - {0x00, "1 row of CSI"}, - {0x01, "2 rows of CSI"}, - {0x02, "3 rows of CSI"}, - {0x03, "4 rows of CSI"}, - {0x00, NULL} - }; + static const value_string txbf_csi_max_rows_bf_flags = {{0x00, "1 row of CSI"}, + {0x01, "2 rows of CSI"}, + {0x02, "3 rows of CSI"}, + {0x03, "4 rows of CSI"}, + {0x00, NULL}}; - static const value_string txbf_chan_est_flags = { - {0x00, "1 space time stream"}, - {0x01, "2 space time streams"}, - {0x02, "3 space time streams"}, - {0x03, "4 space time streams"}, - {0x00, NULL} - }; + static const value_string txbf_chan_est_flags = {{0x00, "1 space time stream"}, + {0x01, "2 space time streams"}, + {0x02, "3 space time streams"}, + {0x03, "4 space time streams"}, + {0x00, NULL}}; - static const value_string txbf_min_group_flags = { - {0x00, "No grouping supported"}, - {0x01, "Groups of 1,2 supported"}, - {0x02, "Groups of 1,4 supported"}, - {0x03, "Groups of 1,2,4 supported"}, - {0x00, NULL} - }; + static const value_string txbf_min_group_flags = {{0x00, "No grouping supported"}, + {0x01, "Groups of 1,2 supported"}, + {0x02, "Groups of 1,4 supported"}, + {0x03, "Groups of 1,2,4 supported"}, + {0x00, NULL}}; static const value_string vht_max_mpdu_length_flag = { - {0x00, "3 895"}, - {0x01, "7 991"}, - {0x02, "11 454"}, - {0x03, "Reserved"}, - {0x00, NULL} - }; + {0x00, "3 895"}, {0x01, "7 991"}, {0x02, "11 454"}, {0x03, "Reserved"}, {0x00, NULL}}; static const value_string vht_supported_chan_width_set_flag = { {0x00, "Neither 160MHz nor 80+80 supported"}, {0x01, "160MHz supported"}, {0x02, "160MHz and 80+80 Supported"}, {0x03, "Reserved"}, - {0x00, NULL} - }; + {0x00, NULL}}; - static const value_string vht_rx_stbc_flag = { - {0x00, "None"}, - {0x01, "1 Spatial Stream Supported"}, - {0x02, "1 to 2 Spatial Stream Supported"}, - {0x03, "1 to 3 Spatial Stream Supported"}, - {0x04, "1 to 4 Spatial Stream Supported"}, - {0x02, "160MHz and 80+80 Supported"}, - {0x05, "Reserved"}, - {0x06, "Reserved"}, - {0x07, "Reserved"}, - {0x00, NULL} - }; + static const value_string vht_rx_stbc_flag = {{0x00, "None"}, + {0x01, "1 Spatial Stream Supported"}, + {0x02, "1 to 2 Spatial Stream Supported"}, + {0x03, "1 to 3 Spatial Stream Supported"}, + {0x04, "1 to 4 Spatial Stream Supported"}, + {0x02, "160MHz and 80+80 Supported"}, + {0x05, "Reserved"}, + {0x06, "Reserved"}, + {0x07, "Reserved"}, + {0x00, NULL}}; - static const value_string num_plus_one_3bit_flag = { - {0x00, "1"}, - {0x01, "2"}, - {0x02, "3"}, - {0x03, "4"}, - {0x04, "5"}, - {0x05, "6"}, - {0x06, "7"}, - {0x07, "8"}, - {0x00, NULL} - }; + static const value_string num_plus_one_3bit_flag = {{0x00, "1"}, {0x01, "2"}, {0x02, "3"}, + {0x03, "4"}, {0x04, "5"}, {0x05, "6"}, + {0x06, "7"}, {0x07, "8"}, {0x00, NULL}}; static const value_string vht_max_ampdu_flag = { - {0x00, "8 191"}, - {0x01, "16 383"}, - {0x02, "32 767"}, - {0x03, "65,535"}, - {0x04, "131 071"}, - {0x05, "262 143"}, - {0x06, "524 287"}, - {0x07, "1 048 575"}, - {0x00, NULL} - }; + {0x00, "8 191"}, {0x01, "16 383"}, {0x02, "32 767"}, + {0x03, "65,535"}, {0x04, "131 071"}, {0x05, "262 143"}, + {0x06, "524 287"}, {0x07, "1 048 575"}, {0x00, NULL}}; static const value_string vht_link_adapt_flag = { {0x00, "No Feedback"}, {0x01, "Reserved (logically only solicited feedback)"}, {0x02, "Unsolicited feedback only"}, {0x03, "Both (can provide unsolicited feedback and respond to VHT MRQ)"}, - {0x00, NULL} - }; + {0x00, NULL}}; static const value_string ieee80211_supported_rates_vals = { - { 0x02, "1" }, - { 0x03, "1.5" }, - { 0x04, "2" }, - { 0x05, "2.5" }, - { 0x06, "3" }, - { 0x09, "4.5" }, - { 0x0B, "5.5" }, - { 0x0C, "6" }, - { 0x12, "9" }, - { 0x16, "11" }, - { 0x18, "12" }, - { 0x1B, "13.5" }, - { 0x24, "18" }, - { 0x2C, "22" }, - { 0x30, "24" }, - { 0x36, "27" }, - { 0x42, "33" }, - { 0x48, "36" }, - { 0x60, "48" }, - { 0x6C, "54" }, - { 0x82, "1(B)" }, - { 0x83, "1.5(B)" }, - { 0x84, "2(B)" }, - { 0x85, "2.5(B)" }, - { 0x86, "3(B)" }, - { 0x89, "4.5(B)" }, - { 0x8B, "5.5(B)" }, - { 0x8C, "6(B)" }, - { 0x92, "9(B)" }, - { 0x96, "11(B)" }, - { 0x98, "12(B)" }, - { 0x9B, "13.5(B)" }, - { 0xA4, "18(B)" }, - { 0xAC, "22(B)" }, - { 0xB0, "24(B)" }, - { 0xB6, "27(B)" }, - { 0xC2, "33(B)" }, - { 0xC8, "36(B)" }, - { 0xE0, "48(B)" }, - { 0xEC, "54(B)" }, - { 0xFF, "BSS requires support for mandatory features of HT PHY (IEEE 802.11 - Clause 20)" }, - { 0, NULL} - }; + {0x02, "1"}, + {0x03, "1.5"}, + {0x04, "2"}, + {0x05, "2.5"}, + {0x06, "3"}, + {0x09, "4.5"}, + {0x0B, "5.5"}, + {0x0C, "6"}, + {0x12, "9"}, + {0x16, "11"}, + {0x18, "12"}, + {0x1B, "13.5"}, + {0x24, "18"}, + {0x2C, "22"}, + {0x30, "24"}, + {0x36, "27"}, + {0x42, "33"}, + {0x48, "36"}, + {0x60, "48"}, + {0x6C, "54"}, + {0x82, "1(B)"}, + {0x83, "1.5(B)"}, + {0x84, "2(B)"}, + {0x85, "2.5(B)"}, + {0x86, "3(B)"}, + {0x89, "4.5(B)"}, + {0x8B, "5.5(B)"}, + {0x8C, "6(B)"}, + {0x92, "9(B)"}, + {0x96, "11(B)"}, + {0x98, "12(B)"}, + {0x9B, "13.5(B)"}, + {0xA4, "18(B)"}, + {0xAC, "22(B)"}, + {0xB0, "24(B)"}, + {0xB6, "27(B)"}, + {0xC2, "33(B)"}, + {0xC8, "36(B)"}, + {0xE0, "48(B)"}, + {0xEC, "54(B)"}, + {0xFF, "BSS requires support for mandatory features of HT PHY (IEEE 802.11 - Clause 20)"}, + {0, NULL}}; static const value_string environment_vals = { - { 0x20, "Any" }, - { 0x4f, "Outdoor" }, - { 0x49, "Indoor" }, - { 0, NULL } - }; + {0x20, "Any"}, {0x4f, "Outdoor"}, {0x49, "Indoor"}, {0, NULL}}; static const value_string service_interval_granularity_vals = { - { 0, "5 ms" }, - { 1, "10 ms" }, - { 2, "15 ms" }, - { 3, "20 ms" }, - { 4, "25 ms" }, - { 5, "30 ms" }, - { 6, "35 ms" }, - { 7, "40 ms" }, - { 0x00, NULL } - }; + {0, "5 ms"}, {1, "10 ms"}, {2, "15 ms"}, {3, "20 ms"}, {4, "25 ms"}, + {5, "30 ms"}, {6, "35 ms"}, {7, "40 ms"}, {0x00, NULL}}; static const value_string ieee80211_rsn_cipher_vals = { - {0, "NONE"}, - {1, "WEP (40-bit)"}, - {2, "TKIP"}, - {3, "AES (OCB)"}, - {4, "AES (CCM)"}, - {5, "WEP (104-bit)"}, - {6, "BIP"}, - {7, "Group addressed traffic not allowed"}, - {0, NULL} - }; + {0, "NONE"}, {1, "WEP (40-bit)"}, + {2, "TKIP"}, {3, "AES (OCB)"}, + {4, "AES (CCM)"}, {5, "WEP (104-bit)"}, + {6, "BIP"}, {7, "Group addressed traffic not allowed"}, + {0, NULL}}; - static const value_string ieee80211_rsn_keymgmt_vals = { - {0, "NONE"}, - {1, "WPA"}, - {2, "PSK"}, - {3, "FT over IEEE 802.1X"}, + static const value_string ieee80211_rsn_keymgmt_vals = {{0, "NONE"}, + {1, "WPA"}, + {2, "PSK"}, + {3, "FT over IEEE 802.1X"}, - {4, "FT using PSK"}, - {5, "WPA (SHA256)"}, - {6, "PSK (SHA256)"}, - {7, "TDLS / TPK Handshake"}, - {0, NULL} - }; + {4, "FT using PSK"}, + {5, "WPA (SHA256)"}, + {6, "PSK (SHA256)"}, + {7, "TDLS / TPK Handshake"}, + {0, NULL}}; static const value_string rsn_cap_replay_counter = { {0x00, "1 replay counter per PTKSA/GTKSA/STAKeySA"}, {0x01, "2 replay counters per PTKSA/GTKSA/STAKeySA"}, {0x02, "4 replay counters per PTKSA/GTKSA/STAKeySA"}, {0x03, "16 replay counters per PTKSA/GTKSA/STAKeySA"}, - {0, NULL} - }; + {0, NULL}}; static const value_string ieee802111_wfa_ie_type_vals = { - { 1, "WPA Information Element" }, - { 2, "WMM/WME" }, - { 4, "WPS" }, - { 0, NULL } - }; + {1, "WPA Information Element"}, {2, "WMM/WME"}, {4, "WPS"}, {0, NULL}}; static const value_string ieee80211_wfa_ie_wpa_cipher_vals = { - { 0, "NONE" }, - { 1, "WEP (40-bit)" }, - { 2, "TKIP" }, - { 3, "AES (OCB)" }, - { 4, "AES (CCM)" }, - { 5, "WEP (104-bit)" }, - { 6, "BIP" }, - { 7, "Group addressed traffic not allowed" }, - { 0, NULL } - }; + {0, "NONE"}, {1, "WEP (40-bit)"}, + {2, "TKIP"}, {3, "AES (OCB)"}, + {4, "AES (CCM)"}, {5, "WEP (104-bit)"}, + {6, "BIP"}, {7, "Group addressed traffic not allowed"}, + {0, NULL}}; - static const value_string ieee80211_wfa_ie_wpa_keymgmt_vals = { - { 0, "NONE" }, - { 1, "WPA" }, - { 2, "PSK" }, - { 3, "FT over IEEE 802.1X" }, - { 4, "FT using PSK" }, - { 5, "WPA (SHA256)" }, - { 6, "PSK (SHA256)" }, - { 7, "TDLS / TPK Handshake" }, - { 0, NULL } - }; + static const value_string ieee80211_wfa_ie_wpa_keymgmt_vals = {{0, "NONE"}, + {1, "WPA"}, + {2, "PSK"}, + {3, "FT over IEEE 802.1X"}, + {4, "FT using PSK"}, + {5, "WPA (SHA256)"}, + {6, "PSK (SHA256)"}, + {7, "TDLS / TPK Handshake"}, + {0, NULL}}; static const value_string ieee802111_wfa_ie_wme_type = { - { 0, "Information Element" }, - { 1, "Parameter Element" }, - { 2, "TSPEC Element" }, - { 0, NULL} - }; + {0, "Information Element"}, {1, "Parameter Element"}, {2, "TSPEC Element"}, {0, NULL}}; static const value_string ieee802111_wfa_ie_wme_qos_info_sta_max_sp_length_vals = { - { 0, "WMM AP may deliver all buffered frames (MSDUs and MMPDUs)" }, - { 1, "WMM AP may deliver a maximum of 2 buffered frames (MSDUs and MMPDUs) per USP" }, - { 2, "WMM AP may deliver a maximum of 4 buffered frames (MSDUs and MMPDUs) per USP" }, - { 3, "WMM AP may deliver a maximum of 6 buffered frames (MSDUs and MMPDUs) per USP" }, - { 0, NULL} - }; + {0, "WMM AP may deliver all buffered frames (MSDUs and MMPDUs)"}, + {1, "WMM AP may deliver a maximum of 2 buffered frames (MSDUs and MMPDUs) per USP"}, + {2, "WMM AP may deliver a maximum of 4 buffered frames (MSDUs and MMPDUs) per USP"}, + {3, "WMM AP may deliver a maximum of 6 buffered frames (MSDUs and MMPDUs) per USP"}, + {0, NULL}}; static const value_string ieee80211_wfa_ie_wme_acs_vals = { - { 0, "Best Effort" }, - { 1, "Background" }, - { 2, "Video" }, - { 3, "Voice" }, - { 0, NULL } - }; + {0, "Best Effort"}, {1, "Background"}, {2, "Video"}, {3, "Voice"}, {0, NULL}}; static const value_string ieee80211_wfa_ie_wme_tspec_tsinfo_direction_vals = { - { 0, "Uplink" }, - { 1, "Downlink" }, - { 2, "Direct link" }, - { 3, "Bidirectional link" }, - { 0, NULL } - }; + {0, "Uplink"}, {1, "Downlink"}, {2, "Direct link"}, {3, "Bidirectional link"}, {0, NULL}}; static const value_string ieee80211_wfa_ie_wme_tspec_tsinfo_psb_vals = { - { 0, "Legacy" }, - { 1, "U-APSD" }, - { 0, NULL } - }; + {0, "Legacy"}, {1, "U-APSD"}, {0, NULL}}; - static const value_string ieee80211_wfa_ie_wme_tspec_tsinfo_up_vals = { - { 0, "Best Effort" }, - { 1, "Background" }, - { 2, "Spare" }, - { 3, "Excellent Effort" }, - { 4, "Controlled Load" }, - { 5, "Video" }, - { 6, "Voice" }, - { 7, "Network Control" }, - { 0, NULL } - }; + static const value_string ieee80211_wfa_ie_wme_tspec_tsinfo_up_vals = {{0, "Best Effort"}, + {1, "Background"}, + {2, "Spare"}, + {3, "Excellent Effort"}, + {4, "Controlled Load"}, + {5, "Video"}, + {6, "Voice"}, + {7, "Network Control"}, + {0, NULL}}; static const value_string hta_ext_chan_offset_flag = { {0x00, "No Extension Channel"}, {0x01, "Extension Channel above control channel"}, {0x02, "Undefined"}, {0x03, "Extension Channel below control channel"}, - {0x00, NULL} - }; + {0x00, NULL}}; static const value_string hta_service_interval_flag = { - {0x00, "5ms"}, - {0x01, "10ms"}, - {0x02, "15ms"}, - {0x03, "20ms"}, - {0x04, "25ms"}, - {0x05, "30ms"}, - {0x06, "35ms"}, - {0x07, "40ms"}, - {0x00, NULL} - }; + {0x00, "5ms"}, {0x01, "10ms"}, {0x02, "15ms"}, {0x03, "20ms"}, {0x04, "25ms"}, + {0x05, "30ms"}, {0x06, "35ms"}, {0x07, "40ms"}, {0x00, NULL}}; static const value_string hta_operating_mode_flag = { {0x00, "Pure HT, no protection"}, {0x01, "There may be non-HT devices (control & ext channel)"}, {0x02, "No non-HT is associated, but at least 1 20MHz is. protect on"}, {0x03, "Mixed: no non-HT is associated, protect on"}, - {0x00, NULL} - }; + {0x00, NULL}}; static const value_string wfa_subtype_vals = { - { WFA_SUBTYPE_P2P, "P2P" }, - { WFA_SUBTYPE_HS20_INDICATION, "Hotspot 2.0 Indication" }, - { WFA_SUBTYPE_HS20_ANQP, "Hotspot 2.0 ANQP" }, - { 0, NULL } - }; + {WFA_SUBTYPE_P2P, "P2P"}, + {WFA_SUBTYPE_HS20_INDICATION, "Hotspot 2.0 Indication"}, + {WFA_SUBTYPE_HS20_ANQP, "Hotspot 2.0 ANQP"}, + {0, NULL}}; - const char * VALS(const value_string &vals, uint v) { - for(const auto &e:vals) { - if(e.first==v && e.second!=NULL) + const char *VALS(const value_string &vals, uint v) { + for (const auto &e : vals) { + if (e.first == v && e.second != NULL) return e.second; } return "unknown"; @@ -692,56 +598,82 @@ namespace OpenWifi { bool bitSet(unsigned char c, uint bit) { switch (bit) { - case 0: return (c & 0x01); - case 1: return (c & 0x02); - case 2: return (c & 0x04); - case 3: return (c & 0x08); - case 4: return (c & 0x10); - case 5: return (c & 0x20); - case 6: return (c & 0x40); - case 7: return (c & 0x90); - default: return false; + case 0: + return (c & 0x01); + case 1: + return (c & 0x02); + case 2: + return (c & 0x04); + case 3: + return (c & 0x08); + case 4: + return (c & 0x10); + case 5: + return (c & 0x20); + case 6: + return (c & 0x40); + case 7: + return (c & 0x90); + default: + return false; } } bool bitSet(uint16_t c, uint bit) { switch (bit) { - case 0: return (c & 0x0001); - case 1: return (c & 0x0002); - case 2: return (c & 0x0004); - case 3: return (c & 0x0008); - case 4: return (c & 0x0010); - case 5: return (c & 0x0020); - case 6: return (c & 0x0040); - case 7: return (c & 0x0080); - case 8: return (c & 0x0100); - case 9: return (c & 0x0200); - case 10: return (c & 0x0400); - case 11: return (c & 0x0800); - case 12: return (c & 0x1000); - case 13: return (c & 0x2000); - case 14: return (c & 0x4000); - case 15: return (c & 0x8000); - default: return false; + case 0: + return (c & 0x0001); + case 1: + return (c & 0x0002); + case 2: + return (c & 0x0004); + case 3: + return (c & 0x0008); + case 4: + return (c & 0x0010); + case 5: + return (c & 0x0020); + case 6: + return (c & 0x0040); + case 7: + return (c & 0x0080); + case 8: + return (c & 0x0100); + case 9: + return (c & 0x0200); + case 10: + return (c & 0x0400); + case 11: + return (c & 0x0800); + case 12: + return (c & 0x1000); + case 13: + return (c & 0x2000); + case 14: + return (c & 0x4000); + case 15: + return (c & 0x8000); + default: + return false; } } std::string BufferToHex(const std::vector &b) { static const char hex[] = "0123456789abcdef"; std::string result; - for(const auto &c:b) { - if(!result.empty()) + for (const auto &c : b) { + if (!result.empty()) result += ' '; - result += (hex[ (c & 0xf0) >> 4]); - result += (hex[ (c & 0x0f) ]); + result += (hex[(c & 0xf0) >> 4]); + result += (hex[(c & 0x0f)]); } return result; } - std::string BufferToHex(const unsigned char *b,uint size, char separator=' ') { + std::string BufferToHex(const unsigned char *b, uint size, char separator = ' ') { static const char hex[] = "0123456789abcdef"; std::string result; - while(size) { + while (size) { if (!result.empty()) result += separator; result += (hex[(*b & 0xf0) >> 4]); @@ -754,8 +686,8 @@ namespace OpenWifi { std::string bitString(unsigned char c) { std::string R; - for(std::size_t i=0;i<8;i++) { - if(c & 0x80) + for (std::size_t i = 0; i < 8; i++) { + if (c & 0x80) R += '1'; else R += '0'; @@ -764,93 +696,96 @@ namespace OpenWifi { return R; } - uint16_t GetUInt16(const unsigned char *d,uint & offset) { - uint16_t value = d[offset] + d[offset+1]*256; - offset +=2; + uint16_t GetUInt16(const unsigned char *d, uint &offset) { + uint16_t value = d[offset] + d[offset + 1] * 256; + offset += 2; return value; } - uint32_t GetUInt32(const unsigned char *d,uint & offset) { - uint32_t value = d[offset+0]+d[offset+1]*256 + d[offset+2]*256*256 + d[offset+3]*256*256*256; - offset +=4; + uint32_t GetUInt32(const unsigned char *d, uint &offset) { + uint32_t value = d[offset + 0] + d[offset + 1] * 256 + d[offset + 2] * 256 * 256 + + d[offset + 3] * 256 * 256 * 256; + offset += 4; return value; } - uint32_t GetUInt32Big(const unsigned char *d,uint & offset) { - uint32_t value = d[offset+3]+d[offset+2]*256 + d[offset+1]*256*256 + d[offset+0]*256*256*256; - offset +=4; + uint32_t GetUInt32Big(const unsigned char *d, uint &offset) { + uint32_t value = d[offset + 3] + d[offset + 2] * 256 + d[offset + 1] * 256 * 256 + + d[offset + 0] * 256 * 256 * 256; + offset += 4; return value; } - uint32_t GetUInt24Big(const unsigned char *d,uint & offset) { - uint32_t value = d[offset+2] + d[offset+1]*256 + d[offset+0]*256*256; - offset +=3; + uint32_t GetUInt24Big(const unsigned char *d, uint &offset) { + uint32_t value = d[offset + 2] + d[offset + 1] * 256 + d[offset + 0] * 256 * 256; + offset += 3; return value; } - uint32_t GetUInt24(const unsigned char *d,uint & offset) { - uint32_t value = d[offset+0] + d[offset+1]*256 + d[offset+2]*256*256; - offset +=3; + uint32_t GetUInt24(const unsigned char *d, uint &offset) { + uint32_t value = d[offset + 0] + d[offset + 1] * 256 + d[offset + 2] * 256 * 256; + offset += 3; return value; } // 0x01 inline nlohmann::json WFS_WLAN_EID_SUPP_RATES(const std::vector &data) { - nlohmann::json Rates = nlohmann::json::array(); - nlohmann::json new_ie; - for(const auto &c:data) { - nlohmann::json Rate; - Rates.push_back(VALS(ieee80211_supported_rates_vals,c)); + nlohmann::json Rates = nlohmann::json::array(); + nlohmann::json new_ie; + for (const auto &c : data) { + nlohmann::json Rate; + Rates.push_back(VALS(ieee80211_supported_rates_vals, c)); } - new_ie["name"]="Supported Rates (Mbps)"; - new_ie["content"]=Rates; - new_ie["type"]=WLAN_EID_SUPP_RATES; + new_ie["name"] = "Supported Rates (Mbps)"; + new_ie["content"] = Rates; + new_ie["type"] = WLAN_EID_SUPP_RATES; return new_ie; } // 0x02 inline nlohmann::json WFS_WLAN_EID_FH_PARAMS(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; - content["Dwell Time"] = (uint64_t) (data[0] * 256 + data[1]); + nlohmann::json new_ie; + nlohmann::json content; + content["Dwell Time"] = (uint64_t)(data[0] * 256 + data[1]); content["Hop Set"] = (uint)data[2]; content["Hop Pattern"] = (uint)data[3]; content["Hop Index"] = (uint)data[4]; - new_ie["name"]="FH Params"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_FH_PARAMS; + new_ie["name"] = "FH Params"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_FH_PARAMS; return new_ie; } // 0x03 inline nlohmann::json WFS_WLAN_EID_DS_PARAMS(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; - content["current_channel"] = (uint64_t) data[0]; - new_ie["name"]="DS Params"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_DS_PARAMS; + nlohmann::json new_ie; + nlohmann::json content; + content["current_channel"] = (uint64_t)data[0]; + new_ie["name"] = "DS Params"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_DS_PARAMS; return new_ie; } // 0x05 inline nlohmann::json WFS_WLAN_EID_TIM(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; - if(data.size()>=4) { - uint offset=0; + nlohmann::json new_ie; + nlohmann::json content; + if (data.size() >= 4) { + uint offset = 0; content["DTIM count"] = (uint64_t)data[offset++]; content["DTIM period"] = (uint64_t)data[offset++]; content["Bitmap control"]["Multicast"] = (uint)data[offset] & 0x01; content["Bitmap control"]["Bitmap Offset"] = (uint)(data[offset] & 0xFe) >> 1; offset++; - if(offset &data) { - nlohmann::json new_ie; - nlohmann::json content; - if(data.size()==4) { + nlohmann::json new_ie; + nlohmann::json content; + if (data.size() == 4) { content["Cisco QBSS Version 1 - non CCA"]["QBSS Version"] = 1; - content["Cisco QBSS Version 1 - non CCA"]["Station Count"] = (uint)( data[2] + data[1]*256); - content["Cisco QBSS Version 1 - non CCA"]["Channel Utilization"] = (uint) data[3]; - content["Cisco QBSS Version 1 - non CCA"]["Available Admission Capabilities"] = (uint) data[4]; - } else if(data.size()==5) { + content["Cisco QBSS Version 1 - non CCA"]["Station Count"] = + (uint)(data[2] + data[1] * 256); + content["Cisco QBSS Version 1 - non CCA"]["Channel Utilization"] = (uint)data[3]; + content["Cisco QBSS Version 1 - non CCA"]["Available Admission Capabilities"] = + (uint)data[4]; + } else if (data.size() == 5) { content["802.11e CCA Version"]["QBSS Version"] = 2; - content["802.11e CCA Version"]["Station Count"] = (uint)( data[2] + data[1]*256); - content["802.11e CCA Version"]["Channel Utilization"] = (uint) data[3]; - content["802.11e CCA Version"]["Available Admission Capabilities"] = (uint) data[4] + data[5]*256; + content["802.11e CCA Version"]["Station Count"] = (uint)(data[2] + data[1] * 256); + content["802.11e CCA Version"]["Channel Utilization"] = (uint)data[3]; + content["802.11e CCA Version"]["Available Admission Capabilities"] = + (uint)data[4] + data[5] * 256; } - new_ie["name"]="QBSS Load"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_QBSS_LOAD; + new_ie["name"] = "QBSS Load"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_QBSS_LOAD; return new_ie; } inline nlohmann::json WFS_WLAN_EID_PWR_CONSTRAINT(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; - content["Local Power Constraint"] = (uint) data[0]; - new_ie["name"]="Local Power Constraint"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_PWR_CONSTRAINT; + nlohmann::json new_ie; + nlohmann::json content; + content["Local Power Constraint"] = (uint)data[0]; + new_ie["name"] = "Local Power Constraint"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_PWR_CONSTRAINT; return new_ie; } inline nlohmann::json WFS_WLAN_EID_ERP_INFO(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; - content["Non ERP Present"] = bitSet(data[0],0); - content["Use Protection"] = bitSet(data[0],1); - content["Barker Preamble Mode"] = bitSet(data[0],2); - new_ie["name"]="ERP Information"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_ERP_INFO; + nlohmann::json new_ie; + nlohmann::json content; + content["Non ERP Present"] = bitSet(data[0], 0); + content["Use Protection"] = bitSet(data[0], 1); + content["Barker Preamble Mode"] = bitSet(data[0], 2); + new_ie["name"] = "ERP Information"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_ERP_INFO; return new_ie; } inline nlohmann::json WFS_WLAN_EID_TPC_REPORT(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; - if(data.size()==2) { - content["Transmit Power"] = (uint) data[0]; - content["Link Margin"] = (uint) data[1]; + nlohmann::json new_ie; + nlohmann::json content; + if (data.size() == 2) { + content["Transmit Power"] = (uint)data[0]; + content["Link Margin"] = (uint)data[1]; } - new_ie["name"]="TPC Report"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_TPC_REPORT; + new_ie["name"] = "TPC Report"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_TPC_REPORT; return new_ie; } - inline nlohmann::json WFS_WLAN_EID_SUPPORTED_REGULATORY_CLASSES(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; - if(data.size()>=2) { - content["Current Regulatory Class"]= (uint) data[0]; + inline nlohmann::json + WFS_WLAN_EID_SUPPORTED_REGULATORY_CLASSES(const std::vector &data) { + nlohmann::json new_ie; + nlohmann::json content; + if (data.size() >= 2) { + content["Current Regulatory Class"] = (uint)data[0]; std::string alternates; - for(uint i=1;i> 4; - content["HT Capabilities Info"]["HT Short GI for 20MHz"] = bitSet(ht_caps,5); - content["HT Capabilities Info"]["HT Short GI for 40MHz"] = bitSet(ht_caps,6); - content["HT Capabilities Info"]["HT Tx STBC"] = bitSet(ht_caps,7); + content["HT Capabilities Info"]["HT Short GI for 20MHz"] = bitSet(ht_caps, 5); + content["HT Capabilities Info"]["HT Short GI for 40MHz"] = bitSet(ht_caps, 6); + content["HT Capabilities Info"]["HT Tx STBC"] = bitSet(ht_caps, 7); content["HT Capabilities Info"]["HT Rx STBC"] = (ht_caps & 0x0300) >> 8; - content["HT Capabilities Info"]["HT Delayed Block ACK"] = bitSet(ht_caps,11); - content["HT Capabilities Info"]["HT Max A-MSDU length"] = bitSet(ht_caps,12); - content["HT Capabilities Info"]["HT PSMP Support"] = bitSet(ht_caps,13); - content["HT Capabilities Info"]["HT Forty MHz Intolerant"] = bitSet(ht_caps,14); - content["HT Capabilities Info"]["HT L-SIG TXOP Protection support"] = bitSet(ht_caps,15); + content["HT Capabilities Info"]["HT Delayed Block ACK"] = bitSet(ht_caps, 11); + content["HT Capabilities Info"]["HT Max A-MSDU length"] = bitSet(ht_caps, 12); + content["HT Capabilities Info"]["HT PSMP Support"] = bitSet(ht_caps, 13); + content["HT Capabilities Info"]["HT Forty MHz Intolerant"] = bitSet(ht_caps, 14); + content["HT Capabilities Info"]["HT L-SIG TXOP Protection support"] = + bitSet(ht_caps, 15); offset += 2; auto ampduparam = data[offset]; @@ -995,187 +937,258 @@ namespace OpenWifi { offset += 16; content["HT Extended Capabilities"]["Transmitter supports PCO"] = data[offset] & 0x01; - content["HT Extended Capabilities"]["Time needed to transition between 20MHz and 40MHz"] = (data[offset] & 0x06) >> 1; + content["HT Extended Capabilities"] + ["Time needed to transition between 20MHz and 40MHz"] = + (data[offset] & 0x06) >> 1; offset++; content["HT Extended Capabilities"]["MCS Feedback capability"] = data[offset] & 0x03; content["HT Extended Capabilities"]["High Throughput"] = (data[offset] & 0x04) >> 2; - content["HT Extended Capabilities"]["Reverse Direction Responder"] = (data[offset] & 0x08) >> 3; + content["HT Extended Capabilities"]["Reverse Direction Responder"] = + (data[offset] & 0x08) >> 3; offset++; - uint32_t caps = data[offset] + data[offset+1]*256 + data[offset+2] * 256 * 256 + data[offset+3] * 256 * 256 * 256 ; + uint32_t caps = data[offset] + data[offset + 1] * 256 + data[offset + 2] * 256 * 256 + + data[offset + 3] * 256 * 256 * 256; - content["Transmit Beam Forming (TxBF) Capabilities"]["Transmit Beamforming"] = (caps & 0x00000001) >> 0; - content["Transmit Beam Forming (TxBF) Capabilities"]["Receive Staggered Sounding"] = (caps & 0x00000002) >> 1; - content["Transmit Beam Forming (TxBF) Capabilities"]["Transmit Staggered Sounding"] = (caps & 0x00000004) >> 2; - content["Transmit Beam Forming (TxBF) Capabilities"]["Receive Null Data packet (NDP)"] = (caps & 0x00000008) >> 3; - content["Transmit Beam Forming (TxBF) Capabilities"]["Transmit Null Data packet (NDP)"] = (caps & 0x00000010) >> 4; - content["Transmit Beam Forming (TxBF) Capabilities"]["Implicit TxBF capable"] = (caps & 0x00000020) >> 5; - content["Transmit Beam Forming (TxBF) Capabilities"]["Calibration"] = VALS(txbf_calib_flag,(caps & 0x000000c0) >> 6); - content["Transmit Beam Forming (TxBF) Capabilities"]["STA can apply TxBF using CSI explicit feedback"] = (caps & 0x00000100) >> 8; - content["Transmit Beam Forming (TxBF) Capabilities"]["STA can apply TxBF using uncompressed beamforming feedback matrix"] = (caps & 0x00000200) >> 9; - content["Transmit Beam Forming (TxBF) Capabilities"]["STA can apply TxBF using compressed beamforming feedback matrix"] = (caps & 0x00000400) >> 10; - content["Transmit Beam Forming (TxBF) Capabilities"]["Receiver can return explicit CSI feedback"] = VALS(txbf_feedback_flags,(caps & 0x00001800) >> 11); - content["Transmit Beam Forming (TxBF) Capabilities"]["Receiver can return explicit uncompressed Beamforming Feedback Matrix"] = VALS(txbf_feedback_flags,(caps & 0x00006000) >>13); - content["Transmit Beam Forming (TxBF) Capabilities"]["STA can compress and use compressed Beamforming Feedback Matrix"] = VALS(txbf_feedback_flags,(caps & 0x00018000) >> 15); - content["Transmit Beam Forming (TxBF) Capabilities"]["Minimal grouping used for explicit feedback reports"] = VALS(txbf_min_group_flags,(caps & 0x00060000) >> 17); - content["Transmit Beam Forming (TxBF) Capabilities"]["Max antennae STA can support when CSI feedback required"] = VALS(txbf_antenna_flags,(caps & 0x00180000) >> 19); - content["Transmit Beam Forming (TxBF) Capabilities"]["Max antennae STA can support when uncompressed Beamforming feedback required"] = VALS(txbf_antenna_flags,(caps & 0x00600000) >> 21); - content["Transmit Beam Forming (TxBF) Capabilities"]["Max antennae STA can support when compressed Beamforming feedback required"] = VALS(txbf_antenna_flags,(caps & 0x01800000) >> 23); - content["Transmit Beam Forming (TxBF) Capabilities"]["Maximum number of rows of CSI explicit feedback"] = VALS(txbf_antenna_flags,(caps & 0x06000000) >> 25); - content["Transmit Beam Forming (TxBF) Capabilities"]["Maximum number of space time streams for which channel dimensions can be simultaneously estimated"] = VALS(txbf_chan_est_flags,(caps & 0x18000000) >> 27); - offset+=4; + content["Transmit Beam Forming (TxBF) Capabilities"]["Transmit Beamforming"] = + (caps & 0x00000001) >> 0; + content["Transmit Beam Forming (TxBF) Capabilities"]["Receive Staggered Sounding"] = + (caps & 0x00000002) >> 1; + content["Transmit Beam Forming (TxBF) Capabilities"]["Transmit Staggered Sounding"] = + (caps & 0x00000004) >> 2; + content["Transmit Beam Forming (TxBF) Capabilities"]["Receive Null Data packet (NDP)"] = + (caps & 0x00000008) >> 3; + content["Transmit Beam Forming (TxBF) Capabilities"] + ["Transmit Null Data packet (NDP)"] = (caps & 0x00000010) >> 4; + content["Transmit Beam Forming (TxBF) Capabilities"]["Implicit TxBF capable"] = + (caps & 0x00000020) >> 5; + content["Transmit Beam Forming (TxBF) Capabilities"]["Calibration"] = + VALS(txbf_calib_flag, (caps & 0x000000c0) >> 6); + content["Transmit Beam Forming (TxBF) Capabilities"] + ["STA can apply TxBF using CSI explicit feedback"] = (caps & 0x00000100) >> 8; + content["Transmit Beam Forming (TxBF) Capabilities"] + ["STA can apply TxBF using uncompressed beamforming feedback matrix"] = + (caps & 0x00000200) >> 9; + content["Transmit Beam Forming (TxBF) Capabilities"] + ["STA can apply TxBF using compressed beamforming feedback matrix"] = + (caps & 0x00000400) >> 10; + content["Transmit Beam Forming (TxBF) Capabilities"] + ["Receiver can return explicit CSI feedback"] = + VALS(txbf_feedback_flags, (caps & 0x00001800) >> 11); + content["Transmit Beam Forming (TxBF) Capabilities"] + ["Receiver can return explicit uncompressed Beamforming Feedback Matrix"] = + VALS(txbf_feedback_flags, (caps & 0x00006000) >> 13); + content["Transmit Beam Forming (TxBF) Capabilities"] + ["STA can compress and use compressed Beamforming Feedback Matrix"] = + VALS(txbf_feedback_flags, (caps & 0x00018000) >> 15); + content["Transmit Beam Forming (TxBF) Capabilities"] + ["Minimal grouping used for explicit feedback reports"] = + VALS(txbf_min_group_flags, (caps & 0x00060000) >> 17); + content["Transmit Beam Forming (TxBF) Capabilities"] + ["Max antennae STA can support when CSI feedback required"] = + VALS(txbf_antenna_flags, (caps & 0x00180000) >> 19); + content + ["Transmit Beam Forming (TxBF) Capabilities"] + ["Max antennae STA can support when uncompressed Beamforming feedback required"] = + VALS(txbf_antenna_flags, (caps & 0x00600000) >> 21); + content["Transmit Beam Forming (TxBF) Capabilities"] + ["Max antennae STA can support when compressed Beamforming feedback required"] = + VALS(txbf_antenna_flags, (caps & 0x01800000) >> 23); + content["Transmit Beam Forming (TxBF) Capabilities"] + ["Maximum number of rows of CSI explicit feedback"] = + VALS(txbf_antenna_flags, (caps & 0x06000000) >> 25); + content["Transmit Beam Forming (TxBF) Capabilities"] + ["Maximum number of space time streams for which channel dimensions can be " + "simultaneously estimated"] = + VALS(txbf_chan_est_flags, (caps & 0x18000000) >> 27); + offset += 4; caps = data[offset]; - content["Antenna Selection (ASEL) Capabilities"]["Antenna Selection Capable"] = (caps & 0x00000001) >> 0; - content["Antenna Selection (ASEL) Capabilities"]["Antenna Selection Capable TXCSI"] = (caps & 0x00000002) >> 1; - content["Antenna Selection (ASEL) Capabilities"]["Antenna Indices Feedback Based Tx ASEL"] = (caps & 0x00000004) >> 2; - content["Antenna Selection (ASEL) Capabilities"]["Explicit CSI Feedback"] = (caps & 0x00000008) >> 3; - content["Antenna Selection (ASEL) Capabilities"]["Antenna Indices Feedback"] = (caps & 0x00000010) >> 4; + content["Antenna Selection (ASEL) Capabilities"]["Antenna Selection Capable"] = + (caps & 0x00000001) >> 0; + content["Antenna Selection (ASEL) Capabilities"]["Antenna Selection Capable TXCSI"] = + (caps & 0x00000002) >> 1; + content["Antenna Selection (ASEL) Capabilities"] + ["Antenna Indices Feedback Based Tx ASEL"] = (caps & 0x00000004) >> 2; + content["Antenna Selection (ASEL) Capabilities"]["Explicit CSI Feedback"] = + (caps & 0x00000008) >> 3; + content["Antenna Selection (ASEL) Capabilities"]["Antenna Indices Feedback"] = + (caps & 0x00000010) >> 4; content["Antenna Selection (ASEL) Capabilities"]["Rx ASEL"] = (caps & 0x00000020) >> 5; - content["Antenna Selection (ASEL) Capabilities"]["Tx Sounding PPDUs"] = (caps & 0x00000040) >> 6; + content["Antenna Selection (ASEL) Capabilities"]["Tx Sounding PPDUs"] = + (caps & 0x00000040) >> 6; } - } - void dissect_ht_info_ie_1_0(const unsigned char *data, uint size, nlohmann::json & content) - { + void dissect_ht_info_ie_1_0(const unsigned char *data, uint size, nlohmann::json &content) { if (size != 22) { return; } - uint offset=0; + uint offset = 0; content["HT Control Channel"] = data[offset++]; auto htcaps = data[offset++]; - content["HT Additional Capabilities"]["Extension Channel Offset"] = VALS(hta_ext_chan_offset_flag, htcaps & 0x0003); - content["HT Additional Capabilities"]["Recommended Tx Channel Width"] = (htcaps & 0x0003) >> 2; - content["HT Additional Capabilities"]["Reduced Interframe Spacing (RIFS) Mode"] = (htcaps & 0x0008) >> 3; + content["HT Additional Capabilities"]["Extension Channel Offset"] = + VALS(hta_ext_chan_offset_flag, htcaps & 0x0003); + content["HT Additional Capabilities"]["Recommended Tx Channel Width"] = + (htcaps & 0x0003) >> 2; + content["HT Additional Capabilities"]["Reduced Interframe Spacing (RIFS) Mode"] = + (htcaps & 0x0008) >> 3; content["HT Additional Capabilities"]["Controlled Access Only"] = (htcaps & 0x0010) >> 4; - content["HT Additional Capabilities"]["Service Interval Granularity"] = VALS(hta_service_interval_flag, (htcaps & 0x00e0) >> 5); + content["HT Additional Capabilities"]["Service Interval Granularity"] = + VALS(hta_service_interval_flag, (htcaps & 0x00e0) >> 5); - htcaps = GetUInt16(data,offset); - content["HT Additional Capabilities"]["Operating Mode"] = VALS(hta_operating_mode_flag, (htcaps & 0x0003) >> 0); - content["HT Additional Capabilities"]["Non Greenfield (GF) devices Present"] = (htcaps & 0x0004) >> 2; + htcaps = GetUInt16(data, offset); + content["HT Additional Capabilities"]["Operating Mode"] = + VALS(hta_operating_mode_flag, (htcaps & 0x0003) >> 0); + content["HT Additional Capabilities"]["Non Greenfield (GF) devices Present"] = + (htcaps & 0x0004) >> 2; - htcaps = GetUInt16(data,offset); - content["HT Additional Capabilities"]["Basic STB Modulation and Coding Scheme (MCS)"] = (htcaps & 0x007f) >> 0; - content["HT Additional Capabilities"]["Dual Clear To Send (CTS) Protection"] = (htcaps & 0x0080) >> 7; + htcaps = GetUInt16(data, offset); + content["HT Additional Capabilities"]["Basic STB Modulation and Coding Scheme (MCS)"] = + (htcaps & 0x007f) >> 0; + content["HT Additional Capabilities"]["Dual Clear To Send (CTS) Protection"] = + (htcaps & 0x0080) >> 7; content["HT Additional Capabilities"]["Secondary Beacon"] = (htcaps & 0x0100) >> 8; - content["HT Additional Capabilities"]["L-SIG TXOP Protection Support"] = (htcaps & 0x0200) >> 9; - content["HT Additional Capabilities"]["Phased Coexistence Operation (PCO) Active"] = (htcaps & 0x0400) >> 10; - content["HT Additional Capabilities"]["Phased Coexistence Operation (PCO) Phase"] = (htcaps & 0x0800) >> 11; - ParseMCSset(&data[offset],content); + content["HT Additional Capabilities"]["L-SIG TXOP Protection Support"] = + (htcaps & 0x0200) >> 9; + content["HT Additional Capabilities"]["Phased Coexistence Operation (PCO) Active"] = + (htcaps & 0x0400) >> 10; + content["HT Additional Capabilities"]["Phased Coexistence Operation (PCO) Phase"] = + (htcaps & 0x0800) >> 11; + ParseMCSset(&data[offset], content); } inline nlohmann::json WFS_WLAN_EID_HT_CAPABILITY(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; + nlohmann::json new_ie; + nlohmann::json content; - if(data.size()==26) { - dissect_ht_capability_ie(&data[0],data.size(),content); + if (data.size() == 26) { + dissect_ht_capability_ie(&data[0], data.size(), content); } - new_ie["name"]="HT Capabilities"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_HT_CAPABILITY; + new_ie["name"] = "HT Capabilities"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_HT_CAPABILITY; return new_ie; } inline nlohmann::json WFS_WLAN_EID_EXT_SUPP_RATES(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; + nlohmann::json new_ie; + nlohmann::json content; std::string Rates; - for(const auto &rate:data) { - if(!Rates.empty()) + for (const auto &rate : data) { + if (!Rates.empty()) Rates += ", "; - Rates += VALS(ieee80211_supported_rates_vals,rate); + Rates += VALS(ieee80211_supported_rates_vals, rate); } - Rates += " [Mbit/sec]"; + Rates += " [Mbit/sec]"; content["Supported Rates"] = Rates; - new_ie["name"]="Supported Rates"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_EXT_SUPP_RATES; + new_ie["name"] = "Supported Rates"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_EXT_SUPP_RATES; return new_ie; } inline nlohmann::json WFS_WLAN_EID_TX_POWER_ENVELOPE(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; + nlohmann::json new_ie; + nlohmann::json content; - if(data.size()>=2 && data.size()<=5) { + if (data.size() >= 2 && data.size() <= 5) { auto len = data[0]; - for(uint i=0;i<=len;i++) { - switch(i) { + for (uint i = 0; i <= len; i++) { + switch (i) { case 0: - content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 20MHz"] = (uint16_t) data[i+1]; + content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 20MHz"] = + (uint16_t)data[i + 1]; break; case 1: - content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 40MHz"] = (uint16_t) data[i+1]; + content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 40MHz"] = + (uint16_t)data[i + 1]; break; case 2: - content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 80MHz"] = (uint16_t) data[i+1]; + content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 80MHz"] = + (uint16_t)data[i + 1]; break; case 3: - content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 160MHz/80+80 MHz"] = (uint16_t) data[i+1]; + content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 160MHz/80+80 MHz"] = + (uint16_t)data[i + 1]; break; default: - content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 160MHz/80+80 MHz"] = (uint16_t) 0xff; + content["Tx Pwr Info"]["Local Max Tx Pwr Constraint 160MHz/80+80 MHz"] = + (uint16_t)0xff; } } } - new_ie["name"]="Tx Pwr Info"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_TX_POWER_ENVELOPE; + new_ie["name"] = "Tx Pwr Info"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_TX_POWER_ENVELOPE; return new_ie; } inline nlohmann::json WFS_WLAN_EID_VHT_CAPABILITY(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; + nlohmann::json new_ie; + nlohmann::json content; - if(data.size()==12) { - uint offset=0; - uint caps = data[offset] + data[offset+1]* 256 + data[offset+2]*256*256 + data[offset+3]*256*256*256; + if (data.size() == 12) { + uint offset = 0; + uint caps = data[offset] + data[offset + 1] * 256 + data[offset + 2] * 256 * 256 + + data[offset + 3] * 256 * 256 * 256; - content["VHT Capabilities Info"]["Maximum MPDU Length"] = VALS(vht_max_mpdu_length_flag, (caps & 0x00000003) >> 0 ); - content["VHT Capabilities Info"]["Supported Channel Width Set"] = VALS(vht_supported_chan_width_set_flag, (caps & 0x0000000c) >> 2 ); - content["VHT Capabilities Info"]["Rx LDPC"] = (caps & 0x00000010) >> 4 ; - content["VHT Capabilities Info"]["Short GI for 80MHz"] = (caps & 0x00000020) >> 5 ; - content["VHT Capabilities Info"]["Short GI for 160MHz and 80+80MHz"] = (caps & 0x00000040) >> 6 ; - content["VHT Capabilities Info"]["Tx STBC"] = (caps & 0x00000080) >> 7 ; + content["VHT Capabilities Info"]["Maximum MPDU Length"] = + VALS(vht_max_mpdu_length_flag, (caps & 0x00000003) >> 0); + content["VHT Capabilities Info"]["Supported Channel Width Set"] = + VALS(vht_supported_chan_width_set_flag, (caps & 0x0000000c) >> 2); + content["VHT Capabilities Info"]["Rx LDPC"] = (caps & 0x00000010) >> 4; + content["VHT Capabilities Info"]["Short GI for 80MHz"] = (caps & 0x00000020) >> 5; + content["VHT Capabilities Info"]["Short GI for 160MHz and 80+80MHz"] = + (caps & 0x00000040) >> 6; + content["VHT Capabilities Info"]["Tx STBC"] = (caps & 0x00000080) >> 7; - content["VHT Capabilities Info"]["Rx STBC"] = VALS(vht_rx_stbc_flag,(caps & 0x00000700) >> 8) ; - content["VHT Capabilities Info"]["SU Beam-former Capable"] = (caps & 0x00000800) >> 11 ; - content["VHT Capabilities Info"]["SU Beam-formee Capable"] = (caps & 0x00001000) >> 12 ; - content["VHT Capabilities Info"]["Compressed Steering Number of Beamformer Antennas Supported"] = VALS(num_plus_one_3bit_flag,(caps & 0x0000e000) >> 13) ; + content["VHT Capabilities Info"]["Rx STBC"] = + VALS(vht_rx_stbc_flag, (caps & 0x00000700) >> 8); + content["VHT Capabilities Info"]["SU Beam-former Capable"] = (caps & 0x00000800) >> 11; + content["VHT Capabilities Info"]["SU Beam-formee Capable"] = (caps & 0x00001000) >> 12; + content["VHT Capabilities Info"] + ["Compressed Steering Number of Beamformer Antennas Supported"] = + VALS(num_plus_one_3bit_flag, (caps & 0x0000e000) >> 13); - content["VHT Capabilities Info"]["Number of Sounding Dimensions"] = VALS(num_plus_one_3bit_flag,(caps & 0x00070000) >> 16); - content["VHT Capabilities Info"]["MU Beam-former Capable"] = VALS(num_plus_one_3bit_flag,(caps & 0x00080000) >> 17); + content["VHT Capabilities Info"]["Number of Sounding Dimensions"] = + VALS(num_plus_one_3bit_flag, (caps & 0x00070000) >> 16); + content["VHT Capabilities Info"]["MU Beam-former Capable"] = + VALS(num_plus_one_3bit_flag, (caps & 0x00080000) >> 17); content["VHT Capabilities Info"]["MU Beam-formee Capable"] = (caps & 0x00200000) >> 18; content["VHT Capabilities Info"]["VHT TXOP PS"] = (caps & 0x00400000) >> 19; - content["VHT Capabilities Info"]["HTC-VHT Capable VHT variant HT Control field"] = (caps & 0x00400000) >> 20; + content["VHT Capabilities Info"]["HTC-VHT Capable VHT variant HT Control field"] = + (caps & 0x00400000) >> 20; - content["VHT Capabilities Info"]["Max A-MPDU Length"] = VALS(vht_max_ampdu_flag,(caps & 0x03800000) >> 21); - content["VHT Capabilities Info"]["VHT Link Adaptation"] = VALS(vht_link_adapt_flag,(caps & 0x0c000000) >> 24); + content["VHT Capabilities Info"]["Max A-MPDU Length"] = + VALS(vht_max_ampdu_flag, (caps & 0x03800000) >> 21); + content["VHT Capabilities Info"]["VHT Link Adaptation"] = + VALS(vht_link_adapt_flag, (caps & 0x0c000000) >> 24); - content["VHT Capabilities Info"]["Rx Antenna Pattern Consistency"] = (caps & 0x10000000) >> 28; - content["VHT Capabilities Info"]["Tx Antenna Pattern Consistency"] = (caps & 0x20000000) >> 29; + content["VHT Capabilities Info"]["Rx Antenna Pattern Consistency"] = + (caps & 0x10000000) >> 28; + content["VHT Capabilities Info"]["Tx Antenna Pattern Consistency"] = + (caps & 0x20000000) >> 29; offset += 4; - ParseMCSset(&data[offset],content); + ParseMCSset(&data[offset], content); } - new_ie["name"]="VHT Capabilities Info"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_VHT_CAPABILITY; + new_ie["name"] = "VHT Capabilities Info"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_VHT_CAPABILITY; return new_ie; } - inline nlohmann::json WFS_WLAN_EID_RRM_ENABLED_CAPABILITIES(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; + inline nlohmann::json + WFS_WLAN_EID_RRM_ENABLED_CAPABILITIES(const std::vector &data) { + nlohmann::json new_ie; + nlohmann::json content; - if(data.size()==5) { - uint offset=0; + if (data.size() == 5) { + uint offset = 0; uint caps = data[offset++]; content["RM Capabilities"]["Link Measurement"] = (caps & 0x00000001) >> 0; content["RM Capabilities"]["Neighbor Report"] = (caps & 0x00000002) >> 1; @@ -1184,7 +1197,8 @@ namespace OpenWifi { content["RM Capabilities"]["Beacon Passive Measurement"] = (caps & 0x00000010) >> 4; content["RM Capabilities"]["Beacon Active Measurement"] = (caps & 0x00000020) >> 5; content["RM Capabilities"]["Beacon Table Measurement"] = (caps & 0x00000040) >> 6; - content["RM Capabilities"]["Beacon Measurement Reporting Conditions"] = (caps & 0x00000080) >> 7; + content["RM Capabilities"]["Beacon Measurement Reporting Conditions"] = + (caps & 0x00000080) >> 7; caps = data[offset++]; content["RM Capabilities"]["Frame Measurement"] = (caps & 0x00000001) >> 0; @@ -1193,14 +1207,18 @@ namespace OpenWifi { content["RM Capabilities"]["Statistics Measurement"] = (caps & 0x00000008) >> 3; content["RM Capabilities"]["LCI Measurement"] = (caps & 0x00000010) >> 4; content["RM Capabilities"]["LCI Azimuth capability"] = (caps & 0x00000020) >> 5; - content["RM Capabilities"]["Transmit Stream/Category Measurement"] = (caps & 0x00000040) >> 6; - content["RM Capabilities"]["Triggered Transmit Stream/Category Measurement"] = (caps & 0x00000080) >> 7; + content["RM Capabilities"]["Transmit Stream/Category Measurement"] = + (caps & 0x00000040) >> 6; + content["RM Capabilities"]["Triggered Transmit Stream/Category Measurement"] = + (caps & 0x00000080) >> 7; caps = data[offset++]; content["RM Capabilities"]["AP Channel Report capability"] = (caps & 0x00000007) >> 0; content["RM Capabilities"]["RM MIB capability"] = (caps & 0x00000002) >> 1; - content["RM Capabilities"]["Operating Channel Max Measurement Duration"] = (caps & 0x0000001c) >> 2; - content["RM Capabilities"]["Nonoperating Channel Max Measurement Duration"] = (caps & 0x000000e0) >> 5; + content["RM Capabilities"]["Operating Channel Max Measurement Duration"] = + (caps & 0x0000001c) >> 2; + content["RM Capabilities"]["Nonoperating Channel Max Measurement Duration"] = + (caps & 0x000000e0) >> 5; caps = data[offset++]; content["RM Capabilities"]["Measurement Pilotcapability"] = (caps & 0x00000007) >> 0; @@ -1208,28 +1226,32 @@ namespace OpenWifi { content["RM Capabilities"]["Neighbor Report TSF Offset"] = (caps & 0x00000010) >> 4; content["RM Capabilities"]["RCPI Measurement capability"] = (caps & 0x00000020) >> 5; content["RM Capabilities"]["RSNI Measurement capability"] = (caps & 0x00000040) >> 6; - content["RM Capabilities"]["BSS Average Access Delay capability"] = (caps & 0x00000080) >> 7; + content["RM Capabilities"]["BSS Average Access Delay capability"] = + (caps & 0x00000080) >> 7; caps = data[offset]; - content["RM Capabilities"]["BSS Available Admission Capacity capability"] = (caps & 0x00000001) >> 0; + content["RM Capabilities"]["BSS Available Admission Capacity capability"] = + (caps & 0x00000001) >> 0; content["RM Capabilities"]["Antenna capability"] = (caps & 0x00000002) >> 1; } - new_ie["name"]="RM Capabilities"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_RRM_ENABLED_CAPABILITIES; + new_ie["name"] = "RM Capabilities"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_RRM_ENABLED_CAPABILITIES; return new_ie; } inline nlohmann::json WFS_WLAN_EID_EXT_CAPABILITY(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; + nlohmann::json new_ie; + nlohmann::json content; - if(data.size()>=1) { - uint offset=0; - content["Extended Capabilities"]["20/40 BSS Coexistence Management Support"] = (data[offset] & 0x01) >> 0; + if (data.size() >= 1) { + uint offset = 0; + content["Extended Capabilities"]["20/40 BSS Coexistence Management Support"] = + (data[offset] & 0x01) >> 0; content["Extended Capabilities"]["On-demand beacon"] = (data[offset] & 0x02) >> 1; - content["Extended Capabilities"]["Extended Channel Switching"] = (data[offset] & 0x04) >> 2; + content["Extended Capabilities"]["Extended Channel Switching"] = + (data[offset] & 0x04) >> 2; content["Extended Capabilities"]["WAVE indication"] = (data[offset] & 0x08) >> 3; content["Extended Capabilities"]["PSMP Capability"] = (data[offset] & 0x10) >> 4; content["Extended Capabilities"]["Reserved"] = (data[offset] & 0x20) >> 5; @@ -1237,43 +1259,50 @@ namespace OpenWifi { content["Extended Capabilities"]["Event"] = (data[offset] & 0x80) >> 7; offset++; - if(offset> 0; - content["Extended Capabilities"]["Multicast Diagnostics"] = (data[offset] & 0x02) >> 1; + content["Extended Capabilities"]["Multicast Diagnostics"] = + (data[offset] & 0x02) >> 1; content["Extended Capabilities"]["Location Tracking"] = (data[offset] & 0x04) >> 2; content["Extended Capabilities"]["FMS"] = (data[offset] & 0x08) >> 3; content["Extended Capabilities"]["Proxy ARP Service"] = (data[offset] & 0x10) >> 4; - content["Extended Capabilities"]["Collocated Interference Reporting"] = (data[offset] & 0x20) >> 5; + content["Extended Capabilities"]["Collocated Interference Reporting"] = + (data[offset] & 0x20) >> 5; content["Extended Capabilities"]["Civic Location"] = (data[offset] & 0x40) >> 6; - content["Extended Capabilities"]["Geospatial Location"] = (data[offset] & 0x80) >> 7; + content["Extended Capabilities"]["Geospatial Location"] = + (data[offset] & 0x80) >> 7; } offset++; - if(offset> 0; content["Extended Capabilities"]["WNM-Sleep Mode"] = (data[offset] & 0x02) >> 1; content["Extended Capabilities"]["TIM Broadcast"] = (data[offset] & 0x04) >> 2; content["Extended Capabilities"]["BSS Transition"] = (data[offset] & 0x08) >> 3; - content["Extended Capabilities"]["QoS Traffic Capability"] = (data[offset] & 0x10) >> 4; + content["Extended Capabilities"]["QoS Traffic Capability"] = + (data[offset] & 0x10) >> 4; content["Extended Capabilities"]["AC Station Count"] = (data[offset] & 0x20) >> 5; content["Extended Capabilities"]["Multiple BSSID"] = (data[offset] & 0x40) >> 6; content["Extended Capabilities"]["Timing Measurement"] = (data[offset] & 0x80) >> 7; } offset++; - if(offset> 0; content["Extended Capabilities"]["SSID List"] = (data[offset] & 0x02) >> 1; content["Extended Capabilities"]["DMS"] = (data[offset] & 0x04) >> 2; content["Extended Capabilities"]["UTC TSF Offset"] = (data[offset] & 0x08) >> 3; - content["Extended Capabilities"]["Peer U-APSD Buffer STA Support"] = (data[offset] & 0x10) >> 4; - content["Extended Capabilities"]["TDLS Peer PSM Support"] = (data[offset] & 0x20) >> 5; - content["Extended Capabilities"]["TDLS channel switching"] = (data[offset] & 0x40) >> 6; + content["Extended Capabilities"]["Peer U-APSD Buffer STA Support"] = + (data[offset] & 0x10) >> 4; + content["Extended Capabilities"]["TDLS Peer PSM Support"] = + (data[offset] & 0x20) >> 5; + content["Extended Capabilities"]["TDLS channel switching"] = + (data[offset] & 0x40) >> 6; content["Extended Capabilities"]["Interworking"] = (data[offset] & 0x80) >> 7; } offset++; - if(offset> 0; content["Extended Capabilities"]["EBR"] = (data[offset] & 0x02) >> 1; content["Extended Capabilities"]["SSPN Interface"] = (data[offset] & 0x04) >> 2; @@ -1281,47 +1310,51 @@ namespace OpenWifi { content["Extended Capabilities"]["MSGCF Capability"] = (data[offset] & 0x10) >> 4; content["Extended Capabilities"]["TDLS support"] = (data[offset] & 0x20) >> 5; content["Extended Capabilities"]["TDLS Prohibited"] = (data[offset] & 0x40) >> 6; - content["Extended Capabilities"]["TDLS Channel Switching Prohibited"] = (data[offset] & 0x80) >> 7; + content["Extended Capabilities"]["TDLS Channel Switching Prohibited"] = + (data[offset] & 0x80) >> 7; } offset++; - if(offset> 0; - content["Extended Capabilities"]["Service Interval Granularity"] = VALS(service_interval_granularity_vals,(data[offset] & 0x0e) >> 1); - content["Extended Capabilities"]["Identifier Location"] = (data[offset] & 0x10) >> 4; + if (offset < data.size()) { + content["Extended Capabilities"]["Reject Unadmitted Frame"] = + (data[offset] & 0x01) >> 0; + content["Extended Capabilities"]["Service Interval Granularity"] = + VALS(service_interval_granularity_vals, (data[offset] & 0x0e) >> 1); + content["Extended Capabilities"]["Identifier Location"] = + (data[offset] & 0x10) >> 4; content["Extended Capabilities"]["U-APSD Coexistence"] = (data[offset] & 0x20) >> 5; content["Extended Capabilities"]["WNM-Notification"] = (data[offset] & 0x40) >> 6; content["Extended Capabilities"]["Reserved"] = (data[offset] & 0x80) >> 7; } offset++; - if(offset> 0; } } - new_ie["name"]="Extended Capabilities"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_EXT_CAPABILITY; + new_ie["name"] = "Extended Capabilities"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_EXT_CAPABILITY; return new_ie; } inline nlohmann::json WFS_WLAN_EID_RSN(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; + nlohmann::json new_ie; + nlohmann::json content; // 01 00 00 0f ac 04 01 00 00 0f ac 04 02 00 00 0f ac 02 00 0f ac 06 8c 00 - uint offset = 0 ; - content["RSN Version"] = GetUInt16(&data[0],offset); - auto RSNOUI = GetUInt24Big(&data[0],offset); - content["Group Cipher Suite OUI"] = BufferToHex(&data[offset-3],3,':'); - if(RSNOUI==OUI_RSN) { - content["Group Cipher Suite type"] = VALS(ieee80211_rsn_cipher_vals,data[offset++]); + uint offset = 0; + content["RSN Version"] = GetUInt16(&data[0], offset); + auto RSNOUI = GetUInt24Big(&data[0], offset); + content["Group Cipher Suite OUI"] = BufferToHex(&data[offset - 3], 3, ':'); + if (RSNOUI == OUI_RSN) { + content["Group Cipher Suite type"] = VALS(ieee80211_rsn_cipher_vals, data[offset++]); } else { - content["Group Cipher Suite type"] = BufferToHex(&data[offset++],1); + content["Group Cipher Suite type"] = BufferToHex(&data[offset++], 1); } - if(offset> 0; content["RSN Capabilities"]["RSN No Pairwise capabilities"] = (rsn_cap & 0x0002) >> 1; @@ -1380,90 +1414,91 @@ namespace OpenWifi { content["RSN Capabilities"]["PeerKey Enabled"] = (rsn_cap & 0x0200) >> 9; } - if(offset+2<=data.size()) { - auto pmkid_count = GetUInt16(&data[0],offset); + if (offset + 2 <= data.size()) { + auto pmkid_count = GetUInt16(&data[0], offset); content["PMKID Count"] = pmkid_count; - if(offset+pmkid_count*16<=data.size()) { - nlohmann::json list=nlohmann::json::array(); - while(pmkid_count) { + if (offset + pmkid_count * 16 <= data.size()) { + nlohmann::json list = nlohmann::json::array(); + while (pmkid_count) { nlohmann::json entry; - entry["PMKID"] = BufferToHex(&data[offset],16); + entry["PMKID"] = BufferToHex(&data[offset], 16); list.push_back(entry); pmkid_count--; - offset+=16; + offset += 16; } - content["PMKID List"]=list; + content["PMKID List"] = list; } } - if(offset+4<=data.size()) { - RSNOUI = GetUInt24Big(&data[0],offset); - content["Group Management Cipher Suite"]["Group Management Cipher Suite OUI"] = BufferToHex(&data[offset-3],3,':'); - if(RSNOUI==OUI_RSN) { - content["Group Management Cipher Suite"]["Group Management Cipher Suite type"] = VALS(ieee80211_rsn_cipher_vals,data[offset++]); + if (offset + 4 <= data.size()) { + RSNOUI = GetUInt24Big(&data[0], offset); + content["Group Management Cipher Suite"]["Group Management Cipher Suite OUI"] = + BufferToHex(&data[offset - 3], 3, ':'); + if (RSNOUI == OUI_RSN) { + content["Group Management Cipher Suite"]["Group Management Cipher Suite type"] = + VALS(ieee80211_rsn_cipher_vals, data[offset++]); } else { - content["Group Management Cipher Suite"]["Group Management Cipher Suite type"] = BufferToHex(&data[offset++],1); + content["Group Management Cipher Suite"]["Group Management Cipher Suite type"] = + BufferToHex(&data[offset++], 1); } } - new_ie["name"]="RSN"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_RSN; + new_ie["name"] = "RSN"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_RSN; return new_ie; } - inline nlohmann::json - dissect_qos_info(const unsigned char *b,uint l) - { + inline nlohmann::json dissect_qos_info(const unsigned char *b, uint l) { nlohmann::json content; - if(l<1) + if (l < 1) return content; auto ftype = MGT_PROBE_REQ; switch (ftype) { - case MGT_ASSOC_REQ: - case MGT_PROBE_REQ: - case MGT_REASSOC_REQ: - { - /* To AP so decode as per WMM standard Figure 7 QoS Info field when sent from WMM STA*/ - content["WME QoS Info"]["Max SP Length"] = VALS(ieee802111_wfa_ie_wme_qos_info_sta_max_sp_length_vals,(*b & 0x60) >> 5); - content["WME QoS Info"]["AC_BE"] = (*b & 0x08) >> 3; - content["WME QoS Info"]["AC_BK"] = (*b & 0x04) >> 2; - content["WME QoS Info"]["AC_VI"] = (*b & 0x02) >> 1; - content["WME QoS Info"]["AC_VO"] = (*b & 0x01) >> 0; - break; - } - case MGT_BEACON: - case MGT_PROBE_RESP: - case MGT_ASSOC_RESP: - case MGT_REASSOC_RESP: - { - /* From AP so decode as per WMM standard Figure 6 QoS Info field when sent from WMM AP */ - content["WME QoS Info"]["U-APSD"] = (*b & 0x80) >> 4; - content["WME QoS Info"]["Parameter Set Count"] = (*b & 0x0f) >> 0; - break; - } - default: - content["WME QoS Info"]["invalid"] = true; - break; + case MGT_ASSOC_REQ: + case MGT_PROBE_REQ: + case MGT_REASSOC_REQ: { + /* To AP so decode as per WMM standard Figure 7 QoS Info field when sent from WMM STA*/ + content["WME QoS Info"]["Max SP Length"] = + VALS(ieee802111_wfa_ie_wme_qos_info_sta_max_sp_length_vals, (*b & 0x60) >> 5); + content["WME QoS Info"]["AC_BE"] = (*b & 0x08) >> 3; + content["WME QoS Info"]["AC_BK"] = (*b & 0x04) >> 2; + content["WME QoS Info"]["AC_VI"] = (*b & 0x02) >> 1; + content["WME QoS Info"]["AC_VO"] = (*b & 0x01) >> 0; + break; + } + case MGT_BEACON: + case MGT_PROBE_RESP: + case MGT_ASSOC_RESP: + case MGT_REASSOC_RESP: { + /* From AP so decode as per WMM standard Figure 6 QoS Info field when sent from WMM AP + */ + content["WME QoS Info"]["U-APSD"] = (*b & 0x80) >> 4; + content["WME QoS Info"]["Parameter Set Count"] = (*b & 0x0f) >> 0; + break; + } + default: + content["WME QoS Info"]["invalid"] = true; + break; } return content; } inline nlohmann::json dissect_vendor_ie_wpawme(const unsigned char *b, uint l) { nlohmann::json ie; - uint offset=0; + uint offset = 0; // ie["dump"] = BufferToHex(b,l); ie["vendor"] = "Wi-Fi : WPA / WME"; auto type = b[0]; - ie["type"] = VALS(ieee802111_wfa_ie_type_vals,type); + ie["type"] = VALS(ieee802111_wfa_ie_type_vals, type); offset++; - if(offset> 5); + entry["Admission Control Mandatory"] = (b[offset] & 0x10) >> 4; + entry["AIFSN"] = (b[offset] & 0x0f) >> 5; offset++; - offset++; // skip reserved... - nlohmann::json list=nlohmann::json::array(); - for(uint i=0;i<4;i++) { - nlohmann::json entry; - entry["ACI"] = VALS(ieee80211_wfa_ie_wme_acs_vals, (b[offset] & 0x60)>>5); - entry["Admission Control Mandatory"] = (b[offset] & 0x10) >> 4; - entry["AIFSN"] = (b[offset] & 0x0f)>>5; - offset++; - entry["ECW Max"] = (b[offset] & 0xf0)>>4; - entry["ECW Min"] = (b[offset] & 0x0f)>>0; - offset++; - entry["TXOP Limit"] = b[offset] + b[offset+1]*256; - offset+=2; - list.push_back(entry); - } - ie["Ac Parameters"]["ACI / AIFSN Field"] = list; - } - break; - case 2: { - auto tid = GetUInt24(b,offset); - ie["TS Info"]["TID"] = (tid & 0x00001E) >> 1; - ie["TS Info"]["Direction"] = VALS(ieee80211_wfa_ie_wme_tspec_tsinfo_direction_vals,(tid & 0x000060) >> 5); - ie["TS Info"]["PSB"] = VALS(ieee80211_wfa_ie_wme_tspec_tsinfo_psb_vals, (tid & 0x000400) >> 10); - ie["TS Info"]["UP"] = VALS(ieee80211_wfa_ie_wme_tspec_tsinfo_up_vals,(tid & 0x003800) >> 11); - ie["TS Info"]["Normal MSDU Size"] = GetUInt16(b,offset); - ie["TS Info"]["Maximum MSDU Size"] = GetUInt16(b,offset); - ie["TS Info"]["Minimum Service Interval"] = GetUInt32(b,offset); - ie["TS Info"]["Maximum Service Interval"] = GetUInt32(b,offset); - ie["TS Info"]["Inactivity Interval"] = GetUInt32(b,offset); - ie["TS Info"]["Suspension Interval"] = GetUInt32(b,offset); - ie["TS Info"]["Service Start Time"] = GetUInt32(b,offset); - ie["TS Info"]["Minimum Data Rate"] = GetUInt32(b,offset); - ie["TS Info"]["Mean Data Rate"] = GetUInt32(b,offset); - ie["TS Info"]["Peak Data Rate"] = GetUInt32(b,offset); - ie["TS Info"]["Burst Size"] = GetUInt32(b,offset); - ie["TS Info"]["Delay Bound"] = GetUInt32(b,offset); - ie["TS Info"]["Minimum PHY Rate"] = GetUInt32(b,offset); - ie["TS Info"]["Surplus Bandwidth Allowance"] = GetUInt16(b,offset); - ie["TS Info"]["Medium Time"] = GetUInt16(b,offset); - } - break; - default: - break; + entry["ECW Max"] = (b[offset] & 0xf0) >> 4; + entry["ECW Min"] = (b[offset] & 0x0f) >> 0; + offset++; + entry["TXOP Limit"] = b[offset] + b[offset + 1] * 256; + offset += 2; + list.push_back(entry); + } + ie["Ac Parameters"]["ACI / AIFSN Field"] = list; + } break; + case 2: { + auto tid = GetUInt24(b, offset); + ie["TS Info"]["TID"] = (tid & 0x00001E) >> 1; + ie["TS Info"]["Direction"] = VALS( + ieee80211_wfa_ie_wme_tspec_tsinfo_direction_vals, (tid & 0x000060) >> 5); + ie["TS Info"]["PSB"] = + VALS(ieee80211_wfa_ie_wme_tspec_tsinfo_psb_vals, (tid & 0x000400) >> 10); + ie["TS Info"]["UP"] = + VALS(ieee80211_wfa_ie_wme_tspec_tsinfo_up_vals, (tid & 0x003800) >> 11); + ie["TS Info"]["Normal MSDU Size"] = GetUInt16(b, offset); + ie["TS Info"]["Maximum MSDU Size"] = GetUInt16(b, offset); + ie["TS Info"]["Minimum Service Interval"] = GetUInt32(b, offset); + ie["TS Info"]["Maximum Service Interval"] = GetUInt32(b, offset); + ie["TS Info"]["Inactivity Interval"] = GetUInt32(b, offset); + ie["TS Info"]["Suspension Interval"] = GetUInt32(b, offset); + ie["TS Info"]["Service Start Time"] = GetUInt32(b, offset); + ie["TS Info"]["Minimum Data Rate"] = GetUInt32(b, offset); + ie["TS Info"]["Mean Data Rate"] = GetUInt32(b, offset); + ie["TS Info"]["Peak Data Rate"] = GetUInt32(b, offset); + ie["TS Info"]["Burst Size"] = GetUInt32(b, offset); + ie["TS Info"]["Delay Bound"] = GetUInt32(b, offset); + ie["TS Info"]["Minimum PHY Rate"] = GetUInt32(b, offset); + ie["TS Info"]["Surplus Bandwidth Allowance"] = GetUInt16(b, offset); + ie["TS Info"]["Medium Time"] = GetUInt16(b, offset); + } break; + default: + break; } } break; case 4: { - ie["TLV Block"] = BufferToHex(&b[offset],l-offset); + ie["TLV Block"] = BufferToHex(&b[offset], l - offset); } break; default: - ie["Data"] = BufferToHex(&b[1],l-1); + ie["Data"] = BufferToHex(&b[1], l - 1); break; } } @@ -1582,13 +1617,12 @@ namespace OpenWifi { nlohmann::json ie; ie["vendor"] = "Wi-Fi : RSN"; - switch(b[0]) { + switch (b[0]) { case 4: { - ie["RSN PMKID"] = BufferToHex(&b[1],16); - } - break; + ie["RSN PMKID"] = BufferToHex(&b[1], 16); + } break; default: - ie["RSN Unknown"] = BufferToHex(&b[1],l-1); + ie["RSN Unknown"] = BufferToHex(&b[1], l - 1); break; } return ie; @@ -1599,17 +1633,15 @@ namespace OpenWifi { ie["vendor"] = "Wi-Fi : 802.11 Pre-N"; --l; auto type = b[0]; - switch(type) { + switch (type) { case 51: { - dissect_ht_capability_ie(&b[1],l-1,ie); - } - break; + dissect_ht_capability_ie(&b[1], l - 1, ie); + } break; case 52: { - dissect_ht_info_ie_1_0(&b[1],l-1,ie); - } - break; + dissect_ht_info_ie_1_0(&b[1], l - 1, ie); + } break; default: - ie["802.11n (Pre) Unknown Data"] = BufferToHex(&b[1],l-1); + ie["802.11n (Pre) Unknown Data"] = BufferToHex(&b[1], l - 1); break; } return ie; @@ -1618,134 +1650,140 @@ namespace OpenWifi { inline nlohmann::json dissect_vendor_ie_wfa(const unsigned char *b, uint l) { nlohmann::json ie; ie["vendor"] = "Wi-Fi Alliance"; - ie["Data"] = BufferToHex(&b[1],l-1); - b++;l++; + ie["Data"] = BufferToHex(&b[1], l - 1); + b++; + l++; return ie; } inline nlohmann::json dissect_vendor_ie_aironet(const unsigned char *b, uint l) { nlohmann::json ie; ie["vendor"] = "Cisco Wireless (Aironet)"; - ie["Data"] = BufferToHex(&b[1],l-1); - b++;l++; + ie["Data"] = BufferToHex(&b[1], l - 1); + b++; + l++; return ie; } inline nlohmann::json dissect_vendor_ie_marvell(const unsigned char *b, uint l) { nlohmann::json ie; ie["vendor"] = "Marvell Semiconductor"; - ie["Data"] = BufferToHex(&b[1],l-1); - b++;l++; + ie["Data"] = BufferToHex(&b[1], l - 1); + b++; + l++; return ie; } inline nlohmann::json dissect_vendor_ie_atheros(const unsigned char *b, uint l) { nlohmann::json ie; ie["vendor"] = "Atheros Communications"; - ie["Data"] = BufferToHex(&b[1],l-1); - b++;l++; + ie["Data"] = BufferToHex(&b[1], l - 1); + b++; + l++; return ie; } inline nlohmann::json dissect_vendor_ie_aruba(const unsigned char *b, uint l) { nlohmann::json ie; ie["vendor"] = "Aruba Networks"; - ie["Data"] = BufferToHex(&b[1],l-1); - b++;l++; + ie["Data"] = BufferToHex(&b[1], l - 1); + b++; + l++; return ie; } inline nlohmann::json dissect_vendor_ie_nintendo(const unsigned char *b, uint l) { nlohmann::json ie; ie["vendor"] = "Nintendo"; - ie["Data"] = BufferToHex(&b[1],l-1); - b++;l++; + ie["Data"] = BufferToHex(&b[1], l - 1); + b++; + l++; return ie; } inline nlohmann::json WFS_WLAN_EID_VENDOR_SPECIFIC(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; + nlohmann::json new_ie; + nlohmann::json content; - if(data.size()>=3) { - uint offset=0; - auto RSNOUI = GetUInt24Big(&data[0],offset); + if (data.size() >= 3) { + uint offset = 0; + auto RSNOUI = GetUInt24Big(&data[0], offset); - switch(RSNOUI) { + switch (RSNOUI) { case OUI_WPAWME: - content = dissect_vendor_ie_wpawme(&data[offset], data.size()-offset); + content = dissect_vendor_ie_wpawme(&data[offset], data.size() - offset); break; case OUI_RSN: - content = dissect_vendor_ie_rsn(&data[offset], data.size()-offset); + content = dissect_vendor_ie_rsn(&data[offset], data.size() - offset); break; case OUI_PRE11N: - content = dissect_vendor_ie_ht(&data[offset], data.size()-offset); + content = dissect_vendor_ie_ht(&data[offset], data.size() - offset); break; case OUI_WFA: - content = dissect_vendor_ie_wfa(&data[offset], data.size()-offset); + content = dissect_vendor_ie_wfa(&data[offset], data.size() - offset); break; case OUI_CISCOWL: - content = dissect_vendor_ie_aironet(&data[offset], data.size()-offset); + content = dissect_vendor_ie_aironet(&data[offset], data.size() - offset); break; case OUI_MARVELL: - content = dissect_vendor_ie_marvell(&data[offset], data.size()-offset); + content = dissect_vendor_ie_marvell(&data[offset], data.size() - offset); break; case OUI_ATHEROS: - content = dissect_vendor_ie_atheros(&data[offset], data.size()-offset); + content = dissect_vendor_ie_atheros(&data[offset], data.size() - offset); break; case OUI_ARUBA: - content = dissect_vendor_ie_aruba(&data[offset], data.size()-offset); + content = dissect_vendor_ie_aruba(&data[offset], data.size() - offset); break; case OUI_NINTENDO: - content = dissect_vendor_ie_nintendo(&data[offset], data.size()-offset); + content = dissect_vendor_ie_nintendo(&data[offset], data.size() - offset); break; default: - content["content"] = BufferToHex(&data[0],data.size()); + content["content"] = BufferToHex(&data[0], data.size()); break; } - } - new_ie["name"]="Vendor Specific"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_VENDOR_SPECIFIC; + new_ie["name"] = "Vendor Specific"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_VENDOR_SPECIFIC; return new_ie; } inline nlohmann::json WFS_WLAN_EID_EXTENSION(const std::vector &data) { - nlohmann::json new_ie; - nlohmann::json content; + nlohmann::json new_ie; + nlohmann::json content; // std::cout << BufferToHex(&data[0],data.size()) << std::endl; - uint offset=0; + uint offset = 0; auto sub_ie = data[offset++]; switch (sub_ie) { case WLAN_EID_EXT_HE_CAPABILITY: { - content["Extension EID"] = BufferToHex(&data[0],1); - content["Block"] = BufferToHex(&data[1],data.size()-1); + content["Extension EID"] = BufferToHex(&data[0], 1); + content["Block"] = BufferToHex(&data[1], data.size() - 1); } break; case WLAN_EID_EXT_HE_OPERATION: { - content["Extension EID"] = BufferToHex(&data[0],1); - content["Block"] = BufferToHex(&data[1],data.size()-1); + content["Extension EID"] = BufferToHex(&data[0], 1); + content["Block"] = BufferToHex(&data[1], data.size() - 1); } break; case WLAN_EID_EXT_HE_MU_EDCA: { - content["Extension EID"] = BufferToHex(&data[0],1); - content["Block"] = BufferToHex(&data[1],data.size()-1); + content["Extension EID"] = BufferToHex(&data[0], 1); + content["Block"] = BufferToHex(&data[1], data.size() - 1); } break; default: - content["Extension EID"] = BufferToHex(&data[0],1); - content["Block"] = BufferToHex(&data[1],data.size()-1); + content["Extension EID"] = BufferToHex(&data[0], 1); + content["Block"] = BufferToHex(&data[1], data.size() - 1); break; } - new_ie["name"]="EI Extensions"; - new_ie["content"]=content; - new_ie["type"]=WLAN_EID_EXTENSION; + new_ie["name"] = "EI Extensions"; + new_ie["content"] = content; + new_ie["type"] = WLAN_EID_EXTENSION; return new_ie; } - inline bool ParseWifiScan(Poco::JSON::Object::Ptr &Obj, std::stringstream &Result, Poco::Logger &Logger) { - std::ostringstream ofs; + inline bool ParseWifiScan(Poco::JSON::Object::Ptr &Obj, std::stringstream &Result, + Poco::Logger &Logger) { + std::ostringstream ofs; Obj->stringify(ofs); try { @@ -1765,7 +1803,8 @@ namespace OpenWifi { if (ie.contains("type") && ie.contains("data")) { uint64_t ie_type = ie["type"]; std::string ie_data = ie["data"]; - // std::cout << "TYPE:" << ie_type << " DATA:" << ie_data << std::endl; + // std::cout << "TYPE:" << ie_type << " DATA:" << ie_data + // << std::endl; auto data = Base64Decode2Vec(ie_data); if (ie_type == ieee80211_eid::WLAN_EID_COUNTRY) { new_ies.push_back(WFS_WLAN_EID_COUNTRY(data)); @@ -1825,7 +1864,8 @@ namespace OpenWifi { new_ies.push_back(ie); } } else { - // std::cout << "Skipping IE: no data and type" << std::endl; + // std::cout << "Skipping IE: no data and type" << + // std::endl; new_ies.push_back(ie); } } catch (...) { @@ -1858,4 +1898,3 @@ namespace OpenWifi { } } // namespace OpenWifi - diff --git a/src/RADIUS_helpers.h b/src/RADIUS_helpers.h index 103635de..8c5481ac 100644 --- a/src/RADIUS_helpers.h +++ b/src/RADIUS_helpers.h @@ -4,274 +4,271 @@ #pragma once +#include +#include #include #include -#include -#include #include "Poco/HMACEngine.h" #include "Poco/MD5Engine.h" -#include "Poco/StringTokenizer.h" #include "Poco/Net/SocketAddress.h" +#include "Poco/StringTokenizer.h" namespace OpenWifi::RADIUS { -#define RADCMD_ACCESS_REQ 1 /* Access-Request */ -#define RADCMD_ACCESS_ACC 2 /* Access-Accept */ -#define RADCMD_ACCESS_REJ 3 /* Access-Reject */ -#define RADCMD_ACCOUN_REQ 4 /* Accounting-Request */ -#define RADCMD_ACCOUN_RES 5 /* Accounting-Response */ -#define RADCMD_ACCOUN_STATUS 6 /* Accounting-Status */ -#define RADCMD_PASSWORD_REQUEST 7 /* Password-Request [RFC3575] */ -#define RADCMD_PASSWORD_ACK 8 /* Password-Ack [RFC3575] */ -#define RADCMD_PASSWORD_REJECT 9 /* Password-Reject [RFC3575] */ -#define RADCMD_ACCOUN_MESSAGE 10 /* Accounting-Message [RFC3575] */ +#define RADCMD_ACCESS_REQ 1 /* Access-Request */ +#define RADCMD_ACCESS_ACC 2 /* Access-Accept */ +#define RADCMD_ACCESS_REJ 3 /* Access-Reject */ +#define RADCMD_ACCOUN_REQ 4 /* Accounting-Request */ +#define RADCMD_ACCOUN_RES 5 /* Accounting-Response */ +#define RADCMD_ACCOUN_STATUS 6 /* Accounting-Status */ +#define RADCMD_PASSWORD_REQUEST 7 /* Password-Request [RFC3575] */ +#define RADCMD_PASSWORD_ACK 8 /* Password-Ack [RFC3575] */ +#define RADCMD_PASSWORD_REJECT 9 /* Password-Reject [RFC3575] */ +#define RADCMD_ACCOUN_MESSAGE 10 /* Accounting-Message [RFC3575] */ -#define RADCMD_RES_FREE_REQ 21 /* Resource-Free-Request [RFC3575] */ -#define RADCMD_RES_FREE_RES 22 /* Resource-Free-Response [RFC3575] */ -#define RADCMD_RES_QUERY_REQ 23 /* Resource-Query-Request [RFC3575] */ -#define RADCMD_RES_QUERY_RES 24 /* Resource-Query-Response [RFC3575] */ -#define RADCMD_RES_ALT_RECLAIM_REQ 25 /* Alternate-Resource-Reclaim-Request [RFC3575] */ +#define RADCMD_RES_FREE_REQ 21 /* Resource-Free-Request [RFC3575] */ +#define RADCMD_RES_FREE_RES 22 /* Resource-Free-Response [RFC3575] */ +#define RADCMD_RES_QUERY_REQ 23 /* Resource-Query-Request [RFC3575] */ +#define RADCMD_RES_QUERY_RES 24 /* Resource-Query-Response [RFC3575] */ +#define RADCMD_RES_ALT_RECLAIM_REQ 25 /* Alternate-Resource-Reclaim-Request [RFC3575] */ -#define RADCMD_ACCESS_CHA 11 /* Access-Challenge */ -#define RADCMD_STATUS_SER 12 /* Status-Server */ -#define RADCMD_STATUS_CLI 13 /* Status-Client */ -#define RADCMD_DISCON_REQ 40 /* Disconnect-Request */ -#define RADCMD_DISCON_ACK 41 /* Disconnect-ACK */ -#define RADCMD_DISCON_NAK 42 /* Disconnect-NAK */ -#define RADCMD_COA_REQ 43 /* CoA-Request */ -#define RADCMD_COA_ACK 44 /* CoA-ACK */ -#define RADCMD_COA_NAK 45 /* CoA-NAK */ -#define RADCMD_RESERVED 255 /* Reserved */ +#define RADCMD_ACCESS_CHA 11 /* Access-Challenge */ +#define RADCMD_STATUS_SER 12 /* Status-Server */ +#define RADCMD_STATUS_CLI 13 /* Status-Client */ +#define RADCMD_DISCON_REQ 40 /* Disconnect-Request */ +#define RADCMD_DISCON_ACK 41 /* Disconnect-ACK */ +#define RADCMD_DISCON_NAK 42 /* Disconnect-NAK */ +#define RADCMD_COA_REQ 43 /* CoA-Request */ +#define RADCMD_COA_ACK 44 /* CoA-ACK */ +#define RADCMD_COA_NAK 45 /* CoA-NAK */ +#define RADCMD_RESERVED 255 /* Reserved */ -/* - 21 Resource-Free-Request [RFC3575] - 22 Resource-Free-Response [RFC3575] - 23 Resource-Query-Request [RFC3575] - 24 Resource-Query-Response [RFC3575] - 25 Alternate-Resource-Reclaim-Request [RFC3575] + /* + 21 Resource-Free-Request [RFC3575] + 22 Resource-Free-Response [RFC3575] + 23 Resource-Query-Request [RFC3575] + 24 Resource-Query-Response [RFC3575] + 25 Alternate-Resource-Reclaim-Request [RFC3575] - 26 NAS-Reboot-Request [RFC3575] - 27 NAS-Reboot-Response [RFC3575] - 28 Reserved - 29 Next-Passcode [RFC3575] - 30 New-Pin [RFC3575] - 31 Terminate-Session [RFC3575] - 32 Password-Expired [RFC3575] - 33 Event-Request [RFC3575] - 34 Event-Response [RFC3575] - 35-39 Unassigned - 40 Disconnect-Request [RFC3575][RFC5176] - 41 Disconnect-ACK [RFC3575][RFC5176] - 42 Disconnect-NAK [RFC3575][RFC5176] - 43 CoA-Request [RFC3575][RFC5176] - 44 CoA-ACK [RFC3575][RFC5176] - 45 CoA-NAK [RFC3575][RFC5176] - 46-49 Unassigned - 50 IP-Address-Allocate [RFC3575] - 51 IP-Address-Release [RFC3575] - 52 Protocol-Error [RFC7930] - 53-249 Unassigned - 250-253 Experimental Use [RFC3575] - 254 Reserved [RFC3575] - 255 Reserved [RFC3575] -*/ + 26 NAS-Reboot-Request [RFC3575] + 27 NAS-Reboot-Response [RFC3575] + 28 Reserved + 29 Next-Passcode [RFC3575] + 30 New-Pin [RFC3575] + 31 Terminate-Session [RFC3575] + 32 Password-Expired [RFC3575] + 33 Event-Request [RFC3575] + 34 Event-Response [RFC3575] + 35-39 Unassigned + 40 Disconnect-Request [RFC3575][RFC5176] + 41 Disconnect-ACK [RFC3575][RFC5176] + 42 Disconnect-NAK [RFC3575][RFC5176] + 43 CoA-Request [RFC3575][RFC5176] + 44 CoA-ACK [RFC3575][RFC5176] + 45 CoA-NAK [RFC3575][RFC5176] + 46-49 Unassigned + 50 IP-Address-Allocate [RFC3575] + 51 IP-Address-Release [RFC3575] + 52 Protocol-Error [RFC7930] + 53-249 Unassigned + 250-253 Experimental Use [RFC3575] + 254 Reserved [RFC3575] + 255 Reserved [RFC3575] + */ -struct tok { - uint cmd; - const char * name; -}; + struct tok { + uint cmd; + const char *name; + }; -/* + /* -Radius commands + Radius commands - char const *fr_packet_codes[FR_MAX_PACKET_CODE] = { - "", //!< 0 - "Access-Request", - "Access-Accept", - "Access-Reject", - "Accounting-Request", - "Accounting-Response", - "Accounting-Status", - "Password-Request", - "Password-Accept", - "Password-Reject", - "Accounting-Message", //!< 10 - "Access-Challenge", - "Status-Server", - "Status-Client", - "14", - "15", - "16", - "17", - "18", - "19", - "20", //!< 20 - "Resource-Free-Request", - "Resource-Free-Response", - "Resource-Query-Request", - "Resource-Query-Response", - "Alternate-Resource-Reclaim-Request", - "NAS-Reboot-Request", - "NAS-Reboot-Response", - "28", - "Next-Passcode", - "New-Pin", //!< 30 - "Terminate-Session", - "Password-Expired", - "Event-Request", - "Event-Response", - "35", - "36", - "37", - "38", - "39", - "Disconnect-Request", //!< 40 - "Disconnect-ACK", - "Disconnect-NAK", - "CoA-Request", - "CoA-ACK", - "CoA-NAK", - "46", - "47", - "48", - "49", - "IP-Address-Allocate", - "IP-Address-Release", //!< 50 -}; + char const *fr_packet_codes[FR_MAX_PACKET_CODE] = { + "", //!< 0 + "Access-Request", + "Access-Accept", + "Access-Reject", + "Accounting-Request", + "Accounting-Response", + "Accounting-Status", + "Password-Request", + "Password-Accept", + "Password-Reject", + "Accounting-Message", //!< 10 + "Access-Challenge", + "Status-Server", + "Status-Client", + "14", + "15", + "16", + "17", + "18", + "19", + "20", //!< 20 + "Resource-Free-Request", + "Resource-Free-Response", + "Resource-Query-Request", + "Resource-Query-Response", + "Alternate-Resource-Reclaim-Request", + "NAS-Reboot-Request", + "NAS-Reboot-Response", + "28", + "Next-Passcode", + "New-Pin", //!< 30 + "Terminate-Session", + "Password-Expired", + "Event-Request", + "Event-Response", + "35", + "36", + "37", + "38", + "39", + "Disconnect-Request", //!< 40 + "Disconnect-ACK", + "Disconnect-NAK", + "CoA-Request", + "CoA-ACK", + "CoA-NAK", + "46", + "47", + "48", + "49", + "IP-Address-Allocate", + "IP-Address-Release", //!< 50 + }; - */ + */ -static const struct tok radius_command_values[] = { - { RADCMD_ACCESS_REQ, "Access-Request" }, - { RADCMD_ACCESS_ACC, "Access-Accept" }, - { RADCMD_ACCESS_REJ, "Access-Reject" }, - { RADCMD_ACCOUN_REQ, "Accounting-Request" }, - { RADCMD_ACCOUN_RES, "Accounting-Response" }, - { RADCMD_ACCESS_CHA, "Access-Challenge" }, - { RADCMD_STATUS_SER, "Status-Server" }, - { RADCMD_STATUS_CLI, "Status-Client" }, - { RADCMD_DISCON_REQ, "Disconnect-Request" }, - { RADCMD_DISCON_ACK, "Disconnect-ACK" }, - { RADCMD_DISCON_NAK, "Disconnect-NAK" }, - { RADCMD_COA_REQ, "CoA-Request" }, - { RADCMD_COA_ACK, "CoA-ACK" }, - { RADCMD_COA_NAK, "CoA-NAK" }, - { RADCMD_RESERVED, "Reserved" }, - { RADCMD_ACCOUN_STATUS, "Accounting-Status"}, - { RADCMD_PASSWORD_REQUEST, "Password-Request"}, - { RADCMD_PASSWORD_ACK, "Password-Ack"}, - { RADCMD_PASSWORD_REJECT, "Password-Reject"}, - { RADCMD_ACCOUN_MESSAGE, "Accounting-Message"}, - { RADCMD_RES_FREE_REQ, "Resource-Free-Request"}, - { RADCMD_RES_FREE_RES, "Resource-Free-Response"}, - { RADCMD_RES_QUERY_REQ, "Resource-Query-Request"}, - { RADCMD_RES_QUERY_RES, "Resource-Query-Response"}, - { RADCMD_RES_ALT_RECLAIM_REQ, "Alternate-Resource-Reclaim-Request"}, - { 0, nullptr} -}; + static const struct tok radius_command_values[] = { + {RADCMD_ACCESS_REQ, "Access-Request"}, + {RADCMD_ACCESS_ACC, "Access-Accept"}, + {RADCMD_ACCESS_REJ, "Access-Reject"}, + {RADCMD_ACCOUN_REQ, "Accounting-Request"}, + {RADCMD_ACCOUN_RES, "Accounting-Response"}, + {RADCMD_ACCESS_CHA, "Access-Challenge"}, + {RADCMD_STATUS_SER, "Status-Server"}, + {RADCMD_STATUS_CLI, "Status-Client"}, + {RADCMD_DISCON_REQ, "Disconnect-Request"}, + {RADCMD_DISCON_ACK, "Disconnect-ACK"}, + {RADCMD_DISCON_NAK, "Disconnect-NAK"}, + {RADCMD_COA_REQ, "CoA-Request"}, + {RADCMD_COA_ACK, "CoA-ACK"}, + {RADCMD_COA_NAK, "CoA-NAK"}, + {RADCMD_RESERVED, "Reserved"}, + {RADCMD_ACCOUN_STATUS, "Accounting-Status"}, + {RADCMD_PASSWORD_REQUEST, "Password-Request"}, + {RADCMD_PASSWORD_ACK, "Password-Ack"}, + {RADCMD_PASSWORD_REJECT, "Password-Reject"}, + {RADCMD_ACCOUN_MESSAGE, "Accounting-Message"}, + {RADCMD_RES_FREE_REQ, "Resource-Free-Request"}, + {RADCMD_RES_FREE_RES, "Resource-Free-Response"}, + {RADCMD_RES_QUERY_REQ, "Resource-Query-Request"}, + {RADCMD_RES_QUERY_RES, "Resource-Query-Response"}, + {RADCMD_RES_ALT_RECLAIM_REQ, "Alternate-Resource-Reclaim-Request"}, + {0, nullptr}}; -static const struct tok radius_attribute_names[] = { - {1,"User-Name"}, - {2,"User-Password"}, - {3,"CHAP-Password"}, - {4,"NAS-IP Address"}, - {5,"NAS-Port"}, - {6,"Service-Type"}, - {7,"Framed-Protocol"}, - {8,"Framed-IP-Address"}, - {9,"Framed-IP-Netmask"}, - {10,"Framed-Routing"}, - {11,"Filter-Id"}, - {12,"Framed-MTU"}, - {13,"Framed-Compression"}, - {14,"Login-IP-Host"}, - {15,"Login-Service"}, - {16,"Login-TCP-Port"}, - {18,"Reply-Message"}, - {19,"Callback-Number"}, - {20,"Callback-ID"}, - {22,"Framed-Route"}, - {23,"Framed-IPX-Network"}, - {24,"State"}, - {25,"Class"}, - {26,"Vendor-Specific"}, - {27,"Session-Timeout"}, - {28,"Idle-Timeout"}, - {29,"Termination-Action"}, - {30,"Called-Station-Id"}, - {31,"Calling-Station-Id"}, - {32,"NAS-Identifier"}, - {33,"Proxy-State"}, - {34,"Login-LAT-Service"}, - {35,"Login-LAT-Node"}, - {36,"Login-LAT-Group"}, - {37,"Framed-AppleTalk-Link"}, - {38,"Framed-AppleTalk-Network"}, - {39,"Framed-AppleTalk-Zone"}, - {40,"Acct-Status-Type"}, - {41,"Acct-Delay-Time"}, - {42,"Acct-Input-Octets"}, - {43,"Acct-Output-Octets"}, - {44,"Acct-Session-Id"}, - {45,"Acct-Authentic"}, - {46,"Acct-Session-Time"}, - {47,"Acct-Input-Packets"}, - {48,"Acct-Output-Packets"}, - {49,"Acct-Terminate-Cause"}, - {50,"Acct-Multi-Session-Id"}, - {51,"Acct-Link-Count"}, - {52,"Acct-Input-Gigawords"}, - {53,"Acct-Output-Gigawords"}, - {55,"Event-Timestamp"}, - {60,"CHAP-Challenge"}, - {61,"NAS-Port-Type"}, - {62,"Port-Limit"}, - {63,"Login-LAT-Port"}, - {64,"Tunnel-Type3"}, - {65,"Tunnel-Medium-Type1"}, - {66,"Tunnel-Client-Endpoint"}, - {67,"Tunnel-Server-Endpoint1"}, - {68,"Acct-Tunnel-Connection-ID"}, - {69,"Tunnel-Password1"}, - {70,"ARAP-Password"}, - {71,"ARAP-Features"}, - {72,"ARAP-Zone-Access"}, - {73,"ARAP-Security"}, - {74,"ARAP-Security-Data"}, - {75,"Password-Retry"}, - {76,"Prompt"}, - {77,"Connect-Info"}, - {78,"Configuration-Token"}, - {79,"EAP-Message"}, - {80,"Message-Authenticator"}, - {81,"Tunnel-Private-Group-ID"}, - {82,"Tunnel-Assignment-ID1"}, - {83,"Tunnel-Preference"}, - {84,"ARAP-Challenge-Response"}, - {85,"Acct-Interim-Interval"}, - {86,"Acct-Tunnel-Packets-Lost"}, - {87,"NAS-Port-ID"}, - {88,"Framed-Pool"}, - {90,"Tunnel-Client-Auth-ID"}, - {91,"Tunnel-Server-Auth-ID"}, - {0, nullptr} -}; + static const struct tok radius_attribute_names[] = {{1, "User-Name"}, + {2, "User-Password"}, + {3, "CHAP-Password"}, + {4, "NAS-IP Address"}, + {5, "NAS-Port"}, + {6, "Service-Type"}, + {7, "Framed-Protocol"}, + {8, "Framed-IP-Address"}, + {9, "Framed-IP-Netmask"}, + {10, "Framed-Routing"}, + {11, "Filter-Id"}, + {12, "Framed-MTU"}, + {13, "Framed-Compression"}, + {14, "Login-IP-Host"}, + {15, "Login-Service"}, + {16, "Login-TCP-Port"}, + {18, "Reply-Message"}, + {19, "Callback-Number"}, + {20, "Callback-ID"}, + {22, "Framed-Route"}, + {23, "Framed-IPX-Network"}, + {24, "State"}, + {25, "Class"}, + {26, "Vendor-Specific"}, + {27, "Session-Timeout"}, + {28, "Idle-Timeout"}, + {29, "Termination-Action"}, + {30, "Called-Station-Id"}, + {31, "Calling-Station-Id"}, + {32, "NAS-Identifier"}, + {33, "Proxy-State"}, + {34, "Login-LAT-Service"}, + {35, "Login-LAT-Node"}, + {36, "Login-LAT-Group"}, + {37, "Framed-AppleTalk-Link"}, + {38, "Framed-AppleTalk-Network"}, + {39, "Framed-AppleTalk-Zone"}, + {40, "Acct-Status-Type"}, + {41, "Acct-Delay-Time"}, + {42, "Acct-Input-Octets"}, + {43, "Acct-Output-Octets"}, + {44, "Acct-Session-Id"}, + {45, "Acct-Authentic"}, + {46, "Acct-Session-Time"}, + {47, "Acct-Input-Packets"}, + {48, "Acct-Output-Packets"}, + {49, "Acct-Terminate-Cause"}, + {50, "Acct-Multi-Session-Id"}, + {51, "Acct-Link-Count"}, + {52, "Acct-Input-Gigawords"}, + {53, "Acct-Output-Gigawords"}, + {55, "Event-Timestamp"}, + {60, "CHAP-Challenge"}, + {61, "NAS-Port-Type"}, + {62, "Port-Limit"}, + {63, "Login-LAT-Port"}, + {64, "Tunnel-Type3"}, + {65, "Tunnel-Medium-Type1"}, + {66, "Tunnel-Client-Endpoint"}, + {67, "Tunnel-Server-Endpoint1"}, + {68, "Acct-Tunnel-Connection-ID"}, + {69, "Tunnel-Password1"}, + {70, "ARAP-Password"}, + {71, "ARAP-Features"}, + {72, "ARAP-Zone-Access"}, + {73, "ARAP-Security"}, + {74, "ARAP-Security-Data"}, + {75, "Password-Retry"}, + {76, "Prompt"}, + {77, "Connect-Info"}, + {78, "Configuration-Token"}, + {79, "EAP-Message"}, + {80, "Message-Authenticator"}, + {81, "Tunnel-Private-Group-ID"}, + {82, "Tunnel-Assignment-ID1"}, + {83, "Tunnel-Preference"}, + {84, "ARAP-Challenge-Response"}, + {85, "Acct-Interim-Interval"}, + {86, "Acct-Tunnel-Packets-Lost"}, + {87, "NAS-Port-ID"}, + {88, "Framed-Pool"}, + {90, "Tunnel-Client-Auth-ID"}, + {91, "Tunnel-Server-Auth-ID"}, + {0, nullptr}}; -#pragma pack(push,1) +#pragma pack(push, 1) struct RadiusAttribute { - unsigned char type{0}; - uint16_t pos{0}; - unsigned len{0}; + unsigned char type{0}; + uint16_t pos{0}; + unsigned len{0}; }; struct RawRadiusPacket { - unsigned char code{1}; - unsigned char identifier{0}; - uint16_t rawlen{0}; - unsigned char authenticator[16]{0}; - unsigned char attributes[4096]{0}; + unsigned char code{1}; + unsigned char identifier{0}; + uint16_t rawlen{0}; + unsigned char authenticator[16]{0}; + unsigned char attributes[4096]{0}; }; #pragma pack(pop) @@ -286,7 +283,7 @@ static const struct tok radius_attribute_names[] = { constexpr unsigned char Accounting_Message = 10; constexpr unsigned char Disconnect_Request = 40; - constexpr unsigned char Disconnect_ACK = 41; + constexpr unsigned char Disconnect_ACK = 41; constexpr unsigned char Disconnect_NAK = 42; constexpr unsigned char CoA_Request = 43; constexpr unsigned char CoA_ACK = 44; @@ -295,47 +292,42 @@ static const struct tok radius_attribute_names[] = { constexpr unsigned char ATTR_MessageAuthenticator = 80; inline bool IsAuthentication(unsigned char t) { - return (t == RADIUS::Access_Request || - t == RADIUS::Access_Accept || - t == RADIUS::Access_Challenge || - t == RADIUS::Access_Reject); + return (t == RADIUS::Access_Request || t == RADIUS::Access_Accept || + t == RADIUS::Access_Challenge || t == RADIUS::Access_Reject); } inline bool IsAccounting(unsigned char t) { - return (t == RADIUS::Accounting_Request || - t == RADIUS::Accounting_Response || - t == RADIUS::Accounting_Status || - t == RADIUS::Accounting_Message); + return (t == RADIUS::Accounting_Request || t == RADIUS::Accounting_Response || + t == RADIUS::Accounting_Status || t == RADIUS::Accounting_Message); } inline bool IsAuthority(unsigned char t) { - return (t == RADIUS::Disconnect_Request || - t == RADIUS::Disconnect_ACK || - t == RADIUS::Disconnect_NAK || - t == RADIUS::CoA_Request || - t == RADIUS::CoA_ACK || + return (t == RADIUS::Disconnect_Request || t == RADIUS::Disconnect_ACK || + t == RADIUS::Disconnect_NAK || t == RADIUS::CoA_Request || t == RADIUS::CoA_ACK || t == RADIUS::CoA_NAK); } - inline const char * CommandName(uint cmd) { + inline const char *CommandName(uint cmd) { auto cmds = radius_command_values; - while(cmds->cmd && (cmds->cmd!=cmd)) + while (cmds->cmd && (cmds->cmd != cmd)) cmds++; - if(cmds->cmd==cmd) return cmds->name; + if (cmds->cmd == cmd) + return cmds->name; return "Unknown"; } - inline const char * AttributeName(uint cmd) { + inline const char *AttributeName(uint cmd) { auto cmds = radius_attribute_names; - while(cmds->cmd && (cmds->cmd!=cmd)) + while (cmds->cmd && (cmds->cmd != cmd)) cmds++; - if(cmds->cmd==cmd) return cmds->name; + if (cmds->cmd == cmd) + return cmds->name; return "Unknown"; } inline void MakeRadiusAuthenticator(unsigned char *authenticator) { - for(int i=0;i<16;i++) - authenticator[i]=std::rand() & 0xff; + for (int i = 0; i < 16; i++) + authenticator[i] = std::rand() & 0xff; } // @@ -349,29 +341,35 @@ static const struct tok radius_attribute_names[] = { using AttributeList = std::list; inline std::ostream &operator<<(std::ostream &os, AttributeList const &P) { - for(const auto &attr:P) { - os << "\tAttr: " << (uint16_t) attr.type << " Size: " << (uint16_t) attr.len << std::endl; + for (const auto &attr : P) { + os << "\tAttr: " << (uint16_t)attr.type << " Size: " << (uint16_t)attr.len + << std::endl; } return os; } - inline bool ParseRadius(uint32_t offset, const unsigned char *Buffer, uint16_t Size, AttributeList &Attrs) { + inline bool ParseRadius(uint32_t offset, const unsigned char *Buffer, uint16_t Size, + AttributeList &Attrs) { Attrs.clear(); - uint16_t pos=0; - auto x=25; - while(pos & Buf) { - if(Buf.size() >= sizeof(RawRadiusPacket)) { + explicit RadiusPacket(const Poco::Buffer &Buf) { + if (Buf.size() >= sizeof(RawRadiusPacket)) { Valid_ = false; return; } - memcpy((void *)&P_,Buf.begin(), Buf.size()); - Size_=Buf.size(); - Valid_ = (Size_== htons(P_.rawlen)); - if(Valid_) - Valid_ = ParseRadius(0,(unsigned char *)&P_.attributes[0],Size_-20,Attrs_); + memcpy((void *)&P_, Buf.begin(), Buf.size()); + Size_ = Buf.size(); + Valid_ = (Size_ == htons(P_.rawlen)); + if (Valid_) + Valid_ = ParseRadius(0, (unsigned char *)&P_.attributes[0], Size_ - 20, Attrs_); } explicit RadiusPacket(const unsigned char *buffer, uint16_t size) { - if(size >= sizeof(RawRadiusPacket)) { + if (size >= sizeof(RawRadiusPacket)) { Valid_ = false; return; } - memcpy((void *)&P_,buffer, size); - Size_=size; - Valid_ = (Size_== htons(P_.rawlen)); - if(Valid_) - Valid_ = ParseRadius(0,(unsigned char *)&P_.attributes[0],Size_-20,Attrs_); + memcpy((void *)&P_, buffer, size); + Size_ = size; + Valid_ = (Size_ == htons(P_.rawlen)); + if (Valid_) + Valid_ = ParseRadius(0, (unsigned char *)&P_.attributes[0], Size_ - 20, Attrs_); } explicit RadiusPacket(const std::string &p) { - if(p.size() >= sizeof(RawRadiusPacket)) { + if (p.size() >= sizeof(RawRadiusPacket)) { Valid_ = false; return; } - memcpy((void *)&P_,(const unsigned char*) p.c_str(), p.size()); - Size_=p.size(); - Valid_ = (Size_== htons(P_.rawlen)); - if(Valid_) - Valid_ = ParseRadius(0,(unsigned char *)&P_.attributes[0],Size_-20,Attrs_); + memcpy((void *)&P_, (const unsigned char *)p.c_str(), p.size()); + Size_ = p.size(); + Valid_ = (Size_ == htons(P_.rawlen)); + if (Valid_) + Valid_ = ParseRadius(0, (unsigned char *)&P_.attributes[0], Size_ - 20, Attrs_); } explicit RadiusPacket(const RadiusPacket &P) { @@ -424,76 +422,65 @@ static const struct tok radius_attribute_names[] = { explicit RadiusPacket() = default; - unsigned char * Buffer() { return (unsigned char *)&P_; } - [[nodiscard]] uint16_t BufferLen() const { return sizeof(P_);} + unsigned char *Buffer() { return (unsigned char *)&P_; } + [[nodiscard]] uint16_t BufferLen() const { return sizeof(P_); } void Evaluate(uint16_t size) { Size_ = size; - Valid_ = ParseRadius(0,(unsigned char *)&P_.attributes[0],Size_-20,Attrs_); + Valid_ = ParseRadius(0, (unsigned char *)&P_.attributes[0], Size_ - 20, Attrs_); } - [[nodiscard]] uint16_t Len() const { return htons(P_.rawlen); } - [[nodiscard]] uint16_t Size() const { return Size_; } + [[nodiscard]] uint16_t Len() const { return htons(P_.rawlen); } + [[nodiscard]] uint16_t Size() const { return Size_; } friend std::ostream &operator<<(std::ostream &os, RadiusPacket const &P); inline bool IsAuthentication() { - return (P_.code == RADIUS::Access_Request || - P_.code == RADIUS::Access_Accept || - P_.code == RADIUS::Access_Challenge || - P_.code == RADIUS::Access_Reject || - P_.code == RADCMD_RES_FREE_REQ || - P_.code == RADCMD_RES_FREE_RES || - P_.code == RADCMD_RES_QUERY_REQ || - P_.code == RADCMD_RES_QUERY_RES || + return (P_.code == RADIUS::Access_Request || P_.code == RADIUS::Access_Accept || + P_.code == RADIUS::Access_Challenge || P_.code == RADIUS::Access_Reject || + P_.code == RADCMD_RES_FREE_REQ || P_.code == RADCMD_RES_FREE_RES || + P_.code == RADCMD_RES_QUERY_REQ || P_.code == RADCMD_RES_QUERY_RES || P_.code == RADCMD_RES_ALT_RECLAIM_REQ); } inline bool IsAccounting() { return (P_.code == RADIUS::Accounting_Request || P_.code == RADIUS::Accounting_Response || - P_.code == RADIUS::Accounting_Status || - P_.code == RADIUS::Accounting_Message); + P_.code == RADIUS::Accounting_Status || P_.code == RADIUS::Accounting_Message); } inline bool IsAuthority() { - return (P_.code == RADIUS::Disconnect_Request || - P_.code == RADIUS::Disconnect_ACK || - P_.code == RADIUS::Disconnect_NAK || - P_.code == RADIUS::CoA_Request || - P_.code == RADIUS::CoA_ACK || - P_.code == RADIUS::CoA_NAK); + return (P_.code == RADIUS::Disconnect_Request || P_.code == RADIUS::Disconnect_ACK || + P_.code == RADIUS::Disconnect_NAK || P_.code == RADIUS::CoA_Request || + P_.code == RADIUS::CoA_ACK || P_.code == RADIUS::CoA_NAK); } void Log(std::ostream &os) { uint16_t p = 0; - while(p(4+2)) { - if (ParseRadius(attribute.pos + 4, &P_.attributes[attribute.pos + 4], attribute.len - 4 - 2, - VendorAttributes)) { + if (VendorId == TIP_vendor_id && attribute.len > (4 + 2)) { + if (ParseRadius(attribute.pos + 4, &P_.attributes[attribute.pos + 4], + attribute.len - 4 - 2, VendorAttributes)) { // std::cout << VendorAttributes << std::endl; - for (const auto &vendorAttr: VendorAttributes) { + for (const auto &vendorAttr : VendorAttributes) { if (vendorAttr.type == TIP_serial) { for (uint16_t i = 0; i < vendorAttr.len; i++) { if (P_.attributes[vendorAttr.pos + i] == '-') continue; - R += (char) P_.attributes[vendorAttr.pos + i]; + R += (char)P_.attributes[vendorAttr.pos + i]; } return R; } @@ -605,17 +594,18 @@ static const struct tok radius_attribute_names[] = { std::string ExtractSerialNumberFromProxyState() { std::string Result; - for(const auto &attribute:Attrs_) { - if(attribute.type==33) { + for (const auto &attribute : Attrs_) { + if (attribute.type == 33) { std::string Attr33; // format is serial:IP:port:interface - Attr33.assign((const char *)(const char *)&P_.attributes[attribute.pos],attribute.len-2); - auto Parts = Poco::StringTokenizer(Attr33,"|"); - if(Parts.count()==4) { + Attr33.assign((const char *)(const char *)&P_.attributes[attribute.pos], + attribute.len - 2); + auto Parts = Poco::StringTokenizer(Attr33, "|"); + if (Parts.count() == 4) { return Parts[0]; } - Parts = Poco::StringTokenizer(Attr33,":"); - if(Parts.count()==4) { + Parts = Poco::StringTokenizer(Attr33, ":"); + if (Parts.count() == 4) { return Parts[0]; } return Result; @@ -626,19 +616,20 @@ static const struct tok radius_attribute_names[] = { std::string ExtractProxyStateDestination() { std::string Result; - for(const auto &attribute:Attrs_) { - if(attribute.type==33 && attribute.len>2) { + for (const auto &attribute : Attrs_) { + if (attribute.type == 33 && attribute.len > 2) { std::string Attr33; // format is serial:IP:port:interface - Attr33.assign((const char *)(const char *)&P_.attributes[attribute.pos],attribute.len-2); - auto Parts = Poco::StringTokenizer(Attr33,"|"); - if(Parts.count()==4) { - Poco::Net::SocketAddress D(Parts[1],Parts[2]); + Attr33.assign((const char *)(const char *)&P_.attributes[attribute.pos], + attribute.len - 2); + auto Parts = Poco::StringTokenizer(Attr33, "|"); + if (Parts.count() == 4) { + Poco::Net::SocketAddress D(Parts[1], Parts[2]); return D.toString(); } - Parts = Poco::StringTokenizer(Attr33,":"); - if(Parts.count()==4) { - Poco::Net::SocketAddress D(Parts[1],Parts[2]); + Parts = Poco::StringTokenizer(Attr33, ":"); + if (Parts.count() == 4) { + Poco::Net::SocketAddress D(Parts[1], Parts[2]); return D.toString(); } return Result; @@ -649,9 +640,10 @@ static const struct tok radius_attribute_names[] = { std::string ExtractCallingStationID() { std::string Result; - for(const auto &attribute:Attrs_) { - if(attribute.type==31 && attribute.len>2) { - Result.assign((const char *)(const char *)&P_.attributes[attribute.pos],attribute.len-2); + for (const auto &attribute : Attrs_) { + if (attribute.type == 31 && attribute.len > 2) { + Result.assign((const char *)(const char *)&P_.attributes[attribute.pos], + attribute.len - 2); return Result; } } @@ -660,9 +652,10 @@ static const struct tok radius_attribute_names[] = { std::string ExtractCalledStationID() { std::string Result; - for(const auto &attribute:Attrs_) { - if(attribute.type==30 && attribute.len>2) { - Result.assign((const char *)(const char *)&P_.attributes[attribute.pos],attribute.len-2); + for (const auto &attribute : Attrs_) { + if (attribute.type == 30 && attribute.len > 2) { + Result.assign((const char *)(const char *)&P_.attributes[attribute.pos], + attribute.len - 2); return Result; } } @@ -670,9 +663,9 @@ static const struct tok radius_attribute_names[] = { } [[nodiscard]] std::string UserName() const { - for(const auto &attr:Attrs_) { - if(attr.type==1) { - std::string user_name{(const char *)&P_.attributes[attr.pos],attr.len}; + for (const auto &attr : Attrs_) { + if (attr.type == 1) { + std::string user_name{(const char *)&P_.attributes[attr.pos], attr.len}; return user_name; } } @@ -680,24 +673,23 @@ static const struct tok radius_attribute_names[] = { } private: - RawRadiusPacket P_; - uint16_t Size_{0}; - AttributeList Attrs_; - bool Valid_=false; + RawRadiusPacket P_; + uint16_t Size_{0}; + AttributeList Attrs_; + bool Valid_ = false; }; class RadiusOutputPacket { public: - explicit RadiusOutputPacket(const std::string &Secret) - : Secret_(Secret) { - } + explicit RadiusOutputPacket(const std::string &Secret) : Secret_(Secret) {} inline void MakeStatusMessage() { P_.code = RADCMD_STATUS_SER; P_.identifier = std::rand() & 0x00ff; MakeRadiusAuthenticator(P_.authenticator); unsigned char MessageAuthenticator[16]{0}; - AddAttribute(ATTR_MessageAuthenticator,sizeof(MessageAuthenticator),MessageAuthenticator); + AddAttribute(ATTR_MessageAuthenticator, sizeof(MessageAuthenticator), + MessageAuthenticator); P_.rawlen = 1 + 1 + 2 + 16 + 1 + 1 + 16; Poco::HMACEngine H(Secret_); @@ -708,24 +700,26 @@ static const struct tok radius_attribute_names[] = { P_.attributes[1 + 1 + p++] = i; } - inline void AddAttribute(unsigned char attr, uint8_t len, const unsigned char * data) { + inline void AddAttribute(unsigned char attr, uint8_t len, const unsigned char *data) { P_.attributes[AttributesLen_++] = attr; P_.attributes[AttributesLen_++] = len; - memcpy(&P_.attributes[AttributesLen_],data,len); - AttributesLen_+=len; + memcpy(&P_.attributes[AttributesLen_], data, len); + AttributesLen_ += len; } - [[nodiscard]] inline const unsigned char * Data() const { return (const unsigned char *) &P_;} + [[nodiscard]] inline const unsigned char *Data() const { + return (const unsigned char *)&P_; + } [[nodiscard]] inline std::uint16_t Len() const { return P_.rawlen; } private: - RawRadiusPacket P_; - uint16_t AttributesLen_=0; - std::string Secret_; + RawRadiusPacket P_; + uint16_t AttributesLen_ = 0; + std::string Secret_; }; inline std::ostream &operator<<(std::ostream &os, RadiusPacket const &P) { - os << P.Attrs_ ; + os << P.Attrs_; return os; } -} \ No newline at end of file +} // namespace OpenWifi::RADIUS \ No newline at end of file diff --git a/src/RADIUS_proxy_server.cpp b/src/RADIUS_proxy_server.cpp index 803c2262..a12c6fb2 100644 --- a/src/RADIUS_proxy_server.cpp +++ b/src/RADIUS_proxy_server.cpp @@ -4,85 +4,108 @@ #include "Poco/JSON/Parser.h" -#include "RADIUS_proxy_server.h" -#include "RADIUS_helpers.h" #include "AP_WS_Server.h" +#include "RADIUS_helpers.h" +#include "RADIUS_proxy_server.h" #include "framework/MicroServiceFuncs.h" namespace OpenWifi { - const int SMALLEST_RADIUS_PACKET = 20+19+4; + const int SMALLEST_RADIUS_PACKET = 20 + 19 + 4; const int DEFAULT_RADIUS_AUTHENTICATION_PORT = 1812; const int DEFAULT_RADIUS_ACCOUNTING_PORT = 1813; const int DEFAULT_RADIUS_CoA_PORT = 3799; int RADIUS_proxy_server::Start() { - ConfigFilename_ = MicroServiceDataDirectory()+"/radius_pool_config.json"; - Poco::File Config(ConfigFilename_); + ConfigFilename_ = MicroServiceDataDirectory() + "/radius_pool_config.json"; + Poco::File Config(ConfigFilename_); - Enabled_ = MicroServiceConfigGetBool("radius.proxy.enable",false); - if(!Enabled_ && !Config.exists()) { + Enabled_ = MicroServiceConfigGetBool("radius.proxy.enable", false); + if (!Enabled_ && !Config.exists()) { StopRADSECServers(); return 0; } - poco_notice(Logger(),"Starting..."); + poco_notice(Logger(), "Starting..."); Enabled_ = true; - Poco::Net::SocketAddress AuthSockAddrV4(Poco::Net::AddressFamily::IPv4, - MicroServiceConfigGetInt("radius.proxy.authentication.port",DEFAULT_RADIUS_AUTHENTICATION_PORT)); - AuthenticationSocketV4_ = std::make_unique(AuthSockAddrV4,true,true); - Poco::Net::SocketAddress AuthSockAddrV6(Poco::Net::AddressFamily::IPv6, - MicroServiceConfigGetInt("radius.proxy.authentication.port",DEFAULT_RADIUS_AUTHENTICATION_PORT)); - AuthenticationSocketV6_ = std::make_unique(AuthSockAddrV6,true,true); + Poco::Net::SocketAddress AuthSockAddrV4( + Poco::Net::AddressFamily::IPv4, + MicroServiceConfigGetInt("radius.proxy.authentication.port", + DEFAULT_RADIUS_AUTHENTICATION_PORT)); + AuthenticationSocketV4_ = + std::make_unique(AuthSockAddrV4, true, true); + Poco::Net::SocketAddress AuthSockAddrV6( + Poco::Net::AddressFamily::IPv6, + MicroServiceConfigGetInt("radius.proxy.authentication.port", + DEFAULT_RADIUS_AUTHENTICATION_PORT)); + AuthenticationSocketV6_ = + std::make_unique(AuthSockAddrV6, true, true); - Poco::Net::SocketAddress AcctSockAddrV4(Poco::Net::AddressFamily::IPv4, - MicroServiceConfigGetInt("radius.proxy.accounting.port",DEFAULT_RADIUS_ACCOUNTING_PORT)); - AccountingSocketV4_ = std::make_unique(AcctSockAddrV4,true,true); - Poco::Net::SocketAddress AcctSockAddrV6(Poco::Net::AddressFamily::IPv6, - MicroServiceConfigGetInt("radius.proxy.accounting.port",DEFAULT_RADIUS_ACCOUNTING_PORT)); - AccountingSocketV6_ = std::make_unique(AcctSockAddrV6,true,true); + Poco::Net::SocketAddress AcctSockAddrV4( + Poco::Net::AddressFamily::IPv4, + MicroServiceConfigGetInt("radius.proxy.accounting.port", + DEFAULT_RADIUS_ACCOUNTING_PORT)); + AccountingSocketV4_ = + std::make_unique(AcctSockAddrV4, true, true); + Poco::Net::SocketAddress AcctSockAddrV6( + Poco::Net::AddressFamily::IPv6, + MicroServiceConfigGetInt("radius.proxy.accounting.port", + DEFAULT_RADIUS_ACCOUNTING_PORT)); + AccountingSocketV6_ = + std::make_unique(AcctSockAddrV6, true, true); - Poco::Net::SocketAddress CoASockAddrV4(Poco::Net::AddressFamily::IPv4, - MicroServiceConfigGetInt("radius.proxy.coa.port",DEFAULT_RADIUS_CoA_PORT)); - CoASocketV4_ = std::make_unique(CoASockAddrV4,true,true); - Poco::Net::SocketAddress CoASockAddrV6(Poco::Net::AddressFamily::IPv6, - MicroServiceConfigGetInt("radius.proxy.coa.port",DEFAULT_RADIUS_CoA_PORT)); - CoASocketV6_ = std::make_unique(CoASockAddrV6,true,true); + Poco::Net::SocketAddress CoASockAddrV4( + Poco::Net::AddressFamily::IPv4, + MicroServiceConfigGetInt("radius.proxy.coa.port", DEFAULT_RADIUS_CoA_PORT)); + CoASocketV4_ = std::make_unique(CoASockAddrV4, true, true); + Poco::Net::SocketAddress CoASockAddrV6( + Poco::Net::AddressFamily::IPv6, + MicroServiceConfigGetInt("radius.proxy.coa.port", DEFAULT_RADIUS_CoA_PORT)); + CoASocketV6_ = std::make_unique(CoASockAddrV6, true, true); RadiusReactor_.reset(); RadiusReactor_ = std::make_unique(); - RadiusReactor_->addEventHandler(*AuthenticationSocketV4_,Poco::NObserver( - *this, &RADIUS_proxy_server::OnAuthenticationSocketReadable)); - RadiusReactor_->addEventHandler(*AuthenticationSocketV6_,Poco::NObserver( - *this, &RADIUS_proxy_server::OnAuthenticationSocketReadable)); + RadiusReactor_->addEventHandler( + *AuthenticationSocketV4_, + Poco::NObserver( + *this, &RADIUS_proxy_server::OnAuthenticationSocketReadable)); + RadiusReactor_->addEventHandler( + *AuthenticationSocketV6_, + Poco::NObserver( + *this, &RADIUS_proxy_server::OnAuthenticationSocketReadable)); - RadiusReactor_->addEventHandler(*AccountingSocketV4_,Poco::NObserver( - *this, &RADIUS_proxy_server::OnAccountingSocketReadable)); - RadiusReactor_->addEventHandler(*AccountingSocketV6_,Poco::NObserver( - *this, &RADIUS_proxy_server::OnAccountingSocketReadable)); + RadiusReactor_->addEventHandler( + *AccountingSocketV4_, + Poco::NObserver( + *this, &RADIUS_proxy_server::OnAccountingSocketReadable)); + RadiusReactor_->addEventHandler( + *AccountingSocketV6_, + Poco::NObserver( + *this, &RADIUS_proxy_server::OnAccountingSocketReadable)); - - RadiusReactor_->addEventHandler(*CoASocketV4_,Poco::NObserver( - *this, &RADIUS_proxy_server::OnCoASocketReadable)); - RadiusReactor_->addEventHandler(*CoASocketV6_,Poco::NObserver( - *this, &RADIUS_proxy_server::OnCoASocketReadable)); + RadiusReactor_->addEventHandler( + *CoASocketV4_, Poco::NObserver( + *this, &RADIUS_proxy_server::OnCoASocketReadable)); + RadiusReactor_->addEventHandler( + *CoASocketV6_, Poco::NObserver( + *this, &RADIUS_proxy_server::OnCoASocketReadable)); ParseConfig(); StartRADSECServers(); RadiusReactorThread_.start(*RadiusReactor_); - Utils::SetThreadName(RadiusReactorThread_,"rad:reactor"); + Utils::SetThreadName(RadiusReactorThread_, "rad:reactor"); Running_ = true; return 0; } void RADIUS_proxy_server::Stop() { - if(Enabled_ && Running_) { - poco_information(Logger(),"Stopping..."); + if (Enabled_ && Running_) { + poco_information(Logger(), "Stopping..."); RadiusReactor_->removeEventHandler( *AuthenticationSocketV4_, Poco::NObserver( @@ -127,96 +150,112 @@ namespace OpenWifi { StopRADSECServers(); RadiusReactor_->stop(); RadiusReactorThread_.join(); - Running_=false; - poco_information(Logger(),"Stopped..."); + Running_ = false; + poco_information(Logger(), "Stopped..."); } } void RADIUS_proxy_server::StartRADSECServers() { - std::lock_guard G(Mutex_); - for(const auto &pool:PoolList_.pools) { - for(const auto &entry:pool.authConfig.servers) { - if(entry.radsec) { - RADSECservers_[ Poco::Net::SocketAddress(entry.ip,0) ] = std::make_unique(*RadiusReactor_,entry); + std::lock_guard G(Mutex_); + for (const auto &pool : PoolList_.pools) { + for (const auto &entry : pool.authConfig.servers) { + if (entry.radsec) { + RADSECservers_[Poco::Net::SocketAddress(entry.ip, 0)] = + std::make_unique(*RadiusReactor_, entry); } } } } void RADIUS_proxy_server::StopRADSECServers() { - std::lock_guard G(Mutex_); + std::lock_guard G(Mutex_); RADSECservers_.clear(); } - void RADIUS_proxy_server::OnAccountingSocketReadable(const Poco::AutoPtr& pNf) { - Poco::Net::SocketAddress Sender; - RADIUS::RadiusPacket P; + void RADIUS_proxy_server::OnAccountingSocketReadable( + const Poco::AutoPtr &pNf) { + Poco::Net::SocketAddress Sender; + RADIUS::RadiusPacket P; - auto ReceiveSize = pNf->socket().impl()->receiveBytes(P.Buffer(),P.BufferLen()); - if(ReceiveSizesocket().impl()->receiveBytes(P.Buffer(), P.BufferLen()); + if (ReceiveSize < SMALLEST_RADIUS_PACKET) { + poco_warning(Logger(), "Accounting: bad packet received."); return; } P.Evaluate(ReceiveSize); auto SerialNumber = P.ExtractSerialNumberFromProxyState(); - if(SerialNumber.empty()) { - poco_warning(Logger(),"Accounting: missing serial number."); + if (SerialNumber.empty()) { + poco_warning(Logger(), "Accounting: missing serial number."); return; } auto CallingStationID = P.ExtractCallingStationID(); auto CalledStationID = P.ExtractCalledStationID(); - poco_debug(Logger(), fmt::format("Accounting Packet received for {}, CalledStationID: {}, CallingStationID:{}",SerialNumber, CalledStationID, CallingStationID)); - AP_WS_Server()->SendRadiusAccountingData(SerialNumber,P.Buffer(),P.Size()); + poco_debug( + Logger(), + fmt::format( + "Accounting Packet received for {}, CalledStationID: {}, CallingStationID:{}", + SerialNumber, CalledStationID, CallingStationID)); + AP_WS_Server()->SendRadiusAccountingData(SerialNumber, P.Buffer(), P.Size()); } - void RADIUS_proxy_server::OnAuthenticationSocketReadable(const Poco::AutoPtr& pNf) { - Poco::Net::SocketAddress Sender; - RADIUS::RadiusPacket P; + void RADIUS_proxy_server::OnAuthenticationSocketReadable( + const Poco::AutoPtr &pNf) { + Poco::Net::SocketAddress Sender; + RADIUS::RadiusPacket P; - auto ReceiveSize = pNf->socket().impl()->receiveBytes(P.Buffer(),P.BufferLen()); - if(ReceiveSizesocket().impl()->receiveBytes(P.Buffer(), P.BufferLen()); + if (ReceiveSize < SMALLEST_RADIUS_PACKET) { + poco_warning(Logger(), "Authentication: bad packet received."); return; } P.Evaluate(ReceiveSize); auto SerialNumber = P.ExtractSerialNumberFromProxyState(); - if(SerialNumber.empty()) { - poco_warning(Logger(),"Authentication: missing serial number."); + if (SerialNumber.empty()) { + poco_warning(Logger(), "Authentication: missing serial number."); return; } auto CallingStationID = P.ExtractCallingStationID(); auto CalledStationID = P.ExtractCalledStationID(); - poco_debug(Logger(), fmt::format("Authentication Packet received for {}, CalledStationID: {}, CallingStationID:{}",SerialNumber, CalledStationID, CallingStationID)); - AP_WS_Server()->SendRadiusAuthenticationData(SerialNumber,P.Buffer(),P.Size()); + poco_debug( + Logger(), + fmt::format( + "Authentication Packet received for {}, CalledStationID: {}, CallingStationID:{}", + SerialNumber, CalledStationID, CallingStationID)); + AP_WS_Server()->SendRadiusAuthenticationData(SerialNumber, P.Buffer(), P.Size()); } - void RADIUS_proxy_server::OnCoASocketReadable(const Poco::AutoPtr& pNf) { - Poco::Net::SocketAddress Sender; - RADIUS::RadiusPacket P; + void RADIUS_proxy_server::OnCoASocketReadable( + const Poco::AutoPtr &pNf) { + Poco::Net::SocketAddress Sender; + RADIUS::RadiusPacket P; - auto ReceiveSize = pNf.get()->socket().impl()->receiveBytes(P.Buffer(),P.BufferLen()); - if(ReceiveSizesocket().impl()->receiveBytes(P.Buffer(), P.BufferLen()); + if (ReceiveSize < SMALLEST_RADIUS_PACKET) { + poco_warning(Logger(), "CoA/DM: bad packet received."); return; } P.Evaluate(ReceiveSize); auto SerialNumber = P.ExtractSerialNumberTIP(); - if(SerialNumber.empty()) { - poco_warning(Logger(),"CoA/DM: missing serial number."); + if (SerialNumber.empty()) { + poco_warning(Logger(), "CoA/DM: missing serial number."); return; } auto CallingStationID = P.ExtractCallingStationID(); auto CalledStationID = P.ExtractCalledStationID(); - poco_debug(Logger(), fmt::format("CoA Packet received for {}, CalledStationID: {}, CallingStationID:{}",SerialNumber, CalledStationID, CallingStationID)); - AP_WS_Server()->SendRadiusCoAData(SerialNumber,P.Buffer(),P.Size()); + poco_debug( + Logger(), + fmt::format("CoA Packet received for {}, CalledStationID: {}, CallingStationID:{}", + SerialNumber, CalledStationID, CallingStationID)); + AP_WS_Server()->SendRadiusCoAData(SerialNumber, P.Buffer(), P.Size()); } - void RADIUS_proxy_server::SendAccountingData(const std::string &serialNumber, const char *buffer, std::size_t size) { + void RADIUS_proxy_server::SendAccountingData(const std::string &serialNumber, + const char *buffer, std::size_t size) { - if(!Continue()) + if (!Continue()) return; try { @@ -257,41 +296,46 @@ namespace OpenWifi { fmt::format("{}: Could not send Accounting packet packet to {}.", serialNumber, Destination)); else - poco_debug(Logger(), fmt::format("{}: Sending Accounting Packet to {}, CalledStationID: {}, CallingStationID:{}", + poco_debug(Logger(), fmt::format("{}: Sending Accounting Packet to {}, " + "CalledStationID: {}, CallingStationID:{}", serialNumber, FinalDestination.toString(), CalledStationID, CallingStationID)); } } catch (const Poco::Exception &E) { Logger().log(E); } catch (...) { - poco_warning(Logger(),fmt::format("Bad RADIUS ACCT Packet from {}. Dropped.",serialNumber)); + poco_warning(Logger(), + fmt::format("Bad RADIUS ACCT Packet from {}. Dropped.", serialNumber)); } } - bool RADIUS_proxy_server::SendData( Poco::Net::DatagramSocket & Sock, const unsigned char *buf , std::size_t size, const Poco::Net::SocketAddress &S) { - return Sock.sendTo(buf, size, S)==(int)size; + bool RADIUS_proxy_server::SendData(Poco::Net::DatagramSocket &Sock, const unsigned char *buf, + std::size_t size, const Poco::Net::SocketAddress &S) { + return Sock.sendTo(buf, size, S) == (int)size; } - void RADIUS_proxy_server::SendAuthenticationData(const std::string &serialNumber, const char *buffer, std::size_t size) { + void RADIUS_proxy_server::SendAuthenticationData(const std::string &serialNumber, + const char *buffer, std::size_t size) { - if(!Continue()) + if (!Continue()) return; try { - RADIUS::RadiusPacket P((unsigned char *)buffer,size); + RADIUS::RadiusPacket P((unsigned char *)buffer, size); auto Destination = P.ExtractProxyStateDestination(); auto CallingStationID = P.ExtractCallingStationID(); auto CalledStationID = P.ExtractCalledStationID(); - Poco::Net::SocketAddress Dst(Destination); + Poco::Net::SocketAddress Dst(Destination); - std::lock_guard G(Mutex_); + std::lock_guard G(Mutex_); bool UseRADSEC = false; auto FinalDestination = Route(radius_type::auth, Dst, P, UseRADSEC); - if(UseRADSEC) { - Poco::Net::SocketAddress RSP(FinalDestination.host(),0); + if (UseRADSEC) { + Poco::Net::SocketAddress RSP(FinalDestination.host(), 0); auto DestinationServer = RADSECservers_.find(RSP); - if(DestinationServer!=end(RADSECservers_)) { - DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer, size); + if (DestinationServer != end(RADSECservers_)) { + DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer, + size); } } else { if ((Dst.family() == Poco::Net::SocketAddress::IPv4 && @@ -300,66 +344,74 @@ namespace OpenWifi { AuthenticationSocketV6_ == nullptr)) { poco_debug( Logger(), - fmt::format("AUTH: Trying to use RADIUS GW PROXY but not configured. Device={}", - serialNumber)); + fmt::format( + "AUTH: Trying to use RADIUS GW PROXY but not configured. Device={}", + serialNumber)); return; } - auto AllSent = - SendData(Dst.family() == Poco::Net::SocketAddress::IPv4 ? *AuthenticationSocketV4_ - : *AuthenticationSocketV6_, - (const unsigned char *)buffer, size, FinalDestination); + auto AllSent = SendData(Dst.family() == Poco::Net::SocketAddress::IPv4 + ? *AuthenticationSocketV4_ + : *AuthenticationSocketV6_, + (const unsigned char *)buffer, size, FinalDestination); if (!AllSent) poco_error(Logger(), fmt::format("{}: Could not send Authentication packet packet to {}.", serialNumber, Destination)); else - poco_debug(Logger(), fmt::format("{}: Sending Authentication Packet to {}, CalledStationID: {}, CallingStationID:{}", + poco_debug(Logger(), fmt::format("{}: Sending Authentication Packet to {}, " + "CalledStationID: {}, CallingStationID:{}", serialNumber, FinalDestination.toString(), CalledStationID, CallingStationID)); } } catch (const Poco::Exception &E) { Logger().log(E); } catch (...) { - poco_warning(Logger(),fmt::format("Bad RADIUS AUTH Packet from {}. Dropped.",serialNumber)); + poco_warning(Logger(), + fmt::format("Bad RADIUS AUTH Packet from {}. Dropped.", serialNumber)); } - } - void RADIUS_proxy_server::SendCoAData(const std::string &serialNumber, const char *buffer, std::size_t size) { + void RADIUS_proxy_server::SendCoAData(const std::string &serialNumber, const char *buffer, + std::size_t size) { - if(!Continue()) + if (!Continue()) return; try { - RADIUS::RadiusPacket P((unsigned char *)buffer,size); + RADIUS::RadiusPacket P((unsigned char *)buffer, size); auto Destination = P.ExtractProxyStateDestination(); - if(Destination.empty()) { + if (Destination.empty()) { Destination = "0.0.0.0:0"; } - Poco::Net::SocketAddress Dst(Destination); - std::lock_guard G(Mutex_); + Poco::Net::SocketAddress Dst(Destination); + std::lock_guard G(Mutex_); bool UseRADSEC = false; auto FinalDestination = Route(radius_type::coa, Dst, P, UseRADSEC); - if(UseRADSEC) { - Poco::Net::SocketAddress RSP(FinalDestination.host(),0); + if (UseRADSEC) { + Poco::Net::SocketAddress RSP(FinalDestination.host(), 0); auto DestinationServer = RADSECservers_.find(RSP); - if(DestinationServer!=end(RADSECservers_)) { - DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer, size); + if (DestinationServer != end(RADSECservers_)) { + DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer, + size); } } else { - if( (Dst.family() == Poco::Net::SocketAddress::IPv4 && CoASocketV4_== nullptr) || - (Dst.family() == Poco::Net::SocketAddress::IPv6 && CoASocketV6_== nullptr)) { - poco_debug(Logger(),fmt::format("CoA: Trying to use RADIUS GW PROXY but not configured. Device={}",serialNumber)); + if ((Dst.family() == Poco::Net::SocketAddress::IPv4 && CoASocketV4_ == nullptr) || + (Dst.family() == Poco::Net::SocketAddress::IPv6 && CoASocketV6_ == nullptr)) { + poco_debug( + Logger(), + fmt::format( + "CoA: Trying to use RADIUS GW PROXY but not configured. Device={}", + serialNumber)); return; } - auto AllSent = SendData(Dst.family() == Poco::Net::SocketAddress::IPv4 ? *CoASocketV4_ - : *CoASocketV6_, - (const unsigned char *)buffer, size, FinalDestination); + auto AllSent = SendData( + Dst.family() == Poco::Net::SocketAddress::IPv4 ? *CoASocketV4_ : *CoASocketV6_, + (const unsigned char *)buffer, size, FinalDestination); if (!AllSent) - poco_error(Logger(),fmt::format("{}: Could not send CoA packet packet to {}.", - serialNumber, Destination)); + poco_error(Logger(), fmt::format("{}: Could not send CoA packet packet to {}.", + serialNumber, Destination)); else poco_debug(Logger(), fmt::format("{}: Sending CoA Packet to {}", serialNumber, FinalDestination.toString())); @@ -367,39 +419,42 @@ namespace OpenWifi { } catch (const Poco::Exception &E) { Logger().log(E); } catch (...) { - poco_warning(Logger(),fmt::format("Bad RADIUS CoA/DM Packet from {}. Dropped.",serialNumber)); + poco_warning(Logger(), + fmt::format("Bad RADIUS CoA/DM Packet from {}. Dropped.", serialNumber)); } } - void RADIUS_proxy_server::ParseServerList(const GWObjects::RadiusProxyServerConfig & Config, std::vector &V4, std::vector &V6, bool setAsDefault) { - uint64_t TotalV4=0, TotalV6=0; + void RADIUS_proxy_server::ParseServerList(const GWObjects::RadiusProxyServerConfig &Config, + std::vector &V4, + std::vector &V6, bool setAsDefault) { + uint64_t TotalV4 = 0, TotalV6 = 0; - for(const auto &server:Config.servers) { + for (const auto &server : Config.servers) { Poco::Net::IPAddress a; - if(!Poco::Net::IPAddress::tryParse(server.ip,a)) { - poco_error(Logger(),fmt::format("RADIUS-PARSE Config: server address {} is nto a valid address in v4 or v6. Entry skipped.",server.ip)); + if (!Poco::Net::IPAddress::tryParse(server.ip, a)) { + poco_error(Logger(), fmt::format("RADIUS-PARSE Config: server address {} is nto a " + "valid address in v4 or v6. Entry skipped.", + server.ip)); continue; } - auto S = Poco::Net::SocketAddress(fmt::format("{}:{}",server.ip,server.port)); - Destination D{ - .Addr = S, - .state = 0, - .step = 0, - .weight = server.weight, - .available = true, - .strategy = Config.strategy, - .monitor = Config. monitor, - .monitorMethod = Config.monitorMethod, - .methodParameters = Config.methodParameters, - .useAsDefault = setAsDefault, - .useRADSEC = server.radsec, - .realms = server.radsecRealms - }; + auto S = Poco::Net::SocketAddress(fmt::format("{}:{}", server.ip, server.port)); + Destination D{.Addr = S, + .state = 0, + .step = 0, + .weight = server.weight, + .available = true, + .strategy = Config.strategy, + .monitor = Config.monitor, + .monitorMethod = Config.monitorMethod, + .methodParameters = Config.methodParameters, + .useAsDefault = setAsDefault, + .useRADSEC = server.radsec, + .realms = server.radsecRealms}; - if(setAsDefault && D.useRADSEC) + if (setAsDefault && D.useRADSEC) DefaultIsRADSEC_ = true; - if(S.family()==Poco::Net::IPAddress::IPv4) { + if (S.family() == Poco::Net::IPAddress::IPv4) { TotalV4 += server.weight; V4.push_back(D); } else { @@ -408,16 +463,16 @@ namespace OpenWifi { } } - for(auto &i:V4) { - if(TotalV4==0) { + for (auto &i : V4) { + if (TotalV4 == 0) { i.step = 1000; } else { i.step = 1000 - ((1000 * i.weight) / TotalV4); } } - for(auto &i:V6) { - if(TotalV6==0) { + for (auto &i : V6) { + if (TotalV6 == 0) { i.step = 1000; } else { i.step = 1000 - ((1000 * i.weight) / TotalV6); @@ -428,59 +483,68 @@ namespace OpenWifi { void RADIUS_proxy_server::ParseConfig() { try { - Poco::File F(ConfigFilename_); + Poco::File F(ConfigFilename_); - std::lock_guard G(Mutex_); + std::lock_guard G(Mutex_); - if(F.exists()) { - std::ifstream ifs(ConfigFilename_,std::ios_base::binary); - Poco::JSON::Parser P; + if (F.exists()) { + std::ifstream ifs(ConfigFilename_, std::ios_base::binary); + Poco::JSON::Parser P; auto RawConfig = P.parse(ifs).extract(); - GWObjects::RadiusProxyPoolList RPC; - if(RPC.from_json(RawConfig)) { + GWObjects::RadiusProxyPoolList RPC; + if (RPC.from_json(RawConfig)) { ResetConfig(); PoolList_ = RPC; - for(const auto &pool:RPC.pools) { - RadiusPool NewPool; - ParseServerList(pool.authConfig, NewPool.AuthV4, NewPool.AuthV6, pool.useByDefault); - ParseServerList(pool.acctConfig, NewPool.AcctV4, NewPool.AcctV6, pool.useByDefault); - ParseServerList(pool.coaConfig, NewPool.CoaV4, NewPool.CoaV6, pool.useByDefault); + for (const auto &pool : RPC.pools) { + RadiusPool NewPool; + ParseServerList(pool.authConfig, NewPool.AuthV4, NewPool.AuthV6, + pool.useByDefault); + ParseServerList(pool.acctConfig, NewPool.AcctV4, NewPool.AcctV6, + pool.useByDefault); + ParseServerList(pool.coaConfig, NewPool.CoaV4, NewPool.CoaV6, + pool.useByDefault); Pools_.push_back(NewPool); } } else { - poco_warning(Logger(),fmt::format("Configuration file '{}' is bad.",ConfigFilename_)); + poco_warning(Logger(), + fmt::format("Configuration file '{}' is bad.", ConfigFilename_)); } } else { - poco_warning(Logger(),fmt::format("No configuration file '{}' exists.",ConfigFilename_)); + poco_warning(Logger(), + fmt::format("No configuration file '{}' exists.", ConfigFilename_)); } } catch (const Poco::Exception &E) { Logger().log(E); } catch (...) { - poco_error(Logger(),fmt::format("Error while parsing configuration file '{}'",ConfigFilename_)); + poco_error(Logger(), + fmt::format("Error while parsing configuration file '{}'", ConfigFilename_)); } } - static bool RealmMatch(const std::string &user_realm, const std::string & realm) { - if(realm.find_first_of('*') == std::string::npos) + static bool RealmMatch(const std::string &user_realm, const std::string &realm) { + if (realm.find_first_of('*') == std::string::npos) return user_realm == realm; return realm.find(user_realm) != std::string::npos; } - Poco::Net::SocketAddress RADIUS_proxy_server::DefaultRoute(radius_type rtype, const Poco::Net::SocketAddress &RequestedAddress, const RADIUS::RadiusPacket &P, bool &UseRADSEC) { - bool IsV4 = RequestedAddress.family()==Poco::Net::SocketAddress::IPv4; + Poco::Net::SocketAddress + RADIUS_proxy_server::DefaultRoute(radius_type rtype, + const Poco::Net::SocketAddress &RequestedAddress, + const RADIUS::RadiusPacket &P, bool &UseRADSEC) { + bool IsV4 = RequestedAddress.family() == Poco::Net::SocketAddress::IPv4; // find the realm... auto UserName = P.UserName(); - if(!UserName.empty()) { + if (!UserName.empty()) { auto UserTokens = Poco::StringTokenizer(UserName, "@"); auto UserRealm = ((UserTokens.count() > 1) ? UserTokens[1] : UserName); Poco::toLowerInPlace(UserRealm); - for(const auto &pool:Pools_) { - for(const auto &server:pool.AuthV4) { - if(!server.realms.empty()) { - for(const auto &realm:server.realms) { - if (RealmMatch(UserRealm,realm)) { + for (const auto &pool : Pools_) { + for (const auto &server : pool.AuthV4) { + if (!server.realms.empty()) { + for (const auto &realm : server.realms) { + if (RealmMatch(UserRealm, realm)) { std::cout << "Realm match..." << std::endl; UseRADSEC = true; return server.Addr; @@ -491,58 +555,65 @@ namespace OpenWifi { } } - if(DefaultIsRADSEC_) { + if (DefaultIsRADSEC_) { UseRADSEC = true; - return (IsV4 ? Pools_[DefaultPoolIndex_].AuthV4[0].Addr : Pools_[DefaultPoolIndex_].AuthV6[0].Addr ); + return (IsV4 ? Pools_[DefaultPoolIndex_].AuthV4[0].Addr + : Pools_[DefaultPoolIndex_].AuthV6[0].Addr); } - switch(rtype) { - case radius_type::auth: { - return ChooseAddress(IsV4 ? Pools_[DefaultPoolIndex_].AuthV4 - : Pools_[DefaultPoolIndex_].AuthV6, - RequestedAddress); - } - case radius_type::acct: - default: { - return ChooseAddress(IsV4 ? Pools_[DefaultPoolIndex_].AcctV4 - : Pools_[DefaultPoolIndex_].AcctV6, - RequestedAddress); - } - case radius_type::coa: { - return ChooseAddress(IsV4 ? Pools_[DefaultPoolIndex_].CoaV4 - : Pools_[DefaultPoolIndex_].CoaV6, - RequestedAddress); - } - } + switch (rtype) { + case radius_type::auth: { + return ChooseAddress(IsV4 ? Pools_[DefaultPoolIndex_].AuthV4 + : Pools_[DefaultPoolIndex_].AuthV6, + RequestedAddress); + } + case radius_type::acct: + default: { + return ChooseAddress(IsV4 ? Pools_[DefaultPoolIndex_].AcctV4 + : Pools_[DefaultPoolIndex_].AcctV6, + RequestedAddress); + } + case radius_type::coa: { + return ChooseAddress(IsV4 ? Pools_[DefaultPoolIndex_].CoaV4 + : Pools_[DefaultPoolIndex_].CoaV6, + RequestedAddress); + } + } } - Poco::Net::SocketAddress RADIUS_proxy_server::Route([[maybe_unused]] radius_type rtype, const Poco::Net::SocketAddress &RequestedAddress, const RADIUS::RadiusPacket &P, bool &UseRADSEC) { - std::lock_guard G(Mutex_); + Poco::Net::SocketAddress + RADIUS_proxy_server::Route([[maybe_unused]] radius_type rtype, + const Poco::Net::SocketAddress &RequestedAddress, + const RADIUS::RadiusPacket &P, bool &UseRADSEC) { + std::lock_guard G(Mutex_); - if(Pools_.empty()) { + if (Pools_.empty()) { UseRADSEC = false; return RequestedAddress; } - bool IsV4 = RequestedAddress.family()==Poco::Net::SocketAddress::IPv4; + bool IsV4 = RequestedAddress.family() == Poco::Net::SocketAddress::IPv4; bool useDefault; - useDefault = IsV4 ? RequestedAddress.host() == Poco::Net::IPAddress::wildcard(Poco::Net::IPAddress::IPv4) : RequestedAddress.host() == Poco::Net::IPAddress::wildcard(Poco::Net::IPAddress::IPv6) ; + useDefault = IsV4 ? RequestedAddress.host() == + Poco::Net::IPAddress::wildcard(Poco::Net::IPAddress::IPv4) + : RequestedAddress.host() == + Poco::Net::IPAddress::wildcard(Poco::Net::IPAddress::IPv6); - if(useDefault) { + if (useDefault) { return DefaultRoute(rtype, RequestedAddress, P, UseRADSEC); } - auto isAddressInPool = [&](const std::vector & D, bool &UseRADSEC) -> bool { - for(const auto &entry:D) - if(entry.Addr.host()==RequestedAddress.host()) { + auto isAddressInPool = [&](const std::vector &D, bool &UseRADSEC) -> bool { + for (const auto &entry : D) + if (entry.Addr.host() == RequestedAddress.host()) { UseRADSEC = entry.useRADSEC; return true; } return false; }; - for(auto &i:Pools_) { - switch(rtype) { + for (auto &i : Pools_) { + switch (rtype) { case radius_type::coa: { if (isAddressInPool((IsV4 ? i.CoaV4 : i.CoaV6), UseRADSEC)) { return ChooseAddress(IsV4 ? i.CoaV4 : i.CoaV6, RequestedAddress); @@ -565,9 +636,11 @@ namespace OpenWifi { return RequestedAddress; } - Poco::Net::SocketAddress RADIUS_proxy_server::ChooseAddress(std::vector &Pool, const Poco::Net::SocketAddress & OriginalAddress) { + Poco::Net::SocketAddress + RADIUS_proxy_server::ChooseAddress(std::vector &Pool, + const Poco::Net::SocketAddress &OriginalAddress) { - if(Pool.size()==1) { + if (Pool.size() == 1) { return Pool[0].Addr; } @@ -628,12 +701,12 @@ namespace OpenWifi { } void RADIUS_proxy_server::SetConfig(const GWObjects::RadiusProxyPoolList &C) { - std::lock_guard G(Mutex_); + std::lock_guard G(Mutex_); - Poco::JSON::Object Disk; + Poco::JSON::Object Disk; C.to_json(Disk); - std::ofstream ofs(ConfigFilename_, std::ios_base::trunc | std::ios_base::binary ); + std::ofstream ofs(ConfigFilename_, std::ios_base::trunc | std::ios_base::binary); Disk.stringify(ofs); ofs.close(); @@ -646,27 +719,26 @@ namespace OpenWifi { void RADIUS_proxy_server::ResetConfig() { PoolList_.pools.clear(); Pools_.clear(); - DefaultPoolIndex_=0; - DefaultIsRADSEC_=false; + DefaultPoolIndex_ = 0; + DefaultIsRADSEC_ = false; } void RADIUS_proxy_server::DeleteConfig() { - std::lock_guard G(Mutex_); + std::lock_guard G(Mutex_); try { Poco::File F(ConfigFilename_); if (F.exists()) F.remove(); } catch (...) { - } Stop(); ResetConfig(); } void RADIUS_proxy_server::GetConfig(GWObjects::RadiusProxyPoolList &C) { - std::lock_guard G(Mutex_); + std::lock_guard G(Mutex_); C = PoolList_; } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/RADIUS_proxy_server.h b/src/RADIUS_proxy_server.h index 83eba152..7c4b391e 100644 --- a/src/RADIUS_proxy_server.h +++ b/src/RADIUS_proxy_server.h @@ -15,15 +15,12 @@ namespace OpenWifi { - enum class radius_type { - auth, acct, coa - }; - + enum class radius_type { auth, acct, coa }; class RADIUS_proxy_server : public SubSystemServer { public: inline static auto instance() { - static auto instance_= new RADIUS_proxy_server; + static auto instance_ = new RADIUS_proxy_server; return instance_; } @@ -31,12 +28,15 @@ namespace OpenWifi { void Stop() final; inline bool Enabled() const { return Enabled_; } - void OnAccountingSocketReadable(const Poco::AutoPtr& pNf); - void OnAuthenticationSocketReadable(const Poco::AutoPtr& pNf); - void OnCoASocketReadable(const Poco::AutoPtr& pNf); + void OnAccountingSocketReadable(const Poco::AutoPtr &pNf); + void + OnAuthenticationSocketReadable(const Poco::AutoPtr &pNf); + void OnCoASocketReadable(const Poco::AutoPtr &pNf); - void SendAccountingData(const std::string &serialNumber, const char *buffer, std::size_t size); - void SendAuthenticationData(const std::string &serialNumber, const char *buffer, std::size_t size); + void SendAccountingData(const std::string &serialNumber, const char *buffer, + std::size_t size); + void SendAuthenticationData(const std::string &serialNumber, const char *buffer, + std::size_t size); void SendCoAData(const std::string &serialNumber, const char *buffer, std::size_t size); void SetConfig(const GWObjects::RadiusProxyPoolList &C); @@ -47,70 +47,73 @@ namespace OpenWifi { void StopRADSECServers(); struct Destination { - Poco::Net::SocketAddress Addr; - uint64_t state = 0; - uint64_t step = 0; - uint64_t weight=0; - bool available = true; - std::string strategy; - bool monitor=false; - std::string monitorMethod; - std::vector methodParameters; - bool useAsDefault=false; - bool useRADSEC=false; - std::vector realms; + Poco::Net::SocketAddress Addr; + uint64_t state = 0; + uint64_t step = 0; + uint64_t weight = 0; + bool available = true; + std::string strategy; + bool monitor = false; + std::string monitorMethod; + std::vector methodParameters; + bool useAsDefault = false; + bool useRADSEC = false; + std::vector realms; }; - inline bool Continue() const { - return Running_ && Enabled_ && !Pools_.empty(); - } + inline bool Continue() const { return Running_ && Enabled_ && !Pools_.empty(); } private: - std::unique_ptr AccountingSocketV4_; - std::unique_ptr AccountingSocketV6_; - std::unique_ptr AuthenticationSocketV4_; - std::unique_ptr AuthenticationSocketV6_; - std::unique_ptr CoASocketV4_; - std::unique_ptr CoASocketV6_; - std::unique_ptr RadiusReactor_; - Poco::Thread RadiusReactorThread_; + std::unique_ptr AccountingSocketV4_; + std::unique_ptr AccountingSocketV6_; + std::unique_ptr AuthenticationSocketV4_; + std::unique_ptr AuthenticationSocketV6_; + std::unique_ptr CoASocketV4_; + std::unique_ptr CoASocketV6_; + std::unique_ptr RadiusReactor_; + Poco::Thread RadiusReactorThread_; - GWObjects::RadiusProxyPoolList PoolList_; - std::string ConfigFilename_; + GWObjects::RadiusProxyPoolList PoolList_; + std::string ConfigFilename_; std::map> RADSECservers_; struct RadiusPool { - std::vector AuthV4; - std::vector AuthV6; - std::vector AcctV4; - std::vector AcctV6; - std::vector CoaV4; - std::vector CoaV6; + std::vector AuthV4; + std::vector AuthV6; + std::vector AcctV4; + std::vector AcctV6; + std::vector CoaV4; + std::vector CoaV6; }; - std::vector Pools_; - uint DefaultPoolIndex_=0; - bool Enabled_=false; - bool DefaultIsRADSEC_=false; - std::atomic_bool Running_=false; + std::vector Pools_; + uint DefaultPoolIndex_ = 0; + bool Enabled_ = false; + bool DefaultIsRADSEC_ = false; + std::atomic_bool Running_ = false; - RADIUS_proxy_server() noexcept: - SubSystemServer("RADIUS-PROXY", "RADIUS-PROXY", "radius.proxy") - { - } + RADIUS_proxy_server() noexcept + : SubSystemServer("RADIUS-PROXY", "RADIUS-PROXY", "radius.proxy") {} - static bool SendData( Poco::Net::DatagramSocket & Sock, const unsigned char *buf , std::size_t size, const Poco::Net::SocketAddress &S); + static bool SendData(Poco::Net::DatagramSocket &Sock, const unsigned char *buf, + std::size_t size, const Poco::Net::SocketAddress &S); void ParseConfig(); void ResetConfig(); - Poco::Net::SocketAddress Route(radius_type rtype, const Poco::Net::SocketAddress &A, const RADIUS::RadiusPacket &P, bool &UseRADSEC); - void ParseServerList(const GWObjects::RadiusProxyServerConfig & Config, std::vector &V4, std::vector &V6, bool setAsDefault); - static Poco::Net::SocketAddress ChooseAddress(std::vector &Pool, const Poco::Net::SocketAddress & OriginalAddress); - Poco::Net::SocketAddress DefaultRoute([[maybe_unused]] radius_type rtype, const Poco::Net::SocketAddress &RequestedAddress, const RADIUS::RadiusPacket &P, bool &UseRADSEC); + Poco::Net::SocketAddress Route(radius_type rtype, const Poco::Net::SocketAddress &A, + const RADIUS::RadiusPacket &P, bool &UseRADSEC); + void ParseServerList(const GWObjects::RadiusProxyServerConfig &Config, + std::vector &V4, std::vector &V6, + bool setAsDefault); + static Poco::Net::SocketAddress + ChooseAddress(std::vector &Pool, + const Poco::Net::SocketAddress &OriginalAddress); + Poco::Net::SocketAddress DefaultRoute([[maybe_unused]] radius_type rtype, + const Poco::Net::SocketAddress &RequestedAddress, + const RADIUS::RadiusPacket &P, bool &UseRADSEC); }; inline auto RADIUS_proxy_server() { return RADIUS_proxy_server::instance(); } -} - +} // namespace OpenWifi diff --git a/src/RADSEC_server.h b/src/RADSEC_server.h index 855fa58f..08d78488 100644 --- a/src/RADSEC_server.h +++ b/src/RADSEC_server.h @@ -4,42 +4,37 @@ #pragma once -#include #include +#include #include "RESTObjects/RESTAPI_GWobjects.h" -#include "Poco/Net/SocketReactor.h" -#include "Poco/Net/SecureStreamSocket.h" -#include "Poco/Net/Context.h" #include "Poco/Crypto/X509Certificate.h" +#include "Poco/Net/Context.h" #include "Poco/Net/NetException.h" +#include "Poco/Net/SecureStreamSocket.h" +#include "Poco/Net/SocketReactor.h" #include "Poco/TemporaryFile.h" #include "framework/MicroServiceFuncs.h" #include "fmt/format.h" -#include "RADIUS_helpers.h" #include "AP_WS_Server.h" +#include "RADIUS_helpers.h" namespace OpenWifi { class RADSEC_server : public Poco::Runnable { public: - RADSEC_server(Poco::Net::SocketReactor & R, GWObjects::RadiusProxyServerEntry E) : - Reactor_(R), - Server_(std::move(E)), - Logger_(Poco::Logger::get(fmt::format("RADSEC: {}@{}:{}", - Server_.name , - Server_.ip, - Server_.port))) { + RADSEC_server(Poco::Net::SocketReactor &R, GWObjects::RadiusProxyServerEntry E) + : Reactor_(R), Server_(std::move(E)), + Logger_(Poco::Logger::get( + fmt::format("RADSEC: {}@{}:{}", Server_.name, Server_.ip, Server_.port))) { Start(); } - ~RADSEC_server() { - Stop(); - } + ~RADSEC_server() { Stop(); } inline int Start() { ReconnectThread_.start(*this); @@ -55,17 +50,17 @@ namespace OpenWifi { inline void run() final { Poco::Thread::trySleep(3000); - std::uint64_t LastStatus=0 ; - auto RadSecKeepAlive = MicroServiceConfigGetInt("radsec.keepalive",120); - while(TryAgain_) { - if(!Connected_) { + std::uint64_t LastStatus = 0; + auto RadSecKeepAlive = MicroServiceConfigGetInt("radsec.keepalive", 120); + while (TryAgain_) { + if (!Connected_) { std::lock_guard G(LocalMutex_); - LastStatus = Utils::Now() ; + LastStatus = Utils::Now(); Connect(); - } else if( (Utils::Now() - LastStatus) > RadSecKeepAlive) { + } else if ((Utils::Now() - LastStatus) > RadSecKeepAlive) { RADIUS::RadiusOutputPacket P(Server_.radsecSecret); P.MakeStatusMessage(); - poco_information(Logger_,"Keep-Alive message."); + poco_information(Logger_, "Keep-Alive message."); Socket_->sendBytes(P.Data(), P.Len()); LastStatus = Utils::Now(); } @@ -73,7 +68,8 @@ namespace OpenWifi { } } - inline bool SendData(const std::string &serial_number, const unsigned char *buffer, int length) { + inline bool SendData(const std::string &serial_number, const unsigned char *buffer, + int length) { try { if (Connected_) { RADIUS::RadiusPacket P(buffer, length); @@ -93,21 +89,22 @@ namespace OpenWifi { } catch (const Poco::Exception &E) { Logger_.log(E); } catch (...) { - poco_warning(Logger_,"Exception occurred: while sending data."); + poco_warning(Logger_, "Exception occurred: while sending data."); } return false; } - inline void onData([[maybe_unused]] const Poco::AutoPtr& pNf) { + inline void + onData([[maybe_unused]] const Poco::AutoPtr &pNf) { unsigned char Buffer[4096]; try { - auto NumberOfReceivedBytes = Socket_->receiveBytes(Buffer,sizeof(Buffer)); - if(NumberOfReceivedBytes>=20) { - RADIUS::RadiusPacket P(Buffer,NumberOfReceivedBytes); + auto NumberOfReceivedBytes = Socket_->receiveBytes(Buffer, sizeof(Buffer)); + if (NumberOfReceivedBytes >= 20) { + RADIUS::RadiusPacket P(Buffer, NumberOfReceivedBytes); if (P.IsAuthentication()) { auto SerialNumber = P.ExtractSerialNumberFromProxyState(); - if(!SerialNumber.empty()) { + if (!SerialNumber.empty()) { poco_debug(Logger_, fmt::format("{}: {} Received {} bytes.", SerialNumber, P.PacketType(), NumberOfReceivedBytes)); @@ -118,7 +115,7 @@ namespace OpenWifi { } } else if (P.IsAccounting()) { auto SerialNumber = P.ExtractSerialNumberFromProxyState(); - if(!SerialNumber.empty()) { + if (!SerialNumber.empty()) { poco_debug(Logger_, fmt::format("{}: {} Received {} bytes.", SerialNumber, P.PacketType(), NumberOfReceivedBytes)); @@ -129,20 +126,22 @@ namespace OpenWifi { } } else if (P.IsAuthority()) { auto SerialNumber = P.ExtractSerialNumberTIP(); - if(!SerialNumber.empty()) { + if (!SerialNumber.empty()) { poco_debug(Logger_, fmt::format("{}: {} Received {} bytes.", SerialNumber, P.PacketType(), NumberOfReceivedBytes)); AP_WS_Server()->SendRadiusCoAData(SerialNumber, Buffer, - NumberOfReceivedBytes); + NumberOfReceivedBytes); } else { poco_debug(Logger_, "CoA/DM packet dropped."); } } else { - poco_warning(Logger_,fmt::format("Unknown packet: Type: {} (type={}) Length={}", P.PacketType(), P.PacketTypeInt(), P.BufferLen())); + poco_warning(Logger_, + fmt::format("Unknown packet: Type: {} (type={}) Length={}", + P.PacketType(), P.PacketTypeInt(), P.BufferLen())); } } else { - poco_warning(Logger_,"Invalid packet received. Resetting the connection."); + poco_warning(Logger_, "Invalid packet received. Resetting the connection."); Disconnect(); } } catch (const Poco::Exception &E) { @@ -150,47 +149,49 @@ namespace OpenWifi { Disconnect(); } catch (...) { Disconnect(); - poco_warning(Logger_,"Exception occurred. Resetting the connection."); + poco_warning(Logger_, "Exception occurred. Resetting the connection."); } } - inline void onError([[maybe_unused]] const Poco::AutoPtr& pNf) { - poco_warning(Logger_,"Socker error. Terminating connection."); + inline void + onError([[maybe_unused]] const Poco::AutoPtr &pNf) { + poco_warning(Logger_, "Socker error. Terminating connection."); Disconnect(); } - inline void onShutdown([[maybe_unused]] const Poco::AutoPtr& pNf) { - poco_warning(Logger_,"Socker socket shutdown. Terminating connection."); + inline void + onShutdown([[maybe_unused]] const Poco::AutoPtr &pNf) { + poco_warning(Logger_, "Socker socket shutdown. Terminating connection."); Disconnect(); } inline bool Connect() { - if(TryAgain_) { + if (TryAgain_) { std::lock_guard G(LocalMutex_); - Poco::TemporaryFile CertFile_(MicroServiceDataDirectory()); - Poco::TemporaryFile KeyFile_(MicroServiceDataDirectory()); + Poco::TemporaryFile CertFile_(MicroServiceDataDirectory()); + Poco::TemporaryFile KeyFile_(MicroServiceDataDirectory()); std::vector> CaCertFiles_; DecodeFile(CertFile_.path(), Server_.radsecCert); DecodeFile(KeyFile_.path(), Server_.radsecKey); - for(auto &cert:Server_.radsecCacerts) { - CaCertFiles_.emplace_back(std::make_unique(MicroServiceDataDirectory())); - DecodeFile(CaCertFiles_[CaCertFiles_.size()-1]->path(), cert); + for (auto &cert : Server_.radsecCacerts) { + CaCertFiles_.emplace_back( + std::make_unique(MicroServiceDataDirectory())); + DecodeFile(CaCertFiles_[CaCertFiles_.size() - 1]->path(), cert); } - Poco::Net::Context::Ptr SecureContext = Poco::AutoPtr( - new Poco::Net::Context(Poco::Net::Context::TLS_CLIENT_USE, - KeyFile_.path(), - CertFile_.path(),"")); - if(Server_.allowSelfSigned) { + Poco::Net::Context::Ptr SecureContext = + Poco::AutoPtr(new Poco::Net::Context( + Poco::Net::Context::TLS_CLIENT_USE, KeyFile_.path(), CertFile_.path(), "")); + if (Server_.allowSelfSigned) { SecureContext->setSecurityLevel(Poco::Net::Context::SECURITY_LEVEL_NONE); SecureContext->enableExtendedCertificateVerification(false); } - for(const auto &ca:CaCertFiles_) { - Poco::Crypto::X509Certificate cert(ca->path()); + for (const auto &ca : CaCertFiles_) { + Poco::Crypto::X509Certificate cert(ca->path()); SecureContext->addCertificateAuthority(cert); } @@ -203,49 +204,48 @@ namespace OpenWifi { Socket_->connect(Destination, Poco::Timespan(100, 0)); Socket_->completeHandshake(); - if(!Server_.allowSelfSigned) { + if (!Server_.allowSelfSigned) { Socket_->verifyPeerCertificate(); } - if(Socket_->havePeerCertificate()) { - Peer_Cert_ = std::make_unique(Socket_->peerCertificate()); + if (Socket_->havePeerCertificate()) { + Peer_Cert_ = std::make_unique( + Socket_->peerCertificate()); } Socket_->setBlocking(false); Socket_->setNoDelay(true); Socket_->setKeepAlive(true); - Socket_->setReceiveTimeout(Poco::Timespan(1 * 60 * 60,0)); + Socket_->setReceiveTimeout(Poco::Timespan(1 * 60 * 60, 0)); Reactor_.addEventHandler( - *Socket_, - Poco::NObserver( - *this, &RADSEC_server::onData)); + *Socket_, Poco::NObserver( + *this, &RADSEC_server::onData)); Reactor_.addEventHandler( *Socket_, Poco::NObserver( - *this, &RADSEC_server::onError)); + *this, &RADSEC_server::onError)); Reactor_.addEventHandler( - *Socket_, - Poco::NObserver( - *this, &RADSEC_server::onShutdown)); + *Socket_, Poco::NObserver( + *this, &RADSEC_server::onShutdown)); Connected_ = true; - poco_information(Logger_,fmt::format("Connected. CN={}",CommonName())); + poco_information(Logger_, fmt::format("Connected. CN={}", CommonName())); return true; } catch (const Poco::Net::NetException &E) { - poco_information(Logger_,"Could not connect."); + poco_information(Logger_, "Could not connect."); Logger_.log(E); } catch (const Poco::Exception &E) { - poco_information(Logger_,"Could not connect."); + poco_information(Logger_, "Could not connect."); Logger_.log(E); } catch (...) { - poco_information(Logger_,"Could not connect."); + poco_information(Logger_, "Could not connect."); } } return false; } inline void Disconnect() { - if(Connected_) { + if (Connected_) { std::lock_guard G(LocalMutex_); Reactor_.removeEventHandler( @@ -260,44 +260,45 @@ namespace OpenWifi { Socket_->close(); Connected_ = false; } - poco_information(Logger_,"Disconnecting."); + poco_information(Logger_, "Disconnecting."); } static void DecodeFile(const std::string &filename, const std::string &s) { - std::ofstream sec_file(filename,std::ios_base::out|std::ios_base::trunc|std::ios_base::binary); + std::ofstream sec_file(filename, std::ios_base::out | std::ios_base::trunc | + std::ios_base::binary); std::stringstream is(s); - Poco::Base64Decoder ds(is); - Poco::StreamCopier::copyStream(ds,sec_file); + Poco::Base64Decoder ds(is); + Poco::StreamCopier::copyStream(ds, sec_file); sec_file.close(); } [[nodiscard]] inline std::string CommonName() { - if(Peer_Cert_) + if (Peer_Cert_) return Peer_Cert_->commonName(); return ""; } [[nodiscard]] inline std::string IssuerName() { - if(Peer_Cert_) + if (Peer_Cert_) return Peer_Cert_->issuerName(); return ""; } [[nodiscard]] inline std::string SubjectName() { - if(Peer_Cert_) + if (Peer_Cert_) return Peer_Cert_->subjectName(); return ""; } private: - std::recursive_mutex LocalMutex_; - Poco::Net::SocketReactor &Reactor_; - GWObjects::RadiusProxyServerEntry Server_; - Poco::Logger &Logger_; - std::unique_ptr Socket_; - Poco::Thread ReconnectThread_; - std::unique_ptr Peer_Cert_; - volatile bool Connected_=false; - volatile bool TryAgain_=true; + std::recursive_mutex LocalMutex_; + Poco::Net::SocketReactor &Reactor_; + GWObjects::RadiusProxyServerEntry Server_; + Poco::Logger &Logger_; + std::unique_ptr Socket_; + Poco::Thread ReconnectThread_; + std::unique_ptr Peer_Cert_; + volatile bool Connected_ = false; + volatile bool TryAgain_ = true; }; -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/SDKcalls.cpp b/src/SDKcalls.cpp index 5ce471f3..b2aae9ba 100644 --- a/src/SDKcalls.cpp +++ b/src/SDKcalls.cpp @@ -4,26 +4,26 @@ #include "SDKcalls.h" -#include "framework/OpenAPIRequests.h" #include "framework/MicroServiceNames.h" +#include "framework/OpenAPIRequests.h" namespace OpenWifi { - bool SDKCalls::GetProvisioningConfiguration(const std::string &SerialNumber, std::string & Config) { + bool SDKCalls::GetProvisioningConfiguration(const std::string &SerialNumber, + std::string &Config) { - Types::StringPairVec QD { {"config","true"}}; - OpenAPIRequestGet API(uSERVICE_PROVISIONING, - "/api/v1/inventory/" + SerialNumber, - QD,20000); + Types::StringPairVec QD{{"config", "true"}}; + OpenAPIRequestGet API(uSERVICE_PROVISIONING, "/api/v1/inventory/" + SerialNumber, QD, + 20000); Poco::JSON::Object::Ptr ResponseObject; - if(API.Do(ResponseObject)==Poco::Net::HTTPResponse::HTTP_OK) { - if(ResponseObject->has("config")) { + if (API.Do(ResponseObject) == Poco::Net::HTTPResponse::HTTP_OK) { + if (ResponseObject->has("config")) { Config = ResponseObject->get("config").toString(); return true; } } return false; } -} +} // namespace OpenWifi diff --git a/src/SDKcalls.h b/src/SDKcalls.h index 295f7b92..1343750c 100644 --- a/src/SDKcalls.h +++ b/src/SDKcalls.h @@ -9,8 +9,9 @@ namespace OpenWifi { class SDKCalls { public: - static bool GetProvisioningConfiguration(const std::string & SerialNumber, std::string & Config); + static bool GetProvisioningConfiguration(const std::string &SerialNumber, + std::string &Config); + private: }; -} - +} // namespace OpenWifi diff --git a/src/ScriptManager.cpp b/src/ScriptManager.cpp index 86b4f2a1..0e932626 100644 --- a/src/ScriptManager.cpp +++ b/src/ScriptManager.cpp @@ -3,21 +3,22 @@ // #include "ScriptManager.h" +#include "Poco/JSON/Parser.h" #include "framework/MicroServiceFuncs.h" #include -#include "Poco/JSON/Parser.h" namespace OpenWifi { int ScriptManager::Start() { - poco_notice(Logger(),"Starting..."); - ScriptDir_ = MicroServiceConfigPath("script.manager.directory", MicroServiceDataDirectory() + "/included_scripts" ); + poco_notice(Logger(), "Starting..."); + ScriptDir_ = MicroServiceConfigPath("script.manager.directory", + MicroServiceDataDirectory() + "/included_scripts"); return 0; } void ScriptManager::Stop() { - poco_notice(Logger(),"Stopping..."); - poco_notice(Logger(),"Stopped..."); + poco_notice(Logger(), "Stopping..."); + poco_notice(Logger(), "Stopped..."); } } // namespace OpenWifi \ No newline at end of file diff --git a/src/ScriptManager.h b/src/ScriptManager.h index d6b256b6..6f08a1a9 100644 --- a/src/ScriptManager.h +++ b/src/ScriptManager.h @@ -19,16 +19,12 @@ namespace OpenWifi { void Stop(); private: - std::string ScriptDir_; - - explicit ScriptManager() noexcept: - SubSystemServer("ScriptManager", "SCRIPT-MGR", "script.manager") - { - } + std::string ScriptDir_; + explicit ScriptManager() noexcept + : SubSystemServer("ScriptManager", "SCRIPT-MGR", "script.manager") {} }; inline auto ScriptManager() { return ScriptManager::instance(); } } // namespace OpenWifi - diff --git a/src/SerialNumberCache.cpp b/src/SerialNumberCache.cpp index 9cf75e83..9905cb3f 100644 --- a/src/SerialNumberCache.cpp +++ b/src/SerialNumberCache.cpp @@ -11,23 +11,23 @@ namespace OpenWifi { int SerialNumberCache::Start() { - poco_notice(Logger(),"Starting..."); + poco_notice(Logger(), "Starting..."); StorageService()->UpdateSerialNumberCache(); return 0; } void SerialNumberCache::Stop() { - poco_notice(Logger(),"Stopping..."); + poco_notice(Logger(), "Stopping..."); SNs_.clear(); Reverse_SNs_.clear(); - poco_notice(Logger(),"Stopped..."); + poco_notice(Logger(), "Stopped..."); } void SerialNumberCache::AddSerialNumber(const std::string &S) { - std::lock_guard G(Mutex_); + std::lock_guard G(Mutex_); uint64_t SN = std::stoull(S, nullptr, 16); - if(std::find(std::begin(SNs_),std::end(SNs_),SN) == std::end(SNs_)) { + if (std::find(std::begin(SNs_), std::end(SNs_), SN) == std::end(SNs_)) { auto insert_point = std::lower_bound(SNs_.begin(), SNs_.end(), SN); SNs_.insert(insert_point, SN); @@ -39,17 +39,17 @@ namespace OpenWifi { } void SerialNumberCache::DeleteSerialNumber(const std::string &S) { - std::lock_guard G(Mutex_); + std::lock_guard G(Mutex_); - uint64_t SN = std::stoull(S,nullptr,16); - auto It = std::find(SNs_.begin(),SNs_.end(),SN); - if(It != SNs_.end()) { + uint64_t SN = std::stoull(S, nullptr, 16); + auto It = std::find(SNs_.begin(), SNs_.end(), SN); + if (It != SNs_.end()) { SNs_.erase(It); auto R = ReverseSerialNumber(S); uint64_t RSN = std::stoull(R, nullptr, 16); - auto RIt = std::find(Reverse_SNs_.begin(),Reverse_SNs_.end(),RSN); - if(RIt != Reverse_SNs_.end()) { + auto RIt = std::find(Reverse_SNs_.begin(), Reverse_SNs_.end(), RSN); + if (RIt != Reverse_SNs_.end()) { Reverse_SNs_.erase(RIt); } } @@ -60,13 +60,15 @@ namespace OpenWifi { for (int i = 0; i < 16; i++) { Res = (Res << 4) + (N & 0x000000000000000f); - N >>= 4; + N >>= 4; } Res >>= 16; return Res; } - void SerialNumberCache::ReturnNumbers(const std::string &S, uint HowMany, const std::vector &SNArr, std::vector &A, bool ReverseResult) { + void SerialNumberCache::ReturnNumbers(const std::string &S, uint HowMany, + const std::vector &SNArr, + std::vector &A, bool ReverseResult) { std::lock_guard G(Mutex_); if (S.length() == 12) { @@ -82,9 +84,10 @@ namespace OpenWifi { auto LB = std::lower_bound(SNArr.begin(), SNArr.end(), SN); if (LB != SNArr.end()) { for (; LB != SNArr.end() && HowMany; ++LB, --HowMany) { - if(ReverseResult) { - const auto TSN = ReverseSerialNumber(Utils::IntToSerialNumber(Reverse(*LB))); - if (S == TSN.substr(0,S.size())) { + if (ReverseResult) { + const auto TSN = + ReverseSerialNumber(Utils::IntToSerialNumber(Reverse(*LB))); + if (S == TSN.substr(0, S.size())) { A.emplace_back(Reverse(*LB)); } else { break; @@ -102,18 +105,19 @@ namespace OpenWifi { } } - void SerialNumberCache::FindNumbers(const std::string &S, uint HowMany, std::vector &A) { - if(S.empty()) + void SerialNumberCache::FindNumbers(const std::string &S, uint HowMany, + std::vector &A) { + if (S.empty()) return; if (S[0] == '*') { std::string Reversed; - std::copy(rbegin(S), rend(S)-1, std::back_inserter(Reversed)); - if(Reversed.empty()) + std::copy(rbegin(S), rend(S) - 1, std::back_inserter(Reversed)); + if (Reversed.empty()) return; return ReturnNumbers(Reversed, HowMany, Reverse_SNs_, A, true); } else { return ReturnNumbers(S, HowMany, SNs_, A, false); } } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/SerialNumberCache.h b/src/SerialNumberCache.h index b6c6f95b..5c4acd5f 100644 --- a/src/SerialNumberCache.h +++ b/src/SerialNumberCache.h @@ -8,10 +8,9 @@ namespace OpenWifi { class SerialNumberCache : public SubSystemServer { - public: - + public: static auto instance() { - static auto instance_ = new SerialNumberCache; + static auto instance_ = new SerialNumberCache; return instance_; } @@ -21,29 +20,29 @@ namespace OpenWifi { void DeleteSerialNumber(const std::string &SerialNumber); void FindNumbers(const std::string &SerialNumber, uint HowMany, std::vector &A); inline bool NumberExists(uint64_t SerialNumber) { - std::lock_guard G(Mutex_); - return std::find(SNs_.begin(),SNs_.end(),SerialNumber)!=SNs_.end(); + std::lock_guard G(Mutex_); + return std::find(SNs_.begin(), SNs_.end(), SerialNumber) != SNs_.end(); } static inline std::string ReverseSerialNumber(const std::string &S) { std::string ReversedString; - std::copy(rbegin(S),rend(S),std::back_inserter(ReversedString)); + std::copy(rbegin(S), rend(S), std::back_inserter(ReversedString)); return ReversedString; } private: - std::vector SNs_; - std::vector Reverse_SNs_; + std::vector SNs_; + std::vector Reverse_SNs_; - void ReturnNumbers(const std::string &S, uint HowMany, const std::vector & SNArr, std::vector &A, bool ReverseResult); + void ReturnNumbers(const std::string &S, uint HowMany, const std::vector &SNArr, + std::vector &A, bool ReverseResult); - SerialNumberCache() noexcept: - SubSystemServer("SerialNumberCache", "SNCACHE-SVR", "serialcache") - { - SNs_.reserve(2000); - } + SerialNumberCache() noexcept + : SubSystemServer("SerialNumberCache", "SNCACHE-SVR", "serialcache") { + SNs_.reserve(2000); + } }; inline auto SerialNumberCache() { return SerialNumberCache::instance(); } -} // namespace OpenWiFi +} // namespace OpenWifi diff --git a/src/SignatureMgr.cpp b/src/SignatureMgr.cpp deleted file mode 100644 index 32667201..00000000 --- a/src/SignatureMgr.cpp +++ /dev/null @@ -1,7 +0,0 @@ -// -// Created by stephane bourque on 2022-11-22. -// - -#include "SignatureMgr.h" - -namespace OpenWifi {} // namespace OpenWifi \ No newline at end of file diff --git a/src/SignatureMgr.h b/src/SignatureMgr.h index ee6e859a..8fa592a6 100644 --- a/src/SignatureMgr.h +++ b/src/SignatureMgr.h @@ -7,18 +7,18 @@ #include #include -#include "framework/SubSystemServer.h" #include "framework/MicroServiceFuncs.h" +#include "framework/SubSystemServer.h" #include "framework/utils.h" -#include "RESTObjects/RESTAPI_GWobjects.h" -#include "Poco/DigestStream.h" -#include "Poco/DigestEngine.h" #include "Poco/Crypto/RSADigestEngine.h" -#include "Poco/StreamCopier.h" +#include "Poco/DigestEngine.h" +#include "Poco/DigestStream.h" #include "Poco/File.h" +#include "Poco/StreamCopier.h" #include "Poco/StringTokenizer.h" #include "Poco/TemporaryFile.h" +#include "RESTObjects/RESTAPI_GWobjects.h" #include "fmt/format.h" namespace OpenWifi { @@ -31,61 +31,66 @@ namespace OpenWifi { } struct SignatureCacheEntry { - std::string vendor_uri_hash; - std::string signature; + std::string vendor_uri_hash; + std::string signature; }; inline int Start() final { - poco_notice(Logger(),"Starting..."); + poco_notice(Logger(), "Starting..."); std::shared_lock L(KeyMutex_); CacheFilename_ = MicroServiceDataDirectory() + "/signature_cache"; - Poco::File CacheFile(CacheFilename_); + Poco::File CacheFile(CacheFilename_); - if(CacheFile.exists()) { - std::fstream CacheFileContent(CacheFilename_, std::ios_base::in); - std::string line; - while(std::getline(CacheFileContent, line)) { - auto Tokens = Poco::StringTokenizer(line,":"); - if(Tokens.count()==2) { + if (CacheFile.exists()) { + std::fstream CacheFileContent(CacheFilename_, std::ios_base::in); + std::string line; + while (std::getline(CacheFileContent, line)) { + auto Tokens = Poco::StringTokenizer(line, ":"); + if (Tokens.count() == 2) { SignatureCache_[Tokens[0]] = Tokens[1]; } } } - poco_information(Logger(),fmt::format("Found {} entries in signature cache.", SignatureCache_.size())); + poco_information(Logger(), fmt::format("Found {} entries in signature cache.", + SignatureCache_.size())); // read all the key vendors. // signature.manager.0.key.public // signature.manager.0.key.private // signature.manager.0.vendor - int i=0; - while(true) { - auto Vendor = MicroServiceConfigGetString("signature.manager." + std::to_string(i) + ".vendor",""); - auto PrivateKey = MicroServiceConfigPath("signature.manager." + std::to_string(i) + ".key.private",""); - auto PublicKey = MicroServiceConfigPath("signature.manager." + std::to_string(i) + ".key.public",""); - if(Vendor.empty() || PrivateKey.empty() || PublicKey.empty()) { + int i = 0; + while (true) { + auto Vendor = MicroServiceConfigGetString( + "signature.manager." + std::to_string(i) + ".vendor", ""); + auto PrivateKey = MicroServiceConfigPath( + "signature.manager." + std::to_string(i) + ".key.private", ""); + auto PublicKey = MicroServiceConfigPath( + "signature.manager." + std::to_string(i) + ".key.public", ""); + if (Vendor.empty() || PrivateKey.empty() || PublicKey.empty()) { break; } - Poco::File PubKey(PublicKey), PrivKey(PrivateKey); - if(PubKey.exists() && PrivKey.exists()) { + Poco::File PubKey(PublicKey), PrivKey(PrivateKey); + if (PubKey.exists() && PrivKey.exists()) { Keys_[Vendor] = Poco::SharedPtr( new Poco::Crypto::RSAKey(PublicKey, PrivateKey, "")); } ++i; } - poco_information(Logger(),fmt::format("{} signatures in dictionary.", Keys_.size())); + poco_information(Logger(), fmt::format("{} signatures in dictionary.", Keys_.size())); return 0; } inline void Stop() final { - poco_notice(Logger(),"Stopping..."); - poco_notice(Logger(),"Stopped..."); + poco_notice(Logger(), "Stopping..."); + poco_notice(Logger(), "Stopped..."); } - inline std::string Sign(const GWObjects::DeviceRestrictions &Restrictions, const std::string &Data) const { + inline std::string Sign(const GWObjects::DeviceRestrictions &Restrictions, + const std::string &Data) const { std::shared_lock L(KeyMutex_); try { if (Restrictions.key_info.algo == "static") { @@ -93,7 +98,8 @@ namespace OpenWifi { } auto Vendor = Keys_.find(Restrictions.key_info.vendor); if (Vendor == Keys_.end()) { - poco_error( Logger(), fmt::format("{}: vendor unknown.", Restrictions.key_info.vendor)); + poco_error(Logger(), + fmt::format("{}: vendor unknown.", Restrictions.key_info.vendor)); return ""; } @@ -112,7 +118,8 @@ namespace OpenWifi { return ""; } - inline std::string Sign(const GWObjects::DeviceRestrictions &Restrictions, const Poco::URI &uri) { + inline std::string Sign(const GWObjects::DeviceRestrictions &Restrictions, + const Poco::URI &uri) { std::shared_lock L(KeyMutex_); try { if (Restrictions.key_info.algo == "static") { @@ -121,13 +128,15 @@ namespace OpenWifi { auto Vendor = Keys_.find(Restrictions.key_info.vendor); if (Vendor == Keys_.end()) { - poco_error( Logger(), fmt::format("{}: vendor unknown.", Restrictions.key_info.vendor)); + poco_error(Logger(), + fmt::format("{}: vendor unknown.", Restrictions.key_info.vendor)); return ""; } if (Restrictions.key_info.algo == "dgst-sha256") { auto FileHash = - Utils::ComputeHash(Restrictions.key_info.vendor, Restrictions.key_info.algo, uri.getPathAndQuery()); + Utils::ComputeHash(Restrictions.key_info.vendor, Restrictions.key_info.algo, + uri.getPathAndQuery()); auto CacheEntry = SignatureCache_.find(FileHash); if (CacheEntry != end(SignatureCache_)) { return CacheEntry->second; @@ -141,7 +150,8 @@ namespace OpenWifi { std::ios_base::in | std::ios_base::binary); Poco::StreamCopier::copyStream(ifs, ofs); ofs.flush(); - auto Signature = Utils::base64encode((const unsigned char *)R.signature().data(),R.signature().size()); + auto Signature = Utils::base64encode( + (const unsigned char *)R.signature().data(), R.signature().size()); SignatureCache_[FileHash] = Signature; SaveCache(); return Signature; @@ -154,9 +164,9 @@ namespace OpenWifi { } void SaveCache() { - std::ofstream ofs(CacheFilename_, std::ios_base::trunc | std::ios_base::out); + std::ofstream ofs(CacheFilename_, std::ios_base::trunc | std::ios_base::out); - for(const auto &[hash,signature]:SignatureCache_) { + for (const auto &[hash, signature] : SignatureCache_) { ofs << hash << ":" << signature << std::endl; } } @@ -164,13 +174,12 @@ namespace OpenWifi { private: mutable std::shared_mutex KeyMutex_; std::map> Keys_; - std::map SignatureCache_; - std::string CacheFilename_; + std::map SignatureCache_; + std::string CacheFilename_; explicit SignatureManager() noexcept : SubSystemServer("SignatureManager", "SIGNATURE-MGR", "signature.manager") {} }; inline auto SignatureManager() { return SignatureManager::instance(); } -} - +} // namespace OpenWifi diff --git a/src/StateUtils.cpp b/src/StateUtils.cpp index 5388fd71..5ab11170 100644 --- a/src/StateUtils.cpp +++ b/src/StateUtils.cpp @@ -8,60 +8,62 @@ namespace OpenWifi::StateUtils { static int ChannelToBand(uint64_t C) { - if(C>=1 && C<=16) return 2; + if (C >= 1 && C <= 16) + return 2; return 5; } static int BandToInt(const std::string &band) { - if(band=="2G") return 2; - if(band=="5G") return 5; - if(band=="6G") return 6; + if (band == "2G") + return 2; + if (band == "5G") + return 5; + if (band == "6G") + return 6; return 2; } - bool ComputeAssociations(const Poco::JSON::Object::Ptr RawObject, - uint64_t &Radios_2G, + bool ComputeAssociations(const Poco::JSON::Object::Ptr RawObject, uint64_t &Radios_2G, uint64_t &Radios_5G, uint64_t &Radios_6G) { - Radios_2G = 0 ; + Radios_2G = 0; Radios_5G = 0; Radios_6G = 0; - if(RawObject->isArray("radios") && RawObject->isArray("interfaces")) { + if (RawObject->isArray("radios") && RawObject->isArray("interfaces")) { auto RA = RawObject->getArray("radios"); // map of phy to 2g/5g - std::map RadioPHYs; + std::map RadioPHYs; // parse radios and get the phy out with the band bool UseBandInfo = false; - for(auto const &i:*RA) { -// Poco::JSON::Parser p2; + for (auto const &i : *RA) { + // Poco::JSON::Parser p2; auto RadioObj = i.extract(); - if(RadioObj->has("band")) { + if (RadioObj->has("band")) { // std::cout << "Use band info" << std::endl; - UseBandInfo = true ; - } else if(RadioObj->has("phy") && RadioObj->has("channel")) { - if(RadioObj->isArray("channel")) { + UseBandInfo = true; + } else if (RadioObj->has("phy") && RadioObj->has("channel")) { + if (RadioObj->isArray("channel")) { auto ChannelArray = RadioObj->getArray("channel"); - if(ChannelArray->size()) { + if (ChannelArray->size()) { RadioPHYs[RadioObj->get("phy")] = - ChannelToBand( ChannelArray->getElement(0) ); + ChannelToBand(ChannelArray->getElement(0)); } } else { - RadioPHYs[RadioObj->get("phy")] = - ChannelToBand(RadioObj->get("channel")); + RadioPHYs[RadioObj->get("phy")] = ChannelToBand(RadioObj->get("channel")); } } } auto InterfaceArray = RawObject->getArray("interfaces"); - for(auto const &interface:*InterfaceArray) { + for (auto const &interface : *InterfaceArray) { auto InterfaceObj = interface.extract(); - if(InterfaceObj->isArray("ssids")) { + if (InterfaceObj->isArray("ssids")) { auto SSIDArray = InterfaceObj->getArray("ssids"); - for(const auto &ssid:*SSIDArray) { + for (const auto &ssid : *SSIDArray) { auto SSID_info = ssid.extract(); - if(SSID_info->isArray("associations") && SSID_info->has("phy")) { + if (SSID_info->isArray("associations") && SSID_info->has("phy")) { int Radio = 2; - if(UseBandInfo) { + if (UseBandInfo) { Radio = BandToInt(SSID_info->get("band")); } else { auto PHY = SSID_info->get("phy"); @@ -70,19 +72,27 @@ namespace OpenWifi::StateUtils { Radio = Rit->second; } auto AssocA = SSID_info->getArray("associations"); - switch(Radio) { - case 2: Radios_2G += AssocA->size(); break; - case 5: Radios_5G += AssocA->size(); break; - case 6: Radios_6G += AssocA->size(); break; - default: Radios_2G += AssocA->size(); break; + switch (Radio) { + case 2: + Radios_2G += AssocA->size(); + break; + case 5: + Radios_5G += AssocA->size(); + break; + case 6: + Radios_6G += AssocA->size(); + break; + default: + Radios_2G += AssocA->size(); + break; } } } } } -// std::cout << Radios_2G << " " << Radios_5G << " " << Radios_6G << std::endl; + // std::cout << Radios_2G << " " << Radios_5G << " " << Radios_6G << std::endl; return true; } return false; } -} \ No newline at end of file +} // namespace OpenWifi::StateUtils \ No newline at end of file diff --git a/src/StateUtils.h b/src/StateUtils.h index 590e6594..ec2ec4ed 100644 --- a/src/StateUtils.h +++ b/src/StateUtils.h @@ -8,5 +8,5 @@ namespace OpenWifi::StateUtils { bool ComputeAssociations(const Poco::JSON::Object::Ptr RawObject, uint64_t &Radios_2G, - uint64_t &Radios_5G, uint64_t &Radio_6G); + uint64_t &Radios_5G, uint64_t &Radio_6G); } \ No newline at end of file diff --git a/src/StorageArchiver.cpp b/src/StorageArchiver.cpp index 5bc15c05..095b34f7 100644 --- a/src/StorageArchiver.cpp +++ b/src/StorageArchiver.cpp @@ -8,42 +8,37 @@ #include "StorageService.h" #include "framework/AppServiceRegistry.h" -#include "framework/utils.h" #include "framework/MicroServiceFuncs.h" +#include "framework/utils.h" #include "fmt/format.h" namespace OpenWifi { - void Archiver::onTimer([[maybe_unused]] Poco::Timer &timer){ + void Archiver::onTimer([[maybe_unused]] Poco::Timer &timer) { Utils::SetThreadName("strg-archiver"); auto now = Utils::Now(); - for(const auto &[DBName, Keep]:DBs_) { + for (const auto &[DBName, Keep] : DBs_) { if (!Poco::icompare(DBName, "healthchecks")) { - poco_information(Logger(),"Archiving HealthChecks..."); - StorageService()->RemoveHealthChecksRecordsOlderThan( - now - (Keep * 24 * 60 * 60)); + poco_information(Logger(), "Archiving HealthChecks..."); + StorageService()->RemoveHealthChecksRecordsOlderThan(now - (Keep * 24 * 60 * 60)); } else if (!Poco::icompare(DBName, "statistics")) { - poco_information(Logger(),"Archiving Statistics..."); - StorageService()->RemoveStatisticsRecordsOlderThan( - now - (Keep * 24 * 60 * 60)); + poco_information(Logger(), "Archiving Statistics..."); + StorageService()->RemoveStatisticsRecordsOlderThan(now - (Keep * 24 * 60 * 60)); } else if (!Poco::icompare(DBName, "devicelogs")) { - poco_information(Logger(),"Archiving Device Logs..."); - StorageService()->RemoveDeviceLogsRecordsOlderThan( - now - (Keep * 24 * 60 * 60)); + poco_information(Logger(), "Archiving Device Logs..."); + StorageService()->RemoveDeviceLogsRecordsOlderThan(now - (Keep * 24 * 60 * 60)); } else if (!Poco::icompare(DBName, "commandlist")) { - poco_information(Logger(),"Archiving Command History..."); - StorageService()->RemoveCommandListRecordsOlderThan( - now - (Keep * 24 * 60 * 60)); + poco_information(Logger(), "Archiving Command History..."); + StorageService()->RemoveCommandListRecordsOlderThan(now - (Keep * 24 * 60 * 60)); } else if (!Poco::icompare(DBName, "fileuploads")) { - poco_information(Logger(),"Archiving Upload files..."); - StorageService()->RemoveUploadedFilesRecordsOlderThan( - now - (Keep * 24 * 60 * 60)); + poco_information(Logger(), "Archiving Upload files..."); + StorageService()->RemoveUploadedFilesRecordsOlderThan(now - (Keep * 24 * 60 * 60)); } else { - poco_information(Logger(),fmt::format("Cannot archive DB '{}'", DBName)); + poco_information(Logger(), fmt::format("Cannot archive DB '{}'", DBName)); } } - AppServiceRegistry().Set("lastStorageArchiverRun", (uint64_t) now); + AppServiceRegistry().Set("lastStorageArchiverRun", (uint64_t)now); } static auto CalculateDelta(std::uint64_t H, std::uint64_t M) { @@ -51,56 +46,58 @@ namespace OpenWifi { Poco::LocalDateTime scheduled(dt.year(), dt.month(), dt.day(), (int)H, (int)M, 0); std::uint64_t delta = 0; - if ((dt.hour() < (int)H) || (dt.hour()==(int)H && dt.minute()<(int)M)) { + if ((dt.hour() < (int)H) || (dt.hour() == (int)H && dt.minute() < (int)M)) { delta = scheduled.timestamp().epochTime() - dt.timestamp().epochTime(); } else { - delta = (24*60*60) - (dt.timestamp().epochTime() - scheduled.timestamp().epochTime()); + delta = + (24 * 60 * 60) - (dt.timestamp().epochTime() - scheduled.timestamp().epochTime()); } return delta; } int StorageArchiver::Start() { - Enabled_ = MicroServiceConfigGetBool("archiver.enabled",false); - if(!Enabled_) { - poco_information(Logger(),"Archiver is disabled."); + Enabled_ = MicroServiceConfigGetBool("archiver.enabled", false); + if (!Enabled_) { + poco_information(Logger(), "Archiver is disabled."); return 0; } Archiver_ = std::make_unique(Logger()); - ArchiverCallback_ = std::make_unique>(*Archiver_,&Archiver::onTimer); + ArchiverCallback_ = + std::make_unique>(*Archiver_, &Archiver::onTimer); - auto Schedule = MicroServiceConfigGetString("archiver.schedule","03:00"); - auto S = Poco::StringTokenizer(Schedule,":"); + auto Schedule = MicroServiceConfigGetString("archiver.schedule", "03:00"); + auto S = Poco::StringTokenizer(Schedule, ":"); std::uint64_t RunAtHour_, RunAtMin_; - if(S.count()!=2) { - RunAtHour_ = 3 ; + if (S.count() != 2) { + RunAtHour_ = 3; RunAtMin_ = 0; } else { RunAtHour_ = std::strtoull(S[0].c_str(), nullptr, 10); RunAtMin_ = std::strtoull(S[1].c_str(), nullptr, 10); } - for(int i=0;i<20;i++) { + for (int i = 0; i < 20; i++) { std::string key = "archiver.db." + std::to_string(i) + ".name"; - auto DBName = MicroServiceConfigGetString(key,""); - if(!DBName.empty()) { - for(auto const &DB:AllInternalDBNames) { - if(Poco::icompare(DBName,DB)==0) { + auto DBName = MicroServiceConfigGetString(key, ""); + if (!DBName.empty()) { + for (auto const &DB : AllInternalDBNames) { + if (Poco::icompare(DBName, DB) == 0) { std::string Key = "archiver.db." + std::to_string(i) + ".keep"; - auto Keep = MicroServiceConfigGetInt(Key,7); + auto Keep = MicroServiceConfigGetInt(Key, 7); Archiver_->AddDb(DB, Keep); } } } } - int NextRun = CalculateDelta(RunAtHour_,RunAtMin_); + int NextRun = CalculateDelta(RunAtHour_, RunAtMin_); - poco_information(Logger(),fmt::format("Next run in {} seconds.",NextRun)); + poco_information(Logger(), fmt::format("Next run in {} seconds.", NextRun)); - Timer_.setStartInterval( NextRun * 1000); + Timer_.setStartInterval(NextRun * 1000); Timer_.setPeriodicInterval(24 * 60 * 60 * 1000); // 1 hours Timer_.start(*ArchiverCallback_, MicroServiceTimerPool()); @@ -108,11 +105,11 @@ namespace OpenWifi { } void StorageArchiver::Stop() { - poco_information(Logger(),"Stopping..."); - if(Enabled_) { + poco_information(Logger(), "Stopping..."); + if (Enabled_) { Timer_.stop(); } - poco_information(Logger(),"Stopped..."); + poco_information(Logger(), "Stopped..."); } -}; +}; // namespace OpenWifi diff --git a/src/StorageArchiver.h b/src/StorageArchiver.h index b85ae344..e6c32018 100644 --- a/src/StorageArchiver.h +++ b/src/StorageArchiver.h @@ -13,52 +13,50 @@ namespace OpenWifi { - static const std::list AllInternalDBNames{"healthchecks", "statistics", "devicelogs" , "commandlist", "fileuploads"}; + static const std::list AllInternalDBNames{ + "healthchecks", "statistics", "devicelogs", "commandlist", "fileuploads"}; - class Archiver { - public: - - explicit Archiver(Poco::Logger &Logger): - Logger_(Logger) { - for(const auto &db:AllInternalDBNames) { - DBs_[db] = 7 ; + class Archiver { + public: + explicit Archiver(Poco::Logger &Logger) : Logger_(Logger) { + for (const auto &db : AllInternalDBNames) { + DBs_[db] = 7; } } - void onTimer(Poco::Timer & timer); - inline void AddDb(const std::string &dbname, std::uint64_t retain) { + void onTimer(Poco::Timer &timer); + inline void AddDb(const std::string &dbname, std::uint64_t retain) { DBs_[dbname] = retain; } - inline Poco::Logger & Logger() { return Logger_; } - private: - Poco::Logger &Logger_; - std::map DBs_; - }; + inline Poco::Logger &Logger() { return Logger_; } - class StorageArchiver : public SubSystemServer { + private: + Poco::Logger &Logger_; + std::map DBs_; + }; - public: - static auto instance() { - static auto instance_ = new StorageArchiver; - return instance_; - } + class StorageArchiver : public SubSystemServer { - int Start() override; - void Stop() override; - inline bool Enabled() const { return Enabled_; } + public: + static auto instance() { + static auto instance_ = new StorageArchiver; + return instance_; + } - private: - std::atomic_bool Enabled_ = false; - Poco::Timer Timer_; - std::unique_ptr Archiver_; - std::unique_ptr> ArchiverCallback_; + int Start() override; + void Stop() override; + inline bool Enabled() const { return Enabled_; } - StorageArchiver() noexcept: - SubSystemServer("StorageArchiver", "STORAGE-ARCHIVE", "archiver") - { - } - }; + private: + std::atomic_bool Enabled_ = false; + Poco::Timer Timer_; + std::unique_ptr Archiver_; + std::unique_ptr> ArchiverCallback_; - inline auto StorageArchiver() { return StorageArchiver::instance(); } + StorageArchiver() noexcept + : SubSystemServer("StorageArchiver", "STORAGE-ARCHIVE", "archiver") {} + }; -} // namespace + inline auto StorageArchiver() { return StorageArchiver::instance(); } + +} // namespace OpenWifi diff --git a/src/StorageService.cpp b/src/StorageService.cpp index 3425ad41..1bc1bd2d 100644 --- a/src/StorageService.cpp +++ b/src/StorageService.cpp @@ -10,25 +10,26 @@ namespace OpenWifi { - int Storage::Start() { - std::lock_guard Guard(Mutex_); + int Storage::Start() { + std::lock_guard Guard(Mutex_); StorageClass::Start(); Create_Tables(); - InitializeBlackListCache(); + InitializeBlackListCache(); - ScriptDB_ = std::make_unique("Scripts", "scr", dbType_,*Pool_, Logger()); + ScriptDB_ = + std::make_unique("Scripts", "scr", dbType_, *Pool_, Logger()); ScriptDB_->Create(); ScriptDB_->Initialize(); return 0; - } + } - void Storage::Stop() { - std::lock_guard Guard(Mutex_); - poco_notice(Logger(),"Stopping..."); + void Storage::Stop() { + std::lock_guard Guard(Mutex_); + poco_notice(Logger(), "Stopping..."); StorageClass::Stop(); - poco_notice(Logger(),"Stopped..."); - } -} -// namespace \ No newline at end of file + poco_notice(Logger(), "Stopped..."); + } +} // namespace OpenWifi + // namespace \ No newline at end of file diff --git a/src/StorageService.h b/src/StorageService.h index 03f59ee1..6a5f2f4a 100644 --- a/src/StorageService.h +++ b/src/StorageService.h @@ -8,63 +8,69 @@ #pragma once -#include "framework/StorageClass.h" -#include "RESTObjects//RESTAPI_GWobjects.h" -#include "Poco/Net/IPAddress.h" #include "CentralConfig.h" +#include "Poco/Net/IPAddress.h" +#include "RESTObjects//RESTAPI_GWobjects.h" +#include "framework/StorageClass.h" #include "storage/storage_scripts.h" namespace OpenWifi { - class Storage : public StorageClass { - - public: + class Storage : public StorageClass { + public: enum class CommandExecutionType { COMMAND_PENDING, COMMAND_EXECUTED, COMMAND_COMPLETED, COMMAND_TIMEDOUT, COMMAND_FAILED, - COMMAND_EXPIRED, + COMMAND_EXPIRED, COMMAND_EXECUTING }; - inline OpenWifi::ScriptDB & ScriptDB() { return *ScriptDB_; } + inline OpenWifi::ScriptDB &ScriptDB() { return *ScriptDB_; } inline std::string to_string(const CommandExecutionType &C) { - switch(C) { - case CommandExecutionType::COMMAND_PENDING: return "pending"; - case CommandExecutionType::COMMAND_EXECUTED: return "executed"; - case CommandExecutionType::COMMAND_COMPLETED: return "completed"; - case CommandExecutionType::COMMAND_TIMEDOUT: return "timedout"; - case CommandExecutionType::COMMAND_FAILED: return "failed"; - case CommandExecutionType::COMMAND_EXPIRED: return "expired"; - case CommandExecutionType::COMMAND_EXECUTING: - default: - return "executing"; + switch (C) { + case CommandExecutionType::COMMAND_PENDING: + return "pending"; + case CommandExecutionType::COMMAND_EXECUTED: + return "executed"; + case CommandExecutionType::COMMAND_COMPLETED: + return "completed"; + case CommandExecutionType::COMMAND_TIMEDOUT: + return "timedout"; + case CommandExecutionType::COMMAND_FAILED: + return "failed"; + case CommandExecutionType::COMMAND_EXPIRED: + return "expired"; + case CommandExecutionType::COMMAND_EXECUTING: + default: + return "executing"; } } [[nodiscard]] inline std::string ComputeRange(uint64_t From, uint64_t HowMany) { - if(dbType_==sqlite) { + if (dbType_ == sqlite) { return " LIMIT " + std::to_string(From) + ", " + std::to_string(HowMany) + " "; - } else if(dbType_==pgsql) { - return " LIMIT " + std::to_string(HowMany) + " OFFSET " + std::to_string(From) + " "; - } else if(dbType_==mysql) { - return " LIMIT " + std::to_string(HowMany) + " OFFSET " + std::to_string(From) + " "; + } else if (dbType_ == pgsql) { + return " LIMIT " + std::to_string(HowMany) + " OFFSET " + std::to_string(From) + + " "; + } else if (dbType_ == mysql) { + return " LIMIT " + std::to_string(HowMany) + " OFFSET " + std::to_string(From) + + " "; } return " LIMIT " + std::to_string(HowMany) + " OFFSET " + std::to_string(From) + " "; } - inline std::string ConvertParams(const std::string & S) const { + inline std::string ConvertParams(const std::string &S) const { std::string R; - R.reserve(S.size()*2+1); - if(dbType_==pgsql) { - auto Idx=1; - for(auto const & i:S) - { - if(i=='?') { + R.reserve(S.size() * 2 + 1); + if (dbType_ == pgsql) { + auto Idx = 1; + for (auto const &i : S) { + if (i == '?') { R += '$'; R.append(std::to_string(Idx++)); } else { @@ -77,104 +83,136 @@ namespace OpenWifi { return R; } - static auto instance() { + static auto instance() { static auto instance_ = new Storage; return instance_; - } + } // typedef std::map DeviceCapabilitiesCache; - bool AddLog(const GWObjects::DeviceLog & Log); - bool AddStatisticsData(const GWObjects::Statistics & Stats); - bool GetStatisticsData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, uint64_t Offset, uint64_t HowMany, + bool AddLog(const GWObjects::DeviceLog &Log); + bool AddStatisticsData(const GWObjects::Statistics &Stats); + bool GetStatisticsData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, + uint64_t Offset, uint64_t HowMany, std::vector &Stats); - bool GetNumberOfStatisticsDataRecords(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, std::uint64_t &Count); - bool DeleteStatisticsData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate ); - bool GetNewestStatisticsData(std::string &SerialNumber, uint64_t HowMany, std::vector &Stats); + bool GetNumberOfStatisticsDataRecords(std::string &SerialNumber, uint64_t FromDate, + uint64_t ToDate, std::uint64_t &Count); + bool DeleteStatisticsData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate); + bool GetNewestStatisticsData(std::string &SerialNumber, uint64_t HowMany, + std::vector &Stats); bool AddHealthCheckData(const GWObjects::HealthCheck &Check); - bool GetHealthCheckData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, uint64_t Offset, uint64_t HowMany, + bool GetHealthCheckData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, + uint64_t Offset, uint64_t HowMany, std::vector &Checks); - bool DeleteHealthCheckData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate ); + bool DeleteHealthCheckData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate); bool GetNewestHealthCheckData(std::string &SerialNumber, uint64_t HowMany, std::vector &Checks); - bool UpdateDeviceConfiguration(std::string &SerialNumber, std::string &Configuration, uint64_t & NewUUID ); + bool UpdateDeviceConfiguration(std::string &SerialNumber, std::string &Configuration, + uint64_t &NewUUID); bool CreateDevice(GWObjects::Device &); - bool CreateDefaultDevice(std::string &SerialNumber, const Config::Capabilities &Caps, std::string & Firmware, const Poco::Net::IPAddress & IPAddress); + bool CreateDefaultDevice(std::string &SerialNumber, const Config::Capabilities &Caps, + std::string &Firmware, const Poco::Net::IPAddress &IPAddress); bool GetDevice(std::string &SerialNumber, GWObjects::Device &); - bool GetDevices(uint64_t From, uint64_t HowMany, std::vector &Devices, const std::string & orderBy=""); -// bool GetDevices(uint64_t From, uint64_t HowMany, const std::string & Select, std::vector &Devices, const std::string & orderBy=""); + bool GetDevices(uint64_t From, uint64_t HowMany, std::vector &Devices, + const std::string &orderBy = ""); + // bool GetDevices(uint64_t From, uint64_t HowMany, const std::string & Select, + //std::vector &Devices, const std::string & orderBy=""); bool DeleteDevice(std::string &SerialNumber); bool UpdateDevice(GWObjects::Device &); - bool DeviceExists(std::string & SerialNumber); + bool DeviceExists(std::string &SerialNumber); bool SetConnectInfo(std::string &SerialNumber, std::string &Firmware); - bool GetDeviceCount(uint64_t & Count); - bool GetDeviceSerialNumbers(uint64_t From, uint64_t HowMany, std::vector & SerialNumbers, const std::string & orderBy=""); - bool GetDeviceFWUpdatePolicy(std::string & SerialNumber, std::string & Policy); - bool SetDevicePassword(std::string & SerialNumber, std::string & Password); + bool GetDeviceCount(uint64_t &Count); + bool GetDeviceSerialNumbers(uint64_t From, uint64_t HowMany, + std::vector &SerialNumbers, + const std::string &orderBy = ""); + bool GetDeviceFWUpdatePolicy(std::string &SerialNumber, std::string &Policy); + bool SetDevicePassword(std::string &SerialNumber, std::string &Password); bool UpdateSerialNumberCache(); - static void GetDeviceDbFieldList( Types::StringVec & Fields); + static void GetDeviceDbFieldList(Types::StringVec &Fields); - bool ExistingConfiguration(std::string &SerialNumber, uint64_t CurrentConfig, std::string &NewConfig, uint64_t &); + bool ExistingConfiguration(std::string &SerialNumber, uint64_t CurrentConfig, + std::string &NewConfig, uint64_t &); - bool UpdateDeviceCapabilities(std::string &SerialNumber, const Config::Capabilities & Capabilities); + bool UpdateDeviceCapabilities(std::string &SerialNumber, + const Config::Capabilities &Capabilities); bool GetDeviceCapabilities(std::string &SerialNumber, GWObjects::Capabilities &); - bool DeleteDeviceCapabilities(std::string & SerialNumber); - bool CreateDeviceCapabilities(std::string & SerialNumber, const Config::Capabilities & Capabilities); + bool DeleteDeviceCapabilities(std::string &SerialNumber); + bool CreateDeviceCapabilities(std::string &SerialNumber, + const Config::Capabilities &Capabilities); bool InitCapabilitiesCache(); - bool GetLogData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, uint64_t Offset, uint64_t HowMany, - std::vector &Stats, uint64_t Type); - bool DeleteLogData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, uint64_t Type); - bool GetNewestLogData(std::string &SerialNumber, uint64_t HowMany, std::vector &Stats, uint64_t Type); + bool GetLogData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, + uint64_t Offset, uint64_t HowMany, std::vector &Stats, + uint64_t Type); + bool DeleteLogData(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, + uint64_t Type); + bool GetNewestLogData(std::string &SerialNumber, uint64_t HowMany, + std::vector &Stats, uint64_t Type); - bool CreateDefaultConfiguration(std::string & name, GWObjects::DefaultConfiguration & DefConfig); - bool DeleteDefaultConfiguration(std::string & name); - bool UpdateDefaultConfiguration(std::string & name, GWObjects::DefaultConfiguration & DefConfig); - bool GetDefaultConfiguration(std::string &name, GWObjects::DefaultConfiguration & DefConfig); - bool GetDefaultConfigurations(uint64_t From, uint64_t HowMany, std::vector &Devices); - bool FindDefaultConfigurationForModel(const std::string & Model, GWObjects::DefaultConfiguration & DefConfig ); + bool CreateDefaultConfiguration(std::string &name, + GWObjects::DefaultConfiguration &DefConfig); + bool DeleteDefaultConfiguration(std::string &name); + bool UpdateDefaultConfiguration(std::string &name, + GWObjects::DefaultConfiguration &DefConfig); + bool GetDefaultConfiguration(std::string &name, GWObjects::DefaultConfiguration &DefConfig); + bool GetDefaultConfigurations(uint64_t From, uint64_t HowMany, + std::vector &Devices); + bool FindDefaultConfigurationForModel(const std::string &Model, + GWObjects::DefaultConfiguration &DefConfig); uint64_t GetDefaultConfigurationsCount(); bool DefaultConfigurationAlreadyExists(std::string &Name); - bool AddCommand(std::string & SerialNumber, GWObjects::CommandDetails & Command,CommandExecutionType Type); - bool GetCommands(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, uint64_t Offset, uint64_t HowMany, std::vector & Commands); + bool AddCommand(std::string &SerialNumber, GWObjects::CommandDetails &Command, + CommandExecutionType Type); + bool GetCommands(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate, + uint64_t Offset, uint64_t HowMany, + std::vector &Commands); bool DeleteCommands(std::string &SerialNumber, uint64_t FromDate, uint64_t ToDate); - bool GetNonExecutedCommands( uint64_t Offset, uint64_t HowMany, std::vector & Commands ); - bool UpdateCommand( std::string &UUID, GWObjects::CommandDetails & Command ); - bool GetCommand( const std::string &UUID, GWObjects::CommandDetails & Command ); - bool DeleteCommand( std::string &UUID ); - bool GetReadyToExecuteCommands( uint64_t Offset, uint64_t HowMany, std::vector & Commands ); - bool CommandExecuted(std::string & UUID); - bool SetCommandLastTry(std::string & UUID); - bool CommandCompleted(std::string & UUID, Poco::JSON::Object::Ptr ReturnVars, const std::chrono::duration & execution_time, bool FullCommand); - bool AttachFileDataToCommand(std::string & UUID, const std::stringstream &s, const std::string &Type); - bool CancelWaitFile( std::string & UUID, std::string & ErrorText ); - bool GetAttachedFileContent(std::string & UUID, const std::string & SerialNumber, std::string & FileContent, std::string &Type); - bool RemoveAttachedFile(std::string & UUID); - bool SetCommandResult(std::string & UUID, std::string & Result); - bool GetNewestCommands(std::string &SerialNumber, uint64_t HowMany, std::vector & Commands); - bool SetCommandExecuted(std::string & CommandUUID); + bool GetNonExecutedCommands(uint64_t Offset, uint64_t HowMany, + std::vector &Commands); + bool UpdateCommand(std::string &UUID, GWObjects::CommandDetails &Command); + bool GetCommand(const std::string &UUID, GWObjects::CommandDetails &Command); + bool DeleteCommand(std::string &UUID); + bool GetReadyToExecuteCommands(uint64_t Offset, uint64_t HowMany, + std::vector &Commands); + bool CommandExecuted(std::string &UUID); + bool SetCommandLastTry(std::string &UUID); + bool CommandCompleted(std::string &UUID, Poco::JSON::Object::Ptr ReturnVars, + const std::chrono::duration &execution_time, + bool FullCommand); + bool AttachFileDataToCommand(std::string &UUID, const std::stringstream &s, + const std::string &Type); + bool CancelWaitFile(std::string &UUID, std::string &ErrorText); + bool GetAttachedFileContent(std::string &UUID, const std::string &SerialNumber, + std::string &FileContent, std::string &Type); + bool RemoveAttachedFile(std::string &UUID); + bool SetCommandResult(std::string &UUID, std::string &Result); + bool GetNewestCommands(std::string &SerialNumber, uint64_t HowMany, + std::vector &Commands); + bool SetCommandExecuted(std::string &CommandUUID); bool SetCommandTimedOut(std::string &CommandUUID); - bool SetCommandStatus(std::string & CommandUUID, std::uint64_t Error, const char *ErrorText); + bool SetCommandStatus(std::string &CommandUUID, std::uint64_t Error, const char *ErrorText); void RemovedExpiredCommands(); void RemoveTimedOutCommands(); - bool RemoveOldCommands(std::string & SerilNumber, std::string & Command); + bool RemoveOldCommands(std::string &SerilNumber, std::string &Command); - bool AddBlackListDevices(std::vector & Devices); - bool AddBlackListDevice(GWObjects::BlackListedDevice & Device); - bool GetBlackListDevice(std::string & SerialNumber, GWObjects::BlackListedDevice & Device); - bool DeleteBlackListDevice(std::string & SerialNumber); - bool IsBlackListed(const std::string &SerialNumber, std::string &reason, std::string &author, std::uint64_t &created); + bool AddBlackListDevices(std::vector &Devices); + bool AddBlackListDevice(GWObjects::BlackListedDevice &Device); + bool GetBlackListDevice(std::string &SerialNumber, GWObjects::BlackListedDevice &Device); + bool DeleteBlackListDevice(std::string &SerialNumber); + bool IsBlackListed(const std::string &SerialNumber, std::string &reason, + std::string &author, std::uint64_t &created); bool IsBlackListed(const std::string &SerialNumber); bool InitializeBlackListCache(); - bool GetBlackListDevices(uint64_t Offset, uint64_t HowMany, std::vector & Devices ); - bool UpdateBlackListDevice(std::string & SerialNumber, GWObjects::BlackListedDevice & Device); + bool GetBlackListDevices(uint64_t Offset, uint64_t HowMany, + std::vector &Devices); + bool UpdateBlackListDevice(std::string &SerialNumber, GWObjects::BlackListedDevice &Device); uint64_t GetBlackListDeviceCount(); bool RemoveHealthChecksRecordsOlderThan(uint64_t Date); @@ -197,16 +235,13 @@ namespace OpenWifi { bool AnalyzeCommands(Types::CountedMap &R); bool AnalyzeDevices(GWObjects::Dashboard &D); - int Start() override; - void Stop() override; + int Start() override; + void Stop() override; private: + std::unique_ptr ScriptDB_; + }; - std::unique_ptr ScriptDB_; - - }; - - inline auto StorageService() { return Storage::instance(); } - -} // namespace + inline auto StorageService() { return Storage::instance(); } +} // namespace OpenWifi diff --git a/src/TelemetryClient.cpp b/src/TelemetryClient.cpp index a406062f..3fc92f49 100644 --- a/src/TelemetryClient.cpp +++ b/src/TelemetryClient.cpp @@ -2,27 +2,21 @@ // Created by stephane bourque on 2022-02-03. // -#include "AP_WS_Server.h" #include "TelemetryClient.h" -#include "TelemetryStream.h" +#include "AP_WS_Server.h" #include "CommandManager.h" +#include "TelemetryStream.h" #include "Poco/Net/SSLException.h" #include "fmt/format.h" namespace OpenWifi { - TelemetryClient::TelemetryClient( - std::string UUID, - uint64_t SerialNumber, - std::unique_ptr WSock, - Poco::Net::SocketReactor& Reactor, - Poco::Logger &Logger): - UUID_(std::move(UUID)), - SerialNumber_(SerialNumber), - Reactor_(Reactor), - Logger_(Logger), - WS_(std::move(WSock)) { + TelemetryClient::TelemetryClient(std::string UUID, uint64_t SerialNumber, + std::unique_ptr WSock, + Poco::Net::SocketReactor &Reactor, Poco::Logger &Logger) + : UUID_(std::move(UUID)), SerialNumber_(SerialNumber), Reactor_(Reactor), Logger_(Logger), + WS_(std::move(WSock)) { CompleteStartup(); } @@ -38,115 +32,126 @@ namespace OpenWifi { WS_->setKeepAlive(true); WS_->setMaxPayloadSize(2048); WS_->setBlocking(false); - Reactor_.addEventHandler( - *WS_, Poco::NObserver( - *this, &TelemetryClient::OnSocketReadable)); - Reactor_.addEventHandler( - *WS_, Poco::NObserver( - *this, &TelemetryClient::OnSocketShutdown)); - Reactor_.addEventHandler( - *WS_, Poco::NObserver( - *this, &TelemetryClient::OnSocketError)); + Reactor_.addEventHandler(*WS_, + Poco::NObserver( + *this, &TelemetryClient::OnSocketReadable)); + Reactor_.addEventHandler(*WS_, + Poco::NObserver( + *this, &TelemetryClient::OnSocketShutdown)); + Reactor_.addEventHandler(*WS_, + Poco::NObserver( + *this, &TelemetryClient::OnSocketError)); Registered_ = true; - poco_information(Logger(),fmt::format("TELEMETRY-CONNECTION({}): Connection completed.", CId_)); + poco_information(Logger(), + fmt::format("TELEMETRY-CONNECTION({}): Connection completed.", CId_)); } TelemetryClient::~TelemetryClient() { - poco_information(Logger(),fmt::format("TELEMETRY-CONNECTION({}): Closing connection.", CId_)); + poco_information(Logger(), + fmt::format("TELEMETRY-CONNECTION({}): Closing connection.", CId_)); DeRegister(); } void TelemetryClient::DeRegister() { - if(Registered_) { + if (Registered_) { Registered_ = false; - Reactor_.removeEventHandler(*WS_, - Poco::NObserver(*this,&TelemetryClient::OnSocketReadable)); - Reactor_.removeEventHandler(*WS_, - Poco::NObserver(*this,&TelemetryClient::OnSocketShutdown)); - Reactor_.removeEventHandler(*WS_, - Poco::NObserver(*this,&TelemetryClient::OnSocketError)); + Reactor_.removeEventHandler( + *WS_, Poco::NObserver( + *this, &TelemetryClient::OnSocketReadable)); + Reactor_.removeEventHandler( + *WS_, Poco::NObserver( + *this, &TelemetryClient::OnSocketShutdown)); + Reactor_.removeEventHandler( + *WS_, Poco::NObserver( + *this, &TelemetryClient::OnSocketError)); } } bool TelemetryClient::Send(const std::string &Payload) { std::lock_guard Guard(Mutex_); - size_t BytesSent = WS_->sendFrame(Payload.c_str(),(int)Payload.size()); - return BytesSent == Payload.size(); + size_t BytesSent = WS_->sendFrame(Payload.c_str(), (int)Payload.size()); + return BytesSent == Payload.size(); } void TelemetryClient::SendTelemetryShutdown() { - poco_information(Logger(),fmt::format("TELEMETRY-SHUTDOWN({}): Closing.",CId_)); + poco_information(Logger(), fmt::format("TELEMETRY-SHUTDOWN({}): Closing.", CId_)); DeRegister(); AP_WS_Server()->StopWebSocketTelemetry(CommandManager()->Next_RPC_ID(), SerialNumber_); TelemetryStream()->DeRegisterClient(UUID_); } - void TelemetryClient::OnSocketShutdown([[maybe_unused]] const Poco::AutoPtr& pNf) { - poco_information(Logger(),fmt::format("TELEMETRY-SOCKET-SHUTDOWN({}): Orderly shutdown.", CId_)); + void TelemetryClient::OnSocketShutdown( + [[maybe_unused]] const Poco::AutoPtr &pNf) { + poco_information(Logger(), + fmt::format("TELEMETRY-SOCKET-SHUTDOWN({}): Orderly shutdown.", CId_)); SendTelemetryShutdown(); } - void TelemetryClient::OnSocketError([[maybe_unused]] const Poco::AutoPtr& pNf) { - poco_information(Logger(),fmt::format("TELEMETRY-SOCKET-ERROR({}): Closing.",CId_)); + void TelemetryClient::OnSocketError( + [[maybe_unused]] const Poco::AutoPtr &pNf) { + poco_information(Logger(), fmt::format("TELEMETRY-SOCKET-ERROR({}): Closing.", CId_)); SendTelemetryShutdown(); } - void TelemetryClient::OnSocketReadable([[maybe_unused]] const Poco::AutoPtr& pNf) { - try - { + void TelemetryClient::OnSocketReadable( + [[maybe_unused]] const Poco::AutoPtr &pNf) { + try { std::lock_guard Guard(Mutex_); return ProcessIncomingFrame(); - } - catch (const Poco::Exception & E) - { + } catch (const Poco::Exception &E) { Logger().log(E); - } - catch (const std::exception & E) { + } catch (const std::exception &E) { std::string W = E.what(); - poco_information(Logger(),fmt::format("TELEMETRY-std::exception caught: {}. Connection terminated with {}",W,CId_)); - } - catch ( ... ) { - poco_information(Logger(),fmt::format("TELEMETRY-Unknown exception for {}. Connection terminated.",CId_)); + poco_information( + Logger(), + fmt::format("TELEMETRY-std::exception caught: {}. Connection terminated with {}", W, + CId_)); + } catch (...) { + poco_information( + Logger(), + fmt::format("TELEMETRY-Unknown exception for {}. Connection terminated.", CId_)); } SendTelemetryShutdown(); } void TelemetryClient::ProcessIncomingFrame() { - bool MustDisconnect=false; - Poco::Buffer IncomingFrame(0); + bool MustDisconnect = false; + Poco::Buffer IncomingFrame(0); try { - int Op,flags; + int Op, flags; int IncomingSize; - IncomingSize = WS_->receiveFrame(IncomingFrame,flags); + IncomingSize = WS_->receiveFrame(IncomingFrame, flags); Op = flags & Poco::Net::WebSocket::FRAME_OP_BITMASK; if (IncomingSize == 0 && flags == 0 && Op == 0) { - poco_information(Logger(),fmt::format("TELEMETRY-DISCONNECT({}): device has disconnected.", CId_)); + poco_information( + Logger(), + fmt::format("TELEMETRY-DISCONNECT({}): device has disconnected.", CId_)); MustDisconnect = true; } else { if (Op == Poco::Net::WebSocket::FRAME_OP_PING) { - Logger().debug(fmt::format("TELEMETRY-WS-PING({}): received. PONG sent back.", CId_)); + Logger().debug( + fmt::format("TELEMETRY-WS-PING({}): received. PONG sent back.", CId_)); WS_->sendFrame("", 0, (int)Poco::Net::WebSocket::FRAME_OP_PONG | (int)Poco::Net::WebSocket::FRAME_FLAG_FIN); } else if (Op == Poco::Net::WebSocket::FRAME_OP_CLOSE) { - poco_information(Logger(),fmt::format("TELEMETRY-DISCONNECT({}): device wants to disconnect.", CId_)); - MustDisconnect = true ; + poco_information( + Logger(), + fmt::format("TELEMETRY-DISCONNECT({}): device wants to disconnect.", CId_)); + MustDisconnect = true; } } } catch (...) { - MustDisconnect = true ; + MustDisconnect = true; } - if(!MustDisconnect) + if (!MustDisconnect) return; SendTelemetryShutdown(); } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/TelemetryClient.h b/src/TelemetryClient.h index 8f88dbdd..244131b2 100644 --- a/src/TelemetryClient.h +++ b/src/TelemetryClient.h @@ -4,46 +4,44 @@ #pragma once -#include #include +#include #include "Poco/AutoPtr.h" +#include "Poco/Logger.h" +#include "Poco/Net/SocketNotification.h" #include "Poco/Net/SocketReactor.h" #include "Poco/Net/WebSocket.h" -#include "Poco/Net/SocketNotification.h" -#include "Poco/Logger.h" namespace OpenWifi { class TelemetryClient { static constexpr int BufSize = 64000; + public: - TelemetryClient( - std::string UUID, - uint64_t SerialNumber, - std::unique_ptr WSock, - Poco::Net::SocketReactor& Reactor, - Poco::Logger &Logger); + TelemetryClient(std::string UUID, uint64_t SerialNumber, + std::unique_ptr WSock, + Poco::Net::SocketReactor &Reactor, Poco::Logger &Logger); ~TelemetryClient(); - void OnSocketReadable(const Poco::AutoPtr& pNf); - void OnSocketShutdown(const Poco::AutoPtr& pNf); - void OnSocketError(const Poco::AutoPtr& pNf); + void OnSocketReadable(const Poco::AutoPtr &pNf); + void OnSocketShutdown(const Poco::AutoPtr &pNf); + void OnSocketError(const Poco::AutoPtr &pNf); bool Send(const std::string &Payload); void ProcessIncomingFrame(); - inline Poco::Logger & Logger() { return Logger_; } + inline Poco::Logger &Logger() { return Logger_; } private: - std::recursive_mutex Mutex_; - std::string UUID_; - uint64_t SerialNumber_; - Poco::Net::SocketReactor &Reactor_; - Poco::Logger &Logger_; - Poco::Net::StreamSocket Socket_; - std::string CId_; - std::unique_ptr WS_; - bool Registered_=false; + std::recursive_mutex Mutex_; + std::string UUID_; + uint64_t SerialNumber_; + Poco::Net::SocketReactor &Reactor_; + Poco::Logger &Logger_; + Poco::Net::StreamSocket Socket_; + std::string CId_; + std::unique_ptr WS_; + bool Registered_ = false; void SendTelemetryShutdown(); void CompleteStartup(); void DeRegister(); }; -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file diff --git a/src/TelemetryStream.cpp b/src/TelemetryStream.cpp index be9910b4..9667c95d 100644 --- a/src/TelemetryStream.cpp +++ b/src/TelemetryStream.cpp @@ -17,41 +17,42 @@ namespace OpenWifi { int TelemetryStream::Start() { Running_ = true; ReactorThr_.start(Reactor_); - Utils::SetThreadName(ReactorThr_,"tel:reactor"); + Utils::SetThreadName(ReactorThr_, "tel:reactor"); NotificationMgr_.start(*this); return 0; } void TelemetryStream::Stop() { - poco_information(Logger(),"Stopping..."); + poco_information(Logger(), "Stopping..."); Running_ = false; Reactor_.stop(); ReactorThr_.join(); MsgQueue_.wakeUpAll(); NotificationMgr_.wakeUp(); NotificationMgr_.join(); - poco_information(Logger(),"Stopped..."); + poco_information(Logger(), "Stopped..."); } - bool TelemetryStream::IsValidEndPoint(uint64_t SerialNumber, const std::string & UUID) { - std::lock_guard G(Mutex_); + bool TelemetryStream::IsValidEndPoint(uint64_t SerialNumber, const std::string &UUID) { + std::lock_guard G(Mutex_); auto U = Clients_.find(UUID); - if(U == Clients_.end() ) + if (U == Clients_.end()) return false; auto N = SerialNumbers_.find(SerialNumber); - if(N == SerialNumbers_.end()) + if (N == SerialNumbers_.end()) return false; return (N->second.find(UUID) != N->second.end()); } - bool TelemetryStream::CreateEndpoint(uint64_t SerialNumber, std::string &EndPoint, const std::string &UUID) { - std::lock_guard G(Mutex_); + bool TelemetryStream::CreateEndpoint(uint64_t SerialNumber, std::string &EndPoint, + const std::string &UUID) { + std::lock_guard G(Mutex_); - Poco::URI Public(MicroServiceConfigGetString("openwifi.system.uri.public","")); - Poco::URI U; + Poco::URI Public(MicroServiceConfigGetString("openwifi.system.uri.public", "")); + Poco::URI U; U.setScheme("wss"); U.setHost(Public.getHost()); U.setPort(Public.getPort()); @@ -73,60 +74,74 @@ namespace OpenWifi { while (NextNotification && Running_) { auto Notification = dynamic_cast(NextNotification.get()); if (Notification != nullptr) { - std::lock_guard Lock(Mutex_); - switch( Notification->Type_ ) { - case TelemetryNotification::NotificationType::data : { - auto SerialNumberSetOfUUIDs = SerialNumbers_.find(Notification->SerialNumber_); - if (SerialNumberSetOfUUIDs != SerialNumbers_.end()) { - for (auto &uuid : SerialNumberSetOfUUIDs->second) { - auto Client = Clients_.find(uuid); - if (Client != Clients_.end() && Client->second != nullptr) { - try { - // std::cout << "Sent WS telemetry notification" << std::endl; - Client->second->Send(Notification->Data_); - } catch (const Poco::Exception &E) { - Logger().log(E); - } catch (std::exception &E) { - poco_warning(Logger(),fmt::format("Std:Ex Cannot send WS telemetry notification: {} for SerialNumber: {}", E.what(), Utils::IntToSerialNumber(Notification->SerialNumber_))); - } - } else { - poco_warning(Logger(),fmt::format("Cannot send WS telemetry notification for SerialNumber: {}", Utils::IntToSerialNumber(Notification->SerialNumber_))); + std::lock_guard Lock(Mutex_); + switch (Notification->Type_) { + case TelemetryNotification::NotificationType::data: { + auto SerialNumberSetOfUUIDs = SerialNumbers_.find(Notification->SerialNumber_); + if (SerialNumberSetOfUUIDs != SerialNumbers_.end()) { + for (auto &uuid : SerialNumberSetOfUUIDs->second) { + auto Client = Clients_.find(uuid); + if (Client != Clients_.end() && Client->second != nullptr) { + try { + // std::cout << "Sent WS telemetry notification" << std::endl; + Client->second->Send(Notification->Data_); + } catch (const Poco::Exception &E) { + Logger().log(E); + } catch (std::exception &E) { + poco_warning( + Logger(), + fmt::format( + "Std:Ex Cannot send WS telemetry notification: {} for " + "SerialNumber: {}", + E.what(), + Utils::IntToSerialNumber(Notification->SerialNumber_))); } + } else { + poco_warning(Logger(), + fmt::format("Cannot send WS telemetry notification " + "for SerialNumber: {}", + Utils::IntToSerialNumber( + Notification->SerialNumber_))); } - } else { - poco_warning(Logger(),fmt::format("Cannot find serial: {}", Utils::IntToSerialNumber(Notification->SerialNumber_))); } - } break; - case TelemetryNotification::NotificationType::unregister : { - std::lock_guard G(Mutex_); + } else { + poco_warning(Logger(), fmt::format("Cannot find serial: {}", + Utils::IntToSerialNumber( + Notification->SerialNumber_))); + } + } break; + case TelemetryNotification::NotificationType::unregister: { + std::lock_guard G(Mutex_); - auto client = Clients_.find(Notification->Data_); - if(client!=Clients_.end()) { - for(auto i = SerialNumbers_.begin(); i!= SerialNumbers_.end();) { - i->second.erase(Notification->Data_); - if(i->second.empty()) { - i = SerialNumbers_.erase(i); - } else { - ++i; - } + auto client = Clients_.find(Notification->Data_); + if (client != Clients_.end()) { + for (auto i = SerialNumbers_.begin(); i != SerialNumbers_.end();) { + i->second.erase(Notification->Data_); + if (i->second.empty()) { + i = SerialNumbers_.erase(i); + } else { + ++i; } - Clients_.erase(client); - } else { - poco_warning(Logger(),fmt::format("Unknown connection: {}", Notification->Data_)); } - } break; + Clients_.erase(client); + } else { + poco_warning(Logger(), + fmt::format("Unknown connection: {}", Notification->Data_)); + } + } break; - default: { + default: { - } break; + } break; } } NextNotification = MsgQueue_.waitDequeueNotification(); } } - bool TelemetryStream::NewClient(const std::string &UUID, uint64_t SerialNumber, std::unique_ptr Client) { - std::lock_guard G(Mutex_); + bool TelemetryStream::NewClient(const std::string &UUID, uint64_t SerialNumber, + std::unique_ptr Client) { + std::lock_guard G(Mutex_); try { Clients_[UUID] = std::make_unique( UUID, SerialNumber, std::move(Client), NextReactor(), Logger()); @@ -137,8 +152,12 @@ namespace OpenWifi { } catch (const Poco::Exception &E) { Logger().log(E); } catch (...) { - poco_warning(Logger(),fmt::format("Could not create a telemetry client for session {} and serial number {}", UUID, SerialNumber)); + poco_warning( + Logger(), + fmt::format( + "Could not create a telemetry client for session {} and serial number {}", UUID, + SerialNumber)); } return false; } -} +} // namespace OpenWifi diff --git a/src/TelemetryStream.h b/src/TelemetryStream.h index 965389b5..e4fbbdcb 100644 --- a/src/TelemetryStream.h +++ b/src/TelemetryStream.h @@ -6,20 +6,20 @@ #include -#include "Poco/Net/SocketReactor.h" -#include "Poco/Net/ParallelSocketAcceptor.h" -#include "Poco/Net/WebSocket.h" -#include "Poco/Net/SecureStreamSocket.h" -#include "Poco/Net/SecureStreamSocketImpl.h" -#include "Poco/Net/HTTPRequestHandlerFactory.h" #include "Poco/Net/HTTPRequestHandler.h" +#include "Poco/Net/HTTPRequestHandlerFactory.h" +#include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerRequestImpl.h" +#include "Poco/Net/ParallelSocketAcceptor.h" +#include "Poco/Net/SecureStreamSocket.h" +#include "Poco/Net/SecureStreamSocketImpl.h" +#include "Poco/Net/SocketReactor.h" +#include "Poco/Net/WebSocket.h" +#include "Poco/Notification.h" +#include "Poco/NotificationQueue.h" #include "Poco/Timespan.h" #include "Poco/URI.h" -#include "Poco/Net/HTTPServer.h" -#include "Poco/NotificationQueue.h" -#include "Poco/Notification.h" #include "framework/SubSystemServer.h" @@ -30,37 +30,28 @@ namespace OpenWifi { class TelemetryNotification : public Poco::Notification { public: - enum class NotificationType { - data, - unregister - }; + enum class NotificationType { data, unregister }; - explicit TelemetryNotification(std::uint64_t SerialNumber, const std::string &Payload) : - Type_(NotificationType::data), - SerialNumber_(SerialNumber), - Data_(Payload) { - } + explicit TelemetryNotification(std::uint64_t SerialNumber, const std::string &Payload) + : Type_(NotificationType::data), SerialNumber_(SerialNumber), Data_(Payload) {} - explicit TelemetryNotification(const std::string &UUID) : - Type_(NotificationType::unregister), - Data_(UUID) { - } + explicit TelemetryNotification(const std::string &UUID) + : Type_(NotificationType::unregister), Data_(UUID) {} - NotificationType Type_; - std::uint64_t SerialNumber_=0; - std::string Data_; + NotificationType Type_; + std::uint64_t SerialNumber_ = 0; + std::string Data_; }; class TelemetryStream : public SubSystemServer, Poco::Runnable { public: - struct QueueUpdate { - uint64_t SerialNumber; + uint64_t SerialNumber; std::string Payload; }; static auto instance() { - static auto instance_ = new TelemetryStream; + static auto instance_ = new TelemetryStream; return instance_; } @@ -68,37 +59,36 @@ namespace OpenWifi { void Stop() override; void run() final; - bool IsValidEndPoint(uint64_t SerialNumber, const std::string & UUID); + bool IsValidEndPoint(uint64_t SerialNumber, const std::string &UUID); bool CreateEndpoint(uint64_t SerialNumber, std::string &EndPoint, const std::string &UUID); inline void NotifyEndPoint(uint64_t SerialNumber, const std::string &PayLoad) { - MsgQueue_.enqueueNotification(new TelemetryNotification(SerialNumber,PayLoad)); + MsgQueue_.enqueueNotification(new TelemetryNotification(SerialNumber, PayLoad)); } inline void DeRegisterClient(const std::string &UUID) { MsgQueue_.enqueueNotification(new TelemetryNotification(UUID)); } - bool NewClient(const std::string &UUID, uint64_t SerialNumber, std::unique_ptr Client); + bool NewClient(const std::string &UUID, uint64_t SerialNumber, + std::unique_ptr Client); - - Poco::Net::SocketReactor & NextReactor() { return Reactor_; } + Poco::Net::SocketReactor &NextReactor() { return Reactor_; } private: - volatile std::atomic_bool Running_=false; - std::map> SerialNumbers_; // serialNumber -> uuid - Poco::Net::SocketReactor Reactor_; - Poco::Thread ReactorThr_; - Poco::Thread NotificationMgr_; - Poco::NotificationQueue MsgQueue_; + volatile std::atomic_bool Running_ = false; + std::map> SerialNumbers_; // serialNumber -> uuid + Poco::Net::SocketReactor Reactor_; + Poco::Thread ReactorThr_; + Poco::Thread NotificationMgr_; + Poco::NotificationQueue MsgQueue_; - std::map > Clients_; // uuid -> client + std::map> Clients_; // uuid -> client - TelemetryStream() noexcept: - SubSystemServer("TelemetryServer", "TELEMETRY-SVR", "openwifi.telemetry") { - } + TelemetryStream() noexcept + : SubSystemServer("TelemetryServer", "TELEMETRY-SVR", "openwifi.telemetry") {} }; inline auto TelemetryStream() { return TelemetryStream::instance(); } - } +} // namespace OpenWifi diff --git a/src/UI_GW_WebSocketNotifications.cpp b/src/UI_GW_WebSocketNotifications.cpp index e25af41c..ba6615ab 100644 --- a/src/UI_GW_WebSocketNotifications.cpp +++ b/src/UI_GW_WebSocketNotifications.cpp @@ -7,154 +7,147 @@ namespace OpenWifi::GWWebSocketNotifications { inline void SingleDevice::to_json(Poco::JSON::Object &Obj) const { - RESTAPI_utils::field_to_json(Obj,"serialNumber", serialNumber); + RESTAPI_utils::field_to_json(Obj, "serialNumber", serialNumber); } inline bool SingleDevice::from_json(const Poco::JSON::Object::Ptr &Obj) { try { - RESTAPI_utils::field_from_json(Obj,"serialNumber", serialNumber); + RESTAPI_utils::field_from_json(Obj, "serialNumber", serialNumber); return true; } catch (...) { - } return false; } inline void SingleDeviceConfigurationChange::to_json(Poco::JSON::Object &Obj) const { - RESTAPI_utils::field_to_json(Obj,"serialNumber", serialNumber); - RESTAPI_utils::field_to_json(Obj,"oldUUID", oldUUID); - RESTAPI_utils::field_to_json(Obj,"newUUID", newUUID); + RESTAPI_utils::field_to_json(Obj, "serialNumber", serialNumber); + RESTAPI_utils::field_to_json(Obj, "oldUUID", oldUUID); + RESTAPI_utils::field_to_json(Obj, "newUUID", newUUID); } inline bool SingleDeviceConfigurationChange::from_json(const Poco::JSON::Object::Ptr &Obj) { try { - RESTAPI_utils::field_from_json(Obj,"serialNumber", serialNumber); - RESTAPI_utils::field_from_json(Obj,"oldUUID", oldUUID); - RESTAPI_utils::field_from_json(Obj,"newUUID", newUUID); + RESTAPI_utils::field_from_json(Obj, "serialNumber", serialNumber); + RESTAPI_utils::field_from_json(Obj, "oldUUID", oldUUID); + RESTAPI_utils::field_from_json(Obj, "newUUID", newUUID); return true; } catch (...) { - } return false; } inline void SingleDeviceFirmwareChange::to_json(Poco::JSON::Object &Obj) const { - RESTAPI_utils::field_to_json(Obj,"serialNumber", serialNumber); - RESTAPI_utils::field_to_json(Obj,"newFirmware", newFirmware); + RESTAPI_utils::field_to_json(Obj, "serialNumber", serialNumber); + RESTAPI_utils::field_to_json(Obj, "newFirmware", newFirmware); } inline bool SingleDeviceFirmwareChange::from_json(const Poco::JSON::Object::Ptr &Obj) { try { - RESTAPI_utils::field_from_json(Obj,"serialNumber", serialNumber); - RESTAPI_utils::field_from_json(Obj,"newFirmware", newFirmware); + RESTAPI_utils::field_from_json(Obj, "serialNumber", serialNumber); + RESTAPI_utils::field_from_json(Obj, "newFirmware", newFirmware); return true; } catch (...) { - } return false; } inline void NumberOfConnection::to_json(Poco::JSON::Object &Obj) const { - RESTAPI_utils::field_to_json(Obj,"numberOfDevices", numberOfDevices); - RESTAPI_utils::field_to_json(Obj,"averageConnectedTime", averageConnectedTime); - RESTAPI_utils::field_to_json(Obj,"numberOfConnectingDevices", numberOfConnectingDevices); + RESTAPI_utils::field_to_json(Obj, "numberOfDevices", numberOfDevices); + RESTAPI_utils::field_to_json(Obj, "averageConnectedTime", averageConnectedTime); + RESTAPI_utils::field_to_json(Obj, "numberOfConnectingDevices", numberOfConnectingDevices); } inline bool NumberOfConnection::from_json(const Poco::JSON::Object::Ptr &Obj) { try { - RESTAPI_utils::field_from_json(Obj,"numberOfDevices", numberOfDevices); - RESTAPI_utils::field_from_json(Obj,"averageConnectedTime", averageConnectedTime); - RESTAPI_utils::field_from_json(Obj,"numberOfConnectingDevices", numberOfConnectingDevices); + RESTAPI_utils::field_from_json(Obj, "numberOfDevices", numberOfDevices); + RESTAPI_utils::field_from_json(Obj, "averageConnectedTime", averageConnectedTime); + RESTAPI_utils::field_from_json(Obj, "numberOfConnectingDevices", + numberOfConnectingDevices); return true; } catch (...) { - } return false; } void NumberOfConnections(NumberOfConnection_t &N) { // N.type = "device_connections_statistics"; - N.type_id = 1000 ; + N.type_id = 1000; UI_WebSocketClientServer()->SendNotification(N); } - void NumberOfConnections(const std::string & User, NumberOfConnection_t &N) { + void NumberOfConnections(const std::string &User, NumberOfConnection_t &N) { // N.type = "device_connections_statistics"; - N.type_id = 1000 ; - UI_WebSocketClientServer()->SendUserNotification(User,N); + N.type_id = 1000; + UI_WebSocketClientServer()->SendUserNotification(User, N); } void DeviceConfigurationChange(SingleDeviceConfigurationChange_t &N) { // N.type = "device_configuration_upgrade"; - N.type_id = 2000 ; + N.type_id = 2000; UI_WebSocketClientServer()->SendNotification(N); } - void DeviceConfigurationChange(const std::string & User, SingleDeviceConfigurationChange_t &N) { + void DeviceConfigurationChange(const std::string &User, SingleDeviceConfigurationChange_t &N) { // N.type = "device_configuration_upgrade"; - N.type_id = 2000 ; - UI_WebSocketClientServer()->SendUserNotification(User,N); + N.type_id = 2000; + UI_WebSocketClientServer()->SendUserNotification(User, N); } void DeviceFirmwareUpdated(SingleDeviceFirmwareChange_t &N) { // N.type = "device_firmware_upgrade"; - N.type_id = 3000 ; + N.type_id = 3000; UI_WebSocketClientServer()->SendNotification(N); } - void DeviceFirmwareUpdated(const std::string & User, SingleDeviceFirmwareChange_t &N){ + void DeviceFirmwareUpdated(const std::string &User, SingleDeviceFirmwareChange_t &N) { // N.type = "device_firmware_upgrade"; - N.type_id = 3000 ; - UI_WebSocketClientServer()->SendUserNotification(User,N); + N.type_id = 3000; + UI_WebSocketClientServer()->SendUserNotification(User, N); } - void DeviceConnected(SingleDevice_t &N){ + void DeviceConnected(SingleDevice_t &N) { // N.type = "device_connection"; - N.type_id = 4000 ; + N.type_id = 4000; UI_WebSocketClientServer()->SendNotification(N); } - void DeviceConnected(const std::string & User, SingleDevice_t &N){ + void DeviceConnected(const std::string &User, SingleDevice_t &N) { // N.type = "device_connection"; - N.type_id = 4000 ; - UI_WebSocketClientServer()->SendUserNotification(User,N); + N.type_id = 4000; + UI_WebSocketClientServer()->SendUserNotification(User, N); } - void DeviceDisconnected(const std::string & User, SingleDevice_t &N){ + void DeviceDisconnected(const std::string &User, SingleDevice_t &N) { // N.type = "device_disconnection"; - N.type_id = 5000 ; - UI_WebSocketClientServer()->SendUserNotification(User,N); + N.type_id = 5000; + UI_WebSocketClientServer()->SendUserNotification(User, N); } - void DeviceDisconnected(SingleDevice_t &N){ + void DeviceDisconnected(SingleDevice_t &N) { // N.type = "device_disconnection"; - N.type_id = 5000 ; + N.type_id = 5000; UI_WebSocketClientServer()->SendNotification(N); } - void DeviceStatistics(const std::string & User, SingleDevice_t &N){ + void DeviceStatistics(const std::string &User, SingleDevice_t &N) { // N.type = "device_statistics"; - N.type_id = 6000 ; - UI_WebSocketClientServer()->SendUserNotification(User,N); + N.type_id = 6000; + UI_WebSocketClientServer()->SendUserNotification(User, N); } - void DeviceStatistics(SingleDevice_t &N){ + void DeviceStatistics(SingleDevice_t &N) { // N.type = "device_statistics"; - N.type_id = 6000 ; + N.type_id = 6000; UI_WebSocketClientServer()->SendNotification(N); } void Register() { static const UI_WebSocketClientServer::NotificationTypeIdVec Notifications = { - { 1000, "device_connections_statistics" }, - { 2000, "device_configuration_upgrade" }, - { 3000, "device_firmware_upgrade" }, - { 4000, "device_connection" }, - { 5000, "device_disconnection" }, - { 6000, "device_statistics" } - }; + {1000, "device_connections_statistics"}, {2000, "device_configuration_upgrade"}, + {3000, "device_firmware_upgrade"}, {4000, "device_connection"}, + {5000, "device_disconnection"}, {6000, "device_statistics"}}; UI_WebSocketClientServer()->RegisterNotifications(Notifications); } -} \ No newline at end of file +} // namespace OpenWifi::GWWebSocketNotifications \ No newline at end of file diff --git a/src/UI_GW_WebSocketNotifications.h b/src/UI_GW_WebSocketNotifications.h index e58b2009..8a059060 100644 --- a/src/UI_GW_WebSocketNotifications.h +++ b/src/UI_GW_WebSocketNotifications.h @@ -10,40 +10,41 @@ namespace OpenWifi::GWWebSocketNotifications { struct SingleDevice { - std::string serialNumber; - inline void to_json(Poco::JSON::Object &Obj) const ; + std::string serialNumber; + inline void to_json(Poco::JSON::Object &Obj) const; inline bool from_json(const Poco::JSON::Object::Ptr &Obj); }; struct SingleDeviceConfigurationChange { - std::string serialNumber; - uint64_t oldUUID; - uint64_t newUUID; + std::string serialNumber; + uint64_t oldUUID; + uint64_t newUUID; - inline void to_json(Poco::JSON::Object &Obj) const ; + inline void to_json(Poco::JSON::Object &Obj) const; inline bool from_json(const Poco::JSON::Object::Ptr &Obj); }; struct SingleDeviceFirmwareChange { - std::string serialNumber; - std::string newFirmware; - inline void to_json(Poco::JSON::Object &Obj) const ; + std::string serialNumber; + std::string newFirmware; + inline void to_json(Poco::JSON::Object &Obj) const; inline bool from_json(const Poco::JSON::Object::Ptr &Obj); }; struct NumberOfConnection { - std::uint64_t numberOfDevices=0; - std::uint64_t averageConnectedTime=0; - std::uint64_t numberOfConnectingDevices=0; + std::uint64_t numberOfDevices = 0; + std::uint64_t averageConnectedTime = 0; + std::uint64_t numberOfConnectingDevices = 0; - inline void to_json(Poco::JSON::Object &Obj) const ; + inline void to_json(Poco::JSON::Object &Obj) const; inline bool from_json(const Poco::JSON::Object::Ptr &Obj); }; void Register(); typedef WebSocketNotification SingleDevice_t; - typedef WebSocketNotification SingleDeviceConfigurationChange_t; + typedef WebSocketNotification + SingleDeviceConfigurationChange_t; typedef WebSocketNotification SingleDeviceFirmwareChange_t; typedef WebSocketNotification NumberOfConnection_t; @@ -54,11 +55,11 @@ namespace OpenWifi::GWWebSocketNotifications { void DeviceDisconnected(SingleDevice_t &N); void DeviceStatistics(SingleDevice_t &N); - void NumberOfConnections(const std::string & User, NumberOfConnection_t &N); - void DeviceConfigurationChange(const std::string & User, SingleDeviceConfigurationChange_t &N); - void DeviceFirmwareUpdated(const std::string & User, SingleDeviceFirmwareChange_t &); - void DeviceConnected(const std::string & User, SingleDevice_t &N); - void DeviceDisconnected(const std::string & User, SingleDevice_t &N); - void DeviceStatistics(const std::string & User, SingleDevice_t &N); + void NumberOfConnections(const std::string &User, NumberOfConnection_t &N); + void DeviceConfigurationChange(const std::string &User, SingleDeviceConfigurationChange_t &N); + void DeviceFirmwareUpdated(const std::string &User, SingleDeviceFirmwareChange_t &); + void DeviceConnected(const std::string &User, SingleDevice_t &N); + void DeviceDisconnected(const std::string &User, SingleDevice_t &N); + void DeviceStatistics(const std::string &User, SingleDevice_t &N); -}; \ No newline at end of file +}; // namespace OpenWifi::GWWebSocketNotifications \ No newline at end of file diff --git a/src/VenueBroadcaster.h b/src/VenueBroadcaster.h index b3552325..65db2af9 100644 --- a/src/VenueBroadcaster.h +++ b/src/VenueBroadcaster.h @@ -7,8 +7,8 @@ #include "Poco/Notification.h" #include "Poco/NotificationQueue.h" -#include "sdks/sdk_prov.h" #include "AP_WS_Server.h" +#include "sdks/sdk_prov.h" #include "framework/MicroServiceFuncs.h" #include "framework/SubSystemServer.h" @@ -18,15 +18,12 @@ namespace OpenWifi { class VenueBroadcastNotification : public Poco::Notification { public: - VenueBroadcastNotification(const std::string &SourceSerialNumber, const std::string &Data, uint64_t TimeStamp) : - SourceSerialNumber_(SourceSerialNumber), - Data_(Data), - TimeStamp_(TimeStamp) { - - } - std::string SourceSerialNumber_; - std::string Data_; - uint64_t TimeStamp_=Utils::Now(); + VenueBroadcastNotification(const std::string &SourceSerialNumber, const std::string &Data, + uint64_t TimeStamp) + : SourceSerialNumber_(SourceSerialNumber), Data_(Data), TimeStamp_(TimeStamp) {} + std::string SourceSerialNumber_; + std::string Data_; + uint64_t TimeStamp_ = Utils::Now(); }; class VenueBroadcaster : public SubSystemServer, Poco::Runnable { @@ -37,54 +34,57 @@ namespace OpenWifi { } inline int Start() override { - Enabled_ = MicroServiceConfigGetBool("venue_broadcast.enabled",true); - if(Enabled_) { + Enabled_ = MicroServiceConfigGetBool("venue_broadcast.enabled", true); + if (Enabled_) { BroadcastManager_.start(*this); } return 0; } inline void Stop() override { - poco_information(Logger(),"Stopping..."); - if(Enabled_ && Running_) { + poco_information(Logger(), "Stopping..."); + if (Enabled_ && Running_) { BroadcastQueue_.wakeUpAll(); BroadcastManager_.wakeUp(); BroadcastManager_.join(); } - poco_information(Logger(),"Stopped..."); + poco_information(Logger(), "Stopped..."); } inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { - poco_information(Logger(),"Reinitializing."); + poco_information(Logger(), "Reinitializing."); } - struct VenueInfo { - uint64_t timestamp=Utils::Now(); - Types::StringVec serialNumbers; + uint64_t timestamp = Utils::Now(); + Types::StringVec serialNumbers; }; - inline bool FindSerialNumberList(const std::string &Source, OpenWifi::Types::StringVec & SerialNumbers) { + inline bool FindSerialNumberList(const std::string &Source, + OpenWifi::Types::StringVec &SerialNumbers) { // Can we find our serial number in any of the lists so far... - for(const auto &venue:Venues_) { - auto entry = std::find(venue.second.serialNumbers.begin(),venue.second.serialNumbers.end(),Source); - if(entry!=venue.second.serialNumbers.end() && (Utils::Now()-venue.second.timestamp)<600) { + for (const auto &venue : Venues_) { + auto entry = std::find(venue.second.serialNumbers.begin(), + venue.second.serialNumbers.end(), Source); + if (entry != venue.second.serialNumbers.end() && + (Utils::Now() - venue.second.timestamp) < 600) { SerialNumbers = venue.second.serialNumbers; - auto entry2 = std::find(SerialNumbers.begin(),SerialNumbers.end(),Source); + auto entry2 = std::find(SerialNumbers.begin(), SerialNumbers.end(), Source); SerialNumbers.erase(entry2); return true; } } // get the venue from Prov and the serial numbers. - Types::UUID_t Venue; - Types::StringVec TmpSerialNumbers; - if(OpenWifi::SDK::Prov::GetSerialNumbersForVenueOfSerialNumber(Source,Venue,TmpSerialNumbers,Logger())) { - std::sort(TmpSerialNumbers.begin(),TmpSerialNumbers.end()); - VenueInfo V{.timestamp=Utils::Now(), .serialNumbers=TmpSerialNumbers}; + Types::UUID_t Venue; + Types::StringVec TmpSerialNumbers; + if (OpenWifi::SDK::Prov::GetSerialNumbersForVenueOfSerialNumber( + Source, Venue, TmpSerialNumbers, Logger())) { + std::sort(TmpSerialNumbers.begin(), TmpSerialNumbers.end()); + VenueInfo V{.timestamp = Utils::Now(), .serialNumbers = TmpSerialNumbers}; Venues_[Venue] = V; - auto p = std::find(TmpSerialNumbers.begin(),TmpSerialNumbers.end(),Source); - if(p!=TmpSerialNumbers.end()) { + auto p = std::find(TmpSerialNumbers.begin(), TmpSerialNumbers.end(), Source); + if (p != TmpSerialNumbers.end()) { TmpSerialNumbers.erase(p); SerialNumbers = TmpSerialNumbers; return true; @@ -94,57 +94,58 @@ namespace OpenWifi { return false; } - inline void SendToDevice(const std::string &SerialNumber,const std::string &Payload) { - AP_WS_Server()->SendFrame(SerialNumber,Payload); + inline void SendToDevice(const std::string &SerialNumber, const std::string &Payload) { + AP_WS_Server()->SendFrame(SerialNumber, Payload); } inline void run() final { Running_ = true; Utils::SetThreadName("venue-bcast"); - Poco::AutoPtr NextNotification(BroadcastQueue_.waitDequeueNotification()); + Poco::AutoPtr NextNotification( + BroadcastQueue_.waitDequeueNotification()); while (NextNotification && Running_) { - auto Notification = dynamic_cast(NextNotification.get()); + auto Notification = + dynamic_cast(NextNotification.get()); if (Notification != nullptr) { Types::StringVec SerialNumbers; - if(FindSerialNumberList(Notification->SourceSerialNumber_,SerialNumbers)) { - Poco::JSON::Object Payload; - Payload.set("jsonrpc","2.0"); - Payload.set("method","venue_broadcast"); - Poco::JSON::Object ParamBlock; - ParamBlock.set("serial",Notification->SourceSerialNumber_); - ParamBlock.set("timestamp",Notification->TimeStamp_); - ParamBlock.set("data",Notification->Data_); + if (FindSerialNumberList(Notification->SourceSerialNumber_, SerialNumbers)) { + Poco::JSON::Object Payload; + Payload.set("jsonrpc", "2.0"); + Payload.set("method", "venue_broadcast"); + Poco::JSON::Object ParamBlock; + ParamBlock.set("serial", Notification->SourceSerialNumber_); + ParamBlock.set("timestamp", Notification->TimeStamp_); + ParamBlock.set("data", Notification->Data_); Payload.set("params", ParamBlock); std::ostringstream o; Payload.stringify(o); - for(const auto &Device:SerialNumbers) { - SendToDevice(Device,o.str()); + for (const auto &Device : SerialNumbers) { + SendToDevice(Device, o.str()); } } } NextNotification = BroadcastQueue_.waitDequeueNotification(); } - Running_=false; + Running_ = false; } - inline void Broadcast(const std::string &SourceSerial, const std::string &Data, uint64_t TimeStamp) { - BroadcastQueue_.enqueueNotification(new VenueBroadcastNotification(SourceSerial,Data,TimeStamp)); + inline void Broadcast(const std::string &SourceSerial, const std::string &Data, + uint64_t TimeStamp) { + BroadcastQueue_.enqueueNotification( + new VenueBroadcastNotification(SourceSerial, Data, TimeStamp)); } - private: - std::atomic_bool Running_=false; - bool Enabled_=false; - Poco::NotificationQueue BroadcastQueue_; - Poco::Thread BroadcastManager_; + std::atomic_bool Running_ = false; + bool Enabled_ = false; + Poco::NotificationQueue BroadcastQueue_; + Poco::Thread BroadcastManager_; - std::map Venues_; + std::map Venues_; - VenueBroadcaster() noexcept: - SubSystemServer("VenueBroadcaster", "VENUE-BCAST", "venue.broacast") - { - } + VenueBroadcaster() noexcept + : SubSystemServer("VenueBroadcaster", "VENUE-BCAST", "venue.broacast") {} }; inline auto VenueBroadcaster() { return VenueBroadcaster::instance(); } -} \ No newline at end of file +} // namespace OpenWifi \ No newline at end of file