blob: 64f29492bae000621efa81de7a176f57eb28a02a [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>
Roman Kiryanovccc15c52021-03-09 13:20:36 -080047#include <string_view>
Tom Cherryfe815412019-04-23 15:11:07 -070048#include <thread>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070049#include <vector>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080050
Nikita Ioffe92116e42020-03-31 01:28:35 +010051#include <InitProperties.sysprop.h>
Tom Cherryede0d532017-07-06 14:20:11 -070052#include <android-base/chrono_utils.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080053#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070054#include <android-base/logging.h>
Jiyong Park8178c5f2020-06-29 10:42:03 +090055#include <android-base/parseint.h>
Jaekyun Seok0cf3a072017-04-24 18:52:54 +090056#include <android-base/properties.h>
Inseob Kim946c9722022-05-23 16:37:44 +090057#include <android-base/result.h>
Tom Cherrya84e14d2017-09-05 12:38:30 -070058#include <android-base/stringprintf.h>
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +000059#include <android-base/strings.h>
Yi-Yo Chiangb8c23252023-07-25 22:08:55 +080060#include <fs_mgr.h>
Paul Lawrence689adfa2023-07-18 08:39:10 -070061#include <private/android_filesystem_config.h>
Tom Cherry2ae2f602017-12-14 01:58:17 +000062#include <property_info_parser/property_info_parser.h>
63#include <property_info_serializer/property_info_serializer.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070064#include <selinux/android.h>
65#include <selinux/label.h>
66#include <selinux/selinux.h>
Justin Yun6bc1bfe2024-01-10 13:47:02 +090067#include <vendorsupport/api_level.h>
Andres Moralesdb5f5d42015-05-08 08:30:33 -070068
Bowgo Tsai30afda72019-04-11 23:57:24 +080069#include "debug_ramdisk.h"
Tom Cherry3707d322019-08-15 13:07:24 -070070#include "epoll.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080071#include "init.h"
Tom Cherry16fad422017-08-04 15:59:03 -070072#include "persistent_properties.h"
Tom Cherry927c5d52017-12-11 01:40:07 -080073#include "property_type.h"
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070074#include "proto_utils.h"
Yifan Honga68ee762020-10-06 16:58:19 -070075#include "second_stage_resources.h"
Logan Chien837b2a42018-05-03 14:33:52 +080076#include "selinux.h"
Tom Cherrydc375862018-02-28 10:39:01 -080077#include "subcontext.h"
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070078#include "system/core/init/property_service.pb.h"
Colin Cross3899e9f2010-04-13 20:35:46 -070079#include "util.h"
maxwen107cae32020-09-30 17:51:49 +020080#include "vendor_init.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080081
Nate Myrenc25abe42023-08-25 14:30:50 -070082static constexpr char APPCOMPAT_OVERRIDE_PROP_FOLDERNAME[] =
83 "/dev/__properties__/appcompat_override";
84static constexpr char APPCOMPAT_OVERRIDE_PROP_TREE_FILE[] =
85 "/dev/__properties__/appcompat_override/property_info";
Tom Cherrydc375862018-02-28 10:39:01 -080086using namespace std::literals;
87
Inseob Kim946c9722022-05-23 16:37:44 +090088using android::base::ErrnoError;
89using android::base::Error;
Justin Yun29192392023-12-07 22:22:53 +000090using android::base::GetIntProperty;
Steven Laver57a740e2019-01-29 20:19:05 -080091using android::base::GetProperty;
Jiyong Park8178c5f2020-06-29 10:42:03 +090092using android::base::ParseInt;
Tom Cherry2ae2f602017-12-14 01:58:17 +000093using android::base::ReadFileToString;
Inseob Kim946c9722022-05-23 16:37:44 +090094using android::base::Result;
Tom Cherry2ae2f602017-12-14 01:58:17 +000095using android::base::Split;
Tom Cherry1cf8d692017-10-10 13:35:01 -070096using android::base::StartsWith;
Tom Cherrya84e14d2017-09-05 12:38:30 -070097using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070098using android::base::Timer;
Tom Cherry2ae2f602017-12-14 01:58:17 +000099using android::base::Trim;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700100using android::base::unique_fd;
Tom Cherry2ae2f602017-12-14 01:58:17 +0000101using android::base::WriteStringToFile;
102using android::properties::BuildTrie;
Tom Cherry919458c2018-01-03 14:39:28 -0800103using android::properties::ParsePropertyInfoFile;
Tom Cherry2ae2f602017-12-14 01:58:17 +0000104using android::properties::PropertyInfoAreaFile;
105using android::properties::PropertyInfoEntry;
Nikita Ioffe92116e42020-03-31 01:28:35 +0100106using android::sysprop::InitProperties::is_userspace_reboot_supported;
Tom Cherryede0d532017-07-06 14:20:11 -0700107
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700108namespace android {
109namespace init {
David Anderson0af9ab32022-10-07 00:19:55 -0700110
111class PersistWriteThread;
112
Tianjiebecfa772021-05-05 17:23:46 -0700113constexpr auto FINGERPRINT_PROP = "ro.build.fingerprint";
114constexpr auto LEGACY_FINGERPRINT_PROP = "ro.build.legacy.fingerprint";
115constexpr auto ID_PROP = "ro.build.id";
116constexpr auto LEGACY_ID_PROP = "ro.build.legacy.id";
117constexpr auto VBMETA_DIGEST_PROP = "ro.boot.vbmeta.digest";
118constexpr auto DIGEST_SIZE_USED = 8;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700119
Tom Cherry16fad422017-08-04 15:59:03 -0700120static bool persistent_properties_loaded = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800121
Tom Cherry802864c2020-03-12 14:29:25 -0700122static int from_init_socket = -1;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700123static int init_socket = -1;
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100124static bool accept_messages = false;
Tom Cherry802864c2020-03-12 14:29:25 -0700125static std::mutex accept_messages_lock;
Paul Lawrence689adfa2023-07-18 08:39:10 -0700126static std::mutex selinux_check_access_lock;
Tom Cherry802864c2020-03-12 14:29:25 -0700127static std::thread property_service_thread;
Paul Lawrence689adfa2023-07-18 08:39:10 -0700128static std::thread property_service_for_system_thread;
Colin Crossd11beb22010-04-13 19:33:37 -0700129
David Anderson0af9ab32022-10-07 00:19:55 -0700130static std::unique_ptr<PersistWriteThread> persist_write_thread;
131
Tom Cherry2ae2f602017-12-14 01:58:17 +0000132static PropertyInfoAreaFile property_info_area;
133
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700134struct PropertyAuditData {
135 const ucred* cr;
136 const char* name;
137};
138
Tom Cherry2f113ad2019-04-22 10:22:41 -0700139static int PropertyAuditCallback(void* data, security_class_t /*cls*/, char* buf, size_t len) {
140 auto* d = reinterpret_cast<PropertyAuditData*>(data);
141
142 if (!d || !d->name || !d->cr) {
143 LOG(ERROR) << "AuditCallback invoked with null data arguments!";
144 return 0;
145 }
146
147 snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name, d->cr->pid, d->cr->uid,
148 d->cr->gid);
149 return 0;
150}
151
Tom Cherry802864c2020-03-12 14:29:25 -0700152void StartSendingMessages() {
153 auto lock = std::lock_guard{accept_messages_lock};
154 accept_messages = true;
155}
156
157void StopSendingMessages() {
158 auto lock = std::lock_guard{accept_messages_lock};
Tom Cherry68855272020-03-27 13:57:53 -0700159 accept_messages = false;
Tom Cherry802864c2020-03-12 14:29:25 -0700160}
161
Tom Cherryb35f8272018-10-22 14:50:52 -0700162bool CanReadProperty(const std::string& source_context, const std::string& name) {
163 const char* target_context = nullptr;
164 property_info_area->GetPropertyInfo(name.c_str(), &target_context, nullptr);
165
166 PropertyAuditData audit_data;
167
168 audit_data.name = name.c_str();
169
170 ucred cr = {.pid = 0, .uid = 0, .gid = 0};
171 audit_data.cr = &cr;
172
Paul Lawrence689adfa2023-07-18 08:39:10 -0700173 auto lock = std::lock_guard{selinux_check_access_lock};
Tom Cherryb35f8272018-10-22 14:50:52 -0700174 return selinux_check_access(source_context.c_str(), target_context, "file", "read",
175 &audit_data) == 0;
176}
177
Tom Cherry927c5d52017-12-11 01:40:07 -0800178static bool CheckMacPerms(const std::string& name, const char* target_context,
Tom Cherry32228482018-01-18 16:14:25 -0800179 const char* source_context, const ucred& cr) {
Tom Cherry927c5d52017-12-11 01:40:07 -0800180 if (!target_context || !source_context) {
Tom Cherry2ae2f602017-12-14 01:58:17 +0000181 return false;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000182 }
183
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700184 PropertyAuditData audit_data;
rpcraig63207cd2012-08-09 10:05:49 -0400185
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000186 audit_data.name = name.c_str();
Tom Cherry32228482018-01-18 16:14:25 -0800187 audit_data.cr = &cr;
William Robertsd7aea442015-10-01 16:03:47 -0700188
Paul Lawrence689adfa2023-07-18 08:39:10 -0700189 auto lock = std::lock_guard{selinux_check_access_lock};
190 return selinux_check_access(source_context, target_context, "property_service", "set",
191 &audit_data) == 0;
rpcraig63207cd2012-08-09 10:05:49 -0400192}
193
David Anderson0af9ab32022-10-07 00:19:55 -0700194void NotifyPropertyChange(const std::string& name, const std::string& value) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700195 // If init hasn't started its main loop, then it won't be handling property changed messages
196 // anyway, so there's no need to try to send them.
Tom Cherry802864c2020-03-12 14:29:25 -0700197 auto lock = std::lock_guard{accept_messages_lock};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100198 if (accept_messages) {
Tom Cherry802864c2020-03-12 14:29:25 -0700199 PropertyChanged(name, value);
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700200 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800201}
202
Tom Cherry832f9f12020-03-10 11:47:24 -0700203class AsyncRestorecon {
Tom Cherryfe815412019-04-23 15:11:07 -0700204 public:
Tom Cherry832f9f12020-03-10 11:47:24 -0700205 void TriggerRestorecon(const std::string& path) {
Tom Cherry7205c622020-01-29 14:09:24 -0800206 auto guard = std::lock_guard{mutex_};
Tom Cherry832f9f12020-03-10 11:47:24 -0700207 paths_.emplace(path);
Tom Cherry7205c622020-01-29 14:09:24 -0800208
Tom Cherry832f9f12020-03-10 11:47:24 -0700209 if (!thread_started_) {
210 thread_started_ = true;
211 std::thread{&AsyncRestorecon::ThreadFunction, this}.detach();
Tom Cherryfe815412019-04-23 15:11:07 -0700212 }
213 }
214
215 private:
216 void ThreadFunction() {
217 auto lock = std::unique_lock{mutex_};
218
Tom Cherry832f9f12020-03-10 11:47:24 -0700219 while (!paths_.empty()) {
220 auto path = paths_.front();
221 paths_.pop();
Tom Cherryfe815412019-04-23 15:11:07 -0700222
223 lock.unlock();
Tom Cherry832f9f12020-03-10 11:47:24 -0700224 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
225 LOG(ERROR) << "Asynchronous restorecon of '" << path << "' failed'";
226 }
227 android::base::SetProperty(kRestoreconProperty, path);
Tom Cherryfe815412019-04-23 15:11:07 -0700228 lock.lock();
229 }
230
Tom Cherry832f9f12020-03-10 11:47:24 -0700231 thread_started_ = false;
Tom Cherryfe815412019-04-23 15:11:07 -0700232 }
233
234 std::mutex mutex_;
Tom Cherry832f9f12020-03-10 11:47:24 -0700235 std::queue<std::string> paths_;
236 bool thread_started_ = false;
Tom Marshall62696902017-06-09 18:29:23 +0000237};
238
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000239class SocketConnection {
Tom Cherry32228482018-01-18 16:14:25 -0800240 public:
David Anderson0af9ab32022-10-07 00:19:55 -0700241 SocketConnection() = default;
Tom Cherry32228482018-01-18 16:14:25 -0800242 SocketConnection(int socket, const ucred& cred) : socket_(socket), cred_(cred) {}
David Anderson0af9ab32022-10-07 00:19:55 -0700243 SocketConnection(SocketConnection&&) = default;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000244
Tom Cherry32228482018-01-18 16:14:25 -0800245 bool RecvUint32(uint32_t* value, uint32_t* timeout_ms) {
246 return RecvFully(value, sizeof(*value), timeout_ms);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000247 }
248
Tom Cherry32228482018-01-18 16:14:25 -0800249 bool RecvChars(char* chars, size_t size, uint32_t* timeout_ms) {
250 return RecvFully(chars, size, timeout_ms);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000251 }
252
Tom Cherry32228482018-01-18 16:14:25 -0800253 bool RecvString(std::string* value, uint32_t* timeout_ms) {
254 uint32_t len = 0;
255 if (!RecvUint32(&len, timeout_ms)) {
256 return false;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000257 }
Tom Cherry32228482018-01-18 16:14:25 -0800258
259 if (len == 0) {
260 *value = "";
261 return true;
262 }
263
264 // http://b/35166374: don't allow init to make arbitrarily large allocations.
265 if (len > 0xffff) {
266 LOG(ERROR) << "sys_prop: RecvString asked to read huge string: " << len;
267 errno = ENOMEM;
268 return false;
269 }
270
271 std::vector<char> chars(len);
272 if (!RecvChars(&chars[0], len, timeout_ms)) {
273 return false;
274 }
275
276 *value = std::string(&chars[0], len);
277 return true;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000278 }
279
Tom Cherry32228482018-01-18 16:14:25 -0800280 bool SendUint32(uint32_t value) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700281 if (!socket_.ok()) {
282 return true;
283 }
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800284 int result = TEMP_FAILURE_RETRY(send(socket_.get(), &value, sizeof(value), 0));
Tom Cherry32228482018-01-18 16:14:25 -0800285 return result == sizeof(value);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000286 }
287
Tom Cherry7f160af2019-04-22 13:28:28 -0700288 bool GetSourceContext(std::string* source_context) const {
289 char* c_source_context = nullptr;
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800290 if (getpeercon(socket_.get(), &c_source_context) != 0) {
Tom Cherry7f160af2019-04-22 13:28:28 -0700291 return false;
292 }
293 *source_context = c_source_context;
294 freecon(c_source_context);
295 return true;
296 }
297
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700298 [[nodiscard]] int Release() { return socket_.release(); }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000299
Tom Cherry32228482018-01-18 16:14:25 -0800300 const ucred& cred() { return cred_; }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000301
David Anderson0af9ab32022-10-07 00:19:55 -0700302 SocketConnection& operator=(SocketConnection&&) = default;
303
Tom Cherry32228482018-01-18 16:14:25 -0800304 private:
305 bool PollIn(uint32_t* timeout_ms) {
Bart Van Asschefdc0f892022-12-02 18:45:33 -0800306 struct pollfd ufd = {
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800307 .fd = socket_.get(),
Bart Van Asschefdc0f892022-12-02 18:45:33 -0800308 .events = POLLIN,
309 };
Tom Cherry32228482018-01-18 16:14:25 -0800310 while (*timeout_ms > 0) {
311 auto start_time = std::chrono::steady_clock::now();
Bart Van Asschefdc0f892022-12-02 18:45:33 -0800312 int nr = poll(&ufd, 1, *timeout_ms);
Tom Cherry32228482018-01-18 16:14:25 -0800313 auto now = std::chrono::steady_clock::now();
314 auto time_elapsed =
315 std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
316 uint64_t millis = time_elapsed.count();
317 *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
318
319 if (nr > 0) {
320 return true;
321 }
322
323 if (nr == 0) {
324 // Timeout
325 break;
326 }
327
328 if (nr < 0 && errno != EINTR) {
329 PLOG(ERROR) << "sys_prop: error waiting for uid " << cred_.uid
330 << " to send property message";
331 return false;
332 } else { // errno == EINTR
333 // Timer rounds milliseconds down in case of EINTR we want it to be rounded up
334 // to avoid slowing init down by causing EINTR with under millisecond timeout.
335 if (*timeout_ms > 0) {
336 --(*timeout_ms);
337 }
338 }
339 }
340
341 LOG(ERROR) << "sys_prop: timeout waiting for uid " << cred_.uid
342 << " to send property message.";
343 return false;
344 }
345
346 bool RecvFully(void* data_ptr, size_t size, uint32_t* timeout_ms) {
347 size_t bytes_left = size;
348 char* data = static_cast<char*>(data_ptr);
349 while (*timeout_ms > 0 && bytes_left > 0) {
350 if (!PollIn(timeout_ms)) {
351 return false;
352 }
353
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800354 int result = TEMP_FAILURE_RETRY(recv(socket_.get(), data, bytes_left, MSG_DONTWAIT));
Tom Cherry32228482018-01-18 16:14:25 -0800355 if (result <= 0) {
DuXiao40533592018-05-21 14:43:56 +0800356 PLOG(ERROR) << "sys_prop: recv error";
Tom Cherry32228482018-01-18 16:14:25 -0800357 return false;
358 }
359
360 bytes_left -= result;
361 data += result;
362 }
363
DuXiao40533592018-05-21 14:43:56 +0800364 if (bytes_left != 0) {
365 LOG(ERROR) << "sys_prop: recv data is not properly obtained.";
366 }
367
Tom Cherry32228482018-01-18 16:14:25 -0800368 return bytes_left == 0;
369 }
370
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700371 unique_fd socket_;
Tom Cherry32228482018-01-18 16:14:25 -0800372 ucred cred_;
Tom Cherry3da2ba62019-08-28 17:47:49 +0000373
David Anderson0af9ab32022-10-07 00:19:55 -0700374 DISALLOW_COPY_AND_ASSIGN(SocketConnection);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000375};
376
David Anderson0af9ab32022-10-07 00:19:55 -0700377class PersistWriteThread {
378 public:
379 PersistWriteThread();
380 void Write(std::string name, std::string value, SocketConnection socket);
381
382 private:
383 void Work();
384
385 private:
386 std::thread thread_;
387 std::mutex mutex_;
388 std::condition_variable cv_;
389 std::deque<std::tuple<std::string, std::string, SocketConnection>> work_;
390};
391
392static std::optional<uint32_t> PropertySet(const std::string& name, const std::string& value,
393 SocketConnection* socket, std::string* error) {
394 size_t valuelen = value.size();
395
396 if (!IsLegalPropertyName(name)) {
397 *error = "Illegal property name";
398 return {PROP_ERROR_INVALID_NAME};
399 }
400
401 if (auto result = IsLegalPropertyValue(name, value); !result.ok()) {
402 *error = result.error().message();
403 return {PROP_ERROR_INVALID_VALUE};
404 }
405
Paul Lawrence689adfa2023-07-18 08:39:10 -0700406 if (name == "sys.powerctl") {
407 // No action here - NotifyPropertyChange will trigger the appropriate action, and since this
408 // can come to the second thread, we mustn't call out to the __system_property_* functions
409 // which support multiple readers but only one mutator.
David Anderson0af9ab32022-10-07 00:19:55 -0700410 } else {
Paul Lawrence689adfa2023-07-18 08:39:10 -0700411 prop_info* pi = (prop_info*)__system_property_find(name.c_str());
412 if (pi != nullptr) {
413 // ro.* properties are actually "write-once".
414 if (StartsWith(name, "ro.")) {
415 *error = "Read-only property was already set";
416 return {PROP_ERROR_READ_ONLY_PROPERTY};
417 }
David Anderson0af9ab32022-10-07 00:19:55 -0700418
Paul Lawrence689adfa2023-07-18 08:39:10 -0700419 __system_property_update(pi, value.c_str(), valuelen);
420 } else {
421 int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
422 if (rc < 0) {
423 *error = "__system_property_add failed";
424 return {PROP_ERROR_SET_FAILED};
425 }
David Anderson0af9ab32022-10-07 00:19:55 -0700426 }
Paul Lawrence689adfa2023-07-18 08:39:10 -0700427
428 // Don't write properties to disk until after we have read all default
429 // properties to prevent them from being overwritten by default values.
Dennis Shenecf8e1c2023-09-18 19:52:52 +0000430 bool need_persist = StartsWith(name, "persist.") || StartsWith(name, "next_boot.");
431 if (socket && persistent_properties_loaded && need_persist) {
Paul Lawrence689adfa2023-07-18 08:39:10 -0700432 if (persist_write_thread) {
433 persist_write_thread->Write(name, value, std::move(*socket));
434 return {};
435 }
436 WritePersistentProperty(name, value);
437 }
David Anderson0af9ab32022-10-07 00:19:55 -0700438 }
439
440 NotifyPropertyChange(name, value);
441 return {PROP_SUCCESS};
442}
443
444// Helper for PropertySet, for the case where no socket is used, and therefore an asynchronous
445// return is not possible.
446static uint32_t PropertySetNoSocket(const std::string& name, const std::string& value,
447 std::string* error) {
448 auto ret = PropertySet(name, value, nullptr, error);
449 CHECK(ret.has_value());
450 return *ret;
451}
452
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700453static uint32_t SendControlMessage(const std::string& msg, const std::string& name, pid_t pid,
454 SocketConnection* socket, std::string* error) {
Tom Cherry802864c2020-03-12 14:29:25 -0700455 auto lock = std::lock_guard{accept_messages_lock};
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100456 if (!accept_messages) {
Elliott Hughesc9d44b82024-04-30 20:20:43 +0000457 // If we're already shutting down and you're asking us to stop something,
458 // just say we did (https://issuetracker.google.com/336223505).
459 if (msg == "stop") return PROP_SUCCESS;
460
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700461 *error = "Received control message after shutdown, ignoring";
462 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
463 }
464
Tom Cherry832f9f12020-03-10 11:47:24 -0700465 // We must release the fd before sending it to init, otherwise there will be a race with init.
466 // If init calls close() before Release(), then fdsan will see the wrong tag and abort().
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700467 int fd = -1;
Tom Cherry5310db82019-10-22 08:27:23 -0700468 if (socket != nullptr && SelinuxGetVendorAndroidVersion() > __ANDROID_API_Q__) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700469 fd = socket->Release();
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700470 }
471
Tom Cherry802864c2020-03-12 14:29:25 -0700472 bool queue_success = QueueControlMessage(msg, name, pid, fd);
473 if (!queue_success && fd != -1) {
474 uint32_t response = PROP_ERROR_HANDLE_CONTROL_MESSAGE;
475 TEMP_FAILURE_RETRY(send(fd, &response, sizeof(response), 0));
476 close(fd);
Tom Cherry832f9f12020-03-10 11:47:24 -0700477 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700478
479 return PROP_SUCCESS;
480}
481
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700482bool CheckControlPropertyPerms(const std::string& name, const std::string& value,
483 const std::string& source_context, const ucred& cr) {
484 // We check the legacy method first but these properties are dontaudit, so we only log an audit
485 // if the newer method fails as well. We only do this with the legacy ctl. properties.
486 if (name == "ctl.start" || name == "ctl.stop" || name == "ctl.restart") {
487 // The legacy permissions model is that ctl. properties have their name ctl.<action> and
488 // their value is the name of the service to apply that action to. Permissions for these
489 // actions are based on the service, so we must create a fake name of ctl.<service> to
490 // check permissions.
491 auto control_string_legacy = "ctl." + value;
492 const char* target_context_legacy = nullptr;
493 const char* type_legacy = nullptr;
494 property_info_area->GetPropertyInfo(control_string_legacy.c_str(), &target_context_legacy,
495 &type_legacy);
496
497 if (CheckMacPerms(control_string_legacy, target_context_legacy, source_context.c_str(), cr)) {
498 return true;
499 }
500 }
501
502 auto control_string_full = name + "$" + value;
503 const char* target_context_full = nullptr;
504 const char* type_full = nullptr;
505 property_info_area->GetPropertyInfo(control_string_full.c_str(), &target_context_full,
506 &type_full);
507
508 return CheckMacPerms(control_string_full, target_context_full, source_context.c_str(), cr);
509}
510
Tom Cherry32228482018-01-18 16:14:25 -0800511// This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
Tom Cherrybe048922019-02-16 12:03:19 -0800512uint32_t CheckPermissions(const std::string& name, const std::string& value,
513 const std::string& source_context, const ucred& cr, std::string* error) {
Tom Cherryde6bd502018-02-13 16:50:08 -0800514 if (!IsLegalPropertyName(name)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800515 *error = "Illegal property name";
Tom Cherry32228482018-01-18 16:14:25 -0800516 return PROP_ERROR_INVALID_NAME;
517 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000518
Tom Cherry32228482018-01-18 16:14:25 -0800519 if (StartsWith(name, "ctl.")) {
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700520 if (!CheckControlPropertyPerms(name, value, source_context, cr)) {
521 *error = StringPrintf("Invalid permissions to perform '%s' on '%s'", name.c_str() + 4,
522 value.c_str());
Tom Cherry32228482018-01-18 16:14:25 -0800523 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
524 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000525
Tom Cherry32228482018-01-18 16:14:25 -0800526 return PROP_SUCCESS;
527 }
Tom Cherry927c5d52017-12-11 01:40:07 -0800528
Tom Cherry32228482018-01-18 16:14:25 -0800529 const char* target_context = nullptr;
530 const char* type = nullptr;
531 property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type);
Tom Cherrya84e14d2017-09-05 12:38:30 -0700532
Tom Cherry32228482018-01-18 16:14:25 -0800533 if (!CheckMacPerms(name, target_context, source_context.c_str(), cr)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800534 *error = "SELinux permission check failed";
Tom Cherry32228482018-01-18 16:14:25 -0800535 return PROP_ERROR_PERMISSION_DENIED;
536 }
537
Tom Cherryb5f2ec02019-11-08 17:54:27 -0800538 if (!CheckType(type, value)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800539 *error = StringPrintf("Property type check failed, value doesn't match expected type '%s'",
540 (type ?: "(null)"));
Tom Cherry32228482018-01-18 16:14:25 -0800541 return PROP_ERROR_INVALID_VALUE;
542 }
543
Tom Cherrybe048922019-02-16 12:03:19 -0800544 return PROP_SUCCESS;
545}
546
David Anderson0af9ab32022-10-07 00:19:55 -0700547// This returns one of the enum of PROP_SUCCESS or PROP_ERROR*, or std::nullopt
548// if asynchronous.
549std::optional<uint32_t> HandlePropertySet(const std::string& name, const std::string& value,
550 const std::string& source_context, const ucred& cr,
551 SocketConnection* socket, std::string* error) {
Tom Cherrybe048922019-02-16 12:03:19 -0800552 if (auto ret = CheckPermissions(name, value, source_context, cr, error); ret != PROP_SUCCESS) {
David Anderson0af9ab32022-10-07 00:19:55 -0700553 return {ret};
Tom Cherrybe048922019-02-16 12:03:19 -0800554 }
555
556 if (StartsWith(name, "ctl.")) {
David Anderson0af9ab32022-10-07 00:19:55 -0700557 return {SendControlMessage(name.c_str() + 4, value, cr.pid, socket, error)};
Tom Cherrybe048922019-02-16 12:03:19 -0800558 }
559
Tom Cherry32228482018-01-18 16:14:25 -0800560 // sys.powerctl is a special property that is used to make the device reboot. We want to log
561 // any process that sets this property to be able to accurately blame the cause of a shutdown.
562 if (name == "sys.powerctl") {
563 std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
564 std::string process_cmdline;
565 std::string process_log_string;
566 if (ReadFileToString(cmdline_path, &process_cmdline)) {
567 // Since cmdline is null deliminated, .c_str() conveniently gives us just the process
568 // path.
569 process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
570 }
571 LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
572 << process_log_string;
Nikita Ioffe92116e42020-03-31 01:28:35 +0100573 if (value == "reboot,userspace" && !is_userspace_reboot_supported().value_or(false)) {
574 *error = "Userspace reboot is not supported by this device";
David Anderson0af9ab32022-10-07 00:19:55 -0700575 return {PROP_ERROR_INVALID_VALUE};
Nikita Ioffe92116e42020-03-31 01:28:35 +0100576 }
Tom Cherry32228482018-01-18 16:14:25 -0800577 }
578
Tom Cherryfe815412019-04-23 15:11:07 -0700579 // If a process other than init is writing a non-empty value, it means that process is
580 // requesting that init performs a restorecon operation on the path specified by 'value'.
581 // We use a thread to do this restorecon operation to prevent holding up init, as it may take
582 // a long time to complete.
583 if (name == kRestoreconProperty && cr.pid != 1 && !value.empty()) {
Tom Cherry832f9f12020-03-10 11:47:24 -0700584 static AsyncRestorecon async_restorecon;
585 async_restorecon.TriggerRestorecon(value);
David Anderson0af9ab32022-10-07 00:19:55 -0700586 return {PROP_SUCCESS};
Tom Cherry69d47aa2018-03-01 11:00:57 -0800587 }
588
David Anderson0af9ab32022-10-07 00:19:55 -0700589 return PropertySet(name, value, socket, error);
590}
591
592// Helper for HandlePropertySet, for the case where no socket is used, and
593// therefore an asynchronous return is not possible.
594uint32_t HandlePropertySetNoSocket(const std::string& name, const std::string& value,
595 const std::string& source_context, const ucred& cr,
596 std::string* error) {
597 auto ret = HandlePropertySet(name, value, source_context, cr, nullptr, error);
598 CHECK(ret.has_value());
599 return *ret;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000600}
601
Paul Lawrence689adfa2023-07-18 08:39:10 -0700602static void handle_property_set_fd(int fd) {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000603 static constexpr uint32_t kDefaultSocketTimeout = 2000; /* ms */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800604
Paul Lawrence689adfa2023-07-18 08:39:10 -0700605 int s = accept4(fd, nullptr, nullptr, SOCK_CLOEXEC);
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700606 if (s == -1) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800607 return;
608 }
609
Tom Cherry32228482018-01-18 16:14:25 -0800610 ucred cr;
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700611 socklen_t cr_size = sizeof(cr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800612 if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
613 close(s);
Elliott Hughesb005d902017-02-22 14:54:15 -0800614 PLOG(ERROR) << "sys_prop: unable to get SO_PEERCRED";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800615 return;
616 }
617
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000618 SocketConnection socket(s, cr);
619 uint32_t timeout_ms = kDefaultSocketTimeout;
620
621 uint32_t cmd = 0;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000622 if (!socket.RecvUint32(&cmd, &timeout_ms)) {
623 PLOG(ERROR) << "sys_prop: error while reading command from the socket";
624 socket.SendUint32(PROP_ERROR_READ_CMD);
JP Abgrall4515d812014-01-31 14:37:07 -0800625 return;
626 }
627
Elliott Hughesb005d902017-02-22 14:54:15 -0800628 switch (cmd) {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000629 case PROP_MSG_SETPROP: {
630 char prop_name[PROP_NAME_MAX];
631 char prop_value[PROP_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800632
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000633 if (!socket.RecvChars(prop_name, PROP_NAME_MAX, &timeout_ms) ||
634 !socket.RecvChars(prop_value, PROP_VALUE_MAX, &timeout_ms)) {
635 PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP): error while reading name/value from the socket";
636 return;
Nick Kralevich69463612013-09-13 17:21:28 -0700637 }
638
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000639 prop_name[PROP_NAME_MAX-1] = 0;
640 prop_value[PROP_VALUE_MAX-1] = 0;
rpcraig63207cd2012-08-09 10:05:49 -0400641
Tom Cherry7f160af2019-04-22 13:28:28 -0700642 std::string source_context;
643 if (!socket.GetSourceContext(&source_context)) {
644 PLOG(ERROR) << "Unable to set property '" << prop_name << "': getpeercon() failed";
645 return;
646 }
647
Tom Cherry69d47aa2018-03-01 11:00:57 -0800648 const auto& cr = socket.cred();
649 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -0700650 auto result = HandlePropertySetNoSocket(prop_name, prop_value, source_context, cr, &error);
Tom Cherry69d47aa2018-03-01 11:00:57 -0800651 if (result != PROP_SUCCESS) {
Nick Kralevich9ca898f2019-04-04 10:10:01 -0700652 LOG(ERROR) << "Unable to set property '" << prop_name << "' from uid:" << cr.uid
653 << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800654 }
655
Dimitry Ivanovdee4bd22017-01-19 14:53:00 -0800656 break;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000657 }
Dimitry Ivanov70c4ecf2017-01-24 18:38:09 +0000658
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000659 case PROP_MSG_SETPROP2: {
660 std::string name;
661 std::string value;
662 if (!socket.RecvString(&name, &timeout_ms) ||
663 !socket.RecvString(&value, &timeout_ms)) {
664 PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP2): error while reading name/value from the socket";
665 socket.SendUint32(PROP_ERROR_READ_DATA);
666 return;
667 }
668
Tom Cherry7f160af2019-04-22 13:28:28 -0700669 std::string source_context;
670 if (!socket.GetSourceContext(&source_context)) {
671 PLOG(ERROR) << "Unable to set property '" << name << "': getpeercon() failed";
672 socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
673 return;
674 }
675
David Anderson0af9ab32022-10-07 00:19:55 -0700676 // HandlePropertySet takes ownership of the socket if the set is handled asynchronously.
Tom Cherry69d47aa2018-03-01 11:00:57 -0800677 const auto& cr = socket.cred();
678 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -0700679 auto result = HandlePropertySet(name, value, source_context, cr, &socket, &error);
680 if (!result) {
681 // Result will be sent after completion.
682 return;
683 }
684 if (*result != PROP_SUCCESS) {
Nick Kralevich9ca898f2019-04-04 10:10:01 -0700685 LOG(ERROR) << "Unable to set property '" << name << "' from uid:" << cr.uid
686 << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800687 }
David Anderson0af9ab32022-10-07 00:19:55 -0700688 socket.SendUint32(*result);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000689 break;
690 }
Elliott Hughesb005d902017-02-22 14:54:15 -0800691
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800692 default:
Elliott Hughesb005d902017-02-22 14:54:15 -0800693 LOG(ERROR) << "sys_prop: invalid command " << cmd;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000694 socket.SendUint32(PROP_ERROR_INVALID_CMD);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800695 break;
696 }
697}
698
Tom Cherryc88d8f92019-08-19 15:21:25 -0700699uint32_t InitPropertySet(const std::string& name, const std::string& value) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700700 ucred cr = {.pid = 1, .uid = 0, .gid = 0};
701 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -0700702 auto result = HandlePropertySetNoSocket(name, value, kInitContext, cr, &error);
Tom Cherryc88d8f92019-08-19 15:21:25 -0700703 if (result != PROP_SUCCESS) {
704 LOG(ERROR) << "Init cannot set '" << name << "' to '" << value << "': " << error;
705 }
706
707 return result;
708}
709
Inseob Kim946c9722022-05-23 16:37:44 +0900710static Result<void> load_properties_from_file(const char*, const char*,
711 std::map<std::string, std::string>*);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800712
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800713/*
714 * Filter is used to decide which properties to load: NULL loads all keys,
715 * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
716 */
Tom Cherrybe048922019-02-16 12:03:19 -0800717static void LoadProperties(char* data, const char* filter, const char* filename,
718 std::map<std::string, std::string>* properties) {
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800719 char *key, *value, *eol, *sol, *tmp, *fn;
720 size_t flen = 0;
721
Yifan Hong9258f2e2020-07-15 17:04:43 -0700722 static constexpr const char* const kVendorPathPrefixes[4] = {
Tom Cherry14c24722019-09-18 13:47:19 -0700723 "/vendor",
724 "/odm",
Yifan Hong2ed3cda2020-06-24 18:29:22 -0700725 "/vendor_dlkm",
Yifan Hong9258f2e2020-07-15 17:04:43 -0700726 "/odm_dlkm",
Tom Cherry14c24722019-09-18 13:47:19 -0700727 };
728
729 const char* context = kInitContext;
Tom Cherry40acb372018-08-01 13:41:12 -0700730 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
Tom Cherry14c24722019-09-18 13:47:19 -0700731 for (const auto& vendor_path_prefix : kVendorPathPrefixes) {
732 if (StartsWith(filename, vendor_path_prefix)) {
733 context = kVendorContext;
Tom Cherrya1dbeb82018-04-11 15:50:00 -0700734 }
Tom Cherrydc375862018-02-28 10:39:01 -0800735 }
736 }
737
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800738 if (filter) {
739 flen = strlen(filter);
740 }
741
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800742 sol = data;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800743 while ((eol = strchr(sol, '\n'))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800744 key = sol;
745 *eol++ = 0;
746 sol = eol;
747
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800748 while (isspace(*key)) key++;
749 if (*key == '#') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800750
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800751 tmp = eol - 2;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800752 while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800753
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800754 if (!strncmp(key, "import ", 7) && flen == 0) {
755 fn = key + 7;
756 while (isspace(*fn)) fn++;
757
758 key = strchr(fn, ' ');
759 if (key) {
760 *key++ = 0;
761 while (isspace(*key)) key++;
762 }
763
Dongcheol Shina87c0f92019-06-12 09:31:35 +0900764 std::string raw_filename(fn);
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700765 auto expanded_filename = ExpandProps(raw_filename);
766
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900767 if (!expanded_filename.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700768 LOG(ERROR) << "Could not expand filename ': " << expanded_filename.error();
Dongcheol Shina87c0f92019-06-12 09:31:35 +0900769 continue;
770 }
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800771
Inseob Kim946c9722022-05-23 16:37:44 +0900772 if (auto res = load_properties_from_file(expanded_filename->c_str(), key, properties);
773 !res.ok()) {
774 LOG(WARNING) << res.error();
775 }
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800776 } else {
777 value = strchr(key, '=');
778 if (!value) continue;
779 *value++ = 0;
780
781 tmp = value - 2;
782 while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
783
784 while (isspace(*value)) value++;
785
786 if (flen > 0) {
787 if (filter[flen - 1] == '*') {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700788 if (strncmp(key, filter, flen - 1) != 0) continue;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800789 } else {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700790 if (strcmp(key, filter) != 0) continue;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800791 }
792 }
793
Tom Cherrydc375862018-02-28 10:39:01 -0800794 if (StartsWith(key, "ctl.") || key == "sys.powerctl"s ||
Tom Cherryfe815412019-04-23 15:11:07 -0700795 std::string{key} == kRestoreconProperty) {
Tom Cherrydc375862018-02-28 10:39:01 -0800796 LOG(ERROR) << "Ignoring disallowed property '" << key
797 << "' with special meaning in prop file '" << filename << "'";
798 continue;
799 }
800
Tom Cherrydc375862018-02-28 10:39:01 -0800801 ucred cr = {.pid = 1, .uid = 0, .gid = 0};
802 std::string error;
Tom Cherrybe048922019-02-16 12:03:19 -0800803 if (CheckPermissions(key, value, context, cr, &error) == PROP_SUCCESS) {
804 auto it = properties->find(key);
805 if (it == properties->end()) {
806 (*properties)[key] = value;
807 } else if (it->second != value) {
Jiyong Parke714cde2020-06-11 19:41:54 +0900808 LOG(WARNING) << "Overriding previous property '" << key << "':'" << it->second
809 << "' with new value '" << value << "'";
Tom Cherrybe048922019-02-16 12:03:19 -0800810 it->second = value;
811 }
812 } else {
813 LOG(ERROR) << "Do not have permissions to set '" << key << "' to '" << value
Tom Cherrydc375862018-02-28 10:39:01 -0800814 << "' in property file '" << filename << "': " << error;
815 }
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800816 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800817 }
818}
819
Elliott Hughes5a7ad842016-09-30 14:12:33 -0700820// Filter is used to decide which properties to load: NULL loads all keys,
821// "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
Inseob Kim946c9722022-05-23 16:37:44 +0900822static Result<void> load_properties_from_file(const char* filename, const char* filter,
823 std::map<std::string, std::string>* properties) {
Elliott Hughesda40c002015-03-27 23:20:44 -0700824 Timer t;
Tom Cherry62ca6632017-08-03 12:54:07 -0700825 auto file_contents = ReadFile(filename);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900826 if (!file_contents.ok()) {
Inseob Kim946c9722022-05-23 16:37:44 +0900827 return Error() << "Couldn't load property file '" << filename
828 << "': " << file_contents.error();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800829 }
Tom Cherry62ca6632017-08-03 12:54:07 -0700830 file_contents->push_back('\n');
Tom Cherrydc375862018-02-28 10:39:01 -0800831
Tom Cherrybe048922019-02-16 12:03:19 -0800832 LoadProperties(file_contents->data(), filter, filename, properties);
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000833 LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
Inseob Kim946c9722022-05-23 16:37:44 +0900834 return {};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800835}
836
Yifan Honga68ee762020-10-06 16:58:19 -0700837static void LoadPropertiesFromSecondStageRes(std::map<std::string, std::string>* properties) {
838 std::string prop = GetRamdiskPropForSecondStage();
839 if (access(prop.c_str(), R_OK) != 0) {
840 CHECK(errno == ENOENT) << "Cannot access " << prop << ": " << strerror(errno);
841 return;
842 }
Inseob Kim946c9722022-05-23 16:37:44 +0900843 if (auto res = load_properties_from_file(prop.c_str(), nullptr, properties); !res.ok()) {
844 LOG(WARNING) << res.error();
845 }
Yifan Honga68ee762020-10-06 16:58:19 -0700846}
847
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900848// persist.sys.usb.config values can't be combined on build-time when property
849// files are split into each partition.
850// So we need to apply the same rule of build/make/tools/post_process_props.py
851// on runtime.
852static void update_sys_usb_config() {
853 bool is_debuggable = android::base::GetBoolProperty("ro.debuggable", false);
854 std::string config = android::base::GetProperty("persist.sys.usb.config", "");
Howard Yenbb578202020-02-26 21:36:59 +0800855 // b/150130503, add (config == "none") condition here to prevent appending
856 // ",adb" if "none" is explicitly defined in default prop.
857 if (config.empty() || config == "none") {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700858 InitPropertySet("persist.sys.usb.config", is_debuggable ? "adb" : "none");
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900859 } else if (is_debuggable && config.find("adb") == std::string::npos &&
860 config.length() + 4 < PROP_VALUE_MAX) {
861 config.append(",adb");
Tom Cherryc88d8f92019-08-19 15:21:25 -0700862 InitPropertySet("persist.sys.usb.config", config);
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900863 }
864}
865
Nick Kralevich32b90232012-09-19 11:15:24 -0700866static void load_override_properties() {
Elliott Hughesc0e919c2015-02-04 14:46:36 -0800867 if (ALLOW_LOCAL_PROP_OVERRIDE) {
Tom Cherrybe048922019-02-16 12:03:19 -0800868 std::map<std::string, std::string> properties;
869 load_properties_from_file("/data/local.prop", nullptr, &properties);
870 for (const auto& [name, value] : properties) {
871 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -0700872 if (PropertySetNoSocket(name, value, &error) != PROP_SUCCESS) {
Tom Cherrybe048922019-02-16 12:03:19 -0800873 LOG(ERROR) << "Could not set '" << name << "' to '" << value
874 << "' in /data/local.prop: " << error;
875 }
876 }
Nick Kralevich32b90232012-09-19 11:15:24 -0700877 }
Nick Kralevich32b90232012-09-19 11:15:24 -0700878}
879
Steven Laver57a740e2019-01-29 20:19:05 -0800880// If the ro.product.[brand|device|manufacturer|model|name] properties have not been explicitly
881// set, derive them from ro.product.${partition}.* properties
882static void property_initialize_ro_product_props() {
883 const char* RO_PRODUCT_PROPS_PREFIX = "ro.product.";
884 const char* RO_PRODUCT_PROPS[] = {
885 "brand", "device", "manufacturer", "model", "name",
886 };
887 const char* RO_PRODUCT_PROPS_ALLOWED_SOURCES[] = {
Justin Yun7eaf9b52019-06-28 14:28:00 +0900888 "odm", "product", "system_ext", "system", "vendor",
Steven Laver57a740e2019-01-29 20:19:05 -0800889 };
Justin Yun7eaf9b52019-06-28 14:28:00 +0900890 const char* RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER = "product,odm,vendor,system_ext,system";
Steven Laver57a740e2019-01-29 20:19:05 -0800891 const std::string EMPTY = "";
892
893 std::string ro_product_props_source_order =
894 GetProperty("ro.product.property_source_order", EMPTY);
895
896 if (!ro_product_props_source_order.empty()) {
897 // Verify that all specified sources are valid
898 for (const auto& source : Split(ro_product_props_source_order, ",")) {
899 // Verify that the specified source is valid
900 bool is_allowed_source = false;
901 for (const auto& allowed_source : RO_PRODUCT_PROPS_ALLOWED_SOURCES) {
902 if (source == allowed_source) {
903 is_allowed_source = true;
904 break;
905 }
906 }
907 if (!is_allowed_source) {
908 LOG(ERROR) << "Found unexpected source in ro.product.property_source_order; "
909 "using the default property source order";
910 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
911 break;
912 }
913 }
914 } else {
915 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
916 }
917
918 for (const auto& ro_product_prop : RO_PRODUCT_PROPS) {
919 std::string base_prop(RO_PRODUCT_PROPS_PREFIX);
920 base_prop += ro_product_prop;
921
922 std::string base_prop_val = GetProperty(base_prop, EMPTY);
923 if (!base_prop_val.empty()) {
924 continue;
925 }
926
927 for (const auto& source : Split(ro_product_props_source_order, ",")) {
928 std::string target_prop(RO_PRODUCT_PROPS_PREFIX);
929 target_prop += source;
930 target_prop += '.';
931 target_prop += ro_product_prop;
932
933 std::string target_prop_val = GetProperty(target_prop, EMPTY);
934 if (!target_prop_val.empty()) {
935 LOG(INFO) << "Setting product property " << base_prop << " to '" << target_prop_val
936 << "' (from " << target_prop << ")";
937 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -0700938 auto res = PropertySetNoSocket(base_prop, target_prop_val, &error);
Steven Laver57a740e2019-01-29 20:19:05 -0800939 if (res != PROP_SUCCESS) {
940 LOG(ERROR) << "Error setting product property " << base_prop << ": err=" << res
941 << " (" << error << ")";
942 }
943 break;
944 }
945 }
946 }
947}
948
Tianjiebecfa772021-05-05 17:23:46 -0700949static void property_initialize_build_id() {
950 std::string build_id = GetProperty(ID_PROP, "");
951 if (!build_id.empty()) {
Steven Laver57a740e2019-01-29 20:19:05 -0800952 return;
953 }
954
Tianjiebecfa772021-05-05 17:23:46 -0700955 std::string legacy_build_id = GetProperty(LEGACY_ID_PROP, "");
956 std::string vbmeta_digest = GetProperty(VBMETA_DIGEST_PROP, "");
957 if (vbmeta_digest.size() < DIGEST_SIZE_USED) {
958 LOG(ERROR) << "vbmeta digest size too small " << vbmeta_digest;
959 // Still try to set the id field in the unexpected case.
960 build_id = legacy_build_id;
961 } else {
962 // Derive the ro.build.id by appending the vbmeta digest to the base value.
963 build_id = legacy_build_id + "." + vbmeta_digest.substr(0, DIGEST_SIZE_USED);
964 }
965
966 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -0700967 auto res = PropertySetNoSocket(ID_PROP, build_id, &error);
Tianjiebecfa772021-05-05 17:23:46 -0700968 if (res != PROP_SUCCESS) {
969 LOG(ERROR) << "Failed to set " << ID_PROP << " to " << build_id;
970 }
971}
972
973static std::string ConstructBuildFingerprint(bool legacy) {
Steven Laver57a740e2019-01-29 20:19:05 -0800974 const std::string UNKNOWN = "unknown";
Tianjiebecfa772021-05-05 17:23:46 -0700975 std::string build_fingerprint = GetProperty("ro.product.brand", UNKNOWN);
Steven Laver57a740e2019-01-29 20:19:05 -0800976 build_fingerprint += '/';
977 build_fingerprint += GetProperty("ro.product.name", UNKNOWN);
Steven Moreland188d59a2024-05-15 20:03:53 +0000978
979 // should be set in /product/etc/build.prop
980 // when we have a dev option device, and we've switched the kernel to 16kb mode
981 // we use the same system image, but we've switched out the kernel, so make it
982 // visible at a high level
983 bool has16KbDevOption =
984 android::base::GetBoolProperty("ro.product.build.16k_page.enabled", false);
985 if (has16KbDevOption && getpagesize() == 16384) {
986 build_fingerprint += "_16kb";
987 }
988
Steven Laver57a740e2019-01-29 20:19:05 -0800989 build_fingerprint += '/';
990 build_fingerprint += GetProperty("ro.product.device", UNKNOWN);
991 build_fingerprint += ':';
Colin Crossb519c712020-10-13 12:38:48 -0700992 build_fingerprint += GetProperty("ro.build.version.release_or_codename", UNKNOWN);
Steven Laver57a740e2019-01-29 20:19:05 -0800993 build_fingerprint += '/';
Tianjiebecfa772021-05-05 17:23:46 -0700994
995 std::string build_id =
996 legacy ? GetProperty(LEGACY_ID_PROP, UNKNOWN) : GetProperty(ID_PROP, UNKNOWN);
997 build_fingerprint += build_id;
Steven Laver57a740e2019-01-29 20:19:05 -0800998 build_fingerprint += '/';
999 build_fingerprint += GetProperty("ro.build.version.incremental", UNKNOWN);
1000 build_fingerprint += ':';
1001 build_fingerprint += GetProperty("ro.build.type", UNKNOWN);
1002 build_fingerprint += '/';
1003 build_fingerprint += GetProperty("ro.build.tags", UNKNOWN);
1004
Tianjiebecfa772021-05-05 17:23:46 -07001005 return build_fingerprint;
1006}
1007
1008// Derive the legacy build fingerprint if we overwrite the build id at runtime.
1009static void property_derive_legacy_build_fingerprint() {
1010 std::string legacy_build_fingerprint = GetProperty(LEGACY_FINGERPRINT_PROP, "");
1011 if (!legacy_build_fingerprint.empty()) {
1012 return;
1013 }
1014
1015 // The device doesn't have a legacy build id, skipping the legacy fingerprint.
1016 std::string legacy_build_id = GetProperty(LEGACY_ID_PROP, "");
1017 if (legacy_build_id.empty()) {
1018 return;
1019 }
1020
1021 legacy_build_fingerprint = ConstructBuildFingerprint(true /* legacy fingerprint */);
1022 LOG(INFO) << "Setting property '" << LEGACY_FINGERPRINT_PROP << "' to '"
1023 << legacy_build_fingerprint << "'";
Steven Laver57a740e2019-01-29 20:19:05 -08001024
1025 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -07001026 auto res = PropertySetNoSocket(LEGACY_FINGERPRINT_PROP, legacy_build_fingerprint, &error);
Steven Laver57a740e2019-01-29 20:19:05 -08001027 if (res != PROP_SUCCESS) {
Tianjiebecfa772021-05-05 17:23:46 -07001028 LOG(ERROR) << "Error setting property '" << LEGACY_FINGERPRINT_PROP << "': err=" << res
1029 << " (" << error << ")";
1030 }
1031}
1032
1033// If the ro.build.fingerprint property has not been set, derive it from constituent pieces
1034static void property_derive_build_fingerprint() {
1035 std::string build_fingerprint = GetProperty("ro.build.fingerprint", "");
1036 if (!build_fingerprint.empty()) {
1037 return;
1038 }
1039
1040 build_fingerprint = ConstructBuildFingerprint(false /* legacy fingerprint */);
1041 LOG(INFO) << "Setting property '" << FINGERPRINT_PROP << "' to '" << build_fingerprint << "'";
1042
1043 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -07001044 auto res = PropertySetNoSocket(FINGERPRINT_PROP, build_fingerprint, &error);
Tianjiebecfa772021-05-05 17:23:46 -07001045 if (res != PROP_SUCCESS) {
1046 LOG(ERROR) << "Error setting property '" << FINGERPRINT_PROP << "': err=" << res << " ("
1047 << error << ")";
Steven Laver57a740e2019-01-29 20:19:05 -08001048 }
1049}
1050
SzuWei Lin0061d4d2020-12-31 16:52:39 +08001051// If the ro.product.cpu.abilist* properties have not been explicitly
1052// set, derive them from ro.${partition}.product.cpu.abilist* properties.
1053static void property_initialize_ro_cpu_abilist() {
1054 // From high to low priority.
1055 const char* kAbilistSources[] = {
1056 "product",
1057 "odm",
1058 "vendor",
1059 "system",
1060 };
1061 const std::string EMPTY = "";
1062 const char* kAbilistProp = "ro.product.cpu.abilist";
1063 const char* kAbilist32Prop = "ro.product.cpu.abilist32";
1064 const char* kAbilist64Prop = "ro.product.cpu.abilist64";
1065
1066 // If the properties are defined explicitly, just use them.
1067 if (GetProperty(kAbilistProp, EMPTY) != EMPTY) {
1068 return;
1069 }
1070
1071 // Find the first source defining these properties by order.
1072 std::string abilist32_prop_val;
1073 std::string abilist64_prop_val;
1074 for (const auto& source : kAbilistSources) {
1075 const auto abilist32_prop = std::string("ro.") + source + ".product.cpu.abilist32";
1076 const auto abilist64_prop = std::string("ro.") + source + ".product.cpu.abilist64";
1077 abilist32_prop_val = GetProperty(abilist32_prop, EMPTY);
1078 abilist64_prop_val = GetProperty(abilist64_prop, EMPTY);
1079 // The properties could be empty on 32-bit-only or 64-bit-only devices,
1080 // but we cannot identify a property is empty or undefined by GetProperty().
1081 // So, we assume both of these 2 properties are empty as undefined.
1082 if (abilist32_prop_val != EMPTY || abilist64_prop_val != EMPTY) {
1083 break;
1084 }
1085 }
1086
1087 // Merge ABI lists for ro.product.cpu.abilist
1088 auto abilist_prop_val = abilist64_prop_val;
1089 if (abilist32_prop_val != EMPTY) {
1090 if (abilist_prop_val != EMPTY) {
1091 abilist_prop_val += ",";
1092 }
1093 abilist_prop_val += abilist32_prop_val;
1094 }
1095
1096 // Set these properties
1097 const std::pair<const char*, const std::string&> set_prop_list[] = {
1098 {kAbilistProp, abilist_prop_val},
1099 {kAbilist32Prop, abilist32_prop_val},
1100 {kAbilist64Prop, abilist64_prop_val},
1101 };
1102 for (const auto& [prop, prop_val] : set_prop_list) {
1103 LOG(INFO) << "Setting property '" << prop << "' to '" << prop_val << "'";
1104
1105 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -07001106 auto res = PropertySetNoSocket(prop, prop_val, &error);
SzuWei Lin0061d4d2020-12-31 16:52:39 +08001107 if (res != PROP_SUCCESS) {
1108 LOG(ERROR) << "Error setting property '" << prop << "': err=" << res << " (" << error
1109 << ")";
1110 }
1111 }
1112}
1113
Justin Yundfbdd932021-09-29 15:37:27 +09001114static void property_initialize_ro_vendor_api_level() {
1115 // ro.vendor.api_level shows the api_level that the vendor images (vendor, odm, ...) are
1116 // required to support.
1117 constexpr auto VENDOR_API_LEVEL_PROP = "ro.vendor.api_level";
Justin Yundfbdd932021-09-29 15:37:27 +09001118
Justin Yun4058ba22024-02-28 21:03:41 +09001119 if (__system_property_find(VENDOR_API_LEVEL_PROP) != nullptr) {
1120 // The device already have ro.vendor.api_level in its vendor/build.prop.
1121 // Skip initializing the ro.vendor.api_level property.
1122 return;
1123 }
1124
Justin Yun6bc1bfe2024-01-10 13:47:02 +09001125 auto vendor_api_level = GetIntProperty("ro.board.first_api_level", __ANDROID_VENDOR_API_MAX__);
1126 if (vendor_api_level != __ANDROID_VENDOR_API_MAX__) {
Justin Yun29192392023-12-07 22:22:53 +00001127 // Update the vendor_api_level with "ro.board.api_level" only if both "ro.board.api_level"
1128 // and "ro.board.first_api_level" are defined.
1129 vendor_api_level = GetIntProperty("ro.board.api_level", vendor_api_level);
1130 }
Justin Yun4446a852021-10-13 18:13:28 +09001131
Justin Yun29192392023-12-07 22:22:53 +00001132 auto product_first_api_level =
1133 GetIntProperty("ro.product.first_api_level", __ANDROID_API_FUTURE__);
1134 if (product_first_api_level == __ANDROID_API_FUTURE__) {
1135 // Fallback to "ro.build.version.sdk" if the "ro.product.first_api_level" is not defined.
1136 product_first_api_level = GetIntProperty("ro.build.version.sdk", __ANDROID_API_FUTURE__);
1137 }
1138
Justin Yun8ce23dc2024-02-15 15:46:59 +09001139 vendor_api_level =
1140 std::min(AVendorSupport_getVendorApiLevelOf(product_first_api_level), vendor_api_level);
Justin Yun29192392023-12-07 22:22:53 +00001141
Justin Yun6bc1bfe2024-01-10 13:47:02 +09001142 if (vendor_api_level < 0) {
1143 LOG(ERROR) << "Unexpected vendor api level for " << VENDOR_API_LEVEL_PROP << ". Check "
1144 << "ro.product.first_api_level and ro.build.version.sdk.";
1145 vendor_api_level = __ANDROID_VENDOR_API_MAX__;
1146 }
1147
Justin Yun4446a852021-10-13 18:13:28 +09001148 std::string error;
Justin Yun29192392023-12-07 22:22:53 +00001149 auto res = PropertySetNoSocket(VENDOR_API_LEVEL_PROP, std::to_string(vendor_api_level), &error);
Justin Yun4446a852021-10-13 18:13:28 +09001150 if (res != PROP_SUCCESS) {
Justin Yun29192392023-12-07 22:22:53 +00001151 LOG(ERROR) << "Failed to set " << VENDOR_API_LEVEL_PROP << " with " << vendor_api_level
1152 << ": " << error << "(" << res << ")";
Justin Yundfbdd932021-09-29 15:37:27 +09001153 }
Justin Yundfbdd932021-09-29 15:37:27 +09001154}
1155
Tom Cherryc88d8f92019-08-19 15:21:25 -07001156void PropertyLoadBootDefaults() {
Tom Cherrybe048922019-02-16 12:03:19 -08001157 // We read the properties and their values into a map, in order to always allow properties
1158 // loaded in the later property files to override the properties in loaded in the earlier
1159 // property files, regardless of if they are "ro." properties or not.
1160 std::map<std::string, std::string> properties;
Jiyong Parkc068d0e2020-05-11 16:47:05 +09001161
1162 if (IsRecoveryMode()) {
Inseob Kim946c9722022-05-23 16:37:44 +09001163 if (auto res = load_properties_from_file("/prop.default", nullptr, &properties);
1164 !res.ok()) {
1165 LOG(ERROR) << res.error();
1166 }
Jiyong Park3b316ee2019-01-13 02:42:31 +09001167 }
Jiyong Parkc068d0e2020-05-11 16:47:05 +09001168
Jiyong Park8178c5f2020-06-29 10:42:03 +09001169 // /<part>/etc/build.prop is the canonical location of the build-time properties since S.
1170 // Falling back to /<part>/defalt.prop and /<part>/build.prop only when legacy path has to
1171 // be supported, which is controlled by the support_legacy_path_until argument.
1172 const auto load_properties_from_partition = [&properties](const std::string& partition,
1173 int support_legacy_path_until) {
1174 auto path = "/" + partition + "/etc/build.prop";
Inseob Kim946c9722022-05-23 16:37:44 +09001175 if (load_properties_from_file(path.c_str(), nullptr, &properties).ok()) {
Jiyong Park8178c5f2020-06-29 10:42:03 +09001176 return;
1177 }
1178 // To read ro.<partition>.build.version.sdk, temporarily load the legacy paths into a
1179 // separate map. Then by comparing its value with legacy_version, we know that if the
1180 // partition is old enough so that we need to respect the legacy paths.
1181 std::map<std::string, std::string> temp;
1182 auto legacy_path1 = "/" + partition + "/default.prop";
1183 auto legacy_path2 = "/" + partition + "/build.prop";
1184 load_properties_from_file(legacy_path1.c_str(), nullptr, &temp);
1185 load_properties_from_file(legacy_path2.c_str(), nullptr, &temp);
1186 bool support_legacy_path = false;
1187 auto version_prop_name = "ro." + partition + ".build.version.sdk";
1188 auto it = temp.find(version_prop_name);
1189 if (it == temp.end()) {
1190 // This is embarassing. Without the prop, we can't determine how old the partition is.
1191 // Let's be conservative by assuming it is very very old.
1192 support_legacy_path = true;
1193 } else if (int value;
1194 ParseInt(it->second.c_str(), &value) && value <= support_legacy_path_until) {
1195 support_legacy_path = true;
1196 }
1197 if (support_legacy_path) {
1198 // We don't update temp into properties directly as it might skip any (future) logic
1199 // for resolving duplicates implemented in load_properties_from_file. Instead, read
1200 // the files again into the properties map.
1201 load_properties_from_file(legacy_path1.c_str(), nullptr, &properties);
1202 load_properties_from_file(legacy_path2.c_str(), nullptr, &properties);
1203 } else {
1204 LOG(FATAL) << legacy_path1 << " and " << legacy_path2 << " were not loaded "
1205 << "because " << version_prop_name << "(" << it->second << ") is newer "
1206 << "than " << support_legacy_path_until;
1207 }
1208 };
1209
1210 // Order matters here. The more the partition is specific to a product, the higher its
1211 // precedence is.
Yifan Honga68ee762020-10-06 16:58:19 -07001212 LoadPropertiesFromSecondStageRes(&properties);
Inseob Kim946c9722022-05-23 16:37:44 +09001213
1214 // system should have build.prop, unlike the other partitions
1215 if (auto res = load_properties_from_file("/system/build.prop", nullptr, &properties);
1216 !res.ok()) {
1217 LOG(WARNING) << res.error();
1218 }
1219
Jiyong Park8178c5f2020-06-29 10:42:03 +09001220 load_properties_from_partition("system_ext", /* support_legacy_path_until */ 30);
Ramji Jiyani84313282022-01-28 02:34:29 +00001221 load_properties_from_file("/system_dlkm/etc/build.prop", nullptr, &properties);
Jiyong Park8178c5f2020-06-29 10:42:03 +09001222 // TODO(b/117892318): uncomment the following condition when vendor.imgs for aosp_* targets are
1223 // all updated.
1224 // if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_R__) {
1225 load_properties_from_file("/vendor/default.prop", nullptr, &properties);
1226 // }
Tom Cherrybe048922019-02-16 12:03:19 -08001227 load_properties_from_file("/vendor/build.prop", nullptr, &properties);
Yifan Hong2ed3cda2020-06-24 18:29:22 -07001228 load_properties_from_file("/vendor_dlkm/etc/build.prop", nullptr, &properties);
Yifan Hong9258f2e2020-07-15 17:04:43 -07001229 load_properties_from_file("/odm_dlkm/etc/build.prop", nullptr, &properties);
Jiyong Park8178c5f2020-06-29 10:42:03 +09001230 load_properties_from_partition("odm", /* support_legacy_path_until */ 28);
1231 load_properties_from_partition("product", /* support_legacy_path_until */ 30);
Jiyong Park85695522020-05-11 15:59:44 +09001232
Tom Cherryc88d8f92019-08-19 15:21:25 -07001233 if (access(kDebugRamdiskProp, R_OK) == 0) {
Bowgo Tsai30afda72019-04-11 23:57:24 +08001234 LOG(INFO) << "Loading " << kDebugRamdiskProp;
Inseob Kim946c9722022-05-23 16:37:44 +09001235 if (auto res = load_properties_from_file(kDebugRamdiskProp, nullptr, &properties);
1236 !res.ok()) {
1237 LOG(WARNING) << res.error();
1238 }
Bowgo Tsai1dacd422019-03-04 17:53:34 +08001239 }
1240
Tom Cherrybe048922019-02-16 12:03:19 -08001241 for (const auto& [name, value] : properties) {
1242 std::string error;
David Anderson0af9ab32022-10-07 00:19:55 -07001243 if (PropertySetNoSocket(name, value, &error) != PROP_SUCCESS) {
Tom Cherrybe048922019-02-16 12:03:19 -08001244 LOG(ERROR) << "Could not set '" << name << "' to '" << value
1245 << "' while loading .prop files" << error;
1246 }
1247 }
Jiyong Park3b316ee2019-01-13 02:42:31 +09001248
Steven Laver57a740e2019-01-29 20:19:05 -08001249 property_initialize_ro_product_props();
Tianjiebecfa772021-05-05 17:23:46 -07001250 property_initialize_build_id();
Steven Laver57a740e2019-01-29 20:19:05 -08001251 property_derive_build_fingerprint();
Tianjiebecfa772021-05-05 17:23:46 -07001252 property_derive_legacy_build_fingerprint();
SzuWei Lin0061d4d2020-12-31 16:52:39 +08001253 property_initialize_ro_cpu_abilist();
Justin Yundfbdd932021-09-29 15:37:27 +09001254 property_initialize_ro_vendor_api_level();
Steven Laver57a740e2019-01-29 20:19:05 -08001255
Jiyong Park3b316ee2019-01-13 02:42:31 +09001256 update_sys_usb_config();
Riley Andrewse4b7b292014-06-16 15:06:21 -07001257}
1258
Tom Cherry2ae2f602017-12-14 01:58:17 +00001259bool LoadPropertyInfoFromFile(const std::string& filename,
1260 std::vector<PropertyInfoEntry>* property_infos) {
1261 auto file_contents = std::string();
1262 if (!ReadFileToString(filename, &file_contents)) {
1263 PLOG(ERROR) << "Could not read properties from '" << filename << "'";
1264 return false;
1265 }
1266
Tom Cherry919458c2018-01-03 14:39:28 -08001267 auto errors = std::vector<std::string>{};
Tom Cherry4b077c52019-12-11 07:56:51 -08001268 bool require_prefix_or_exact = SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__;
1269 ParsePropertyInfoFile(file_contents, require_prefix_or_exact, property_infos, &errors);
Tom Cherry919458c2018-01-03 14:39:28 -08001270 // Individual parsing errors are reported but do not cause a failed boot, which is what
1271 // returning false would do here.
1272 for (const auto& error : errors) {
1273 LOG(ERROR) << "Could not read line from '" << filename << "': " << error;
Tom Cherry2ae2f602017-12-14 01:58:17 +00001274 }
Tom Cherry919458c2018-01-03 14:39:28 -08001275
Tom Cherry2ae2f602017-12-14 01:58:17 +00001276 return true;
1277}
1278
1279void CreateSerializedPropertyInfo() {
1280 auto property_infos = std::vector<PropertyInfoEntry>();
1281 if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
1282 if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",
1283 &property_infos)) {
1284 return;
1285 }
Tom Cherry2d451662020-07-27 11:20:29 -07001286 // Don't check for failure here, since we don't always have all of these partitions.
Tom Cherry2ae2f602017-12-14 01:58:17 +00001287 // E.g. In case of recovery, the vendor partition will not have mounted and we
1288 // still need the system / platform properties to function.
Bowgo Tsai1a191bf2019-10-02 16:23:32 +08001289 if (access("/system_ext/etc/selinux/system_ext_property_contexts", R_OK) != -1) {
1290 LoadPropertyInfoFromFile("/system_ext/etc/selinux/system_ext_property_contexts",
1291 &property_infos);
1292 }
Jeff Vander Stoep5effda42021-11-05 09:03:11 +01001293 if (access("/vendor/etc/selinux/vendor_property_contexts", R_OK) != -1) {
1294 LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",
Bowgo Tsai36cf3532017-12-07 16:05:25 +08001295 &property_infos);
1296 }
Jinguang Dongf42e08d2019-02-15 16:56:28 +08001297 if (access("/product/etc/selinux/product_property_contexts", R_OK) != -1) {
1298 LoadPropertyInfoFromFile("/product/etc/selinux/product_property_contexts",
1299 &property_infos);
1300 }
1301 if (access("/odm/etc/selinux/odm_property_contexts", R_OK) != -1) {
1302 LoadPropertyInfoFromFile("/odm/etc/selinux/odm_property_contexts", &property_infos);
1303 }
Tom Cherry2ae2f602017-12-14 01:58:17 +00001304 } else {
1305 if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {
1306 return;
1307 }
Bowgo Tsai1a191bf2019-10-02 16:23:32 +08001308 LoadPropertyInfoFromFile("/system_ext_property_contexts", &property_infos);
Jeff Vander Stoep5effda42021-11-05 09:03:11 +01001309 LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos);
Jinguang Dongf42e08d2019-02-15 16:56:28 +08001310 LoadPropertyInfoFromFile("/product_property_contexts", &property_infos);
1311 LoadPropertyInfoFromFile("/odm_property_contexts", &property_infos);
Tom Cherry2ae2f602017-12-14 01:58:17 +00001312 }
Tom Cherry927c5d52017-12-11 01:40:07 -08001313
Tom Cherry2ae2f602017-12-14 01:58:17 +00001314 auto serialized_contexts = std::string();
1315 auto error = std::string();
Tom Cherry927c5d52017-12-11 01:40:07 -08001316 if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,
Tom Cherry2ae2f602017-12-14 01:58:17 +00001317 &error)) {
1318 LOG(ERROR) << "Unable to serialize property contexts: " << error;
1319 return;
1320 }
1321
Nate Myrenc25abe42023-08-25 14:30:50 -07001322 if (!WriteStringToFile(serialized_contexts, PROP_TREE_FILE, 0444, 0, 0, false)) {
Tom Cherry2ae2f602017-12-14 01:58:17 +00001323 PLOG(ERROR) << "Unable to write serialized property infos to file";
1324 }
Nate Myrenc25abe42023-08-25 14:30:50 -07001325 selinux_android_restorecon(PROP_TREE_FILE, 0);
1326
Nate Myrenb9e05452024-05-28 23:40:59 +00001327#ifdef WRITE_APPCOMPAT_OVERRIDE_SYSTEM_PROPERTIES
Nate Myrenc25abe42023-08-25 14:30:50 -07001328 mkdir(APPCOMPAT_OVERRIDE_PROP_FOLDERNAME, S_IRWXU | S_IXGRP | S_IXOTH);
1329 if (!WriteStringToFile(serialized_contexts, APPCOMPAT_OVERRIDE_PROP_TREE_FILE, 0444, 0, 0,
1330 false)) {
Nate Myren5ae7a802023-08-25 14:30:50 -07001331 PLOG(ERROR) << "Unable to write appcompat override property infos to file";
Nate Myrenc25abe42023-08-25 14:30:50 -07001332 }
1333 selinux_android_restorecon(APPCOMPAT_OVERRIDE_PROP_TREE_FILE, 0);
Nate Myrenb9e05452024-05-28 23:40:59 +00001334#endif
Tom Cherry2ae2f602017-12-14 01:58:17 +00001335}
1336
Tom Cherryc88d8f92019-08-19 15:21:25 -07001337static void ExportKernelBootProps() {
1338 constexpr const char* UNSET = "";
1339 struct {
1340 const char* src_prop;
1341 const char* dst_prop;
1342 const char* default_value;
1343 } prop_map[] = {
1344 // clang-format off
1345 { "ro.boot.serialno", "ro.serialno", UNSET, },
1346 { "ro.boot.mode", "ro.bootmode", "unknown", },
1347 { "ro.boot.baseband", "ro.baseband", "unknown", },
1348 { "ro.boot.bootloader", "ro.bootloader", "unknown", },
1349 { "ro.boot.hardware", "ro.hardware", "unknown", },
1350 { "ro.boot.revision", "ro.revision", "0", },
1351 // clang-format on
1352 };
1353 for (const auto& prop : prop_map) {
1354 std::string value = GetProperty(prop.src_prop, prop.default_value);
1355 if (value != UNSET) InitPropertySet(prop.dst_prop, value);
1356 }
1357}
1358
1359static void ProcessKernelDt() {
1360 if (!is_android_dt_value_expected("compatible", "android,firmware")) {
1361 return;
1362 }
1363
Yi-Yo Chiangb8c23252023-07-25 22:08:55 +08001364 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(android::fs_mgr::GetAndroidDtDir().c_str()),
1365 closedir);
Tom Cherryc88d8f92019-08-19 15:21:25 -07001366 if (!dir) return;
1367
1368 std::string dt_file;
1369 struct dirent* dp;
1370 while ((dp = readdir(dir.get())) != NULL) {
1371 if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") ||
1372 !strcmp(dp->d_name, "name")) {
1373 continue;
1374 }
1375
Yi-Yo Chiangb8c23252023-07-25 22:08:55 +08001376 std::string file_name = android::fs_mgr::GetAndroidDtDir() + dp->d_name;
Tom Cherryc88d8f92019-08-19 15:21:25 -07001377
1378 android::base::ReadFileToString(file_name, &dt_file);
1379 std::replace(dt_file.begin(), dt_file.end(), ',', '.');
1380
1381 InitPropertySet("ro.boot."s + dp->d_name, dt_file);
1382 }
1383}
1384
Roman Kiryanovccc15c52021-03-09 13:20:36 -08001385constexpr auto ANDROIDBOOT_PREFIX = "androidboot."sv;
1386
Tom Cherryc88d8f92019-08-19 15:21:25 -07001387static void ProcessKernelCmdline() {
Yi-Yo Chiangda5323e2023-08-02 01:08:23 +08001388 android::fs_mgr::ImportKernelCmdline([&](const std::string& key, const std::string& value) {
Roman Kiryanov1a705d42021-03-09 18:19:23 -08001389 if (StartsWith(key, ANDROIDBOOT_PREFIX)) {
Roman Kiryanovccc15c52021-03-09 13:20:36 -08001390 InitPropertySet("ro.boot." + key.substr(ANDROIDBOOT_PREFIX.size()), value);
Tom Cherryc88d8f92019-08-19 15:21:25 -07001391 }
1392 });
Tom Cherryc88d8f92019-08-19 15:21:25 -07001393}
1394
Roman Kiryanov6e20ff82021-04-28 15:15:44 -07001395
Devin Moorea4ef15b2020-12-15 16:14:37 -08001396static void ProcessBootconfig() {
Yi-Yo Chiang79ad1e22023-07-29 17:37:23 +08001397 android::fs_mgr::ImportBootconfig([&](const std::string& key, const std::string& value) {
Roman Kiryanovccc15c52021-03-09 13:20:36 -08001398 if (StartsWith(key, ANDROIDBOOT_PREFIX)) {
1399 InitPropertySet("ro.boot." + key.substr(ANDROIDBOOT_PREFIX.size()), value);
Devin Moorea4ef15b2020-12-15 16:14:37 -08001400 }
1401 });
1402}
1403
Tom Cherryc88d8f92019-08-19 15:21:25 -07001404void PropertyInit() {
1405 selinux_callback cb;
1406 cb.func_audit = PropertyAuditCallback;
1407 selinux_set_callback(SELINUX_CB_AUDIT, cb);
1408
1409 mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);
1410 CreateSerializedPropertyInfo();
1411 if (__system_property_area_init()) {
1412 LOG(FATAL) << "Failed to initialize property area";
1413 }
1414 if (!property_info_area.LoadDefaultPath()) {
1415 LOG(FATAL) << "Failed to load serialized property info file";
1416 }
1417
1418 // If arguments are passed both on the command line and in DT,
1419 // properties set in DT always have priority over the command-line ones.
1420 ProcessKernelDt();
1421 ProcessKernelCmdline();
Devin Moorea4ef15b2020-12-15 16:14:37 -08001422 ProcessBootconfig();
Tom Cherryc88d8f92019-08-19 15:21:25 -07001423
1424 // Propagate the kernel variables to internal variables
1425 // used by init as well as the current required properties.
1426 ExportKernelBootProps();
1427
1428 PropertyLoadBootDefaults();
1429}
1430
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001431static void HandleInitSocket() {
1432 auto message = ReadMessage(init_socket);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001433 if (!message.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001434 LOG(ERROR) << "Could not read message from init_dedicated_recv_socket: " << message.error();
1435 return;
1436 }
1437
1438 auto init_message = InitMessage{};
1439 if (!init_message.ParseFromString(*message)) {
1440 LOG(ERROR) << "Could not parse message from init";
1441 return;
1442 }
1443
1444 switch (init_message.msg_case()) {
1445 case InitMessage::kLoadPersistentProperties: {
1446 load_override_properties();
Dennis Shen678d2682023-09-18 19:52:52 +00001447
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001448 auto persistent_properties = LoadPersistentProperties();
Dennis Shen678d2682023-09-18 19:52:52 +00001449 for (const auto& property_record : persistent_properties.properties()) {
1450 auto const& prop_name = property_record.name();
1451 auto const& prop_value = property_record.value();
Dennis Shen79283ef2023-10-24 17:30:12 +00001452 InitPropertySet(prop_name, prop_value);
Dennis Shen678d2682023-09-18 19:52:52 +00001453 }
1454
Yi-Yo Chiang70c53f52022-06-08 19:11:43 +08001455 // Apply debug ramdisk special settings after persistent properties are loaded.
1456 if (android::base::GetBoolProperty("ro.force.debuggable", false)) {
1457 // Always enable usb adb if device is booted with debug ramdisk.
1458 update_sys_usb_config();
1459 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001460 InitPropertySet("ro.persistent_properties.ready", "true");
1461 persistent_properties_loaded = true;
maxwen107cae32020-09-30 17:51:49 +02001462
1463 /* vendor-specific properties
1464 */
1465 vendor_load_properties();
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001466 break;
1467 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001468 default:
1469 LOG(ERROR) << "Unknown message type from init: " << init_message.msg_case();
1470 }
1471}
1472
Paul Lawrence689adfa2023-07-18 08:39:10 -07001473static void PropertyServiceThread(int fd, bool listen_init) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001474 Epoll epoll;
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001475 if (auto result = epoll.Open(); !result.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001476 LOG(FATAL) << result.error();
1477 }
1478
Paul Lawrence689adfa2023-07-18 08:39:10 -07001479 if (auto result = epoll.RegisterHandler(fd, std::bind(handle_property_set_fd, fd));
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001480 !result.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001481 LOG(FATAL) << result.error();
1482 }
1483
Paul Lawrence689adfa2023-07-18 08:39:10 -07001484 if (listen_init) {
1485 if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result.ok()) {
1486 LOG(FATAL) << result.error();
1487 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001488 }
1489
Tom Cherry832f9f12020-03-10 11:47:24 -07001490 while (true) {
Bart Van Asschebc5c4a42022-10-14 09:13:19 -07001491 auto epoll_result = epoll.Wait(std::nullopt);
1492 if (!epoll_result.ok()) {
1493 LOG(ERROR) << epoll_result.error();
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001494 }
1495 }
1496}
1497
David Anderson0af9ab32022-10-07 00:19:55 -07001498PersistWriteThread::PersistWriteThread() {
1499 auto new_thread = std::thread([this]() -> void { Work(); });
1500 thread_.swap(new_thread);
1501}
1502
1503void PersistWriteThread::Work() {
1504 while (true) {
1505 std::tuple<std::string, std::string, SocketConnection> item;
1506
1507 // Grab the next item within the lock.
1508 {
1509 std::unique_lock<std::mutex> lock(mutex_);
1510
1511 while (work_.empty()) {
1512 cv_.wait(lock);
1513 }
1514
1515 item = std::move(work_.front());
1516 work_.pop_front();
1517 }
1518
David Anderson0af9ab32022-10-07 00:19:55 -07001519 // Perform write/fsync outside the lock.
1520 WritePersistentProperty(std::get<0>(item), std::get<1>(item));
1521 NotifyPropertyChange(std::get<0>(item), std::get<1>(item));
1522
1523 SocketConnection& socket = std::get<2>(item);
1524 socket.SendUint32(PROP_SUCCESS);
1525 }
1526}
1527
1528void PersistWriteThread::Write(std::string name, std::string value, SocketConnection socket) {
1529 {
1530 std::unique_lock<std::mutex> lock(mutex_);
1531 work_.emplace_back(std::move(name), std::move(value), std::move(socket));
1532 }
1533 cv_.notify_all();
1534}
1535
Paul Lawrence689adfa2023-07-18 08:39:10 -07001536void StartThread(const char* name, int mode, int gid, std::thread& t, bool listen_init) {
1537 int fd = -1;
1538 if (auto result = CreateSocket(name, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1539 /*passcred=*/false, /*should_listen=*/false, mode, /*uid=*/0,
1540 /*gid=*/gid, /*socketcon=*/{});
1541 result.ok()) {
1542 fd = *result;
1543 } else {
1544 LOG(FATAL) << "start_property_service socket creation failed: " << result.error();
1545 }
1546
1547 listen(fd, 8);
1548
1549 auto new_thread = std::thread(PropertyServiceThread, fd, listen_init);
1550 t.swap(new_thread);
1551}
1552
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001553void StartPropertyService(int* epoll_socket) {
Tom Cherryc88d8f92019-08-19 15:21:25 -07001554 InitPropertySet("ro.property_service.version", "2");
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +00001555
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001556 int sockets[2];
1557 if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != 0) {
1558 PLOG(FATAL) << "Failed to socketpair() between property_service and init";
1559 }
Tom Cherry802864c2020-03-12 14:29:25 -07001560 *epoll_socket = from_init_socket = sockets[0];
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001561 init_socket = sockets[1];
Tom Cherry802864c2020-03-12 14:29:25 -07001562 StartSendingMessages();
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001563
Paul Lawrence689adfa2023-07-18 08:39:10 -07001564 StartThread(PROP_SERVICE_FOR_SYSTEM_NAME, 0660, AID_SYSTEM, property_service_for_system_thread,
1565 true);
1566 StartThread(PROP_SERVICE_NAME, 0666, 0, property_service_thread, false);
David Anderson0af9ab32022-10-07 00:19:55 -07001567
1568 auto async_persist_writes =
1569 android::base::GetBoolProperty("ro.property_service.async_persist_writes", false);
1570
1571 if (async_persist_writes) {
1572 persist_write_thread = std::make_unique<PersistWriteThread>();
1573 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001574}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001575
1576} // namespace init
1577} // namespace android