openvpn-mgmt-frame 1.0.0-rc.4

Low-level line framing for the OpenVPN management protocol.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Frame decoder for the OpenVPN management protocol.

use std::collections::BTreeMap;
use std::io;

use bytes::{Buf, BytesMut};
use tokio_util::codec::Decoder;
use tracing::warn;

use crate::encoder::AccumulationLimit;
use crate::frame::Frame;

/// May arrive without a trailing newline (OpenVPN >= 2.6 sends it as an
/// interactive prompt).
const PW_PROMPT: &[u8] = b"ENTER PASSWORD:";

/// Internal accumulator for `>CLIENT:` ENV blocks.
#[derive(Debug)]
struct ClientEnvAccumulator {
    event: String,
    args: String,
    env: BTreeMap<String, String>,
}

/// A low-level decoder that splits the byte stream into [`Frame`] values.
///
/// This decoder classifies each line purely from its content — it does
/// **not** track which command was sent. Multi-line response accumulation
/// (`Line`/`End` grouping) is left to higher layers.
///
/// `>CLIENT:ENV` accumulation **is** handled here because the protocol
/// guarantees atomicity for that block.
///
/// # Example
///
/// ```
/// use bytes::BytesMut;
/// use tokio_util::codec::Decoder;
/// use openvpn_mgmt_frame::{Frame, FrameDecoder};
///
/// let mut decoder = FrameDecoder::new();
/// let mut buf = BytesMut::from(">INFO:OpenVPN Management Interface\n");
///
/// // The first >INFO: line is emitted as Frame::Info (the connection banner).
/// assert_eq!(
///     decoder.decode(&mut buf).unwrap(),
///     Some(Frame::Info("OpenVPN Management Interface".to_string())),
/// );
/// ```
#[derive(Debug)]
pub struct FrameDecoder {
    /// Accumulator for `>CLIENT:` ENV blocks.
    client_notification: Option<ClientEnvAccumulator>,

    /// Maximum ENV entries.
    max_client_env_entries: AccumulationLimit,

    /// Whether the initial `>INFO:` banner has been seen.
    seen_info: bool,
}

impl Default for FrameDecoder {
    fn default() -> Self {
        Self {
            client_notification: None,
            max_client_env_entries: AccumulationLimit::Unlimited,
            seen_info: false,
        }
    }
}

impl FrameDecoder {
    /// Create a new frame decoder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the maximum ENV entries for `>CLIENT:` notifications.
    pub fn with_max_client_env_entries(mut self, limit: AccumulationLimit) -> Self {
        self.max_client_env_entries = limit;
        self
    }
}

fn check_accumulation_limit(
    current_len: usize,
    limit: AccumulationLimit,
    what: &'static str,
) -> Result<(), io::Error> {
    if let AccumulationLimit::Max(max) = limit
        && current_len >= max
    {
        return Err(io::Error::other(AccumulationLimitExceeded { what, max }));
    }
    Ok(())
}

#[derive(Debug, thiserror::Error)]
#[error("{what} accumulation limit exceeded ({max})")]
struct AccumulationLimitExceeded {
    what: &'static str,
    max: usize,
}

impl Decoder for FrameDecoder {
    type Item = Frame;
    type Error = io::Error;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        loop {
            // Find the next complete line.
            let Some(newline_pos) = src.iter().position(|&b| b == b'\n') else {
                // No complete line. Check for password prompt without
                // trailing newline (OpenVPN >= 2.6).
                if src.starts_with(PW_PROMPT) {
                    let mut consume = PW_PROMPT.len();
                    if src.get(consume) == Some(&b'\r') {
                        consume += 1;
                    }
                    src.advance(consume);
                    return Ok(Some(Frame::PasswordPrompt));
                }
                if src.capacity() - src.len() < 256 {
                    src.reserve(256);
                }
                return Ok(None);
            };

            // Extract and decode the line.
            let line_bytes = src.split_to(newline_pos + 1);
            let line = match std::str::from_utf8(&line_bytes) {
                Ok(text) => text,
                Err(error) => {
                    self.client_notification = None;
                    return Err(io::Error::new(io::ErrorKind::InvalidData, error));
                }
            }
            .trim_end_matches(['\r', '\n'])
            .to_string();

            // Empty lines carry no information when the decoder is not
            // inside a CLIENT ENV accumulation. However, they *are*
            // meaningful in multi-line response blocks — the higher layer
            // decides whether to keep or discard them, so we emit them
            // as `Frame::Line("")`.
            if line.is_empty() && self.client_notification.is_none() {
                return Ok(Some(Frame::Line(line)));
            }

            // --- Phase 1: >CLIENT:ENV accumulation ---
            if let Some(ref mut accum) = self.client_notification
                && let Some(rest) = line.strip_prefix(">CLIENT:ENV,")
            {
                if rest == "END" {
                    let finished = self.client_notification.take().expect("guarded by if-let");
                    return Ok(Some(Frame::ClientEnv {
                        event: finished.event,
                        args: finished.args,
                        env: finished.env,
                    }));
                }
                let (k, v) = rest
                    .split_once('=')
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .unwrap_or_else(|| (rest.to_string(), String::new()));
                check_accumulation_limit(
                    accum.env.len(),
                    self.max_client_env_entries,
                    "client ENV",
                )?;
                accum.env.insert(k, v);
                continue;
            }

            // --- Phase 2: Self-describing lines ---

            if let Some(rest) = line.strip_prefix("SUCCESS:") {
                return Ok(Some(Frame::Success(
                    rest.strip_prefix(' ').unwrap_or(rest).to_string(),
                )));
            }

            if let Some(rest) = line.strip_prefix("ERROR:") {
                return Ok(Some(Frame::Error(
                    rest.strip_prefix(' ').unwrap_or(rest).to_string(),
                )));
            }

            if line == "ENTER PASSWORD:" {
                return Ok(Some(Frame::PasswordPrompt));
            }

            if line == "END" {
                return Ok(Some(Frame::End));
            }

            // --- Phase 3: Notifications ---
            if let Some(inner) = line.strip_prefix('>') {
                let Some((kind, payload)) = inner.split_once(':') else {
                    warn!(line = %line, "malformed notification (no colon)");
                    // Emit as a plain Line — the higher layer decides
                    // whether this is Unrecognized.
                    return Ok(Some(Frame::Line(line)));
                };

                // >INFO: banner handling.
                if kind == "INFO" {
                    if !self.seen_info {
                        self.seen_info = true;
                        return Ok(Some(Frame::Info(payload.to_string())));
                    }
                    return Ok(Some(Frame::Notification {
                        kind: kind.to_string(),
                        payload: payload.to_string(),
                    }));
                }

                // >CLIENT: — start ENV accumulation (except ADDRESS which
                // is single-line).
                if kind == "CLIENT" {
                    let (event, args) = payload
                        .split_once(',')
                        .map(|(e, a)| (e.to_string(), a.to_string()))
                        .unwrap_or_else(|| (payload.to_string(), String::new()));

                    if event == "ADDRESS" {
                        // Single-line — emit as Notification directly.
                        return Ok(Some(Frame::Notification {
                            kind: "CLIENT".to_string(),
                            payload: payload.to_string(),
                        }));
                    }

                    // Multi-line CLIENT notification — start accumulation.
                    self.client_notification = Some(ClientEnvAccumulator {
                        event,
                        args,
                        env: BTreeMap::new(),
                    });
                    continue; // Read ENV lines.
                }

                return Ok(Some(Frame::Notification {
                    kind: kind.to_string(),
                    payload: payload.to_string(),
                }));
            }

            // --- Phase 4: Unclassified line ---
            return Ok(Some(Frame::Line(line)));
        }
    }
}

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

    fn decode_one(input: &str) -> Frame {
        let mut decoder = FrameDecoder::new();
        let mut buf = BytesMut::from(input);
        decoder.decode(&mut buf).unwrap().unwrap()
    }

    #[test]
    fn success_line() {
        assert_eq!(
            decode_one("SUCCESS: pid=42\n"),
            Frame::Success("pid=42".to_string())
        );
    }

    #[test]
    fn error_line() {
        assert_eq!(
            decode_one("ERROR: unknown command\n"),
            Frame::Error("unknown command".to_string())
        );
    }

    #[test]
    fn end_line() {
        assert_eq!(decode_one("END\n"), Frame::End);
    }

    #[test]
    fn plain_line() {
        assert_eq!(
            decode_one("TITLE\tOpenVPN 2.6.8\n"),
            Frame::Line("TITLE\tOpenVPN 2.6.8".to_string())
        );
    }

    #[test]
    fn notification() {
        assert_eq!(
            decode_one(">HOLD:Waiting for hold release:0\n"),
            Frame::Notification {
                kind: "HOLD".to_string(),
                payload: "Waiting for hold release:0".to_string(),
            }
        );
    }

    #[test]
    fn info_banner() {
        let mut decoder = FrameDecoder::new();
        let mut buf = BytesMut::from(">INFO:OpenVPN Management Interface\n>INFO:second\n");

        let first = decoder.decode(&mut buf).unwrap().unwrap();
        assert_eq!(
            first,
            Frame::Info("OpenVPN Management Interface".to_string())
        );

        let second = decoder.decode(&mut buf).unwrap().unwrap();
        assert_eq!(
            second,
            Frame::Notification {
                kind: "INFO".to_string(),
                payload: "second".to_string(),
            }
        );
    }

    #[test]
    fn state_notification() {
        let frame = decode_one(">STATE:1711000000,CONNECTED,SUCCESS,10.8.0.6,1.2.3.4,,,,\n");
        assert!(matches!(frame, Frame::Notification { kind, .. } if kind == "STATE"));
    }

    #[test]
    fn client_env_accumulation() {
        let mut decoder = FrameDecoder::new();
        let input = "\
            >CLIENT:CONNECT,1,2\n\
            >CLIENT:ENV,common_name=alice\n\
            >CLIENT:ENV,password=secret\n\
            >CLIENT:ENV,END\n";
        let mut buf = BytesMut::from(input);

        let frame = decoder.decode(&mut buf).unwrap().unwrap();
        match frame {
            Frame::ClientEnv { event, args, env } => {
                assert_eq!(event, "CONNECT");
                assert_eq!(args, "1,2");
                assert_eq!(env.get("common_name").unwrap(), "alice");
                assert_eq!(env.get("password").unwrap(), "secret");
            }
            other => panic!("expected ClientEnv, got {other:?}"),
        }
    }

    #[test]
    fn client_address_is_single_line() {
        let frame = decode_one(">CLIENT:ADDRESS,1,10.8.0.6,1\n");
        assert!(matches!(frame, Frame::Notification { kind, .. } if kind == "CLIENT"));
    }

    #[test]
    fn password_prompt_with_newline() {
        assert_eq!(decode_one("ENTER PASSWORD:\n"), Frame::PasswordPrompt,);
    }

    #[test]
    fn password_prompt_without_newline() {
        let mut decoder = FrameDecoder::new();
        let mut buf = BytesMut::from("ENTER PASSWORD:");
        let frame = decoder.decode(&mut buf).unwrap().unwrap();
        assert_eq!(frame, Frame::PasswordPrompt);
    }

    #[test]
    fn empty_lines_emitted_as_line() {
        let mut decoder = FrameDecoder::new();
        let mut buf = BytesMut::from("\n\n\nSUCCESS: ok\n");
        // Empty lines are emitted as Frame::Line("") — the higher layer
        // decides whether to keep or discard them.
        assert_eq!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Line(String::new())
        );
        assert_eq!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Line(String::new())
        );
        assert_eq!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Line(String::new())
        );
        assert_eq!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Success("ok".to_string())
        );
    }

    // --- Multi-frame sequences ---

    #[test]
    fn multi_frame_sequence() {
        let mut decoder = FrameDecoder::new();
        let mut buf =
            BytesMut::from("SUCCESS: pid=42\n>STATE:0,CONNECTING,,,,,,,\nERROR: unknown\nEND\n");

        assert_eq!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Success("pid=42".to_string())
        );
        assert!(matches!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Notification { ref kind, .. } if kind == "STATE"
        ));
        assert_eq!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Error("unknown".to_string())
        );
        assert_eq!(decoder.decode(&mut buf).unwrap().unwrap(), Frame::End);
        assert_eq!(decoder.decode(&mut buf).unwrap(), None);
    }

    #[test]
    fn line_then_end_sequence() {
        let mut decoder = FrameDecoder::new();
        let mut buf = BytesMut::from("TITLE\tOpenVPN 2.6\nManagement Version: 5\nEND\n");

        assert_eq!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Line("TITLE\tOpenVPN 2.6".to_string())
        );
        assert_eq!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Line("Management Version: 5".to_string())
        );
        assert_eq!(decoder.decode(&mut buf).unwrap().unwrap(), Frame::End);
    }

    // --- Partial reads ---

    #[test]
    fn partial_line_returns_none() {
        let mut decoder = FrameDecoder::new();
        let mut buf = BytesMut::from("SUCCESS: pi");
        assert_eq!(decoder.decode(&mut buf).unwrap(), None);

        // Complete the line.
        buf.extend_from_slice(b"d=42\n");
        assert_eq!(
            decoder.decode(&mut buf).unwrap().unwrap(),
            Frame::Success("pid=42".to_string())
        );
    }

    #[test]
    fn partial_client_env_accumulates_across_calls() {
        let mut decoder = FrameDecoder::new();

        let mut buf = BytesMut::from(">CLIENT:CONNECT,5,3\n");
        assert_eq!(decoder.decode(&mut buf).unwrap(), None); // starts accumulation

        buf.extend_from_slice(b">CLIENT:ENV,user=alice\n");
        assert_eq!(decoder.decode(&mut buf).unwrap(), None); // still accumulating

        buf.extend_from_slice(b">CLIENT:ENV,END\n");
        let frame = decoder.decode(&mut buf).unwrap().unwrap();
        match frame {
            Frame::ClientEnv { event, args, env } => {
                assert_eq!(event, "CONNECT");
                assert_eq!(args, "5,3");
                assert_eq!(env.len(), 1);
                assert_eq!(env["user"], "alice");
            }
            other => panic!("expected ClientEnv, got {other:?}"),
        }
    }

    // --- CR_RESPONSE client event ---

    #[test]
    fn client_cr_response_starts_accumulation() {
        let mut decoder = FrameDecoder::new();
        let mut buf = BytesMut::from(">CLIENT:CR_RESPONSE,10,2,dGVzdA==\n>CLIENT:ENV,END\n");
        let frame = decoder.decode(&mut buf).unwrap().unwrap();
        match frame {
            Frame::ClientEnv { event, args, .. } => {
                assert_eq!(event, "CR_RESPONSE");
                assert!(args.contains("10,2,dGVzdA=="));
            }
            other => panic!("expected ClientEnv, got {other:?}"),
        }
    }

    // --- UTF-8 errors ---

    #[test]
    fn invalid_utf8_returns_error() {
        let mut decoder = FrameDecoder::new();
        let mut buf = BytesMut::from(&b"SUCCESS: \xff\xfe\n"[..]);
        let err = decoder.decode(&mut buf).unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
    }

    // --- CRLF handling ---

    #[test]
    fn crlf_line_endings_stripped() {
        assert_eq!(
            decode_one("SUCCESS: ok\r\n"),
            Frame::Success("ok".to_string())
        );
    }

    // --- SUCCESS/ERROR edge cases ---

    #[test]
    fn success_bare_no_payload() {
        assert_eq!(decode_one("SUCCESS:\n"), Frame::Success(String::new()));
    }

    #[test]
    fn error_bare_no_payload() {
        assert_eq!(decode_one("ERROR:\n"), Frame::Error(String::new()));
    }

    // --- Malformed notification ---

    #[test]
    fn notification_without_colon_emitted_as_line() {
        // `>GARBAGE` has no `:` — emitted as Line, not Notification.
        let frame = decode_one(">GARBAGE\n");
        assert_eq!(frame, Frame::Line(">GARBAGE".to_string()));
    }

    // --- ENV accumulation limit ---

    #[test]
    fn client_env_limit_exceeded() {
        let mut decoder =
            FrameDecoder::new().with_max_client_env_entries(crate::AccumulationLimit::Max(2));
        let mut buf = BytesMut::from(
            ">CLIENT:CONNECT,1,0\n\
             >CLIENT:ENV,a=1\n\
             >CLIENT:ENV,b=2\n\
             >CLIENT:ENV,c=3\n",
        );

        // First two ENV lines are fine, third exceeds the limit.
        let err = loop {
            match decoder.decode(&mut buf) {
                Ok(Some(_)) => continue,
                Ok(None) => continue,
                Err(e) => break e,
            }
        };
        assert!(err.to_string().contains("limit exceeded"));
    }

    // --- Notification interleaved with CLIENT ENV ---

    #[test]
    fn non_env_line_during_client_accumulation_falls_through() {
        let mut decoder = FrameDecoder::new();
        let mut buf =
            BytesMut::from(">CLIENT:CONNECT,1,0\n>STATE:0,CONNECTING,,,,,,,\n>CLIENT:ENV,END\n");

        // The >STATE: notification arrives during CLIENT accumulation.
        // It should fall through and be emitted as a Notification.
        let first = decoder.decode(&mut buf).unwrap().unwrap();
        assert!(matches!(
            first,
            Frame::Notification { ref kind, .. } if kind == "STATE"
        ));

        // Then the CLIENT block completes.
        let second = decoder.decode(&mut buf).unwrap().unwrap();
        assert!(matches!(second, Frame::ClientEnv { .. }));
    }

    // --- Password prompt edge case ---

    #[test]
    fn password_prompt_with_carriage_return() {
        let mut decoder = FrameDecoder::new();
        let mut buf = BytesMut::from("ENTER PASSWORD:\r");
        let frame = decoder.decode(&mut buf).unwrap().unwrap();
        assert_eq!(frame, Frame::PasswordPrompt);
        assert!(buf.is_empty()); // CR consumed
    }
}