stephb9959
2023-02-21 13:41:37 -08:00
parent 05158f2c52
commit ac34383dfa
108 changed files with 13401 additions and 13013 deletions

178
.clang-format Normal file
View File

@@ -0,0 +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
...

2
build
View File

@@ -1 +1 @@
5 6

View File

@@ -5,68 +5,76 @@
#include "ConfigMaker.h" #include "ConfigMaker.h"
#include "RESTObjects/RESTAPI_SubObjects.h" #include "RESTObjects/RESTAPI_SubObjects.h"
#include "StorageService.h" #include "StorageService.h"
#include "sdks/SDK_prov.h"
#include "sdks/SDK_gw.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "nlohmann/json.hpp" #include "nlohmann/json.hpp"
#include "sdks/SDK_gw.h"
#include "sdks/SDK_prov.h"
namespace OpenWifi { namespace OpenWifi {
static std::string ConvertBand(const std::string &B) { static std::string ConvertBand(const std::string &B) {
if(B=="2G") return "2G"; if (B == "2G")
if(B=="6G") return "6G"; return "2G";
if(B=="5GU") return "5G-upper"; if (B == "6G")
if(B=="5GL") return "5G-lower"; return "6G";
return B; if (B == "5GU")
} return "5G-upper";
if (B == "5GL")
return "5G-lower";
return B;
}
static std::vector<std::string> ConvertBands(const std::vector<std::string> &Bs) { static std::vector<std::string> ConvertBands(const std::vector<std::string> &Bs) {
std::vector<std::string> R; std::vector<std::string> R;
for(const auto &i:Bs) for (const auto &i : Bs)
R.emplace_back(ConvertBand(i)); R.emplace_back(ConvertBand(i));
return R; return R;
} }
void CreateDHCPInfo( std::string &Subnet, const std::string &First, const std::string &Last, uint64_t & DHCPFirst, uint64_t & HowMany) { void CreateDHCPInfo(std::string &Subnet, const std::string &First, const std::string &Last,
Poco::Net::IPAddress SubnetAddr, FirstAddress, LastAddress; uint64_t &DHCPFirst, uint64_t &HowMany) {
auto Tokens = Poco::StringTokenizer(Subnet,"/"); Poco::Net::IPAddress SubnetAddr, FirstAddress, LastAddress;
if(!Poco::Net::IPAddress::tryParse(Tokens[0],SubnetAddr) || !Poco::Net::IPAddress::tryParse(First,FirstAddress) || !Poco::Net::IPAddress::tryParse(Last,LastAddress)) { auto Tokens = Poco::StringTokenizer(Subnet, "/");
Subnet = "192.168.1.1/24"; if (!Poco::Net::IPAddress::tryParse(Tokens[0], SubnetAddr) ||
DHCPFirst = 10; !Poco::Net::IPAddress::tryParse(First, FirstAddress) ||
HowMany = 100; !Poco::Net::IPAddress::tryParse(Last, LastAddress)) {
return; Subnet = "192.168.1.1/24";
} DHCPFirst = 10;
HowMany = 100;
return;
}
if(LastAddress<FirstAddress) if (LastAddress < FirstAddress)
std::swap(LastAddress,FirstAddress); std::swap(LastAddress, FirstAddress);
struct in_addr FA{*static_cast<const in_addr *>(FirstAddress.addr())}, struct in_addr FA {
LA{*static_cast<const in_addr *>(LastAddress.addr())}; *static_cast<const in_addr *>(FirstAddress.addr())
}, LA{*static_cast<const in_addr *>(LastAddress.addr())};
HowMany = htonl(LA.s_addr) - htonl(FA.s_addr); HowMany = htonl(LA.s_addr) - htonl(FA.s_addr);
auto SubNetBits = std::stoull(Tokens[1],nullptr,10); auto SubNetBits = std::stoull(Tokens[1], nullptr, 10);
uint64_t SubNetBitMask; uint64_t SubNetBitMask;
if(SubNetBits==8) if (SubNetBits == 8)
SubNetBitMask = 0x000000ff ; SubNetBitMask = 0x000000ff;
else if(SubNetBits==16) else if (SubNetBits == 16)
SubNetBitMask = 0x0000ffff ; SubNetBitMask = 0x0000ffff;
else else
SubNetBitMask = 0x000000ff; SubNetBitMask = 0x000000ff;
DHCPFirst = htonl(FA.s_addr) & SubNetBitMask; DHCPFirst = htonl(FA.s_addr) & SubNetBitMask;
} }
// #define __DBG__ std::cout << __LINE__ << std::endl ; // #define __DBG__ std::cout << __LINE__ << std::endl ;
// #define __DBG__ // #define __DBG__
bool ConfigMaker::Prepare() { bool ConfigMaker::Prepare() {
SubObjects::SubscriberInfo SI; SubObjects::SubscriberInfo SI;
if(!StorageService()->SubInfoDB().GetRecord("id", id_, SI)) { if (!StorageService()->SubInfoDB().GetRecord("id", id_, SI)) {
bad_ = true; bad_ = true;
return false; return false;
} }
// We need to create the basic sections // We need to create the basic sections
auto metrics = R"( auto metrics = R"(
{ {
"metrics": { "metrics": {
"dhcp-snooping": { "dhcp-snooping": {
@@ -109,7 +117,7 @@ namespace OpenWifi {
} }
)"_json; )"_json;
auto services = R"( auto services = R"(
{ {
"services": { "services": {
"lldp": { "lldp": {
@@ -124,254 +132,253 @@ namespace OpenWifi {
} }
} )"_json; } )"_json;
for(auto &i:SI.accessPoints.list) { for (auto &i : SI.accessPoints.list) {
nlohmann::json Interfaces; nlohmann::json Interfaces;
nlohmann::json UpstreamInterface; nlohmann::json UpstreamInterface;
nlohmann::json DownstreamInterface; nlohmann::json DownstreamInterface;
nlohmann::json radios; nlohmann::json radios;
if(i.macAddress.empty()) if (i.macAddress.empty())
continue; continue;
Logger_.information(fmt::format("{}: Generating configuration.",i.macAddress)); Logger_.information(fmt::format("{}: Generating configuration.", i.macAddress));
UpstreamInterface["name"] = "WAN"; UpstreamInterface["name"] = "WAN";
UpstreamInterface["role"] = "upstream"; UpstreamInterface["role"] = "upstream";
UpstreamInterface["services"].push_back("lldp"); UpstreamInterface["services"].push_back("lldp");
std::vector<std::string> AllBands; std::vector<std::string> AllBands;
for(const auto &rr:i.radios) for (const auto &rr : i.radios)
AllBands.emplace_back(ConvertBand(rr.band)); AllBands.emplace_back(ConvertBand(rr.band));
nlohmann::json UpstreamPort, DownstreamPort; nlohmann::json UpstreamPort, DownstreamPort;
if(i.internetConnection.type=="manual") { if (i.internetConnection.type == "manual") {
UpstreamInterface["addressing"] = "static"; UpstreamInterface["addressing"] = "static";
UpstreamInterface["subnet"] = i.internetConnection.subnetMask; UpstreamInterface["subnet"] = i.internetConnection.subnetMask;
UpstreamInterface["gateway"] = i.internetConnection.defaultGateway; UpstreamInterface["gateway"] = i.internetConnection.defaultGateway;
UpstreamInterface["send-hostname"] = i.internetConnection.sendHostname; UpstreamInterface["send-hostname"] = i.internetConnection.sendHostname;
UpstreamInterface["use-dns"].push_back(i.internetConnection.primaryDns); UpstreamInterface["use-dns"].push_back(i.internetConnection.primaryDns);
if(!i.internetConnection.secondaryDns.empty()) if (!i.internetConnection.secondaryDns.empty())
UpstreamInterface["use-dns"].push_back(i.internetConnection.secondaryDns); UpstreamInterface["use-dns"].push_back(i.internetConnection.secondaryDns);
} else if(i.internetConnection.type=="pppoe") { } else if (i.internetConnection.type == "pppoe") {
nlohmann::json Port; nlohmann::json Port;
Port["select-ports"].push_back("WAN*"); Port["select-ports"].push_back("WAN*");
UpstreamInterface["ethernet"].push_back(Port); UpstreamInterface["ethernet"].push_back(Port);
UpstreamInterface["broad-band"]["protocol"] = "pppoe"; UpstreamInterface["broad-band"]["protocol"] = "pppoe";
UpstreamInterface["broad-band"]["user-name"] = i.internetConnection.username; UpstreamInterface["broad-band"]["user-name"] = i.internetConnection.username;
UpstreamInterface["broad-band"]["password"] = i.internetConnection.password; UpstreamInterface["broad-band"]["password"] = i.internetConnection.password;
UpstreamInterface["ipv4"]["addressing"] = "dynamic"; UpstreamInterface["ipv4"]["addressing"] = "dynamic";
if(i.internetConnection.ipV6Support) if (i.internetConnection.ipV6Support)
UpstreamInterface["ipv6"]["addressing"] = "dynamic"; UpstreamInterface["ipv6"]["addressing"] = "dynamic";
} else if(i.internetConnection.type=="automatic") { } else if (i.internetConnection.type == "automatic") {
nlohmann::json Port; nlohmann::json Port;
Port["select-ports"].push_back("WAN*"); Port["select-ports"].push_back("WAN*");
if(i.deviceMode.type=="bridge") if (i.deviceMode.type == "bridge")
Port["select-ports"].push_back("LAN*"); Port["select-ports"].push_back("LAN*");
UpstreamInterface["ethernet"].push_back(Port); UpstreamInterface["ethernet"].push_back(Port);
UpstreamInterface["ipv4"]["addressing"] = "dynamic"; UpstreamInterface["ipv4"]["addressing"] = "dynamic";
if(i.internetConnection.ipV6Support) if (i.internetConnection.ipV6Support)
UpstreamInterface["ipv6"]["addressing"] = "dynamic"; UpstreamInterface["ipv6"]["addressing"] = "dynamic";
} }
if(i.deviceMode.type=="bridge") { if (i.deviceMode.type == "bridge") {
UpstreamPort["select-ports"].push_back("LAN*"); UpstreamPort["select-ports"].push_back("LAN*");
UpstreamPort["select-ports"].push_back("WAN*"); UpstreamPort["select-ports"].push_back("WAN*");
} else if(i.deviceMode.type=="manual") { } else if (i.deviceMode.type == "manual") {
UpstreamPort.push_back("WAN*"); UpstreamPort.push_back("WAN*");
DownstreamPort.push_back("LAN*"); DownstreamPort.push_back("LAN*");
DownstreamInterface["name"] = "LAN"; DownstreamInterface["name"] = "LAN";
DownstreamInterface["role"] = "downstream"; DownstreamInterface["role"] = "downstream";
DownstreamInterface["services"].push_back("lldp"); DownstreamInterface["services"].push_back("lldp");
DownstreamInterface["services"].push_back("ssh"); DownstreamInterface["services"].push_back("ssh");
DownstreamInterface["ipv4"]["addressing"] = "static"; DownstreamInterface["ipv4"]["addressing"] = "static";
uint64_t HowMany=0; uint64_t HowMany = 0;
uint64_t FirstIPInRange; uint64_t FirstIPInRange;
CreateDHCPInfo(i.deviceMode.subnet,i.deviceMode.startIP,i.deviceMode.endIP,FirstIPInRange,HowMany); CreateDHCPInfo(i.deviceMode.subnet, i.deviceMode.startIP, i.deviceMode.endIP,
DownstreamInterface["ipv4"]["subnet"] = i.deviceMode.subnet; FirstIPInRange, HowMany);
DownstreamInterface["ipv4"]["dhcp"]["lease-first"] = FirstIPInRange; DownstreamInterface["ipv4"]["subnet"] = i.deviceMode.subnet;
DownstreamInterface["ipv4"]["dhcp"]["lease-count"] = HowMany; DownstreamInterface["ipv4"]["dhcp"]["lease-first"] = FirstIPInRange;
DownstreamInterface["ipv4"]["dhcp"]["lease-time"] = i.deviceMode.leaseTime.empty() ? "24h" : i.deviceMode.leaseTime; DownstreamInterface["ipv4"]["dhcp"]["lease-count"] = HowMany;
} else if(i.deviceMode.type=="nat") { DownstreamInterface["ipv4"]["dhcp"]["lease-time"] =
UpstreamPort["select-ports"].push_back("WAN*"); i.deviceMode.leaseTime.empty() ? "24h" : i.deviceMode.leaseTime;
DownstreamPort["select-ports"].push_back("LAN*"); } else if (i.deviceMode.type == "nat") {
DownstreamInterface["name"] = "LAN"; UpstreamPort["select-ports"].push_back("WAN*");
DownstreamInterface["role"] = "downstream"; DownstreamPort["select-ports"].push_back("LAN*");
DownstreamInterface["services"].push_back("lldp"); DownstreamInterface["name"] = "LAN";
DownstreamInterface["services"].push_back("ssh"); DownstreamInterface["role"] = "downstream";
DownstreamInterface["ipv4"]["addressing"] = "static"; DownstreamInterface["services"].push_back("lldp");
uint64_t HowMany=0; DownstreamInterface["services"].push_back("ssh");
uint64_t FirstIPInRange; DownstreamInterface["ipv4"]["addressing"] = "static";
CreateDHCPInfo(i.deviceMode.subnet,i.deviceMode.startIP,i.deviceMode.endIP,FirstIPInRange,HowMany); uint64_t HowMany = 0;
DownstreamInterface["ipv4"]["subnet"] = i.deviceMode.subnet; uint64_t FirstIPInRange;
DownstreamInterface["ipv4"]["dhcp"]["lease-first"] = FirstIPInRange; CreateDHCPInfo(i.deviceMode.subnet, i.deviceMode.startIP, i.deviceMode.endIP,
DownstreamInterface["ipv4"]["dhcp"]["lease-count"] = HowMany; FirstIPInRange, HowMany);
DownstreamInterface["ipv4"]["dhcp"]["lease-time"] = i.deviceMode.leaseTime.empty() ? "24h" : i.deviceMode.leaseTime; DownstreamInterface["ipv4"]["subnet"] = i.deviceMode.subnet;
} DownstreamInterface["ipv4"]["dhcp"]["lease-first"] = FirstIPInRange;
bool hasGuest=false; DownstreamInterface["ipv4"]["dhcp"]["lease-count"] = HowMany;
nlohmann::json main_ssids, guest_ssids; DownstreamInterface["ipv4"]["dhcp"]["lease-time"] =
for(const auto &j:i.wifiNetworks.wifiNetworks) { i.deviceMode.leaseTime.empty() ? "24h" : i.deviceMode.leaseTime;
nlohmann::json ssid; }
ssid["name"] = j.name ; bool hasGuest = false;
if(j.bands[0]=="all") { nlohmann::json main_ssids, guest_ssids;
ssid["wifi-bands"] = AllBands; for (const auto &j : i.wifiNetworks.wifiNetworks) {
} else { nlohmann::json ssid;
ssid["wifi-bands"] = ConvertBands(j.bands); ssid["name"] = j.name;
} if (j.bands[0] == "all") {
ssid["bss-mode"] = "ap"; ssid["wifi-bands"] = AllBands;
if(j.encryption=="wpa1-personal") { } else {
ssid["encryption"]["proto"] = "psk"; ssid["wifi-bands"] = ConvertBands(j.bands);
ssid["encryption"]["ieee80211w"] = "disabled"; }
} else if(j.encryption=="wpa2-personal") { ssid["bss-mode"] = "ap";
ssid["encryption"]["proto"] = "psk2"; if (j.encryption == "wpa1-personal") {
ssid["encryption"]["ieee80211w"] = "disabled"; ssid["encryption"]["proto"] = "psk";
} else if(j.encryption=="wpa3-personal") { ssid["encryption"]["ieee80211w"] = "disabled";
ssid["encryption"]["proto"] = "sae"; } else if (j.encryption == "wpa2-personal") {
ssid["encryption"]["ieee80211w"] = "required"; ssid["encryption"]["proto"] = "psk2";
} else if (j.encryption=="wpa1/2-personal") { ssid["encryption"]["ieee80211w"] = "disabled";
ssid["encryption"]["proto"] = "psk-mixed"; } else if (j.encryption == "wpa3-personal") {
ssid["encryption"]["ieee80211w"] = "disabled"; ssid["encryption"]["proto"] = "sae";
} else if (j.encryption=="wpa2/3-personal") { ssid["encryption"]["ieee80211w"] = "required";
ssid["encryption"]["proto"] = "sae-mixed"; } else if (j.encryption == "wpa1/2-personal") {
ssid["encryption"]["ieee80211w"] = "disabled"; ssid["encryption"]["proto"] = "psk-mixed";
} ssid["encryption"]["ieee80211w"] = "disabled";
ssid["encryption"]["key"] = j.password; } else if (j.encryption == "wpa2/3-personal") {
if(j.type=="main") { ssid["encryption"]["proto"] = "sae-mixed";
main_ssids.push_back(ssid); ssid["encryption"]["ieee80211w"] = "disabled";
} }
else { ssid["encryption"]["key"] = j.password;
hasGuest = true; if (j.type == "main") {
ssid["isolate-clients"] = true; main_ssids.push_back(ssid);
guest_ssids.push_back(ssid); } else {
} hasGuest = true;
} ssid["isolate-clients"] = true;
guest_ssids.push_back(ssid);
}
}
if(i.deviceMode.type=="bridge") if (i.deviceMode.type == "bridge")
UpstreamInterface["ssids"] = main_ssids; UpstreamInterface["ssids"] = main_ssids;
else else
DownstreamInterface["ssids"] = main_ssids; DownstreamInterface["ssids"] = main_ssids;
nlohmann::json UpStreamEthernet, nlohmann::json UpStreamEthernet, DownStreamEthernet;
DownStreamEthernet; if (!UpstreamPort.empty()) {
if(!UpstreamPort.empty()) { UpStreamEthernet.push_back(UpstreamPort);
UpStreamEthernet.push_back(UpstreamPort); }
} if (!DownstreamPort.empty()) {
if(!DownstreamPort.empty()) { DownStreamEthernet.push_back(DownstreamPort);
DownStreamEthernet.push_back(DownstreamPort); }
}
if(i.deviceMode.type=="bridge") { if (i.deviceMode.type == "bridge") {
UpstreamInterface["ethernet"] = UpStreamEthernet; UpstreamInterface["ethernet"] = UpStreamEthernet;
Interfaces.push_back(UpstreamInterface); Interfaces.push_back(UpstreamInterface);
} else { } else {
UpstreamInterface["ethernet"] = UpStreamEthernet; UpstreamInterface["ethernet"] = UpStreamEthernet;
DownstreamInterface["ethernet"] = DownStreamEthernet; DownstreamInterface["ethernet"] = DownStreamEthernet;
Interfaces.push_back(UpstreamInterface); Interfaces.push_back(UpstreamInterface);
Interfaces.push_back(DownstreamInterface); Interfaces.push_back(DownstreamInterface);
} }
if(hasGuest) { if (hasGuest) {
nlohmann::json GuestInterface; nlohmann::json GuestInterface;
GuestInterface["name"] = "Guest"; GuestInterface["name"] = "Guest";
GuestInterface["role"] = "downstream"; GuestInterface["role"] = "downstream";
GuestInterface["isolate-hosts"] = true; GuestInterface["isolate-hosts"] = true;
GuestInterface["ipv4"]["addressing"] = "static"; GuestInterface["ipv4"]["addressing"] = "static";
GuestInterface["ipv4"]["subnet"] = "192.168.10.1/24"; GuestInterface["ipv4"]["subnet"] = "192.168.10.1/24";
GuestInterface["ipv4"]["dhcp"]["lease-first"] = (uint64_t )10; GuestInterface["ipv4"]["dhcp"]["lease-first"] = (uint64_t)10;
GuestInterface["ipv4"]["dhcp"]["lease-count"] = (uint64_t )100; GuestInterface["ipv4"]["dhcp"]["lease-count"] = (uint64_t)100;
GuestInterface["ipv4"]["dhcp"]["lease-time"] = "6h"; GuestInterface["ipv4"]["dhcp"]["lease-time"] = "6h";
GuestInterface["ssids"] = guest_ssids; GuestInterface["ssids"] = guest_ssids;
Interfaces.push_back(GuestInterface); Interfaces.push_back(GuestInterface);
} }
for(const auto &k:i.radios) { for (const auto &k : i.radios) {
nlohmann::json radio; nlohmann::json radio;
radio["band"] = ConvertBand(k.band); radio["band"] = ConvertBand(k.band);
radio["bandwidth"] = k.bandwidth; radio["bandwidth"] = k.bandwidth;
if(k.channel==0) if (k.channel == 0)
radio["channel"] = "auto"; radio["channel"] = "auto";
else else
radio["channel"] = k.channel; radio["channel"] = k.channel;
if(k.country.size()==2) if (k.country.size() == 2)
radio["country"] = k.country; radio["country"] = k.country;
radio["channel-mode"] = k.channelMode; radio["channel-mode"] = k.channelMode;
radio["channel-width"] = k.channelWidth; radio["channel-width"] = k.channelWidth;
if(!k.requireMode.empty()) if (!k.requireMode.empty())
radio["require-mode"] = k.requireMode; radio["require-mode"] = k.requireMode;
if(k.txpower>0) if (k.txpower > 0)
radio["tx-power"] = k.txpower; radio["tx-power"] = k.txpower;
if(k.allowDFS) if (k.allowDFS)
radio["allow-dfs"] = true; radio["allow-dfs"] = true;
if(!k.mimo.empty()) if (!k.mimo.empty())
radio["mimo"] = k.mimo; radio["mimo"] = k.mimo;
radio["legacy-rates"] = k.legacyRates; radio["legacy-rates"] = k.legacyRates;
radio["beacon-interval"] = k.beaconInterval; radio["beacon-interval"] = k.beaconInterval;
radio["dtim-period"] = k.dtimPeriod; radio["dtim-period"] = k.dtimPeriod;
radio["maximum-clients"] = k.maximumClients; radio["maximum-clients"] = k.maximumClients;
radio["rates"]["beacon"] = k.rates.beacon; radio["rates"]["beacon"] = k.rates.beacon;
radio["rates"]["multicast"] = k.rates.multicast; radio["rates"]["multicast"] = k.rates.multicast;
radio["he-settings"]["multiple-bssid"] = k.he.multipleBSSID; radio["he-settings"]["multiple-bssid"] = k.he.multipleBSSID;
radio["he-settings"]["ema"] = k.he.ema; radio["he-settings"]["ema"] = k.he.ema;
radio["he-settings"]["bss-color"] = k.he.bssColor; radio["he-settings"]["bss-color"] = k.he.bssColor;
radios.push_back(radio); radios.push_back(radio);
} }
ProvObjects::DeviceConfigurationElement Metrics{ ProvObjects::DeviceConfigurationElement Metrics{.name = "metrics",
.name = "metrics", .description = "default metrics",
.description = "default metrics", .weight = 0,
.weight = 0, .configuration = to_string(metrics)};
.configuration = to_string(metrics)
};
ProvObjects::DeviceConfigurationElement Services{ ProvObjects::DeviceConfigurationElement Services{.name = "services",
.name = "services", .description = "default services",
.description = "default services", .weight = 0,
.weight = 0, .configuration = to_string(services)};
.configuration = to_string(services)
};
nlohmann::json InterfaceSection; nlohmann::json InterfaceSection;
InterfaceSection["interfaces"] = Interfaces; InterfaceSection["interfaces"] = Interfaces;
ProvObjects::DeviceConfigurationElement InterfacesList{ ProvObjects::DeviceConfigurationElement InterfacesList{
.name = "interfaces", .name = "interfaces",
.description = "default interfaces", .description = "default interfaces",
.weight = 0, .weight = 0,
.configuration = to_string(InterfaceSection) .configuration = to_string(InterfaceSection)};
};
nlohmann::json RadiosSection; nlohmann::json RadiosSection;
RadiosSection["radios"] = radios; RadiosSection["radios"] = radios;
ProvObjects::DeviceConfigurationElement RadiosList{ ProvObjects::DeviceConfigurationElement RadiosList{.name = "radios",
.name = "radios", .description = "default radios",
.description = "default radios", .weight = 0,
.weight = 0, .configuration =
.configuration = to_string(RadiosSection) to_string(RadiosSection)};
};
ProvObjects::SubscriberDevice SubDevice; ProvObjects::SubscriberDevice SubDevice;
if(SDK::Prov::Subscriber::GetDevice(nullptr,i.serialNumber, SubDevice)) { if (SDK::Prov::Subscriber::GetDevice(nullptr, i.serialNumber, SubDevice)) {
SubDevice.configuration.clear(); SubDevice.configuration.clear();
SubDevice.configuration.push_back(Metrics); SubDevice.configuration.push_back(Metrics);
SubDevice.configuration.push_back(Services); SubDevice.configuration.push_back(Services);
SubDevice.configuration.push_back(InterfacesList); SubDevice.configuration.push_back(InterfacesList);
SubDevice.configuration.push_back(RadiosList); SubDevice.configuration.push_back(RadiosList);
SubDevice.deviceRules.firmwareUpgrade = i.automaticUpgrade ? "yes" : "no"; SubDevice.deviceRules.firmwareUpgrade = i.automaticUpgrade ? "yes" : "no";
if(SDK::Prov::Subscriber::SetDevice(nullptr, SubDevice)) { if (SDK::Prov::Subscriber::SetDevice(nullptr, SubDevice)) {
Logger_.information(fmt::format("Updating configuration for {}", i.serialNumber)); Logger_.information(
} else { fmt::format("Updating configuration for {}", i.serialNumber));
Logger_.information(fmt::format("Cannot update configuration for {}", i.serialNumber)); } else {
} Logger_.information(
} else { fmt::format("Cannot update configuration for {}", i.serialNumber));
Logger_.information(fmt::format("Could not find Subscriber device in provisioning for {}", i.serialNumber)); }
} } else {
SDK::GW::Device::SetSubscriber(nullptr, i.serialNumber, SI.id); Logger_.information(fmt::format(
} "Could not find Subscriber device in provisioning for {}", i.serialNumber));
SI.modified = Utils::Now(); }
return StorageService()->SubInfoDB().UpdateRecord("id",id_,SI); SDK::GW::Device::SetSubscriber(nullptr, i.serialNumber, SI.id);
} }
SI.modified = Utils::Now();
return StorageService()->SubInfoDB().UpdateRecord("id", id_, SI);
}
} } // namespace OpenWifi

View File

@@ -4,21 +4,19 @@
#pragma once #pragma once
#include "RESTObjects/RESTAPI_ProvObjects.h"
#include "Poco/Logger.h" #include "Poco/Logger.h"
#include "RESTObjects/RESTAPI_ProvObjects.h"
namespace OpenWifi { namespace OpenWifi {
class ConfigMaker { class ConfigMaker {
public: public:
explicit ConfigMaker(Poco::Logger &L, const std::string &Id): explicit ConfigMaker(Poco::Logger &L, const std::string &Id) : Logger_(L), id_(Id) {}
Logger_(L), bool Prepare();
id_(Id) { bool Push();
}
bool Prepare(); private:
bool Push(); Poco::Logger &Logger_;
private: const std::string id_;
Poco::Logger &Logger_; bool bad_ = false;
const std::string id_; };
bool bad_=false; } // namespace OpenWifi
};
}

View File

@@ -7,9 +7,9 @@
// //
#include "Daemon.h" #include "Daemon.h"
#include "StatsSvr.h"
#include "StorageService.h" #include "StorageService.h"
#include "SubscriberCache.h" #include "SubscriberCache.h"
#include "StatsSvr.h"
#include "Poco/Net/SSLManager.h" #include "Poco/Net/SSLManager.h"
#include "framework/UI_WebSocketClientServer.h" #include "framework/UI_WebSocketClientServer.h"
@@ -19,49 +19,41 @@ namespace OpenWifi {
class Daemon *Daemon::instance() { class Daemon *Daemon::instance() {
if (instance_ == nullptr) { if (instance_ == nullptr) {
instance_ = new Daemon(vDAEMON_PROPERTIES_FILENAME, instance_ = new Daemon(vDAEMON_PROPERTIES_FILENAME, vDAEMON_ROOT_ENV_VAR,
vDAEMON_ROOT_ENV_VAR, vDAEMON_CONFIG_ENV_VAR, vDAEMON_APP_NAME, vDAEMON_BUS_TIMER,
vDAEMON_CONFIG_ENV_VAR, SubSystemVec{StorageService(), SubscriberCache(), StatsSvr(),
vDAEMON_APP_NAME, UI_WebSocketClientServer()});
vDAEMON_BUS_TIMER,
SubSystemVec{
StorageService(),
SubscriberCache(),
StatsSvr(),
UI_WebSocketClientServer()
});
} }
return instance_; return instance_;
} }
void Daemon::PostInitialization([[maybe_unused]] Poco::Util::Application &self) { void Daemon::PostInitialization([[maybe_unused]] Poco::Util::Application &self) {}
}
void DaemonPostInitialization(Poco::Util::Application &self) { void DaemonPostInitialization(Poco::Util::Application &self) {
Daemon()->PostInitialization(self); Daemon()->PostInitialization(self);
} }
} } // namespace OpenWifi
int main(int argc, char **argv) { int main(int argc, char **argv) {
int ExitCode; int ExitCode;
try { try {
Poco::Net::SSLManager::instance().initializeServer(nullptr, nullptr, nullptr); Poco::Net::SSLManager::instance().initializeServer(nullptr, nullptr, nullptr);
auto App = OpenWifi::Daemon::instance(); auto App = OpenWifi::Daemon::instance();
ExitCode = App->run(argc, argv); ExitCode = App->run(argc, argv);
Poco::Net::SSLManager::instance().shutdown(); Poco::Net::SSLManager::instance().shutdown();
} catch (Poco::Exception &exc) { } catch (Poco::Exception &exc) {
ExitCode = Poco::Util::Application::EXIT_SOFTWARE; ExitCode = Poco::Util::Application::EXIT_SOFTWARE;
std::cout << exc.displayText() << std::endl; std::cout << exc.displayText() << std::endl;
} catch (std::exception &exc) { } catch (std::exception &exc) {
ExitCode = Poco::Util::Application::EXIT_TEMPFAIL; ExitCode = Poco::Util::Application::EXIT_TEMPFAIL;
std::cout << exc.what() << std::endl; std::cout << exc.what() << std::endl;
} catch (...) { } catch (...) {
ExitCode = Poco::Util::Application::EXIT_TEMPFAIL; ExitCode = Poco::Util::Application::EXIT_TEMPFAIL;
std::cout << "Exception on closure" << std::endl; std::cout << "Exception on closure" << std::endl;
} }
std::cout << "Exitcode: " << ExitCode << std::endl; std::cout << "Exitcode: " << ExitCode << std::endl;
return ExitCode; return ExitCode;
} }
// end of namespace // end of namespace

View File

@@ -9,43 +9,40 @@
#pragma once #pragma once
#include <array> #include <array>
#include <iostream>
#include <cstdlib> #include <cstdlib>
#include <vector> #include <iostream>
#include <set> #include <set>
#include <vector>
#include "Dashboard.h"
#include "framework/MicroService.h" #include "framework/MicroService.h"
#include "framework/MicroServiceNames.h" #include "framework/MicroServiceNames.h"
#include "Dashboard.h"
namespace OpenWifi { namespace OpenWifi {
[[maybe_unused]] static const char * vDAEMON_PROPERTIES_FILENAME = "owsub.properties"; [[maybe_unused]] static const char *vDAEMON_PROPERTIES_FILENAME = "owsub.properties";
[[maybe_unused]] static const char * vDAEMON_ROOT_ENV_VAR = "OWSUB_ROOT"; [[maybe_unused]] static const char *vDAEMON_ROOT_ENV_VAR = "OWSUB_ROOT";
[[maybe_unused]] static const char * vDAEMON_CONFIG_ENV_VAR = "OWSUB_CONFIG"; [[maybe_unused]] static const char *vDAEMON_CONFIG_ENV_VAR = "OWSUB_CONFIG";
[[maybe_unused]] static const char * vDAEMON_APP_NAME = uSERVICE_SUBCRIBER.c_str() ; [[maybe_unused]] static const char *vDAEMON_APP_NAME = uSERVICE_SUBCRIBER.c_str();
[[maybe_unused]] static const uint64_t vDAEMON_BUS_TIMER = 10000; [[maybe_unused]] static const uint64_t vDAEMON_BUS_TIMER = 10000;
class Daemon : public MicroService { class Daemon : public MicroService {
public: public:
explicit Daemon(const std::string & PropFile, explicit Daemon(const std::string &PropFile, const std::string &RootEnv,
const std::string & RootEnv, const std::string &ConfigEnv, const std::string &AppName, uint64_t BusTimer,
const std::string & ConfigEnv, const SubSystemVec &SubSystems)
const std::string & AppName, : MicroService(PropFile, RootEnv, ConfigEnv, AppName, BusTimer, SubSystems){};
uint64_t BusTimer,
const SubSystemVec & SubSystems) :
MicroService( PropFile, RootEnv, ConfigEnv, AppName, BusTimer, SubSystems) {};
void PostInitialization(Poco::Util::Application &self); void PostInitialization(Poco::Util::Application &self);
static Daemon *instance(); static Daemon *instance();
inline OpenWifi::SubDashboard & GetDashboard() { return DB_; } inline OpenWifi::SubDashboard &GetDashboard() { return DB_; }
Poco::Logger & Log() { return Poco::Logger::get(AppName()); } Poco::Logger &Log() { return Poco::Logger::get(AppName()); }
private:
static Daemon *instance_;
OpenWifi::SubDashboard DB_{};
}; private:
static Daemon *instance_;
OpenWifi::SubDashboard DB_{};
};
inline Daemon * Daemon() { return Daemon::instance(); } inline Daemon *Daemon() { return Daemon::instance(); }
void DaemonPostInitialization(Poco::Util::Application &self); void DaemonPostInitialization(Poco::Util::Application &self);
} } // namespace OpenWifi

View File

@@ -9,11 +9,11 @@
#include "framework/utils.h" #include "framework/utils.h"
namespace OpenWifi { namespace OpenWifi {
void SubDashboard::Create() { void SubDashboard::Create() {
uint64_t Now = Utils::Now(); uint64_t Now = Utils::Now();
if(LastRun_==0 || (Now-LastRun_)>120) { if (LastRun_ == 0 || (Now - LastRun_) > 120) {
DB_.reset(); DB_.reset();
LastRun_ = Now; LastRun_ = Now;
} }
} }
} } // namespace OpenWifi

View File

@@ -8,19 +8,23 @@
#ifndef UCENTRALGW_DASHBOARD_H #ifndef UCENTRALGW_DASHBOARD_H
#define UCENTRALGW_DASHBOARD_H #define UCENTRALGW_DASHBOARD_H
#include "framework/OpenWifiTypes.h"
#include "RESTObjects/RESTAPI_ProvObjects.h" #include "RESTObjects/RESTAPI_ProvObjects.h"
#include "framework/OpenWifiTypes.h"
namespace OpenWifi { namespace OpenWifi {
class SubDashboard { class SubDashboard {
public: public:
void Create(); void Create();
[[nodiscard]] const ProvObjects::Report & Report() const { return DB_;} [[nodiscard]] const ProvObjects::Report &Report() const { return DB_; }
inline void Reset() { LastRun_=0; DB_.reset(); } inline void Reset() {
LastRun_ = 0;
DB_.reset();
}
private: private:
ProvObjects::Report DB_{}; ProvObjects::Report DB_{};
uint64_t LastRun_=0; uint64_t LastRun_ = 0;
}; };
} } // namespace OpenWifi
#endif // UCENTRALGW_DASHBOARD_H #endif // UCENTRALGW_DASHBOARD_H

View File

@@ -3,66 +3,67 @@
// //
#include "RESTAPI_action_handler.h" #include "RESTAPI_action_handler.h"
#include "SubscriberCache.h"
#include "StorageService.h"
#include "sdks/SDK_gw.h"
#include "ConfigMaker.h" #include "ConfigMaker.h"
#include "StorageService.h"
#include "SubscriberCache.h"
#include "sdks/SDK_gw.h"
namespace OpenWifi { namespace OpenWifi {
void RESTAPI_action_handler::DoPost() { void RESTAPI_action_handler::DoPost() {
auto Command = GetParameter("action",""); auto Command = GetParameter("action", "");
if(Command.empty()) { if (Command.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters); return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
} }
const auto & Body = ParsedBody_; const auto &Body = ParsedBody_;
std::string Mac, ImageName,Pattern{"blink"}; std::string Mac, ImageName, Pattern{"blink"};
AssignIfPresent(Body,"mac",Mac); AssignIfPresent(Body, "mac", Mac);
Poco::toLowerInPlace(Mac); Poco::toLowerInPlace(Mac);
Poco::trimInPlace(Mac); Poco::trimInPlace(Mac);
if(Mac.empty()) { if (Mac.empty()) {
return BadRequest(RESTAPI::Errors::MissingSerialNumber); return BadRequest(RESTAPI::Errors::MissingSerialNumber);
} }
uint64_t When=0, Duration = 30; uint64_t When = 0, Duration = 30;
bool keepRedirector=true; bool keepRedirector = true;
AssignIfPresent(Body, "when",When); AssignIfPresent(Body, "when", When);
AssignIfPresent(Body, "duration", Duration); AssignIfPresent(Body, "duration", Duration);
AssignIfPresent(Body, "uri", ImageName); AssignIfPresent(Body, "uri", ImageName);
AssignIfPresent(Body, "pattern", Pattern); AssignIfPresent(Body, "pattern", Pattern);
AssignIfPresent(Body, "keepRedirector",keepRedirector); AssignIfPresent(Body, "keepRedirector", keepRedirector);
Poco::SharedPtr<SubObjects::SubscriberInfo> SubInfo; Poco::SharedPtr<SubObjects::SubscriberInfo> SubInfo;
auto UserFound = SubscriberCache()->GetSubInfo(UserInfo_.userinfo.id,SubInfo); auto UserFound = SubscriberCache()->GetSubInfo(UserInfo_.userinfo.id, SubInfo);
if(!UserFound) { if (!UserFound) {
SubObjects::SubscriberInfo SI; SubObjects::SubscriberInfo SI;
if(!StorageService()->SubInfoDB().GetRecord("id",UserInfo_.userinfo.id,SI)) if (!StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, SI))
return BadRequest(RESTAPI::Errors::SubNoDeviceActivated); return BadRequest(RESTAPI::Errors::SubNoDeviceActivated);
} }
for(const auto &i:SubInfo->accessPoints.list) { for (const auto &i : SubInfo->accessPoints.list) {
if(i.macAddress == Mac) { if (i.macAddress == Mac) {
if(Command == "reboot") { if (Command == "reboot") {
return SDK::GW::Device::Reboot(this, i.serialNumber, When); return SDK::GW::Device::Reboot(this, i.serialNumber, When);
} else if(Command == "blink") { } else if (Command == "blink") {
return SDK::GW::Device::LEDs(this, i.serialNumber, When, Duration, Pattern); return SDK::GW::Device::LEDs(this, i.serialNumber, When, Duration, Pattern);
} else if(Command == "upgrade") { } else if (Command == "upgrade") {
return SDK::GW::Device::Upgrade(this, i.serialNumber, When, i.latestFirmwareURI, keepRedirector); return SDK::GW::Device::Upgrade(this, i.serialNumber, When, i.latestFirmwareURI,
} else if(Command == "factory") { keepRedirector);
return SDK::GW::Device::Factory(this, i.serialNumber, When, keepRedirector); } else if (Command == "factory") {
} else if(Command == "refresh") { return SDK::GW::Device::Factory(this, i.serialNumber, When, keepRedirector);
ConfigMaker InitialConfig(Logger(),UserInfo_.userinfo.id); } else if (Command == "refresh") {
if(InitialConfig.Prepare()) ConfigMaker InitialConfig(Logger(), UserInfo_.userinfo.id);
return OK(); if (InitialConfig.Prepare())
else return OK();
return InternalError(RESTAPI::Errors::SubConfigNotRefreshed); else
} else { return InternalError(RESTAPI::Errors::SubConfigNotRefreshed);
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters); } else {
} return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
} }
} }
return NotFound(); }
} return NotFound();
} }
} // namespace OpenWifi

View File

@@ -7,32 +7,31 @@
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_action_handler : public RESTAPIHandler { class RESTAPI_action_handler : public RESTAPIHandler {
public: public:
RESTAPI_action_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) RESTAPI_action_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
: RESTAPIHandler(bindings, L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
std::vector<std::string>{ bool Internal)
Poco::Net::HTTPRequest::HTTP_POST, : RESTAPIHandler(bindings, L,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST,
Server, Poco::Net::HTTPRequest::HTTP_OPTIONS},
TransactionId, Server, TransactionId, Internal, true, false, RateLimit{}, true) {}
Internal,true, false, RateLimit{}, true){}
static auto PathName() { return std::list<std::string>{"/api/v1/action"}; }; static auto PathName() { return std::list<std::string>{"/api/v1/action"}; };
inline bool RoleIsAuthorized(std::string & Reason) { inline bool RoleIsAuthorized(std::string &Reason) {
if(UserInfo_.userinfo.userRole != SecurityObjects::USER_ROLE::SUBSCRIBER) { if (UserInfo_.userinfo.userRole != SecurityObjects::USER_ROLE::SUBSCRIBER) {
Reason = "User must be a subscriber"; Reason = "User must be a subscriber";
return false; return false;
} }
return true; return true;
} }
void DoGet() final {}; void DoGet() final{};
void DoPost() final; void DoPost() final;
void DoPut() final {}; void DoPut() final{};
void DoDelete() final {}; void DoDelete() final{};
private:
}; private:
} };
} // namespace OpenWifi

View File

@@ -8,33 +8,32 @@
namespace OpenWifi { namespace OpenWifi {
void RESTAPI_claim_handler::DoPut() { void RESTAPI_claim_handler::DoPut() {
std::string SerialNumber, Id; std::string SerialNumber, Id;
if(!HasParameter("serialNumber",SerialNumber) || !HasParameter("id",Id)) { if (!HasParameter("serialNumber", SerialNumber) || !HasParameter("id", Id)) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters); return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
} }
if(!Utils::ValidSerialNumber(SerialNumber)) { if (!Utils::ValidSerialNumber(SerialNumber)) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters); return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
} }
std::string EndPoint{"/api/v1/inventory"}; std::string EndPoint{"/api/v1/inventory"};
Poco::JSON::Object Body; Poco::JSON::Object Body;
OpenAPIRequestPut API(uSERVICE_PROVISIONING, EndPoint, OpenAPIRequestPut API(uSERVICE_PROVISIONING, EndPoint,
{ { "serialNumber" , SerialNumber }, {{"serialNumber", SerialNumber}, {"claimer", UserInfo_.userinfo.id}},
{ "claimer" , UserInfo_.userinfo.id }}, Body, 20000);
Body, 20000);
Poco::JSON::Object::Ptr CallResponse; Poco::JSON::Object::Ptr CallResponse;
auto StatusCode = API.Do(CallResponse, UserInfo_.userinfo.id); auto StatusCode = API.Do(CallResponse, UserInfo_.userinfo.id);
if(StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) { if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) {
return ReturnObject(*CallResponse); return ReturnObject(*CallResponse);
} else { } else {
return ReturnStatus(StatusCode); return ReturnStatus(StatusCode);
} }
} }
} } // namespace OpenWifi

View File

@@ -7,24 +7,24 @@
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_claim_handler : public RESTAPIHandler { class RESTAPI_claim_handler : public RESTAPIHandler {
public: public:
RESTAPI_claim_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) RESTAPI_claim_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
: RESTAPIHandler(bindings, L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
std::vector<std::string>{ bool Internal)
Poco::Net::HTTPRequest::HTTP_GET, : RESTAPIHandler(bindings, L,
Poco::Net::HTTPRequest::HTTP_PUT, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, Poco::Net::HTTPRequest::HTTP_PUT,
Server, Poco::Net::HTTPRequest::HTTP_OPTIONS},
TransactionId, Server, TransactionId, Internal) {}
Internal){}
static auto PathName() { return std::list<std::string>{"/api/v1/claim"}; }; static auto PathName() { return std::list<std::string>{"/api/v1/claim"}; };
void DoGet() final {}; void DoGet() final{};
void DoPost() final {}; void DoPost() final{};
void DoPut() final; void DoPut() final;
void DoDelete() final {}; void DoDelete() final{};
private:
}; private:
} };
} // namespace OpenWifi

View File

@@ -8,12 +8,14 @@
namespace OpenWifi { namespace OpenWifi {
void RESTAPI_mfa_handler::DoPut() { void RESTAPI_mfa_handler::DoPut() {
API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),"/api/v1/submfa"); API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),
} "/api/v1/submfa");
}
void RESTAPI_mfa_handler::DoGet() { void RESTAPI_mfa_handler::DoGet() {
API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),"/api/v1/submfa"); API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),
} "/api/v1/submfa");
}
} } // namespace OpenWifi

View File

@@ -6,24 +6,25 @@
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_mfa_handler : public RESTAPIHandler { class RESTAPI_mfa_handler : public RESTAPIHandler {
public: public:
RESTAPI_mfa_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) RESTAPI_mfa_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
: RESTAPIHandler(bindings, L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
std::vector<std::string>{ bool Internal)
Poco::Net::HTTPRequest::HTTP_GET, : RESTAPIHandler(bindings, L,
Poco::Net::HTTPRequest::HTTP_PUT, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, Poco::Net::HTTPRequest::HTTP_PUT,
Server, Poco::Net::HTTPRequest::HTTP_OPTIONS},
TransactionId, Server, TransactionId, Internal, true, false,
Internal, true, false, RateLimit{.Interval=1000,.MaxCalls=10}, true){} RateLimit{.Interval = 1000, .MaxCalls = 10}, true) {}
static auto PathName() { return std::list<std::string>{"/api/v1/submfa"}; }; static auto PathName() { return std::list<std::string>{"/api/v1/submfa"}; };
void DoGet() final; void DoGet() final;
void DoPost() final {}; void DoPost() final{};
void DoPut() final; void DoPut() final;
void DoDelete() final {}; void DoDelete() final{};
private:
}; private:
} };
} // namespace OpenWifi

View File

@@ -3,21 +3,24 @@
// //
#include "RESTAPI_oauth2_handler.h" #include "RESTAPI_oauth2_handler.h"
#include "framework/MicroServiceNames.h"
#include "framework/API_Proxy.h" #include "framework/API_Proxy.h"
#include "framework/MicroServiceNames.h"
namespace OpenWifi { namespace OpenWifi {
void RESTAPI_oauth2_handler::DoPost() { void RESTAPI_oauth2_handler::DoPost() {
API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),"/api/v1/suboauth2"); API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),
} "/api/v1/suboauth2");
}
void RESTAPI_oauth2_handler::DoGet() { void RESTAPI_oauth2_handler::DoGet() {
API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),"/api/v1/suboauth2"); API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),
} "/api/v1/suboauth2");
}
void RESTAPI_oauth2_handler::DoDelete() { void RESTAPI_oauth2_handler::DoDelete() {
API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),"/api/v1/suboauth2"); API_Proxy(Logger_, Request, Response, OpenWifi::uSERVICE_SECURITY.c_str(),
} "/api/v1/suboauth2");
}
} } // namespace OpenWifi

View File

@@ -7,26 +7,27 @@
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_oauth2_handler : public RESTAPIHandler { class RESTAPI_oauth2_handler : public RESTAPIHandler {
public: public:
RESTAPI_oauth2_handler(const RESTAPIHandler::BindingMap &bindings, RESTAPI_oauth2_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
Poco::Logger &L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) bool Internal)
: RESTAPIHandler(bindings, L, : RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_DELETE, Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, Server, TransactionId, Internal, false, true,
TransactionId, RateLimit{.Interval = 1000, .MaxCalls = 10}) {}
Internal, false, true , RateLimit{.Interval=1000,.MaxCalls=10}) {} static auto PathName() {
static auto PathName() { return std::list<std::string>{"/api/v1/oauth2/{token}","/api/v1/oauth2"}; }; return std::list<std::string>{"/api/v1/oauth2/{token}", "/api/v1/oauth2"};
};
void DoGet() final; void DoGet() final;
void DoPost() final; void DoPost() final;
void DoPut() final {}; void DoPut() final{};
void DoDelete() final; void DoDelete() final;
private:
};
}
private:
};
} // namespace OpenWifi

View File

@@ -2,53 +2,38 @@
// Created by stephane bourque on 2021-10-23. // Created by stephane bourque on 2021-10-23.
// //
#include "RESTAPI/RESTAPI_wifiClients_handler.h"
#include "RESTAPI//RESTAPI_wiredClients_handler.h" #include "RESTAPI//RESTAPI_wiredClients_handler.h"
#include "RESTAPI/RESTAPI_subscriber_handler.h"
#include "RESTAPI/RESTAPI_oauth2_handler.h"
#include "RESTAPI/RESTAPI_action_handler.h" #include "RESTAPI/RESTAPI_action_handler.h"
#include "RESTAPI/RESTAPI_mfa_handler.h"
#include "RESTAPI/RESTAPI_claim_handler.h" #include "RESTAPI/RESTAPI_claim_handler.h"
#include "RESTAPI/RESTAPI_mfa_handler.h"
#include "RESTAPI/RESTAPI_oauth2_handler.h"
#include "RESTAPI/RESTAPI_signup_handler.h" #include "RESTAPI/RESTAPI_signup_handler.h"
#include "RESTAPI/RESTAPI_stats_handler.h" #include "RESTAPI/RESTAPI_stats_handler.h"
#include "RESTAPI/RESTAPI_subscriber_handler.h"
#include "RESTAPI/RESTAPI_wifiClients_handler.h"
#include "framework/RESTAPI_SystemCommand.h" #include "framework/RESTAPI_SystemCommand.h"
#include "framework/RESTAPI_WebSocketServer.h" #include "framework/RESTAPI_WebSocketServer.h"
namespace OpenWifi { namespace OpenWifi {
Poco::Net::HTTPRequestHandler * RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings, Poco::Net::HTTPRequestHandler *
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
uint64_t TransactionId) { Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t TransactionId) {
return RESTAPI_Router< return RESTAPI_Router<RESTAPI_wifiClients_handler, RESTAPI_wiredClients_handler,
RESTAPI_wifiClients_handler, RESTAPI_subscriber_handler, RESTAPI_oauth2_handler,
RESTAPI_wiredClients_handler, RESTAPI_action_handler, RESTAPI_mfa_handler, RESTAPI_claim_handler,
RESTAPI_subscriber_handler, RESTAPI_signup_handler, RESTAPI_system_command, RESTAPI_stats_handler,
RESTAPI_oauth2_handler, RESTAPI_webSocketServer>(Path, Bindings, L, S, TransactionId);
RESTAPI_action_handler, }
RESTAPI_mfa_handler,
RESTAPI_claim_handler,
RESTAPI_signup_handler,
RESTAPI_system_command,
RESTAPI_stats_handler,
RESTAPI_webSocketServer
>(Path, Bindings, L, S, TransactionId);
}
Poco::Net::HTTPRequestHandler * RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings, Poco::Net::HTTPRequestHandler *
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
uint64_t TransactionId) { Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t TransactionId) {
return RESTAPI_Router_I< return RESTAPI_Router_I<RESTAPI_wifiClients_handler, RESTAPI_wiredClients_handler,
RESTAPI_wifiClients_handler, RESTAPI_subscriber_handler, RESTAPI_oauth2_handler,
RESTAPI_wiredClients_handler, RESTAPI_action_handler, RESTAPI_mfa_handler, RESTAPI_claim_handler,
RESTAPI_subscriber_handler, RESTAPI_signup_handler, RESTAPI_system_command,
RESTAPI_oauth2_handler, RESTAPI_stats_handler>(Path, Bindings, L, S, TransactionId);
RESTAPI_action_handler, }
RESTAPI_mfa_handler,
RESTAPI_claim_handler,
RESTAPI_signup_handler,
RESTAPI_system_command,
RESTAPI_stats_handler
>(Path, Bindings, L, S, TransactionId);
}
} } // namespace OpenWifi

View File

@@ -8,45 +8,49 @@
namespace OpenWifi { namespace OpenWifi {
void RESTAPI_signup_handler::DoPost() { void RESTAPI_signup_handler::DoPost() {
// do dome basic checking before we send this over. // do dome basic checking before we send this over.
auto UserName = GetParameter("email"); auto UserName = GetParameter("email");
Poco::toLowerInPlace(UserName); Poco::toLowerInPlace(UserName);
Poco::trimInPlace(UserName); Poco::trimInPlace(UserName);
auto SerialNumber = GetParameter("macAddress"); auto SerialNumber = GetParameter("macAddress");
Poco::toLowerInPlace(SerialNumber); Poco::toLowerInPlace(SerialNumber);
Poco::trimInPlace(SerialNumber); Poco::trimInPlace(SerialNumber);
auto registrationId = GetParameter("registrationId"); auto registrationId = GetParameter("registrationId");
Poco::toLowerInPlace(registrationId); Poco::toLowerInPlace(registrationId);
Poco::trimInPlace(registrationId); Poco::trimInPlace(registrationId);
if(!Utils::ValidSerialNumber(SerialNumber)) { if (!Utils::ValidSerialNumber(SerialNumber)) {
return BadRequest(RESTAPI::Errors::InvalidSerialNumber); return BadRequest(RESTAPI::Errors::InvalidSerialNumber);
} }
if(!Utils::ValidEMailAddress(UserName)) { if (!Utils::ValidEMailAddress(UserName)) {
return BadRequest(RESTAPI::Errors::InvalidEmailAddress); return BadRequest(RESTAPI::Errors::InvalidEmailAddress);
} }
if(registrationId.empty()) { if (registrationId.empty()) {
return BadRequest(RESTAPI::Errors::InvalidRegistrationOperatorName); return BadRequest(RESTAPI::Errors::InvalidRegistrationOperatorName);
} }
return API_Proxy(Logger(), Request, Response, uSERVICE_PROVISIONING.c_str(), "/api/v1/signup", 60000); return API_Proxy(Logger(), Request, Response, uSERVICE_PROVISIONING.c_str(),
} "/api/v1/signup", 60000);
}
void RESTAPI_signup_handler::DoPut() { void RESTAPI_signup_handler::DoPut() {
return API_Proxy(Logger(), Request, Response, uSERVICE_PROVISIONING.c_str(), "/api/v1/signup", 60000); return API_Proxy(Logger(), Request, Response, uSERVICE_PROVISIONING.c_str(),
} "/api/v1/signup", 60000);
}
void RESTAPI_signup_handler::DoGet() { void RESTAPI_signup_handler::DoGet() {
return API_Proxy(Logger(), Request, Response, uSERVICE_PROVISIONING.c_str(), "/api/v1/signup", 60000); return API_Proxy(Logger(), Request, Response, uSERVICE_PROVISIONING.c_str(),
} "/api/v1/signup", 60000);
}
void RESTAPI_signup_handler::DoDelete() { void RESTAPI_signup_handler::DoDelete() {
return API_Proxy(Logger(), Request, Response, uSERVICE_PROVISIONING.c_str(), "/api/v1/signup", 60000); return API_Proxy(Logger(), Request, Response, uSERVICE_PROVISIONING.c_str(),
} "/api/v1/signup", 60000);
}
} } // namespace OpenWifi

View File

@@ -7,38 +7,34 @@
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_signup_handler : public RESTAPIHandler { class RESTAPI_signup_handler : public RESTAPIHandler {
public: public:
RESTAPI_signup_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) RESTAPI_signup_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
: RESTAPIHandler(bindings, L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
std::vector<std::string>{ bool Internal)
Poco::Net::HTTPRequest::HTTP_POST, : RESTAPIHandler(bindings, L,
Poco::Net::HTTPRequest::HTTP_OPTIONS, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_PUT, Poco::Net::HTTPRequest::HTTP_OPTIONS,
Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_DELETE Poco::Net::HTTPRequest::HTTP_GET,
}, Poco::Net::HTTPRequest::HTTP_DELETE},
Server, Server, TransactionId, Internal, false, true) {}
TransactionId,
Internal, false, true ) {
} static auto PathName() { return std::list<std::string>{"/api/v1/signup"}; };
static auto PathName() { return std::list<std::string>{"/api/v1/signup"}; }; /* inline bool RoleIsAuthorized(std::string & Reason) {
if(UserInfo_.userinfo.userRole != SecurityObjects::USER_ROLE::SUBSCRIBER) {
Reason = "User must be a subscriber";
return false;
}
return true;
}
*/
void DoGet() final;
void DoPost() final;
void DoPut() final;
void DoDelete() final;
/* inline bool RoleIsAuthorized(std::string & Reason) { private:
if(UserInfo_.userinfo.userRole != SecurityObjects::USER_ROLE::SUBSCRIBER) { };
Reason = "User must be a subscriber"; } // namespace OpenWifi
return false;
}
return true;
}
*/
void DoGet() final;
void DoPost() final;
void DoPut() final ;
void DoDelete() final;
private:
};
}

View File

@@ -4,31 +4,31 @@
#include "RESTAPI_stats_handler.h" #include "RESTAPI_stats_handler.h"
#include "RESTObjects/RESTAPI_SubObjects.h" #include "RESTObjects/RESTAPI_SubObjects.h"
#include "StorageService.h"
#include "StatsSvr.h" #include "StatsSvr.h"
#include "StorageService.h"
namespace OpenWifi { namespace OpenWifi {
void RESTAPI_stats_handler::DoGet() { void RESTAPI_stats_handler::DoGet() {
auto MAC = GetBinding("mac",""); auto MAC = GetBinding("mac", "");
if(MAC.empty() || !Utils::ValidSerialNumber(MAC)) { if (MAC.empty() || !Utils::ValidSerialNumber(MAC)) {
return BadRequest(RESTAPI::Errors::InvalidSerialNumber); return BadRequest(RESTAPI::Errors::InvalidSerialNumber);
} }
SubObjects::SubscriberInfo SI; SubObjects::SubscriberInfo SI;
if(!StorageService()->SubInfoDB().GetRecord("id",UserInfo_.userinfo.id,SI)) { if (!StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, SI)) {
return NotFound(); return NotFound();
} }
SubObjects::StatsBlock SB; SubObjects::StatsBlock SB;
for(const auto &device:SI.accessPoints.list) { for (const auto &device : SI.accessPoints.list) {
if(device.macAddress==MAC) { if (device.macAddress == MAC) {
StatsSvr()->Get(device.serialNumber,SB); StatsSvr()->Get(device.serialNumber, SB);
break; break;
} }
} }
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
SB.to_json(Answer); SB.to_json(Answer);
return ReturnObject(Answer); return ReturnObject(Answer);
} }
} } // namespace OpenWifi

View File

@@ -11,23 +11,23 @@
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_stats_handler : public RESTAPIHandler { class RESTAPI_stats_handler : public RESTAPIHandler {
public: public:
RESTAPI_stats_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) RESTAPI_stats_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
: RESTAPIHandler(bindings, L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
std::vector<std::string>{ bool Internal)
Poco::Net::HTTPRequest::HTTP_GET, : RESTAPIHandler(bindings, L,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Server, Poco::Net::HTTPRequest::HTTP_OPTIONS},
TransactionId, Server, TransactionId, Internal, true, false,
Internal, true, false, RateLimit{.Interval=1000,.MaxCalls=10}, true){} RateLimit{.Interval = 1000, .MaxCalls = 10}, true) {}
static auto PathName() { return std::list<std::string>{"/api/v1/stats/{mac}"}; }; static auto PathName() { return std::list<std::string>{"/api/v1/stats/{mac}"}; };
private: private:
void DoGet() final; void DoGet() final;
void DoPost() final {}; void DoPost() final{};
void DoPut() final {}; void DoPut() final{};
void DoDelete() final {}; void DoDelete() final{};
}; };
} } // namespace OpenWifi

View File

@@ -3,331 +3,348 @@
// //
#include "RESTAPI_subscriber_handler.h" #include "RESTAPI_subscriber_handler.h"
#include "StorageService.h"
#include "RESTObjects/RESTAPI_SubObjects.h"
#include "SubscriberCache.h"
#include "sdks/SDK_prov.h"
#include "sdks/SDK_gw.h"
#include "sdks/SDK_fms.h"
#include "sdks/SDK_sec.h"
#include "ConfigMaker.h" #include "ConfigMaker.h"
#include "nlohmann/json.hpp" #include "RESTObjects/RESTAPI_SubObjects.h"
#include "StorageService.h"
#include "SubscriberCache.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "nlohmann/json.hpp"
#include "sdks/SDK_fms.h"
#include "sdks/SDK_gw.h"
#include "sdks/SDK_prov.h"
#include "sdks/SDK_sec.h"
namespace OpenWifi { namespace OpenWifi {
template <typename T> void AssignIfModified(T & Var, const T & Value, int &Mods) { template <typename T> void AssignIfModified(T &Var, const T &Value, int &Mods) {
if(Var!=Value) { if (Var != Value) {
Var = Value; Var = Value;
Mods++; Mods++;
} }
} }
void RESTAPI_subscriber_handler::DoGet() { void RESTAPI_subscriber_handler::DoGet() {
if(UserInfo_.userinfo.id.empty()) { if (UserInfo_.userinfo.id.empty()) {
return NotFound(); return NotFound();
} }
Logger().information(fmt::format("{}: Get basic info.", UserInfo_.userinfo.email)); Logger().information(fmt::format("{}: Get basic info.", UserInfo_.userinfo.email));
SubObjects::SubscriberInfo SI; SubObjects::SubscriberInfo SI;
if(StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id,SI)) { if (StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, SI)) {
int Mods=0; int Mods = 0;
// we need to get the stats for each AP // we need to get the stats for each AP
for(auto &i:SI.accessPoints.list) { for (auto &i : SI.accessPoints.list) {
if(i.macAddress.empty()) if (i.macAddress.empty())
continue; continue;
Poco::JSON::Object::Ptr LastStats; Poco::JSON::Object::Ptr LastStats;
if(SDK::GW::Device::GetLastStats(nullptr,i.serialNumber,LastStats)) { if (SDK::GW::Device::GetLastStats(nullptr, i.serialNumber, LastStats)) {
std::ostringstream OS; std::ostringstream OS;
LastStats->stringify(OS); LastStats->stringify(OS);
try { try {
nlohmann::json LA = nlohmann::json::parse(OS.str()); nlohmann::json LA = nlohmann::json::parse(OS.str());
for (const auto &j: LA["interfaces"]) { for (const auto &j : LA["interfaces"]) {
if (j.contains("location") && j["location"].get<std::string>()=="/interfaces/0" && j.contains("ipv4")) { if (j.contains("location") &&
j["location"].get<std::string>() == "/interfaces/0" &&
j.contains("ipv4")) {
if( j["ipv4"]["addresses"].is_array() if (j["ipv4"]["addresses"].is_array() &&
&& !j["ipv4"]["addresses"].empty() ) { !j["ipv4"]["addresses"].empty()) {
auto IPParts = Poco::StringTokenizer(j["ipv4"]["addresses"][0].get<std::string>(), "/"); auto IPParts = Poco::StringTokenizer(
AssignIfModified(i.internetConnection.ipAddress,IPParts[0],Mods); j["ipv4"]["addresses"][0].get<std::string>(), "/");
i.internetConnection.subnetMask = IPParts[1]; AssignIfModified(i.internetConnection.ipAddress, IPParts[0],
} Mods);
if (j["ipv4"].contains("dhcp_server")) i.internetConnection.subnetMask = IPParts[1];
AssignIfModified(i.internetConnection.defaultGateway,j["ipv4"]["dhcp_server"].get<std::string>(),Mods); }
else if (j["ipv4"].contains("dhcp_server"))
AssignIfModified(i.internetConnection.defaultGateway,std::string{"---"},Mods); AssignIfModified(i.internetConnection.defaultGateway,
j["ipv4"]["dhcp_server"].get<std::string>(),
Mods);
else
AssignIfModified(i.internetConnection.defaultGateway,
std::string{"---"}, Mods);
if (j.contains("dns_servers") && j["dns_servers"].is_array()) { if (j.contains("dns_servers") && j["dns_servers"].is_array()) {
auto dns = j["dns_servers"]; auto dns = j["dns_servers"];
if (!dns.empty()) if (!dns.empty())
AssignIfModified(i.internetConnection.primaryDns,dns[0].get<std::string>(),Mods); AssignIfModified(i.internetConnection.primaryDns,
else dns[0].get<std::string>(), Mods);
AssignIfModified(i.internetConnection.primaryDns,std::string{"---"},Mods); else
if (dns.size() > 1) AssignIfModified(i.internetConnection.primaryDns,
AssignIfModified(i.internetConnection.secondaryDns, dns[1].get<std::string>(),Mods); std::string{"---"}, Mods);
else if (dns.size() > 1)
AssignIfModified(i.internetConnection.secondaryDns, std::string{"---"},Mods); AssignIfModified(i.internetConnection.secondaryDns,
} dns[1].get<std::string>(), Mods);
} else
} AssignIfModified(i.internetConnection.secondaryDns,
} catch(...) { std::string{"---"}, Mods);
AssignIfModified(i.internetConnection.ipAddress, std::string{"--"}, Mods); }
i.internetConnection.subnetMask = "--"; }
i.internetConnection.defaultGateway = "--"; }
i.internetConnection.primaryDns = "--"; } catch (...) {
i.internetConnection.secondaryDns = "--"; AssignIfModified(i.internetConnection.ipAddress, std::string{"--"}, Mods);
} i.internetConnection.subnetMask = "--";
} else { i.internetConnection.defaultGateway = "--";
AssignIfModified(i.internetConnection.ipAddress, std::string{"-"}, Mods); i.internetConnection.primaryDns = "--";
i.internetConnection.subnetMask = "-"; i.internetConnection.secondaryDns = "--";
i.internetConnection.defaultGateway = "-"; }
i.internetConnection.primaryDns = "-"; } else {
i.internetConnection.secondaryDns = "-"; AssignIfModified(i.internetConnection.ipAddress, std::string{"-"}, Mods);
} i.internetConnection.subnetMask = "-";
i.internetConnection.defaultGateway = "-";
i.internetConnection.primaryDns = "-";
i.internetConnection.secondaryDns = "-";
}
FMSObjects::DeviceInformation DI; FMSObjects::DeviceInformation DI;
if(SDK::FMS::Firmware::GetDeviceInformation(nullptr,i.serialNumber,DI)) { if (SDK::FMS::Firmware::GetDeviceInformation(nullptr, i.serialNumber, DI)) {
AssignIfModified(i.currentFirmwareDate, DI.currentFirmwareDate, Mods); AssignIfModified(i.currentFirmwareDate, DI.currentFirmwareDate, Mods);
AssignIfModified(i.currentFirmware, DI.currentFirmware, Mods); AssignIfModified(i.currentFirmware, DI.currentFirmware, Mods);
AssignIfModified(i.latestFirmwareDate, DI.latestFirmwareDate, Mods); AssignIfModified(i.latestFirmwareDate, DI.latestFirmwareDate, Mods);
AssignIfModified(i.latestFirmware, DI.latestFirmware, Mods); AssignIfModified(i.latestFirmware, DI.latestFirmware, Mods);
AssignIfModified(i.newFirmwareAvailable, DI.latestFirmwareAvailable, Mods); AssignIfModified(i.newFirmwareAvailable, DI.latestFirmwareAvailable, Mods);
AssignIfModified(i.latestFirmwareURI, DI.latestFirmwareURI, Mods); AssignIfModified(i.latestFirmwareURI, DI.latestFirmwareURI, Mods);
} }
} }
if(Mods) { if (Mods) {
auto now = Utils::Now(); auto now = Utils::Now();
if(SI.modified==now) if (SI.modified == now)
SI.modified++; SI.modified++;
else else
SI.modified=now; SI.modified = now;
StorageService()->SubInfoDB().UpdateRecord("id", UserInfo_.userinfo.id,SI); StorageService()->SubInfoDB().UpdateRecord("id", UserInfo_.userinfo.id, SI);
} }
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
SI.to_json(Answer); SI.to_json(Answer);
return ReturnObject(Answer); return ReturnObject(Answer);
} }
// if the user does not have a device, we cannot continue. // if the user does not have a device, we cannot continue.
ProvObjects::SubscriberDeviceList Devices; ProvObjects::SubscriberDeviceList Devices;
if(!SDK::Prov::Subscriber::GetDevices(this,UserInfo_.userinfo.id,UserInfo_.userinfo.owner,Devices)) { if (!SDK::Prov::Subscriber::GetDevices(this, UserInfo_.userinfo.id,
return BadRequest(RESTAPI::Errors::ProvServiceNotAvailable); UserInfo_.userinfo.owner, Devices)) {
} return BadRequest(RESTAPI::Errors::ProvServiceNotAvailable);
}
if(Devices.subscriberDevices.empty() ) { if (Devices.subscriberDevices.empty()) {
return BadRequest(RESTAPI::Errors::SubNoDeviceActivated); return BadRequest(RESTAPI::Errors::SubNoDeviceActivated);
} }
Logger().information(fmt::format("{}: Creating default user information.", UserInfo_.userinfo.email)); Logger().information(
StorageService()->SubInfoDB().CreateDefaultSubscriberInfo(UserInfo_, SI, Devices); fmt::format("{}: Creating default user information.", UserInfo_.userinfo.email));
Logger().information(fmt::format("{}: Creating default configuration.", UserInfo_.userinfo.email)); StorageService()->SubInfoDB().CreateDefaultSubscriberInfo(UserInfo_, SI, Devices);
StorageService()->SubInfoDB().CreateRecord(SI); Logger().information(
fmt::format("{}: Creating default configuration.", UserInfo_.userinfo.email));
StorageService()->SubInfoDB().CreateRecord(SI);
Logger().information(fmt::format("{}: Generating initial configuration.", UserInfo_.userinfo.email)); Logger().information(
ConfigMaker InitialConfig(Logger(),SI.id); fmt::format("{}: Generating initial configuration.", UserInfo_.userinfo.email));
InitialConfig.Prepare(); ConfigMaker InitialConfig(Logger(), SI.id);
StorageService()->SubInfoDB().GetRecord("id", SI.id, SI); InitialConfig.Prepare();
StorageService()->SubInfoDB().GetRecord("id", SI.id, SI);
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
SI.to_json(Answer); SI.to_json(Answer);
ReturnObject(Answer); ReturnObject(Answer);
} }
static bool ValidIPv4(const std::string &IP) { static bool ValidIPv4(const std::string &IP) {
if(IP.empty()) if (IP.empty())
return false; return false;
Poco::Net::IPAddress A; Poco::Net::IPAddress A;
if(!Poco::Net::IPAddress::tryParse(IP,A) || A.family()!=Poco::Net::AddressFamily::IPv4) if (!Poco::Net::IPAddress::tryParse(IP, A) || A.family() != Poco::Net::AddressFamily::IPv4)
return false; return false;
return true; return true;
} }
[[maybe_unused]] static bool ValidIPv6(const std::string &IP) { [[maybe_unused]] static bool ValidIPv6(const std::string &IP) {
if(IP.empty()) if (IP.empty())
return false; return false;
Poco::Net::IPAddress A; Poco::Net::IPAddress A;
if(!Poco::Net::IPAddress::tryParse(IP,A) || A.family()!=Poco::Net::AddressFamily::IPv6) if (!Poco::Net::IPAddress::tryParse(IP, A) || A.family() != Poco::Net::AddressFamily::IPv6)
return false; return false;
return true; return true;
} }
[[maybe_unused]] static bool ValidIPv4v6(const std::string &IP) { [[maybe_unused]] static bool ValidIPv4v6(const std::string &IP) {
if(IP.empty()) if (IP.empty())
return false; return false;
Poco::Net::IPAddress A; Poco::Net::IPAddress A;
if(!Poco::Net::IPAddress::tryParse(IP,A)) if (!Poco::Net::IPAddress::tryParse(IP, A))
return false; return false;
return true; return true;
} }
static bool ValidateIPv4Subnet(const std::string &IP) { static bool ValidateIPv4Subnet(const std::string &IP) {
auto IPParts = Poco::StringTokenizer(IP,"/"); auto IPParts = Poco::StringTokenizer(IP, "/");
if(IPParts.count()!=2) { if (IPParts.count() != 2) {
return false; return false;
} }
if(!ValidIPv4(IPParts[0])) { if (!ValidIPv4(IPParts[0])) {
return false; return false;
} }
auto X=std::atoll(IPParts[1].c_str()); auto X = std::atoll(IPParts[1].c_str());
if(X<8 || X>24) { if (X < 8 || X > 24) {
return false; return false;
} }
return true; return true;
} }
void RESTAPI_subscriber_handler::DoPut() { void RESTAPI_subscriber_handler::DoPut() {
auto ConfigChanged = GetParameter("configChanged","true") == "true"; auto ConfigChanged = GetParameter("configChanged", "true") == "true";
auto ApplyConfigOnly = GetParameter("applyConfigOnly","true") == "true"; auto ApplyConfigOnly = GetParameter("applyConfigOnly", "true") == "true";
if(UserInfo_.userinfo.id.empty()) { if (UserInfo_.userinfo.id.empty()) {
return NotFound(); return NotFound();
} }
SubObjects::SubscriberInfo Existing; SubObjects::SubscriberInfo Existing;
if(!StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, Existing)) { if (!StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, Existing)) {
return NotFound(); return NotFound();
} }
if(ApplyConfigOnly) { if (ApplyConfigOnly) {
ConfigMaker InitialConfig(Logger(),UserInfo_.userinfo.id); ConfigMaker InitialConfig(Logger(), UserInfo_.userinfo.id);
if(InitialConfig.Prepare()) if (InitialConfig.Prepare())
return OK(); return OK();
else else
return InternalError(RESTAPI::Errors::SubConfigNotRefreshed); return InternalError(RESTAPI::Errors::SubConfigNotRefreshed);
} }
const auto & Body = ParsedBody_; const auto &Body = ParsedBody_;
SubObjects::SubscriberInfo Changes; SubObjects::SubscriberInfo Changes;
if(!Changes.from_json(Body)) { if (!Changes.from_json(Body)) {
return BadRequest(RESTAPI::Errors::InvalidJSONDocument); return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
} }
auto Now = Utils::Now(); auto Now = Utils::Now();
if(Body->has("firstName")) if (Body->has("firstName"))
Existing.firstName = Changes.firstName; Existing.firstName = Changes.firstName;
if(Body->has("initials")) if (Body->has("initials"))
Existing.initials = Changes.initials; Existing.initials = Changes.initials;
if(Body->has("lastName")) if (Body->has("lastName"))
Existing.lastName = Changes.lastName; Existing.lastName = Changes.lastName;
if(Body->has("secondaryEmail") && Utils::ValidEMailAddress(Changes.secondaryEmail)) if (Body->has("secondaryEmail") && Utils::ValidEMailAddress(Changes.secondaryEmail))
Existing.secondaryEmail = Changes.secondaryEmail; Existing.secondaryEmail = Changes.secondaryEmail;
if(Body->has("serviceAddress")) if (Body->has("serviceAddress"))
Existing.serviceAddress = Changes.serviceAddress; Existing.serviceAddress = Changes.serviceAddress;
if(Body->has("billingAddress")) if (Body->has("billingAddress"))
Existing.billingAddress = Changes.billingAddress; Existing.billingAddress = Changes.billingAddress;
if(Body->has("phoneNumber")) if (Body->has("phoneNumber"))
Existing.phoneNumber = Changes.phoneNumber; Existing.phoneNumber = Changes.phoneNumber;
Existing.modified = Now; Existing.modified = Now;
// Look at the access points // Look at the access points
for (auto &NewAP: Changes.accessPoints.list) { for (auto &NewAP : Changes.accessPoints.list) {
for (auto &ExistingAP: Existing.accessPoints.list) { for (auto &ExistingAP : Existing.accessPoints.list) {
if (NewAP.macAddress == ExistingAP.macAddress) { if (NewAP.macAddress == ExistingAP.macAddress) {
for(const auto &ssid:NewAP.wifiNetworks.wifiNetworks) { for (const auto &ssid : NewAP.wifiNetworks.wifiNetworks) {
if( ssid.password.length()<8 || if (ssid.password.length() < 8 || ssid.password.length() > 32) {
ssid.password.length()>32 ) { return BadRequest(RESTAPI::Errors::SSIDInvalidPassword);
return BadRequest(RESTAPI::Errors::SSIDInvalidPassword); }
} }
} if (NewAP.deviceMode.type == "nat") {
if(NewAP.deviceMode.type=="nat") { if (!ValidIPv4(NewAP.deviceMode.startIP) ||
if(!ValidIPv4(NewAP.deviceMode.startIP) || !ValidIPv4(NewAP.deviceMode.endIP)) { !ValidIPv4(NewAP.deviceMode.endIP)) {
return BadRequest(RESTAPI::Errors::InvalidStartingIPAddress); return BadRequest(RESTAPI::Errors::InvalidStartingIPAddress);
} }
if(!ValidateIPv4Subnet(NewAP.deviceMode.subnet)) { if (!ValidateIPv4Subnet(NewAP.deviceMode.subnet)) {
return BadRequest(RESTAPI::Errors::SubnetFormatError); return BadRequest(RESTAPI::Errors::SubnetFormatError);
} }
} else if(NewAP.deviceMode.type=="bridge") { } else if (NewAP.deviceMode.type == "bridge") {
} else if(NewAP.deviceMode.type=="manual") { } else if (NewAP.deviceMode.type == "manual") {
if(!ValidateIPv4Subnet(NewAP.deviceMode.subnet)) { if (!ValidateIPv4Subnet(NewAP.deviceMode.subnet)) {
return BadRequest(RESTAPI::Errors::DeviceModeError); return BadRequest(RESTAPI::Errors::DeviceModeError);
} }
if(!ValidIPv4(NewAP.deviceMode.startIP)) { if (!ValidIPv4(NewAP.deviceMode.startIP)) {
return BadRequest(RESTAPI::Errors::DeviceModeError); return BadRequest(RESTAPI::Errors::DeviceModeError);
} }
if(!ValidIPv4(NewAP.deviceMode.endIP)) { if (!ValidIPv4(NewAP.deviceMode.endIP)) {
return BadRequest(RESTAPI::Errors::DeviceModeError); return BadRequest(RESTAPI::Errors::DeviceModeError);
} }
} else { } else {
return BadRequest(RESTAPI::Errors::BadDeviceMode); return BadRequest(RESTAPI::Errors::BadDeviceMode);
} }
if(NewAP.internetConnection.type=="manual") { if (NewAP.internetConnection.type == "manual") {
if(!ValidateIPv4Subnet(NewAP.internetConnection.subnetMask)) { if (!ValidateIPv4Subnet(NewAP.internetConnection.subnetMask)) {
return BadRequest(RESTAPI::Errors::SubnetFormatError); return BadRequest(RESTAPI::Errors::SubnetFormatError);
} }
if(!ValidIPv4(NewAP.internetConnection.defaultGateway)) { if (!ValidIPv4(NewAP.internetConnection.defaultGateway)) {
return BadRequest(RESTAPI::Errors::DefaultGatewayFormat); return BadRequest(RESTAPI::Errors::DefaultGatewayFormat);
} }
if(!ValidIPv4(NewAP.internetConnection.primaryDns)) { if (!ValidIPv4(NewAP.internetConnection.primaryDns)) {
return BadRequest(RESTAPI::Errors::PrimaryDNSFormat); return BadRequest(RESTAPI::Errors::PrimaryDNSFormat);
} }
if(!NewAP.internetConnection.secondaryDns.empty() && !ValidIPv4(NewAP.internetConnection.secondaryDns)) { if (!NewAP.internetConnection.secondaryDns.empty() &&
return BadRequest(RESTAPI::Errors::SecondaryDNSFormat); !ValidIPv4(NewAP.internetConnection.secondaryDns)) {
} return BadRequest(RESTAPI::Errors::SecondaryDNSFormat);
} else if(NewAP.internetConnection.type=="pppoe") { }
} else if (NewAP.internetConnection.type == "pppoe") {
} else if(NewAP.internetConnection.type=="automatic") { } else if (NewAP.internetConnection.type == "automatic") {
} else { } else {
return BadRequest(RESTAPI::Errors::BadConnectionType); return BadRequest(RESTAPI::Errors::BadConnectionType);
} }
ExistingAP = NewAP; ExistingAP = NewAP;
ExistingAP.internetConnection.modified = Now; ExistingAP.internetConnection.modified = Now;
ExistingAP.deviceMode.modified = Now; ExistingAP.deviceMode.modified = Now;
ExistingAP.wifiNetworks.modified = Now; ExistingAP.wifiNetworks.modified = Now;
ExistingAP.subscriberDevices.modified = Now; ExistingAP.subscriberDevices.modified = Now;
} }
} }
Changes.modified = Utils::Now(); Changes.modified = Utils::Now();
} }
if(StorageService()->SubInfoDB().UpdateRecord("id",UserInfo_.userinfo.id, Existing)) { if (StorageService()->SubInfoDB().UpdateRecord("id", UserInfo_.userinfo.id, Existing)) {
if(ConfigChanged) { if (ConfigChanged) {
ConfigMaker InitialConfig(Logger(),UserInfo_.userinfo.id); ConfigMaker InitialConfig(Logger(), UserInfo_.userinfo.id);
InitialConfig.Prepare(); InitialConfig.Prepare();
} }
SubObjects::SubscriberInfo Modified; SubObjects::SubscriberInfo Modified;
StorageService()->SubInfoDB().GetRecord("id",UserInfo_.userinfo.id,Modified); StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, Modified);
SubscriberCache()->UpdateSubInfo(UserInfo_.userinfo.id,Modified); SubscriberCache()->UpdateSubInfo(UserInfo_.userinfo.id, Modified);
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
Modified.to_json(Answer); Modified.to_json(Answer);
return ReturnObject(Answer); return ReturnObject(Answer);
} }
return InternalError(RESTAPI::Errors::RecordNotUpdated); return InternalError(RESTAPI::Errors::RecordNotUpdated);
} }
void RESTAPI_subscriber_handler::DoDelete() { void RESTAPI_subscriber_handler::DoDelete() {
auto id = GetParameter("id",""); auto id = GetParameter("id", "");
if(!id.empty()) { if (!id.empty()) {
StorageService()->SubInfoDB().DeleteRecord("id",id); StorageService()->SubInfoDB().DeleteRecord("id", id);
return OK(); return OK();
} }
SubObjects::SubscriberInfo SI; SubObjects::SubscriberInfo SI;
if(StorageService()->SubInfoDB().GetRecord("id",UserInfo_.userinfo.id,SI)) { if (StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, SI)) {
for(const auto &i:SI.accessPoints.list) { for (const auto &i : SI.accessPoints.list) {
if(!i.serialNumber.empty()) { if (!i.serialNumber.empty()) {
SDK::Prov::Subscriber::ReturnDeviceToInventory(nullptr, UserInfo_.userinfo.id, i.serialNumber); SDK::Prov::Subscriber::ReturnDeviceToInventory(nullptr, UserInfo_.userinfo.id,
} i.serialNumber);
} }
SDK::Sec::Subscriber::Delete(nullptr, UserInfo_.userinfo.id); }
StorageService()->SubInfoDB().DeleteRecord("id", UserInfo_.userinfo.id); SDK::Sec::Subscriber::Delete(nullptr, UserInfo_.userinfo.id);
return OK(); StorageService()->SubInfoDB().DeleteRecord("id", UserInfo_.userinfo.id);
} return OK();
return NotFound(); }
} return NotFound();
} }
} // namespace OpenWifi

View File

@@ -7,26 +7,26 @@
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_subscriber_handler : public RESTAPIHandler { class RESTAPI_subscriber_handler : public RESTAPIHandler {
public: public:
RESTAPI_subscriber_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, RESTAPI_subscriber_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
uint64_t TransactionId, bool Internal) RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
: RESTAPIHandler(bindings, L, bool Internal)
std::vector<std::string>{ : RESTAPIHandler(bindings, L,
Poco::Net::HTTPRequest::HTTP_GET, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_PUT, Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_DELETE, Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, Server, TransactionId, Internal, true, false,
TransactionId, RateLimit{.Interval = 1000, .MaxCalls = 10}, true) {}
Internal, true, false, RateLimit{.Interval=1000,.MaxCalls=10}, true){}
static auto PathName() { return std::list<std::string>{"/api/v1/subscriber"}; }; static auto PathName() { return std::list<std::string>{"/api/v1/subscriber"}; };
void DoGet() final; void DoGet() final;
void DoPost() final {}; void DoPost() final{};
void DoPut() final; void DoPut() final;
void DoDelete() final; void DoDelete() final;
private:
}; private:
} };
} // namespace OpenWifi

View File

@@ -5,115 +5,126 @@
#include "RESTAPI_wifiClients_handler.h" #include "RESTAPI_wifiClients_handler.h"
#include "RESTObjects/RESTAPI_SubObjects.h" #include "RESTObjects/RESTAPI_SubObjects.h"
#include "StorageService.h" #include "StorageService.h"
#include "sdks/SDK_gw.h"
#include "nlohmann/json.hpp"
#include "framework/utils.h" #include "framework/utils.h"
#include "nlohmann/json.hpp"
#include "sdks/SDK_gw.h"
// #define __DBG__ std::cout << __LINE__ << std::endl ; // #define __DBG__ std::cout << __LINE__ << std::endl ;
#define __DBG__ #define __DBG__
namespace OpenWifi { namespace OpenWifi {
static void AddManufacturers(SubObjects::AssociationList &List) { static void AddManufacturers(SubObjects::AssociationList &List) {
std::vector<std::pair<std::string,std::string>> MacList; std::vector<std::pair<std::string, std::string>> MacList;
for(const auto &i:List.associations) { for (const auto &i : List.associations) {
MacList.push_back(std::make_pair(i.macAddress,"")); MacList.push_back(std::make_pair(i.macAddress, ""));
} }
if(SDK::GW::Device::GetOUIs(nullptr,MacList)) { if (SDK::GW::Device::GetOUIs(nullptr, MacList)) {
for(const auto &i:MacList) for (const auto &i : MacList)
for(auto &j:List.associations) for (auto &j : List.associations)
if(j.macAddress==i.first) { if (j.macAddress == i.first) {
// std::cout << i.first << " :: " << i.second << std::endl; // std::cout << i.first << " :: " << i.second << std::endl;
j.manufacturer = i.second; j.manufacturer = i.second;
} }
} }
} }
void RESTAPI_wifiClients_handler::DoGet() { void RESTAPI_wifiClients_handler::DoGet() {
auto SerialNumber = GetParameter("serialNumber",""); auto SerialNumber = GetParameter("serialNumber", "");
if(SerialNumber.empty()) { if (SerialNumber.empty()) {
return BadRequest(RESTAPI::Errors::MissingSerialNumber); return BadRequest(RESTAPI::Errors::MissingSerialNumber);
} }
Logger().information(fmt::format("{}: Getting list of wireless clients.",SerialNumber)); Logger().information(fmt::format("{}: Getting list of wireless clients.", SerialNumber));
SubObjects::SubscriberInfo SI; SubObjects::SubscriberInfo SI;
if(!StorageService()->SubInfoDB().GetRecord("id",UserInfo_.userinfo.id,SI)) { if (!StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, SI)) {
return NotFound(); return NotFound();
} }
for(const auto &i:SI.accessPoints.list) { for (const auto &i : SI.accessPoints.list) {
if(i.macAddress.empty()) if (i.macAddress.empty())
continue; continue;
if(SerialNumber==i.macAddress) { if (SerialNumber == i.macAddress) {
Poco::JSON::Object::Ptr LastStats; Poco::JSON::Object::Ptr LastStats;
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
if(SDK::GW::Device::GetLastStats(nullptr,i.serialNumber,LastStats)){ if (SDK::GW::Device::GetLastStats(nullptr, i.serialNumber, LastStats)) {
uint64_t Now = Utils::Now(); uint64_t Now = Utils::Now();
SubObjects::AssociationList AssocList; SubObjects::AssociationList AssocList;
AssocList.modified = AssocList.created = Now; AssocList.modified = AssocList.created = Now;
std::stringstream SS; std::stringstream SS;
LastStats->stringify(SS); LastStats->stringify(SS);
try { try {
auto stats = nlohmann::json::parse(SS.str()); auto stats = nlohmann::json::parse(SS.str());
if(stats.contains("interfaces") && stats["interfaces"].is_array()) { if (stats.contains("interfaces") && stats["interfaces"].is_array()) {
auto ifs = stats["interfaces"]; auto ifs = stats["interfaces"];
for (const auto &cur_interface: ifs) { for (const auto &cur_interface : ifs) {
// create a map of MAC -> IP for clients // create a map of MAC -> IP for clients
std::map<std::string,std::pair<std::string,std::string>> IPs; std::map<std::string, std::pair<std::string, std::string>> IPs;
if (cur_interface.contains("clients") && cur_interface["clients"].is_array()) { if (cur_interface.contains("clients") &&
auto clients = cur_interface["clients"]; cur_interface["clients"].is_array()) {
for(const auto &cur_client:clients) { auto clients = cur_interface["clients"];
if(cur_client.contains("mac")) { for (const auto &cur_client : clients) {
std::string ipv4,ipv6; if (cur_client.contains("mac")) {
if( cur_client.contains("ipv6_addresses") && std::string ipv4, ipv6;
cur_client["ipv6_addresses"].is_array() && if (cur_client.contains("ipv6_addresses") &&
!cur_client["ipv6_addresses"].empty()) { cur_client["ipv6_addresses"].is_array() &&
ipv6 = cur_client["ipv6_addresses"][0].get<std::string>(); !cur_client["ipv6_addresses"].empty()) {
} ipv6 = cur_client["ipv6_addresses"][0]
if( cur_client.contains("ipv4_addresses") && .get<std::string>();
cur_client["ipv4_addresses"].is_array() && }
!cur_client["ipv4_addresses"].empty()) { if (cur_client.contains("ipv4_addresses") &&
ipv4 = cur_client["ipv4_addresses"][0].get<std::string>(); cur_client["ipv4_addresses"].is_array() &&
} !cur_client["ipv4_addresses"].empty()) {
IPs[cur_client["mac"].get<std::string>()] = std::make_pair(ipv4,ipv6); ipv4 = cur_client["ipv4_addresses"][0]
} .get<std::string>();
} }
} IPs[cur_client["mac"].get<std::string>()] =
std::make_pair(ipv4, ipv6);
}
}
}
if (cur_interface.contains("ssids") && cur_interface["ssids"].is_array() && !cur_interface["ssids"].empty()) { if (cur_interface.contains("ssids") &&
for (const auto &cur_ssid: cur_interface["ssids"]) { cur_interface["ssids"].is_array() &&
if (cur_ssid.contains("associations") && cur_ssid["associations"].is_array() && !cur_ssid["associations"].empty()) { !cur_interface["ssids"].empty()) {
for (const auto &cur_client: cur_ssid["associations"]) { for (const auto &cur_ssid : cur_interface["ssids"]) {
SubObjects::Association Assoc; if (cur_ssid.contains("associations") &&
Assoc.ssid = cur_ssid["ssid"].get<std::string>(); cur_ssid["associations"].is_array() &&
Assoc.macAddress = cur_client["station"].get<std::string>(); !cur_ssid["associations"].empty()) {
Assoc.rssi = cur_client["rssi"].get<int32_t>(); for (const auto &cur_client :
Assoc.rx = cur_client["rx_bytes"].get<uint64_t>(); cur_ssid["associations"]) {
Assoc.tx = cur_client["tx_bytes"].get<uint64_t>(); SubObjects::Association Assoc;
Assoc.power = 0; Assoc.ssid = cur_ssid["ssid"].get<std::string>();
Assoc.name = cur_client["station"].get<std::string>(); Assoc.macAddress =
auto which_ips = IPs.find(Assoc.macAddress); cur_client["station"].get<std::string>();
if(which_ips != IPs.end()) { Assoc.rssi = cur_client["rssi"].get<int32_t>();
Assoc.ipv4 = which_ips->second.first; Assoc.rx = cur_client["rx_bytes"].get<uint64_t>();
Assoc.ipv6 = which_ips->second.second; Assoc.tx = cur_client["tx_bytes"].get<uint64_t>();
} Assoc.power = 0;
AssocList.associations.push_back(Assoc); Assoc.name =
} cur_client["station"].get<std::string>();
} auto which_ips = IPs.find(Assoc.macAddress);
} if (which_ips != IPs.end()) {
} Assoc.ipv4 = which_ips->second.first;
} Assoc.ipv6 = which_ips->second.second;
} }
AddManufacturers(AssocList); AssocList.associations.push_back(Assoc);
AssocList.to_json(Answer); }
} catch (...) { }
} }
} }
return ReturnObject(Answer); }
} }
} AddManufacturers(AssocList);
return NotFound(); AssocList.to_json(Answer);
} } catch (...) {
}
}
return ReturnObject(Answer);
}
}
return NotFound();
}
} } // namespace OpenWifi

View File

@@ -7,31 +7,32 @@
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_wifiClients_handler : public RESTAPIHandler { class RESTAPI_wifiClients_handler : public RESTAPIHandler {
public: public:
RESTAPI_wifiClients_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) RESTAPI_wifiClients_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
: RESTAPIHandler(bindings, L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
std::vector<std::string>{ bool Internal)
Poco::Net::HTTPRequest::HTTP_GET, : RESTAPIHandler(bindings, L,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Server, Poco::Net::HTTPRequest::HTTP_OPTIONS},
TransactionId, Server, TransactionId, Internal, true, false,
Internal,true, false, RateLimit{.Interval=1000,.MaxCalls=10}, true){} RateLimit{.Interval = 1000, .MaxCalls = 10}, true) {}
static auto PathName() { return std::list<std::string>{"/api/v1/wificlients"}; }; static auto PathName() { return std::list<std::string>{"/api/v1/wificlients"}; };
inline bool RoleIsAuthorized(std::string & Reason) { inline bool RoleIsAuthorized(std::string &Reason) {
if(UserInfo_.userinfo.userRole != SecurityObjects::USER_ROLE::SUBSCRIBER) { if (UserInfo_.userinfo.userRole != SecurityObjects::USER_ROLE::SUBSCRIBER) {
Reason = "User must be a subscriber"; Reason = "User must be a subscriber";
return false; return false;
} }
return true; return true;
} }
void DoGet() final; void DoGet() final;
void DoPost() final {}; void DoPost() final{};
void DoPut() final {}; void DoPut() final{};
void DoDelete() final {}; void DoDelete() final{};
private:
}; private:
} };
} // namespace OpenWifi

View File

@@ -4,119 +4,127 @@
#include "RESTAPI_wiredClients_handler.h" #include "RESTAPI_wiredClients_handler.h"
#include "RESTObjects/RESTAPI_SubObjects.h" #include "RESTObjects/RESTAPI_SubObjects.h"
#include "nlohmann/json.hpp"
#include "StorageService.h" #include "StorageService.h"
#include "sdks/SDK_gw.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "nlohmann/json.hpp"
#include "sdks/SDK_gw.h"
namespace OpenWifi { namespace OpenWifi {
static void AddManufacturers(SubObjects::ClientList &List) { static void AddManufacturers(SubObjects::ClientList &List) {
std::vector<std::pair<std::string,std::string>> MacList; std::vector<std::pair<std::string, std::string>> MacList;
for(const auto &i:List.clients) { for (const auto &i : List.clients) {
MacList.push_back(std::make_pair(i.macAddress,"")); MacList.push_back(std::make_pair(i.macAddress, ""));
} }
if(SDK::GW::Device::GetOUIs(nullptr,MacList)) { if (SDK::GW::Device::GetOUIs(nullptr, MacList)) {
for(const auto &i:MacList) for (const auto &i : MacList)
for(auto &j:List.clients) for (auto &j : List.clients)
if(j.macAddress==i.first) { if (j.macAddress == i.first) {
// std::cout << i.first << " :: " << i.second << std::endl; // std::cout << i.first << " :: " << i.second << std::endl;
j.manufacturer = i.second; j.manufacturer = i.second;
} }
} }
} }
void RESTAPI_wiredClients_handler::DoGet() { void RESTAPI_wiredClients_handler::DoGet() {
auto SerialNumber = GetParameter("serialNumber", ""); auto SerialNumber = GetParameter("serialNumber", "");
if (SerialNumber.empty()) { if (SerialNumber.empty()) {
return BadRequest(RESTAPI::Errors::MissingSerialNumber); return BadRequest(RESTAPI::Errors::MissingSerialNumber);
} }
Logger().information(fmt::format("{}: Getting list of wired clients.",SerialNumber)); Logger().information(fmt::format("{}: Getting list of wired clients.", SerialNumber));
SubObjects::SubscriberInfo SI; SubObjects::SubscriberInfo SI;
if (!StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, SI)) { if (!StorageService()->SubInfoDB().GetRecord("id", UserInfo_.userinfo.id, SI)) {
return NotFound(); return NotFound();
} }
for (const auto &i: SI.accessPoints.list) { for (const auto &i : SI.accessPoints.list) {
if (SerialNumber == i.macAddress) { if (SerialNumber == i.macAddress) {
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
uint64_t Now = Utils::Now(); uint64_t Now = Utils::Now();
Answer.set("created", Now); Answer.set("created", Now);
Answer.set("modified", Now); Answer.set("modified", Now);
SubObjects::ClientList CList; SubObjects::ClientList CList;
CList.modified = CList.created = Now; CList.modified = CList.created = Now;
Poco::JSON::Object::Ptr LastStats; Poco::JSON::Object::Ptr LastStats;
if(SDK::GW::Device::GetLastStats(nullptr,i.serialNumber,LastStats)){ if (SDK::GW::Device::GetLastStats(nullptr, i.serialNumber, LastStats)) {
SubObjects::AssociationList AssocList; SubObjects::AssociationList AssocList;
AssocList.modified = AssocList.created = Now; AssocList.modified = AssocList.created = Now;
std::stringstream SS; std::stringstream SS;
LastStats->stringify(SS); LastStats->stringify(SS);
try { try {
auto Stats = nlohmann::json::parse(SS.str()); auto Stats = nlohmann::json::parse(SS.str());
if(Stats.contains("interfaces") && Stats["interfaces"].is_array()) { if (Stats.contains("interfaces") && Stats["interfaces"].is_array()) {
auto interfaces = Stats["interfaces"]; auto interfaces = Stats["interfaces"];
for (const auto &cur_interface: interfaces) { for (const auto &cur_interface : interfaces) {
std::set<std::string> WifiMacs; std::set<std::string> WifiMacs;
if (cur_interface.contains("ssids") && cur_interface["ssids"].is_array() && !cur_interface["ssids"].empty()) { if (cur_interface.contains("ssids") &&
for (const auto &cur_ssid: cur_interface["ssids"]) { cur_interface["ssids"].is_array() &&
if (cur_ssid.contains("associations") && cur_ssid["associations"].is_array() && !cur_ssid["associations"].empty()) { !cur_interface["ssids"].empty()) {
for (const auto &cur_client: cur_ssid["associations"]) { for (const auto &cur_ssid : cur_interface["ssids"]) {
WifiMacs.insert(cur_client["station"].get<std::string>()); if (cur_ssid.contains("associations") &&
} cur_ssid["associations"].is_array() &&
} !cur_ssid["associations"].empty()) {
} for (const auto &cur_client :
} cur_ssid["associations"]) {
WifiMacs.insert(
cur_client["station"].get<std::string>());
}
}
}
}
if(cur_interface.contains("clients") && cur_interface["clients"].is_array() && !cur_interface["clients"].empty()) { if (cur_interface.contains("clients") &&
auto clients = cur_interface["clients"]; cur_interface["clients"].is_array() &&
for (const auto &cur_client: clients) { !cur_interface["clients"].empty()) {
auto clients = cur_interface["clients"];
for (const auto &cur_client : clients) {
std::string Mac = cur_client["mac"]; std::string Mac = cur_client["mac"];
if(WifiMacs.find(Mac)==WifiMacs.end()) { if (WifiMacs.find(Mac) == WifiMacs.end()) {
SubObjects::Client C; SubObjects::Client C;
C.macAddress = Mac; C.macAddress = Mac;
if (cur_client.contains("ipv6_addresses") && if (cur_client.contains("ipv6_addresses") &&
cur_client["ipv6_addresses"].is_array() && cur_client["ipv6_addresses"].is_array() &&
!cur_client["ipv6_addresses"].empty()) { !cur_client["ipv6_addresses"].empty()) {
auto ipv6addresses = cur_client["ipv6_addresses"]; auto ipv6addresses = cur_client["ipv6_addresses"];
for (const auto &cur_addr: ipv6addresses) { for (const auto &cur_addr : ipv6addresses) {
C.ipv6 = cur_addr; C.ipv6 = cur_addr;
break; break;
} }
} }
if (cur_client.contains("ipv4_addresses") && if (cur_client.contains("ipv4_addresses") &&
cur_client["ipv4_addresses"].is_array() && cur_client["ipv4_addresses"].is_array() &&
!cur_client["ipv4_addresses"].empty()) { !cur_client["ipv4_addresses"].empty()) {
auto ipv4addresses = cur_client["ipv4_addresses"]; auto ipv4addresses = cur_client["ipv4_addresses"];
for (const auto &cur_addr: ipv4addresses) { for (const auto &cur_addr : ipv4addresses) {
C.ipv4 = cur_addr; C.ipv4 = cur_addr;
} }
} }
C.tx = C.rx = 0; C.tx = C.rx = 0;
C.speed = "auto"; C.speed = "auto";
C.mode = "auto"; C.mode = "auto";
CList.clients.push_back(C); CList.clients.push_back(C);
} }
} }
} }
} }
} }
AddManufacturers(CList); AddManufacturers(CList);
CList.to_json(Answer); CList.to_json(Answer);
} catch (...) { } catch (...) {
} }
} }
return ReturnObject(Answer); return ReturnObject(Answer);
} }
} }
return NotFound(); return NotFound();
} }
} } // namespace OpenWifi

View File

@@ -7,31 +7,32 @@
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_wiredClients_handler : public RESTAPIHandler { class RESTAPI_wiredClients_handler : public RESTAPIHandler {
public: public:
RESTAPI_wiredClients_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) RESTAPI_wiredClients_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
: RESTAPIHandler(bindings, L, RESTAPI_GenericServerAccounting &Server,
std::vector<std::string>{ uint64_t TransactionId, bool Internal)
Poco::Net::HTTPRequest::HTTP_GET, : RESTAPIHandler(bindings, L,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Server, Poco::Net::HTTPRequest::HTTP_OPTIONS},
TransactionId, Server, TransactionId, Internal, true, false,
Internal,true, false, RateLimit{.Interval=1000,.MaxCalls=10}, true){} RateLimit{.Interval = 1000, .MaxCalls = 10}, true) {}
static auto PathName() { return std::list<std::string>{"/api/v1/wiredclients"}; }; static auto PathName() { return std::list<std::string>{"/api/v1/wiredclients"}; };
inline bool RoleIsAuthorized(std::string & Reason) { inline bool RoleIsAuthorized(std::string &Reason) {
if(UserInfo_.userinfo.userRole != SecurityObjects::USER_ROLE::SUBSCRIBER) { if (UserInfo_.userinfo.userRole != SecurityObjects::USER_ROLE::SUBSCRIBER) {
Reason = "User must be a subscriber"; Reason = "User must be a subscriber";
return false; return false;
} }
return true; return true;
} }
void DoGet() final; void DoGet() final;
void DoPost() final {}; void DoPost() final{};
void DoPut() final {}; void DoPut() final{};
void DoDelete() final {}; void DoDelete() final{};
private:
}; private:
} };
} // namespace OpenWifi

File diff suppressed because it is too large Load Diff

View File

@@ -10,414 +10,334 @@
namespace OpenWifi { namespace OpenWifi {
namespace AnalyticsObjects { namespace AnalyticsObjects {
struct Report { struct Report {
uint64_t snapShot = 0; uint64_t snapShot = 0;
void reset(); void reset();
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct VenueInfo { struct VenueInfo {
OpenWifi::Types::UUID_t id; OpenWifi::Types::UUID_t id;
std::string name; std::string name;
std::string description; std::string description;
uint64_t retention = 0; uint64_t retention = 0;
uint64_t interval = 0; uint64_t interval = 0;
bool monitorSubVenues = false; bool monitorSubVenues = false;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct BoardInfo { struct BoardInfo {
ProvObjects::ObjectInfo info; ProvObjects::ObjectInfo info;
std::vector<VenueInfo> venueList; std::vector<VenueInfo> venueList;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
inline bool operator<(const BoardInfo &bb) const { inline bool operator<(const BoardInfo &bb) const { return info.id < bb.info.id; }
return info.id < bb.info.id;
} inline bool operator==(const BoardInfo &bb) const { return info.id == bb.info.id; }
};
inline bool operator==(const BoardInfo &bb) const {
return info.id == bb.info.id; struct DeviceInfo {
} std::string boardId;
}; std::string type;
std::string serialNumber;
struct DeviceInfo { std::string deviceType;
std::string boardId; uint64_t lastContact = 0;
std::string type; uint64_t lastPing = 0;
std::string serialNumber; uint64_t lastState = 0;
std::string deviceType; std::string lastFirmware;
uint64_t lastContact = 0 ; uint64_t lastFirmwareUpdate = 0;
uint64_t lastPing = 0; uint64_t lastConnection = 0;
uint64_t lastState = 0; uint64_t lastDisconnection = 0;
std::string lastFirmware; uint64_t pings = 0;
uint64_t lastFirmwareUpdate = 0; uint64_t states = 0;
uint64_t lastConnection = 0; bool connected = false;
uint64_t lastDisconnection = 0; std::string connectionIp;
uint64_t pings = 0; uint64_t associations_2g = 0;
uint64_t states = 0; uint64_t associations_5g = 0;
bool connected = false; uint64_t associations_6g = 0;
std::string connectionIp; uint64_t health = 0;
uint64_t associations_2g = 0; uint64_t lastHealth = 0;
uint64_t associations_5g = 0; std::string locale;
uint64_t associations_6g = 0; uint64_t uptime = 0;
uint64_t health = 0; double memory = 0.0;
uint64_t lastHealth = 0;
std::string locale; void to_json(Poco::JSON::Object &Obj) const;
uint64_t uptime = 0; bool from_json(const Poco::JSON::Object::Ptr &Obj);
double memory = 0.0; };
void to_json(Poco::JSON::Object &Obj) const; struct DeviceInfoList {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::vector<DeviceInfo> devices;
};
void to_json(Poco::JSON::Object &Obj) const;
struct DeviceInfoList { bool from_json(const Poco::JSON::Object::Ptr &Obj);
std::vector<DeviceInfo> devices; };
void to_json(Poco::JSON::Object &Obj) const; enum wifi_band { band_2g = 0, band_5g = 1, band_6g = 2 };
bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; struct TIDstat_entry {
uint64_t rx_msdu = 0, tx_msdu = 0, tx_msdu_failed = 0, tx_msdu_retries = 0;
enum wifi_band {
band_2g = 0, band_5g = 1, band_6g = 2 void to_json(Poco::JSON::Object &Obj) const;
}; bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct TIDstat_entry {
uint64_t rx_msdu = 0, struct UE_rate {
tx_msdu = 0, uint64_t bitrate = 0;
tx_msdu_failed = 0, uint64_t mcs = 0;
tx_msdu_retries = 0; uint64_t nss = 0;
bool ht = false;
void to_json(Poco::JSON::Object &Obj) const; bool sgi = false;
bool from_json(const Poco::JSON::Object::Ptr &Obj); uint64_t chwidth = 0;
};
void to_json(Poco::JSON::Object &Obj) const;
struct UE_rate { bool from_json(const Poco::JSON::Object::Ptr &Obj);
uint64_t bitrate=0; };
uint64_t mcs=0;
uint64_t nss=0; struct AveragePoint {
bool ht=false; double min = 0.0, max = 0.0, avg = 0.0;
bool sgi=false; void to_json(Poco::JSON::Object &Obj) const;
uint64_t chwidth=0; bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); struct UETimePoint {
}; std::string station;
int64_t rssi = 0;
struct AveragePoint { uint64_t tx_bytes = 0, rx_bytes = 0, tx_duration = 0, rx_packets = 0, tx_packets = 0,
double min = 0.0, tx_retries = 0, tx_failed = 0, connected = 0, inactive = 0;
max = 0.0,
avg = 0.0; double tx_bytes_bw = 0.0, rx_bytes_bw = 0.0, tx_packets_bw = 0.0, rx_packets_bw = 0.0,
void to_json(Poco::JSON::Object &Obj) const; tx_failed_pct = 0.0, tx_retries_pct = 0.0, tx_duration_pct = 0.0;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; uint64_t tx_bytes_delta = 0, rx_bytes_delta = 0, tx_duration_delta = 0,
rx_packets_delta = 0, tx_packets_delta = 0, tx_retries_delta = 0,
struct UETimePoint { tx_failed_delta = 0;
std::string station;
int64_t rssi = 0; UE_rate tx_rate, rx_rate;
uint64_t tx_bytes = 0, std::vector<TIDstat_entry> tidstats;
rx_bytes = 0,
tx_duration = 0, void to_json(Poco::JSON::Object &Obj) const;
rx_packets = 0, bool from_json(const Poco::JSON::Object::Ptr &Obj);
tx_packets = 0, };
tx_retries = 0,
tx_failed = 0, enum SSID_MODES { unknown = 0, ap, mesh, sta, wds_ap, wds_sta, wds_repeater };
connected = 0,
inactive = 0; inline SSID_MODES SSID_Mode(const std::string &m) {
if (m == "ap")
double tx_bytes_bw = 0.0 , return ap;
rx_bytes_bw = 0.0 , if (m == "sta")
tx_packets_bw = 0.0 , return sta;
rx_packets_bw = 0.0 , if (m == "mesh")
tx_failed_pct = 0.0 , return mesh;
tx_retries_pct = 0.0 , if (m == "wds-ap")
tx_duration_pct = 0.0; return wds_ap;
if (m == "wds-sta")
uint64_t tx_bytes_delta = 0, return wds_sta;
rx_bytes_delta = 0, if (m == "wds-repeater")
tx_duration_delta = 0, return wds_repeater;
rx_packets_delta = 0, return unknown;
tx_packets_delta = 0, }
tx_retries_delta = 0,
tx_failed_delta = 0; struct SSIDTimePoint {
std::string bssid, mode, ssid;
UE_rate tx_rate, uint64_t band = 0, channel = 0;
rx_rate; std::vector<UETimePoint> associations;
std::vector<TIDstat_entry> tidstats;
AveragePoint tx_bytes_bw, rx_bytes_bw, tx_packets_bw, rx_packets_bw, tx_failed_pct,
void to_json(Poco::JSON::Object &Obj) const; tx_retries_pct, tx_duration_pct;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
enum SSID_MODES { };
unknown = 0,
ap, struct APTimePoint {
mesh, uint64_t collisions = 0, multicast = 0, rx_bytes = 0, rx_dropped = 0, rx_errors = 0,
sta, rx_packets = 0, tx_bytes = 0, tx_dropped = 0, tx_errors = 0, tx_packets = 0;
wds_ap,
wds_sta, double tx_bytes_bw = 0.0, rx_bytes_bw = 0.0, rx_dropped_pct = 0.0, tx_dropped_pct = 0.0,
wds_repeater rx_packets_bw = 0.0, tx_packets_bw = 0.0, rx_errors_pct = 0.0,
}; tx_errors_pct = 0.0;
inline SSID_MODES SSID_Mode(const std::string &m) { uint64_t tx_bytes_delta = 0, rx_bytes_delta = 0, rx_dropped_delta = 0,
if (m == "ap") tx_dropped_delta = 0, rx_packets_delta = 0, tx_packets_delta = 0,
return ap; rx_errors_delta = 0, tx_errors_delta = 0;
if (m == "sta")
return sta; void to_json(Poco::JSON::Object &Obj) const;
if (m == "mesh") bool from_json(const Poco::JSON::Object::Ptr &Obj);
return mesh; };
if (m == "wds-ap")
return wds_ap; struct RadioTimePoint {
if (m == "wds-sta") uint64_t band = 0, channel_width = 0;
return wds_sta; uint64_t active_ms = 0, busy_ms = 0, receive_ms = 0, transmit_ms = 0, tx_power = 0,
if (m == "wds-repeater") channel = 0;
return wds_repeater; int64_t temperature = 0, noise = 0;
return unknown;
} double active_pct = 0.0, busy_pct = 0.0, receive_pct = 0.0, transmit_pct = 0.0;
struct SSIDTimePoint { void to_json(Poco::JSON::Object &Obj) const;
std::string bssid, bool from_json(const Poco::JSON::Object::Ptr &Obj);
mode, };
ssid;
uint64_t band=0, struct DeviceTimePoint {
channel=0; std::string id;
std::vector<UETimePoint> associations; std::string boardId;
uint64_t timestamp = 0;
AveragePoint tx_bytes_bw, APTimePoint ap_data;
rx_bytes_bw, std::vector<SSIDTimePoint> ssid_data;
tx_packets_bw, std::vector<RadioTimePoint> radio_data;
rx_packets_bw, AnalyticsObjects::DeviceInfo device_info;
tx_failed_pct, std::string serialNumber;
tx_retries_pct,
tx_duration_pct; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); inline bool operator<(const DeviceTimePoint &rhs) const {
}; if (timestamp < rhs.timestamp)
return true;
if (timestamp > rhs.timestamp)
struct APTimePoint { return false;
uint64_t collisions = 0, if (device_info.serialNumber < rhs.device_info.serialNumber)
multicast = 0, return true;
rx_bytes = 0, return false;
rx_dropped = 0, }
rx_errors = 0,
rx_packets = 0, inline bool operator==(const DeviceTimePoint &rhs) const {
tx_bytes = 0, return timestamp == rhs.timestamp &&
tx_dropped = 0, device_info.serialNumber == rhs.device_info.serialNumber;
tx_errors = 0, }
tx_packets = 0;
inline bool operator>(const DeviceTimePoint &rhs) const {
double tx_bytes_bw = 0.0 , if (timestamp > rhs.timestamp)
rx_bytes_bw = 0.0 , return true;
rx_dropped_pct = 0.0, if (timestamp < rhs.timestamp)
tx_dropped_pct = 0.0, return false;
rx_packets_bw = 0.0, if (device_info.serialNumber > rhs.device_info.serialNumber)
tx_packets_bw = 0.0, return true;
rx_errors_pct = 0.0 , return false;
tx_errors_pct = 0.0; }
};
uint64_t tx_bytes_delta = 0,
rx_bytes_delta = 0 , struct DeviceTimePointAnalysis {
rx_dropped_delta = 0, uint64_t timestamp;
tx_dropped_delta = 0,
rx_packets_delta = 0, AveragePoint noise;
tx_packets_delta = 0, AveragePoint temperature;
rx_errors_delta = 0, AveragePoint active_pct;
tx_errors_delta = 0; AveragePoint busy_pct;
AveragePoint receive_pct;
void to_json(Poco::JSON::Object &Obj) const; AveragePoint transmit_pct;
bool from_json(const Poco::JSON::Object::Ptr &Obj); AveragePoint tx_power;
};
AveragePoint tx_bytes_bw;
struct RadioTimePoint { AveragePoint rx_bytes_bw;
uint64_t band = 0, AveragePoint rx_dropped_pct;
channel_width = 0; AveragePoint tx_dropped_pct;
uint64_t active_ms = 0, AveragePoint rx_packets_bw;
busy_ms = 0, AveragePoint tx_packets_bw;
receive_ms = 0, AveragePoint rx_errors_pct;
transmit_ms = 0, AveragePoint tx_errors_pct;
tx_power = 0,
channel = 0; void to_json(Poco::JSON::Object &Obj) const;
int64_t temperature = 0, bool from_json(const Poco::JSON::Object::Ptr &Obj);
noise = 0; };
double active_pct = 0.0 , struct DeviceTimePointList {
busy_pct = 0.0, std::vector<DeviceTimePoint> points;
receive_pct = 0.0, std::vector<DeviceTimePointAnalysis> stats;
transmit_pct = 0.0; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
void to_json(Poco::JSON::Object &Obj) const; };
bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; struct BandwidthAnalysisEntry {
uint64_t timestamp = 0;
};
struct DeviceTimePoint {
std::string id; struct BandwidthAnalysis {};
std::string boardId;
uint64_t timestamp = 0; struct AverageValueSigned {
APTimePoint ap_data; int64_t peak = 0, avg = 0, low = 0;
std::vector<SSIDTimePoint> ssid_data; };
std::vector<RadioTimePoint> radio_data;
AnalyticsObjects::DeviceInfo device_info; struct AverageValueUnsigned {
std::string serialNumber; uint64_t peak = 0, avg = 0, low = 0;
};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); struct RadioAnalysis {
uint64_t timestamp = 0;
inline bool operator<(const DeviceTimePoint &rhs) const { AverageValueSigned noise, temperature;
if(timestamp < rhs.timestamp) AverageValueUnsigned active_ms, busy_ms, transmit_ms, receive_ms;
return true; };
if(timestamp > rhs.timestamp)
return false; struct DeviceTimePointStats {
if(device_info.serialNumber < rhs.device_info.serialNumber) uint64_t firstPoint = 0;
return true; uint64_t lastPoint = 0;
return false; uint64_t count = 0;
}
void to_json(Poco::JSON::Object &Obj) const;
inline bool operator==(const DeviceTimePoint &rhs) const { bool from_json(const Poco::JSON::Object::Ptr &Obj);
return timestamp==rhs.timestamp && device_info.serialNumber==rhs.device_info.serialNumber; };
}
struct WifiClientRate {
inline bool operator>(const DeviceTimePoint &rhs) const { uint32_t bitrate = 0;
if(timestamp > rhs.timestamp) uint32_t chwidth = 0;
return true; uint16_t mcs = 0;
if(timestamp < rhs.timestamp) uint16_t nss = 0;
return false; bool vht = false;
if(device_info.serialNumber > rhs.device_info.serialNumber)
return true; void to_json(Poco::JSON::Object &Obj) const;
return false; bool from_json(const Poco::JSON::Object::Ptr &Obj);
} };
}; struct WifiClientHistory {
uint64_t timestamp = Utils::Now();
struct DeviceTimePointAnalysis { std::string station_id;
uint64_t timestamp; std::string bssid;
std::string ssid;
AveragePoint noise; int64_t rssi = 0;
AveragePoint temperature; uint32_t rx_bitrate = 0;
AveragePoint active_pct; uint32_t rx_chwidth = 0;
AveragePoint busy_pct; uint16_t rx_mcs = 0;
AveragePoint receive_pct; uint16_t rx_nss = 0;
AveragePoint transmit_pct; bool rx_vht = false;
AveragePoint tx_power; uint32_t tx_bitrate = 0;
uint32_t tx_chwidth = 0;
AveragePoint tx_bytes_bw; uint16_t tx_mcs = 0;
AveragePoint rx_bytes_bw; uint16_t tx_nss = 0;
AveragePoint rx_dropped_pct; bool tx_vht = false;
AveragePoint tx_dropped_pct; uint64_t rx_bytes = 0;
AveragePoint rx_packets_bw; uint64_t tx_bytes = 0;
AveragePoint tx_packets_bw; uint64_t rx_duration = 0;
AveragePoint rx_errors_pct; uint64_t tx_duration = 0;
AveragePoint tx_errors_pct; uint64_t rx_packets = 0;
uint64_t tx_packets = 0;
void to_json(Poco::JSON::Object &Obj) const; std::string ipv4;
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string ipv6;
uint64_t channel_width = 0;
}; int64_t noise = 0;
uint64_t tx_power = 0;
struct DeviceTimePointList { uint64_t channel = 0;
std::vector<DeviceTimePoint> points; uint64_t active_ms = 0;
std::vector<DeviceTimePointAnalysis> stats; uint64_t busy_ms = 0;
void to_json(Poco::JSON::Object &Obj) const; uint64_t receive_ms = 0;
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string mode;
}; int64_t ack_signal = 0;
int64_t ack_signal_avg = 0;
struct BandwidthAnalysisEntry { uint64_t connected = 0;
uint64_t timestamp = 0; uint64_t inactive = 0;
uint64_t tx_retries = 0;
}; std::string venue_id;
struct BandwidthAnalysis { void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct AverageValueSigned { } // namespace AnalyticsObjects
int64_t peak=0, avg=0, low=0;
}; } // namespace OpenWifi
struct AverageValueUnsigned {
uint64_t peak=0, avg=0, low=0;
};
struct RadioAnalysis {
uint64_t timestamp=0;
AverageValueSigned noise, temperature;
AverageValueUnsigned active_ms,
busy_ms,
transmit_ms,
receive_ms;
};
struct DeviceTimePointStats {
uint64_t firstPoint=0;
uint64_t lastPoint=0;
uint64_t count=0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WifiClientRate {
uint32_t bitrate=0;
uint32_t chwidth=0;
uint16_t mcs=0;
uint16_t nss=0;
bool vht=false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WifiClientHistory {
uint64_t timestamp=Utils::Now();
std::string station_id;
std::string bssid;
std::string ssid;
int64_t rssi=0;
uint32_t rx_bitrate=0;
uint32_t rx_chwidth=0;
uint16_t rx_mcs=0;
uint16_t rx_nss=0;
bool rx_vht=false;
uint32_t tx_bitrate=0;
uint32_t tx_chwidth=0;
uint16_t tx_mcs=0;
uint16_t tx_nss=0;
bool tx_vht=false;
uint64_t rx_bytes=0;
uint64_t tx_bytes=0;
uint64_t rx_duration=0;
uint64_t tx_duration=0;
uint64_t rx_packets=0;
uint64_t tx_packets=0;
std::string ipv4;
std::string ipv6;
uint64_t channel_width=0;
int64_t noise=0;
uint64_t tx_power=0;
uint64_t channel=0;
uint64_t active_ms=0;
uint64_t busy_ms=0;
uint64_t receive_ms=0;
std::string mode;
int64_t ack_signal=0;
int64_t ack_signal_avg=0;
uint64_t connected=0;
uint64_t inactive=0;
uint64_t tx_retries=0;
std::string venue_id;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
}
}

View File

@@ -5,208 +5,208 @@
#include "RESTAPI_CertObjects.h" #include "RESTAPI_CertObjects.h"
#include "framework/RESTAPI_utils.h" #include "framework/RESTAPI_utils.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json; using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::field_to_json;
namespace OpenWifi::CertObjects { namespace OpenWifi::CertObjects {
void CertificateEntry::to_json(Poco::JSON::Object &Obj) const { void CertificateEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id); field_to_json(Obj, "id", id);
field_to_json(Obj,"entity", entity); field_to_json(Obj, "entity", entity);
field_to_json(Obj,"creator", creator); field_to_json(Obj, "creator", creator);
field_to_json(Obj,"type", type); field_to_json(Obj, "type", type);
field_to_json(Obj,"status", status); field_to_json(Obj, "status", status);
field_to_json(Obj,"certificate", certificate); field_to_json(Obj, "certificate", certificate);
field_to_json(Obj,"key", key); field_to_json(Obj, "key", key);
field_to_json(Obj,"devid", devid); field_to_json(Obj, "devid", devid);
field_to_json(Obj,"cas", cas); field_to_json(Obj, "cas", cas);
field_to_json(Obj,"manufacturer", manufacturer); field_to_json(Obj, "manufacturer", manufacturer);
field_to_json(Obj,"model", model); field_to_json(Obj, "model", model);
field_to_json(Obj,"redirector", redirector); field_to_json(Obj, "redirector", redirector);
field_to_json(Obj,"commonName", commonName); field_to_json(Obj, "commonName", commonName);
field_to_json(Obj,"certificateId", certificateId); field_to_json(Obj, "certificateId", certificateId);
field_to_json(Obj,"batch", batch); field_to_json(Obj, "batch", batch);
field_to_json(Obj,"created", created); field_to_json(Obj, "created", created);
field_to_json(Obj,"modified", modified); field_to_json(Obj, "modified", modified);
field_to_json(Obj,"revoked", revoked); field_to_json(Obj, "revoked", revoked);
field_to_json(Obj,"revokeCount", revokeCount); field_to_json(Obj, "revokeCount", revokeCount);
field_to_json(Obj,"synched", synched); field_to_json(Obj, "synched", synched);
field_to_json(Obj,"expiryDate", expiryDate); field_to_json(Obj, "expiryDate", expiryDate);
} }
bool CertificateEntry::from_json(const Poco::JSON::Object::Ptr &Obj) { bool CertificateEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"id", id); field_from_json(Obj, "id", id);
field_from_json(Obj,"entity", entity); field_from_json(Obj, "entity", entity);
field_from_json(Obj,"creator", creator); field_from_json(Obj, "creator", creator);
field_from_json(Obj,"type", type); field_from_json(Obj, "type", type);
field_from_json(Obj,"status", status); field_from_json(Obj, "status", status);
field_from_json(Obj,"certificate", certificate); field_from_json(Obj, "certificate", certificate);
field_from_json(Obj,"key", key); field_from_json(Obj, "key", key);
field_from_json(Obj,"devid", devid); field_from_json(Obj, "devid", devid);
field_from_json(Obj,"cas", cas); field_from_json(Obj, "cas", cas);
field_from_json(Obj,"manufacturer", manufacturer); field_from_json(Obj, "manufacturer", manufacturer);
field_from_json(Obj,"model", model); field_from_json(Obj, "model", model);
field_from_json(Obj,"redirector", redirector); field_from_json(Obj, "redirector", redirector);
field_from_json(Obj,"commonName", commonName); field_from_json(Obj, "commonName", commonName);
field_from_json(Obj,"certificateId", certificateId); field_from_json(Obj, "certificateId", certificateId);
field_from_json(Obj,"batch", batch); field_from_json(Obj, "batch", batch);
field_from_json(Obj,"created", created); field_from_json(Obj, "created", created);
field_from_json(Obj,"modified", modified); field_from_json(Obj, "modified", modified);
field_from_json(Obj,"revoked", revoked); field_from_json(Obj, "revoked", revoked);
field_from_json(Obj,"revokeCount", revokeCount); field_from_json(Obj, "revokeCount", revokeCount);
field_from_json(Obj,"synched", synched); field_from_json(Obj, "synched", synched);
field_from_json(Obj,"expiryDate", expiryDate); field_from_json(Obj, "expiryDate", expiryDate);
return true; return true;
} catch (...) { } catch (...) {
} }
return false; return false;
} }
void EntityEntry::to_json(Poco::JSON::Object &Obj) const { void EntityEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id); field_to_json(Obj, "id", id);
field_to_json(Obj,"creator", creator); field_to_json(Obj, "creator", creator);
field_to_json(Obj,"name", name); field_to_json(Obj, "name", name);
field_to_json(Obj,"description", description); field_to_json(Obj, "description", description);
field_to_json(Obj,"defaultRedirector", defaultRedirector); field_to_json(Obj, "defaultRedirector", defaultRedirector);
field_to_json(Obj,"apiKey", apiKey); field_to_json(Obj, "apiKey", apiKey);
field_to_json(Obj,"serverEnrollmentProfile", serverEnrollmentProfile); field_to_json(Obj, "serverEnrollmentProfile", serverEnrollmentProfile);
field_to_json(Obj,"clientEnrollmentProfile", clientEnrollmentProfile); field_to_json(Obj, "clientEnrollmentProfile", clientEnrollmentProfile);
field_to_json(Obj,"organization", organization); field_to_json(Obj, "organization", organization);
field_to_json(Obj,"created", created); field_to_json(Obj, "created", created);
field_to_json(Obj,"modified", modified); field_to_json(Obj, "modified", modified);
field_to_json(Obj,"suspended", suspended); field_to_json(Obj, "suspended", suspended);
field_to_json(Obj,"deleted", deleted); field_to_json(Obj, "deleted", deleted);
field_to_json(Obj,"notes", notes); field_to_json(Obj, "notes", notes);
} }
bool EntityEntry::from_json(const Poco::JSON::Object::Ptr &Obj) { bool EntityEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"id", id); field_from_json(Obj, "id", id);
field_from_json(Obj,"creator", creator); field_from_json(Obj, "creator", creator);
field_from_json(Obj,"name", name); field_from_json(Obj, "name", name);
field_from_json(Obj,"description", description); field_from_json(Obj, "description", description);
field_from_json(Obj,"defaultRedirector", defaultRedirector); field_from_json(Obj, "defaultRedirector", defaultRedirector);
field_from_json(Obj,"apiKey", apiKey); field_from_json(Obj, "apiKey", apiKey);
field_from_json(Obj,"serverEnrollmentProfile", serverEnrollmentProfile); field_from_json(Obj, "serverEnrollmentProfile", serverEnrollmentProfile);
field_from_json(Obj,"clientEnrollmentProfile", clientEnrollmentProfile); field_from_json(Obj, "clientEnrollmentProfile", clientEnrollmentProfile);
field_from_json(Obj,"organization", organization); field_from_json(Obj, "organization", organization);
field_from_json(Obj,"created", created); field_from_json(Obj, "created", created);
field_from_json(Obj,"modified", modified); field_from_json(Obj, "modified", modified);
field_from_json(Obj,"suspended", suspended); field_from_json(Obj, "suspended", suspended);
field_from_json(Obj,"deleted", deleted); field_from_json(Obj, "deleted", deleted);
field_from_json(Obj,"notes", notes); field_from_json(Obj, "notes", notes);
return true; return true;
} catch (...) { } catch (...) {
} }
return false; return false;
} }
void BatchEntry::to_json(Poco::JSON::Object &Obj) const { void BatchEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id); field_to_json(Obj, "id", id);
field_to_json(Obj,"entity", entity); field_to_json(Obj, "entity", entity);
field_to_json(Obj,"creator", creator); field_to_json(Obj, "creator", creator);
field_to_json(Obj,"name", name); field_to_json(Obj, "name", name);
field_to_json(Obj,"description", description); field_to_json(Obj, "description", description);
field_to_json(Obj,"manufacturer", manufacturer); field_to_json(Obj, "manufacturer", manufacturer);
field_to_json(Obj,"model", model); field_to_json(Obj, "model", model);
field_to_json(Obj,"redirector", redirector); field_to_json(Obj, "redirector", redirector);
field_to_json(Obj,"commonNames", commonNames); field_to_json(Obj, "commonNames", commonNames);
field_to_json(Obj,"jobHistory", jobHistory); field_to_json(Obj, "jobHistory", jobHistory);
field_to_json(Obj,"notes", notes); field_to_json(Obj, "notes", notes);
field_to_json(Obj,"submitted", submitted); field_to_json(Obj, "submitted", submitted);
field_to_json(Obj,"started", started); field_to_json(Obj, "started", started);
field_to_json(Obj,"completed", completed); field_to_json(Obj, "completed", completed);
field_to_json(Obj,"modified", modified); field_to_json(Obj, "modified", modified);
} }
bool BatchEntry::from_json(const Poco::JSON::Object::Ptr &Obj) { bool BatchEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"id", id); field_from_json(Obj, "id", id);
field_from_json(Obj,"entity", entity); field_from_json(Obj, "entity", entity);
field_from_json(Obj,"creator", creator); field_from_json(Obj, "creator", creator);
field_from_json(Obj,"name", name); field_from_json(Obj, "name", name);
field_from_json(Obj,"description", description); field_from_json(Obj, "description", description);
field_from_json(Obj,"manufacturer", manufacturer); field_from_json(Obj, "manufacturer", manufacturer);
field_from_json(Obj,"model", model); field_from_json(Obj, "model", model);
field_from_json(Obj,"redirector", redirector); field_from_json(Obj, "redirector", redirector);
field_from_json(Obj,"commonNames", commonNames); field_from_json(Obj, "commonNames", commonNames);
field_from_json(Obj,"jobHistory", jobHistory); field_from_json(Obj, "jobHistory", jobHistory);
field_from_json(Obj,"notes", notes); field_from_json(Obj, "notes", notes);
field_from_json(Obj,"submitted", submitted); field_from_json(Obj, "submitted", submitted);
field_from_json(Obj,"started", started); field_from_json(Obj, "started", started);
field_from_json(Obj,"completed", completed); field_from_json(Obj, "completed", completed);
field_from_json(Obj,"modified", modified); field_from_json(Obj, "modified", modified);
return true; return true;
} catch (...) { } catch (...) {
} }
return false; return false;
} }
void JobEntry::to_json(Poco::JSON::Object &Obj) const { void JobEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id); field_to_json(Obj, "id", id);
field_to_json(Obj,"entity", entity); field_to_json(Obj, "entity", entity);
field_to_json(Obj,"creator", creator); field_to_json(Obj, "creator", creator);
field_to_json(Obj,"batch", batch); field_to_json(Obj, "batch", batch);
field_to_json(Obj,"commonNames", commonNames); field_to_json(Obj, "commonNames", commonNames);
field_to_json(Obj,"completedNames", completedNames); field_to_json(Obj, "completedNames", completedNames);
field_to_json(Obj,"errorNames", errorNames); field_to_json(Obj, "errorNames", errorNames);
field_to_json(Obj,"status", status); field_to_json(Obj, "status", status);
field_to_json(Obj,"command", command); field_to_json(Obj, "command", command);
field_to_json(Obj,"parameters", parameters); field_to_json(Obj, "parameters", parameters);
field_to_json(Obj,"submitted", submitted); field_to_json(Obj, "submitted", submitted);
field_to_json(Obj,"started", started); field_to_json(Obj, "started", started);
field_to_json(Obj,"completed", completed); field_to_json(Obj, "completed", completed);
field_to_json(Obj,"requesterUsername", requesterUsername); field_to_json(Obj, "requesterUsername", requesterUsername);
} }
bool JobEntry::from_json(const Poco::JSON::Object::Ptr &Obj) { bool JobEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"id", id); field_from_json(Obj, "id", id);
field_from_json(Obj,"entity", entity); field_from_json(Obj, "entity", entity);
field_from_json(Obj,"creator", creator); field_from_json(Obj, "creator", creator);
field_from_json(Obj,"batch", batch); field_from_json(Obj, "batch", batch);
field_from_json(Obj,"commonNames", commonNames); field_from_json(Obj, "commonNames", commonNames);
field_from_json(Obj,"completedNames", completedNames); field_from_json(Obj, "completedNames", completedNames);
field_from_json(Obj,"errorNames", errorNames); field_from_json(Obj, "errorNames", errorNames);
field_from_json(Obj,"status", status); field_from_json(Obj, "status", status);
field_from_json(Obj,"command", command); field_from_json(Obj, "command", command);
field_from_json(Obj,"parameters", parameters); field_from_json(Obj, "parameters", parameters);
field_from_json(Obj,"submitted", submitted); field_from_json(Obj, "submitted", submitted);
field_from_json(Obj,"started", started); field_from_json(Obj, "started", started);
field_from_json(Obj,"completed", completed); field_from_json(Obj, "completed", completed);
field_from_json(Obj,"requesterUsername", requesterUsername); field_from_json(Obj, "requesterUsername", requesterUsername);
return true; return true;
} catch (...) { } catch (...) {
} }
return false; return false;
} }
void DashBoardYearlyStats::to_json(Poco::JSON::Object &Obj) const { void DashBoardYearlyStats::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "year", year); field_to_json(Obj, "year", year);
field_to_json(Obj, "activeCerts", activeCerts); field_to_json(Obj, "activeCerts", activeCerts);
field_to_json(Obj, "revokedCerts", revokedCerts); field_to_json(Obj, "revokedCerts", revokedCerts);
} }
void Dashboard::to_json(Poco::JSON::Object &Obj) const { void Dashboard::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"snapshot", snapshot); field_to_json(Obj, "snapshot", snapshot);
field_to_json(Obj,"numberOfIssuedCerts", numberOfIssuedCerts); field_to_json(Obj, "numberOfIssuedCerts", numberOfIssuedCerts);
field_to_json(Obj,"numberOfRevokedCerts", numberOfRevokedCerts); field_to_json(Obj, "numberOfRevokedCerts", numberOfRevokedCerts);
field_to_json(Obj,"activeCertsPerOrganization", activeCertsPerOrganization); field_to_json(Obj, "activeCertsPerOrganization", activeCertsPerOrganization);
field_to_json(Obj,"revokedCertsPerOrganization", revokedCertsPerOrganization); field_to_json(Obj, "revokedCertsPerOrganization", revokedCertsPerOrganization);
field_to_json(Obj,"numberOfRedirectors", numberOfRedirectors); field_to_json(Obj, "numberOfRedirectors", numberOfRedirectors);
field_to_json(Obj,"deviceTypes", deviceTypes); field_to_json(Obj, "deviceTypes", deviceTypes);
field_to_json(Obj,"monthlyNumberOfCerts", monthlyNumberOfCerts); field_to_json(Obj, "monthlyNumberOfCerts", monthlyNumberOfCerts);
field_to_json(Obj,"monthlyNumberOfCertsPerOrgPerYear", monthlyNumberOfCertsPerOrgPerYear); field_to_json(Obj, "monthlyNumberOfCertsPerOrgPerYear", monthlyNumberOfCertsPerOrgPerYear);
} }
void Dashboard::reset() { void Dashboard::reset() {
snapshot=0; snapshot = 0;
numberOfRevokedCerts = numberOfIssuedCerts = 0; numberOfRevokedCerts = numberOfIssuedCerts = 0;
activeCertsPerOrganization.clear(); activeCertsPerOrganization.clear();
revokedCertsPerOrganization.clear(); revokedCertsPerOrganization.clear();
numberOfRedirectors.clear(); numberOfRedirectors.clear();
deviceTypes.clear(); deviceTypes.clear();
monthlyNumberOfCerts.clear(); monthlyNumberOfCerts.clear();
monthlyNumberOfCertsPerOrgPerYear.clear(); monthlyNumberOfCertsPerOrgPerYear.clear();
} }
} } // namespace OpenWifi::CertObjects

View File

@@ -4,121 +4,121 @@
#pragma once #pragma once
#include <string>
#include "framework/OpenWifiTypes.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h" #include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "framework/OpenWifiTypes.h"
#include <string>
namespace OpenWifi::CertObjects { namespace OpenWifi::CertObjects {
struct CertificateEntry { struct CertificateEntry {
OpenWifi::Types::UUID_t id; OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t entity; OpenWifi::Types::UUID_t entity;
OpenWifi::Types::UUID_t creator; OpenWifi::Types::UUID_t creator;
std::string type; std::string type;
std::string status; std::string status;
std::string certificate; std::string certificate;
std::string key; std::string key;
std::string devid; std::string devid;
std::string cas; std::string cas;
std::string manufacturer; std::string manufacturer;
std::string model; std::string model;
std::string redirector; std::string redirector;
std::string commonName; std::string commonName;
std::string certificateId; std::string certificateId;
OpenWifi::Types::UUID_t batch; OpenWifi::Types::UUID_t batch;
uint64_t created = 0; uint64_t created = 0;
uint64_t modified = 0; uint64_t modified = 0;
uint64_t revoked = 0; uint64_t revoked = 0;
uint64_t revokeCount = 0; uint64_t revokeCount = 0;
uint64_t synched = 0; uint64_t synched = 0;
uint64_t expiryDate = 0 ; uint64_t expiryDate = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct EntityEntry { struct EntityEntry {
OpenWifi::Types::UUID_t id; OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t creator; OpenWifi::Types::UUID_t creator;
std::string name; std::string name;
std::string description; std::string description;
std::string defaultRedirector; std::string defaultRedirector;
std::string apiKey; std::string apiKey;
std::string serverEnrollmentProfile; std::string serverEnrollmentProfile;
std::string clientEnrollmentProfile; std::string clientEnrollmentProfile;
std::string organization; std::string organization;
SecurityObjects::NoteInfoVec notes; SecurityObjects::NoteInfoVec notes;
bool suspended=false; bool suspended = false;
bool deleted=false; bool deleted = false;
uint64_t created = 0 ; uint64_t created = 0;
uint64_t modified = 0 ; uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct BatchEntry { struct BatchEntry {
OpenWifi::Types::UUID_t id; OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t entity; OpenWifi::Types::UUID_t entity;
OpenWifi::Types::UUID_t creator; OpenWifi::Types::UUID_t creator;
std::string name; std::string name;
std::string description; std::string description;
std::string manufacturer; std::string manufacturer;
std::string model; std::string model;
std::string redirector; std::string redirector;
std::vector<std::string> commonNames; std::vector<std::string> commonNames;
std::vector<std::string> jobHistory; std::vector<std::string> jobHistory;
SecurityObjects::NoteInfoVec notes; SecurityObjects::NoteInfoVec notes;
uint64_t submitted = 0 ; uint64_t submitted = 0;
uint64_t started = 0 ; uint64_t started = 0;
uint64_t completed = 0 ; uint64_t completed = 0;
uint64_t modified = 0 ; uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct JobEntry { struct JobEntry {
OpenWifi::Types::UUID_t id; OpenWifi::Types::UUID_t id;
OpenWifi::Types::UUID_t entity; OpenWifi::Types::UUID_t entity;
OpenWifi::Types::UUID_t creator; OpenWifi::Types::UUID_t creator;
OpenWifi::Types::UUID_t batch; OpenWifi::Types::UUID_t batch;
std::string command; std::string command;
OpenWifi::Types::StringVec commonNames; OpenWifi::Types::StringVec commonNames;
OpenWifi::Types::StringVec completedNames; OpenWifi::Types::StringVec completedNames;
OpenWifi::Types::StringVec errorNames; OpenWifi::Types::StringVec errorNames;
Types::StringPairVec parameters; Types::StringPairVec parameters;
std::string status; std::string status;
uint64_t submitted=0; uint64_t submitted = 0;
uint64_t started=0; uint64_t started = 0;
uint64_t completed=0; uint64_t completed = 0;
std::string requesterUsername; std::string requesterUsername;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DashBoardYearlyStats { struct DashBoardYearlyStats {
uint64_t year=0; uint64_t year = 0;
OpenWifi::Types::Counted3DMapSII activeCerts; OpenWifi::Types::Counted3DMapSII activeCerts;
OpenWifi::Types::Counted3DMapSII revokedCerts; OpenWifi::Types::Counted3DMapSII revokedCerts;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct Dashboard { struct Dashboard {
uint64_t snapshot=0; uint64_t snapshot = 0;
uint64_t numberOfIssuedCerts=0; uint64_t numberOfIssuedCerts = 0;
uint64_t numberOfRevokedCerts=0; uint64_t numberOfRevokedCerts = 0;
OpenWifi::Types::CountedMap activeCertsPerOrganization; OpenWifi::Types::CountedMap activeCertsPerOrganization;
OpenWifi::Types::CountedMap revokedCertsPerOrganization; OpenWifi::Types::CountedMap revokedCertsPerOrganization;
OpenWifi::Types::CountedMap numberOfRedirectors; OpenWifi::Types::CountedMap numberOfRedirectors;
OpenWifi::Types::CountedMap deviceTypes; OpenWifi::Types::CountedMap deviceTypes;
OpenWifi::Types::CountedMap monthlyNumberOfCerts; OpenWifi::Types::CountedMap monthlyNumberOfCerts;
std::vector<DashBoardYearlyStats> monthlyNumberOfCertsPerOrgPerYear; std::vector<DashBoardYearlyStats> monthlyNumberOfCertsPerOrgPerYear;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
void reset(); void reset();
}; };
} } // namespace OpenWifi::CertObjects

View File

@@ -6,305 +6,293 @@
#include "framework/RESTAPI_utils.h" #include "framework/RESTAPI_utils.h"
#include "framework/utils.h" #include "framework/utils.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json; using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::field_to_json;
namespace OpenWifi::FMSObjects { namespace OpenWifi::FMSObjects {
void Firmware::to_json(Poco::JSON::Object &Obj) const { void Firmware::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id); field_to_json(Obj, "id", id);
field_to_json(Obj, "release", release); field_to_json(Obj, "release", release);
field_to_json(Obj, "deviceType", deviceType); field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "description", description); field_to_json(Obj, "description", description);
field_to_json(Obj, "revision", revision); field_to_json(Obj, "revision", revision);
field_to_json(Obj, "uri", uri); field_to_json(Obj, "uri", uri);
field_to_json(Obj, "image", image); field_to_json(Obj, "image", image);
field_to_json(Obj, "imageDate", imageDate); field_to_json(Obj, "imageDate", imageDate);
field_to_json(Obj, "size", size); field_to_json(Obj, "size", size);
field_to_json(Obj, "downloadCount", downloadCount); field_to_json(Obj, "downloadCount", downloadCount);
field_to_json(Obj, "firmwareHash", firmwareHash); field_to_json(Obj, "firmwareHash", firmwareHash);
field_to_json(Obj, "owner", owner); field_to_json(Obj, "owner", owner);
field_to_json(Obj, "location", location); field_to_json(Obj, "location", location);
field_to_json(Obj, "uploader", uploader); field_to_json(Obj, "uploader", uploader);
field_to_json(Obj, "digest", digest); field_to_json(Obj, "digest", digest);
field_to_json(Obj, "latest", latest); field_to_json(Obj, "latest", latest);
field_to_json(Obj, "notes", notes); field_to_json(Obj, "notes", notes);
field_to_json(Obj, "created", created); field_to_json(Obj, "created", created);
}; };
bool Firmware::from_json(const Poco::JSON::Object::Ptr &Obj) { bool Firmware::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj, "id", id); field_from_json(Obj, "id", id);
field_from_json(Obj, "release", release); field_from_json(Obj, "release", release);
field_from_json(Obj, "deviceType", deviceType); field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "description", description); field_from_json(Obj, "description", description);
field_from_json(Obj, "revision", revision); field_from_json(Obj, "revision", revision);
field_from_json(Obj, "uri", uri); field_from_json(Obj, "uri", uri);
field_from_json(Obj, "image", image); field_from_json(Obj, "image", image);
field_from_json(Obj, "imageDate", imageDate); field_from_json(Obj, "imageDate", imageDate);
field_from_json(Obj, "size", size); field_from_json(Obj, "size", size);
field_from_json(Obj, "downloadCount", downloadCount); field_from_json(Obj, "downloadCount", downloadCount);
field_from_json(Obj, "firmwareHash", firmwareHash); field_from_json(Obj, "firmwareHash", firmwareHash);
field_from_json(Obj, "owner", owner); field_from_json(Obj, "owner", owner);
field_from_json(Obj, "location", location); field_from_json(Obj, "location", location);
field_from_json(Obj, "uploader", uploader); field_from_json(Obj, "uploader", uploader);
field_from_json(Obj, "digest", digest); field_from_json(Obj, "digest", digest);
field_from_json(Obj, "latest", latest); field_from_json(Obj, "latest", latest);
field_from_json(Obj, "notes", notes); field_from_json(Obj, "notes", notes);
field_from_json(Obj, "created", created); field_from_json(Obj, "created", created);
return true; return true;
} catch (...) { } catch (...) {
}
return true;
}
} void FirmwareList::to_json(Poco::JSON::Object &Obj) const {
return true; field_to_json(Obj, "firmwares", firmwares);
} }
void FirmwareList::to_json(Poco::JSON::Object &Obj) const { bool FirmwareList::from_json(const Poco::JSON::Object::Ptr &Obj) {
field_to_json(Obj,"firmwares",firmwares); try {
} field_from_json(Obj, "firmwares", firmwares);
return true;
} catch (...) {
}
return false;
}
bool FirmwareList::from_json(const Poco::JSON::Object::Ptr &Obj) { void DeviceType::to_json(Poco::JSON::Object &Obj) const {
try { field_to_json(Obj, "id", id);
field_from_json(Obj, "firmwares", firmwares); field_to_json(Obj, "deviceType", deviceType);
return true; field_to_json(Obj, "manufacturer", manufacturer);
} catch (...) { field_to_json(Obj, "model", model);
field_to_json(Obj, "policy", policy);
field_to_json(Obj, "notes", notes);
field_to_json(Obj, "lastUpdate", lastUpdate);
field_to_json(Obj, "created", created);
field_to_json(Obj, "id", id);
field_to_json(Obj, "id", id);
field_to_json(Obj, "id", id);
}
} bool DeviceType::from_json(const Poco::JSON::Object::Ptr &Obj) {
return false; try {
} field_from_json(Obj, "id", id);
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "manufacturer", manufacturer);
field_from_json(Obj, "model", model);
field_from_json(Obj, "policy", policy);
field_from_json(Obj, "notes", notes);
field_from_json(Obj, "lastUpdate", lastUpdate);
field_from_json(Obj, "created", created);
field_from_json(Obj, "id", id);
field_from_json(Obj, "id", id);
field_from_json(Obj, "id", id);
return true;
} catch (...) {
}
return false;
}
void DeviceType::to_json(Poco::JSON::Object &Obj) const { void DeviceTypeList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id); field_to_json(Obj, "deviceTypes", deviceTypes);
field_to_json(Obj, "deviceType", deviceType); }
field_to_json(Obj, "manufacturer", manufacturer);
field_to_json(Obj, "model", model);
field_to_json(Obj, "policy", policy);
field_to_json(Obj, "notes", notes);
field_to_json(Obj, "lastUpdate", lastUpdate);
field_to_json(Obj, "created", created);
field_to_json(Obj, "id", id);
field_to_json(Obj, "id", id);
field_to_json(Obj, "id", id);
}
bool DeviceType::from_json(const Poco::JSON::Object::Ptr &Obj) { bool DeviceTypeList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj, "id", id); field_from_json(Obj, "deviceTypes", deviceTypes);
field_from_json(Obj, "deviceType", deviceType); return true;
field_from_json(Obj, "manufacturer", manufacturer); } catch (...) {
field_from_json(Obj, "model", model); }
field_from_json(Obj, "policy", policy); return false;
field_from_json(Obj, "notes", notes); }
field_from_json(Obj, "lastUpdate", lastUpdate);
field_from_json(Obj, "created", created);
field_from_json(Obj, "id", id);
field_from_json(Obj, "id", id);
field_from_json(Obj, "id", id);
return true;
} catch (...) {
} void RevisionHistoryEntry::to_json(Poco::JSON::Object &Obj) const {
return false; field_to_json(Obj, "id", id);
} field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "fromRelease", fromRelease);
field_to_json(Obj, "toRelease", toRelease);
field_to_json(Obj, "commandUUID", commandUUID);
field_to_json(Obj, "revisionId", revisionId);
field_to_json(Obj, "upgraded", upgraded);
}
void DeviceTypeList::to_json(Poco::JSON::Object &Obj) const { bool RevisionHistoryEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
field_to_json(Obj,"deviceTypes", deviceTypes); try {
} field_from_json(Obj, "id", id);
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "fromRelease", fromRelease);
field_from_json(Obj, "toRelease", toRelease);
field_from_json(Obj, "commandUUID", commandUUID);
field_from_json(Obj, "revisionId", revisionId);
field_from_json(Obj, "upgraded", upgraded);
return true;
} catch (...) {
}
return false;
}
bool DeviceTypeList::from_json(const Poco::JSON::Object::Ptr &Obj) { void RevisionHistoryEntryList::to_json(Poco::JSON::Object &Obj) const {
try { field_to_json(Obj, "deviceTypes", history);
field_from_json(Obj,"deviceTypes", deviceTypes); }
return true;
} catch(...) {
} bool RevisionHistoryEntryList::from_json(const Poco::JSON::Object::Ptr &Obj) {
return false; try {
} field_from_json(Obj, "deviceTypes", history);
return true;
} catch (...) {
}
return false;
}
void RevisionHistoryEntry::to_json(Poco::JSON::Object &Obj) const { void FirmwareAgeDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id); field_to_json(Obj, "latestId", latestId);
field_to_json(Obj, "serialNumber", serialNumber); field_to_json(Obj, "image", image);
field_to_json(Obj, "fromRelease", fromRelease); field_to_json(Obj, "imageDate", imageDate);
field_to_json(Obj, "toRelease", toRelease); field_to_json(Obj, "revision", revision);
field_to_json(Obj, "commandUUID", commandUUID); field_to_json(Obj, "uri", uri);
field_to_json(Obj, "revisionId", revisionId); field_to_json(Obj, "age", age);
field_to_json(Obj, "upgraded", upgraded); field_to_json(Obj, "latest", latest);
} }
bool RevisionHistoryEntry::from_json(const Poco::JSON::Object::Ptr &Obj) { bool FirmwareAgeDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj, "id", id); field_from_json(Obj, "latestId", latestId);
field_from_json(Obj, "serialNumber", serialNumber); field_from_json(Obj, "image", image);
field_from_json(Obj, "fromRelease", fromRelease); field_from_json(Obj, "imageDate", imageDate);
field_from_json(Obj, "toRelease", toRelease); field_from_json(Obj, "revision", revision);
field_from_json(Obj, "commandUUID", commandUUID); field_from_json(Obj, "uri", uri);
field_from_json(Obj, "revisionId", revisionId); field_from_json(Obj, "age", age);
field_from_json(Obj, "upgraded", upgraded); field_from_json(Obj, "latest", latest);
return true; return true;
} catch(...) { } catch (...) {
}
return false;
}
} void DeviceConnectionInformation::to_json(Poco::JSON::Object &Obj) const {
return false; field_to_json(Obj, "serialNumber", serialNumber);
} field_to_json(Obj, "revision", revision);
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "endPoint", endPoint);
field_to_json(Obj, "lastUpdate", lastUpdate);
field_to_json(Obj, "status", status);
}
void RevisionHistoryEntryList::to_json(Poco::JSON::Object &Obj) const { bool DeviceConnectionInformation::from_json(const Poco::JSON::Object::Ptr &Obj) {
field_to_json(Obj,"deviceTypes", history); try {
} field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "endPoint", endPoint);
field_from_json(Obj, "lastUpdate", lastUpdate);
field_from_json(Obj, "status", status);
return true;
} catch (...) {
}
return false;
}
bool RevisionHistoryEntryList::from_json(const Poco::JSON::Object::Ptr &Obj) { void DeviceReport::to_json(Poco::JSON::Object &Obj) const {
try { field_to_json(Obj, "ouis", OUI_);
field_from_json(Obj,"deviceTypes", history); field_to_json(Obj, "revisions", Revisions_);
return true; field_to_json(Obj, "deviceTypes", DeviceTypes_);
} catch(...) { field_to_json(Obj, "status", Status_);
field_to_json(Obj, "endPoints", EndPoints_);
field_to_json(Obj, "usingLatest", UsingLatest_);
field_to_json(Obj, "unknownFirmwares", UnknownFirmwares_);
field_to_json(Obj, "snapshot", snapshot);
field_to_json(Obj, "numberOfDevices", numberOfDevices);
field_to_json(Obj, "totalSecondsOld", totalSecondsOld_);
}
} void DeviceReport::reset() {
return false; OUI_.clear();
} Revisions_.clear();
DeviceTypes_.clear();
Status_.clear();
EndPoints_.clear();
UsingLatest_.clear();
UnknownFirmwares_.clear();
totalSecondsOld_.clear();
numberOfDevices = 0;
snapshot = Utils::Now();
}
void FirmwareAgeDetails::to_json(Poco::JSON::Object &Obj) const { bool DeviceReport::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) {
field_to_json(Obj,"latestId", latestId); try {
field_to_json(Obj,"image", image);
field_to_json(Obj,"imageDate", imageDate);
field_to_json(Obj,"revision", revision);
field_to_json(Obj,"uri", uri);
field_to_json(Obj,"age", age);
field_to_json(Obj,"latest",latest);
}
bool FirmwareAgeDetails::from_json(const Poco::JSON::Object::Ptr &Obj) { return true;
try { } catch (...) {
field_from_json(Obj,"latestId", latestId); }
field_from_json(Obj,"image", image); return false;
field_from_json(Obj,"imageDate", imageDate); }
field_from_json(Obj,"revision", revision);
field_from_json(Obj,"uri", uri);
field_from_json(Obj,"age", age);
field_from_json(Obj,"latest", latest);
return true;
} catch(...) {
} void DeviceInformation::to_json(Poco::JSON::Object &Obj) const {
return false; field_to_json(Obj, "serialNumber", serialNumber);
} field_to_json(Obj, "history", history);
field_to_json(Obj, "currentFirmware", currentFirmware);
field_to_json(Obj, "currentFirmwareDate", currentFirmwareDate);
field_to_json(Obj, "latestFirmware", latestFirmware);
field_to_json(Obj, "latestFirmwareDate", latestFirmwareDate);
field_to_json(Obj, "latestFirmwareAvailable", latestFirmwareAvailable);
field_to_json(Obj, "latestFirmwareURI", latestFirmwareURI);
}
void DeviceConnectionInformation::to_json(Poco::JSON::Object &Obj) const { bool DeviceInformation::from_json(const Poco::JSON::Object::Ptr &Obj) {
field_to_json(Obj, "serialNumber", serialNumber); try {
field_to_json(Obj, "revision", revision); field_from_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "deviceType", deviceType); field_from_json(Obj, "history", history);
field_to_json(Obj, "endPoint", endPoint); field_from_json(Obj, "currentFirmware", currentFirmware);
field_to_json(Obj, "lastUpdate", lastUpdate); field_from_json(Obj, "currentFirmwareDate", currentFirmwareDate);
field_to_json(Obj, "status", status); field_from_json(Obj, "latestFirmware", latestFirmware);
} field_from_json(Obj, "latestFirmwareDate", latestFirmwareDate);
field_from_json(Obj, "latestFirmwareAvailable", latestFirmwareAvailable);
field_from_json(Obj, "latestFirmwareURI", latestFirmwareURI);
return true;
} catch (...) {
}
return false;
}
bool DeviceConnectionInformation::from_json(const Poco::JSON::Object::Ptr &Obj) { void DeviceCurrentInfo::to_json(Poco::JSON::Object &Obj) const {
try { field_to_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "serialNumber", serialNumber); field_to_json(Obj, "revision", revision);
field_from_json(Obj, "revision", revision); field_to_json(Obj, "upgraded", upgraded);
field_from_json(Obj, "deviceType", deviceType); }
field_from_json(Obj, "endPoint", endPoint);
field_from_json(Obj, "lastUpdate", lastUpdate);
field_from_json(Obj, "status", status);
return true;
} catch(...) {
} bool DeviceCurrentInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
return false; try {
} field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "upgraded", upgraded);
return true;
} catch (...) {
}
return false;
}
void DeviceReport::to_json(Poco::JSON::Object &Obj) const { void DeviceCurrentInfoList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "ouis",OUI_); field_to_json(Obj, "devices", devices);
field_to_json(Obj, "revisions", Revisions_); }
field_to_json(Obj, "deviceTypes", DeviceTypes_);
field_to_json(Obj, "status", Status_);
field_to_json(Obj, "endPoints", EndPoints_);
field_to_json(Obj, "usingLatest", UsingLatest_);
field_to_json(Obj, "unknownFirmwares", UnknownFirmwares_);
field_to_json(Obj,"snapshot",snapshot);
field_to_json(Obj,"numberOfDevices",numberOfDevices);
field_to_json(Obj, "totalSecondsOld", totalSecondsOld_);
}
void DeviceReport::reset() { bool DeviceCurrentInfoList::from_json(const Poco::JSON::Object::Ptr &Obj) {
OUI_.clear(); try {
Revisions_.clear(); field_from_json(Obj, "devices", devices);
DeviceTypes_.clear(); return true;
Status_.clear(); } catch (...) {
EndPoints_.clear(); }
UsingLatest_.clear(); return false;
UnknownFirmwares_.clear(); }
totalSecondsOld_.clear();
numberOfDevices = 0 ;
snapshot = Utils::Now();
}
bool DeviceReport::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) { } // namespace OpenWifi::FMSObjects
try {
return true;
} catch (...) {
}
return false;
}
void DeviceInformation::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "serialNumber",serialNumber);
field_to_json(Obj, "history", history);
field_to_json(Obj, "currentFirmware", currentFirmware);
field_to_json(Obj, "currentFirmwareDate", currentFirmwareDate);
field_to_json(Obj, "latestFirmware", latestFirmware);
field_to_json(Obj, "latestFirmwareDate", latestFirmwareDate);
field_to_json(Obj, "latestFirmwareAvailable",latestFirmwareAvailable);
field_to_json(Obj, "latestFirmwareURI",latestFirmwareURI);
}
bool DeviceInformation::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber",serialNumber);
field_from_json(Obj, "history", history);
field_from_json(Obj, "currentFirmware", currentFirmware);
field_from_json(Obj, "currentFirmwareDate", currentFirmwareDate);
field_from_json(Obj, "latestFirmware", latestFirmware);
field_from_json(Obj, "latestFirmwareDate", latestFirmwareDate);
field_from_json(Obj, "latestFirmwareAvailable",latestFirmwareAvailable);
field_from_json(Obj, "latestFirmwareURI",latestFirmwareURI);
return true;
} catch(...) {
}
return false;
}
void DeviceCurrentInfo::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "serialNumber",serialNumber);
field_to_json(Obj, "revision", revision);
field_to_json(Obj, "upgraded", upgraded);
}
bool DeviceCurrentInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber",serialNumber);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "upgraded", upgraded);
return true;
} catch(...) {
}
return false;
}
void DeviceCurrentInfoList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "devices",devices);
}
bool DeviceCurrentInfoList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "devices",devices);
return true;
} catch(...) {
}
return false;
}
}

View File

@@ -11,149 +11,149 @@
namespace OpenWifi::FMSObjects { namespace OpenWifi::FMSObjects {
struct Firmware { struct Firmware {
std::string id; std::string id;
std::string release; std::string release;
std::string deviceType; std::string deviceType;
std::string description; std::string description;
std::string revision; std::string revision;
std::string uri; std::string uri;
std::string image; std::string image;
uint64_t imageDate=0; uint64_t imageDate = 0;
uint64_t size=0; uint64_t size = 0;
uint64_t downloadCount=0; uint64_t downloadCount = 0;
std::string firmwareHash; std::string firmwareHash;
std::string owner; std::string owner;
std::string location; std::string location;
std::string uploader; std::string uploader;
std::string digest; std::string digest;
bool latest=false; bool latest = false;
SecurityObjects::NoteInfoVec notes; SecurityObjects::NoteInfoVec notes;
uint64_t created=0; uint64_t created = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
typedef std::vector<Firmware> FirmwareVec; typedef std::vector<Firmware> FirmwareVec;
struct FirmwareList { struct FirmwareList {
FirmwareVec firmwares; FirmwareVec firmwares;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DeviceType { struct DeviceType {
std::string id; std::string id;
std::string deviceType; std::string deviceType;
std::string manufacturer; std::string manufacturer;
std::string model; std::string model;
std::string policy; std::string policy;
SecurityObjects::NoteInfoVec notes; SecurityObjects::NoteInfoVec notes;
uint64_t lastUpdate=0; uint64_t lastUpdate = 0;
uint64_t created=0; uint64_t created = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
typedef std::vector<DeviceType> DeviceTypeVec; typedef std::vector<DeviceType> DeviceTypeVec;
struct DeviceTypeList { struct DeviceTypeList {
DeviceTypeVec deviceTypes; DeviceTypeVec deviceTypes;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct RevisionHistoryEntry { struct RevisionHistoryEntry {
std::string id; std::string id;
std::string serialNumber; std::string serialNumber;
std::string fromRelease; std::string fromRelease;
std::string toRelease; std::string toRelease;
std::string commandUUID; std::string commandUUID;
std::string revisionId; std::string revisionId;
uint64_t upgraded; uint64_t upgraded;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
typedef std::vector<RevisionHistoryEntry> RevisionHistoryEntryVec; typedef std::vector<RevisionHistoryEntry> RevisionHistoryEntryVec;
struct RevisionHistoryEntryList { struct RevisionHistoryEntryList {
RevisionHistoryEntryVec history; RevisionHistoryEntryVec history;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct FirmwareAgeDetails { struct FirmwareAgeDetails {
std::string latestId; std::string latestId;
std::string image; std::string image;
uint64_t imageDate; uint64_t imageDate;
std::string revision; std::string revision;
std::string uri; std::string uri;
uint64_t age=0; uint64_t age = 0;
bool latest=true; bool latest = true;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DeviceConnectionInformation { struct DeviceConnectionInformation {
std::string serialNumber; std::string serialNumber;
std::string revision; std::string revision;
std::string deviceType; std::string deviceType;
std::string endPoint; std::string endPoint;
uint64_t lastUpdate; uint64_t lastUpdate;
std::string status; std::string status;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DeviceReport { struct DeviceReport {
uint64_t snapshot=0; uint64_t snapshot = 0;
uint64_t numberOfDevices=0; uint64_t numberOfDevices = 0;
Types::CountedMap OUI_; Types::CountedMap OUI_;
Types::CountedMap Revisions_; Types::CountedMap Revisions_;
Types::CountedMap DeviceTypes_; Types::CountedMap DeviceTypes_;
Types::CountedMap Status_; Types::CountedMap Status_;
Types::CountedMap EndPoints_; Types::CountedMap EndPoints_;
Types::CountedMap UsingLatest_; Types::CountedMap UsingLatest_;
Types::CountedMap UnknownFirmwares_; Types::CountedMap UnknownFirmwares_;
Types::CountedMap totalSecondsOld_; Types::CountedMap totalSecondsOld_;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
void reset(); void reset();
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DeviceInformation { struct DeviceInformation {
std::string serialNumber; std::string serialNumber;
RevisionHistoryEntryList history; RevisionHistoryEntryList history;
std::string currentFirmware; std::string currentFirmware;
uint64_t currentFirmwareDate=0; uint64_t currentFirmwareDate = 0;
std::string latestFirmware; std::string latestFirmware;
uint64_t latestFirmwareDate=0; uint64_t latestFirmwareDate = 0;
bool latestFirmwareAvailable; bool latestFirmwareAvailable;
std::string latestFirmwareURI; std::string latestFirmwareURI;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DeviceCurrentInfo { struct DeviceCurrentInfo {
std::string serialNumber; std::string serialNumber;
std::string revision; std::string revision;
uint64_t upgraded=0; uint64_t upgraded = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DeviceCurrentInfoList { struct DeviceCurrentInfoList {
std::vector<DeviceCurrentInfo> devices; std::vector<DeviceCurrentInfo> devices;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
} } // namespace OpenWifi::FMSObjects

View File

@@ -10,7 +10,7 @@
#include "Poco/JSON/Stringifier.h" #include "Poco/JSON/Stringifier.h"
#include "Daemon.h" #include "Daemon.h"
#ifdef TIP_GATEWAY_SERVICE #ifdef TIP_GATEWAY_SERVICE
#include "AP_WS_Server.h" #include "AP_WS_Server.h"
#include "CapabilitiesCache.h" #include "CapabilitiesCache.h"
#endif #endif
@@ -19,41 +19,41 @@
#include "framework/RESTAPI_utils.h" #include "framework/RESTAPI_utils.h"
#include "framework/utils.h" #include "framework/utils.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::EmbedDocument; using OpenWifi::RESTAPI_utils::EmbedDocument;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::field_to_json;
namespace OpenWifi::GWObjects { namespace OpenWifi::GWObjects {
void Device::to_json(Poco::JSON::Object &Obj) const { void Device::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"serialNumber", SerialNumber); field_to_json(Obj, "serialNumber", SerialNumber);
#ifdef TIP_GATEWAY_SERVICE #ifdef TIP_GATEWAY_SERVICE
field_to_json(Obj,"deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible)); field_to_json(Obj, "deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible));
#endif #endif
field_to_json(Obj,"macAddress", MACAddress); field_to_json(Obj, "macAddress", MACAddress);
field_to_json(Obj,"manufacturer", Manufacturer); field_to_json(Obj, "manufacturer", Manufacturer);
field_to_json(Obj,"UUID", UUID); field_to_json(Obj, "UUID", UUID);
EmbedDocument("configuration", Obj, Configuration); EmbedDocument("configuration", Obj, Configuration);
field_to_json(Obj,"notes", Notes); field_to_json(Obj, "notes", Notes);
field_to_json(Obj,"createdTimestamp", CreationTimestamp); field_to_json(Obj, "createdTimestamp", CreationTimestamp);
field_to_json(Obj,"lastConfigurationChange", LastConfigurationChange); field_to_json(Obj, "lastConfigurationChange", LastConfigurationChange);
field_to_json(Obj,"lastConfigurationDownload", LastConfigurationDownload); field_to_json(Obj, "lastConfigurationDownload", LastConfigurationDownload);
field_to_json(Obj,"lastFWUpdate", LastFWUpdate); field_to_json(Obj, "lastFWUpdate", LastFWUpdate);
field_to_json(Obj,"owner", Owner); field_to_json(Obj, "owner", Owner);
field_to_json(Obj,"location", Location); field_to_json(Obj, "location", Location);
field_to_json(Obj,"venue", Venue); field_to_json(Obj, "venue", Venue);
field_to_json(Obj,"firmware", Firmware); field_to_json(Obj, "firmware", Firmware);
field_to_json(Obj,"compatible", Compatible); field_to_json(Obj, "compatible", Compatible);
field_to_json(Obj,"fwUpdatePolicy", FWUpdatePolicy); field_to_json(Obj, "fwUpdatePolicy", FWUpdatePolicy);
field_to_json(Obj,"devicePassword", DevicePassword); field_to_json(Obj, "devicePassword", DevicePassword);
field_to_json(Obj,"subscriber", subscriber); field_to_json(Obj, "subscriber", subscriber);
field_to_json(Obj,"entity", entity); field_to_json(Obj, "entity", entity);
field_to_json(Obj,"modified", modified); field_to_json(Obj, "modified", modified);
field_to_json(Obj,"locale", locale); field_to_json(Obj, "locale", locale);
field_to_json(Obj,"restrictedDevice", restrictedDevice); field_to_json(Obj, "restrictedDevice", restrictedDevice);
field_to_json(Obj,"pendingConfiguration", pendingConfiguration); field_to_json(Obj, "pendingConfiguration", pendingConfiguration);
field_to_json(Obj,"pendingConfigurationCmd", pendingConfigurationCmd); field_to_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd);
field_to_json(Obj,"restrictionDetails", restrictionDetails); field_to_json(Obj, "restrictionDetails", restrictionDetails);
} }
void Device::to_json_with_status(Poco::JSON::Object &Obj) const { void Device::to_json_with_status(Poco::JSON::Object &Obj) const {
@@ -65,39 +65,39 @@ namespace OpenWifi::GWObjects {
if (AP_WS_Server()->GetState(SerialNumber, ConState)) { if (AP_WS_Server()->GetState(SerialNumber, ConState)) {
ConState.to_json(Obj); ConState.to_json(Obj);
} else { } else {
field_to_json(Obj,"ipAddress", ""); field_to_json(Obj, "ipAddress", "");
field_to_json(Obj,"txBytes", (uint64_t) 0); field_to_json(Obj, "txBytes", (uint64_t)0);
field_to_json(Obj,"rxBytes", (uint64_t )0); field_to_json(Obj, "rxBytes", (uint64_t)0);
field_to_json(Obj,"messageCount", (uint64_t )0); field_to_json(Obj, "messageCount", (uint64_t)0);
field_to_json(Obj,"connected", false); field_to_json(Obj, "connected", false);
field_to_json(Obj,"lastContact", ""); field_to_json(Obj, "lastContact", "");
field_to_json(Obj,"verifiedCertificate", "NO_CERTIFICATE"); field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
field_to_json(Obj,"associations_2G", (uint64_t) 0); field_to_json(Obj, "associations_2G", (uint64_t)0);
field_to_json(Obj,"associations_5G", (uint64_t) 0); field_to_json(Obj, "associations_5G", (uint64_t)0);
field_to_json(Obj,"associations_6G", (uint64_t) 0); field_to_json(Obj, "associations_6G", (uint64_t)0);
} }
#endif #endif
} }
bool Device::from_json(const Poco::JSON::Object::Ptr &Obj) { bool Device::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"serialNumber",SerialNumber); field_from_json(Obj, "serialNumber", SerialNumber);
field_from_json(Obj,"deviceType",DeviceType); field_from_json(Obj, "deviceType", DeviceType);
field_from_json(Obj,"macAddress",MACAddress); field_from_json(Obj, "macAddress", MACAddress);
field_from_json(Obj,"configuration",Configuration); field_from_json(Obj, "configuration", Configuration);
field_from_json(Obj,"notes",Notes); field_from_json(Obj, "notes", Notes);
field_from_json(Obj,"manufacturer",Manufacturer); field_from_json(Obj, "manufacturer", Manufacturer);
field_from_json(Obj,"owner",Owner); field_from_json(Obj, "owner", Owner);
field_from_json(Obj,"location",Location); field_from_json(Obj, "location", Location);
field_from_json(Obj,"venue",Venue); field_from_json(Obj, "venue", Venue);
field_from_json(Obj,"compatible",Compatible); field_from_json(Obj, "compatible", Compatible);
field_from_json(Obj,"subscriber", subscriber); field_from_json(Obj, "subscriber", subscriber);
field_from_json(Obj,"entity", entity); field_from_json(Obj, "entity", entity);
field_from_json(Obj,"locale", locale); field_from_json(Obj, "locale", locale);
field_from_json(Obj,"restrictedDevice", restrictedDevice); field_from_json(Obj, "restrictedDevice", restrictedDevice);
field_from_json(Obj,"pendingConfiguration", pendingConfiguration); field_from_json(Obj, "pendingConfiguration", pendingConfiguration);
field_from_json(Obj,"pendingConfigurationCmd", pendingConfigurationCmd); field_from_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd);
field_from_json(Obj,"restrictionDetails", restrictionDetails); field_from_json(Obj, "restrictionDetails", restrictionDetails);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -105,73 +105,74 @@ namespace OpenWifi::GWObjects {
} }
void Device::Print() const { void Device::Print() const {
std::cout << "Device: " << SerialNumber << " DeviceType:" << DeviceType << " MACAddress:" << MACAddress << " Manufacturer:" std::cout << "Device: " << SerialNumber << " DeviceType:" << DeviceType
<< Manufacturer << " " << Configuration << std::endl; << " MACAddress:" << MACAddress << " Manufacturer:" << Manufacturer << " "
<< Configuration << std::endl;
} }
void Statistics::to_json(Poco::JSON::Object &Obj) const { void Statistics::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("data", Obj, Data); EmbedDocument("data", Obj, Data);
field_to_json(Obj,"UUID", UUID); field_to_json(Obj, "UUID", UUID);
field_to_json(Obj,"recorded", Recorded); field_to_json(Obj, "recorded", Recorded);
} }
void Capabilities::to_json(Poco::JSON::Object &Obj) const { void Capabilities::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("capabilities", Obj, Capabilities); EmbedDocument("capabilities", Obj, Capabilities);
field_to_json(Obj,"firstUpdate", FirstUpdate); field_to_json(Obj, "firstUpdate", FirstUpdate);
field_to_json(Obj,"lastUpdate", LastUpdate); field_to_json(Obj, "lastUpdate", LastUpdate);
} }
void DeviceLog::to_json(Poco::JSON::Object &Obj) const { void DeviceLog::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("data", Obj, Data); EmbedDocument("data", Obj, Data);
field_to_json(Obj,"log", Log); field_to_json(Obj, "log", Log);
field_to_json(Obj,"severity", Severity); field_to_json(Obj, "severity", Severity);
field_to_json(Obj,"recorded", Recorded); field_to_json(Obj, "recorded", Recorded);
field_to_json(Obj,"logType", LogType); field_to_json(Obj, "logType", LogType);
field_to_json(Obj,"UUID", UUID); field_to_json(Obj, "UUID", UUID);
} }
void HealthCheck::to_json(Poco::JSON::Object &Obj) const { void HealthCheck::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("values", Obj, Data); EmbedDocument("values", Obj, Data);
field_to_json(Obj,"UUID", UUID); field_to_json(Obj, "UUID", UUID);
field_to_json(Obj,"sanity", Sanity); field_to_json(Obj, "sanity", Sanity);
field_to_json(Obj,"recorded", Recorded); field_to_json(Obj, "recorded", Recorded);
} }
void DefaultConfiguration::to_json(Poco::JSON::Object &Obj) const { void DefaultConfiguration::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("configuration", Obj, Configuration); EmbedDocument("configuration", Obj, Configuration);
field_to_json(Obj,"name", Name); field_to_json(Obj, "name", Name);
field_to_json(Obj,"modelIds", Models); field_to_json(Obj, "modelIds", Models);
field_to_json(Obj,"description", Description); field_to_json(Obj, "description", Description);
field_to_json(Obj,"created", Created); field_to_json(Obj, "created", Created);
field_to_json(Obj,"lastModified", LastModified); field_to_json(Obj, "lastModified", LastModified);
} }
void CommandDetails::to_json(Poco::JSON::Object &Obj) const { void CommandDetails::to_json(Poco::JSON::Object &Obj) const {
EmbedDocument("details", Obj, Details); EmbedDocument("details", Obj, Details);
EmbedDocument("results", Obj, Results); EmbedDocument("results", Obj, Results);
field_to_json(Obj,"UUID", UUID); field_to_json(Obj, "UUID", UUID);
field_to_json(Obj,"serialNumber", SerialNumber); field_to_json(Obj, "serialNumber", SerialNumber);
field_to_json(Obj,"command", Command); field_to_json(Obj, "command", Command);
field_to_json(Obj,"errorText", ErrorText); field_to_json(Obj, "errorText", ErrorText);
field_to_json(Obj,"submittedBy", SubmittedBy); field_to_json(Obj, "submittedBy", SubmittedBy);
field_to_json(Obj,"status", Status); field_to_json(Obj, "status", Status);
field_to_json(Obj,"submitted", Submitted); field_to_json(Obj, "submitted", Submitted);
field_to_json(Obj,"executed", Executed); field_to_json(Obj, "executed", Executed);
field_to_json(Obj,"completed", Completed); field_to_json(Obj, "completed", Completed);
field_to_json(Obj,"when", RunAt); field_to_json(Obj, "when", RunAt);
field_to_json(Obj,"errorCode", ErrorCode); field_to_json(Obj, "errorCode", ErrorCode);
field_to_json(Obj,"custom", Custom); field_to_json(Obj, "custom", Custom);
field_to_json(Obj,"waitingForFile", WaitingForFile); field_to_json(Obj, "waitingForFile", WaitingForFile);
field_to_json(Obj,"attachFile", AttachDate); field_to_json(Obj, "attachFile", AttachDate);
field_to_json(Obj,"executionTime", executionTime); field_to_json(Obj, "executionTime", executionTime);
} }
bool DefaultConfiguration::from_json(const Poco::JSON::Object::Ptr &Obj) { bool DefaultConfiguration::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"name",Name); field_from_json(Obj, "name", Name);
field_from_json(Obj,"configuration",Configuration); field_from_json(Obj, "configuration", Configuration);
field_from_json(Obj,"modelIds",Models); field_from_json(Obj, "modelIds", Models);
field_from_json(Obj,"description",Description); field_from_json(Obj, "description", Description);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -179,18 +180,18 @@ namespace OpenWifi::GWObjects {
} }
void BlackListedDevice::to_json(Poco::JSON::Object &Obj) const { void BlackListedDevice::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"serialNumber", serialNumber); field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj,"author", author); field_to_json(Obj, "author", author);
field_to_json(Obj,"reason", reason); field_to_json(Obj, "reason", reason);
field_to_json(Obj,"created", created); field_to_json(Obj, "created", created);
} }
bool BlackListedDevice::from_json(const Poco::JSON::Object::Ptr &Obj) { bool BlackListedDevice::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"serialNumber",serialNumber); field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj,"author",author); field_from_json(Obj, "author", author);
field_from_json(Obj,"reason",reason); field_from_json(Obj, "reason", reason);
field_from_json(Obj,"created",created); field_from_json(Obj, "created", created);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -198,53 +199,58 @@ namespace OpenWifi::GWObjects {
} }
void ConnectionState::to_json(Poco::JSON::Object &Obj) const { void ConnectionState::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"ipAddress", Address); field_to_json(Obj, "ipAddress", Address);
field_to_json(Obj,"txBytes", TX); field_to_json(Obj, "txBytes", TX);
field_to_json(Obj,"rxBytes", RX); field_to_json(Obj, "rxBytes", RX);
field_to_json(Obj,"messageCount", MessageCount); field_to_json(Obj, "messageCount", MessageCount);
field_to_json(Obj,"UUID", UUID); field_to_json(Obj, "UUID", UUID);
field_to_json(Obj,"connected", Connected); field_to_json(Obj, "connected", Connected);
field_to_json(Obj,"firmware", Firmware); field_to_json(Obj, "firmware", Firmware);
field_to_json(Obj,"lastContact", LastContact); field_to_json(Obj, "lastContact", LastContact);
field_to_json(Obj,"associations_2G", Associations_2G); field_to_json(Obj, "associations_2G", Associations_2G);
field_to_json(Obj,"associations_5G", Associations_5G); field_to_json(Obj, "associations_5G", Associations_5G);
field_to_json(Obj,"associations_6G", Associations_6G); field_to_json(Obj, "associations_6G", Associations_6G);
field_to_json(Obj,"webSocketClients", webSocketClients); field_to_json(Obj, "webSocketClients", webSocketClients);
field_to_json(Obj,"websocketPackets", websocketPackets); field_to_json(Obj, "websocketPackets", websocketPackets);
field_to_json(Obj,"kafkaClients", kafkaClients); field_to_json(Obj, "kafkaClients", kafkaClients);
field_to_json(Obj,"kafkaPackets", kafkaPackets); field_to_json(Obj, "kafkaPackets", kafkaPackets);
field_to_json(Obj,"locale", locale); field_to_json(Obj, "locale", locale);
field_to_json(Obj,"started", started); field_to_json(Obj, "started", started);
field_to_json(Obj,"sessionId", sessionId); field_to_json(Obj, "sessionId", sessionId);
field_to_json(Obj,"connectionCompletionTime", connectionCompletionTime); field_to_json(Obj, "connectionCompletionTime", connectionCompletionTime);
field_to_json(Obj,"totalConnectionTime", Utils::Now() - started); field_to_json(Obj, "totalConnectionTime", Utils::Now() - started);
field_to_json(Obj,"certificateExpiryDate", certificateExpiryDate); field_to_json(Obj, "certificateExpiryDate", certificateExpiryDate);
switch(VerifiedCertificate) { switch (VerifiedCertificate) {
case NO_CERTIFICATE: case NO_CERTIFICATE:
field_to_json(Obj,"verifiedCertificate", "NO_CERTIFICATE"); break; field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
case VALID_CERTIFICATE: break;
field_to_json(Obj,"verifiedCertificate", "VALID_CERTIFICATE"); break; case VALID_CERTIFICATE:
case MISMATCH_SERIAL: field_to_json(Obj, "verifiedCertificate", "VALID_CERTIFICATE");
field_to_json(Obj,"verifiedCertificate", "MISMATCH_SERIAL"); break; break;
case VERIFIED: case MISMATCH_SERIAL:
field_to_json(Obj,"verifiedCertificate", "VERIFIED"); break; field_to_json(Obj, "verifiedCertificate", "MISMATCH_SERIAL");
default: break;
field_to_json(Obj,"verifiedCertificate", "NO_CERTIFICATE"); break; case VERIFIED:
field_to_json(Obj, "verifiedCertificate", "VERIFIED");
break;
default:
field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
break;
} }
} }
void DeviceConnectionStatistics::to_json(Poco::JSON::Object &Obj) const { void DeviceConnectionStatistics::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"averageConnectionTime", averageConnectionTime); field_to_json(Obj, "averageConnectionTime", averageConnectionTime);
field_to_json(Obj,"connectedDevices", connectedDevices ); field_to_json(Obj, "connectedDevices", connectedDevices);
field_to_json(Obj,"connectingDevices", connectingDevices ); field_to_json(Obj, "connectingDevices", connectingDevices);
} }
bool DeviceConnectionStatistics::from_json(const Poco::JSON::Object::Ptr &Obj) { bool DeviceConnectionStatistics::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"averageConnectionTime", averageConnectionTime); field_from_json(Obj, "averageConnectionTime", averageConnectionTime);
field_from_json(Obj,"connectedDevices", connectedDevices ); field_from_json(Obj, "connectedDevices", connectedDevices);
field_from_json(Obj,"connectingDevices", connectingDevices ); field_from_json(Obj, "connectingDevices", connectingDevices);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -252,37 +258,37 @@ namespace OpenWifi::GWObjects {
} }
void RttySessionDetails::to_json(Poco::JSON::Object &Obj) const { void RttySessionDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"serialNumber", SerialNumber); field_to_json(Obj, "serialNumber", SerialNumber);
field_to_json(Obj,"server", Server); field_to_json(Obj, "server", Server);
field_to_json(Obj,"port", Port); field_to_json(Obj, "port", Port);
field_to_json(Obj,"token",Token); field_to_json(Obj, "token", Token);
field_to_json(Obj,"timeout", TimeOut); field_to_json(Obj, "timeout", TimeOut);
field_to_json(Obj,"connectionId",ConnectionId); field_to_json(Obj, "connectionId", ConnectionId);
field_to_json(Obj,"commandUUID",CommandUUID); field_to_json(Obj, "commandUUID", CommandUUID);
field_to_json(Obj,"started", Started); field_to_json(Obj, "started", Started);
field_to_json(Obj,"viewport",ViewPort); field_to_json(Obj, "viewport", ViewPort);
field_to_json(Obj,"password",DevicePassword); field_to_json(Obj, "password", DevicePassword);
} }
void Dashboard::to_json(Poco::JSON::Object &Obj) const { void Dashboard::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"commands",commands); field_to_json(Obj, "commands", commands);
field_to_json(Obj,"upTimes",upTimes); field_to_json(Obj, "upTimes", upTimes);
field_to_json(Obj,"memoryUsed",memoryUsed); field_to_json(Obj, "memoryUsed", memoryUsed);
field_to_json(Obj,"load1",load1); field_to_json(Obj, "load1", load1);
field_to_json(Obj,"load5",load5); field_to_json(Obj, "load5", load5);
field_to_json(Obj,"load15",load15); field_to_json(Obj, "load15", load15);
field_to_json(Obj,"vendors",vendors); field_to_json(Obj, "vendors", vendors);
field_to_json(Obj,"status",status); field_to_json(Obj, "status", status);
field_to_json(Obj,"deviceType",deviceType); field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj,"healths",healths); field_to_json(Obj, "healths", healths);
field_to_json(Obj,"certificates",certificates); field_to_json(Obj, "certificates", certificates);
field_to_json(Obj,"lastContact",lastContact); field_to_json(Obj, "lastContact", lastContact);
field_to_json(Obj,"associations",associations); field_to_json(Obj, "associations", associations);
field_to_json(Obj,"snapshot",snapshot); field_to_json(Obj, "snapshot", snapshot);
field_to_json(Obj,"numberOfDevices",numberOfDevices); field_to_json(Obj, "numberOfDevices", numberOfDevices);
} }
void Dashboard::reset() { void Dashboard::reset() {
commands.clear(); commands.clear();
upTimes.clear(); upTimes.clear();
memoryUsed.clear(); memoryUsed.clear();
@@ -296,38 +302,38 @@ namespace OpenWifi::GWObjects {
certificates.clear(); certificates.clear();
lastContact.clear(); lastContact.clear();
associations.clear(); associations.clear();
numberOfDevices = 0 ; numberOfDevices = 0;
snapshot = Utils::Now(); snapshot = Utils::Now();
} }
void CapabilitiesModel::to_json(Poco::JSON::Object &Obj) const{ void CapabilitiesModel::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"deviceType", deviceType); field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj,"capabilities", capabilities); field_to_json(Obj, "capabilities", capabilities);
}; };
void ScriptRequest::to_json(Poco::JSON::Object &Obj) const { void ScriptRequest::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"serialNumber",serialNumber); field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj,"timeout",timeout); field_to_json(Obj, "timeout", timeout);
field_to_json(Obj,"type",type); field_to_json(Obj, "type", type);
field_to_json(Obj,"scriptId",scriptId); field_to_json(Obj, "scriptId", scriptId);
field_to_json(Obj,"script",script); field_to_json(Obj, "script", script);
field_to_json(Obj,"when",when); field_to_json(Obj, "when", when);
field_to_json(Obj,"signature", signature); field_to_json(Obj, "signature", signature);
field_to_json(Obj,"deferred", deferred); field_to_json(Obj, "deferred", deferred);
field_to_json(Obj,"uri", uri); field_to_json(Obj, "uri", uri);
} }
bool ScriptRequest::from_json(const Poco::JSON::Object::Ptr &Obj) { bool ScriptRequest::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"serialNumber",serialNumber); field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj,"timeout",timeout); field_from_json(Obj, "timeout", timeout);
field_from_json(Obj,"type",type); field_from_json(Obj, "type", type);
field_from_json(Obj,"script",script); field_from_json(Obj, "script", script);
field_from_json(Obj,"scriptId",scriptId); field_from_json(Obj, "scriptId", scriptId);
field_from_json(Obj,"when",when); field_from_json(Obj, "when", when);
field_from_json(Obj,"signature", signature); field_from_json(Obj, "signature", signature);
field_from_json(Obj,"deferred", deferred); field_from_json(Obj, "deferred", deferred);
field_from_json(Obj,"uri", uri); field_from_json(Obj, "uri", uri);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -335,12 +341,12 @@ namespace OpenWifi::GWObjects {
} }
void RadiusProxyPoolList::to_json(Poco::JSON::Object &Obj) const { void RadiusProxyPoolList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"pools",pools); field_to_json(Obj, "pools", pools);
} }
bool RadiusProxyPoolList::from_json(const Poco::JSON::Object::Ptr &Obj) { bool RadiusProxyPoolList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"pools",pools); field_from_json(Obj, "pools", pools);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -348,22 +354,22 @@ namespace OpenWifi::GWObjects {
} }
void RadiusProxyPool::to_json(Poco::JSON::Object &Obj) const { void RadiusProxyPool::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"name",name); field_to_json(Obj, "name", name);
field_to_json(Obj,"description",description); field_to_json(Obj, "description", description);
field_to_json(Obj,"authConfig",authConfig); field_to_json(Obj, "authConfig", authConfig);
field_to_json(Obj,"acctConfig",acctConfig); field_to_json(Obj, "acctConfig", acctConfig);
field_to_json(Obj,"coaConfig",coaConfig); field_to_json(Obj, "coaConfig", coaConfig);
field_to_json(Obj,"useByDefault",useByDefault); field_to_json(Obj, "useByDefault", useByDefault);
} }
bool RadiusProxyPool::from_json(const Poco::JSON::Object::Ptr &Obj) { bool RadiusProxyPool::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"name",name); field_from_json(Obj, "name", name);
field_from_json(Obj,"description",description); field_from_json(Obj, "description", description);
field_from_json(Obj,"authConfig",authConfig); field_from_json(Obj, "authConfig", authConfig);
field_from_json(Obj,"acctConfig",acctConfig); field_from_json(Obj, "acctConfig", acctConfig);
field_from_json(Obj,"coaConfig",coaConfig); field_from_json(Obj, "coaConfig", coaConfig);
field_from_json(Obj,"useByDefault",useByDefault); field_from_json(Obj, "useByDefault", useByDefault);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -371,20 +377,20 @@ namespace OpenWifi::GWObjects {
} }
void RadiusProxyServerConfig::to_json(Poco::JSON::Object &Obj) const { void RadiusProxyServerConfig::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"strategy",strategy); field_to_json(Obj, "strategy", strategy);
field_to_json(Obj,"monitor",monitor); field_to_json(Obj, "monitor", monitor);
field_to_json(Obj,"monitorMethod",monitorMethod); field_to_json(Obj, "monitorMethod", monitorMethod);
field_to_json(Obj,"methodParameters",methodParameters); field_to_json(Obj, "methodParameters", methodParameters);
field_to_json(Obj,"servers",servers); field_to_json(Obj, "servers", servers);
} }
bool RadiusProxyServerConfig::from_json(const Poco::JSON::Object::Ptr &Obj) { bool RadiusProxyServerConfig::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"strategy",strategy); field_from_json(Obj, "strategy", strategy);
field_from_json(Obj,"monitor",monitor); field_from_json(Obj, "monitor", monitor);
field_from_json(Obj,"monitorMethod",monitorMethod); field_from_json(Obj, "monitorMethod", monitorMethod);
field_from_json(Obj,"methodParameters",methodParameters); field_from_json(Obj, "methodParameters", methodParameters);
field_from_json(Obj,"servers",servers); field_from_json(Obj, "servers", servers);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -392,40 +398,40 @@ namespace OpenWifi::GWObjects {
} }
void RadiusProxyServerEntry::to_json(Poco::JSON::Object &Obj) const { void RadiusProxyServerEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"name",name); field_to_json(Obj, "name", name);
field_to_json(Obj,"ip",ip); field_to_json(Obj, "ip", ip);
field_to_json(Obj,"port",port); field_to_json(Obj, "port", port);
field_to_json(Obj,"weight",weight); field_to_json(Obj, "weight", weight);
field_to_json(Obj,"secret",secret); field_to_json(Obj, "secret", secret);
field_to_json(Obj,"certificate",certificate); field_to_json(Obj, "certificate", certificate);
field_to_json(Obj,"radsec",radsec); field_to_json(Obj, "radsec", radsec);
field_to_json(Obj,"allowSelfSigned",allowSelfSigned); field_to_json(Obj, "allowSelfSigned", allowSelfSigned);
field_to_json(Obj,"radsecPort",radsecPort); field_to_json(Obj, "radsecPort", radsecPort);
field_to_json(Obj,"radsecSecret",radsecSecret); field_to_json(Obj, "radsecSecret", radsecSecret);
field_to_json(Obj,"radsecCacerts",radsecCacerts); field_to_json(Obj, "radsecCacerts", radsecCacerts);
field_to_json(Obj,"radsecCert",radsecCert); field_to_json(Obj, "radsecCert", radsecCert);
field_to_json(Obj,"radsecKey",radsecKey); field_to_json(Obj, "radsecKey", radsecKey);
field_to_json(Obj,"radsecRealms",radsecRealms); field_to_json(Obj, "radsecRealms", radsecRealms);
field_to_json(Obj,"ignore",ignore); field_to_json(Obj, "ignore", ignore);
} }
bool RadiusProxyServerEntry::from_json(const Poco::JSON::Object::Ptr &Obj) { bool RadiusProxyServerEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"name",name); field_from_json(Obj, "name", name);
field_from_json(Obj,"ip",ip); field_from_json(Obj, "ip", ip);
field_from_json(Obj,"port",port); field_from_json(Obj, "port", port);
field_from_json(Obj,"weight",weight); field_from_json(Obj, "weight", weight);
field_from_json(Obj,"secret",secret); field_from_json(Obj, "secret", secret);
field_from_json(Obj,"certificate",certificate); field_from_json(Obj, "certificate", certificate);
field_from_json(Obj,"radsec",radsec); field_from_json(Obj, "radsec", radsec);
field_from_json(Obj,"allowSelfSigned",allowSelfSigned); field_from_json(Obj, "allowSelfSigned", allowSelfSigned);
field_from_json(Obj,"radsecSecret",radsecSecret); field_from_json(Obj, "radsecSecret", radsecSecret);
field_from_json(Obj,"radsecPort",radsecPort); field_from_json(Obj, "radsecPort", radsecPort);
field_from_json(Obj,"radsecCacerts",radsecCacerts); field_from_json(Obj, "radsecCacerts", radsecCacerts);
field_from_json(Obj,"radsecCert",radsecCert); field_from_json(Obj, "radsecCert", radsecCert);
field_from_json(Obj,"radsecKey",radsecKey); field_from_json(Obj, "radsecKey", radsecKey);
field_from_json(Obj,"radsecRealms",radsecRealms); field_from_json(Obj, "radsecRealms", radsecRealms);
field_from_json(Obj,"ignore",ignore); field_from_json(Obj, "ignore", ignore);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -433,38 +439,38 @@ namespace OpenWifi::GWObjects {
} }
void ScriptEntry::to_json(Poco::JSON::Object &Obj) const { void ScriptEntry::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id); field_to_json(Obj, "id", id);
field_to_json(Obj,"name", name); field_to_json(Obj, "name", name);
field_to_json(Obj,"description", description); field_to_json(Obj, "description", description);
field_to_json(Obj,"uri", uri); field_to_json(Obj, "uri", uri);
field_to_json(Obj,"content", content); field_to_json(Obj, "content", content);
field_to_json(Obj,"version", version); field_to_json(Obj, "version", version);
field_to_json(Obj,"type", type); field_to_json(Obj, "type", type);
field_to_json(Obj,"created", created); field_to_json(Obj, "created", created);
field_to_json(Obj,"modified", modified); field_to_json(Obj, "modified", modified);
field_to_json(Obj,"author", author); field_to_json(Obj, "author", author);
field_to_json(Obj,"restricted", restricted); field_to_json(Obj, "restricted", restricted);
field_to_json(Obj,"deferred", deferred); field_to_json(Obj, "deferred", deferred);
field_to_json(Obj,"timeout", timeout); field_to_json(Obj, "timeout", timeout);
field_to_json(Obj,"defaultUploadURI", defaultUploadURI); field_to_json(Obj, "defaultUploadURI", defaultUploadURI);
} }
bool ScriptEntry::from_json(const Poco::JSON::Object::Ptr &Obj) { bool ScriptEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"id", id); field_from_json(Obj, "id", id);
field_from_json(Obj,"name", name); field_from_json(Obj, "name", name);
field_from_json(Obj,"description", description); field_from_json(Obj, "description", description);
field_from_json(Obj,"uri", uri); field_from_json(Obj, "uri", uri);
field_from_json(Obj,"content", content); field_from_json(Obj, "content", content);
field_from_json(Obj,"version", version); field_from_json(Obj, "version", version);
field_from_json(Obj,"type", type); field_from_json(Obj, "type", type);
field_from_json(Obj,"created", created); field_from_json(Obj, "created", created);
field_from_json(Obj,"modified", modified); field_from_json(Obj, "modified", modified);
field_from_json(Obj,"author", author); field_from_json(Obj, "author", author);
field_from_json(Obj,"restricted", restricted); field_from_json(Obj, "restricted", restricted);
field_from_json(Obj,"deferred", deferred); field_from_json(Obj, "deferred", deferred);
field_from_json(Obj,"timeout", timeout); field_from_json(Obj, "timeout", timeout);
field_from_json(Obj,"defaultUploadURI", defaultUploadURI); field_from_json(Obj, "defaultUploadURI", defaultUploadURI);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -472,12 +478,12 @@ namespace OpenWifi::GWObjects {
} }
void ScriptEntryList::to_json(Poco::JSON::Object &Obj) const { void ScriptEntryList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"scripts",scripts); field_to_json(Obj, "scripts", scripts);
} }
bool ScriptEntryList::from_json(const Poco::JSON::Object::Ptr &Obj) { bool ScriptEntryList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"scripts",scripts); field_from_json(Obj, "scripts", scripts);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -485,63 +491,57 @@ namespace OpenWifi::GWObjects {
} }
void DeviceRestrictionsKeyInfo::to_json(Poco::JSON::Object &Obj) const { void DeviceRestrictionsKeyInfo::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"vendor", vendor); field_to_json(Obj, "vendor", vendor);
field_to_json(Obj,"algo", algo); field_to_json(Obj, "algo", algo);
} }
bool DeviceRestrictionsKeyInfo::from_json(const Poco::JSON::Object::Ptr &Obj) { bool DeviceRestrictionsKeyInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"vendor", vendor); field_from_json(Obj, "vendor", vendor);
field_from_json(Obj,"algo", algo); field_from_json(Obj, "algo", algo);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
return false; return false;
} }
void DeviceRestrictions::to_json(Poco::JSON::Object &Obj) const { void DeviceRestrictions::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"dfs", dfs); field_to_json(Obj, "dfs", dfs);
field_to_json(Obj,"ssh", ssh); field_to_json(Obj, "ssh", ssh);
field_to_json(Obj,"rtty", rtty); field_to_json(Obj, "rtty", rtty);
field_to_json(Obj,"tty", tty); field_to_json(Obj, "tty", tty);
field_to_json(Obj,"developer", developer); field_to_json(Obj, "developer", developer);
field_to_json(Obj,"upgrade", upgrade); field_to_json(Obj, "upgrade", upgrade);
field_to_json(Obj,"commands", commands); field_to_json(Obj, "commands", commands);
field_to_json(Obj,"country", country); field_to_json(Obj, "country", country);
field_to_json(Obj,"key_info", key_info); field_to_json(Obj, "key_info", key_info);
} }
bool DeviceRestrictions::from_json(const Poco::JSON::Object::Ptr &Obj) { bool DeviceRestrictions::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"dfs", dfs); field_from_json(Obj, "dfs", dfs);
field_from_json(Obj,"ssh", ssh); field_from_json(Obj, "ssh", ssh);
field_from_json(Obj,"rtty", rtty); field_from_json(Obj, "rtty", rtty);
field_from_json(Obj,"tty", tty); field_from_json(Obj, "tty", tty);
field_from_json(Obj,"developer", developer); field_from_json(Obj, "developer", developer);
field_from_json(Obj,"upgrade", upgrade); field_from_json(Obj, "upgrade", upgrade);
field_from_json(Obj,"commands", commands); field_from_json(Obj, "commands", commands);
field_from_json(Obj,"country", country); field_from_json(Obj, "country", country);
field_from_json(Obj,"key_info", key_info); field_from_json(Obj, "key_info", key_info);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
return false; return false;
} }
bool DeviceRestrictionsKeyInfo::operator!=(const OpenWifi::GWObjects::DeviceRestrictionsKeyInfo &T) const { bool DeviceRestrictionsKeyInfo::operator!=(
return (T.algo!=algo) || (T.vendor!=vendor); const OpenWifi::GWObjects::DeviceRestrictionsKeyInfo &T) const {
return (T.algo != algo) || (T.vendor != vendor);
} }
bool DeviceRestrictions::operator!=(const OpenWifi::GWObjects::DeviceRestrictions &T) const { bool DeviceRestrictions::operator!=(const OpenWifi::GWObjects::DeviceRestrictions &T) const {
return ( (T.dfs!=dfs) || return ((T.dfs != dfs) || (T.rtty != rtty) || (T.upgrade != upgrade) ||
(T.rtty!=rtty) || (T.commands != commands) || (T.developer != developer) || (T.ssh != ssh) ||
(T.upgrade!=upgrade) || (T.key_info != key_info) || (T.country != country));
(T.commands != commands) ||
(T.developer != developer) ||
(T.ssh !=ssh) ||
(T.key_info != key_info) ||
(T.country != country) );
} }
} } // namespace OpenWifi::GWObjects

View File

@@ -13,62 +13,57 @@
namespace OpenWifi::GWObjects { namespace OpenWifi::GWObjects {
enum CertificateValidation { enum CertificateValidation { NO_CERTIFICATE, VALID_CERTIFICATE, MISMATCH_SERIAL, VERIFIED };
NO_CERTIFICATE,
VALID_CERTIFICATE,
MISMATCH_SERIAL,
VERIFIED
};
struct ConnectionState { struct ConnectionState {
uint64_t MessageCount = 0 ; uint64_t MessageCount = 0;
std::string Address; std::string Address;
uint64_t UUID = 0 ; uint64_t UUID = 0;
uint64_t PendingUUID = 0 ; uint64_t PendingUUID = 0;
uint64_t TX = 0, RX = 0; uint64_t TX = 0, RX = 0;
uint64_t Associations_2G=0; uint64_t Associations_2G = 0;
uint64_t Associations_5G=0; uint64_t Associations_5G = 0;
uint64_t Associations_6G=0; uint64_t Associations_6G = 0;
bool Connected = false; bool Connected = false;
uint64_t LastContact=0; uint64_t LastContact = 0;
std::string Firmware; std::string Firmware;
CertificateValidation VerifiedCertificate = NO_CERTIFICATE; CertificateValidation VerifiedCertificate = NO_CERTIFICATE;
std::string Compatible; std::string Compatible;
uint64_t kafkaClients=0; uint64_t kafkaClients = 0;
uint64_t webSocketClients=0; uint64_t webSocketClients = 0;
uint64_t kafkaPackets=0; uint64_t kafkaPackets = 0;
uint64_t websocketPackets=0; uint64_t websocketPackets = 0;
std::string locale; std::string locale;
uint64_t started=0; uint64_t started = 0;
uint64_t sessionId=0; uint64_t sessionId = 0;
double connectionCompletionTime=0.0; double connectionCompletionTime = 0.0;
std::uint64_t certificateExpiryDate=0; std::uint64_t certificateExpiryDate = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct DeviceRestrictionsKeyInfo { struct DeviceRestrictionsKeyInfo {
std::string vendor; std::string vendor;
std::string algo; std::string algo;
bool operator !=(const DeviceRestrictionsKeyInfo &b) const; bool operator!=(const DeviceRestrictionsKeyInfo &b) const;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DeviceRestrictions { struct DeviceRestrictions {
bool dfs = false; bool dfs = false;
bool ssh = false; bool ssh = false;
bool rtty = false; bool rtty = false;
bool tty = false; bool tty = false;
bool developer = false; bool developer = false;
bool upgrade = false; bool upgrade = false;
bool commands = false; bool commands = false;
std::vector<std::string> country; std::vector<std::string> country;
DeviceRestrictionsKeyInfo key_info; DeviceRestrictionsKeyInfo key_info;
bool operator !=(const DeviceRestrictions &D) const; bool operator!=(const DeviceRestrictions &D) const;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
@@ -80,27 +75,27 @@ namespace OpenWifi::GWObjects {
std::string MACAddress; std::string MACAddress;
std::string Manufacturer; std::string Manufacturer;
std::string Configuration; std::string Configuration;
SecurityObjects::NoteInfoVec Notes; SecurityObjects::NoteInfoVec Notes;
std::string Owner; std::string Owner;
std::string Location; std::string Location;
std::string Firmware; std::string Firmware;
std::string Compatible; std::string Compatible;
std::string FWUpdatePolicy; std::string FWUpdatePolicy;
uint64_t UUID = 0 ; uint64_t UUID = 0;
uint64_t CreationTimestamp = 0 ; uint64_t CreationTimestamp = 0;
uint64_t LastConfigurationChange = 0 ; uint64_t LastConfigurationChange = 0;
uint64_t LastConfigurationDownload = 0 ; uint64_t LastConfigurationDownload = 0;
uint64_t LastFWUpdate = 0 ; uint64_t LastFWUpdate = 0;
std::string Venue; std::string Venue;
std::string DevicePassword; std::string DevicePassword;
std::string subscriber; std::string subscriber;
std::string entity; std::string entity;
uint64_t modified=0; uint64_t modified = 0;
std::string locale; std::string locale;
bool restrictedDevice=false; bool restrictedDevice = false;
std::string pendingConfiguration; std::string pendingConfiguration;
std::string pendingConfigurationCmd; std::string pendingConfigurationCmd;
DeviceRestrictions restrictionDetails; DeviceRestrictions restrictionDetails;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
void to_json_with_status(Poco::JSON::Object &Obj) const; void to_json_with_status(Poco::JSON::Object &Obj) const;
@@ -119,26 +114,26 @@ namespace OpenWifi::GWObjects {
struct Statistics { struct Statistics {
std::string SerialNumber; std::string SerialNumber;
uint64_t UUID = 0 ; uint64_t UUID = 0;
std::string Data; std::string Data;
uint64_t Recorded = 0; uint64_t Recorded = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct HealthCheck { struct HealthCheck {
std::string SerialNumber; std::string SerialNumber;
uint64_t UUID = 0 ; uint64_t UUID = 0;
std::string Data; std::string Data;
uint64_t Recorded = 0 ; uint64_t Recorded = 0;
uint64_t Sanity = 0 ; uint64_t Sanity = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct Capabilities { struct Capabilities {
std::string Capabilities; std::string Capabilities;
uint64_t FirstUpdate = 0 ; uint64_t FirstUpdate = 0;
uint64_t LastUpdate = 0 ; uint64_t LastUpdate = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct DeviceLog { struct DeviceLog {
@@ -155,11 +150,11 @@ namespace OpenWifi::GWObjects {
std::string SerialNumber; std::string SerialNumber;
std::string Log; std::string Log;
std::string Data; std::string Data;
uint64_t Severity = 0 ; uint64_t Severity = 0;
uint64_t Recorded = 0 ; uint64_t Recorded = 0;
uint64_t LogType = 0 ; uint64_t LogType = 0;
uint64_t UUID = 0 ; uint64_t UUID = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct DefaultConfiguration { struct DefaultConfiguration {
@@ -167,10 +162,10 @@ namespace OpenWifi::GWObjects {
std::string Configuration; std::string Configuration;
Types::StringVec Models; Types::StringVec Models;
std::string Description; std::string Description;
uint64_t Created; uint64_t Created;
uint64_t LastModified; uint64_t LastModified;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct CommandDetails { struct CommandDetails {
@@ -184,15 +179,15 @@ namespace OpenWifi::GWObjects {
std::string ErrorText; std::string ErrorText;
uint64_t Submitted = time(nullptr); uint64_t Submitted = time(nullptr);
uint64_t Executed = 0; uint64_t Executed = 0;
uint64_t Completed = 0 ; uint64_t Completed = 0;
uint64_t RunAt = 0 ; uint64_t RunAt = 0;
uint64_t ErrorCode = 0 ; uint64_t ErrorCode = 0;
uint64_t Custom = 0 ; uint64_t Custom = 0;
uint64_t WaitingForFile = 0 ; uint64_t WaitingForFile = 0;
uint64_t AttachDate = 0 ; uint64_t AttachDate = 0;
uint64_t AttachSize = 0 ; uint64_t AttachSize = 0;
std::string AttachType; std::string AttachType;
double executionTime = 0.0; double executionTime = 0.0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
@@ -208,20 +203,20 @@ namespace OpenWifi::GWObjects {
struct RttySessionDetails { struct RttySessionDetails {
std::string SerialNumber; std::string SerialNumber;
std::string Server; std::string Server;
uint64_t Port = 0 ; uint64_t Port = 0;
std::string Token; std::string Token;
uint64_t TimeOut = 0 ; uint64_t TimeOut = 0;
std::string ConnectionId; std::string ConnectionId;
uint64_t Started = 0 ; uint64_t Started = 0;
std::string CommandUUID; std::string CommandUUID;
uint64_t ViewPort = 0 ; uint64_t ViewPort = 0;
std::string DevicePassword; std::string DevicePassword;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct Dashboard { struct Dashboard {
uint64_t snapshot = 0 ; uint64_t snapshot = 0;
uint64_t numberOfDevices = 0 ; uint64_t numberOfDevices = 0;
Types::CountedMap commands; Types::CountedMap commands;
Types::CountedMap upTimes; Types::CountedMap upTimes;
Types::CountedMap memoryUsed; Types::CountedMap memoryUsed;
@@ -247,27 +242,27 @@ namespace OpenWifi::GWObjects {
}; };
struct ScriptEntry { struct ScriptEntry {
std::string id; std::string id;
std::string name; std::string name;
std::string description; std::string description;
std::string uri; std::string uri;
std::string content; std::string content;
std::string version; std::string version;
std::string type; std::string type;
std::uint64_t created; std::uint64_t created;
std::uint64_t modified; std::uint64_t modified;
std::string author; std::string author;
Types::StringVec restricted; Types::StringVec restricted;
bool deferred=false; bool deferred = false;
std::uint64_t timeout=30; std::uint64_t timeout = 30;
std::string defaultUploadURI; std::string defaultUploadURI;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct ScriptEntryList { struct ScriptEntryList {
std::vector<ScriptEntry> scripts; std::vector<ScriptEntry> scripts;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
@@ -275,7 +270,7 @@ namespace OpenWifi::GWObjects {
struct ScriptRequest { struct ScriptRequest {
std::string serialNumber; std::string serialNumber;
uint64_t timeout=30; uint64_t timeout = 30;
std::string type; std::string type;
std::string script; std::string script;
std::string scriptId; std::string scriptId;
@@ -291,52 +286,52 @@ namespace OpenWifi::GWObjects {
struct RadiusProxyServerEntry { struct RadiusProxyServerEntry {
std::string name; std::string name;
std::string ip; std::string ip;
uint16_t port=0; uint16_t port = 0;
uint64_t weight=0; uint64_t weight = 0;
std::string secret; std::string secret;
std::string certificate; std::string certificate;
bool radsec=false; bool radsec = false;
bool allowSelfSigned=false; bool allowSelfSigned = false;
uint16_t radsecPort=2083; uint16_t radsecPort = 2083;
std::string radsecSecret; std::string radsecSecret;
std::string radsecKey; std::string radsecKey;
std::string radsecCert; std::string radsecCert;
std::vector<std::string> radsecCacerts; std::vector<std::string> radsecCacerts;
std::vector<std::string> radsecRealms; std::vector<std::string> radsecRealms;
bool ignore=false; bool ignore = false;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct RadiusProxyServerConfig { struct RadiusProxyServerConfig {
std::string strategy; std::string strategy;
bool monitor=false; bool monitor = false;
std::string monitorMethod; std::string monitorMethod;
std::vector<std::string> methodParameters; std::vector<std::string> methodParameters;
std::vector<RadiusProxyServerEntry> servers; std::vector<RadiusProxyServerEntry> servers;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct RadiusProxyPool { struct RadiusProxyPool {
std::string name; std::string name;
std::string description; std::string description;
RadiusProxyServerConfig authConfig; RadiusProxyServerConfig authConfig;
RadiusProxyServerConfig acctConfig; RadiusProxyServerConfig acctConfig;
RadiusProxyServerConfig coaConfig; RadiusProxyServerConfig coaConfig;
bool useByDefault=false; bool useByDefault = false;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct RadiusProxyPoolList { struct RadiusProxyPoolList {
std::vector<RadiusProxyPool> pools; std::vector<RadiusProxyPool> pools;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
} } // namespace OpenWifi::GWObjects

View File

@@ -4,9 +4,9 @@
#include "framework/RESTAPI_utils.h" #include "framework/RESTAPI_utils.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::EmbedDocument; using OpenWifi::RESTAPI_utils::EmbedDocument;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::field_to_json;
#include "RESTAPI_OWLSobjects.h" #include "RESTAPI_OWLSobjects.h"
@@ -14,97 +14,89 @@ using OpenWifi::RESTAPI_utils::EmbedDocument;
namespace OpenWifi::OWLSObjects { namespace OpenWifi::OWLSObjects {
void SimulationDetails::to_json(Poco::JSON::Object &Obj) const { void SimulationDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id); field_to_json(Obj, "id", id);
field_to_json(Obj,"name", name); field_to_json(Obj, "name", name);
field_to_json(Obj,"gateway", gateway); field_to_json(Obj, "gateway", gateway);
field_to_json(Obj,"certificate", certificate); field_to_json(Obj, "certificate", certificate);
field_to_json(Obj,"key", key); field_to_json(Obj, "key", key);
field_to_json(Obj,"macPrefix", macPrefix); field_to_json(Obj, "macPrefix", macPrefix);
field_to_json(Obj,"deviceType", deviceType); field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj,"devices", devices); field_to_json(Obj, "devices", devices);
field_to_json(Obj,"healthCheckInterval", healthCheckInterval); field_to_json(Obj, "healthCheckInterval", healthCheckInterval);
field_to_json(Obj,"stateInterval", stateInterval); field_to_json(Obj, "stateInterval", stateInterval);
field_to_json(Obj,"minAssociations", minAssociations); field_to_json(Obj, "minAssociations", minAssociations);
field_to_json(Obj,"maxAssociations", maxAssociations); field_to_json(Obj, "maxAssociations", maxAssociations);
field_to_json(Obj,"minClients", minClients); field_to_json(Obj, "minClients", minClients);
field_to_json(Obj,"maxClients", maxClients); field_to_json(Obj, "maxClients", maxClients);
field_to_json(Obj,"simulationLength", simulationLength); field_to_json(Obj, "simulationLength", simulationLength);
field_to_json(Obj,"threads", threads); field_to_json(Obj, "threads", threads);
field_to_json(Obj,"clientInterval", clientInterval); field_to_json(Obj, "clientInterval", clientInterval);
field_to_json(Obj,"keepAlive", keepAlive); field_to_json(Obj, "keepAlive", keepAlive);
field_to_json(Obj,"reconnectInterval", reconnectInterval); field_to_json(Obj, "reconnectInterval", reconnectInterval);
field_to_json(Obj,"concurrentDevices", concurrentDevices); field_to_json(Obj, "concurrentDevices", concurrentDevices);
} }
bool SimulationDetails::from_json(const Poco::JSON::Object::Ptr &Obj) { bool SimulationDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
field_from_json(Obj,"id", id); field_from_json(Obj, "id", id);
field_from_json(Obj,"name", name); field_from_json(Obj, "name", name);
field_from_json(Obj,"gateway", gateway); field_from_json(Obj, "gateway", gateway);
field_from_json(Obj,"certificate", certificate); field_from_json(Obj, "certificate", certificate);
field_from_json(Obj,"key", key); field_from_json(Obj, "key", key);
field_from_json(Obj,"macPrefix", macPrefix); field_from_json(Obj, "macPrefix", macPrefix);
field_from_json(Obj,"deviceType", deviceType); field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj,"devices", devices); field_from_json(Obj, "devices", devices);
field_from_json(Obj,"healthCheckInterval", healthCheckInterval); field_from_json(Obj, "healthCheckInterval", healthCheckInterval);
field_from_json(Obj,"stateInterval", stateInterval); field_from_json(Obj, "stateInterval", stateInterval);
field_from_json(Obj,"minAssociations", minAssociations); field_from_json(Obj, "minAssociations", minAssociations);
field_from_json(Obj,"maxAssociations", maxAssociations); field_from_json(Obj, "maxAssociations", maxAssociations);
field_from_json(Obj,"minClients", minClients); field_from_json(Obj, "minClients", minClients);
field_from_json(Obj,"maxClients", maxClients); field_from_json(Obj, "maxClients", maxClients);
field_from_json(Obj,"simulationLength", simulationLength); field_from_json(Obj, "simulationLength", simulationLength);
field_from_json(Obj,"threads", threads); field_from_json(Obj, "threads", threads);
field_from_json(Obj,"clientInterval", clientInterval); field_from_json(Obj, "clientInterval", clientInterval);
field_from_json(Obj,"keepAlive", keepAlive); field_from_json(Obj, "keepAlive", keepAlive);
field_from_json(Obj,"reconnectInterval", reconnectInterval); field_from_json(Obj, "reconnectInterval", reconnectInterval);
field_from_json(Obj,"concurrentDevices", concurrentDevices); field_from_json(Obj, "concurrentDevices", concurrentDevices);
return true; return true;
} catch(...) { } catch (...) {
}
return false;
}
} void SimulationDetailsList::to_json(Poco::JSON::Object &Obj) const {
return false; field_to_json(Obj, "list", list);
} }
void SimulationDetailsList::to_json(Poco::JSON::Object &Obj) const { bool SimulationDetailsList::from_json(const Poco::JSON::Object::Ptr &Obj) {
field_to_json(Obj,"list", list); try {
} field_from_json(Obj, "list", list);
return true;
} catch (...) {
}
return false;
}
bool SimulationDetailsList::from_json(const Poco::JSON::Object::Ptr &Obj) { void SimulationStatus::to_json(Poco::JSON::Object &Obj) const {
try { field_to_json(Obj, "id", id);
field_from_json(Obj,"list", list); field_to_json(Obj, "simulationId", simulationId);
return true; field_to_json(Obj, "state", state);
} catch(...) { field_to_json(Obj, "tx", tx);
field_to_json(Obj, "rx", rx);
field_to_json(Obj, "msgsTx", msgsTx);
field_to_json(Obj, "msgsRx", msgsRx);
field_to_json(Obj, "liveDevices", liveDevices);
field_to_json(Obj, "timeToFullDevices", timeToFullDevices);
field_to_json(Obj, "startTime", startTime);
field_to_json(Obj, "endTime", endTime);
field_to_json(Obj, "errorDevices", errorDevices);
field_to_json(Obj, "owner", owner);
}
} void Dashboard::to_json([[maybe_unused]] Poco::JSON::Object &Obj) const {}
return false;
}
void SimulationStatus::to_json(Poco::JSON::Object &Obj) const { bool Dashboard::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) { return true; }
field_to_json(Obj,"id", id);
field_to_json(Obj,"simulationId", simulationId);
field_to_json(Obj,"state", state);
field_to_json(Obj,"tx", tx);
field_to_json(Obj,"rx", rx);
field_to_json(Obj,"msgsTx", msgsTx);
field_to_json(Obj,"msgsRx", msgsRx);
field_to_json(Obj,"liveDevices", liveDevices);
field_to_json(Obj,"timeToFullDevices", timeToFullDevices);
field_to_json(Obj,"startTime", startTime);
field_to_json(Obj,"endTime", endTime);
field_to_json(Obj,"errorDevices", errorDevices);
field_to_json(Obj,"owner", owner);
}
void Dashboard::to_json([[maybe_unused]] Poco::JSON::Object &Obj) const { void Dashboard::reset() {}
} // namespace OpenWifi::OWLSObjects
}
bool Dashboard::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) {
return true;
}
void Dashboard::reset() {
}
}

View File

@@ -5,73 +5,70 @@
#ifndef UCENTRALSIM_RESTAPI_OWLSOBJECTS_H #ifndef UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
#define UCENTRALSIM_RESTAPI_OWLSOBJECTS_H #define UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
#include <vector>
#include "Poco/JSON/Object.h" #include "Poco/JSON/Object.h"
#include <vector>
namespace OpenWifi::OWLSObjects { namespace OpenWifi::OWLSObjects {
struct SimulationDetails { struct SimulationDetails {
std::string id; std::string id;
std::string name; std::string name;
std::string gateway; std::string gateway;
std::string certificate; std::string certificate;
std::string key; std::string key;
std::string macPrefix; std::string macPrefix;
std::string deviceType; std::string deviceType;
uint64_t devices = 5; uint64_t devices = 5;
uint64_t healthCheckInterval = 60; uint64_t healthCheckInterval = 60;
uint64_t stateInterval = 60 ; uint64_t stateInterval = 60;
uint64_t minAssociations = 1; uint64_t minAssociations = 1;
uint64_t maxAssociations = 3; uint64_t maxAssociations = 3;
uint64_t minClients = 1 ; uint64_t minClients = 1;
uint64_t maxClients = 3; uint64_t maxClients = 3;
uint64_t simulationLength = 60 * 60; uint64_t simulationLength = 60 * 60;
uint64_t threads = 16; uint64_t threads = 16;
uint64_t clientInterval = 1; uint64_t clientInterval = 1;
uint64_t keepAlive = 300; uint64_t keepAlive = 300;
uint64_t reconnectInterval = 30 ; uint64_t reconnectInterval = 30;
uint64_t concurrentDevices = 5; uint64_t concurrentDevices = 5;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct SimulationDetailsList { struct SimulationDetailsList {
std::vector<SimulationDetails> list; std::vector<SimulationDetails> list;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct SimulationStatus { struct SimulationStatus {
std::string id; std::string id;
std::string simulationId; std::string simulationId;
std::string state; std::string state;
uint64_t tx; uint64_t tx;
uint64_t rx; uint64_t rx;
uint64_t msgsTx; uint64_t msgsTx;
uint64_t msgsRx; uint64_t msgsRx;
uint64_t liveDevices; uint64_t liveDevices;
uint64_t timeToFullDevices; uint64_t timeToFullDevices;
uint64_t startTime; uint64_t startTime;
uint64_t endTime; uint64_t endTime;
uint64_t errorDevices; uint64_t errorDevices;
std::string owner; std::string owner;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct Dashboard {
int O;
struct Dashboard { void to_json(Poco::JSON::Object &Obj) const;
int O; bool from_json(const Poco::JSON::Object::Ptr &Obj);
void reset();
};
void to_json(Poco::JSON::Object &Obj) const; } // namespace OpenWifi::OWLSObjects
bool from_json(const Poco::JSON::Object::Ptr &Obj);
void reset();
}; #endif // UCENTRALSIM_RESTAPI_OWLSOBJECTS_H
}
#endif //UCENTRALSIM_RESTAPI_OWLSOBJECTS_H

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -8,361 +8,364 @@
#pragma once #pragma once
#include <string>
#include <type_traits>
#include "framework/OpenWifiTypes.h"
#include "Poco/JSON/Object.h"
#include "Poco/Data/LOB.h" #include "Poco/Data/LOB.h"
#include "Poco/Data/LOBStream.h" #include "Poco/Data/LOBStream.h"
#include "Poco/JSON/Object.h"
#include "framework/OpenWifiTypes.h"
#include "framework/utils.h" #include "framework/utils.h"
#include <string>
#include <type_traits>
namespace OpenWifi { namespace OpenWifi {
uint64_t Now(); uint64_t Now();
namespace SecurityObjects { namespace SecurityObjects {
typedef std::string USER_ID_TYPE;
struct AclTemplate { typedef std::string USER_ID_TYPE;
bool Read_ = true;
bool ReadWrite_ = true;
bool ReadWriteCreate_ = true;
bool Delete_ = true;
bool PortalLogin_ = true;
AclTemplate() noexcept = default; struct AclTemplate {
bool Read_ = true;
bool ReadWrite_ = true;
bool ReadWriteCreate_ = true;
bool Delete_ = true;
bool PortalLogin_ = true;
void to_json(Poco::JSON::Object &Obj) const; AclTemplate() noexcept = default;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
static_assert( std::is_nothrow_move_constructible_v<AclTemplate> ); void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct WebToken { static_assert(std::is_nothrow_move_constructible_v<AclTemplate>);
std::string access_token_;
std::string refresh_token_;
std::string id_token_;
std::string token_type_;
std::string username_;
bool userMustChangePassword=false;
uint64_t errorCode=0;
uint64_t expires_in_=0;
uint64_t idle_timeout_=0;
AclTemplate acl_template_;
uint64_t created_=0;
uint64_t lastRefresh_=0;
void to_json(Poco::JSON::Object &Obj) const; struct WebToken {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string access_token_;
}; std::string refresh_token_;
std::string id_token_;
std::string token_type_;
std::string username_;
bool userMustChangePassword = false;
uint64_t errorCode = 0;
uint64_t expires_in_ = 0;
uint64_t idle_timeout_ = 0;
AclTemplate acl_template_;
uint64_t created_ = 0;
uint64_t lastRefresh_ = 0;
enum USER_ROLE { void to_json(Poco::JSON::Object &Obj) const;
UNKNOWN, ROOT, ADMIN, SUBSCRIBER, CSR, SYSTEM, INSTALLER, NOC, ACCOUNTING, PARTNER bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
USER_ROLE UserTypeFromString(const std::string &U); enum USER_ROLE {
std::string UserTypeToString(USER_ROLE U); UNKNOWN,
ROOT,
ADMIN,
SUBSCRIBER,
CSR,
SYSTEM,
INSTALLER,
NOC,
ACCOUNTING,
PARTNER
};
struct NoteInfo { USER_ROLE UserTypeFromString(const std::string &U);
uint64_t created=0; // = Utils::Now(); std::string UserTypeToString(USER_ROLE U);
std::string createdBy;
std::string note;
void to_json(Poco::JSON::Object &Obj) const; struct NoteInfo {
bool from_json(const Poco::JSON::Object::Ptr &Obj); uint64_t created = 0; // = Utils::Now();
}; std::string createdBy;
typedef std::vector<NoteInfo> NoteInfoVec; std::string note;
struct MobilePhoneNumber { void to_json(Poco::JSON::Object &Obj) const;
std::string number; bool from_json(const Poco::JSON::Object::Ptr &Obj);
bool verified = false; };
bool primary = false; typedef std::vector<NoteInfo> NoteInfoVec;
void to_json(Poco::JSON::Object &Obj) const; struct MobilePhoneNumber {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string number;
}; bool verified = false;
bool primary = false;
struct MfaAuthInfo { void to_json(Poco::JSON::Object &Obj) const;
bool enabled = false; bool from_json(const Poco::JSON::Object::Ptr &Obj);
std::string method; };
void to_json(Poco::JSON::Object &Obj) const; struct MfaAuthInfo {
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool enabled = false;
}; std::string method;
struct UserLoginLoginExtensions { void to_json(Poco::JSON::Object &Obj) const;
std::vector<MobilePhoneNumber> mobiles; bool from_json(const Poco::JSON::Object::Ptr &Obj);
struct MfaAuthInfo mfa; };
std::string authenticatorSecret;
void to_json(Poco::JSON::Object &Obj) const; struct UserLoginLoginExtensions {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::vector<MobilePhoneNumber> mobiles;
}; struct MfaAuthInfo mfa;
std::string authenticatorSecret;
struct MFAChallengeRequest { void to_json(Poco::JSON::Object &Obj) const;
std::string uuid; bool from_json(const Poco::JSON::Object::Ptr &Obj);
std::string question; };
std::string method;
uint64_t created = Utils::Now();
void to_json(Poco::JSON::Object &Obj) const; struct MFAChallengeRequest {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string uuid;
}; std::string question;
std::string method;
uint64_t created = Utils::Now();
struct MFAChallengeResponse { void to_json(Poco::JSON::Object &Obj) const;
std::string uuid; bool from_json(const Poco::JSON::Object::Ptr &Obj);
std::string answer; };
void to_json(Poco::JSON::Object &Obj) const; struct MFAChallengeResponse {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string uuid;
}; std::string answer;
struct UserInfo { void to_json(Poco::JSON::Object &Obj) const;
std::string id; bool from_json(const Poco::JSON::Object::Ptr &Obj);
std::string name; };
std::string description;
std::string avatar;
std::string email;
bool validated = false;
std::string validationEmail;
uint64_t validationDate = 0;
uint64_t creationDate = 0;
std::string validationURI;
bool changePassword = false;
uint64_t lastLogin = 0;
std::string currentLoginURI;
uint64_t lastPasswordChange = 0;
uint64_t lastEmailCheck = 0;
bool waitingForEmailCheck = false;
std::string locale;
NoteInfoVec notes;
std::string location;
std::string owner;
bool suspended = false;
bool blackListed = false;
USER_ROLE userRole;
UserLoginLoginExtensions userTypeProprietaryInfo;
std::string securityPolicy;
uint64_t securityPolicyChange = 0 ;
std::string currentPassword;
OpenWifi::Types::StringVec lastPasswords;
std::string oauthType;
std::string oauthUserInfo;
uint64_t modified;
std::string signingUp;
void to_json(Poco::JSON::Object &Obj) const; struct UserInfo {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string id;
}; std::string name;
typedef std::vector<UserInfo> UserInfoVec; std::string description;
std::string avatar;
std::string email;
bool validated = false;
std::string validationEmail;
uint64_t validationDate = 0;
uint64_t creationDate = 0;
std::string validationURI;
bool changePassword = false;
uint64_t lastLogin = 0;
std::string currentLoginURI;
uint64_t lastPasswordChange = 0;
uint64_t lastEmailCheck = 0;
bool waitingForEmailCheck = false;
std::string locale;
NoteInfoVec notes;
std::string location;
std::string owner;
bool suspended = false;
bool blackListed = false;
USER_ROLE userRole;
UserLoginLoginExtensions userTypeProprietaryInfo;
std::string securityPolicy;
uint64_t securityPolicyChange = 0;
std::string currentPassword;
OpenWifi::Types::StringVec lastPasswords;
std::string oauthType;
std::string oauthUserInfo;
uint64_t modified;
std::string signingUp;
struct UserInfoList { void to_json(Poco::JSON::Object &Obj) const;
std::vector<UserInfo> users; bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<UserInfo> UserInfoVec;
void to_json(Poco::JSON::Object &Obj) const; struct UserInfoList {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::vector<UserInfo> users;
};
// bool append_from_json(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec & Notes); void to_json(Poco::JSON::Object &Obj) const;
bool MergeNotes(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec & Notes); bool from_json(const Poco::JSON::Object::Ptr &Obj);
bool MergeNotes(const NoteInfoVec & NewNotes, const UserInfo &UInfo, NoteInfoVec & ExistingNotes); };
struct InternalServiceInfo { // bool append_from_json(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec &
std::string privateURI; // Notes);
std::string publicURI; bool MergeNotes(Poco::JSON::Object::Ptr Obj, const UserInfo &UInfo, NoteInfoVec &Notes);
std::string token; bool MergeNotes(const NoteInfoVec &NewNotes, const UserInfo &UInfo,
void to_json(Poco::JSON::Object &Obj) const; NoteInfoVec &ExistingNotes);
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<InternalServiceInfo> InternalServiceInfoVec;
struct InternalSystemServices { struct InternalServiceInfo {
std::string key; std::string privateURI;
std::string version; std::string publicURI;
InternalServiceInfoVec services; std::string token;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
typedef std::vector<InternalServiceInfo> InternalServiceInfoVec;
struct SystemEndpoint { struct InternalSystemServices {
std::string type; std::string key;
uint64_t id = 0; std::string version;
std::string vendor{"OpenWiFi"}; InternalServiceInfoVec services;
std::string uri; void to_json(Poco::JSON::Object &Obj) const;
std::string authenticationType{"internal_v1"}; bool from_json(const Poco::JSON::Object::Ptr &Obj);
void to_json(Poco::JSON::Object &Obj) const; };
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<SystemEndpoint> SystemEndpointVec;
struct SystemEndpointList { struct SystemEndpoint {
SystemEndpointVec endpoints; std::string type;
void to_json(Poco::JSON::Object &Obj) const; uint64_t id = 0;
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string vendor{"OpenWiFi"};
}; std::string uri;
std::string authenticationType{"internal_v1"};
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<SystemEndpoint> SystemEndpointVec;
struct UserInfoAndPolicy { struct SystemEndpointList {
WebToken webtoken; SystemEndpointVec endpoints;
UserInfo userinfo; void to_json(Poco::JSON::Object &Obj) const;
void to_json(Poco::JSON::Object &Obj) const; bool from_json(const Poco::JSON::Object::Ptr &Obj);
bool from_json(const Poco::JSON::Object::Ptr &Obj); };
};
typedef std::map<std::string,SecurityObjects::UserInfoAndPolicy> UserInfoCache;
enum ResourceAccessType { struct UserInfoAndPolicy {
NONE, WebToken webtoken;
READ, UserInfo userinfo;
MODIFY, void to_json(Poco::JSON::Object &Obj) const;
DELETE, bool from_json(const Poco::JSON::Object::Ptr &Obj);
CREATE, };
TEST, typedef std::map<std::string, SecurityObjects::UserInfoAndPolicy> UserInfoCache;
MOVE
};
ResourceAccessType ResourceAccessTypeFromString(const std::string &s); enum ResourceAccessType { NONE, READ, MODIFY, DELETE, CREATE, TEST, MOVE };
std::string ResourceAccessTypeToString(const ResourceAccessType & T);
struct ProfileAction { ResourceAccessType ResourceAccessTypeFromString(const std::string &s);
std::string resource; std::string ResourceAccessTypeToString(const ResourceAccessType &T);
ResourceAccessType access;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<ProfileAction> ProfileActionVec;
struct SecurityProfile { struct ProfileAction {
uint64_t id=0; std::string resource;
std::string name; ResourceAccessType access;
std::string description; void to_json(Poco::JSON::Object &Obj) const;
ProfileActionVec policy; bool from_json(const Poco::JSON::Object::Ptr &Obj);
std::string role; };
NoteInfoVec notes; typedef std::vector<ProfileAction> ProfileActionVec;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<SecurityProfile> SecurityProfileVec;
struct SecurityProfileList { struct SecurityProfile {
SecurityProfileVec profiles; uint64_t id = 0;
void to_json(Poco::JSON::Object &Obj) const; std::string name;
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string description;
}; ProfileActionVec policy;
std::string role;
NoteInfoVec notes;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
typedef std::vector<SecurityProfile> SecurityProfileVec;
enum LinkActions { struct SecurityProfileList {
FORGOT_PASSWORD=1, SecurityProfileVec profiles;
VERIFY_EMAIL, void to_json(Poco::JSON::Object &Obj) const;
SUB_FORGOT_PASSWORD, bool from_json(const Poco::JSON::Object::Ptr &Obj);
SUB_VERIFY_EMAIL, };
SUB_SIGNUP,
EMAIL_INVITATION
};
struct ActionLink { enum LinkActions {
std::string id; FORGOT_PASSWORD = 1,
uint64_t action; VERIFY_EMAIL,
std::string userId; SUB_FORGOT_PASSWORD,
std::string actionTemplate; SUB_VERIFY_EMAIL,
Types::StringPairVec variables; SUB_SIGNUP,
std::string locale; EMAIL_INVITATION
std::string message; };
uint64_t sent=0;
uint64_t created=Utils::Now();
uint64_t expires=0;
uint64_t completed=0;
uint64_t canceled=0;
bool userAction=true;
void to_json(Poco::JSON::Object &Obj) const; struct ActionLink {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string id;
}; uint64_t action;
std::string userId;
std::string actionTemplate;
Types::StringPairVec variables;
std::string locale;
std::string message;
uint64_t sent = 0;
uint64_t created = Utils::Now();
uint64_t expires = 0;
uint64_t completed = 0;
uint64_t canceled = 0;
bool userAction = true;
struct Preferences { void to_json(Poco::JSON::Object &Obj) const;
std::string id; bool from_json(const Poco::JSON::Object::Ptr &Obj);
uint64_t modified; };
Types::StringPairVec data;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct SubMfaConfig { struct Preferences {
std::string id; std::string id;
std::string type; uint64_t modified;
std::string sms; Types::StringPairVec data;
std::string email; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const; struct SubMfaConfig {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string id;
}; std::string type;
std::string sms;
std::string email;
struct Token { void to_json(Poco::JSON::Object &Obj) const;
std::string token; bool from_json(const Poco::JSON::Object::Ptr &Obj);
std::string refreshToken; };
std::string tokenType;
std::string userName;
uint64_t created=0;
uint64_t expires=0;
uint64_t idleTimeout=0;
uint64_t revocationDate=0;
uint64_t lastRefresh=0;
void to_json(Poco::JSON::Object &Obj) const; struct Token {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string token;
}; std::string refreshToken;
std::string tokenType;
std::string userName;
uint64_t created = 0;
uint64_t expires = 0;
uint64_t idleTimeout = 0;
uint64_t revocationDate = 0;
uint64_t lastRefresh = 0;
struct Avatar { void to_json(Poco::JSON::Object &Obj) const;
std::string id; bool from_json(const Poco::JSON::Object::Ptr &Obj);
std::string type; };
uint64_t created=0;
std::string name;
Poco::Data::BLOB avatar;
};
struct LoginRecordInfo { struct Avatar {
std::string sessionId; std::string id;
std::string userId; std::string type;
std::string email; uint64_t created = 0;
uint64_t login=0; std::string name;
uint64_t logout=0; Poco::Data::BLOB avatar;
};
void to_json(Poco::JSON::Object &Obj) const; struct LoginRecordInfo {
}; std::string sessionId;
std::string userId;
std::string email;
uint64_t login = 0;
uint64_t logout = 0;
struct ApiKeyAccessRight { void to_json(Poco::JSON::Object &Obj) const;
std::string service; };
std::string access;
void to_json(Poco::JSON::Object &Obj) const; struct ApiKeyAccessRight {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::string service;
}; std::string access;
struct ApiKeyAccessRightList { void to_json(Poco::JSON::Object &Obj) const;
std::vector<ApiKeyAccessRight> acls; bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const; struct ApiKeyAccessRightList {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::vector<ApiKeyAccessRight> acls;
};
struct ApiKeyEntry { void to_json(Poco::JSON::Object &Obj) const;
Types::UUID_t id; bool from_json(const Poco::JSON::Object::Ptr &Obj);
Types::UUID_t userUuid; };
std::string name;
std::string description;
std::string apiKey;
std::string salt;
std::uint64_t created;
std::uint64_t expiresOn=0;
ApiKeyAccessRightList rights;
std::uint64_t lastUse=0;
void to_json(Poco::JSON::Object &Obj) const; struct ApiKeyEntry {
bool from_json(const Poco::JSON::Object::Ptr &Obj); Types::UUID_t id;
}; Types::UUID_t userUuid;
std::string name;
std::string description;
std::string apiKey;
std::string salt;
std::uint64_t created;
std::uint64_t expiresOn = 0;
ApiKeyAccessRightList rights;
std::uint64_t lastUse = 0;
struct ApiKeyEntryList { void to_json(Poco::JSON::Object &Obj) const;
std::vector<ApiKeyEntry> apiKeys; bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
void to_json(Poco::JSON::Object &Obj) const; struct ApiKeyEntryList {
bool from_json(const Poco::JSON::Object::Ptr &Obj); std::vector<ApiKeyEntry> apiKeys;
};
} void to_json(Poco::JSON::Object &Obj) const;
} bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
} // namespace SecurityObjects
} // namespace OpenWifi

File diff suppressed because it is too large Load Diff

View File

@@ -11,312 +11,312 @@
namespace OpenWifi::SubObjects { namespace OpenWifi::SubObjects {
struct HomeDeviceMode { struct HomeDeviceMode {
bool enableLEDS = true; bool enableLEDS = true;
std::string type; // bridge, manual, automatic std::string type; // bridge, manual, automatic
std::string subnet; std::string subnet;
std::string subnetMask; std::string subnetMask;
std::string startIP; std::string startIP;
std::string endIP; std::string endIP;
uint64_t created = 0 ; uint64_t created = 0;
uint64_t modified = 0 ; uint64_t modified = 0;
std::string subnetV6; std::string subnetV6;
int subnetMaskV6=0; int subnetMaskV6 = 0;
std::string startIPV6; std::string startIPV6;
std::string endIPV6; std::string endIPV6;
std::string leaseTime; std::string leaseTime;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct IPReservation { struct IPReservation {
std::string nickname; std::string nickname;
std::string ipAddress; std::string ipAddress;
std::string macAddress; std::string macAddress;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct IPReservationList { struct IPReservationList {
std::string id; std::string id;
std::vector<IPReservation> reservations; std::vector<IPReservation> reservations;
uint64_t created = 0 ; uint64_t created = 0;
uint64_t modified = 0 ; uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DnsConfiguration { struct DnsConfiguration {
bool ISP=false; bool ISP = false;
bool custom=false; bool custom = false;
std::string primary; std::string primary;
std::string secondary; std::string secondary;
std::string primaryV6; std::string primaryV6;
std::string secondaryV6; std::string secondaryV6;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct InternetConnection { struct InternetConnection {
std::string type; // automatic, pppoe, manual std::string type; // automatic, pppoe, manual
std::string username; std::string username;
std::string password; std::string password;
std::string ipAddress; std::string ipAddress;
std::string subnetMask; std::string subnetMask;
std::string defaultGateway; std::string defaultGateway;
bool sendHostname = true; bool sendHostname = true;
std::string primaryDns; std::string primaryDns;
std::string secondaryDns; std::string secondaryDns;
uint64_t created=0; uint64_t created = 0;
uint64_t modified=0; uint64_t modified = 0;
bool ipV6Support=false; bool ipV6Support = false;
std::string ipAddressV6; std::string ipAddressV6;
int subnetMaskV6=0; int subnetMaskV6 = 0;
std::string defaultGatewayV6; std::string defaultGatewayV6;
std::string primaryDnsV6; std::string primaryDnsV6;
std::string secondaryDnsV6; std::string secondaryDnsV6;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct WifiNetwork { struct WifiNetwork {
std::string type; // main, guest std::string type; // main, guest
std::string name; std::string name;
std::string password; std::string password;
std::string encryption; std::string encryption;
std::vector<std::string> bands; std::vector<std::string> bands;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct WifiNetworkList { struct WifiNetworkList {
std::vector<WifiNetwork> wifiNetworks; std::vector<WifiNetwork> wifiNetworks;
uint64_t created=0; uint64_t created = 0;
uint64_t modified=0; uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct AccessTime { struct AccessTime {
std::string day; std::string day;
std::vector<std::string> rangeList; std::vector<std::string> rangeList;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct AccessTimes { struct AccessTimes {
std::vector<AccessTime> schedule; std::vector<AccessTime> schedule;
uint64_t created=0; uint64_t created = 0;
uint64_t modified=0; uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct SubscriberDevice { struct SubscriberDevice {
std::string name; std::string name;
std::string description; std::string description;
std::string macAddress; std::string macAddress;
std::string manufacturer; std::string manufacturer;
uint64_t firstContact=0; uint64_t firstContact = 0;
uint64_t lastContact=0; uint64_t lastContact = 0;
std::string group; std::string group;
std::string icon; std::string icon;
bool suspended=false; bool suspended = false;
std::string ip; std::string ip;
std::vector<AccessTimes> schedule; std::vector<AccessTimes> schedule;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct SubscriberDeviceList { struct SubscriberDeviceList {
std::vector<SubscriberDevice> devices; std::vector<SubscriberDevice> devices;
uint64_t created=0; uint64_t created = 0;
uint64_t modified=0; uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct Association { struct Association {
std::string name; std::string name;
std::string ssid; std::string ssid;
std::string macAddress; std::string macAddress;
int rssi=0; int rssi = 0;
int power=0; int power = 0;
std::string ipv4; std::string ipv4;
std::string ipv6; std::string ipv6;
uint64_t tx=0; uint64_t tx = 0;
uint64_t rx=0; uint64_t rx = 0;
std::string manufacturer; std::string manufacturer;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct AssociationList { struct AssociationList {
std::vector<Association> associations; std::vector<Association> associations;
uint64_t created=0; uint64_t created = 0;
uint64_t modified=0; uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct Client { struct Client {
std::string macAddress; std::string macAddress;
std::string speed; std::string speed;
std::string mode; std::string mode;
std::string ipv4; std::string ipv4;
std::string ipv6; std::string ipv6;
uint64_t tx=0; uint64_t tx = 0;
uint64_t rx=0; uint64_t rx = 0;
std::string manufacturer; std::string manufacturer;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct ClientList { struct ClientList {
std::vector<Client> clients; std::vector<Client> clients;
uint64_t created=0; uint64_t created = 0;
uint64_t modified=0; uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct Location { struct Location {
std::string buildingName; std::string buildingName;
std::vector<std::string> addressLines; std::vector<std::string> addressLines;
std::string city; std::string city;
std::string state; std::string state;
std::string postal; std::string postal;
std::string country; std::string country;
std::vector<std::string> phones; std::vector<std::string> phones;
std::vector<std::string> mobiles; std::vector<std::string> mobiles;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct RadioHE { struct RadioHE {
bool multipleBSSID = false; bool multipleBSSID = false;
bool ema = false; bool ema = false;
uint64_t bssColor = 64; uint64_t bssColor = 64;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct RadioRates { struct RadioRates {
uint64_t beacon = 6000; uint64_t beacon = 6000;
uint64_t multicast = 24000; uint64_t multicast = 24000;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct RadioInformation { struct RadioInformation {
std::string band; std::string band;
uint64_t bandwidth; uint64_t bandwidth;
uint64_t channel = 0 ; uint64_t channel = 0;
std::string country; std::string country;
std::string channelMode{"HE"}; std::string channelMode{"HE"};
uint64_t channelWidth = 80; uint64_t channelWidth = 80;
std::string requireMode; std::string requireMode;
uint64_t txpower=0; uint64_t txpower = 0;
bool legacyRates = false; bool legacyRates = false;
uint64_t beaconInterval = 100; uint64_t beaconInterval = 100;
uint64_t dtimPeriod = 2; uint64_t dtimPeriod = 2;
uint64_t maximumClients = 64; uint64_t maximumClients = 64;
RadioRates rates; RadioRates rates;
RadioHE he; RadioHE he;
bool allowDFS=false; bool allowDFS = false;
std::string mimo; std::string mimo;
std::vector<std::string> rawInfo; std::vector<std::string> rawInfo;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct AccessPoint { struct AccessPoint {
std::string id; std::string id;
std::string macAddress; std::string macAddress;
std::string serialNumber; std::string serialNumber;
std::string name; std::string name;
std::string deviceType; std::string deviceType;
SubscriberDeviceList subscriberDevices; SubscriberDeviceList subscriberDevices;
IPReservationList ipReservations; IPReservationList ipReservations;
Location address; Location address;
WifiNetworkList wifiNetworks; WifiNetworkList wifiNetworks;
InternetConnection internetConnection; InternetConnection internetConnection;
HomeDeviceMode deviceMode; HomeDeviceMode deviceMode;
DnsConfiguration dnsConfiguration; DnsConfiguration dnsConfiguration;
std::vector<RadioInformation> radios; std::vector<RadioInformation> radios;
bool automaticUpgrade = true; bool automaticUpgrade = true;
std::string configurationUUID; std::string configurationUUID;
std::string currentFirmware; std::string currentFirmware;
uint64_t currentFirmwareDate; uint64_t currentFirmwareDate;
std::string latestFirmware; std::string latestFirmware;
uint64_t latestFirmwareDate; uint64_t latestFirmwareDate;
bool newFirmwareAvailable; bool newFirmwareAvailable;
std::string latestFirmwareURI; std::string latestFirmwareURI;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct AccessPointList { struct AccessPointList {
std::vector<AccessPoint> list; std::vector<AccessPoint> list;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct SubscriberInfo { struct SubscriberInfo {
std::string id; std::string id;
std::string userId; std::string userId;
std::string firstName; std::string firstName;
std::string initials; std::string initials;
std::string lastName; std::string lastName;
std::string phoneNumber; std::string phoneNumber;
std::string secondaryEmail; std::string secondaryEmail;
AccessPointList accessPoints; AccessPointList accessPoints;
Location serviceAddress; Location serviceAddress;
Location billingAddress; Location billingAddress;
uint64_t created = 0; uint64_t created = 0;
uint64_t modified = 0; uint64_t modified = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct StatsEntry { struct StatsEntry {
uint64_t timestamp=0; uint64_t timestamp = 0;
uint64_t tx=0; uint64_t tx = 0;
uint64_t rx=0; uint64_t rx = 0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct StatsBlock { struct StatsBlock {
uint64_t modified=0; uint64_t modified = 0;
std::vector<StatsEntry> external, internal; std::vector<StatsEntry> external, internal;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
} } // namespace OpenWifi::SubObjects
#endif //OWSUB_RESTAPI_SUBOBJECTS_H #endif // OWSUB_RESTAPI_SUBOBJECTS_H

View File

@@ -3,8 +3,8 @@
// //
#include "StatsSvr.h" #include "StatsSvr.h"
#include "framework/KafkaTopics.h"
#include "framework/KafkaManager.h" #include "framework/KafkaManager.h"
#include "framework/KafkaTopics.h"
#include "nlohmann/json.hpp" #include "nlohmann/json.hpp"
#include <fmt/format.h> #include <fmt/format.h>
@@ -12,99 +12,120 @@
namespace OpenWifi { namespace OpenWifi {
int StatsSvr::Start() { int StatsSvr::Start() {
Running_ = true; Running_ = true;
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) { this->StatsReceived(Key,Payload); }; Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) {
StatsWatcherId_ = KafkaManager()->RegisterTopicWatcher(KafkaTopics::STATE, F); this->StatsReceived(Key, Payload);
Worker_.start(*this); };
return 0; StatsWatcherId_ = KafkaManager()->RegisterTopicWatcher(KafkaTopics::STATE, F);
} Worker_.start(*this);
return 0;
}
void StatsSvr::Stop() { void StatsSvr::Stop() {
Running_ = false; Running_ = false;
KafkaManager()->UnregisterTopicWatcher(KafkaTopics::CONNECTION, StatsWatcherId_); KafkaManager()->UnregisterTopicWatcher(KafkaTopics::CONNECTION, StatsWatcherId_);
Queue_.wakeUpAll(); Queue_.wakeUpAll();
Worker_.join(); Worker_.join();
} }
void StatsSvr::run() { void StatsSvr::run() {
Utils::SetThreadName("stats-svr"); Utils::SetThreadName("stats-svr");
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification()); Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
while(Note && Running_) { while (Note && Running_) {
auto Msg = dynamic_cast<Stats_Msg *>(Note.get()); auto Msg = dynamic_cast<Stats_Msg *>(Note.get());
if(Msg!= nullptr) { if (Msg != nullptr) {
try { try {
nlohmann::json msg = nlohmann::json::parse(Msg->Payload()); nlohmann::json msg = nlohmann::json::parse(Msg->Payload());
if (msg.contains(uCentralProtocol::PAYLOAD)) { if (msg.contains(uCentralProtocol::PAYLOAD)) {
auto payload = msg[uCentralProtocol::PAYLOAD]; auto payload = msg[uCentralProtocol::PAYLOAD];
if (payload.contains("state") && payload.contains("serial")) { if (payload.contains("state") && payload.contains("serial")) {
auto serialNumber = payload["serial"].get<std::string>(); auto serialNumber = payload["serial"].get<std::string>();
auto state = payload["state"]; auto state = payload["state"];
if (state.contains("version")) { if (state.contains("version")) {
if (state.contains("unit")) { if (state.contains("unit")) {
auto unit = state["unit"]; auto unit = state["unit"];
if (unit.contains("localtime")) { if (unit.contains("localtime")) {
uint64_t timestamp = unit["localtime"]; uint64_t timestamp = unit["localtime"];
if (state.contains("interfaces")) { if (state.contains("interfaces")) {
if (state["interfaces"].is_array()) { if (state["interfaces"].is_array()) {
auto interfaces = state["interfaces"]; auto interfaces = state["interfaces"];
auto serial_int = Utils::SerialNumberToInt(serialNumber); auto serial_int =
uint64_t int_rx=0, int_tx=0, ext_rx=0,ext_tx=0; Utils::SerialNumberToInt(serialNumber);
for (const auto &cur_int: interfaces) { uint64_t int_rx = 0, int_tx = 0, ext_rx = 0,
bool external_stats=true; ext_tx = 0;
if(cur_int.contains("location")) { for (const auto &cur_int : interfaces) {
auto location = cur_int["location"].get<std::string>(); bool external_stats = true;
auto parts = Poco::StringTokenizer(location,"/"); if (cur_int.contains("location")) {
if(parts.count()==3) { auto location =
if(parts[2]=="0") cur_int["location"].get<std::string>();
external_stats = true; auto parts =
else Poco::StringTokenizer(location, "/");
external_stats = false; if (parts.count() == 3) {
} if (parts[2] == "0")
} external_stats = true;
else
external_stats = false;
}
}
if (cur_int.contains("counters") && cur_int["counters"].contains("rx_bytes") && cur_int["counters"].contains("tx_bytes")) { if (cur_int.contains("counters") &&
if(external_stats) { cur_int["counters"].contains("rx_bytes") &&
ext_rx = cur_int["counters"]["rx_bytes"].get<uint64_t>(); cur_int["counters"].contains("tx_bytes")) {
ext_tx = cur_int["counters"]["tx_bytes"].get<uint64_t>(); if (external_stats) {
} else { ext_rx = cur_int["counters"]["rx_bytes"]
int_rx = cur_int["counters"]["rx_bytes"].get<uint64_t>(); .get<uint64_t>();
int_tx = cur_int["counters"]["tx_bytes"].get<uint64_t>(); ext_tx = cur_int["counters"]["tx_bytes"]
} .get<uint64_t>();
} } else {
} int_rx = cur_int["counters"]["rx_bytes"]
{ .get<uint64_t>();
std::lock_guard G(Mutex_); int_tx = cur_int["counters"]["tx_bytes"]
auto it = DeviceStats_.find(serial_int); .get<uint64_t>();
if (it == end(DeviceStats_)) { }
DeviceStats D; }
D.AddValue(timestamp, ext_tx, ext_rx, int_tx, int_rx); }
DeviceStats_[serial_int] = D; {
poco_debug(Logger(),fmt::format("Creating statistics cache for device {}",serialNumber)); std::lock_guard G(Mutex_);
} else { auto it = DeviceStats_.find(serial_int);
poco_debug(Logger(),fmt::format("Adding statistics cache for device {}",serialNumber)); if (it == end(DeviceStats_)) {
it->second.AddValue(timestamp, ext_tx, ext_rx, int_tx, int_rx); DeviceStats D;
std::cout << "Adding device stats entries for " << serialNumber D.AddValue(timestamp, ext_tx, ext_rx,
<< std::endl; int_tx, int_rx);
} DeviceStats_[serial_int] = D;
} poco_debug(
} Logger(),
} fmt::format("Creating statistics cache "
} "for device {}",
} serialNumber));
} } else {
} poco_debug(
} Logger(),
} catch (const Poco::Exception &E) { fmt::format("Adding statistics cache "
Logger().log(E); "for device {}",
} catch (...) { serialNumber));
it->second.AddValue(timestamp, ext_tx,
ext_rx, int_tx, int_rx);
std::cout
<< "Adding device stats entries for "
<< serialNumber << std::endl;
}
}
}
}
}
}
}
}
}
} catch (const Poco::Exception &E) {
Logger().log(E);
} catch (...) {
}
} else {
}
Note = Queue_.waitDequeueNotification();
}
}
} } // namespace OpenWifi
} else {
}
Note = Queue_.waitDequeueNotification();
}
}
}

View File

@@ -4,121 +4,120 @@
#pragma once #pragma once
#include "RESTObjects/RESTAPI_SubObjects.h"
#include "framework/SubSystemServer.h"
#include "Poco/Notification.h" #include "Poco/Notification.h"
#include "Poco/NotificationQueue.h" #include "Poco/NotificationQueue.h"
#include "RESTObjects/RESTAPI_SubObjects.h"
#include "framework/SubSystemServer.h"
#include "framework/utils.h" #include "framework/utils.h"
namespace OpenWifi { namespace OpenWifi {
class Stats_Msg : public Poco::Notification { class Stats_Msg : public Poco::Notification {
public: public:
explicit Stats_Msg(std::string Key, std::string Payload ) : explicit Stats_Msg(std::string Key, std::string Payload)
Key_(std::move(Key)), : Key_(std::move(Key)), Payload_(std::move(Payload)) {}
Payload_(std::move(Payload)) {} const std::string &Key() { return Key_; }
const std::string & Key() { return Key_; } const std::string &Payload() { return Payload_; }
const std::string & Payload() { return Payload_; }
private:
std::string Key_;
std::string Payload_;
};
struct DeviceStats { private:
uint64_t LastUpdate_=0; std::string Key_;
constexpr static const size_t buffer_size = 20; std::string Payload_;
std::array<std::uint64_t,buffer_size> timestamps,ext_txs,ext_rxs,int_txs,int_rxs; };
uint64_t base_int_tx=0,base_int_rx=0,base_ext_tx=0,base_ext_rx=0;
uint32_t index_=0; struct DeviceStats {
bool no_base=true; uint64_t LastUpdate_ = 0;
void AddValue(uint64_t ts, uint32_t ext_tx, uint32_t ext_rx, uint32_t int_tx, uint32_t int_rx ) { constexpr static const size_t buffer_size = 20;
if(no_base) { std::array<std::uint64_t, buffer_size> timestamps, ext_txs, ext_rxs, int_txs, int_rxs;
base_int_rx = int_rx; uint64_t base_int_tx = 0, base_int_rx = 0, base_ext_tx = 0, base_ext_rx = 0;
base_int_tx = int_tx;
base_ext_rx = ext_rx;
base_ext_tx = ext_tx;
no_base = false;
return;
}
timestamps[index_] = ts; uint32_t index_ = 0;
int_txs[index_] = int_tx - base_int_tx; bool no_base = true;
base_int_tx = int_tx; void AddValue(uint64_t ts, uint32_t ext_tx, uint32_t ext_rx, uint32_t int_tx,
int_rxs[index_] = int_rx - base_int_rx; uint32_t int_rx) {
base_int_rx = int_rx; if (no_base) {
ext_txs[index_] = ext_tx - base_ext_tx; base_int_rx = int_rx;
base_ext_tx = ext_tx; base_int_tx = int_tx;
ext_rxs[index_] = ext_rx - base_ext_rx; base_ext_rx = ext_rx;
base_ext_rx = ext_rx; base_ext_tx = ext_tx;
index_++; no_base = false;
return;
}
if(index_==buffer_size) { timestamps[index_] = ts;
// move everything down by one... int_txs[index_] = int_tx - base_int_tx;
std::memmove(&timestamps[0],&timestamps[1], sizeof(timestamps[1])*buffer_size-1); base_int_tx = int_tx;
std::memmove(&ext_txs[0],&ext_txs[1], sizeof(ext_txs[1])*buffer_size-1); int_rxs[index_] = int_rx - base_int_rx;
std::memmove(&ext_rxs[0],&ext_rxs[1], sizeof(ext_rxs[1])*buffer_size-1); base_int_rx = int_rx;
std::memmove(&int_txs[0],&int_txs[1], sizeof(int_txs[1])*buffer_size-1); ext_txs[index_] = ext_tx - base_ext_tx;
std::memmove(&int_rxs[0],&int_rxs[1], sizeof(int_rxs[1])*buffer_size-1); base_ext_tx = ext_tx;
index_--; ext_rxs[index_] = ext_rx - base_ext_rx;
} base_ext_rx = ext_rx;
LastUpdate_ = Utils::Now(); index_++;
}
void print() { if (index_ == buffer_size) {
for(size_t i=0;i<index_;i++) { // move everything down by one...
std::cout << "TS: " << timestamps[i] << " ext_tx:" << ext_txs[i] << " ext_rx:" << ext_rxs[i] << std::memmove(&timestamps[0], &timestamps[1],
" int_tx:" << int_txs[i] << " int_rx:" << int_rxs[i] << std::endl; sizeof(timestamps[1]) * buffer_size - 1);
} std::memmove(&ext_txs[0], &ext_txs[1], sizeof(ext_txs[1]) * buffer_size - 1);
} std::memmove(&ext_rxs[0], &ext_rxs[1], sizeof(ext_rxs[1]) * buffer_size - 1);
std::memmove(&int_txs[0], &int_txs[1], sizeof(int_txs[1]) * buffer_size - 1);
std::memmove(&int_rxs[0], &int_rxs[1], sizeof(int_rxs[1]) * buffer_size - 1);
index_--;
}
LastUpdate_ = Utils::Now();
}
void Get(SubObjects::StatsBlock &Stats) { void print() {
Stats.modified = LastUpdate_; for (size_t i = 0; i < index_; i++) {
for(size_t i=0;i<index_;i++) { std::cout << "TS: " << timestamps[i] << " ext_tx:" << ext_txs[i]
Stats.external.push_back({timestamps[i], ext_txs[i],ext_rxs[i]}); << " ext_rx:" << ext_rxs[i] << " int_tx:" << int_txs[i]
Stats.internal.push_back({timestamps[i], int_txs[i],int_rxs[i]}); << " int_rx:" << int_rxs[i] << std::endl;
} }
} }
};
class StatsSvr : public SubSystemServer, Poco::Runnable { void Get(SubObjects::StatsBlock &Stats) {
public: Stats.modified = LastUpdate_;
static auto instance() { for (size_t i = 0; i < index_; i++) {
static auto instance_ = new StatsSvr; Stats.external.push_back({timestamps[i], ext_txs[i], ext_rxs[i]});
return instance_; Stats.internal.push_back({timestamps[i], int_txs[i], int_rxs[i]});
} }
}
};
int Start() override; class StatsSvr : public SubSystemServer, Poco::Runnable {
void Stop() override; public:
void run() override; static auto instance() {
static auto instance_ = new StatsSvr;
return instance_;
}
inline void StatsReceived( const std::string & Key, const std::string & Payload) { int Start() override;
std::lock_guard G(Mutex_); void Stop() override;
// Logger().information(fmt::format("Device({}): Connection/Ping message.", Key)); void run() override;
Queue_.enqueueNotification( new Stats_Msg(Key,Payload));
}
inline void Get(const std::string &SerialNumber, SubObjects::StatsBlock &Stats) { inline void StatsReceived(const std::string &Key, const std::string &Payload) {
std::lock_guard G(Mutex_); std::lock_guard G(Mutex_);
// Logger().information(fmt::format("Device({}): Connection/Ping message.", Key));
Queue_.enqueueNotification(new Stats_Msg(Key, Payload));
}
auto it = DeviceStats_.find(Utils::SerialNumberToInt(SerialNumber)); inline void Get(const std::string &SerialNumber, SubObjects::StatsBlock &Stats) {
if(it==end(DeviceStats_)) std::lock_guard G(Mutex_);
return;
it->second.Get(Stats);
}
private: auto it = DeviceStats_.find(Utils::SerialNumberToInt(SerialNumber));
uint64_t StatsWatcherId_=0; if (it == end(DeviceStats_))
Poco::NotificationQueue Queue_; return;
Poco::Thread Worker_; it->second.Get(Stats);
std::atomic_bool Running_=false; }
std::map<std::uint64_t, DeviceStats> DeviceStats_;
StatsSvr() noexcept: private:
SubSystemServer("StateSvr", "STATS-SVR", "statscache") uint64_t StatsWatcherId_ = 0;
{ Poco::NotificationQueue Queue_;
} Poco::Thread Worker_;
std::atomic_bool Running_ = false;
std::map<std::uint64_t, DeviceStats> DeviceStats_;
}; StatsSvr() noexcept : SubSystemServer("StateSvr", "STATS-SVR", "statscache") {}
inline auto StatsSvr() { return StatsSvr::instance(); } };
} inline auto StatsSvr() { return StatsSvr::instance(); }
} // namespace OpenWifi

View File

@@ -10,23 +10,23 @@
namespace OpenWifi { namespace OpenWifi {
int StorageService::Start() { int StorageService::Start() {
std::lock_guard Guard(Mutex_); std::lock_guard Guard(Mutex_);
Logger().notice("Starting."); Logger().notice("Starting.");
StorageClass::Start(); StorageClass::Start();
SubscriberDB_ = std::make_unique<OpenWifi::SubscriberInfoDB>(dbType_,*Pool_, Logger()); SubscriberDB_ = std::make_unique<OpenWifi::SubscriberInfoDB>(dbType_, *Pool_, Logger());
SubscriberDB_->Create(); SubscriberDB_->Create();
return 0; return 0;
} }
void StorageService::Stop() { void StorageService::Stop() {
std::lock_guard Guard(Mutex_); std::lock_guard Guard(Mutex_);
StorageClass::Stop(); StorageClass::Stop();
Logger().notice("Stopping."); Logger().notice("Stopping.");
} }
} } // namespace OpenWifi
// namespace // namespace

View File

@@ -10,11 +10,11 @@
#include <map> #include <map>
#include "Poco/Data/MySQL/Connector.h"
#include "Poco/Data/PostgreSQL/Connector.h"
#include "Poco/Data/SQLite/Connector.h"
#include "Poco/Data/Session.h" #include "Poco/Data/Session.h"
#include "Poco/Data/SessionPool.h" #include "Poco/Data/SessionPool.h"
#include "Poco/Data/SQLite/Connector.h"
#include "Poco/Data/PostgreSQL/Connector.h"
#include "Poco/Data/MySQL/Connector.h"
#include "framework/StorageClass.h" #include "framework/StorageClass.h"
@@ -22,24 +22,24 @@
namespace OpenWifi { namespace OpenWifi {
class StorageService : public StorageClass { class StorageService : public StorageClass {
public: public:
static StorageService *instance() { static StorageService *instance() {
static auto instance_ = new StorageService; static auto instance_ = new StorageService;
return instance_; return instance_;
} }
OpenWifi::SubscriberInfoDB & SubInfoDB() { return *SubscriberDB_; }; OpenWifi::SubscriberInfoDB &SubInfoDB() { return *SubscriberDB_; };
int Start() override; int Start() override;
void Stop() override; void Stop() override;
private: private:
std::unique_ptr<OpenWifi::SubscriberInfoDB> SubscriberDB_; std::unique_ptr<OpenWifi::SubscriberInfoDB> SubscriberDB_;
Poco::Thread Updater_; Poco::Thread Updater_;
std::atomic_bool Running_=false; std::atomic_bool Running_ = false;
}; };
inline class StorageService * StorageService() { return StorageService::instance(); } inline class StorageService *StorageService() { return StorageService::instance(); }
} // namespace } // namespace OpenWifi

View File

@@ -7,28 +7,27 @@
namespace OpenWifi { namespace OpenWifi {
int SubscriberCache::Start() { int SubscriberCache::Start() { return 0; }
return 0;
}
void SubscriberCache::Stop() { void SubscriberCache::Stop() {}
}
bool SubscriberCache::GetSubInfo(const std::string &Id, Poco::SharedPtr<SubObjects::SubscriberInfo> & SubInfo) { bool SubscriberCache::GetSubInfo(const std::string &Id,
if(SubsCache_.has(Id)) { Poco::SharedPtr<SubObjects::SubscriberInfo> &SubInfo) {
SubInfo = SubsCache_.get(Id); if (SubsCache_.has(Id)) {
return true; SubInfo = SubsCache_.get(Id);
} return true;
SubObjects::SubscriberInfo Sub; }
if(StorageService()->SubInfoDB().GetRecord("id",Id,Sub)) { SubObjects::SubscriberInfo Sub;
SubsCache_.update(Id,Sub); if (StorageService()->SubInfoDB().GetRecord("id", Id, Sub)) {
SubInfo = SubsCache_.get(Id); SubsCache_.update(Id, Sub);
return true; SubInfo = SubsCache_.get(Id);
} return true;
return false; }
} return false;
}
void SubscriberCache::UpdateSubInfo(const std::string &Id, const SubObjects::SubscriberInfo &SubInfo) { void SubscriberCache::UpdateSubInfo(const std::string &Id,
SubsCache_.update(Id,SubInfo); const SubObjects::SubscriberInfo &SubInfo) {
} SubsCache_.update(Id, SubInfo);
} }
} // namespace OpenWifi

View File

@@ -4,34 +4,31 @@
#pragma once #pragma once
#include "framework/SubSystemServer.h"
#include "RESTObjects/RESTAPI_SubObjects.h"
#include "Poco/ExpireLRUCache.h" #include "Poco/ExpireLRUCache.h"
#include "RESTObjects/RESTAPI_SubObjects.h"
#include "framework/SubSystemServer.h"
namespace OpenWifi { namespace OpenWifi {
class SubscriberCache : public SubSystemServer { class SubscriberCache : public SubSystemServer {
public: public:
static SubscriberCache *instance() { static SubscriberCache *instance() {
static auto instance_ = new SubscriberCache; static auto instance_ = new SubscriberCache;
return instance_; return instance_;
} }
int Start() override; int Start() override;
void Stop() override; void Stop() override;
bool GetSubInfo(const std::string &Id, Poco::SharedPtr<SubObjects::SubscriberInfo> & SubInfo); bool GetSubInfo(const std::string &Id,
void UpdateSubInfo(const std::string &Id, const SubObjects::SubscriberInfo& SubInfo); Poco::SharedPtr<SubObjects::SubscriberInfo> &SubInfo);
void UpdateSubInfo(const std::string &Id, const SubObjects::SubscriberInfo &SubInfo);
private: private:
Poco::ExpireLRUCache<std::string,SubObjects::SubscriberInfo> SubsCache_{2048}; Poco::ExpireLRUCache<std::string, SubObjects::SubscriberInfo> SubsCache_{2048};
SubscriberCache() noexcept: SubscriberCache() noexcept : SubSystemServer("SubscriberCache", "SUb-CACHE", "subcache") {}
SubSystemServer("SubscriberCache", "SUb-CACHE", "subcache") };
{
}
}; inline class SubscriberCache *SubscriberCache() { return SubscriberCache::instance(); }
inline class SubscriberCache * SubscriberCache() { return SubscriberCache::instance(); } } // namespace OpenWifi
}

View File

@@ -4,17 +4,19 @@
#include "ALBserver.h" #include "ALBserver.h"
#include "framework/utils.h"
#include "framework/MicroServiceFuncs.h"
#include "fmt/format.h" #include "fmt/format.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
namespace OpenWifi { namespace OpenWifi {
void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) { void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request,
Poco::Net::HTTPServerResponse &Response) {
Utils::SetThreadName("alb-request"); Utils::SetThreadName("alb-request");
try { try {
if((id_ % 100) == 0) { if ((id_ % 100) == 0) {
Logger_.debug(fmt::format("ALB-REQUEST({}): ALB Request {}.", Request.clientAddress().toString(), id_)); Logger_.debug(fmt::format("ALB-REQUEST({}): ALB Request {}.",
Request.clientAddress().toString(), id_));
} }
Response.setChunkedTransferEncoding(true); Response.setChunkedTransferEncoding(true);
Response.setContentType("text/html"); Response.setContentType("text/html");
@@ -26,31 +28,27 @@ namespace OpenWifi {
std::ostream &Answer = Response.send(); std::ostream &Answer = Response.send();
Answer << "process Alive and kicking!"; Answer << "process Alive and kicking!";
} catch (...) { } catch (...) {
} }
} }
ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger & L): ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger &L) : Logger_(L) {}
Logger_(L) {
}
ALBRequestHandler* ALBRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest& request) { ALBRequestHandler *
ALBRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &request) {
if (request.getURI() == "/") if (request.getURI() == "/")
return new ALBRequestHandler(Logger_, req_id_++); return new ALBRequestHandler(Logger_, req_id_++);
else else
return nullptr; return nullptr;
} }
ALBHealthCheckServer::ALBHealthCheckServer() : ALBHealthCheckServer::ALBHealthCheckServer()
SubSystemServer("ALBHealthCheckServer", "ALB-SVR", "alb") : SubSystemServer("ALBHealthCheckServer", "ALB-SVR", "alb") {}
{
}
int ALBHealthCheckServer::Start() { int ALBHealthCheckServer::Start() {
if(MicroServiceConfigGetBool("alb.enable",false)) { if (MicroServiceConfigGetBool("alb.enable", false)) {
poco_information(Logger(),"Starting..."); poco_information(Logger(), "Starting...");
Running_=true; Running_ = true;
Port_ = (int)MicroServiceConfigGetInt("alb.port",15015); Port_ = (int)MicroServiceConfigGetInt("alb.port", 15015);
Poco::Net::IPAddress Addr(Poco::Net::IPAddress::wildcard( Poco::Net::IPAddress Addr(Poco::Net::IPAddress::wildcard(
Poco::Net::Socket::supportsIPv6() ? Poco::Net::AddressFamily::IPv6 Poco::Net::Socket::supportsIPv6() ? Poco::Net::AddressFamily::IPv6
: Poco::Net::AddressFamily::IPv4)); : Poco::Net::AddressFamily::IPv4));
@@ -60,7 +58,8 @@ namespace OpenWifi {
Socket_ = std::make_unique<Poco::Net::ServerSocket>(SockAddr, Port_); Socket_ = std::make_unique<Poco::Net::ServerSocket>(SockAddr, Port_);
auto Params = new Poco::Net::HTTPServerParams; auto Params = new Poco::Net::HTTPServerParams;
Params->setName("ws:alb"); Params->setName("ws:alb");
Server_ = std::make_unique<Poco::Net::HTTPServer>(new ALBRequestHandlerFactory(Logger()), *Socket_, Params); Server_ = std::make_unique<Poco::Net::HTTPServer>(
new ALBRequestHandlerFactory(Logger()), *Socket_, Params);
Server_->start(); Server_->start();
} }
@@ -68,10 +67,10 @@ namespace OpenWifi {
} }
void ALBHealthCheckServer::Stop() { void ALBHealthCheckServer::Stop() {
poco_information(Logger(),"Stopping..."); poco_information(Logger(), "Stopping...");
if(Running_) if (Running_)
Server_->stopAll(true); Server_->stopAll(true);
poco_information(Logger(),"Stopped..."); poco_information(Logger(), "Stopped...");
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -7,35 +7,34 @@
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h" #include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
namespace OpenWifi { namespace OpenWifi {
class ALBRequestHandler: public Poco::Net::HTTPRequestHandler { class ALBRequestHandler : public Poco::Net::HTTPRequestHandler {
public: public:
explicit ALBRequestHandler(Poco::Logger & L, uint64_t id) explicit ALBRequestHandler(Poco::Logger &L, uint64_t id) : Logger_(L), id_(id) {}
: Logger_(L), id_(id) {
}
void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) override; void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request,
Poco::Net::HTTPServerResponse &Response) override;
private: private:
Poco::Logger & Logger_; Poco::Logger &Logger_;
uint64_t id_; uint64_t id_;
}; };
class ALBRequestHandlerFactory: public Poco::Net::HTTPRequestHandlerFactory class ALBRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
{
public: public:
explicit ALBRequestHandlerFactory(Poco::Logger & L); explicit ALBRequestHandlerFactory(Poco::Logger &L);
ALBRequestHandler* createRequestHandler(const Poco::Net::HTTPServerRequest& request) override; ALBRequestHandler *
createRequestHandler(const Poco::Net::HTTPServerRequest &request) override;
private: private:
Poco::Logger &Logger_; Poco::Logger &Logger_;
inline static std::atomic_uint64_t req_id_=1; inline static std::atomic_uint64_t req_id_ = 1;
}; };
class ALBHealthCheckServer : public SubSystemServer { class ALBHealthCheckServer : public SubSystemServer {
@@ -51,13 +50,12 @@ namespace OpenWifi {
void Stop() override; void Stop() override;
private: private:
std::unique_ptr<Poco::Net::HTTPServer> Server_; std::unique_ptr<Poco::Net::HTTPServer> Server_;
std::unique_ptr<Poco::Net::ServerSocket> Socket_; std::unique_ptr<Poco::Net::ServerSocket> Socket_;
int Port_ = 0; int Port_ = 0;
mutable std::atomic_bool Running_=false; mutable std::atomic_bool Running_ = false;
}; };
inline auto ALBHealthCheckServer() { return ALBHealthCheckServer::instance(); } inline auto ALBHealthCheckServer() { return ALBHealthCheckServer::instance(); }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,96 +4,94 @@
#pragma once #pragma once
#include "Poco/Logger.h"
#include "Poco/JSON/Parser.h" #include "Poco/JSON/Parser.h"
#include "Poco/Logger.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/URI.h" #include "Poco/URI.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
namespace OpenWifi { namespace OpenWifi {
inline void API_Proxy( Poco::Logger &Logger, inline void API_Proxy(Poco::Logger &Logger, Poco::Net::HTTPServerRequest *Request,
Poco::Net::HTTPServerRequest *Request, Poco::Net::HTTPServerResponse *Response, const char *ServiceType,
Poco::Net::HTTPServerResponse *Response, const char *PathRewrite, uint64_t msTimeout_ = 10000) {
const char * ServiceType, try {
const char * PathRewrite, auto Services = MicroServiceGetServices(ServiceType);
uint64_t msTimeout_ = 10000 ) { for (auto const &Svc : Services) {
try { Poco::URI SourceURI(Request->getURI());
auto Services = MicroServiceGetServices(ServiceType); Poco::URI DestinationURI(Svc.PrivateEndPoint);
for(auto const &Svc:Services) { DestinationURI.setPath(PathRewrite);
Poco::URI SourceURI(Request->getURI()); DestinationURI.setQuery(SourceURI.getQuery());
Poco::URI DestinationURI(Svc.PrivateEndPoint);
DestinationURI.setPath(PathRewrite);
DestinationURI.setQuery(SourceURI.getQuery());
// std::cout << " Source: " << SourceURI.toString() << std::endl; // std::cout << " Source: " << SourceURI.toString() << std::endl;
// std::cout << "Destination: " << DestinationURI.toString() << std::endl; // std::cout << "Destination: " << DestinationURI.toString() << std::endl;
Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(), DestinationURI.getPort()); Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(),
Session.setKeepAlive(true); DestinationURI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_/1000, msTimeout_ % 1000)); Session.setKeepAlive(true);
Poco::Net::HTTPRequest ProxyRequest(Request->getMethod(), Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
DestinationURI.getPathAndQuery(), Poco::Net::HTTPRequest ProxyRequest(Request->getMethod(),
Poco::Net::HTTPMessage::HTTP_1_1); DestinationURI.getPathAndQuery(),
if(Request->has("Authorization")) { Poco::Net::HTTPMessage::HTTP_1_1);
ProxyRequest.add("Authorization", Request->get("Authorization")); if (Request->has("Authorization")) {
} else { ProxyRequest.add("Authorization", Request->get("Authorization"));
ProxyRequest.add("X-API-KEY", Svc.AccessKey); } else {
ProxyRequest.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); ProxyRequest.add("X-API-KEY", Svc.AccessKey);
} ProxyRequest.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
}
if(Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE) { if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_DELETE) {
Session.sendRequest(ProxyRequest); Session.sendRequest(ProxyRequest);
Poco::Net::HTTPResponse ProxyResponse; Poco::Net::HTTPResponse ProxyResponse;
Session.receiveResponse(ProxyResponse); Session.receiveResponse(ProxyResponse);
Response->setStatus(ProxyResponse.getStatus()); Response->setStatus(ProxyResponse.getStatus());
Response->send(); Response->send();
return; return;
} else { } else {
Poco::JSON::Parser P; Poco::JSON::Parser P;
std::stringstream SS; std::stringstream SS;
try { try {
auto Body = P.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>(); auto Body = P.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>();
Poco::JSON::Stringifier::condense(Body,SS); Poco::JSON::Stringifier::condense(Body, SS);
SS << "\r\n\r\n"; SS << "\r\n\r\n";
} catch(const Poco::Exception &E) { } catch (const Poco::Exception &E) {
Logger.log(E); Logger.log(E);
} }
if(SS.str().empty()) { if (SS.str().empty()) {
Session.sendRequest(ProxyRequest); Session.sendRequest(ProxyRequest);
} else { } else {
ProxyRequest.setContentType("application/json"); ProxyRequest.setContentType("application/json");
ProxyRequest.setContentLength(SS.str().size()); ProxyRequest.setContentLength(SS.str().size());
std::ostream & os = Session.sendRequest(ProxyRequest); std::ostream &os = Session.sendRequest(ProxyRequest);
os << SS.str() ; os << SS.str();
} }
Poco::Net::HTTPResponse ProxyResponse; Poco::Net::HTTPResponse ProxyResponse;
std::stringstream SSR; std::stringstream SSR;
try { try {
std::istream &ProxyResponseStream = Session.receiveResponse(ProxyResponse); std::istream &ProxyResponseStream = Session.receiveResponse(ProxyResponse);
Poco::JSON::Parser P2; Poco::JSON::Parser P2;
auto ProxyResponseBody = P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>(); auto ProxyResponseBody =
Poco::JSON::Stringifier::condense(ProxyResponseBody,SSR); P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>();
Response->setContentType("application/json"); Poco::JSON::Stringifier::condense(ProxyResponseBody, SSR);
Response->setContentLength(SSR.str().size()); Response->setContentType("application/json");
Response->setStatus(ProxyResponse.getStatus()); Response->setContentLength(SSR.str().size());
Response->sendBuffer(SSR.str().c_str(),SSR.str().size()); Response->setStatus(ProxyResponse.getStatus());
return; Response->sendBuffer(SSR.str().c_str(), SSR.str().size());
} catch( const Poco::Exception & E) { return;
} catch (const Poco::Exception &E) {
}
Response->setStatus(ProxyResponse.getStatus());
Response->send();
return;
}
}
} } catch (const Poco::Exception &E) {
Response->setStatus(ProxyResponse.getStatus()); Logger.log(E);
Response->send(); }
return; }
} } // namespace OpenWifi
}
} catch (const Poco::Exception &E) {
Logger.log(E);
}
}
}

View File

@@ -4,13 +4,13 @@
#pragma once #pragma once
#include <string>
#include <fstream> #include <fstream>
#include <iomanip> #include <iomanip>
#include <iostream> #include <iostream>
#include <string>
#include "Poco/StreamCopier.h"
#include "Poco/File.h" #include "Poco/File.h"
#include "Poco/StreamCopier.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
@@ -18,7 +18,6 @@
namespace OpenWifi { namespace OpenWifi {
class AppServiceRegistry { class AppServiceRegistry {
public: public:
AppServiceRegistry() { AppServiceRegistry() {
@@ -26,9 +25,9 @@ namespace OpenWifi {
Poco::File F(FileName); Poco::File F(FileName);
try { try {
if(F.exists()) { if (F.exists()) {
std::ostringstream OS; std::ostringstream OS;
std::ifstream IF(FileName); std::ifstream IF(FileName);
Poco::StreamCopier::copyStream(IF, OS); Poco::StreamCopier::copyStream(IF, OS);
Registry_ = nlohmann::json::parse(OS.str()); Registry_ = nlohmann::json::parse(OS.str());
} }
@@ -37,55 +36,53 @@ namespace OpenWifi {
} }
} }
static AppServiceRegistry & instance() { static AppServiceRegistry &instance() {
static auto instance_= new AppServiceRegistry; static auto instance_ = new AppServiceRegistry;
return *instance_; return *instance_;
} }
inline ~AppServiceRegistry() { inline ~AppServiceRegistry() { Save(); }
Save();
}
inline void Save() { inline void Save() {
std::istringstream IS( to_string(Registry_)); std::istringstream IS(to_string(Registry_));
std::ofstream OF; std::ofstream OF;
OF.open(FileName,std::ios::binary | std::ios::trunc); OF.open(FileName, std::ios::binary | std::ios::trunc);
Poco::StreamCopier::copyStream(IS, OF); Poco::StreamCopier::copyStream(IS, OF);
} }
inline void Set(const char *Key, uint64_t Value ) { inline void Set(const char *Key, uint64_t Value) {
Registry_[Key] = Value; Registry_[Key] = Value;
Save(); Save();
} }
inline void Set(const char *Key, const std::string &Value ) { inline void Set(const char *Key, const std::string &Value) {
Registry_[Key] = Value; Registry_[Key] = Value;
Save(); Save();
} }
inline void Set(const char *Key, bool Value ) { inline void Set(const char *Key, bool Value) {
Registry_[Key] = Value; Registry_[Key] = Value;
Save(); Save();
} }
inline bool Get(const char *Key, bool & Value ) { inline bool Get(const char *Key, bool &Value) {
if(Registry_[Key].is_boolean()) { if (Registry_[Key].is_boolean()) {
Value = Registry_[Key].get<bool>(); Value = Registry_[Key].get<bool>();
return true; return true;
} }
return false; return false;
} }
inline bool Get(const char *Key, uint64_t & Value ) { inline bool Get(const char *Key, uint64_t &Value) {
if(Registry_[Key].is_number_unsigned()) { if (Registry_[Key].is_number_unsigned()) {
Value = Registry_[Key].get<uint64_t>(); Value = Registry_[Key].get<uint64_t>();
return true; return true;
} }
return false; return false;
} }
inline bool Get(const char *Key, std::string & Value ) { inline bool Get(const char *Key, std::string &Value) {
if(Registry_[Key].is_string()) { if (Registry_[Key].is_string()) {
Value = Registry_[Key].get<std::string>(); Value = Registry_[Key].get<std::string>();
return true; return true;
} }
@@ -93,10 +90,10 @@ namespace OpenWifi {
} }
private: private:
std::string FileName; std::string FileName;
nlohmann::json Registry_; nlohmann::json Registry_;
}; };
inline auto AppServiceRegistry() { return AppServiceRegistry::instance(); } inline auto AppServiceRegistry() { return AppServiceRegistry::instance(); }
} } // namespace OpenWifi

View File

@@ -4,41 +4,40 @@
#include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/HTTPServerResponse.h"
#include "fmt/format.h"
#include "framework/AuthClient.h" #include "framework/AuthClient.h"
#include "framework/MicroServiceNames.h" #include "framework/MicroServiceNames.h"
#include "framework/OpenAPIRequests.h" #include "framework/OpenAPIRequests.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "fmt/format.h"
namespace OpenWifi { namespace OpenWifi {
bool AuthClient::RetrieveTokenInformation(const std::string & SessionToken, bool AuthClient::RetrieveTokenInformation(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy & UInfo, SecurityObjects::UserInfoAndPolicy &UInfo,
std::uint64_t TID, std::uint64_t TID, bool &Expired, bool &Contacted,
bool & Expired, bool & Contacted, bool Sub) { bool Sub) {
try { try {
Types::StringPairVec QueryData; Types::StringPairVec QueryData;
QueryData.push_back(std::make_pair("token",SessionToken)); QueryData.push_back(std::make_pair("token", SessionToken));
std::string AlternateURIForLogging = fmt::format("{}?token={}", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", Utils::SanitizeToken(SessionToken)); std::string AlternateURIForLogging = fmt::format(
OpenAPIRequestGet Req( uSERVICE_SECURITY, "{}?token={}", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken",
Utils::SanitizeToken(SessionToken));
OpenAPIRequestGet Req(uSERVICE_SECURITY,
Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken",
QueryData, QueryData, 10000, AlternateURIForLogging);
10000,
AlternateURIForLogging
);
Poco::JSON::Object::Ptr Response; Poco::JSON::Object::Ptr Response;
auto StatusCode = Req.Do(Response); auto StatusCode = Req.Do(Response);
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) { if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
Contacted = false; Contacted = false;
return false; return false;
} }
Contacted = true; Contacted = true;
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_OK) { if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) {
if(Response->has("tokenInfo") && Response->has("userInfo")) { if (Response->has("tokenInfo") && Response->has("userInfo")) {
UInfo.from_json(Response); UInfo.from_json(Response);
if(IsTokenExpired(UInfo.webtoken)) { if (IsTokenExpired(UInfo.webtoken)) {
Expired = true; Expired = true;
return false; return false;
} }
@@ -50,18 +49,19 @@ namespace OpenWifi {
} }
} }
} catch (...) { } catch (...) {
poco_error(Logger(),fmt::format("Failed to retrieve token={} for TID={}", Utils::SanitizeToken(SessionToken), TID)); poco_error(Logger(), fmt::format("Failed to retrieve token={} for TID={}",
Utils::SanitizeToken(SessionToken), TID));
} }
Expired = false; Expired = false;
return false; return false;
} }
bool AuthClient::IsAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo, bool AuthClient::IsAuthorized(const std::string &SessionToken,
std::uint64_t TID, SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
bool & Expired, bool & Contacted, bool Sub) { bool &Expired, bool &Contacted, bool Sub) {
auto User = Cache_.get(SessionToken); auto User = Cache_.get(SessionToken);
if(!User.isNull()) { if (!User.isNull()) {
if(IsTokenExpired(User->webtoken)) { if (IsTokenExpired(User->webtoken)) {
Expired = true; Expired = true;
Cache_.remove(SessionToken); Cache_.remove(SessionToken);
return false; return false;
@@ -73,57 +73,60 @@ namespace OpenWifi {
return RetrieveTokenInformation(SessionToken, UInfo, TID, Expired, Contacted, Sub); return RetrieveTokenInformation(SessionToken, UInfo, TID, Expired, Contacted, Sub);
} }
bool AuthClient::RetrieveApiKeyInformation(const std::string & SessionToken, bool AuthClient::RetrieveApiKeyInformation(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy & UInfo, SecurityObjects::UserInfoAndPolicy &UInfo,
std::uint64_t TID, std::uint64_t TID, bool &Expired, bool &Contacted,
bool & Expired, bool & Contacted, [[maybe_unused]] bool & Suspended) { [[maybe_unused]] bool &Suspended) {
try { try {
Types::StringPairVec QueryData; Types::StringPairVec QueryData;
QueryData.push_back(std::make_pair("apikey",SessionToken)); QueryData.push_back(std::make_pair("apikey", SessionToken));
std::string AlternateURIForLogging = fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken)); std::string AlternateURIForLogging =
OpenAPIRequestGet Req( uSERVICE_SECURITY, fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken));
"/api/v1/validateApiKey" , OpenAPIRequestGet Req(uSERVICE_SECURITY, "/api/v1/validateApiKey", QueryData, 10000,
QueryData, AlternateURIForLogging);
10000, Poco::JSON::Object::Ptr Response;
AlternateURIForLogging);
Poco::JSON::Object::Ptr Response;
auto StatusCode = Req.Do(Response); auto StatusCode = Req.Do(Response);
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) { if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT) {
Contacted = false; Contacted = false;
return false; return false;
} }
Contacted = true; Contacted = true;
if(StatusCode==Poco::Net::HTTPServerResponse::HTTP_OK) { if (StatusCode == Poco::Net::HTTPServerResponse::HTTP_OK) {
if(Response->has("tokenInfo") && Response->has("userInfo") && Response->has("expiresOn")) { if (Response->has("tokenInfo") && Response->has("userInfo") &&
UInfo.from_json(Response); Response->has("expiresOn")) {
Expired = false; UInfo.from_json(Response);
ApiKeyCache_.update(SessionToken, ApiKeyCacheEntry{ .UserInfo = UInfo, .ExpiresOn = Response->get("expiresOn")}); Expired = false;
return true; ApiKeyCache_.update(SessionToken,
} else { ApiKeyCacheEntry{.UserInfo = UInfo,
return false; .ExpiresOn = Response->get("expiresOn")});
} return true;
} } else {
} catch (...) { return false;
poco_error(Logger(),fmt::format("Failed to retrieve api key={} for TID={}", Utils::SanitizeToken(SessionToken), TID)); }
} }
Expired = false; } catch (...) {
return false; poco_error(Logger(), fmt::format("Failed to retrieve api key={} for TID={}",
} Utils::SanitizeToken(SessionToken), TID));
}
Expired = false;
return false;
}
bool AuthClient::IsValidApiKey(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy &UInfo, bool AuthClient::IsValidApiKey(const std::string &SessionToken,
std::uint64_t TID, bool &Expired, bool &Contacted, bool & Suspended) { SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
auto User = ApiKeyCache_.get(SessionToken); bool &Expired, bool &Contacted, bool &Suspended) {
if (!User.isNull()) { auto User = ApiKeyCache_.get(SessionToken);
if(User->ExpiresOn < Utils::Now()) { if (!User.isNull()) {
Expired = false; if (User->ExpiresOn < Utils::Now()) {
UInfo = User->UserInfo; Expired = false;
return true; UInfo = User->UserInfo;
} return true;
}
ApiKeyCache_.remove(SessionToken); ApiKeyCache_.remove(SessionToken);
} }
return RetrieveApiKeyInformation(SessionToken, UInfo, TID, Expired, Contacted, Suspended); return RetrieveApiKeyInformation(SessionToken, UInfo, TID, Expired, Contacted, Suspended);
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,9 +4,9 @@
#pragma once #pragma once
#include "framework/SubSystemServer.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "Poco/ExpireLRUCache.h" #include "Poco/ExpireLRUCache.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "framework/SubSystemServer.h"
#include "framework/utils.h" #include "framework/utils.h"
namespace OpenWifi { namespace OpenWifi {
@@ -14,66 +14,59 @@ namespace OpenWifi {
class AuthClient : public SubSystemServer { class AuthClient : public SubSystemServer {
public: public:
explicit AuthClient() noexcept: explicit AuthClient() noexcept
SubSystemServer("Authentication", "AUTH-CLNT", "authentication") : SubSystemServer("Authentication", "AUTH-CLNT", "authentication") {}
{
}
static auto instance() { static auto instance() {
static auto instance_ = new AuthClient; static auto instance_ = new AuthClient;
return instance_; return instance_;
} }
struct ApiKeyCacheEntry { struct ApiKeyCacheEntry {
OpenWifi::SecurityObjects::UserInfoAndPolicy UserInfo; OpenWifi::SecurityObjects::UserInfoAndPolicy UserInfo;
std::uint64_t ExpiresOn; std::uint64_t ExpiresOn;
}; };
inline int Start() override { inline int Start() override { return 0; }
return 0;
}
inline void Stop() override { inline void Stop() override {
poco_information(Logger(),"Stopping..."); poco_information(Logger(), "Stopping...");
std::lock_guard G(Mutex_); std::lock_guard G(Mutex_);
Cache_.clear(); Cache_.clear();
poco_information(Logger(),"Stopped..."); poco_information(Logger(), "Stopped...");
} }
inline void RemovedCachedToken(const std::string &Token) { inline void RemovedCachedToken(const std::string &Token) {
Cache_.remove(Token); Cache_.remove(Token);
ApiKeyCache_.remove(Token); ApiKeyCache_.remove(Token);
} }
inline static bool IsTokenExpired(const SecurityObjects::WebToken &T) { inline static bool IsTokenExpired(const SecurityObjects::WebToken &T) {
return ((T.expires_in_+T.created_) < Utils::Now()); return ((T.expires_in_ + T.created_) < Utils::Now());
} }
bool RetrieveTokenInformation(const std::string & SessionToken, bool RetrieveTokenInformation(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy & UInfo, SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
std::uint64_t TID, bool &Expired, bool &Contacted, bool Sub = false);
bool & Expired, bool & Contacted, bool Sub=false);
bool RetrieveApiKeyInformation(const std::string & SessionToken, bool RetrieveApiKeyInformation(const std::string &SessionToken,
SecurityObjects::UserInfoAndPolicy & UInfo, SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
std::uint64_t TID, bool &Expired, bool &Contacted, bool &Suspended);
bool & Expired, bool & Contacted, bool & Suspended);
bool IsAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo, bool IsAuthorized(const std::string &SessionToken,
std::uint64_t TID, SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
bool & Expired, bool & Contacted, bool Sub = false); bool &Expired, bool &Contacted, bool Sub = false);
bool IsValidApiKey(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo, bool IsValidApiKey(const std::string &SessionToken,
std::uint64_t TID, SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID,
bool & Expired, bool & Contacted, bool & Suspended) ; bool &Expired, bool &Contacted, bool &Suspended);
private: private:
Poco::ExpireLRUCache<std::string, OpenWifi::SecurityObjects::UserInfoAndPolicy> Cache_{
Poco::ExpireLRUCache<std::string,OpenWifi::SecurityObjects::UserInfoAndPolicy> Cache_{512,1200000 }; 512, 1200000};
Poco::ExpireLRUCache<std::string,ApiKeyCacheEntry> ApiKeyCache_{512,1200000 }; Poco::ExpireLRUCache<std::string, ApiKeyCacheEntry> ApiKeyCache_{512, 1200000};
}; };
inline auto AuthClient() { return AuthClient::instance(); } inline auto AuthClient() { return AuthClient::instance(); }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -21,13 +21,13 @@ namespace OpenWifi::CIDR {
} }
static bool cidr6_match(const in6_addr &address, const in6_addr &network, uint8_t bits) { static bool cidr6_match(const in6_addr &address, const in6_addr &network, uint8_t bits) {
#ifdef __linux__ #ifdef __linux__
const uint32_t *a = address.s6_addr32; const uint32_t *a = address.s6_addr32;
const uint32_t *n = network.s6_addr32; const uint32_t *n = network.s6_addr32;
#else #else
const uint32_t *a = address.__u6_addr.__u6_addr32; const uint32_t *a = address.__u6_addr.__u6_addr32;
const uint32_t *n = network.__u6_addr.__u6_addr32; const uint32_t *n = network.__u6_addr.__u6_addr32;
#endif #endif
int bits_whole, bits_incomplete; int bits_whole, bits_incomplete;
bits_whole = bits >> 5; // number of whole u32 bits_whole = bits >> 5; // number of whole u32
bits_incomplete = bits & 0x1F; // number of bits in incomplete u32 bits_incomplete = bits & 0x1F; // number of bits in incomplete u32
@@ -152,4 +152,4 @@ namespace OpenWifi::CIDR {
[[nodiscard]] inline bool ValidateIpRanges(const Types::StringVec &Ranges) { [[nodiscard]] inline bool ValidateIpRanges(const Types::StringVec &Ranges) {
return std::all_of(cbegin(Ranges), cend(Ranges), ValidateRange); return std::all_of(cbegin(Ranges), cend(Ranges), ValidateRange);
} }
} } // namespace OpenWifi::CIDR

View File

@@ -2,8 +2,8 @@
// Created by stephane bourque on 2021-09-14. // Created by stephane bourque on 2021-09-14.
// //
#include <iostream>
#include <fstream> #include <fstream>
#include <iostream>
#include <regex> #include <regex>
#include "ConfigurationValidator.h" #include "ConfigurationValidator.h"
@@ -17,14 +17,15 @@
#include "fmt/format.h" #include "fmt/format.h"
#include <valijson/adapters/poco_json_adapter.hpp> #include <valijson/adapters/poco_json_adapter.hpp>
#include <valijson/utils/poco_json_utils.hpp> #include <valijson/constraints/constraint.hpp>
#include <valijson/schema.hpp> #include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp> #include <valijson/schema_parser.hpp>
#include <valijson/utils/poco_json_utils.hpp>
#include <valijson/validator.hpp> #include <valijson/validator.hpp>
#include <valijson/constraints/constraint.hpp>
static const std::string GitUCentralJSONSchemaFile{ static const std::string GitUCentralJSONSchemaFile{
"https://raw.githubusercontent.com/Telecominfraproject/wlan-ucentral-schema/main/ucentral.schema.json"}; "https://raw.githubusercontent.com/Telecominfraproject/wlan-ucentral-schema/main/"
"ucentral.schema.json"};
static std::string DefaultUCentralSchema = R"foo( static std::string DefaultUCentralSchema = R"foo(
@@ -3184,7 +3185,6 @@ static std::string DefaultUCentralSchema = R"foo(
)foo"; )foo";
static inline bool IsIPv4(const std::string &value) { static inline bool IsIPv4(const std::string &value) {
Poco::Net::IPAddress A; Poco::Net::IPAddress A;
return ((Poco::Net::IPAddress::tryParse(value, A) && A.family() == Poco::Net::IPAddress::IPv4)); return ((Poco::Net::IPAddress::tryParse(value, A) && A.family() == Poco::Net::IPAddress::IPv4));
@@ -3242,57 +3242,68 @@ bool ExternalValijsonFormatChecker(const std::string &format, const std::string
if (format == "uc-cidr4") { if (format == "uc-cidr4") {
if (IsCIDRv4(value)) if (IsCIDRv4(value))
return true; return true;
if(results) results->pushError(context,fmt::format("{} is not a valid CIDR IPv4 block",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid CIDR IPv4 block", value));
} else if (format == "uc-cidr6") { } else if (format == "uc-cidr6") {
if (IsCIDRv6(value)) if (IsCIDRv6(value))
return true; return true;
if(results) results->pushError(context,fmt::format("{} is not a valid CIDR IPv6 block",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid CIDR IPv6 block", value));
} else if (format == "uc-cidr") { } else if (format == "uc-cidr") {
if (IsCIDR(value)) if (IsCIDR(value))
return true; return true;
if(results) results->pushError(context,fmt::format("{} is not a valid CIDR block",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid CIDR block", value));
} else if (format == "uc-mac") { } else if (format == "uc-mac") {
if (std::regex_match(value, mac_regex)) if (std::regex_match(value, mac_regex))
return true; return true;
if(results) results->pushError(context,fmt::format("{} is not a valid MAC address",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid MAC address", value));
} else if (format == "uc-timeout") { } else if (format == "uc-timeout") {
if (std::regex_match(value, uc_timeout_regex)) if (std::regex_match(value, uc_timeout_regex))
return true; return true;
if(results) results->pushError(context,fmt::format("{} is not a valid timeout value",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid timeout value", value));
} else if (format == "uc-host") { } else if (format == "uc-host") {
if (IsIP(value)) if (IsIP(value))
return true; return true;
if (std::regex_match(value, host_regex)) if (std::regex_match(value, host_regex))
return true; return true;
if(results) results->pushError(context,fmt::format("{} is not a valid hostname",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid hostname", value));
} else if (format == "fqdn" || format == "uc-fqdn") { } else if (format == "fqdn" || format == "uc-fqdn") {
if (std::regex_match(value, host_regex)) if (std::regex_match(value, host_regex))
return true; return true;
if(results) results->pushError(context,fmt::format("{} is not a valid FQDN",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid FQDN", value));
} else if (format == "uc-base64") { } else if (format == "uc-base64") {
std::string s{value}; std::string s{value};
Poco::trimInPlace(s); Poco::trimInPlace(s);
if ((s.size() % 4 == 0) && std::regex_match(s, b64_regex)) if ((s.size() % 4 == 0) && std::regex_match(s, b64_regex))
return true; return true;
if(results) results->pushError(context,fmt::format("{} is not a valid base 64 value",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid base 64 value", value));
} else if (format == "uri") { } else if (format == "uri") {
try { try {
Poco::URI uri(value); Poco::URI uri(value);
return true; return true;
} catch (...) { } catch (...) {
} }
if(results) results->pushError(context,fmt::format("{} is not a valid URL",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid URL", value));
} else if (format == "uc-portrange") { } else if (format == "uc-portrange") {
try { try {
if (IsPortRangeIsValid(value)) if (IsPortRangeIsValid(value))
return true; return true;
} catch (...) { } catch (...) {
} }
if(results) results->pushError(context,fmt::format("{} is not a valid post range",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid post range", value));
} else if (format == "ip") { } else if (format == "ip") {
if (IsIP(value)) if (IsIP(value))
return true; return true;
if(results) results->pushError(context,fmt::format("{} is not a valid IP address",value)); if (results)
results->pushError(context, fmt::format("{} is not a valid IP address", value));
} }
return true; return true;
} }
@@ -3304,9 +3315,7 @@ namespace OpenWifi {
return 0; return 0;
} }
void ConfigurationValidator::Stop() { void ConfigurationValidator::Stop() {}
}
bool ConfigurationValidator::SetSchema(const std::string &SchemaStr) { bool ConfigurationValidator::SetSchema(const std::string &SchemaStr) {
try { try {
@@ -3318,9 +3327,9 @@ namespace OpenWifi {
SchemaParser_->populateSchema(*PocoJsonAdapter_, *RootSchema_); SchemaParser_->populateSchema(*PocoJsonAdapter_, *RootSchema_);
Initialized_ = Working_ = true; Initialized_ = Working_ = true;
return true; return true;
} catch(const Poco::Exception &E) { } catch (const Poco::Exception &E) {
Logger().log(E); Logger().log(E);
} catch(...) { } catch (...) {
Logger().error("Validation schema is invalid, falling back."); Logger().error("Validation schema is invalid, falling back.");
} }
return false; return false;
@@ -3331,7 +3340,7 @@ namespace OpenWifi {
return; return;
std::string GitSchema; std::string GitSchema;
if(MicroServiceConfigGetBool("ucentral.datamodel.internal",true)) { if (MicroServiceConfigGetBool("ucentral.datamodel.internal", true)) {
SetSchema(DefaultUCentralSchema); SetSchema(DefaultUCentralSchema);
poco_information(Logger(), "Using uCentral validation from built-in default."); poco_information(Logger(), "Using uCentral validation from built-in default.");
return; return;
@@ -3339,34 +3348,35 @@ namespace OpenWifi {
try { try {
auto GitURI = auto GitURI =
MicroServiceConfigGetString("ucentral.datamodel.uri",GitUCentralJSONSchemaFile); MicroServiceConfigGetString("ucentral.datamodel.uri", GitUCentralJSONSchemaFile);
if(Utils::wgets(GitURI, GitSchema) && SetSchema(GitSchema)) { if (Utils::wgets(GitURI, GitSchema) && SetSchema(GitSchema)) {
poco_information(Logger(),"Using uCentral data model validation schema from GIT."); poco_information(Logger(), "Using uCentral data model validation schema from GIT.");
return;
} else {
std::string FileName{MicroServiceDataDirectory() + "/ucentral.schema.json"};
std::ifstream input(FileName);
std::stringstream schema_file;
schema_file << input.rdbuf();
input.close();
if (SetSchema(schema_file.str())) {
poco_information(
Logger(), "Using uCentral data model validation schema from local file.");
return; return;
} else {
std::string FileName{ MicroServiceDataDirectory() + "/ucentral.schema.json" };
std::ifstream input(FileName);
std::stringstream schema_file;
schema_file << input.rdbuf();
input.close();
if(SetSchema(schema_file.str())) {
poco_information(Logger(),
"Using uCentral data model validation schema from local file.");
return;
}
} }
}
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} catch (...) { } catch (...) {
} }
SetSchema(DefaultUCentralSchema); SetSchema(DefaultUCentralSchema);
poco_information(Logger(),"Using uCentral data model validation schema from built-in default."); poco_information(Logger(),
"Using uCentral data model validation schema from built-in default.");
} }
bool ConfigurationValidator::Validate(const std::string &C, std::vector<std::string> &Errors, bool Strict) { bool ConfigurationValidator::Validate(const std::string &C, std::vector<std::string> &Errors,
if(Working_) { bool Strict) {
try { if (Working_) {
try {
Poco::JSON::Parser P; Poco::JSON::Parser P;
auto Doc = P.parse(C).extract<Poco::JSON::Object::Ptr>(); auto Doc = P.parse(C).extract<Poco::JSON::Object::Ptr>();
valijson::adapters::PocoJsonAdapter Tester(Doc); valijson::adapters::PocoJsonAdapter Tester(Doc);
@@ -3375,27 +3385,28 @@ namespace OpenWifi {
if (Validator.validate(*RootSchema_, Tester, &Results)) { if (Validator.validate(*RootSchema_, Tester, &Results)) {
return true; return true;
} }
for(const auto &error:Results) { for (const auto &error : Results) {
Errors.push_back(error.description); Errors.push_back(error.description);
} }
return false; return false;
} catch(const Poco::Exception &E) { } catch (const Poco::Exception &E) {
Logger().log(E); Logger().log(E);
} catch(const std::exception &E) { } catch (const std::exception &E) {
Logger().warning(fmt::format("Error wile validating a configuration (1): {}", E.what())); Logger().warning(
} catch(...) { fmt::format("Error wile validating a configuration (1): {}", E.what()));
} catch (...) {
Logger().warning("Error wile validating a configuration (2)"); Logger().warning("Error wile validating a configuration (2)");
} }
} }
if(Strict) if (Strict)
return false; return false;
return true; return true;
} }
void ConfigurationValidator::reinitialize([[maybe_unused]] Poco::Util::Application &self) { void ConfigurationValidator::reinitialize([[maybe_unused]] Poco::Util::Application &self) {
poco_information(Logger(),"Reinitializing."); poco_information(Logger(), "Reinitializing.");
Working_ = Initialized_ = false; Working_ = Initialized_ = false;
Init(); Init();
} }
} } // namespace OpenWifi

View File

@@ -7,43 +7,43 @@
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include <valijson/adapters/poco_json_adapter.hpp> #include <valijson/adapters/poco_json_adapter.hpp>
#include <valijson/utils/poco_json_utils.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
#include <valijson/validator.hpp>
#include <valijson/constraints/constraint.hpp> #include <valijson/constraints/constraint.hpp>
#include <valijson/constraints/constraint_visitor.hpp> #include <valijson/constraints/constraint_visitor.hpp>
#include <valijson/schema.hpp>
#include <valijson/schema_parser.hpp>
#include <valijson/utils/poco_json_utils.hpp>
#include <valijson/validator.hpp>
namespace OpenWifi { namespace OpenWifi {
class ConfigurationValidator : public SubSystemServer { class ConfigurationValidator : public SubSystemServer {
public: public:
static auto instance() {
static auto instance_ = new ConfigurationValidator;
return instance_;
}
static auto instance() { bool Validate(const std::string &C, std::vector<std::string> &Errors, bool Strict);
static auto instance_ = new ConfigurationValidator; int Start() override;
return instance_; void Stop() override;
} void reinitialize(Poco::Util::Application &self) override;
bool Validate(const std::string &C, std::vector<std::string> &Errors, bool Strict); private:
int Start() override; bool Initialized_ = false;
void Stop() override; bool Working_ = false;
void reinitialize(Poco::Util::Application &self) override; void Init();
std::unique_ptr<valijson::Schema> RootSchema_;
std::unique_ptr<valijson::SchemaParser> SchemaParser_;
std::unique_ptr<valijson::adapters::PocoJsonAdapter> PocoJsonAdapter_;
Poco::JSON::Object::Ptr SchemaDocPtr_;
bool SetSchema(const std::string &SchemaStr);
private: ConfigurationValidator()
bool Initialized_=false; : SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") {}
bool Working_=false; };
void Init();
std::unique_ptr<valijson::Schema> RootSchema_;
std::unique_ptr<valijson::SchemaParser> SchemaParser_;
std::unique_ptr<valijson::adapters::PocoJsonAdapter> PocoJsonAdapter_;
Poco::JSON::Object::Ptr SchemaDocPtr_;
bool SetSchema(const std::string &SchemaStr);
ConfigurationValidator():
SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") {
}
};
inline auto ConfigurationValidator() { return ConfigurationValidator::instance(); }
inline bool ValidateUCentralConfiguration(const std::string &C, std::vector<std::string> &Error, bool strict) { return ConfigurationValidator::instance()->Validate(C, Error, strict); }
}
inline auto ConfigurationValidator() { return ConfigurationValidator::instance(); }
inline bool ValidateUCentralConfiguration(const std::string &C, std::vector<std::string> &Error,
bool strict) {
return ConfigurationValidator::instance()->Validate(C, Error, strict);
}
} // namespace OpenWifi

View File

@@ -4,268 +4,266 @@
#pragma once #pragma once
#include <vector>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector>
namespace OpenWifi { namespace OpenWifi {
struct CountryInfo {
std::string code;
std::string name;
};
inline static const std::vector<CountryInfo> CountryCodes {
{ .code= "US", .name= "United States" },
{ .code= "GB", .name= "United Kingdom" },
{ .code= "CA", .name= "Canada" },
{ .code= "AF", .name= "Afghanistan" },
{ .code= "AX", .name= "Aland Islands" },
{ .code= "AL", .name= "Albania" },
{ .code= "DZ", .name= "Algeria" },
{ .code= "AS", .name= "American Samoa" },
{ .code= "AD", .name= "Andorra" },
{ .code= "AO", .name= "Angola" },
{ .code= "AI", .name= "Anguilla" },
{ .code= "AQ", .name= "Antarctica" },
{ .code= "AG", .name= "Antigua And Barbuda" },
{ .code= "AR", .name= "Argentina" },
{ .code= "AM", .name= "Armenia" },
{ .code= "AN", .name= "Netherlands Antilles" },
{ .code= "AW", .name= "Aruba" },
{ .code= "AU", .name= "Australia" },
{ .code= "AT", .name= "Austria" },
{ .code= "AZ", .name= "Azerbaijan" },
{ .code= "BS", .name= "Bahamas" },
{ .code= "BH", .name= "Bahrain" },
{ .code= "BD", .name= "Bangladesh" },
{ .code= "BB", .name= "Barbados" },
{ .code= "BY", .name= "Belarus" },
{ .code= "BE", .name= "Belgium" },
{ .code= "BZ", .name= "Belize" },
{ .code= "BJ", .name= "Benin" },
{ .code= "BM", .name= "Bermuda" },
{ .code= "BT", .name= "Bhutan" },
{ .code= "BO", .name= "Bolivia" },
{ .code= "BA", .name= "Bosnia And Herzegovina" },
{ .code= "BW", .name= "Botswana" },
{ .code= "BV", .name= "Bouvet Island" },
{ .code= "BR", .name= "Brazil" },
{ .code= "IO", .name= "British Indian Ocean Territory" },
{ .code= "BN", .name= "Brunei Darussalam" },
{ .code= "BG", .name= "Bulgaria" },
{ .code= "BF", .name= "Burkina Faso" },
{ .code= "BI", .name= "Burundi" },
{ .code= "KH", .name= "Cambodia" },
{ .code= "CM", .name= "Cameroon" },
{ .code= "CA", .name= "Canada" },
{ .code= "CV", .name= "Cape Verde" },
{ .code= "KY", .name= "Cayman Islands" },
{ .code= "CF", .name= "Central African Republic" },
{ .code= "TD", .name= "Chad" },
{ .code= "CL", .name= "Chile" },
{ .code= "CN", .name= "China" },
{ .code= "CX", .name= "Christmas Island" },
{ .code= "CC", .name= "Cocos (Keeling) Islands" },
{ .code= "CO", .name= "Colombia" },
{ .code= "KM", .name= "Comoros" },
{ .code= "CG", .name= "Congo" },
{ .code= "CD", .name= "Congo, Democratic Republic" },
{ .code= "CK", .name= "Cook Islands" },
{ .code= "CR", .name= "Costa Rica" },
{ .code= "CI", .name= "Cote D\"Ivoire" },
{ .code= "HR", .name= "Croatia" },
{ .code= "CU", .name= "Cuba" },
{ .code= "CY", .name= "Cyprus" },
{ .code= "CZ", .name= "Czech Republic" },
{ .code= "DK", .name= "Denmark" },
{ .code= "DJ", .name= "Djibouti" },
{ .code= "DM", .name= "Dominica" },
{ .code= "DO", .name= "Dominican Republic" },
{ .code= "EC", .name= "Ecuador" },
{ .code= "EG", .name= "Egypt" },
{ .code= "SV", .name= "El Salvador" },
{ .code= "GQ", .name= "Equatorial Guinea" },
{ .code= "ER", .name= "Eritrea" },
{ .code= "EE", .name= "Estonia" },
{ .code= "ET", .name= "Ethiopia" },
{ .code= "FK", .name= "Falkland Islands (Malvinas)" },
{ .code= "FO", .name= "Faroe Islands" },
{ .code= "FJ", .name= "Fiji" },
{ .code= "FI", .name= "Finland" },
{ .code= "FR", .name= "France" },
{ .code= "GF", .name= "French Guiana" },
{ .code= "PF", .name= "French Polynesia" },
{ .code= "TF", .name= "French Southern Territories" },
{ .code= "GA", .name= "Gabon" },
{ .code= "GM", .name= "Gambia" },
{ .code= "GE", .name= "Georgia" },
{ .code= "DE", .name= "Germany" },
{ .code= "GH", .name= "Ghana" },
{ .code= "GI", .name= "Gibraltar" },
{ .code= "GR", .name= "Greece" },
{ .code= "GL", .name= "Greenland" },
{ .code= "GD", .name= "Grenada" },
{ .code= "GP", .name= "Guadeloupe" },
{ .code= "GU", .name= "Guam" },
{ .code= "GT", .name= "Guatemala" },
{ .code= "GG", .name= "Guernsey" },
{ .code= "GN", .name= "Guinea" },
{ .code= "GW", .name= "Guinea-Bissau" },
{ .code= "GY", .name= "Guyana" },
{ .code= "HT", .name= "Haiti" },
{ .code= "HM", .name= "Heard Island & Mcdonald Islands" },
{ .code= "VA", .name= "Holy See (Vatican City State)" },
{ .code= "HN", .name= "Honduras" },
{ .code= "HK", .name= "Hong Kong" },
{ .code= "HU", .name= "Hungary" },
{ .code= "IS", .name= "Iceland" },
{ .code= "IN", .name= "India" },
{ .code= "ID", .name= "Indonesia" },
{ .code= "IR", .name= "Iran, Islamic Republic Of" },
{ .code= "IQ", .name= "Iraq" },
{ .code= "IE", .name= "Ireland" },
{ .code= "IM", .name= "Isle Of Man" },
{ .code= "IL", .name= "Israel" },
{ .code= "IT", .name= "Italy" },
{ .code= "JM", .name= "Jamaica" },
{ .code= "JP", .name= "Japan" },
{ .code= "JE", .name= "Jersey" },
{ .code= "JO", .name= "Jordan" },
{ .code= "KZ", .name= "Kazakhstan" },
{ .code= "KE", .name= "Kenya" },
{ .code= "KI", .name= "Kiribati" },
{ .code= "KR", .name= "Korea" },
{ .code= "KW", .name= "Kuwait" },
{ .code= "KG", .name= "Kyrgyzstan" },
{ .code= "LA", .name= "Lao People\"s Democratic Republic" },
{ .code= "LV", .name= "Latvia" },
{ .code= "LB", .name= "Lebanon" },
{ .code= "LS", .name= "Lesotho" },
{ .code= "LR", .name= "Liberia" },
{ .code= "LY", .name= "Libyan Arab Jamahiriya" },
{ .code= "LI", .name= "Liechtenstein" },
{ .code= "LT", .name= "Lithuania" },
{ .code= "LU", .name= "Luxembourg" },
{ .code= "MO", .name= "Macao" },
{ .code= "MK", .name= "Macedonia" },
{ .code= "MG", .name= "Madagascar" },
{ .code= "MW", .name= "Malawi" },
{ .code= "MY", .name= "Malaysia" },
{ .code= "MV", .name= "Maldives" },
{ .code= "ML", .name= "Mali" },
{ .code= "MT", .name= "Malta" },
{ .code= "MH", .name= "Marshall Islands" },
{ .code= "MQ", .name= "Martinique" },
{ .code= "MR", .name= "Mauritania" },
{ .code= "MU", .name= "Mauritius" },
{ .code= "YT", .name= "Mayotte" },
{ .code= "MX", .name= "Mexico" },
{ .code= "FM", .name= "Micronesia, Federated States Of" },
{ .code= "MD", .name= "Moldova" },
{ .code= "MC", .name= "Monaco" },
{ .code= "MN", .name= "Mongolia" },
{ .code= "ME", .name= "Montenegro" },
{ .code= "MS", .name= "Montserrat" },
{ .code= "MA", .name= "Morocco" },
{ .code= "MZ", .name= "Mozambique" },
{ .code= "MM", .name= "Myanmar" },
{ .code= "NA", .name= "Namibia" },
{ .code= "NR", .name= "Nauru" },
{ .code= "NP", .name= "Nepal" },
{ .code= "NL", .name= "Netherlands" },
{ .code= "AN", .name= "Netherlands Antilles" },
{ .code= "NC", .name= "New Caledonia" },
{ .code= "NZ", .name= "New Zealand" },
{ .code= "NI", .name= "Nicaragua" },
{ .code= "NE", .name= "Niger" },
{ .code= "NG", .name= "Nigeria" },
{ .code= "NU", .name= "Niue" },
{ .code= "NF", .name= "Norfolk Island" },
{ .code= "MP", .name= "Northern Mariana Islands" },
{ .code= "NO", .name= "Norway" },
{ .code= "OM", .name= "Oman" },
{ .code= "PK", .name= "Pakistan" },
{ .code= "PW", .name= "Palau" },
{ .code= "PS", .name= "Palestinian Territory, Occupied" },
{ .code= "PA", .name= "Panama" },
{ .code= "PG", .name= "Papua New Guinea" },
{ .code= "PY", .name= "Paraguay" },
{ .code= "PE", .name= "Peru" },
{ .code= "PH", .name= "Philippines" },
{ .code= "PN", .name= "Pitcairn" },
{ .code= "PL", .name= "Poland" },
{ .code= "PT", .name= "Portugal" },
{ .code= "PR", .name= "Puerto Rico" },
{ .code= "QA", .name= "Qatar" },
{ .code= "RE", .name= "Reunion" },
{ .code= "RO", .name= "Romania" },
{ .code= "RU", .name= "Russian Federation" },
{ .code= "RW", .name= "Rwanda" },
{ .code= "BL", .name= "Saint Barthelemy" },
{ .code= "SH", .name= "Saint Helena" },
{ .code= "KN", .name= "Saint Kitts And Nevis" },
{ .code= "LC", .name= "Saint Lucia" },
{ .code= "MF", .name= "Saint Martin" },
{ .code= "PM", .name= "Saint Pierre And Miquelon" },
{ .code= "VC", .name= "Saint Vincent And Grenadines" },
{ .code= "WS", .name= "Samoa" },
{ .code= "SM", .name= "San Marino" },
{ .code= "ST", .name= "Sao Tome And Principe" },
{ .code= "SA", .name= "Saudi Arabia" },
{ .code= "SN", .name= "Senegal" },
{ .code= "RS", .name= "Serbia" },
{ .code= "SC", .name= "Seychelles" },
{ .code= "SL", .name= "Sierra Leone" },
{ .code= "SG", .name= "Singapore" },
{ .code= "SK", .name= "Slovakia" },
{ .code= "SI", .name= "Slovenia" },
{ .code= "SB", .name= "Solomon Islands" },
{ .code= "SO", .name= "Somalia" },
{ .code= "ZA", .name= "South Africa" },
{ .code= "GS", .name= "South Georgia And Sandwich Isl." },
{ .code= "ES", .name= "Spain" },
{ .code= "LK", .name= "Sri Lanka" },
{ .code= "SD", .name= "Sudan" },
{ .code= "SR", .name= "Suriname" },
{ .code= "SJ", .name= "Svalbard And Jan Mayen" },
{ .code= "SZ", .name= "Swaziland" },
{ .code= "SE", .name= "Sweden" },
{ .code= "CH", .name= "Switzerland" },
{ .code= "SY", .name= "Syrian Arab Republic" },
{ .code= "TW", .name= "Taiwan" },
{ .code= "TJ", .name= "Tajikistan" },
{ .code= "TZ", .name= "Tanzania" },
{ .code= "TH", .name= "Thailand" },
{ .code= "TL", .name= "Timor-Leste" },
{ .code= "TG", .name= "Togo" },
{ .code= "TK", .name= "Tokelau" },
{ .code= "TO", .name= "Tonga" },
{ .code= "TT", .name= "Trinidad And Tobago" },
{ .code= "TN", .name= "Tunisia" },
{ .code= "TR", .name= "Turkey" },
{ .code= "TM", .name= "Turkmenistan" },
{ .code= "TC", .name= "Turks And Caicos Islands" },
{ .code= "TV", .name= "Tuvalu" },
{ .code= "UG", .name= "Uganda" },
{ .code= "UA", .name= "Ukraine" },
{ .code= "AE", .name= "United Arab Emirates" },
{ .code= "GB", .name= "United Kingdom" },
{ .code= "US", .name= "United States" },
{ .code= "UM", .name= "United States Outlying Islands" },
{ .code= "UY", .name= "Uruguay" },
{ .code= "UZ", .name= "Uzbekistan" },
{ .code= "VU", .name= "Vanuatu" },
{ .code= "VE", .name= "Venezuela" },
{ .code= "VN", .name= "Viet Nam" },
{ .code= "VG", .name= "Virgin Islands, British" },
{ .code= "VI", .name= "Virgin Islands, U.S." },
{ .code= "WF", .name= "Wallis And Futuna" },
{ .code= "EH", .name= "Western Sahara" },
{ .code= "YE", .name= "Yemen" },
{ .code= "ZM", .name= "Zambia" },
{ .code= "ZW", .name= "Zimbabwe" }
};
} struct CountryInfo {
std::string code;
std::string name;
};
inline static const std::vector<CountryInfo> CountryCodes{
{.code = "US", .name = "United States"},
{.code = "GB", .name = "United Kingdom"},
{.code = "CA", .name = "Canada"},
{.code = "AF", .name = "Afghanistan"},
{.code = "AX", .name = "Aland Islands"},
{.code = "AL", .name = "Albania"},
{.code = "DZ", .name = "Algeria"},
{.code = "AS", .name = "American Samoa"},
{.code = "AD", .name = "Andorra"},
{.code = "AO", .name = "Angola"},
{.code = "AI", .name = "Anguilla"},
{.code = "AQ", .name = "Antarctica"},
{.code = "AG", .name = "Antigua And Barbuda"},
{.code = "AR", .name = "Argentina"},
{.code = "AM", .name = "Armenia"},
{.code = "AN", .name = "Netherlands Antilles"},
{.code = "AW", .name = "Aruba"},
{.code = "AU", .name = "Australia"},
{.code = "AT", .name = "Austria"},
{.code = "AZ", .name = "Azerbaijan"},
{.code = "BS", .name = "Bahamas"},
{.code = "BH", .name = "Bahrain"},
{.code = "BD", .name = "Bangladesh"},
{.code = "BB", .name = "Barbados"},
{.code = "BY", .name = "Belarus"},
{.code = "BE", .name = "Belgium"},
{.code = "BZ", .name = "Belize"},
{.code = "BJ", .name = "Benin"},
{.code = "BM", .name = "Bermuda"},
{.code = "BT", .name = "Bhutan"},
{.code = "BO", .name = "Bolivia"},
{.code = "BA", .name = "Bosnia And Herzegovina"},
{.code = "BW", .name = "Botswana"},
{.code = "BV", .name = "Bouvet Island"},
{.code = "BR", .name = "Brazil"},
{.code = "IO", .name = "British Indian Ocean Territory"},
{.code = "BN", .name = "Brunei Darussalam"},
{.code = "BG", .name = "Bulgaria"},
{.code = "BF", .name = "Burkina Faso"},
{.code = "BI", .name = "Burundi"},
{.code = "KH", .name = "Cambodia"},
{.code = "CM", .name = "Cameroon"},
{.code = "CA", .name = "Canada"},
{.code = "CV", .name = "Cape Verde"},
{.code = "KY", .name = "Cayman Islands"},
{.code = "CF", .name = "Central African Republic"},
{.code = "TD", .name = "Chad"},
{.code = "CL", .name = "Chile"},
{.code = "CN", .name = "China"},
{.code = "CX", .name = "Christmas Island"},
{.code = "CC", .name = "Cocos (Keeling) Islands"},
{.code = "CO", .name = "Colombia"},
{.code = "KM", .name = "Comoros"},
{.code = "CG", .name = "Congo"},
{.code = "CD", .name = "Congo, Democratic Republic"},
{.code = "CK", .name = "Cook Islands"},
{.code = "CR", .name = "Costa Rica"},
{.code = "CI", .name = "Cote D\"Ivoire"},
{.code = "HR", .name = "Croatia"},
{.code = "CU", .name = "Cuba"},
{.code = "CY", .name = "Cyprus"},
{.code = "CZ", .name = "Czech Republic"},
{.code = "DK", .name = "Denmark"},
{.code = "DJ", .name = "Djibouti"},
{.code = "DM", .name = "Dominica"},
{.code = "DO", .name = "Dominican Republic"},
{.code = "EC", .name = "Ecuador"},
{.code = "EG", .name = "Egypt"},
{.code = "SV", .name = "El Salvador"},
{.code = "GQ", .name = "Equatorial Guinea"},
{.code = "ER", .name = "Eritrea"},
{.code = "EE", .name = "Estonia"},
{.code = "ET", .name = "Ethiopia"},
{.code = "FK", .name = "Falkland Islands (Malvinas)"},
{.code = "FO", .name = "Faroe Islands"},
{.code = "FJ", .name = "Fiji"},
{.code = "FI", .name = "Finland"},
{.code = "FR", .name = "France"},
{.code = "GF", .name = "French Guiana"},
{.code = "PF", .name = "French Polynesia"},
{.code = "TF", .name = "French Southern Territories"},
{.code = "GA", .name = "Gabon"},
{.code = "GM", .name = "Gambia"},
{.code = "GE", .name = "Georgia"},
{.code = "DE", .name = "Germany"},
{.code = "GH", .name = "Ghana"},
{.code = "GI", .name = "Gibraltar"},
{.code = "GR", .name = "Greece"},
{.code = "GL", .name = "Greenland"},
{.code = "GD", .name = "Grenada"},
{.code = "GP", .name = "Guadeloupe"},
{.code = "GU", .name = "Guam"},
{.code = "GT", .name = "Guatemala"},
{.code = "GG", .name = "Guernsey"},
{.code = "GN", .name = "Guinea"},
{.code = "GW", .name = "Guinea-Bissau"},
{.code = "GY", .name = "Guyana"},
{.code = "HT", .name = "Haiti"},
{.code = "HM", .name = "Heard Island & Mcdonald Islands"},
{.code = "VA", .name = "Holy See (Vatican City State)"},
{.code = "HN", .name = "Honduras"},
{.code = "HK", .name = "Hong Kong"},
{.code = "HU", .name = "Hungary"},
{.code = "IS", .name = "Iceland"},
{.code = "IN", .name = "India"},
{.code = "ID", .name = "Indonesia"},
{.code = "IR", .name = "Iran, Islamic Republic Of"},
{.code = "IQ", .name = "Iraq"},
{.code = "IE", .name = "Ireland"},
{.code = "IM", .name = "Isle Of Man"},
{.code = "IL", .name = "Israel"},
{.code = "IT", .name = "Italy"},
{.code = "JM", .name = "Jamaica"},
{.code = "JP", .name = "Japan"},
{.code = "JE", .name = "Jersey"},
{.code = "JO", .name = "Jordan"},
{.code = "KZ", .name = "Kazakhstan"},
{.code = "KE", .name = "Kenya"},
{.code = "KI", .name = "Kiribati"},
{.code = "KR", .name = "Korea"},
{.code = "KW", .name = "Kuwait"},
{.code = "KG", .name = "Kyrgyzstan"},
{.code = "LA", .name = "Lao People\"s Democratic Republic"},
{.code = "LV", .name = "Latvia"},
{.code = "LB", .name = "Lebanon"},
{.code = "LS", .name = "Lesotho"},
{.code = "LR", .name = "Liberia"},
{.code = "LY", .name = "Libyan Arab Jamahiriya"},
{.code = "LI", .name = "Liechtenstein"},
{.code = "LT", .name = "Lithuania"},
{.code = "LU", .name = "Luxembourg"},
{.code = "MO", .name = "Macao"},
{.code = "MK", .name = "Macedonia"},
{.code = "MG", .name = "Madagascar"},
{.code = "MW", .name = "Malawi"},
{.code = "MY", .name = "Malaysia"},
{.code = "MV", .name = "Maldives"},
{.code = "ML", .name = "Mali"},
{.code = "MT", .name = "Malta"},
{.code = "MH", .name = "Marshall Islands"},
{.code = "MQ", .name = "Martinique"},
{.code = "MR", .name = "Mauritania"},
{.code = "MU", .name = "Mauritius"},
{.code = "YT", .name = "Mayotte"},
{.code = "MX", .name = "Mexico"},
{.code = "FM", .name = "Micronesia, Federated States Of"},
{.code = "MD", .name = "Moldova"},
{.code = "MC", .name = "Monaco"},
{.code = "MN", .name = "Mongolia"},
{.code = "ME", .name = "Montenegro"},
{.code = "MS", .name = "Montserrat"},
{.code = "MA", .name = "Morocco"},
{.code = "MZ", .name = "Mozambique"},
{.code = "MM", .name = "Myanmar"},
{.code = "NA", .name = "Namibia"},
{.code = "NR", .name = "Nauru"},
{.code = "NP", .name = "Nepal"},
{.code = "NL", .name = "Netherlands"},
{.code = "AN", .name = "Netherlands Antilles"},
{.code = "NC", .name = "New Caledonia"},
{.code = "NZ", .name = "New Zealand"},
{.code = "NI", .name = "Nicaragua"},
{.code = "NE", .name = "Niger"},
{.code = "NG", .name = "Nigeria"},
{.code = "NU", .name = "Niue"},
{.code = "NF", .name = "Norfolk Island"},
{.code = "MP", .name = "Northern Mariana Islands"},
{.code = "NO", .name = "Norway"},
{.code = "OM", .name = "Oman"},
{.code = "PK", .name = "Pakistan"},
{.code = "PW", .name = "Palau"},
{.code = "PS", .name = "Palestinian Territory, Occupied"},
{.code = "PA", .name = "Panama"},
{.code = "PG", .name = "Papua New Guinea"},
{.code = "PY", .name = "Paraguay"},
{.code = "PE", .name = "Peru"},
{.code = "PH", .name = "Philippines"},
{.code = "PN", .name = "Pitcairn"},
{.code = "PL", .name = "Poland"},
{.code = "PT", .name = "Portugal"},
{.code = "PR", .name = "Puerto Rico"},
{.code = "QA", .name = "Qatar"},
{.code = "RE", .name = "Reunion"},
{.code = "RO", .name = "Romania"},
{.code = "RU", .name = "Russian Federation"},
{.code = "RW", .name = "Rwanda"},
{.code = "BL", .name = "Saint Barthelemy"},
{.code = "SH", .name = "Saint Helena"},
{.code = "KN", .name = "Saint Kitts And Nevis"},
{.code = "LC", .name = "Saint Lucia"},
{.code = "MF", .name = "Saint Martin"},
{.code = "PM", .name = "Saint Pierre And Miquelon"},
{.code = "VC", .name = "Saint Vincent And Grenadines"},
{.code = "WS", .name = "Samoa"},
{.code = "SM", .name = "San Marino"},
{.code = "ST", .name = "Sao Tome And Principe"},
{.code = "SA", .name = "Saudi Arabia"},
{.code = "SN", .name = "Senegal"},
{.code = "RS", .name = "Serbia"},
{.code = "SC", .name = "Seychelles"},
{.code = "SL", .name = "Sierra Leone"},
{.code = "SG", .name = "Singapore"},
{.code = "SK", .name = "Slovakia"},
{.code = "SI", .name = "Slovenia"},
{.code = "SB", .name = "Solomon Islands"},
{.code = "SO", .name = "Somalia"},
{.code = "ZA", .name = "South Africa"},
{.code = "GS", .name = "South Georgia And Sandwich Isl."},
{.code = "ES", .name = "Spain"},
{.code = "LK", .name = "Sri Lanka"},
{.code = "SD", .name = "Sudan"},
{.code = "SR", .name = "Suriname"},
{.code = "SJ", .name = "Svalbard And Jan Mayen"},
{.code = "SZ", .name = "Swaziland"},
{.code = "SE", .name = "Sweden"},
{.code = "CH", .name = "Switzerland"},
{.code = "SY", .name = "Syrian Arab Republic"},
{.code = "TW", .name = "Taiwan"},
{.code = "TJ", .name = "Tajikistan"},
{.code = "TZ", .name = "Tanzania"},
{.code = "TH", .name = "Thailand"},
{.code = "TL", .name = "Timor-Leste"},
{.code = "TG", .name = "Togo"},
{.code = "TK", .name = "Tokelau"},
{.code = "TO", .name = "Tonga"},
{.code = "TT", .name = "Trinidad And Tobago"},
{.code = "TN", .name = "Tunisia"},
{.code = "TR", .name = "Turkey"},
{.code = "TM", .name = "Turkmenistan"},
{.code = "TC", .name = "Turks And Caicos Islands"},
{.code = "TV", .name = "Tuvalu"},
{.code = "UG", .name = "Uganda"},
{.code = "UA", .name = "Ukraine"},
{.code = "AE", .name = "United Arab Emirates"},
{.code = "GB", .name = "United Kingdom"},
{.code = "US", .name = "United States"},
{.code = "UM", .name = "United States Outlying Islands"},
{.code = "UY", .name = "Uruguay"},
{.code = "UZ", .name = "Uzbekistan"},
{.code = "VU", .name = "Vanuatu"},
{.code = "VE", .name = "Venezuela"},
{.code = "VN", .name = "Viet Nam"},
{.code = "VG", .name = "Virgin Islands, British"},
{.code = "VI", .name = "Virgin Islands, U.S."},
{.code = "WF", .name = "Wallis And Futuna"},
{.code = "EH", .name = "Western Sahara"},
{.code = "YE", .name = "Yemen"},
{.code = "ZM", .name = "Zambia"},
{.code = "ZW", .name = "Zimbabwe"}};
} // namespace OpenWifi

View File

@@ -4,45 +4,46 @@
#include "framework/EventBusManager.h" #include "framework/EventBusManager.h"
#include "framework/KafkaManager.h" #include "framework/KafkaManager.h"
#include "framework/utils.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
namespace OpenWifi { namespace OpenWifi {
EventBusManager::EventBusManager(Poco::Logger &L) : EventBusManager::EventBusManager(Poco::Logger &L) : Logger_(L) {}
Logger_(L) {
}
void EventBusManager::run() { void EventBusManager::run() {
Running_ = true; Running_ = true;
Utils::SetThreadName("fmwk:EventMgr"); Utils::SetThreadName("fmwk:EventMgr");
auto Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_JOIN); auto Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_JOIN);
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false); KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg,
while(Running_) { false);
while (Running_) {
Poco::Thread::trySleep((unsigned long)MicroServiceDaemonBusTimer()); Poco::Thread::trySleep((unsigned long)MicroServiceDaemonBusTimer());
if(!Running_) if (!Running_)
break; break;
Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE); Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE);
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false); KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(),
Msg, false);
} }
Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE); Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE);
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false); KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg,
false);
}; };
void EventBusManager::Start() { void EventBusManager::Start() {
poco_information(Logger(),"Starting..."); poco_information(Logger(), "Starting...");
if(KafkaManager()->Enabled()) { if (KafkaManager()->Enabled()) {
Thread_.start(*this); Thread_.start(*this);
} }
} }
void EventBusManager::Stop() { void EventBusManager::Stop() {
if(KafkaManager()->Enabled()) { if (KafkaManager()->Enabled()) {
poco_information(Logger(),"Stopping..."); poco_information(Logger(), "Stopping...");
Running_ = false; Running_ = false;
Thread_.wakeUp(); Thread_.wakeUp();
Thread_.join(); Thread_.join();
poco_information(Logger(),"Stopped..."); poco_information(Logger(), "Stopped...");
} }
} }

View File

@@ -4,8 +4,8 @@
#pragma once #pragma once
#include "Poco/Runnable.h"
#include "Poco/Logger.h" #include "Poco/Logger.h"
#include "Poco/Runnable.h"
#include "Poco/Thread.h" #include "Poco/Thread.h"
namespace OpenWifi { namespace OpenWifi {
@@ -16,13 +16,12 @@ namespace OpenWifi {
void run() final; void run() final;
void Start(); void Start();
void Stop(); void Stop();
inline Poco::Logger & Logger() { return Logger_; } inline Poco::Logger &Logger() { return Logger_; }
private: private:
mutable std::atomic_bool Running_ = false; mutable std::atomic_bool Running_ = false;
Poco::Thread Thread_; Poco::Thread Thread_;
Poco::Logger &Logger_; Poco::Logger &Logger_;
}; };
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,251 +4,260 @@
#include "KafkaManager.h" #include "KafkaManager.h"
#include "framework/MicroServiceFuncs.h"
#include "fmt/format.h" #include "fmt/format.h"
#include "framework/MicroServiceFuncs.h"
namespace OpenWifi { namespace OpenWifi {
void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int level, const std::string & facility, const std::string &message) { void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int level,
switch ((cppkafka::LogLevel) level) { const std::string &facility, const std::string &message) {
switch ((cppkafka::LogLevel)level) {
case cppkafka::LogLevel::LogNotice: { case cppkafka::LogLevel::LogNotice: {
poco_notice(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); poco_notice(KafkaManager()->Logger(),
} fmt::format("kafka-log: facility: {} message: {}", facility, message));
break; } break;
case cppkafka::LogLevel::LogDebug: { case cppkafka::LogLevel::LogDebug: {
poco_debug(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); poco_debug(KafkaManager()->Logger(),
} fmt::format("kafka-log: facility: {} message: {}", facility, message));
break; } break;
case cppkafka::LogLevel::LogInfo: { case cppkafka::LogLevel::LogInfo: {
poco_information(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); poco_information(KafkaManager()->Logger(),
} fmt::format("kafka-log: facility: {} message: {}", facility, message));
break; } break;
case cppkafka::LogLevel::LogWarning: { case cppkafka::LogLevel::LogWarning: {
poco_warning(KafkaManager()->Logger(), fmt::format("kafka-log: facility: {} message: {}",facility, message)); poco_warning(KafkaManager()->Logger(),
} fmt::format("kafka-log: facility: {} message: {}", facility, message));
break; } break;
case cppkafka::LogLevel::LogAlert: case cppkafka::LogLevel::LogAlert:
case cppkafka::LogLevel::LogCrit: { case cppkafka::LogLevel::LogCrit: {
poco_critical(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); poco_critical(KafkaManager()->Logger(),
} fmt::format("kafka-log: facility: {} message: {}", facility, message));
break; } break;
case cppkafka::LogLevel::LogErr: case cppkafka::LogLevel::LogErr:
case cppkafka::LogLevel::LogEmerg: case cppkafka::LogLevel::LogEmerg:
default: { default: {
poco_error(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message)); poco_error(KafkaManager()->Logger(),
} fmt::format("kafka-log: facility: {} message: {}", facility, message));
break; } break;
} }
} }
inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int error, const std::string &reason) { inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int error,
poco_error(KafkaManager()->Logger(),fmt::format("kafka-error: {}, reason: {}", error, reason)); const std::string &reason) {
poco_error(KafkaManager()->Logger(),
fmt::format("kafka-error: {}, reason: {}", error, reason));
} }
inline void AddKafkaSecurity(cppkafka::Configuration & Config) { inline void AddKafkaSecurity(cppkafka::Configuration &Config) {
auto CA = MicroServiceConfigGetString("openwifi.kafka.ssl.ca.location",""); auto CA = MicroServiceConfigGetString("openwifi.kafka.ssl.ca.location", "");
auto Certificate = MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location",""); auto Certificate =
auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location",""); MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location", "");
auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password",""); auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location", "");
auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password", "");
if(CA.empty() || Certificate.empty() || Key.empty()) if (CA.empty() || Certificate.empty() || Key.empty())
return; return;
Config.set("ssl.ca.location", CA); Config.set("ssl.ca.location", CA);
Config.set("ssl.certificate.location", Certificate); Config.set("ssl.certificate.location", Certificate);
Config.set("ssl.key.location", Key); Config.set("ssl.key.location", Key);
if(!Password.empty()) if (!Password.empty())
Config.set("ssl.key.password", Password); Config.set("ssl.key.password", Password);
} }
void KafkaManager::initialize(Poco::Util::Application &self) {
void KafkaManager::initialize(Poco::Util::Application & self) {
SubSystemServer::initialize(self); SubSystemServer::initialize(self);
KafkaEnabled_ = MicroServiceConfigGetBool("openwifi.kafka.enable",false); KafkaEnabled_ = MicroServiceConfigGetBool("openwifi.kafka.enable", false);
} }
inline void KafkaProducer::run() { inline void KafkaProducer::run() {
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel()); Poco::Logger &Logger_ =
poco_information(Logger_,"Starting..."); Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel());
poco_information(Logger_, "Starting...");
Utils::SetThreadName("Kafka:Prod"); Utils::SetThreadName("Kafka:Prod");
cppkafka::Configuration Config({ cppkafka::Configuration Config(
{ "client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "") }, {{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")},
{ "metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist", "") } {"metadata.broker.list",
}); MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")}});
AddKafkaSecurity(Config); AddKafkaSecurity(Config);
Config.set_log_callback(KafkaLoggerFun); Config.set_log_callback(KafkaLoggerFun);
Config.set_error_callback(KafkaErrorFun); Config.set_error_callback(KafkaErrorFun);
KafkaManager()->SystemInfoWrapper_ = R"lit({ "system" : { "id" : )lit" + KafkaManager()->SystemInfoWrapper_ =
std::to_string(MicroServiceID()) + R"lit({ "system" : { "id" : )lit" + std::to_string(MicroServiceID()) +
R"lit( , "host" : ")lit" + MicroServicePrivateEndPoint() + R"lit( , "host" : ")lit" + MicroServicePrivateEndPoint() +
R"lit(" } , "payload" : )lit" ; R"lit(" } , "payload" : )lit";
cppkafka::Producer Producer(Config); cppkafka::Producer Producer(Config);
Running_ = true; Running_ = true;
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification()); Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
while(Note && Running_) { while (Note && Running_) {
try { try {
auto Msg = dynamic_cast<KafkaMessage *>(Note.get()); auto Msg = dynamic_cast<KafkaMessage *>(Note.get());
if (Msg != nullptr) { if (Msg != nullptr) {
Producer.produce( Producer.produce(cppkafka::MessageBuilder(Msg->Topic())
cppkafka::MessageBuilder(Msg->Topic()).key(Msg->Key()).payload(Msg->Payload())); .key(Msg->Key())
.payload(Msg->Payload()));
} }
} catch (const cppkafka::HandleException &E) { } catch (const cppkafka::HandleException &E) {
poco_warning(Logger_,fmt::format("Caught a Kafka exception (producer): {}", E.what())); poco_warning(Logger_,
} catch( const Poco::Exception &E) { fmt::format("Caught a Kafka exception (producer): {}", E.what()));
} catch (const Poco::Exception &E) {
Logger_.log(E); Logger_.log(E);
} catch (...) { } catch (...) {
poco_error(Logger_,"std::exception"); poco_error(Logger_, "std::exception");
} }
Note = Queue_.waitDequeueNotification(); Note = Queue_.waitDequeueNotification();
} }
poco_information(Logger_,"Stopped..."); poco_information(Logger_, "Stopped...");
} }
inline void KafkaConsumer::run() { inline void KafkaConsumer::run() {
Utils::SetThreadName("Kafka:Cons"); Utils::SetThreadName("Kafka:Cons");
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-CONSUMER", KafkaManager()->Logger().getChannel()); Poco::Logger &Logger_ =
Poco::Logger::create("KAFKA-CONSUMER", KafkaManager()->Logger().getChannel());
poco_information(Logger_,"Starting..."); poco_information(Logger_, "Starting...");
cppkafka::Configuration Config({ cppkafka::Configuration Config(
{ "client.id", MicroServiceConfigGetString("openwifi.kafka.client.id","") }, {{"client.id", MicroServiceConfigGetString("openwifi.kafka.client.id", "")},
{ "metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist","") }, {"metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist", "")},
{ "group.id", MicroServiceConfigGetString("openwifi.kafka.group.id","") }, {"group.id", MicroServiceConfigGetString("openwifi.kafka.group.id", "")},
{ "enable.auto.commit", MicroServiceConfigGetBool("openwifi.kafka.auto.commit",false) }, {"enable.auto.commit", MicroServiceConfigGetBool("openwifi.kafka.auto.commit", false)},
{ "auto.offset.reset", "latest" } , {"auto.offset.reset", "latest"},
{ "enable.partition.eof", false } {"enable.partition.eof", false}});
});
AddKafkaSecurity(Config); AddKafkaSecurity(Config);
Config.set_log_callback(KafkaLoggerFun); Config.set_log_callback(KafkaLoggerFun);
Config.set_error_callback(KafkaErrorFun); Config.set_error_callback(KafkaErrorFun);
cppkafka::TopicConfiguration topic_config = { cppkafka::TopicConfiguration topic_config = {{"auto.offset.reset", "smallest"}};
{ "auto.offset.reset", "smallest" }
};
// Now configure it to be the default topic config // Now configure it to be the default topic config
Config.set_default_topic_configuration(topic_config); Config.set_default_topic_configuration(topic_config);
cppkafka::Consumer Consumer(Config); cppkafka::Consumer Consumer(Config);
Consumer.set_assignment_callback([&](cppkafka::TopicPartitionList& partitions) { Consumer.set_assignment_callback([&](cppkafka::TopicPartitionList &partitions) {
if(!partitions.empty()) { if (!partitions.empty()) {
poco_information(Logger_,fmt::format("Partition assigned: {}...", poco_information(Logger_, fmt::format("Partition assigned: {}...",
partitions.front().get_partition())); partitions.front().get_partition()));
} }
}); });
Consumer.set_revocation_callback([&](const cppkafka::TopicPartitionList& partitions) { Consumer.set_revocation_callback([&](const cppkafka::TopicPartitionList &partitions) {
if(!partitions.empty()) { if (!partitions.empty()) {
poco_information(Logger_,fmt::format("Partition revocation: {}...", poco_information(Logger_, fmt::format("Partition revocation: {}...",
partitions.front().get_partition())); partitions.front().get_partition()));
} }
}); });
bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit",false); bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit", false);
auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize",20); auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize", 20);
Types::StringVec Topics; Types::StringVec Topics;
KafkaManager()->Topics(Topics); KafkaManager()->Topics(Topics);
Consumer.subscribe(Topics); Consumer.subscribe(Topics);
Running_ = true; Running_ = true;
while(Running_) { while (Running_) {
try { try {
std::vector<cppkafka::Message> MsgVec = Consumer.poll_batch(BatchSize, std::chrono::milliseconds(100)); std::vector<cppkafka::Message> MsgVec =
for(auto const &Msg:MsgVec) { Consumer.poll_batch(BatchSize, std::chrono::milliseconds(100));
for (auto const &Msg : MsgVec) {
if (!Msg) if (!Msg)
continue; continue;
if (Msg.get_error()) { if (Msg.get_error()) {
if (!Msg.is_eof()) { if (!Msg.is_eof()) {
poco_error(Logger_,fmt::format("Error: {}", Msg.get_error().to_string())); poco_error(Logger_,
fmt::format("Error: {}", Msg.get_error().to_string()));
} }
if(!AutoCommit) if (!AutoCommit)
Consumer.async_commit(Msg); Consumer.async_commit(Msg);
continue; continue;
} }
KafkaManager()->Dispatch(Msg.get_topic(), Msg.get_key(),Msg.get_payload() ); KafkaManager()->Dispatch(Msg.get_topic(), Msg.get_key(), Msg.get_payload());
if (!AutoCommit) if (!AutoCommit)
Consumer.async_commit(Msg); Consumer.async_commit(Msg);
} }
} catch (const cppkafka::HandleException &E) { } catch (const cppkafka::HandleException &E) {
poco_warning(Logger_,fmt::format("Caught a Kafka exception (consumer): {}", E.what())); poco_warning(Logger_,
fmt::format("Caught a Kafka exception (consumer): {}", E.what()));
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
Logger_.log(E); Logger_.log(E);
} catch (...) { } catch (...) {
poco_error(Logger_,"std::exception"); poco_error(Logger_, "std::exception");
} }
} }
Consumer.unsubscribe(); Consumer.unsubscribe();
poco_information(Logger_,"Stopped..."); poco_information(Logger_, "Stopped...");
} }
void KafkaProducer::Start() { void KafkaProducer::Start() {
if(!Running_) { if (!Running_) {
Running_=true; Running_ = true;
Worker_.start(*this); Worker_.start(*this);
} }
} }
void KafkaProducer::Stop() { void KafkaProducer::Stop() {
if(Running_) { if (Running_) {
Running_=false; Running_ = false;
Queue_.wakeUpAll(); Queue_.wakeUpAll();
Worker_.join(); Worker_.join();
} }
} }
void KafkaProducer::Produce(const std::string &Topic, const std::string &Key, const std::string &Payload) { void KafkaProducer::Produce(const std::string &Topic, const std::string &Key,
std::lock_guard G(Mutex_); const std::string &Payload) {
Queue_.enqueueNotification( new KafkaMessage(Topic,Key,Payload)); std::lock_guard G(Mutex_);
Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload));
} }
void KafkaConsumer::Start() { void KafkaConsumer::Start() {
if(!Running_) { if (!Running_) {
Running_=true; Running_ = true;
Worker_.start(*this); Worker_.start(*this);
} }
} }
void KafkaConsumer::Stop() { void KafkaConsumer::Stop() {
if(Running_) { if (Running_) {
Running_=false; Running_ = false;
Worker_.wakeUp(); Worker_.wakeUp();
Worker_.join(); Worker_.join();
} }
} }
void KafkaDispatcher::Start() { void KafkaDispatcher::Start() {
if(!Running_) { if (!Running_) {
Running_=true; Running_ = true;
Worker_.start(*this); Worker_.start(*this);
} }
} }
void KafkaDispatcher::Stop() { void KafkaDispatcher::Stop() {
if(Running_) { if (Running_) {
Running_=false; Running_ = false;
Queue_.wakeUpAll(); Queue_.wakeUpAll();
Worker_.join(); Worker_.join();
} }
} }
auto KafkaDispatcher::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) { auto KafkaDispatcher::RegisterTopicWatcher(const std::string &Topic,
Types::TopicNotifyFunction &F) {
std::lock_guard G(Mutex_); std::lock_guard G(Mutex_);
auto It = Notifiers_.find(Topic); auto It = Notifiers_.find(Topic);
if(It == Notifiers_.end()) { if (It == Notifiers_.end()) {
Types::TopicNotifyFunctionList L; Types::TopicNotifyFunctionList L;
L.emplace(L.end(),std::make_pair(F,FunctionId_)); L.emplace(L.end(), std::make_pair(F, FunctionId_));
Notifiers_[Topic] = std::move(L); Notifiers_[Topic] = std::move(L);
} else { } else {
It->second.emplace(It->second.end(),std::make_pair(F,FunctionId_)); It->second.emplace(It->second.end(), std::make_pair(F, FunctionId_));
} }
return FunctionId_++; return FunctionId_++;
} }
@@ -256,110 +265,114 @@ namespace OpenWifi {
void KafkaDispatcher::UnregisterTopicWatcher(const std::string &Topic, int Id) { void KafkaDispatcher::UnregisterTopicWatcher(const std::string &Topic, int Id) {
std::lock_guard G(Mutex_); std::lock_guard G(Mutex_);
auto It = Notifiers_.find(Topic); auto It = Notifiers_.find(Topic);
if(It != Notifiers_.end()) { if (It != Notifiers_.end()) {
Types::TopicNotifyFunctionList & L = It->second; Types::TopicNotifyFunctionList &L = It->second;
for(auto it=L.begin(); it!=L.end(); it++) for (auto it = L.begin(); it != L.end(); it++)
if(it->second == Id) { if (it->second == Id) {
L.erase(it); L.erase(it);
break; break;
} }
} }
} }
void KafkaDispatcher::Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload) { void KafkaDispatcher::Dispatch(const std::string &Topic, const std::string &Key,
std::lock_guard G(Mutex_); const std::string &Payload) {
std::lock_guard G(Mutex_);
auto It = Notifiers_.find(Topic); auto It = Notifiers_.find(Topic);
if(It!=Notifiers_.end()) { if (It != Notifiers_.end()) {
Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload)); Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload));
} }
} }
void KafkaDispatcher::run() { void KafkaDispatcher::run() {
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-DISPATCHER", KafkaManager()->Logger().getChannel()); Poco::Logger &Logger_ =
poco_information(Logger_,"Starting..."); Poco::Logger::create("KAFKA-DISPATCHER", KafkaManager()->Logger().getChannel());
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification()); poco_information(Logger_, "Starting...");
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
Utils::SetThreadName("kafka:dispatch"); Utils::SetThreadName("kafka:dispatch");
while(Note && Running_) { while (Note && Running_) {
auto Msg = dynamic_cast<KafkaMessage*>(Note.get()); auto Msg = dynamic_cast<KafkaMessage *>(Note.get());
if(Msg!= nullptr) { if (Msg != nullptr) {
auto It = Notifiers_.find(Msg->Topic()); auto It = Notifiers_.find(Msg->Topic());
if (It != Notifiers_.end()) { if (It != Notifiers_.end()) {
const auto & FL = It->second; const auto &FL = It->second;
for(const auto &[CallbackFunc,_]:FL) { for (const auto &[CallbackFunc, _] : FL) {
CallbackFunc(Msg->Key(), Msg->Payload()); CallbackFunc(Msg->Key(), Msg->Payload());
} }
} }
} }
Note = Queue_.waitDequeueNotification(); Note = Queue_.waitDequeueNotification();
} }
poco_information(Logger_,"Stopped..."); poco_information(Logger_, "Stopped...");
} }
void KafkaDispatcher::Topics(std::vector<std::string> &T) { void KafkaDispatcher::Topics(std::vector<std::string> &T) {
T.clear(); T.clear();
for(const auto &[TopicName,_]:Notifiers_) for (const auto &[TopicName, _] : Notifiers_)
T.push_back(TopicName); T.push_back(TopicName);
} }
int KafkaManager::Start() { int KafkaManager::Start() {
if(!KafkaEnabled_) if (!KafkaEnabled_)
return 0; return 0;
ConsumerThr_.Start(); ConsumerThr_.Start();
ProducerThr_.Start(); ProducerThr_.Start();
Dispatcher_.Start(); Dispatcher_.Start();
return 0; return 0;
} }
void KafkaManager::Stop() { void KafkaManager::Stop() {
if(KafkaEnabled_) { if (KafkaEnabled_) {
poco_information(Logger(),"Stopping..."); poco_information(Logger(), "Stopping...");
Dispatcher_.Stop(); Dispatcher_.Stop();
ProducerThr_.Stop(); ProducerThr_.Stop();
ConsumerThr_.Stop(); ConsumerThr_.Stop();
poco_information(Logger(),"Stopped..."); poco_information(Logger(), "Stopped...");
return; return;
} }
} }
void KafkaManager::PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage ) { void KafkaManager::PostMessage(const std::string &topic, const std::string &key,
if(KafkaEnabled_) { const std::string &PayLoad, bool WrapMessage) {
ProducerThr_.Produce(topic,key,WrapMessage ? WrapSystemId(PayLoad) : PayLoad); if (KafkaEnabled_) {
ProducerThr_.Produce(topic, key, WrapMessage ? WrapSystemId(PayLoad) : PayLoad);
} }
} }
void KafkaManager::Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload) { void KafkaManager::Dispatch(const std::string &Topic, const std::string &Key,
const std::string &Payload) {
Dispatcher_.Dispatch(Topic, Key, Payload); Dispatcher_.Dispatch(Topic, Key, Payload);
} }
[[nodiscard]] std::string KafkaManager::WrapSystemId(const std::string & PayLoad) { [[nodiscard]] std::string KafkaManager::WrapSystemId(const std::string &PayLoad) {
return SystemInfoWrapper_ + PayLoad + "}"; return SystemInfoWrapper_ + PayLoad + "}";
} }
uint64_t KafkaManager::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) { uint64_t KafkaManager::RegisterTopicWatcher(const std::string &Topic,
if(KafkaEnabled_) { Types::TopicNotifyFunction &F) {
return Dispatcher_.RegisterTopicWatcher(Topic,F); if (KafkaEnabled_) {
return Dispatcher_.RegisterTopicWatcher(Topic, F);
} else { } else {
return 0; return 0;
} }
} }
void KafkaManager::UnregisterTopicWatcher(const std::string &Topic, uint64_t Id) { void KafkaManager::UnregisterTopicWatcher(const std::string &Topic, uint64_t Id) {
if(KafkaEnabled_) { if (KafkaEnabled_) {
Dispatcher_.UnregisterTopicWatcher(Topic, Id); Dispatcher_.UnregisterTopicWatcher(Topic, Id);
} }
} }
void KafkaManager::Topics(std::vector<std::string> &T) { void KafkaManager::Topics(std::vector<std::string> &T) { Dispatcher_.Topics(T); }
Dispatcher_.Topics(T);
void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList &partitions) {
poco_information(
Logger(), fmt::format("Partition assigned: {}...", partitions.front().get_partition()));
} }
void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList& partitions) { void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList &partitions) {
poco_information(Logger(),fmt::format("Partition assigned: {}...", partitions.front().get_partition())); poco_information(Logger(), fmt::format("Partition revocation: {}...",
} partitions.front().get_partition()));
void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList& partitions) {
poco_information(Logger(),fmt::format("Partition revocation: {}...",partitions.front().get_partition()));
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -7,44 +7,43 @@
#include "Poco/Notification.h" #include "Poco/Notification.h"
#include "Poco/NotificationQueue.h" #include "Poco/NotificationQueue.h"
#include "framework/SubSystemServer.h"
#include "framework/OpenWifiTypes.h"
#include "framework/utils.h"
#include "framework/KafkaTopics.h" #include "framework/KafkaTopics.h"
#include "framework/OpenWifiTypes.h"
#include "framework/SubSystemServer.h"
#include "framework/utils.h"
#include "cppkafka/cppkafka.h" #include "cppkafka/cppkafka.h"
namespace OpenWifi { namespace OpenWifi {
class KafkaMessage: public Poco::Notification { class KafkaMessage : public Poco::Notification {
public: public:
KafkaMessage( const std::string &Topic, const std::string &Key, const std::string & Payload) : KafkaMessage(const std::string &Topic, const std::string &Key, const std::string &Payload)
Topic_(Topic), Key_(Key), Payload_(Payload) { : Topic_(Topic), Key_(Key), Payload_(Payload) {}
}
inline const std::string & Topic() { return Topic_; } inline const std::string &Topic() { return Topic_; }
inline const std::string & Key() { return Key_; } inline const std::string &Key() { return Key_; }
inline const std::string & Payload() { return Payload_; } inline const std::string &Payload() { return Payload_; }
private: private:
std::string Topic_; std::string Topic_;
std::string Key_; std::string Key_;
std::string Payload_; std::string Payload_;
}; };
class KafkaProducer : public Poco::Runnable { class KafkaProducer : public Poco::Runnable {
public: public:
void run () override; void run() override;
void Start(); void Start();
void Stop(); void Stop();
void Produce(const std::string &Topic, const std::string &Key, const std::string &Payload); void Produce(const std::string &Topic, const std::string &Key, const std::string &Payload);
private: private:
std::recursive_mutex Mutex_; std::recursive_mutex Mutex_;
Poco::Thread Worker_; Poco::Thread Worker_;
mutable std::atomic_bool Running_=false; mutable std::atomic_bool Running_ = false;
Poco::NotificationQueue Queue_; Poco::NotificationQueue Queue_;
}; };
class KafkaConsumer : public Poco::Runnable { class KafkaConsumer : public Poco::Runnable {
public: public:
@@ -53,9 +52,9 @@ namespace OpenWifi {
void Stop(); void Stop();
private: private:
std::recursive_mutex Mutex_; std::recursive_mutex Mutex_;
Poco::Thread Worker_; Poco::Thread Worker_;
mutable std::atomic_bool Running_=false; mutable std::atomic_bool Running_ = false;
}; };
class KafkaDispatcher : public Poco::Runnable { class KafkaDispatcher : public Poco::Runnable {
@@ -69,21 +68,20 @@ namespace OpenWifi {
void Topics(std::vector<std::string> &T); void Topics(std::vector<std::string> &T);
private: private:
std::recursive_mutex Mutex_; std::recursive_mutex Mutex_;
Types::NotifyTable Notifiers_; Types::NotifyTable Notifiers_;
Poco::Thread Worker_; Poco::Thread Worker_;
mutable std::atomic_bool Running_=false; mutable std::atomic_bool Running_ = false;
uint64_t FunctionId_=1; uint64_t FunctionId_ = 1;
Poco::NotificationQueue Queue_; Poco::NotificationQueue Queue_;
}; };
class KafkaManager : public SubSystemServer { class KafkaManager : public SubSystemServer {
public: public:
friend class KafkaConsumer; friend class KafkaConsumer;
friend class KafkaProducer; friend class KafkaProducer;
inline void initialize(Poco::Util::Application & self) override; inline void initialize(Poco::Util::Application &self) override;
static auto instance() { static auto instance() {
static auto instance_ = new KafkaManager; static auto instance_ = new KafkaManager;
@@ -93,30 +91,28 @@ namespace OpenWifi {
int Start() override; int Start() override;
void Stop() override; void Stop() override;
void PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage = true ); void PostMessage(const std::string &topic, const std::string &key,
void Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload); const std::string &PayLoad, bool WrapMessage = true);
[[nodiscard]] std::string WrapSystemId(const std::string & PayLoad); void Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload);
[[nodiscard]] std::string WrapSystemId(const std::string &PayLoad);
[[nodiscard]] inline bool Enabled() const { return KafkaEnabled_; } [[nodiscard]] inline bool Enabled() const { return KafkaEnabled_; }
uint64_t RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F); uint64_t RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F);
void UnregisterTopicWatcher(const std::string &Topic, uint64_t Id); void UnregisterTopicWatcher(const std::string &Topic, uint64_t Id);
void Topics(std::vector<std::string> &T); void Topics(std::vector<std::string> &T);
private: private:
bool KafkaEnabled_ = false; bool KafkaEnabled_ = false;
std::string SystemInfoWrapper_; std::string SystemInfoWrapper_;
KafkaProducer ProducerThr_; KafkaProducer ProducerThr_;
KafkaConsumer ConsumerThr_; KafkaConsumer ConsumerThr_;
KafkaDispatcher Dispatcher_; KafkaDispatcher Dispatcher_;
void PartitionAssignment(const cppkafka::TopicPartitionList& partitions); void PartitionAssignment(const cppkafka::TopicPartitionList &partitions);
void PartitionRevocation(const cppkafka::TopicPartitionList& partitions); void PartitionRevocation(const cppkafka::TopicPartitionList &partitions);
KafkaManager() noexcept: KafkaManager() noexcept : SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") {}
SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") {
}
}; };
inline auto KafkaManager() { return KafkaManager::instance(); } inline auto KafkaManager() { return KafkaManager::instance(); }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -19,7 +19,7 @@ namespace OpenWifi::KafkaTopics {
static const std::string SERVICE_EVENTS{"service_events"}; static const std::string SERVICE_EVENTS{"service_events"};
static const std::string DEVICE_EVENT_QUEUE{"device_event_queue"}; static const std::string DEVICE_EVENT_QUEUE{"device_event_queue"};
static const std::string DEVICE_TELEMETRY{"device_telemetry"}; static const std::string DEVICE_TELEMETRY{"device_telemetry"};
static const std::string PROVISIONING_CHANGE{"provisioning_change"}; static const std::string PROVISIONING_CHANGE{"provisioning_change"};
namespace ServiceEvents { namespace ServiceEvents {
static const std::string EVENT_JOIN{"join"}; static const std::string EVENT_JOIN{"join"};
@@ -36,7 +36,6 @@ namespace OpenWifi::KafkaTopics {
static const std::string KEY{"key"}; static const std::string KEY{"key"};
static const std::string VRSN{"version"}; static const std::string VRSN{"version"};
static const std::string TOKEN{"token"}; static const std::string TOKEN{"token"};
} } // namespace Fields
} } // namespace ServiceEvents
} } // namespace OpenWifi::KafkaTopics

View File

@@ -2,40 +2,39 @@
// Created by stephane bourque on 2022-10-26. // Created by stephane bourque on 2022-10-26.
// //
#include "Poco/FileChannel.h"
#include "Poco/ConsoleChannel.h"
#include "Poco/PatternFormatter.h"
#include "Poco/FormattingChannel.h"
#include "Poco/AsyncChannel.h" #include "Poco/AsyncChannel.h"
#include "Poco/NullChannel.h" #include "Poco/ConsoleChannel.h"
#include "Poco/SplitterChannel.h" #include "Poco/FileChannel.h"
#include "Poco/Net/HTTPStreamFactory.h" #include "Poco/FormattingChannel.h"
#include "Poco/Net/HTTPSStreamFactory.h" #include "Poco/JSON/JSONException.h"
#include "Poco/Net/FTPSStreamFactory.h" #include "Poco/Net/FTPSStreamFactory.h"
#include "Poco/Net/FTPStreamFactory.h" #include "Poco/Net/FTPStreamFactory.h"
#include "Poco/Net/HTTPSStreamFactory.h"
#include "Poco/Net/HTTPStreamFactory.h"
#include "Poco/Net/SSLManager.h" #include "Poco/Net/SSLManager.h"
#include "Poco/JSON/JSONException.h" #include "Poco/NullChannel.h"
#include "Poco/PatternFormatter.h"
#include "Poco/SplitterChannel.h"
#include "framework/ALBserver.h"
#include "framework/AuthClient.h"
#include "framework/KafkaManager.h"
#include "framework/MicroService.h" #include "framework/MicroService.h"
#include "framework/MicroServiceErrorHandler.h" #include "framework/MicroServiceErrorHandler.h"
#include "framework/UI_WebSocketClientServer.h"
#include "framework/MicroServiceNames.h" #include "framework/MicroServiceNames.h"
#include "framework/AuthClient.h"
#include "framework/ALBserver.h"
#include "framework/KafkaManager.h"
#include "framework/RESTAPI_GenericServerAccounting.h"
#include "framework/RESTAPI_ExtServer.h" #include "framework/RESTAPI_ExtServer.h"
#include "framework/RESTAPI_GenericServerAccounting.h"
#include "framework/RESTAPI_IntServer.h" #include "framework/RESTAPI_IntServer.h"
#include "framework/utils.h" #include "framework/UI_WebSocketClientServer.h"
#include "framework/WebSocketLogger.h" #include "framework/WebSocketLogger.h"
#include "framework/utils.h"
namespace OpenWifi { namespace OpenWifi {
void MicroService::Exit(int Reason) { void MicroService::Exit(int Reason) { std::exit(Reason); }
std::exit(Reason);
}
void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key, const std::string & Payload) { void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key,
const std::string &Payload) {
std::lock_guard G(InfraMutex_); std::lock_guard G(InfraMutex_);
try { try {
Poco::JSON::Parser P; Poco::JSON::Parser P;
@@ -43,66 +42,99 @@ namespace OpenWifi {
if (Object->has(KafkaTopics::ServiceEvents::Fields::ID) && if (Object->has(KafkaTopics::ServiceEvents::Fields::ID) &&
Object->has(KafkaTopics::ServiceEvents::Fields::EVENT)) { Object->has(KafkaTopics::ServiceEvents::Fields::EVENT)) {
uint64_t ID = Object->get(KafkaTopics::ServiceEvents::Fields::ID); uint64_t ID = Object->get(KafkaTopics::ServiceEvents::Fields::ID);
auto Event = Object->get(KafkaTopics::ServiceEvents::Fields::EVENT).toString(); auto Event = Object->get(KafkaTopics::ServiceEvents::Fields::EVENT).toString();
if (ID != ID_) { if (ID != ID_) {
if( Event==KafkaTopics::ServiceEvents::EVENT_JOIN || if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN ||
Event==KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE || Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE ||
Event==KafkaTopics::ServiceEvents::EVENT_LEAVE ) { Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) {
if( Object->has(KafkaTopics::ServiceEvents::Fields::TYPE) && if (Object->has(KafkaTopics::ServiceEvents::Fields::TYPE) &&
Object->has(KafkaTopics::ServiceEvents::Fields::PUBLIC) && Object->has(KafkaTopics::ServiceEvents::Fields::PUBLIC) &&
Object->has(KafkaTopics::ServiceEvents::Fields::PRIVATE) && Object->has(KafkaTopics::ServiceEvents::Fields::PRIVATE) &&
Object->has(KafkaTopics::ServiceEvents::Fields::VRSN) && Object->has(KafkaTopics::ServiceEvents::Fields::VRSN) &&
Object->has(KafkaTopics::ServiceEvents::Fields::KEY)) { Object->has(KafkaTopics::ServiceEvents::Fields::KEY)) {
auto PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(); auto PrivateEndPoint =
if (Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE && Services_.find(PrivateEndPoint) != Services_.end()) { Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString();
if (Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE &&
Services_.find(PrivateEndPoint) != Services_.end()) {
Services_[PrivateEndPoint].LastUpdate = Utils::Now(); Services_[PrivateEndPoint].LastUpdate = Utils::Now();
} else if (Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) { } else if (Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) {
Services_.erase(PrivateEndPoint); Services_.erase(PrivateEndPoint);
poco_debug(logger(),fmt::format("Service {} ID={} leaving system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID)); poco_debug(
} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN || Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) { logger(),
poco_debug(logger(),fmt::format("Service {} ID={} joining system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID)); fmt::format(
"Service {} ID={} leaving system.",
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN ||
Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) {
poco_debug(
logger(),
fmt::format(
"Service {} ID={} joining system.",
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
Services_[PrivateEndPoint] = Types::MicroServiceMeta{ Services_[PrivateEndPoint] = Types::MicroServiceMeta{
.Id = ID, .Id = ID,
.Type = Poco::toLower(Object->get(KafkaTopics::ServiceEvents::Fields::TYPE).toString()), .Type = Poco::toLower(
.PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(), Object->get(KafkaTopics::ServiceEvents::Fields::TYPE)
.PublicEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PUBLIC).toString(), .toString()),
.AccessKey = Object->get(KafkaTopics::ServiceEvents::Fields::KEY).toString(), .PrivateEndPoint =
.Version = Object->get(KafkaTopics::ServiceEvents::Fields::VRSN).toString(), Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.LastUpdate = Utils::Now() }; .toString(),
.PublicEndPoint =
Object->get(KafkaTopics::ServiceEvents::Fields::PUBLIC)
.toString(),
.AccessKey =
Object->get(KafkaTopics::ServiceEvents::Fields::KEY)
.toString(),
.Version = Object->get(KafkaTopics::ServiceEvents::Fields::VRSN)
.toString(),
.LastUpdate = Utils::Now()};
std::string SvcList; std::string SvcList;
for (const auto &Svc: Services_) { for (const auto &Svc : Services_) {
if(SvcList.empty()) if (SvcList.empty())
SvcList = Svc.second.Type; SvcList = Svc.second.Type;
else else
SvcList += ", " + Svc.second.Type; SvcList += ", " + Svc.second.Type;
} }
poco_information(logger(),fmt::format("Current list of microservices: {}", SvcList)); poco_information(
logger(),
fmt::format("Current list of microservices: {}", SvcList));
} }
} else { } else {
poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing a field.",Event)); poco_error(
logger(),
fmt::format("KAFKA-MSG: invalid event '{}', missing a field.",
Event));
} }
} else if (Event==KafkaTopics::ServiceEvents::EVENT_REMOVE_TOKEN) { } else if (Event == KafkaTopics::ServiceEvents::EVENT_REMOVE_TOKEN) {
if(Object->has(KafkaTopics::ServiceEvents::Fields::TOKEN)) { if (Object->has(KafkaTopics::ServiceEvents::Fields::TOKEN)) {
#ifndef TIP_SECURITY_SERVICE #ifndef TIP_SECURITY_SERVICE
AuthClient()->RemovedCachedToken(Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString()); AuthClient()->RemovedCachedToken(
#endif Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString());
#endif
} else { } else {
poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing token",Event)); poco_error(
logger(),
fmt::format("KAFKA-MSG: invalid event '{}', missing token", Event));
} }
} else { } else {
poco_error(logger(),fmt::format("Unknown Event: {} Source: {}", Event, ID)); poco_error(logger(),
fmt::format("Unknown Event: {} Source: {}", Event, ID));
} }
} }
} else { } else {
poco_error(logger(),"Bad bus message."); poco_error(logger(), "Bad bus message.");
} }
auto i=Services_.begin(); auto i = Services_.begin();
auto now = Utils::Now(); auto now = Utils::Now();
for(;i!=Services_.end();) { for (; i != Services_.end();) {
if((now - i->second.LastUpdate)>60) { if ((now - i->second.LastUpdate) > 60) {
i = Services_.erase(i); i = Services_.erase(i);
} else } else
++i; ++i;
@@ -113,13 +145,13 @@ namespace OpenWifi {
} }
} }
Types::MicroServiceMetaVec MicroService::GetServices(const std::string & Type) { Types::MicroServiceMetaVec MicroService::GetServices(const std::string &Type) {
std::lock_guard G(InfraMutex_); std::lock_guard G(InfraMutex_);
auto T = Poco::toLower(Type); auto T = Poco::toLower(Type);
Types::MicroServiceMetaVec Res; Types::MicroServiceMetaVec Res;
for(const auto &[_,ServiceRec]:Services_) { for (const auto &[_, ServiceRec] : Services_) {
if(ServiceRec.Type==T) if (ServiceRec.Type == T)
Res.push_back(ServiceRec); Res.push_back(ServiceRec);
} }
return Res; return Res;
@@ -128,23 +160,25 @@ namespace OpenWifi {
Types::MicroServiceMetaVec MicroService::GetServices() { Types::MicroServiceMetaVec MicroService::GetServices() {
std::lock_guard G(InfraMutex_); std::lock_guard G(InfraMutex_);
Types::MicroServiceMetaVec Res; Types::MicroServiceMetaVec Res;
for(const auto &[_,ServiceRec]:Services_) { for (const auto &[_, ServiceRec] : Services_) {
Res.push_back(ServiceRec); Res.push_back(ServiceRec);
} }
return Res; return Res;
} }
void MicroService::LoadConfigurationFile() { void MicroService::LoadConfigurationFile() {
std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR,"."); std::string Location = Poco::Environment::get(DAEMON_CONFIG_ENV_VAR, ".");
ConfigFileName_ = ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_; ConfigFileName_ =
ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : ConfigFileName_;
Poco::Path ConfigFile(ConfigFileName_); Poco::Path ConfigFile(ConfigFileName_);
if(!ConfigFile.isFile()) if (!ConfigFile.isFile()) {
{ std::cerr << DAEMON_APP_NAME << ": Configuration " << ConfigFile.toString()
std::cerr << DAEMON_APP_NAME << ": Configuration " << " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR +
<< ConfigFile.toString() << " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR " env variable the path of the " + DAEMON_PROPERTIES_FILENAME +
+ " env variable the path of the " + DAEMON_PROPERTIES_FILENAME + " file." << std::endl; " file."
<< std::endl;
std::exit(Poco::Util::Application::EXIT_CONFIG); std::exit(Poco::Util::Application::EXIT_CONFIG);
} }
@@ -159,11 +193,12 @@ namespace OpenWifi {
} }
void MicroService::LoadMyConfig() { void MicroService::LoadMyConfig() {
NoAPISecurity_ = ConfigGetBool("openwifi.security.restapi.disable",false); NoAPISecurity_ = ConfigGetBool("openwifi.security.restapi.disable", false);
std::string KeyFile = ConfigPath("openwifi.service.key",""); std::string KeyFile = ConfigPath("openwifi.service.key", "");
if(!KeyFile.empty()) { if (!KeyFile.empty()) {
std::string KeyFilePassword = ConfigPath("openwifi.service.key.password", ""); std::string KeyFilePassword = ConfigPath("openwifi.service.key.password", "");
AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword)); AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(
new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword));
Cipher_ = CipherFactory_.createCipher(*AppKey_); Cipher_ = CipherFactory_.createCipher(*AppKey_);
Signer_.setRSAKey(AppKey_); Signer_.setRSAKey(AppKey_);
Signer_.addAllAlgorithms(); Signer_.addAllAlgorithms();
@@ -173,8 +208,8 @@ namespace OpenWifi {
} }
ID_ = Utils::GetSystemId(); ID_ = Utils::GetSystemId();
if(!DebugMode_) if (!DebugMode_)
DebugMode_ = ConfigGetBool("openwifi.system.debug",false); DebugMode_ = ConfigGetBool("openwifi.system.debug", false);
MyPrivateEndPoint_ = ConfigGetString("openwifi.system.uri.private"); MyPrivateEndPoint_ = ConfigGetString("openwifi.system.uri.private");
MyPublicEndPoint_ = ConfigGetString("openwifi.system.uri.public"); MyPublicEndPoint_ = ConfigGetString("openwifi.system.uri.public");
UIURI_ = ConfigGetString("openwifi.system.uri.ui"); UIURI_ = ConfigGetString("openwifi.system.uri.ui");
@@ -184,151 +219,170 @@ namespace OpenWifi {
void MicroService::InitializeLoggingSystem() { void MicroService::InitializeLoggingSystem() {
static auto initialized = false; static auto initialized = false;
if(!initialized) { if (!initialized) {
initialized = true; initialized = true;
LoadConfigurationFile(); LoadConfigurationFile();
auto LoggingDestination = MicroService::instance().ConfigGetString("logging.type", "file"); auto LoggingDestination =
auto LoggingFormat = MicroService::instance().ConfigGetString("logging.format", MicroService::instance().ConfigGetString("logging.type", "file");
"%Y-%m-%d %H:%M:%S.%i %s: [%p][thr:%I] %t"); auto LoggingFormat = MicroService::instance().ConfigGetString(
"logging.format", "%Y-%m-%d %H:%M:%S.%i %s: [%p][thr:%I] %t");
auto UseAsyncLogs_ = MicroService::instance().ConfigGetBool("logging.asynch", true); auto UseAsyncLogs_ = MicroService::instance().ConfigGetBool("logging.asynch", true);
auto DisableWebSocketLogging = MicroService::instance().ConfigGetBool("logging.websocket",false); auto DisableWebSocketLogging =
MicroService::instance().ConfigGetBool("logging.websocket", false);
if (LoggingDestination == "null") { if (LoggingDestination == "null") {
Poco::AutoPtr<Poco::NullChannel> DevNull(new Poco::NullChannel); Poco::AutoPtr<Poco::NullChannel> DevNull(new Poco::NullChannel);
Poco::Logger::root().setChannel(DevNull); Poco::Logger::root().setChannel(DevNull);
} else if (LoggingDestination == "console") { } else if (LoggingDestination == "console") {
SetConsoleLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat); SetConsoleLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
} else if (LoggingDestination == "colorconsole") { } else if (LoggingDestination == "colorconsole") {
SetColorConsoleLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat); SetColorConsoleLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
} else if (LoggingDestination == "sql") { } else if (LoggingDestination == "sql") {
SetSQLLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat); SetSQLLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
} else if (LoggingDestination == "syslog") { } else if (LoggingDestination == "syslog") {
SetSyslogLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat); SetSyslogLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
} else { } else {
SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat, DAEMON_ROOT_ENV_VAR); SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat,
} DAEMON_ROOT_ENV_VAR);
}
auto Level = Poco::Logger::parseLevel(MicroService::instance().ConfigGetString("logging.level", "debug")); auto Level = Poco::Logger::parseLevel(
MicroService::instance().ConfigGetString("logging.level", "debug"));
Poco::Logger::root().setLevel(Level); Poco::Logger::root().setLevel(Level);
if(!DisableWebSocketLogging) { if (!DisableWebSocketLogging) {
static const UI_WebSocketClientServer::NotificationTypeIdVec Notifications = { static const UI_WebSocketClientServer::NotificationTypeIdVec Notifications = {
{1, "log"}}; {1, "log"}};
UI_WebSocketClientServer()->RegisterNotifications(Notifications); UI_WebSocketClientServer()->RegisterNotifications(Notifications);
} }
} }
} }
void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) { void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging,
const std::string &FormatterPattern) {
Poco::AutoPtr<Poco::ConsoleChannel> Console(new Poco::ConsoleChannel); Poco::AutoPtr<Poco::ConsoleChannel> Console(new Poco::ConsoleChannel);
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
Formatter->setProperty("pattern", FormatterPattern); Formatter->setProperty("pattern", FormatterPattern);
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console)); Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(
new Poco::FormattingChannel(Formatter, Console));
if(DisableWebSocketLogging) { if (DisableWebSocketLogging) {
if(UseAsync) { if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel)); Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
Poco::Logger::root().setChannel(Async); Poco::Logger::root().setChannel(Async);
} else { } else {
Poco::Logger::root().setChannel(FormattingChannel); Poco::Logger::root().setChannel(FormattingChannel);
} }
} else { } else {
Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger); Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger);
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel); Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
Splitter->addChannel(WSLogger); Splitter->addChannel(WSLogger);
Splitter->addChannel(FormattingChannel); Splitter->addChannel(FormattingChannel);
if(UseAsync) { if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter)); Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
Poco::Logger::root().setChannel(Async); Poco::Logger::root().setChannel(Async);
} else { } else {
Poco::Logger::root().setChannel(Splitter); Poco::Logger::root().setChannel(Splitter);
} }
} }
Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging)); Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}",
} UseAsync, DisableWebSocketLogging));
}
void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) { void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging,
const std::string &FormatterPattern) {
Poco::AutoPtr<Poco::ColorConsoleChannel> Console(new Poco::ColorConsoleChannel); Poco::AutoPtr<Poco::ColorConsoleChannel> Console(new Poco::ColorConsoleChannel);
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
Formatter->setProperty("pattern", FormatterPattern); Formatter->setProperty("pattern", FormatterPattern);
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console)); Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(
new Poco::FormattingChannel(Formatter, Console));
if(DisableWebSocketLogging) { if (DisableWebSocketLogging) {
if(UseAsync) { if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel)); Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
Poco::Logger::root().setChannel(Async); Poco::Logger::root().setChannel(Async);
} else { } else {
Poco::Logger::root().setChannel(FormattingChannel); Poco::Logger::root().setChannel(FormattingChannel);
} }
} else { } else {
Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger); Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger);
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel); Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
Splitter->addChannel(WSLogger); Splitter->addChannel(WSLogger);
Splitter->addChannel(FormattingChannel); Splitter->addChannel(FormattingChannel);
if(UseAsync) { if (UseAsync) {
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter)); Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
Poco::Logger::root().setChannel(Async); Poco::Logger::root().setChannel(Async);
} else { } else {
Poco::Logger::root().setChannel(Splitter); Poco::Logger::root().setChannel(Splitter);
} }
} }
Poco::Logger::root().information(fmt::format("Enabled color console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging)); Poco::Logger::root().information(
} fmt::format("Enabled color console logs: asynch={} websocket={}", UseAsync,
DisableWebSocketLogging));
}
void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]] bool DisableWebSocketLogging,[[maybe_unused]] const std::string & FormatterPattern) { void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync,
//"CREATE TABLE T_POCO_LOG (Source VARCHAR, Name VARCHAR, ProcessId INTEGER, Thread VARCHAR, ThreadId INTEGER, Priority INTEGER, Text VARCHAR, DateTime DATE)" [[maybe_unused]] bool DisableWebSocketLogging,
} [[maybe_unused]] const std::string &FormatterPattern) {
//"CREATE TABLE T_POCO_LOG (Source VARCHAR, Name VARCHAR, ProcessId INTEGER, Thread VARCHAR,
//ThreadId INTEGER, Priority INTEGER, Text VARCHAR, DateTime DATE)"
}
void MicroService::SetSyslogLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]] bool DisableWebSocketLogging,[[maybe_unused]] const std::string & FormatterPattern) { void MicroService::SetSyslogLogs([[maybe_unused]] bool UseAsync,
[[maybe_unused]] bool DisableWebSocketLogging,
[[maybe_unused]] const std::string &FormatterPattern) {}
} void MicroService::SetFileLogs(bool UseAsync, bool DisableWebSocketLogging,
const std::string &FormatterPattern,
const std::string &root_env_var) {
std::string DefaultLogPath = fmt::format("${}/logs", root_env_var);
auto LoggingLocationDir =
MicroService::instance().ConfigPath("logging.path", DefaultLogPath);
Poco::File LD(LoggingLocationDir);
try {
if (!LD.exists()) {
LD.createDirectory();
}
} catch (const Poco::Exception &E) {
std::cout << "Cannot create " << LD.path() << " Error: " << E.message() << std::endl;
}
auto LoggingLocationDirFilePattern = LoggingLocationDir + "/log";
void MicroService::SetFileLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern, const std::string & root_env_var) { Poco::AutoPtr<Poco::FileChannel> FileChannel(new Poco::FileChannel);
std::string DefaultLogPath = fmt::format("${}/logs",root_env_var); FileChannel->setProperty("rotation", "10 M");
auto LoggingLocationDir = MicroService::instance().ConfigPath("logging.path", DefaultLogPath); FileChannel->setProperty("archive", "timestamp");
Poco::File LD(LoggingLocationDir); FileChannel->setProperty("purgeCount", "10");
try { FileChannel->setProperty("path", LoggingLocationDirFilePattern);
if(!LD.exists()) {
LD.createDirectory();
}
} catch(const Poco::Exception &E) {
std::cout << "Cannot create " << LD.path() << " Error: " << E.message() << std::endl;
}
auto LoggingLocationDirFilePattern = LoggingLocationDir + "/log";
Poco::AutoPtr<Poco::FileChannel> FileChannel(new Poco::FileChannel); Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
FileChannel->setProperty("rotation", "10 M"); Formatter->setProperty("pattern", FormatterPattern);
FileChannel->setProperty("archive", "timestamp"); Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(
FileChannel->setProperty("purgeCount", "10"); new Poco::FormattingChannel(Formatter, FileChannel));
FileChannel->setProperty("path", LoggingLocationDirFilePattern);
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); if (DisableWebSocketLogging) {
Formatter->setProperty("pattern", FormatterPattern); if (UseAsync) {
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, FileChannel)); Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel));
Poco::Logger::root().setChannel(Async);
if(DisableWebSocketLogging) { } else {
if(UseAsync) { Poco::Logger::root().setChannel(FormattingChannel);
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(FormattingChannel)); }
Poco::Logger::root().setChannel(Async); } else {
} else { Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger);
Poco::Logger::root().setChannel(FormattingChannel); Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel);
} Splitter->addChannel(WSLogger);
} else { Splitter->addChannel(FormattingChannel);
Poco::AutoPtr<WebSocketLogger> WSLogger(new WebSocketLogger); if (UseAsync) {
Poco::AutoPtr<Poco::SplitterChannel> Splitter(new Poco::SplitterChannel); Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter));
Splitter->addChannel(WSLogger); Poco::Logger::root().setChannel(Async);
Splitter->addChannel(FormattingChannel); } else {
if(UseAsync) { Poco::Logger::root().setChannel(Splitter);
Poco::AutoPtr<Poco::AsyncChannel> Async(new Poco::AsyncChannel(Splitter)); }
Poco::Logger::root().setChannel(Async); }
} else { Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}",
Poco::Logger::root().setChannel(Splitter); UseAsync, DisableWebSocketLogging));
} }
}
Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
}
void DaemonPostInitialization(Poco::Util::Application &self); void DaemonPostInitialization(Poco::Util::Application &self);
@@ -341,37 +395,39 @@ namespace OpenWifi {
SubSystems_.push_back(ALBHealthCheckServer()); SubSystems_.push_back(ALBHealthCheckServer());
SubSystems_.push_back(RESTAPI_ExtServer()); SubSystems_.push_back(RESTAPI_ExtServer());
SubSystems_.push_back(RESTAPI_IntServer()); SubSystems_.push_back(RESTAPI_IntServer());
#ifndef TIP_SECURITY_SERVICE #ifndef TIP_SECURITY_SERVICE
SubSystems_.push_back(AuthClient()); SubSystems_.push_back(AuthClient());
#endif #endif
Poco::Net::initializeSSL(); Poco::Net::initializeSSL();
Poco::Net::HTTPStreamFactory::registerFactory(); Poco::Net::HTTPStreamFactory::registerFactory();
Poco::Net::HTTPSStreamFactory::registerFactory(); Poco::Net::HTTPSStreamFactory::registerFactory();
Poco::Net::FTPStreamFactory::registerFactory(); Poco::Net::FTPStreamFactory::registerFactory();
Poco::Net::FTPSStreamFactory::registerFactory(); Poco::Net::FTPSStreamFactory::registerFactory();
Poco::File DataDir(ConfigPath("openwifi.system.data")); Poco::File DataDir(ConfigPath("openwifi.system.data"));
DataDir_ = DataDir.path(); DataDir_ = DataDir.path();
if(!DataDir.exists()) { if (!DataDir.exists()) {
try { try {
DataDir.createDirectory(); DataDir.createDirectory();
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
logger().log(E); logger().log(E);
} }
} }
WWWAssetsDir_ = ConfigPath("openwifi.restapi.wwwassets",""); WWWAssetsDir_ = ConfigPath("openwifi.restapi.wwwassets", "");
if(WWWAssetsDir_.empty()) if (WWWAssetsDir_.empty())
WWWAssetsDir_ = DataDir_; WWWAssetsDir_ = DataDir_;
LoadMyConfig(); LoadMyConfig();
AllowExternalMicroServices_ = ConfigGetBool("allowexternalmicroservices",true); AllowExternalMicroServices_ = ConfigGetBool("allowexternalmicroservices", true);
InitializeSubSystemServers(); InitializeSubSystemServers();
ServerApplication::initialize(self); ServerApplication::initialize(self);
DaemonPostInitialization(self); DaemonPostInitialization(self);
Types::TopicNotifyFunction F = [this](const std::string &Key,const std::string &Payload) { this->BusMessageReceived(Key, Payload); }; Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) {
this->BusMessageReceived(Key, Payload);
};
KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F); KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F);
} }
@@ -392,58 +448,64 @@ namespace OpenWifi {
Poco::Util::Option("help", "", "display help information on command line arguments") Poco::Util::Option("help", "", "display help information on command line arguments")
.required(false) .required(false)
.repeatable(false) .repeatable(false)
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp))); .callback(
Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp)));
options.addOption( options.addOption(Poco::Util::Option("file", "", "specify the configuration file")
Poco::Util::Option("file", "", "specify the configuration file") .required(false)
.required(false) .repeatable(false)
.repeatable(false) .argument("file")
.argument("file") .callback(Poco::Util::OptionCallback<MicroService>(
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleConfig))); this, &MicroService::handleConfig)));
options.addOption( options.addOption(Poco::Util::Option("debug", "", "to run in debug, set to true")
Poco::Util::Option("debug", "", "to run in debug, set to true") .required(false)
.required(false) .repeatable(false)
.repeatable(false) .callback(Poco::Util::OptionCallback<MicroService>(
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleDebug))); this, &MicroService::handleDebug)));
options.addOption( options.addOption(
Poco::Util::Option("logs", "", "specify the log directory and file (i.e. dir/file.log)") Poco::Util::Option("logs", "", "specify the log directory and file (i.e. dir/file.log)")
.required(false) .required(false)
.repeatable(false) .repeatable(false)
.argument("dir") .argument("dir")
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs))); .callback(
Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs)));
options.addOption(
Poco::Util::Option("version", "", "get the version and quit.")
.required(false)
.repeatable(false)
.callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleVersion)));
options.addOption(Poco::Util::Option("version", "", "get the version and quit.")
.required(false)
.repeatable(false)
.callback(Poco::Util::OptionCallback<MicroService>(
this, &MicroService::handleVersion)));
} }
void MicroService::handleHelp([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) { void MicroService::handleHelp([[maybe_unused]] const std::string &name,
[[maybe_unused]] const std::string &value) {
HelpRequested_ = true; HelpRequested_ = true;
displayHelp(); displayHelp();
stopOptionsProcessing(); stopOptionsProcessing();
} }
void MicroService::handleVersion([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) { void MicroService::handleVersion([[maybe_unused]] const std::string &name,
[[maybe_unused]] const std::string &value) {
HelpRequested_ = true; HelpRequested_ = true;
std::cout << Version() << std::endl; std::cout << Version() << std::endl;
stopOptionsProcessing(); stopOptionsProcessing();
} }
void MicroService::handleDebug([[maybe_unused]] const std::string &name, const std::string &value) { void MicroService::handleDebug([[maybe_unused]] const std::string &name,
if(value == "true") const std::string &value) {
DebugMode_ = true ; if (value == "true")
DebugMode_ = true;
} }
void MicroService::handleLogs([[maybe_unused]] const std::string &name, const std::string &value) { void MicroService::handleLogs([[maybe_unused]] const std::string &name,
const std::string &value) {
LogDir_ = value; LogDir_ = value;
} }
void MicroService::handleConfig([[maybe_unused]] const std::string &name, const std::string &value) { void MicroService::handleConfig([[maybe_unused]] const std::string &name,
const std::string &value) {
ConfigFileName_ = value; ConfigFileName_ = value;
} }
@@ -456,31 +518,32 @@ namespace OpenWifi {
} }
void MicroService::InitializeSubSystemServers() { void MicroService::InitializeSubSystemServers() {
for(auto i:SubSystems_) { for (auto i : SubSystems_) {
addSubsystem(i); addSubsystem(i);
} }
} }
void MicroService::StartSubSystemServers() { void MicroService::StartSubSystemServers() {
AddActivity("Starting"); AddActivity("Starting");
for(auto i:SubSystems_) { for (auto i : SubSystems_) {
i->Start(); i->Start();
} }
EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create("EventBusManager",Poco::Logger::root().getChannel(),Poco::Logger::root().getLevel())); EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create(
"EventBusManager", Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel()));
EventBusManager_->Start(); EventBusManager_->Start();
} }
void MicroService::StopSubSystemServers() { void MicroService::StopSubSystemServers() {
AddActivity("Stopping"); AddActivity("Stopping");
EventBusManager_->Stop(); EventBusManager_->Stop();
for(auto i=SubSystems_.rbegin(); i!=SubSystems_.rend(); ++i) { for (auto i = SubSystems_.rbegin(); i != SubSystems_.rend(); ++i) {
(*i)->Stop(); (*i)->Stop();
} }
} }
[[nodiscard]] std::string MicroService::CreateUUID() { [[nodiscard]] std::string MicroService::CreateUUID() {
static std::random_device rd; static std::random_device rd;
static std::mt19937_64 gen(rd()); static std::mt19937_64 gen(rd());
static std::uniform_int_distribution<> dis(0, 15); static std::uniform_int_distribution<> dis(0, 15);
static std::uniform_int_distribution<> dis2(8, 11); static std::uniform_int_distribution<> dis2(8, 11);
@@ -510,7 +573,8 @@ namespace OpenWifi {
return ss.str(); return ss.str();
} }
bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) { bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem,
const std::string &Level) {
try { try {
auto P = Poco::Logger::parseLevel(Level); auto P = Poco::Logger::parseLevel(Level);
auto Sub = Poco::toLower(SubSystem); auto Sub = Poco::toLower(SubSystem);
@@ -528,7 +592,7 @@ namespace OpenWifi {
} }
} }
} }
} catch (const Poco::Exception & E) { } catch (const Poco::Exception &E) {
std::cerr << "Exception" << std::endl; std::cerr << "Exception" << std::endl;
} }
return false; return false;
@@ -545,7 +609,7 @@ namespace OpenWifi {
Types::StringVec MicroService::GetSubSystems() const { Types::StringVec MicroService::GetSubSystems() const {
Types::StringVec Result; Types::StringVec Result;
for(auto i:SubSystems_) for (auto i : SubSystems_)
Result.push_back(Poco::toLower(i->Name())); Result.push_back(Poco::toLower(i->Name()));
return Result; return Result;
} }
@@ -553,35 +617,32 @@ namespace OpenWifi {
Types::StringPairVec MicroService::GetLogLevels() { Types::StringPairVec MicroService::GetLogLevels() {
Types::StringPairVec Result; Types::StringPairVec Result;
for(auto &i:SubSystems_) { for (auto &i : SubSystems_) {
auto P = std::make_pair( i->Name(), Utils::LogLevelToString(i->GetLoggingLevel())); auto P = std::make_pair(i->Name(), Utils::LogLevelToString(i->GetLoggingLevel()));
Result.push_back(P); Result.push_back(P);
} }
return Result; return Result;
} }
const Types::StringVec & MicroService::GetLogLevelNames() { const Types::StringVec &MicroService::GetLogLevelNames() {
static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning", "notice", "information", "debug", "trace" }; static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning",
"notice", "information", "debug", "trace"};
return LevelNames; return LevelNames;
} }
uint64_t MicroService::ConfigGetInt(const std::string &Key,uint64_t Default) { uint64_t MicroService::ConfigGetInt(const std::string &Key, uint64_t Default) {
return (uint64_t) config().getInt64(Key,Default); return (uint64_t)config().getInt64(Key, Default);
} }
uint64_t MicroService::ConfigGetInt(const std::string &Key) { uint64_t MicroService::ConfigGetInt(const std::string &Key) { return config().getInt(Key); }
return config().getInt(Key);
uint64_t MicroService::ConfigGetBool(const std::string &Key, bool Default) {
return config().getBool(Key, Default);
} }
uint64_t MicroService::ConfigGetBool(const std::string &Key,bool Default) { uint64_t MicroService::ConfigGetBool(const std::string &Key) { return config().getBool(Key); }
return config().getBool(Key,Default);
}
uint64_t MicroService::ConfigGetBool(const std::string &Key) { std::string MicroService::ConfigGetString(const std::string &Key, const std::string &Default) {
return config().getBool(Key);
}
std::string MicroService::ConfigGetString(const std::string &Key,const std::string & Default) {
return config().getString(Key, Default); return config().getString(Key, Default);
} }
@@ -589,7 +650,7 @@ namespace OpenWifi {
return config().getString(Key); return config().getString(Key);
} }
std::string MicroService::ConfigPath(const std::string &Key,const std::string & Default) { std::string MicroService::ConfigPath(const std::string &Key, const std::string &Default) {
std::string R = config().getString(Key, Default); std::string R = config().getString(Key, Default);
return Poco::Path::expand(R); return Poco::Path::expand(R);
} }
@@ -600,28 +661,30 @@ namespace OpenWifi {
} }
std::string MicroService::Encrypt(const std::string &S) { std::string MicroService::Encrypt(const std::string &S) {
if(NoBuiltInCrypto_) { if (NoBuiltInCrypto_) {
return S; return S;
} }
return Cipher_->encryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);; return Cipher_->encryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);
;
} }
std::string MicroService::Decrypt(const std::string &S) { std::string MicroService::Decrypt(const std::string &S) {
if(NoBuiltInCrypto_) { if (NoBuiltInCrypto_) {
return S; return S;
} }
return Cipher_->decryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);; return Cipher_->decryptString(S, Poco::Crypto::Cipher::Cipher::ENC_BASE64);
;
} }
std::string MicroService::MakeSystemEventMessage( const std::string & Type ) const { std::string MicroService::MakeSystemEventMessage(const std::string &Type) const {
Poco::JSON::Object Obj; Poco::JSON::Object Obj;
Obj.set(KafkaTopics::ServiceEvents::Fields::EVENT,Type); Obj.set(KafkaTopics::ServiceEvents::Fields::EVENT, Type);
Obj.set(KafkaTopics::ServiceEvents::Fields::ID,ID_); Obj.set(KafkaTopics::ServiceEvents::Fields::ID, ID_);
Obj.set(KafkaTopics::ServiceEvents::Fields::TYPE,Poco::toLower(DAEMON_APP_NAME)); Obj.set(KafkaTopics::ServiceEvents::Fields::TYPE, Poco::toLower(DAEMON_APP_NAME));
Obj.set(KafkaTopics::ServiceEvents::Fields::PUBLIC,MyPublicEndPoint_); Obj.set(KafkaTopics::ServiceEvents::Fields::PUBLIC, MyPublicEndPoint_);
Obj.set(KafkaTopics::ServiceEvents::Fields::PRIVATE,MyPrivateEndPoint_); Obj.set(KafkaTopics::ServiceEvents::Fields::PRIVATE, MyPrivateEndPoint_);
Obj.set(KafkaTopics::ServiceEvents::Fields::KEY,MyHash_); Obj.set(KafkaTopics::ServiceEvents::Fields::KEY, MyHash_);
Obj.set(KafkaTopics::ServiceEvents::Fields::VRSN,Version_); Obj.set(KafkaTopics::ServiceEvents::Fields::VRSN, Version_);
std::stringstream ResultText; std::stringstream ResultText;
Poco::JSON::Stringifier::stringify(Obj, ResultText); Poco::JSON::Stringifier::stringify(Obj, ResultText);
return ResultText.str(); return ResultText.str();
@@ -640,75 +703,73 @@ namespace OpenWifi {
void MicroService::SavePID() { void MicroService::SavePID() {
try { try {
std::ofstream O; std::ofstream O;
O.open(MicroService::instance().DataDir() + "/pidfile",std::ios::binary | std::ios::trunc); O.open(MicroService::instance().DataDir() + "/pidfile",
std::ios::binary | std::ios::trunc);
O << Poco::Process::id(); O << Poco::Process::id();
O.close(); O.close();
} catch (...) } catch (...) {
{
std::cout << "Could not save system ID" << std::endl; std::cout << "Could not save system ID" << std::endl;
} }
} }
int MicroService::main([[maybe_unused]] const ArgVec &args) { int MicroService::main([[maybe_unused]] const ArgVec &args) {
MicroServiceErrorHandler ErrorHandler(*this); MicroServiceErrorHandler ErrorHandler(*this);
Poco::ErrorHandler::set(&ErrorHandler); Poco::ErrorHandler::set(&ErrorHandler);
if (!HelpRequested_) { if (!HelpRequested_) {
SavePID(); SavePID();
Poco::Logger &logger = Poco::Logger::get(DAEMON_APP_NAME); Poco::Logger &logger = Poco::Logger::get(DAEMON_APP_NAME);
logger.notice(fmt::format("Starting {} version {}.",DAEMON_APP_NAME, Version())); logger.notice(fmt::format("Starting {} version {}.", DAEMON_APP_NAME, Version()));
if(Poco::Net::Socket::supportsIPv6()) if (Poco::Net::Socket::supportsIPv6())
poco_information(logger,"System supports IPv6."); poco_information(logger, "System supports IPv6.");
else else
poco_information(logger,"System does NOT support IPv6."); poco_information(logger, "System does NOT support IPv6.");
if (config().getBool("application.runAsDaemon", false)) { if (config().getBool("application.runAsDaemon", false)) {
poco_information(logger,"Starting as a daemon."); poco_information(logger, "Starting as a daemon.");
} }
poco_information(logger,fmt::format("System ID set to {}",ID_)); poco_information(logger, fmt::format("System ID set to {}", ID_));
StartSubSystemServers(); StartSubSystemServers();
waitForTerminationRequest(); waitForTerminationRequest();
StopSubSystemServers(); StopSubSystemServers();
logger.notice(fmt::format("Stopped {}...",DAEMON_APP_NAME)); logger.notice(fmt::format("Stopped {}...", DAEMON_APP_NAME));
} }
return Application::EXIT_OK; return Application::EXIT_OK;
} }
void MicroService::AddActivity(const std::string &Activity) { void MicroService::AddActivity(const std::string &Activity) {
if(!DataDir_.empty()) { if (!DataDir_.empty()) {
std::string ActivityFile{ DataDir_ + "/activity.log"}; std::string ActivityFile{DataDir_ + "/activity.log"};
try { try {
std::ofstream of(ActivityFile,std::ios_base::app | std::ios_base::out ); std::ofstream of(ActivityFile, std::ios_base::app | std::ios_base::out);
auto t = std::chrono::system_clock::now(); auto t = std::chrono::system_clock::now();
std::time_t now = std::chrono::system_clock::to_time_t(t); std::time_t now = std::chrono::system_clock::to_time_t(t);
of << Activity << " at " << std::ctime(&now) ; of << Activity << " at " << std::ctime(&now);
} catch (...) { } catch (...) {
} }
} }
} }
[[nodiscard]] std::string MicroService::Sign(Poco::JWT::Token &T, const std::string &Algo) { [[nodiscard]] std::string MicroService::Sign(Poco::JWT::Token &T, const std::string &Algo) {
if(NoBuiltInCrypto_) { if (NoBuiltInCrypto_) {
return T.toString(); return T.toString();
} else { } else {
return Signer_.sign(T,Algo); return Signer_.sign(T, Algo);
} }
} }
void MicroService::DeleteOverrideConfiguration() { void MicroService::DeleteOverrideConfiguration() {
Poco::File F(DataDir_ + ExtraConfigurationFilename); Poco::File F(DataDir_ + ExtraConfigurationFilename);
try { try {
if(F.exists()) if (F.exists())
F.remove(); F.remove();
} catch (...) { } catch (...) {
} }
} }
} } // namespace OpenWifi

View File

@@ -9,12 +9,11 @@
#pragma once #pragma once
#include <array> #include <array>
#include <iostream>
#include <vector>
#include <fstream>
#include <random>
#include <ctime> #include <ctime>
#include <fstream>
#include <iostream>
#include <random>
#include <vector>
// This must be defined for poco_debug and poco_trace macros to function. // This must be defined for poco_debug and poco_trace macros to function.
@@ -23,97 +22,94 @@
#endif #endif
namespace OpenWifi { namespace OpenWifi {
inline uint64_t Now() { return std::time(nullptr); }; inline uint64_t Now() { return std::time(nullptr); };
} } // namespace OpenWifi
#include "Poco/Util/Application.h" #include "Poco/AutoPtr.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Crypto/RSAKey.h"
#include "Poco/Crypto/CipherFactory.h"
#include "Poco/Crypto/Cipher.h" #include "Poco/Crypto/Cipher.h"
#include "Poco/Crypto/CipherFactory.h"
#include "Poco/Crypto/RSAKey.h"
#include "Poco/Environment.h"
#include "Poco/JSON/Object.h"
#include "Poco/JWT/Signer.h"
#include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Process.h" #include "Poco/Process.h"
#include "Poco/Util/Application.h"
#include "Poco/Util/HelpFormatter.h" #include "Poco/Util/HelpFormatter.h"
#include "Poco/JSON/Object.h" #include "Poco/Util/Option.h"
#include "Poco/AutoPtr.h" #include "Poco/Util/OptionSet.h"
#include "Poco/Util/PropertyFileConfiguration.h" #include "Poco/Util/PropertyFileConfiguration.h"
#include "Poco/JWT/Signer.h" #include "Poco/Util/ServerApplication.h"
#include "Poco/Environment.h"
#include "framework/OpenWifiTypes.h" #include "framework/OpenWifiTypes.h"
#include "framework/EventBusManager.h"
#include "framework/SubSystemServer.h"
#include "framework/ow_constants.h" #include "framework/ow_constants.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "framework/SubSystemServer.h"
#include "framework/EventBusManager.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h" #include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "cppkafka/cppkafka.h" #include "cppkafka/cppkafka.h"
#include "fmt/core.h"
#include "nlohmann/json.hpp" #include "nlohmann/json.hpp"
#include "ow_version.h" #include "ow_version.h"
#include "fmt/core.h"
#define _OWDEBUG_ std::cout<< __FILE__ <<":" << __LINE__ << std::endl; #define _OWDEBUG_ std::cout << __FILE__ << ":" << __LINE__ << std::endl;
// #define _OWDEBUG_ Logger().debug(Poco::format("%s: %lu",__FILE__,__LINE__)); // #define _OWDEBUG_ Logger().debug(Poco::format("%s: %lu",__FILE__,__LINE__));
namespace OpenWifi { namespace OpenWifi {
class MicroService : public Poco::Util::ServerApplication { class MicroService : public Poco::Util::ServerApplication {
public: public:
explicit MicroService( std::string PropFile, explicit MicroService(std::string PropFile, std::string RootEnv, std::string ConfigVar,
std::string RootEnv, std::string AppName, uint64_t BusTimer, SubSystemVec Subsystems)
std::string ConfigVar, : DAEMON_PROPERTIES_FILENAME(std::move(PropFile)),
std::string AppName, DAEMON_ROOT_ENV_VAR(std::move(RootEnv)), DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)),
uint64_t BusTimer, DAEMON_APP_NAME(std::move(AppName)), DAEMON_BUS_TIMER(BusTimer),
SubSystemVec Subsystems) : SubSystems_(std::move(Subsystems)), Logger_(Poco::Logger::get("FRAMEWORK")) {
DAEMON_PROPERTIES_FILENAME(std::move(PropFile)), instance_ = this;
DAEMON_ROOT_ENV_VAR(std::move(RootEnv)), RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count());
DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)),
DAEMON_APP_NAME(std::move(AppName)),
DAEMON_BUS_TIMER(BusTimer),
SubSystems_(std::move(Subsystems)),
Logger_(Poco::Logger::get("FRAMEWORK")) {
instance_ = this;
RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count());
// Logger_ = Poco::Logger::root().get("BASE-SVC"); // Logger_ = Poco::Logger::root().get("BASE-SVC");
} }
inline static const char * ExtraConfigurationFilename = "/configuration_override.json"; inline static const char *ExtraConfigurationFilename = "/configuration_override.json";
inline void SaveConfig() { PropConfigurationFile_->save(ConfigFileName_); } inline void SaveConfig() { PropConfigurationFile_->save(ConfigFileName_); }
inline auto UpdateConfig() { return PropConfigurationFile_; } inline auto UpdateConfig() { return PropConfigurationFile_; }
inline bool NoAPISecurity() const { return NoAPISecurity_; } inline bool NoAPISecurity() const { return NoAPISecurity_; }
inline Poco::ThreadPool & TimerPool() { return TimerPool_; } inline Poco::ThreadPool &TimerPool() { return TimerPool_; }
[[nodiscard]] std::string Version() { return Version_; } [[nodiscard]] std::string Version() { return Version_; }
[[nodiscard]] inline const std::string & DataDir() { return DataDir_; } [[nodiscard]] inline const std::string &DataDir() { return DataDir_; }
[[nodiscard]] inline const std::string & WWWAssetsDir() { return WWWAssetsDir_; } [[nodiscard]] inline const std::string &WWWAssetsDir() { return WWWAssetsDir_; }
[[nodiscard]] bool Debug() const { return DebugMode_; } [[nodiscard]] bool Debug() const { return DebugMode_; }
[[nodiscard]] uint64_t ID() const { return ID_; } [[nodiscard]] uint64_t ID() const { return ID_; }
[[nodiscard]] std::string Hash() const { return MyHash_; }; [[nodiscard]] std::string Hash() const { return MyHash_; };
[[nodiscard]] std::string ServiceType() const { return DAEMON_APP_NAME; }; [[nodiscard]] std::string ServiceType() const { return DAEMON_APP_NAME; };
[[nodiscard]] std::string PrivateEndPoint() const { return MyPrivateEndPoint_; }; [[nodiscard]] std::string PrivateEndPoint() const { return MyPrivateEndPoint_; };
[[nodiscard]] std::string PublicEndPoint() const { return MyPublicEndPoint_; }; [[nodiscard]] std::string PublicEndPoint() const { return MyPublicEndPoint_; };
[[nodiscard]] const SubSystemVec & GetFullSubSystems() { return SubSystems_; } [[nodiscard]] const SubSystemVec &GetFullSubSystems() { return SubSystems_; }
inline uint64_t DaemonBusTimer() const { return DAEMON_BUS_TIMER; }; inline uint64_t DaemonBusTimer() const { return DAEMON_BUS_TIMER; };
[[nodiscard]] const std::string & AppName() { return DAEMON_APP_NAME; } [[nodiscard]] const std::string &AppName() { return DAEMON_APP_NAME; }
static inline uint64_t GetPID() { return Poco::Process::id(); }; static inline uint64_t GetPID() { return Poco::Process::id(); };
[[nodiscard]] inline const std::string GetPublicAPIEndPoint() { return MyPublicEndPoint_ + "/api/v1"; }; [[nodiscard]] inline const std::string GetPublicAPIEndPoint() {
[[nodiscard]] inline const std::string & GetUIURI() const { return UIURI_;}; return MyPublicEndPoint_ + "/api/v1";
[[nodiscard]] inline uint64_t Random(uint64_t ceiling) { return (RandomEngine_() % ceiling); } };
[[nodiscard]] inline uint64_t Random(uint64_t min, uint64_t max) { [[nodiscard]] inline const std::string &GetUIURI() const { return UIURI_; };
return ((RandomEngine_() % (max-min)) + min); [[nodiscard]] inline uint64_t Random(uint64_t ceiling) {
return (RandomEngine_() % ceiling);
} }
virtual void GetExtraConfiguration(Poco::JSON::Object & Cfg) { [[nodiscard]] inline uint64_t Random(uint64_t min, uint64_t max) {
Cfg.set("additionalConfiguration",false); return ((RandomEngine_() % (max - min)) + min);
} }
static MicroService & instance() { return *instance_; } virtual void GetExtraConfiguration(Poco::JSON::Object &Cfg) {
Cfg.set("additionalConfiguration", false);
}
static MicroService &instance() { return *instance_; }
inline void Exit(int Reason); inline void Exit(int Reason);
void BusMessageReceived(const std::string &Key, const std::string & Payload); void BusMessageReceived(const std::string &Key, const std::string &Payload);
Types::MicroServiceMetaVec GetServices(const std::string & Type); Types::MicroServiceMetaVec GetServices(const std::string &Type);
Types::MicroServiceMetaVec GetServices(); Types::MicroServiceMetaVec GetServices();
void LoadConfigurationFile(); void LoadConfigurationFile();
void Reload(); void Reload();
@@ -136,71 +132,78 @@ namespace OpenWifi {
void Reload(const std::string &Sub); void Reload(const std::string &Sub);
Types::StringVec GetSubSystems() const; Types::StringVec GetSubSystems() const;
Types::StringPairVec GetLogLevels(); Types::StringPairVec GetLogLevels();
const Types::StringVec & GetLogLevelNames(); const Types::StringVec &GetLogLevelNames();
uint64_t ConfigGetInt(const std::string &Key,uint64_t Default); uint64_t ConfigGetInt(const std::string &Key, uint64_t Default);
uint64_t ConfigGetInt(const std::string &Key); uint64_t ConfigGetInt(const std::string &Key);
uint64_t ConfigGetBool(const std::string &Key,bool Default); uint64_t ConfigGetBool(const std::string &Key, bool Default);
uint64_t ConfigGetBool(const std::string &Key); uint64_t ConfigGetBool(const std::string &Key);
std::string ConfigGetString(const std::string &Key,const std::string & Default); std::string ConfigGetString(const std::string &Key, const std::string &Default);
std::string ConfigGetString(const std::string &Key); std::string ConfigGetString(const std::string &Key);
std::string ConfigPath(const std::string &Key,const std::string & Default); std::string ConfigPath(const std::string &Key, const std::string &Default);
std::string ConfigPath(const std::string &Key); std::string ConfigPath(const std::string &Key);
std::string Encrypt(const std::string &S); std::string Encrypt(const std::string &S);
std::string Decrypt(const std::string &S); std::string Decrypt(const std::string &S);
std::string MakeSystemEventMessage( const std::string & Type ) const; std::string MakeSystemEventMessage(const std::string &Type) const;
[[nodiscard]] bool IsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request); [[nodiscard]] bool IsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request);
static void SavePID(); static void SavePID();
int main(const ArgVec &args) override; int main(const ArgVec &args) override;
void InitializeLoggingSystem(); void InitializeLoggingSystem();
void DeleteOverrideConfiguration(); void DeleteOverrideConfiguration();
[[nodiscard]] std::string Sign(Poco::JWT::Token &T, const std::string &Algo); [[nodiscard]] std::string Sign(Poco::JWT::Token &T, const std::string &Algo);
void AddActivity(const std::string &Activity); void AddActivity(const std::string &Activity);
static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern); static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket,
static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern); const std::string &FormatterPattern);
static void SetSQLLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern); static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket,
static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern); const std::string &FormatterPattern);
static void SetFileLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern, const std::string & root_env_var); static void SetSQLLogs(bool UseAsync, bool AllowWebSocket,
inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; } const std::string &FormatterPattern);
static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket,
const std::string &FormatterPattern);
static void SetFileLogs(bool UseAsync, bool AllowWebSocket,
const std::string &FormatterPattern,
const std::string &root_env_var);
inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; }
private: private:
static MicroService * instance_; static MicroService *instance_;
bool HelpRequested_ = false; bool HelpRequested_ = false;
std::string LogDir_; std::string LogDir_;
std::string ConfigFileName_; std::string ConfigFileName_;
uint64_t ID_ = 1; uint64_t ID_ = 1;
Poco::SharedPtr<Poco::Crypto::RSAKey> AppKey_; Poco::SharedPtr<Poco::Crypto::RSAKey> AppKey_;
bool DebugMode_ = false; bool DebugMode_ = false;
std::string DataDir_; std::string DataDir_;
std::string WWWAssetsDir_; std::string WWWAssetsDir_;
Poco::Crypto::CipherFactory & CipherFactory_ = Poco::Crypto::CipherFactory::defaultFactory(); Poco::Crypto::CipherFactory &CipherFactory_ = Poco::Crypto::CipherFactory::defaultFactory();
Poco::Crypto::Cipher * Cipher_ = nullptr; Poco::Crypto::Cipher *Cipher_ = nullptr;
Types::MicroServiceMetaMap Services_; Types::MicroServiceMetaMap Services_;
std::string MyHash_; std::string MyHash_;
std::string MyPrivateEndPoint_; std::string MyPrivateEndPoint_;
std::string MyPublicEndPoint_; std::string MyPublicEndPoint_;
std::string UIURI_; std::string UIURI_;
std::string Version_{ OW_VERSION::VERSION + "("+ OW_VERSION::BUILD + ")" + " - " + OW_VERSION::HASH }; std::string Version_{OW_VERSION::VERSION + "(" + OW_VERSION::BUILD + ")" + " - " +
std::recursive_mutex InfraMutex_; OW_VERSION::HASH};
std::default_random_engine RandomEngine_; std::recursive_mutex InfraMutex_;
Poco::Util::PropertyFileConfiguration * PropConfigurationFile_ = nullptr; std::default_random_engine RandomEngine_;
std::string DAEMON_PROPERTIES_FILENAME; Poco::Util::PropertyFileConfiguration *PropConfigurationFile_ = nullptr;
std::string DAEMON_ROOT_ENV_VAR; std::string DAEMON_PROPERTIES_FILENAME;
std::string DAEMON_CONFIG_ENV_VAR; std::string DAEMON_ROOT_ENV_VAR;
std::string DAEMON_APP_NAME; std::string DAEMON_CONFIG_ENV_VAR;
uint64_t DAEMON_BUS_TIMER; std::string DAEMON_APP_NAME;
SubSystemVec SubSystems_; uint64_t DAEMON_BUS_TIMER;
bool NoAPISecurity_=false; SubSystemVec SubSystems_;
bool NoBuiltInCrypto_=false; bool NoAPISecurity_ = false;
bool AllowExternalMicroServices_=false; bool NoBuiltInCrypto_ = false;
Poco::JWT::Signer Signer_; bool AllowExternalMicroServices_ = false;
Poco::Logger &Logger_; Poco::JWT::Signer Signer_;
Poco::ThreadPool TimerPool_{"timer:pool",2,32}; Poco::Logger &Logger_;
std::unique_ptr<EventBusManager> EventBusManager_; Poco::ThreadPool TimerPool_{"timer:pool", 2, 32};
}; std::unique_ptr<EventBusManager> EventBusManager_;
};
inline MicroService * MicroService::instance_ = nullptr; inline MicroService *MicroService::instance_ = nullptr;
} } // namespace OpenWifi

View File

@@ -4,25 +4,24 @@
#pragma once #pragma once
#include "fmt/format.h"
#include "Poco/Util/Application.h"
#include "Poco/ErrorHandler.h" #include "Poco/ErrorHandler.h"
#include "Poco/JSON/JSONException.h"
#include "Poco/JSON/Template.h"
#include "Poco/Net/NetException.h" #include "Poco/Net/NetException.h"
#include "Poco/Net/SSLException.h" #include "Poco/Net/SSLException.h"
#include "Poco/JSON/Template.h"
#include "Poco/JSON/JSONException.h"
#include "Poco/Thread.h" #include "Poco/Thread.h"
#include "Poco/Util/Application.h"
#include "fmt/format.h"
namespace OpenWifi { namespace OpenWifi {
class MicroServiceErrorHandler : public Poco::ErrorHandler { class MicroServiceErrorHandler : public Poco::ErrorHandler {
public: public:
explicit MicroServiceErrorHandler(Poco::Util::Application &App) : App_(App) { explicit MicroServiceErrorHandler(Poco::Util::Application &App) : App_(App) {}
}
inline void exception(const Poco::Exception & Base) override { inline void exception(const Poco::Exception &Base) override {
try { try {
if(Poco::Thread::current()!= nullptr) { if (Poco::Thread::current() != nullptr) {
t_name = Poco::Thread::current()->getName(); t_name = Poco::Thread::current()->getName();
t_id = Poco::Thread::current()->id(); t_id = Poco::Thread::current()->id();
} else { } else {
@@ -34,179 +33,167 @@ namespace OpenWifi {
Base.rethrow(); Base.rethrow();
} catch (const Poco::Net::InvalidCertificateException &E) { } catch (const Poco::Net::InvalidCertificateException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::InvalidCertificateException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(),
t_name, t_id, E.code(), fmt::format("Poco::Net::InvalidCertificateException thr_name={} "
E.displayText(), "thr_id={} code={} text={} msg={} what={}",
E.message(), t_name, t_id, E.code(), E.displayText(), E.message(),
E.what())); E.what()));
} catch (const Poco::Net::InvalidSocketException &E) { } catch (const Poco::Net::InvalidSocketException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::InvalidSocketException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(),
t_name, t_id, E.code(), fmt::format("Poco::Net::InvalidSocketException thr_name={} thr_id={} "
E.displayText(), "code={} text={} msg={} what={}",
E.message(), t_name, t_id, E.code(), E.displayText(), E.message(),
E.what())); E.what()));
} catch (const Poco::Net::WebSocketException &E) { } catch (const Poco::Net::WebSocketException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::Net::ConnectionResetException &E) { } catch (const Poco::Net::ConnectionResetException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::ConnectionResetException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(),
t_name, t_id, E.code(), fmt::format("Poco::Net::ConnectionResetException thr_name={} thr_id={} "
E.displayText(), "code={} text={} msg={} what={}",
E.message(), t_name, t_id, E.code(), E.displayText(), E.message(),
E.what())); E.what()));
} catch (const Poco::Net::CertificateValidationException &E) { } catch (const Poco::Net::CertificateValidationException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::CertificateValidationException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(),
t_name, t_id, E.code(), fmt::format("Poco::Net::CertificateValidationException thr_name={} "
E.displayText(), "thr_id={} code={} text={} msg={} what={}",
E.message(), t_name, t_id, E.code(), E.displayText(), E.message(),
E.what())); E.what()));
} catch (const Poco::Net::SSLConnectionUnexpectedlyClosedException &E) { } catch (const Poco::Net::SSLConnectionUnexpectedlyClosedException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(),
t_name, t_id, E.code(), fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException "
E.displayText(), "thr_name={} thr_id={} code={} text={} msg={} what={}",
E.message(), t_name, t_id, E.code(), E.displayText(), E.message(),
E.what())); E.what()));
} catch (const Poco::Net::SSLContextException &E) { } catch (const Poco::Net::SSLContextException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::Net::SSLException &E) { } catch (const Poco::Net::SSLException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::SSLException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::Net::SSLException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::Net::InvalidAddressException &E) { } catch (const Poco::Net::InvalidAddressException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::InvalidAddressException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(),
t_name, t_id, E.code(), fmt::format("Poco::Net::InvalidAddressException thr_name={} thr_id={} "
E.displayText(), "code={} text={} msg={} what={}",
E.message(), t_name, t_id, E.code(), E.displayText(), E.message(),
E.what())); E.what()));
} catch (const Poco::Net::NetException &E) { } catch (const Poco::Net::NetException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::IOException &E) { } catch (const Poco::IOException &E) {
poco_error(App_.logger(), fmt::format("Poco::IOException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(
t_name, t_id, E.code(), App_.logger(),
E.displayText(), fmt::format(
E.message(), "Poco::IOException thr_name={} thr_id={} code={} text={} msg={} what={}",
E.what())); t_name, t_id, E.code(), E.displayText(), E.message(), E.what()));
} catch (const Poco::TimeoutException &E) { } catch (const Poco::TimeoutException &E) {
poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::NoThreadAvailableException &E) { } catch (const Poco::NoThreadAvailableException &E) {
poco_error(App_.logger(), fmt::format("Poco::NoThreadAvailableException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(),
t_name, t_id, E.code(), fmt::format("Poco::NoThreadAvailableException thr_name={} thr_id={} "
E.displayText(), "code={} text={} msg={} what={}",
E.message(), t_name, t_id, E.code(), E.displayText(), E.message(),
E.what())); E.what()));
} catch (const Poco::OutOfMemoryException &E) { } catch (const Poco::OutOfMemoryException &E) {
poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::BadCastException &E) { } catch (const Poco::BadCastException &E) {
poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::DataException &E) { } catch (const Poco::DataException &E) {
poco_error(App_.logger(), fmt::format("Poco::DataException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(
t_name, t_id, E.code(), App_.logger(),
E.displayText(), fmt::format(
E.message(), "Poco::DataException thr_name={} thr_id={} code={} text={} msg={} what={}",
E.what())); t_name, t_id, E.code(), E.displayText(), E.message(), E.what()));
} catch (const Poco::PoolOverflowException &E) { } catch (const Poco::PoolOverflowException &E) {
poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::SystemException &E) { } catch (const Poco::SystemException &E) {
poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} "
t_name, t_id, E.code(), "code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::RuntimeException &E) { } catch (const Poco::RuntimeException &E) {
poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::JSON::JSONTemplateException &E) { } catch (const Poco::JSON::JSONTemplateException &E) {
poco_error(App_.logger(), fmt::format("Poco::JSON::JSONTemplateException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(),
t_name, t_id, E.code(), fmt::format("Poco::JSON::JSONTemplateException thr_name={} thr_id={} "
E.displayText(), "code={} text={} msg={} what={}",
E.message(), t_name, t_id, E.code(), E.displayText(), E.message(),
E.what())); E.what()));
} catch (const Poco::JSON::JSONException &E) { } catch (const Poco::JSON::JSONException &E) {
poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::ApplicationException &E) { } catch (const Poco::ApplicationException &E) {
poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} "
t_name, t_id, E.code(), "thr_id={} code={} text={} msg={} what={}",
E.displayText(), t_name, t_id, E.code(), E.displayText(),
E.message(), E.message(), E.what()));
E.what()));
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
poco_error(App_.logger(), fmt::format("Poco::Exception thr_name={} thr_id={} code={} text={} msg={} what={}", poco_error(
t_name, t_id, E.code(), App_.logger(),
E.displayText(), fmt::format(
E.message(), "Poco::Exception thr_name={} thr_id={} code={} text={} msg={} what={}",
E.what())); t_name, t_id, E.code(), E.displayText(), E.message(), E.what()));
} catch (...) { } catch (...) {
poco_error(App_.logger(), fmt::format("Poco:Generic thr_name={}",t_name, t_id)); poco_error(App_.logger(), fmt::format("Poco:Generic thr_name={}", t_name, t_id));
} }
} }
inline void exception(const std::exception & E) override { inline void exception(const std::exception &E) override {
if(Poco::Thread::current()!= nullptr) { if (Poco::Thread::current() != nullptr) {
t_name = Poco::Thread::current()->getName(); t_name = Poco::Thread::current()->getName();
t_id = Poco::Thread::current()->id(); t_id = Poco::Thread::current()->id();
} else { } else {
t_name = "startup_code"; t_name = "startup_code";
t_id = 0; t_id = 0;
} }
poco_warning(App_.logger(), fmt::format("std::exception in {}: {} thr_id={}", poco_warning(App_.logger(),
t_name,E.what(), fmt::format("std::exception in {}: {} thr_id={}", t_name, E.what(), t_id));
t_id));
} }
inline void exception() override { inline void exception() override {
if(Poco::Thread::current()!= nullptr) { if (Poco::Thread::current() != nullptr) {
t_name = Poco::Thread::current()->getName(); t_name = Poco::Thread::current()->getName();
t_id = Poco::Thread::current()->id(); t_id = Poco::Thread::current()->id();
} else { } else {
t_name = "startup_code"; t_name = "startup_code";
t_id = 0; t_id = 0;
} }
poco_warning(App_.logger(), fmt::format("generic exception in {} thr_id={}", poco_warning(App_.logger(),
t_name, t_id)); fmt::format("generic exception in {} thr_id={}", t_name, t_id));
} }
private: private:
Poco::Util::Application &App_; Poco::Util::Application &App_;
std::string t_name; std::string t_name;
int t_id=0; int t_id = 0;
}; };
} } // namespace OpenWifi

View File

@@ -4,8 +4,8 @@
#pragma once #pragma once
#include <string>
#include <map> #include <map>
#include <string>
#include "Poco/BasicEvent.h" #include "Poco/BasicEvent.h"
#include "Poco/ExpireLRUCache.h" #include "Poco/ExpireLRUCache.h"
@@ -13,46 +13,40 @@
namespace OpenWifi { namespace OpenWifi {
class ConfigurationEntry { class ConfigurationEntry {
public: public:
template <typename T> explicit ConfigurationEntry(T def) : template <typename T> explicit ConfigurationEntry(T def) : Default_(def), Current_(def) {}
Default_(def),
Current_(def){ template <typename T>
explicit ConfigurationEntry(T def, T cur, const std::string &Hint = "")
: Default_(def), Current_(cur), Hint_(Hint) {}
inline ConfigurationEntry() = default;
inline ~ConfigurationEntry() = default;
template <typename T> explicit operator T() const { return std::get<T>(Current_); }
inline ConfigurationEntry &operator=(const char *v) {
Current_ = std::string(v);
return *this;
}
template <typename T> ConfigurationEntry &operator=(T v) {
Current_ = (T)v;
return *this;
} }
template <typename T> explicit ConfigurationEntry(T def, T cur, const std::string &Hint="") : void reset() { Current_ = Default_; }
Default_(def),
Current_(cur),
Hint_(Hint){
}
inline ConfigurationEntry()=default;
inline ~ConfigurationEntry()=default;
template <typename T> explicit operator T () const { return std::get<T>(Current_); }
inline ConfigurationEntry & operator=(const char *v) { Current_ = std::string(v); return *this;}
template <typename T> ConfigurationEntry & operator=(T v) { Current_ = (T) v; return *this;}
void reset() {
Current_ = Default_;
}
private: private:
std::variant<bool,uint64_t,std::string> Default_, Current_; std::variant<bool, uint64_t, std::string> Default_, Current_;
std::string Hint_; std::string Hint_;
}; };
inline std::string to_string(const ConfigurationEntry &v) { return (std::string) v; } inline std::string to_string(const ConfigurationEntry &v) { return (std::string)v; }
typedef std::map<std::string,ConfigurationEntry> ConfigurationMap_t; typedef std::map<std::string, ConfigurationEntry> ConfigurationMap_t;
template <typename T> class FIFO { template <typename T> class FIFO {
public: public:
explicit FIFO(uint32_t Size) : explicit FIFO(uint32_t Size) : Size_(Size) { Buffer_ = new T[Size_]; }
Size_(Size) {
Buffer_ = new T [Size_];
}
~FIFO() { ~FIFO() { delete[] Buffer_; }
delete [] Buffer_;
}
mutable Poco::BasicEvent<bool> Writable_; mutable Poco::BasicEvent<bool> Writable_;
mutable Poco::BasicEvent<bool> Readable_; mutable Poco::BasicEvent<bool> Readable_;
@@ -84,7 +78,7 @@ namespace OpenWifi {
Write_ = 0; Write_ = 0;
} }
Used_++; Used_++;
MaxEverUsed_ = std::max(Used_,MaxEverUsed_); MaxEverUsed_ = std::max(Used_, MaxEverUsed_);
} }
bool flag = true; bool flag = true;
Readable_.notify(this, flag); Readable_.notify(this, flag);
@@ -93,40 +87,32 @@ namespace OpenWifi {
inline bool isFull() { inline bool isFull() {
std::lock_guard M(Mutex_); std::lock_guard M(Mutex_);
return Used_==Buffer_->capacity(); return Used_ == Buffer_->capacity();
} }
inline auto MaxEverUser() const { return MaxEverUsed_; } inline auto MaxEverUser() const { return MaxEverUsed_; }
private: private:
std::recursive_mutex Mutex_; std::recursive_mutex Mutex_;
uint32_t Size_=0; uint32_t Size_ = 0;
uint32_t Read_=0; uint32_t Read_ = 0;
uint32_t Write_=0; uint32_t Write_ = 0;
uint32_t Used_=0; uint32_t Used_ = 0;
uint32_t MaxEverUsed_=0; uint32_t MaxEverUsed_ = 0;
T * Buffer_ = nullptr; T *Buffer_ = nullptr;
}; };
template <class Record, typename KeyType = std::string, int Size=256, int Expiry=60000> class RecordCache { template <class Record, typename KeyType = std::string, int Size = 256, int Expiry = 60000>
class RecordCache {
public: public:
explicit RecordCache( KeyType Record::* Q) : explicit RecordCache(KeyType Record::*Q) : MemberOffset(Q){};
MemberOffset(Q){ inline auto update(const Record &R) { return Cache_.update(R.*MemberOffset, R); }
}; inline auto get(const KeyType &K) { return Cache_.get(K); }
inline auto update(const Record &R) { inline auto remove(const KeyType &K) { return Cache_.remove(K); }
return Cache_.update(R.*MemberOffset, R); inline auto remove(const Record &R) { return Cache_.remove(R.*MemberOffset); }
}
inline auto get(const KeyType &K) {
return Cache_.get(K);
}
inline auto remove(const KeyType &K) {
return Cache_.remove(K);
}
inline auto remove(const Record &R) {
return Cache_.remove(R.*MemberOffset);
}
private: private:
KeyType Record::* MemberOffset; KeyType Record::*MemberOffset;
Poco::ExpireLRUCache<KeyType,Record> Cache_{Size,Expiry}; Poco::ExpireLRUCache<KeyType, Record> Cache_{Size, Expiry};
}; };
} } // namespace OpenWifi

View File

@@ -2,125 +2,125 @@
// Created by stephane bourque on 2022-10-25. // Created by stephane bourque on 2022-10-25.
// //
#include "framework/MicroService.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
#include "framework/MicroService.h"
namespace OpenWifi { namespace OpenWifi {
const std::string &MicroServiceDataDirectory() { return MicroService::instance().DataDir(); } const std::string &MicroServiceDataDirectory() { return MicroService::instance().DataDir(); }
Types::MicroServiceMetaVec MicroServiceGetServices(const std::string &Type) { Types::MicroServiceMetaVec MicroServiceGetServices(const std::string &Type) {
return MicroService::instance().GetServices(Type); return MicroService::instance().GetServices(Type);
} }
Types::MicroServiceMetaVec MicroServiceGetServices() { Types::MicroServiceMetaVec MicroServiceGetServices() {
return MicroService::instance().GetServices(); return MicroService::instance().GetServices();
} }
std::string MicroServicePublicEndPoint() { return MicroService::instance().PublicEndPoint(); } std::string MicroServicePublicEndPoint() { return MicroService::instance().PublicEndPoint(); }
std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue) { std::string MicroServiceConfigGetString(const std::string &Key,
return MicroService::instance().ConfigGetString(Key, DefaultValue); const std::string &DefaultValue) {
} return MicroService::instance().ConfigGetString(Key, DefaultValue);
}
bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue) { bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue) {
return MicroService::instance().ConfigGetBool(Key, DefaultValue); return MicroService::instance().ConfigGetBool(Key, DefaultValue);
} }
std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue) { std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue) {
return MicroService::instance().ConfigGetInt(Key, DefaultValue); return MicroService::instance().ConfigGetInt(Key, DefaultValue);
} }
std::string MicroServicePrivateEndPoint() { return MicroService::instance().PrivateEndPoint(); } std::string MicroServicePrivateEndPoint() { return MicroService::instance().PrivateEndPoint(); }
std::uint64_t MicroServiceID() { return MicroService::instance().ID(); } std::uint64_t MicroServiceID() { return MicroService::instance().ID(); }
bool MicroServiceIsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request) { bool MicroServiceIsValidAPIKEY(const Poco::Net::HTTPServerRequest &Request) {
return MicroService::instance().IsValidAPIKEY(Request); return MicroService::instance().IsValidAPIKEY(Request);
} }
bool MicroServiceNoAPISecurity() { return MicroService::instance().NoAPISecurity(); } bool MicroServiceNoAPISecurity() { return MicroService::instance().NoAPISecurity(); }
void MicroServiceLoadConfigurationFile() { MicroService::instance().LoadConfigurationFile(); } void MicroServiceLoadConfigurationFile() { MicroService::instance().LoadConfigurationFile(); }
void MicroServiceReload() { MicroService::instance().Reload(); } void MicroServiceReload() { MicroService::instance().Reload(); }
void MicroServiceReload(const std::string &Type) { MicroService::instance().Reload(Type); } void MicroServiceReload(const std::string &Type) { MicroService::instance().Reload(Type); }
const Types::StringVec MicroServiceGetLogLevelNames() { const Types::StringVec MicroServiceGetLogLevelNames() {
return MicroService::instance().GetLogLevelNames(); return MicroService::instance().GetLogLevelNames();
} }
const Types::StringVec MicroServiceGetSubSystems() { const Types::StringVec MicroServiceGetSubSystems() {
return MicroService::instance().GetSubSystems(); return MicroService::instance().GetSubSystems();
} }
Types::StringPairVec MicroServiceGetLogLevels() { return MicroService::instance().GetLogLevels(); } Types::StringPairVec MicroServiceGetLogLevels() {
return MicroService::instance().GetLogLevels();
}
bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) { bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) {
return MicroService::instance().SetSubsystemLogLevel(SubSystem, Level); return MicroService::instance().SetSubsystemLogLevel(SubSystem, Level);
} }
void MicroServiceGetExtraConfiguration(Poco::JSON::Object &Answer) { void MicroServiceGetExtraConfiguration(Poco::JSON::Object &Answer) {
MicroService::instance().GetExtraConfiguration(Answer); MicroService::instance().GetExtraConfiguration(Answer);
} }
std::string MicroServiceVersion() { return MicroService::instance().Version(); } std::string MicroServiceVersion() { return MicroService::instance().Version(); }
std::uint64_t MicroServiceUptimeTotalSeconds() { std::uint64_t MicroServiceUptimeTotalSeconds() {
return MicroService::instance().uptime().totalSeconds(); return MicroService::instance().uptime().totalSeconds();
} }
std::uint64_t MicroServiceStartTimeEpochTime() { std::uint64_t MicroServiceStartTimeEpochTime() {
return MicroService::instance().startTime().epochTime(); return MicroService::instance().startTime().epochTime();
} }
std::string MicroServiceGetUIURI() { return MicroService::instance().GetUIURI(); } std::string MicroServiceGetUIURI() { return MicroService::instance().GetUIURI(); }
const SubSystemVec MicroServiceGetFullSubSystems() { const SubSystemVec MicroServiceGetFullSubSystems() {
return MicroService::instance().GetFullSubSystems(); return MicroService::instance().GetFullSubSystems();
} }
std::string MicroServiceCreateUUID() { return MicroService::CreateUUID(); } std::string MicroServiceCreateUUID() { return MicroService::CreateUUID(); }
std::uint64_t MicroServiceDaemonBusTimer() { return MicroService::instance().DaemonBusTimer(); } std::uint64_t MicroServiceDaemonBusTimer() { return MicroService::instance().DaemonBusTimer(); }
std::string MicroServiceMakeSystemEventMessage(const std::string &Type) { std::string MicroServiceMakeSystemEventMessage(const std::string &Type) {
return MicroService::instance().MakeSystemEventMessage(Type); return MicroService::instance().MakeSystemEventMessage(Type);
} }
Poco::ThreadPool &MicroServiceTimerPool() { return MicroService::instance().TimerPool(); } Poco::ThreadPool &MicroServiceTimerPool() { return MicroService::instance().TimerPool(); }
std::string MicroServiceConfigPath(const std::string &Key, std::string MicroServiceConfigPath(const std::string &Key, const std::string &DefaultValue) {
const std::string &DefaultValue) { return MicroService::instance().ConfigPath(Key, DefaultValue);
return MicroService::instance().ConfigPath(Key, DefaultValue); }
}
std::string MicroServiceWWWAssetsDir() { std::string MicroServiceWWWAssetsDir() { return MicroService::instance().WWWAssetsDir(); }
return MicroService::instance().WWWAssetsDir();
}
std::uint64_t MicroServiceRandom(std::uint64_t Start,std::uint64_t End) { std::uint64_t MicroServiceRandom(std::uint64_t Start, std::uint64_t End) {
return MicroService::instance().Random(Start, End); return MicroService::instance().Random(Start, End);
} }
std::uint64_t MicroServiceRandom(std::uint64_t Range) { std::uint64_t MicroServiceRandom(std::uint64_t Range) {
return MicroService::instance().Random(Range); return MicroService::instance().Random(Range);
} }
std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo) { std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo) {
return MicroService::instance().Sign(T, Algo); return MicroService::instance().Sign(T, Algo);
} }
std::string MicroServiceGetPublicAPIEndPoint() { std::string MicroServiceGetPublicAPIEndPoint() {
return MicroService::instance().GetPublicAPIEndPoint(); return MicroService::instance().GetPublicAPIEndPoint();
} }
void MicroServiceDeleteOverrideConfiguration() { void MicroServiceDeleteOverrideConfiguration() {
return MicroService::instance().DeleteOverrideConfiguration(); return MicroService::instance().DeleteOverrideConfiguration();
} }
bool AllowExternalMicroServices() { bool AllowExternalMicroServices() {
return MicroService::instance().AllowExternalMicroServices(); return MicroService::instance().AllowExternalMicroServices();
} }
} } // namespace OpenWifi

View File

@@ -8,20 +8,20 @@
#include "framework/OpenWifiTypes.h" #include "framework/OpenWifiTypes.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/JSON/Object.h" #include "Poco/JSON/Object.h"
#include "Poco/ThreadPool.h"
#include "Poco/JWT/Token.h" #include "Poco/JWT/Token.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/ThreadPool.h"
namespace OpenWifi { namespace OpenWifi {
class SubSystemServer; class SubSystemServer;
using SubSystemVec=std::vector<SubSystemServer *>; using SubSystemVec = std::vector<SubSystemServer *>;
const std::string & MicroServiceDataDirectory(); const std::string &MicroServiceDataDirectory();
Types::MicroServiceMetaVec MicroServiceGetServices(const std::string & Type); Types::MicroServiceMetaVec MicroServiceGetServices(const std::string &Type);
Types::MicroServiceMetaVec MicroServiceGetServices(); Types::MicroServiceMetaVec MicroServiceGetServices();
std::string MicroServicePublicEndPoint(); std::string MicroServicePublicEndPoint();
std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue); std::string MicroServiceConfigGetString(const std::string &Key,
const std::string &DefaultValue);
bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue); bool MicroServiceConfigGetBool(const std::string &Key, bool DefaultValue);
std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue); std::uint64_t MicroServiceConfigGetInt(const std::string &Key, std::uint64_t DefaultValue);
std::string MicroServicePrivateEndPoint(); std::string MicroServicePrivateEndPoint();
@@ -43,15 +43,14 @@ namespace OpenWifi {
const SubSystemVec MicroServiceGetFullSubSystems(); const SubSystemVec MicroServiceGetFullSubSystems();
std::string MicroServiceCreateUUID(); std::string MicroServiceCreateUUID();
std::uint64_t MicroServiceDaemonBusTimer(); std::uint64_t MicroServiceDaemonBusTimer();
std::string MicroServiceMakeSystemEventMessage( const std::string & Type ); std::string MicroServiceMakeSystemEventMessage(const std::string &Type);
Poco::ThreadPool & MicroServiceTimerPool(); Poco::ThreadPool &MicroServiceTimerPool();
std::string MicroServiceConfigPath(const std::string &Key, std::string MicroServiceConfigPath(const std::string &Key, const std::string &DefaultValue);
const std::string &DefaultValue); std::string MicroServiceWWWAssetsDir();
std::string MicroServiceWWWAssetsDir(); std::uint64_t MicroServiceRandom(std::uint64_t Start, std::uint64_t End);
std::uint64_t MicroServiceRandom(std::uint64_t Start,std::uint64_t End); std::uint64_t MicroServiceRandom(std::uint64_t Range);
std::uint64_t MicroServiceRandom(std::uint64_t Range); std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo);
std::string MicroServiceSign(Poco::JWT::Token &T, const std::string &Algo); std::string MicroServiceGetPublicAPIEndPoint();
std::string MicroServiceGetPublicAPIEndPoint();
void MicroServiceDeleteOverrideConfiguration(); void MicroServiceDeleteOverrideConfiguration();
bool AllowExternalMicroServices(); bool AllowExternalMicroServices();
} } // namespace OpenWifi

View File

@@ -10,13 +10,13 @@ namespace OpenWifi {
static const std::string uSERVICE_SECURITY{"owsec"}; static const std::string uSERVICE_SECURITY{"owsec"};
static const std::string uSERVICE_GATEWAY{"owgw"}; static const std::string uSERVICE_GATEWAY{"owgw"};
static const std::string uSERVICE_FIRMWARE{ "owfms"}; static const std::string uSERVICE_FIRMWARE{"owfms"};
static const std::string uSERVICE_TOPOLOGY{ "owtopo"}; static const std::string uSERVICE_TOPOLOGY{"owtopo"};
static const std::string uSERVICE_PROVISIONING{ "owprov"}; static const std::string uSERVICE_PROVISIONING{"owprov"};
static const std::string uSERVICE_OWLS{ "owls"}; static const std::string uSERVICE_OWLS{"owls"};
static const std::string uSERVICE_SUBCRIBER{ "owsub"}; static const std::string uSERVICE_SUBCRIBER{"owsub"};
static const std::string uSERVICE_INSTALLER{ "owinst"}; static const std::string uSERVICE_INSTALLER{"owinst"};
static const std::string uSERVICE_ANALYTICS{ "owanalytics"}; static const std::string uSERVICE_ANALYTICS{"owanalytics"};
static const std::string uSERVICE_OWRRM{ "owrrm"}; static const std::string uSERVICE_OWRRM{"owrrm"};
} } // namespace OpenWifi

View File

@@ -4,286 +4,281 @@
#include "OpenAPIRequests.h" #include "OpenAPIRequests.h"
#include "Poco/JSON/Parser.h"
#include "Poco/Logger.h" #include "Poco/Logger.h"
#include "Poco/URI.h"
#include "Poco/Net/HTTPRequest.h" #include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPSClientSession.h" #include "Poco/Net/HTTPSClientSession.h"
#include "Poco/JSON/Parser.h" #include "Poco/URI.h"
#include "fmt/format.h" #include "fmt/format.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
namespace OpenWifi { namespace OpenWifi {
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) { Poco::Net::HTTPServerResponse::HTTPStatus
try { OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_); auto Services = MicroServiceGetServices(Type_);
for(auto const &Svc:Services) { for (auto const &Svc : Services) {
Poco::URI URI(Svc.PrivateEndPoint); Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https"); auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_); URI.setPath(EndPoint_);
for (const auto &qp : QueryData_) for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second); URI.addQueryParameter(qp.first, qp.second);
std::string Path(URI.getPathAndQuery()); std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, Path,
Path, Poco::Net::HTTPMessage::HTTP_1_1);
Poco::Net::HTTPMessage::HTTP_1_1);
poco_debug(Poco::Logger::get("REST-CALLER-GET"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) ); poco_debug(Poco::Logger::get("REST-CALLER-GET"),
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
if(BearerToken.empty()) { if (BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey); Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if(Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
}
}
}
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-GET").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
for(auto const &Svc:Services) {
Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-PUT"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT,
Path,
Poco::Net::HTTPMessage::HTTP_1_1);
std::ostringstream obody;
Poco::JSON::Stringifier::stringify(Body_,obody);
Request.setContentType("application/json");
Request.setContentLength(obody.str().size());
if(BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if(Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else { } else {
Poco::JSON::Parser P; // Authorization: Bearer ${token}
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>(); Request.add("Authorization", "Bearer " + BearerToken);
} }
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request); if (Secure) {
os << obody.str(); Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Poco::Net::HTTPResponse Response; Session.sendRequest(Request);
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) { Poco::Net::HTTPResponse Response;
Poco::JSON::Parser P; std::istream &is = Session.receiveResponse(Response);
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>(); if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} else { } else {
Poco::JSON::Parser P; Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>(); Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} }
return Response.getStatus();
} }
} catch (const Poco::Exception &E) {
Poco::Logger::get("REST-CALLER-GET").log(E);
} }
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
} }
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-PUT").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) { Poco::Net::HTTPServerResponse::HTTPStatus
try { OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) {
auto Services = MicroServiceGetServices(Type_); try {
auto Services = MicroServiceGetServices(Type_);
for (auto const &Svc : Services) {
Poco::URI URI(Svc.PrivateEndPoint);
for(auto const &Svc:Services) { auto Secure = (URI.getScheme() == "https");
Poco::URI URI(Svc.PrivateEndPoint);
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
auto Secure = (URI.getScheme() == "https"); poco_debug(Poco::Logger::get("REST-CALLER-PUT"),
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
URI.setPath(EndPoint_); std::string Path(URI.getPathAndQuery());
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-POST"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) ); Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT, Path,
Poco::Net::HTTPMessage::HTTP_1_1);
std::ostringstream obody;
Poco::JSON::Stringifier::stringify(Body_, obody);
std::string Path(URI.getPathAndQuery()); Request.setContentType("application/json");
Request.setContentLength(obody.str().size());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST, if (BearerToken.empty()) {
Path, Request.add("X-API-KEY", Svc.AccessKey);
Poco::Net::HTTPMessage::HTTP_1_1); Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
std::ostringstream obody;
Poco::JSON::Stringifier::stringify(Body_,obody);
Request.setContentType("application/json");
Request.setContentLength(obody.str().size());
if(BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if(Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else { } else {
Poco::JSON::Parser P; // Authorization: Bearer ${token}
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>(); Request.add("Authorization", "Bearer " + BearerToken);
} }
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response; if (Secure) {
std::istream &is = Session.receiveResponse(Response); Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) { Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>(); std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} else { } else {
Poco::JSON::Parser P; Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>(); Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} }
return Response.getStatus();
} }
} catch (const Poco::Exception &E) {
Poco::Logger::get("REST-CALLER-PUT").log(E);
} }
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
} }
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-POST").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestDelete::Do(const std::string & BearerToken) { Poco::Net::HTTPServerResponse::HTTPStatus
try { OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject,
auto Services = MicroServiceGetServices(Type_); const std::string &BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
for(auto const &Svc:Services) { for (auto const &Svc : Services) {
Poco::URI URI(Svc.PrivateEndPoint); Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https"); auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_); URI.setPath(EndPoint_);
for (const auto &qp : QueryData_) for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second); URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-DELETE"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) ); poco_debug(Poco::Logger::get("REST-CALLER-POST"),
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
std::string Path(URI.getPathAndQuery()); std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_DELETE, Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST, Path,
Path, Poco::Net::HTTPMessage::HTTP_1_1);
Poco::Net::HTTPMessage::HTTP_1_1); std::ostringstream obody;
if(BearerToken.empty()) { Poco::JSON::Stringifier::stringify(Body_, obody);
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint()); Request.setContentType("application/json");
} else { Request.setContentLength(obody.str().size());
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken); if (BearerToken.empty()) {
} Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
if(Secure) { } else {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort()); // Authorization: Bearer ${token}
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); Request.add("Authorization", "Bearer " + BearerToken);
Session.sendRequest(Request); }
Poco::Net::HTTPResponse Response;
Session.receiveResponse(Response); if (Secure) {
return Response.getStatus(); Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
} else { Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort()); std::ostream &os = Session.sendRequest(Request);
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000)); os << obody.str();
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response; Poco::Net::HTTPResponse Response;
Session.receiveResponse(Response); std::istream &is = Session.receiveResponse(Response);
return Response.getStatus(); if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
std::ostream &os = Session.sendRequest(Request);
os << obody.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
} else {
Poco::JSON::Parser P;
ResponseObject = P.parse(is).extract<Poco::JSON::Object::Ptr>();
}
return Response.getStatus();
}
} }
} catch (const Poco::Exception &E) {
Poco::Logger::get("REST-CALLER-POST").log(E);
} }
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
} }
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-DELETE").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
Poco::Net::HTTPServerResponse::HTTPStatus
OpenAPIRequestDelete::Do(const std::string &BearerToken) {
try {
auto Services = MicroServiceGetServices(Type_);
for (auto const &Svc : Services) {
Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_);
for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-DELETE"),
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_DELETE, Path,
Poco::Net::HTTPMessage::HTTP_1_1);
if (BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey);
Request.add("X-INTERNAL-NAME", MicroServicePublicEndPoint());
} else {
// Authorization: Bearer ${token}
Request.add("Authorization", "Bearer " + BearerToken);
}
if (Secure) {
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
Session.receiveResponse(Response);
return Response.getStatus();
} else {
Poco::Net::HTTPClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(msTimeout_ / 1000, msTimeout_ % 1000));
Session.sendRequest(Request);
Poco::Net::HTTPResponse Response;
Session.receiveResponse(Response);
return Response.getStatus();
}
}
} catch (const Poco::Exception &E) {
Poco::Logger::get("REST-CALLER-DELETE").log(E);
}
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
}
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -15,96 +15,79 @@ namespace OpenWifi {
class OpenAPIRequestGet { class OpenAPIRequestGet {
public: public:
explicit OpenAPIRequestGet( const std::string & Type, explicit OpenAPIRequestGet(const std::string &Type, const std::string &EndPoint,
const std::string & EndPoint, const Types::StringPairVec &QueryData, uint64_t msTimeout,
const Types::StringPairVec & QueryData, const std::string &LoggingStr = "")
uint64_t msTimeout, : Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
const std::string &LoggingStr=""): LoggingStr_(LoggingStr){};
Type_(Type), Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject,
EndPoint_(EndPoint), const std::string &BearerToken = "");
QueryData_(QueryData),
msTimeout_(msTimeout),
LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
private: private:
std::string Type_; std::string Type_;
std::string EndPoint_; std::string EndPoint_;
Types::StringPairVec QueryData_; Types::StringPairVec QueryData_;
uint64_t msTimeout_; uint64_t msTimeout_;
std::string LoggingStr_; std::string LoggingStr_;
}; };
class OpenAPIRequestPut { class OpenAPIRequestPut {
public: public:
explicit OpenAPIRequestPut( const std::string & Type, explicit OpenAPIRequestPut(const std::string &Type, const std::string &EndPoint,
const std::string & EndPoint, const Types::StringPairVec &QueryData,
const Types::StringPairVec & QueryData, const Poco::JSON::Object &Body, uint64_t msTimeout,
const Poco::JSON::Object & Body, const std::string &LoggingStr = "")
uint64_t msTimeout, : Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
const std::string &LoggingStr=""): Body_(Body), LoggingStr_(LoggingStr){};
Type_(Type),
EndPoint_(EndPoint),
QueryData_(QueryData),
msTimeout_(msTimeout),
Body_(Body),
LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = ""); Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject,
const std::string &BearerToken = "");
private: private:
std::string Type_; std::string Type_;
std::string EndPoint_; std::string EndPoint_;
Types::StringPairVec QueryData_; Types::StringPairVec QueryData_;
uint64_t msTimeout_; uint64_t msTimeout_;
Poco::JSON::Object Body_; Poco::JSON::Object Body_;
std::string LoggingStr_; std::string LoggingStr_;
}; };
class OpenAPIRequestPost { class OpenAPIRequestPost {
public: public:
explicit OpenAPIRequestPost( const std::string & Type, explicit OpenAPIRequestPost(const std::string &Type, const std::string &EndPoint,
const std::string & EndPoint, const Types::StringPairVec &QueryData,
const Types::StringPairVec & QueryData, const Poco::JSON::Object &Body, uint64_t msTimeout,
const Poco::JSON::Object & Body, const std::string &LoggingStr = "")
uint64_t msTimeout, : Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
const std::string &LoggingStr=""): Body_(Body), LoggingStr_(LoggingStr){};
Type_(Type), Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject,
EndPoint_(EndPoint), const std::string &BearerToken = "");
QueryData_(QueryData),
msTimeout_(msTimeout),
Body_(Body),
LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
private: private:
std::string Type_; std::string Type_;
std::string EndPoint_; std::string EndPoint_;
Types::StringPairVec QueryData_; Types::StringPairVec QueryData_;
uint64_t msTimeout_; uint64_t msTimeout_;
Poco::JSON::Object Body_; Poco::JSON::Object Body_;
std::string LoggingStr_; std::string LoggingStr_;
}; };
class OpenAPIRequestDelete { class OpenAPIRequestDelete {
public: public:
explicit OpenAPIRequestDelete( const std::string & Type, explicit OpenAPIRequestDelete(const std::string &Type, const std::string &EndPoint,
const std::string & EndPoint, const Types::StringPairVec &QueryData, uint64_t msTimeout,
const Types::StringPairVec & QueryData, const std::string &LoggingStr = "")
uint64_t msTimeout, : Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout),
const std::string &LoggingStr=""): LoggingStr_(LoggingStr){};
Type_(Type), Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string &BearerToken = "");
EndPoint_(EndPoint),
QueryData_(QueryData),
msTimeout_(msTimeout),
LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string & BearerToken = "");
private: private:
std::string Type_; std::string Type_;
std::string EndPoint_; std::string EndPoint_;
Types::StringPairVec QueryData_; Types::StringPairVec QueryData_;
uint64_t msTimeout_; uint64_t msTimeout_;
Poco::JSON::Object Body_; Poco::JSON::Object Body_;
std::string LoggingStr_; std::string LoggingStr_;
}; };
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,70 +4,71 @@
#pragma once #pragma once
#include <functional>
#include <list>
#include <map> #include <map>
#include <queue>
#include <set>
#include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include <functional>
#include <string>
#include <queue>
#include <list>
#include <set>
namespace OpenWifi::Types { namespace OpenWifi::Types {
typedef std::pair<std::string,std::string> StringPair; typedef std::pair<std::string, std::string> StringPair;
typedef std::vector<StringPair> StringPairVec; typedef std::vector<StringPair> StringPairVec;
typedef std::queue<StringPair> StringPairQueue; typedef std::queue<StringPair> StringPairQueue;
typedef std::vector<std::string> StringVec; typedef std::vector<std::string> StringVec;
typedef std::set<std::string> StringSet; typedef std::set<std::string> StringSet;
typedef std::map<std::string,std::set<std::string>> StringMapStringSet; typedef std::map<std::string, std::set<std::string>> StringMapStringSet;
typedef std::function<void(const std::string &, const std::string &)> TopicNotifyFunction; typedef std::function<void(const std::string &, const std::string &)> TopicNotifyFunction;
typedef std::list<std::pair<TopicNotifyFunction,int>> TopicNotifyFunctionList; typedef std::list<std::pair<TopicNotifyFunction, int>> TopicNotifyFunctionList;
typedef std::map<std::string, TopicNotifyFunctionList> NotifyTable; typedef std::map<std::string, TopicNotifyFunctionList> NotifyTable;
typedef std::map<std::string,uint64_t> CountedMap; typedef std::map<std::string, uint64_t> CountedMap;
typedef std::vector<uint64_t> TagList; typedef std::vector<uint64_t> TagList;
typedef std::string UUID_t; typedef std::string UUID_t;
typedef std::vector<UUID_t> UUIDvec_t; typedef std::vector<UUID_t> UUIDvec_t;
typedef std::map<std::string,std::map<uint32_t,uint64_t>> Counted3DMapSII; typedef std::map<std::string, std::map<uint32_t, uint64_t>> Counted3DMapSII;
struct MicroServiceMeta { struct MicroServiceMeta {
uint64_t Id=0; uint64_t Id = 0;
std::string Type; std::string Type;
std::string PrivateEndPoint; std::string PrivateEndPoint;
std::string PublicEndPoint; std::string PublicEndPoint;
std::string AccessKey; std::string AccessKey;
std::string Version; std::string Version;
uint64_t LastUpdate=0; uint64_t LastUpdate = 0;
}; };
typedef std::map<std::string, MicroServiceMeta> MicroServiceMetaMap; typedef std::map<std::string, MicroServiceMeta> MicroServiceMetaMap;
typedef std::vector<MicroServiceMeta> MicroServiceMetaVec; typedef std::vector<MicroServiceMeta> MicroServiceMetaVec;
} } // namespace OpenWifi::Types
namespace OpenWifi { namespace OpenWifi {
inline void UpdateCountedMap(OpenWifi::Types::CountedMap &M, const std::string &S, uint64_t Increment=1) { inline void UpdateCountedMap(OpenWifi::Types::CountedMap &M, const std::string &S,
auto it = M.find(S); uint64_t Increment = 1) {
if(it==M.end()) auto it = M.find(S);
M[S] = Increment; if (it == M.end())
else M[S] = Increment;
it->second += Increment; else
} it->second += Increment;
}
inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S, uint32_t Index, uint64_t Increment=1) { inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S,
auto it = M.find(S); uint32_t Index, uint64_t Increment = 1) {
if(it==M.end()) { auto it = M.find(S);
std::map<uint32_t,uint64_t> E; if (it == M.end()) {
E[Index] = Increment; std::map<uint32_t, uint64_t> E;
M[S] = E; E[Index] = Increment;
} M[S] = E;
else { } else {
std::map<uint32_t,uint64_t> & IndexMap = it->second; std::map<uint32_t, uint64_t> &IndexMap = it->second;
auto it_index = IndexMap.find(Index); auto it_index = IndexMap.find(Index);
if(it_index == IndexMap.end()) { if (it_index == IndexMap.end()) {
IndexMap[Index] = Increment; IndexMap[Index] = Increment;
} else { } else {
it_index->second += Increment; it_index->second += Increment;
} }
} }
} }
} } // namespace OpenWifi

View File

@@ -6,22 +6,23 @@
namespace OpenWifi { namespace OpenWifi {
Poco::Net::HTTPRequestHandler *ExtRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &Request) { Poco::Net::HTTPRequestHandler *
ExtRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &Request) {
try { try {
Poco::URI uri(Request.getURI()); Poco::URI uri(Request.getURI());
auto TID = NextTransactionId_++; auto TID = NextTransactionId_++;
Utils::SetThreadName(fmt::format("x-rest:{}",TID).c_str()); Utils::SetThreadName(fmt::format("x-rest:{}", TID).c_str());
return RESTAPI_ExtServer()->CallServer(uri.getPath(), TID); return RESTAPI_ExtServer()->CallServer(uri.getPath(), TID);
} catch (...) { } catch (...) {
} }
return nullptr; return nullptr;
} }
Poco::Net::HTTPRequestHandler *RESTAPI_ExtServer::CallServer(const std::string &Path, uint64_t Id) { Poco::Net::HTTPRequestHandler *RESTAPI_ExtServer::CallServer(const std::string &Path,
uint64_t Id) {
RESTAPIHandler::BindingMap Bindings; RESTAPIHandler::BindingMap Bindings;
Utils::SetThreadName(fmt::format("x-rest:{}",Id).c_str()); Utils::SetThreadName(fmt::format("x-rest:{}", Id).c_str());
return RESTAPI_ExtRouter(Path, Bindings, Logger(), Server_, Id); return RESTAPI_ExtRouter(Path, Bindings, Logger(), Server_, Id);
} }
} } // namespace OpenWifi

View File

@@ -6,20 +6,23 @@
#include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPServer.h"
#include "framework/SubSystemServer.h"
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
#include "framework/SubSystemServer.h"
namespace OpenWifi { namespace OpenWifi {
Poco::Net::HTTPRequestHandler * RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings, Poco::Net::HTTPRequestHandler *
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t Id); RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t Id);
class ExtRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { class ExtRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
public: public:
ExtRequestHandlerFactory() = default; ExtRequestHandlerFactory() = default;
Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override; Poco::Net::HTTPRequestHandler *
createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
private: private:
static inline std::atomic_uint64_t NextTransactionId_ = 1; static inline std::atomic_uint64_t NextTransactionId_ = 1;
}; };
class RESTAPI_ExtServer : public SubSystemServer { class RESTAPI_ExtServer : public SubSystemServer {
@@ -30,16 +33,21 @@ namespace OpenWifi {
} }
inline int Start() override { inline int Start() override {
poco_information(Logger(),"Starting."); poco_information(Logger(), "Starting.");
Server_.InitLogging(); Server_.InitLogging();
for(const auto & Svr: ConfigServersList_) { for (const auto &Svr : ConfigServersList_) {
if(MicroServiceNoAPISecurity()) { if (MicroServiceNoAPISecurity()) {
poco_information(Logger(),fmt::format("Starting: {}:{}. Security has been disabled for APIs.", Svr.Address(), Svr.Port())); poco_information(
Logger(),
fmt::format("Starting: {}:{}. Security has been disabled for APIs.",
Svr.Address(), Svr.Port()));
} else { } else {
poco_information(Logger(),fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}", Svr.Address(), Svr.Port(), poco_information(Logger(),
Svr.KeyFile(),Svr.CertFile())); fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}",
Svr.Address(), Svr.Port(), Svr.KeyFile(),
Svr.CertFile()));
Svr.LogCert(Logger()); Svr.LogCert(Logger());
if (!Svr.RootCA().empty()) if (!Svr.RootCA().empty())
Svr.LogCas(Logger()); Svr.LogCas(Logger());
@@ -49,13 +57,15 @@ namespace OpenWifi {
Params->setKeepAlive(true); Params->setKeepAlive(true);
Params->setName("ws:xrest"); Params->setName("ws:xrest");
std::unique_ptr<Poco::Net::HTTPServer> NewServer; std::unique_ptr<Poco::Net::HTTPServer> NewServer;
if(MicroServiceNoAPISecurity()) { if (MicroServiceNoAPISecurity()) {
auto Sock{Svr.CreateSocket(Logger())}; auto Sock{Svr.CreateSocket(Logger())};
NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params); NewServer = std::make_unique<Poco::Net::HTTPServer>(
new ExtRequestHandlerFactory, Pool_, Sock, Params);
} else { } else {
auto Sock{Svr.CreateSecureSocket(Logger())}; auto Sock{Svr.CreateSecureSocket(Logger())};
NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params); NewServer = std::make_unique<Poco::Net::HTTPServer>(
new ExtRequestHandlerFactory, Pool_, Sock, Params);
}; };
NewServer->start(); NewServer->start();
RESTServers_.push_back(std::move(NewServer)); RESTServers_.push_back(std::move(NewServer));
@@ -64,36 +74,34 @@ namespace OpenWifi {
} }
inline void Stop() override { inline void Stop() override {
poco_information(Logger(),"Stopping..."); poco_information(Logger(), "Stopping...");
for( const auto & svr : RESTServers_ ) for (const auto &svr : RESTServers_)
svr->stopAll(true); svr->stopAll(true);
Pool_.stopAll(); Pool_.stopAll();
Pool_.joinAll(); Pool_.joinAll();
RESTServers_.clear(); RESTServers_.clear();
poco_information(Logger(),"Stopped..."); poco_information(Logger(), "Stopped...");
} }
inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override {
MicroServiceLoadConfigurationFile(); MicroServiceLoadConfigurationFile();
poco_information(Logger(),"Reinitializing."); poco_information(Logger(), "Reinitializing.");
Stop(); Stop();
Start(); Start();
} }
Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id); Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id);
const Poco::ThreadPool & Pool() { return Pool_; } const Poco::ThreadPool &Pool() { return Pool_; }
private: private:
std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_; std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
Poco::ThreadPool Pool_{"x-rest",8,128}; Poco::ThreadPool Pool_{"x-rest", 8, 128};
RESTAPI_GenericServerAccounting Server_; RESTAPI_GenericServerAccounting Server_;
RESTAPI_ExtServer() noexcept: RESTAPI_ExtServer() noexcept
SubSystemServer("RESTAPI_ExtServer", "REST-XSRV", "openwifi.restapi") : SubSystemServer("RESTAPI_ExtServer", "REST-XSRV", "openwifi.restapi") {}
{
}
}; };
inline auto RESTAPI_ExtServer() { return RESTAPI_ExtServer::instance(); }; inline auto RESTAPI_ExtServer() { return RESTAPI_ExtServer::instance(); };
} } // namespace OpenWifi

View File

@@ -4,72 +4,70 @@
#pragma once #pragma once
#include <string>
#include <array> #include <array>
#include <string>
#include "Poco/StringTokenizer.h"
#include "Poco/String.h"
#include "Poco/Net/HTTPRequest.h" #include "Poco/Net/HTTPRequest.h"
#include "Poco/String.h"
#include "Poco/StringTokenizer.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_GenericServerAccounting { class RESTAPI_GenericServerAccounting {
public: public:
enum { LOG_GET = 0, LOG_DELETE, LOG_PUT, LOG_POST };
enum {
LOG_GET=0,
LOG_DELETE,
LOG_PUT,
LOG_POST
};
void inline SetFlags(bool External, const std::string &Methods) { void inline SetFlags(bool External, const std::string &Methods) {
Poco::StringTokenizer Tokens(Methods,","); Poco::StringTokenizer Tokens(Methods, ",");
auto Offset = (External ? 0 : 4); auto Offset = (External ? 0 : 4);
for(const auto &i:Tokens) { for (const auto &i : Tokens) {
if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_DELETE)==0) if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_DELETE) == 0)
LogFlags_[Offset+LOG_DELETE]=true; LogFlags_[Offset + LOG_DELETE] = true;
else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_PUT)==0) else if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_PUT) == 0)
LogFlags_[Offset+LOG_PUT]=true; LogFlags_[Offset + LOG_PUT] = true;
else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_POST)==0) else if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_POST) == 0)
LogFlags_[Offset+LOG_POST]=true; LogFlags_[Offset + LOG_POST] = true;
else if(Poco::icompare(i,Poco::Net::HTTPRequest::HTTP_GET)==0) else if (Poco::icompare(i, Poco::Net::HTTPRequest::HTTP_GET) == 0)
LogFlags_[Offset+LOG_GET]=true; LogFlags_[Offset + LOG_GET] = true;
} }
} }
inline void InitLogging() { inline void InitLogging() {
std::string Public = MicroServiceConfigGetString("apilogging.public.methods","PUT,POST,DELETE"); std::string Public =
MicroServiceConfigGetString("apilogging.public.methods", "PUT,POST,DELETE");
SetFlags(true, Public); SetFlags(true, Public);
std::string Private = MicroServiceConfigGetString("apilogging.private.methods","PUT,POST,DELETE"); std::string Private =
MicroServiceConfigGetString("apilogging.private.methods", "PUT,POST,DELETE");
SetFlags(false, Private); SetFlags(false, Private);
std::string PublicBadTokens = MicroServiceConfigGetString("apilogging.public.badtokens.methods",""); std::string PublicBadTokens =
LogBadTokens_[0] = (Poco::icompare(PublicBadTokens,"true")==0); MicroServiceConfigGetString("apilogging.public.badtokens.methods", "");
std::string PrivateBadTokens = MicroServiceConfigGetString("apilogging.private.badtokens.methods",""); LogBadTokens_[0] = (Poco::icompare(PublicBadTokens, "true") == 0);
LogBadTokens_[1] = (Poco::icompare(PrivateBadTokens,"true")==0); std::string PrivateBadTokens =
MicroServiceConfigGetString("apilogging.private.badtokens.methods", "");
LogBadTokens_[1] = (Poco::icompare(PrivateBadTokens, "true") == 0);
} }
[[nodiscard]] inline bool LogIt(const std::string &Method, bool External) const { [[nodiscard]] inline bool LogIt(const std::string &Method, bool External) const {
auto Offset = (External ? 0 : 4); auto Offset = (External ? 0 : 4);
if(Method == Poco::Net::HTTPRequest::HTTP_GET) if (Method == Poco::Net::HTTPRequest::HTTP_GET)
return LogFlags_[Offset+LOG_GET]; return LogFlags_[Offset + LOG_GET];
if(Method == Poco::Net::HTTPRequest::HTTP_POST) if (Method == Poco::Net::HTTPRequest::HTTP_POST)
return LogFlags_[Offset+LOG_POST]; return LogFlags_[Offset + LOG_POST];
if(Method == Poco::Net::HTTPRequest::HTTP_PUT) if (Method == Poco::Net::HTTPRequest::HTTP_PUT)
return LogFlags_[Offset+LOG_PUT]; return LogFlags_[Offset + LOG_PUT];
if(Method == Poco::Net::HTTPRequest::HTTP_DELETE) if (Method == Poco::Net::HTTPRequest::HTTP_DELETE)
return LogFlags_[Offset+LOG_DELETE]; return LogFlags_[Offset + LOG_DELETE];
return false; return false;
}; };
[[nodiscard]] inline bool LogBadTokens(bool External) const { [[nodiscard]] inline bool LogBadTokens(bool External) const {
return LogBadTokens_[ (External ? 0 : 1) ]; return LogBadTokens_[(External ? 0 : 1)];
}; };
private: private:
std::array<bool,8> LogFlags_{false}; std::array<bool, 8> LogFlags_{false};
std::array<bool,2> LogBadTokens_{false}; std::array<bool, 2> LogBadTokens_{false};
}; };
} } // namespace OpenWifi

View File

@@ -4,5 +4,4 @@
#include "RESTAPI_Handler.h" #include "RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {} // namespace OpenWifi
} // namespace OpenWifi

File diff suppressed because it is too large Load Diff

View File

@@ -6,20 +6,23 @@
#include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPServer.h"
#include "framework/SubSystemServer.h"
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
#include "framework/SubSystemServer.h"
namespace OpenWifi { namespace OpenWifi {
Poco::Net::HTTPRequestHandler * RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings, Poco::Net::HTTPRequestHandler *
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t Id); RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger &L, RESTAPI_GenericServerAccounting &S, uint64_t Id);
class IntRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory { class IntRequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
public: public:
inline IntRequestHandlerFactory() = default; inline IntRequestHandlerFactory() = default;
Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override; Poco::Net::HTTPRequestHandler *
createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
private: private:
static inline std::atomic_uint64_t NextTransactionId_ = 1; static inline std::atomic_uint64_t NextTransactionId_ = 1;
}; };
class RESTAPI_IntServer : public SubSystemServer { class RESTAPI_IntServer : public SubSystemServer {
@@ -30,16 +33,21 @@ namespace OpenWifi {
} }
inline int Start() override { inline int Start() override {
poco_information(Logger(),"Starting."); poco_information(Logger(), "Starting.");
Server_.InitLogging(); Server_.InitLogging();
for(const auto & Svr: ConfigServersList_) { for (const auto &Svr : ConfigServersList_) {
if(MicroServiceNoAPISecurity()) { if (MicroServiceNoAPISecurity()) {
poco_information(Logger(),fmt::format("Starting: {}:{}. Security has been disabled for APIs.", Svr.Address(), Svr.Port())); poco_information(
Logger(),
fmt::format("Starting: {}:{}. Security has been disabled for APIs.",
Svr.Address(), Svr.Port()));
} else { } else {
poco_information(Logger(),fmt::format("Starting: {}:{}. Keyfile:{} CertFile: {}", Svr.Address(), Svr.Port(), poco_information(Logger(),
Svr.KeyFile(),Svr.CertFile())); fmt::format("Starting: {}:{}. Keyfile:{} CertFile: {}",
Svr.Address(), Svr.Port(), Svr.KeyFile(),
Svr.CertFile()));
Svr.LogCert(Logger()); Svr.LogCert(Logger());
if (!Svr.RootCA().empty()) if (!Svr.RootCA().empty())
Svr.LogCas(Logger()); Svr.LogCas(Logger());
@@ -49,13 +57,15 @@ namespace OpenWifi {
Params->setKeepAlive(true); Params->setKeepAlive(true);
Params->setName("ws:irest"); Params->setName("ws:irest");
std::unique_ptr<Poco::Net::HTTPServer> NewServer; std::unique_ptr<Poco::Net::HTTPServer> NewServer;
if(MicroServiceNoAPISecurity()) { if (MicroServiceNoAPISecurity()) {
auto Sock{Svr.CreateSocket(Logger())}; auto Sock{Svr.CreateSocket(Logger())};
NewServer = std::make_unique<Poco::Net::HTTPServer>(new IntRequestHandlerFactory, Pool_, Sock, Params); NewServer = std::make_unique<Poco::Net::HTTPServer>(
new IntRequestHandlerFactory, Pool_, Sock, Params);
} else { } else {
auto Sock{Svr.CreateSecureSocket(Logger())}; auto Sock{Svr.CreateSecureSocket(Logger())};
NewServer = std::make_unique<Poco::Net::HTTPServer>(new IntRequestHandlerFactory, Pool_, Sock, Params); NewServer = std::make_unique<Poco::Net::HTTPServer>(
new IntRequestHandlerFactory, Pool_, Sock, Params);
}; };
NewServer->start(); NewServer->start();
RESTServers_.push_back(std::move(NewServer)); RESTServers_.push_back(std::move(NewServer));
@@ -65,40 +75,37 @@ namespace OpenWifi {
} }
inline void Stop() override { inline void Stop() override {
poco_information(Logger(),"Stopping..."); poco_information(Logger(), "Stopping...");
for( const auto & svr : RESTServers_ ) for (const auto &svr : RESTServers_)
svr->stopAll(true); svr->stopAll(true);
Pool_.stopAll(); Pool_.stopAll();
Pool_.joinAll(); Pool_.joinAll();
poco_information(Logger(),"Stopped..."); poco_information(Logger(), "Stopped...");
} }
inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override {
MicroServiceLoadConfigurationFile(); MicroServiceLoadConfigurationFile();
poco_information(Logger(),"Reinitializing."); poco_information(Logger(), "Reinitializing.");
Stop(); Stop();
Start(); Start();
} }
inline Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id) { inline Poco::Net::HTTPRequestHandler *CallServer(const std::string &Path, uint64_t Id) {
RESTAPIHandler::BindingMap Bindings; RESTAPIHandler::BindingMap Bindings;
Utils::SetThreadName(fmt::format("i-rest:{}",Id).c_str()); Utils::SetThreadName(fmt::format("i-rest:{}", Id).c_str());
return RESTAPI_IntRouter(Path, Bindings, Logger(), Server_, Id); return RESTAPI_IntRouter(Path, Bindings, Logger(), Server_, Id);
} }
const Poco::ThreadPool & Pool() { return Pool_; } const Poco::ThreadPool &Pool() { return Pool_; }
private:
std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
Poco::ThreadPool Pool_{"i-rest",4,64};
RESTAPI_GenericServerAccounting Server_;
RESTAPI_IntServer() noexcept: private:
SubSystemServer("RESTAPI_IntServer", "REST-ISRV", "openwifi.internal.restapi") std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
{ Poco::ThreadPool Pool_{"i-rest", 4, 64};
} RESTAPI_GenericServerAccounting Server_;
RESTAPI_IntServer() noexcept
: SubSystemServer("RESTAPI_IntServer", "REST-ISRV", "openwifi.internal.restapi") {}
}; };
inline auto RESTAPI_IntServer() { return RESTAPI_IntServer::instance(); }; inline auto RESTAPI_IntServer() { return RESTAPI_IntServer::instance(); };
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,29 +4,26 @@
#pragma once #pragma once
#include <string>
#include "Poco/Net/PartHandler.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/CountingStream.h" #include "Poco/CountingStream.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/Net/PartHandler.h"
#include "Poco/NullStream.h" #include "Poco/NullStream.h"
#include "Poco/StreamCopier.h" #include "Poco/StreamCopier.h"
#include <string>
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_PartHandler: public Poco::Net::PartHandler { class RESTAPI_PartHandler : public Poco::Net::PartHandler {
public: public:
RESTAPI_PartHandler(): RESTAPI_PartHandler() : _length(0) {}
_length(0)
{
}
inline void handlePart(const Poco::Net::MessageHeader& header, std::istream& stream) override inline void handlePart(const Poco::Net::MessageHeader &header,
{ std::istream &stream) override {
_type = header.get("Content-Type", "(unspecified)"); _type = header.get("Content-Type", "(unspecified)");
if (header.has("Content-Disposition")) if (header.has("Content-Disposition")) {
{
std::string disp; std::string disp;
Poco::Net::NameValueCollection params; Poco::Net::NameValueCollection params;
Poco::Net::MessageHeader::splitParameters(header["Content-Disposition"], disp, params); Poco::Net::MessageHeader::splitParameters(header["Content-Disposition"], disp,
params);
_name = params.get("name", "(unnamed)"); _name = params.get("name", "(unnamed)");
_fileName = params.get("filename", "(unnamed)"); _fileName = params.get("filename", "(unnamed)");
} }
@@ -37,25 +34,13 @@ namespace OpenWifi {
_length = (int)istr.chars(); _length = (int)istr.chars();
} }
[[nodiscard]] inline int length() const [[nodiscard]] inline int length() const { return _length; }
{
return _length;
}
[[nodiscard]] inline const std::string& name() const [[nodiscard]] inline const std::string &name() const { return _name; }
{
return _name;
}
[[nodiscard]] inline const std::string& fileName() const [[nodiscard]] inline const std::string &fileName() const { return _fileName; }
{
return _fileName;
}
[[nodiscard]] inline const std::string& contentType() const [[nodiscard]] inline const std::string &contentType() const { return _type; }
{
return _type;
}
private: private:
int _length; int _length;
@@ -63,4 +48,4 @@ namespace OpenWifi {
std::string _name; std::string _name;
std::string _fileName; std::string _fileName;
}; };
} } // namespace OpenWifi

View File

@@ -6,9 +6,9 @@
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "Poco/URI.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/ExpireLRUCache.h" #include "Poco/ExpireLRUCache.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/URI.h"
#include "fmt/format.h" #include "fmt/format.h"
@@ -16,10 +16,9 @@ namespace OpenWifi {
class RESTAPI_RateLimiter : public SubSystemServer { class RESTAPI_RateLimiter : public SubSystemServer {
public: public:
struct ClientCacheEntry { struct ClientCacheEntry {
int64_t Start=0; int64_t Start = 0;
int Count=0; int Count = 0;
}; };
static auto instance() { static auto instance() {
@@ -27,49 +26,47 @@ namespace OpenWifi {
return instance_; return instance_;
} }
inline int Start() final { return 0;}; inline int Start() final { return 0; };
inline void Stop() final { }; inline void Stop() final{};
inline bool IsRateLimited(const Poco::Net::HTTPServerRequest &R, int64_t Period, int64_t MaxCalls) { inline bool IsRateLimited(const Poco::Net::HTTPServerRequest &R, int64_t Period,
Poco::URI uri(R.getURI()); int64_t MaxCalls) {
Poco::URI uri(R.getURI());
auto H = str_hash(uri.getPath() + R.clientAddress().host().toString()); auto H = str_hash(uri.getPath() + R.clientAddress().host().toString());
auto E = Cache_.get(H); auto E = Cache_.get(H);
auto Now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); auto Now = std::chrono::duration_cast<std::chrono::milliseconds>(
if(E.isNull()) { std::chrono::system_clock::now().time_since_epoch())
Cache_.add(H,ClientCacheEntry{.Start=Now, .Count=1}); .count();
if (E.isNull()) {
Cache_.add(H, ClientCacheEntry{.Start = Now, .Count = 1});
return false; return false;
} }
if((Now-E->Start)<Period) { if ((Now - E->Start) < Period) {
E->Count++; E->Count++;
Cache_.update(H,E); Cache_.update(H, E);
if(E->Count > MaxCalls) { if (E->Count > MaxCalls) {
poco_warning(Logger(),fmt::format("RATE-LIMIT-EXCEEDED: from '{}'", R.clientAddress().toString())); poco_warning(Logger(), fmt::format("RATE-LIMIT-EXCEEDED: from '{}'",
R.clientAddress().toString()));
return true; return true;
} }
return false; return false;
} }
E->Start = Now; E->Start = Now;
E->Count = 1; E->Count = 1;
Cache_.update(H,E); Cache_.update(H, E);
return false; return false;
} }
inline void Clear() { inline void Clear() { Cache_.clear(); }
Cache_.clear();
}
private: private:
Poco::ExpireLRUCache<uint64_t,ClientCacheEntry> Cache_{2048}; Poco::ExpireLRUCache<uint64_t, ClientCacheEntry> Cache_{2048};
std::hash<std::string> str_hash; std::hash<std::string> str_hash;
RESTAPI_RateLimiter() noexcept:
SubSystemServer("RateLimiter", "RATE-LIMITER", "rate.limiter")
{
}
RESTAPI_RateLimiter() noexcept
: SubSystemServer("RateLimiter", "RATE-LIMITER", "rate.limiter") {}
}; };
inline auto RESTAPI_RateLimiter() { return RESTAPI_RateLimiter::instance(); } inline auto RESTAPI_RateLimiter() { return RESTAPI_RateLimiter::instance(); }
} // namespace OpenWifi
}

View File

@@ -14,19 +14,19 @@ namespace OpenWifi {
class RESTAPI_system_command : public RESTAPIHandler { class RESTAPI_system_command : public RESTAPIHandler {
public: public:
RESTAPI_system_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal) RESTAPI_system_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L, : RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, Server, TransactionId, Internal) {}
TransactionId, static auto PathName() { return std::list<std::string>{"/api/v1/system"}; }
Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/system"};}
inline void DoGet() { inline void DoGet() {
std::string Arg; std::string Arg;
if(HasParameter("command",Arg) && Arg=="info") { if (HasParameter("command", Arg) && Arg == "info") {
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
Answer.set(RESTAPI::Protocol::VERSION, MicroServiceVersion()); Answer.set(RESTAPI::Protocol::VERSION, MicroServiceVersion());
Answer.set(RESTAPI::Protocol::UPTIME, MicroServiceUptimeTotalSeconds()); Answer.set(RESTAPI::Protocol::UPTIME, MicroServiceUptimeTotalSeconds());
@@ -36,19 +36,19 @@ namespace OpenWifi {
Answer.set(RESTAPI::Protocol::HOSTNAME, Poco::Environment::nodeName()); Answer.set(RESTAPI::Protocol::HOSTNAME, Poco::Environment::nodeName());
Answer.set(RESTAPI::Protocol::UI, MicroServiceGetUIURI()); Answer.set(RESTAPI::Protocol::UI, MicroServiceGetUIURI());
Poco::JSON::Array Certificates; Poco::JSON::Array Certificates;
auto SubSystems = MicroServiceGetFullSubSystems(); auto SubSystems = MicroServiceGetFullSubSystems();
std::set<std::string> CertNames; std::set<std::string> CertNames;
for(const auto &i:SubSystems) { for (const auto &i : SubSystems) {
auto Hosts=i->HostSize(); auto Hosts = i->HostSize();
for(uint64_t j=0;j<Hosts;++j) { for (uint64_t j = 0; j < Hosts; ++j) {
auto CertFileName = i->Host(j).CertFile(); auto CertFileName = i->Host(j).CertFile();
if(!CertFileName.empty()) { if (!CertFileName.empty()) {
Poco::File F1(CertFileName); Poco::File F1(CertFileName);
if(F1.exists()) { if (F1.exists()) {
auto InsertResult = CertNames.insert(CertFileName); auto InsertResult = CertNames.insert(CertFileName);
if(InsertResult.second) { if (InsertResult.second) {
Poco::JSON::Object Inner; Poco::JSON::Object Inner;
Poco::Path F(CertFileName); Poco::Path F(CertFileName);
Inner.set("filename", F.getFileName()); Inner.set("filename", F.getFileName());
@@ -64,8 +64,8 @@ namespace OpenWifi {
Answer.set("certificates", Certificates); Answer.set("certificates", Certificates);
return ReturnObject(Answer); return ReturnObject(Answer);
} }
if(GetBoolParameter("extraConfiguration")) { if (GetBoolParameter("extraConfiguration")) {
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
MicroServiceGetExtraConfiguration(Answer); MicroServiceGetExtraConfiguration(Answer);
return ReturnObject(Answer); return ReturnObject(Answer);
} }
@@ -73,7 +73,7 @@ namespace OpenWifi {
} }
inline void DoPost() final { inline void DoPost() final {
const auto & Obj = ParsedBody_; const auto &Obj = ParsedBody_;
if (Obj->has(RESTAPI::Protocol::COMMAND)) { if (Obj->has(RESTAPI::Protocol::COMMAND)) {
auto Command = Poco::toLower(Obj->get(RESTAPI::Protocol::COMMAND).toString()); auto Command = Poco::toLower(Obj->get(RESTAPI::Protocol::COMMAND).toString());
if (Command == RESTAPI::Protocol::SETLOGLEVEL) { if (Command == RESTAPI::Protocol::SETLOGLEVEL) {
@@ -88,7 +88,8 @@ namespace OpenWifi {
auto Name = GetS(RESTAPI::Protocol::TAG, InnerObj); auto Name = GetS(RESTAPI::Protocol::TAG, InnerObj);
auto Value = GetS(RESTAPI::Protocol::VALUE, InnerObj); auto Value = GetS(RESTAPI::Protocol::VALUE, InnerObj);
MicroServiceSetSubsystemLogLevel(Name, Value); MicroServiceSetSubsystemLogLevel(Name, Value);
poco_information(Logger_, poco_information(
Logger_,
fmt::format("Setting log level for {} at {}", Name, Value)); fmt::format("Setting log level for {} at {}", Name, Value));
} }
} }
@@ -109,7 +110,7 @@ namespace OpenWifi {
} else if (Command == RESTAPI::Protocol::GETLOGLEVELNAMES) { } else if (Command == RESTAPI::Protocol::GETLOGLEVELNAMES) {
Poco::JSON::Object Result; Poco::JSON::Object Result;
Poco::JSON::Array LevelNamesArray; Poco::JSON::Array LevelNamesArray;
const Types::StringVec &LevelNames = MicroServiceGetLogLevelNames(); const Types::StringVec &LevelNames = MicroServiceGetLogLevelNames();
for (const auto &i : LevelNames) for (const auto &i : LevelNames)
LevelNamesArray.add(i); LevelNamesArray.add(i);
Result.set(RESTAPI::Protocol::LIST, LevelNamesArray); Result.set(RESTAPI::Protocol::LIST, LevelNamesArray);
@@ -117,7 +118,7 @@ namespace OpenWifi {
} else if (Command == RESTAPI::Protocol::GETSUBSYSTEMNAMES) { } else if (Command == RESTAPI::Protocol::GETSUBSYSTEMNAMES) {
Poco::JSON::Object Result; Poco::JSON::Object Result;
Poco::JSON::Array LevelNamesArray; Poco::JSON::Array LevelNamesArray;
const Types::StringVec &SubSystemNames = MicroServiceGetSubSystems(); const Types::StringVec &SubSystemNames = MicroServiceGetSubSystems();
for (const auto &i : SubSystemNames) for (const auto &i : SubSystemNames)
LevelNamesArray.add(i); LevelNamesArray.add(i);
Result.set(RESTAPI::Protocol::LIST, LevelNamesArray); Result.set(RESTAPI::Protocol::LIST, LevelNamesArray);
@@ -131,10 +132,10 @@ namespace OpenWifi {
std::vector<std::string> Names; std::vector<std::string> Names;
for (const auto &i : *SubSystems) for (const auto &i : *SubSystems)
Names.push_back(i.toString()); Names.push_back(i.toString());
std::thread ReloadThread([Names](){ std::thread ReloadThread([Names]() {
std::this_thread::sleep_for(10000ms); std::this_thread::sleep_for(10000ms);
for(const auto &i:Names) { for (const auto &i : Names) {
if(i=="daemon") if (i == "daemon")
MicroServiceReload(); MicroServiceReload();
else else
MicroServiceReload(i); MicroServiceReload(i);
@@ -150,8 +151,8 @@ namespace OpenWifi {
BadRequest(RESTAPI::Errors::MissingOrInvalidParameters); BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
} }
void DoPut() final {}; void DoPut() final{};
void DoDelete() final {}; void DoDelete() final{};
}; };
} } // namespace OpenWifi

View File

@@ -4,8 +4,8 @@
#pragma once #pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
#include "framework/RESTAPI_Handler.h"
using namespace std::chrono_literals; using namespace std::chrono_literals;
@@ -14,8 +14,8 @@ namespace OpenWifi {
class RESTAPI_system_configuration : public RESTAPIHandler { class RESTAPI_system_configuration : public RESTAPIHandler {
public: public:
RESTAPI_system_configuration(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_system_configuration(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, RESTAPI_GenericServerAccounting &Server,
bool Internal) uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L, : RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_PUT, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest::HTTP_GET,
@@ -27,21 +27,18 @@ namespace OpenWifi {
inline void DoPost() final {} inline void DoPost() final {}
inline void DoGet() final { inline void DoGet() final { return OK(); }
return OK(); inline void DoPut() final {
} if (UserInfo_.userinfo.userRole != SecurityObjects::ROOT) {
inline void DoPut() final{
if(UserInfo_.userinfo.userRole!=SecurityObjects::ROOT) {
return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED); return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED);
} }
return OK(); return OK();
}; };
inline void DoDelete() final{ inline void DoDelete() final {
if(UserInfo_.userinfo.userRole!=SecurityObjects::ROOT) { if (UserInfo_.userinfo.userRole != SecurityObjects::ROOT) {
return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED); return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED);
} }
MicroServiceDeleteOverrideConfiguration(); MicroServiceDeleteOverrideConfiguration();
@@ -49,4 +46,4 @@ namespace OpenWifi {
}; };
}; };
} } // namespace OpenWifi

View File

@@ -4,42 +4,44 @@
#pragma once #pragma once
#include "framework/RESTAPI_Handler.h"
#include "Poco/Net/WebSocket.h" #include "Poco/Net/WebSocket.h"
#include "framework/RESTAPI_Handler.h"
#include "framework/UI_WebSocketClientServer.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
#include "framework/UI_WebSocketClientServer.h"
namespace OpenWifi { namespace OpenWifi {
class RESTAPI_webSocketServer : public RESTAPIHandler { class RESTAPI_webSocketServer : public RESTAPIHandler {
public: public:
inline RESTAPI_webSocketServer(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, bool Internal) inline RESTAPI_webSocketServer(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server,
uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L, : RESTAPIHandler(bindings, L,
std::vector<std::string>{ Poco::Net::HTTPRequest::HTTP_GET, std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS}, Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal,false) {} Server, TransactionId, Internal, false) {}
static auto PathName() { return std::list<std::string>{"/api/v1/ws"};} static auto PathName() { return std::list<std::string>{"/api/v1/ws"}; }
void DoGet() final { void DoGet() final {
try try {
{ if (Request->find("Upgrade") != Request->end() &&
if(Request->find("Upgrade") != Request->end() && Poco::icompare((*Request)["Upgrade"], "websocket") == 0) { Poco::icompare((*Request)["Upgrade"], "websocket") == 0) {
try try {
{ Poco::Net::WebSocket WS(*Request, *Response);
Poco::Net::WebSocket WS(*Request, *Response); auto Id = MicroServiceCreateUUID();
auto Id = MicroServiceCreateUUID(); UI_WebSocketClientServer()->NewClient(WS, Id, UserInfo_.userinfo.email,
UI_WebSocketClientServer()->NewClient(WS,Id,UserInfo_.userinfo.email, TransactionId_); TransactionId_);
} } catch (...) {
catch (...) { std::cout << "Cannot create websocket client..." << std::endl;
std::cout << "Cannot create websocket client..." << std::endl;
}
} }
} catch(...) {
std::cout << "Cannot upgrade connection..." << std::endl;
} }
}; } catch (...) {
void DoDelete() final {}; std::cout << "Cannot upgrade connection..." << std::endl;
void DoPost() final {}; }
void DoPut() final {}; };
void DoDelete() final{};
void DoPost() final{};
void DoPut() final{};
private: private:
}; };
} } // namespace OpenWifi

View File

@@ -6,9 +6,9 @@
#include <string> #include <string>
#include "Poco/Data/LOB.h"
#include "Poco/JSON/Object.h" #include "Poco/JSON/Object.h"
#include "Poco/JSON/Parser.h" #include "Poco/JSON/Parser.h"
#include "Poco/Data/LOB.h"
#include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerRequest.h"
#include "framework/OpenWifiTypes.h" #include "framework/OpenWifiTypes.h"
@@ -16,7 +16,8 @@
namespace OpenWifi::RESTAPI_utils { namespace OpenWifi::RESTAPI_utils {
inline void EmbedDocument(const std::string & ObjName, Poco::JSON::Object & Obj, const std::string &ObjStr) { inline void EmbedDocument(const std::string &ObjName, Poco::JSON::Object &Obj,
const std::string &ObjStr) {
std::string D = ObjStr.empty() ? "{}" : ObjStr; std::string D = ObjStr.empty() ? "{}" : ObjStr;
Poco::JSON::Parser P; Poco::JSON::Parser P;
Poco::Dynamic::Var result = P.parse(D); Poco::Dynamic::Var result = P.parse(D);
@@ -25,23 +26,23 @@ namespace OpenWifi::RESTAPI_utils {
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, bool V) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, bool V) {
Obj.set(Field,V); Obj.set(Field, V);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, double V) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, double V) {
Obj.set(Field,V); Obj.set(Field, V);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, float V) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, float V) {
Obj.set(Field,V); Obj.set(Field, V);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::string & S) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::string &S) {
Obj.set(Field,S); Obj.set(Field, S);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const char * S) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const char *S) {
Obj.set(Field,S); Obj.set(Field, S);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, int16_t Value) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, int16_t Value) {
@@ -65,87 +66,93 @@ namespace OpenWifi::RESTAPI_utils {
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, uint64_t Value) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, uint64_t Value) {
Obj.set(Field,Value); Obj.set(Field, Value);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Poco::Data::BLOB &Value) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
auto Result = Utils::base64encode((const unsigned char *)Value.rawContent(),Value.size()); const Poco::Data::BLOB &Value) {
Obj.set(Field,Result); auto Result = Utils::base64encode((const unsigned char *)Value.rawContent(), Value.size());
Obj.set(Field, Result);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::StringPairVec & S) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
Poco::JSON::Array Array; const Types::StringPairVec &S) {
for(const auto &i:S) { Poco::JSON::Array Array;
Poco::JSON::Object O; for (const auto &i : S) {
O.set("tag",i.first); Poco::JSON::Object O;
O.set("tag", i.first);
O.set("value", i.second); O.set("value", i.second);
Array.add(O); Array.add(O);
} }
Obj.set(Field,Array); Obj.set(Field, Array);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::StringVec &V) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
Poco::JSON::Array A; const Types::StringVec &V) {
for(const auto &i:V) Poco::JSON::Array A;
for (const auto &i : V)
A.add(i); A.add(i);
Obj.set(Field,A); Obj.set(Field, A);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::TagList &V) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::TagList &V) {
Poco::JSON::Array A; Poco::JSON::Array A;
for(const auto &i:V) for (const auto &i : V)
A.add(i); A.add(i);
Obj.set(Field,A); Obj.set(Field, A);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::CountedMap &M) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
Poco::JSON::Array A; const Types::CountedMap &M) {
for(const auto &[Key,Value]:M) { Poco::JSON::Array A;
Poco::JSON::Object O; for (const auto &[Key, Value] : M) {
O.set("tag",Key); Poco::JSON::Object O;
O.set("tag", Key);
O.set("value", Value); O.set("value", Value);
A.add(O); A.add(O);
} }
Obj.set(Field,A); Obj.set(Field, A);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::Counted3DMapSII &M) { inline void field_to_json(Poco::JSON::Object &Obj, const char *Field,
Poco::JSON::Array A; const Types::Counted3DMapSII &M) {
for(const auto &[OrgName,MonthlyNumberMap]:M) { Poco::JSON::Array A;
Poco::JSON::Object OrgObject; for (const auto &[OrgName, MonthlyNumberMap] : M) {
OrgObject.set("tag",OrgName); Poco::JSON::Object OrgObject;
Poco::JSON::Array MonthlyArray; OrgObject.set("tag", OrgName);
for(const auto &[Month,Counter]:MonthlyNumberMap) { Poco::JSON::Array MonthlyArray;
Poco::JSON::Object Inner; for (const auto &[Month, Counter] : MonthlyNumberMap) {
Poco::JSON::Object Inner;
Inner.set("value", Month); Inner.set("value", Month);
Inner.set("counter", Counter); Inner.set("counter", Counter);
MonthlyArray.add(Inner); MonthlyArray.add(Inner);
} }
OrgObject.set("index",MonthlyArray); OrgObject.set("index", MonthlyArray);
A.add(OrgObject); A.add(OrgObject);
} }
Obj.set(Field, A); Obj.set(Field, A);
} }
template<typename T> void field_to_json(Poco::JSON::Object &Obj, template <typename T>
const char *Field, void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &V,
const T &V,
std::function<std::string(const T &)> F) { std::function<std::string(const T &)> F) {
Obj.set(Field, F(V)); Obj.set(Field, F(V));
} }
template<class T> void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::vector<T> &Value) { template <class T>
void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::vector<T> &Value) {
Poco::JSON::Array Arr; Poco::JSON::Array Arr;
for(const auto &i:Value) { for (const auto &i : Value) {
Poco::JSON::Object AO; Poco::JSON::Object AO;
i.to_json(AO); i.to_json(AO);
Arr.add(AO); Arr.add(AO);
} }
Obj.set(Field, Arr); Obj.set(Field, Arr);
} }
template<class T> void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &Value) { template <class T>
Poco::JSON::Object Answer; void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &Value) {
Poco::JSON::Object Answer;
Value.to_json(Answer); Value.to_json(Answer);
Obj.set(Field, Answer); Obj.set(Field, Answer);
} }
@@ -155,188 +162,207 @@ namespace OpenWifi::RESTAPI_utils {
/////////////////////////// ///////////////////////////
/////////////////////////// ///////////////////////////
template<typename T> bool field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T & V, template <typename T>
bool field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &V,
std::function<T(const std::string &)> F) { std::function<T(const std::string &)> F) {
if(Obj->has(Field) && !Obj->isNull(Field)) if (Obj->has(Field) && !Obj->isNull(Field))
V = F(Obj->get(Field).toString()); V = F(Obj->get(Field).toString());
return true; return true;
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, std::string &S) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) std::string &S) {
if (Obj->has(Field) && !Obj->isNull(Field))
S = Obj->get(Field).toString(); S = Obj->get(Field).toString();
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, double & Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) double &Value) {
if (Obj->has(Field) && !Obj->isNull(Field))
Value = (double)Obj->get(Field); Value = (double)Obj->get(Field);
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, float & Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) float &Value) {
if (Obj->has(Field) && !Obj->isNull(Field))
Value = (float)Obj->get(Field); Value = (float)Obj->get(Field);
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, bool &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) bool &Value) {
if (Obj->has(Field) && !Obj->isNull(Field))
Value = (Obj->get(Field).toString() == "true"); Value = (Obj->get(Field).toString() == "true");
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int16_t &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) int16_t &Value) {
if (Obj->has(Field) && !Obj->isNull(Field))
Value = (int16_t)Obj->get(Field); Value = (int16_t)Obj->get(Field);
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int32_t &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) int32_t &Value) {
Value = (int32_t) Obj->get(Field); if (Obj->has(Field) && !Obj->isNull(Field))
Value = (int32_t)Obj->get(Field);
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int64_t &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) int64_t &Value) {
if (Obj->has(Field) && !Obj->isNull(Field))
Value = (int64_t)Obj->get(Field); Value = (int64_t)Obj->get(Field);
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint16_t &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) uint16_t &Value) {
if (Obj->has(Field) && !Obj->isNull(Field))
Value = (uint16_t)Obj->get(Field); Value = (uint16_t)Obj->get(Field);
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint32_t &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) uint32_t &Value) {
if (Obj->has(Field) && !Obj->isNull(Field))
Value = (uint32_t)Obj->get(Field); Value = (uint32_t)Obj->get(Field);
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint64_t &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) uint64_t &Value) {
if (Obj->has(Field) && !Obj->isNull(Field))
Value = (uint64_t)Obj->get(Field); Value = (uint64_t)Obj->get(Field);
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Poco::Data::BLOB &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->has(Field) && !Obj->isNull(Field)) { Poco::Data::BLOB &Value) {
if (Obj->has(Field) && !Obj->isNull(Field)) {
auto Result = Utils::base64decode(Obj->get(Field).toString()); auto Result = Utils::base64decode(Obj->get(Field).toString());
Value.assignRaw((const unsigned char *)&Result[0],Result.size()); Value.assignRaw((const unsigned char *)&Result[0], Result.size());
} }
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::StringPairVec &Vec) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->isArray(Field) && !Obj->isNull(Field)) { Types::StringPairVec &Vec) {
if (Obj->isArray(Field) && !Obj->isNull(Field)) {
auto O = Obj->getArray(Field); auto O = Obj->getArray(Field);
for(const auto &i:*O) { for (const auto &i : *O) {
std::string S1,S2; std::string S1, S2;
auto Inner = i.extract<Poco::JSON::Object::Ptr>(); auto Inner = i.extract<Poco::JSON::Object::Ptr>();
if(Inner->has("tag")) if (Inner->has("tag"))
S1 = Inner->get("tag").toString(); S1 = Inner->get("tag").toString();
if(Inner->has("value")) if (Inner->has("value"))
S2 = Inner->get("value").toString(); S2 = Inner->get("value").toString();
auto P = std::make_pair(S1,S2); auto P = std::make_pair(S1, S2);
Vec.push_back(P); Vec.push_back(P);
} }
} }
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::StringVec &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->isArray(Field) && !Obj->isNull(Field)) { Types::StringVec &Value) {
if (Obj->isArray(Field) && !Obj->isNull(Field)) {
Value.clear(); Value.clear();
Poco::JSON::Array::Ptr A = Obj->getArray(Field); Poco::JSON::Array::Ptr A = Obj->getArray(Field);
for(const auto &i:*A) { for (const auto &i : *A) {
Value.push_back(i.toString()); Value.push_back(i.toString());
} }
} }
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::TagList &Value) { inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
if(Obj->isArray(Field) && !Obj->isNull(Field)) { Types::TagList &Value) {
if (Obj->isArray(Field) && !Obj->isNull(Field)) {
Value.clear(); Value.clear();
Poco::JSON::Array::Ptr A = Obj->getArray(Field); Poco::JSON::Array::Ptr A = Obj->getArray(Field);
for(const auto &i:*A) { for (const auto &i : *A) {
Value.push_back(i); Value.push_back(i);
} }
} }
} }
template<class T> void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, std::vector<T> &Value) { template <class T>
if(Obj->isArray(Field) && !Obj->isNull(Field)) { void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
Poco::JSON::Array::Ptr Arr = Obj->getArray(Field); std::vector<T> &Value) {
for(auto &i:*Arr) { if (Obj->isArray(Field) && !Obj->isNull(Field)) {
Poco::JSON::Array::Ptr Arr = Obj->getArray(Field);
for (auto &i : *Arr) {
auto InnerObj = i.extract<Poco::JSON::Object::Ptr>(); auto InnerObj = i.extract<Poco::JSON::Object::Ptr>();
T NewItem; T NewItem;
NewItem.from_json(InnerObj); NewItem.from_json(InnerObj);
Value.push_back(NewItem); Value.push_back(NewItem);
} }
} }
} }
template<class T> void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &Value) { template <class T>
if(Obj->isObject(Field) && !Obj->isNull(Field)) { void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &Value) {
Poco::JSON::Object::Ptr A = Obj->getObject(Field); if (Obj->isObject(Field) && !Obj->isNull(Field)) {
Poco::JSON::Object::Ptr A = Obj->getObject(Field);
Value.from_json(A); Value.from_json(A);
} }
} }
inline std::string to_string(const Types::TagList & ObjectArray) { inline std::string to_string(const Types::TagList &ObjectArray) {
Poco::JSON::Array OutputArr; Poco::JSON::Array OutputArr;
if(ObjectArray.empty()) if (ObjectArray.empty())
return "[]"; return "[]";
for(auto const &i:ObjectArray) { for (auto const &i : ObjectArray) {
OutputArr.add(i); OutputArr.add(i);
} }
std::ostringstream OS; std::ostringstream OS;
Poco::JSON::Stringifier::stringify(OutputArr,OS, 0,0, Poco::JSON_PRESERVE_KEY_ORDER ); Poco::JSON::Stringifier::stringify(OutputArr, OS, 0, 0, Poco::JSON_PRESERVE_KEY_ORDER);
return OS.str(); return OS.str();
} }
inline std::string to_string(const Types::StringVec & ObjectArray) { inline std::string to_string(const Types::StringVec &ObjectArray) {
Poco::JSON::Array OutputArr; Poco::JSON::Array OutputArr;
if(ObjectArray.empty()) if (ObjectArray.empty())
return "[]"; return "[]";
for(auto const &i:ObjectArray) { for (auto const &i : ObjectArray) {
OutputArr.add(i); OutputArr.add(i);
} }
std::ostringstream OS; std::ostringstream OS;
Poco::JSON::Stringifier::condense(OutputArr,OS); Poco::JSON::Stringifier::condense(OutputArr, OS);
return OS.str(); return OS.str();
} }
inline std::string to_string(const Types::StringPairVec & ObjectArray) { inline std::string to_string(const Types::StringPairVec &ObjectArray) {
Poco::JSON::Array OutputArr; Poco::JSON::Array OutputArr;
if(ObjectArray.empty()) if (ObjectArray.empty())
return "[]"; return "[]";
for(auto const &i:ObjectArray) { for (auto const &i : ObjectArray) {
Poco::JSON::Array InnerArray; Poco::JSON::Array InnerArray;
InnerArray.add(i.first); InnerArray.add(i.first);
InnerArray.add(i.second); InnerArray.add(i.second);
OutputArr.add(InnerArray); OutputArr.add(InnerArray);
} }
std::ostringstream OS; std::ostringstream OS;
Poco::JSON::Stringifier::condense(OutputArr,OS); Poco::JSON::Stringifier::condense(OutputArr, OS);
return OS.str(); return OS.str();
} }
template<class T> std::string to_string(const std::vector<T> & ObjectArray) { template <class T> std::string to_string(const std::vector<T> &ObjectArray) {
Poco::JSON::Array OutputArr; Poco::JSON::Array OutputArr;
if(ObjectArray.empty()) if (ObjectArray.empty())
return "[]"; return "[]";
for(auto const &i:ObjectArray) { for (auto const &i : ObjectArray) {
Poco::JSON::Object O; Poco::JSON::Object O;
i.to_json(O); i.to_json(O);
OutputArr.add(O); OutputArr.add(O);
} }
std::ostringstream OS; std::ostringstream OS;
Poco::JSON::Stringifier::condense(OutputArr,OS); Poco::JSON::Stringifier::condense(OutputArr, OS);
return OS.str(); return OS.str();
} }
template<class T> std::string to_string(const std::vector<std::vector<T>> & ObjectArray) { template <class T> std::string to_string(const std::vector<std::vector<T>> &ObjectArray) {
Poco::JSON::Array OutputArr; Poco::JSON::Array OutputArr;
if(ObjectArray.empty()) if (ObjectArray.empty())
return "[]"; return "[]";
for(auto const &i:ObjectArray) { for (auto const &i : ObjectArray) {
Poco::JSON::Array InnerArr; Poco::JSON::Array InnerArr;
for(auto const &j:i) { for (auto const &j : i) {
if constexpr(std::is_integral<T>::value) { if constexpr (std::is_integral<T>::value) {
InnerArr.add(j); InnerArr.add(j);
} if constexpr(std::is_same_v<T,std::string>) { }
if constexpr (std::is_same_v<T, std::string>) {
InnerArr.add(j); InnerArr.add(j);
} else { } else {
InnerArr.add(j); InnerArr.add(j);
@@ -348,22 +374,22 @@ namespace OpenWifi::RESTAPI_utils {
OutputArr.add(InnerArr); OutputArr.add(InnerArr);
} }
std::ostringstream OS; std::ostringstream OS;
Poco::JSON::Stringifier::condense(OutputArr,OS); Poco::JSON::Stringifier::condense(OutputArr, OS);
return OS.str(); return OS.str();
} }
template<class T> std::string to_string(const T & Object) { template <class T> std::string to_string(const T &Object) {
Poco::JSON::Object OutputObj; Poco::JSON::Object OutputObj;
Object.to_json(OutputObj); Object.to_json(OutputObj);
std::ostringstream OS; std::ostringstream OS;
Poco::JSON::Stringifier::condense(OutputObj,OS); Poco::JSON::Stringifier::condense(OutputObj, OS);
return OS.str(); return OS.str();
} }
inline Types::StringVec to_object_array(const std::string & ObjectString) { inline Types::StringVec to_object_array(const std::string &ObjectString) {
Types::StringVec Result; Types::StringVec Result;
if(ObjectString.empty()) if (ObjectString.empty())
return Result; return Result;
try { try {
@@ -373,14 +399,13 @@ namespace OpenWifi::RESTAPI_utils {
Result.push_back(i.toString()); Result.push_back(i.toString());
} }
} catch (...) { } catch (...) {
} }
return Result; return Result;
} }
inline OpenWifi::Types::TagList to_taglist(const std::string & ObjectString) { inline OpenWifi::Types::TagList to_taglist(const std::string &ObjectString) {
Types::TagList Result; Types::TagList Result;
if(ObjectString.empty()) if (ObjectString.empty())
return Result; return Result;
try { try {
@@ -390,36 +415,34 @@ namespace OpenWifi::RESTAPI_utils {
Result.push_back(i); Result.push_back(i);
} }
} catch (...) { } catch (...) {
} }
return Result; return Result;
} }
inline Types::StringPairVec to_stringpair_array(const std::string &S) { inline Types::StringPairVec to_stringpair_array(const std::string &S) {
Types::StringPairVec R; Types::StringPairVec R;
if(S.empty()) if (S.empty())
return R; return R;
try { try {
Poco::JSON::Parser P; Poco::JSON::Parser P;
auto Object = P.parse(S).template extract<Poco::JSON::Array::Ptr>(); auto Object = P.parse(S).template extract<Poco::JSON::Array::Ptr>();
for (const auto &i : *Object) { for (const auto &i : *Object) {
auto InnerObject = i.template extract<Poco::JSON::Array::Ptr>(); auto InnerObject = i.template extract<Poco::JSON::Array::Ptr>();
if(InnerObject->size()==2) { if (InnerObject->size() == 2) {
auto S1 = InnerObject->getElement<std::string>(0); auto S1 = InnerObject->getElement<std::string>(0);
auto S2 = InnerObject->getElement<std::string>(1); auto S2 = InnerObject->getElement<std::string>(1);
R.push_back(std::make_pair(S1,S2)); R.push_back(std::make_pair(S1, S2));
} }
} }
} catch (...) { } catch (...) {
} }
return R; return R;
} }
template<class T> std::vector<T> to_object_array(const std::string & ObjectString) { template <class T> std::vector<T> to_object_array(const std::string &ObjectString) {
std::vector<T> Result; std::vector<T> Result;
if(ObjectString.empty()) if (ObjectString.empty())
return Result; return Result;
try { try {
@@ -432,14 +455,14 @@ namespace OpenWifi::RESTAPI_utils {
Result.push_back(Obj); Result.push_back(Obj);
} }
} catch (...) { } catch (...) {
} }
return Result; return Result;
} }
template<class T> std::vector<std::vector<T>> to_array_of_array_of_object(const std::string & ObjectString) { template <class T>
std::vector<std::vector<T>> Result; std::vector<std::vector<T>> to_array_of_array_of_object(const std::string &ObjectString) {
if(ObjectString.empty()) std::vector<std::vector<T>> Result;
if (ObjectString.empty())
return Result; return Result;
try { try {
Poco::JSON::Parser P1; Poco::JSON::Parser P1;
@@ -447,8 +470,8 @@ namespace OpenWifi::RESTAPI_utils {
for (auto const &i : *OutterArray) { for (auto const &i : *OutterArray) {
Poco::JSON::Parser P2; Poco::JSON::Parser P2;
auto InnerArray = P2.parse(i).template extract<Poco::JSON::Array::Ptr>(); auto InnerArray = P2.parse(i).template extract<Poco::JSON::Array::Ptr>();
std::vector<T> InnerVector; std::vector<T> InnerVector;
for(auto const &j: *InnerArray) { for (auto const &j : *InnerArray) {
auto Object = j.template extract<Poco::JSON::Object::Ptr>(); auto Object = j.template extract<Poco::JSON::Object::Ptr>();
T Obj; T Obj;
Obj.from_json(Object); Obj.from_json(Object);
@@ -457,28 +480,27 @@ namespace OpenWifi::RESTAPI_utils {
Result.push_back(InnerVector); Result.push_back(InnerVector);
} }
} catch (...) { } catch (...) {
} }
return Result; return Result;
} }
template<class T> T to_object(const std::string & ObjectString) { template <class T> T to_object(const std::string &ObjectString) {
T Result; T Result;
if(ObjectString.empty()) if (ObjectString.empty())
return Result; return Result;
Poco::JSON::Parser P; Poco::JSON::Parser P;
auto Object = P.parse(ObjectString).template extract<Poco::JSON::Object::Ptr>(); auto Object = P.parse(ObjectString).template extract<Poco::JSON::Object::Ptr>();
Result.from_json(Object); Result.from_json(Object);
return Result; return Result;
} }
template<class T> bool from_request(T & Obj, Poco::Net::HTTPServerRequest &Request) { template <class T> bool from_request(T &Obj, Poco::Net::HTTPServerRequest &Request) {
Poco::JSON::Parser IncomingParser; Poco::JSON::Parser IncomingParser;
auto RawObject = IncomingParser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>(); auto RawObject = IncomingParser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>();
Obj.from_json(RawObject); Obj.from_json(RawObject);
return true; return true;
} }
} } // namespace OpenWifi::RESTAPI_utils

View File

@@ -4,137 +4,133 @@
#pragma once #pragma once
#include "Poco/Data/SQLite/Connector.h"
#include "Poco/Data/Session.h" #include "Poco/Data/Session.h"
#include "Poco/Data/SessionPool.h" #include "Poco/Data/SessionPool.h"
#include "Poco/Data/SQLite/Connector.h"
#include "Poco/JSON/Object.h" #include "Poco/JSON/Object.h"
#ifndef SMALL_BUILD #ifndef SMALL_BUILD
#include "Poco/Data/PostgreSQL/Connector.h"
#include "Poco/Data/MySQL/Connector.h" #include "Poco/Data/MySQL/Connector.h"
#include "Poco/Data/PostgreSQL/Connector.h"
#endif #endif
#include "framework/SubSystemServer.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
#include "framework/SubSystemServer.h"
namespace OpenWifi { namespace OpenWifi {
enum DBType { enum DBType { sqlite, pgsql, mysql };
sqlite,
pgsql,
mysql
};
class StorageClass : public SubSystemServer { class StorageClass : public SubSystemServer {
public: public:
StorageClass() noexcept: StorageClass() noexcept : SubSystemServer("StorageClass", "STORAGE-SVR", "storage") {}
SubSystemServer("StorageClass", "STORAGE-SVR", "storage")
{
}
int Start() override { int Start() override {
std::lock_guard Guard(Mutex_); std::lock_guard Guard(Mutex_);
Logger().notice("Starting."); Logger().notice("Starting.");
std::string DBType = MicroServiceConfigGetString("storage.type",""); std::string DBType = MicroServiceConfigGetString("storage.type", "");
if (DBType == "sqlite") { if (DBType == "sqlite") {
Setup_SQLite(); Setup_SQLite();
} else if (DBType == "postgresql") { } else if (DBType == "postgresql") {
Setup_PostgreSQL(); Setup_PostgreSQL();
} else if (DBType == "mysql") { } else if (DBType == "mysql") {
Setup_MySQL(); Setup_MySQL();
} }
return 0; return 0;
} }
void Stop() override { void Stop() override { Pool_->shutdown(); }
Pool_->shutdown();
}
DBType Type() const { return dbType_; }; DBType Type() const { return dbType_; };
private:
inline int Setup_SQLite();
inline int Setup_MySQL();
inline int Setup_PostgreSQL();
protected: private:
std::unique_ptr<Poco::Data::SessionPool> Pool_; inline int Setup_SQLite();
Poco::Data::SQLite::Connector SQLiteConn_; inline int Setup_MySQL();
Poco::Data::PostgreSQL::Connector PostgresConn_; inline int Setup_PostgreSQL();
Poco::Data::MySQL::Connector MySQLConn_;
DBType dbType_ = sqlite;
};
#ifdef SMALL_BUILD protected:
int Service::Setup_MySQL() { Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); return 0; } std::unique_ptr<Poco::Data::SessionPool> Pool_;
int Service::Setup_PostgreSQL() { Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); return 0; } Poco::Data::SQLite::Connector SQLiteConn_;
Poco::Data::PostgreSQL::Connector PostgresConn_;
Poco::Data::MySQL::Connector MySQLConn_;
DBType dbType_ = sqlite;
};
#ifdef SMALL_BUILD
int Service::Setup_MySQL() {
Daemon()->exit(Poco::Util::Application::EXIT_CONFIG);
return 0;
}
int Service::Setup_PostgreSQL() {
Daemon()->exit(Poco::Util::Application::EXIT_CONFIG);
return 0;
}
#else #else
inline int StorageClass::Setup_SQLite() { inline int StorageClass::Setup_SQLite() {
Logger().notice("SQLite StorageClass enabled."); Logger().notice("SQLite StorageClass enabled.");
dbType_ = sqlite; dbType_ = sqlite;
auto DBName = MicroServiceDataDirectory() + "/" + MicroServiceConfigGetString("storage.type.sqlite.db",""); auto DBName = MicroServiceDataDirectory() + "/" +
int NumSessions = (int) MicroServiceConfigGetInt("storage.type.sqlite.maxsessions", 64); MicroServiceConfigGetString("storage.type.sqlite.db", "");
int IdleTime = (int) MicroServiceConfigGetInt("storage.type.sqlite.idletime", 60); int NumSessions = (int)MicroServiceConfigGetInt("storage.type.sqlite.maxsessions", 64);
int IdleTime = (int)MicroServiceConfigGetInt("storage.type.sqlite.idletime", 60);
Poco::Data::SQLite::Connector::registerConnector(); Poco::Data::SQLite::Connector::registerConnector();
// Pool_ = std::make_unique<Poco::Data::SessionPool>(new Poco::Data::SessionPool(SQLiteConn_.name(), DBName, 8, // Pool_ = std::make_unique<Poco::Data::SessionPool>(new
// (int)NumSessions, (int)IdleTime)); // Poco::Data::SessionPool(SQLiteConn_.name(), DBName, 8,
Pool_ = std::make_unique<Poco::Data::SessionPool>(SQLiteConn_.name(), DBName, 8, // (int)NumSessions,
(int)NumSessions, (int)IdleTime); // (int)IdleTime));
return 0; Pool_ = std::make_unique<Poco::Data::SessionPool>(SQLiteConn_.name(), DBName, 8,
} (int)NumSessions, (int)IdleTime);
return 0;
}
inline int StorageClass::Setup_MySQL() { inline int StorageClass::Setup_MySQL() {
Logger().notice("MySQL StorageClass enabled."); Logger().notice("MySQL StorageClass enabled.");
dbType_ = mysql; dbType_ = mysql;
int NumSessions = (int) MicroServiceConfigGetInt("storage.type.mysql.maxsessions", 64); int NumSessions = (int)MicroServiceConfigGetInt("storage.type.mysql.maxsessions", 64);
int IdleTime = (int) MicroServiceConfigGetInt("storage.type.mysql.idletime", 60); int IdleTime = (int)MicroServiceConfigGetInt("storage.type.mysql.idletime", 60);
auto Host = MicroServiceConfigGetString("storage.type.mysql.host",""); auto Host = MicroServiceConfigGetString("storage.type.mysql.host", "");
auto Username = MicroServiceConfigGetString("storage.type.mysql.username",""); auto Username = MicroServiceConfigGetString("storage.type.mysql.username", "");
auto Password = MicroServiceConfigGetString("storage.type.mysql.password",""); auto Password = MicroServiceConfigGetString("storage.type.mysql.password", "");
auto Database = MicroServiceConfigGetString("storage.type.mysql.database",""); auto Database = MicroServiceConfigGetString("storage.type.mysql.database", "");
auto Port = MicroServiceConfigGetString("storage.type.mysql.port",""); auto Port = MicroServiceConfigGetString("storage.type.mysql.port", "");
std::string ConnectionStr = std::string ConnectionStr = "host=" + Host + ";user=" + Username + ";password=" + Password +
"host=" + Host + ";db=" + Database + ";port=" + Port +
";user=" + Username + ";compress=true;auto-reconnect=true";
";password=" + Password +
";db=" + Database +
";port=" + Port +
";compress=true;auto-reconnect=true";
Poco::Data::MySQL::Connector::registerConnector(); Poco::Data::MySQL::Connector::registerConnector();
Pool_ = std::make_unique<Poco::Data::SessionPool>(MySQLConn_.name(), ConnectionStr, 8, NumSessions, IdleTime); Pool_ = std::make_unique<Poco::Data::SessionPool>(MySQLConn_.name(), ConnectionStr, 8,
NumSessions, IdleTime);
return 0; return 0;
} }
inline int StorageClass::Setup_PostgreSQL() { inline int StorageClass::Setup_PostgreSQL() {
Logger().notice("PostgreSQL StorageClass enabled."); Logger().notice("PostgreSQL StorageClass enabled.");
dbType_ = pgsql; dbType_ = pgsql;
int NumSessions = (int) MicroServiceConfigGetInt("storage.type.postgresql.maxsessions", 64); int NumSessions = (int)MicroServiceConfigGetInt("storage.type.postgresql.maxsessions", 64);
int IdleTime = (int) MicroServiceConfigGetInt("storage.type.postgresql.idletime", 60); int IdleTime = (int)MicroServiceConfigGetInt("storage.type.postgresql.idletime", 60);
auto Host = MicroServiceConfigGetString("storage.type.postgresql.host", ""); auto Host = MicroServiceConfigGetString("storage.type.postgresql.host", "");
auto Username = MicroServiceConfigGetString("storage.type.postgresql.username", ""); auto Username = MicroServiceConfigGetString("storage.type.postgresql.username", "");
auto Password = MicroServiceConfigGetString("storage.type.postgresql.password", ""); auto Password = MicroServiceConfigGetString("storage.type.postgresql.password", "");
auto Database = MicroServiceConfigGetString("storage.type.postgresql.database", ""); auto Database = MicroServiceConfigGetString("storage.type.postgresql.database", "");
auto Port = MicroServiceConfigGetString("storage.type.postgresql.port", ""); auto Port = MicroServiceConfigGetString("storage.type.postgresql.port", "");
auto ConnectionTimeout = MicroServiceConfigGetString("storage.type.postgresql.connectiontimeout", ""); auto ConnectionTimeout =
MicroServiceConfigGetString("storage.type.postgresql.connectiontimeout", "");
std::string ConnectionStr = std::string ConnectionStr = "host=" + Host + " user=" + Username + " password=" + Password +
"host=" + Host + " dbname=" + Database + " port=" + Port +
" user=" + Username + " connect_timeout=" + ConnectionTimeout;
" password=" + Password +
" dbname=" + Database +
" port=" + Port +
" connect_timeout=" + ConnectionTimeout;
Poco::Data::PostgreSQL::Connector::registerConnector(); Poco::Data::PostgreSQL::Connector::registerConnector();
Pool_ = std::make_unique<Poco::Data::SessionPool>(PostgresConn_.name(), ConnectionStr, 8, NumSessions, IdleTime); Pool_ = std::make_unique<Poco::Data::SessionPool>(PostgresConn_.name(), ConnectionStr, 8,
NumSessions, IdleTime);
return 0; return 0;
} }
#endif #endif
} } // namespace OpenWifi

View File

@@ -6,36 +6,29 @@
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "Poco/Net/SSLManager.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h" #include "Poco/DateTimeFormat.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/Net/SSLManager.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
namespace OpenWifi { namespace OpenWifi {
PropertiesFileServerEntry::PropertiesFileServerEntry(std::string Address, uint32_t port, std::string Key_file, PropertiesFileServerEntry::PropertiesFileServerEntry(
std::string Cert_file, std::string RootCa, std::string Issuer, std::string Address, uint32_t port, std::string Key_file, std::string Cert_file,
std::string ClientCas, std::string Cas, std::string RootCa, std::string Issuer, std::string ClientCas, std::string Cas,
std::string Key_file_password, std::string Name, std::string Key_file_password, std::string Name, Poco::Net::Context::VerificationMode M,
Poco::Net::Context::VerificationMode M, int backlog)
int backlog) : address_(std::move(Address)), port_(port), cert_file_(std::move(Cert_file)),
: address_(std::move(Address)), key_file_(std::move(Key_file)), root_ca_(std::move(RootCa)),
port_(port), key_file_password_(std::move(Key_file_password)), issuer_cert_file_(std::move(Issuer)),
cert_file_(std::move(Cert_file)), client_cas_(std::move(ClientCas)), cas_(std::move(Cas)), name_(std::move(Name)),
key_file_(std::move(Key_file)), backlog_(backlog), level_(M){
root_ca_(std::move(RootCa)),
key_file_password_(std::move(Key_file_password)),
issuer_cert_file_(std::move(Issuer)),
client_cas_(std::move(ClientCas)),
cas_(std::move(Cas)),
name_(std::move(Name)),
backlog_(backlog),
level_(M) {
}; };
[[nodiscard]] Poco::Net::SecureServerSocket PropertiesFileServerEntry::CreateSecureSocket(Poco::Logger &L) const { [[nodiscard]] Poco::Net::SecureServerSocket
PropertiesFileServerEntry::CreateSecureSocket(Poco::Logger &L) const {
Poco::Net::Context::Params P; Poco::Net::Context::Params P;
P.verificationMode = level_; P.verificationMode = level_;
@@ -45,11 +38,13 @@ namespace OpenWifi {
P.dhUse2048Bits = true; P.dhUse2048Bits = true;
P.caLocation = cas_; P.caLocation = cas_;
auto Context = Poco::AutoPtr<Poco::Net::Context>(new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P)); auto Context = Poco::AutoPtr<Poco::Net::Context>(
new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P));
if(!key_file_password_.empty()) { if (!key_file_password_.empty()) {
auto PassphraseHandler = Poco::SharedPtr<MyPrivateKeyPassphraseHandler>( new MyPrivateKeyPassphraseHandler(key_file_password_,L)); auto PassphraseHandler = Poco::SharedPtr<MyPrivateKeyPassphraseHandler>(
Poco::Net::SSLManager::instance().initializeServer(PassphraseHandler, nullptr,Context); new MyPrivateKeyPassphraseHandler(key_file_password_, L));
Poco::Net::SSLManager::instance().initializeServer(PassphraseHandler, nullptr, Context);
} }
if (!cert_file_.empty() && !key_file_.empty()) { if (!cert_file_.empty() && !key_file_.empty()) {
@@ -111,7 +106,8 @@ namespace OpenWifi {
} }
} }
[[nodiscard]] Poco::Net::ServerSocket PropertiesFileServerEntry::CreateSocket([[maybe_unused]] Poco::Logger &L) const { [[nodiscard]] Poco::Net::ServerSocket
PropertiesFileServerEntry::CreateSocket([[maybe_unused]] Poco::Logger &L) const {
Poco::Net::Context::Params P; Poco::Net::Context::Params P;
if (address_ == "*") { if (address_ == "*") {
@@ -127,20 +123,25 @@ namespace OpenWifi {
} }
} }
void PropertiesFileServerEntry::LogCertInfo(Poco::Logger &L, const Poco::Crypto::X509Certificate &C) const { void PropertiesFileServerEntry::LogCertInfo(Poco::Logger &L,
L.information("============================================================================================="); const Poco::Crypto::X509Certificate &C) const {
L.information("============================================================================"
"=================");
L.information(fmt::format("> Issuer: {}", C.issuerName())); L.information(fmt::format("> Issuer: {}", C.issuerName()));
L.information("---------------------------------------------------------------------------------------------"); L.information("----------------------------------------------------------------------------"
"-----------------");
L.information(fmt::format("> Common Name: {}", L.information(fmt::format("> Common Name: {}",
C.issuerName(Poco::Crypto::X509Certificate::NID_COMMON_NAME))); C.issuerName(Poco::Crypto::X509Certificate::NID_COMMON_NAME)));
L.information(fmt::format("> Country: {}", L.information(fmt::format("> Country: {}",
C.issuerName(Poco::Crypto::X509Certificate::NID_COUNTRY))); C.issuerName(Poco::Crypto::X509Certificate::NID_COUNTRY)));
L.information(fmt::format("> Locality: {}", L.information(fmt::format("> Locality: {}",
C.issuerName(Poco::Crypto::X509Certificate::NID_LOCALITY_NAME))); C.issuerName(Poco::Crypto::X509Certificate::NID_LOCALITY_NAME)));
L.information(fmt::format("> State/Prov: {}", L.information(
C.issuerName(Poco::Crypto::X509Certificate::NID_STATE_OR_PROVINCE))); fmt::format("> State/Prov: {}",
L.information(fmt::format("> Org name: {}", C.issuerName(Poco::Crypto::X509Certificate::NID_STATE_OR_PROVINCE)));
C.issuerName(Poco::Crypto::X509Certificate::NID_ORGANIZATION_NAME))); L.information(
fmt::format("> Org name: {}",
C.issuerName(Poco::Crypto::X509Certificate::NID_ORGANIZATION_NAME)));
L.information( L.information(
fmt::format("> Org unit: {}", fmt::format("> Org unit: {}",
C.issuerName(Poco::Crypto::X509Certificate::NID_ORGANIZATION_UNIT_NAME))); C.issuerName(Poco::Crypto::X509Certificate::NID_ORGANIZATION_UNIT_NAME)));
@@ -149,9 +150,11 @@ namespace OpenWifi {
C.issuerName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS))); C.issuerName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS)));
L.information(fmt::format("> Serial#: {}", L.information(fmt::format("> Serial#: {}",
C.issuerName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER))); C.issuerName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER)));
L.information("---------------------------------------------------------------------------------------------"); L.information("----------------------------------------------------------------------------"
"-----------------");
L.information(fmt::format("> Subject: {}", C.subjectName())); L.information(fmt::format("> Subject: {}", C.subjectName()));
L.information("---------------------------------------------------------------------------------------------"); L.information("----------------------------------------------------------------------------"
"-----------------");
L.information(fmt::format("> Common Name: {}", L.information(fmt::format("> Common Name: {}",
C.subjectName(Poco::Crypto::X509Certificate::NID_COMMON_NAME))); C.subjectName(Poco::Crypto::X509Certificate::NID_COMMON_NAME)));
L.information(fmt::format("> Country: {}", L.information(fmt::format("> Country: {}",
@@ -172,52 +175,66 @@ namespace OpenWifi {
C.subjectName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS))); C.subjectName(Poco::Crypto::X509Certificate::NID_PKCS9_EMAIL_ADDRESS)));
L.information(fmt::format("> Serial#: {}", L.information(fmt::format("> Serial#: {}",
C.subjectName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER))); C.subjectName(Poco::Crypto::X509Certificate::NID_SERIAL_NUMBER)));
L.information("---------------------------------------------------------------------------------------------"); L.information("----------------------------------------------------------------------------"
"-----------------");
L.information(fmt::format("> Signature Algo: {}", C.signatureAlgorithm())); L.information(fmt::format("> Signature Algo: {}", C.signatureAlgorithm()));
auto From = Poco::DateTimeFormatter::format(C.validFrom(), Poco::DateTimeFormat::HTTP_FORMAT); auto From =
Poco::DateTimeFormatter::format(C.validFrom(), Poco::DateTimeFormat::HTTP_FORMAT);
L.information(fmt::format("> Valid from: {}", From)); L.information(fmt::format("> Valid from: {}", From));
auto Expires = auto Expires =
Poco::DateTimeFormatter::format(C.expiresOn(), Poco::DateTimeFormat::HTTP_FORMAT); Poco::DateTimeFormatter::format(C.expiresOn(), Poco::DateTimeFormat::HTTP_FORMAT);
L.information(fmt::format("> Expires on: {}", Expires)); L.information(fmt::format("> Expires on: {}", Expires));
L.information(fmt::format("> Version: {}", (int)C.version())); L.information(fmt::format("> Version: {}", (int)C.version()));
L.information(fmt::format("> Serial #: {}", C.serialNumber())); L.information(fmt::format("> Serial #: {}", C.serialNumber()));
L.information("============================================================================================="); L.information("============================================================================"
"=================");
} }
void PropertiesFileServerEntry::LogCert(Poco::Logger &L) const { void PropertiesFileServerEntry::LogCert(Poco::Logger &L) const {
try { try {
Poco::Crypto::X509Certificate C(cert_file_); Poco::Crypto::X509Certificate C(cert_file_);
L.information("============================================================================================="); L.information("========================================================================"
L.information("============================================================================================="); "=====================");
L.information("========================================================================"
"=====================");
L.information(fmt::format("Certificate Filename: {}", cert_file_)); L.information(fmt::format("Certificate Filename: {}", cert_file_));
LogCertInfo(L, C); LogCertInfo(L, C);
L.information("============================================================================================="); L.information("========================================================================"
"=====================");
if (!issuer_cert_file_.empty()) { if (!issuer_cert_file_.empty()) {
Poco::Crypto::X509Certificate C1(issuer_cert_file_); Poco::Crypto::X509Certificate C1(issuer_cert_file_);
L.information("============================================================================================="); L.information("===================================================================="
L.information("============================================================================================="); "=========================");
L.information("===================================================================="
"=========================");
L.information(fmt::format("Issues Certificate Filename: {}", issuer_cert_file_)); L.information(fmt::format("Issues Certificate Filename: {}", issuer_cert_file_));
LogCertInfo(L, C1); LogCertInfo(L, C1);
L.information("============================================================================================="); L.information("===================================================================="
"=========================");
} }
if (!client_cas_.empty()) { if (!client_cas_.empty()) {
std::vector<Poco::Crypto::X509Certificate> Certs = std::vector<Poco::Crypto::X509Certificate> Certs =
Poco::Net::X509Certificate::readPEM(client_cas_); Poco::Net::X509Certificate::readPEM(client_cas_);
L.information("============================================================================================="); L.information("===================================================================="
L.information("============================================================================================="); "=========================");
L.information("===================================================================="
"=========================");
L.information(fmt::format("Client CAs Filename: {}", client_cas_)); L.information(fmt::format("Client CAs Filename: {}", client_cas_));
L.information("============================================================================================="); L.information("===================================================================="
"=========================");
auto i = 1; auto i = 1;
for (const auto &C3 : Certs) { for (const auto &C3 : Certs) {
L.information(fmt::format(" Index: {}", i)); L.information(fmt::format(" Index: {}", i));
L.information("============================================================================================="); L.information("================================================================"
"=============================");
LogCertInfo(L, C3); LogCertInfo(L, C3);
i++; i++;
} }
L.information("============================================================================================="); L.information("===================================================================="
"=========================");
} }
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
@@ -230,28 +247,31 @@ namespace OpenWifi {
std::vector<Poco::Crypto::X509Certificate> Certs = std::vector<Poco::Crypto::X509Certificate> Certs =
Poco::Net::X509Certificate::readPEM(root_ca_); Poco::Net::X509Certificate::readPEM(root_ca_);
L.information("============================================================================================="); L.information("========================================================================"
L.information("============================================================================================="); "=====================");
L.information("========================================================================"
"=====================");
L.information(fmt::format("CA Filename: {}", root_ca_)); L.information(fmt::format("CA Filename: {}", root_ca_));
L.information("============================================================================================="); L.information("========================================================================"
"=====================");
auto i = 1; auto i = 1;
for (const auto &C : Certs) { for (const auto &C : Certs) {
L.information(fmt::format(" Index: {}", i)); L.information(fmt::format(" Index: {}", i));
L.information("============================================================================================="); L.information("===================================================================="
"=========================");
LogCertInfo(L, C); LogCertInfo(L, C);
i++; i++;
} }
L.information("============================================================================================="); L.information("========================================================================"
"=====================");
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
L.log(E); L.log(E);
} }
} }
SubSystemServer::SubSystemServer(const std::string &Name, const std::string &LoggingPrefix, SubSystemServer::SubSystemServer(const std::string &Name, const std::string &LoggingPrefix,
const std::string &SubSystemConfigPrefix): const std::string &SubSystemConfigPrefix)
Name_(Name), : Name_(Name), LoggerPrefix_(LoggingPrefix), SubSystemConfigPrefix_(SubSystemConfigPrefix) {
LoggerPrefix_(LoggingPrefix),
SubSystemConfigPrefix_(SubSystemConfigPrefix) {
} }
void SubSystemServer::initialize([[maybe_unused]] Poco::Util::Application &self) { void SubSystemServer::initialize([[maybe_unused]] Poco::Util::Application &self) {
@@ -259,10 +279,13 @@ namespace OpenWifi {
bool good = true; bool good = true;
auto NewLevel = MicroServiceConfigGetString("logging.level." + Name_, ""); auto NewLevel = MicroServiceConfigGetString("logging.level." + Name_, "");
if(NewLevel.empty()) if (NewLevel.empty())
Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel())); Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(
LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel()));
else else
Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::parseLevel(NewLevel))); Logger_ = std::make_unique<LoggerWrapper>(
Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(),
Poco::Logger::parseLevel(NewLevel)));
ConfigServersList_.clear(); ConfigServersList_.clear();
while (good) { while (good) {
@@ -297,24 +320,18 @@ namespace OpenWifi {
} else if (L == "once") } else if (L == "once")
M = Poco::Net::Context::VERIFY_ONCE; M = Poco::Net::Context::VERIFY_ONCE;
PropertiesFileServerEntry entry(MicroServiceConfigGetString(address, ""), PropertiesFileServerEntry entry(
MicroServiceConfigGetInt(port, 0), MicroServiceConfigGetString(address, ""), MicroServiceConfigGetInt(port, 0),
MicroServiceConfigPath(key, ""), MicroServiceConfigPath(key, ""), MicroServiceConfigPath(cert, ""),
MicroServiceConfigPath(cert, ""), MicroServiceConfigPath(rootca, ""), MicroServiceConfigPath(issuer, ""),
MicroServiceConfigPath(rootca, ""), MicroServiceConfigPath(clientcas, ""), MicroServiceConfigPath(cas, ""),
MicroServiceConfigPath(issuer, ""), MicroServiceConfigGetString(key_password, ""),
MicroServiceConfigPath(clientcas, ""), MicroServiceConfigGetString(name, ""), M,
MicroServiceConfigPath(cas, ""), (int)MicroServiceConfigGetInt(backlog, 64));
MicroServiceConfigGetString(key_password, ""),
MicroServiceConfigGetString(name, ""), M,
(int)MicroServiceConfigGetInt(backlog, 64));
ConfigServersList_.push_back(entry); ConfigServersList_.push_back(entry);
i++; i++;
} }
} }
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,32 +4,30 @@
#pragma once #pragma once
#include <string>
#include <mutex> #include <mutex>
#include <string>
#include "Poco/Util/Application.h"
#include "Poco/Net/Context.h" #include "Poco/Net/Context.h"
#include "Poco/Net/SecureServerSocket.h"
#include "Poco/Net/PrivateKeyPassphraseHandler.h" #include "Poco/Net/PrivateKeyPassphraseHandler.h"
#include "Poco/Net/SecureServerSocket.h"
#include "Poco/Util/Application.h"
namespace OpenWifi { namespace OpenWifi {
class MyPrivateKeyPassphraseHandler : public Poco::Net::PrivateKeyPassphraseHandler { class MyPrivateKeyPassphraseHandler : public Poco::Net::PrivateKeyPassphraseHandler {
public: public:
explicit MyPrivateKeyPassphraseHandler(const std::string &Password, Poco::Logger & Logger): explicit MyPrivateKeyPassphraseHandler(const std::string &Password, Poco::Logger &Logger)
PrivateKeyPassphraseHandler(true), : PrivateKeyPassphraseHandler(true), Password_(Password), Logger_(Logger) {}
Password_(Password),
Logger_(Logger) {
}
void onPrivateKeyRequested([[maybe_unused]] const void * pSender,std::string & privateKey) { void onPrivateKeyRequested([[maybe_unused]] const void *pSender, std::string &privateKey) {
poco_information(Logger_,"Returning key passphrase."); poco_information(Logger_, "Returning key passphrase.");
privateKey = Password_; privateKey = Password_;
}; };
inline Poco::Logger & Logger() { return Logger_; } inline Poco::Logger &Logger() { return Logger_; }
private: private:
std::string Password_; std::string Password_;
Poco::Logger & Logger_; Poco::Logger &Logger_;
}; };
class PropertiesFileServerEntry { class PropertiesFileServerEntry {
@@ -76,24 +74,24 @@ namespace OpenWifi {
class SubSystemServer : public Poco::Util::Application::Subsystem { class SubSystemServer : public Poco::Util::Application::Subsystem {
public: public:
SubSystemServer(const std::string & Name, const std::string &LoggingPrefix, SubSystemServer(const std::string &Name, const std::string &LoggingPrefix,
const std::string & SubSystemConfigPrefix); const std::string &SubSystemConfigPrefix);
void initialize(Poco::Util::Application &self) override; void initialize(Poco::Util::Application &self) override;
inline void uninitialize() override { inline void uninitialize() override {}
}
inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override { inline void reinitialize([[maybe_unused]] Poco::Util::Application &self) override {
poco_information(Logger_->L_,"Reloading of this subsystem is not supported."); poco_information(Logger_->L_, "Reloading of this subsystem is not supported.");
} }
inline void defineOptions([[maybe_unused]] Poco::Util::OptionSet &options) override { inline void defineOptions([[maybe_unused]] Poco::Util::OptionSet &options) override {}
} inline const std::string &Name() const { return Name_; };
inline const std::string & Name() const { return Name_; }; inline const char *name() const override { return Name_.c_str(); }
inline const char * name() const override { return Name_.c_str(); }
inline const PropertiesFileServerEntry & Host(uint64_t index) { return ConfigServersList_[index]; }; inline const PropertiesFileServerEntry &Host(uint64_t index) {
return ConfigServersList_[index];
};
inline uint64_t HostSize() const { return ConfigServersList_.size(); } inline uint64_t HostSize() const { return ConfigServersList_.size(); }
inline Poco::Logger & Logger() const { return Logger_->L_; } inline Poco::Logger &Logger() const { return Logger_->L_; }
inline void SetLoggingLevel(const std::string & levelName) { inline void SetLoggingLevel(const std::string &levelName) {
Logger_->L_.setLevel(Poco::Logger::parseLevel(levelName)); Logger_->L_.setLevel(Poco::Logger::parseLevel(levelName));
} }
inline int GetLoggingLevel() { return Logger_->L_.getLevel(); } inline int GetLoggingLevel() { return Logger_->L_.getLevel(); }
@@ -102,23 +100,21 @@ namespace OpenWifi {
virtual void Stop() = 0; virtual void Stop() = 0;
struct LoggerWrapper { struct LoggerWrapper {
Poco::Logger & L_; Poco::Logger &L_;
LoggerWrapper(Poco::Logger &L) : LoggerWrapper(Poco::Logger &L) : L_(L) {}
L_(L) {
}
}; };
protected: protected:
std::recursive_mutex Mutex_; std::recursive_mutex Mutex_;
std::vector<PropertiesFileServerEntry> ConfigServersList_; std::vector<PropertiesFileServerEntry> ConfigServersList_;
private: private:
std::unique_ptr<LoggerWrapper> Logger_; std::unique_ptr<LoggerWrapper> Logger_;
std::string Name_; std::string Name_;
std::string LoggerPrefix_; std::string LoggerPrefix_;
std::string SubSystemConfigPrefix_; std::string SubSystemConfigPrefix_;
}; };
typedef std::vector<SubSystemServer *> SubSystemVec; typedef std::vector<SubSystemServer *> SubSystemVec;
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -5,7 +5,4 @@
#include "framework/UI_WebSocketClientNotifications.h" #include "framework/UI_WebSocketClientNotifications.h"
#include "framework/UI_WebSocketClientServer.h" #include "framework/UI_WebSocketClientServer.h"
namespace OpenWifi { namespace OpenWifi {}
}

View File

@@ -9,37 +9,35 @@
namespace OpenWifi { namespace OpenWifi {
template<typename ContentStruct> template <typename ContentStruct>
struct WebSocketNotification { struct WebSocketNotification {
inline static uint64_t xid = 1; inline static uint64_t xid = 1;
uint64_t notification_id = ++xid; uint64_t notification_id = ++xid;
std::uint64_t type_id=0; std::uint64_t type_id = 0;
ContentStruct content; ContentStruct content;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
template<typename ContentStruct> template <typename ContentStruct>
void WebSocketNotification<ContentStruct>::to_json(Poco::JSON::Object &Obj) const { void WebSocketNotification<ContentStruct>::to_json(Poco::JSON::Object &Obj) const {
RESTAPI_utils::field_to_json(Obj, "notification_id", notification_id); RESTAPI_utils::field_to_json(Obj, "notification_id", notification_id);
RESTAPI_utils::field_to_json(Obj, "type_id", type_id); RESTAPI_utils::field_to_json(Obj, "type_id", type_id);
RESTAPI_utils::field_to_json(Obj, "content", content); RESTAPI_utils::field_to_json(Obj, "content", content);
} }
template<typename ContentStruct> template <typename ContentStruct>
bool WebSocketNotification<ContentStruct>::from_json(const Poco::JSON::Object::Ptr &Obj) { bool WebSocketNotification<ContentStruct>::from_json(const Poco::JSON::Object::Ptr &Obj) {
try { try {
RESTAPI_utils::field_from_json(Obj, "notification_id", notification_id); RESTAPI_utils::field_from_json(Obj, "notification_id", notification_id);
RESTAPI_utils::field_from_json(Obj, "type_id", type_id); RESTAPI_utils::field_from_json(Obj, "type_id", type_id);
RESTAPI_utils::field_from_json(Obj, "content", content); RESTAPI_utils::field_from_json(Obj, "content", content);
return true; return true;
} catch (...) { } catch (...) {
}
} return false;
return false; }
} } // namespace OpenWifi
}

View File

@@ -4,14 +4,14 @@
#include <mutex> #include <mutex>
#include "Poco/NObserver.h"
#include "Poco/JSON/JSONException.h" #include "Poco/JSON/JSONException.h"
#include "Poco/JSON/Parser.h" #include "Poco/JSON/Parser.h"
#include "Poco/Logger.h" #include "Poco/Logger.h"
#include "Poco/NObserver.h"
#include "framework/UI_WebSocketClientServer.h"
#include "framework/AuthClient.h" #include "framework/AuthClient.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
#include "framework/UI_WebSocketClientServer.h"
#include "fmt/format.h" #include "fmt/format.h"
@@ -19,80 +19,82 @@
#include "AuthService.h" #include "AuthService.h"
#endif #endif
#define DBG { std::cout << __LINE__ << std::endl; } #define DBG \
{ std::cout << __LINE__ << std::endl; }
namespace OpenWifi { namespace OpenWifi {
void UI_WebSocketClientServer::NewClient(Poco::Net::WebSocket & WS, const std::string &Id, const std::string &UserName, std::uint64_t TID ) { void UI_WebSocketClientServer::NewClient(Poco::Net::WebSocket &WS, const std::string &Id,
const std::string &UserName, std::uint64_t TID) {
std::lock_guard G(LocalMutex_); std::lock_guard G(LocalMutex_);
auto Client = std::make_unique<UI_WebSocketClientInfo>(WS,Id, UserName); auto Client = std::make_unique<UI_WebSocketClientInfo>(WS, Id, UserName);
auto ClientSocket = Client->WS_->impl()->sockfd(); auto ClientSocket = Client->WS_->impl()->sockfd();
TID_ = TID; TID_ = TID;
Client->WS_->setNoDelay(true); Client->WS_->setNoDelay(true);
Client->WS_->setKeepAlive(true); Client->WS_->setKeepAlive(true);
Client->WS_->setBlocking(false); Client->WS_->setBlocking(false);
Reactor_.addEventHandler(*Client->WS_, Reactor_.addEventHandler(
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ReadableNotification>( *Client->WS_,
*this, &UI_WebSocketClientServer::OnSocketReadable)); Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ReadableNotification>(
Reactor_.addEventHandler(*Client->WS_, *this, &UI_WebSocketClientServer::OnSocketReadable));
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ShutdownNotification>( Reactor_.addEventHandler(
*this, &UI_WebSocketClientServer::OnSocketShutdown)); *Client->WS_,
Reactor_.addEventHandler(*Client->WS_, Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ShutdownNotification>(
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ErrorNotification>( *this, &UI_WebSocketClientServer::OnSocketShutdown));
*this, &UI_WebSocketClientServer::OnSocketError)); Reactor_.addEventHandler(
Client->SocketRegistered_ = true; *Client->WS_, Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ErrorNotification>(
Clients_[ClientSocket] = std::move(Client); *this, &UI_WebSocketClientServer::OnSocketError));
Client->SocketRegistered_ = true;
Clients_[ClientSocket] = std::move(Client);
UsersConnected_ = Clients_.size(); UsersConnected_ = Clients_.size();
}
void UI_WebSocketClientServer::SetProcessor( UI_WebSocketClientProcessor * F) {
Processor_ = F;
} }
UI_WebSocketClientServer::UI_WebSocketClientServer() noexcept: void UI_WebSocketClientServer::SetProcessor(UI_WebSocketClientProcessor *F) { Processor_ = F; }
SubSystemServer("WebSocketClientServer", "UI-WSCLNT-SVR", "websocketclients")
{ UI_WebSocketClientServer::UI_WebSocketClientServer() noexcept
} : SubSystemServer("WebSocketClientServer", "UI-WSCLNT-SVR", "websocketclients") {}
void UI_WebSocketClientServer::run() { void UI_WebSocketClientServer::run() {
Running_ = true; Running_ = true;
while(Running_) { while (Running_) {
Poco::Thread::trySleep(2000); Poco::Thread::trySleep(2000);
if(!Running_) if (!Running_)
break; break;
std::lock_guard G(LocalMutex_); std::lock_guard G(LocalMutex_);
for(const auto i:ToBeRemoved_) { for (const auto i : ToBeRemoved_) {
// std::cout << "Erasing old WS UI connection..." << std::endl; // std::cout << "Erasing old WS UI connection..." << std::endl;
Clients_.erase(i); Clients_.erase(i);
} }
ToBeRemoved_.clear(); ToBeRemoved_.clear();
UsersConnected_ = Clients_.size(); UsersConnected_ = Clients_.size();
} }
} }
void UI_WebSocketClientServer::EndConnection(ClientList::iterator Client) { void UI_WebSocketClientServer::EndConnection(ClientList::iterator Client) {
if(Client->second->SocketRegistered_) { if (Client->second->SocketRegistered_) {
Client->second->SocketRegistered_ = false; Client->second->SocketRegistered_ = false;
Reactor_.removeEventHandler(*Client->second->WS_, Reactor_.removeEventHandler(
Poco::NObserver<UI_WebSocketClientServer, *Client->second->WS_,
Poco::Net::ReadableNotification>(*this,&UI_WebSocketClientServer::OnSocketReadable)); Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ReadableNotification>(
Reactor_.removeEventHandler(*Client->second->WS_, *this, &UI_WebSocketClientServer::OnSocketReadable));
Poco::NObserver<UI_WebSocketClientServer, Reactor_.removeEventHandler(
Poco::Net::ShutdownNotification>(*this,&UI_WebSocketClientServer::OnSocketShutdown)); *Client->second->WS_,
Reactor_.removeEventHandler(*Client->second->WS_, Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ShutdownNotification>(
Poco::NObserver<UI_WebSocketClientServer, *this, &UI_WebSocketClientServer::OnSocketShutdown));
Poco::Net::ErrorNotification>(*this,&UI_WebSocketClientServer::OnSocketError)); Reactor_.removeEventHandler(
} *Client->second->WS_,
Poco::NObserver<UI_WebSocketClientServer, Poco::Net::ErrorNotification>(
*this, &UI_WebSocketClientServer::OnSocketError));
}
ToBeRemoved_.push_back(Client); ToBeRemoved_.push_back(Client);
} }
int UI_WebSocketClientServer::Start() { int UI_WebSocketClientServer::Start() {
poco_information(Logger(),"Starting..."); poco_information(Logger(), "Starting...");
GoogleApiKey_ = MicroServiceConfigGetString("google.apikey",""); GoogleApiKey_ = MicroServiceConfigGetString("google.apikey", "");
GeoCodeEnabled_ = !GoogleApiKey_.empty(); GeoCodeEnabled_ = !GoogleApiKey_.empty();
ReactorThread_.start(Reactor_); ReactorThread_.start(Reactor_);
ReactorThread_.setName("ws:ui-reactor"); ReactorThread_.setName("ws:ui-reactor");
@@ -102,29 +104,31 @@ namespace OpenWifi {
}; };
void UI_WebSocketClientServer::Stop() { void UI_WebSocketClientServer::Stop() {
if(Running_) { if (Running_) {
poco_information(Logger(),"Stopping..."); poco_information(Logger(), "Stopping...");
Clients_.clear(); Clients_.clear();
Reactor_.stop(); Reactor_.stop();
ReactorThread_.join(); ReactorThread_.join();
Running_ = false; Running_ = false;
CleanerThread_.wakeUp(); CleanerThread_.wakeUp();
CleanerThread_.join(); CleanerThread_.join();
poco_information(Logger(),"Stopped..."); poco_information(Logger(), "Stopped...");
} }
}; };
bool UI_WebSocketClientServer::IsFiltered(std::uint64_t id, const OpenWifi::UI_WebSocketClientInfo &Client) { bool UI_WebSocketClientServer::IsFiltered(std::uint64_t id,
return std::find(Client.Filter_.begin(), Client.Filter_.end(),id)!=end(Client.Filter_); const OpenWifi::UI_WebSocketClientInfo &Client) {
return std::find(Client.Filter_.begin(), Client.Filter_.end(), id) != end(Client.Filter_);
} }
bool UI_WebSocketClientServer::SendToUser(const std::string &UserName, std::uint64_t id, const std::string &Payload) { bool UI_WebSocketClientServer::SendToUser(const std::string &UserName, std::uint64_t id,
const std::string &Payload) {
std::lock_guard G(LocalMutex_); std::lock_guard G(LocalMutex_);
for(const auto &Client:Clients_) { for (const auto &Client : Clients_) {
if(Client.second->UserName_ == UserName) { if (Client.second->UserName_ == UserName) {
try { try {
if(!IsFiltered(id,*Client.second) && Client.second->Authenticated_) { if (!IsFiltered(id, *Client.second) && Client.second->Authenticated_) {
return Client.second->WS_->sendFrame( return Client.second->WS_->sendFrame(
Payload.c_str(), (int)Payload.size()) == (int)Payload.size(); Payload.c_str(), (int)Payload.size()) == (int)Payload.size();
} else { } else {
@@ -141,31 +145,32 @@ namespace OpenWifi {
void UI_WebSocketClientServer::SendToAll(std::uint64_t id, const std::string &Payload) { void UI_WebSocketClientServer::SendToAll(std::uint64_t id, const std::string &Payload) {
std::lock_guard G(LocalMutex_); std::lock_guard G(LocalMutex_);
for(const auto &Client:Clients_) { for (const auto &Client : Clients_) {
try { try {
if(!IsFiltered(id,*Client.second) && Client.second->Authenticated_) if (!IsFiltered(id, *Client.second) && Client.second->Authenticated_)
Client.second->WS_->sendFrame(Payload.c_str(),(int)Payload.size()); Client.second->WS_->sendFrame(Payload.c_str(), (int)Payload.size());
} catch (...) { } catch (...) {
} }
} }
} }
UI_WebSocketClientServer::ClientList::iterator UI_WebSocketClientServer::FindWSClient( [[maybe_unused]] std::lock_guard<std::recursive_mutex> &G, int ClientSocket) { UI_WebSocketClientServer::ClientList::iterator UI_WebSocketClientServer::FindWSClient(
return Clients_.find(ClientSocket); [[maybe_unused]] std::lock_guard<std::recursive_mutex> &G, int ClientSocket) {
} return Clients_.find(ClientSocket);
}
void UI_WebSocketClientServer::SortNotifications() { void UI_WebSocketClientServer::SortNotifications() {
struct { struct {
bool operator()(const NotificationEntry &A, const NotificationEntry & B) const { bool operator()(const NotificationEntry &A, const NotificationEntry &B) const {
return A.id < B.id; }; return A.id < B.id;
};
} CompareNotifications; } CompareNotifications;
std::sort(NotificationTypes_.begin(), NotificationTypes_.end(), CompareNotifications); std::sort(NotificationTypes_.begin(), NotificationTypes_.end(), CompareNotifications);
NotificationTypesJSON_.clear(); NotificationTypesJSON_.clear();
Poco::JSON::Array AllNotifications; Poco::JSON::Array AllNotifications;
for(const auto &notification:NotificationTypes_) { for (const auto &notification : NotificationTypes_) {
Poco::JSON::Object Notification; Poco::JSON::Object Notification;
Notification.set("id", notification.id); Notification.set("id", notification.id);
Notification.set("helper", notification.helper); Notification.set("helper", notification.helper);
AllNotifications.add(Notification); AllNotifications.add(Notification);
@@ -173,52 +178,60 @@ namespace OpenWifi {
NotificationTypesJSON_.set("notificationTypes", AllNotifications); NotificationTypesJSON_.set("notificationTypes", AllNotifications);
} }
void UI_WebSocketClientServer::RegisterNotifications(const OpenWifi::UI_WebSocketClientServer::NotificationTypeIdVec &Notifications) { void UI_WebSocketClientServer::RegisterNotifications(
std::copy(Notifications.begin(), Notifications.end(), std::back_inserter(NotificationTypes_)); const OpenWifi::UI_WebSocketClientServer::NotificationTypeIdVec &Notifications) {
std::copy(Notifications.begin(), Notifications.end(),
std::back_inserter(NotificationTypes_));
SortNotifications(); SortNotifications();
} }
void UI_WebSocketClientServer::OnSocketError([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf) { void UI_WebSocketClientServer::OnSocketError(
std::lock_guard G(LocalMutex_); [[maybe_unused]] const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf) {
auto Client = Clients_.find(pNf->socket().impl()->sockfd()); std::lock_guard G(LocalMutex_);
if(Client==end(Clients_)) auto Client = Clients_.find(pNf->socket().impl()->sockfd());
return; if (Client == end(Clients_))
EndConnection(Client); return;
EndConnection(Client);
} }
void UI_WebSocketClientServer::OnSocketReadable([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf) { void UI_WebSocketClientServer::OnSocketReadable(
[[maybe_unused]] const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf) {
UI_WebSocketClientServer::ClientList::iterator Client; UI_WebSocketClientServer::ClientList::iterator Client;
std::lock_guard G(LocalMutex_); std::lock_guard G(LocalMutex_);
try { try {
Client = Clients_.find(pNf->socket().impl()->sockfd()); Client = Clients_.find(pNf->socket().impl()->sockfd());
if( Client == end(Clients_)) if (Client == end(Clients_))
return; return;
Poco::Buffer<char> IncomingFrame(0); Poco::Buffer<char> IncomingFrame(0);
int flags; int flags;
int n; int n;
n = Client->second->WS_->receiveFrame(IncomingFrame, flags); n = Client->second->WS_->receiveFrame(IncomingFrame, flags);
auto Op = flags & Poco::Net::WebSocket::FRAME_OP_BITMASK; auto Op = flags & Poco::Net::WebSocket::FRAME_OP_BITMASK;
if (n == 0) { if (n == 0) {
poco_debug(Logger(),fmt::format("CLOSE({}): {} UI Client is closing WS connection.", Client->second->Id_, Client->second->UserName_)); poco_debug(Logger(),
fmt::format("CLOSE({}): {} UI Client is closing WS connection.",
Client->second->Id_, Client->second->UserName_));
return EndConnection(Client); return EndConnection(Client);
} }
switch (Op) { switch (Op) {
case Poco::Net::WebSocket::FRAME_OP_PING: { case Poco::Net::WebSocket::FRAME_OP_PING: {
Client->second->WS_->sendFrame("", 0, Client->second->WS_->sendFrame("", 0,
(int)Poco::Net::WebSocket::FRAME_OP_PONG | (int)Poco::Net::WebSocket::FRAME_OP_PONG |
(int)Poco::Net::WebSocket::FRAME_FLAG_FIN); (int)Poco::Net::WebSocket::FRAME_FLAG_FIN);
} break; } break;
case Poco::Net::WebSocket::FRAME_OP_PONG: { case Poco::Net::WebSocket::FRAME_OP_PONG: {
} break; } break;
case Poco::Net::WebSocket::FRAME_OP_CLOSE: { case Poco::Net::WebSocket::FRAME_OP_CLOSE: {
poco_debug(Logger(),fmt::format("CLOSE({}): {} UI Client is closing WS connection.", Client->second->Id_, Client->second->UserName_)); poco_debug(Logger(),
return EndConnection(Client); fmt::format("CLOSE({}): {} UI Client is closing WS connection.",
Client->second->Id_, Client->second->UserName_));
return EndConnection(Client);
} break; } break;
case Poco::Net::WebSocket::FRAME_OP_TEXT: { case Poco::Net::WebSocket::FRAME_OP_TEXT: {
constexpr const char *DropMessagesCommand = "drop-notifications"; constexpr const char *DropMessagesCommand = "drop-notifications";
@@ -228,80 +241,84 @@ namespace OpenWifi {
auto Tokens = Utils::Split(Frame, ':'); auto Tokens = Utils::Split(Frame, ':');
bool Expired = false; bool Expired = false;
#if not defined(TIP_SECURITY_SERVICE) #if not defined(TIP_SECURITY_SERVICE)
bool Contacted = false; bool Contacted = false;
#endif #endif
if (Tokens.size() == 2 && if (Tokens.size() == 2 &&
#if defined(TIP_SECURITY_SERVICE) #if defined(TIP_SECURITY_SERVICE)
AuthService()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_, Expired)) { AuthService()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_,
Expired)) {
#else #else
AuthClient()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_, Expired, Contacted)) { AuthClient()->IsAuthorized(Tokens[1], Client->second->UserInfo_, TID_,
Expired, Contacted)) {
#endif #endif
Client->second->Authenticated_ = true; Client->second->Authenticated_ = true;
Client->second->UserName_ = Client->second->UserInfo_.userinfo.email; Client->second->UserName_ = Client->second->UserInfo_.userinfo.email;
poco_debug(Logger(),fmt::format("START({}): {} UI Client is starting WS connection.", Client->second->Id_, Client->second->UserName_)); poco_debug(Logger(),
fmt::format("START({}): {} UI Client is starting WS connection.",
Client->second->Id_, Client->second->UserName_));
auto WelcomeMessage = NotificationTypesJSON_; auto WelcomeMessage = NotificationTypesJSON_;
WelcomeMessage.set("success", "Welcome! Bienvenue! Bienvenidos!"); WelcomeMessage.set("success", "Welcome! Bienvenue! Bienvenidos!");
std::ostringstream OS; std::ostringstream OS;
WelcomeMessage.stringify(OS); WelcomeMessage.stringify(OS);
Client->second->WS_->sendFrame(OS.str().c_str(), (int) OS.str().size()); Client->second->WS_->sendFrame(OS.str().c_str(), (int)OS.str().size());
Client->second->UserName_ = Client->second->UserInfo_.userinfo.email; Client->second->UserName_ = Client->second->UserInfo_.userinfo.email;
} else { } else {
Poco::JSON::Object WelcomeMessage; Poco::JSON::Object WelcomeMessage;
WelcomeMessage.set("error", "Invalid token. Closing connection."); WelcomeMessage.set("error", "Invalid token. Closing connection.");
std::ostringstream OS; std::ostringstream OS;
WelcomeMessage.stringify(OS); WelcomeMessage.stringify(OS);
Client->second->WS_->sendFrame(OS.str().c_str(), (int) OS.str().size()); Client->second->WS_->sendFrame(OS.str().c_str(), (int)OS.str().size());
return EndConnection(Client); return EndConnection(Client);
} }
} else { } else {
Poco::JSON::Parser P; Poco::JSON::Parser P;
auto Obj = auto Obj = P.parse(IncomingFrame.begin()).extract<Poco::JSON::Object::Ptr>();
P.parse(IncomingFrame.begin()).extract<Poco::JSON::Object::Ptr>();
if(Obj->has(DropMessagesCommand) && Obj->isArray(DropMessagesCommand)) { if (Obj->has(DropMessagesCommand) && Obj->isArray(DropMessagesCommand)) {
auto Filters = Obj->getArray(DropMessagesCommand); auto Filters = Obj->getArray(DropMessagesCommand);
Client->second->Filter_.clear(); Client->second->Filter_.clear();
for(const auto &Filter:*Filters) { for (const auto &Filter : *Filters) {
Client->second->Filter_.emplace_back( (std::uint64_t) Filter); Client->second->Filter_.emplace_back((std::uint64_t)Filter);
} }
std::sort(begin(Client->second->Filter_),end(Client->second->Filter_)); std::sort(begin(Client->second->Filter_), end(Client->second->Filter_));
return; return;
} }
std::string Answer; std::string Answer;
bool CloseConnection=false; bool CloseConnection = false;
if (Processor_ != nullptr) { if (Processor_ != nullptr) {
Processor_->Processor(Obj, Answer, CloseConnection,Client->second->UserInfo_.userinfo); Processor_->Processor(Obj, Answer, CloseConnection,
} Client->second->UserInfo_.userinfo);
if (!Answer.empty()) }
Client->second->WS_->sendFrame(Answer.c_str(), (int)Answer.size()); if (!Answer.empty())
else { Client->second->WS_->sendFrame(Answer.c_str(), (int)Answer.size());
Client->second->WS_->sendFrame("{}", 2); else {
} Client->second->WS_->sendFrame("{}", 2);
}
if(CloseConnection) { if (CloseConnection) {
return EndConnection(Client); return EndConnection(Client);
} }
} }
} break; } break;
default: { default: {
} }
} }
} catch (...) { } catch (...) {
return EndConnection(Client); return EndConnection(Client);
} }
} }
void UI_WebSocketClientServer::OnSocketShutdown([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf) { void UI_WebSocketClientServer::OnSocketShutdown(
try { [[maybe_unused]] const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf) {
std::lock_guard G(LocalMutex_); try {
std::lock_guard G(LocalMutex_);
auto Client = Clients_.find(pNf->socket().impl()->sockfd()); auto Client = Clients_.find(pNf->socket().impl()->sockfd());
if (Client == end(Clients_)) if (Client == end(Clients_))
return; return;
EndConnection(Client); EndConnection(Client);
} catch (...) { } catch (...) {
}
}
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -7,11 +7,11 @@
#include <map> #include <map>
#include <string> #include <string>
#include "Poco/Runnable.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/WebSocket.h"
#include "Poco/JSON/Object.h" #include "Poco/JSON/Object.h"
#include "Poco/Net/SocketNotification.h" #include "Poco/Net/SocketNotification.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/WebSocket.h"
#include "Poco/Runnable.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h" #include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
@@ -21,25 +21,28 @@ namespace OpenWifi {
class UI_WebSocketClientProcessor { class UI_WebSocketClientProcessor {
public: public:
virtual void Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done , const SecurityObjects::UserInfo & UserInfo) = 0; virtual void Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done,
const SecurityObjects::UserInfo &UserInfo) = 0;
private: private:
}; };
struct UI_WebSocketClientInfo { struct UI_WebSocketClientInfo {
std::unique_ptr<Poco::Net::WebSocket> WS_ = nullptr; std::unique_ptr<Poco::Net::WebSocket> WS_ = nullptr;
std::string Id_; std::string Id_;
std::string UserName_; std::string UserName_;
bool Authenticated_ = false; bool Authenticated_ = false;
bool SocketRegistered_=false; bool SocketRegistered_ = false;
std::vector<std::uint64_t> Filter_; std::vector<std::uint64_t> Filter_;
SecurityObjects::UserInfoAndPolicy UserInfo_; SecurityObjects::UserInfoAndPolicy UserInfo_;
UI_WebSocketClientInfo(Poco::Net::WebSocket &WS, const std::string &Id, const std::string &username) { UI_WebSocketClientInfo(Poco::Net::WebSocket &WS, const std::string &Id,
WS_ = std::make_unique<Poco::Net::WebSocket>(WS); const std::string &username) {
Id_ = Id; WS_ = std::make_unique<Poco::Net::WebSocket>(WS);
UserName_ = username; Id_ = Id;
} UserName_ = username;
}; }
};
class UI_WebSocketClientServer : public SubSystemServer, Poco::Runnable { class UI_WebSocketClientServer : public SubSystemServer, Poco::Runnable {
@@ -49,26 +52,26 @@ namespace OpenWifi {
return instance_; return instance_;
} }
bool IsAnyoneConnected() { bool IsAnyoneConnected() { return UsersConnected_; }
return UsersConnected_;
}
int Start() override; int Start() override;
void Stop() override; void Stop() override;
void run() override; void run() override;
Poco::Net::SocketReactor & Reactor() { return Reactor_; } Poco::Net::SocketReactor &Reactor() { return Reactor_; }
void NewClient(Poco::Net::WebSocket &WS, const std::string &Id, const std::string &UserName, std::uint64_t TID); void NewClient(Poco::Net::WebSocket &WS, const std::string &Id, const std::string &UserName,
std::uint64_t TID);
void SetProcessor(UI_WebSocketClientProcessor *F); void SetProcessor(UI_WebSocketClientProcessor *F);
[[nodiscard]] inline bool GeoCodeEnabled() const { return GeoCodeEnabled_; } [[nodiscard]] inline bool GeoCodeEnabled() const { return GeoCodeEnabled_; }
[[nodiscard]] inline std::string GoogleApiKey() const { return GoogleApiKey_; } [[nodiscard]] inline std::string GoogleApiKey() const { return GoogleApiKey_; }
template <typename T> bool template <typename T>
SendUserNotification(const std::string &userName, const WebSocketNotification<T> &Notification) { bool SendUserNotification(const std::string &userName,
const WebSocketNotification<T> &Notification) {
Poco::JSON::Object Payload; Poco::JSON::Object Payload;
Notification.to_json(Payload); Notification.to_json(Payload);
Poco::JSON::Object Msg; Poco::JSON::Object Msg;
Msg.set("notification",Payload); Msg.set("notification", Payload);
std::ostringstream OO; std::ostringstream OO;
Msg.stringify(OO); Msg.stringify(OO);
@@ -76,58 +79,59 @@ namespace OpenWifi {
} }
template <typename T> void SendNotification(const WebSocketNotification<T> &Notification) { template <typename T> void SendNotification(const WebSocketNotification<T> &Notification) {
Poco::JSON::Object Payload; Poco::JSON::Object Payload;
Notification.to_json(Payload); Notification.to_json(Payload);
Poco::JSON::Object Msg; Poco::JSON::Object Msg;
Msg.set("notification",Payload); Msg.set("notification", Payload);
std::ostringstream OO; std::ostringstream OO;
Msg.stringify(OO); Msg.stringify(OO);
SendToAll(Notification.type_id, OO.str()); SendToAll(Notification.type_id, OO.str());
} }
[[nodiscard]] bool SendToUser(const std::string &userName, std::uint64_t id, const std::string &Payload); [[nodiscard]] bool SendToUser(const std::string &userName, std::uint64_t id,
const std::string &Payload);
void SendToAll(std::uint64_t id, const std::string &Payload); void SendToAll(std::uint64_t id, const std::string &Payload);
struct NotificationEntry { struct NotificationEntry {
std::uint64_t id=0; std::uint64_t id = 0;
std::string helper; std::string helper;
}; };
using ClientList = std::map<int,std::unique_ptr<UI_WebSocketClientInfo>>; using ClientList = std::map<int, std::unique_ptr<UI_WebSocketClientInfo>>;
using NotificationTypeIdVec = std::vector<NotificationEntry>; using NotificationTypeIdVec = std::vector<NotificationEntry>;
void RegisterNotifications(const NotificationTypeIdVec & Notifications); void RegisterNotifications(const NotificationTypeIdVec &Notifications);
bool IsFiltered(std::uint64_t id, const UI_WebSocketClientInfo &Client); bool IsFiltered(std::uint64_t id, const UI_WebSocketClientInfo &Client);
private: private:
volatile bool Running_ = false; volatile bool Running_ = false;
std::atomic_uint64_t UsersConnected_=0; std::atomic_uint64_t UsersConnected_ = 0;
Poco::Net::SocketReactor Reactor_; Poco::Net::SocketReactor Reactor_;
Poco::Thread ReactorThread_; Poco::Thread ReactorThread_;
Poco::Thread CleanerThread_; Poco::Thread CleanerThread_;
std::recursive_mutex LocalMutex_; std::recursive_mutex LocalMutex_;
bool GeoCodeEnabled_ = false; bool GeoCodeEnabled_ = false;
std::string GoogleApiKey_; std::string GoogleApiKey_;
ClientList Clients_; ClientList Clients_;
UI_WebSocketClientProcessor *Processor_ = nullptr; UI_WebSocketClientProcessor *Processor_ = nullptr;
NotificationTypeIdVec NotificationTypes_; NotificationTypeIdVec NotificationTypes_;
Poco::JSON::Object NotificationTypesJSON_; Poco::JSON::Object NotificationTypesJSON_;
std::vector<ClientList::iterator> ToBeRemoved_; std::vector<ClientList::iterator> ToBeRemoved_;
std::uint64_t TID_=0; std::uint64_t TID_ = 0;
UI_WebSocketClientServer() noexcept; UI_WebSocketClientServer() noexcept;
void EndConnection(ClientList::iterator Client); void EndConnection(ClientList::iterator Client);
void OnSocketReadable(const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf); void OnSocketReadable(const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf);
void OnSocketShutdown(const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf); void OnSocketShutdown(const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf);
void OnSocketError(const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf); void OnSocketError(const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf);
ClientList::iterator FindWSClient( std::lock_guard<std::recursive_mutex> &G, int ClientSocket); ClientList::iterator FindWSClient(std::lock_guard<std::recursive_mutex> &G,
int ClientSocket);
void SortNotifications(); void SortNotifications();
}; };
inline auto UI_WebSocketClientServer() { return UI_WebSocketClientServer::instance(); } inline auto UI_WebSocketClientServer() { return UI_WebSocketClientServer::instance(); }
}; }; // namespace OpenWifi

View File

@@ -5,61 +5,64 @@
#pragma once #pragma once
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "framework/UI_WebSocketClientServer.h"
#include "framework/UI_WebSocketClientNotifications.h" #include "framework/UI_WebSocketClientNotifications.h"
#include "framework/UI_WebSocketClientServer.h"
namespace OpenWifi { namespace OpenWifi {
class WebSocketLogger : public Poco::Channel { class WebSocketLogger : public Poco::Channel {
public: public:
WebSocketLogger() {}
WebSocketLogger() { ~WebSocketLogger() {}
}
~WebSocketLogger() { std::string getProperty([[maybe_unused]] const std::string &p) const {
}
std::string getProperty( [[maybe_unused]] const std::string &p ) const {
std::cout << "WS getProperty" << std::endl; std::cout << "WS getProperty" << std::endl;
return ""; return "";
} }
void close() final { void close() final {}
}
void open() final { void open() final {}
}
static std::string to_string(Poco::Message::Priority p) { static std::string to_string(Poco::Message::Priority p) {
switch(p) { switch (p) {
case Poco::Message::PRIO_INFORMATION: return "information"; case Poco::Message::PRIO_INFORMATION:
case Poco::Message::PRIO_CRITICAL: return "critical"; return "information";
case Poco::Message::PRIO_DEBUG: return "debug"; case Poco::Message::PRIO_CRITICAL:
case Poco::Message::PRIO_ERROR: return "error"; return "critical";
case Poco::Message::PRIO_FATAL: return "fatal"; case Poco::Message::PRIO_DEBUG:
case Poco::Message::PRIO_NOTICE: return "notice"; return "debug";
case Poco::Message::PRIO_TRACE: return "trace"; case Poco::Message::PRIO_ERROR:
case Poco::Message::PRIO_WARNING: return "warning"; return "error";
default: return "none"; case Poco::Message::PRIO_FATAL:
return "fatal";
case Poco::Message::PRIO_NOTICE:
return "notice";
case Poco::Message::PRIO_TRACE:
return "trace";
case Poco::Message::PRIO_WARNING:
return "warning";
default:
return "none";
} }
} }
struct NotificationLogMessage { struct NotificationLogMessage {
std::string msg; std::string msg;
std::string level; std::string level;
std::uint64_t timestamp; std::uint64_t timestamp;
std::string source; std::string source;
std::string thread_name; std::string thread_name;
std::uint64_t thread_id=0; std::uint64_t thread_id = 0;
inline void to_json(Poco::JSON::Object &Obj) const { inline void to_json(Poco::JSON::Object &Obj) const {
RESTAPI_utils::field_to_json(Obj,"msg", msg); RESTAPI_utils::field_to_json(Obj, "msg", msg);
RESTAPI_utils::field_to_json(Obj,"level", level); RESTAPI_utils::field_to_json(Obj, "level", level);
RESTAPI_utils::field_to_json(Obj,"timestamp", timestamp); RESTAPI_utils::field_to_json(Obj, "timestamp", timestamp);
RESTAPI_utils::field_to_json(Obj,"source", source); RESTAPI_utils::field_to_json(Obj, "source", source);
RESTAPI_utils::field_to_json(Obj,"thread_name", thread_name); RESTAPI_utils::field_to_json(Obj, "thread_name", thread_name);
RESTAPI_utils::field_to_json(Obj,"thread_id", thread_id); RESTAPI_utils::field_to_json(Obj, "thread_id", thread_id);
} }
inline bool from_json(const Poco::JSON::Object::Ptr &Obj) { inline bool from_json(const Poco::JSON::Object::Ptr &Obj) {
@@ -71,18 +74,18 @@ namespace OpenWifi {
RESTAPI_utils::field_from_json(Obj, "thread_name", thread_name); RESTAPI_utils::field_from_json(Obj, "thread_name", thread_name);
RESTAPI_utils::field_from_json(Obj, "thread_id", thread_id); RESTAPI_utils::field_from_json(Obj, "thread_id", thread_id);
return true; return true;
} catch(...) { } catch (...) {
} }
return false; return false;
} }
}; };
typedef WebSocketNotification<NotificationLogMessage> WebSocketClientNotificationLogMessage_t; typedef WebSocketNotification<NotificationLogMessage>
WebSocketClientNotificationLogMessage_t;
void log(const Poco::Message &m) final { void log(const Poco::Message &m) final {
if(UI_WebSocketClientServer()->IsAnyoneConnected()) { if (UI_WebSocketClientServer()->IsAnyoneConnected()) {
WebSocketClientNotificationLogMessage_t Msg; WebSocketClientNotificationLogMessage_t Msg;
Msg.content.msg = m.getText(); Msg.content.msg = m.getText();
Msg.content.level = WebSocketLogger::to_string(m.getPriority()); Msg.content.level = WebSocketLogger::to_string(m.getPriority());
Msg.content.timestamp = m.getTime().epochTime(); Msg.content.timestamp = m.getTime().epochTime();
@@ -94,14 +97,15 @@ namespace OpenWifi {
} }
} }
void setProperty([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) { void setProperty([[maybe_unused]] const std::string &name,
[[maybe_unused]] const std::string &value) {
std::cout << "WS setProperty" << std::endl; std::cout << "WS setProperty" << std::endl;
} }
private: private:
std::recursive_mutex Mutex_; std::recursive_mutex Mutex_;
}; };
// inline auto WebSocketLogger() { return WebSocketLogger::instance(); } // inline auto WebSocketLogger() { return WebSocketLogger::instance(); }
} } // namespace OpenWifi

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -4,145 +4,140 @@
#pragma once #pragma once
#include <string>
#include <fstream> #include <fstream>
#include <iostream>
#include <iomanip> #include <iomanip>
#include <iostream>
#include <random> #include <random>
#include <regex> #include <regex>
#include <thread>
#include <shared_mutex> #include <shared_mutex>
#include <string>
#include <thread>
#include "Poco/Thread.h"
#include "Poco/StringTokenizer.h"
#include "Poco/String.h"
#include "Poco/SHA2Engine.h"
#include "Poco/Message.h"
#include "Poco/StreamCopier.h"
#include "Poco/File.h"
#include "Poco/Net/NetworkInterface.h"
#include "Poco/URI.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Base64Decoder.h" #include "Poco/Base64Decoder.h"
#include "Poco/Base64Encoder.h" #include "Poco/Base64Encoder.h"
#include "Poco/File.h"
#include "Poco/Message.h"
#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPSClientSession.h"
#include "Poco/Net/NetworkInterface.h"
#include "Poco/SHA2Engine.h"
#include "Poco/StreamCopier.h"
#include "Poco/String.h"
#include "Poco/StringTokenizer.h"
#include "Poco/Thread.h"
#include "Poco/URI.h"
#include "Poco/zlib.h" #include "Poco/zlib.h"
#include "framework/ow_constants.h"
#include "framework/OpenWifiTypes.h" #include "framework/OpenWifiTypes.h"
#include "framework/ow_constants.h"
namespace OpenWifi::Utils { namespace OpenWifi::Utils {
inline uint64_t Now() { return std::time(nullptr); }; inline uint64_t Now() { return std::time(nullptr); };
bool NormalizeMac(std::string & Mac); bool NormalizeMac(std::string &Mac);
inline void SetThreadName(const char *name) { inline void SetThreadName(const char *name) {
#ifdef __linux__ #ifdef __linux__
Poco::Thread::current()->setName(name); Poco::Thread::current()->setName(name);
pthread_setname_np(pthread_self(), name); pthread_setname_np(pthread_self(), name);
#endif #endif
#ifdef __APPLE__ #ifdef __APPLE__
Poco::Thread::current()->setName(name); Poco::Thread::current()->setName(name);
pthread_setname_np(name); pthread_setname_np(name);
#endif #endif
} }
inline void SetThreadName(Poco::Thread &thr, const char *name) { inline void SetThreadName(Poco::Thread &thr, const char *name) {
#ifdef __linux__ #ifdef __linux__
thr.setName(name); thr.setName(name);
pthread_setname_np(thr.tid(), name); pthread_setname_np(thr.tid(), name);
#endif #endif
#ifdef __APPLE__ #ifdef __APPLE__
thr.setName(name); thr.setName(name);
#endif #endif
} }
enum MediaTypeEncodings { enum MediaTypeEncodings { PLAIN, BINARY, BASE64 };
PLAIN,
BINARY,
BASE64
};
struct MediaTypeEncoding { struct MediaTypeEncoding {
MediaTypeEncodings Encoding=PLAIN; MediaTypeEncodings Encoding = PLAIN;
std::string ContentType; std::string ContentType;
}; };
[[nodiscard]] bool ValidSerialNumber(const std::string &Serial); [[nodiscard]] bool ValidSerialNumber(const std::string &Serial);
[[nodiscard]] bool ValidUUID(const std::string &UUID); [[nodiscard]] bool ValidUUID(const std::string &UUID);
[[nodiscard]] bool ValidHostname(const std::string &hostname); [[nodiscard]] bool ValidHostname(const std::string &hostname);
template <typename ...Args> std::string ComputeHash(Args&&... args) { template <typename... Args> std::string ComputeHash(Args &&...args) {
Poco::SHA2Engine E; Poco::SHA2Engine E;
auto as_string = [](auto p) { auto as_string = [](auto p) {
if constexpr(std::is_arithmetic_v<decltype(p)>) { if constexpr (std::is_arithmetic_v<decltype(p)>) {
return std::to_string(p); return std::to_string(p);
} else { } else {
return p; return p;
} }
}; };
(E.update(as_string(args)),...); (E.update(as_string(args)), ...);
return Poco::SHA2Engine::digestToHex(E.digest()); return Poco::SHA2Engine::digestToHex(E.digest());
} }
[[nodiscard]] std::vector<std::string> Split(const std::string &List, char Delimiter=',' ); [[nodiscard]] std::vector<std::string> Split(const std::string &List, char Delimiter = ',');
[[nodiscard]] std::string FormatIPv6(const std::string & I ); [[nodiscard]] std::string FormatIPv6(const std::string &I);
void padTo(std::string& str, size_t num, char paddingChar = '\0'); void padTo(std::string &str, size_t num, char paddingChar = '\0');
[[nodiscard]] std::string SerialToMAC(const std::string &Serial); [[nodiscard]] std::string SerialToMAC(const std::string &Serial);
uint64_t MACToInt(const std::string &MAC); uint64_t MACToInt(const std::string &MAC);
[[nodiscard]] std::string ToHex(const std::vector<unsigned char> & B); [[nodiscard]] std::string ToHex(const std::vector<unsigned char> &B);
using byte = std::uint8_t; using byte = std::uint8_t;
[[nodiscard]] std::string base64encode(const byte *input, uint32_t size); [[nodiscard]] std::string base64encode(const byte *input, uint32_t size);
[[nodiscard]] std::vector<byte> base64decode(const std::string& input);; [[nodiscard]] std::vector<byte> base64decode(const std::string &input);
bool ParseTime(const std::string &Time, int & Hours, int & Minutes, int & Seconds); ;
bool ParseDate(const std::string &Time, int & Year, int & Month, int & Day); bool ParseTime(const std::string &Time, int &Hours, int &Minutes, int &Seconds);
bool CompareTime( int H1, int H2, int M1, int M2, int S1, int S2); bool ParseDate(const std::string &Time, int &Year, int &Month, int &Day);
bool CompareTime(int H1, int H2, int M1, int M2, int S1, int S2);
[[nodiscard]] std::string LogLevelToString(int Level); [[nodiscard]] std::string LogLevelToString(int Level);
[[nodiscard]] uint64_t SerialNumberToInt(const std::string & S); [[nodiscard]] uint64_t SerialNumberToInt(const std::string &S);
[[nodiscard]] std::string IntToSerialNumber(uint64_t S); [[nodiscard]] std::string IntToSerialNumber(uint64_t S);
[[nodiscard]] bool SerialNumberMatch(const std::string &S1, const std::string &S2, int Bits=2); [[nodiscard]] bool SerialNumberMatch(const std::string &S1, const std::string &S2,
[[nodiscard]] uint64_t SerialNumberToOUI(const std::string & S); int Bits = 2);
[[nodiscard]] uint64_t SerialNumberToOUI(const std::string &S);
[[nodiscard]] uint64_t GetDefaultMacAsInt64(); [[nodiscard]] uint64_t GetDefaultMacAsInt64();
[[nodiscard]] uint64_t InitializeSystemId(); [[nodiscard]] uint64_t InitializeSystemId();
[[nodiscard]] uint64_t GetSystemId(); [[nodiscard]] uint64_t GetSystemId();
[[nodiscard]] bool ValidEMailAddress(const std::string &email); [[nodiscard]] bool ValidEMailAddress(const std::string &email);
[[nodiscard]] std::string LoadFile( const Poco::File & F); [[nodiscard]] std::string LoadFile(const Poco::File &F);
void ReplaceVariables( std::string & Content , const Types::StringPairVec & P); void ReplaceVariables(std::string &Content, const Types::StringPairVec &P);
[[nodiscard]] MediaTypeEncoding FindMediaType(const Poco::File &F); [[nodiscard]] MediaTypeEncoding FindMediaType(const Poco::File &F);
[[nodiscard]] std::string BinaryFileToHexString(const Poco::File &F); [[nodiscard]] std::string BinaryFileToHexString(const Poco::File &F);
[[nodiscard]] std::string SecondsToNiceText(uint64_t Seconds); [[nodiscard]] std::string SecondsToNiceText(uint64_t Seconds);
[[nodiscard]] bool wgets(const std::string &URL, std::string &Response); [[nodiscard]] bool wgets(const std::string &URL, std::string &Response);
[[nodiscard]] bool wgetfile(const Poco::URI &uri, const std::string &FileName); [[nodiscard]] bool wgetfile(const Poco::URI &uri, const std::string &FileName);
[[nodiscard]] bool IsAlphaNumeric(const std::string &s); [[nodiscard]] bool IsAlphaNumeric(const std::string &s);
[[nodiscard]] std::string SanitizeToken(const std::string &Token); [[nodiscard]] std::string SanitizeToken(const std::string &Token);
[[nodiscard]] bool ValidateURI(const std::string &uri); [[nodiscard]] bool ValidateURI(const std::string &uri);
[[nodiscard]] std::uint64_t ConvertDate(const std::string &d); [[nodiscard]] std::uint64_t ConvertDate(const std::string &d);
template< typename T > template <typename T> std::string int_to_hex(T i) {
std::string int_to_hex( T i )
{
std::stringstream stream; std::stringstream stream;
stream << std::setfill ('0') << std::setw(12) stream << std::setfill('0') << std::setw(12) << std::hex << i;
<< std::hex << i;
return stream.str(); return stream.str();
} }
inline bool SpinLock_Read(std::shared_mutex &M, volatile bool &Flag, uint64_t wait_ms=100) { inline bool SpinLock_Read(std::shared_mutex &M, volatile bool &Flag, uint64_t wait_ms = 100) {
while(!M.try_lock_shared() && Flag) { while (!M.try_lock_shared() && Flag) {
Poco::Thread::yield(); Poco::Thread::yield();
Poco::Thread::trySleep((long)wait_ms); Poco::Thread::trySleep((long)wait_ms);
} }
return Flag; return Flag;
} }
inline bool SpinLock_Write(std::shared_mutex &M, volatile bool &Flag, uint64_t wait_ms=100) { inline bool SpinLock_Write(std::shared_mutex &M, volatile bool &Flag, uint64_t wait_ms = 100) {
while(!M.try_lock() && Flag) { while (!M.try_lock() && Flag) {
Poco::Thread::yield(); Poco::Thread::yield();
Poco::Thread::trySleep(wait_ms); Poco::Thread::trySleep(wait_ms);
} }
@@ -150,5 +145,5 @@ namespace OpenWifi::Utils {
} }
bool ExtractBase64CompressedData(const std::string &CompressedData, bool ExtractBase64CompressedData(const std::string &CompressedData,
std::string &UnCompressedData, uint64_t compress_sz ); std::string &UnCompressedData, uint64_t compress_sz);
} } // namespace OpenWifi::Utils

View File

@@ -3,25 +3,25 @@
// //
#include "SDK_fms.h" #include "SDK_fms.h"
#include "framework/OpenAPIRequests.h"
#include "framework/MicroServiceNames.h" #include "framework/MicroServiceNames.h"
#include "framework/OpenAPIRequests.h"
namespace OpenWifi::SDK::FMS { namespace OpenWifi::SDK::FMS {
namespace Firmware { namespace Firmware {
bool GetDeviceInformation(RESTAPIHandler *client, const Types::UUID_t & SerialNumber, FMSObjects::DeviceInformation & DI) { bool GetDeviceInformation(RESTAPIHandler *client, const Types::UUID_t &SerialNumber,
OpenAPIRequestGet Req( uSERVICE_FIRMWARE, FMSObjects::DeviceInformation &DI) {
"/api/v1/deviceInformation/" + SerialNumber, OpenAPIRequestGet Req(uSERVICE_FIRMWARE, "/api/v1/deviceInformation/" + SerialNumber,
{}, {}, 10000);
10000);
Poco::JSON::Object::Ptr Response; Poco::JSON::Object::Ptr Response;
auto StatusCode = Req.Do(Response,client== nullptr ? "" : client->UserInfo_.webtoken.access_token_); auto StatusCode =
if( StatusCode == Poco::Net::HTTPResponse::HTTP_OK) { Req.Do(Response, client == nullptr ? "" : client->UserInfo_.webtoken.access_token_);
return DI.from_json(Response); if (StatusCode == Poco::Net::HTTPResponse::HTTP_OK) {
} return DI.from_json(Response);
return false; }
} return false;
} }
} // namespace Firmware
} } // namespace OpenWifi::SDK::FMS

View File

@@ -4,14 +4,14 @@
#pragma once #pragma once
#include "framework/RESTAPI_Handler.h"
#include "RESTObjects/RESTAPI_FMSObjects.h" #include "RESTObjects/RESTAPI_FMSObjects.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi::SDK::FMS { namespace OpenWifi::SDK::FMS {
namespace Firmware { namespace Firmware {
bool GetDeviceInformation(RESTAPIHandler *client, const Types::UUID_t & SerialNumber, FMSObjects::DeviceInformation & DI); bool GetDeviceInformation(RESTAPIHandler *client, const Types::UUID_t &SerialNumber,
} FMSObjects::DeviceInformation &DI);
}
}
} // namespace OpenWifi::SDK::FMS

Some files were not shown because too many files have changed in this diff Show More