Path: blob/main/devices/src/usb/backend/fido_backend/hid_utils.rs
5394 views
// Copyright 2024 The ChromiumOS Authors1// Use of this source code is governed by a BSD-style license that can be2// found in the LICENSE file.34use std::fs::File;5use std::os::raw::c_int;67use base::handle_eintr_errno;8use base::ioctl_ior_nr;910use crate::usb::backend::fido_backend::constants;11use crate::usb::backend::fido_backend::error::Error;12use crate::usb::backend::fido_backend::error::Result;1314#[repr(C)]15#[derive(Clone)]16pub struct HidrawReportDescriptor {17pub size: u32,18pub value: [u8; constants::HID_MAX_DESCRIPTOR_SIZE],19}2021pub const HID_IO_TYPE: u32 = 'H' as u32;2223ioctl_ior_nr!(HIDIOCGRDESCSIZE, HID_IO_TYPE, 0x01, c_int);24ioctl_ior_nr!(HIDIOCGRDESC, HID_IO_TYPE, 0x02, HidrawReportDescriptor);2526/// Verifies that the given `hidraw` file handle is a valid FIDO device.27/// In case it is not, it returns an `InvalidHidrawDevice` erro.28pub fn verify_is_fido_device(hidraw: &File) -> Result<()> {29let mut desc_size: c_int = 0;30// SAFETY:31// Safe because:32// - We check the return value after the call.33// - ioctl(HIDIOCGRDDESCSIZE) does not hold the descriptor after the call.34unsafe {35let ret = handle_eintr_errno!(base::ioctl_with_mut_ref(36hidraw,37HIDIOCGRDESCSIZE,38&mut desc_size39));40if ret < 0 || (desc_size as usize) < constants::HID_REPORT_DESC_HEADER.len() {41return Err(Error::InvalidHidrawDevice);42}43}4445let mut descriptor = HidrawReportDescriptor {46size: desc_size as u32,47value: [0; constants::HID_MAX_DESCRIPTOR_SIZE],48};4950// SAFETY:51// Safe because:52// - We check the return value after the call.53// - ioctl(HIDIOCGRDESC) does not hold the descriptor after the call.54unsafe {55let ret = handle_eintr_errno!(base::ioctl_with_mut_ref(56hidraw,57HIDIOCGRDESC,58&mut descriptor59));60if ret < 0 {61return Err(Error::InvalidHidrawDevice);62}63}6465if descriptor.value[..constants::HID_REPORT_DESC_HEADER.len()]66!= *constants::HID_REPORT_DESC_HEADER67{68return Err(Error::InvalidHidrawDevice);69}70Ok(())71}727374