use std::ffi::{c_int, c_void};
pub const AF_BLUETOOTH: c_int = 31;
pub const SOCK_SEQPACKET: c_int = 5;
pub const SOCK_STREAM: c_int = 1;
pub const SOCK_RAW: c_int = 3;
pub const BTPROTO_L2CAP: c_int = 0;
pub const BTPROTO_RFCOMM: c_int = 3;
pub const SOL_BLUETOOTH: c_int = 274;
pub const BT_SECURITY: c_int = 4;
pub const BT_SNDMTU: c_int = 12;
pub const BT_RCVMTU: c_int = 13;
pub const EMSGSIZE: i32 = 90;
#[allow(dead_code)]
pub const BT_SECURITY_SDP: u8 = 0;
pub const BT_SECURITY_LOW: u8 = 1;
pub const BT_SECURITY_MEDIUM: u8 = 2;
pub const BT_SECURITY_HIGH: u8 = 3;
pub const BT_SECURITY_FIPS: u8 = 4;
pub const BTPROTO_HCI: c_int = 1;
pub const BDADDR_LE_PUBLIC: u8 = 1;
pub const BDADDR_ANY: [u8; 6] = [0; 6];
pub const BDADDR_LE_RANDOM: u8 = 2;
pub const SHUT_RDWR: c_int = 2;
pub const EINTR: i32 = 4;
pub const EBUSY: i32 = 16;
pub const ECONNRESET: i32 = 104;
unsafe extern "C" {
pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int;
#[link_name = "read"]
fn libc_read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
#[link_name = "write"]
fn libc_write(fd: c_int, buf: *const c_void, count: usize) -> isize;
pub fn close(fd: c_int) -> c_int;
pub fn shutdown(fd: c_int, how: c_int) -> c_int;
#[link_name = "setsockopt"]
pub fn bluetooth_setsockopt(
fd: c_int,
level: c_int,
option: c_int,
value: *const core::ffi::c_void,
length: u32,
) -> c_int;
#[link_name = "getsockopt"]
pub fn bluetooth_getsockopt(
fd: c_int,
level: c_int,
option: c_int,
value: *mut core::ffi::c_void,
length: *mut u32,
) -> c_int;
fn __errno_location() -> *mut c_int;
}
pub fn bluetooth_u16_option(fd: c_int, option: c_int) -> Option<u16> {
let mut value = 0u16;
let mut length = std::mem::size_of::<u16>() as u32;
let rc = unsafe {
bluetooth_getsockopt(fd, SOL_BLUETOOTH, option, (&raw mut value).cast(), &mut length)
};
(rc == 0 && value > 0).then_some(value)
}
pub unsafe fn read(fd: c_int, buf: *mut u8, count: usize) -> isize {
unsafe { libc_read(fd, buf.cast(), count) }
}
pub unsafe fn write(fd: c_int, buf: *const u8, count: usize) -> isize {
unsafe { libc_write(fd, buf.cast(), count) }
}
pub fn set_le_security(fd: c_int, encryption_required: bool) -> Result<(), i32> {
let level = if encryption_required { BT_SECURITY_MEDIUM } else { BT_SECURITY_LOW };
let value = [level, 0];
let result = unsafe {
bluetooth_setsockopt(
fd,
SOL_BLUETOOTH,
BT_SECURITY,
value.as_ptr().cast(),
value.len() as u32,
)
};
if result == 0 {
Ok(())
} else {
Err(errno())
}
}
#[cfg(feature = "classic")]
pub fn set_classic_security(
fd: c_int,
security: webbluetooth_core::classic::ClassicSecurity,
) -> Result<(), i32> {
let level = match security {
webbluetooth_core::classic::ClassicSecurity::None => BT_SECURITY_LOW,
webbluetooth_core::classic::ClassicSecurity::Authentication => BT_SECURITY_LOW,
webbluetooth_core::classic::ClassicSecurity::Encryption => BT_SECURITY_MEDIUM,
webbluetooth_core::classic::ClassicSecurity::SecureEncryption => BT_SECURITY_FIPS,
};
let value = [level, 0];
let result = unsafe {
bluetooth_setsockopt(
fd,
SOL_BLUETOOTH,
BT_SECURITY,
value.as_ptr().cast(),
value.len() as u32,
)
};
if result == 0 {
Ok(())
} else {
Err(errno())
}
}
pub fn errno() -> i32 {
unsafe { *__errno_location() }
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct SockAddrL2 {
pub family: u16,
pub psm: u16,
pub bdaddr: [u8; 6],
pub cid: u16,
pub bdaddr_type: u8,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct SockAddrRc {
pub family: u16,
pub bdaddr: [u8; 6],
pub channel: u8,
}
unsafe extern "C" {
pub fn connect(fd: c_int, addr: *const SockAddrL2, len: u32) -> c_int;
pub fn listen(fd: c_int, backlog: c_int) -> c_int;
pub fn accept(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
pub fn bind(fd: c_int, addr: *const core::ffi::c_void, len: u32) -> c_int;
pub fn getsockname(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
fn poll(fds: *mut PollFd, nfds: core::ffi::c_ulong, timeout: c_int) -> c_int;
}
pub fn parse_address(address: &str) -> Option<[u8; 6]> {
let parts: Vec<&str> = address.split(':').collect();
if parts.len() != 6 {
return None;
}
let mut out = [0u8; 6];
for (i, part) in parts.iter().enumerate() {
out[5 - i] = u8::from_str_radix(part, 16).ok()?;
}
Some(out)
}
pub fn format_address(wire: &[u8; 6]) -> String {
let mut out = String::with_capacity(17);
for (i, b) in wire.iter().rev().enumerate() {
if i > 0 {
out.push(':');
}
out.push_str(&format!("{b:02X}"));
}
out
}
#[repr(C)]
struct PollFd {
fd: c_int,
events: i16,
revents: i16,
}
pub const POLLIN: i16 = 0x001;
pub const POLLOUT: i16 = 0x004;
const POLLERR: i16 = 0x008;
const POLLHUP: i16 = 0x010;
#[derive(Debug, PartialEq, Eq)]
pub enum Ready {
Yes,
TimedOut,
Closed,
}
pub fn wait_ready(fd: c_int, events: i16, timeout_ms: c_int) -> Result<Ready, i32> {
let mut fds = PollFd {
fd,
events,
revents: 0,
};
loop {
let rc = unsafe { poll(&mut fds, 1, timeout_ms) };
if rc < 0 {
let e = errno();
if e == EINTR {
continue;
}
return Err(e);
}
if rc == 0 {
return Ok(Ready::TimedOut);
}
if fds.revents & (POLLERR | POLLHUP) != 0 {
return Ok(Ready::Closed);
}
return Ok(Ready::Yes);
}
}
pub fn address_type(random: bool) -> u8 {
if random {
BDADDR_LE_RANDOM
} else {
BDADDR_LE_PUBLIC
}
}
pub fn bind_le_source(fd: c_int, psm: u16, cid: u16) -> Result<(), i32> {
let addr = SockAddrL2 {
family: AF_BLUETOOTH as u16,
psm: psm.to_le(),
bdaddr: BDADDR_ANY,
cid: cid.to_le(),
bdaddr_type: BDADDR_LE_PUBLIC,
};
let len = core::mem::size_of::<SockAddrL2>() as u32;
if unsafe { bind(fd, (&raw const addr).cast(), len) } < 0 {
return Err(errno());
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn the_rfcomm_socket_address_matches_the_kernel_layout() {
assert_eq!(std::mem::size_of::<SockAddrRc>(), 10);
assert_eq!(std::mem::offset_of!(SockAddrRc, family), 0);
assert_eq!(std::mem::offset_of!(SockAddrRc, bdaddr), 2);
assert_eq!(std::mem::offset_of!(SockAddrRc, channel), 8);
}
use super::*;
#[test]
fn addresses_are_reversed_onto_the_wire() {
assert_eq!(
parse_address("AA:BB:CC:DD:EE:FF"),
Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
);
assert_eq!(
parse_address("00:00:00:00:00:01"),
Some([0x01, 0, 0, 0, 0, 0])
);
}
#[test]
fn formatting_is_the_inverse_of_parsing() {
let written = "AA:BB:CC:DD:EE:FF";
assert_eq!(format_address(&parse_address(written).unwrap()), written);
}
#[test]
fn malformed_addresses_are_rejected() {
for bad in [
"",
"AA:BB:CC:DD:EE",
"AA:BB:CC:DD:EE:FF:00",
"ZZ:BB:CC:DD:EE:FF",
] {
assert_eq!(parse_address(bad), None, "{bad:?} should not parse");
}
}
#[test]
fn the_socket_address_matches_the_kernel_layout() {
assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
}
}