1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #pragma once
16 #include <lib/fit/result.h>
17 
18 #include "pw_bluetooth_sapphire/internal/host/common/byte_buffer.h"
19 #include "pw_bluetooth_sapphire/internal/host/common/packet_view.h"
20 #include "pw_bluetooth_sapphire/internal/host/sm/smp.h"
21 
22 namespace bt::sm {
23 
24 // Utilities for processing SMP packets.
25 // TODO(fxbug.dev/42125894): Merge PacketReader & ValidPacketReader types into
26 // one type for validating & accessing SM packets once PacketReader is no longer
27 // used.
28 class PacketReader : public PacketView<Header> {
29  public:
30   explicit PacketReader(const ByteBuffer* buffer);
code()31   inline Code code() const { return header().code; }
32 };
33 
34 // A type which has been verified to satisfy all the preconditions of a valid
35 // SMP packet. Namely, 1.) The packet's length is at least that of an SMP
36 // header. 2.) The packet's header code is a valid SMP code that our stack
37 // supports. 3.) The length of the packet's payload matches the payload
38 // associated with its header code.
39 class ValidPacketReader : public PacketReader {
40  public:
41   // Convert a ByteBufferPtr to a ValidPacketReader if possible to allow
42   // unchecked access to its payload, or an error explaining why we could not.
43   static fit::result<ErrorCode, ValidPacketReader> ParseSdu(
44       const ByteBufferPtr& sdu);
45 
46  private:
47   // Private constructor because a valid PacketReader must be parsed from a
48   // ByteBufferPtr
49   explicit ValidPacketReader(const ByteBuffer* buffer);
50 };
51 
52 class PacketWriter : public MutablePacketView<Header> {
53  public:
54   // Constructor writes |code| into |buffer|.
55   PacketWriter(Code code, MutableByteBuffer* buffer);
56 };
57 
58 }  // namespace bt::sm
59