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
//! Implements the SSDP layer of the `UPnP` standard.
//!
//! This module deals with interface discovery as well as HTTP extensions for
//! accomodating SSDP.

use std::fmt::{Display, Error, Formatter};
use std::result::Result;
use std::borrow::Cow;

/// Separator character for a `FieldMap` and it's value.
pub const PAIR_SEPARATOR: char = ':';

/// Prefix for the "upnp" field key.
const UPNP_PREFIX: &'static str = "upnp";
/// Prefix for the "uuid" field key.
const UUID_PREFIX: &'static str = "uuid";
/// Prefix for the "usn" field key.
const URN_PREFIX: &'static str = "urn";

/// Enumerates key value pairs embedded within SSDP header fields.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum FieldMap {
    /// The "upnp" key with its associated value.
    UPnP(String),
    /// The "uuid" key with its associated value.
    UUID(String),
    /// The "urn" key with its associated value.
    URN(String),
    /// An undefined key, the key and it's value are returned.
    Unknown(String, String),
}

impl FieldMap {
    /// Breaks a field up into a single key and single value which are
    /// separated by a colon and neither of which are empty.
    ///
    /// Separation will occur at the first colon encountered.
    pub fn new<'a, S: Into<Cow<'a, str>>>(value: S) -> Option<Self> {
        FieldMap::parse_bytes(value.into().as_bytes())
    }

    /// Breaks a field up into a single key and single value which are
    /// separated by a colon and neither of which are empty.
    ///
    /// Separation will occur at the first colon encountered.
    pub fn parse_bytes(field: &[u8]) -> Option<Self> {
        let split_index = match field.iter().position(|&b| b == PAIR_SEPARATOR as u8) {
            Some(n) => n,
            None => return None,
        };
        let (key, mut value) = field.split_at(split_index);

        // Ignore Separator Byte
        value = &value[1..];

        // Check Empty Byte Slices
        if key.len() == 0 || value.len() == 0 {
            return None;
        }

        let key = String::from_utf8_lossy(key);
        let value = String::from_utf8_lossy(value).into_owned();

        if matches_uuid_key(key.as_ref()) {
            Some(FieldMap::UUID(value))
        } else if matches_urn_key(key.as_ref()) {
            Some(FieldMap::URN(value))
        } else if matches_upnp_key(key.as_ref()) {
            Some(FieldMap::UPnP(value))
        } else {
            Some(FieldMap::Unknown(key.into_owned(), value))
        }
    }

    pub fn upnp<'a, S: Into<Cow<'a, str>>>(value: S) -> Self {
        FieldMap::UPnP(value.into().into_owned())
    }

    pub fn uuid<'a, S: Into<Cow<'a, str>>>(value: S) -> Self {
        FieldMap::UUID(value.into().into_owned())
    }

    pub fn urn<'a, S: Into<Cow<'a, str>>>(value: S) -> Self {
        FieldMap::URN(value.into().into_owned())
    }

    pub fn unknown<'a, S: Into<Cow<'a, str>>, S2: Into<Cow<'a, str>>>(key: S, value: S2) -> Self {
        FieldMap::Unknown(key.into().into_owned(), value.into().into_owned())
    }
}

impl Display for FieldMap {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        let value = match *self {
            FieldMap::UPnP(ref v) => {
                try!(f.write_str(UPNP_PREFIX));
                v
            }
            FieldMap::UUID(ref v) => {
                try!(f.write_str(UUID_PREFIX));
                v
            }
            FieldMap::URN(ref v) => {
                try!(f.write_str(URN_PREFIX));
                v
            }
            FieldMap::Unknown(ref k, ref v) => {
                try!(Display::fmt(k, f));
                v
            }
        };
        try!(f.write_fmt(format_args!("{}", PAIR_SEPARATOR)));
        try!(Display::fmt(value, f));
        Ok(())
    }
}

/// Returns the header field value if the key matches the uuid key, else returns None.
fn matches_uuid_key(key: &str) -> bool {
    UUID_PREFIX == key
}

/// Returns the header field value if the key matches the urn key, else returns None.
fn matches_urn_key(key: &str) -> bool {
    URN_PREFIX == key
}

/// Returns the header field value if the key matches the upnp key, else returns None.
fn matches_upnp_key(key: &str) -> bool {
    UPNP_PREFIX == key
}

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

    #[test]
    fn positive_non_utf8() {
        let uuid_pair = FieldMap::parse_bytes(&b"uuid:some_value_\x80"[..]).unwrap();
        assert_eq!(uuid_pair, FieldMap::uuid(String::from_utf8_lossy(&b"some_value_\x80".to_vec())));
    }

    #[test]
    fn positive_unknown_non_utf8() {
        let unknown_pair = FieldMap::parse_bytes(&b"some_key\x80:some_value_\x80"[..]).unwrap();
        assert_eq!(unknown_pair,
                   FieldMap::unknown(String::from_utf8_lossy(&b"some_key\x80".to_vec()),
                                     String::from_utf8_lossy(&b"some_value_\x80".to_vec())));
    }

    #[test]
    fn positive_upnp() {
        let upnp_pair = FieldMap::new("upnp:some_value").unwrap();
        assert_eq!(upnp_pair, FieldMap::upnp("some_value"));
    }

    #[test]
    fn positive_uuid() {
        let uuid_pair = FieldMap::new("uuid:some_value").unwrap();
        assert_eq!(uuid_pair, FieldMap::uuid("some_value"));
    }

    #[test]
    fn positive_urn() {
        let urn_pair = FieldMap::new("urn:some_value").unwrap();
        assert_eq!(urn_pair, FieldMap::urn("some_value"));
    }

    #[test]
    fn positive_unknown() {
        let unknown_pair = FieldMap::new("some_key:some_value").unwrap();
        assert_eq!(unknown_pair, FieldMap::unknown("some_key", "some_value"));
    }

    #[test]
    #[should_panic]
    fn negative_no_colon() {
        FieldMap::new("upnpsome_value").unwrap();
    }
}