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
use std::convert::From;
use std::fmt;
use std::result::Result as StdResult;

use serde::de::{Deserialize, Deserializer, Error as SerdeError, Visitor};
use serde::ser::{Serialize, Serializer};

use crate::boxes::ByteBox;
use crate::errors::SaltyError;
use crate::tasks::TaskMessage;
use crate::Event;

/// The role of a peer.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Role {
    /// A SaltyRTC compliant client who wants to establish a WebRTC or ORTC
    /// peer-to-peer connection to a responder.
    Initiator,
    /// A SaltyRTC compliant client who wants to establish a WebRTC or ORTC
    /// peer-to-peer connection to an initiator.
    Responder,
}

impl Role {
    /// Return true if this role is the initiator.
    pub fn is_initiator(self) -> bool {
        self == Role::Initiator
    }

    /// Return true if this role is the responder.
    pub fn is_responder(self) -> bool {
        self == Role::Responder
    }
}

impl fmt::Display for Role {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Role::Initiator => write!(f, "Initiator"),
            Role::Responder => write!(f, "Responder"),
        }
    }
}

/// A peer identity.
///
/// On the network level, this is encoded as a single unsigned byte.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Identity {
    /// The server has the identity `0x00`.
    Server,
    /// The initiator has the identity `0x01`.
    Initiator,
    /// The responder has an identity in the range `0x02-0xff`.
    Responder(u8),
}

impl From<Address> for Identity {
    fn from(val: Address) -> Self {
        match val.0 {
            0x00 => Identity::Server,
            0x01 => Identity::Initiator,
            addr => Identity::Responder(addr),
        }
    }
}

impl fmt::Display for Identity {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Identity::Initiator => write!(f, "initiator"),
            Identity::Responder(id) => write!(f, "responder {:#04x}", id),
            Identity::Server => write!(f, "server"),
        }
    }
}

/// A client identity.
///
/// This is like the [`Identity`](enum.identity.html), but the `Server` value
/// is not allowed. Additionally, the `Unknown` value can be used for identities
/// that aren't initialized yet.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) enum ClientIdentity {
    /// An unknown identity is initialized to `0x00`.
    Unknown,
    /// The initiator has the identity `0x01`.
    Initiator,
    /// The responder has an identity in the range `0x02-0xff`.
    Responder(u8),
}

impl fmt::Display for ClientIdentity {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ClientIdentity::Unknown => write!(f, "unknown"),
            ClientIdentity::Initiator => write!(f, "initiator"),
            ClientIdentity::Responder(ref val) => write!(f, "responder {:#04x}", val),
        }
    }
}

/// An address.
///
/// This is an unsigned byte like the [`Identity`](enum.Identity.html),
/// but without any semantic information attached.
#[derive(PartialEq, Eq, Copy, Clone, Hash)]
pub(crate) struct Address(pub(crate) u8);

impl Address {
    /// Return whether this address is a valid server address.
    pub(crate) fn is_server(self) -> bool {
        self.0 == 0x00
    }

    /// Return whether this address is a valid unknown address.
    pub(crate) fn is_unknown(self) -> bool {
        self.0 == 0x00
    }

    /// Return whether this address is the initiator address.
    pub(crate) fn is_initiator(self) -> bool {
        self.0 == 0x01
    }

    /// Return whether this address is in the responder range.
    pub(crate) fn is_responder(self) -> bool {
        self.0 >= 0x02
    }
}

impl fmt::Display for Address {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:#04x}", self.0)
    }
}

impl fmt::Debug for Address {
    // Impl this ourselves to avoid too much spacing in alternative debug format
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Address({:#04x})", self.0)
    }
}

impl From<ClientIdentity> for Address {
    /// Convert a [`ClientIdentity`](enum.ClientIdentity.html) into the
    /// corresponding address.
    ///
    /// Panics if a `Responder` with an out-of-range value is encountered.
    fn from(val: ClientIdentity) -> Self {
        Address(match val {
            ClientIdentity::Unknown => 0x00,
            ClientIdentity::Initiator => 0x01,
            ClientIdentity::Responder(address) => {
                assert!(address > 0x01, "address <= 0x01");
                address
            }
        })
    }
}

impl From<Identity> for Address {
    /// Convert an [`Identity`](enum.Identity.html) into the
    /// corresponding address.
    ///
    /// Panics if a `Responder` with an out-of-range value is encountered.
    fn from(val: Identity) -> Self {
        Address(match val {
            Identity::Server => 0x00,
            Identity::Initiator => 0x01,
            Identity::Responder(address) => {
                assert!(address > 0x01, "address <= 0x01");
                address
            }
        })
    }
}

impl From<u8> for Address {
    /// Convert an u8 into the corresponding address.
    fn from(val: u8) -> Self {
        Address(val)
    }
}

/// Waiting for https://github.com/3Hren/msgpack-rust/issues/129
impl Serialize for Address {
    fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u8(self.0)
    }
}

struct AddressVisitor;

impl<'de> Visitor<'de> for AddressVisitor {
    type Value = Address;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("an address byte")
    }

    fn visit_u8<E>(self, v: u8) -> StdResult<Self::Value, E>
    where
        E: SerdeError,
    {
        Ok(Address(v))
    }
}

/// Waiting for https://github.com/3Hren/msgpack-rust/issues/129
impl<'de> Deserialize<'de> for Address {
    fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_u8(AddressVisitor)
    }
}

/// An enum returned when an incoming message is handled.
///
/// It can contain different actions that should be done to finish handling the
/// message.
#[must_use]
#[derive(Debug, PartialEq)]
pub(crate) enum HandleAction {
    /// Send the specified message through the websocket.
    Reply(ByteBox),
    /// Raise an error during the handshake.
    /// This is only needed when having to handle an error condition with a
    /// message (e.g. the 'close' message on NoSharedTask).
    HandshakeError(SaltyError),
    /// The server and peer handshake are done.
    HandshakeDone,
    /// An event happened.
    Event(Event),
    /// A task message was received and decoded.
    TaskMessage(TaskMessage),
}

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

    #[test]
    fn client_identity_into_address() {
        let unknown = ClientIdentity::Unknown;
        let initiator = ClientIdentity::Initiator;
        let responder = ClientIdentity::Responder(0x13);

        assert_eq!(Address::from(unknown), Address(0x00));
        assert_eq!(Address::from(initiator), Address(0x01));
        assert_eq!(Address::from(responder), Address(0x13));
    }

    /// Converting an invalid `Responder` into an `Address` should panic.
    #[test]
    #[should_panic(expected = "address <= 0x01")]
    fn client_identity_invalid_responder_into_address() {
        let responder_invalid = ClientIdentity::Responder(0x01);
        let _: Address = responder_invalid.into();
    }

    #[test]
    fn address_display() {
        assert_eq!(format!("{}", Address(0)), "0x00");
        assert_eq!(format!("{}", Address(3)), "0x03");
        assert_eq!(format!("{}", Address(255)), "0xff");
    }

    #[test]
    fn client_identity_display() {
        let unknown = ClientIdentity::Unknown;
        let initiator = ClientIdentity::Initiator;
        let responder = ClientIdentity::Responder(10);

        assert_eq!(format!("{}", unknown), "unknown");
        assert_eq!(format!("{}", initiator), "initiator");
        assert_eq!(format!("{}", responder), "responder 0x0a");
    }
}