Compare commits

..

3 Commits

Author SHA1 Message Date
stephb9959
17fe350d8c https://telecominfraproject.atlassian.net/browse/WIFI-10846
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2022-09-30 08:02:11 -07:00
stephb9959
73e4f0df94 https://telecominfraproject.atlassian.net/browse/WIFI-10846
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2022-09-29 22:53:48 -07:00
stephb9959
702d863e6b https://telecominfraproject.atlassian.net/browse/WIFI-10846
Signed-off-by: stephb9959 <stephane.bourque@gmail.com>
2022-09-29 22:46:24 -07:00
182 changed files with 8802 additions and 8302 deletions

View File

@@ -79,56 +79,12 @@ add_executable( owgw
src/framework/KafkaTopics.h
src/framework/MicroService.h
src/framework/OpenWifiTypes.h
src/framework/MicroServiceErrorHandler.h
src/framework/orm.h
src/framework/StorageClass.h
src/framework/MicroServiceErrorHandler.h
src/framework/UI_WebSocketClientServer.cpp
src/framework/UI_WebSocketClientServer.h
src/framework/UI_WebSocketClientNotifications.cpp
src/framework/UI_WebSocketClientNotifications.h
src/framework/utils.h
src/framework/utils.cpp
src/framework/AppServiceRegistry.h
src/framework/SubSystemServer.cpp
src/framework/SubSystemServer.h
src/framework/RESTAPI_utils.h
src/framework/AuthClient.cpp
src/framework/AuthClient.h
src/framework/MicroServiceNames.h
src/framework/MicroServiceFuncs.h
src/framework/OpenAPIRequests.cpp
src/framework/OpenAPIRequests.h
src/framework/MicroServiceFuncs.cpp
src/framework/ALBserver.cpp
src/framework/ALBserver.h
src/framework/KafkaManager.cpp
src/framework/KafkaManager.h
src/framework/RESTAPI_RateLimiter.h
src/framework/WebSocketLogger.h
src/framework/RESTAPI_GenericServerAccounting.h
src/framework/CIDR.h
src/framework/RESTAPI_Handler.cpp
src/framework/RESTAPI_Handler.h
src/framework/RESTAPI_ExtServer.h
src/framework/RESTAPI_ExtServer.cpp
src/framework/RESTAPI_IntServer.cpp
src/framework/RESTAPI_IntServer.h
src/framework/RESTAPI_SystemCommand.h
src/framework/RESTAPI_WebSocketServer.h
src/framework/EventBusManager.cpp
src/framework/EventBusManager.h
src/framework/RESTAPI_PartHandler.h
src/framework/MicroService.cpp
src/framework/MicroServiceExtra.h
src/RESTObjects/RESTAPI_SecurityObjects.h src/RESTObjects/RESTAPI_SecurityObjects.cpp
src/RESTObjects/RESTAPI_ProvObjects.cpp src/RESTObjects/RESTAPI_ProvObjects.h
src/RESTObjects/RESTAPI_GWobjects.h src/RESTObjects/RESTAPI_GWobjects.cpp
src/RESTObjects/RESTAPI_FMSObjects.h src/RESTObjects/RESTAPI_FMSObjects.cpp
src/RESTObjects/RESTAPI_CertObjects.cpp src/RESTObjects/RESTAPI_CertObjects.h
src/RESTObjects/RESTAPI_OWLSobjects.cpp src/RESTObjects/RESTAPI_OWLSobjects.h
src/RESTObjects/RESTAPI_ProvObjects.cpp src/RESTObjects/RESTAPI_ProvObjects.h
src/RESTObjects/RESTAPI_AnalyticsObjects.cpp src/RESTObjects/RESTAPI_AnalyticsObjects.h
src/RESTObjects/RESTAPI_SubObjects.cpp src/RESTObjects/RESTAPI_SubObjects.h
src/RESTAPI/RESTAPI_devices_handler.cpp src/RESTAPI/RESTAPI_devices_handler.h
src/RESTAPI/RESTAPI_device_handler.cpp src/RESTAPI/RESTAPI_device_handler.h
src/RESTAPI/RESTAPI_device_commandHandler.cpp src/RESTAPI/RESTAPI_device_commandHandler.h
@@ -152,6 +108,7 @@ add_executable( owgw
src/Daemon.cpp src/Daemon.h
src/AP_WS_Server.cpp src/AP_WS_Server.h
src/StorageService.cpp src/StorageService.h
src/DeviceRegistry.cpp src/DeviceRegistry.h
src/CommandManager.cpp src/CommandManager.h
src/CentralConfig.cpp src/CentralConfig.h
src/FileUploader.cpp src/FileUploader.h
@@ -170,36 +127,12 @@ add_executable( owgw
src/rttys/RTTYS_ClientConnection.cpp
src/rttys/RTTYS_ClientConnection.h
src/rttys/RTTYS_WebServer.cpp
src/rttys/RTTYS_WebServer.h src/RESTAPI/RESTAPI_device_helper.h
src/SDKcalls.cpp
src/SDKcalls.h
src/StateUtils.cpp src/StateUtils.h
src/AP_WS_ReactorPool.h
src/AP_WS_Connection.h
src/AP_WS_Connection.cpp
src/TelemetryClient.h src/TelemetryClient.cpp
src/RESTAPI/RESTAPI_iptocountry_handler.cpp src/RESTAPI/RESTAPI_iptocountry_handler.h
src/framework/ow_constants.h
src/GwWebSocketClient.cpp src/GwWebSocketClient.h
src/RADIUS_proxy_server.cpp src/RADIUS_proxy_server.h
src/RESTAPI/RESTAPI_radiusProxyConfig_handler.cpp src/RESTAPI/RESTAPI_radiusProxyConfig_handler.h
src/ParseWifiScan.h
src/RADIUS_helpers.h
src/VenueBroadcaster.h
src/sdks/sdk_prov.h
src/rttys/RTTYS_WebServer.h src/RESTAPI/RESTAPI_device_helper.h src/SDKcalls.cpp src/SDKcalls.h src/StateUtils.cpp src/StateUtils.h src/AP_WS_ReactorPool.h src/AP_WS_Connection.h src/AP_WS_Connection.cpp src/TelemetryClient.h src/TelemetryClient.cpp src/RESTAPI/RESTAPI_iptocountry_handler.cpp src/RESTAPI/RESTAPI_iptocountry_handler.h src/framework/ow_constants.h src/GwWebSocketClient.cpp src/GwWebSocketClient.h src/framework/WebSocketClientNotifications.h src/RADIUS_proxy_server.cpp src/RADIUS_proxy_server.h src/RESTAPI/RESTAPI_radiusProxyConfig_handler.cpp src/RESTAPI/RESTAPI_radiusProxyConfig_handler.h src/ParseWifiScan.h src/RADIUS_helpers.h src/VenueBroadcaster.h src/sdks/sdk_prov.h
src/AP_WS_Process_connect.cpp
src/AP_WS_Process_state.cpp
src/AP_WS_Process_healthcheck.cpp
src/AP_WS_Process_log.cpp
src/AP_WS_Process_crashlog.cpp
src/AP_WS_Process_ping.cpp
src/AP_WS_Process_cfgpending.cpp
src/AP_WS_Process_recovery.cpp
src/AP_WS_Process_deviceupdate.cpp
src/AP_WS_Process_telemetry.cpp
src/AP_WS_Process_venuebroadcast.cpp
src/RADSEC_server.h
src/UI_GW_WebSocketNotifications.cpp src/UI_GW_WebSocketNotifications.h)
src/AP_WS_Process_crashlog.cpp src/AP_WS_Process_ping.cpp src/AP_WS_Process_cfgpending.cpp src/AP_WS_Process_recovery.cpp src/AP_WS_Process_deviceupdate.cpp src/AP_WS_Process_telemetry.cpp src/AP_WS_Process_venuebroadcast.cpp src/RADSECserver.h src/framework/MicroServiceErrorHandler.h)
if(NOT SMALL_BUILD)

View File

@@ -1,15 +1,16 @@
ARG DEBIAN_VERSION=11.5-slim
ARG ALPINE_VERSION=3.16.2
ARG POCO_VERSION=poco-tip-v1
ARG FMTLIB_VERSION=9.0.0
ARG CPPKAFKA_VERSION=tip-v1
ARG JSON_VALIDATOR_VERSION=2.1.0
FROM debian:$DEBIAN_VERSION AS build-base
FROM alpine:$ALPINE_VERSION AS build-base
RUN apt-get update && apt-get install --no-install-recommends -y \
RUN apk add --update --no-cache \
make cmake g++ git \
libpq-dev libmariadb-dev libmariadbclient-dev-compat \
librdkafka-dev libboost-all-dev libssl-dev \
zlib1g-dev nlohmann-json3-dev ca-certificates libfmt-dev
unixodbc-dev postgresql-dev mariadb-dev \
librdkafka-dev boost-dev openssl-dev \
zlib-dev nlohmann-json ca-certificates
FROM build-base AS poco-build
@@ -25,6 +26,20 @@ RUN cmake ..
RUN cmake --build . --config Release -j8
RUN cmake --build . --target install
FROM build-base AS fmtlib-build
ARG FMTLIB_VERSION
ADD https://api.github.com/repos/fmtlib/fmt/git/refs/tags/${FMTLIB_VERSION} version.json
RUN git clone https://github.com/fmtlib/fmt --branch ${FMTLIB_VERSION} /fmtlib
WORKDIR /fmtlib
RUN mkdir cmake-build
WORKDIR cmake-build
RUN cmake ..
RUN make
RUN make install
FROM build-base AS cppkafka-build
ARG CPPKAFKA_VERSION
@@ -66,6 +81,8 @@ COPY --from=cppkafka-build /usr/local/include /usr/local/include
COPY --from=cppkafka-build /usr/local/lib /usr/local/lib
COPY --from=json-schema-validator-build /usr/local/include /usr/local/include
COPY --from=json-schema-validator-build /usr/local/lib /usr/local/lib
COPY --from=fmtlib-build /usr/local/include /usr/local/include
COPY --from=fmtlib-build /usr/local/lib /usr/local/lib
WORKDIR /owgw
RUN mkdir cmake-build
@@ -73,21 +90,21 @@ WORKDIR /owgw/cmake-build
RUN cmake ..
RUN cmake --build . --config Release -j8
FROM debian:$DEBIAN_VERSION
FROM alpine:$ALPINE_VERSION
ENV OWGW_USER=owgw \
OWGW_ROOT=/owgw-data \
OWGW_CONFIG=/owgw-data
RUN useradd "$OWGW_USER"
RUN addgroup -S "$OWGW_USER" && \
adduser -S -G "$OWGW_USER" "$OWGW_USER"
RUN mkdir /openwifi
RUN mkdir -p "$OWGW_ROOT" "$OWGW_CONFIG" && \
chown "$OWGW_USER": "$OWGW_ROOT" "$OWGW_CONFIG"
RUN apt-get update && apt-get install --no-install-recommends -y \
librdkafka++1 gosu gettext ca-certificates bash jq curl wget \
libmariadb-dev-compat libpq5 unixodbc postgresql-client libfmt7 sqlite3
RUN apk add --update --no-cache librdkafka su-exec gettext ca-certificates bash jq curl \
mariadb-connector-c libpq unixodbc postgresql-client
COPY readiness_check /readiness_check
COPY test_scripts/curl/cli /cli
@@ -97,14 +114,12 @@ COPY docker-entrypoint.sh /
COPY wait-for-postgres.sh /
COPY rtty_ui /dist/rtty_ui
RUN wget https://raw.githubusercontent.com/Telecominfraproject/wlan-cloud-ucentral-deploy/main/docker-compose/certs/restapi-ca.pem \
-O /usr/local/share/ca-certificates/restapi-ca-selfsigned.crt
-O /usr/local/share/ca-certificates/restapi-ca-selfsigned.pem
COPY --from=owgw-build /owgw/cmake-build/owgw /openwifi/owgw
COPY --from=cppkafka-build /cppkafka/cmake-build/src/lib /usr/local/lib/
COPY --from=poco-build /poco/cmake-build/lib /usr/local/lib
RUN ldconfig
EXPOSE 15002 16002 16003 17002 16102
ENTRYPOINT ["/docker-entrypoint.sh"]

View File

@@ -423,6 +423,44 @@ The device should answer:
- 1 : device cannot flash LEDs because it does not have any.
- 2 : device rejects the request. `text` should include information as to why.
#### Controller sends a device specific command
Controller sends this command specific to this device. The command is proprietary and must be agreed upon by the device
and the controller.
```json
{ "jsonrpc" : "2.0" ,
"method" : "perform" ,
"params" : {
"serial" : <serial number> ,
"when" : Optional - <UTC time when to perform this command, 0 mean immediate, this is a suggestion>,
"command" : <this is device specific and is TEXT only>,
"payload" : <JSON Document: containing additional information about the command>
},
"id" : <some number>
}
```
The device should answer:
```json
{ "jsonrpc" : "2.0" ,
"result" : {
"serial" : <serial number> ,
"status" : {
"error" : 0 or an error number,
"text" : <description of the error or success>,
"when" : <in UTC time in seconds>,
"resultCode" : <0 or an appropriate error code>,
"resultText" : <any text resulting from the command. This is propietary to each command>
}
},
"id" : <same number>
}
```
##### The device answer
The device should answer with teh above message. The `error` value should be interpreted the following way:
- 0 : the command was performed as requested and the reults of the command is available in the `resultCode` and `resultText` parameters.
- 1 : the command will be performed in the future and `when` shows that time. The `resultCode` and `resultText` dod not contain anything relevant.
- 2 : the command cannot be performed as indicated. `resultCode` and `resultText` may contain some indication as to why.
#### Controller wants the device to perform a trace
Controller sends this command when it needs the device to perform a trace (i.e. tcpdump).
```json

View File

@@ -119,61 +119,54 @@ cmake ..
make
```
### macOS Build
The following instructions have proven to work on macOS Big Sur. You need to install [Homebrew](https://brew.sh/). You must also have installed [XCode for OS X](https://www.freecodecamp.org/news/how-to-download-and-install-xcode/).
### OSX Build
The following instructions have proven to work on OSX Big Sur. You need to install [Homebrew](https://brew.sh/). You must also have installed [XCode for OS X](https://www.freecodecamp.org/news/how-to-download-and-install-xcode/).
```
brew install openssl \
cmake \
libpq \
mysql-client \
apr \
apr-util \
boost \
yaml-cpp \
postgresql \
librdkafka \
nlohmann-json \
fmt
brew install openssl
brew install cmake
brew install libpq
brew install mysql-client
brew install apr
brew install apr-util
brew install boost
brew install yaml-cpp
brew install postgresql
brew install librdkafka
brew install nlohmann-json
git clone https://github.com/AriliaWireless/poco --branch poco-tip-v1
pushd poco
cd poco
mkdir cmake-build
push cmake-build
cmake -DOPENSSL_ROOT_DIR=</path/to/openssl> -DENABLE_NETSSL=1 -DENABLE_JWT=1 -DENABLE_CRYPTO=1 ..
cmake --build . --config Release
sudo cmake --build . --target install
popd
popd
git clone https://github.com/AriliaWireless/cppkafka --branch tip-v1
pushd cppkafka
mkdir cmake-build
pushd cmake-build
cd cmake-build
cmake ..
cmake --build . --config Release
sudo cmake --build . --target install
popd
popd
git clone https://github.com/pboettch/json-schema-validator.git --branch 2.1.0
pushd json-schema-validator
git clone https://github.com/AriliaWireless/cppkafka --branch tip-v1
cd cppkafka
mkdir cmake-build
pushd cmake-build
cd cmake-build
cmake ..
cmake --build . --config Release
sudo cmake --build . --target install
cd ~
git clone https://github.com/pboettch/json-schema-validator.git --branch 2.1.0
cd json-schema-validator
mkdir cmake-build
cd cmake-build
cmake ..
make -j
sudo make install
popd
popd
cd ~
git clone https://github.com/Telecominfraproject/wlan-cloud-ucentralgw
pushd wlan-cloud-ucentralgw
cd wlan-cloud-ucentralgw
mkdir cmake-build
pushd cmake-build
cd cmake-build
cmake ..
make -j
popd
popd
```
### Raspberry

2
build
View File

@@ -1 +1 @@
42
128

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,4 @@
#include <librdkafka/rdkafka.h>
#if RD_KAFKA_VERSION >= 0x00090400
int main() { }
#endif

26
config.yaml Normal file
View File

@@ -0,0 +1,26 @@
tip:
port: 6051
server: ssc.wlan.local
username: support@example.com
password: support
certificates:
keyfile: keyfile.pem
certfile: certfile.pem
password: mypassword
ucentral:
port: 1991
listeners: 100
logger:
size: 10
days: 31
ui:
port: 9771
username: support@example.com
password: support

View File

@@ -1,4 +1,4 @@
#!/bin/bash
#!/bin/sh
set -e
if [ "$SELFSIGNED_CERTS" = 'true' ]; then
@@ -38,12 +38,7 @@ if [[ "$TEMPLATE_CONFIG" = 'true' ]]; then
SYSTEM_URI_PRIVATE=${SYSTEM_URI_PRIVATE:-"https://localhost:17002"} \
SYSTEM_URI_PUBLIC=${SYSTEM_URI_PUBLIC:-"https://localhost:16002"} \
SYSTEM_URI_UI=${SYSTEM_URI_UI:-"http://localhost"} \
SECURITY_RESTAPI_DISABLE=${SECURITY_RESTAPI_DISABLE:-"false"} \
SIMULATORID=${SIMULATORID:-""} \
IPTOCOUNTRY_PROVIDER=${IPTOCOUNTRY_PROVIDER:-"ipinfo"} \
IPTOCOUNTRY_IPINFO_TOKEN=${IPTOCOUNTRY_IPINFO_TOKEN:-""} \
IPTOCOUNTRY_IPDATA_APIKEY=${IPTOCOUNTRY_IPDATA_APIKEY:-""} \
AUTOPROVISIONING_PROCESS=${AUTOPROVISIONING_PROCESS:-"prov,default"} \
RTTY_INTERNAL=${RTTY_INTERNAL:-"true"} \
RTTY_ENABLED=${RTTY_ENABLED:-"true"} \
RTTY_SERVER=${RTTY_SERVER:-"localhost"} \
@@ -52,10 +47,6 @@ if [[ "$TEMPLATE_CONFIG" = 'true' ]]; then
RTTY_TIMEOUT=${RTTY_TIMEOUT:-"60"} \
RTTY_VIEWPORT=${RTTY_VIEWPORT:-"5913"} \
RTTY_ASSETS=${RTTY_ASSETS:-"\$OWGW_ROOT/rtty_ui"} \
RADIUS_PROXY_ENABLE=${RADIUS_PROXY_ENABLE:-"false"} \
RADIUS_PROXY_ACCOUNTING_PORT=${RADIUS_PROXY_ACCOUNTING_PORT:-"1813"} \
RADIUS_PROXY_AUTHENTICATION_PORT=${RADIUS_PROXY_AUTHENTICATION_PORT:-"1812"} \
RADIUS_PROXY_COA_PORT=${RADIUS_PROXY_COA_PORT:-"3799"} \
KAFKA_ENABLE=${KAFKA_ENABLE:-"true"} \
KAFKA_BROKERLIST=${KAFKA_BROKERLIST:-"localhost:9092"} \
KAFKA_SSL_CA_LOCATION=${KAFKA_SSL_CA_LOCATION:-""} \
@@ -95,7 +86,7 @@ if [ "$1" = '/openwifi/owgw' -a "$(id -u)" = '0' ]; then
if [ "$RUN_CHOWN" = 'true' ]; then
chown -R "$OWGW_USER": "$OWGW_ROOT" "$OWGW_CONFIG"
fi
exec gosu "$OWGW_USER" "$@"
exec su-exec "$OWGW_USER" "$@"
fi
exec "$@"

14
docker_build.sh Executable file
View File

@@ -0,0 +1,14 @@
USERNAME=arilia
HUBNAME=tip-tip-wlan-cloud-ucentral.jfrog.io
IMAGE_NAME=ucentralgw
echo "Removing docker images before build..."
docker rmi -f $(docker images -a -q)
echo "Building $IMAGE_NAME image..."
docker build --no-cache --tag $IMAGE_NAME .
IMAGE_ID=`docker images -q $IMAGE_NAME`
docker login --username=$USERNAME $HUBNAME
docker tag $IMAGE_ID $HUBNAME/$IMAGE_NAME:latest
echo "Updating $HUBNAME with the latest $IMAGE_NAME image..."
docker push $HUBNAME/$IMAGE_NAME
docker logout $HUBNAME

5
docker_clean.sh Normal file
View File

@@ -0,0 +1,5 @@
#!/bin/sh
# Removes all local images. This is dangerous but good when debugging
docker rmi -f $(docker images -a -q)

43
docker_run.sh Normal file
View File

@@ -0,0 +1,43 @@
#!/bin/sh
HUBNAME=tip-tip-wlan-cloud-ucentral.jfrog.io
IMAGE_NAME=ucentralgw
DOCKER_NAME=$HUBNAME/$IMAGE_NAME:master
CONTAINER_NAME=ucentralgw
#stop previously running images
docker container stop $CONTAINER_NAME
docker container rm $CONTAINER_NAME --force
if [[ ! -d logs ]]
then
mkdir logs
fi
if [[ ! -d uploads ]]
then
mkdir uploads
fi
if [[ ! -d certs ]]
then
echo "certs directory does not exist. Please create and add the proper certificates."
exit 1
fi
if [[ ! -f owgw.properties ]]
then
echo "Configuration file ucentral.properties is missing in the current directory"
exit 2
fi
docker run -d -p 15002:15002 \
-p 16001:16001 \
-p 16003:16003 \
--init \
--volume="$PWD:/ucentral-data" \
-e UCENTRALGW_ROOT="/ucentral-data" \
-e UCENTRALGW_CONFIG="/ucentral-data" \
--name="ucentralgw" $DOCKER_NAME

View File

@@ -79,8 +79,7 @@ The following table lists the configurable parameters of the chart and their def
| persistence.size | string | Defines PV size | `'10Gi'` |
| public_env_variables | hash | Defines list of environment variables to be passed to the Gateway | |
| configProperties | hash | Configuration properties that should be passed to the application in `owgw.properties`. May be passed by key in set (i.e. `configProperties."rtty\.token"`) | |
| existingCertsSecret | string | Existing Kubernetes secret containing all required certificates and private keys for microservice operation. If set, certificates from `certs` key are ignored | `""` |
| certs | hash | Defines files (keys and certificates) that should be passed to the Gateway (PEM format is adviced to be used) (see `volumes.owgw` on where it is mounted). If `existingCertsSecret` is set, certificates passed this way will not be used. | |
| certs | hash | Defines files (keys and certificates) that should be passed to the Gateway (PEM format is adviced to be used) (see `volumes.owgw` on where it is mounted) | |
| certsCAs | hash | Defines files with CAs that should be passed to the Gateway (see `volumes.owgw` on where it is mounted) | |

View File

@@ -109,11 +109,6 @@ spec:
containerPort: {{ $portValue.targetPort }}
protocol: {{ $portValue.protocol }}
{{- end }}
{{- range $port, $portValue := .Values.services.radius.ports }}
- name: {{ $port }}
containerPort: {{ $portValue.targetPort }}
protocol: {{ $portValue.protocol }}
{{- end }}
volumeMounts:
{{- range .Values.volumes.owgw }}

View File

@@ -9,7 +9,7 @@ fullnameOverride: ""
images:
owgw:
repository: tip-tip-wlan-cloud-ucentral.jfrog.io/owgw
tag: v2.7.2
tag: master
pullPolicy: Always
# regcred:
# registry: tip-tip-wlan-cloud-ucentral.jfrog.io
@@ -46,21 +46,6 @@ services:
rttys-view:
servicePort: 5913
targetPort: 5913
radius:
type: ClusterIP
ports:
acc:
servicePort: 1813
targetPort: 1813
protocol: UDP
auth:
servicePort: 1812
targetPort: 1812
protocol: UDP
coa:
servicePort: 3799
targetPort: 3799
protocol: UDP
checks:
owgw:
@@ -112,7 +97,7 @@ volumes:
mountPath: /owgw-data/certs
volumeDefinition: |
secret:
secretName: {{ if .Values.existingCertsSecret }}{{ .Values.existingCertsSecret }}{{ else }}{{ include "owgw.fullname" . }}-certs{{ end }}
secretName: {{ include "owgw.fullname" . }}-certs
- name: certs-cas
mountPath: /owgw-data/certs/cas
volumeDefinition: |
@@ -138,7 +123,7 @@ resources: {}
# memory: 128Mi
securityContext:
fsGroup: 1000
fsGroup: 101
# Usage of unsafe sysctls requires multiple things:
# - allow these unsafe sysctls on kubelet level (by adding --allowed-unsafe-sysctls flag)
# - enabling addition of PodSecurityContext setting podSecurityPolicy.enabled to "true" below
@@ -246,11 +231,6 @@ configProperties:
rtty.timeout: 60
rtty.viewport: 5913
rtty.assets: $OWGW_ROOT/rtty_ui
# RADIUS proxy
radius.proxy.enable: "true"
radius.proxy.accounting.port: 1813
radius.proxy.authentication.port: 1812
radius.proxy.coa.port: 3799
# ALB
alb.enable: "true"
alb.port: 16102
@@ -291,7 +271,6 @@ configProperties:
openwifi.system.debug: "true"
openwifi.system.uri.private: https://localhost:17002
openwifi.system.uri.public: https://localhost:16002
openwifi.system.uri.ui: https://localhost
openwifi.system.commandchannel: /tmp/app_owgw
# Logging
logging.type: console
@@ -331,22 +310,166 @@ configProperties:
storage.type.mysql.username: stephb
storage.type.mysql.password: snoopy99
# NOTE: List of required certificates may be found in "certs" key. Alternative way to pass required certificates is to create external secret with all required certificates and set secret name in "existingCertsSecret" key. Details may be found in https://github.com/Telecominfraproject/wlan-cloud-ucentral-deploy/tree/main/chart#tldr
existingCertsSecret: ""
certs:
clientcas.pem: ""
issuer.pem: ""
restapi-ca.pem: ""
restapi-cert.pem: ""
restapi-key.pem: ""
root.pem: ""
websocket-cert.pem: ""
websocket-key.pem: ""
clientcas.pem: |
-----BEGIN CERTIFICATE-----
MIIEnDCCA4SgAwIBAgIUVpyCUx1MUeUwxg+7I1BvGFTz7HkwDQYJKoZIhvcNAQEL
BQAwaTELMAkGA1UEBhMCVVMxJDAiBgNVBAoTG1RlbGVjb20gSW5mcmEgUHJvamVj
dCwgSW5jLjEMMAoGA1UECxMDVElQMSYwJAYDVQQDEx1UZWxlY29tIEluZnJhIFBy
b2plY3QgUm9vdCBDQTAeFw0yMTA0MTMyMjUxMjZaFw0yNjA0MTMyMjM4NDZaMGwx
CzAJBgNVBAYTAlVTMSQwIgYDVQQKExtUZWxlY29tIEluZnJhIFByb2plY3QsIElu
Yy4xDDAKBgNVBAsTA1RJUDEpMCcGA1UEAxMgVGVsZWNvbSBJbmZyYSBQcm9qZWN0
IElzc3VpbmcgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDtKBrq
qd2aKVSk25KfL5xHu8X7/8rJrz3IvyPuVKWhk/N1zabot3suBcGaYNKjnRHxg78R
yKwKzajKYWtiQFqztu24g16LQeAnoUxZnF6a0z3JkkRPsz14A2y8TUhdEe1tx+UU
4VGsk3n+FMmOQHL+79FO57zQC1LwylgfLSltrI6mF3jowVUQvnwzKhUzT87AJ6EO
ndK/q0T/Bgi+aI39zfVOjJjsTJwghvrmYW3iarP1THSKxeib2s02bZKrvvHa5HL4
UI8+LvREpVZl4mzt1z6Nl344Y6f+UeJlYa/Ci0jJqaXJmyVnUbAz+c0i5JfwAVn3
YQzfC4eLnZCmdF8zAgMBAAGjggE3MIIBMzAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud
DgQWBBSzG1S44EerPfM4gOQ85f0AYW3R6DAfBgNVHSMEGDAWgBQCRpZgebFT9qny
98WfIUDk6ZEB+jAOBgNVHQ8BAf8EBAMCAYYwgYMGCCsGAQUFBwEBBHcwdTAoBggr
BgEFBQcwAYYcaHR0cDovL29jc3Aub25lLmRpZ2ljZXJ0LmNvbTBJBggrBgEFBQcw
AoY9aHR0cDovL2NhY2VydHMub25lLmRpZ2ljZXJ0LmNvbS9UZWxlY29tSW5mcmFQ
cm9qZWN0Um9vdENBLmNydDBKBgNVHR8EQzBBMD+gPaA7hjlodHRwOi8vY3JsLm9u
ZS5kaWdpY2VydC5jb20vVGVsZWNvbUluZnJhUHJvamVjdFJvb3RDQS5jcmwwDQYJ
KoZIhvcNAQELBQADggEBAFbz+K94bHIkBMJqps0dApniUmOn0pO6Q6cGh47UP/kX
IiPIsnYgG+hqYD/qtsiqJhaWi0hixRWn38UmvZxMRk27aSTGE/TWx0JTC3qDGsSe
XkUagumbSfmS0ZyiTwMPeGAjXwyzGorqZWeA95eKfImntMiOf3E7//GK0K7HpCx8
IPCnLZsZD2q/mLyBsduImFIRQJbLAhwIxpcd1qYJk+BlGFL+HtBpEbq6JxW2Xy+v
DpNWc2WIsUTle0rTc9JNJrLX4ChUJmKqf8obKHap3Xh3//qw/jDB9pOAinA33FLJ
EmCnwBvQr9mfNmPBGMYZVU8cPruDQJ57GjmmvdisbJY=
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIDojCCAoqgAwIBAgIUPVYBpqNbcLYygF6Mx+qxSWwQyFowDQYJKoZIhvcNAQEL
BQAwaTELMAkGA1UEBhMCVVMxJDAiBgNVBAoTG1RlbGVjb20gSW5mcmEgUHJvamVj
dCwgSW5jLjEMMAoGA1UECxMDVElQMSYwJAYDVQQDEx1UZWxlY29tIEluZnJhIFBy
b2plY3QgUm9vdCBDQTAeFw0yMTA0MTMyMjQyNDRaFw0zMTA0MTMyMjM4NDZaMGkx
CzAJBgNVBAYTAlVTMSQwIgYDVQQKExtUZWxlY29tIEluZnJhIFByb2plY3QsIElu
Yy4xDDAKBgNVBAsTA1RJUDEmMCQGA1UEAxMdVGVsZWNvbSBJbmZyYSBQcm9qZWN0
IFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDIGCibwf5u
AAwZ+1H8U0e3u2V+0d2gSctucoK86XwUmfe1V2a/qlCYZd29r80IuN1IIeB0naIm
KnK/MzXW87clF6tFd1+HzEvmlY/W4KyIXalVCTEzirFSvBEG2oZpM0yC3AefytAO
aOpA00LaM3xTfTqMKIRhJBuLy0I4ANUVG6ixVebbGuc78IodleqiLoWy2Q9QHyEO
t/7hZndJhiVogh0PveRhho45EbsACu7ymDY+JhlIleevqwlE3iQoq0YcmYADHno6
Eq8vcwLpZFxihupUafkd1T3WJYQAJf9coCjBu2qIhNgrcrGD8R9fGswwNRzMRMpX
720+GjcDW3bJAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFAJG
lmB5sVP2qfL3xZ8hQOTpkQH6MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsF
AAOCAQEAVjl9dm4epG9NUYnagT9sg7scVQEPfz3Lt6w1NXJXgD8mAUlK0jXmEyvM
dCPD4514n+8+lM7US8fh+nxc7jO//LwK17Wm9FblgjNFR7+anv0Q99T9fP19DLlF
PSNHL2emogy1bl1lLTAoj8nxg2wVKPDSHBGviQ5LR9fsWUIJDv9Bs5k0qWugWYSj
19S6qnHeskRDB8MqRLhKMG82oDVLerSnhD0P6HjySBHgTTU7/tYS/OZr1jI6MPbG
L+/DtiR5fDVMNdBSGU89UNTi0wHY9+RFuNlIuvZC+x/swF0V9R5mN+ywquTPtDLA
5IOM7ItsRmen6u3qu+JXros54e4juQ==
-----END CERTIFICATE-----
issuer.pem: |
-----BEGIN CERTIFICATE-----
MIIEnDCCA4SgAwIBAgIUVpyCUx1MUeUwxg+7I1BvGFTz7HkwDQYJKoZIhvcNAQEL
BQAwaTELMAkGA1UEBhMCVVMxJDAiBgNVBAoTG1RlbGVjb20gSW5mcmEgUHJvamVj
dCwgSW5jLjEMMAoGA1UECxMDVElQMSYwJAYDVQQDEx1UZWxlY29tIEluZnJhIFBy
b2plY3QgUm9vdCBDQTAeFw0yMTA0MTMyMjUxMjZaFw0yNjA0MTMyMjM4NDZaMGwx
CzAJBgNVBAYTAlVTMSQwIgYDVQQKExtUZWxlY29tIEluZnJhIFByb2plY3QsIElu
Yy4xDDAKBgNVBAsTA1RJUDEpMCcGA1UEAxMgVGVsZWNvbSBJbmZyYSBQcm9qZWN0
IElzc3VpbmcgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDtKBrq
qd2aKVSk25KfL5xHu8X7/8rJrz3IvyPuVKWhk/N1zabot3suBcGaYNKjnRHxg78R
yKwKzajKYWtiQFqztu24g16LQeAnoUxZnF6a0z3JkkRPsz14A2y8TUhdEe1tx+UU
4VGsk3n+FMmOQHL+79FO57zQC1LwylgfLSltrI6mF3jowVUQvnwzKhUzT87AJ6EO
ndK/q0T/Bgi+aI39zfVOjJjsTJwghvrmYW3iarP1THSKxeib2s02bZKrvvHa5HL4
UI8+LvREpVZl4mzt1z6Nl344Y6f+UeJlYa/Ci0jJqaXJmyVnUbAz+c0i5JfwAVn3
YQzfC4eLnZCmdF8zAgMBAAGjggE3MIIBMzAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud
DgQWBBSzG1S44EerPfM4gOQ85f0AYW3R6DAfBgNVHSMEGDAWgBQCRpZgebFT9qny
98WfIUDk6ZEB+jAOBgNVHQ8BAf8EBAMCAYYwgYMGCCsGAQUFBwEBBHcwdTAoBggr
BgEFBQcwAYYcaHR0cDovL29jc3Aub25lLmRpZ2ljZXJ0LmNvbTBJBggrBgEFBQcw
AoY9aHR0cDovL2NhY2VydHMub25lLmRpZ2ljZXJ0LmNvbS9UZWxlY29tSW5mcmFQ
cm9qZWN0Um9vdENBLmNydDBKBgNVHR8EQzBBMD+gPaA7hjlodHRwOi8vY3JsLm9u
ZS5kaWdpY2VydC5jb20vVGVsZWNvbUluZnJhUHJvamVjdFJvb3RDQS5jcmwwDQYJ
KoZIhvcNAQELBQADggEBAFbz+K94bHIkBMJqps0dApniUmOn0pO6Q6cGh47UP/kX
IiPIsnYgG+hqYD/qtsiqJhaWi0hixRWn38UmvZxMRk27aSTGE/TWx0JTC3qDGsSe
XkUagumbSfmS0ZyiTwMPeGAjXwyzGorqZWeA95eKfImntMiOf3E7//GK0K7HpCx8
IPCnLZsZD2q/mLyBsduImFIRQJbLAhwIxpcd1qYJk+BlGFL+HtBpEbq6JxW2Xy+v
DpNWc2WIsUTle0rTc9JNJrLX4ChUJmKqf8obKHap3Xh3//qw/jDB9pOAinA33FLJ
EmCnwBvQr9mfNmPBGMYZVU8cPruDQJ57GjmmvdisbJY=
-----END CERTIFICATE-----
# restapi-ca.pem: ""
# restapi-cert.pem: ""
# restapi-key.pem: ""
root.pem: |
-----BEGIN CERTIFICATE-----
MIIDojCCAoqgAwIBAgIUPVYBpqNbcLYygF6Mx+qxSWwQyFowDQYJKoZIhvcNAQEL
BQAwaTELMAkGA1UEBhMCVVMxJDAiBgNVBAoTG1RlbGVjb20gSW5mcmEgUHJvamVj
dCwgSW5jLjEMMAoGA1UECxMDVElQMSYwJAYDVQQDEx1UZWxlY29tIEluZnJhIFBy
b2plY3QgUm9vdCBDQTAeFw0yMTA0MTMyMjQyNDRaFw0zMTA0MTMyMjM4NDZaMGkx
CzAJBgNVBAYTAlVTMSQwIgYDVQQKExtUZWxlY29tIEluZnJhIFByb2plY3QsIElu
Yy4xDDAKBgNVBAsTA1RJUDEmMCQGA1UEAxMdVGVsZWNvbSBJbmZyYSBQcm9qZWN0
IFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDIGCibwf5u
AAwZ+1H8U0e3u2V+0d2gSctucoK86XwUmfe1V2a/qlCYZd29r80IuN1IIeB0naIm
KnK/MzXW87clF6tFd1+HzEvmlY/W4KyIXalVCTEzirFSvBEG2oZpM0yC3AefytAO
aOpA00LaM3xTfTqMKIRhJBuLy0I4ANUVG6ixVebbGuc78IodleqiLoWy2Q9QHyEO
t/7hZndJhiVogh0PveRhho45EbsACu7ymDY+JhlIleevqwlE3iQoq0YcmYADHno6
Eq8vcwLpZFxihupUafkd1T3WJYQAJf9coCjBu2qIhNgrcrGD8R9fGswwNRzMRMpX
720+GjcDW3bJAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFAJG
lmB5sVP2qfL3xZ8hQOTpkQH6MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsF
AAOCAQEAVjl9dm4epG9NUYnagT9sg7scVQEPfz3Lt6w1NXJXgD8mAUlK0jXmEyvM
dCPD4514n+8+lM7US8fh+nxc7jO//LwK17Wm9FblgjNFR7+anv0Q99T9fP19DLlF
PSNHL2emogy1bl1lLTAoj8nxg2wVKPDSHBGviQ5LR9fsWUIJDv9Bs5k0qWugWYSj
19S6qnHeskRDB8MqRLhKMG82oDVLerSnhD0P6HjySBHgTTU7/tYS/OZr1jI6MPbG
L+/DtiR5fDVMNdBSGU89UNTi0wHY9+RFuNlIuvZC+x/swF0V9R5mN+ywquTPtDLA
5IOM7ItsRmen6u3qu+JXros54e4juQ==
-----END CERTIFICATE-----
# websocket-cert.pem: ""
# websocket-key.pem: ""
certsCAs:
issuer.pem: ""
root.pem: ""
issuer.pem: |
-----BEGIN CERTIFICATE-----
MIIEnDCCA4SgAwIBAgIUVpyCUx1MUeUwxg+7I1BvGFTz7HkwDQYJKoZIhvcNAQEL
BQAwaTELMAkGA1UEBhMCVVMxJDAiBgNVBAoTG1RlbGVjb20gSW5mcmEgUHJvamVj
dCwgSW5jLjEMMAoGA1UECxMDVElQMSYwJAYDVQQDEx1UZWxlY29tIEluZnJhIFBy
b2plY3QgUm9vdCBDQTAeFw0yMTA0MTMyMjUxMjZaFw0yNjA0MTMyMjM4NDZaMGwx
CzAJBgNVBAYTAlVTMSQwIgYDVQQKExtUZWxlY29tIEluZnJhIFByb2plY3QsIElu
Yy4xDDAKBgNVBAsTA1RJUDEpMCcGA1UEAxMgVGVsZWNvbSBJbmZyYSBQcm9qZWN0
IElzc3VpbmcgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDtKBrq
qd2aKVSk25KfL5xHu8X7/8rJrz3IvyPuVKWhk/N1zabot3suBcGaYNKjnRHxg78R
yKwKzajKYWtiQFqztu24g16LQeAnoUxZnF6a0z3JkkRPsz14A2y8TUhdEe1tx+UU
4VGsk3n+FMmOQHL+79FO57zQC1LwylgfLSltrI6mF3jowVUQvnwzKhUzT87AJ6EO
ndK/q0T/Bgi+aI39zfVOjJjsTJwghvrmYW3iarP1THSKxeib2s02bZKrvvHa5HL4
UI8+LvREpVZl4mzt1z6Nl344Y6f+UeJlYa/Ci0jJqaXJmyVnUbAz+c0i5JfwAVn3
YQzfC4eLnZCmdF8zAgMBAAGjggE3MIIBMzAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud
DgQWBBSzG1S44EerPfM4gOQ85f0AYW3R6DAfBgNVHSMEGDAWgBQCRpZgebFT9qny
98WfIUDk6ZEB+jAOBgNVHQ8BAf8EBAMCAYYwgYMGCCsGAQUFBwEBBHcwdTAoBggr
BgEFBQcwAYYcaHR0cDovL29jc3Aub25lLmRpZ2ljZXJ0LmNvbTBJBggrBgEFBQcw
AoY9aHR0cDovL2NhY2VydHMub25lLmRpZ2ljZXJ0LmNvbS9UZWxlY29tSW5mcmFQ
cm9qZWN0Um9vdENBLmNydDBKBgNVHR8EQzBBMD+gPaA7hjlodHRwOi8vY3JsLm9u
ZS5kaWdpY2VydC5jb20vVGVsZWNvbUluZnJhUHJvamVjdFJvb3RDQS5jcmwwDQYJ
KoZIhvcNAQELBQADggEBAFbz+K94bHIkBMJqps0dApniUmOn0pO6Q6cGh47UP/kX
IiPIsnYgG+hqYD/qtsiqJhaWi0hixRWn38UmvZxMRk27aSTGE/TWx0JTC3qDGsSe
XkUagumbSfmS0ZyiTwMPeGAjXwyzGorqZWeA95eKfImntMiOf3E7//GK0K7HpCx8
IPCnLZsZD2q/mLyBsduImFIRQJbLAhwIxpcd1qYJk+BlGFL+HtBpEbq6JxW2Xy+v
DpNWc2WIsUTle0rTc9JNJrLX4ChUJmKqf8obKHap3Xh3//qw/jDB9pOAinA33FLJ
EmCnwBvQr9mfNmPBGMYZVU8cPruDQJ57GjmmvdisbJY=
-----END CERTIFICATE-----
root.pem: |
-----BEGIN CERTIFICATE-----
MIIDojCCAoqgAwIBAgIUPVYBpqNbcLYygF6Mx+qxSWwQyFowDQYJKoZIhvcNAQEL
BQAwaTELMAkGA1UEBhMCVVMxJDAiBgNVBAoTG1RlbGVjb20gSW5mcmEgUHJvamVj
dCwgSW5jLjEMMAoGA1UECxMDVElQMSYwJAYDVQQDEx1UZWxlY29tIEluZnJhIFBy
b2plY3QgUm9vdCBDQTAeFw0yMTA0MTMyMjQyNDRaFw0zMTA0MTMyMjM4NDZaMGkx
CzAJBgNVBAYTAlVTMSQwIgYDVQQKExtUZWxlY29tIEluZnJhIFByb2plY3QsIElu
Yy4xDDAKBgNVBAsTA1RJUDEmMCQGA1UEAxMdVGVsZWNvbSBJbmZyYSBQcm9qZWN0
IFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDIGCibwf5u
AAwZ+1H8U0e3u2V+0d2gSctucoK86XwUmfe1V2a/qlCYZd29r80IuN1IIeB0naIm
KnK/MzXW87clF6tFd1+HzEvmlY/W4KyIXalVCTEzirFSvBEG2oZpM0yC3AefytAO
aOpA00LaM3xTfTqMKIRhJBuLy0I4ANUVG6ixVebbGuc78IodleqiLoWy2Q9QHyEO
t/7hZndJhiVogh0PveRhho45EbsACu7ymDY+JhlIleevqwlE3iQoq0YcmYADHno6
Eq8vcwLpZFxihupUafkd1T3WJYQAJf9coCjBu2qIhNgrcrGD8R9fGswwNRzMRMpX
720+GjcDW3bJAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFAJG
lmB5sVP2qfL3xZ8hQOTpkQH6MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsF
AAOCAQEAVjl9dm4epG9NUYnagT9sg7scVQEPfz3Lt6w1NXJXgD8mAUlK0jXmEyvM
dCPD4514n+8+lM7US8fh+nxc7jO//LwK17Wm9FblgjNFR7+anv0Q99T9fP19DLlF
PSNHL2emogy1bl1lLTAoj8nxg2wVKPDSHBGviQ5LR9fsWUIJDv9Bs5k0qWugWYSj
19S6qnHeskRDB8MqRLhKMG82oDVLerSnhD0P6HjySBHgTTU7/tYS/OZr1jI6MPbG
L+/DtiR5fDVMNdBSGU89UNTi0wHY9+RFuNlIuvZC+x/swF0V9R5mN+ywquTPtDLA
5IOM7ItsRmen6u3qu+JXros54e4juQ==
-----END CERTIFICATE-----
# PostgreSQL (https://github.com/bitnami/charts/tree/master/bitnami/postgresql)
postgresql:

View File

@@ -65,7 +65,6 @@ openwifi.system.debug = true
openwifi.system.uri.private = https://localhost:17002
openwifi.system.uri.public = https://ucentral.dpaas.arilia.com:16002
openwifi.system.uri.ui = https://ucentral-ui.arilia.com
openwifi.security.restapi.disable = false
openwifi.system.commandchannel = /tmp/app.ucentralgw
#
@@ -178,4 +177,4 @@ archiver.db.3.keep = 7
########################################################################
logging.type = file
logging.path = $OWGW_ROOT/logs
logging.level = information
logging.level = debug

View File

@@ -52,8 +52,8 @@ openwifi.fileuploader.host.0.cert = ${FILEUPLOADER_HOST_CERT}
openwifi.fileuploader.host.0.key = ${FILEUPLOADER_HOST_KEY}
openwifi.fileuploader.host.0.key.password = ${FILEUPLOADER_HOST_KEY_PASSWORD}
openwifi.fileuploader.path = ${FILEUPLOADER_PATH}
openwifi.fileuploader.maxsize = 10000
openwifi.fileuploader.uri = ${FILEUPLOADER_URI}
openwifi.fileuploader.maxsize = 10000
#
# Generic section that all microservices must have
@@ -65,7 +65,6 @@ openwifi.system.debug = true
openwifi.system.uri.private = ${SYSTEM_URI_PRIVATE}
openwifi.system.uri.public = ${SYSTEM_URI_PUBLIC}
openwifi.system.uri.ui = ${SYSTEM_URI_UI}
openwifi.security.restapi.disable = ${SECURITY_RESTAPI_DISABLE}
openwifi.system.commandchannel = /tmp/app.ucentralgw
#
@@ -76,13 +75,8 @@ openwifi.devicetypes.0 = AP:linksys_ea8300,edgecore_eap101,linksys_e8450-ubi
openwifi.devicetypes.1 = SWITCH:edgecore_ecs4100-12ph
openwifi.devicetypes.2 = IOT:esp32
oui.download.uri = https://standards-oui.ieee.org/oui/oui.txt
firmware.autoupdate.policy.default = auto
simulatorid = ${SIMULATORID}
iptocountry.default = US
iptocountry.provider = ${IPTOCOUNTRY_PROVIDER}
iptocountry.ipinfo.token = ${IPTOCOUNTRY_IPINFO_TOKEN}
iptocountry.ipdata.apikey = ${IPTOCOUNTRY_IPDATA_APIKEY}
autoprovisioning.process = ${AUTOPROVISIONING_PROCESS}
#
# rtty
@@ -96,12 +90,6 @@ rtty.timeout = ${RTTY_TIMEOUT}
rtty.viewport = ${RTTY_VIEWPORT}
rtty.assets = ${RTTY_ASSETS}
### RADIUS proxy config
radius.proxy.enable = ${RADIUS_PROXY_ENABLE}
radius.proxy.accounting.port = ${RADIUS_PROXY_ACCOUNTING_PORT}
radius.proxy.authentication.port = ${RADIUS_PROXY_AUTHENTICATION_PORT}
radius.proxy.coa.port = ${RADIUS_PROXY_COA_PORT}
#############################
# Generic information for all micro services
#############################
@@ -120,7 +108,6 @@ openwifi.kafka.enable = ${KAFKA_ENABLE}
openwifi.kafka.brokerlist = ${KAFKA_BROKERLIST}
openwifi.kafka.auto.commit = false
openwifi.kafka.queue.buffering.max.ms = 50
openwifi.kafka.ssl.ca.location = ${KAFKA_SSL_CA_LOCATION}
openwifi.kafka.ssl.certificate.location = ${KAFKA_SSL_CERTIFICATE_LOCATION}
openwifi.kafka.ssl.key.location = ${KAFKA_SSL_KEY_LOCATION}
@@ -174,4 +161,4 @@ archiver.db.3.keep = 7
########################################################################
logging.type = console
logging.path = $OWGW_ROOT/logs
logging.level = information
logging.level = debug

41
pcap/radius Normal file
View File

@@ -0,0 +1,41 @@
/* Frame (255 bytes) */
static const unsigned char pkt41[255] = {
0x14, 0x98, 0x77, 0x71, 0xc6, 0xe7, 0x34, 0xef, /* ..wq..4. */
0xb6, 0xaf, 0x4a, 0x5c, 0x08, 0x00, 0x45, 0x00, /* ..J\..E. */
0x00, 0xf1, 0x87, 0x50, 0x00, 0x00, 0x40, 0x11, /* ...P..@. */
0x0c, 0xdf, 0xc0, 0xa8, 0xb2, 0x1b, 0xc0, 0xa8, /* ........ */
0xb2, 0x60, 0xc3, 0xfe, 0x07, 0x14, 0x00, 0xdd, /* .`...... */
0x26, 0x63, 0x01, 0x04, 0x00, 0xd5, 0xcc, 0x29, /* &c.....) */
0x82, 0x36, 0xd6, 0x57, 0x3d, 0xa7, 0xd5, 0x62, /* .6.W=..b */
0x70, 0x12, 0x00, 0xc0, 0xf2, 0x19, 0x01, 0x03, /* p....... */
0x61, 0x1e, 0x1c, 0x33, 0x34, 0x2d, 0x45, 0x46, /* a..34-EF */
0x2d, 0x42, 0x36, 0x2d, 0x41, 0x46, 0x2d, 0x34, /* -B6-AF-4 */
0x41, 0x2d, 0x36, 0x30, 0x3a, 0x4f, 0x70, 0x65, /* A-60:Ope */
0x6e, 0x57, 0x69, 0x66, 0x69, 0x3d, 0x06, 0x00, /* nWifi=.. */
0x00, 0x00, 0x13, 0x06, 0x06, 0x00, 0x00, 0x00, /* ........ */
0x02, 0x05, 0x06, 0x00, 0x00, 0x00, 0x01, 0x1f, /* ........ */
0x13, 0x42, 0x36, 0x2d, 0x43, 0x34, 0x2d, 0x30, /* .B6-C4-0 */
0x36, 0x2d, 0x30, 0x39, 0x2d, 0x31, 0x35, 0x2d, /* 6-09-15- */
0x42, 0x37, 0x4d, 0x18, 0x43, 0x4f, 0x4e, 0x4e, /* B7M.CONN */
0x45, 0x43, 0x54, 0x20, 0x35, 0x34, 0x4d, 0x62, /* ECT 54Mb */
0x70, 0x73, 0x20, 0x38, 0x30, 0x32, 0x2e, 0x31, /* ps 802.1 */
0x31, 0x61, 0x2c, 0x12, 0x33, 0x42, 0x45, 0x44, /* 1a,.3BED */
0x37, 0x32, 0x39, 0x30, 0x44, 0x30, 0x43, 0x38, /* 7290D0C8 */
0x35, 0x36, 0x44, 0x33, 0xba, 0x06, 0x00, 0x0f, /* 56D3.... */
0xac, 0x04, 0xbb, 0x06, 0x00, 0x0f, 0xac, 0x04, /* ........ */
0xbc, 0x06, 0x00, 0x0f, 0xac, 0x05, 0xbd, 0x06, /* ........ */
0x00, 0x0f, 0xac, 0x06, 0x1a, 0x1b, 0x00, 0x00, /* ........ */
0xe6, 0x08, 0x47, 0x15, 0x01, 0x13, 0x33, 0x34, /* ..G...34 */
0x2d, 0x65, 0x66, 0x2d, 0x62, 0x36, 0x2d, 0x61, /* -ef-b6-a */
0x66, 0x2d, 0x34, 0x61, 0x2d, 0x35, 0x63, 0x0c, /* f-4a-5c. */
0x06, 0x00, 0x00, 0x05, 0x78, 0x4f, 0x08, 0x02, /* ....xO.. */
0x01, 0x00, 0x06, 0x01, 0x61, 0x50, 0x12, 0x20, /* ....aP. */
0x9c, 0xae, 0xe5, 0xe3, 0x77, 0xaf, 0x0b, 0x1b, /* ....w... */
0xaf, 0x0e, 0xb5, 0x08, 0x82, 0x9e, 0xeb /* ....... */
};
/* Reassembled EAP (6 bytes) */
static const unsigned char pkt41_1[6] = {
0x02, 0x01, 0x00, 0x06, 0x01, 0x61 /* .....a */
};

1
pcap/radius.blob.bin Normal file
View File

@@ -0,0 +1 @@
192.168.178.1

BIN
pcap/radius.pcapng Normal file

Binary file not shown.

24
run.sh Executable file
View File

@@ -0,0 +1,24 @@
#!/bin/bash
daemon=ucentralgw
if [[ "$1" == "aws" ]]
then
cp ${daemon}.properties.aws ${daemon}.properties
. ./set_env.sh
cd cmake-build
./${daemon} --daemon
echo "Running AWS version as daemon..."
fi
if [[ "$1" == "priv" ]]
then
cp ${daemon}.properties.priv ${daemon}.properties
. ./set_env.sh
cd cmake-build
./${daemon} --daemon
echo "Running private version as daemon..."
fi

View File

@@ -11,7 +11,7 @@
#include "Poco/Net/SSLException.h"
#include "Poco/Net/Context.h"
#include "Poco/Base64Decoder.h"
#include "Poco/Net/WebSocketImpl.h"
#include "Poco/zlib.h"
#include "AP_WS_Server.h"
@@ -20,14 +20,8 @@
#include "ConfigurationCache.h"
#include "StorageService.h"
#include "TelemetryStream.h"
#include "framework/KafkaManager.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
#include "UI_GW_WebSocketNotifications.h"
#include "fmt/format.h"
#include "framework/WebSocketClientNotifications.h"
#include "Poco/Net/WebSocketImpl.h"
#include "RADIUS_proxy_server.h"
@@ -41,7 +35,7 @@ namespace OpenWifi {
AP_WS_Connection::AP_WS_Connection(Poco::Net::HTTPServerRequest &request,
Poco::Net::HTTPServerResponse &response,
uint64_t connection_id,
std::uint64_t connection_id,
Poco::Logger &L,
Poco::Net::SocketReactor &R)
: Logger_(L) ,
@@ -68,7 +62,6 @@ namespace OpenWifi {
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ErrorNotification>(
*this, &AP_WS_Connection::OnSocketError));
Registered_ = true;
Valid_ = true;
}
class ThreadedCounter {
@@ -96,9 +89,6 @@ namespace OpenWifi {
if(DeviceValidated_)
return true;
if(!Valid_)
return false;
try {
auto SockImpl = dynamic_cast<Poco::Net::WebSocketImpl *>(WS_->impl());
auto SS = dynamic_cast<Poco::Net::SecureStreamSocketImpl*>(SockImpl->streamSocketImpl());
@@ -106,7 +96,7 @@ namespace OpenWifi {
PeerAddress_ = SS->peerAddress().host();
CId_ = Utils::FormatIPv6(SS->peerAddress().toString());
State_.started = Utils::Now();
State_.started = OpenWifi::Now();
if (!SS->secure()) {
poco_warning(Logger_,fmt::format("TLS-CONNECTION({}): Session={} Connection is NOT secure. Device is not allowed.", CId_, State_.sessionId ));
@@ -146,7 +136,7 @@ namespace OpenWifi {
return false;
}
if (!CN_.empty() && StorageService()->IsBlackListed(CN_)) {
if (!CN_.empty() && StorageService()->IsBlackListed(SerialNumber_)) {
poco_warning(
Logger_,
fmt::format("TLS-CONNECTION({}): Session={} Device {} is black listed. Disconnecting.",
@@ -199,12 +189,131 @@ namespace OpenWifi {
return false;
}
void AP_WS_Connection::CompleteStartup() {
std::lock_guard Guard(Mutex_);
auto TC = ThreadedCounter(Threaded_,ConcurrentStartingDevices_);
try {
auto SockImpl = dynamic_cast<Poco::Net::WebSocketImpl *>(WS_->impl());
auto SS = dynamic_cast<Poco::Net::SecureStreamSocketImpl*>(SockImpl->streamSocketImpl());
/* while (true) {
auto V = SS->completeHandshake();
if (V == 1)
break;
}
*/
PeerAddress_ = SS->peerAddress().host();
CId_ = Utils::FormatIPv6(SS->peerAddress().toString());
State_.started = OpenWifi::Now();
if (!SS->secure()) {
poco_warning(Logger_,fmt::format("CONNECTION({}): Session={} Connection is NOT secure. Device is not allowed.", CId_, State_.sessionId ));
return EndConnection();
}
poco_debug(Logger_,fmt::format("CONNECTION({}): Session={} Connection is secure.", CId_, State_.sessionId ));
if (!SS->havePeerCertificate()) {
State_.VerifiedCertificate = GWObjects::NO_CERTIFICATE;
poco_warning(Logger_,fmt::format("CONNECTION({}): Session={} No certificates available..", CId_, State_.sessionId ));
return EndConnection();
}
Poco::Crypto::X509Certificate PeerCert(SS->peerCertificate());
if (!AP_WS_Server()->ValidateCertificate(CId_, PeerCert)) {
State_.VerifiedCertificate = GWObjects::NO_CERTIFICATE;
poco_warning(Logger_, fmt::format("CONNECTION({}): Session={} Device certificate is not valid. Device is not allowed.",
CId_, State_.sessionId ));
return EndConnection();
}
CN_ = Poco::trim(Poco::toLower(PeerCert.commonName()));
State_.VerifiedCertificate = GWObjects::VALID_CERTIFICATE;
poco_debug(Logger_,
fmt::format("CONNECTION({}): Session={} Valid certificate: CN={}", CId_, State_.sessionId , CN_));
if (AP_WS_Server::IsSim(CN_) && !AP_WS_Server()->IsSimEnabled()) {
poco_warning(
Logger_,
fmt::format("CONNECTION({}): Session={} Sim Device {} is not allowed. Disconnecting.",
CId_, State_.sessionId , CN_));
return EndConnection();
}
if (!CN_.empty() && StorageService()->IsBlackListed(SerialNumber_)) {
poco_warning(
Logger_,
fmt::format("CONNECTION({}): Session={} Device {} is black listed. Disconnecting.",
CId_, State_.sessionId , CN_));
return EndConnection();
}
SerialNumber_ = CN_;
SerialNumberInt_ = Utils::SerialNumberToInt(SerialNumber_);
WS_->setMaxPayloadSize(BufSize);
auto TS = Poco::Timespan(360, 0);
WS_->setReceiveTimeout(TS);
WS_->setNoDelay(true);
WS_->setKeepAlive(true);
WS_->setBlocking(false);
Reactor_.addEventHandler(
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ReadableNotification>(
*this, &AP_WS_Connection::OnSocketReadable));
Reactor_.addEventHandler(
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ShutdownNotification>(
*this, &AP_WS_Connection::OnSocketShutdown));
Reactor_.addEventHandler(
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ErrorNotification>(
*this, &AP_WS_Connection::OnSocketError));
Registered_ = true;
poco_debug(Logger_, fmt::format("CONNECTION({}): Session={} CN={} Completed. (t={})", CId_, State_.sessionId , CN_, ConcurrentStartingDevices_));
return;
} catch (const Poco::Net::CertificateValidationException &E) {
poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::CertificateValidationException Certificate Validation failed during connection. Device will have to retry.",
CId_, State_.sessionId ));
Logger_.log(E);
} catch (const Poco::Net::WebSocketException &E) {
poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::WebSocketException WebSocket error during connection. Device will have to retry.",
CId_, State_.sessionId ));
Logger_.log(E);
} catch (const Poco::Net::ConnectionAbortedException &E) {
poco_error(Logger_,fmt::format("CONNECTION({}):Session:{} Poco::ConnectionAbortedException Connection was aborted during connection. Device will have to retry.",
CId_, State_.sessionId ));
Logger_.log(E);
} catch (const Poco::Net::ConnectionResetException &E) {
poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::ConnectionResetException Connection was reset during connection. Device will have to retry.",
CId_, State_.sessionId ));
Logger_.log(E);
} catch (const Poco::Net::InvalidCertificateException &E) {
poco_error(Logger_,fmt::format(
"CONNECTION({}): Session:{} Poco::InvalidCertificateException Invalid certificate. Device will have to retry.",
CId_, State_.sessionId ));
Logger_.log(E);
} catch (const Poco::Net::SSLException &E) {
poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::SSLException SSL Exception during connection. Device will have to retry.",
CId_, State_.sessionId ));
Logger_.log(E);
} catch (const Poco::Exception &E) {
poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Poco::Exception caught during device connection. Device will have to retry.",
CId_, State_.sessionId ));
Logger_.log(E);
} catch (...) {
poco_error(Logger_,fmt::format("CONNECTION({}): Session:{} Exception caught during device connection. Device will have to retry. Unsecure connect denied.",
CId_, State_.sessionId ));
}
return EndConnection();
}
static void NotifyKafkaDisconnect(const std::string & SerialNumber) {
try {
Poco::JSON::Object Disconnect;
Poco::JSON::Object Details;
Details.set(uCentralProtocol::SERIALNUMBER, SerialNumber);
Details.set(uCentralProtocol::TIMESTAMP, Utils::Now());
Details.set(uCentralProtocol::TIMESTAMP, OpenWifi::Now());
Disconnect.set(uCentralProtocol::DISCONNECTION, Details);
Poco::JSON::Stringifier Stringify;
std::ostringstream OS;
@@ -215,41 +324,36 @@ namespace OpenWifi {
}
AP_WS_Connection::~AP_WS_Connection() {
Valid_=false;
EndConnection();
if(!Dead_)
EndConnection();
}
void AP_WS_Connection::EndConnection() {
Valid_=false;
if(!Dead_.test_and_set()) {
Dead_=true;
poco_information(Logger_,fmt::format("CONNECTION-CLOSING({}): Session={} Serial={}.", CId_, State_.sessionId, SerialNumber_));
auto SessionDeleted = DeviceRegistry()->EndSession(State_.sessionId, SerialNumberInt_);
if (Registered_) {
Registered_ = false;
Reactor_.removeEventHandler(
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ReadableNotification>(
*this, &AP_WS_Connection::OnSocketReadable));
Reactor_.removeEventHandler(
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ShutdownNotification>(
*this, &AP_WS_Connection::OnSocketShutdown));
Reactor_.removeEventHandler(
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ErrorNotification>(
*this, &AP_WS_Connection::OnSocketError));
}
WS_->close();
if (KafkaManager()->Enabled() && !SerialNumber_.empty()) {
std::string s(SerialNumber_);
std::thread t([s]() { NotifyKafkaDisconnect(s); });
t.detach();
}
auto SessionDeleted = AP_WS_Server()->EndSession(State_.sessionId, SerialNumberInt_);
if (SessionDeleted) {
WebNotificationSingleDevice_t N;
N.content.serialNumber = SerialNumber_;
WebSocketClientNotificationDeviceDisconnected(N);
}
if (Registered_) {
Reactor_.removeEventHandler(
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ReadableNotification>(
*this, &AP_WS_Connection::OnSocketReadable));
Reactor_.removeEventHandler(
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ShutdownNotification>(
*this, &AP_WS_Connection::OnSocketShutdown));
Reactor_.removeEventHandler(
*WS_, Poco::NObserver<AP_WS_Connection, Poco::Net::ErrorNotification>(
*this, &AP_WS_Connection::OnSocketError));
}
WS_->close();
if (KafkaManager()->Enabled() && !SerialNumber_.empty()) {
std::string s(SerialNumber_);
std::thread t([s]() { NotifyKafkaDisconnect(s); });
t.detach();
}
if(SessionDeleted)
WebSocketClientNotificationDeviceDisconnected(SerialNumber_);
AP_WS_Server()->DeleteConnection(State_.sessionId);
}
bool AP_WS_Connection::LookForUpgrade(const uint64_t UUID, uint64_t & UpgradedUUID) {
@@ -289,7 +393,7 @@ namespace OpenWifi {
State_.PendingUUID = D.UUID;
GWObjects::CommandDetails Cmd;
Cmd.SerialNumber = SerialNumber_;
Cmd.UUID = MicroServiceCreateUUID();
Cmd.UUID = MicroService::CreateUUID();
Cmd.SubmittedBy = uCentralProtocol::SUBMITTED_BY_SYSTEM;
Cmd.Status = uCentralProtocol::PENDING;
Cmd.Command = uCentralProtocol::CONFIGURE;
@@ -311,11 +415,7 @@ namespace OpenWifi {
StorageService()->AddCommand(SerialNumber_, Cmd, Storage::CommandExecutionType::COMMAND_EXECUTED);
CommandManager()->PostCommand(CommandManager()->NextRPCId(),SerialNumber_, Cmd.Command, Params, Cmd.UUID, Sent);
WebNotificationSingleDeviceConfigurationChange_t Notification;
Notification.content.serialNumber = D.SerialNumber;
Notification.content.oldUUID = UUID;
Notification.content.newUUID = UpgradedUUID;
WebSocketClientNotificationDeviceConfigurationChange(Notification);
WebSocketClientNotificationDeviceConfigurationChange(D.SerialNumber, UUID, UpgradedUUID);
return true;
}
@@ -449,14 +549,14 @@ namespace OpenWifi {
}
}
bool AP_WS_Connection::StartTelemetry(uint64_t RPCID) {
bool AP_WS_Connection::StartTelemetry(std::uint64_t RPCID) {
poco_information(Logger_, fmt::format("TELEMETRY({}): Starting.", CId_));
Poco::JSON::Object StartMessage;
StartMessage.set("jsonrpc", "2.0");
StartMessage.set("method", "telemetry");
Poco::JSON::Object Params;
Params.set("serial", SerialNumber_);
Params.set("interval", (uint64_t)TelemetryInterval_);
Params.set("interval", TelemetryInterval_);
Poco::JSON::Array Types;
Types.add("wifi-frames");
Types.add("dhcp-snooping");
@@ -470,7 +570,7 @@ namespace OpenWifi {
return Send(OS.str());
}
bool AP_WS_Connection::StopTelemetry(uint64_t RPCID) {
bool AP_WS_Connection::StopTelemetry(std::uint64_t RPCID) {
poco_information(Logger_, fmt::format("TELEMETRY({}): Stopping.", CId_));
Poco::JSON::Object StopMessage;
StopMessage.set("jsonrpc", "2.0");
@@ -493,13 +593,13 @@ namespace OpenWifi {
State_.webSocketClients = TelemetryWebSocketRefCount_;
}
bool AP_WS_Connection::SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t Interval,
uint64_t LifeTime) {
bool AP_WS_Connection::SetWebSocketTelemetryReporting(std::uint64_t RPCID, uint64_t Interval,
uint64_t LifeTime) {
std::unique_lock Lock(TelemetryMutex_);
TelemetryWebSocketRefCount_++;
TelemetryInterval_ = TelemetryInterval_ ? ( Interval< TelemetryInterval_ ? Interval : TelemetryInterval_) : Interval;
auto TelemetryWebSocketTimer = LifeTime + Utils::Now();
TelemetryWebSocketTimer_ = TelemetryWebSocketTimer > TelemetryWebSocketTimer_ ? TelemetryWebSocketTimer : TelemetryWebSocketTimer_;
TelemetryInterval_ = TelemetryInterval_ ? std::min(Interval, TelemetryInterval_) : Interval;
auto TelemetryWebSocketTimer = LifeTime + OpenWifi::Now();
TelemetryWebSocketTimer_ = std::max(TelemetryWebSocketTimer, TelemetryWebSocketTimer_);
UpdateCounts();
if (!TelemetryReporting_) {
TelemetryReporting_ = true;
@@ -508,12 +608,12 @@ namespace OpenWifi {
return true;
}
bool AP_WS_Connection::SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t Interval, uint64_t LifeTime) {
bool AP_WS_Connection::SetKafkaTelemetryReporting(std::uint64_t RPCID, uint64_t Interval, uint64_t LifeTime) {
std::unique_lock Lock(TelemetryMutex_);
TelemetryKafkaRefCount_++;
TelemetryInterval_ = TelemetryInterval_ ? ( Interval<TelemetryInterval_ ? Interval : TelemetryInterval_) : Interval;
auto TelemetryKafkaTimer = LifeTime + Utils::Now();
TelemetryKafkaTimer_ = TelemetryKafkaTimer > TelemetryKafkaTimer_ ? TelemetryKafkaTimer : TelemetryKafkaTimer_;
TelemetryInterval_ = TelemetryInterval_ ? std::min(Interval, TelemetryInterval_) : Interval;
auto TelemetryKafkaTimer = LifeTime + OpenWifi::Now();
TelemetryKafkaTimer_ = std::max(TelemetryKafkaTimer, TelemetryKafkaTimer_);
UpdateCounts();
if (!TelemetryReporting_) {
TelemetryReporting_ = true;
@@ -522,7 +622,7 @@ namespace OpenWifi {
return true;
}
bool AP_WS_Connection::StopWebSocketTelemetry(uint64_t RPCID) {
bool AP_WS_Connection::StopWebSocketTelemetry(std::uint64_t RPCID) {
std::unique_lock Lock(TelemetryMutex_);
if (TelemetryWebSocketRefCount_)
TelemetryWebSocketRefCount_--;
@@ -534,7 +634,7 @@ namespace OpenWifi {
return true;
}
bool AP_WS_Connection::StopKafkaTelemetry(uint64_t RPCID) {
bool AP_WS_Connection::StopKafkaTelemetry(std::uint64_t RPCID) {
std::unique_lock Lock(TelemetryMutex_);
if (TelemetryKafkaRefCount_)
TelemetryKafkaRefCount_--;
@@ -547,19 +647,19 @@ namespace OpenWifi {
}
void AP_WS_Connection::OnSocketShutdown([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ShutdownNotification> &pNf) {
std::lock_guard Guard(Mutex_);
poco_trace(Logger_, fmt::format("SOCKET-SHUTDOWN({}): Closing.", CId_));
return EndConnection();
}
void AP_WS_Connection::OnSocketError([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ErrorNotification> &pNf) {
std::lock_guard Guard(Mutex_);
poco_trace(Logger_, fmt::format("SOCKET-ERROR({}): Closing.", CId_));
return EndConnection();
}
void AP_WS_Connection::OnSocketReadable([[maybe_unused]] const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf) {
if(!Valid_)
return;
std::lock_guard Guard(Mutex_);
if(!AP_WS_Server()->Running())
return EndConnection();
@@ -599,7 +699,7 @@ namespace OpenWifi {
State_.RX += IncomingSize;
State_.MessageCount++;
State_.LastContact = Utils::Now();
State_.LastContact = OpenWifi::Now();
switch (Op) {
case Poco::Net::WebSocket::FRAME_OP_PING: {
@@ -616,7 +716,7 @@ namespace OpenWifi {
PingDetails.set(uCentralProtocol::SERIALNUMBER, SerialNumber_);
PingDetails.set(uCentralProtocol::COMPATIBLE, Compatible_);
PingDetails.set(uCentralProtocol::CONNECTIONIP, CId_);
PingDetails.set(uCentralProtocol::TIMESTAMP, Utils::Now());
PingDetails.set(uCentralProtocol::TIMESTAMP, OpenWifi::Now());
PingDetails.set("locale", State_.locale );
PingObject.set(uCentralProtocol::PING, PingDetails);
Poco::JSON::Stringifier Stringify;

View File

@@ -5,8 +5,6 @@
#pragma once
#include <string>
#include <shared_mutex>
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/JSON/Object.h"
@@ -14,6 +12,7 @@
#include "Poco/Logger.h"
#include "Poco/Net/WebSocket.h"
#include "DeviceRegistry.h"
#include "RESTObjects/RESTAPI_GWobjects.h"
@@ -24,7 +23,7 @@ namespace OpenWifi {
public:
explicit AP_WS_Connection( Poco::Net::HTTPServerRequest &request,
Poco::Net::HTTPServerResponse &response,
uint64_t connection_id,
std::uint64_t connection_id,
Poco::Logger &L,
Poco::Net::SocketReactor &R);
~AP_WS_Connection();
@@ -48,10 +47,10 @@ namespace OpenWifi {
static bool ExtractBase64CompressedData(const std::string & CompressedData, std::string & UnCompressedData, uint64_t compress_sz);
void LogException(const Poco::Exception &E);
inline Poco::Logger & Logger() { return Logger_; }
bool SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t interval, uint64_t TelemetryWebSocketTimer);
bool SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t interval, uint64_t TelemetryKafkaTimer);
bool StopWebSocketTelemetry(uint64_t RPCID);
bool StopKafkaTelemetry(uint64_t RPCID);
bool SetWebSocketTelemetryReporting(std::uint64_t RPCID, uint64_t interval, uint64_t TelemetryWebSocketTimer);
bool SetKafkaTelemetryReporting(std::uint64_t RPCID, uint64_t interval, uint64_t TelemetryKafkaTimer);
bool StopWebSocketTelemetry(std::uint64_t RPCID);
bool StopKafkaTelemetry(std::uint64_t RPCID);
void Process_connect(Poco::JSON::Object::Ptr ParamsObj, const std::string &Serial);
void Process_state(Poco::JSON::Object::Ptr ParamsObj);
@@ -84,10 +83,9 @@ namespace OpenWifi {
}
friend class DeviceRegistry;
friend class AP_WS_Server;
private:
// std::recursive_mutex LocalMutex_;
std::recursive_mutex Mutex_;
std::shared_mutex TelemetryMutex_;
Poco::Logger &Logger_;
Poco::Net::SocketReactor &Reactor_;
@@ -100,28 +98,28 @@ namespace OpenWifi {
std::string CN_;
uint64_t Errors_=0;
Poco::Net::IPAddress PeerAddress_;
volatile bool TelemetryReporting_ = false;
volatile uint64_t TelemetryWebSocketRefCount_ = 0;
volatile uint64_t TelemetryKafkaRefCount_ = 0;
volatile uint64_t TelemetryWebSocketTimer_ = 0;
volatile uint64_t TelemetryKafkaTimer_ = 0 ;
volatile uint64_t TelemetryInterval_ = 0;
volatile uint64_t TelemetryWebSocketPackets_=0;
volatile uint64_t TelemetryKafkaPackets_=0;
std::atomic_bool TelemetryReporting_ = false;
std::atomic_uint64_t TelemetryWebSocketRefCount_ = 0;
std::atomic_uint64_t TelemetryKafkaRefCount_ = 0;
uint64_t TelemetryWebSocketTimer_ = 0;
uint64_t TelemetryKafkaTimer_ = 0 ;
uint64_t TelemetryInterval_ = 0;
std::atomic_uint64_t TelemetryWebSocketPackets_=0;
std::atomic_uint64_t TelemetryKafkaPackets_=0;
GWObjects::ConnectionState State_;
std::string LastStats_;
GWObjects::HealthCheck LastHealthcheck_;
std::chrono::time_point<std::chrono::high_resolution_clock> ConnectionStart_ = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> ConnectionCompletionTime_{0.0};
bool Threaded_=false;
std::atomic_flag Dead_=false;
std::atomic_bool Dead_=false;
std::atomic_bool DeviceValidated_=false;
std::atomic_bool Valid_=false;
static inline std::atomic_uint64_t ConcurrentStartingDevices_=0;
bool StartTelemetry(uint64_t RPCID);
bool StopTelemetry(uint64_t RPCID);
void CompleteStartup();
bool StartTelemetry(std::uint64_t RPCID);
bool StopTelemetry(std::uint64_t RPCID);
void UpdateCounts();
};

View File

@@ -3,8 +3,6 @@
//
#include "AP_WS_Connection.h"
#include "fmt/format.h"
#include "framework/ow_constants.h"
namespace OpenWifi {
void AP_WS_Connection::Process_cfgpending(Poco::JSON::Object::Ptr ParamsObj) {

View File

@@ -6,139 +6,119 @@
#include "AP_WS_Server.h"
#include "StorageService.h"
#include "FindCountry.h"
#include "framework/WebSocketClientNotifications.h"
#include "Daemon.h"
#include "CentralConfig.h"
#include "CommandManager.h"
#include "framework/KafkaManager.h"
#include "framework/utils.h"
#include "UI_GW_WebSocketNotifications.h"
namespace OpenWifi {
void AP_WS_Connection::Process_connect(Poco::JSON::Object::Ptr ParamsObj, const std::string &Serial) {
if (ParamsObj->has(uCentralProtocol::UUID) &&
ParamsObj->has(uCentralProtocol::FIRMWARE) &&
ParamsObj->has(uCentralProtocol::CAPABILITIES)) {
uint64_t UUID = ParamsObj->get(uCentralProtocol::UUID);
auto Firmware = ParamsObj->get(uCentralProtocol::FIRMWARE).toString();
auto CapabilitiesString = ParamsObj->get(uCentralProtocol::CAPABILITIES).toString();
void AP_WS_Connection::Process_connect(Poco::JSON::Object::Ptr ParamsObj, const std::string &Serial) {
if (ParamsObj->has(uCentralProtocol::UUID) &&
ParamsObj->has(uCentralProtocol::FIRMWARE) &&
ParamsObj->has(uCentralProtocol::CAPABILITIES)) {
uint64_t UUID = ParamsObj->get(uCentralProtocol::UUID);
auto Firmware = ParamsObj->get(uCentralProtocol::FIRMWARE).toString();
auto Capabilities = ParamsObj->get(uCentralProtocol::CAPABILITIES).toString();
Config::Capabilities Caps(CapabilitiesString);
Compatible_ = Caps.Compatible();
//// change this
SerialNumber_ = Serial;
SerialNumberInt_ = Utils::SerialNumberToInt(SerialNumber_);
SerialNumber_ = Serial;
SerialNumberInt_ = Utils::SerialNumberToInt(SerialNumber_);
CommandManager()->ClearQueue(SerialNumberInt_);
CommandManager()->ClearQueue(SerialNumberInt_);
DeviceRegistry()->SetSessionDetails(State_.sessionId,SerialNumberInt_);
State_.UUID = UUID;
State_.Firmware = Firmware;
State_.PendingUUID = 0;
State_.Address = Utils::FormatIPv6(WS_->peerAddress().toString());
CId_ = SerialNumber_ + "@" + CId_;
AP_WS_Server()->SetSessionDetails(State_.sessionId,SerialNumberInt_);
State_.UUID = UUID;
State_.Firmware = Firmware;
State_.PendingUUID = 0;
State_.Address = Utils::FormatIPv6(WS_->peerAddress().toString());
CId_ = SerialNumber_ + "@" + CId_;
auto IP = PeerAddress_.toString();
if(IP.substr(0,7)=="::ffff:") {
IP = IP.substr(7);
}
State_.locale = FindCountryFromIP()->Get(IP);
GWObjects::Device DeviceInfo;
auto DeviceExists = StorageService()->GetDevice(SerialNumber_,DeviceInfo);
if (Daemon()->AutoProvisioning() && !DeviceExists) {
StorageService()->CreateDefaultDevice(SerialNumber_, CapabilitiesString, Firmware,
Compatible_, PeerAddress_);
} else if (DeviceExists) {
StorageService()->UpdateDeviceCapabilities(SerialNumber_, CapabilitiesString,
Compatible_);
bool Updated = false;
if(!Firmware.empty()) {
if(Firmware!=DeviceInfo.Firmware) {
DeviceInfo.Firmware = Firmware;
DeviceInfo.LastFWUpdate = Utils::Now();
Updated = true;
WebNotificationSingleDeviceFirmwareChange_t Notification;
Notification.content.serialNumber = SerialNumber_;
Notification.content.newFirmware = Firmware;
WebSocketClientNotificationDeviceFirmwareUpdated(Notification);
} else if(DeviceInfo.LastFWUpdate==0) {
DeviceInfo.LastFWUpdate = Utils::Now();
Updated = true;
}
}
if(DeviceInfo.locale != State_.locale) {
DeviceInfo.locale = State_.locale;
Updated = true;
}
if(Compatible_ != DeviceInfo.DeviceType) {
DeviceInfo.DeviceType = Compatible_;
Updated = true;
}
if(Updated) {
StorageService()->UpdateDevice(DeviceInfo);
}
uint64_t UpgradedUUID=0;
LookForUpgrade(UUID,UpgradedUUID);
State_.UUID = UpgradedUUID;
}
State_.Compatible = Compatible_;
State_.Connected = true;
ConnectionCompletionTime_ = std::chrono::high_resolution_clock::now() - ConnectionStart_;
State_.connectionCompletionTime = ConnectionCompletionTime_.count();
if(State_.VerifiedCertificate == GWObjects::VALID_CERTIFICATE) {
if (( Utils::SerialNumberMatch(CN_, SerialNumber_, AP_WS_Server()->MismatchDepth())) ||
AP_WS_Server()->IsSimSerialNumber(CN_)) {
State_.VerifiedCertificate = GWObjects::VERIFIED;
poco_information(Logger_, fmt::format("CONNECT({}): Fully validated and authenticated device. Session={} ConnectionCompletion Time={}",
CId_,
State_.sessionId,
State_.connectionCompletionTime ));
} else {
State_.VerifiedCertificate = GWObjects::MISMATCH_SERIAL;
if(AP_WS_Server()->AllowSerialNumberMismatch()) {
poco_information(
Logger_, fmt::format("CONNECT({}): Serial number mismatch allowed. CN={} Serial={} Session={} ConnectionCompletion Time={}",
CId_, CN_, SerialNumber_, State_.sessionId,
State_.connectionCompletionTime));
} else {
poco_information(
Logger_, fmt::format("CONNECT({}): Serial number mismatch disallowed. Device rejected. CN={} Serial={} Session={} ConnectionCompletion Time={}",
CId_, CN_, SerialNumber_, State_.sessionId,
State_.connectionCompletionTime));
return EndConnection();
}
}
}
WebNotificationSingleDevice_t Notification;
Notification.content.serialNumber = SerialNumber_;
WebSocketClientNotificationDeviceConnected(Notification);
// std::cout << "Serial: " << SerialNumber_ << "Session: " << State_.sessionId << std::endl;
if (KafkaManager()->Enabled()) {
Poco::JSON::Stringifier Stringify;
ParamsObj->set(uCentralProtocol::CONNECTIONIP, CId_);
ParamsObj->set("locale", State_.locale );
ParamsObj->set(uCentralProtocol::TIMESTAMP, Utils::Now());
std::ostringstream OS;
Stringify.condense(ParamsObj, OS);
KafkaManager()->PostMessage(KafkaTopics::CONNECTION, SerialNumber_, OS.str());
}
} else {
poco_warning(Logger_,fmt::format("INVALID-PROTOCOL({}): Missing one of uuid, firmware, or capabilities", CId_));
Errors_++;
auto IP = PeerAddress_.toString();
if(IP.substr(0,7)=="::ffff:") {
IP = IP.substr(7);
}
State_.locale = FindCountryFromIP()->Get(IP);
GWObjects::Device DeviceInfo;
auto DeviceExists = StorageService()->GetDevice(SerialNumber_,DeviceInfo);
if (Daemon()->AutoProvisioning() && !DeviceExists) {
StorageService()->CreateDefaultDevice(SerialNumber_, Capabilities, Firmware,
Compatible_, PeerAddress_);
} else if (DeviceExists) {
StorageService()->UpdateDeviceCapabilities(SerialNumber_, Capabilities,
Compatible_);
bool Updated = false;
if(!Firmware.empty() && Firmware!=DeviceInfo.Firmware) {
DeviceInfo.Firmware = Firmware;
Updated = true;
WebSocketClientNotificationDeviceFirmwareUpdated(SerialNumber_, Firmware);
}
if(DeviceInfo.locale != State_.locale) {
DeviceInfo.locale = State_.locale;
Updated = true;
}
if(Compatible_ != DeviceInfo.DeviceType) {
DeviceInfo.DeviceType = Compatible_;
Updated = true;
}
if(Updated) {
StorageService()->UpdateDevice(DeviceInfo);
}
uint64_t UpgradedUUID=0;
LookForUpgrade(UUID,UpgradedUUID);
State_.UUID = UpgradedUUID;
}
State_.Compatible = Compatible_;
State_.Connected = true;
ConnectionCompletionTime_ = std::chrono::high_resolution_clock::now() - ConnectionStart_;
State_.connectionCompletionTime = ConnectionCompletionTime_.count();
if(State_.VerifiedCertificate == GWObjects::VALID_CERTIFICATE) {
if (( Utils::SerialNumberMatch(CN_, SerialNumber_, AP_WS_Server()->MismatchDepth())) ||
AP_WS_Server()->IsSimSerialNumber(CN_)) {
State_.VerifiedCertificate = GWObjects::VERIFIED;
poco_information(Logger_, fmt::format("CONNECT({}): Fully validated and authenticated device. Session={} ConnectionCompletion Time={}",
CId_,
State_.sessionId,
State_.connectionCompletionTime ));
} else {
State_.VerifiedCertificate = GWObjects::MISMATCH_SERIAL;
if(AP_WS_Server()->AllowSerialNumberMismatch()) {
poco_information(
Logger_, fmt::format("CONNECT({}): Serial number mismatch allowed. CN={} Serial={} Session={} ConnectionCompletion Time={}",
CId_, CN_, SerialNumber_, State_.sessionId,
State_.connectionCompletionTime));
} else {
poco_information(
Logger_, fmt::format("CONNECT({}): Serial number mismatch disallowed. Device rejected. CN={} Serial={} Session={} ConnectionCompletion Time={}",
CId_, CN_, SerialNumber_, State_.sessionId,
State_.connectionCompletionTime));
return EndConnection();
}
}
}
WebSocketClientNotificationDeviceConnected(SerialNumber_);
if (KafkaManager()->Enabled()) {
Poco::JSON::Stringifier Stringify;
ParamsObj->set(uCentralProtocol::CONNECTIONIP, CId_);
ParamsObj->set("locale", State_.locale );
ParamsObj->set(uCentralProtocol::TIMESTAMP, OpenWifi::Now());
std::ostringstream OS;
Stringify.condense(ParamsObj, OS);
KafkaManager()->PostMessage(KafkaTopics::CONNECTION, SerialNumber_, OS.str());
}
} else {
poco_warning(Logger_,fmt::format("INVALID-PROTOCOL({}): Missing one of uuid, firmware, or capabilities", CId_));
Errors_++;
}
}
}

View File

@@ -5,10 +5,6 @@
#include "AP_WS_Connection.h"
#include "StorageService.h"
#include "framework/utils.h"
#include "framework/ow_constants.h"
#include "fmt/format.h"
namespace OpenWifi {
void AP_WS_Connection::Process_crashlog(Poco::JSON::Object::Ptr ParamsObj) {
if (ParamsObj->has(uCentralProtocol::UUID) && ParamsObj->has(uCentralProtocol::LOGLINES)) {

View File

@@ -5,8 +5,6 @@
#include "AP_WS_Connection.h"
#include "StorageService.h"
#include "fmt/format.h"
namespace OpenWifi {
void AP_WS_Connection::Process_deviceupdate(Poco::JSON::Object::Ptr ParamsObj, std::string &Serial) {

View File

@@ -5,10 +5,6 @@
#include "AP_WS_Connection.h"
#include "StorageService.h"
#include "framework/KafkaManager.h"
#include "framework/utils.h"
#include "fmt/format.h"
namespace OpenWifi {
void AP_WS_Connection::Process_healthcheck(Poco::JSON::Object::Ptr ParamsObj) {
@@ -46,7 +42,7 @@ void AP_WS_Connection::Process_healthcheck(Poco::JSON::Object::Ptr ParamsObj) {
GWObjects::HealthCheck Check;
Check.SerialNumber = SerialNumber_;
Check.Recorded = Utils::Now();
Check.Recorded = OpenWifi::Now();
Check.UUID = UUID;
Check.Data = CheckData;
Check.Sanity = Sanity;
@@ -61,7 +57,7 @@ void AP_WS_Connection::Process_healthcheck(Poco::JSON::Object::Ptr ParamsObj) {
if (KafkaManager()->Enabled()) {
Poco::JSON::Stringifier Stringify;
std::ostringstream OS;
ParamsObj->set("timestamp", Utils::Now());
ParamsObj->set("timestamp", OpenWifi::Now());
Stringify.condense(ParamsObj, OS);
KafkaManager()->PostMessage(KafkaTopics::HEALTHCHECK, SerialNumber_, OS.str());
}

View File

@@ -5,9 +5,6 @@
#include "AP_WS_Connection.h"
#include "StorageService.h"
#include "framework/ow_constants.h"
#include "fmt/format.h"
namespace OpenWifi {
void AP_WS_Connection::Process_log(Poco::JSON::Object::Ptr ParamsObj) {
if (!State_.Connected) {

View File

@@ -3,8 +3,6 @@
//
#include "AP_WS_Connection.h"
#include "fmt/format.h"
#include "framework/ow_constants.h"
namespace OpenWifi {
void AP_WS_Connection::Process_ping(Poco::JSON::Object::Ptr ParamsObj) {

View File

@@ -6,10 +6,6 @@
#include "StorageService.h"
#include "CommandManager.h"
#include "framework/ow_constants.h"
#include "framework/MicroServiceFuncs.h"
#include "fmt/format.h"
namespace OpenWifi {
void AP_WS_Connection::Process_recovery(Poco::JSON::Object::Ptr ParamsObj) {
if (ParamsObj->has(uCentralProtocol::SERIAL) &&
@@ -40,7 +36,7 @@ namespace OpenWifi {
if (ParamsObj->get(uCentralProtocol::REBOOT).toString() == "true") {
GWObjects::CommandDetails Cmd;
Cmd.SerialNumber = SerialNumber_;
Cmd.UUID = MicroServiceCreateUUID();
Cmd.UUID = MicroService::CreateUUID();
Cmd.SubmittedBy = uCentralProtocol::SUBMITTED_BY_SYSTEM;
Cmd.Status = uCentralProtocol::PENDING;
Cmd.Command = uCentralProtocol::REBOOT;

View File

@@ -4,15 +4,9 @@
#include "AP_WS_Connection.h"
#include "StorageService.h"
#include "framework/WebSocketClientNotifications.h"
#include "StateUtils.h"
#include "UI_GW_WebSocketNotifications.h"
#include "framework/KafkaManager.h"
#include "framework/utils.h"
#include "fmt/format.h"
namespace OpenWifi {
void AP_WS_Connection::Process_state(Poco::JSON::Object::Ptr ParamsObj) {
if (!State_.Connected) {
@@ -45,7 +39,7 @@ namespace OpenWifi {
GWObjects::Statistics Stats{
.SerialNumber = SerialNumber_, .UUID = UUID, .Data = StateStr};
Stats.Recorded = Utils::Now();
Stats.Recorded = OpenWifi::Now();
StorageService()->AddStatisticsData(Stats);
if (!request_uuid.empty()) {
StorageService()->SetCommandResult(request_uuid, StateStr);
@@ -61,9 +55,10 @@ namespace OpenWifi {
KafkaManager()->PostMessage(KafkaTopics::STATE, SerialNumber_, OS.str());
}
WebNotificationSingleDevice_t N;
WebSocketNotification<WebNotificationSingleDevice> N;
N.content.serialNumber = SerialNumber_;
WebSocketClientNotificationDeviceStatistics(N);
N.type = "device_statistics";
WebSocketClientServer()->SendNotification(N);
} else {
poco_warning(Logger_, fmt::format("STATE({}): Invalid request. Missing serial, uuid, or state", CId_));

View File

@@ -6,10 +6,6 @@
#include "TelemetryStream.h"
#include "CommandManager.h"
#include "framework/KafkaManager.h"
#include "framework/utils.h"
#include "fmt/format.h"
namespace OpenWifi {
void AP_WS_Connection::Process_telemetry(Poco::JSON::Object::Ptr ParamsObj) {
if (!State_.Connected) {
@@ -18,20 +14,19 @@ namespace OpenWifi {
Errors_++;
return;
}
poco_trace(Logger_,fmt::format("Telemetry data received for {}", SerialNumber_));
if (TelemetryReporting_) {
if (ParamsObj->has("data")) {
auto Payload = ParamsObj->get("data").extract<Poco::JSON::Object::Ptr>();
Payload->set("timestamp", Utils::Now());
Payload->set("timestamp", OpenWifi::Now());
std::ostringstream SS;
Payload->stringify(SS);
auto now=Utils::Now();
auto now=OpenWifi::Now();
if (TelemetryWebSocketRefCount_) {
if(now<TelemetryWebSocketTimer_) {
// std::cout << SerialNumber_ << ": Updating WebSocket telemetry" << std::endl;
TelemetryWebSocketPackets_++;
State_.websocketPackets = TelemetryWebSocketPackets_;
TelemetryStream()->NotifyEndPoint(SerialNumberInt_, SS.str());
TelemetryStream()->UpdateEndPoint(SerialNumberInt_, SS.str());
} else {
StopWebSocketTelemetry(CommandManager()->NextRPCId());
}

View File

@@ -10,8 +10,6 @@
#include "Poco/Net/SocketAcceptor.h"
#include "Poco/Environment.h"
#include "framework/utils.h"
namespace OpenWifi {
class AP_WS_ReactorThreadPool {
public:

View File

@@ -7,19 +7,13 @@
//
#include "Poco/Net/HTTPHeaderStream.h"
#include "Poco/JSON/Array.h"
#include "Poco/Net/Context.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "AP_WS_Server.h"
#include "AP_WS_Connection.h"
#include "ConfigurationCache.h"
#include "TelemetryStream.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
#include "UI_GW_WebSocketNotifications.h"
#include "fmt/format.h"
namespace OpenWifi {
void AP_WS_RequestHandler::handleRequest(Poco::Net::HTTPServerRequest &request,
@@ -44,8 +38,8 @@ namespace OpenWifi {
int AP_WS_Server::Start() {
AllowSerialNumberMismatch_ = MicroServiceConfigGetBool("openwifi.certificates.allowmismatch",true);
MismatchDepth_ = MicroServiceConfigGetInt("openwifi.certificates.mismatchdepth",2);
AllowSerialNumberMismatch_ = MicroService::instance().ConfigGetBool("openwifi.certificates.allowmismatch",true);
MismatchDepth_ = MicroService::instance().ConfigGetInt("openwifi.certificates.mismatchdepth",2);
Reactor_pool_ = std::make_unique<AP_WS_ReactorThreadPool>();
Reactor_pool_->Start();
@@ -76,11 +70,11 @@ namespace OpenWifi {
auto Context = Poco::AutoPtr<Poco::Net::Context>(new Poco::Net::Context(Poco::Net::Context::TLS_SERVER_USE, P));
/* if(!Svr.KeyFilePassword().empty()) {
if(!Svr.KeyFilePassword().empty()) {
auto PassphraseHandler = Poco::SharedPtr<MyPrivateKeyPassphraseHandler>( new MyPrivateKeyPassphraseHandler(Svr.KeyFilePassword(),Logger()));
Poco::Net::SSLManager::instance().initializeServer(PassphraseHandler, nullptr,Context);
}
*/
Poco::Crypto::X509Certificate Cert(Svr.CertFile());
Poco::Crypto::X509Certificate Root(Svr.RootCA());
@@ -132,7 +126,7 @@ namespace OpenWifi {
ReactorThread_.start(Reactor_);
auto ProvString = MicroServiceConfigGetString("autoprovisioning.process","default");
auto ProvString = MicroService::instance().ConfigGetString("autoprovisioning.process","default");
if(ProvString!="default") {
auto Tokens = Poco::StringTokenizer(ProvString, ",");
for (const auto &i : Tokens) {
@@ -145,72 +139,18 @@ namespace OpenWifi {
UseDefaultConfig_ = true;
}
SimulatorId_ = MicroServiceConfigGetString("simulatorid","");
SimulatorId_ = MicroService::instance().ConfigGetString("simulatorid","");
SimulatorEnabled_ = !SimulatorId_.empty();
Utils::SetThreadName(ReactorThread_,"dev:react:head");
GarbageCollectorCallback_ = std::make_unique<Poco::TimerCallback<AP_WS_Server>>(*this,&AP_WS_Server::onGarbageCollecting);
Timer_.setStartInterval(10 * 1000);
Timer_.setPeriodicInterval(5 * 1000); // every minute
Timer_.start(*GarbageCollectorCallback_, MicroServiceTimerPool());
Running_ = true;
return 0;
}
void AP_WS_Server::onGarbageCollecting([[maybe_unused]] Poco::Timer &timer) {
std::lock_guard Lock(LocalMutex_);
if(Garbage_.size()>0) {
std::cout << "Removing " << Garbage_.size() << " old connections." << std::endl;
Garbage_.clear();
}
static uint64_t last_log = Utils::Now();
NumberOfConnectedDevices_ = 0;
NumberOfConnectingDevices_ = 0;
AverageDeviceConnectionTime_ = 0;
uint64_t total_connected_time=0;
auto now = Utils::Now();
for (auto connection=SerialNumbers_.begin(); connection!=SerialNumbers_.end();) {
if(connection->second.second== nullptr) {
connection++;
continue;
}
if (connection->second.second->State_.Connected) {
NumberOfConnectedDevices_++;
total_connected_time += (now - connection->second.second->State_.started);
connection++;
} else {
NumberOfConnectingDevices_++;
connection++;
}
}
AverageDeviceConnectionTime_ = (NumberOfConnectedDevices_!=0) ? total_connected_time/NumberOfConnectedDevices_ : 0;
if((now-last_log)>120) {
last_log = now;
poco_information(Logger(),
fmt::format("Active AP connections: {} Connecting: {} Average connection time: {} seconds",
NumberOfConnectedDevices_, NumberOfConnectingDevices_, AverageDeviceConnectionTime_));
}
WebSocketClientNotificationNumberOfConnection_t Notification;
Notification.content.numberOfConnectingDevices = NumberOfConnectingDevices_;
Notification.content.numberOfDevices = NumberOfConnectedDevices_;
Notification.content.averageConnectedTime = AverageDeviceConnectionTime_;
WebSocketClientNotificationNumberOfConnections(Notification);
}
void AP_WS_Server::Stop() {
poco_information(Logger(),"Stopping...");
Running_ = false;
Timer_.stop();
for(auto &server:WebServers_) {
server->stopAll();
}
@@ -220,198 +160,4 @@ namespace OpenWifi {
poco_information(Logger(),"Stopped...");
}
bool AP_WS_Server::GetStatistics(uint64_t SerialNumber, std::string &Statistics) const {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device == SerialNumbers_.end() || Device->second.second==nullptr)
return false;
Statistics = Device->second.second->LastStats_;
return true;
}
bool AP_WS_Server::GetState(uint64_t SerialNumber, GWObjects::ConnectionState & State) const {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device == SerialNumbers_.end() || Device->second.second==nullptr)
return false;
State = Device->second.second->State_;
return true;
}
bool AP_WS_Server::GetHealthcheck(uint64_t SerialNumber, GWObjects::HealthCheck & CheckData) const {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device == SerialNumbers_.end() || Device->second.second==nullptr)
return false;
CheckData = Device->second.second->LastHealthcheck_;
return true;
}
void AP_WS_Server::SetSessionDetails(uint64_t connection_id, uint64_t SerialNumber) {
std::lock_guard Lock(LocalMutex_);
auto Conn = Sessions_.find(connection_id);
if(Conn == end(Sessions_))
return;
auto CurrentSerialNumber = SerialNumbers_.find(SerialNumber);
if( (CurrentSerialNumber==SerialNumbers_.end()) ||
(CurrentSerialNumber->second.first<connection_id)) {
SerialNumbers_[SerialNumber] = std::make_pair(connection_id, Conn->second.first);
return;
}
}
bool AP_WS_Server::EndSession(uint64_t session_id, uint64_t serial_number) {
std::unique_lock G(LocalMutex_);
auto Session = Sessions_.find(session_id);
if(Session==end(Sessions_))
return false;
Garbage_.push_back(Session->second.first);
auto Device = SerialNumbers_.find(serial_number);
if (Device == end(SerialNumbers_)) {
Sessions_.erase(Session);
return false;
}
if(Device->second.first==session_id) {
Sessions_.erase(Session);
SerialNumbers_.erase(Device);
return true;
}
Sessions_.erase(Session);
return false;
}
bool AP_WS_Server::Connected(uint64_t SerialNumber) const {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second== nullptr)
return false;
return Device->second.second->State_.Connected;
}
bool AP_WS_Server::SendFrame(uint64_t SerialNumber, const std::string & Payload) const {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==SerialNumbers_.end() || Device->second.second== nullptr)
return false;
try {
// std::cout << "Device connection pointer: " << (uint64_t) Device->second.second << std::endl;
return Device->second.second->Send(Payload);
} catch (...) {
poco_debug(Logger(),fmt::format(": SendFrame: Could not send data to device '{}'", Utils::IntToSerialNumber(SerialNumber)));
}
return false;
}
void AP_WS_Server::StopWebSocketTelemetry(uint64_t RPCID, uint64_t SerialNumber) {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second==nullptr)
return;
Device->second.second->StopWebSocketTelemetry(RPCID);
}
void AP_WS_Server::SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime) {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second==nullptr)
return;
Device->second.second->SetWebSocketTelemetryReporting(RPCID, Interval, Lifetime);
}
void AP_WS_Server::SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime) {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second== nullptr)
return;
Device->second.second->SetKafkaTelemetryReporting(RPCID, Interval, Lifetime);
}
void AP_WS_Server::StopKafkaTelemetry(uint64_t RPCID, uint64_t SerialNumber) {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second== nullptr)
return;
Device->second.second->StopKafkaTelemetry(RPCID);
}
void AP_WS_Server::GetTelemetryParameters(uint64_t SerialNumber , bool & TelemetryRunning,
uint64_t & TelemetryInterval,
uint64_t & TelemetryWebSocketTimer,
uint64_t & TelemetryKafkaTimer,
uint64_t & TelemetryWebSocketCount,
uint64_t & TelemetryKafkaCount,
uint64_t & TelemetryWebSocketPackets,
uint64_t & TelemetryKafkaPackets) {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_)|| Device->second.second== nullptr)
return;
Device->second.second->GetTelemetryParameters(TelemetryRunning,
TelemetryInterval,
TelemetryWebSocketTimer,
TelemetryKafkaTimer,
TelemetryWebSocketCount,
TelemetryKafkaCount,
TelemetryWebSocketPackets,
TelemetryKafkaPackets);
}
bool AP_WS_Server::SendRadiusAccountingData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size) {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(Utils::SerialNumberToInt(SerialNumber));
if(Device==SerialNumbers_.end() || Device->second.second== nullptr)
return false;
try {
return Device->second.second->SendRadiusAccountingData(buffer,size);
} catch (...) {
poco_debug(Logger(),fmt::format(": SendRadiusAuthenticationData: Could not send data to device '{}'", SerialNumber));
}
return false;
}
bool AP_WS_Server::SendRadiusAuthenticationData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size) {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(Utils::SerialNumberToInt(SerialNumber));
if(Device==SerialNumbers_.end() || Device->second.second== nullptr)
return false;
try {
return Device->second.second->SendRadiusAuthenticationData(buffer,size);
} catch (...) {
poco_debug(Logger(),fmt::format(": SendRadiusAuthenticationData: Could not send data to device '{}'", SerialNumber));
}
return false;
}
bool AP_WS_Server::SendRadiusCoAData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size) {
std::lock_guard Lock(LocalMutex_);
auto Device = SerialNumbers_.find(Utils::SerialNumberToInt(SerialNumber));
if(Device==SerialNumbers_.end() || Device->second.second== nullptr)
return false;
try {
return Device->second.second->SendRadiusCoAData(buffer,size);
} catch (...) {
poco_debug(Logger(),fmt::format(": SendRadiusCoAData: Could not send data to device '{}'", SerialNumber));
}
return false;
}
} //namespace

View File

@@ -13,27 +13,21 @@
#include <array>
#include <ctime>
#include "framework/MicroService.h"
#include "Poco/AutoPtr.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/ParallelSocketAcceptor.h"
#include "Poco/Net/SocketAcceptor.h"
#include "Poco/Timer.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "AP_WS_Connection.h"
#include "AP_WS_ReactorPool.h"
#include "framework/utils.h"
#include "framework/SubSystemServer.h"
namespace OpenWifi {
class AP_WS_RequestHandler : public Poco::Net::HTTPRequestHandler {
public:
explicit AP_WS_RequestHandler(Poco::Logger &L, uint64_t id)
explicit AP_WS_RequestHandler(Poco::Logger &L, std::uint64_t id)
: Logger_(L),
id_(id){
};
@@ -42,7 +36,7 @@ namespace OpenWifi {
Poco::Net::HTTPServerResponse &response) override;
private:
Poco::Logger &Logger_;
uint64_t id_=0;
std::uint64_t id_=0;
};
class AP_WS_RequestHandlerFactory : public Poco::Net::HTTPRequestHandlerFactory {
@@ -63,7 +57,7 @@ namespace OpenWifi {
}
private:
Poco::Logger &Logger_;
inline static uint64_t id_=1;
inline static std::uint64_t id_=1;
};
class AP_WS_Server : public SubSystemServer {
@@ -95,7 +89,7 @@ namespace OpenWifi {
return AllowSerialNumberMismatch_;
}
inline uint64_t MismatchDepth() const {
inline std::uint64_t MismatchDepth() const {
return MismatchDepth_;
}
@@ -105,99 +99,42 @@ namespace OpenWifi {
[[nodiscard]] inline Poco::Net::SocketReactor & NextReactor() { return Reactor_pool_->NextReactor(); }
[[nodiscard]] inline bool Running() const { return Running_; }
inline void AddConnection(uint64_t session_id, std::shared_ptr<AP_WS_Connection> Connection ) {
std::lock_guard Lock(LocalMutex_);
Sessions_[session_id] = std::make_pair(std::move(Connection),false);
inline void AddConnection(std::uint64_t session_id, std::shared_ptr<AP_WS_Connection> Connection ) {
std::unique_lock Lock(LocalMutex_);
Connections_[session_id] = Connection;
}
inline std::shared_ptr<AP_WS_Connection> FindConnection(uint64_t session_id) const {
std::lock_guard Lock(LocalMutex_);
inline void DeleteConnection(std::uint64_t session_id) {
std::unique_lock Lock(LocalMutex_);
Connections_.erase(session_id);
}
auto Connection = Sessions_.find(session_id);
if(Connection!=end(Sessions_))
return Connection->second.first;
inline std::shared_ptr<AP_WS_Connection> FindConnection(std::uint64_t session_id) const {
std::shared_lock Lock(LocalMutex_);
auto Connection = Connections_.find(session_id);
if(Connection!=end(Connections_))
return Connection->second;
return nullptr;
}
inline bool GetStatistics(const std::string &SerialNumber, std::string & Statistics) const {
return GetStatistics(Utils::SerialNumberToInt(SerialNumber),Statistics);
}
bool GetStatistics(uint64_t SerialNumber, std::string & Statistics) const ;
inline bool GetState(const std::string & SerialNumber, GWObjects::ConnectionState & State) const {
return GetState(Utils::SerialNumberToInt(SerialNumber), State);
}
bool GetState(uint64_t SerialNumber, GWObjects::ConnectionState & State) const;
inline bool GetHealthcheck(const std::string &SerialNumber, GWObjects::HealthCheck & CheckData) const {
return GetHealthcheck(Utils::SerialNumberToInt(SerialNumber), CheckData);
}
bool GetHealthcheck(uint64_t SerialNumber, GWObjects::HealthCheck & CheckData) const ;
bool Connected(uint64_t SerialNumber) const ;
inline bool SendFrame(const std::string & SerialNumber, const std::string & Payload) const {
return SendFrame(Utils::SerialNumberToInt(SerialNumber), Payload);
}
bool SendFrame(uint64_t SerialNumber, const std::string & Payload) const ;
bool SendRadiusAuthenticationData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size);
bool SendRadiusAccountingData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size);
bool SendRadiusCoAData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size);
void SetSessionDetails(uint64_t connection_id, uint64_t SerialNumber);
bool EndSession(uint64_t connection_id, uint64_t serial_number);
void SetWebSocketTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime);
void StopWebSocketTelemetry(uint64_t RPCID, uint64_t SerialNumber);
void SetKafkaTelemetryReporting(uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime);
void StopKafkaTelemetry(uint64_t RPCID, uint64_t SerialNumber);
void GetTelemetryParameters(uint64_t SerialNumber , bool & TelemetryRunning,
uint64_t & TelemetryInterval,
uint64_t & TelemetryWebSocketTimer,
uint64_t & TelemetryKafkaTimer,
uint64_t & TelemetryWebSocketCount,
uint64_t & TelemetryKafkaCount,
uint64_t & TelemetryWebSocketPackets,
uint64_t & TelemetryKafkaPackets);
void onGarbageCollecting(Poco::Timer & timer);
inline void AverageDeviceStatistics( uint64_t & Connections, uint64_t & AverageConnectionTime, uint64_t & NumberOfConnectingDevices) const {
Connections = NumberOfConnectedDevices_;
AverageConnectionTime = AverageDeviceConnectionTime_;
NumberOfConnectingDevices = NumberOfConnectingDevices_;
}
private:
mutable std::recursive_mutex LocalMutex_;
mutable std::shared_mutex LocalMutex_;
std::unique_ptr<Poco::Crypto::X509Certificate> IssuerCert_;
std::list<std::unique_ptr<Poco::Net::HTTPServer>> WebServers_;
Poco::Net::SocketReactor Reactor_;
Poco::Thread ReactorThread_;
std::string SimulatorId_;
Poco::ThreadPool DeviceConnectionPool_{"ws:dev-pool", 2, 64};
Poco::ThreadPool DeviceConnectionPool_{"ws:dev-pool", 2, 32};
bool LookAtProvisioning_ = false;
bool UseDefaultConfig_ = true;
bool SimulatorEnabled_=false;
std::unique_ptr<AP_WS_ReactorThreadPool> Reactor_pool_;
std::atomic_bool Running_=false;
std::map<uint64_t, std::pair<std::shared_ptr<AP_WS_Connection>,bool>> Sessions_;
std::map<uint64_t, std::pair<uint64_t,std::shared_ptr<AP_WS_Connection>>> SerialNumbers_;
std::map<std::uint64_t, std::shared_ptr<AP_WS_Connection>> Connections_;
std::atomic_bool AllowSerialNumberMismatch_=true;
std::atomic_uint64_t MismatchDepth_=2;
std::atomic_uint64_t NumberOfConnectedDevices_=0;
std::atomic_uint64_t AverageDeviceConnectionTime_=0;
std::atomic_uint64_t NumberOfConnectingDevices_=0;
std::vector<std::shared_ptr<AP_WS_Connection>> Garbage_;
std::unique_ptr<Poco::TimerCallback<AP_WS_Server>> GarbageCollectorCallback_;
Poco::Timer Timer_;
Poco::Thread GarbageCollector_;
AP_WS_Server() noexcept:
SubSystemServer("WebSocketServer", "WS-SVR", "ucentral.websocket") {
}

View File

@@ -4,12 +4,7 @@
#pragma once
#include <string>
#include <map>
#include <mutex>
#include <fstream>
#include "framework/MicroServiceFuncs.h"
#include "framework/MicroService.h"
#include "nlohmann/json.hpp"
@@ -97,8 +92,8 @@ namespace OpenWifi {
std::atomic_bool CapabilitiesLoaded_=false;
std::map<std::string,std::string> Platforms_;
CapabilitiesCache_t Capabilities_;
std::string PlatformCacheFileName_{ MicroServiceDataDirectory()+PlatformCacheFileName };
std::string CapabilitiesCacheFileName_{ MicroServiceDataDirectory()+CapabilitiesCacheFileName };
std::string PlatformCacheFileName_{ MicroService::instance().DataDir()+PlatformCacheFileName };
std::string CapabilitiesCacheFileName_{ MicroService::instance().DataDir()+CapabilitiesCacheFileName };
inline void LoadPlatforms() {
try {

View File

@@ -7,6 +7,8 @@
//
#include <fstream>
#include "framework/MicroService.h"
#include "Poco/JSON/Object.h"
#include "Poco/JSON/Parser.h"
#include "Poco/File.h"

View File

@@ -8,16 +8,14 @@
#include <algorithm>
#include "framework/MicroService.h"
#include "Poco/JSON/Parser.h"
#include "CommandManager.h"
#include "AP_WS_Server.h"
#include "DeviceRegistry.h"
#include "StorageService.h"
#include "framework/ow_constants.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
using namespace std::chrono_literals;
namespace OpenWifi {
@@ -43,7 +41,7 @@ namespace OpenWifi {
uint64_t ID = Payload.get(uCentralProtocol::ID);
poco_debug(Logger(),fmt::format("({}): Processing {} response.", SerialNumber, ID));
if (ID > 1) {
std::lock_guard Lock(LocalMutex_);
std::unique_lock Lock(LocalMutex_);
auto RPC = OutStandingRequests_.find(ID);
if (RPC == OutStandingRequests_.end() ||
RPC->second.SerialNumber !=
@@ -85,12 +83,12 @@ namespace OpenWifi {
JanitorCallback_ = std::make_unique<Poco::TimerCallback<CommandManager>>(*this,&CommandManager::onJanitorTimer);
JanitorTimer_.setStartInterval( 10000 );
JanitorTimer_.setPeriodicInterval(10 * 60 * 1000); // 1 hours
JanitorTimer_.start(*JanitorCallback_, MicroServiceTimerPool());
JanitorTimer_.start(*JanitorCallback_, MicroService::instance().TimerPool());
CommandRunnerCallback_ = std::make_unique<Poco::TimerCallback<CommandManager>>(*this,&CommandManager::onCommandRunnerTimer);
CommandRunnerTimer_.setStartInterval( 10000 );
CommandRunnerTimer_.setPeriodicInterval(30 * 1000); // 1 hours
CommandRunnerTimer_.start(*CommandRunnerCallback_, MicroServiceTimerPool());
CommandRunnerTimer_.start(*CommandRunnerCallback_, MicroService::instance().TimerPool());
return 0;
}
@@ -112,7 +110,7 @@ namespace OpenWifi {
}
void CommandManager::onJanitorTimer([[maybe_unused]] Poco::Timer & timer) {
std::lock_guard Lock(LocalMutex_);
std::unique_lock Lock(LocalMutex_);
Utils::SetThreadName("cmd:janitor");
Poco::Logger & MyLogger = Poco::Logger::get("CMD-MGR-JANITOR");
auto now = std::chrono::high_resolution_clock::now();
@@ -133,7 +131,7 @@ namespace OpenWifi {
}
bool CommandManager::IsCommandRunning(const std::string &C) {
std::lock_guard Lock(LocalMutex_);
std::shared_lock Lock(LocalMutex_);
for (const auto &request : OutStandingRequests_) {
if (request.second.UUID == C) {
return true;
@@ -170,7 +168,7 @@ namespace OpenWifi {
if(IsCommandRunning(Cmd.UUID))
continue;
auto now = Utils::Now();
auto now = OpenWifi::Now();
// 2 hour timeout for commands
if ((now - Cmd.Submitted) > (1 * 60 * 60)) {
poco_information(
@@ -180,7 +178,7 @@ namespace OpenWifi {
continue;
}
if (!AP_WS_Server()->Connected(
if (!DeviceRegistry()->Connected(
Utils::SerialNumberToInt(Cmd.SerialNumber))) {
poco_trace(
MyLogger,
@@ -270,7 +268,7 @@ namespace OpenWifi {
Idx.rpc_entry = disk_only ? nullptr : std::make_shared<CommandManager::promise_type_t>();
poco_debug(Logger(), fmt::format("{}: Sending command. ID: {}", UUID, RPCID));
if(AP_WS_Server()->SendFrame(SerialNumber, ToSend.str())) {
if(DeviceRegistry()->SendFrame(SerialNumber, ToSend.str())) {
if(!oneway_rpc) {
std::lock_guard M(Mutex_);
OutStandingRequests_[RPCID] = Idx;

View File

@@ -15,15 +15,12 @@
#include <functional>
#include <shared_mutex>
#include "framework/MicroService.h"
#include "Poco/JSON/Object.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Timer.h"
#include "Poco/Notification.h"
#include "Poco/NotificationQueue.h"
#include "framework/SubSystemServer.h"
#include "fmt/format.h"
#include "RESTObjects/RESTAPI_GWobjects.h"
@@ -156,7 +153,7 @@ namespace OpenWifi {
}
inline bool CommandRunningForDevice(std::uint64_t SerialNumber, std::string & uuid, std::string &command) {
std::lock_guard Lock(LocalMutex_);
std::shared_lock Lock(LocalMutex_);
for(const auto &[Request,Command]:OutStandingRequests_) {
if(Command.SerialNumber==SerialNumber) {
@@ -169,7 +166,7 @@ namespace OpenWifi {
}
inline void ClearQueue(std::uint64_t SerialNumber) {
std::lock_guard Lock(LocalMutex_);
std::unique_lock Lock(LocalMutex_);
for(auto Request = OutStandingRequests_.begin(); Request != OutStandingRequests_.end() ; ) {
if(Request->second.SerialNumber==SerialNumber)
Request = OutStandingRequests_.erase(Request);
@@ -179,7 +176,7 @@ namespace OpenWifi {
}
private:
mutable std::recursive_mutex LocalMutex_;
mutable std::shared_mutex LocalMutex_;
std::atomic_bool Running_ = false;
Poco::Thread ManagerThread;
std::atomic_uint64_t Id_=3; // do not start @1. We ignore ID=1 & 0 is illegal..

View File

@@ -7,6 +7,7 @@
#include <map>
#include <string>
#include <mutex>
#include "framework/MicroService.h"
namespace OpenWifi {
class ConfigurationCache {

View File

@@ -6,6 +6,8 @@
// Arilia Wireless Inc.
//
#include "framework/MicroService.h"
#include "Poco/Util/Application.h"
#include "Poco/Util/Option.h"
#include "Poco/Environment.h"
@@ -15,6 +17,7 @@
#include "AP_WS_Server.h"
#include "CommandManager.h"
#include "Daemon.h"
#include "DeviceRegistry.h"
#include "FileUploader.h"
#include "FindCountry.h"
#include "OUIServer.h"
@@ -26,7 +29,6 @@
#include "VenueBroadcaster.h"
#include "framework/ConfigurationValidator.h"
#include "rttys/RTTYS_server.h"
#include "framework/UI_WebSocketClientServer.h"
namespace OpenWifi {
class Daemon *Daemon::instance() {
@@ -39,9 +41,10 @@ namespace OpenWifi {
StorageService(),
SerialNumberCache(),
ConfigurationValidator(),
UI_WebSocketClientServer(),
WebSocketClientServer(),
OUIServer(),
FindCountryFromIP(),
DeviceRegistry(),
CommandManager(),
FileUploader(),
StorageArchiver(),
@@ -102,10 +105,6 @@ namespace OpenWifi {
}
return "AP";
}
void DaemonPostInitialization(Poco::Util::Application &self) {
Daemon()->PostInitialization(self);
}
}
int main(int argc, char **argv) {

View File

@@ -14,9 +14,18 @@
#include <vector>
#include <set>
#include "framework/MicroServiceNames.h"
#include "framework/MicroService.h"
#include "Poco/Util/Application.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/UUIDGenerator.h"
#include "Poco/ErrorHandler.h"
#include "Poco/Crypto/RSAKey.h"
#include "Poco/Crypto/CipherFactory.h"
#include "Poco/Crypto/Cipher.h"
#include "Dashboard.h"
#include "framework/OpenWifiTypes.h"
#include "GwWebSocketClient.h"
@@ -53,6 +62,8 @@ namespace OpenWifi {
};
inline Daemon * Daemon() { return Daemon::instance(); }
void DaemonPostInitialization(Poco::Util::Application &self);
inline void DaemonPostInitialization(Poco::Util::Application &self) {
Daemon()->PostInitialization(self);
}
}

View File

@@ -3,12 +3,12 @@
//
#include "Dashboard.h"
#include "DeviceRegistry.h"
#include "StorageService.h"
#include "framework/utils.h"
namespace OpenWifi {
void DeviceDashboard::Create() {
uint64_t Now = Utils::Now();
uint64_t Now = OpenWifi::Now();
if(LastRun_==0 || (Now-LastRun_)>120) {
DB_.reset();

263
src/DeviceRegistry.cpp Normal file
View File

@@ -0,0 +1,263 @@
//
// License type: BSD 3-Clause License
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
// Created by Stephane Bourque on 2021-03-04.
// Arilia Wireless Inc.
//
#include "Poco/JSON/Object.h"
#include "AP_WS_Server.h"
#include "DeviceRegistry.h"
#include "CommandManager.h"
#include "framework/WebSocketClientNotifications.h"
namespace OpenWifi {
int DeviceRegistry::Start() {
std::lock_guard Guard(Mutex_);
poco_notice(Logger(),"Starting");
ArchiverCallback_ = std::make_unique<Poco::TimerCallback<DeviceRegistry>>(*this,&DeviceRegistry::onConnectionJanitor);
Timer_.setStartInterval(60 * 1000);
Timer_.setPeriodicInterval(20 * 1000); // every minute
Timer_.start(*ArchiverCallback_, MicroService::instance().TimerPool());
return 0;
}
void DeviceRegistry::Stop() {
poco_notice(Logger(),"Stopping...");
std::lock_guard Guard(Mutex_);
Timer_.stop();
poco_notice(Logger(),"Stopped...");
}
void DeviceRegistry::onConnectionJanitor([[maybe_unused]] Poco::Timer &timer) {
static std::uint64_t last_log = OpenWifi::Now();
std::shared_lock Guard(LocalMutex_);
NumberOfConnectedDevices_ = 0;
NumberOfConnectingDevices_ = 0;
AverageDeviceConnectionTime_ = 0;
std::uint64_t total_connected_time=0;
auto now = OpenWifi::Now();
for (auto connection=SerialNumbers_.begin(); connection!=SerialNumbers_.end();) {
if(connection->second.second== nullptr) {
connection++;
continue;
}
if (connection->second.second->State_.Connected) {
NumberOfConnectedDevices_++;
total_connected_time += (now - connection->second.second->State_.started);
connection++;
} else {
NumberOfConnectingDevices_++;
connection++;
}
}
AverageDeviceConnectionTime_ = (NumberOfConnectedDevices_!=0) ? total_connected_time/NumberOfConnectedDevices_ : 0;
if((now-last_log)>120) {
last_log = now;
poco_information(Logger(),
fmt::format("Active AP connections: {} Connecting: {} Average connection time: {} seconds",
NumberOfConnectedDevices_, NumberOfConnectingDevices_, AverageDeviceConnectionTime_));
}
WebSocketClientNotificationNumberOfConnections(NumberOfConnectedDevices_,
AverageDeviceConnectionTime_,
NumberOfConnectingDevices_);
}
bool DeviceRegistry::GetStatistics(uint64_t SerialNumber, std::string & Statistics) const {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device == SerialNumbers_.end() || Device->second.second==nullptr)
return false;
Statistics = Device->second.second->LastStats_;
return true;
}
bool DeviceRegistry::GetState(uint64_t SerialNumber, GWObjects::ConnectionState & State) const {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device == SerialNumbers_.end() || Device->second.second==nullptr)
return false;
State = Device->second.second->State_;
return true;
}
bool DeviceRegistry::GetHealthcheck(uint64_t SerialNumber, GWObjects::HealthCheck & CheckData) const {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device == SerialNumbers_.end() || Device->second.second==nullptr)
return false;
CheckData = Device->second.second->LastHealthcheck_;
return true;
}
bool DeviceRegistry::EndSession(std::uint64_t connection_id, std::uint64_t serial_number) {
std::unique_lock G(LocalMutex_);
auto Connection = SerialNumbers_.find(serial_number);
if(Connection==end(SerialNumbers_)) {
return false;
}
if(Connection->second.first!=connection_id) {
return false;
}
SerialNumbers_.erase(Connection);
return true;
}
void DeviceRegistry::SetSessionDetails(std::uint64_t connection_id, uint64_t SerialNumber) {
auto Connection = AP_WS_Server()->FindConnection(connection_id);
if(Connection== nullptr)
return;
std::unique_lock G(LocalMutex_);
auto CurrentSerialNumber = SerialNumbers_.find(SerialNumber);
if( (CurrentSerialNumber==SerialNumbers_.end()) ||
(CurrentSerialNumber->second.first<connection_id)) {
SerialNumbers_[SerialNumber] = std::make_pair(connection_id, Connection);
return;
}
}
bool DeviceRegistry::Connected(uint64_t SerialNumber) const {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second== nullptr)
return false;
return Device->second.second->State_.Connected;
}
bool DeviceRegistry::SendFrame(uint64_t SerialNumber, const std::string & Payload) const {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==SerialNumbers_.end() || Device->second.second== nullptr)
return false;
try {
// std::cout << "Device connection pointer: " << (std::uint64_t) Device->second.second << std::endl;
return Device->second.second->Send(Payload);
} catch (...) {
poco_debug(Logger(),fmt::format(": SendFrame: Could not send data to device '{}'", Utils::IntToSerialNumber(SerialNumber)));
}
return false;
}
void DeviceRegistry::StopWebSocketTelemetry(std::uint64_t RPCID, uint64_t SerialNumber) {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second==nullptr)
return;
Device->second.second->StopWebSocketTelemetry(RPCID);
}
void DeviceRegistry::SetWebSocketTelemetryReporting(std::uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime) {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second==nullptr)
return;
Device->second.second->SetWebSocketTelemetryReporting(RPCID, Interval, Lifetime);
}
void DeviceRegistry::SetKafkaTelemetryReporting(std::uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime) {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second== nullptr)
return;
Device->second.second->SetKafkaTelemetryReporting(RPCID, Interval, Lifetime);
}
void DeviceRegistry::StopKafkaTelemetry(std::uint64_t RPCID, uint64_t SerialNumber) {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_) || Device->second.second== nullptr)
return;
Device->second.second->StopKafkaTelemetry(RPCID);
}
void DeviceRegistry::GetTelemetryParameters(uint64_t SerialNumber , bool & TelemetryRunning,
uint64_t & TelemetryInterval,
uint64_t & TelemetryWebSocketTimer,
uint64_t & TelemetryKafkaTimer,
uint64_t & TelemetryWebSocketCount,
uint64_t & TelemetryKafkaCount,
uint64_t & TelemetryWebSocketPackets,
uint64_t & TelemetryKafkaPackets) {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(SerialNumber);
if(Device==end(SerialNumbers_)|| Device->second.second== nullptr)
return;
Device->second.second->GetTelemetryParameters(TelemetryRunning,
TelemetryInterval,
TelemetryWebSocketTimer,
TelemetryKafkaTimer,
TelemetryWebSocketCount,
TelemetryKafkaCount,
TelemetryWebSocketPackets,
TelemetryKafkaPackets);
}
bool DeviceRegistry::SendRadiusAccountingData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size) {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(Utils::SerialNumberToInt(SerialNumber));
if(Device==SerialNumbers_.end() || Device->second.second== nullptr)
return false;
try {
return Device->second.second->SendRadiusAccountingData(buffer,size);
} catch (...) {
poco_debug(Logger(),fmt::format(": SendRadiusAuthenticationData: Could not send data to device '{}'", SerialNumber));
}
return false;
}
bool DeviceRegistry::SendRadiusAuthenticationData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size) {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(Utils::SerialNumberToInt(SerialNumber));
if(Device==SerialNumbers_.end() || Device->second.second== nullptr)
return false;
try {
return Device->second.second->SendRadiusAuthenticationData(buffer,size);
} catch (...) {
poco_debug(Logger(),fmt::format(": SendRadiusAuthenticationData: Could not send data to device '{}'", SerialNumber));
}
return false;
}
bool DeviceRegistry::SendRadiusCoAData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size) {
std::shared_lock Guard(LocalMutex_);
auto Device = SerialNumbers_.find(Utils::SerialNumberToInt(SerialNumber));
if(Device==SerialNumbers_.end() || Device->second.second== nullptr)
return false;
try {
return Device->second.second->SendRadiusCoAData(buffer,size);
} catch (...) {
poco_debug(Logger(),fmt::format(": SendRadiusCoAData: Could not send data to device '{}'", SerialNumber));
}
return false;
}
} // namespace

104
src/DeviceRegistry.h Normal file
View File

@@ -0,0 +1,104 @@
//
// License type: BSD 3-Clause License
// License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE
//
// Created by Stephane Bourque on 2021-03-04.
// Arilia Wireless Inc.
//
#pragma once
#include <shared_mutex>
#include "framework/MicroService.h"
#include "Poco/JSON/Object.h"
#include "Poco/Timer.h"
#include "RESTObjects//RESTAPI_GWobjects.h"
namespace OpenWifi {
class AP_WS_Connection;
class DeviceRegistry : public SubSystemServer {
public:
DeviceRegistry() noexcept:
SubSystemServer("DeviceRegistry", "DevStatus", "devicestatus") {
}
static auto instance() {
static auto instance_ = new DeviceRegistry;
return instance_;
}
int Start() override;
void Stop() override;
inline bool GetStatistics(const std::string &SerialNumber, std::string & Statistics) const {
return GetStatistics(Utils::SerialNumberToInt(SerialNumber),Statistics);
}
bool GetStatistics(std::uint64_t SerialNumber, std::string & Statistics) const;
inline bool GetState(const std::string & SerialNumber, GWObjects::ConnectionState & State) const {
return GetState(Utils::SerialNumberToInt(SerialNumber), State);
}
bool GetState(std::uint64_t SerialNumber, GWObjects::ConnectionState & State) const;
inline bool GetHealthcheck(const std::string &SerialNumber, GWObjects::HealthCheck & CheckData) const {
return GetHealthcheck(Utils::SerialNumberToInt(SerialNumber), CheckData);
}
bool GetHealthcheck(std::uint64_t SerialNumber, GWObjects::HealthCheck & CheckData) const ;
bool Connected(uint64_t SerialNumber) const ;
inline bool SendFrame(const std::string & SerialNumber, const std::string & Payload) const {
return SendFrame(Utils::SerialNumberToInt(SerialNumber), Payload);
}
bool SendFrame(std::uint64_t SerialNumber, const std::string & Payload) const ;
bool SendRadiusAuthenticationData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size);
bool SendRadiusAccountingData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size);
bool SendRadiusCoAData(const std::string & SerialNumber, const unsigned char * buffer, std::size_t size);
void SetSessionDetails(std::uint64_t connection_id, uint64_t SerialNumber);
bool EndSession(std::uint64_t connection_id, std::uint64_t serial_number);
void SetWebSocketTelemetryReporting(std::uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime);
void StopWebSocketTelemetry(std::uint64_t RPCID, uint64_t SerialNumber);
void SetKafkaTelemetryReporting(std::uint64_t RPCID, uint64_t SerialNumber, uint64_t Interval, uint64_t Lifetime);
void StopKafkaTelemetry(std::uint64_t RPCID, uint64_t SerialNumber);
void GetTelemetryParameters(uint64_t SerialNumber , bool & TelemetryRunning,
uint64_t & TelemetryInterval,
uint64_t & TelemetryWebSocketTimer,
uint64_t & TelemetryKafkaTimer,
uint64_t & TelemetryWebSocketCount,
uint64_t & TelemetryKafkaCount,
uint64_t & TelemetryWebSocketPackets,
uint64_t & TelemetryKafkaPackets);
void onConnectionJanitor(Poco::Timer & timer);
inline void AverageDeviceStatistics( std::uint64_t & Connections, std::uint64_t & AverageConnectionTime, std::uint64_t & NumberOfConnectingDevices) const {
Connections = NumberOfConnectedDevices_;
AverageConnectionTime = AverageDeviceConnectionTime_;
NumberOfConnectingDevices = NumberOfConnectingDevices_;
}
private:
mutable std::shared_mutex LocalMutex_;
std::map<std::uint64_t, std::pair<std::uint64_t,std::shared_ptr<AP_WS_Connection>>> SerialNumbers_;
std::unique_ptr<Poco::TimerCallback<DeviceRegistry>> ArchiverCallback_;
Poco::Timer Timer_;
Poco::Thread ConnectionJanitor_;
std::atomic_uint64_t NumberOfConnectedDevices_=0;
std::atomic_uint64_t AverageDeviceConnectionTime_=0;
std::atomic_uint64_t NumberOfConnectingDevices_=0;
};
inline auto DeviceRegistry() { return DeviceRegistry::instance(); }
} // namespace

View File

@@ -8,6 +8,8 @@
#include <iostream>
#include "framework/MicroService.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/DynamicAny.h"
@@ -17,16 +19,9 @@
#include "Poco/CountingStream.h"
#include "Poco/StreamCopier.h"
#include "Poco/Exception.h"
#include "Poco/File.h"
#include "Poco/StringTokenizer.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/ow_constants.h"
#include "framework/utils.h"
#include "FileUploader.h"
#include "StorageService.h"
#include "fmt/format.h"
namespace OpenWifi {
@@ -35,7 +30,7 @@ namespace OpenWifi {
int FileUploader::Start() {
poco_notice(Logger(),"Starting.");
Poco::File UploadsDir(MicroServiceConfigPath("openwifi.fileuploader.path","/tmp"));
Poco::File UploadsDir(MicroService::instance().ConfigPath("openwifi.fileuploader.path","/tmp"));
Path_ = UploadsDir.path();
if(!UploadsDir.exists()) {
try {
@@ -47,7 +42,7 @@ namespace OpenWifi {
}
for(const auto & Svr: ConfigServersList_) {
if(MicroServiceNoAPISecurity()) {
if(MicroService::instance().NoAPISecurity()) {
poco_notice(Logger(), fmt::format("Starting: {}:{}",Svr.Address(),Svr.Port()));
auto Sock{Svr.CreateSocket(Logger())};
@@ -59,7 +54,7 @@ namespace OpenWifi {
if (FullName_.empty()) {
std::string TmpName =
MicroServiceConfigGetString("openwifi.fileuploader.uri", "");
MicroService::instance().ConfigGetString("openwifi.fileuploader.uri", "");
if (TmpName.empty()) {
FullName_ =
"https://" + Svr.Name() + ":" + std::to_string(Svr.Port()) + URI_BASE;
@@ -92,7 +87,7 @@ namespace OpenWifi {
if (FullName_.empty()) {
std::string TmpName =
MicroServiceConfigGetString("openwifi.fileuploader.uri", "");
MicroService::instance().ConfigGetString("openwifi.fileuploader.uri", "");
if (TmpName.empty()) {
FullName_ =
"https://" + Svr.Name() + ":" + std::to_string(Svr.Port()) + URI_BASE;
@@ -109,13 +104,13 @@ namespace OpenWifi {
}
}
MaxSize_ = 1000 * MicroServiceConfigGetInt("openwifi.fileuploader.maxsize", 10000);
MaxSize_ = 1000 * MicroService::instance().ConfigGetInt("openwifi.fileuploader.maxsize", 10000);
return 0;
}
void FileUploader::reinitialize([[maybe_unused]] Poco::Util::Application &self) {
MicroServiceLoadConfigurationFile();
MicroService::instance().LoadConfigurationFile();
poco_information(Logger(),"Reinitializing.");
Stop();
Start();
@@ -129,7 +124,7 @@ namespace OpenWifi {
bool FileUploader::AddUUID( const std::string & UUID) {
std::lock_guard Guard(Mutex_);
uint64_t now = Utils::Now();
uint64_t now = OpenWifi::Now();
// remove old stuff...
for(auto i=OutStandingUploads_.begin();i!=OutStandingUploads_.end();) {

View File

@@ -8,12 +8,13 @@
#pragma once
#include "framework/MicroService.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "framework/SubSystemServer.h"
namespace OpenWifi {

View File

@@ -4,11 +4,9 @@
#pragma once
#include "framework/MicroService.h"
#include "Poco/Net/IPAddress.h"
#include "framework/SubSystemServer.h"
#include "framework/MicroServiceFuncs.h"
#include "nlohmann/json.hpp"
namespace OpenWifi {
@@ -26,7 +24,7 @@ namespace OpenWifi {
public:
static std::string Name() { return "ipinfo"; }
inline bool Init() override {
Key_ = MicroServiceConfigGetString("iptocountry.ipinfo.token", "");
Key_ = MicroService::instance().ConfigGetString("iptocountry.ipinfo.token", "");
return !Key_.empty();
}
@@ -58,7 +56,7 @@ namespace OpenWifi {
public:
static std::string Name() { return "ipdata"; }
inline bool Init() override {
Key_ = MicroServiceConfigGetString("iptocountry.ipdata.apikey", "");
Key_ = MicroService::instance().ConfigGetString("iptocountry.ipdata.apikey", "");
return !Key_.empty();
}
@@ -88,7 +86,7 @@ namespace OpenWifi {
public:
static std::string Name() { return "ip2location"; }
inline bool Init() override {
Key_ = MicroServiceConfigGetString("iptocountry.ip2location.apikey", "");
Key_ = MicroService::instance().ConfigGetString("iptocountry.ip2location.apikey", "");
return !Key_.empty();
}
@@ -137,14 +135,14 @@ namespace OpenWifi {
inline int Start() final {
poco_notice(Logger(),"Starting...");
ProviderName_ = MicroServiceConfigGetString("iptocountry.provider","");
ProviderName_ = MicroService::instance().ConfigGetString("iptocountry.provider","");
if(!ProviderName_.empty()) {
Provider_ = IPLocationProvider<IPToCountryProvider, IPInfo, IPData, IP2Location>(ProviderName_);
if(Provider_!= nullptr) {
Enabled_ = Provider_->Init();
}
}
Default_ = MicroServiceConfigGetString("iptocountry.default", "US");
Default_ = MicroService::instance().ConfigGetString("iptocountry.default", "US");
return 0;
}

View File

@@ -9,11 +9,11 @@ namespace OpenWifi {
GwWebSocketClient::GwWebSocketClient(Poco::Logger &Logger):
Logger_(Logger){
UI_WebSocketClientServer()->SetProcessor(this);
WebSocketClientServer()->SetProcessor(this);
}
GwWebSocketClient::~GwWebSocketClient() {
UI_WebSocketClientServer()->SetProcessor(nullptr);
WebSocketClientServer()->SetProcessor(nullptr);
}
void GwWebSocketClient::Processor(const Poco::JSON::Object::Ptr &O, std::string &Answer, bool &Done ) {
@@ -60,4 +60,7 @@ namespace OpenWifi {
Done = false;
Answer = std::string{R"lit({ "error" : "invalid command" })lit"};
}
}

View File

@@ -4,10 +4,10 @@
#pragma once
#include "framework/UI_WebSocketClientServer.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class GwWebSocketClient : public UI_WebSocketClientProcessor {
class GwWebSocketClient : public WebSocketClientProcessor {
public:
explicit GwWebSocketClient(Poco::Logger &Logger);
virtual ~GwWebSocketClient();

View File

@@ -11,42 +11,20 @@
#include "Poco/StreamCopier.h"
#include "Poco/File.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
#include "fmt/format.h"
#include "OUIServer.h"
#include "framework/MicroService.h"
namespace OpenWifi {
int OUIServer::Start() {
Running_ = true;
LatestOUIFileName_ = MicroServiceDataDirectory() + "/newOUIFile.txt";
CurrentOUIFileName_ = MicroServiceDataDirectory() + "/current_oui.txt";
bool Recovered = false;
Poco::File OuiFile(CurrentOUIFileName_);
if(OuiFile.exists()) {
std::unique_lock Lock(LocalMutex_);
Recovered = ProcessFile(CurrentOUIFileName_,OUIs_);
if(Recovered) {
poco_notice(Logger(),
fmt::format("Recovered last OUI file - {}", CurrentOUIFileName_));
}
} else {
poco_notice(Logger(),
fmt::format("No existing OUIFile.", CurrentOUIFileName_));
}
LatestOUIFileName_ = MicroService::instance().DataDir() + "/newOUIFile.txt";
CurrentOUIFileName_ = MicroService::instance().DataDir() + "/current_oui.txt";
UpdaterCallBack_ = std::make_unique<Poco::TimerCallback<OUIServer>>(*this, &OUIServer::onTimer);
if(Recovered) {
Timer_.setStartInterval(60 * 60 * 1000); // first run in 1 hour
} else {
Timer_.setStartInterval(30 * 1000); // first run in 5 minutes
}
Timer_.setStartInterval(30 * 1000); // first run in 5 minutes
Timer_.setPeriodicInterval(7 * 24 * 60 * 60 * 1000);
Timer_.start(*UpdaterCallBack_, MicroServiceTimerPool());
Timer_.start(*UpdaterCallBack_, MicroService::instance().TimerPool());
return 0;
}
@@ -58,7 +36,7 @@ namespace OpenWifi {
}
void OUIServer::reinitialize([[maybe_unused]] Poco::Util::Application &self) {
MicroServiceLoadConfigurationFile();
MicroService::instance().LoadConfigurationFile();
poco_information(Logger(),"Reinitializing.");
Stop();
Start();
@@ -66,15 +44,15 @@ namespace OpenWifi {
bool OUIServer::GetFile(const std::string &FileName) {
try {
LastUpdate_ = Utils::Now();
poco_information(Logger(), fmt::format("Start: Retrieving OUI file: {}",MicroServiceConfigGetString("oui.download.uri","")));
LastUpdate_ = OpenWifi::Now();
poco_information(Logger(), fmt::format("Start: Retrieving OUI file: {}",MicroService::instance().ConfigGetString("oui.download.uri")));
std::unique_ptr<std::istream> pStr(
Poco::URIStreamOpener::defaultOpener().open(MicroServiceConfigGetString("oui.download.uri","")));
Poco::URIStreamOpener::defaultOpener().open(MicroService::instance().ConfigGetString("oui.download.uri")));
std::ofstream OS;
OS.open(FileName);
Poco::StreamCopier::copyStream(*pStr, OS);
OS.close();
poco_information(Logger(), fmt::format("Done: Retrieving OUI file: {}",MicroServiceConfigGetString("oui.download.uri","")));
poco_information(Logger(), fmt::format("Done: Retrieving OUI file: {}",MicroService::instance().ConfigGetString("oui.download.uri")));
return true;
} catch (const Poco::Exception &E) {
Logger().log(E);
@@ -124,12 +102,10 @@ namespace OpenWifi {
return;
Updating_ = true;
poco_information(Logger(),"Starting to process OUI file...");
// fetch data from server, if not available, just use the file we already have.
Poco::File Current(CurrentOUIFileName_);
if(Current.exists()) {
if((Utils::Now()-Current.getLastModified().epochTime()) < (7*24*60*60)) {
if((OpenWifi::Now()-Current.getLastModified().epochTime()) < (7*24*60*60)) {
if(!Initialized_) {
if(ProcessFile(CurrentOUIFileName_, OUIs_)) {
Initialized_ = true;
@@ -146,9 +122,9 @@ namespace OpenWifi {
OUIMap TmpOUIs;
if(GetFile(LatestOUIFileName_) && ProcessFile(LatestOUIFileName_, TmpOUIs)) {
std::unique_lock G(LocalMutex_);
std::lock_guard G(Mutex_);
OUIs_ = std::move(TmpOUIs);
LastUpdate_ = Utils::Now();
LastUpdate_ = OpenWifi::Now();
Poco::File F1(CurrentOUIFileName_);
if(F1.exists())
F1.remove();
@@ -157,19 +133,17 @@ namespace OpenWifi {
poco_information(Logger(), fmt::format("New OUI file {} downloaded.",LatestOUIFileName_));
} else if(OUIs_.empty()) {
if(ProcessFile(CurrentOUIFileName_, TmpOUIs)) {
LastUpdate_ = Utils::Now();
std::unique_lock G(LocalMutex_);
LastUpdate_ = OpenWifi::Now();
std::lock_guard G(Mutex_);
OUIs_ = std::move(TmpOUIs);
}
}
Initialized_=true;
Updating_ = false;
poco_information(Logger(),"Done processing OUI file...");
}
std::string OUIServer::GetManufacturer(const std::string &MAC) {
std::shared_lock Lock(LocalMutex_);
std::lock_guard Guard(Mutex_);
auto Manufacturer = OUIs_.find(Utils::SerialNumberToOUI(MAC));
if(Manufacturer != OUIs_.end())
return Manufacturer->second;

View File

@@ -4,10 +4,7 @@
#pragma once
#include <shared_mutex>
#include "framework/SubSystemServer.h"
#include "framework/MicroService.h"
#include "Poco/Timer.h"
namespace OpenWifi {
@@ -33,7 +30,6 @@ namespace OpenWifi {
[[nodiscard]] bool ProcessFile(const std::string &FileName, OUIMap &Map);
private:
std::shared_mutex LocalMutex_;
uint64_t LastUpdate_ = 0 ;
bool Initialized_ = false;
OUIMap OUIs_;

View File

@@ -4,12 +4,7 @@
#pragma once
#include <string>
#include <vector>
#include <map>
#include <utility>
#include "nlohmann/json.hpp"
#include "framework/MicroService.h"
namespace OpenWifi {

View File

@@ -11,7 +11,6 @@
#include "Poco/HMACEngine.h"
#include "Poco/MD5Engine.h"
#include "Poco/StringTokenizer.h"
namespace OpenWifi::RADIUS {

View File

@@ -2,13 +2,9 @@
// Created by stephane bourque on 2022-05-18.
//
#include "Poco/JSON/Parser.h"
#include "RADIUS_proxy_server.h"
#include "DeviceRegistry.h"
#include "RADIUS_helpers.h"
#include "AP_WS_Server.h"
#include "framework/MicroServiceFuncs.h"
namespace OpenWifi {
@@ -19,38 +15,34 @@ namespace OpenWifi {
int RADIUS_proxy_server::Start() {
ConfigFilename_ = MicroServiceDataDirectory()+"/radius_pool_config.json";
ConfigFilename_ = MicroService::instance().DataDir()+"/radius_pool_config.json";
Poco::File Config(ConfigFilename_);
enabled_ = MicroServiceConfigGetBool("radius.proxy.enable",false);
if(!enabled_ && !Config.exists()) {
StopRADSECServers();
enabled_ = MicroService::instance().ConfigGetBool("radius.proxy.enable",false);
if(!enabled_ && !Config.exists())
return 0;
}
poco_notice(Logger(),"Starting...");
enabled_ = true;
Poco::Net::SocketAddress AuthSockAddrV4(Poco::Net::AddressFamily::IPv4,
MicroServiceConfigGetInt("radius.proxy.authentication.port",DEFAULT_RADIUS_AUTHENTICATION_PORT));
MicroService::instance().ConfigGetInt("radius.proxy.authentication.port",DEFAULT_RADIUS_AUTHENTICATION_PORT));
AuthenticationSocketV4_ = std::make_unique<Poco::Net::DatagramSocket>(AuthSockAddrV4,true);
Poco::Net::SocketAddress AuthSockAddrV6(Poco::Net::AddressFamily::IPv6,
MicroServiceConfigGetInt("radius.proxy.authentication.port",DEFAULT_RADIUS_AUTHENTICATION_PORT));
MicroService::instance().ConfigGetInt("radius.proxy.authentication.port",DEFAULT_RADIUS_AUTHENTICATION_PORT));
AuthenticationSocketV6_ = std::make_unique<Poco::Net::DatagramSocket>(AuthSockAddrV6,true);
Poco::Net::SocketAddress AcctSockAddrV4(Poco::Net::AddressFamily::IPv4,
MicroServiceConfigGetInt("radius.proxy.accounting.port",DEFAULT_RADIUS_ACCOUNTING_PORT));
MicroService::instance().ConfigGetInt("radius.proxy.accounting.port",DEFAULT_RADIUS_ACCOUNTING_PORT));
AccountingSocketV4_ = std::make_unique<Poco::Net::DatagramSocket>(AcctSockAddrV4,true);
Poco::Net::SocketAddress AcctSockAddrV6(Poco::Net::AddressFamily::IPv6,
MicroServiceConfigGetInt("radius.proxy.accounting.port",DEFAULT_RADIUS_ACCOUNTING_PORT));
MicroService::instance().ConfigGetInt("radius.proxy.accounting.port",DEFAULT_RADIUS_ACCOUNTING_PORT));
AccountingSocketV6_ = std::make_unique<Poco::Net::DatagramSocket>(AcctSockAddrV6,true);
Poco::Net::SocketAddress CoASockAddrV4(Poco::Net::AddressFamily::IPv4,
MicroServiceConfigGetInt("radius.proxy.coa.port",DEFAULT_RADIUS_CoA_PORT));
MicroService::instance().ConfigGetInt("radius.proxy.coa.port",DEFAULT_RADIUS_CoA_PORT));
CoASocketV4_ = std::make_unique<Poco::Net::DatagramSocket>(CoASockAddrV4,true);
Poco::Net::SocketAddress CoASockAddrV6(Poco::Net::AddressFamily::IPv6,
MicroServiceConfigGetInt("radius.proxy.coa.port",DEFAULT_RADIUS_CoA_PORT));
MicroService::instance().ConfigGetInt("radius.proxy.coa.port",DEFAULT_RADIUS_CoA_PORT));
CoASocketV6_ = std::make_unique<Poco::Net::DatagramSocket>(CoASockAddrV6,true);
RadiusReactor_.addEventHandler(*AuthenticationSocketV4_,Poco::NObserver<RADIUS_proxy_server, Poco::Net::ReadableNotification>(
@@ -72,7 +64,6 @@ namespace OpenWifi {
ParseConfig();
// start RADSEC servers...
StopRADSECServers();
StartRADSECServers();
RadiusReactorThread_.start(RadiusReactor_);
@@ -113,7 +104,9 @@ namespace OpenWifi {
Poco::NObserver<RADIUS_proxy_server, Poco::Net::ReadableNotification>(
*this, &RADIUS_proxy_server::OnCoASocketReadable));
StopRADSECServers();
for(auto &[_,radsec_server]:RADSECservers_)
radsec_server->Stop();
RadiusReactor_.stop();
RadiusReactorThread_.join();
enabled_=false;
@@ -132,12 +125,8 @@ namespace OpenWifi {
}
}
void RADIUS_proxy_server::StopRADSECServers() {
RADSECservers_.clear();
}
void RADIUS_proxy_server::StartRADSECServer(const GWObjects::RadiusProxyServerEntry &E) {
RADSECservers_[ Poco::Net::SocketAddress(E.ip,0) ] = std::make_unique<RADSEC_server>(RadiusReactor_,E);
RADSECservers_[ Poco::Net::SocketAddress(E.ip,0) ] = std::make_unique<RADSECserver>(RadiusReactor_,E);
}
void RADIUS_proxy_server::OnAccountingSocketReadable(const Poco::AutoPtr<Poco::Net::ReadableNotification>& pNf) {
@@ -158,8 +147,8 @@ namespace OpenWifi {
auto CallingStationID = P.ExtractCallingStationID();
auto CalledStationID = P.ExtractCalledStationID();
poco_debug(Logger(), fmt::format("Accounting Packet received for {}, CalledStationID: {}, CallingStationID:{}",SerialNumber, CalledStationID, CallingStationID));
AP_WS_Server()->SendRadiusAccountingData(SerialNumber,P.Buffer(),P.Size());
poco_information(Logger(), fmt::format("Accounting Packet received for {}, CalledStationID: {}, CallingStationID:{}",SerialNumber, CalledStationID, CallingStationID));
DeviceRegistry()->SendRadiusAccountingData(SerialNumber,P.Buffer(),P.Size());
}
void RADIUS_proxy_server::OnAuthenticationSocketReadable(const Poco::AutoPtr<Poco::Net::ReadableNotification>& pNf) {
@@ -180,8 +169,8 @@ namespace OpenWifi {
auto CallingStationID = P.ExtractCallingStationID();
auto CalledStationID = P.ExtractCalledStationID();
poco_debug(Logger(), fmt::format("Authentication Packet received for {}, CalledStationID: {}, CallingStationID:{}",SerialNumber, CalledStationID, CallingStationID));
AP_WS_Server()->SendRadiusAuthenticationData(SerialNumber,P.Buffer(),P.Size());
poco_information(Logger(), fmt::format("Authentication Packet received for {}, CalledStationID: {}, CallingStationID:{}",SerialNumber, CalledStationID, CallingStationID));
DeviceRegistry()->SendRadiusAuthenticationData(SerialNumber,P.Buffer(),P.Size());
}
void RADIUS_proxy_server::OnCoASocketReadable(const Poco::AutoPtr<Poco::Net::ReadableNotification>& pNf) {
@@ -202,61 +191,38 @@ namespace OpenWifi {
auto CallingStationID = P.ExtractCallingStationID();
auto CalledStationID = P.ExtractCalledStationID();
poco_debug(Logger(), fmt::format("CoA Packet received for {}, CalledStationID: {}, CallingStationID:{}",SerialNumber, CalledStationID, CallingStationID));
AP_WS_Server()->SendRadiusCoAData(SerialNumber,P.Buffer(),P.Size());
poco_information(Logger(), fmt::format("CoA Packet received for {}, CalledStationID: {}, CallingStationID:{}",SerialNumber, CalledStationID, CallingStationID));
DeviceRegistry()->SendRadiusCoAData(SerialNumber,P.Buffer(),P.Size());
}
void RADIUS_proxy_server::SendAccountingData(const std::string &serialNumber, const char *buffer, std::size_t size) {
RADIUS::RadiusPacket P((unsigned char *)buffer,size);
auto Destination = P.ExtractProxyStateDestination();
auto CallingStationID = P.ExtractCallingStationID();
auto CalledStationID = P.ExtractCalledStationID();
Poco::Net::SocketAddress Dst(Destination);
if(Pools_.empty() || !enabled_)
return;
try {
RADIUS::RadiusPacket P((unsigned char *)buffer, size);
auto Destination = P.ExtractProxyStateDestination();
auto CallingStationID = P.ExtractCallingStationID();
auto CalledStationID = P.ExtractCalledStationID();
Poco::Net::SocketAddress Dst(Destination);
std::lock_guard G(Mutex_);
bool UseRADSEC = false;
auto FinalDestination = Route(radius_type::acct, Dst, P, UseRADSEC);
if (UseRADSEC) {
Poco::Net::SocketAddress RSP(FinalDestination.host(), 0);
auto DestinationServer = RADSECservers_.find(RSP);
if (DestinationServer != end(RADSECservers_)) {
DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer,
size);
}
} else {
if ((Dst.family() == Poco::Net::SocketAddress::IPv4 &&
AccountingSocketV4_ == nullptr) ||
(Dst.family() == Poco::Net::SocketAddress::IPv6 &&
AccountingSocketV6_ == nullptr)) {
poco_debug(
Logger(),
fmt::format(
"ACCT: Trying to use RADIUS GW PROXY but not configured. Device={}",
serialNumber));
return;
}
auto AllSent =
SendData(Dst.family() == Poco::Net::SocketAddress::IPv4 ? *AccountingSocketV4_
: *AccountingSocketV6_,
(const unsigned char *)buffer, size, FinalDestination);
if (!AllSent)
poco_error(Logger(),
fmt::format("{}: Could not send Accounting packet packet to {}.",
serialNumber, Destination));
else
poco_debug(Logger(), fmt::format("{}: Sending Accounting Packet to {}, CalledStationID: {}, CallingStationID:{}",
serialNumber, FinalDestination.toString(),
CalledStationID, CallingStationID));
std::lock_guard G(Mutex_);
bool UseRADSEC = false;
auto FinalDestination = Route(radius_type::acct, Dst, P, UseRADSEC);
if(UseRADSEC) {
Poco::Net::SocketAddress RSP(FinalDestination.host(),0);
auto DestinationServer = RADSECservers_.find(RSP);
if(DestinationServer!=end(RADSECservers_)) {
DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer, size);
}
} catch (const Poco::Exception &E) {
Logger().log(E);
} catch (...) {
poco_warning(Logger(),fmt::format("Bad RADIUS ACCT Packet from {}. Dropped.",serialNumber));
} else {
auto AllSent =
SendData(Dst.family() == Poco::Net::SocketAddress::IPv4 ? *AccountingSocketV4_
: *AccountingSocketV6_,
(const unsigned char *)buffer, size, FinalDestination);
if (!AllSent)
poco_error(Logger(),fmt::format("{}: Could not send Accounting packet packet to {}.",
serialNumber, Destination));
else
poco_information(Logger(), fmt::format(
"{}: Sending Accounting Packet to {}, CalledStationID: {}, CallingStationID:{}",
serialNumber, FinalDestination.toString(), CalledStationID, CallingStationID));
}
}
@@ -265,101 +231,64 @@ namespace OpenWifi {
}
void RADIUS_proxy_server::SendAuthenticationData(const std::string &serialNumber, const char *buffer, std::size_t size) {
RADIUS::RadiusPacket P((unsigned char *)buffer,size);
auto Destination = P.ExtractProxyStateDestination();
auto CallingStationID = P.ExtractCallingStationID();
auto CalledStationID = P.ExtractCalledStationID();
Poco::Net::SocketAddress Dst(Destination);
if(Pools_.empty() || !enabled_)
return;
try {
RADIUS::RadiusPacket P((unsigned char *)buffer,size);
auto Destination = P.ExtractProxyStateDestination();
auto CallingStationID = P.ExtractCallingStationID();
auto CalledStationID = P.ExtractCalledStationID();
Poco::Net::SocketAddress Dst(Destination);
std::lock_guard G(Mutex_);
bool UseRADSEC = false;
auto FinalDestination = Route(radius_type::auth, Dst, P, UseRADSEC);
if(UseRADSEC) {
Poco::Net::SocketAddress RSP(FinalDestination.host(),0);
auto DestinationServer = RADSECservers_.find(RSP);
if(DestinationServer!=end(RADSECservers_)) {
DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer, size);
}
} else {
if ((Dst.family() == Poco::Net::SocketAddress::IPv4 &&
AuthenticationSocketV4_ == nullptr) ||
(Dst.family() == Poco::Net::SocketAddress::IPv6 &&
AuthenticationSocketV6_ == nullptr)) {
poco_debug(
Logger(),
fmt::format("AUTH: Trying to use RADIUS GW PROXY but not configured. Device={}",
serialNumber));
return;
}
auto AllSent =
SendData(Dst.family() == Poco::Net::SocketAddress::IPv4 ? *AuthenticationSocketV4_
: *AuthenticationSocketV6_,
(const unsigned char *)buffer, size, FinalDestination);
if (!AllSent)
poco_error(Logger(),
fmt::format("{}: Could not send Authentication packet packet to {}.",
serialNumber, Destination));
else
poco_debug(Logger(), fmt::format("{}: Sending Authentication Packet to {}, CalledStationID: {}, CallingStationID:{}",
serialNumber, FinalDestination.toString(),
CalledStationID, CallingStationID));
std::lock_guard G(Mutex_);
bool UseRADSEC = false;
auto FinalDestination = Route(radius_type::auth, Dst, P, UseRADSEC);
if(UseRADSEC) {
Poco::Net::SocketAddress RSP(FinalDestination.host(),0);
auto DestinationServer = RADSECservers_.find(RSP);
if(DestinationServer!=end(RADSECservers_)) {
DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer, size);
}
} catch (const Poco::Exception &E) {
Logger().log(E);
} catch (...) {
poco_warning(Logger(),fmt::format("Bad RADIUS AUTH Packet from {}. Dropped.",serialNumber));
} else {
auto AllSent =
SendData(Dst.family() == Poco::Net::SocketAddress::IPv4 ? *AuthenticationSocketV4_
: *AuthenticationSocketV6_,
(const unsigned char *)buffer, size, FinalDestination);
if (!AllSent)
poco_error(Logger(),fmt::format("{}: Could not send Authentication packet packet to {}.",
serialNumber, Destination));
else
poco_information(Logger(), fmt::format("{}: Sending Authentication Packet to {}, CalledStationID: {}, CallingStationID:{}",
serialNumber, FinalDestination.toString(),
CalledStationID, CallingStationID));
}
}
void RADIUS_proxy_server::SendCoAData(const std::string &serialNumber, const char *buffer, std::size_t size) {
RADIUS::RadiusPacket P((unsigned char *)buffer,size);
auto Destination = P.ExtractProxyStateDestination();
if(Pools_.empty() || !enabled_)
return;
if(Destination.empty()) {
Destination = "0.0.0.0:0";
}
try {
RADIUS::RadiusPacket P((unsigned char *)buffer,size);
auto Destination = P.ExtractProxyStateDestination();
if(Destination.empty()) {
Destination = "0.0.0.0:0";
Poco::Net::SocketAddress Dst(Destination);
std::lock_guard G(Mutex_);
bool UseRADSEC = false;
auto FinalDestination = Route(radius_type::coa, Dst, P, UseRADSEC);
if(UseRADSEC) {
Poco::Net::SocketAddress RSP(FinalDestination.host(),0);
auto DestinationServer = RADSECservers_.find(RSP);
if(DestinationServer!=end(RADSECservers_)) {
DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer, size);
}
Poco::Net::SocketAddress Dst(Destination);
std::lock_guard G(Mutex_);
bool UseRADSEC = false;
auto FinalDestination = Route(radius_type::coa, Dst, P, UseRADSEC);
if(UseRADSEC) {
Poco::Net::SocketAddress RSP(FinalDestination.host(),0);
auto DestinationServer = RADSECservers_.find(RSP);
if(DestinationServer!=end(RADSECservers_)) {
DestinationServer->second->SendData(serialNumber, (const unsigned char *)buffer, size);
}
} else {
if( (Dst.family() == Poco::Net::SocketAddress::IPv4 && CoASocketV4_== nullptr) ||
(Dst.family() == Poco::Net::SocketAddress::IPv6 && CoASocketV6_== nullptr)) {
poco_debug(Logger(),fmt::format("CoA: Trying to use RADIUS GW PROXY but not configured. Device={}",serialNumber));
return;
}
auto AllSent = SendData(Dst.family() == Poco::Net::SocketAddress::IPv4 ? *CoASocketV4_
: *CoASocketV6_,
(const unsigned char *)buffer, size, FinalDestination);
if (!AllSent)
poco_error(Logger(),fmt::format("{}: Could not send CoA packet packet to {}.",
serialNumber, Destination));
else
poco_debug(Logger(), fmt::format("{}: Sending CoA Packet to {}", serialNumber,
FinalDestination.toString()));
}
} catch (const Poco::Exception &E) {
Logger().log(E);
} catch (...) {
poco_warning(Logger(),fmt::format("Bad RADIUS CoA/DM Packet from {}. Dropped.",serialNumber));
} else {
auto AllSent = SendData(Dst.family() == Poco::Net::SocketAddress::IPv4 ? *CoASocketV4_
: *CoASocketV6_,
(const unsigned char *)buffer, size, FinalDestination);
if (!AllSent)
poco_error(Logger(),fmt::format("{}: Could not send CoA packet packet to {}.",
serialNumber, Destination));
else
poco_information(Logger(), fmt::format("{}: Sending CoA Packet to {}", serialNumber,
FinalDestination.toString()));
}
}
@@ -552,9 +481,7 @@ namespace OpenWifi {
} break;
}
}
UseRADSEC = false;
return RequestedAddress;
return DefaultRoute(rtype, RequestedAddress, P, UseRADSEC);
}
Poco::Net::SocketAddress RADIUS_proxy_server::ChooseAddress(std::vector<Destination> &Pool, const Poco::Net::SocketAddress & OriginalAddress) {

View File

@@ -4,14 +4,13 @@
#pragma once
#include "framework/MicroService.h"
#include "RESTObjects/RESTAPI_GWobjects.h"
#include "Poco/Net/DatagramSocket.h"
#include "Poco/Net/SocketReactor.h"
#include "framework/SubSystemServer.h"
#include "RADSEC_server.h"
#include "RADSECserver.h"
namespace OpenWifi {
@@ -45,7 +44,6 @@ namespace OpenWifi {
void StartRADSECServers();
void StartRADSECServer(const GWObjects::RadiusProxyServerEntry &E);
void StopRADSECServers();
struct Destination {
Poco::Net::SocketAddress Addr;
@@ -75,7 +73,7 @@ namespace OpenWifi {
GWObjects::RadiusProxyPoolList PoolList_;
std::string ConfigFilename_;
std::map<Poco::Net::SocketAddress, std::unique_ptr<RADSEC_server>> RADSECservers_;
std::map<Poco::Net::SocketAddress, std::unique_ptr<RADSECserver>> RADSECservers_;
struct RadiusPool {
std::vector<Destination> AuthV4;

View File

@@ -7,6 +7,8 @@
#include <iostream>
#include <fstream>
#include "framework/MicroService.h"
#include "RESTObjects/RESTAPI_GWobjects.h"
#include "Poco/Net/SocketReactor.h"
@@ -16,18 +18,14 @@
#include "Poco/Net/NetException.h"
#include "Poco/TemporaryFile.h"
#include "framework/MicroServiceFuncs.h"
#include "fmt/format.h"
#include "RADIUS_helpers.h"
#include "AP_WS_Server.h"
#include "DeviceRegistry.h"
namespace OpenWifi {
class RADSEC_server : public Poco::Runnable {
class RADSECserver : public Poco::Runnable {
public:
RADSEC_server(Poco::Net::SocketReactor & R, GWObjects::RadiusProxyServerEntry E) :
RADSECserver(Poco::Net::SocketReactor & R, GWObjects::RadiusProxyServerEntry E) :
Reactor_(R),
Server_(std::move(E)),
Logger_(Poco::Logger::get(fmt::format("RADSEC: {}@{}:{}",
@@ -35,20 +33,7 @@ namespace OpenWifi {
Server_.ip,
Server_.port)))
{
ReconnectThread_.start(*this);
}
~RADSEC_server() {
if(ReconnectThread_.isRunning()) {
Stop();
}
}
inline void Stop() {
TryAgain_ = false;
Disconnect();
ReconnectThread_.wakeUp();
ReconnectThread_.join();
ReconnectorThr_.start(*this);
}
inline void run() final {
@@ -57,7 +42,7 @@ namespace OpenWifi {
std::unique_lock G(Mutex_);
Connect();
}
Poco::Thread::trySleep(3000);
Poco::Thread::trySleep(1000);
}
}
@@ -68,11 +53,11 @@ namespace OpenWifi {
// std::cout << serial_number << " Sending " << P.PacketType() << " " << length << " bytes" << std::endl;
int sent_bytes;
if (P.VerifyMessageAuthenticator(Server_.radsecSecret)) {
poco_debug(Logger_,fmt::format("{}: {} Sending {} bytes", serial_number,
Logger_.debug(fmt::format("{}: {} Sending {} bytes", serial_number,
P.PacketType(), length));
sent_bytes = Socket_->sendBytes(buffer, length);
} else {
poco_debug(Logger_,fmt::format("{}: {} Sending {} bytes", serial_number,
Logger_.debug(fmt::format("{}: {} Sending {} bytes", serial_number,
P.PacketType(), length));
P.ComputeMessageAuthenticator(Server_.radsecSecret);
sent_bytes = Socket_->sendBytes(P.Buffer(), length);
@@ -92,32 +77,20 @@ namespace OpenWifi {
auto NumberOfReceivedBytes = Socket_->receiveBytes(Buffer,sizeof(Buffer));
if(NumberOfReceivedBytes>40) {
RADIUS::RadiusPacket P(Buffer,NumberOfReceivedBytes);
// P.Log(std::cout);
// std::cout << "RADSEC: " << P.PacketType() << " " << (int) P.PacketTypeInt() << " Received " << NumberOfReceivedBytes << " bytes" << std::endl;
if (P.IsAuthentication()) {
auto SerialNumber = P.ExtractSerialNumberFromProxyState();
if(!SerialNumber.empty()) {
poco_debug(Logger_,
fmt::format("{}: {} Received {} bytes.", SerialNumber,
P.PacketType(), NumberOfReceivedBytes));
AP_WS_Server()->SendRadiusAuthenticationData(SerialNumber, Buffer,
NumberOfReceivedBytes);
} else {
poco_debug(Logger_,
fmt::format("Invalid AUTH packet received in proxy dropped. No serial number Source={}",
Socket_->address().toString()));
}
Logger_.debug(fmt::format("{}: {} Received {} bytes.", SerialNumber, P.PacketType(), NumberOfReceivedBytes));
DeviceRegistry()->SendRadiusAuthenticationData(
SerialNumber, Buffer,
NumberOfReceivedBytes);
} else if (P.IsAccounting()) {
auto SerialNumber = P.ExtractSerialNumberFromProxyState();
if(!SerialNumber.empty()) {
poco_debug(Logger_,
fmt::format("{}: {} Received {} bytes.", SerialNumber,
P.PacketType(), NumberOfReceivedBytes));
AP_WS_Server()->SendRadiusAccountingData(SerialNumber, Buffer,
NumberOfReceivedBytes);
} else {
poco_debug(Logger_,
fmt::format("Invalid ACCT packet received in proxy dropped. No serial number Source={}",
Socket_->address().toString()));
}
Logger_.debug(fmt::format("{}: {} Received {} bytes.", SerialNumber, P.PacketType(), NumberOfReceivedBytes));
DeviceRegistry()->SendRadiusAccountingData(
SerialNumber, Buffer,
NumberOfReceivedBytes);
} else if (P.IsAuthority()) {
}
} else {
@@ -142,15 +115,15 @@ namespace OpenWifi {
inline bool Connect() {
if(TryAgain_) {
Poco::TemporaryFile CertFile_(MicroServiceDataDirectory());
Poco::TemporaryFile KeyFile_(MicroServiceDataDirectory());
Poco::TemporaryFile CertFile_(MicroService::instance().DataDir());
Poco::TemporaryFile KeyFile_(MicroService::instance().DataDir());
std::vector<Poco::TemporaryFile> CaCertFiles_;
DecodeFile(CertFile_.path(), Server_.radsecCert);
DecodeFile(KeyFile_.path(), Server_.radsecKey);
for(auto &cert:Server_.radsecCacerts) {
CaCertFiles_.emplace_back(Poco::TemporaryFile(MicroServiceDataDirectory()));
CaCertFiles_.emplace_back(Poco::TemporaryFile(MicroService::instance().DataDir()));
DecodeFile(CaCertFiles_[CaCertFiles_.size()-1].path(), cert);
}
@@ -181,19 +154,18 @@ namespace OpenWifi {
Socket_->setBlocking(false);
Socket_->setNoDelay(true);
Socket_->setKeepAlive(true);
Socket_->setReceiveTimeout(Poco::Timespan(1 * 60 * 60,0));
Reactor_.addEventHandler(
*Socket_,
Poco::NObserver<RADSEC_server, Poco::Net::ReadableNotification>(
*this, &RADSEC_server::onData));
Poco::NObserver<RADSECserver, Poco::Net::ReadableNotification>(
*this, &RADSECserver::onData));
Reactor_.addEventHandler(
*Socket_, Poco::NObserver<RADSEC_server, Poco::Net::ErrorNotification>(
*this, &RADSEC_server::onError));
*Socket_, Poco::NObserver<RADSECserver, Poco::Net::ErrorNotification>(
*this, &RADSECserver::onError));
Reactor_.addEventHandler(
*Socket_,
Poco::NObserver<RADSEC_server, Poco::Net::ShutdownNotification>(
*this, &RADSEC_server::onShutdown));
Poco::NObserver<RADSECserver, Poco::Net::ShutdownNotification>(
*this, &RADSECserver::onShutdown));
Socket_->setBlocking(false);
Socket_->setNoDelay(true);
Socket_->setKeepAlive(true);
@@ -219,19 +191,26 @@ namespace OpenWifi {
std::unique_lock G(Mutex_);
Reactor_.removeEventHandler(
*Socket_, Poco::NObserver<RADSEC_server, Poco::Net::ReadableNotification>(
*this, &RADSEC_server::onData));
*Socket_, Poco::NObserver<RADSECserver, Poco::Net::ReadableNotification>(
*this, &RADSECserver::onData));
Reactor_.removeEventHandler(
*Socket_, Poco::NObserver<RADSEC_server, Poco::Net::ErrorNotification>(
*this, &RADSEC_server::onError));
*Socket_, Poco::NObserver<RADSECserver, Poco::Net::ErrorNotification>(
*this, &RADSECserver::onError));
Reactor_.removeEventHandler(
*Socket_, Poco::NObserver<RADSEC_server, Poco::Net::ShutdownNotification>(
*this, &RADSEC_server::onShutdown));
*Socket_, Poco::NObserver<RADSECserver, Poco::Net::ShutdownNotification>(
*this, &RADSECserver::onShutdown));
Connected_ = false;
}
poco_information(Logger_,"Disconnecting.");
}
inline void Stop() {
TryAgain_ = false;
Disconnect();
ReconnectorThr_.wakeUp();
ReconnectorThr_.join();
}
static void DecodeFile(const std::string &filename, const std::string &s) {
std::ofstream sec_file(filename,std::ios_base::out|std::ios_base::trunc|std::ios_base::binary);
std::stringstream is(s);
@@ -259,14 +238,14 @@ namespace OpenWifi {
}
private:
std::recursive_mutex Mutex_;
std::shared_mutex Mutex_;
Poco::Net::SocketReactor &Reactor_;
GWObjects::RadiusProxyServerEntry Server_;
Poco::Logger &Logger_;
std::atomic_bool Connected_=false;
std::atomic_bool TryAgain_=true;
std::unique_ptr<Poco::Net::SecureStreamSocket> Socket_;
Poco::Thread ReconnectThread_;
Poco::Thread ReconnectorThr_;
std::unique_ptr<Poco::Crypto::X509Certificate> Peer_Cert_;
volatile bool Connected_=false;
volatile bool TryAgain_=true;
};
}

View File

@@ -8,12 +8,10 @@
#include "RESTAPI_RPC.h"
#include "CommandManager.h"
#include "AP_WS_Server.h"
#include "DeviceRegistry.h"
#include "StorageService.h"
#include "framework/ow_constants.h"
#include "framework/RESTAPI_Handler.h"
#include "ParseWifiScan.h"
#include "framework/utils.h"
namespace OpenWifi::RESTAPI_RPC {
void SetCommandStatus(GWObjects::CommandDetails &Cmd,
@@ -50,16 +48,16 @@ namespace OpenWifi::RESTAPI_RPC {
// then we should just add the command to
// the DB and let it figure out when to deliver the command.
auto SerialNumberInt = Utils::SerialNumberToInt(Cmd.SerialNumber);
if (Cmd.RunAt || (!AP_WS_Server()->Connected(SerialNumberInt) && RetryLater)) {
if (Cmd.RunAt || (!DeviceRegistry()->Connected(SerialNumberInt) && RetryLater)) {
Logger.information(fmt::format("{},{}: Command will be run in the future or when device is connected again.", Cmd.UUID, RPCID));
SetCommandStatus(Cmd, Request, Response, Handler, Storage::CommandExecutionType::COMMAND_PENDING, Logger);
return;
} else if ((!AP_WS_Server()->Connected(SerialNumberInt) && !RetryLater)){
} else if ((!DeviceRegistry()->Connected(SerialNumberInt) && !RetryLater)){
Logger.information(fmt::format("{},{}: Command canceled. Device is not connected. Command will not be retried.", Cmd.UUID, RPCID));
return SetCommandStatus(Cmd, Request, Response, Handler, Storage::CommandExecutionType::COMMAND_FAILED, Logger);
}
Cmd.Executed = Utils::Now();
Cmd.Executed = OpenWifi::Now();
bool Sent;
std::chrono::time_point<std::chrono::high_resolution_clock> rpc_submitted = std::chrono::high_resolution_clock::now();
@@ -126,7 +124,7 @@ namespace OpenWifi::RESTAPI_RPC {
}
Cmd.Results = ResultText.str();
Cmd.Status = "completed";
Cmd.Completed = Utils::Now();
Cmd.Completed = OpenWifi::Now();
Cmd.executionTime = rpc_execution_time.count();
if (Cmd.ErrorCode && Cmd.Command == uCentralProtocol::TRACE) {

View File

@@ -16,7 +16,7 @@
#include "RESTObjects/RESTAPI_GWobjects.h"
#include "StorageService.h"
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi::RESTAPI_RPC {

View File

@@ -6,11 +6,13 @@
// Arilia Wireless Inc.
//
#include <ctime>
#include "Poco/JSON/Parser.h"
#include "Poco/JSON/Stringifier.h"
#include "RESTAPI_blacklist.h"
#include "StorageService.h"
#include "framework/ow_constants.h"
#include "framework/utils.h"
namespace OpenWifi {
void RESTAPI_blacklist::DoDelete() {
@@ -66,7 +68,7 @@ namespace OpenWifi {
}
D.author = UserInfo_.userinfo.email;
D.created = Utils::Now();
D.created = OpenWifi::Now();
if(StorageService()->AddBlackListDevice(D)) {
GWObjects::BlackListedDevice CreatedDevice;

View File

@@ -8,12 +8,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_blacklist : public RESTAPIHandler {
public:
RESTAPI_blacklist(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server , uint64_t TransactionId , bool Internal)
RESTAPI_blacklist(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server , uint64_t TransactionId , bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_POST,

View File

@@ -4,12 +4,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_blacklist_list : public RESTAPIHandler {
public:
RESTAPI_blacklist_list(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_blacklist_list(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},

View File

@@ -4,12 +4,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_capabilities_handler : public RESTAPIHandler {
public:
RESTAPI_capabilities_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_capabilities_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},

View File

@@ -8,12 +8,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_command : public RESTAPIHandler {
public:
RESTAPI_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_command(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_DELETE,

View File

@@ -8,12 +8,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_commands : public RESTAPIHandler {
public:
RESTAPI_commands(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_commands(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_DELETE,

View File

@@ -15,7 +15,6 @@
#include "framework/ow_constants.h"
#include "framework/ConfigurationValidator.h"
#include "framework/orm.h"
#include "framework/utils.h"
namespace OpenWifi {
void RESTAPI_default_configuration::DoGet() {
@@ -67,7 +66,7 @@ namespace OpenWifi {
return BadRequest(RESTAPI::Errors::ConfigBlockInvalid);
}
DefConfig.Created = DefConfig.LastModified = Utils::Now();
DefConfig.Created = DefConfig.LastModified = OpenWifi::Now();
if (StorageService()->CreateDefaultConfiguration(Name, DefConfig)) {
return OK();
}
@@ -97,7 +96,7 @@ namespace OpenWifi {
Existing.Configuration = NewConfig.Configuration;
}
Existing.LastModified = Utils::Now();
Existing.LastModified = OpenWifi::Now();
AssignIfPresent(Obj,"description",Existing.Description);
if(Obj->has("modelIds"))
Existing.Models = NewConfig.Models;

View File

@@ -8,12 +8,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_default_configuration : public RESTAPIHandler {
public:
RESTAPI_default_configuration(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_default_configuration(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest::HTTP_POST,

View File

@@ -8,12 +8,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_default_configurations : public RESTAPIHandler {
public:
RESTAPI_default_configurations(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_default_configurations(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},

View File

@@ -4,12 +4,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_deviceDashboardHandler : public RESTAPIHandler {
public:
RESTAPI_deviceDashboardHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_deviceDashboardHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest::HTTP_POST,

View File

@@ -13,6 +13,7 @@
#include "AP_WS_Server.h"
#include "CentralConfig.h"
#include "DeviceRegistry.h"
#include "FileUploader.h"
#include "RESTAPI_RPC.h"
#include "RESTAPI_device_commandHandler.h"
@@ -20,14 +21,9 @@
#include "StorageService.h"
#include "TelemetryStream.h"
#include "CommandManager.h"
#include "framework/ConfigurationValidator.h"
#include "framework/KafkaTopics.h"
#include "framework/ow_constants.h"
#include "framework/KafkaManager.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
#include "rttys/RTTYS_server.h"
namespace OpenWifi {
@@ -64,11 +60,11 @@ namespace OpenWifi {
} else if (Command_ == RESTAPI::Protocol::STATUS) {
return GetStatus();
} else if (Command_ == RESTAPI::Protocol::RTTY) {
if(!AP_WS_Server()->Connected(SerialNumberInt_)) {
if(!DeviceRegistry()->Connected(SerialNumberInt_)) {
CallCanceled(Command_.c_str(), RESTAPI::Errors::DeviceNotConnected);
return BadRequest(RESTAPI::Errors::DeviceNotConnected);
}
auto UUID = MicroServiceCreateUUID();
auto UUID = MicroService::CreateUUID();
auto RPC = CommandManager()->NextRPCId();
poco_debug(Logger_,fmt::format("Command rtty TID={} can proceed. Identified as {} and RPCID as {}. thr_id={}",
TransactionId_, UUID, RPC,
@@ -169,7 +165,7 @@ namespace OpenWifi {
for(const auto &Command:PostCommands) {
if(Command_==Command.Command) {
Poco::Thread::current()->setName(fmt::format("{}:{}:{}",Command.Command, TransactionId_,SerialNumber_));
if(Command.RequireConnection && !AP_WS_Server()->Connected(SerialNumberInt_)) {
if(Command.RequireConnection && !DeviceRegistry()->Connected(SerialNumberInt_)) {
CallCanceled(Command.Command, RESTAPI::Errors::DeviceNotConnected);
return BadRequest(RESTAPI::Errors::DeviceNotConnected);
}
@@ -179,7 +175,7 @@ namespace OpenWifi {
CallCanceled(Command.Command, RESTAPI::Errors::DeviceIsAlreadyBusy, Extra);
return BadRequest(RESTAPI::Errors::DeviceIsAlreadyBusy, Extra);
}
auto UUID = MicroServiceCreateUUID();
auto UUID = MicroService::CreateUUID();
auto RPC = CommandManager()->NextRPCId();
poco_debug(Logger_,fmt::format("Command {} TID={} can proceed. Identified as {} and RPCID as {}. thr_id={}",
Command.Command, TransactionId_, UUID, RPC,
@@ -220,14 +216,14 @@ namespace OpenWifi {
Poco::Thread::current()->id()));
if (QB_.LastOnly) {
std::string Stats;
if (AP_WS_Server()->GetStatistics(SerialNumber_, Stats) && !Stats.empty()) {
if (DeviceRegistry()->GetStatistics(SerialNumber_, Stats)) {
Poco::JSON::Parser P;
if (Stats.empty())
Stats = uCentralProtocol::EMPTY_JSON_DOC;
auto Obj = P.parse(Stats).extract<Poco::JSON::Object::Ptr>();
return ReturnObject(*Obj);
}
return BadRequest(RESTAPI::Errors::DeviceNotConnected);
return NotFound();
}
std::vector<GWObjects::Statistics> Stats;
@@ -267,7 +263,7 @@ namespace OpenWifi {
Poco::Thread::current()->id()));
GWObjects::ConnectionState State;
if (AP_WS_Server()->GetState(SerialNumber_, State)) {
if (DeviceRegistry()->GetState(SerialNumber_, State)) {
Poco::JSON::Object RetObject;
State.to_json(RetObject);
return ReturnObject(RetObject);
@@ -323,7 +319,7 @@ namespace OpenWifi {
if (QB_.LastOnly) {
GWObjects::HealthCheck HC;
if (AP_WS_Server()->GetHealthcheck(SerialNumber_, HC)) {
if (DeviceRegistry()->GetHealthcheck(SerialNumber_, HC)) {
Poco::JSON::Object Answer;
HC.to_json(Answer);
return ReturnObject(Answer);
@@ -513,7 +509,7 @@ namespace OpenWifi {
Params.stringify(ParamStream);
Cmd.Details = ParamStream.str();
// AP_WS_Server()->SetPendingUUID(SerialNumber_, NewUUID);
// DeviceRegistry()->SetPendingUUID(SerialNumber_, NewUUID);
return RESTAPI_RPC::WaitForCommand(CMD_RPC,true,Cmd, Params, *Request, *Response, timeout, nullptr, this, Logger_);
}
return BadRequest(RESTAPI::Errors::RecordNotUpdated);
@@ -917,39 +913,39 @@ namespace OpenWifi {
void RESTAPI_device_commandHandler::Rtty(const std::string &CMD_UUID, uint64_t CMD_RPC, std::chrono::milliseconds timeout) {
Logger_.information(fmt::format("RTTY({},{}): TID={} user={} serial={}", CMD_UUID, CMD_RPC, TransactionId_, Requester(), SerialNumber_));
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
if (MicroServiceConfigGetBool("rtty.enabled", false)) {
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
if (MicroService::instance().ConfigGetBool("rtty.enabled", false)) {
GWObjects::Device Device;
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
if (StorageService()->GetDevice(SerialNumber_, Device)) {
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
GWObjects::RttySessionDetails Rtty{
.SerialNumber = SerialNumber_,
.Server = MicroServiceConfigGetString("rtty.server", "localhost"),
.Port = MicroServiceConfigGetInt("rtty.port", 5912),
.Token = MicroServiceConfigGetString("rtty.token", "nothing"),
.TimeOut = MicroServiceConfigGetInt("rtty.timeout", 60),
.ConnectionId = Utils::ComputeHash(SerialNumber_,Utils::Now()).substr(0,RTTY_DEVICE_TOKEN_LENGTH),
.Started = Utils::Now(),
.Server = MicroService::instance().ConfigGetString("rtty.server", "localhost"),
.Port = MicroService::instance().ConfigGetInt("rtty.port", 5912),
.Token = MicroService::instance().ConfigGetString("rtty.token", "nothing"),
.TimeOut = MicroService::instance().ConfigGetInt("rtty.timeout", 60),
.ConnectionId = Utils::ComputeHash(SerialNumber_,OpenWifi::Now()).substr(0,32),
.Started = OpenWifi::Now(),
.CommandUUID = CMD_UUID,
.ViewPort = MicroServiceConfigGetInt("rtty.viewport", 5913),
.ViewPort = MicroService::instance().ConfigGetInt("rtty.viewport", 5913),
.DevicePassword = ""
};
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
if(RTTYS_server()->UseInternal()) {
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
Rtty.Token = Utils::ComputeHash(UserInfo_.webtoken.refresh_token_,Utils::Now()).substr(0,RTTY_DEVICE_TOKEN_LENGTH);
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
Rtty.Token = Utils::ComputeHash(UserInfo_.webtoken.refresh_token_,OpenWifi::Now()).substr(0,32);
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
if(!RTTYS_server()->CreateEndPoint(Rtty.ConnectionId, Rtty.Token, Requester(), SerialNumber_)) {
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
return BadRequest(RESTAPI::Errors::MaximumRTTYSessionsReached);
}
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
}
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
Poco::JSON::Object ReturnedObject;
Rtty.to_json(ReturnedObject);
@@ -961,7 +957,7 @@ namespace OpenWifi {
Cmd.UUID = CMD_UUID;
Cmd.Command = uCentralProtocol::RTTY;
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
Poco::JSON::Object Params;
Params.set(uCentralProtocol::METHOD, uCentralProtocol::RTTY);
@@ -974,15 +970,15 @@ namespace OpenWifi {
Params.set(uCentralProtocol::TIMEOUT, Rtty.TimeOut);
Params.set(uCentralProtocol::PASSWORD, Device.DevicePassword);
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
std::stringstream ParamStream;
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
Params.stringify(ParamStream);
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
Cmd.Details = ParamStream.str();
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
Logger_.information(fmt::format("RTTY: user={} serial={} rttyid={} token={} cmd={}.", Requester(), SerialNumber_, Rtty.ConnectionId, Rtty.Token, CMD_UUID));
// poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
poco_debug(Logger_,fmt::format("RTTY_DEBUG {} ", __LINE__ ));
return RESTAPI_RPC::WaitForCommand(CMD_RPC,false,Cmd, Params, *Request, *Response, timeout, &ReturnedObject, this, Logger_);
}
return NotFound();
@@ -991,13 +987,10 @@ namespace OpenWifi {
return ReturnStatus(Poco::Net::HTTPResponse::HTTP_SERVICE_UNAVAILABLE);
}
// #define DBG { std::cout << __LINE__ << std::endl; }
void RESTAPI_device_commandHandler::Telemetry(const std::string &CMD_UUID, uint64_t CMD_RPC, [[maybe_unused]] std::chrono::milliseconds timeout){
Logger_.information(fmt::format("TELEMETRY({},{}): TID={} user={} serial={}", CMD_UUID, CMD_RPC, TransactionId_, Requester(), SerialNumber_));
const auto &Obj = ParsedBody_;
if (Obj->has(RESTAPI::Protocol::SERIALNUMBER) &&
Obj->has(RESTAPI::Protocol::INTERVAL) &&
Obj->has(RESTAPI::Protocol::TYPES)) {
@@ -1012,8 +1005,8 @@ namespace OpenWifi {
Obj->stringify(oooss);
// std::cout << "Payload:" << oooss.str() << std::endl;
std::uint64_t Lifetime = 60 * 60 ; // 1 hour
std::uint64_t Interval = 5;
uint64_t Lifetime = 60 * 60 ; // 1 hour
uint64_t Interval = 5;
bool KafkaOnly = false;
if(Obj->has("kafka")) {
@@ -1032,16 +1025,16 @@ namespace OpenWifi {
if(!StatusOnly) {
if (KafkaOnly) {
if (Interval) {
AP_WS_Server()->SetKafkaTelemetryReporting(CMD_RPC,IntSerialNumber, Interval, Lifetime);
DeviceRegistry()->SetKafkaTelemetryReporting(CMD_RPC,IntSerialNumber, Interval, Lifetime);
Answer.set("action", "Kafka telemetry started.");
Answer.set("uuid", CMD_UUID);
} else {
AP_WS_Server()->StopKafkaTelemetry(CMD_RPC,IntSerialNumber);
DeviceRegistry()->StopKafkaTelemetry(CMD_RPC,IntSerialNumber);
Answer.set("action", "Kafka telemetry stopped.");
}
} else {
if (Interval) {
AP_WS_Server()->SetWebSocketTelemetryReporting(CMD_RPC, IntSerialNumber, Interval,
DeviceRegistry()->SetWebSocketTelemetryReporting(CMD_RPC,IntSerialNumber, Interval,
Lifetime);
std::string EndPoint;
if (TelemetryStream()->CreateEndpoint(Utils::SerialNumberToInt(SerialNumber_), EndPoint, CMD_UUID)) {
@@ -1054,7 +1047,7 @@ namespace OpenWifi {
}
} else {
Answer.set("action", "WebSocket telemetry stopped.");
AP_WS_Server()->StopWebSocketTelemetry(CMD_RPC,IntSerialNumber);
DeviceRegistry()->StopWebSocketTelemetry(CMD_RPC,IntSerialNumber);
}
}
} else {
@@ -1062,10 +1055,10 @@ namespace OpenWifi {
}
bool TelemetryRunning;
std::uint64_t TelemetryWebSocketCount, TelemetryKafkaCount, TelemetryInterval,
uint64_t TelemetryWebSocketCount, TelemetryKafkaCount, TelemetryInterval,
TelemetryWebSocketTimer, TelemetryKafkaTimer, TelemetryWebSocketPackets,
TelemetryKafkaPackets;
AP_WS_Server()->GetTelemetryParameters(IntSerialNumber,TelemetryRunning,
DeviceRegistry()->GetTelemetryParameters(IntSerialNumber,TelemetryRunning,
TelemetryInterval,
TelemetryWebSocketTimer,
TelemetryKafkaTimer,

View File

@@ -8,12 +8,13 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
#include "framework/ow_constants.h"
namespace OpenWifi {
class RESTAPI_device_commandHandler : public RESTAPIHandler {
public:
RESTAPI_device_commandHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_device_commandHandler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest::HTTP_POST,

View File

@@ -9,12 +9,11 @@
#include "RESTAPI_device_handler.h"
#include "CentralConfig.h"
#include "ConfigurationCache.h"
#include "Poco/JSON/Parser.h"
#include "StorageService.h"
#include "framework/ConfigurationValidator.h"
#include "framework/MicroService.h"
#include "framework/ow_constants.h"
#include "framework/utils.h"
#include "RESTAPI_device_helper.h"
namespace OpenWifi {
@@ -132,11 +131,11 @@ namespace OpenWifi {
for(auto &i:Device.Notes) {
i.createdBy = UserInfo_.userinfo.email;
i.created = Utils::Now();
i.created = OpenWifi::Now();
}
Config::Config NewConfig(Device.Configuration);
Device.UUID = Utils::Now();
Device.UUID = OpenWifi::Now();
NewConfig.SetUUID(Device.UUID);
Device.Configuration = NewConfig.get();
@@ -175,7 +174,7 @@ namespace OpenWifi {
return BadRequest(RESTAPI::Errors::ConfigBlockInvalid);
}
Config::Config NewConfig(NewDevice.Configuration);
uint64_t NewConfigUUID = Utils::Now();
uint64_t NewConfigUUID = OpenWifi::Now();
NewConfig.SetUUID(NewConfigUUID);
Existing.Configuration = NewConfig.get();
Existing.UUID = NewConfigUUID;
@@ -189,11 +188,11 @@ namespace OpenWifi {
for(auto &i:NewDevice.Notes) {
i.createdBy = UserInfo_.userinfo.email;
i.created = Utils::Now();
i.created = OpenWifi::Now();
Existing.Notes.push_back(i);
}
Existing.LastConfigurationChange = Utils::Now();
Existing.LastConfigurationChange = OpenWifi::Now();
if (StorageService()->UpdateDevice(Existing)) {
SetCurrentConfigurationID(SerialNumber, Existing.UUID);
Poco::JSON::Object DevObj;

View File

@@ -8,12 +8,14 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_device_handler : public RESTAPIHandler {
public:
RESTAPI_device_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_device_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_GET, Poco::Net::HTTPRequest::HTTP_POST,

View File

@@ -6,17 +6,17 @@
#include "RESTObjects/RESTAPI_GWobjects.h"
#include "StorageService.h"
#include "AP_WS_Server.h"
#include "DeviceRegistry.h"
namespace OpenWifi {
inline void CompleteDeviceInfo(const GWObjects::Device & Device, Poco::JSON::Object & Answer) {
GWObjects::ConnectionState CS;
AP_WS_Server()->GetState(Device.SerialNumber,CS);
DeviceRegistry()->GetState(Device.SerialNumber,CS);
GWObjects::HealthCheck HC;
AP_WS_Server()->GetHealthcheck(Device.SerialNumber, HC);
DeviceRegistry()->GetHealthcheck(Device.SerialNumber, HC);
std::string Stats;
AP_WS_Server()->GetStatistics(Device.SerialNumber, Stats);
DeviceRegistry()->GetStatistics(Device.SerialNumber, Stats);
Poco::JSON::Object DeviceInfo;
Device.to_json(DeviceInfo);

View File

@@ -12,10 +12,10 @@
#include "RESTAPI_devices_handler.h"
#include "StorageService.h"
#include "framework/ow_constants.h"
#include "framework/MicroService.h"
#include "RESTAPI/RESTAPI_device_helper.h"
#include "Poco/StringTokenizer.h"
#include "framework/orm.h"
#include "AP_WS_Server.h"
namespace OpenWifi {
@@ -61,7 +61,7 @@ namespace OpenWifi {
GWObjects::DeviceConnectionStatistics DCS;
Poco::JSON::Object Answer;
AP_WS_Server()->AverageDeviceStatistics(DCS.connectedDevices,DCS.averageConnectionTime, DCS.connectingDevices);
DeviceRegistry()->AverageDeviceStatistics(DCS.connectedDevices,DCS.averageConnectionTime, DCS.connectingDevices);
DCS.to_json(Answer);
return ReturnObject(Answer);
}

View File

@@ -8,12 +8,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_devices_handler : public RESTAPIHandler {
public:
RESTAPI_devices_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_devices_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},

View File

@@ -8,12 +8,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_file : public RESTAPIHandler {
public:
RESTAPI_file(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_file(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_DELETE,

View File

@@ -4,12 +4,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_iptocountry_handler : public RESTAPIHandler {
public:
RESTAPI_iptocountry_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting & Server, uint64_t TransactionId, bool Internal)
RESTAPI_iptocountry_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer & Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},

View File

@@ -4,12 +4,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_ouis : public RESTAPIHandler {
public:
RESTAPI_ouis(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, bool Internal)
RESTAPI_ouis(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer &Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{
Poco::Net::HTTPRequest::HTTP_GET,

View File

@@ -9,9 +9,6 @@
namespace OpenWifi {
void RESTAPI_radiusProxyConfig_handler::DoGet() {
Logger_.information(fmt::format("GET-RADIUS-PROXY-CONFIG: TID={} user={} thr_id={}",
TransactionId_, Requester(),
Poco::Thread::current()->id()));
GWObjects::RadiusProxyPoolList C;
RADIUS_proxy_server()->GetConfig(C);
Poco::JSON::Object Answer;
@@ -20,9 +17,6 @@ namespace OpenWifi {
}
void RESTAPI_radiusProxyConfig_handler::DoDelete() {
Logger_.information(fmt::format("DELETE-RADIUS-PROXY-CONFIG: TID={} user={} thr_id={}",
TransactionId_, Requester(),
Poco::Thread::current()->id()));
if(!Internal_ && (UserInfo_.userinfo.userRole!=SecurityObjects::ROOT && UserInfo_.userinfo.userRole!=SecurityObjects::ADMIN)) {
return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED);
}
@@ -31,9 +25,7 @@ namespace OpenWifi {
}
void RESTAPI_radiusProxyConfig_handler::DoPut() {
Logger_.information(fmt::format("MODIFY-RADIUS-PROXY-CONFIG: TID={} user={} thr_id={}",
TransactionId_, Requester(),
Poco::Thread::current()->id()));
if(!Internal_ && (UserInfo_.userinfo.userRole!=SecurityObjects::ROOT && UserInfo_.userinfo.userRole!=SecurityObjects::ADMIN)) {
return UnAuthorized(RESTAPI::Errors::ACCESS_DENIED);
}
@@ -49,8 +41,6 @@ namespace OpenWifi {
return BadRequest(RESTAPI::Errors::PoolNameInvalid);
}
for(const auto &config:{pool.acctConfig,pool.authConfig,pool.coaConfig}) {
if(config.servers.empty())
continue;
if(config.strategy!="random" && config.strategy!="round_robin" && config.strategy!="weighted") {
return BadRequest(RESTAPI::Errors::InvalidRadiusProxyStrategy);
}
@@ -73,9 +63,6 @@ namespace OpenWifi {
}
}
Logger_.information(fmt::format("MODIFY-RADIUS-PROXY-CONFIG: TID={} user={} thr_id={}. Applying new RADIUS Proxy config.",
TransactionId_, Requester(),
Poco::Thread::current()->id()));
RADIUS_proxy_server()->SetConfig(C);
return ReturnObject(*ParsedBody_);
}

View File

@@ -4,13 +4,13 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_radiusProxyConfig_handler : public RESTAPIHandler {
public:
RESTAPI_radiusProxyConfig_handler(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L,
RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId,
RESTAPI_GenericServer &Server, uint64_t TransactionId,
bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{Poco::Net::HTTPRequest::HTTP_GET,

View File

@@ -2,6 +2,8 @@
// Created by stephane bourque on 2021-10-23.
//
#include "framework/MicroService.h"
#include "RESTAPI/RESTAPI_blacklist.h"
#include "RESTAPI/RESTAPI_blacklist_list.h"
#include "RESTAPI/RESTAPI_command.h"
@@ -18,13 +20,11 @@
#include "RESTAPI/RESTAPI_telemetryWebSocket.h"
#include "RESTAPI/RESTAPI_iptocountry_handler.h"
#include "RESTAPI/RESTAPI_radiusProxyConfig_handler.h"
#include "framework/RESTAPI_SystemCommand.h"
#include "framework/RESTAPI_WebSocketServer.h"
namespace OpenWifi {
Poco::Net::HTTPRequestHandler * RESTAPI_ExtRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t TransactionId) {
Poco::Logger & L, RESTAPI_GenericServer & S, uint64_t TransactionId) {
return RESTAPI_Router<
RESTAPI_devices_handler,
@@ -47,7 +47,7 @@ namespace OpenWifi {
}
Poco::Net::HTTPRequestHandler * RESTAPI_IntRouter(const std::string &Path, RESTAPIHandler::BindingMap &Bindings,
Poco::Logger & L, RESTAPI_GenericServerAccounting & S, uint64_t TransactionId) {
Poco::Logger & L, RESTAPI_GenericServer & S, uint64_t TransactionId) {
return RESTAPI_Router_I<
RESTAPI_devices_handler,

View File

@@ -9,8 +9,6 @@
namespace OpenWifi {
// #define DBG { std::cout << __LINE__ << std::endl; }
void RESTAPI_telemetryWebSocket::DoGet() {
// try and upgrade this session to websocket...
if (Request->find("Upgrade") != Request->end() &&
@@ -34,15 +32,16 @@ void RESTAPI_telemetryWebSocket::DoGet() {
auto SerialNumber = Utils::SerialNumberToInt(SNum);
if(!TelemetryStream()->IsValidEndPoint(SerialNumber,UUID)) {
Logger_.warning(fmt::format("Illegal telemetry request for Serial: {}, UUID: {}", SNum, UUID));
Logger_.warning(fmt::format("Illegal telemetry request for S: {}, UUID: {}", SerialNumber, UUID));
Response->setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
Response->setContentLength(0);
Response->send();
return;
}
auto WS = std::make_unique<Poco::Net::WebSocket>(*Request, *Response);
TelemetryStream()->NewClient(UUID, SerialNumber, std::move(WS) );
return;
new TelemetryClient(UUID, SerialNumber, std::move(WS), TelemetryStream()->NextReactor(), Logger_);
} catch (const Poco::Net::WebSocketException &E) {
Logger_.log(E);
switch (E.code()) {

View File

@@ -4,12 +4,12 @@
#pragma once
#include "framework/RESTAPI_Handler.h"
#include "framework/MicroService.h"
namespace OpenWifi {
class RESTAPI_telemetryWebSocket : public RESTAPIHandler {
public:
RESTAPI_telemetryWebSocket(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServerAccounting &Server, uint64_t TransactionId, bool Internal)
RESTAPI_telemetryWebSocket(const RESTAPIHandler::BindingMap &bindings, Poco::Logger &L, RESTAPI_GenericServer &Server, uint64_t TransactionId, bool Internal)
: RESTAPIHandler(bindings, L,
std::vector<std::string>{ Poco::Net::HTTPRequest::HTTP_GET,
Poco::Net::HTTPRequest::HTTP_OPTIONS},

View File

@@ -4,7 +4,7 @@
#include "RESTAPI_AnalyticsObjects.h"
#include "RESTAPI_ProvObjects.h"
#include "framework/RESTAPI_utils.h"
#include "framework/MicroService.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;

View File

@@ -5,7 +5,6 @@
#pragma once
#include "RESTAPI_ProvObjects.h"
#include "framework/utils.h"
#include <vector>
namespace OpenWifi {
@@ -376,7 +375,7 @@ namespace OpenWifi {
};
struct WifiClientHistory {
uint64_t timestamp=Utils::Now();
uint64_t timestamp=OpenWifi::Now();
std::string station_id;
std::string bssid;
std::string ssid;

View File

@@ -3,7 +3,7 @@
//
#include "RESTAPI_CertObjects.h"
#include "framework/RESTAPI_utils.h"
#include "framework/MicroService.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
@@ -154,7 +154,6 @@ namespace OpenWifi::CertObjects {
field_to_json(Obj,"submitted", submitted);
field_to_json(Obj,"started", started);
field_to_json(Obj,"completed", completed);
field_to_json(Obj,"requesterUsername", requesterUsername);
}
bool JobEntry::from_json(const Poco::JSON::Object::Ptr &Obj) {
@@ -172,7 +171,6 @@ namespace OpenWifi::CertObjects {
field_from_json(Obj,"submitted", submitted);
field_from_json(Obj,"started", started);
field_from_json(Obj,"completed", completed);
field_from_json(Obj,"requesterUsername", requesterUsername);
return true;
} catch (...) {
}

View File

@@ -91,7 +91,6 @@ namespace OpenWifi::CertObjects {
uint64_t submitted=0;
uint64_t started=0;
uint64_t completed=0;
std::string requesterUsername;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);

View File

@@ -3,8 +3,7 @@
//
#include "RESTAPI_FMSObjects.h"
#include "framework/RESTAPI_utils.h"
#include "framework/utils.h"
#include "framework/MicroService.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
@@ -234,7 +233,7 @@ namespace OpenWifi::FMSObjects {
UnknownFirmwares_.clear();
totalSecondsOld_.clear();
numberOfDevices = 0 ;
snapshot = Utils::Now();
snapshot = OpenWifi::Now();
}
bool DeviceReport::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) {

View File

@@ -11,13 +11,12 @@
#include "Daemon.h"
#ifdef TIP_GATEWAY_SERVICE
#include "AP_WS_Server.h"
#include "DeviceRegistry.h"
#include "CapabilitiesCache.h"
#endif
#include "RESTAPI_GWobjects.h"
#include "framework/RESTAPI_utils.h"
#include "framework/utils.h"
#include "framework/MicroService.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
@@ -58,7 +57,7 @@ namespace OpenWifi::GWObjects {
#ifdef TIP_GATEWAY_SERVICE
ConnectionState ConState;
if (AP_WS_Server()->GetState(SerialNumber, ConState)) {
if (DeviceRegistry()->GetState(SerialNumber, ConState)) {
ConState.to_json(Obj);
} else {
field_to_json(Obj,"ipAddress", "");
@@ -207,7 +206,7 @@ namespace OpenWifi::GWObjects {
field_to_json(Obj,"started", started);
field_to_json(Obj,"sessionId", sessionId);
field_to_json(Obj,"connectionCompletionTime", connectionCompletionTime);
field_to_json(Obj,"totalConnectionTime", Utils::Now() - started);
field_to_json(Obj,"totalConnectionTime", OpenWifi::Now() - started);
switch(VerifiedCertificate) {
case NO_CERTIFICATE:
@@ -286,7 +285,7 @@ namespace OpenWifi::GWObjects {
lastContact.clear();
associations.clear();
numberOfDevices = 0 ;
snapshot = Utils::Now();
snapshot = OpenWifi::Now();
}
void CapabilitiesModel::to_json(Poco::JSON::Object &Obj) const{

View File

@@ -1,110 +0,0 @@
//
// Created by stephane bourque on 2021-08-31.
//
#include "framework/RESTAPI_utils.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
using OpenWifi::RESTAPI_utils::EmbedDocument;
#include "RESTAPI_OWLSobjects.h"
// SIM -> 0x53/0x073, 0x49/0x69, 0x4d/0x6d
namespace OpenWifi::OWLSObjects {
void SimulationDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id);
field_to_json(Obj,"name", name);
field_to_json(Obj,"gateway", gateway);
field_to_json(Obj,"certificate", certificate);
field_to_json(Obj,"key", key);
field_to_json(Obj,"macPrefix", macPrefix);
field_to_json(Obj,"deviceType", deviceType);
field_to_json(Obj,"devices", devices);
field_to_json(Obj,"healthCheckInterval", healthCheckInterval);
field_to_json(Obj,"stateInterval", stateInterval);
field_to_json(Obj,"minAssociations", minAssociations);
field_to_json(Obj,"maxAssociations", maxAssociations);
field_to_json(Obj,"minClients", minClients);
field_to_json(Obj,"maxClients", maxClients);
field_to_json(Obj,"simulationLength", simulationLength);
field_to_json(Obj,"threads", threads);
field_to_json(Obj,"clientInterval", clientInterval);
field_to_json(Obj,"keepAlive", keepAlive);
field_to_json(Obj,"reconnectInterval", reconnectInterval);
field_to_json(Obj,"concurrentDevices", concurrentDevices);
}
bool SimulationDetails::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,"gateway", gateway);
field_from_json(Obj,"certificate", certificate);
field_from_json(Obj,"key", key);
field_from_json(Obj,"macPrefix", macPrefix);
field_from_json(Obj,"deviceType", deviceType);
field_from_json(Obj,"devices", devices);
field_from_json(Obj,"healthCheckInterval", healthCheckInterval);
field_from_json(Obj,"stateInterval", stateInterval);
field_from_json(Obj,"minAssociations", minAssociations);
field_from_json(Obj,"maxAssociations", maxAssociations);
field_from_json(Obj,"minClients", minClients);
field_from_json(Obj,"maxClients", maxClients);
field_from_json(Obj,"simulationLength", simulationLength);
field_from_json(Obj,"threads", threads);
field_from_json(Obj,"clientInterval", clientInterval);
field_from_json(Obj,"keepAlive", keepAlive);
field_from_json(Obj,"reconnectInterval", reconnectInterval);
field_from_json(Obj,"concurrentDevices", concurrentDevices);
return true;
} catch(...) {
}
return false;
}
void SimulationDetailsList::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"list", list);
}
bool SimulationDetailsList::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"list", list);
return true;
} catch(...) {
}
return false;
}
void SimulationStatus::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"id", id);
field_to_json(Obj,"simulationId", simulationId);
field_to_json(Obj,"state", state);
field_to_json(Obj,"tx", tx);
field_to_json(Obj,"rx", rx);
field_to_json(Obj,"msgsTx", msgsTx);
field_to_json(Obj,"msgsRx", msgsRx);
field_to_json(Obj,"liveDevices", liveDevices);
field_to_json(Obj,"timeToFullDevices", timeToFullDevices);
field_to_json(Obj,"startTime", startTime);
field_to_json(Obj,"endTime", endTime);
field_to_json(Obj,"errorDevices", errorDevices);
field_to_json(Obj,"owner", owner);
}
void Dashboard::to_json([[maybe_unused]] Poco::JSON::Object &Obj) const {
}
bool Dashboard::from_json([[maybe_unused]] const Poco::JSON::Object::Ptr &Obj) {
return true;
}
void Dashboard::reset() {
}
}

View File

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

View File

@@ -8,9 +8,7 @@
#include "RESTAPI_ProvObjects.h"
#include "framework/RESTAPI_utils.h"
#include "framework/MicroServiceFuncs.h"
#include "framework/utils.h"
#include "framework/MicroService.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
@@ -1093,7 +1091,7 @@ namespace OpenWifi::ProvObjects {
}
bool UpdateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U, ObjectInfo &I) {
uint64_t Now = Utils::Now();
uint64_t Now = OpenWifi::Now();
if(O->has("name"))
I.name = O->get("name").toString();
@@ -1114,7 +1112,7 @@ namespace OpenWifi::ProvObjects {
}
bool CreateObjectInfo(const Poco::JSON::Object::Ptr &O, const SecurityObjects::UserInfo &U, ObjectInfo &I) {
uint64_t Now = Utils::Now();
uint64_t Now = OpenWifi::Now();
if(O->has("name"))
I.name = O->get("name").toString();
@@ -1132,14 +1130,14 @@ namespace OpenWifi::ProvObjects {
}
I.notes = N;
I.modified = I.created = Now;
I.id = MicroServiceCreateUUID();
I.id = MicroService::CreateUUID();
return true;
}
bool CreateObjectInfo([[maybe_unused]] const SecurityObjects::UserInfo &U, ObjectInfo &I) {
I.modified = I.created = Utils::Now();
I.id = MicroServiceCreateUUID();
I.modified = I.created = OpenWifi::Now();
I.id = MicroService::CreateUUID();
return true;
}
@@ -1161,40 +1159,5 @@ namespace OpenWifi::ProvObjects {
return false;
}
void RRMAlgorithmDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"name",name);
field_to_json(Obj,"parameters",parameters);
}
bool RRMAlgorithmDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"name",name);
field_from_json(Obj,"parameters",parameters);
return true;
} catch(...) {
}
return false;
}
void RRMDetails::to_json(Poco::JSON::Object &Obj) const {
field_to_json(Obj,"vendor",vendor);
field_to_json(Obj,"schedule",schedule);
field_to_json(Obj,"algorithms",algorithms);
}
bool RRMDetails::from_json(const Poco::JSON::Object::Ptr &Obj) {
try {
field_from_json(Obj,"vendor",vendor);
field_from_json(Obj,"schedule",schedule);
field_from_json(Obj,"algorithms",algorithms);
return true;
} catch(...) {
}
return false;
}
}

View File

@@ -8,7 +8,8 @@
#pragma once
#include "RESTObjects/RESTAPI_SecurityObjects.h"
#include <string>
#include "RESTAPI_SecurityObjects.h"
namespace OpenWifi::ProvObjects {
@@ -61,21 +62,6 @@ namespace OpenWifi::ProvObjects {
};
typedef std::vector<ManagementPolicy> ManagementPolicyVec;
struct RRMAlgorithmDetails {
std::string name;
std::string parameters;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct RRMDetails {
std::string vendor;
std::string schedule;
std::vector<RRMAlgorithmDetails> algorithms;
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
};
struct DeviceRules {
std::string rcOnly{"inherit"};
std::string rrm{"inherit"};

View File

@@ -9,7 +9,7 @@
#include "Poco/JSON/Parser.h"
#include "Poco/JSON/Stringifier.h"
#include "framework/RESTAPI_utils.h"
#include "framework/MicroService.h"
#include "RESTAPI_SecurityObjects.h"
using OpenWifi::RESTAPI_utils::field_to_json;
@@ -433,7 +433,7 @@ namespace OpenWifi::SecurityObjects {
SecurityObjects::NoteInfoVec NIV;
NIV = RESTAPI_utils::to_object_array<SecurityObjects::NoteInfo>(Obj->get("notes").toString());
for(auto const &i:NIV) {
SecurityObjects::NoteInfo ii{.created=(uint64_t)Utils::Now(), .createdBy=UInfo.email, .note=i.note};
SecurityObjects::NoteInfo ii{.created=(uint64_t)OpenWifi::Now(), .createdBy=UInfo.email, .note=i.note};
Notes.push_back(ii);
}
}
@@ -446,7 +446,7 @@ namespace OpenWifi::SecurityObjects {
bool MergeNotes(const NoteInfoVec & NewNotes, const UserInfo &UInfo, NoteInfoVec & ExistingNotes) {
for(auto const &i:NewNotes) {
SecurityObjects::NoteInfo ii{.created=(uint64_t)Utils::Now(), .createdBy=UInfo.email, .note=i.note};
SecurityObjects::NoteInfo ii{.created=(uint64_t)OpenWifi::Now(), .createdBy=UInfo.email, .note=i.note};
ExistingNotes.push_back(ii);
}
return true;

View File

@@ -14,7 +14,6 @@
#include "Poco/JSON/Object.h"
#include "Poco/Data/LOB.h"
#include "Poco/Data/LOBStream.h"
#include "framework/utils.h"
namespace OpenWifi {
uint64_t Now();
@@ -63,7 +62,7 @@ namespace OpenWifi {
std::string UserTypeToString(USER_ROLE U);
struct NoteInfo {
uint64_t created=0; // = Utils::Now();
uint64_t created=0; // = OpenWifi::Now();
std::string createdBy;
std::string note;
@@ -102,7 +101,7 @@ namespace OpenWifi {
std::string uuid;
std::string question;
std::string method;
uint64_t created = Utils::Now();
uint64_t created = OpenWifi::Now();
void to_json(Poco::JSON::Object &Obj) const;
bool from_json(const Poco::JSON::Object::Ptr &Obj);
@@ -252,8 +251,7 @@ namespace OpenWifi {
VERIFY_EMAIL,
SUB_FORGOT_PASSWORD,
SUB_VERIFY_EMAIL,
SUB_SIGNUP,
EMAIL_INVITATION
SUB_SIGNUP
};
struct ActionLink {
@@ -265,7 +263,7 @@ namespace OpenWifi {
std::string locale;
std::string message;
uint64_t sent=0;
uint64_t created=Utils::Now();
uint64_t created=OpenWifi::Now();
uint64_t expires=0;
uint64_t completed=0;
uint64_t canceled=0;

View File

@@ -3,11 +3,12 @@
//
#include "RESTAPI_SubObjects.h"
#include "framework/RESTAPI_utils.h"
#include "framework/MicroService.h"
using OpenWifi::RESTAPI_utils::field_to_json;
using OpenWifi::RESTAPI_utils::field_from_json;
namespace OpenWifi::SubObjects {
void HomeDeviceMode::to_json(Poco::JSON::Object &Obj) const {

View File

@@ -4,9 +4,6 @@
#include "SDKcalls.h"
#include "framework/OpenAPIRequests.h"
#include "framework/MicroServiceNames.h"
namespace OpenWifi {
bool SDKCalls::GetProvisioningConfiguration(const std::string &SerialNumber, std::string & Config) {

View File

@@ -4,7 +4,7 @@
#pragma once
#include <string>
#include "framework/MicroService.h"
namespace OpenWifi {
class SDKCalls {

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