Skip to content

Commit

Permalink
teliod cgi: Prepare teliod for cgi
Browse files Browse the repository at this point in the history
Prepared teliod structure to make cgi development easier.
  • Loading branch information
packgron committed Dec 18, 2024
1 parent 4276742 commit 51cd3b1
Show file tree
Hide file tree
Showing 14 changed files with 79 additions and 138 deletions.
Empty file.
12 changes: 11 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ black fix="false":
pylint:
docker run --rm -t -v$(pwd):/code 'ubuntu:22.04' sh -c "apt-get update && apt-get -y install python3-pip && cd code && pip3 install --no-deps -r requirements.txt && pipenv install --system && cd nat-lab && pipenv install --system && pylint -f colorized . --ignore telio_bindings.py"

# Start a dev web cgi server, for local teliod cgi development
web:
@echo "Go to http://127.0.0.1:8080/cgi-bin/teliod.cgi"
python3 -m http.server --cgi -d $(pwd)/contrib/http_root/ -b 127.0.0.1 8080


_udeps-install: _nightly-install
cargo +{{ nightly }} install cargo-udeps@0.1.47 --locked

Expand Down
1 change: 1 addition & 0 deletions ci/build_libtelio.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ def post_qnap_build_wrap_binary_on_qpkg(config, args):
"packages": {
"teliod": {"teliod": "teliod"},
},
"build_args": ("--features", "qnap"),
},
"macos": {
"packages": {
Expand Down
5 changes: 5 additions & 0 deletions clis/teliod/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ anyhow.workspace = true
smart-default = "0.7.1"
base64 = "0.22.1"
dirs = "4.0.0"
rust-cgi = { version = "0.7.1", optional = true }

[dev-dependencies]
rand = "0.8.5"

[features]
cgi = ["rust-cgi"]
qnap = ["cgi"]
13 changes: 13 additions & 0 deletions clis/teliod/src/cgi/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use rust_cgi::{http::StatusCode, text_response, Request, Response};

const CHAIN: &[fn(&Request) -> Option<Response>] = &[];

pub(crate) fn handle_request(request: Request) -> Response {
for handler in CHAIN.iter() {
if let Some(response) = handler(&request) {
return response;
}
}

text_response(StatusCode::BAD_REQUEST, "Invalid request.")
}
5 changes: 3 additions & 2 deletions clis/teliod/src/configure_interface.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::TeliodError;
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use std::net::IpAddr;
use std::process::Command;
use tracing::{error, info};
Expand All @@ -24,9 +24,10 @@ fn execute(command: &mut Command) -> Result<(), TeliodError> {
}
}

#[derive(Debug, Deserialize, PartialEq, Eq)]
#[derive(Default, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum InterfaceConfigurationProvider {
#[default]
Manual,
Ifconfig,
Iproute,
Expand Down
10 changes: 10 additions & 0 deletions clis/teliod/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ use tokio::{
};
use tracing::{debug, error};

#[cfg(feature = "cgi")]
mod cgi;
mod command_listener;
mod comms;
mod config;
Expand Down Expand Up @@ -44,6 +46,9 @@ enum Cmd {
Daemon { config_path: String },
#[clap(flatten)]
Client(ClientCmd),
#[cfg(feature = "cgi")]
#[clap(about = "Receive and parse http requests")]
Cgi,
}

#[derive(Debug, ThisError)]
Expand Down Expand Up @@ -134,5 +139,10 @@ async fn main() -> Result<(), TeliodError> {
Err(TeliodError::DaemonIsNotRunning)
}
}
#[cfg(feature = "cgi")]
Cmd::Cgi => {
rust_cgi::handle(cgi::handle_request);
Ok(())
}
}
}
1 change: 1 addition & 0 deletions contrib/http_root/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/*.log
17 changes: 17 additions & 0 deletions contrib/http_root/cgi-bin/teliod.cgi
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/env bash

set -eu -o pipefail

fail() {
cat $DEV_DIR/cargo.log
exit 0
}

DEV_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BIN_DIR="$(realpath $DEV_DIR/../../../target/debug/)"

cargo build -F cgi -p teliod >"$DEV_DIR/cargo.log" 2>&1 || fail

export PATH=$BIN_DIR:$PATH

exec teliod cgi
8 changes: 4 additions & 4 deletions qnap/package_routines
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,10 @@
#}"
#
PKG_POST_REMOVE="{
rm -rf /tmp/nordsecmeshnet
rm -f /home/Qhttpd/Web/NordSecurityMeshnet
rm -f /home/httpd/cgi-bin/qpkg/teliod.cgi
rm -f /var/log/teliod.log
$CMD_RM -rf /tmp/nordsecuritymeshnet
$CMD_RM -f /home/Qhttpd/Web/NordSecurityMeshnet
$CMD_RM -f /home/httpd/cgi-bin/qpkg/teliod.cgi
$CMD_RM -f /var/log/teliod.log
}"
#
######################################################################
Expand Down
3 changes: 2 additions & 1 deletion qnap/shared/NordSecMeshnet.sh
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
#!/bin/sh
set -eu

CONF=/etc/config/qpkg.conf
QPKG_NAME="NordSecurityMeshnet"


QPKG_ROOT=`/sbin/getcfg $QPKG_NAME Install_Path -f ${CONF}`
APACHE_ROOT=`/sbin/getcfg SHARE_DEF defWeb -d Qweb -f /etc/config/def_share.info`
export QNAP_QPKG=$QPKG_NAME
Expand Down
1 change: 0 additions & 1 deletion qnap/shared/teliod.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,3 @@
"config_provider": "manual"
}
}

135 changes: 6 additions & 129 deletions qnap/shared/teliod.cgi
Original file line number Diff line number Diff line change
@@ -1,131 +1,8 @@
#!/bin/bash
#!/bin/sh
set -eu

echo "Content-Type: application/json"
echo ""
CONF=/etc/config/qpkg.conf
QPKG_NAME="NordSecurityMeshnet"
QPKG_ROOT=`/sbin/getcfg $QPKG_NAME Install_Path -f ${CONF}`

# Varibles set by the HTTP web server
#
# $REQUEST_METHOD
# $QUERY_STRING
# $CONTENT_LENGTH

POST_DATA=""

if [[ "$REQUEST_METHOD" == "POST" || "$REQUEST_METHOD" == "PATCH" ]]; then
read -n $CONTENT_LENGTH POST_DATA
fi

QPKG_DIR="/share/CACHEDEV1_DATA/.qpkg/NordSecurityMeshnet"
APP_TMP_DIR="/tmp/nordsecuritymeshnet"
APP_CMD="$QPKG_DIR/teliod"
CONFIG_FILE="$QPKG_DIR/teliod.cfg"
LOG_FILE="/var/log/teliod.log"
PID_FILE="$APP_TMP_DIR/teliod.pid"

is_application_running() {
if [ -f ${PID_FILE} ]; then
PID=$(cat ${PID_FILE})
if [ -d /proc/${PID}/ ]; then
# application is running
return 0
fi
fi
# application is NOT running
return 1
}

send_response() {
local code=$1
local message=$2
echo "{\"code\": $code, \"message\": \"$message\"}"
exit $code
}

start_daemon() {
if is_application_running; then
send_response 400 "Application is already running."
fi
$APP_CMD daemon $CONFIG_FILE > $LOG_FILE 2>&1 &
if [[ $? -eq 0 ]]; then
echo $! > ${PID_FILE}
send_response 200 "Application started successfully."
else
echo $! > ${PID_FILE}
send_response 500 "Failed to start the application."
fi
}

stop_daemon() {
if [ -f ${PID_FILE} ]; then
PID=$(cat ${PID_FILE})
kill ${PID} || true
rm -f ${PID_FILE}
send_response 200 "Application stopped successfully."
else
send_response 400 "Application PID not found."
fi
}

update_config() {
NEW_CONFIG=$(echo "$POST_DATA" | jq -r '.config')
if [[ -z "$NEW_CONFIG" ]]; then
send_response 400 "No configuration provided."
fi
echo "$NEW_CONFIG" > $CONFIG_FILE
if [[ $? -eq 0 ]]; then
send_response 200 "Configuration updated successfully."
else
send_response 500 "Failed to update configuration."
fi
}

get_status() {
if is_application_running; then
STATUS=$($APP_CMD get-status)
echo "{\"code\": 200, \"status-report\": $STATUS}"
exit 0
else
send_response 400 "Application is not running."
fi
}

get_logs() {
if [[ -f $LOG_FILE ]]; then
LOGS=$(tail -n 100 $LOG_FILE | jq -R -s '.')
echo "{\"code\": 200, \"logs\": $LOGS}"
exit 0
else
send_response 404 "Log file not found."
fi
}

case "$REQUEST_METHOD" in
POST)
if [[ "$QUERY_STRING" == "action=start" ]]; then
start_daemon
elif [[ "$QUERY_STRING" == "action=stop" ]]; then
stop_daemon
else
send_response 400 "Invalid action for POST."
fi
;;
PATCH)
if [[ "$QUERY_STRING" == "action=update-config" ]]; then
update_config
else
send_response 400 "Invalid action for PATCH."
fi
;;
GET)
if [[ "$QUERY_STRING" == "action=get-status" ]]; then
get_status
elif [[ "$QUERY_STRING" == "action=get-logs" ]]; then
get_logs
else
send_response 400 "Invalid action for GET."
fi
;;
*)
send_response 405 "Method not allowed."
;;
esac
exec "${QPKG_ROOT}/teliod" cgi

0 comments on commit 51cd3b1

Please sign in to comment.