Skip to main content

bluetooth_host/
host.rs

1//! The host: opens a controller, sets it up, and runs the event loop that
2//! everything else hangs off.
3
4use std::collections::HashMap;
5use std::path::PathBuf;
6use std::sync::{Arc, Mutex, OnceLock};
7use std::time::Duration;
8
9use bt_hci::cmd::controller_baseband::{Reset, SetEventMask};
10use bt_hci::cmd::info::{
11    ReadBdAddr, ReadLocalSupportedCmds, ReadLocalSupportedFeatures, ReadLocalVersionInformation,
12};
13use bt_hci::cmd::le::{
14    LeReadBufferSize, LeReadFilterAcceptListSize, LeReadLocalSupportedFeatures,
15    LeReadMaxAdvDataLength, LeReadMaxDataLength, LeReadNumberOfSupportedAdvSets,
16    LeReadResolvingListSize, LeReadSupportedStates, LeSetDefaultPhy, LeSetEventMask,
17    LeSetRandomAddr, LeWriteSuggestedDefaultDataLength,
18};
19use bt_hci::event::le::LeEvent;
20use bt_hci::event::Event;
21use bt_hci::param::{AllPhys, BdAddr, EventMask, LeEventMask, PhyMask};
22use bt_hci::FromHciBytes;
23use tokio::sync::{broadcast, mpsc, oneshot, watch};
24
25use crate::address::Address;
26use crate::connection::{ConnState, Connection, Role};
27use crate::controller::Capabilities;
28use crate::error::{Error, Result};
29use crate::gatt::server::Database;
30use crate::hci::{Hci, Reassembly};
31use crate::keys::Keys;
32use crate::scan::Scanner;
33use crate::smp::{Agent, AutoAgent, IoCapability};
34use crate::transport::{self, Packet, PacketReader, TransportSpec};
35use crate::{advertise, l2cap, scan, smp};
36
37/// How the host presents itself and pairs.
38#[derive(Clone)]
39pub struct HostConfig {
40    /// Where bonds and the local identity are kept; `None` keeps them in memory only.
41    pub data_dir: Option<PathBuf>,
42    /// The name in the GAP service (and the default advertising name).
43    pub device_name: String,
44    /// The GAP Appearance value.
45    pub appearance: u16,
46    /// Our input and output capabilities for pairing.
47    pub io_capability: IoCapability,
48    /// Answers pairing prompts (passkeys, numeric comparison, OOB data).
49    pub agent: Arc<dyn Agent>,
50    /// Bond when pairing (store keys so the device stays trusted).
51    pub bonding: bool,
52    /// Insist on MITM protection (rules out Just Works).
53    pub mitm: bool,
54    /// Refuse LE legacy pairing (Secure Connections only).
55    pub secure_connections_only: bool,
56    /// Accept a peer that uses the published debug key (insecure; tests only).
57    pub allow_debug_keys: bool,
58    /// Use the controller's public address as our identity when it has one;
59    /// otherwise (or when false) a static random address kept in `data_dir`.
60    pub use_public_address: bool,
61    /// Capacity of the event channel; slow readers lose the oldest events.
62    pub event_capacity: usize,
63}
64
65impl Default for HostConfig {
66    fn default() -> Self {
67        HostConfig {
68            data_dir: None,
69            device_name: "bluetooth-bridge".into(),
70            appearance: 0,
71            io_capability: IoCapability::NoInputNoOutput,
72            agent: Arc::new(AutoAgent),
73            bonding: true,
74            mitm: false,
75            secure_connections_only: false,
76            allow_debug_keys: false,
77            use_public_address: true,
78            event_capacity: 1024,
79        }
80    }
81}
82
83/// Something that happened, for the application.
84#[derive(Debug, Clone)]
85#[non_exhaustive]
86pub enum HostEvent {
87    /// An advertisement (after duplicate filtering), with its scan response
88    /// when there was one.
89    Advertisement(Arc<scan::Report>),
90    /// A periodic advertising report from a synchronized train.
91    PeriodicReport(Arc<scan::PeriodicReport>),
92    /// A periodic advertising train was lost.
93    PeriodicSyncLost {
94        /// The sync handle.
95        sync: u16,
96    },
97    /// A new connection, in either role.
98    Connected(Connection),
99    /// A connection closed.
100    Disconnected {
101        /// The connection handle.
102        handle: u16,
103        /// The peer, as connected.
104        peer: Address,
105        /// The HCI reason code.
106        reason: u8,
107    },
108    /// An advertising set stopped: its duration ran out, it reached its
109    /// event count, or (connectable) someone connected.
110    AdvertisingStopped {
111        /// The set.
112        set: u8,
113        /// The connection it made, if any.
114        connection: Option<u16>,
115    },
116    /// A scanner sent a scan request to one of our sets (when asked for).
117    ScanRequest {
118        /// The set.
119        set: u8,
120        /// Who asked.
121        scanner: Address,
122    },
123    /// Pairing finished.
124    Paired {
125        /// The connection.
126        handle: u16,
127        /// The peer's identity address.
128        identity: Address,
129        /// Keys were stored.
130        bonded: bool,
131        /// The resulting security.
132        security: crate::connection::Security,
133    },
134    /// Pairing failed.
135    PairingFailed {
136        /// The connection.
137        handle: u16,
138        /// Why.
139        reason: String,
140    },
141    /// A client wrote one of our GATT server's characteristics.
142    GattWrite {
143        /// The connection.
144        handle: u16,
145        /// The attribute handle.
146        attribute: u16,
147        /// The value written (whole, after a long write).
148        value: Vec<u8>,
149    },
150    /// A client changed its notification or indication subscription.
151    GattSubscription {
152        /// The connection.
153        handle: u16,
154        /// The characteristic value handle.
155        attribute: u16,
156        /// Notifications on.
157        notify: bool,
158        /// Indications on.
159        indicate: bool,
160    },
161    /// The host stopped (the transport closed, or the controller failed).
162    Stopped(String),
163}
164
165pub(crate) struct Inner {
166    pub(crate) hci: Hci,
167    pub(crate) caps: OnceLock<Capabilities>,
168    pub(crate) config: HostConfig,
169    pub(crate) events: broadcast::Sender<HostEvent>,
170    pub(crate) conns: Mutex<HashMap<u16, Arc<ConnState>>>,
171    pub(crate) scanner: Mutex<Scanner>,
172    pub(crate) advertiser: tokio::sync::Mutex<advertise::Advertiser>,
173    pub(crate) connect_waiter: Mutex<Option<oneshot::Sender<Result<Arc<ConnState>>>>>,
174    pub(crate) sync_waiter: Mutex<Option<oneshot::Sender<Result<u16>>>>,
175    pub(crate) keys: Keys,
176    pub(crate) gatt: Arc<Database>,
177    pub(crate) l2cap_servers: Mutex<HashMap<u16, (u16, mpsc::Sender<l2cap::Channel>)>>,
178    pub(crate) local_address: OnceLock<Address>,
179    pub(crate) stopped: watch::Sender<Option<String>>,
180}
181
182/// A running Bluetooth host on one controller. Cloning it is cheap; every
183/// clone drives the same controller.
184#[derive(Clone)]
185pub struct Host {
186    pub(crate) inner: Arc<Inner>,
187}
188
189impl Host {
190    /// Opens the controller named by `spec`, resets it and reads what it can do.
191    pub async fn open(spec: &TransportSpec, config: HostConfig) -> Result<Host> {
192        let (reader, writer) = transport::open(spec).await?;
193        Self::start(reader, writer, config).await
194    }
195
196    /// Starts on an already open transport.
197    pub async fn start(
198        reader: PacketReader,
199        writer: transport::PacketWriter,
200        config: HostConfig,
201    ) -> Result<Host> {
202        let keys = Keys::open(config.data_dir.as_deref())?;
203        let gatt = Arc::new(Database::new(&config.device_name, config.appearance));
204        let (events, _) = broadcast::channel(config.event_capacity.max(16));
205        let inner = Arc::new(Inner {
206            hci: Hci::new(writer),
207            caps: OnceLock::new(),
208            events,
209            conns: Mutex::new(HashMap::new()),
210            scanner: Mutex::new(Scanner::default()),
211            advertiser: tokio::sync::Mutex::new(advertise::Advertiser::default()),
212            connect_waiter: Mutex::new(None),
213            sync_waiter: Mutex::new(None),
214            keys,
215            gatt,
216            l2cap_servers: Mutex::new(HashMap::new()),
217            local_address: OnceLock::new(),
218            stopped: watch::channel(None).0,
219            config,
220        });
221        tokio::spawn(read_loop(Arc::downgrade(&inner), reader));
222        let host = Host { inner };
223        host.init().await?;
224        Ok(host)
225    }
226
227    async fn init(&self) -> Result<()> {
228        let hci = &self.inner.hci;
229        hci.command(
230            Reset::OPCODE_RAW,
231            &crate::hci::encode(&Reset::new()),
232            Duration::from_secs(10),
233        )
234        .await?;
235        let version = hci.exec(&ReadLocalVersionInformation::new()).await?;
236        let cmds = hci.exec(&ReadLocalSupportedCmds::new()).await?;
237        let cmds_raw = cmds.into_inner();
238        let lmp = hci.exec(&ReadLocalSupportedFeatures::new()).await?;
239        let addr = hci
240            .exec(&ReadBdAddr::new())
241            .await
242            .map(|a| a.raw().try_into().unwrap_or([0; 6]))
243            .unwrap_or([0; 6]);
244        let mut caps = Capabilities {
245            public_address: addr,
246            hci_version: version.hci_version.into_inner(),
247            hci_subversion: version.hci_subversion,
248            lmp_version: version.lmp_version.into_inner(),
249            lmp_subversion: version.lmp_subversion,
250            manufacturer: version.company_identifier,
251            commands: cmds_raw,
252            lmp_features: u64::from_le_bytes(lmp.into_inner()),
253            le_features: 0,
254            le_states: 0,
255            le_acl: (27, 1),
256            iso: (0, 0),
257            max_adv_data: 31,
258            adv_sets: 1,
259            filter_accept_list_size: 0,
260            resolving_list_size: 0,
261            max_data_length: (27, 328, 27, 328),
262        };
263        let m = caps.cmds();
264
265        hci.exec(&SetEventMask::new(
266            EventMask::new()
267                .enable_disconnection_complete(true)
268                .enable_encryption_change_v1(true)
269                .enable_read_remote_version_information_complete(true)
270                .enable_hardware_error(true)
271                .enable_data_buffer_overflow(true)
272                .enable_encryption_key_refresh_complete(true)
273                .enable_le_meta(true),
274        ))
275        .await?;
276
277        if m.le_read_local_supported_features() {
278            caps.le_features = u64::from_le_bytes(
279                hci.exec(&LeReadLocalSupportedFeatures::new())
280                    .await?
281                    .into_inner(),
282            );
283        }
284        if m.le_read_supported_states() {
285            caps.le_states = u64::from_le_bytes(hci.exec(&LeReadSupportedStates::new()).await?);
286        }
287        let b = hci.exec(&LeReadBufferSize::new()).await?;
288        caps.le_acl = (
289            b.le_acl_data_packet_length,
290            u16::from(b.total_num_le_acl_data_packets),
291        );
292        if caps.le_acl.1 == 0 {
293            // A controller that shares its BR/EDR buffers with LE. bt-hci has
294            // no HCI_Read_Buffer_Size yet, so it is sent raw:
295            // ACL length (2), SCO length (1), ACL count (2), SCO count (2).
296            if let crate::hci::Reply::Complete { status: 0, params } = hci
297                .command(0x1005, &[0x05, 0x10, 0x00], crate::hci::COMMAND_TIMEOUT)
298                .await?
299            {
300                if params.len() >= 5 {
301                    caps.le_acl = (
302                        u16::from_le_bytes([params[0], params[1]]),
303                        u16::from_le_bytes([params[3], params[4]]),
304                    );
305                }
306            }
307        }
308        hci.set_acl_buffers(caps.le_acl.0, caps.le_acl.1);
309
310        if m.le_read_filter_accept_list_size() {
311            caps.filter_accept_list_size = hci.exec(&LeReadFilterAcceptListSize::new()).await?;
312        }
313        if m.le_read_resolving_list_size() {
314            caps.resolving_list_size = hci.exec(&LeReadResolvingListSize::new()).await?;
315        }
316        if caps.data_length_extension() && m.le_read_maximum_data_length() {
317            let d = hci.exec(&LeReadMaxDataLength::new()).await?;
318            caps.max_data_length = (
319                d.supported_max_tx_octets,
320                d.supported_max_tx_time,
321                d.supported_max_rx_octets,
322                d.supported_max_rx_time,
323            );
324            if m.le_write_suggested_default_data_length() {
325                hci.exec(&LeWriteSuggestedDefaultDataLength::new(
326                    d.supported_max_tx_octets,
327                    d.supported_max_tx_time,
328                ))
329                .await?;
330            }
331        }
332        if caps.extended_advertising() {
333            // Mandatory with the feature; a controller that refuses them
334            // keeps the legacy limits.
335            if let Ok(n) = hci.exec(&LeReadMaxAdvDataLength::new()).await {
336                caps.max_adv_data = n;
337            }
338            if let Ok(n) = hci.exec(&LeReadNumberOfSupportedAdvSets::new()).await {
339                caps.adv_sets = n.max(1);
340            }
341        }
342        if m.le_set_default_phy() && (caps.phy_2m() || caps.coded_phy()) {
343            // Let the controller use every PHY it has; peers negotiate down.
344            let mut phys = PhyMask::new().set_le_1m_phy(true);
345            if caps.phy_2m() {
346                phys = phys.set_le_2m_phy(true);
347            }
348            if caps.coded_phy() {
349                phys = phys.set_le_coded_phy(true);
350            }
351            hci.exec(&LeSetDefaultPhy::new(AllPhys::new(), phys, phys))
352                .await?;
353        }
354
355        let mut le_mask = LeEventMask::new()
356            .enable_le_conn_complete(true)
357            .enable_le_adv_report(true)
358            .enable_le_conn_update_complete(true)
359            .enable_le_read_remote_features_page_0_complete(true)
360            .enable_le_long_term_key_request(true)
361            .enable_le_remote_conn_parameter_request(true)
362            .enable_le_data_length_change(true)
363            .enable_le_enhanced_conn_complete_v1(true)
364            .enable_le_directed_adv_report(true)
365            .enable_le_phy_update_complete(true)
366            .enable_le_channel_selection_algorithm(true);
367        if caps.extended_scanning() || caps.extended_advertising() {
368            le_mask = le_mask
369                .enable_le_ext_adv_report(true)
370                .enable_le_scan_timeout(true)
371                .enable_le_adv_set_terminated(true)
372                .enable_le_scan_request_received(true);
373        }
374        if caps.periodic_advertising() {
375            le_mask = le_mask
376                .enable_le_periodic_adv_sync_established_v1(true)
377                .enable_le_periodic_adv_report_v1(true)
378                .enable_le_periodic_adv_sync_lost(true);
379        }
380        hci.exec(&LeSetEventMask::new(le_mask)).await?;
381
382        // Our identity address.
383        let identity = if self.inner.config.use_public_address && addr != [0; 6] {
384            Address::public(addr)
385        } else {
386            let a = self.inner.keys.local_static_address();
387            hci.exec(&LeSetRandomAddr::new(BdAddr::new(a.bytes)))
388                .await?;
389            a
390        };
391        let _ = self.inner.local_address.set(identity);
392        tracing::info!(
393            "controller {} ({}), {}, LE features: {}",
394            identity,
395            caps.manufacturer_name().unwrap_or("unknown manufacturer"),
396            caps.version_name().unwrap_or("unknown version"),
397            caps.le_feature_names().join(", ")
398        );
399        let _ = self.inner.caps.set(caps);
400        Ok(())
401    }
402
403    /// What the controller can do.
404    pub fn capabilities(&self) -> &Capabilities {
405        // Set before `start` returns.
406        self.inner
407            .caps
408            .get()
409            .expect("capabilities are read at start")
410    }
411
412    /// Our identity address (public, or the static random one).
413    pub fn address(&self) -> Address {
414        *self
415            .inner
416            .local_address
417            .get()
418            .expect("address is set at start")
419    }
420
421    /// Events, from now on. Each call gets its own receiver.
422    pub fn events(&self) -> broadcast::Receiver<HostEvent> {
423        self.inner.events.subscribe()
424    }
425
426    /// Resolves when the host stops, with the reason.
427    pub async fn stopped(&self) -> String {
428        let mut rx = self.inner.stopped.subscribe();
429        loop {
430            if let Some(r) = rx.borrow().clone() {
431                return r;
432            }
433            if rx.changed().await.is_err() {
434                return "host dropped".into();
435            }
436        }
437    }
438
439    /// The GATT server's database: add services, set values, notify.
440    pub fn gatt_server(&self) -> crate::gatt::server::Server {
441        crate::gatt::server::Server { host: self.clone() }
442    }
443
444    /// Bonds and keys.
445    pub fn keys(&self) -> &Keys {
446        &self.inner.keys
447    }
448
449    /// Open connections.
450    pub fn connections(&self) -> Vec<Connection> {
451        self.inner
452            .conns
453            .lock()
454            .unwrap_or_else(|e| e.into_inner())
455            .values()
456            .map(|s| Connection::new(self.clone(), s.clone()))
457            .collect()
458    }
459
460    /// A connection by handle.
461    pub fn connection(&self, handle: u16) -> Option<Connection> {
462        self.inner
463            .conns
464            .lock()
465            .unwrap_or_else(|e| e.into_inner())
466            .get(&handle)
467            .map(|s| Connection::new(self.clone(), s.clone()))
468    }
469
470    pub(crate) fn emit(&self, e: HostEvent) {
471        let _ = self.inner.events.send(e);
472    }
473}
474
475impl Inner {
476    pub(crate) fn caps(&self) -> &Capabilities {
477        self.caps.get().expect("capabilities are read at start")
478    }
479}
480
481/// Reads packets until the transport closes, dispatching each.
482async fn read_loop(weak: std::sync::Weak<Inner>, mut reader: PacketReader) {
483    let mut acl = Reassembly::default();
484    let reason = loop {
485        let packet = reader.read().await;
486        let Some(inner) = weak.upgrade() else { return };
487        let host = Host { inner };
488        match packet {
489            Ok(Packet::Event(bytes)) => {
490                if let Some(fatal) = on_event(&host, &bytes) {
491                    break fatal;
492                }
493                // Disconnection Complete: drop any half-received PDU.
494                if bytes.first() == Some(&0x05) && bytes.len() >= 6 {
495                    acl.close(u16::from_le_bytes([bytes[3], bytes[4]]) & 0x0fff);
496                }
497            }
498            Ok(Packet::Acl(bytes)) => {
499                if let Some((handle, pdu)) = acl.push(&bytes) {
500                    l2cap::dispatch(&host, handle, pdu);
501                }
502            }
503            Ok(_) => {}
504            Err(e) => break format!("transport: {e}"),
505        }
506    };
507    tracing::error!("host stopped: {reason}");
508    if let Some(inner) = weak.upgrade() {
509        let host = Host { inner };
510        host.inner.hci.shutdown();
511        let conns: Vec<_> = host
512            .inner
513            .conns
514            .lock()
515            .unwrap_or_else(|e| e.into_inner())
516            .drain()
517            .map(|(_, c)| c)
518            .collect();
519        for c in conns {
520            c.close(0x08);
521        }
522        host.emit(HostEvent::Stopped(reason.clone()));
523        let _ = host.inner.stopped.send(Some(reason));
524    }
525}
526
527/// Rejects malformed HCI events before they are handed to the parser: each
528/// LE Extended Advertising Report must hold its 24 fixed octets and the data
529/// its length names. bt-hci 0.11 panics on a report that ends after
530/// Primary_PHY (https://github.com/embassy-rs/bt-hci/issues/110); delete this
531/// once a release with the fix is the one we use.
532pub(crate) fn well_formed(bytes: &[u8]) -> bool {
533    if bytes.first() != Some(&0x3e) || bytes.get(2) != Some(&0x0d) {
534        return true;
535    }
536    let end = (2 + usize::from(bytes.get(1).copied().unwrap_or(0))).min(bytes.len());
537    let Some(&n) = bytes.get(3) else { return false };
538    let mut at = 4;
539    for _ in 0..n {
540        let Some(&len) = bytes.get(at + 23) else {
541            return false;
542        };
543        at += 24 + usize::from(len);
544        if at > end {
545            return false;
546        }
547    }
548    true
549}
550
551/// Handles one event; returns a reason when the host must stop.
552fn on_event(host: &Host, bytes: &[u8]) -> Option<String> {
553    if !well_formed(bytes) {
554        tracing::warn!("dropping a malformed extended advertising report");
555        return None;
556    }
557    let event = match Event::from_hci_bytes(bytes) {
558        Ok((e, _)) => e,
559        Err(e) => {
560            tracing::debug!("unparsed event {:02x?}: {e:?}", bytes.get(..2));
561            return None;
562        }
563    };
564    let inner = &host.inner;
565    match event {
566        Event::CommandComplete(e) => inner.hci.complete(e.cmd_opcode.to_raw(), &e.bytes),
567        Event::CommandStatus(e) => inner
568            .hci
569            .status(e.cmd_opcode.to_raw(), e.status.into_inner()),
570        Event::NumberOfCompletedPackets(e) => {
571            for c in e.completed_packets {
572                if let (Ok(h), Ok(n)) = (c.handle(), c.num_completed_packets()) {
573                    inner.hci.completed(h.raw(), n);
574                }
575            }
576        }
577        Event::DisconnectionComplete(e) => {
578            let handle = e.handle.raw();
579            inner.hci.close_handle(handle);
580            let conn = inner
581                .conns
582                .lock()
583                .unwrap_or_else(|e| e.into_inner())
584                .remove(&handle);
585            if let Some(c) = conn {
586                let reason = e.reason.into_inner();
587                // Keep a bonded client's subscriptions for its next connection.
588                let cccd = inner.gatt.connection_closed(handle);
589                let identity = c.identity();
590                if inner.keys.bond(&identity).is_some() {
591                    if let Err(e) = inner.keys.update(&identity, |b| b.cccd = cccd) {
592                        tracing::warn!("saving {identity}'s subscriptions: {e}");
593                    }
594                }
595                c.close(reason);
596                host.emit(HostEvent::Disconnected {
597                    handle,
598                    peer: c.peer,
599                    reason,
600                });
601            }
602        }
603        Event::EncryptionChangeV1(e) => {
604            if let Some(c) = host.state(e.handle.raw()) {
605                c.encryption_changed(e.status.into_inner(), e.enabled as u8 != 0);
606            }
607        }
608        Event::EncryptionKeyRefreshComplete(e) => {
609            if let Some(c) = host.state(e.handle.raw()) {
610                c.encryption_changed(e.status.into_inner(), true);
611            }
612        }
613        Event::HardwareError(e) => {
614            return Some(format!(
615                "controller hardware error {:#04x}",
616                e.hardware_code
617            ))
618        }
619        Event::DataBufferOverflow(_) => tracing::warn!("controller reports an ACL buffer overflow"),
620        Event::Le(le) => on_le_event(host, le),
621        _ => {}
622    }
623    None
624}
625
626fn on_le_event(host: &Host, le: LeEvent<'_>) {
627    let inner = &host.inner;
628    match le {
629        LeEvent::LeAdvertisingReport(e) => {
630            for r in e.reports.iter().flatten() {
631                scan::on_legacy_report(host, &r);
632            }
633        }
634        LeEvent::LeExtendedAdvertisingReport(e) => {
635            for r in e.reports.iter().flatten() {
636                scan::on_extended_report(host, &r);
637            }
638        }
639        LeEvent::LeDirectedAdvertisingReport(e) => {
640            for r in e.reports {
641                scan::on_directed_report(host, r);
642            }
643        }
644        LeEvent::LePeriodicAdvertisingSyncEstablished(e) => {
645            let status = e.status.into_inner();
646            let result = if status == 0 {
647                scan::on_sync_established(host, &e);
648                Ok(e.sync_handle.into_inner())
649            } else {
650                Err(Error::hci(0x2044, status))
651            };
652            if let Some(w) = inner
653                .sync_waiter
654                .lock()
655                .unwrap_or_else(|e| e.into_inner())
656                .take()
657            {
658                let _ = w.send(result);
659            }
660        }
661        LeEvent::LePeriodicAdvertisingReport(e) => scan::on_periodic_report(host, &e),
662        LeEvent::LePeriodicAdvertisingSyncLost(e) => {
663            scan::on_sync_lost(host, e.sync_handle.into_inner());
664            host.emit(HostEvent::PeriodicSyncLost {
665                sync: e.sync_handle.into_inner(),
666            });
667        }
668        LeEvent::LeConnectionComplete(e) => connection_complete(
669            host,
670            e.status.into_inner(),
671            e.handle.raw(),
672            e.role as u8 == 0,
673            Address::from_hci(e.peer_addr_kind.into_inner(), raw6(&e.peer_addr)),
674            None,
675            (
676                e.conn_interval.as_u16(),
677                e.peripheral_latency,
678                e.supervision_timeout.as_u16(),
679            ),
680        ),
681        LeEvent::LeEnhancedConnectionComplete(e) => {
682            let peer_rpa = raw6(&e.peer_resolvable_private_addr);
683            connection_complete(
684                host,
685                e.status.into_inner(),
686                e.handle.raw(),
687                e.role as u8 == 0,
688                Address::from_hci(e.peer_addr_kind.into_inner(), raw6(&e.peer_addr)),
689                (peer_rpa != [0; 6]).then_some(Address::random(peer_rpa)),
690                (
691                    e.conn_interval.as_u16(),
692                    e.peripheral_latency,
693                    e.supervision_timeout.as_u16(),
694                ),
695            )
696        }
697        LeEvent::LeConnectionUpdateComplete(e) => {
698            if let Some(c) = host.state(e.handle.raw()) {
699                c.params_updated(
700                    e.status.into_inner(),
701                    e.conn_interval.as_u16(),
702                    e.peripheral_latency,
703                    e.supervision_timeout.as_u16(),
704                );
705            }
706        }
707        LeEvent::LeRemoteConnectionParameterRequest(e) => {
708            crate::connection::on_remote_param_request(
709                host,
710                e.handle.raw(),
711                e.interval_min.as_u16(),
712                e.interval_max.as_u16(),
713                e.max_latency,
714                e.timeout.as_u16(),
715            );
716        }
717        LeEvent::LeDataLengthChange(e) => {
718            if let Some(c) = host.state(e.handle.raw()) {
719                c.data_length_changed(
720                    e.max_tx_octets,
721                    e.max_tx_time,
722                    e.max_rx_octets,
723                    e.max_rx_time,
724                );
725            }
726        }
727        LeEvent::LePhyUpdateComplete(e) => {
728            if let Some(c) = host.state(e.handle.raw()) {
729                c.phy_updated(e.status.into_inner(), e.tx_phy as u8, e.rx_phy as u8);
730            }
731        }
732        LeEvent::LeReadRemoteFeaturesComplete(e) => {
733            if let Some(c) = host.state(e.handle.raw()) {
734                c.remote_features(
735                    e.status.into_inner(),
736                    u64::from_le_bytes(e.le_features.into_inner()),
737                );
738            }
739        }
740        LeEvent::LeLongTermKeyRequest(e) => {
741            smp::on_ltk_request(
742                host,
743                e.handle.raw(),
744                e.random_number,
745                e.encrypted_diversifier,
746            );
747        }
748        LeEvent::LeAdvertisingSetTerminated(e) => {
749            let set = e.adv_handle.as_raw();
750            let conn = (e.status.into_inner() == 0).then_some(e.handle.raw());
751            advertise::on_set_terminated(host, set, conn);
752            host.emit(HostEvent::AdvertisingStopped {
753                set,
754                connection: conn,
755            });
756        }
757        LeEvent::LeScanRequestReceived(e) => host.emit(HostEvent::ScanRequest {
758            set: e.adv_handle.as_raw(),
759            scanner: Address::from_hci(e.scanner_addr_kind.into_inner(), raw6(&e.scanner_addr)),
760        }),
761        LeEvent::LeScanTimeout(_) => scan::on_scan_timeout(host),
762        _ => {}
763    }
764}
765
766pub(crate) fn raw6(a: &BdAddr) -> [u8; 6] {
767    a.raw().try_into().unwrap_or([0; 6])
768}
769
770fn connection_complete(
771    host: &Host,
772    status: u8,
773    handle: u16,
774    central: bool,
775    peer: Address,
776    peer_rpa: Option<Address>,
777    params: (u16, u16, u16),
778) {
779    let inner = &host.inner;
780    if status != 0 {
781        // A failed or cancelled connect (0x02 after a cancel, 0x3c for an
782        // advertising timeout). Only a pending connect() cares.
783        if let Some(w) = inner
784            .connect_waiter
785            .lock()
786            .unwrap_or_else(|e| e.into_inner())
787            .take()
788        {
789            let _ = w.send(Err(Error::hci(0x200d, status)));
790        }
791        return;
792    }
793    let role = if central {
794        Role::Central
795    } else {
796        Role::Peripheral
797    };
798    // The address the peer actually used on the air, for SMP's c1/f5/f6.
799    let on_air = peer_rpa.unwrap_or(peer);
800    let state = ConnState::spawn(host, handle, role, on_air);
801    // The peer's identity: from an IRK for a private address, or a bond.
802    if let Some(id) = inner.keys.identity_of(&on_air) {
803        state.set_identity(id);
804    } else if peer_rpa.is_some() {
805        state.set_identity(peer);
806    }
807    state.set_params(params.0, params.1, params.2);
808    if let Some(bond) = inner.keys.bond(&state.identity()) {
809        inner.gatt.restore(handle, &bond.cccd);
810    }
811    inner
812        .conns
813        .lock()
814        .unwrap_or_else(|e| e.into_inner())
815        .insert(handle, state.clone());
816    let conn = Connection::new(host.clone(), state.clone());
817    if central {
818        if let Some(w) = inner
819            .connect_waiter
820            .lock()
821            .unwrap_or_else(|e| e.into_inner())
822            .take()
823        {
824            let _ = w.send(Ok(state));
825        }
826    }
827    host.emit(HostEvent::Connected(conn));
828}
829
830impl Host {
831    pub(crate) fn state(&self, handle: u16) -> Option<Arc<ConnState>> {
832        self.inner
833            .conns
834            .lock()
835            .unwrap_or_else(|e| e.into_inner())
836            .get(&handle)
837            .cloned()
838    }
839}
840
841/// The opcode of HCI_Reset, for the longer timeout it gets.
842trait OpcodeRaw {
843    const OPCODE_RAW: u16;
844}
845
846impl OpcodeRaw for Reset {
847    const OPCODE_RAW: u16 = <Reset as bt_hci::cmd::Cmd>::OPCODE.to_raw();
848}