• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
__anon061cc8c60102() 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 
GetConfigCache()109 ConfigCache* StorageModule::GetConfigCache() {
110   std::lock_guard<std::recursive_mutex> lock(mutex_);
111   return &pimpl_->cache_;
112 }
113 
GetMemoryOnlyConfigCache()114 ConfigCache* StorageModule::GetMemoryOnlyConfigCache() {
115   std::lock_guard<std::recursive_mutex> lock(mutex_);
116   return &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)), config_save_delay_);
126   pimpl_->has_pending_config_save_ = true;
127 }
128 
SaveImmediately()129 void StorageModule::SaveImmediately() {
130   std::lock_guard<std::recursive_mutex> lock(mutex_);
131   if (pimpl_->has_pending_config_save_) {
132     pimpl_->config_save_alarm_.Cancel();
133     pimpl_->has_pending_config_save_ = false;
134   }
135   // 1. rename old config to backup name
136   if (os::FileExists(config_file_path_)) {
137     ASSERT(os::RenameFile(config_file_path_, config_backup_path_));
138   }
139   // 2. write in-memory config to disk, if failed, backup can still be used
140   ASSERT(LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_));
141   // 3. now write back up to disk as well
142   ASSERT(LegacyConfigFile::FromPath(config_backup_path_).Write(pimpl_->cache_));
143   // 4. save checksum if it is running in common criteria mode
144   if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr &&
145       bluetooth::os::ParameterProvider::IsCommonCriteriaMode()) {
146     bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->set_encrypt_key_or_remove_key(
147         kConfigFilePrefix, kConfigFileHash);
148   }
149 }
150 
ListDependencies(ModuleList * list) const151 void StorageModule::ListDependencies(ModuleList* list) const {
152     list->add<metrics::CounterMetrics>();
153 }
154 
Start()155 void StorageModule::Start() {
156   std::lock_guard<std::recursive_mutex> lock(mutex_);
157   std::string file_source;
158   if (os::GetSystemProperty(kFactoryResetProperty) == "true") {
159     LOG_INFO("%s is true, delete config files", kFactoryResetProperty.c_str());
160     LegacyConfigFile::FromPath(config_file_path_).Delete();
161     LegacyConfigFile::FromPath(config_backup_path_).Delete();
162     os::SetSystemProperty(kFactoryResetProperty, "false");
163   }
164   if (!is_config_checksum_pass(kConfigFileComparePass)) {
165     LegacyConfigFile::FromPath(config_file_path_).Delete();
166   }
167   if (!is_config_checksum_pass(kConfigBackupComparePass)) {
168     LegacyConfigFile::FromPath(config_backup_path_).Delete();
169   }
170   auto config = LegacyConfigFile::FromPath(config_file_path_).Read(temp_devices_capacity_);
171   if (!config || !config->HasSection(kAdapterSection)) {
172     LOG_WARN("cannot load config at %s, using backup at %s.", config_file_path_.c_str(), config_backup_path_.c_str());
173     config = LegacyConfigFile::FromPath(config_backup_path_).Read(temp_devices_capacity_);
174     file_source = "Backup";
175   }
176   if (!config || !config->HasSection(kAdapterSection)) {
177     LOG_WARN("cannot load backup config at %s; creating new empty ones", config_backup_path_.c_str());
178     config.emplace(temp_devices_capacity_, Device::kLinkKeyProperties);
179     file_source = "Empty";
180   }
181   if (!file_source.empty()) {
182     config->SetProperty(kInfoSection, kFileSourceProperty, std::move(file_source));
183   }
184   // Cleanup temporary pairings if we have left guest mode
185   if (!is_restricted_mode_) {
186     config->RemoveSectionWithProperty("Restricted");
187   }
188   // Read or set config file creation timestamp
189   auto time_str = config->GetProperty(kInfoSection, kTimeCreatedProperty);
190   if (!time_str) {
191     std::stringstream ss;
192     auto now = std::chrono::system_clock::now();
193     auto now_time_t = std::chrono::system_clock::to_time_t(now);
194     ss << std::put_time(std::localtime(&now_time_t), kTimeCreatedFormat.c_str());
195     config->SetProperty(kInfoSection, kTimeCreatedProperty, ss.str());
196   }
197   config->FixDeviceTypeInconsistencies();
198   config->SetPersistentConfigChangedCallback([this] { this->CallOn(this, &StorageModule::SaveDelayed); });
199   // TODO (b/158035889) Migrate metrics module to GD
200   pimpl_ = std::make_unique<impl>(GetHandler(), std::move(config.value()), temp_devices_capacity_);
201   SaveDelayed();
202   if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr) {
203     bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->ConvertEncryptOrDecryptKeyIfNeeded();
204   }
205 }
206 
Stop()207 void StorageModule::Stop() {
208   std::lock_guard<std::recursive_mutex> lock(mutex_);
209   SaveImmediately();
210   if (bluetooth::os::ParameterProvider::GetBtKeystoreInterface() != nullptr) {
211     bluetooth::os::ParameterProvider::GetBtKeystoreInterface()->clear_map();
212   }
213   pimpl_.reset();
214 }
215 
ToString() const216 std::string StorageModule::ToString() const {
217   return "Storage Module";
218 }
219 
GetDeviceByLegacyKey(hci::Address legacy_key_address)220 Device StorageModule::GetDeviceByLegacyKey(hci::Address legacy_key_address) {
221   std::lock_guard<std::recursive_mutex> lock(mutex_);
222   return Device(
223       &pimpl_->cache_,
224       &pimpl_->memory_only_cache_,
225       std::move(legacy_key_address),
226       Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS);
227 }
228 
GetDeviceByClassicMacAddress(hci::Address classic_address)229 Device StorageModule::GetDeviceByClassicMacAddress(hci::Address classic_address) {
230   std::lock_guard<std::recursive_mutex> lock(mutex_);
231   return Device(
232       &pimpl_->cache_,
233       &pimpl_->memory_only_cache_,
234       std::move(classic_address),
235       Device::ConfigKeyAddressType::CLASSIC_ADDRESS);
236 }
237 
GetDeviceByLeIdentityAddress(hci::Address le_identity_address)238 Device StorageModule::GetDeviceByLeIdentityAddress(hci::Address le_identity_address) {
239   std::lock_guard<std::recursive_mutex> lock(mutex_);
240   return Device(
241       &pimpl_->cache_,
242       &pimpl_->memory_only_cache_,
243       std::move(le_identity_address),
244       Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS);
245 }
246 
GetAdapterConfig()247 AdapterConfig StorageModule::GetAdapterConfig() {
248   std::lock_guard<std::recursive_mutex> lock(mutex_);
249   return AdapterConfig(&pimpl_->cache_, &pimpl_->memory_only_cache_, kAdapterSection);
250 }
251 
GetBondedDevices()252 std::vector<Device> StorageModule::GetBondedDevices() {
253   std::lock_guard<std::recursive_mutex> lock(mutex_);
254   auto persistent_sections = GetConfigCache()->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 
267 }  // namespace storage
268 }  // namespace bluetooth
269