1use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
9use std::sync::{Arc, Mutex};
10use std::time::Duration;
11
12use tokio::sync::{mpsc, oneshot};
13
14use crate::connection::{ConnEvent, ConnState};
15use crate::error::{Error, Result};
16use crate::host::Host;
17use crate::l2cap::cid;
18
19pub mod op {
21 pub const ERROR_RSP: u8 = 0x01;
23 pub const MTU_REQ: u8 = 0x02;
25 pub const MTU_RSP: u8 = 0x03;
27 pub const FIND_INFO_REQ: u8 = 0x04;
29 pub const FIND_INFO_RSP: u8 = 0x05;
31 pub const FIND_BY_TYPE_REQ: u8 = 0x06;
33 pub const FIND_BY_TYPE_RSP: u8 = 0x07;
35 pub const READ_BY_TYPE_REQ: u8 = 0x08;
37 pub const READ_BY_TYPE_RSP: u8 = 0x09;
39 pub const READ_REQ: u8 = 0x0a;
41 pub const READ_RSP: u8 = 0x0b;
43 pub const READ_BLOB_REQ: u8 = 0x0c;
45 pub const READ_BLOB_RSP: u8 = 0x0d;
47 pub const READ_MULTIPLE_REQ: u8 = 0x0e;
49 pub const READ_MULTIPLE_RSP: u8 = 0x0f;
51 pub const READ_BY_GROUP_REQ: u8 = 0x10;
53 pub const READ_BY_GROUP_RSP: u8 = 0x11;
55 pub const WRITE_REQ: u8 = 0x12;
57 pub const WRITE_RSP: u8 = 0x13;
59 pub const WRITE_CMD: u8 = 0x52;
61 pub const SIGNED_WRITE_CMD: u8 = 0xd2;
63 pub const PREPARE_WRITE_REQ: u8 = 0x16;
65 pub const PREPARE_WRITE_RSP: u8 = 0x17;
67 pub const EXECUTE_WRITE_REQ: u8 = 0x18;
69 pub const EXECUTE_WRITE_RSP: u8 = 0x19;
71 pub const NOTIFY: u8 = 0x1b;
73 pub const INDICATE: u8 = 0x1d;
75 pub const CONFIRM: u8 = 0x1e;
77 pub const READ_MULTIPLE_VAR_REQ: u8 = 0x20;
79 pub const READ_MULTIPLE_VAR_RSP: u8 = 0x21;
81 pub const MULTIPLE_NOTIFY: u8 = 0x23;
83}
84
85pub mod ecode {
87 pub const INVALID_HANDLE: u8 = 0x01;
89 pub const READ_NOT_PERMITTED: u8 = 0x02;
91 pub const WRITE_NOT_PERMITTED: u8 = 0x03;
93 pub const INVALID_PDU: u8 = 0x04;
95 pub const INSUFFICIENT_AUTHENTICATION: u8 = 0x05;
97 pub const REQUEST_NOT_SUPPORTED: u8 = 0x06;
99 pub const INVALID_OFFSET: u8 = 0x07;
101 pub const INSUFFICIENT_AUTHORIZATION: u8 = 0x08;
103 pub const PREPARE_QUEUE_FULL: u8 = 0x09;
105 pub const ATTRIBUTE_NOT_FOUND: u8 = 0x0a;
107 pub const ATTRIBUTE_NOT_LONG: u8 = 0x0b;
109 pub const KEY_SIZE_TOO_SHORT: u8 = 0x0c;
111 pub const INVALID_LENGTH: u8 = 0x0d;
113 pub const UNLIKELY: u8 = 0x0e;
115 pub const INSUFFICIENT_ENCRYPTION: u8 = 0x0f;
117 pub const UNSUPPORTED_GROUP_TYPE: u8 = 0x10;
119 pub const INSUFFICIENT_RESOURCES: u8 = 0x11;
121 pub const VALUE_NOT_ALLOWED: u8 = 0x13;
123 pub const CCCD_IMPROPER: u8 = 0xfd;
125}
126
127pub fn error_name(code: u8) -> &'static str {
129 match code {
130 0x01 => "Invalid Handle",
131 0x02 => "Read Not Permitted",
132 0x03 => "Write Not Permitted",
133 0x04 => "Invalid PDU",
134 0x05 => "Insufficient Authentication",
135 0x06 => "Request Not Supported",
136 0x07 => "Invalid Offset",
137 0x08 => "Insufficient Authorization",
138 0x09 => "Prepare Queue Full",
139 0x0a => "Attribute Not Found",
140 0x0b => "Attribute Not Long",
141 0x0c => "Encryption Key Size Too Short",
142 0x0d => "Invalid Attribute Value Length",
143 0x0e => "Unlikely Error",
144 0x0f => "Insufficient Encryption",
145 0x10 => "Unsupported Group Type",
146 0x11 => "Insufficient Resources",
147 0x12 => "Database Out Of Sync",
148 0x13 => "Value Not Allowed",
149 0x80..=0x9f => "Application Error",
150 0xfc => "Write Request Rejected",
151 0xfd => "Client Characteristic Configuration Descriptor Improperly Configured",
152 0xfe => "Procedure Already in Progress",
153 0xff => "Out of Range",
154 _ => "Reserved",
155 }
156}
157
158pub const DEFAULT_MTU: u16 = 23;
160pub const MAX_MTU: u16 = 517;
162
163const TRANSACTION_TIMEOUT: Duration = Duration::from_secs(30);
165
166struct Pending {
167 request: u8,
168 tx: oneshot::Sender<Result<Vec<u8>>>,
169}
170
171pub(crate) struct Bearer {
173 mtu: AtomicU16,
174 mtu_exchanged: AtomicBool,
175 client: tokio::sync::Mutex<()>,
176 pending: Mutex<Option<Pending>>,
177 indications: tokio::sync::Mutex<()>,
178 confirm: Mutex<Option<oneshot::Sender<()>>>,
179}
180
181impl Default for Bearer {
182 fn default() -> Self {
183 Bearer {
184 mtu: AtomicU16::new(DEFAULT_MTU),
185 mtu_exchanged: AtomicBool::new(false),
186 client: tokio::sync::Mutex::new(()),
187 pending: Mutex::new(None),
188 indications: tokio::sync::Mutex::new(()),
189 confirm: Mutex::new(None),
190 }
191 }
192}
193
194impl Bearer {
195 pub(crate) fn mtu(&self) -> u16 {
197 self.mtu.load(Ordering::Relaxed)
198 }
199
200 fn set_mtu(&self, m: u16) {
201 self.mtu
202 .store(m.clamp(DEFAULT_MTU, MAX_MTU), Ordering::Relaxed);
203 }
204
205 pub(crate) fn close(&self) {
206 if let Some(p) = self
207 .pending
208 .lock()
209 .unwrap_or_else(|e| e.into_inner())
210 .take()
211 {
212 let _ = p.tx.send(Err(Error::Disconnected));
213 }
214 self.confirm
215 .lock()
216 .unwrap_or_else(|e| e.into_inner())
217 .take();
218 }
219
220 pub(crate) async fn request(
222 &self,
223 host: &Host,
224 conn: &ConnState,
225 pdu: Vec<u8>,
226 ) -> Result<Vec<u8>> {
227 let _one = self.client.lock().await;
228 let (tx, rx) = oneshot::channel();
229 *self.pending.lock().unwrap_or_else(|e| e.into_inner()) = Some(Pending {
230 request: pdu[0],
231 tx,
232 });
233 conn.send(host, cid::ATT, &pdu).await?;
234 match tokio::time::timeout(TRANSACTION_TIMEOUT, rx).await {
235 Ok(Ok(r)) => r,
236 Ok(Err(_)) => Err(Error::Disconnected),
237 Err(_) => {
238 self.pending
240 .lock()
241 .unwrap_or_else(|e| e.into_inner())
242 .take();
243 Err(Error::Timeout("an ATT response"))
244 }
245 }
246 }
247
248 pub(crate) async fn command(&self, host: &Host, conn: &ConnState, pdu: &[u8]) -> Result<()> {
250 conn.send(host, cid::ATT, pdu).await
251 }
252
253 pub(crate) async fn indicate(
255 &self,
256 host: &Host,
257 conn: &ConnState,
258 handle: u16,
259 value: &[u8],
260 ) -> Result<()> {
261 let _one = self.indications.lock().await;
262 let (tx, rx) = oneshot::channel();
263 *self.confirm.lock().unwrap_or_else(|e| e.into_inner()) = Some(tx);
264 let mut pdu = vec![op::INDICATE];
265 pdu.extend_from_slice(&handle.to_le_bytes());
266 pdu.extend_from_slice(&value[..value.len().min(usize::from(self.mtu()) - 3)]);
267 conn.send(host, cid::ATT, &pdu).await?;
268 match tokio::time::timeout(TRANSACTION_TIMEOUT, rx).await {
269 Ok(Ok(())) => Ok(()),
270 Ok(Err(_)) => Err(Error::Disconnected),
271 Err(_) => Err(Error::Timeout("an indication's confirmation")),
272 }
273 }
274
275 pub(crate) async fn notify(
277 &self,
278 host: &Host,
279 conn: &ConnState,
280 handle: u16,
281 value: &[u8],
282 ) -> Result<()> {
283 let mut pdu = vec![op::NOTIFY];
284 pdu.extend_from_slice(&handle.to_le_bytes());
285 pdu.extend_from_slice(&value[..value.len().min(usize::from(self.mtu()) - 3)]);
286 conn.send(host, cid::ATT, &pdu).await
287 }
288
289 pub(crate) async fn exchange_mtu(
291 &self,
292 host: &Host,
293 conn: &ConnState,
294 ours: u16,
295 ) -> Result<u16> {
296 let ours = ours.clamp(DEFAULT_MTU, MAX_MTU);
297 let mut pdu = vec![op::MTU_REQ];
298 pdu.extend_from_slice(&ours.to_le_bytes());
299 let rsp = self.request(host, conn, pdu).await?;
300 let theirs = match rsp.as_slice() {
301 [op::MTU_RSP, a, b] => u16::from_le_bytes([*a, *b]),
302 _ => return Err(Error::Protocol("malformed Exchange MTU Response".into())),
303 };
304 let m = ours.min(theirs).max(DEFAULT_MTU);
305 self.set_mtu(m);
306 self.mtu_exchanged.store(true, Ordering::Relaxed);
307 let _ = conn.events.send(ConnEvent::MtuExchanged(m));
308 Ok(m)
309 }
310}
311
312fn response_to(opcode: u8) -> Option<u8> {
314 match opcode {
315 op::MTU_RSP
316 | op::FIND_INFO_RSP
317 | op::FIND_BY_TYPE_RSP
318 | op::READ_BY_TYPE_RSP
319 | op::READ_RSP
320 | op::READ_BLOB_RSP
321 | op::READ_MULTIPLE_RSP
322 | op::READ_BY_GROUP_RSP
323 | op::WRITE_RSP
324 | op::PREPARE_WRITE_RSP
325 | op::EXECUTE_WRITE_RSP
326 | op::READ_MULTIPLE_VAR_RSP => Some(opcode - 1),
327 _ => None,
328 }
329}
330
331pub(crate) async fn run(host: Host, conn: Arc<ConnState>, mut rx: mpsc::Receiver<Vec<u8>>) {
333 loop {
334 let pdu = tokio::select! {
335 p = rx.recv() => match p { Some(p) => p, None => return },
336 _ = conn.wait_closed() => return,
337 };
338 if let Err(e) = on_pdu(&host, &conn, pdu).await {
339 tracing::debug!("ATT on {:#05x}: {e}", conn.handle);
340 }
341 }
342}
343
344async fn on_pdu(host: &Host, conn: &Arc<ConnState>, pdu: Vec<u8>) -> Result<()> {
345 let Some(&opcode) = pdu.first() else {
346 return Ok(());
347 };
348 let bearer = &conn.att;
349 if opcode == op::ERROR_RSP {
350 if pdu.len() == 5 {
351 let (request, handle, code) = (pdu[1], u16::from_le_bytes([pdu[2], pdu[3]]), pdu[4]);
352 let mut p = bearer.pending.lock().unwrap_or_else(|e| e.into_inner());
353 if p.as_ref().is_some_and(|p| p.request == request) {
354 if let Some(p) = p.take() {
355 let _ = p.tx.send(Err(Error::Att {
356 request,
357 handle,
358 code,
359 }));
360 }
361 }
362 }
363 return Ok(());
364 }
365 if let Some(request) = response_to(opcode) {
366 let mut p = bearer.pending.lock().unwrap_or_else(|e| e.into_inner());
367 if p.as_ref().is_some_and(|p| p.request == request) {
368 if let Some(p) = p.take() {
369 let _ = p.tx.send(Ok(pdu));
370 }
371 } else {
372 tracing::debug!("unexpected ATT response {opcode:#04x}");
373 }
374 return Ok(());
375 }
376 match opcode {
377 op::NOTIFY | op::INDICATE if pdu.len() >= 3 => {
378 let handle = u16::from_le_bytes([pdu[1], pdu[2]]);
379 let indication = opcode == op::INDICATE;
380 let _ = conn.events.send(ConnEvent::Notification {
381 handle,
382 value: pdu[3..].to_vec(),
383 indication,
384 });
385 if indication {
386 bearer.command(host, conn, &[op::CONFIRM]).await?;
387 }
388 }
389 op::MULTIPLE_NOTIFY => {
390 let mut rest = &pdu[1..];
391 while rest.len() >= 4 {
392 let handle = u16::from_le_bytes([rest[0], rest[1]]);
393 let len = usize::from(u16::from_le_bytes([rest[2], rest[3]]));
394 let Some(value) = rest.get(4..4 + len) else {
395 break;
396 };
397 let _ = conn.events.send(ConnEvent::Notification {
398 handle,
399 value: value.to_vec(),
400 indication: false,
401 });
402 rest = &rest[4 + len..];
403 }
404 }
405 op::CONFIRM => {
406 if let Some(tx) = bearer
407 .confirm
408 .lock()
409 .unwrap_or_else(|e| e.into_inner())
410 .take()
411 {
412 let _ = tx.send(());
413 }
414 }
415 op::MTU_REQ => {
416 let theirs = match pdu.as_slice() {
417 [_, a, b] => u16::from_le_bytes([*a, *b]),
418 _ => return send_error(host, conn, opcode, 0, ecode::INVALID_PDU).await,
419 };
420 let mut rsp = vec![op::MTU_RSP];
421 rsp.extend_from_slice(&MAX_MTU.to_le_bytes());
422 bearer.command(host, conn, &rsp).await?;
423 bearer.set_mtu(theirs.min(MAX_MTU));
425 bearer.mtu_exchanged.store(true, Ordering::Relaxed);
426 let _ = conn.events.send(ConnEvent::MtuExchanged(bearer.mtu()));
427 }
428 _ => {
429 let rsp = host.inner.gatt.handle(host, conn, &pdu).await;
430 if let Some(rsp) = rsp {
431 bearer.command(host, conn, &rsp).await?;
432 }
433 }
434 }
435 Ok(())
436}
437
438pub(crate) async fn send_error(
439 host: &Host,
440 conn: &ConnState,
441 request: u8,
442 handle: u16,
443 code: u8,
444) -> Result<()> {
445 conn.att
446 .command(host, conn, &error_pdu(request, handle, code))
447 .await
448}
449
450pub(crate) fn error_pdu(request: u8, handle: u16, code: u8) -> Vec<u8> {
452 let h = handle.to_le_bytes();
453 vec![op::ERROR_RSP, request, h[0], h[1], code]
454}