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(std::shared_ptr<HciTransport> transport,
45                                               std::shared_ptr<std::ostream> outputStream = nullptr,
46                                               std::shared_ptr<PcapFilter> /*filter*/ = nullptr) {
47     return std::make_shared<HciSniffer>(transport, outputStream);
48   }
49 
50   // Sets and initializes the output stream
51   void SetOutputStream(std::shared_ptr<std::ostream> outputStream);
52   void SetPcapFilter(std::shared_ptr<PcapFilter> filter);
53 
54   void Send(PacketType packet_type, const std::vector<uint8_t>& packet) override;
55 
56   void RegisterCallbacks(PacketCallback packet_callback, CloseCallback close_callback) override;
57 
58   void Tick() override;
59   void Close() override;
60 
61 private:
62   void AppendRecord(PacketDirection direction, PacketType type, const std::vector<uint8_t>& packet);
63 
64   std::shared_ptr<std::ostream> output_;
65   std::shared_ptr<HciTransport> transport_;
66   std::shared_ptr<rootcanal::PcapFilter> filter_;
67 };
68 
69 }  // namespace rootcanal
70