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 <chrono>
18 #include <memory>
19
20 #include "hci/acl_manager.h"
21 #include "l2cap/classic/dynamic_channel_manager.h"
22 #include "l2cap/classic/internal/fixed_channel_impl.h"
23 #include "l2cap/classic/internal/link.h"
24 #include "l2cap/internal/parameter_provider.h"
25 #include "os/alarm.h"
26
27 namespace bluetooth {
28 namespace l2cap {
29 namespace classic {
30 namespace internal {
31
Link(os::Handler * l2cap_handler,std::unique_ptr<hci::AclConnection> acl_connection,l2cap::internal::ParameterProvider * parameter_provider,DynamicChannelServiceManagerImpl * dynamic_service_manager,FixedChannelServiceManagerImpl * fixed_service_manager)32 Link::Link(os::Handler* l2cap_handler, std::unique_ptr<hci::AclConnection> acl_connection,
33 l2cap::internal::ParameterProvider* parameter_provider,
34 DynamicChannelServiceManagerImpl* dynamic_service_manager,
35 FixedChannelServiceManagerImpl* fixed_service_manager)
36 : l2cap_handler_(l2cap_handler), acl_connection_(std::move(acl_connection)),
37 data_pipeline_manager_(l2cap_handler, this, acl_connection_->GetAclQueueEnd()),
38 parameter_provider_(parameter_provider), dynamic_service_manager_(dynamic_service_manager),
39 fixed_service_manager_(fixed_service_manager),
40 signalling_manager_(l2cap_handler_, this, &data_pipeline_manager_, dynamic_service_manager_,
41 &dynamic_channel_allocator_, fixed_service_manager_) {
42 ASSERT(l2cap_handler_ != nullptr);
43 ASSERT(acl_connection_ != nullptr);
44 ASSERT(parameter_provider_ != nullptr);
45 link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)),
46 parameter_provider_->GetClassicLinkIdleDisconnectTimeout());
47 acl_connection_->RegisterCallbacks(this, l2cap_handler_);
48 }
49
~Link()50 Link::~Link() {
51 acl_connection_->UnregisterCallbacks(this);
52 }
53
OnAclDisconnected(hci::ErrorCode status)54 void Link::OnAclDisconnected(hci::ErrorCode status) {
55 signalling_manager_.CancelAlarm();
56 fixed_channel_allocator_.OnAclDisconnected(status);
57 dynamic_channel_allocator_.OnAclDisconnected(status);
58 DynamicChannelManager::ConnectionResult result{
59 .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_HCI_ERROR,
60 .hci_error = status,
61 .l2cap_connection_response_result = ConnectionResponseResult::SUCCESS,
62 };
63 while (!local_cid_to_pending_dynamic_channel_connection_map_.empty()) {
64 auto entry = local_cid_to_pending_dynamic_channel_connection_map_.begin();
65 NotifyChannelFail(entry->first, result);
66 }
67 }
68
Disconnect()69 void Link::Disconnect() {
70 acl_connection_->Disconnect(hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
71 }
72
Encrypt()73 void Link::Encrypt() {
74 acl_connection_->SetConnectionEncryption(hci::Enable::ENABLED);
75 }
76
Authenticate()77 void Link::Authenticate() {
78 acl_connection_->AuthenticationRequested();
79 }
80
IsAuthenticated() const81 bool Link::IsAuthenticated() const {
82 return encryption_enabled_ != hci::EncryptionEnabled::OFF;
83 }
84
ReadRemoteVersionInformation()85 void Link::ReadRemoteVersionInformation() {
86 acl_connection_->ReadRemoteVersionInformation();
87 }
88
ReadRemoteSupportedFeatures()89 void Link::ReadRemoteSupportedFeatures() {
90 acl_connection_->ReadRemoteSupportedFeatures();
91 }
92
ReadRemoteExtendedFeatures()93 void Link::ReadRemoteExtendedFeatures() {
94 acl_connection_->ReadRemoteExtendedFeatures();
95 }
96
ReadClockOffset()97 void Link::ReadClockOffset() {
98 acl_connection_->ReadClockOffset();
99 }
100
AllocateFixedChannel(Cid cid,SecurityPolicy security_policy)101 std::shared_ptr<FixedChannelImpl> Link::AllocateFixedChannel(Cid cid, SecurityPolicy security_policy) {
102 auto channel = fixed_channel_allocator_.AllocateChannel(cid, security_policy);
103 data_pipeline_manager_.AttachChannel(cid, channel, l2cap::internal::DataPipelineManager::ChannelMode::BASIC);
104 return channel;
105 }
106
IsFixedChannelAllocated(Cid cid)107 bool Link::IsFixedChannelAllocated(Cid cid) {
108 return fixed_channel_allocator_.IsChannelAllocated(cid);
109 }
110
ReserveDynamicChannel()111 Cid Link::ReserveDynamicChannel() {
112 return dynamic_channel_allocator_.ReserveChannel();
113 }
114
SendConnectionRequest(Psm psm,Cid local_cid)115 void Link::SendConnectionRequest(Psm psm, Cid local_cid) {
116 signalling_manager_.SendConnectionRequest(psm, local_cid);
117 }
118
SendConnectionRequest(Psm psm,Cid local_cid,PendingDynamicChannelConnection pending_dynamic_channel_connection)119 void Link::SendConnectionRequest(Psm psm, Cid local_cid,
120 PendingDynamicChannelConnection pending_dynamic_channel_connection) {
121 local_cid_to_pending_dynamic_channel_connection_map_[local_cid] = std::move(pending_dynamic_channel_connection);
122 signalling_manager_.SendConnectionRequest(psm, local_cid);
123 }
124
OnOutgoingConnectionRequestFail(Cid local_cid)125 void Link::OnOutgoingConnectionRequestFail(Cid local_cid) {
126 if (local_cid_to_pending_dynamic_channel_connection_map_.find(local_cid) !=
127 local_cid_to_pending_dynamic_channel_connection_map_.end()) {
128 DynamicChannelManager::ConnectionResult result{
129 .connection_result_code = DynamicChannelManager::ConnectionResultCode::FAIL_HCI_ERROR,
130 .hci_error = hci::ErrorCode::CONNECTION_TIMEOUT,
131 .l2cap_connection_response_result = ConnectionResponseResult::SUCCESS,
132 };
133 NotifyChannelFail(local_cid, result);
134 }
135 dynamic_channel_allocator_.FreeChannel(local_cid);
136 }
137
SendDisconnectionRequest(Cid local_cid,Cid remote_cid)138 void Link::SendDisconnectionRequest(Cid local_cid, Cid remote_cid) {
139 signalling_manager_.SendDisconnectionRequest(local_cid, remote_cid);
140 }
141
SendInformationRequest(InformationRequestInfoType type)142 void Link::SendInformationRequest(InformationRequestInfoType type) {
143 signalling_manager_.SendInformationRequest(type);
144 }
145
AllocateDynamicChannel(Psm psm,Cid remote_cid,SecurityPolicy security_policy)146 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateDynamicChannel(Psm psm, Cid remote_cid,
147 SecurityPolicy security_policy) {
148 auto channel = dynamic_channel_allocator_.AllocateChannel(psm, remote_cid, security_policy);
149 if (channel != nullptr) {
150 data_pipeline_manager_.AttachChannel(channel->GetCid(), channel,
151 l2cap::internal::DataPipelineManager::ChannelMode::BASIC);
152 RefreshRefCount();
153 }
154 channel->local_initiated_ = false;
155 return channel;
156 }
157
AllocateReservedDynamicChannel(Cid reserved_cid,Psm psm,Cid remote_cid,SecurityPolicy security_policy)158 std::shared_ptr<l2cap::internal::DynamicChannelImpl> Link::AllocateReservedDynamicChannel(
159 Cid reserved_cid, Psm psm, Cid remote_cid, SecurityPolicy security_policy) {
160 auto channel = dynamic_channel_allocator_.AllocateReservedChannel(reserved_cid, psm, remote_cid, security_policy);
161 if (channel != nullptr) {
162 data_pipeline_manager_.AttachChannel(channel->GetCid(), channel,
163 l2cap::internal::DataPipelineManager::ChannelMode::BASIC);
164 RefreshRefCount();
165 }
166 channel->local_initiated_ = true;
167 return channel;
168 }
169
GetConfigurationForInitialConfiguration(Cid cid)170 classic::DynamicChannelConfigurationOption Link::GetConfigurationForInitialConfiguration(Cid cid) {
171 ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
172 local_cid_to_pending_dynamic_channel_connection_map_.end());
173 return local_cid_to_pending_dynamic_channel_connection_map_[cid].configuration_;
174 }
175
FreeDynamicChannel(Cid cid)176 void Link::FreeDynamicChannel(Cid cid) {
177 if (dynamic_channel_allocator_.FindChannelByCid(cid) == nullptr) {
178 return;
179 }
180 data_pipeline_manager_.DetachChannel(cid);
181 dynamic_channel_allocator_.FreeChannel(cid);
182 RefreshRefCount();
183 }
184
RefreshRefCount()185 void Link::RefreshRefCount() {
186 int ref_count = 0;
187 ref_count += fixed_channel_allocator_.GetRefCount();
188 ref_count += dynamic_channel_allocator_.NumberOfChannels();
189 ASSERT_LOG(ref_count >= 0, "ref_count %d is less than 0", ref_count);
190 if (ref_count > 0) {
191 link_idle_disconnect_alarm_.Cancel();
192 } else {
193 link_idle_disconnect_alarm_.Schedule(common::BindOnce(&Link::Disconnect, common::Unretained(this)),
194 parameter_provider_->GetClassicLinkIdleDisconnectTimeout());
195 }
196 }
197
NotifyChannelCreation(Cid cid,std::unique_ptr<DynamicChannel> user_channel)198 void Link::NotifyChannelCreation(Cid cid, std::unique_ptr<DynamicChannel> user_channel) {
199 ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
200 local_cid_to_pending_dynamic_channel_connection_map_.end());
201 auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
202 pending_dynamic_channel_connection.handler_->Post(
203 common::BindOnce(std::move(pending_dynamic_channel_connection.on_open_callback_), std::move(user_channel)));
204 local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
205 }
206
NotifyChannelFail(Cid cid,DynamicChannelManager::ConnectionResult result)207 void Link::NotifyChannelFail(Cid cid, DynamicChannelManager::ConnectionResult result) {
208 ASSERT(local_cid_to_pending_dynamic_channel_connection_map_.find(cid) !=
209 local_cid_to_pending_dynamic_channel_connection_map_.end());
210 auto& pending_dynamic_channel_connection = local_cid_to_pending_dynamic_channel_connection_map_[cid];
211 pending_dynamic_channel_connection.handler_->Post(
212 common::BindOnce(std::move(pending_dynamic_channel_connection.on_fail_callback_), result));
213 local_cid_to_pending_dynamic_channel_connection_map_.erase(cid);
214 }
215
SetRemoteConnectionlessMtu(Mtu mtu)216 void Link::SetRemoteConnectionlessMtu(Mtu mtu) {
217 remote_connectionless_mtu_ = mtu;
218 }
219
GetRemoteConnectionlessMtu() const220 Mtu Link::GetRemoteConnectionlessMtu() const {
221 return remote_connectionless_mtu_;
222 }
223
SetRemoteSupportsErtm(bool supported)224 void Link::SetRemoteSupportsErtm(bool supported) {
225 remote_supports_ertm_ = supported;
226 }
227
GetRemoteSupportsErtm() const228 bool Link::GetRemoteSupportsErtm() const {
229 return remote_supports_ertm_;
230 }
231
SetRemoteSupportsFcs(bool supported)232 void Link::SetRemoteSupportsFcs(bool supported) {
233 remote_supports_fcs_ = supported;
234 }
235
GetRemoteSupportsFcs() const236 bool Link::GetRemoteSupportsFcs() const {
237 return remote_supports_fcs_;
238 }
239
AddChannelPendingingAuthentication(PendingAuthenticateDynamicChannelConnection pending_channel)240 void Link::AddChannelPendingingAuthentication(PendingAuthenticateDynamicChannelConnection pending_channel) {
241 pending_channel_list_.push_back(std::move(pending_channel));
242 }
243
OnConnectionPacketTypeChanged(uint16_t packet_type)244 void Link::OnConnectionPacketTypeChanged(uint16_t packet_type) {
245 LOG_DEBUG("UNIMPLEMENTED %s packet_type:%x", __func__, packet_type);
246 }
247
OnAuthenticationComplete()248 void Link::OnAuthenticationComplete() {
249 if (!pending_channel_list_.empty()) {
250 acl_connection_->SetConnectionEncryption(hci::Enable::ENABLED);
251 }
252 }
253
OnEncryptionChange(hci::EncryptionEnabled enabled)254 void Link::OnEncryptionChange(hci::EncryptionEnabled enabled) {
255 encryption_enabled_ = enabled;
256 if (encryption_enabled_ == hci::EncryptionEnabled::OFF) {
257 LOG_DEBUG("Encryption has changed to disabled");
258 return;
259 }
260 LOG_DEBUG("Encryption has changed to enabled .. restarting channels:%zd", pending_channel_list_.size());
261
262 for (auto& channel : pending_channel_list_) {
263 local_cid_to_pending_dynamic_channel_connection_map_[channel.cid_] =
264 std::move(channel.pending_dynamic_channel_connection_);
265 signalling_manager_.SendConnectionRequest(channel.psm_, channel.cid_);
266 }
267 pending_channel_list_.clear();
268 }
269
OnChangeConnectionLinkKeyComplete()270 void Link::OnChangeConnectionLinkKeyComplete() {
271 LOG_DEBUG("UNIMPLEMENTED %s", __func__);
272 }
273
OnReadClockOffsetComplete(uint16_t clock_offset)274 void Link::OnReadClockOffsetComplete(uint16_t clock_offset) {
275 LOG_DEBUG("UNIMPLEMENTED %s clock_offset:%d", __func__, clock_offset);
276 }
277
OnModeChange(hci::Mode current_mode,uint16_t interval)278 void Link::OnModeChange(hci::Mode current_mode, uint16_t interval) {
279 LOG_DEBUG("UNIMPLEMENTED %s mode:%s interval:%d", __func__, hci::ModeText(current_mode).c_str(), interval);
280 }
281
OnQosSetupComplete(hci::ServiceType service_type,uint32_t token_rate,uint32_t peak_bandwidth,uint32_t latency,uint32_t delay_variation)282 void Link::OnQosSetupComplete(hci::ServiceType service_type, uint32_t token_rate, uint32_t peak_bandwidth,
283 uint32_t latency, uint32_t delay_variation) {
284 LOG_DEBUG("UNIMPLEMENTED %s service_type:%s token_rate:%d peak_bandwidth:%d latency:%d delay_varitation:%d", __func__,
285 hci::ServiceTypeText(service_type).c_str(), token_rate, peak_bandwidth, latency, delay_variation);
286 }
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)287 void Link::OnFlowSpecificationComplete(hci::FlowDirection flow_direction, hci::ServiceType service_type,
288 uint32_t token_rate, uint32_t token_bucket_size, uint32_t peak_bandwidth,
289 uint32_t access_latency) {
290 LOG_DEBUG(
291 "UNIMPLEMENTED %s flow_direction:%s service_type:%s token_rate:%d token_bucket_size:%d peak_bandwidth:%d "
292 "access_latency:%d",
293 __func__, hci::FlowDirectionText(flow_direction).c_str(), hci::ServiceTypeText(service_type).c_str(), token_rate,
294 token_bucket_size, peak_bandwidth, access_latency);
295 }
OnFlushOccurred()296 void Link::OnFlushOccurred() {
297 LOG_DEBUG("UNIMPLEMENTED %s", __func__);
298 }
OnRoleDiscoveryComplete(hci::Role current_role)299 void Link::OnRoleDiscoveryComplete(hci::Role current_role) {
300 LOG_DEBUG("UNIMPLEMENTED %s current_role:%s", __func__, hci::RoleText(current_role).c_str());
301 }
OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings)302 void Link::OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings) {
303 LOG_DEBUG("UNIMPLEMENTED %s link_policy_settings:0x%x", __func__, link_policy_settings);
304 }
OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout)305 void Link::OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) {
306 LOG_DEBUG("UNIMPLEMENTED %s flush_timeout:%d", __func__, flush_timeout);
307 }
OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level)308 void Link::OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) {
309 LOG_DEBUG("UNIMPLEMENTED %s transmit_power_level:%d", __func__, transmit_power_level);
310 }
OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout)311 void Link::OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout) {
312 LOG_DEBUG("UNIMPLEMENTED %s link_supervision_timeout:%d", __func__, link_supervision_timeout);
313 }
OnReadFailedContactCounterComplete(uint16_t failed_contact_counter)314 void Link::OnReadFailedContactCounterComplete(uint16_t failed_contact_counter) {
315 LOG_DEBUG("UNIMPLEMENTED %sfailed_contact_counter:%hu", __func__, failed_contact_counter);
316 }
OnReadLinkQualityComplete(uint8_t link_quality)317 void Link::OnReadLinkQualityComplete(uint8_t link_quality) {
318 LOG_DEBUG("UNIMPLEMENTED %s link_quality:%hhu", __func__, link_quality);
319 }
OnReadAfhChannelMapComplete(hci::AfhMode afh_mode,std::array<uint8_t,10> afh_channel_map)320 void Link::OnReadAfhChannelMapComplete(hci::AfhMode afh_mode, std::array<uint8_t, 10> afh_channel_map) {
321 LOG_DEBUG("UNIMPLEMENTED %s afh_mode:%s", __func__, hci::AfhModeText(afh_mode).c_str());
322 }
OnReadRssiComplete(uint8_t rssi)323 void Link::OnReadRssiComplete(uint8_t rssi) {
324 LOG_DEBUG("UNIMPLEMENTED %s rssi:%hhd", __func__, rssi);
325 }
OnReadClockComplete(uint32_t clock,uint16_t accuracy)326 void Link::OnReadClockComplete(uint32_t clock, uint16_t accuracy) {
327 LOG_DEBUG("UNIMPLEMENTED %s clock:%u accuracy:%hu", __func__, clock, accuracy);
328 }
329
330 } // namespace internal
331 } // namespace classic
332 } // namespace l2cap
333 } // namespace bluetooth
334