• 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 "storage/storage_module.h"
18 
19 #include <bluetooth/log.h>
20 #include <com_android_bluetooth_flags.h>
21 
22 #include <chrono>
23 #include <ctime>
24 #include <iomanip>
25 #include <memory>
26 #include <utility>
27 
28 #include "common/bind.h"
29 #include "metrics/counter_metrics.h"
30 #include "os/alarm.h"
31 #include "os/files.h"
32 #include "os/handler.h"
33 #include "os/parameter_provider.h"
34 #include "os/system_properties.h"
35 #include "storage/config_cache.h"
36 #include "storage/config_keys.h"
37 #include "storage/legacy_config_file.h"
38 #include "storage/mutation.h"
39 
40 namespace bluetooth {
41 namespace storage {
42 
43 using os::Alarm;
44 using os::Handler;
45 
46 static const std::string kFactoryResetProperty = "persist.bluetooth.factoryreset";
47 
48 static const size_t kDefaultTempDeviceCapacity = 10000;
49 // Save config whenever there is a change, but delay it by this value so that burst config change
50 // won't overwhelm disk
51 static const std::chrono::milliseconds kDefaultConfigSaveDelay = std::chrono::milliseconds(3000);
52 // Writing a config to disk takes a minimum 10 ms on a decent x86_64 machine
53 // The config saving delay must be bigger than this value to avoid overwhelming the disk
54 static const std::chrono::milliseconds kMinConfigSaveDelay = std::chrono::milliseconds(20);
55 
56 const int kConfigFileComparePass = 1;
57 const std::string kConfigFilePrefix = "bt_config-origin";
58 const std::string kConfigFileHash = "hash";
59 
60 const std::string StorageModule::kInfoSection = BTIF_STORAGE_SECTION_INFO;
61 const std::string StorageModule::kTimeCreatedProperty = "TimeCreated";
62 const std::string StorageModule::kTimeCreatedFormat = "%Y-%m-%d %H:%M:%S";
63 
64 const std::string StorageModule::kAdapterSection = BTIF_STORAGE_SECTION_ADAPTER;
65 
StorageModule()66 StorageModule::StorageModule()
67     : StorageModule(nullptr, os::ParameterProvider::ConfigFilePath(), kDefaultConfigSaveDelay,
68                     kDefaultTempDeviceCapacity, false, false) {}
69 
StorageModule(os::Handler * handler)70 StorageModule::StorageModule(os::Handler* handler)
71     : StorageModule(handler, os::ParameterProvider::ConfigFilePath(), kDefaultConfigSaveDelay,
72                     kDefaultTempDeviceCapacity, false, false) {}
73 
StorageModule(os::Handler * handler,std::string config_file_path,std::chrono::milliseconds config_save_delay,size_t temp_devices_capacity,bool is_restricted_mode,bool is_single_user_mode)74 StorageModule::StorageModule(os::Handler* handler, std::string config_file_path,
75                              std::chrono::milliseconds config_save_delay,
76                              size_t temp_devices_capacity, bool is_restricted_mode,
77                              bool is_single_user_mode)
78     : Module(handler),
79       config_file_path_(std::move(config_file_path)),
80       config_save_delay_(config_save_delay),
81       temp_devices_capacity_(temp_devices_capacity),
82       is_restricted_mode_(is_restricted_mode),
83       is_single_user_mode_(is_single_user_mode) {
84   log::assert_that(config_save_delay > kMinConfigSaveDelay,
85                    "Config save delay of {} ms is not enough, must be at least {} ms to avoid "
86                    "overwhelming the "
87                    "disk",
88                    config_save_delay_.count(), kMinConfigSaveDelay.count());
89 }
90 
~StorageModule()91 StorageModule::~StorageModule() {
92   std::lock_guard<std::recursive_mutex> lock(mutex_);
93 
94   if (!com::android::bluetooth::flags::same_handler_for_all_modules()) {
95     GetHandler()->Clear();
96     GetHandler()->WaitUntilStopped(std::chrono::milliseconds(2000));
97     delete GetHandler();
98   }
99 
100   pimpl_.reset();
101 }
102 
103 struct StorageModule::impl {
implbluetooth::storage::StorageModule::impl104   explicit impl(Handler* handler, ConfigCache cache, size_t in_memory_cache_size_limit)
105       : config_save_alarm_(handler),
106         cache_(std::move(cache)),
107         memory_only_cache_(in_memory_cache_size_limit, {}) {}
108   Alarm config_save_alarm_;
109   ConfigCache cache_;
110   ConfigCache memory_only_cache_;
111   bool has_pending_config_save_ = false;
112 };
113 
Modify()114 Mutation StorageModule::Modify() {
115   std::lock_guard<std::recursive_mutex> lock(mutex_);
116   return Mutation(&pimpl_->cache_, &pimpl_->memory_only_cache_);
117 }
118 
SaveDelayed()119 void StorageModule::SaveDelayed() {
120   std::lock_guard<std::recursive_mutex> lock(mutex_);
121   if (pimpl_->has_pending_config_save_) {
122     return;
123   }
124   pimpl_->config_save_alarm_.Schedule(
125           common::BindOnce(&StorageModule::SaveImmediately, common::Unretained(this)),
126           config_save_delay_);
127   pimpl_->has_pending_config_save_ = true;
128 }
129 
SaveImmediately()130 void StorageModule::SaveImmediately() {
131   std::lock_guard<std::recursive_mutex> lock(mutex_);
132   if (pimpl_->has_pending_config_save_) {
133     pimpl_->config_save_alarm_.Cancel();
134     pimpl_->has_pending_config_save_ = false;
135   }
136 #ifndef TARGET_FLOSS
137   log::assert_that(
138           LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_),
139           "assert failed: LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_)");
140 #else
141   if (!LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_)) {
142     log::error("Unable to write config file to disk");
143   }
144 #endif
145   // save checksum if it is running in common criteria mode
146   if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr &&
147       bluetooth::os::ParameterProvider::IsCommonCriteriaMode()) {
148     bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->set_encrypt_key_or_remove_key(
149             kConfigFilePrefix, kConfigFileHash);
150   }
151 }
152 
Clear()153 void StorageModule::Clear() {
154   std::lock_guard<std::recursive_mutex> lock(mutex_);
155   pimpl_->cache_.Clear();
156 }
157 
ListDependencies(ModuleList *) const158 void StorageModule::ListDependencies(ModuleList* /*list*/) const {}
159 
Start()160 void StorageModule::Start() {
161   std::lock_guard<std::recursive_mutex> lock(mutex_);
162   if (os::GetSystemProperty(kFactoryResetProperty) == "true") {
163     log::info("{} is true, delete config files", kFactoryResetProperty);
164     LegacyConfigFile::FromPath(config_file_path_).Delete();
165     os::SetSystemProperty(kFactoryResetProperty, "false");
166   }
167   if (!is_config_checksum_pass(kConfigFileComparePass)) {
168     LegacyConfigFile::FromPath(config_file_path_).Delete();
169   }
170   auto config = LegacyConfigFile::FromPath(config_file_path_).Read(temp_devices_capacity_);
171   bool save_needed = false;
172   if (!config || !config->HasSection(kAdapterSection)) {
173     log::warn("Failed to load config at {}; creating new empty ones", config_file_path_);
174     config.emplace(temp_devices_capacity_, Device::kLinkKeyProperties);
175 
176     // Set config file creation timestamp
177     std::stringstream ss;
178     auto now = std::chrono::system_clock::now();
179     auto now_time_t = std::chrono::system_clock::to_time_t(now);
180     ss << std::put_time(std::localtime(&now_time_t), kTimeCreatedFormat.c_str());
181     config->SetProperty(kInfoSection, kTimeCreatedProperty, ss.str());
182     save_needed = true;
183   }
184   pimpl_ = std::make_unique<impl>(GetHandler(), std::move(config.value()), temp_devices_capacity_);
185   pimpl_->cache_.SetPersistentConfigChangedCallback(
186           [this] { this->CallOn(this, &StorageModule::SaveDelayed); });
187 
188   // Cleanup temporary pairings if we have left guest mode
189   if (!com::android::bluetooth::flags::guest_mode_bond() && !is_restricted_mode_) {
190     pimpl_->cache_.RemoveSectionWithProperty("Restricted");
191   }
192 
193   pimpl_->cache_.FixDeviceTypeInconsistencies();
194   if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr) {
195     bluetooth::os::ParameterProvider::GetBtKeystoreInterface()
196             ->ConvertEncryptOrDecryptKeyIfNeeded();
197   }
198 
199   if (save_needed) {
200     SaveDelayed();
201   }
202 }
203 
Stop()204 void StorageModule::Stop() {
205   std::lock_guard<std::recursive_mutex> lock(mutex_);
206   log::assert_that(pimpl_ != nullptr, "StorageModule is not started");
207   if (pimpl_->has_pending_config_save_) {
208     // Save pending changes before stopping the module.
209     SaveImmediately();
210   }
211   if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr) {
212     bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->clear_map();
213   }
214   pimpl_.reset();
215 }
216 
ToString() const217 std::string StorageModule::ToString() const { return "Storage Module"; }
218 
GetDeviceByLegacyKey(hci::Address legacy_key_address)219 Device StorageModule::GetDeviceByLegacyKey(hci::Address legacy_key_address) {
220   std::lock_guard<std::recursive_mutex> lock(mutex_);
221   return Device(&pimpl_->cache_, &pimpl_->memory_only_cache_, std::move(legacy_key_address),
222                 Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS);
223 }
224 
GetDeviceByClassicMacAddress(hci::Address classic_address)225 Device StorageModule::GetDeviceByClassicMacAddress(hci::Address classic_address) {
226   std::lock_guard<std::recursive_mutex> lock(mutex_);
227   return Device(&pimpl_->cache_, &pimpl_->memory_only_cache_, std::move(classic_address),
228                 Device::ConfigKeyAddressType::CLASSIC_ADDRESS);
229 }
230 
GetDeviceByLeIdentityAddress(hci::Address le_identity_address)231 Device StorageModule::GetDeviceByLeIdentityAddress(hci::Address le_identity_address) {
232   std::lock_guard<std::recursive_mutex> lock(mutex_);
233   return Device(&pimpl_->cache_, &pimpl_->memory_only_cache_, std::move(le_identity_address),
234                 Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS);
235 }
236 
GetBondedDevices()237 std::vector<Device> StorageModule::GetBondedDevices() {
238   std::lock_guard<std::recursive_mutex> lock(mutex_);
239   auto persistent_sections = pimpl_->cache_.GetPersistentSections();
240   std::vector<Device> result;
241   result.reserve(persistent_sections.size());
242   for (const auto& section : persistent_sections) {
243     result.emplace_back(&pimpl_->cache_, &pimpl_->memory_only_cache_, section);
244   }
245   return result;
246 }
247 
is_config_checksum_pass(int check_bit)248 bool StorageModule::is_config_checksum_pass(int check_bit) {
249   return (os::ParameterProvider::GetCommonCriteriaConfigCompareResult() & check_bit) == check_bit;
250 }
251 
HasSection(const std::string & section) const252 bool StorageModule::HasSection(const std::string& section) const {
253   std::lock_guard<std::recursive_mutex> lock(mutex_);
254   return pimpl_->cache_.HasSection(section);
255 }
256 
HasProperty(const std::string & section,const std::string & property) const257 bool StorageModule::HasProperty(const std::string& section, const std::string& property) const {
258   std::lock_guard<std::recursive_mutex> lock(mutex_);
259   return pimpl_->cache_.HasProperty(section, property);
260 }
261 
GetProperty(const std::string & section,const std::string & property) const262 std::optional<std::string> StorageModule::GetProperty(const std::string& section,
263                                                       const std::string& property) const {
264   std::lock_guard<std::recursive_mutex> lock(mutex_);
265   return pimpl_->cache_.GetProperty(section, property);
266 }
267 
SetProperty(std::string section,std::string property,std::string value)268 void StorageModule::SetProperty(std::string section, std::string property, std::string value) {
269   std::lock_guard<std::recursive_mutex> lock(mutex_);
270   pimpl_->cache_.SetProperty(section, property, value);
271 }
272 
GetPersistentSections() const273 std::vector<std::string> StorageModule::GetPersistentSections() const {
274   std::lock_guard<std::recursive_mutex> lock(mutex_);
275   return pimpl_->cache_.GetPersistentSections();
276 }
277 
RemoveSection(const std::string & section)278 void StorageModule::RemoveSection(const std::string& section) {
279   std::lock_guard<std::recursive_mutex> lock(mutex_);
280   pimpl_->cache_.RemoveSection(section);
281 }
282 
RemoveProperty(const std::string & section,const std::string & property)283 bool StorageModule::RemoveProperty(const std::string& section, const std::string& property) {
284   std::lock_guard<std::recursive_mutex> lock(mutex_);
285   return pimpl_->cache_.RemoveProperty(section, property);
286 }
287 
ConvertEncryptOrDecryptKeyIfNeeded()288 void StorageModule::ConvertEncryptOrDecryptKeyIfNeeded() {
289   std::lock_guard<std::recursive_mutex> lock(mutex_);
290   pimpl_->cache_.ConvertEncryptOrDecryptKeyIfNeeded();
291 }
292 
RemoveSectionWithProperty(const std::string & property)293 void StorageModule::RemoveSectionWithProperty(const std::string& property) {
294   std::lock_guard<std::recursive_mutex> lock(mutex_);
295   return pimpl_->cache_.RemoveSectionWithProperty(property);
296 }
297 
SetBool(const std::string & section,const std::string & property,bool value)298 void StorageModule::SetBool(const std::string& section, const std::string& property, bool value) {
299   std::lock_guard<std::recursive_mutex> lock(mutex_);
300   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetBool(section, property, value);
301 }
302 
GetBool(const std::string & section,const std::string & property) const303 std::optional<bool> StorageModule::GetBool(const std::string& section,
304                                            const std::string& property) const {
305   std::lock_guard<std::recursive_mutex> lock(mutex_);
306   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetBool(section, property);
307 }
308 
SetUint64(const std::string & section,const std::string & property,uint64_t value)309 void StorageModule::SetUint64(const std::string& section, const std::string& property,
310                               uint64_t value) {
311   std::lock_guard<std::recursive_mutex> lock(mutex_);
312   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetUint64(section, property, value);
313 }
314 
GetUint64(const std::string & section,const std::string & property) const315 std::optional<uint64_t> StorageModule::GetUint64(const std::string& section,
316                                                  const std::string& property) const {
317   std::lock_guard<std::recursive_mutex> lock(mutex_);
318   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetUint64(section, property);
319 }
320 
SetUint32(const std::string & section,const std::string & property,uint32_t value)321 void StorageModule::SetUint32(const std::string& section, const std::string& property,
322                               uint32_t value) {
323   std::lock_guard<std::recursive_mutex> lock(mutex_);
324   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetUint32(section, property, value);
325 }
326 
GetUint32(const std::string & section,const std::string & property) const327 std::optional<uint32_t> StorageModule::GetUint32(const std::string& section,
328                                                  const std::string& property) const {
329   std::lock_guard<std::recursive_mutex> lock(mutex_);
330   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetUint32(section, property);
331 }
SetInt64(const std::string & section,const std::string & property,int64_t value)332 void StorageModule::SetInt64(const std::string& section, const std::string& property,
333                              int64_t value) {
334   std::lock_guard<std::recursive_mutex> lock(mutex_);
335   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetInt64(section, property, value);
336 }
GetInt64(const std::string & section,const std::string & property) const337 std::optional<int64_t> StorageModule::GetInt64(const std::string& section,
338                                                const std::string& property) const {
339   std::lock_guard<std::recursive_mutex> lock(mutex_);
340   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetInt64(section, property);
341 }
342 
SetInt(const std::string & section,const std::string & property,int value)343 void StorageModule::SetInt(const std::string& section, const std::string& property, int value) {
344   std::lock_guard<std::recursive_mutex> lock(mutex_);
345   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetInt(section, property, value);
346 }
347 
GetInt(const std::string & section,const std::string & property) const348 std::optional<int> StorageModule::GetInt(const std::string& section,
349                                          const std::string& property) const {
350   std::lock_guard<std::recursive_mutex> lock(mutex_);
351   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetInt(section, property);
352 }
353 
SetBin(const std::string & section,const std::string & property,const std::vector<uint8_t> & value)354 void StorageModule::SetBin(const std::string& section, const std::string& property,
355                            const std::vector<uint8_t>& value) {
356   std::lock_guard<std::recursive_mutex> lock(mutex_);
357   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetBin(section, property, value);
358 }
359 
GetBin(const std::string & section,const std::string & property) const360 std::optional<std::vector<uint8_t>> StorageModule::GetBin(const std::string& section,
361                                                           const std::string& property) const {
362   std::lock_guard<std::recursive_mutex> lock(mutex_);
363   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetBin(section, property);
364 }
365 
366 }  // namespace storage
367 }  // namespace bluetooth
368