1use crate::att::{self, AttError, Characteristic, Descriptor, Response, Service, Uuid};
16use crate::sys::{
17 address_type, bind_le_source, close, connect, errno, parse_address, read, shutdown, socket,
18 wait_ready, write, Ready, SockAddrL2, AF_BLUETOOTH, BTPROTO_L2CAP, EINTR, POLLIN, POLLOUT,
19 SHUT_RDWR, SOCK_SEQPACKET,
20};
21use std::ffi::c_int;
22use std::sync::atomic::{AtomicBool, Ordering};
23use std::sync::{Arc, Condvar, Mutex};
24use std::time::Duration;
25
26const ATT_CID: u16 = 4;
27const DEFAULT_MTU: u16 = 517;
28const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
29
30#[derive(Debug, Clone)]
32pub enum Error {
33 Io(String),
35 Att(AttError),
37 Timeout,
39 Disconnected,
41 Protocol(String),
43}
44
45impl std::fmt::Display for Error {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 match self {
48 Self::Io(m) => write!(f, "{m}"),
49 Self::Att(e) => write!(f, "the peer refused: {e}"),
50 Self::Timeout => f.write_str("the peer did not answer"),
51 Self::Disconnected => f.write_str("the link dropped"),
52 Self::Protocol(m) => write!(f, "protocol error: {m}"),
53 }
54 }
55}
56
57type Result<T> = std::result::Result<T, Error>;
58
59pub trait NotificationSink: Send + Sync {
61 fn on_notification(&self, handle: u16, value: Vec<u8>);
63 fn on_disconnected(&self);
65}
66
67struct Shared {
68 fd: c_int,
69 reply: Mutex<Option<Response>>,
71 arrived: Condvar,
72 stopped: AtomicBool,
73}
74
75impl Shared {
76 fn send(&self, pdu: &[u8]) {
82 if !matches!(wait_ready(self.fd, POLLOUT, 1000), Ok(Ready::Yes)) {
83 return;
84 }
85 unsafe { write(self.fd, pdu.as_ptr(), pdu.len()) };
86 }
87
88 fn answer(&self, opcode: u8, body: &[u8]) {
96 if opcode == att::opcode::EXCHANGE_MTU_REQUEST && body.len() >= 2 {
97 self.send(&att::exchange_mtu_response(DEFAULT_MTU));
98 return;
99 }
100 let handle = if body.len() >= 2 {
102 u16::from_le_bytes([body[0], body[1]])
103 } else {
104 0
105 };
106 self.send(&att::error_response(
107 opcode,
108 handle,
109 AttError(AttError::REQUEST_NOT_SUPPORTED),
110 ));
111 }
112}
113
114impl Drop for Shared {
115 fn drop(&mut self) {
116 unsafe { close(self.fd) };
117 }
118}
119
120pub struct Connection {
122 shared: Arc<Shared>,
123 in_flight: Mutex<()>,
125 mtu: Mutex<u16>,
126 peer: String,
127}
128
129impl Connection {
130 pub fn open(
135 address: &str,
136 random_address: bool,
137 sink: Arc<dyn NotificationSink>,
138 ) -> Result<Self> {
139 let bdaddr = parse_address(address)
140 .ok_or_else(|| Error::Io(format!("{address:?} is not a Bluetooth address")))?;
141
142 let fd = unsafe { socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP) };
143 if fd < 0 {
144 return Err(Error::Io(format!(
145 "could not create an L2CAP socket (errno {})",
146 errno()
147 )));
148 }
149
150 if let Err(e) = bind_le_source(fd, 0, ATT_CID) {
151 unsafe { close(fd) };
152 return Err(Error::Io(format!(
153 "could not bind an LE ATT socket (errno {e})"
154 )));
155 }
156
157 let addr = SockAddrL2 {
158 family: AF_BLUETOOTH as u16,
159 psm: 0,
160 bdaddr,
161 cid: ATT_CID.to_le(),
162 bdaddr_type: address_type(random_address),
163 };
164 if unsafe { connect(fd, &addr, std::mem::size_of::<SockAddrL2>() as u32) } < 0 {
165 let e = errno();
166 unsafe { close(fd) };
167 return Err(Error::Io(connect_error(address, e)));
168 }
169
170 let shared = Arc::new(Shared {
171 fd,
172 reply: Mutex::new(None),
173 arrived: Condvar::new(),
174 stopped: AtomicBool::new(false),
175 });
176 spawn_reader(shared.clone(), sink);
177
178 let connection = Self {
179 shared,
180 in_flight: Mutex::new(()),
181 mtu: Mutex::new(23),
182 peer: address.to_owned(),
183 };
184
185 if let Ok(Response::Mtu(mtu)) = connection.request(&att::exchange_mtu_request(DEFAULT_MTU))
188 {
189 *connection.mtu.lock().unwrap() = mtu.clamp(23, DEFAULT_MTU);
190 }
191 Ok(connection)
192 }
193
194 pub fn peer(&self) -> &str {
195 &self.peer
196 }
197
198 pub fn mtu(&self) -> u16 {
200 *self.mtu.lock().unwrap()
201 }
202
203 pub fn is_connected(&self) -> bool {
204 !self.shared.stopped.load(Ordering::Acquire)
205 }
206
207 pub fn close(&self) {
208 self.shared.stopped.store(true, Ordering::Release);
209 unsafe { shutdown(self.shared.fd, SHUT_RDWR) };
210 }
211
212 fn request(&self, pdu: &[u8]) -> Result<Response> {
214 let _one_at_a_time = self.in_flight.lock().map_err(|_| Error::Disconnected)?;
215 if !self.is_connected() {
216 return Err(Error::Disconnected);
217 }
218 *self.shared.reply.lock().unwrap() = None;
219
220 let deadline = std::time::Instant::now() + REQUEST_TIMEOUT;
221 self.send(pdu, deadline)?;
222
223 let mut guard = self.shared.reply.lock().map_err(|_| Error::Disconnected)?;
224 while guard.is_none() {
225 if !self.is_connected() {
226 return Err(Error::Disconnected);
227 }
228 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
229 if remaining.is_zero() {
230 return Err(Error::Timeout);
231 }
232 let (g, _) = self
233 .shared
234 .arrived
235 .wait_timeout(guard, remaining)
236 .map_err(|_| Error::Disconnected)?;
237 guard = g;
238 }
239 guard.take().ok_or(Error::Disconnected)
240 }
241
242 fn send(&self, pdu: &[u8], deadline: std::time::Instant) -> Result<()> {
251 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
252 if remaining.is_zero() {
253 return Err(Error::Timeout);
254 }
255 let ms = remaining.as_millis().min(i32::MAX as u128) as i32;
256 match wait_ready(self.shared.fd, POLLOUT, ms) {
257 Ok(Ready::Yes) => {}
258 Ok(Ready::TimedOut) => return Err(Error::Timeout),
259 Ok(Ready::Closed) => return Err(Error::Disconnected),
260 Err(e) => return Err(Error::Io(format!("poll failed (errno {e})"))),
261 }
262 let n = unsafe { write(self.shared.fd, pdu.as_ptr(), pdu.len()) };
263 if n as usize != pdu.len() {
264 return Err(Error::Io(format!("ATT write failed (errno {})", errno())));
265 }
266 Ok(())
267 }
268
269 fn write_long(&self, handle: u16, value: &[u8]) -> Result<()> {
276 let chunk = (*self.mtu.lock().unwrap() as usize)
279 .saturating_sub(5)
280 .max(1);
281 for (i, part) in value.chunks(chunk).enumerate() {
282 let offset = (i * chunk) as u16;
283 match self.checked(&att::prepare_write_request(handle, offset, part)) {
284 Ok(Response::PrepareWriteComplete) => {}
285 Ok(other) => {
286 let _ = self.request(&att::execute_write_request(false));
289 return Err(Error::Protocol(format!(
290 "unexpected reply to a prepared write: {other:?}"
291 )));
292 }
293 Err(e) => {
294 let _ = self.request(&att::execute_write_request(false));
295 return Err(e);
296 }
297 }
298 }
299 match self.checked(&att::execute_write_request(true))? {
300 Response::WriteComplete => Ok(()),
301 other => Err(Error::Protocol(format!(
302 "unexpected reply to an executed write: {other:?}"
303 ))),
304 }
305 }
306
307 fn checked(&self, pdu: &[u8]) -> Result<Response> {
309 match self.request(pdu)? {
310 Response::Error { error, .. } => Err(Error::Att(error)),
311 other => Ok(other),
312 }
313 }
314
315 pub fn discover_services(&self) -> Result<Vec<Service>> {
320 let mut found: Vec<Service> = Vec::new();
321 let mut start = 0x0001u16;
322 loop {
323 let pdu =
324 att::read_by_group_type_request(start, 0xFFFF, att::gatt_type::PRIMARY_SERVICE);
325 match self.request(&pdu)? {
326 Response::Services(batch) if !batch.is_empty() => {
327 let last = batch.last().map(|s| s.end_handle).unwrap_or(0xFFFF);
328 found.extend(batch);
329 if last == 0xFFFF {
331 break;
332 }
333 start = last + 1;
334 }
335 Response::Error { error, .. } if error.is_end_of_discovery() => break,
336 Response::Error { error, .. } => return Err(Error::Att(error)),
337 other => {
338 return Err(Error::Protocol(format!(
339 "unexpected reply to discovery: {other:?}"
340 )))
341 }
342 }
343 }
344 Ok(found)
345 }
346
347 pub fn discover_included_services(&self, service: &Service) -> Result<Vec<Service>> {
355 let mut found: Vec<Service> = Vec::new();
356 let mut start = service.start_handle;
357 loop {
358 if start > service.end_handle {
359 break;
360 }
361 let pdu = att::read_by_type_request(start, service.end_handle, att::gatt_type::INCLUDE);
362 match self.request(&pdu)? {
363 Response::Includes(batch) if !batch.is_empty() => {
364 let last = batch.last().map(|i| i.handle).unwrap_or(service.end_handle);
365 for include in batch {
366 let uuid = match include.uuid {
367 Some(uuid) => uuid,
368 None => match self.read(include.start_handle) {
370 Ok(bytes) => match att::Uuid::parse(&bytes) {
371 Some(uuid) => uuid,
372 None => continue,
373 },
374 Err(_) => continue,
375 },
376 };
377 found.push(Service {
378 start_handle: include.start_handle,
379 end_handle: include.end_handle,
380 uuid,
381 });
382 }
383 if last >= service.end_handle {
384 break;
385 }
386 start = last + 1;
387 }
388 Response::Includes(_) => break,
391 Response::Error { error, .. } if error.is_end_of_discovery() => break,
392 Response::Error { error, .. } => return Err(Error::Att(error)),
393 other => {
394 return Err(Error::Protocol(format!(
395 "unexpected reply to include discovery: {other:?}"
396 )))
397 }
398 }
399 }
400 Ok(found)
401 }
402
403 pub fn discover_characteristics(&self, service: &Service) -> Result<Vec<Characteristic>> {
404 let mut found: Vec<Characteristic> = Vec::new();
405 let mut start = service.start_handle;
406 loop {
407 if start > service.end_handle {
408 break;
409 }
410 let pdu = att::read_by_type_request(
411 start,
412 service.end_handle,
413 att::gatt_type::CHARACTERISTIC,
414 );
415 match self.request(&pdu)? {
416 Response::Characteristics(batch) if !batch.is_empty() => {
417 let last = batch.last().map(|c| c.handle).unwrap_or(service.end_handle);
418 found.extend(batch);
419 if last >= service.end_handle {
420 break;
421 }
422 start = last + 1;
423 }
424 Response::Error { error, .. } if error.is_end_of_discovery() => break,
425 Response::Error { error, .. } => return Err(Error::Att(error)),
426 other => {
427 return Err(Error::Protocol(format!(
428 "unexpected reply to discovery: {other:?}"
429 )))
430 }
431 }
432 }
433 Ok(found)
434 }
435
436 pub fn discover_descriptors(&self, start: u16, end: u16) -> Result<Vec<Descriptor>> {
439 if start > end {
440 return Ok(Vec::new());
441 }
442 let mut found: Vec<Descriptor> = Vec::new();
443 let mut cursor = start;
444 loop {
445 if cursor > end {
446 break;
447 }
448 match self.request(&att::find_information_request(cursor, end))? {
449 Response::Descriptors(batch) if !batch.is_empty() => {
450 let last = batch.last().map(|d| d.handle).unwrap_or(end);
451 found.extend(batch);
452 if last >= end {
453 break;
454 }
455 cursor = last + 1;
456 }
457 Response::Error { error, .. } if error.is_end_of_discovery() => break,
458 Response::Error { error, .. } => return Err(Error::Att(error)),
459 other => {
460 return Err(Error::Protocol(format!(
461 "unexpected reply to discovery: {other:?}"
462 )))
463 }
464 }
465 }
466 Ok(found)
467 }
468
469 pub fn read(&self, handle: u16) -> Result<Vec<u8>> {
472 let Response::Value(mut value) = self.checked(&att::read_request(handle))? else {
473 return Err(Error::Protocol("expected a value".into()));
474 };
475 let first_chunk = self.mtu() as usize - 1;
476 while value.len() == first_chunk + (value.len() - first_chunk) && value.len() >= first_chunk
477 {
478 let offset = value.len() as u16;
479 match self.checked(&att::read_blob_request(handle, offset)) {
480 Ok(Response::Value(more)) if !more.is_empty() => value.extend_from_slice(&more),
481 _ => break,
483 }
484 if value.len() >= 512 {
485 break;
486 }
487 }
488 Ok(value)
489 }
490
491 pub fn write(&self, handle: u16, value: &[u8]) -> Result<()> {
493 let single = (*self.mtu.lock().unwrap() as usize).saturating_sub(3);
497 if value.len() > single {
498 return self.write_long(handle, value);
499 }
500 match self.checked(&att::write_request(handle, value))? {
501 Response::WriteComplete => Ok(()),
502 other => Err(Error::Protocol(format!(
503 "unexpected reply to a write: {other:?}"
504 ))),
505 }
506 }
507
508 pub fn write_command(&self, handle: u16, value: &[u8]) -> Result<()> {
511 let single = (*self.mtu.lock().unwrap() as usize).saturating_sub(3);
515 if value.len() > single {
516 return Err(Error::Protocol(format!(
517 "{} bytes does not fit one unacknowledged write (MTU allows {single}); \
518 use an acknowledged write",
519 value.len()
520 )));
521 }
522 let deadline = std::time::Instant::now() + REQUEST_TIMEOUT;
523 self.send(&att::write_command(handle, value), deadline)
524 }
525
526 pub fn set_notify(&self, cccd_handle: u16, notify: bool, indicate: bool) -> Result<()> {
531 let bits: u16 = u16::from(notify) | (u16::from(indicate) << 1);
532 self.write(cccd_handle, &bits.to_le_bytes())
533 }
534}
535
536fn connect_error(address: &str, errno: i32) -> String {
545 if errno == crate::sys::EBUSY {
546 format!(
547 "could not connect to {address}: its LE link already has an ATT client \
548 (errno {errno}), almost certainly bluetoothd, which connects bonded devices \
549 by itself. linux-hci cannot share a link with it; disconnect the device \
550 in bluetoothd (`bluetoothctl disconnect {address}`) and take it off \
551 auto-connect, or stop bluetoothd"
552 )
553 } else {
554 format!("could not connect to {address} (errno {errno})")
555 }
556}
557
558impl Drop for Connection {
559 fn drop(&mut self) {
560 self.close();
561 }
562}
563
564fn spawn_reader(shared: Arc<Shared>, sink: Arc<dyn NotificationSink>) {
565 std::thread::Builder::new()
566 .name("webbluetooth-att".into())
567 .spawn(move || {
568 let mut buf = vec![0u8; 1024];
569 while !shared.stopped.load(Ordering::Acquire) {
570 match wait_ready(shared.fd, POLLIN, 250) {
573 Ok(Ready::Yes) => {}
574 Ok(Ready::TimedOut) => continue,
575 Ok(Ready::Closed) => break,
576 Err(e) if e == EINTR => continue,
577 Err(_) => break,
578 }
579 let n = unsafe { read(shared.fd, buf.as_mut_ptr(), buf.len()) };
580 if n <= 0 {
581 if n < 0 && errno() == EINTR {
582 continue; }
584 break;
585 }
586 let pdu = &buf[..n as usize];
587 let Some(response) = att::parse(pdu) else {
588 continue;
589 };
590
591 match response {
596 Response::Notification { handle, value } => sink.on_notification(handle, value),
597 Response::Indication { handle, value } => {
598 sink.on_notification(handle, value);
599 shared.send(&att::handle_value_confirmation());
600 }
601 Response::PeerRequest { opcode, body } => {
602 shared.answer(opcode, &body);
603 }
604 other => {
605 *shared.reply.lock().unwrap() = Some(other);
606 shared.arrived.notify_all();
607 }
608 }
609 }
610 shared.stopped.store(true, Ordering::Release);
611 shared.arrived.notify_all();
613 sink.on_disconnected();
614 })
615 .expect("could not start the ATT reader thread");
616}
617
618pub fn find_cccd(descriptors: &[Descriptor]) -> Option<u16> {
620 descriptors
621 .iter()
622 .find(|d| d.uuid == Uuid::Short(att::gatt_type::CLIENT_CHARACTERISTIC_CONFIGURATION))
623 .map(|d| d.handle)
624}
625
626#[cfg(test)]
627mod tests {
628 use super::*;
629
630 #[test]
633 fn a_link_held_by_bluetoothd_is_explained() {
634 let busy = connect_error("AA:BB:CC:DD:EE:FF", crate::sys::EBUSY);
635 assert!(busy.contains("bluetoothd"), "{busy}");
636 assert!(
637 busy.contains("bluetoothctl disconnect AA:BB:CC:DD:EE:FF"),
638 "{busy}"
639 );
640 assert_eq!(
641 connect_error("AA:BB:CC:DD:EE:FF", 111),
642 "could not connect to AA:BB:CC:DD:EE:FF (errno 111)"
643 );
644 }
645
646 #[test]
649 fn the_cccd_is_found_by_uuid() {
650 let descriptors = vec![
651 Descriptor {
652 handle: 0x0010,
653 uuid: Uuid::Short(0x2901),
654 },
655 Descriptor {
656 handle: 0x0011,
657 uuid: Uuid::Short(0x2902),
658 },
659 ];
660 assert_eq!(find_cccd(&descriptors), Some(0x0011));
661 assert_eq!(find_cccd(&[]), None);
662 }
663}