1use std::ffi::c_int;
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_SECURITY_SDP: u8 = 0;
18pub const BT_SECURITY_LOW: u8 = 1;
19pub const BT_SECURITY_MEDIUM: u8 = 2;
20pub const BT_SECURITY_HIGH: u8 = 3;
21pub const BT_SECURITY_FIPS: u8 = 4;
22pub const BTPROTO_HCI: c_int = 1;
23pub const BDADDR_LE_PUBLIC: u8 = 1;
24pub const BDADDR_ANY: [u8; 6] = [0; 6];
26pub const BDADDR_LE_RANDOM: u8 = 2;
27pub const SHUT_RDWR: c_int = 2;
28pub const EINTR: i32 = 4;
30
31unsafe extern "C" {
32 pub fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int;
33 pub fn read(fd: c_int, buf: *mut u8, count: usize) -> isize;
34 pub fn write(fd: c_int, buf: *const u8, count: usize) -> isize;
35 pub fn close(fd: c_int) -> c_int;
36 pub fn shutdown(fd: c_int, how: c_int) -> c_int;
37 #[link_name = "setsockopt"]
42 pub fn bluetooth_setsockopt(
43 fd: c_int,
44 level: c_int,
45 option: c_int,
46 value: *const core::ffi::c_void,
47 length: u32,
48 ) -> c_int;
49 fn __errno_location() -> *mut c_int;
50}
51
52#[cfg(feature = "classic")]
54pub fn set_classic_security(
55 fd: c_int,
56 security: webbluetooth_core::classic::ClassicSecurity,
57) -> Result<(), i32> {
58 let level = match security {
59 webbluetooth_core::classic::ClassicSecurity::None => BT_SECURITY_SDP,
60 webbluetooth_core::classic::ClassicSecurity::Authentication => BT_SECURITY_LOW,
61 webbluetooth_core::classic::ClassicSecurity::Encryption => BT_SECURITY_MEDIUM,
62 webbluetooth_core::classic::ClassicSecurity::SecureEncryption => BT_SECURITY_FIPS,
63 };
64 let value = [level, 0];
65 let result = unsafe {
66 bluetooth_setsockopt(
67 fd,
68 SOL_BLUETOOTH,
69 BT_SECURITY,
70 value.as_ptr().cast(),
71 value.len() as u32,
72 )
73 };
74 if result == 0 {
75 Ok(())
76 } else {
77 Err(errno())
78 }
79}
80
81pub fn errno() -> i32 {
83 unsafe { *__errno_location() }
84}
85
86#[repr(C, packed)]
91#[derive(Clone, Copy)]
92pub struct SockAddrL2 {
93 pub family: u16,
94 pub psm: u16,
95 pub bdaddr: [u8; 6],
96 pub cid: u16,
97 pub bdaddr_type: u8,
98}
99
100#[repr(C, packed)]
102#[derive(Clone, Copy)]
103pub struct SockAddrRc {
104 pub family: u16,
105 pub bdaddr: [u8; 6],
106 pub channel: u8,
107}
108
109unsafe extern "C" {
110 pub fn connect(fd: c_int, addr: *const SockAddrL2, len: u32) -> c_int;
111 pub fn listen(fd: c_int, backlog: c_int) -> c_int;
112 pub fn accept(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
113 pub fn bind(fd: c_int, addr: *const core::ffi::c_void, len: u32) -> c_int;
118 pub fn getsockname(fd: c_int, addr: *mut core::ffi::c_void, len: *mut u32) -> c_int;
119 fn poll(fds: *mut PollFd, nfds: core::ffi::c_ulong, timeout: c_int) -> c_int;
120}
121
122pub fn parse_address(address: &str) -> Option<[u8; 6]> {
129 let parts: Vec<&str> = address.split(':').collect();
130 if parts.len() != 6 {
131 return None;
132 }
133 let mut out = [0u8; 6];
134 for (i, part) in parts.iter().enumerate() {
135 out[5 - i] = u8::from_str_radix(part, 16).ok()?;
136 }
137 Some(out)
138}
139
140pub fn format_address(wire: &[u8; 6]) -> String {
142 let mut out = String::with_capacity(17);
143 for (i, b) in wire.iter().rev().enumerate() {
144 if i > 0 {
145 out.push(':');
146 }
147 out.push_str(&format!("{b:02X}"));
148 }
149 out
150}
151
152#[repr(C)]
153struct PollFd {
154 fd: c_int,
155 events: i16,
156 revents: i16,
157}
158
159pub const POLLIN: i16 = 0x001;
160pub const POLLOUT: i16 = 0x004;
161const POLLERR: i16 = 0x008;
162const POLLHUP: i16 = 0x010;
163
164#[derive(Debug, PartialEq, Eq)]
166pub enum Ready {
167 Yes,
168 TimedOut,
169 Closed,
171}
172
173pub fn wait_ready(fd: c_int, events: i16, timeout_ms: c_int) -> Result<Ready, i32> {
181 let mut fds = PollFd {
182 fd,
183 events,
184 revents: 0,
185 };
186 loop {
187 let rc = unsafe { poll(&mut fds, 1, timeout_ms) };
188 if rc < 0 {
189 let e = errno();
190 if e == EINTR {
191 continue;
192 }
193 return Err(e);
194 }
195 if rc == 0 {
196 return Ok(Ready::TimedOut);
197 }
198 if fds.revents & (POLLERR | POLLHUP) != 0 {
199 return Ok(Ready::Closed);
200 }
201 return Ok(Ready::Yes);
202 }
203}
204
205pub fn address_type(random: bool) -> u8 {
207 if random {
208 BDADDR_LE_RANDOM
209 } else {
210 BDADDR_LE_PUBLIC
211 }
212}
213
214pub fn bind_le_source(fd: c_int, psm: u16, cid: u16) -> Result<(), i32> {
224 let addr = SockAddrL2 {
225 family: AF_BLUETOOTH as u16,
226 psm: psm.to_le(),
227 bdaddr: BDADDR_ANY,
228 cid: cid.to_le(),
229 bdaddr_type: BDADDR_LE_PUBLIC,
230 };
231 let len = core::mem::size_of::<SockAddrL2>() as u32;
232 if unsafe { bind(fd, (&raw const addr).cast(), len) } < 0 {
233 return Err(errno());
234 }
235 Ok(())
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241
242 #[test]
243 fn addresses_are_reversed_onto_the_wire() {
244 assert_eq!(
245 parse_address("AA:BB:CC:DD:EE:FF"),
246 Some([0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA])
247 );
248 assert_eq!(
249 parse_address("00:00:00:00:00:01"),
250 Some([0x01, 0, 0, 0, 0, 0])
251 );
252 }
253
254 #[test]
255 fn formatting_is_the_inverse_of_parsing() {
256 let written = "AA:BB:CC:DD:EE:FF";
257 assert_eq!(format_address(&parse_address(written).unwrap()), written);
258 }
259
260 #[test]
261 fn malformed_addresses_are_rejected() {
262 for bad in [
263 "",
264 "AA:BB:CC:DD:EE",
265 "AA:BB:CC:DD:EE:FF:00",
266 "ZZ:BB:CC:DD:EE:FF",
267 ] {
268 assert_eq!(parse_address(bad), None, "{bad:?} should not parse");
269 }
270 }
271
272 #[test]
273 fn the_socket_address_matches_the_kernel_layout() {
274 assert_eq!(std::mem::size_of::<SockAddrL2>(), 13);
275 }
276}