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 using namespace model::packets;
31 using model::packets::PacketType;
32 
33 namespace test_vendor_lib {
34 
35 constexpr uint16_t kNumCommandPackets = 0x01;
36 
37 // TODO: Model Rssi?
GetRssi()38 static uint8_t GetRssi() {
39   static uint8_t rssi = 0;
40   rssi += 5;
41   if (rssi > 128) {
42     rssi = rssi % 7;
43   }
44   return -(rssi);
45 }
46 
SendLeLinkLayerPacket(std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet)47 void LinkLayerController::SendLeLinkLayerPacket(
48     std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet) {
49   std::shared_ptr<model::packets::LinkLayerPacketBuilder> shared_packet =
50       std::move(packet);
51   ScheduleTask(milliseconds(50), [this, shared_packet]() {
52     send_to_remote_(shared_packet, Phy::Type::LOW_ENERGY);
53   });
54 }
55 
SendLinkLayerPacket(std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet)56 void LinkLayerController::SendLinkLayerPacket(
57     std::unique_ptr<model::packets::LinkLayerPacketBuilder> packet) {
58   std::shared_ptr<model::packets::LinkLayerPacketBuilder> shared_packet =
59       std::move(packet);
60   ScheduleTask(milliseconds(50), [this, shared_packet]() {
61     send_to_remote_(shared_packet, Phy::Type::BR_EDR);
62   });
63 }
64 
SendLeCommandToRemoteByAddress(OpCode opcode,bluetooth::packet::PacketView<true> args,const Address & remote,const Address & local)65 ErrorCode LinkLayerController::SendLeCommandToRemoteByAddress(
66     OpCode opcode, bluetooth::packet::PacketView<true> args,
67     const Address& remote, const Address& local) {
68   switch (opcode) {
69     case (OpCode::LE_READ_REMOTE_FEATURES):
70       SendLinkLayerPacket(
71           model::packets::LeReadRemoteFeaturesBuilder::Create(local, remote));
72       break;
73     default:
74       LOG_INFO("Dropping unhandled command 0x%04x",
75                static_cast<uint16_t>(opcode));
76       return ErrorCode::UNKNOWN_HCI_COMMAND;
77   }
78 
79   return ErrorCode::SUCCESS;
80 }
81 
SendCommandToRemoteByAddress(OpCode opcode,bluetooth::packet::PacketView<true> args,const Address & remote)82 ErrorCode LinkLayerController::SendCommandToRemoteByAddress(
83     OpCode opcode, bluetooth::packet::PacketView<true> args,
84     const Address& remote) {
85   Address local_address = properties_.GetAddress();
86 
87   switch (opcode) {
88     case (OpCode::REMOTE_NAME_REQUEST):
89       // LMP features get requested with remote name requests.
90       SendLinkLayerPacket(model::packets::ReadRemoteLmpFeaturesBuilder::Create(
91           local_address, remote));
92       SendLinkLayerPacket(model::packets::RemoteNameRequestBuilder::Create(
93           local_address, remote));
94       break;
95     case (OpCode::READ_REMOTE_SUPPORTED_FEATURES):
96       SendLinkLayerPacket(
97           model::packets::ReadRemoteSupportedFeaturesBuilder::Create(
98               local_address, remote));
99       break;
100     case (OpCode::READ_REMOTE_EXTENDED_FEATURES): {
101       uint8_t page_number =
102           (args.begin() + 2).extract<uint8_t>();  // skip the handle
103       SendLinkLayerPacket(
104           model::packets::ReadRemoteExtendedFeaturesBuilder::Create(
105               local_address, remote, page_number));
106     } break;
107     case (OpCode::READ_REMOTE_VERSION_INFORMATION):
108       SendLinkLayerPacket(
109           model::packets::ReadRemoteVersionInformationBuilder::Create(
110               local_address, remote));
111       break;
112     case (OpCode::READ_CLOCK_OFFSET):
113       SendLinkLayerPacket(model::packets::ReadClockOffsetBuilder::Create(
114           local_address, remote));
115       break;
116     default:
117       LOG_INFO("Dropping unhandled command 0x%04x",
118                static_cast<uint16_t>(opcode));
119       return ErrorCode::UNKNOWN_HCI_COMMAND;
120   }
121 
122   return ErrorCode::SUCCESS;
123 }
124 
SendCommandToRemoteByHandle(OpCode opcode,bluetooth::packet::PacketView<true> args,uint16_t handle)125 ErrorCode LinkLayerController::SendCommandToRemoteByHandle(
126     OpCode opcode, bluetooth::packet::PacketView<true> args, uint16_t handle) {
127   if (!connections_.HasHandle(handle)) {
128     return ErrorCode::UNKNOWN_CONNECTION;
129   }
130 
131   switch (opcode) {
132     case (OpCode::LE_READ_REMOTE_FEATURES):
133       return SendLeCommandToRemoteByAddress(
134           opcode, args, connections_.GetAddress(handle).GetAddress(),
135           connections_.GetOwnAddress(handle).GetAddress());
136     default:
137       return SendCommandToRemoteByAddress(
138           opcode, args, connections_.GetAddress(handle).GetAddress());
139   }
140 }
141 
SendAclToRemote(bluetooth::hci::AclView acl_packet)142 ErrorCode LinkLayerController::SendAclToRemote(
143     bluetooth::hci::AclView acl_packet) {
144   uint16_t handle = acl_packet.GetHandle();
145   if (!connections_.HasHandle(handle)) {
146     return ErrorCode::UNKNOWN_CONNECTION;
147   }
148 
149   AddressWithType my_address = connections_.GetOwnAddress(handle);
150   AddressWithType destination = connections_.GetAddress(handle);
151   Phy::Type phy = connections_.GetPhyType(handle);
152 
153   ScheduleTask(milliseconds(1), [this, handle]() {
154     std::vector<bluetooth::hci::CompletedPackets> completed_packets;
155     bluetooth::hci::CompletedPackets cp;
156     cp.connection_handle_ = handle;
157     cp.host_num_of_completed_packets_ = kNumCommandPackets;
158     completed_packets.push_back(cp);
159     auto packet = bluetooth::hci::NumberOfCompletedPacketsBuilder::Create(
160         completed_packets);
161     send_event_(std::move(packet));
162   });
163 
164   auto acl_payload = acl_packet.GetPayload();
165 
166   std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
167       std::make_unique<bluetooth::packet::RawBuilder>();
168   std::vector<uint8_t> payload_bytes(acl_payload.begin(), acl_payload.end());
169 
170   uint16_t first_two_bytes =
171       static_cast<uint16_t>(acl_packet.GetHandle()) +
172       (static_cast<uint16_t>(acl_packet.GetPacketBoundaryFlag()) << 12) +
173       (static_cast<uint16_t>(acl_packet.GetBroadcastFlag()) << 14);
174   raw_builder_ptr->AddOctets2(first_two_bytes);
175   raw_builder_ptr->AddOctets2(static_cast<uint16_t>(payload_bytes.size()));
176   raw_builder_ptr->AddOctets(payload_bytes);
177 
178   auto acl = model::packets::AclBuilder::Create(my_address.GetAddress(),
179                                                 destination.GetAddress(),
180                                                 std::move(raw_builder_ptr));
181 
182   switch (phy) {
183     case Phy::Type::BR_EDR:
184       SendLinkLayerPacket(std::move(acl));
185       break;
186     case Phy::Type::LOW_ENERGY:
187       SendLeLinkLayerPacket(std::move(acl));
188       break;
189   }
190   return ErrorCode::SUCCESS;
191 }
192 
IncomingPacket(model::packets::LinkLayerPacketView incoming)193 void LinkLayerController::IncomingPacket(
194     model::packets::LinkLayerPacketView incoming) {
195   ASSERT(incoming.IsValid());
196   auto destination_address = incoming.GetDestinationAddress();
197 
198   // Match broadcasts
199   bool address_matches = (destination_address == Address::kEmpty);
200 
201   // Match addresses from device properties
202   if (destination_address == properties_.GetAddress() ||
203       destination_address == properties_.GetLeAddress()) {
204     address_matches = true;
205   }
206 
207   // Check advertising addresses
208   for (const auto& advertiser : advertisers_) {
209     if (advertiser.IsEnabled() &&
210         advertiser.GetAddress().GetAddress() == destination_address) {
211       address_matches = true;
212     }
213   }
214 
215   // Check connection addresses
216   if (connections_.GetHandleOnlyAddress(destination_address) !=
217       kReservedHandle) {
218     address_matches = true;
219   }
220 
221   // Drop packets not addressed to me
222   if (!address_matches) {
223     return;
224   }
225 
226   switch (incoming.GetType()) {
227     case model::packets::PacketType::ACL:
228       IncomingAclPacket(incoming);
229       break;
230     case model::packets::PacketType::DISCONNECT:
231       IncomingDisconnectPacket(incoming);
232       break;
233     case model::packets::PacketType::ENCRYPT_CONNECTION:
234       IncomingEncryptConnection(incoming);
235       break;
236     case model::packets::PacketType::ENCRYPT_CONNECTION_RESPONSE:
237       IncomingEncryptConnectionResponse(incoming);
238       break;
239     case model::packets::PacketType::INQUIRY:
240       if (inquiry_scans_enabled_) {
241         IncomingInquiryPacket(incoming);
242       }
243       break;
244     case model::packets::PacketType::INQUIRY_RESPONSE:
245       IncomingInquiryResponsePacket(incoming);
246       break;
247     case model::packets::PacketType::IO_CAPABILITY_REQUEST:
248       IncomingIoCapabilityRequestPacket(incoming);
249       break;
250     case model::packets::PacketType::IO_CAPABILITY_RESPONSE:
251       IncomingIoCapabilityResponsePacket(incoming);
252       break;
253     case model::packets::PacketType::IO_CAPABILITY_NEGATIVE_RESPONSE:
254       IncomingIoCapabilityNegativeResponsePacket(incoming);
255       break;
256     case PacketType::ISO:
257       IncomingIsoPacket(incoming);
258       break;
259     case PacketType::ISO_CONNECTION_REQUEST:
260       IncomingIsoConnectionRequestPacket(incoming);
261       break;
262     case PacketType::ISO_CONNECTION_RESPONSE:
263       IncomingIsoConnectionResponsePacket(incoming);
264       break;
265     case PacketType::KEYPRESS_NOTIFICATION:
266       IncomingKeypressNotificationPacket(incoming);
267       break;
268     case model::packets::PacketType::LE_ADVERTISEMENT:
269       if (le_scan_enable_ != bluetooth::hci::OpCode::NONE || le_connect_) {
270         IncomingLeAdvertisementPacket(incoming);
271       }
272       break;
273     case model::packets::PacketType::LE_CONNECT:
274       IncomingLeConnectPacket(incoming);
275       break;
276     case model::packets::PacketType::LE_CONNECT_COMPLETE:
277       IncomingLeConnectCompletePacket(incoming);
278       break;
279     case model::packets::PacketType::LE_ENCRYPT_CONNECTION:
280       IncomingLeEncryptConnection(incoming);
281       break;
282     case model::packets::PacketType::LE_ENCRYPT_CONNECTION_RESPONSE:
283       IncomingLeEncryptConnectionResponse(incoming);
284       break;
285     case (model::packets::PacketType::LE_READ_REMOTE_FEATURES):
286       IncomingLeReadRemoteFeatures(incoming);
287       break;
288     case (model::packets::PacketType::LE_READ_REMOTE_FEATURES_RESPONSE):
289       IncomingLeReadRemoteFeaturesResponse(incoming);
290       break;
291     case model::packets::PacketType::LE_SCAN:
292       // TODO: Check Advertising flags and see if we are scannable.
293       IncomingLeScanPacket(incoming);
294       break;
295     case model::packets::PacketType::LE_SCAN_RESPONSE:
296       if (le_scan_enable_ != bluetooth::hci::OpCode::NONE &&
297           le_scan_type_ == 1) {
298         IncomingLeScanResponsePacket(incoming);
299       }
300       break;
301     case model::packets::PacketType::PAGE:
302       if (page_scans_enabled_) {
303         IncomingPagePacket(incoming);
304       }
305       break;
306     case model::packets::PacketType::PAGE_RESPONSE:
307       IncomingPageResponsePacket(incoming);
308       break;
309     case model::packets::PacketType::PAGE_REJECT:
310       IncomingPageRejectPacket(incoming);
311       break;
312     case (model::packets::PacketType::PASSKEY):
313       IncomingPasskeyPacket(incoming);
314       break;
315     case (model::packets::PacketType::PASSKEY_FAILED):
316       IncomingPasskeyFailedPacket(incoming);
317       break;
318     case (model::packets::PacketType::PIN_REQUEST):
319       IncomingPinRequestPacket(incoming);
320       break;
321     case (model::packets::PacketType::PIN_RESPONSE):
322       IncomingPinResponsePacket(incoming);
323       break;
324     case (model::packets::PacketType::REMOTE_NAME_REQUEST):
325       IncomingRemoteNameRequest(incoming);
326       break;
327     case (model::packets::PacketType::REMOTE_NAME_REQUEST_RESPONSE):
328       IncomingRemoteNameRequestResponse(incoming);
329       break;
330     case (model::packets::PacketType::READ_REMOTE_SUPPORTED_FEATURES):
331       IncomingReadRemoteSupportedFeatures(incoming);
332       break;
333     case (model::packets::PacketType::READ_REMOTE_SUPPORTED_FEATURES_RESPONSE):
334       IncomingReadRemoteSupportedFeaturesResponse(incoming);
335       break;
336     case (model::packets::PacketType::READ_REMOTE_LMP_FEATURES):
337       IncomingReadRemoteLmpFeatures(incoming);
338       break;
339     case (model::packets::PacketType::READ_REMOTE_LMP_FEATURES_RESPONSE):
340       IncomingReadRemoteLmpFeaturesResponse(incoming);
341       break;
342     case (model::packets::PacketType::READ_REMOTE_EXTENDED_FEATURES):
343       IncomingReadRemoteExtendedFeatures(incoming);
344       break;
345     case (model::packets::PacketType::READ_REMOTE_EXTENDED_FEATURES_RESPONSE):
346       IncomingReadRemoteExtendedFeaturesResponse(incoming);
347       break;
348     case (model::packets::PacketType::READ_REMOTE_VERSION_INFORMATION):
349       IncomingReadRemoteVersion(incoming);
350       break;
351     case (model::packets::PacketType::READ_REMOTE_VERSION_INFORMATION_RESPONSE):
352       IncomingReadRemoteVersionResponse(incoming);
353       break;
354     case (model::packets::PacketType::READ_CLOCK_OFFSET):
355       IncomingReadClockOffset(incoming);
356       break;
357     case (model::packets::PacketType::READ_CLOCK_OFFSET_RESPONSE):
358       IncomingReadClockOffsetResponse(incoming);
359       break;
360     default:
361       LOG_WARN("Dropping unhandled packet of type %s",
362                model::packets::PacketTypeText(incoming.GetType()).c_str());
363   }
364 }
365 
IncomingAclPacket(model::packets::LinkLayerPacketView incoming)366 void LinkLayerController::IncomingAclPacket(
367     model::packets::LinkLayerPacketView incoming) {
368   LOG_INFO("Acl Packet %s -> %s",
369            incoming.GetSourceAddress().ToString().c_str(),
370            incoming.GetDestinationAddress().ToString().c_str());
371 
372   auto acl = model::packets::AclView::Create(incoming);
373   ASSERT(acl.IsValid());
374   auto payload = acl.GetPayload();
375   std::shared_ptr<std::vector<uint8_t>> payload_bytes =
376       std::make_shared<std::vector<uint8_t>>(payload.begin(), payload.end());
377 
378   bluetooth::hci::PacketView<bluetooth::hci::kLittleEndian> raw_packet(
379       payload_bytes);
380   auto acl_view = bluetooth::hci::AclView::Create(raw_packet);
381   ASSERT(acl_view.IsValid());
382 
383   LOG_INFO("Remote handle 0x%x size %d", acl_view.GetHandle(),
384            static_cast<int>(acl_view.size()));
385   uint16_t local_handle =
386       connections_.GetHandleOnlyAddress(incoming.GetSourceAddress());
387   LOG_INFO("Local handle 0x%x", local_handle);
388 
389   std::vector<uint8_t> payload_data(acl_view.GetPayload().begin(),
390                                     acl_view.GetPayload().end());
391   uint16_t acl_buffer_size = properties_.GetAclDataPacketSize();
392   int num_packets =
393       (payload_data.size() + acl_buffer_size - 1) / acl_buffer_size;
394 
395   auto pb_flag_controller_to_host = acl_view.GetPacketBoundaryFlag();
396   if (pb_flag_controller_to_host ==
397       bluetooth::hci::PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE) {
398     pb_flag_controller_to_host =
399         bluetooth::hci::PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE;
400   }
401   for (int i = 0; i < num_packets; i++) {
402     size_t start_index = acl_buffer_size * i;
403     size_t end_index =
404         std::min(start_index + acl_buffer_size, payload_data.size());
405     std::vector<uint8_t> fragment(&payload_data[start_index],
406                                   &payload_data[end_index]);
407     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
408         std::make_unique<bluetooth::packet::RawBuilder>(fragment);
409     auto acl_packet = bluetooth::hci::AclBuilder::Create(
410         local_handle, pb_flag_controller_to_host, acl_view.GetBroadcastFlag(),
411         std::move(raw_builder_ptr));
412     pb_flag_controller_to_host =
413         bluetooth::hci::PacketBoundaryFlag::CONTINUING_FRAGMENT;
414 
415     send_acl_(std::move(acl_packet));
416   }
417 }
418 
IncomingRemoteNameRequest(model::packets::LinkLayerPacketView packet)419 void LinkLayerController::IncomingRemoteNameRequest(
420     model::packets::LinkLayerPacketView packet) {
421   auto view = model::packets::RemoteNameRequestView::Create(packet);
422   ASSERT(view.IsValid());
423 
424   SendLinkLayerPacket(model::packets::RemoteNameRequestResponseBuilder::Create(
425       packet.GetDestinationAddress(), packet.GetSourceAddress(),
426       properties_.GetName()));
427 }
428 
IncomingRemoteNameRequestResponse(model::packets::LinkLayerPacketView packet)429 void LinkLayerController::IncomingRemoteNameRequestResponse(
430     model::packets::LinkLayerPacketView packet) {
431   auto view = model::packets::RemoteNameRequestResponseView::Create(packet);
432   ASSERT(view.IsValid());
433 
434   send_event_(bluetooth::hci::RemoteNameRequestCompleteBuilder::Create(
435       ErrorCode::SUCCESS, packet.GetSourceAddress(), view.GetName()));
436 }
437 
IncomingReadRemoteLmpFeatures(model::packets::LinkLayerPacketView packet)438 void LinkLayerController::IncomingReadRemoteLmpFeatures(
439     model::packets::LinkLayerPacketView packet) {
440   SendLinkLayerPacket(
441       model::packets::ReadRemoteLmpFeaturesResponseBuilder::Create(
442           packet.GetDestinationAddress(), packet.GetSourceAddress(),
443           properties_.GetExtendedFeatures(1)));
444 }
445 
IncomingReadRemoteLmpFeaturesResponse(model::packets::LinkLayerPacketView packet)446 void LinkLayerController::IncomingReadRemoteLmpFeaturesResponse(
447     model::packets::LinkLayerPacketView packet) {
448   auto view = model::packets::ReadRemoteLmpFeaturesResponseView::Create(packet);
449   ASSERT(view.IsValid());
450   send_event_(
451       bluetooth::hci::RemoteHostSupportedFeaturesNotificationBuilder::Create(
452           packet.GetSourceAddress(), view.GetFeatures()));
453 }
454 
IncomingReadRemoteSupportedFeatures(model::packets::LinkLayerPacketView packet)455 void LinkLayerController::IncomingReadRemoteSupportedFeatures(
456     model::packets::LinkLayerPacketView packet) {
457   SendLinkLayerPacket(
458       model::packets::ReadRemoteSupportedFeaturesResponseBuilder::Create(
459           packet.GetDestinationAddress(), packet.GetSourceAddress(),
460           properties_.GetSupportedFeatures()));
461 }
462 
IncomingReadRemoteSupportedFeaturesResponse(model::packets::LinkLayerPacketView packet)463 void LinkLayerController::IncomingReadRemoteSupportedFeaturesResponse(
464     model::packets::LinkLayerPacketView packet) {
465   auto view =
466       model::packets::ReadRemoteSupportedFeaturesResponseView::Create(packet);
467   ASSERT(view.IsValid());
468   Address source = packet.GetSourceAddress();
469   uint16_t handle = connections_.GetHandleOnlyAddress(source);
470   if (handle == kReservedHandle) {
471     LOG_INFO("Discarding response from a disconnected device %s",
472              source.ToString().c_str());
473     return;
474   }
475   send_event_(
476       bluetooth::hci::ReadRemoteSupportedFeaturesCompleteBuilder::Create(
477           ErrorCode::SUCCESS, handle, view.GetFeatures()));
478 }
479 
IncomingReadRemoteExtendedFeatures(model::packets::LinkLayerPacketView packet)480 void LinkLayerController::IncomingReadRemoteExtendedFeatures(
481     model::packets::LinkLayerPacketView packet) {
482   auto view = model::packets::ReadRemoteExtendedFeaturesView::Create(packet);
483   ASSERT(view.IsValid());
484   uint8_t page_number = view.GetPageNumber();
485   uint8_t error_code = static_cast<uint8_t>(ErrorCode::SUCCESS);
486   if (page_number > properties_.GetExtendedFeaturesMaximumPageNumber()) {
487     error_code = static_cast<uint8_t>(ErrorCode::INVALID_LMP_OR_LL_PARAMETERS);
488   }
489   SendLinkLayerPacket(
490       model::packets::ReadRemoteExtendedFeaturesResponseBuilder::Create(
491           packet.GetDestinationAddress(), packet.GetSourceAddress(), error_code,
492           page_number, properties_.GetExtendedFeaturesMaximumPageNumber(),
493           properties_.GetExtendedFeatures(view.GetPageNumber())));
494 }
495 
IncomingReadRemoteExtendedFeaturesResponse(model::packets::LinkLayerPacketView packet)496 void LinkLayerController::IncomingReadRemoteExtendedFeaturesResponse(
497     model::packets::LinkLayerPacketView packet) {
498   auto view =
499       model::packets::ReadRemoteExtendedFeaturesResponseView::Create(packet);
500   ASSERT(view.IsValid());
501   Address source = packet.GetSourceAddress();
502   uint16_t handle = connections_.GetHandleOnlyAddress(source);
503   if (handle == kReservedHandle) {
504     LOG_INFO("Discarding response from a disconnected device %s",
505              source.ToString().c_str());
506     return;
507   }
508   send_event_(bluetooth::hci::ReadRemoteExtendedFeaturesCompleteBuilder::Create(
509       static_cast<ErrorCode>(view.GetStatus()), handle, view.GetPageNumber(),
510       view.GetMaxPageNumber(), view.GetFeatures()));
511 }
512 
IncomingReadRemoteVersion(model::packets::LinkLayerPacketView packet)513 void LinkLayerController::IncomingReadRemoteVersion(
514     model::packets::LinkLayerPacketView packet) {
515   SendLinkLayerPacket(
516       model::packets::ReadRemoteVersionInformationResponseBuilder::Create(
517           packet.GetDestinationAddress(), packet.GetSourceAddress(),
518           properties_.GetLmpPalVersion(), properties_.GetLmpPalSubversion(),
519           properties_.GetManufacturerName()));
520 }
521 
IncomingReadRemoteVersionResponse(model::packets::LinkLayerPacketView packet)522 void LinkLayerController::IncomingReadRemoteVersionResponse(
523     model::packets::LinkLayerPacketView packet) {
524   auto view =
525       model::packets::ReadRemoteVersionInformationResponseView::Create(packet);
526   ASSERT(view.IsValid());
527   Address source = packet.GetSourceAddress();
528   uint16_t handle = connections_.GetHandleOnlyAddress(source);
529   if (handle == kReservedHandle) {
530     LOG_INFO("Discarding response from a disconnected device %s",
531              source.ToString().c_str());
532     return;
533   }
534   send_event_(
535       bluetooth::hci::ReadRemoteVersionInformationCompleteBuilder::Create(
536           ErrorCode::SUCCESS, handle, view.GetLmpVersion(),
537           view.GetManufacturerName(), view.GetLmpSubversion()));
538 }
539 
IncomingReadClockOffset(model::packets::LinkLayerPacketView packet)540 void LinkLayerController::IncomingReadClockOffset(
541     model::packets::LinkLayerPacketView packet) {
542   SendLinkLayerPacket(model::packets::ReadClockOffsetResponseBuilder::Create(
543       packet.GetDestinationAddress(), packet.GetSourceAddress(),
544       properties_.GetClockOffset()));
545 }
546 
IncomingReadClockOffsetResponse(model::packets::LinkLayerPacketView packet)547 void LinkLayerController::IncomingReadClockOffsetResponse(
548     model::packets::LinkLayerPacketView packet) {
549   auto view = model::packets::ReadClockOffsetResponseView::Create(packet);
550   ASSERT(view.IsValid());
551   Address source = packet.GetSourceAddress();
552   uint16_t handle = connections_.GetHandleOnlyAddress(source);
553   if (handle == kReservedHandle) {
554     LOG_INFO("Discarding response from a disconnected device %s",
555              source.ToString().c_str());
556     return;
557   }
558   send_event_(bluetooth::hci::ReadClockOffsetCompleteBuilder::Create(
559       ErrorCode::SUCCESS, handle, view.GetOffset()));
560 }
561 
IncomingDisconnectPacket(model::packets::LinkLayerPacketView incoming)562 void LinkLayerController::IncomingDisconnectPacket(
563     model::packets::LinkLayerPacketView incoming) {
564   LOG_INFO("Disconnect Packet");
565   auto disconnect = model::packets::DisconnectView::Create(incoming);
566   ASSERT(disconnect.IsValid());
567 
568   Address peer = incoming.GetSourceAddress();
569   uint16_t handle = connections_.GetHandleOnlyAddress(peer);
570   if (handle == kReservedHandle) {
571     LOG_INFO("Discarding disconnect from a disconnected device %s",
572              peer.ToString().c_str());
573     return;
574   }
575   ASSERT_LOG(connections_.Disconnect(handle),
576              "GetHandle() returned invalid handle %hx", handle);
577 
578   uint8_t reason = disconnect.GetReason();
579   ScheduleTask(milliseconds(20),
580                [this, handle, reason]() { DisconnectCleanup(handle, reason); });
581 }
582 
IncomingEncryptConnection(model::packets::LinkLayerPacketView incoming)583 void LinkLayerController::IncomingEncryptConnection(
584     model::packets::LinkLayerPacketView incoming) {
585   LOG_INFO();
586 
587   // TODO: Check keys
588   Address peer = incoming.GetSourceAddress();
589   uint16_t handle = connections_.GetHandleOnlyAddress(peer);
590   if (handle == kReservedHandle) {
591     LOG_INFO("Unknown connection @%s", peer.ToString().c_str());
592     return;
593   }
594   send_event_(bluetooth::hci::EncryptionChangeBuilder::Create(
595       ErrorCode::SUCCESS, handle, bluetooth::hci::EncryptionEnabled::ON));
596 
597   uint16_t count = security_manager_.ReadKey(peer);
598   if (count == 0) {
599     LOG_ERROR("NO KEY HERE for %s", peer.ToString().c_str());
600     return;
601   }
602   auto array = security_manager_.GetKey(peer);
603   std::vector<uint8_t> key_vec{array.begin(), array.end()};
604   auto response = model::packets::EncryptConnectionResponseBuilder::Create(
605       properties_.GetAddress(), peer, key_vec);
606   SendLinkLayerPacket(std::move(response));
607 }
608 
IncomingEncryptConnectionResponse(model::packets::LinkLayerPacketView incoming)609 void LinkLayerController::IncomingEncryptConnectionResponse(
610     model::packets::LinkLayerPacketView incoming) {
611   LOG_INFO();
612   // TODO: Check keys
613   uint16_t handle =
614       connections_.GetHandleOnlyAddress(incoming.GetSourceAddress());
615   if (handle == kReservedHandle) {
616     LOG_INFO("Unknown connection @%s",
617              incoming.GetSourceAddress().ToString().c_str());
618     return;
619   }
620   auto packet = bluetooth::hci::EncryptionChangeBuilder::Create(
621       ErrorCode::SUCCESS, handle, bluetooth::hci::EncryptionEnabled::ON);
622   send_event_(std::move(packet));
623 }
624 
IncomingInquiryPacket(model::packets::LinkLayerPacketView incoming)625 void LinkLayerController::IncomingInquiryPacket(
626     model::packets::LinkLayerPacketView incoming) {
627   auto inquiry = model::packets::InquiryView::Create(incoming);
628   ASSERT(inquiry.IsValid());
629 
630   Address peer = incoming.GetSourceAddress();
631 
632   switch (inquiry.GetInquiryType()) {
633     case (model::packets::InquiryType::STANDARD): {
634       auto inquiry_response = model::packets::InquiryResponseBuilder::Create(
635           properties_.GetAddress(), peer,
636           properties_.GetPageScanRepetitionMode(),
637           properties_.GetClassOfDevice(), properties_.GetClockOffset());
638       SendLinkLayerPacket(std::move(inquiry_response));
639     } break;
640     case (model::packets::InquiryType::RSSI): {
641       auto inquiry_response =
642           model::packets::InquiryResponseWithRssiBuilder::Create(
643               properties_.GetAddress(), peer,
644               properties_.GetPageScanRepetitionMode(),
645               properties_.GetClassOfDevice(), properties_.GetClockOffset(),
646               GetRssi());
647       SendLinkLayerPacket(std::move(inquiry_response));
648     } break;
649     case (model::packets::InquiryType::EXTENDED): {
650       auto inquiry_response =
651           model::packets::ExtendedInquiryResponseBuilder::Create(
652               properties_.GetAddress(), peer,
653               properties_.GetPageScanRepetitionMode(),
654               properties_.GetClassOfDevice(), properties_.GetClockOffset(),
655               GetRssi(), properties_.GetExtendedInquiryData());
656       SendLinkLayerPacket(std::move(inquiry_response));
657 
658     } break;
659     default:
660       LOG_WARN("Unhandled Incoming Inquiry of type %d",
661                static_cast<int>(inquiry.GetType()));
662       return;
663   }
664   // TODO: Send an Inquiry Response Notification Event 7.7.74
665 }
666 
IncomingInquiryResponsePacket(model::packets::LinkLayerPacketView incoming)667 void LinkLayerController::IncomingInquiryResponsePacket(
668     model::packets::LinkLayerPacketView incoming) {
669   auto basic_inquiry_response =
670       model::packets::BasicInquiryResponseView::Create(incoming);
671   ASSERT(basic_inquiry_response.IsValid());
672   std::vector<uint8_t> eir;
673 
674   switch (basic_inquiry_response.GetInquiryType()) {
675     case (model::packets::InquiryType::STANDARD): {
676       // TODO: Support multiple inquiries in the same packet.
677       auto inquiry_response =
678           model::packets::InquiryResponseView::Create(basic_inquiry_response);
679       ASSERT(inquiry_response.IsValid());
680 
681       auto page_scan_repetition_mode =
682           (bluetooth::hci::PageScanRepetitionMode)
683               inquiry_response.GetPageScanRepetitionMode();
684 
685       std::vector<bluetooth::hci::InquiryResult> responses;
686       responses.emplace_back();
687       responses.back().bd_addr_ = inquiry_response.GetSourceAddress();
688       responses.back().page_scan_repetition_mode_ = page_scan_repetition_mode;
689       responses.back().class_of_device_ = inquiry_response.GetClassOfDevice();
690       responses.back().clock_offset_ = inquiry_response.GetClockOffset();
691       auto packet = bluetooth::hci::InquiryResultBuilder::Create(responses);
692       send_event_(std::move(packet));
693     } break;
694 
695     case (model::packets::InquiryType::RSSI): {
696       auto inquiry_response =
697           model::packets::InquiryResponseWithRssiView::Create(
698               basic_inquiry_response);
699       ASSERT(inquiry_response.IsValid());
700 
701       auto page_scan_repetition_mode =
702           (bluetooth::hci::PageScanRepetitionMode)
703               inquiry_response.GetPageScanRepetitionMode();
704 
705       std::vector<bluetooth::hci::InquiryResultWithRssi> responses;
706       responses.emplace_back();
707       responses.back().address_ = inquiry_response.GetSourceAddress();
708       responses.back().page_scan_repetition_mode_ = page_scan_repetition_mode;
709       responses.back().class_of_device_ = inquiry_response.GetClassOfDevice();
710       responses.back().clock_offset_ = inquiry_response.GetClockOffset();
711       responses.back().rssi_ = inquiry_response.GetRssi();
712       auto packet =
713           bluetooth::hci::InquiryResultWithRssiBuilder::Create(responses);
714       send_event_(std::move(packet));
715     } break;
716 
717     case (model::packets::InquiryType::EXTENDED): {
718       auto inquiry_response =
719           model::packets::ExtendedInquiryResponseView::Create(
720               basic_inquiry_response);
721       ASSERT(inquiry_response.IsValid());
722 
723       std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
724           std::make_unique<bluetooth::packet::RawBuilder>();
725       raw_builder_ptr->AddOctets1(kNumCommandPackets);
726       raw_builder_ptr->AddAddress(inquiry_response.GetSourceAddress());
727       raw_builder_ptr->AddOctets1(inquiry_response.GetPageScanRepetitionMode());
728       raw_builder_ptr->AddOctets1(0x00);  // _reserved_
729       auto class_of_device = inquiry_response.GetClassOfDevice();
730       for (unsigned int i = 0; i < class_of_device.kLength; i++) {
731         raw_builder_ptr->AddOctets1(class_of_device.cod[i]);
732       }
733       raw_builder_ptr->AddOctets2(inquiry_response.GetClockOffset());
734       raw_builder_ptr->AddOctets1(inquiry_response.GetRssi());
735       raw_builder_ptr->AddOctets(inquiry_response.GetExtendedData());
736 
737       auto packet = bluetooth::hci::EventBuilder::Create(
738           bluetooth::hci::EventCode::EXTENDED_INQUIRY_RESULT,
739           std::move(raw_builder_ptr));
740       send_event_(std::move(packet));
741     } break;
742     default:
743       LOG_WARN("Unhandled Incoming Inquiry Response of type %d",
744                static_cast<int>(basic_inquiry_response.GetInquiryType()));
745   }
746 }
747 
IncomingIoCapabilityRequestPacket(model::packets::LinkLayerPacketView incoming)748 void LinkLayerController::IncomingIoCapabilityRequestPacket(
749     model::packets::LinkLayerPacketView incoming) {
750   Address peer = incoming.GetSourceAddress();
751   uint16_t handle = connections_.GetHandle(AddressWithType(
752       peer, bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS));
753   if (handle == kReservedHandle) {
754     LOG_INFO("Device not connected %s", peer.ToString().c_str());
755     return;
756   }
757 
758   if (!properties_.GetSecureSimplePairingSupported()) {
759     LOG_WARN("Trying PIN pairing for %s",
760              incoming.GetDestinationAddress().ToString().c_str());
761     SendLinkLayerPacket(
762         model::packets::IoCapabilityNegativeResponseBuilder::Create(
763             incoming.GetDestinationAddress(), incoming.GetSourceAddress(),
764             static_cast<uint8_t>(
765                 ErrorCode::UNSUPPORTED_REMOTE_OR_LMP_FEATURE)));
766     security_manager_.AuthenticationRequest(incoming.GetSourceAddress(),
767                                             handle);
768     security_manager_.SetPinRequested(peer);
769     send_event_(bluetooth::hci::PinCodeRequestBuilder::Create(
770         incoming.GetSourceAddress()));
771     return;
772   }
773 
774   auto request = model::packets::IoCapabilityRequestView::Create(incoming);
775   ASSERT(request.IsValid());
776 
777   uint8_t io_capability = request.GetIoCapability();
778   uint8_t oob_data_present = request.GetOobDataPresent();
779   uint8_t authentication_requirements = request.GetAuthenticationRequirements();
780 
781   auto packet = bluetooth::hci::IoCapabilityResponseBuilder::Create(
782       peer, static_cast<bluetooth::hci::IoCapability>(io_capability),
783       static_cast<bluetooth::hci::OobDataPresent>(oob_data_present),
784       static_cast<bluetooth::hci::AuthenticationRequirements>(
785           authentication_requirements));
786   send_event_(std::move(packet));
787 
788   bool pairing_started = security_manager_.AuthenticationInProgress();
789   if (!pairing_started) {
790     security_manager_.AuthenticationRequest(peer, handle);
791     StartSimplePairing(peer);
792   }
793 
794   security_manager_.SetPeerIoCapability(peer, io_capability, oob_data_present,
795                                         authentication_requirements);
796   if (pairing_started) {
797     PairingType pairing_type = security_manager_.GetSimplePairingType();
798     if (pairing_type != PairingType::INVALID) {
799       ScheduleTask(milliseconds(5), [this, peer, pairing_type]() {
800         AuthenticateRemoteStage1(peer, pairing_type);
801       });
802     } else {
803       LOG_INFO("Security Manager returned INVALID");
804     }
805   }
806 }
807 
IncomingIoCapabilityResponsePacket(model::packets::LinkLayerPacketView incoming)808 void LinkLayerController::IncomingIoCapabilityResponsePacket(
809     model::packets::LinkLayerPacketView incoming) {
810   auto response = model::packets::IoCapabilityResponseView::Create(incoming);
811   ASSERT(response.IsValid());
812   if (!properties_.GetSecureSimplePairingSupported()) {
813     LOG_WARN("Only simple pairing mode is implemented");
814     SendLinkLayerPacket(
815         model::packets::IoCapabilityNegativeResponseBuilder::Create(
816             incoming.GetDestinationAddress(), incoming.GetSourceAddress(),
817             static_cast<uint8_t>(
818                 ErrorCode::UNSUPPORTED_REMOTE_OR_LMP_FEATURE)));
819     return;
820   }
821 
822   Address peer = incoming.GetSourceAddress();
823   uint8_t io_capability = response.GetIoCapability();
824   uint8_t oob_data_present = response.GetOobDataPresent();
825   uint8_t authentication_requirements =
826       response.GetAuthenticationRequirements();
827 
828   security_manager_.SetPeerIoCapability(peer, io_capability, oob_data_present,
829                                         authentication_requirements);
830 
831   auto packet = bluetooth::hci::IoCapabilityResponseBuilder::Create(
832       peer, static_cast<bluetooth::hci::IoCapability>(io_capability),
833       static_cast<bluetooth::hci::OobDataPresent>(oob_data_present),
834       static_cast<bluetooth::hci::AuthenticationRequirements>(
835           authentication_requirements));
836   send_event_(std::move(packet));
837 
838   PairingType pairing_type = security_manager_.GetSimplePairingType();
839   if (pairing_type != PairingType::INVALID) {
840     ScheduleTask(milliseconds(5), [this, peer, pairing_type]() {
841       AuthenticateRemoteStage1(peer, pairing_type);
842     });
843   } else {
844     LOG_INFO("Security Manager returned INVALID");
845   }
846 }
847 
IncomingIoCapabilityNegativeResponsePacket(model::packets::LinkLayerPacketView incoming)848 void LinkLayerController::IncomingIoCapabilityNegativeResponsePacket(
849     model::packets::LinkLayerPacketView incoming) {
850   Address peer = incoming.GetSourceAddress();
851 
852   ASSERT(security_manager_.GetAuthenticationAddress() == peer);
853 
854   security_manager_.InvalidateIoCapabilities();
855   LOG_INFO("%s doesn't support SSP, try PIN",
856            incoming.GetSourceAddress().ToString().c_str());
857   security_manager_.SetPinRequested(peer);
858   send_event_(bluetooth::hci::PinCodeRequestBuilder::Create(
859       incoming.GetSourceAddress()));
860 }
861 
IncomingIsoPacket(LinkLayerPacketView incoming)862 void LinkLayerController::IncomingIsoPacket(LinkLayerPacketView incoming) {
863   auto iso = IsoDataPacketView::Create(incoming);
864   ASSERT(iso.IsValid());
865 
866   uint16_t cis_handle = iso.GetHandle();
867   if (!connections_.HasCisHandle(cis_handle)) {
868     LOG_INFO("Dropping ISO packet to unknown handle 0x%hx", cis_handle);
869     return;
870   }
871   if (!connections_.HasConnectedCis(cis_handle)) {
872     LOG_INFO("Dropping ISO packet to a disconnected handle 0x%hx", cis_handle);
873     return;
874   }
875 
876   auto sc = iso.GetSc();
877   switch (sc) {
878     case StartContinuation::START: {
879       auto iso_start = IsoStartView::Create(iso);
880       ASSERT(iso_start.IsValid());
881       if (iso.GetCmplt() == Complete::COMPLETE) {
882         send_iso_(bluetooth::hci::IsoWithoutTimestampBuilder::Create(
883             cis_handle, bluetooth::hci::IsoPacketBoundaryFlag::COMPLETE_SDU,
884             0 /* seq num */, bluetooth::hci::IsoPacketStatusFlag::VALID,
885             std::make_unique<bluetooth::packet::RawBuilder>(
886                 std::vector<uint8_t>(iso_start.GetPayload().begin(),
887                                      iso_start.GetPayload().end()))));
888       } else {
889         send_iso_(bluetooth::hci::IsoWithoutTimestampBuilder::Create(
890             cis_handle, bluetooth::hci::IsoPacketBoundaryFlag::FIRST_FRAGMENT,
891             0 /* seq num */, bluetooth::hci::IsoPacketStatusFlag::VALID,
892             std::make_unique<bluetooth::packet::RawBuilder>(
893                 std::vector<uint8_t>(iso_start.GetPayload().begin(),
894                                      iso_start.GetPayload().end()))));
895       }
896     } break;
897     case StartContinuation::CONTINUATION: {
898       auto continuation = IsoContinuationView::Create(iso);
899       ASSERT(continuation.IsValid());
900       if (iso.GetCmplt() == Complete::COMPLETE) {
901         send_iso_(bluetooth::hci::IsoWithoutTimestampBuilder::Create(
902             cis_handle, bluetooth::hci::IsoPacketBoundaryFlag::LAST_FRAGMENT,
903             0 /* seq num */, bluetooth::hci::IsoPacketStatusFlag::VALID,
904             std::make_unique<bluetooth::packet::RawBuilder>(
905                 std::vector<uint8_t>(continuation.GetPayload().begin(),
906                                      continuation.GetPayload().end()))));
907       } else {
908         send_iso_(bluetooth::hci::IsoWithoutTimestampBuilder::Create(
909             cis_handle,
910             bluetooth::hci::IsoPacketBoundaryFlag::CONTINUATION_FRAGMENT,
911             0 /* seq num */, bluetooth::hci::IsoPacketStatusFlag::VALID,
912             std::make_unique<bluetooth::packet::RawBuilder>(
913                 std::vector<uint8_t>(continuation.GetPayload().begin(),
914                                      continuation.GetPayload().end()))));
915       }
916     } break;
917   }
918 }
919 
HandleIso(bluetooth::hci::IsoView iso)920 void LinkLayerController::HandleIso(bluetooth::hci::IsoView iso) {
921   auto cis_handle = iso.GetConnectionHandle();
922   if (!connections_.HasCisHandle(cis_handle)) {
923     LOG_INFO("Dropping ISO packet to unknown handle 0x%hx", cis_handle);
924     return;
925   }
926   if (!connections_.HasConnectedCis(cis_handle)) {
927     LOG_INFO("Dropping ISO packet to disconnected handle 0x%hx", cis_handle);
928     return;
929   }
930 
931   auto acl_handle = connections_.GetAclHandleForCisHandle(cis_handle);
932   uint16_t remote_handle =
933       connections_.GetRemoteCisHandleForCisHandle(cis_handle);
934   model::packets::StartContinuation start_flag =
935       model::packets::StartContinuation::START;
936   model::packets::Complete complete_flag = model::packets::Complete::COMPLETE;
937   switch (iso.GetPbFlag()) {
938     case bluetooth::hci::IsoPacketBoundaryFlag::COMPLETE_SDU:
939       start_flag = model::packets::StartContinuation::START;
940       complete_flag = model::packets::Complete::COMPLETE;
941       break;
942     case bluetooth::hci::IsoPacketBoundaryFlag::CONTINUATION_FRAGMENT:
943       start_flag = model::packets::StartContinuation::CONTINUATION;
944       complete_flag = model::packets::Complete::INCOMPLETE;
945       break;
946     case bluetooth::hci::IsoPacketBoundaryFlag::FIRST_FRAGMENT:
947       start_flag = model::packets::StartContinuation::START;
948       complete_flag = model::packets::Complete::INCOMPLETE;
949       break;
950     case bluetooth::hci::IsoPacketBoundaryFlag::LAST_FRAGMENT:
951       start_flag = model::packets::StartContinuation::CONTINUATION;
952       complete_flag = model::packets::Complete::INCOMPLETE;
953       break;
954   }
955   if (start_flag == model::packets::StartContinuation::START) {
956     if (iso.GetTsFlag() == bluetooth::hci::TimeStampFlag::PRESENT) {
957       auto timestamped = bluetooth::hci::IsoWithTimestampView::Create(iso);
958       ASSERT(timestamped.IsValid());
959       uint32_t timestamp = timestamped.GetTimeStamp();
960       std::unique_ptr<bluetooth::packet::RawBuilder> payload =
961           std::make_unique<bluetooth::packet::RawBuilder>();
962       for (const auto it : timestamped.GetPayload()) {
963         payload->AddOctets1(it);
964       }
965 
966       SendLeLinkLayerPacket(model::packets::IsoStartBuilder::Create(
967           connections_.GetOwnAddress(acl_handle).GetAddress(),
968           connections_.GetAddress(acl_handle).GetAddress(), remote_handle,
969           complete_flag, timestamp, std::move(payload)));
970     } else {
971       auto pkt = bluetooth::hci::IsoWithoutTimestampView::Create(iso);
972       ASSERT(pkt.IsValid());
973 
974       auto payload =
975           std::make_unique<bluetooth::packet::RawBuilder>(std::vector<uint8_t>(
976               pkt.GetPayload().begin(), pkt.GetPayload().end()));
977 
978       SendLeLinkLayerPacket(model::packets::IsoStartBuilder::Create(
979           connections_.GetOwnAddress(acl_handle).GetAddress(),
980           connections_.GetAddress(acl_handle).GetAddress(), remote_handle,
981           complete_flag, 0, std::move(payload)));
982     }
983   } else {
984     auto pkt = bluetooth::hci::IsoWithoutTimestampView::Create(iso);
985     ASSERT(pkt.IsValid());
986     std::unique_ptr<bluetooth::packet::RawBuilder> payload =
987         std::make_unique<bluetooth::packet::RawBuilder>(std::vector<uint8_t>(
988             pkt.GetPayload().begin(), pkt.GetPayload().end()));
989     SendLeLinkLayerPacket(model::packets::IsoContinuationBuilder::Create(
990         connections_.GetOwnAddress(acl_handle).GetAddress(),
991         connections_.GetAddress(acl_handle).GetAddress(), remote_handle,
992         complete_flag, std::move(payload)));
993   }
994 }
995 
IncomingIsoConnectionRequestPacket(LinkLayerPacketView incoming)996 void LinkLayerController::IncomingIsoConnectionRequestPacket(
997     LinkLayerPacketView incoming) {
998   auto req = IsoConnectionRequestView::Create(incoming);
999   ASSERT(req.IsValid());
1000   std::vector<bluetooth::hci::CisParametersConfig> stream_configs;
1001   bluetooth::hci::CisParametersConfig stream_config;
1002 
1003   stream_config.max_sdu_m_to_s_ = req.GetMaxSduMToS();
1004   stream_config.max_sdu_s_to_m_ = req.GetMaxSduSToM();
1005 
1006   stream_configs.push_back(stream_config);
1007 
1008   uint8_t group_id = req.GetCigId();
1009 
1010   /* CIG should be created by the local host before use */
1011   bluetooth::hci::CreateCisConfig config;
1012   config.cis_connection_handle_ = req.GetRequesterCisHandle();
1013 
1014   config.acl_connection_handle_ =
1015       connections_.GetHandleOnlyAddress(incoming.GetSourceAddress());
1016   connections_.CreatePendingCis(config);
1017   connections_.SetRemoteCisHandle(config.cis_connection_handle_,
1018                                   req.GetRequesterCisHandle());
1019   send_event_(bluetooth::hci::LeCisRequestBuilder::Create(
1020       config.acl_connection_handle_, config.cis_connection_handle_, group_id,
1021       req.GetId()));
1022 }
1023 
IncomingIsoConnectionResponsePacket(LinkLayerPacketView incoming)1024 void LinkLayerController::IncomingIsoConnectionResponsePacket(
1025     LinkLayerPacketView incoming) {
1026   auto response = IsoConnectionResponseView::Create(incoming);
1027   ASSERT(response.IsValid());
1028 
1029   bluetooth::hci::CreateCisConfig config;
1030   config.acl_connection_handle_ = response.GetRequesterAclHandle();
1031   config.cis_connection_handle_ = response.GetRequesterCisHandle();
1032   if (!connections_.HasPendingCisConnection(config.cis_connection_handle_)) {
1033     LOG_INFO("Ignoring connection response with unknown CIS handle 0x%04hx",
1034              config.cis_connection_handle_);
1035     return;
1036   }
1037   ErrorCode status = static_cast<ErrorCode>(response.GetStatus());
1038   if (status != ErrorCode::SUCCESS) {
1039     send_event_(bluetooth::hci::LeCisEstablishedBuilder::Create(
1040         status, config.cis_connection_handle_, 0, 0, 0, 0,
1041         bluetooth::hci::SecondaryPhyType::NO_PACKETS,
1042         bluetooth::hci::SecondaryPhyType::NO_PACKETS, 0, 0, 0, 0, 0, 0, 0, 0));
1043     return;
1044   }
1045   connections_.SetRemoteCisHandle(config.cis_connection_handle_,
1046                                   response.GetResponderCisHandle());
1047   connections_.ConnectCis(config.cis_connection_handle_);
1048   auto stream_parameters =
1049       connections_.GetStreamParameters(config.cis_connection_handle_);
1050   auto group_parameters =
1051       connections_.GetGroupParameters(stream_parameters.group_id);
1052   // TODO: Which of these are important enough to fake?
1053   uint32_t cig_sync_delay = 0x100;
1054   uint32_t cis_sync_delay = 0x200;
1055   uint32_t latency_m_to_s = group_parameters.max_transport_latency_m_to_s;
1056   uint32_t latency_s_to_m = group_parameters.max_transport_latency_s_to_m;
1057   uint8_t nse = 1;
1058   uint8_t bn_m_to_s = 0;
1059   uint8_t bn_s_to_m = 0;
1060   uint8_t ft_m_to_s = 0;
1061   uint8_t ft_s_to_m = 0;
1062   uint8_t max_pdu_m_to_s = 0x40;
1063   uint8_t max_pdu_s_to_m = 0x40;
1064   uint16_t iso_interval = 0x100;
1065   send_event_(bluetooth::hci::LeCisEstablishedBuilder::Create(
1066       status, config.cis_connection_handle_, cig_sync_delay, cis_sync_delay,
1067       latency_m_to_s, latency_s_to_m,
1068       bluetooth::hci::SecondaryPhyType::NO_PACKETS,
1069       bluetooth::hci::SecondaryPhyType::NO_PACKETS, nse, bn_m_to_s, bn_s_to_m,
1070       ft_m_to_s, ft_s_to_m, max_pdu_m_to_s, max_pdu_s_to_m, iso_interval));
1071 }
1072 
IncomingKeypressNotificationPacket(model::packets::LinkLayerPacketView incoming)1073 void LinkLayerController::IncomingKeypressNotificationPacket(
1074     model::packets::LinkLayerPacketView incoming) {
1075   auto keypress = model::packets::KeypressNotificationView::Create(incoming);
1076   ASSERT(keypress.IsValid());
1077   auto notification_type = keypress.GetNotificationType();
1078   if (notification_type >
1079       model::packets::PasskeyNotificationType::ENTRY_COMPLETED) {
1080     LOG_WARN("Dropping unknown notification type %d",
1081              static_cast<int>(notification_type));
1082     return;
1083   }
1084   send_event_(bluetooth::hci::KeypressNotificationBuilder::Create(
1085       incoming.GetSourceAddress(),
1086       static_cast<bluetooth::hci::KeypressNotificationType>(
1087           notification_type)));
1088 }
1089 
IncomingLeAdvertisementPacket(model::packets::LinkLayerPacketView incoming)1090 void LinkLayerController::IncomingLeAdvertisementPacket(
1091     model::packets::LinkLayerPacketView incoming) {
1092   // TODO: Handle multiple advertisements per packet.
1093 
1094   Address address = incoming.GetSourceAddress();
1095   auto advertisement = model::packets::LeAdvertisementView::Create(incoming);
1096   ASSERT(advertisement.IsValid());
1097   auto address_type = advertisement.GetAddressType();
1098   auto adv_type = advertisement.GetAdvertisementType();
1099 
1100   if (le_scan_enable_ == bluetooth::hci::OpCode::LE_SET_SCAN_ENABLE) {
1101     vector<uint8_t> ad = advertisement.GetData();
1102 
1103     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
1104         std::make_unique<bluetooth::packet::RawBuilder>();
1105     raw_builder_ptr->AddOctets1(
1106         static_cast<uint8_t>(bluetooth::hci::SubeventCode::ADVERTISING_REPORT));
1107     raw_builder_ptr->AddOctets1(0x01);  // num reports
1108     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(adv_type));
1109     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
1110     raw_builder_ptr->AddAddress(address);
1111     raw_builder_ptr->AddOctets1(ad.size());
1112     raw_builder_ptr->AddOctets(ad);
1113     raw_builder_ptr->AddOctets1(GetRssi());
1114     auto packet = bluetooth::hci::EventBuilder::Create(
1115         bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr));
1116     send_event_(std::move(packet));
1117   }
1118 
1119   if (le_scan_enable_ == bluetooth::hci::OpCode::LE_SET_EXTENDED_SCAN_ENABLE) {
1120     vector<uint8_t> ad = advertisement.GetData();
1121 
1122     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
1123         std::make_unique<bluetooth::packet::RawBuilder>();
1124     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(
1125         bluetooth::hci::SubeventCode::EXTENDED_ADVERTISING_REPORT));
1126     raw_builder_ptr->AddOctets1(0x01);  // num reports
1127     switch (adv_type) {
1128       case model::packets::AdvertisementType::ADV_IND:
1129         raw_builder_ptr->AddOctets1(0x13);
1130         break;
1131       case model::packets::AdvertisementType::ADV_DIRECT_IND:
1132         raw_builder_ptr->AddOctets1(0x15);
1133         break;
1134       case model::packets::AdvertisementType::ADV_SCAN_IND:
1135         raw_builder_ptr->AddOctets1(0x12);
1136         break;
1137       case model::packets::AdvertisementType::ADV_NONCONN_IND:
1138         raw_builder_ptr->AddOctets1(0x10);
1139         break;
1140       case model::packets::AdvertisementType::SCAN_RESPONSE:
1141         raw_builder_ptr->AddOctets1(0x1b);  // 0x1a for ADV_SCAN_IND scan
1142         return;
1143     }
1144     raw_builder_ptr->AddOctets1(0x00);  // Reserved
1145     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
1146     raw_builder_ptr->AddAddress(address);
1147     raw_builder_ptr->AddOctets1(1);     // Primary_PHY
1148     raw_builder_ptr->AddOctets1(0);     // Secondary_PHY
1149     raw_builder_ptr->AddOctets1(0xFF);  // Advertising_SID - not provided
1150     raw_builder_ptr->AddOctets1(0x7F);  // Tx_Power - Not available
1151     raw_builder_ptr->AddOctets1(GetRssi());
1152     raw_builder_ptr->AddOctets2(0);  // Periodic_Advertising_Interval - None
1153     raw_builder_ptr->AddOctets1(0);  // Direct_Address_Type - PUBLIC
1154     raw_builder_ptr->AddAddress(Address::kEmpty);  // Direct_Address
1155     raw_builder_ptr->AddOctets1(ad.size());
1156     raw_builder_ptr->AddOctets(ad);
1157     send_event_(bluetooth::hci::EventBuilder::Create(
1158         bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr)));
1159   }
1160 
1161   // Active scanning
1162   if (le_scan_enable_ != bluetooth::hci::OpCode::NONE && le_scan_type_ == 1) {
1163     auto to_send = model::packets::LeScanBuilder::Create(
1164         properties_.GetLeAddress(), address);
1165     SendLeLinkLayerPacket(std::move(to_send));
1166   }
1167 
1168   // Connect
1169   if ((le_connect_ && le_peer_address_ == address &&
1170        le_peer_address_type_ == static_cast<uint8_t>(address_type) &&
1171        (adv_type == model::packets::AdvertisementType::ADV_IND ||
1172         adv_type == model::packets::AdvertisementType::ADV_DIRECT_IND)) ||
1173       (LeConnectListContainsDevice(address,
1174                                    static_cast<uint8_t>(address_type)))) {
1175     if (!connections_.CreatePendingLeConnection(AddressWithType(
1176             address, static_cast<bluetooth::hci::AddressType>(address_type)))) {
1177       LOG_WARN(
1178           "CreatePendingLeConnection failed for connection to %s (type %hhx)",
1179           incoming.GetSourceAddress().ToString().c_str(), address_type);
1180     }
1181     Address own_address;
1182     auto own_address_type =
1183         static_cast<bluetooth::hci::OwnAddressType>(le_address_type_);
1184     switch (own_address_type) {
1185       case bluetooth::hci::OwnAddressType::PUBLIC_DEVICE_ADDRESS:
1186         own_address = properties_.GetAddress();
1187         break;
1188       case bluetooth::hci::OwnAddressType::RANDOM_DEVICE_ADDRESS:
1189         own_address = properties_.GetLeAddress();
1190         break;
1191       default:
1192         LOG_ALWAYS_FATAL(
1193             "Unhandled connection address type %s",
1194             bluetooth::hci::OwnAddressTypeText(own_address_type).c_str());
1195     }
1196     LOG_INFO("Connecting to %s (type %hhx) own_address %s (type %hhx)",
1197              incoming.GetSourceAddress().ToString().c_str(), address_type,
1198              own_address.ToString().c_str(), le_address_type_);
1199     le_connect_ = false;
1200     le_scan_enable_ = bluetooth::hci::OpCode::NONE;
1201 
1202     auto to_send = model::packets::LeConnectBuilder::Create(
1203         own_address, incoming.GetSourceAddress(), le_connection_interval_min_,
1204         le_connection_interval_max_, le_connection_latency_,
1205         le_connection_supervision_timeout_,
1206         static_cast<uint8_t>(le_address_type_));
1207 
1208     SendLeLinkLayerPacket(std::move(to_send));
1209   }
1210 }
1211 
HandleLeConnection(AddressWithType address,AddressWithType own_address,uint8_t role,uint16_t connection_interval,uint16_t connection_latency,uint16_t supervision_timeout)1212 void LinkLayerController::HandleLeConnection(AddressWithType address,
1213                                              AddressWithType own_address,
1214                                              uint8_t role,
1215                                              uint16_t connection_interval,
1216                                              uint16_t connection_latency,
1217                                              uint16_t supervision_timeout) {
1218   // TODO: Choose between LeConnectionComplete and LeEnhancedConnectionComplete
1219   uint16_t handle = connections_.CreateLeConnection(address, own_address);
1220   if (handle == kReservedHandle) {
1221     LOG_WARN("No pending connection for connection from %s",
1222              address.ToString().c_str());
1223     return;
1224   }
1225   auto packet = bluetooth::hci::LeConnectionCompleteBuilder::Create(
1226       ErrorCode::SUCCESS, handle, static_cast<bluetooth::hci::Role>(role),
1227       address.GetAddressType(), address.GetAddress(), connection_interval,
1228       connection_latency, supervision_timeout,
1229       static_cast<bluetooth::hci::ClockAccuracy>(0x00));
1230   send_event_(std::move(packet));
1231 }
1232 
IncomingLeConnectPacket(model::packets::LinkLayerPacketView incoming)1233 void LinkLayerController::IncomingLeConnectPacket(
1234     model::packets::LinkLayerPacketView incoming) {
1235   auto connect = model::packets::LeConnectView::Create(incoming);
1236   ASSERT(connect.IsValid());
1237   uint16_t connection_interval = (connect.GetLeConnectionIntervalMax() +
1238                                   connect.GetLeConnectionIntervalMin()) /
1239                                  2;
1240   if (!connections_.CreatePendingLeConnection(AddressWithType(
1241           incoming.GetSourceAddress(), static_cast<bluetooth::hci::AddressType>(
1242                                            connect.GetAddressType())))) {
1243     LOG_WARN(
1244         "CreatePendingLeConnection failed for connection from %s (type "
1245         "%hhx)",
1246         incoming.GetSourceAddress().ToString().c_str(),
1247         connect.GetAddressType());
1248     return;
1249   }
1250   bluetooth::hci::AddressWithType my_address{};
1251   bool matched_advertiser = false;
1252   for (auto advertiser : advertisers_) {
1253     AddressWithType advertiser_address = advertiser.GetAddress();
1254     if (incoming.GetDestinationAddress() == advertiser_address.GetAddress()) {
1255       my_address = advertiser_address;
1256       matched_advertiser = true;
1257     }
1258   }
1259 
1260   if (!matched_advertiser) {
1261     LOG_INFO("Dropping unmatched connection request to %s",
1262              incoming.GetSourceAddress().ToString().c_str());
1263     return;
1264   }
1265 
1266   HandleLeConnection(
1267       AddressWithType(
1268           incoming.GetSourceAddress(),
1269           static_cast<bluetooth::hci::AddressType>(connect.GetAddressType())),
1270       my_address, static_cast<uint8_t>(bluetooth::hci::Role::PERIPHERAL),
1271       connection_interval, connect.GetLeConnectionLatency(),
1272       connect.GetLeConnectionSupervisionTimeout());
1273 
1274   auto to_send = model::packets::LeConnectCompleteBuilder::Create(
1275       incoming.GetDestinationAddress(), incoming.GetSourceAddress(),
1276       connection_interval, connect.GetLeConnectionLatency(),
1277       connect.GetLeConnectionSupervisionTimeout(),
1278       static_cast<uint8_t>(my_address.GetAddressType()));
1279   SendLeLinkLayerPacket(std::move(to_send));
1280 }
1281 
IncomingLeConnectCompletePacket(model::packets::LinkLayerPacketView incoming)1282 void LinkLayerController::IncomingLeConnectCompletePacket(
1283     model::packets::LinkLayerPacketView incoming) {
1284   auto complete = model::packets::LeConnectCompleteView::Create(incoming);
1285   ASSERT(complete.IsValid());
1286   HandleLeConnection(
1287       AddressWithType(
1288           incoming.GetSourceAddress(),
1289           static_cast<bluetooth::hci::AddressType>(complete.GetAddressType())),
1290       AddressWithType(
1291           incoming.GetDestinationAddress(),
1292           static_cast<bluetooth::hci::AddressType>(le_address_type_)),
1293       static_cast<uint8_t>(bluetooth::hci::Role::CENTRAL),
1294       complete.GetLeConnectionInterval(), complete.GetLeConnectionLatency(),
1295       complete.GetLeConnectionSupervisionTimeout());
1296 }
1297 
IncomingLeEncryptConnection(model::packets::LinkLayerPacketView incoming)1298 void LinkLayerController::IncomingLeEncryptConnection(
1299     model::packets::LinkLayerPacketView incoming) {
1300   LOG_INFO();
1301 
1302   Address peer = incoming.GetSourceAddress();
1303   uint16_t handle = connections_.GetHandleOnlyAddress(peer);
1304   if (handle == kReservedHandle) {
1305     LOG_INFO("@%s: Unknown connection @%s",
1306              incoming.GetDestinationAddress().ToString().c_str(),
1307              peer.ToString().c_str());
1308     return;
1309   }
1310   auto le_encrypt = model::packets::LeEncryptConnectionView::Create(incoming);
1311   ASSERT(le_encrypt.IsValid());
1312 
1313   // TODO: Save keys to check
1314 
1315   send_event_(bluetooth::hci::LeLongTermKeyRequestBuilder::Create(
1316       handle, le_encrypt.GetRand(), le_encrypt.GetEdiv()));
1317 }
1318 
IncomingLeEncryptConnectionResponse(model::packets::LinkLayerPacketView incoming)1319 void LinkLayerController::IncomingLeEncryptConnectionResponse(
1320     model::packets::LinkLayerPacketView incoming) {
1321   LOG_INFO();
1322   // TODO: Check keys
1323   uint16_t handle =
1324       connections_.GetHandleOnlyAddress(incoming.GetSourceAddress());
1325   if (handle == kReservedHandle) {
1326     LOG_INFO("@%s: Unknown connection @%s",
1327              incoming.GetDestinationAddress().ToString().c_str(),
1328              incoming.GetSourceAddress().ToString().c_str());
1329     return;
1330   }
1331   ErrorCode status = ErrorCode::SUCCESS;
1332   auto response =
1333       model::packets::LeEncryptConnectionResponseView::Create(incoming);
1334   ASSERT(response.IsValid());
1335 
1336   // Zero LTK is a rejection
1337   if (response.GetLtk() == std::array<uint8_t, 16>()) {
1338     status = ErrorCode::AUTHENTICATION_FAILURE;
1339   }
1340 
1341   if (connections_.IsEncrypted(handle)) {
1342     send_event_(bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create(
1343         status, handle));
1344   } else {
1345     connections_.Encrypt(handle);
1346     send_event_(bluetooth::hci::EncryptionChangeBuilder::Create(
1347         status, handle, bluetooth::hci::EncryptionEnabled::ON));
1348   }
1349 }
1350 
IncomingLeReadRemoteFeatures(model::packets::LinkLayerPacketView incoming)1351 void LinkLayerController::IncomingLeReadRemoteFeatures(
1352     model::packets::LinkLayerPacketView incoming) {
1353   uint16_t handle =
1354       connections_.GetHandleOnlyAddress(incoming.GetSourceAddress());
1355   ErrorCode status = ErrorCode::SUCCESS;
1356   if (handle == kReservedHandle) {
1357     LOG_WARN("@%s: Unknown connection @%s",
1358              incoming.GetDestinationAddress().ToString().c_str(),
1359              incoming.GetSourceAddress().ToString().c_str());
1360   }
1361   SendLinkLayerPacket(
1362       model::packets::LeReadRemoteFeaturesResponseBuilder::Create(
1363           incoming.GetDestinationAddress(), incoming.GetSourceAddress(),
1364           properties_.GetLeSupportedFeatures(), static_cast<uint8_t>(status)));
1365 }
1366 
IncomingLeReadRemoteFeaturesResponse(model::packets::LinkLayerPacketView incoming)1367 void LinkLayerController::IncomingLeReadRemoteFeaturesResponse(
1368     model::packets::LinkLayerPacketView incoming) {
1369   uint16_t handle =
1370       connections_.GetHandleOnlyAddress(incoming.GetSourceAddress());
1371   ErrorCode status = ErrorCode::SUCCESS;
1372   auto response =
1373       model::packets::LeReadRemoteFeaturesResponseView::Create(incoming);
1374   ASSERT(response.IsValid());
1375   if (handle == kReservedHandle) {
1376     LOG_INFO("@%s: Unknown connection @%s",
1377              incoming.GetDestinationAddress().ToString().c_str(),
1378              incoming.GetSourceAddress().ToString().c_str());
1379     status = ErrorCode::UNKNOWN_CONNECTION;
1380   } else {
1381     status = static_cast<ErrorCode>(response.GetStatus());
1382   }
1383   send_event_(bluetooth::hci::LeReadRemoteFeaturesCompleteBuilder::Create(
1384       status, handle, response.GetFeatures()));
1385 }
1386 
IncomingLeScanPacket(model::packets::LinkLayerPacketView incoming)1387 void LinkLayerController::IncomingLeScanPacket(
1388     model::packets::LinkLayerPacketView incoming) {
1389   for (auto& advertiser : advertisers_) {
1390     auto to_send = advertiser.GetScanResponse(incoming.GetDestinationAddress(),
1391                                               incoming.GetSourceAddress());
1392     if (to_send != nullptr) {
1393       SendLeLinkLayerPacket(std::move(to_send));
1394     }
1395   }
1396 }
1397 
IncomingLeScanResponsePacket(model::packets::LinkLayerPacketView incoming)1398 void LinkLayerController::IncomingLeScanResponsePacket(
1399     model::packets::LinkLayerPacketView incoming) {
1400   auto scan_response = model::packets::LeScanResponseView::Create(incoming);
1401   ASSERT(scan_response.IsValid());
1402   vector<uint8_t> ad = scan_response.GetData();
1403   auto adv_type = scan_response.GetAdvertisementType();
1404   auto address_type =
1405       static_cast<LeAdvertisement::AddressType>(scan_response.GetAddressType());
1406   if (le_scan_enable_ == bluetooth::hci::OpCode::LE_SET_SCAN_ENABLE) {
1407     if (adv_type != model::packets::AdvertisementType::SCAN_RESPONSE) {
1408       return;
1409     }
1410     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
1411         std::make_unique<bluetooth::packet::RawBuilder>();
1412     raw_builder_ptr->AddOctets1(
1413         static_cast<uint8_t>(bluetooth::hci::SubeventCode::ADVERTISING_REPORT));
1414     raw_builder_ptr->AddOctets1(0x01);  // num reports
1415     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(
1416         bluetooth::hci::AdvertisingEventType::SCAN_RESPONSE));
1417     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
1418     raw_builder_ptr->AddAddress(incoming.GetSourceAddress());
1419     raw_builder_ptr->AddOctets1(ad.size());
1420     raw_builder_ptr->AddOctets(ad);
1421     raw_builder_ptr->AddOctets1(GetRssi());
1422     auto packet = bluetooth::hci::EventBuilder::Create(
1423         bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr));
1424     send_event_(std::move(packet));
1425   }
1426 
1427   if (le_scan_enable_ == bluetooth::hci::OpCode::LE_SET_EXTENDED_SCAN_ENABLE) {
1428     std::unique_ptr<bluetooth::packet::RawBuilder> raw_builder_ptr =
1429         std::make_unique<bluetooth::packet::RawBuilder>();
1430     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(
1431         bluetooth::hci::SubeventCode::EXTENDED_ADVERTISING_REPORT));
1432     raw_builder_ptr->AddOctets1(0x01);  // num reports
1433     raw_builder_ptr->AddOctets1(0x1a);  // TODO: 0x1b for ADV_SCAN_IND
1434     raw_builder_ptr->AddOctets1(static_cast<uint8_t>(address_type));
1435     raw_builder_ptr->AddAddress(incoming.GetSourceAddress());
1436     raw_builder_ptr->AddOctets1(1);     // Primary_PHY
1437     raw_builder_ptr->AddOctets1(0);     // Secondary_PHY
1438     raw_builder_ptr->AddOctets1(0xFF);  // Advertising_SID - not provided
1439     raw_builder_ptr->AddOctets1(0x7F);  // Tx_Power - Not available
1440     raw_builder_ptr->AddOctets1(GetRssi());
1441     raw_builder_ptr->AddOctets1(0);  // Periodic_Advertising_Interval - None
1442     raw_builder_ptr->AddOctets1(0);  // Direct_Address_Type - PUBLIC
1443     raw_builder_ptr->AddAddress(Address::kEmpty);  // Direct_Address
1444     raw_builder_ptr->AddOctets1(ad.size());
1445     raw_builder_ptr->AddOctets(ad);
1446     auto packet = bluetooth::hci::EventBuilder::Create(
1447         bluetooth::hci::EventCode::LE_META_EVENT, std::move(raw_builder_ptr));
1448     send_event_(std::move(packet));
1449   }
1450 }
1451 
IncomingPasskeyPacket(model::packets::LinkLayerPacketView incoming)1452 void LinkLayerController::IncomingPasskeyPacket(
1453     model::packets::LinkLayerPacketView incoming) {
1454   auto passkey = model::packets::PasskeyView::Create(incoming);
1455   ASSERT(passkey.IsValid());
1456   SaveKeyAndAuthenticate('P', incoming.GetSourceAddress());
1457 }
1458 
IncomingPasskeyFailedPacket(model::packets::LinkLayerPacketView incoming)1459 void LinkLayerController::IncomingPasskeyFailedPacket(
1460     model::packets::LinkLayerPacketView incoming) {
1461   auto failed = model::packets::PasskeyFailedView::Create(incoming);
1462   ASSERT(failed.IsValid());
1463   auto current_peer = incoming.GetSourceAddress();
1464   security_manager_.AuthenticationRequestFinished();
1465   ScheduleTask(milliseconds(5), [this, current_peer]() {
1466     send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1467         ErrorCode::AUTHENTICATION_FAILURE, current_peer));
1468   });
1469 }
1470 
IncomingPinRequestPacket(model::packets::LinkLayerPacketView incoming)1471 void LinkLayerController::IncomingPinRequestPacket(
1472     model::packets::LinkLayerPacketView incoming) {
1473   auto request = model::packets::PinRequestView::Create(incoming);
1474   ASSERT(request.IsValid());
1475   auto peer = incoming.GetSourceAddress();
1476   auto handle = connections_.GetHandle(AddressWithType(
1477       peer, bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS));
1478   if (handle == kReservedHandle) {
1479     LOG_INFO("Dropping %s request (no connection)", peer.ToString().c_str());
1480     auto wrong_pin = request.GetPinCode();
1481     wrong_pin[0] = wrong_pin[0]++;
1482     SendLinkLayerPacket(model::packets::PinResponseBuilder::Create(
1483         properties_.GetAddress(), peer, wrong_pin));
1484     return;
1485   }
1486   if (security_manager_.AuthenticationInProgress()) {
1487     auto current_peer = security_manager_.GetAuthenticationAddress();
1488     if (current_peer != peer) {
1489       LOG_INFO("Dropping %s request (%s in progress)", peer.ToString().c_str(),
1490                current_peer.ToString().c_str());
1491       auto wrong_pin = request.GetPinCode();
1492       wrong_pin[0] = wrong_pin[0]++;
1493       SendLinkLayerPacket(model::packets::PinResponseBuilder::Create(
1494           properties_.GetAddress(), peer, wrong_pin));
1495       return;
1496     }
1497   } else {
1498     LOG_INFO("Incoming authentication request %s", peer.ToString().c_str());
1499     security_manager_.AuthenticationRequest(peer, handle);
1500   }
1501   auto current_peer = security_manager_.GetAuthenticationAddress();
1502   security_manager_.SetRemotePin(peer, request.GetPinCode());
1503   if (security_manager_.GetPinRequested(peer)) {
1504     if (security_manager_.GetLocalPinResponseReceived(peer)) {
1505       SendLinkLayerPacket(model::packets::PinResponseBuilder::Create(
1506           properties_.GetAddress(), peer, request.GetPinCode()));
1507       if (security_manager_.PinCompare()) {
1508         LOG_INFO("Authenticating %s", peer.ToString().c_str());
1509         SaveKeyAndAuthenticate('L', peer);  // Legacy
1510       } else {
1511         security_manager_.AuthenticationRequestFinished();
1512         ScheduleTask(milliseconds(5), [this, peer]() {
1513           send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1514               ErrorCode::AUTHENTICATION_FAILURE, peer));
1515         });
1516       }
1517     }
1518   } else {
1519     LOG_INFO("PIN pairing %s", properties_.GetAddress().ToString().c_str());
1520     ScheduleTask(milliseconds(5), [this, peer]() {
1521       security_manager_.SetPinRequested(peer);
1522       send_event_(bluetooth::hci::PinCodeRequestBuilder::Create(peer));
1523     });
1524   }
1525 }
1526 
IncomingPinResponsePacket(model::packets::LinkLayerPacketView incoming)1527 void LinkLayerController::IncomingPinResponsePacket(
1528     model::packets::LinkLayerPacketView incoming) {
1529   auto request = model::packets::PinResponseView::Create(incoming);
1530   ASSERT(request.IsValid());
1531   auto peer = incoming.GetSourceAddress();
1532   auto handle = connections_.GetHandle(AddressWithType(
1533       peer, bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS));
1534   if (handle == kReservedHandle) {
1535     LOG_INFO("Dropping %s request (no connection)", peer.ToString().c_str());
1536     return;
1537   }
1538   if (security_manager_.AuthenticationInProgress()) {
1539     auto current_peer = security_manager_.GetAuthenticationAddress();
1540     if (current_peer != peer) {
1541       LOG_INFO("Dropping %s request (%s in progress)", peer.ToString().c_str(),
1542                current_peer.ToString().c_str());
1543       return;
1544     }
1545   } else {
1546     LOG_INFO("Dropping response without authentication request %s",
1547              peer.ToString().c_str());
1548     return;
1549   }
1550   auto current_peer = security_manager_.GetAuthenticationAddress();
1551   security_manager_.SetRemotePin(peer, request.GetPinCode());
1552   if (security_manager_.GetPinRequested(peer)) {
1553     if (security_manager_.GetLocalPinResponseReceived(peer)) {
1554       SendLinkLayerPacket(model::packets::PinResponseBuilder::Create(
1555           properties_.GetAddress(), peer, request.GetPinCode()));
1556       if (security_manager_.PinCompare()) {
1557         LOG_INFO("Authenticating %s", peer.ToString().c_str());
1558         SaveKeyAndAuthenticate('L', peer);  // Legacy
1559       } else {
1560         security_manager_.AuthenticationRequestFinished();
1561         ScheduleTask(milliseconds(5), [this, peer]() {
1562           send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1563               ErrorCode::AUTHENTICATION_FAILURE, peer));
1564         });
1565       }
1566     }
1567   } else {
1568     LOG_INFO("PIN pairing %s", properties_.GetAddress().ToString().c_str());
1569     ScheduleTask(milliseconds(5), [this, peer]() {
1570       security_manager_.SetPinRequested(peer);
1571       send_event_(bluetooth::hci::PinCodeRequestBuilder::Create(peer));
1572     });
1573   }
1574 }
1575 
IncomingPagePacket(model::packets::LinkLayerPacketView incoming)1576 void LinkLayerController::IncomingPagePacket(
1577     model::packets::LinkLayerPacketView incoming) {
1578   auto page = model::packets::PageView::Create(incoming);
1579   ASSERT(page.IsValid());
1580   LOG_INFO("from %s", incoming.GetSourceAddress().ToString().c_str());
1581 
1582   if (!connections_.CreatePendingConnection(
1583           incoming.GetSourceAddress(), properties_.GetAuthenticationEnable())) {
1584     // Send a response to indicate that we're busy, or drop the packet?
1585     LOG_WARN("Failed to create a pending connection for %s",
1586              incoming.GetSourceAddress().ToString().c_str());
1587   }
1588 
1589   bluetooth::hci::Address source_address{};
1590   bluetooth::hci::Address::FromString(page.GetSourceAddress().ToString(),
1591                                       source_address);
1592 
1593   auto packet = bluetooth::hci::ConnectionRequestBuilder::Create(
1594       source_address, page.GetClassOfDevice(),
1595       bluetooth::hci::ConnectionRequestLinkType::ACL);
1596 
1597   send_event_(std::move(packet));
1598 }
1599 
IncomingPageRejectPacket(model::packets::LinkLayerPacketView incoming)1600 void LinkLayerController::IncomingPageRejectPacket(
1601     model::packets::LinkLayerPacketView incoming) {
1602   LOG_INFO("%s", incoming.GetSourceAddress().ToString().c_str());
1603   auto reject = model::packets::PageRejectView::Create(incoming);
1604   ASSERT(reject.IsValid());
1605   LOG_INFO("Sending CreateConnectionComplete");
1606   auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
1607       static_cast<ErrorCode>(reject.GetReason()), 0x0eff,
1608       incoming.GetSourceAddress(), bluetooth::hci::LinkType::ACL,
1609       bluetooth::hci::Enable::DISABLED);
1610   send_event_(std::move(packet));
1611 }
1612 
IncomingPageResponsePacket(model::packets::LinkLayerPacketView incoming)1613 void LinkLayerController::IncomingPageResponsePacket(
1614     model::packets::LinkLayerPacketView incoming) {
1615   Address peer = incoming.GetSourceAddress();
1616   LOG_INFO("%s", peer.ToString().c_str());
1617   bool awaiting_authentication = connections_.AuthenticatePendingConnection();
1618   uint16_t handle =
1619       connections_.CreateConnection(peer, incoming.GetDestinationAddress());
1620   if (handle == kReservedHandle) {
1621     LOG_WARN("No free handles");
1622     return;
1623   }
1624   auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
1625       ErrorCode::SUCCESS, handle, incoming.GetSourceAddress(),
1626       bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED);
1627   send_event_(std::move(packet));
1628 
1629   if (awaiting_authentication) {
1630     ScheduleTask(milliseconds(5), [this, peer, handle]() {
1631       HandleAuthenticationRequest(peer, handle);
1632     });
1633   }
1634 }
1635 
TimerTick()1636 void LinkLayerController::TimerTick() {
1637   if (inquiry_timer_task_id_ != kInvalidTaskId) Inquiry();
1638   LeAdvertising();
1639 }
1640 
LeAdvertising()1641 void LinkLayerController::LeAdvertising() {
1642   steady_clock::time_point now = steady_clock::now();
1643   for (auto& advertiser : advertisers_) {
1644     auto ad = advertiser.GetAdvertisement(now);
1645     if (ad == nullptr) {
1646       continue;
1647     }
1648     SendLeLinkLayerPacket(std::move(ad));
1649   }
1650 }
1651 
RegisterEventChannel(const std::function<void (std::shared_ptr<bluetooth::hci::EventBuilder>)> & callback)1652 void LinkLayerController::RegisterEventChannel(
1653     const std::function<void(std::shared_ptr<bluetooth::hci::EventBuilder>)>&
1654         callback) {
1655   send_event_ = callback;
1656 }
1657 
RegisterAclChannel(const std::function<void (std::shared_ptr<bluetooth::hci::AclBuilder>)> & callback)1658 void LinkLayerController::RegisterAclChannel(
1659     const std::function<void(std::shared_ptr<bluetooth::hci::AclBuilder>)>&
1660         callback) {
1661   send_acl_ = callback;
1662 }
1663 
RegisterScoChannel(const std::function<void (std::shared_ptr<bluetooth::hci::ScoBuilder>)> & callback)1664 void LinkLayerController::RegisterScoChannel(
1665     const std::function<void(std::shared_ptr<bluetooth::hci::ScoBuilder>)>&
1666         callback) {
1667   send_sco_ = callback;
1668 }
1669 
RegisterIsoChannel(const std::function<void (std::shared_ptr<bluetooth::hci::IsoBuilder>)> & callback)1670 void LinkLayerController::RegisterIsoChannel(
1671     const std::function<void(std::shared_ptr<bluetooth::hci::IsoBuilder>)>&
1672         callback) {
1673   send_iso_ = callback;
1674 }
1675 
RegisterRemoteChannel(const std::function<void (std::shared_ptr<model::packets::LinkLayerPacketBuilder>,Phy::Type)> & callback)1676 void LinkLayerController::RegisterRemoteChannel(
1677     const std::function<void(
1678         std::shared_ptr<model::packets::LinkLayerPacketBuilder>, Phy::Type)>&
1679         callback) {
1680   send_to_remote_ = callback;
1681 }
1682 
RegisterTaskScheduler(std::function<AsyncTaskId (milliseconds,const TaskCallback &)> event_scheduler)1683 void LinkLayerController::RegisterTaskScheduler(
1684     std::function<AsyncTaskId(milliseconds, const TaskCallback&)>
1685         event_scheduler) {
1686   schedule_task_ = event_scheduler;
1687 }
1688 
ScheduleTask(milliseconds delay_ms,const TaskCallback & callback)1689 AsyncTaskId LinkLayerController::ScheduleTask(milliseconds delay_ms,
1690                                               const TaskCallback& callback) {
1691   if (schedule_task_) {
1692     return schedule_task_(delay_ms, callback);
1693   } else {
1694     callback();
1695     return 0;
1696   }
1697 }
1698 
RegisterPeriodicTaskScheduler(std::function<AsyncTaskId (milliseconds,milliseconds,const TaskCallback &)> periodic_event_scheduler)1699 void LinkLayerController::RegisterPeriodicTaskScheduler(
1700     std::function<AsyncTaskId(milliseconds, milliseconds, const TaskCallback&)>
1701         periodic_event_scheduler) {
1702   schedule_periodic_task_ = periodic_event_scheduler;
1703 }
1704 
CancelScheduledTask(AsyncTaskId task_id)1705 void LinkLayerController::CancelScheduledTask(AsyncTaskId task_id) {
1706   if (schedule_task_ && cancel_task_) {
1707     cancel_task_(task_id);
1708   }
1709 }
1710 
RegisterTaskCancel(std::function<void (AsyncTaskId)> task_cancel)1711 void LinkLayerController::RegisterTaskCancel(
1712     std::function<void(AsyncTaskId)> task_cancel) {
1713   cancel_task_ = task_cancel;
1714 }
1715 
StartSimplePairing(const Address & address)1716 void LinkLayerController::StartSimplePairing(const Address& address) {
1717   // IO Capability Exchange (See the Diagram in the Spec)
1718   auto packet = bluetooth::hci::IoCapabilityRequestBuilder::Create(address);
1719   send_event_(std::move(packet));
1720 
1721   // Get a Key, then authenticate
1722   // PublicKeyExchange(address);
1723   // AuthenticateRemoteStage1(address);
1724   // AuthenticateRemoteStage2(address);
1725 }
1726 
AuthenticateRemoteStage1(const Address & peer,PairingType pairing_type)1727 void LinkLayerController::AuthenticateRemoteStage1(const Address& peer,
1728                                                    PairingType pairing_type) {
1729   ASSERT(security_manager_.GetAuthenticationAddress() == peer);
1730   // TODO: Public key exchange first?
1731   switch (pairing_type) {
1732     case PairingType::AUTO_CONFIRMATION:
1733       send_event_(
1734           bluetooth::hci::UserConfirmationRequestBuilder::Create(peer, 123456));
1735       break;
1736     case PairingType::CONFIRM_Y_N:
1737       send_event_(
1738           bluetooth::hci::UserConfirmationRequestBuilder::Create(peer, 123456));
1739       break;
1740     case PairingType::DISPLAY_PIN:
1741       send_event_(
1742           bluetooth::hci::UserPasskeyNotificationBuilder::Create(peer, 123456));
1743       break;
1744     case PairingType::DISPLAY_AND_CONFIRM:
1745       send_event_(
1746           bluetooth::hci::UserConfirmationRequestBuilder::Create(peer, 123456));
1747       break;
1748     case PairingType::INPUT_PIN:
1749       send_event_(bluetooth::hci::UserPasskeyRequestBuilder::Create(peer));
1750       break;
1751     case PairingType::OUT_OF_BAND:
1752       LOG_INFO("Oob data request for %s", peer.ToString().c_str());
1753       send_event_(bluetooth::hci::RemoteOobDataRequestBuilder::Create(peer));
1754       break;
1755     case PairingType::PEER_HAS_OUT_OF_BAND:
1756       LOG_INFO("Trusting that %s has OOB data", peer.ToString().c_str());
1757       SaveKeyAndAuthenticate('P', peer);
1758       break;
1759     default:
1760       LOG_ALWAYS_FATAL("Invalid PairingType %d",
1761                        static_cast<int>(pairing_type));
1762   }
1763 }
1764 
AuthenticateRemoteStage2(const Address & peer)1765 void LinkLayerController::AuthenticateRemoteStage2(const Address& peer) {
1766   uint16_t handle = security_manager_.GetAuthenticationHandle();
1767   ASSERT(security_manager_.GetAuthenticationAddress() == peer);
1768   // Check key in security_manager_ ?
1769   auto packet = bluetooth::hci::AuthenticationCompleteBuilder::Create(
1770       ErrorCode::SUCCESS, handle);
1771   send_event_(std::move(packet));
1772 }
1773 
LinkKeyRequestReply(const Address & peer,const std::array<uint8_t,16> & key)1774 ErrorCode LinkLayerController::LinkKeyRequestReply(
1775     const Address& peer, const std::array<uint8_t, 16>& key) {
1776   security_manager_.WriteKey(peer, key);
1777   security_manager_.AuthenticationRequestFinished();
1778 
1779   ScheduleTask(milliseconds(5),
1780                [this, peer]() { AuthenticateRemoteStage2(peer); });
1781 
1782   return ErrorCode::SUCCESS;
1783 }
1784 
LinkKeyRequestNegativeReply(const Address & address)1785 ErrorCode LinkLayerController::LinkKeyRequestNegativeReply(
1786     const Address& address) {
1787   security_manager_.DeleteKey(address);
1788   // Simple pairing to get a key
1789   uint16_t handle = connections_.GetHandleOnlyAddress(address);
1790   if (handle == kReservedHandle) {
1791     LOG_INFO("Device not connected %s", address.ToString().c_str());
1792     return ErrorCode::UNKNOWN_CONNECTION;
1793   }
1794 
1795   if (properties_.GetSecureSimplePairingSupported()) {
1796     security_manager_.AuthenticationRequest(address, handle);
1797 
1798     ScheduleTask(milliseconds(5),
1799                  [this, address]() { StartSimplePairing(address); });
1800   } else {
1801     LOG_INFO("PIN pairing %s", properties_.GetAddress().ToString().c_str());
1802     ScheduleTask(milliseconds(5), [this, address]() {
1803       security_manager_.SetPinRequested(address);
1804       send_event_(bluetooth::hci::PinCodeRequestBuilder::Create(address));
1805     });
1806   }
1807   return ErrorCode::SUCCESS;
1808 }
1809 
IoCapabilityRequestReply(const Address & peer,uint8_t io_capability,uint8_t oob_data_present_flag,uint8_t authentication_requirements)1810 ErrorCode LinkLayerController::IoCapabilityRequestReply(
1811     const Address& peer, uint8_t io_capability, uint8_t oob_data_present_flag,
1812     uint8_t authentication_requirements) {
1813   security_manager_.SetLocalIoCapability(
1814       peer, io_capability, oob_data_present_flag, authentication_requirements);
1815 
1816   PairingType pairing_type = security_manager_.GetSimplePairingType();
1817 
1818   if (pairing_type != PairingType::INVALID) {
1819     ScheduleTask(milliseconds(5), [this, peer, pairing_type]() {
1820       AuthenticateRemoteStage1(peer, pairing_type);
1821     });
1822     SendLinkLayerPacket(model::packets::IoCapabilityResponseBuilder::Create(
1823         properties_.GetAddress(), peer, io_capability, oob_data_present_flag,
1824         authentication_requirements));
1825   } else {
1826     LOG_INFO("Requesting remote capability");
1827 
1828     SendLinkLayerPacket(model::packets::IoCapabilityRequestBuilder::Create(
1829         properties_.GetAddress(), peer, io_capability, oob_data_present_flag,
1830         authentication_requirements));
1831   }
1832 
1833   return ErrorCode::SUCCESS;
1834 }
1835 
IoCapabilityRequestNegativeReply(const Address & peer,ErrorCode reason)1836 ErrorCode LinkLayerController::IoCapabilityRequestNegativeReply(
1837     const Address& peer, ErrorCode reason) {
1838   if (security_manager_.GetAuthenticationAddress() != peer) {
1839     return ErrorCode::AUTHENTICATION_FAILURE;
1840   }
1841 
1842   security_manager_.InvalidateIoCapabilities();
1843 
1844   auto packet = model::packets::IoCapabilityNegativeResponseBuilder::Create(
1845       properties_.GetAddress(), peer, static_cast<uint8_t>(reason));
1846   SendLinkLayerPacket(std::move(packet));
1847 
1848   return ErrorCode::SUCCESS;
1849 }
1850 
SaveKeyAndAuthenticate(uint8_t key_type,const Address & peer)1851 void LinkLayerController::SaveKeyAndAuthenticate(uint8_t key_type,
1852                                                  const Address& peer) {
1853   std::array<uint8_t, 16> key_vec{'k',
1854                                   'e',
1855                                   'y',
1856                                   ' ',
1857                                   key_type,
1858                                   5,
1859                                   6,
1860                                   7,
1861                                   8,
1862                                   9,
1863                                   10,
1864                                   11,
1865                                   12,
1866                                   13,
1867                                   static_cast<uint8_t>(key_id_ >> 8u),
1868                                   static_cast<uint8_t>(key_id_)};
1869   key_id_ += 1;
1870   security_manager_.WriteKey(peer, key_vec);
1871 
1872   security_manager_.AuthenticationRequestFinished();
1873 
1874   if (key_type == 'L') {
1875     // Legacy
1876     ScheduleTask(milliseconds(5), [this, peer, key_vec]() {
1877       send_event_(bluetooth::hci::LinkKeyNotificationBuilder::Create(
1878           peer, key_vec, bluetooth::hci::KeyType::AUTHENTICATED_P192));
1879     });
1880   } else {
1881     ScheduleTask(milliseconds(5), [this, peer]() {
1882       send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1883           ErrorCode::SUCCESS, peer));
1884     });
1885 
1886     ScheduleTask(milliseconds(5), [this, peer, key_vec]() {
1887       send_event_(bluetooth::hci::LinkKeyNotificationBuilder::Create(
1888           peer, key_vec, bluetooth::hci::KeyType::AUTHENTICATED_P256));
1889     });
1890   }
1891 
1892   ScheduleTask(milliseconds(15),
1893                [this, peer]() { AuthenticateRemoteStage2(peer); });
1894 }
1895 
PinCodeRequestReply(const Address & peer,std::vector<uint8_t> pin)1896 ErrorCode LinkLayerController::PinCodeRequestReply(const Address& peer,
1897                                                    std::vector<uint8_t> pin) {
1898   LOG_INFO("%s", properties_.GetAddress().ToString().c_str());
1899   auto current_peer = security_manager_.GetAuthenticationAddress();
1900   if (peer != current_peer) {
1901     LOG_INFO("%s: %s != %s", properties_.GetAddress().ToString().c_str(),
1902              peer.ToString().c_str(), current_peer.ToString().c_str());
1903     security_manager_.AuthenticationRequestFinished();
1904     ScheduleTask(milliseconds(5), [this, current_peer]() {
1905       send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1906           ErrorCode::AUTHENTICATION_FAILURE, current_peer));
1907     });
1908     return ErrorCode::UNKNOWN_CONNECTION;
1909   }
1910   if (!security_manager_.GetPinRequested(peer)) {
1911     LOG_INFO("No Pin Requested for %s", peer.ToString().c_str());
1912     return ErrorCode::COMMAND_DISALLOWED;
1913   }
1914   security_manager_.SetLocalPin(peer, pin);
1915   if (security_manager_.GetRemotePinResponseReceived(peer)) {
1916     if (security_manager_.PinCompare()) {
1917       LOG_INFO("Authenticating %s", peer.ToString().c_str());
1918       SaveKeyAndAuthenticate('L', peer);  // Legacy
1919     } else {
1920       security_manager_.AuthenticationRequestFinished();
1921       ScheduleTask(milliseconds(5), [this, peer]() {
1922         send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1923             ErrorCode::AUTHENTICATION_FAILURE, peer));
1924       });
1925     }
1926   } else {
1927     SendLinkLayerPacket(model::packets::PinRequestBuilder::Create(
1928         properties_.GetAddress(), peer, pin));
1929   }
1930   return ErrorCode::SUCCESS;
1931 }
1932 
PinCodeRequestNegativeReply(const Address & peer)1933 ErrorCode LinkLayerController::PinCodeRequestNegativeReply(
1934     const Address& peer) {
1935   auto current_peer = security_manager_.GetAuthenticationAddress();
1936   security_manager_.AuthenticationRequestFinished();
1937   ScheduleTask(milliseconds(5), [this, current_peer]() {
1938     send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1939         ErrorCode::AUTHENTICATION_FAILURE, current_peer));
1940   });
1941   if (peer != current_peer) {
1942     return ErrorCode::UNKNOWN_CONNECTION;
1943   }
1944   if (!security_manager_.GetPinRequested(peer)) {
1945     LOG_INFO("No Pin Requested for %s", peer.ToString().c_str());
1946     return ErrorCode::COMMAND_DISALLOWED;
1947   }
1948   return ErrorCode::SUCCESS;
1949 }
1950 
UserConfirmationRequestReply(const Address & peer)1951 ErrorCode LinkLayerController::UserConfirmationRequestReply(
1952     const Address& peer) {
1953   if (security_manager_.GetAuthenticationAddress() != peer) {
1954     return ErrorCode::AUTHENTICATION_FAILURE;
1955   }
1956   SaveKeyAndAuthenticate('U', peer);
1957   return ErrorCode::SUCCESS;
1958 }
1959 
UserConfirmationRequestNegativeReply(const Address & peer)1960 ErrorCode LinkLayerController::UserConfirmationRequestNegativeReply(
1961     const Address& peer) {
1962   auto current_peer = security_manager_.GetAuthenticationAddress();
1963   security_manager_.AuthenticationRequestFinished();
1964   ScheduleTask(milliseconds(5), [this, current_peer]() {
1965     send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1966         ErrorCode::AUTHENTICATION_FAILURE, current_peer));
1967   });
1968   if (peer != current_peer) {
1969     return ErrorCode::UNKNOWN_CONNECTION;
1970   }
1971   return ErrorCode::SUCCESS;
1972 }
1973 
UserPasskeyRequestReply(const Address & peer,uint32_t numeric_value)1974 ErrorCode LinkLayerController::UserPasskeyRequestReply(const Address& peer,
1975                                                        uint32_t numeric_value) {
1976   if (security_manager_.GetAuthenticationAddress() != peer) {
1977     return ErrorCode::AUTHENTICATION_FAILURE;
1978   }
1979   SendLinkLayerPacket(model::packets::PasskeyBuilder::Create(
1980       properties_.GetAddress(), peer, numeric_value));
1981   SaveKeyAndAuthenticate('P', peer);
1982 
1983   return ErrorCode::SUCCESS;
1984 }
1985 
UserPasskeyRequestNegativeReply(const Address & peer)1986 ErrorCode LinkLayerController::UserPasskeyRequestNegativeReply(
1987     const Address& peer) {
1988   auto current_peer = security_manager_.GetAuthenticationAddress();
1989   security_manager_.AuthenticationRequestFinished();
1990   ScheduleTask(milliseconds(5), [this, current_peer]() {
1991     send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
1992         ErrorCode::AUTHENTICATION_FAILURE, current_peer));
1993   });
1994   if (peer != current_peer) {
1995     return ErrorCode::UNKNOWN_CONNECTION;
1996   }
1997   return ErrorCode::SUCCESS;
1998 }
1999 
RemoteOobDataRequestReply(const Address & peer,const std::array<uint8_t,16> & c,const std::array<uint8_t,16> & r)2000 ErrorCode LinkLayerController::RemoteOobDataRequestReply(
2001     const Address& peer, const std::array<uint8_t, 16>& c,
2002     const std::array<uint8_t, 16>& r) {
2003   if (security_manager_.GetAuthenticationAddress() != peer) {
2004     return ErrorCode::AUTHENTICATION_FAILURE;
2005   }
2006   LOG_INFO("TODO:Do something with the OOB data c=%d r=%d", c[0], r[0]);
2007   SaveKeyAndAuthenticate('o', peer);
2008 
2009   return ErrorCode::SUCCESS;
2010 }
2011 
RemoteOobDataRequestNegativeReply(const Address & peer)2012 ErrorCode LinkLayerController::RemoteOobDataRequestNegativeReply(
2013     const Address& peer) {
2014   auto current_peer = security_manager_.GetAuthenticationAddress();
2015   security_manager_.AuthenticationRequestFinished();
2016   ScheduleTask(milliseconds(5), [this, current_peer]() {
2017     send_event_(bluetooth::hci::SimplePairingCompleteBuilder::Create(
2018         ErrorCode::AUTHENTICATION_FAILURE, current_peer));
2019   });
2020   if (peer != current_peer) {
2021     return ErrorCode::UNKNOWN_CONNECTION;
2022   }
2023   return ErrorCode::SUCCESS;
2024 }
2025 
RemoteOobExtendedDataRequestReply(const Address & peer,const std::array<uint8_t,16> & c192,const std::array<uint8_t,16> & r192,const std::array<uint8_t,16> & c256,const std::array<uint8_t,16> & r256)2026 ErrorCode LinkLayerController::RemoteOobExtendedDataRequestReply(
2027     const Address& peer, const std::array<uint8_t, 16>& c192,
2028     const std::array<uint8_t, 16>& r192, const std::array<uint8_t, 16>& c256,
2029     const std::array<uint8_t, 16>& r256) {
2030   if (security_manager_.GetAuthenticationAddress() != peer) {
2031     return ErrorCode::AUTHENTICATION_FAILURE;
2032   }
2033   LOG_INFO(
2034       "TODO:Do something with the OOB data c192=%d r192=%d c256=%d r256=%d",
2035       c192[0], r192[0], c256[0], r256[0]);
2036   SaveKeyAndAuthenticate('O', peer);
2037 
2038   return ErrorCode::SUCCESS;
2039 }
2040 
SendKeypressNotification(const Address & peer,bluetooth::hci::KeypressNotificationType notification_type)2041 ErrorCode LinkLayerController::SendKeypressNotification(
2042     const Address& peer,
2043     bluetooth::hci::KeypressNotificationType notification_type) {
2044   if (notification_type >
2045       bluetooth::hci::KeypressNotificationType::ENTRY_COMPLETED) {
2046     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2047   }
2048 
2049   SendLinkLayerPacket(model::packets::KeypressNotificationBuilder::Create(
2050       properties_.GetAddress(), peer,
2051       static_cast<model::packets::PasskeyNotificationType>(notification_type)));
2052   return ErrorCode::SUCCESS;
2053 }
2054 
HandleAuthenticationRequest(const Address & address,uint16_t handle)2055 void LinkLayerController::HandleAuthenticationRequest(const Address& address,
2056                                                       uint16_t handle) {
2057     security_manager_.AuthenticationRequest(address, handle);
2058     auto packet = bluetooth::hci::LinkKeyRequestBuilder::Create(address);
2059     send_event_(std::move(packet));
2060 }
2061 
AuthenticationRequested(uint16_t handle)2062 ErrorCode LinkLayerController::AuthenticationRequested(uint16_t handle) {
2063   if (!connections_.HasHandle(handle)) {
2064     LOG_INFO("Authentication Requested for unknown handle %04x", handle);
2065     return ErrorCode::UNKNOWN_CONNECTION;
2066   }
2067 
2068   AddressWithType remote = connections_.GetAddress(handle);
2069 
2070   ScheduleTask(milliseconds(5), [this, remote, handle]() {
2071     HandleAuthenticationRequest(remote.GetAddress(), handle);
2072   });
2073 
2074   return ErrorCode::SUCCESS;
2075 }
2076 
HandleSetConnectionEncryption(const Address & peer,uint16_t handle,uint8_t encryption_enable)2077 void LinkLayerController::HandleSetConnectionEncryption(
2078     const Address& peer, uint16_t handle, uint8_t encryption_enable) {
2079   // TODO: Block ACL traffic or at least guard against it
2080 
2081   if (connections_.IsEncrypted(handle) && encryption_enable) {
2082     auto packet = bluetooth::hci::EncryptionChangeBuilder::Create(
2083         ErrorCode::SUCCESS, handle,
2084         static_cast<bluetooth::hci::EncryptionEnabled>(encryption_enable));
2085     send_event_(std::move(packet));
2086     return;
2087   }
2088 
2089   uint16_t count = security_manager_.ReadKey(peer);
2090   if (count == 0) {
2091     LOG_ERROR("NO KEY HERE for %s", peer.ToString().c_str());
2092     return;
2093   }
2094   auto array = security_manager_.GetKey(peer);
2095   std::vector<uint8_t> key_vec{array.begin(), array.end()};
2096   auto packet = model::packets::EncryptConnectionBuilder::Create(
2097       properties_.GetAddress(), peer, key_vec);
2098   SendLinkLayerPacket(std::move(packet));
2099 }
2100 
SetConnectionEncryption(uint16_t handle,uint8_t encryption_enable)2101 ErrorCode LinkLayerController::SetConnectionEncryption(
2102     uint16_t handle, uint8_t encryption_enable) {
2103   if (!connections_.HasHandle(handle)) {
2104     LOG_INFO("Set Connection Encryption for unknown handle %04x", handle);
2105     return ErrorCode::UNKNOWN_CONNECTION;
2106   }
2107 
2108   if (connections_.IsEncrypted(handle) && !encryption_enable) {
2109     return ErrorCode::ENCRYPTION_MODE_NOT_ACCEPTABLE;
2110   }
2111   AddressWithType remote = connections_.GetAddress(handle);
2112 
2113   if (security_manager_.ReadKey(remote.GetAddress()) == 0) {
2114     return ErrorCode::PIN_OR_KEY_MISSING;
2115   }
2116 
2117   ScheduleTask(milliseconds(5), [this, remote, handle, encryption_enable]() {
2118     HandleSetConnectionEncryption(remote.GetAddress(), handle,
2119                                   encryption_enable);
2120   });
2121   return ErrorCode::SUCCESS;
2122 }
2123 
AcceptConnectionRequest(const Address & addr,bool try_role_switch)2124 ErrorCode LinkLayerController::AcceptConnectionRequest(const Address& addr,
2125                                                        bool try_role_switch) {
2126   if (!connections_.HasPendingConnection(addr)) {
2127     LOG_INFO("No pending connection for %s", addr.ToString().c_str());
2128     return ErrorCode::UNKNOWN_CONNECTION;
2129   }
2130 
2131   LOG_INFO("Accept in 200ms");
2132   ScheduleTask(milliseconds(200), [this, addr, try_role_switch]() {
2133     LOG_INFO("Accepted");
2134     MakePeripheralConnection(addr, try_role_switch);
2135   });
2136 
2137   return ErrorCode::SUCCESS;
2138 }
2139 
MakePeripheralConnection(const Address & addr,bool try_role_switch)2140 void LinkLayerController::MakePeripheralConnection(const Address& addr,
2141                                                    bool try_role_switch) {
2142   LOG_INFO("Sending page response to %s", addr.ToString().c_str());
2143   auto to_send = model::packets::PageResponseBuilder::Create(
2144       properties_.GetAddress(), addr, try_role_switch);
2145   SendLinkLayerPacket(std::move(to_send));
2146 
2147   uint16_t handle =
2148       connections_.CreateConnection(addr, properties_.GetAddress());
2149   if (handle == kReservedHandle) {
2150     LOG_INFO("CreateConnection failed");
2151     return;
2152   }
2153   LOG_INFO("CreateConnection returned handle 0x%x", handle);
2154   auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
2155       ErrorCode::SUCCESS, handle, addr, bluetooth::hci::LinkType::ACL,
2156       bluetooth::hci::Enable::DISABLED);
2157   send_event_(std::move(packet));
2158 }
2159 
RejectConnectionRequest(const Address & addr,uint8_t reason)2160 ErrorCode LinkLayerController::RejectConnectionRequest(const Address& addr,
2161                                                        uint8_t reason) {
2162   if (!connections_.HasPendingConnection(addr)) {
2163     LOG_INFO("No pending connection for %s", addr.ToString().c_str());
2164     return ErrorCode::UNKNOWN_CONNECTION;
2165   }
2166 
2167   ScheduleTask(milliseconds(200), [this, addr, reason]() {
2168     RejectPeripheralConnection(addr, reason);
2169   });
2170 
2171   return ErrorCode::SUCCESS;
2172 }
2173 
RejectPeripheralConnection(const Address & addr,uint8_t reason)2174 void LinkLayerController::RejectPeripheralConnection(const Address& addr,
2175                                                      uint8_t reason) {
2176   auto to_send = model::packets::PageRejectBuilder::Create(
2177       properties_.GetAddress(), addr, reason);
2178   LOG_INFO("Sending page reject to %s (reason 0x%02hhx)",
2179            addr.ToString().c_str(), reason);
2180   SendLinkLayerPacket(std::move(to_send));
2181 
2182   auto packet = bluetooth::hci::ConnectionCompleteBuilder::Create(
2183       static_cast<ErrorCode>(reason), 0xeff, addr,
2184       bluetooth::hci::LinkType::ACL, bluetooth::hci::Enable::DISABLED);
2185   send_event_(std::move(packet));
2186 }
2187 
CreateConnection(const Address & addr,uint16_t,uint8_t,uint16_t,uint8_t allow_role_switch)2188 ErrorCode LinkLayerController::CreateConnection(const Address& addr, uint16_t,
2189                                                 uint8_t, uint16_t,
2190                                                 uint8_t allow_role_switch) {
2191   if (!connections_.CreatePendingConnection(
2192           addr, properties_.GetAuthenticationEnable() == 1)) {
2193     return ErrorCode::CONTROLLER_BUSY;
2194   }
2195   auto page = model::packets::PageBuilder::Create(
2196       properties_.GetAddress(), addr, properties_.GetClassOfDevice(),
2197       allow_role_switch);
2198   SendLinkLayerPacket(std::move(page));
2199 
2200   return ErrorCode::SUCCESS;
2201 }
2202 
CreateConnectionCancel(const Address & addr)2203 ErrorCode LinkLayerController::CreateConnectionCancel(const Address& addr) {
2204   if (!connections_.CancelPendingConnection(addr)) {
2205     return ErrorCode::UNKNOWN_CONNECTION;
2206   }
2207   return ErrorCode::SUCCESS;
2208 }
2209 
Disconnect(uint16_t handle,uint8_t reason)2210 ErrorCode LinkLayerController::Disconnect(uint16_t handle, uint8_t reason) {
2211   if (!connections_.HasHandle(handle)) {
2212     return ErrorCode::UNKNOWN_CONNECTION;
2213   }
2214 
2215   const AddressWithType remote = connections_.GetAddress(handle);
2216   auto packet = model::packets::DisconnectBuilder::Create(
2217       properties_.GetAddress(), remote.GetAddress(), reason);
2218   SendLinkLayerPacket(std::move(packet));
2219   ASSERT_LOG(connections_.Disconnect(handle), "Disconnecting %hx", handle);
2220 
2221   ScheduleTask(milliseconds(20), [this, handle]() {
2222     DisconnectCleanup(
2223         handle,
2224         static_cast<uint8_t>(ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST));
2225   });
2226 
2227   return ErrorCode::SUCCESS;
2228 }
2229 
DisconnectCleanup(uint16_t handle,uint8_t reason)2230 void LinkLayerController::DisconnectCleanup(uint16_t handle, uint8_t reason) {
2231   // TODO: Clean up other connection state.
2232   auto packet = bluetooth::hci::DisconnectionCompleteBuilder::Create(
2233       ErrorCode::SUCCESS, handle, static_cast<ErrorCode>(reason));
2234   send_event_(std::move(packet));
2235 }
2236 
ChangeConnectionPacketType(uint16_t handle,uint16_t types)2237 ErrorCode LinkLayerController::ChangeConnectionPacketType(uint16_t handle,
2238                                                           uint16_t types) {
2239   if (!connections_.HasHandle(handle)) {
2240     return ErrorCode::UNKNOWN_CONNECTION;
2241   }
2242   auto packet = bluetooth::hci::ConnectionPacketTypeChangedBuilder::Create(
2243       ErrorCode::SUCCESS, handle, types);
2244   std::shared_ptr<bluetooth::hci::ConnectionPacketTypeChangedBuilder>
2245       shared_packet = std::move(packet);
2246   ScheduleTask(milliseconds(20), [this, shared_packet]() {
2247     send_event_(std::move(shared_packet));
2248   });
2249 
2250   return ErrorCode::SUCCESS;
2251 }
2252 
ChangeConnectionLinkKey(uint16_t handle)2253 ErrorCode LinkLayerController::ChangeConnectionLinkKey(uint16_t handle) {
2254   if (!connections_.HasHandle(handle)) {
2255     return ErrorCode::UNKNOWN_CONNECTION;
2256   }
2257 
2258   // TODO: implement real logic
2259   return ErrorCode::COMMAND_DISALLOWED;
2260 }
2261 
CentralLinkKey(uint8_t)2262 ErrorCode LinkLayerController::CentralLinkKey(uint8_t /* key_flag */) {
2263   // TODO: implement real logic
2264   return ErrorCode::COMMAND_DISALLOWED;
2265 }
2266 
HoldMode(uint16_t handle,uint16_t hold_mode_max_interval,uint16_t hold_mode_min_interval)2267 ErrorCode LinkLayerController::HoldMode(uint16_t handle,
2268                                         uint16_t hold_mode_max_interval,
2269                                         uint16_t hold_mode_min_interval) {
2270   if (!connections_.HasHandle(handle)) {
2271     return ErrorCode::UNKNOWN_CONNECTION;
2272   }
2273 
2274   if (hold_mode_max_interval < hold_mode_min_interval) {
2275     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2276   }
2277 
2278   // TODO: implement real logic
2279   return ErrorCode::COMMAND_DISALLOWED;
2280 }
2281 
SniffMode(uint16_t handle,uint16_t sniff_max_interval,uint16_t sniff_min_interval,uint16_t sniff_attempt,uint16_t sniff_timeout)2282 ErrorCode LinkLayerController::SniffMode(uint16_t handle,
2283                                          uint16_t sniff_max_interval,
2284                                          uint16_t sniff_min_interval,
2285                                          uint16_t sniff_attempt,
2286                                          uint16_t sniff_timeout) {
2287   if (!connections_.HasHandle(handle)) {
2288     return ErrorCode::UNKNOWN_CONNECTION;
2289   }
2290 
2291   if (sniff_max_interval < sniff_min_interval || sniff_attempt < 0x0001 ||
2292       sniff_attempt > 0x7FFF || sniff_timeout > 0x7FFF) {
2293     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2294   }
2295 
2296   // TODO: implement real logic
2297   return ErrorCode::COMMAND_DISALLOWED;
2298 }
2299 
ExitSniffMode(uint16_t handle)2300 ErrorCode LinkLayerController::ExitSniffMode(uint16_t handle) {
2301   if (!connections_.HasHandle(handle)) {
2302     return ErrorCode::UNKNOWN_CONNECTION;
2303   }
2304 
2305   // TODO: implement real logic
2306   return ErrorCode::COMMAND_DISALLOWED;
2307 }
2308 
QosSetup(uint16_t handle,uint8_t service_type,uint32_t,uint32_t,uint32_t,uint32_t)2309 ErrorCode LinkLayerController::QosSetup(uint16_t handle, uint8_t service_type,
2310                                         uint32_t /* token_rate */,
2311                                         uint32_t /* peak_bandwidth */,
2312                                         uint32_t /* latency */,
2313                                         uint32_t /* delay_variation */) {
2314   if (!connections_.HasHandle(handle)) {
2315     return ErrorCode::UNKNOWN_CONNECTION;
2316   }
2317 
2318   if (service_type > 0x02) {
2319     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2320   }
2321 
2322   // TODO: implement real logic
2323   return ErrorCode::COMMAND_DISALLOWED;
2324 }
2325 
SwitchRole(Address,uint8_t)2326 ErrorCode LinkLayerController::SwitchRole(Address /* bd_addr */,
2327                                           uint8_t /* role */) {
2328   // TODO: implement real logic
2329   return ErrorCode::COMMAND_DISALLOWED;
2330 }
2331 
WriteLinkPolicySettings(uint16_t handle,uint16_t)2332 ErrorCode LinkLayerController::WriteLinkPolicySettings(uint16_t handle,
2333                                                        uint16_t) {
2334   if (!connections_.HasHandle(handle)) {
2335     return ErrorCode::UNKNOWN_CONNECTION;
2336   }
2337   return ErrorCode::SUCCESS;
2338 }
2339 
WriteDefaultLinkPolicySettings(uint16_t settings)2340 ErrorCode LinkLayerController::WriteDefaultLinkPolicySettings(
2341     uint16_t settings) {
2342   if (settings > 7 /* Sniff + Hold + Role switch */) {
2343     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2344   }
2345   default_link_policy_settings_ = settings;
2346   return ErrorCode::SUCCESS;
2347 }
2348 
ReadDefaultLinkPolicySettings()2349 uint16_t LinkLayerController::ReadDefaultLinkPolicySettings() {
2350   return default_link_policy_settings_;
2351 }
2352 
ReadLocalOobData()2353 void LinkLayerController::ReadLocalOobData() {
2354   std::array<uint8_t, 16> c_array(
2355       {'c', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '0', '0', '0', '0', '0', '0',
2356        static_cast<uint8_t>((oob_id_ % 0x10000) >> 8u),
2357        static_cast<uint8_t>(oob_id_ % 0x100)});
2358 
2359   std::array<uint8_t, 16> r_array(
2360       {'r', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '0', '0', '0', '0', '0', '0',
2361        static_cast<uint8_t>((oob_id_ % 0x10000) >> 8u),
2362        static_cast<uint8_t>(oob_id_ % 0x100)});
2363 
2364   send_event_(bluetooth::hci::ReadLocalOobDataCompleteBuilder::Create(
2365       1, ErrorCode::SUCCESS, c_array, r_array));
2366   oob_id_ += 1;
2367 }
2368 
ReadLocalOobExtendedData()2369 void LinkLayerController::ReadLocalOobExtendedData() {
2370   std::array<uint8_t, 16> c_192_array(
2371       {'c', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '1', '9', '2', '0', '0', '0',
2372        static_cast<uint8_t>((oob_id_ % 0x10000) >> 8u),
2373        static_cast<uint8_t>(oob_id_ % 0x100)});
2374 
2375   std::array<uint8_t, 16> r_192_array(
2376       {'r', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '1', '9', '2', '0', '0', '0',
2377        static_cast<uint8_t>((oob_id_ % 0x10000) >> 8u),
2378        static_cast<uint8_t>(oob_id_ % 0x100)});
2379 
2380   std::array<uint8_t, 16> c_256_array(
2381       {'c', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '2', '5', '6', '0', '0', '0',
2382        static_cast<uint8_t>((oob_id_ % 0x10000) >> 8u),
2383        static_cast<uint8_t>(oob_id_ % 0x100)});
2384 
2385   std::array<uint8_t, 16> r_256_array(
2386       {'r', ' ', 'a', 'r', 'r', 'a', 'y', ' ', '2', '5', '6', '0', '0', '0',
2387        static_cast<uint8_t>((oob_id_ % 0x10000) >> 8u),
2388        static_cast<uint8_t>(oob_id_ % 0x100)});
2389 
2390   send_event_(bluetooth::hci::ReadLocalOobExtendedDataCompleteBuilder::Create(
2391       1, ErrorCode::SUCCESS, c_192_array, r_192_array, c_256_array,
2392       r_256_array));
2393   oob_id_ += 1;
2394 }
2395 
FlowSpecification(uint16_t handle,uint8_t flow_direction,uint8_t service_type,uint32_t,uint32_t,uint32_t,uint32_t)2396 ErrorCode LinkLayerController::FlowSpecification(
2397     uint16_t handle, uint8_t flow_direction, uint8_t service_type,
2398     uint32_t /* token_rate */, uint32_t /* token_bucket_size */,
2399     uint32_t /* peak_bandwidth */, uint32_t /* access_latency */) {
2400   if (!connections_.HasHandle(handle)) {
2401     return ErrorCode::UNKNOWN_CONNECTION;
2402   }
2403 
2404   if (flow_direction > 0x01 || service_type > 0x02) {
2405     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2406   }
2407 
2408   // TODO: implement real logic
2409   return ErrorCode::COMMAND_DISALLOWED;
2410 }
2411 
WriteLinkSupervisionTimeout(uint16_t handle,uint16_t)2412 ErrorCode LinkLayerController::WriteLinkSupervisionTimeout(uint16_t handle,
2413                                                            uint16_t) {
2414   if (!connections_.HasHandle(handle)) {
2415     return ErrorCode::UNKNOWN_CONNECTION;
2416   }
2417   return ErrorCode::SUCCESS;
2418 }
2419 
SetLeExtendedAddress(uint8_t set,Address address)2420 ErrorCode LinkLayerController::SetLeExtendedAddress(uint8_t set,
2421                                                     Address address) {
2422   advertisers_[set].SetAddress(address);
2423   return ErrorCode::SUCCESS;
2424 }
2425 
SetLeExtendedAdvertisingData(uint8_t set,const std::vector<uint8_t> & data)2426 ErrorCode LinkLayerController::SetLeExtendedAdvertisingData(
2427     uint8_t set, const std::vector<uint8_t>& data) {
2428   advertisers_[set].SetData(data);
2429   return ErrorCode::SUCCESS;
2430 }
2431 
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)2432 ErrorCode LinkLayerController::SetLeExtendedAdvertisingParameters(
2433     uint8_t set, uint16_t interval_min, uint16_t interval_max,
2434     bluetooth::hci::LegacyAdvertisingProperties type,
2435     bluetooth::hci::OwnAddressType own_address_type,
2436     bluetooth::hci::PeerAddressType peer_address_type, Address peer,
2437     bluetooth::hci::AdvertisingFilterPolicy filter_policy) {
2438   model::packets::AdvertisementType ad_type;
2439   switch (type) {
2440     case bluetooth::hci::LegacyAdvertisingProperties::ADV_IND:
2441       ad_type = model::packets::AdvertisementType::ADV_IND;
2442       peer = Address::kEmpty;
2443       break;
2444     case bluetooth::hci::LegacyAdvertisingProperties::ADV_NONCONN_IND:
2445       ad_type = model::packets::AdvertisementType::ADV_NONCONN_IND;
2446       peer = Address::kEmpty;
2447       break;
2448     case bluetooth::hci::LegacyAdvertisingProperties::ADV_SCAN_IND:
2449       ad_type = model::packets::AdvertisementType::ADV_SCAN_IND;
2450       peer = Address::kEmpty;
2451       break;
2452     case bluetooth::hci::LegacyAdvertisingProperties::ADV_DIRECT_IND_HIGH:
2453     case bluetooth::hci::LegacyAdvertisingProperties::ADV_DIRECT_IND_LOW:
2454       ad_type = model::packets::AdvertisementType::ADV_DIRECT_IND;
2455       break;
2456   }
2457   auto interval_ms =
2458       static_cast<int>((interval_max + interval_min) * 0.625 / 2);
2459 
2460   AddressWithType peer_address;
2461   switch (peer_address_type) {
2462     case bluetooth::hci::PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS:
2463       peer_address = AddressWithType(
2464           peer, bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS);
2465       break;
2466     case bluetooth::hci::PeerAddressType::RANDOM_DEVICE_OR_IDENTITY_ADDRESS:
2467       peer_address = AddressWithType(
2468           peer, bluetooth::hci::AddressType::RANDOM_DEVICE_ADDRESS);
2469       break;
2470   }
2471 
2472   bluetooth::hci::AddressType own_address_address_type;
2473   switch (own_address_type) {
2474     case bluetooth::hci::OwnAddressType::RANDOM_DEVICE_ADDRESS:
2475       own_address_address_type =
2476           bluetooth::hci::AddressType::RANDOM_DEVICE_ADDRESS;
2477       break;
2478     case bluetooth::hci::OwnAddressType::PUBLIC_DEVICE_ADDRESS:
2479       own_address_address_type =
2480           bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS;
2481       break;
2482     case bluetooth::hci::OwnAddressType::RESOLVABLE_OR_PUBLIC_ADDRESS:
2483       own_address_address_type =
2484           bluetooth::hci::AddressType::PUBLIC_IDENTITY_ADDRESS;
2485       break;
2486     case bluetooth::hci::OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS:
2487       own_address_address_type =
2488           bluetooth::hci::AddressType::RANDOM_IDENTITY_ADDRESS;
2489       break;
2490   }
2491 
2492   bluetooth::hci::LeScanningFilterPolicy scanning_filter_policy;
2493   switch (filter_policy) {
2494     case bluetooth::hci::AdvertisingFilterPolicy::ALL_DEVICES:
2495       scanning_filter_policy =
2496           bluetooth::hci::LeScanningFilterPolicy::ACCEPT_ALL;
2497       break;
2498     case bluetooth::hci::AdvertisingFilterPolicy::LISTED_SCAN:
2499       scanning_filter_policy =
2500           bluetooth::hci::LeScanningFilterPolicy::CONNECT_LIST_ONLY;
2501       break;
2502     case bluetooth::hci::AdvertisingFilterPolicy::LISTED_CONNECT:
2503       scanning_filter_policy =
2504           bluetooth::hci::LeScanningFilterPolicy::CHECK_INITIATORS_IDENTITY;
2505       break;
2506     case bluetooth::hci::AdvertisingFilterPolicy::LISTED_SCAN_AND_CONNECT:
2507       scanning_filter_policy = bluetooth::hci::LeScanningFilterPolicy::
2508           CONNECT_LIST_AND_INITIATORS_IDENTITY;
2509       break;
2510   }
2511 
2512   advertisers_[set].InitializeExtended(own_address_address_type, peer_address,
2513                                        scanning_filter_policy, ad_type,
2514                                        std::chrono::milliseconds(interval_ms));
2515 
2516   return ErrorCode::SUCCESS;
2517 }
2518 
LeRemoveAdvertisingSet(uint8_t set)2519 ErrorCode LinkLayerController::LeRemoveAdvertisingSet(uint8_t set) {
2520   if (set >= advertisers_.size()) {
2521     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2522   }
2523   advertisers_[set].Disable();
2524   return ErrorCode::SUCCESS;
2525 }
2526 
LeClearAdvertisingSets()2527 ErrorCode LinkLayerController::LeClearAdvertisingSets() {
2528   for (auto& advertiser : advertisers_) {
2529     if (advertiser.IsEnabled()) {
2530       return ErrorCode::COMMAND_DISALLOWED;
2531     }
2532   }
2533   for (auto& advertiser : advertisers_) {
2534     advertiser.Clear();
2535   }
2536   return ErrorCode::SUCCESS;
2537 }
2538 
LeConnectionUpdateComplete(bluetooth::hci::LeConnectionUpdateView connection_update)2539 void LinkLayerController::LeConnectionUpdateComplete(
2540     bluetooth::hci::LeConnectionUpdateView connection_update) {
2541   uint16_t handle = connection_update.GetConnectionHandle();
2542   ErrorCode status = ErrorCode::SUCCESS;
2543   if (!connections_.HasHandle(handle)) {
2544     status = ErrorCode::UNKNOWN_CONNECTION;
2545   }
2546   uint16_t interval_min = connection_update.GetConnIntervalMin();
2547   uint16_t interval_max = connection_update.GetConnIntervalMax();
2548   uint16_t latency = connection_update.GetConnLatency();
2549   uint16_t supervision_timeout = connection_update.GetSupervisionTimeout();
2550 
2551   if (interval_min < 6 || interval_max > 0xC80 || interval_min > interval_max ||
2552       interval_max < interval_min || latency > 0x1F3 ||
2553       supervision_timeout < 0xA || supervision_timeout > 0xC80 ||
2554       // The Supervision_Timeout in milliseconds (*10) shall be larger than (1 +
2555       // Connection_Latency) * Connection_Interval_Max (* 5/4) * 2
2556       supervision_timeout <= ((((1 + latency) * interval_max * 10) / 4) / 10)) {
2557     status = ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2558   }
2559   uint16_t interval = (interval_min + interval_max) / 2;
2560   send_event_(bluetooth::hci::LeConnectionUpdateCompleteBuilder::Create(
2561       status, handle, interval, latency, supervision_timeout));
2562 }
2563 
LeConnectionUpdate(bluetooth::hci::LeConnectionUpdateView connection_update)2564 ErrorCode LinkLayerController::LeConnectionUpdate(
2565     bluetooth::hci::LeConnectionUpdateView connection_update) {
2566   uint16_t handle = connection_update.GetConnectionHandle();
2567   if (!connections_.HasHandle(handle)) {
2568     return ErrorCode::UNKNOWN_CONNECTION;
2569   }
2570 
2571   // This could negotiate with the remote device in the future
2572   ScheduleTask(milliseconds(25), [this, connection_update]() {
2573     LeConnectionUpdateComplete(connection_update);
2574   });
2575 
2576   return ErrorCode::SUCCESS;
2577 }
2578 
LeConnectListClear()2579 ErrorCode LinkLayerController::LeConnectListClear() {
2580   if (ConnectListBusy()) {
2581     return ErrorCode::COMMAND_DISALLOWED;
2582   }
2583 
2584   le_connect_list_.clear();
2585   return ErrorCode::SUCCESS;
2586 }
2587 
LeResolvingListClear()2588 ErrorCode LinkLayerController::LeResolvingListClear() {
2589   if (ResolvingListBusy()) {
2590     return ErrorCode::COMMAND_DISALLOWED;
2591   }
2592 
2593   le_resolving_list_.clear();
2594   return ErrorCode::SUCCESS;
2595 }
2596 
LeConnectListAddDevice(Address addr,uint8_t addr_type)2597 ErrorCode LinkLayerController::LeConnectListAddDevice(Address addr,
2598                                                       uint8_t addr_type) {
2599   if (ConnectListBusy()) {
2600     return ErrorCode::COMMAND_DISALLOWED;
2601   }
2602   std::tuple<Address, uint8_t> new_tuple = std::make_tuple(addr, addr_type);
2603   for (auto dev : le_connect_list_) {
2604     if (dev == new_tuple) {
2605       return ErrorCode::SUCCESS;
2606     }
2607   }
2608   if (LeConnectListFull()) {
2609     return ErrorCode::MEMORY_CAPACITY_EXCEEDED;
2610   }
2611   le_connect_list_.emplace_back(new_tuple);
2612   return ErrorCode::SUCCESS;
2613 }
2614 
LeResolvingListAddDevice(Address addr,uint8_t addr_type,std::array<uint8_t,kIrk_size> peerIrk,std::array<uint8_t,kIrk_size> localIrk)2615 ErrorCode LinkLayerController::LeResolvingListAddDevice(
2616     Address addr, uint8_t addr_type, std::array<uint8_t, kIrk_size> peerIrk,
2617     std::array<uint8_t, kIrk_size> localIrk) {
2618   if (ResolvingListBusy()) {
2619     return ErrorCode::COMMAND_DISALLOWED;
2620   }
2621   std::tuple<Address, uint8_t, std::array<uint8_t, kIrk_size>,
2622              std::array<uint8_t, kIrk_size>>
2623       new_tuple = std::make_tuple(addr, addr_type, peerIrk, localIrk);
2624   for (size_t i = 0; i < le_connect_list_.size(); i++) {
2625     auto curr = le_connect_list_[i];
2626     if (std::get<0>(curr) == addr && std::get<1>(curr) == addr_type) {
2627       le_resolving_list_[i] = new_tuple;
2628       return ErrorCode::SUCCESS;
2629     }
2630   }
2631   if (LeResolvingListFull()) {
2632     return ErrorCode::MEMORY_CAPACITY_EXCEEDED;
2633   }
2634   le_resolving_list_.emplace_back(new_tuple);
2635   return ErrorCode::SUCCESS;
2636 }
2637 
LeSetPrivacyMode(uint8_t address_type,Address addr,uint8_t mode)2638 void LinkLayerController::LeSetPrivacyMode(uint8_t address_type, Address addr,
2639                                            uint8_t mode) {
2640   // set mode for addr
2641   LOG_INFO("address type = %d ", address_type);
2642   LOG_INFO("address = %s ", addr.ToString().c_str());
2643   LOG_INFO("mode = %d ", mode);
2644 }
2645 
LeReadIsoTxSync(uint16_t handle)2646 void LinkLayerController::LeReadIsoTxSync(uint16_t handle) {}
2647 
LeSetCigParameters(uint8_t cig_id,uint32_t sdu_interval_m_to_s,uint32_t sdu_interval_s_to_m,bluetooth::hci::ClockAccuracy clock_accuracy,bluetooth::hci::Packing packing,bluetooth::hci::Enable framing,uint16_t max_transport_latency_m_to_s,uint16_t max_transport_latency_s_to_m,std::vector<bluetooth::hci::CisParametersConfig> cis_config)2648 void LinkLayerController::LeSetCigParameters(
2649     uint8_t cig_id, uint32_t sdu_interval_m_to_s, uint32_t sdu_interval_s_to_m,
2650     bluetooth::hci::ClockAccuracy clock_accuracy,
2651     bluetooth::hci::Packing packing, bluetooth::hci::Enable framing,
2652     uint16_t max_transport_latency_m_to_s,
2653     uint16_t max_transport_latency_s_to_m,
2654     std::vector<bluetooth::hci::CisParametersConfig> cis_config) {
2655   send_event_(connections_.SetCigParameters(
2656       cig_id, sdu_interval_m_to_s, sdu_interval_s_to_m, clock_accuracy, packing,
2657       framing, max_transport_latency_m_to_s, max_transport_latency_s_to_m,
2658       cis_config));
2659 }
2660 
LeCreateCis(std::vector<bluetooth::hci::CreateCisConfig> cis_config)2661 ErrorCode LinkLayerController::LeCreateCis(
2662     std::vector<bluetooth::hci::CreateCisConfig> cis_config) {
2663   if (connections_.HasPendingCis()) {
2664     return ErrorCode::COMMAND_DISALLOWED;
2665   }
2666   for (auto& config : cis_config) {
2667     if (!connections_.HasHandle(config.acl_connection_handle_)) {
2668       LOG_INFO("Unknown ACL handle %04x", config.acl_connection_handle_);
2669       return ErrorCode::UNKNOWN_CONNECTION;
2670     }
2671     if (!connections_.HasCisHandle(config.cis_connection_handle_)) {
2672       LOG_INFO("Unknown CIS handle %04x", config.cis_connection_handle_);
2673       return ErrorCode::UNKNOWN_CONNECTION;
2674     }
2675   }
2676   for (auto& config : cis_config) {
2677     connections_.CreatePendingCis(config);
2678     auto own_address =
2679         connections_.GetOwnAddress(config.acl_connection_handle_);
2680     auto peer_address = connections_.GetAddress(config.acl_connection_handle_);
2681     StreamParameters stream_parameters =
2682         connections_.GetStreamParameters(config.cis_connection_handle_);
2683     GroupParameters group_parameters =
2684         connections_.GetGroupParameters(stream_parameters.group_id);
2685 
2686     SendLeLinkLayerPacket(model::packets::IsoConnectionRequestBuilder::Create(
2687         own_address.GetAddress(), peer_address.GetAddress(),
2688         stream_parameters.group_id, group_parameters.sdu_interval_m_to_s,
2689         group_parameters.sdu_interval_s_to_m, group_parameters.interleaved,
2690         group_parameters.framed, group_parameters.max_transport_latency_m_to_s,
2691         group_parameters.max_transport_latency_s_to_m,
2692         stream_parameters.stream_id, stream_parameters.max_sdu_m_to_s,
2693         stream_parameters.max_sdu_s_to_m, config.cis_connection_handle_,
2694         config.acl_connection_handle_));
2695   }
2696   return ErrorCode::SUCCESS;
2697 }
2698 
LeRemoveCig(uint8_t cig_id)2699 ErrorCode LinkLayerController::LeRemoveCig(uint8_t cig_id) {
2700   return connections_.RemoveCig(cig_id);
2701 }
2702 
LeAcceptCisRequest(uint16_t cis_handle)2703 ErrorCode LinkLayerController::LeAcceptCisRequest(uint16_t cis_handle) {
2704   if (!connections_.HasPendingCisConnection(cis_handle)) {
2705     return ErrorCode::UNKNOWN_CONNECTION;
2706   }
2707   auto acl_handle = connections_.GetPendingAclHandle(cis_handle);
2708 
2709   connections_.ConnectCis(cis_handle);
2710 
2711   SendLeLinkLayerPacket(model::packets::IsoConnectionResponseBuilder::Create(
2712       connections_.GetOwnAddress(acl_handle).GetAddress(),
2713       connections_.GetAddress(acl_handle).GetAddress(),
2714       static_cast<uint8_t>(ErrorCode::SUCCESS), cis_handle, acl_handle,
2715       connections_.GetRemoteCisHandleForCisHandle(cis_handle)));
2716 
2717   // Both sides have to send LeCisEstablished event
2718 
2719   uint32_t cig_sync_delay = 0x100;
2720   uint32_t cis_sync_delay = 0x200;
2721   uint32_t latency_m_to_s = 0x200;
2722   uint32_t latency_s_to_m = 0x200;
2723   uint8_t nse = 1;
2724   uint8_t bn_m_to_s = 0;
2725   uint8_t bn_s_to_m = 0;
2726   uint8_t ft_m_to_s = 0;
2727   uint8_t ft_s_to_m = 0;
2728   uint8_t max_pdu_m_to_s = 0x40;
2729   uint8_t max_pdu_s_to_m = 0x40;
2730   uint16_t iso_interval = 0x100;
2731   send_event_(bluetooth::hci::LeCisEstablishedBuilder::Create(
2732       ErrorCode::SUCCESS, cis_handle, cig_sync_delay, cis_sync_delay,
2733       latency_m_to_s, latency_s_to_m,
2734       bluetooth::hci::SecondaryPhyType::NO_PACKETS,
2735       bluetooth::hci::SecondaryPhyType::NO_PACKETS, nse, bn_m_to_s, bn_s_to_m,
2736       ft_m_to_s, ft_s_to_m, max_pdu_m_to_s, max_pdu_s_to_m, iso_interval));
2737   return ErrorCode::SUCCESS;
2738 }
2739 
LeRejectCisRequest(uint16_t cis_handle,ErrorCode reason)2740 ErrorCode LinkLayerController::LeRejectCisRequest(uint16_t cis_handle,
2741                                                   ErrorCode reason) {
2742   if (!connections_.HasPendingCisConnection(cis_handle)) {
2743     return ErrorCode::UNKNOWN_CONNECTION;
2744   }
2745   auto acl_handle = connections_.GetPendingAclHandle(cis_handle);
2746 
2747   SendLeLinkLayerPacket(model::packets::IsoConnectionResponseBuilder::Create(
2748       connections_.GetOwnAddress(acl_handle).GetAddress(),
2749       connections_.GetAddress(acl_handle).GetAddress(),
2750       static_cast<uint8_t>(reason), acl_handle, cis_handle, kReservedHandle));
2751   connections_.RejectCis(cis_handle);
2752   return ErrorCode::SUCCESS;
2753 }
2754 
LeCreateBig(uint8_t big_handle,uint8_t advertising_handle,uint8_t num_bis,uint32_t sdu_interval,uint16_t max_sdu,uint16_t max_transport_latency,uint8_t rtn,bluetooth::hci::SecondaryPhyType phy,bluetooth::hci::Packing packing,bluetooth::hci::Enable framing,bluetooth::hci::Enable encryption,std::vector<uint16_t> broadcast_code)2755 ErrorCode LinkLayerController::LeCreateBig(
2756     uint8_t big_handle, uint8_t advertising_handle, uint8_t num_bis,
2757     uint32_t sdu_interval, uint16_t max_sdu, uint16_t max_transport_latency,
2758     uint8_t rtn, bluetooth::hci::SecondaryPhyType phy,
2759     bluetooth::hci::Packing packing, bluetooth::hci::Enable framing,
2760     bluetooth::hci::Enable encryption, std::vector<uint16_t> broadcast_code) {
2761   return ErrorCode::SUCCESS;
2762 }
2763 
LeTerminateBig(uint8_t big_handle,ErrorCode reason)2764 ErrorCode LinkLayerController::LeTerminateBig(uint8_t big_handle,
2765                                               ErrorCode reason) {
2766   return ErrorCode::SUCCESS;
2767 }
2768 
LeBigCreateSync(uint8_t big_handle,uint16_t sync_handle,bluetooth::hci::Enable encryption,std::vector<uint16_t> broadcast_code,uint8_t mse,uint16_t big_sync_timeout,std::vector<uint8_t> bis)2769 ErrorCode LinkLayerController::LeBigCreateSync(
2770     uint8_t big_handle, uint16_t sync_handle, bluetooth::hci::Enable encryption,
2771     std::vector<uint16_t> broadcast_code, uint8_t mse,
2772     uint16_t big_sync_timeout, std::vector<uint8_t> bis) {
2773   return ErrorCode::SUCCESS;
2774 }
2775 
LeBigTerminateSync(uint8_t big_handle)2776 void LinkLayerController::LeBigTerminateSync(uint8_t big_handle) {}
2777 
LeRequestPeerSca(uint16_t request_handle)2778 ErrorCode LinkLayerController::LeRequestPeerSca(uint16_t request_handle) {
2779   return ErrorCode::SUCCESS;
2780 }
2781 
LeSetupIsoDataPath(uint16_t connection_handle,bluetooth::hci::DataPathDirection data_path_direction,uint8_t data_path_id,uint64_t codec_id,uint32_t controller_Delay,std::vector<uint8_t> codec_configuration)2782 void LinkLayerController::LeSetupIsoDataPath(
2783     uint16_t connection_handle,
2784     bluetooth::hci::DataPathDirection data_path_direction, uint8_t data_path_id,
2785     uint64_t codec_id, uint32_t controller_Delay,
2786     std::vector<uint8_t> codec_configuration) {}
2787 
LeRemoveIsoDataPath(uint16_t connection_handle,bluetooth::hci::DataPathDirection data_path_direction)2788 void LinkLayerController::LeRemoveIsoDataPath(
2789     uint16_t connection_handle,
2790     bluetooth::hci::DataPathDirection data_path_direction) {}
2791 
HandleLeEnableEncryption(uint16_t handle,std::array<uint8_t,8> rand,uint16_t ediv,std::array<uint8_t,16> ltk)2792 void LinkLayerController::HandleLeEnableEncryption(
2793     uint16_t handle, std::array<uint8_t, 8> rand, uint16_t ediv,
2794     std::array<uint8_t, 16> ltk) {
2795   // TODO: Check keys
2796   // TODO: Block ACL traffic or at least guard against it
2797   if (!connections_.HasHandle(handle)) {
2798     return;
2799   }
2800   SendLeLinkLayerPacket(model::packets::LeEncryptConnectionBuilder::Create(
2801       connections_.GetOwnAddress(handle).GetAddress(),
2802       connections_.GetAddress(handle).GetAddress(), rand, ediv, ltk));
2803 }
2804 
LeEnableEncryption(uint16_t handle,std::array<uint8_t,8> rand,uint16_t ediv,std::array<uint8_t,16> ltk)2805 ErrorCode LinkLayerController::LeEnableEncryption(uint16_t handle,
2806                                                   std::array<uint8_t, 8> rand,
2807                                                   uint16_t ediv,
2808                                                   std::array<uint8_t, 16> ltk) {
2809   if (!connections_.HasHandle(handle)) {
2810     LOG_INFO("Unknown handle %04x", handle);
2811     return ErrorCode::UNKNOWN_CONNECTION;
2812   }
2813 
2814   ScheduleTask(milliseconds(5), [this, handle, rand, ediv, ltk]() {
2815     HandleLeEnableEncryption(handle, rand, ediv, ltk);
2816   });
2817   return ErrorCode::SUCCESS;
2818 }
2819 
LeLongTermKeyRequestReply(uint16_t handle,std::array<uint8_t,16> ltk)2820 ErrorCode LinkLayerController::LeLongTermKeyRequestReply(
2821     uint16_t handle, std::array<uint8_t, 16> ltk) {
2822   if (!connections_.HasHandle(handle)) {
2823     LOG_INFO("Unknown handle %04x", handle);
2824     return ErrorCode::UNKNOWN_CONNECTION;
2825   }
2826 
2827   // TODO: Check keys
2828   if (connections_.IsEncrypted(handle)) {
2829     send_event_(bluetooth::hci::EncryptionKeyRefreshCompleteBuilder::Create(
2830         ErrorCode::SUCCESS, handle));
2831   } else {
2832     connections_.Encrypt(handle);
2833     send_event_(bluetooth::hci::EncryptionChangeBuilder::Create(
2834         ErrorCode::SUCCESS, handle, bluetooth::hci::EncryptionEnabled::ON));
2835   }
2836   SendLeLinkLayerPacket(
2837       model::packets::LeEncryptConnectionResponseBuilder::Create(
2838           connections_.GetOwnAddress(handle).GetAddress(),
2839           connections_.GetAddress(handle).GetAddress(),
2840           std::array<uint8_t, 8>(), uint16_t(), ltk));
2841 
2842   return ErrorCode::SUCCESS;
2843 }
2844 
LeLongTermKeyRequestNegativeReply(uint16_t handle)2845 ErrorCode LinkLayerController::LeLongTermKeyRequestNegativeReply(
2846     uint16_t handle) {
2847   if (!connections_.HasHandle(handle)) {
2848     LOG_INFO("Unknown handle %04x", handle);
2849     return ErrorCode::UNKNOWN_CONNECTION;
2850   }
2851 
2852   SendLeLinkLayerPacket(
2853       model::packets::LeEncryptConnectionResponseBuilder::Create(
2854           connections_.GetOwnAddress(handle).GetAddress(),
2855           connections_.GetAddress(handle).GetAddress(),
2856           std::array<uint8_t, 8>(), uint16_t(), std::array<uint8_t, 16>()));
2857   return ErrorCode::SUCCESS;
2858 }
2859 
SetLeAdvertisingEnable(uint8_t le_advertising_enable)2860 ErrorCode LinkLayerController::SetLeAdvertisingEnable(
2861     uint8_t le_advertising_enable) {
2862   if (!le_advertising_enable) {
2863     advertisers_[0].Disable();
2864     return ErrorCode::SUCCESS;
2865   }
2866   auto interval_ms = (properties_.GetLeAdvertisingIntervalMax() +
2867                       properties_.GetLeAdvertisingIntervalMin()) *
2868                      0.625 / 2;
2869 
2870   Address own_address = properties_.GetAddress();
2871   if (properties_.GetLeAdvertisingOwnAddressType() ==
2872           static_cast<uint8_t>(
2873               bluetooth::hci::AddressType::RANDOM_DEVICE_ADDRESS) ||
2874       properties_.GetLeAdvertisingOwnAddressType() ==
2875           static_cast<uint8_t>(
2876               bluetooth::hci::AddressType::RANDOM_IDENTITY_ADDRESS)) {
2877     if (properties_.GetLeAddress().ToString() == "bb:bb:bb:ba:d0:1e" ||
2878         properties_.GetLeAddress() == Address::kEmpty) {
2879       return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2880     }
2881     own_address = properties_.GetLeAddress();
2882   }
2883   auto own_address_with_type = AddressWithType(
2884       own_address, static_cast<bluetooth::hci::AddressType>(
2885                        properties_.GetLeAdvertisingOwnAddressType()));
2886 
2887   auto interval = std::chrono::milliseconds(static_cast<uint64_t>(interval_ms));
2888   if (interval < std::chrono::milliseconds(20)) {
2889     return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2890   }
2891   advertisers_[0].Initialize(
2892       own_address_with_type,
2893       bluetooth::hci::AddressWithType(
2894           properties_.GetLeAdvertisingPeerAddress(),
2895           static_cast<bluetooth::hci::AddressType>(
2896               properties_.GetLeAdvertisingPeerAddressType())),
2897       static_cast<bluetooth::hci::LeScanningFilterPolicy>(
2898           properties_.GetLeAdvertisingFilterPolicy()),
2899       static_cast<model::packets::AdvertisementType>(
2900           properties_.GetLeAdvertisementType()),
2901       properties_.GetLeAdvertisement(), properties_.GetLeScanResponse(),
2902       interval);
2903   advertisers_[0].Enable();
2904   return ErrorCode::SUCCESS;
2905 }
2906 
LeDisableAdvertisingSets()2907 void LinkLayerController::LeDisableAdvertisingSets() {
2908   for (auto& advertiser : advertisers_) {
2909     advertiser.Disable();
2910   }
2911 }
2912 
LeReadNumberOfSupportedAdvertisingSets()2913 uint8_t LinkLayerController::LeReadNumberOfSupportedAdvertisingSets() {
2914   return advertisers_.size();
2915 }
2916 
SetLeExtendedAdvertisingEnable(bluetooth::hci::Enable enable,const std::vector<bluetooth::hci::EnabledSet> & enabled_sets)2917 ErrorCode LinkLayerController::SetLeExtendedAdvertisingEnable(
2918     bluetooth::hci::Enable enable,
2919     const std::vector<bluetooth::hci::EnabledSet>& enabled_sets) {
2920   for (const auto& set : enabled_sets) {
2921     if (set.advertising_handle_ > advertisers_.size()) {
2922       return ErrorCode::INVALID_HCI_COMMAND_PARAMETERS;
2923     }
2924   }
2925   for (const auto& set : enabled_sets) {
2926     auto handle = set.advertising_handle_;
2927     if (enable == bluetooth::hci::Enable::ENABLED) {
2928       advertisers_[handle].EnableExtended(
2929           std::chrono::milliseconds(10 * set.duration_));
2930     } else {
2931       advertisers_[handle].Disable();
2932     }
2933   }
2934   return ErrorCode::SUCCESS;
2935 }
2936 
ConnectListBusy()2937 bool LinkLayerController::ConnectListBusy() {
2938   if (le_connect_) LOG_INFO("le_connect_");
2939   if (le_scan_enable_ != bluetooth::hci::OpCode::NONE)
2940     LOG_INFO("le_scan_enable");
2941   for (auto advertiser : advertisers_)
2942     if (advertiser.IsEnabled()) {
2943       LOG_INFO("Advertising");
2944       return true;
2945     }
2946   return le_connect_ || le_scan_enable_ != bluetooth::hci::OpCode::NONE;
2947 }
2948 
ResolvingListBusy()2949 bool LinkLayerController::ResolvingListBusy() {
2950   return ConnectListBusy();  // TODO: Add
2951                              // HCI_LE_Periodic_Advertising_Create_Sync
2952 }
2953 
LeConnectListRemoveDevice(Address addr,uint8_t addr_type)2954 ErrorCode LinkLayerController::LeConnectListRemoveDevice(Address addr,
2955                                                          uint8_t addr_type) {
2956   if (ConnectListBusy()) {
2957     return ErrorCode::COMMAND_DISALLOWED;
2958   }
2959   std::tuple<Address, uint8_t> erase_tuple = std::make_tuple(addr, addr_type);
2960   for (size_t i = 0; i < le_connect_list_.size(); i++) {
2961     if (le_connect_list_[i] == erase_tuple) {
2962       le_connect_list_.erase(le_connect_list_.begin() + i);
2963     }
2964   }
2965   return ErrorCode::SUCCESS;
2966 }
2967 
LeResolvingListRemoveDevice(Address addr,uint8_t addr_type)2968 ErrorCode LinkLayerController::LeResolvingListRemoveDevice(Address addr,
2969                                                            uint8_t addr_type) {
2970   if (ResolvingListBusy()) {
2971     return ErrorCode::COMMAND_DISALLOWED;
2972   }
2973   for (size_t i = 0; i < le_connect_list_.size(); i++) {
2974     auto curr = le_connect_list_[i];
2975     if (std::get<0>(curr) == addr && std::get<1>(curr) == addr_type) {
2976       le_resolving_list_.erase(le_resolving_list_.begin() + i);
2977     }
2978   }
2979   return ErrorCode::SUCCESS;
2980 }
2981 
LeConnectListContainsDevice(Address addr,uint8_t addr_type)2982 bool LinkLayerController::LeConnectListContainsDevice(Address addr,
2983                                                       uint8_t addr_type) {
2984   std::tuple<Address, uint8_t> sought_tuple = std::make_tuple(addr, addr_type);
2985   for (size_t i = 0; i < le_connect_list_.size(); i++) {
2986     if (le_connect_list_[i] == sought_tuple) {
2987       return true;
2988     }
2989   }
2990   return false;
2991 }
2992 
LeResolvingListContainsDevice(Address addr,uint8_t addr_type)2993 bool LinkLayerController::LeResolvingListContainsDevice(Address addr,
2994                                                         uint8_t addr_type) {
2995   for (size_t i = 0; i < le_connect_list_.size(); i++) {
2996     auto curr = le_connect_list_[i];
2997     if (std::get<0>(curr) == addr && std::get<1>(curr) == addr_type) {
2998       return true;
2999     }
3000   }
3001   return false;
3002 }
3003 
LeConnectListFull()3004 bool LinkLayerController::LeConnectListFull() {
3005   return le_connect_list_.size() >= properties_.GetLeConnectListSize();
3006 }
3007 
LeResolvingListFull()3008 bool LinkLayerController::LeResolvingListFull() {
3009   return le_resolving_list_.size() >= properties_.GetLeResolvingListSize();
3010 }
3011 
Reset()3012 void LinkLayerController::Reset() {
3013   if (inquiry_timer_task_id_ != kInvalidTaskId) {
3014     CancelScheduledTask(inquiry_timer_task_id_);
3015     inquiry_timer_task_id_ = kInvalidTaskId;
3016   }
3017   last_inquiry_ = steady_clock::now();
3018   le_scan_enable_ = bluetooth::hci::OpCode::NONE;
3019   LeDisableAdvertisingSets();
3020   le_connect_ = 0;
3021 }
3022 
StartInquiry(milliseconds timeout)3023 void LinkLayerController::StartInquiry(milliseconds timeout) {
3024   inquiry_timer_task_id_ = ScheduleTask(milliseconds(timeout), [this]() {
3025     LinkLayerController::InquiryTimeout();
3026   });
3027 }
3028 
InquiryCancel()3029 void LinkLayerController::InquiryCancel() {
3030   ASSERT(inquiry_timer_task_id_ != kInvalidTaskId);
3031   CancelScheduledTask(inquiry_timer_task_id_);
3032   inquiry_timer_task_id_ = kInvalidTaskId;
3033 }
3034 
InquiryTimeout()3035 void LinkLayerController::InquiryTimeout() {
3036   if (inquiry_timer_task_id_ != kInvalidTaskId) {
3037     inquiry_timer_task_id_ = kInvalidTaskId;
3038     auto packet =
3039         bluetooth::hci::InquiryCompleteBuilder::Create(ErrorCode::SUCCESS);
3040     send_event_(std::move(packet));
3041   }
3042 }
3043 
SetInquiryMode(uint8_t mode)3044 void LinkLayerController::SetInquiryMode(uint8_t mode) {
3045   inquiry_mode_ = static_cast<model::packets::InquiryType>(mode);
3046 }
3047 
SetInquiryLAP(uint64_t lap)3048 void LinkLayerController::SetInquiryLAP(uint64_t lap) { inquiry_lap_ = lap; }
3049 
SetInquiryMaxResponses(uint8_t max)3050 void LinkLayerController::SetInquiryMaxResponses(uint8_t max) {
3051   inquiry_max_responses_ = max;
3052 }
3053 
Inquiry()3054 void LinkLayerController::Inquiry() {
3055   steady_clock::time_point now = steady_clock::now();
3056   if (duration_cast<milliseconds>(now - last_inquiry_) < milliseconds(2000)) {
3057     return;
3058   }
3059 
3060   auto packet = model::packets::InquiryBuilder::Create(
3061       properties_.GetAddress(), Address::kEmpty, inquiry_mode_);
3062   SendLinkLayerPacket(std::move(packet));
3063   last_inquiry_ = now;
3064 }
3065 
SetInquiryScanEnable(bool enable)3066 void LinkLayerController::SetInquiryScanEnable(bool enable) {
3067   inquiry_scans_enabled_ = enable;
3068 }
3069 
SetPageScanEnable(bool enable)3070 void LinkLayerController::SetPageScanEnable(bool enable) {
3071   page_scans_enabled_ = enable;
3072 }
3073 
3074 }  // namespace test_vendor_lib
3075