1use std::ffi::{c_int, c_void};
8
9pub const AF_BLUETOOTH: c_int = 31;
10pub const SOCK_SEQPACKET: c_int = 5;
11pub const SOCK_STREAM: c_int = 1;
12pub const SOCK_RAW: c_int = 3;
13pub const BTPROTO_L2CAP: c_int = 0;
14pub const BTPROTO_RFCOMM: c_int = 3;
15pub const SOL_BLUETOOTH: c_int = 274;
16pub const BT_SECURITY: c_int = 4;
17#[allow(dead_code)]
19pub const BT_SECURITY_SDP: u8 = 0;
20pub const BT_SECURITY_LOW: u8 = 1;
21pub const BT_SECURITY_MEDIUM: u8 = 2;
22pub const BT_SECURITY_HIGH: u8 = 3;
23pub const BT_SECURITY_FIPS: u8 = 4;
24pub const BTPROTO_HCI: c_int = 1;
25pub const BDADDR_LE_PUBLIC: u8 = 1;
26pub const BDADDR_ANY: [u8; 6] = [0; 6];
28pub const BDADDR_LE_RANDOM: u8 = 2;
29pub const SHUT_RDWR: c_int = 2;
30pub const EINTR: i32 = 4;
32pub const EBUSY: i32 = 16;
34pub const ECONNRESET: i32 = 104;
36
37unsafe extern "C" {
38 pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int;
39 #[link_name = "read"]
44 fn libc_read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
45 #[link_name = "write"]
46 fn libc_write(fd: c_int, buf: *const c_void, count: usize) -> isize;
47 pub fn close(fd: c_int) -> c_int;
48 pub fn shutdown(fd: c_int, how: c_int) -> c_int;
49 #[link_name = "setsockopt"]
54 pub fn bluetooth_setsockopt(
55 fd: c_int,
56 level: c_int,
57 option: c_int,
58 value: *const core::ffi::c_void,
59 length: u32,
60 ) -> c_int;
61 fn __errno_location() -> *mut c_int;
62}
63
64pub unsafe fn read(fd: c_int, buf: *mut u8, count: usize) -> isize {
69 unsafe { libc_read(fd, buf.cast(), count) }
70}
71
72pub unsafe fn write(fd: c_int, buf: *const u8, count: usize) -> isize {
77 unsafe { libc_write(fd, buf.cast(), count) }
78}
79
80#[cfg(feature = "classic")]
82pub fn set_classic_security(
83 fd: c_int,
84 security: webbluetooth_core::classic::ClassicSecurity,
85) -> Result<(), i32> {
86 let level = match security {
87 webbluetooth_core::classic::ClassicSecurity::None => BT_SECURITY_LOW,
96 webbluetooth_core::classic::ClassicSecurity::Authentication => BT_SECURITY_LOW,
97 webbluetooth_core::classic::ClassicSecurity::Encryption => BT_SECURITY_MEDIUM,
98 webbluetooth_core::classic::ClassicSecurity::SecureEncryption => BT_SECURITY_FIPS,
99 };
100 let value = [level, 0];
101 let result = unsafe {
102 bluetooth_setsockopt(
103 fd,
104 SOL_BLUETOOTH,
105 BT_SECURITY,
106 value.as_ptr().cast(),
107 value.len() as u32,
108 )
109 };
110 if result == 0 {
111 Ok(())
112 } else {
113 Err(errno())
114 }
115}
116
117pub fn errno() -> i32 {
119 unsafe { *__errno_location() }
120}
121
122#[repr(C, packed)]
127#[derive(Clone, Copy)]
128pub struct SockAddrL2 {
129 pub family: u16,
130 pub psm: u16,
131 pub bdaddr: [u8; 6],
132 pub cid: u16,
133 pub bdaddr_type: u8,
134}
135
136#[repr(C)]
145#[derive(Clone, Copy)]
146pub struct SockAddrRc {
147 pub family: u16,
148 pub bdaddr: [u8; 6],
149 pub channel: u8,
150}
151
152unsafe extern "C" {
153 pub fn connect(fd: c_int, addr: *const SockAddrL2, len: u32) -> c_int;
154 pub fn listen(fd: c_int, backlog: c_int) -> c_int;
155 pub fn accept(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
156 pub fn bind(fd: c_int, addr: *const core::ffi::c_void, len: u32) -> c_int;
161 pub fn getsockname(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
162 fn poll(fds: *mut PollFd, nfds: core::ffi::c_ulong, timeout: c_int) -> c_int;
163}
164
165pub fn parse_address(address: &str) -> Option<[u8; 6]> {
172 let parts: Vec<&str> = address.split(':').collect();
173 if parts.len() != 6 {
174 return None;
175 }
176 let mut out = [0u8; 6];
177 for (i, part) in parts.iter().enumerate() {
178 out[5 - i] = u8::from_str_radix(part, 16).ok()?;
179 }
180 Some(out)
181}
182
183pub fn format_address(wire: &[u8; 6]) -> String {
185 let mut out = String::with_capacity(17);
186 for (i, b) in wire.iter().rev().enumerate() {
187 if i > 0 {
188 out.push(':');
189 }
190 out.push_str(&format!("{b:02X}"));
191 }
192 out
193}
194
195#[repr(C)]
196struct PollFd {
197 fd: c_int,
198 events: i16,
199 revents: i16,
200}
201
202pub const POLLIN: i16 = 0x001;
203pub const POLLOUT: i16 = 0x004;
204const POLLERR: i16 = 0x008;
205const POLLHUP: i16 = 0x010;
206
207#[derive(Debug, PartialEq, Eq)]
209pub enum Ready {
210 Yes,
211 TimedOut,
212 Closed,
214}
215
216pub fn wait_ready(fd: c_int, events: i16, timeout_ms: c_int) -> Result<Ready, i32> {
224 let mut fds = PollFd {
225 fd,
226 events,
227 revents: 0,
228 };
229 loop {
230 let rc = unsafe { poll(&mut fds, 1, timeout_ms) };
231 if rc < 0 {
232 let e = errno();
233 if e == EINTR {
234 continue;
235 }
236 return Err(e);
237 }
238 if rc == 0 {
239 return Ok(Ready::TimedOut);
240 }
241 if fds.revents & (POLLERR | POLLHUP) != 0 {
242 return Ok(Ready::Closed);
243 }
244 return Ok(Ready::Yes);
245 }
246}
247
248pub fn address_type(random: bool) -> u8 {
250 if random {
251 BDADDR_LE_RANDOM
252 } else {
253 BDADDR_LE_PUBLIC
254 }
255}
256
257pub fn bind_le_source(fd: c_int, psm: u16, cid: u16) -> Result<(), i32> {
267 let addr = SockAddrL2 {
268 family: AF_BLUETOOTH as u16,
269 psm: psm.to_le(),
270 bdaddr: BDADDR_ANY,
271 cid: cid.to_le(),
272 bdaddr_type: BDADDR_LE_PUBLIC,
273 };
274 let len = core::mem::size_of::<SockAddrL2>() as u32;
275 if unsafe { bind(fd, (&raw const addr).cast(), len) } < 0 {
276 return Err(errno());
277 }
278 Ok(())
279}
280
281#[cfg(test)]
282mod tests {
283
284 #[test]
285 fn the_rfcomm_socket_address_matches_the_kernel_layout() {
286 assert_eq!(std::mem::size_of::<SockAddrRc>(), 10);
289 assert_eq!(std::mem::offset_of!(SockAddrRc, family), 0);
290 assert_eq!(std::mem::offset_of!(SockAddrRc, bdaddr), 2);
291 assert_eq!(std::mem::offset_of!(SockAddrRc, channel), 8);
292 }
293
294 use super::*;
295
296 #[test]
297 fn addresses_are_reversed_onto_the_wire() {
298 assert_eq!(
299 parse_address("AA:BB:CC:DD:EE:FF"),
300 Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
301 );
302 assert_eq!(
303 parse_address("00:00:00:00:00:01"),
304 Some([0x01, 0, 0, 0, 0, 0])
305 );
306 }
307
308 #[test]
309 fn formatting_is_the_inverse_of_parsing() {
310 let written = "AA:BB:CC:DD:EE:FF";
311 assert_eq!(format_address(&parse_address(written).unwrap()), written);
312 }
313
314 #[test]
315 fn malformed_addresses_are_rejected() {
316 for bad in [
317 "",
318 "AA:BB:CC:DD:EE",
319 "AA:BB:CC:DD:EE:FF:00",
320 "ZZ:BB:CC:DD:EE:FF",
321 ] {
322 assert_eq!(parse_address(bad), None, "{bad:?} should not parse");
323 }
324 }
325
326 #[test]
327 fn the_socket_address_matches_the_kernel_layout() {
328 assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
329 }
330}