| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
#![cfg_attr(feature = "cargo-clippy", allow(clippy::cast_lossless))] |
| 5 |
|
| 6 |
extern crate libc; |
| 7 |
|
| 8 |
use std::io; |
| 9 |
use std::os::unix::io::RawFd; |
| 10 |
|
| 11 |
use super::hidwrapper::{_HIDIOCGRDESC, _HIDIOCGRDESCSIZE}; |
| 12 |
use crate::consts::MAX_HID_RPT_SIZE; |
| 13 |
use crate::transport::hidproto::*; |
| 14 |
use crate::util::{from_unix_result, io_err}; |
| 15 |
|
| 16 |
#[allow(non_camel_case_types)] |
| 17 |
#[repr(C)] |
| 18 |
pub struct LinuxReportDescriptor { |
| 19 |
size: ::libc::c_int, |
| 20 |
value: [u8; 4096], |
| 21 |
} |
| 22 |
|
| 23 |
const HID_MAX_DESCRIPTOR_SIZE: usize = 4096; |
| 24 |
|
| 25 |
#[cfg(not(target_env = "musl"))] |
| 26 |
type IocType = libc::c_ulong; |
| 27 |
#[cfg(target_env = "musl")] |
| 28 |
type IocType = libc::c_int; |
| 29 |
|
| 30 |
pub unsafe fn hidiocgrdescsize( |
| 31 |
fd: libc::c_int, |
| 32 |
val: *mut ::libc::c_int, |
| 33 |
) -> io::Result<libc::c_int> { |
| 34 |
from_unix_result(libc::ioctl(fd, _HIDIOCGRDESCSIZE as IocType, val)) |
| 35 |
} |
| 36 |
|
| 37 |
pub unsafe fn hidiocgrdesc( |
| 38 |
fd: libc::c_int, |
| 39 |
val: *mut LinuxReportDescriptor, |
| 40 |
) -> io::Result<libc::c_int> { |
| 41 |
from_unix_result(libc::ioctl(fd, _HIDIOCGRDESC as IocType, val)) |
| 42 |
} |
| 43 |
|
| 44 |
pub fn is_u2f_device(fd: RawFd) -> bool { |
| 45 |
match read_report_descriptor(fd) { |
| 46 |
Ok(desc) => has_fido_usage(desc), |
| 47 |
Err(_) => false, // Upon failure, just say it's not a U2F device. |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
pub fn read_hid_rpt_sizes_or_defaults(fd: RawFd) -> (usize, usize) { |
| 52 |
let default_rpt_sizes = (MAX_HID_RPT_SIZE, MAX_HID_RPT_SIZE); |
| 53 |
let desc = read_report_descriptor(fd); |
| 54 |
if let Ok(desc) = desc { |
| 55 |
if let Ok(rpt_sizes) = read_hid_rpt_sizes(desc) { |
| 56 |
rpt_sizes |
| 57 |
} else { |
| 58 |
default_rpt_sizes |
| 59 |
} |
| 60 |
} else { |
| 61 |
default_rpt_sizes |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
fn read_report_descriptor(fd: RawFd) -> io::Result<ReportDescriptor> { |
| 66 |
let mut desc = LinuxReportDescriptor { |
| 67 |
size: 0, |
| 68 |
value: [0; HID_MAX_DESCRIPTOR_SIZE], |
| 69 |
}; |
| 70 |
|
| 71 |
let _ = unsafe { hidiocgrdescsize(fd, &mut desc.size)? }; |
| 72 |
if desc.size == 0 || desc.size as usize > desc.value.len() { |
| 73 |
return Err(io_err("unexpected hidiocgrdescsize() result")); |
| 74 |
} |
| 75 |
|
| 76 |
let _ = unsafe { hidiocgrdesc(fd, &mut desc)? }; |
| 77 |
let mut value = Vec::from(&desc.value[..]); |
| 78 |
value.truncate(desc.size as usize); |
| 79 |
Ok(ReportDescriptor { value }) |
| 80 |
} |