summaryrefslogtreecommitdiffstats
path: root/src/configuration/uapi/get.rs
blob: 9b0542144d9df6a9eb7b5e3656cebc82d6f46e55 (plain) (blame)
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
use hex::FromHex;
use subtle::ConstantTimeEq;

use super::Configuration;
use std::io;

pub fn serialize<C: Configuration, W: io::Write>(writer: &mut W, config: &C) -> io::Result<()> {
    let mut write = |key: &'static str, value: String| {
        debug_assert!(value.is_ascii());
        debug_assert!(key.is_ascii());
        writer.write(key.as_ref())?;
        writer.write(b"=")?;
        writer.write(value.as_ref())
    };

    // serialize interface
    config
        .get_private_key()
        .map(|sk| write("private_key", hex::encode(sk.to_bytes())));

    config
        .get_listen_port()
        .map(|port| write("listen_port", port.to_string()));

    config
        .get_fwmark()
        .map(|fwmark| write("fwmark", fwmark.to_string()));

    // serialize all peers
    let mut peers = config.get_peers();
    while let Some(p) = peers.pop() {
        write("rx_bytes", p.rx_bytes.to_string())?;
        write("tx_bytes", p.tx_bytes.to_string())?;
        write(
            "last_handshake_time_sec",
            p.last_handshake_time_nsec.to_string(),
        )?;
        write(
            "last_handshake_time_nsec",
            p.last_handshake_time_nsec.to_string(),
        )?;
        write("public_key", hex::encode(p.public_key.as_bytes()))?;
        if let Some(psk) = p.preshared_key {
            write("preshared_key", hex::encode(psk))?;
        }
        for (ip, cidr) in p.allowed_ips {
            write("allowed_ip", ip.to_string() + "/" + &cidr.to_string())?;
        }
    }

    Ok(())
}