blob: 71f235532ebf00248521fb05aad5b89936c29f3b [file] [log] [blame]
Tom Cherry16fad422017-08-04 15:59:03 -07001/*
2 * Copyright (C) 2017 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 "persistent_properties.h"
18
19#include <dirent.h>
20#include <fcntl.h>
21#include <sys/stat.h>
22#include <sys/system_properties.h>
23#include <sys/types.h>
24
25#include <memory>
26
27#include <android-base/file.h>
28#include <android-base/logging.h>
29#include <android-base/strings.h>
30#include <android-base/unique_fd.h>
31
32#include "util.h"
33
34using android::base::ReadFdToString;
35using android::base::StartsWith;
36using android::base::WriteStringToFd;
37using android::base::unique_fd;
38
39namespace android {
40namespace init {
41
42std::string persistent_property_filename = "/data/property/persistent_properties";
43
44namespace {
45
46constexpr const uint32_t kMagic = 0x8495E0B4;
47constexpr const char kLegacyPersistentPropertyDir[] = "/data/property";
48
Tom Cherrya97faba2017-09-15 15:44:04 -070049void AddPersistentProperty(const std::string& name, const std::string& value,
50 PersistentProperties* persistent_properties) {
51 auto persistent_property_record = persistent_properties->add_properties();
52 persistent_property_record->set_name(name);
53 persistent_property_record->set_value(value);
54}
55
56Result<PersistentProperties> LoadLegacyPersistentProperties() {
Tom Cherry16fad422017-08-04 15:59:03 -070057 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kLegacyPersistentPropertyDir), closedir);
58 if (!dir) {
59 return ErrnoError() << "Unable to open persistent property directory \""
60 << kLegacyPersistentPropertyDir << "\"";
61 }
62
Tom Cherrya97faba2017-09-15 15:44:04 -070063 PersistentProperties persistent_properties;
Tom Cherry16fad422017-08-04 15:59:03 -070064 dirent* entry;
65 while ((entry = readdir(dir.get())) != nullptr) {
66 if (!StartsWith(entry->d_name, "persist.")) {
67 continue;
68 }
69 if (entry->d_type != DT_REG) {
70 continue;
71 }
72
73 unique_fd fd(openat(dirfd(dir.get()), entry->d_name, O_RDONLY | O_NOFOLLOW));
74 if (fd == -1) {
75 PLOG(ERROR) << "Unable to open persistent property file \"" << entry->d_name << "\"";
76 continue;
77 }
78
79 struct stat sb;
80 if (fstat(fd, &sb) == -1) {
81 PLOG(ERROR) << "fstat on property file \"" << entry->d_name << "\" failed";
82 continue;
83 }
84
85 // File must not be accessible to others, be owned by root/root, and
86 // not be a hard link to any other file.
87 if (((sb.st_mode & (S_IRWXG | S_IRWXO)) != 0) || sb.st_uid != 0 || sb.st_gid != 0 ||
88 sb.st_nlink != 1) {
89 PLOG(ERROR) << "skipping insecure property file " << entry->d_name
90 << " (uid=" << sb.st_uid << " gid=" << sb.st_gid << " nlink=" << sb.st_nlink
91 << " mode=" << std::oct << sb.st_mode << ")";
92 continue;
93 }
94
95 std::string value;
96 if (ReadFdToString(fd, &value)) {
Tom Cherrya97faba2017-09-15 15:44:04 -070097 AddPersistentProperty(entry->d_name, value, &persistent_properties);
Tom Cherry16fad422017-08-04 15:59:03 -070098 } else {
99 PLOG(ERROR) << "Unable to read persistent property file " << entry->d_name;
100 }
101 }
102 return persistent_properties;
103}
104
105void RemoveLegacyPersistentPropertyFiles() {
106 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(kLegacyPersistentPropertyDir), closedir);
107 if (!dir) {
108 PLOG(ERROR) << "Unable to open persistent property directory \""
109 << kLegacyPersistentPropertyDir << "\"";
110 return;
111 }
112
113 dirent* entry;
114 while ((entry = readdir(dir.get())) != nullptr) {
115 if (!StartsWith(entry->d_name, "persist.")) {
116 continue;
117 }
118 if (entry->d_type != DT_REG) {
119 continue;
120 }
121 unlinkat(dirfd(dir.get()), entry->d_name, 0);
122 }
123}
124
Tom Cherrya97faba2017-09-15 15:44:04 -0700125PersistentProperties LoadPersistentPropertiesFromMemory() {
126 PersistentProperties persistent_properties;
Tom Cherry16fad422017-08-04 15:59:03 -0700127 __system_property_foreach(
128 [](const prop_info* pi, void* cookie) {
129 __system_property_read_callback(
130 pi,
131 [](void* cookie, const char* name, const char* value, unsigned serial) {
132 if (StartsWith(name, "persist.")) {
Tom Cherrya97faba2017-09-15 15:44:04 -0700133 auto properties = reinterpret_cast<PersistentProperties*>(cookie);
134 AddPersistentProperty(name, value, properties);
Tom Cherry16fad422017-08-04 15:59:03 -0700135 }
136 },
137 cookie);
138 },
Tom Cherrya97faba2017-09-15 15:44:04 -0700139 &persistent_properties);
140 return persistent_properties;
Tom Cherry16fad422017-08-04 15:59:03 -0700141}
142
143class PersistentPropertyFileParser {
144 public:
145 PersistentPropertyFileParser(const std::string& contents) : contents_(contents), position_(0) {}
Tom Cherrya97faba2017-09-15 15:44:04 -0700146 Result<PersistentProperties> Parse();
Tom Cherry16fad422017-08-04 15:59:03 -0700147
148 private:
149 Result<std::string> ReadString();
150 Result<uint32_t> ReadUint32();
151
152 const std::string& contents_;
153 size_t position_;
154};
155
Tom Cherrya97faba2017-09-15 15:44:04 -0700156Result<PersistentProperties> PersistentPropertyFileParser::Parse() {
Tom Cherry16fad422017-08-04 15:59:03 -0700157 if (auto magic = ReadUint32(); magic) {
158 if (*magic != kMagic) {
159 return Error() << "Magic value '0x" << std::hex << *magic
160 << "' does not match expected value '0x" << kMagic << "'";
161 }
162 } else {
163 return Error() << "Could not read magic value: " << magic.error();
164 }
165
166 if (auto version = ReadUint32(); version) {
167 if (*version != 1) {
168 return Error() << "Version '" << *version
169 << "' does not match any compatible version: (1)";
170 }
171 } else {
172 return Error() << "Could not read version: " << version.error();
173 }
174
175 auto num_properties = ReadUint32();
176 if (!num_properties) {
177 return Error() << "Could not read num_properties: " << num_properties.error();
178 }
179
Tom Cherrya97faba2017-09-15 15:44:04 -0700180 PersistentProperties result;
Tom Cherry16fad422017-08-04 15:59:03 -0700181 while (position_ < contents_.size()) {
Tom Cherrya97faba2017-09-15 15:44:04 -0700182 auto name = ReadString();
183 if (!name) {
184 return Error() << "Could not read name: " << name.error();
Tom Cherry16fad422017-08-04 15:59:03 -0700185 }
Tom Cherrya97faba2017-09-15 15:44:04 -0700186 if (!StartsWith(*name, "persist.")) {
187 return Error() << "Property '" << *name << "' does not starts with 'persist.'";
Tom Cherry16fad422017-08-04 15:59:03 -0700188 }
189 auto value = ReadString();
190 if (!value) {
191 return Error() << "Could not read value: " << value.error();
192 }
Tom Cherrya97faba2017-09-15 15:44:04 -0700193 AddPersistentProperty(*name, *value, &result);
Tom Cherry16fad422017-08-04 15:59:03 -0700194 }
195
196 return result;
197}
198
199Result<std::string> PersistentPropertyFileParser::ReadString() {
200 auto string_length = ReadUint32();
201 if (!string_length) {
202 return Error() << "Could not read size for string";
203 }
204
205 if (position_ + *string_length > contents_.size()) {
206 return Error() << "String size would cause it to overflow the input buffer";
207 }
208 auto result = std::string(contents_, position_, *string_length);
209 position_ += *string_length;
210 return result;
211}
212
213Result<uint32_t> PersistentPropertyFileParser::ReadUint32() {
214 if (position_ + 3 > contents_.size()) {
215 return Error() << "Input buffer not large enough to read uint32_t";
216 }
217 uint32_t result = *reinterpret_cast<const uint32_t*>(&contents_[position_]);
218 position_ += sizeof(uint32_t);
219 return result;
220}
221
Tom Cherrya97faba2017-09-15 15:44:04 -0700222Result<std::string> ReadPersistentPropertyFile() {
Tom Cherry16fad422017-08-04 15:59:03 -0700223 const std::string temp_filename = persistent_property_filename + ".tmp";
224 if (access(temp_filename.c_str(), F_OK) == 0) {
225 LOG(INFO)
226 << "Found temporary property file while attempting to persistent system properties"
227 " a previous persistent property write may have failed";
228 unlink(temp_filename.c_str());
229 }
230 auto file_contents = ReadFile(persistent_property_filename);
231 if (!file_contents) {
232 return Error() << "Unable to read persistent property file: " << file_contents.error();
233 }
Tom Cherrya97faba2017-09-15 15:44:04 -0700234 return *file_contents;
235}
236
237} // namespace
238
239Result<PersistentProperties> LoadPersistentPropertyFile() {
240 auto file_contents = ReadPersistentPropertyFile();
241 if (!file_contents) return file_contents.error();
242
243 // Check the intermediate "I should have used protobufs from the start" format.
244 // TODO: Remove this.
Tom Cherry16fad422017-08-04 15:59:03 -0700245 auto parsed_contents = PersistentPropertyFileParser(*file_contents).Parse();
Tom Cherrya97faba2017-09-15 15:44:04 -0700246 if (parsed_contents) {
247 LOG(INFO) << "Intermediate format persistent property file found, converting to protobuf";
248
249 // Update to the protobuf format
250 WritePersistentPropertyFile(*parsed_contents);
251 return parsed_contents;
Tom Cherry16fad422017-08-04 15:59:03 -0700252 }
Tom Cherrya97faba2017-09-15 15:44:04 -0700253
254 PersistentProperties persistent_properties;
255 if (persistent_properties.ParseFromString(*file_contents)) return persistent_properties;
256
257 // If the file cannot be parsed in either format, then we don't have any recovery
258 // mechanisms, so we delete it to allow for future writes to take place successfully.
259 unlink(persistent_property_filename.c_str());
260 return Error() << "Unable to parse persistent property file: " << parsed_contents.error();
Tom Cherry16fad422017-08-04 15:59:03 -0700261}
262
Tom Cherrya97faba2017-09-15 15:44:04 -0700263Result<Success> WritePersistentPropertyFile(const PersistentProperties& persistent_properties) {
Tom Cherry16fad422017-08-04 15:59:03 -0700264 const std::string temp_filename = persistent_property_filename + ".tmp";
265 unique_fd fd(TEMP_FAILURE_RETRY(
266 open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
267 if (fd == -1) {
268 return ErrnoError() << "Could not open temporary properties file";
269 }
Tom Cherrya97faba2017-09-15 15:44:04 -0700270 std::string serialized_string;
271 if (!persistent_properties.SerializeToString(&serialized_string)) {
272 return Error() << "Unable to serialize properties";
273 }
274 if (!WriteStringToFd(serialized_string, fd)) {
Tom Cherry16fad422017-08-04 15:59:03 -0700275 return ErrnoError() << "Unable to write file contents";
276 }
277 fsync(fd);
278 fd.reset();
279
280 if (rename(temp_filename.c_str(), persistent_property_filename.c_str())) {
281 int saved_errno = errno;
282 unlink(temp_filename.c_str());
283 return Error(saved_errno) << "Unable to rename persistent property file";
284 }
285 return Success();
286}
287
288// Persistent properties are not written often, so we rather not keep any data in memory and read
289// then rewrite the persistent property file for each update.
290void WritePersistentProperty(const std::string& name, const std::string& value) {
Tom Cherrya97faba2017-09-15 15:44:04 -0700291 auto file_contents = ReadPersistentPropertyFile();
292 PersistentProperties persistent_properties;
293
294 if (!file_contents || !persistent_properties.ParseFromString(*file_contents)) {
Tom Cherry16fad422017-08-04 15:59:03 -0700295 LOG(ERROR) << "Recovering persistent properties from memory: "
Tom Cherrya97faba2017-09-15 15:44:04 -0700296 << (!file_contents ? file_contents.error_string() : "Could not parse protobuf");
Tom Cherry16fad422017-08-04 15:59:03 -0700297 persistent_properties = LoadPersistentPropertiesFromMemory();
298 }
Tom Cherrya97faba2017-09-15 15:44:04 -0700299 auto it = std::find_if(persistent_properties.mutable_properties()->begin(),
300 persistent_properties.mutable_properties()->end(),
301 [&name](const auto& record) { return record.name() == name; });
302 if (it != persistent_properties.mutable_properties()->end()) {
303 it->set_name(name);
304 it->set_value(value);
Tom Cherry16fad422017-08-04 15:59:03 -0700305 } else {
Tom Cherrya97faba2017-09-15 15:44:04 -0700306 AddPersistentProperty(name, value, &persistent_properties);
Tom Cherry16fad422017-08-04 15:59:03 -0700307 }
308
Tom Cherrya97faba2017-09-15 15:44:04 -0700309 if (auto result = WritePersistentPropertyFile(persistent_properties); !result) {
Tom Cherry16fad422017-08-04 15:59:03 -0700310 LOG(ERROR) << "Could not store persistent property: " << result.error();
311 }
312}
313
Tom Cherrya97faba2017-09-15 15:44:04 -0700314PersistentProperties LoadPersistentProperties() {
Tom Cherry16fad422017-08-04 15:59:03 -0700315 auto persistent_properties = LoadPersistentPropertyFile();
316
317 if (!persistent_properties) {
318 LOG(ERROR) << "Could not load single persistent property file, trying legacy directory: "
319 << persistent_properties.error();
320 persistent_properties = LoadLegacyPersistentProperties();
321 if (!persistent_properties) {
322 LOG(ERROR) << "Unable to load legacy persistent properties: "
323 << persistent_properties.error();
324 return {};
325 }
326 if (auto result = WritePersistentPropertyFile(*persistent_properties); result) {
327 RemoveLegacyPersistentPropertyFiles();
328 } else {
329 LOG(ERROR) << "Unable to write single persistent property file: " << result.error();
330 // Fall through so that we still set the properties that we've read.
331 }
332 }
333
334 return *persistent_properties;
335}
336
337} // namespace init
338} // namespace android