1 /*
2  * Copyright 2017 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 "link_layer_controller.h"
18 #include <hci/hci_packets.h>
19 
20 #include "include/le_advertisement.h"
21 #include "os/log.h"
22 #include "packet/raw_builder.h"
23 
24 using std::vector;
25 using namespace std::chrono;
26 using bluetooth::hci::Address;
27 using bluetooth::hci::AddressType;
28 using bluetooth::hci::AddressWithType;
29 
30 namespace test_vendor_lib {
31 
32 constexpr uint16_t kNumCommandPackets = 0x01;
33 
34 // TODO: Model Rssi?
GetRssi()35 static uint8_t GetRssi() {
36   static uint8_t rssi = 0;
37   rssi += 5;
38   if (rssi > 128) {
39     rssi = rssi % 7;
40   }
41   return -(rssi);
42 }
43 
SendLeLinkLayerPacket(std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet)44 void LinkLayerController::SendLeLinkLayerPacket(
45     std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet) {
46   std::shared_ptr<model::packets::LinkLayerPacketBuilder> shared_packet =
47       std::move(packet);
48   ScheduleTask(milliseconds(50), [this, shared_packet]() {
49     send_to_remote_(std::move(shared_packet), Phy::Type::LOW_ENERGY);
50   });
51 }
52 
SendLinkLayerPacket(std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet)53 void LinkLayerController::SendLinkLayerPacket(
54     std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet) {
55   std::shared_ptr<model::packets::LinkLayerPacketBuilder> shared_packet =
56       std::move(packet);
57   ScheduleTask(milliseconds(50), [this, shared_packet]() {
58     send_to_remote_(std::move(shared_packet), Phy::Type::BR_EDR);
59   });
60 }
61 
SendCommandToRemoteByAddress(OpCode opcode,bluetooth::packet::PacketView<true> args,const Address & remote)62 ErrorCode LinkLayerController::SendCommandToRemoteByAddress(
63     OpCode opcode, bluetooth::packet::PacketView<true> args,
64     const Address& remote) {
65   Address local_address = properties_.GetAddress();
66 
67   switch (opcode) {
68     case (OpCode::REMOTE_NAME_REQUEST):
69       // LMP features get requested with remote name requests.
70       SendLinkLayerPacket(model::packets::ReadRemoteLmpFeaturesBuilder::Create(
71           local_address, remote));
72       SendLinkLayerPacket(model::packets::RemoteNameRequestBuilder::Create(
73           local_address, remote));
74       break;
75     case (OpCode::READ_REMOTE_SUPPORTED_FEATURES):
76       SendLinkLayerPacket(
77           model::packets::ReadRemoteSupportedFeaturesBuilder::Create(
78               local_address, remote));
79       break;
80     case (OpCode::READ_REMOTE_EXTENDED_FEATURES): {
81       uint8_t page_number =
82           (args.begin() + 2).extract<uint8_t>();  // skip the handle
83       SendLinkLayerPacket(
84           model::packets::ReadRemoteExtendedFeaturesBuilder::Create(
85               local_address, remote, page_number));
86     } break;
87     case (OpCode::READ_REMOTE_VERSION_INFORMATION):
88       SendLinkLayerPacket(
89           model::packets::ReadRemoteVersionInformationBuilder::Create(
90               local_address, remote));
91       break;
92     case (OpCode::READ_CLOCK_OFFSET):
93       SendLinkLayerPacket(model::packets::ReadClockOffsetBuilder::Create(
94           local_address, remote));
95       break;
96     default:
97       LOG_INFO("Dropping unhandled command 0x%04x",
98                static_cast<uint16_t>(opcode));
99       return ErrorCode::UNKNOWN_HCI_COMMAND;
100   }
101 
102   return ErrorCode::SUCCESS;
103 }
104 
SendCommandToRemoteByHandle(OpCode opcode,bluetooth::packet::PacketView<true> args,uint16_t handle)105 ErrorCode LinkLayerController::SendCommandToRemoteByHandle(
106     OpCode opcode, bluetooth::packet::PacketView<true> args, uint16_t handle) {
107   // TODO: Handle LE connections
108   if (!connections_.HasHandle(handle)) {
109     return ErrorCode::UNKNOWN_CONNECTION;
110   }
111   return SendCommandToRemoteByAddress(
112       opcode, args, connections_.GetAddress(handle).GetAddress());
113 }
114 
SendAclToRemote(bluetooth::hci::AclPacketView acl_packet)115 ErrorCode LinkLayerController::SendAclToRemote(
116     bluetooth::hci::AclPacketView acl_packet) {
117   uint16_t handle = acl_packet.GetHandle();
118   if (!connections_.HasHandle(handle)) {
119     return ErrorCode::UNKNOWN_CONNECTION;
120   }
121 
122   AddressWithType my_address = connections_.GetOwnAddress(handle);
123   AddressWithType destination = connections_.GetAddress(handle);
124   Phy::Type phy = connections_.GetPhyType(handle);
125 
126   ScheduleTask(milliseconds(1), [this, handle]() {
127     std::vector<bluetooth::hci::CompletedPackets> completed_packets;
128     bluetooth::hci::CompletedPackets cp;
129     cp.connection_handle_ = handle;
130     cp.host_num_of_completed_packets_ = kNumCommandPackets;
131     completed_packets.push_back(cp);
132     auto packet = bluetooth::hci::NumberOfCompletedPacketsBuilder::Create(
133         completed_packets);
134     send_event_(std::move(packet));
135   });
136 
137   auto acl_payload = acl_packet.GetPayload();
138 
139   std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
140       std::make_unique<bluetooth::packet::RawBuilder>();
141   std::vector<uint8_t> payload_bytes(acl_payload.begin(), acl_payload.end());
142 
143   uint16_t first_two_bytes =
144       static_cast<uint16_t>(acl_packet.GetHandle()) +
145       (static_cast<uint16_t>(acl_packet.GetPacketBoundaryFlag()) << 12) +
146       (static_cast<uint16_t>(acl_packet.GetBroadcastFlag()) << 14);
147   raw_builder_ptr->AddOctets2(first_two_bytes);
148   raw_builder_ptr->AddOctets2(static_cast<uint16_t>(payload_bytes.size()));
149   raw_builder_ptr->AddOctets(payload_bytes);
150 
151   auto acl = model::packets::AclPacketBuilder::Create(
152       my_address.GetAddress(), destination.GetAddress(),
153       std::move(raw_builder_ptr));
154 
155   switch (phy) {
156     case Phy::Type::BR_EDR:
157       SendLinkLayerPacket(std::move(acl));
158       break;
159     case Phy::Type::LOW_ENERGY:
160       SendLeLinkLayerPacket(std::move(acl));
161       break;
162   }
163   return ErrorCode::SUCCESS;
164 }
165 
IncomingPacket(model::packets::LinkLayerPacketView incoming)166 void LinkLayerController::IncomingPacket(
167     model::packets::LinkLayerPacketView incoming) {
168   ASSERT(incoming.IsValid());
169   auto destination_address = incoming.GetDestinationAddress();
170 
171   // Match broadcasts
172   bool address_matches = (destination_address == Address::kEmpty);
173 
174   // Match addresses from device properties
175   if (destination_address == properties_.GetAddress() ||
176       destination_address == properties_.GetLeAddress()) {
177     address_matches = true;
178   }
179 
180   // Check advertising addresses
181   for (const auto& advertiser : advertisers_) {
182     if (advertiser.IsEnabled() &&
183         advertiser.GetAddress().GetAddress() == destination_address) {
184       address_matches = true;
185     }
186   }
187 
188   // Drop packets not addressed to me
189   if (!address_matches) {
190     return;
191   }
192 
193   switch (incoming.GetType()) {
194     case model::packets::PacketType::ACL:
195       IncomingAclPacket(incoming);
196       break;
197     case model::packets::PacketType::DISCONNECT:
198       IncomingDisconnectPacket(incoming);
199       break;
200     case model::packets::PacketType::ENCRYPT_CONNECTION:
201       IncomingEncryptConnection(incoming);
202       break;
203     case model::packets::PacketType::ENCRYPT_CONNECTION_RESPONSE:
204       IncomingEncryptConnectionResponse(incoming);
205       break;
206     case model::packets::PacketType::INQUIRY:
207       if (inquiry_scans_enabled_) {
208         IncomingInquiryPacket(incoming);
209       }
210       break;
211     case model::packets::PacketType::INQUIRY_RESPONSE:
212       IncomingInquiryResponsePacket(incoming);
213       break;
214     case model::packets::PacketType::IO_CAPABILITY_REQUEST:
215       IncomingIoCapabilityRequestPacket(incoming);
216       break;
217     case model::packets::PacketType::IO_CAPABILITY_RESPONSE:
218       IncomingIoCapabilityResponsePacket(incoming);
219       break;
220     case model::packets::PacketType::IO_CAPABILITY_NEGATIVE_RESPONSE:
221       IncomingIoCapabilityNegativeResponsePacket(incoming);
222       break;
223     case model::packets::PacketType::LE_ADVERTISEMENT:
224       if (le_scan_enable_ != bluetooth::hci::OpCode::NONE || le_connect_) {
225         IncomingLeAdvertisementPacket(incoming);
226       }
227       break;
228     case model::packets::PacketType::LE_CONNECT:
229       IncomingLeConnectPacket(incoming);
230       break;
231     case model::packets::PacketType::LE_CONNECT_COMPLETE:
232       IncomingLeConnectCompletePacket(incoming);
233       break;
234     case model::packets::PacketType::LE_ENCRYPT_CONNECTION:
235       IncomingLeEncryptConnection(incoming);
236       break;
237     case model::packets::PacketType::LE_ENCRYPT_CONNECTION_RESPONSE:
238       IncomingLeEncryptConnectionResponse(incoming);
239       break;
240     case model::packets::PacketType::LE_SCAN:
241       // TODO: Check Advertising flags and see if we are scannable.
242       IncomingLeScanPacket(incoming);
243       break;
244     case model::packets::PacketType::LE_SCAN_RESPONSE:
245       if (le_scan_enable_ != bluetooth::hci::OpCode::NONE &&
246           le_scan_type_ == 1) {
247         IncomingLeScanResponsePacket(incoming);
248       }
249       break;
250     case model::packets::PacketType::PAGE:
251       if (page_scans_enabled_) {
252         IncomingPagePacket(incoming);
253       }
254       break;
255     case model::packets::PacketType::PAGE_RESPONSE:
256       IncomingPageResponsePacket(incoming);
257       break;
258     case model::packets::PacketType::PAGE_REJECT:
259       IncomingPageRejectPacket(incoming);
260       break;
261     case (model::packets::PacketType::REMOTE_NAME_REQUEST):
262       IncomingRemoteNameRequest(incoming);
263       break;
264     case (model::packets::PacketType::REMOTE_NAME_REQUEST_RESPONSE):
265       IncomingRemoteNameRequestResponse(incoming);
266       break;
267     case (model::packets::PacketType::READ_REMOTE_SUPPORTED_FEATURES):
268       IncomingReadRemoteSupportedFeatures(incoming);
269       break;
270     case (model::packets::PacketType::READ_REMOTE_SUPPORTED_FEATURES_RESPONSE):
271       IncomingReadRemoteSupportedFeaturesResponse(incoming);
272       break;
273     case (model::packets::PacketType::READ_REMOTE_LMP_FEATURES):
274       IncomingReadRemoteLmpFeatures(incoming);
275       break;
276     case (model::packets::PacketType::READ_REMOTE_LMP_FEATURES_RESPONSE):
277       IncomingReadRemoteLmpFeaturesResponse(incoming);
278       break;
279     case (model::packets::PacketType::READ_REMOTE_EXTENDED_FEATURES):
280       IncomingReadRemoteExtendedFeatures(incoming);
281       break;
282     case (model::packets::PacketType::READ_REMOTE_EXTENDED_FEATURES_RESPONSE):
283       IncomingReadRemoteExtendedFeaturesResponse(incoming);
284       break;
285     case (model::packets::PacketType::READ_REMOTE_VERSION_INFORMATION):
286       IncomingReadRemoteVersion(incoming);
287       break;
288     case (model::packets::PacketType::READ_REMOTE_VERSION_INFORMATION_RESPONSE):
289       IncomingReadRemoteVersionResponse(incoming);
290       break;
291     case (model::packets::PacketType::READ_CLOCK_OFFSET):
292       IncomingReadClockOffset(incoming);
293       break;
294     case (model::packets::PacketType::READ_CLOCK_OFFSET_RESPONSE):
295       IncomingReadClockOffsetResponse(incoming);
296       break;
297     default:
298       LOG_WARN("Dropping unhandled packet of type %s",
299                model::packets::PacketTypeText(incoming.GetType()).c_str());
300   }
301 }
302 
IncomingAclPacket(model::packets::LinkLayerPacketView incoming)303 void LinkLayerController::IncomingAclPacket(
304     model::packets::LinkLayerPacketView incoming) {
305   LOG_INFO("Acl Packet %s -> %s",
306            incoming.GetSourceAddress().ToString().c_str(),
307            incoming.GetDestinationAddress().ToString().c_str());
308 
309   auto acl = model::packets::AclPacketView::Create(incoming);
310   ASSERT(acl.IsValid());
311   auto payload = acl.GetPayload();
312   std::shared_ptr<std::vector<uint8_t>> payload_bytes =
313       std::make_shared<std::vector<uint8_t>>(payload.begin(), payload.end());
314 
315   bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian> raw_packet(
316       payload_bytes);
317   auto acl_view = bluetooth::hci::AclPacketView::Create(raw_packet);
318   ASSERT(acl_view.IsValid());
319 
320   LOG_INFO("Remote handle 0x%x size %d", acl_view.GetHandle(),
321            static_cast<int>(acl_view.size()));
322   uint16_t local_handle =
323       connections_.GetHandleOnlyAddress(incoming.GetSourceAddress());
324   LOG_INFO("Local handle 0x%x", local_handle);
325 
326   std::vector<uint8_t> payload_data(acl_view.GetPayload().begin(),
327                                     acl_view.GetPayload().end());
328   uint16_t acl_buffer_size = properties_.GetAclDataPacketSize();
329   int num_packets =
330       (payload_data.size() + acl_buffer_size - 1) / acl_buffer_size;
331 
332   auto pb_flag_controller_to_host = acl_view.GetPacketBoundaryFlag();
333   if (pb_flag_controller_to_host ==
334       bluetooth::hci::PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE) {
335     pb_flag_controller_to_host =
336         bluetooth::hci::PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
337   }
338   for (int i = 0; i < num_packets; i++) {
339     size_t start_index = acl_buffer_size * i;
340     size_t end_index =
341         std::min(start_index + acl_buffer_size, payload_data.size());
342     std::vector<uint8_t> fragment(&payload_data[start_index],
343                                   &payload_data[end_index]);
344     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
345         std::make_unique<bluetooth::packet::RawBuilder>(fragment);
346     auto acl_packet = bluetooth::hci::AclPacketBuilder::Create(
347         local_handle, pb_flag_controller_to_host, acl_view.GetBroadcastFlag(),
348         std::move(raw_builder_ptr));
349     pb_flag_controller_to_host =
350         bluetooth::hci::PacketBoundaryFlag::CONTINUING_FRAGMENT;
351 
352     send_acl_(std::move(acl_packet));
353   }
354 }
355 
IncomingRemoteNameRequest(model::packets::LinkLayerPacketView packet)356 void LinkLayerController::IncomingRemoteNameRequest(
357     model::packets::LinkLayerPacketView packet) {
358   auto view = model::packets::RemoteNameRequestView::Create(packet);
359   ASSERT(view.IsValid());
360 
361   SendLinkLayerPacket(model::packets::RemoteNameRequestResponseBuilder::Create(
362       packet.GetDestinationAddress(), packet.GetSourceAddress(),
363       properties_.GetName()));
364 }
365 
IncomingRemoteNameRequestResponse(model::packets::LinkLayerPacketView packet)366 void LinkLayerController::IncomingRemoteNameRequestResponse(
367     model::packets::LinkLayerPacketView packet) {
368   auto view = model::packets::RemoteNameRequestResponseView::Create(packet);
369   ASSERT(view.IsValid());
370 
371   send_event_(bluetooth::hci::RemoteNameRequestCompleteBuilder::Create(
372       ErrorCode::SUCCESS, packet.GetSourceAddress(), view.GetName()));
373 }
374 
IncomingReadRemoteLmpFeatures(model::packets::LinkLayerPacketView packet)375 void LinkLayerController::IncomingReadRemoteLmpFeatures(
376     model::packets::LinkLayerPacketView packet) {
377   SendLinkLayerPacket(
378       model::packets::ReadRemoteLmpFeaturesResponseBuilder::Create(
379           packet.GetDestinationAddress(), packet.GetSourceAddress(),
380           properties_.GetExtendedFeatures(1)));
381 }
382 
IncomingReadRemoteLmpFeaturesResponse(model::packets::LinkLayerPacketView packet)383 void LinkLayerController::IncomingReadRemoteLmpFeaturesResponse(
384     model::packets::LinkLayerPacketView packet) {
385   auto view = model::packets::ReadRemoteLmpFeaturesResponseView::Create(packet);
386   ASSERT(view.IsValid());
387   send_event_(
388       bluetooth::hci::RemoteHostSupportedFeaturesNotificationBuilder::Create(
389           packet.GetSourceAddress(), view.GetFeatures()));
390 }
391 
IncomingReadRemoteSupportedFeatures(model::packets::LinkLayerPacketView packet)392 void LinkLayerController::IncomingReadRemoteSupportedFeatures(
393     model::packets::LinkLayerPacketView packet) {
394   SendLinkLayerPacket(
395       model::packets::ReadRemoteSupportedFeaturesResponseBuilder::Create(
396           packet.GetDestinationAddress(), packet.GetSourceAddress(),
397           properties_.GetSupportedFeatures()));
398 }
399 
IncomingReadRemoteSupportedFeaturesResponse(model::packets::LinkLayerPacketView packet)400 void LinkLayerController::IncomingReadRemoteSupportedFeaturesResponse(
401     model::packets::LinkLayerPacketView packet) {
402   auto view =
403       model::packets::ReadRemoteSupportedFeaturesResponseView::Create(packet);
404   ASSERT(view.IsValid());
405   Address source = packet.GetSourceAddress();
406   uint16_t handle = connections_.GetHandleOnlyAddress(source);
407   if (handle == acl::kReservedHandle) {
408     LOG_INFO("Discarding response from a disconnected device %s",
409              source.ToString().c_str());
410     return;
411   }
412   send_event_(
413       bluetooth::hci::ReadRemoteSupportedFeaturesCompleteBuilder::Create(
414           ErrorCode::SUCCESS, handle, view.GetFeatures()));
415 }
416 
IncomingReadRemoteExtendedFeatures(model::packets::LinkLayerPacketView packet)417 void LinkLayerController::IncomingReadRemoteExtendedFeatures(
418     model::packets::LinkLayerPacketView packet) {
419   auto view = model::packets::ReadRemoteExtendedFeaturesView::Create(packet);
420   ASSERT(view.IsValid());
421   uint8_t page_number = view.GetPageNumber();
422   uint8_t error_code = static_cast<uint8_t>(ErrorCode::SUCCESS);
423   if (page_number > properties_.GetExtendedFeaturesMaximumPageNumber()) {
424     error_code = static_cast<uint8_t>(ErrorCode::INVALID_LMP_OR_LL_PARAMETERS);
425   }
426   SendLinkLayerPacket(
427       model::packets::ReadRemoteExtendedFeaturesResponseBuilder::Create(
428           packet.GetDestinationAddress(), packet.GetSourceAddress(), error_code,
429           page_number, properties_.GetExtendedFeaturesMaximumPageNumber(),
430           properties_.GetExtendedFeatures(view.GetPageNumber())));
431 }
432 
IncomingReadRemoteExtendedFeaturesResponse(model::packets::LinkLayerPacketView packet)433 void LinkLayerController::IncomingReadRemoteExtendedFeaturesResponse(
434     model::packets::LinkLayerPacketView packet) {
435   auto view =
436       model::packets::ReadRemoteExtendedFeaturesResponseView::Create(packet);
437   ASSERT(view.IsValid());
438   Address source = packet.GetSourceAddress();
439   uint16_t handle = connections_.GetHandleOnlyAddress(source);
440   if (handle == acl::kReservedHandle) {
441     LOG_INFO("Discarding response from a disconnected device %s",
442              source.ToString().c_str());
443     return;
444   }
445   send_event_(bluetooth::hci::ReadRemoteExtendedFeaturesCompleteBuilder::Create(
446       static_cast<ErrorCode>(view.GetStatus()), handle, view.GetPageNumber(),
447       view.GetMaxPageNumber(), view.GetFeatures()));
448 }
449 
IncomingReadRemoteVersion(model::packets::LinkLayerPacketView packet)450 void LinkLayerController::IncomingReadRemoteVersion(
451     model::packets::LinkLayerPacketView packet) {
452   SendLinkLayerPacket(
453       model::packets::ReadRemoteSupportedFeaturesResponseBuilder::Create(
454           packet.GetDestinationAddress(), packet.GetSourceAddress(),
455           properties_.GetSupportedFeatures()));
456 }
457 
IncomingReadRemoteVersionResponse(model::packets::LinkLayerPacketView packet)458 void LinkLayerController::IncomingReadRemoteVersionResponse(
459     model::packets::LinkLayerPacketView packet) {
460   auto view =
461       model::packets::ReadRemoteVersionInformationResponseView::Create(packet);
462   ASSERT(view.IsValid());
463   Address source = packet.GetSourceAddress();
464   uint16_t handle = connections_.GetHandleOnlyAddress(source);
465   if (handle == acl::kReservedHandle) {
466     LOG_INFO("Discarding response from a disconnected device %s",
467              source.ToString().c_str());
468     return;
469   }
470   send_event_(
471       bluetooth::hci::ReadRemoteVersionInformationCompleteBuilder::Create(
472           ErrorCode::SUCCESS, handle, view.GetLmpVersion(),
473           view.GetManufacturerName(), view.GetLmpSubversion()));
474 }
475 
IncomingReadClockOffset(model::packets::LinkLayerPacketView packet)476 void LinkLayerController::IncomingReadClockOffset(
477     model::packets::LinkLayerPacketView packet) {
478   SendLinkLayerPacket(model::packets::ReadClockOffsetResponseBuilder::Create(
479       packet.GetDestinationAddress(), packet.GetSourceAddress(),
480       properties_.GetClockOffset()));
481 }
482 
IncomingReadClockOffsetResponse(model::packets::LinkLayerPacketView packet)483 void LinkLayerController::IncomingReadClockOffsetResponse(
484     model::packets::LinkLayerPacketView packet) {
485   auto view = model::packets::ReadClockOffsetResponseView::Create(packet);
486   ASSERT(view.IsValid());
487   Address source = packet.GetSourceAddress();
488   uint16_t handle = connections_.GetHandleOnlyAddress(source);
489   if (handle == acl::kReservedHandle) {
490     LOG_INFO("Discarding response from a disconnected device %s",
491              source.ToString().c_str());
492     return;
493   }
494   send_event_(bluetooth::hci::ReadClockOffsetCompleteBuilder::Create(
495       ErrorCode::SUCCESS, handle, view.GetOffset()));
496 }
497 
IncomingDisconnectPacket(model::packets::LinkLayerPacketView incoming)498 void LinkLayerController::IncomingDisconnectPacket(
499     model::packets::LinkLayerPacketView incoming) {
500   LOG_INFO("Disconnect Packet");
501   auto disconnect = model::packets::DisconnectView::Create(incoming);
502   ASSERT(disconnect.IsValid());
503 
504   Address peer = incoming.GetSourceAddress();
505   uint16_t handle = connections_.GetHandleOnlyAddress(peer);
506   if (handle == acl::kReservedHandle) {
507     LOG_INFO("Discarding disconnect from a disconnected device %s",
508              peer.ToString().c_str());
509     return;
510   }
511   ASSERT_LOG(connections_.Disconnect(handle),
512              "GetHandle() returned invalid handle %hx", handle);
513 
514   uint8_t reason = disconnect.GetReason();
515   ScheduleTask(milliseconds(20),
516                [this, handle, reason]() { DisconnectCleanup(handle, reason); });
517 }
518 
IncomingEncryptConnection(model::packets::LinkLayerPacketView incoming)519 void LinkLayerController::IncomingEncryptConnection(
520     model::packets::LinkLayerPacketView incoming) {
521   LOG_INFO();
522 
523   // TODO: Check keys
524   Address peer = incoming.GetSourceAddress();
525   uint16_t handle = connections_.GetHandleOnlyAddress(peer);
526   if (handle == acl::kReservedHandle) {
527     LOG_INFO("Unknown connection @%s", peer.ToString().c_str());
528     return;
529   }
530   send_event_(bluetooth::hci::EncryptionChangeBuilder::Create(
531       ErrorCode::SUCCESS, handle, bluetooth::hci::EncryptionEnabled::ON));
532 
533   uint16_t count = security_manager_.ReadKey(peer);
534   if (count == 0) {
535     LOG_ERROR("NO KEY HERE for %s", peer.ToString().c_str());
536     return;
537   }
538   auto array = security_manager_.GetKey(peer);
539   std::vector<uint8_t> key_vec{array.begin(), array.end()};
540   auto response = model::packets::EncryptConnectionResponseBuilder::Create(
541       properties_.GetAddress(), peer, key_vec);
542   SendLinkLayerPacket(std::move(response));
543 }
544 
IncomingEncryptConnectionResponse(model::packets::LinkLayerPacketView incoming)545 void LinkLayerController::IncomingEncryptConnectionResponse(
546     model::packets::LinkLayerPacketView incoming) {
547   LOG_INFO();
548   // TODO: Check keys
549   uint16_t handle =
550       connections_.GetHandleOnlyAddress(incoming.GetSourceAddress());
551   if (handle == acl::kReservedHandle) {
552     LOG_INFO("Unknown connection @%s",
553              incoming.GetSourceAddress().ToString().c_str());
554     return;
555   }
556   auto packet = bluetooth::hci::EncryptionChangeBuilder::Create(
557       ErrorCode::SUCCESS, handle, bluetooth::hci::EncryptionEnabled::ON);
558   send_event_(std::move(packet));
559 }
560 
IncomingInquiryPacket(model::packets::LinkLayerPacketView incoming)561 void LinkLayerController::IncomingInquiryPacket(
562     model::packets::LinkLayerPacketView incoming) {
563   auto inquiry = model::packets::InquiryView::Create(incoming);
564   ASSERT(inquiry.IsValid());
565 
566   Address peer = incoming.GetSourceAddress();
567 
568   switch (inquiry.GetInquiryType()) {
569     case (model::packets::InquiryType::STANDARD): {
570       auto inquiry_response = model::packets::InquiryResponseBuilder::Create(
571           properties_.GetAddress(), peer,
572           properties_.GetPageScanRepetitionMode(),
573           properties_.GetClassOfDevice(), properties_.GetClockOffset());
574       SendLinkLayerPacket(std::move(inquiry_response));
575     } break;
576     case (model::packets::InquiryType::RSSI): {
577       auto inquiry_response =
578           model::packets::InquiryResponseWithRssiBuilder::Create(
579               properties_.GetAddress(), peer,
580               properties_.GetPageScanRepetitionMode(),
581               properties_.GetClassOfDevice(), properties_.GetClockOffset(),
582               GetRssi());
583       SendLinkLayerPacket(std::move(inquiry_response));
584     } break;
585     case (model::packets::InquiryType::EXTENDED): {
586       auto inquiry_response =
587           model::packets::ExtendedInquiryResponseBuilder::Create(
588               properties_.GetAddress(), peer,
589               properties_.GetPageScanRepetitionMode(),
590               properties_.GetClassOfDevice(), properties_.GetClockOffset(),
591               GetRssi(), properties_.GetExtendedInquiryData());
592       SendLinkLayerPacket(std::move(inquiry_response));
593 
594     } break;
595     default:
596       LOG_WARN("Unhandled Incoming Inquiry of type %d",
597                static_cast<int>(inquiry.GetType()));
598       return;
599   }
600   // TODO: Send an Inquiry Response Notification Event 7.7.74
601 }
602 
IncomingInquiryResponsePacket(model::packets::LinkLayerPacketView incoming)603 void LinkLayerController::IncomingInquiryResponsePacket(
604     model::packets::LinkLayerPacketView incoming) {
605   auto basic_inquiry_response =
606       model::packets::BasicInquiryResponseView::Create(incoming);
607   ASSERT(basic_inquiry_response.IsValid());
608   std::vector<uint8_t> eir;
609 
610   switch (basic_inquiry_response.GetInquiryType()) {
611     case (model::packets::InquiryType::STANDARD): {
612       // TODO: Support multiple inquiries in the same packet.
613       auto inquiry_response =
614           model::packets::InquiryResponseView::Create(basic_inquiry_response);
615       ASSERT(inquiry_response.IsValid());
616 
617       auto page_scan_repetition_mode =
618           (bluetooth::hci::PageScanRepetitionMode)
619               inquiry_response.GetPageScanRepetitionMode();
620 
621       std::vector<bluetooth::hci::InquiryResult> responses;
622       responses.emplace_back();
623       responses.back().bd_addr_ = inquiry_response.GetSourceAddress();
624       responses.back().page_scan_repetition_mode_ = page_scan_repetition_mode;
625       responses.back().class_of_device_ = inquiry_response.GetClassOfDevice();
626       responses.back().clock_offset_ = inquiry_response.GetClockOffset();
627       auto packet = bluetooth::hci::InquiryResultBuilder::Create(responses);
628       send_event_(std::move(packet));
629     } break;
630 
631     case (model::packets::InquiryType::RSSI): {
632       auto inquiry_response =
633           model::packets::InquiryResponseWithRssiView::Create(
634               basic_inquiry_response);
635       ASSERT(inquiry_response.IsValid());
636 
637       auto page_scan_repetition_mode =
638           (bluetooth::hci::PageScanRepetitionMode)
639               inquiry_response.GetPageScanRepetitionMode();
640 
641       std::vector<bluetooth::hci::InquiryResultWithRssi> responses;
642       responses.emplace_back();
643       responses.back().address_ = inquiry_response.GetSourceAddress();
644       responses.back().page_scan_repetition_mode_ = page_scan_repetition_mode;
645       responses.back().class_of_device_ = inquiry_response.GetClassOfDevice();
646       responses.back().clock_offset_ = inquiry_response.GetClockOffset();
647       responses.back().rssi_ = inquiry_response.GetRssi();
648       auto packet =
649           bluetooth::hci::InquiryResultWithRssiBuilder::Create(responses);
650       send_event_(std::move(packet));
651     } break;
652 
653     case (model::packets::InquiryType::EXTENDED): {
654       auto inquiry_response =
655           model::packets::ExtendedInquiryResponseView::Create(
656               basic_inquiry_response);
657       ASSERT(inquiry_response.IsValid());
658 
659       std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
660           std::make_unique<bluetooth::packet::RawBuilder>();
661       raw_builder_ptr->AddOctets1(kNumCommandPackets);
662       raw_builder_ptr->AddAddress(inquiry_response.GetSourceAddress());
663       raw_builder_ptr->AddOctets1(inquiry_response.GetPageScanRepetitionMode());
664       raw_builder_ptr->AddOctets1(0x00);  // _reserved_
665       auto class_of_device = inquiry_response.GetClassOfDevice();
666       for (unsigned int i = 0; i < class_of_device.kLength; i++) {
667         raw_builder_ptr->AddOctets1(class_of_device.cod[i]);
668       }
669       raw_builder_ptr->AddOctets2(inquiry_response.GetClockOffset());
670       raw_builder_ptr->AddOctets1(inquiry_response.GetRssi());
671       raw_builder_ptr->AddOctets(inquiry_response.GetExtendedData());
672 
673       auto packet = bluetooth::hci::EventPacketBuilder::Create(
674           bluetooth::hci::EventCode::EXTENDED_INQUIRY_RESULT,
675           std::move(raw_builder_ptr));
676       send_event_(std::move(packet));
677     } break;
678     default:
679       LOG_WARN("Unhandled Incoming Inquiry Response of type %d",
680                static_cast<int>(basic_inquiry_response.GetInquiryType()));
681   }
682 }
683 
IncomingIoCapabilityRequestPacket(model::packets::LinkLayerPacketView incoming)684 void LinkLayerController::IncomingIoCapabilityRequestPacket(
685     model::packets::LinkLayerPacketView incoming) {
686   LOG_DEBUG();
687   if (!simple_pairing_mode_enabled_) {
688     LOG_WARN("Only simple pairing mode is implemented");
689     return;
690   }
691 
692   auto request = model::packets::IoCapabilityRequestView::Create(incoming);
693   ASSERT(request.IsValid());
694 
695   Address peer = incoming.GetSourceAddress();
696   uint8_t io_capability = request.GetIoCapability();
697   uint8_t oob_data_present = request.GetOobDataPresent();
698   uint8_t authentication_requirements = request.GetAuthenticationRequirements();
699 
700   uint16_t handle = connections_.GetHandle(AddressWithType(
701       peer, bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS));
702   if (handle == acl::kReservedHandle) {
703     LOG_INFO("Device not connected %s", peer.ToString().c_str());
704     return;
705   }
706 
707   security_manager_.AuthenticationRequest(peer, handle);
708 
709   security_manager_.SetPeerIoCapability(peer, io_capability, oob_data_present,
710                                         authentication_requirements);
711 
712   auto packet = bluetooth::hci::IoCapabilityResponseBuilder::Create(
713       peer, static_cast<bluetooth::hci::IoCapability>(io_capability),
714       static_cast<bluetooth::hci::OobDataPresent>(oob_data_present),
715       static_cast<bluetooth::hci::AuthenticationRequirements>(
716           authentication_requirements));
717   send_event_(std::move(packet));
718 
719   StartSimplePairing(peer);
720 }
721 
IncomingIoCapabilityResponsePacket(model::packets::LinkLayerPacketView incoming)722 void LinkLayerController::IncomingIoCapabilityResponsePacket(
723     model::packets::LinkLayerPacketView incoming) {
724   LOG_DEBUG();
725 
726   auto response = model::packets::IoCapabilityResponseView::Create(incoming);
727   ASSERT(response.IsValid());
728 
729   Address peer = incoming.GetSourceAddress();
730   uint8_t io_capability = response.GetIoCapability();
731   uint8_t oob_data_present = response.GetOobDataPresent();
732   uint8_t authentication_requirements =
733       response.GetAuthenticationRequirements();
734 
735   security_manager_.SetPeerIoCapability(peer, io_capability, oob_data_present,
736                                         authentication_requirements);
737 
738   auto packet = bluetooth::hci::IoCapabilityResponseBuilder::Create(
739       peer, static_cast<bluetooth::hci::IoCapability>(io_capability),
740       static_cast<bluetooth::hci::OobDataPresent>(oob_data_present),
741       static_cast<bluetooth::hci::AuthenticationRequirements>(
742           authentication_requirements));
743   send_event_(std::move(packet));
744 
745   PairingType pairing_type = security_manager_.GetSimplePairingType();
746   if (pairing_type != PairingType::INVALID) {
747     ScheduleTask(milliseconds(5), [this, peer, pairing_type]() {
748       AuthenticateRemoteStage1(peer, pairing_type);
749     });
750   } else {
751     LOG_INFO("Security Manager returned INVALID");
752   }
753 }
754 
IncomingIoCapabilityNegativeResponsePacket(model::packets::LinkLayerPacketView incoming)755 void LinkLayerController::IncomingIoCapabilityNegativeResponsePacket(
756     model::packets::LinkLayerPacketView incoming) {
757   LOG_DEBUG();
758   Address peer = incoming.GetSourceAddress();
759 
760   ASSERT(security_manager_.GetAuthenticationAddress() == peer);
761 
762   security_manager_.InvalidateIoCapabilities();
763 }
764 
IncomingLeAdvertisementPacket(model::packets::LinkLayerPacketView incoming)765 void LinkLayerController::IncomingLeAdvertisementPacket(
766     model::packets::LinkLayerPacketView incoming) {
767   // TODO: Handle multiple advertisements per packet.
768 
769   Address address = incoming.GetSourceAddress();
770   auto advertisement = model::packets::LeAdvertisementView::Create(incoming);
771   ASSERT(advertisement.IsValid());
772   auto address_type = advertisement.GetAddressType();
773   auto adv_type = advertisement.GetAdvertisementType();
774 
775   if (le_scan_enable_ == bluetooth::hci::OpCode::LE_SET_SCAN_ENABLE) {
776     vector<uint8_t> ad = advertisement.GetData();
777 
778     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
779         std::make_unique<bluetooth::packet::RawBuilder>();
780     raw_builder_ptr->AddOctets1(
781         static_cast<uint8_t>(bluetooth::hci::SubeventCode::ADVERTISING_REPORT));
782     raw_builder_ptr->AddOctets1(0x01);  // num reports
783     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(adv_type));
784     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
785     raw_builder_ptr->AddAddress(address);
786     raw_builder_ptr->AddOctets1(ad.size());
787     raw_builder_ptr->AddOctets(ad);
788     raw_builder_ptr->AddOctets1(GetRssi());
789     auto packet = bluetooth::hci::EventPacketBuilder::Create(
790         bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr));
791     send_event_(std::move(packet));
792   }
793 
794   if (le_scan_enable_ == bluetooth::hci::OpCode::LE_SET_EXTENDED_SCAN_ENABLE) {
795     vector<uint8_t> ad = advertisement.GetData();
796 
797     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
798         std::make_unique<bluetooth::packet::RawBuilder>();
799     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(
800         bluetooth::hci::SubeventCode::EXTENDED_ADVERTISING_REPORT));
801     raw_builder_ptr->AddOctets1(0x01);  // num reports
802     switch (adv_type) {
803       case model::packets::AdvertisementType::ADV_IND:
804         raw_builder_ptr->AddOctets1(0x13);
805         break;
806       case model::packets::AdvertisementType::ADV_DIRECT_IND:
807         raw_builder_ptr->AddOctets1(0x15);
808         break;
809       case model::packets::AdvertisementType::ADV_SCAN_IND:
810         raw_builder_ptr->AddOctets1(0x12);
811         break;
812       case model::packets::AdvertisementType::ADV_NONCONN_IND:
813         raw_builder_ptr->AddOctets1(0x10);
814         break;
815       case model::packets::AdvertisementType::SCAN_RESPONSE:
816         raw_builder_ptr->AddOctets1(0x1b);  // 0x1a for ADV_SCAN_IND scan
817         return;
818     }
819     raw_builder_ptr->AddOctets1(0x00);  // Reserved
820     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
821     raw_builder_ptr->AddAddress(address);
822     raw_builder_ptr->AddOctets1(1);     // Primary_PHY
823     raw_builder_ptr->AddOctets1(0);     // Secondary_PHY
824     raw_builder_ptr->AddOctets1(0xFF);  // Advertising_SID - not provided
825     raw_builder_ptr->AddOctets1(0x7F);  // Tx_Power - Not available
826     raw_builder_ptr->AddOctets1(GetRssi());
827     raw_builder_ptr->AddOctets2(0);  // Periodic_Advertising_Interval - None
828     raw_builder_ptr->AddOctets1(0);  // Direct_Address_Type - PUBLIC
829     raw_builder_ptr->AddAddress(Address::kEmpty);  // Direct_Address
830     raw_builder_ptr->AddOctets1(ad.size());
831     raw_builder_ptr->AddOctets(ad);
832     send_event_(bluetooth::hci::EventPacketBuilder::Create(
833         bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr)));
834   }
835 
836   // Active scanning
837   if (le_scan_enable_ != bluetooth::hci::OpCode::NONE && le_scan_type_ == 1) {
838     auto to_send = model::packets::LeScanBuilder::Create(
839         properties_.GetLeAddress(), address);
840     SendLeLinkLayerPacket(std::move(to_send));
841   }
842 
843   // Connect
844   if ((le_connect_ && le_peer_address_ == address &&
845        le_peer_address_type_ == static_cast<uint8_t>(address_type) &&
846        (adv_type == model::packets::AdvertisementType::ADV_IND ||
847         adv_type == model::packets::AdvertisementType::ADV_DIRECT_IND)) ||
848       (LeConnectListContainsDevice(address,
849                                    static_cast<uint8_t>(address_type)))) {
850     if (!connections_.CreatePendingLeConnection(AddressWithType(
851             address, static_cast<bluetooth::hci::AddressType>(address_type)))) {
852       LOG_WARN(
853           "CreatePendingLeConnection failed for connection to %s (type %hhx)",
854           incoming.GetSourceAddress().ToString().c_str(), address_type);
855     }
856     LOG_INFO("Connecting to %s (type %hhx) own_address %s (type %hhx)",
857              incoming.GetSourceAddress().ToString().c_str(), address_type,
858              properties_.GetLeAddress().ToString().c_str(), le_address_type_);
859     le_connect_ = false;
860     le_scan_enable_ = bluetooth::hci::OpCode::NONE;
861 
862     auto to_send = model::packets::LeConnectBuilder::Create(
863         properties_.GetLeAddress(), incoming.GetSourceAddress(),
864         le_connection_interval_min_, le_connection_interval_max_,
865         le_connection_latency_, le_connection_supervision_timeout_,
866         static_cast<uint8_t>(le_address_type_));
867 
868     SendLeLinkLayerPacket(std::move(to_send));
869   }
870 }
871 
HandleLeConnection(AddressWithType address,AddressWithType own_address,uint8_t role,uint16_t connection_interval,uint16_t connection_latency,uint16_t supervision_timeout)872 void LinkLayerController::HandleLeConnection(AddressWithType address,
873                                              AddressWithType own_address,
874                                              uint8_t role,
875                                              uint16_t connection_interval,
876                                              uint16_t connection_latency,
877                                              uint16_t supervision_timeout) {
878   // TODO: Choose between LeConnectionComplete and LeEnhancedConnectionComplete
879   uint16_t handle = connections_.CreateLeConnection(address, own_address);
880   if (handle == acl::kReservedHandle) {
881     LOG_WARN("No pending connection for connection from %s",
882              address.ToString().c_str());
883     return;
884   }
885   auto packet = bluetooth::hci::LeConnectionCompleteBuilder::Create(
886       ErrorCode::SUCCESS, handle, static_cast<bluetooth::hci::Role>(role),
887       address.GetAddressType(), address.GetAddress(), connection_interval,
888       connection_latency, supervision_timeout,
889       static_cast<bluetooth::hci::ClockAccuracy>(0x00));
890   send_event_(std::move(packet));
891 }
892 
IncomingLeConnectPacket(model::packets::LinkLayerPacketView incoming)893 void LinkLayerController::IncomingLeConnectPacket(
894     model::packets::LinkLayerPacketView incoming) {
895   auto connect = model::packets::LeConnectView::Create(incoming);
896   ASSERT(connect.IsValid());
897   uint16_t connection_interval = (connect.GetLeConnectionIntervalMax() +
898                                   connect.GetLeConnectionIntervalMin()) /
899                                  2;
900   if (!connections_.CreatePendingLeConnection(AddressWithType(
901           incoming.GetSourceAddress(), static_cast<bluetooth::hci::AddressType>(
902                                            connect.GetAddressType())))) {
903     LOG_WARN(
904         "CreatePendingLeConnection failed for connection from %s (type "
905         "%hhx)",
906         incoming.GetSourceAddress().ToString().c_str(),
907         connect.GetAddressType());
908     return;
909   }
910   bluetooth::hci::AddressWithType my_address{};
911   bool matched_advertiser = false;
912   for (auto advertiser : advertisers_) {
913     AddressWithType advertiser_address = advertiser.GetAddress();
914     if (incoming.GetDestinationAddress() == advertiser_address.GetAddress()) {
915       my_address = advertiser_address;
916       matched_advertiser = true;
917     }
918   }
919 
920   if (!matched_advertiser) {
921     LOG_INFO("Dropping unmatched connection request to %s",
922              incoming.GetSourceAddress().ToString().c_str());
923     return;
924   }
925 
926   HandleLeConnection(
927       AddressWithType(
928           incoming.GetSourceAddress(),
929           static_cast<bluetooth::hci::AddressType>(connect.GetAddressType())),
930       my_address, static_cast<uint8_t>(bluetooth::hci::Role::SLAVE),
931       connection_interval, connect.GetLeConnectionLatency(),
932       connect.GetLeConnectionSupervisionTimeout());
933 
934   auto to_send = model::packets::LeConnectCompleteBuilder::Create(
935       incoming.GetDestinationAddress(), incoming.GetSourceAddress(),
936       connection_interval, connect.GetLeConnectionLatency(),
937       connect.GetLeConnectionSupervisionTimeout(),
938       static_cast<uint8_t>(my_address.GetAddressType()));
939   SendLeLinkLayerPacket(std::move(to_send));
940 }
941 
IncomingLeConnectCompletePacket(model::packets::LinkLayerPacketView incoming)942 void LinkLayerController::IncomingLeConnectCompletePacket(
943     model::packets::LinkLayerPacketView incoming) {
944   auto complete = model::packets::LeConnectCompleteView::Create(incoming);
945   ASSERT(complete.IsValid());
946   HandleLeConnection(
947       AddressWithType(
948           incoming.GetSourceAddress(),
949           static_cast<bluetooth::hci::AddressType>(complete.GetAddressType())),
950       AddressWithType(
951           incoming.GetDestinationAddress(),
952           static_cast<bluetooth::hci::AddressType>(le_address_type_)),
953       static_cast<uint8_t>(bluetooth::hci::Role::MASTER),
954       complete.GetLeConnectionInterval(), complete.GetLeConnectionLatency(),
955       complete.GetLeConnectionSupervisionTimeout());
956 }
957 
IncomingLeEncryptConnection(model::packets::LinkLayerPacketView incoming)958 void LinkLayerController::IncomingLeEncryptConnection(
959     model::packets::LinkLayerPacketView incoming) {
960   LOG_INFO();
961 
962   // TODO: Check keys
963   Address peer = incoming.GetSourceAddress();
964   uint16_t handle = connections_.GetHandleOnlyAddress(peer);
965   if (handle == acl::kReservedHandle) {
966     LOG_INFO("@%s: Unknown connection @%s",
967              incoming.GetDestinationAddress().ToString().c_str(),
968              peer.ToString().c_str());
969     return;
970   }
971   ErrorCode status = ErrorCode::SUCCESS;
972   auto le_encrypt = model::packets::LeEncryptConnectionView::Create(incoming);
973   ASSERT(le_encrypt.IsValid());
974 
975   if (connections_.IsEncrypted(handle)) {
976     send_event_(bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create(
977         status, handle));
978   } else {
979     connections_.Encrypt(handle);
980     send_event_(bluetooth::hci::EncryptionChangeBuilder::Create(
981         status, handle, bluetooth::hci::EncryptionEnabled::ON));
982   }
983   SendLeLinkLayerPacket(
984       model::packets::LeEncryptConnectionResponseBuilder::Create(
985           connections_.GetOwnAddress(handle).GetAddress(), peer,
986           le_encrypt.GetRand(), le_encrypt.GetEdiv(), le_encrypt.GetLtk()));
987 }
988 
IncomingLeEncryptConnectionResponse(model::packets::LinkLayerPacketView incoming)989 void LinkLayerController::IncomingLeEncryptConnectionResponse(
990     model::packets::LinkLayerPacketView incoming) {
991   LOG_INFO();
992   // TODO: Check keys
993   uint16_t handle =
994       connections_.GetHandleOnlyAddress(incoming.GetSourceAddress());
995   if (handle == acl::kReservedHandle) {
996     LOG_INFO("@%s: Unknown connection @%s",
997              incoming.GetDestinationAddress().ToString().c_str(),
998              incoming.GetSourceAddress().ToString().c_str());
999     return;
1000   }
1001   ErrorCode status = ErrorCode::SUCCESS;
1002 
1003   if (connections_.IsEncrypted(handle)) {
1004     send_event_(bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create(
1005         status, handle));
1006   } else {
1007     connections_.Encrypt(handle);
1008     send_event_(bluetooth::hci::EncryptionChangeBuilder::Create(
1009         status, handle, bluetooth::hci::EncryptionEnabled::ON));
1010   }
1011 }
1012 
IncomingLeScanPacket(model::packets::LinkLayerPacketView incoming)1013 void LinkLayerController::IncomingLeScanPacket(
1014     model::packets::LinkLayerPacketView incoming) {
1015   for (auto& advertiser : advertisers_) {
1016     auto to_send = advertiser.GetScanResponse(incoming.GetDestinationAddress(),
1017                                               incoming.GetSourceAddress());
1018     if (to_send != nullptr) {
1019       SendLeLinkLayerPacket(std::move(to_send));
1020     }
1021   }
1022 }
1023 
IncomingLeScanResponsePacket(model::packets::LinkLayerPacketView incoming)1024 void LinkLayerController::IncomingLeScanResponsePacket(
1025     model::packets::LinkLayerPacketView incoming) {
1026   auto scan_response = model::packets::LeScanResponseView::Create(incoming);
1027   ASSERT(scan_response.IsValid());
1028   vector<uint8_t> ad = scan_response.GetData();
1029   auto adv_type = scan_response.GetAdvertisementType();
1030   auto address_type =
1031       static_cast<LeAdvertisement::AddressType>(scan_response.GetAddressType());
1032   if (le_scan_enable_ == bluetooth::hci::OpCode::LE_SET_SCAN_ENABLE) {
1033     if (adv_type != model::packets::AdvertisementType::SCAN_RESPONSE) {
1034       return;
1035     }
1036     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
1037         std::make_unique<bluetooth::packet::RawBuilder>();
1038     raw_builder_ptr->AddOctets1(
1039         static_cast<uint8_t>(bluetooth::hci::SubeventCode::ADVERTISING_REPORT));
1040     raw_builder_ptr->AddOctets1(0x01);  // num reports
1041     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(
1042         bluetooth::hci::AdvertisingEventType::SCAN_RESPONSE));
1043     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
1044     raw_builder_ptr->AddAddress(incoming.GetSourceAddress());
1045     raw_builder_ptr->AddOctets1(ad.size());
1046     raw_builder_ptr->AddOctets(ad);
1047     raw_builder_ptr->AddOctets1(GetRssi());
1048     auto packet = bluetooth::hci::EventPacketBuilder::Create(
1049         bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr));
1050     send_event_(std::move(packet));
1051   }
1052 
1053   if (le_scan_enable_ == bluetooth::hci::OpCode::LE_SET_EXTENDED_SCAN_ENABLE) {
1054     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
1055         std::make_unique<bluetooth::packet::RawBuilder>();
1056     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(
1057         bluetooth::hci::SubeventCode::EXTENDED_ADVERTISING_REPORT));
1058     raw_builder_ptr->AddOctets1(0x01);  // num reports
1059     raw_builder_ptr->AddOctets1(0x1a);  // TODO: 0x1b for ADV_SCAN_IND
1060     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
1061     raw_builder_ptr->AddAddress(incoming.GetSourceAddress());
1062     raw_builder_ptr->AddOctets1(1);     // Primary_PHY
1063     raw_builder_ptr->AddOctets1(0);     // Secondary_PHY
1064     raw_builder_ptr->AddOctets1(0xFF);  // Advertising_SID - not provided
1065     raw_builder_ptr->AddOctets1(0x7F);  // Tx_Power - Not available
1066     raw_builder_ptr->AddOctets1(GetRssi());
1067     raw_builder_ptr->AddOctets1(0);  // Periodic_Advertising_Interval - None
1068     raw_builder_ptr->AddOctets1(0);  // Direct_Address_Type - PUBLIC
1069     raw_builder_ptr->AddAddress(Address::kEmpty);  // Direct_Address
1070     raw_builder_ptr->AddOctets1(ad.size());
1071     raw_builder_ptr->AddOctets(ad);
1072     auto packet = bluetooth::hci::EventPacketBuilder::Create(
1073         bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr));
1074     send_event_(std::move(packet));
1075   }
1076 }
1077 
IncomingPagePacket(model::packets::LinkLayerPacketView incoming)1078 void LinkLayerController::IncomingPagePacket(
1079     model::packets::LinkLayerPacketView incoming) {
1080   auto page = model::packets::PageView::Create(incoming);
1081   ASSERT(page.IsValid());
1082   LOG_INFO("from %s", incoming.GetSourceAddress().ToString().c_str());
1083 
1084   if (!connections_.CreatePendingConnection(
1085           incoming.GetSourceAddress(), properties_.GetAuthenticationEnable())) {
1086     // Send a response to indicate that we're busy, or drop the packet?
1087     LOG_WARN("Failed to create a pending connection for %s",
1088              incoming.GetSourceAddress().ToString().c_str());
1089   }
1090 
1091   bluetooth::hci::Address source_address{};
1092   bluetooth::hci::Address::FromString(page.GetSourceAddress().ToString(),
1093                                       source_address);
1094 
1095   auto packet = bluetooth::hci::ConnectionRequestBuilder::Create(
1096       source_address, page.GetClassOfDevice(),
1097       bluetooth::hci::ConnectionRequestLinkType::ACL);
1098 
1099   send_event_(std::move(packet));
1100 }
1101 
IncomingPageRejectPacket(model::packets::LinkLayerPacketView incoming)1102 void LinkLayerController::IncomingPageRejectPacket(
1103     model::packets::LinkLayerPacketView incoming) {
1104   LOG_INFO("%s", incoming.GetSourceAddress().ToString().c_str());
1105   auto reject = model::packets::PageRejectView::Create(incoming);
1106   ASSERT(reject.IsValid());
1107   LOG_INFO("Sending CreateConnectionComplete");
1108   auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
1109       static_cast<ErrorCode>(reject.GetReason()), 0x0eff,
1110       incoming.GetSourceAddress(), bluetooth::hci::LinkType::ACL,
1111       bluetooth::hci::Enable::DISABLED);
1112   send_event_(std::move(packet));
1113 }
1114 
IncomingPageResponsePacket(model::packets::LinkLayerPacketView incoming)1115 void LinkLayerController::IncomingPageResponsePacket(
1116     model::packets::LinkLayerPacketView incoming) {
1117   Address peer = incoming.GetSourceAddress();
1118   LOG_INFO("%s", peer.ToString().c_str());
1119   bool awaiting_authentication = connections_.AuthenticatePendingConnection();
1120   uint16_t handle =
1121       connections_.CreateConnection(peer, incoming.GetDestinationAddress());
1122   if (handle == acl::kReservedHandle) {
1123     LOG_WARN("No free handles");
1124     return;
1125   }
1126   auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
1127       ErrorCode::SUCCESS, handle, incoming.GetSourceAddress(),
1128       bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED);
1129   send_event_(std::move(packet));
1130 
1131   if (awaiting_authentication) {
1132     ScheduleTask(milliseconds(5), [this, peer, handle]() {
1133       HandleAuthenticationRequest(peer, handle);
1134     });
1135   }
1136 }
1137 
TimerTick()1138 void LinkLayerController::TimerTick() {
1139   if (inquiry_timer_task_id_ != kInvalidTaskId) Inquiry();
1140   LeAdvertising();
1141 }
1142 
LeAdvertising()1143 void LinkLayerController::LeAdvertising() {
1144   steady_clock::time_point now = steady_clock::now();
1145   for (auto& advertiser : advertisers_) {
1146     auto ad = advertiser.GetAdvertisement(now);
1147     if (ad == nullptr) {
1148       continue;
1149     }
1150     SendLeLinkLayerPacket(std::move(ad));
1151   }
1152 }
1153 
RegisterEventChannel(const std::function<void (std::shared_ptr<bluetooth::hci::EventPacketBuilder>)> & callback)1154 void LinkLayerController::RegisterEventChannel(
1155     const std::function<
1156         void(std::shared_ptr<bluetooth::hci::EventPacketBuilder>)>& callback) {
1157   send_event_ = callback;
1158 }
1159 
RegisterAclChannel(const std::function<void (std::shared_ptr<bluetooth::hci::AclPacketBuilder>)> & callback)1160 void LinkLayerController::RegisterAclChannel(
1161     const std::function<
1162         void(std::shared_ptr<bluetooth::hci::AclPacketBuilder>)>& callback) {
1163   send_acl_ = callback;
1164 }
1165 
RegisterScoChannel(const std::function<void (std::shared_ptr<std::vector<uint8_t>>)> & callback)1166 void LinkLayerController::RegisterScoChannel(
1167     const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>&
1168         callback) {
1169   send_sco_ = callback;
1170 }
1171 
RegisterIsoChannel(const std::function<void (std::shared_ptr<std::vector<uint8_t>>)> & callback)1172 void LinkLayerController::RegisterIsoChannel(
1173     const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>&
1174         callback) {
1175   send_iso_ = callback;
1176 }
1177 
RegisterRemoteChannel(const std::function<void (std::shared_ptr<model::packets::LinkLayerPacketBuilder>,Phy::Type)> & callback)1178 void LinkLayerController::RegisterRemoteChannel(
1179     const std::function<void(
1180         std::shared_ptr<model::packets::LinkLayerPacketBuilder>, Phy::Type)>&
1181         callback) {
1182   send_to_remote_ = callback;
1183 }
1184 
RegisterTaskScheduler(std::function<AsyncTaskId (milliseconds,const TaskCallback &)> event_scheduler)1185 void LinkLayerController::RegisterTaskScheduler(
1186     std::function<AsyncTaskId(milliseconds, const TaskCallback&)>
1187         event_scheduler) {
1188   schedule_task_ = event_scheduler;
1189 }
1190 
ScheduleTask(milliseconds delay_ms,const TaskCallback & callback)1191 AsyncTaskId LinkLayerController::ScheduleTask(milliseconds delay_ms,
1192                                               const TaskCallback& callback) {
1193   if (schedule_task_) {
1194     return schedule_task_(delay_ms, callback);
1195   } else {
1196     callback();
1197     return 0;
1198   }
1199 }
1200 
RegisterPeriodicTaskScheduler(std::function<AsyncTaskId (milliseconds,milliseconds,const TaskCallback &)> periodic_event_scheduler)1201 void LinkLayerController::RegisterPeriodicTaskScheduler(
1202     std::function<AsyncTaskId(milliseconds, milliseconds, const TaskCallback&)>
1203         periodic_event_scheduler) {
1204   schedule_periodic_task_ = periodic_event_scheduler;
1205 }
1206 
CancelScheduledTask(AsyncTaskId task_id)1207 void LinkLayerController::CancelScheduledTask(AsyncTaskId task_id) {
1208   if (schedule_task_ && cancel_task_) {
1209     cancel_task_(task_id);
1210   }
1211 }
1212 
RegisterTaskCancel(std::function<void (AsyncTaskId)> task_cancel)1213 void LinkLayerController::RegisterTaskCancel(
1214     std::function<void(AsyncTaskId)> task_cancel) {
1215   cancel_task_ = task_cancel;
1216 }
1217 
WriteSimplePairingMode(bool enabled)1218 void LinkLayerController::WriteSimplePairingMode(bool enabled) {
1219   ASSERT_LOG(enabled, "The spec says don't disable this!");
1220   simple_pairing_mode_enabled_ = enabled;
1221 }
1222 
StartSimplePairing(const Address & address)1223 void LinkLayerController::StartSimplePairing(const Address& address) {
1224   // IO Capability Exchange (See the Diagram in the Spec)
1225   auto packet = bluetooth::hci::IoCapabilityRequestBuilder::Create(address);
1226   send_event_(std::move(packet));
1227 
1228   // Get a Key, then authenticate
1229   // PublicKeyExchange(address);
1230   // AuthenticateRemoteStage1(address);
1231   // AuthenticateRemoteStage2(address);
1232 }
1233 
AuthenticateRemoteStage1(const Address & peer,PairingType pairing_type)1234 void LinkLayerController::AuthenticateRemoteStage1(const Address& peer,
1235                                                    PairingType pairing_type) {
1236   ASSERT(security_manager_.GetAuthenticationAddress() == peer);
1237   // TODO: Public key exchange first?
1238   switch (pairing_type) {
1239     case PairingType::AUTO_CONFIRMATION:
1240       send_event_(
1241           bluetooth::hci::UserConfirmationRequestBuilder::Create(peer, 123456));
1242       break;
1243     case PairingType::CONFIRM_Y_N:
1244       send_event_(
1245           bluetooth::hci::UserConfirmationRequestBuilder::Create(peer, 123456));
1246       break;
1247     case PairingType::DISPLAY_PIN:
1248       send_event_(
1249           bluetooth::hci::UserConfirmationRequestBuilder::Create(peer, 123456));
1250       break;
1251     case PairingType::DISPLAY_AND_CONFIRM:
1252       send_event_(
1253           bluetooth::hci::UserConfirmationRequestBuilder::Create(peer, 123456));
1254       break;
1255     case PairingType::INPUT_PIN:
1256       send_event_(bluetooth::hci::UserPasskeyRequestBuilder::Create(peer));
1257       break;
1258     default:
1259       LOG_ALWAYS_FATAL("Invalid PairingType %d",
1260                        static_cast<int>(pairing_type));
1261   }
1262 }
1263 
AuthenticateRemoteStage2(const Address & peer)1264 void LinkLayerController::AuthenticateRemoteStage2(const Address& peer) {
1265   uint16_t handle = security_manager_.GetAuthenticationHandle();
1266   ASSERT(security_manager_.GetAuthenticationAddress() == peer);
1267   // Check key in security_manager_ ?
1268   auto packet = bluetooth::hci::AuthenticationCompleteBuilder::Create(
1269       ErrorCode::SUCCESS, handle);
1270   send_event_(std::move(packet));
1271 }
1272 
LinkKeyRequestReply(const Address & peer,const std::array<uint8_t,16> & key)1273 ErrorCode LinkLayerController::LinkKeyRequestReply(
1274     const Address& peer, const std::array<uint8_t, 16>& key) {
1275   security_manager_.WriteKey(peer, key);
1276   security_manager_.AuthenticationRequestFinished();
1277 
1278   ScheduleTask(milliseconds(5),
1279                [this, peer]() { AuthenticateRemoteStage2(peer); });
1280 
1281   return ErrorCode::SUCCESS;
1282 }
1283 
LinkKeyRequestNegativeReply(const Address & address)1284 ErrorCode LinkLayerController::LinkKeyRequestNegativeReply(
1285     const Address& address) {
1286   security_manager_.DeleteKey(address);
1287   // Simple pairing to get a key
1288   uint16_t handle = connections_.GetHandleOnlyAddress(address);
1289   if (handle == acl::kReservedHandle) {
1290     LOG_INFO("Device not connected %s", address.ToString().c_str());
1291     return ErrorCode::UNKNOWN_CONNECTION;
1292   }
1293 
1294   security_manager_.AuthenticationRequest(address, handle);
1295 
1296   ScheduleTask(milliseconds(5),
1297                [this, address]() { StartSimplePairing(address); });
1298   return ErrorCode::SUCCESS;
1299 }
1300 
IoCapabilityRequestReply(const Address & peer,uint8_t io_capability,uint8_t oob_data_present_flag,uint8_t authentication_requirements)1301 ErrorCode LinkLayerController::IoCapabilityRequestReply(
1302     const Address& peer, uint8_t io_capability, uint8_t oob_data_present_flag,
1303     uint8_t authentication_requirements) {
1304   security_manager_.SetLocalIoCapability(
1305       peer, io_capability, oob_data_present_flag, authentication_requirements);
1306 
1307   PairingType pairing_type = security_manager_.GetSimplePairingType();
1308 
1309   if (pairing_type != PairingType::INVALID) {
1310     ScheduleTask(milliseconds(5), [this, peer, pairing_type]() {
1311       AuthenticateRemoteStage1(peer, pairing_type);
1312     });
1313     SendLinkLayerPacket(model::packets::IoCapabilityResponseBuilder::Create(
1314         properties_.GetAddress(), peer, io_capability, oob_data_present_flag,
1315         authentication_requirements));
1316   } else {
1317     LOG_INFO("Requesting remote capability");
1318 
1319     SendLinkLayerPacket(model::packets::IoCapabilityRequestBuilder::Create(
1320         properties_.GetAddress(), peer, io_capability, oob_data_present_flag,
1321         authentication_requirements));
1322   }
1323 
1324   return ErrorCode::SUCCESS;
1325 }
1326 
IoCapabilityRequestNegativeReply(const Address & peer,ErrorCode reason)1327 ErrorCode LinkLayerController::IoCapabilityRequestNegativeReply(
1328     const Address& peer, ErrorCode reason) {
1329   if (security_manager_.GetAuthenticationAddress() != peer) {
1330     return ErrorCode::AUTHENTICATION_FAILURE;
1331   }
1332 
1333   security_manager_.InvalidateIoCapabilities();
1334 
1335   auto packet = model::packets::IoCapabilityNegativeResponseBuilder::Create(
1336       properties_.GetAddress(), peer, static_cast<uint8_t>(reason));
1337   SendLinkLayerPacket(std::move(packet));
1338 
1339   return ErrorCode::SUCCESS;
1340 }
1341 
UserConfirmationRequestReply(const Address & peer)1342 ErrorCode LinkLayerController::UserConfirmationRequestReply(
1343     const Address& peer) {
1344   if (security_manager_.GetAuthenticationAddress() != peer) {
1345     return ErrorCode::AUTHENTICATION_FAILURE;
1346   }
1347   // TODO: Key could be calculated here.
1348   std::array<uint8_t, 16> key_vec{1, 2,  3,  4,  5,  6,  7,  8,
1349                                   9, 10, 11, 12, 13, 14, 15, 16};
1350   security_manager_.WriteKey(peer, key_vec);
1351 
1352   security_manager_.AuthenticationRequestFinished();
1353 
1354   ScheduleTask(milliseconds(5), [this, peer]() {
1355     send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1356         ErrorCode::SUCCESS, peer));
1357   });
1358 
1359   ScheduleTask(milliseconds(5), [this, peer, key_vec]() {
1360     send_event_(bluetooth::hci::LinkKeyNotificationBuilder::Create(
1361         peer, key_vec, bluetooth::hci::KeyType::AUTHENTICATED_P256));
1362   });
1363 
1364   ScheduleTask(milliseconds(15),
1365                [this, peer]() { AuthenticateRemoteStage2(peer); });
1366   return ErrorCode::SUCCESS;
1367 }
1368 
UserConfirmationRequestNegativeReply(const Address & peer)1369 ErrorCode LinkLayerController::UserConfirmationRequestNegativeReply(
1370     const Address& peer) {
1371   if (security_manager_.GetAuthenticationAddress() != peer) {
1372     return ErrorCode::AUTHENTICATION_FAILURE;
1373   }
1374 
1375   ScheduleTask(milliseconds(5), [this, peer]() {
1376     send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1377         ErrorCode::AUTHENTICATION_FAILURE, peer));
1378   });
1379 
1380   return ErrorCode::SUCCESS;
1381 }
1382 
UserPasskeyRequestReply(const Address & peer,uint32_t numeric_value)1383 ErrorCode LinkLayerController::UserPasskeyRequestReply(const Address& peer,
1384                                                        uint32_t numeric_value) {
1385   if (security_manager_.GetAuthenticationAddress() != peer) {
1386     return ErrorCode::AUTHENTICATION_FAILURE;
1387   }
1388   LOG_INFO("TODO:Do something with the passkey %06d", numeric_value);
1389   return ErrorCode::SUCCESS;
1390 }
1391 
UserPasskeyRequestNegativeReply(const Address & peer)1392 ErrorCode LinkLayerController::UserPasskeyRequestNegativeReply(
1393     const Address& peer) {
1394   if (security_manager_.GetAuthenticationAddress() != peer) {
1395     return ErrorCode::AUTHENTICATION_FAILURE;
1396   }
1397   return ErrorCode::SUCCESS;
1398 }
1399 
RemoteOobDataRequestReply(const Address & peer,const std::vector<uint8_t> & c,const std::vector<uint8_t> & r)1400 ErrorCode LinkLayerController::RemoteOobDataRequestReply(
1401     const Address& peer, const std::vector<uint8_t>& c,
1402     const std::vector<uint8_t>& r) {
1403   if (security_manager_.GetAuthenticationAddress() != peer) {
1404     return ErrorCode::AUTHENTICATION_FAILURE;
1405   }
1406   LOG_INFO("TODO:Do something with the OOB data c=%d r=%d", c[0], r[0]);
1407   return ErrorCode::SUCCESS;
1408 }
1409 
RemoteOobDataRequestNegativeReply(const Address & peer)1410 ErrorCode LinkLayerController::RemoteOobDataRequestNegativeReply(
1411     const Address& peer) {
1412   if (security_manager_.GetAuthenticationAddress() != peer) {
1413     return ErrorCode::AUTHENTICATION_FAILURE;
1414   }
1415   return ErrorCode::SUCCESS;
1416 }
1417 
HandleAuthenticationRequest(const Address & address,uint16_t handle)1418 void LinkLayerController::HandleAuthenticationRequest(const Address& address,
1419                                                       uint16_t handle) {
1420   if (simple_pairing_mode_enabled_ == true) {
1421     security_manager_.AuthenticationRequest(address, handle);
1422     auto packet = bluetooth::hci::LinkKeyRequestBuilder::Create(address);
1423     send_event_(std::move(packet));
1424   } else {  // Should never happen for our phones
1425     // Check for a key, try to authenticate, ask for a PIN.
1426     auto packet = bluetooth::hci::AuthenticationCompleteBuilder::Create(
1427         ErrorCode::AUTHENTICATION_FAILURE, handle);
1428     send_event_(std::move(packet));
1429   }
1430 }
1431 
AuthenticationRequested(uint16_t handle)1432 ErrorCode LinkLayerController::AuthenticationRequested(uint16_t handle) {
1433   if (!connections_.HasHandle(handle)) {
1434     LOG_INFO("Authentication Requested for unknown handle %04x", handle);
1435     return ErrorCode::UNKNOWN_CONNECTION;
1436   }
1437 
1438   AddressWithType remote = connections_.GetAddress(handle);
1439 
1440   ScheduleTask(milliseconds(5), [this, remote, handle]() {
1441     HandleAuthenticationRequest(remote.GetAddress(), handle);
1442   });
1443 
1444   return ErrorCode::SUCCESS;
1445 }
1446 
HandleSetConnectionEncryption(const Address & peer,uint16_t handle,uint8_t encryption_enable)1447 void LinkLayerController::HandleSetConnectionEncryption(
1448     const Address& peer, uint16_t handle, uint8_t encryption_enable) {
1449   // TODO: Block ACL traffic or at least guard against it
1450 
1451   if (connections_.IsEncrypted(handle) && encryption_enable) {
1452     auto packet = bluetooth::hci::EncryptionChangeBuilder::Create(
1453         ErrorCode::SUCCESS, handle,
1454         static_cast<bluetooth::hci::EncryptionEnabled>(encryption_enable));
1455     send_event_(std::move(packet));
1456     return;
1457   }
1458 
1459   uint16_t count = security_manager_.ReadKey(peer);
1460   if (count == 0) {
1461     LOG_ERROR("NO KEY HERE for %s", peer.ToString().c_str());
1462     return;
1463   }
1464   auto array = security_manager_.GetKey(peer);
1465   std::vector<uint8_t> key_vec{array.begin(), array.end()};
1466   auto packet = model::packets::EncryptConnectionBuilder::Create(
1467       properties_.GetAddress(), peer, key_vec);
1468   SendLinkLayerPacket(std::move(packet));
1469 }
1470 
SetConnectionEncryption(uint16_t handle,uint8_t encryption_enable)1471 ErrorCode LinkLayerController::SetConnectionEncryption(
1472     uint16_t handle, uint8_t encryption_enable) {
1473   if (!connections_.HasHandle(handle)) {
1474     LOG_INFO("Set Connection Encryption for unknown handle %04x", handle);
1475     return ErrorCode::UNKNOWN_CONNECTION;
1476   }
1477 
1478   if (connections_.IsEncrypted(handle) && !encryption_enable) {
1479     return ErrorCode::ENCRYPTION_MODE_NOT_ACCEPTABLE;
1480   }
1481   AddressWithType remote = connections_.GetAddress(handle);
1482 
1483   if (security_manager_.ReadKey(remote.GetAddress()) == 0) {
1484     return ErrorCode::PIN_OR_KEY_MISSING;
1485   }
1486 
1487   ScheduleTask(milliseconds(5), [this, remote, handle, encryption_enable]() {
1488     HandleSetConnectionEncryption(remote.GetAddress(), handle,
1489                                   encryption_enable);
1490   });
1491   return ErrorCode::SUCCESS;
1492 }
1493 
AcceptConnectionRequest(const Address & addr,bool try_role_switch)1494 ErrorCode LinkLayerController::AcceptConnectionRequest(const Address& addr,
1495                                                        bool try_role_switch) {
1496   if (!connections_.HasPendingConnection(addr)) {
1497     LOG_INFO("No pending connection for %s", addr.ToString().c_str());
1498     return ErrorCode::UNKNOWN_CONNECTION;
1499   }
1500 
1501   LOG_INFO("Accept in 200ms");
1502   ScheduleTask(milliseconds(200), [this, addr, try_role_switch]() {
1503     LOG_INFO("Accepted");
1504     MakeSlaveConnection(addr, try_role_switch);
1505   });
1506 
1507   return ErrorCode::SUCCESS;
1508 }
1509 
MakeSlaveConnection(const Address & addr,bool try_role_switch)1510 void LinkLayerController::MakeSlaveConnection(const Address& addr,
1511                                               bool try_role_switch) {
1512   LOG_INFO("Sending page response to %s", addr.ToString().c_str());
1513   auto to_send = model::packets::PageResponseBuilder::Create(
1514       properties_.GetAddress(), addr, try_role_switch);
1515   SendLinkLayerPacket(std::move(to_send));
1516 
1517   uint16_t handle =
1518       connections_.CreateConnection(addr, properties_.GetAddress());
1519   if (handle == acl::kReservedHandle) {
1520     LOG_INFO("CreateConnection failed");
1521     return;
1522   }
1523   LOG_INFO("CreateConnection returned handle 0x%x", handle);
1524   auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
1525       ErrorCode::SUCCESS, handle, addr, bluetooth::hci::LinkType::ACL,
1526       bluetooth::hci::Enable::DISABLED);
1527   send_event_(std::move(packet));
1528 }
1529 
RejectConnectionRequest(const Address & addr,uint8_t reason)1530 ErrorCode LinkLayerController::RejectConnectionRequest(const Address& addr,
1531                                                        uint8_t reason) {
1532   if (!connections_.HasPendingConnection(addr)) {
1533     LOG_INFO("No pending connection for %s", addr.ToString().c_str());
1534     return ErrorCode::UNKNOWN_CONNECTION;
1535   }
1536 
1537   ScheduleTask(milliseconds(200),
1538                [this, addr, reason]() { RejectSlaveConnection(addr, reason); });
1539 
1540   return ErrorCode::SUCCESS;
1541 }
1542 
RejectSlaveConnection(const Address & addr,uint8_t reason)1543 void LinkLayerController::RejectSlaveConnection(const Address& addr,
1544                                                 uint8_t reason) {
1545   auto to_send = model::packets::PageRejectBuilder::Create(
1546       properties_.GetAddress(), addr, reason);
1547   LOG_INFO("Sending page reject to %s (reason 0x%02hhx)",
1548            addr.ToString().c_str(), reason);
1549   SendLinkLayerPacket(std::move(to_send));
1550 
1551   auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
1552       static_cast<ErrorCode>(reason), 0xeff, addr,
1553       bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED);
1554   send_event_(std::move(packet));
1555 }
1556 
CreateConnection(const Address & addr,uint16_t,uint8_t,uint16_t,uint8_t allow_role_switch)1557 ErrorCode LinkLayerController::CreateConnection(const Address& addr, uint16_t,
1558                                                 uint8_t, uint16_t,
1559                                                 uint8_t allow_role_switch) {
1560   if (!connections_.CreatePendingConnection(
1561           addr, properties_.GetAuthenticationEnable() == 1)) {
1562     return ErrorCode::CONTROLLER_BUSY;
1563   }
1564   auto page = model::packets::PageBuilder::Create(
1565       properties_.GetAddress(), addr, properties_.GetClassOfDevice(),
1566       allow_role_switch);
1567   SendLinkLayerPacket(std::move(page));
1568 
1569   return ErrorCode::SUCCESS;
1570 }
1571 
CreateConnectionCancel(const Address & addr)1572 ErrorCode LinkLayerController::CreateConnectionCancel(const Address& addr) {
1573   if (!connections_.CancelPendingConnection(addr)) {
1574     return ErrorCode::UNKNOWN_CONNECTION;
1575   }
1576   return ErrorCode::SUCCESS;
1577 }
1578 
Disconnect(uint16_t handle,uint8_t reason)1579 ErrorCode LinkLayerController::Disconnect(uint16_t handle, uint8_t reason) {
1580   if (!connections_.HasHandle(handle)) {
1581     return ErrorCode::UNKNOWN_CONNECTION;
1582   }
1583 
1584   const AddressWithType remote = connections_.GetAddress(handle);
1585   auto packet = model::packets::DisconnectBuilder::Create(
1586       properties_.GetAddress(), remote.GetAddress(), reason);
1587   SendLinkLayerPacket(std::move(packet));
1588   ASSERT_LOG(connections_.Disconnect(handle), "Disconnecting %hx", handle);
1589 
1590   ScheduleTask(milliseconds(20), [this, handle]() {
1591     DisconnectCleanup(
1592         handle,
1593         static_cast<uint8_t>(ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST));
1594   });
1595 
1596   return ErrorCode::SUCCESS;
1597 }
1598 
DisconnectCleanup(uint16_t handle,uint8_t reason)1599 void LinkLayerController::DisconnectCleanup(uint16_t handle, uint8_t reason) {
1600   // TODO: Clean up other connection state.
1601   auto packet = bluetooth::hci::DisconnectionCompleteBuilder::Create(
1602       ErrorCode::SUCCESS, handle, static_cast<ErrorCode>(reason));
1603   send_event_(std::move(packet));
1604 }
1605 
ChangeConnectionPacketType(uint16_t handle,uint16_t types)1606 ErrorCode LinkLayerController::ChangeConnectionPacketType(uint16_t handle,
1607                                                           uint16_t types) {
1608   if (!connections_.HasHandle(handle)) {
1609     return ErrorCode::UNKNOWN_CONNECTION;
1610   }
1611   auto packet = bluetooth::hci::ConnectionPacketTypeChangedBuilder::Create(
1612       ErrorCode::SUCCESS, handle, types);
1613   std::shared_ptr<bluetooth::hci::ConnectionPacketTypeChangedBuilder>
1614       shared_packet = std::move(packet);
1615   ScheduleTask(milliseconds(20), [this, shared_packet]() {
1616     send_event_(std::move(shared_packet));
1617   });
1618 
1619   return ErrorCode::SUCCESS;
1620 }
1621 
ChangeConnectionLinkKey(uint16_t handle)1622 ErrorCode LinkLayerController::ChangeConnectionLinkKey(uint16_t handle) {
1623   if (!connections_.HasHandle(handle)) {
1624     return ErrorCode::UNKNOWN_CONNECTION;
1625   }
1626 
1627   // TODO: implement real logic
1628   return ErrorCode::COMMAND_DISALLOWED;
1629 }
1630 
MasterLinkKey(uint8_t)1631 ErrorCode LinkLayerController::MasterLinkKey(uint8_t /* key_flag */) {
1632   // TODO: implement real logic
1633   return ErrorCode::COMMAND_DISALLOWED;
1634 }
1635 
HoldMode(uint16_t handle,uint16_t hold_mode_max_interval,uint16_t hold_mode_min_interval)1636 ErrorCode LinkLayerController::HoldMode(uint16_t handle,
1637                                         uint16_t hold_mode_max_interval,
1638                                         uint16_t hold_mode_min_interval) {
1639   if (!connections_.HasHandle(handle)) {
1640     return ErrorCode::UNKNOWN_CONNECTION;
1641   }
1642 
1643   if (hold_mode_max_interval < hold_mode_min_interval) {
1644     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
1645   }
1646 
1647   // TODO: implement real logic
1648   return ErrorCode::COMMAND_DISALLOWED;
1649 }
1650 
SniffMode(uint16_t handle,uint16_t sniff_max_interval,uint16_t sniff_min_interval,uint16_t sniff_attempt,uint16_t sniff_timeout)1651 ErrorCode LinkLayerController::SniffMode(uint16_t handle,
1652                                          uint16_t sniff_max_interval,
1653                                          uint16_t sniff_min_interval,
1654                                          uint16_t sniff_attempt,
1655                                          uint16_t sniff_timeout) {
1656   if (!connections_.HasHandle(handle)) {
1657     return ErrorCode::UNKNOWN_CONNECTION;
1658   }
1659 
1660   if (sniff_max_interval < sniff_min_interval || sniff_attempt < 0x0001 ||
1661       sniff_attempt > 0x7FFF || sniff_timeout > 0x7FFF) {
1662     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
1663   }
1664 
1665   // TODO: implement real logic
1666   return ErrorCode::COMMAND_DISALLOWED;
1667 }
1668 
ExitSniffMode(uint16_t handle)1669 ErrorCode LinkLayerController::ExitSniffMode(uint16_t handle) {
1670   if (!connections_.HasHandle(handle)) {
1671     return ErrorCode::UNKNOWN_CONNECTION;
1672   }
1673 
1674   // TODO: implement real logic
1675   return ErrorCode::COMMAND_DISALLOWED;
1676 }
1677 
QosSetup(uint16_t handle,uint8_t service_type,uint32_t,uint32_t,uint32_t,uint32_t)1678 ErrorCode LinkLayerController::QosSetup(uint16_t handle, uint8_t service_type,
1679                                         uint32_t /* token_rate */,
1680                                         uint32_t /* peak_bandwidth */,
1681                                         uint32_t /* latency */,
1682                                         uint32_t /* delay_variation */) {
1683   if (!connections_.HasHandle(handle)) {
1684     return ErrorCode::UNKNOWN_CONNECTION;
1685   }
1686 
1687   if (service_type > 0x02) {
1688     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
1689   }
1690 
1691   // TODO: implement real logic
1692   return ErrorCode::COMMAND_DISALLOWED;
1693 }
1694 
SwitchRole(Address,uint8_t)1695 ErrorCode LinkLayerController::SwitchRole(Address /* bd_addr */,
1696                                           uint8_t /* role */) {
1697   // TODO: implement real logic
1698   return ErrorCode::COMMAND_DISALLOWED;
1699 }
1700 
WriteLinkPolicySettings(uint16_t handle,uint16_t)1701 ErrorCode LinkLayerController::WriteLinkPolicySettings(uint16_t handle,
1702                                                        uint16_t) {
1703   if (!connections_.HasHandle(handle)) {
1704     return ErrorCode::UNKNOWN_CONNECTION;
1705   }
1706   return ErrorCode::SUCCESS;
1707 }
1708 
WriteDefaultLinkPolicySettings(uint16_t settings)1709 ErrorCode LinkLayerController::WriteDefaultLinkPolicySettings(
1710     uint16_t settings) {
1711   if (settings > 7 /* Sniff + Hold + Role switch */) {
1712     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
1713   }
1714   default_link_policy_settings_ = settings;
1715   return ErrorCode::SUCCESS;
1716 }
1717 
ReadDefaultLinkPolicySettings()1718 uint16_t LinkLayerController::ReadDefaultLinkPolicySettings() {
1719   return default_link_policy_settings_;
1720 }
1721 
FlowSpecification(uint16_t handle,uint8_t flow_direction,uint8_t service_type,uint32_t,uint32_t,uint32_t,uint32_t)1722 ErrorCode LinkLayerController::FlowSpecification(
1723     uint16_t handle, uint8_t flow_direction, uint8_t service_type,
1724     uint32_t /* token_rate */, uint32_t /* token_bucket_size */,
1725     uint32_t /* peak_bandwidth */, uint32_t /* access_latency */) {
1726   if (!connections_.HasHandle(handle)) {
1727     return ErrorCode::UNKNOWN_CONNECTION;
1728   }
1729 
1730   if (flow_direction > 0x01 || service_type > 0x02) {
1731     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
1732   }
1733 
1734   // TODO: implement real logic
1735   return ErrorCode::COMMAND_DISALLOWED;
1736 }
1737 
WriteLinkSupervisionTimeout(uint16_t handle,uint16_t)1738 ErrorCode LinkLayerController::WriteLinkSupervisionTimeout(uint16_t handle,
1739                                                            uint16_t) {
1740   if (!connections_.HasHandle(handle)) {
1741     return ErrorCode::UNKNOWN_CONNECTION;
1742   }
1743   return ErrorCode::SUCCESS;
1744 }
1745 
SetLeExtendedAddress(uint8_t set,Address address)1746 ErrorCode LinkLayerController::SetLeExtendedAddress(uint8_t set,
1747                                                     Address address) {
1748   advertisers_[set].SetAddress(address);
1749   return ErrorCode::SUCCESS;
1750 }
1751 
SetLeExtendedAdvertisingData(uint8_t set,const std::vector<uint8_t> & data)1752 ErrorCode LinkLayerController::SetLeExtendedAdvertisingData(
1753     uint8_t set, const std::vector<uint8_t>& data) {
1754   advertisers_[set].SetData(data);
1755   return ErrorCode::SUCCESS;
1756 }
1757 
SetLeExtendedAdvertisingParameters(uint8_t set,uint16_t interval_min,uint16_t interval_max,bluetooth::hci::LegacyAdvertisingProperties type,bluetooth::hci::OwnAddressType own_address_type,bluetooth::hci::PeerAddressType peer_address_type,Address peer,bluetooth::hci::AdvertisingFilterPolicy filter_policy)1758 ErrorCode LinkLayerController::SetLeExtendedAdvertisingParameters(
1759     uint8_t set, uint16_t interval_min, uint16_t interval_max,
1760     bluetooth::hci::LegacyAdvertisingProperties type,
1761     bluetooth::hci::OwnAddressType own_address_type,
1762     bluetooth::hci::PeerAddressType peer_address_type, Address peer,
1763     bluetooth::hci::AdvertisingFilterPolicy filter_policy) {
1764   model::packets::AdvertisementType ad_type;
1765   switch (type) {
1766     case bluetooth::hci::LegacyAdvertisingProperties::ADV_IND:
1767       ad_type = model::packets::AdvertisementType::ADV_IND;
1768       peer = Address::kEmpty;
1769       break;
1770     case bluetooth::hci::LegacyAdvertisingProperties::ADV_NONCONN_IND:
1771       ad_type = model::packets::AdvertisementType::ADV_NONCONN_IND;
1772       peer = Address::kEmpty;
1773       break;
1774     case bluetooth::hci::LegacyAdvertisingProperties::ADV_SCAN_IND:
1775       ad_type = model::packets::AdvertisementType::ADV_SCAN_IND;
1776       peer = Address::kEmpty;
1777       break;
1778     case bluetooth::hci::LegacyAdvertisingProperties::ADV_DIRECT_IND_HIGH:
1779     case bluetooth::hci::LegacyAdvertisingProperties::ADV_DIRECT_IND_LOW:
1780       ad_type = model::packets::AdvertisementType::ADV_DIRECT_IND;
1781       break;
1782   }
1783   auto interval_ms =
1784       static_cast<int>((interval_max + interval_min) * 0.625 / 2);
1785 
1786   AddressWithType peer_address;
1787   switch (peer_address_type) {
1788     case bluetooth::hci::PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS:
1789       peer_address = AddressWithType(
1790           peer, bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS);
1791       break;
1792     case bluetooth::hci::PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS:
1793       peer_address = AddressWithType(
1794           peer, bluetooth::hci::AddressType::RANDOM_DEVICE_ADDRESS);
1795       break;
1796   }
1797 
1798   AddressType own_address_address_type;
1799   switch (own_address_type) {
1800     case bluetooth::hci::OwnAddressType::RANDOM_DEVICE_ADDRESS:
1801       own_address_address_type =
1802           bluetooth::hci::AddressType::RANDOM_DEVICE_ADDRESS;
1803       break;
1804     case bluetooth::hci::OwnAddressType::PUBLIC_DEVICE_ADDRESS:
1805       own_address_address_type =
1806           bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS;
1807       break;
1808     case bluetooth::hci::OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS:
1809       own_address_address_type =
1810           bluetooth::hci::AddressType::PUBLIC_IDENTITY_ADDRESS;
1811       break;
1812     case bluetooth::hci::OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS:
1813       own_address_address_type =
1814           bluetooth::hci::AddressType::RANDOM_IDENTITY_ADDRESS;
1815       break;
1816   }
1817 
1818   bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy;
1819   switch (filter_policy) {
1820     case bluetooth::hci::AdvertisingFilterPolicy::ALL_DEVICES:
1821       scanning_filter_policy =
1822           bluetooth::hci::LeScanningFilterPolicy::ACCEPT_ALL;
1823       break;
1824     case bluetooth::hci::AdvertisingFilterPolicy::LISTED_SCAN:
1825       scanning_filter_policy =
1826           bluetooth::hci::LeScanningFilterPolicy::CONNECT_LIST_ONLY;
1827       break;
1828     case bluetooth::hci::AdvertisingFilterPolicy::LISTED_CONNECT:
1829       scanning_filter_policy =
1830           bluetooth::hci::LeScanningFilterPolicy::CHECK_INITIATORS_IDENTITY;
1831       break;
1832     case bluetooth::hci::AdvertisingFilterPolicy::LISTED_SCAN_AND_CONNECT:
1833       scanning_filter_policy = bluetooth::hci::LeScanningFilterPolicy::
1834           CONNECT_LIST_AND_INITIATORS_IDENTITY;
1835       break;
1836   }
1837 
1838   advertisers_[set].InitializeExtended(own_address_address_type, peer_address,
1839                                        scanning_filter_policy, ad_type,
1840                                        std::chrono::milliseconds(interval_ms));
1841 
1842   return ErrorCode::SUCCESS;
1843 }
1844 
LeRemoveAdvertisingSet(uint8_t set)1845 ErrorCode LinkLayerController::LeRemoveAdvertisingSet(uint8_t set) {
1846   if (set >= advertisers_.size()) {
1847     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
1848   }
1849   advertisers_[set].Disable();
1850   return ErrorCode::SUCCESS;
1851 }
1852 
LeClearAdvertisingSets()1853 ErrorCode LinkLayerController::LeClearAdvertisingSets() {
1854   for (auto& advertiser : advertisers_) {
1855     if (advertiser.IsEnabled()) {
1856       return ErrorCode::COMMAND_DISALLOWED;
1857     }
1858   }
1859   for (auto& advertiser : advertisers_) {
1860     advertiser.Clear();
1861   }
1862   return ErrorCode::SUCCESS;
1863 }
1864 
LeConnectionUpdateComplete(bluetooth::hci::LeConnectionUpdateView connection_update)1865 void LinkLayerController::LeConnectionUpdateComplete(
1866     bluetooth::hci::LeConnectionUpdateView connection_update) {
1867   uint16_t handle = connection_update.GetConnectionHandle();
1868   ErrorCode status = ErrorCode::SUCCESS;
1869   if (!connections_.HasHandle(handle)) {
1870     status = ErrorCode::UNKNOWN_CONNECTION;
1871   }
1872   uint16_t interval_min = connection_update.GetConnIntervalMin();
1873   uint16_t interval_max = connection_update.GetConnIntervalMax();
1874   uint16_t latency = connection_update.GetConnLatency();
1875   uint16_t supervision_timeout = connection_update.GetSupervisionTimeout();
1876 
1877   if (interval_min < 6 || interval_max > 0xC80 || interval_min > interval_max ||
1878       interval_max < interval_min || latency > 0x1F3 ||
1879       supervision_timeout < 0xA || supervision_timeout > 0xC80 ||
1880       // The Supervision_Timeout in milliseconds (*10) shall be larger than (1 +
1881       // Connection_Latency) * Connection_Interval_Max (* 5/4) * 2
1882       supervision_timeout <= ((((1 + latency) * interval_max * 10) / 4) / 10)) {
1883     status = ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
1884   }
1885   uint16_t interval = (interval_min + interval_max) / 2;
1886   send_event_(bluetooth::hci::LeConnectionUpdateCompleteBuilder::Create(
1887       status, handle, interval, latency, supervision_timeout));
1888 }
1889 
LeConnectionUpdate(bluetooth::hci::LeConnectionUpdateView connection_update)1890 ErrorCode LinkLayerController::LeConnectionUpdate(
1891     bluetooth::hci::LeConnectionUpdateView connection_update) {
1892   uint16_t handle = connection_update.GetConnectionHandle();
1893   if (!connections_.HasHandle(handle)) {
1894     return ErrorCode::UNKNOWN_CONNECTION;
1895   }
1896 
1897   // This could negotiate with the remote device in the future
1898   ScheduleTask(milliseconds(25), [this, connection_update]() {
1899     LeConnectionUpdateComplete(connection_update);
1900   });
1901 
1902   return ErrorCode::SUCCESS;
1903 }
1904 
LeConnectListClear()1905 void LinkLayerController::LeConnectListClear() { le_connect_list_.clear(); }
1906 
LeResolvingListClear()1907 void LinkLayerController::LeResolvingListClear() { le_resolving_list_.clear(); }
1908 
LeConnectListAddDevice(Address addr,uint8_t addr_type)1909 void LinkLayerController::LeConnectListAddDevice(Address addr,
1910                                                  uint8_t addr_type) {
1911   std::tuple<Address, uint8_t> new_tuple = std::make_tuple(addr, addr_type);
1912   for (auto dev : le_connect_list_) {
1913     if (dev == new_tuple) {
1914       return;
1915     }
1916   }
1917   le_connect_list_.emplace_back(new_tuple);
1918 }
1919 
LeResolvingListAddDevice(Address addr,uint8_t addr_type,std::array<uint8_t,kIrk_size> peerIrk,std::array<uint8_t,kIrk_size> localIrk)1920 void LinkLayerController::LeResolvingListAddDevice(
1921     Address addr, uint8_t addr_type, std::array<uint8_t, kIrk_size> peerIrk,
1922     std::array<uint8_t, kIrk_size> localIrk) {
1923   std::tuple<Address, uint8_t, std::array<uint8_t, kIrk_size>,
1924              std::array<uint8_t, kIrk_size>>
1925       new_tuple = std::make_tuple(addr, addr_type, peerIrk, localIrk);
1926   for (size_t i = 0; i < le_connect_list_.size(); i++) {
1927     auto curr = le_connect_list_[i];
1928     if (std::get<0>(curr) == addr && std::get<1>(curr) == addr_type) {
1929       le_resolving_list_[i] = new_tuple;
1930       return;
1931     }
1932   }
1933   le_resolving_list_.emplace_back(new_tuple);
1934 }
1935 
LeSetPrivacyMode(uint8_t address_type,Address addr,uint8_t mode)1936 void LinkLayerController::LeSetPrivacyMode(uint8_t address_type, Address addr,
1937                                            uint8_t mode) {
1938   // set mode for addr
1939   LOG_INFO("address type = %d ", address_type);
1940   LOG_INFO("address = %s ", addr.ToString().c_str());
1941   LOG_INFO("mode = %d ", mode);
1942 }
1943 
HandleLeEnableEncryption(uint16_t handle,std::array<uint8_t,8> rand,uint16_t ediv,std::array<uint8_t,16> ltk)1944 void LinkLayerController::HandleLeEnableEncryption(
1945     uint16_t handle, std::array<uint8_t, 8> rand, uint16_t ediv,
1946     std::array<uint8_t, 16> ltk) {
1947   // TODO: Check keys
1948   // TODO: Block ACL traffic or at least guard against it
1949   if (!connections_.HasHandle(handle)) {
1950     return;
1951   }
1952   SendLeLinkLayerPacket(model::packets::LeEncryptConnectionBuilder::Create(
1953       connections_.GetOwnAddress(handle).GetAddress(),
1954       connections_.GetAddress(handle).GetAddress(), rand, ediv, ltk));
1955 }
1956 
LeEnableEncryption(uint16_t handle,std::array<uint8_t,8> rand,uint16_t ediv,std::array<uint8_t,16> ltk)1957 ErrorCode LinkLayerController::LeEnableEncryption(uint16_t handle,
1958                                                   std::array<uint8_t, 8> rand,
1959                                                   uint16_t ediv,
1960                                                   std::array<uint8_t, 16> ltk) {
1961   if (!connections_.HasHandle(handle)) {
1962     LOG_INFO("Unknown handle %04x", handle);
1963     return ErrorCode::UNKNOWN_CONNECTION;
1964   }
1965 
1966   ScheduleTask(milliseconds(5), [this, handle, rand, ediv, ltk]() {
1967     HandleLeEnableEncryption(handle, rand, ediv, ltk);
1968   });
1969   return ErrorCode::SUCCESS;
1970 }
1971 
SetLeAdvertisingEnable(uint8_t le_advertising_enable)1972 ErrorCode LinkLayerController::SetLeAdvertisingEnable(
1973     uint8_t le_advertising_enable) {
1974   if (!le_advertising_enable) {
1975     advertisers_[0].Disable();
1976     return ErrorCode::SUCCESS;
1977   }
1978   auto interval_ms = (properties_.GetLeAdvertisingIntervalMax() +
1979                       properties_.GetLeAdvertisingIntervalMin()) *
1980                      0.625 / 2;
1981 
1982   Address own_address = properties_.GetAddress();
1983   if (properties_.GetLeAdvertisingOwnAddressType() ==
1984           static_cast<uint8_t>(AddressType::RANDOM_DEVICE_ADDRESS) ||
1985       properties_.GetLeAdvertisingOwnAddressType() ==
1986           static_cast<uint8_t>(AddressType::RANDOM_IDENTITY_ADDRESS)) {
1987     if (properties_.GetLeAddress().ToString() == "bb:bb:bb:ba:d0:1e" ||
1988         properties_.GetLeAddress() == Address::kEmpty) {
1989       return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
1990     }
1991     own_address = properties_.GetLeAddress();
1992   }
1993   auto own_address_with_type = AddressWithType(
1994       own_address, static_cast<bluetooth::hci::AddressType>(
1995                        properties_.GetLeAdvertisingOwnAddressType()));
1996 
1997   auto interval = std::chrono::milliseconds(static_cast<uint64_t>(interval_ms));
1998   if (interval < std::chrono::milliseconds(20)) {
1999     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2000   }
2001   advertisers_[0].Initialize(
2002       own_address_with_type,
2003       bluetooth::hci::AddressWithType(
2004           properties_.GetLeAdvertisingPeerAddress(),
2005           static_cast<bluetooth::hci::AddressType>(
2006               properties_.GetLeAdvertisingPeerAddressType())),
2007       static_cast<bluetooth::hci::LeScanningFilterPolicy>(
2008           properties_.GetLeAdvertisingFilterPolicy()),
2009       static_cast<model::packets::AdvertisementType>(
2010           properties_.GetLeAdvertisementType()),
2011       properties_.GetLeAdvertisement(), properties_.GetLeScanResponse(),
2012       interval);
2013   advertisers_[0].Enable();
2014   return ErrorCode::SUCCESS;
2015 }
2016 
LeDisableAdvertisingSets()2017 void LinkLayerController::LeDisableAdvertisingSets() {
2018   for (auto& advertiser : advertisers_) {
2019     advertiser.Disable();
2020   }
2021 }
2022 
LeReadNumberOfSupportedAdvertisingSets()2023 uint8_t LinkLayerController::LeReadNumberOfSupportedAdvertisingSets() {
2024   return advertisers_.size();
2025 }
2026 
SetLeExtendedAdvertisingEnable(bluetooth::hci::Enable enable,const std::vector<bluetooth::hci::EnabledSet> & enabled_sets)2027 ErrorCode LinkLayerController::SetLeExtendedAdvertisingEnable(
2028     bluetooth::hci::Enable enable,
2029     const std::vector<bluetooth::hci::EnabledSet>& enabled_sets) {
2030   for (const auto& set : enabled_sets) {
2031     if (set.advertising_handle_ > advertisers_.size()) {
2032       return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2033     }
2034   }
2035   for (const auto& set : enabled_sets) {
2036     auto handle = set.advertising_handle_;
2037     if (enable == bluetooth::hci::Enable::ENABLED) {
2038       advertisers_[handle].EnableExtended(
2039           std::chrono::milliseconds(10 * set.duration_));
2040     } else {
2041       advertisers_[handle].Disable();
2042     }
2043   }
2044   return ErrorCode::SUCCESS;
2045 }
2046 
LeConnectListRemoveDevice(Address addr,uint8_t addr_type)2047 void LinkLayerController::LeConnectListRemoveDevice(Address addr,
2048                                                     uint8_t addr_type) {
2049   // TODO: Add checks to see if advertising, scanning, or a connection request
2050   // with the connect list is ongoing.
2051   std::tuple<Address, uint8_t> erase_tuple = std::make_tuple(addr, addr_type);
2052   for (size_t i = 0; i < le_connect_list_.size(); i++) {
2053     if (le_connect_list_[i] == erase_tuple) {
2054       le_connect_list_.erase(le_connect_list_.begin() + i);
2055     }
2056   }
2057 }
2058 
LeResolvingListRemoveDevice(Address addr,uint8_t addr_type)2059 void LinkLayerController::LeResolvingListRemoveDevice(Address addr,
2060                                                       uint8_t addr_type) {
2061   // TODO: Add checks to see if advertising, scanning, or a connection request
2062   // with the connect list is ongoing.
2063   for (size_t i = 0; i < le_connect_list_.size(); i++) {
2064     auto curr = le_connect_list_[i];
2065     if (std::get<0>(curr) == addr && std::get<1>(curr) == addr_type) {
2066       le_resolving_list_.erase(le_resolving_list_.begin() + i);
2067     }
2068   }
2069 }
2070 
LeConnectListContainsDevice(Address addr,uint8_t addr_type)2071 bool LinkLayerController::LeConnectListContainsDevice(Address addr,
2072                                                       uint8_t addr_type) {
2073   std::tuple<Address, uint8_t> sought_tuple = std::make_tuple(addr, addr_type);
2074   for (size_t i = 0; i < le_connect_list_.size(); i++) {
2075     if (le_connect_list_[i] == sought_tuple) {
2076       return true;
2077     }
2078   }
2079   return false;
2080 }
2081 
LeResolvingListContainsDevice(Address addr,uint8_t addr_type)2082 bool LinkLayerController::LeResolvingListContainsDevice(Address addr,
2083                                                         uint8_t addr_type) {
2084   for (size_t i = 0; i < le_connect_list_.size(); i++) {
2085     auto curr = le_connect_list_[i];
2086     if (std::get<0>(curr) == addr && std::get<1>(curr) == addr_type) {
2087       return true;
2088     }
2089   }
2090   return false;
2091 }
2092 
LeConnectListFull()2093 bool LinkLayerController::LeConnectListFull() {
2094   return le_connect_list_.size() >= properties_.GetLeConnectListSize();
2095 }
2096 
LeResolvingListFull()2097 bool LinkLayerController::LeResolvingListFull() {
2098   return le_resolving_list_.size() >= properties_.GetLeResolvingListSize();
2099 }
2100 
Reset()2101 void LinkLayerController::Reset() {
2102   if (inquiry_timer_task_id_ != kInvalidTaskId) {
2103     CancelScheduledTask(inquiry_timer_task_id_);
2104     inquiry_timer_task_id_ = kInvalidTaskId;
2105   }
2106   last_inquiry_ = steady_clock::now();
2107   le_scan_enable_ = bluetooth::hci::OpCode::NONE;
2108   LeDisableAdvertisingSets();
2109   le_connect_ = 0;
2110 }
2111 
StartInquiry(milliseconds timeout)2112 void LinkLayerController::StartInquiry(milliseconds timeout) {
2113   inquiry_timer_task_id_ = ScheduleTask(milliseconds(timeout), [this]() {
2114     LinkLayerController::InquiryTimeout();
2115   });
2116 }
2117 
InquiryCancel()2118 void LinkLayerController::InquiryCancel() {
2119   ASSERT(inquiry_timer_task_id_ != kInvalidTaskId);
2120   CancelScheduledTask(inquiry_timer_task_id_);
2121   inquiry_timer_task_id_ = kInvalidTaskId;
2122 }
2123 
InquiryTimeout()2124 void LinkLayerController::InquiryTimeout() {
2125   if (inquiry_timer_task_id_ != kInvalidTaskId) {
2126     inquiry_timer_task_id_ = kInvalidTaskId;
2127     auto packet =
2128         bluetooth::hci::InquiryCompleteBuilder::Create(ErrorCode::SUCCESS);
2129     send_event_(std::move(packet));
2130   }
2131 }
2132 
SetInquiryMode(uint8_t mode)2133 void LinkLayerController::SetInquiryMode(uint8_t mode) {
2134   inquiry_mode_ = static_cast<model::packets::InquiryType>(mode);
2135 }
2136 
SetInquiryLAP(uint64_t lap)2137 void LinkLayerController::SetInquiryLAP(uint64_t lap) { inquiry_lap_ = lap; }
2138 
SetInquiryMaxResponses(uint8_t max)2139 void LinkLayerController::SetInquiryMaxResponses(uint8_t max) {
2140   inquiry_max_responses_ = max;
2141 }
2142 
Inquiry()2143 void LinkLayerController::Inquiry() {
2144   steady_clock::time_point now = steady_clock::now();
2145   if (duration_cast<milliseconds>(now - last_inquiry_) < milliseconds(2000)) {
2146     return;
2147   }
2148 
2149   auto packet = model::packets::InquiryBuilder::Create(
2150       properties_.GetAddress(), Address::kEmpty, inquiry_mode_);
2151   SendLinkLayerPacket(std::move(packet));
2152   last_inquiry_ = now;
2153 }
2154 
SetInquiryScanEnable(bool enable)2155 void LinkLayerController::SetInquiryScanEnable(bool enable) {
2156   inquiry_scans_enabled_ = enable;
2157 }
2158 
SetPageScanEnable(bool enable)2159 void LinkLayerController::SetPageScanEnable(bool enable) {
2160   page_scans_enabled_ = enable;
2161 }
2162 
2163 }  // namespace test_vendor_lib
2164