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 "os/alarm.h"
27 #include "os/files.h"
28 #include "os/handler.h"
29 #include "os/parameter_provider.h"
30 #include "os/system_properties.h"
31 #include "storage/config_cache.h"
32 #include "storage/legacy_config_file.h"
33 #include "storage/mutation.h"
34 
35 namespace bluetooth {
36 namespace storage {
37 
38 using common::ListMap;
39 using common::LruCache;
40 using os::Alarm;
41 using os::Handler;
42 
43 static const std::string kFactoryResetProperty = "persist.bluetooth.factoryreset";
44 
45 static const size_t kDefaultTempDeviceCapacity = 10000;
46 // Save config whenever there is a change, but delay it by this value so that burst config change won't overwhelm disk
47 static const std::chrono::milliseconds kDefaultConfigSaveDelay = std::chrono::milliseconds(3000);
48 // Writing a config to disk takes a minimum 10 ms on a decent x86_64 machine, and 20 ms if including backup file
49 // The config saving delay must be bigger than this value to avoid overwhelming the disk
50 static const std::chrono::milliseconds kMinConfigSaveDelay = std::chrono::milliseconds(20);
51 
52 const std::string StorageModule::kInfoSection = "Info";
53 const std::string StorageModule::kFileSourceProperty = "FileSource";
54 const std::string StorageModule::kTimeCreatedProperty = "TimeCreated";
55 const std::string StorageModule::kTimeCreatedFormat = "%Y-%m-%d %H:%M:%S";
56 
57 const std::string StorageModule::kAdapterSection = "Adapter";
58 
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)59 StorageModule::StorageModule(
60     std::string config_file_path,
61     std::chrono::milliseconds config_save_delay,
62     size_t temp_devices_capacity,
63     bool is_restricted_mode,
64     bool is_single_user_mode)
65     : config_file_path_(std::move(config_file_path)),
66       config_save_delay_(config_save_delay),
67       temp_devices_capacity_(temp_devices_capacity),
68       is_restricted_mode_(is_restricted_mode),
69       is_single_user_mode_(is_single_user_mode) {
70   // e.g. "/data/misc/bluedroid/bt_config.conf" to "/data/misc/bluedroid/bt_config.bak"
71   config_backup_path_ = config_file_path_.substr(0, config_file_path_.find_last_of('.')) + ".bak";
72   ASSERT_LOG(
73       config_save_delay > kMinConfigSaveDelay,
74       "Config save delay of %lld ms is not enough, must be at least %lld ms to avoid overwhelming the disk",
75       config_save_delay_.count(),
76       kMinConfigSaveDelay.count());
77 };
78 
~StorageModule()79 StorageModule::~StorageModule() {
80   std::lock_guard<std::recursive_mutex> lock(mutex_);
81   pimpl_.reset();
82 }
83 
__anonce50ba040102() 84 const ModuleFactory StorageModule::Factory = ModuleFactory([]() {
85   return new StorageModule(
86       os::ParameterProvider::ConfigFilePath(), kDefaultConfigSaveDelay, kDefaultTempDeviceCapacity, false, false);
87 });
88 
89 struct StorageModule::impl {
implbluetooth::storage::StorageModule::impl90   explicit impl(Handler* handler, ConfigCache cache, size_t in_memory_cache_size_limit)
91       : config_save_alarm_(handler), cache_(std::move(cache)), memory_only_cache_(in_memory_cache_size_limit, {}) {}
92   Alarm config_save_alarm_;
93   ConfigCache cache_;
94   ConfigCache memory_only_cache_;
95   bool has_pending_config_save_ = false;
96 };
97 
Modify()98 Mutation StorageModule::Modify() {
99   std::lock_guard<std::recursive_mutex> lock(mutex_);
100   return Mutation(&pimpl_->cache_, &pimpl_->memory_only_cache_);
101 }
102 
GetConfigCache()103 ConfigCache* StorageModule::GetConfigCache() {
104   std::lock_guard<std::recursive_mutex> lock(mutex_);
105   return &pimpl_->cache_;
106 }
107 
GetMemoryOnlyConfigCache()108 ConfigCache* StorageModule::GetMemoryOnlyConfigCache() {
109   std::lock_guard<std::recursive_mutex> lock(mutex_);
110   return &pimpl_->memory_only_cache_;
111 }
112 
SaveDelayed()113 void StorageModule::SaveDelayed() {
114   std::lock_guard<std::recursive_mutex> lock(mutex_);
115   if (pimpl_->has_pending_config_save_) {
116     return;
117   }
118   pimpl_->config_save_alarm_.Schedule(
119       common::BindOnce(&StorageModule::SaveImmediately, common::Unretained(this)), config_save_delay_);
120   pimpl_->has_pending_config_save_ = true;
121 }
122 
SaveImmediately()123 void StorageModule::SaveImmediately() {
124   std::lock_guard<std::recursive_mutex> lock(mutex_);
125   if (pimpl_->has_pending_config_save_) {
126     pimpl_->config_save_alarm_.Cancel();
127     pimpl_->has_pending_config_save_ = false;
128   }
129   // 1. rename old config to backup name
130   if (os::FileExists(config_file_path_)) {
131     ASSERT(os::RenameFile(config_file_path_, config_backup_path_));
132   }
133   // 2. write in-memory config to disk, if failed, backup can still be used
134   ASSERT(LegacyConfigFile::FromPath(config_file_path_).Write(pimpl_->cache_));
135   // 3. now write back up to disk as well
136   ASSERT(LegacyConfigFile::FromPath(config_backup_path_).Write(pimpl_->cache_));
137 }
138 
ListDependencies(ModuleList * list)139 void StorageModule::ListDependencies(ModuleList* list) {
140   // No dependencies
141 }
142 
Start()143 void StorageModule::Start() {
144   std::lock_guard<std::recursive_mutex> lock(mutex_);
145   std::string file_source;
146   if (os::GetSystemProperty(kFactoryResetProperty) == "true") {
147     LegacyConfigFile::FromPath(config_file_path_).Delete();
148     LegacyConfigFile::FromPath(config_backup_path_).Delete();
149   }
150   auto config = LegacyConfigFile::FromPath(config_file_path_).Read(temp_devices_capacity_);
151   if (!config || !config->HasSection(kAdapterSection)) {
152     LOG_WARN("cannot load config at %s, using backup at %s.", config_file_path_.c_str(), config_backup_path_.c_str());
153     config = LegacyConfigFile::FromPath(config_backup_path_).Read(temp_devices_capacity_);
154     file_source = "Backup";
155   }
156   if (!config || !config->HasSection(kAdapterSection)) {
157     LOG_WARN("cannot load backup config at %s; creating new empty ones", config_backup_path_.c_str());
158     config.emplace(temp_devices_capacity_, Device::kLinkKeyProperties);
159     file_source = "Empty";
160   }
161   if (!file_source.empty()) {
162     config->SetProperty(kInfoSection, kFileSourceProperty, std::move(file_source));
163   }
164   // Cleanup temporary pairings if we have left guest mode
165   if (!is_restricted_mode_) {
166     config->RemoveSectionWithProperty("Restricted");
167   }
168   // Read or set config file creation timestamp
169   auto time_str = config->GetProperty(kInfoSection, kTimeCreatedProperty);
170   if (!time_str) {
171     std::stringstream ss;
172     auto now = std::chrono::system_clock::now();
173     auto now_time_t = std::chrono::system_clock::to_time_t(now);
174     ss << std::put_time(std::localtime(&now_time_t), kTimeCreatedFormat.c_str());
175     config->SetProperty(kInfoSection, kTimeCreatedProperty, ss.str());
176   }
177   config->FixDeviceTypeInconsistencies();
178   config->SetPersistentConfigChangedCallback([this] { this->SaveDelayed(); });
179   // TODO (b/158035889) Migrate metrics module to GD
180   pimpl_ = std::make_unique<impl>(GetHandler(), std::move(config.value()), temp_devices_capacity_);
181   SaveDelayed();
182 }
183 
Stop()184 void StorageModule::Stop() {
185   std::lock_guard<std::recursive_mutex> lock(mutex_);
186   SaveImmediately();
187   pimpl_.reset();
188 }
189 
ToString() const190 std::string StorageModule::ToString() const {
191   return "Storage Module";
192 }
193 
GetDeviceByLegacyKey(hci::Address legacy_key_address)194 Device StorageModule::GetDeviceByLegacyKey(hci::Address legacy_key_address) {
195   std::lock_guard<std::recursive_mutex> lock(mutex_);
196   return Device(
197       &pimpl_->cache_,
198       &pimpl_->memory_only_cache_,
199       std::move(legacy_key_address),
200       Device::ConfigKeyAddressType::LEGACY_KEY_ADDRESS);
201 }
202 
GetDeviceByClassicMacAddress(hci::Address classic_address)203 Device StorageModule::GetDeviceByClassicMacAddress(hci::Address classic_address) {
204   std::lock_guard<std::recursive_mutex> lock(mutex_);
205   return Device(
206       &pimpl_->cache_,
207       &pimpl_->memory_only_cache_,
208       std::move(classic_address),
209       Device::ConfigKeyAddressType::CLASSIC_ADDRESS);
210 }
211 
GetDeviceByLeIdentityAddress(hci::Address le_identity_address)212 Device StorageModule::GetDeviceByLeIdentityAddress(hci::Address le_identity_address) {
213   std::lock_guard<std::recursive_mutex> lock(mutex_);
214   return Device(
215       &pimpl_->cache_,
216       &pimpl_->memory_only_cache_,
217       std::move(le_identity_address),
218       Device::ConfigKeyAddressType::LE_IDENTITY_ADDRESS);
219 }
220 
GetAdapterConfig()221 AdapterConfig StorageModule::GetAdapterConfig() {
222   std::lock_guard<std::recursive_mutex> lock(mutex_);
223   return AdapterConfig(&pimpl_->cache_, &pimpl_->memory_only_cache_, kAdapterSection);
224 }
225 
GetBondedDevices()226 std::vector<Device> StorageModule::GetBondedDevices() {
227   std::lock_guard<std::recursive_mutex> lock(mutex_);
228   auto persistent_sections = GetConfigCache()->GetPersistentSections();
229   std::vector<Device> result;
230   result.reserve(persistent_sections.size());
231   for (const auto& section : persistent_sections) {
232     result.emplace_back(&pimpl_->cache_, &pimpl_->memory_only_cache_, section);
233   }
234   return result;
235 }
236 
237 }  // namespace storage
238 }  // namespace bluetooth