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/classic/internal/link.h"
18
19 #include <chrono>
20 #include <memory>
21
22 #include "common/bind.h"
23 #include "hci/acl_manager/classic_acl_connection.h"
24 #include "l2cap/classic/dynamic_channel_manager.h"
25 #include "l2cap/classic/internal/fixed_channel_impl.h"
26 #include "l2cap/classic/internal/link_manager.h"
27 #include "l2cap/internal/parameter_provider.h"
28 #include "os/alarm.h"
29
30 namespace bluetooth {
31 namespace l2cap {
32 namespace classic {
33 namespace internal {
34
35 using RetransmissionAndFlowControlMode = DynamicChannelConfigurationOption::RetransmissionAndFlowControlMode;
36 using ConnectionResult = DynamicChannelManager::ConnectionResult;
37 using ConnectionResultCode = DynamicChannelManager::ConnectionResultCode;
38
Link(os::Handler * l2cap_handler,std::unique_ptr<hci::acl_manager::ClassicAclConnection> acl_connection,l2cap::internal::ParameterProvider * parameter_provider,DynamicChannelServiceManagerImpl * dynamic_service_manager,FixedChannelServiceManagerImpl * fixed_service_manager,LinkManager * link_manager)39 Link::Link(os::Handler* l2cap_handler, std::unique_ptr<hci::acl_manager::ClassicAclConnection> acl_connection,
40 l2cap::internal::ParameterProvider* parameter_provider,
41 DynamicChannelServiceManagerImpl* dynamic_service_manager,
42 FixedChannelServiceManagerImpl* fixed_service_manager, LinkManager* link_manager)
43 : l2cap_handler_(l2cap_handler), acl_connection_(std::move(acl_connection)),
44 data_pipeline_manager_(l2cap_handler, this, acl_connection_->GetAclQueueEnd()),
45 parameter_provider_(parameter_provider), dynamic_service_manager_(dynamic_service_manager),
46 fixed_service_manager_(fixed_service_manager), link_manager_(link_manager),
47 signalling_manager_(l2cap_handler_, this, &data_pipeline_manager_, dynamic_service_manager_,
48 &dynamic_channel_allocator_, fixed_service_manager_) {
49 ASSERT(l2cap_handler_ != nullptr);
50 ASSERT(acl_connection_ != nullptr);
51 ASSERT(parameter_provider_ != nullptr);
52 link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)),
53 parameter_provider_->GetClassicLinkIdleDisconnectTimeout());
54 acl_connection_->RegisterCallbacks(this, l2cap_handler_);
55 }
56
OnAclDisconnected(hci::ErrorCode status)57 void Link::OnAclDisconnected(hci::ErrorCode status) {
58 signalling_manager_.CancelAlarm();
59 fixed_channel_allocator_.OnAclDisconnected(status);
60 dynamic_channel_allocator_.OnAclDisconnected(status);
61 ConnectionResult result{
62 .connection_result_code = ConnectionResultCode::FAIL_HCI_ERROR,
63 .hci_error = status,
64 .l2cap_connection_response_result = ConnectionResponseResult::SUCCESS,
65 };
66 while (!local_cid_to_pending_dynamic_channel_connection_map_.empty()) {
67 auto entry = local_cid_to_pending_dynamic_channel_connection_map_.begin();
68 NotifyChannelFail(entry->first, result);
69 }
70 }
71
Disconnect()72 void Link::Disconnect() {
73 acl_connection_->Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
74 }
75
Encrypt()76 void Link::Encrypt() {
77 acl_connection_->SetConnectionEncryption(hci::Enable::ENABLED);
78 }
79
Authenticate()80 void Link::Authenticate() {
81 if (!IsAuthenticated() && !has_requested_authentication_) {
82 has_requested_authentication_ = true;
83 acl_connection_->AuthenticationRequested();
84 }
85 }
86
IsAuthenticated() const87 bool Link::IsAuthenticated() const {
88 return encryption_enabled_ != hci::EncryptionEnabled::OFF;
89 }
90
ReadRemoteVersionInformation()91 void Link::ReadRemoteVersionInformation() {
92 acl_connection_->ReadRemoteVersionInformation();
93 }
94
ReadRemoteSupportedFeatures()95 void Link::ReadRemoteSupportedFeatures() {
96 acl_connection_->ReadRemoteSupportedFeatures();
97 }
98
ReadRemoteExtendedFeatures()99 void Link::ReadRemoteExtendedFeatures() {
100 acl_connection_->ReadRemoteExtendedFeatures();
101 }
102
ReadClockOffset()103 void Link::ReadClockOffset() {
104 acl_connection_->ReadClockOffset();
105 }
106
AcquireSecurityHold()107 void Link::AcquireSecurityHold() {
108 used_by_security_module_ = true;
109 RefreshRefCount();
110 }
ReleaseSecurityHold()111 void Link::ReleaseSecurityHold() {
112 used_by_security_module_ = false;
113 RefreshRefCount();
114 }
115
AllocateFixedChannel(Cid cid)116 std::shared_ptr<FixedChannelImpl> Link::AllocateFixedChannel(Cid cid) {
117 auto channel = fixed_channel_allocator_.AllocateChannel(cid);
118 data_pipeline_manager_.AttachChannel(cid, channel, l2cap::internal::DataPipelineManager::ChannelMode::BASIC);
119 return channel;
120 }
121
IsFixedChannelAllocated(Cid cid)122 bool Link::IsFixedChannelAllocated(Cid cid) {
123 return fixed_channel_allocator_.IsChannelAllocated(cid);
124 }
125
ReserveDynamicChannel()126 Cid Link::ReserveDynamicChannel() {
127 return dynamic_channel_allocator_.ReserveChannel();
128 }
129
SendConnectionRequest(Psm psm,Cid local_cid)130 void Link::SendConnectionRequest(Psm psm, Cid local_cid) {
131 signalling_manager_.SendConnectionRequest(psm, local_cid);
132 }
133
SendConnectionRequest(Psm psm,Cid local_cid,PendingDynamicChannelConnection pending_dynamic_channel_connection)134 void Link::SendConnectionRequest(Psm psm, Cid local_cid,
135 PendingDynamicChannelConnection pending_dynamic_channel_connection) {
136 if (pending_dynamic_channel_connection.configuration_.channel_mode ==
137 RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION &&
138 !remote_extended_feature_received_) {
139 pending_dynamic_psm_list_.push_back(psm);
140 pending_dynamic_channel_callback_list_.push_back(std::move(pending_dynamic_channel_connection));
141 LOG_INFO("Will connect after information response ERTM feature support is received");
142 dynamic_channel_allocator_.FreeChannel(local_cid);
143 return;
144 } else if (pending_dynamic_channel_connection.configuration_.channel_mode ==
145 RetransmissionAndFlowControlMode::ENHANCED_RETRANSMISSION &&
146 !GetRemoteSupportsErtm()) {
147 LOG_WARN("Remote doesn't support ERTM. Dropping connection request");
148 ConnectionResult result{
149 .connection_result_code = ConnectionResultCode::FAIL_REMOTE_NOT_SUPPORT,
150 };
151 pending_dynamic_channel_connection.on_fail_callback_.Invoke(result);
152 dynamic_channel_allocator_.FreeChannel(local_cid);
153 return;
154 } else {
155 local_cid_to_pending_dynamic_channel_connection_map_[local_cid] = std::move(pending_dynamic_channel_connection);
156 signalling_manager_.SendConnectionRequest(psm, local_cid);
157 }
158 }
159
SetPendingDynamicChannels(std::list<Psm> psm_list,std::list<Link::PendingDynamicChannelConnection> callback_list)160 void Link::SetPendingDynamicChannels(std::list<Psm> psm_list,
161 std::list<Link::PendingDynamicChannelConnection> callback_list) {
162 ASSERT(psm_list.size() == callback_list.size());
163 pending_dynamic_psm_list_ = std::move(psm_list);
164 pending_dynamic_channel_callback_list_ = std::move(callback_list);
165 }
166
connect_to_pending_dynamic_channels()167 void Link::connect_to_pending_dynamic_channels() {
168 auto psm = pending_dynamic_psm_list_.begin();
169 auto callback = pending_dynamic_channel_callback_list_.begin();
170 while (psm != pending_dynamic_psm_list_.end()) {
171 SendConnectionRequest(*psm, ReserveDynamicChannel(), std::move(*callback));
172 psm++;
173 callback++;
174 }
175 }
176
send_pending_configuration_requests()177 void Link::send_pending_configuration_requests() {
178 for (auto local_cid : pending_outgoing_configuration_request_list_) {
179 signalling_manager_.SendInitialConfigRequest(local_cid);
180 }
181 pending_outgoing_configuration_request_list_.clear();
182 }
183
OnOutgoingConnectionRequestFail(Cid local_cid,ConnectionResult result)184 void Link::OnOutgoingConnectionRequestFail(Cid local_cid, ConnectionResult result) {
185 if (local_cid_to_pending_dynamic_channel_connection_map_.find(local_cid) !=
186 local_cid_to_pending_dynamic_channel_connection_map_.end()) {
187 NotifyChannelFail(local_cid, result);
188 }
189 dynamic_channel_allocator_.FreeChannel(local_cid);
190 }
191
SendInitialConfigRequestOrQueue(Cid local_cid)192 void Link::SendInitialConfigRequestOrQueue(Cid local_cid) {
193 if (remote_extended_feature_received_) {
194 signalling_manager_.SendInitialConfigRequest(local_cid);
195 } else {
196 pending_outgoing_configuration_request_list_.push_back(local_cid);
197 }
198 }
199
SendDisconnectionRequest(Cid local_cid,Cid remote_cid)200 void Link::SendDisconnectionRequest(Cid local_cid, Cid remote_cid) {
201 signalling_manager_.SendDisconnectionRequest(local_cid, remote_cid);
202 }
203
SendInformationRequest(InformationRequestInfoType type)204 void Link::SendInformationRequest(InformationRequestInfoType type) {
205 signalling_manager_.SendInformationRequest(type);
206 }
207
AllocateDynamicChannel(Psm psm,Cid remote_cid)208 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateDynamicChannel(Psm psm, Cid remote_cid) {
209 auto channel = dynamic_channel_allocator_.AllocateChannel(psm, remote_cid);
210 if (channel != nullptr) {
211 RefreshRefCount();
212 }
213 channel->local_initiated_ = false;
214 return channel;
215 }
216
AllocateReservedDynamicChannel(Cid reserved_cid,Psm psm,Cid remote_cid)217 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateReservedDynamicChannel(Cid reserved_cid, Psm psm,
218 Cid remote_cid) {
219 auto channel = dynamic_channel_allocator_.AllocateReservedChannel(reserved_cid, psm, remote_cid);
220 if (channel != nullptr) {
221 RefreshRefCount();
222 }
223 channel->local_initiated_ = true;
224 return channel;
225 }
226
GetConfigurationForInitialConfiguration(Cid cid)227 classic::DynamicChannelConfigurationOption Link::GetConfigurationForInitialConfiguration(Cid cid) {
228 ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
229 local_cid_to_pending_dynamic_channel_connection_map_.end());
230 return local_cid_to_pending_dynamic_channel_connection_map_[cid].configuration_;
231 }
232
FreeDynamicChannel(Cid cid)233 void Link::FreeDynamicChannel(Cid cid) {
234 if (dynamic_channel_allocator_.FindChannelByCid(cid) == nullptr) {
235 return;
236 }
237 dynamic_channel_allocator_.FreeChannel(cid);
238 RefreshRefCount();
239 }
240
RefreshRefCount()241 void Link::RefreshRefCount() {
242 int ref_count = 0;
243 ref_count += fixed_channel_allocator_.GetRefCount();
244 ref_count += dynamic_channel_allocator_.NumberOfChannels();
245 if (used_by_security_module_) {
246 ref_count += 1;
247 }
248 ASSERT_LOG(ref_count >= 0, "ref_count %d is less than 0", ref_count);
249 if (ref_count > 0) {
250 link_idle_disconnect_alarm_.Cancel();
251 } else {
252 link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)),
253 parameter_provider_->GetClassicLinkIdleDisconnectTimeout());
254 }
255 }
256
NotifyChannelCreation(Cid cid,std::unique_ptr<DynamicChannel> user_channel)257 void Link::NotifyChannelCreation(Cid cid, std::unique_ptr<DynamicChannel> user_channel) {
258 ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
259 local_cid_to_pending_dynamic_channel_connection_map_.end());
260 auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
261 pending_dynamic_channel_connection.on_open_callback_.Invoke(std::move(user_channel));
262 local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
263 }
264
NotifyChannelFail(Cid cid,ConnectionResult result)265 void Link::NotifyChannelFail(Cid cid, ConnectionResult result) {
266 ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
267 local_cid_to_pending_dynamic_channel_connection_map_.end());
268 auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
269 pending_dynamic_channel_connection.on_fail_callback_.Invoke(result);
270 local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
271 }
272
SetRemoteConnectionlessMtu(Mtu mtu)273 void Link::SetRemoteConnectionlessMtu(Mtu mtu) {
274 remote_connectionless_mtu_ = mtu;
275 }
276
GetRemoteConnectionlessMtu() const277 Mtu Link::GetRemoteConnectionlessMtu() const {
278 return remote_connectionless_mtu_;
279 }
280
GetRemoteSupportsErtm() const281 bool Link::GetRemoteSupportsErtm() const {
282 return remote_supports_ertm_;
283 }
284
GetRemoteSupportsFcs() const285 bool Link::GetRemoteSupportsFcs() const {
286 return remote_supports_fcs_;
287 }
288
OnRemoteExtendedFeatureReceived(bool ertm_supported,bool fcs_supported)289 void Link::OnRemoteExtendedFeatureReceived(bool ertm_supported, bool fcs_supported) {
290 remote_supports_ertm_ = ertm_supported;
291 remote_supports_fcs_ = fcs_supported;
292 remote_extended_feature_received_ = true;
293 connect_to_pending_dynamic_channels();
294 send_pending_configuration_requests();
295 }
296
AddChannelPendingingAuthentication(PendingAuthenticateDynamicChannelConnection pending_channel)297 void Link::AddChannelPendingingAuthentication(PendingAuthenticateDynamicChannelConnection pending_channel) {
298 pending_channel_list_.push_back(std::move(pending_channel));
299 }
300
OnConnectionPacketTypeChanged(uint16_t packet_type)301 void Link::OnConnectionPacketTypeChanged(uint16_t packet_type) {
302 LOG_DEBUG("UNIMPLEMENTED %s packet_type:%x", __func__, packet_type);
303 }
304
OnAuthenticationComplete()305 void Link::OnAuthenticationComplete() {
306 Encrypt();
307 }
308
OnEncryptionChange(hci::EncryptionEnabled enabled)309 void Link::OnEncryptionChange(hci::EncryptionEnabled enabled) {
310 encryption_enabled_ = enabled;
311 if (encryption_enabled_ == hci::EncryptionEnabled::OFF) {
312 LOG_DEBUG("Encryption has changed to disabled");
313 return;
314 }
315 LOG_DEBUG("Encryption has changed to enabled .. restarting channels:%zd", pending_channel_list_.size());
316
317 for (auto& channel : pending_channel_list_) {
318 local_cid_to_pending_dynamic_channel_connection_map_[channel.cid_] =
319 std::move(channel.pending_dynamic_channel_connection_);
320 signalling_manager_.SendConnectionRequest(channel.psm_, channel.cid_);
321 }
322 pending_channel_list_.clear();
323 }
324
OnChangeConnectionLinkKeyComplete()325 void Link::OnChangeConnectionLinkKeyComplete() {
326 LOG_DEBUG("UNIMPLEMENTED %s", __func__);
327 }
328
OnReadClockOffsetComplete(uint16_t clock_offset)329 void Link::OnReadClockOffsetComplete(uint16_t clock_offset) {
330 LOG_DEBUG("UNIMPLEMENTED %s clock_offset:%d", __func__, clock_offset);
331 }
332
OnModeChange(hci::Mode current_mode,uint16_t interval)333 void Link::OnModeChange(hci::Mode current_mode, uint16_t interval) {
334 LOG_DEBUG("UNIMPLEMENTED %s mode:%s interval:%d", __func__, hci::ModeText(current_mode).c_str(), interval);
335 }
336
OnQosSetupComplete(hci::ServiceType service_type,uint32_t token_rate,uint32_t peak_bandwidth,uint32_t latency,uint32_t delay_variation)337 void Link::OnQosSetupComplete(hci::ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth,
338 uint32_t latency, uint32_t delay_variation) {
339 LOG_DEBUG("UNIMPLEMENTED %s service_type:%s token_rate:%d peak_bandwidth:%d latency:%d delay_varitation:%d", __func__,
340 hci::ServiceTypeText(service_type).c_str(), token_rate, peak_bandwidth, latency, delay_variation);
341 }
OnFlowSpecificationComplete(hci::FlowDirection flow_direction,hci::ServiceType service_type,uint32_t token_rate,uint32_t token_bucket_size,uint32_t peak_bandwidth,uint32_t access_latency)342 void Link::OnFlowSpecificationComplete(hci::FlowDirection flow_direction, hci::ServiceType service_type,
343 uint32_t token_rate, uint32_t token_bucket_size, uint32_t peak_bandwidth,
344 uint32_t access_latency) {
345 LOG_DEBUG(
346 "UNIMPLEMENTED %s flow_direction:%s service_type:%s token_rate:%d token_bucket_size:%d peak_bandwidth:%d "
347 "access_latency:%d",
348 __func__, hci::FlowDirectionText(flow_direction).c_str(), hci::ServiceTypeText(service_type).c_str(), token_rate,
349 token_bucket_size, peak_bandwidth, access_latency);
350 }
OnFlushOccurred()351 void Link::OnFlushOccurred() {
352 LOG_DEBUG("UNIMPLEMENTED %s", __func__);
353 }
OnRoleDiscoveryComplete(hci::Role current_role)354 void Link::OnRoleDiscoveryComplete(hci::Role current_role) {
355 LOG_DEBUG("UNIMPLEMENTED %s current_role:%s", __func__, hci::RoleText(current_role).c_str());
356 }
OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings)357 void Link::OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings) {
358 LOG_DEBUG("UNIMPLEMENTED %s link_policy_settings:0x%x", __func__, link_policy_settings);
359 }
OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout)360 void Link::OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) {
361 LOG_DEBUG("UNIMPLEMENTED %s flush_timeout:%d", __func__, flush_timeout);
362 }
OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level)363 void Link::OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) {
364 LOG_DEBUG("UNIMPLEMENTED %s transmit_power_level:%d", __func__, transmit_power_level);
365 }
OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout)366 void Link::OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) {
367 LOG_DEBUG("UNIMPLEMENTED %s link_supervision_timeout:%d", __func__, link_supervision_timeout);
368 }
OnReadFailedContactCounterComplete(uint16_t failed_contact_counter)369 void Link::OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) {
370 LOG_DEBUG("UNIMPLEMENTED %sfailed_contact_counter:%hu", __func__, failed_contact_counter);
371 }
OnReadLinkQualityComplete(uint8_t link_quality)372 void Link::OnReadLinkQualityComplete(uint8_t link_quality) {
373 LOG_DEBUG("UNIMPLEMENTED %s link_quality:%hhu", __func__, link_quality);
374 }
OnReadAfhChannelMapComplete(hci::AfhMode afh_mode,std::array<uint8_t,10> afh_channel_map)375 void Link::OnReadAfhChannelMapComplete(hci::AfhMode afh_mode, std::array<uint8_t, 10> afh_channel_map) {
376 LOG_DEBUG("UNIMPLEMENTED %s afh_mode:%s", __func__, hci::AfhModeText(afh_mode).c_str());
377 }
OnReadRssiComplete(uint8_t rssi)378 void Link::OnReadRssiComplete(uint8_t rssi) {
379 LOG_DEBUG("UNIMPLEMENTED %s rssi:%hhd", __func__, rssi);
380 }
OnReadClockComplete(uint32_t clock,uint16_t accuracy)381 void Link::OnReadClockComplete(uint32_t clock, uint16_t accuracy) {
382 LOG_DEBUG("UNIMPLEMENTED %s clock:%u accuracy:%hu", __func__, clock, accuracy);
383 }
OnMasterLinkKeyComplete(hci::KeyFlag key_flag)384 void Link::OnMasterLinkKeyComplete(hci::KeyFlag key_flag) {
385 LOG_DEBUG("UNIMPLEMENTED key_flag:%s", hci::KeyFlagText(key_flag).c_str());
386 }
OnRoleChange(hci::Role new_role)387 void Link::OnRoleChange(hci::Role new_role) {
388 LOG_DEBUG("UNIMPLEMENTED role:%s", hci::RoleText(new_role).c_str());
389 }
OnDisconnection(hci::ErrorCode reason)390 void Link::OnDisconnection(hci::ErrorCode reason) {
391 OnAclDisconnected(reason);
392 link_manager_->OnDisconnect(GetDevice().GetAddress(), reason);
393 }
394
395 } // namespace internal
396 } // namespace classic
397 } // namespace l2cap
398 } // namespace bluetooth
399