• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "hci/facade/acl_manager_facade.h"
18 
19 #include <condition_variable>
20 #include <memory>
21 #include <mutex>
22 
23 #include "common/bind.h"
24 #include "grpc/grpc_event_queue.h"
25 #include "hci/acl_manager.h"
26 #include "hci/facade/acl_manager_facade.grpc.pb.h"
27 #include "hci/facade/acl_manager_facade.pb.h"
28 #include "hci/hci_packets.h"
29 #include "packet/raw_builder.h"
30 
31 using ::grpc::ServerAsyncResponseWriter;
32 using ::grpc::ServerAsyncWriter;
33 using ::grpc::ServerContext;
34 
35 using ::bluetooth::packet::RawBuilder;
36 
37 namespace bluetooth {
38 namespace hci {
39 namespace facade {
40 
41 class AclManagerFacadeService : public AclManagerFacade::Service,
42                                 public ::bluetooth::hci::ConnectionCallbacks,
43                                 public ::bluetooth::hci::ConnectionManagementCallbacks,
44                                 public ::bluetooth::hci::AclManagerCallbacks {
45  public:
AclManagerFacadeService(AclManager * acl_manager,::bluetooth::os::Handler * facade_handler)46   AclManagerFacadeService(AclManager* acl_manager, ::bluetooth::os::Handler* facade_handler)
47       : acl_manager_(acl_manager), facade_handler_(facade_handler) {
48     acl_manager_->RegisterCallbacks(this, facade_handler_);
49     acl_manager_->RegisterAclManagerCallbacks(this, facade_handler_);
50   }
51 
~AclManagerFacadeService()52   ~AclManagerFacadeService() override {
53     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
54     for (auto connection : acl_connections_) {
55       connection.second->GetAclQueueEnd()->UnregisterDequeue();
56     }
57   }
58 
CreateConnection(::grpc::ServerContext * context,const ConnectionMsg * request,::grpc::ServerWriter<ConnectionEvent> * writer)59   ::grpc::Status CreateConnection(::grpc::ServerContext* context, const ConnectionMsg* request,
60                                   ::grpc::ServerWriter<ConnectionEvent>* writer) override {
61     Address peer;
62     ASSERT(Address::FromString(request->address(), peer));
63     acl_manager_->CreateConnection(peer);
64     if (per_connection_events_.size() > current_connection_request_) {
65       return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Only one outstanding request is supported");
66     }
67     per_connection_events_.emplace_back(std::make_unique<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>>(
68         std::string("connection attempt ") + std::to_string(current_connection_request_)));
69     return per_connection_events_[current_connection_request_]->RunLoop(context, writer);
70   }
71 
Disconnect(::grpc::ServerContext * context,const HandleMsg * request,::google::protobuf::Empty * response)72   ::grpc::Status Disconnect(::grpc::ServerContext* context, const HandleMsg* request,
73                             ::google::protobuf::Empty* response) override {
74     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
75     auto connection = acl_connections_.find(request->handle());
76     if (connection == acl_connections_.end()) {
77       LOG_ERROR("Invalid handle");
78       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
79     } else {
80       connection->second->Disconnect(DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
81       return ::grpc::Status::OK;
82     }
83   }
84 
AuthenticationRequested(::grpc::ServerContext * context,const HandleMsg * request,::google::protobuf::Empty * response)85   ::grpc::Status AuthenticationRequested(::grpc::ServerContext* context, const HandleMsg* request,
86                                          ::google::protobuf::Empty* response) override {
87     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
88     auto connection = acl_connections_.find(request->handle());
89     if (connection == acl_connections_.end()) {
90       LOG_ERROR("Invalid handle");
91       return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
92     } else {
93       connection->second->AuthenticationRequested();
94       return ::grpc::Status::OK;
95     }
96   };
97 
FetchIncomingConnection(::grpc::ServerContext * context,const google::protobuf::Empty * request,::grpc::ServerWriter<ConnectionEvent> * writer)98   ::grpc::Status FetchIncomingConnection(::grpc::ServerContext* context, const google::protobuf::Empty* request,
99                                          ::grpc::ServerWriter<ConnectionEvent>* writer) override {
100     if (per_connection_events_.size() > current_connection_request_) {
101       return ::grpc::Status(::grpc::StatusCode::RESOURCE_EXHAUSTED, "Only one outstanding connection is supported");
102     }
103     per_connection_events_.emplace_back(std::make_unique<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>>(
104         std::string("incoming connection ") + std::to_string(current_connection_request_)));
105     return per_connection_events_[current_connection_request_]->RunLoop(context, writer);
106   }
107 
SendAclData(::grpc::ServerContext * context,const AclData * request,::google::protobuf::Empty * response)108   ::grpc::Status SendAclData(::grpc::ServerContext* context, const AclData* request,
109                              ::google::protobuf::Empty* response) override {
110     std::promise<void> promise;
111     auto future = promise.get_future();
112     {
113       std::unique_lock<std::mutex> lock(acl_connections_mutex_);
114       auto connection = acl_connections_.find(request->handle());
115       if (connection == acl_connections_.end()) {
116         LOG_ERROR("Invalid handle");
117         return ::grpc::Status(::grpc::StatusCode::INVALID_ARGUMENT, "Invalid handle");
118       } else {
119         connection->second->GetAclQueueEnd()->RegisterEnqueue(
120             facade_handler_, common::Bind(&AclManagerFacadeService::enqueue_packet, common::Unretained(this),
121                                           common::Unretained(request), common::Passed(std::move(promise))));
122       }
123     }
124     future.wait();
125     return ::grpc::Status::OK;
126   }
127 
enqueue_packet(const AclData * request,std::promise<void> promise)128   std::unique_ptr<BasePacketBuilder> enqueue_packet(const AclData* request, std::promise<void> promise) {
129     acl_connections_[request->handle()]->GetAclQueueEnd()->UnregisterEnqueue();
130     std::unique_ptr<RawBuilder> packet =
131         std::make_unique<RawBuilder>(std::vector<uint8_t>(request->payload().begin(), request->payload().end()));
132     promise.set_value();
133     return packet;
134   }
135 
FetchAclData(::grpc::ServerContext * context,const::google::protobuf::Empty * request,::grpc::ServerWriter<AclData> * writer)136   ::grpc::Status FetchAclData(::grpc::ServerContext* context, const ::google::protobuf::Empty* request,
137                               ::grpc::ServerWriter<AclData>* writer) override {
138     return pending_acl_data_.RunLoop(context, writer);
139   }
140 
to_handle(uint32_t current_request)141   static inline uint16_t to_handle(uint32_t current_request) {
142     return (current_request + 0x10) % 0xe00;
143   }
144 
builder_to_string(std::unique_ptr<BasePacketBuilder> builder)145   static inline std::string builder_to_string(std::unique_ptr<BasePacketBuilder> builder) {
146     std::vector<uint8_t> bytes;
147     BitInserter bit_inserter(bytes);
148     builder->Serialize(bit_inserter);
149     return std::string(bytes.begin(), bytes.end());
150   }
151 
on_incoming_acl(std::shared_ptr<AclConnection> connection,uint16_t handle)152   void on_incoming_acl(std::shared_ptr<AclConnection> connection, uint16_t handle) {
153     auto packet = connection->GetAclQueueEnd()->TryDequeue();
154     AclData acl_data;
155     acl_data.set_handle(handle);
156     acl_data.set_payload(std::string(packet->begin(), packet->end()));
157     pending_acl_data_.OnIncomingEvent(acl_data);
158   }
159 
on_disconnect(std::shared_ptr<AclConnection> connection,uint32_t entry,ErrorCode code)160   void on_disconnect(std::shared_ptr<AclConnection> connection, uint32_t entry, ErrorCode code) {
161     connection->GetAclQueueEnd()->UnregisterDequeue();
162     connection->Finish();
163     std::unique_ptr<BasePacketBuilder> builder =
164         DisconnectBuilder::Create(to_handle(entry), static_cast<DisconnectReason>(code));
165     ConnectionEvent disconnection;
166     disconnection.set_event(builder_to_string(std::move(builder)));
167     per_connection_events_[entry]->OnIncomingEvent(disconnection);
168   }
169 
OnConnectSuccess(std::unique_ptr<::bluetooth::hci::AclConnection> connection)170   void OnConnectSuccess(std::unique_ptr<::bluetooth::hci::AclConnection> connection) override {
171     std::unique_lock<std::mutex> lock(acl_connections_mutex_);
172     auto addr = connection->GetAddress();
173     std::shared_ptr<::bluetooth::hci::AclConnection> shared_connection = std::move(connection);
174     acl_connections_.emplace(to_handle(current_connection_request_), shared_connection);
175     auto remote_address = shared_connection->GetAddress().ToString();
176     shared_connection->GetAclQueueEnd()->RegisterDequeue(
177         facade_handler_, common::Bind(&AclManagerFacadeService::on_incoming_acl, common::Unretained(this),
178                                       shared_connection, to_handle(current_connection_request_)));
179     shared_connection->RegisterDisconnectCallback(
180         common::BindOnce(&AclManagerFacadeService::on_disconnect, common::Unretained(this), shared_connection,
181                          current_connection_request_),
182         facade_handler_);
183     shared_connection->RegisterCallbacks(this, facade_handler_);
184     std::unique_ptr<BasePacketBuilder> builder = ConnectionCompleteBuilder::Create(
185         ErrorCode::SUCCESS, to_handle(current_connection_request_), addr, LinkType::ACL, Enable::DISABLED);
186     ConnectionEvent success;
187     success.set_event(builder_to_string(std::move(builder)));
188     per_connection_events_[current_connection_request_]->OnIncomingEvent(success);
189     current_connection_request_++;
190   }
191 
OnMasterLinkKeyComplete(uint16_t connection_handle,KeyFlag key_flag)192   void OnMasterLinkKeyComplete(uint16_t connection_handle, KeyFlag key_flag) override {
193     LOG_DEBUG("OnMasterLinkKeyComplete connection_handle:%d", connection_handle);
194   }
195 
OnRoleChange(Address bd_addr,Role new_role)196   void OnRoleChange(Address bd_addr, Role new_role) override {
197     LOG_DEBUG("OnRoleChange bd_addr:%s, new_role:%d", bd_addr.ToString().c_str(), (uint8_t)new_role);
198   }
199 
OnReadDefaultLinkPolicySettingsComplete(uint16_t default_link_policy_settings)200   void OnReadDefaultLinkPolicySettingsComplete(uint16_t default_link_policy_settings) override {
201     LOG_DEBUG("OnReadDefaultLinkPolicySettingsComplete default_link_policy_settings:%d", default_link_policy_settings);
202   }
203 
OnConnectFail(Address address,ErrorCode reason)204   void OnConnectFail(Address address, ErrorCode reason) override {
205     std::unique_ptr<BasePacketBuilder> builder =
206         ConnectionCompleteBuilder::Create(reason, 0, address, LinkType::ACL, Enable::DISABLED);
207     ConnectionEvent fail;
208     fail.set_event(builder_to_string(std::move(builder)));
209     per_connection_events_[current_connection_request_]->OnIncomingEvent(fail);
210     current_connection_request_++;
211   }
212 
OnConnectionPacketTypeChanged(uint16_t packet_type)213   void OnConnectionPacketTypeChanged(uint16_t packet_type) override {
214     LOG_DEBUG("OnConnectionPacketTypeChanged packet_type:%d", packet_type);
215   }
216 
OnAuthenticationComplete()217   void OnAuthenticationComplete() override {
218     LOG_DEBUG("OnAuthenticationComplete");
219   }
220 
OnEncryptionChange(EncryptionEnabled enabled)221   void OnEncryptionChange(EncryptionEnabled enabled) override {
222     LOG_DEBUG("OnConnectionPacketTypeChanged enabled:%d", (uint8_t)enabled);
223   }
224 
OnChangeConnectionLinkKeyComplete()225   void OnChangeConnectionLinkKeyComplete() override {
226     LOG_DEBUG("OnChangeConnectionLinkKeyComplete");
227   };
228 
OnReadClockOffsetComplete(uint16_t clock_offset)229   void OnReadClockOffsetComplete(uint16_t clock_offset) override {
230     LOG_DEBUG("OnReadClockOffsetComplete clock_offset:%d", clock_offset);
231   };
232 
OnModeChange(Mode current_mode,uint16_t interval)233   void OnModeChange(Mode current_mode, uint16_t interval) override {
234     LOG_DEBUG("OnModeChange Mode:%d, interval:%d", (uint8_t)current_mode, interval);
235   };
236 
OnQosSetupComplete(ServiceType service_type,uint32_t token_rate,uint32_t peak_bandwidth,uint32_t latency,uint32_t delay_variation)237   void OnQosSetupComplete(ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency,
238                           uint32_t delay_variation) override {
239     LOG_DEBUG("OnQosSetupComplete service_type:%d, token_rate:%d, peak_bandwidth:%d, latency:%d, delay_variation:%d",
240               (uint8_t)service_type, token_rate, peak_bandwidth, latency, delay_variation);
241   }
242 
OnFlowSpecificationComplete(FlowDirection flow_direction,ServiceType service_type,uint32_t token_rate,uint32_t token_bucket_size,uint32_t peak_bandwidth,uint32_t access_latency)243   void OnFlowSpecificationComplete(FlowDirection flow_direction, ServiceType service_type, uint32_t token_rate,
244                                    uint32_t token_bucket_size, uint32_t peak_bandwidth,
245                                    uint32_t access_latency) override {
246     LOG_DEBUG(
247         "OnFlowSpecificationComplete flow_direction:%d. service_type:%d, token_rate:%d, token_bucket_size:%d, "
248         "peak_bandwidth:%d, access_latency:%d",
249         (uint8_t)flow_direction, (uint8_t)service_type, token_rate, token_bucket_size, peak_bandwidth, access_latency);
250   }
251 
OnFlushOccurred()252   void OnFlushOccurred() override {
253     LOG_DEBUG("OnFlushOccurred");
254   }
255 
OnRoleDiscoveryComplete(Role current_role)256   void OnRoleDiscoveryComplete(Role current_role) override {
257     LOG_DEBUG("OnRoleDiscoveryComplete current_role:%d", (uint8_t)current_role);
258   }
259 
OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings)260   void OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings) override {
261     LOG_DEBUG("OnReadLinkPolicySettingsComplete link_policy_settings:%d", link_policy_settings);
262   }
263 
OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout)264   void OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) override {
265     LOG_DEBUG("OnReadAutomaticFlushTimeoutComplete flush_timeout:%d", flush_timeout);
266   }
267 
OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level)268   void OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) override {
269     LOG_DEBUG("OnReadTransmitPowerLevelComplete transmit_power_level:%d", transmit_power_level);
270   }
271 
OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout)272   void OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) override {
273     LOG_DEBUG("OnReadLinkSupervisionTimeoutComplete link_supervision_timeout:%d", link_supervision_timeout);
274   }
275 
OnReadFailedContactCounterComplete(uint16_t failed_contact_counter)276   void OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) override {
277     LOG_DEBUG("OnReadFailedContactCounterComplete failed_contact_counter:%d", failed_contact_counter);
278   }
279 
OnReadLinkQualityComplete(uint8_t link_quality)280   void OnReadLinkQualityComplete(uint8_t link_quality) override {
281     LOG_DEBUG("OnReadLinkQualityComplete link_quality:%d", link_quality);
282   }
283 
OnReadAfhChannelMapComplete(AfhMode afh_mode,std::array<uint8_t,10> afh_channel_map)284   void OnReadAfhChannelMapComplete(AfhMode afh_mode, std::array<uint8_t, 10> afh_channel_map) override {
285     LOG_DEBUG("OnReadAfhChannelMapComplete afh_mode:%d", (uint8_t)afh_mode);
286   }
287 
OnReadRssiComplete(uint8_t rssi)288   void OnReadRssiComplete(uint8_t rssi) override {
289     LOG_DEBUG("OnReadRssiComplete rssi:%d", rssi);
290   }
291 
OnReadClockComplete(uint32_t clock,uint16_t accuracy)292   void OnReadClockComplete(uint32_t clock, uint16_t accuracy) override {
293     LOG_DEBUG("OnReadClockComplete clock:%d, accuracy:%d", clock, accuracy);
294   }
295 
296  private:
297   AclManager* acl_manager_;
298   ::bluetooth::os::Handler* facade_handler_;
299   mutable std::mutex acl_connections_mutex_;
300   std::map<uint16_t, std::shared_ptr<AclConnection>> acl_connections_;
301   ::bluetooth::grpc::GrpcEventQueue<AclData> pending_acl_data_{"FetchAclData"};
302   std::vector<std::unique_ptr<::bluetooth::grpc::GrpcEventQueue<ConnectionEvent>>> per_connection_events_;
303   uint32_t current_connection_request_{0};
304 };
305 
ListDependencies(ModuleList * list)306 void AclManagerFacadeModule::ListDependencies(ModuleList* list) {
307   ::bluetooth::grpc::GrpcFacadeModule::ListDependencies(list);
308   list->add<AclManager>();
309 }
310 
Start()311 void AclManagerFacadeModule::Start() {
312   ::bluetooth::grpc::GrpcFacadeModule::Start();
313   service_ = new AclManagerFacadeService(GetDependency<AclManager>(), GetHandler());
314 }
315 
Stop()316 void AclManagerFacadeModule::Stop() {
317   delete service_;
318   ::bluetooth::grpc::GrpcFacadeModule::Stop();
319 }
320 
GetService() const321 ::grpc::Service* AclManagerFacadeModule::GetService() const {
322   return service_;
323 }
324 
325 const ModuleFactory AclManagerFacadeModule::Factory =
__anond41f78540102() 326     ::bluetooth::ModuleFactory([]() { return new AclManagerFacadeModule(); });
327 
328 }  // namespace facade
329 }  // namespace hci
330 }  // namespace bluetooth
331