usbip 0.8.0

A library to run USB/IP server
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
//! USB/IP protocol structs
//!
//! This module contains declarations of all structs used in the USB/IP protocol,
//! as well as functions to serialize and deserialize them to/from byte arrays,
//! and functions to send and receive them over a socket.
//!
//! They are based on the [Linux kernel documentation](https://docs.kernel.org/usb/usbip_protocol.html).

use log::trace;
use std::io::Result;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::UsbDevice;

/// USB/IP protocol version
///
/// This is currently the only supported version of USB/IP
/// for this library.
pub const USBIP_VERSION: u16 = 0x0111;

/// Command code: Retrieve the list of exported USB devices
pub const OP_REQ_DEVLIST: u16 = 0x8005;
/// Command code: import a remote USB device
pub const OP_REQ_IMPORT: u16 = 0x8003;
/// Reply code: The list of exported USB devices
pub const OP_REP_DEVLIST: u16 = 0x0005;
/// Reply code: Reply to import
pub const OP_REP_IMPORT: u16 = 0x0003;

/// Command code: Submit an URB
pub const USBIP_CMD_SUBMIT: u16 = 0x0001;
/// Command code: Unlink an URB
pub const USBIP_CMD_UNLINK: u16 = 0x0002;
/// Reply code: Reply for submitting an URB
pub const USBIP_RET_SUBMIT: u16 = 0x0003;
/// Reply code: Reply for URB unlink
pub const USBIP_RET_UNLINK: u16 = 0x0004;

/// USB/IP direction
///
/// NOTE: Must not be confused with rusb::Direction,
/// which has the opposite enum values. This is only for
/// internal use in the USB/IP protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
    Out = 0,
    In = 1,
}

/// Common header for all context sensitive packets
///
/// All commands/responses which rely on a device being attached
/// to a client use this header.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct UsbIpHeaderBasic {
    pub command: u32,
    pub seqnum: u32,
    pub devid: u32,
    pub direction: u32,
    pub ep: u32,
}

impl UsbIpHeaderBasic {
    /// Converts a byte array into a [UsbIpHeaderBasic].
    pub fn from_bytes(bytes: &[u8; 20]) -> Self {
        let result = UsbIpHeaderBasic {
            command: u32::from_be_bytes(bytes[0..4].try_into().unwrap()),
            seqnum: u32::from_be_bytes(bytes[4..8].try_into().unwrap()),
            devid: u32::from_be_bytes(bytes[8..12].try_into().unwrap()),
            direction: u32::from_be_bytes(bytes[12..16].try_into().unwrap()),
            ep: u32::from_be_bytes(bytes[16..20].try_into().unwrap()),
        };
        // The direction should be 0 or 1
        debug_assert!(result.direction & 1 == result.direction);
        result
    }

    /// Converts the [UsbIpHeaderBasic] into a byte array.
    pub fn to_bytes(&self) -> [u8; 20] {
        let mut result = [0u8; 20];
        result[0..4].copy_from_slice(&self.command.to_be_bytes());
        result[4..8].copy_from_slice(&self.seqnum.to_be_bytes());
        result[8..12].copy_from_slice(&self.devid.to_be_bytes());
        result[12..16].copy_from_slice(&self.direction.to_be_bytes());
        result[16..20].copy_from_slice(&self.ep.to_be_bytes());
        result
    }

    pub(crate) async fn read_from_socket_with_command<T: AsyncReadExt + Unpin>(
        socket: &mut T,
        command: u16,
    ) -> Result<Self> {
        let seqnum = socket.read_u32().await?;
        let devid = socket.read_u32().await?;
        let direction = socket.read_u32().await?;
        // The direction should be 0 or 1
        debug_assert!(direction & 1 == direction);
        let ep = socket.read_u32().await?;

        Ok(UsbIpHeaderBasic {
            command: command.into(),
            seqnum,
            devid,
            direction,
            ep,
        })
    }
}

/// Client side commands from the Virtual Host Controller
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum UsbIpCommand {
    OpReqDevlist {
        status: u32,
    },
    OpReqImport {
        status: u32,
        busid: [u8; 32],
    },
    UsbIpCmdSubmit {
        header: UsbIpHeaderBasic,
        transfer_flags: u32,
        transfer_buffer_length: u32,
        start_frame: u32,
        number_of_packets: u32,
        interval: u32,
        setup: [u8; 8],
        data: Vec<u8>,
        iso_packet_descriptor: Vec<u8>,
    },
    UsbIpCmdUnlink {
        header: UsbIpHeaderBasic,
        unlink_seqnum: u32,
    },
}

impl UsbIpCommand {
    /// Constructs a [UsbIpCommand] from a socket
    ///
    /// This will consume a variable amount of bytes from the socket.
    /// It might fail if the bytes does not follow the USB/IP protocol properly.
    pub async fn read_from_socket<T: AsyncReadExt + Unpin>(socket: &mut T) -> Result<UsbIpCommand> {
        let version: u16 = socket.read_u16().await?;

        if version != 0 && version != USBIP_VERSION {
            return Err(std::io::Error::other(format!(
                "Unknown version: {version:#04X}"
            )));
        }

        let command: u16 = socket.read_u16().await?;

        trace!(
            "Received command: {:#04X} ({}), parsing...",
            command,
            match command {
                OP_REQ_DEVLIST => "OP_REQ_DEVLIST",
                OP_REQ_IMPORT => "OP_REQ_IMPORT",
                USBIP_CMD_SUBMIT => "USBIP_CMD_SUBMIT",
                USBIP_CMD_UNLINK => "USBIP_CMD_UNLINK",
                _ => "Unknown",
            }
        );

        match command {
            OP_REQ_DEVLIST => {
                let status = socket.read_u32().await?;
                debug_assert!(status == 0);

                Ok(UsbIpCommand::OpReqDevlist { status })
            }
            OP_REQ_IMPORT => {
                let status = socket.read_u32().await?;
                debug_assert!(status == 0);
                let mut busid = [0; 32];
                socket.read_exact(&mut busid).await?;

                Ok(UsbIpCommand::OpReqImport { status, busid })
            }
            USBIP_CMD_SUBMIT => {
                let header =
                    UsbIpHeaderBasic::read_from_socket_with_command(socket, USBIP_CMD_SUBMIT)
                        .await?;
                let transfer_flags = socket.read_u32().await?;
                let transfer_buffer_length = socket.read_u32().await?;
                let start_frame = socket.read_u32().await?;
                let number_of_packets = socket.read_u32().await?;
                let interval = socket.read_u32().await?;

                let mut setup = [0; 8];
                socket.read_exact(&mut setup).await?;

                let data = if header.direction == Direction::In as u32 {
                    vec![]
                } else {
                    let mut data = vec![0; transfer_buffer_length as usize];
                    socket.read_exact(&mut data).await?;
                    data
                };

                // The kernel docs specifies that this should be set to 0xFFFFFFFF for all
                // non-ISO packets, however the actual implementation resorts to 0x00000000
                // https://stackoverflow.com/questions/76899798/usb-ip-what-is-the-size-of-the-iso-packet-descriptor
                let iso_packet_descriptor =
                    if number_of_packets != 0 && number_of_packets != 0xFFFFFFFF {
                        let mut result = vec![0; 16 * number_of_packets as usize];
                        socket.read_exact(&mut result).await?;
                        result
                    } else {
                        vec![]
                    };

                Ok(UsbIpCommand::UsbIpCmdSubmit {
                    header,
                    transfer_flags,
                    transfer_buffer_length,
                    start_frame,
                    number_of_packets,
                    interval,
                    setup,
                    data,
                    iso_packet_descriptor,
                })
            }
            USBIP_CMD_UNLINK => {
                let header =
                    UsbIpHeaderBasic::read_from_socket_with_command(socket, USBIP_CMD_UNLINK)
                        .await?;
                let unlink_seqnum = socket.read_u32().await?;

                let mut _padding = [0; 24];
                socket.read_exact(&mut _padding).await?;

                Ok(UsbIpCommand::UsbIpCmdUnlink {
                    header,
                    unlink_seqnum,
                })
            }
            _ => Err(std::io::Error::other(format!(
                "Unknown command: {command:#04X}"
            ))),
        }
    }

    /// Converts the [UsbIpCommand] into a byte vector
    pub fn to_bytes(&self) -> Vec<u8> {
        match *self {
            UsbIpCommand::OpReqDevlist { status } => {
                let mut result = Vec::with_capacity(8);
                result.extend_from_slice(&USBIP_VERSION.to_be_bytes());
                result.extend_from_slice(&OP_REQ_DEVLIST.to_be_bytes());
                result.extend_from_slice(&status.to_be_bytes());
                result
            }
            UsbIpCommand::OpReqImport { status, busid } => {
                let mut result = Vec::with_capacity(40);
                result.extend_from_slice(&USBIP_VERSION.to_be_bytes());
                result.extend_from_slice(&OP_REQ_IMPORT.to_be_bytes());
                result.extend_from_slice(&status.to_be_bytes());
                result.extend_from_slice(&busid);
                result
            }
            UsbIpCommand::UsbIpCmdSubmit {
                ref header,
                transfer_flags,
                transfer_buffer_length,
                start_frame,
                number_of_packets,
                interval,
                setup,
                ref data,
                ref iso_packet_descriptor,
            } => {
                debug_assert!(
                    header.direction != Direction::Out as u32
                        || transfer_buffer_length == data.len() as u32
                );

                let mut result = Vec::with_capacity(48 + data.len() + iso_packet_descriptor.len());
                result.extend_from_slice(&header.to_bytes());
                result.extend_from_slice(&transfer_flags.to_be_bytes());
                result.extend_from_slice(&transfer_buffer_length.to_be_bytes());
                result.extend_from_slice(&start_frame.to_be_bytes());
                result.extend_from_slice(&number_of_packets.to_be_bytes());
                result.extend_from_slice(&interval.to_be_bytes());
                result.extend_from_slice(&setup);
                result.extend_from_slice(data);
                result.extend_from_slice(iso_packet_descriptor);
                result
            }
            UsbIpCommand::UsbIpCmdUnlink {
                ref header,
                unlink_seqnum,
            } => {
                let mut result = Vec::with_capacity(48);
                result.extend_from_slice(&header.to_bytes());
                result.extend_from_slice(&unlink_seqnum.to_be_bytes());
                result.extend_from_slice(&[0; 24]);
                result
            }
        }
    }
}

/// Server side responses from the USB Host
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub enum UsbIpResponse {
    OpRepDevlist {
        status: u32,
        device_count: u32,
        devices: Vec<UsbDevice>,
    },
    OpRepImport {
        status: u32,
        device: Option<UsbDevice>,
    },
    UsbIpRetSubmit {
        header: UsbIpHeaderBasic,
        status: u32,
        actual_length: u32,
        start_frame: u32,
        number_of_packets: u32,
        error_count: u32,
        transfer_buffer: Vec<u8>,
        iso_packet_descriptor: Vec<u8>,
    },
    UsbIpRetUnlink {
        header: UsbIpHeaderBasic,
        status: u32,
    },
}

impl UsbIpResponse {
    /// Converts the [UsbIpResponse] into a byte vector
    pub fn to_bytes(&self) -> Vec<u8> {
        match *self {
            Self::OpRepDevlist {
                status,
                device_count,
                ref devices,
            } => {
                let mut result = Vec::with_capacity(
                    12 + devices.len() * 312
                        + devices
                            .iter()
                            .map(|d| d.interfaces.len() * 4)
                            .sum::<usize>(),
                );
                result.extend_from_slice(&USBIP_VERSION.to_be_bytes());
                result.extend_from_slice(&OP_REP_DEVLIST.to_be_bytes());
                result.extend_from_slice(&status.to_be_bytes());
                result.extend_from_slice(&device_count.to_be_bytes());
                for dev in devices {
                    result.extend_from_slice(&dev.to_bytes_with_interfaces());
                }
                result
            }
            Self::OpRepImport { status, ref device } => {
                let mut result = Vec::with_capacity(320);
                result.extend_from_slice(&USBIP_VERSION.to_be_bytes());
                result.extend_from_slice(&OP_REP_IMPORT.to_be_bytes());
                result.extend_from_slice(&status.to_be_bytes());
                if let Some(device) = device {
                    result.extend_from_slice(&device.to_bytes());
                }
                result
            }
            Self::UsbIpRetSubmit {
                ref header,
                status,
                actual_length,
                start_frame,
                number_of_packets,
                error_count,
                ref transfer_buffer,
                ref iso_packet_descriptor,
            } => {
                let mut result =
                    Vec::with_capacity(48 + transfer_buffer.len() + iso_packet_descriptor.len());

                debug_assert!(header.command == USBIP_RET_SUBMIT.into());
                debug_assert!(if header.direction == Direction::In as u32 {
                    actual_length == transfer_buffer.len() as u32
                } else {
                    actual_length == 0
                });

                result.extend_from_slice(&header.to_bytes());
                result.extend_from_slice(&status.to_be_bytes());
                result.extend_from_slice(&actual_length.to_be_bytes());
                result.extend_from_slice(&start_frame.to_be_bytes());
                result.extend_from_slice(&number_of_packets.to_be_bytes());
                result.extend_from_slice(&error_count.to_be_bytes());
                result.extend_from_slice(&[0; 8]);
                result.extend_from_slice(transfer_buffer);
                result.extend_from_slice(iso_packet_descriptor);
                result
            }
            Self::UsbIpRetUnlink { ref header, status } => {
                let mut result = Vec::with_capacity(48);

                debug_assert!(header.command == USBIP_RET_UNLINK.into());

                result.extend_from_slice(&header.to_bytes());
                result.extend_from_slice(&status.to_be_bytes());
                result.extend_from_slice(&[0; 24]);
                result
            }
        }
    }

    pub async fn write_to_socket<T: AsyncWriteExt + Unpin>(&self, socket: &mut T) -> Result<()> {
        socket.write_all(&self.to_bytes()).await
    }

    /// Constructs a OP_REP_DEVLIST response
    pub fn op_rep_devlist(devices: &[UsbDevice]) -> Self {
        Self::OpRepDevlist {
            status: 0,
            device_count: devices.len() as u32,
            devices: devices.to_vec(),
        }
    }

    /// Constructs a successful OP_REP_IMPORT response
    pub fn op_rep_import_success(device: &UsbDevice) -> Self {
        Self::OpRepImport {
            status: 0,
            device: Some(device.clone()),
        }
    }

    /// Constructs a failed OP_REP_IMPORT response
    pub fn op_rep_import_fail() -> Self {
        Self::OpRepImport {
            status: 1,
            device: None,
        }
    }

    /// Constructs a successful OP_REP_IMPORT response
    pub fn usbip_ret_submit_success(
        header: &UsbIpHeaderBasic,
        start_frame: u32,
        number_of_packets: u32,
        transfer_buffer: Vec<u8>,
        iso_packet_descriptor: Vec<u8>,
    ) -> Self {
        Self::UsbIpRetSubmit {
            header: header.clone(),
            status: 0,
            actual_length: transfer_buffer.len() as u32,
            start_frame,
            number_of_packets,
            error_count: 0,
            transfer_buffer,
            iso_packet_descriptor,
        }
    }

    /// Constructs a failed OP_REP_IMPORT response
    pub fn usbip_ret_submit_fail(header: &UsbIpHeaderBasic) -> Self {
        Self::UsbIpRetSubmit {
            header: header.clone(),
            status: 1,
            actual_length: 0,
            start_frame: 0,
            number_of_packets: 0,
            error_count: 0,
            transfer_buffer: vec![],
            iso_packet_descriptor: vec![],
        }
    }

    /// Constructs a successful OP_REP_IMPORT response
    pub fn usbip_ret_unlink_success(header: &UsbIpHeaderBasic) -> Self {
        Self::UsbIpRetUnlink {
            header: header.clone(),
            status: 0,
        }
    }

    /// Constructs a failed OP_REP_IMPORT response.
    pub fn usbip_ret_unlink_fail(header: &UsbIpHeaderBasic) -> Self {
        Self::UsbIpRetUnlink {
            header: header.clone(),
            status: 1,
        }
    }
}

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

    use super::*;

    fn example_device() -> UsbDevice {
        UsbDevice::default()
    }

    #[test]
    fn byte_serialize_op_req_devlist() {
        setup_test_logger();
        let cmd = UsbIpCommand::OpReqDevlist { status: 0 };
        assert_eq!(
            cmd.to_bytes(),
            [
                0x01, 0x11, // version,
                0x80, 0x05, // command
                0x00, 0x00, 0x00, 0x00, // status
            ]
        );
    }

    #[test]
    fn byte_serialize_op_req_import() {
        setup_test_logger();
        let cmd = UsbIpCommand::OpReqImport {
            status: 0,
            busid: [0; 32],
        };
        assert_eq!(
            cmd.to_bytes(),
            [
                0x01, 0x11, // version,
                0x80, 0x03, // command
                0x00, 0x00, 0x00, 0x00, // status
                0x00, 0x00, 0x00, 0x00, // busid
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
            ]
        );
    }

    #[test]
    fn byte_serialize_usbip_cmd_submit() {
        setup_test_logger();
        let cmd = UsbIpCommand::UsbIpCmdSubmit {
            header: UsbIpHeaderBasic {
                command: 1,
                seqnum: 2,
                devid: 3,
                direction: 4,
                ep: 5,
            },
            transfer_flags: 0,
            transfer_buffer_length: 0,
            start_frame: 6,
            number_of_packets: 0,
            interval: 7,
            setup: [0xFF; 8],
            data: vec![],
            iso_packet_descriptor: vec![],
        };
        assert_eq!(
            cmd.to_bytes(),
            [
                0x00, 0x00, 0x00, 0x01, // command
                0x00, 0x00, 0x00, 0x02, // seqnum
                0x00, 0x00, 0x00, 0x03, // devid
                0x00, 0x00, 0x00, 0x04, // direction
                0x00, 0x00, 0x00, 0x05, // ep
                0x00, 0x00, 0x00, 0x00, // transfer_flags
                0x00, 0x00, 0x00, 0x00, // transfer_buffer_length
                0x00, 0x00, 0x00, 0x06, // start_frame
                0x00, 0x00, 0x00, 0x00, // number_of_packets
                0x00, 0x00, 0x00, 0x07, // interval
                0xFF, 0xFF, 0xFF, 0xFF, // setup
                0xFF, 0xFF, 0xFF, 0xFF,
                // data
                // iso_packet_descriptor
            ]
        );
    }

    #[test]
    fn byte_serialize_usbip_cmd_unlink() {
        setup_test_logger();
        let cmd = UsbIpCommand::UsbIpCmdUnlink {
            header: UsbIpHeaderBasic {
                command: 0,
                seqnum: 1,
                devid: 2,
                direction: 3,
                ep: 4,
            },
            unlink_seqnum: 5,
        };
        assert_eq!(
            cmd.to_bytes(),
            [
                0x00, 0x00, 0x00, 0x00, // command
                0x00, 0x00, 0x00, 0x01, // seqnum
                0x00, 0x00, 0x00, 0x02, // devid
                0x00, 0x00, 0x00, 0x03, // direction
                0x00, 0x00, 0x00, 0x04, // ep
                0x00, 0x00, 0x00, 0x05, // unlink_seqnum
                0x00, 0x00, 0x00, 0x00, // padding
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
                0x00, 0x00, 0x00, 0x00, //
            ]
        );
    }

    #[test]
    fn byte_serialize_op_rep_devlist() {
        setup_test_logger();
        let device = example_device();
        let res = UsbIpResponse::op_rep_devlist(std::slice::from_ref(&device));
        assert_eq!(
            res.to_bytes(),
            [
                vec![0x01, 0x11],             // version
                vec![0x00, 0x05],             // command
                vec![0x00, 0x00, 0x00, 0x00], // status
                vec![0x00, 0x00, 0x00, 0x01], // device_count
                device.to_bytes()
            ]
            .concat()
            .as_slice()
        );
    }

    #[test]
    fn byte_serialize_op_rep_import() {
        setup_test_logger();
        let device = example_device();
        let res = UsbIpResponse::op_rep_import_success(&device);
        assert_eq!(
            res.to_bytes(),
            [
                vec![0x01, 0x11],             // version
                vec![0x00, 0x03],             // command
                vec![0x00, 0x00, 0x00, 0x00], // status
                device.to_bytes()
            ]
            .concat()
            .as_slice()
        );

        let res = UsbIpResponse::op_rep_import_fail();
        assert_eq!(
            res.to_bytes(),
            vec![
                0x01, 0x11, // version
                0x00, 0x03, // command
                0x00, 0x00, 0x00, 0x01, // status
            ]
        );
    }

    #[test]
    fn byte_serialize_usbip_ret_submit() {
        setup_test_logger();
        let res = UsbIpResponse::UsbIpRetSubmit {
            header: UsbIpHeaderBasic {
                command: USBIP_RET_SUBMIT.into(),
                seqnum: 2,
                devid: 3,
                direction: Direction::In as u32,
                ep: 4,
            },
            status: 5,
            actual_length: 4,
            start_frame: 7,
            number_of_packets: 8,
            error_count: 9,
            transfer_buffer: vec![0xFF; 4],
            iso_packet_descriptor: vec![],
        };

        assert_eq!(
            res.to_bytes(),
            vec![
                0x00, 0x00, 0x00, 0x03, // command
                0x00, 0x00, 0x00, 0x02, // seqnum
                0x00, 0x00, 0x00, 0x03, // devid
                0x00, 0x00, 0x00, 0x01, // direction
                0x00, 0x00, 0x00, 0x04, // ep
                0x00, 0x00, 0x00, 0x05, // status
                0x00, 0x00, 0x00, 0x04, // actual_length
                0x00, 0x00, 0x00, 0x07, // start_frame
                0x00, 0x00, 0x00, 0x08, // number_of_packets
                0x00, 0x00, 0x00, 0x09, // error_count
                0x00, 0x00, 0x00, 0x00, // padding
                0x00, 0x00, 0x00, 0x00, //
                0xFF, 0xFF, 0xFF,
                0xFF, // transfer_buffer
                      // iso_packet_descriptor
            ],
        );
    }

    #[test]
    #[should_panic]
    fn byte_serialize_invalid_usbip_ret_submit() {
        setup_test_logger();
        let res = UsbIpResponse::UsbIpRetSubmit {
            header: UsbIpHeaderBasic {
                command: USBIP_RET_SUBMIT.into(),
                seqnum: 2,
                devid: 3,
                direction: Direction::Out as u32, // data section should be empty, but is not
                ep: 4,
            },
            status: 5,
            actual_length: 4,
            start_frame: 7,
            number_of_packets: 8,
            error_count: 9,
            transfer_buffer: vec![0xFF; 4],
            iso_packet_descriptor: vec![0xFF; 16],
        };

        res.to_bytes();
    }

    #[test]
    fn byte_serialize_usbip_ret_unlink() {
        setup_test_logger();
        let res = UsbIpResponse::usbip_ret_unlink_success(&UsbIpHeaderBasic {
            command: USBIP_RET_UNLINK.into(),
            seqnum: 1,
            devid: 2,
            direction: 3,
            ep: 4,
        });

        let mut expected_result = vec![
            0x00, 0x00, 0x00, 0x04, // command
            0x00, 0x00, 0x00, 0x01, // seqnum
            0x00, 0x00, 0x00, 0x02, // devid
            0x00, 0x00, 0x00, 0x03, // direction
            0x00, 0x00, 0x00, 0x04, // ep
            0x00, 0x00, 0x00, 0x00, // status
            0x00, 0x00, 0x00, 0x00, // padding
            0x00, 0x00, 0x00, 0x00, //
            0x00, 0x00, 0x00, 0x00, //
            0x00, 0x00, 0x00, 0x00, //
            0x00, 0x00, 0x00, 0x00, //
            0x00, 0x00, 0x00, 0x00, //
        ];

        assert_eq!(res.to_bytes(), expected_result,);

        let res = UsbIpResponse::usbip_ret_unlink_fail(&UsbIpHeaderBasic {
            command: USBIP_RET_UNLINK.into(),
            seqnum: 1,
            devid: 2,
            direction: 3,
            ep: 4,
        });

        expected_result[5 * 4 + 3] = 1; // status

        assert_eq!(res.to_bytes(), expected_result,);
    }

    #[tokio::test]
    async fn read_op_req_devlist_from_socket() -> Result<()> {
        setup_test_logger();
        let cmd = UsbIpCommand::OpReqDevlist { status: 0 };

        assert_eq!(
            cmd.to_bytes(),
            UsbIpCommand::read_from_socket(&mut MockSocket::new(cmd.to_bytes()))
                .await?
                .to_bytes()
        );

        Ok(())
    }

    #[tokio::test]
    async fn read_op_req_import_from_socket() -> Result<()> {
        setup_test_logger();
        let cmd = UsbIpCommand::OpReqImport {
            status: 0,
            busid: {
                let mut b = "0-0-0".as_bytes().to_vec();
                b.resize(32, 0);
                b.as_slice().try_into().unwrap()
            },
        };

        assert_eq!(
            cmd.to_bytes(),
            UsbIpCommand::read_from_socket(&mut MockSocket::new(cmd.to_bytes()))
                .await?
                .to_bytes()
        );

        Ok(())
    }

    #[tokio::test]
    async fn read_usbip_cmd_submit_from_socket() -> Result<()> {
        setup_test_logger();
        let cmd = UsbIpCommand::UsbIpCmdSubmit {
            header: UsbIpHeaderBasic {
                command: USBIP_CMD_SUBMIT.into(),
                seqnum: 1,
                devid: 2,
                direction: Direction::Out as u32,
                ep: 4,
            },
            transfer_flags: 5,
            transfer_buffer_length: 4,
            start_frame: 7,
            number_of_packets: 1,
            interval: 9,
            setup: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07],
            data: vec![0x08, 0x09, 0x0A, 0x0B],
            iso_packet_descriptor: vec![0xFF; 16],
        };

        assert_eq!(
            cmd.to_bytes(),
            UsbIpCommand::read_from_socket(&mut MockSocket::new(cmd.to_bytes()))
                .await?
                .to_bytes()
        );

        Ok(())
    }

    #[tokio::test]
    async fn read_usbip_cmd_submit_from_socket_with_no_data() -> Result<()> {
        setup_test_logger();
        let cmd = UsbIpCommand::UsbIpCmdSubmit {
            header: UsbIpHeaderBasic {
                command: USBIP_CMD_SUBMIT.into(),
                seqnum: 1,
                devid: 2,
                direction: Direction::In as u32, // data section should be ignored despite transfer_buffer_length
                ep: 4,
            },
            transfer_flags: 5,
            transfer_buffer_length: 64,
            start_frame: 7,
            number_of_packets: 1,
            interval: 9,
            setup: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xFF],
            data: vec![],
            iso_packet_descriptor: vec![0xFF; 16],
        };

        assert_eq!(
            cmd.to_bytes(),
            UsbIpCommand::read_from_socket(&mut MockSocket::new(cmd.to_bytes()))
                .await?
                .to_bytes()
        );

        Ok(())
    }

    #[tokio::test]
    async fn read_usbip_cmd_unlink_from_socket() -> Result<()> {
        setup_test_logger();
        let cmd = UsbIpCommand::UsbIpCmdUnlink {
            header: UsbIpHeaderBasic {
                command: USBIP_CMD_UNLINK.into(),
                seqnum: 1,
                devid: 2,
                direction: 0,
                ep: 4,
            },
            unlink_seqnum: 1,
        };

        assert_eq!(
            cmd.to_bytes(),
            UsbIpCommand::read_from_socket(&mut MockSocket::new(cmd.to_bytes()))
                .await?
                .to_bytes()
        );

        Ok(())
    }

    #[tokio::test]
    async fn byte_serialization_fails_on_old_usbip_version() {
        setup_test_logger();

        let cmd = UsbIpCommand::OpReqDevlist { status: 0 };
        let mut bytes = cmd.to_bytes();
        bytes[1] = 0x10; // set version to 0x0110

        let mut socket = MockSocket::new(bytes);
        let result = UsbIpCommand::read_from_socket(&mut socket).await;
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Unknown version: 0x110".to_string()
        );
    }

    #[tokio::test]
    async fn byte_serialization_fails_on_invalid_command() {
        setup_test_logger();

        let cmd = UsbIpCommand::OpReqDevlist { status: 0 };
        let mut bytes = cmd.to_bytes();
        bytes[2] = 0x10; // set command to 0x1005

        let mut socket = MockSocket::new(bytes);
        let result = UsbIpCommand::read_from_socket(&mut socket).await;
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Unknown command: 0x1005".to_string()
        );
    }
}