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 [[maybe_unused]] 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.empty()) {
50 continue;
51 }
52
53 if (line.front() == '\0' || line.front() == '#') {
54 continue;
55 }
56 if (line.front() == '[') {
57 if (line.back() != ']') {
58 LOG_WARN("unterminated section name on line %d", line_num);
59 return std::nullopt;
60 }
61 // Read 'test' from '[text]', hence -2
62 section = line.substr(1, line.size() - 2);
63 } else {
64 auto tokens = common::StringSplit(line, "=", 2);
65 if (tokens.size() != 2) {
66 LOG_WARN("no key/value separator found on line %d", line_num);
67 return std::nullopt;
68 }
69 tokens[0] = common::StringTrim(std::move(tokens[0]));
70 tokens[1] = common::StringTrim(std::move(tokens[1]));
71 cache.SetProperty(section, tokens[0], std::move(tokens[1]));
72 }
73 }
74 return cache;
75 }
76
Write(const ConfigCache & cache)77 bool LegacyConfigFile::Write(const ConfigCache& cache) {
78 return os::WriteToFile(path_, cache.SerializeToLegacyFormat());
79 }
80
Delete()81 bool LegacyConfigFile::Delete() {
82 if (!os::FileExists(path_)) {
83 LOG_WARN("Config file at \"%s\" does not exist", path_.c_str());
84 return false;
85 }
86 return os::RemoveFile(path_);
87 }
88
89 } // namespace storage
90 } // namespace bluetooth
91