Compare commits

..

4 Commits

Author SHA1 Message Date
TIP Automation User
9bc5086f24 Chg: update image tag in helm values to v2.9.0 2023-03-31 19:26:05 +00:00
TIP Automation User
71eefca353 Chg: update image tag in helm values to v2.9.0-RC2 2023-03-20 16:53:40 +00:00
Stephane Bourque
1cccd2aa73 Merge pull request #88 from Telecominfraproject/main
https://telecominfraproject.atlassian.net/browse/WIFI-12342
2023-03-02 11:30:51 -08:00
TIP Automation User
198888d554 Chg: update image tag in helm values to v2.9.0-RC1 2023-02-28 18:27:42 +00:00
125 changed files with 6790 additions and 12317 deletions

View File

@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.13) cmake_minimum_required(VERSION 3.13)
project(owprov VERSION 3.0.0) project(owprov VERSION 2.9.0)
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)
@@ -37,7 +37,7 @@ if(GIT_FOUND AND EXISTS "${PROJECT_SOURCE_DIR}/.git")
string(REGEX REPLACE "\n$" "" GIT_HASH "${GIT_HASH}") string(REGEX REPLACE "\n$" "" GIT_HASH "${GIT_HASH}")
endif() endif()
add_definitions(-DAWS_CUSTOM_MEMORY_MANAGEMENT -DBOOST_NO_CXX98_FUNCTION_BASE=1) add_definitions(-DAWS_CUSTOM_MEMORY_MANAGEMENT)
find_package(OpenSSL REQUIRED) find_package(OpenSSL REQUIRED)
find_package(ZLIB REQUIRED) find_package(ZLIB REQUIRED)
@@ -117,7 +117,6 @@ add_executable(owprov
src/framework/MicroServiceExtra.h src/framework/MicroServiceExtra.h
src/framework/ConfigurationValidator.cpp src/framework/ConfigurationValidator.cpp
src/framework/ConfigurationValidator.h src/framework/ConfigurationValidator.h
src/framework/default_device_types.h
src/UI_Prov_WebSocketNotifications.h src/UI_Prov_WebSocketNotifications.h
src/UI_Prov_WebSocketNotifications.cpp src/UI_Prov_WebSocketNotifications.cpp
src/RESTObjects/RESTAPI_SecurityObjects.h src/RESTObjects/RESTAPI_SecurityObjects.cpp src/RESTObjects/RESTAPI_SecurityObjects.h src/RESTObjects/RESTAPI_SecurityObjects.cpp
@@ -209,37 +208,12 @@ add_executable(owprov
src/ProvWebSocketClient.cpp src/ProvWebSocketClient.h src/ProvWebSocketClient.cpp src/ProvWebSocketClient.h
src/Tasks/VenueRebooter.h src/Tasks/VenueUpgrade.h src/Tasks/VenueRebooter.h src/Tasks/VenueUpgrade.h
src/sdks/SDK_fms.cpp src/sdks/SDK_fms.h src/sdks/SDK_fms.cpp src/sdks/SDK_fms.h
src/RESTAPI/RESTAPI_overrides_handler.cpp src/RESTAPI/RESTAPI_overrides_handler.h src/RESTAPI/RESTAPI_overrides_handler.cpp src/RESTAPI/RESTAPI_overrides_handler.h)
src/storage/storage_glblraccounts.cpp src/storage/storage_glblraccounts.h
src/storage/storage_glblrcerts.cpp src/storage/storage_glblrcerts.h
src/RESTAPI/RESTAPI_openroaming_gr_list_acct_handler.cpp src/RESTAPI/RESTAPI_openroaming_gr_list_acct_handler.h
src/RESTAPI/RESTAPI_openroaming_gr_acct_handler.cpp src/RESTAPI/RESTAPI_openroaming_gr_acct_handler.h
src/RESTAPI/RESTAPI_openroaming_gr_list_certificates.cpp src/RESTAPI/RESTAPI_openroaming_gr_list_certificates.h
src/RESTAPI/RESTAPI_openroaming_gr_cert_handler.cpp src/RESTAPI/RESTAPI_openroaming_gr_cert_handler.h
src/RESTAPI/RESTAPI_openroaming_orion_list_acct_handler.cpp src/RESTAPI/RESTAPI_openroaming_orion_list_acct_handler.h
src/RESTAPI/RESTAPI_openroaming_orion_acct_handler.cpp src/RESTAPI/RESTAPI_openroaming_orion_acct_handler.h
src/storage/storage_orion_accounts.cpp src/storage/storage_orion_accounts.h
src/storage/storage_radius_endpoints.cpp
src/storage/storage_radius_endpoints.h
src/RESTAPI/RESTAPI_radiusendpoint_list_handler.cpp
src/RESTAPI/RESTAPI_radiusendpoint_list_handler.h
src/RESTAPI/RESTAPI_radius_endpoint_handler.cpp
src/RESTAPI/RESTAPI_radius_endpoint_handler.h
src/RadiusEndpointTypes/GlobalReach.cpp src/RadiusEndpointTypes/GlobalReach.h
src/RadiusEndpointTypes/OrionWifi.h
src/RadiusEndpointUpdater.cpp
src/RadiusEndpointUpdater.h
src/RadiusEndpointTypes/Radsec.cpp
src/RadiusEndpointTypes/Radsec.h
src/RadiusEndpointTypes/GenericRadius.cpp
src/RadiusEndpointTypes/GenericRadius.h
)
target_link_libraries(owprov PUBLIC target_link_libraries(owprov PUBLIC
${Poco_LIBRARIES} ${Poco_LIBRARIES}
${MySQL_LIBRARIES} ${MySQL_LIBRARIES}
${ZLIB_LIBRARIES} ${ZLIB_LIBRARIES}
CppKafka::cppkafka CppKafka::cppkafka
resolv
fmt::fmt) fmt::fmt)

2
build
View File

@@ -1 +1 @@
10 21

View File

@@ -1,84 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PayloadContent</key>
<array>
<dict>
<key>AutoJoin</key>
<true/>
<key>CaptiveBypass</key>
<false/>
<key>DisableAssociationMACRandomization</key>
<false/>
<key>DisplayedOperatorName</key>
<string>OpenRo.am</string>
<key>DomainName</key>
<string>openro.am</string>
<key>EAPClientConfiguration</key>
<dict>
<key>AcceptEAPTypes</key>
<array>
<integer>21</integer>
</array>
<key>OuterIdentity</key>
<string>anonymous@openro.am</string>
<key>TLSMaximumVersion</key>
<string>1.2</string>
<key>TLSMinimumVersion</key>
<string>1.2</string>
<key>TTLSInnerAuthentication</key>
<string>MSCHAPv2</string>
<key>UserName</key>
<string>420a5371-47d4-4d1d-b234-d17be4e54bb3@openro.am</string>
<key>UserPassword</key>
<string>XaHBCFhgGxi-mCK9XXdQ8</string>
</dict>
<key>EncryptionType</key>
<string>WPA2</string>
<key>HIDDEN_NETWORK</key>
<false/>
<key>IsHotspot</key>
<true/>
<key>NAIRealmNames</key>
<array>
<string>openro.am</string>
</array>
<key>PayloadDescription</key>
<string>Configures Wi-Fi settings</string>
<key>PayloadDisplayName</key>
<string>Wi-Fi</string>
<key>PayloadIdentifier</key>
<string>com.apple.wifi.managed.12788EED-2E0C-4370-9411-4EEFC8D9ABB0</string>
<key>PayloadType</key>
<string>com.apple.wifi.managed</string>
<key>PayloadUUID</key>
<string>12788EED-2E0C-4370-9411-4EEFC8D9ABB0</string>
<key>PayloadVersion</key>
<integer>1</integer>
<key>ProxyType</key>
<string>None</string>
<key>RoamingConsortiumOIs</key>
<array>
<string>5A03BA0000</string>
</array>
<key>ServiceProviderRoamingEnabled</key>
<true/>
</dict>
</array>
<key>PayloadDisplayName</key>
<string>OpenRo.am Test</string>
<key>PayloadIdentifier</key>
<string>openroam.44A21054-2F3F-437F-822A-C2F6766A2A23</string>
<key>PayloadOrganization</key>
<string>OpenRo.am</string>
<key>PayloadRemovalDisallowed</key>
<false/>
<key>PayloadType</key>
<string>Configuration</string>
<key>PayloadUUID</key>
<string>1D460B0F-9311-4FD2-A75D-BADA866BC31C</string>
<key>PayloadVersion</key>
<integer>1</integer>
</dict>
</plist>

View File

@@ -42,7 +42,6 @@ if [[ "$TEMPLATE_CONFIG" = 'true' ]]; then
STORAGE_TYPE_MYSQL_PASSWORD=${STORAGE_TYPE_MYSQL_PASSWORD:-"owprov"} \ STORAGE_TYPE_MYSQL_PASSWORD=${STORAGE_TYPE_MYSQL_PASSWORD:-"owprov"} \
STORAGE_TYPE_MYSQL_DATABASE=${STORAGE_TYPE_MYSQL_DATABASE:-"owprov"} \ STORAGE_TYPE_MYSQL_DATABASE=${STORAGE_TYPE_MYSQL_DATABASE:-"owprov"} \
STORAGE_TYPE_MYSQL_PORT=${STORAGE_TYPE_MYSQL_PORT:-"3306"} \ STORAGE_TYPE_MYSQL_PORT=${STORAGE_TYPE_MYSQL_PORT:-"3306"} \
RRM_PROVIDERS=${RRM_PROVIDERS:-"owrrm"} \
envsubst < /owprov.properties.tmpl > $OWPROV_CONFIG/owprov.properties envsubst < /owprov.properties.tmpl > $OWPROV_CONFIG/owprov.properties
fi fi

View File

@@ -9,7 +9,7 @@ fullnameOverride: ""
images: images:
owprov: owprov:
repository: tip-tip-wlan-cloud-ucentral.jfrog.io/owprov repository: tip-tip-wlan-cloud-ucentral.jfrog.io/owprov
tag: v3.0.0 tag: v2.9.0
pullPolicy: Always pullPolicy: Always
# regcred: # regcred:
# registry: tip-tip-wlan-cloud-ucentral.jfrog.io # registry: tip-tip-wlan-cloud-ucentral.jfrog.io

View File

@@ -1,407 +0,0 @@
openapi: 3.0.1
info:
title: OpenWiFi RadiusEndpointTypes Provisioning Model for Global Reach
description: Definitions and APIs to Open Roaming WiFi.
version: 2.5.0
license:
name: BSD3
url: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
servers:
- url: 'https://localhost:16005/api/v1'
security:
- bearerAuth: []
- ApiKeyAuth: []
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
responses:
NotFound:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/NotFound'
Unauthorized:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/Unauthorized'
Success:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/Success'
BadRequest:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/BadRequest'
schemas:
GLBLRAccountInfo:
type: object
properties:
allOf:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-owprov/blob/main/openpapi/owprov.yaml#/components/schemas/ObjectInfo'
privateKey:
type: string
country:
type: string
province:
type: string
city:
type: string
organization:
type: string
commonName:
type: string
CSR:
type: string
CSRPrivateKey:
type: string
CSRPublicKey:
type: string
GlobalReachAcctId:
type: string
GLBLRCertificateInfo:
type: object
properties:
id:
type: string
format: uuid
name:
type: string
accountId:
type: string
format: uuid
csr:
type: string
certificate:
type: string
certificateChain:
type: string
certificateId:
type: string
expiresAt:
type: integer
format: int64
created:
type: integer
format: int64
paths:
/openroaming/globalreach/accounts:
get:
tags:
- RadiusEndpointTypes-Global Reach
operationId: getOpenRoamingGlobalReachAccountList
summary: Retrieve account list.
parameters:
- in: query
description: Pagination start (starts at 1. If not specified, 1 is assumed)
name: offset
schema:
type: integer
required: false
- in: query
description: Maximum number of entries to return (if absent, no limit is assumed)
name: limit
schema:
type: integer
required: false
- in: query
description: return the number of accounts
name: countOnly
schema:
type: boolean
required: false
responses:
200:
description: The list of accounts
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/GLBLRAccountInfo'
$ref: '#/components/responses/Success'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
/openroaming/globalreach/account/{name}:
get:
tags:
- RadiusEndpointTypes-Global Reach
operationId: getOpenRoamingGlobalReachAccount
summary: Retrieve account information.
parameters:
- in: path
description: The account name
name: name
schema:
type: string
required: true
responses:
200:
$ref: '#/components/schemas/GLBLRAccountInfo'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
delete:
tags:
- RadiusEndpointTypes-Global Reach
operationId: deleteOpenRoamingGlobalReachAccount
summary: Delete account information.
parameters:
- in: path
description: The account name
name: name
schema:
type: string
required: true
responses:
200:
$ref: '#/components/responses/Success'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
post:
tags:
- RadiusEndpointTypes-Global Reach
operationId: createOpenRoamingGlobalReachAccount
summary: Create account information.
parameters:
- in: path
description: The account name
name: name
schema:
type: string
required: true
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/GLBLRAccountInfo'
responses:
200:
$ref: '#/components/schemas/GLBLRAccountInfo'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
put:
tags:
- RadiusEndpointTypes-Global Reach
operationId: modifyOpenRoamingGlobalReachAccount
summary: Modify account information.
parameters:
- in: path
description: The account name
name: name
schema:
type: string
required: true
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/GLBLRAccountInfo'
responses:
200:
$ref: '#/components/schemas/GLBLRAccountInfo'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
/openroaming/globalreach/certificates/{account}:
get:
tags:
- RadiusEndpointTypes-Global Reach Certificate
operationId: getOpenRoamingGlobalReachCertificateList
summary: Retrieve certificate list.
parameters:
- in: path
description: The account name
name: account
schema:
type: string
required: true
- in: query
description: Pagination start (starts at 1. If not specified, 1 is assumed)
name: offset
schema:
type: integer
required: false
- in: query
description: Maximum number of entries to return (if absent, no limit is assumed)
name: limit
schema:
type: integer
required: false
- in: query
description: return the number of certificates
name: countOnly
schema:
type: boolean
required: false
responses:
200:
description: The list of certificates
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/GLBLRCertificateInfo'
$ref: '#/components/responses/Success'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
/openroaming/globalreach/certificate/{account}/{id}:
get:
tags:
- RadiusEndpointTypes-Global Reach Certificate
operationId: getOpenRoamingGlobalReachCertificate
summary: Retrieve certificate information.
parameters:
- in: path
description: The account name - this is the provisioning ID for the account. Not the GlobalReach ID.
name: account
schema:
type: string
required: true
- in: path
description: The certificate id in provisioning - not the certificate_id from GlobalReach
name: id
schema:
type: string
required: true
responses:
200:
$ref: '#/components/schemas/GLBLRCertificateInfo'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
delete:
tags:
- RadiusEndpointTypes-Global Reach Certificate
operationId: deleteOpenRoamingGlobalReachCertificate
summary: Delete certificate information.
parameters:
- in: path
description: The account name - this is the provisioning ID for the account. Not the GlobalReach ID.
name: account
schema:
type: string
required: true
- in: path
description: The certificate id in provisioning - not the certificate_id from GlobalReach
name: id
schema:
type: string
required: true
responses:
200:
$ref: '#/components/responses/Success'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
post:
tags:
- RadiusEndpointTypes-Global Reach Certificate
operationId: createOpenRoamingGlobalReachCertificate
summary: Create certificate information.
parameters:
- in: path
description: The account name - this is the provisioning ID for the account. Not the GlobalReach ID.
name: account
schema:
type: string
required: true
- in: path
description: Must be set to "0"
name: id
schema:
type: string
required: true
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/GLBLRCertificateInfo'
responses:
200:
$ref: '#/components/schemas/GLBLRCertificateInfo'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
put:
tags:
- RadiusEndpointTypes-Global Reach Certificate
operationId: updateOpenRoamingGlobalReachCertificate
summary: Update certificate information.
parameters:
- in: path
description: The account name - this is the provisioning ID for the account. Not the GlobalReach ID.
name: account
schema:
type: string
required: true
- in: path
description: the UUID of the certificate
name: id
schema:
type: string
required: true
- in: query
description: Update an existing certificate
name: updateCertificate
schema:
type: boolean
default: false
required: false
responses:
200:
$ref: '#/components/schemas/GLBLRCertificateInfo'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'

View File

@@ -1,199 +0,0 @@
openapi: 3.0.1
info:
title: OpenWiFi RadiusEndpointTypes Provisioning Model for Google Orion
description: Definitions and APIs to Open Roaming WiFi.
version: 2.5.0
license:
name: BSD3
url: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
servers:
- url: 'https://localhost:16005/api/v1'
security:
- bearerAuth: []
- ApiKeyAuth: []
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
responses:
NotFound:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/NotFound'
Unauthorized:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/Unauthorized'
Success:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/Success'
BadRequest:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/BadRequest'
schemas:
GooglOrionAccountInfo:
type: object
properties:
allOf:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-owprov/blob/main/openpapi/owprov.yaml#/components/schemas/ObjectInfo'
privateKey:
type: string
certificate:
type: string
cacerts:
type: array
items:
type: string
paths:
/openroaming/orion/accounts:
get:
tags:
- RadiusEndpointTypes-Google Orion
operationId: getOpenRoamingGlobalReachAccountList
summary: Retrieve account list.
parameters:
- in: query
description: Pagination start (starts at 1. If not specified, 1 is assumed)
name: offset
schema:
type: integer
required: false
- in: query
description: Maximum number of entries to return (if absent, no limit is assumed)
name: limit
schema:
type: integer
required: false
- in: query
description: return the number of accounts
name: countOnly
schema:
type: boolean
required: false
responses:
200:
description: The list of accounts
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/GooglOrionAccountInfo'
$ref: '#/components/responses/Success'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
/openroaming/orion/account/{id}:
get:
tags:
- RadiusEndpointTypes-Google Orion
operationId: getOpenRoamingGlobalReachAccount
summary: Retrieve account information.
parameters:
- in: path
description: The account ID
name: id
schema:
type: string
format: uuid
required: true
responses:
200:
$ref: '#/components/schemas/GooglOrionAccountInfo'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
delete:
tags:
- RadiusEndpointTypes-Google Orion
operationId: deleteOpenRoamingGlobalReachAccount
summary: Delete account information.
parameters:
- in: path
description: The account ID
name: id
schema:
type: string
format: uuid
required: true
responses:
200:
$ref: '#/components/responses/Success'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
post:
tags:
- RadiusEndpointTypes-Google Orion
operationId: createOpenRoamingGlobalReachAccount
summary: Create account information.
parameters:
- in: path
description: The account ID
name: id
schema:
type: string
format: uuid
required: true
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/GooglOrionAccountInfo'
responses:
200:
$ref: '#/components/schemas/GooglOrionAccountInfo'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
put:
tags:
- RadiusEndpointTypes-Google Orion
operationId: modifyOpenRoamingGlobalReachAccount
summary: Modify account information.
parameters:
- in: path
description: The account ID
name: id
schema:
type: string
format: uuid
required: true
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/GooglOrionAccountInfo'
responses:
200:
$ref: '#/components/schemas/GooglOrionAccountInfo'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'

View File

@@ -0,0 +1,268 @@
openapi: 3.0.1
info:
title: OpenWiFi Open roaming Ameriband Provisioning Model
description: Registration of an OpenRoaming profile with Ameriband for TIP OpenWifi.
version: 1.0.0
license:
name: BSD3
url: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
servers:
- url: 'https://tip.regiatration.ameriband.com:8001/api/v1'
security:
- bearerAuth: []
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
responses:
NotFound:
description: The specified resource was not found.
content:
application/json:
schema:
properties:
ErrorCode:
type: integer
ErrorDetails:
type: string
ErrorDescription:
type: string
Unauthorized:
description: The requested does not have sufficient rights to perform the operation.
content:
application/json:
schema:
properties:
ErrorCode:
type: integer
enum:
- 0 # Success
- 8 # INVALID_TOKEN
- 9 # EXPIRED_TOKEN
ErrorDetails:
type: string
ErrorDescription:
type: string
Success:
description: The requested operation was performed.
content:
application/json:
schema:
properties:
Operation:
type: string
Details:
type: string
Code:
type: integer
BadRequest:
description: The requested operation failed.
content:
application/json:
schema:
properties:
ErrorCode:
type: integer
ErrorDetails:
type: string
ErrorDescription:
type: integer
schemas:
RegistrationRequest:
type: object
properties:
orgRequestId:
type: string
format: uuid
minLength: 36
maxLength: 36
example:
Client will generate a UUID that must be returned in the response.
orgAcceptedTermsAndConditions:
type: boolean
default: false
orgLegalName:
type: string
minLength: 1
orgWebSite:
type: string
format: url
minLength: 1
orgContact:
type: string
minLength: 1
example:
John Smith
orgEmail:
type: string
format: email
minLength: 1
orgPhone:
type: string
example:
(607)555-1234 or +1(223)555-1222
orgLocation:
type: string
example:
Boston, NH - LA, CA
orgCertificate:
type: string
minLength: 1
example:
This must be the entire PEM file content of the certificate, encoded using base64
RegistrationResponse:
type: object
properties:
orgRequestId:
type: string
format: uuid
minLength: 36
maxLength: 36
example:
This should be the same orgRequestId passed during registration.
orgNASID:
type: string
minLength: 10
description:
This is the NASID generated by Ameriband. It will be used by the operator as NASID when contacting Ameriband.
ameribandCertificate:
type: string
minLength: 1
example:
This must be the entire PEM file content of the certificate, encoded using base64
RegistrationInformationRequest:
type: object
properties:
link:
description: This should be the link where a potential registrant can read the terms and conditions of registering with Ameriband.
type: string
format: url
minLength: 1
example:
https://ameriband.com/romain-registration.html
paths:
/termsAndConditions:
get:
summary: The registrant must be given a chance to view the terms and conditions of the relationship they are entering into
operationId: getTermsAndConditions
responses:
200:
description: Sucessfully retrieved Terms and Conditions
content:
application/json:
schema:
$ref: '#/components/schemas/RegistrationInformationRequest'
404:
$ref: '#/components/responses/Unauthorized'
/registration:
get:
tags:
- Registration
operationId: getRegistrationInformation
summary: This should return the information from a registration based on the NASID
parameters:
- in: query
name: orgNASID
schema:
type: string
required: true
example:
This is the orgNASID returned during registration.
responses:
200:
$ref: '#/components/schemas/RegistrationResponse'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
post:
summary: Called when the registrant ahs read the T&Cs and iw willing to submit their information to enter in a partnership
tags:
- Registration
operationId: createRegistration
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/RegistrationRequest'
responses:
200:
description: Succesfully registered
content:
application/json:
schema:
$ref: '#/components/schemas/RegistrationResponse'
400:
description: Registration failed due to missing or incomplete information
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
put:
summary: Called when the registrant needs to update its information with Ameriband. The does not generate a new NASID.
tags:
- Registration
operationId: updateRegistration
parameters:
- in: query
name: orgNASID
schema:
type: string
required: true
example:
This is the orgNASID returned during registration.
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/RegistrationRequest'
responses:
200:
description: Succesfully found the information based on the orgNASID
content:
application/json:
schema:
$ref: '#/components/schemas/RegistrationResponse'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
delete:
tags:
- Registration
summary: When a registrant wants to terminate a relationship with Ameriband. Ameriband should also delete all information from the registrant
operationId: deleteRegistration
parameters:
- in: query
name: orgNASID
schema:
type: string
required: true
example:
This is the orgNASID returned during registration.
responses:
204:
$ref: '#/components/responses/Success'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'

View File

@@ -1331,6 +1331,12 @@ components:
- $ref: '#/components/schemas/StringList' - $ref: '#/components/schemas/StringList'
- $ref: '#/components/schemas/TagValuePairList' - $ref: '#/components/schemas/TagValuePairList'
SystemCommandResults:
type: object
oneOf:
- $ref: '#/components/schemas/StringList'
- $ref: '#/components/schemas/TagValuePairList'
NoteInfo: NoteInfo:
type: object type: object
properties: properties:
@@ -1370,33 +1376,6 @@ components:
type: integer type: integer
format: int64 format: int64
SystemResources:
type: object
properties:
numberOfFileDescriptors:
type: integer
format: int64
currRealMem:
type: integer
format: int64
peakRealMem:
type: integer
format: int64
currVirtMem:
type: integer
format: int64
peakVirtMem:
type: integer
format: int64
SystemCommandResults:
type: object
oneOf:
- $ref: '#/components/schemas/SystemResources'
- $ref: '#/components/schemas/SystemInfoResults'
- $ref: '#/components/schemas/StringList'
- $ref: '#/components/schemas/TagValuePairList'
Dashboard: Dashboard:
type: object type: object
properties: properties:
@@ -2279,7 +2258,7 @@ paths:
get: get:
tags: tags:
- Configuration Overrides - Configuration Overrides
operationId: getConfigurationOverrides operationId: getCponfigurationOverrides
summary: retrieve a list of configuration overrides for a given device summary: retrieve a list of configuration overrides for a given device
parameters: parameters:
- in: path - in: path
@@ -2303,7 +2282,7 @@ paths:
delete: delete:
tags: tags:
- Configuration Overrides - Configuration Overrides
operationId: deleteConfigurationOverrides operationId: deleteCponfigurationOverrides
summary: delete all configuration overrides for a given device from a given source summary: delete all configuration overrides for a given device from a given source
parameters: parameters:
- in: path - in: path
@@ -4444,12 +4423,15 @@ paths:
type: string type: string
enum: enum:
- info - info
- extraConfiguration
- resources
required: true required: true
responses: responses:
200: 200:
$ref: '#/components/schemas/SystemCommandResults' description: Successful command execution
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/SystemInfoResults'
403: 403:
$ref: '#/components/responses/Unauthorized' $ref: '#/components/responses/Unauthorized'
404: 404:

View File

@@ -1,342 +0,0 @@
openapi: 3.0.1
info:
title: OpenWiFi RADIUS Resource Model
description: Definitions and APIs to manage RADIUS Resources.
version: 1.0.0
license:
name: BSD3
url: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
servers:
- url: 'https://localhost:16005/api/v1'
security:
- bearerAuth: []
- ApiKeyAuth: []
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
responses:
NotFound:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/NotFound'
Unauthorized:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/Unauthorized'
Success:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/Success'
BadRequest:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-ucentralsec/blob/main/openpapi/owsec.yaml#/components/responses/BadRequest'
schemas:
RADIUSServer:
type: object
properties:
Hostname:
type: string
IP:
type: string
Port:
type: integer
format: int32
Secret:
type: string
RADIUSEndPointRadiusType:
type: object
properties:
Authentication:
type: array
items:
$ref: '#/components/schemas/RADIUSServer'
Accounting:
type: array
items:
$ref: '#/components/schemas/RADIUSServer'
CoA:
type: array
items:
$ref: '#/components/schemas/RADIUSServer'
AccountingInterval:
type: integer
format: int32
RADIUSEndPointRadsecType:
type: object
properties:
Hostname:
type: string
IP:
type: string
Port:
type: integer
Secret:
type: string
default: radsec
UseOpenRoamingAccount:
type: string
format: uuid
Weight:
type: integer
format: int32
Certificate:
type: string
PrivateKey:
type: string
CaCerts:
type: array
items:
type: string
AllowSelfSigned:
type: boolean
default: false
RADIUSEndPoint:
type: object
properties:
allOf:
$ref: 'https://github.com/Telecominfraproject/wlan-cloud-owprov/blob/main/openpapi/owprov.yaml#/components/schemas/ObjectInfo'
Type:
type: string
enum:
- generic
- radsec
- globalreach
- orion
default: radius
RadsecServers:
type: array
items:
$ref: '#/components/schemas/RADIUSEndPointRadsecType'
RadiusServers:
type: array
items:
$ref: '#/components/schemas/RADIUSEndPointRadiusType'
PoolStrategy:
type: string
enum:
- round_robin
- weighted
- random
default: random
UseGWProxy:
type: boolean
default: true
Index:
type: string
example:
- 0.0.1.1: a ficticious IP address that should be between 0.0.1.1 and 0.0.2.254
UsedBy:
type: array
description: list of configuration using this endpoint
items:
type: string
format: uuid
NasIdentifier:
type: string
AccountingInterval:
type: integer
format: int64
RADIUSEndpointUpdateStatus:
type: object
properties:
lastUpdate:
type: integer
format: int64
lastConfigurationChange:
type: integer
format: int64
paths:
/RADIUSEndPoints:
get:
tags:
- RADIUS Endpoints
operationId: getRADIUSEndPoints
summary: Retrieve the lists of RADIUSendPoints
parameters:
- in: query
description: Pagination start (starts at 1. If not specified, 1 is assumed)
name: offset
schema:
type: integer
required: false
- in: query
description: Maximum number of entries to return (if absent, no limit is assumed)
name: limit
schema:
type: integer
required: false
- in: query
description: return the number of certificates
name: countOnly
schema:
type: boolean
required: false
- in: query
description: return the last update time
name: currentStatus
schema:
type: boolean
required: false
responses:
200:
description: The list of endpoints
content:
application/json:
schema:
oneOf:
- type: array
items:
$ref: '#/components/schemas/RADIUSEndPoint'
- $ref: '#/components/schemas/RADIUSEndpointUpdateStatus'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
put:
tags:
- RADIUS Endpoints
operationId: updateRADIUSEndpoints
summary: Force an Update to teh RADIUSendPoints in the controller
parameters:
- in: query
name: updateEndpoints
schema:
type: boolean
required: false
responses:
200:
description: The list of endpoints
content:
application/json:
schema:
type: object
properties:
Error:
type: string
ErrorNum:
type: integer
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
/RADIUSEndPoint/{id}:
get:
tags:
- RADIUS Endpoints
operationId: getRADIUSEndPoint
summary: Retrieve a RADIUSendPoint
parameters:
- in: path
name: id
schema:
type: string
format: uuid
required: true
responses:
200:
description: The endpoint
content:
application/json:
schema:
$ref: '#/components/schemas/RADIUSEndPoint'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
delete:
tags:
- RADIUS Endpoints
operationId: deleteRADIUSEndPoint
summary: Delete a RADIUSendPoint
parameters:
- in: path
name: id
schema:
type: string
format: uuid
required: true
responses:
200:
$ref: '#/components/responses/Success'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
post:
tags:
- RADIUS Endpoints
operationId: createRADIUSEndPoint
summary: Create a RADIUSendPoint
parameters:
- in: path
name: id
schema:
type: string
format: uuid
required: true
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/RADIUSEndPoint'
responses:
200:
$ref: '#/components/schemas/RADIUSEndPoint'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'
put:
tags:
- RADIUS Endpoints
operationId: modifyRADIUSEndPoint
summary: Modify a RADIUSendPoint
parameters:
- in: path
name: id
schema:
type: string
format: uuid
required: true
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/RADIUSEndPoint'
responses:
200:
$ref: '#/components/schemas/RADIUSEndPoint'
400:
$ref: '#/components/responses/BadRequest'
403:
$ref: '#/components/responses/Unauthorized'
404:
$ref: '#/components/responses/NotFound'

View File

@@ -133,32 +133,29 @@ paths:
summary: Run a specific or default RRM algorithm. The UI user or CLI user will have the ability to run an algorithm on demand. summary: Run a specific or default RRM algorithm. The UI user or CLI user will have the ability to run an algorithm on demand.
parameters: parameters:
- in: query - in: query
description: The venue this algorithm should be run on. description:
name: venue name: venue
schema: schema:
type: string type: string
format: uuid format: uuid
required: true required: true
- in: query - in: query
description: Perform RRM asynchronously, synchronously or in mockRun mode (without updating anything, this may be used by an admin to see what RRM would do). description: Perform RRM without updating anything. This may be used by an admin to see what RRM would do.
name: mode name: mock
schema: schema:
type: string type: boolean
enum: [ async, sync, mockRun ] default: false
required: false required: false
- in: query - in: query
description: Specify the RRM algorithm to use. If omitted, select the default algorithm. description: Specify the RRM algorithm to use. If omitted, select the default algorithm.
name: algorithm
schema: schema:
type: string type: string
required: false required: false
- in: query - in: query
description: Specify the comma separated name=value parameters to use with the RRM algorithm to use. If omitted, select the default parameters. description: Specify the parameters to use with the RRM algorithm to use. If omitted, select the default parameters.
name: parameters
schema: schema:
type: string type: string
required: false required: false
responses: responses:
200: 200:
description: Return the list of actions that were or would be performed. description: Return the list of actions that were or would be performed.

View File

@@ -37,12 +37,10 @@ openwifi.system.data = ${SYSTEM_DATA}
openwifi.system.debug = false openwifi.system.debug = false
openwifi.system.uri.private = ${SYSTEM_URI_PRIVATE} openwifi.system.uri.private = ${SYSTEM_URI_PRIVATE}
openwifi.system.uri.public = ${SYSTEM_URI_PUBLIC} openwifi.system.uri.public = ${SYSTEM_URI_PUBLIC}
openwifi.system.commandchannel = /tmp/app.owprov openwifi.system.commandchannel = /tmp/app.ucentralfms
openwifi.system.uri.ui = ${SYSTEM_URI_UI} openwifi.system.uri.ui = ${SYSTEM_URI_UI}
openwifi.security.restapi.disable = ${SECURITY_RESTAPI_DISABLE} openwifi.security.restapi.disable = ${SECURITY_RESTAPI_DISABLE}
rrm.providers = ${RRM_PROVIDERS}
############################# #############################
# Generic information for all micro services # Generic information for all micro services
############################# #############################

View File

@@ -9,11 +9,6 @@
#include "Poco/StringTokenizer.h" #include "Poco/StringTokenizer.h"
#include "fmt/format.h" #include "fmt/format.h"
#include <RadiusEndpointTypes/OrionWifi.h>
#include <RadiusEndpointTypes/GlobalReach.h>
#include <RadiusEndpointTypes/Radsec.h>
#include <RadiusEndpointTypes/GenericRadius.h>
namespace OpenWifi { namespace OpenWifi {
APConfig::APConfig(const std::string &SerialNumber, const std::string &DeviceType, APConfig::APConfig(const std::string &SerialNumber, const std::string &DeviceType,
@@ -60,33 +55,14 @@ namespace OpenWifi {
*/ */
} }
bool APConfig::InsertRadiusEndPoint(const ProvObjects::RADIUSEndPoint &RE, Poco::JSON::Object &Result) { bool APConfig::ReplaceVariablesInObject(const Poco::JSON::Object::Ptr &Original,
if(RE.UseGWProxy) { Poco::JSON::Object::Ptr &Result) {
Poco::JSON::Object ServerSettings;
if (RE.Type == "orion") {
return OpenRoaming_Orion()->Render(RE, SerialNumber_, Result);
} else if (RE.Type == "globalreach") {
return OpenRoaming_GlobalReach()->Render(RE, SerialNumber_, Result);
} else if (RE.Type == "radsec") {
return OpenRoaming_Radsec()->Render(RE, SerialNumber_, Result);
} else if (RE.Type == "generic") {
return OpenRoaming_GenericRadius()->Render(RE, SerialNumber_, Result);
}
Result.set( "radius" , ServerSettings);
} else {
std::cout << "Radius proxy off" << RE.info.name << std::endl;
}
return false;
}
bool APConfig::ReplaceVariablesInObject(const Poco::JSON::Object &Original,
Poco::JSON::Object &Result) {
// get all the names and expand // get all the names and expand
auto Names = Original.getNames(); auto Names = Original->getNames();
for (const auto &i : Names) { for (const auto &i : Names) {
if (i == "__variableBlock") { if (i == "__variableBlock") {
if (Original.isArray(i)) { if (Original->isArray(i)) {
auto UUIDs = Original.getArray(i); auto UUIDs = Original->getArray(i);
for (const auto &uuid : *UUIDs) { for (const auto &uuid : *UUIDs) {
ProvObjects::VariableBlock VB; ProvObjects::VariableBlock VB;
if (StorageService()->VariablesDB().GetRecord("id", uuid, VB)) { if (StorageService()->VariablesDB().GetRecord("id", uuid, VB)) {
@@ -96,92 +72,58 @@ namespace OpenWifi {
P.parse(var.value).extract<Poco::JSON::Object::Ptr>(); P.parse(var.value).extract<Poco::JSON::Object::Ptr>();
auto VarNames = VariableBlockInfo->getNames(); auto VarNames = VariableBlockInfo->getNames();
for (const auto &j : VarNames) { for (const auto &j : VarNames) {
// std::cout << "Name: " << j << std::endl; Result->set(j, VariableBlockInfo->get(j));
if(VariableBlockInfo->isArray(j)) { }
auto Elements = VariableBlockInfo->getArray(j); }
if(Elements->size()>0) { }
Poco::JSON::Array InnerArray; }
ReplaceVariablesInArray(*Elements, InnerArray); }
Result.set(j, InnerArray); } else if (Original->isArray(i)) {
// std::cout << "Array!!!" << std::endl; auto Arr = Poco::makeShared<Poco::JSON::Array>();
auto Obj = Original->getArray(i);
ReplaceVariablesInArray(Obj, Arr);
Result->set(i, Arr);
} else if (Original->isObject(i)) {
auto Expanded = Poco::makeShared<Poco::JSON::Object>();
auto Obj = Original->getObject(i);
ReplaceVariablesInObject(Obj, Expanded);
Result->set(i, Expanded);
} else { } else {
// std::cout << "Empty Array!!!" << std::endl; Result->set(i, Original->get(i));
}
} else if(VariableBlockInfo->isObject(j)) {
Poco::JSON::Object InnerEval;
// std::cout << "Visiting object " << j << std::endl;
auto O = VariableBlockInfo->getObject(j);
ReplaceVariablesInObject(*O,InnerEval);
Result.set(j, InnerEval);
} else {
Result.set(j, VariableBlockInfo->get(j));
}
}
}
}
}
}
} else if (i == "__radiusEndpoint") {
auto EndPointId = Original.get(i).toString();
ProvObjects::RADIUSEndPoint RE;
// std::cout << "ID->" << EndPointId << std::endl;
if(StorageService()->RadiusEndpointDB().GetRecord("id",EndPointId,RE)) {
InsertRadiusEndPoint(RE, Result);
} else {
poco_error(Logger_, fmt::format("RADIUS Endpoint {} could not be found. Please delete this configuration and recreate it."));
return false;
}
} else if (Original.isArray(i)) {
Poco::JSON::Array Arr;
auto Obj = Original.getArray(i);
if(Obj->size()>0) {
ReplaceVariablesInArray(*Obj, Arr);
Result.set(i, Arr);
}
} else if (Original.isObject(i)) {
Poco::JSON::Object Expanded;
auto Obj = Original.getObject(i);
ReplaceVariablesInObject(*Obj, Expanded);
Result.set(i, Expanded);
} else {
Result.set(i, Original.get(i));
} }
} }
return true; return true;
} }
bool APConfig::ReplaceVariablesInArray(const Poco::JSON::Array &Original, bool APConfig::ReplaceVariablesInArray(const Poco::JSON::Array::Ptr &Original,
Poco::JSON::Array &ResultArray) { Poco::JSON::Array::Ptr &ResultArray) {
for (const auto &element : *Original) {
for (const auto &element : Original) {
// std::cout << element.toString() << std::endl;
if (element.isArray()) { if (element.isArray()) {
Poco::JSON::Array Expanded; auto Expanded = Poco::makeShared<Poco::JSON::Array>();
const auto Object = element.extract<Poco::JSON::Array::Ptr>(); const auto &Object = element.extract<Poco::JSON::Array::Ptr>();
if(Object->size()>0) { ReplaceVariablesInArray(Object, Expanded);
ReplaceVariablesInArray(*Object, Expanded); ResultArray->add(Expanded);
ResultArray.add(Expanded);
}
} else if (element.isStruct()) { } else if (element.isStruct()) {
Poco::JSON::Object Expanded; auto Expanded = Poco::makeShared<Poco::JSON::Object>();
const auto &Object = element.extract<Poco::JSON::Object::Ptr>(); const auto &Object = element.extract<Poco::JSON::Object::Ptr>();
ReplaceVariablesInObject(*Object, Expanded); ReplaceVariablesInObject(Object, Expanded);
ResultArray.add(Expanded); ResultArray->add(Expanded);
} else if (element.isString() || element.isNumeric() || element.isBoolean() || } else if (element.isString() || element.isNumeric() || element.isBoolean() ||
element.isInteger() || element.isSigned()) { element.isInteger() || element.isSigned()) {
ResultArray.add(element); ResultArray->add(element);
} else { } else {
Poco::JSON::Object Expanded; auto Expanded = Poco::makeShared<Poco::JSON::Object>();
const auto &Object = element.extract<Poco::JSON::Object::Ptr>(); const auto &Object = element.extract<Poco::JSON::Object::Ptr>();
ReplaceVariablesInObject(*Object, Expanded); ReplaceVariablesInObject(Object, Expanded);
ResultArray.add(Expanded); ResultArray->add(Expanded);
} }
} }
return true; return true;
} }
bool APConfig::Get(Poco::JSON::Object::Ptr &Configuration) { bool APConfig::Get(Poco::JSON::Object::Ptr &Configuration) {
if (Config_.empty()) { if (Config_.empty()) {
Explanation_.clear(); Explanation_.clear();
try { try {
@@ -235,8 +177,8 @@ namespace OpenWifi {
ExObj.set("element", OriginalArray); ExObj.set("element", OriginalArray);
Explanation_.add(ExObj); Explanation_.add(ExObj);
} }
Poco::JSON::Array ExpandedArray; auto ExpandedArray = Poco::makeShared<Poco::JSON::Array>();
ReplaceVariablesInArray(*OriginalArray, ExpandedArray); ReplaceVariablesInArray(OriginalArray, ExpandedArray);
Configuration->set(SectionName, ExpandedArray); Configuration->set(SectionName, ExpandedArray);
} else if (O->isObject(SectionName)) { } else if (O->isObject(SectionName)) {
auto OriginalSection = auto OriginalSection =
@@ -249,8 +191,8 @@ namespace OpenWifi {
ExObj.set("element", OriginalSection); ExObj.set("element", OriginalSection);
Explanation_.add(ExObj); Explanation_.add(ExObj);
} }
Poco::JSON::Object ExpandedSection; auto ExpandedSection = Poco::makeShared<Poco::JSON::Object>();
ReplaceVariablesInObject(*OriginalSection, ExpandedSection); ReplaceVariablesInObject(OriginalSection, ExpandedSection);
Configuration->set(SectionName, ExpandedSection); Configuration->set(SectionName, ExpandedSection);
} else { } else {
poco_warning(Logger(), fmt::format("Unknown config element type: {}",O->get(SectionName).toString())); poco_warning(Logger(), fmt::format("Unknown config element type: {}",O->get(SectionName).toString()));
@@ -283,7 +225,7 @@ namespace OpenWifi {
RadioArray->get(RadioIndex).extract<Poco::JSON::Object::Ptr>(); RadioArray->get(RadioIndex).extract<Poco::JSON::Object::Ptr>();
if (Tokens[2] == "tx-power") { if (Tokens[2] == "tx-power") {
IndexedRadio->set( IndexedRadio->set(
"tx-power", "rx-power",
std::strtoull(col.parameterValue.c_str(), nullptr, 10)); std::strtoull(col.parameterValue.c_str(), nullptr, 10));
if (Explain_) { if (Explain_) {
Poco::JSON::Object ExObj; Poco::JSON::Object ExObj;
@@ -375,7 +317,6 @@ namespace OpenWifi {
ProvObjects::DeviceConfiguration Config; ProvObjects::DeviceConfiguration Config;
if (StorageService()->ConfigurationDB().GetRecord("id", UUID, Config)) { if (StorageService()->ConfigurationDB().GetRecord("id", UUID, Config)) {
// std::cout << Config.info.name << ":" << Config.configuration.size() << std::endl;
if (!Config.configuration.empty()) { if (!Config.configuration.empty()) {
if (DeviceTypeMatch(DeviceType_, Config.deviceTypes)) { if (DeviceTypeMatch(DeviceType_, Config.deviceTypes)) {
for (const auto &i : Config.configuration) { for (const auto &i : Config.configuration) {

View File

@@ -45,10 +45,10 @@ namespace OpenWifi {
bool Sub_ = false; bool Sub_ = false;
Poco::Logger &Logger() { return Logger_; } Poco::Logger &Logger() { return Logger_; }
bool ReplaceVariablesInArray(const Poco::JSON::Array &O, bool ReplaceVariablesInArray(const Poco::JSON::Array::Ptr &O,
Poco::JSON::Array &Result); Poco::JSON::Array::Ptr &Result);
bool ReplaceVariablesInObject(const Poco::JSON::Object &Original, bool ReplaceVariablesInObject(const Poco::JSON::Object::Ptr &Original,
Poco::JSON::Object &Result); Poco::JSON::Object::Ptr &Result);
bool FindRadio(const std::string &Band, const Poco::JSON::Array::Ptr &Arr, bool FindRadio(const std::string &Band, const Poco::JSON::Array::Ptr &Arr,
Poco::JSON::Object::Ptr &Radio); Poco::JSON::Object::Ptr &Radio);
@@ -58,6 +58,5 @@ namespace OpenWifi {
Poco::JSON::Object::Ptr &C); Poco::JSON::Object::Ptr &C);
bool RemoveBand(const std::string &Band, const Poco::JSON::Array::Ptr &A_in, bool RemoveBand(const std::string &Band, const Poco::JSON::Array::Ptr &A_in,
Poco::JSON::Array::Ptr &A_Out); Poco::JSON::Array::Ptr &A_Out);
bool InsertRadiusEndPoint(const ProvObjects::RADIUSEndPoint &EP, Poco::JSON::Object &Result);
}; };
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -31,48 +31,6 @@ namespace OpenWifi {
poco_information(Logger(), "Stopped..."); poco_information(Logger(), "Stopped...");
}; };
void AutoDiscovery::ProcessPing(const Poco::JSON::Object::Ptr & P, std::string &FW, std::string &SN,
std::string &Compat, std::string &Conn, std::string &locale) {
if (P->has(uCentralProtocol::CONNECTIONIP))
Conn = P->get(uCentralProtocol::CONNECTIONIP).toString();
if (P->has(uCentralProtocol::FIRMWARE))
FW = P->get(uCentralProtocol::FIRMWARE).toString();
if (P->has(uCentralProtocol::SERIALNUMBER))
SN = P->get(uCentralProtocol::SERIALNUMBER).toString();
if (P->has(uCentralProtocol::COMPATIBLE))
Compat = P->get(uCentralProtocol::COMPATIBLE).toString();
if (P->has("locale")) {
locale = P->get("locale").toString();
}
}
void AutoDiscovery::ProcessConnect(const Poco::JSON::Object::Ptr &P, std::string &FW, std::string &SN,
std::string &Compat, std::string &Conn, std::string &locale) {
if (P->has(uCentralProtocol::CONNECTIONIP))
Conn = P->get(uCentralProtocol::CONNECTIONIP).toString();
if (P->has(uCentralProtocol::FIRMWARE))
FW = P->get(uCentralProtocol::FIRMWARE).toString();
if (P->has(uCentralProtocol::SERIALNUMBER))
SN = P->get(uCentralProtocol::SERIALNUMBER).toString();
if (P->has("locale")) {
locale = P->get("locale").toString();
}
if(P->has(uCentralProtocol::CAPABILITIES)) {
auto CapObj = P->getObject(uCentralProtocol::CAPABILITIES);
if (CapObj->has(uCentralProtocol::COMPATIBLE))
Compat = CapObj->get(uCentralProtocol::COMPATIBLE).toString();
}
}
void AutoDiscovery::ProcessDisconnect(const Poco::JSON::Object::Ptr &P, [[maybe_unused]] std::string &FW,
std::string &SN,
[[maybe_unused]] std::string &Compat,
[[maybe_unused]] std::string &Conn,
[[maybe_unused]] std::string &locale) {
if (P->has(uCentralProtocol::SERIALNUMBER))
SN = P->get(uCentralProtocol::SERIALNUMBER).toString();
}
void AutoDiscovery::run() { void AutoDiscovery::run() {
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification()); Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
Utils::SetThreadName("auto-discovery"); Utils::SetThreadName("auto-discovery");
@@ -82,31 +40,43 @@ namespace OpenWifi {
try { try {
Poco::JSON::Parser Parser; Poco::JSON::Parser Parser;
auto Object = Parser.parse(Msg->Payload()).extract<Poco::JSON::Object::Ptr>(); auto Object = Parser.parse(Msg->Payload()).extract<Poco::JSON::Object::Ptr>();
bool Connected=true;
if (Object->has(uCentralProtocol::PAYLOAD)) { if (Object->has(uCentralProtocol::PAYLOAD)) {
auto PayloadObj = Object->getObject(uCentralProtocol::PAYLOAD); auto PayloadObj = Object->getObject(uCentralProtocol::PAYLOAD);
std::string ConnectedIP, SerialNumber, Compatible, Firmware, Locale ; std::string ConnectedIP, SerialNumber, DeviceType;
if (PayloadObj->has(uCentralProtocol::PING)) { if (PayloadObj->has(uCentralProtocol::CONNECTIONIP))
auto PingObj = PayloadObj->getObject("ping"); ConnectedIP =
ProcessPing(PingObj, Firmware, SerialNumber, Compatible, ConnectedIP, Locale); PayloadObj->get(uCentralProtocol::CONNECTIONIP).toString();
} else if(PayloadObj->has("capabilities")) { if (PayloadObj->has(uCentralProtocol::CAPABILITIES)) {
ProcessConnect(PayloadObj, Firmware, SerialNumber, Compatible, ConnectedIP, Locale); auto CapObj = PayloadObj->getObject(uCentralProtocol::CAPABILITIES);
} else if(PayloadObj->has("disconnection")) { if (CapObj->has(uCentralProtocol::COMPATIBLE)) {
// we ignore disconnection in provisioning DeviceType = CapObj->get(uCentralProtocol::COMPATIBLE).toString();
Connected=false; SerialNumber = PayloadObj->get(uCentralProtocol::SERIAL).toString();
ProcessConnect(PayloadObj, Firmware, SerialNumber, Compatible, ConnectedIP, Locale);
} else {
poco_debug(Logger(),fmt::format("Unknown message on 'connection' topic: {}",Msg->Payload()));
} }
} else if (PayloadObj->has(uCentralProtocol::PING)) {
auto PingMessage = PayloadObj->getObject(uCentralProtocol::PING);
if (PingMessage->has(uCentralProtocol::FIRMWARE) &&
PingMessage->has(uCentralProtocol::SERIALNUMBER) &&
PingMessage->has(uCentralProtocol::COMPATIBLE)) {
if (PingMessage->has(uCentralProtocol::CONNECTIONIP))
ConnectedIP =
PingMessage->get(uCentralProtocol::CONNECTIONIP).toString();
SerialNumber =
PingMessage->get(uCentralProtocol::SERIALNUMBER).toString();
DeviceType =
PingMessage->get(uCentralProtocol::COMPATIBLE).toString();
}
}
std::string Locale;
if (PayloadObj->has("locale"))
Locale = PayloadObj->get("locale").toString();
if (!SerialNumber.empty() && Connected) { if (!SerialNumber.empty()) {
StorageService()->InventoryDB().CreateFromConnection( StorageService()->InventoryDB().CreateFromConnection(
SerialNumber, ConnectedIP, Compatible, Locale); SerialNumber, ConnectedIP, DeviceType, Locale);
} }
} }
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
std::cout << "EX:" << Msg->Payload() << std::endl;
Logger().log(E); Logger().log(E);
} catch (...) { } catch (...) {
} }

View File

@@ -9,7 +9,6 @@
#include "Poco/Notification.h" #include "Poco/Notification.h"
#include "Poco/NotificationQueue.h" #include "Poco/NotificationQueue.h"
#include "Poco/JSON/Object.h"
namespace OpenWifi { namespace OpenWifi {
@@ -47,13 +46,6 @@ namespace OpenWifi {
Poco::Thread Worker_; Poco::Thread Worker_;
std::atomic_bool Running_ = false; std::atomic_bool Running_ = false;
void ProcessPing(const Poco::JSON::Object::Ptr & P, std::string &FW, std::string &SN,
std::string &Compat, std::string &Conn, std::string &locale) ;
void ProcessConnect(const Poco::JSON::Object::Ptr & P, std::string &FW, std::string &SN,
std::string &Compat, std::string &Conn, std::string &locale) ;
void ProcessDisconnect(const Poco::JSON::Object::Ptr & P, std::string &FW, std::string &SN,
std::string &Compat, std::string &Conn, std::string &locale) ;
AutoDiscovery() noexcept AutoDiscovery() noexcept
: SubSystemServer("AutoDiscovery", "AUTO-DISCOVERY", "discovery") {} : SubSystemServer("AutoDiscovery", "AUTO-DISCOVERY", "discovery") {}
}; };

View File

@@ -23,10 +23,6 @@
#include "UI_Prov_WebSocketNotifications.h" #include "UI_Prov_WebSocketNotifications.h"
#include "framework/ConfigurationValidator.h" #include "framework/ConfigurationValidator.h"
#include "framework/UI_WebSocketClientServer.h" #include "framework/UI_WebSocketClientServer.h"
#include <RadiusEndpointTypes/GlobalReach.h>
#include <RadiusEndpointTypes/OrionWifi.h>
#include <RadiusEndpointTypes/Radsec.h>
#include <RadiusEndpointTypes/GenericRadius.h>
namespace OpenWifi { namespace OpenWifi {
class Daemon *Daemon::instance_ = nullptr; class Daemon *Daemon::instance_ = nullptr;
@@ -39,11 +35,7 @@ namespace OpenWifi {
ConfigurationValidator(), SerialNumberCache(), ConfigurationValidator(), SerialNumberCache(),
AutoDiscovery(), JobController(), AutoDiscovery(), JobController(),
UI_WebSocketClientServer(), FindCountryFromIP(), UI_WebSocketClientServer(), FindCountryFromIP(),
Signup(), FileDownloader(), Signup(), FileDownloader()});
OpenRoaming_GlobalReach(),
OpenRoaming_Orion(), OpenRoaming_Radsec(),
OpenRoaming_GenericRadius()
});
} }
return instance_; return instance_;
} }

View File

@@ -63,9 +63,17 @@ namespace OpenWifi {
std::lock_guard G(Mutex_); std::lock_guard G(Mutex_);
Initialized_ = true; Initialized_ = true;
std::vector<std::string> DeviceTypes; std::string DeviceTypes;
AppServiceRegistry().Get("deviceTypes", DeviceTypes); if (AppServiceRegistry().Get("deviceTypes", DeviceTypes)) {
std::for_each(DeviceTypes.begin(),DeviceTypes.end(),[&](const std::string &s){ DeviceTypes_.insert(s);}); Poco::JSON::Parser P;
try {
auto O = P.parse(DeviceTypes).extract<Poco::JSON::Array::Ptr>();
for (const auto &i : *O) {
DeviceTypes_.insert(i.toString());
}
} catch (...) {
}
}
} }
inline bool UpdateDeviceTypes() { inline bool UpdateDeviceTypes() {
@@ -99,9 +107,15 @@ namespace OpenWifi {
inline void SaveCache() { inline void SaveCache() {
std::lock_guard G(Mutex_); std::lock_guard G(Mutex_);
std::vector<std::string> DeviceTypes;
std::for_each(DeviceTypes_.begin(),DeviceTypes_.end(),[&](const std::string &s){DeviceTypes.emplace_back(s);}); Poco::JSON::Array Arr;
AppServiceRegistry().Set("deviceTypes", DeviceTypes); for (auto const &i : DeviceTypes_)
Arr.add(i);
std::stringstream OS;
Arr.stringify(OS);
AppServiceRegistry().Set("deviceTypes", OS.str());
} }
}; };

View File

@@ -24,15 +24,9 @@ namespace OpenWifi {
void FileDownloader::onTimer([[maybe_unused]] Poco::Timer &timer) { void FileDownloader::onTimer([[maybe_unused]] Poco::Timer &timer) {
const static std::vector<std::pair<std::string, std::string>> Files{ const static std::vector<std::pair<std::string, std::string>> Files{
{ {"https://raw.githubusercontent.com/blogic/ucentral-schema/main/ucentral.schema.json",
"https://raw.githubusercontent.com/Telecominfraproject/wlan-ucentral-schema/main/ucentral.schema.pretty.json", "ucentral.schema.json"},
"ucentral.schema.pretty.json" {"https://ucentral.io/ucentral.schema.pretty.json", "ucentral.schema.pretty.json"}};
},
{
"https://raw.githubusercontent.com/Telecominfraproject/wlan-ucentral-schema/main/ucentral.schema.json",
"ucentral.schema.json"
}
};
Utils::SetThreadName("file-dmnldr"); Utils::SetThreadName("file-dmnldr");

View File

@@ -39,7 +39,9 @@ namespace OpenWifi {
Poco::JSON::Object Payload; Poco::JSON::Object Payload;
obj.to_json(Payload); obj.to_json(Payload);
Payload.set("ObjectType", OT); Payload.set("ObjectType", OT);
KafkaManager()->PostMessage(KafkaTopics::PROVISIONING_CHANGE, Ops[op], Payload); std::ostringstream OS;
Payload.stringify(OS);
KafkaManager()->PostMessage(KafkaTopics::PROVISIONING_CHANGE, Ops[op], OS.str());
return true; return true;
} }

View File

@@ -1,125 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#include "RESTAPI_openroaming_gr_acct_handler.h"
#include <RadiusEndpointTypes/GlobalReach.h>
namespace OpenWifi {
void RESTAPI_openroaming_gr_acct_handler::DoGet() {
auto Account = GetBinding("id","");
if(Account.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
RecordType Record;
if(DB_.GetRecord("id",Account,Record)) {
return ReturnObject(Record);
}
return NotFound();
}
void RESTAPI_openroaming_gr_acct_handler::DoDelete() {
auto Account = GetBinding("id","");
if(Account.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
RecordType Record;
if(!DB_.GetRecord("id",Account,Record)) {
return NotFound();
}
StorageService()->GLBLRCertsDB().DeleteRecords(fmt::format(" accountId='{}' ", Account));
DB_.DeleteRecord("id", Account);
return OK();
}
void RESTAPI_openroaming_gr_acct_handler::DoPost() {
auto Account = GetBinding("id","");
if(Account.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
const auto &RawObject = ParsedBody_;
RecordType NewObject;
if( !NewObject.from_json(RawObject)) {
return BadRequest(OpenWifi::RESTAPI::Errors::InvalidJSONDocument);
}
if(NewObject.privateKey.empty() || NewObject.GlobalReachAcctId.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
if(!NewObject.privateKey.empty() && !Utils::VerifyECKey(NewObject.privateKey)) {
return BadRequest(RESTAPI::Errors::NotAValidECKey);
}
std::string GlobalReachName;
if(!OpenRoaming_GlobalReach()->VerifyAccount(NewObject.GlobalReachAcctId,NewObject.privateKey,GlobalReachName)) {
return BadRequest(RESTAPI::Errors::InvalidGlobalReachAccount);
}
if( NewObject.commonName.empty() || NewObject.organization.empty() ||
NewObject.city.empty() || NewObject.province.empty() || NewObject.country.empty() ) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
Utils::CSRCreationParameters P;
P.Country = NewObject.country;
P.CommonName = NewObject.commonName;
P.Province = NewObject.province;
P.City = NewObject.city;
P.Organization = NewObject.organization;
Utils::CSRCreationResults R;
if(!Utils::CreateX509CSR(P,R)) {
return BadRequest(RESTAPI::Errors::CannotCreateCSR);
}
NewObject.CSR = R.CSR;
NewObject.CSRPublicKey = R.PublicKey;
NewObject.CSRPrivateKey = R.PrivateKey;
ProvObjects::CreateObjectInfo(RawObject,UserInfo_.userinfo,NewObject.info);
if(DB_.CreateRecord(NewObject)) {
RecordType StoredObject;
DB_.GetRecord("id",NewObject.info.id,StoredObject);
return ReturnObject(StoredObject);
}
return BadRequest(RESTAPI::Errors::RecordNotCreated);
}
void RESTAPI_openroaming_gr_acct_handler::DoPut() {
auto Account = GetBinding("account","");
if(Account.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
const auto &RawObject = ParsedBody_;
RecordType Modify;
if(!Modify.from_json(RawObject)) {
return BadRequest(OpenWifi::RESTAPI::Errors::InvalidJSONDocument);
}
RecordType Existing;
if(!DB_.GetRecord("id",Account,Existing)) {
return NotFound();
}
if(!ProvObjects::UpdateObjectInfo(RawObject,UserInfo_.userinfo,Existing.info)) {
return BadRequest(OpenWifi::RESTAPI::Errors::InvalidJSONDocument);
}
if(DB_.UpdateRecord("id",Existing.info.id,Existing)) {
RecordType StoredObject;
DB_.GetRecord("id",Existing.info.id,StoredObject);
return ReturnObject(StoredObject);
}
return BadRequest(RESTAPI::Errors::RecordNotUpdated);
}
} // OpenWifi

View File

@@ -1,32 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#pragma once
#include "StorageService.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_openroaming_gr_acct_handler : public RESTAPIHandler {
public:
RESTAPI_openroaming_gr_acct_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/openroaming/globalreach/account/{id}"}; };
private:
using RecordType = ProvObjects::GLBLRAccountInfo;
GLBLRAccountInfoDB &DB_ = StorageService()->GLBLRAccountInfoDB();
void DoGet() final;
void DoPost() final;
void DoPut() final;
void DoDelete() final;
};
} // namespace OpenWifi

View File

@@ -1,113 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#include "RESTAPI_openroaming_gr_cert_handler.h"
#include <RadiusEndpointTypes/GlobalReach.h>
namespace OpenWifi {
void RESTAPI_openroaming_gr_cert_handler::DoGet() {
auto Account = GetBinding("account","");
auto Id = GetBinding("id","");
if(Account.empty() || Id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
if(!StorageService()->GLBLRAccountInfoDB().Exists("id",Account)) {
return NotFound();
}
std::vector<RecordType> Certificates;
DB_.GetRecords(0,1,Certificates,fmt::format(" accountId='{}' and id='{}' ", Account, Id));
if(Certificates.empty()) {
return NotFound();
}
return ReturnObject(Certificates[0]);
}
void RESTAPI_openroaming_gr_cert_handler::DoDelete() {
auto Account = GetBinding("account","");
auto Id = GetBinding("id","");
if(Account.empty() || Id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
if(!StorageService()->GLBLRAccountInfoDB().Exists("id",Account)) {
return NotFound();
}
DB_.DeleteRecords(fmt::format(" accountId='{}' and id='{}' ", Account, Id));
return OK();
}
void RESTAPI_openroaming_gr_cert_handler::DoPost() {
auto Account = GetBinding("account","");
auto Id = GetBinding("id","");
if(Account.empty() || Id.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
const auto &RawObject = ParsedBody_;
RecordType NewObject;
if( !NewObject.from_json(RawObject)) {
return BadRequest(OpenWifi::RESTAPI::Errors::InvalidJSONDocument);
}
if(NewObject.name.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
ProvObjects::GLBLRAccountInfo AccountInfo;
if(!StorageService()->GLBLRAccountInfoDB().GetRecord("id",Account, AccountInfo)) {
return BadRequest(RESTAPI::Errors::InvalidGlobalReachAccount);
}
if(OpenRoaming_GlobalReach()->CreateRADSECCertificate(AccountInfo.GlobalReachAcctId,NewObject.name,AccountInfo.CSR, NewObject)) {
NewObject.id = MicroServiceCreateUUID();
NewObject.accountId = Account;
NewObject.created = Utils::Now();
NewObject.csr = AccountInfo.CSR;
DB_.CreateRecord(NewObject);
RecordType CreatedObject;
DB_.GetRecord("id",NewObject.id,CreatedObject);
return ReturnObject(CreatedObject);
}
return BadRequest(RESTAPI::Errors::RecordNotCreated);
}
void RESTAPI_openroaming_gr_cert_handler::DoPut() {
auto Account = GetBinding("account","");
auto Id = GetBinding("id","");
auto UpdateCertificate = GetBoolParameter("updateCertificate",false);
if(Account.empty() || Id.empty() || !UpdateCertificate){
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
ProvObjects::GLBLRAccountInfo AccountInfo;
if(!StorageService()->GLBLRAccountInfoDB().GetRecord("id",Account, AccountInfo)) {
return BadRequest(RESTAPI::Errors::InvalidGlobalReachAccount);
}
ProvObjects::GLBLRCertificateInfo Existing;
if(!DB_.GetRecord("id",Id,Existing)) {
return NotFound();
}
if(OpenRoaming_GlobalReach()->CreateRADSECCertificate(AccountInfo.GlobalReachAcctId,Existing.name,AccountInfo.CSR, Existing)) {
Existing.created = Utils::Now();
DB_.UpdateRecord("id",Existing.id,Existing);
RecordType CreatedObject;
DB_.GetRecord("id",Existing.id,CreatedObject);
ProvObjects::RADIUSEndpointUpdateStatus Status;
Status.ChangeConfiguration();
return ReturnObject(CreatedObject);
}
return BadRequest(RESTAPI::Errors::RecordNotUpdated);
}
} // OpenWifi

View File

@@ -1,32 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#pragma once
#include "StorageService.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_openroaming_gr_cert_handler : public RESTAPIHandler {
public:
RESTAPI_openroaming_gr_cert_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/openroaming/globalreach/certificate/{account}/{id}"}; };
private:
using RecordType = ProvObjects::GLBLRCertificateInfo;
GLBLRCertsDB &DB_ = StorageService()->GLBLRCertsDB();
void DoGet() final;
void DoPost() final;
void DoPut() final ;
void DoDelete() final;
};
} // namespace OpenWifi

View File

@@ -1,20 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#include "RESTAPI_openroaming_gr_list_acct_handler.h"
namespace OpenWifi {
void RESTAPI_openroaming_gr_list_acct_handler::DoGet() {
if(GetBoolParameter("countOnly")) {
return ReturnCountOnly(DB_.Count());
}
std::vector<RecordType> Accounts;
DB_.GetRecords(QB_.Offset,QB_.Limit,Accounts);
return ReturnObject(Accounts);
}
} // OpenWifi

View File

@@ -1,30 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#pragma once
#include "StorageService.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_openroaming_gr_list_acct_handler : public RESTAPIHandler {
public:
RESTAPI_openroaming_gr_list_acct_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/openroaming/globalreach/accounts"}; };
private:
using RecordType = ProvObjects::GLBLRAccountInfo;
GLBLRAccountInfoDB &DB_ = StorageService()->GLBLRAccountInfoDB();
void DoGet() final;
void DoPost() final{};
void DoPut() final{};
void DoDelete() final{};
};
} // namespace OpenWifi

View File

@@ -1,36 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#include "RESTAPI_openroaming_gr_list_certificates.h"
namespace OpenWifi {
void RESTAPI_openroaming_gr_list_certificates::DoGet() {
auto Account = GetBinding("account");
if(Account.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
if(Account=="*") {
std::vector< ProvObjects::GLBLRCertificateInfo> Arr;
for(const auto &cert:QB_.Select) {
ProvObjects::GLBLRCertificateInfo CInfo;
if(StorageService()->GLBLRCertsDB().GetRecord("id",cert,CInfo)) {
Arr.emplace_back(CInfo);
}
}
return ReturnObject(Arr);
}
auto Where = fmt::format(" accountId='{}'", Account);
if(GetBoolParameter("countOnly")) {
return ReturnCountOnly(DB_.Count(Where));
}
std::vector<RecordType> Certificates;
DB_.GetRecords(QB_.Offset,QB_.Limit,Certificates, Where);
return ReturnObject(Certificates);
}
} // OpenWifi

View File

@@ -1,30 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#pragma once
#include "StorageService.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_openroaming_gr_list_certificates : public RESTAPIHandler {
public:
RESTAPI_openroaming_gr_list_certificates(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/openroaming/globalreach/certificates/{account}"}; };
private:
using RecordType = ProvObjects::GLBLRCertificateInfo;
GLBLRCertsDB &DB_ = StorageService()->GLBLRCertsDB();
void DoGet() final;
void DoPost() final{};
void DoPut() final{};
void DoDelete() final{};
};
} // namespace OpenWifi

View File

@@ -1,99 +0,0 @@
//
// Created by stephane bourque on 2023-09-15.
//
#include "RESTAPI_openroaming_orion_acct_handler.h"
namespace OpenWifi {
void RESTAPI_openroaming_orion_acct_handler::DoGet() {
auto Account = GetBinding("id","");
if(Account.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
RecordType Record;
if(DB_.GetRecord("id",Account,Record)) {
return ReturnObject(Record);
}
return NotFound();
}
void RESTAPI_openroaming_orion_acct_handler::DoDelete() {
auto Account = GetBinding("id","");
if(Account.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
RecordType Record;
if(!DB_.GetRecord("id",Account,Record)) {
return NotFound();
}
DB_.DeleteRecord("id", Account);
return OK();
}
void RESTAPI_openroaming_orion_acct_handler::DoPost() {
auto Account = GetBinding("id","");
if(Account.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
const auto &RawObject = ParsedBody_;
RecordType NewObject;
if( !NewObject.from_json(RawObject)) {
return BadRequest(OpenWifi::RESTAPI::Errors::InvalidJSONDocument);
}
if( NewObject.privateKey.empty() ||
NewObject.certificate.empty() ||
NewObject.cacerts.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
if( !Utils::VerifyECKey(NewObject.privateKey) ||
!Utils::ValidX509Certificate(NewObject.certificate) ||
!Utils::ValidX509Certificate(NewObject.cacerts)) {
return BadRequest(RESTAPI::Errors::NotAValidECKey);
}
ProvObjects::CreateObjectInfo(RawObject,UserInfo_.userinfo,NewObject.info);
if(DB_.CreateRecord(NewObject)) {
RecordType StoredObject;
DB_.GetRecord("id",NewObject.info.id,StoredObject);
return ReturnObject(StoredObject);
}
return BadRequest(RESTAPI::Errors::RecordNotCreated);
}
void RESTAPI_openroaming_orion_acct_handler::DoPut() {
auto Account = GetBinding("id","");
if(Account.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
}
const auto &RawObject = ParsedBody_;
RecordType Modify;
if(!Modify.from_json(RawObject)) {
return BadRequest(OpenWifi::RESTAPI::Errors::InvalidJSONDocument);
}
RecordType Existing;
if(!DB_.GetRecord("id",Account,Existing)) {
return NotFound();
}
if(!ProvObjects::UpdateObjectInfo(RawObject,UserInfo_.userinfo,Existing.info)) {
return BadRequest(OpenWifi::RESTAPI::Errors::InvalidJSONDocument);
}
if(DB_.UpdateRecord("id",Existing.info.id,Existing)) {
RecordType StoredObject;
DB_.GetRecord("id",Existing.info.id,StoredObject);
return ReturnObject(StoredObject);
}
return BadRequest(RESTAPI::Errors::RecordNotUpdated);
}
} // OpenWifi

View File

@@ -1,32 +0,0 @@
//
// Created by stephane bourque on 2023-09-15.
//
#pragma once
#include "StorageService.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_openroaming_orion_acct_handler : public RESTAPIHandler {
public:
RESTAPI_openroaming_orion_acct_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/openroaming/orion/account/{id}"}; };
private:
using RecordType = ProvObjects::GooglOrionAccountInfo;
OrionAccountsDB &DB_ = StorageService()->OrionAccountsDB();
void DoGet() final;
void DoPost() final;
void DoPut() final;
void DoDelete() final;
};
} // namespace OpenWifi

View File

@@ -1,19 +0,0 @@
//
// Created by stephane bourque on 2023-09-15.
//
#include "RESTAPI_openroaming_orion_list_acct_handler.h"
namespace OpenWifi {
void RESTAPI_openroaming_orion_list_acct_handler::DoGet() {
if(GetBoolParameter("countOnly")) {
return ReturnCountOnly(DB_.Count());
}
std::vector<RecordType > Accounts;
DB_.GetRecords(QB_.Offset,QB_.Limit,Accounts);
return ReturnObject(Accounts);
}
} // OpenWifi

View File

@@ -1,30 +0,0 @@
//
// Created by stephane bourque on 2023-09-15.
//
#pragma once
#include "StorageService.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_openroaming_orion_list_acct_handler : public RESTAPIHandler {
public:
RESTAPI_openroaming_orion_list_acct_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/openroaming/orion/accounts"}; };
private:
using RecordType = ProvObjects::GooglOrionAccountInfo;
OrionAccountsDB &DB_ = StorageService()->OrionAccountsDB();
void DoGet() final;
void DoPost() final{};
void DoPut() final{};
void DoDelete() final{};
};
} // namespace OpenWifi

View File

@@ -1,202 +0,0 @@
//
// Created by stephane bourque on 2023-09-27.
//
#include "RESTAPI_radius_endpoint_handler.h"
#include <storage/storage_orion_accounts.h>
#include <RESTObjects/RESTAPI_GWobjects.h>
namespace OpenWifi {
void RESTAPI_radius_endpoint_handler::DoGet() {
auto id = GetBinding("id");
if(id.empty()) {
return BadRequest(RESTAPI::Errors::MissingAuthenticationInformation);
}
RecordType Record;
if(DB_.GetRecord("id",id,Record)) {
return ReturnObject(Record);
}
return NotFound();
}
void RESTAPI_radius_endpoint_handler::DoDelete() {
auto id = GetBinding("id");
if(id.empty()) {
return BadRequest(RESTAPI::Errors::MissingAuthenticationInformation);
}
RecordType Record;
if(DB_.GetRecord("id",id,Record)) {
DB_.DeleteRecord("id",id);
ProvObjects::RADIUSEndpointUpdateStatus Status;
Status.ChangeConfiguration();
return OK();
}
return NotFound();
}
static bool ValidPort(std::uint32_t P) {
return P>0 && P<65535;
}
static bool ValidRadiusServer(const ProvObjects::RADIUSServer &S) {
if(S.Hostname.empty() || !ValidPort(S.Port) || !Utils::ValidIP(S.IP) || S.Secret.empty()) {
return false;
}
return true;
}
static bool ValidRadiusServer(const std::vector<ProvObjects::RADIUSServer> &ServerList) {
return std::all_of(ServerList.begin(),ServerList.end(),[](const ProvObjects::RADIUSServer &Server)->bool { return ValidRadiusServer(Server); });
}
void RESTAPI_radius_endpoint_handler::DoPost() {
auto id = GetBinding("id");
if(id.empty()) {
return BadRequest(RESTAPI::Errors::MissingAuthenticationInformation);
}
const auto &RawObject = ParsedBody_;
RecordType NewRecord;
if(!NewRecord.from_json(RawObject)) {
return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
}
if(GWObjects::RadiusEndpointType(NewRecord.Type)==GWObjects::RadiusEndpointType::unknown) {
return BadRequest(RESTAPI::Errors::InvalidRadiusTypeEndpoint);
}
if(GWObjects::RadiusPoolStrategy(NewRecord.PoolStrategy)==GWObjects::RadiusPoolStrategy::unknown) {
return BadRequest(RESTAPI::Errors::InvalidRadiusEndpointPoolStrategy);
}
if(!NewRecord.RadiusServers.empty() && !NewRecord.RadsecServers.empty()) {
return BadRequest(RESTAPI::Errors::EndpointMustHaveOneTypeOfServers);
}
auto EndPointType = GWObjects::RadiusEndpointType(NewRecord.Type);
switch(EndPointType) {
case GWObjects::RadiusEndpointType::radsec:
case GWObjects::RadiusEndpointType::orion:
case GWObjects::RadiusEndpointType::globalreach:
{
if(NewRecord.RadsecServers.empty()) {
return BadRequest(RESTAPI::Errors::EndpointMustHaveOneTypeOfServers);
}
} break;
case GWObjects::RadiusEndpointType::generic: {
if(NewRecord.RadiusServers.empty()) {
return BadRequest(RESTAPI::Errors::EndpointMustHaveOneTypeOfServers);
}
} break;
default:
return BadRequest(RESTAPI::Errors::EndpointMustHaveOneTypeOfServers);
}
if(NewRecord.Index.empty() || !RadiusEndpointDB::ValidIndex(NewRecord.Index)) {
return BadRequest(RESTAPI::Errors::RadiusEndpointIndexInvalid);
}
// Make sure that nobody is using that index
auto where = fmt::format(" index='{}' ", NewRecord.Index);
if(DB_.Count(where)!=0) {
return BadRequest(RESTAPI::Errors::RadiusEndpointIndexInvalid);
}
if(EndPointType==GWObjects::RadiusEndpointType::generic) {
for(const auto &Server:NewRecord.RadiusServers) {
if(!ValidRadiusServer(Server.Authentication) ||
!ValidRadiusServer(Server.Accounting) ||
!ValidRadiusServer(Server.CoA)) {
return BadRequest(RESTAPI::Errors::InvalidRadiusServer);
}
}
} else {
switch(EndPointType) {
case GWObjects::RadiusEndpointType::orion: {
for(const auto &Server:NewRecord.RadsecServers) {
if(!StorageService()->OrionAccountsDB().Exists("id",Server.UseOpenRoamingAccount)) {
return BadRequest(RESTAPI::Errors::OrionAccountMustExist);
}
}
} break;
case GWObjects::RadiusEndpointType::globalreach: {
for(const auto &Server:NewRecord.RadsecServers) {
if(!StorageService()->GLBLRCertsDB().Exists("id",Server.UseOpenRoamingAccount)) {
return BadRequest(RESTAPI::Errors::GlobalReachCertMustExist);
}
}
} break;
case GWObjects::RadiusEndpointType::radsec: {
for(const auto &Server:NewRecord.RadsecServers) {
if(Server.Certificate.empty() || !Utils::ValidX509Certificate(Server.Certificate)) {
return BadRequest(RESTAPI::Errors::InvalidRadsecMainCertificate);
}
if(Server.CaCerts.empty() || !Utils::ValidX509Certificate(Server.CaCerts)) {
return BadRequest(RESTAPI::Errors::InvalidRadsecCaCertificate);
}
if(Server.PrivateKey.empty() || !Utils::VerifyPrivateKey(Server.PrivateKey)) {
return BadRequest(RESTAPI::Errors::InvalidRadsecPrivteKey);
}
if(!Utils::ValidIP(Server.IP)) {
return BadRequest(RESTAPI::Errors::InvalidRadsecIPAddress);
}
if(!(Server.Port>0 && Server.Port<65535)) {
return BadRequest(RESTAPI::Errors::InvalidRadsecPort);
}
if(Server.Secret.empty()) {
return BadRequest(RESTAPI::Errors::InvalidRadsecSecret);
}
}
} break;
default: {
}
}
}
ProvObjects::CreateObjectInfo(RawObject,UserInfo_.userinfo,NewRecord.info);
if(DB_.CreateRecord(NewRecord)) {
RecordType AddedRecord;
DB_.GetRecord("id", NewRecord.info.id, AddedRecord);
ProvObjects::RADIUSEndpointUpdateStatus Status;
Status.ChangeConfiguration();
return ReturnObject(AddedRecord);
}
return BadRequest(RESTAPI::Errors::RecordNotCreated);
}
void RESTAPI_radius_endpoint_handler::DoPut() {
auto id = GetBinding("id");
if(id.empty()) {
return BadRequest(RESTAPI::Errors::MissingAuthenticationInformation);
}
const auto &RawObject = ParsedBody_;
RecordType ModifiedRecord;
if(!ModifiedRecord.from_json(RawObject)) {
return BadRequest(RESTAPI::Errors::InvalidJSONDocument);
}
RecordType Existing;
if(!DB_.GetRecord("id",id,Existing)) {
return NotFound();
}
AssignIfPresent(RawObject,"NasIdentifier", Existing.NasIdentifier);
AssignIfPresent(RawObject,"AccountingInterval", Existing.AccountingInterval);
ProvObjects::UpdateObjectInfo(RawObject, UserInfo_.userinfo, Existing.info);
if(DB_.UpdateRecord("id", Existing.info.id, Existing)) {
RecordType AddedRecord;
DB_.GetRecord("id", Existing.info.id, AddedRecord);
ProvObjects::RADIUSEndpointUpdateStatus Status;
Status.ChangeConfiguration();
return ReturnObject(AddedRecord);
}
return BadRequest(RESTAPI::Errors::NotImplemented);
}
} // OpenWifi

View File

@@ -1,33 +0,0 @@
//
// Created by stephane bourque on 2023-09-27.
//
#pragma once
#include "StorageService.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_radius_endpoint_handler : public RESTAPIHandler {
public:
RESTAPI_radius_endpoint_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_POST,
Poco::Net::HTTPRequest::HTTP_DELETE,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/RADIUSEndPoint/{id}"}; };
private:
using RecordType = ProvObjects::RADIUSEndPoint;
RadiusEndpointDB &DB_ = StorageService()->RadiusEndpointDB();
void DoGet() final;
void DoPost() final;
void DoPut() final;
void DoDelete() final;
};
} // namespace OpenWifi

View File

@@ -1,49 +0,0 @@
//
// Created by stephane bourque on 2023-09-27.
//
#include "RESTAPI_radiusendpoint_list_handler.h"
#include "framework/AppServiceRegistry.h"
#include "RadiusEndpointUpdater.h"
namespace OpenWifi {
void RESTAPI_radiusendpoint_list_handler::DoGet() {
if(GetBoolParameter("currentStatus")) {
ProvObjects::RADIUSEndpointUpdateStatus Status;
Status.Read();
return ReturnObject(Status);
}
if(QB_.CountOnly) {
return ReturnCountOnly(DB_.Count());
}
std::vector<RecordType> Records;
DB_.GetRecords(QB_.Offset,QB_.Limit,Records);
return ReturnObject(Records);
}
void RESTAPI_radiusendpoint_list_handler::DoPut() {
if( UserInfo_.userinfo.userRole!=SecurityObjects::ROOT &&
UserInfo_.userinfo.userRole!=SecurityObjects::ADMIN) {
return BadRequest(RESTAPI::Errors::ACCESS_DENIED);
}
if(GetBoolParameter("updateEndpoints")) {
RadiusEndpointUpdater R;
std::uint64_t ErrorCode;
std::string ErrorDetails;
std::string ErrorDescription;
if(!R.UpdateEndpoints(this, ErrorCode, ErrorDetails,ErrorDescription)) {
return InternalError(RESTAPI::Errors::msg{.err_num = ErrorCode, .err_txt = ErrorDetails + ":" + ErrorDescription});
}
return OK();
}
return BadRequest(RESTAPI::Errors::MissingAuthenticationInformation);
}
} // OpenWifi

View File

@@ -1,31 +0,0 @@
//
// Created by stephane bourque on 2023-09-27.
//
#pragma once
#include "StorageService.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi {
class RESTAPI_radiusendpoint_list_handler : public RESTAPIHandler {
public:
RESTAPI_radiusendpoint_list_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_PUT,
Poco::Net::HTTPRequest::HTTP_OPTIONS},
Server, TransactionId, Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/RADIUSEndPoints"}; };
private:
using RecordType = ProvObjects::RADIUSEndPoint;
RadiusEndpointDB &DB_ = StorageService()->RadiusEndpointDB();
void DoGet() final;
void DoPost() final{};
void DoPut() final;
void DoDelete() final{};
};
} // namespace OpenWifi

View File

@@ -35,14 +35,6 @@
#include "RESTAPI/RESTAPI_variables_list_handler.h" #include "RESTAPI/RESTAPI_variables_list_handler.h"
#include "RESTAPI/RESTAPI_venue_handler.h" #include "RESTAPI/RESTAPI_venue_handler.h"
#include "RESTAPI/RESTAPI_venue_list_handler.h" #include "RESTAPI/RESTAPI_venue_list_handler.h"
#include "RESTAPI/RESTAPI_openroaming_gr_acct_handler.h"
#include "RESTAPI/RESTAPI_openroaming_gr_list_acct_handler.h"
#include "RESTAPI/RESTAPI_openroaming_gr_cert_handler.h"
#include "RESTAPI/RESTAPI_openroaming_gr_list_certificates.h"
#include "RESTAPI/RESTAPI_openroaming_orion_acct_handler.h"
#include "RESTAPI/RESTAPI_openroaming_orion_list_acct_handler.h"
#include "RESTAPI/RESTAPI_radiusendpoint_list_handler.h"
#include "RESTAPI/RESTAPI_radius_endpoint_handler.h"
#include "framework/RESTAPI_SystemCommand.h" #include "framework/RESTAPI_SystemCommand.h"
#include "framework/RESTAPI_WebSocketServer.h" #include "framework/RESTAPI_WebSocketServer.h"
@@ -68,11 +60,7 @@ namespace OpenWifi {
RESTAPI_operators_list_handler, RESTAPI_service_class_handler, RESTAPI_operators_list_handler, RESTAPI_service_class_handler,
RESTAPI_service_class_list_handler, RESTAPI_op_contact_handler, RESTAPI_service_class_list_handler, RESTAPI_op_contact_handler,
RESTAPI_op_contact_list_handler, RESTAPI_op_location_handler, RESTAPI_op_contact_list_handler, RESTAPI_op_location_handler,
RESTAPI_op_location_list_handler, RESTAPI_asset_server, RESTAPI_overrides_handler, RESTAPI_op_location_list_handler, RESTAPI_asset_server, RESTAPI_overrides_handler>(
RESTAPI_openroaming_gr_acct_handler, RESTAPI_openroaming_gr_list_acct_handler,
RESTAPI_openroaming_gr_cert_handler, RESTAPI_openroaming_gr_list_certificates,
RESTAPI_openroaming_orion_acct_handler, RESTAPI_openroaming_orion_list_acct_handler,
RESTAPI_radiusendpoint_list_handler, RESTAPI_radius_endpoint_handler>(
Path, Bindings, L, S, TransactionId); Path, Bindings, L, S, TransactionId);
} }
@@ -94,11 +82,7 @@ namespace OpenWifi {
RESTAPI_operators_list_handler, RESTAPI_service_class_handler, RESTAPI_operators_list_handler, RESTAPI_service_class_handler,
RESTAPI_service_class_list_handler, RESTAPI_op_contact_handler, RESTAPI_service_class_list_handler, RESTAPI_op_contact_handler,
RESTAPI_op_contact_list_handler, RESTAPI_op_location_handler, RESTAPI_op_contact_list_handler, RESTAPI_op_location_handler,
RESTAPI_op_location_list_handler, RESTAPI_overrides_handler, RESTAPI_op_location_list_handler, RESTAPI_overrides_handler>(Path, Bindings, L, S,
RESTAPI_openroaming_gr_acct_handler, RESTAPI_openroaming_gr_list_acct_handler, TransactionId);
RESTAPI_openroaming_gr_cert_handler, RESTAPI_openroaming_gr_list_certificates,
RESTAPI_openroaming_orion_acct_handler, RESTAPI_openroaming_orion_list_acct_handler,
RESTAPI_radiusendpoint_list_handler, RESTAPI_radius_endpoint_handler>(
Path, Bindings, L, S,TransactionId);
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -90,9 +90,9 @@ namespace OpenWifi {
} }
if (!Existing.contacts.empty()) { if (!Existing.contacts.empty()) {
for (const auto &contact_uuid : Existing.contacts) for (const auto &i : Existing.contacts)
StorageService()->ContactDB().DeleteInUse( StorageService()->ContactDB().DeleteInUse(
"id", contact_uuid, StorageService()->VenueDB().Prefix(), UUID); "id", i, StorageService()->VenueDB().Prefix(), UUID);
} }
if (!Existing.location.empty()) if (!Existing.location.empty())
StorageService()->LocationDB().DeleteInUse("id", Existing.location, StorageService()->LocationDB().DeleteInUse("id", Existing.location,
@@ -101,9 +101,9 @@ namespace OpenWifi {
StorageService()->PolicyDB().DeleteInUse("id", Existing.managementPolicy, StorageService()->PolicyDB().DeleteInUse("id", Existing.managementPolicy,
StorageService()->VenueDB().Prefix(), UUID); StorageService()->VenueDB().Prefix(), UUID);
if (!Existing.deviceConfiguration.empty()) { if (!Existing.deviceConfiguration.empty()) {
for (auto &configuration_uuid : Existing.deviceConfiguration) for (auto &i : Existing.deviceConfiguration)
StorageService()->ConfigurationDB().DeleteInUse( StorageService()->ConfigurationDB().DeleteInUse(
"id", configuration_uuid, StorageService()->VenueDB().Prefix(), UUID); "id", i, StorageService()->VenueDB().Prefix(), UUID);
} }
if (!Existing.parent.empty()) if (!Existing.parent.empty())
StorageService()->VenueDB().DeleteChild("id", Existing.parent, UUID); StorageService()->VenueDB().DeleteChild("id", Existing.parent, UUID);
@@ -157,10 +157,6 @@ namespace OpenWifi {
return BadRequest(RESTAPI::Errors::EntityMustExist); return BadRequest(RESTAPI::Errors::EntityMustExist);
} }
if(StorageService()->VenueDB().DoesVenueNameAlreadyExist(NewObject.info.name,NewObject.entity, NewObject.parent)) {
return BadRequest(RESTAPI::Errors::VenuesNameAlreadyExists);
}
if (!NewObject.contacts.empty()) { if (!NewObject.contacts.empty()) {
for (const auto &i : NewObject.contacts) { for (const auto &i : NewObject.contacts) {
if (!StorageService()->ContactDB().Exists("id", i)) { if (!StorageService()->ContactDB().Exists("id", i)) {
@@ -276,19 +272,21 @@ namespace OpenWifi {
auto testUpdateOnly = GetBoolParameter("testUpdateOnly"); auto testUpdateOnly = GetBoolParameter("testUpdateOnly");
if (testUpdateOnly) { if (testUpdateOnly) {
ProvObjects::SerialNumberList SNL; ProvObjects::SerialNumberList SNL;
StorageService()->InventoryDB().GetDevicesForVenue(UUID, SNL.serialNumbers);
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
SNL.serialNumbers = Existing.devices;
SNL.to_json(Answer); SNL.to_json(Answer);
return ReturnObject(Answer); return ReturnObject(Answer);
} }
if (GetBoolParameter("updateAllDevices")) { if (GetBoolParameter("updateAllDevices")) {
ProvObjects::SerialNumberList SNL; ProvObjects::SerialNumberList SNL;
StorageService()->InventoryDB().GetDevicesForVenue(UUID, SNL.serialNumbers);
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
SNL.serialNumbers = Existing.devices;
auto JobId = MicroServiceCreateUUID(); auto JobId = MicroServiceCreateUUID();
Types::StringVec Parameters{UUID}; Types::StringVec Parameters{UUID};
;
auto NewJob = new VenueConfigUpdater(JobId, "VenueConfigurationUpdater", Parameters, 0, auto NewJob = new VenueConfigUpdater(JobId, "VenueConfigurationUpdater", Parameters, 0,
UserInfo_.userinfo, Logger()); UserInfo_.userinfo, Logger());
JobController()->AddJob(dynamic_cast<Job *>(NewJob)); JobController()->AddJob(dynamic_cast<Job *>(NewJob));
@@ -300,10 +298,11 @@ namespace OpenWifi {
if (GetBoolParameter("upgradeAllDevices")) { if (GetBoolParameter("upgradeAllDevices")) {
if (GetBoolParameter("revisionsAvailable")) { if (GetBoolParameter("revisionsAvailable")) {
std::set<std::string> DeviceTypes; std::set<std::string> DeviceTypes;
std::vector<ProvObjects::InventoryTag> ExistingDevices; for (const auto &serialNumber : Existing.devices) {
StorageService()->InventoryDB().GetDevicesForVenue(UUID, ExistingDevices); ProvObjects::InventoryTag Device;
for (const auto &device : ExistingDevices) { if (StorageService()->InventoryDB().GetRecord("id", serialNumber, Device)) {
DeviceTypes.insert(device.deviceType); DeviceTypes.insert(Device.deviceType);
}
} }
// Get all the revisions for all the device types // Get all the revisions for all the device types
@@ -371,17 +370,18 @@ namespace OpenWifi {
return ReturnObject(Answer); return ReturnObject(Answer);
} }
ProvObjects::SerialNumberList SNL;
auto Revision = GetParameter("revision", ""); auto Revision = GetParameter("revision", "");
if (Revision.empty()) { if (Revision.empty()) {
return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters); return BadRequest(RESTAPI::Errors::MissingOrInvalidParameters);
} }
ProvObjects::SerialNumberList SNL;
StorageService()->InventoryDB().GetDevicesForVenue(UUID, SNL.serialNumbers);
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
SNL.serialNumbers = Existing.devices;
auto JobId = MicroServiceCreateUUID(); auto JobId = MicroServiceCreateUUID();
Types::StringVec Parameters{UUID, Revision}; Types::StringVec Parameters{UUID, Revision};
;
auto NewJob = new VenueUpgrade(JobId, "VenueFirmwareUpgrade", Parameters, 0, auto NewJob = new VenueUpgrade(JobId, "VenueFirmwareUpgrade", Parameters, 0,
UserInfo_.userinfo, Logger()); UserInfo_.userinfo, Logger());
JobController()->AddJob(dynamic_cast<Job *>(NewJob)); JobController()->AddJob(dynamic_cast<Job *>(NewJob));
@@ -392,9 +392,9 @@ namespace OpenWifi {
if (GetBoolParameter("rebootAllDevices")) { if (GetBoolParameter("rebootAllDevices")) {
ProvObjects::SerialNumberList SNL; ProvObjects::SerialNumberList SNL;
StorageService()->InventoryDB().GetDevicesForVenue(UUID, SNL.serialNumbers);
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
SNL.serialNumbers = Existing.devices;
auto JobId = MicroServiceCreateUUID(); auto JobId = MicroServiceCreateUUID();
Types::StringVec Parameters{UUID}; Types::StringVec Parameters{UUID};
; ;
@@ -432,7 +432,7 @@ namespace OpenWifi {
std::string MoveFromEntity, MoveToEntity; std::string MoveFromEntity, MoveToEntity;
if (AssignIfPresent(RawObject, "entity", MoveToEntity)) { if (AssignIfPresent(RawObject, "entity", MoveToEntity)) {
if (MoveToEntity.empty() || !StorageService()->EntityDB().Exists("id", MoveToEntity)) { if (!MoveToEntity.empty() && !StorageService()->EntityDB().Exists("id", MoveToEntity)) {
return BadRequest(RESTAPI::Errors::EntityMustExist); return BadRequest(RESTAPI::Errors::EntityMustExist);
} }
MoveFromEntity = Existing.entity; MoveFromEntity = Existing.entity;
@@ -441,7 +441,7 @@ namespace OpenWifi {
std::string MoveToVenue, MoveFromVenue; std::string MoveToVenue, MoveFromVenue;
if (AssignIfPresent(RawObject, "venue", MoveToVenue)) { if (AssignIfPresent(RawObject, "venue", MoveToVenue)) {
if (MoveToVenue.empty() || !StorageService()->VenueDB().Exists("id", MoveToVenue)) { if (!MoveToVenue.empty() && !StorageService()->VenueDB().Exists("id", MoveToVenue)) {
return BadRequest(RESTAPI::Errors::VenueMustExist); return BadRequest(RESTAPI::Errors::VenueMustExist);
} }
MoveFromVenue = Existing.parent; MoveFromVenue = Existing.parent;
@@ -450,7 +450,7 @@ namespace OpenWifi {
std::string MoveFromLocation, MoveToLocation; std::string MoveFromLocation, MoveToLocation;
if (AssignIfPresent(RawObject, "location", MoveToLocation)) { if (AssignIfPresent(RawObject, "location", MoveToLocation)) {
if (MoveToLocation.empty() || if (!MoveToLocation.empty() &&
!StorageService()->LocationDB().Exists("id", MoveToLocation)) { !StorageService()->LocationDB().Exists("id", MoveToLocation)) {
return BadRequest(RESTAPI::Errors::LocationMustExist); return BadRequest(RESTAPI::Errors::LocationMustExist);
} }
@@ -460,8 +460,8 @@ namespace OpenWifi {
Types::UUIDvec_t MoveFromContacts, MoveToContacts; Types::UUIDvec_t MoveFromContacts, MoveToContacts;
if (AssignIfPresent(RawObject, "contacts", MoveToContacts)) { if (AssignIfPresent(RawObject, "contacts", MoveToContacts)) {
for (const auto &contact : NewObject.contacts) { for (const auto &i : NewObject.contacts) {
if (!StorageService()->ContactDB().Exists("id", contact)) { if (!StorageService()->ContactDB().Exists("id", i)) {
return BadRequest(RESTAPI::Errors::ContactMustExist); return BadRequest(RESTAPI::Errors::ContactMustExist);
} }
} }
@@ -471,7 +471,7 @@ namespace OpenWifi {
std::string MoveFromPolicy, MoveToPolicy; std::string MoveFromPolicy, MoveToPolicy;
if (AssignIfPresent(RawObject, "managementPolicy", MoveToPolicy)) { if (AssignIfPresent(RawObject, "managementPolicy", MoveToPolicy)) {
if (MoveToPolicy.empty() || !StorageService()->PolicyDB().Exists("id", MoveToPolicy)) { if (!MoveToPolicy.empty() && !StorageService()->PolicyDB().Exists("id", MoveToPolicy)) {
return BadRequest(RESTAPI::Errors::UnknownManagementPolicyUUID); return BadRequest(RESTAPI::Errors::UnknownManagementPolicyUUID);
} }
MoveFromPolicy = Existing.managementPolicy; MoveFromPolicy = Existing.managementPolicy;
@@ -481,8 +481,8 @@ namespace OpenWifi {
Types::UUIDvec_t MoveToConfigurations, MoveFromConfigurations; Types::UUIDvec_t MoveToConfigurations, MoveFromConfigurations;
if (RawObject->has("deviceConfiguration")) { if (RawObject->has("deviceConfiguration")) {
MoveToConfigurations = NewObject.deviceConfiguration; MoveToConfigurations = NewObject.deviceConfiguration;
for (auto &configuration : MoveToConfigurations) { for (auto &i : MoveToConfigurations) {
if (!StorageService()->ConfigurationDB().Exists("id", configuration)) { if (!StorageService()->ConfigurationDB().Exists("id", i)) {
return BadRequest(RESTAPI::Errors::ConfigurationMustExist); return BadRequest(RESTAPI::Errors::ConfigurationMustExist);
} }
} }

View File

@@ -13,7 +13,6 @@
#ifdef TIP_GATEWAY_SERVICE #ifdef TIP_GATEWAY_SERVICE
#include "AP_WS_Server.h" #include "AP_WS_Server.h"
#include "CapabilitiesCache.h" #include "CapabilitiesCache.h"
#include "RADIUSSessionTracker.h"
#endif #endif
#include "RESTAPI_GWobjects.h" #include "RESTAPI_GWobjects.h"
@@ -30,7 +29,6 @@ namespace OpenWifi::GWObjects {
field_to_json(Obj, "serialNumber", SerialNumber); field_to_json(Obj, "serialNumber", SerialNumber);
#ifdef TIP_GATEWAY_SERVICE #ifdef TIP_GATEWAY_SERVICE
field_to_json(Obj, "deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible)); field_to_json(Obj, "deviceType", CapabilitiesCache::instance()->GetPlatform(Compatible));
field_to_json(Obj, "hasRADIUSSessions", RADIUSSessionTracker()->HasSessions(SerialNumber));
#endif #endif
field_to_json(Obj, "macAddress", MACAddress); field_to_json(Obj, "macAddress", MACAddress);
field_to_json(Obj, "manufacturer", Manufacturer); field_to_json(Obj, "manufacturer", Manufacturer);
@@ -56,9 +54,6 @@ namespace OpenWifi::GWObjects {
field_to_json(Obj, "pendingConfiguration", pendingConfiguration); field_to_json(Obj, "pendingConfiguration", pendingConfiguration);
field_to_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd); field_to_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd);
field_to_json(Obj, "restrictionDetails", restrictionDetails); field_to_json(Obj, "restrictionDetails", restrictionDetails);
field_to_json(Obj, "pendingUUID", pendingUUID);
field_to_json(Obj, "simulated", simulated);
field_to_json(Obj, "lastRecordedContact", lastRecordedContact);
} }
void Device::to_json_with_status(Poco::JSON::Object &Obj) const { void Device::to_json_with_status(Poco::JSON::Object &Obj) const {
@@ -68,7 +63,7 @@ namespace OpenWifi::GWObjects {
ConnectionState ConState; ConnectionState ConState;
if (AP_WS_Server()->GetState(SerialNumber, ConState)) { if (AP_WS_Server()->GetState(SerialNumber, ConState)) {
ConState.to_json(SerialNumber,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);
@@ -80,13 +75,6 @@ namespace OpenWifi::GWObjects {
field_to_json(Obj, "associations_2G", (uint64_t)0); field_to_json(Obj, "associations_2G", (uint64_t)0);
field_to_json(Obj, "associations_5G", (uint64_t)0); field_to_json(Obj, "associations_5G", (uint64_t)0);
field_to_json(Obj, "associations_6G", (uint64_t)0); field_to_json(Obj, "associations_6G", (uint64_t)0);
field_to_json(Obj, "hasRADIUSSessions", false);
field_to_json(Obj, "hasGPS", ConState.hasGPS);
field_to_json(Obj, "sanity", ConState.sanity);
field_to_json(Obj, "memoryUsed", ConState.memoryUsed);
field_to_json(Obj, "sanity", ConState.sanity);
field_to_json(Obj, "load", ConState.load);
field_to_json(Obj, "temperature", ConState.temperature);
} }
#endif #endif
} }
@@ -96,32 +84,20 @@ namespace OpenWifi::GWObjects {
field_from_json(Obj, "serialNumber", SerialNumber); field_from_json(Obj, "serialNumber", SerialNumber);
field_from_json(Obj, "deviceType", DeviceType); field_from_json(Obj, "deviceType", DeviceType);
field_from_json(Obj, "macAddress", MACAddress); field_from_json(Obj, "macAddress", MACAddress);
field_from_json(Obj, "manufacturer", Manufacturer);
field_from_json(Obj, "UUID", UUID);
field_from_json(Obj, "configuration", Configuration); field_from_json(Obj, "configuration", Configuration);
field_from_json(Obj, "notes", Notes); field_from_json(Obj, "notes", Notes);
field_from_json(Obj, "createdTimestamp", CreationTimestamp); field_from_json(Obj, "manufacturer", Manufacturer);
field_from_json(Obj, "lastConfigurationChange", LastConfigurationChange);
field_from_json(Obj, "lastConfigurationDownload", LastConfigurationDownload);
field_from_json(Obj, "lastFWUpdate", LastFWUpdate);
field_from_json(Obj, "owner", Owner); field_from_json(Obj, "owner", Owner);
field_from_json(Obj, "location", Location); field_from_json(Obj, "location", Location);
field_from_json(Obj, "venue", Venue); field_from_json(Obj, "venue", Venue);
field_from_json(Obj, "firmware", Firmware);
field_from_json(Obj, "compatible", Compatible); field_from_json(Obj, "compatible", Compatible);
field_from_json(Obj, "fwUpdatePolicy", FWUpdatePolicy);
field_from_json(Obj, "devicePassword", DevicePassword);
field_from_json(Obj, "subscriber", subscriber); field_from_json(Obj, "subscriber", subscriber);
field_from_json(Obj, "entity", entity); field_from_json(Obj, "entity", entity);
field_from_json(Obj, "modified", modified);
field_from_json(Obj, "locale", locale); field_from_json(Obj, "locale", locale);
field_from_json(Obj, "restrictedDevice", restrictedDevice); field_from_json(Obj, "restrictedDevice", restrictedDevice);
field_from_json(Obj, "pendingConfiguration", pendingConfiguration); field_from_json(Obj, "pendingConfiguration", pendingConfiguration);
field_from_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd); field_from_json(Obj, "pendingConfigurationCmd", pendingConfigurationCmd);
field_from_json(Obj, "restrictionDetails", restrictionDetails); field_from_json(Obj, "restrictionDetails", restrictionDetails);
field_from_json(Obj, "pendingUUID", pendingUUID);
field_from_json(Obj, "simulated", simulated);
field_from_json(Obj, "lastRecordedContact", lastRecordedContact);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -171,31 +147,6 @@ namespace OpenWifi::GWObjects {
field_to_json(Obj, "lastModified", LastModified); field_to_json(Obj, "lastModified", LastModified);
} }
void DefaultFirmware::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "deviceType", deviceType);
field_to_json(Obj, "description", Description);
field_to_json(Obj, "uri", uri);
field_to_json(Obj, "revision", revision);
field_to_json(Obj, "imageCreationDate", imageCreationDate);
field_to_json(Obj, "created", Created);
field_to_json(Obj, "lastModified", LastModified);
}
bool DefaultFirmware::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "deviceType", deviceType);
field_from_json(Obj, "description", Description);
field_from_json(Obj, "uri", uri);
field_from_json(Obj, "revision", revision);
field_from_json(Obj, "imageCreationDate", imageCreationDate);
field_from_json(Obj, "created", Created);
field_from_json(Obj, "lastModified", LastModified);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
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);
@@ -214,8 +165,6 @@ namespace OpenWifi::GWObjects {
field_to_json(Obj, "waitingForFile", WaitingForFile); field_to_json(Obj, "waitingForFile", WaitingForFile);
field_to_json(Obj, "attachFile", AttachDate); field_to_json(Obj, "attachFile", AttachDate);
field_to_json(Obj, "executionTime", executionTime); field_to_json(Obj, "executionTime", executionTime);
field_to_json(Obj, "lastTry", lastTry);
field_to_json(Obj, "deferred", deferred);
} }
bool DefaultConfiguration::from_json(const Poco::JSON::Object::Ptr &Obj) { bool DefaultConfiguration::from_json(const Poco::JSON::Object::Ptr &Obj) {
@@ -249,7 +198,7 @@ namespace OpenWifi::GWObjects {
return false; return false;
} }
void ConnectionState::to_json([[maybe_unused]] const std::string &SerialNumber, Poco::JSON::Object &Obj) { 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);
@@ -271,22 +220,6 @@ namespace OpenWifi::GWObjects {
field_to_json(Obj, "connectionCompletionTime", connectionCompletionTime); field_to_json(Obj, "connectionCompletionTime", connectionCompletionTime);
field_to_json(Obj, "totalConnectionTime", Utils::Now() - started); field_to_json(Obj, "totalConnectionTime", Utils::Now() - started);
field_to_json(Obj, "certificateExpiryDate", certificateExpiryDate); field_to_json(Obj, "certificateExpiryDate", certificateExpiryDate);
field_to_json(Obj, "connectReason", connectReason);
#ifdef TIP_GATEWAY_SERVICE
hasRADIUSSessions = RADIUSSessionTracker()->HasSessions(SerialNumber);
AP_WS_Server()->ExtendedAttributes(SerialNumber, hasGPS, sanity,
memoryUsed,
load,
temperature);
#endif
field_to_json(Obj, "hasRADIUSSessions", hasRADIUSSessions );
field_to_json(Obj, "hasGPS", hasGPS);
field_to_json(Obj, "sanity", sanity);
field_to_json(Obj, "memoryUsed", memoryUsed);
field_to_json(Obj, "sanity", sanity);
field_to_json(Obj, "load", load);
field_to_json(Obj, "temperature", temperature);
switch (VerifiedCertificate) { switch (VerifiedCertificate) {
case NO_CERTIFICATE: case NO_CERTIFICATE:
@@ -301,9 +234,6 @@ namespace OpenWifi::GWObjects {
case VERIFIED: case VERIFIED:
field_to_json(Obj, "verifiedCertificate", "VERIFIED"); field_to_json(Obj, "verifiedCertificate", "VERIFIED");
break; break;
case SIMULATED:
field_to_json(Obj, "verifiedCertificate", "SIMULATED");
break;
default: default:
field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE"); field_to_json(Obj, "verifiedCertificate", "NO_CERTIFICATE");
break; break;
@@ -430,10 +360,6 @@ namespace OpenWifi::GWObjects {
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);
field_to_json(Obj, "radsecKeepAlive", radsecKeepAlive);
field_to_json(Obj, "poolProxyIp", poolProxyIp);
field_to_json(Obj, "radsecPoolType", radsecPoolType);
field_to_json(Obj, "enabled", enabled);
} }
bool RadiusProxyPool::from_json(const Poco::JSON::Object::Ptr &Obj) { bool RadiusProxyPool::from_json(const Poco::JSON::Object::Ptr &Obj) {
@@ -444,10 +370,6 @@ namespace OpenWifi::GWObjects {
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);
field_from_json(Obj, "radsecKeepAlive", radsecKeepAlive);
field_from_json(Obj, "poolProxyIp", poolProxyIp);
field_from_json(Obj, "radsecPoolType", radsecPoolType);
field_from_json(Obj, "enabled", enabled);
return true; return true;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
} }
@@ -568,29 +490,6 @@ namespace OpenWifi::GWObjects {
return false; return false;
} }
void RangeOptions::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "NO_IR", NO_IR);
field_to_json(Obj, "AUTO_BW", AUTO_BW);
field_to_json(Obj, "DFS", DFS);
field_to_json(Obj, "NO_OUTDOOR", NO_OUTDOOR);
field_to_json(Obj, "wmmrule_ETSI", wmmrule_ETSI);
field_to_json(Obj, "NO_OFDM", NO_OFDM);
}
void FrequencyRange::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "from", from);
field_to_json(Obj, "to", to);
field_to_json(Obj, "channelWidth", channelWidth);
field_to_json(Obj, "powerDb", powerDb);
field_to_json(Obj, "options", options);
}
void RegulatoryCountryInfo::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "country", country);
field_to_json(Obj, "domain", domain);
field_to_json(Obj, "ranges", ranges);
}
void DeviceRestrictionsKeyInfo::to_json(Poco::JSON::Object &Obj) const { void DeviceRestrictionsKeyInfo::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "vendor", vendor); field_to_json(Obj, "vendor", vendor);
field_to_json(Obj, "algo", algo); field_to_json(Obj, "algo", algo);
@@ -645,74 +544,4 @@ namespace OpenWifi::GWObjects {
(T.commands != commands) || (T.developer != developer) || (T.ssh != ssh) || (T.commands != commands) || (T.developer != developer) || (T.ssh != ssh) ||
(T.key_info != key_info) || (T.country != country)); (T.key_info != key_info) || (T.country != country));
} }
void RADIUSSession::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "started", started);
field_to_json(Obj, "lastTransaction", lastTransaction);
field_to_json(Obj, "destination", destination);
field_to_json(Obj, "serialNumber", serialNumber);
field_to_json(Obj, "userName", userName);
field_to_json(Obj, "accountingSessionId", accountingSessionId);
field_to_json(Obj, "accountingMultiSessionId", accountingMultiSessionId);
field_to_json(Obj, "inputPackets", inputPackets);
field_to_json(Obj, "outputPackets", outputPackets);
field_to_json(Obj, "inputOctets", inputOctets);
field_to_json(Obj, "outputOctets", outputOctets);
field_to_json(Obj, "inputGigaWords", inputGigaWords);
field_to_json(Obj, "outputGigaWords", outputGigaWords);
field_to_json(Obj, "sessionTime", sessionTime);
field_to_json(Obj, "callingStationId", callingStationId);
field_to_json(Obj, "chargeableUserIdentity", chargeableUserIdentity);
field_to_json(Obj, "interface", interface);
field_to_json(Obj, "secret", secret);
field_to_json(Obj, "nasId", nasId);
field_to_json(Obj, "calledStationId", calledStationId);
}
void RADIUSSessionList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "sessions", sessions);
}
void RadiusCoADMParameters::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "accountingSessionId", accountingSessionId);
field_to_json(Obj, "accountingMultiSessionId", accountingMultiSessionId);
field_to_json(Obj, "callingStationId", callingStationId);
field_to_json(Obj, "chargeableUserIdentity", chargeableUserIdentity);
field_to_json(Obj, "userName", userName);
}
bool RadiusCoADMParameters::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "accountingSessionId", accountingSessionId);
field_from_json(Obj, "accountingMultiSessionId", accountingMultiSessionId);
field_from_json(Obj, "callingStationId", callingStationId);
field_from_json(Obj, "chargeableUserIdentity", chargeableUserIdentity);
field_from_json(Obj, "userName", userName);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
bool DeviceTransferRequest::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "server", server);
field_from_json(Obj, "port", port);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
bool DeviceCertificateUpdateRequest::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "serialNumber", serialNumber);
field_from_json(Obj, "encodedCertificate", encodedCertificate);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
} // namespace OpenWifi::GWObjects } // namespace OpenWifi::GWObjects

View File

@@ -11,13 +11,9 @@
#include "Poco/JSON/Object.h" #include "Poco/JSON/Object.h"
#include "RESTAPI_SecurityObjects.h" #include "RESTAPI_SecurityObjects.h"
#ifdef TIP_GATEWAY_SERVICE
#include <RADIUS_helpers.h>
#endif
namespace OpenWifi::GWObjects { namespace OpenWifi::GWObjects {
enum CertificateValidation { NO_CERTIFICATE, VALID_CERTIFICATE, MISMATCH_SERIAL, VERIFIED, SIMULATED }; enum CertificateValidation { NO_CERTIFICATE, VALID_CERTIFICATE, MISMATCH_SERIAL, VERIFIED };
struct ConnectionState { struct ConnectionState {
uint64_t MessageCount = 0; uint64_t MessageCount = 0;
@@ -42,15 +38,8 @@ namespace OpenWifi::GWObjects {
uint64_t sessionId = 0; uint64_t sessionId = 0;
double connectionCompletionTime = 0.0; double connectionCompletionTime = 0.0;
std::uint64_t certificateExpiryDate = 0; std::uint64_t certificateExpiryDate = 0;
std::uint64_t hasRADIUSSessions = 0;
bool hasGPS = false;
std::uint64_t sanity=0;
std::double_t memoryUsed=0.0;
std::double_t load=0.0;
std::double_t temperature=0.0;
std::string connectReason;
void to_json(const std::string &SerialNumber, Poco::JSON::Object &Obj) ; void to_json(Poco::JSON::Object &Obj) const;
}; };
struct DeviceRestrictionsKeyInfo { struct DeviceRestrictionsKeyInfo {
@@ -107,9 +96,6 @@ namespace OpenWifi::GWObjects {
std::string pendingConfiguration; std::string pendingConfiguration;
std::string pendingConfigurationCmd; std::string pendingConfigurationCmd;
DeviceRestrictions restrictionDetails; DeviceRestrictions restrictionDetails;
std::uint64_t pendingUUID = 0;
bool simulated=false;
std::uint64_t lastRecordedContact=0;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
void to_json_with_status(Poco::JSON::Object &Obj) const; void to_json_with_status(Poco::JSON::Object &Obj) const;
@@ -182,26 +168,6 @@ namespace OpenWifi::GWObjects {
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct DefaultFirmware {
std::string deviceType;
std::string Description;
std::string uri;
std::string revision;
uint64_t imageCreationDate;
uint64_t Created;
uint64_t LastModified;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DefaultFirmwareList {
std::vector<DefaultFirmware> firmwares;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct CommandDetails { struct CommandDetails {
std::string UUID; std::string UUID;
std::string SerialNumber; std::string SerialNumber;
@@ -222,11 +188,7 @@ namespace OpenWifi::GWObjects {
uint64_t AttachSize = 0; uint64_t AttachSize = 0;
std::string AttachType; std::string AttachType;
double executionTime = 0.0; double executionTime = 0.0;
std::uint64_t lastTry = 0;
bool deferred = false;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct BlackListedDevice { struct BlackListedDevice {
@@ -360,10 +322,6 @@ namespace OpenWifi::GWObjects {
RadiusProxyServerConfig acctConfig; RadiusProxyServerConfig acctConfig;
RadiusProxyServerConfig coaConfig; RadiusProxyServerConfig coaConfig;
bool useByDefault = false; bool useByDefault = false;
std::string radsecPoolType;
std::string poolProxyIp;
std::uint64_t radsecKeepAlive=25;
bool enabled=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);
@@ -376,139 +334,4 @@ namespace OpenWifi::GWObjects {
bool from_json(const Poco::JSON::Object::Ptr &Obj); bool from_json(const Poco::JSON::Object::Ptr &Obj);
}; };
struct RangeOptions {
bool NO_IR=false;
bool AUTO_BW=false;
bool DFS=false;
bool NO_OUTDOOR=false;
bool wmmrule_ETSI=false;
bool NO_OFDM=false;
void to_json(Poco::JSON::Object &Obj) const;
};
struct FrequencyRange {
float from = 0.0;
float to = 0.0;
int channelWidth = 0;
int powerDb = 0;
RangeOptions options;
void to_json(Poco::JSON::Object &Obj) const;
};
struct RegulatoryCountryInfo {
std::string country;
std::string domain;
std::vector<FrequencyRange> ranges;
void to_json(Poco::JSON::Object &Obj) const;
};
using RegulatoryInfoCountryMap = std::map<std::string,RegulatoryCountryInfo>;
struct RADIUSSession {
std::uint64_t started=0,
lastTransaction=0;
std::string serialNumber,
destination,
userName,
accountingSessionId,
accountingMultiSessionId,
callingStationId,
chargeableUserIdentity,
secret,
interface,
nasId;
std::uint64_t inputPackets = 0,
outputPackets = 0,
inputOctets = 0,
outputOctets = 0,
inputGigaWords = 0,
outputGigaWords = 0;
std::uint32_t sessionTime = 0;
std::string calledStationId;
#ifdef TIP_GATEWAY_SERVICE
RADIUS::RadiusPacket accountingPacket;
#endif
void to_json(Poco::JSON::Object &Obj) const;
};
struct RADIUSSessionList {
std::vector<RADIUSSession> sessions;
void to_json(Poco::JSON::Object &Obj) const;
};
struct RadiusCoADMParameters {
std::string accountingSessionId,
accountingMultiSessionId,
callingStationId,
chargeableUserIdentity,
userName;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
void to_json(Poco::JSON::Object &Obj) const;
};
enum class RadiusPoolStrategy {
round_robin, random, weighted, unknown
};
enum class RadiusEndpointType {
generic, radsec, globalreach, orion, unknown
};
static inline RadiusEndpointType RadiusEndpointType(const std::string &T) {
if(T=="generic") return RadiusEndpointType::generic;
if(T=="radsec") return RadiusEndpointType::radsec;
if(T=="globalreach") return RadiusEndpointType::globalreach;
if(T=="orion") return RadiusEndpointType::orion;
return RadiusEndpointType::unknown;
}
static inline RadiusPoolStrategy RadiusPoolStrategy(const std::string &T) {
if(T=="round_robin") return RadiusPoolStrategy::round_robin;
if(T=="random") return RadiusPoolStrategy::random;
if(T=="weighted") return RadiusPoolStrategy::weighted;
return RadiusPoolStrategy::unknown;
}
static inline std::string to_string(enum RadiusEndpointType T) {
switch(T) {
case RadiusEndpointType::generic: return "generic";
case RadiusEndpointType::radsec: return "radsec";
case RadiusEndpointType::globalreach: return "globalreach";
case RadiusEndpointType::orion: return "orion";
default:
return "unknown";
}
}
static inline std::string to_string(enum RadiusPoolStrategy T) {
switch(T) {
case RadiusPoolStrategy::round_robin: return "round_robin";
case RadiusPoolStrategy::random: return "random";
case RadiusPoolStrategy::weighted: return "weighted";
default:
return "unknown";
}
}
struct DeviceTransferRequest {
std::string serialNumber;
std::string server;
std::uint64_t port;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceCertificateUpdateRequest {
std::string serialNumber;
std::string encodedCertificate;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
} // namespace OpenWifi::GWObjects } // namespace OpenWifi::GWObjects

View File

@@ -92,7 +92,6 @@ namespace OpenWifi::OWLSObjects {
field_to_json(Obj, "endTime", endTime); field_to_json(Obj, "endTime", endTime);
field_to_json(Obj, "errorDevices", errorDevices); field_to_json(Obj, "errorDevices", errorDevices);
field_to_json(Obj, "owner", owner); field_to_json(Obj, "owner", owner);
field_to_json(Obj, "expectedDevices", expectedDevices);
} }
void Dashboard::to_json([[maybe_unused]] Poco::JSON::Object &Obj) const {} void Dashboard::to_json([[maybe_unused]] Poco::JSON::Object &Obj) const {}

View File

@@ -57,7 +57,6 @@ namespace OpenWifi::OWLSObjects {
uint64_t endTime; uint64_t endTime;
uint64_t errorDevices; uint64_t errorDevices;
std::string owner; std::string owner;
uint64_t expectedDevices;
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };

View File

@@ -1194,243 +1194,4 @@ namespace OpenWifi::ProvObjects {
return false; return false;
} }
void GLBLRAccountInfo::to_json(Poco::JSON::Object &Obj) const {
info.to_json(Obj);
field_to_json(Obj, "privateKey", privateKey);
field_to_json(Obj, "country", country);
field_to_json(Obj, "province", province);
field_to_json(Obj, "city", city);
field_to_json(Obj, "organization", organization);
field_to_json(Obj, "commonName", commonName);
field_to_json(Obj, "CSR", CSR);
field_to_json(Obj, "CSRPrivateKey", CSRPrivateKey);
field_to_json(Obj, "CSRPublicKey", CSRPublicKey);
field_to_json(Obj, "GlobalReachAcctId", GlobalReachAcctId);
}
bool GLBLRAccountInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
info.from_json(Obj);
field_from_json(Obj, "privateKey", privateKey);
field_from_json(Obj, "country", country);
field_from_json(Obj, "province", province);
field_from_json(Obj, "city", city);
field_from_json(Obj, "organization", organization);
field_from_json(Obj, "commonName", commonName);
field_from_json(Obj, "CSR", CSR);
field_from_json(Obj, "CSRPrivateKey", CSRPrivateKey);
field_from_json(Obj, "CSRPublicKey", CSRPublicKey);
field_from_json(Obj, "GlobalReachAcctId", GlobalReachAcctId);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void GLBLRCertificateInfo::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "id", id);
field_to_json(Obj, "name", name);
field_to_json(Obj, "accountId", accountId);
field_to_json(Obj, "csr", csr);
field_to_json(Obj, "certificate", certificate);
field_to_json(Obj, "certificateChain", certificateChain);
field_to_json(Obj, "certificateId", certificateId);
field_to_json(Obj, "expiresAt", expiresAt);
field_to_json(Obj, "created", created);
}
bool GLBLRCertificateInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "id", id);
field_from_json(Obj, "name", name);
field_from_json(Obj, "accountId", accountId);
field_from_json(Obj, "csr", csr);
field_from_json(Obj, "certificate", certificate);
field_from_json(Obj, "certificateChain", certificateChain);
field_from_json(Obj, "certificateId", certificateId);
field_from_json(Obj, "expiresAt", expiresAt);
field_from_json(Obj, "created", created);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void GooglOrionAccountInfo::to_json(Poco::JSON::Object &Obj) const {
info.to_json(Obj);
field_to_json(Obj, "privateKey", privateKey);
field_to_json(Obj, "certificate", certificate);
field_to_json(Obj, "cacerts", cacerts);
}
bool GooglOrionAccountInfo::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
info.from_json(Obj);
field_from_json(Obj, "privateKey", privateKey);
field_from_json(Obj, "certificate", certificate);
field_from_json(Obj, "cacerts", cacerts);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void RADIUSServer::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "Hostname", Hostname);
field_to_json(Obj, "IP", IP);
field_to_json(Obj, "Port", Port);
field_to_json(Obj, "Secret", Secret);
}
bool RADIUSServer::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "Hostname", Hostname);
field_from_json(Obj, "IP", IP);
field_from_json(Obj, "Port", Port);
field_from_json(Obj, "Secret", Secret);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void RADIUSEndPointRadiusType::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "Authentication", Authentication);
field_to_json(Obj, "Accounting", Accounting);
field_to_json(Obj, "CoA", CoA);
field_to_json(Obj, "AccountingInterval", AccountingInterval);
}
bool RADIUSEndPointRadiusType::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "Authentication", Authentication);
field_from_json(Obj, "Accounting", Accounting);
field_from_json(Obj, "CoA", CoA);
field_from_json(Obj, "AccountingInterval", AccountingInterval);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void RADIUSEndPointRadsecType::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "Hostname", Hostname);
field_to_json(Obj, "IP", IP);
field_to_json(Obj, "Port", Port);
field_to_json(Obj, "Secret", Secret);
field_to_json(Obj, "OpenRoamingType", OpenRoamingType);
field_to_json(Obj, "UseOpenRoamingAccount", UseOpenRoamingAccount);
field_to_json(Obj, "Weight", Weight);
field_to_json(Obj, "Certificate", Certificate);
field_to_json(Obj, "PrivateKey", PrivateKey);
field_to_json(Obj, "CaCerts", CaCerts);
field_to_json(Obj, "AllowSelfSigned", AllowSelfSigned);
}
bool RADIUSEndPointRadsecType::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "Hostname", Hostname);
field_from_json(Obj, "IP", IP);
field_from_json(Obj, "Port", Port);
field_from_json(Obj, "Secret", Secret);
field_from_json(Obj, "OpenRoamingType", OpenRoamingType);
field_from_json(Obj, "UseOpenRoamingAccount", UseOpenRoamingAccount);
field_from_json(Obj, "Weight", Weight);
field_from_json(Obj, "Certificate", Certificate);
field_from_json(Obj, "PrivateKey", PrivateKey);
field_from_json(Obj, "CaCerts", CaCerts);
field_from_json(Obj, "AllowSelfSigned", AllowSelfSigned);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void RADIUSEndPoint::to_json(Poco::JSON::Object &Obj) const {
info.to_json(Obj);
field_to_json(Obj, "Type", Type);
field_to_json(Obj, "RadsecServers", RadsecServers);
field_to_json(Obj, "RadiusServers", RadiusServers);
field_to_json(Obj, "PoolStrategy", PoolStrategy);
field_to_json(Obj, "Index", Index);
field_to_json(Obj, "UsedBy", UsedBy);
field_to_json(Obj, "UseGWProxy", UseGWProxy);
field_to_json(Obj, "NasIdentifier", NasIdentifier);
field_to_json(Obj, "AccountingInterval", AccountingInterval);
}
bool RADIUSEndPoint::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
info.from_json(Obj);
field_from_json(Obj, "Type", Type);
field_from_json(Obj, "RadsecServers", RadsecServers);
field_from_json(Obj, "RadiusServers", RadiusServers);
field_from_json(Obj, "PoolStrategy", PoolStrategy);
field_from_json(Obj, "Index", Index);
field_from_json(Obj, "UsedBy", UsedBy);
field_from_json(Obj, "UseGWProxy", UseGWProxy);
field_from_json(Obj, "NasIdentifier", NasIdentifier);
field_from_json(Obj, "AccountingInterval", AccountingInterval);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
void RADIUSEndpointUpdateStatus::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj, "lastUpdate", lastUpdate);
field_to_json(Obj, "lastConfigurationChange", lastConfigurationChange);
}
bool RADIUSEndpointUpdateStatus::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj, "lastUpdate", lastUpdate);
field_from_json(Obj, "lastConfigurationChange", lastConfigurationChange);
return true;
} catch (const Poco::Exception &E) {
}
return false;
}
bool RADIUSEndpointUpdateStatus::Read() {
Poco::File F(OpenWifi::MicroServiceDataDirectory()+"/RADIUSEndpointUpdateStatus.json");
try {
if (F.exists()) {
Poco::JSON::Parser P;
std::ifstream ifs(F.path(), std::ios_base::in | std::ios_base::binary);
auto Obj = P.parse(ifs);
return from_json(Obj.extract<Poco::JSON::Object::Ptr>());
}
} catch (...) {
}
return false;
}
bool RADIUSEndpointUpdateStatus::Save() {
Poco::File F(OpenWifi::MicroServiceDataDirectory()+"/RADIUSEndpointUpdateStatus.json");
try {
Poco::JSON::Object Obj;
to_json(Obj);
std::ofstream O(F.path(), std::ios_base::out | std::ios_base::trunc | std::ios_base::binary);
Poco::JSON::Stringifier::stringify(Obj, O);
return true;
} catch (...) {
}
return false;
}
bool RADIUSEndpointUpdateStatus::ChangeConfiguration() {
Read();
lastConfigurationChange = Utils::Now();
return Save();
}
} // namespace OpenWifi::ProvObjects } // namespace OpenWifi::ProvObjects

View File

@@ -29,7 +29,6 @@ namespace OpenWifi::ProvObjects {
Types::TagList tags; Types::TagList tags;
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);
}; };
@@ -37,7 +36,6 @@ namespace OpenWifi::ProvObjects {
Types::UUIDvec_t serialNumbers; Types::UUIDvec_t serialNumbers;
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);
}; };
@@ -48,7 +46,6 @@ namespace OpenWifi::ProvObjects {
std::string policy; std::string policy;
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);
}; };
@@ -60,18 +57,14 @@ namespace OpenWifi::ProvObjects {
Types::UUID_t venue; Types::UUID_t venue;
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<ManagementPolicy> ManagementPolicyVec; typedef std::vector<ManagementPolicy> ManagementPolicyVec;
struct RRMAlgorithmDetails { struct RRMAlgorithmDetails {
std::string name; std::string name;
std::string parameters; std::string parameters;
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);
}; };
@@ -79,9 +72,7 @@ namespace OpenWifi::ProvObjects {
std::string vendor; std::string vendor;
std::string schedule; std::string schedule;
std::vector<RRMAlgorithmDetails> algorithms; std::vector<RRMAlgorithmDetails> algorithms;
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);
}; };
@@ -91,7 +82,6 @@ namespace OpenWifi::ProvObjects {
std::string firmwareUpgrade{"inherit"}; std::string firmwareUpgrade{"inherit"};
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);
}; };
@@ -114,10 +104,8 @@ namespace OpenWifi::ProvObjects {
Types::UUIDvec_t configurations; Types::UUIDvec_t configurations;
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<Entity> EntityVec; typedef std::vector<Entity> EntityVec;
struct DiGraphEntry { struct DiGraphEntry {
@@ -125,7 +113,6 @@ namespace OpenWifi::ProvObjects {
Types::UUID_t child; Types::UUID_t child;
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);
}; };
@@ -153,10 +140,8 @@ namespace OpenWifi::ProvObjects {
Types::UUIDvec_t boards; Types::UUIDvec_t boards;
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<Venue> VenueVec; typedef std::vector<Venue> VenueVec;
struct UserInfoDigest { struct UserInfoDigest {
@@ -165,7 +150,6 @@ namespace OpenWifi::ProvObjects {
std::string userType; std::string userType;
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);
}; };
@@ -178,10 +162,8 @@ namespace OpenWifi::ProvObjects {
Types::UUID_t venue; Types::UUID_t venue;
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<ManagementRole> ManagementRoleVec; typedef std::vector<ManagementRole> ManagementRoleVec;
enum LocationType { enum LocationType {
@@ -250,10 +232,8 @@ namespace OpenWifi::ProvObjects {
Types::UUID_t managementPolicy; Types::UUID_t managementPolicy;
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<Location> LocationVec; typedef std::vector<Location> LocationVec;
struct OperatorLocation { struct OperatorLocation {
@@ -273,10 +253,8 @@ namespace OpenWifi::ProvObjects {
Types::UUID_t managementPolicy; Types::UUID_t managementPolicy;
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<Location> LocationVec; typedef std::vector<Location> LocationVec;
struct SubLocation { struct SubLocation {
@@ -292,7 +270,6 @@ namespace OpenWifi::ProvObjects {
std::string geoCode; std::string geoCode;
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);
}; };
@@ -300,7 +277,6 @@ namespace OpenWifi::ProvObjects {
std::vector<OperatorLocation> locations; std::vector<OperatorLocation> locations;
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);
}; };
@@ -380,10 +356,8 @@ namespace OpenWifi::ProvObjects {
Types::UUID_t managementPolicy; Types::UUID_t managementPolicy;
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<Contact> ContactVec; typedef std::vector<Contact> ContactVec;
struct OperatorContact { struct OperatorContact {
@@ -405,7 +379,6 @@ namespace OpenWifi::ProvObjects {
Types::UUID_t managementPolicy; Types::UUID_t managementPolicy;
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);
}; };
@@ -424,7 +397,6 @@ namespace OpenWifi::ProvObjects {
std::string accessPIN; std::string accessPIN;
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);
}; };
@@ -432,7 +404,6 @@ namespace OpenWifi::ProvObjects {
std::vector<OperatorContact> contacts; std::vector<OperatorContact> contacts;
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);
}; };
@@ -445,10 +416,8 @@ namespace OpenWifi::ProvObjects {
std::string configuration; std::string configuration;
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<DeviceConfigurationElement> DeviceConfigurationElementVec; typedef std::vector<DeviceConfigurationElement> DeviceConfigurationElementVec;
struct DeviceConfiguration { struct DeviceConfiguration {
@@ -465,10 +434,8 @@ namespace OpenWifi::ProvObjects {
std::string subscriber; std::string subscriber;
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<DeviceConfiguration> DeviceConfigurationVec; typedef std::vector<DeviceConfiguration> DeviceConfigurationVec;
struct InventoryTag { struct InventoryTag {
@@ -492,7 +459,6 @@ namespace OpenWifi::ProvObjects {
bool doNotAllowOverrides = false; bool doNotAllowOverrides = 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);
}; };
@@ -502,7 +468,6 @@ namespace OpenWifi::ProvObjects {
InventoryTagVec taglist; InventoryTagVec taglist;
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);
}; };
@@ -513,7 +478,6 @@ namespace OpenWifi::ProvObjects {
uint64_t errorCode; uint64_t errorCode;
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);
}; };
@@ -522,7 +486,6 @@ namespace OpenWifi::ProvObjects {
Types::CountedMap tenants; Types::CountedMap tenants;
void reset(); void reset();
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;
}; };
@@ -532,7 +495,6 @@ namespace OpenWifi::ProvObjects {
std::string description; std::string description;
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);
}; };
@@ -541,7 +503,6 @@ namespace OpenWifi::ProvObjects {
std::vector<ExpandedUseEntry> entries; std::vector<ExpandedUseEntry> entries;
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);
}; };
@@ -549,7 +510,6 @@ namespace OpenWifi::ProvObjects {
std::vector<ExpandedUseEntryList> entries; std::vector<ExpandedUseEntryList> entries;
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);
}; };
@@ -557,13 +517,10 @@ namespace OpenWifi::ProvObjects {
Types::UUIDvec_t list; Types::UUIDvec_t 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);
}; };
enum ACLACCESS { enum ACLACCESS { NONE = 0, READ = 1, MODIFY = 2, CREATE = 3, DELETE = 4 };
NONE = 0, READ = 1, MODIFY = 2, CREATE = 3, DELETE = 4
};
struct ObjectACL { struct ObjectACL {
UuidList users; UuidList users;
@@ -571,7 +528,6 @@ namespace OpenWifi::ProvObjects {
uint64_t access = (uint64_t)NONE; uint64_t access = (uint64_t)NONE;
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);
}; };
@@ -579,7 +535,6 @@ namespace OpenWifi::ProvObjects {
std::vector<ObjectACL> list; std::vector<ObjectACL> 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);
}; };
@@ -594,7 +549,6 @@ namespace OpenWifi::ProvObjects {
std::string venue; std::string venue;
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);
}; };
@@ -602,7 +556,6 @@ namespace OpenWifi::ProvObjects {
std::vector<Map> list; std::vector<Map> 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);
}; };
@@ -632,7 +585,6 @@ namespace OpenWifi::ProvObjects {
std::string operatorId; std::string operatorId;
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);
}; };
@@ -643,7 +595,6 @@ namespace OpenWifi::ProvObjects {
std::string value; std::string value;
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);
}; };
@@ -651,7 +602,6 @@ namespace OpenWifi::ProvObjects {
std::vector<Variable> variables; std::vector<Variable> variables;
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);
}; };
@@ -666,7 +616,6 @@ namespace OpenWifi::ProvObjects {
Types::UUID_t managementPolicy; Types::UUID_t managementPolicy;
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);
}; };
@@ -674,7 +623,6 @@ namespace OpenWifi::ProvObjects {
std::vector<VariableBlock> variableBlocks; std::vector<VariableBlock> variableBlocks;
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);
}; };
@@ -689,7 +637,6 @@ namespace OpenWifi::ProvObjects {
std::string registrationId; std::string registrationId;
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);
}; };
@@ -697,7 +644,6 @@ namespace OpenWifi::ProvObjects {
std::vector<Operator> operators; std::vector<Operator> operators;
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);
}; };
@@ -708,7 +654,6 @@ namespace OpenWifi::ProvObjects {
Types::UUIDvec_t devices; Types::UUIDvec_t 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);
}; };
@@ -724,7 +669,6 @@ namespace OpenWifi::ProvObjects {
bool defaultService = false; bool defaultService = 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);
}; };
@@ -732,7 +676,6 @@ namespace OpenWifi::ProvObjects {
std::vector<ServiceClass> serviceClasses; std::vector<ServiceClass> serviceClasses;
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);
}; };
@@ -743,7 +686,6 @@ namespace OpenWifi::ProvObjects {
std::string firmwareRCOnly{"inherit"}; std::string firmwareRCOnly{"inherit"};
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);
}; };
@@ -768,7 +710,6 @@ namespace OpenWifi::ProvObjects {
std::string realMacAddress; std::string realMacAddress;
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);
}; };
@@ -776,7 +717,6 @@ namespace OpenWifi::ProvObjects {
std::vector<SubscriberDevice> subscriberDevices; std::vector<SubscriberDevice> subscriberDevices;
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);
}; };
@@ -789,7 +729,6 @@ namespace OpenWifi::ProvObjects {
std::uint64_t modified; std::uint64_t modified;
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);
}; };
@@ -799,119 +738,12 @@ namespace OpenWifi::ProvObjects {
std::vector<ConfigurationOverride> overrides; std::vector<ConfigurationOverride> overrides;
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);
}; };
bool UpdateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U, bool UpdateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U,
ObjectInfo &I); ObjectInfo &I);
bool CreateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U, bool CreateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U,
ObjectInfo &I); ObjectInfo &I);
bool CreateObjectInfo(const SecurityObjects::UserInfo &U, ObjectInfo &I); bool CreateObjectInfo(const SecurityObjects::UserInfo &U, ObjectInfo &I);
struct GLBLRAccountInfo {
ObjectInfo info;
std::string privateKey;
std::string country, province, city, organization, commonName;
std::string CSR, CSRPrivateKey, CSRPublicKey;
std::string GlobalReachAcctId;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct GLBLRCertificateInfo {
std::string id;
std::string name;
std::string accountId;
std::string csr;
std::string certificate;
std::string certificateChain;
std::string certificateId;
std::uint64_t expiresAt = 0;
std::uint64_t created = 0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct GooglOrionAccountInfo {
ObjectInfo info;
std::string privateKey;
std::string certificate;
std::vector<std::string> cacerts;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RADIUSServer {
std::string Hostname;
std::string IP;
std::uint64_t Port=0;
std::string Secret;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RADIUSEndPointRadiusType {
std::vector<RADIUSServer> Authentication;
std::vector<RADIUSServer> Accounting;
std::vector<RADIUSServer> CoA;
std::uint64_t AccountingInterval = 60;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RADIUSEndPointRadsecType {
std::string Hostname;
std::string IP;
std::uint64_t Port=2083;
std::string Secret{"radsec"};
std::string OpenRoamingType;
std::string UseOpenRoamingAccount;
std::uint64_t Weight=0;
std::string Certificate;
std::string PrivateKey;
std::vector<std::string> CaCerts;
bool AllowSelfSigned=false;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RADIUSEndPoint {
ObjectInfo info;
std::string Type{"radius"};
std::string PoolStrategy{"none"};
bool UseGWProxy=true;
std::string Index;
std::vector<std::string> UsedBy;
std::vector<RADIUSEndPointRadiusType> RadiusServers;
std::vector<RADIUSEndPointRadsecType> RadsecServers;
std::string NasIdentifier;
std::uint64_t AccountingInterval=600;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RADIUSEndpointUpdateStatus {
std::uint64_t lastUpdate=0;
std::uint64_t lastConfigurationChange=0;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
bool Read();
bool Save();
bool ChangeConfiguration();
};
}; // namespace OpenWifi::ProvObjects }; // namespace OpenWifi::ProvObjects

View File

@@ -1,8 +0,0 @@
//
// Created by stephane bourque on 2023-10-18.
//
#include "GenericRadius.h"
namespace OpenWifi {
} // OpenWifi

View File

@@ -1,67 +0,0 @@
//
// Created by stephane bourque on 2023-10-18.
//
#pragma once
#include <Poco/Net/IPAddress.h>
#include <Poco/Net/SocketAddress.h>
#include <framework/utils.h>
#include <framework/SubSystemServer.h>
#include <RESTObjects/RESTAPI_ProvObjects.h>
namespace OpenWifi {
namespace GenericRadius {
class OpenRoaming : public SubSystemServer {
public:
static auto instance() {
static auto instance_ = new OpenRoaming;
return instance_;
}
inline int Start() override {
return 0;
}
inline void Stop() override {
}
inline bool Render(const OpenWifi::ProvObjects::RADIUSEndPoint &RE, const std::string &SerialNumber,
Poco::JSON::Object &Result) {
if (RE.UseGWProxy) {
Poco::JSON::Object Auth, Acct, CoA;
Auth.set("host", RE.Index);
Auth.set("port", RE.RadiusServers[0].Authentication[0].Port);
Auth.set("secret", RE.RadiusServers[0].Authentication[0].Secret);
Acct.set("host", RE.Index);
Acct.set("port", RE.RadiusServers[0].Accounting[0].Port);
Acct.set("secret", RE.RadiusServers[0].Accounting[0].Secret);
Acct.set("interval", RE.AccountingInterval);
CoA.set("host", RE.Index);
CoA.set("port", RE.RadiusServers[0].CoA[0].Port);
CoA.set("secret", RE.RadiusServers[0].CoA[0].Secret);
Result.set("nas-identifier", RE.NasIdentifier.empty() ? SerialNumber : RE.NasIdentifier);
Result.set("authentication", Auth);
Result.set("accounting", Acct);
Result.set("dynamic-authorization", CoA);
} else {
}
return false;
}
private:
OpenRoaming() noexcept
: SubSystemServer("OpenRoaming_GenericRadius", "GENRAD", "genrad") {
}
};
}
inline auto OpenRoaming_GenericRadius() { return GenericRadius::OpenRoaming::instance(); }
}

View File

@@ -1,258 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#include "GlobalReach.h"
#include <Poco/JWT/Token.h>
#include <Poco/JWT/Signer.h>
#include <Poco/Net/HTTPSClientSession.h>
#include <Poco/Net/DNS.h>
#include <Poco/URI.h>
#include <Poco/TemporaryFile.h>
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Parser.h>
#include <framework/RESTAPI_Handler.h>
#include <framework/MicroServiceFuncs.h>
#include <StorageService.h>
namespace OpenWifi {
namespace GlobalReach {
int OpenRoaming::Start() {
poco_information(Logger(), "Starting...");
InitCache();
return 0;
}
void OpenRoaming::Stop() {
poco_information(Logger(), "Stopping...");
poco_information(Logger(), "Stopped...");
}
void OpenRoaming::InitCache() {
auto F = [&](const ProvObjects::GLBLRAccountInfo &Info) {
poco_information(Logger(), fmt::format("Adding {} to cache.", Info.info.name));
if (!Info.privateKey.empty() && !Info.GlobalReachAcctId.empty()) {
MakeToken(Info.GlobalReachAcctId, Info.privateKey);
}
return true;
};
StorageService()->GLBLRAccountInfoDB().Iterate(F);
}
bool OpenRoaming::Render(const OpenWifi::ProvObjects::RADIUSEndPoint &RE, const std::string &SerialNumber, Poco::JSON::Object &Result) {
if(RE.UseGWProxy) {
Poco::JSON::Object Auth, Acct, CoA;
Auth.set("host", RE.Index);
Auth.set("port", 1812 );
Auth.set("secret", RE.RadsecServers[0].Secret);
Acct.set("host", RE.Index);
Acct.set("port", 1813);
Acct.set("secret", RE.RadsecServers[0].Secret);
Acct.set("interval", RE.AccountingInterval);
CoA.set("host", RE.Index);
CoA.set("port", 3799);
CoA.set("secret", RE.RadsecServers[0].Secret);
Result.set("nas-identifier", RE.NasIdentifier.empty() ? SerialNumber : RE.NasIdentifier );
Result.set("authentication", Auth);
Result.set("accounting", Acct);
Result.set("dynamic-authorization", CoA);
} else {
}
return false;
}
bool OpenRoaming::CreateRADSECCertificate(
const std::string &GlobalReachAccountId,
const std::string &Name,
const std::string &CSR,
ProvObjects::GLBLRCertificateInfo &NewCertificate) {
try {
auto BearerToken = MakeToken(GlobalReachAccountId);
Poco::URI URI{"https://config.openro.am/v1/radsec/issue"};
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST, Path,
Poco::Net::HTTPMessage::HTTP_1_1);
Request.add("Authorization", "Bearer " + BearerToken);
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(10000, 10000));
Poco::JSON::Object CertRequestBody;
CertRequestBody.set("name", Name);
CertRequestBody.set("csr", CSR);
std::ostringstream os;
CertRequestBody.stringify(os);
Request.setContentType("application/json");
Request.setContentLength((long) os.str().size());
auto &Body = Session.sendRequest(Request);
Body << os.str();
Poco::Net::HTTPResponse Response;
std::istream &is = Session.receiveResponse(Response);
if (Response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) {
Poco::JSON::Parser P;
auto Result = P.parse(is).extract<Poco::JSON::Object::Ptr>();
RESTAPIHandler::AssignIfPresent(Result, "certificate", NewCertificate.certificate);
RESTAPIHandler::AssignIfPresent(Result, "certificate_chain", NewCertificate.certificateChain);
RESTAPIHandler::AssignIfPresent(Result, "certificate_id", NewCertificate.certificateId);
RESTAPIHandler::AssignIfPresent(Result, "expires_at", NewCertificate.expiresAt);
return true;
}
Poco::JSON::Parser P;
std::ostringstream oos;
auto Result = P.parse(is).extract<Poco::JSON::Object::Ptr>();
Result->stringify(oos);
} catch (const Poco::Exception &E) {
poco_error(Logger(),
fmt::format("Could not create a new RADSEC certificate: {},{}", E.name(), E.displayText()));
}
return false;
}
bool OpenRoaming::GetRADSECCertificate(
const std::string &GlobalReachAccountId,
std::string &CertificateId,
ProvObjects::GLBLRCertificateInfo &NewCertificate) {
try {
Poco::URI URI{fmt::format("https://config.openro.am/v1/radsec/cert/{}", CertificateId)};
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, Path,
Poco::Net::HTTPMessage::HTTP_1_1);
auto BearerToken = MakeToken(GlobalReachAccountId);
Request.add("Authorization", "Bearer " + BearerToken);
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(10000, 10000));
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;
auto Result = P.parse(is).extract<Poco::JSON::Object::Ptr>();
RESTAPIHandler::AssignIfPresent(Result, "certificate", NewCertificate.certificate);
RESTAPIHandler::AssignIfPresent(Result, "certificate_chain", NewCertificate.certificateChain);
RESTAPIHandler::AssignIfPresent(Result, "certificate_id", NewCertificate.certificateId);
RESTAPIHandler::AssignIfPresent(Result, "expires_at", NewCertificate.expiresAt);
return true;
}
} catch (const Poco::Exception &E) {
poco_error(Logger(), fmt::format("Could not retrieve the certificate from GlobalReach: {},{}", E.name(),
E.displayText()));
}
return false;
}
std::string
OpenRoaming::MakeToken(const std::string &GlobalReachAccountId, const std::string &PrivateKey) {
try {
Poco::JWT::Token token;
token.setType("JWT");
token.setAlgorithm("ES256");
token.setIssuedAt(std::time(nullptr));
token.payload().set("iss", GlobalReachAccountId);
token.payload().set("iat", (unsigned long) std::time(nullptr));
Poco::SharedPtr<Poco::Crypto::ECKey> Key;
auto KeyHash = Utils::ComputeHash(PrivateKey);
auto KeyHint = PrivateKeys_.find(GlobalReachAccountId);
if (KeyHint != PrivateKeys_.end() && PrivateKey.empty()) {
Key = KeyHint->second.second;
} else {
if (PrivateKey.empty()) {
return "";
}
Poco::TemporaryFile F;
std::ofstream ofs(F.path().c_str(),
std::ios_base::trunc | std::ios_base::out | std::ios_base::binary);
ofs << PrivateKey;
ofs.close();
auto NewKey = Poco::SharedPtr<Poco::Crypto::ECKey>(
new Poco::Crypto::ECKey("", F.path(), ""));
Key = NewKey;
PrivateKeys_[GlobalReachAccountId] = std::make_pair(KeyHash, NewKey);
}
Poco::JWT::Signer Signer;
Signer.setECKey(Key);
Signer.addAllAlgorithms();
return Signer.sign(token, Poco::JWT::Signer::ALGO_ES256);
} catch (const Poco::Exception &E) {
poco_error(Logger(),
fmt::format("Cannot create a Global Reach token: {},{}", E.name(), E.displayText()));
}
return "";
}
bool
OpenRoaming::VerifyAccount(const std::string &GlobalReachAccountId, const std::string &PrivateKey,
std::string &Name) {
auto BearerToken = MakeToken(GlobalReachAccountId, PrivateKey);
Poco::URI URI{"https://config.openro.am/v1/config"};
std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, Path,
Poco::Net::HTTPMessage::HTTP_1_1);
Request.add("Authorization", "Bearer " + BearerToken);
Poco::Net::HTTPSClientSession Session(URI.getHost(), URI.getPort());
Session.setTimeout(Poco::Timespan(10000, 10000));
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;
auto Result = P.parse(is).extract<Poco::JSON::Object::Ptr>();
if (Result->has("name")) {
Name = Result->get("name").toString();
}
return true;
}
return false;
}
// static std::string ServiceName{"\"aaa+auth:radius.tls.tcp\""};
static std::string ServiceName{"\"x-openroam:radius.tls.tcp\""};
std::vector<Utils::HostNameServerResult> OpenRoaming::GetServers() {
const std::string &domain = "openro.am";
auto Naptrs = Utils::getNAPTRRecords(domain);
std::vector<Utils::HostNameServerResult> Results;
for(const auto &rec:Naptrs) {
if(rec.service==ServiceName) {
auto Srvs = Utils::getSRVRecords(rec.replacement);
for(const auto &srv:Srvs) {
Utils::HostNameServerResult R{srv.srvname,srv.port};
if(!Utils::ValidIP(srv.srvname)) {
auto Server = Poco::Net::DNS::hostByName(srv.srvname).addresses();
if(!Server.empty()) {
R.Hostname = Server[0].toString();
}
}
Results.emplace_back(R);
}
}
}
return Results;
}
}
} // OpenWifi

View File

@@ -1,57 +0,0 @@
//
// Created by stephane bourque on 2023-09-11.
//
#pragma once
#include "framework/SubSystemServer.h"
#include "framework/utils.h"
#include "Poco/JSON/Object.h"
#include "RESTObjects/RESTAPI_ProvObjects.h"
namespace OpenWifi {
namespace GlobalReach {
class OpenRoaming : public SubSystemServer {
public:
static auto instance() {
static auto instance_ = new OpenRoaming;
return instance_;
}
int Start() override;
void Stop() override;
bool CreateRADSECCertificate(const std::string &AccountName,
const std::string &Name,
const std::string &CSR,
ProvObjects::GLBLRCertificateInfo &NewCertificate);
bool GetRADSECCertificate(const std::string &AccountName, std::string &CertificateId,
ProvObjects::GLBLRCertificateInfo &NewCertificate);
bool
VerifyAccount(const std::string &GlobalReachAccountId, const std::string &PrivateKey, std::string &Name);
void InitCache();
bool Render(const OpenWifi::ProvObjects::RADIUSEndPoint &RE, const std::string & SerialNUmber, Poco::JSON::Object &Result);
std::vector<Utils::HostNameServerResult> GetServers();
private:
std::string MakeToken(const std::string &GlobalReachAccountId, const std::string &PrivateKey = "");
std::map<std::string, std::pair<std::string, Poco::SharedPtr<Poco::Crypto::ECKey>>> PrivateKeys_;
OpenRoaming() noexcept
: SubSystemServer("OpenRoaming_GlobalReach", "GLBL-REACH", "globalreach") {
}
};
}
inline auto OpenRoaming_GlobalReach() { return GlobalReach::OpenRoaming::instance(); }
} // OpenWifi

View File

@@ -1,79 +0,0 @@
//
// Created by stephane bourque on 2023-09-28.
//
#pragma once
#include <Poco/Net/IPAddress.h>
#include <Poco/Net/SocketAddress.h>
#include <framework/utils.h>
#include <framework/SubSystemServer.h>
namespace OpenWifi {
namespace Orion {
class OpenRoaming : public SubSystemServer {
public:
static auto instance() {
static auto instance_ = new OpenRoaming;
return instance_;
}
inline int Start() override {
return 0;
}
inline void Stop() override {
}
static inline const std::vector<Utils::HostNameServerResult> OrionWifiServerAddresses = {
{"216.239.32.91", 2083},
{"216.239.34.91", 2083}
};
inline std::vector<Utils::HostNameServerResult> GetServers() {
return OrionWifiServerAddresses;
}
inline bool Render(const OpenWifi::ProvObjects::RADIUSEndPoint &RE, const std::string &SerialNumber, Poco::JSON::Object &Result) {
if(RE.UseGWProxy) {
Poco::JSON::Object Auth, Acct, CoA;
Auth.set("host", RE.Index);
Auth.set("port", 1812 );
Auth.set("secret", RE.RadsecServers[0].Secret);
Acct.set("host", RE.Index);
Acct.set("port", 1813);
Acct.set("secret", RE.RadsecServers[0].Secret);
Acct.set("interval", RE.AccountingInterval);
CoA.set("host", RE.Index);
CoA.set("port", 3799);
CoA.set("secret", RE.RadsecServers[0].Secret);
Result.set("nas-identifier", RE.NasIdentifier.empty() ? SerialNumber : RE.NasIdentifier );
Result.set("authentication", Auth);
Result.set("accounting", Acct);
Result.set("dynamic-authorization", CoA);
} else {
}
return false;
}
private:
OpenRoaming() noexcept
: SubSystemServer("OpenRoaming_Orion", "ORION", "orion") {
}
};
}
inline auto OpenRoaming_Orion() { return Orion::OpenRoaming::instance(); }
}

View File

@@ -1,8 +0,0 @@
//
// Created by stephane bourque on 2023-10-03.
//
#include "Radsec.h"
namespace OpenWidi {
} // OpenWidi

View File

@@ -1,71 +0,0 @@
//
// Created by stephane bourque on 2023-10-03.
//
#pragma once
#include <Poco/Net/IPAddress.h>
#include <Poco/Net/SocketAddress.h>
#include <framework/utils.h>
#include <framework/SubSystemServer.h>
#include <RESTObjects/RESTAPI_ProvObjects.h>
namespace OpenWifi {
namespace Radsec {
class OpenRoaming : public SubSystemServer {
public:
static auto instance() {
static auto instance_ = new OpenRoaming;
return instance_;
}
inline int Start() override {
return 0;
}
inline void Stop() override {
}
inline bool Render(const OpenWifi::ProvObjects::RADIUSEndPoint &RE, const std::string &SerialNumber, Poco::JSON::Object &Result) {
if(RE.UseGWProxy) {
Poco::JSON::Object Auth, Acct, CoA;
Auth.set("host", RE.Index);
Auth.set("port", 1812 );
Auth.set("secret", RE.RadsecServers[0].Secret);
Acct.set("host", RE.Index);
Acct.set("port", 1813);
Acct.set("secret", RE.RadsecServers[0].Secret);
Acct.set("interval", RE.AccountingInterval);
CoA.set("host", RE.Index);
CoA.set("port", 3799);
CoA.set("secret", RE.RadsecServers[0].Secret);
Result.set("nas-identifier", RE.NasIdentifier.empty() ? SerialNumber : RE.NasIdentifier );
Result.set("authentication", Auth);
Result.set("accounting", Acct);
Result.set("dynamic-authorization", CoA);
} else {
}
return false;
}
private:
OpenRoaming() noexcept
: SubSystemServer("OpenRoaming_Raadsec", "RADSEC", "radsec") {
}
};
}
inline auto OpenRoaming_Radsec() { return Radsec::OpenRoaming::instance(); }
}

View File

@@ -1,5 +0,0 @@
//
// Created by stephane bourque on 2023-10-02.
//
#include "RadiusEndpointUpdater.h"

View File

@@ -1,225 +0,0 @@
//
// Created by stephane bourque on 2023-10-02.
//
#pragma once
#include <vector>
#include <utility>
#include <framework/AppServiceRegistry.h>
#include <framework/utils.h>
#include <StorageService.h>
#include <RadiusEndpointTypes/OrionWifi.h>
#include <RadiusEndpointTypes/GlobalReach.h>
#include <sdks/SDK_gw.h>
#include <RESTObjects/RESTAPI_GWobjects.h>
namespace OpenWifi {
class RadiusEndpointUpdater {
public:
void ParseCertChain(const std::string &Chain, std::vector<std::string> &ChainVec) {
std::istringstream os(Chain);
std::string CurrentCert;
bool InCert = false;
std::string Line;
while(std::getline(os,Line)) {
if(Line=="-----BEGIN CERTIFICATE-----") {
InCert = true;
CurrentCert += Line;
CurrentCert += "\n";
continue;
}
if(Line=="-----END CERTIFICATE-----" && InCert) {
InCert = false;
CurrentCert += Line;
CurrentCert += "\n";
ChainVec.emplace_back(CurrentCert);
continue;
}
if(InCert) {
CurrentCert += Line;
CurrentCert += "\n";
}
}
}
void UpdateRadiusServerEntry( GWObjects::RadiusProxyServerConfig &Config,
const ProvObjects::RADIUSEndPoint &Endpoint,
const std::vector<ProvObjects::RADIUSServer> &Servers) {
Config.monitor = false;
Config.strategy = Endpoint.PoolStrategy;
Config.monitorMethod = "none";
Config.strategy = "random";
for (const auto &Server: Servers) {
GWObjects::RadiusProxyServerEntry PE;
PE.radsec = false;
PE.name = Server.Hostname;
PE.ignore = false;
PE.ip = Server.IP;
PE.port = PE.radsecPort = Server.Port;
PE.allowSelfSigned = false;
PE.weight = 10;
PE.secret = PE.radsecSecret = "radsec";
Config.servers.emplace_back(PE);
}
}
inline bool UpdateEndpoints( RESTAPIHandler *Client, std::uint64_t & ErrorCode,
std::string & ErrorDetails,
std::string & ErrorDescription) {
std::vector<ProvObjects::RADIUSEndPoint> Endpoints;
GWObjects::RadiusProxyPoolList Pools;
StorageService()->RadiusEndpointDB().GetRecords(0,500,Endpoints);
for(const auto &Endpoint:Endpoints) {
GWObjects::RadiusProxyPool PP;
PP.name = Endpoint.info.name;
PP.description = Endpoint.info.description;
PP.useByDefault = false;
PP.poolProxyIp = Endpoint.Index;
PP.radsecKeepAlive = 25;
PP.enabled = true;
if(Endpoint.Type=="orion" && !Endpoint.RadsecServers.empty()) {
auto Svrs = OpenRoaming_Orion()->GetServers();
PP.radsecPoolType="orion";
ProvObjects::GooglOrionAccountInfo OA;
if(StorageService()->OrionAccountsDB().GetRecord("id", Endpoint.RadsecServers[0].UseOpenRoamingAccount, OA)) {
for(auto *ServerType:{&PP.authConfig, &PP.acctConfig, &PP.coaConfig}) {
ServerType->monitor = false;
ServerType->strategy = Endpoint.PoolStrategy;
ServerType->monitorMethod = "none";
ServerType->strategy = "random";
int i=1;
for (const auto &Server: Svrs) {
GWObjects::RadiusProxyServerEntry PE;
PE.radsecCert = Utils::base64encode((const u_char *)OA.certificate.c_str(),OA.certificate.size());
PE.radsecKey = Utils::base64encode((const u_char *)OA.privateKey.c_str(),OA.privateKey.size());
for(const auto &cert:OA.cacerts) {
auto C = Utils::base64encode((const u_char *)cert.c_str(),cert.size());
PE.radsecCacerts.emplace_back(C);
}
PE.radsec = true;
PE.name = fmt::format("Server {}",i++);
PE.ignore = false;
PE.ip = Server.Hostname;
PE.port = PE.radsecPort = Server.Port;
PE.allowSelfSigned = false;
PE.weight = 10;
PE.secret = PE.radsecSecret = "radsec";
ServerType->servers.emplace_back(PE);
}
}
Pools.pools.emplace_back(PP);
}
} else if(Endpoint.Type=="globalreach" && !Endpoint.RadsecServers.empty()) {
auto Svrs = OpenRoaming_GlobalReach()->GetServers();
PP.radsecPoolType="globalreach";
ProvObjects::GLBLRCertificateInfo GRCertificate;
ProvObjects::GLBLRAccountInfo GRAccountInfo;
if( StorageService()->GLBLRCertsDB().GetRecord("id",Endpoint.RadsecServers[0].UseOpenRoamingAccount,GRCertificate) &&
StorageService()->GLBLRAccountInfoDB().GetRecord("id",GRCertificate.accountId,GRAccountInfo)) {
for(auto *ServerType:{&PP.authConfig, &PP.acctConfig, &PP.coaConfig}) {
ServerType->monitor = false;
ServerType->monitorMethod = "none";
ServerType->strategy = Endpoint.PoolStrategy;
ServerType->strategy = "random";
int i = 1;
for (const auto &Server: Svrs) {
GWObjects::RadiusProxyServerEntry PE;
PE.radsecCert = Utils::base64encode((const u_char *)GRCertificate.certificate.c_str(),GRCertificate.certificate.size());
PE.radsecKey = Utils::base64encode((const u_char *)GRAccountInfo.CSRPrivateKey.c_str(),GRAccountInfo.CSRPrivateKey.size());
std::vector<std::string> Chain;
ParseCertChain(GRCertificate.certificateChain,Chain);
for(const auto &cert:Chain) {
PE.radsecCacerts.emplace_back( Utils::base64encode((const u_char *)cert.c_str(),cert.size()));
}
PE.radsec = true;
PE.name = fmt::format("Server {}", i++);
PE.ignore = false;
PE.ip = Server.Hostname;
PE.port = PE.radsecPort = Server.Port;
PE.allowSelfSigned = false;
PE.weight = 10;
PE.secret = PE.radsecSecret = "radsec";
ServerType->servers.emplace_back(PE);
}
}
Pools.pools.emplace_back(PP);
}
} else if(Endpoint.Type=="radsec" && !Endpoint.RadsecServers.empty()) {
PP.radsecPoolType="radsec";
for(auto *ServerType:{&PP.authConfig, &PP.acctConfig, &PP.coaConfig}) {
ServerType->monitor = false;
ServerType->strategy = Endpoint.PoolStrategy;
ServerType->monitorMethod = "none";
ServerType->strategy = "random";
for (const auto &Server: Endpoint.RadsecServers) {
GWObjects::RadiusProxyServerEntry PE;
PE.radsecCert = Utils::base64encode((const u_char *)Server.Certificate.c_str(), Server.Certificate.size());
PE.radsecKey = Utils::base64encode((const u_char *)Server.PrivateKey.c_str(),Server.PrivateKey.size());
for(const auto &C:Server.CaCerts) {
PE.radsecCacerts.emplace_back(Utils::base64encode(
(const u_char *) C.c_str(),
C.size()));
}
PE.radsec = true;
PE.name = Server.Hostname;
PE.ignore = false;
PE.ip = Server.IP;
PE.port = PE.radsecPort = Server.Port;
PE.allowSelfSigned = false;
PE.weight = 10;
PE.secret = PE.radsecSecret = "radsec";
ServerType->servers.emplace_back(PE);
}
}
Pools.pools.emplace_back(PP);
} else if(Endpoint.Type=="generic" && !Endpoint.RadiusServers.empty()) {
PP.radsecPoolType="generic";
UpdateRadiusServerEntry(PP.authConfig, Endpoint, Endpoint.RadiusServers[0].Authentication);
UpdateRadiusServerEntry(PP.acctConfig, Endpoint, Endpoint.RadiusServers[0].Accounting);
UpdateRadiusServerEntry(PP.coaConfig, Endpoint, Endpoint.RadiusServers[0].CoA);
Pools.pools.emplace_back(PP);
}
}
/*
Poco::JSON::Object oo;
Pools.to_json(oo);
oo.stringify(std::cout,2,2);
*/
GWObjects::RadiusProxyPoolList NewPools;
Poco::JSON::Object ErrorObj;
if(SDK::GW::RADIUS::SetConfiguration(Client, Pools, NewPools, ErrorObj)) {
ProvObjects::RADIUSEndpointUpdateStatus Status;
Status.Read();
Status.lastConfigurationChange = Status.lastUpdate = Utils::Now();
return Status.Save();
}
/*
ErrorCode:
type: integer
ErrorDetails:
type: string
ErrorDescription:
type: string
*/
if(ErrorObj.has("ErrorCode") && !ErrorObj.isNull("ErrorCode"))
ErrorCode = ErrorObj.get("ErrorCode");
if(ErrorObj.has("ErrorDescription") && !ErrorObj.isNull("ErrorDescription"))
ErrorDescription = ErrorObj.get("ErrorDescription").toString();
if(ErrorObj.has("ErrorDetails") && !ErrorObj.isNull("ErrorDetails"))
ErrorDetails += ErrorObj.get("ErrorDetails").toString();
return false;
}
private:
};
} // OpenWifi

View File

@@ -39,10 +39,6 @@ namespace OpenWifi {
OpLocationDB_ = std::make_unique<OpenWifi::OpLocationDB>(dbType_, *Pool_, Logger()); OpLocationDB_ = std::make_unique<OpenWifi::OpLocationDB>(dbType_, *Pool_, Logger());
OpContactDB_ = std::make_unique<OpenWifi::OpContactDB>(dbType_, *Pool_, Logger()); OpContactDB_ = std::make_unique<OpenWifi::OpContactDB>(dbType_, *Pool_, Logger());
OverridesDB_ = std::make_unique<OpenWifi::OverridesDB>(dbType_, *Pool_, Logger()); OverridesDB_ = std::make_unique<OpenWifi::OverridesDB>(dbType_, *Pool_, Logger());
GLBLRAccountInfoDB_ = std::make_unique<OpenWifi::GLBLRAccountInfoDB>(dbType_, *Pool_, Logger());
GLBLRCertsDB_ = std::make_unique<OpenWifi::GLBLRCertsDB>(dbType_, *Pool_, Logger());
OrionAccountsDB_ = std::make_unique<OpenWifi::OrionAccountsDB>(dbType_, *Pool_, Logger());
RadiusEndpointDB_ = std::make_unique<OpenWifi::RadiusEndpointDB>(dbType_, *Pool_, Logger());
EntityDB_->Create(); EntityDB_->Create();
PolicyDB_->Create(); PolicyDB_->Create();
@@ -63,10 +59,6 @@ namespace OpenWifi {
OpLocationDB_->Create(); OpLocationDB_->Create();
OpContactDB_->Create(); OpContactDB_->Create();
OverridesDB_->Create(); OverridesDB_->Create();
GLBLRAccountInfoDB_->Create();
GLBLRCertsDB_->Create();
OrionAccountsDB_->Create();
RadiusEndpointDB_->Create();
ExistFunc_[EntityDB_->Prefix()] = [=](const char *F, std::string &V) -> bool { ExistFunc_[EntityDB_->Prefix()] = [=](const char *F, std::string &V) -> bool {
return EntityDB_->Exists(F, V); return EntityDB_->Exists(F, V);
@@ -125,20 +117,6 @@ namespace OpenWifi {
ExistFunc_[OverridesDB_->Prefix()] = [=](const char *F, std::string &V) -> bool { ExistFunc_[OverridesDB_->Prefix()] = [=](const char *F, std::string &V) -> bool {
return OverridesDB_->Exists(F, V); return OverridesDB_->Exists(F, V);
}; };
ExistFunc_[GLBLRAccountInfoDB_->Prefix()] = [=](const char *F, std::string &V) -> bool {
return GLBLRAccountInfoDB_->Exists(F, V);
};
ExistFunc_[GLBLRCertsDB_->Prefix()] = [=](const char *F, std::string &V) -> bool {
return GLBLRCertsDB_->Exists(F, V);
};
ExistFunc_[OrionAccountsDB_->Prefix()] = [=](const char *F, std::string &V) -> bool {
return OrionAccountsDB_->Exists(F, V);
};
ExistFunc_[RadiusEndpointDB_->Prefix()] = [=](const char *F, std::string &V) -> bool {
return RadiusEndpointDB_->Exists(F, V);
};
ExpandFunc_[EntityDB_->Prefix()] = [=](const char *F, std::string &V, std::string &Name, ExpandFunc_[EntityDB_->Prefix()] = [=](const char *F, std::string &V, std::string &Name,
std::string &Description) -> bool { std::string &Description) -> bool {
@@ -228,29 +206,9 @@ namespace OpenWifi {
[=]([[maybe_unused]] const char *F, [[maybe_unused]] std::string &V, [=]([[maybe_unused]] const char *F, [[maybe_unused]] std::string &V,
[[maybe_unused]] std::string &Name, [[maybe_unused]] std::string &Name,
[[maybe_unused]] std::string &Description) -> bool { return false; }; [[maybe_unused]] std::string &Description) -> bool { return false; };
ExpandFunc_[GLBLRAccountInfoDB_->Prefix()] =
[=]([[maybe_unused]] const char *F, [[maybe_unused]] std::string &V,
[[maybe_unused]] std::string &Name,
[[maybe_unused]] std::string &Description) -> bool { return false; };
ExpandFunc_[OverridesDB_->Prefix()] =
[=]([[maybe_unused]] const char *F, [[maybe_unused]] std::string &V,
[[maybe_unused]] std::string &Name,
[[maybe_unused]] std::string &Description) -> bool { return false; };
ExpandFunc_[GLBLRCertsDB_->Prefix()] =
[=]([[maybe_unused]] const char *F, [[maybe_unused]] std::string &V,
[[maybe_unused]] std::string &Name,
[[maybe_unused]] std::string &Description) -> bool { return false; };
ExpandFunc_[OrionAccountsDB_->Prefix()] =
[=]([[maybe_unused]] const char *F, [[maybe_unused]] std::string &V,
[[maybe_unused]] std::string &Name,
[[maybe_unused]] std::string &Description) -> bool { return false; };
ExpandFunc_[RadiusEndpointDB_->Prefix()] =
[=]([[maybe_unused]] const char *F, [[maybe_unused]] std::string &V,
[[maybe_unused]] std::string &Name,
[[maybe_unused]] std::string &Description) -> bool { return false; };
InventoryDB_->InitializeSerialCache(); InventoryDB_->InitializeSerialCache();
ConsistencyCheck(); ConsistencyCheck();
InitializeSystemDBs(); InitializeSystemDBs();

View File

@@ -28,10 +28,6 @@
#include "storage/storage_tags.h" #include "storage/storage_tags.h"
#include "storage/storage_variables.h" #include "storage/storage_variables.h"
#include "storage/storage_venue.h" #include "storage/storage_venue.h"
#include "storage/storage_glblraccounts.h"
#include "storage/storage_glblrcerts.h"
#include "storage/storage_orion_accounts.h"
#include "storage/storage_radius_endpoints.h"
#include "Poco/URI.h" #include "Poco/URI.h"
#include "framework/ow_constants.h" #include "framework/ow_constants.h"
@@ -51,29 +47,25 @@ namespace OpenWifi {
typedef std::list<ProvObjects::ExpandedUseEntry> ExpandedInUseList; typedef std::list<ProvObjects::ExpandedUseEntry> ExpandedInUseList;
typedef std::map<std::string, ProvObjects::ExpandedUseEntryList> ExpandedListMap; typedef std::map<std::string, ProvObjects::ExpandedUseEntryList> ExpandedListMap;
inline OpenWifi::EntityDB &EntityDB() { return *EntityDB_; }; OpenWifi::EntityDB &EntityDB() { return *EntityDB_; };
inline OpenWifi::PolicyDB &PolicyDB() { return *PolicyDB_; }; OpenWifi::PolicyDB &PolicyDB() { return *PolicyDB_; };
inline OpenWifi::VenueDB &VenueDB() { return *VenueDB_; }; OpenWifi::VenueDB &VenueDB() { return *VenueDB_; };
inline OpenWifi::LocationDB &LocationDB() { return *LocationDB_; }; OpenWifi::LocationDB &LocationDB() { return *LocationDB_; };
inline OpenWifi::ContactDB &ContactDB() { return *ContactDB_; }; OpenWifi::ContactDB &ContactDB() { return *ContactDB_; };
inline OpenWifi::InventoryDB &InventoryDB() { return *InventoryDB_; }; OpenWifi::InventoryDB &InventoryDB() { return *InventoryDB_; };
inline OpenWifi::ManagementRoleDB &RolesDB() { return *RolesDB_; }; OpenWifi::ManagementRoleDB &RolesDB() { return *RolesDB_; };
inline OpenWifi::ConfigurationDB &ConfigurationDB() { return *ConfigurationDB_; }; OpenWifi::ConfigurationDB &ConfigurationDB() { return *ConfigurationDB_; };
inline OpenWifi::TagsDictionaryDB &TagsDictionaryDB() { return *TagsDictionaryDB_; }; OpenWifi::TagsDictionaryDB &TagsDictionaryDB() { return *TagsDictionaryDB_; };
inline OpenWifi::TagsObjectDB &TagsObjectDB() { return *TagsObjectDB_; }; OpenWifi::TagsObjectDB &TagsObjectDB() { return *TagsObjectDB_; };
inline OpenWifi::MapDB &MapDB() { return *MapDB_; }; OpenWifi::MapDB &MapDB() { return *MapDB_; };
inline OpenWifi::SignupDB &SignupDB() { return *SignupDB_; }; OpenWifi::SignupDB &SignupDB() { return *SignupDB_; };
inline OpenWifi::VariablesDB &VariablesDB() { return *VariablesDB_; }; OpenWifi::VariablesDB &VariablesDB() { return *VariablesDB_; };
inline OpenWifi::OperatorDB &OperatorDB() { return *OperatorDB_; }; OpenWifi::OperatorDB &OperatorDB() { return *OperatorDB_; };
inline OpenWifi::ServiceClassDB &ServiceClassDB() { return *ServiceClassDB_; }; OpenWifi::ServiceClassDB &ServiceClassDB() { return *ServiceClassDB_; };
inline OpenWifi::SubscriberDeviceDB &SubscriberDeviceDB() { return *SubscriberDeviceDB_; }; OpenWifi::SubscriberDeviceDB &SubscriberDeviceDB() { return *SubscriberDeviceDB_; };
inline OpenWifi::OpLocationDB &OpLocationDB() { return *OpLocationDB_; }; OpenWifi::OpLocationDB &OpLocationDB() { return *OpLocationDB_; };
inline OpenWifi::OpContactDB &OpContactDB() { return *OpContactDB_; }; OpenWifi::OpContactDB &OpContactDB() { return *OpContactDB_; };
inline OpenWifi::OverridesDB &OverridesDB() { return *OverridesDB_; }; OpenWifi::OverridesDB &OverridesDB() { return *OverridesDB_; };
inline OpenWifi::GLBLRAccountInfoDB &GLBLRAccountInfoDB() { return *GLBLRAccountInfoDB_; }
inline OpenWifi::GLBLRCertsDB &GLBLRCertsDB() { return *GLBLRCertsDB_; }
inline OpenWifi::OrionAccountsDB &OrionAccountsDB() { return *OrionAccountsDB_; }
inline OpenWifi::RadiusEndpointDB &RadiusEndpointDB() { return *RadiusEndpointDB_; }
bool Validate(const Poco::URI::QueryParameters &P, RESTAPI::Errors::msg &Error); bool Validate(const Poco::URI::QueryParameters &P, RESTAPI::Errors::msg &Error);
bool Validate(const Types::StringVec &P, std::string &Error); bool Validate(const Types::StringVec &P, std::string &Error);
@@ -133,10 +125,6 @@ namespace OpenWifi {
std::unique_ptr<OpenWifi::OpLocationDB> OpLocationDB_; std::unique_ptr<OpenWifi::OpLocationDB> OpLocationDB_;
std::unique_ptr<OpenWifi::OpContactDB> OpContactDB_; std::unique_ptr<OpenWifi::OpContactDB> OpContactDB_;
std::unique_ptr<OpenWifi::OverridesDB> OverridesDB_; std::unique_ptr<OpenWifi::OverridesDB> OverridesDB_;
std::unique_ptr<OpenWifi::GLBLRAccountInfoDB> GLBLRAccountInfoDB_;
std::unique_ptr<OpenWifi::GLBLRCertsDB> GLBLRCertsDB_;
std::unique_ptr<OpenWifi::OrionAccountsDB> OrionAccountsDB_;
std::unique_ptr<OpenWifi::RadiusEndpointDB> RadiusEndpointDB_;
std::string DefaultOperator_; std::string DefaultOperator_;
typedef std::function<bool(const char *FieldName, std::string &Value)> exist_func; typedef std::function<bool(const char *FieldName, std::string &Value)> exist_func;

View File

@@ -118,9 +118,8 @@ namespace OpenWifi {
Poco::ThreadPool Pool_; Poco::ThreadPool Pool_;
std::list<VenueDeviceConfigUpdater *> JobList; std::list<VenueDeviceConfigUpdater *> JobList;
std::vector<std::string> DeviceList;
StorageService()->InventoryDB().GetDevicesUUIDForVenue(Venue.info.id, DeviceList); for (const auto &uuid : Venue.devices) {
for (const auto &uuid : DeviceList) {
auto NewTask = new VenueDeviceConfigUpdater(uuid, Venue.info.name, Logger()); auto NewTask = new VenueDeviceConfigUpdater(uuid, Venue.info.name, Logger());
bool TaskAdded = false; bool TaskAdded = false;
while (!TaskAdded) { while (!TaskAdded) {

View File

@@ -68,10 +68,8 @@ namespace OpenWifi {
Poco::ThreadPool Pool_; Poco::ThreadPool Pool_;
std::list<VenueDeviceRebooter *> JobList; std::list<VenueDeviceRebooter *> JobList;
std::vector<std::string> DeviceList;
StorageService()->InventoryDB().GetDevicesUUIDForVenue(Venue.info.id, DeviceList);
for (const auto &uuid : DeviceList) { for (const auto &uuid : Venue.devices) {
auto NewTask = new VenueDeviceRebooter(uuid, Venue.info.name, Logger()); auto NewTask = new VenueDeviceRebooter(uuid, Venue.info.name, Logger());
bool TaskAdded = false; bool TaskAdded = false;
while (!TaskAdded) { while (!TaskAdded) {

View File

@@ -28,7 +28,7 @@ namespace OpenWifi {
Storage::ApplyRules(rules_, Device.deviceRules); Storage::ApplyRules(rules_, Device.deviceRules);
if (Device.deviceRules.firmwareUpgrade == "no") { if (Device.deviceRules.firmwareUpgrade == "no") {
poco_debug(Logger(), fmt::format("Skipped Upgrade: {} : Venue rules prevent upgrading", Device.serialNumber)); poco_debug(Logger(), fmt::format("Skipped Upgrade: {}", Device.serialNumber));
skipped_++; skipped_++;
done_ = true; done_ = true;
return; return;
@@ -36,15 +36,10 @@ namespace OpenWifi {
FMSObjects::Firmware F; FMSObjects::Firmware F;
if (SDK::FMS::Firmware::GetFirmware(Device.deviceType, revision_, F)) { if (SDK::FMS::Firmware::GetFirmware(Device.deviceType, revision_, F)) {
std::string Status; if (SDK::GW::Device::Upgrade(nullptr, Device.serialNumber, 0, F.uri)) {
if (SDK::GW::Device::Upgrade(nullptr, Device.serialNumber, 0, F.uri, Status)) { Logger().debug(
if(Status=="pending") { fmt::format("{}: Upgraded to {}.", Device.serialNumber, revision_));
pending_++;
poco_debug(Logger(), fmt::format("Upgrade Pending: {} : {}", Device.serialNumber, Status));
} else {
upgraded_++; upgraded_++;
poco_debug(Logger(), fmt::format("Upgrade Success: {} : {}", Device.serialNumber, Status));
}
} else { } else {
poco_information(Logger(), fmt::format("{}: Not Upgraded to {}.", poco_information(Logger(), fmt::format("{}: Not Upgraded to {}.",
Device.serialNumber, revision_)); Device.serialNumber, revision_));
@@ -58,9 +53,10 @@ namespace OpenWifi {
} }
} }
done_ = true; done_ = true;
// std::cout << "Done push for " << Device.serialNumber << std::endl;
} }
std::uint64_t upgraded_ = 0, not_connected_ = 0, skipped_ = 0, no_firmware_ = 0, pending_ = 0; std::uint64_t upgraded_ = 0, not_connected_ = 0, skipped_ = 0, no_firmware_ = 0;
bool started_ = false, done_ = false; bool started_ = false, done_ = false;
std::string SerialNumber; std::string SerialNumber;
@@ -89,7 +85,7 @@ namespace OpenWifi {
ProvWebSocketNotifications::VenueFWUpgradeList_t N; ProvWebSocketNotifications::VenueFWUpgradeList_t N;
ProvObjects::Venue Venue; ProvObjects::Venue Venue;
uint64_t upgraded_ = 0, not_connected_ = 0, skipped_ = 0, no_firmware_ = 0, pending_=0; uint64_t upgraded_ = 0, not_connected_ = 0, skipped_ = 0, no_firmware_ = 0;
if (StorageService()->VenueDB().GetRecord("id", VenueUUID_, Venue)) { if (StorageService()->VenueDB().GetRecord("id", VenueUUID_, Venue)) {
N.content.title = fmt::format("Upgrading {} devices.", Venue.info.name); N.content.title = fmt::format("Upgrading {} devices.", Venue.info.name);
@@ -100,10 +96,8 @@ namespace OpenWifi {
ProvObjects::DeviceRules Rules; ProvObjects::DeviceRules Rules;
StorageService()->VenueDB().EvaluateDeviceRules(Venue.info.id, Rules); StorageService()->VenueDB().EvaluateDeviceRules(Venue.info.id, Rules);
std::vector<std::string> DeviceList;
StorageService()->InventoryDB().GetDevicesUUIDForVenue(Venue.info.id, DeviceList);
for (const auto &uuid : DeviceList) { for (const auto &uuid : Venue.devices) {
auto NewTask = auto NewTask =
new VenueDeviceUpgrade(uuid, Venue.info.name, Revision_, Rules, Logger()); new VenueDeviceUpgrade(uuid, Venue.info.name, Revision_, Rules, Logger());
bool TaskAdded = false; bool TaskAdded = false;
@@ -127,13 +121,10 @@ namespace OpenWifi {
N.content.not_connected.push_back(current_job->SerialNumber); N.content.not_connected.push_back(current_job->SerialNumber);
else if (current_job->no_firmware_) else if (current_job->no_firmware_)
N.content.no_firmware.push_back(current_job->SerialNumber); N.content.no_firmware.push_back(current_job->SerialNumber);
else if (current_job->pending_)
N.content.pending.push_back(current_job->SerialNumber);
upgraded_ += current_job->upgraded_; upgraded_ += current_job->upgraded_;
skipped_ += current_job->skipped_; skipped_ += current_job->skipped_;
no_firmware_ += current_job->no_firmware_; no_firmware_ += current_job->no_firmware_;
not_connected_ += current_job->not_connected_; not_connected_ += current_job->not_connected_;
pending_ += current_job->pending_;
job_it = JobList.erase(job_it); job_it = JobList.erase(job_it);
delete current_job; delete current_job;
} else { } else {
@@ -155,13 +146,10 @@ namespace OpenWifi {
N.content.not_connected.push_back(current_job->SerialNumber); N.content.not_connected.push_back(current_job->SerialNumber);
else if (current_job->no_firmware_) else if (current_job->no_firmware_)
N.content.no_firmware.push_back(current_job->SerialNumber); N.content.no_firmware.push_back(current_job->SerialNumber);
else if (current_job->pending_)
N.content.pending.push_back(current_job->SerialNumber);
upgraded_ += current_job->upgraded_; upgraded_ += current_job->upgraded_;
skipped_ += current_job->skipped_; skipped_ += current_job->skipped_;
no_firmware_ += current_job->no_firmware_; no_firmware_ += current_job->no_firmware_;
not_connected_ += current_job->not_connected_; not_connected_ += current_job->not_connected_;
pending_ += current_job->pending_;
job_it = JobList.erase(job_it); job_it = JobList.erase(job_it);
delete current_job; delete current_job;
} else { } else {
@@ -170,8 +158,8 @@ namespace OpenWifi {
} }
N.content.details = fmt::format( N.content.details = fmt::format(
"Job {} Completed: {} upgraded, {} not connected, {} skipped, {} no firmware, {} pending.", "Job {} Completed: {} upgraded, {} not connected, {} skipped, {} no firmware.",
JobId(), upgraded_, not_connected_, skipped_, no_firmware_, pending_); JobId(), upgraded_, not_connected_, skipped_, no_firmware_);
} else { } else {
N.content.details = fmt::format("Venue {} no longer exists.", VenueUUID_); N.content.details = fmt::format("Venue {} no longer exists.", VenueUUID_);
Logger().warning(N.content.details); Logger().warning(N.content.details);

View File

@@ -60,7 +60,6 @@ namespace OpenWifi::ProvWebSocketNotifications {
RESTAPI_utils::field_to_json(Obj, "success", success); RESTAPI_utils::field_to_json(Obj, "success", success);
RESTAPI_utils::field_to_json(Obj, "notConnected", not_connected); RESTAPI_utils::field_to_json(Obj, "notConnected", not_connected);
RESTAPI_utils::field_to_json(Obj, "noFirmware", no_firmware); RESTAPI_utils::field_to_json(Obj, "noFirmware", no_firmware);
RESTAPI_utils::field_to_json(Obj, "pending", pending);
RESTAPI_utils::field_to_json(Obj, "skipped", skipped); RESTAPI_utils::field_to_json(Obj, "skipped", skipped);
RESTAPI_utils::field_to_json(Obj, "timeStamp", timeStamp); RESTAPI_utils::field_to_json(Obj, "timeStamp", timeStamp);
RESTAPI_utils::field_to_json(Obj, "details", details); RESTAPI_utils::field_to_json(Obj, "details", details);
@@ -72,7 +71,6 @@ namespace OpenWifi::ProvWebSocketNotifications {
RESTAPI_utils::field_from_json(Obj, "jobId", jobId); RESTAPI_utils::field_from_json(Obj, "jobId", jobId);
RESTAPI_utils::field_from_json(Obj, "success", success); RESTAPI_utils::field_from_json(Obj, "success", success);
RESTAPI_utils::field_from_json(Obj, "notConnected", not_connected); RESTAPI_utils::field_from_json(Obj, "notConnected", not_connected);
RESTAPI_utils::field_from_json(Obj, "pending", pending);
RESTAPI_utils::field_from_json(Obj, "noFirmware", no_firmware); RESTAPI_utils::field_from_json(Obj, "noFirmware", no_firmware);
RESTAPI_utils::field_from_json(Obj, "skipped", skipped); RESTAPI_utils::field_from_json(Obj, "skipped", skipped);
RESTAPI_utils::field_from_json(Obj, "timeStamp", timeStamp); RESTAPI_utils::field_from_json(Obj, "timeStamp", timeStamp);

View File

@@ -32,7 +32,7 @@ namespace OpenWifi::ProvWebSocketNotifications {
struct FWUpgradeList { struct FWUpgradeList {
std::string title, details, jobId; std::string title, details, jobId;
std::vector<std::string> success, skipped, no_firmware, not_connected, pending; std::vector<std::string> success, skipped, no_firmware, not_connected;
uint64_t timeStamp = OpenWifi::Utils::Now(); uint64_t timeStamp = OpenWifi::Utils::Now();
void to_json(Poco::JSON::Object &Obj) const; void to_json(Poco::JSON::Object &Obj) const;

View File

@@ -4,19 +4,17 @@
#include "ALBserver.h" #include "ALBserver.h"
#include "fmt/format.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "framework/MicroServiceFuncs.h"
#include "fmt/format.h"
namespace OpenWifi { namespace OpenWifi {
void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request, void ALBRequestHandler::handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) {
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 {}.", Logger_.debug(fmt::format("ALB-REQUEST({}): ALB Request {}.", Request.clientAddress().toString(), id_));
Request.clientAddress().toString(), id_));
} }
Response.setChunkedTransferEncoding(true); Response.setChunkedTransferEncoding(true);
Response.setContentType("text/html"); Response.setContentType("text/html");
@@ -26,23 +24,27 @@ namespace OpenWifi {
Response.set("Connection", "keep-alive"); Response.set("Connection", "keep-alive");
Response.setVersion(Poco::Net::HTTPMessage::HTTP_1_1); Response.setVersion(Poco::Net::HTTPMessage::HTTP_1_1);
std::ostream &Answer = Response.send(); std::ostream &Answer = Response.send();
Answer << ALBHealthCheckServer()->CallbackText(); Answer << "process Alive and kicking!";
} catch (...) { } catch (...) {
} }
} }
ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger &L) : Logger_(L) {} ALBRequestHandlerFactory::ALBRequestHandlerFactory(Poco::Logger & L):
Logger_(L) {
}
ALBRequestHandler * ALBRequestHandler* ALBRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest& request) {
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)) {
@@ -58,8 +60,7 @@ 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>( Server_ = std::make_unique<Poco::Net::HTTPServer>(new ALBRequestHandlerFactory(Logger()), *Socket_, Params);
new ALBRequestHandlerFactory(Logger()), *Socket_, Params);
Server_->start(); Server_->start();
} }

View File

@@ -7,38 +7,37 @@
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServer.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) : Logger_(L), id_(id) {} explicit ALBRequestHandler(Poco::Logger & L, uint64_t id)
: Logger_(L), id_(id) {
}
void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest &Request, void handleRequest([[maybe_unused]] Poco::Net::HTTPServerRequest& Request, Poco::Net::HTTPServerResponse& Response) override;
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 * ALBRequestHandler* createRequestHandler(const Poco::Net::HTTPServerRequest& request) override;
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;
}; };
typedef std::string ALBHealthMessageCallback();
class ALBHealthCheckServer : public SubSystemServer { class ALBHealthCheckServer : public SubSystemServer {
public: public:
ALBHealthCheckServer(); ALBHealthCheckServer();
@@ -50,22 +49,10 @@ namespace OpenWifi {
int Start() override; int Start() override;
void Stop() override; void Stop() override;
inline void RegisterExtendedHealthMessage(ALBHealthMessageCallback *F) {
Callback_=F;
};
inline std::string CallbackText() {
if(Callback_== nullptr) {
return "process Alive and kicking!";
} else {
return Callback_();
}
}
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_;
ALBHealthMessageCallback *Callback_= nullptr;
int Port_ = 0; int Port_ = 0;
mutable std::atomic_bool Running_=false; mutable std::atomic_bool Running_=false;
}; };
@@ -73,3 +60,4 @@ namespace OpenWifi {
inline auto ALBHealthCheckServer() { return ALBHealthCheckServer::instance(); } inline auto ALBHealthCheckServer() { return ALBHealthCheckServer::instance(); }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,19 +4,22 @@
#pragma once #pragma once
#include "Poco/JSON/Parser.h"
#include "Poco/Logger.h" #include "Poco/Logger.h"
#include "Poco/Net/HTTPSClientSession.h" #include "Poco/JSON/Parser.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, Poco::Net::HTTPServerRequest *Request, inline void API_Proxy( Poco::Logger &Logger,
Poco::Net::HTTPServerResponse *Response, const char *ServiceType, Poco::Net::HTTPServerRequest *Request,
const char *PathRewrite, uint64_t msTimeout_ = 10000) { Poco::Net::HTTPServerResponse *Response,
const char * ServiceType,
const char * PathRewrite,
uint64_t msTimeout_ = 10000 ) {
try { try {
auto Services = MicroServiceGetServices(ServiceType); auto Services = MicroServiceGetServices(ServiceType);
for(auto const &Svc:Services) { for(auto const &Svc:Services) {
@@ -28,8 +31,7 @@ namespace OpenWifi {
// std::cout << " Source: " << SourceURI.toString() << std::endl; // std::cout << " Source: " << SourceURI.toString() << std::endl;
// std::cout << "Destination: " << DestinationURI.toString() << std::endl; // std::cout << "Destination: " << DestinationURI.toString() << std::endl;
Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(), Poco::Net::HTTPSClientSession Session(DestinationURI.getHost(), DestinationURI.getPort());
DestinationURI.getPort());
Session.setKeepAlive(true); Session.setKeepAlive(true);
Session.setTimeout(Poco::Timespan(msTimeout_/1000, msTimeout_ % 1000)); Session.setTimeout(Poco::Timespan(msTimeout_/1000, msTimeout_ % 1000));
Poco::Net::HTTPRequest ProxyRequest(Request->getMethod(), Poco::Net::HTTPRequest ProxyRequest(Request->getMethod(),
@@ -74,8 +76,7 @@ namespace OpenWifi {
try { try {
std::istream &ProxyResponseStream = Session.receiveResponse(ProxyResponse); std::istream &ProxyResponseStream = Session.receiveResponse(ProxyResponse);
Poco::JSON::Parser P2; Poco::JSON::Parser P2;
auto ProxyResponseBody = auto ProxyResponseBody = P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>();
P2.parse(ProxyResponseStream).extract<Poco::JSON::Object::Ptr>();
Poco::JSON::Stringifier::condense(ProxyResponseBody,SSR); Poco::JSON::Stringifier::condense(ProxyResponseBody,SSR);
Response->setContentType("application/json"); Response->setContentType("application/json");
Response->setContentLength(SSR.str().size()); Response->setContentLength(SSR.str().size());
@@ -83,6 +84,7 @@ namespace OpenWifi {
Response->sendBuffer(SSR.str().c_str(),SSR.str().size()); Response->sendBuffer(SSR.str().c_str(),SSR.str().size());
return; return;
} catch( const Poco::Exception & E) { } catch( const Poco::Exception & E) {
} }
Response->setStatus(ProxyResponse.getStatus()); Response->setStatus(ProxyResponse.getStatus());
Response->send(); Response->send();
@@ -94,4 +96,4 @@ namespace OpenWifi {
Logger.log(E); Logger.log(E);
} }
} }
} // namespace OpenWifi }

View File

@@ -4,22 +4,21 @@
#pragma once #pragma once
#include <string>
#include <fstream> #include <fstream>
#include <iomanip> #include <iomanip>
#include <iostream> #include <iostream>
#include <string>
#include "Poco/File.h"
#include "Poco/StreamCopier.h" #include "Poco/StreamCopier.h"
#include "Poco/JSON/Object.h" #include "Poco/File.h"
#include "Poco/JSON/Parser.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
// #include "nlohmann/json.hpp" #include "nlohmann/json.hpp"
namespace OpenWifi { namespace OpenWifi {
class AppServiceRegistry { class AppServiceRegistry {
public: public:
AppServiceRegistry() { AppServiceRegistry() {
@@ -30,11 +29,11 @@ namespace OpenWifi {
if(F.exists()) { if(F.exists()) {
std::ostringstream OS; std::ostringstream OS;
std::ifstream IF(FileName); std::ifstream IF(FileName);
Poco::JSON::Parser P; Poco::StreamCopier::copyStream(IF, OS);
Registry_ = P.parse(IF).extract<Poco::JSON::Object::Ptr>(); Registry_ = nlohmann::json::parse(OS.str());
} }
} catch (...) { } catch (...) {
Registry_ = Poco::makeShared<Poco::JSON::Object>(); Registry_ = nlohmann::json::parse("{}");
} }
} }
@@ -43,42 +42,51 @@ namespace OpenWifi {
return *instance_; return *instance_;
} }
inline ~AppServiceRegistry() { Save(); } inline ~AppServiceRegistry() {
Save();
}
inline void Save() { inline void Save() {
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);
Registry_->stringify(OF); Poco::StreamCopier::copyStream(IS, OF);
} }
void Set(const char *key, const std::vector<std::string> &V) { inline void Set(const char *Key, uint64_t Value ) {
Poco::JSON::Array Arr; Registry_[Key] = Value;
for(const auto &s:V) {
Arr.add(s);
}
Registry_->set(key,Arr);
Save(); Save();
} }
template<class T> void Set(const char *key, const T &Value) { inline void Set(const char *Key, const std::string &Value ) {
Registry_->set(key,Value); Registry_[Key] = Value;
Save(); Save();
} }
bool Get(const char *key, std::vector<std::string> &Value) { inline void Set(const char *Key, bool Value ) {
if(Registry_->has(key) && !Registry_->isNull(key) && Registry_->isArray(key)) { Registry_[Key] = Value;
auto Arr = Registry_->get(key); Save();
for(const auto &v:Arr) {
Value.emplace_back(v);
} }
inline bool Get(const char *Key, bool & Value ) {
if(Registry_[Key].is_boolean()) {
Value = Registry_[Key].get<bool>();
return true; return true;
} }
return false; return false;
} }
template<class T> bool Get(const char *key, T &Value) { inline bool Get(const char *Key, uint64_t & Value ) {
if(Registry_->has(key) && !Registry_->isNull(key)) { if(Registry_[Key].is_number_unsigned()) {
Value = Registry_->getValue<T>(key); Value = Registry_[Key].get<uint64_t>();
return true;
}
return false;
}
inline bool Get(const char *Key, std::string & Value ) {
if(Registry_[Key].is_string()) {
Value = Registry_[Key].get<std::string>();
return true; return true;
} }
return false; return false;
@@ -86,9 +94,9 @@ namespace OpenWifi {
private: private:
std::string FileName; std::string FileName;
Poco::JSON::Object::Ptr Registry_; nlohmann::json Registry_;
}; };
inline auto AppServiceRegistry() { return AppServiceRegistry::instance(); } inline auto AppServiceRegistry() { return AppServiceRegistry::instance(); }
} // namespace OpenWifi }

View File

@@ -4,27 +4,28 @@
#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, bool &Expired, bool &Contacted, std::uint64_t TID,
bool Sub) { bool & Expired, bool & Contacted, 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( std::string AlternateURIForLogging = fmt::format("{}?token={}", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", Utils::SanitizeToken(SessionToken));
"{}?token={}", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken",
Utils::SanitizeToken(SessionToken));
OpenAPIRequestGet Req( uSERVICE_SECURITY, OpenAPIRequestGet Req( uSERVICE_SECURITY,
Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken", Sub ? "/api/v1/validateSubToken" : "/api/v1/validateToken",
QueryData, 10000, AlternateURIForLogging); QueryData,
10000,
AlternateURIForLogging
);
Poco::JSON::Object::Ptr Response; Poco::JSON::Object::Ptr Response;
auto StatusCode = Req.Do(Response); auto StatusCode = Req.Do(Response);
@@ -49,15 +50,14 @@ namespace OpenWifi {
} }
} }
} catch (...) { } catch (...) {
poco_error(Logger(), fmt::format("Failed to retrieve token={} for TID={}", poco_error(Logger(),fmt::format("Failed to retrieve token={} for TID={}", Utils::SanitizeToken(SessionToken), TID));
Utils::SanitizeToken(SessionToken), TID));
} }
Expired = false; Expired = false;
return false; return false;
} }
bool AuthClient::IsAuthorized(const std::string &SessionToken, bool AuthClient::IsAuthorized(const std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo,
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID, 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()) {
@@ -75,14 +75,16 @@ namespace OpenWifi {
bool AuthClient::RetrieveApiKeyInformation(const std::string & SessionToken, bool AuthClient::RetrieveApiKeyInformation(const std::string & SessionToken,
SecurityObjects::UserInfoAndPolicy & UInfo, SecurityObjects::UserInfoAndPolicy & UInfo,
std::uint64_t TID, bool &Expired, bool &Contacted, std::uint64_t TID,
[[maybe_unused]] bool &Suspended) { bool & Expired, bool & Contacted, [[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 = std::string AlternateURIForLogging = fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken));
fmt::format("/api/v1/validateApiKey?apiKey={}", Utils::SanitizeToken(SessionToken)); OpenAPIRequestGet Req( uSERVICE_SECURITY,
OpenAPIRequestGet Req(uSERVICE_SECURITY, "/api/v1/validateApiKey", QueryData, 10000, "/api/v1/validateApiKey" ,
QueryData,
10000,
AlternateURIForLogging); AlternateURIForLogging);
Poco::JSON::Object::Ptr Response; Poco::JSON::Object::Ptr Response;
@@ -94,29 +96,24 @@ namespace OpenWifi {
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") && Response->has("expiresOn")) {
Response->has("expiresOn")) {
UInfo.from_json(Response); UInfo.from_json(Response);
Expired = false; Expired = false;
ApiKeyCache_.update(SessionToken, ApiKeyCache_.update(SessionToken, ApiKeyCacheEntry{ .UserInfo = UInfo, .ExpiresOn = Response->get("expiresOn")});
ApiKeyCacheEntry{.UserInfo = UInfo,
.ExpiresOn = Response->get("expiresOn")});
return true; return true;
} else { } else {
return false; return false;
} }
} }
} catch (...) { } catch (...) {
poco_error(Logger(), fmt::format("Failed to retrieve api key={} for TID={}", poco_error(Logger(),fmt::format("Failed to retrieve api key={} for TID={}", Utils::SanitizeToken(SessionToken), TID));
Utils::SanitizeToken(SessionToken), TID));
} }
Expired = false; Expired = false;
return false; return false;
} }
bool AuthClient::IsValidApiKey(const std::string &SessionToken, bool AuthClient::IsValidApiKey(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) {
auto User = ApiKeyCache_.get(SessionToken); auto User = ApiKeyCache_.get(SessionToken);
if (!User.isNull()) { if (!User.isNull()) {
if(User->ExpiresOn < Utils::Now()) { if(User->ExpiresOn < Utils::Now()) {

View File

@@ -4,9 +4,9 @@
#pragma once #pragma once
#include "Poco/ExpireLRUCache.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include "Poco/ExpireLRUCache.h"
#include "framework/utils.h" #include "framework/utils.h"
namespace OpenWifi { namespace OpenWifi {
@@ -14,8 +14,10 @@ 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;
@@ -27,7 +29,9 @@ namespace OpenWifi {
std::uint64_t ExpiresOn; std::uint64_t ExpiresOn;
}; };
inline int Start() override { return 0; } inline int Start() override {
return 0;
}
inline void Stop() override { inline void Stop() override {
poco_information(Logger(),"Stopping..."); poco_information(Logger(),"Stopping...");
@@ -46,27 +50,30 @@ namespace OpenWifi {
} }
bool RetrieveTokenInformation(const std::string & SessionToken, bool RetrieveTokenInformation(const std::string & SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo, 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 RetrieveApiKeyInformation(const std::string & SessionToken, bool RetrieveApiKeyInformation(const std::string & SessionToken,
SecurityObjects::UserInfoAndPolicy &UInfo, std::uint64_t TID, SecurityObjects::UserInfoAndPolicy & UInfo,
std::uint64_t TID,
bool & Expired, bool & Contacted, bool & Suspended); bool & Expired, bool & Contacted, bool & Suspended);
bool IsAuthorized(const std::string &SessionToken, bool IsAuthorized(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 IsValidApiKey(const std::string &SessionToken, bool IsValidApiKey(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) ;
private: private:
Poco::ExpireLRUCache<std::string, OpenWifi::SecurityObjects::UserInfoAndPolicy> Cache_{
512, 1200000}; Poco::ExpireLRUCache<std::string,OpenWifi::SecurityObjects::UserInfoAndPolicy> Cache_{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

@@ -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 }

File diff suppressed because it is too large Load Diff

View File

@@ -7,16 +7,17 @@
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include <valijson/adapters/poco_json_adapter.hpp> #include <valijson/adapters/poco_json_adapter.hpp>
#include <valijson/constraints/constraint.hpp> #include <valijson/utils/poco_json_utils.hpp>
#include <valijson/constraints/constraint_visitor.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>
#include <valijson/constraints/constraint_visitor.hpp>
namespace OpenWifi { namespace OpenWifi {
class ConfigurationValidator : public SubSystemServer { class ConfigurationValidator : public SubSystemServer {
public: public:
static auto instance() { static auto instance() {
static auto instance_ = new ConfigurationValidator; static auto instance_ = new ConfigurationValidator;
return instance_; return instance_;
@@ -37,13 +38,12 @@ namespace OpenWifi {
Poco::JSON::Object::Ptr SchemaDocPtr_; Poco::JSON::Object::Ptr SchemaDocPtr_;
bool SetSchema(const std::string &SchemaStr); bool SetSchema(const std::string &SchemaStr);
ConfigurationValidator() ConfigurationValidator():
: SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") {} SubSystemServer("ConfigValidator", "CFG-VALIDATOR", "config.validator") {
}
}; };
inline auto ConfigurationValidator() { return ConfigurationValidator::instance(); } inline auto ConfigurationValidator() { return ConfigurationValidator::instance(); }
inline bool ValidateUCentralConfiguration(const std::string &C, std::vector<std::string> &Error, inline bool ValidateUCentralConfiguration(const std::string &C, std::vector<std::string> &Error, bool strict) { return ConfigurationValidator::instance()->Validate(C, Error, strict); }
bool strict) {
return ConfigurationValidator::instance()->Validate(C, Error, strict);
} }
} // namespace OpenWifi

View File

@@ -4,9 +4,9 @@
#pragma once #pragma once
#include <vector>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector>
namespace OpenWifi { namespace OpenWifi {
@@ -264,6 +264,8 @@ namespace OpenWifi {
{ .code= "EH", .name= "Western Sahara" }, { .code= "EH", .name= "Western Sahara" },
{ .code= "YE", .name= "Yemen" }, { .code= "YE", .name= "Yemen" },
{ .code= "ZM", .name= "Zambia" }, { .code= "ZM", .name= "Zambia" },
{.code = "ZW", .name = "Zimbabwe"}}; { .code= "ZW", .name= "Zimbabwe" }
};
}
} // namespace OpenWifi

View File

@@ -4,28 +4,29 @@
#include "framework/EventBusManager.h" #include "framework/EventBusManager.h"
#include "framework/KafkaManager.h" #include "framework/KafkaManager.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "framework/MicroServiceFuncs.h"
namespace OpenWifi { namespace OpenWifi {
EventBusManager::EventBusManager(Poco::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, KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false);
false);
while(Running_) { 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(), KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false);
Msg, false);
} }
Msg = (MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE)); Msg = MicroServiceMakeSystemEventMessage(KafkaTopics::ServiceEvents::EVENT_LEAVE);
KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS, MicroServicePrivateEndPoint(), Msg, KafkaManager()->PostMessage(KafkaTopics::SERVICE_EVENTS,MicroServicePrivateEndPoint(),Msg, false);
false);
}; };
void EventBusManager::Start() { void EventBusManager::Start() {

View File

@@ -4,24 +4,14 @@
#pragma once #pragma once
#include "Poco/Logger.h"
#include "Poco/Runnable.h" #include "Poco/Runnable.h"
#include "Poco/Logger.h"
#include "Poco/Thread.h" #include "Poco/Thread.h"
namespace OpenWifi { namespace OpenWifi {
class EventBusManager : public Poco::Runnable { class EventBusManager : public Poco::Runnable {
public: public:
EventBusManager() :
Logger_(Poco::Logger::create(
"EventBusManager", Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel())) {
}
static auto instance() {
static auto instance_ = new EventBusManager;
return instance_;
}
explicit EventBusManager(Poco::Logger &L); explicit EventBusManager(Poco::Logger &L);
void run() final; void run() final;
void Start(); void Start();
@@ -34,6 +24,5 @@ namespace OpenWifi {
Poco::Logger &Logger_; Poco::Logger &Logger_;
}; };
inline auto EventBusManager() { return EventBusManager::instance(); }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,55 +4,50 @@
#include "KafkaManager.h" #include "KafkaManager.h"
#include "fmt/format.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
#include "cppkafka/utils/consumer_dispatcher.h" #include "fmt/format.h"
namespace OpenWifi { namespace OpenWifi {
void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int level, void KafkaLoggerFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int level, const std::string & facility, const std::string &message) {
const std::string &facility, const std::string &message) {
switch ((cppkafka::LogLevel) level) { switch ((cppkafka::LogLevel) level) {
case cppkafka::LogLevel::LogNotice: { case cppkafka::LogLevel::LogNotice: {
poco_notice(KafkaManager()->Logger(), poco_notice(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
fmt::format("kafka-log: facility: {} message: {}", facility, message)); }
} break; break;
case cppkafka::LogLevel::LogDebug: { case cppkafka::LogLevel::LogDebug: {
poco_debug(KafkaManager()->Logger(), poco_debug(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
fmt::format("kafka-log: facility: {} message: {}", facility, message)); }
} break; break;
case cppkafka::LogLevel::LogInfo: { case cppkafka::LogLevel::LogInfo: {
poco_information(KafkaManager()->Logger(), poco_information(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
fmt::format("kafka-log: facility: {} message: {}", facility, message)); }
} break; break;
case cppkafka::LogLevel::LogWarning: { case cppkafka::LogLevel::LogWarning: {
poco_warning(KafkaManager()->Logger(), poco_warning(KafkaManager()->Logger(), fmt::format("kafka-log: facility: {} message: {}",facility, message));
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(), poco_critical(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
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(), poco_error(KafkaManager()->Logger(),fmt::format("kafka-log: facility: {} message: {}",facility, message));
fmt::format("kafka-log: facility: {} message: {}", facility, message)); }
} break; break;
} }
} }
inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase &handle, int error, inline void KafkaErrorFun([[maybe_unused]] cppkafka::KafkaHandleBase & handle, int error, const std::string &reason) {
const std::string &reason) { poco_error(KafkaManager()->Logger(),fmt::format("kafka-error: {}, reason: {}", error, 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 = auto Certificate = MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location","");
MicroServiceConfigGetString("openwifi.kafka.ssl.certificate.location", "");
auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location",""); auto Key = MicroServiceConfigGetString("openwifi.kafka.ssl.key.location","");
auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password",""); auto Password = MicroServiceConfigGetString("openwifi.kafka.ssl.key.password","");
@@ -66,29 +61,29 @@ namespace OpenWifi {
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 &Logger_ = Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel());
Poco::Logger::create("KAFKA-PRODUCER", KafkaManager()->Logger().getChannel());
poco_information(Logger_,"Starting..."); 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", { "metadata.broker.list", MicroServiceConfigGetString("openwifi.kafka.brokerlist", "") }
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_ = KafkaManager()->SystemInfoWrapper_ = R"lit({ "system" : { "id" : )lit" +
R"lit({ "system" : { "id" : )lit" + std::to_string(MicroServiceID()) + std::to_string(MicroServiceID()) +
R"lit( , "host" : ")lit" + MicroServicePrivateEndPoint() + R"lit( , "host" : ")lit" + MicroServicePrivateEndPoint() +
R"lit(" } , "payload" : )lit" ; R"lit(" } , "payload" : )lit" ;
@@ -100,16 +95,11 @@ namespace OpenWifi {
try { try {
auto Msg = dynamic_cast<KafkaMessage *>(Note.get()); auto Msg = dynamic_cast<KafkaMessage *>(Note.get());
if (Msg != nullptr) { if (Msg != nullptr) {
auto NewMessage = cppkafka::MessageBuilder(Msg->Topic()); Producer.produce(
NewMessage.key(Msg->Key()); cppkafka::MessageBuilder(Msg->Topic()).key(Msg->Key()).payload(Msg->Payload()));
NewMessage.partition(0);
NewMessage.payload(Msg->Payload());
Producer.produce(NewMessage);
Producer.flush();
} }
} catch (const cppkafka::HandleException &E) { } catch (const cppkafka::HandleException &E) {
poco_warning(Logger_, poco_warning(Logger_,fmt::format("Caught a Kafka exception (producer): {}", E.what()));
fmt::format("Caught a Kafka exception (producer): {}", E.what()));
} catch( const Poco::Exception &E) { } catch( const Poco::Exception &E) {
Logger_.log(E); Logger_.log(E);
} catch (...) { } catch (...) {
@@ -123,25 +113,27 @@ namespace OpenWifi {
inline void KafkaConsumer::run() { inline void KafkaConsumer::run() {
Utils::SetThreadName("Kafka:Cons"); Utils::SetThreadName("Kafka:Cons");
Poco::Logger &Logger_ = Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-CONSUMER", KafkaManager()->Logger().getChannel());
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 = {{"auto.offset.reset", "smallest"}}; cppkafka::TopicConfiguration topic_config = {
{ "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);
@@ -160,49 +152,40 @@ namespace OpenWifi {
} }
}); });
// bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit", false); bool AutoCommit = MicroServiceConfigGetBool("openwifi.kafka.auto.commit",false);
// auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize", 100); auto BatchSize = MicroServiceConfigGetInt("openwifi.kafka.consumer.batchsize",20);
Types::StringVec Topics; Types::StringVec Topics;
std::for_each(Topics_.begin(),Topics_.end(), KafkaManager()->Topics(Topics);
[&](const std::string & T) { Topics.emplace_back(T); });
Consumer.subscribe(Topics); Consumer.subscribe(Topics);
Running_ = true; Running_ = true;
std::vector<cppkafka::Message> MsgVec; while(Running_) {
Dispatcher_ = std::make_unique<cppkafka::ConsumerDispatcher>(Consumer);
Dispatcher_->run(
// Callback executed whenever a new message is consumed
[&](cppkafka::Message msg) {
// Print the key (if any)
std::lock_guard G(ConsumerMutex_);
auto It = Notifiers_.find(msg.get_topic());
if (It != Notifiers_.end()) {
const auto &FL = It->second;
for (const auto &[CallbackFunc, _] : FL) {
try { try {
CallbackFunc(msg.get_key(), msg.get_payload()); std::vector<cppkafka::Message> MsgVec = Consumer.poll_batch(BatchSize, std::chrono::milliseconds(100));
for(auto const &Msg:MsgVec) {
if (!Msg)
continue;
if (Msg.get_error()) {
if (!Msg.is_eof()) {
poco_error(Logger_,fmt::format("Error: {}", Msg.get_error().to_string()));
}
if(!AutoCommit)
Consumer.async_commit(Msg);
continue;
}
KafkaManager()->Dispatch(Msg.get_topic(), Msg.get_key(),Msg.get_payload() );
if (!AutoCommit)
Consumer.async_commit(Msg);
}
} catch (const cppkafka::HandleException &E) {
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);
} catch (...) { } catch (...) {
poco_error(Logger_,"std::exception");
} }
} }
}
Consumer.commit(msg);
},
// Whenever there's an error (other than the EOF soft error)
[&Logger_](cppkafka::Error error) {
poco_warning(Logger_,fmt::format("Error: {}", error.to_string()));
},
// Whenever EOF is reached on a partition, print this
[&Logger_](cppkafka::ConsumerDispatcher::EndOfFile, const cppkafka::TopicPartition& topic_partition) {
poco_debug(Logger_,fmt::format("Partition {} EOF", topic_partition.get_partition()));
}
);
Consumer.unsubscribe(); Consumer.unsubscribe();
poco_information(Logger_,"Stopped..."); poco_information(Logger_,"Stopped...");
} }
@@ -222,14 +205,14 @@ namespace OpenWifi {
} }
} }
void KafkaProducer::Produce(const char *Topic, const std::string &Key, void KafkaProducer::Produce(const std::string &Topic, const std::string &Key, const std::string &Payload) {
const std::string &Payload) {
std::lock_guard G(Mutex_); std::lock_guard G(Mutex_);
Queue_.enqueueNotification( new KafkaMessage(Topic,Key,Payload)); Queue_.enqueueNotification( new KafkaMessage(Topic,Key,Payload));
} }
void KafkaConsumer::Start() { void KafkaConsumer::Start() {
if(!Running_) { if(!Running_) {
Running_=true;
Worker_.start(*this); Worker_.start(*this);
} }
} }
@@ -237,16 +220,28 @@ namespace OpenWifi {
void KafkaConsumer::Stop() { void KafkaConsumer::Stop() {
if(Running_) { if(Running_) {
Running_=false; Running_=false;
if(Dispatcher_) { Worker_.wakeUp();
Dispatcher_->stop();
}
Worker_.join(); Worker_.join();
} }
} }
std::uint64_t KafkaConsumer::RegisterTopicWatcher(const std::string &Topic, void KafkaDispatcher::Start() {
Types::TopicNotifyFunction &F) { if(!Running_) {
std::lock_guard G(ConsumerMutex_); Running_=true;
Worker_.start(*this);
}
}
void KafkaDispatcher::Stop() {
if(Running_) {
Running_=false;
Queue_.wakeUpAll();
Worker_.join();
}
}
auto KafkaDispatcher::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) {
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;
@@ -255,12 +250,11 @@ namespace OpenWifi {
} else { } else {
It->second.emplace(It->second.end(),std::make_pair(F,FunctionId_)); It->second.emplace(It->second.end(),std::make_pair(F,FunctionId_));
} }
Topics_.insert(Topic);
return FunctionId_++; return FunctionId_++;
} }
void KafkaConsumer::UnregisterTopicWatcher(const std::string &Topic, int Id) { void KafkaDispatcher::UnregisterTopicWatcher(const std::string &Topic, int Id) {
std::lock_guard G(ConsumerMutex_); 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;
@@ -272,17 +266,55 @@ namespace OpenWifi {
} }
} }
void KafkaDispatcher::Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload) {
std::lock_guard G(Mutex_);
auto It = Notifiers_.find(Topic);
if(It!=Notifiers_.end()) {
Queue_.enqueueNotification(new KafkaMessage(Topic, Key, Payload));
}
}
void KafkaDispatcher::run() {
Poco::Logger &Logger_ = Poco::Logger::create("KAFKA-DISPATCHER", KafkaManager()->Logger().getChannel());
poco_information(Logger_,"Starting...");
Poco::AutoPtr<Poco::Notification> Note(Queue_.waitDequeueNotification());
Utils::SetThreadName("kafka:dispatch");
while(Note && Running_) {
auto Msg = dynamic_cast<KafkaMessage*>(Note.get());
if(Msg!= nullptr) {
auto It = Notifiers_.find(Msg->Topic());
if (It != Notifiers_.end()) {
const auto & FL = It->second;
for(const auto &[CallbackFunc,_]:FL) {
CallbackFunc(Msg->Key(), Msg->Payload());
}
}
}
Note = Queue_.waitDequeueNotification();
}
poco_information(Logger_,"Stopped...");
}
void KafkaDispatcher::Topics(std::vector<std::string> &T) {
T.clear();
for(const auto &[TopicName,_]:Notifiers_)
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();
return 0; return 0;
} }
void KafkaManager::Stop() { void KafkaManager::Stop() {
if(KafkaEnabled_) { if(KafkaEnabled_) {
poco_information(Logger(),"Stopping..."); poco_information(Logger(),"Stopping...");
Dispatcher_.Stop();
ProducerThr_.Stop(); ProducerThr_.Stop();
ConsumerThr_.Stop(); ConsumerThr_.Stop();
poco_information(Logger(),"Stopped..."); poco_information(Logger(),"Stopped...");
@@ -290,35 +322,44 @@ namespace OpenWifi {
} }
} }
void KafkaManager::PostMessage(const char *topic, const std::string &key, void KafkaManager::PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage ) {
const std::string & PayLoad, bool WrapMessage) {
if(KafkaEnabled_) { if(KafkaEnabled_) {
ProducerThr_.Produce(topic,key,WrapMessage ? WrapSystemId(PayLoad) : PayLoad); ProducerThr_.Produce(topic,key,WrapMessage ? WrapSystemId(PayLoad) : PayLoad);
} }
} }
void KafkaManager::PostMessage(const char *topic, const std::string &key, void KafkaManager::Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload) {
const Poco::JSON::Object &Object, bool WrapMessage) { Dispatcher_.Dispatch(Topic, Key, Payload);
if (KafkaEnabled_) {
std::ostringstream ObjectStr;
Object.stringify(ObjectStr);
ProducerThr_.Produce(topic, key, WrapMessage ? WrapSystemId(ObjectStr.str()) : ObjectStr.str());
}
} }
[[nodiscard]] std::string KafkaManager::WrapSystemId(const std::string & PayLoad) { [[nodiscard]] std::string KafkaManager::WrapSystemId(const std::string & PayLoad) {
return fmt::format( R"lit({{ "system" : {{ "id" : {}, "host" : "{}" }}, "payload" : {} }})lit", return SystemInfoWrapper_ + PayLoad + "}";
MicroServiceID(), MicroServicePrivateEndPoint(), PayLoad ) ; }
uint64_t KafkaManager::RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) {
if(KafkaEnabled_) {
return Dispatcher_.RegisterTopicWatcher(Topic,F);
} else {
return 0;
}
}
void KafkaManager::UnregisterTopicWatcher(const std::string &Topic, uint64_t Id) {
if(KafkaEnabled_) {
Dispatcher_.UnregisterTopicWatcher(Topic, Id);
}
}
void KafkaManager::Topics(std::vector<std::string> &T) {
Dispatcher_.Topics(T);
} }
void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList& partitions) { void KafkaManager::PartitionAssignment(const cppkafka::TopicPartitionList& partitions) {
poco_information( poco_information(Logger(),fmt::format("Partition assigned: {}...", partitions.front().get_partition()));
Logger(), fmt::format("Partition assigned: {}...", partitions.front().get_partition()));
} }
void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList& partitions) { void KafkaManager::PartitionRevocation(const cppkafka::TopicPartitionList& partitions) {
poco_information(Logger(), fmt::format("Partition revocation: {}...", poco_information(Logger(),fmt::format("Partition revocation: {}...",partitions.front().get_partition()));
partitions.front().get_partition()));
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -6,11 +6,11 @@
#include "Poco/Notification.h" #include "Poco/Notification.h"
#include "Poco/NotificationQueue.h" #include "Poco/NotificationQueue.h"
#include "Poco/JSON/Object.h"
#include "framework/KafkaTopics.h"
#include "framework/OpenWifiTypes.h"
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "framework/OpenWifiTypes.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "framework/KafkaTopics.h"
#include "cppkafka/cppkafka.h" #include "cppkafka/cppkafka.h"
@@ -18,15 +18,16 @@ namespace OpenWifi {
class KafkaMessage: public Poco::Notification { class KafkaMessage: public Poco::Notification {
public: public:
KafkaMessage(const char * 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 char * 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:
const char *Topic_; std::string Topic_;
std::string Key_; std::string Key_;
std::string Payload_; std::string Payload_;
}; };
@@ -36,10 +37,10 @@ namespace OpenWifi {
void run () override; void run () override;
void Start(); void Start();
void Stop(); void Stop();
void Produce(const char *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::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_;
@@ -47,26 +48,38 @@ namespace OpenWifi {
class KafkaConsumer : public Poco::Runnable { class KafkaConsumer : public Poco::Runnable {
public: public:
void run() override;
void Start(); void Start();
void Stop(); void Stop();
private: private:
std::mutex ConsumerMutex_; std::recursive_mutex Mutex_;
Poco::Thread Worker_;
mutable std::atomic_bool Running_=false;
};
class KafkaDispatcher : public Poco::Runnable {
public:
void Start();
void Stop();
auto RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F);
void UnregisterTopicWatcher(const std::string &Topic, int Id);
void Dispatch(const std::string &Topic, const std::string &Key, const std::string &Payload);
void run() override;
void Topics(std::vector<std::string> &T);
private:
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;
std::unique_ptr<cppkafka::ConsumerDispatcher> Dispatcher_; Poco::NotificationQueue Queue_;
std::set<std::string> Topics_;
void run() override;
friend class KafkaManager;
std::uint64_t RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F);
void UnregisterTopicWatcher(const std::string &Topic, int Id);
}; };
class KafkaManager : public SubSystemServer { class KafkaManager : public SubSystemServer {
public: public:
friend class KafkaConsumer; friend class KafkaConsumer;
friend class KafkaProducer; friend class KafkaProducer;
@@ -80,32 +93,30 @@ namespace OpenWifi {
int Start() override; int Start() override;
void Stop() override; void Stop() override;
void PostMessage(const char *topic, const std::string &key, void PostMessage(const std::string &topic, const std::string & key, const std::string &PayLoad, bool WrapMessage = true );
const std::string &PayLoad, bool WrapMessage = true); void Dispatch(const std::string &Topic, const std::string & Key, const std::string &Payload);
void PostMessage(const char *topic, const std::string &key,
const Poco::JSON::Object &Object, bool WrapMessage = true);
[[nodiscard]] std::string WrapSystemId(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_; }
inline std::uint64_t RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F) { uint64_t RegisterTopicWatcher(const std::string &Topic, Types::TopicNotifyFunction &F);
return ConsumerThr_.RegisterTopicWatcher(Topic,F); void UnregisterTopicWatcher(const std::string &Topic, uint64_t Id);
} void Topics(std::vector<std::string> &T);
inline void UnregisterTopicWatcher(const std::string &Topic, uint64_t Id) {
return ConsumerThr_.UnregisterTopicWatcher(Topic,Id);
}
private: private:
bool KafkaEnabled_ = false; bool KafkaEnabled_ = false;
std::string SystemInfoWrapper_; std::string SystemInfoWrapper_;
KafkaProducer ProducerThr_; KafkaProducer ProducerThr_;
KafkaConsumer ConsumerThr_; KafkaConsumer ConsumerThr_;
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 : SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") {} KafkaManager() noexcept:
SubSystemServer("KafkaManager", "KAFKA-SVR", "openwifi.kafka") {
}
}; };
inline auto KafkaManager() { return KafkaManager::instance(); } inline auto KafkaManager() { return KafkaManager::instance(); }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -10,33 +10,33 @@
#include <string> #include <string>
namespace OpenWifi::KafkaTopics { namespace OpenWifi::KafkaTopics {
inline const char * HEALTHCHECK = "healthcheck"; static const std::string HEALTHCHECK{"healthcheck"};
inline const char * STATE = "state"; static const std::string STATE{"state"};
inline const char * CONNECTION = "connection"; static const std::string CONNECTION{"connection"};
inline const char * WIFISCAN = "wifiscan"; static const std::string WIFISCAN{"wifiscan"};
inline const char * ALERTS = "alerts"; static const std::string ALERTS{"alerts"};
inline const char * COMMAND = "command"; static const std::string COMMAND{"command"};
inline const char * SERVICE_EVENTS = "service_events"; static const std::string SERVICE_EVENTS{"service_events"};
inline const char * DEVICE_EVENT_QUEUE = "device_event_queue"; static const std::string DEVICE_EVENT_QUEUE{"device_event_queue"};
inline const char * DEVICE_TELEMETRY = "device_telemetry"; static const std::string DEVICE_TELEMETRY{"device_telemetry"};
inline const char * PROVISIONING_CHANGE = "provisioning_change"; static const std::string PROVISIONING_CHANGE{"provisioning_change"};
inline const char * RRM = "rrm";
namespace ServiceEvents { namespace ServiceEvents {
inline const char * EVENT_JOIN = "join"; static const std::string EVENT_JOIN{"join"};
inline const char * EVENT_LEAVE = "leave"; static const std::string EVENT_LEAVE{"leave"};
inline const char * EVENT_KEEP_ALIVE = "keep-alive"; static const std::string EVENT_KEEP_ALIVE{"keep-alive"};
inline const char * EVENT_REMOVE_TOKEN = "remove-token"; static const std::string EVENT_REMOVE_TOKEN{"remove-token"};
namespace Fields { namespace Fields {
inline const char * EVENT = "event"; static const std::string EVENT{"event"};
inline const char * ID = "id"; static const std::string ID{"id"};
inline const char * TYPE = "type"; static const std::string TYPE{"type"};
inline const char * PUBLIC = "publicEndPoint"; static const std::string PUBLIC{"publicEndPoint"};
inline const char * PRIVATE = "privateEndPoint"; static const std::string PRIVATE{"privateEndPoint"};
inline const char * KEY = "key"; static const std::string KEY{"key"};
inline const char * VRSN = "version"; static const std::string VRSN{"version"};
inline const char * TOKEN = "token"; static const std::string TOKEN{"token"};
} // namespace Fields }
} // namespace ServiceEvents }
} // namespace OpenWifi::KafkaTopics }

View File

@@ -2,54 +2,41 @@
// Created by stephane bourque on 2022-10-26. // Created by stephane bourque on 2022-10-26.
// //
#include "Poco/AsyncChannel.h"
#include "Poco/ConsoleChannel.h"
#include "Poco/FileChannel.h" #include "Poco/FileChannel.h"
#include "Poco/ConsoleChannel.h"
#include "Poco/PatternFormatter.h"
#include "Poco/FormattingChannel.h" #include "Poco/FormattingChannel.h"
#include "Poco/JSON/JSONException.h" #include "Poco/AsyncChannel.h"
#include "Poco/NullChannel.h"
#include "Poco/SplitterChannel.h"
#include "Poco/Net/HTTPStreamFactory.h"
#include "Poco/Net/HTTPSStreamFactory.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/NullChannel.h" #include "Poco/JSON/JSONException.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/MicroServiceNames.h"
#include "framework/RESTAPI_ExtServer.h"
#include "framework/RESTAPI_GenericServerAccounting.h"
#include "framework/RESTAPI_IntServer.h"
#include "framework/UI_WebSocketClientServer.h" #include "framework/UI_WebSocketClientServer.h"
#include "framework/WebSocketLogger.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_IntServer.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "framework/WebSocketLogger.h"
namespace OpenWifi { namespace OpenWifi {
void MicroService::Exit(int Reason) { std::exit(Reason); } void MicroService::Exit(int Reason) {
std::exit(Reason);
static std::string MakeServiceListString(const Types::MicroServiceMetaMap &Services) {
std::string SvcList;
for (const auto &Svc : Services) {
if (SvcList.empty())
SvcList = Svc.second.Type;
else
SvcList += ", " + Svc.second.Type;
}
return SvcList;
} }
void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key, void MicroService::BusMessageReceived([[maybe_unused]] const std::string &Key, const std::string & Payload) {
const std::string &Payload) {
std::lock_guard G(InfraMutex_); std::lock_guard G(InfraMutex_);
Poco::Logger &BusLogger = EventBusManager()->Logger();
try { try {
Poco::JSON::Parser P; Poco::JSON::Parser P;
auto Object = P.parse(Payload).extract<Poco::JSON::Object::Ptr>(); auto Object = P.parse(Payload).extract<Poco::JSON::Object::Ptr>();
@@ -67,53 +54,23 @@ namespace OpenWifi {
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 = auto PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString();
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(); if (Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE && Services_.find(PrivateEndPoint) != Services_.end()) {
if (Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) { Services_[PrivateEndPoint].LastUpdate = Utils::Now();
} else if (Event == KafkaTopics::ServiceEvents::EVENT_LEAVE) {
Services_.erase(PrivateEndPoint); Services_.erase(PrivateEndPoint);
poco_information( poco_debug(logger(),fmt::format("Service {} ID={} leaving system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID));
BusLogger, } else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN || Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) {
fmt::format( poco_debug(logger(),fmt::format("Service {} ID={} joining system.",Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),ID));
"Service {} ID={} leaving system.", Services_[PrivateEndPoint] = Types::MicroServiceMeta{
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
} else if (Event == KafkaTopics::ServiceEvents::EVENT_JOIN ||
Event == KafkaTopics::ServiceEvents::EVENT_KEEP_ALIVE) {
auto ServiceInfo = Types::MicroServiceMeta{
.Id = ID, .Id = ID,
.Type = Poco::toLower( .Type = Poco::toLower(Object->get(KafkaTopics::ServiceEvents::Fields::TYPE).toString()),
Object->get(KafkaTopics::ServiceEvents::Fields::TYPE) .PrivateEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE).toString(),
.toString()), .PublicEndPoint = Object->get(KafkaTopics::ServiceEvents::Fields::PUBLIC).toString(),
.PrivateEndPoint = .AccessKey = Object->get(KafkaTopics::ServiceEvents::Fields::KEY).toString(),
Object->get(KafkaTopics::ServiceEvents::Fields::PRIVATE) .Version = Object->get(KafkaTopics::ServiceEvents::Fields::VRSN).toString(),
.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() }; .LastUpdate = Utils::Now() };
auto s1 = MakeServiceListString(Services_);
auto PreviousSize = Services_.size();
Services_[PrivateEndPoint] = ServiceInfo;
auto CurrentSize = Services_.size();
if(Event == KafkaTopics::ServiceEvents::EVENT_JOIN) {
if(!s1.empty()) {
poco_information(
BusLogger,
fmt::format(
"Service {} ID={} is joining the system.",
Object
->get(
KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
}
std::string SvcList; std::string SvcList;
for (const auto &Svc: Services_) { for (const auto &Svc: Services_) {
if(SvcList.empty()) if(SvcList.empty())
@@ -121,66 +78,38 @@ namespace OpenWifi {
else else
SvcList += ", " + Svc.second.Type; SvcList += ", " + Svc.second.Type;
} }
poco_information( poco_information(logger(),fmt::format("Current list of microservices: {}", SvcList));
BusLogger,
fmt::format("Current list of microservices: {}", SvcList));
} else if(CurrentSize!=PreviousSize) {
poco_information(
BusLogger,
fmt::format(
"Service {} ID={} is being added back in.",
Object
->get(KafkaTopics::ServiceEvents::Fields::PRIVATE)
.toString(),
ID));
}
} }
} else { } else {
poco_information( poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing a field.",Event));
BusLogger,
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( AuthClient()->RemovedCachedToken(Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString());
Object->get(KafkaTopics::ServiceEvents::Fields::TOKEN).toString());
#endif #endif
} else { } else {
poco_information( poco_error(logger(),fmt::format("KAFKA-MSG: invalid event '{}', missing token",Event));
BusLogger,
fmt::format("KAFKA-MSG: invalid event '{}', missing token", Event));
} }
} else { } else {
poco_information(BusLogger, poco_error(logger(),fmt::format("Unknown Event: {} Source: {}", Event, ID));
fmt::format("Unknown Event: {} Source: {}", Event, ID));
} }
} }
} else { } else {
std::ostringstream os; poco_error(logger(),"Bad bus message.");
Object->stringify(std::cout);
poco_error(BusLogger, fmt::format("Bad bus message: {}", os.str()));
} }
auto ServiceHint = Services_.begin(); auto i=Services_.begin();
auto now = Utils::Now(); auto now = Utils::Now();
auto si1 = Services_.size(); for(;i!=Services_.end();) {
auto ss1 = MakeServiceListString(Services_); if((now - i->second.LastUpdate)>60) {
while(ServiceHint!=Services_.end()) { i = Services_.erase(i);
if ((now - ServiceHint->second.LastUpdate) > 120) {
poco_information(BusLogger, fmt::format("ZombieService: Removing service {}, ", ServiceHint->second.PublicEndPoint));
ServiceHint = Services_.erase(ServiceHint);
} else } else
++ServiceHint; ++i;
}
if(Services_.size() != si1) {
auto ss2 = MakeServiceListString(Services_);
poco_information(BusLogger, fmt::format("Current list of microservices: {} -> {}", ss1, ss2));
} }
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
BusLogger.log(E); logger().log(E);
} }
} }
@@ -208,16 +137,14 @@ namespace OpenWifi {
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_ = ConfigFileName_.empty() ? Location + "/" + DAEMON_PROPERTIES_FILENAME : 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() {
<< " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR + std::cerr << DAEMON_APP_NAME << ": Configuration "
" env variable the path of the " + DAEMON_PROPERTIES_FILENAME + << ConfigFile.toString() << " does not seem to exist. Please set " + DAEMON_CONFIG_ENV_VAR
" file." + " env variable the path of the " + DAEMON_PROPERTIES_FILENAME + " file." << std::endl;
<< std::endl;
std::exit(Poco::Util::Application::EXIT_CONFIG); std::exit(Poco::Util::Application::EXIT_CONFIG);
} }
@@ -236,8 +163,7 @@ namespace OpenWifi {
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>( AppKey_ = Poco::SharedPtr<Poco::Crypto::RSAKey>(new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword));
new Poco::Crypto::RSAKey("", KeyFile, KeyFilePassword));
Cipher_ = CipherFactory_.createCipher(*AppKey_); Cipher_ = CipherFactory_.createCipher(*AppKey_);
Signer_.setRSAKey(AppKey_); Signer_.setRSAKey(AppKey_);
Signer_.addAllAlgorithms(); Signer_.addAllAlgorithms();
@@ -262,13 +188,11 @@ namespace OpenWifi {
initialized = true; initialized = true;
LoadConfigurationFile(); LoadConfigurationFile();
auto LoggingDestination = auto LoggingDestination = MicroService::instance().ConfigGetString("logging.type", "file");
MicroService::instance().ConfigGetString("logging.type", "file"); auto LoggingFormat = MicroService::instance().ConfigGetString("logging.format",
auto LoggingFormat = MicroService::instance().ConfigGetString( "%Y-%m-%d %H:%M:%S.%i %s: [%p][thr:%I] %t");
"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 = auto DisableWebSocketLogging = MicroService::instance().ConfigGetBool("logging.websocket",false);
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);
@@ -282,12 +206,10 @@ namespace OpenWifi {
} else if (LoggingDestination == "syslog") { } else if (LoggingDestination == "syslog") {
SetSyslogLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat); SetSyslogLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat);
} else { } else {
SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat, SetFileLogs(UseAsyncLogs_, DisableWebSocketLogging, LoggingFormat, DAEMON_ROOT_ENV_VAR);
DAEMON_ROOT_ENV_VAR);
} }
auto Level = Poco::Logger::parseLevel( auto Level = Poco::Logger::parseLevel(MicroService::instance().ConfigGetString("logging.level", "debug"));
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 = {
@@ -297,14 +219,12 @@ namespace OpenWifi {
} }
} }
void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, void MicroService::SetConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) {
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( Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console));
new Poco::FormattingChannel(Formatter, Console));
if(DisableWebSocketLogging) { if(DisableWebSocketLogging) {
if(UseAsync) { if(UseAsync) {
@@ -325,18 +245,15 @@ namespace OpenWifi {
Poco::Logger::root().setChannel(Splitter); Poco::Logger::root().setChannel(Splitter);
} }
} }
Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}", Poco::Logger::root().information(fmt::format("Enabled console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
UseAsync, DisableWebSocketLogging));
} }
void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, void MicroService::SetColorConsoleLogs(bool UseAsync, bool DisableWebSocketLogging, const std::string & FormatterPattern) {
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( Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, Console));
new Poco::FormattingChannel(Formatter, Console));
if(DisableWebSocketLogging) { if(DisableWebSocketLogging) {
if(UseAsync) { if(UseAsync) {
@@ -357,28 +274,20 @@ namespace OpenWifi {
Poco::Logger::root().setChannel(Splitter); Poco::Logger::root().setChannel(Splitter);
} }
} }
Poco::Logger::root().information( Poco::Logger::root().information(fmt::format("Enabled color console logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
fmt::format("Enabled color console logs: asynch={} websocket={}", UseAsync,
DisableWebSocketLogging));
} }
void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync, void MicroService::SetSQLLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]] bool DisableWebSocketLogging,[[maybe_unused]] const std::string & FormatterPattern) {
[[maybe_unused]] bool DisableWebSocketLogging, //"CREATE TABLE T_POCO_LOG (Source VARCHAR, Name VARCHAR, ProcessId INTEGER, Thread VARCHAR, ThreadId INTEGER, Priority INTEGER, Text VARCHAR, DateTime DATE)"
[[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, void MicroService::SetSyslogLogs([[maybe_unused]] bool UseAsync,[[maybe_unused]] bool DisableWebSocketLogging,[[maybe_unused]] const std::string & FormatterPattern) {
[[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) { 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); std::string DefaultLogPath = fmt::format("${}/logs",root_env_var);
auto LoggingLocationDir = auto LoggingLocationDir = MicroService::instance().ConfigPath("logging.path", DefaultLogPath);
MicroService::instance().ConfigPath("logging.path", DefaultLogPath);
Poco::File LD(LoggingLocationDir); Poco::File LD(LoggingLocationDir);
try { try {
if(!LD.exists()) { if(!LD.exists()) {
@@ -397,8 +306,7 @@ namespace OpenWifi {
Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter); Poco::AutoPtr<Poco::PatternFormatter> Formatter(new Poco::PatternFormatter);
Formatter->setProperty("pattern", FormatterPattern); Formatter->setProperty("pattern", FormatterPattern);
Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel( Poco::AutoPtr<Poco::FormattingChannel> FormattingChannel(new Poco::FormattingChannel(Formatter, FileChannel));
new Poco::FormattingChannel(Formatter, FileChannel));
if(DisableWebSocketLogging) { if(DisableWebSocketLogging) {
if(UseAsync) { if(UseAsync) {
@@ -419,8 +327,7 @@ namespace OpenWifi {
Poco::Logger::root().setChannel(Splitter); Poco::Logger::root().setChannel(Splitter);
} }
} }
Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}", Poco::Logger::root().information(fmt::format("Enabled file logs: asynch={} websocket={}",UseAsync,DisableWebSocketLogging));
UseAsync, DisableWebSocketLogging));
} }
void DaemonPostInitialization(Poco::Util::Application &self); void DaemonPostInitialization(Poco::Util::Application &self);
@@ -449,7 +356,7 @@ namespace OpenWifi {
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","");
@@ -464,9 +371,7 @@ namespace OpenWifi {
ServerApplication::initialize(self); ServerApplication::initialize(self);
DaemonPostInitialization(self); DaemonPostInitialization(self);
Types::TopicNotifyFunction F = [this](const std::string &Key, const std::string &Payload) { Types::TopicNotifyFunction F = [this](const std::string &Key,const std::string &Payload) { this->BusMessageReceived(Key, Payload); };
this->BusMessageReceived(Key, Payload);
};
KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F); KafkaManager()->RegisterTopicWatcher(KafkaTopics::SERVICE_EVENTS, F);
} }
@@ -487,64 +392,58 @@ 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( .callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp)));
Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleHelp)));
options.addOption(Poco::Util::Option("file", "", "specify the configuration file") options.addOption(
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(Poco::Util::Option("debug", "", "to run in debug, set to true") options.addOption(
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( .callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs)));
Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleLogs)));
options.addOption(Poco::Util::Option("version", "", "get the version and quit.") options.addOption(
Poco::Util::Option("version", "", "get the version and quit.")
.required(false) .required(false)
.repeatable(false) .repeatable(false)
.callback(Poco::Util::OptionCallback<MicroService>( .callback(Poco::Util::OptionCallback<MicroService>(this, &MicroService::handleVersion)));
this, &MicroService::handleVersion)));
} }
void MicroService::handleHelp([[maybe_unused]] const std::string &name, void MicroService::handleHelp([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) {
[[maybe_unused]] const std::string &value) {
HelpRequested_ = true; HelpRequested_ = true;
displayHelp(); displayHelp();
stopOptionsProcessing(); stopOptionsProcessing();
} }
void MicroService::handleVersion([[maybe_unused]] const std::string &name, void MicroService::handleVersion([[maybe_unused]] const std::string &name, [[maybe_unused]] const std::string &value) {
[[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, void MicroService::handleDebug([[maybe_unused]] const std::string &name, const std::string &value) {
const std::string &value) {
if(value == "true") if(value == "true")
DebugMode_ = true ; DebugMode_ = true ;
} }
void MicroService::handleLogs([[maybe_unused]] const std::string &name, void MicroService::handleLogs([[maybe_unused]] const std::string &name, const std::string &value) {
const std::string &value) {
LogDir_ = value; LogDir_ = value;
} }
void MicroService::handleConfig([[maybe_unused]] const std::string &name, void MicroService::handleConfig([[maybe_unused]] const std::string &name, const std::string &value) {
const std::string &value) {
ConfigFileName_ = value; ConfigFileName_ = value;
} }
@@ -567,12 +466,13 @@ namespace OpenWifi {
for(auto i:SubSystems_) { for(auto i:SubSystems_) {
i->Start(); i->Start();
} }
EventBusManager()->Start(); EventBusManager_ = std::make_unique<EventBusManager>(Poco::Logger::create("EventBusManager",Poco::Logger::root().getChannel(),Poco::Logger::root().getLevel()));
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();
} }
@@ -610,8 +510,7 @@ namespace OpenWifi {
return ss.str(); return ss.str();
} }
bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem, bool MicroService::SetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level) {
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);
@@ -662,8 +561,7 @@ namespace OpenWifi {
} }
const Types::StringVec & MicroService::GetLogLevelNames() { const Types::StringVec & MicroService::GetLogLevelNames() {
static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning", static Types::StringVec LevelNames{"none", "fatal", "critical", "error", "warning", "notice", "information", "debug", "trace" };
"notice", "information", "debug", "trace"};
return LevelNames; return LevelNames;
} }
@@ -671,13 +569,17 @@ namespace OpenWifi {
return (uint64_t) config().getInt64(Key,Default); return (uint64_t) config().getInt64(Key,Default);
} }
uint64_t MicroService::ConfigGetInt(const std::string &Key) { return config().getInt(Key); } uint64_t MicroService::ConfigGetInt(const std::string &Key) {
return config().getInt(Key);
}
uint64_t MicroService::ConfigGetBool(const std::string &Key,bool Default) { uint64_t MicroService::ConfigGetBool(const std::string &Key,bool Default) {
return config().getBool(Key,Default); return config().getBool(Key,Default);
} }
uint64_t MicroService::ConfigGetBool(const std::string &Key) { return config().getBool(Key); } uint64_t MicroService::ConfigGetBool(const std::string &Key) {
return config().getBool(Key);
}
std::string MicroService::ConfigGetString(const std::string &Key,const std::string & Default) { std::string MicroService::ConfigGetString(const std::string &Key,const std::string & Default) {
return config().getString(Key, Default); return config().getString(Key, Default);
@@ -701,16 +603,14 @@ namespace OpenWifi {
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 {
@@ -732,7 +632,7 @@ namespace OpenWifi {
auto APIKEY = Request.get("X-API-KEY"); auto APIKEY = Request.get("X-API-KEY");
return APIKEY == MyHash_; return APIKEY == MyHash_;
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
Logger_.log(E); logger().log(E);
} }
return false; return false;
} }
@@ -740,11 +640,11 @@ namespace OpenWifi {
void MicroService::SavePID() { void MicroService::SavePID() {
try { try {
std::ofstream O; std::ofstream O;
O.open(MicroService::instance().DataDir() + "/pidfile", O.open(MicroService::instance().DataDir() + "/pidfile",std::ios::binary | std::ios::trunc);
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;
} }
} }
@@ -787,6 +687,7 @@ namespace OpenWifi {
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 (...) {
} }
} }
} }
@@ -806,7 +707,8 @@ namespace OpenWifi {
if(F.exists()) if(F.exists())
F.remove(); F.remove();
} catch (...) { } catch (...) {
} }
} }
} // namespace OpenWifi }

View File

@@ -9,11 +9,12 @@
#pragma once #pragma once
#include <array> #include <array>
#include <ctime>
#include <fstream>
#include <iostream> #include <iostream>
#include <random>
#include <vector> #include <vector>
#include <fstream>
#include <random>
#include <ctime>
// 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,37 +24,37 @@
namespace OpenWifi { namespace OpenWifi {
inline uint64_t Now() { return std::time(nullptr); }; inline uint64_t Now() { return std::time(nullptr); };
} // namespace OpenWifi }
#include "Poco/AutoPtr.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/Process.h"
#include "Poco/Util/Application.h" #include "Poco/Util/Application.h"
#include "Poco/Util/HelpFormatter.h" #include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h" #include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h" #include "Poco/Util/OptionSet.h"
#include "Poco/Crypto/RSAKey.h"
#include "Poco/Crypto/CipherFactory.h"
#include "Poco/Crypto/Cipher.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Process.h"
#include "Poco/Util/HelpFormatter.h"
#include "Poco/JSON/Object.h"
#include "Poco/AutoPtr.h"
#include "Poco/Util/PropertyFileConfiguration.h" #include "Poco/Util/PropertyFileConfiguration.h"
#include "Poco/Util/ServerApplication.h" #include "Poco/JWT/Signer.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__));
@@ -62,12 +63,19 @@ namespace OpenWifi {
class MicroService : public Poco::Util::ServerApplication { class MicroService : public Poco::Util::ServerApplication {
public: public:
explicit MicroService(std::string PropFile, std::string RootEnv, std::string ConfigVar, explicit MicroService( std::string PropFile,
std::string AppName, uint64_t BusTimer, SubSystemVec Subsystems) std::string RootEnv,
: DAEMON_PROPERTIES_FILENAME(std::move(PropFile)), std::string ConfigVar,
DAEMON_ROOT_ENV_VAR(std::move(RootEnv)), DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)), std::string AppName,
DAEMON_APP_NAME(std::move(AppName)), DAEMON_BUS_TIMER(BusTimer), uint64_t BusTimer,
SubSystems_(std::move(Subsystems)), Logger_(Poco::Logger::get("FRAMEWORK")) { SubSystemVec Subsystems) :
DAEMON_PROPERTIES_FILENAME(std::move(PropFile)),
DAEMON_ROOT_ENV_VAR(std::move(RootEnv)),
DAEMON_CONFIG_ENV_VAR(std::move(ConfigVar)),
DAEMON_APP_NAME(std::move(AppName)),
DAEMON_BUS_TIMER(BusTimer),
SubSystems_(std::move(Subsystems)),
Logger_(Poco::Logger::get("FRAMEWORK")) {
instance_ = this; instance_ = this;
RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count()); RandomEngine_.seed(std::chrono::steady_clock::now().time_since_epoch().count());
// Logger_ = Poco::Logger::root().get("BASE-SVC"); // Logger_ = Poco::Logger::root().get("BASE-SVC");
@@ -92,13 +100,9 @@ namespace OpenWifi {
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() { [[nodiscard]] inline const std::string GetPublicAPIEndPoint() { return MyPublicEndPoint_ + "/api/v1"; };
return MyPublicEndPoint_ + "/api/v1";
};
[[nodiscard]] inline const std::string & GetUIURI() const { return UIURI_;}; [[nodiscard]] inline const std::string & GetUIURI() const { return UIURI_;};
[[nodiscard]] inline uint64_t Random(uint64_t ceiling) { [[nodiscard]] inline uint64_t Random(uint64_t ceiling) { return (RandomEngine_() % ceiling); }
return (RandomEngine_() % ceiling);
}
[[nodiscard]] inline uint64_t Random(uint64_t min, uint64_t max) { [[nodiscard]] inline uint64_t Random(uint64_t min, uint64_t max) {
return ((RandomEngine_() % (max-min)) + min); return ((RandomEngine_() % (max-min)) + min);
} }
@@ -154,17 +158,11 @@ namespace OpenWifi {
[[nodiscard]] std::string Sign(Poco::JWT::Token &T, const std::string &Algo); [[nodiscard]] std::string Sign(Poco::JWT::Token &T, const std::string &Algo);
void AddActivity(const std::string &Activity); void AddActivity(const std::string &Activity);
static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket, static void SetConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
const std::string &FormatterPattern); static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
static void SetColorConsoleLogs(bool UseAsync, bool AllowWebSocket, static void SetSQLLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
const std::string &FormatterPattern); static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern);
static void SetSQLLogs(bool UseAsync, bool AllowWebSocket, static void SetFileLogs(bool UseAsync, bool AllowWebSocket, const std::string & FormatterPattern, const std::string & root_env_var);
const std::string &FormatterPattern);
static void SetSyslogLogs(bool UseAsync, bool AllowWebSocket,
const std::string &FormatterPattern);
static void SetFileLogs(bool UseAsync, bool AllowWebSocket,
const std::string &FormatterPattern,
const std::string &root_env_var);
inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; } inline bool AllowExternalMicroServices() const { return AllowExternalMicroServices_; }
private: private:
@@ -184,8 +182,7 @@ namespace OpenWifi {
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 + ")" + " - " + std::string Version_{ OW_VERSION::VERSION + "("+ OW_VERSION::BUILD + ")" + " - " + OW_VERSION::HASH };
OW_VERSION::HASH};
std::recursive_mutex InfraMutex_; std::recursive_mutex InfraMutex_;
std::default_random_engine RandomEngine_; std::default_random_engine RandomEngine_;
Poco::Util::PropertyFileConfiguration * PropConfigurationFile_ = nullptr; Poco::Util::PropertyFileConfiguration * PropConfigurationFile_ = nullptr;
@@ -201,8 +198,9 @@ namespace OpenWifi {
Poco::JWT::Signer Signer_; Poco::JWT::Signer Signer_;
Poco::Logger &Logger_; Poco::Logger &Logger_;
Poco::ThreadPool TimerPool_{"timer:pool",2,32}; Poco::ThreadPool TimerPool_{"timer:pool",2,32};
std::unique_ptr<EventBusManager> EventBusManager_;
}; };
inline MicroService * MicroService::instance_ = nullptr; inline MicroService * MicroService::instance_ = nullptr;
} // namespace OpenWifi }

View File

@@ -4,20 +4,21 @@
#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 {
@@ -33,134 +34,146 @@ namespace OpenWifi {
Base.rethrow(); Base.rethrow();
} catch (const Poco::Net::InvalidCertificateException &E) { } catch (const Poco::Net::InvalidCertificateException &E) {
poco_error(App_.logger(), poco_error(App_.logger(), fmt::format("Poco::Net::InvalidCertificateException thr_name={} thr_id={} code={} text={} msg={} what={}",
fmt::format("Poco::Net::InvalidCertificateException 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::InvalidSocketException &E) { } catch (const Poco::Net::InvalidSocketException &E) {
poco_error(App_.logger(), poco_error(App_.logger(), fmt::format("Poco::Net::InvalidSocketException thr_name={} thr_id={} code={} text={} msg={} what={}",
fmt::format("Poco::Net::InvalidSocketException 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::Net::WebSocketException &E) { } catch (const Poco::Net::WebSocketException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::Net::WebSocketException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::Net::ConnectionResetException &E) { } catch (const Poco::Net::ConnectionResetException &E) {
poco_error(App_.logger(), poco_error(App_.logger(), fmt::format("Poco::Net::ConnectionResetException thr_name={} thr_id={} code={} text={} msg={} what={}",
fmt::format("Poco::Net::ConnectionResetException 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::Net::CertificateValidationException &E) { } catch (const Poco::Net::CertificateValidationException &E) {
poco_error(App_.logger(), poco_error(App_.logger(), fmt::format("Poco::Net::CertificateValidationException thr_name={} thr_id={} code={} text={} msg={} what={}",
fmt::format("Poco::Net::CertificateValidationException 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::SSLConnectionUnexpectedlyClosedException &E) { } catch (const Poco::Net::SSLConnectionUnexpectedlyClosedException &E) {
poco_error(App_.logger(), poco_error(App_.logger(), fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException thr_name={} thr_id={} code={} text={} msg={} what={}",
fmt::format("Poco::Net::SSLConnectionUnexpectedlyClosedException " t_name, t_id, E.code(),
"thr_name={} 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::SSLContextException &E) { } catch (const Poco::Net::SSLContextException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::Net::SSLContextException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
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={} " poco_error(App_.logger(), fmt::format("Poco::Net::SSLException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::Net::InvalidAddressException &E) { } catch (const Poco::Net::InvalidAddressException &E) {
poco_error(App_.logger(), poco_error(App_.logger(), fmt::format("Poco::Net::InvalidAddressException thr_name={} thr_id={} code={} text={} msg={} what={}",
fmt::format("Poco::Net::InvalidAddressException 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::Net::NetException &E) { } catch (const Poco::Net::NetException &E) {
poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::Net::NetException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::IOException &E) { } catch (const Poco::IOException &E) {
poco_error( poco_error(App_.logger(), fmt::format("Poco::IOException thr_name={} thr_id={} code={} text={} msg={} what={}",
App_.logger(), t_name, t_id, E.code(),
fmt::format( E.displayText(),
"Poco::IOException 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::TimeoutException &E) { } catch (const Poco::TimeoutException &E) {
poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::TimeoutException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::NoThreadAvailableException &E) { } catch (const Poco::NoThreadAvailableException &E) {
poco_error(App_.logger(), poco_error(App_.logger(), fmt::format("Poco::NoThreadAvailableException thr_name={} thr_id={} code={} text={} msg={} what={}",
fmt::format("Poco::NoThreadAvailableException 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::OutOfMemoryException &E) { } catch (const Poco::OutOfMemoryException &E) {
poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::OutOfMemoryException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::BadCastException &E) { } catch (const Poco::BadCastException &E) {
poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::BadCastException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::DataException &E) { } catch (const Poco::DataException &E) {
poco_error( poco_error(App_.logger(), fmt::format("Poco::DataException thr_name={} thr_id={} code={} text={} msg={} what={}",
App_.logger(), t_name, t_id, E.code(),
fmt::format( E.displayText(),
"Poco::DataException 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::PoolOverflowException &E) { } catch (const Poco::PoolOverflowException &E) {
poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::PoolOverflowException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::SystemException &E) { } catch (const Poco::SystemException &E) {
poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} " poco_error(App_.logger(), fmt::format("Poco::SystemException thr_name={} thr_id={} code={} text={} msg={} what={}",
"code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::RuntimeException &E) { } catch (const Poco::RuntimeException &E) {
poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::RuntimeException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::JSON::JSONTemplateException &E) { } catch (const Poco::JSON::JSONTemplateException &E) {
poco_error(App_.logger(), poco_error(App_.logger(), fmt::format("Poco::JSON::JSONTemplateException thr_name={} thr_id={} code={} text={} msg={} what={}",
fmt::format("Poco::JSON::JSONTemplateException 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::JSON::JSONException &E) { } catch (const Poco::JSON::JSONException &E) {
poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::JSON::JSONException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::ApplicationException &E) { } catch (const Poco::ApplicationException &E) {
poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} " poco_error(App_.logger(), fmt::format("Poco::ApplicationException thr_name={} thr_id={} code={} text={} msg={} what={}",
"thr_id={} code={} text={} msg={} what={}", t_name, t_id, E.code(),
t_name, t_id, E.code(), E.displayText(), E.displayText(),
E.message(), E.what())); E.message(),
E.what()));
} catch (const Poco::Exception &E) { } catch (const Poco::Exception &E) {
poco_error( poco_error(App_.logger(), fmt::format("Poco::Exception thr_name={} thr_id={} code={} text={} msg={} what={}",
App_.logger(), t_name, t_id, E.code(),
fmt::format( E.displayText(),
"Poco::Exception 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 (...) { } 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));
} }
@@ -174,8 +187,9 @@ namespace OpenWifi {
t_name = "startup_code"; t_name = "startup_code";
t_id = 0; t_id = 0;
} }
poco_warning(App_.logger(), poco_warning(App_.logger(), fmt::format("std::exception in {}: {} thr_id={}",
fmt::format("std::exception in {}: {} thr_id={}", t_name, E.what(), t_id)); t_name,E.what(),
t_id));
} }
inline void exception() override { inline void exception() override {
@@ -186,14 +200,13 @@ namespace OpenWifi {
t_name = "startup_code"; t_name = "startup_code";
t_id = 0; t_id = 0;
} }
poco_warning(App_.logger(), poco_warning(App_.logger(), fmt::format("generic exception in {} thr_id={}",
fmt::format("generic exception in {} thr_id={}", t_name, t_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 <map>
#include <string> #include <string>
#include <map>
#include "Poco/BasicEvent.h" #include "Poco/BasicEvent.h"
#include "Poco/ExpireLRUCache.h" #include "Poco/ExpireLRUCache.h"
@@ -13,26 +13,27 @@
namespace OpenWifi { namespace OpenWifi {
class ConfigurationEntry { class ConfigurationEntry {
public: public:
template <typename T> explicit ConfigurationEntry(T def) : Default_(def), Current_(def) {} template <typename T> explicit ConfigurationEntry(T def) :
Default_(def),
Current_(def){
}
template <typename T> template <typename T> explicit ConfigurationEntry(T def, T cur, const std::string &Hint="") :
explicit ConfigurationEntry(T def, T cur, const std::string &Hint = "") Default_(def),
: Default_(def), Current_(cur), Hint_(Hint) {} Current_(cur),
Hint_(Hint){
}
inline ConfigurationEntry()=default; inline ConfigurationEntry()=default;
inline ~ConfigurationEntry()=default; inline ~ConfigurationEntry()=default;
template <typename T> explicit operator T () const { return std::get<T>(Current_); } template <typename T> explicit operator T () const { return std::get<T>(Current_); }
inline ConfigurationEntry &operator=(const char *v) { inline ConfigurationEntry & operator=(const char *v) { Current_ = std::string(v); return *this;}
Current_ = std::string(v); template <typename T> ConfigurationEntry & operator=(T v) { Current_ = (T) v; return *this;}
return *this;
}
template <typename T> ConfigurationEntry &operator=(T v) {
Current_ = (T)v;
return *this;
}
void reset() { Current_ = Default_; } void reset() {
Current_ = Default_;
}
private: private:
std::variant<bool,uint64_t,std::string> Default_, Current_; std::variant<bool,uint64_t,std::string> Default_, Current_;
@@ -44,9 +45,14 @@ namespace OpenWifi {
template <typename T> class FIFO { template <typename T> class FIFO {
public: public:
explicit FIFO(uint32_t Size) : Size_(Size) { Buffer_ = new T[Size_]; } explicit FIFO(uint32_t Size) :
Size_(Size) {
Buffer_ = new T [Size_];
}
~FIFO() { delete[] Buffer_; } ~FIFO() {
delete [] Buffer_;
}
mutable Poco::BasicEvent<bool> Writable_; mutable Poco::BasicEvent<bool> Writable_;
mutable Poco::BasicEvent<bool> Readable_; mutable Poco::BasicEvent<bool> Readable_;
@@ -102,17 +108,25 @@ namespace OpenWifi {
T * Buffer_ = nullptr; T * Buffer_ = nullptr;
}; };
template <class Record, typename KeyType = std::string, int Size = 256, int Expiry = 60000> template <class Record, typename KeyType = std::string, int Size=256, int Expiry=60000> class RecordCache {
class RecordCache {
public: public:
explicit RecordCache(KeyType Record::*Q) : MemberOffset(Q){}; explicit RecordCache( KeyType Record::* Q) :
inline auto update(const Record &R) { return Cache_.update(R.*MemberOffset, R); } MemberOffset(Q){
inline auto get(const KeyType &K) { return Cache_.get(K); } };
inline auto remove(const KeyType &K) { return Cache_.remove(K); } inline auto update(const Record &R) {
inline auto remove(const Record &R) { return Cache_.remove(R.*MemberOffset); } return Cache_.update(R.*MemberOffset, R);
}
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,10 +2,8 @@
// Created by stephane bourque on 2022-10-25. // Created by stephane bourque on 2022-10-25.
// //
#include "framework/MicroServiceFuncs.h"
#include "framework/MicroService.h" #include "framework/MicroService.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/ALBserver.h"
namespace OpenWifi { namespace OpenWifi {
const std::string &MicroServiceDataDirectory() { return MicroService::instance().DataDir(); } const std::string &MicroServiceDataDirectory() { return MicroService::instance().DataDir(); }
@@ -20,8 +18,7 @@ namespace OpenWifi {
std::string MicroServicePublicEndPoint() { return MicroService::instance().PublicEndPoint(); } std::string MicroServicePublicEndPoint() { return MicroService::instance().PublicEndPoint(); }
std::string MicroServiceConfigGetString(const std::string &Key, std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue) {
const std::string &DefaultValue) {
return MicroService::instance().ConfigGetString(Key, DefaultValue); return MicroService::instance().ConfigGetString(Key, DefaultValue);
} }
@@ -49,17 +46,15 @@ namespace OpenWifi {
void MicroServiceReload(const std::string &Type) { MicroService::instance().Reload(Type); } void MicroServiceReload(const std::string &Type) { MicroService::instance().Reload(Type); }
Types::StringVec MicroServiceGetLogLevelNames() { const Types::StringVec MicroServiceGetLogLevelNames() {
return MicroService::instance().GetLogLevelNames(); return MicroService::instance().GetLogLevelNames();
} }
Types::StringVec MicroServiceGetSubSystems() { const Types::StringVec MicroServiceGetSubSystems() {
return MicroService::instance().GetSubSystems(); return MicroService::instance().GetSubSystems();
} }
Types::StringPairVec MicroServiceGetLogLevels() { Types::StringPairVec MicroServiceGetLogLevels() { return MicroService::instance().GetLogLevels(); }
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);
@@ -81,7 +76,7 @@ namespace OpenWifi {
std::string MicroServiceGetUIURI() { return MicroService::instance().GetUIURI(); } std::string MicroServiceGetUIURI() { return MicroService::instance().GetUIURI(); }
SubSystemVec MicroServiceGetFullSubSystems() { const SubSystemVec MicroServiceGetFullSubSystems() {
return MicroService::instance().GetFullSubSystems(); return MicroService::instance().GetFullSubSystems();
} }
@@ -89,17 +84,20 @@ namespace OpenWifi {
std::uint64_t MicroServiceDaemonBusTimer() { return MicroService::instance().DaemonBusTimer(); } std::uint64_t MicroServiceDaemonBusTimer() { return MicroService::instance().DaemonBusTimer(); }
std::string MicroServiceMakeSystemEventMessage(const char *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, const std::string &DefaultValue) { std::string MicroServiceConfigPath(const std::string &Key,
const std::string &DefaultValue) {
return MicroService::instance().ConfigPath(Key, DefaultValue); return MicroService::instance().ConfigPath(Key, DefaultValue);
} }
std::string MicroServiceWWWAssetsDir() { return MicroService::instance().WWWAssetsDir(); } std::string MicroServiceWWWAssetsDir() {
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);
@@ -125,12 +123,4 @@ namespace OpenWifi {
return MicroService::instance().AllowExternalMicroServices(); return MicroService::instance().AllowExternalMicroServices();
} }
void MicroServiceALBCallback( std::string Callback()) {
return ALBHealthCheckServer()->RegisterExtendedHealthMessage(Callback);
} }
std::string MicroServiceAccessKey() {
return MicroService::instance().Hash();
}
} // namespace OpenWifi

View File

@@ -8,10 +8,11 @@
#include "framework/OpenWifiTypes.h" #include "framework/OpenWifiTypes.h"
#include "Poco/JSON/Object.h"
#include "Poco/JWT/Token.h"
#include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerRequest.h"
#include "Poco/JSON/Object.h"
#include "Poco/ThreadPool.h" #include "Poco/ThreadPool.h"
#include "Poco/JWT/Token.h"
namespace OpenWifi { namespace OpenWifi {
class SubSystemServer; class SubSystemServer;
@@ -20,9 +21,7 @@ namespace OpenWifi {
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, std::string MicroServiceConfigGetString(const std::string &Key, const std::string &DefaultValue);
const std::string &DefaultValue);
std::string MicroServiceAccessKey();
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();
@@ -32,8 +31,8 @@ namespace OpenWifi {
void MicroServiceLoadConfigurationFile(); void MicroServiceLoadConfigurationFile();
void MicroServiceReload(); void MicroServiceReload();
void MicroServiceReload(const std::string &Type); void MicroServiceReload(const std::string &Type);
Types::StringVec MicroServiceGetLogLevelNames(); const Types::StringVec MicroServiceGetLogLevelNames();
Types::StringVec MicroServiceGetSubSystems(); const Types::StringVec MicroServiceGetSubSystems();
Types::StringPairVec MicroServiceGetLogLevels(); Types::StringPairVec MicroServiceGetLogLevels();
bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level); bool MicroServiceSetSubsystemLogLevel(const std::string &SubSystem, const std::string &Level);
void MicroServiceGetExtraConfiguration(Poco::JSON::Object &Answer); void MicroServiceGetExtraConfiguration(Poco::JSON::Object &Answer);
@@ -41,12 +40,13 @@ namespace OpenWifi {
std::uint64_t MicroServiceUptimeTotalSeconds(); std::uint64_t MicroServiceUptimeTotalSeconds();
std::uint64_t MicroServiceStartTimeEpochTime(); std::uint64_t MicroServiceStartTimeEpochTime();
std::string MicroServiceGetUIURI(); std::string MicroServiceGetUIURI();
SubSystemVec MicroServiceGetFullSubSystems(); const SubSystemVec MicroServiceGetFullSubSystems();
std::string MicroServiceCreateUUID(); std::string MicroServiceCreateUUID();
std::uint64_t MicroServiceDaemonBusTimer(); std::uint64_t MicroServiceDaemonBusTimer();
std::string MicroServiceMakeSystemEventMessage(const char *Type); std::string MicroServiceMakeSystemEventMessage( const std::string & Type );
Poco::ThreadPool & MicroServiceTimerPool(); Poco::ThreadPool & MicroServiceTimerPool();
std::string MicroServiceConfigPath(const std::string &Key, const std::string &DefaultValue); std::string MicroServiceConfigPath(const std::string &Key,
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);
@@ -54,5 +54,4 @@ namespace OpenWifi {
std::string MicroServiceGetPublicAPIEndPoint(); std::string MicroServiceGetPublicAPIEndPoint();
void MicroServiceDeleteOverrideConfiguration(); void MicroServiceDeleteOverrideConfiguration();
bool AllowExternalMicroServices(); bool AllowExternalMicroServices();
void MicroServiceALBCallback( std::string Callback()); }
} // namespace OpenWifi

View File

@@ -19,4 +19,4 @@ namespace OpenWifi {
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,19 +4,18 @@
#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/URI.h" #include "Poco/JSON/Parser.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 Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
OpenAPIRequestGet::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) {
try { try {
auto Services = MicroServiceGetServices(Type_); auto Services = MicroServiceGetServices(Type_);
@@ -30,11 +29,11 @@ namespace OpenWifi {
URI.addQueryParameter(qp.first, qp.second); URI.addQueryParameter(qp.first, qp.second);
std::string Path(URI.getPathAndQuery()); std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET, Path, Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_GET,
Path,
Poco::Net::HTTPMessage::HTTP_1_1); Poco::Net::HTTPMessage::HTTP_1_1);
poco_debug(Poco::Logger::get("REST-CALLER-GET"), poco_debug(Poco::Logger::get("REST-CALLER-GET"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
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);
@@ -72,14 +71,15 @@ namespace OpenWifi {
return Response.getStatus(); return Response.getStatus();
} }
} }
} catch (const Poco::Exception &E) { }
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-GET").log(E); Poco::Logger::get("REST-CALLER-GET").log(E);
} }
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
} }
Poco::Net::HTTPServerResponse::HTTPStatus Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
OpenAPIRequestPut::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string &BearerToken) {
try { try {
auto Services = MicroServiceGetServices(Type_); auto Services = MicroServiceGetServices(Type_);
for(auto const &Svc:Services) { for(auto const &Svc:Services) {
@@ -91,12 +91,12 @@ namespace OpenWifi {
for (const auto &qp : QueryData_) for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second); URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-PUT"), poco_debug(Poco::Logger::get("REST-CALLER-PUT"), fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
std::string Path(URI.getPathAndQuery()); std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT, Path, Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_PUT,
Path,
Poco::Net::HTTPMessage::HTTP_1_1); Poco::Net::HTTPMessage::HTTP_1_1);
std::ostringstream obody; std::ostringstream obody;
Poco::JSON::Stringifier::stringify(Body_,obody); Poco::JSON::Stringifier::stringify(Body_,obody);
@@ -148,33 +148,34 @@ namespace OpenWifi {
return Response.getStatus(); return Response.getStatus();
} }
} }
} catch (const Poco::Exception &E) { }
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-PUT").log(E); Poco::Logger::get("REST-CALLER-PUT").log(E);
} }
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
} }
Poco::Net::HTTPServerResponse::HTTPStatus Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken) {
OpenAPIRequestPost::Do(Poco::JSON::Object::Ptr &ResponseObject,
const std::string &BearerToken) {
try { try {
auto Services = MicroServiceGetServices(Type_); auto Services = MicroServiceGetServices(Type_);
for(auto const &Svc:Services) { for(auto const &Svc:Services) {
Poco::URI URI(Svc.PrivateEndPoint); Poco::URI URI(Svc.PrivateEndPoint);
auto Secure = (URI.getScheme() == "https"); auto Secure = (URI.getScheme() == "https");
URI.setPath(EndPoint_); URI.setPath(EndPoint_);
for (const auto &qp : QueryData_) for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second); URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-POST"), poco_debug(Poco::Logger::get("REST-CALLER-POST"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_));
std::string Path(URI.getPathAndQuery()); std::string Path(URI.getPathAndQuery());
Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST, Path, Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_POST,
Path,
Poco::Net::HTTPMessage::HTTP_1_1); Poco::Net::HTTPMessage::HTTP_1_1);
std::ostringstream obody; std::ostringstream obody;
Poco::JSON::Stringifier::stringify(Body_,obody); Poco::JSON::Stringifier::stringify(Body_,obody);
@@ -224,14 +225,15 @@ namespace OpenWifi {
return Response.getStatus(); return Response.getStatus();
} }
} }
} catch (const Poco::Exception &E) { }
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-POST").log(E); Poco::Logger::get("REST-CALLER-POST").log(E);
} }
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
} }
Poco::Net::HTTPServerResponse::HTTPStatus Poco::Net::HTTPServerResponse::HTTPStatus OpenAPIRequestDelete::Do(const std::string & BearerToken) {
OpenAPIRequestDelete::Do(const std::string &BearerToken) {
try { try {
auto Services = MicroServiceGetServices(Type_); auto Services = MicroServiceGetServices(Type_);
@@ -244,12 +246,12 @@ namespace OpenWifi {
for (const auto &qp : QueryData_) for (const auto &qp : QueryData_)
URI.addQueryParameter(qp.first, qp.second); URI.addQueryParameter(qp.first, qp.second);
poco_debug(Poco::Logger::get("REST-CALLER-DELETE"), poco_debug(Poco::Logger::get("REST-CALLER-DELETE"),fmt::format(" {}", LoggingStr_.empty() ? URI.toString() : LoggingStr_ ) );
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, Path, Poco::Net::HTTPRequest Request(Poco::Net::HTTPRequest::HTTP_DELETE,
Path,
Poco::Net::HTTPMessage::HTTP_1_1); Poco::Net::HTTPMessage::HTTP_1_1);
if(BearerToken.empty()) { if(BearerToken.empty()) {
Request.add("X-API-KEY", Svc.AccessKey); Request.add("X-API-KEY", Svc.AccessKey);
@@ -275,10 +277,13 @@ namespace OpenWifi {
return Response.getStatus(); return Response.getStatus();
} }
} }
} catch (const Poco::Exception &E) { }
catch (const Poco::Exception &E)
{
Poco::Logger::get("REST-CALLER-DELETE").log(E); Poco::Logger::get("REST-CALLER-DELETE").log(E);
} }
return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT; return Poco::Net::HTTPServerResponse::HTTP_GATEWAY_TIMEOUT;
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -15,14 +15,17 @@ namespace OpenWifi {
class OpenAPIRequestGet { class OpenAPIRequestGet {
public: public:
explicit OpenAPIRequestGet(const std::string &Type, const std::string &EndPoint, explicit OpenAPIRequestGet( const std::string & Type,
const Types::StringPairVec &QueryData, uint64_t msTimeout, const std::string & EndPoint,
const std::string &LoggingStr = "") const Types::StringPairVec & QueryData,
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout), uint64_t msTimeout,
const std::string &LoggingStr=""):
Type_(Type),
EndPoint_(EndPoint),
QueryData_(QueryData),
msTimeout_(msTimeout),
LoggingStr_(LoggingStr){}; LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
const std::string &BearerToken = "");
private: private:
std::string Type_; std::string Type_;
std::string EndPoint_; std::string EndPoint_;
@@ -33,15 +36,20 @@ namespace OpenWifi {
class OpenAPIRequestPut { class OpenAPIRequestPut {
public: public:
explicit OpenAPIRequestPut(const std::string &Type, const std::string &EndPoint, explicit OpenAPIRequestPut( const std::string & Type,
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, Poco::Net::HTTPServerResponse::HTTPStatus Do(Poco::JSON::Object::Ptr &ResponseObject, const std::string & BearerToken = "");
const std::string &BearerToken = "");
private: private:
std::string Type_; std::string Type_;
@@ -54,15 +62,19 @@ namespace OpenWifi {
class OpenAPIRequestPost { class OpenAPIRequestPost {
public: public:
explicit OpenAPIRequestPost(const std::string &Type, const std::string &EndPoint, explicit OpenAPIRequestPost( const std::string & Type,
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_;
@@ -74,10 +86,15 @@ namespace OpenWifi {
class OpenAPIRequestDelete { class OpenAPIRequestDelete {
public: public:
explicit OpenAPIRequestDelete(const std::string &Type, const std::string &EndPoint, explicit OpenAPIRequestDelete( const std::string & Type,
const Types::StringPairVec &QueryData, uint64_t msTimeout, const std::string & EndPoint,
const std::string &LoggingStr = "") const Types::StringPairVec & QueryData,
: Type_(Type), EndPoint_(EndPoint), QueryData_(QueryData), msTimeout_(msTimeout), uint64_t msTimeout,
const std::string &LoggingStr=""):
Type_(Type),
EndPoint_(EndPoint),
QueryData_(QueryData),
msTimeout_(msTimeout),
LoggingStr_(LoggingStr){}; LoggingStr_(LoggingStr){};
Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string & BearerToken = ""); Poco::Net::HTTPServerResponse::HTTPStatus Do(const std::string & BearerToken = "");

View File

@@ -4,14 +4,14 @@
#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;
@@ -28,9 +28,6 @@ namespace OpenWifi::Types {
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;
typedef std::vector<int64_t> IntList;
typedef std::vector<uint64_t> UIntList;
typedef std::vector<double> DoubleList;
struct MicroServiceMeta { struct MicroServiceMeta {
uint64_t Id=0; uint64_t Id=0;
@@ -44,12 +41,11 @@ namespace OpenWifi::Types {
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, inline void UpdateCountedMap(OpenWifi::Types::CountedMap &M, const std::string &S, uint64_t Increment=1) {
uint64_t Increment = 1) {
auto it = M.find(S); auto it = M.find(S);
if(it==M.end()) if(it==M.end())
M[S] = Increment; M[S] = Increment;
@@ -57,14 +53,14 @@ namespace OpenWifi {
it->second += Increment; it->second += Increment;
} }
inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S, inline void UpdateCountedMap(OpenWifi::Types::Counted3DMapSII &M, const std::string &S, uint32_t Index, uint64_t Increment=1) {
uint32_t Index, uint64_t Increment = 1) {
auto it = M.find(S); auto it = M.find(S);
if(it==M.end()) { if(it==M.end()) {
std::map<uint32_t,uint64_t> E; std::map<uint32_t,uint64_t> E;
E[Index] = Increment; E[Index] = Increment;
M[S] = E; M[S] = E;
} else { }
else {
std::map<uint32_t,uint64_t> & IndexMap = it->second; std::map<uint32_t,uint64_t> & IndexMap = it->second;
auto it_index = IndexMap.find(Index); auto it_index = IndexMap.find(Index);
if(it_index == IndexMap.end()) { if(it_index == IndexMap.end()) {
@@ -74,4 +70,4 @@ namespace OpenWifi {
} }
} }
} }
} // namespace OpenWifi }

View File

@@ -6,23 +6,22 @@
namespace OpenWifi { namespace OpenWifi {
Poco::Net::HTTPRequestHandler * Poco::Net::HTTPRequestHandler *ExtRequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest &Request) {
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, Poco::Net::HTTPRequestHandler *RESTAPI_ExtServer::CallServer(const std::string &Path, uint64_t Id) {
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,21 +6,18 @@
#include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPServer.h"
#include "framework/RESTAPI_Handler.h"
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
Poco::Net::HTTPRequestHandler * Poco::Net::HTTPRequestHandler * RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t Id); 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 * Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
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;
}; };
@@ -39,15 +36,10 @@ namespace OpenWifi {
for(const auto & Svr: ConfigServersList_) { for(const auto & Svr: ConfigServersList_) {
if(MicroServiceNoAPISecurity()) { if(MicroServiceNoAPISecurity()) {
poco_information( poco_information(Logger(),fmt::format("Starting: {}:{}. Security has been disabled for APIs.", Svr.Address(), Svr.Port()));
Logger(),
fmt::format("Starting: {}:{}. Security has been disabled for APIs.",
Svr.Address(), Svr.Port()));
} else { } else {
poco_information(Logger(), poco_information(Logger(),fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}", Svr.Address(), Svr.Port(),
fmt::format("Starting: {}:{} Keyfile:{} CertFile: {}", Svr.KeyFile(),Svr.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());
@@ -60,12 +52,10 @@ namespace OpenWifi {
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>( NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params);
new ExtRequestHandlerFactory, Pool_, Sock, Params);
} else { } else {
auto Sock{Svr.CreateSecureSocket(Logger())}; auto Sock{Svr.CreateSecureSocket(Logger())};
NewServer = std::make_unique<Poco::Net::HTTPServer>( NewServer = std::make_unique<Poco::Net::HTTPServer>(new ExtRequestHandlerFactory, Pool_, Sock, Params);
new ExtRequestHandlerFactory, Pool_, Sock, Params);
}; };
NewServer->start(); NewServer->start();
RESTServers_.push_back(std::move(NewServer)); RESTServers_.push_back(std::move(NewServer));
@@ -98,10 +88,12 @@ namespace OpenWifi {
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,19 +4,25 @@
#pragma once #pragma once
#include <array>
#include <string> #include <string>
#include <array>
#include "Poco/Net/HTTPRequest.h"
#include "Poco/String.h"
#include "Poco/StringTokenizer.h" #include "Poco/StringTokenizer.h"
#include "Poco/String.h"
#include "Poco/Net/HTTPRequest.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,",");
@@ -34,18 +40,14 @@ namespace OpenWifi {
} }
inline void InitLogging() { inline void InitLogging() {
std::string Public = std::string Public = MicroServiceConfigGetString("apilogging.public.methods","PUT,POST,DELETE");
MicroServiceConfigGetString("apilogging.public.methods", "PUT,POST,DELETE");
SetFlags(true, Public); SetFlags(true, Public);
std::string Private = std::string Private = MicroServiceConfigGetString("apilogging.private.methods","PUT,POST,DELETE");
MicroServiceConfigGetString("apilogging.private.methods", "PUT,POST,DELETE");
SetFlags(false, Private); SetFlags(false, Private);
std::string PublicBadTokens = std::string PublicBadTokens = MicroServiceConfigGetString("apilogging.public.badtokens.methods","");
MicroServiceConfigGetString("apilogging.public.badtokens.methods", "");
LogBadTokens_[0] = (Poco::icompare(PublicBadTokens,"true")==0); LogBadTokens_[0] = (Poco::icompare(PublicBadTokens,"true")==0);
std::string PrivateBadTokens = std::string PrivateBadTokens = MicroServiceConfigGetString("apilogging.private.badtokens.methods","");
MicroServiceConfigGetString("apilogging.private.badtokens.methods", "");
LogBadTokens_[1] = (Poco::icompare(PrivateBadTokens,"true")==0); LogBadTokens_[1] = (Poco::icompare(PrivateBadTokens,"true")==0);
} }
@@ -70,4 +72,4 @@ namespace OpenWifi {
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,4 +4,5 @@
#include "RESTAPI_Handler.h" #include "RESTAPI_Handler.h"
namespace OpenWifi {} // namespace OpenWifi namespace OpenWifi {
} // namespace OpenWifi

View File

@@ -4,27 +4,27 @@
#pragma once #pragma once
#include <map>
#include <string> #include <string>
#include <vector> #include <vector>
#include <map>
#include "Poco/DeflatingStream.h" #include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Logger.h"
#include "Poco/JSON/Object.h" #include "Poco/JSON/Object.h"
#include "Poco/JSON/Parser.h" #include "Poco/JSON/Parser.h"
#include "Poco/Logger.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPResponse.h" #include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/OAuth20Credentials.h" #include "Poco/DeflatingStream.h"
#include "Poco/TemporaryFile.h" #include "Poco/TemporaryFile.h"
#include "Poco/Net/OAuth20Credentials.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h" #include "framework/ow_constants.h"
#include "framework/AuthClient.h"
#include "framework/RESTAPI_GenericServerAccounting.h" #include "framework/RESTAPI_GenericServerAccounting.h"
#include "framework/RESTAPI_RateLimiter.h" #include "framework/RESTAPI_RateLimiter.h"
#include "framework/RESTAPI_utils.h"
#include "framework/ow_constants.h"
#include "framework/utils.h" #include "framework/utils.h"
#include "framework/RESTAPI_utils.h"
#include "framework/AuthClient.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#if defined(TIP_SECURITY_SERVICE) #if defined(TIP_SECURITY_SERVICE)
#include "AuthService.h" #include "AuthService.h"
@@ -40,8 +40,7 @@ namespace OpenWifi {
uint64_t StartDate = 0 , EndDate = 0 , Offset = 0 , Limit = 0, LogType = 0 ; uint64_t StartDate = 0 , EndDate = 0 , Offset = 0 , Limit = 0, LogType = 0 ;
std::string SerialNumber, Filter; std::string SerialNumber, Filter;
std::vector<std::string> Select; std::vector<std::string> Select;
bool Lifetime = false, LastOnly = false, Newest = false, CountOnly = false, bool Lifetime=false, LastOnly=false, Newest=false, CountOnly=false, AdditionalInfo=false;
AdditionalInfo = false;
}; };
typedef std::map<std::string, std::string> BindingMap; typedef std::map<std::string, std::string> BindingMap;
@@ -50,19 +49,30 @@ namespace OpenWifi {
int64_t MaxCalls=10; int64_t MaxCalls=10;
}; };
RESTAPIHandler(BindingMap map, Poco::Logger &l, std::vector<std::string> Methods, RESTAPIHandler( BindingMap map,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, Poco::Logger &l,
bool Internal, bool AlwaysAuthorize = true, bool RateLimited = false, std::vector<std::string> Methods,
RESTAPI_GenericServerAccounting & Server,
uint64_t TransactionId,
bool Internal,
bool AlwaysAuthorize=true,
bool RateLimited=false,
const RateLimit & Profile = RateLimit{.Interval=1000,.MaxCalls=100}, const RateLimit & Profile = RateLimit{.Interval=1000,.MaxCalls=100},
bool SubscriberOnly=false) bool SubscriberOnly=false)
: Bindings_(std::move(map)), Logger_(l), Methods_(std::move(Methods)), : Bindings_(std::move(map)),
Internal_(Internal), RateLimited_(RateLimited), SubOnlyService_(SubscriberOnly), Logger_(l),
AlwaysAuthorize_(AlwaysAuthorize), Server_(Server), MyRates_(Profile), Methods_(std::move(Methods)),
TransactionId_(TransactionId) {} Internal_(Internal),
RateLimited_(RateLimited),
SubOnlyService_(SubscriberOnly),
AlwaysAuthorize_(AlwaysAuthorize),
Server_(Server),
MyRates_(Profile),
TransactionId_(TransactionId)
{
}
inline bool RoleIsAuthorized([[maybe_unused]] const std::string &Path, inline bool RoleIsAuthorized([[maybe_unused]] const std::string & Path, [[maybe_unused]] const std::string & Method, [[maybe_unused]] std::string & Reason) {
[[maybe_unused]] const std::string &Method,
[[maybe_unused]] std::string &Reason) {
return true; return true;
} }
@@ -77,13 +87,11 @@ namespace OpenWifi {
if(Request->getContentLength()>0) { if(Request->getContentLength()>0) {
if(Request->getContentType().find("application/json")!=std::string::npos) { if(Request->getContentType().find("application/json")!=std::string::npos) {
ParsedBody_ = IncomingParser_.parse(Request->stream()) ParsedBody_ = IncomingParser_.parse(Request->stream()).extract<Poco::JSON::Object::Ptr>();
.extract<Poco::JSON::Object::Ptr>();
} }
} }
if (RateLimited_ && RESTAPI_RateLimiter()->IsRateLimited( if(RateLimited_ && RESTAPI_RateLimiter()->IsRateLimited(RequestIn,MyRates_.Interval, MyRates_.MaxCalls)) {
RequestIn, MyRates_.Interval, MyRates_.MaxCalls)) {
return UnAuthorized(RESTAPI::Errors::RATE_LIMIT_EXCEEDED); return UnAuthorized(RESTAPI::Errors::RATE_LIMIT_EXCEEDED);
} }
@@ -122,13 +130,9 @@ namespace OpenWifi {
} }
[[nodiscard]] inline bool NeedAdditionalInfo() const { return QB_.AdditionalInfo; } [[nodiscard]] inline bool NeedAdditionalInfo() const { return QB_.AdditionalInfo; }
[[nodiscard]] inline const std::vector<std::string> &SelectedRecords() const { [[nodiscard]] inline const std::vector<std::string> & SelectedRecords() const { return QB_.Select; }
return QB_.Select;
}
inline static bool ParseBindings(const std::string &Request, inline static bool ParseBindings(const std::string & Request, const std::list<std::string> & EndPoints, BindingMap &bindings) {
const std::list<std::string> &EndPoints,
BindingMap &bindings) {
bindings.clear(); bindings.clear();
auto PathItems = Poco::StringTokenizer(Request, "/"); auto PathItems = Poco::StringTokenizer(Request, "/");
@@ -176,39 +180,29 @@ namespace OpenWifi {
return false; return false;
} }
[[nodiscard]] inline uint64_t GetParameter(const std::string &Name, [[nodiscard]] inline uint64_t GetParameter(const std::string &Name, const uint64_t Default) {
const uint64_t Default) { auto Hint = std::find_if(Parameters_.begin(),Parameters_.end(),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
auto Hint = std::find_if(
Parameters_.begin(), Parameters_.end(),
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
if(Hint==Parameters_.end() || !is_number(Hint->second)) if(Hint==Parameters_.end() || !is_number(Hint->second))
return Default; return Default;
return std::stoull(Hint->second); return std::stoull(Hint->second);
} }
[[nodiscard]] inline bool GetBoolParameter(const std::string &Name, bool Default=false) { [[nodiscard]] inline bool GetBoolParameter(const std::string &Name, bool Default=false) {
auto Hint = std::find_if( auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
begin(Parameters_), end(Parameters_),
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
if(Hint==end(Parameters_) || !is_bool(Hint->second)) if(Hint==end(Parameters_) || !is_bool(Hint->second))
return Default; return Default;
return Hint->second=="true"; return Hint->second=="true";
} }
[[nodiscard]] inline std::string GetParameter(const std::string &Name, [[nodiscard]] inline std::string GetParameter(const std::string &Name, const std::string &Default="") {
const std::string &Default = "") { auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
auto Hint = std::find_if(
begin(Parameters_), end(Parameters_),
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
if(Hint==end(Parameters_)) if(Hint==end(Parameters_))
return Default; return Default;
return Hint->second; return Hint->second;
} }
[[nodiscard]] inline bool HasParameter(const std::string &Name, std::string &Value) { [[nodiscard]] inline bool HasParameter(const std::string &Name, std::string &Value) {
auto Hint = std::find_if( auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
begin(Parameters_), end(Parameters_),
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
if(Hint==end(Parameters_)) if(Hint==end(Parameters_))
return false; return false;
Value = Hint->second; Value = Hint->second;
@@ -216,17 +210,14 @@ namespace OpenWifi {
} }
[[nodiscard]] inline bool HasParameter(const std::string &Name, uint64_t & Value) { [[nodiscard]] inline bool HasParameter(const std::string &Name, uint64_t & Value) {
auto Hint = std::find_if( auto Hint = std::find_if(begin(Parameters_),end(Parameters_),[&](const std::pair<std::string,std::string> &S){ return S.first==Name; });
begin(Parameters_), end(Parameters_),
[&](const std::pair<std::string, std::string> &S) { return S.first == Name; });
if(Hint==end(Parameters_)) if(Hint==end(Parameters_))
return false; return false;
Value = std::stoull(Hint->second); Value = std::stoull(Hint->second);
return true; return true;
} }
[[nodiscard]] inline const std::string &GetBinding(const std::string &Name, [[nodiscard]] inline const std::string & GetBinding(const std::string &Name, const std::string &Default="") {
const std::string &Default = "") {
auto E = Bindings_.find(Poco::toLower(Name)); auto E = Bindings_.find(Poco::toLower(Name));
if (E == Bindings_.end()) if (E == Bindings_.end())
return Default; return Default;
@@ -245,8 +236,7 @@ namespace OpenWifi {
return Return; return Return;
} }
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, Types::UUIDvec_t & Value) {
const std::string &Field, Types::UUIDvec_t &Value) {
if(O->has(Field) && O->isArray(Field)) { if(O->has(Field) && O->isArray(Field)) {
auto Arr = O->getArray(Field); auto Arr = O->getArray(Field);
for(const auto &i:*Arr) for(const auto &i:*Arr)
@@ -256,8 +246,7 @@ namespace OpenWifi {
return false; return false;
} }
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, std::string &Value) {
const std::string &Field, std::string &Value) {
if(O->has(Field)) { if(O->has(Field)) {
Value = O->get(Field).toString(); Value = O->get(Field).toString();
return true; return true;
@@ -265,8 +254,7 @@ namespace OpenWifi {
return false; return false;
} }
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, uint64_t &Value) {
const std::string &Field, uint64_t &Value) {
if(O->has(Field)) { if(O->has(Field)) {
Value = O->get(Field); Value = O->get(Field);
return true; return true;
@@ -274,8 +262,7 @@ namespace OpenWifi {
return false; return false;
} }
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, bool &Value) {
const std::string &Field, bool &Value) {
if(O->has(Field)) { if(O->has(Field)) {
Value = O->get(Field).toString()=="true"; Value = O->get(Field).toString()=="true";
return true; return true;
@@ -283,8 +270,7 @@ namespace OpenWifi {
return false; return false;
} }
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, double &Value) {
const std::string &Field, double &Value) {
if(O->has(Field)) { if(O->has(Field)) {
Value = (double) O->get(Field); Value = (double) O->get(Field);
return true; return true;
@@ -292,8 +278,7 @@ namespace OpenWifi {
return false; return false;
} }
static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, static inline bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, Poco::Data::BLOB &Value) {
const std::string &Field, Poco::Data::BLOB &Value) {
if(O->has(Field)) { if(O->has(Field)) {
std::string Content = O->get(Field).toString(); std::string Content = O->get(Field).toString();
auto DecodedBlob = Utils::base64decode(Content); auto DecodedBlob = Utils::base64decode(Content);
@@ -303,9 +288,8 @@ namespace OpenWifi {
return false; return false;
} }
template <typename T>
bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, template <typename T> bool AssignIfPresent(const Poco::JSON::Object::Ptr &O, const std::string &Field, const T &value, T & assignee) {
const T &value, T &assignee) {
if(O->has(Field)) { if(O->has(Field)) {
assignee = value; assignee = value;
return true; return true;
@@ -358,15 +342,13 @@ namespace OpenWifi {
Response->send(); Response->send();
} }
inline void PrepareResponse( inline void PrepareResponse(Poco::Net::HTTPResponse::HTTPStatus Status = Poco::Net::HTTPResponse::HTTP_OK,
Poco::Net::HTTPResponse::HTTPStatus Status = Poco::Net::HTTPResponse::HTTP_OK,
bool CloseConnection = false) { bool CloseConnection = false) {
Response->setStatus(Status); Response->setStatus(Status);
SetCommonHeaders(CloseConnection); SetCommonHeaders(CloseConnection);
} }
inline void BadRequest(const OpenWifi::RESTAPI::Errors::msg &E, inline void BadRequest(const OpenWifi::RESTAPI::Errors::msg &E, const std::string & Extra="") {
const std::string &Extra = "") {
PrepareResponse(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); PrepareResponse(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
Poco::JSON::Object ErrorObject; Poco::JSON::Object ErrorObject;
ErrorObject.set("ErrorCode",400); ErrorObject.set("ErrorCode",400);
@@ -374,8 +356,7 @@ namespace OpenWifi {
if(Extra.empty()) if(Extra.empty())
ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ; ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ;
else else
ErrorObject.set("ErrorDescription", ErrorObject.set("ErrorDescription",fmt::format("{}: {} ({})",E.err_num,E.err_txt, Extra)) ;
fmt::format("{}: {} ({})", E.err_num, E.err_txt, Extra));
std::ostream &Answer = Response->send(); std::ostream &Answer = Response->send();
Poco::JSON::Stringifier::stringify(ErrorObject, Answer); Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
@@ -410,10 +391,11 @@ namespace OpenWifi {
ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ; ErrorObject.set("ErrorDescription",fmt::format("{}: {}",E.err_num,E.err_txt)) ;
std::ostream &Answer = Response->send(); std::ostream &Answer = Response->send();
Poco::JSON::Stringifier::stringify(ErrorObject, Answer); Poco::JSON::Stringifier::stringify(ErrorObject, Answer);
poco_debug(Logger_, poco_debug(Logger_,fmt::format("RES-NOTFOUND: User='{}@{}' Method='{}' Path='{}",
fmt::format("RES-NOTFOUND: User='{}@{}' Method='{}' Path='{}", Requester(), Requester(),
Utils::FormatIPv6(Request->clientAddress().toString()), Utils::FormatIPv6(Request->clientAddress().toString()),
Request->getMethod(), Request->getURI())); Request->getMethod(),
Request->getURI()));
} }
inline void OK() { inline void OK() {
@@ -474,8 +456,7 @@ namespace OpenWifi {
Response->sendFile(File.path(),MT.ContentType); Response->sendFile(File.path(),MT.ContentType);
} }
inline void SendFile(Poco::TemporaryFile &TempAvatar, inline void SendFile(Poco::TemporaryFile &TempAvatar, [[maybe_unused]] const std::string &Type, const std::string & Name) {
[[maybe_unused]] const std::string &Type, const std::string &Name) {
Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
SetCommonHeaders(); SetCommonHeaders();
auto MT = Utils::FindMediaType(Name); auto MT = Utils::FindMediaType(Name);
@@ -483,7 +464,6 @@ namespace OpenWifi {
Response->set("Content-Transfer-Encoding","binary"); Response->set("Content-Transfer-Encoding","binary");
Response->set("Accept-Ranges", "bytes"); Response->set("Accept-Ranges", "bytes");
} }
Response->set("Access-Control-Expose-Headers", "Content-Disposition");
Response->set("Content-Disposition", "attachment; filename=" + Name ); Response->set("Content-Disposition", "attachment; filename=" + Name );
Response->set("Accept-Ranges", "bytes"); Response->set("Accept-Ranges", "bytes");
Response->set("Cache-Control", "no-store"); Response->set("Cache-Control", "no-store");
@@ -492,8 +472,7 @@ namespace OpenWifi {
Response->sendFile(TempAvatar.path(),MT.ContentType); Response->sendFile(TempAvatar.path(),MT.ContentType);
} }
inline void SendFileContent(const std::string &Content, [[maybe_unused]] const std::string &Type, inline void SendFileContent(const std::string &Content, const std::string &Type, const std::string & Name) {
const std::string &Name) {
Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
SetCommonHeaders(); SetCommonHeaders();
auto MT = Utils::FindMediaType(Name); auto MT = Utils::FindMediaType(Name);
@@ -501,18 +480,18 @@ namespace OpenWifi {
Response->set("Content-Transfer-Encoding","binary"); Response->set("Content-Transfer-Encoding","binary");
Response->set("Accept-Ranges", "bytes"); Response->set("Accept-Ranges", "bytes");
} }
Response->set("Access-Control-Expose-Headers", "Content-Disposition");
Response->set("Content-Disposition", "attachment; filename=" + Name ); Response->set("Content-Disposition", "attachment; filename=" + Name );
Response->set("Accept-Ranges", "bytes"); Response->set("Accept-Ranges", "bytes");
Response->set("Cache-Control", "no-store"); Response->set("Cache-Control", "no-store");
Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT"); Response->set("Expires", "Mon, 26 Jul 2027 05:00:00 GMT");
Response->setContentLength(Content.size()); Response->setContentLength(Content.size());
Response->setContentType(MT.ContentType); Response->setContentType(Type );
auto & OutputStream = Response->send(); auto & OutputStream = Response->send();
OutputStream << Content ; OutputStream << Content ;
} }
inline void SendHTMLFileBack(Poco::File &File, const Types::StringPairVec &FormVars) { inline void SendHTMLFileBack(Poco::File & File,
const Types::StringPairVec & FormVars) {
Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK); Response->setStatus(Poco::Net::HTTPResponse::HTTPStatus::HTTP_OK);
SetCommonHeaders(); SetCommonHeaders();
Response->set("Pragma", "private"); Response->set("Pragma", "private");
@@ -526,8 +505,7 @@ namespace OpenWifi {
ostr << FormContent; ostr << FormContent;
} }
inline void ReturnStatus(Poco::Net::HTTPResponse::HTTPStatus Status, inline void ReturnStatus(Poco::Net::HTTPResponse::HTTPStatus Status, bool CloseConnection=false) {
bool CloseConnection = false) {
PrepareResponse(Status, CloseConnection); PrepareResponse(Status, CloseConnection);
if(Status == Poco::Net::HTTPResponse::HTTP_NO_CONTENT) { if(Status == Poco::Net::HTTPResponse::HTTP_NO_CONTENT) {
Response->setContentLength(0); Response->setContentLength(0);
@@ -541,8 +519,7 @@ namespace OpenWifi {
if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS) { if (Request->getMethod() == Poco::Net::HTTPRequest::HTTP_OPTIONS) {
ProcessOptions(); ProcessOptions();
return false; return false;
} else if (std::find(Methods_.begin(), Methods_.end(), Request->getMethod()) == } else if (std::find(Methods_.begin(), Methods_.end(), Request->getMethod()) == Methods_.end()) {
Methods_.end()) {
BadRequest(RESTAPI::Errors::UnsupportedHTTPMethod); BadRequest(RESTAPI::Errors::UnsupportedHTTPMethod);
return false; return false;
} }
@@ -562,8 +539,7 @@ namespace OpenWifi {
AcceptedEncoding->second.find("compress")!=std::string::npos) { AcceptedEncoding->second.find("compress")!=std::string::npos) {
Response->set("Content-Encoding", "gzip"); Response->set("Content-Encoding", "gzip");
std::ostream &Answer = Response->send(); std::ostream &Answer = Response->send();
Poco::DeflatingOutputStream deflater(Answer, Poco::DeflatingOutputStream deflater(Answer, Poco::DeflatingStreamBuf::STREAM_GZIP);
Poco::DeflatingStreamBuf::STREAM_GZIP);
Poco::JSON::Stringifier::stringify(Object, deflater); Poco::JSON::Stringifier::stringify(Object, deflater);
deflater.close(); deflater.close();
return; return;
@@ -574,36 +550,6 @@ namespace OpenWifi {
Poco::JSON::Stringifier::stringify(Object, Answer); Poco::JSON::Stringifier::stringify(Object, Answer);
} }
inline void ReturnObject(const std::vector<std::string> &Strings) {
Poco::JSON::Array Arr;
for(const auto &String:Strings) {
Arr.add(String);
}
std::ostringstream os;
Arr.stringify(os);
return ReturnRawJSON(os.str());
}
template<class T> void ReturnObject(const std::vector<T> &Objects) {
Poco::JSON::Array Arr;
for(const auto &Object:Objects) {
Poco::JSON::Object O;
Object.to_json(O);
Arr.add(O);
}
std::ostringstream os;
Arr.stringify(os);
return ReturnRawJSON(os.str());
}
template<class T> void ReturnObject(const T &Object) {
Poco::JSON::Object O;
Object.to_json(O);
std::ostringstream os;
O.stringify(os);
return ReturnRawJSON(os.str());
}
inline void ReturnRawJSON(const std::string &json_doc) { inline void ReturnRawJSON(const std::string &json_doc) {
PrepareResponse(); PrepareResponse();
if(Request!= nullptr) { if(Request!= nullptr) {
@@ -614,8 +560,7 @@ namespace OpenWifi {
AcceptedEncoding->second.find("compress")!=std::string::npos) { AcceptedEncoding->second.find("compress")!=std::string::npos) {
Response->set("Content-Encoding", "gzip"); Response->set("Content-Encoding", "gzip");
std::ostream &Answer = Response->send(); std::ostream &Answer = Response->send();
Poco::DeflatingOutputStream deflater(Answer, Poco::DeflatingOutputStream deflater(Answer, Poco::DeflatingStreamBuf::STREAM_GZIP);
Poco::DeflatingStreamBuf::STREAM_GZIP);
deflater << json_doc; deflater << json_doc;
deflater.close(); deflater.close();
return; return;
@@ -660,23 +605,19 @@ namespace OpenWifi {
return true; return true;
} }
[[nodiscard]] inline uint64_t Get(const char *Parameter, const Poco::JSON::Object::Ptr &Obj, [[nodiscard]] inline uint64_t Get(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, uint64_t Default=0){
uint64_t Default = 0) {
if(Obj->has(Parameter)) if(Obj->has(Parameter))
return Obj->get(Parameter); return Obj->get(Parameter);
return Default; return Default;
} }
[[nodiscard]] inline std::string GetS(const char *Parameter, [[nodiscard]] inline std::string GetS(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, const std::string & Default=""){
const Poco::JSON::Object::Ptr &Obj,
const std::string &Default = "") {
if(Obj->has(Parameter)) if(Obj->has(Parameter))
return Obj->get(Parameter).toString(); return Obj->get(Parameter).toString();
return Default; return Default;
} }
[[nodiscard]] inline bool GetB(const char *Parameter, const Poco::JSON::Object::Ptr &Obj, [[nodiscard]] inline bool GetB(const char *Parameter,const Poco::JSON::Object::Ptr &Obj, bool Default=false){
bool Default = false) {
if(Obj->has(Parameter)) if(Obj->has(Parameter))
return Obj->get(Parameter).toString()=="true"; return Obj->get(Parameter).toString()=="true";
return Default; return Default;
@@ -716,7 +657,6 @@ namespace OpenWifi {
SecurityObjects::UserInfoAndPolicy UserInfo_; SecurityObjects::UserInfoAndPolicy UserInfo_;
QueryBlock QB_; QueryBlock QB_;
const std::string & Requester() const { return REST_Requester_; } const std::string & Requester() const { return REST_Requester_; }
protected: protected:
BindingMap Bindings_; BindingMap Bindings_;
Poco::URI::QueryParameters Parameters_; Poco::URI::QueryParameters Parameters_;
@@ -737,33 +677,29 @@ namespace OpenWifi {
}; };
#ifdef TIP_SECURITY_SERVICE #ifdef TIP_SECURITY_SERVICE
[[nodiscard]] bool AuthServiceIsAuthorized(Poco::Net::HTTPServerRequest &Request, [[nodiscard]] bool AuthServiceIsAuthorized(Poco::Net::HTTPServerRequest & Request,std::string &SessionToken,
std::string &SessionToken, SecurityObjects::UserInfoAndPolicy & UInfo, std::uint64_t TID, bool & Expired , bool Sub );
SecurityObjects::UserInfoAndPolicy &UInfo,
std::uint64_t TID, bool &Expired, bool Sub);
#endif #endif
inline bool RESTAPIHandler::IsAuthorized(bool &Expired, [[maybe_unused]] bool &Contacted, inline bool RESTAPIHandler::IsAuthorized( bool & Expired , [[maybe_unused]] bool & Contacted , bool Sub ) {
bool Sub) {
if(Internal_ && Request->has("X-INTERNAL-NAME")) { if(Internal_ && Request->has("X-INTERNAL-NAME")) {
auto Allowed = MicroServiceIsValidAPIKEY(*Request); auto Allowed = MicroServiceIsValidAPIKEY(*Request);
Contacted = true; Contacted = true;
if(!Allowed) { if(!Allowed) {
if(Server_.LogBadTokens(false)) { if(Server_.LogBadTokens(false)) {
poco_debug(Logger_, poco_debug(Logger_,fmt::format("I-REQ-DENIED({}): TID={} Method={} Path={}",
fmt::format("I-REQ-DENIED({}): TID={} Method={} Path={}",
Utils::FormatIPv6(Request->clientAddress().toString()), Utils::FormatIPv6(Request->clientAddress().toString()),
TransactionId_, Request->getMethod(), TransactionId_,
Request->getURI())); Request->getMethod(), Request->getURI()));
} }
} else { } else {
auto Id = Request->get("X-INTERNAL-NAME", "unknown"); auto Id = Request->get("X-INTERNAL-NAME", "unknown");
REST_Requester_ = Id; REST_Requester_ = Id;
if(Server_.LogIt(Request->getMethod(),true)) { if(Server_.LogIt(Request->getMethod(),true)) {
poco_debug(Logger_, poco_debug(Logger_,fmt::format("I-REQ-ALLOWED({}): TID={} User='{}' Method={} Path={}",
fmt::format("I-REQ-ALLOWED({}): TID={} User='{}' Method={} Path={}",
Utils::FormatIPv6(Request->clientAddress().toString()), Utils::FormatIPv6(Request->clientAddress().toString()),
TransactionId_, Id, Request->getMethod(), TransactionId_,
Request->getURI())); Id,
Request->getMethod(), Request->getURI()));
} }
} }
return Allowed; return Allowed;
@@ -772,29 +708,27 @@ namespace OpenWifi {
bool suspended=false; bool suspended=false;
#ifdef TIP_SECURITY_SERVICE #ifdef TIP_SECURITY_SERVICE
std::uint64_t expiresOn; std::uint64_t expiresOn;
if (AuthService()->IsValidApiKey(SessionToken_, UserInfo_.webtoken, UserInfo_.userinfo, if (AuthService()->IsValidApiKey(SessionToken_, UserInfo_.webtoken, UserInfo_.userinfo, Expired, expiresOn, suspended)) {
Expired, expiresOn, suspended)) {
#else #else
if (AuthClient()->IsValidApiKey(SessionToken_, UserInfo_, TransactionId_, Expired, if (AuthClient()->IsValidApiKey( SessionToken_, UserInfo_, TransactionId_, Expired, Contacted, suspended)) {
Contacted, suspended)) {
#endif #endif
REST_Requester_ = UserInfo_.userinfo.email; REST_Requester_ = UserInfo_.userinfo.email;
if(Server_.LogIt(Request->getMethod(),true)) { if(Server_.LogIt(Request->getMethod(),true)) {
poco_debug(Logger_, poco_debug(Logger_,fmt::format("X-REQ-ALLOWED({}): APIKEY-ACCESS TID={} User='{}@{}' Method={} Path={}",
fmt::format("X-REQ-ALLOWED({}): APIKEY-ACCESS TID={} User='{}@{}' " UserInfo_.userinfo.email,
"Method={} Path={}", TransactionId_,
UserInfo_.userinfo.email, TransactionId_,
Utils::FormatIPv6(Request->clientAddress().toString()), Utils::FormatIPv6(Request->clientAddress().toString()),
Request->clientAddress().toString(), Request->clientAddress().toString(),
Request->getMethod(), Request->getURI())); Request->getMethod(),
Request->getURI()));
} }
return true; return true;
} else { } else {
if(Server_.LogBadTokens(true)) { if(Server_.LogBadTokens(true)) {
poco_debug(Logger_, poco_debug(Logger_,fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}",
fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}",
Utils::FormatIPv6(Request->clientAddress().toString()), Utils::FormatIPv6(Request->clientAddress().toString()),
TransactionId_, Request->getMethod(), TransactionId_,
Request->getMethod(),
Request->getURI())); Request->getURI()));
} }
} }
@@ -811,29 +745,27 @@ namespace OpenWifi {
} }
} }
#ifdef TIP_SECURITY_SERVICE #ifdef TIP_SECURITY_SERVICE
if (AuthServiceIsAuthorized(*Request, SessionToken_, UserInfo_, TransactionId_, Expired, if (AuthServiceIsAuthorized(*Request, SessionToken_, UserInfo_, TransactionId_, Expired, Sub)) {
Sub)) {
#else #else
if (AuthClient()->IsAuthorized(SessionToken_, UserInfo_, TransactionId_, Expired, if (AuthClient()->IsAuthorized( SessionToken_, UserInfo_, TransactionId_, Expired, Contacted, Sub)) {
Contacted, Sub)) {
#endif #endif
REST_Requester_ = UserInfo_.userinfo.email; REST_Requester_ = UserInfo_.userinfo.email;
if(Server_.LogIt(Request->getMethod(),true)) { if(Server_.LogIt(Request->getMethod(),true)) {
poco_debug( poco_debug(Logger_,fmt::format("X-REQ-ALLOWED({}): TID={} User='{}@{}' Method={} Path={}",
Logger_, UserInfo_.userinfo.email,
fmt::format("X-REQ-ALLOWED({}): TID={} User='{}@{}' Method={} Path={}", TransactionId_,
UserInfo_.userinfo.email, TransactionId_,
Utils::FormatIPv6(Request->clientAddress().toString()), Utils::FormatIPv6(Request->clientAddress().toString()),
Request->clientAddress().toString(), Request->getMethod(), Request->clientAddress().toString(),
Request->getMethod(),
Request->getURI())); Request->getURI()));
} }
return true; return true;
} else { } else {
if(Server_.LogBadTokens(true)) { if(Server_.LogBadTokens(true)) {
poco_debug(Logger_, poco_debug(Logger_,fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}",
fmt::format("X-REQ-DENIED({}): TID={} Method={} Path={}",
Utils::FormatIPv6(Request->clientAddress().toString()), Utils::FormatIPv6(Request->clientAddress().toString()),
TransactionId_, Request->getMethod(), TransactionId_,
Request->getMethod(),
Request->getURI())); Request->getURI()));
} }
} }
@@ -843,11 +775,8 @@ namespace OpenWifi {
class RESTAPI_UnknownRequestHandler : public RESTAPIHandler { class RESTAPI_UnknownRequestHandler : public RESTAPIHandler {
public: public:
RESTAPI_UnknownRequestHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_UnknownRequestHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_GenericServerAccounting &Server, : RESTAPIHandler(bindings, L, std::vector<std::string>{}, Server, TransactionId, Internal) {}
uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L, std::vector<std::string>{}, Server, TransactionId,
Internal) {}
inline void DoGet() override {}; inline void DoGet() override {};
inline void DoPost() override {}; inline void DoPost() override {};
inline void DoPut() override {}; inline void DoPut() override {};
@@ -855,37 +784,35 @@ namespace OpenWifi {
}; };
template<class T> template<class T>
constexpr auto test_has_PathName_method(T *) -> decltype(T::PathName(), std::true_type{}) { constexpr auto test_has_PathName_method(T*)
-> decltype( T::PathName() , std::true_type{} )
{
return std::true_type{}; return std::true_type{};
} }
constexpr auto test_has_PathName_method(...) -> std::false_type { return std::false_type{}; } constexpr auto test_has_PathName_method(...) -> std::false_type
{
return std::false_type{};
}
template<typename T, typename... Args> template<typename T, typename... Args>
RESTAPIHandler *RESTAPI_Router(const std::string &RequestedPath, RESTAPIHandler * RESTAPI_Router(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings,
RESTAPIHandler::BindingMap &Bindings, Poco::Logger &Logger, Poco::Logger & Logger, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId) {
RESTAPI_GenericServerAccounting &Server, static_assert(test_has_PathName_method((T*)nullptr), "Class must have a static PathName() method.");
uint64_t TransactionId) {
static_assert(test_has_PathName_method((T *)nullptr),
"Class must have a static PathName() method.");
if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) { if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) {
return new T(Bindings, Logger, Server, TransactionId, false); return new T(Bindings, Logger, Server, TransactionId, false);
} }
if constexpr (sizeof...(Args) == 0) { if constexpr (sizeof...(Args) == 0) {
return new RESTAPI_UnknownRequestHandler(Bindings, Logger, Server, TransactionId, return new RESTAPI_UnknownRequestHandler(Bindings,Logger, Server, TransactionId, false);
false);
} else { } else {
return RESTAPI_Router<Args...>(RequestedPath, Bindings, Logger, Server, TransactionId); return RESTAPI_Router<Args...>(RequestedPath, Bindings, Logger, Server, TransactionId);
} }
} }
template<typename T, typename... Args> template<typename T, typename... Args>
RESTAPIHandler *RESTAPI_Router_I(const std::string &RequestedPath, RESTAPIHandler * RESTAPI_Router_I(const std::string & RequestedPath, RESTAPIHandler::BindingMap &Bindings,
RESTAPIHandler::BindingMap &Bindings, Poco::Logger &Logger, Poco::Logger & Logger, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId) {
RESTAPI_GenericServerAccounting &Server, static_assert(test_has_PathName_method((T*)nullptr), "Class must have a static PathName() method.");
uint64_t TransactionId) {
static_assert(test_has_PathName_method((T *)nullptr),
"Class must have a static PathName() method.");
if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) { if(RESTAPIHandler::ParseBindings(RequestedPath,T::PathName(),Bindings)) {
return new T(Bindings, Logger, Server, TransactionId, true ); return new T(Bindings, Logger, Server, TransactionId, true );
} }
@@ -893,8 +820,7 @@ namespace OpenWifi {
if constexpr (sizeof...(Args) == 0) { if constexpr (sizeof...(Args) == 0) {
return new RESTAPI_UnknownRequestHandler(Bindings,Logger, Server, TransactionId, true); return new RESTAPI_UnknownRequestHandler(Bindings,Logger, Server, TransactionId, true);
} else { } else {
return RESTAPI_Router_I<Args...>(RequestedPath, Bindings, Logger, Server, return RESTAPI_Router_I<Args...>(RequestedPath, Bindings, Logger, Server, TransactionId);
TransactionId);
} }
} }

View File

@@ -6,21 +6,18 @@
#include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPServer.h"
#include "framework/RESTAPI_Handler.h"
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "framework/RESTAPI_Handler.h"
namespace OpenWifi { namespace OpenWifi {
Poco::Net::HTTPRequestHandler * Poco::Net::HTTPRequestHandler * RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t Id); 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 * Poco::Net::HTTPRequestHandler *createRequestHandler(const Poco::Net::HTTPServerRequest &Request) override;
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;
}; };
@@ -39,15 +36,10 @@ namespace OpenWifi {
for(const auto & Svr: ConfigServersList_) { for(const auto & Svr: ConfigServersList_) {
if(MicroServiceNoAPISecurity()) { if(MicroServiceNoAPISecurity()) {
poco_information( poco_information(Logger(),fmt::format("Starting: {}:{}. Security has been disabled for APIs.", Svr.Address(), Svr.Port()));
Logger(),
fmt::format("Starting: {}:{}. Security has been disabled for APIs.",
Svr.Address(), Svr.Port()));
} else { } else {
poco_information(Logger(), poco_information(Logger(),fmt::format("Starting: {}:{}. Keyfile:{} CertFile: {}", Svr.Address(), Svr.Port(),
fmt::format("Starting: {}:{}. Keyfile:{} CertFile: {}", Svr.KeyFile(),Svr.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());
@@ -60,12 +52,10 @@ namespace OpenWifi {
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>( NewServer = std::make_unique<Poco::Net::HTTPServer>(new IntRequestHandlerFactory, Pool_, Sock, Params);
new IntRequestHandlerFactory, Pool_, Sock, Params);
} else { } else {
auto Sock{Svr.CreateSecureSocket(Logger())}; auto Sock{Svr.CreateSecureSocket(Logger())};
NewServer = std::make_unique<Poco::Net::HTTPServer>( NewServer = std::make_unique<Poco::Net::HTTPServer>(new IntRequestHandlerFactory, Pool_, Sock, Params);
new IntRequestHandlerFactory, Pool_, Sock, Params);
}; };
NewServer->start(); NewServer->start();
RESTServers_.push_back(std::move(NewServer)); RESTServers_.push_back(std::move(NewServer));
@@ -96,16 +86,19 @@ namespace OpenWifi {
return RESTAPI_IntRouter(Path, Bindings, Logger(), Server_, Id); return RESTAPI_IntRouter(Path, Bindings, Logger(), Server_, Id);
} }
const Poco::ThreadPool & Pool() { return Pool_; } const Poco::ThreadPool & Pool() { return Pool_; }
private: private:
std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_; std::vector<std::unique_ptr<Poco::Net::HTTPServer>> RESTServers_;
Poco::ThreadPool Pool_{"i-rest",4,64}; Poco::ThreadPool Pool_{"i-rest",4,64};
RESTAPI_GenericServerAccounting Server_; RESTAPI_GenericServerAccounting Server_;
RESTAPI_IntServer() noexcept RESTAPI_IntServer() noexcept:
: SubSystemServer("RESTAPI_IntServer", "REST-ISRV", "openwifi.internal.restapi") {} SubSystemServer("RESTAPI_IntServer", "REST-ISRV", "openwifi.internal.restapi")
{
}
}; };
inline auto RESTAPI_IntServer() { return RESTAPI_IntServer::instance(); }; inline auto RESTAPI_IntServer() { return RESTAPI_IntServer::instance(); };
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,26 +4,29 @@
#pragma once #pragma once
#include "Poco/CountingStream.h" #include <string>
#include "Poco/Net/MessageHeader.h"
#include "Poco/Net/PartHandler.h" #include "Poco/Net/PartHandler.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/CountingStream.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() : _length(0) {} RESTAPI_PartHandler():
_length(0)
{
}
inline void handlePart(const Poco::Net::MessageHeader &header, inline void handlePart(const Poco::Net::MessageHeader& header, std::istream& stream) override
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, Poco::Net::MessageHeader::splitParameters(header["Content-Disposition"], disp, params);
params);
_name = params.get("name", "(unnamed)"); _name = params.get("name", "(unnamed)");
_fileName = params.get("filename", "(unnamed)"); _fileName = params.get("filename", "(unnamed)");
} }
@@ -34,13 +37,25 @@ namespace OpenWifi {
_length = (int)istr.chars(); _length = (int)istr.chars();
} }
[[nodiscard]] inline int length() const { return _length; } [[nodiscard]] inline int length() const
{
return _length;
}
[[nodiscard]] inline const std::string &name() const { return _name; } [[nodiscard]] inline const std::string& name() const
{
return _name;
}
[[nodiscard]] inline const std::string &fileName() const { return _fileName; } [[nodiscard]] inline const std::string& fileName() const
{
return _fileName;
}
[[nodiscard]] inline const std::string &contentType() const { return _type; } [[nodiscard]] inline const std::string& contentType() const
{
return _type;
}
private: private:
int _length; int _length;
@@ -48,4 +63,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/ExpireLRUCache.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/URI.h" #include "Poco/URI.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/ExpireLRUCache.h"
#include "fmt/format.h" #include "fmt/format.h"
@@ -16,6 +16,7 @@ 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;
@@ -29,14 +30,11 @@ namespace OpenWifi {
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, inline bool IsRateLimited(const Poco::Net::HTTPServerRequest &R, int64_t Period, int64_t MaxCalls) {
int64_t MaxCalls) {
Poco::URI uri(R.getURI()); Poco::URI uri(R.getURI());
auto H = str_hash(uri.getPath() + R.clientAddress().host().toString()); auto H = str_hash(uri.getPath() + R.clientAddress().host().toString());
auto E = Cache_.get(H); auto E = Cache_.get(H);
auto Now = std::chrono::duration_cast<std::chrono::milliseconds>( auto Now = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
std::chrono::system_clock::now().time_since_epoch())
.count();
if(E.isNull()) { if(E.isNull()) {
Cache_.add(H,ClientCacheEntry{.Start=Now, .Count=1}); Cache_.add(H,ClientCacheEntry{.Start=Now, .Count=1});
return false; return false;
@@ -45,8 +43,7 @@ namespace OpenWifi {
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 '{}'", poco_warning(Logger(),fmt::format("RATE-LIMIT-EXCEEDED: from '{}'", R.clientAddress().toString()));
R.clientAddress().toString()));
return true; return true;
} }
return false; return false;
@@ -57,16 +54,22 @@ namespace OpenWifi {
return false; return false;
} }
inline void Clear() { Cache_.clear(); } inline void Clear() {
Cache_.clear();
}
private: private:
Poco::ExpireLRUCache<uint64_t,ClientCacheEntry> Cache_{2048}; Poco::ExpireLRUCache<uint64_t,ClientCacheEntry> Cache_{2048};
std::hash<std::string> str_hash; std::hash<std::string> str_hash;
RESTAPI_RateLimiter() noexcept RESTAPI_RateLimiter() noexcept:
: SubSystemServer("RateLimiter", "RATE-LIMITER", "rate.limiter") {} SubSystemServer("RateLimiter", "RATE-LIMITER", "rate.limiter")
{
}
}; };
inline auto RESTAPI_RateLimiter() { return RESTAPI_RateLimiter::instance(); } inline auto RESTAPI_RateLimiter() { return RESTAPI_RateLimiter::instance(); }
} // namespace OpenWifi
}

View File

@@ -14,20 +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_system_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
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, TransactionId, Internal) {} Server,
TransactionId,
Internal) {}
static auto PathName() { return std::list<std::string>{"/api/v1/system"};} static auto PathName() { return std::list<std::string>{"/api/v1/system"};}
inline void DoGet() final { inline void DoGet() {
std::string Arg; std::string Arg;
if (HasParameter("command", Arg)) { if(HasParameter("command",Arg) && Arg=="info") {
if (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());
@@ -65,23 +64,11 @@ namespace OpenWifi {
Answer.set("certificates", Certificates); Answer.set("certificates", Certificates);
return ReturnObject(Answer); return ReturnObject(Answer);
} }
if (Arg == "extraConfiguration") { if(GetBoolParameter("extraConfiguration")) {
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
MicroServiceGetExtraConfiguration(Answer); MicroServiceGetExtraConfiguration(Answer);
return ReturnObject(Answer); return ReturnObject(Answer);
} }
if (Arg == "resources") {
Poco::JSON::Object Answer;
Answer.set("numberOfFileDescriptors", Utils::get_open_fds());
std::uint64_t currRealMem, peakRealMem, currVirtMem, peakVirtMem;
Utils::getMemory(currRealMem, peakRealMem, currVirtMem, peakVirtMem);
Answer.set("currRealMem", currRealMem);
Answer.set("peakRealMem", peakRealMem);
Answer.set("currVirtMem", currVirtMem);
Answer.set("peakVirtMem", peakVirtMem);
return ReturnObject(Answer);
}
}
BadRequest(RESTAPI::Errors::InvalidCommand); BadRequest(RESTAPI::Errors::InvalidCommand);
} }
@@ -101,8 +88,7 @@ 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( poco_information(Logger_,
Logger_,
fmt::format("Setting log level for {} at {}", Name, Value)); fmt::format("Setting log level for {} at {}", Name, Value));
} }
} }
@@ -168,4 +154,4 @@ namespace OpenWifi {
void DoDelete() final {}; void DoDelete() final {};
}; };
} // namespace OpenWifi }

View File

@@ -4,33 +4,32 @@
#pragma once #pragma once
#include "Poco/Net/WebSocket.h"
#include "framework/RESTAPI_Handler.h" #include "framework/RESTAPI_Handler.h"
#include "Poco/Net/WebSocket.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/UI_WebSocketClientServer.h" #include "framework/UI_WebSocketClientServer.h"
#include "framework/MicroServiceFuncs.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, inline RESTAPI_webSocketServer(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, bool Internal)
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() && {
Poco::icompare((*Request)["Upgrade"], "websocket") == 0) { if(Request->find("Upgrade") != Request->end() && 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;
} }
} }
@@ -41,7 +40,6 @@ namespace OpenWifi {
void DoDelete() final {}; void DoDelete() final {};
void DoPost() final {}; void DoPost() final {};
void DoPut() final {}; void DoPut() final {};
private: private:
}; };
} // namespace OpenWifi }

View File

@@ -6,25 +6,17 @@
#include <string> #include <string>
#include "Poco/Data/LOB.h"
#include "Poco/JSON/Object.h" #include "Poco/JSON/Object.h"
#include "Poco/JSON/Parser.h" #include "Poco/JSON/Parser.h"
#include "Poco/Data/LOB.h"
#include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerRequest.h"
#include "framework/OpenWifiTypes.h" #include "framework/OpenWifiTypes.h"
#include "framework/utils.h" #include "framework/utils.h"
#include <RESTObjects/RESTAPI_SecurityObjects.h>
namespace OpenWifi::RESTAPI_utils { namespace OpenWifi::RESTAPI_utils {
inline bool IsRootOrAdmin(const SecurityObjects::UserInfo &UI) { inline void EmbedDocument(const std::string & ObjName, Poco::JSON::Object & Obj, const std::string &ObjStr) {
return UI.userRole==SecurityObjects::ROOT ||
UI.userRole==SecurityObjects::ADMIN;
}
inline void EmbedDocument(const std::string &ObjName, Poco::JSON::Object &Obj,
const std::string &ObjStr) {
std::string D = ObjStr.empty() ? "{}" : ObjStr; std::string D = ObjStr.empty() ? "{}" : ObjStr;
Poco::JSON::Parser P; Poco::JSON::Parser P;
Poco::Dynamic::Var result = P.parse(D); Poco::Dynamic::Var result = P.parse(D);
@@ -76,14 +68,12 @@ namespace OpenWifi::RESTAPI_utils {
Obj.set(Field,Value); Obj.set(Field,Value);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Poco::Data::BLOB &Value) {
const Poco::Data::BLOB &Value) {
auto Result = Utils::base64encode((const unsigned char *)Value.rawContent(),Value.size()); auto Result = Utils::base64encode((const unsigned char *)Value.rawContent(),Value.size());
Obj.set(Field,Result); Obj.set(Field,Result);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::StringPairVec & S) {
const Types::StringPairVec &S) {
Poco::JSON::Array Array; Poco::JSON::Array Array;
for(const auto &i:S) { for(const auto &i:S) {
Poco::JSON::Object O; Poco::JSON::Object O;
@@ -94,22 +84,7 @@ namespace OpenWifi::RESTAPI_utils {
Obj.set(Field,Array); Obj.set(Field,Array);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::StringVec &V) {
const Types::StringVec &V) {
Poco::JSON::Array A;
for (const auto &i : V)
A.add(i);
Obj.set(Field, A);
}
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::DoubleList &V) {
Poco::JSON::Array A;
for (const auto &i : V)
A.add(i);
Obj.set(Field, A);
}
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::IntList &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);
@@ -123,8 +98,7 @@ namespace OpenWifi::RESTAPI_utils {
Obj.set(Field,A); Obj.set(Field,A);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::CountedMap &M) {
const Types::CountedMap &M) {
Poco::JSON::Array A; Poco::JSON::Array A;
for(const auto &[Key,Value]:M) { for(const auto &[Key,Value]:M) {
Poco::JSON::Object O; Poco::JSON::Object O;
@@ -135,8 +109,7 @@ namespace OpenWifi::RESTAPI_utils {
Obj.set(Field,A); Obj.set(Field,A);
} }
inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, inline void field_to_json(Poco::JSON::Object &Obj, const char *Field, const Types::Counted3DMapSII &M) {
const Types::Counted3DMapSII &M) {
Poco::JSON::Array A; Poco::JSON::Array A;
for(const auto &[OrgName,MonthlyNumberMap]:M) { for(const auto &[OrgName,MonthlyNumberMap]:M) {
Poco::JSON::Object OrgObject; Poco::JSON::Object OrgObject;
@@ -154,14 +127,14 @@ namespace OpenWifi::RESTAPI_utils {
Obj.set(Field, A); Obj.set(Field, A);
} }
template <typename T> template<typename T> void field_to_json(Poco::JSON::Object &Obj,
void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &V, const char *Field,
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> template<class T> void field_to_json(Poco::JSON::Object &Obj, const char *Field, const std::vector<T> &Value) {
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;
@@ -171,8 +144,7 @@ namespace OpenWifi::RESTAPI_utils {
Obj.set(Field, Arr); Obj.set(Field, Arr);
} }
template <class T> template<class T> void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &Value) {
void field_to_json(Poco::JSON::Object &Obj, const char *Field, const T &Value) {
Poco::JSON::Object Answer; Poco::JSON::Object Answer;
Value.to_json(Answer); Value.to_json(Answer);
Obj.set(Field, Answer); Obj.set(Field, Answer);
@@ -183,84 +155,71 @@ namespace OpenWifi::RESTAPI_utils {
/////////////////////////// ///////////////////////////
/////////////////////////// ///////////////////////////
template <typename T> template<typename T> bool field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T & V,
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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, std::string &S) {
std::string &S) {
if(Obj->has(Field) && !Obj->isNull(Field)) 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, double & Value) {
double &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, float & Value) {
float &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, bool &Value) {
bool &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int16_t &Value) {
int16_t &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int32_t &Value) {
int32_t &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) if(Obj->has(Field) && !Obj->isNull(Field))
Value = (int32_t) Obj->get(Field); Value = (int32_t) Obj->get(Field);
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, int64_t &Value) {
int64_t &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint16_t &Value) {
uint16_t &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint32_t &Value) {
uint32_t &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, uint64_t &Value) {
uint64_t &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Poco::Data::BLOB &Value) {
Poco::Data::BLOB &Value) {
if(Obj->has(Field) && !Obj->isNull(Field)) { 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, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::StringPairVec &Vec) {
Types::StringPairVec &Vec) {
if(Obj->isArray(Field) && !Obj->isNull(Field)) { 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) {
@@ -276,8 +235,7 @@ namespace OpenWifi::RESTAPI_utils {
} }
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::StringVec &Value) {
Types::StringVec &Value) {
if(Obj->isArray(Field) && !Obj->isNull(Field)) { 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);
@@ -287,8 +245,7 @@ namespace OpenWifi::RESTAPI_utils {
} }
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, Types::TagList &Value) {
Types::TagList &Value) {
if(Obj->isArray(Field) && !Obj->isNull(Field)) { 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);
@@ -298,31 +255,7 @@ namespace OpenWifi::RESTAPI_utils {
} }
} }
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, template<class T> void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, std::vector<T> &Value) {
Types::DoubleList &Value) {
if (Obj->isArray(Field) && !Obj->isNull(Field)) {
Value.clear();
Poco::JSON::Array::Ptr A = Obj->getArray(Field);
for (const auto &i : *A) {
Value.push_back(i);
}
}
}
inline void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
Types::IntList &Value) {
if (Obj->isArray(Field) && !Obj->isNull(Field)) {
Value.clear();
Poco::JSON::Array::Ptr A = Obj->getArray(Field);
for (const auto &i : *A) {
Value.push_back(i);
}
}
}
template <class T>
void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field,
std::vector<T> &Value) {
if(Obj->isArray(Field) && !Obj->isNull(Field)) { if(Obj->isArray(Field) && !Obj->isNull(Field)) {
Poco::JSON::Array::Ptr Arr = Obj->getArray(Field); Poco::JSON::Array::Ptr Arr = Obj->getArray(Field);
for(auto &i:*Arr) { for(auto &i:*Arr) {
@@ -334,8 +267,7 @@ namespace OpenWifi::RESTAPI_utils {
} }
} }
template <class T> template<class T> void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &Value) {
void field_from_json(const Poco::JSON::Object::Ptr &Obj, const char *Field, T &Value) {
if(Obj->isObject(Field) && !Obj->isNull(Field)) { if(Obj->isObject(Field) && !Obj->isNull(Field)) {
Poco::JSON::Object::Ptr A = Obj->getObject(Field); Poco::JSON::Object::Ptr A = Obj->getObject(Field);
Value.from_json(A); Value.from_json(A);
@@ -404,8 +336,7 @@ namespace OpenWifi::RESTAPI_utils {
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);
@@ -442,6 +373,7 @@ namespace OpenWifi::RESTAPI_utils {
Result.push_back(i.toString()); Result.push_back(i.toString());
} }
} catch (...) { } catch (...) {
} }
return Result; return Result;
} }
@@ -458,6 +390,7 @@ namespace OpenWifi::RESTAPI_utils {
Result.push_back(i); Result.push_back(i);
} }
} catch (...) { } catch (...) {
} }
return Result; return Result;
} }
@@ -478,6 +411,7 @@ namespace OpenWifi::RESTAPI_utils {
} }
} }
} catch (...) { } catch (...) {
} }
return R; return R;
@@ -498,12 +432,12 @@ namespace OpenWifi::RESTAPI_utils {
Result.push_back(Obj); Result.push_back(Obj);
} }
} catch (...) { } catch (...) {
} }
return Result; return Result;
} }
template <class T> template<class T> std::vector<std::vector<T>> to_array_of_array_of_object(const std::string & ObjectString) {
std::vector<std::vector<T>> to_array_of_array_of_object(const std::string &ObjectString) {
std::vector<std::vector<T>> Result; std::vector<std::vector<T>> Result;
if(ObjectString.empty()) if(ObjectString.empty())
return Result; return Result;
@@ -523,6 +457,7 @@ namespace OpenWifi::RESTAPI_utils {
Result.push_back(InnerVector); Result.push_back(InnerVector);
} }
} catch (...) { } catch (...) {
} }
return Result; return Result;
} }
@@ -546,4 +481,4 @@ namespace OpenWifi::RESTAPI_utils {
Obj.from_json(RawObject); Obj.from_json(RawObject);
return true; return true;
} }
} // namespace OpenWifi::RESTAPI_utils }

View File

@@ -4,26 +4,34 @@
#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/MySQL/Connector.h"
#include "Poco/Data/PostgreSQL/Connector.h" #include "Poco/Data/PostgreSQL/Connector.h"
#include "Poco/Data/MySQL/Connector.h"
#endif #endif
#include "framework/MicroServiceFuncs.h"
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "framework/MicroServiceFuncs.h"
namespace OpenWifi { namespace OpenWifi {
enum DBType { sqlite, pgsql, mysql }; enum DBType {
sqlite,
pgsql,
mysql
};
class StorageClass : public SubSystemServer { class StorageClass : public SubSystemServer {
public: public:
StorageClass() noexcept:
SubSystemServer("StorageClass", "STORAGE-SVR", "storage")
{
}
inline int Start() override { int Start() override {
std::lock_guard Guard(Mutex_); std::lock_guard Guard(Mutex_);
Logger().notice("Starting."); Logger().notice("Starting.");
@@ -39,24 +47,18 @@ namespace OpenWifi {
return 0; return 0;
} }
inline void Stop() override { Pool_->shutdown(); } void Stop() override {
Pool_->shutdown();
DBType Type() const { return dbType_; };
StorageClass() noexcept : SubSystemServer("StorageClass", "STORAGE-SVR", "storage") {
} }
Poco::Data::SessionPool &Pool() { return *Pool_; } DBType Type() const { return dbType_; };
private: private:
inline int Setup_SQLite(); inline int Setup_SQLite();
inline int Setup_MySQL(); inline int Setup_MySQL();
inline int Setup_PostgreSQL(); inline int Setup_PostgreSQL();
protected: protected:
std::shared_ptr<Poco::Data::SessionPool> Pool_; std::unique_ptr<Poco::Data::SessionPool> Pool_;
Poco::Data::SQLite::Connector SQLiteConn_; Poco::Data::SQLite::Connector SQLiteConn_;
Poco::Data::PostgreSQL::Connector PostgresConn_; Poco::Data::PostgreSQL::Connector PostgresConn_;
Poco::Data::MySQL::Connector MySQLConn_; Poco::Data::MySQL::Connector MySQLConn_;
@@ -64,30 +66,21 @@ namespace OpenWifi {
}; };
#ifdef SMALL_BUILD #ifdef SMALL_BUILD
int Service::Setup_MySQL() { int Service::Setup_MySQL() { Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); return 0; }
Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); int Service::Setup_PostgreSQL() { Daemon()->exit(Poco::Util::Application::EXIT_CONFIG); return 0; }
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() + "/" + auto DBName = MicroServiceDataDirectory() + "/" + MicroServiceConfigGetString("storage.type.sqlite.db","");
MicroServiceConfigGetString("storage.type.sqlite.db", "");
int NumSessions = (int) MicroServiceConfigGetInt("storage.type.sqlite.maxsessions", 64); int NumSessions = (int) MicroServiceConfigGetInt("storage.type.sqlite.maxsessions", 64);
int IdleTime = (int) MicroServiceConfigGetInt("storage.type.sqlite.idletime", 60); 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 // Pool_ = std::make_unique<Poco::Data::SessionPool>(new Poco::Data::SessionPool(SQLiteConn_.name(), DBName, 8,
// Poco::Data::SessionPool(SQLiteConn_.name(), DBName, 8, // (int)NumSessions, (int)IdleTime));
// (int)NumSessions, Pool_ = std::make_unique<Poco::Data::SessionPool>(SQLiteConn_.name(), DBName, 8,
// (int)IdleTime));
Pool_ = std::make_shared<Poco::Data::SessionPool>(SQLiteConn_.name(), DBName, 8,
(int)NumSessions, (int)IdleTime); (int)NumSessions, (int)IdleTime);
return 0; return 0;
} }
@@ -103,13 +96,16 @@ namespace OpenWifi {
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 = "host=" + Host + ";user=" + Username + ";password=" + Password + std::string ConnectionStr =
";db=" + Database + ";port=" + Port + "host=" + Host +
";user=" + Username +
";password=" + Password +
";db=" + Database +
";port=" + Port +
";compress=true;auto-reconnect=true"; ";compress=true;auto-reconnect=true";
Poco::Data::MySQL::Connector::registerConnector(); Poco::Data::MySQL::Connector::registerConnector();
Pool_ = std::make_shared<Poco::Data::SessionPool>(MySQLConn_.name(), ConnectionStr, 8, Pool_ = std::make_unique<Poco::Data::SessionPool>(MySQLConn_.name(), ConnectionStr, 8, NumSessions, IdleTime);
NumSessions, IdleTime);
return 0; return 0;
} }
@@ -124,19 +120,21 @@ namespace OpenWifi {
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 = auto ConnectionTimeout = MicroServiceConfigGetString("storage.type.postgresql.connectiontimeout", "");
MicroServiceConfigGetString("storage.type.postgresql.connectiontimeout", "");
std::string ConnectionStr = "host=" + Host + " user=" + Username + " password=" + Password + std::string ConnectionStr =
" dbname=" + Database + " port=" + Port + "host=" + Host +
" user=" + Username +
" password=" + Password +
" dbname=" + Database +
" port=" + Port +
" connect_timeout=" + ConnectionTimeout; " connect_timeout=" + ConnectionTimeout;
Poco::Data::PostgreSQL::Connector::registerConnector(); Poco::Data::PostgreSQL::Connector::registerConnector();
Pool_ = std::make_shared<Poco::Data::SessionPool>(PostgresConn_.name(), ConnectionStr, 8, Pool_ = std::make_unique<Poco::Data::SessionPool>(PostgresConn_.name(), ConnectionStr, 8, NumSessions, IdleTime);
NumSessions, IdleTime);
return 0; return 0;
} }
#endif #endif
} // namespace OpenWifi }

View File

@@ -6,29 +6,36 @@
#include "framework/SubSystemServer.h" #include "framework/SubSystemServer.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/Net/SSLManager.h" #include "Poco/Net/SSLManager.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "framework/MicroServiceFuncs.h" #include "framework/MicroServiceFuncs.h"
namespace OpenWifi { namespace OpenWifi {
PropertiesFileServerEntry::PropertiesFileServerEntry( PropertiesFileServerEntry::PropertiesFileServerEntry(std::string Address, uint32_t port, std::string Key_file,
std::string Address, uint32_t port, std::string Key_file, std::string Cert_file, std::string Cert_file, std::string RootCa, std::string Issuer,
std::string RootCa, std::string Issuer, std::string ClientCas, std::string Cas, std::string ClientCas, std::string Cas,
std::string Key_file_password, std::string Name, Poco::Net::Context::VerificationMode M, std::string Key_file_password, std::string Name,
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 [[nodiscard]] Poco::Net::SecureServerSocket PropertiesFileServerEntry::CreateSecureSocket(Poco::Logger &L) const {
PropertiesFileServerEntry::CreateSecureSocket(Poco::Logger &L) const {
Poco::Net::Context::Params P; Poco::Net::Context::Params P;
P.verificationMode = level_; P.verificationMode = level_;
@@ -37,14 +44,11 @@ namespace OpenWifi {
P.cipherList = "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"; P.cipherList = "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH";
P.dhUse2048Bits = true; P.dhUse2048Bits = true;
P.caLocation = cas_; P.caLocation = cas_;
// P.securityLevel =
auto Context = Poco::AutoPtr<Poco::Net::Context>( auto Context = Poco::AutoPtr<Poco::Net::Context>(new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P));
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>( auto PassphraseHandler = Poco::SharedPtr<MyPrivateKeyPassphraseHandler>( new MyPrivateKeyPassphraseHandler(key_file_password_,L));
new MyPrivateKeyPassphraseHandler(key_file_password_, L));
Poco::Net::SSLManager::instance().initializeServer(PassphraseHandler, nullptr,Context); Poco::Net::SSLManager::instance().initializeServer(PassphraseHandler, nullptr,Context);
} }
@@ -54,6 +58,7 @@ namespace OpenWifi {
Context->useCertificate(Cert); Context->useCertificate(Cert);
Context->addChainCertificate(Root); Context->addChainCertificate(Root);
Context->addCertificateAuthority(Root); Context->addCertificateAuthority(Root);
if (level_ == Poco::Net::Context::VERIFY_STRICT) { if (level_ == Poco::Net::Context::VERIFY_STRICT) {
@@ -76,18 +81,18 @@ namespace OpenWifi {
L.fatal(fmt::format("Wrong Certificate({}) for Key({})", cert_file_, key_file_)); L.fatal(fmt::format("Wrong Certificate({}) for Key({})", cert_file_, key_file_));
} }
SSL_CTX_set_verify(SSLCtx, level_==Poco::Net::Context::VERIFY_NONE ? SSL_VERIFY_NONE : SSL_VERIFY_PEER, nullptr); SSL_CTX_set_verify(SSLCtx, SSL_VERIFY_PEER, nullptr);
if (level_ == Poco::Net::Context::VERIFY_STRICT) { if (level_ == Poco::Net::Context::VERIFY_STRICT) {
SSL_CTX_set_client_CA_list(SSLCtx, SSL_load_client_CA_file(client_cas_.c_str())); SSL_CTX_set_client_CA_list(SSLCtx, SSL_load_client_CA_file(client_cas_.c_str()));
SSL_CTX_enable_ct(SSLCtx, SSL_CT_VALIDATION_STRICT);
} }
SSL_CTX_enable_ct(SSLCtx, SSL_CT_VALIDATION_STRICT);
SSL_CTX_dane_enable(SSLCtx); SSL_CTX_dane_enable(SSLCtx);
Context->enableSessionCache(); Context->enableSessionCache();
Context->setSessionCacheSize(0); Context->setSessionCacheSize(0);
Context->setSessionTimeout(60); Context->setSessionTimeout(60);
Context->enableExtendedCertificateVerification( level_!= Poco::Net::Context::VERIFY_NONE ); Context->enableExtendedCertificateVerification(true);
Context->disableStatelessSessionResumption(); Context->disableStatelessSessionResumption();
} }
@@ -106,8 +111,7 @@ namespace OpenWifi {
} }
} }
[[nodiscard]] Poco::Net::ServerSocket [[nodiscard]] Poco::Net::ServerSocket PropertiesFileServerEntry::CreateSocket([[maybe_unused]] Poco::Logger &L) const {
PropertiesFileServerEntry::CreateSocket([[maybe_unused]] Poco::Logger &L) const {
Poco::Net::Context::Params P; Poco::Net::Context::Params P;
if (address_ == "*") { if (address_ == "*") {
@@ -123,24 +127,19 @@ namespace OpenWifi {
} }
} }
void PropertiesFileServerEntry::LogCertInfo(Poco::Logger &L, void PropertiesFileServerEntry::LogCertInfo(Poco::Logger &L, const Poco::Crypto::X509Certificate &C) const {
const Poco::Crypto::X509Certificate &C) const { L.information("=============================================================================================");
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( L.information(fmt::format("> State/Prov: {}",
fmt::format("> State/Prov: {}",
C.issuerName(Poco::Crypto::X509Certificate::NID_STATE_OR_PROVINCE))); C.issuerName(Poco::Crypto::X509Certificate::NID_STATE_OR_PROVINCE)));
L.information( L.information(fmt::format("> Org name: {}",
fmt::format("> Org name: {}",
C.issuerName(Poco::Crypto::X509Certificate::NID_ORGANIZATION_NAME))); C.issuerName(Poco::Crypto::X509Certificate::NID_ORGANIZATION_NAME)));
L.information( L.information(
fmt::format("> Org unit: {}", fmt::format("> Org unit: {}",
@@ -150,11 +149,9 @@ 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: {}",
@@ -175,66 +172,52 @@ 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 = auto From = Poco::DateTimeFormatter::format(C.validFrom(), Poco::DateTimeFormat::HTTP_FORMAT);
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) {
@@ -247,31 +230,28 @@ 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), LoggerPrefix_(LoggingPrefix), SubSystemConfigPrefix_(SubSystemConfigPrefix) { Name_(Name),
LoggerPrefix_(LoggingPrefix),
SubSystemConfigPrefix_(SubSystemConfigPrefix) {
} }
void SubSystemServer::initialize([[maybe_unused]] Poco::Util::Application &self) { void SubSystemServer::initialize([[maybe_unused]] Poco::Util::Application &self) {
@@ -280,12 +260,9 @@ namespace OpenWifi {
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( Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel()));
LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::root().getLevel()));
else else
Logger_ = std::make_unique<LoggerWrapper>( Logger_ = std::make_unique<LoggerWrapper>(Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(), Poco::Logger::parseLevel(NewLevel)));
Poco::Logger::create(LoggerPrefix_, Poco::Logger::root().getChannel(),
Poco::Logger::parseLevel(NewLevel)));
ConfigServersList_.clear(); ConfigServersList_.clear();
while (good) { while (good) {
@@ -320,11 +297,14 @@ namespace OpenWifi {
} else if (L == "once") } else if (L == "once")
M = Poco::Net::Context::VERIFY_ONCE; M = Poco::Net::Context::VERIFY_ONCE;
PropertiesFileServerEntry entry( PropertiesFileServerEntry entry(MicroServiceConfigGetString(address, ""),
MicroServiceConfigGetString(address, ""), MicroServiceConfigGetInt(port, 0), MicroServiceConfigGetInt(port, 0),
MicroServiceConfigPath(key, ""), MicroServiceConfigPath(cert, ""), MicroServiceConfigPath(key, ""),
MicroServiceConfigPath(rootca, ""), MicroServiceConfigPath(issuer, ""), MicroServiceConfigPath(cert, ""),
MicroServiceConfigPath(clientcas, ""), MicroServiceConfigPath(cas, ""), MicroServiceConfigPath(rootca, ""),
MicroServiceConfigPath(issuer, ""),
MicroServiceConfigPath(clientcas, ""),
MicroServiceConfigPath(cas, ""),
MicroServiceConfigGetString(key_password, ""), MicroServiceConfigGetString(key_password, ""),
MicroServiceConfigGetString(name, ""), M, MicroServiceConfigGetString(name, ""), M,
(int)MicroServiceConfigGetInt(backlog, 64)); (int)MicroServiceConfigGetInt(backlog, 64));
@@ -334,4 +314,7 @@ namespace OpenWifi {
} }
} }
} // namespace OpenWifi } // namespace OpenWifi

View File

@@ -4,27 +4,29 @@
#pragma once #pragma once
#include <mutex>
#include <string> #include <string>
#include <mutex>
#include "Poco/Net/Context.h"
#include "Poco/Net/PrivateKeyPassphraseHandler.h"
#include "Poco/Net/SecureServerSocket.h"
#include "Poco/Util/Application.h" #include "Poco/Util/Application.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/SecureServerSocket.h"
#include "Poco/Net/PrivateKeyPassphraseHandler.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), Password_(Password), Logger_(Logger) {} PrivateKeyPassphraseHandler(true),
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_;
@@ -78,17 +80,17 @@ namespace OpenWifi {
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) { inline const PropertiesFileServerEntry & Host(uint64_t index) { return ConfigServersList_[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) {
@@ -101,7 +103,9 @@ namespace OpenWifi {
struct LoggerWrapper { struct LoggerWrapper {
Poco::Logger & L_; Poco::Logger & L_;
LoggerWrapper(Poco::Logger &L) : L_(L) {} LoggerWrapper(Poco::Logger &L) :
L_(L) {
}
}; };
protected: protected:

View File

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

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