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
use super::bundle::*;
use serde::de::{SeqAccess, Visitor};
use serde::ser::{SerializeSeq, Serializer};
use serde::{de, Deserialize, Deserializer, Serialize};
use std::convert::From;
use std::fmt;
use url::Url;

/******************************
 *
 * Endpoint ID
 *
 ******************************/

pub const ENDPOINT_URI_SCHEME_DTN: u8 = 1;
pub const ENDPOINT_URI_SCHEME_IPN: u8 = 2;

pub const DTN_NONE: EndpointID = EndpointID::DtnNone(ENDPOINT_URI_SCHEME_DTN, 0);

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct IpnAddress(pub u32, pub u32);

/// # Examples
///
/// ```
/// use bp7::eid::*;
///
/// let cbor_eid = [130, 1, 106, 110, 111, 100, 101, 49, 47, 116, 101, 115, 116];
/// let deserialized: EndpointID = serde_cbor::from_slice(&cbor_eid).unwrap();
/// assert_eq!(deserialized, EndpointID::Dtn(ENDPOINT_URI_SCHEME_DTN, "node1/test".to_string()))
///
/// ```
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum EndpointID {
    Dtn(u8, String), // Order of probable occurence, serde tries decoding in untagged enums in this order
    DtnNone(u8, u8),
    Ipn(u8, IpnAddress),
}
/*
// manual implementation not really faster
impl Serialize for EndpointID {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(2))?;
        match self {
            EndpointID::Dtn(eid_type, name) => {
                seq.serialize_element(&eid_type)?;
                seq.serialize_element(&name)?;
            }
            EndpointID::DtnNone(eid_type, name) => {
                seq.serialize_element(&eid_type)?;
                seq.serialize_element(&name)?;
            }
            EndpointID::Ipn(eid_type, ipnaddr) => {
                seq.serialize_element(&eid_type)?;
                seq.serialize_element(&ipnaddr)?;
            }
        }

        seq.end()
    }
}*/
impl<'de> Deserialize<'de> for EndpointID {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct EndpointIDVisitor;

        impl<'de> Visitor<'de> for EndpointIDVisitor {
            type Value = EndpointID;

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

            fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
            where
                V: SeqAccess<'de>,
            {
                let eid_type: u8 = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
                if eid_type == ENDPOINT_URI_SCHEME_DTN {
                    // TODO: rewrite to check following typ, currently if not string return dtn:none
                    let name: String = seq.next_element().unwrap_or_default().unwrap_or_default();
                    if name == "" {
                        Ok(EndpointID::with_dtn_none())
                    } else {
                        Ok(EndpointID::Dtn(eid_type, name))
                    }
                } else if eid_type == ENDPOINT_URI_SCHEME_IPN {
                    let ipnaddr: IpnAddress = seq
                        .next_element()?
                        .ok_or_else(|| de::Error::invalid_length(1, &self))?;
                    Ok(EndpointID::with_ipn(ipnaddr))
                } else {
                    Err(de::Error::invalid_value(
                        de::Unexpected::Unsigned(eid_type.into()),
                        &self,
                    ))
                }
            }
        }

        deserializer.deserialize_any(EndpointIDVisitor)
    }
}

impl Default for EndpointID {
    fn default() -> Self {
        EndpointID::DtnNone(ENDPOINT_URI_SCHEME_DTN, 0)
    }
}
impl EndpointID {
    pub fn new() -> EndpointID {
        Default::default()
    }
    /// # Examples
    ///
    /// ```
    /// use bp7::eid::*;
    ///
    /// assert_eq!(EndpointID::with_dtn("node1".to_string()),EndpointID::Dtn(ENDPOINT_URI_SCHEME_DTN,"node1".to_string()));
    ///
    /// assert_eq!(EndpointID::with_dtn("node1/endpoint1".to_string()),EndpointID::Dtn(ENDPOINT_URI_SCHEME_DTN,"node1/endpoint1".to_string()));
    /// ```
    pub fn with_dtn(addr: String) -> EndpointID {
        EndpointID::Dtn(ENDPOINT_URI_SCHEME_DTN, addr)
    }
    /// # Examples
    ///
    /// ```
    /// use bp7::eid::*;
    ///
    /// assert_eq!(EndpointID::with_dtn_none(), EndpointID::DtnNone(ENDPOINT_URI_SCHEME_DTN,0));
    /// let encoded_eid = serde_cbor::to_vec(&EndpointID::with_dtn_none()).expect("Error serializing packet as cbor.");
    /// println!("{:02x?}", &encoded_eid);
    /// assert_eq!(EndpointID::with_dtn_none(), serde_cbor::from_slice(&encoded_eid).expect("Decoding packet failed"));
    /// ```
    pub fn with_dtn_none() -> EndpointID {
        EndpointID::DtnNone(ENDPOINT_URI_SCHEME_DTN, 0)
    }
    /// # Examples
    ///
    /// ```
    /// use bp7::eid::*;
    ///
    /// assert_eq!(EndpointID::with_ipn( IpnAddress(23, 42) ), EndpointID::Ipn(ENDPOINT_URI_SCHEME_IPN, IpnAddress(23, 42)) );
    ///
    /// let ipn_eid = EndpointID::with_ipn(IpnAddress(23, 42));
    /// let encoded_eid = serde_cbor::to_vec(&ipn_eid).expect("Error serializing packet as cbor.");
    /// println!("{:02x?}", &encoded_eid);
    /// assert_eq!(ipn_eid, serde_cbor::from_slice(&encoded_eid).expect("Decoding packet failed"));
    /// ```
    pub fn with_ipn(addr: IpnAddress) -> EndpointID {
        EndpointID::Ipn(ENDPOINT_URI_SCHEME_IPN, addr)
    }

    pub fn get_scheme(&self) -> String {
        match self {
            EndpointID::DtnNone(_, _) => "dtn".to_string(),
            EndpointID::Dtn(_, _) => "dtn".to_string(),
            EndpointID::Ipn(_, _) => "ipn".to_string(),
        }
    }
    pub fn get_scheme_specific_part_dtn(&self) -> Option<String> {
        match self {
            EndpointID::Dtn(_, ssp) => Some(ssp.to_string()),
            _ => None,
        }
    }
    pub fn to_string(&self) -> String {
        let result = format!(
            "{}://{}",
            self.get_scheme(),
            self.get_scheme_specific_part_dtn()
                .unwrap_or_else(|| "none".to_string())
        );
        result
    }
}

impl fmt::Display for EndpointID {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.to_string())
    }
}

impl EndpointID {
    /// # Examples
    ///
    /// ```
    /// use bp7::eid::*;
    ///
    /// let eid : EndpointID = "ipn://0.0".to_string().into();
    /// assert_eq!(eid.node_part(),Some("0".to_string()));
    ///
    /// let eid : EndpointID = "dtn://node1/incoming".to_string().into();
    /// assert_eq!(eid.node_part(),Some("node1".to_string()));
    ///
    /// let eid : EndpointID = "dtn://node1".to_string().into();
    /// assert_eq!(eid.node_part(),Some("node1".to_string()));
    /// ```
    pub fn node_part(&self) -> Option<String> {
        match self {
            EndpointID::DtnNone(_, _) => None,
            EndpointID::Dtn(_, eid) => {
                let nodeid: Vec<&str> = eid.split('/').collect();
                Some(nodeid[0].to_string())
            }
            EndpointID::Ipn(_, addr) => Some(addr.0.to_string()),
        }
    }
    /// # Examples
    ///
    /// ```
    /// use bp7::eid::*;
    ///
    /// let eid : EndpointID = "ipn://0.0".to_string().into();
    /// assert_eq!(eid.is_node_id(), true);
    ///
    /// let eid : EndpointID = "ipn://0.1".to_string().into();
    /// assert_eq!(eid.is_node_id(), false);
    ///
    /// let eid : EndpointID = "dtn://node1/incoming".to_string().into();
    /// assert_eq!(eid.is_node_id(), false);
    ///
    /// let eid : EndpointID = "dtn://node1".to_string().into();
    /// assert_eq!(eid.is_node_id(), true);
    /// ```
    pub fn is_node_id(&self) -> bool {
        match self {
            EndpointID::DtnNone(_, _) => false,
            EndpointID::Dtn(_, eid) => self.node_part() == Some(eid.to_string()),
            EndpointID::Ipn(_, addr) => addr.1 == 0,
        }
    }

    /// # Examples
    ///
    /// ```
    /// use bp7::eid::*;
    ///
    /// let eid = EndpointID::DtnNone(1, 0);
    /// assert_eq!(eid.validation_error().is_none(), true); // should not fail
    ///
    /// let eid = EndpointID::DtnNone(0, 0);
    /// assert_eq!(eid.validation_error().is_some(), true); // should fail   
    /// let eid = EndpointID::DtnNone(1, 1);
    /// assert_eq!(eid.validation_error().is_some(), true); // should fail   
    ///
    /// let eid = EndpointID::Ipn(2, IpnAddress(23, 42));
    /// assert_eq!(eid.validation_error().is_none(), true); // should not fail
    /// let eid = EndpointID::Ipn(1, IpnAddress(23, 42));
    /// assert_eq!(eid.validation_error().is_some(), true); // should fail   
    /// let eid = EndpointID::Ipn(2, IpnAddress(0, 0));
    /// assert_eq!(eid.validation_error().is_some(), true); // should fail   
    /// ```
    pub fn validation_error(&self) -> Option<Bp7Error> {
        match self {
            EndpointID::Dtn(_, _) => None, // TODO: Implement validation for dtn scheme
            EndpointID::Ipn(code, addr) => {
                if *code != ENDPOINT_URI_SCHEME_IPN {
                    Some(Bp7Error::EIDError(
                        "Wrong URI scheme code for IPN".to_string(),
                    ))
                } else if addr.0 < 1 || addr.1 < 1 {
                    Some(Bp7Error::EIDError(
                        "IPN's node and service number must be >= 1".to_string(),
                    ))
                } else {
                    None
                }
            }
            EndpointID::DtnNone(code, addr) => {
                if *code != ENDPOINT_URI_SCHEME_DTN {
                    Some(Bp7Error::EIDError(
                        "Wrong URI scheme code for DTN".to_string(),
                    ))
                } else if *addr != 0 {
                    Some(Bp7Error::EIDError(
                        "dtn none must have uint(0) set as address".to_string(),
                    ))
                } else {
                    None
                }
            }
        }
    }
}

/// Load EndpointID from URL string.
/// Support for IPN and dtn schemes.
///
/// # Examples
///
/// ```
/// use bp7::eid::*;
///
/// let eid = EndpointID::from("dtn://none".to_string());
/// assert_eq!(eid, EndpointID::DtnNone(ENDPOINT_URI_SCHEME_DTN, 0));
///
/// let eid = EndpointID::from("dtn:none".to_string());
/// assert_eq!(eid, EndpointID::DtnNone(ENDPOINT_URI_SCHEME_DTN, 0));
///
/// let eid = EndpointID::from("dtn://node1/endpoint1".to_string());
/// assert_eq!(eid, EndpointID::Dtn(ENDPOINT_URI_SCHEME_DTN, "node1/endpoint1".to_string()));
///
/// let eid = EndpointID::from("dtn:node1/endpoint1".to_string());
/// assert_eq!(eid, EndpointID::Dtn(ENDPOINT_URI_SCHEME_DTN, "node1/endpoint1".to_string()));
///   
/// ```
///
/// This should panic:
///
/// ```should_panic
/// use bp7::eid::*;
///
/// let eid = EndpointID::from("node1".to_string());
/// ```
impl From<String> for EndpointID {
    fn from(item: String) -> Self {
        let item = if item.contains("://") {
            item
        } else {
            item.replace(":", "://")
        };
        let u = Url::parse(&item).expect("EndpointID url parsing error");
        let host = u.host_str().expect("EndpointID host parsing error");

        match u.scheme() {
            "dtn" => {
                if host == "none" {
                    return <EndpointID>::with_dtn_none();
                }
                let mut host = format!("{}{}", host, u.path());
                if host.ends_with('/') {
                    host.truncate(host.len() - 1);
                }
                EndpointID::with_dtn(host)
            }
            "ipn" => {
                let fields: Vec<&str> = host.split('.').collect();
                if fields.len() != 2 {
                    panic!("wrong number of fields in IPN address");
                }
                let p1: u32 = fields[0].parse().unwrap();
                let p2: u32 = fields[1].parse().unwrap();

                EndpointID::with_ipn(IpnAddress(p1, p2))
            }
            _ => <EndpointID>::with_dtn_none(),
        }
    }
}

impl From<&str> for EndpointID {
    fn from(item: &str) -> Self {
        EndpointID::from(String::from(item))
    }
}