1use std::collections::HashMap;
5use std::sync::atomic::AtomicU16;
6use std::sync::{Arc, Mutex};
7use std::time::Duration;
8
9use bt_hci::cmd::le::{
10 LeConnUpdate, LeReadPhy, LeReadRemoteFeatures, LeRemoteConnectionParameterRequestReply,
11 LeSetDataLength, LeSetPhy,
12};
13use bt_hci::cmd::link_control::Disconnect;
14use bt_hci::cmd::status::ReadRssi;
15use bt_hci::param::{
16 AllPhys, ConnHandle, DisconnectReason, Duration as HciDuration, PhyMask, PhyOptions,
17};
18use serde::Serialize;
19use tokio::sync::{broadcast, mpsc, oneshot, watch};
20
21use crate::address::Address;
22use crate::error::{Error, Result};
23use crate::host::Host;
24use crate::{att, l2cap, smp};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
28#[serde(rename_all = "snake_case")]
29pub enum Role {
30 Central,
32 Peripheral,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]
38#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
39#[serde(rename_all = "snake_case")]
40pub enum Phy {
41 Le1m,
43 Le2m,
45 LeCoded,
47}
48
49impl Phy {
50 pub(crate) fn from_hci(v: u8) -> Phy {
51 match v {
52 2 => Phy::Le2m,
53 3 => Phy::LeCoded,
54 _ => Phy::Le1m,
55 }
56 }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
61pub struct Security {
62 pub encrypted: bool,
64 pub authenticated: bool,
66 pub secure_connections: bool,
68 pub key_size: u8,
70 pub bonded: bool,
72}
73
74impl Security {
75 pub fn level(&self) -> u8 {
78 match (
79 self.encrypted,
80 self.authenticated,
81 self.secure_connections && self.key_size == 16,
82 ) {
83 (false, _, _) => 1,
84 (true, false, _) => 2,
85 (true, true, false) => 3,
86 (true, true, true) => 4,
87 }
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]
93pub struct ConnParams {
94 pub interval: u16,
96 pub latency: u16,
98 pub timeout: u16,
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]
104pub struct ParamsRequest {
105 pub interval_min: u16,
107 pub interval_max: u16,
109 pub latency: u16,
111 pub timeout: u16,
113}
114
115impl Default for ParamsRequest {
116 fn default() -> Self {
117 ParamsRequest {
118 interval_min: 24,
119 interval_max: 40,
120 latency: 0,
121 timeout: 400,
122 }
123 }
124}
125
126impl ParamsRequest {
127 pub(crate) fn check(&self) -> Result<()> {
128 let ok = (6..=3200).contains(&self.interval_min)
129 && (self.interval_min..=3200).contains(&self.interval_max)
130 && self.latency <= 499
131 && (10..=3200).contains(&self.timeout)
132 && u32::from(self.timeout) * 8 > (1 + u32::from(self.latency)) * u32::from(self.interval_max) * 2;
134 if ok {
135 Ok(())
136 } else {
137 Err(Error::InvalidParameter(format!(
138 "connection parameters {self:?}"
139 )))
140 }
141 }
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
146pub struct DataLength {
147 pub tx_octets: u16,
149 pub tx_time: u16,
151 pub rx_octets: u16,
153 pub rx_time: u16,
155}
156
157#[derive(Debug, Clone)]
159#[non_exhaustive]
160pub enum ConnEvent {
161 Notification {
163 handle: u16,
165 value: Vec<u8>,
167 indication: bool,
169 },
170 ParamsUpdated(ConnParams),
172 PhyUpdated(Phy, Phy),
174 DataLengthChanged(DataLength),
176 SecurityChanged(Security),
178 MtuExchanged(u16),
180 Disconnected(u8),
182}
183
184#[derive(Default)]
185pub(crate) struct Waiters {
186 pub(crate) params: Option<oneshot::Sender<u8>>,
187 pub(crate) phy: Option<oneshot::Sender<u8>>,
188 pub(crate) features: Option<oneshot::Sender<(u8, u64)>>,
189 pub(crate) encryption: Option<oneshot::Sender<u8>>,
190}
191
192pub(crate) struct ConnState {
194 pub(crate) handle: u16,
195 pub(crate) role: Role,
196 pub(crate) peer: Address,
198 identity: Mutex<Option<Address>>,
199 params: Mutex<ConnParams>,
200 phy: Mutex<(Phy, Phy)>,
201 data_length: Mutex<DataLength>,
202 pub(crate) security: watch::Sender<Security>,
203 closed: watch::Sender<Option<u8>>,
204 pub(crate) in_flight: Arc<AtomicU16>,
205 pub(crate) send_lock: tokio::sync::Mutex<()>,
206 pub(crate) att_tx: mpsc::Sender<Vec<u8>>,
207 pub(crate) smp_tx: mpsc::Sender<Vec<u8>>,
208 pub(crate) smp_cmd: mpsc::Sender<smp::Command>,
209 pub(crate) sig_tx: mpsc::Sender<Vec<u8>>,
210 pub(crate) att: att::Bearer,
211 pub(crate) coc: Mutex<HashMap<u16, l2cap::ChannelEnd>>,
212 pub(crate) sig: l2cap::Signaling,
213 pub(crate) events: broadcast::Sender<ConnEvent>,
214 pub(crate) waiters: Mutex<Waiters>,
215 pub(crate) remote_features: Mutex<Option<u64>>,
216 pub(crate) pairing_key: smp::PairingKey,
218 pub(crate) security_op: tokio::sync::Mutex<()>,
220}
221
222const CHANNEL_DEPTH: usize = 64;
225
226impl ConnState {
227 pub(crate) fn spawn(host: &Host, handle: u16, role: Role, peer: Address) -> Arc<ConnState> {
228 let (att_tx, att_rx) = mpsc::channel(CHANNEL_DEPTH);
229 let (smp_tx, smp_rx) = mpsc::channel(CHANNEL_DEPTH);
230 let (smp_cmd, smp_cmd_rx) = mpsc::channel(4);
231 let (sig_tx, sig_rx) = mpsc::channel(CHANNEL_DEPTH);
232 let in_flight = host.inner.hci.open_handle(handle);
233 let bonded_security = Security::default();
234 let state = Arc::new(ConnState {
235 handle,
236 role,
237 peer,
238 identity: Mutex::new(None),
239 params: Mutex::new(ConnParams {
240 interval: 0,
241 latency: 0,
242 timeout: 0,
243 }),
244 phy: Mutex::new((Phy::Le1m, Phy::Le1m)),
245 data_length: Mutex::new(DataLength {
246 tx_octets: 27,
247 tx_time: 328,
248 rx_octets: 27,
249 rx_time: 328,
250 }),
251 security: watch::channel(bonded_security).0,
252 closed: watch::channel(None).0,
253 in_flight,
254 send_lock: tokio::sync::Mutex::new(()),
255 att_tx,
256 smp_tx,
257 smp_cmd,
258 sig_tx,
259 att: att::Bearer::default(),
260 coc: Mutex::new(HashMap::new()),
261 sig: l2cap::Signaling::default(),
262 events: broadcast::channel(256).0,
263 waiters: Mutex::new(Waiters::default()),
264 remote_features: Mutex::new(None),
265 pairing_key: Mutex::new(None),
266 security_op: tokio::sync::Mutex::new(()),
267 });
268 tokio::spawn(att::run(host.clone(), state.clone(), att_rx));
269 tokio::spawn(smp::run(host.clone(), state.clone(), smp_rx, smp_cmd_rx));
270 tokio::spawn(l2cap::run_signaling(host.clone(), state.clone(), sig_rx));
271 state
272 }
273
274 pub(crate) fn identity(&self) -> Address {
275 self.identity
276 .lock()
277 .unwrap_or_else(|e| e.into_inner())
278 .unwrap_or(self.peer)
279 }
280
281 pub(crate) fn set_identity(&self, a: Address) {
282 *self.identity.lock().unwrap_or_else(|e| e.into_inner()) = Some(a);
283 }
284
285 pub(crate) fn set_params(&self, interval: u16, latency: u16, timeout: u16) {
286 *self.params.lock().unwrap_or_else(|e| e.into_inner()) = ConnParams {
287 interval,
288 latency,
289 timeout,
290 };
291 }
292
293 pub(crate) fn waiters(&self) -> std::sync::MutexGuard<'_, Waiters> {
294 self.waiters.lock().unwrap_or_else(|e| e.into_inner())
295 }
296
297 pub(crate) fn is_closed(&self) -> bool {
298 self.closed.borrow().is_some()
299 }
300
301 pub(crate) async fn wait_closed(&self) -> u8 {
303 let mut rx = self.closed.subscribe();
304 loop {
305 if let Some(r) = *rx.borrow() {
306 return r;
307 }
308 if rx.changed().await.is_err() {
309 return 0x16;
310 }
311 }
312 }
313
314 pub(crate) fn close(&self, reason: u8) {
315 let _ = self.closed.send(Some(reason));
316 let _ = self.events.send(ConnEvent::Disconnected(reason));
317 let mut w = self.waiters();
318 *w = Waiters::default();
319 drop(w);
320 self.att.close();
321 self.coc.lock().unwrap_or_else(|e| e.into_inner()).clear();
322 }
323
324 pub(crate) fn params_updated(&self, status: u8, interval: u16, latency: u16, timeout: u16) {
325 if status == 0 {
326 self.set_params(interval, latency, timeout);
327 let _ = self.events.send(ConnEvent::ParamsUpdated(ConnParams {
328 interval,
329 latency,
330 timeout,
331 }));
332 }
333 if let Some(w) = self.waiters().params.take() {
334 let _ = w.send(status);
335 }
336 }
337
338 pub(crate) fn phy_updated(&self, status: u8, tx: u8, rx: u8) {
339 if status == 0 {
340 let p = (Phy::from_hci(tx), Phy::from_hci(rx));
341 *self.phy.lock().unwrap_or_else(|e| e.into_inner()) = p;
342 let _ = self.events.send(ConnEvent::PhyUpdated(p.0, p.1));
343 }
344 if let Some(w) = self.waiters().phy.take() {
345 let _ = w.send(status);
346 }
347 }
348
349 pub(crate) fn data_length_changed(
350 &self,
351 tx_octets: u16,
352 tx_time: u16,
353 rx_octets: u16,
354 rx_time: u16,
355 ) {
356 let d = DataLength {
357 tx_octets,
358 tx_time,
359 rx_octets,
360 rx_time,
361 };
362 *self.data_length.lock().unwrap_or_else(|e| e.into_inner()) = d;
363 let _ = self.events.send(ConnEvent::DataLengthChanged(d));
364 }
365
366 pub(crate) fn remote_features(&self, status: u8, features: u64) {
367 if status == 0 {
368 *self
369 .remote_features
370 .lock()
371 .unwrap_or_else(|e| e.into_inner()) = Some(features);
372 }
373 if let Some(w) = self.waiters().features.take() {
374 let _ = w.send((status, features));
375 }
376 }
377
378 pub(crate) fn encryption_changed(&self, status: u8, on: bool) {
379 if status == 0 && on {
380 self.security.send_modify(|s| s.encrypted = true);
381 let _ = self
382 .events
383 .send(ConnEvent::SecurityChanged(*self.security.borrow()));
384 } else if status == 0 {
385 self.security.send_modify(|s| s.encrypted = false);
386 }
387 if let Some(w) = self.waiters().encryption.take() {
388 let _ = w.send(status);
389 }
390 }
391
392 pub(crate) async fn send(&self, host: &Host, cid: u16, payload: &[u8]) -> Result<()> {
394 if self.is_closed() {
395 return Err(Error::Disconnected);
396 }
397 let len = u16::try_from(payload.len())
398 .map_err(|_| Error::InvalidParameter("L2CAP PDU over 65535 octets".into()))?;
399 let mut pdu = Vec::with_capacity(4 + payload.len());
400 pdu.extend_from_slice(&len.to_le_bytes());
401 pdu.extend_from_slice(&cid.to_le_bytes());
402 pdu.extend_from_slice(payload);
403 let _g = self.send_lock.lock().await;
404 host.inner
405 .hci
406 .send_acl(self.handle, &pdu, &self.in_flight)
407 .await
408 }
409}
410
411#[derive(Clone)]
413pub struct Connection {
414 pub(crate) host: Host,
415 pub(crate) state: Arc<ConnState>,
416}
417
418impl std::fmt::Debug for Connection {
419 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420 f.debug_struct("Connection")
421 .field("handle", &self.state.handle)
422 .field("role", &self.state.role)
423 .field("peer", &self.state.peer)
424 .finish()
425 }
426}
427
428const PROCEDURE_TIMEOUT: Duration = Duration::from_secs(40);
429
430impl Connection {
431 pub(crate) fn new(host: Host, state: Arc<ConnState>) -> Self {
432 Connection { host, state }
433 }
434
435 pub fn handle(&self) -> u16 {
437 self.state.handle
438 }
439
440 pub fn role(&self) -> Role {
442 self.state.role
443 }
444
445 pub fn peer(&self) -> Address {
447 self.state.peer
448 }
449
450 pub fn identity(&self) -> Address {
453 self.state.identity()
454 }
455
456 pub fn params(&self) -> ConnParams {
458 *self.state.params.lock().unwrap_or_else(|e| e.into_inner())
459 }
460
461 pub fn phy(&self) -> (Phy, Phy) {
463 *self.state.phy.lock().unwrap_or_else(|e| e.into_inner())
464 }
465
466 pub fn data_length(&self) -> DataLength {
468 *self
469 .state
470 .data_length
471 .lock()
472 .unwrap_or_else(|e| e.into_inner())
473 }
474
475 pub fn security(&self) -> Security {
477 *self.state.security.borrow()
478 }
479
480 pub fn att_mtu(&self) -> u16 {
482 self.state.att.mtu()
483 }
484
485 pub fn events(&self) -> broadcast::Receiver<ConnEvent> {
487 self.state.events.subscribe()
488 }
489
490 pub fn is_connected(&self) -> bool {
492 !self.state.is_closed()
493 }
494
495 pub async fn disconnected(&self) -> u8 {
497 self.state.wait_closed().await
498 }
499
500 pub async fn disconnect(&self) -> Result<()> {
502 if self.state.is_closed() {
503 return Ok(());
504 }
505 self.host
506 .inner
507 .hci
508 .exec_async(&Disconnect::new(
509 ConnHandle::new(self.state.handle),
510 DisconnectReason::RemoteUserTerminatedConn,
511 ))
512 .await?;
513 tokio::time::timeout(Duration::from_secs(10), self.state.wait_closed())
514 .await
515 .map(|_| ())
516 .map_err(|_| Error::Timeout("disconnection"))
517 }
518
519 pub async fn update_params(&self, p: ParamsRequest) -> Result<ConnParams> {
522 p.check()?;
523 match self.state.role {
524 Role::Central => {
525 let (tx, rx) = oneshot::channel();
526 self.state.waiters().params = Some(tx);
527 self.host
528 .inner
529 .hci
530 .exec_async(&LeConnUpdate::new(
531 ConnHandle::new(self.state.handle),
532 HciDuration::from_u16(p.interval_min),
533 HciDuration::from_u16(p.interval_max),
534 p.latency,
535 HciDuration::from_u16(p.timeout),
536 HciDuration::from_u16(0),
537 HciDuration::from_u16(0),
538 ))
539 .await?;
540 match tokio::time::timeout(PROCEDURE_TIMEOUT, rx).await {
541 Ok(Ok(0)) => Ok(self.params()),
542 Ok(Ok(s)) => Err(Error::hci(0x2013, s)),
543 Ok(Err(_)) => Err(Error::Disconnected),
544 Err(_) => Err(Error::Timeout("connection update")),
545 }
546 }
547 Role::Peripheral => {
548 let mut rx = self.state.events.subscribe();
549 l2cap::request_param_update(&self.host, &self.state, p).await?;
550 let deadline = tokio::time::Instant::now() + PROCEDURE_TIMEOUT;
552 loop {
553 match tokio::time::timeout_at(deadline, rx.recv()).await {
554 Ok(Ok(ConnEvent::ParamsUpdated(c))) => return Ok(c),
555 Ok(Ok(ConnEvent::Disconnected(_)))
556 | Ok(Err(broadcast::error::RecvError::Closed)) => {
557 return Err(Error::Disconnected)
558 }
559 Ok(_) => {}
560 Err(_) => return Ok(self.params()),
561 }
562 }
563 }
564 }
565 }
566
567 pub async fn set_phy(&self, tx: &[Phy], rx: &[Phy], coded_s8: bool) -> Result<(Phy, Phy)> {
570 if !self.host.inner.caps().phy_update() {
571 return Err(Error::Unsupported("PHY update (no 2M or coded PHY)"));
572 }
573 let mask = |s: &[Phy]| {
574 let mut m = PhyMask::new();
575 for p in s {
576 m = match p {
577 Phy::Le1m => m.set_le_1m_phy(true),
578 Phy::Le2m => m.set_le_2m_phy(true),
579 Phy::LeCoded => m.set_le_coded_phy(true),
580 };
581 }
582 m
583 };
584 let options = if coded_s8 {
585 PhyOptions::S8CodingPreferred
586 } else {
587 PhyOptions::NoPreferredCoding
588 };
589 let (txw, rxw) = oneshot::channel();
590 self.state.waiters().phy = Some(txw);
591 self.host
592 .inner
593 .hci
594 .exec_async(&LeSetPhy::new(
595 ConnHandle::new(self.state.handle),
596 AllPhys::new(),
597 mask(tx),
598 mask(rx),
599 options,
600 ))
601 .await?;
602 match tokio::time::timeout(PROCEDURE_TIMEOUT, rxw).await {
603 Ok(Ok(0)) => Ok(self.phy()),
604 Ok(Ok(s)) => Err(Error::hci(0x2032, s)),
605 Ok(Err(_)) => Err(Error::Disconnected),
606 Err(_) => Err(Error::Timeout("PHY update")),
607 }
608 }
609
610 pub async fn read_phy(&self) -> Result<(Phy, Phy)> {
612 if !self.host.inner.caps().cmds().le_read_phy() {
613 return Ok(self.phy());
614 }
615 let r = self
616 .host
617 .inner
618 .hci
619 .exec(&LeReadPhy::new(ConnHandle::new(self.state.handle)))
620 .await?;
621 let p = (Phy::from_hci(r.tx_phy as u8), Phy::from_hci(r.rx_phy as u8));
622 *self.state.phy.lock().unwrap_or_else(|e| e.into_inner()) = p;
623 Ok(p)
624 }
625
626 pub async fn set_data_length(&self, tx_octets: u16, tx_time: u16) -> Result<()> {
628 if !self.host.inner.caps().data_length_extension() {
629 return Err(Error::Unsupported("data length extension"));
630 }
631 if !(27..=251).contains(&tx_octets) || !(328..=17040).contains(&tx_time) {
632 return Err(Error::InvalidParameter(format!(
633 "data length {tx_octets} octets, {tx_time} µs"
634 )));
635 }
636 self.host
637 .inner
638 .hci
639 .exec(&LeSetDataLength::new(
640 ConnHandle::new(self.state.handle),
641 tx_octets,
642 tx_time,
643 ))
644 .await?;
645 Ok(())
646 }
647
648 pub async fn read_rssi(&self) -> Result<i8> {
650 let r = self
651 .host
652 .inner
653 .hci
654 .exec(&ReadRssi::new(ConnHandle::new(self.state.handle)))
655 .await?;
656 Ok(r.rssi)
657 }
658
659 pub async fn remote_features(&self) -> Result<u64> {
661 if let Some(f) = *self
662 .state
663 .remote_features
664 .lock()
665 .unwrap_or_else(|e| e.into_inner())
666 {
667 return Ok(f);
668 }
669 let (tx, rx) = oneshot::channel();
670 self.state.waiters().features = Some(tx);
671 self.host
672 .inner
673 .hci
674 .exec_async(&LeReadRemoteFeatures::new(ConnHandle::new(
675 self.state.handle,
676 )))
677 .await?;
678 match tokio::time::timeout(PROCEDURE_TIMEOUT, rx).await {
679 Ok(Ok((0, f))) => Ok(f),
680 Ok(Ok((s, _))) => Err(Error::hci(0x2016, s)),
681 Ok(Err(_)) => Err(Error::Disconnected),
682 Err(_) => Err(Error::Timeout("remote features")),
683 }
684 }
685
686 pub fn gatt(&self) -> crate::gatt::client::Client {
688 crate::gatt::client::Client { conn: self.clone() }
689 }
690
691 pub async fn pair(&self) -> Result<Security> {
694 smp::pair(self).await
695 }
696
697 pub async fn secure(&self) -> Result<Security> {
699 smp::secure(self).await
700 }
701
702 pub async fn open_channel(&self, spsm: u16, mtu: u16) -> Result<l2cap::Channel> {
704 l2cap::connect(self, spsm, mtu).await
705 }
706}
707
708pub(crate) fn on_remote_param_request(
711 host: &Host,
712 handle: u16,
713 min: u16,
714 max: u16,
715 latency: u16,
716 timeout: u16,
717) {
718 let host = host.clone();
719 tokio::spawn(async move {
720 let r = host
721 .inner
722 .hci
723 .exec(&LeRemoteConnectionParameterRequestReply::new(
724 ConnHandle::new(handle),
725 HciDuration::from_u16(min),
726 HciDuration::from_u16(max),
727 latency,
728 HciDuration::from_u16(timeout),
729 HciDuration::from_u16(0),
730 HciDuration::from_u16(0),
731 ))
732 .await;
733 if let Err(e) = r {
734 tracing::warn!("could not accept connection parameters on {handle:#05x}: {e}");
735 }
736 });
737}