Skip to main content

bt_hci_linux/
lib.rs

1#[cfg(not(target_os = "linux"))]
2compile_error!("Only Linux is supported");
3
4use core::future::Future;
5use core::mem;
6use core::pin::Pin;
7use core::task::{ready, Context, Poll};
8use std::io;
9use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd};
10
11use bt_hci_transport::{PacketKind, PacketToController, PacketToHost, ReadHciError, WithIndicator};
12use tokio::io::unix::AsyncFd;
13use tokio::io::{split, AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _, ReadBuf, ReadHalf, WriteHalf};
14use tokio::sync::Mutex;
15
16const BTPROTO_HCI: libc::c_int = 1;
17const HCI_CHANNEL_USER: libc::c_ushort = 1;
18#[repr(C)]
19#[derive(Debug, Copy, Clone)]
20struct sockaddr_hci {
21    hci_family: libc::c_ushort,
22    hci_dev: libc::c_ushort,
23    hci_channel: libc::c_ushort,
24}
25
26#[derive(Debug)]
27#[allow(dead_code)]
28pub enum Error {
29    ReadHci(ReadHciError<core::convert::Infallible>),
30    Io(io::Error),
31}
32
33impl core::error::Error for Error {}
34
35impl core::fmt::Display for Error {
36    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
37        write!(f, "{:?}", self)
38    }
39}
40
41impl embedded_io::Error for Error {
42    fn kind(&self) -> embedded_io::ErrorKind {
43        embedded_io::ErrorKind::Other
44    }
45}
46
47impl From<ReadHciError<core::convert::Infallible>> for Error {
48    fn from(e: ReadHciError<core::convert::Infallible>) -> Self {
49        Self::ReadHci(e)
50    }
51}
52
53pub struct Socket {
54    fd: AsyncFd<OwnedFd>,
55}
56
57// We use `libc` directly because
58// * `nix` makes it awkward to bind an arbitrary address
59// * `rustix` makes it awkward to set arbitrary sockopts
60impl Socket {
61    pub fn new(dev: u16) -> io::Result<Self> {
62        let fd = unsafe {
63            libc::socket(
64                libc::AF_BLUETOOTH,
65                libc::SOCK_RAW | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK,
66                BTPROTO_HCI,
67            )
68        };
69        let fd = if fd < 0i32 {
70            return Err(io::Error::last_os_error());
71        } else {
72            unsafe { OwnedFd::from_raw_fd(fd) }
73        };
74
75        let mut addr: sockaddr_hci = unsafe { mem::zeroed() };
76        addr.hci_family = libc::AF_BLUETOOTH as u16;
77        addr.hci_dev = dev;
78        addr.hci_channel = HCI_CHANNEL_USER;
79        if unsafe {
80            libc::bind(
81                fd.as_raw_fd(),
82                (&raw const addr).cast(),
83                mem::size_of::<sockaddr_hci>() as libc::socklen_t,
84            )
85        } < 0i32
86        {
87            return Err(io::Error::last_os_error());
88        }
89
90        Ok(Self { fd: AsyncFd::new(fd)? })
91    }
92}
93
94impl AsyncRead for Socket {
95    fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
96        let Self { ref mut fd } = *self.get_mut();
97        loop {
98            let mut guard = ready!(fd.poll_read_ready_mut(cx))?;
99
100            let unfilled = buf.initialize_unfilled();
101            match guard.try_io(|inner| {
102                let ret = unsafe { libc::read(inner.as_raw_fd(), unfilled.as_mut_ptr().cast(), unfilled.len()) };
103                usize::try_from(ret).map_err(|_try_from_int_error| io::Error::last_os_error())
104            }) {
105                Ok(result) => {
106                    return Poll::Ready(result.map(|len| buf.advance(len)));
107                }
108                Err(_would_block) => {}
109            }
110        }
111    }
112}
113
114impl AsyncWrite for Socket {
115    fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
116        let Self { ref mut fd } = *self.get_mut();
117        loop {
118            let mut guard = ready!(fd.poll_write_ready_mut(cx))?;
119
120            match guard.try_io(|inner| {
121                let ret = unsafe { libc::write(inner.as_raw_fd(), buf.as_ptr().cast(), buf.len()) };
122                usize::try_from(ret).map_err(|_try_from_int_error| io::Error::last_os_error())
123            }) {
124                Ok(result) => {
125                    return Poll::Ready(result);
126                }
127                Err(_would_block) => {}
128            }
129        }
130    }
131
132    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
133        Poll::Ready(Ok(()))
134    }
135
136    fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
137        Poll::Ready(Ok(()))
138    }
139}
140
141pub struct Transport {
142    rx: Mutex<ReadHalf<Socket>>,
143    tx: Mutex<WriteHalf<Socket>>,
144}
145
146impl Transport {
147    pub fn new(dev: u16) -> Result<Self, io::Error> {
148        let (rx, tx) = split(Socket::new(dev)?);
149        Ok(Self {
150            rx: Mutex::new(rx),
151            tx: Mutex::new(tx),
152        })
153    }
154}
155
156impl bt_hci_transport::Transport for Transport {
157    async fn read<'a, P: PacketToHost<'a>>(&self, rx: &'a mut [u8]) -> Result<P, Self::Error> {
158        let mut tmp = vec![0u8; rx.len() + 1];
159        let read = self.rx.lock().await.read(&mut tmp).await.map_err(Error::Io)?;
160        let mut data = tmp
161            .get(..read)
162            .expect("More bytes were read than their buffer. This probably shouldn't happen.");
163        let kind = PacketKind::read(&mut data).map_err(Error::ReadHci)?;
164        P::read_hci(kind, &mut data, rx).map_err(Error::ReadHci)
165    }
166
167    fn write<T: PacketToController>(&self, val: &T) -> impl Future<Output = Result<(), Self::Error>> {
168        let mut buf = Vec::<u8>::new();
169        WithIndicator::new(val).write_hci(&mut buf).unwrap();
170        async move {
171            let written = self.tx.lock().await.write(&buf).await.map_err(Error::Io)?;
172            assert!(
173                written == buf.len(),
174                "Fewer bytes were written than the whole packet. This probably shouldn't happen."
175            );
176            Ok(())
177        }
178    }
179}
180
181impl embedded_io::ErrorType for Transport {
182    type Error = Error;
183}