• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define LOG_TAG "link_layer_controller"
18 
19 #include "link_layer_controller.h"
20 
21 #include <base/logging.h>
22 
23 #include "hci.h"
24 #include "osi/include/log.h"
25 #include "packets/hci/acl_packet_builder.h"
26 #include "packets/hci/command_packet_view.h"
27 #include "packets/hci/event_packet_builder.h"
28 #include "packets/hci/sco_packet_builder.h"
29 #include "packets/link_layer/command_builder.h"
30 #include "packets/link_layer/command_view.h"
31 #include "packets/link_layer/disconnect_view.h"
32 #include "packets/link_layer/encrypt_connection_view.h"
33 #include "packets/link_layer/inquiry_response_view.h"
34 #include "packets/link_layer/inquiry_view.h"
35 #include "packets/link_layer/io_capability_view.h"
36 #include "packets/link_layer/le_advertisement_view.h"
37 #include "packets/link_layer/page_response_view.h"
38 #include "packets/link_layer/page_view.h"
39 #include "packets/link_layer/response_view.h"
40 
41 using std::vector;
42 using namespace std::chrono;
43 using namespace test_vendor_lib::packets;
44 
45 namespace test_vendor_lib {
46 
47 // TODO: Model Rssi?
GetRssi()48 static uint8_t GetRssi() {
49   static uint8_t rssi = 0;
50   rssi += 5;
51   if (rssi > 128) {
52     rssi = rssi % 7;
53   }
54   return -(rssi);
55 }
56 
SendLELinkLayerPacket(std::shared_ptr<LinkLayerPacketBuilder> packet)57 void LinkLayerController::SendLELinkLayerPacket(std::shared_ptr<LinkLayerPacketBuilder> packet) {
58   if (schedule_task_) {
59     schedule_task_(milliseconds(50), [this, packet]() { send_to_remote_(packet, Phy::Type::LOW_ENERGY); });
60   } else {
61     send_to_remote_(packet, Phy::Type::LOW_ENERGY);
62   }
63 }
64 
SendLinkLayerPacket(std::shared_ptr<LinkLayerPacketBuilder> packet)65 void LinkLayerController::SendLinkLayerPacket(std::shared_ptr<LinkLayerPacketBuilder> packet) {
66   if (schedule_task_) {
67     schedule_task_(milliseconds(50), [this, packet]() { send_to_remote_(packet, Phy::Type::BR_EDR); });
68   } else {
69     send_to_remote_(packet, Phy::Type::BR_EDR);
70   }
71 }
72 
SendCommandToRemoteByAddress(hci::OpCode opcode,PacketView<true> args,const Address & remote,bool use_public_address)73 hci::Status LinkLayerController::SendCommandToRemoteByAddress(hci::OpCode opcode, PacketView<true> args,
74                                                               const Address& remote, bool use_public_address) {
75   std::shared_ptr<LinkLayerPacketBuilder> command;
76   Address local_address;
77   if (use_public_address) {
78     local_address = properties_.GetAddress();
79   } else {
80     local_address = properties_.GetLeAddress();
81   }
82   command = LinkLayerPacketBuilder::WrapCommand(CommandBuilder::Create(static_cast<uint16_t>(opcode), args),
83                                                 local_address, remote);
84   SendLinkLayerPacket(std::move(command));
85   return hci::Status::SUCCESS;
86 }
87 
SendCommandToRemoteByHandle(hci::OpCode opcode,PacketView<true> args,uint16_t handle)88 hci::Status LinkLayerController::SendCommandToRemoteByHandle(hci::OpCode opcode, PacketView<true> args,
89                                                              uint16_t handle) {
90   // TODO: Handle LE connections
91   bool use_public_address = true;
92   if (!classic_connections_.HasHandle(handle)) {
93     return hci::Status::UNKNOWN_CONNECTION;
94   }
95   return SendCommandToRemoteByAddress(opcode, args, classic_connections_.GetAddress(handle), use_public_address);
96 }
97 
SendAclToRemote(AclPacketView acl_packet)98 hci::Status LinkLayerController::SendAclToRemote(AclPacketView acl_packet) {
99   // TODO: Handle LE connections
100   uint16_t handle = acl_packet.GetHandle();
101   if (!classic_connections_.HasHandle(handle)) {
102     return hci::Status::UNKNOWN_CONNECTION;
103   }
104 
105   std::unique_ptr<ViewForwarderBuilder> acl_builder = ViewForwarderBuilder::Create(acl_packet);
106 
107   std::shared_ptr<LinkLayerPacketBuilder> acl = LinkLayerPacketBuilder::WrapAcl(
108       std::move(acl_builder), properties_.GetAddress(), classic_connections_.GetAddress(handle));
109 
110   LOG_INFO(LOG_TAG, "%s(%s): handle 0x%x size %d", __func__, properties_.GetAddress().ToString().c_str(), handle,
111            static_cast<int>(acl_packet.size()));
112 
113   schedule_task_(milliseconds(5), [this, handle]() {
114     send_event_(EventPacketBuilder::CreateNumberOfCompletedPacketsEvent(handle, 1)->ToVector());
115   });
116   SendLinkLayerPacket(acl);
117   return hci::Status::SUCCESS;
118 }
119 
IncomingPacket(LinkLayerPacketView incoming)120 void LinkLayerController::IncomingPacket(LinkLayerPacketView incoming) {
121   // TODO: Resolvable private addresses?
122   if (incoming.GetDestinationAddress() != properties_.GetAddress() &&
123       incoming.GetDestinationAddress() != properties_.GetLeAddress() &&
124       incoming.GetDestinationAddress() != Address::kEmpty) {
125     // Drop packets not addressed to me
126     return;
127   }
128 
129   switch (incoming.GetType()) {
130     case Link::PacketType::ACL:
131       IncomingAclPacket(incoming);
132       break;
133     case Link::PacketType::COMMAND:
134       IncomingCommandPacket(incoming);
135       break;
136     case Link::PacketType::DISCONNECT:
137       IncomingDisconnectPacket(incoming);
138       break;
139     case Link::PacketType::ENCRYPT_CONNECTION:
140       IncomingEncryptConnection(incoming);
141       break;
142     case Link::PacketType::ENCRYPT_CONNECTION_RESPONSE:
143       IncomingEncryptConnectionResponse(incoming);
144       break;
145     case Link::PacketType::INQUIRY:
146       if (inquiry_scans_enabled_) {
147         IncomingInquiryPacket(incoming);
148       }
149       break;
150     case Link::PacketType::INQUIRY_RESPONSE:
151       IncomingInquiryResponsePacket(incoming);
152       break;
153     case Link::PacketType::IO_CAPABILITY_REQUEST:
154       IncomingIoCapabilityRequestPacket(incoming);
155       break;
156     case Link::PacketType::IO_CAPABILITY_RESPONSE:
157       IncomingIoCapabilityResponsePacket(incoming);
158       break;
159     case Link::PacketType::IO_CAPABILITY_NEGATIVE_RESPONSE:
160       IncomingIoCapabilityNegativeResponsePacket(incoming);
161       break;
162     case Link::PacketType::LE_ADVERTISEMENT:
163       if (le_scan_enable_ || le_connect_) {
164         IncomingLeAdvertisementPacket(incoming);
165       }
166       break;
167     case Link::PacketType::LE_SCAN:
168       // TODO: Check Advertising flags and see if we are scannable.
169       IncomingLeScanPacket(incoming);
170       break;
171     case Link::PacketType::LE_SCAN_RESPONSE:
172       if (le_scan_enable_ && le_scan_type_ == 1) {
173         IncomingLeScanResponsePacket(incoming);
174       }
175       break;
176     case Link::PacketType::PAGE:
177       if (page_scans_enabled_) {
178         IncomingPagePacket(incoming);
179       }
180       break;
181     case Link::PacketType::PAGE_RESPONSE:
182       IncomingPageResponsePacket(incoming);
183       break;
184     case Link::PacketType::RESPONSE:
185       IncomingResponsePacket(incoming);
186       break;
187     default:
188       LOG_WARN(LOG_TAG, "Dropping unhandled packet of type %d", static_cast<int32_t>(incoming.GetType()));
189   }
190 }
191 
IncomingAclPacket(LinkLayerPacketView incoming)192 void LinkLayerController::IncomingAclPacket(LinkLayerPacketView incoming) {
193   LOG_INFO(LOG_TAG, "Acl Packet %s -> %s", incoming.GetSourceAddress().ToString().c_str(),
194            incoming.GetDestinationAddress().ToString().c_str());
195   AclPacketView acl_view = AclPacketView::Create(incoming.GetPayload());
196   LOG_INFO(LOG_TAG, "%s: remote handle 0x%x size %d", __func__, acl_view.GetHandle(),
197            static_cast<int>(acl_view.size()));
198   uint16_t local_handle = classic_connections_.GetHandle(incoming.GetSourceAddress());
199   LOG_INFO(LOG_TAG, "%s: local handle 0x%x", __func__, local_handle);
200 
201   acl::PacketBoundaryFlagsType boundary_flags = acl_view.GetPacketBoundaryFlags();
202   acl::BroadcastFlagsType broadcast_flags = acl_view.GetBroadcastFlags();
203   std::unique_ptr<ViewForwarderBuilder> builder = ViewForwarderBuilder::Create(acl_view.GetPayload());
204   std::unique_ptr<AclPacketBuilder> local_acl =
205       AclPacketBuilder::Create(local_handle, boundary_flags, broadcast_flags, std::move(builder));
206   send_acl_(local_acl->ToVector());
207 }
208 
IncomingCommandPacket(LinkLayerPacketView incoming)209 void LinkLayerController::IncomingCommandPacket(LinkLayerPacketView incoming) {
210   // TODO: Check the destination address to see if this packet is for me.
211   CommandView command = CommandView::GetCommand(incoming);
212   hci::OpCode opcode = static_cast<hci::OpCode>(command.GetOpcode());
213   auto args = command.GetData();
214   std::vector<uint64_t> response_data;
215 
216   switch (opcode) {
217     case (hci::OpCode::REMOTE_NAME_REQUEST): {
218       std::vector<uint8_t> name = properties_.GetName();
219       LOG_INFO(LOG_TAG, "Remote Name (Local Name) %d", static_cast<int>(name.size()));
220       response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
221       response_data.push_back(name.size());
222       uint64_t word = 0;
223       for (size_t i = 0; i < name.size(); i++) {
224         if (i > 0 && (i % 8 == 0)) {
225           response_data.push_back(word);
226           word = 0;
227         }
228         word |= static_cast<uint64_t>(name[i]) << (8 * (i % 8));
229       }
230       response_data.push_back(word);
231     } break;
232     case (hci::OpCode::READ_REMOTE_SUPPORTED_FEATURES):
233       LOG_INFO(LOG_TAG, "(%s) Remote Supported Features Requested by: %s %x",
234                incoming.GetDestinationAddress().ToString().c_str(), incoming.GetSourceAddress().ToString().c_str(),
235                static_cast<int>(properties_.GetSupportedFeatures()));
236       response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
237       response_data.push_back(properties_.GetSupportedFeatures());
238       break;
239     case (hci::OpCode::READ_REMOTE_EXTENDED_FEATURES): {
240       uint8_t page_number = (args + 2).extract<uint8_t>();  // skip the handle
241       LOG_INFO(LOG_TAG, "(%s) Remote Extended Features %d Requested by: %s",
242                incoming.GetDestinationAddress().ToString().c_str(), page_number,
243                incoming.GetSourceAddress().ToString().c_str());
244       uint8_t max_page_number = properties_.GetExtendedFeaturesMaximumPageNumber();
245       if (page_number > max_page_number) {
246         response_data.push_back(static_cast<uint8_t>(hci::Status::INVALID_HCI_COMMAND_PARAMETERS));
247         response_data.push_back(page_number);
248         response_data.push_back(max_page_number);
249         response_data.push_back(0);
250       } else {
251         response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
252         response_data.push_back(page_number);
253         response_data.push_back(max_page_number);
254         response_data.push_back(properties_.GetExtendedFeatures(page_number));
255       }
256     } break;
257     case (hci::OpCode::READ_REMOTE_VERSION_INFORMATION):
258       response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
259       response_data.push_back(properties_.GetLmpPalVersion());
260       response_data.push_back(properties_.GetManufacturerName());
261       response_data.push_back(properties_.GetLmpPalSubversion());
262       break;
263     case (hci::OpCode::READ_CLOCK_OFFSET):
264       response_data.push_back(static_cast<uint8_t>(hci::Status::SUCCESS));
265       response_data.push_back(properties_.GetClockOffset());
266       break;
267     default:
268       LOG_INFO(LOG_TAG, "Dropping unhandled command 0x%04x", static_cast<uint16_t>(opcode));
269       return;
270   }
271   SendLinkLayerPacket(
272       LinkLayerPacketBuilder::WrapResponse(ResponseBuilder::Create(static_cast<uint16_t>(opcode), response_data),
273                                            properties_.GetAddress(), incoming.GetSourceAddress()));
274 }
275 
IncomingDisconnectPacket(LinkLayerPacketView incoming)276 void LinkLayerController::IncomingDisconnectPacket(LinkLayerPacketView incoming) {
277   LOG_INFO(LOG_TAG, "Disconnect Packet");
278   DisconnectView disconnect = DisconnectView::GetDisconnect(incoming);
279   Address peer = incoming.GetSourceAddress();
280   uint16_t handle = classic_connections_.GetHandle(peer);
281   if (handle == acl::kReservedHandle) {
282     LOG_INFO(LOG_TAG, "%s: Unknown connection @%s", __func__, peer.ToString().c_str());
283     return;
284   }
285   CHECK(classic_connections_.Disconnect(handle)) << "GetHandle() returned invalid handle " << handle;
286 
287   uint8_t reason = disconnect.GetReason();
288   schedule_task_(milliseconds(20), [this, handle, reason]() { DisconnectCleanup(handle, reason); });
289 }
290 
IncomingEncryptConnection(LinkLayerPacketView incoming)291 void LinkLayerController::IncomingEncryptConnection(LinkLayerPacketView incoming) {
292   LOG_INFO(LOG_TAG, "%s", __func__);
293   // TODO: Check keys
294   Address peer = incoming.GetSourceAddress();
295   uint16_t handle = classic_connections_.GetHandle(peer);
296   if (handle == acl::kReservedHandle) {
297     LOG_INFO(LOG_TAG, "%s: Unknown connection @%s", __func__, peer.ToString().c_str());
298     return;
299   }
300   send_event_(EventPacketBuilder::CreateEncryptionChange(hci::Status::SUCCESS, handle, 1)->ToVector());
301   SendLinkLayerPacket(LinkLayerPacketBuilder::WrapEncryptConnectionResponse(
302       EncryptConnectionBuilder::Create(security_manager_.GetKey(peer)), properties_.GetAddress(), peer));
303 }
304 
IncomingEncryptConnectionResponse(LinkLayerPacketView incoming)305 void LinkLayerController::IncomingEncryptConnectionResponse(LinkLayerPacketView incoming) {
306   LOG_INFO(LOG_TAG, "%s", __func__);
307   // TODO: Check keys
308   uint16_t handle = classic_connections_.GetHandle(incoming.GetSourceAddress());
309   if (handle == acl::kReservedHandle) {
310     LOG_INFO(LOG_TAG, "%s: Unknown connection @%s", __func__, incoming.GetSourceAddress().ToString().c_str());
311     return;
312   }
313   send_event_(EventPacketBuilder::CreateEncryptionChange(hci::Status::SUCCESS, handle, 1)->ToVector());
314 }
315 
IncomingInquiryPacket(LinkLayerPacketView incoming)316 void LinkLayerController::IncomingInquiryPacket(LinkLayerPacketView incoming) {
317   InquiryView inquiry = InquiryView::GetInquiry(incoming);
318   std::unique_ptr<InquiryResponseBuilder> inquiry_response;
319   switch (inquiry.GetType()) {
320     case (Inquiry::InquiryType::STANDARD):
321       inquiry_response = InquiryResponseBuilder::CreateStandard(
322           properties_.GetPageScanRepetitionMode(), properties_.GetClassOfDevice(), properties_.GetClockOffset());
323       break;
324 
325     case (Inquiry::InquiryType::RSSI):
326       inquiry_response =
327           InquiryResponseBuilder::CreateRssi(properties_.GetPageScanRepetitionMode(), properties_.GetClassOfDevice(),
328                                              properties_.GetClockOffset(), GetRssi());
329       break;
330 
331     case (Inquiry::InquiryType::EXTENDED):
332       inquiry_response = InquiryResponseBuilder::CreateExtended(
333           properties_.GetPageScanRepetitionMode(), properties_.GetClassOfDevice(), properties_.GetClockOffset(),
334           GetRssi(), properties_.GetExtendedInquiryData());
335       break;
336     default:
337       LOG_WARN(LOG_TAG, "Unhandled Incoming Inquiry of type %d", static_cast<int>(inquiry.GetType()));
338       return;
339   }
340   SendLinkLayerPacket(LinkLayerPacketBuilder::WrapInquiryResponse(std::move(inquiry_response), properties_.GetAddress(),
341                                                                   incoming.GetSourceAddress()));
342   // TODO: Send an Inquriy Response Notification Event 7.7.74
343 }
344 
IncomingInquiryResponsePacket(LinkLayerPacketView incoming)345 void LinkLayerController::IncomingInquiryResponsePacket(LinkLayerPacketView incoming) {
346   InquiryResponseView inquiry_response = InquiryResponseView::GetInquiryResponse(incoming);
347   std::vector<uint8_t> eir;
348 
349   switch (inquiry_response.GetType()) {
350     case (Inquiry::InquiryType::STANDARD): {
351       LOG_WARN(LOG_TAG, "Incoming Standard Inquiry Response");
352       // TODO: Support multiple inquiries in the same packet.
353       std::unique_ptr<EventPacketBuilder> inquiry_result = EventPacketBuilder::CreateInquiryResultEvent();
354       bool result_added =
355           inquiry_result->AddInquiryResult(incoming.GetSourceAddress(), inquiry_response.GetPageScanRepetitionMode(),
356                                            inquiry_response.GetClassOfDevice(), inquiry_response.GetClockOffset());
357       CHECK(result_added);
358       send_event_(inquiry_result->ToVector());
359     } break;
360 
361     case (Inquiry::InquiryType::RSSI):
362       LOG_WARN(LOG_TAG, "Incoming RSSI Inquiry Response");
363       send_event_(EventPacketBuilder::CreateExtendedInquiryResultEvent(
364                       incoming.GetSourceAddress(), inquiry_response.GetPageScanRepetitionMode(),
365                       inquiry_response.GetClassOfDevice(), inquiry_response.GetClockOffset(), GetRssi(), eir)
366                       ->ToVector());
367       break;
368 
369     case (Inquiry::InquiryType::EXTENDED): {
370       LOG_WARN(LOG_TAG, "Incoming Extended Inquiry Response");
371       auto eir_itr = inquiry_response.GetExtendedData();
372       size_t eir_bytes = eir_itr.NumBytesRemaining();
373       LOG_WARN(LOG_TAG, "Payload size = %d", static_cast<int>(eir_bytes));
374       for (size_t i = 0; i < eir_bytes; i++) {
375         eir.push_back(eir_itr.extract<uint8_t>());
376       }
377       send_event_(EventPacketBuilder::CreateExtendedInquiryResultEvent(
378                       incoming.GetSourceAddress(), inquiry_response.GetPageScanRepetitionMode(),
379                       inquiry_response.GetClassOfDevice(), inquiry_response.GetClockOffset(), GetRssi(), eir)
380                       ->ToVector());
381     } break;
382     default:
383       LOG_WARN(LOG_TAG, "Unhandled Incoming Inquiry Response of type %d", static_cast<int>(inquiry_response.GetType()));
384   }
385 }
386 
IncomingIoCapabilityRequestPacket(LinkLayerPacketView incoming)387 void LinkLayerController::IncomingIoCapabilityRequestPacket(LinkLayerPacketView incoming) {
388   LOG_DEBUG(LOG_TAG, "%s", __func__);
389   if (!simple_pairing_mode_enabled_) {
390     LOG_WARN(LOG_TAG, "%s: Only simple pairing mode is implemented", __func__);
391     return;
392   }
393   auto request = IoCapabilityView::GetIoCapability(incoming);
394   Address peer = incoming.GetSourceAddress();
395 
396   uint8_t io_capability = request.GetIoCapability();
397   uint8_t oob_data_present = request.GetOobDataPresent();
398   uint8_t authentication_requirements = request.GetAuthenticationRequirements();
399 
400   uint16_t handle = classic_connections_.GetHandle(peer);
401   if (handle == acl::kReservedHandle) {
402     LOG_INFO(LOG_TAG, "%s: Device not connected %s", __func__, peer.ToString().c_str());
403     return;
404   }
405 
406   security_manager_.AuthenticationRequest(peer, handle);
407 
408   security_manager_.SetPeerIoCapability(peer, io_capability, oob_data_present, authentication_requirements);
409 
410   send_event_(EventPacketBuilder::CreateIoCapabilityResponseEvent(peer, io_capability, oob_data_present,
411                                                                   authentication_requirements)
412                   ->ToVector());
413 
414   StartSimplePairing(peer);
415 }
416 
IncomingIoCapabilityResponsePacket(LinkLayerPacketView incoming)417 void LinkLayerController::IncomingIoCapabilityResponsePacket(LinkLayerPacketView incoming) {
418   LOG_DEBUG(LOG_TAG, "%s", __func__);
419   auto response = IoCapabilityView::GetIoCapability(incoming);
420   Address peer = incoming.GetSourceAddress();
421   uint8_t io_capability = response.GetIoCapability();
422   uint8_t oob_data_present = response.GetOobDataPresent();
423   uint8_t authentication_requirements = response.GetAuthenticationRequirements();
424 
425   security_manager_.SetPeerIoCapability(peer, io_capability, oob_data_present, authentication_requirements);
426 
427   send_event_(EventPacketBuilder::CreateIoCapabilityResponseEvent(peer, io_capability, oob_data_present,
428                                                                   authentication_requirements)
429                   ->ToVector());
430 
431   PairingType pairing_type = security_manager_.GetSimplePairingType();
432   if (pairing_type != PairingType::INVALID) {
433     schedule_task_(milliseconds(5), [this, peer, pairing_type]() { AuthenticateRemoteStage1(peer, pairing_type); });
434   } else {
435     LOG_INFO(LOG_TAG, "%s: Security Manager returned INVALID", __func__);
436   }
437 }
438 
IncomingIoCapabilityNegativeResponsePacket(LinkLayerPacketView incoming)439 void LinkLayerController::IncomingIoCapabilityNegativeResponsePacket(LinkLayerPacketView incoming) {
440   LOG_DEBUG(LOG_TAG, "%s", __func__);
441   Address peer = incoming.GetSourceAddress();
442 
443   CHECK(security_manager_.GetAuthenticationAddress() == peer);
444 
445   security_manager_.InvalidateIoCapabilities();
446 }
447 
IncomingLeAdvertisementPacket(LinkLayerPacketView incoming)448 void LinkLayerController::IncomingLeAdvertisementPacket(LinkLayerPacketView incoming) {
449   // TODO: Handle multiple advertisements per packet.
450 
451   LeAdvertisementView advertisement = LeAdvertisementView::GetLeAdvertisementView(incoming);
452   LeAdvertisement::AdvertisementType adv_type = advertisement.GetAdvertisementType();
453   LeAdvertisement::AddressType addr_type = advertisement.GetAddressType();
454 
455   if (le_scan_enable_) {
456     vector<uint8_t> ad;
457     auto itr = advertisement.GetData();
458     size_t ad_size = itr.NumBytesRemaining();
459     for (size_t i = 0; i < ad_size; i++) {
460       ad.push_back(itr.extract<uint8_t>());
461     }
462     std::unique_ptr<EventPacketBuilder> le_adverts = EventPacketBuilder::CreateLeAdvertisingReportEvent();
463 
464     if (!le_adverts->AddLeAdvertisingReport(adv_type, addr_type, incoming.GetSourceAddress(), ad, GetRssi())) {
465       LOG_INFO(LOG_TAG, "Couldn't add the advertising report.");
466     } else {
467       send_event_(le_adverts->ToVector());
468     }
469   }
470 
471 #if 0
472       // Connect
473       if (le_connect_ && (adv_type == BTM_BLE_CONNECT_EVT ||
474                           adv_type == BTM_BLE_CONNECT_DIR_EVT)) {
475         LOG_INFO(LOG_TAG, "Connecting to device %d", static_cast<int>(dev));
476         if (le_peer_address_ == addr && le_peer_address_type_ == addr_type &&
477             remote_devices_[dev]->LeConnect()) {
478           uint16_t handle = LeGetHandle();
479           send_event_(EventPacketBuilder::CreateLeConnectionCompleteEvent(
480               hci::Status::SUCCESS, handle, HCI_ROLE_MASTER, addr_type, addr, 1,
481               2, 3)->ToVector());
482 
483           // TODO: LeGetConnInterval(), LeGetConnLatency(),
484           // LeGetSupervisionTimeout()));
485           le_connect_ = false;
486 
487           std::shared_ptr<Connection> new_connection =
488               std::make_shared<Connection>(remote_devices_[dev], handle);
489           /*
490           connections_.push_back(new_connection);
491 
492           remote_devices_[dev]->SetConnection(new_connection);
493           */
494         }
495 
496         if (LeWhiteListContainsDevice(addr, addr_type) &&
497             remote_devices_[dev]->LeConnect()) {
498           LOG_INFO(LOG_TAG, "White List Connecting to device %d",
499                    static_cast<int>(dev));
500           uint16_t handle = LeGetHandle();
501           send_event_(EventPacketBuilder::CreateLeConnectionCompleteEvent(
502               hci::Status::SUCCESS, handle, HCI_ROLE_MASTER, addr_type, addr, 1,
503               2, 3)->ToVector());
504           // TODO: LeGetConnInterval(), LeGetConnLatency(),
505           // LeGetSupervisionTimeout()));
506           le_connect_ = false;
507 
508           std::shared_ptr<Connection> new_connection =
509               std::make_shared<Connection>(remote_devices_[dev], handle);
510           /*
511           connections_.push_back(new_connection);
512           remote_devices_[dev]->SetConnection(new_connection);
513           */
514         }
515       }
516 #endif
517 
518   // Active scanning
519   if (le_scan_enable_ && le_scan_type_ == 1) {
520     std::shared_ptr<LinkLayerPacketBuilder> to_send =
521         LinkLayerPacketBuilder::WrapLeScan(properties_.GetLeAddress(), incoming.GetSourceAddress());
522     SendLELinkLayerPacket(to_send);
523   }
524 }
525 
IncomingLeScanPacket(LinkLayerPacketView incoming)526 void LinkLayerController::IncomingLeScanPacket(LinkLayerPacketView incoming) {
527   LOG_INFO(LOG_TAG, "LE Scan Packet");
528   std::unique_ptr<LeAdvertisementBuilder> response = LeAdvertisementBuilder::Create(
529       static_cast<LeAdvertisement::AddressType>(properties_.GetLeAddressType()),
530       static_cast<LeAdvertisement::AdvertisementType>(properties_.GetLeAdvertisementType()),
531       properties_.GetLeScanResponse());
532   std::shared_ptr<LinkLayerPacketBuilder> to_send = LinkLayerPacketBuilder::WrapLeScanResponse(
533       std::move(response), properties_.GetLeAddress(), incoming.GetSourceAddress());
534   SendLELinkLayerPacket(to_send);
535 }
536 
IncomingLeScanResponsePacket(LinkLayerPacketView incoming)537 void LinkLayerController::IncomingLeScanResponsePacket(LinkLayerPacketView incoming) {
538   LeAdvertisementView scan_response = LeAdvertisementView::GetLeAdvertisementView(incoming);
539   vector<uint8_t> ad;
540   auto itr = scan_response.GetData();
541   size_t scan_size = itr.NumBytesRemaining();
542   for (size_t i = 0; i < scan_size; i++) {
543     ad.push_back(itr.extract<uint8_t>());
544   }
545 
546   std::unique_ptr<EventPacketBuilder> le_adverts = EventPacketBuilder::CreateLeAdvertisingReportEvent();
547 
548   if (!le_adverts->AddLeAdvertisingReport(scan_response.GetAdvertisementType(), scan_response.GetAddressType(),
549                                           incoming.GetSourceAddress(), ad, GetRssi())) {
550     LOG_INFO(LOG_TAG, "Couldn't add the scan response.");
551   } else {
552     LOG_INFO(LOG_TAG, "Sending scan response");
553     send_event_(le_adverts->ToVector());
554   }
555 }
556 
IncomingPagePacket(LinkLayerPacketView incoming)557 void LinkLayerController::IncomingPagePacket(LinkLayerPacketView incoming) {
558   PageView page = PageView::GetPage(incoming);
559   LOG_INFO(LOG_TAG, "%s from %s", __func__, incoming.GetSourceAddress().ToString().c_str());
560 
561   if (!classic_connections_.CreatePendingConnection(incoming.GetSourceAddress())) {
562     // Send a response to indicate that we're busy, or drop the packet?
563     LOG_WARN(LOG_TAG, "%s: Failed to create a pending connection", __func__);
564   }
565 
566   send_event_(EventPacketBuilder::CreateConnectionRequestEvent(incoming.GetSourceAddress(), page.GetClassOfDevice(),
567                                                                hci::LinkType::ACL)
568                   ->ToVector());
569 }
570 
IncomingPageResponsePacket(LinkLayerPacketView incoming)571 void LinkLayerController::IncomingPageResponsePacket(LinkLayerPacketView incoming) {
572   LOG_INFO(LOG_TAG, "%s: %s", __func__, incoming.GetSourceAddress().ToString().c_str());
573   uint16_t handle = classic_connections_.CreateConnection(incoming.GetSourceAddress());
574   if (handle == acl::kReservedHandle) {
575     LOG_WARN(LOG_TAG, "%s: No free handles", __func__);
576     return;
577   }
578   LOG_INFO(LOG_TAG, "%s: Sending CreateConnectionComplete", __func__);
579   send_event_(EventPacketBuilder::CreateConnectionCompleteEvent(hci::Status::SUCCESS, handle,
580                                                                 incoming.GetSourceAddress(), hci::LinkType::ACL, false)
581                   ->ToVector());
582 }
583 
IncomingResponsePacket(LinkLayerPacketView incoming)584 void LinkLayerController::IncomingResponsePacket(LinkLayerPacketView incoming) {
585   ResponseView response = ResponseView::GetResponse(incoming);
586 
587   // TODO: Check to see if I'm expecting this response.
588 
589   hci::OpCode opcode = static_cast<hci::OpCode>(response.GetOpcode());
590   auto args = response.GetResponseData();
591   hci::Status status = static_cast<hci::Status>(args.extract<uint64_t>());
592 
593   uint16_t handle = classic_connections_.GetHandle(incoming.GetSourceAddress());
594 
595   switch (opcode) {
596     case (hci::OpCode::REMOTE_NAME_REQUEST): {
597       std::string remote_name = "";
598       size_t length = args.extract<uint64_t>();
599       uint64_t word = 0;
600       for (size_t b = 0; b < length; b++) {
601         size_t byte = b % 8;
602         if (byte == 0) {
603           word = args.extract<uint64_t>();
604         }
605         remote_name += static_cast<uint8_t>(word >> (byte * 8));
606       }
607       send_event_(
608           EventPacketBuilder::CreateRemoteNameRequestCompleteEvent(status, incoming.GetSourceAddress(), remote_name)
609               ->ToVector());
610     } break;
611     case (hci::OpCode::READ_REMOTE_SUPPORTED_FEATURES): {
612       send_event_(
613           EventPacketBuilder::CreateRemoteSupportedFeaturesEvent(status, handle, args.extract<uint64_t>())->ToVector());
614     } break;
615     case (hci::OpCode::READ_REMOTE_EXTENDED_FEATURES): {
616       if (status == hci::Status::SUCCESS) {
617         send_event_(EventPacketBuilder::CreateReadRemoteExtendedFeaturesEvent(
618                         status, handle, args.extract<uint64_t>(), args.extract<uint64_t>(), args.extract<uint64_t>())
619                         ->ToVector());
620       } else {
621         send_event_(EventPacketBuilder::CreateReadRemoteExtendedFeaturesEvent(status, handle, 0, 0, 0)->ToVector());
622       }
623     } break;
624     case (hci::OpCode::READ_REMOTE_VERSION_INFORMATION): {
625       send_event_(EventPacketBuilder::CreateReadRemoteVersionInformationEvent(
626                       status, handle, args.extract<uint64_t>(), args.extract<uint64_t>(), args.extract<uint64_t>())
627                       ->ToVector());
628       LOG_INFO(LOG_TAG, "Read remote version handle 0x%04x", handle);
629     } break;
630     case (hci::OpCode::READ_CLOCK_OFFSET): {
631       send_event_(EventPacketBuilder::CreateReadClockOffsetEvent(status, handle, args.extract<uint64_t>())->ToVector());
632     } break;
633     default:
634       LOG_INFO(LOG_TAG, "Unhandled response to command 0x%04x", static_cast<uint16_t>(opcode));
635   }
636 }
637 
TimerTick()638 void LinkLayerController::TimerTick() {
639   if (inquiry_state_ == Inquiry::InquiryState::INQUIRY) Inquiry();
640   if (inquiry_state_ == Inquiry::InquiryState::INQUIRY) PageScan();
641   Connections();
642 }
643 
Connections()644 void LinkLayerController::Connections() {
645   // TODO: Keep connections alive?
646 }
647 
RegisterEventChannel(const std::function<void (std::shared_ptr<std::vector<uint8_t>>)> & callback)648 void LinkLayerController::RegisterEventChannel(
649     const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& callback) {
650   send_event_ = callback;
651 }
652 
RegisterAclChannel(const std::function<void (std::shared_ptr<std::vector<uint8_t>>)> & callback)653 void LinkLayerController::RegisterAclChannel(
654     const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& callback) {
655   send_acl_ = callback;
656 }
657 
RegisterScoChannel(const std::function<void (std::shared_ptr<std::vector<uint8_t>>)> & callback)658 void LinkLayerController::RegisterScoChannel(
659     const std::function<void(std::shared_ptr<std::vector<uint8_t>>)>& callback) {
660   send_sco_ = callback;
661 }
662 
RegisterRemoteChannel(const std::function<void (std::shared_ptr<LinkLayerPacketBuilder>,Phy::Type)> & callback)663 void LinkLayerController::RegisterRemoteChannel(
664     const std::function<void(std::shared_ptr<LinkLayerPacketBuilder>, Phy::Type)>& callback) {
665   send_to_remote_ = callback;
666 }
667 
RegisterTaskScheduler(std::function<AsyncTaskId (milliseconds,const TaskCallback &)> event_scheduler)668 void LinkLayerController::RegisterTaskScheduler(
669     std::function<AsyncTaskId(milliseconds, const TaskCallback&)> event_scheduler) {
670   schedule_task_ = event_scheduler;
671 }
672 
RegisterPeriodicTaskScheduler(std::function<AsyncTaskId (milliseconds,milliseconds,const TaskCallback &)> periodic_event_scheduler)673 void LinkLayerController::RegisterPeriodicTaskScheduler(
674     std::function<AsyncTaskId(milliseconds, milliseconds, const TaskCallback&)> periodic_event_scheduler) {
675   schedule_periodic_task_ = periodic_event_scheduler;
676 }
677 
RegisterTaskCancel(std::function<void (AsyncTaskId)> task_cancel)678 void LinkLayerController::RegisterTaskCancel(std::function<void(AsyncTaskId)> task_cancel) {
679   cancel_task_ = task_cancel;
680 }
681 
AddControllerEvent(milliseconds delay,const TaskCallback & task)682 void LinkLayerController::AddControllerEvent(milliseconds delay, const TaskCallback& task) {
683   controller_events_.push_back(schedule_task_(delay, task));
684 }
685 
WriteSimplePairingMode(bool enabled)686 void LinkLayerController::WriteSimplePairingMode(bool enabled) {
687   CHECK(enabled) << "The spec says don't disable this!";
688   simple_pairing_mode_enabled_ = enabled;
689 }
690 
StartSimplePairing(const Address & address)691 void LinkLayerController::StartSimplePairing(const Address& address) {
692   // IO Capability Exchange (See the Diagram in the Spec)
693   send_event_(EventPacketBuilder::CreateIoCapabilityRequestEvent(address)->ToVector());
694 
695   // Get a Key, then authenticate
696   // PublicKeyExchange(address);
697   // AuthenticateRemoteStage1(address);
698   // AuthenticateRemoteStage2(address);
699 }
700 
AuthenticateRemoteStage1(const Address & peer,PairingType pairing_type)701 void LinkLayerController::AuthenticateRemoteStage1(const Address& peer, PairingType pairing_type) {
702   CHECK(security_manager_.GetAuthenticationAddress() == peer);
703   // TODO: Public key exchange first?
704   switch (pairing_type) {
705     case PairingType::AUTO_CONFIRMATION:
706       send_event_(EventPacketBuilder::CreateUserConfirmationRequestEvent(peer, 123456)->ToVector());
707       break;
708     case PairingType::CONFIRM_Y_N:
709       CHECK(false) << __func__ << "Unimplemented PairingType" << static_cast<int>(pairing_type);
710       break;
711     case PairingType::DISPLAY_PIN:
712       CHECK(false) << __func__ << "Unimplemented PairingType" << static_cast<int>(pairing_type);
713       break;
714     case PairingType::DISPLAY_AND_CONFIRM:
715       CHECK(false) << __func__ << "Unimplemented PairingType" << static_cast<int>(pairing_type);
716       break;
717     case PairingType::INPUT_PIN:
718       CHECK(false) << __func__ << "Unimplemented PairingType" << static_cast<int>(pairing_type);
719       break;
720     case PairingType::INVALID:
721       CHECK(false) << __func__ << "Unimplemented PairingType" << static_cast<int>(pairing_type);
722       break;
723     default:
724       CHECK(false) << __func__ << ": Invalid PairingType " << static_cast<int>(pairing_type);
725   }
726 }
727 
AuthenticateRemoteStage2(const Address & peer)728 void LinkLayerController::AuthenticateRemoteStage2(const Address& peer) {
729   uint16_t handle = security_manager_.GetAuthenticationHandle();
730   CHECK(security_manager_.GetAuthenticationAddress() == peer);
731   // Check key in security_manager_ ?
732   send_event_(EventPacketBuilder::CreateAuthenticationCompleteEvent(hci::Status::SUCCESS, handle)->ToVector());
733 }
734 
LinkKeyRequestReply(const Address & peer,PacketView<true> key)735 hci::Status LinkLayerController::LinkKeyRequestReply(const Address& peer, PacketView<true> key) {
736   std::vector<uint8_t> key_vec(key.begin(), key.end());
737   security_manager_.WriteKey(peer, key_vec);
738   security_manager_.AuthenticationRequestFinished();
739 
740   schedule_task_(milliseconds(5), [this, peer]() { AuthenticateRemoteStage2(peer); });
741 
742   return hci::Status::SUCCESS;
743 }
744 
LinkKeyRequestNegativeReply(const Address & address)745 hci::Status LinkLayerController::LinkKeyRequestNegativeReply(const Address& address) {
746   security_manager_.DeleteKey(address);
747   // Simple pairing to get a key
748   uint16_t handle = classic_connections_.GetHandle(address);
749   if (handle == acl::kReservedHandle) {
750     LOG_INFO(LOG_TAG, "%s: Device not connected %s", __func__, address.ToString().c_str());
751     return hci::Status::UNKNOWN_CONNECTION;
752   }
753 
754   security_manager_.AuthenticationRequest(address, handle);
755 
756   schedule_task_(milliseconds(5), [this, address]() { StartSimplePairing(address); });
757   return hci::Status::SUCCESS;
758 }
759 
IoCapabilityRequestReply(const Address & peer,uint8_t io_capability,uint8_t oob_data_present_flag,uint8_t authentication_requirements)760 hci::Status LinkLayerController::IoCapabilityRequestReply(const Address& peer, uint8_t io_capability,
761                                                           uint8_t oob_data_present_flag,
762                                                           uint8_t authentication_requirements) {
763   security_manager_.SetLocalIoCapability(peer, io_capability, oob_data_present_flag, authentication_requirements);
764 
765   PairingType pairing_type = security_manager_.GetSimplePairingType();
766   if (pairing_type != PairingType::INVALID) {
767     schedule_task_(milliseconds(5), [this, peer, pairing_type]() { AuthenticateRemoteStage1(peer, pairing_type); });
768     SendLinkLayerPacket(LinkLayerPacketBuilder::WrapIoCapabilityResponse(
769         IoCapabilityBuilder::Create(io_capability, oob_data_present_flag, authentication_requirements),
770         properties_.GetAddress(), peer));
771   } else {
772     LOG_INFO(LOG_TAG, "%s: Requesting remote capability", __func__);
773     SendLinkLayerPacket(LinkLayerPacketBuilder::WrapIoCapabilityRequest(
774         IoCapabilityBuilder::Create(io_capability, oob_data_present_flag, authentication_requirements),
775         properties_.GetAddress(), peer));
776   }
777 
778   return hci::Status::SUCCESS;
779 }
780 
IoCapabilityRequestNegativeReply(const Address & peer,hci::Status reason)781 hci::Status LinkLayerController::IoCapabilityRequestNegativeReply(const Address& peer, hci::Status reason) {
782   if (security_manager_.GetAuthenticationAddress() != peer) {
783     return hci::Status::AUTHENTICATION_FAILURE;
784   }
785 
786   security_manager_.InvalidateIoCapabilities();
787 
788   SendLinkLayerPacket(LinkLayerPacketBuilder::WrapIoCapabilityNegativeResponse(
789       IoCapabilityNegativeResponseBuilder::Create(static_cast<uint8_t>(reason)), properties_.GetAddress(), peer));
790 
791   return hci::Status::SUCCESS;
792 }
793 
UserConfirmationRequestReply(const Address & peer)794 hci::Status LinkLayerController::UserConfirmationRequestReply(const Address& peer) {
795   if (security_manager_.GetAuthenticationAddress() != peer) {
796     return hci::Status::AUTHENTICATION_FAILURE;
797   }
798   // TODO: Key could be calculated here.
799   std::vector<uint8_t> key_vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
800   security_manager_.WriteKey(peer, key_vec);
801 
802   security_manager_.AuthenticationRequestFinished();
803 
804   schedule_task_(milliseconds(5), [this, peer]() { AuthenticateRemoteStage2(peer); });
805   return hci::Status::SUCCESS;
806 }
807 
UserConfirmationRequestNegativeReply(const Address & peer)808 hci::Status LinkLayerController::UserConfirmationRequestNegativeReply(const Address& peer) {
809   if (security_manager_.GetAuthenticationAddress() != peer) {
810     return hci::Status::AUTHENTICATION_FAILURE;
811   }
812   return hci::Status::SUCCESS;
813 }
814 
UserPasskeyRequestReply(const Address & peer,uint32_t numeric_value)815 hci::Status LinkLayerController::UserPasskeyRequestReply(const Address& peer, uint32_t numeric_value) {
816   if (security_manager_.GetAuthenticationAddress() != peer) {
817     return hci::Status::AUTHENTICATION_FAILURE;
818   }
819   LOG_INFO(LOG_TAG, "TODO:Do something with the passkey %06d", numeric_value);
820   return hci::Status::SUCCESS;
821 }
822 
UserPasskeyRequestNegativeReply(const Address & peer)823 hci::Status LinkLayerController::UserPasskeyRequestNegativeReply(const Address& peer) {
824   if (security_manager_.GetAuthenticationAddress() != peer) {
825     return hci::Status::AUTHENTICATION_FAILURE;
826   }
827   return hci::Status::SUCCESS;
828 }
829 
RemoteOobDataRequestReply(const Address & peer,const std::vector<uint8_t> & c,const std::vector<uint8_t> & r)830 hci::Status LinkLayerController::RemoteOobDataRequestReply(const Address& peer, const std::vector<uint8_t>& c,
831                                                            const std::vector<uint8_t>& r) {
832   if (security_manager_.GetAuthenticationAddress() != peer) {
833     return hci::Status::AUTHENTICATION_FAILURE;
834   }
835   LOG_INFO(LOG_TAG, "TODO:Do something with the OOB data c=%d r=%d", c[0], r[0]);
836   return hci::Status::SUCCESS;
837 }
838 
RemoteOobDataRequestNegativeReply(const Address & peer)839 hci::Status LinkLayerController::RemoteOobDataRequestNegativeReply(const Address& peer) {
840   if (security_manager_.GetAuthenticationAddress() != peer) {
841     return hci::Status::AUTHENTICATION_FAILURE;
842   }
843   return hci::Status::SUCCESS;
844 }
845 
HandleAuthenticationRequest(const Address & address,uint16_t handle)846 void LinkLayerController::HandleAuthenticationRequest(const Address& address, uint16_t handle) {
847   if (simple_pairing_mode_enabled_ == true) {
848     security_manager_.AuthenticationRequest(address, handle);
849     send_event_(EventPacketBuilder::CreateLinkKeyRequestEvent(address)->ToVector());
850   } else {  // Should never happen for our phones
851     // Check for a key, try to authenticate, ask for a PIN.
852     send_event_(
853         EventPacketBuilder::CreateAuthenticationCompleteEvent(hci::Status::AUTHENTICATION_FAILURE, handle)->ToVector());
854   }
855 }
856 
AuthenticationRequested(uint16_t handle)857 hci::Status LinkLayerController::AuthenticationRequested(uint16_t handle) {
858   if (!classic_connections_.HasHandle(handle)) {
859     LOG_INFO(LOG_TAG, "Authentication Requested for unknown handle %04x", handle);
860     return hci::Status::UNKNOWN_CONNECTION;
861   }
862 
863   Address remote = classic_connections_.GetAddress(handle);
864 
865   schedule_task_(milliseconds(5), [this, remote, handle]() { HandleAuthenticationRequest(remote, handle); });
866 
867   return hci::Status::SUCCESS;
868 }
869 
HandleSetConnectionEncryption(const Address & peer,uint16_t handle,uint8_t encryption_enable)870 void LinkLayerController::HandleSetConnectionEncryption(const Address& peer, uint16_t handle,
871                                                         uint8_t encryption_enable) {
872   // TODO: Block ACL traffic or at least guard against it
873 
874   if (classic_connections_.IsEncrypted(handle) && encryption_enable) {
875     send_event_(
876         EventPacketBuilder::CreateEncryptionChange(hci::Status::SUCCESS, handle, encryption_enable)->ToVector());
877     return;
878   }
879 
880   SendLinkLayerPacket(LinkLayerPacketBuilder::WrapEncryptConnection(
881       EncryptConnectionBuilder::Create(security_manager_.GetKey(peer)), properties_.GetAddress(), peer));
882 }
883 
SetConnectionEncryption(uint16_t handle,uint8_t encryption_enable)884 hci::Status LinkLayerController::SetConnectionEncryption(uint16_t handle, uint8_t encryption_enable) {
885   if (!classic_connections_.HasHandle(handle)) {
886     LOG_INFO(LOG_TAG, "Authentication Requested for unknown handle %04x", handle);
887     return hci::Status::UNKNOWN_CONNECTION;
888   }
889 
890   if (classic_connections_.IsEncrypted(handle) && !encryption_enable) {
891     return hci::Status::ENCRYPTION_MODE_NOT_ACCEPTABLE;
892   }
893   Address remote = classic_connections_.GetAddress(handle);
894 
895   schedule_task_(milliseconds(5), [this, remote, handle, encryption_enable]() {
896     HandleSetConnectionEncryption(remote, handle, encryption_enable);
897   });
898 
899   return hci::Status::SUCCESS;
900 }
901 
AcceptConnectionRequest(const Address & addr,bool try_role_switch)902 hci::Status LinkLayerController::AcceptConnectionRequest(const Address& addr, bool try_role_switch) {
903   if (!classic_connections_.HasPendingConnection(addr)) {
904     LOG_INFO(LOG_TAG, "%s: No pending connection", __func__);
905     return hci::Status::UNKNOWN_CONNECTION;
906   }
907 
908   LOG_INFO(LOG_TAG, "%s: Accept in 200ms", __func__);
909   schedule_task_(milliseconds(200), [this, addr, try_role_switch]() {
910     LOG_INFO(LOG_TAG, "%s: Accepted", __func__);
911     MakeSlaveConnection(addr, try_role_switch);
912   });
913 
914   return hci::Status::SUCCESS;
915 }
916 
MakeSlaveConnection(const Address & addr,bool try_role_switch)917 void LinkLayerController::MakeSlaveConnection(const Address& addr, bool try_role_switch) {
918   std::shared_ptr<LinkLayerPacketBuilder> to_send = LinkLayerPacketBuilder::WrapPageResponse(
919       PageResponseBuilder::Create(try_role_switch), properties_.GetAddress(), addr);
920   LOG_INFO(LOG_TAG, "%s sending page response to %s", __func__, addr.ToString().c_str());
921   SendLinkLayerPacket(to_send);
922 
923   uint16_t handle = classic_connections_.CreateConnection(addr);
924   if (handle == acl::kReservedHandle) {
925     LOG_INFO(LOG_TAG, "%s CreateConnection failed", __func__);
926     return;
927   }
928   LOG_INFO(LOG_TAG, "%s CreateConnection returned handle 0x%x", __func__, handle);
929   send_event_(
930       EventPacketBuilder::CreateConnectionCompleteEvent(hci::Status::SUCCESS, handle, addr, hci::LinkType::ACL, false)
931           ->ToVector());
932 }
933 
RejectConnectionRequest(const Address & addr,uint8_t reason)934 hci::Status LinkLayerController::RejectConnectionRequest(const Address& addr, uint8_t reason) {
935   if (!classic_connections_.HasPendingConnection(addr)) {
936     LOG_INFO(LOG_TAG, "%s: No pending connection", __func__);
937     return hci::Status::UNKNOWN_CONNECTION;
938   }
939 
940   LOG_INFO(LOG_TAG, "%s: Reject in 200ms", __func__);
941   schedule_task_(milliseconds(200), [this, addr, reason]() {
942     LOG_INFO(LOG_TAG, "%s: Reject", __func__);
943     RejectSlaveConnection(addr, reason);
944   });
945 
946   return hci::Status::SUCCESS;
947 }
948 
RejectSlaveConnection(const Address & addr,uint8_t reason)949 void LinkLayerController::RejectSlaveConnection(const Address& addr, uint8_t reason) {
950   CHECK(reason > 0x0f || reason < 0x0d);
951   send_event_(EventPacketBuilder::CreateConnectionCompleteEvent(static_cast<hci::Status>(reason), 0xeff, addr,
952                                                                 hci::LinkType::ACL, false)
953                   ->ToVector());
954 }
955 
CreateConnection(const Address & addr,uint16_t,uint8_t,uint16_t,uint8_t allow_role_switch)956 hci::Status LinkLayerController::CreateConnection(const Address& addr, uint16_t, uint8_t, uint16_t,
957                                                   uint8_t allow_role_switch) {
958   if (!classic_connections_.CreatePendingConnection(addr)) {
959     return hci::Status::CONTROLLER_BUSY;
960   }
961 
962   std::unique_ptr<PageBuilder> page = PageBuilder::Create(properties_.GetClassOfDevice(), allow_role_switch);
963   SendLinkLayerPacket(LinkLayerPacketBuilder::WrapPage(std::move(page), properties_.GetAddress(), addr));
964 
965   return hci::Status::SUCCESS;
966 }
967 
CreateConnectionCancel(const Address & addr)968 hci::Status LinkLayerController::CreateConnectionCancel(const Address& addr) {
969   if (!classic_connections_.CancelPendingConnection(addr)) {
970     return hci::Status::UNKNOWN_CONNECTION;
971   }
972   return hci::Status::SUCCESS;
973 }
974 
Disconnect(uint16_t handle,uint8_t reason)975 hci::Status LinkLayerController::Disconnect(uint16_t handle, uint8_t reason) {
976   // TODO: Handle LE
977   if (!classic_connections_.HasHandle(handle)) {
978     return hci::Status::UNKNOWN_CONNECTION;
979   }
980 
981   const Address& remote = classic_connections_.GetAddress(handle);
982   std::shared_ptr<LinkLayerPacketBuilder> to_send =
983       LinkLayerPacketBuilder::WrapDisconnect(DisconnectBuilder::Create(reason), properties_.GetAddress(), remote);
984   SendLinkLayerPacket(to_send);
985   CHECK(classic_connections_.Disconnect(handle)) << "Disconnecting " << handle;
986 
987   schedule_task_(milliseconds(20), [this, handle]() {
988     DisconnectCleanup(handle, static_cast<uint8_t>(hci::Status::CONNECTION_TERMINATED_BY_LOCAL_HOST));
989   });
990 
991   return hci::Status::SUCCESS;
992 }
993 
DisconnectCleanup(uint16_t handle,uint8_t reason)994 void LinkLayerController::DisconnectCleanup(uint16_t handle, uint8_t reason) {
995   // TODO: Clean up other connection state.
996   send_event_(EventPacketBuilder::CreateDisconnectionCompleteEvent(hci::Status::SUCCESS, handle, reason)->ToVector());
997 }
998 
ChangeConnectionPacketType(uint16_t handle,uint16_t types)999 hci::Status LinkLayerController::ChangeConnectionPacketType(uint16_t handle, uint16_t types) {
1000   if (!classic_connections_.HasHandle(handle)) {
1001     return hci::Status::UNKNOWN_CONNECTION;
1002   }
1003   std::unique_ptr<EventPacketBuilder> packet =
1004       EventPacketBuilder::CreateConnectionPacketTypeChangedEvent(hci::Status::SUCCESS, handle, types);
1005   std::shared_ptr<std::vector<uint8_t>> raw_packet = packet->ToVector();
1006   if (schedule_task_) {
1007     schedule_task_(milliseconds(20), [this, raw_packet]() { send_event_(raw_packet); });
1008   } else {
1009     send_event_(raw_packet);
1010   }
1011 
1012   return hci::Status::SUCCESS;
1013 }
1014 
WriteLinkPolicySettings(uint16_t handle,uint16_t)1015 hci::Status LinkLayerController::WriteLinkPolicySettings(uint16_t handle, uint16_t) {
1016   if (!classic_connections_.HasHandle(handle)) {
1017     return hci::Status::UNKNOWN_CONNECTION;
1018   }
1019   return hci::Status::SUCCESS;
1020 }
1021 
WriteLinkSupervisionTimeout(uint16_t handle,uint16_t)1022 hci::Status LinkLayerController::WriteLinkSupervisionTimeout(uint16_t handle, uint16_t) {
1023   if (!classic_connections_.HasHandle(handle)) {
1024     return hci::Status::UNKNOWN_CONNECTION;
1025   }
1026   return hci::Status::SUCCESS;
1027 }
1028 
LeWhiteListClear()1029 void LinkLayerController::LeWhiteListClear() {
1030   le_white_list_.clear();
1031 }
1032 
LeWhiteListAddDevice(Address addr,uint8_t addr_type)1033 void LinkLayerController::LeWhiteListAddDevice(Address addr, uint8_t addr_type) {
1034   std::tuple<Address, uint8_t> new_tuple = std::make_tuple(addr, addr_type);
1035   for (auto dev : le_white_list_) {
1036     if (dev == new_tuple) {
1037       return;
1038     }
1039   }
1040   le_white_list_.emplace_back(new_tuple);
1041 }
1042 
LeWhiteListRemoveDevice(Address addr,uint8_t addr_type)1043 void LinkLayerController::LeWhiteListRemoveDevice(Address addr, uint8_t addr_type) {
1044   // TODO: Add checks to see if advertising, scanning, or a connection request
1045   // with the white list is ongoing.
1046   std::tuple<Address, uint8_t> erase_tuple = std::make_tuple(addr, addr_type);
1047   for (size_t i = 0; i < le_white_list_.size(); i++) {
1048     if (le_white_list_[i] == erase_tuple) {
1049       le_white_list_.erase(le_white_list_.begin() + i);
1050     }
1051   }
1052 }
1053 
LeWhiteListContainsDevice(Address addr,uint8_t addr_type)1054 bool LinkLayerController::LeWhiteListContainsDevice(Address addr, uint8_t addr_type) {
1055   std::tuple<Address, uint8_t> sought_tuple = std::make_tuple(addr, addr_type);
1056   for (size_t i = 0; i < le_white_list_.size(); i++) {
1057     if (le_white_list_[i] == sought_tuple) {
1058       return true;
1059     }
1060   }
1061   return false;
1062 }
1063 
LeWhiteListFull()1064 bool LinkLayerController::LeWhiteListFull() {
1065   return le_white_list_.size() >= properties_.GetLeWhiteListSize();
1066 }
1067 
Reset()1068 void LinkLayerController::Reset() {
1069   inquiry_state_ = Inquiry::InquiryState::STANDBY;
1070   last_inquiry_ = steady_clock::now();
1071   le_scan_enable_ = 0;
1072   le_connect_ = 0;
1073 }
1074 
PageScan()1075 void LinkLayerController::PageScan() {}
1076 
StartInquiry(milliseconds timeout)1077 void LinkLayerController::StartInquiry(milliseconds timeout) {
1078   schedule_task_(milliseconds(timeout), [this]() { LinkLayerController::InquiryTimeout(); });
1079   inquiry_state_ = Inquiry::InquiryState::INQUIRY;
1080   LOG_INFO(LOG_TAG, "InquiryState = %d ", static_cast<int>(inquiry_state_));
1081 }
1082 
InquiryCancel()1083 void LinkLayerController::InquiryCancel() {
1084   CHECK(inquiry_state_ == Inquiry::InquiryState::INQUIRY);
1085   inquiry_state_ = Inquiry::InquiryState::STANDBY;
1086 }
1087 
InquiryTimeout()1088 void LinkLayerController::InquiryTimeout() {
1089   if (inquiry_state_ == Inquiry::InquiryState::INQUIRY) {
1090     inquiry_state_ = Inquiry::InquiryState::STANDBY;
1091     send_event_(EventPacketBuilder::CreateInquiryCompleteEvent(hci::Status::SUCCESS)->ToVector());
1092   }
1093 }
1094 
SetInquiryMode(uint8_t mode)1095 void LinkLayerController::SetInquiryMode(uint8_t mode) {
1096   inquiry_mode_ = static_cast<Inquiry::InquiryType>(mode);
1097 }
1098 
SetInquiryLAP(uint64_t lap)1099 void LinkLayerController::SetInquiryLAP(uint64_t lap) {
1100   inquiry_lap_ = lap;
1101 }
1102 
SetInquiryMaxResponses(uint8_t max)1103 void LinkLayerController::SetInquiryMaxResponses(uint8_t max) {
1104   inquiry_max_responses_ = max;
1105 }
1106 
Inquiry()1107 void LinkLayerController::Inquiry() {
1108   steady_clock::time_point now = steady_clock::now();
1109   if (duration_cast<milliseconds>(now - last_inquiry_) < milliseconds(2000)) {
1110     return;
1111   }
1112   LOG_INFO(LOG_TAG, "Inquiry ");
1113   std::unique_ptr<InquiryBuilder> inquiry = InquiryBuilder::Create(inquiry_mode_);
1114   std::shared_ptr<LinkLayerPacketBuilder> to_send =
1115       LinkLayerPacketBuilder::WrapInquiry(std::move(inquiry), properties_.GetAddress());
1116   SendLinkLayerPacket(to_send);
1117   last_inquiry_ = now;
1118 }
1119 
SetInquiryScanEnable(bool enable)1120 void LinkLayerController::SetInquiryScanEnable(bool enable) {
1121   inquiry_scans_enabled_ = enable;
1122 }
1123 
SetPageScanEnable(bool enable)1124 void LinkLayerController::SetPageScanEnable(bool enable) {
1125   page_scans_enabled_ = enable;
1126 }
1127 
1128 /* TODO: Connection handling
1129   // TODO: Handle in the link manager.
1130   uint16_t handle = LeGetHandle();
1131 
1132   std::shared_ptr<Connection> new_connection =
1133       std::make_shared<Connection>(peer, handle);
1134   connections_.push_back(new_connection);
1135   peer->SetConnection(new_connection);
1136 
1137   send_event_(EventPacketBuilder::CreateLeEnhancedConnectionCompleteEvent(
1138       hci::Status::SUCCESS, handle, 0x00,  // role
1139       le_peer_address_type_, le_peer_address_, Address::kEmpty,
1140   Address::kEmpty, 0x0024, 0x0000, 0x01f4)->ToVector());
1141 */
1142 }  // namespace test_vendor_lib
1143