usb-descriptor-decoder 0.1.0

A no-std extensible USB Descriptor Decoder, support organize Descriptors as tree structure
Documentation
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
use core::ptr;

//
use alloc::vec::Vec;
use log::{error, trace};
use num_traits::FromPrimitive;

use crate::descriptors::USBStandardDescriptorTypes;

use super::{
    desc_device::StandardUSBDeviceClassCode,
    desc_interface::{Interface, InterfaceAssociation},
    desc_uvc::{
        uvc_interfaces::{
            UVCInterfaceSubclass, UVCStandardVideoInterfaceClass,
            UVCStandardVideoInterfaceProtocols,
        },
        UVCDescriptorTypes,
    },
    topological_desc::{
        TopologicalUSBDescriptorConfiguration, TopologicalUSBDescriptorDevice,
        TopologicalUSBDescriptorEndpoint, TopologicalUSBDescriptorFunction,
        TopologicalUSBDescriptorRoot,
    },
    USBDescriptor,
};

pub struct RawDescriptorParser {
    device: Vec<u8>,
    configs: Vec<(Vec<u8>, usize)>,
    state: ParserStateMachine,
    result: Option<TopologicalUSBDescriptorDevice>,
    others: Vec<USBDescriptor>,
    metadata: ParserMetaData,
    current: usize,
    current_len: usize,
}

#[derive(Debug)]
pub enum Error {
    UnrecognizedType(u8),
    ParseOrderError,
    EndOfDescriptors,
    NotReadyToParse,
    StateSwitch,
}

#[derive(PartialEq, Debug)]
enum ParserStateMachine {
    Device,
    NotReady,
    Config(usize),
    Inetrface(usize, u8),
    END,
}

#[derive(Clone, Debug)]
pub enum ParserMetaData {
    UVC(u8),
    HID,
    Unknown(ParserMetaDataUnknownSituation),
    NotDetermined,
}

#[derive(Clone, Debug)]
pub enum ParserMetaDataUnknownSituation {
    NoSpecial, //treat as standard usb device
    ReferIAC,
    ReferInterface,
}

impl ParserMetaData {
    //refer https://www.usb.org/defined-class-codes
    pub fn determine(class: u8, subclass: u8, protocol: u8) -> Self {
        trace!("parse metadata! determining");
        let result = {
            match (
                StandardUSBDeviceClassCode::from_u8(class),
                subclass,
                protocol,
            ) {
                (Some(StandardUSBDeviceClassCode::Miscellaneous), 0x02, 0x01) => {
                    return Self::Unknown(ParserMetaDataUnknownSituation::ReferIAC)
                }
                (Some(StandardUSBDeviceClassCode::HID), _, _) => return Self::HID,
                (Some(StandardUSBDeviceClassCode::ReferInterfaceDescriptor), _, _) => {
                    return Self::Unknown(ParserMetaDataUnknownSituation::ReferInterface)
                }
                _ => {}
            }

            if let (
                    Some(UVCStandardVideoInterfaceClass::CC_Video),
                    Some(UVCInterfaceSubclass::VIDEO_INTERFACE_COLLECTION),
                    Some(UVCStandardVideoInterfaceProtocols::PC_PROTOCOL_UNDEFINED),
                ) = (
                UVCStandardVideoInterfaceClass::from_u8(class),
                UVCInterfaceSubclass::from_u8(subclass),
                UVCStandardVideoInterfaceProtocols::from_u8(protocol),
            ) { return Self::UVC(0u8) }

            Self::Unknown(ParserMetaDataUnknownSituation::NoSpecial)
        };
        trace!("result is {:?}", result);

        result
    }
}

impl RawDescriptorParser {
    pub fn new(raw_device: Vec<u8>) -> Self {
        let len = raw_device.len();
        Self {
            device: raw_device,
            configs: Vec::new(),
            state: ParserStateMachine::Device,
            current: 0,
            current_len: len,
            result: None,
            others: Vec::new(),
            metadata: ParserMetaData::NotDetermined,
        }
    }

    pub fn num_of_configs(&self) -> usize {
        if self.state != ParserStateMachine::Device {
            self.result
                .as_ref()
                .map(|r| r.data.num_configurations as _)
                .unwrap()
        } else {
            panic!("do not call this method before device has been deserialized!");
        }
    }

    pub fn append_config(&mut self, raw_config: Vec<u8>) -> &mut Self {
        let len = raw_config.len();
        self.configs.push((raw_config, len));
        self
    }

    pub fn summarize(mut self) -> TopologicalUSBDescriptorRoot {
        while self.single_state_cycle() {}
        TopologicalUSBDescriptorRoot {
            device: self.result.unwrap(),
            others: self.others,
            metadata: self.metadata,
        }
    }

    //return false if reach end, otherwise true
    pub fn single_state_cycle(&mut self) -> bool {
        match &self.state {
            ParserStateMachine::Device => {
                self.result = self.parse_single_device_descriptor().ok();
                self.state = ParserStateMachine::NotReady;
                trace!("state change:{:?}", self.state);
                self.current = 0;
                self.current_len = 0;
                true
            }
            ParserStateMachine::Config(index) => {
                let num_of_configs = self.num_of_configs();
                let current_index = *index;
                if current_index >= num_of_configs {
                    self.state = ParserStateMachine::END;
                    trace!("state change:{:?}", self.state);
                    return false;
                }
                let topological_usbdescriptor_configuration = self.parse_current_config().unwrap();
                self.result
                    .as_mut()
                    .unwrap()
                    .child
                    .push(topological_usbdescriptor_configuration);
                self.state = ParserStateMachine::Config(current_index + 1);
                trace!("state change:{:?}", self.state);
                true
            }
            ParserStateMachine::END => panic!("should not call anymore while reaching end"),
            ParserStateMachine::NotReady => {
                if let Some(res) = &self.result
                    && self.configs.len() >= res.data.num_configurations as _
                {
                    self.state = ParserStateMachine::Config(0);
                    trace!("state change:{:?}", self.state);
                    self.current_len = self.configs[0].1;
                    true
                } else {
                    false
                }
            }
            _ => true,
        }
    }

    fn cut_raw_descriptor(&mut self) -> Result<Vec<u8>, Error> {
        match &self.state {
            ParserStateMachine::Device => {
                let len: usize = self.device[self.current].into();
                let v = self.device[self.current..(self.current + len)].to_vec();
                self.current += len;
                Ok(v)
            }
            ParserStateMachine::NotReady => Err(Error::NotReadyToParse),
            ParserStateMachine::Config(cfg_index) | ParserStateMachine::Inetrface(cfg_index, _) => {
                let len: usize = (self.configs[*cfg_index].0)[self.current].into();
                let v = (self.configs[*cfg_index].0)[self.current..(self.current + len)].to_vec();
                self.current += len;
                Ok(v)
            }
            ParserStateMachine::END => Err(Error::EndOfDescriptors),
        }
    }

    fn parse_single_device_descriptor(&mut self) -> Result<TopologicalUSBDescriptorDevice, Error> {
        trace!("parse single device desc!");
        if let USBDescriptor::Device(dev) = self.parse_any_descriptor()? {
            if let ParserMetaData::NotDetermined = self.metadata {
                    self.metadata =
                        ParserMetaData::determine(dev.class, dev.subclass, dev.protocol);
                    trace!("determined device type: {:?}", self.metadata)
                };
            Ok(TopologicalUSBDescriptorDevice {
                data: dev,
                child: Vec::new(),
            })
        } else {
            Err(Error::ParseOrderError)
        }
    }

    fn parse_current_config(&mut self) -> Result<TopologicalUSBDescriptorConfiguration, Error> {
        trace!("parse config desc!");
        let raw = self.cut_raw_descriptor()?;

        let mut cfg =
            USBDescriptor::from_slice(&raw, self.metadata.clone()).and_then(|converted| {
                if let USBDescriptor::Configuration(cfg) = converted {
                    Ok(TopologicalUSBDescriptorConfiguration {
                        data: cfg,
                        child: Vec::new(),
                    })
                } else {
                    Err(Error::ParseOrderError)
                }
            })?;

        trace!("max num of interface num:{}", cfg.data.num_interfaces());

        loop {
            match self.parse_function() {
                Ok(func) => {
                    cfg.child.push(func);
                }
                Err(Error::EndOfDescriptors) => {
                    break;
                }
                Err(Error::StateSwitch) => {
                    continue;
                }
                Err(other) => return Err(other),
            }
        }

        Ok(cfg)
    }

    fn parse_function(&mut self) -> Result<TopologicalUSBDescriptorFunction, Error> {
        trace!("parse function desc!");

        if let Some(desc_type) = self.peek_std_desc_type() {
            match desc_type {
                USBStandardDescriptorTypes::Interface => {
                    trace!(
                        "parse single interface desc! current state:{:?}",
                        self.state
                    );
                    // let collections = TopologicalUSBDescriptorFunction::Interface(vec![]);
                    let mut interfaces = Vec::new();

                    loop {
                        trace!("loop! state:{:?}", self.state);
                        match &self.state {
                            ParserStateMachine::Config(cfg_id) => {
                                self.state = ParserStateMachine::Inetrface(
                                    *cfg_id,
                                    self.peek_interface().unwrap().interface_number,
                                );
                                trace!("state change:{:?}", self.state);
                            }
                            ParserStateMachine::Inetrface(cfg_index, current_interface_id) => {
                                trace!("state interface!");
                                match &self.peek_interface() {
                                    Some(next)
                                        if (next.interface_number) == *current_interface_id =>
                                    {
                                        trace!("equal!");
                                        trace!("current:{:?}", current_interface_id);
                                        let interface = self.parse_interface().unwrap();
                                        trace!("got interface {:?}", interface);
                                        let additional = self.parse_other_descriptors_by_metadata();
                                        trace!("got additional data {:?}", additional);
                                        let endpoints = self.parse_endpoints();
                                        trace!("got endpoints {:?}", endpoints);
                                        interfaces.push((interface, additional, endpoints))
                                    }
                                    Some(next)
                                        if (next.interface_number) != *current_interface_id =>
                                    {
                                        trace!("not equal!");
                                        self.state = ParserStateMachine::Inetrface(
                                            *cfg_index,
                                            next.interface_number,
                                        );
                                        trace!("state change:{:?}", self.state);
                                        break;
                                    }
                                    None => {
                                        trace!("None! wtf?");
                                        break;
                                    }
                                    other => panic!("deserialize error! {:?}", other),
                                };
                            }
                            _ => panic!("impossible situation!"),
                        }
                    }

                    Ok(TopologicalUSBDescriptorFunction::Interface(interfaces))
                }
                USBStandardDescriptorTypes::InterfaceAssociation => {
                    trace!("parse InterfaceAssociation desc!");
                    let interface_association = self.parse_interface_association().unwrap();
                    // match &self.state {
                    //     ParserStateMachine::Config(cfg_id) => {
                    //         self.state = ParserStateMachine::Inetrface(cfg_id.clone(), 0);
                    //         trace!("state change:{:?}", self.state);
                    //     }
                    //     other => panic!("error on switching state! {:?}", other),
                    // }
                    let mut interfaces = Vec::new();
                    for i in 0..interface_association.interface_count {
                        trace!("parsing {i}th interface!");
                        //agreement:there is always some interfaces that match the cound behind association
                        interfaces.push(self.parse_function()?);
                    }
                    Ok(TopologicalUSBDescriptorFunction::InterfaceAssociation((
                        interface_association,
                        interfaces,
                    )))
                }
                anyother => {
                    trace!("unrecognize type!");
                    Err(Error::UnrecognizedType(anyother as u8))
                }
            }
        } else {
            Err(Error::EndOfDescriptors)
        }
    }

    fn parse_any_descriptor(&mut self) -> Result<USBDescriptor, Error> {
        trace!(
            "parse any desc at current{}! type:{:?}",
            self.current,
            self.peek_std_desc_type()
        );
        let raw = self.cut_raw_descriptor()?;
        USBDescriptor::from_slice(&raw, self.metadata.clone())
    }

    fn parse_interface_association(&mut self) -> Result<InterfaceAssociation, Error> {
        match self.parse_any_descriptor()? {
            USBDescriptor::InterfaceAssociation(interface_association) => {
                if let ParserMetaData::Unknown(ParserMetaDataUnknownSituation::ReferIAC) =
                    self.metadata
                {
                    self.metadata = ParserMetaData::determine(
                        interface_association.function_class,
                        interface_association.function_subclass,
                        interface_association.function_protocol,
                    );
                    trace!("determined currend device type: {:?}", self.metadata);
                }

                Ok(interface_association)
            }
            _ => Err(Error::ParseOrderError),
        }
    }

    fn peek_std_desc_type(&self) -> Option<USBStandardDescriptorTypes> {
        match self.state {
            ParserStateMachine::Device => {
                let peeked =
                    USBStandardDescriptorTypes::from_u8(self.device[self.current + 1]);
                trace!("peeked type:{:?}", peeked);
                peeked
            }
            ParserStateMachine::Config(index) | ParserStateMachine::Inetrface(index, _) => {
                let peeked = USBStandardDescriptorTypes::from_u8(
                    self.configs[index].0[self.current + 1],
                );
                trace!("peeked std type:{:?}", peeked);
                peeked
            }
            _ => panic!("impossible!"),
        }
    }

    //while call this methods, parser state machine always at "config" state
    fn peek_uvc_desc_type(&mut self) -> Option<UVCDescriptorTypes> {
        trace!("peek uvc type!");
        match self.state {
            ParserStateMachine::Config(index) | ParserStateMachine::Inetrface(index, _) => {
                UVCDescriptorTypes::from_u8(self.configs[index].0[self.current + 1])
            }
            _ => None,
        }
    }

    fn peek_interface(&self) -> Option<Interface> {
        match self.state {
            ParserStateMachine::Config(index) | ParserStateMachine::Inetrface(index, _) => {
                trace!(
                    "peek at {},value:{}",
                    self.current,
                    self.configs[index].0[self.current]
                );

                if self.peek_std_desc_type() == Some(USBStandardDescriptorTypes::Interface) {
                    let len = self.configs[index].0[self.current] as usize;
                    let from = self.current;
                    let to = from + len - 1;
                    trace!("len{len},from{from},to{to}");
                    let raw = (&self.configs[index].0[from..to]) as *const [u8];
                    let interface = unsafe { ptr::read_volatile(raw as *const Interface) }; //do not cast, in current version rust still had value cache issue
                    trace!("got:{:?}", interface);

                    return Some(interface);
                }
            }
            _ => {}
        }
        None
    }

    fn parse_interface(&mut self) -> Result<Interface, Error> {
        trace!("parse interfaces,metadata:{:?}", self.metadata);
        match self.parse_any_descriptor()? {
            USBDescriptor::Interface(int) => {
                match &self.metadata {
                    ParserMetaData::UVC(_) => {
                        self.metadata = ParserMetaData::UVC(int.interface_subclass);
                    }
                    ParserMetaData::Unknown(ParserMetaDataUnknownSituation::ReferInterface) => {
                        self.metadata = ParserMetaData::determine(
                            int.interface_class,
                            int.interface_subclass,
                            int.interface_protocol,
                        );

                        trace!("determined current device type:{:?}", self.metadata);
                    }
                    _ => {}
                }
                Ok(int)
            }
            _ => Err(Error::ParseOrderError),
        }
    }

    fn parse_other_descriptors_by_metadata(&mut self) -> Vec<USBDescriptor> {
        trace!(
            "parse additional data for interface with metadata:{:?}",
            self.metadata
        );
        let mut vec = Vec::new();
        loop {
            match self.peek_std_desc_type() {
                Some(
                    USBStandardDescriptorTypes::Endpoint
                    | USBStandardDescriptorTypes::Interface
                    | USBStandardDescriptorTypes::InterfaceAssociation,
                ) => break,
                Some(_) | None => {
                    trace!("parse misc desc!");
                    vec.push(
                        self.parse_any_descriptor()
                            .inspect_err(|e| error!("usb descriptor parse failed:{:?}", e))
                            .unwrap(),
                    );
                    continue;
                }
            }
        }
        vec
    }

    fn parse_endpoints(&mut self) -> Vec<TopologicalUSBDescriptorEndpoint> {
        trace!("parse enedpoints, metadata:{:?}", self.metadata);
        let mut endpoints = Vec::new();

        loop {
            if let Some(USBStandardDescriptorTypes::Endpoint) = self.peek_std_desc_type() {
                if let USBDescriptor::Endpoint(endpoint) = self.parse_any_descriptor().unwrap() {
                    trace!("parsed endpoint:{:?}", endpoint);
                    endpoints.push(TopologicalUSBDescriptorEndpoint::Standard(endpoint))
                }
                continue;
            }

            if let ParserMetaData::UVC(_) = self.metadata {
                if let Some(UVCDescriptorTypes::UVCClassSpecVideoControlInterruptEndpoint) =
                    self.peek_uvc_desc_type()
                {
                    trace!("uvc interrupt endpoint!");
                    match self.parse_any_descriptor().unwrap() {
                        USBDescriptor::UVCClassSpecVideoControlInterruptEndpoint(ep) => {
                            trace!("got {:?}", ep);
                            endpoints.push(TopologicalUSBDescriptorEndpoint::UNVVideoControlInterruptEndpoint(ep));
                        }
                        _ => {
                            panic!("impossible!");
                        }
                    }
                    continue;
                } else {
                    trace!("not uvc data!");
                }
            }

            break;
        }
        endpoints
    }
}