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/legacy_config_file.h"
18
19 #include <cerrno>
20 #include <fstream>
21 #include <sstream>
22
23 #include "common/strings.h"
24 #include "os/files.h"
25 #include "os/log.h"
26 #include "storage/device.h"
27
28 namespace bluetooth {
29 namespace storage {
30
LegacyConfigFile(std::string path)31 LegacyConfigFile::LegacyConfigFile(std::string path) : path_(std::move(path)) {
32 ASSERT(!path_.empty());
33 };
34
Read(size_t temp_devices_capacity)35 std::optional<ConfigCache> LegacyConfigFile::Read(size_t temp_devices_capacity) {
36 ASSERT(!path_.empty());
37 std::ifstream config_file(path_);
38 if (!config_file || !config_file.is_open()) {
39 LOG_ERROR("unable to open file '%s', error: %s", path_.c_str(), strerror(errno));
40 return std::nullopt;
41 }
42 int line_num = 0;
43 ConfigCache cache(temp_devices_capacity, Device::kLinkKeyProperties);
44 std::string line;
45 std::string section(ConfigCache::kDefaultSectionName);
46 while (std::getline(config_file, line)) {
47 ++line_num;
48 line = common::StringTrim(std::move(line));
49 if (line.front() == '\0' || line.front() == '#') {
50 continue;
51 }
52 if (line.front() == '[') {
53 if (line.back() != ']') {
54 LOG_WARN("unterminated section name on line %d", line_num);
55 return std::nullopt;
56 }
57 // Read 'test' from '[text]', hence -2
58 section = line.substr(1, line.size() - 2);
59 } else {
60 auto tokens = common::StringSplit(line, "=", 2);
61 if (tokens.size() != 2) {
62 LOG_WARN("no key/value separator found on line %d", line_num);
63 return std::nullopt;
64 }
65 tokens[0] = common::StringTrim(std::move(tokens[0]));
66 tokens[1] = common::StringTrim(std::move(tokens[1]));
67 cache.SetProperty(section, tokens[0], std::move(tokens[1]));
68 }
69 }
70 return cache;
71 }
72
Write(const ConfigCache & cache)73 bool LegacyConfigFile::Write(const ConfigCache& cache) {
74 return os::WriteToFile(path_, cache.SerializeToLegacyFormat());
75 }
76
Delete()77 bool LegacyConfigFile::Delete() {
78 if (remove(path_.c_str()) != 0) {
79 LOG_WARN("unable to remove file '%s', error: %s", path_.c_str(), strerror(errno));
80 return false;
81 }
82 return true;
83 }
84
85 } // namespace storage
86 } // namespace bluetooth