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(format!(
168 "could not connect to {address} (errno {e})"
169 )));
170 }
171
172 let shared = Arc::new(Shared {
173 fd,
174 reply: Mutex::new(None),
175 arrived: Condvar::new(),
176 stopped: AtomicBool::new(false),
177 });
178 spawn_reader(shared.clone(), sink);
179
180 let connection = Self {
181 shared,
182 in_flight: Mutex::new(()),
183 mtu: Mutex::new(23),
184 peer: address.to_owned(),
185 };
186
187 if let Ok(Response::Mtu(mtu)) = connection.request(&att::exchange_mtu_request(DEFAULT_MTU))
190 {
191 *connection.mtu.lock().unwrap() = mtu.clamp(23, DEFAULT_MTU);
192 }
193 Ok(connection)
194 }
195
196 pub fn peer(&self) -> &str {
197 &self.peer
198 }
199
200 pub fn mtu(&self) -> u16 {
202 *self.mtu.lock().unwrap()
203 }
204
205 pub fn is_connected(&self) -> bool {
206 !self.shared.stopped.load(Ordering::Acquire)
207 }
208
209 pub fn close(&self) {
210 self.shared.stopped.store(true, Ordering::Release);
211 unsafe { shutdown(self.shared.fd, SHUT_RDWR) };
212 }
213
214 fn request(&self, pdu: &[u8]) -> Result<Response> {
216 let _one_at_a_time = self.in_flight.lock().map_err(|_| Error::Disconnected)?;
217 if !self.is_connected() {
218 return Err(Error::Disconnected);
219 }
220 *self.shared.reply.lock().unwrap() = None;
221
222 let deadline = std::time::Instant::now() + REQUEST_TIMEOUT;
223 self.send(pdu, deadline)?;
224
225 let mut guard = self.shared.reply.lock().map_err(|_| Error::Disconnected)?;
226 while guard.is_none() {
227 if !self.is_connected() {
228 return Err(Error::Disconnected);
229 }
230 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
231 if remaining.is_zero() {
232 return Err(Error::Timeout);
233 }
234 let (g, _) = self
235 .shared
236 .arrived
237 .wait_timeout(guard, remaining)
238 .map_err(|_| Error::Disconnected)?;
239 guard = g;
240 }
241 guard.take().ok_or(Error::Disconnected)
242 }
243
244 fn send(&self, pdu: &[u8], deadline: std::time::Instant) -> Result<()> {
253 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
254 if remaining.is_zero() {
255 return Err(Error::Timeout);
256 }
257 let ms = remaining.as_millis().min(i32::MAX as u128) as i32;
258 match wait_ready(self.shared.fd, POLLOUT, ms) {
259 Ok(Ready::Yes) => {}
260 Ok(Ready::TimedOut) => return Err(Error::Timeout),
261 Ok(Ready::Closed) => return Err(Error::Disconnected),
262 Err(e) => return Err(Error::Io(format!("poll failed (errno {e})"))),
263 }
264 let n = unsafe { write(self.shared.fd, pdu.as_ptr(), pdu.len()) };
265 if n as usize != pdu.len() {
266 return Err(Error::Io(format!("ATT write failed (errno {})", errno())));
267 }
268 Ok(())
269 }
270
271 fn write_long(&self, handle: u16, value: &[u8]) -> Result<()> {
278 let chunk = (*self.mtu.lock().unwrap() as usize)
281 .saturating_sub(5)
282 .max(1);
283 for (i, part) in value.chunks(chunk).enumerate() {
284 let offset = (i * chunk) as u16;
285 match self.checked(&att::prepare_write_request(handle, offset, part)) {
286 Ok(Response::PrepareWriteComplete) => {}
287 Ok(other) => {
288 let _ = self.request(&att::execute_write_request(false));
291 return Err(Error::Protocol(format!(
292 "unexpected reply to a prepared write: {other:?}"
293 )));
294 }
295 Err(e) => {
296 let _ = self.request(&att::execute_write_request(false));
297 return Err(e);
298 }
299 }
300 }
301 match self.checked(&att::execute_write_request(true))? {
302 Response::WriteComplete => Ok(()),
303 other => Err(Error::Protocol(format!(
304 "unexpected reply to an executed write: {other:?}"
305 ))),
306 }
307 }
308
309 fn checked(&self, pdu: &[u8]) -> Result<Response> {
311 match self.request(pdu)? {
312 Response::Error { error, .. } => Err(Error::Att(error)),
313 other => Ok(other),
314 }
315 }
316
317 pub fn discover_services(&self) -> Result<Vec<Service>> {
322 let mut found: Vec<Service> = Vec::new();
323 let mut start = 0x0001u16;
324 loop {
325 let pdu =
326 att::read_by_group_type_request(start, 0xFFFF, att::gatt_type::PRIMARY_SERVICE);
327 match self.request(&pdu)? {
328 Response::Services(batch) if !batch.is_empty() => {
329 let last = batch.last().map(|s| s.end_handle).unwrap_or(0xFFFF);
330 found.extend(batch);
331 if last == 0xFFFF {
333 break;
334 }
335 start = last + 1;
336 }
337 Response::Error { error, .. } if error.is_end_of_discovery() => break,
338 Response::Error { error, .. } => return Err(Error::Att(error)),
339 other => {
340 return Err(Error::Protocol(format!(
341 "unexpected reply to discovery: {other:?}"
342 )))
343 }
344 }
345 }
346 Ok(found)
347 }
348
349 pub fn discover_included_services(&self, service: &Service) -> Result<Vec<Service>> {
357 let mut found: Vec<Service> = Vec::new();
358 let mut start = service.start_handle;
359 loop {
360 if start > service.end_handle {
361 break;
362 }
363 let pdu = att::read_by_type_request(start, service.end_handle, att::gatt_type::INCLUDE);
364 match self.request(&pdu)? {
365 Response::Includes(batch) if !batch.is_empty() => {
366 let last = batch.last().map(|i| i.handle).unwrap_or(service.end_handle);
367 for include in batch {
368 let uuid = match include.uuid {
369 Some(uuid) => uuid,
370 None => match self.read(include.start_handle) {
372 Ok(bytes) => match att::Uuid::parse(&bytes) {
373 Some(uuid) => uuid,
374 None => continue,
375 },
376 Err(_) => continue,
377 },
378 };
379 found.push(Service {
380 start_handle: include.start_handle,
381 end_handle: include.end_handle,
382 uuid,
383 });
384 }
385 if last >= service.end_handle {
386 break;
387 }
388 start = last + 1;
389 }
390 Response::Includes(_) => break,
393 Response::Error { error, .. } if error.is_end_of_discovery() => break,
394 Response::Error { error, .. } => return Err(Error::Att(error)),
395 other => {
396 return Err(Error::Protocol(format!(
397 "unexpected reply to include discovery: {other:?}"
398 )))
399 }
400 }
401 }
402 Ok(found)
403 }
404
405 pub fn discover_characteristics(&self, service: &Service) -> Result<Vec<Characteristic>> {
406 let mut found: Vec<Characteristic> = Vec::new();
407 let mut start = service.start_handle;
408 loop {
409 if start > service.end_handle {
410 break;
411 }
412 let pdu = att::read_by_type_request(
413 start,
414 service.end_handle,
415 att::gatt_type::CHARACTERISTIC,
416 );
417 match self.request(&pdu)? {
418 Response::Characteristics(batch) if !batch.is_empty() => {
419 let last = batch.last().map(|c| c.handle).unwrap_or(service.end_handle);
420 found.extend(batch);
421 if last >= service.end_handle {
422 break;
423 }
424 start = last + 1;
425 }
426 Response::Error { error, .. } if error.is_end_of_discovery() => break,
427 Response::Error { error, .. } => return Err(Error::Att(error)),
428 other => {
429 return Err(Error::Protocol(format!(
430 "unexpected reply to discovery: {other:?}"
431 )))
432 }
433 }
434 }
435 Ok(found)
436 }
437
438 pub fn discover_descriptors(&self, start: u16, end: u16) -> Result<Vec<Descriptor>> {
441 if start > end {
442 return Ok(Vec::new());
443 }
444 let mut found: Vec<Descriptor> = Vec::new();
445 let mut cursor = start;
446 loop {
447 if cursor > end {
448 break;
449 }
450 match self.request(&att::find_information_request(cursor, end))? {
451 Response::Descriptors(batch) if !batch.is_empty() => {
452 let last = batch.last().map(|d| d.handle).unwrap_or(end);
453 found.extend(batch);
454 if last >= end {
455 break;
456 }
457 cursor = last + 1;
458 }
459 Response::Error { error, .. } if error.is_end_of_discovery() => break,
460 Response::Error { error, .. } => return Err(Error::Att(error)),
461 other => {
462 return Err(Error::Protocol(format!(
463 "unexpected reply to discovery: {other:?}"
464 )))
465 }
466 }
467 }
468 Ok(found)
469 }
470
471 pub fn read(&self, handle: u16) -> Result<Vec<u8>> {
474 let Response::Value(mut value) = self.checked(&att::read_request(handle))? else {
475 return Err(Error::Protocol("expected a value".into()));
476 };
477 let first_chunk = self.mtu() as usize - 1;
478 while value.len() == first_chunk + (value.len() - first_chunk) && value.len() >= first_chunk
479 {
480 let offset = value.len() as u16;
481 match self.checked(&att::read_blob_request(handle, offset)) {
482 Ok(Response::Value(more)) if !more.is_empty() => value.extend_from_slice(&more),
483 _ => break,
485 }
486 if value.len() >= 512 {
487 break;
488 }
489 }
490 Ok(value)
491 }
492
493 pub fn write(&self, handle: u16, value: &[u8]) -> Result<()> {
495 let single = (*self.mtu.lock().unwrap() as usize).saturating_sub(3);
499 if value.len() > single {
500 return self.write_long(handle, value);
501 }
502 match self.checked(&att::write_request(handle, value))? {
503 Response::WriteComplete => Ok(()),
504 other => Err(Error::Protocol(format!(
505 "unexpected reply to a write: {other:?}"
506 ))),
507 }
508 }
509
510 pub fn write_command(&self, handle: u16, value: &[u8]) -> Result<()> {
513 let single = (*self.mtu.lock().unwrap() as usize).saturating_sub(3);
517 if value.len() > single {
518 return Err(Error::Protocol(format!(
519 "{} bytes does not fit one unacknowledged write (MTU allows {single}); \
520 use an acknowledged write",
521 value.len()
522 )));
523 }
524 let deadline = std::time::Instant::now() + REQUEST_TIMEOUT;
525 self.send(&att::write_command(handle, value), deadline)
526 }
527
528 pub fn set_notify(&self, cccd_handle: u16, notify: bool, indicate: bool) -> Result<()> {
533 let bits: u16 = u16::from(notify) | (u16::from(indicate) << 1);
534 self.write(cccd_handle, &bits.to_le_bytes())
535 }
536}
537
538impl Drop for Connection {
539 fn drop(&mut self) {
540 self.close();
541 }
542}
543
544fn spawn_reader(shared: Arc<Shared>, sink: Arc<dyn NotificationSink>) {
545 std::thread::Builder::new()
546 .name("webbluetooth-att".into())
547 .spawn(move || {
548 let mut buf = vec![0u8; 1024];
549 while !shared.stopped.load(Ordering::Acquire) {
550 match wait_ready(shared.fd, POLLIN, 250) {
553 Ok(Ready::Yes) => {}
554 Ok(Ready::TimedOut) => continue,
555 Ok(Ready::Closed) => break,
556 Err(e) if e == EINTR => continue,
557 Err(_) => break,
558 }
559 let n = unsafe { read(shared.fd, buf.as_mut_ptr(), buf.len()) };
560 if n <= 0 {
561 if n < 0 && errno() == EINTR {
562 continue; }
564 break;
565 }
566 let pdu = &buf[..n as usize];
567 let Some(response) = att::parse(pdu) else {
568 continue;
569 };
570
571 match response {
576 Response::Notification { handle, value } => sink.on_notification(handle, value),
577 Response::Indication { handle, value } => {
578 sink.on_notification(handle, value);
579 shared.send(&att::handle_value_confirmation());
580 }
581 Response::PeerRequest { opcode, body } => {
582 shared.answer(opcode, &body);
583 }
584 other => {
585 *shared.reply.lock().unwrap() = Some(other);
586 shared.arrived.notify_all();
587 }
588 }
589 }
590 shared.stopped.store(true, Ordering::Release);
591 shared.arrived.notify_all();
593 sink.on_disconnected();
594 })
595 .expect("could not start the ATT reader thread");
596}
597
598pub fn find_cccd(descriptors: &[Descriptor]) -> Option<u16> {
600 descriptors
601 .iter()
602 .find(|d| d.uuid == Uuid::Short(att::gatt_type::CLIENT_CHARACTERISTIC_CONFIGURATION))
603 .map(|d| d.handle)
604}
605
606#[cfg(test)]
607mod tests {
608 use super::*;
609
610 #[test]
613 fn the_cccd_is_found_by_uuid() {
614 let descriptors = vec![
615 Descriptor {
616 handle: 0x0010,
617 uuid: Uuid::Short(0x2901),
618 },
619 Descriptor {
620 handle: 0x0011,
621 uuid: Uuid::Short(0x2902),
622 },
623 ];
624 assert_eq!(find_cccd(&descriptors), Some(0x0011));
625 assert_eq!(find_cccd(&[]), None);
626 }
627}