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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! RADIUS Dictionary implementation


use std::fs::File;
use std::io::{self, BufRead};

use super::error::RadiusError;

#[derive(Debug, PartialEq)]
/// Represents a list of supported data types
/// as defined in RFC 2865 & RFC 8044
pub enum SupportedAttributeTypes {
    /// Rust's String; RFC 8044 calls this "text" - UTF-8 text
    AsciiString,
    /// Rusts's [u8]; RFC 8044 calls this "string" (FreeRADIUS calls this "octets") - binary data as a sequence of undistinguished octets
    ByteString,
    /// Rust's u32
    Integer,
    /// Rust's u64
    Integer64,
    /// Rust's u32; RFC 8044 calls this "time"
    Date,
    /// Rust's \[u8;4\]
    IPv4Addr,
    /// Rust's \[u8;5\]
    IPv4Prefix,
    /// Rust's \[u8;16\]
    IPv6Addr,
    /// Rust's \[u8;18\]
    IPv6Prefix,
    /// Rust's \[u8;8\]; RFC 8044 calls this "ifid"
    InterfaceId,
    /// Rust's u32
    Enum,
    /// Rust's [u8]
    Tlv,
    /// Rust's [u8]; RFC 8044 defines this as vendor-specific data
    Vsa,
    /// Rust's [u8]; RFC 8044 defines this as Extended-Vendor-Specific Attribute (FreeRADIUS
    /// accepts VSA instead of EVS data type)
    Evs,
    /// Rust's [u8]; Doesn't look like a type on its own, but rather an extension to some data types (in FreeRADIUS this is a flag)
    /// usually string/octets
    Concat,
    /// Rust's [u8]; Doesn't look like a type on its own, but rather an extension to some data types (in FreeRADIUS this is a flag)
    Extended,
    /// Rust's [u8]; Doesn't look like a type on its own, but rather an extension to some data types (in FreeRADIUS this is a flag)
    LongExtended
}


#[derive(Debug, PartialEq)]
/// Represents an ATTRIBUTE from RADIUS dictionary file
pub struct DictionaryAttribute {
    /*
     * |--------|   name  | code | code type |
     * ATTRIBUTE User-Name   1      string
     */
    name:        String,
    vendor_name: String,
    code:        u8,
    code_type:   Option<SupportedAttributeTypes>
}

impl DictionaryAttribute {
    /// Return name of the Attribute
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Return code of the Attribute
    pub fn code(&self) -> u8 {
        self.code
    }

    /// Return code_type of the Attribute
    pub fn code_type(&self) -> &Option<SupportedAttributeTypes> {
        &self.code_type
    }
}


#[derive(Debug, PartialEq)]
/// Represents a VALUE from RADIUS dictionary file
pub struct DictionaryValue {
    attribute_name: String,
    value_name:     String,
    vendor_name:    String,
    value:          String
}

impl DictionaryValue {
    /// Return name of the Value
    pub fn name(&self) -> &str {
        &self.value_name
    }

    /// Return attribute_name of the Value
    pub fn attribute_name(&self) -> &str {
        &self.attribute_name
    }

    /// Return value of the Value
    pub fn value(&self) -> &str {
        &self.value
    }
}


#[derive(Debug, PartialEq)]
/// Represents a VENDOR from RADIUS dictionary file
pub struct DictionaryVendor {
    name: String,
    id:   u8
}


const COMMENT_PREFIX: &str = "#";

#[derive(Debug, Default, PartialEq)]
/// Represents RADIUS dictionary
pub struct Dictionary {
    attributes: Vec<DictionaryAttribute>,
    values:     Vec<DictionaryValue>,
    vendors:    Vec<DictionaryVendor>
}

#[allow(unused)]
impl Dictionary {
    /// Creates Dictionary from a string
    pub fn from_str(dictionary_str: &str) -> Result<Dictionary, RadiusError> {
        todo!()
    }

    /// Creates Dictionary from a RADIUS dictionary file
    pub fn from_file(file_path: &str) -> Result<Dictionary, RadiusError> {
        let mut attributes:  Vec<DictionaryAttribute> = Vec::new();
        let mut values:      Vec<DictionaryValue>     = Vec::new();
        let mut vendors:     Vec<DictionaryVendor>    = Vec::new();

        match parse_file(file_path, &mut attributes, &mut values, &mut vendors) {
            Ok(())     => Ok(Dictionary { attributes, values, vendors }),
            Err(error) => Err(error)
        }
    }

    /// Adds a dictionary file to existing Dictionary
    ///
    /// Processes attributes, values and vendors from supplied dictionary file
    /// and adds them to existing attributes, values and vendors
    pub fn add_file(&mut self, file_path: &str) -> Result<(), RadiusError> {
        parse_file(file_path, &mut self.attributes, &mut self.values, &mut self.vendors)
    }

    /// Returns parsed DictionaryAttributes
    pub fn attributes(&self) -> &[DictionaryAttribute] {
        &self.attributes
    }

    /// Returns parsed DictionaryValues
    pub fn values(&self) -> &[DictionaryValue] {
        &self.values
    }

    /// Returns parsed DictionaryVendors
    pub fn vendors(&self) -> &[DictionaryVendor] {
        &self.vendors
    }
}

fn assign_attribute_type(code_type: &str) -> Option<SupportedAttributeTypes> {
    match code_type {
        "text"          => Some(SupportedAttributeTypes::AsciiString),
        "string"        => Some(SupportedAttributeTypes::ByteString),
        "integer"       => Some(SupportedAttributeTypes::Integer),
        "integer64"     => Some(SupportedAttributeTypes::Integer64),
        "time"          => Some(SupportedAttributeTypes::Date),
        "ipv4addr"      => Some(SupportedAttributeTypes::IPv4Addr),
        "ipv4prefix"    => Some(SupportedAttributeTypes::IPv4Prefix),
        "ipv6addr"      => Some(SupportedAttributeTypes::IPv6Addr),
        "ipv6prefix"    => Some(SupportedAttributeTypes::IPv6Prefix),
        "ifid"          => Some(SupportedAttributeTypes::InterfaceId),
        "enum"          => Some(SupportedAttributeTypes::Enum),
        "tlv"           => Some(SupportedAttributeTypes::Tlv),
        "vsa"           => Some(SupportedAttributeTypes::Vsa),
        "evs"           => Some(SupportedAttributeTypes::Evs),
        "concat"        => Some(SupportedAttributeTypes::Concat),
        "extended"      => Some(SupportedAttributeTypes::Extended),
        "long-extended" => Some(SupportedAttributeTypes::LongExtended),
        _               => None
    }
}

fn parse_file(file_path: &str, attributes: &mut Vec<DictionaryAttribute>, values: &mut Vec<DictionaryValue>, vendors: &mut Vec<DictionaryVendor>) -> Result<(), RadiusError> {
    let mut vendor_name: String = String::new();

    let reader = io::BufReader::new(File::open(file_path).map_err(|error| RadiusError::MalformedDictionaryError { error })?);
    let lines  = reader.lines()
        .filter_map(Result::ok)
        .filter(|line| !line.is_empty())
        .filter(|line| !line.contains(&COMMENT_PREFIX));

    for line in lines {
        let parsed_line: Vec<&str> = line.split_whitespace().filter(|&item| !item.is_empty()).collect();
        match parsed_line[0] {
            "ATTRIBUTE"    => parse_attribute(parsed_line, &vendor_name, attributes),
            "VALUE"        => parse_value(parsed_line, &vendor_name, values),
            "VENDOR"       => parse_vendor(parsed_line, vendors),
            "BEGIN-VENDOR" => { vendor_name.insert_str(0, parsed_line[1]) },
            "END-VENDOR"   => { vendor_name.clear() },
            _              => continue
        }
    };

    Ok(())
}

fn parse_attribute(parsed_line: Vec<&str>, vendor_name: &str, attributes: &mut Vec<DictionaryAttribute>) {
    if let Ok(code) = parsed_line[2].parse::<u8>() {
        attributes.push(DictionaryAttribute {
            name:        parsed_line[1].to_string(),
            vendor_name: vendor_name.to_string(),
            code,
            code_type:   assign_attribute_type(parsed_line[3])
        });
    }
}

fn parse_value(parsed_line: Vec<&str>, vendor_name: &str, values: &mut Vec<DictionaryValue>) {
    values.push(DictionaryValue {
        attribute_name: parsed_line[1].to_string(),
        value_name:     parsed_line[2].to_string(),
        vendor_name:    vendor_name.to_string(),
        value:          parsed_line[3].to_string()
    })
}

fn parse_vendor(parsed_line: Vec<&str>, vendors: &mut Vec<DictionaryVendor>) {
    if let Ok(id) = parsed_line[2].parse::<u8>() {
        vendors.push(DictionaryVendor {
            name: parsed_line[1].to_string(),
            id,
        })
    }
}


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

    #[test]
    fn test_from_file() {
        let dictionary_path = "./dict_examples/test_dictionary_dict";

        let dict = Dictionary::from_file(dictionary_path).unwrap();

        let mut attributes: Vec<DictionaryAttribute> = Vec::new();
        attributes.push(DictionaryAttribute {
            name:        "User-Name".to_string(),
            vendor_name: "".to_string(),
            code:        1,
            code_type:   Some(SupportedAttributeTypes::AsciiString)
        });
        attributes.push(DictionaryAttribute {
            name:        "NAS-IP-Address".to_string(),
            vendor_name: "".to_string(),
            code:        4,
            code_type:   Some(SupportedAttributeTypes::IPv4Addr)
        });
        attributes.push(DictionaryAttribute {
            name:        "NAS-Port-Id".to_string(),
            vendor_name: "".to_string(),
            code:        5,
            code_type:   Some(SupportedAttributeTypes::Integer)
        });
        attributes.push(DictionaryAttribute {
            name:        "Framed-Protocol".to_string(),
            vendor_name: "".to_string(),
            code:        7,
            code_type:   Some(SupportedAttributeTypes::Integer)
        });
        attributes.push(DictionaryAttribute {
            name:        "Chargeable-User-Identity".to_string(),
            vendor_name: "".to_string(),
            code:        89,
            code_type:   Some(SupportedAttributeTypes::ByteString)
        });
        attributes.push(DictionaryAttribute {
            name:        "Delegated-IPv6-Prefix".to_string(),
            vendor_name: "".to_string(),
            code:        123,
            code_type:   Some(SupportedAttributeTypes::IPv6Prefix)
        });
        attributes.push(DictionaryAttribute {
            name:        "MIP6-Feature-Vector".to_string(),
            vendor_name: "".to_string(),
            code:        124,
            code_type:   Some(SupportedAttributeTypes::Integer64)
        });
        attributes.push(DictionaryAttribute {
            name:        "Mobile-Node-Identifier".to_string(),
            vendor_name: "".to_string(),
            code:        145,
            code_type:   Some(SupportedAttributeTypes::ByteString)
        });
        attributes.push(DictionaryAttribute {
            name:        "PMIP6-Home-Interface-ID".to_string(),
            vendor_name: "".to_string(),
            code:        153,
            code_type:   Some(SupportedAttributeTypes::InterfaceId)
        });
        attributes.push(DictionaryAttribute {
            name:        "PMIP6-Home-IPv4-HoA".to_string(),
            vendor_name: "".to_string(),
            code:        155,
            code_type:   Some(SupportedAttributeTypes::IPv4Prefix)
        });
        attributes.push(DictionaryAttribute {
            name:        "Somevendor-Name".to_string(),
            vendor_name: "Somevendor".to_string(),
            code:        1,
            code_type:   Some(SupportedAttributeTypes::AsciiString)
        });
        attributes.push(DictionaryAttribute {
            name:        "Somevendor-Number".to_string(),
            vendor_name: "Somevendor".to_string(),
            code:        2,
            code_type:   Some(SupportedAttributeTypes::Integer)
        });
        attributes.push(DictionaryAttribute {
            name:        "Class".to_string(),
            vendor_name: "".to_string(),
            code:        25,
            code_type:   Some(SupportedAttributeTypes::ByteString)
        });

        let mut values: Vec<DictionaryValue> = Vec::new();
        values.push(DictionaryValue {
            attribute_name: "Framed-Protocol".to_string(),
            value_name:     "PPP".to_string(),
            vendor_name:    "".to_string(),
            value:          "1".to_string()
        });
        values.push(DictionaryValue {
            attribute_name: "Somevendor-Number".to_string(),
            value_name:     "Two".to_string(),
            vendor_name:    "Somevendor".to_string(),
            value:          "2".to_string()
        });

        let mut vendors: Vec<DictionaryVendor> = Vec::new();
        vendors.push(DictionaryVendor {
            name: "Somevendor".to_string(),
            id:   10,
        });

        let expected_dict = Dictionary { attributes, values, vendors };
        assert_eq!(dict, expected_dict)
    }

    #[test]
    fn test_add_file() {
        let empty_dictionary_path = "./dict_examples/empty_test_dictionary_dict";
        let dictionary_path       = "./dict_examples/test_dictionary_dict";

        let mut dict = Dictionary::from_file(empty_dictionary_path).unwrap();
        dict.add_file(dictionary_path).unwrap();

        let mut attributes: Vec<DictionaryAttribute> = Vec::new();
        attributes.push(DictionaryAttribute {
            name:        "User-Name".to_string(),
            vendor_name: "".to_string(),
            code:        1,
            code_type:   Some(SupportedAttributeTypes::AsciiString)
        });
        attributes.push(DictionaryAttribute {
            name:        "NAS-IP-Address".to_string(),
            vendor_name: "".to_string(),
            code:        4,
            code_type:   Some(SupportedAttributeTypes::IPv4Addr)
        });
        attributes.push(DictionaryAttribute {
            name:        "NAS-Port-Id".to_string(),
            vendor_name: "".to_string(),
            code:        5,
            code_type:   Some(SupportedAttributeTypes::Integer)
        });
        attributes.push(DictionaryAttribute {
            name:        "Framed-Protocol".to_string(),
            vendor_name: "".to_string(),
            code:        7,
            code_type:   Some(SupportedAttributeTypes::Integer)
        });
        attributes.push(DictionaryAttribute {
            name:        "Chargeable-User-Identity".to_string(),
            vendor_name: "".to_string(),
            code:        89,
            code_type:   Some(SupportedAttributeTypes::ByteString)
        });
        attributes.push(DictionaryAttribute {
            name:        "Delegated-IPv6-Prefix".to_string(),
            vendor_name: "".to_string(),
            code:        123,
            code_type:   Some(SupportedAttributeTypes::IPv6Prefix)
        });
        attributes.push(DictionaryAttribute {
            name:        "MIP6-Feature-Vector".to_string(),
            vendor_name: "".to_string(),
            code:        124,
            code_type:   Some(SupportedAttributeTypes::Integer64)
        });
        attributes.push(DictionaryAttribute {
            name:        "Mobile-Node-Identifier".to_string(),
            vendor_name: "".to_string(),
            code:        145,
            code_type:   Some(SupportedAttributeTypes::ByteString)
        });
        attributes.push(DictionaryAttribute {
            name:        "PMIP6-Home-Interface-ID".to_string(),
            vendor_name: "".to_string(),
            code:        153,
            code_type:   Some(SupportedAttributeTypes::InterfaceId)
        });
        attributes.push(DictionaryAttribute {
            name:        "PMIP6-Home-IPv4-HoA".to_string(),
            vendor_name: "".to_string(),
            code:        155,
            code_type:   Some(SupportedAttributeTypes::IPv4Prefix)
        });
        attributes.push(DictionaryAttribute {
            name:        "Somevendor-Name".to_string(),
            vendor_name: "Somevendor".to_string(),
            code:        1,
            code_type:   Some(SupportedAttributeTypes::AsciiString)
        });
        attributes.push(DictionaryAttribute {
            name:        "Somevendor-Number".to_string(),
            vendor_name: "Somevendor".to_string(),
            code:        2,
            code_type:   Some(SupportedAttributeTypes::Integer)
        });
        attributes.push(DictionaryAttribute {
            name:        "Class".to_string(),
            vendor_name: "".to_string(),
            code:        25,
            code_type:   Some(SupportedAttributeTypes::ByteString)
        });

        let mut values: Vec<DictionaryValue> = Vec::new();
        values.push(DictionaryValue {
            attribute_name: "Framed-Protocol".to_string(),
            value_name:     "PPP".to_string(),
            vendor_name:    "".to_string(),
            value:          "1".to_string()
        });
        values.push(DictionaryValue {
            attribute_name: "Somevendor-Number".to_string(),
            value_name:     "Two".to_string(),
            vendor_name:    "Somevendor".to_string(),
            value:          "2".to_string()
        });

        let mut vendors: Vec<DictionaryVendor> = Vec::new();
        vendors.push(DictionaryVendor {
            name: "Somevendor".to_string(),
            id:   10,
        });

        let expected_dict = Dictionary { attributes, values, vendors };
        assert_eq!(dict, expected_dict)
    }
}