1 /*
2  * Copyright 2019 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 #include <bluetooth/log.h>
18 #include <netdb.h>
19 #include <netinet/in.h>
20 #include <poll.h>
21 #include <sys/socket.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 
25 #include <chrono>
26 #include <csignal>
27 #include <mutex>
28 #include <queue>
29 
30 #include "hal/hci_hal.h"
31 #include "hal/hci_hal_host.h"
32 #include "hal/snoop_logger.h"
33 #include "metrics/counter_metrics.h"
34 #include "os/log.h"
35 #include "os/reactor.h"
36 #include "os/thread.h"
37 
38 namespace {
39 constexpr int INVALID_FD = -1;
40 
41 constexpr uint8_t kH4Command = 0x01;
42 constexpr uint8_t kH4Acl = 0x02;
43 constexpr uint8_t kH4Sco = 0x03;
44 constexpr uint8_t kH4Event = 0x04;
45 constexpr uint8_t kH4Iso = 0x05;
46 
47 constexpr uint8_t kH4HeaderSize = 1;
48 constexpr uint8_t kHciAclHeaderSize = 4;
49 constexpr uint8_t kHciScoHeaderSize = 3;
50 constexpr uint8_t kHciEvtHeaderSize = 2;
51 constexpr uint8_t kHciIsoHeaderSize = 4;
52 constexpr int kBufSize = 1024 + 4 + 1;  // DeviceProperties::acl_data_packet_size_ + ACL header + H4 header
53 
ConnectToSocket()54 int ConnectToSocket() {
55   auto* config = bluetooth::hal::HciHalHostRootcanalConfig::Get();
56   const std::string& server = config->GetServerAddress();
57   int port = config->GetPort();
58 
59   int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
60   if (socket_fd < 1) {
61     bluetooth::log::error("can't create socket: {}", strerror(errno));
62     return INVALID_FD;
63   }
64 
65   struct hostent* host;
66   host = gethostbyname(server.c_str());
67   if (host == nullptr) {
68     bluetooth::log::error("can't get server name");
69     return INVALID_FD;
70   }
71 
72   struct sockaddr_in serv_addr;
73   memset((void*)&serv_addr, 0, sizeof(serv_addr));
74   serv_addr.sin_family = AF_INET;
75   serv_addr.sin_addr.s_addr = INADDR_ANY;
76   serv_addr.sin_port = htons(port);
77 
78   int result = connect(socket_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
79   if (result < 0) {
80     bluetooth::log::error("can't connect: {}", strerror(errno));
81     return INVALID_FD;
82   }
83 
84   timeval socket_timeout{
85       .tv_sec = 3,
86       .tv_usec = 0,
87   };
88   int ret = setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO, &socket_timeout, sizeof(socket_timeout));
89   if (ret == -1) {
90     bluetooth::log::error("can't control socket fd: {}", strerror(errno));
91     return INVALID_FD;
92   }
93   return socket_fd;
94 }
95 }  // namespace
96 
97 namespace bluetooth {
98 namespace hal {
99 
100 class HciHalHost : public HciHal {
101  public:
registerIncomingPacketCallback(HciHalCallbacks * callback)102   void registerIncomingPacketCallback(HciHalCallbacks* callback) override {
103     std::lock_guard<std::mutex> lock(api_mutex_);
104     log::info("before");
105     {
106       std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
107       log::assert_that(
108           incoming_packet_callback_ == nullptr && callback != nullptr,
109           "assert failed: incoming_packet_callback_ == nullptr && callback != nullptr");
110       incoming_packet_callback_ = callback;
111     }
112     log::info("after");
113   }
114 
unregisterIncomingPacketCallback()115   void unregisterIncomingPacketCallback() override {
116     std::lock_guard<std::mutex> lock(api_mutex_);
117     log::info("before");
118     {
119       std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
120       incoming_packet_callback_ = nullptr;
121     }
122     log::info("after");
123   }
124 
sendHciCommand(HciPacket command)125   void sendHciCommand(HciPacket command) override {
126     std::lock_guard<std::mutex> lock(api_mutex_);
127     log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD");
128     std::vector<uint8_t> packet = std::move(command);
129     btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::CMD);
130     packet.insert(packet.cbegin(), kH4Command);
131     write_to_fd(packet);
132   }
133 
sendAclData(HciPacket data)134   void sendAclData(HciPacket data) override {
135     std::lock_guard<std::mutex> lock(api_mutex_);
136     log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD");
137     std::vector<uint8_t> packet = std::move(data);
138     btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ACL);
139     packet.insert(packet.cbegin(), kH4Acl);
140     write_to_fd(packet);
141   }
142 
sendScoData(HciPacket data)143   void sendScoData(HciPacket data) override {
144     std::lock_guard<std::mutex> lock(api_mutex_);
145     log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD");
146     std::vector<uint8_t> packet = std::move(data);
147     btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::SCO);
148     packet.insert(packet.cbegin(), kH4Sco);
149     write_to_fd(packet);
150   }
151 
sendIsoData(HciPacket data)152   void sendIsoData(HciPacket data) override {
153     std::lock_guard<std::mutex> lock(api_mutex_);
154     log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD");
155     std::vector<uint8_t> packet = std::move(data);
156     btsnoop_logger_->Capture(packet, SnoopLogger::Direction::OUTGOING, SnoopLogger::PacketType::ISO);
157     packet.insert(packet.cbegin(), kH4Iso);
158     write_to_fd(packet);
159   }
160 
161  protected:
ListDependencies(ModuleList * list) const162   void ListDependencies(ModuleList* list) const {
163     list->add<metrics::CounterMetrics>();
164     list->add<SnoopLogger>();
165   }
166 
Start()167   void Start() override {
168     std::lock_guard<std::mutex> lock(api_mutex_);
169     log::assert_that(sock_fd_ == INVALID_FD, "assert failed: sock_fd_ == INVALID_FD");
170     sock_fd_ = ConnectToSocket();
171     log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD");
172     reactable_ = hci_incoming_thread_.GetReactor()->Register(
173         sock_fd_,
174         common::Bind(&HciHalHost::incoming_packet_received, common::Unretained(this)),
175         common::Bind(&HciHalHost::send_packet_ready, common::Unretained(this)));
176     hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, os::Reactor::REACT_ON_READ_ONLY);
177     btsnoop_logger_ = GetDependency<SnoopLogger>();
178     log::info("HAL opened successfully");
179   }
180 
Stop()181   void Stop() override {
182     std::lock_guard<std::mutex> lock(api_mutex_);
183     log::info("HAL is closing");
184     if (reactable_ != nullptr) {
185       hci_incoming_thread_.GetReactor()->Unregister(reactable_);
186       log::info("HAL is stopping, start waiting for last callback");
187       // Wait up to 1 second for the last incoming packet callback to finish
188       hci_incoming_thread_.GetReactor()->WaitForUnregisteredReactable(std::chrono::milliseconds(1000));
189       log::info("HAL is stopping, finished waiting for last callback");
190       log::assert_that(sock_fd_ != INVALID_FD, "assert failed: sock_fd_ != INVALID_FD");
191     }
192     reactable_ = nullptr;
193     {
194       std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
195       incoming_packet_callback_ = nullptr;
196     }
197     ::close(sock_fd_);
198     sock_fd_ = INVALID_FD;
199     log::info("HAL is closed");
200   }
201 
ToString() const202   std::string ToString() const override {
203     return std::string("HciHalHost");
204   }
205 
206  private:
207   // Held when APIs are called, NOT to be held during callbacks
208   std::mutex api_mutex_;
209   HciHalCallbacks* incoming_packet_callback_ = nullptr;
210   std::mutex incoming_packet_callback_mutex_;
211   int sock_fd_ = INVALID_FD;
212   bluetooth::os::Thread hci_incoming_thread_ =
213       bluetooth::os::Thread("hci_incoming_thread", bluetooth::os::Thread::Priority::NORMAL);
214   bluetooth::os::Reactor::Reactable* reactable_ = nullptr;
215   std::queue<std::vector<uint8_t>> hci_outgoing_queue_;
216   SnoopLogger* btsnoop_logger_ = nullptr;
217 
write_to_fd(HciPacket packet)218   void write_to_fd(HciPacket packet) {
219     // TODO: replace this with new queue when it's ready
220     hci_outgoing_queue_.emplace(packet);
221     if (hci_outgoing_queue_.size() == 1) {
222       hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, os::Reactor::REACT_ON_READ_WRITE);
223     }
224   }
225 
send_packet_ready()226   void send_packet_ready() {
227     std::lock_guard<std::mutex> lock(api_mutex_);
228     if (hci_outgoing_queue_.empty()) return;
229     auto packet_to_send = hci_outgoing_queue_.front();
230     auto bytes_written = write(sock_fd_, (void*)packet_to_send.data(), packet_to_send.size());
231     hci_outgoing_queue_.pop();
232     if (bytes_written == -1) {
233       abort();
234     }
235     if (hci_outgoing_queue_.empty()) {
236       hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_, os::Reactor::REACT_ON_READ_ONLY);
237     }
238   }
239 
socketRecvAll(void * buffer,int bufferLen)240   bool socketRecvAll(void* buffer, int bufferLen) {
241     auto buf = static_cast<char*>(buffer);
242     while (bufferLen > 0) {
243       ssize_t ret;
244       RUN_NO_INTR(ret = recv(sock_fd_, buf, bufferLen, 0));
245       if (ret <= 0) {
246         return false;
247       }
248       buf += ret;
249       bufferLen -= ret;
250     }
251     return true;
252   }
253 
incoming_packet_received()254   void incoming_packet_received() {
255     {
256       std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
257       if (incoming_packet_callback_ == nullptr) {
258         log::info("Dropping a packet");
259         return;
260       }
261     }
262     uint8_t buf[kBufSize] = {};
263 
264     ssize_t received_size;
265     RUN_NO_INTR(received_size = recv(sock_fd_, buf, kH4HeaderSize, 0));
266     log::assert_that(received_size != -1, "Can't receive from socket: {}", strerror(errno));
267     if (received_size == 0) {
268       log::warn("Can't read H4 header. EOF received");
269       raise(SIGINT);
270       return;
271     }
272 
273     if (buf[0] == kH4Event) {
274       log::assert_that(
275           socketRecvAll(buf + kH4HeaderSize, kHciEvtHeaderSize),
276           "Can't receive from socket: {}",
277           strerror(errno));
278 
279       uint8_t hci_evt_parameter_total_length = buf[2];
280       log::assert_that(
281           socketRecvAll(buf + kH4HeaderSize + kHciEvtHeaderSize, hci_evt_parameter_total_length),
282           "Can't receive from socket: {}",
283           strerror(errno));
284 
285       HciPacket receivedHciPacket;
286       receivedHciPacket.assign(
287           buf + kH4HeaderSize, buf + kH4HeaderSize + kHciEvtHeaderSize + hci_evt_parameter_total_length);
288       btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::EVT);
289       {
290         std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
291         if (incoming_packet_callback_ == nullptr) {
292           log::info("Dropping an event after processing");
293           return;
294         }
295         incoming_packet_callback_->hciEventReceived(receivedHciPacket);
296       }
297     }
298 
299     if (buf[0] == kH4Acl) {
300       log::assert_that(
301           socketRecvAll(buf + kH4HeaderSize, kHciAclHeaderSize),
302           "Can't receive from socket: {}",
303           strerror(errno));
304 
305       uint16_t hci_acl_data_total_length = (buf[4] << 8) + buf[3];
306       log::assert_that(
307           socketRecvAll(buf + kH4HeaderSize + kHciAclHeaderSize, hci_acl_data_total_length),
308           "Can't receive from socket: {}",
309           strerror(errno));
310 
311       HciPacket receivedHciPacket;
312       receivedHciPacket.assign(
313           buf + kH4HeaderSize, buf + kH4HeaderSize + kHciAclHeaderSize + hci_acl_data_total_length);
314       btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL);
315       {
316         std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
317         if (incoming_packet_callback_ == nullptr) {
318           log::info("Dropping an ACL packet after processing");
319           return;
320         }
321         incoming_packet_callback_->aclDataReceived(receivedHciPacket);
322       }
323     }
324 
325     if (buf[0] == kH4Sco) {
326       log::assert_that(
327           socketRecvAll(buf + kH4HeaderSize, kHciScoHeaderSize),
328           "Can't receive from socket: {}",
329           strerror(errno));
330 
331       uint8_t hci_sco_data_total_length = buf[3];
332       log::assert_that(
333           socketRecvAll(buf + kH4HeaderSize + kHciScoHeaderSize, hci_sco_data_total_length),
334           "Can't receive from socket: {}",
335           strerror(errno));
336 
337       HciPacket receivedHciPacket;
338       receivedHciPacket.assign(
339           buf + kH4HeaderSize, buf + kH4HeaderSize + kHciScoHeaderSize + hci_sco_data_total_length);
340       btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::SCO);
341       {
342         std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
343         if (incoming_packet_callback_ == nullptr) {
344           log::info("Dropping a SCO packet after processing");
345           return;
346         }
347         incoming_packet_callback_->scoDataReceived(receivedHciPacket);
348       }
349     }
350 
351     if (buf[0] == kH4Iso) {
352       log::assert_that(
353           socketRecvAll(buf + kH4HeaderSize, kHciIsoHeaderSize),
354           "Can't receive from socket: {}",
355           strerror(errno));
356 
357       uint16_t hci_iso_data_total_length = ((buf[4] & 0x3f) << 8) + buf[3];
358       log::assert_that(
359           socketRecvAll(buf + kH4HeaderSize + kHciIsoHeaderSize, hci_iso_data_total_length),
360           "Can't receive from socket: {}",
361           strerror(errno));
362 
363       HciPacket receivedHciPacket;
364       receivedHciPacket.assign(
365           buf + kH4HeaderSize, buf + kH4HeaderSize + kHciIsoHeaderSize + hci_iso_data_total_length);
366       btsnoop_logger_->Capture(receivedHciPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ISO);
367       {
368         std::lock_guard<std::mutex> incoming_packet_callback_lock(incoming_packet_callback_mutex_);
369         if (incoming_packet_callback_ == nullptr) {
370           log::info("Dropping a ISO packet after processing");
371           return;
372         }
373         incoming_packet_callback_->isoDataReceived(receivedHciPacket);
374       }
375     }
376     memset(buf, 0, kBufSize);
377   }
378 };
379 
__anon49125c870202() 380 const ModuleFactory HciHal::Factory = ModuleFactory([]() { return new HciHalHost(); });
381 
382 }  // namespace hal
383 }  // namespace bluetooth
384