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 <chrono>
20 #include <ctime>
21 #include <iomanip>
22 #include <memory>
23 #include <utility>
24
25 #include "common/bind.h"
26 #include "metrics/counter_metrics.h"
27 #include "os/alarm.h"
28 #include "os/files.h"
29 #include "os/handler.h"
30 #include "os/parameter_provider.h"
31 #include "os/system_properties.h"
32 #include "storage/config_cache.h"
33 #include "storage/legacy_config_file.h"
34 #include "storage/mutation.h"
35
36 namespace bluetooth {
37 namespace storage {
38
39 using common::ListMap;
40 using common::LruCache;
41 using os::Alarm;
42 using os::Handler;
43
44 static const std::string kFactoryResetProperty = "persist.bluetooth.factoryreset";
45
46 static const size_t kDefaultTempDeviceCapacity = 10000;
47 // Save config whenever there is a change, but delay it by this value so that burst config change won't overwhelm disk
48 static const std::chrono::milliseconds kDefaultConfigSaveDelay = std::chrono::milliseconds(3000);
49 // Writing a config to disk takes a minimum 10 ms on a decent x86_64 machine, and 20 ms if including backup file
50 // The config saving delay must be bigger than this value to avoid overwhelming the disk
51 static const std::chrono::milliseconds kMinConfigSaveDelay = std::chrono::milliseconds(20);
52
53 const int kConfigFileComparePass = 1;
54 const int kConfigBackupComparePass = 2;
55 const std::string kConfigFilePrefix = "bt_config-origin";
56 const std::string kConfigFileHash = "hash";
57
58 const std::string StorageModule::kInfoSection = "Info";
59 const std::string StorageModule::kFileSourceProperty = "FileSource";
60 const std::string StorageModule::kTimeCreatedProperty = "TimeCreated";
61 const std::string StorageModule::kTimeCreatedFormat = "%Y-%m-%d %H:%M:%S";
62
63 const std::string StorageModule::kAdapterSection = "Adapter";
64
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)65 StorageModule::StorageModule(
66 std::string config_file_path,
67 std::chrono::milliseconds config_save_delay,
68 size_t temp_devices_capacity,
69 bool is_restricted_mode,
70 bool is_single_user_mode)
71 : config_file_path_(std::move(config_file_path)),
72 config_save_delay_(config_save_delay),
73 temp_devices_capacity_(temp_devices_capacity),
74 is_restricted_mode_(is_restricted_mode),
75 is_single_user_mode_(is_single_user_mode) {
76 // e.g. "/data/misc/bluedroid/bt_config.conf" to "/data/misc/bluedroid/bt_config.bak"
77 config_backup_path_ = config_file_path_.substr(0, config_file_path_.find_last_of('.')) + ".bak";
78 ASSERT_LOG(
79 config_save_delay > kMinConfigSaveDelay,
80 "Config save delay of %lld ms is not enough, must be at least %lld ms to avoid overwhelming the disk",
81 config_save_delay_.count(),
82 kMinConfigSaveDelay.count());
83 };
84
~StorageModule()85 StorageModule::~StorageModule() {
86 std::lock_guard<std::recursive_mutex> lock(mutex_);
87 pimpl_.reset();
88 }
89
__anon229bdddf0102() 90 const ModuleFactory StorageModule::Factory = ModuleFactory([]() {
91 return new StorageModule(
92 os::ParameterProvider::ConfigFilePath(), kDefaultConfigSaveDelay, kDefaultTempDeviceCapacity, false, false);
93 });
94
95 struct StorageModule::impl {
implbluetooth::storage::StorageModule::impl96 explicit impl(Handler* handler, ConfigCache cache, size_t in_memory_cache_size_limit)
97 : config_save_alarm_(handler), cache_(std::move(cache)), memory_only_cache_(in_memory_cache_size_limit, {}) {}
98 Alarm config_save_alarm_;
99 ConfigCache cache_;
100 ConfigCache memory_only_cache_;
101 bool has_pending_config_save_ = false;
102 };
103
Modify()104 Mutation StorageModule::Modify() {
105 std::lock_guard<std::recursive_mutex> lock(mutex_);
106 return Mutation(&pimpl_->cache_, &pimpl_->memory_only_cache_);
107 }
108
SaveDelayed()109 void StorageModule::SaveDelayed() {
110 std::lock_guard<std::recursive_mutex> lock(mutex_);
111 if (pimpl_->has_pending_config_save_) {
112 return;
113 }
114 pimpl_->config_save_alarm_.Schedule(
115 common::BindOnce(&StorageModule::SaveImmediately, common::Unretained(this)), 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 // 1. rename old config to backup name
126 if (os::FileExists(config_file_path_)) {
127 ASSERT(os::RenameFile(config_file_path_, config_backup_path_));
128 }
129 // 2. write in-memory config to disk, if failed, backup can still be used
130 ASSERT(LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_));
131 // 3. now write back up to disk as well
132 ASSERT(LegacyConfigFile::FromPath(config_backup_path_).Write(pimpl_->cache_));
133 // 4. save checksum if it is running in common criteria mode
134 if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr &&
135 bluetooth::os::ParameterProvider::IsCommonCriteriaMode()) {
136 bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->set_encrypt_key_or_remove_key(
137 kConfigFilePrefix, kConfigFileHash);
138 }
139 }
140
Clear()141 void StorageModule::Clear() {
142 std::lock_guard<std::recursive_mutex> lock(mutex_);
143 pimpl_->cache_.Clear();
144 }
145
ListDependencies(ModuleList * list) const146 void StorageModule::ListDependencies(ModuleList* list) const {
147 list->add<metrics::CounterMetrics>();
148 }
149
Start()150 void StorageModule::Start() {
151 std::lock_guard<std::recursive_mutex> lock(mutex_);
152 std::string file_source;
153 if (os::GetSystemProperty(kFactoryResetProperty) == "true") {
154 LOG_INFO("%s is true, delete config files", kFactoryResetProperty.c_str());
155 LegacyConfigFile::FromPath(config_file_path_).Delete();
156 LegacyConfigFile::FromPath(config_backup_path_).Delete();
157 os::SetSystemProperty(kFactoryResetProperty, "false");
158 }
159 if (!is_config_checksum_pass(kConfigFileComparePass)) {
160 LegacyConfigFile::FromPath(config_file_path_).Delete();
161 }
162 if (!is_config_checksum_pass(kConfigBackupComparePass)) {
163 LegacyConfigFile::FromPath(config_backup_path_).Delete();
164 }
165 bool save_needed = false;
166 auto config = LegacyConfigFile::FromPath(config_file_path_).Read(temp_devices_capacity_);
167 if (!config || !config->HasSection(kAdapterSection)) {
168 LOG_WARN("cannot load config at %s, using backup at %s.", config_file_path_.c_str(), config_backup_path_.c_str());
169 config = LegacyConfigFile::FromPath(config_backup_path_).Read(temp_devices_capacity_);
170 file_source = "Backup";
171 // Make sure to update the file, since it wasn't read from the config_file_path_
172 save_needed = true;
173 }
174 if (!config || !config->HasSection(kAdapterSection)) {
175 LOG_WARN("cannot load backup config at %s; creating new empty ones", config_backup_path_.c_str());
176 config.emplace(temp_devices_capacity_, Device::kLinkKeyProperties);
177 file_source = "Empty";
178 }
179 if (!file_source.empty()) {
180 config->SetProperty(kInfoSection, kFileSourceProperty, std::move(file_source));
181 }
182 // Cleanup temporary pairings if we have left guest mode
183 if (!is_restricted_mode_) {
184 config->RemoveSectionWithProperty("Restricted");
185 }
186 // Read or set config file creation timestamp
187 auto time_str = config->GetProperty(kInfoSection, kTimeCreatedProperty);
188 if (!time_str) {
189 std::stringstream ss;
190 auto now = std::chrono::system_clock::now();
191 auto now_time_t = std::chrono::system_clock::to_time_t(now);
192 ss << std::put_time(std::localtime(&now_time_t), kTimeCreatedFormat.c_str());
193 config->SetProperty(kInfoSection, kTimeCreatedProperty, ss.str());
194 }
195 config->FixDeviceTypeInconsistencies();
196 // TODO (b/158035889) Migrate metrics module to GD
197 pimpl_ = std::make_unique<impl>(GetHandler(), std::move(config.value()), temp_devices_capacity_);
198 if (save_needed) {
199 // Set a timer and write the new config file to disk.
200 SaveDelayed();
201 }
202 pimpl_->cache_.SetPersistentConfigChangedCallback(
203 [this] { this->CallOn(this, &StorageModule::SaveDelayed); });
204 if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr) {
205 bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->ConvertEncryptOrDecryptKeyIfNeeded();
206 }
207 }
208
Stop()209 void StorageModule::Stop() {
210 std::lock_guard<std::recursive_mutex> lock(mutex_);
211 if (pimpl_->has_pending_config_save_) {
212 // Save pending changes before stopping the module.
213 SaveImmediately();
214 }
215 if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr) {
216 bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->clear_map();
217 }
218 pimpl_.reset();
219 }
220
ToString() const221 std::string StorageModule::ToString() const {
222 return "Storage Module";
223 }
224
GetDeviceByLegacyKey(hci::Address legacy_key_address)225 Device StorageModule::GetDeviceByLegacyKey(hci::Address legacy_key_address) {
226 std::lock_guard<std::recursive_mutex> lock(mutex_);
227 return Device(
228 &pimpl_->cache_,
229 &pimpl_->memory_only_cache_,
230 std::move(legacy_key_address),
231 Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS);
232 }
233
GetDeviceByClassicMacAddress(hci::Address classic_address)234 Device StorageModule::GetDeviceByClassicMacAddress(hci::Address classic_address) {
235 std::lock_guard<std::recursive_mutex> lock(mutex_);
236 return Device(
237 &pimpl_->cache_,
238 &pimpl_->memory_only_cache_,
239 std::move(classic_address),
240 Device::ConfigKeyAddressType::CLASSIC_ADDRESS);
241 }
242
GetDeviceByLeIdentityAddress(hci::Address le_identity_address)243 Device StorageModule::GetDeviceByLeIdentityAddress(hci::Address le_identity_address) {
244 std::lock_guard<std::recursive_mutex> lock(mutex_);
245 return Device(
246 &pimpl_->cache_,
247 &pimpl_->memory_only_cache_,
248 std::move(le_identity_address),
249 Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS);
250 }
251
GetBondedDevices()252 std::vector<Device> StorageModule::GetBondedDevices() {
253 std::lock_guard<std::recursive_mutex> lock(mutex_);
254 auto persistent_sections = pimpl_->cache_.GetPersistentSections();
255 std::vector<Device> result;
256 result.reserve(persistent_sections.size());
257 for (const auto& section : persistent_sections) {
258 result.emplace_back(&pimpl_->cache_, &pimpl_->memory_only_cache_, section);
259 }
260 return result;
261 }
262
is_config_checksum_pass(int check_bit)263 bool StorageModule::is_config_checksum_pass(int check_bit) {
264 return ((os::ParameterProvider::GetCommonCriteriaConfigCompareResult() & check_bit) == check_bit);
265 }
266
HasSection(const std::string & section) const267 bool StorageModule::HasSection(const std::string& section) const {
268 std::lock_guard<std::recursive_mutex> lock(mutex_);
269 return pimpl_->cache_.HasSection(section);
270 }
271
HasProperty(const std::string & section,const std::string & property) const272 bool StorageModule::HasProperty(const std::string& section, const std::string& property) const {
273 std::lock_guard<std::recursive_mutex> lock(mutex_);
274 return pimpl_->cache_.HasProperty(section, property);
275 }
276
GetProperty(const std::string & section,const std::string & property) const277 std::optional<std::string> StorageModule::GetProperty(
278 const std::string& section, const std::string& property) const {
279 std::lock_guard<std::recursive_mutex> lock(mutex_);
280 return pimpl_->cache_.GetProperty(section, property);
281 }
282
SetProperty(std::string section,std::string property,std::string value)283 void StorageModule::SetProperty(std::string section, std::string property, std::string value) {
284 std::lock_guard<std::recursive_mutex> lock(mutex_);
285 pimpl_->cache_.SetProperty(section, property, value);
286 }
287
GetPersistentSections() const288 std::vector<std::string> StorageModule::GetPersistentSections() const {
289 std::lock_guard<std::recursive_mutex> lock(mutex_);
290 return pimpl_->cache_.GetPersistentSections();
291 }
292
RemoveSection(const std::string & section)293 void StorageModule::RemoveSection(const std::string& section) {
294 std::lock_guard<std::recursive_mutex> lock(mutex_);
295 pimpl_->cache_.RemoveSection(section);
296 }
297
RemoveProperty(const std::string & section,const std::string & property)298 bool StorageModule::RemoveProperty(const std::string& section, const std::string& property) {
299 std::lock_guard<std::recursive_mutex> lock(mutex_);
300 return pimpl_->cache_.RemoveProperty(section, property);
301 }
302
ConvertEncryptOrDecryptKeyIfNeeded()303 void StorageModule::ConvertEncryptOrDecryptKeyIfNeeded() {
304 std::lock_guard<std::recursive_mutex> lock(mutex_);
305 pimpl_->cache_.ConvertEncryptOrDecryptKeyIfNeeded();
306 }
307
RemoveSectionWithProperty(const std::string & property)308 void StorageModule::RemoveSectionWithProperty(const std::string& property) {
309 std::lock_guard<std::recursive_mutex> lock(mutex_);
310 return pimpl_->cache_.RemoveSectionWithProperty(property);
311 }
312
SetBool(const std::string & section,const std::string & property,bool value)313 void StorageModule::SetBool(const std::string& section, const std::string& property, bool value) {
314 std::lock_guard<std::recursive_mutex> lock(mutex_);
315 ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetBool(section, property, value);
316 }
317
GetBool(const std::string & section,const std::string & property) const318 std::optional<bool> StorageModule::GetBool(
319 const std::string& section, const std::string& property) const {
320 std::lock_guard<std::recursive_mutex> lock(mutex_);
321 return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetBool(section, property);
322 }
323
SetUint64(const std::string & section,const std::string & property,uint64_t value)324 void StorageModule::SetUint64(
325 const std::string& section, const std::string& property, uint64_t value) {
326 std::lock_guard<std::recursive_mutex> lock(mutex_);
327 ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetUint64(section, property, value);
328 }
329
GetUint64(const std::string & section,const std::string & property) const330 std::optional<uint64_t> StorageModule::GetUint64(
331 const std::string& section, const std::string& property) const {
332 std::lock_guard<std::recursive_mutex> lock(mutex_);
333 return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetUint64(section, property);
334 }
335
SetUint32(const std::string & section,const std::string & property,uint32_t value)336 void StorageModule::SetUint32(
337 const std::string& section, const std::string& property, uint32_t value) {
338 std::lock_guard<std::recursive_mutex> lock(mutex_);
339 ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetUint32(section, property, value);
340 }
341
GetUint32(const std::string & section,const std::string & property) const342 std::optional<uint32_t> StorageModule::GetUint32(
343 const std::string& section, const std::string& property) const {
344 std::lock_guard<std::recursive_mutex> lock(mutex_);
345 return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetUint32(section, property);
346 }
SetInt64(const std::string & section,const std::string & property,int64_t value)347 void StorageModule::SetInt64(
348 const std::string& section, const std::string& property, int64_t value) {
349 std::lock_guard<std::recursive_mutex> lock(mutex_);
350 ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetInt64(section, property, value);
351 }
GetInt64(const std::string & section,const std::string & property) const352 std::optional<int64_t> StorageModule::GetInt64(
353 const std::string& section, const std::string& property) const {
354 std::lock_guard<std::recursive_mutex> lock(mutex_);
355 return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetInt64(section, property);
356 }
357
SetInt(const std::string & section,const std::string & property,int value)358 void StorageModule::SetInt(const std::string& section, const std::string& property, int value) {
359 std::lock_guard<std::recursive_mutex> lock(mutex_);
360 ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetInt(section, property, value);
361 }
362
GetInt(const std::string & section,const std::string & property) const363 std::optional<int> StorageModule::GetInt(
364 const std::string& section, const std::string& property) const {
365 std::lock_guard<std::recursive_mutex> lock(mutex_);
366 return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetInt(section, property);
367 }
368
SetBin(const std::string & section,const std::string & property,const std::vector<uint8_t> & value)369 void StorageModule::SetBin(
370 const std::string& section, const std::string& property, const std::vector<uint8_t>& value) {
371 std::lock_guard<std::recursive_mutex> lock(mutex_);
372 ConfigCacheHelper::FromConfigCache(pimpl_->cache_).SetBin(section, property, value);
373 }
374
GetBin(const std::string & section,const std::string & property) const375 std::optional<std::vector<uint8_t>> StorageModule::GetBin(
376 const std::string& section, const std::string& property) const {
377 std::lock_guard<std::recursive_mutex> lock(mutex_);
378 return ConfigCacheHelper::FromConfigCache(pimpl_->cache_).GetBin(section, property);
379 }
380
381 } // namespace storage
382 } // namespace bluetooth
383