usb-gadget 1.2.0

Expose standard or fully custom USB peripherals (gadgets) through a USB device controller (UDC) on Linux.
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
//! USB gadget.

use rustix::io::Errno;
use std::{
    collections::HashMap,
    ffi::{OsStr, OsString},
    fmt, fs,
    io::{Error, ErrorKind, Result},
    os::unix::{
        fs::symlink,
        prelude::{OsStrExt, OsStringExt},
    },
    path::{Path, PathBuf},
};

use crate::{
    configfs_dir, function,
    function::{
        util::{call_remove_handler, init_remove_handlers},
        Handle,
    },
    hex_u16, hex_u8,
    lang::Language,
    request_module, trim_os_str,
    udc::Udc,
    Speed,
};

/// USB gadget ioctl magic byte.
pub const GADGET_IOC_MAGIC: u8 = b'g';

/// USB gadget or interface class.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Class {
    /// Class code.
    pub class: u8,
    /// Subclass code.
    pub sub_class: u8,
    /// Protocol code.
    pub protocol: u8,
}

impl Class {
    /// Vendor specific class code.
    pub const VENDOR_SPECIFIC: u8 = 0xff;

    /// Creates a new USB device or interface class.
    pub const fn new(class: u8, sub_class: u8, protocol: u8) -> Self {
        Self { class, sub_class, protocol }
    }

    /// Creates a new USB device or interface class with vendor-specific class code.
    pub const fn vendor_specific(sub_class: u8, protocol: u8) -> Self {
        Self::new(Self::VENDOR_SPECIFIC, sub_class, protocol)
    }

    /// Indicates that class information should be determined from the interface descriptors in the
    /// device.
    ///
    /// Can only be used as device class.
    ///
    /// Use [`INTERFACE_SPECIFIC`](Self::INTERFACE_SPECIFIC) instead.
    #[deprecated(since = "1.1.0", note = "use Class::INTERFACE_SPECIFIC instead")]
    pub const fn interface_specific() -> Self {
        Self::new(0, 0, 0)
    }

    // --- Device-level classes ---

    /// Class information determined from interface descriptors.
    ///
    /// This is the most common device-level class and can only be used as device class.
    pub const INTERFACE_SPECIFIC: Self = Self::new(0x00, 0x00, 0x00);

    /// Miscellaneous device with Interface Association Descriptor (IAD).
    ///
    /// Used as device class when the gadget has multiple functions grouped via IADs
    /// (e.g. composite devices with CDC + other functions, or UVC devices).
    pub const MISCELLANEOUS_IAD: Self = Self::new(0xEF, 0x02, 0x01);

    // --- Audio (class 0x01) ---

    /// Audio control interface.
    pub const AUDIO_CONTROL: Self = Self::new(0x01, 0x01, 0x00);
    /// Audio streaming interface.
    pub const AUDIO_STREAMING: Self = Self::new(0x01, 0x02, 0x00);
    /// MIDI streaming interface.
    pub const AUDIO_MIDISTREAMING: Self = Self::new(0x01, 0x03, 0x00);

    // --- CDC (class 0x02 / 0x0A) ---

    /// Communications Device Class, Abstract Control Model (modem/serial).
    pub const CDC_ACM: Self = Self::new(0x02, 0x02, 0x01);
    /// CDC Ethernet Networking Control Model.
    pub const CDC_ECM: Self = Self::new(0x02, 0x06, 0x00);
    /// CDC Ethernet Emulation Model.
    pub const CDC_EEM: Self = Self::new(0x02, 0x0C, 0x07);
    /// CDC Network Control Model.
    pub const CDC_NCM: Self = Self::new(0x02, 0x0D, 0x00);
    /// CDC Data interface.
    pub const CDC_DATA: Self = Self::new(0x0A, 0x00, 0x00);

    // --- HID (class 0x03) ---

    /// Human Interface Device, no boot protocol.
    pub const HID: Self = Self::new(0x03, 0x00, 0x00);
    /// HID boot interface, keyboard protocol.
    pub const HID_BOOT_KEYBOARD: Self = Self::new(0x03, 0x01, 0x01);
    /// HID boot interface, mouse protocol.
    pub const HID_BOOT_MOUSE: Self = Self::new(0x03, 0x01, 0x02);

    // --- Printer (class 0x07) ---

    /// Printer, unidirectional.
    pub const PRINTER_UNIDIRECTIONAL: Self = Self::new(0x07, 0x01, 0x01);
    /// Printer, bidirectional.
    pub const PRINTER_BIDIRECTIONAL: Self = Self::new(0x07, 0x01, 0x02);

    // --- Mass Storage (class 0x08) ---

    /// Mass storage, SCSI transparent command set, bulk-only transport.
    pub const MASS_STORAGE_SCSI_BULK: Self = Self::new(0x08, 0x06, 0x50);

    // --- Video (class 0x0E) ---

    /// Video control interface.
    pub const VIDEO_CONTROL: Self = Self::new(0x0E, 0x01, 0x00);
    /// Video streaming interface.
    pub const VIDEO_STREAMING: Self = Self::new(0x0E, 0x02, 0x00);

    // --- Application-specific (class 0xFE) ---

    /// Device Firmware Upgrade (DFU), runtime mode.
    pub const DFU_RUNTIME: Self = Self::new(0xFE, 0x01, 0x01);
    /// Device Firmware Upgrade (DFU), DFU mode.
    pub const DFU_MODE: Self = Self::new(0xFE, 0x01, 0x02);
}

/// USB gadget id.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id {
    /// Vendor id.
    pub vendor: u16,
    /// Product id.
    pub product: u16,
}

impl Id {
    /// Creates a new USB device id.
    pub const fn new(vendor: u16, product: u16) -> Self {
        Self { vendor, product }
    }

    /// Linux Foundation vendor id.
    ///
    /// Intended for development and testing of Linux USB gadgets.
    /// For production devices, register your own vendor id with the USB-IF
    /// or obtain one from <https://pid.codes>.
    pub const LINUX_FOUNDATION_VID: u16 = 0x1d6b;

    /// Linux Foundation serial gadget (CDC ACM).
    ///
    /// Intended for development and testing only.
    pub const LINUX_FOUNDATION_SERIAL: Self = Self::new(0x1d6b, 0x0101);
    /// Linux Foundation ethernet gadget (RNDIS/CDC).
    ///
    /// Intended for development and testing only.
    pub const LINUX_FOUNDATION_ETHERNET: Self = Self::new(0x1d6b, 0x0102);
    /// Linux Foundation file-backed storage gadget.
    ///
    /// Intended for development and testing only.
    pub const LINUX_FOUNDATION_STORAGE: Self = Self::new(0x1d6b, 0x0103);
    /// Linux Foundation multifunction composite gadget.
    ///
    /// Intended for development and testing only.
    pub const LINUX_FOUNDATION_COMPOSITE: Self = Self::new(0x1d6b, 0x0104);
    /// Linux Foundation FunctionFS gadget.
    ///
    /// Intended for development and testing only.
    pub const LINUX_FOUNDATION_FFS: Self = Self::new(0x1d6b, 0x0105);
}

/// USB gadget description strings.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Strings {
    /// Manufacturer name.
    pub manufacturer: String,
    /// Product name.
    pub product: String,
    /// Serial number.
    pub serial_number: String,
}

impl Strings {
    /// Creates new USB device strings.
    pub fn new(manufacturer: impl AsRef<str>, product: impl AsRef<str>, serial_number: impl AsRef<str>) -> Self {
        Self {
            manufacturer: manufacturer.as_ref().to_string(),
            product: product.as_ref().to_string(),
            serial_number: serial_number.as_ref().to_string(),
        }
    }
}

/// USB gadget operating system descriptor.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OsDescriptor {
    /// Vendor code for requests.
    pub vendor_code: u8,
    /// Signature.
    pub qw_sign: String,
    /// Index of configuration in [`Gadget::configs`] to be reported at index 0.
    ///
    /// Hosts which expect the "OS Descriptors" ask only for configurations at index 0,
    /// but Linux-based USB devices can provide more than one configuration.
    pub config: usize,
}

impl OsDescriptor {
    /// Creates a new instance.
    pub const fn new(vendor_code: u8, qw_sign: String) -> Self {
        Self { vendor_code, qw_sign, config: 0 }
    }

    /// The Microsoft OS descriptor.
    ///
    /// Uses vendor code 0xf0 for requests.
    pub fn microsoft() -> Self {
        Self { vendor_code: 0xf0, qw_sign: "MSFT100".to_string(), config: 0 }
    }
}

/// WebUSB version.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum WebUsbVersion {
    /// Version 1.0
    #[default]
    V10,
    /// Other version in BCD format.
    Other(u16),
}

impl From<WebUsbVersion> for u16 {
    fn from(value: WebUsbVersion) -> Self {
        match value {
            WebUsbVersion::V10 => 0x0100,
            WebUsbVersion::Other(ver) => ver,
        }
    }
}

/// USB gadget WebUSB descriptor.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WebUsb {
    /// WebUSB specification version number.
    pub version: WebUsbVersion,
    /// bRequest value used for issuing WebUSB requests.
    pub vendor_code: u8,
    /// URL of the device's landing page.
    pub landing_page: String,
}

impl WebUsb {
    /// Creates a new instance.
    pub fn new(vendor_code: u8, landing_page: impl AsRef<str>) -> Self {
        Self { version: WebUsbVersion::default(), vendor_code, landing_page: landing_page.as_ref().to_string() }
    }
}

/// USB gadget configuration.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Config {
    /// Maximum power in mA.
    pub max_power: u16,
    /// Self powered?
    pub self_powered: bool,
    /// Remote wakeup?
    pub remote_wakeup: bool,
    /// Configuration description string.
    pub description: HashMap<Language, String>,
    /// Functions, i.e. USB interfaces, present in this configuration.
    pub functions: Vec<function::Handle>,
}

impl Config {
    /// Creates a new USB gadget configuration.
    pub fn new(description: impl AsRef<str>) -> Self {
        Self {
            max_power: 500,
            self_powered: false,
            remote_wakeup: false,
            description: [(Language::default(), description.as_ref().to_string())].into(),
            functions: Default::default(),
        }
    }

    /// Adds a USB function (interface) to this configuration.
    pub fn add_function(&mut self, function_handle: function::Handle) {
        self.functions.push(function_handle);
    }

    /// Adds a USB function (interface) to this configuration.
    #[must_use]
    pub fn with_function(mut self, function_handle: function::Handle) -> Self {
        self.add_function(function_handle);
        self
    }

    fn register(
        &self, gadget_dir: &Path, idx: usize, func_dirs: &HashMap<function::Handle, PathBuf>,
    ) -> Result<PathBuf> {
        let dir = gadget_dir.join("configs").join(format!("c.{idx}"));
        log::debug!("creating config at {}", dir.display());
        fs::create_dir(&dir)?;

        let mut attributes = 1 << 7;
        if self.self_powered {
            attributes |= 1 << 6;
        }
        if self.remote_wakeup {
            attributes |= 1 << 5;
        }

        fs::write(dir.join("bmAttributes"), hex_u8(attributes))?;
        fs::write(dir.join("MaxPower"), self.max_power.to_string())?;

        for (&lang, desc) in &self.description {
            let lang_dir = dir.join("strings").join(hex_u16(lang.into()));
            fs::create_dir(&lang_dir)?;
            fs::write(lang_dir.join("configuration"), desc)?;
        }

        for func in &self.functions {
            let func_dir = &func_dirs[func];
            log::debug!("adding function {}", func_dir.display());
            symlink(func_dir, dir.join(func_dir.file_name().unwrap()))?;
        }

        Ok(dir)
    }
}

/// USB version.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UsbVersion {
    /// USB 1.1
    V11,
    /// USB 2.0
    #[default]
    V20,
    /// USB 2.0 with BOS descriptor support (bcdUSB 0x0201), needed for WinUSB.
    V21,
    /// USB 3.0
    V30,
    /// USB 3.1
    V31,
    /// Other version in BCD format.
    Other(u16),
}

impl From<UsbVersion> for u16 {
    fn from(value: UsbVersion) -> Self {
        match value {
            UsbVersion::V11 => 0x0110,
            UsbVersion::V20 => 0x0200,
            UsbVersion::V21 => 0x0201,
            UsbVersion::V30 => 0x0300,
            UsbVersion::V31 => 0x0310,
            UsbVersion::Other(ver) => ver,
        }
    }
}

/// USB gadget definition.
///
/// Fields set to `None` are left at their kernel-provided default values.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Gadget {
    /// Custom name for the gadget in configfs.
    ///
    /// If `None`, an auto-generated name like `usb-gadget0` is used.
    pub name: Option<String>,
    /// USB device class.
    pub device_class: Class,
    /// USB device id.
    pub id: Id,
    /// USB device strings.
    pub strings: HashMap<Language, Strings>,
    /// Maximum endpoint 0 packet size.
    pub max_packet_size0: u8,
    /// Device release number in BCD format.
    ///
    /// No hexadecimal digit must exceed 9.
    pub device_release: u16,
    /// USB specification version.
    pub usb_version: UsbVersion,
    /// Maximum speed supported by driver.
    pub max_speed: Option<Speed>,
    /// OS descriptor extension.
    pub os_descriptor: Option<OsDescriptor>,
    /// WebUSB extension.
    pub web_usb: Option<WebUsb>,
    /// USB device configurations.
    pub configs: Vec<Config>,
}

impl Gadget {
    /// Creates a new USB gadget definition.
    pub fn new(device_class: Class, id: Id, strings: Strings) -> Self {
        Self {
            name: None,
            device_class,
            id,
            strings: [(Language::default(), strings)].into(),
            max_packet_size0: 64,
            device_release: 0x0000,
            usb_version: UsbVersion::default(),
            max_speed: None,
            os_descriptor: None,
            web_usb: None,
            configs: Vec::new(),
        }
    }

    /// Adds a USB device configuration.
    pub fn add_config(&mut self, config: Config) {
        self.configs.push(config);
    }

    /// Adds a USB device configuration.
    #[must_use]
    pub fn with_config(mut self, config: Config) -> Self {
        self.add_config(config);
        self
    }

    /// Sets the OS descriptor.
    #[must_use]
    pub fn with_os_descriptor(mut self, os_descriptor: OsDescriptor) -> Self {
        self.os_descriptor = Some(os_descriptor);
        self
    }

    /// Sets the WebUSB extension.
    #[must_use]
    pub fn with_web_usb(mut self, web_usb: WebUsb) -> Self {
        self.web_usb = Some(web_usb);
        self
    }

    /// Register the USB gadget.
    ///
    /// At least one [configuration](Config) must be added before the gadget
    /// can be registered.
    #[must_use = "consumes the gadget"]
    pub fn register(self) -> Result<RegGadget> {
        if self.configs.is_empty() {
            return Err(Error::new(ErrorKind::InvalidInput, "USB gadget must have at least one configuration"));
        }

        let usb_gadget_dir = usb_gadget_dir()?;

        let dir = if let Some(ref name) = self.name {
            let dir = usb_gadget_dir.join(name);
            fs::create_dir(&dir)?;
            dir
        } else {
            let mut gadget_idx: u16 = 0;
            loop {
                let dir = usb_gadget_dir.join(format!("usb-gadget{gadget_idx}"));
                match fs::create_dir(&dir) {
                    Ok(()) => break dir,
                    Err(err) if err.kind() == ErrorKind::AlreadyExists => (),
                    Err(err) => return Err(err),
                }
                gadget_idx = gadget_idx
                    .checked_add(1)
                    .ok_or_else(|| Error::new(ErrorKind::OutOfMemory, "USB gadgets exhausted"))?;
            }
        };

        log::debug!("registering gadget at {}", dir.display());

        fs::write(dir.join("bDeviceClass"), hex_u8(self.device_class.class))?;
        fs::write(dir.join("bDeviceSubClass"), hex_u8(self.device_class.sub_class))?;
        fs::write(dir.join("bDeviceProtocol"), hex_u8(self.device_class.protocol))?;

        fs::write(dir.join("idVendor"), hex_u16(self.id.vendor))?;
        fs::write(dir.join("idProduct"), hex_u16(self.id.product))?;

        fs::write(dir.join("bMaxPacketSize0"), hex_u8(self.max_packet_size0))?;
        fs::write(dir.join("bcdDevice"), hex_u16(self.device_release))?;
        fs::write(dir.join("bcdUSB"), hex_u16(self.usb_version.into()))?;

        if let Some(v) = self.max_speed {
            fs::write(dir.join("max_speed"), v.to_string())?;
        }

        if let Some(webusb) = &self.web_usb {
            let webusb_dir = dir.join("webusb");
            if webusb_dir.is_dir() {
                fs::write(webusb_dir.join("bVendorCode"), hex_u8(webusb.vendor_code))?;
                fs::write(webusb_dir.join("bcdVersion"), hex_u16(webusb.version.into()))?;
                fs::write(webusb_dir.join("landingPage"), &webusb.landing_page)?;
                fs::write(webusb_dir.join("use"), "1")?;
            } else {
                log::warn!("WebUSB descriptor is unsupported by kernel");
            }
        }

        for (&lang, strs) in &self.strings {
            let lang_dir = dir.join("strings").join(hex_u16(lang.into()));
            fs::create_dir(&lang_dir)?;

            fs::write(lang_dir.join("manufacturer"), &strs.manufacturer)?;
            fs::write(lang_dir.join("product"), &strs.product)?;
            fs::write(lang_dir.join("serialnumber"), &strs.serial_number)?;
        }

        let gadget_name = dir.file_name().unwrap().to_string_lossy();
        let mut functions = Vec::new();
        for func in self.configs.iter().flat_map(|c| &c.functions) {
            if !functions.contains(&func) {
                functions.push(func);
            }
        }
        let mut func_dirs = HashMap::new();
        for (func_idx, &func) in functions.iter().enumerate() {
            let func_dir = dir.join(
                dir.join("functions")
                    .join(format!("{}.{gadget_name}-{func_idx}", func.get().driver().to_string_lossy())),
            );
            log::debug!("creating function at {}", func_dir.display());
            fs::create_dir(&func_dir)?;

            func.get().dir().set_dir(&func_dir);
            func.get().register()?;

            func_dirs.insert(func.clone(), func_dir);
        }

        let mut config_dirs = Vec::new();
        for (idx, config) in self.configs.iter().enumerate() {
            let dir = config.register(&dir, idx + 1, &func_dirs)?;
            config_dirs.push(dir);
        }

        if let Some(os_desc) = &self.os_descriptor {
            let os_desc_dir = dir.join("os_desc");
            if os_desc_dir.is_dir() {
                fs::write(os_desc_dir.join("b_vendor_code"), hex_u8(os_desc.vendor_code))?;
                fs::write(os_desc_dir.join("qw_sign"), &os_desc.qw_sign)?;
                fs::write(os_desc_dir.join("use"), "1")?;

                let config_dir = config_dirs.get(os_desc.config).ok_or_else(|| {
                    Error::new(ErrorKind::InvalidInput, "invalid configuration index in OS descriptor")
                })?;
                log::debug!("linking OS descriptor to config dir {}", config_dir.display());
                symlink(config_dir, os_desc_dir.join(config_dir.file_name().unwrap()))?;
            } else {
                log::warn!("USB OS descriptor is unsupported by kernel");
            }
        }

        log::debug!("gadget at {} registered", dir.display());
        Ok(RegGadget { dir, attached: true, func_dirs })
    }

    /// Register and bind USB gadget to a USB device controller (UDC).
    ///
    /// At least one [configuration](Config) must be added before the gadget
    /// can be bound.
    #[must_use = "consumes the gadget"]
    pub fn bind(self, udc: &Udc) -> Result<RegGadget> {
        let reg = self.register()?;
        reg.bind(Some(udc))?;
        Ok(reg)
    }
}

/// USB gadget registered with the system.
///
/// A function instance registered in a USB gadget.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RegFunction {
    /// Function driver name, e.g. "acm", "ecm", "mass_storage".
    driver: String,
    /// Instance name, e.g. "composite-0".
    instance: String,
}

impl RegFunction {
    /// Function driver name, e.g. "acm", "ecm", "mass_storage".
    pub fn driver(&self) -> &str {
        &self.driver
    }

    /// Instance name, e.g. "composite-0".
    pub fn instance(&self) -> &str {
        &self.instance
    }
}

impl fmt::Display for RegFunction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}.{}", self.driver, self.instance)
    }
}

/// If this was obtained by calling [`Gadget::bind`], the USB gadget will be
/// unbound and removed when this is dropped.
///
/// Call [`registered`] to obtain all gadgets registered on the system.
#[must_use = "The USB gadget is removed when RegGadget is dropped."]
pub struct RegGadget {
    dir: PathBuf,
    attached: bool,
    func_dirs: HashMap<Handle, PathBuf>,
}

impl fmt::Debug for RegGadget {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("RegGadget").field("name", &self.name()).field("is_attached", &self.is_attached()).finish()
    }
}

impl RegGadget {
    /// Name of this USB gadget in configfs.
    pub fn name(&self) -> &OsStr {
        self.dir.file_name().unwrap()
    }

    /// Path of this USB gadget in configfs.
    pub fn path(&self) -> &Path {
        &self.dir
    }

    /// If true, the USB gadget will be removed when this is dropped.
    pub fn is_attached(&self) -> bool {
        self.attached
    }

    /// The name of the USB device controller (UDC) this gadget is bound to.
    pub fn udc(&self) -> Result<Option<OsString>> {
        let data = OsString::from_vec(fs::read(self.dir.join("UDC"))?);
        let data = trim_os_str(&data);
        if data.is_empty() {
            Ok(None)
        } else {
            Ok(Some(data.to_os_string()))
        }
    }

    /// Returns all function instances registered in this gadget.
    pub fn functions(&self) -> Result<Vec<RegFunction>> {
        let func_dir = self.dir.join("functions");
        let mut functions = Vec::new();

        if let Ok(entries) = fs::read_dir(&func_dir) {
            for entry in entries {
                let Ok(entry) = entry else { continue };
                if !entry.metadata()?.is_dir() {
                    continue;
                }
                let name = entry.file_name().to_string_lossy().to_string();
                if let Some((driver, instance)) = name.split_once('.') {
                    functions.push(RegFunction { driver: driver.to_string(), instance: instance.to_string() });
                }
            }
        }

        functions.sort();
        Ok(functions)
    }

    /// Binds the gadget to the specified USB device controller (UDC).
    ///
    /// If `udc` is `None`, the gadget is unbound from any UDC.
    pub fn bind(&self, udc: Option<&Udc>) -> Result<()> {
        log::debug!("binding gadget {:?} to {:?}", self, &udc);

        let name = match udc {
            Some(udc) => udc.name().to_os_string(),
            None => "\n".into(),
        };

        match fs::write(self.dir.join("UDC"), name.as_bytes()) {
            Ok(()) => (),
            Err(err) if udc.is_none() && err.raw_os_error() == Some(Errno::NODEV.raw_os_error()) => (),
            Err(err) => return Err(err),
        }

        for func in self.func_dirs.keys() {
            func.get().dir().set_bound(udc.is_some());
        }

        Ok(())
    }

    /// Detach the handle from the USB gadget while keeping the USB gadget active.
    ///
    /// This prevents the USB gadget from being deregistered when this handle is dropped.
    pub fn detach(&mut self) {
        self.attached = false;
    }

    fn do_remove(&mut self) -> Result<()> {
        for func in self.func_dirs.keys() {
            func.get().pre_removal()?;
        }

        for func in self.func_dirs.keys() {
            func.get().dir().set_bound(false);
        }

        remove_at(&self.dir)?;

        for func in self.func_dirs.keys() {
            func.get().dir().reset_dir();
        }

        for (func, dir) in &self.func_dirs {
            func.get().post_removal(dir)?;
        }

        self.detach();
        Ok(())
    }

    /// Unbind from the UDC and remove the USB gadget.
    pub fn remove(mut self) -> Result<()> {
        self.do_remove()
    }
}

impl Drop for RegGadget {
    fn drop(&mut self) {
        if self.attached {
            if let Err(err) = self.do_remove() {
                log::warn!("removing gadget at {} failed: {err}", self.dir.display());
            }
        }
    }
}

/// Remove USB gadget at specified configfs gadget directory.
fn remove_at(dir: &Path) -> Result<()> {
    log::debug!("removing gadget at {}", dir.display());

    init_remove_handlers();

    let _ = fs::write(dir.join("UDC"), "\n");

    if let Ok(entries) = fs::read_dir(dir.join("os_desc")) {
        for file in entries {
            let Ok(file) = file else { continue };
            let Ok(file_type) = file.file_type() else { continue };
            if file_type.is_symlink() {
                fs::remove_file(file.path())?;
            }
        }
    }

    for config_dir in fs::read_dir(dir.join("configs"))? {
        let Ok(config_dir) = config_dir else { continue };
        if !config_dir.metadata()?.is_dir() {
            continue;
        }

        for func in fs::read_dir(config_dir.path())? {
            let Ok(func) = func else { continue };
            if func.metadata()?.is_symlink() {
                fs::remove_file(func.path())?;
            }
        }

        for lang in fs::read_dir(config_dir.path().join("strings"))? {
            let Ok(lang) = lang else { continue };
            if lang.metadata()?.is_dir() {
                fs::remove_dir(lang.path())?;
            }
        }

        fs::remove_dir(config_dir.path())?;
    }

    for func_dir in fs::read_dir(dir.join("functions"))? {
        let Ok(func_dir) = func_dir else { continue };
        if !func_dir.metadata()?.is_dir() {
            continue;
        }

        call_remove_handler(&func_dir.path())?;

        fs::remove_dir(func_dir.path())?;
    }

    for lang in fs::read_dir(dir.join("strings"))? {
        let Ok(lang) = lang else { continue };
        if lang.metadata()?.is_dir() {
            fs::remove_dir(lang.path())?;
        }
    }

    fs::remove_dir(dir)?;

    log::debug!("removed gadget at {}", dir.display());
    Ok(())
}

/// The path to the USB gadget configuration directory within configfs.
fn usb_gadget_dir() -> Result<PathBuf> {
    let _ = request_module("libcomposite");

    let usb_gadget_dir = configfs_dir()?.join("usb_gadget");
    if usb_gadget_dir.is_dir() {
        Ok(usb_gadget_dir)
    } else {
        Err(Error::new(ErrorKind::NotFound, "usb_gadget not found in configfs"))
    }
}

/// Get all USB gadgets registered on the system.
///
/// This returns all USB gadgets, including gadgets not created by the running program or
/// registered by other means than using this library.
pub fn registered() -> Result<Vec<RegGadget>> {
    let usb_gadget_dir = usb_gadget_dir()?;

    let mut gadgets = Vec::new();
    for gadget_dir in fs::read_dir(usb_gadget_dir)? {
        let Ok(gadget_dir) = gadget_dir else { continue };
        if gadget_dir.metadata()?.is_dir() {
            gadgets.push(RegGadget { dir: gadget_dir.path(), attached: false, func_dirs: HashMap::new() });
        }
    }

    Ok(gadgets)
}

/// Remove all USB gadgets defined on the system.
///
/// This removes all USB gadgets, including gadgets not created by the running program or
/// registered by other means than using this library.
pub fn remove_all() -> Result<()> {
    let mut res = Ok(());

    for gadget in registered()? {
        if let Err(err) = gadget.remove() {
            res = Err(err);
        }
    }

    res
}

/// Unbind all USB gadgets defined on the system.
///
/// This unbinds all USB gadgets, including gadgets not created by the running program or
/// registered by other means than using this library.
pub fn unbind_all() -> Result<()> {
    let mut res = Ok(());

    for gadget in registered()? {
        if let Err(err) = gadget.bind(None) {
            res = Err(err);
        }
    }

    res
}