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
#![doc(html_logo_url = "https://raw.githubusercontent.com/musec/rusty-shark/master/artwork/wordmark.png")]
extern crate byteorder;
extern crate num;
extern crate promising_future;
use byteorder::ByteOrder;
pub use promising_future::Future;
use std::fmt;
pub trait Protocol {
fn short_name(&self) -> &'static str;
fn full_name(&self) -> &'static str;
fn dissect(&self, &[u8]) -> Result;
}
#[derive(Debug)]
pub enum Val {
Signed(i64),
Unsigned { value: u64, radix: u8 },
Enum(u64, &'static str),
String(String),
Address { bytes: Vec<u8>, encoded: String },
Subpacket(Vec<NamedValue>),
Bytes(Vec<u8>),
Error(Error),
Warning(Error),
}
impl Val {
pub fn base2<T>(x: T) -> Result<Val>
where T: num::ToPrimitive + std::fmt::Display
{
Val::unsigned(x, 2)
}
pub fn base10<T>(x: T) -> Result<Val>
where T: num::ToPrimitive + std::fmt::Display
{
Val::unsigned(x, 10)
}
pub fn base16<T>(x: T) -> Result<Val>
where T: num::ToPrimitive + std::fmt::Display
{
Val::unsigned(x, 16)
}
pub fn unsigned<T>(x: T, radix:u8) -> Result<Val>
where T: num::ToPrimitive + std::fmt::Display
{
x.to_u64()
.map(|value| Val::Unsigned { value: value, radix: radix })
.ok_or(Error::InvalidData(format!["Cannot convert {} to u64", x]))
}
pub fn str<Str>(s: Str) -> Val
where Str: Into<String>
{
Val::String(s.into())
}
pub fn pretty_print(self, indent_level:usize) -> String {
match self {
Val::Subpacket(values) => {
let indent:String = std::iter::repeat(" ").take(2 * indent_level).collect();
"\n".to_string() + &values.into_iter()
.map(|(k,v)| {
format!["{}{}: ", indent, k]
+ &match v {
Ok(val) => val.pretty_print(indent_level + 1),
Err(e) => format!["<< Error: {} >>", e],
}
})
.collect::<Vec<String>>()
.join("\n")
}
Val::Signed(i) => format!["{}", i],
Val::Unsigned { value, radix } => match radix {
2 => format!["{:b}", value],
8 => format!["{:o}", value],
10 => format!["{}", value],
16 => format!["{:x}", value],
_ => format!["{:?} (base {})", value, radix],
},
Val::Enum(i, s) => format!["{} ({})", i, s],
Val::String(ref s) => format!["{}", s],
Val::Address { ref encoded, .. } => format!["{}", encoded],
Val::Bytes(ref bytes) => {
let mut s = format!["{} B [", bytes.len()];
let to_print:&[u8] =
if bytes.len() < 16 { bytes }
else { &bytes[..16] }
;
for b in to_print {
s = s + &format![" {:02x}", b];
}
if bytes.len() > 16 {
s = s + " ...";
}
s + " ]"
},
Val::Warning(w) => format!["Warning: {}", w],
Val::Error(e) => format!["Error: {}", e],
}
}
}
#[derive(Clone, Debug)]
pub enum Error {
Underflow { expected: usize, have: usize, subject: String, },
InvalidData(String),
}
impl Error
{
fn underflow<T,S>(expected: usize, have: usize, subject: S) -> Result<T>
where S: Into<String>
{
Err(Error::Underflow { expected: expected, have: have, subject: subject.into() })
}
fn inval<T,S>(message: S) -> Result<T>
where S: Into<String>
{
Err(Error::InvalidData(message.into()))
}
}
impl fmt::Display for Error {
fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
match self {
&Error::Underflow { expected: expect, have, ref subject } =>
write![f, "underflow: {} expected {} B, have {}", subject, expect, have],
&Error::InvalidData(ref msg) => write![f, "invalid data: {}", msg],
}
}
}
pub type Result<T=Val> = ::std::result::Result<T,Error>;
pub type NamedValue = (&'static str,Result<Val>);
pub fn signed<T, E>(buffer: &[u8]) -> Result<T>
where T: num::FromPrimitive, E: ByteOrder
{
let len = buffer.len();
let conversion_error = "Failed to convert integer";
match len {
1 => T::from_u8(buffer[0]).ok_or(conversion_error),
2 => T::from_i16(E::read_i16(buffer)).ok_or(conversion_error),
4 => T::from_i32(E::read_i32(buffer)).ok_or(conversion_error),
8 => T::from_i64(E::read_i64(buffer)).ok_or(conversion_error),
_ => Err("Invalid integer size"),
}
.map_err(|s| format!["{} ({} B)", s, len])
.map_err(Error::InvalidData)
}
pub fn unsigned<T, E>(buffer: &[u8]) -> Result<T>
where T: num::FromPrimitive, E: ByteOrder
{
let len = buffer.len();
let conversion_error = "Failed to convert {} B integer";
match len {
1 => T::from_u8(buffer[0]).ok_or(conversion_error),
2 => T::from_u16(E::read_u16(buffer)).ok_or(conversion_error),
4 => T::from_u32(E::read_u32(buffer)).ok_or(conversion_error),
8 => T::from_u64(E::read_u64(buffer)).ok_or(conversion_error),
_ => Err("Invalid integer size: {}"),
}
.map_err(|s| format!["{} ({} B)", s, len])
.map_err(Error::InvalidData)
}
pub struct RawBytes {
short_name: &'static str,
full_name: &'static str,
}
impl RawBytes {
fn boxed(short_name: &'static str, full_name: &'static str) -> Box<RawBytes>
{
Box::new(RawBytes {
short_name: short_name,
full_name: full_name,
})
}
fn unknown_protocol(description: &'static str) -> Box<RawBytes> {
Box::new(RawBytes {
short_name: "UNKNOWN",
full_name: description,
})
}
}
impl Protocol for RawBytes {
fn short_name(&self) -> &'static str { self.short_name }
fn full_name(&self) -> &'static str { self.full_name }
fn dissect(&self, data: &[u8]) -> Result {
Ok(Val::Subpacket(
vec![("raw data", Ok(Val::Bytes(data.to_vec())))]
))
}
}
pub mod ethernet;
pub mod ip;