Skip to main content

bluetooth_host/
transport.rs

1//! Moving HCI packets to and from a controller.
2//!
3//! | Transport | Spec | Use |
4//! |---|---|---|
5//! | Linux HCI user channel | `hci0` | any controller the kernel has a driver for (btusb, hci_uart after `hciattach`); the kernel loads its firmware and then hands the whole controller to us |
6//! | H4 over a serial port | `serial:/dev/ttyAMA0:115200` | UART controllers, with no kernel driver at all |
7//! | H4 over TCP | `tcp:127.0.0.1:9000` | virtual controllers (Bumble), network HCI bridges |
8//!
9//! The user channel needs the interface down and nothing else using it: on a
10//! system with BlueZ, stop `bluetoothd` first. Opening it needs
11//! `CAP_NET_ADMIN`.
12
13use std::fmt;
14use std::io;
15use std::str::FromStr;
16
17use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
18
19/// HCI packet indicators (H4).
20pub mod indicator {
21    /// Command, host to controller.
22    pub const COMMAND: u8 = 0x01;
23    /// ACL data.
24    pub const ACL: u8 = 0x02;
25    /// Synchronous (SCO) data.
26    pub const SCO: u8 = 0x03;
27    /// Event, controller to host.
28    pub const EVENT: u8 = 0x04;
29    /// Isochronous data.
30    pub const ISO: u8 = 0x05;
31}
32
33/// One HCI packet, without its H4 indicator.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum Packet {
36    /// A command (header included).
37    Command(Vec<u8>),
38    /// ACL data (header included).
39    Acl(Vec<u8>),
40    /// SCO data (header included).
41    Sco(Vec<u8>),
42    /// An event (header included).
43    Event(Vec<u8>),
44    /// ISO data (header included).
45    Iso(Vec<u8>),
46}
47
48impl Packet {
49    /// The H4 indicator.
50    pub fn indicator(&self) -> u8 {
51        match self {
52            Packet::Command(_) => indicator::COMMAND,
53            Packet::Acl(_) => indicator::ACL,
54            Packet::Sco(_) => indicator::SCO,
55            Packet::Event(_) => indicator::EVENT,
56            Packet::Iso(_) => indicator::ISO,
57        }
58    }
59
60    /// The bytes after the indicator.
61    pub fn bytes(&self) -> &[u8] {
62        match self {
63            Packet::Command(b)
64            | Packet::Acl(b)
65            | Packet::Sco(b)
66            | Packet::Event(b)
67            | Packet::Iso(b) => b,
68        }
69    }
70
71    /// Splits an H4 frame (indicator first) into a packet, checking that the
72    /// length in its header matches.
73    pub fn from_h4(frame: &[u8]) -> io::Result<Packet> {
74        let (&ind, rest) = frame
75            .split_first()
76            .ok_or_else(|| invalid("empty HCI packet"))?;
77        let header = header_len(ind)?;
78        if rest.len() < header || rest.len() != header + payload_len(ind, &rest[..header]) {
79            return Err(invalid("HCI packet length does not match its header"));
80        }
81        Ok(Self::with_indicator(ind, rest.to_vec()))
82    }
83
84    fn with_indicator(ind: u8, b: Vec<u8>) -> Packet {
85        match ind {
86            indicator::COMMAND => Packet::Command(b),
87            indicator::ACL => Packet::Acl(b),
88            indicator::SCO => Packet::Sco(b),
89            indicator::EVENT => Packet::Event(b),
90            _ => Packet::Iso(b),
91        }
92    }
93}
94
95fn invalid(msg: &str) -> io::Error {
96    io::Error::new(io::ErrorKind::InvalidData, msg)
97}
98
99fn header_len(ind: u8) -> io::Result<usize> {
100    match ind {
101        indicator::COMMAND | indicator::SCO => Ok(3),
102        indicator::ACL | indicator::ISO => Ok(4),
103        indicator::EVENT => Ok(2),
104        other => Err(invalid(&format!(
105            "unknown HCI packet indicator {other:#04x}"
106        ))),
107    }
108}
109
110fn payload_len(ind: u8, h: &[u8]) -> usize {
111    match ind {
112        indicator::COMMAND | indicator::SCO => usize::from(h[2]),
113        indicator::ACL => usize::from(u16::from_le_bytes([h[2], h[3]])),
114        indicator::ISO => usize::from(u16::from_le_bytes([h[2], h[3]]) & 0x3fff),
115        _ => usize::from(h[1]),
116    }
117}
118
119/// Which controller to open.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub enum TransportSpec {
122    /// The Linux HCI user channel of `hciN`.
123    UserChannel(u16),
124    /// H4 over a serial port.
125    Serial {
126        /// The device path.
127        path: String,
128        /// Baud rate.
129        baud: u32,
130        /// RTS/CTS flow control (most UART controllers need it).
131        flow_control: bool,
132    },
133    /// H4 over TCP, as `host:port`.
134    Tcp(String),
135}
136
137impl fmt::Display for TransportSpec {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        match self {
140            TransportSpec::UserChannel(n) => write!(f, "hci{n}"),
141            TransportSpec::Serial {
142                path,
143                baud,
144                flow_control,
145            } => write!(
146                f,
147                "serial:{path}:{baud}{}",
148                if *flow_control { "" } else { ":noflow" }
149            ),
150            TransportSpec::Tcp(a) => write!(f, "tcp:{a}"),
151        }
152    }
153}
154
155impl FromStr for TransportSpec {
156    type Err = String;
157
158    /// `hci0`, `serial:/dev/ttyUSB0:115200` (append `:noflow` to turn RTS/CTS
159    /// off), or `tcp:host:port`.
160    fn from_str(s: &str) -> Result<Self, Self::Err> {
161        if let Some(n) = s.strip_prefix("hci") {
162            let n = n.trim_start_matches(':');
163            return n
164                .parse()
165                .map(TransportSpec::UserChannel)
166                .map_err(|_| format!("bad HCI device {s:?}"));
167        }
168        if let Some(a) = s.strip_prefix("tcp:") {
169            return Ok(TransportSpec::Tcp(a.trim_start_matches("//").to_string()));
170        }
171        if let Some(rest) = s.strip_prefix("serial:") {
172            let mut parts: Vec<&str> = rest.split(':').collect();
173            let flow_control = if parts.last() == Some(&"noflow") {
174                parts.pop();
175                false
176            } else {
177                true
178            };
179            let (path, baud) = match parts.as_slice() {
180                [path] => (path.to_string(), 115_200),
181                [path, baud] => (
182                    path.to_string(),
183                    baud.parse()
184                        .map_err(|_| format!("bad baud rate in {s:?}"))?,
185                ),
186                _ => return Err(format!("bad serial spec {s:?}")),
187            };
188            return Ok(TransportSpec::Serial {
189                path,
190                baud,
191                flow_control,
192            });
193        }
194        Err(format!(
195            "unknown transport {s:?}: want hciN, serial:PATH:BAUD or tcp:HOST:PORT"
196        ))
197    }
198}
199
200type BoxRead = Box<dyn AsyncRead + Send + Unpin>;
201type BoxWrite = Box<dyn AsyncWrite + Send + Unpin>;
202
203/// Reads whole packets.
204pub struct PacketReader {
205    inner: ReadKind,
206}
207
208enum ReadKind {
209    /// A byte stream with H4 framing (UART, TCP).
210    Stream(BufReader<BoxRead>),
211    /// A socket that returns one packet per read (the user channel).
212    Datagram(BoxRead, Vec<u8>),
213}
214
215/// Writes whole packets.
216pub struct PacketWriter {
217    inner: BoxWrite,
218}
219
220impl PacketReader {
221    /// Wraps a byte stream carrying H4 frames.
222    pub fn stream(r: impl AsyncRead + Send + Unpin + 'static) -> Self {
223        PacketReader {
224            inner: ReadKind::Stream(BufReader::with_capacity(4096, Box::new(r))),
225        }
226    }
227
228    /// Wraps a socket that returns exactly one H4 frame per read.
229    pub fn datagram(r: impl AsyncRead + Send + Unpin + 'static) -> Self {
230        PacketReader {
231            inner: ReadKind::Datagram(Box::new(r), vec![0u8; 1 + 4 + 65_535]),
232        }
233    }
234
235    /// The next packet. An error means the transport is gone or out of sync.
236    pub async fn read(&mut self) -> io::Result<Packet> {
237        match &mut self.inner {
238            ReadKind::Stream(r) => {
239                let ind = r.read_u8().await?;
240                let hl = header_len(ind)?;
241                let mut buf = vec![0u8; hl];
242                r.read_exact(&mut buf).await?;
243                let pl = payload_len(ind, &buf);
244                buf.resize(hl + pl, 0);
245                r.read_exact(&mut buf[hl..]).await?;
246                Ok(Packet::with_indicator(ind, buf))
247            }
248            ReadKind::Datagram(r, buf) => loop {
249                let n = r.read(buf).await?;
250                if n == 0 {
251                    return Err(io::Error::new(
252                        io::ErrorKind::UnexpectedEof,
253                        "HCI socket closed",
254                    ));
255                }
256                match Packet::from_h4(&buf[..n]) {
257                    Ok(p) => return Ok(p),
258                    Err(e) => tracing::warn!("dropping malformed HCI packet: {e}"),
259                }
260            },
261        }
262    }
263}
264
265impl PacketWriter {
266    /// Wraps the write half of a transport.
267    pub fn new(w: impl AsyncWrite + Send + Unpin + 'static) -> Self {
268        PacketWriter { inner: Box::new(w) }
269    }
270
271    /// Writes one packet, indicator first, in a single write.
272    pub async fn write(&mut self, indicator: u8, bytes: &[u8]) -> io::Result<()> {
273        let mut frame = Vec::with_capacity(1 + bytes.len());
274        frame.push(indicator);
275        frame.extend_from_slice(bytes);
276        self.inner.write_all(&frame).await?;
277        self.inner.flush().await
278    }
279}
280
281/// Opens a transport.
282pub async fn open(spec: &TransportSpec) -> io::Result<(PacketReader, PacketWriter)> {
283    match spec {
284        TransportSpec::Tcp(addr) => {
285            let s = tokio::net::TcpStream::connect(addr).await?;
286            s.set_nodelay(true)?;
287            let (r, w) = s.into_split();
288            Ok((PacketReader::stream(r), PacketWriter::new(w)))
289        }
290        #[cfg(feature = "serial")]
291        TransportSpec::Serial {
292            path,
293            baud,
294            flow_control,
295        } => {
296            use tokio_serial::SerialPortBuilderExt;
297            let port = tokio_serial::new(path, *baud)
298                .flow_control(if *flow_control {
299                    tokio_serial::FlowControl::Hardware
300                } else {
301                    tokio_serial::FlowControl::None
302                })
303                .open_native_async()
304                .map_err(io::Error::other)?;
305            let (r, w) = tokio::io::split(port);
306            Ok((PacketReader::stream(r), PacketWriter::new(w)))
307        }
308        #[cfg(not(feature = "serial"))]
309        TransportSpec::Serial { .. } => Err(io::Error::new(
310            io::ErrorKind::Unsupported,
311            "built without the `serial` feature",
312        )),
313        TransportSpec::UserChannel(dev) => user_channel(*dev).await,
314    }
315}
316
317#[cfg(target_os = "linux")]
318async fn user_channel(dev: u16) -> io::Result<(PacketReader, PacketWriter)> {
319    // The kernel refuses the bind (EBUSY) while the interface is up or still
320    // being set up after hotplug (firmware loading); wait that out.
321    let mut tries = 0;
322    let socket = loop {
323        match bt_hci_linux::Socket::new(dev) {
324            Ok(s) => break s,
325            Err(e) if e.raw_os_error() == Some(16) && tries < 20 => {
326                tries += 1;
327                tracing::info!("hci{dev} is busy (up, or still loading firmware); retrying");
328                tokio::time::sleep(std::time::Duration::from_millis(500)).await;
329            }
330            Err(e) if e.raw_os_error() == Some(16) => {
331                return Err(io::Error::new(
332                    e.kind(),
333                    format!(
334                        "hci{dev} stays busy: is bluetoothd running, or the interface up? ({e})"
335                    ),
336                ))
337            }
338            Err(e) => return Err(e),
339        }
340    };
341    let (r, w) = tokio::io::split(socket);
342    Ok((PacketReader::datagram(r), PacketWriter::new(w)))
343}
344
345#[cfg(not(target_os = "linux"))]
346async fn user_channel(_dev: u16) -> io::Result<(PacketReader, PacketWriter)> {
347    Err(io::Error::new(
348        io::ErrorKind::Unsupported,
349        "the HCI user channel exists only on Linux; use serial: or tcp:",
350    ))
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356
357    #[test]
358    fn specs() {
359        assert_eq!("hci0".parse(), Ok(TransportSpec::UserChannel(0)));
360        assert_eq!("hci:1".parse(), Ok(TransportSpec::UserChannel(1)));
361        assert_eq!(
362            "tcp:127.0.0.1:9000".parse(),
363            Ok(TransportSpec::Tcp("127.0.0.1:9000".into()))
364        );
365        assert_eq!(
366            "serial:/dev/ttyAMA0:460800:noflow".parse(),
367            Ok(TransportSpec::Serial {
368                path: "/dev/ttyAMA0".into(),
369                baud: 460_800,
370                flow_control: false
371            })
372        );
373        assert!("usb:0".parse::<TransportSpec>().is_err());
374    }
375
376    #[tokio::test]
377    async fn h4_stream_framing() {
378        // An event (Command Complete, Reset), then ACL data, split arbitrarily.
379        let bytes = [
380            0x04u8, 0x0e, 0x04, 0x01, 0x03, 0x0c, 0x00, 0x02, 0x40, 0x20, 0x02, 0x00, 0xaa, 0xbb,
381        ];
382        let (a, mut b) = tokio::io::duplex(64);
383        tokio::spawn(async move {
384            for c in bytes.chunks(3) {
385                b.write_all(c).await.unwrap();
386            }
387        });
388        let mut r = PacketReader::stream(a);
389        assert_eq!(
390            r.read().await.unwrap(),
391            Packet::Event(vec![0x0e, 0x04, 0x01, 0x03, 0x0c, 0x00])
392        );
393        assert_eq!(
394            r.read().await.unwrap(),
395            Packet::Acl(vec![0x40, 0x20, 0x02, 0x00, 0xaa, 0xbb])
396        );
397        assert!(r.read().await.is_err());
398    }
399
400    #[test]
401    fn from_h4_checks_length() {
402        assert!(Packet::from_h4(&[0x04, 0x0e, 0x01, 0x00]).is_ok());
403        assert!(Packet::from_h4(&[0x04, 0x0e, 0x02, 0x00]).is_err());
404        assert!(Packet::from_h4(&[0x09, 0x00]).is_err());
405        assert!(Packet::from_h4(&[]).is_err());
406    }
407}