blob: b7227020d2fd42bc5cb9ebf0b3f51a47e143b466 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 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
Tom Cherry3f5eaae52017-04-06 16:30:22 -070017#include "property_service.h"
18
Tom Cherry40acb372018-08-01 13:41:12 -070019#include <android/api-level.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070020#include <ctype.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070021#include <errno.h>
22#include <fcntl.h>
Keun-young Park7d320262017-02-17 17:48:56 -080023#include <inttypes.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070024#include <limits.h>
25#include <netinet/in.h>
26#include <stdarg.h>
Tom Cherryf57c0bf2017-04-07 13:46:21 -070027#include <stddef.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080028#include <stdio.h>
29#include <stdlib.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080030#include <string.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070031#include <sys/mman.h>
JP Abgrall4515d812014-01-31 14:37:07 -080032#include <sys/poll.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070033#include <sys/select.h>
34#include <sys/types.h>
35#include <sys/un.h>
36#include <unistd.h>
Tom Cherry8702dcb2017-10-13 16:20:19 -070037#include <wchar.h>
Elliott Hughes81399e12015-03-10 08:39:45 -070038
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080039#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
40#include <sys/_system_properties.h>
41
Tom Cherrybe048922019-02-16 12:03:19 -080042#include <map>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070043#include <memory>
Tom Cherryfe815412019-04-23 15:11:07 -070044#include <mutex>
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070045#include <optional>
Tom Marshall62696902017-06-09 18:29:23 +000046#include <queue>
Tom Cherryfe815412019-04-23 15:11:07 -070047#include <thread>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070048#include <vector>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080049
Nikita Ioffe92116e42020-03-31 01:28:35 +010050#include <InitProperties.sysprop.h>
Tom Cherryede0d532017-07-06 14:20:11 -070051#include <android-base/chrono_utils.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080052#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070053#include <android-base/logging.h>
Jiyong Park8178c5f2020-06-29 10:42:03 +090054#include <android-base/parseint.h>
Jaekyun Seok0cf3a072017-04-24 18:52:54 +090055#include <android-base/properties.h>
Tom Cherrya84e14d2017-09-05 12:38:30 -070056#include <android-base/stringprintf.h>
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +000057#include <android-base/strings.h>
Tom Cherry2ae2f602017-12-14 01:58:17 +000058#include <property_info_parser/property_info_parser.h>
59#include <property_info_serializer/property_info_serializer.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070060#include <selinux/android.h>
61#include <selinux/label.h>
62#include <selinux/selinux.h>
Andres Moralesdb5f5d42015-05-08 08:30:33 -070063
Bowgo Tsai30afda72019-04-11 23:57:24 +080064#include "debug_ramdisk.h"
Tom Cherry3707d322019-08-15 13:07:24 -070065#include "epoll.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080066#include "init.h"
Tom Cherry16fad422017-08-04 15:59:03 -070067#include "persistent_properties.h"
Tom Cherry927c5d52017-12-11 01:40:07 -080068#include "property_type.h"
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070069#include "proto_utils.h"
Yifan Honga68ee762020-10-06 16:58:19 -070070#include "second_stage_resources.h"
Logan Chien837b2a42018-05-03 14:33:52 +080071#include "selinux.h"
Tom Cherrydc375862018-02-28 10:39:01 -080072#include "subcontext.h"
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070073#include "system/core/init/property_service.pb.h"
Colin Cross3899e9f2010-04-13 20:35:46 -070074#include "util.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080075
Tom Cherrydc375862018-02-28 10:39:01 -080076using namespace std::literals;
77
Steven Laver57a740e2019-01-29 20:19:05 -080078using android::base::GetProperty;
Jiyong Park8178c5f2020-06-29 10:42:03 +090079using android::base::ParseInt;
Tom Cherry2ae2f602017-12-14 01:58:17 +000080using android::base::ReadFileToString;
81using android::base::Split;
Tom Cherry1cf8d692017-10-10 13:35:01 -070082using android::base::StartsWith;
Tom Cherrya84e14d2017-09-05 12:38:30 -070083using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070084using android::base::Timer;
Tom Cherry2ae2f602017-12-14 01:58:17 +000085using android::base::Trim;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070086using android::base::unique_fd;
Tom Cherry2ae2f602017-12-14 01:58:17 +000087using android::base::WriteStringToFile;
88using android::properties::BuildTrie;
Tom Cherry919458c2018-01-03 14:39:28 -080089using android::properties::ParsePropertyInfoFile;
Tom Cherry2ae2f602017-12-14 01:58:17 +000090using android::properties::PropertyInfoAreaFile;
91using android::properties::PropertyInfoEntry;
Nikita Ioffe92116e42020-03-31 01:28:35 +010092using android::sysprop::InitProperties::is_userspace_reboot_supported;
Tom Cherryede0d532017-07-06 14:20:11 -070093
Tom Cherry81f5d3e2017-06-22 12:53:17 -070094namespace android {
95namespace init {
96
Tom Cherry16fad422017-08-04 15:59:03 -070097static bool persistent_properties_loaded = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080098
Colin Crossd11beb22010-04-13 19:33:37 -070099static int property_set_fd = -1;
Tom Cherry802864c2020-03-12 14:29:25 -0700100static int from_init_socket = -1;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700101static int init_socket = -1;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100102static bool accept_messages = false;
Tom Cherry802864c2020-03-12 14:29:25 -0700103static std::mutex accept_messages_lock;
104static std::thread property_service_thread;
Colin Crossd11beb22010-04-13 19:33:37 -0700105
Tom Cherry2ae2f602017-12-14 01:58:17 +0000106static PropertyInfoAreaFile property_info_area;
107
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700108struct PropertyAuditData {
109 const ucred* cr;
110 const char* name;
111};
112
Tom Cherry2f113ad2019-04-22 10:22:41 -0700113static int PropertyAuditCallback(void* data, security_class_t /*cls*/, char* buf, size_t len) {
114 auto* d = reinterpret_cast<PropertyAuditData*>(data);
115
116 if (!d || !d->name || !d->cr) {
117 LOG(ERROR) << "AuditCallback invoked with null data arguments!";
118 return 0;
119 }
120
121 snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name, d->cr->pid, d->cr->uid,
122 d->cr->gid);
123 return 0;
124}
125
Tom Cherry802864c2020-03-12 14:29:25 -0700126void StartSendingMessages() {
127 auto lock = std::lock_guard{accept_messages_lock};
128 accept_messages = true;
129}
130
131void StopSendingMessages() {
132 auto lock = std::lock_guard{accept_messages_lock};
Tom Cherry68855272020-03-27 13:57:53 -0700133 accept_messages = false;
Tom Cherry802864c2020-03-12 14:29:25 -0700134}
135
Tom Cherryb35f8272018-10-22 14:50:52 -0700136bool CanReadProperty(const std::string& source_context, const std::string& name) {
137 const char* target_context = nullptr;
138 property_info_area->GetPropertyInfo(name.c_str(), &target_context, nullptr);
139
140 PropertyAuditData audit_data;
141
142 audit_data.name = name.c_str();
143
144 ucred cr = {.pid = 0, .uid = 0, .gid = 0};
145 audit_data.cr = &cr;
146
147 return selinux_check_access(source_context.c_str(), target_context, "file", "read",
148 &audit_data) == 0;
149}
150
Tom Cherry927c5d52017-12-11 01:40:07 -0800151static bool CheckMacPerms(const std::string& name, const char* target_context,
Tom Cherry32228482018-01-18 16:14:25 -0800152 const char* source_context, const ucred& cr) {
Tom Cherry927c5d52017-12-11 01:40:07 -0800153 if (!target_context || !source_context) {
Tom Cherry2ae2f602017-12-14 01:58:17 +0000154 return false;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000155 }
156
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700157 PropertyAuditData audit_data;
rpcraig63207cd2012-08-09 10:05:49 -0400158
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000159 audit_data.name = name.c_str();
Tom Cherry32228482018-01-18 16:14:25 -0800160 audit_data.cr = &cr;
William Robertsd7aea442015-10-01 16:03:47 -0700161
Tom Cherry927c5d52017-12-11 01:40:07 -0800162 bool has_access = (selinux_check_access(source_context, target_context, "property_service",
163 "set", &audit_data) == 0);
rpcraig63207cd2012-08-09 10:05:49 -0400164
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000165 return has_access;
rpcraig63207cd2012-08-09 10:05:49 -0400166}
167
Tom Cherry69d47aa2018-03-01 11:00:57 -0800168static uint32_t PropertySet(const std::string& name, const std::string& value, std::string* error) {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000169 size_t valuelen = value.size();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800170
Tom Cherryde6bd502018-02-13 16:50:08 -0800171 if (!IsLegalPropertyName(name)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800172 *error = "Illegal property name";
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000173 return PROP_ERROR_INVALID_NAME;
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000174 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000175
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900176 if (auto result = IsLegalPropertyValue(name, value); !result.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700177 *error = result.error().message();
Tom Cherry8702dcb2017-10-13 16:20:19 -0700178 return PROP_ERROR_INVALID_VALUE;
179 }
180
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000181 prop_info* pi = (prop_info*) __system_property_find(name.c_str());
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000182 if (pi != nullptr) {
183 // ro.* properties are actually "write-once".
Tom Cherry1cf8d692017-10-10 13:35:01 -0700184 if (StartsWith(name, "ro.")) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800185 *error = "Read-only property was already set";
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000186 return PROP_ERROR_READ_ONLY_PROPERTY;
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000187 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800188
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000189 __system_property_update(pi, value.c_str(), valuelen);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800190 } else {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000191 int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
Elliott Hughesdb3f2672015-03-20 09:45:18 -0700192 if (rc < 0) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800193 *error = "__system_property_add failed";
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000194 return PROP_ERROR_SET_FAILED;
Johan Redestigfd7ffb12013-04-29 09:11:57 +0200195 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800196 }
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000197
Elliott Hughes4f915812016-12-05 13:12:48 -0800198 // Don't write properties to disk until after we have read all default
199 // properties to prevent them from being overwritten by default values.
Tom Cherry1cf8d692017-10-10 13:35:01 -0700200 if (persistent_properties_loaded && StartsWith(name, "persist.")) {
Tom Cherry16fad422017-08-04 15:59:03 -0700201 WritePersistentProperty(name, value);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800202 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700203 // If init hasn't started its main loop, then it won't be handling property changed messages
204 // anyway, so there's no need to try to send them.
Tom Cherry802864c2020-03-12 14:29:25 -0700205 auto lock = std::lock_guard{accept_messages_lock};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100206 if (accept_messages) {
Tom Cherry802864c2020-03-12 14:29:25 -0700207 PropertyChanged(name, value);
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700208 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000209 return PROP_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800210}
211
Tom Cherry832f9f12020-03-10 11:47:24 -0700212class AsyncRestorecon {
Tom Cherryfe815412019-04-23 15:11:07 -0700213 public:
Tom Cherry832f9f12020-03-10 11:47:24 -0700214 void TriggerRestorecon(const std::string& path) {
Tom Cherry7205c622020-01-29 14:09:24 -0800215 auto guard = std::lock_guard{mutex_};
Tom Cherry832f9f12020-03-10 11:47:24 -0700216 paths_.emplace(path);
Tom Cherry7205c622020-01-29 14:09:24 -0800217
Tom Cherry832f9f12020-03-10 11:47:24 -0700218 if (!thread_started_) {
219 thread_started_ = true;
220 std::thread{&AsyncRestorecon::ThreadFunction, this}.detach();
Tom Cherryfe815412019-04-23 15:11:07 -0700221 }
222 }
223
224 private:
225 void ThreadFunction() {
226 auto lock = std::unique_lock{mutex_};
227
Tom Cherry832f9f12020-03-10 11:47:24 -0700228 while (!paths_.empty()) {
229 auto path = paths_.front();
230 paths_.pop();
Tom Cherryfe815412019-04-23 15:11:07 -0700231
232 lock.unlock();
Tom Cherry832f9f12020-03-10 11:47:24 -0700233 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
234 LOG(ERROR) << "Asynchronous restorecon of '" << path << "' failed'";
235 }
236 android::base::SetProperty(kRestoreconProperty, path);
Tom Cherryfe815412019-04-23 15:11:07 -0700237 lock.lock();
238 }
239
Tom Cherry832f9f12020-03-10 11:47:24 -0700240 thread_started_ = false;
Tom Cherryfe815412019-04-23 15:11:07 -0700241 }
242
243 std::mutex mutex_;
Tom Cherry832f9f12020-03-10 11:47:24 -0700244 std::queue<std::string> paths_;
245 bool thread_started_ = false;
Tom Marshall62696902017-06-09 18:29:23 +0000246};
247
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000248class SocketConnection {
Tom Cherry32228482018-01-18 16:14:25 -0800249 public:
250 SocketConnection(int socket, const ucred& cred) : socket_(socket), cred_(cred) {}
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000251
Tom Cherry32228482018-01-18 16:14:25 -0800252 bool RecvUint32(uint32_t* value, uint32_t* timeout_ms) {
253 return RecvFully(value, sizeof(*value), timeout_ms);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000254 }
255
Tom Cherry32228482018-01-18 16:14:25 -0800256 bool RecvChars(char* chars, size_t size, uint32_t* timeout_ms) {
257 return RecvFully(chars, size, timeout_ms);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000258 }
259
Tom Cherry32228482018-01-18 16:14:25 -0800260 bool RecvString(std::string* value, uint32_t* timeout_ms) {
261 uint32_t len = 0;
262 if (!RecvUint32(&len, timeout_ms)) {
263 return false;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000264 }
Tom Cherry32228482018-01-18 16:14:25 -0800265
266 if (len == 0) {
267 *value = "";
268 return true;
269 }
270
271 // http://b/35166374: don't allow init to make arbitrarily large allocations.
272 if (len > 0xffff) {
273 LOG(ERROR) << "sys_prop: RecvString asked to read huge string: " << len;
274 errno = ENOMEM;
275 return false;
276 }
277
278 std::vector<char> chars(len);
279 if (!RecvChars(&chars[0], len, timeout_ms)) {
280 return false;
281 }
282
283 *value = std::string(&chars[0], len);
284 return true;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000285 }
286
Tom Cherry32228482018-01-18 16:14:25 -0800287 bool SendUint32(uint32_t value) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700288 if (!socket_.ok()) {
289 return true;
290 }
Tom Cherry32228482018-01-18 16:14:25 -0800291 int result = TEMP_FAILURE_RETRY(send(socket_, &value, sizeof(value), 0));
292 return result == sizeof(value);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000293 }
294
Tom Cherry7f160af2019-04-22 13:28:28 -0700295 bool GetSourceContext(std::string* source_context) const {
296 char* c_source_context = nullptr;
297 if (getpeercon(socket_, &c_source_context) != 0) {
298 return false;
299 }
300 *source_context = c_source_context;
301 freecon(c_source_context);
302 return true;
303 }
304
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700305 [[nodiscard]] int Release() { return socket_.release(); }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000306
Tom Cherry32228482018-01-18 16:14:25 -0800307 const ucred& cred() { return cred_; }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000308
Tom Cherry32228482018-01-18 16:14:25 -0800309 private:
310 bool PollIn(uint32_t* timeout_ms) {
311 struct pollfd ufds[1];
312 ufds[0].fd = socket_;
313 ufds[0].events = POLLIN;
314 ufds[0].revents = 0;
315 while (*timeout_ms > 0) {
316 auto start_time = std::chrono::steady_clock::now();
317 int nr = poll(ufds, 1, *timeout_ms);
318 auto now = std::chrono::steady_clock::now();
319 auto time_elapsed =
320 std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
321 uint64_t millis = time_elapsed.count();
322 *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
323
324 if (nr > 0) {
325 return true;
326 }
327
328 if (nr == 0) {
329 // Timeout
330 break;
331 }
332
333 if (nr < 0 && errno != EINTR) {
334 PLOG(ERROR) << "sys_prop: error waiting for uid " << cred_.uid
335 << " to send property message";
336 return false;
337 } else { // errno == EINTR
338 // Timer rounds milliseconds down in case of EINTR we want it to be rounded up
339 // to avoid slowing init down by causing EINTR with under millisecond timeout.
340 if (*timeout_ms > 0) {
341 --(*timeout_ms);
342 }
343 }
344 }
345
346 LOG(ERROR) << "sys_prop: timeout waiting for uid " << cred_.uid
347 << " to send property message.";
348 return false;
349 }
350
351 bool RecvFully(void* data_ptr, size_t size, uint32_t* timeout_ms) {
352 size_t bytes_left = size;
353 char* data = static_cast<char*>(data_ptr);
354 while (*timeout_ms > 0 && bytes_left > 0) {
355 if (!PollIn(timeout_ms)) {
356 return false;
357 }
358
359 int result = TEMP_FAILURE_RETRY(recv(socket_, data, bytes_left, MSG_DONTWAIT));
360 if (result <= 0) {
DuXiao40533592018-05-21 14:43:56 +0800361 PLOG(ERROR) << "sys_prop: recv error";
Tom Cherry32228482018-01-18 16:14:25 -0800362 return false;
363 }
364
365 bytes_left -= result;
366 data += result;
367 }
368
DuXiao40533592018-05-21 14:43:56 +0800369 if (bytes_left != 0) {
370 LOG(ERROR) << "sys_prop: recv data is not properly obtained.";
371 }
372
Tom Cherry32228482018-01-18 16:14:25 -0800373 return bytes_left == 0;
374 }
375
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700376 unique_fd socket_;
Tom Cherry32228482018-01-18 16:14:25 -0800377 ucred cred_;
Tom Cherry3da2ba62019-08-28 17:47:49 +0000378
379 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketConnection);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000380};
381
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700382static uint32_t SendControlMessage(const std::string& msg, const std::string& name, pid_t pid,
383 SocketConnection* socket, std::string* error) {
Tom Cherry802864c2020-03-12 14:29:25 -0700384 auto lock = std::lock_guard{accept_messages_lock};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100385 if (!accept_messages) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700386 *error = "Received control message after shutdown, ignoring";
387 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
388 }
389
Tom Cherry832f9f12020-03-10 11:47:24 -0700390 // We must release the fd before sending it to init, otherwise there will be a race with init.
391 // If init calls close() before Release(), then fdsan will see the wrong tag and abort().
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700392 int fd = -1;
Tom Cherry5310db82019-10-22 08:27:23 -0700393 if (socket != nullptr && SelinuxGetVendorAndroidVersion() > __ANDROID_API_Q__) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700394 fd = socket->Release();
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700395 }
396
Tom Cherry802864c2020-03-12 14:29:25 -0700397 bool queue_success = QueueControlMessage(msg, name, pid, fd);
398 if (!queue_success && fd != -1) {
399 uint32_t response = PROP_ERROR_HANDLE_CONTROL_MESSAGE;
400 TEMP_FAILURE_RETRY(send(fd, &response, sizeof(response), 0));
401 close(fd);
Tom Cherry832f9f12020-03-10 11:47:24 -0700402 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700403
404 return PROP_SUCCESS;
405}
406
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700407bool CheckControlPropertyPerms(const std::string& name, const std::string& value,
408 const std::string& source_context, const ucred& cr) {
409 // We check the legacy method first but these properties are dontaudit, so we only log an audit
410 // if the newer method fails as well. We only do this with the legacy ctl. properties.
411 if (name == "ctl.start" || name == "ctl.stop" || name == "ctl.restart") {
412 // The legacy permissions model is that ctl. properties have their name ctl.<action> and
413 // their value is the name of the service to apply that action to. Permissions for these
414 // actions are based on the service, so we must create a fake name of ctl.<service> to
415 // check permissions.
416 auto control_string_legacy = "ctl." + value;
417 const char* target_context_legacy = nullptr;
418 const char* type_legacy = nullptr;
419 property_info_area->GetPropertyInfo(control_string_legacy.c_str(), &target_context_legacy,
420 &type_legacy);
421
422 if (CheckMacPerms(control_string_legacy, target_context_legacy, source_context.c_str(), cr)) {
423 return true;
424 }
425 }
426
427 auto control_string_full = name + "$" + value;
428 const char* target_context_full = nullptr;
429 const char* type_full = nullptr;
430 property_info_area->GetPropertyInfo(control_string_full.c_str(), &target_context_full,
431 &type_full);
432
433 return CheckMacPerms(control_string_full, target_context_full, source_context.c_str(), cr);
434}
435
Tom Cherry32228482018-01-18 16:14:25 -0800436// This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
Tom Cherrybe048922019-02-16 12:03:19 -0800437uint32_t CheckPermissions(const std::string& name, const std::string& value,
438 const std::string& source_context, const ucred& cr, std::string* error) {
Tom Cherryde6bd502018-02-13 16:50:08 -0800439 if (!IsLegalPropertyName(name)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800440 *error = "Illegal property name";
Tom Cherry32228482018-01-18 16:14:25 -0800441 return PROP_ERROR_INVALID_NAME;
442 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000443
Tom Cherry32228482018-01-18 16:14:25 -0800444 if (StartsWith(name, "ctl.")) {
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700445 if (!CheckControlPropertyPerms(name, value, source_context, cr)) {
446 *error = StringPrintf("Invalid permissions to perform '%s' on '%s'", name.c_str() + 4,
447 value.c_str());
Tom Cherry32228482018-01-18 16:14:25 -0800448 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
449 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000450
Tom Cherry32228482018-01-18 16:14:25 -0800451 return PROP_SUCCESS;
452 }
Tom Cherry927c5d52017-12-11 01:40:07 -0800453
Tom Cherry32228482018-01-18 16:14:25 -0800454 const char* target_context = nullptr;
455 const char* type = nullptr;
456 property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type);
Tom Cherrya84e14d2017-09-05 12:38:30 -0700457
Tom Cherry32228482018-01-18 16:14:25 -0800458 if (!CheckMacPerms(name, target_context, source_context.c_str(), cr)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800459 *error = "SELinux permission check failed";
Tom Cherry32228482018-01-18 16:14:25 -0800460 return PROP_ERROR_PERMISSION_DENIED;
461 }
462
Tom Cherryb5f2ec02019-11-08 17:54:27 -0800463 if (!CheckType(type, value)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800464 *error = StringPrintf("Property type check failed, value doesn't match expected type '%s'",
465 (type ?: "(null)"));
Tom Cherry32228482018-01-18 16:14:25 -0800466 return PROP_ERROR_INVALID_VALUE;
467 }
468
Tom Cherrybe048922019-02-16 12:03:19 -0800469 return PROP_SUCCESS;
470}
471
472// This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
473uint32_t HandlePropertySet(const std::string& name, const std::string& value,
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700474 const std::string& source_context, const ucred& cr,
475 SocketConnection* socket, std::string* error) {
Tom Cherrybe048922019-02-16 12:03:19 -0800476 if (auto ret = CheckPermissions(name, value, source_context, cr, error); ret != PROP_SUCCESS) {
477 return ret;
478 }
479
480 if (StartsWith(name, "ctl.")) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700481 return SendControlMessage(name.c_str() + 4, value, cr.pid, socket, error);
Tom Cherrybe048922019-02-16 12:03:19 -0800482 }
483
Tom Cherry32228482018-01-18 16:14:25 -0800484 // sys.powerctl is a special property that is used to make the device reboot. We want to log
485 // any process that sets this property to be able to accurately blame the cause of a shutdown.
486 if (name == "sys.powerctl") {
487 std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
488 std::string process_cmdline;
489 std::string process_log_string;
490 if (ReadFileToString(cmdline_path, &process_cmdline)) {
491 // Since cmdline is null deliminated, .c_str() conveniently gives us just the process
492 // path.
493 process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
494 }
495 LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
496 << process_log_string;
Tom Cherry9174a9b2020-03-31 14:36:03 -0700497 if (!value.empty()) {
498 DebugRebootLogging();
499 }
Nikita Ioffe92116e42020-03-31 01:28:35 +0100500 if (value == "reboot,userspace" && !is_userspace_reboot_supported().value_or(false)) {
501 *error = "Userspace reboot is not supported by this device";
502 return PROP_ERROR_INVALID_VALUE;
503 }
Tom Cherry32228482018-01-18 16:14:25 -0800504 }
505
Tom Cherryfe815412019-04-23 15:11:07 -0700506 // If a process other than init is writing a non-empty value, it means that process is
507 // requesting that init performs a restorecon operation on the path specified by 'value'.
508 // We use a thread to do this restorecon operation to prevent holding up init, as it may take
509 // a long time to complete.
510 if (name == kRestoreconProperty && cr.pid != 1 && !value.empty()) {
Tom Cherry832f9f12020-03-10 11:47:24 -0700511 static AsyncRestorecon async_restorecon;
512 async_restorecon.TriggerRestorecon(value);
Tom Cherryfe815412019-04-23 15:11:07 -0700513 return PROP_SUCCESS;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800514 }
515
516 return PropertySet(name, value, error);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000517}
518
519static void handle_property_set_fd() {
520 static constexpr uint32_t kDefaultSocketTimeout = 2000; /* ms */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800521
Robert Sesekca2da602017-01-25 08:08:51 -0500522 int s = accept4(property_set_fd, nullptr, nullptr, SOCK_CLOEXEC);
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700523 if (s == -1) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800524 return;
525 }
526
Tom Cherry32228482018-01-18 16:14:25 -0800527 ucred cr;
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700528 socklen_t cr_size = sizeof(cr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800529 if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
530 close(s);
Elliott Hughesb005d902017-02-22 14:54:15 -0800531 PLOG(ERROR) << "sys_prop: unable to get SO_PEERCRED";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800532 return;
533 }
534
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000535 SocketConnection socket(s, cr);
536 uint32_t timeout_ms = kDefaultSocketTimeout;
537
538 uint32_t cmd = 0;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000539 if (!socket.RecvUint32(&cmd, &timeout_ms)) {
540 PLOG(ERROR) << "sys_prop: error while reading command from the socket";
541 socket.SendUint32(PROP_ERROR_READ_CMD);
JP Abgrall4515d812014-01-31 14:37:07 -0800542 return;
543 }
544
Elliott Hughesb005d902017-02-22 14:54:15 -0800545 switch (cmd) {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000546 case PROP_MSG_SETPROP: {
547 char prop_name[PROP_NAME_MAX];
548 char prop_value[PROP_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800549
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000550 if (!socket.RecvChars(prop_name, PROP_NAME_MAX, &timeout_ms) ||
551 !socket.RecvChars(prop_value, PROP_VALUE_MAX, &timeout_ms)) {
552 PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP): error while reading name/value from the socket";
553 return;
Nick Kralevich69463612013-09-13 17:21:28 -0700554 }
555
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000556 prop_name[PROP_NAME_MAX-1] = 0;
557 prop_value[PROP_VALUE_MAX-1] = 0;
rpcraig63207cd2012-08-09 10:05:49 -0400558
Tom Cherry7f160af2019-04-22 13:28:28 -0700559 std::string source_context;
560 if (!socket.GetSourceContext(&source_context)) {
561 PLOG(ERROR) << "Unable to set property '" << prop_name << "': getpeercon() failed";
562 return;
563 }
564
Tom Cherry69d47aa2018-03-01 11:00:57 -0800565 const auto& cr = socket.cred();
566 std::string error;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700567 uint32_t result =
568 HandlePropertySet(prop_name, prop_value, source_context, cr, nullptr, &error);
Tom Cherry69d47aa2018-03-01 11:00:57 -0800569 if (result != PROP_SUCCESS) {
Nick Kralevich9ca898f2019-04-04 10:10:01 -0700570 LOG(ERROR) << "Unable to set property '" << prop_name << "' from uid:" << cr.uid
571 << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800572 }
573
Dimitry Ivanovdee4bd22017-01-19 14:53:00 -0800574 break;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000575 }
Dimitry Ivanov70c4ecf2017-01-24 18:38:09 +0000576
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000577 case PROP_MSG_SETPROP2: {
578 std::string name;
579 std::string value;
580 if (!socket.RecvString(&name, &timeout_ms) ||
581 !socket.RecvString(&value, &timeout_ms)) {
582 PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP2): error while reading name/value from the socket";
583 socket.SendUint32(PROP_ERROR_READ_DATA);
584 return;
585 }
586
Tom Cherry7f160af2019-04-22 13:28:28 -0700587 std::string source_context;
588 if (!socket.GetSourceContext(&source_context)) {
589 PLOG(ERROR) << "Unable to set property '" << name << "': getpeercon() failed";
590 socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
591 return;
592 }
593
Tom Cherry69d47aa2018-03-01 11:00:57 -0800594 const auto& cr = socket.cred();
595 std::string error;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700596 uint32_t result = HandlePropertySet(name, value, source_context, cr, &socket, &error);
Tom Cherry69d47aa2018-03-01 11:00:57 -0800597 if (result != PROP_SUCCESS) {
Nick Kralevich9ca898f2019-04-04 10:10:01 -0700598 LOG(ERROR) << "Unable to set property '" << name << "' from uid:" << cr.uid
599 << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800600 }
Tom Cherryf4514262019-08-26 16:33:40 +0000601 socket.SendUint32(result);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000602 break;
603 }
Elliott Hughesb005d902017-02-22 14:54:15 -0800604
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800605 default:
Elliott Hughesb005d902017-02-22 14:54:15 -0800606 LOG(ERROR) << "sys_prop: invalid command " << cmd;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000607 socket.SendUint32(PROP_ERROR_INVALID_CMD);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800608 break;
609 }
610}
611
Tom Cherryc88d8f92019-08-19 15:21:25 -0700612uint32_t InitPropertySet(const std::string& name, const std::string& value) {
613 uint32_t result = 0;
614 ucred cr = {.pid = 1, .uid = 0, .gid = 0};
615 std::string error;
616 result = HandlePropertySet(name, value, kInitContext, cr, nullptr, &error);
617 if (result != PROP_SUCCESS) {
618 LOG(ERROR) << "Init cannot set '" << name << "' to '" << value << "': " << error;
619 }
620
621 return result;
622}
623
Tom Cherrybe048922019-02-16 12:03:19 -0800624static bool load_properties_from_file(const char*, const char*,
625 std::map<std::string, std::string>*);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800626
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800627/*
628 * Filter is used to decide which properties to load: NULL loads all keys,
629 * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
630 */
Tom Cherrybe048922019-02-16 12:03:19 -0800631static void LoadProperties(char* data, const char* filter, const char* filename,
632 std::map<std::string, std::string>* properties) {
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800633 char *key, *value, *eol, *sol, *tmp, *fn;
634 size_t flen = 0;
635
Yifan Hong9258f2e2020-07-15 17:04:43 -0700636 static constexpr const char* const kVendorPathPrefixes[4] = {
Tom Cherry14c24722019-09-18 13:47:19 -0700637 "/vendor",
638 "/odm",
Yifan Hong2ed3cda2020-06-24 18:29:22 -0700639 "/vendor_dlkm",
Yifan Hong9258f2e2020-07-15 17:04:43 -0700640 "/odm_dlkm",
Tom Cherry14c24722019-09-18 13:47:19 -0700641 };
642
643 const char* context = kInitContext;
Tom Cherry40acb372018-08-01 13:41:12 -0700644 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
Tom Cherry14c24722019-09-18 13:47:19 -0700645 for (const auto& vendor_path_prefix : kVendorPathPrefixes) {
646 if (StartsWith(filename, vendor_path_prefix)) {
647 context = kVendorContext;
Tom Cherrya1dbeb82018-04-11 15:50:00 -0700648 }
Tom Cherrydc375862018-02-28 10:39:01 -0800649 }
650 }
651
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800652 if (filter) {
653 flen = strlen(filter);
654 }
655
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800656 sol = data;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800657 while ((eol = strchr(sol, '\n'))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800658 key = sol;
659 *eol++ = 0;
660 sol = eol;
661
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800662 while (isspace(*key)) key++;
663 if (*key == '#') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800664
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800665 tmp = eol - 2;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800666 while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800667
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800668 if (!strncmp(key, "import ", 7) && flen == 0) {
669 fn = key + 7;
670 while (isspace(*fn)) fn++;
671
672 key = strchr(fn, ' ');
673 if (key) {
674 *key++ = 0;
675 while (isspace(*key)) key++;
676 }
677
Dongcheol Shina87c0f92019-06-12 09:31:35 +0900678 std::string raw_filename(fn);
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700679 auto expanded_filename = ExpandProps(raw_filename);
680
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900681 if (!expanded_filename.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700682 LOG(ERROR) << "Could not expand filename ': " << expanded_filename.error();
Dongcheol Shina87c0f92019-06-12 09:31:35 +0900683 continue;
684 }
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800685
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700686 load_properties_from_file(expanded_filename->c_str(), key, properties);
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800687 } else {
688 value = strchr(key, '=');
689 if (!value) continue;
690 *value++ = 0;
691
692 tmp = value - 2;
693 while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
694
695 while (isspace(*value)) value++;
696
697 if (flen > 0) {
698 if (filter[flen - 1] == '*') {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700699 if (strncmp(key, filter, flen - 1) != 0) continue;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800700 } else {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700701 if (strcmp(key, filter) != 0) continue;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800702 }
703 }
704
Tom Cherrydc375862018-02-28 10:39:01 -0800705 if (StartsWith(key, "ctl.") || key == "sys.powerctl"s ||
Tom Cherryfe815412019-04-23 15:11:07 -0700706 std::string{key} == kRestoreconProperty) {
Tom Cherrydc375862018-02-28 10:39:01 -0800707 LOG(ERROR) << "Ignoring disallowed property '" << key
708 << "' with special meaning in prop file '" << filename << "'";
709 continue;
710 }
711
Tom Cherrydc375862018-02-28 10:39:01 -0800712 ucred cr = {.pid = 1, .uid = 0, .gid = 0};
713 std::string error;
Tom Cherrybe048922019-02-16 12:03:19 -0800714 if (CheckPermissions(key, value, context, cr, &error) == PROP_SUCCESS) {
715 auto it = properties->find(key);
716 if (it == properties->end()) {
717 (*properties)[key] = value;
718 } else if (it->second != value) {
Jiyong Parke714cde2020-06-11 19:41:54 +0900719 LOG(WARNING) << "Overriding previous property '" << key << "':'" << it->second
720 << "' with new value '" << value << "'";
Tom Cherrybe048922019-02-16 12:03:19 -0800721 it->second = value;
722 }
723 } else {
724 LOG(ERROR) << "Do not have permissions to set '" << key << "' to '" << value
Tom Cherrydc375862018-02-28 10:39:01 -0800725 << "' in property file '" << filename << "': " << error;
726 }
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800727 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800728 }
729}
730
Elliott Hughes5a7ad842016-09-30 14:12:33 -0700731// Filter is used to decide which properties to load: NULL loads all keys,
732// "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
Tom Cherrybe048922019-02-16 12:03:19 -0800733static bool load_properties_from_file(const char* filename, const char* filter,
734 std::map<std::string, std::string>* properties) {
Elliott Hughesda40c002015-03-27 23:20:44 -0700735 Timer t;
Tom Cherry62ca6632017-08-03 12:54:07 -0700736 auto file_contents = ReadFile(filename);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900737 if (!file_contents.ok()) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700738 PLOG(WARNING) << "Couldn't load property file '" << filename
739 << "': " << file_contents.error();
Hung-ying Tyanaef2b092017-06-02 18:59:46 +0800740 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800741 }
Tom Cherry62ca6632017-08-03 12:54:07 -0700742 file_contents->push_back('\n');
Tom Cherrydc375862018-02-28 10:39:01 -0800743
Tom Cherrybe048922019-02-16 12:03:19 -0800744 LoadProperties(file_contents->data(), filter, filename, properties);
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000745 LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
Hung-ying Tyanaef2b092017-06-02 18:59:46 +0800746 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800747}
748
Yifan Honga68ee762020-10-06 16:58:19 -0700749static void LoadPropertiesFromSecondStageRes(std::map<std::string, std::string>* properties) {
750 std::string prop = GetRamdiskPropForSecondStage();
751 if (access(prop.c_str(), R_OK) != 0) {
752 CHECK(errno == ENOENT) << "Cannot access " << prop << ": " << strerror(errno);
753 return;
754 }
755 load_properties_from_file(prop.c_str(), nullptr, properties);
756}
757
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900758// persist.sys.usb.config values can't be combined on build-time when property
759// files are split into each partition.
760// So we need to apply the same rule of build/make/tools/post_process_props.py
761// on runtime.
762static void update_sys_usb_config() {
763 bool is_debuggable = android::base::GetBoolProperty("ro.debuggable", false);
764 std::string config = android::base::GetProperty("persist.sys.usb.config", "");
Howard Yenbb578202020-02-26 21:36:59 +0800765 // b/150130503, add (config == "none") condition here to prevent appending
766 // ",adb" if "none" is explicitly defined in default prop.
767 if (config.empty() || config == "none") {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700768 InitPropertySet("persist.sys.usb.config", is_debuggable ? "adb" : "none");
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900769 } else if (is_debuggable && config.find("adb") == std::string::npos &&
770 config.length() + 4 < PROP_VALUE_MAX) {
771 config.append(",adb");
Tom Cherryc88d8f92019-08-19 15:21:25 -0700772 InitPropertySet("persist.sys.usb.config", config);
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900773 }
774}
775
Nick Kralevich32b90232012-09-19 11:15:24 -0700776static void load_override_properties() {
Elliott Hughesc0e919c2015-02-04 14:46:36 -0800777 if (ALLOW_LOCAL_PROP_OVERRIDE) {
Tom Cherrybe048922019-02-16 12:03:19 -0800778 std::map<std::string, std::string> properties;
779 load_properties_from_file("/data/local.prop", nullptr, &properties);
780 for (const auto& [name, value] : properties) {
781 std::string error;
782 if (PropertySet(name, value, &error) != PROP_SUCCESS) {
783 LOG(ERROR) << "Could not set '" << name << "' to '" << value
784 << "' in /data/local.prop: " << error;
785 }
786 }
Nick Kralevich32b90232012-09-19 11:15:24 -0700787 }
Nick Kralevich32b90232012-09-19 11:15:24 -0700788}
789
Steven Laver57a740e2019-01-29 20:19:05 -0800790// If the ro.product.[brand|device|manufacturer|model|name] properties have not been explicitly
791// set, derive them from ro.product.${partition}.* properties
792static void property_initialize_ro_product_props() {
793 const char* RO_PRODUCT_PROPS_PREFIX = "ro.product.";
794 const char* RO_PRODUCT_PROPS[] = {
795 "brand", "device", "manufacturer", "model", "name",
796 };
797 const char* RO_PRODUCT_PROPS_ALLOWED_SOURCES[] = {
Justin Yun7eaf9b52019-06-28 14:28:00 +0900798 "odm", "product", "system_ext", "system", "vendor",
Steven Laver57a740e2019-01-29 20:19:05 -0800799 };
Justin Yun7eaf9b52019-06-28 14:28:00 +0900800 const char* RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER = "product,odm,vendor,system_ext,system";
Steven Laver57a740e2019-01-29 20:19:05 -0800801 const std::string EMPTY = "";
802
803 std::string ro_product_props_source_order =
804 GetProperty("ro.product.property_source_order", EMPTY);
805
806 if (!ro_product_props_source_order.empty()) {
807 // Verify that all specified sources are valid
808 for (const auto& source : Split(ro_product_props_source_order, ",")) {
809 // Verify that the specified source is valid
810 bool is_allowed_source = false;
811 for (const auto& allowed_source : RO_PRODUCT_PROPS_ALLOWED_SOURCES) {
812 if (source == allowed_source) {
813 is_allowed_source = true;
814 break;
815 }
816 }
817 if (!is_allowed_source) {
818 LOG(ERROR) << "Found unexpected source in ro.product.property_source_order; "
819 "using the default property source order";
820 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
821 break;
822 }
823 }
824 } else {
825 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
826 }
827
828 for (const auto& ro_product_prop : RO_PRODUCT_PROPS) {
829 std::string base_prop(RO_PRODUCT_PROPS_PREFIX);
830 base_prop += ro_product_prop;
831
832 std::string base_prop_val = GetProperty(base_prop, EMPTY);
833 if (!base_prop_val.empty()) {
834 continue;
835 }
836
837 for (const auto& source : Split(ro_product_props_source_order, ",")) {
838 std::string target_prop(RO_PRODUCT_PROPS_PREFIX);
839 target_prop += source;
840 target_prop += '.';
841 target_prop += ro_product_prop;
842
843 std::string target_prop_val = GetProperty(target_prop, EMPTY);
844 if (!target_prop_val.empty()) {
845 LOG(INFO) << "Setting product property " << base_prop << " to '" << target_prop_val
846 << "' (from " << target_prop << ")";
847 std::string error;
848 uint32_t res = PropertySet(base_prop, target_prop_val, &error);
849 if (res != PROP_SUCCESS) {
850 LOG(ERROR) << "Error setting product property " << base_prop << ": err=" << res
851 << " (" << error << ")";
852 }
853 break;
854 }
855 }
856 }
857}
858
859// If the ro.build.fingerprint property has not been set, derive it from constituent pieces
860static void property_derive_build_fingerprint() {
861 std::string build_fingerprint = GetProperty("ro.build.fingerprint", "");
862 if (!build_fingerprint.empty()) {
863 return;
864 }
865
866 const std::string UNKNOWN = "unknown";
867 build_fingerprint = GetProperty("ro.product.brand", UNKNOWN);
868 build_fingerprint += '/';
869 build_fingerprint += GetProperty("ro.product.name", UNKNOWN);
870 build_fingerprint += '/';
871 build_fingerprint += GetProperty("ro.product.device", UNKNOWN);
872 build_fingerprint += ':';
Colin Crossb519c712020-10-13 12:38:48 -0700873 build_fingerprint += GetProperty("ro.build.version.release_or_codename", UNKNOWN);
Steven Laver57a740e2019-01-29 20:19:05 -0800874 build_fingerprint += '/';
875 build_fingerprint += GetProperty("ro.build.id", UNKNOWN);
876 build_fingerprint += '/';
877 build_fingerprint += GetProperty("ro.build.version.incremental", UNKNOWN);
878 build_fingerprint += ':';
879 build_fingerprint += GetProperty("ro.build.type", UNKNOWN);
880 build_fingerprint += '/';
881 build_fingerprint += GetProperty("ro.build.tags", UNKNOWN);
882
883 LOG(INFO) << "Setting property 'ro.build.fingerprint' to '" << build_fingerprint << "'";
884
885 std::string error;
886 uint32_t res = PropertySet("ro.build.fingerprint", build_fingerprint, &error);
887 if (res != PROP_SUCCESS) {
888 LOG(ERROR) << "Error setting property 'ro.build.fingerprint': err=" << res << " (" << error
889 << ")";
890 }
891}
892
SzuWei Lin0061d4d2020-12-31 16:52:39 +0800893// If the ro.product.cpu.abilist* properties have not been explicitly
894// set, derive them from ro.${partition}.product.cpu.abilist* properties.
895static void property_initialize_ro_cpu_abilist() {
896 // From high to low priority.
897 const char* kAbilistSources[] = {
898 "product",
899 "odm",
900 "vendor",
901 "system",
902 };
903 const std::string EMPTY = "";
904 const char* kAbilistProp = "ro.product.cpu.abilist";
905 const char* kAbilist32Prop = "ro.product.cpu.abilist32";
906 const char* kAbilist64Prop = "ro.product.cpu.abilist64";
907
908 // If the properties are defined explicitly, just use them.
909 if (GetProperty(kAbilistProp, EMPTY) != EMPTY) {
910 return;
911 }
912
913 // Find the first source defining these properties by order.
914 std::string abilist32_prop_val;
915 std::string abilist64_prop_val;
916 for (const auto& source : kAbilistSources) {
917 const auto abilist32_prop = std::string("ro.") + source + ".product.cpu.abilist32";
918 const auto abilist64_prop = std::string("ro.") + source + ".product.cpu.abilist64";
919 abilist32_prop_val = GetProperty(abilist32_prop, EMPTY);
920 abilist64_prop_val = GetProperty(abilist64_prop, EMPTY);
921 // The properties could be empty on 32-bit-only or 64-bit-only devices,
922 // but we cannot identify a property is empty or undefined by GetProperty().
923 // So, we assume both of these 2 properties are empty as undefined.
924 if (abilist32_prop_val != EMPTY || abilist64_prop_val != EMPTY) {
925 break;
926 }
927 }
928
929 // Merge ABI lists for ro.product.cpu.abilist
930 auto abilist_prop_val = abilist64_prop_val;
931 if (abilist32_prop_val != EMPTY) {
932 if (abilist_prop_val != EMPTY) {
933 abilist_prop_val += ",";
934 }
935 abilist_prop_val += abilist32_prop_val;
936 }
937
938 // Set these properties
939 const std::pair<const char*, const std::string&> set_prop_list[] = {
940 {kAbilistProp, abilist_prop_val},
941 {kAbilist32Prop, abilist32_prop_val},
942 {kAbilist64Prop, abilist64_prop_val},
943 };
944 for (const auto& [prop, prop_val] : set_prop_list) {
945 LOG(INFO) << "Setting property '" << prop << "' to '" << prop_val << "'";
946
947 std::string error;
948 uint32_t res = PropertySet(prop, prop_val, &error);
949 if (res != PROP_SUCCESS) {
950 LOG(ERROR) << "Error setting property '" << prop << "': err=" << res << " (" << error
951 << ")";
952 }
953 }
954}
955
Tom Cherryc88d8f92019-08-19 15:21:25 -0700956void PropertyLoadBootDefaults() {
Tom Cherrybe048922019-02-16 12:03:19 -0800957 // We read the properties and their values into a map, in order to always allow properties
958 // loaded in the later property files to override the properties in loaded in the earlier
959 // property files, regardless of if they are "ro." properties or not.
960 std::map<std::string, std::string> properties;
Jiyong Parkc068d0e2020-05-11 16:47:05 +0900961
962 if (IsRecoveryMode()) {
963 load_properties_from_file("/prop.default", nullptr, &properties);
Jiyong Park3b316ee2019-01-13 02:42:31 +0900964 }
Jiyong Parkc068d0e2020-05-11 16:47:05 +0900965
Jiyong Park8178c5f2020-06-29 10:42:03 +0900966 // /<part>/etc/build.prop is the canonical location of the build-time properties since S.
967 // Falling back to /<part>/defalt.prop and /<part>/build.prop only when legacy path has to
968 // be supported, which is controlled by the support_legacy_path_until argument.
969 const auto load_properties_from_partition = [&properties](const std::string& partition,
970 int support_legacy_path_until) {
971 auto path = "/" + partition + "/etc/build.prop";
972 if (load_properties_from_file(path.c_str(), nullptr, &properties)) {
973 return;
974 }
975 // To read ro.<partition>.build.version.sdk, temporarily load the legacy paths into a
976 // separate map. Then by comparing its value with legacy_version, we know that if the
977 // partition is old enough so that we need to respect the legacy paths.
978 std::map<std::string, std::string> temp;
979 auto legacy_path1 = "/" + partition + "/default.prop";
980 auto legacy_path2 = "/" + partition + "/build.prop";
981 load_properties_from_file(legacy_path1.c_str(), nullptr, &temp);
982 load_properties_from_file(legacy_path2.c_str(), nullptr, &temp);
983 bool support_legacy_path = false;
984 auto version_prop_name = "ro." + partition + ".build.version.sdk";
985 auto it = temp.find(version_prop_name);
986 if (it == temp.end()) {
987 // This is embarassing. Without the prop, we can't determine how old the partition is.
988 // Let's be conservative by assuming it is very very old.
989 support_legacy_path = true;
990 } else if (int value;
991 ParseInt(it->second.c_str(), &value) && value <= support_legacy_path_until) {
992 support_legacy_path = true;
993 }
994 if (support_legacy_path) {
995 // We don't update temp into properties directly as it might skip any (future) logic
996 // for resolving duplicates implemented in load_properties_from_file. Instead, read
997 // the files again into the properties map.
998 load_properties_from_file(legacy_path1.c_str(), nullptr, &properties);
999 load_properties_from_file(legacy_path2.c_str(), nullptr, &properties);
1000 } else {
1001 LOG(FATAL) << legacy_path1 << " and " << legacy_path2 << " were not loaded "
1002 << "because " << version_prop_name << "(" << it->second << ") is newer "
1003 << "than " << support_legacy_path_until;
1004 }
1005 };
1006
1007 // Order matters here. The more the partition is specific to a product, the higher its
1008 // precedence is.
Yifan Honga68ee762020-10-06 16:58:19 -07001009 LoadPropertiesFromSecondStageRes(&properties);
Tom Cherrybe048922019-02-16 12:03:19 -08001010 load_properties_from_file("/system/build.prop", nullptr, &properties);
Jiyong Park8178c5f2020-06-29 10:42:03 +09001011 load_properties_from_partition("system_ext", /* support_legacy_path_until */ 30);
1012 // TODO(b/117892318): uncomment the following condition when vendor.imgs for aosp_* targets are
1013 // all updated.
1014 // if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_R__) {
1015 load_properties_from_file("/vendor/default.prop", nullptr, &properties);
1016 // }
Tom Cherrybe048922019-02-16 12:03:19 -08001017 load_properties_from_file("/vendor/build.prop", nullptr, &properties);
Yifan Hong2ed3cda2020-06-24 18:29:22 -07001018 load_properties_from_file("/vendor_dlkm/etc/build.prop", nullptr, &properties);
Yifan Hong9258f2e2020-07-15 17:04:43 -07001019 load_properties_from_file("/odm_dlkm/etc/build.prop", nullptr, &properties);
Jiyong Park8178c5f2020-06-29 10:42:03 +09001020 load_properties_from_partition("odm", /* support_legacy_path_until */ 28);
1021 load_properties_from_partition("product", /* support_legacy_path_until */ 30);
Jiyong Park85695522020-05-11 15:59:44 +09001022
Tom Cherryc88d8f92019-08-19 15:21:25 -07001023 if (access(kDebugRamdiskProp, R_OK) == 0) {
Bowgo Tsai30afda72019-04-11 23:57:24 +08001024 LOG(INFO) << "Loading " << kDebugRamdiskProp;
1025 load_properties_from_file(kDebugRamdiskProp, nullptr, &properties);
Bowgo Tsai1dacd422019-03-04 17:53:34 +08001026 }
1027
Tom Cherrybe048922019-02-16 12:03:19 -08001028 for (const auto& [name, value] : properties) {
1029 std::string error;
1030 if (PropertySet(name, value, &error) != PROP_SUCCESS) {
1031 LOG(ERROR) << "Could not set '" << name << "' to '" << value
1032 << "' while loading .prop files" << error;
1033 }
1034 }
Jiyong Park3b316ee2019-01-13 02:42:31 +09001035
Steven Laver57a740e2019-01-29 20:19:05 -08001036 property_initialize_ro_product_props();
1037 property_derive_build_fingerprint();
SzuWei Lin0061d4d2020-12-31 16:52:39 +08001038 property_initialize_ro_cpu_abilist();
Steven Laver57a740e2019-01-29 20:19:05 -08001039
Jiyong Park3b316ee2019-01-13 02:42:31 +09001040 update_sys_usb_config();
Riley Andrewse4b7b292014-06-16 15:06:21 -07001041}
1042
Tom Cherry2ae2f602017-12-14 01:58:17 +00001043bool LoadPropertyInfoFromFile(const std::string& filename,
1044 std::vector<PropertyInfoEntry>* property_infos) {
1045 auto file_contents = std::string();
1046 if (!ReadFileToString(filename, &file_contents)) {
1047 PLOG(ERROR) << "Could not read properties from '" << filename << "'";
1048 return false;
1049 }
1050
Tom Cherry919458c2018-01-03 14:39:28 -08001051 auto errors = std::vector<std::string>{};
Tom Cherry4b077c52019-12-11 07:56:51 -08001052 bool require_prefix_or_exact = SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__;
1053 ParsePropertyInfoFile(file_contents, require_prefix_or_exact, property_infos, &errors);
Tom Cherry919458c2018-01-03 14:39:28 -08001054 // Individual parsing errors are reported but do not cause a failed boot, which is what
1055 // returning false would do here.
1056 for (const auto& error : errors) {
1057 LOG(ERROR) << "Could not read line from '" << filename << "': " << error;
Tom Cherry2ae2f602017-12-14 01:58:17 +00001058 }
Tom Cherry919458c2018-01-03 14:39:28 -08001059
Tom Cherry2ae2f602017-12-14 01:58:17 +00001060 return true;
1061}
1062
1063void CreateSerializedPropertyInfo() {
1064 auto property_infos = std::vector<PropertyInfoEntry>();
1065 if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
1066 if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",
1067 &property_infos)) {
1068 return;
1069 }
Tom Cherry2d451662020-07-27 11:20:29 -07001070 // Don't check for failure here, since we don't always have all of these partitions.
Tom Cherry2ae2f602017-12-14 01:58:17 +00001071 // E.g. In case of recovery, the vendor partition will not have mounted and we
1072 // still need the system / platform properties to function.
Bowgo Tsai1a191bf2019-10-02 16:23:32 +08001073 if (access("/system_ext/etc/selinux/system_ext_property_contexts", R_OK) != -1) {
1074 LoadPropertyInfoFromFile("/system_ext/etc/selinux/system_ext_property_contexts",
1075 &property_infos);
1076 }
Bowgo Tsai36cf3532017-12-07 16:05:25 +08001077 if (!LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",
1078 &property_infos)) {
1079 // Fallback to nonplat_* if vendor_* doesn't exist.
1080 LoadPropertyInfoFromFile("/vendor/etc/selinux/nonplat_property_contexts",
1081 &property_infos);
1082 }
Jinguang Dongf42e08d2019-02-15 16:56:28 +08001083 if (access("/product/etc/selinux/product_property_contexts", R_OK) != -1) {
1084 LoadPropertyInfoFromFile("/product/etc/selinux/product_property_contexts",
1085 &property_infos);
1086 }
1087 if (access("/odm/etc/selinux/odm_property_contexts", R_OK) != -1) {
1088 LoadPropertyInfoFromFile("/odm/etc/selinux/odm_property_contexts", &property_infos);
1089 }
Tom Cherry2ae2f602017-12-14 01:58:17 +00001090 } else {
1091 if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {
1092 return;
1093 }
Bowgo Tsai1a191bf2019-10-02 16:23:32 +08001094 LoadPropertyInfoFromFile("/system_ext_property_contexts", &property_infos);
Bowgo Tsai36cf3532017-12-07 16:05:25 +08001095 if (!LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos)) {
1096 // Fallback to nonplat_* if vendor_* doesn't exist.
1097 LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos);
1098 }
Jinguang Dongf42e08d2019-02-15 16:56:28 +08001099 LoadPropertyInfoFromFile("/product_property_contexts", &property_infos);
1100 LoadPropertyInfoFromFile("/odm_property_contexts", &property_infos);
Tom Cherry2ae2f602017-12-14 01:58:17 +00001101 }
Tom Cherry927c5d52017-12-11 01:40:07 -08001102
Tom Cherry2ae2f602017-12-14 01:58:17 +00001103 auto serialized_contexts = std::string();
1104 auto error = std::string();
Tom Cherry927c5d52017-12-11 01:40:07 -08001105 if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,
Tom Cherry2ae2f602017-12-14 01:58:17 +00001106 &error)) {
1107 LOG(ERROR) << "Unable to serialize property contexts: " << error;
1108 return;
1109 }
1110
1111 constexpr static const char kPropertyInfosPath[] = "/dev/__properties__/property_info";
1112 if (!WriteStringToFile(serialized_contexts, kPropertyInfosPath, 0444, 0, 0, false)) {
1113 PLOG(ERROR) << "Unable to write serialized property infos to file";
1114 }
1115 selinux_android_restorecon(kPropertyInfosPath, 0);
1116}
1117
Tom Cherryc88d8f92019-08-19 15:21:25 -07001118static void ExportKernelBootProps() {
1119 constexpr const char* UNSET = "";
1120 struct {
1121 const char* src_prop;
1122 const char* dst_prop;
1123 const char* default_value;
1124 } prop_map[] = {
1125 // clang-format off
1126 { "ro.boot.serialno", "ro.serialno", UNSET, },
1127 { "ro.boot.mode", "ro.bootmode", "unknown", },
1128 { "ro.boot.baseband", "ro.baseband", "unknown", },
1129 { "ro.boot.bootloader", "ro.bootloader", "unknown", },
1130 { "ro.boot.hardware", "ro.hardware", "unknown", },
1131 { "ro.boot.revision", "ro.revision", "0", },
1132 // clang-format on
1133 };
1134 for (const auto& prop : prop_map) {
1135 std::string value = GetProperty(prop.src_prop, prop.default_value);
1136 if (value != UNSET) InitPropertySet(prop.dst_prop, value);
1137 }
1138}
1139
1140static void ProcessKernelDt() {
1141 if (!is_android_dt_value_expected("compatible", "android,firmware")) {
1142 return;
1143 }
1144
1145 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(get_android_dt_dir().c_str()), closedir);
1146 if (!dir) return;
1147
1148 std::string dt_file;
1149 struct dirent* dp;
1150 while ((dp = readdir(dir.get())) != NULL) {
1151 if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") ||
1152 !strcmp(dp->d_name, "name")) {
1153 continue;
1154 }
1155
1156 std::string file_name = get_android_dt_dir() + dp->d_name;
1157
1158 android::base::ReadFileToString(file_name, &dt_file);
1159 std::replace(dt_file.begin(), dt_file.end(), ',', '.');
1160
1161 InitPropertySet("ro.boot."s + dp->d_name, dt_file);
1162 }
1163}
1164
1165static void ProcessKernelCmdline() {
1166 bool for_emulator = false;
1167 ImportKernelCmdline([&](const std::string& key, const std::string& value) {
1168 if (key == "qemu") {
1169 for_emulator = true;
1170 } else if (StartsWith(key, "androidboot.")) {
1171 InitPropertySet("ro.boot." + key.substr(12), value);
1172 }
1173 });
1174
1175 if (for_emulator) {
1176 ImportKernelCmdline([&](const std::string& key, const std::string& value) {
1177 // In the emulator, export any kernel option with the "ro.kernel." prefix.
1178 InitPropertySet("ro.kernel." + key, value);
1179 });
1180 }
1181}
1182
Devin Moorea4ef15b2020-12-15 16:14:37 -08001183static void ProcessBootconfig() {
1184 ImportBootconfig([&](const std::string& key, const std::string& value) {
1185 if (StartsWith(key, "androidboot.")) {
1186 InitPropertySet("ro.boot." + key.substr(12), value);
1187 }
1188 });
1189}
1190
Tom Cherryc88d8f92019-08-19 15:21:25 -07001191void PropertyInit() {
1192 selinux_callback cb;
1193 cb.func_audit = PropertyAuditCallback;
1194 selinux_set_callback(SELINUX_CB_AUDIT, cb);
1195
1196 mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);
1197 CreateSerializedPropertyInfo();
1198 if (__system_property_area_init()) {
1199 LOG(FATAL) << "Failed to initialize property area";
1200 }
1201 if (!property_info_area.LoadDefaultPath()) {
1202 LOG(FATAL) << "Failed to load serialized property info file";
1203 }
1204
1205 // If arguments are passed both on the command line and in DT,
1206 // properties set in DT always have priority over the command-line ones.
1207 ProcessKernelDt();
1208 ProcessKernelCmdline();
Devin Moorea4ef15b2020-12-15 16:14:37 -08001209 ProcessBootconfig();
Tom Cherryc88d8f92019-08-19 15:21:25 -07001210
1211 // Propagate the kernel variables to internal variables
1212 // used by init as well as the current required properties.
1213 ExportKernelBootProps();
1214
1215 PropertyLoadBootDefaults();
1216}
1217
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001218static void HandleInitSocket() {
1219 auto message = ReadMessage(init_socket);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001220 if (!message.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001221 LOG(ERROR) << "Could not read message from init_dedicated_recv_socket: " << message.error();
1222 return;
1223 }
1224
1225 auto init_message = InitMessage{};
1226 if (!init_message.ParseFromString(*message)) {
1227 LOG(ERROR) << "Could not parse message from init";
1228 return;
1229 }
1230
1231 switch (init_message.msg_case()) {
1232 case InitMessage::kLoadPersistentProperties: {
1233 load_override_properties();
1234 // Read persistent properties after all default values have been loaded.
1235 auto persistent_properties = LoadPersistentProperties();
1236 for (const auto& persistent_property_record : persistent_properties.properties()) {
1237 InitPropertySet(persistent_property_record.name(),
1238 persistent_property_record.value());
1239 }
1240 InitPropertySet("ro.persistent_properties.ready", "true");
1241 persistent_properties_loaded = true;
1242 break;
1243 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001244 default:
1245 LOG(ERROR) << "Unknown message type from init: " << init_message.msg_case();
1246 }
1247}
1248
1249static void PropertyServiceThread() {
1250 Epoll epoll;
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001251 if (auto result = epoll.Open(); !result.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001252 LOG(FATAL) << result.error();
1253 }
1254
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001255 if (auto result = epoll.RegisterHandler(property_set_fd, handle_property_set_fd);
1256 !result.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001257 LOG(FATAL) << result.error();
1258 }
1259
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001260 if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001261 LOG(FATAL) << result.error();
1262 }
1263
Tom Cherry832f9f12020-03-10 11:47:24 -07001264 while (true) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001265 auto pending_functions = epoll.Wait(std::nullopt);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001266 if (!pending_functions.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001267 LOG(ERROR) << pending_functions.error();
1268 } else {
1269 for (const auto& function : *pending_functions) {
1270 (*function)();
1271 }
1272 }
1273 }
1274}
1275
1276void StartPropertyService(int* epoll_socket) {
Tom Cherryc88d8f92019-08-19 15:21:25 -07001277 InitPropertySet("ro.property_service.version", "2");
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +00001278
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001279 int sockets[2];
1280 if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != 0) {
1281 PLOG(FATAL) << "Failed to socketpair() between property_service and init";
1282 }
Tom Cherry802864c2020-03-12 14:29:25 -07001283 *epoll_socket = from_init_socket = sockets[0];
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001284 init_socket = sockets[1];
Tom Cherry802864c2020-03-12 14:29:25 -07001285 StartSendingMessages();
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001286
Tom Cherry3da2ba62019-08-28 17:47:49 +00001287 if (auto result = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001288 false, 0666, 0, 0, {});
1289 result.ok()) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -07001290 property_set_fd = *result;
1291 } else {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001292 LOG(FATAL) << "start_property_service socket creation failed: " << result.error();
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001293 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001294
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001295 listen(property_set_fd, 8);
Colin Crossd11beb22010-04-13 19:33:37 -07001296
Tom Cherry802864c2020-03-12 14:29:25 -07001297 auto new_thread = std::thread{PropertyServiceThread};
1298 property_service_thread.swap(new_thread);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001299}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001300
1301} // namespace init
1302} // namespace android