uas-cot 0.7.0

Your TAK map shows fake drones as real ones: open Remote ID receivers flagged 0 of 10 spoofed drones. uas-cot puts a trust verdict on Remote ID markers. Drone telemetry to Cursor on Target: Remote ID (remoteid spoof verdicts), MISB ST 0601 KLV (STANAG 4609), MAVLink and MAVLink-M friendly position reports to ATAK/WinTAK/TAK Server; targeting and engagement messages refused at compile time
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! uas2cot: drone telemetry files or streams to Cursor on Target.
//!
//! ```text
//! uas2cot klv  <file.klv>   MISB ST 0601 KLV stream (ffmpeg -i in.ts -map 0:d -c copy -f data file.klv)
//! uas2cot tlog <file.tlog>  MAVLink telemetry log (QGroundControl, Mission Planner, MAVProxy)
//! uas2cot pcap <file.pcap>  Wi-Fi monitor-mode capture with Remote ID beacons / NAN (radiotap or 802.11)
//! uas2cot mavlink-udp <bind addr>   live MAVLink over UDP, for example 0.0.0.0:14550
//!
//! Built with the `mavlink-m` feature, `tlog` and `mavlink-udp` also turn
//! MAVLink-M (military.xml) PARTICIPANT_POSITION friendly position reports
//! into CoT. Target, track, fires and engagement messages are dropped.
//!
//! options:
//!   --udp <addr>       send each event as a UDP datagram (239.2.3.1:6969 is the TAK SA multicast group)
//!   --tcp <addr>       send to a TAK Server TCP streaming input, for example takserver:8087
//!   --tls <addr>       (feature tls) send to a TAK Server TLS input, for example takserver:8089,
//!                      with --ca ca.pem --cert user.pem --key user.key [--tls-any-name]
//!   --uid <uid>        platform UID for KLV input
//!   --video <url>      video URL to attach to the KLV platform
//!   --affiliation <c>  u, n, f, a, s or h (defaults: f for KLV and MAVLink, u for Remote ID)
//!   --realtime         replay files at their recorded pace
//!   --friendly <id>    Remote ID: this Basic ID or Operator ID is one of yours (repeatable);
//!                      drawn friendly unless its verdict is spoofed or suspicious
//!   --spoofed-as <c>   Remote ID: affiliation for a spoofed verdict (default s, suspect)
//!   --suspicious-as <c> Remote ID: affiliation for a suspicious verdict (default unchanged)
//!   --picture          Remote ID: enrich each aircraft marker with a plain-language headline
//!                      (model identity, trust verdict, launch point) and join its takeoff
//!                      point to the aircraft with a link
//! ```
//!
//! Remote ID ground markers say what the broadcast position is: a takeoff
//! point gets its own `rid-takeoff-<id>` marker, not an operator marker.
//!
//! Without `--udp` or `--tcp` the events are printed, one XML document per line.

use std::io::{self, Write};
use std::time::Duration;
use uas_cot::net::{TcpSender, UdpSender};
use uas_cot::{fmv, mavlink, rid, Event};

enum Sink {
    Stdout(io::Stdout),
    Udp(UdpSender),
    Tcp(TcpSender),
    #[cfg(feature = "tls")]
    Tls(Box<uas_cot::net::TlsSender>),
}

impl Sink {
    fn send(&mut self, e: &Event) -> io::Result<()> {
        match self {
            Sink::Stdout(o) => writeln!(o.lock(), "{}", e.to_xml()),
            Sink::Udp(u) => u.send(e),
            Sink::Tcp(t) => t.send(e),
            #[cfg(feature = "tls")]
            Sink::Tls(t) => t.send(e),
        }
    }
}

struct Args {
    mode: String,
    input: String,
    sink: Sink,
    uid: Option<String>,
    video: Option<String>,
    affiliation: Option<char>,
    realtime: bool,
    rules: rid::AffiliationRules,
    picture: bool,
}

fn usage() -> ! {
    eprintln!("usage: uas2cot <klv|tlog|pcap|mavlink-udp> <input> [--udp addr | --tcp addr | --tls addr --ca f --cert f --key f [--tls-any-name]] [--uid uid] [--video url] [--affiliation c] [--friendly id]... [--spoofed-as c] [--suspicious-as c] [--picture] [--realtime]");
    std::process::exit(2)
}

fn parse_args() -> io::Result<Args> {
    let mut it = std::env::args().skip(1);
    let mode = it.next().unwrap_or_else(|| usage());
    let input = it.next().unwrap_or_else(|| usage());
    let mut a = Args {
        mode,
        input,
        sink: Sink::Stdout(io::stdout()),
        uid: None,
        video: None,
        affiliation: None,
        realtime: false,
        rules: rid::AffiliationRules::default(),
        picture: false,
    };
    let mut tls_addr: Option<String> = None;
    let (mut ca, mut cert, mut key, mut any_name) = (None, None, None, false);
    while let Some(flag) = it.next() {
        let mut val = || it.next().unwrap_or_else(|| usage());
        match flag.as_str() {
            "--udp" => a.sink = Sink::Udp(UdpSender::new(val())?),
            "--tcp" => a.sink = Sink::Tcp(TcpSender::connect(val())?),
            "--uid" => a.uid = Some(val()),
            "--video" => a.video = Some(val()),
            "--affiliation" => a.affiliation = val().chars().next(),
            "--realtime" => a.realtime = true,
            "--picture" => a.picture = true,
            "--friendly" => a.rules = a.rules.clone().friendly_id(val()),
            "--spoofed-as" => {
                a.rules = a
                    .rules
                    .clone()
                    .spoofed_as(val().chars().next().unwrap_or('s'))
            }
            "--suspicious-as" => {
                a.rules = a
                    .rules
                    .clone()
                    .suspicious_as(val().chars().next().unwrap_or('u'))
            }
            "--tls" => tls_addr = Some(val()),
            "--ca" => ca = Some(val()),
            "--cert" => cert = Some(val()),
            "--key" => key = Some(val()),
            "--tls-any-name" => any_name = true,
            _ => usage(),
        }
    }
    if let Some(addr) = tls_addr {
        a.sink = tls_sink(&addr, ca, cert, key, any_name)?;
    }
    Ok(a)
}

#[cfg(feature = "tls")]
fn tls_sink(
    addr: &str,
    ca: Option<String>,
    cert: Option<String>,
    key: Option<String>,
    any_name: bool,
) -> io::Result<Sink> {
    let (Some(ca), Some(cert), Some(key)) = (ca, cert, key) else {
        eprintln!("uas2cot: --tls needs --ca, --cert and --key (PEM files)");
        std::process::exit(2)
    };
    let (ca, cert, key) = (
        std::fs::read(ca)?,
        std::fs::read(cert)?,
        std::fs::read(key)?,
    );
    let cfg = if any_name {
        uas_cot::net::TlsConfig::from_pem_any_name(&ca, &cert, &key)?
    } else {
        uas_cot::net::TlsConfig::from_pem(&ca, &cert, &key)?
    };
    Ok(Sink::Tls(Box::new(uas_cot::net::TlsSender::connect(
        addr, &cfg,
    )?)))
}

#[cfg(not(feature = "tls"))]
fn tls_sink(
    _: &str,
    _: Option<String>,
    _: Option<String>,
    _: Option<String>,
    _: bool,
) -> io::Result<Sink> {
    eprintln!("uas2cot: built without TLS; cargo install uas-cot --features tls");
    std::process::exit(2)
}

/// Sleeps so that events go out at the pace of their timestamps.
struct Pacer {
    first: Option<(u64, std::time::Instant)>,
    on: bool,
}

impl Pacer {
    fn wait(&mut self, ts_us: u64) {
        if !self.on {
            return;
        }
        let (t0, w0) = *self.first.get_or_insert((ts_us, std::time::Instant::now()));
        let due = w0 + Duration::from_micros(ts_us.saturating_sub(t0));
        if let Some(d) = due.checked_duration_since(std::time::Instant::now()) {
            std::thread::sleep(d);
        }
    }
}

fn run_klv(a: &mut Args) -> io::Result<usize> {
    let bytes = std::fs::read(&a.input)?;
    let mut opts = fmv::Options {
        uid: a.uid.clone(),
        video_url: a.video.clone(),
        ..Default::default()
    };
    if let Some(c) = a.affiliation {
        opts.affiliation = c;
    }
    let mut pacer = Pacer {
        first: None,
        on: a.realtime,
    };
    let mut n = 0;
    for unit in misb::klv::split(&bytes) {
        let Ok(packet) = misb::st0601::Packet::from_unit(&unit) else {
            continue;
        };
        if let Some(t) = packet.timestamp() {
            pacer.wait(t);
        }
        for e in fmv::events(&packet, &opts) {
            a.sink.send(&e)?;
            n += 1;
        }
    }
    Ok(n)
}

/// Per-stream MAVLink state: vehicle types and, with `mavlink-m`, the
/// MAVLink-M gateway.
struct MavState {
    opts: mavlink::Options,
    types: [Option<u8>; 256],
    #[cfg(feature = "mavlink-m")]
    gw: uas_cot::mavlink_m::Gateway,
}

impl MavState {
    fn new(affiliation: Option<char>) -> Self {
        let mut opts = mavlink::Options::default();
        if let Some(c) = affiliation {
            opts.affiliation = c;
        }
        MavState {
            opts,
            types: [None; 256],
            #[cfg(feature = "mavlink-m")]
            gw: uas_cot::mavlink_m::Gateway::default(),
        }
    }

    /// The event for one frame, if it makes one.
    fn frame(&mut self, frame: &mavlink_tlog::FrameRef<'_>, ts: u64) -> Option<Event> {
        let sys = frame.sys_id();
        match frame.msg_id() {
            mavlink::HEARTBEAT_ID if frame.comp_id() == 1 => {
                self.types[sys as usize] = mavlink::heartbeat_mav_type(frame.payload());
                None
            }
            mavlink::GLOBAL_POSITION_INT_ID => {
                let pos = mavlink::GlobalPositionInt::parse(frame.payload())?;
                mavlink::vehicle(sys, &pos, self.types[sys as usize], ts, &self.opts)
            }
            #[cfg(feature = "mavlink-m")]
            id => self.gw.ingest(sys, id, frame.payload(), ts),
            #[cfg(not(feature = "mavlink-m"))]
            _ => None,
        }
    }
}

/// CRC_EXTRA lookup: the built-in common/ardupilot table, then MAVLink-M.
fn crc_extra(id: u32) -> Option<u8> {
    if let Some(i) = mavlink_tlog::message_info(id) {
        return Some(i.crc_extra);
    }
    #[cfg(feature = "mavlink-m")]
    {
        uas_cot::mavlink_m::crc_extra(id)
    }
    #[cfg(not(feature = "mavlink-m"))]
    {
        None
    }
}

fn run_tlog(a: &mut Args) -> io::Result<usize> {
    let file = std::fs::File::open(&a.input)?;
    let mut reader = mavlink_tlog::TlogReader::new(io::BufReader::new(file));
    let mut st = MavState::new(a.affiliation);
    let mut pacer = Pacer {
        first: None,
        on: a.realtime,
    };
    let mut n = 0;
    while let Some(rec) = reader.next_record()? {
        let (ts, frame) = (rec.timestamp_us, rec.frame);
        if frame
            .check(mavlink_tlog::CrcPolicy::Custom(crc_extra))
            .is_err()
        {
            continue;
        }
        if let Some(e) = st.frame(&frame, ts) {
            pacer.wait(ts);
            a.sink.send(&e)?;
            n += 1;
        }
    }
    Ok(n)
}

fn run_mavlink_udp(a: &mut Args) -> io::Result<usize> {
    let sock = std::net::UdpSocket::bind(&a.input)?;
    let mut st = MavState::new(a.affiliation);
    let mut buf = [0u8; 2048];
    loop {
        let len = sock.recv(&mut buf)?;
        let mut data = &buf[..len];
        while !data.is_empty() {
            let Ok(frame) = mavlink_tlog::FrameRef::parse_unchecked(data) else {
                break;
            };
            data = &data[frame.len()..];
            if frame
                .check(mavlink_tlog::CrcPolicy::Custom(crc_extra))
                .is_err()
            {
                continue;
            }
            if let Some(e) = st.frame(&frame, uas_cot::now_us()) {
                a.sink.send(&e)?;
            }
        }
    }
}

/// (linktype, timestamp us, packet) from a classic little-endian pcap.
fn read_pcap(b: &[u8]) -> io::Result<Vec<(u32, u64, &[u8])>> {
    let bad = || io::Error::new(io::ErrorKind::InvalidData, "not a little-endian pcap file");
    if b.len() < 24 {
        return Err(bad());
    }
    let nanos = match b[..4] {
        [0xd4, 0xc3, 0xb2, 0xa1] => false,
        [0x4d, 0x3c, 0xb2, 0xa1] => true,
        _ => return Err(bad()),
    };
    let lt = u32::from_le_bytes([b[20], b[21], b[22], b[23]]);
    let mut off = 24;
    let mut out = Vec::new();
    while off + 16 <= b.len() {
        let sec = u32::from_le_bytes(b[off..off + 4].try_into().expect("4 bytes")) as u64;
        let frac = u32::from_le_bytes(b[off + 4..off + 8].try_into().expect("4 bytes")) as u64;
        let cl = u32::from_le_bytes(b[off + 8..off + 12].try_into().expect("4 bytes")) as usize;
        off += 16;
        let Some(pkt) = b.get(off..off + cl) else {
            break;
        };
        out.push((
            lt,
            sec * 1_000_000 + if nanos { frac / 1000 } else { frac },
            pkt,
        ));
        off += cl;
    }
    Ok(out)
}

fn run_pcap(a: &mut Args) -> io::Result<usize> {
    let bytes = std::fs::read(&a.input)?;
    let mut opts = rid::Options::default();
    if let Some(c) = a.affiliation {
        opts.affiliation = c;
    }
    let mut tracker = remoteid::Tracker::new(remoteid::TrackerConfig {
        timeout: u64::MAX,
        ..Default::default()
    });
    let mut pacer = Pacer {
        first: None,
        on: a.realtime,
    };
    let mut n = 0;
    for (lt, ts, pkt) in read_pcap(&bytes)? {
        let frame = match lt {
            127 => match remoteid::wifi::strip_radiotap(pkt) {
                Ok(f) => f,
                Err(_) => continue,
            },
            105 => pkt,
            _ => continue,
        };
        let Ok(r) = remoteid::wifi::parse_frame(frame) else {
            continue;
        };
        let mac: String = r.source.iter().map(|b| format!("{b:02X}")).collect();
        let uas = tracker.ingest_wifi(&r, ts / 1000);
        pacer.wait(ts);
        let events = if a.picture {
            // A Wi-Fi capture carries no video, so there is no camera ground
            // target here; the headline, model identity and joined takeoff
            // point still apply.
            rid::tracked_picture(uas, Some(&mac), ts, &opts, &a.rules, None)
        } else {
            rid::tracked_with(uas, Some(&mac), ts, &opts, &a.rules)
        };
        for e in events {
            a.sink.send(&e)?;
            n += 1;
        }
    }
    Ok(n)
}

fn main() {
    let r = parse_args().and_then(|mut a| match a.mode.as_str() {
        "klv" => run_klv(&mut a),
        "tlog" => run_tlog(&mut a),
        "pcap" => run_pcap(&mut a),
        "mavlink-udp" => run_mavlink_udp(&mut a),
        _ => usage(),
    });
    match r {
        Ok(n) => eprintln!("uas2cot: {n} events"),
        Err(e) => {
            eprintln!("uas2cot: {e}");
            std::process::exit(1);
        }
    }
}