blob: f5d1143caa9b91d72a3fbb201d1b3e7d636cc29d [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
Tom Cherryede0d532017-07-06 14:20:11 -070050#include <android-base/chrono_utils.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080051#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070052#include <android-base/logging.h>
Jaekyun Seok0cf3a072017-04-24 18:52:54 +090053#include <android-base/properties.h>
Tom Cherrya84e14d2017-09-05 12:38:30 -070054#include <android-base/stringprintf.h>
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +000055#include <android-base/strings.h>
Tom Cherry2ae2f602017-12-14 01:58:17 +000056#include <property_info_parser/property_info_parser.h>
57#include <property_info_serializer/property_info_serializer.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070058#include <selinux/android.h>
59#include <selinux/label.h>
60#include <selinux/selinux.h>
Andres Moralesdb5f5d42015-05-08 08:30:33 -070061
Bowgo Tsai30afda72019-04-11 23:57:24 +080062#include "debug_ramdisk.h"
Tom Cherry3707d322019-08-15 13:07:24 -070063#include "epoll.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080064#include "init.h"
Tom Cherry16fad422017-08-04 15:59:03 -070065#include "persistent_properties.h"
Tom Cherry927c5d52017-12-11 01:40:07 -080066#include "property_type.h"
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070067#include "proto_utils.h"
Logan Chien837b2a42018-05-03 14:33:52 +080068#include "selinux.h"
Tom Cherrydc375862018-02-28 10:39:01 -080069#include "subcontext.h"
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070070#include "system/core/init/property_service.pb.h"
Colin Cross3899e9f2010-04-13 20:35:46 -070071#include "util.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080072
Tom Cherrydc375862018-02-28 10:39:01 -080073using namespace std::literals;
74
Steven Laver57a740e2019-01-29 20:19:05 -080075using android::base::GetProperty;
Tom Cherry2ae2f602017-12-14 01:58:17 +000076using android::base::ReadFileToString;
77using android::base::Split;
Tom Cherry1cf8d692017-10-10 13:35:01 -070078using android::base::StartsWith;
Tom Cherrya84e14d2017-09-05 12:38:30 -070079using android::base::StringPrintf;
Tom Cherryede0d532017-07-06 14:20:11 -070080using android::base::Timer;
Tom Cherry2ae2f602017-12-14 01:58:17 +000081using android::base::Trim;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070082using android::base::unique_fd;
Tom Cherry2ae2f602017-12-14 01:58:17 +000083using android::base::WriteStringToFile;
84using android::properties::BuildTrie;
Tom Cherry919458c2018-01-03 14:39:28 -080085using android::properties::ParsePropertyInfoFile;
Tom Cherry2ae2f602017-12-14 01:58:17 +000086using android::properties::PropertyInfoAreaFile;
87using android::properties::PropertyInfoEntry;
Tom Cherryede0d532017-07-06 14:20:11 -070088
Tom Cherry81f5d3e2017-06-22 12:53:17 -070089namespace android {
90namespace init {
91
Tom Cherry16fad422017-08-04 15:59:03 -070092static bool persistent_properties_loaded = false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080093
Colin Crossd11beb22010-04-13 19:33:37 -070094static int property_set_fd = -1;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070095static int init_socket = -1;
Colin Crossd11beb22010-04-13 19:33:37 -070096
Tom Cherry2ae2f602017-12-14 01:58:17 +000097static PropertyInfoAreaFile property_info_area;
98
99void CreateSerializedPropertyInfo();
Tom Cherryc3692b32017-08-10 12:22:44 -0700100
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700101struct PropertyAuditData {
102 const ucred* cr;
103 const char* name;
104};
105
Tom Cherry2f113ad2019-04-22 10:22:41 -0700106static int PropertyAuditCallback(void* data, security_class_t /*cls*/, char* buf, size_t len) {
107 auto* d = reinterpret_cast<PropertyAuditData*>(data);
108
109 if (!d || !d->name || !d->cr) {
110 LOG(ERROR) << "AuditCallback invoked with null data arguments!";
111 return 0;
112 }
113
114 snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name, d->cr->pid, d->cr->uid,
115 d->cr->gid);
116 return 0;
117}
118
Elliott Hughesda40c002015-03-27 23:20:44 -0700119void property_init() {
Tom Cherry2f113ad2019-04-22 10:22:41 -0700120 selinux_callback cb;
121 cb.func_audit = PropertyAuditCallback;
122 selinux_set_callback(SELINUX_CB_AUDIT, cb);
123
Tom Cherry2ae2f602017-12-14 01:58:17 +0000124 mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);
125 CreateSerializedPropertyInfo();
Elliott Hughesda40c002015-03-27 23:20:44 -0700126 if (__system_property_area_init()) {
Tom Cherry4a679452017-09-26 16:30:03 -0700127 LOG(FATAL) << "Failed to initialize property area";
Elliott Hughesda40c002015-03-27 23:20:44 -0700128 }
Tom Cherry2ae2f602017-12-14 01:58:17 +0000129 if (!property_info_area.LoadDefaultPath()) {
130 LOG(FATAL) << "Failed to load serialized property info file";
131 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800132}
Tom Cherryb35f8272018-10-22 14:50:52 -0700133
134bool CanReadProperty(const std::string& source_context, const std::string& name) {
135 const char* target_context = nullptr;
136 property_info_area->GetPropertyInfo(name.c_str(), &target_context, nullptr);
137
138 PropertyAuditData audit_data;
139
140 audit_data.name = name.c_str();
141
142 ucred cr = {.pid = 0, .uid = 0, .gid = 0};
143 audit_data.cr = &cr;
144
145 return selinux_check_access(source_context.c_str(), target_context, "file", "read",
146 &audit_data) == 0;
147}
148
Tom Cherry927c5d52017-12-11 01:40:07 -0800149static bool CheckMacPerms(const std::string& name, const char* target_context,
Tom Cherry32228482018-01-18 16:14:25 -0800150 const char* source_context, const ucred& cr) {
Tom Cherry927c5d52017-12-11 01:40:07 -0800151 if (!target_context || !source_context) {
Tom Cherry2ae2f602017-12-14 01:58:17 +0000152 return false;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000153 }
154
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700155 PropertyAuditData audit_data;
rpcraig63207cd2012-08-09 10:05:49 -0400156
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000157 audit_data.name = name.c_str();
Tom Cherry32228482018-01-18 16:14:25 -0800158 audit_data.cr = &cr;
William Robertsd7aea442015-10-01 16:03:47 -0700159
Tom Cherry927c5d52017-12-11 01:40:07 -0800160 bool has_access = (selinux_check_access(source_context, target_context, "property_service",
161 "set", &audit_data) == 0);
rpcraig63207cd2012-08-09 10:05:49 -0400162
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000163 return has_access;
rpcraig63207cd2012-08-09 10:05:49 -0400164}
165
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700166static void SendPropertyChanged(const std::string& name, const std::string& value) {
167 auto property_msg = PropertyMessage{};
168 auto* changed_message = property_msg.mutable_changed_message();
169 changed_message->set_name(name);
170 changed_message->set_value(value);
171
172 if (auto result = SendMessage(init_socket, property_msg); !result) {
173 LOG(ERROR) << "Failed to send property changed message: " << result.error();
174 }
175}
176
Tom Cherry69d47aa2018-03-01 11:00:57 -0800177static uint32_t PropertySet(const std::string& name, const std::string& value, std::string* error) {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000178 size_t valuelen = value.size();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800179
Tom Cherryde6bd502018-02-13 16:50:08 -0800180 if (!IsLegalPropertyName(name)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800181 *error = "Illegal property name";
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000182 return PROP_ERROR_INVALID_NAME;
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000183 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000184
Tom Cherry4772f1d2019-07-30 09:34:41 -0700185 if (auto result = IsLegalPropertyValue(name, value); !result) {
186 *error = result.error().message();
Tom Cherry8702dcb2017-10-13 16:20:19 -0700187 return PROP_ERROR_INVALID_VALUE;
188 }
189
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000190 prop_info* pi = (prop_info*) __system_property_find(name.c_str());
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000191 if (pi != nullptr) {
192 // ro.* properties are actually "write-once".
Tom Cherry1cf8d692017-10-10 13:35:01 -0700193 if (StartsWith(name, "ro.")) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800194 *error = "Read-only property was already set";
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000195 return PROP_ERROR_READ_ONLY_PROPERTY;
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000196 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800197
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000198 __system_property_update(pi, value.c_str(), valuelen);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800199 } else {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000200 int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
Elliott Hughesdb3f2672015-03-20 09:45:18 -0700201 if (rc < 0) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800202 *error = "__system_property_add failed";
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000203 return PROP_ERROR_SET_FAILED;
Johan Redestigfd7ffb12013-04-29 09:11:57 +0200204 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800205 }
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000206
Elliott Hughes4f915812016-12-05 13:12:48 -0800207 // Don't write properties to disk until after we have read all default
208 // properties to prevent them from being overwritten by default values.
Tom Cherry1cf8d692017-10-10 13:35:01 -0700209 if (persistent_properties_loaded && StartsWith(name, "persist.")) {
Tom Cherry16fad422017-08-04 15:59:03 -0700210 WritePersistentProperty(name, value);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800211 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700212 // If init hasn't started its main loop, then it won't be handling property changed messages
213 // anyway, so there's no need to try to send them.
214 if (init_socket != -1) {
215 SendPropertyChanged(name, value);
216 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000217 return PROP_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800218}
219
Tom Cherryfe815412019-04-23 15:11:07 -0700220class AsyncRestorecon {
221 public:
222 void TriggerRestorecon(const std::string& path) {
223 auto guard = std::lock_guard{mutex_};
224 paths_.emplace(path);
Tom Marshall62696902017-06-09 18:29:23 +0000225
Tom Cherryfe815412019-04-23 15:11:07 -0700226 if (!thread_started_) {
227 thread_started_ = true;
228 std::thread{&AsyncRestorecon::ThreadFunction, this}.detach();
229 }
230 }
231
232 private:
233 void ThreadFunction() {
234 auto lock = std::unique_lock{mutex_};
235
236 while (!paths_.empty()) {
237 auto path = paths_.front();
238 paths_.pop();
239
240 lock.unlock();
241 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
242 LOG(ERROR) << "Asynchronous restorecon of '" << path << "' failed'";
243 }
244 android::base::SetProperty(kRestoreconProperty, path);
245 lock.lock();
246 }
247
248 thread_started_ = false;
249 }
250
251 std::mutex mutex_;
252 std::queue<std::string> paths_;
253 bool thread_started_ = false;
Tom Marshall62696902017-06-09 18:29:23 +0000254};
255
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000256class SocketConnection {
Tom Cherry32228482018-01-18 16:14:25 -0800257 public:
258 SocketConnection(int socket, const ucred& cred) : socket_(socket), cred_(cred) {}
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000259
Tom Cherry32228482018-01-18 16:14:25 -0800260 bool RecvUint32(uint32_t* value, uint32_t* timeout_ms) {
261 return RecvFully(value, sizeof(*value), timeout_ms);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000262 }
263
Tom Cherry32228482018-01-18 16:14:25 -0800264 bool RecvChars(char* chars, size_t size, uint32_t* timeout_ms) {
265 return RecvFully(chars, size, timeout_ms);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000266 }
267
Tom Cherry32228482018-01-18 16:14:25 -0800268 bool RecvString(std::string* value, uint32_t* timeout_ms) {
269 uint32_t len = 0;
270 if (!RecvUint32(&len, timeout_ms)) {
271 return false;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000272 }
Tom Cherry32228482018-01-18 16:14:25 -0800273
274 if (len == 0) {
275 *value = "";
276 return true;
277 }
278
279 // http://b/35166374: don't allow init to make arbitrarily large allocations.
280 if (len > 0xffff) {
281 LOG(ERROR) << "sys_prop: RecvString asked to read huge string: " << len;
282 errno = ENOMEM;
283 return false;
284 }
285
286 std::vector<char> chars(len);
287 if (!RecvChars(&chars[0], len, timeout_ms)) {
288 return false;
289 }
290
291 *value = std::string(&chars[0], len);
292 return true;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000293 }
294
Tom Cherry32228482018-01-18 16:14:25 -0800295 bool SendUint32(uint32_t value) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700296 if (!socket_.ok()) {
297 return true;
298 }
Tom Cherry32228482018-01-18 16:14:25 -0800299 int result = TEMP_FAILURE_RETRY(send(socket_, &value, sizeof(value), 0));
300 return result == sizeof(value);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000301 }
302
Tom Cherry7f160af2019-04-22 13:28:28 -0700303 bool GetSourceContext(std::string* source_context) const {
304 char* c_source_context = nullptr;
305 if (getpeercon(socket_, &c_source_context) != 0) {
306 return false;
307 }
308 *source_context = c_source_context;
309 freecon(c_source_context);
310 return true;
311 }
312
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700313 [[nodiscard]] int Release() { return socket_.release(); }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000314
Tom Cherry32228482018-01-18 16:14:25 -0800315 const ucred& cred() { return cred_; }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000316
Tom Cherry32228482018-01-18 16:14:25 -0800317 private:
318 bool PollIn(uint32_t* timeout_ms) {
319 struct pollfd ufds[1];
320 ufds[0].fd = socket_;
321 ufds[0].events = POLLIN;
322 ufds[0].revents = 0;
323 while (*timeout_ms > 0) {
324 auto start_time = std::chrono::steady_clock::now();
325 int nr = poll(ufds, 1, *timeout_ms);
326 auto now = std::chrono::steady_clock::now();
327 auto time_elapsed =
328 std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
329 uint64_t millis = time_elapsed.count();
330 *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
331
332 if (nr > 0) {
333 return true;
334 }
335
336 if (nr == 0) {
337 // Timeout
338 break;
339 }
340
341 if (nr < 0 && errno != EINTR) {
342 PLOG(ERROR) << "sys_prop: error waiting for uid " << cred_.uid
343 << " to send property message";
344 return false;
345 } else { // errno == EINTR
346 // Timer rounds milliseconds down in case of EINTR we want it to be rounded up
347 // to avoid slowing init down by causing EINTR with under millisecond timeout.
348 if (*timeout_ms > 0) {
349 --(*timeout_ms);
350 }
351 }
352 }
353
354 LOG(ERROR) << "sys_prop: timeout waiting for uid " << cred_.uid
355 << " to send property message.";
356 return false;
357 }
358
359 bool RecvFully(void* data_ptr, size_t size, uint32_t* timeout_ms) {
360 size_t bytes_left = size;
361 char* data = static_cast<char*>(data_ptr);
362 while (*timeout_ms > 0 && bytes_left > 0) {
363 if (!PollIn(timeout_ms)) {
364 return false;
365 }
366
367 int result = TEMP_FAILURE_RETRY(recv(socket_, data, bytes_left, MSG_DONTWAIT));
368 if (result <= 0) {
DuXiao40533592018-05-21 14:43:56 +0800369 PLOG(ERROR) << "sys_prop: recv error";
Tom Cherry32228482018-01-18 16:14:25 -0800370 return false;
371 }
372
373 bytes_left -= result;
374 data += result;
375 }
376
DuXiao40533592018-05-21 14:43:56 +0800377 if (bytes_left != 0) {
378 LOG(ERROR) << "sys_prop: recv data is not properly obtained.";
379 }
380
Tom Cherry32228482018-01-18 16:14:25 -0800381 return bytes_left == 0;
382 }
383
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700384 unique_fd socket_;
Tom Cherry32228482018-01-18 16:14:25 -0800385 ucred cred_;
Tom Cherry3da2ba62019-08-28 17:47:49 +0000386
387 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketConnection);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000388};
389
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700390static uint32_t SendControlMessage(const std::string& msg, const std::string& name, pid_t pid,
391 SocketConnection* socket, std::string* error) {
392 if (init_socket == -1) {
393 *error = "Received control message after shutdown, ignoring";
394 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
395 }
396
397 auto property_msg = PropertyMessage{};
398 auto* control_message = property_msg.mutable_control_message();
399 control_message->set_msg(msg);
400 control_message->set_name(name);
401 control_message->set_pid(pid);
402
403 // We must release the fd before sending it to init, otherwise there will be a race with init.
404 // If init calls close() before Release(), then fdsan will see the wrong tag and abort().
405 int fd = -1;
406 if (socket != nullptr) {
407 fd = socket->Release();
408 control_message->set_fd(fd);
409 }
410
411 if (auto result = SendMessage(init_socket, property_msg); !result) {
412 // We've already released the fd above, so if we fail to send the message to init, we need
413 // to manually free it here.
414 if (fd != -1) {
415 close(fd);
416 }
417 *error = "Failed to send control message: " + result.error().message();
418 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
419 }
420
421 return PROP_SUCCESS;
422}
423
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700424bool CheckControlPropertyPerms(const std::string& name, const std::string& value,
425 const std::string& source_context, const ucred& cr) {
426 // We check the legacy method first but these properties are dontaudit, so we only log an audit
427 // if the newer method fails as well. We only do this with the legacy ctl. properties.
428 if (name == "ctl.start" || name == "ctl.stop" || name == "ctl.restart") {
429 // The legacy permissions model is that ctl. properties have their name ctl.<action> and
430 // their value is the name of the service to apply that action to. Permissions for these
431 // actions are based on the service, so we must create a fake name of ctl.<service> to
432 // check permissions.
433 auto control_string_legacy = "ctl." + value;
434 const char* target_context_legacy = nullptr;
435 const char* type_legacy = nullptr;
436 property_info_area->GetPropertyInfo(control_string_legacy.c_str(), &target_context_legacy,
437 &type_legacy);
438
439 if (CheckMacPerms(control_string_legacy, target_context_legacy, source_context.c_str(), cr)) {
440 return true;
441 }
442 }
443
444 auto control_string_full = name + "$" + value;
445 const char* target_context_full = nullptr;
446 const char* type_full = nullptr;
447 property_info_area->GetPropertyInfo(control_string_full.c_str(), &target_context_full,
448 &type_full);
449
450 return CheckMacPerms(control_string_full, target_context_full, source_context.c_str(), cr);
451}
452
Tom Cherry32228482018-01-18 16:14:25 -0800453// This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
Tom Cherrybe048922019-02-16 12:03:19 -0800454uint32_t CheckPermissions(const std::string& name, const std::string& value,
455 const std::string& source_context, const ucred& cr, std::string* error) {
Tom Cherryde6bd502018-02-13 16:50:08 -0800456 if (!IsLegalPropertyName(name)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800457 *error = "Illegal property name";
Tom Cherry32228482018-01-18 16:14:25 -0800458 return PROP_ERROR_INVALID_NAME;
459 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000460
Tom Cherry32228482018-01-18 16:14:25 -0800461 if (StartsWith(name, "ctl.")) {
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700462 if (!CheckControlPropertyPerms(name, value, source_context, cr)) {
463 *error = StringPrintf("Invalid permissions to perform '%s' on '%s'", name.c_str() + 4,
464 value.c_str());
Tom Cherry32228482018-01-18 16:14:25 -0800465 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
466 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000467
Tom Cherry32228482018-01-18 16:14:25 -0800468 return PROP_SUCCESS;
469 }
Tom Cherry927c5d52017-12-11 01:40:07 -0800470
Tom Cherry32228482018-01-18 16:14:25 -0800471 const char* target_context = nullptr;
472 const char* type = nullptr;
473 property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type);
Tom Cherrya84e14d2017-09-05 12:38:30 -0700474
Tom Cherry32228482018-01-18 16:14:25 -0800475 if (!CheckMacPerms(name, target_context, source_context.c_str(), cr)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800476 *error = "SELinux permission check failed";
Tom Cherry32228482018-01-18 16:14:25 -0800477 return PROP_ERROR_PERMISSION_DENIED;
478 }
479
480 if (type == nullptr || !CheckType(type, value)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800481 *error = StringPrintf("Property type check failed, value doesn't match expected type '%s'",
482 (type ?: "(null)"));
Tom Cherry32228482018-01-18 16:14:25 -0800483 return PROP_ERROR_INVALID_VALUE;
484 }
485
Tom Cherrybe048922019-02-16 12:03:19 -0800486 return PROP_SUCCESS;
487}
488
489// This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
490uint32_t HandlePropertySet(const std::string& name, const std::string& value,
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700491 const std::string& source_context, const ucred& cr,
492 SocketConnection* socket, std::string* error) {
Tom Cherrybe048922019-02-16 12:03:19 -0800493 if (auto ret = CheckPermissions(name, value, source_context, cr, error); ret != PROP_SUCCESS) {
494 return ret;
495 }
496
497 if (StartsWith(name, "ctl.")) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700498 return SendControlMessage(name.c_str() + 4, value, cr.pid, socket, error);
Tom Cherrybe048922019-02-16 12:03:19 -0800499 }
500
Tom Cherry32228482018-01-18 16:14:25 -0800501 // sys.powerctl is a special property that is used to make the device reboot. We want to log
502 // any process that sets this property to be able to accurately blame the cause of a shutdown.
503 if (name == "sys.powerctl") {
504 std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
505 std::string process_cmdline;
506 std::string process_log_string;
507 if (ReadFileToString(cmdline_path, &process_cmdline)) {
508 // Since cmdline is null deliminated, .c_str() conveniently gives us just the process
509 // path.
510 process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
511 }
512 LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
513 << process_log_string;
514 }
515
Tom Cherryfe815412019-04-23 15:11:07 -0700516 // If a process other than init is writing a non-empty value, it means that process is
517 // requesting that init performs a restorecon operation on the path specified by 'value'.
518 // We use a thread to do this restorecon operation to prevent holding up init, as it may take
519 // a long time to complete.
520 if (name == kRestoreconProperty && cr.pid != 1 && !value.empty()) {
521 static AsyncRestorecon async_restorecon;
522 async_restorecon.TriggerRestorecon(value);
523 return PROP_SUCCESS;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800524 }
525
526 return PropertySet(name, value, error);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000527}
528
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700529uint32_t InitPropertySet(const std::string& name, const std::string& value) {
530 uint32_t result = 0;
531 ucred cr = {.pid = 1, .uid = 0, .gid = 0};
532 std::string error;
Tom Cherry14c24722019-09-18 13:47:19 -0700533 result = HandlePropertySet(name, value, kInitContext, cr, nullptr, &error);
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700534 if (result != PROP_SUCCESS) {
535 LOG(ERROR) << "Init cannot set '" << name << "' to '" << value << "': " << error;
536 }
537
538 return result;
539}
540
541uint32_t (*property_set)(const std::string& name, const std::string& value) = InitPropertySet;
542
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000543static void handle_property_set_fd() {
544 static constexpr uint32_t kDefaultSocketTimeout = 2000; /* ms */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800545
Robert Sesekca2da602017-01-25 08:08:51 -0500546 int s = accept4(property_set_fd, nullptr, nullptr, SOCK_CLOEXEC);
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700547 if (s == -1) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800548 return;
549 }
550
Tom Cherry32228482018-01-18 16:14:25 -0800551 ucred cr;
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700552 socklen_t cr_size = sizeof(cr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800553 if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
554 close(s);
Elliott Hughesb005d902017-02-22 14:54:15 -0800555 PLOG(ERROR) << "sys_prop: unable to get SO_PEERCRED";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800556 return;
557 }
558
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000559 SocketConnection socket(s, cr);
560 uint32_t timeout_ms = kDefaultSocketTimeout;
561
562 uint32_t cmd = 0;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000563 if (!socket.RecvUint32(&cmd, &timeout_ms)) {
564 PLOG(ERROR) << "sys_prop: error while reading command from the socket";
565 socket.SendUint32(PROP_ERROR_READ_CMD);
JP Abgrall4515d812014-01-31 14:37:07 -0800566 return;
567 }
568
Elliott Hughesb005d902017-02-22 14:54:15 -0800569 switch (cmd) {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000570 case PROP_MSG_SETPROP: {
571 char prop_name[PROP_NAME_MAX];
572 char prop_value[PROP_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800573
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000574 if (!socket.RecvChars(prop_name, PROP_NAME_MAX, &timeout_ms) ||
575 !socket.RecvChars(prop_value, PROP_VALUE_MAX, &timeout_ms)) {
576 PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP): error while reading name/value from the socket";
577 return;
Nick Kralevich69463612013-09-13 17:21:28 -0700578 }
579
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000580 prop_name[PROP_NAME_MAX-1] = 0;
581 prop_value[PROP_VALUE_MAX-1] = 0;
rpcraig63207cd2012-08-09 10:05:49 -0400582
Tom Cherry7f160af2019-04-22 13:28:28 -0700583 std::string source_context;
584 if (!socket.GetSourceContext(&source_context)) {
585 PLOG(ERROR) << "Unable to set property '" << prop_name << "': getpeercon() failed";
586 return;
587 }
588
Tom Cherry69d47aa2018-03-01 11:00:57 -0800589 const auto& cr = socket.cred();
590 std::string error;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700591 uint32_t result =
592 HandlePropertySet(prop_name, prop_value, source_context, cr, nullptr, &error);
Tom Cherry69d47aa2018-03-01 11:00:57 -0800593 if (result != PROP_SUCCESS) {
Nick Kralevich9ca898f2019-04-04 10:10:01 -0700594 LOG(ERROR) << "Unable to set property '" << prop_name << "' from uid:" << cr.uid
595 << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800596 }
597
Dimitry Ivanovdee4bd22017-01-19 14:53:00 -0800598 break;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000599 }
Dimitry Ivanov70c4ecf2017-01-24 18:38:09 +0000600
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000601 case PROP_MSG_SETPROP2: {
602 std::string name;
603 std::string value;
604 if (!socket.RecvString(&name, &timeout_ms) ||
605 !socket.RecvString(&value, &timeout_ms)) {
606 PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP2): error while reading name/value from the socket";
607 socket.SendUint32(PROP_ERROR_READ_DATA);
608 return;
609 }
610
Tom Cherry7f160af2019-04-22 13:28:28 -0700611 std::string source_context;
612 if (!socket.GetSourceContext(&source_context)) {
613 PLOG(ERROR) << "Unable to set property '" << name << "': getpeercon() failed";
614 socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
615 return;
616 }
617
Tom Cherry69d47aa2018-03-01 11:00:57 -0800618 const auto& cr = socket.cred();
619 std::string error;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700620 uint32_t result = HandlePropertySet(name, value, source_context, cr, &socket, &error);
Tom Cherry69d47aa2018-03-01 11:00:57 -0800621 if (result != PROP_SUCCESS) {
Nick Kralevich9ca898f2019-04-04 10:10:01 -0700622 LOG(ERROR) << "Unable to set property '" << name << "' from uid:" << cr.uid
623 << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800624 }
Tom Cherryf4514262019-08-26 16:33:40 +0000625 socket.SendUint32(result);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000626 break;
627 }
Elliott Hughesb005d902017-02-22 14:54:15 -0800628
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800629 default:
Elliott Hughesb005d902017-02-22 14:54:15 -0800630 LOG(ERROR) << "sys_prop: invalid command " << cmd;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000631 socket.SendUint32(PROP_ERROR_INVALID_CMD);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800632 break;
633 }
634}
635
Tom Cherrybe048922019-02-16 12:03:19 -0800636static bool load_properties_from_file(const char*, const char*,
637 std::map<std::string, std::string>*);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800638
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800639/*
640 * Filter is used to decide which properties to load: NULL loads all keys,
641 * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
642 */
Tom Cherrybe048922019-02-16 12:03:19 -0800643static void LoadProperties(char* data, const char* filter, const char* filename,
644 std::map<std::string, std::string>* properties) {
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800645 char *key, *value, *eol, *sol, *tmp, *fn;
646 size_t flen = 0;
647
Tom Cherry14c24722019-09-18 13:47:19 -0700648 static constexpr const char* const kVendorPathPrefixes[2] = {
649 "/vendor",
650 "/odm",
651 };
652
653 const char* context = kInitContext;
Tom Cherry40acb372018-08-01 13:41:12 -0700654 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
Tom Cherry14c24722019-09-18 13:47:19 -0700655 for (const auto& vendor_path_prefix : kVendorPathPrefixes) {
656 if (StartsWith(filename, vendor_path_prefix)) {
657 context = kVendorContext;
Tom Cherrya1dbeb82018-04-11 15:50:00 -0700658 }
Tom Cherrydc375862018-02-28 10:39:01 -0800659 }
660 }
661
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800662 if (filter) {
663 flen = strlen(filter);
664 }
665
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800666 sol = data;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800667 while ((eol = strchr(sol, '\n'))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800668 key = sol;
669 *eol++ = 0;
670 sol = eol;
671
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800672 while (isspace(*key)) key++;
673 if (*key == '#') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800674
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800675 tmp = eol - 2;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800676 while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800677
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800678 if (!strncmp(key, "import ", 7) && flen == 0) {
679 fn = key + 7;
680 while (isspace(*fn)) fn++;
681
682 key = strchr(fn, ' ');
683 if (key) {
684 *key++ = 0;
685 while (isspace(*key)) key++;
686 }
687
Dongcheol Shina87c0f92019-06-12 09:31:35 +0900688 std::string raw_filename(fn);
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700689 auto expanded_filename = ExpandProps(raw_filename);
690
691 if (!expanded_filename) {
692 LOG(ERROR) << "Could not expand filename ': " << expanded_filename.error();
Dongcheol Shina87c0f92019-06-12 09:31:35 +0900693 continue;
694 }
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800695
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700696 load_properties_from_file(expanded_filename->c_str(), key, properties);
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800697 } else {
698 value = strchr(key, '=');
699 if (!value) continue;
700 *value++ = 0;
701
702 tmp = value - 2;
703 while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
704
705 while (isspace(*value)) value++;
706
707 if (flen > 0) {
708 if (filter[flen - 1] == '*') {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700709 if (strncmp(key, filter, flen - 1) != 0) continue;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800710 } else {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700711 if (strcmp(key, filter) != 0) continue;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800712 }
713 }
714
Tom Cherrydc375862018-02-28 10:39:01 -0800715 if (StartsWith(key, "ctl.") || key == "sys.powerctl"s ||
Tom Cherryfe815412019-04-23 15:11:07 -0700716 std::string{key} == kRestoreconProperty) {
Tom Cherrydc375862018-02-28 10:39:01 -0800717 LOG(ERROR) << "Ignoring disallowed property '" << key
718 << "' with special meaning in prop file '" << filename << "'";
719 continue;
720 }
721
Tom Cherrydc375862018-02-28 10:39:01 -0800722 ucred cr = {.pid = 1, .uid = 0, .gid = 0};
723 std::string error;
Tom Cherrybe048922019-02-16 12:03:19 -0800724 if (CheckPermissions(key, value, context, cr, &error) == PROP_SUCCESS) {
725 auto it = properties->find(key);
726 if (it == properties->end()) {
727 (*properties)[key] = value;
728 } else if (it->second != value) {
729 LOG(WARNING) << "Overriding previous 'ro.' property '" << key << "':'"
730 << it->second << "' with new value '" << value << "'";
731 it->second = value;
732 }
733 } else {
734 LOG(ERROR) << "Do not have permissions to set '" << key << "' to '" << value
Tom Cherrydc375862018-02-28 10:39:01 -0800735 << "' in property file '" << filename << "': " << error;
736 }
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800737 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800738 }
739}
740
Elliott Hughes5a7ad842016-09-30 14:12:33 -0700741// Filter is used to decide which properties to load: NULL loads all keys,
742// "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
Tom Cherrybe048922019-02-16 12:03:19 -0800743static bool load_properties_from_file(const char* filename, const char* filter,
744 std::map<std::string, std::string>* properties) {
Elliott Hughesda40c002015-03-27 23:20:44 -0700745 Timer t;
Tom Cherry62ca6632017-08-03 12:54:07 -0700746 auto file_contents = ReadFile(filename);
747 if (!file_contents) {
748 PLOG(WARNING) << "Couldn't load property file '" << filename
749 << "': " << file_contents.error();
Hung-ying Tyanaef2b092017-06-02 18:59:46 +0800750 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800751 }
Tom Cherry62ca6632017-08-03 12:54:07 -0700752 file_contents->push_back('\n');
Tom Cherrydc375862018-02-28 10:39:01 -0800753
Tom Cherrybe048922019-02-16 12:03:19 -0800754 LoadProperties(file_contents->data(), filter, filename, properties);
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000755 LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
Hung-ying Tyanaef2b092017-06-02 18:59:46 +0800756 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800757}
758
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900759// persist.sys.usb.config values can't be combined on build-time when property
760// files are split into each partition.
761// So we need to apply the same rule of build/make/tools/post_process_props.py
762// on runtime.
763static void update_sys_usb_config() {
764 bool is_debuggable = android::base::GetBoolProperty("ro.debuggable", false);
765 std::string config = android::base::GetProperty("persist.sys.usb.config", "");
766 if (config.empty()) {
767 property_set("persist.sys.usb.config", is_debuggable ? "adb" : "none");
768 } else if (is_debuggable && config.find("adb") == std::string::npos &&
769 config.length() + 4 < PROP_VALUE_MAX) {
770 config.append(",adb");
771 property_set("persist.sys.usb.config", config);
772 }
773}
774
Nick Kralevich32b90232012-09-19 11:15:24 -0700775static void load_override_properties() {
Elliott Hughesc0e919c2015-02-04 14:46:36 -0800776 if (ALLOW_LOCAL_PROP_OVERRIDE) {
Tom Cherrybe048922019-02-16 12:03:19 -0800777 std::map<std::string, std::string> properties;
778 load_properties_from_file("/data/local.prop", nullptr, &properties);
779 for (const auto& [name, value] : properties) {
780 std::string error;
781 if (PropertySet(name, value, &error) != PROP_SUCCESS) {
782 LOG(ERROR) << "Could not set '" << name << "' to '" << value
783 << "' in /data/local.prop: " << error;
784 }
785 }
Nick Kralevich32b90232012-09-19 11:15:24 -0700786 }
Nick Kralevich32b90232012-09-19 11:15:24 -0700787}
788
Steven Laver57a740e2019-01-29 20:19:05 -0800789// If the ro.product.[brand|device|manufacturer|model|name] properties have not been explicitly
790// set, derive them from ro.product.${partition}.* properties
791static void property_initialize_ro_product_props() {
792 const char* RO_PRODUCT_PROPS_PREFIX = "ro.product.";
793 const char* RO_PRODUCT_PROPS[] = {
794 "brand", "device", "manufacturer", "model", "name",
795 };
796 const char* RO_PRODUCT_PROPS_ALLOWED_SOURCES[] = {
Justin Yun7eaf9b52019-06-28 14:28:00 +0900797 "odm", "product", "system_ext", "system", "vendor",
Steven Laver57a740e2019-01-29 20:19:05 -0800798 };
Justin Yun7eaf9b52019-06-28 14:28:00 +0900799 const char* RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER = "product,odm,vendor,system_ext,system";
Steven Laver57a740e2019-01-29 20:19:05 -0800800 const std::string EMPTY = "";
801
802 std::string ro_product_props_source_order =
803 GetProperty("ro.product.property_source_order", EMPTY);
804
805 if (!ro_product_props_source_order.empty()) {
806 // Verify that all specified sources are valid
807 for (const auto& source : Split(ro_product_props_source_order, ",")) {
808 // Verify that the specified source is valid
809 bool is_allowed_source = false;
810 for (const auto& allowed_source : RO_PRODUCT_PROPS_ALLOWED_SOURCES) {
811 if (source == allowed_source) {
812 is_allowed_source = true;
813 break;
814 }
815 }
816 if (!is_allowed_source) {
817 LOG(ERROR) << "Found unexpected source in ro.product.property_source_order; "
818 "using the default property source order";
819 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
820 break;
821 }
822 }
823 } else {
824 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
825 }
826
827 for (const auto& ro_product_prop : RO_PRODUCT_PROPS) {
828 std::string base_prop(RO_PRODUCT_PROPS_PREFIX);
829 base_prop += ro_product_prop;
830
831 std::string base_prop_val = GetProperty(base_prop, EMPTY);
832 if (!base_prop_val.empty()) {
833 continue;
834 }
835
836 for (const auto& source : Split(ro_product_props_source_order, ",")) {
837 std::string target_prop(RO_PRODUCT_PROPS_PREFIX);
838 target_prop += source;
839 target_prop += '.';
840 target_prop += ro_product_prop;
841
842 std::string target_prop_val = GetProperty(target_prop, EMPTY);
843 if (!target_prop_val.empty()) {
844 LOG(INFO) << "Setting product property " << base_prop << " to '" << target_prop_val
845 << "' (from " << target_prop << ")";
846 std::string error;
847 uint32_t res = PropertySet(base_prop, target_prop_val, &error);
848 if (res != PROP_SUCCESS) {
849 LOG(ERROR) << "Error setting product property " << base_prop << ": err=" << res
850 << " (" << error << ")";
851 }
852 break;
853 }
854 }
855 }
856}
857
858// If the ro.build.fingerprint property has not been set, derive it from constituent pieces
859static void property_derive_build_fingerprint() {
860 std::string build_fingerprint = GetProperty("ro.build.fingerprint", "");
861 if (!build_fingerprint.empty()) {
862 return;
863 }
864
865 const std::string UNKNOWN = "unknown";
866 build_fingerprint = GetProperty("ro.product.brand", UNKNOWN);
867 build_fingerprint += '/';
868 build_fingerprint += GetProperty("ro.product.name", UNKNOWN);
869 build_fingerprint += '/';
870 build_fingerprint += GetProperty("ro.product.device", UNKNOWN);
871 build_fingerprint += ':';
872 build_fingerprint += GetProperty("ro.build.version.release", UNKNOWN);
873 build_fingerprint += '/';
874 build_fingerprint += GetProperty("ro.build.id", UNKNOWN);
875 build_fingerprint += '/';
876 build_fingerprint += GetProperty("ro.build.version.incremental", UNKNOWN);
877 build_fingerprint += ':';
878 build_fingerprint += GetProperty("ro.build.type", UNKNOWN);
879 build_fingerprint += '/';
880 build_fingerprint += GetProperty("ro.build.tags", UNKNOWN);
881
882 LOG(INFO) << "Setting property 'ro.build.fingerprint' to '" << build_fingerprint << "'";
883
884 std::string error;
885 uint32_t res = PropertySet("ro.build.fingerprint", build_fingerprint, &error);
886 if (res != PROP_SUCCESS) {
887 LOG(ERROR) << "Error setting property 'ro.build.fingerprint': err=" << res << " (" << error
888 << ")";
889 }
890}
891
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800892void property_load_boot_defaults(bool load_debug_prop) {
Jiyong Park3b316ee2019-01-13 02:42:31 +0900893 // TODO(b/117892318): merge prop.default and build.prop files into one
Tom Cherrybe048922019-02-16 12:03:19 -0800894 // We read the properties and their values into a map, in order to always allow properties
895 // loaded in the later property files to override the properties in loaded in the earlier
896 // property files, regardless of if they are "ro." properties or not.
897 std::map<std::string, std::string> properties;
898 if (!load_properties_from_file("/system/etc/prop.default", nullptr, &properties)) {
Jiyong Park3b316ee2019-01-13 02:42:31 +0900899 // Try recovery path
Tom Cherrybe048922019-02-16 12:03:19 -0800900 if (!load_properties_from_file("/prop.default", nullptr, &properties)) {
Jiyong Park3b316ee2019-01-13 02:42:31 +0900901 // Try legacy path
Tom Cherrybe048922019-02-16 12:03:19 -0800902 load_properties_from_file("/default.prop", nullptr, &properties);
Jiyong Park3b316ee2019-01-13 02:42:31 +0900903 }
904 }
Tom Cherrybe048922019-02-16 12:03:19 -0800905 load_properties_from_file("/system/build.prop", nullptr, &properties);
Justin Yun7eaf9b52019-06-28 14:28:00 +0900906 load_properties_from_file("/system_ext/build.prop", nullptr, &properties);
Tom Cherrybe048922019-02-16 12:03:19 -0800907 load_properties_from_file("/vendor/default.prop", nullptr, &properties);
908 load_properties_from_file("/vendor/build.prop", nullptr, &properties);
Bowgo Tsai9fc8dcf2019-05-17 15:40:18 +0800909 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_Q__) {
910 load_properties_from_file("/odm/etc/build.prop", nullptr, &properties);
911 } else {
912 load_properties_from_file("/odm/default.prop", nullptr, &properties);
913 load_properties_from_file("/odm/build.prop", nullptr, &properties);
914 }
Tom Cherrybe048922019-02-16 12:03:19 -0800915 load_properties_from_file("/product/build.prop", nullptr, &properties);
Tom Cherrybe048922019-02-16 12:03:19 -0800916 load_properties_from_file("/factory/factory.prop", "ro.*", &properties);
917
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800918 if (load_debug_prop) {
Bowgo Tsai30afda72019-04-11 23:57:24 +0800919 LOG(INFO) << "Loading " << kDebugRamdiskProp;
920 load_properties_from_file(kDebugRamdiskProp, nullptr, &properties);
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800921 }
922
Tom Cherrybe048922019-02-16 12:03:19 -0800923 for (const auto& [name, value] : properties) {
924 std::string error;
925 if (PropertySet(name, value, &error) != PROP_SUCCESS) {
926 LOG(ERROR) << "Could not set '" << name << "' to '" << value
927 << "' while loading .prop files" << error;
928 }
929 }
Jiyong Park3b316ee2019-01-13 02:42:31 +0900930
Steven Laver57a740e2019-01-29 20:19:05 -0800931 property_initialize_ro_product_props();
932 property_derive_build_fingerprint();
933
Jiyong Park3b316ee2019-01-13 02:42:31 +0900934 update_sys_usb_config();
Riley Andrewse4b7b292014-06-16 15:06:21 -0700935}
936
Tom Cherry2ae2f602017-12-14 01:58:17 +0000937bool LoadPropertyInfoFromFile(const std::string& filename,
938 std::vector<PropertyInfoEntry>* property_infos) {
939 auto file_contents = std::string();
940 if (!ReadFileToString(filename, &file_contents)) {
941 PLOG(ERROR) << "Could not read properties from '" << filename << "'";
942 return false;
943 }
944
Tom Cherry919458c2018-01-03 14:39:28 -0800945 auto errors = std::vector<std::string>{};
946 ParsePropertyInfoFile(file_contents, property_infos, &errors);
947 // Individual parsing errors are reported but do not cause a failed boot, which is what
948 // returning false would do here.
949 for (const auto& error : errors) {
950 LOG(ERROR) << "Could not read line from '" << filename << "': " << error;
Tom Cherry2ae2f602017-12-14 01:58:17 +0000951 }
Tom Cherry919458c2018-01-03 14:39:28 -0800952
Tom Cherry2ae2f602017-12-14 01:58:17 +0000953 return true;
954}
955
956void CreateSerializedPropertyInfo() {
957 auto property_infos = std::vector<PropertyInfoEntry>();
958 if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
959 if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",
960 &property_infos)) {
961 return;
962 }
963 // Don't check for failure here, so we always have a sane list of properties.
964 // E.g. In case of recovery, the vendor partition will not have mounted and we
965 // still need the system / platform properties to function.
Bowgo Tsai36cf3532017-12-07 16:05:25 +0800966 if (!LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",
967 &property_infos)) {
968 // Fallback to nonplat_* if vendor_* doesn't exist.
969 LoadPropertyInfoFromFile("/vendor/etc/selinux/nonplat_property_contexts",
970 &property_infos);
971 }
Jinguang Dongf42e08d2019-02-15 16:56:28 +0800972 if (access("/product/etc/selinux/product_property_contexts", R_OK) != -1) {
973 LoadPropertyInfoFromFile("/product/etc/selinux/product_property_contexts",
974 &property_infos);
975 }
976 if (access("/odm/etc/selinux/odm_property_contexts", R_OK) != -1) {
977 LoadPropertyInfoFromFile("/odm/etc/selinux/odm_property_contexts", &property_infos);
978 }
Tom Cherry2ae2f602017-12-14 01:58:17 +0000979 } else {
980 if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {
981 return;
982 }
Bowgo Tsai36cf3532017-12-07 16:05:25 +0800983 if (!LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos)) {
984 // Fallback to nonplat_* if vendor_* doesn't exist.
985 LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos);
986 }
Jinguang Dongf42e08d2019-02-15 16:56:28 +0800987 LoadPropertyInfoFromFile("/product_property_contexts", &property_infos);
988 LoadPropertyInfoFromFile("/odm_property_contexts", &property_infos);
Tom Cherry2ae2f602017-12-14 01:58:17 +0000989 }
Tom Cherry927c5d52017-12-11 01:40:07 -0800990
Tom Cherry2ae2f602017-12-14 01:58:17 +0000991 auto serialized_contexts = std::string();
992 auto error = std::string();
Tom Cherry927c5d52017-12-11 01:40:07 -0800993 if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,
Tom Cherry2ae2f602017-12-14 01:58:17 +0000994 &error)) {
995 LOG(ERROR) << "Unable to serialize property contexts: " << error;
996 return;
997 }
998
999 constexpr static const char kPropertyInfosPath[] = "/dev/__properties__/property_info";
1000 if (!WriteStringToFile(serialized_contexts, kPropertyInfosPath, 0444, 0, 0, false)) {
1001 PLOG(ERROR) << "Unable to write serialized property infos to file";
1002 }
1003 selinux_android_restorecon(kPropertyInfosPath, 0);
1004}
1005
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001006static void HandleInitSocket() {
1007 auto message = ReadMessage(init_socket);
1008 if (!message) {
1009 LOG(ERROR) << "Could not read message from init_dedicated_recv_socket: " << message.error();
1010 return;
1011 }
1012
1013 auto init_message = InitMessage{};
1014 if (!init_message.ParseFromString(*message)) {
1015 LOG(ERROR) << "Could not parse message from init";
1016 return;
1017 }
1018
1019 switch (init_message.msg_case()) {
1020 case InitMessage::kLoadPersistentProperties: {
1021 load_override_properties();
1022 // Read persistent properties after all default values have been loaded.
1023 auto persistent_properties = LoadPersistentProperties();
1024 for (const auto& persistent_property_record : persistent_properties.properties()) {
1025 InitPropertySet(persistent_property_record.name(),
1026 persistent_property_record.value());
1027 }
1028 InitPropertySet("ro.persistent_properties.ready", "true");
1029 persistent_properties_loaded = true;
1030 break;
1031 }
1032 case InitMessage::kStopSendingMessages: {
1033 init_socket = -1;
1034 break;
1035 }
1036 default:
1037 LOG(ERROR) << "Unknown message type from init: " << init_message.msg_case();
1038 }
1039}
1040
1041static void PropertyServiceThread() {
1042 Epoll epoll;
1043 if (auto result = epoll.Open(); !result) {
1044 LOG(FATAL) << result.error();
1045 }
1046
1047 if (auto result = epoll.RegisterHandler(property_set_fd, handle_property_set_fd); !result) {
1048 LOG(FATAL) << result.error();
1049 }
1050
1051 if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result) {
1052 LOG(FATAL) << result.error();
1053 }
1054
1055 while (true) {
1056 auto pending_functions = epoll.Wait(std::nullopt);
1057 if (!pending_functions) {
1058 LOG(ERROR) << pending_functions.error();
1059 } else {
1060 for (const auto& function : *pending_functions) {
1061 (*function)();
1062 }
1063 }
1064 }
1065}
1066
1067void StartPropertyService(int* epoll_socket) {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +00001068 property_set("ro.property_service.version", "2");
1069
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001070 int sockets[2];
1071 if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != 0) {
1072 PLOG(FATAL) << "Failed to socketpair() between property_service and init";
1073 }
1074 *epoll_socket = sockets[0];
1075 init_socket = sockets[1];
1076
Tom Cherry3da2ba62019-08-28 17:47:49 +00001077 if (auto result = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1078 false, 0666, 0, 0, {})) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -07001079 property_set_fd = *result;
1080 } else {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001081 LOG(FATAL) << "start_property_service socket creation failed: " << result.error();
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001082 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001083
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001084 listen(property_set_fd, 8);
Colin Crossd11beb22010-04-13 19:33:37 -07001085
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001086 std::thread{PropertyServiceThread}.detach();
1087
1088 property_set = [](const std::string& key, const std::string& value) -> uint32_t {
1089 android::base::SetProperty(key, value);
1090 return 0;
1091 };
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001092}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001093
1094} // namespace init
1095} // namespace android