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
pub mod error;
pub mod host;

use std::collections::HashSet;
use std::fmt;
use std::net::{IpAddr, SocketAddr};
use std::time::{Duration, SystemTime};

use chrono::DateTime;
use error::NetzworkApiError;
use hmac_sha256::Hash;
use host::id::get_secure_machine_id;
use local_ip_address::list_afinet_netifas;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::host::HostInfo;

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub struct Heartbeat {
    /// Heartbeat type
    pub hb_type: HeartbeatType,
    /// Current timestamp
    pub timestamp: DateTime<chrono::Utc>,
    /// UUID (v4) of this heartbeat
    pub hb_uuid: Uuid,
    /// Payload
    pub payload: Vec<HeartbeatPayload>,
}

impl Heartbeat {
    pub fn new(
        hb_type: HeartbeatType,
        name: String,
        agent_status: Option<AgentStatus>,
    ) -> Heartbeat {
        let status = match agent_status {
            Some(s) => s,
            None => AgentStatus::Undefined,
        };
        Heartbeat {
            hb_type,
            timestamp: DateTime::from(SystemTime::now()),
            hb_uuid: Uuid::new_v4(),
            payload: vec![
                HeartbeatPayload::AgentInfo(AgentInfo { status, name }),
                HeartbeatPayload::HostInfo(HostInfo::new()),
                HeartbeatPayload::BuildInfo(BuildInfo::new()),
                HeartbeatPayload::NetInterfaceInfo(
                    NetInterfaceInfo::from_network_interfaces()
                        .expect("Could not generate network interface info"),
                ),
            ],
        }
    }
    pub fn compact(payload: Vec<HeartbeatPayloadType>) -> Heartbeat {
        let mut hb = Heartbeat {
            hb_type: HeartbeatType::Compact,
            timestamp: DateTime::from(SystemTime::now()),
            hb_uuid: Uuid::new_v4(),
            payload: vec![],
        };
        for p in payload.iter() {
            hb.payload.push(p.to_payload())
        }
        hb
    }
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub enum HeartbeatPayloadType {
    AgentInfo(AgentStatus, String),
    HostInfo,
    BuildInfo,
    NetInterfaceInfo,
}
impl HeartbeatPayloadType {
    pub fn to_payload(&self) -> HeartbeatPayload {
        match self {
            HeartbeatPayloadType::AgentInfo(status, name) => {
                HeartbeatPayload::AgentInfo(AgentInfo {
                    status: status.to_owned(),
                    name: name.to_string(),
                })
            }
            HeartbeatPayloadType::HostInfo => HeartbeatPayload::HostInfo(HostInfo::new()),
            HeartbeatPayloadType::BuildInfo => HeartbeatPayload::BuildInfo(BuildInfo::new()),
            HeartbeatPayloadType::NetInterfaceInfo => HeartbeatPayload::NetInterfaceInfo(
                NetInterfaceInfo::from_network_interfaces()
                    .expect("Could not generate network interface info"),
            ),
        }
    }
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub enum HeartbeatPayload {
    AgentInfo(AgentInfo),
    HostInfo(HostInfo),
    BuildInfo(BuildInfo),
    NetInterfaceInfo(NetInterfaceInfo),
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub enum HeartbeatType {
    /// A full heartbeat contains information in all data structures
    Full,
    /// A compact heartbeat contains a minimal amount of information,
    /// indicating that information is unchanged compared to the previous heartbeat.
    Compact,
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub struct AgentInfo {
    pub status: AgentStatus,
    pub name: String,
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub enum AgentStatus {
    Undefined,
    Initializing,
    AwaitingJoin,
    Running,
    Orphaned,
    Exiting,
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub struct BuildInfo {
    // TODO: Include API crate version here
    // See: https://linear.app/netzwork/issue/NET-31/api-include-api-crate-version-in-the-buildinfo-struct
    build_timestamp: String,
    build_date: String,
    git_branch: String,
    git_timestamp: String,
    git_date: String,
    git_hash: String,
    git_describe: String,
    rustc_host_triple: String,
    rustc_version: String,
    cargo_target_triple: String,
}

impl BuildInfo {
    fn new() -> BuildInfo {
        BuildInfo {
            build_timestamp: String::from(env!("VERGEN_BUILD_TIMESTAMP")),
            build_date: String::from(env!("VERGEN_BUILD_DATE")),
            git_branch: String::from(env!("VERGEN_GIT_BRANCH")),
            git_timestamp: String::from(env!("VERGEN_GIT_COMMIT_TIMESTAMP")),
            git_date: String::from(env!("VERGEN_GIT_COMMIT_DATE")),
            git_hash: String::from(env!("VERGEN_GIT_SHA")),
            git_describe: String::from(env!("VERGEN_GIT_DESCRIBE")),
            rustc_host_triple: String::from(env!("VERGEN_RUSTC_HOST_TRIPLE")),
            rustc_version: String::from(env!("VERGEN_RUSTC_SEMVER")),
            cargo_target_triple: String::from(env!("VERGEN_CARGO_TARGET_TRIPLE")),
        }
    }
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub struct NetInterfaceId {
    machine_id: Uuid,
    if_name: String,
    ip_addr: Vec<IpAddr>,
}

impl fmt::Display for NetInterfaceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let parts: Vec<String> = vec![
            self.machine_id.to_string(),
            self.if_name.clone(),
            self.ip_addr
                .iter()
                .map(|ip| ip.to_string())
                .collect::<Vec<String>>()
                .join(", "),
        ];
        write!(f, "{}", parts.join("_"))
    }
}

impl NetInterfaceId {
    pub fn fingerprint(&self, ip_addr: &IpAddr) -> [u8; 32] {
        let mut hash = Hash::new();
        hash.update(self.machine_id);
        hash.update(self.if_name.clone());
        hash.update(ip_addr.to_string());
        hash.finalize()
    }
    pub fn fingerprint_set(&self) -> HashSet<[u8; 32]> {
        let mut set = HashSet::new();
        for addr in self.ip_addr.iter() {
            set.insert(self.fingerprint(addr));
        }
        set
    }
}

pub fn identify_interface(
    known_interfaces: &[NetInterfaceId],
    remote_socket: &SocketAddr,
    fingerprint: [u8; 32],
) -> Result<NetInterfaceId, NetzworkApiError> {
    for iface in known_interfaces.iter() {
        if iface.ip_addr.contains(&remote_socket.ip())
            && iface.fingerprint(&remote_socket.ip()) == fingerprint
        {
            return Ok(iface.to_owned());
        };
    }
    Err(NetzworkApiError::UnknownNetInterfaceId(format!(
        "{:?} with fingerprint {:?}",
        remote_socket, fingerprint
    )))
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub struct ConnectivityMeasurementSample {
    timestamp: SystemTime,
    rtt: Duration,
    fingerprint: [u8; 32],
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub struct NetInterfaceConnectivityMeasurement {
    interface: NetInterfaceId,
    remote_socket: SocketAddr,
    samples: Vec<ConnectivityMeasurementSample>,
}

#[derive(Debug, PartialEq, Deserialize, Serialize, Clone)]
pub struct NetInterfaceInfo {
    pub interfaces: Vec<NetInterfaceId>,
    pub measurements: Vec<NetInterfaceConnectivityMeasurement>,
}
impl NetInterfaceInfo {
    pub fn new() -> NetInterfaceInfo {
        NetInterfaceInfo {
            interfaces: vec![],
            measurements: vec![],
        }
    }

    pub fn from_network_interfaces() -> Result<NetInterfaceInfo, local_ip_address::Error> {
        let network_interfaces = list_afinet_netifas()?;
        let mut ni_info = NetInterfaceInfo::new();
        for (if_name, ip_addr) in network_interfaces.iter() {
            let mut found_if = false;
            for ifs in ni_info.interfaces.iter_mut() {
                // the interface is known
                if ifs.if_name.eq(if_name) {
                    found_if = true;
                    // the address is not stored yet
                    if !ifs.ip_addr.contains(ip_addr) {
                        // store address
                        ifs.ip_addr.push(*ip_addr);
                    }
                };
            }
            if !found_if {
                // we had no interface matches
                ni_info.interfaces.push(NetInterfaceId {
                    machine_id: get_secure_machine_id(None).unwrap(),
                    if_name: if_name.clone(),
                    ip_addr: vec![*ip_addr],
                })
            }
        }
        Ok(ni_info)
    }
}
impl Default for NetInterfaceInfo {
    fn default() -> Self {
        Self::new()
    }
}