1 /*
2  * Copyright 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <cstdint>
20 #include <fstream>
21 #include <memory>
22 #include <ostream>
23 
24 #include "hci/pcap_filter.h"
25 #include "model/hci/h4.h"
26 #include "model/hci/hci_transport.h"
27 
28 namespace rootcanal {
29 
30 enum class PacketDirection : uint8_t {
31   HOST_TO_CONTROLLER = 0,
32   CONTROLLER_TO_HOST = 1,
33 };
34 
35 // A Hci Transport that logs all the in and out going
36 // packets to a stream.
37 class HciSniffer : public HciTransport {
38  public:
39   HciSniffer(std::shared_ptr<HciTransport> transport,
40              std::shared_ptr<std::ostream> outputStream = nullptr,
41              std::shared_ptr<PcapFilter> filter = nullptr);
42   ~HciSniffer() = default;
43 
44   static std::shared_ptr<HciTransport> Create(
45       std::shared_ptr<HciTransport> transport,
46       std::shared_ptr<std::ostream> outputStream = nullptr,
47       std::shared_ptr<PcapFilter> /*filter*/ = nullptr) {
48     return std::make_shared<HciSniffer>(transport, outputStream);
49   }
50 
51   // Sets and initializes the output stream
52   void SetOutputStream(std::shared_ptr<std::ostream> outputStream);
53   void SetPcapFilter(std::shared_ptr<PcapFilter> filter);
54 
55   void Send(PacketType packet_type,
56             const std::vector<uint8_t>& packet) override;
57 
58   void RegisterCallbacks(PacketCallback packet_callback,
59                          CloseCallback close_callback) override;
60 
61   void Tick() override;
62   void Close() override;
63 
64  private:
65   void AppendRecord(PacketDirection direction, PacketType type,
66                     const std::vector<uint8_t>& packet);
67 
68   std::shared_ptr<std::ostream> output_;
69   std::shared_ptr<HciTransport> transport_;
70   std::shared_ptr<rootcanal::PcapFilter> filter_;
71 };
72 
73 }  // namespace rootcanal
74