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 #include "l2cap/classic/internal/link_manager.h"
17 
18 #include <bluetooth/log.h>
19 
20 #include <memory>
21 #include <unordered_map>
22 
23 #include "hci/acl_manager/classic_acl_connection.h"
24 #include "hci/address.h"
25 #include "hci/class_of_device.h"
26 #include "l2cap/classic/internal/link.h"
27 #include "l2cap/internal/scheduler_fifo.h"
28 #include "os/log.h"
29 
30 namespace bluetooth {
31 namespace l2cap {
32 namespace classic {
33 namespace internal {
34 
ConnectFixedChannelServices(hci::Address device,PendingFixedChannelConnection pending_fixed_channel_connection)35 void LinkManager::ConnectFixedChannelServices(hci::Address device,
36                                               PendingFixedChannelConnection pending_fixed_channel_connection) {
37   // Check if there is any service registered
38   auto fixed_channel_services = fixed_channel_service_manager_->GetRegisteredServices();
39   if (fixed_channel_services.empty()) {
40     // If so, return error
41     pending_fixed_channel_connection.handler_->Post(common::BindOnce(
42         std::move(pending_fixed_channel_connection.on_fail_callback_),
43         FixedChannelManager::ConnectionResult{
44             .connection_result_code = FixedChannelManager::ConnectionResultCode::FAIL_NO_SERVICE_REGISTERED}));
45     return;
46   }
47   // Otherwise, check if device has an ACL connection
48   auto* link = GetLink(device);
49   if (link != nullptr) {
50     // If device already have an ACL connection
51     // Check if all registered services have an allocated channel and allocate one if not already allocated
52     int num_new_channels = 0;
53     for (auto& fixed_channel_service : fixed_channel_services) {
54       if (link->IsFixedChannelAllocated(fixed_channel_service.first)) {
55         // This channel is already allocated for this link, do not allocated twice
56         continue;
57       }
58       // Allocate channel for newly registered fixed channels
59       auto fixed_channel_impl = link->AllocateFixedChannel(fixed_channel_service.first);
60       fixed_channel_service.second->NotifyChannelCreation(
61           std::make_unique<FixedChannel>(fixed_channel_impl, l2cap_handler_));
62       num_new_channels++;
63     }
64     // Declare connection failure if no new channels are created
65     if (num_new_channels == 0) {
66       pending_fixed_channel_connection.handler_->Post(common::BindOnce(
67           std::move(pending_fixed_channel_connection.on_fail_callback_),
68           FixedChannelManager::ConnectionResult{
69               .connection_result_code = FixedChannelManager::ConnectionResultCode::FAIL_ALL_SERVICES_HAVE_CHANNEL}));
70     }
71     // No need to create ACL connection, return without saving any pending connections
72     return;
73   }
74   // If not, create new ACL connection
75   // Add request to pending link list first
76   auto pending_link = pending_links_.find(device);
77   if (pending_link == pending_links_.end()) {
78     // Create pending link if not exist
79     pending_links_.try_emplace(device);
80     pending_link = pending_links_.find(device);
81   }
82   pending_link->second.pending_fixed_channel_connections_.push_back(std::move(pending_fixed_channel_connection));
83   // Then create new ACL connection
84   acl_manager_->CreateConnection(device);
85 }
86 
ConnectDynamicChannelServices(hci::Address device,Link::PendingDynamicChannelConnection pending_dynamic_channel_connection,Psm psm)87 void LinkManager::ConnectDynamicChannelServices(
88     hci::Address device, Link::PendingDynamicChannelConnection pending_dynamic_channel_connection, Psm psm) {
89   if (!IsPsmValid(psm)) {
90     return;
91   }
92   auto* link = GetLink(device);
93   if (link == nullptr) {
94     acl_manager_->CreateConnection(device);
95     if (pending_dynamic_channels_.find(device) != pending_dynamic_channels_.end()) {
96       pending_dynamic_channels_[device].push_back(psm);
97       pending_dynamic_channels_callbacks_[device].push_back(std::move(pending_dynamic_channel_connection));
98     } else {
99       pending_dynamic_channels_[device] = {psm};
100       pending_dynamic_channels_callbacks_[device].push_back(std::move(pending_dynamic_channel_connection));
101     }
102     return;
103   }
104   link->SendConnectionRequest(psm, link->ReserveDynamicChannel(), std::move(pending_dynamic_channel_connection));
105 }
106 
InitiateConnectionForSecurity(hci::Address remote)107 void LinkManager::InitiateConnectionForSecurity(hci::Address remote) {
108   auto* link = GetLink(remote);
109   if (link != nullptr) {
110     log::error("Link already exists for {}", remote);
111   }
112   acl_manager_->CreateConnection(remote);
113 }
114 
RegisterLinkSecurityInterfaceListener(os::Handler * handler,LinkSecurityInterfaceListener * listener)115 void LinkManager::RegisterLinkSecurityInterfaceListener(os::Handler* handler, LinkSecurityInterfaceListener* listener) {
116   link_security_interface_listener_handler_ = handler;
117   link_security_interface_listener_ = listener;
118 }
119 
GetLinkSecurityInterfaceListener()120 LinkSecurityInterfaceListener* LinkManager::GetLinkSecurityInterfaceListener() {
121   return link_security_interface_listener_;
122 }
123 
RegisterLinkPropertyListener(os::Handler * handler,LinkPropertyListener * listener)124 void LinkManager::RegisterLinkPropertyListener(os::Handler* handler, LinkPropertyListener* listener) {
125   link_property_callback_handler_ = handler;
126   link_property_listener_ = listener;
127 }
128 
OnPendingPacketChange(hci::Address remote,int num_packets)129 void LinkManager::OnPendingPacketChange(hci::Address remote, int num_packets) {
130   if (disconnected_links_.count(remote) != 0 && num_packets == 0) {
131     links_.erase(remote);
132     links_with_pending_packets_.erase(remote);
133   } else if (num_packets != 0) {
134     links_with_pending_packets_.emplace(remote);
135   } else {
136     links_with_pending_packets_.erase(remote);
137   }
138 }
139 
GetLink(const hci::Address device)140 Link* LinkManager::GetLink(const hci::Address device) {
141   if (links_.find(device) == links_.end()) {
142     return nullptr;
143   }
144   return &links_.find(device)->second;
145 }
146 
handle_link_security_hold(hci::Address remote)147 void LinkManager::handle_link_security_hold(hci::Address remote) {
148   auto link = GetLink(remote);
149   if (link == nullptr) {
150     log::warn("Remote is disconnected");
151     return;
152   }
153   link->AcquireSecurityHold();
154 }
155 
handle_link_security_release(hci::Address remote)156 void LinkManager::handle_link_security_release(hci::Address remote) {
157   auto link = GetLink(remote);
158   if (link == nullptr) {
159     log::warn("Remote is disconnected");
160     return;
161   }
162   link->ReleaseSecurityHold();
163 }
164 
handle_link_security_disconnect(hci::Address remote)165 void LinkManager::handle_link_security_disconnect(hci::Address remote) {
166   auto link = GetLink(remote);
167   if (link == nullptr) {
168     log::warn("Remote is disconnected");
169     return;
170   }
171   link->Disconnect();
172 }
173 
handle_link_security_ensure_authenticated(hci::Address remote)174 void LinkManager::handle_link_security_ensure_authenticated(hci::Address remote) {
175   auto link = GetLink(remote);
176   if (link == nullptr) {
177     log::warn("Remote is disconnected");
178     return;
179   }
180   link->Authenticate();
181 }
182 
handle_link_security_ensure_encrypted(hci::Address remote)183 void LinkManager::handle_link_security_ensure_encrypted(hci::Address remote) {
184   auto link = GetLink(remote);
185   if (link == nullptr) {
186     log::warn("Remote is disconnected");
187     return;
188   }
189   link->Encrypt();
190 }
191 
192 /**
193  * The implementation for LinkSecurityInterface, which allows the SecurityModule to access some link functionalities.
194  * Note: All public methods implementing this interface are invoked from external context.
195  */
196 class LinkSecurityInterfaceImpl : public LinkSecurityInterface {
197  public:
LinkSecurityInterfaceImpl(os::Handler * handler,LinkManager * link_manager,Link * link)198   LinkSecurityInterfaceImpl(os::Handler* handler, LinkManager* link_manager, Link* link)
199       : handler_(handler),
200         link_manager_(link_manager),
201         remote_(link->GetDevice().GetAddress()),
202         acl_handle_(link->GetAclHandle()) {}
203 
GetRemoteAddress()204   hci::Address GetRemoteAddress() override {
205     return remote_;
206   }
207 
Hold()208   void Hold() override {
209     handler_->CallOn(link_manager_, &LinkManager::handle_link_security_hold, remote_);
210   }
211 
Release()212   void Release() override {
213     handler_->CallOn(link_manager_, &LinkManager::handle_link_security_release, remote_);
214   }
215 
Disconnect()216   void Disconnect() override {
217     handler_->CallOn(link_manager_, &LinkManager::handle_link_security_disconnect, remote_);
218   }
219 
EnsureAuthenticated()220   void EnsureAuthenticated() override {
221     handler_->CallOn(link_manager_, &LinkManager::handle_link_security_ensure_authenticated, remote_);
222   }
223 
EnsureEncrypted()224   void EnsureEncrypted() override {
225     handler_->CallOn(link_manager_, &LinkManager::handle_link_security_ensure_encrypted, remote_);
226   }
227 
GetAclHandle()228   uint16_t GetAclHandle() override {
229     return acl_handle_;
230   }
231 
GetRole()232   hci::Role GetRole() override {
233     return link_manager_->GetLink(remote_)->GetRole();
234   }
235 
236   os::Handler* handler_;
237   LinkManager* link_manager_;
238   hci::Address remote_;
239   uint16_t acl_handle_;
240 };
241 
OnConnectSuccess(std::unique_ptr<hci::acl_manager::ClassicAclConnection> acl_connection)242 void LinkManager::OnConnectSuccess(std::unique_ptr<hci::acl_manager::ClassicAclConnection> acl_connection) {
243   // Same link should not be connected twice
244   hci::Address device = acl_connection->GetAddress();
245   log::assert_that(
246       GetLink(device) == nullptr,
247       "{} is connected twice without disconnection",
248       ADDRESS_TO_LOGGABLE_CSTR(acl_connection->GetAddress()));
249   links_.try_emplace(device, l2cap_handler_, std::move(acl_connection), parameter_provider_,
250                      dynamic_channel_service_manager_, fixed_channel_service_manager_, this);
251   auto* link = GetLink(device);
252   log::assert_that(link != nullptr, "assert failed: link != nullptr");
253   link->SendInformationRequest(InformationRequestInfoType::EXTENDED_FEATURES_SUPPORTED);
254   link->SendInformationRequest(InformationRequestInfoType::FIXED_CHANNELS_SUPPORTED);
255   link->ReadRemoteVersionInformation();
256   link->ReadRemoteSupportedFeatures();
257   link->ReadRemoteExtendedFeatures(1);
258 
259   // Allocate and distribute channels for all registered fixed channel services
260   auto fixed_channel_services = fixed_channel_service_manager_->GetRegisteredServices();
261   for (auto& fixed_channel_service : fixed_channel_services) {
262     auto fixed_channel_impl = link->AllocateFixedChannel(fixed_channel_service.first);
263     fixed_channel_service.second->NotifyChannelCreation(
264         std::make_unique<FixedChannel>(fixed_channel_impl, l2cap_handler_));
265   }
266   if (pending_dynamic_channels_.find(device) != pending_dynamic_channels_.end()) {
267     auto psm_list = pending_dynamic_channels_[device];
268     auto& callback_list = pending_dynamic_channels_callbacks_[device];
269     link->SetPendingDynamicChannels(psm_list, std::move(callback_list));
270     pending_dynamic_channels_.erase(device);
271     pending_dynamic_channels_callbacks_.erase(device);
272   }
273   // Notify link property listener
274   if (link_property_callback_handler_ != nullptr) {
275     link_property_callback_handler_->CallOn(
276         link_property_listener_, &LinkPropertyListener::OnLinkConnected, device, link->GetAclHandle());
277   }
278 
279   // Notify security manager
280   if (link_security_interface_listener_handler_ != nullptr) {
281     link_security_interface_listener_handler_->CallOn(
282         link_security_interface_listener_,
283         &LinkSecurityInterfaceListener::OnLinkConnected,
284         std::make_unique<LinkSecurityInterfaceImpl>(l2cap_handler_, this, link));
285   }
286 
287   // Remove device from pending links list, if any
288   pending_links_.erase(device);
289 }
290 
OnConnectRequest(hci::Address,hci::ClassOfDevice)291 void LinkManager::OnConnectRequest(hci::Address /* device */, hci::ClassOfDevice /* cod */) {
292   log::error("Remote connect request unimplemented");
293 }
294 
OnConnectFail(hci::Address device,hci::ErrorCode reason,bool)295 void LinkManager::OnConnectFail(hci::Address device, hci::ErrorCode reason, bool) {
296   // Notify all pending links for this device
297   auto pending_link = pending_links_.find(device);
298   if (pending_link == pending_links_.end()) {
299     // There is no pending link, exit
300     log::info(
301         "Connection to {} failed without a pending link; reason: {}",
302         device,
303         hci::ErrorCodeText(reason));
304     if (pending_dynamic_channels_callbacks_.find(device) != pending_dynamic_channels_callbacks_.end()) {
305       for (Link::PendingDynamicChannelConnection& callbacks : pending_dynamic_channels_callbacks_[device]) {
306         callbacks.on_fail_callback_(DynamicChannelManager::ConnectionResult{
307             .hci_error = hci::ErrorCode::CONNECTION_TIMEOUT,
308         });
309       }
310       pending_dynamic_channels_.erase(device);
311       pending_dynamic_channels_callbacks_.erase(device);
312     }
313     return;
314   }
315   for (auto& pending_fixed_channel_connection : pending_link->second.pending_fixed_channel_connections_) {
316     pending_fixed_channel_connection.handler_->Post(common::BindOnce(
317         std::move(pending_fixed_channel_connection.on_fail_callback_),
318         FixedChannelManager::ConnectionResult{
319             .connection_result_code = FixedChannelManager::ConnectionResultCode::FAIL_HCI_ERROR, .hci_error = reason}));
320   }
321   // Remove entry in pending link list
322   pending_links_.erase(pending_link);
323 }
324 
OnDisconnect(hci::Address device,hci::ErrorCode status)325 void LinkManager::OnDisconnect(hci::Address device, hci::ErrorCode status) {
326   auto* link = GetLink(device);
327   log::assert_that(
328       link != nullptr,
329       "Device {} is disconnected with reason 0x{:x}, but not in local database",
330       ADDRESS_TO_LOGGABLE_CSTR(device),
331       static_cast<uint8_t>(status));
332   if (link_security_interface_listener_handler_ != nullptr) {
333     link_security_interface_listener_handler_->CallOn(
334         link_security_interface_listener_, &LinkSecurityInterfaceListener::OnLinkDisconnected, device);
335   }
336   if (link_property_callback_handler_ != nullptr) {
337     link_property_callback_handler_->CallOn(link_property_listener_, &LinkPropertyListener::OnLinkDisconnected, device);
338   }
339 
340   if (links_with_pending_packets_.count(device) != 0) {
341     disconnected_links_.emplace(device);
342   } else {
343     links_.erase(device);
344   }
345 }
346 
OnAuthenticationComplete(hci::ErrorCode hci_status,hci::Address device)347 void LinkManager::OnAuthenticationComplete(hci::ErrorCode hci_status, hci::Address device) {
348   if (link_security_interface_listener_handler_ != nullptr) {
349     link_security_interface_listener_handler_->CallOn(
350         link_security_interface_listener_,
351         &LinkSecurityInterfaceListener::OnAuthenticationComplete,
352         hci_status,
353         device);
354   }
355 }
356 
OnEncryptionChange(hci::Address device,hci::EncryptionEnabled enabled)357 void LinkManager::OnEncryptionChange(hci::Address device, hci::EncryptionEnabled enabled) {
358   if (link_security_interface_listener_handler_ != nullptr) {
359     link_security_interface_listener_handler_->CallOn(
360         link_security_interface_listener_,
361         &LinkSecurityInterfaceListener::OnEncryptionChange,
362         device,
363         enabled == hci::EncryptionEnabled::ON || enabled == hci::EncryptionEnabled::BR_EDR_AES_CCM);
364   }
365 }
366 
OnReadRemoteVersionInformation(hci::ErrorCode hci_status,hci::Address device,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)367 void LinkManager::OnReadRemoteVersionInformation(
368     hci::ErrorCode hci_status,
369     hci::Address device,
370     uint8_t lmp_version,
371     uint16_t manufacturer_name,
372     uint16_t sub_version) {
373   if (link_property_callback_handler_ != nullptr) {
374     link_property_callback_handler_->CallOn(
375         link_property_listener_,
376         &LinkPropertyListener::OnReadRemoteVersionInformation,
377         hci_status,
378         device,
379         lmp_version,
380         manufacturer_name,
381         sub_version);
382   }
383 }
384 
OnReadRemoteSupportedFeatures(hci::Address device,uint64_t features)385 void LinkManager::OnReadRemoteSupportedFeatures(hci::Address device, uint64_t features) {
386   if (link_property_callback_handler_ != nullptr) {
387     link_property_callback_handler_->CallOn(
388         link_property_listener_, &LinkPropertyListener::OnReadRemoteSupportedFeatures, device, features);
389   }
390 }
391 
OnReadRemoteExtendedFeatures(hci::Address device,uint8_t page_number,uint8_t max_page_number,uint64_t features)392 void LinkManager::OnReadRemoteExtendedFeatures(
393     hci::Address device, uint8_t page_number, uint8_t max_page_number, uint64_t features) {
394   if (link_property_callback_handler_ != nullptr) {
395     link_property_callback_handler_->CallOn(
396         link_property_listener_,
397         &LinkPropertyListener::OnReadRemoteExtendedFeatures,
398         device,
399         page_number,
400         max_page_number,
401         features);
402   }
403 }
404 
OnRoleChange(hci::ErrorCode hci_status,hci::Address remote,hci::Role role)405 void LinkManager::OnRoleChange(hci::ErrorCode hci_status, hci::Address remote, hci::Role role) {
406   if (link_property_callback_handler_ != nullptr) {
407     link_property_callback_handler_->CallOn(
408         link_property_listener_, &LinkPropertyListener::OnRoleChange, hci_status, remote, role);
409   }
410 }
411 
OnReadClockOffset(hci::Address remote,uint16_t clock_offset)412 void LinkManager::OnReadClockOffset(hci::Address remote, uint16_t clock_offset) {
413   if (link_property_callback_handler_ != nullptr) {
414     link_property_callback_handler_->CallOn(
415         link_property_listener_, &LinkPropertyListener::OnReadClockOffset, remote, clock_offset);
416   }
417 }
418 
OnModeChange(hci::ErrorCode hci_status,hci::Address remote,hci::Mode mode,uint16_t interval)419 void LinkManager::OnModeChange(hci::ErrorCode hci_status, hci::Address remote, hci::Mode mode, uint16_t interval) {
420   if (link_property_callback_handler_ != nullptr) {
421     link_property_callback_handler_->CallOn(
422         link_property_listener_, &LinkPropertyListener::OnModeChange, hci_status, remote, mode, interval);
423   }
424 }
425 
OnSniffSubrating(hci::ErrorCode hci_status,hci::Address remote,uint16_t max_tx_lat,uint16_t max_rx_lat,uint16_t min_remote_timeout,uint16_t min_local_timeout)426 void LinkManager::OnSniffSubrating(
427     hci::ErrorCode hci_status,
428     hci::Address remote,
429     uint16_t max_tx_lat,
430     uint16_t max_rx_lat,
431     uint16_t min_remote_timeout,
432     uint16_t min_local_timeout) {
433   if (link_property_callback_handler_ != nullptr) {
434     link_property_callback_handler_->CallOn(
435         link_property_listener_,
436         &LinkPropertyListener::OnSniffSubrating,
437         hci_status,
438         remote,
439         max_tx_lat,
440         max_rx_lat,
441         min_remote_timeout,
442         min_local_timeout);
443   }
444 }
445 
446 }  // namespace internal
447 }  // namespace classic
448 }  // namespace l2cap
449 }  // namespace bluetooth
450