• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 "hci/le_address_manager.h"
18 
19 #include <bluetooth/log.h>
20 #include <com_android_bluetooth_flags.h>
21 
22 #include <ctime>
23 
24 #include "hci/controller.h"
25 #include "hci/octets.h"
26 #include "include/macros.h"
27 #include "os/rand.h"
28 
29 // TODO(b/378143579) For peer address not in resolving list
30 
31 namespace bluetooth {
32 namespace hci {
33 
34 static constexpr uint8_t BLE_ADDR_MASK = 0xc0u;
35 
36 enum class LeAddressManager::ClientState {
37   WAITING_FOR_PAUSE,
38   PAUSED,
39   WAITING_FOR_RESUME,
40   RESUMED,
41 };
42 
ClientStateText(const ClientState cs)43 std::string LeAddressManager::ClientStateText(const ClientState cs) {
44   switch (cs) {
45     CASE_RETURN_STRING(ClientState::WAITING_FOR_PAUSE);
46     CASE_RETURN_STRING(ClientState::PAUSED);
47     CASE_RETURN_STRING(ClientState::WAITING_FOR_RESUME);
48     CASE_RETURN_STRING(ClientState::RESUMED);
49   }
50   RETURN_UNKNOWN_TYPE_STRING(ClientState, cs);
51 }
52 
AddressPolicyText(const LeAddressManager::AddressPolicy policy)53 static std::string AddressPolicyText(const LeAddressManager::AddressPolicy policy) {
54   switch (policy) {
55     CASE_RETURN_STRING(LeAddressManager::AddressPolicy::POLICY_NOT_SET);
56     CASE_RETURN_STRING(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
57     CASE_RETURN_STRING(LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS);
58     CASE_RETURN_STRING(LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS);
59     CASE_RETURN_STRING(LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS);
60   }
61   RETURN_UNKNOWN_TYPE_STRING(LeAddressManager::AddressPolicy, policy);
62 }
63 
LeAddressManager(common::Callback<void (std::unique_ptr<CommandBuilder>)> enqueue_command,os::Handler * handler,Address public_address,uint8_t accept_list_size,uint8_t resolving_list_size,Controller * controller)64 LeAddressManager::LeAddressManager(
65         common::Callback<void(std::unique_ptr<CommandBuilder>)> enqueue_command,
66         os::Handler* handler, Address public_address, uint8_t accept_list_size,
67         uint8_t resolving_list_size, Controller* controller)
68     : enqueue_command_(enqueue_command),
69       handler_(handler),
70       public_address_(public_address),
71       accept_list_size_(accept_list_size),
72       resolving_list_size_(resolving_list_size),
73       controller_(controller) {}
74 
~LeAddressManager()75 LeAddressManager::~LeAddressManager() {
76   if (address_rotation_wake_alarm_ != nullptr) {
77     address_rotation_wake_alarm_->Cancel();
78     address_rotation_wake_alarm_.reset();
79   }
80   if (address_rotation_non_wake_alarm_ != nullptr) {
81     address_rotation_non_wake_alarm_->Cancel();
82     address_rotation_non_wake_alarm_.reset();
83   }
84   if (address_rotation_interval_min.has_value()) {
85     address_rotation_interval_min.reset();
86   }
87   if (address_rotation_interval_max.has_value()) {
88     address_rotation_interval_max.reset();
89   }
90 }
91 
92 // Called on initialization, and on IRK rotation
SetPrivacyPolicyForInitiatorAddress(AddressPolicy address_policy,AddressWithType fixed_address,Octet16 rotation_irk,bool supports_ble_privacy,std::chrono::milliseconds minimum_rotation_time,std::chrono::milliseconds maximum_rotation_time)93 void LeAddressManager::SetPrivacyPolicyForInitiatorAddress(
94         AddressPolicy address_policy, AddressWithType fixed_address, Octet16 rotation_irk,
95         bool supports_ble_privacy, std::chrono::milliseconds minimum_rotation_time,
96         std::chrono::milliseconds maximum_rotation_time) {
97   // Handle repeated calls to the function for IRK rotation
98   if (address_policy_ != AddressPolicy::POLICY_NOT_SET) {
99     // Need to update some parameteres like IRK if privacy is supported
100     if (supports_ble_privacy) {
101       log::info("Updating rotation parameters.");
102       handler_->CallOn(
103               this, &LeAddressManager::prepare_to_update_irk,
104               UpdateIRKCommand{rotation_irk, minimum_rotation_time, maximum_rotation_time});
105     }
106     return;
107   }
108   log::assert_that(address_policy_ == AddressPolicy::POLICY_NOT_SET,
109                    "assert failed: address_policy_ == AddressPolicy::POLICY_NOT_SET");
110   log::assert_that(address_policy != AddressPolicy::POLICY_NOT_SET,
111                    "assert failed: address_policy != AddressPolicy::POLICY_NOT_SET");
112   log::assert_that(registered_clients_.empty(),
113                    "Policy must be set before clients are registered.");
114   address_policy_ = address_policy;
115   supports_ble_privacy_ = supports_ble_privacy;
116   log::info("New policy: {}", AddressPolicyText(address_policy));
117 
118   if (com::android::bluetooth::flags::nrpa_non_connectable_adv()) {
119     minimum_rotation_time_ = minimum_rotation_time;
120     maximum_rotation_time_ = maximum_rotation_time;
121     log::info("minimum_rotation_time_={}ms, maximum_rotation_time_={}ms",
122               minimum_rotation_time_.count(), maximum_rotation_time_.count());
123   }
124 
125   switch (address_policy_) {
126     case AddressPolicy::USE_PUBLIC_ADDRESS:
127       le_address_ = AddressWithType(public_address_, AddressType::PUBLIC_DEVICE_ADDRESS);
128       handler_->BindOnceOn(this, &LeAddressManager::resume_registered_clients)();
129       break;
130     case AddressPolicy::USE_STATIC_ADDRESS: {
131       auto addr = fixed_address.GetAddress();
132       auto address = addr.address;
133       // The two most significant bits of the static address shall be equal to 1
134       log::assert_that((address[5] & BLE_ADDR_MASK) == BLE_ADDR_MASK,
135                        "The two most significant bits shall be equal to 1");
136       // Bits of the random part of the address shall not be all 1 or all 0
137       if ((address[0] == 0x00 && address[1] == 0x00 && address[2] == 0x00 && address[3] == 0x00 &&
138            address[4] == 0x00 && address[5] == BLE_ADDR_MASK) ||
139           (address[0] == 0xFF && address[1] == 0xFF && address[2] == 0xFF && address[3] == 0xFF &&
140            address[4] == 0xFF && address[5] == 0xFF)) {
141         log::fatal("Bits of the random part of the address shall not be all 1 or all 0");
142       }
143       le_address_ = fixed_address;
144       auto packet = hci::LeSetRandomAddressBuilder::Create(le_address_.GetAddress());
145       handler_->Post(common::BindOnce(enqueue_command_, std::move(packet)));
146     } break;
147     case AddressPolicy::USE_NON_RESOLVABLE_ADDRESS:
148     case AddressPolicy::USE_RESOLVABLE_ADDRESS:
149       le_address_ = fixed_address;
150       rotation_irk_ = rotation_irk;
151       if (!com::android::bluetooth::flags::nrpa_non_connectable_adv()) {
152         minimum_rotation_time_ = minimum_rotation_time;
153         maximum_rotation_time_ = maximum_rotation_time;
154         log::info("minimum_rotation_time_={}ms, maximum_rotation_time_={}ms",
155                   minimum_rotation_time_.count(), maximum_rotation_time_.count());
156       }
157       if (controller_->IsRpaGenerationSupported()) {
158         auto min_seconds = std::chrono::duration_cast<std::chrono::seconds>(minimum_rotation_time_);
159         auto max_seconds = std::chrono::duration_cast<std::chrono::seconds>(maximum_rotation_time_);
160         log::info("Support RPA offload, set min_seconds={}s, max_seconds={}s", min_seconds.count(),
161                   max_seconds.count());
162         /* Default to 7 minutes minimum, 15 minutes maximum for random address refreshing;
163          * device can override. */
164         auto packet = hci::LeSetResolvablePrivateAddressTimeoutV2Builder::Create(
165                 min_seconds.count(), max_seconds.count());
166         enqueue_command_.Run(std::move(packet));
167       } else {
168         address_rotation_wake_alarm_ = std::make_unique<os::Alarm>(handler_, true);
169         address_rotation_non_wake_alarm_ = std::make_unique<os::Alarm>(handler_, false);
170       }
171       set_random_address();
172       break;
173     case AddressPolicy::POLICY_NOT_SET:
174       log::fatal("invalid parameters");
175   }
176 }
177 
178 // TODO(jpawlowski): remove once we have config file abstraction in cert tests
SetPrivacyPolicyForInitiatorAddressForTest(AddressPolicy address_policy,AddressWithType fixed_address,Octet16 rotation_irk,std::chrono::milliseconds minimum_rotation_time,std::chrono::milliseconds maximum_rotation_time)179 void LeAddressManager::SetPrivacyPolicyForInitiatorAddressForTest(
180         AddressPolicy address_policy, AddressWithType fixed_address, Octet16 rotation_irk,
181         std::chrono::milliseconds minimum_rotation_time,
182         std::chrono::milliseconds maximum_rotation_time) {
183   log::assert_that(address_policy != AddressPolicy::POLICY_NOT_SET,
184                    "assert failed: address_policy != AddressPolicy::POLICY_NOT_SET");
185   log::assert_that(registered_clients_.empty(),
186                    "Policy must be set before clients are registered.");
187   address_policy_ = address_policy;
188 
189   switch (address_policy_) {
190     case AddressPolicy::USE_PUBLIC_ADDRESS:
191       le_address_ = fixed_address;
192       break;
193     case AddressPolicy::USE_STATIC_ADDRESS: {
194       auto addr = fixed_address.GetAddress();
195       auto address = addr.address;
196       // The two most significant bits of the static address shall be equal to 1
197       log::assert_that((address[5] & BLE_ADDR_MASK) == BLE_ADDR_MASK,
198                        "The two most significant bits shall be equal to 1");
199       // Bits of the random part of the address shall not be all 1 or all 0
200       if ((address[0] == 0x00 && address[1] == 0x00 && address[2] == 0x00 && address[3] == 0x00 &&
201            address[4] == 0x00 && address[5] == BLE_ADDR_MASK) ||
202           (address[0] == 0xFF && address[1] == 0xFF && address[2] == 0xFF && address[3] == 0xFF &&
203            address[4] == 0xFF && address[5] == 0xFF)) {
204         log::fatal("Bits of the random part of the address shall not be all 1 or all 0");
205       }
206       le_address_ = fixed_address;
207       auto packet = hci::LeSetRandomAddressBuilder::Create(le_address_.GetAddress());
208       handler_->Call(enqueue_command_, std::move(packet));
209     } break;
210     case AddressPolicy::USE_NON_RESOLVABLE_ADDRESS:
211     case AddressPolicy::USE_RESOLVABLE_ADDRESS:
212       rotation_irk_ = rotation_irk;
213       minimum_rotation_time_ = minimum_rotation_time;
214       maximum_rotation_time_ = maximum_rotation_time;
215       log::info("minimum_rotation_time_={}ms, maximum_rotation_time_={}ms",
216                 minimum_rotation_time_.count(), maximum_rotation_time_.count());
217       if (controller_->IsRpaGenerationSupported()) {
218         auto min_seconds = std::chrono::duration_cast<std::chrono::seconds>(minimum_rotation_time_);
219         auto max_seconds = std::chrono::duration_cast<std::chrono::seconds>(maximum_rotation_time_);
220         log::info("Support RPA offload, set min_seconds={}s, max_seconds={}s", min_seconds.count(),
221                   max_seconds.count());
222         /* Default to 7 minutes minimum, 15 minutes maximum for random address refreshing;
223          * device can override. */
224         auto packet = hci::LeSetResolvablePrivateAddressTimeoutV2Builder::Create(
225                 min_seconds.count(), max_seconds.count());
226         enqueue_command_.Run(std::move(packet));
227       } else {
228         address_rotation_wake_alarm_ = std::make_unique<os::Alarm>(handler_, true);
229         address_rotation_non_wake_alarm_ = std::make_unique<os::Alarm>(handler_, false);
230         set_random_address();
231       }
232       break;
233     case AddressPolicy::POLICY_NOT_SET:
234       log::fatal("invalid parameters");
235   }
236 }
GetAddressPolicy()237 LeAddressManager::AddressPolicy LeAddressManager::GetAddressPolicy() { return address_policy_; }
RotatingAddress()238 bool LeAddressManager::RotatingAddress() {
239   return address_policy_ == AddressPolicy::USE_RESOLVABLE_ADDRESS ||
240          address_policy_ == AddressPolicy::USE_NON_RESOLVABLE_ADDRESS;
241 }
Register(LeAddressManagerCallback * callback)242 LeAddressManager::AddressPolicy LeAddressManager::Register(LeAddressManagerCallback* callback) {
243   handler_->BindOnceOn(this, &LeAddressManager::register_client, callback)();
244   return address_policy_;
245 }
246 
register_client(LeAddressManagerCallback * callback)247 void LeAddressManager::register_client(LeAddressManagerCallback* callback) {
248   registered_clients_.insert(
249           std::pair<LeAddressManagerCallback*, ClientState>(callback, ClientState::RESUMED));
250   if (address_policy_ == AddressPolicy::POLICY_NOT_SET) {
251     log::info("address policy isn't set yet, pause clients and return");
252     pause_registered_clients();
253     return;
254   } else if (address_policy_ == AddressPolicy::USE_RESOLVABLE_ADDRESS ||
255              address_policy_ == AddressPolicy::USE_NON_RESOLVABLE_ADDRESS) {
256     if (registered_clients_.size() == 1) {
257       if (!controller_->IsRpaGenerationSupported()) {
258         schedule_rotate_random_address();
259         log::info("Scheduled address rotation for first client registered");
260       }
261     }
262   }
263   log::info("Client registered");
264 }
265 
Unregister(LeAddressManagerCallback * callback)266 void LeAddressManager::Unregister(LeAddressManagerCallback* callback) {
267   handler_->BindOnceOn(this, &LeAddressManager::unregister_client, callback)();
268 }
269 
unregister_client(LeAddressManagerCallback * callback)270 void LeAddressManager::unregister_client(LeAddressManagerCallback* callback) {
271   if (registered_clients_.find(callback) != registered_clients_.end()) {
272     if (registered_clients_.find(callback)->second == ClientState::WAITING_FOR_PAUSE) {
273       ack_pause(callback);
274     } else if (registered_clients_.find(callback)->second == ClientState::WAITING_FOR_RESUME) {
275       ack_resume(callback);
276     }
277     registered_clients_.erase(callback);
278     log::info("Client unregistered");
279   }
280   if (registered_clients_.empty()) {
281     if (address_rotation_wake_alarm_ != nullptr) {
282       address_rotation_wake_alarm_->Cancel();
283     }
284     if (address_rotation_non_wake_alarm_ != nullptr) {
285       address_rotation_non_wake_alarm_->Cancel();
286     }
287     if (address_rotation_interval_min.has_value()) {
288       address_rotation_interval_min.reset();
289     }
290     if (address_rotation_interval_max.has_value()) {
291       address_rotation_interval_max.reset();
292     }
293     log::info("Cancelled address rotation alarm");
294   }
295 }
296 
UnregisterSync(LeAddressManagerCallback * callback,std::chrono::milliseconds timeout)297 bool LeAddressManager::UnregisterSync(LeAddressManagerCallback* callback,
298                                       std::chrono::milliseconds timeout) {
299   handler_->BindOnceOn(this, &LeAddressManager::unregister_client, callback)();
300   std::promise<void> promise;
301   auto future = promise.get_future();
302   handler_->Post(common::BindOnce(&std::promise<void>::set_value, common::Unretained(&promise)));
303   return future.wait_for(timeout) == std::future_status::ready;
304 }
305 
AckPause(LeAddressManagerCallback * callback)306 void LeAddressManager::AckPause(LeAddressManagerCallback* callback) {
307   handler_->BindOnceOn(this, &LeAddressManager::ack_pause, callback)();
308 }
309 
AckResume(LeAddressManagerCallback * callback)310 void LeAddressManager::AckResume(LeAddressManagerCallback* callback) {
311   handler_->BindOnceOn(this, &LeAddressManager::ack_resume, callback)();
312 }
313 
GetInitiatorAddress()314 AddressWithType LeAddressManager::GetInitiatorAddress() {
315   log::assert_that(address_policy_ != AddressPolicy::POLICY_NOT_SET,
316                    "assert failed: address_policy_ != AddressPolicy::POLICY_NOT_SET");
317   return le_address_;
318 }
319 
NewResolvableAddress()320 AddressWithType LeAddressManager::NewResolvableAddress() {
321   log::assert_that(RotatingAddress(), "assert failed: RotatingAddress()");
322   hci::Address address = generate_rpa();
323   auto random_address = AddressWithType(address, AddressType::RANDOM_DEVICE_ADDRESS);
324   return random_address;
325 }
326 
NewNonResolvableAddress()327 AddressWithType LeAddressManager::NewNonResolvableAddress() {
328   if (!com::android::bluetooth::flags::nrpa_non_connectable_adv()) {
329     log::assert_that(RotatingAddress(), "assert failed: RotatingAddress()");
330   }
331   hci::Address address = generate_nrpa();
332   auto random_address = AddressWithType(address, AddressType::RANDOM_DEVICE_ADDRESS);
333   return random_address;
334 }
335 
pause_registered_clients()336 void LeAddressManager::pause_registered_clients() {
337   for (auto& client : registered_clients_) {
338     switch (client.second) {
339       case ClientState::PAUSED:
340       case ClientState::WAITING_FOR_PAUSE:
341         break;
342       case ClientState::WAITING_FOR_RESUME:
343       case ClientState::RESUMED:
344         client.second = ClientState::WAITING_FOR_PAUSE;
345         client.first->OnPause();
346         break;
347     }
348   }
349 }
350 
push_command(Command command)351 void LeAddressManager::push_command(Command command) {
352   pause_registered_clients();
353   cached_commands_.push(std::move(command));
354 }
355 
ack_pause(LeAddressManagerCallback * callback)356 void LeAddressManager::ack_pause(LeAddressManagerCallback* callback) {
357   if (registered_clients_.find(callback) == registered_clients_.end()) {
358     log::info("No clients registered to ack pause");
359     return;
360   }
361   registered_clients_.find(callback)->second = ClientState::PAUSED;
362   for (auto client : registered_clients_) {
363     switch (client.second) {
364       case ClientState::PAUSED:
365         log::verbose("Client already in paused state");
366         break;
367       case ClientState::WAITING_FOR_PAUSE:
368         // make sure all client paused
369         log::debug("Wait all clients paused, return");
370         return;
371       case ClientState::WAITING_FOR_RESUME:
372       case ClientState::RESUMED:
373         log::warn("Trigger OnPause for client {}", ClientStateText(client.second));
374         client.second = ClientState::WAITING_FOR_PAUSE;
375         client.first->OnPause();
376         return;
377     }
378   }
379 
380   if (address_policy_ != AddressPolicy::POLICY_NOT_SET) {
381     check_cached_commands();
382   }
383 }
384 
resume_registered_clients()385 void LeAddressManager::resume_registered_clients() {
386   // Do not resume clients if cached command is not empty
387   if (!cached_commands_.empty()) {
388     handle_next_command();
389     return;
390   }
391 
392   log::info("Resuming registered clients");
393   for (auto& client : registered_clients_) {
394     if (client.second != ClientState::PAUSED) {
395       log::warn("client is not paused {}", ClientStateText(client.second));
396     }
397     client.second = ClientState::WAITING_FOR_RESUME;
398     client.first->OnResume();
399   }
400 }
401 
ack_resume(LeAddressManagerCallback * callback)402 void LeAddressManager::ack_resume(LeAddressManagerCallback* callback) {
403   if (registered_clients_.find(callback) != registered_clients_.end()) {
404     registered_clients_.find(callback)->second = ClientState::RESUMED;
405   } else {
406     log::info("Client not registered");
407   }
408 }
409 
prepare_to_rotate()410 void LeAddressManager::prepare_to_rotate() {
411   Command command = {CommandType::ROTATE_RANDOM_ADDRESS, RotateRandomAddressCommand{}};
412   cached_commands_.push(std::move(command));
413   pause_registered_clients();
414 }
415 
schedule_rotate_random_address()416 void LeAddressManager::schedule_rotate_random_address() {
417   std::string client_name = "LeAddressManager";
418   auto privateAddressIntervalRange = GetNextPrivateAddressIntervalRange(client_name);
419   address_rotation_wake_alarm_->Schedule(
420           common::BindOnce(
421                   []() { log::info("deadline wakeup in schedule_rotate_random_address"); }),
422           privateAddressIntervalRange.max);
423   address_rotation_non_wake_alarm_->Schedule(
424           common::BindOnce(&LeAddressManager::prepare_to_rotate, common::Unretained(this)),
425           privateAddressIntervalRange.min);
426 
427   auto now = std::chrono::system_clock::now();
428   if (address_rotation_interval_min.has_value()) {
429     CheckAddressRotationHappenedInExpectedTimeInterval(
430             *address_rotation_interval_min, *address_rotation_interval_max, now, client_name);
431   }
432 
433   // Update the expected range here.
434   address_rotation_interval_min.emplace(now + privateAddressIntervalRange.min);
435   address_rotation_interval_max.emplace(now + privateAddressIntervalRange.max);
436 }
437 
set_random_address()438 void LeAddressManager::set_random_address() {
439   if (address_policy_ != AddressPolicy::USE_RESOLVABLE_ADDRESS &&
440       address_policy_ != AddressPolicy::USE_NON_RESOLVABLE_ADDRESS) {
441     log::fatal("Invalid address policy!");
442     return;
443   }
444 
445   hci::Address address;
446   if (address_policy_ == AddressPolicy::USE_RESOLVABLE_ADDRESS) {
447     address = generate_rpa();
448   } else {
449     address = generate_nrpa();
450   }
451   auto packet = hci::LeSetRandomAddressBuilder::Create(address);
452   enqueue_command_.Run(std::move(packet));
453   cached_address_ = AddressWithType(address, AddressType::RANDOM_DEVICE_ADDRESS);
454 }
455 
rotate_random_address()456 void LeAddressManager::rotate_random_address() {
457   if (address_policy_ != AddressPolicy::USE_RESOLVABLE_ADDRESS &&
458       address_policy_ != AddressPolicy::USE_NON_RESOLVABLE_ADDRESS) {
459     log::fatal("Invalid address policy!");
460     return;
461   }
462 
463   schedule_rotate_random_address();
464   set_random_address();
465 }
466 
prepare_to_update_irk(UpdateIRKCommand update_irk_command)467 void LeAddressManager::prepare_to_update_irk(UpdateIRKCommand update_irk_command) {
468   Command command = {CommandType::UPDATE_IRK, update_irk_command};
469   cached_commands_.push(std::move(command));
470   if (registered_clients_.empty()) {
471     handle_next_command();
472   } else {
473     pause_registered_clients();
474   }
475 }
476 
update_irk(UpdateIRKCommand command)477 void LeAddressManager::update_irk(UpdateIRKCommand command) {
478   rotation_irk_ = command.rotation_irk;
479   minimum_rotation_time_ = command.minimum_rotation_time;
480   maximum_rotation_time_ = command.maximum_rotation_time;
481   log::info("minimum_rotation_time_={}ms, maximum_rotation_time_={}ms",
482             minimum_rotation_time_.count(), maximum_rotation_time_.count());
483   set_random_address();
484   for (auto& client : registered_clients_) {
485     client.first->NotifyOnIRKChange();
486   }
487 }
488 
489 /* This function generates Resolvable Private Address (RPA) from Identity
490  * Resolving Key |irk| and |prand|*/
generate_rpa()491 hci::Address LeAddressManager::generate_rpa() {
492   // most significant bit, bit7, bit6 is 01 to be resolvable random
493   // Bits of the random part of prand shall not be all 1 or all 0
494   std::array<uint8_t, 3> prand = os::GenerateRandom<3>();
495   constexpr uint8_t BLE_RESOLVE_ADDR_MSB = 0x40;
496   prand[2] &= ~BLE_ADDR_MASK;
497   if ((prand[0] == 0x00 && prand[1] == 0x00 && prand[2] == 0x00) ||
498       (prand[0] == 0xFF && prand[1] == 0xFF && prand[2] == 0x3F)) {
499     prand[0] = (uint8_t)(os::GenerateRandom() % 0xFE + 1);
500   }
501   prand[2] |= BLE_RESOLVE_ADDR_MSB;
502 
503   hci::Address address;
504   address.address[3] = prand[0];
505   address.address[4] = prand[1];
506   address.address[5] = prand[2];
507 
508   Octet16 rand{};
509   rand[0] = prand[0];
510   rand[1] = prand[1];
511   rand[2] = prand[2];
512 
513   /* encrypt with IRK */
514   Octet16 p = crypto_toolbox::aes_128(rotation_irk_, rand);
515 
516   /* set hash to be LSB of rpAddress */
517   address.address[0] = p[0];
518   address.address[1] = p[1];
519   address.address[2] = p[2];
520   return address;
521 }
522 
523 // This function generates NON-Resolvable Private Address (NRPA)
generate_nrpa()524 hci::Address LeAddressManager::generate_nrpa() {
525   // The two most significant bits of the address shall be equal to 0
526   // Bits of the random part of the address shall not be all 1 or all 0
527   std::array<uint8_t, 6> random = os::GenerateRandom<6>();
528   random[5] &= ~BLE_ADDR_MASK;
529   if ((random[0] == 0x00 && random[1] == 0x00 && random[2] == 0x00 && random[3] == 0x00 &&
530        random[4] == 0x00 && random[5] == 0x00) ||
531       (random[0] == 0xFF && random[1] == 0xFF && random[2] == 0xFF && random[3] == 0xFF &&
532        random[4] == 0xFF && random[5] == 0x3F)) {
533     random[0] = (uint8_t)(os::GenerateRandom() % 0xFE + 1);
534   }
535 
536   hci::Address address;
537   address.FromOctets(random.data());
538 
539   // the address shall not be equal to the public address
540   while (address == public_address_) {
541     address.address[0] = (uint8_t)(os::GenerateRandom() % 0xFE + 1);
542   }
543 
544   return address;
545 }
546 
GetNextPrivateAddressIntervalMs()547 std::chrono::milliseconds LeAddressManager::GetNextPrivateAddressIntervalMs() {
548   auto interval_random_part_wake_delay = maximum_rotation_time_ - minimum_rotation_time_;
549   auto random_ms =
550           std::chrono::milliseconds(os::GenerateRandom()) % (interval_random_part_wake_delay);
551   return minimum_rotation_time_ + random_ms;
552 }
553 
GetNextPrivateAddressIntervalRange(const std::string & client_name)554 PrivateAddressIntervalRange LeAddressManager::GetNextPrivateAddressIntervalRange(
555         const std::string& client_name) {
556   // Get both alarms' delays as following:
557   // - Non-wake  : Random between [minimum_rotation_time_, (minimum_rotation_time_ + 2 min)]
558   // - Wake      : Random between [(maximum_rotation_time_ - 2 min), maximum_rotation_time_]
559   // - Ensure that delays are in the given range [minimum_rotation_time_, maximum_rotation_time_]
560   // - Ensure that the non-wake alarm's delay is not greater than wake alarm's delay.
561   auto random_part_max_length = std::chrono::minutes(2);
562 
563   auto nonwake_delay = minimum_rotation_time_ +
564                        (std::chrono::milliseconds(os::GenerateRandom()) % random_part_max_length);
565   nonwake_delay = min(nonwake_delay, maximum_rotation_time_);
566 
567   auto wake_delay = maximum_rotation_time_ -
568                     (std::chrono::milliseconds(os::GenerateRandom()) % random_part_max_length);
569   wake_delay = max(nonwake_delay, max(wake_delay, minimum_rotation_time_));
570 
571   // For readable logging, the durations are rounded down to integer seconds.
572   auto min_minutes = std::chrono::duration_cast<std::chrono::minutes>(nonwake_delay);
573   auto min_seconds = std::chrono::duration_cast<std::chrono::seconds>(nonwake_delay - min_minutes);
574   auto max_minutes = std::chrono::duration_cast<std::chrono::minutes>(wake_delay);
575   auto max_seconds = std::chrono::duration_cast<std::chrono::seconds>(wake_delay - max_minutes);
576   log::info("client={}, nonwake={}m{}s, wake={}m{}s", client_name, min_minutes.count(),
577             min_seconds.count(), max_minutes.count(), max_seconds.count());
578 
579   return PrivateAddressIntervalRange{nonwake_delay, wake_delay};
580 }
581 
CheckAddressRotationHappenedInExpectedTimeInterval(const std::chrono::time_point<std::chrono::system_clock> & interval_min,const std::chrono::time_point<std::chrono::system_clock> & interval_max,const std::chrono::time_point<std::chrono::system_clock> & event_time,const std::string & client_name)582 void LeAddressManager::CheckAddressRotationHappenedInExpectedTimeInterval(
583         const std::chrono::time_point<std::chrono::system_clock>& interval_min,
584         const std::chrono::time_point<std::chrono::system_clock>& interval_max,
585         const std::chrono::time_point<std::chrono::system_clock>& event_time,
586         const std::string& client_name) {
587   // Give some tolerance since alarms may ring a little bit early or late.
588   auto lower_limit_tolerance = std::chrono::seconds(2);
589   auto upper_limit_tolerance = std::chrono::seconds(5);
590 
591   if (event_time < interval_min - lower_limit_tolerance ||
592       event_time > interval_max + upper_limit_tolerance) {
593     log::warn("RPA rotation happened outside expected time interval. client={}", client_name);
594 
595     auto tt_interval_min = std::chrono::system_clock::to_time_t(interval_min);
596     auto tt_interval_max = std::chrono::system_clock::to_time_t(interval_max);
597     auto tt_event_time = std::chrono::system_clock::to_time_t(event_time);
598     log::warn("interval_min={}", ctime(&tt_interval_min));
599     log::warn("interval_max={}", ctime(&tt_interval_max));
600     log::warn("event_time=  {}", ctime(&tt_event_time));
601   }
602 }
603 
GetFilterAcceptListSize()604 uint8_t LeAddressManager::GetFilterAcceptListSize() { return accept_list_size_; }
605 
GetResolvingListSize()606 uint8_t LeAddressManager::GetResolvingListSize() { return resolving_list_size_; }
607 
handle_next_command()608 void LeAddressManager::handle_next_command() {
609   for (auto client : registered_clients_) {
610     if (client.second != ClientState::PAUSED) {
611       // make sure all client paused, if not, this function will be trigger again by ack_pause
612       log::info("waiting for ack_pause, return");
613       return;
614     }
615   }
616 
617   log::assert_that(!cached_commands_.empty(), "assert failed: !cached_commands_.empty()");
618   auto command = std::move(cached_commands_.front());
619   cached_commands_.pop();
620 
621   std::visit(
622           [this](auto&& command) {
623             using T = std::decay_t<decltype(command)>;
624             if constexpr (std::is_same_v<T, UpdateIRKCommand>) {
625               update_irk(command);
626             } else if constexpr (std::is_same_v<T, RotateRandomAddressCommand>) {
627               rotate_random_address();
628             } else if constexpr (std::is_same_v<T, HCICommand>) {
629               enqueue_command_.Run(std::move(command.command));
630             } else {
631               static_assert(!sizeof(T*), "non-exhaustive visitor!");
632             }
633           },
634           command.contents);
635 }
636 
AddDeviceToFilterAcceptList(FilterAcceptListAddressType accept_list_address_type,bluetooth::hci::Address address)637 void LeAddressManager::AddDeviceToFilterAcceptList(
638         FilterAcceptListAddressType accept_list_address_type, bluetooth::hci::Address address) {
639   auto packet_builder =
640           hci::LeAddDeviceToFilterAcceptListBuilder::Create(accept_list_address_type, address);
641   Command command = {CommandType::ADD_DEVICE_TO_ACCEPT_LIST, HCICommand{std::move(packet_builder)}};
642   handler_->BindOnceOn(this, &LeAddressManager::push_command, std::move(command))();
643 }
644 
AddDeviceToResolvingList(PeerAddressType peer_identity_address_type,Address peer_identity_address,const std::array<uint8_t,16> & peer_irk,const std::array<uint8_t,16> & local_irk)645 void LeAddressManager::AddDeviceToResolvingList(PeerAddressType peer_identity_address_type,
646                                                 Address peer_identity_address,
647                                                 const std::array<uint8_t, 16>& peer_irk,
648                                                 const std::array<uint8_t, 16>& local_irk) {
649   if (!supports_ble_privacy_) {
650     return;
651   }
652 
653   // Disable Address resolution
654   auto disable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::DISABLED);
655   Command disable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE,
656                      HCICommand{std::move(disable_builder)}};
657   cached_commands_.push(std::move(disable));
658 
659   auto packet_builder = hci::LeAddDeviceToResolvingListBuilder::Create(
660           peer_identity_address_type, peer_identity_address, peer_irk, local_irk);
661   Command command = {CommandType::ADD_DEVICE_TO_RESOLVING_LIST,
662                      HCICommand{std::move(packet_builder)}};
663   cached_commands_.push(std::move(command));
664 
665   if (supports_ble_privacy_) {
666     auto packet_builder = hci::LeSetPrivacyModeBuilder::Create(
667             peer_identity_address_type, peer_identity_address, PrivacyMode::DEVICE);
668     Command command = {CommandType::LE_SET_PRIVACY_MODE, HCICommand{std::move(packet_builder)}};
669     cached_commands_.push(std::move(command));
670   }
671 
672   // Enable Address resolution
673   auto enable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::ENABLED);
674   Command enable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE,
675                     HCICommand{std::move(enable_builder)}};
676   cached_commands_.push(std::move(enable));
677 
678   if (registered_clients_.empty()) {
679     handler_->BindOnceOn(this, &LeAddressManager::handle_next_command)();
680   } else {
681     handler_->BindOnceOn(this, &LeAddressManager::pause_registered_clients)();
682   }
683 }
684 
RemoveDeviceFromFilterAcceptList(FilterAcceptListAddressType accept_list_address_type,bluetooth::hci::Address address)685 void LeAddressManager::RemoveDeviceFromFilterAcceptList(
686         FilterAcceptListAddressType accept_list_address_type, bluetooth::hci::Address address) {
687   auto packet_builder =
688           hci::LeRemoveDeviceFromFilterAcceptListBuilder::Create(accept_list_address_type, address);
689   Command command = {CommandType::REMOVE_DEVICE_FROM_ACCEPT_LIST,
690                      HCICommand{std::move(packet_builder)}};
691   handler_->BindOnceOn(this, &LeAddressManager::push_command, std::move(command))();
692 }
693 
RemoveDeviceFromResolvingList(PeerAddressType peer_identity_address_type,Address peer_identity_address)694 void LeAddressManager::RemoveDeviceFromResolvingList(PeerAddressType peer_identity_address_type,
695                                                      Address peer_identity_address) {
696   if (!supports_ble_privacy_) {
697     return;
698   }
699 
700   // Disable Address resolution
701   auto disable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::DISABLED);
702   Command disable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE,
703                      HCICommand{std::move(disable_builder)}};
704   cached_commands_.push(std::move(disable));
705 
706   auto packet_builder = hci::LeRemoveDeviceFromResolvingListBuilder::Create(
707           peer_identity_address_type, peer_identity_address);
708   Command command = {CommandType::REMOVE_DEVICE_FROM_RESOLVING_LIST,
709                      HCICommand{std::move(packet_builder)}};
710   cached_commands_.push(std::move(command));
711 
712   // Enable Address resolution
713   auto enable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::ENABLED);
714   Command enable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE,
715                     HCICommand{std::move(enable_builder)}};
716   cached_commands_.push(std::move(enable));
717 
718   if (registered_clients_.empty()) {
719     handler_->BindOnceOn(this, &LeAddressManager::handle_next_command)();
720   } else {
721     handler_->BindOnceOn(this, &LeAddressManager::pause_registered_clients)();
722   }
723 }
724 
ClearFilterAcceptList()725 void LeAddressManager::ClearFilterAcceptList() {
726   auto packet_builder = hci::LeClearFilterAcceptListBuilder::Create();
727   Command command = {CommandType::CLEAR_ACCEPT_LIST, HCICommand{std::move(packet_builder)}};
728   handler_->BindOnceOn(this, &LeAddressManager::push_command, std::move(command))();
729 }
730 
ClearResolvingList()731 void LeAddressManager::ClearResolvingList() {
732   if (!supports_ble_privacy_) {
733     return;
734   }
735 
736   // Disable Address resolution
737   auto disable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::DISABLED);
738   Command disable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE,
739                      HCICommand{std::move(disable_builder)}};
740   cached_commands_.push(std::move(disable));
741 
742   auto packet_builder = hci::LeClearResolvingListBuilder::Create();
743   Command command = {CommandType::CLEAR_RESOLVING_LIST, HCICommand{std::move(packet_builder)}};
744   cached_commands_.push(std::move(command));
745 
746   // Enable Address resolution
747   auto enable_builder = hci::LeSetAddressResolutionEnableBuilder::Create(hci::Enable::ENABLED);
748   Command enable = {CommandType::SET_ADDRESS_RESOLUTION_ENABLE,
749                     HCICommand{std::move(enable_builder)}};
750   cached_commands_.push(std::move(enable));
751 
752   handler_->BindOnceOn(this, &LeAddressManager::pause_registered_clients)();
753 }
754 
755 template <class View>
on_command_complete(CommandCompleteView view)756 void LeAddressManager::on_command_complete(CommandCompleteView view) {
757   auto op_code = view.GetCommandOpCode();
758 
759   auto complete_view = View::Create(view);
760   if (!complete_view.IsValid()) {
761     log::error("Received {} complete with invalid packet", hci::OpCodeText(op_code));
762     return;
763   }
764   auto status = complete_view.GetStatus();
765   if (status != ErrorCode::SUCCESS) {
766     log::error("Received {} complete with status {}", hci::OpCodeText(op_code),
767                ErrorCodeText(complete_view.GetStatus()));
768   }
769 }
770 
OnCommandComplete(bluetooth::hci::CommandCompleteView view)771 void LeAddressManager::OnCommandComplete(bluetooth::hci::CommandCompleteView view) {
772   if (!view.IsValid()) {
773     log::error("Received command complete with invalid packet");
774     return;
775   }
776   auto op_code = view.GetCommandOpCode();
777   log::info("Received command complete with op_code {}", OpCodeText(op_code));
778 
779   switch (op_code) {
780     case OpCode::LE_SET_RANDOM_ADDRESS: {
781       // The command was sent before any client registered, we can make sure all the clients paused
782       // when command complete.
783       if (address_policy_ == AddressPolicy::USE_STATIC_ADDRESS) {
784         log::info(
785                 "Received LE_SET_RANDOM_ADDRESS complete and Address policy is USE_STATIC_ADDRESS, "
786                 "return");
787         return;
788       }
789       auto complete_view = LeSetRandomAddressCompleteView::Create(view);
790       if (!complete_view.IsValid()) {
791         log::error("Received LE_SET_RANDOM_ADDRESS complete with invalid packet");
792       } else {
793         if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
794           log::error("Received LE_SET_RANDOM_ADDRESS complete with status {}",
795                      ErrorCodeText(complete_view.GetStatus()));
796         } else {
797           log::info("update random address : {}", cached_address_.GetAddress());
798           le_address_ = cached_address_;
799         }
800       }
801     } break;
802 
803     case OpCode::LE_SET_PRIVACY_MODE:
804       on_command_complete<LeSetPrivacyModeCompleteView>(view);
805       break;
806 
807     case OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST:
808       on_command_complete<LeAddDeviceToResolvingListCompleteView>(view);
809       break;
810 
811     case OpCode::LE_REMOVE_DEVICE_FROM_RESOLVING_LIST:
812       on_command_complete<LeRemoveDeviceFromResolvingListCompleteView>(view);
813       break;
814 
815     case OpCode::LE_CLEAR_RESOLVING_LIST:
816       on_command_complete<LeClearResolvingListCompleteView>(view);
817       break;
818 
819     case OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST:
820       on_command_complete<LeAddDeviceToFilterAcceptListCompleteView>(view);
821       break;
822 
823     case OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST:
824       on_command_complete<LeRemoveDeviceFromFilterAcceptListCompleteView>(view);
825       break;
826 
827     case OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE:
828       on_command_complete<LeSetAddressResolutionEnableCompleteView>(view);
829       break;
830 
831     case OpCode::LE_CLEAR_FILTER_ACCEPT_LIST:
832       on_command_complete<LeClearFilterAcceptListCompleteView>(view);
833       break;
834 
835     case OpCode::LE_SET_RESOLVABLE_PRIVATE_ADDRESS_TIMEOUT_V2:
836       on_command_complete<LeSetResolvablePrivateAddressTimeoutV2CompleteView>(view);
837       break;
838 
839     default:
840       log::error("Received UNSUPPORTED command {} complete", hci::OpCodeText(op_code));
841       break;
842   }
843 
844   handler_->BindOnceOn(this, &LeAddressManager::check_cached_commands)();
845 }
846 
check_cached_commands()847 void LeAddressManager::check_cached_commands() {
848   for (auto client : registered_clients_) {
849     if (client.second != ClientState::PAUSED && !cached_commands_.empty()) {
850       pause_registered_clients();
851       return;
852     }
853   }
854 
855   if (cached_commands_.empty()) {
856     resume_registered_clients();
857   } else {
858     handle_next_command();
859   }
860 }
861 
862 }  // namespace hci
863 }  // namespace bluetooth
864