takproto 0.4.2

Rust library for TAK (Team Awareness Kit) Protocol - send CoT messages to TAK servers with mTLS support
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
use crate::error::{Result, TakError};
use crate::framing::{decode_tak_header, encode_tak_message};
use crate::proto::{CotEvent, TakMessage};
use crate::tls::TlsConfig;
use bytes::BytesMut;
use prost::Message;
use rustls::pki_types::ServerName;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;

/// Connection type for TAK client
enum Connection {
    Plain(TcpStream),
    Tls(tokio_rustls::client::TlsStream<TcpStream>),
}

impl Connection {
    async fn read_buf(&mut self, buf: &mut BytesMut) -> std::io::Result<usize> {
        match self {
            Connection::Plain(stream) => stream.read_buf(buf).await,
            Connection::Tls(stream) => stream.read_buf(buf).await,
        }
    }

    async fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
        match self {
            Connection::Plain(stream) => stream.write_all(buf).await,
            Connection::Tls(stream) => stream.write_all(buf).await,
        }
    }

    async fn flush(&mut self) -> std::io::Result<()> {
        match self {
            Connection::Plain(stream) => stream.flush().await,
            Connection::Tls(stream) => stream.flush().await,
        }
    }

    async fn shutdown(&mut self) -> std::io::Result<()> {
        match self {
            Connection::Plain(stream) => stream.shutdown().await,
            Connection::Tls(stream) => stream.shutdown().await,
        }
    }
}

/// TAK Protocol client for streaming connections to TAK servers
///
/// This client implements TAK Protocol Version 1 using Protocol Buffers.
/// It handles the framing protocol for streaming connections and supports
/// both plain TCP and TLS (including mTLS with client certificates).
///
/// # Example with mTLS
///
/// ```no_run
/// use takproto::{TakClient, TlsConfig, proto::CotEvent};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let tls_config = TlsConfig::new_with_client_cert(
///         "ca.pem",
///         "client.pem",
///         "client-key.pem"
///     )?;
///
///     let mut client = TakClient::connect_tls(
///         "takserver.example.com:8089",
///         "takserver.example.com",
///         tls_config
///     ).await?;
///
///     let event = CotEvent {
///         r#type: "a-f-G-U-C".to_string(),
///         uid: "RUST-1".to_string(),
///         // ... other fields
///         ..Default::default()
///     };
///
///     client.send_cot_event(event).await?;
///     Ok(())
/// }
/// ```
pub struct TakClient {
    connection: Connection,
    read_buffer: BytesMut,
}

impl TakClient {
    /// Connect to a TAK server at the specified address using plain TCP
    ///
    /// Note: Most production TAK servers require TLS. Use `connect_tls` instead.
    ///
    /// # Arguments
    ///
    /// * `addr` - The address of the TAK server (e.g., "127.0.0.1:8087")
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use takproto::TakClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = TakClient::connect("127.0.0.1:8087").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect(addr: impl tokio::net::ToSocketAddrs) -> Result<Self> {
        let stream = TcpStream::connect(addr).await?;
        Ok(Self {
            connection: Connection::Plain(stream),
            read_buffer: BytesMut::with_capacity(8192),
        })
    }

    /// Connect to a TAK server using TLS with optional client certificate authentication (mTLS)
    ///
    /// # Arguments
    ///
    /// * `addr` - The address of the TAK server (e.g., "takserver.example.com:8089")
    /// * `server_name` - The server name for SNI and certificate validation
    /// * `tls_config` - TLS configuration including optional client certificates
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use takproto::{TakClient, TlsConfig};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let tls_config = TlsConfig::new_with_client_cert(
    ///     "ca.pem",
    ///     "client.pem",
    ///     "client-key.pem"
    /// )?;
    ///
    /// let client = TakClient::connect_tls(
    ///     "takserver.example.com:8089",
    ///     "takserver.example.com",
    ///     tls_config
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect_tls(
        addr: impl tokio::net::ToSocketAddrs,
        server_name: &str,
        tls_config: TlsConfig,
    ) -> Result<Self> {
        let tcp_stream = TcpStream::connect(addr).await?;

        let connector = TlsConnector::from(tls_config.config);

        let server_name = ServerName::try_from(server_name.to_owned())
            .map_err(|e| TakError::Tls(format!("Invalid server name: {}", e)))?;

        let tls_stream = connector.connect(server_name, tcp_stream).await?;

        Ok(Self {
            connection: Connection::Tls(tls_stream),
            read_buffer: BytesMut::with_capacity(8192),
        })
    }

    /// Send a CoT event to the TAK server
    ///
    /// This wraps the CotEvent in a TakMessage and sends it using the
    /// TAK Protocol streaming message format.
    ///
    /// # Arguments
    ///
    /// * `event` - The CoT event to send
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use takproto::{TakClient, proto::CotEvent};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let mut client = TakClient::connect("127.0.0.1:8087").await?;
    /// let event = CotEvent {
    ///     r#type: "a-f-G-U-C".to_string(),
    ///     uid: "RUST-1".to_string(),
    ///     send_time: 1234567890000,
    ///     start_time: 1234567890000,
    ///     stale_time: 1234567950000,
    ///     how: "m-g".to_string(),
    ///     lat: 37.7749,
    ///     lon: -122.4194,
    ///     hae: 10.0,
    ///     ce: 9.9,
    ///     le: 9.9,
    ///     ..Default::default()
    /// };
    /// client.send_cot_event(event).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send_cot_event(&mut self, event: CotEvent) -> Result<()> {
        let tak_message = TakMessage {
            tak_control: None,
            cot_event: Some(event),
        };
        self.send_tak_message(tak_message).await
    }

    /// Send a raw TakMessage to the server
    ///
    /// This is a lower-level method that allows sending any TakMessage,
    /// including those with TakControl fields.
    ///
    /// # Arguments
    ///
    /// * `message` - The TakMessage to send
    pub async fn send_tak_message(&mut self, message: TakMessage) -> Result<()> {
        let frame = encode_tak_message(&message)?;
        self.connection.write_all(&frame).await?;
        self.connection.flush().await?;
        Ok(())
    }

    /// Receive a TakMessage from the server
    ///
    /// This reads from the stream and decodes the next TAK Protocol message.
    ///
    /// # Returns
    ///
    /// * `Ok(Some(message))` - A message was received
    /// * `Ok(None)` - Connection was closed gracefully
    /// * `Err(e)` - An error occurred
    pub async fn receive_tak_message(&mut self) -> Result<Option<TakMessage>> {
        loop {
            // Try to decode a message from the buffer
            if let Some(message) = self.try_decode_message()? {
                return Ok(Some(message));
            }

            // Read more data from the stream
            let n = self.connection.read_buf(&mut self.read_buffer).await?;

            if n == 0 {
                // Connection closed
                if self.read_buffer.is_empty() {
                    return Ok(None);
                } else {
                    return Err(TakError::ConnectionClosed);
                }
            }
        }
    }

    /// Try to decode a message from the read buffer
    fn try_decode_message(&mut self) -> Result<Option<TakMessage>> {
        // Try to decode the header
        let payload_len = match decode_tak_header(&mut self.read_buffer)? {
            Some(len) => len,
            None => return Ok(None), // Need more data
        };

        // Check if we have the complete payload
        if self.read_buffer.len() < payload_len {
            return Ok(None); // Need more data
        }

        // Split off the payload
        let payload = self.read_buffer.split_to(payload_len);

        // Decode the protobuf message
        let message = TakMessage::decode(&payload[..])?;

        Ok(Some(message))
    }

    /// Send a CoT event as XML (Protocol Version 0)
    ///
    /// This is used for initial communication before protocol negotiation,
    /// or when the server doesn't support protobuf.
    pub async fn send_cot_event_xml(&mut self, event: CotEvent) -> Result<()> {
        let xml = crate::xml::encode_cot_event_xml(&event);
        self.connection.write_all(xml.as_bytes()).await?;
        self.connection.flush().await?;
        Ok(())
    }

    /// Negotiate protocol version with TAK server
    ///
    /// This performs the full protocol negotiation handshake:
    /// 1. Waits for server's TakProtocolSupport message
    /// 2. Sends TakRequest for the specified version
    /// 3. Waits for TakResponse confirmation
    ///
    /// After successful negotiation, the connection is ready for protobuf messages.
    ///
    /// # Arguments
    ///
    /// * `version` - Protocol version to negotiate (typically 1)
    /// * `timeout` - Maximum time to wait for negotiation (in seconds)
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if negotiation succeeds, or an error if it fails or times out.
    pub async fn negotiate_protocol(&mut self, version: u32, timeout_secs: u64) -> Result<()> {
        use tokio::time::{timeout, Duration};

        // Wait for server's protocol support announcement
        let xml_buffer = timeout(
            Duration::from_secs(timeout_secs),
            self.read_xml_messages_until(|msg| crate::xml::is_protocol_support(msg)),
        )
        .await
        .map_err(|_| TakError::NegotiationFailed("Timeout waiting for protocol support".to_string()))??;

        if xml_buffer.is_empty() {
            return Err(TakError::NegotiationFailed(
                "Server did not advertise protocol support".to_string(),
            ));
        }

        // Send protocol request
        let request_xml = crate::xml::create_protocol_request(version);
        self.connection.write_all(request_xml.as_bytes()).await?;
        self.connection.flush().await?;

        // Wait for server's response
        let response_xml = timeout(
            Duration::from_secs(timeout_secs),
            self.read_xml_messages_until(|msg| crate::xml::is_protocol_response(msg)),
        )
        .await
        .map_err(|_| TakError::NegotiationFailed("Timeout waiting for protocol response".to_string()))??;

        if response_xml.is_empty() {
            return Err(TakError::NegotiationFailed(
                "No protocol response received".to_string(),
            ));
        }

        // Check if response is successful
        if !crate::xml::is_protocol_response_success(&response_xml) {
            return Err(TakError::NegotiationFailed(
                "Server rejected protocol request".to_string(),
            ));
        }

        Ok(())
    }

    /// Read XML messages from the connection until a condition is met
    async fn read_xml_messages_until<F>(&mut self, mut condition: F) -> Result<String>
    where
        F: FnMut(&str) -> bool,
    {
        let mut buffer = String::new();
        let mut temp_buf = BytesMut::with_capacity(4096);

        loop {
            // Read more data
            temp_buf.clear();
            let n = self.connection.read_buf(&mut temp_buf).await?;

            if n == 0 {
                return Err(TakError::ConnectionClosed);
            }

            // Append to buffer
            buffer.push_str(&String::from_utf8_lossy(&temp_buf[..]));

            // Check for complete XML message(s)
            while let Some(end_pos) = buffer.find("</event>") {
                let message = &buffer[..end_pos + 8]; // Include </event>
                if condition(message) {
                    return Ok(message.to_string());
                }
                // Remove the processed message from buffer
                buffer = buffer[end_pos + 8..].to_string();
            }
        }
    }

    /// Close the connection to the TAK server
    pub async fn close(mut self) -> Result<()> {
        self.connection.shutdown().await?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cot_event_creation() {
        let event = CotEvent {
            r#type: "a-f-G-U-C".to_string(),
            uid: "TEST-1".to_string(),
            send_time: 1000,
            start_time: 1000,
            stale_time: 2000,
            how: "m-g".to_string(),
            lat: 37.7749,
            lon: -122.4194,
            hae: 10.0,
            ce: 9.9,
            le: 9.9,
            ..Default::default()
        };

        assert_eq!(event.r#type, "a-f-G-U-C");
        assert_eq!(event.uid, "TEST-1");
    }
}