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
//! Rust bindings to Fundamentum portforwarding protocol.
//! A library that provides a Rust representation of the basic types, interfaces and
//! other components required to define and interact with portforwarding
//! defined by [`fundamentum-portforwarding-proto`][repo-proto].
//!
//! [repo-proto]: https://bitbucket.org/amotus/fundamentum-portforwarding-proto

pub mod errors;

/// The rust bindings generated from the protobuf files under `./proto/`.
///
/// Mirrors original protobuf top level 'com' namespace.
pub mod com {
    /// Mirrors original protobuf namespace at 'com.fundamentum'.
    ///
    /// Exposes Fundamentum related protobuf symbols.
    pub mod fundamentum {
        /// Mirrors original protobuf namespace at 'com.fundamentum.portforwarding'.
        ///
        /// Exposes Fundamentum Portforwarding related protobuf symbols.
        pub mod portforwarding {
            /// Mirrors original protobuf namespace at 'com.fundamentum.portforwarding.v1'.
            ///
            /// Exposes Fundamentum Portforwarding related protobuf symbols as of version 1
            /// or the services.
            pub mod v1 {
                use crate::Version;

                include!(concat!(
                    env!("OUT_DIR"),
                    "/com.fundamentum.portforwarding.v1.rs"
                ));

                /// Get current version
                pub fn get_version() -> Version {
                    Version::V1
                }
            }
        }
    }
}

use std::{fmt::Display, str::FromStr};

use com::fundamentum::portforwarding::v1;
use derive_new::new;
pub use errors::Error;
use serde::Serialize;
use uuid::Uuid;

#[derive(PartialEq, Eq, Debug, new, Clone, Copy)]
pub struct TargetPort(pub u32);

impl Display for TargetPort {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(PartialEq, Eq, Debug, new, Serialize, Clone, Copy)]
pub struct ProxyPort(pub u32);

impl Display for ProxyPort {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Protocol version
#[derive(Debug)]
pub enum Version {
    V1,
}

impl FromStr for Version {
    type Err = errors::Error;

    fn from_str(input: &str) -> Result<Version, Self::Err> {
        match input {
            "V1" => Ok(Version::V1),
            _ => Err(errors::Error::InvalidVersion),
        }
    }
}

impl Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// Layer that represent portforwarding device message with good typing
pub struct PortforwardingMsg {
    pub session_id: Uuid,
    pub target_port: TargetPort,
    pub operation: Operation,
}

/// Represent each possible operation
#[derive(PartialEq, Eq)]
pub enum Operation {
    TransferData(Vec<u8>),
    Error(i32, String),
    Status(Status),
    OpenConnection,
    CloseConnection,
}

/// Represent each possible status
#[derive(PartialEq, Eq)]
pub enum Status {
    ConnectionEstablished,
}

impl From<PortforwardingMsg> for v1::PortforwardingMsg {
    /// Convert `PortforwardingMsgLayer` to protobuf generated struct
    fn from(val: PortforwardingMsg) -> Self {
        v1::PortforwardingMsg {
            session_id: val.session_id.to_string(),
            target_port: val.target_port.0,
            operation: match &val.operation {
                Operation::TransferData(payload) => Some(
                    v1::portforwarding_msg::Operation::TransferData(v1::TransferData {
                        payload: payload.to_vec(),
                    }),
                ),
                Operation::Error(code, message) => {
                    Some(v1::portforwarding_msg::Operation::Error(v1::Error {
                        code: *code,
                        message: message.to_string(),
                    }))
                }
                Operation::Status(status) => {
                    Some(v1::portforwarding_msg::Operation::Status(match status {
                        Status::ConnectionEstablished => v1::Status::ConnectionEstablished.into(),
                    }))
                }
                Operation::OpenConnection => Some(
                    v1::portforwarding_msg::Operation::OpenConnection(v1::OpenConnection {}),
                ),
                Operation::CloseConnection => Some(
                    v1::portforwarding_msg::Operation::CloseConnection(v1::CloseConnection {}),
                ),
            },
        }
    }
}

impl TryFrom<v1::PortforwardingMsg> for PortforwardingMsg {
    type Error = errors::Error;

    /// Convert protobuf struct into our portforwarding message layer
    fn try_from(value: v1::PortforwardingMsg) -> Result<Self, Self::Error> {
        Ok(PortforwardingMsg {
            session_id: Uuid::parse_str(&value.session_id)?,
            target_port: TargetPort(value.target_port),
            operation: match value.operation {
                Some(v1::portforwarding_msg::Operation::OpenConnection(_)) => {
                    Operation::OpenConnection
                }
                Some(v1::portforwarding_msg::Operation::CloseConnection(_)) => {
                    Operation::CloseConnection
                }
                Some(v1::portforwarding_msg::Operation::TransferData(transfer_data)) => {
                    Operation::TransferData(transfer_data.payload)
                }
                Some(v1::portforwarding_msg::Operation::Error(error)) => {
                    Operation::Error(error.code, error.message)
                }
                Some(v1::portforwarding_msg::Operation::Status(status)) => match status {
                    1 => Operation::Status(Status::ConnectionEstablished),
                    _ => return Err(Error::InvalidStatus),
                },
                None => return Err(Error::NoOperationFound),
            },
        })
    }
}

impl PortforwardingMsg {
    /// Close a connection payload
    #[must_use]
    pub const fn new_close_connection(port: TargetPort, id: Uuid) -> Self {
        Self {
            session_id: id,
            target_port: port,
            operation: Operation::CloseConnection,
        }
    }

    /// generate open connection message
    #[must_use]
    pub const fn new_open_connection(port: TargetPort, id: Uuid) -> Self {
        Self {
            session_id: id,
            target_port: port,
            operation: Operation::OpenConnection,
        }
    }

    /// generate transfer data message
    #[must_use]
    pub const fn new_transfer_data(port: TargetPort, id: Uuid, payload: Vec<u8>) -> Self {
        Self {
            session_id: id,
            target_port: port,
            operation: Operation::TransferData(payload),
        }
    }

    /// generate transfer data message
    #[must_use]
    pub const fn new_connection_established(port: TargetPort, id: Uuid) -> Self {
        Self {
            session_id: id,
            target_port: port,
            operation: Operation::Status(Status::ConnectionEstablished),
        }
    }
}