| 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 |
|
| 5 |
extern crate libc; |
| 6 |
|
| 7 |
use std::io; |
| 8 |
use std::mem; |
| 9 |
use std::os::raw::c_int; |
| 10 |
use std::os::raw::c_uchar; |
| 11 |
|
| 12 |
use crate::transport::hidproto::has_fido_usage; |
| 13 |
use crate::transport::hidproto::ReportDescriptor; |
| 14 |
use crate::transport::platform::fd::Fd; |
| 15 |
use crate::util::io_err; |
| 16 |
|
| 17 |
/* sys/ioccom.h */ |
| 18 |
|
| 19 |
const IOCPARM_MASK: u32 = 0x1fff; |
| 20 |
const IOCPARM_SHIFT: u32 = 16; |
| 21 |
const IOCGROUP_SHIFT: u32 = 8; |
| 22 |
|
| 23 |
//const IOC_VOID: u32 = 0x20000000; |
| 24 |
const IOC_OUT: u32 = 0x40000000; |
| 25 |
const IOC_IN: u32 = 0x80000000; |
| 26 |
//const IOC_INOUT: u32 = IOC_IN|IOC_OUT; |
| 27 |
|
| 28 |
macro_rules! ioctl { |
| 29 |
($dir:expr, $name:ident, $group:expr, $nr:expr, $ty:ty) => { |
| 30 |
unsafe fn $name(fd: libc::c_int, val: *mut $ty) -> io::Result<libc::c_int> { |
| 31 |
let ioc = ($dir as u32) |
| 32 |
| ((mem::size_of::<$ty>() as u32 & IOCPARM_MASK) << IOCPARM_SHIFT) |
| 33 |
| (($group as u32) << IOCGROUP_SHIFT) |
| 34 |
| ($nr as u32); |
| 35 |
let rv = libc::ioctl(fd, ioc as libc::c_ulong, val); |
| 36 |
if rv == -1 { |
| 37 |
return Err(io::Error::last_os_error()); |
| 38 |
} |
| 39 |
Ok(rv) |
| 40 |
} |
| 41 |
}; |
| 42 |
} |
| 43 |
|
| 44 |
#[allow(non_camel_case_types)] |
| 45 |
#[repr(C)] |
| 46 |
struct usb_ctl_report_desc { |
| 47 |
ucrd_size: c_int, |
| 48 |
ucrd_data: [c_uchar; 1024], |
| 49 |
} |
| 50 |
|
| 51 |
ioctl!(IOC_OUT, usb_get_report_desc, b'U', 21, usb_ctl_report_desc); |
| 52 |
|
| 53 |
fn read_report_descriptor(fd: &Fd) -> io::Result<ReportDescriptor> { |
| 54 |
let mut desc = unsafe { mem::zeroed() }; |
| 55 |
unsafe { usb_get_report_desc(fd.fileno, &mut desc) }?; |
| 56 |
if desc.ucrd_size < 0 { |
| 57 |
return Err(io_err("negative report descriptor size")); |
| 58 |
} |
| 59 |
let size = desc.ucrd_size as usize; |
| 60 |
let value = Vec::from(&desc.ucrd_data[..size]); |
| 61 |
Ok(ReportDescriptor { value }) |
| 62 |
} |
| 63 |
|
| 64 |
pub fn is_u2f_device(fd: &Fd) -> bool { |
| 65 |
match read_report_descriptor(fd) { |
| 66 |
Ok(desc) => has_fido_usage(desc), |
| 67 |
Err(_) => false, |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
ioctl!(IOC_IN, usb_hid_set_raw_ioctl, b'h', 2, c_int); |
| 72 |
|
| 73 |
pub fn hid_set_raw(fd: &Fd, raw: bool) -> io::Result<()> { |
| 74 |
let mut raw_int: c_int = if raw { 1 } else { 0 }; |
| 75 |
unsafe { usb_hid_set_raw_ioctl(fd.fileno, &mut raw_int) }?; |
| 76 |
Ok(()) |
| 77 |
} |