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