20 Commits

Author SHA1 Message Date
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
Valmo Trindade
13cd08c655 Added mandol map support 2026-01-03 02:55:39 -03:00
Valmo Trindade
8fe14dc18d Added Clafghan Map Support 2026-01-02 03:28:10 -03:00
Valmo Trindade
1bec26df8a Added UMP Colombia map support 2025-12-21 02:21:02 -03:00
Valmo Trindade
c5d5da636f added malvinas pradero ganso function call 2025-12-13 15:00:33 -03:00
Valmo Trindade
c2e137e67c Added lawn map 2025-12-13 14:59:05 -03:00
Valmo Trindade
de5ac9dbb5 Added Malvinas Maps 2025-12-12 19:12:04 -03:00
Valmo Trindade
ef3be1e768 fixed router entity remover function 2025-12-10 23:07:53 -03:00
56 changed files with 3019 additions and 641 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

@@ -38,6 +38,9 @@ switch (toLower worldName) do {
case "vr": { case "vr": {
_realLocation = _position call armatak_fnc_convert_to_vr; _realLocation = _position call armatak_fnc_convert_to_vr;
}; };
case "lawn": {
_realLocation = _position call armatak_fnc_convert_to_lawn;
};
case "cucui": { case "cucui": {
_realLocation = _position call armatak_fnc_convert_to_cucui; _realLocation = _position call armatak_fnc_convert_to_cucui;
}; };
@@ -74,12 +77,36 @@ switch (toLower worldName) do {
case "kunduz_valley": { case "kunduz_valley": {
_realLocation = _position call armatak_fnc_convert_to_kunduz_valley; _realLocation = _position call armatak_fnc_convert_to_kunduz_valley;
}; };
case "malvinasfalkands": {
_realLocation = _position call armatak_fnc_convert_to_malvinas_malvinasfalkands;
};
case "pebble_island_airfield": {
_realLocation = _position call armatak_fnc_convert_to_malvinas_pebble_island_airfield;
};
case "p_argentino_stanley": {
_realLocation = _position call armatak_fnc_convert_to_malvinas_p_argentino_stanley;
};
case "top_malo_house": {
_realLocation = _position call armatak_fnc_convert_to_malvinas_top_malo_house;
};
case "pradera_ganso": {
_realLocation = _position call armatak_fnc_convert_to_malvinas_pradera_ganso;
};
case "tanoa": { case "tanoa": {
_realLocation = _position call armatak_fnc_convert_to_tanoa; _realLocation = _position call armatak_fnc_convert_to_tanoa;
}; };
case "zagor_zagorsk_reserved_forest": { case "zagor_zagorsk_reserved_forest": {
_realLocation = _position call armatak_fnc_convert_to_zagor_zagorsk_reserved_forest; _realLocation = _position call armatak_fnc_convert_to_zagor_zagorsk_reserved_forest;
}; };
case "umb_colombia": {
_realLocation = _position call armatak_fnc_convert_to_colombia;
};
case "clafghan": {
_realLocation = _position call armatak_fnc_convert_to_clafghan;
};
case "rut_mandol": {
_realLocation = _position call armatak_fnc_convert_to_rut_mandol;
};
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

@@ -68,12 +68,30 @@ class CfgFunctions {
class convert_to_kunduz_valley { class convert_to_kunduz_valley {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_kunduz_valley.sqf"; file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_kunduz_valley.sqf";
}; };
class convert_to_lawn {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_lawn.sqf";
};
class convert_to_livonia { class convert_to_livonia {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_livonia.sqf"; file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_livonia.sqf";
}; };
class convert_to_malden { class convert_to_malden {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_malden.sqf"; file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_malden.sqf";
}; };
class convert_to_malvinas_malvinasfalkands {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_malvinas_malvinasfalkands.sqf";
};
class convert_to_malvinas_p_argentino_stanley {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_malvinas_p_argentino_stanley.sqf";
};
class convert_to_malvinas_pebble_island_airfield {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_malvinas_pebble_island_airfield.sqf";
};
class convert_to_malvinas_pradera_ganso {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_malvinas_pradera_ganso.sqf";
};
class convert_to_malvinas_top_malo_house {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_malvinas_top_malo_house.sqf";
};
class convert_to_southen_sahrani { class convert_to_southen_sahrani {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_southen_sahrani.sqf"; file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_southen_sahrani.sqf";
}; };
@@ -95,6 +113,15 @@ class CfgFunctions {
class convert_to_zagor_zagorsk_reserved_forest { class convert_to_zagor_zagorsk_reserved_forest {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_zagor_zagorsk_reserved_forest.sqf"; file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_zagor_zagorsk_reserved_forest.sqf";
}; };
class convert_to_colombia {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_colombia.sqf";
};
class convert_to_clafghan {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_clafghan.sqf";
};
class convert_to_rut_mandol {
file = "\armatak\armatak\addons\main\functions\map\fn_convert_to_rut_mandol.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

@@ -0,0 +1,23 @@
params["_latitude", "_longitude", "_altitude"];
_playerPosition = [_latitude, _longitude, _altitude];
_playerLatitude = _playerPosition select 0;
_playerLongitude = _playerPosition select 1;
_playerMaxLatitude = 20480;
_playerMaxLongitude = 20480;
_MapMaxLongitude = 33.728772;
_MapMinLongitude = 33.542815;
_MapMaxLatitude = 63.169746;
_MapMinLatitude = 62.938820;
_LongitudeDifference = _MapMaxLongitude - _MapMinLongitude;
_LatitudeDifference = _MapMaxLatitude - _MapMinLatitude;
_RealLongitude = (_playerLongitude / _playerMaxLongitude) * _LongitudeDifference + _MapMinLongitude;
_RealLatitude = (_playerLatitude / _playerMaxLatitude) * _LatitudeDifference + _MapMinLatitude;
[_RealLongitude, _RealLatitude, _playerPosition select 2]

View File

@@ -0,0 +1,23 @@
params["_latitude", "_longitude", "_altitude"];
_playerPosition = [_latitude, _longitude, _altitude];
_playerLatitude = _playerPosition select 0;
_playerLongitude = _playerPosition select 1;
_playerMaxLatitude = 20480;
_playerMaxLongitude = 20480;
_MapMaxLatitude = -67.765153;
_MapMinLatitude = -68.223664;
_MapMaxLongitude = 10.593815;
_MapMinLongitude = 10.137466;
_LongitudeDifference = _MapMaxLongitude - _MapMinLongitude;
_LatitudeDifference = _MapMaxLatitude - _MapMinLatitude;
_RealLongitude = (_playerLongitude / _playerMaxLongitude) * _LongitudeDifference + _MapMinLongitude;
_RealLatitude = (_playerLatitude / _playerMaxLatitude) * _LatitudeDifference + _MapMinLatitude;
[_RealLongitude, _RealLatitude, _playerPosition select 2]

View File

@@ -0,0 +1,23 @@
params["_latitude", "_longitude", "_altitude"];
_playerPosition = [_latitude, _longitude, _altitude];
_playerLatitude = _playerPosition select 0;
_playerLongitude = _playerPosition select 1;
_playerMaxLongitude = 4992;
_playerMaxLatitude = 4992;
_MapMaxLongitude = -99.722665;
_MapMinLongitude = -99.775505;
_MapMaxLatitude = 32.159272;
_MapMinLatitude = 32.114011;
_LongitudeDifference = _MapMaxLongitude - _MapMinLongitude;
_LatitudeDifference = _MapMaxLatitude - _MapMinLatitude;
_RealLongitude = (_playerLongitude / _playerMaxLongitude) * _LongitudeDifference + _MapMinLongitude;
_RealLatitude = (_playerLatitude / _playerMaxLatitude) * _LatitudeDifference + _MapMinLatitude;
[_RealLongitude, _RealLatitude, _playerPosition select 2]

View File

@@ -0,0 +1,30 @@
params ["_longitudeInGame", "_latitudeInGame", "_altitude"];
private _mapWidth = 11264;
private _mapHeight = 11264;
// SW corner (used as origin)
private _SW_lat = -51.736078;
private _SW_lon = -57.915032;
// SE corner
private _SE_lat = -51.736078;
private _SE_lon = -58.077879;
// NW corner
private _NW_lat = -51.634750;
private _NW_lon = -58.077879;
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

@@ -0,0 +1,30 @@
params ["_longitudeInGame", "_latitudeInGame", "_altitude"];
private _mapWidth = 16384;
private _mapHeight = 16384;
// SW corner (used as origin)
private _SW_lat = -51.806546;
private _SW_lon = -57.939747;
// SE corner
private _SE_lat = -51.806546;
private _SE_lon = -57.701978;
// NW corner
private _NW_lat = -51.658913;
private _NW_lon = -57.939747;
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

@@ -0,0 +1,30 @@
params ["_longitudeInGame", "_latitudeInGame", "_altitude"];
private _mapWidth = 10240;
private _mapHeight = 10240;
// SW corner (used as origin)
private _SW_lat = -51.863358;
private _SW_lon = -59.054585;
// SE corner
private _SE_lat = -51.863358;
private _SE_lon = -58.906155;
// NW corner
private _NW_lat = -51.771493;
private _NW_lon = -59.054585;
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

@@ -0,0 +1,23 @@
params["_latitude", "_longitude", "_altitude"];
_playerPosition = [_latitude, _longitude, _altitude];
_playerLatitude = _playerPosition select 0;
_playerLongitude = _playerPosition select 1;
_playerMaxLongitude = 5120;
_playerMaxLatitude = 5120;
_MapMaxLatitude = -51.619725;
_MapMinLatitude = -51.664223;
_MapMaxLongitude = -58.394630;
_MapMinLongitude = -58.469580;
_LongitudeDifference = _MapMaxLongitude - _MapMinLongitude;
_LatitudeDifference = _MapMaxLatitude - _MapMinLatitude;
_RealLongitude = (_playerLongitude / _playerMaxLongitude) * _LongitudeDifference + _MapMinLongitude;
_RealLatitude = (_playerLatitude / _playerMaxLatitude) * _LatitudeDifference + _MapMinLatitude;
[_RealLongitude, _RealLatitude, _playerPosition select 2]

View File

@@ -0,0 +1,23 @@
params["_latitude", "_longitude", "_altitude"];
_playerPosition = [_latitude, _longitude, _altitude];
_playerLatitude = _playerPosition select 0;
_playerLongitude = _playerPosition select 1;
_playerMaxLatitude = 32768;
_playerMaxLongitude = 32768;
_MapMaxLongitude = 35.285485;
_MapMinLongitude = 34.927617;
_MapMaxLatitude = 70.445404;
_MapMinLatitude = 70.016783;
_LongitudeDifference = _MapMaxLongitude - _MapMinLongitude;
_LatitudeDifference = _MapMaxLatitude - _MapMinLatitude;
_RealLongitude = (_playerLongitude / _playerMaxLongitude) * _LongitudeDifference + _MapMinLongitude;
_RealLatitude = (_playerLatitude / _playerMaxLatitude) * _LatitudeDifference + _MapMinLatitude;
[_RealLongitude, _RealLatitude, _playerPosition select 2]

View File

@@ -1,22 +1,11 @@
class CfgVehicles { class CfgVehicles {
class Logic; class Logic;
class Module_F : Logic class Module_F : Logic {
{ class AttributesBase {
class AttributesBase
{
class Default;
class Edit; class Edit;
class Combo;
class Checkbox;
class CheckboxNumber;
class ModuleDescription; class ModuleDescription;
class Units;
};
class ModuleDescription
{
class AnyBrain;
}; };
class ModuleDescription;
}; };
class GVAR(moduleBase): Module_F { class GVAR(moduleBase): Module_F {
@@ -30,13 +19,10 @@ class CfgVehicles {
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;
@@ -47,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";
}; };
@@ -67,17 +59,68 @@ 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) {

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

@@ -34,7 +34,7 @@ switch (false) do {
}; };
} forEach GVAR(syncedUnits); } forEach GVAR(syncedUnits);
missionNmaespace setVariable ["armatak_server_syncedUnits", GVAR(syncedUnits)]; missionNamespace setVariable ["armatak_server_syncedUnits", GVAR(syncedUnits)];
SETVAR(_unit,GVAR(isRouting),false); SETVAR(_unit,GVAR(isRouting),false);
deleteVehicle _logic; deleteVehicle _logic;

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

@@ -4,7 +4,7 @@ class CfgPatches {
class ADDON { class ADDON {
name = COMPONENT_NAME; name = COMPONENT_NAME;
units[] = { units[] = {
QGVAR(videoModule) //QGVAR(videoModule)
}; };
weapons[] = {}; weapons[] = {};
requiredAddons[] = { requiredAddons[] = {

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>,

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 DigitalPointerPayload { pub struct DigitalPointerPayload {
pub link_uid: String, pub link_uid: String,

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 EudCoTPayload { pub struct EudCoTPayload {
pub uuid: String, pub uuid: String,

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,

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,6 +1,6 @@
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;

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(

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,21 +9,30 @@ 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);

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))

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,8 +1,8 @@
#[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() {

View File

@@ -105,7 +105,10 @@ pub fn send_payload(ctx: Context, payload: String) -> &'static str {
"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(
ctx: Context,
cursor_over_time: cot::gps::ExternalPositionPayload,
) -> &'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);

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

@@ -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,
]); ]);