webbluetooth_linux/
sys.rs1use std::ffi::c_int;
8
9pub const AF_BLUETOOTH: c_int = 31;
10pub const SOCK_SEQPACKET: c_int = 5;
11pub const SOCK_RAW: c_int = 3;
12pub const BTPROTO_L2CAP: c_int = 0;
13pub const BTPROTO_HCI: c_int = 1;
14pub const BDADDR_LE_PUBLIC: u8 = 1;
15pub const BDADDR_ANY: [u8; 6] = [0; 6];
17pub const BDADDR_LE_RANDOM: u8 = 2;
18pub const SHUT_RDWR: c_int = 2;
19pub const EINTR: i32 = 4;
21
22unsafe extern "C" {
23 pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int;
24 pub fn read(fd: c_int, buf: *mut u8, count: usize) -> isize;
25 pub fn write(fd: c_int, buf: *const u8, count: usize) -> isize;
26 pub fn close(fd: c_int) -> c_int;
27 pub fn shutdown(fd: c_int, how: c_int) -> c_int;
28 fn __errno_location() -> *mut c_int;
29}
30
31pub fn errno() -> i32 {
33 unsafe { *__errno_location() }
34}
35
36#[repr(C, packed)]
41#[derive(Clone, Copy)]
42pub struct SockAddrL2 {
43 pub family: u16,
44 pub psm: u16,
45 pub bdaddr: [u8; 6],
46 pub cid: u16,
47 pub bdaddr_type: u8,
48}
49
50unsafe extern "C" {
51 pub fn connect(fd: c_int, addr: *const SockAddrL2, len: u32) -> c_int;
52 pub fn bind(fd: c_int, addr: *const core::ffi::c_void, len: u32) -> c_int;
57 fn poll(fds: *mut PollFd, nfds: core::ffi::c_ulong, timeout: c_int) -> c_int;
58}
59
60pub fn parse_address(address: &str) -> Option<[u8; 6]> {
67 let parts: Vec<&str> = address.split(':').collect();
68 if parts.len() != 6 {
69 return None;
70 }
71 let mut out = [0u8; 6];
72 for (i, part) in parts.iter().enumerate() {
73 out[5 - i] = u8::from_str_radix(part, 16).ok()?;
74 }
75 Some(out)
76}
77
78pub fn format_address(wire: &[u8; 6]) -> String {
80 let mut out = String::with_capacity(17);
81 for (i, b) in wire.iter().rev().enumerate() {
82 if i > 0 {
83 out.push(':');
84 }
85 out.push_str(&format!("{b:02X}"));
86 }
87 out
88}
89
90#[repr(C)]
91struct PollFd {
92 fd: c_int,
93 events: i16,
94 revents: i16,
95}
96
97pub const POLLIN: i16 = 0x001;
98pub const POLLOUT: i16 = 0x004;
99const POLLERR: i16 = 0x008;
100const POLLHUP: i16 = 0x010;
101
102#[derive(Debug, PartialEq, Eq)]
104pub enum Ready {
105 Yes,
106 TimedOut,
107 Closed,
109}
110
111pub fn wait_ready(fd: c_int, events: i16, timeout_ms: c_int) -> Result<Ready, i32> {
119 let mut fds = PollFd {
120 fd,
121 events,
122 revents: 0,
123 };
124 loop {
125 let rc = unsafe { poll(&mut fds, 1, timeout_ms) };
126 if rc < 0 {
127 let e = errno();
128 if e == EINTR {
129 continue;
130 }
131 return Err(e);
132 }
133 if rc == 0 {
134 return Ok(Ready::TimedOut);
135 }
136 if fds.revents & (POLLERR | POLLHUP) != 0 {
137 return Ok(Ready::Closed);
138 }
139 return Ok(Ready::Yes);
140 }
141}
142
143pub fn address_type(random: bool) -> u8 {
145 if random {
146 BDADDR_LE_RANDOM
147 } else {
148 BDADDR_LE_PUBLIC
149 }
150}
151
152pub fn bind_le_source(fd: c_int, psm: u16, cid: u16) -> Result<(), i32> {
162 let addr = SockAddrL2 {
163 family: AF_BLUETOOTH as u16,
164 psm: psm.to_le(),
165 bdaddr: BDADDR_ANY,
166 cid: cid.to_le(),
167 bdaddr_type: BDADDR_LE_PUBLIC,
168 };
169 let len = core::mem::size_of::<SockAddrL2>() as u32;
170 if unsafe { bind(fd, (&raw const addr).cast(), len) } < 0 {
171 return Err(errno());
172 }
173 Ok(())
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 #[test]
181 fn addresses_are_reversed_onto_the_wire() {
182 assert_eq!(
183 parse_address("AA:BB:CC:DD:EE:FF"),
184 Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
185 );
186 assert_eq!(
187 parse_address("00:00:00:00:00:01"),
188 Some([0x01, 0, 0, 0, 0, 0])
189 );
190 }
191
192 #[test]
193 fn formatting_is_the_inverse_of_parsing() {
194 let written = "AA:BB:CC:DD:EE:FF";
195 assert_eq!(format_address(&parse_address(written).unwrap()), written);
196 }
197
198 #[test]
199 fn malformed_addresses_are_rejected() {
200 for bad in [
201 "",
202 "AA:BB:CC:DD:EE",
203 "AA:BB:CC:DD:EE:FF:00",
204 "ZZ:BB:CC:DD:EE:FF",
205 ] {
206 assert_eq!(parse_address(bad), None, "{bad:?} should not parse");
207 }
208 }
209
210 #[test]
211 fn the_socket_address_matches_the_kernel_layout() {
212 assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
213 }
214}