19 Commits

Author SHA1 Message Date
0486f2a285 Added initial COT Sensor payloads to support UAV Tools integration for Arma Drones 2026-04-13 08:03:31 -03:00
753dcab26e Added hellanmaaw winter support 2026-03-31 07:23:48 -03:00
2f53488ba8 Added video url prop to 3den editor/zeus, allowing to parse __video prop to cots 2026-03-31 07:21:29 -03:00
323339e679 Removed video addon, too simple for a specific addon 2026-03-31 07:20:19 -03:00
3f14a75e81 Added video url parser to CoT types 2026-03-31 07:19:39 -03:00
469a54c141 Added Hellanmma map support 2026-03-31 07:18:23 -03:00
2ee9030c00 Updated media folder 2026-03-26 14:45:08 -03:00
5b29a40990 Improved mTLS description on readme 2026-03-26 03:47:54 -03:00
708fe5e670 Fixed CoT queue during armatak connection to the TAK Server, running soft as butter 2026-03-26 03:45:05 -03:00
e32aadda4e Splitted Connection Module 2026-03-26 01:05:54 -03:00
c35b7f0268 Updated project readme file 2026-03-24 16:56:26 -03:00
876cf900c3 Changed dialogs and module UI to get mTLS needed params 2026-03-24 16:56:19 -03:00
778ac0ac54 Added the mTLS connection calls to zeus and 3den modules 2026-03-24 16:55:53 -03:00
b816144fb0 Added transport layer and configured extension commands to call mTLS socket connection 2026-03-24 16:55:36 -03:00
61ba9f6d63 Added connector and enrollment for mTLS client certificate auto enrollment on game sessions, will MOCK a official tak client behavior when authenticating 2026-03-24 16:55:05 -03:00
f88c02a7aa formatted some rust files for linting porpuses 2026-03-24 16:44:22 -03:00
5ffc08e6f1 Readded reqwest dependency to cargo toml, will be used for TAK Server API interaction on authencated tak server connections 2026-03-24 16:41:38 -03:00
9392380c78 Added hemtt private key to git ignore 2026-03-24 16:40:58 -03:00
a18343b81d Commented video module 2026-03-24 14:03:28 -03:00
63 changed files with 3237 additions and 843 deletions

1
.gitignore vendored
View File

@@ -3,6 +3,7 @@
hemtt hemtt
hemtt.exe hemtt.exe
*.biprivatekey *.biprivatekey
.hemttprivatekey
source/ source/
.vscode .vscode
releases/ releases/

1073
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -9,6 +9,10 @@ chrono = "0.4.39"
lazy_static = "1.5.0" lazy_static = "1.5.0"
log = "0.4.22" log = "0.4.22"
log4rs = "1.3.0" log4rs = "1.3.0"
reqwest = { version = "0.12.15", default-features = false, features = ["blocking", "json", "rustls-tls"] }
rcgen = { version = "0.13.2", default-features = false, features = ["crypto", "pem", "aws_lc_rs"] }
rustls = "0.23.23"
rustls-pemfile = "2.2.0"
serde = { version = "1.0.210", features = ["derive"] } serde = { version = "1.0.210", features = ["derive"] }
[dependencies.uuid] [dependencies.uuid]

View File

@@ -4,6 +4,10 @@
ARMATAK is a server side Arma 3 addons for streaming unit positions to TAK Clients in sessions on real locations maps. It can be runned both as a clientside mod or a serverside mod, when runned serverside, it will create a TCP Socket connection between Arma 3 and the TAK Server, sending the game session information into it. When used clientside, Arma 3 will host a websocket server that you can connect to your phone and mock the phone's location to the player's in game location. ARMATAK is a server side Arma 3 addons for streaming unit positions to TAK Clients in sessions on real locations maps. It can be runned both as a clientside mod or a serverside mod, when runned serverside, it will create a TCP Socket connection between Arma 3 and the TAK Server, sending the game session information into it. When used clientside, Arma 3 will host a websocket server that you can connect to your phone and mock the phone's location to the player's in game location.
The server-side CoT router supports two transports:
- Plain TCP, for legacy TAK ingress.
- Mutual TLS, using the TAK Server authentication API, so the Arma session can publish as an authenticated TAK device on port `8089`.
## Get in Touch ## Get in Touch
[Join the Discord Server for ARMATAK!](https://discord.gg/svK64PCycU) [Join the Discord Server for ARMATAK!](https://discord.gg/svK64PCycU)

View File

@@ -107,6 +107,12 @@ switch (toLower worldName) do {
case "rut_mandol": { case "rut_mandol": {
_realLocation = _position call armatak_fnc_convert_to_rut_mandol; _realLocation = _position call armatak_fnc_convert_to_rut_mandol;
}; };
case "hellanmaa": {
_realLocation = _position call armatak_fnc_convert_to_hellanmaa;
};
case "hellanmaaw": {
_realLocation = _position call armatak_fnc_convert_to_hellanmaa;
};
default { default {
_warning = format ["<t color='#FF8021'>ARMATAK</t><br/> %1", "Unsupported Map"]; _warning = format ["<t color='#FF8021'>ARMATAK</t><br/> %1", "Unsupported Map"];
[[_warning, 1.5]] call CBA_fnc_notify; [[_warning, 1.5]] call CBA_fnc_notify;

View File

@@ -78,6 +78,16 @@ class Cfg3den {
condition = "objectVehicle"; condition = "objectVehicle";
typeName = "STRING"; typeName = "STRING";
}; };
class armatak_attribute_video_url {
displayName = "Video URL (RTSP)";
tooltip = "RTSP stream URL for UAS Tool integration. When set, the drone will appear in the ATAK UAS Tool with FOV cone and video feed. Format: rtsp://address:port/path (e.g. rtsp://192.168.1.10:8554/live/drone1). Leave empty to disable UAS Tool integration for this entity.";
property = "armatak_attribute_video_url";
control = "Edit";
expression = "_this setVariable ['armatak_attribute_video_url',_value]";
defaultValue = "''";
condition = "objectVehicle";
typeName = "STRING";
};
}; };
}; };
}; };

View File

@@ -19,6 +19,12 @@ class CfgFunctions {
class send_marker_cot { class send_marker_cot {
file = "\armatak\armatak\addons\main\functions\api\fn_send_marker_cot.sqf"; file = "\armatak\armatak\addons\main\functions\api\fn_send_marker_cot.sqf";
}; };
class send_uas_video_cot {
file = "\armatak\armatak\addons\main\functions\api\fn_send_uas_video_cot.sqf";
};
class send_uas_sensor_cot {
file = "\armatak\armatak\addons\main\functions\api\fn_send_uas_sensor_cot.sqf";
};
class stop_tcp_socket { class stop_tcp_socket {
file = "\armatak\armatak\addons\main\functions\api\fn_stop_tcp_socket.sqf"; file = "\armatak\armatak\addons\main\functions\api\fn_stop_tcp_socket.sqf";
}; };

View File

@@ -35,7 +35,12 @@ addMissionEventHandler ["ExtensionCallback", {
[_function, "success", _name] call FUNC(notify); [_function, "success", _name] call FUNC(notify);
}; };
case "TCP SOCKET ERROR": { case "TCP SOCKET ERROR": {
[_function, "error", _name] call FUNC(notify); _message = _function;
if (_data isNotEqualTo "") then {
_message = format ["%1: %2", _function, _data];
};
[_message, "error", _name] call FUNC(notify);
}; };
case "VIDEO": { case "VIDEO": {
[_function, "success", _name] call FUNC(notify); [_function, "success", _name] call FUNC(notify);

View File

@@ -32,3 +32,6 @@ if (!isNil "_pre_defined_role") then {
}; };
_cot = [_drone, _atak_role, _atak_callsign] call armatak_fnc_send_marker_cot; _cot = [_drone, _atak_role, _atak_callsign] call armatak_fnc_send_marker_cot;
[_drone] call armatak_fnc_send_uas_video_cot;
[_drone] call armatak_fnc_send_uas_sensor_cot;

View File

@@ -5,9 +5,10 @@
params ["_unit", "_type", "_callsign"]; params ["_unit", "_type", "_callsign"];
_unit_position = _unit call armatak_client_fnc_extractClientPosition; _unit_position = _unit call armatak_client_fnc_extractClientPosition;
_video_url = [_unit] call armatak_fnc_extract_marker_video_url;
_uuid = _unit call armatak_fnc_extract_uuid; _uuid = _unit call armatak_fnc_extract_uuid;
_marker_cot = [_uuid, _type, _unit_position select 1, _unit_position select 2, _unit_position select 3, _callsign, _unit_position select 5, _unit_position select 6]; _marker_cot = [_uuid, _type, _unit_position select 1, _unit_position select 2, _unit_position select 3, _callsign, _unit_position select 5, _unit_position select 6, _video_url];
"armatak" callExtension ["tcp_socket:cot:marker", [_marker_cot]]; "armatak" callExtension ["tcp_socket:cot:marker", [_marker_cot]];

View File

@@ -0,0 +1,55 @@
// function name: armatak_fnc_send_uas_sensor_cot
// function author: Valmo / ArmaTAK contributors
// function description:
// Sends a b-m-p-s-p-loc CoT event every router tick (1 s) for a drone.
// This is the "sensor position" event consumed by the ATAK UAS Tool to:
// - Draw the FOV cone on the moving map.
// - Compute four-corners for AR marker overlay on the video feed.
// - Show the SPoI (Sensor Point of Interest) crosshair.
//
// The event references the drone's b-i-v video endpoint via the drone UUID,
// so armatak_fnc_send_uas_video_cot must also be called for the same drone.
//
// Exits silently when "armatak_attribute_video_url" is not set, which keeps
// the behavior identical to the old fn_send_drone_cot for drones without a
// configured video stream.
//
// Arguments:
// 0: _drone <OBJECT> The drone object.
//
// Return value: none
params ["_drone"];
private _video_url = _drone getVariable ["armatak_attribute_video_url", ""];
if (_video_url == "") exitWith {};
private _uuid = _drone call armatak_fnc_extract_uuid;
private _sensor_uid = _uuid + "-sensor";
private _callsign = [_drone] call armatak_fnc_extract_marker_callsign;
private _pos = (getPos _drone) call armatak_client_fnc_convertClientLocation;
private _lat = _pos select 0;
private _lon = _pos select 1;
private _hae = _pos select 2;
private _azimuth = parseNumber ((getDir _drone) toFixed 0);
private _allTurrets = [_drone, false] call BIS_fnc_allTurrets;
if (count _allTurrets > 0) then {
private _firstTurretPath = _allTurrets select 0;
private _turretWeapons = _drone weaponsTurret _firstTurretPath;
if (_turretWeapons isNotEqualTo []) then {
private _tDir = _drone weaponDirection (_turretWeapons select 0);
if (!((_tDir select 0) == 0 && (_tDir select 1) == 0)) then {
_azimuth = round (((_tDir select 0) atan2 (_tDir select 1) + 360) mod 360);
};
};
};
private _fov = _drone getVariable ["armatak_uas_fov", 60];
private _range = round (((getPosATL _drone) select 2) max 1);
private _payload = [_sensor_uid, _uuid, _callsign, _lat, _lon, _hae, _azimuth, _fov, _range];
"armatak" callExtension ["tcp_socket:cot:uas_sensor", [_payload]];

View File

@@ -0,0 +1,30 @@
// function name: armatak_fnc_send_uas_video_cot
// function author: Valmo / ArmaTAK contributors
// function description:
// Sends a b-i-v CoT event that declares the RTSP video endpoint for a drone.
// The ATAK UAS Tool picks this up and shows the drone in its UAS list with
// the associated video feed available for playback.
//
// The drone entity MUST have the variable "armatak_attribute_video_url" set
// to a valid RTSP URL, e.g.:
// _drone setVariable ["armatak_attribute_video_url", "rtsp://192.168.1.10:8554/live/drone1"];
// or via the 3DEN attribute "Video URL (RTSP)" in the ARMA Team Awareness Kit
// attribute category.
//
// If the variable is absent or empty the function exits silently.
//
// Arguments:
// 0: _drone <OBJECT> The drone object.
//
// Return value: none
params ["_drone"];
private _video_url = _drone getVariable ["armatak_attribute_video_url", ""];
if (_video_url == "") exitWith {};
private _uuid = _drone call armatak_fnc_extract_uuid;
private _callsign = [_drone] call armatak_fnc_extract_marker_callsign;
private _payload = [_uuid, _callsign, _video_url];
"armatak" callExtension ["tcp_socket:cot:uas_video", [_payload]];

View File

@@ -0,0 +1,13 @@
// function name: armatak_fnc_extract_marker_video_url
// function author: Codex
// function description: Gets the marker video URL configured in 3DEN for a vehicle
params ["_unit"];
private _videoUrl = _unit getVariable ["armatak_attribute_marker_video_url", ""];
if (isNil "_videoUrl") exitWith {
""
};
_videoUrl

View File

@@ -0,0 +1,30 @@
params ["_longitudeInGame", "_latitudeInGame", "_altitude"];
private _mapWidth = 8192;
private _mapHeight = 8192;
// SW corner (used as origin)
private _SW_lat = 63.005389;
private _SW_lon = 22.638957;
// SE corner
private _SE_lat = 63.010092;
private _SE_lon = 22.800107;
// NW corner
private _NW_lat = 63.078713;
private _NW_lon = 22.628542;
private _edgeSE_lat = _SE_lat - _SW_lat;
private _edgeSE_lon = _SE_lon - _SW_lon;
private _edgeNW_lat = _NW_lat - _SW_lat;
private _edgeNW_lon = _NW_lon - _SW_lon;
private _fx = _longitudeInGame / _mapWidth;
private _fy = _latitudeInGame / _mapHeight;
private _realLat = _SW_lat + (_fx * _edgeSE_lat) + (_fy * _edgeNW_lat);
private _realLon = _SW_lon + (_fx * _edgeSE_lon) + (_fy * _edgeNW_lon);
[_realLat, _realLon, _altitude]

View File

@@ -1,34 +1,28 @@
class CfgVehicles { class CfgVehicles {
class Logic; class Logic;
class Module_F : Logic class Module_F : Logic {
{ class AttributesBase {
class AttributesBase
{
class Edit; class Edit;
class ModuleDescription; class ModuleDescription;
}; };
class ModuleDescription; class ModuleDescription;
}; };
class GVAR(moduleBase): Module_F { class GVAR(moduleBase): Module_F {
author = PROJECT_AUTHOR; author = PROJECT_AUTHOR;
category = QEGVAR(main,moduleCategory); category = QEGVAR(main,moduleCategory);
function = QUOTE({}); function = QUOTE({});
functionPriority = 1; functionPriority = 1;
isGlobal = 1; isGlobal = 1;
isTriggerActivated = 0; isTriggerActivated = 0;
scope = 1; scope = 1;
scopeCurator = 2; scopeCurator = 2;
}; };
class GVAR(coreModule): GVAR(moduleBase) { class GVAR(connectionModuleBase): GVAR(moduleBase) {
scope = 2;
scopeCurator = 0; scopeCurator = 0;
displayname = "CoT Router";
icon = "\a3\Modules_F_Curator\Data\iconRadio_ca.paa"; icon = "\a3\Modules_F_Curator\Data\iconRadio_ca.paa";
category = QEGVAR(main,moduleCategory); category = QEGVAR(main,moduleCategory);
function = QFUNC(3denCoreModuleConfig);
functionPriority = 1; functionPriority = 1;
isGlobal = 0; isGlobal = 0;
isTriggerActivated = 1; isTriggerActivated = 1;
@@ -39,19 +33,25 @@ class CfgVehicles {
canSetArea = 0; canSetArea = 0;
canSetAreaShape = 0; canSetAreaShape = 0;
canSetAreaHeight = 0; canSetAreaHeight = 0;
};
class GVAR(tcpModule): GVAR(connectionModuleBase) {
scope = 2;
displayName = "CoT Router (TCP)";
function = QFUNC(3denTcpModuleConfig);
class Attributes: AttributesBase { class Attributes: AttributesBase {
class GVAR(moduleInstanceAddress): Edit { class GVAR(moduleInstanceAddress): Edit {
property = QGVAR(moduleInstanceAddress); property = QGVAR(moduleInstanceAddress);
displayname = "TAK Server Address"; displayName = "TAK Server Address";
tooltip = "TAK Server Instance Address"; tooltip = "Hostname or IP address for the TAK or IronTAK server.";
typeName = "STRING"; typeName = "STRING";
defaultValue = "localhost"; defaultValue = "'localhost'";
}; };
class GVAR(moduleInstancePort): Edit { class GVAR(moduleInstancePort): Edit {
property = QGVAR(moduleInstancePort); property = QGVAR(moduleInstancePort);
displayname = "TAK Server TCP Port"; displayName = "TAK Server TCP Port";
tooltip = "TAK Server instance Port for TCP connection"; tooltip = "Port for the unauthenticated TCP socket.";
typeName = "NUMBER"; typeName = "NUMBER";
defaultValue = "8088"; defaultValue = "8088";
}; };
@@ -59,24 +59,75 @@ class CfgVehicles {
}; };
class ModuleDescription: ModuleDescription { class ModuleDescription: ModuleDescription {
description = "Generate the initial ARMATAK configuration, syncronizing all players to the TAK server instance"; description = "Connect ArmaTAK to a TAK server over plain TCP.";
sync[] = {"LocationArea_F"}; sync[] = {"LocationArea_F"};
}; };
}; };
class GVAR(coreModuleCurator): GVAR(coreModule) { class GVAR(enrollModule): GVAR(connectionModuleBase) {
scope = 2;
displayName = "CoT Router (Authenticated)";
function = QFUNC(3denEnrollModuleConfig);
class Attributes: AttributesBase {
class GVAR(moduleInstanceAddress): Edit {
property = QGVAR(moduleInstanceAddress);
displayname = "TAK Server Address";
tooltip = "Hostname or IP address used for enrollment and the final TLS connection.";
typeName = "STRING";
defaultValue = "'localhost'";
};
class GVAR(moduleEnrollmentPort): Edit {
property = QGVAR(moduleEnrollmentPort);
displayName = "Enrollment HTTPS Port";
tooltip = "Port used for GET /Marti/api/tls/config and POST /Marti/api/tls/signClient/v2.";
typeName = "NUMBER";
defaultValue = "8446";
};
class GVAR(moduleEnrollmentUsername): Edit {
property = QGVAR(moduleEnrollmentUsername);
displayName = "Enrollment Username";
tooltip = "Username used in Basic Auth for client certificate enrollment.";
typeName = "STRING";
defaultValue = "''";
};
class GVAR(moduleEnrollmentPassword): Edit {
property = QGVAR(moduleEnrollmentPassword);
displayName = "Enrollment Password";
tooltip = "Password used in Basic Auth for client certificate enrollment.";
typeName = "STRING";
defaultValue = "''";
};
class ModuleDescription: ModuleDescription {};
};
class ModuleDescription: ModuleDescription {
description = "Enroll a client certificate and connect ArmaTAK over mTLS.";
sync[] = {"LocationArea_F"};
};
};
class GVAR(tcpModuleCurator): GVAR(tcpModule) {
scope = 1; scope = 1;
scopeCurator = 2; scopeCurator = 2;
function = ""; function = "";
displayName = "CoT Router (Zeus)"; displayName = "CoT Router (TCP, Zeus)";
curatorInfoType = "armatak_zeus_core_module_dialog"; curatorInfoType = "armatak_zeus_tcp_module_dialog";
};
class GVAR(enrollModuleCurator): GVAR(enrollModule) {
scope = 1;
scopeCurator = 2;
function = "";
displayName = "CoT Router (Authenticated, Zeus)";
curatorInfoType = "armatak_zeus_enroll_module_dialog";
}; };
class GVAR(markEntity): GVAR(moduleBase) { class GVAR(markEntity): GVAR(moduleBase) {
curatorCanAttach = 1; curatorCanAttach = 1;
category = QEGVAR(main,moduleCategory); category = QEGVAR(main,moduleCategory);
displayname = "Mark Entity"; displayname = "Mark Entity";
function = QFUNC(routerEntityAdd); function = QFUNC(routerEntityAdd);
icon = "\a3\Modules_F_Curator\Data\iconRadio_ca.paa"; icon = "\a3\Modules_F_Curator\Data\iconRadio_ca.paa";
}; };
}; };

View File

@@ -1,4 +1,7 @@
PREP(3denCoreModuleConfig); PREP(3denEnrollModuleConfig);
PREP(3denTcpModuleConfig);
PREP(routerEntityAdd); PREP(routerEntityAdd);
PREP(routerEntityRemove); PREP(routerEntityRemove);
PREP(ZeusCoreModuleConfig); PREP(startCotRouter);
PREP(ZeusEnrollModuleConfig);
PREP(ZeusTcpModuleConfig);

View File

@@ -4,8 +4,10 @@ class CfgPatches {
class ADDON { class ADDON {
name = COMPONENT_NAME; name = COMPONENT_NAME;
units[] = { units[] = {
QGVAR(coreModule), QGVAR(tcpModule),
QGVAR(coreModuleCurator), QGVAR(tcpModuleCurator),
QGVAR(enrollModule),
QGVAR(enrollModuleCurator),
QGVAR(markEntity) QGVAR(markEntity)
}; };
weapons[] = {}; weapons[] = {};

View File

@@ -3,69 +3,172 @@ class RscBackground;
class RscButton; class RscButton;
class RscEdit; class RscEdit;
class armatak_zeus_core_module_dialog { class armatak_zeus_tcp_module_dialog {
idd = 999991; idd = 999991;
movingEnable = 0; movingEnable = 0;
class ControlsBackground { class ControlsBackground {
class armatak_gui_module_zeus_core_dialog_main_frame: RscBackground { class main_frame: RscBackground {
idc = 1800; idc = 1800;
x = "0.386562 * safezoneW + safezoneX"; x = "0.386562 * safezoneW + safezoneX";
y = "0.401 * safezoneH + safezoneY"; y = "0.29 * safezoneH + safezoneY";
w = "0.216563 * safezoneW"; w = "0.216563 * safezoneW";
h = "0.242 * safezoneH"; h = "0.32 * safezoneH";
colorBackground[]={0,0,0,0.45}; colorBackground[] = {0,0,0,0.45};
}; };
}; };
class Controls { class Controls {
class armatak_gui_module_zeus_core_dialog_address_edit: RscEdit { class address_text: RscText {
idc = 14000;
text = "localhost";
x = "0.391719 * safezoneW + safezoneX";
y = "0.445 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.044 * safezoneH";
colorBackground[]={0,0,0,0.5};
};
class armatak_gui_module_zeus_core_dialog_address_port_edit: RscEdit {
idc = 14001;
text = "8088";
x = "0.391719 * safezoneW + safezoneX";
y = "0.522 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.044 * safezoneH";
colorBackground[]={0,0,0,0.5};
};
class armatak_gui_module_zeus_core_dialog_address_text: RscText {
idc = 1000; idc = 1000;
text = "TAK Server Address"; text = "TAK Server Address";
x = "0.391719 * safezoneW + safezoneX"; x = "0.391719 * safezoneW + safezoneX";
y = "0.412 * safezoneH + safezoneY"; y = "0.332 * safezoneH + safezoneY";
w = "0.20625 * safezoneW"; w = "0.20625 * safezoneW";
h = "0.033 * safezoneH"; h = "0.033 * safezoneH";
}; };
class armatak_gui_module_zeus_core_dialog_address_port_text: RscText { class address_edit: RscEdit {
idc = 14000;
text = "localhost";
x = "0.391719 * safezoneW + safezoneX";
y = "0.365 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.044 * safezoneH";
colorBackground[] = {0,0,0,0.5};
};
class port_text: RscText {
idc = 1001; idc = 1001;
text = "TAK Server Port"; text = "TAK Server Port";
x = "0.391719 * safezoneW + safezoneX"; x = "0.391719 * safezoneW + safezoneX";
y = "0.489 * safezoneH + safezoneY"; y = "0.425 * safezoneH + safezoneY";
w = "0.20625 * safezoneW"; w = "0.20625 * safezoneW";
h = "0.033 * safezoneH"; h = "0.033 * safezoneH";
}; };
class armatak_gui_module_zeus_core_dialog_address_button_cancel: RscButton { class port_edit: RscEdit {
idc = 14001;
text = "8088";
x = "0.391719 * safezoneW + safezoneX";
y = "0.458 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.044 * safezoneH";
colorBackground[] = {0,0,0,0.5};
};
class button_cancel: RscButton {
idc = 1601; idc = 1601;
text = "Cancel"; text = "Cancel";
action = "closeDialog 2;"; action = "closeDialog 2;";
x = "0.551563 * safezoneW + safezoneX"; x = "0.551563 * safezoneW + safezoneX";
y = "0.577 * safezoneH + safezoneY"; y = "0.535 * safezoneH + safezoneY";
w = "0.0464063 * safezoneW"; w = "0.0464063 * safezoneW";
h = "0.055 * safezoneH"; h = "0.055 * safezoneH";
}; };
class armatak_gui_module_zeus_core_dialog_address_button_ok: RscButton { class button_ok: RscButton {
idc = 1600; idc = 1600;
text = "Ok"; text = "Ok";
action = QUOTE(call FUNC(zeusCoreModuleConfig)); action = QUOTE(call FUNC(ZeusTcpModuleConfig));
x = "0.5 * safezoneW + safezoneX"; x = "0.5 * safezoneW + safezoneX";
y = "0.577 * safezoneH + safezoneY"; y = "0.535 * safezoneH + safezoneY";
w = "0.0464063 * safezoneW";
h = "0.055 * safezoneH";
};
};
};
class armatak_zeus_enroll_module_dialog {
idd = 999992;
movingEnable = 0;
class ControlsBackground {
class main_frame: RscBackground {
idc = 1810;
x = "0.386562 * safezoneW + safezoneX";
y = "0.2 * safezoneH + safezoneY";
w = "0.216563 * safezoneW";
h = "0.52 * safezoneH";
colorBackground[] = {0,0,0,0.45};
};
};
class Controls {
class address_text: RscText {
idc = 1010;
text = "TAK Server Address";
x = "0.391719 * safezoneW + safezoneX";
y = "0.242 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.033 * safezoneH";
};
class address_edit: RscEdit {
idc = 14100;
text = "localhost";
x = "0.391719 * safezoneW + safezoneX";
y = "0.275 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.044 * safezoneH";
colorBackground[] = {0,0,0,0.5};
};
class enroll_port_text: RscText {
idc = 1011;
text = "Enrollment HTTPS Port";
x = "0.391719 * safezoneW + safezoneX";
y = "0.335 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.033 * safezoneH";
};
class enroll_port_edit: RscEdit {
idc = 14101;
text = "8446";
x = "0.391719 * safezoneW + safezoneX";
y = "0.368 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.044 * safezoneH";
colorBackground[] = {0,0,0,0.5};
};
class username_text: RscText {
idc = 1012;
text = "Enrollment Username";
x = "0.391719 * safezoneW + safezoneX";
y = "0.428 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.033 * safezoneH";
};
class username_edit: RscEdit {
idc = 14102;
text = "";
x = "0.391719 * safezoneW + safezoneX";
y = "0.461 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.044 * safezoneH";
colorBackground[] = {0,0,0,0.5};
};
class password_text: RscText {
idc = 1013;
text = "Enrollment Password";
x = "0.391719 * safezoneW + safezoneX";
y = "0.521 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.033 * safezoneH";
};
class password_edit: RscEdit {
idc = 14103;
text = "";
x = "0.391719 * safezoneW + safezoneX";
y = "0.554 * safezoneH + safezoneY";
w = "0.20625 * safezoneW";
h = "0.044 * safezoneH";
colorBackground[] = {0,0,0,0.5};
};
class button_cancel: RscButton {
idc = 1611;
text = "Cancel";
action = "closeDialog 2;";
x = "0.551563 * safezoneW + safezoneX";
y = "0.645 * safezoneH + safezoneY";
w = "0.0464063 * safezoneW";
h = "0.055 * safezoneH";
};
class button_ok: RscButton {
idc = 1610;
text = "Ok";
action = QUOTE(call FUNC(ZeusEnrollModuleConfig));
x = "0.5 * safezoneW + safezoneX";
y = "0.645 * safezoneH + safezoneY";
w = "0.0464063 * safezoneW"; w = "0.0464063 * safezoneW";
h = "0.055 * safezoneH"; h = "0.055 * safezoneH";
}; };

View File

@@ -1,64 +0,0 @@
#include "..\script_component.hpp"
params [
["_logic", objNull, [objNull]],
["_units", [], [[]]],
["_activated", true, [true]]
];
if (isServer) exitWith {
["Connecting to TCP Socket", "success", "TCP Socket"] call EFUNC(main,notify);
_tak_server_instance_address = _logic getVariable QGVAR(moduleInstanceAddress);
_tak_server_instance_port = _logic getVariable QGVAR(moduleInstancePort);
_tak_server_fulladdress = _tak_server_instance_address + ":" + (str _tak_server_instance_port);
missionNamespace setVariable ["armatak_server_instance", _tak_server_fulladdress];
missionNamespace setVariable ["armatak_tcp_socket_is_running", true];
"armatak" callExtension ["tcp_socket:start", [_tak_server_fulladdress]];
_syncUnits = synchronizedObjects _logic;
missionNamespace setVariable ["armatak_server_syncedUnits", _syncUnits];
GVAR(syncedUnits) = missionNamespace getVariable "armatak_server_syncedUnits";
[{
GVAR(syncedUnits) = missionNamespace getVariable "armatak_server_syncedUnits";
{
_objectType = _x call BIS_fnc_objectType;
switch (true) do {
case ((_objectType select 0) == "Soldier"): {
_callsign = [_x] call armatak_fnc_extract_unit_callsign;
_group_name = [group _x] call armatak_fnc_extract_group_color;
_group_role = [_x] call armatak_fnc_extract_group_role;
[_x, _callsign, _group_name, _group_role] call armatak_fnc_send_eud_cot;
[_x] call armatak_fnc_send_digital_pointer_cot;
};
case ((_objectType select 0) == "Vehicle"): {
_atak_type = [_x] call armatak_fnc_extract_role;
_callsign = [_x] call armatak_fnc_extract_marker_callsign;
[_x, _atak_type, _callsign] call armatak_fnc_send_marker_cot;
_x call armatak_fnc_extract_sensor_data;
};
case ((_objectType select 0) == "VehicleAutonomous"): {
_atak_type = [_x] call armatak_fnc_extract_role;
_callsign = [_x] call armatak_fnc_extract_marker_callsign;
[_x, _atak_type, _callsign] call armatak_fnc_send_drone_cot;
[_x] call armatak_fnc_send_digital_pointer_cot;
_x call armatak_fnc_extract_sensor_data;
};
};
} forEach GVAR(syncedUnits);
}, 1, []] call CBA_fnc_addPerFrameHandler;
};
true;

View File

@@ -0,0 +1,37 @@
#include "..\script_component.hpp"
params [
["_logic", objNull, [objNull]],
["_units", [], [[]]],
["_activated", true, [true]]
];
if (isServer) exitWith {
if (missionNamespace getVariable ["armatak_tcp_socket_is_running", false]) exitWith {
["Socket was called twice", "error", "TCP Socket"] call EFUNC(main,notify);
};
["Connecting to authenticated TAK socket", "success", "TCP Socket"] call EFUNC(main,notify);
_tak_server_instance_address = _logic getVariable [QGVAR(moduleInstanceAddress), "localhost"];
_tak_server_enrollment_port = _logic getVariable [QGVAR(moduleEnrollmentPort), 8446];
_tak_server_enrollment_username = _logic getVariable [QGVAR(moduleEnrollmentUsername), ""];
_tak_server_enrollment_password = _logic getVariable [QGVAR(moduleEnrollmentPassword), ""];
"armatak" callExtension [
"tcp_socket:start_enroll_mtls",
[
_tak_server_instance_address,
_tak_server_instance_address,
str _tak_server_enrollment_port,
_tak_server_enrollment_username,
_tak_server_enrollment_password,
""
]
];
missionNamespace setVariable ["armatak_server_syncedUnits", synchronizedObjects _logic];
_tak_server_instance_address call FUNC(startCotRouter);
};
true

View File

@@ -0,0 +1,26 @@
#include "..\script_component.hpp"
params [
["_logic", objNull, [objNull]],
["_units", [], [[]]],
["_activated", true, [true]]
];
if (isServer) exitWith {
if (missionNamespace getVariable ["armatak_tcp_socket_is_running", false]) exitWith {
["Socket was called twice", "error", "TCP Socket"] call EFUNC(main,notify);
};
["Connecting to TCP Socket", "success", "TCP Socket"] call EFUNC(main,notify);
_tak_server_instance_address = _logic getVariable [QGVAR(moduleInstanceAddress), "localhost"];
_tak_server_instance_port = _logic getVariable [QGVAR(moduleInstancePort), 8088];
_tak_server_fulladdress = _tak_server_instance_address + ":" + (str _tak_server_instance_port);
"armatak" callExtension ["tcp_socket:start", [_tak_server_fulladdress]];
missionNamespace setVariable ["armatak_server_syncedUnits", synchronizedObjects _logic];
_tak_server_fulladdress call FUNC(startCotRouter);
};
true

View File

@@ -1,67 +0,0 @@
#include "..\script_component.hpp"
params ["_logic"];
_socket_is_running = missionNamespace getVariable ["armatak_tcp_socket_is_running", false];
if (_socket_is_running) exitWith {
["Socket was called twice", "error", "TCP Socket"] call EFUNC(main,notify);
closeDialog 1;
};
disableSerialization;
["Connecting to TCP Socket", "success", "TCP Socket"] call EFUNC(main,notify);
_tak_server_instance_address = ctrlText 14000;
_tak_server_instance_port = ctrlText 14001;
_tak_server_fulladdress = ((_tak_server_instance_address) + ":" + (_tak_server_instance_port));
missionNamespace setVariable ["armatak_server_instance", _tak_server_fulladdress];
missionNamespace setVariable ["armatak_tcp_socket_is_running", true];
"armatak" callExtension ["tcp_socket:start", [_tak_server_fulladdress]];
_syncUnits = [];
missionNamespace setVariable ["armatak_server_syncedUnits", _syncUnits];
GVAR(syncedUnits) = missionNamespace getVariable "armatak_server_syncedUnits";
[{
GVAR(syncedUnits) = missionNamespace getVariable "armatak_server_syncedUnits";
{
_objectType = _x call BIS_fnc_objectType;
switch (true) do {
case ((_objectType select 0) == "Soldier"): {
_callsign = [_x] call armatak_fnc_extract_unit_callsign;
_group_name = [group _x] call armatak_fnc_extract_group_color;
_group_role = [_x] call armatak_fnc_extract_group_role;
[_x, _callsign, _group_name, _group_role] call armatak_fnc_send_eud_cot;
[_x] call armatak_fnc_send_digital_pointer_cot;
};
case ((_objectType select 0) == "Vehicle"): {
_atak_type = [_x] call armatak_fnc_extract_role;
_callsign = [_x] call armatak_fnc_extract_marker_callsign;
[_x, _atak_type, _callsign] call armatak_fnc_send_marker_cot;
_x call armatak_fnc_extract_sensor_data;
};
case ((_objectType select 0) == "VehicleAutonomous"): {
_atak_type = [_x] call armatak_fnc_extract_role;
_callsign = [_x] call armatak_fnc_extract_marker_callsign;
[_x, _atak_type, _callsign] call armatak_fnc_send_drone_cot;
[_x] call armatak_fnc_send_digital_pointer_cot;
_x call armatak_fnc_extract_sensor_data;
};
};
} forEach GVAR(syncedUnits);
}, 1, []] call CBA_fnc_addPerFrameHandler;
deleteVehicle _logic;
closeDialog 1;

View File

@@ -0,0 +1,33 @@
#include "..\script_component.hpp"
params ["_logic"];
if (missionNamespace getVariable ["armatak_tcp_socket_is_running", false]) exitWith {
["Socket was called twice", "error", "TCP Socket"] call EFUNC(main,notify);
closeDialog 1;
};
disableSerialization;
["Connecting to authenticated TAK socket", "success", "TCP Socket"] call EFUNC(main,notify);
_tak_server_instance_address = ctrlText 14100;
_tak_server_enrollment_port = ctrlText 14101;
_tak_server_enrollment_username = ctrlText 14102;
_tak_server_enrollment_password = ctrlText 14103;
"armatak" callExtension [
"tcp_socket:start_enroll_mtls",
[
_tak_server_instance_address,
_tak_server_instance_address,
_tak_server_enrollment_port,
_tak_server_enrollment_username,
_tak_server_enrollment_password,
""
]
];
_tak_server_instance_address call FUNC(startCotRouter);
deleteVehicle _logic;
closeDialog 1;

View File

@@ -0,0 +1,22 @@
#include "..\script_component.hpp"
params ["_logic"];
if (missionNamespace getVariable ["armatak_tcp_socket_is_running", false]) exitWith {
["Socket was called twice", "error", "TCP Socket"] call EFUNC(main,notify);
closeDialog 1;
};
disableSerialization;
["Connecting to TCP Socket", "success", "TCP Socket"] call EFUNC(main,notify);
_tak_server_instance_address = ctrlText 14000;
_tak_server_instance_port = ctrlText 14001;
_tak_server_fulladdress = _tak_server_instance_address + ":" + _tak_server_instance_port;
"armatak" callExtension ["tcp_socket:start", [_tak_server_fulladdress]];
_tak_server_fulladdress call FUNC(startCotRouter);
deleteVehicle _logic;
closeDialog 1;

View File

@@ -0,0 +1,47 @@
#include "..\script_component.hpp"
params [["_server_instance", "", [""]]];
missionNamespace setVariable ["armatak_server_instance", _server_instance];
missionNamespace setVariable ["armatak_tcp_socket_is_running", true];
if (isNil { missionNamespace getVariable "armatak_server_syncedUnits" }) then {
missionNamespace setVariable ["armatak_server_syncedUnits", []];
};
GVAR(syncedUnits) = missionNamespace getVariable "armatak_server_syncedUnits";
[{
GVAR(syncedUnits) = missionNamespace getVariable "armatak_server_syncedUnits";
{
_objectType = _x call BIS_fnc_objectType;
switch (true) do {
case ((_objectType select 0) == "Soldier"): {
_callsign = [_x] call armatak_fnc_extract_unit_callsign;
_group_name = [group _x] call armatak_fnc_extract_group_color;
_group_role = [_x] call armatak_fnc_extract_group_role;
[_x, _callsign, _group_name, _group_role] call armatak_fnc_send_eud_cot;
[_x] call armatak_fnc_send_digital_pointer_cot;
};
case ((_objectType select 0) == "Vehicle"): {
_atak_type = [_x] call armatak_fnc_extract_role;
_callsign = [_x] call armatak_fnc_extract_marker_callsign;
[_x, _atak_type, _callsign] call armatak_fnc_send_marker_cot;
_x call armatak_fnc_extract_sensor_data;
};
case ((_objectType select 0) == "VehicleAutonomous"): {
_atak_type = [_x] call armatak_fnc_extract_role;
_callsign = [_x] call armatak_fnc_extract_marker_callsign;
[_x, _atak_type, _callsign] call armatak_fnc_send_drone_cot;
[_x] call armatak_fnc_send_digital_pointer_cot;
_x call armatak_fnc_extract_sensor_data;
};
};
} forEach GVAR(syncedUnits);
}, 1, []] call CBA_fnc_addPerFrameHandler;
true

View File

@@ -1 +0,0 @@
armatak\armatak\addons\video

View File

@@ -1,11 +0,0 @@
class Extended_PreStart_EventHandlers {
class ADDON {
init = QUOTE(call COMPILE_SCRIPT(XEH_preStart));
};
};
class Extended_PreInit_EventHandlers {
class ADDON {
init = QUOTE(call COMPILE_SCRIPT(XEH_preInit));
};
};

View File

@@ -1,73 +0,0 @@
class CfgVehicles {
class Logic;
class Module_F : Logic
{
class AttributesBase
{
class Default;
class Edit;
class Combo;
class Checkbox;
class CheckboxNumber;
class ModuleDescription;
class Units;
};
class ModuleDescription
{
class AnyBrain;
};
};
class EGVAR(server,moduleBase);
class GVAR(videoModule): EGVAR(server,moduleBase) {
scope = 2;
scopeCurator = 0;
displayname = "Video Streaming Handler";
icon = "\a3\Modules_F_Curator\Data\iconRadio_ca.paa";
category = QEGVAR(main,moduleCategory);
function = QFUNC(videoParser);
functionPriority = 1;
isGlobal = 0;
isTriggerActivated = 1;
isDisposable = 1;
is3den = 0;
curatorCanAttach = 0;
curatorInfoType = "RscDisplayAttributeModuleNuke";
canSetArea = 0;
canSetAreaShape = 0;
canSetAreaHeight = 0;
/*
class Attributes: AttributesBase {
class GVAR(instanceAddress): Edit {
property = QGVAR(instanceAddress);
displayname = "MediaMTX Provider Address";
tooltip = "MediaMTX Provider Instance Address";
typeName = "STRING";
defaultValue = "localhost";
};
class GVAR(instancePort): Edit {
property = QGVAR(instancePort);
displayname = QUOTE(MediaMTX Provider Port);
tooltip = QUOTE(MediaMTX Provider Port for handling video streams);
typeName = "STRING";
defaultValue = "8554";
};
class GVAR(instanceAuthUser): Edit {
property = QGVAR(instanceAuthUser);
displayname = QUOTE(MediaMTX Provider Username);
tooltip = QUOTE(MediaMTX Provider Instance Username);
typeName = "STRING";
defaultValue = "administrator";
};
class GVAR(instanceAuthPassword): Edit {
property = QGVAR(instanceAuthPassword);
displayname = QUOTE(MediaMTX Provider Password);
tooltip = QUOTE(MediaMTX Provider Instance Password);
typeName = "STRING";
defaultValue = "password";
};
};
*/
};
};

View File

@@ -1 +0,0 @@
PREP(videoParser);

View File

@@ -1,9 +0,0 @@
#include "script_component.hpp"
ADDON = false;
PREP_RECOMPILE_START;
#include "XEH_PREP.hpp"
PREP_RECOMPILE_END;
ADDON = true;

View File

@@ -1,3 +0,0 @@
#include "script_component.hpp"
#include "XEH_PREP.hpp"

View File

@@ -1,23 +0,0 @@
#include "script_component.hpp"
class CfgPatches {
class ADDON {
name = COMPONENT_NAME;
units[] = {
QGVAR(videoModule)
};
weapons[] = {};
requiredAddons[] = {
"cba_main",
"ace_main",
"armatak_main",
"armatak_server"
};
requiredVersion = REQUIRED_VERSION;
author = PROJECT_AUTHOR;
url = "https://github.com/valmojr/armatak";
};
};
#include "CfgEventHandlers.hpp"
//#include "CfgVehicles.hpp"

View File

@@ -1,83 +0,0 @@
#include "..\script_component.hpp"
params [
["_logic", objNull, [objNull]],
["_units", [], [[]]],
["_activated", true, [true]]
];
if (isServer) exitWith {
private _instance_address = GETVAR(_logic,GVAR(instanceAddress),false);
private _instance_port = GETVAR(_logic,GVAR(instancePort),false);
private _instance_auth_user = GETVAR(_logic,GVAR(instanceAuthUser),false);
private _instance_auth_pass = GETVAR(_logic,GVAR(instanceAuthPassword),false);
SETMVAR(GVAR(instanceAddress),_instance_address);
SETMVAR(GVAR(instancePort),_instance_port);
SETMVAR(GVAR(instanceAuthUser),_instance_auth_user);
SETMVAR(GVAR(instanceAuthPassword),_instance_auth_pass);
_startAction = [
QGVAR(startStream),
"Start Video Feed",
"",
{
_uuid = (_this select 0) call armatak_fnc_extract_uuid;
_uuid_short = _uuid select [0, 8];
_role = roleDescription (_this select 0);
_name = name (_this select 0);
_role = [_role] call BIS_fnc_filterString;
_name = [_name] call BIS_fnc_filterString;
_stream_path = _name + "_" + _role + "_" + _uuid_short;
armatak_mediamtx_video_stream_instance_address = GETMVAR(instance_address,false);
armatak_mediamtx_video_stream_instance_port = missionNamespace getVariable "instance_port";
armatak_mediamtx_video_stream_instance_auth_user = missionNamespace getVariable "instance_auth_user";
armatak_mediamtx_video_stream_instance_auth_pass = missionNamespace getVariable "instance_auth_pass";
"armatak" callExtension ["video_stream:start", [armatak_mediamtx_video_stream_instance_address, armatak_mediamtx_video_stream_instance_port, _stream_path, armatak_mediamtx_video_stream_instance_auth_user, armatak_mediamtx_video_stream_instance_auth_pass]];
(_this select 0) setVariable ["armatak_video_feed_is_streaming", true];
},
{
(_this select 0) getVariable "armatak_video_feed_is_streaming" == false
}
] call ace_interact_menu_fnc_createAction;
[
"Man",
1,
["ACE_SelfActions"],
_startAction,
true
] call ace_interact_menu_fnc_addActionToClass;
_stopAction = [
"ArmatakStopStream",
"Stop Video Feed",
"",
{
"armatak" callExtension ["video_stream:stop", []];
SETVAR(_this select 0,GVAR(isStreaming),false);
},
{
GETVAR((this select 0),GVAR(isStreaming),false)
}
] call ace_interact_menu_fnc_createAction;
[
"Man",
1,
["ACE_SelfActions"],
_stopAction,
true
] call ace_interact_menu_fnc_addActionToClass;
if (isMultiplayer) then {
{
SETVAR(_x,GVAR(isStreaming),false);
} forEach playableUnits;
} else {
SETVAR(player,GVAR(isStreaming),false);
};
};
true;

View File

@@ -1,17 +0,0 @@
#define COMPONENT video
#define COMPONENT_BEAUTIFIED Video Streaming
#include "\armatak\armatak\addons\main\script_mod.hpp"
// #define DEBUG_MODE_FULL
// #define DISABLE_COMPILE_CACHE
// #define ENABLE_PERFORMANCE_COUNTERS
#ifdef DEBUG_ENABLED_MAIN
#define DEBUG_MODE_FULL
#endif
#ifdef DEBUG_SETTINGS_MAIN
#define DEBUG_SETTINGS DEBUG_SETTINGS_MAIN
#endif
#include "\z\ace\addons\main\script_macros.hpp"

BIN
media/delta_larp.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

BIN
media/picture.png LFS Normal file

Binary file not shown.

View File

@@ -1,5 +1,5 @@
use uuid::Uuid;
use chrono::{Duration, SecondsFormat, Utc}; use chrono::{Duration, SecondsFormat, Utc};
use uuid::Uuid;
pub struct CursorOverTime { pub struct CursorOverTime {
pub uuid: Option<String>, pub uuid: Option<String>,
@@ -16,9 +16,18 @@ pub struct CursorOverTime {
pub track_speed: Option<f32>, pub track_speed: Option<f32>,
pub link_uid: Option<String>, pub link_uid: Option<String>,
pub remarker: Option<String>, pub remarker: Option<String>,
pub video_url: Option<String>,
} }
impl CursorOverTime { impl CursorOverTime {
fn escape_xml_attribute(value: &str) -> String {
value
.replace('&', "&amp;")
.replace('"', "&quot;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
pub fn convert_to_xml(&self) -> String { pub fn convert_to_xml(&self) -> String {
let uuid = match &self.uuid { let uuid = match &self.uuid {
Some(uuid) => uuid, Some(uuid) => uuid,
@@ -107,6 +116,18 @@ impl CursorOverTime {
xml.push_str(format!("<remarks>ARMATAK | {}</remarks>", remark).as_str()); xml.push_str(format!("<remarks>ARMATAK | {}</remarks>", remark).as_str());
} }
if let Some(video_url) = &self.video_url {
if !video_url.trim().is_empty() {
xml.push_str(
format!(
"<__video url=\"{}\" />",
Self::escape_xml_attribute(video_url.trim())
)
.as_str(),
);
}
}
xml.push_str("</detail></event>"); xml.push_str("</detail></event>");
return xml; return xml;

View File

@@ -1,45 +1,47 @@
use arma_rs::{FromArma, FromArmaError};
use super::cot::CursorOverTime; use super::cot::CursorOverTime;
use arma_rs::{FromArma, FromArmaError};
pub struct DigitalPointerPayload { pub struct DigitalPointerPayload {
pub link_uid: String, pub link_uid: String,
pub contact_callsign: String, pub contact_callsign: String,
pub point_lat: f64, pub point_lat: f64,
pub point_lon: f64, pub point_lon: f64,
pub point_hae: f32, pub point_hae: f32,
} }
impl FromArma for DigitalPointerPayload { impl FromArma for DigitalPointerPayload {
fn from_arma(data: String) -> Result<DigitalPointerPayload, FromArmaError> { fn from_arma(data: String) -> Result<DigitalPointerPayload, FromArmaError> {
let (link_uid, contact_callsign, point_lat, point_lon, point_hae) = let (link_uid, contact_callsign, point_lat, point_lon, point_hae) =
<(String, String, f64, f64, f32)>::from_arma(data)?; <(String, String, f64, f64, f32)>::from_arma(data)?;
Ok(Self { Ok(Self {
link_uid, link_uid,
contact_callsign, contact_callsign,
point_lat, point_lat,
point_lon, point_lon,
point_hae, point_hae,
}) })
} }
} }
impl DigitalPointerPayload { impl DigitalPointerPayload {
pub fn to_cot(&self) -> CursorOverTime { pub fn to_cot(&self) -> CursorOverTime {
CursorOverTime { CursorOverTime {
uuid: Some(format!("{}{}", self.link_uid.clone(), ".SPI1")), uuid: Some(format!("{}{}", self.link_uid.clone(), ".SPI1")),
r#type: Some("b-m-p-s-p-i".to_string()), r#type: Some("b-m-p-s-p-i".to_string()),
point_lat: self.point_lat, point_lat: self.point_lat,
point_lon: self.point_lon, point_lon: self.point_lon,
point_hae: self.point_hae, point_hae: self.point_hae,
point_ce: None, point_ce: None,
point_le: None, point_le: None,
contact_callsign: self.contact_callsign.clone(), contact_callsign: self.contact_callsign.clone(),
group_name: None, group_name: None,
group_role: None, group_role: None,
track_course: None, track_course: None,
track_speed: None, track_speed: None,
link_uid: Some(self.link_uid.clone()), link_uid: Some(self.link_uid.clone()),
remarker: None, remarker: None,
} video_url: None,
} }
}
} }

View File

@@ -1,62 +1,64 @@
use arma_rs::{FromArma, FromArmaError};
use super::cot::CursorOverTime; use super::cot::CursorOverTime;
use arma_rs::{FromArma, FromArmaError};
pub struct EudCoTPayload { pub struct EudCoTPayload {
pub uuid: String, pub uuid: String,
pub point_lat: f64, pub point_lat: f64,
pub point_lon: f64, pub point_lon: f64,
pub point_hae: f32, pub point_hae: f32,
pub contact_callsign: String, pub contact_callsign: String,
pub group_name: String, pub group_name: String,
pub group_role: String, pub group_role: String,
pub track_course: i32, pub track_course: i32,
pub track_speed: f32, pub track_speed: f32,
} }
impl FromArma for EudCoTPayload { impl FromArma for EudCoTPayload {
fn from_arma(data: String) -> Result<EudCoTPayload, FromArmaError> { fn from_arma(data: String) -> Result<EudCoTPayload, FromArmaError> {
let ( let (
uuid, uuid,
point_lat, point_lat,
point_lon, point_lon,
point_hae, point_hae,
contact_callsign, contact_callsign,
group_name, group_name,
group_role, group_role,
track_course, track_course,
track_speed, track_speed,
) = <(String, f64, f64, f32, String, String, String, i32, f32)>::from_arma(data)?; ) = <(String, f64, f64, f32, String, String, String, i32, f32)>::from_arma(data)?;
Ok(Self { Ok(Self {
uuid, uuid,
point_lat, point_lat,
point_lon, point_lon,
point_hae, point_hae,
contact_callsign, contact_callsign,
group_name, group_name,
group_role, group_role,
track_course, track_course,
track_speed, track_speed,
}) })
} }
} }
impl EudCoTPayload { impl EudCoTPayload {
pub fn to_cot(&self) -> CursorOverTime { pub fn to_cot(&self) -> CursorOverTime {
CursorOverTime { CursorOverTime {
uuid: Some(self.uuid.clone()), uuid: Some(self.uuid.clone()),
r#type: None, r#type: None,
point_lat: self.point_lat, point_lat: self.point_lat,
point_lon: self.point_lon, point_lon: self.point_lon,
point_hae: self.point_hae, point_hae: self.point_hae,
point_ce: None, point_ce: None,
point_le: None, point_le: None,
contact_callsign: self.contact_callsign.clone(), contact_callsign: self.contact_callsign.clone(),
group_name: Some(self.group_name.clone()), group_name: Some(self.group_name.clone()),
group_role: Some(self.group_role.clone()), group_role: Some(self.group_role.clone()),
track_course: Some(self.track_course), track_course: Some(self.track_course),
track_speed: Some(self.track_speed), track_speed: Some(self.track_speed),
link_uid: None, link_uid: None,
remarker: None, remarker: None,
} video_url: None,
} }
}
} }

View File

@@ -1,5 +1,5 @@
use arma_rs::{FromArma, FromArmaError};
use super::cot::CursorOverTime; use super::cot::CursorOverTime;
use arma_rs::{FromArma, FromArmaError};
pub struct ExternalPositionPayload { pub struct ExternalPositionPayload {
pub uuid: String, pub uuid: String,
@@ -13,47 +13,49 @@ pub struct ExternalPositionPayload {
} }
impl FromArma for ExternalPositionPayload { impl FromArma for ExternalPositionPayload {
fn from_arma(data: String) -> Result<ExternalPositionPayload, FromArmaError> { fn from_arma(data: String) -> Result<ExternalPositionPayload, FromArmaError> {
let ( let (
uuid, uuid,
point_lat, point_lat,
point_lon, point_lon,
point_hae, point_hae,
contact_callsign, contact_callsign,
track_course, track_course,
track_speed, track_speed,
remarker, remarker,
) = <(String, f64, f64, f32, String, i32, f32, String)>::from_arma(data)?; ) = <(String, f64, f64, f32, String, i32, f32, String)>::from_arma(data)?;
Ok(Self { Ok(Self {
uuid, uuid,
point_lat, point_lat,
point_lon, point_lon,
point_hae, point_hae,
contact_callsign, contact_callsign,
track_course, track_course,
track_speed, track_speed,
remarker, remarker,
}) })
} }
} }
impl ExternalPositionPayload { impl ExternalPositionPayload {
pub fn to_cot(&self) -> CursorOverTime { pub fn to_cot(&self) -> CursorOverTime {
CursorOverTime { CursorOverTime {
uuid: Some(self.uuid.clone()), uuid: Some(self.uuid.clone()),
r#type: None, r#type: None,
point_lat: self.point_lat, point_lat: self.point_lat,
point_lon: self.point_lon, point_lon: self.point_lon,
point_hae: self.point_hae, point_hae: self.point_hae,
point_ce: None, point_ce: None,
point_le: None, point_le: None,
contact_callsign: self.contact_callsign.clone(), contact_callsign: self.contact_callsign.clone(),
group_name: None, group_name: None,
group_role: None, group_role: None,
track_course: Some(self.track_course), track_course: Some(self.track_course),
track_speed: Some(self.track_speed), track_speed: Some(self.track_speed),
link_uid: None, link_uid: None,
remarker: Some(self.remarker.clone()), remarker: Some(self.remarker.clone()),
} video_url: None,
} }
}
} }

View File

@@ -1,5 +1,5 @@
use arma_rs::{FromArma, FromArmaError}; use arma_rs::{FromArma, FromArmaError};
use chrono::{Utc, Duration, SecondsFormat}; use chrono::{Duration, SecondsFormat, Utc};
use uuid::Uuid; use uuid::Uuid;
pub struct MessagePayload { pub struct MessagePayload {
@@ -14,8 +14,7 @@ pub struct MessagePayload {
impl FromArma for MessagePayload { impl FromArma for MessagePayload {
fn from_arma(data: String) -> Result<Self, FromArmaError> { fn from_arma(data: String) -> Result<Self, FromArmaError> {
let (sender_callsign, chatroom, message_text, let (sender_callsign, chatroom, message_text, point_lat, point_lon, point_hae, sender_uid) =
point_lat, point_lon, point_hae, sender_uid) =
<(String, String, String, f64, f64, f32, String)>::from_arma(data)?; <(String, String, String, f64, f64, f32, String)>::from_arma(data)?;
Ok(Self { Ok(Self {
@@ -55,8 +54,8 @@ impl MessageCot {
pub fn to_xml(&self) -> String { pub fn to_xml(&self) -> String {
let created_time = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true); let created_time = Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true);
let stale_time = (Utc::now() + Duration::days(1)) let stale_time =
.to_rfc3339_opts(SecondsFormat::Millis, true); (Utc::now() + Duration::days(1)).to_rfc3339_opts(SecondsFormat::Millis, true);
// MESSAGE ID (random UUID) // MESSAGE ID (random UUID)
let message_uuid = Uuid::new_v4().to_string(); let message_uuid = Uuid::new_v4().to_string();
@@ -98,10 +97,7 @@ impl MessageCot {
format!( format!(
"<__chat parent=\"RootContactGroup\" groupOwner=\"false\" \ "<__chat parent=\"RootContactGroup\" groupOwner=\"false\" \
messageId=\"{}\" chatroom=\"{}\" id=\"{}\" senderCallsign=\"{}\">", messageId=\"{}\" chatroom=\"{}\" id=\"{}\" senderCallsign=\"{}\">",
message_uuid, message_uuid, self.chatroom, self.chatroom, self.sender_callsign,
self.chatroom,
self.chatroom,
self.sender_callsign,
) )
.as_str(), .as_str(),
); );
@@ -109,9 +105,7 @@ impl MessageCot {
xml.push_str( xml.push_str(
format!( format!(
"<chatgrp uid0=\"{}\" uid1=\"{}\" id=\"{}\" />", "<chatgrp uid0=\"{}\" uid1=\"{}\" id=\"{}\" />",
self.sender_uid, self.sender_uid, self.chatroom, self.chatroom
self.chatroom,
self.chatroom
) )
.as_str(), .as_str(),
); );

View File

@@ -1,7 +1,8 @@
pub mod draws;
pub mod cot; pub mod cot;
pub mod digital_pointer; pub mod digital_pointer;
pub mod draws;
pub mod eud; pub mod eud;
pub mod gps; pub mod gps;
pub mod message; pub mod message;
pub mod nato; pub mod nato;
pub mod uas;

View File

@@ -11,10 +11,40 @@ pub struct MarkerCoTPayload {
pub contact_callsign: String, pub contact_callsign: String,
pub track_course: i32, pub track_course: i32,
pub track_speed: f32, pub track_speed: f32,
pub video_url: Option<String>,
} }
impl FromArma for MarkerCoTPayload { impl FromArma for MarkerCoTPayload {
fn from_arma(data: String) -> Result<MarkerCoTPayload, FromArmaError> { fn from_arma(data: String) -> Result<MarkerCoTPayload, FromArmaError> {
if let Ok((
uuid,
r#type,
point_lat,
point_lon,
point_hae,
contact_callsign,
track_course,
track_speed,
video_url,
)) = <(String, String, f64, f64, f32, String, i32, f32, String)>::from_arma(data.clone())
{
return Ok(Self {
uuid,
r#type,
point_lat,
point_lon,
point_hae,
contact_callsign,
track_course,
track_speed,
video_url: if video_url.trim().is_empty() {
None
} else {
Some(video_url)
},
});
}
let ( let (
uuid, uuid,
r#type, r#type,
@@ -34,6 +64,7 @@ impl FromArma for MarkerCoTPayload {
contact_callsign, contact_callsign,
track_course, track_course,
track_speed, track_speed,
video_url: None,
}) })
} }
} }
@@ -55,6 +86,7 @@ impl MarkerCoTPayload {
track_speed: Some(self.track_speed), track_speed: Some(self.track_speed),
link_uid: None, link_uid: None,
remarker: None, remarker: None,
video_url: self.video_url.clone(),
} }
} }
} }

243
src/cot/uas.rs Normal file
View File

@@ -0,0 +1,243 @@
// src/cot/uas.rs
//
// CoT types required for ATAK UAS Tool integration.
//
// Two event types are needed so that the UAS Tool plugin recognises a drone:
//
// b-i-v — Video endpoint declaration. Tells the UAS Tool where
// to pull the RTSP stream for this drone.
//
// b-m-p-s-p-loc — Sensor position event. Carries the camera azimuth,
// field-of-view, and slant-range that the UAS Tool uses
// to draw the FOV cone on the map and to project AR
// markers onto the video feed.
//
// The two events are linked: the b-m-p-s-p-loc detail contains
// <__video uid="<drone-uuid>"/>
// which references the uid of the b-i-v event, so the UAS Tool knows which
// video stream belongs to this sensor.
use arma_rs::{FromArma, FromArmaError};
use chrono::{Duration, SecondsFormat, Utc};
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/// Parse an RTSP URL of the form rtsp://address:port/path
/// into its three components.
fn parse_rtsp_url(url: &str) -> Option<(String, String, String)> {
let without_proto = url.strip_prefix("rtsp://")?;
let slash_pos = without_proto.find('/')?;
let host_port = &without_proto[..slash_pos];
let path = &without_proto[slash_pos..]; // includes the leading '/'
let colon_pos = host_port.rfind(':')?;
let address = host_port[..colon_pos].to_string();
let port = host_port[colon_pos + 1..].to_string();
Some((address, port, path.to_string()))
}
// ---------------------------------------------------------------------------
// b-i-v Video endpoint declaration
// ---------------------------------------------------------------------------
pub struct UasVideoCoTPayload {
/// The drone's persistent ATAK UUID (same uid used for PPLI / marker CoT).
pub uid: String,
/// Human-readable label shown in the UAS Tool video list.
pub callsign: String,
/// Full RTSP URL, e.g. "rtsp://192.168.1.10:8554/live/drone1".
pub video_url: String,
}
impl FromArma for UasVideoCoTPayload {
fn from_arma(data: String) -> Result<UasVideoCoTPayload, FromArmaError> {
let (uid, callsign, video_url) =
<(String, String, String)>::from_arma(data)?;
Ok(Self {
uid,
callsign,
video_url,
})
}
}
impl UasVideoCoTPayload {
/// Build the complete XML string for the b-i-v CoT event.
/// Returns an empty string if the RTSP URL cannot be parsed.
pub fn to_xml(&self) -> String {
let (address, port, path) = match parse_rtsp_url(&self.video_url) {
Some(parts) => parts,
None => {
log::warn!(
"UasVideoCoTPayload: could not parse RTSP URL: {}",
self.video_url
);
return String::new();
}
};
let now =
Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true);
// Long stale time: the video endpoint is considered valid for 1 hour.
// The CoT is re-sent every router tick so it stays fresh even if the
// TAK server restarts.
let stale = (Utc::now() + Duration::seconds(3600))
.to_rfc3339_opts(SecondsFormat::Millis, true);
let mut xml = String::new();
xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xml.push_str(&format!(
"<event type=\"b-i-v\" version=\"2.0\" how=\"m-g\" \
uid=\"{uid}\" time=\"{now}\" start=\"{now}\" stale=\"{stale}\">",
uid = self.uid,
now = now,
stale = stale
));
// b-i-v events carry no real geographic position.
xml.push_str(
"<point lat=\"0\" lon=\"0\" hae=\"9999999.0\" \
ce=\"9999999.0\" le=\"9999999.0\"/>",
);
xml.push_str("<detail>");
xml.push_str("<__video>");
xml.push_str(&format!(
"<ConnectionEntry \
protocol=\"rtsp\" \
path=\"{path}\" \
address=\"{address}\" \
port=\"{port}\" \
uid=\"{uid}\" \
alias=\"{callsign}\" \
roverPort=\"-1\" \
rtspReliable=\"0\" \
ignoreEmbeddedKLV=\"False\" \
networkTimeout=\"0\" \
bufferTime=\"-1\"/>",
path = path,
address = address,
port = port,
uid = self.uid,
callsign = self.callsign,
));
xml.push_str("</__video>");
xml.push_str(&format!(
"<contact callsign=\"{}\"/>",
self.callsign
));
xml.push_str("</detail>");
xml.push_str("</event>");
xml
}
}
// ---------------------------------------------------------------------------
// b-m-p-s-p-loc Sensor position (FOV cone + video link)
// ---------------------------------------------------------------------------
pub struct UasSensorCoTPayload {
/// UID for this sensor event — conventionally "<drone-uuid>-sensor".
pub uid: String,
/// The drone's ATAK UUID; must match the uid used in the b-i-v event so
/// the UAS Tool can link sensor data to the correct video stream.
pub video_uid: String,
/// Callsign shown in the UAS Tool sensor list.
pub callsign: String,
/// Drone latitude in decimal degrees (WGS-84).
pub point_lat: f64,
/// Drone longitude in decimal degrees (WGS-84).
pub point_lon: f64,
/// Drone height above ellipsoid in metres (WGS-84).
pub point_hae: f32,
/// Camera azimuth in degrees, clockwise from true North (0359).
pub azimuth: i32,
/// Camera horizontal field of view in degrees.
pub fov: i32,
/// Estimated slant range from drone to ground point in metres.
/// A good approximation is the drone's AGL altitude.
pub range: i32,
}
impl FromArma for UasSensorCoTPayload {
fn from_arma(data: String) -> Result<UasSensorCoTPayload, FromArmaError> {
let (
uid,
video_uid,
callsign,
point_lat,
point_lon,
point_hae,
azimuth,
fov,
range,
) = <(String, String, String, f64, f64, f32, i32, i32, i32)>::from_arma(
data,
)?;
Ok(Self {
uid,
video_uid,
callsign,
point_lat,
point_lon,
point_hae,
azimuth,
fov,
range,
})
}
}
impl UasSensorCoTPayload {
/// Build the complete XML string for the b-m-p-s-p-loc CoT event.
pub fn to_xml(&self) -> String {
let now =
Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true);
// 60-second stale: must be refreshed every router tick (1 s) to keep
// the FOV cone visible on the map.
let stale = (Utc::now() + Duration::seconds(60))
.to_rfc3339_opts(SecondsFormat::Millis, true);
let mut xml = String::new();
xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xml.push_str(&format!(
"<event type=\"b-m-p-s-p-loc\" version=\"2.0\" how=\"h-g-i-g-o\" \
uid=\"{uid}\" time=\"{now}\" start=\"{now}\" stale=\"{stale}\">",
uid = self.uid,
now = now,
stale = stale,
));
xml.push_str(&format!(
"<point lat=\"{lat}\" lon=\"{lon}\" hae=\"{hae}\" \
ce=\"9999999.0\" le=\"9999999.0\"/>",
lat = self.point_lat,
lon = self.point_lon,
hae = self.point_hae,
));
xml.push_str("<detail>");
// fovAlpha controls the transparency of the FOV cone fill (01).
// 0.537 ≈ 137/255, the value used by the real UAS Tool.
xml.push_str(&format!(
"<sensor \
fov=\"{fov}\" \
fovRed=\"1\" \
fovGreen=\"1\" \
fovBlue=\"1\" \
fovAlpha=\"0.5372549\" \
displayMagneticReference=\"0\" \
range=\"{range}\" \
azimuth=\"{az}\"/>",
fov = self.fov,
range = self.range,
az = self.azimuth,
));
// Link this sensor event to the b-i-v video endpoint.
xml.push_str(&format!("<__video uid=\"{}\"/>", self.video_uid));
xml.push_str(&format!(
"<contact callsign=\"{}\"/>",
self.callsign
));
xml.push_str("</detail>");
xml.push_str("</event>");
xml
}
}

View File

@@ -1,4 +1,5 @@
use arma_rs::{arma, Extension, Group}; use arma_rs::{arma, Extension, Group};
use rustls::crypto::aws_lc_rs;
mod structs; mod structs;
mod tcp; mod tcp;
mod tests; mod tests;
@@ -31,6 +32,9 @@ pub fn init() -> Extension {
log4rs::init_config(config).unwrap(); log4rs::init_config(config).unwrap();
let _ = aws_lc_rs::default_provider().install_default();
log::info!("Initialized rustls aws-lc crypto provider.");
Extension::build() Extension::build()
.command("local_ip", utils::address::get_local_address) .command("local_ip", utils::address::get_local_address)
.command("uuid", utils::uuid::get_uuid) .command("uuid", utils::uuid::get_uuid)
@@ -47,6 +51,8 @@ pub fn init() -> Extension {
"tcp_socket", "tcp_socket",
Group::new() Group::new()
.command("start", tcp::start) .command("start", tcp::start)
.command("start_mtls", tcp::start_mtls)
.command("start_enroll_mtls", tcp::start_enroll_mtls)
.command("stop", tcp::stop) .command("stop", tcp::stop)
.command("send_payload", tcp::send_payload) .command("send_payload", tcp::send_payload)
.group( .group(
@@ -55,7 +61,10 @@ pub fn init() -> Extension {
.command("eud", tcp::cot::send_eud_cot) .command("eud", tcp::cot::send_eud_cot)
.command("marker", tcp::cot::send_marker_cot) .command("marker", tcp::cot::send_marker_cot)
.command("digital_pointer", tcp::cot::send_digital_pointer_cot) .command("digital_pointer", tcp::cot::send_digital_pointer_cot)
.command("chat", tcp::cot::send_message_cot), .command("chat", tcp::cot::send_message_cot)
// UAS Tool integration
.command("uas_video", tcp::cot::send_uas_video_cot)
.command("uas_sensor", tcp::cot::send_uas_sensor_cot),
) )
.group( .group(
"draw", "draw",

View File

@@ -10,9 +10,6 @@ pub struct LogPayload {
impl FromArma for LogPayload { impl FromArma for LogPayload {
fn from_arma(data: String) -> Result<LogPayload, FromArmaError> { fn from_arma(data: String) -> Result<LogPayload, FromArmaError> {
let (status, message) = <(String, String)>::from_arma(data)?; let (status, message) = <(String, String)>::from_arma(data)?;
Ok(Self { Ok(Self { status, message })
status,
message
})
} }
} }

280
src/tcp/client.rs Normal file
View File

@@ -0,0 +1,280 @@
use arma_rs::Context;
use log::{info, warn};
use std::collections::VecDeque;
use std::panic::{self, AssertUnwindSafe};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender, TryRecvError};
use std::thread;
use std::time::Duration;
use super::config::ConnectionConfig;
use super::transport::{connect_stream, TransportStream};
use super::TCP_CLIENT;
const CONNECT_POLL_INTERVAL: Duration = Duration::from_millis(200);
const MAX_PENDING_MESSAGES: usize = 128;
pub enum TcpCommand {
SendMessage(String, Context),
Stop,
}
pub struct TcpClient {
pub(crate) tx: Sender<TcpCommand>,
}
enum ConnectionState {
Connecting,
Connected,
Failed(String),
}
enum ConnectEvent {
Connected(TransportStream),
Failed(String),
}
fn describe_panic_payload(payload: Box<dyn std::any::Any + Send>) -> String {
if let Some(message) = payload.downcast_ref::<&str>() {
(*message).to_string()
} else if let Some(message) = payload.downcast_ref::<String>() {
message.clone()
} else {
"unknown panic payload".to_string()
}
}
fn log_message_preview(message: &str) -> String {
message.chars().take(96).collect::<String>()
}
fn send_over_stream(
stream: &mut TransportStream,
context: &Context,
message: String,
) -> Result<(), String> {
let message_len = message.len();
info!("Sending TCP payload ({} bytes)", message_len);
stream
.write_message(message.as_bytes())
.map_err(|e| {
let message = e.to_string();
let _ = context.callback_data(
"TCP SOCKET ERROR",
"TAK Socket disconnected",
message.clone(),
);
message
})
}
fn flush_pending_messages(
connection: &mut Option<TransportStream>,
pending_messages: &mut VecDeque<(String, Context)>,
state: &mut ConnectionState,
) {
if pending_messages.is_empty() {
return;
}
let Some(stream) = connection.as_mut() else {
return;
};
info!(
"Flushing {} queued TCP payload(s) after connection became active",
pending_messages.len()
);
while let Some((message, context)) = pending_messages.pop_front() {
if let Err(error) = send_over_stream(stream, &context, message) {
info!("Failed to send queued message: {}", error);
*state = ConnectionState::Failed(error);
*connection = None;
return;
}
}
}
fn poll_connect_event(
connect_rx: &Receiver<ConnectEvent>,
connection: &mut Option<TransportStream>,
state: &mut ConnectionState,
pending_messages: &mut VecDeque<(String, Context)>,
ctx: &Context,
connection_message: &str,
target: &str,
) {
loop {
match connect_rx.try_recv() {
Ok(ConnectEvent::Connected(stream)) => {
info!("TCP connection established successfully: {}", target);
let _ = ctx.callback_data("TCP SOCKET", connection_message, target.to_string());
*connection = Some(stream);
*state = ConnectionState::Connected;
flush_pending_messages(connection, pending_messages, state);
}
Ok(ConnectEvent::Failed(error)) => {
info!("Failed to connect to TCP server: {}", error);
let _ = ctx.callback_data(
"TCP SOCKET ERROR",
"TAK Socket connection failed",
error.clone(),
);
*state = ConnectionState::Failed(error);
}
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => break,
}
}
}
impl TcpClient {
pub fn start(&self, config: ConnectionConfig, rx: Receiver<TcpCommand>, ctx: Context) {
if let Some(ref client) = *TCP_CLIENT.lock().unwrap() {
info!("Existing TCP client detected; stopping previous instance before restart.");
client.stop();
}
thread::spawn(move || {
let mut running = true;
let connection_message = config.connected_message();
let config_description = config.describe();
let target = config.target();
let mut state = ConnectionState::Connecting;
let mut connection: Option<TransportStream> = None;
let mut pending_messages: VecDeque<(String, Context)> = VecDeque::new();
let (connect_tx, connect_rx) = mpsc::channel();
info!("TCP worker thread started with config: {}", config_description);
let tcp_thread = thread::spawn(move || {
let connect_result = panic::catch_unwind(AssertUnwindSafe(|| connect_stream(&config)));
match connect_result {
Ok(Ok(stream)) => {
let _ = connect_tx.send(ConnectEvent::Connected(stream));
}
Ok(Err(error)) => {
let _ = connect_tx.send(ConnectEvent::Failed(error));
}
Err(payload) => {
let message = format!(
"TCP connection worker panicked: {}",
describe_panic_payload(payload)
);
let _ = connect_tx.send(ConnectEvent::Failed(message));
}
}
});
while running {
poll_connect_event(
&connect_rx,
&mut connection,
&mut state,
&mut pending_messages,
&ctx,
connection_message,
&target,
);
match rx.recv_timeout(CONNECT_POLL_INTERVAL) {
Ok(TcpCommand::SendMessage(message, context)) => {
let message_len = message.len();
match &mut state {
ConnectionState::Connected => {
if let Some(stream) = connection.as_mut() {
if let Err(error) = send_over_stream(stream, &context, message) {
info!("Failed to send message: {}", error);
state = ConnectionState::Failed(error);
connection = None;
}
} else {
warn!(
"Connection state said connected, but no socket was present; queuing payload."
);
pending_messages.push_back((message, context));
}
}
ConnectionState::Connecting => {
if pending_messages.len() >= MAX_PENDING_MESSAGES {
let preview = log_message_preview(&message);
warn!(
"Dropping TCP payload because connection is still pending and queue is full ({} bytes, preview={:?})",
message_len, preview
);
let _ = context.callback_data(
"TCP SOCKET ERROR",
"TAK Socket is still connecting",
format!(
"queue full while connecting; dropped payload ({} bytes, preview={:?})",
message_len, preview
),
);
} else {
info!(
"Queueing TCP payload while connection is pending ({} bytes, queued={})",
message_len,
pending_messages.len() + 1
);
pending_messages.push_back((message, context));
}
}
ConnectionState::Failed(error) => {
let preview = log_message_preview(&message);
warn!(
"Dropping TCP payload because connection is in failed state ({} bytes, preview={:?}, error={})",
message_len, preview, error
);
let _ = context.callback_data(
"TCP SOCKET ERROR",
"TAK Socket is not connected",
error.clone(),
);
}
}
}
Ok(TcpCommand::Stop) => {
running = false;
info!("Stopping TCP client.");
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => {
warn!("TCP command channel disconnected.");
running = false;
}
}
}
info!("Waiting for TCP connection thread to finish.");
match tcp_thread.join() {
Ok(()) => info!("TCP connection thread joined successfully."),
Err(payload) => warn!(
"TCP connection thread join reported a panic: {}",
describe_panic_payload(payload)
),
}
info!("TCP worker thread finished.");
});
}
pub fn send_payload(&self, context: Context, payload: String) {
let tx = self.tx.clone();
thread::spawn(move || {
info!("Dispatching queued TCP payload command.");
if let Err(error) = tx.send(TcpCommand::SendMessage(payload, context)) {
warn!("Failed to dispatch TCP payload command: {}", error);
}
});
}
pub fn stop(&self) {
let tx = self.tx.clone();
thread::spawn(move || {
info!("Dispatching TCP stop command.");
if let Err(error) = tx.send(TcpCommand::Stop) {
warn!("Failed to dispatch TCP stop command: {}", error);
}
});
}
}

64
src/tcp/config.rs Normal file
View File

@@ -0,0 +1,64 @@
pub enum ConnectionConfig {
Plain {
address: String,
},
Mtls {
address: String,
server_name: String,
ca_cert_path: String,
client_cert_path: String,
client_key_path: String,
},
EnrollMtls {
host: String,
server_name: String,
enroll_port: String,
username: String,
password: String,
client_uid: String,
},
}
impl ConnectionConfig {
pub fn connected_message(&self) -> &'static str {
match self {
Self::Plain { .. } => "Connected to TCP Server",
Self::Mtls { .. } => "Connected to TAK Server via mTLS",
Self::EnrollMtls { .. } => "Connected to TAK Server via enrolled mTLS certificate",
}
}
pub fn target(&self) -> String {
match self {
Self::Plain { address } | Self::Mtls { address, .. } => address.clone(),
Self::EnrollMtls { host, .. } => host.clone(),
}
}
pub fn describe(&self) -> String {
match self {
Self::Plain { address } => format!("plain tcp -> {}", address),
Self::Mtls {
address,
server_name,
ca_cert_path,
client_cert_path,
client_key_path,
} => format!(
"manual mtls -> {} (server_name={}, ca={}, cert={}, key={})",
address, server_name, ca_cert_path, client_cert_path, client_key_path
),
Self::EnrollMtls {
host,
server_name,
enroll_port,
username,
client_uid,
..
} => format!(
"enroll mtls -> host={} enroll_port={} server_name={} username={} client_uid={}",
host, enroll_port, server_name, username, client_uid
),
}
}
}

View File

@@ -9,24 +9,62 @@ pub fn send_eud_cot(ctx: Context, cursor_over_time: cot::eud::EudCoTPayload) ->
"Sending End User Device Cursor Over Time to TCP server" "Sending End User Device Cursor Over Time to TCP server"
} }
pub fn send_marker_cot(ctx: Context, cursor_over_time: cot::nato::MarkerCoTPayload) -> &'static str { pub fn send_marker_cot(
ctx: Context,
cursor_over_time: cot::nato::MarkerCoTPayload,
) -> &'static str {
let payload = cursor_over_time.to_cot().convert_to_xml(); let payload = cursor_over_time.to_cot().convert_to_xml();
send_payload(ctx, payload); send_payload(ctx, payload);
"Sending Marker Cursor Over Time to TCP server" "Sending Marker Cursor Over Time to TCP server"
} }
pub fn send_digital_pointer_cot(ctx: Context, cursor_over_time: cot::digital_pointer::DigitalPointerPayload) -> &'static str { pub fn send_digital_pointer_cot(
ctx: Context,
cursor_over_time: cot::digital_pointer::DigitalPointerPayload,
) -> &'static str {
let payload = cursor_over_time.to_cot().convert_to_xml(); let payload = cursor_over_time.to_cot().convert_to_xml();
send_payload(ctx, payload); send_payload(ctx, payload);
"Sending Digital Pointer Cursor Over Time to TCP server" "Sending Digital Pointer Cursor Over Time to TCP server"
} }
pub fn send_message_cot(ctx: Context, message_payload: cot::message::MessagePayload) -> &'static str { pub fn send_message_cot(
ctx: Context,
message_payload: cot::message::MessagePayload,
) -> &'static str {
let message_cot = cot::message::MessageCot::from_payload(message_payload); let message_cot = cot::message::MessageCot::from_payload(message_payload);
let payload = message_cot.to_xml(); let payload = message_cot.to_xml();
send_payload(ctx, payload); send_payload(ctx, payload);
"Sending Message CoT to TCP server" "Sending Message CoT to TCP server"
} }
/// Send a b-i-v CoT that declares the RTSP video endpoint for a drone.
/// Called by SQF via: "armatak" callExtension ["tcp_socket:cot:uas_video", [payload]]
///
/// Returns early without sending if the RTSP URL in the payload cannot be parsed.
pub fn send_uas_video_cot(
ctx: Context,
payload: cot::uas::UasVideoCoTPayload,
) -> &'static str {
let xml = payload.to_xml();
if !xml.is_empty() {
send_payload(ctx, xml);
}
"Sending UAS Video (b-i-v) CoT to TCP server"
}
/// Send a b-m-p-s-p-loc CoT carrying the drone camera's azimuth, FOV, and
/// slant-range so the UAS Tool can draw the FOV cone on the map.
/// Called by SQF via: "armatak" callExtension ["tcp_socket:cot:uas_sensor", [payload]]
pub fn send_uas_sensor_cot(
ctx: Context,
payload: cot::uas::UasSensorCoTPayload,
) -> &'static str {
let xml = payload.to_xml();
send_payload(ctx, xml);
"Sending UAS Sensor (b-m-p-s-p-loc) CoT to TCP server"
}

View File

@@ -2,7 +2,10 @@ use arma_rs::Context;
use crate::{cot, tcp::send_payload}; use crate::{cot, tcp::send_payload};
pub fn send_circle_cot(ctx: Context, circle_payload: cot::draws::circle::CircleCoTPayload) -> &'static str { pub fn send_circle_cot(
ctx: Context,
circle_payload: cot::draws::circle::CircleCoTPayload,
) -> &'static str {
let shape_circle_cot = circle_payload.to_cot(); let shape_circle_cot = circle_payload.to_cot();
let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
let stale = (chrono::Utc::now() + chrono::Duration::days(1)) let stale = (chrono::Utc::now() + chrono::Duration::days(1))
@@ -14,21 +17,21 @@ pub fn send_circle_cot(ctx: Context, circle_payload: cot::draws::circle::CircleC
} }
pub fn send_ellipse_cot(ctx: Context) -> &'static str { pub fn send_ellipse_cot(ctx: Context) -> &'static str {
let _ = ctx; let _ = ctx;
"Not implemented: send_ellipse_cot" "Not implemented: send_ellipse_cot"
} }
pub fn send_rectangle_cot(ctx: Context) -> &'static str { pub fn send_rectangle_cot(ctx: Context) -> &'static str {
let _ = ctx; let _ = ctx;
"Not implemented: send_ellipse_cot" "Not implemented: send_ellipse_cot"
} }
pub fn send_freedraw_cot(ctx: Context) -> &'static str { pub fn send_freedraw_cot(ctx: Context) -> &'static str {
let _ = ctx; let _ = ctx;
"Not implemented: send_ellipse_cot" "Not implemented: send_ellipse_cot"
} }
pub fn send_vectordraw_cot(ctx: Context) -> &'static str { pub fn send_vectordraw_cot(ctx: Context) -> &'static str {
let _ = ctx; let _ = ctx;
"Not implemented: send_ellipse_cot" "Not implemented: send_ellipse_cot"
} }

View File

@@ -1,120 +1,90 @@
use arma_rs::Context; use arma_rs::Context;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use log::info; use log::info;
use std::io::Write;
use std::net::TcpStream;
use std::sync::mpsc::{self, Receiver, Sender}; use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::thread;
mod client;
mod config;
mod tls;
mod transport;
pub mod cot; pub mod cot;
pub mod draw; pub mod draw;
pub enum TcpCommand { use client::{TcpClient, TcpCommand};
SendMessage(String, Context), use config::ConnectionConfig;
Stop,
}
pub struct TcpClient {
pub(crate) tx: Sender<TcpCommand>,
}
impl TcpClient {
pub fn start(&self, address: String, rx: Receiver<TcpCommand>, ctx: Context) {
if let Some(ref client) = *TCP_CLIENT.lock().unwrap() {
client.stop();
}
let connection = Arc::new(Mutex::new(None));
let connection_clone = Arc::clone(&connection);
thread::spawn(move || {
let mut running = true;
let tcp_thread = thread::spawn(move || match TcpStream::connect(&address) {
Ok(stream) => {
let _ = ctx.callback_data("TCP SOCKET", "Connected to TCP Server", address);
*connection_clone.lock().unwrap() = Some(stream);
}
Err(e) => {
let _ = ctx.callback_data(
"TCP SOCKET ERROR",
"TAK Socket connection failed",
e.to_string(),
);
info!("Failed to connect to TCP server: {}", e);
}
});
while running {
match rx.recv() {
Ok(TcpCommand::SendMessage(message, context)) => {
if let Some(mut stream) = connection.lock().unwrap().as_ref() {
if let Err(e) = stream.write_all(message.as_bytes()) {
info!("Failed to send message: {}", e);
let _ = context.callback_data(
"TCP SOCKET ERROR",
"TAK Socket disconnected",
e.to_string(),
);
running = false;
}
} else {
let _ = context.callback_null(
"TCP SOCKET ERROR",
"TAK Socket is not active",
);
}
}
Ok(TcpCommand::Stop) => {
running = false;
info!("Stopping TCP client.");
}
Err(error) => {
info!("Error receiving command: {}", error.to_string());
}
}
}
tcp_thread.join().unwrap();
});
}
pub fn send_payload(&self, context: Context, payload: String) {
let tx = self.tx.clone();
thread::spawn(move || {
tx.send(TcpCommand::SendMessage(payload, context)).unwrap();
});
}
pub fn stop(&self) {
let tx = self.tx.clone();
thread::spawn(move || {
tx.send(TcpCommand::Stop).unwrap();
});
}
}
lazy_static! { lazy_static! {
static ref TCP_CLIENT: Arc<Mutex<Option<TcpClient>>> = Arc::new(Mutex::new(None)); static ref TCP_CLIENT: Arc<Mutex<Option<TcpClient>>> = Arc::new(Mutex::new(None));
} }
pub fn start(ctx: Context, address: String) -> &'static str { fn start_with_config(ctx: Context, config: ConnectionConfig) {
info!("Starting TCP client with config: {}", config.describe());
let (tx, rx): (Sender<TcpCommand>, Receiver<TcpCommand>) = mpsc::channel(); let (tx, rx): (Sender<TcpCommand>, Receiver<TcpCommand>) = mpsc::channel();
let client = TcpClient { tx }; let client = TcpClient { tx };
client.start(address, rx, ctx); client.start(config, rx, ctx);
let mut client_guard = TCP_CLIENT.lock().unwrap(); let mut client_guard = TCP_CLIENT.lock().unwrap();
*client_guard = Some(client); *client_guard = Some(client);
}
pub fn start(ctx: Context, address: String) -> &'static str {
start_with_config(ctx, ConnectionConfig::Plain { address });
"Starting TCP Client" "Starting TCP Client"
} }
pub fn start_mtls(
ctx: Context,
address: String,
server_name: String,
ca_cert_path: String,
client_cert_path: String,
client_key_path: String,
) -> &'static str {
start_with_config(
ctx,
ConnectionConfig::Mtls {
address,
server_name,
ca_cert_path,
client_cert_path,
client_key_path,
},
);
"Starting mTLS TCP Client"
}
pub fn start_enroll_mtls(
ctx: Context,
host: String,
server_name: String,
enroll_port: String,
username: String,
password: String,
client_uid: String,
) -> &'static str {
start_with_config(
ctx,
ConnectionConfig::EnrollMtls {
host,
server_name,
enroll_port,
username,
password,
client_uid,
},
);
"Starting enrolled mTLS TCP Client"
}
pub fn send_payload(ctx: Context, payload: String) -> &'static str { pub fn send_payload(ctx: Context, payload: String) -> &'static str {
if let Some(ref client) = *TCP_CLIENT.lock().unwrap() { if let Some(ref client) = *TCP_CLIENT.lock().unwrap() {
info!("Queueing TCP payload ({} bytes)", payload.len());
client.send_payload(ctx, payload); client.send_payload(ctx, payload);
} else { } else {
let _ = ctx.callback_null("TCP SOCKET ERROR", "TCP Client is not running"); let _ = ctx.callback_null("TCP SOCKET ERROR", "TCP Client is not running");
@@ -126,6 +96,7 @@ pub fn send_payload(ctx: Context, payload: String) -> &'static str {
pub fn stop(ctx: Context) -> &'static str { pub fn stop(ctx: Context) -> &'static str {
if let Some(ref client) = *TCP_CLIENT.lock().unwrap() { if let Some(ref client) = *TCP_CLIENT.lock().unwrap() {
info!("Stopping TCP client via extension command.");
client.stop(); client.stop();
let _ = ctx.callback_null("TCP SOCKET", "TCP client stopped"); let _ = ctx.callback_null("TCP SOCKET", "TCP client stopped");
} else { } else {

221
src/tcp/tls/connector.rs Normal file
View File

@@ -0,0 +1,221 @@
use log::info;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
use rustls_pemfile::{certs, private_key};
use std::fs::File;
use std::io::BufReader;
use std::io::Cursor;
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::time::Duration;
use std::sync::Arc;
use crate::tcp::transport::TransportStream;
const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const SOCKET_IO_TIMEOUT: Duration = Duration::from_secs(10);
fn load_certificates(path: &str) -> Result<Vec<CertificateDer<'static>>, String> {
let file = File::open(path).map_err(|e| format!("failed to open cert file {}: {}", path, e))?;
let mut reader = BufReader::new(file);
certs(&mut reader)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("failed to read certs from {}: {}", path, e))
}
fn load_private_key(path: &str) -> Result<PrivateKeyDer<'static>, String> {
let file = File::open(path).map_err(|e| format!("failed to open key file {}: {}", path, e))?;
let mut reader = BufReader::new(file);
private_key(&mut reader)
.map_err(|e| format!("failed to read private key from {}: {}", path, e))?
.ok_or_else(|| format!("no supported private key found in {}", path))
}
fn load_certificates_from_pem(pem: &str) -> Result<Vec<CertificateDer<'static>>, String> {
let mut reader = Cursor::new(pem.as_bytes());
certs(&mut reader)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("failed to read certs from PEM payload: {}", e))
}
fn load_private_key_from_pem(pem: &str) -> Result<PrivateKeyDer<'static>, String> {
let mut reader = Cursor::new(pem.as_bytes());
private_key(&mut reader)
.map_err(|e| format!("failed to read private key from PEM payload: {}", e))?
.ok_or_else(|| "no supported private key found in PEM payload".to_string())
}
fn infer_server_name(address: &str) -> &str {
address
.trim()
.trim_start_matches('[')
.split(']')
.next()
.unwrap_or(address)
.split(':')
.next()
.unwrap_or(address)
}
fn resolve_address(address: &str) -> Result<SocketAddr, String> {
address
.to_socket_addrs()
.map_err(|e| format!("failed to resolve {}: {}", address, e))?
.next()
.ok_or_else(|| format!("failed to resolve {}: no socket addresses returned", address))
}
fn connect_tcp(address: &str) -> Result<TcpStream, String> {
let socket_addr = resolve_address(address)?;
info!(
"Opening TCP connection to {} (resolved={}) with timeout {:?}",
address, socket_addr, TCP_CONNECT_TIMEOUT
);
let tcp_stream = TcpStream::connect_timeout(&socket_addr, TCP_CONNECT_TIMEOUT)
.map_err(|e| format!("failed to connect to {}: {}", address, e))?;
tcp_stream
.set_read_timeout(Some(SOCKET_IO_TIMEOUT))
.map_err(|e| format!("failed to set read timeout on {}: {}", address, e))?;
tcp_stream
.set_write_timeout(Some(SOCKET_IO_TIMEOUT))
.map_err(|e| format!("failed to set write timeout on {}: {}", address, e))?;
Ok(tcp_stream)
}
pub fn connect_mtls(
address: &str,
server_name: &str,
ca_cert_path: &str,
client_cert_path: &str,
client_key_path: &str,
) -> Result<TransportStream, String> {
info!(
"Connecting mTLS from file paths to {} using server_name={}",
address, server_name
);
let mut root_store = RootCertStore::empty();
let ca_certificates = load_certificates(ca_cert_path)?;
info!(
"Loaded {} CA certificate(s) from {}",
ca_certificates.len(),
ca_cert_path
);
for certificate in ca_certificates {
root_store
.add(certificate)
.map_err(|e| format!("failed to add CA certificate from {}: {}", ca_cert_path, e))?;
}
let client_certificates = load_certificates(client_cert_path)?;
info!(
"Loaded {} client certificate(s) from {}",
client_certificates.len(),
client_cert_path
);
let client_key = load_private_key(client_key_path)?;
info!("Loaded client private key from {}", client_key_path);
let tls_config = ClientConfig::builder()
.with_root_certificates(root_store)
.with_client_auth_cert(client_certificates, client_key)
.map_err(|e| format!("failed to configure mTLS client: {}", e))?;
info!("Constructed rustls client config for {}", address);
let tcp_stream = connect_tcp(address)?;
let resolved_server_name = if server_name.trim().is_empty() {
infer_server_name(address).to_string()
} else {
server_name.trim().to_string()
};
let server_name = ServerName::try_from(resolved_server_name.clone())
.map_err(|_| format!("invalid TLS server name: {}", resolved_server_name))?;
let mut tls_stream = StreamOwned::new(
ClientConnection::new(Arc::new(tls_config), server_name)
.map_err(|e| format!("failed to create TLS client: {}", e))?,
tcp_stream,
);
info!("Starting mTLS handshake for {}", address);
while tls_stream.conn.is_handshaking() {
tls_stream
.conn
.complete_io(&mut tls_stream.sock)
.map_err(|e| format!("TLS handshake failed: {}", e))?;
}
info!("mTLS handshake completed successfully for {}", address);
Ok(TransportStream::Mtls(tls_stream))
}
pub fn connect_mtls_from_pem(
address: &str,
server_name: &str,
ca_cert_pem: &str,
client_cert_pem: &str,
client_key_pem: &str,
) -> Result<TransportStream, String> {
info!(
"Connecting mTLS from in-memory PEM payloads to {} using server_name={}",
address, server_name
);
let mut root_store = RootCertStore::empty();
let ca_certificates = load_certificates_from_pem(ca_cert_pem)?;
info!(
"Loaded {} CA certificate(s) from enrollment payload",
ca_certificates.len()
);
for certificate in ca_certificates {
root_store
.add(certificate)
.map_err(|e| format!("failed to add CA certificate from PEM payload: {}", e))?;
}
let client_certificates = load_certificates_from_pem(client_cert_pem)?;
info!(
"Loaded {} client certificate(s) from enrollment payload",
client_certificates.len()
);
let client_key = load_private_key_from_pem(client_key_pem)?;
info!("Loaded client private key from enrollment payload");
let tls_config = ClientConfig::builder()
.with_root_certificates(root_store)
.with_client_auth_cert(client_certificates, client_key)
.map_err(|e| format!("failed to configure mTLS client: {}", e))?;
info!("Constructed rustls client config for {}", address);
let tcp_stream = connect_tcp(address)?;
let resolved_server_name = if server_name.trim().is_empty() {
infer_server_name(address).to_string()
} else {
server_name.trim().to_string()
};
let server_name = ServerName::try_from(resolved_server_name.clone())
.map_err(|_| format!("invalid TLS server name: {}", resolved_server_name))?;
let mut tls_stream = StreamOwned::new(
ClientConnection::new(Arc::new(tls_config), server_name)
.map_err(|e| format!("failed to create TLS client: {}", e))?,
tcp_stream,
);
info!("Starting mTLS handshake for {}", address);
while tls_stream.conn.is_handshaking() {
tls_stream
.conn
.complete_io(&mut tls_stream.sock)
.map_err(|e| format!("TLS handshake failed: {}", e))?;
}
info!("mTLS handshake completed successfully for {}", address);
Ok(TransportStream::Mtls(tls_stream))
}

228
src/tcp/tls/enrollment.rs Normal file
View File

@@ -0,0 +1,228 @@
use rcgen::{CertificateParams, DistinguishedName, DnType, KeyPair, PKCS_RSA_SHA256};
use log::info;
use reqwest::blocking::Client;
use serde::Deserialize;
use uuid::Uuid;
use super::connector::connect_mtls_from_pem;
use crate::tcp::transport::TransportStream;
#[derive(Deserialize)]
struct EnrollmentResponse {
#[serde(rename = "signedCert")]
signed_cert: String,
ca0: String,
}
struct EnrollmentConfig {
server_port: String,
enroll_path: String,
}
fn extract_tag_value(xml: &str, tag_name: &str) -> Option<String> {
let open_tag = format!("<{}>", tag_name);
let close_tag = format!("</{}>", tag_name);
let start = xml.find(&open_tag)? + open_tag.len();
let end = xml[start..].find(&close_tag)? + start;
Some(xml[start..end].trim().to_string())
}
fn wrap_pem_body(base64_body: &str, begin: &str, end: &str) -> String {
let mut wrapped = String::new();
let normalized = base64_body.trim().replace(['\r', '\n'], "");
wrapped.push_str(begin);
wrapped.push('\n');
for chunk in normalized.as_bytes().chunks(64) {
wrapped.push_str(std::str::from_utf8(chunk).unwrap_or_default());
wrapped.push('\n');
}
wrapped.push_str(end);
wrapped.push('\n');
wrapped
}
fn enrollment_http_client() -> Result<Client, String> {
Client::builder()
.danger_accept_invalid_certs(true)
.build()
.map_err(|e| format!("failed to build enrollment HTTP client: {}", e))
}
fn response_error_details(response: reqwest::blocking::Response) -> String {
let status = response.status();
match response.text() {
Ok(body) => {
let trimmed = body.trim();
if trimmed.is_empty() {
status.to_string()
} else {
format!("{}: {}", status, trimmed)
}
}
Err(_) => status.to_string(),
}
}
fn fetch_enrollment_config(host: &str, enroll_port: &str) -> Result<EnrollmentConfig, String> {
let url = format!(
"https://{}:{}/Marti/api/tls/config",
host.trim(),
enroll_port.trim()
);
info!("Fetching TAK enrollment config from {}", url);
let response = enrollment_http_client()?
.get(&url)
.send()
.map_err(|e| format!("failed to fetch {}: {}", url, e))?;
if !response.status().is_success() {
return Err(format!(
"failed to fetch {}: {}",
url,
response_error_details(response)
));
}
let response_text = response
.text()
.map_err(|e| format!("failed to read config response from {}: {}", url, e))?;
let server_port = extract_tag_value(&response_text, "serverPort")
.ok_or_else(|| "missing serverPort in /Marti/api/tls/config response".to_string())?;
let enroll_path = extract_tag_value(&response_text, "enrollPath")
.ok_or_else(|| "missing enrollPath in /Marti/api/tls/config response".to_string())?;
info!(
"Enrollment config received: server_port={} enroll_path={}",
server_port, enroll_path
);
Ok(EnrollmentConfig {
server_port,
enroll_path,
})
}
fn enroll_client_certificate(
host: &str,
enroll_port: &str,
enroll_path: &str,
username: &str,
password: &str,
client_uid: &str,
) -> Result<(String, String, String), String> {
info!(
"Generating RSA client keypair and CSR for enrolled TAK client {}",
client_uid
);
let key_pair = KeyPair::generate_for(&PKCS_RSA_SHA256)
.map_err(|e| format!("failed to generate client keypair: {}", e))?;
let mut distinguished_name = DistinguishedName::new();
distinguished_name.push(DnType::CommonName, client_uid);
distinguished_name.push(DnType::OrganizationName, "ArmaTAK");
distinguished_name.push(DnType::OrganizationalUnitName, "ArmaTAK Session");
let mut params = CertificateParams::new(vec![])
.map_err(|e| format!("failed to create CSR params: {}", e))?;
params.distinguished_name = distinguished_name;
let csr = params
.serialize_request(&key_pair)
.map_err(|e| format!("failed to generate CSR: {}", e))?;
let csr_der = csr.der().as_ref().to_vec();
let url = format!(
"https://{}:{}{}?clientUid={}",
host.trim(),
enroll_port.trim(),
enroll_path.trim(),
client_uid.trim()
);
info!(
"Submitting client certificate enrollment request for {} to {}",
client_uid, url
);
let response = enrollment_http_client()?
.post(&url)
.basic_auth(username.trim(), Some(password.to_string()))
.header("Accept", "application/json")
.header("Content-Type", "application/pkcs10")
.body(csr_der)
.send()
.map_err(|e| format!("failed to enroll client certificate at {}: {}", url, e))?;
if !response.status().is_success() {
return Err(format!(
"failed to enroll client certificate at {}: {}",
url,
response_error_details(response)
));
}
let enrollment: EnrollmentResponse = response
.json()
.map_err(|e| format!("failed to parse enrollment response: {}", e))?;
info!(
"Enrollment response parsed successfully for {} (signed_cert_len={}, ca_len={})",
client_uid,
enrollment.signed_cert.len(),
enrollment.ca0.len()
);
let cert_pem = wrap_pem_body(
&enrollment.signed_cert,
"-----BEGIN CERTIFICATE-----",
"-----END CERTIFICATE-----",
);
let key_pem = key_pair.serialize_pem();
Ok((enrollment.ca0, cert_pem, key_pem))
}
pub fn enroll_and_connect(
host: &str,
server_name: &str,
enroll_port: &str,
username: &str,
password: &str,
client_uid: &str,
) -> Result<TransportStream, String> {
let normalized_client_uid = if client_uid.trim().is_empty() {
format!("armatak-{}", Uuid::new_v4())
} else {
client_uid.trim().to_string()
};
info!(
"Starting enroll_and_connect for host={} enroll_port={} server_name={} client_uid={}",
host,
enroll_port,
server_name,
normalized_client_uid
);
let enrollment_config = fetch_enrollment_config(host, enroll_port)?;
let (ca_cert_pem, client_cert_pem, client_key_pem) = enroll_client_certificate(
host,
enroll_port,
&enrollment_config.enroll_path,
username,
password,
&normalized_client_uid,
)?;
connect_mtls_from_pem(
&format!("{}:{}", host.trim(), enrollment_config.server_port.trim()),
if server_name.trim().is_empty() {
host.trim()
} else {
server_name.trim()
},
&ca_cert_pem,
&client_cert_pem,
&client_key_pem,
)
}

5
src/tcp/tls/mod.rs Normal file
View File

@@ -0,0 +1,5 @@
mod connector;
mod enrollment;
pub use connector::connect_mtls;
pub use enrollment::enroll_and_connect;

90
src/tcp/transport.rs Normal file
View File

@@ -0,0 +1,90 @@
use log::info;
use rustls::{ClientConnection, StreamOwned};
use std::io::Write;
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::time::Duration;
use super::config::ConnectionConfig;
use super::tls::{connect_mtls, enroll_and_connect};
const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const SOCKET_IO_TIMEOUT: Duration = Duration::from_secs(10);
pub enum TransportStream {
Plain(TcpStream),
Mtls(StreamOwned<ClientConnection, TcpStream>),
}
impl TransportStream {
pub fn write_message(&mut self, message: &[u8]) -> Result<(), std::io::Error> {
match self {
Self::Plain(stream) => {
stream.write_all(message)?;
stream.flush()
}
Self::Mtls(stream) => {
stream.write_all(message)?;
stream.flush()
}
}
}
}
fn connect_plain(address: &str) -> Result<TransportStream, String> {
let socket_addr: SocketAddr = address
.to_socket_addrs()
.map_err(|e| format!("failed to resolve {}: {}", address, e))?
.next()
.ok_or_else(|| format!("failed to resolve {}: no socket addresses returned", address))?;
info!(
"Opening plain TCP connection to {} (resolved={}) with timeout {:?}",
address, socket_addr, TCP_CONNECT_TIMEOUT
);
let stream = TcpStream::connect_timeout(&socket_addr, TCP_CONNECT_TIMEOUT)
.map_err(|e| format!("failed to connect to {}: {}", address, e))?;
stream
.set_read_timeout(Some(SOCKET_IO_TIMEOUT))
.map_err(|e| format!("failed to set read timeout on {}: {}", address, e))?;
stream
.set_write_timeout(Some(SOCKET_IO_TIMEOUT))
.map_err(|e| format!("failed to set write timeout on {}: {}", address, e))?;
Ok(TransportStream::Plain(stream))
}
pub fn connect_stream(config: &ConnectionConfig) -> Result<TransportStream, String> {
info!("connect_stream invoked for {}", config.describe());
match config {
ConnectionConfig::Plain { address } => connect_plain(address),
ConnectionConfig::Mtls {
address,
server_name,
ca_cert_path,
client_cert_path,
client_key_path,
} => connect_mtls(
address,
server_name,
ca_cert_path,
client_cert_path,
client_key_path,
),
ConnectionConfig::EnrollMtls {
host,
server_name,
enroll_port,
username,
password,
client_uid,
} => enroll_and_connect(
host,
server_name,
enroll_port,
username,
password,
client_uid,
),
}
}

View File

@@ -1,25 +1,25 @@
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::init; use crate::init;
use uuid::Uuid; use std::vec;
use std::vec; use uuid::Uuid;
#[test] #[test]
fn uuid_output_is_uuid4_identifier() { fn uuid_output_is_uuid4_identifier() {
let extension = init().testing(); let extension = init().testing();
let (output, _) = extension.call("uuid", None); let (output, _) = extension.call("uuid", None);
let validation = Uuid::parse_str(&output); let validation = Uuid::parse_str(&output);
assert!(validation.is_ok()) assert!(validation.is_ok())
} }
#[test] #[test]
fn uuid_output_throws_if_passed_args() { fn uuid_output_throws_if_passed_args() {
let extension = init().testing(); let extension = init().testing();
let args: Vec<String> = vec![1.to_string(),2.to_string()]; let args: Vec<String> = vec![1.to_string(), 2.to_string()];
let (output, _) = extension.call("uuid", Some(args)); let (output, _) = extension.call("uuid", Some(args));
assert_eq!(output,"") assert_eq!(output, "")
} }
} }

View File

@@ -9,116 +9,119 @@ use std::thread;
use crate::cot; use crate::cot;
pub enum UdpCommand { pub enum UdpCommand {
SendMessage(String, Context), SendMessage(String, Context),
Stop, Stop,
} }
pub struct UdpClient { pub struct UdpClient {
pub(crate) tx: Sender<UdpCommand>, pub(crate) tx: Sender<UdpCommand>,
} }
impl UdpClient { impl UdpClient {
pub fn start(&self, address: String, rx: Receiver<UdpCommand>, ctx: Context) { pub fn start(&self, address: String, rx: Receiver<UdpCommand>, ctx: Context) {
if let Some(ref client) = *UDP_CLIENT.lock().unwrap() { if let Some(ref client) = *UDP_CLIENT.lock().unwrap() {
client.stop(); client.stop();
}
thread::spawn(move || {
let socket = match UdpSocket::bind("0.0.0.0:0") {
Ok(s) => s,
Err(e) => {
let _ = ctx.callback_data(
"UDP SOCKET ERROR",
"Failed to bind UDP socket",
e.to_string(),
);
info!("Failed to bind UDP socket: {}", e);
return;
}
};
let _ = ctx.callback_data("UDP SOCKET", "EUD Connected", address.clone());
let mut running = true;
while running {
match rx.recv() {
Ok(UdpCommand::SendMessage(message, context)) => {
if let Err(e) = socket.send_to(message.as_bytes(), &address) {
info!("Failed to send UDP message: {}", e);
let _ = context.callback_data(
"UDP SOCKET ERROR",
"Failed to send UDP message",
e.to_string(),
);
}
}
Ok(UdpCommand::Stop) => {
running = false;
info!("Stopping UDP client.");
}
Err(error) => {
info!("Error receiving command: {}", error.to_string());
}
}
}
});
} }
thread::spawn(move || { pub fn send_payload(&self, context: Context, payload: String) {
let socket = match UdpSocket::bind("0.0.0.0:0") { let tx = self.tx.clone();
Ok(s) => s, thread::spawn(move || {
Err(e) => { tx.send(UdpCommand::SendMessage(payload, context)).unwrap();
let _ = ctx.callback_data( });
"UDP SOCKET ERROR", }
"Failed to bind UDP socket",
e.to_string(),
);
info!("Failed to bind UDP socket: {}", e);
return;
}
};
let _ = ctx.callback_data("UDP SOCKET", "EUD Connected", address.clone()); pub fn stop(&self) {
let tx = self.tx.clone();
let mut running = true; thread::spawn(move || {
while running { tx.send(UdpCommand::Stop).unwrap();
match rx.recv() { });
Ok(UdpCommand::SendMessage(message, context)) => { }
if let Err(e) = socket.send_to(message.as_bytes(), &address) {
info!("Failed to send UDP message: {}", e);
let _ = context.callback_data(
"UDP SOCKET ERROR",
"Failed to send UDP message",
e.to_string(),
);
}
}
Ok(UdpCommand::Stop) => {
running = false;
info!("Stopping UDP client.");
}
Err(error) => {
info!("Error receiving command: {}", error.to_string());
}
}
}
});
}
pub fn send_payload(&self, context: Context, payload: String) {
let tx = self.tx.clone();
thread::spawn(move || {
tx.send(UdpCommand::SendMessage(payload, context)).unwrap();
});
}
pub fn stop(&self) {
let tx = self.tx.clone();
thread::spawn(move || {
tx.send(UdpCommand::Stop).unwrap();
});
}
} }
lazy_static! { lazy_static! {
static ref UDP_CLIENT: Arc<Mutex<Option<UdpClient>>> = Arc::new(Mutex::new(None)); static ref UDP_CLIENT: Arc<Mutex<Option<UdpClient>>> = Arc::new(Mutex::new(None));
} }
pub fn start(ctx: Context, address: String) -> &'static str { pub fn start(ctx: Context, address: String) -> &'static str {
let (tx, rx): (Sender<UdpCommand>, Receiver<UdpCommand>) = mpsc::channel(); let (tx, rx): (Sender<UdpCommand>, Receiver<UdpCommand>) = mpsc::channel();
let client = UdpClient { tx }; let client = UdpClient { tx };
client.start(address, rx, ctx); client.start(address, rx, ctx);
let mut client_guard = UDP_CLIENT.lock().unwrap(); let mut client_guard = UDP_CLIENT.lock().unwrap();
*client_guard = Some(client); *client_guard = Some(client);
"Starting UDP Client" "Starting UDP Client"
} }
pub fn send_payload(ctx: Context, payload: String) -> &'static str { pub fn send_payload(ctx: Context, payload: String) -> &'static str {
if let Some(ref client) = *UDP_CLIENT.lock().unwrap() { if let Some(ref client) = *UDP_CLIENT.lock().unwrap() {
client.send_payload(ctx, payload); client.send_payload(ctx, payload);
} else { } else {
let _ = ctx.callback_null("UDP SOCKET ERROR", "UDP Socket is not running"); let _ = ctx.callback_null("UDP SOCKET ERROR", "UDP Socket is not running");
} }
"Sending payload to UDP server" "Sending payload to UDP server"
} }
pub fn send_gps_cot(ctx: Context, cursor_over_time: cot::gps::ExternalPositionPayload) -> &'static str { pub fn send_gps_cot(
let payload = cursor_over_time.to_cot().convert_to_xml(); ctx: Context,
send_payload(ctx, payload); cursor_over_time: cot::gps::ExternalPositionPayload,
) -> &'static str {
let payload = cursor_over_time.to_cot().convert_to_xml();
send_payload(ctx, payload);
"Sending GPS Cursor Over Time to UDP server" "Sending GPS Cursor Over Time to UDP server"
} }
pub fn stop(ctx: Context) -> &'static str { pub fn stop(ctx: Context) -> &'static str {
if let Some(ref client) = *UDP_CLIENT.lock().unwrap() { if let Some(ref client) = *UDP_CLIENT.lock().unwrap() {
client.stop(); client.stop();
let _ = ctx.callback_null("UDP SOCKET", "EUD Disconnected"); let _ = ctx.callback_null("UDP SOCKET", "EUD Disconnected");
} else { } else {
let _ = ctx.callback_null("UDP SOCKET ERROR", "UDP Socket is not running"); let _ = ctx.callback_null("UDP SOCKET ERROR", "UDP Socket is not running");
} }
"Stopping UDP Client" "Stopping UDP Client"
} }

View File

@@ -1,23 +1,23 @@
use std::net::{IpAddr, UdpSocket}; use std::net::{IpAddr, UdpSocket};
pub fn get_local_address() -> String { pub fn get_local_address() -> String {
fn get_local_ip() -> Result<IpAddr, String> { fn get_local_ip() -> Result<IpAddr, String> {
let socket = UdpSocket::bind("0.0.0.0:0").map_err(|e| e.to_string())?; let socket = UdpSocket::bind("0.0.0.0:0").map_err(|e| e.to_string())?;
socket.connect("8.8.8.8:80").map_err(|e| e.to_string())?; socket.connect("8.8.8.8:80").map_err(|e| e.to_string())?;
socket socket
.local_addr() .local_addr()
.map(|addr| addr.ip()) .map(|addr| addr.ip())
.map_err(|e| e.to_string()) .map_err(|e| e.to_string())
} }
let parsed_data = get_local_ip(); let parsed_data = get_local_ip();
match parsed_data { match parsed_data {
Ok(ip) => { Ok(ip) => {
return format!("ws://{}:4152", ip.to_string()); return format!("ws://{}:4152", ip.to_string());
} }
Err(_) => { Err(_) => {
return "not provided".to_string(); return "not provided".to_string();
} }
} }
} }

View File

@@ -2,11 +2,11 @@ use crate::structs::LogPayload;
use log::{error, info, warn}; use log::{error, info, warn};
pub fn log_info(data: LogPayload) -> String { pub fn log_info(data: LogPayload) -> String {
match data.status.as_str() { match data.status.as_str() {
"info" => info!("{}", data.message), "info" => info!("{}", data.message),
"warn" => warn!("{}", data.message), "warn" => warn!("{}", data.message),
"error" => error!("{}", data.message), "error" => error!("{}", data.message),
_ => error!("{}", "Wrong log call"), _ => error!("{}", "Wrong log call"),
} }
"logged".to_string() "logged".to_string()
} }

View File

@@ -1,3 +1,3 @@
pub mod uuid;
pub mod address; pub mod address;
pub mod log; pub mod log;
pub mod uuid;

View File

@@ -1,7 +1,7 @@
pub fn get_uuid() -> String { pub fn get_uuid() -> String {
use uuid::Uuid; use uuid::Uuid;
let id = Uuid::new_v4().to_string(); let id = Uuid::new_v4().to_string();
return id; return id;
} }

View File

@@ -16,7 +16,13 @@ lazy_static! {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x08000000; const CREATE_NO_WINDOW: u32 = 0x08000000;
fn build_rtsp_url(address: &str, port: &str, stream_path: &str, username: &str, password: &str) -> String { fn build_rtsp_url(
address: &str,
port: &str,
stream_path: &str,
username: &str,
password: &str,
) -> String {
if username.is_empty() || password.is_empty() { if username.is_empty() || password.is_empty() {
format!("rtsp://{}:{}/{}", address, port, stream_path) format!("rtsp://{}:{}/{}", address, port, stream_path)
} else { } else {
@@ -28,20 +34,22 @@ fn build_rtsp_url(address: &str, port: &str, stream_path: &str, username: &str,
} }
#[cfg(any(target_os = "windows", target_os = "linux"))] #[cfg(any(target_os = "windows", target_os = "linux"))]
fn spawn_ffmpeg( fn spawn_ffmpeg(rtsp_url: String, stop_rx: Receiver<()>, status_tx: Sender<Result<(), String>>) {
rtsp_url: String,
stop_rx: Receiver<()>,
status_tx: Sender<Result<(), String>>,
) {
thread::spawn(move || { thread::spawn(move || {
let mut cmd = Command::new("ffmpeg"); let mut cmd = Command::new("ffmpeg");
cmd.args(&[ cmd.args(&[
"-f","x11grab", "-f",
"-framerate","30", "x11grab",
"-video_size","1920x1080", "-framerate",
"-i" ,":0", "30",
"-f","rtsp", "-video_size",
"-rtsp_transport","tcp", "1920x1080",
"-i",
":0",
"-f",
"rtsp",
"-rtsp_transport",
"tcp",
&rtsp_url, &rtsp_url,
]); ]);