1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! Implementation of the Attribute Protocol (ATT).
//!
//! ATT always runs over L2CAP channel `0x0004`, which is connected by default as soon as the
//! Link-Layer connection is established.
//!
//! ATT is used by GATT, the *Generic Attribute Profile*, which introduces the concept of *Services*
//! and *Characteristics* which can all be accessed and discovered over the Attribute Protocol.
//!
//! # Attributes
//!
//! The ATT server hosts a list of *Attributes*, which consist of the following:
//!
//! * A 16-bit *Attribute Handle* ([`AttHandle`]) uniquely identifying the attribute.
//! * A 16- or 128-bit UUID identifying the attribute type. This provides information about how to
//!   interpret the attribute's value (eg. as a little-endian 32-bit integer).
//! * The attribute's *value*, consisting of a dynamically-sized byte array of up to 512 Bytes.
//! * A set of *permissions*, restricting the operations that can be performed on the attribute.
//!
//! ## Attribute Grouping
//!
//! TODO: Figure out how the hell this works and write it down in human-readable form.
//!
//! [`AttHandle`]: struct.AttHandle.html

mod handle;
mod uuid;

use {
    self::handle::*,
    crate::{
        bytes::*,
        l2cap::{L2CAPResponder, Protocol, ProtocolObj},
        utils::HexSlice,
        Error,
    },
};

pub use self::handle::AttHandle;
pub use self::uuid::AttUuid;

enum_with_unknown! {
    /// Specifies an ATT operation to perform.
    ///
    /// The byte values assigned to opcodes are chosen so that the most significant 2 bits indicate
    /// additional information that can be useful in some cases:
    ///
    /// ```notrust
    /// MSb                            LSb
    /// +-----------+---------+----------+
    /// | Signature | Command |  Method  |
    /// |   1 bit   |  1 bit  |  6 bits  |
    /// +-----------+---------+----------+
    /// ```
    ///
    /// * **`Signature`** is set to 1 to indicate that the Attribute Opcode and Parameters are
    ///   followed by an Authentication Signature. This is only allowed for the *Write Command*,
    ///   resulting in the `SignedWriteCommand`.
    /// * **`Command`** is set to 1 when the PDU is a command. This is done purely so that the server
    ///   can ignore unknown commands. Unlike *Requests*, Commands are not followed by a server
    ///   response.
    /// * **`Method`** defines which operation to perform.
    #[derive(Debug, Copy, Clone)]
    enum Opcode(u8) {
        ErrorRsp = 0x01,
        ExchangeMtuReq = 0x02,
        ExchangeMtuRsp = 0x03,
        FindInformationReq = 0x04,
        FindInformationRsp = 0x05,
        FindByTypeReq = 0x06,
        FindByTypeRsp = 0x07,
        ReadByTypeReq = 0x08,
        ReadByTypeRsp = 0x09,
        ReadReq = 0x0A,
        ReadRsp = 0x0B,
        ReadBlobReq = 0x0C,
        ReadBlobRsp = 0x0D,
        ReadMultipleReq = 0x0E,
        ReadMultipleRsp = 0x0F,
        ReadByGroupReq = 0x10,
        ReadByGroupRsp = 0x11,
        WriteReq = 0x12,
        WriteRsp = 0x13,
        WriteCommand = 0x52,
        SignedWriteCommand = 0xD2,
        PrepareWriteReq = 0x16,
        PrepareWriteRsp = 0x17,
        ExecuteWriteReq = 0x18,
        ExecuteWriteRsp = 0x19,
        HandleValueNotification = 0x1B,
        HandleValueIndication = 0x1D,
        HandleValueConfirmation = 0x1E,
    }
}

impl Opcode {
    /// Returns the raw byte corresponding to the opcode `self`.
    fn raw(&self) -> u8 {
        u8::from(*self)
    }

    /// Returns whether the `Signature` bit in this opcode is set.
    ///
    /// If the bit is set, this is an authenticated operation. The opcode parameters are followed by
    /// a 12-Byte signature.
    fn is_authenticated(&self) -> bool {
        self.raw() & 0x80 != 0
    }

    /// Returns whether the `Command` bit in this opcode is set.
    ///
    /// Commands sent to the server are not followed by a server response (ie. it is not indicated
    /// whether they succeed). Unimplemented commands should be ignored, according to the spec.
    fn is_command(&self) -> bool {
        self.raw() & 0x40 != 0
    }
}

/// Structured representation of an ATT message (request or response).
///
/// Note that many responses will need their own type that wraps an iterator.
#[derive(Debug)]
enum AttMsg<'a> {
    /// Request could not be completed due to an error.
    ErrorRsp {
        /// The opcode that caused the error.
        opcode: Opcode,
        /// The attribute handle on which the operation failed.
        handle: AttHandle,
        /// An error code describing the kind of error that occurred.
        error_code: ErrorCode,
    },
    ExchangeMtuReq {
        mtu: u16,
    },
    ExchangeMtuRsp {
        mtu: u16,
    },
    ReadByGroupReq {
        handle_range: RawHandleRange,
        group_type: AttUuid,
    },
    Unknown {
        opcode: Opcode,
        params: HexSlice<&'a [u8]>,
    },
}

/// *Read By Group Type* response PDU holding an iterator.
struct ReadByGroupRsp<
    F: FnMut(&mut FnMut(ByGroupAttData) -> Result<(), Error>) -> Result<(), Error>,
> {
    item_fn: F,
}

impl<'a, F: FnMut(&mut FnMut(ByGroupAttData) -> Result<(), Error>) -> Result<(), Error>>
    ReadByGroupRsp<F>
{
    fn encode(mut self, writer: &mut ByteWriter) -> Result<(), Error> {
        // This is pretty complicated to encode: The length depends on the attributes we fetch from
        // the iterator, and has to be written last, but is located at the start.
        // All the attributes we encode must have the same length. If they don't, we simply stop
        // when reaching the first one with a different size.

        writer.write_u8(Opcode::ReadByGroupRsp.into())?;
        let mut length = writer.split_off(1)?;

        let mut size = None;
        let left = writer.space_left();

        // Encode attribute data until we run out of space or the encoded size differs from the
        // first entry. This might write partial data, but we set the preceding length correctly, so
        // it shouldn't matter.
        (self.item_fn)(&mut |att: ByGroupAttData| {
            trace!("read by group rsp: {:?}", att);
            att.to_bytes(writer)?;

            let used = left - writer.space_left();
            if let Some(expected_size) = size {
                if used != expected_size {
                    return Err(Error::InvalidLength);
                }
            } else {
                size = Some(used);
            }

            Ok(())
        })
        .ok();

        let size = size.expect("empty response");
        assert!(size <= usize::from(u8::max_value()));
        length.write_u8(size as u8).unwrap();
        Ok(())
    }
}

impl AttMsg<'_> {
    fn opcode(&self) -> Opcode {
        match self {
            AttMsg::ErrorRsp { .. } => Opcode::ErrorRsp,
            AttMsg::ExchangeMtuReq { .. } => Opcode::ExchangeMtuReq,
            AttMsg::ExchangeMtuRsp { .. } => Opcode::ExchangeMtuRsp,
            AttMsg::ReadByGroupReq { .. } => Opcode::ReadByGroupReq,
            AttMsg::Unknown { opcode, .. } => *opcode,
        }
    }
}

/// A PDU sent from server to client (over L2CAP).
#[derive(Debug)]
struct OutgoingPdu<'a>(AttMsg<'a>);

impl<'a> From<AttMsg<'a>> for OutgoingPdu<'a> {
    fn from(msg: AttMsg<'a>) -> Self {
        OutgoingPdu(msg)
    }
}

impl<'a> FromBytes<'a> for OutgoingPdu<'a> {
    fn from_bytes(bytes: &mut ByteReader<'a>) -> Result<Self, Error> {
        let opcode = Opcode::from(bytes.read_u8()?);
        let auth = opcode.is_authenticated();

        let msg = match opcode {
            Opcode::ErrorRsp => AttMsg::ErrorRsp {
                opcode: Opcode::from(bytes.read_u8()?),
                handle: AttHandle::from_bytes(bytes)?,
                error_code: ErrorCode::from(bytes.read_u8()?),
            },
            Opcode::ExchangeMtuReq => AttMsg::ExchangeMtuReq {
                mtu: bytes.read_u16_le()?,
            },
            Opcode::ExchangeMtuRsp => AttMsg::ExchangeMtuRsp {
                mtu: bytes.read_u16_le()?,
            },
            Opcode::ReadByGroupReq => AttMsg::ReadByGroupReq {
                handle_range: RawHandleRange::from_bytes(bytes)?,
                group_type: AttUuid::from_bytes(bytes)?,
            },
            _ => AttMsg::Unknown {
                opcode,
                params: HexSlice(bytes.read_slice(bytes.bytes_left() - if auth { 12 } else { 0 })?),
            },
        };

        if auth {
            // Ignore signature
            bytes.skip(12)?;
        }
        Ok(OutgoingPdu(msg))
    }
}

impl ToBytes for OutgoingPdu<'_> {
    fn to_bytes(&self, writer: &mut ByteWriter) -> Result<(), Error> {
        writer.write_u8(self.0.opcode().into())?;
        match self.0 {
            AttMsg::ErrorRsp {
                opcode,
                handle,
                error_code,
            } => {
                writer.write_u8(opcode.into())?;
                writer.write_u16_le(handle.as_u16())?;
                writer.write_u8(error_code.into())?;
            }
            AttMsg::ExchangeMtuReq { mtu } => {
                writer.write_u16_le(mtu)?;
            }
            AttMsg::ExchangeMtuRsp { mtu } => {
                writer.write_u16_le(mtu)?;
            }
            AttMsg::ReadByGroupReq {
                handle_range,
                group_type,
            } => {
                handle_range.to_bytes(writer)?;
                group_type.to_bytes(writer)?;
            }
            AttMsg::Unknown { opcode: _, params } => {
                writer.write_slice(params.0)?;
            }
        }
        if self.0.opcode().is_authenticated() {
            // Write a dummy signature. This should never really be reached since the server never
            // sends authenticated messages.
            writer.write_slice(&[0; 12])?;
        }
        Ok(())
    }
}

/// An ATT PDU transferred from client to server as the L2CAP protocol payload.
///
/// Outgoing PDUs are just `AttMsg`s.
#[derive(Debug)]
struct IncomingPdu<'a> {
    /// The 1-Byte opcode value. It is kept around since it needs to be returned in error responses.
    opcode: Opcode,
    /// Decoded message (request or command) including parameters.
    params: AttMsg<'a>,
    /// `Some` if `opcode.is_authenticated()` is `true`, `None` if not.
    ///
    /// If present, contains 12 Bytes.
    signature: Option<HexSlice<&'a [u8]>>,
}

impl<'a> FromBytes<'a> for IncomingPdu<'a> {
    fn from_bytes(bytes: &mut ByteReader<'a>) -> Result<Self, Error> {
        let opcode = Opcode::from(bytes.read_u8()?);
        let auth = opcode.is_authenticated();

        Ok(Self {
            opcode,
            params: match opcode {
                Opcode::ErrorRsp => AttMsg::ErrorRsp {
                    opcode: Opcode::from(bytes.read_u8()?),
                    handle: AttHandle::from_bytes(bytes)?,
                    error_code: ErrorCode::from(bytes.read_u8()?),
                },
                Opcode::ExchangeMtuReq => AttMsg::ExchangeMtuReq {
                    mtu: bytes.read_u16_le()?,
                },
                Opcode::ExchangeMtuRsp => AttMsg::ExchangeMtuRsp {
                    mtu: bytes.read_u16_le()?,
                },
                Opcode::ReadByGroupReq => AttMsg::ReadByGroupReq {
                    handle_range: RawHandleRange::from_bytes(bytes)?,
                    group_type: AttUuid::from_bytes(bytes)?,
                },
                _ => AttMsg::Unknown {
                    opcode,
                    params: HexSlice(
                        bytes.read_slice(bytes.bytes_left() - if auth { 12 } else { 0 })?,
                    ),
                },
            },
            signature: if auth {
                Some(HexSlice(bytes.read_slice(12)?))
            } else {
                None
            },
        })
    }
}

impl ToBytes for IncomingPdu<'_> {
    fn to_bytes(&self, writer: &mut ByteWriter) -> Result<(), Error> {
        writer.write_u8(self.opcode.into())?;
        match self.params {
            AttMsg::ErrorRsp {
                opcode,
                handle,
                error_code,
            } => {
                writer.write_u8(opcode.into())?;
                writer.write_u16_le(handle.as_u16())?;
                writer.write_u8(error_code.into())?;
            }
            AttMsg::ExchangeMtuReq { mtu } => {
                writer.write_u16_le(mtu)?;
            }
            AttMsg::ExchangeMtuRsp { mtu } => {
                writer.write_u16_le(mtu)?;
            }
            AttMsg::ReadByGroupReq {
                handle_range,
                group_type,
            } => {
                handle_range.to_bytes(writer)?;
                group_type.to_bytes(writer)?;
            }
            AttMsg::Unknown { opcode: _, params } => {
                writer.write_slice(params.0)?;
            }
        }
        if let Some(sig) = self.signature {
            writer.write_slice(sig.0)?;
        }
        Ok(())
    }
}

/// An ATT server attribute
pub struct Attribute<'a> {
    /// The type of the attribute as a UUID16, EG "Primary Service" or "Anaerobic Heart Rate Lower Limit"
    pub att_type: AttUuid,
    /// Unique server-side identifer for attribute
    pub handle: AttHandle,
    /// Attribute values can be any fixed length or variable length octet array, which if too large
    /// can be sent across multiple PDUs
    pub value: HexSlice<&'a [u8]>,
    /// Permissions associated with the attribute
    pub permission: AttPermission,
}

/// Permissions associated with an attribute
pub struct AttPermission {
    _access: AccessPermission,
    _encryption: EncryptionPermission,
    _authentication: AuthenticationPermission,
    _authorization: AuthorizationPermission,
}

pub enum AccessPermission {
    Readable,
    Writeable,
    ReadableWritable,
}

pub enum EncryptionPermission {
    EncryptionRequired,
    EncryptionNotRequired,
}

pub enum AuthenticationPermission {
    AuthenticationRequired,
    AuthenticationNotRequired,
}

pub enum AuthorizationPermission {
    AuthorizationRequired,
    AuthorizationNotRequired,
}

impl Default for AttPermission {
    fn default() -> Self {
        Self {
            _access: AccessPermission::Readable,
            _encryption: EncryptionPermission::EncryptionNotRequired,
            _authentication: AuthenticationPermission::AuthenticationNotRequired,
            _authorization: AuthorizationPermission::AuthorizationNotRequired,
        }
    }
}

/// Trait for attribute sets that can be hosted by an `AttributeServer`.
pub trait AttributeProvider {
    /// Calls a closure `f` with every attribute stored in `self`.
    ///
    /// All attributes will have ascending, consecutive handle values starting at `0x0001`.
    fn for_each_attr(
        &mut self,
        f: &mut dyn FnMut(&mut Attribute) -> Result<(), Error>,
    ) -> Result<(), Error>;

    /// Returns whether the `filter` closure matches any attribute in `self`.
    fn any(&mut self, filter: &mut dyn FnMut(&mut Attribute) -> bool) -> bool {
        match self.for_each_attr(&mut |att| {
            if filter(att) {
                Err(Error::Eof)
            } else {
                Ok(())
            }
        }) {
            Err(Error::Eof) => true,
            _ => false,
        }
    }

    /// Returns whether `uuid` is a valid grouping attribute that can be used in *Read By Group
    /// Type* requests.
    fn is_grouping_attr(&self, uuid: AttUuid) -> bool;

    /// Queries the last attribute that is part of the attribute group denoted by the grouping
    /// attribute at `handle`.
    ///
    /// If `handle` does not refer to a grouping attribute, returns `None`.
    ///
    /// TODO: Human-readable docs that explain what grouping is
    fn group_end(&self, handle: AttHandle) -> Option<&Attribute>;
}

/// An empty attribute set.
///
/// FIXME: Is this even legal according to the spec?
pub struct NoAttributes;

impl AttributeProvider for NoAttributes {
    fn for_each_attr(
        &mut self,
        _: &mut dyn FnMut(&mut Attribute) -> Result<(), Error>,
    ) -> Result<(), Error> {
        Ok(())
    }

    fn is_grouping_attr(&self, _uuid: AttUuid) -> bool {
        false
    }

    fn group_end(&self, _handle: AttHandle) -> Option<&Attribute> {
        None
    }
}

/// An Attribute Protocol server providing read and write access to stored attributes.
pub struct AttributeServer<A: AttributeProvider> {
    attrs: A,
}

impl<A: AttributeProvider> AttributeServer<A> {
    /// Creates an AttributeServer with Attributes
    pub fn new(attrs: A) -> Self {
        Self { attrs }
    }
}

impl<A: AttributeProvider> AttributeServer<A> {
    /// Process an incoming request (or command) PDU and return a response.
    ///
    /// This may return an `AttError`, which the caller will then send as a response. In the success
    /// case, this method will send the response (if any).
    fn process_request<'a>(
        &mut self,
        pdu: IncomingPdu,
        responder: &mut L2CAPResponder,
    ) -> Result<(), AttError> {
        /// Error returned when an ATT error should be sent back.
        ///
        /// Returning this from inside `responder.respond_with` will not send the response and
        /// instead bail out of the closure.
        struct RspError(AttError);

        impl From<Error> for RspError {
            fn from(e: Error) -> Self {
                panic!("unexpected error: {}", e);
            }
        }

        impl From<AttError> for RspError {
            fn from(att: AttError) -> Self {
                RspError(att)
            }
        }

        match pdu.params {
            AttMsg::ReadByGroupReq {
                handle_range,
                group_type,
            } => {
                let range = handle_range.check()?;

                // TODO: Ask GATT whether `group_type` is a grouping attribute, reject if not
                if !self.attrs.is_grouping_attr(group_type) {
                    return Err(AttError {
                        code: ErrorCode::UnsupportedGroupType,
                        handle: range.start(),
                    });
                }

                let mut filter =
                    |att: &mut Attribute| att.att_type == group_type && range.contains(att.handle);

                let result = responder.respond_with(|writer| {
                    // If no attributes match request, return `AttributeNotFound` error, else send
                    // `ReadByGroupResponse` with at least one entry
                    if self.attrs.any(&mut filter) {
                        ReadByGroupRsp {
                            item_fn: |cb: &mut FnMut(ByGroupAttData) -> Result<(), Error>| {
                                // Build the `ByGroupAttData`s for all matching attributes and call
                                // `cb` with them.
                                self.attrs.for_each_attr(&mut |att: &mut Attribute| {
                                    if att.att_type == group_type && range.contains(att.handle) {
                                        cb(ByGroupAttData {
                                            handle: att.handle,
                                            end_group_handle: att.handle, // TODO: Ask GATT where the group ends
                                            value: att.value,
                                        })?;
                                    }

                                    Ok(())
                                })
                            },
                        }
                        .encode(writer)?;
                        Ok(())
                    } else {
                        Err(AttError {
                            code: ErrorCode::AttributeNotFound,
                            handle: AttHandle::NULL,
                        }
                        .into())
                    }
                });

                match result {
                    Ok(()) => Ok(()),
                    Err(RspError(e)) => Err(e),
                }
            }
            AttMsg::ExchangeMtuReq { mtu: _mtu } => {
                responder
                    .respond(OutgoingPdu(AttMsg::ExchangeMtuRsp {
                        mtu: u16::from(Self::RSP_PDU_SIZE),
                    }))
                    .unwrap();
                Ok(())
            }

            AttMsg::Unknown { .. } => {
                if pdu.opcode.is_command() {
                    // According to the spec, unknown Command PDUs should be ignored
                    Ok(())
                } else {
                    // Unknown requests are rejected with a `RequestNotSupported` error
                    Err(AttError {
                        code: ErrorCode::RequestNotSupported,
                        handle: AttHandle::NULL,
                    })
                }
            }

            // Responses are always invalid here
            AttMsg::ErrorRsp { .. } | AttMsg::ExchangeMtuRsp { .. } => Err(AttError {
                code: ErrorCode::InvalidPdu,
                handle: AttHandle::NULL,
            }),
        }
    }
}

impl<A: AttributeProvider> ProtocolObj for AttributeServer<A> {
    fn process_message(
        &mut self,
        message: &[u8],
        mut responder: L2CAPResponder,
    ) -> Result<(), Error> {
        let pdu = IncomingPdu::from_bytes(&mut ByteReader::new(message))?;
        let opcode = pdu.opcode;
        debug!("ATT msg received: {:?}", pdu);

        match self.process_request(pdu, &mut responder) {
            Ok(()) => Ok(()),
            Err(att_error) => {
                debug!("ATT error: {:?}", att_error);

                responder.respond(OutgoingPdu(AttMsg::ErrorRsp {
                    opcode: opcode,
                    handle: att_error.handle,
                    error_code: att_error.code,
                }))
            }
        }
    }
}

impl<A: AttributeProvider> Protocol for AttributeServer<A> {
    // FIXME: Would it be useful to have this as a runtime parameter instead?
    const RSP_PDU_SIZE: u8 = 23;
}

enum_with_unknown! {
    /// Error codes that can be sent from the ATT server to the client in response to a request.
    ///
    /// Used as the payload of `ErrorRsp` PDUs.
    #[derive(Copy, Clone, Debug)]
    pub enum ErrorCode(u8) {
        /// Attempted to use an `AttHandle` that isn't valid on this server.
        InvalidHandle = 0x01,
        /// Attribute isn't readable.
        ReadNotPermitted = 0x02,
        /// Attribute isn't writable.
        WriteNotPermitted = 0x03,
        /// Attribute PDU is invalid.
        InvalidPdu = 0x04,
        /// Authentication needed before attribute can be read/written.
        InsufficientAuthentication = 0x05,
        /// Server doesn't support this operation.
        RequestNotSupported = 0x06,
        /// Offset was past the end of the attribute.
        InvalidOffset = 0x07,
        /// Authorization needed before attribute can be read/written.
        InsufficientAuthorization = 0x08,
        /// Too many "prepare write" requests have been queued.
        PrepareQueueFull = 0x09,
        /// No attribute found within the specified attribute handle range.
        AttributeNotFound = 0x0A,
        /// Attribute can't be read/written using *Read Key Blob* request.
        AttributeNotLong = 0x0B,
        /// The encryption key in use is too weak to access an attribute.
        InsufficientEncryptionKeySize = 0x0C,
        /// Attribute value has an incorrect length for the operation.
        InvalidAttributeValueLength = 0x0D,
        /// Request has encountered an "unlikely" error and could not be completed.
        UnlikelyError = 0x0E,
        /// Attribute cannot be read/written without an encrypted connection.
        InsufficientEncryption = 0x0F,
        /// Attribute type is an invalid grouping attribute according to a higher-layer spec.
        UnsupportedGroupType = 0x10,
        /// Server didn't have enough resources to complete a request.
        InsufficientResources = 0x11,
    }
}

/// An error on the ATT protocol layer. Can be sent as a response.
#[derive(Debug)]
pub struct AttError {
    code: ErrorCode,
    handle: AttHandle,
}

/// Attribute Data returned in *Read By Type* response.
#[derive(Debug)]
pub struct ByTypeAttData<'a> {
    handle: AttHandle,
    value: HexSlice<&'a [u8]>,
}

impl<'a> FromBytes<'a> for ByTypeAttData<'a> {
    fn from_bytes(bytes: &mut ByteReader<'a>) -> Result<Self, Error> {
        Ok(ByTypeAttData {
            handle: AttHandle::from_bytes(bytes)?,
            value: HexSlice(bytes.read_rest()),
        })
    }
}

impl<'a> ToBytes for ByTypeAttData<'a> {
    fn to_bytes(&self, writer: &mut ByteWriter) -> Result<(), Error> {
        writer.write_u16_le(self.handle.as_u16())?;
        writer.write_slice(self.value.0)?;
        Ok(())
    }
}

/// Attribute Data returned in *Read By Group Type* response.
#[derive(Debug, Copy, Clone)]
pub struct ByGroupAttData<'a> {
    /// The handle of this attribute.
    handle: AttHandle,
    end_group_handle: AttHandle,
    value: HexSlice<&'a [u8]>,
}

impl<'a> FromBytes<'a> for ByGroupAttData<'a> {
    fn from_bytes(bytes: &mut ByteReader<'a>) -> Result<Self, Error> {
        Ok(ByGroupAttData {
            handle: AttHandle::from_bytes(bytes)?,
            end_group_handle: AttHandle::from_bytes(bytes)?,
            value: HexSlice(bytes.read_rest()),
        })
    }
}

/// The `ToBytes` impl will truncate the value if it doesn't fit.
impl<'a> ToBytes for ByGroupAttData<'a> {
    fn to_bytes(&self, writer: &mut ByteWriter) -> Result<(), Error> {
        writer.write_u16_le(self.handle.as_u16())?;
        writer.write_u16_le(self.end_group_handle.as_u16())?;
        if writer.space_left() >= self.value.0.len() {
            writer.write_slice(self.value.0)?;
        } else {
            writer
                .write_slice(&self.value.0[..writer.space_left()])
                .unwrap();
        }
        Ok(())
    }
}