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;
17pub const BT_SNDMTU: c_int = 12;
19pub const BT_RCVMTU: c_int = 13;
21pub const EMSGSIZE: i32 = 90;
22#[allow(dead_code)]
24pub const BT_SECURITY_SDP: u8 = 0;
25pub const BT_SECURITY_LOW: u8 = 1;
26pub const BT_SECURITY_MEDIUM: u8 = 2;
27pub const BT_SECURITY_HIGH: u8 = 3;
28pub const BT_SECURITY_FIPS: u8 = 4;
29pub const BTPROTO_HCI: c_int = 1;
30pub const BDADDR_LE_PUBLIC: u8 = 1;
31pub const BDADDR_ANY: [u8; 6] = [0; 6];
33pub const BDADDR_LE_RANDOM: u8 = 2;
34pub const SHUT_RDWR: c_int = 2;
35pub const EINTR: i32 = 4;
37pub const EBUSY: i32 = 16;
39pub const ECONNRESET: i32 = 104;
41
42unsafe extern "C" {
43 pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int;
44 #[link_name = "read"]
49 fn libc_read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
50 #[link_name = "write"]
51 fn libc_write(fd: c_int, buf: *const c_void, count: usize) -> isize;
52 pub fn close(fd: c_int) -> c_int;
53 pub fn shutdown(fd: c_int, how: c_int) -> c_int;
54 #[link_name = "setsockopt"]
59 pub fn bluetooth_setsockopt(
60 fd: c_int,
61 level: c_int,
62 option: c_int,
63 value: *const core::ffi::c_void,
64 length: u32,
65 ) -> c_int;
66 #[link_name = "getsockopt"]
68 pub fn bluetooth_getsockopt(
69 fd: c_int,
70 level: c_int,
71 option: c_int,
72 value: *mut core::ffi::c_void,
73 length: *mut u32,
74 ) -> c_int;
75 fn __errno_location() -> *mut c_int;
76}
77
78pub fn bluetooth_u16_option(fd: c_int, option: c_int) -> Option<u16> {
80 let mut value = 0u16;
81 let mut length = std::mem::size_of::<u16>() as u32;
82 let rc = unsafe {
83 bluetooth_getsockopt(fd, SOL_BLUETOOTH, option, (&raw mut value).cast(), &mut length)
84 };
85 (rc == 0 && value > 0).then_some(value)
86}
87
88pub unsafe fn read(fd: c_int, buf: *mut u8, count: usize) -> isize {
93 unsafe { libc_read(fd, buf.cast(), count) }
94}
95
96pub unsafe fn write(fd: c_int, buf: *const u8, count: usize) -> isize {
101 unsafe { libc_write(fd, buf.cast(), count) }
102}
103
104pub fn set_le_security(fd: c_int, encryption_required: bool) -> Result<(), i32> {
108 let level = if encryption_required { BT_SECURITY_MEDIUM } else { BT_SECURITY_LOW };
109 let value = [level, 0];
110 let result = unsafe {
111 bluetooth_setsockopt(
112 fd,
113 SOL_BLUETOOTH,
114 BT_SECURITY,
115 value.as_ptr().cast(),
116 value.len() as u32,
117 )
118 };
119 if result == 0 {
120 Ok(())
121 } else {
122 Err(errno())
123 }
124}
125
126#[cfg(feature = "classic")]
128pub fn set_classic_security(
129 fd: c_int,
130 security: webbluetooth_core::classic::ClassicSecurity,
131) -> Result<(), i32> {
132 let level = match security {
133 webbluetooth_core::classic::ClassicSecurity::None => BT_SECURITY_LOW,
142 webbluetooth_core::classic::ClassicSecurity::Authentication => BT_SECURITY_LOW,
143 webbluetooth_core::classic::ClassicSecurity::Encryption => BT_SECURITY_MEDIUM,
144 webbluetooth_core::classic::ClassicSecurity::SecureEncryption => BT_SECURITY_FIPS,
145 };
146 let value = [level, 0];
147 let result = unsafe {
148 bluetooth_setsockopt(
149 fd,
150 SOL_BLUETOOTH,
151 BT_SECURITY,
152 value.as_ptr().cast(),
153 value.len() as u32,
154 )
155 };
156 if result == 0 {
157 Ok(())
158 } else {
159 Err(errno())
160 }
161}
162
163pub fn errno() -> i32 {
165 unsafe { *__errno_location() }
166}
167
168#[repr(C, packed)]
173#[derive(Clone, Copy)]
174pub struct SockAddrL2 {
175 pub family: u16,
176 pub psm: u16,
177 pub bdaddr: [u8; 6],
178 pub cid: u16,
179 pub bdaddr_type: u8,
180}
181
182#[repr(C)]
191#[derive(Clone, Copy)]
192pub struct SockAddrRc {
193 pub family: u16,
194 pub bdaddr: [u8; 6],
195 pub channel: u8,
196}
197
198unsafe extern "C" {
199 pub fn connect(fd: c_int, addr: *const SockAddrL2, len: u32) -> c_int;
200 pub fn listen(fd: c_int, backlog: c_int) -> c_int;
201 pub fn accept(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
202 pub fn bind(fd: c_int, addr: *const core::ffi::c_void, len: u32) -> c_int;
207 pub fn getsockname(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
208 fn poll(fds: *mut PollFd, nfds: core::ffi::c_ulong, timeout: c_int) -> c_int;
209}
210
211pub fn parse_address(address: &str) -> Option<[u8; 6]> {
218 let parts: Vec<&str> = address.split(':').collect();
219 if parts.len() != 6 {
220 return None;
221 }
222 let mut out = [0u8; 6];
223 for (i, part) in parts.iter().enumerate() {
224 out[5 - i] = u8::from_str_radix(part, 16).ok()?;
225 }
226 Some(out)
227}
228
229pub fn format_address(wire: &[u8; 6]) -> String {
231 let mut out = String::with_capacity(17);
232 for (i, b) in wire.iter().rev().enumerate() {
233 if i > 0 {
234 out.push(':');
235 }
236 out.push_str(&format!("{b:02X}"));
237 }
238 out
239}
240
241#[repr(C)]
242struct PollFd {
243 fd: c_int,
244 events: i16,
245 revents: i16,
246}
247
248pub const POLLIN: i16 = 0x001;
249pub const POLLOUT: i16 = 0x004;
250const POLLERR: i16 = 0x008;
251const POLLHUP: i16 = 0x010;
252
253#[derive(Debug, PartialEq, Eq)]
255pub enum Ready {
256 Yes,
257 TimedOut,
258 Closed,
260}
261
262pub fn wait_ready(fd: c_int, events: i16, timeout_ms: c_int) -> Result<Ready, i32> {
270 let mut fds = PollFd {
271 fd,
272 events,
273 revents: 0,
274 };
275 loop {
276 let rc = unsafe { poll(&mut fds, 1, timeout_ms) };
277 if rc < 0 {
278 let e = errno();
279 if e == EINTR {
280 continue;
281 }
282 return Err(e);
283 }
284 if rc == 0 {
285 return Ok(Ready::TimedOut);
286 }
287 if fds.revents & (POLLERR | POLLHUP) != 0 {
288 return Ok(Ready::Closed);
289 }
290 return Ok(Ready::Yes);
291 }
292}
293
294pub fn address_type(random: bool) -> u8 {
296 if random {
297 BDADDR_LE_RANDOM
298 } else {
299 BDADDR_LE_PUBLIC
300 }
301}
302
303pub fn bind_le_source(fd: c_int, psm: u16, cid: u16) -> Result<(), i32> {
313 let addr = SockAddrL2 {
314 family: AF_BLUETOOTH as u16,
315 psm: psm.to_le(),
316 bdaddr: BDADDR_ANY,
317 cid: cid.to_le(),
318 bdaddr_type: BDADDR_LE_PUBLIC,
319 };
320 let len = core::mem::size_of::<SockAddrL2>() as u32;
321 if unsafe { bind(fd, (&raw const addr).cast(), len) } < 0 {
322 return Err(errno());
323 }
324 Ok(())
325}
326
327#[cfg(test)]
328mod tests {
329
330 #[test]
331 fn the_rfcomm_socket_address_matches_the_kernel_layout() {
332 assert_eq!(std::mem::size_of::<SockAddrRc>(), 10);
335 assert_eq!(std::mem::offset_of!(SockAddrRc, family), 0);
336 assert_eq!(std::mem::offset_of!(SockAddrRc, bdaddr), 2);
337 assert_eq!(std::mem::offset_of!(SockAddrRc, channel), 8);
338 }
339
340 use super::*;
341
342 #[test]
343 fn addresses_are_reversed_onto_the_wire() {
344 assert_eq!(
345 parse_address("AA:BB:CC:DD:EE:FF"),
346 Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
347 );
348 assert_eq!(
349 parse_address("00:00:00:00:00:01"),
350 Some([0x01, 0, 0, 0, 0, 0])
351 );
352 }
353
354 #[test]
355 fn formatting_is_the_inverse_of_parsing() {
356 let written = "AA:BB:CC:DD:EE:FF";
357 assert_eq!(format_address(&parse_address(written).unwrap()), written);
358 }
359
360 #[test]
361 fn malformed_addresses_are_rejected() {
362 for bad in [
363 "",
364 "AA:BB:CC:DD:EE",
365 "AA:BB:CC:DD:EE:FF:00",
366 "ZZ:BB:CC:DD:EE:FF",
367 ] {
368 assert_eq!(parse_address(bad), None, "{bad:?} should not parse");
369 }
370 }
371
372 #[test]
373 fn the_socket_address_matches_the_kernel_layout() {
374 assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
375 }
376}