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
//! In-memory representation of a single Syslog message.

use std::string::String;
use std::collections::BTreeMap;
use std::convert::Into;
use std::ops;
use std::cmp::Ordering;
use std::str::FromStr;

#[cfg(feature="serde-serialize")]
use serde::{Serializer, Serialize};

#[allow(non_camel_case_types)]
pub type time_t = i64;
#[allow(non_camel_case_types)]
pub type pid_t = i32;
#[allow(non_camel_case_types)]
pub type msgid_t = String;

use severity;
use facility;
use parser;


#[derive(Clone,Debug,PartialEq,Eq)]
/// `ProcID`s are usually numeric PIDs; however, on some systems, they may be something else
pub enum ProcId {
    PID(pid_t),
    Name(String),
}


impl PartialOrd for ProcId {
    fn partial_cmp(&self, other: &ProcId) -> Option<Ordering> {
        match (self, other) {
            (&ProcId::PID(ref s_p), &ProcId::PID(ref o_p)) => Some(s_p.cmp(o_p)),
            (&ProcId::Name(ref s_n), &ProcId::Name(ref o_n)) => Some(s_n.cmp(o_n)),
            _ => None,
        }
    }
}


#[cfg(feature = "serde-serialize")]
impl Serialize for ProcId {
    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        match *self {
            ProcId::PID(ref p) => ser.serialize_i32(*p),
            ProcId::Name(ref n) => ser.serialize_str(n),
        }
    }
}

pub type SDIDType = String;
pub type SDParamIDType = String;
pub type SDParamValueType = String;


pub type StructuredDataElement = BTreeMap<SDParamIDType, SDParamValueType>;


#[derive(Clone,Debug,PartialEq,Eq)]
/// Container for the `StructuredData` component of a syslog message.
///
/// This is a map from `SD_ID` to pairs of `SD_ParamID`, `SD_ParamValue`
///
/// The spec does not forbid repeated keys. However, for convenience, we *do* forbid repeated keys.
/// That is to say, if you have a message like
///
/// [foo bar="baz" bar="bing"]
///
/// There's no way to retrieve the original "baz" mapping.
pub struct StructuredData {
    elements: BTreeMap<SDIDType, StructuredDataElement>,
}

impl ops::Deref for StructuredData {
    type Target = BTreeMap<SDIDType, StructuredDataElement>;
    fn deref(&self) -> &Self::Target {
        &self.elements
    }
}


#[cfg(feature = "serde-serialize")]
impl Serialize for StructuredData {
    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        self.elements.serialize(ser)
    }
}

impl StructuredData {
    pub fn new_empty() -> Self {
        StructuredData { elements: BTreeMap::new() }
    }

    /// Insert a new (sd_id, sd_param_id) -> sd_value mapping into the StructuredData
    pub fn insert_tuple<SI, SPI, SPV>(&mut self,
                                      sd_id: SI,
                                      sd_param_id: SPI,
                                      sd_param_value: SPV)
                                      -> ()
        where SI: Into<SDIDType>,
              SPI: Into<SDParamIDType>,
              SPV: Into<SDParamValueType>
    {
        let sub_map = self.elements.entry(sd_id.into()).or_insert_with(BTreeMap::new);
        sub_map.insert(sd_param_id.into(), sd_param_value.into());
    }

    /// Lookup by SDID, SDParamID pair
    pub fn find_tuple<'b>(&'b self,
                          sd_id: &str,
                          sd_param_id: &str)
                          -> Option<&'b SDParamValueType> {
        // TODO: use traits to make these based on the public types isntead of &str
        if let Some(sub_map) = self.elements.get(sd_id) {
            if let Some(value) = sub_map.get(sd_param_id) {
                Some(value)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Find all param/value mappings for a given SDID
    pub fn find_sdid<'b>(&'b self, sd_id: &str) -> Option<&'b StructuredDataElement> {
        self.elements.get(sd_id)
    }

    /// The number of distinct SD_IDs
    pub fn len(&self) -> usize {
        self.elements.len()
    }

    /// Whether or not this is empty
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }
}


#[cfg_attr(feature = "serde-serialize", derive(Serialize))]
#[derive(Clone,Debug,PartialEq,Eq)]
/// A RFC5424-protocol syslog message
pub struct SyslogMessage {
    pub severity: severity::SyslogSeverity,
    pub facility: facility::SyslogFacility,
    pub version: i32,
    pub timestamp: Option<time_t>,
    pub hostname: Option<String>,
    pub appname: Option<String>,
    pub procid: Option<ProcId>,
    pub msgid: Option<msgid_t>,
    pub sd: StructuredData,
    pub msg: String,
}


impl FromStr for SyslogMessage {
    type Err = parser::ParseErr;

    /// Parse a string into a `SyslogMessage`
    ///
    /// Just calls `parser::parse_message`
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parser::parse_message(s)
    }
}


#[cfg(test)]
mod tests {
    #[cfg(feature = "serde-serialize")]
    use serde_json;
    use super::StructuredData;
    use super::SyslogMessage;
    #[cfg(feature="serde-serialize")]
    use severity::SyslogSeverity::*;
    #[cfg(feature="serde-serialize")]
    use facility::SyslogFacility::*;

    #[test]
    fn test_structured_data_basic() {
        let mut s = StructuredData::new_empty();
        s.insert_tuple("foo", "bar", "baz");
        let v = s.find_tuple("foo", "bar").expect("should find foo/bar");
        assert_eq!(v, "baz");
        assert!(s.find_tuple("foo", "baz").is_none());
    }

    #[cfg(feature = "serde-serialize")]
    #[test]
    fn test_structured_data_serialization_serde() {
        let mut s = StructuredData::new_empty();
        s.insert_tuple("foo", "bar", "baz");
        s.insert_tuple("foo", "baz", "bar");
        s.insert_tuple("faa", "bar", "baz");
        let encoded = serde_json::to_string(&s).expect("Should encode to JSON");
        assert_eq!(encoded,
                   r#"{"faa":{"bar":"baz"},"foo":{"bar":"baz","baz":"bar"}}"#);
    }

    #[cfg(feature = "serde-serialize")]
    #[test]
    fn test_serialization_serde() {
        let m = SyslogMessage {
            severity: SEV_INFO,
            facility: LOG_KERN,
            version: 1,
            timestamp: None,
            hostname: None,
            appname: None,
            procid: None,
            msgid: None,
            sd: StructuredData::new_empty(),
            msg: String::from(""),
        };

        let encoded = serde_json::to_string(&m).expect("Should encode to JSON");
        // XXX: we don't have a guaranteed order, I don't think, so this might break with minor
        // version changes. *shrug*
        assert_eq!(encoded,
                   "{\"severity\":\"info\",\"facility\":\"kern\",\"version\":1,\"timestamp\":null,\"hostname\":null,\"appname\":null,\"procid\":null,\"msgid\":null,\"sd\":{},\"msg\":\"\"}");
    }

    #[test]
    fn test_deref_structureddata() {
        let mut s = StructuredData::new_empty();
        s.insert_tuple("foo", "bar", "baz");
        s.insert_tuple("foo", "baz", "bar");
        s.insert_tuple("faa", "bar", "baz");
        assert_eq!("baz", s.get("foo").and_then(|foo| foo.get("bar")).unwrap());
        assert_eq!("bar", s.get("foo").and_then(|foo| foo.get("baz")).unwrap());
        assert_eq!("baz", s.get("faa").and_then(|foo| foo.get("bar")).unwrap());
    }

    #[test]
    fn test_fromstr() {
        let msg = "<1>1 1985-04-12T23:20:50.52Z host - - - -".parse::<SyslogMessage>().expect("Should parse empty message");
        assert_eq!(msg.timestamp, Some(482196050));
    }
}