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
//! BER encoding support.
use bytes::BytesMut;
use byteorder::{BigEndian, WriteBytesExt};
use common::{TagClass, TagStructure};
use structure::{StructureTag, PL};

use std::io::{self, Write};

/// BER-encode a tag structure into the provided buffer.
pub fn encode_into(buf: &mut BytesMut, tag: StructureTag) -> io::Result<()> {
    let mut tag_vec = Vec::new();
    encode_inner(&mut tag_vec, tag)?;
    buf.extend(tag_vec);
    Ok(())
}

fn encode_inner(buf: &mut Vec<u8>, tag: StructureTag) -> io::Result<()> {
    let structure = match tag.payload {
        PL::P(_) => TagStructure::Primitive,
        PL::C(_) => TagStructure::Constructed,
    };

    write_type(buf, tag.class, structure, tag.id);
    match tag.payload {
        PL::P(v) => {
            write_length(buf, v.len());
            buf.extend(v);
        },
        PL::C(tags) => {
            let mut tmp = Vec::new();
            for tag in tags {
                try!(encode_inner(&mut tmp, tag));
            }
            write_length(buf, tmp.len());
            buf.extend(tmp);
        }
    };

    Ok(())
}

fn write_type(w: &mut Write, class: TagClass, structure: TagStructure, id: u64) {
    let extended_tag: Option<Vec<u8>>;

    let type_byte = {
        // First two bits: Class
        (class as u8) << 6 |
        // Bit 6: Primitive/Constructed
        (structure as u8) << 5 |
        // Bit 5-1: Tag Number
        if id > 30
        {
            let mut tagbytes: Vec<u8> = Vec::new();

            let mut tag = id;
            while tag > 0
            {
                // Only take the 7 lower bits.
                let byte = (tag & 0x7F) as u8;

                tag >>= 7;

                tagbytes.push(byte);
            }

            extended_tag = Some(tagbytes);

            // This means we need to set the 5 tag bits to 11111, so 31 or 0x1F
            0x1F
        }
        else
        {
            extended_tag = None;
            id as u8
        }
    }; // let type_byte

    let _ = w.write_u8(type_byte);

    if let Some(mut ext_bytes) = extended_tag
    {
        for _ in 0..ext_bytes.len()-1
        {
            let mut byte = ext_bytes.pop().unwrap();

            // Set the first bit
            byte |= 0x80;

            let _ = w.write_u8(byte);
        }

        let byte = ext_bytes.pop().unwrap();
        let _ = w.write_u8(byte);
    }
}

// Yes I know you could overflow the length in theory. But, do you have 2^64 bytes of memory?
fn write_length(w: &mut Write, length: usize) {
    // Short form
    if length < 128
    {
        let _ = w.write_u8(length as u8);
    }
    // Long form
    else
    {
        let mut count = 0u8;
        let mut len = length;
        while {count += 1; len >>= 8; len > 0 }{}


        let _ = w.write_u8(count | 0x80);
        let _ = w.write_uint::<BigEndian>(length as u64, count as usize);
    }
}

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

    use std::string;

    use std::default::Default;

    use byteorder::{BigEndian, WriteBytesExt};

    use structures::*;
    use common::TagClass::*;

    #[test]
    fn encode_simple_tag() {
        let tag = Tag::Integer(Integer {
            inner: 1616, 
            .. Default::default()
        });

        let mut buf = Vec::<u8>::new();
        super::encode_into(&mut buf, tag.into_structure());

        assert_eq!(buf, vec![0x2, 0x2, 0x06, 0x50]);
    }

    #[test]
    fn encode_constructed_tag()
    {
        let tag = Tag::Sequence(Sequence {
            inner: vec![
                Tag::OctetString(OctetString {
                    inner: String::from("Hello World!").into_bytes(),
                    .. Default::default()
                })
            ],
            .. Default::default()
        });

        let mut buf = Vec::<u8>::new();
        super::encode_into(&mut buf, tag.into_structure());

        assert_eq!(buf, vec![48,14,4,12,72,101,108,108,111,32,87,111,114,108,100,33]);
    }

    #[test]
    fn complex_tag()
    {
        let tag = Tag::Sequence(Sequence {
            inner: vec![
                Tag::Integer(Integer {
                    inner: 1,
                    .. Default::default()
                }),
                Tag::Sequence(Sequence {
                    id: 0,
                    class: Application,
                    inner: vec![
                           Tag::Integer(Integer {
                               inner: 3,
                                .. Default::default()
                           }),
                           Tag::OctetString(OctetString {
                               inner: String::from("cn=root,dc=plabs").into_bytes(),
                                .. Default::default()
                           }),
                           Tag::OctetString(OctetString {
                               id: 0,
                               class: Context,
                               inner: String::from("asdf").into_bytes(),
                           })
                    ]
                })
            ],
            .. Default::default()
        });

        let expected = vec![
            0x30, 0x20,
                0x02, 0x01, 0x01,
                0x60, 0x1B,
                    0x02, 0x01, 0x03,
                    0x04, 0x10, 0x63, 0x6e, 0x3d, 0x72, 0x6f, 0x6f, 0x74, 0x2c, 0x64, 0x63, 0x3d, 0x70, 0x6c, 0x61, 0x62, 0x73,
                    0x80, 0x04, 0x61, 0x73, 0x64, 0x66
        ];

        let mut buf = Vec::<u8>::new();
        super::encode_into(&mut buf, tag.into_structure());

        assert_eq!(buf, expected);
    }
}