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 #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(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)66 StorageModule::StorageModule(std::string config_file_path,
67                              std::chrono::milliseconds config_save_delay,
68                              size_t temp_devices_capacity, 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(config_save_delay > kMinConfigSaveDelay,
76                    "Config save delay of {} ms is not enough, must be at least {} ms to avoid "
77                    "overwhelming the "
78                    "disk",
79                    config_save_delay_.count(), kMinConfigSaveDelay.count());
80 }
81 
~StorageModule()82 StorageModule::~StorageModule() {
83   std::lock_guard<std::recursive_mutex> lock(mutex_);
84   pimpl_.reset();
85 }
86 
__anon66d68e500102() 87 const ModuleFactory StorageModule::Factory = ModuleFactory([]() {
88   return new StorageModule(os::ParameterProvider::ConfigFilePath(), kDefaultConfigSaveDelay,
89                            kDefaultTempDeviceCapacity, false, false);
90 });
91 
92 struct StorageModule::impl {
implbluetooth::storage::StorageModule::impl93   explicit impl(Handler* handler, ConfigCache cache, size_t in_memory_cache_size_limit)
94       : config_save_alarm_(handler),
95         cache_(std::move(cache)),
96         memory_only_cache_(in_memory_cache_size_limit, {}) {}
97   Alarm config_save_alarm_;
98   ConfigCache cache_;
99   ConfigCache memory_only_cache_;
100   bool has_pending_config_save_ = false;
101 };
102 
Modify()103 Mutation StorageModule::Modify() {
104   std::lock_guard<std::recursive_mutex> lock(mutex_);
105   return Mutation(&pimpl_->cache_, &pimpl_->memory_only_cache_);
106 }
107 
SaveDelayed()108 void StorageModule::SaveDelayed() {
109   std::lock_guard<std::recursive_mutex> lock(mutex_);
110   if (pimpl_->has_pending_config_save_) {
111     return;
112   }
113   pimpl_->config_save_alarm_.Schedule(
114           common::BindOnce(&StorageModule::SaveImmediately, common::Unretained(this)),
115           config_save_delay_);
116   pimpl_->has_pending_config_save_ = true;
117 }
118 
SaveImmediately()119 void StorageModule::SaveImmediately() {
120   std::lock_guard<std::recursive_mutex> lock(mutex_);
121   if (pimpl_->has_pending_config_save_) {
122     pimpl_->config_save_alarm_.Cancel();
123     pimpl_->has_pending_config_save_ = false;
124   }
125 #ifndef TARGET_FLOSS
126   log::assert_that(
127           LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_),
128           "assert failed: LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_)");
129 #else
130   if (!LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_)) {
131     log::error("Unable to write config file to disk");
132   }
133 #endif
134   // save checksum if it is running in common criteria mode
135   if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr &&
136       bluetooth::os::ParameterProvider::IsCommonCriteriaMode()) {
137     bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->set_encrypt_key_or_remove_key(
138             kConfigFilePrefix, kConfigFileHash);
139   }
140 }
141 
Clear()142 void StorageModule::Clear() {
143   std::lock_guard<std::recursive_mutex> lock(mutex_);
144   pimpl_->cache_.Clear();
145 }
146 
ListDependencies(ModuleList * list) const147 void StorageModule::ListDependencies(ModuleList* list) const {
148   list->add<metrics::CounterMetrics>();
149 }
150 
Start()151 void StorageModule::Start() {
152   std::lock_guard<std::recursive_mutex> lock(mutex_);
153   if (os::GetSystemProperty(kFactoryResetProperty) == "true") {
154     log::info("{} is true, delete config files", kFactoryResetProperty);
155     LegacyConfigFile::FromPath(config_file_path_).Delete();
156     os::SetSystemProperty(kFactoryResetProperty, "false");
157   }
158   if (!is_config_checksum_pass(kConfigFileComparePass)) {
159     LegacyConfigFile::FromPath(config_file_path_).Delete();
160   }
161   auto config = LegacyConfigFile::FromPath(config_file_path_).Read(temp_devices_capacity_);
162   bool save_needed = false;
163   if (!config || !config->HasSection(kAdapterSection)) {
164     log::warn("Failed to load config at {}; creating new empty ones", config_file_path_);
165     config.emplace(temp_devices_capacity_, Device::kLinkKeyProperties);
166 
167     // Set config file creation timestamp
168     std::stringstream ss;
169     auto now = std::chrono::system_clock::now();
170     auto now_time_t = std::chrono::system_clock::to_time_t(now);
171     ss << std::put_time(std::localtime(&now_time_t), kTimeCreatedFormat.c_str());
172     config->SetProperty(kInfoSection, kTimeCreatedProperty, ss.str());
173     save_needed = true;
174   }
175   pimpl_ = std::make_unique<impl>(GetHandler(), std::move(config.value()), temp_devices_capacity_);
176   pimpl_->cache_.SetPersistentConfigChangedCallback(
177           [this] { this->CallOn(this, &StorageModule::SaveDelayed); });
178 
179   // Cleanup temporary pairings if we have left guest mode
180   if (!com::android::bluetooth::flags::guest_mode_bond() && !is_restricted_mode_) {
181     pimpl_->cache_.RemoveSectionWithProperty("Restricted");
182   }
183 
184   pimpl_->cache_.FixDeviceTypeInconsistencies();
185   if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr) {
186     bluetooth::os::ParameterProvider::GetBtKeystoreInterface()
187             ->ConvertEncryptOrDecryptKeyIfNeeded();
188   }
189 
190   if (save_needed) {
191     SaveDelayed();
192   }
193 }
194 
Stop()195 void StorageModule::Stop() {
196   std::lock_guard<std::recursive_mutex> lock(mutex_);
197   if (pimpl_->has_pending_config_save_) {
198     // Save pending changes before stopping the module.
199     SaveImmediately();
200   }
201   if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr) {
202     bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->clear_map();
203   }
204   pimpl_.reset();
205 }
206 
ToString() const207 std::string StorageModule::ToString() const { return "Storage Module"; }
208 
GetDeviceByLegacyKey(hci::Address legacy_key_address)209 Device StorageModule::GetDeviceByLegacyKey(hci::Address legacy_key_address) {
210   std::lock_guard<std::recursive_mutex> lock(mutex_);
211   return Device(&pimpl_->cache_, &pimpl_->memory_only_cache_, std::move(legacy_key_address),
212                 Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS);
213 }
214 
GetDeviceByClassicMacAddress(hci::Address classic_address)215 Device StorageModule::GetDeviceByClassicMacAddress(hci::Address classic_address) {
216   std::lock_guard<std::recursive_mutex> lock(mutex_);
217   return Device(&pimpl_->cache_, &pimpl_->memory_only_cache_, std::move(classic_address),
218                 Device::ConfigKeyAddressType::CLASSIC_ADDRESS);
219 }
220 
GetDeviceByLeIdentityAddress(hci::Address le_identity_address)221 Device StorageModule::GetDeviceByLeIdentityAddress(hci::Address le_identity_address) {
222   std::lock_guard<std::recursive_mutex> lock(mutex_);
223   return Device(&pimpl_->cache_, &pimpl_->memory_only_cache_, std::move(le_identity_address),
224                 Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS);
225 }
226 
GetBondedDevices()227 std::vector<Device> StorageModule::GetBondedDevices() {
228   std::lock_guard<std::recursive_mutex> lock(mutex_);
229   auto persistent_sections = pimpl_->cache_.GetPersistentSections();
230   std::vector<Device> result;
231   result.reserve(persistent_sections.size());
232   for (const auto& section : persistent_sections) {
233     result.emplace_back(&pimpl_->cache_, &pimpl_->memory_only_cache_, section);
234   }
235   return result;
236 }
237 
is_config_checksum_pass(int check_bit)238 bool StorageModule::is_config_checksum_pass(int check_bit) {
239   return (os::ParameterProvider::GetCommonCriteriaConfigCompareResult() & check_bit) == check_bit;
240 }
241 
HasSection(const std::string & section) const242 bool StorageModule::HasSection(const std::string& section) const {
243   std::lock_guard<std::recursive_mutex> lock(mutex_);
244   return pimpl_->cache_.HasSection(section);
245 }
246 
HasProperty(const std::string & section,const std::string & property) const247 bool StorageModule::HasProperty(const std::string& section, const std::string& property) const {
248   std::lock_guard<std::recursive_mutex> lock(mutex_);
249   return pimpl_->cache_.HasProperty(section, property);
250 }
251 
GetProperty(const std::string & section,const std::string & property) const252 std::optional<std::string> StorageModule::GetProperty(const std::string& section,
253                                                       const std::string& property) const {
254   std::lock_guard<std::recursive_mutex> lock(mutex_);
255   return pimpl_->cache_.GetProperty(section, property);
256 }
257 
SetProperty(std::string section,std::string property,std::string value)258 void StorageModule::SetProperty(std::string section, std::string property, std::string value) {
259   std::lock_guard<std::recursive_mutex> lock(mutex_);
260   pimpl_->cache_.SetProperty(section, property, value);
261 }
262 
GetPersistentSections() const263 std::vector<std::string> StorageModule::GetPersistentSections() const {
264   std::lock_guard<std::recursive_mutex> lock(mutex_);
265   return pimpl_->cache_.GetPersistentSections();
266 }
267 
RemoveSection(const std::string & section)268 void StorageModule::RemoveSection(const std::string& section) {
269   std::lock_guard<std::recursive_mutex> lock(mutex_);
270   pimpl_->cache_.RemoveSection(section);
271 }
272 
RemoveProperty(const std::string & section,const std::string & property)273 bool StorageModule::RemoveProperty(const std::string& section, const std::string& property) {
274   std::lock_guard<std::recursive_mutex> lock(mutex_);
275   return pimpl_->cache_.RemoveProperty(section, property);
276 }
277 
ConvertEncryptOrDecryptKeyIfNeeded()278 void StorageModule::ConvertEncryptOrDecryptKeyIfNeeded() {
279   std::lock_guard<std::recursive_mutex> lock(mutex_);
280   pimpl_->cache_.ConvertEncryptOrDecryptKeyIfNeeded();
281 }
282 
RemoveSectionWithProperty(const std::string & property)283 void StorageModule::RemoveSectionWithProperty(const std::string& property) {
284   std::lock_guard<std::recursive_mutex> lock(mutex_);
285   return pimpl_->cache_.RemoveSectionWithProperty(property);
286 }
287 
SetBool(const std::string & section,const std::string & property,bool value)288 void StorageModule::SetBool(const std::string& section, const std::string& property, bool value) {
289   std::lock_guard<std::recursive_mutex> lock(mutex_);
290   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetBool(section, property, value);
291 }
292 
GetBool(const std::string & section,const std::string & property) const293 std::optional<bool> StorageModule::GetBool(const std::string& section,
294                                            const std::string& property) const {
295   std::lock_guard<std::recursive_mutex> lock(mutex_);
296   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetBool(section, property);
297 }
298 
SetUint64(const std::string & section,const std::string & property,uint64_t value)299 void StorageModule::SetUint64(const std::string& section, const std::string& property,
300                               uint64_t value) {
301   std::lock_guard<std::recursive_mutex> lock(mutex_);
302   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetUint64(section, property, value);
303 }
304 
GetUint64(const std::string & section,const std::string & property) const305 std::optional<uint64_t> StorageModule::GetUint64(const std::string& section,
306                                                  const std::string& property) const {
307   std::lock_guard<std::recursive_mutex> lock(mutex_);
308   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetUint64(section, property);
309 }
310 
SetUint32(const std::string & section,const std::string & property,uint32_t value)311 void StorageModule::SetUint32(const std::string& section, const std::string& property,
312                               uint32_t value) {
313   std::lock_guard<std::recursive_mutex> lock(mutex_);
314   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetUint32(section, property, value);
315 }
316 
GetUint32(const std::string & section,const std::string & property) const317 std::optional<uint32_t> StorageModule::GetUint32(const std::string& section,
318                                                  const std::string& property) const {
319   std::lock_guard<std::recursive_mutex> lock(mutex_);
320   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetUint32(section, property);
321 }
SetInt64(const std::string & section,const std::string & property,int64_t value)322 void StorageModule::SetInt64(const std::string& section, const std::string& property,
323                              int64_t value) {
324   std::lock_guard<std::recursive_mutex> lock(mutex_);
325   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetInt64(section, property, value);
326 }
GetInt64(const std::string & section,const std::string & property) const327 std::optional<int64_t> StorageModule::GetInt64(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_).GetInt64(section, property);
331 }
332 
SetInt(const std::string & section,const std::string & property,int value)333 void StorageModule::SetInt(const std::string& section, const std::string& property, int value) {
334   std::lock_guard<std::recursive_mutex> lock(mutex_);
335   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetInt(section, property, value);
336 }
337 
GetInt(const std::string & section,const std::string & property) const338 std::optional<int> StorageModule::GetInt(const std::string& section,
339                                          const std::string& property) const {
340   std::lock_guard<std::recursive_mutex> lock(mutex_);
341   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetInt(section, property);
342 }
343 
SetBin(const std::string & section,const std::string & property,const std::vector<uint8_t> & value)344 void StorageModule::SetBin(const std::string& section, const std::string& property,
345                            const std::vector<uint8_t>& value) {
346   std::lock_guard<std::recursive_mutex> lock(mutex_);
347   ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetBin(section, property, value);
348 }
349 
GetBin(const std::string & section,const std::string & property) const350 std::optional<std::vector<uint8_t>> StorageModule::GetBin(const std::string& section,
351                                                           const std::string& property) const {
352   std::lock_guard<std::recursive_mutex> lock(mutex_);
353   return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetBin(section, property);
354 }
355 
356 }  // namespace storage
357 }  // namespace bluetooth
358