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
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

pub use self::answer::DnsAnswer;
pub use self::query::DnsQuery;

use slice;
use u16;
use string::String;
use vec::Vec;

mod answer;
mod query;

#[unstable(feature = "n16", issue="0")]
#[allow(non_camel_case_types)]
#[derive(Copy, Clone, Debug, Default)]
#[repr(packed)]
pub struct n16 {
    inner: u16
}

impl n16 {
    #[unstable(feature = "n16", issue="0")]
    pub fn as_bytes(&self) -> &[u8] {
        unsafe { slice::from_raw_parts((&self.inner as *const u16) as *const u8, 2) }
    }

    #[unstable(feature = "n16", issue="0")]
    pub fn from_bytes(bytes: &[u8]) -> Self {
        n16 {
            inner: unsafe { slice::from_raw_parts(bytes.as_ptr() as *const u16, bytes.len()/2)[0] }
        }
    }
}

#[unstable(feature = "n16", issue="0")]
impl From<u16> for n16 {
    fn from(value: u16) -> Self {
        n16 {
            inner: value.to_be()
        }
    }
}

#[unstable(feature = "n16", issue="0")]
impl From<n16> for u16 {
    fn from(value: n16) -> Self {
        u16::from_be(value.inner)
    }
}

#[derive(Clone, Debug)]
pub struct Dns {
    pub transaction_id: u16,
    pub flags: u16,
    pub queries: Vec<DnsQuery>,
    pub answers: Vec<DnsAnswer>
}

impl Dns {
    pub fn compile(&self) -> Vec<u8> {
        let mut data = Vec::new();

        macro_rules! push_u8 {
            ($value:expr) => {
                data.push($value);
            };
        };

        macro_rules! push_n16 {
            ($value:expr) => {
                data.extend_from_slice(n16::from($value).as_bytes());
            };
        };

        push_n16!(self.transaction_id);
        push_n16!(self.flags);
        push_n16!(self.queries.len() as u16);
        push_n16!(self.answers.len() as u16);
        push_n16!(0);
        push_n16!(0);

        for query in self.queries.iter() {
            for part in query.name.split('.') {
                push_u8!(part.len() as u8);
                data.extend_from_slice(part.as_bytes());
            }
            push_u8!(0);
            push_n16!(query.q_type);
            push_n16!(query.q_class);
        }

        data
    }

    pub fn parse(data: &[u8]) -> Result<Self, String> {
        let name_ind = 0b11000000;
        let mut i = 0;

        macro_rules! pop_u8 {
            () => {
                {
                    i += 1;
                    if i > data.len() {
                        return Err(format!("{}: {}: pop_u8", file!(), line!()));
                    }
                    data[i - 1]
                }
            };
        };

        macro_rules! pop_n16 {
            () => {
                {
                    i += 2;
                    if i > data.len() {
                        return Err(format!("{}: {}: pop_n16", file!(), line!()));
                    }
                    u16::from(n16::from_bytes(&data[i - 2 .. i]))
                }
            };
        };

        macro_rules! pop_data {
            () => {
                {
                    let mut data = Vec::new();

                    let data_len = pop_n16!();
                    for _data_i in 0..data_len {
                        data.push(pop_u8!());
                    }

                    data
                }
            };
        };

        macro_rules! pop_name {
            () => {
                {
                    let mut name = String::new();
                    let old_i = i;

                    loop {
                        let name_len = pop_u8!();
                        if name_len & name_ind == name_ind {
                            i -= 1;
                            i = (pop_n16!() - ((name_ind as u16) << 8)) as usize;
                            continue;
                        }
                        if name_len == 0 {
                            break;
                        }
                        if ! name.is_empty() {
                            name.push('.');
                        }
                        for _name_i in 0..name_len {
                            name.push(pop_u8!() as char);
                        }
                    }

                    if i <= old_i {
                        i = old_i + 2;
                    }

                    name
                }
            };
        };

        let transaction_id = pop_n16!();
        let flags = pop_n16!();
        let queries_len = pop_n16!();
        let answers_len = pop_n16!();
        pop_n16!();
        pop_n16!();

        let mut queries = Vec::new();
        for _query_i in 0..queries_len {
            queries.push(DnsQuery {
                name: pop_name!(),
                q_type: pop_n16!(),
                q_class: pop_n16!()
            });
        }

        let mut answers = Vec::new();
        for _answer_i in 0..answers_len {
            answers.push(DnsAnswer {
                name: pop_name!(),
                a_type: pop_n16!(),
                a_class: pop_n16!(),
                ttl_a: pop_n16!(),
                ttl_b: pop_n16!(),
                data: pop_data!()
            });
        }

        Ok(Dns {
            transaction_id,
            flags,
            queries,
            answers,
        })
    }
}