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