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 "l2cap/le/internal/link.h"
18 
19 #include <bluetooth/log.h>
20 
21 #include <chrono>
22 #include <memory>
23 
24 #include "hci/acl_manager/le_acl_connection.h"
25 #include "l2cap/internal/dynamic_channel_impl.h"
26 #include "l2cap/internal/parameter_provider.h"
27 #include "l2cap/le/dynamic_channel_manager.h"
28 #include "l2cap/le/internal/fixed_channel_impl.h"
29 #include "l2cap/le/internal/link_manager.h"
30 #include "os/alarm.h"
31 
32 namespace bluetooth {
33 namespace l2cap {
34 namespace le {
35 namespace internal {
36 
37 static constexpr uint16_t kDefaultMinimumCeLength = 0x0002;
38 static constexpr uint16_t kDefaultMaximumCeLength = 0x0C00;
39 
Link(os::Handler * l2cap_handler,std::unique_ptr<hci::acl_manager::LeAclConnection> acl_connection,l2cap::internal::ParameterProvider * parameter_provider,DynamicChannelServiceManagerImpl * dynamic_service_manager,FixedChannelServiceManagerImpl *,LinkManager * link_manager)40 Link::Link(
41     os::Handler* l2cap_handler,
42     std::unique_ptr<hci::acl_manager::LeAclConnection> acl_connection,
43     l2cap::internal::ParameterProvider* parameter_provider,
44     DynamicChannelServiceManagerImpl* dynamic_service_manager,
45     FixedChannelServiceManagerImpl* /* fixed_service_manager */,
46     LinkManager* link_manager)
47     : l2cap_handler_(l2cap_handler),
48       acl_connection_(std::move(acl_connection)),
49       data_pipeline_manager_(l2cap_handler, this, acl_connection_->GetAclQueueEnd()),
50       parameter_provider_(parameter_provider),
51       dynamic_service_manager_(dynamic_service_manager),
52       signalling_manager_(
53           l2cap_handler_,
54           this,
55           &data_pipeline_manager_,
56           dynamic_service_manager_,
57           &dynamic_channel_allocator_),
58       link_manager_(link_manager) {
59   log::assert_that(l2cap_handler_ != nullptr, "assert failed: l2cap_handler_ != nullptr");
60   log::assert_that(acl_connection_ != nullptr, "assert failed: acl_connection_ != nullptr");
61   log::assert_that(parameter_provider_ != nullptr, "assert failed: parameter_provider_ != nullptr");
62   link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)),
63                                        parameter_provider_->GetLeLinkIdleDisconnectTimeout());
64   acl_connection_->RegisterCallbacks(this, l2cap_handler_);
65 }
66 
OnAclDisconnected(hci::ErrorCode reason)67 void Link::OnAclDisconnected(hci::ErrorCode reason) {
68   fixed_channel_allocator_.OnAclDisconnected(static_cast<hci::ErrorCode>(reason));
69   dynamic_channel_allocator_.OnAclDisconnected(static_cast<hci::ErrorCode>(reason));
70 }
71 
OnDisconnection(hci::ErrorCode status)72 void Link::OnDisconnection(hci::ErrorCode status) {
73   OnAclDisconnected(status);
74 
75   link_manager_->OnDisconnect(GetAclConnection()->GetRemoteAddress());
76 }
77 
OnConnectionUpdate(hci::ErrorCode,uint16_t connection_interval,uint16_t connection_latency,uint16_t supervision_timeout)78 void Link::OnConnectionUpdate(
79     hci::ErrorCode /* hci_status */,
80     uint16_t connection_interval,
81     uint16_t connection_latency,
82     uint16_t supervision_timeout) {
83   log::info(
84       "interval {:x} latency {:x} supervision_timeout {:x}",
85       connection_interval,
86       connection_latency,
87       supervision_timeout);
88   if (update_request_signal_id_ != kInvalidSignalId) {
89     hci::ErrorCode result = hci::ErrorCode::SUCCESS;
90     if (connection_interval > update_request_interval_max_ || connection_interval < update_request_interval_min_ ||
91         connection_latency != update_request_latency_ || supervision_timeout != update_request_supervision_timeout_) {
92       log::info(
93           "Received connection update complete with different parameters that provided by the "
94           "Host");
95     }
96 
97     if (!CheckConnectionParameters(connection_interval, connection_interval, connection_latency, supervision_timeout)) {
98       result = hci::ErrorCode::UNSPECIFIED_ERROR;
99     }
100 
101     on_connection_update_complete(update_request_signal_id_, result);
102     update_request_signal_id_ = kInvalidSignalId;
103   }
104 }
105 
OnDataLengthChange(uint16_t tx_octets,uint16_t tx_time,uint16_t rx_octets,uint16_t rx_time)106 void Link::OnDataLengthChange(uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time) {
107   log::info(
108       "tx_octets {:x} tx_time {:x} rx_octets {:x} rx_time {:x}",
109       tx_octets,
110       tx_time,
111       rx_octets,
112       rx_time);
113 }
114 
OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)115 void Link::OnReadRemoteVersionInformationComplete(
116     hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version) {
117   log::info(
118       "lmp_version:{} manufacturer_name:{} sub_version:{}",
119       lmp_version,
120       manufacturer_name,
121       sub_version);
122   link_manager_->OnReadRemoteVersionInformationComplete(
123       hci_status, GetDevice(), lmp_version, manufacturer_name, sub_version);
124 }
125 
OnLeReadRemoteFeaturesComplete(hci::ErrorCode,uint64_t)126 void Link::OnLeReadRemoteFeaturesComplete(hci::ErrorCode /* hci_status*/, uint64_t /* features */) {
127 }
128 
OnPhyUpdate(hci::ErrorCode,uint8_t,uint8_t)129 void Link::OnPhyUpdate(
130     hci::ErrorCode /* hci_status */, uint8_t /* tx_phy */, uint8_t /* rx_phy */) {}
131 
OnLeSubrateChange(hci::ErrorCode hci_status,uint16_t subrate_factor,uint16_t peripheral_latency,uint16_t continuation_number,uint16_t supervision_timeout)132 void Link::OnLeSubrateChange(
133     hci::ErrorCode hci_status,
134     uint16_t subrate_factor,
135     uint16_t peripheral_latency,
136     uint16_t continuation_number,
137     uint16_t supervision_timeout) {
138   log::info(
139       "hci_status: {}, subrate_factor: {:#x}, peripheral_latency: {:#x}, continuation_number: "
140       "{:#x}, supervision_timeout: {:#x}",
141       ErrorCodeText(hci_status),
142       subrate_factor,
143       peripheral_latency,
144       continuation_number,
145       supervision_timeout);
146 }
147 
Disconnect()148 void Link::Disconnect() {
149   acl_connection_->Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
150 }
151 
UpdateConnectionParameterFromRemote(SignalId signal_id,uint16_t conn_interval_min,uint16_t conn_interval_max,uint16_t conn_latency,uint16_t supervision_timeout)152 void Link::UpdateConnectionParameterFromRemote(SignalId signal_id, uint16_t conn_interval_min,
153                                                uint16_t conn_interval_max, uint16_t conn_latency,
154                                                uint16_t supervision_timeout) {
155   acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout,
156                                       kDefaultMinimumCeLength, kDefaultMaximumCeLength);
157   update_request_signal_id_ = signal_id;
158   update_request_interval_min_ = conn_interval_min;
159   update_request_interval_max_ = conn_interval_max;
160   update_request_latency_ = conn_latency;
161   update_request_supervision_timeout_ = supervision_timeout;
162 }
163 
CheckConnectionParameters(uint16_t conn_interval_min,uint16_t conn_interval_max,uint16_t conn_latency,uint16_t supervision_timeout)164 bool Link::CheckConnectionParameters(
165     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) {
166   if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 ||
167       conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A ||
168       supervision_timeout > 0x0C80) {
169     log::error("Invalid parameter");
170     return false;
171   }
172 
173   // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms
174   // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms
175   // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where Interval_Max is given in
176   // milliseconds.
177   uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1;
178   if (supervision_timeout * 8 < supervision_timeout_min || conn_interval_max < conn_interval_min) {
179     log::error("Invalid parameter");
180     return false;
181   }
182 
183   return true;
184 }
185 
SendConnectionParameterUpdate(uint16_t conn_interval_min,uint16_t conn_interval_max,uint16_t conn_latency,uint16_t supervision_timeout,uint16_t min_ce_length,uint16_t max_ce_length)186 void Link::SendConnectionParameterUpdate(uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
187                                          uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length) {
188   if (acl_connection_->GetRole() == hci::Role::PERIPHERAL) {
189     // TODO: If both LL central and peripheral support 4.1, use HCI command directly
190     signalling_manager_.SendConnectionParameterUpdateRequest(conn_interval_min, conn_interval_max, conn_latency,
191                                                              supervision_timeout);
192     return;
193   }
194   acl_connection_->LeConnectionUpdate(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout,
195                                       min_ce_length, max_ce_length);
196   update_request_signal_id_ = kInvalidSignalId;
197 }
198 
AllocateFixedChannel(Cid cid,SecurityPolicy)199 std::shared_ptr<FixedChannelImpl> Link::AllocateFixedChannel(
200     Cid cid, SecurityPolicy /* security_policy */) {
201   auto channel = fixed_channel_allocator_.AllocateChannel(cid);
202   data_pipeline_manager_.AttachChannel(cid, channel, l2cap::internal::DataPipelineManager::ChannelMode::BASIC);
203   return channel;
204 }
205 
IsFixedChannelAllocated(Cid cid)206 bool Link::IsFixedChannelAllocated(Cid cid) {
207   return fixed_channel_allocator_.IsChannelAllocated(cid);
208 }
209 
ReserveDynamicChannel()210 Cid Link::ReserveDynamicChannel() {
211   return dynamic_channel_allocator_.ReserveChannel();
212 }
213 
SendConnectionRequest(Psm psm,PendingDynamicChannelConnection pending_dynamic_channel_connection)214 void Link::SendConnectionRequest(Psm psm, PendingDynamicChannelConnection pending_dynamic_channel_connection) {
215   if (dynamic_channel_allocator_.IsPsmUsed(psm)) {
216     log::info("Psm {} is already connected", psm);
217     return;
218   }
219   auto reserved_cid = ReserveDynamicChannel();
220   auto mtu = pending_dynamic_channel_connection.configuration_.mtu;
221   local_cid_to_pending_dynamic_channel_connection_map_[reserved_cid] = std::move(pending_dynamic_channel_connection);
222   signalling_manager_.SendConnectionRequest(psm, reserved_cid, mtu);
223 }
224 
SendDisconnectionRequest(Cid local_cid,Cid remote_cid)225 void Link::SendDisconnectionRequest(Cid local_cid, Cid remote_cid) {
226   auto channel = dynamic_channel_allocator_.FindChannelByCid(local_cid);
227   if (channel == nullptr || channel->GetRemoteCid() != remote_cid) {
228     log::error("Invalid cid");
229   }
230   signalling_manager_.SendDisconnectRequest(local_cid, remote_cid);
231 }
232 
OnOutgoingConnectionRequestFail(Cid local_cid,LeCreditBasedConnectionResponseResult response_result)233 void Link::OnOutgoingConnectionRequestFail(Cid local_cid, LeCreditBasedConnectionResponseResult response_result) {
234   if (local_cid_to_pending_dynamic_channel_connection_map_.find(local_cid) !=
235       local_cid_to_pending_dynamic_channel_connection_map_.end()) {
236     // TODO(hsz): Currently we only notify the client when the remote didn't send connection response SUCCESS.
237     //  Should we notify the client when the link failed to establish?
238     DynamicChannelManager::ConnectionResult result{
239         .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_L2CAP_ERROR,
240         .hci_error = hci::ErrorCode::SUCCESS,
241         .l2cap_connection_response_result = response_result,
242     };
243     NotifyChannelFail(local_cid, result);
244   }
245   dynamic_channel_allocator_.FreeChannel(local_cid);
246 }
247 
AllocateDynamicChannel(Psm psm,Cid remote_cid)248 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateDynamicChannel(Psm psm, Cid remote_cid) {
249   auto channel = dynamic_channel_allocator_.AllocateChannel(psm, remote_cid);
250   if (channel != nullptr) {
251     data_pipeline_manager_.AttachChannel(channel->GetCid(), channel,
252                                          l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED);
253     RefreshRefCount();
254     channel->local_initiated_ = false;
255   }
256   return channel;
257 }
258 
AllocateReservedDynamicChannel(Cid reserved_cid,Psm psm,Cid remote_cid)259 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateReservedDynamicChannel(Cid reserved_cid, Psm psm,
260                                                                                           Cid remote_cid) {
261   auto channel = dynamic_channel_allocator_.AllocateReservedChannel(reserved_cid, psm, remote_cid);
262   if (channel != nullptr) {
263     data_pipeline_manager_.AttachChannel(channel->GetCid(), channel,
264                                          l2cap::internal::DataPipelineManager::ChannelMode::LE_CREDIT_BASED);
265     RefreshRefCount();
266     channel->local_initiated_ = true;
267   }
268   return channel;
269 }
270 
FreeDynamicChannel(Cid cid)271 void Link::FreeDynamicChannel(Cid cid) {
272   if (dynamic_channel_allocator_.FindChannelByCid(cid) == nullptr) {
273     return;
274   }
275   data_pipeline_manager_.DetachChannel(cid);
276   dynamic_channel_allocator_.FreeChannel(cid);
277   RefreshRefCount();
278 }
279 
RefreshRefCount()280 void Link::RefreshRefCount() {
281   int ref_count = 0;
282   ref_count += fixed_channel_allocator_.GetRefCount();
283   ref_count += dynamic_channel_allocator_.NumberOfChannels();
284   log::assert_that(ref_count >= 0, "ref_count {} is less than 0", ref_count);
285   if (ref_count > 0) {
286     link_idle_disconnect_alarm_.Cancel();
287   } else {
288     link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)),
289                                          parameter_provider_->GetLeLinkIdleDisconnectTimeout());
290   }
291 }
292 
NotifyChannelCreation(Cid cid,std::unique_ptr<DynamicChannel> user_channel)293 void Link::NotifyChannelCreation(Cid cid, std::unique_ptr<DynamicChannel> user_channel) {
294   log::assert_that(
295       local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
296           local_cid_to_pending_dynamic_channel_connection_map_.end(),
297       "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != "
298       "local_cid_to_pending_dynamic_channel_connection_map_.end()");
299   auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
300   pending_dynamic_channel_connection.handler_->Post(
301       common::BindOnce(std::move(pending_dynamic_channel_connection.on_open_callback_), std::move(user_channel)));
302   local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
303 }
304 
NotifyChannelFail(Cid cid,DynamicChannelManager::ConnectionResult result)305 void Link::NotifyChannelFail(Cid cid, DynamicChannelManager::ConnectionResult result) {
306   log::assert_that(
307       local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
308           local_cid_to_pending_dynamic_channel_connection_map_.end(),
309       "assert failed: local_cid_to_pending_dynamic_channel_connection_map_.find(cid) != "
310       "local_cid_to_pending_dynamic_channel_connection_map_.end()");
311   auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
312   // TODO(cmanton) Pass proper connection falure result to user
313   pending_dynamic_channel_connection.handler_->Post(
314       common::BindOnce(std::move(pending_dynamic_channel_connection.on_fail_callback_), result));
315   local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
316 }
317 
GetMps() const318 uint16_t Link::GetMps() const {
319   return parameter_provider_->GetLeMps();
320 }
321 
GetInitialCredit() const322 uint16_t Link::GetInitialCredit() const {
323   return parameter_provider_->GetLeInitialCredit();
324 }
325 
SendLeCredit(Cid local_cid,uint16_t credit)326 void Link::SendLeCredit(Cid local_cid, uint16_t credit) {
327   signalling_manager_.SendCredit(local_cid, credit);
328 }
329 
ReadRemoteVersionInformation()330 void Link::ReadRemoteVersionInformation() {
331   acl_connection_->ReadRemoteVersionInformation();
332 }
333 
on_connection_update_complete(SignalId signal_id,hci::ErrorCode error_code)334 void Link::on_connection_update_complete(SignalId signal_id, hci::ErrorCode error_code) {
335   if (!signal_id.IsValid()) {
336     log::info("Invalid signal_id");
337     return;
338   }
339   ConnectionParameterUpdateResponseResult result = (error_code == hci::ErrorCode::SUCCESS)
340                                                        ? ConnectionParameterUpdateResponseResult::ACCEPTED
341                                                        : ConnectionParameterUpdateResponseResult::REJECTED;
342   signalling_manager_.SendConnectionParameterUpdateResponse(SignalId(), result);
343 }
344 
OnPendingPacketChange(Cid,bool has_packet)345 void Link::OnPendingPacketChange(Cid /* local_cid */, bool has_packet) {
346   if (has_packet) {
347     remaining_packets_to_be_sent_++;
348   } else {
349     remaining_packets_to_be_sent_--;
350   }
351   link_manager_->OnPendingPacketChange(GetDevice(), remaining_packets_to_be_sent_);
352 }
353 
354 }  // namespace internal
355 }  // namespace le
356 }  // namespace l2cap
357 }  // namespace bluetooth
358