blob: 730bf6de48588d5e4cd43d6aa09fbf40e3841503 [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;
Nikita Ioffeba6968e2019-10-07 16:26:33 +010096static bool accept_messages = false;
Colin Crossd11beb22010-04-13 19:33:37 -070097
Tom Cherry2ae2f602017-12-14 01:58:17 +000098static PropertyInfoAreaFile property_info_area;
99
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700100struct PropertyAuditData {
101 const ucred* cr;
102 const char* name;
103};
104
Tom Cherry2f113ad2019-04-22 10:22:41 -0700105static int PropertyAuditCallback(void* data, security_class_t /*cls*/, char* buf, size_t len) {
106 auto* d = reinterpret_cast<PropertyAuditData*>(data);
107
108 if (!d || !d->name || !d->cr) {
109 LOG(ERROR) << "AuditCallback invoked with null data arguments!";
110 return 0;
111 }
112
113 snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name, d->cr->pid, d->cr->uid,
114 d->cr->gid);
115 return 0;
116}
117
Tom Cherryb35f8272018-10-22 14:50:52 -0700118bool CanReadProperty(const std::string& source_context, const std::string& name) {
119 const char* target_context = nullptr;
120 property_info_area->GetPropertyInfo(name.c_str(), &target_context, nullptr);
121
122 PropertyAuditData audit_data;
123
124 audit_data.name = name.c_str();
125
126 ucred cr = {.pid = 0, .uid = 0, .gid = 0};
127 audit_data.cr = &cr;
128
129 return selinux_check_access(source_context.c_str(), target_context, "file", "read",
130 &audit_data) == 0;
131}
132
Tom Cherry927c5d52017-12-11 01:40:07 -0800133static bool CheckMacPerms(const std::string& name, const char* target_context,
Tom Cherry32228482018-01-18 16:14:25 -0800134 const char* source_context, const ucred& cr) {
Tom Cherry927c5d52017-12-11 01:40:07 -0800135 if (!target_context || !source_context) {
Tom Cherry2ae2f602017-12-14 01:58:17 +0000136 return false;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000137 }
138
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700139 PropertyAuditData audit_data;
rpcraig63207cd2012-08-09 10:05:49 -0400140
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000141 audit_data.name = name.c_str();
Tom Cherry32228482018-01-18 16:14:25 -0800142 audit_data.cr = &cr;
William Robertsd7aea442015-10-01 16:03:47 -0700143
Tom Cherry927c5d52017-12-11 01:40:07 -0800144 bool has_access = (selinux_check_access(source_context, target_context, "property_service",
145 "set", &audit_data) == 0);
rpcraig63207cd2012-08-09 10:05:49 -0400146
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000147 return has_access;
rpcraig63207cd2012-08-09 10:05:49 -0400148}
149
Tom Cherry832f9f12020-03-10 11:47:24 -0700150static void SendPropertyChanged(const std::string& name, const std::string& value) {
151 auto property_msg = PropertyMessage{};
152 auto* changed_message = property_msg.mutable_changed_message();
153 changed_message->set_name(name);
154 changed_message->set_value(value);
155
156 if (auto result = SendMessage(init_socket, property_msg); !result.ok()) {
157 LOG(ERROR) << "Failed to send property changed message: " << result.error();
158 }
159}
160
Tom Cherry69d47aa2018-03-01 11:00:57 -0800161static uint32_t PropertySet(const std::string& name, const std::string& value, std::string* error) {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000162 size_t valuelen = value.size();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800163
Tom Cherryde6bd502018-02-13 16:50:08 -0800164 if (!IsLegalPropertyName(name)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800165 *error = "Illegal property name";
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000166 return PROP_ERROR_INVALID_NAME;
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000167 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000168
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900169 if (auto result = IsLegalPropertyValue(name, value); !result.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700170 *error = result.error().message();
Tom Cherry8702dcb2017-10-13 16:20:19 -0700171 return PROP_ERROR_INVALID_VALUE;
172 }
173
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000174 prop_info* pi = (prop_info*) __system_property_find(name.c_str());
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000175 if (pi != nullptr) {
176 // ro.* properties are actually "write-once".
Tom Cherry1cf8d692017-10-10 13:35:01 -0700177 if (StartsWith(name, "ro.")) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800178 *error = "Read-only property was already set";
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000179 return PROP_ERROR_READ_ONLY_PROPERTY;
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000180 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800181
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000182 __system_property_update(pi, value.c_str(), valuelen);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800183 } else {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000184 int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
Elliott Hughesdb3f2672015-03-20 09:45:18 -0700185 if (rc < 0) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800186 *error = "__system_property_add failed";
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000187 return PROP_ERROR_SET_FAILED;
Johan Redestigfd7ffb12013-04-29 09:11:57 +0200188 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800189 }
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000190
Elliott Hughes4f915812016-12-05 13:12:48 -0800191 // Don't write properties to disk until after we have read all default
192 // properties to prevent them from being overwritten by default values.
Tom Cherry1cf8d692017-10-10 13:35:01 -0700193 if (persistent_properties_loaded && StartsWith(name, "persist.")) {
Tom Cherry16fad422017-08-04 15:59:03 -0700194 WritePersistentProperty(name, value);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800195 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700196 // If init hasn't started its main loop, then it won't be handling property changed messages
197 // anyway, so there's no need to try to send them.
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100198 if (accept_messages) {
Tom Cherry832f9f12020-03-10 11:47:24 -0700199 SendPropertyChanged(name, value);
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700200 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000201 return PROP_SUCCESS;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800202}
203
Tom Cherry832f9f12020-03-10 11:47:24 -0700204class AsyncRestorecon {
Tom Cherryfe815412019-04-23 15:11:07 -0700205 public:
Tom Cherry832f9f12020-03-10 11:47:24 -0700206 void TriggerRestorecon(const std::string& path) {
Tom Cherry7205c622020-01-29 14:09:24 -0800207 auto guard = std::lock_guard{mutex_};
Tom Cherry832f9f12020-03-10 11:47:24 -0700208 paths_.emplace(path);
Tom Cherry7205c622020-01-29 14:09:24 -0800209
Tom Cherry832f9f12020-03-10 11:47:24 -0700210 if (!thread_started_) {
211 thread_started_ = true;
212 std::thread{&AsyncRestorecon::ThreadFunction, this}.detach();
Tom Cherryfe815412019-04-23 15:11:07 -0700213 }
214 }
215
216 private:
217 void ThreadFunction() {
218 auto lock = std::unique_lock{mutex_};
219
Tom Cherry832f9f12020-03-10 11:47:24 -0700220 while (!paths_.empty()) {
221 auto path = paths_.front();
222 paths_.pop();
Tom Cherryfe815412019-04-23 15:11:07 -0700223
224 lock.unlock();
Tom Cherry832f9f12020-03-10 11:47:24 -0700225 if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
226 LOG(ERROR) << "Asynchronous restorecon of '" << path << "' failed'";
227 }
228 android::base::SetProperty(kRestoreconProperty, path);
Tom Cherryfe815412019-04-23 15:11:07 -0700229 lock.lock();
230 }
231
Tom Cherry832f9f12020-03-10 11:47:24 -0700232 thread_started_ = false;
Tom Cherryfe815412019-04-23 15:11:07 -0700233 }
234
235 std::mutex mutex_;
Tom Cherry832f9f12020-03-10 11:47:24 -0700236 std::queue<std::string> paths_;
237 bool thread_started_ = false;
Tom Marshall62696902017-06-09 18:29:23 +0000238};
239
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000240class SocketConnection {
Tom Cherry32228482018-01-18 16:14:25 -0800241 public:
242 SocketConnection(int socket, const ucred& cred) : socket_(socket), cred_(cred) {}
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000243
Tom Cherry32228482018-01-18 16:14:25 -0800244 bool RecvUint32(uint32_t* value, uint32_t* timeout_ms) {
245 return RecvFully(value, sizeof(*value), timeout_ms);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000246 }
247
Tom Cherry32228482018-01-18 16:14:25 -0800248 bool RecvChars(char* chars, size_t size, uint32_t* timeout_ms) {
249 return RecvFully(chars, size, timeout_ms);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000250 }
251
Tom Cherry32228482018-01-18 16:14:25 -0800252 bool RecvString(std::string* value, uint32_t* timeout_ms) {
253 uint32_t len = 0;
254 if (!RecvUint32(&len, timeout_ms)) {
255 return false;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000256 }
Tom Cherry32228482018-01-18 16:14:25 -0800257
258 if (len == 0) {
259 *value = "";
260 return true;
261 }
262
263 // http://b/35166374: don't allow init to make arbitrarily large allocations.
264 if (len > 0xffff) {
265 LOG(ERROR) << "sys_prop: RecvString asked to read huge string: " << len;
266 errno = ENOMEM;
267 return false;
268 }
269
270 std::vector<char> chars(len);
271 if (!RecvChars(&chars[0], len, timeout_ms)) {
272 return false;
273 }
274
275 *value = std::string(&chars[0], len);
276 return true;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000277 }
278
Tom Cherry32228482018-01-18 16:14:25 -0800279 bool SendUint32(uint32_t value) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700280 if (!socket_.ok()) {
281 return true;
282 }
Tom Cherry32228482018-01-18 16:14:25 -0800283 int result = TEMP_FAILURE_RETRY(send(socket_, &value, sizeof(value), 0));
284 return result == sizeof(value);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000285 }
286
Tom Cherry7f160af2019-04-22 13:28:28 -0700287 bool GetSourceContext(std::string* source_context) const {
288 char* c_source_context = nullptr;
289 if (getpeercon(socket_, &c_source_context) != 0) {
290 return false;
291 }
292 *source_context = c_source_context;
293 freecon(c_source_context);
294 return true;
295 }
296
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700297 [[nodiscard]] int Release() { return socket_.release(); }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000298
Tom Cherry32228482018-01-18 16:14:25 -0800299 const ucred& cred() { return cred_; }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000300
Tom Cherry32228482018-01-18 16:14:25 -0800301 private:
302 bool PollIn(uint32_t* timeout_ms) {
303 struct pollfd ufds[1];
304 ufds[0].fd = socket_;
305 ufds[0].events = POLLIN;
306 ufds[0].revents = 0;
307 while (*timeout_ms > 0) {
308 auto start_time = std::chrono::steady_clock::now();
309 int nr = poll(ufds, 1, *timeout_ms);
310 auto now = std::chrono::steady_clock::now();
311 auto time_elapsed =
312 std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
313 uint64_t millis = time_elapsed.count();
314 *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
315
316 if (nr > 0) {
317 return true;
318 }
319
320 if (nr == 0) {
321 // Timeout
322 break;
323 }
324
325 if (nr < 0 && errno != EINTR) {
326 PLOG(ERROR) << "sys_prop: error waiting for uid " << cred_.uid
327 << " to send property message";
328 return false;
329 } else { // errno == EINTR
330 // Timer rounds milliseconds down in case of EINTR we want it to be rounded up
331 // to avoid slowing init down by causing EINTR with under millisecond timeout.
332 if (*timeout_ms > 0) {
333 --(*timeout_ms);
334 }
335 }
336 }
337
338 LOG(ERROR) << "sys_prop: timeout waiting for uid " << cred_.uid
339 << " to send property message.";
340 return false;
341 }
342
343 bool RecvFully(void* data_ptr, size_t size, uint32_t* timeout_ms) {
344 size_t bytes_left = size;
345 char* data = static_cast<char*>(data_ptr);
346 while (*timeout_ms > 0 && bytes_left > 0) {
347 if (!PollIn(timeout_ms)) {
348 return false;
349 }
350
351 int result = TEMP_FAILURE_RETRY(recv(socket_, data, bytes_left, MSG_DONTWAIT));
352 if (result <= 0) {
DuXiao40533592018-05-21 14:43:56 +0800353 PLOG(ERROR) << "sys_prop: recv error";
Tom Cherry32228482018-01-18 16:14:25 -0800354 return false;
355 }
356
357 bytes_left -= result;
358 data += result;
359 }
360
DuXiao40533592018-05-21 14:43:56 +0800361 if (bytes_left != 0) {
362 LOG(ERROR) << "sys_prop: recv data is not properly obtained.";
363 }
364
Tom Cherry32228482018-01-18 16:14:25 -0800365 return bytes_left == 0;
366 }
367
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700368 unique_fd socket_;
Tom Cherry32228482018-01-18 16:14:25 -0800369 ucred cred_;
Tom Cherry3da2ba62019-08-28 17:47:49 +0000370
371 DISALLOW_IMPLICIT_CONSTRUCTORS(SocketConnection);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000372};
373
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700374static uint32_t SendControlMessage(const std::string& msg, const std::string& name, pid_t pid,
375 SocketConnection* socket, std::string* error) {
Nikita Ioffeba6968e2019-10-07 16:26:33 +0100376 if (!accept_messages) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700377 *error = "Received control message after shutdown, ignoring";
378 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
379 }
380
Tom Cherry832f9f12020-03-10 11:47:24 -0700381 auto property_msg = PropertyMessage{};
382 auto* control_message = property_msg.mutable_control_message();
383 control_message->set_msg(msg);
384 control_message->set_name(name);
385 control_message->set_pid(pid);
386
387 // We must release the fd before sending it to init, otherwise there will be a race with init.
388 // If init calls close() before Release(), then fdsan will see the wrong tag and abort().
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700389 int fd = -1;
Tom Cherry5310db82019-10-22 08:27:23 -0700390 if (socket != nullptr && SelinuxGetVendorAndroidVersion() > __ANDROID_API_Q__) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700391 fd = socket->Release();
Tom Cherry832f9f12020-03-10 11:47:24 -0700392 control_message->set_fd(fd);
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700393 }
394
Tom Cherry832f9f12020-03-10 11:47:24 -0700395 if (auto result = SendMessage(init_socket, property_msg); !result.ok()) {
396 // We've already released the fd above, so if we fail to send the message to init, we need
397 // to manually free it here.
398 if (fd != -1) {
399 close(fd);
400 }
401 *error = "Failed to send control message: " + result.error().message();
402 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
403 }
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700404
405 return PROP_SUCCESS;
406}
407
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700408bool CheckControlPropertyPerms(const std::string& name, const std::string& value,
409 const std::string& source_context, const ucred& cr) {
410 // We check the legacy method first but these properties are dontaudit, so we only log an audit
411 // if the newer method fails as well. We only do this with the legacy ctl. properties.
412 if (name == "ctl.start" || name == "ctl.stop" || name == "ctl.restart") {
413 // The legacy permissions model is that ctl. properties have their name ctl.<action> and
414 // their value is the name of the service to apply that action to. Permissions for these
415 // actions are based on the service, so we must create a fake name of ctl.<service> to
416 // check permissions.
417 auto control_string_legacy = "ctl." + value;
418 const char* target_context_legacy = nullptr;
419 const char* type_legacy = nullptr;
420 property_info_area->GetPropertyInfo(control_string_legacy.c_str(), &target_context_legacy,
421 &type_legacy);
422
423 if (CheckMacPerms(control_string_legacy, target_context_legacy, source_context.c_str(), cr)) {
424 return true;
425 }
426 }
427
428 auto control_string_full = name + "$" + value;
429 const char* target_context_full = nullptr;
430 const char* type_full = nullptr;
431 property_info_area->GetPropertyInfo(control_string_full.c_str(), &target_context_full,
432 &type_full);
433
434 return CheckMacPerms(control_string_full, target_context_full, source_context.c_str(), cr);
435}
436
Tom Cherry32228482018-01-18 16:14:25 -0800437// This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
Tom Cherrybe048922019-02-16 12:03:19 -0800438uint32_t CheckPermissions(const std::string& name, const std::string& value,
439 const std::string& source_context, const ucred& cr, std::string* error) {
Tom Cherryde6bd502018-02-13 16:50:08 -0800440 if (!IsLegalPropertyName(name)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800441 *error = "Illegal property name";
Tom Cherry32228482018-01-18 16:14:25 -0800442 return PROP_ERROR_INVALID_NAME;
443 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000444
Tom Cherry32228482018-01-18 16:14:25 -0800445 if (StartsWith(name, "ctl.")) {
Tom Cherry5ab2e1c2018-05-03 16:57:19 -0700446 if (!CheckControlPropertyPerms(name, value, source_context, cr)) {
447 *error = StringPrintf("Invalid permissions to perform '%s' on '%s'", name.c_str() + 4,
448 value.c_str());
Tom Cherry32228482018-01-18 16:14:25 -0800449 return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
450 }
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000451
Tom Cherry32228482018-01-18 16:14:25 -0800452 return PROP_SUCCESS;
453 }
Tom Cherry927c5d52017-12-11 01:40:07 -0800454
Tom Cherry32228482018-01-18 16:14:25 -0800455 const char* target_context = nullptr;
456 const char* type = nullptr;
457 property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type);
Tom Cherrya84e14d2017-09-05 12:38:30 -0700458
Tom Cherry32228482018-01-18 16:14:25 -0800459 if (!CheckMacPerms(name, target_context, source_context.c_str(), cr)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800460 *error = "SELinux permission check failed";
Tom Cherry32228482018-01-18 16:14:25 -0800461 return PROP_ERROR_PERMISSION_DENIED;
462 }
463
Tom Cherryb5f2ec02019-11-08 17:54:27 -0800464 if (!CheckType(type, value)) {
Tom Cherry69d47aa2018-03-01 11:00:57 -0800465 *error = StringPrintf("Property type check failed, value doesn't match expected type '%s'",
466 (type ?: "(null)"));
Tom Cherry32228482018-01-18 16:14:25 -0800467 return PROP_ERROR_INVALID_VALUE;
468 }
469
Tom Cherrybe048922019-02-16 12:03:19 -0800470 return PROP_SUCCESS;
471}
472
473// This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
474uint32_t HandlePropertySet(const std::string& name, const std::string& value,
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700475 const std::string& source_context, const ucred& cr,
476 SocketConnection* socket, std::string* error) {
Tom Cherrybe048922019-02-16 12:03:19 -0800477 if (auto ret = CheckPermissions(name, value, source_context, cr, error); ret != PROP_SUCCESS) {
478 return ret;
479 }
480
481 if (StartsWith(name, "ctl.")) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700482 return SendControlMessage(name.c_str() + 4, value, cr.pid, socket, error);
Tom Cherrybe048922019-02-16 12:03:19 -0800483 }
484
Tom Cherry32228482018-01-18 16:14:25 -0800485 // sys.powerctl is a special property that is used to make the device reboot. We want to log
486 // any process that sets this property to be able to accurately blame the cause of a shutdown.
487 if (name == "sys.powerctl") {
488 std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
489 std::string process_cmdline;
490 std::string process_log_string;
491 if (ReadFileToString(cmdline_path, &process_cmdline)) {
492 // Since cmdline is null deliminated, .c_str() conveniently gives us just the process
493 // path.
494 process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
495 }
496 LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
497 << process_log_string;
498 }
499
Tom Cherryfe815412019-04-23 15:11:07 -0700500 // If a process other than init is writing a non-empty value, it means that process is
501 // requesting that init performs a restorecon operation on the path specified by 'value'.
502 // We use a thread to do this restorecon operation to prevent holding up init, as it may take
503 // a long time to complete.
504 if (name == kRestoreconProperty && cr.pid != 1 && !value.empty()) {
Tom Cherry832f9f12020-03-10 11:47:24 -0700505 static AsyncRestorecon async_restorecon;
506 async_restorecon.TriggerRestorecon(value);
Tom Cherryfe815412019-04-23 15:11:07 -0700507 return PROP_SUCCESS;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800508 }
509
510 return PropertySet(name, value, error);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000511}
512
513static void handle_property_set_fd() {
514 static constexpr uint32_t kDefaultSocketTimeout = 2000; /* ms */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800515
Robert Sesekca2da602017-01-25 08:08:51 -0500516 int s = accept4(property_set_fd, nullptr, nullptr, SOCK_CLOEXEC);
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700517 if (s == -1) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800518 return;
519 }
520
Tom Cherry32228482018-01-18 16:14:25 -0800521 ucred cr;
Elliott Hughes3dcfa3f2016-08-23 12:50:00 -0700522 socklen_t cr_size = sizeof(cr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800523 if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
524 close(s);
Elliott Hughesb005d902017-02-22 14:54:15 -0800525 PLOG(ERROR) << "sys_prop: unable to get SO_PEERCRED";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800526 return;
527 }
528
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000529 SocketConnection socket(s, cr);
530 uint32_t timeout_ms = kDefaultSocketTimeout;
531
532 uint32_t cmd = 0;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000533 if (!socket.RecvUint32(&cmd, &timeout_ms)) {
534 PLOG(ERROR) << "sys_prop: error while reading command from the socket";
535 socket.SendUint32(PROP_ERROR_READ_CMD);
JP Abgrall4515d812014-01-31 14:37:07 -0800536 return;
537 }
538
Elliott Hughesb005d902017-02-22 14:54:15 -0800539 switch (cmd) {
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000540 case PROP_MSG_SETPROP: {
541 char prop_name[PROP_NAME_MAX];
542 char prop_value[PROP_VALUE_MAX];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800543
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000544 if (!socket.RecvChars(prop_name, PROP_NAME_MAX, &timeout_ms) ||
545 !socket.RecvChars(prop_value, PROP_VALUE_MAX, &timeout_ms)) {
546 PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP): error while reading name/value from the socket";
547 return;
Nick Kralevich69463612013-09-13 17:21:28 -0700548 }
549
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000550 prop_name[PROP_NAME_MAX-1] = 0;
551 prop_value[PROP_VALUE_MAX-1] = 0;
rpcraig63207cd2012-08-09 10:05:49 -0400552
Tom Cherry7f160af2019-04-22 13:28:28 -0700553 std::string source_context;
554 if (!socket.GetSourceContext(&source_context)) {
555 PLOG(ERROR) << "Unable to set property '" << prop_name << "': getpeercon() failed";
556 return;
557 }
558
Tom Cherry69d47aa2018-03-01 11:00:57 -0800559 const auto& cr = socket.cred();
560 std::string error;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700561 uint32_t result =
562 HandlePropertySet(prop_name, prop_value, source_context, cr, nullptr, &error);
Tom Cherry69d47aa2018-03-01 11:00:57 -0800563 if (result != PROP_SUCCESS) {
Nick Kralevich9ca898f2019-04-04 10:10:01 -0700564 LOG(ERROR) << "Unable to set property '" << prop_name << "' from uid:" << cr.uid
565 << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800566 }
567
Dimitry Ivanovdee4bd22017-01-19 14:53:00 -0800568 break;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000569 }
Dimitry Ivanov70c4ecf2017-01-24 18:38:09 +0000570
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000571 case PROP_MSG_SETPROP2: {
572 std::string name;
573 std::string value;
574 if (!socket.RecvString(&name, &timeout_ms) ||
575 !socket.RecvString(&value, &timeout_ms)) {
576 PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP2): error while reading name/value from the socket";
577 socket.SendUint32(PROP_ERROR_READ_DATA);
578 return;
579 }
580
Tom Cherry7f160af2019-04-22 13:28:28 -0700581 std::string source_context;
582 if (!socket.GetSourceContext(&source_context)) {
583 PLOG(ERROR) << "Unable to set property '" << name << "': getpeercon() failed";
584 socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
585 return;
586 }
587
Tom Cherry69d47aa2018-03-01 11:00:57 -0800588 const auto& cr = socket.cred();
589 std::string error;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -0700590 uint32_t result = HandlePropertySet(name, value, source_context, cr, &socket, &error);
Tom Cherry69d47aa2018-03-01 11:00:57 -0800591 if (result != PROP_SUCCESS) {
Nick Kralevich9ca898f2019-04-04 10:10:01 -0700592 LOG(ERROR) << "Unable to set property '" << name << "' from uid:" << cr.uid
593 << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
Tom Cherry69d47aa2018-03-01 11:00:57 -0800594 }
Tom Cherryf4514262019-08-26 16:33:40 +0000595 socket.SendUint32(result);
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000596 break;
597 }
Elliott Hughesb005d902017-02-22 14:54:15 -0800598
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800599 default:
Elliott Hughesb005d902017-02-22 14:54:15 -0800600 LOG(ERROR) << "sys_prop: invalid command " << cmd;
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +0000601 socket.SendUint32(PROP_ERROR_INVALID_CMD);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800602 break;
603 }
604}
605
Tom Cherryc88d8f92019-08-19 15:21:25 -0700606uint32_t InitPropertySet(const std::string& name, const std::string& value) {
607 uint32_t result = 0;
608 ucred cr = {.pid = 1, .uid = 0, .gid = 0};
609 std::string error;
610 result = HandlePropertySet(name, value, kInitContext, cr, nullptr, &error);
611 if (result != PROP_SUCCESS) {
612 LOG(ERROR) << "Init cannot set '" << name << "' to '" << value << "': " << error;
613 }
614
615 return result;
616}
617
Tom Cherrybe048922019-02-16 12:03:19 -0800618static bool load_properties_from_file(const char*, const char*,
619 std::map<std::string, std::string>*);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800621/*
622 * Filter is used to decide which properties to load: NULL loads all keys,
623 * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
624 */
Tom Cherrybe048922019-02-16 12:03:19 -0800625static void LoadProperties(char* data, const char* filter, const char* filename,
626 std::map<std::string, std::string>* properties) {
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800627 char *key, *value, *eol, *sol, *tmp, *fn;
628 size_t flen = 0;
629
Tom Cherry14c24722019-09-18 13:47:19 -0700630 static constexpr const char* const kVendorPathPrefixes[2] = {
631 "/vendor",
632 "/odm",
633 };
634
635 const char* context = kInitContext;
Tom Cherry40acb372018-08-01 13:41:12 -0700636 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
Tom Cherry14c24722019-09-18 13:47:19 -0700637 for (const auto& vendor_path_prefix : kVendorPathPrefixes) {
638 if (StartsWith(filename, vendor_path_prefix)) {
639 context = kVendorContext;
Tom Cherrya1dbeb82018-04-11 15:50:00 -0700640 }
Tom Cherrydc375862018-02-28 10:39:01 -0800641 }
642 }
643
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800644 if (filter) {
645 flen = strlen(filter);
646 }
647
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800648 sol = data;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800649 while ((eol = strchr(sol, '\n'))) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800650 key = sol;
651 *eol++ = 0;
652 sol = eol;
653
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800654 while (isspace(*key)) key++;
655 if (*key == '#') continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800656
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800657 tmp = eol - 2;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800658 while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800659
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800660 if (!strncmp(key, "import ", 7) && flen == 0) {
661 fn = key + 7;
662 while (isspace(*fn)) fn++;
663
664 key = strchr(fn, ' ');
665 if (key) {
666 *key++ = 0;
667 while (isspace(*key)) key++;
668 }
669
Dongcheol Shina87c0f92019-06-12 09:31:35 +0900670 std::string raw_filename(fn);
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700671 auto expanded_filename = ExpandProps(raw_filename);
672
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900673 if (!expanded_filename.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700674 LOG(ERROR) << "Could not expand filename ': " << expanded_filename.error();
Dongcheol Shina87c0f92019-06-12 09:31:35 +0900675 continue;
676 }
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800677
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700678 load_properties_from_file(expanded_filename->c_str(), key, properties);
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800679 } else {
680 value = strchr(key, '=');
681 if (!value) continue;
682 *value++ = 0;
683
684 tmp = value - 2;
685 while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
686
687 while (isspace(*value)) value++;
688
689 if (flen > 0) {
690 if (filter[flen - 1] == '*') {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700691 if (strncmp(key, filter, flen - 1) != 0) continue;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800692 } else {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700693 if (strcmp(key, filter) != 0) continue;
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800694 }
695 }
696
Tom Cherrydc375862018-02-28 10:39:01 -0800697 if (StartsWith(key, "ctl.") || key == "sys.powerctl"s ||
Tom Cherryfe815412019-04-23 15:11:07 -0700698 std::string{key} == kRestoreconProperty) {
Tom Cherrydc375862018-02-28 10:39:01 -0800699 LOG(ERROR) << "Ignoring disallowed property '" << key
700 << "' with special meaning in prop file '" << filename << "'";
701 continue;
702 }
703
Tom Cherrydc375862018-02-28 10:39:01 -0800704 ucred cr = {.pid = 1, .uid = 0, .gid = 0};
705 std::string error;
Tom Cherrybe048922019-02-16 12:03:19 -0800706 if (CheckPermissions(key, value, context, cr, &error) == PROP_SUCCESS) {
707 auto it = properties->find(key);
708 if (it == properties->end()) {
709 (*properties)[key] = value;
710 } else if (it->second != value) {
711 LOG(WARNING) << "Overriding previous 'ro.' property '" << key << "':'"
712 << it->second << "' with new value '" << value << "'";
713 it->second = value;
714 }
715 } else {
716 LOG(ERROR) << "Do not have permissions to set '" << key << "' to '" << value
Tom Cherrydc375862018-02-28 10:39:01 -0800717 << "' in property file '" << filename << "': " << error;
718 }
Jeff Sharkeyf96b0442014-03-06 14:26:36 -0800719 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800720 }
721}
722
Elliott Hughes5a7ad842016-09-30 14:12:33 -0700723// Filter is used to decide which properties to load: NULL loads all keys,
724// "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
Tom Cherrybe048922019-02-16 12:03:19 -0800725static bool load_properties_from_file(const char* filename, const char* filter,
726 std::map<std::string, std::string>* properties) {
Elliott Hughesda40c002015-03-27 23:20:44 -0700727 Timer t;
Tom Cherry62ca6632017-08-03 12:54:07 -0700728 auto file_contents = ReadFile(filename);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900729 if (!file_contents.ok()) {
Tom Cherry62ca6632017-08-03 12:54:07 -0700730 PLOG(WARNING) << "Couldn't load property file '" << filename
731 << "': " << file_contents.error();
Hung-ying Tyanaef2b092017-06-02 18:59:46 +0800732 return false;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800733 }
Tom Cherry62ca6632017-08-03 12:54:07 -0700734 file_contents->push_back('\n');
Tom Cherrydc375862018-02-28 10:39:01 -0800735
Tom Cherrybe048922019-02-16 12:03:19 -0800736 LoadProperties(file_contents->data(), filter, filename, properties);
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000737 LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
Hung-ying Tyanaef2b092017-06-02 18:59:46 +0800738 return true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800739}
740
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900741// persist.sys.usb.config values can't be combined on build-time when property
742// files are split into each partition.
743// So we need to apply the same rule of build/make/tools/post_process_props.py
744// on runtime.
745static void update_sys_usb_config() {
746 bool is_debuggable = android::base::GetBoolProperty("ro.debuggable", false);
747 std::string config = android::base::GetProperty("persist.sys.usb.config", "");
Howard Yenbb578202020-02-26 21:36:59 +0800748 // b/150130503, add (config == "none") condition here to prevent appending
749 // ",adb" if "none" is explicitly defined in default prop.
750 if (config.empty() || config == "none") {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700751 InitPropertySet("persist.sys.usb.config", is_debuggable ? "adb" : "none");
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900752 } else if (is_debuggable && config.find("adb") == std::string::npos &&
753 config.length() + 4 < PROP_VALUE_MAX) {
754 config.append(",adb");
Tom Cherryc88d8f92019-08-19 15:21:25 -0700755 InitPropertySet("persist.sys.usb.config", config);
Jaekyun Seok0cf3a072017-04-24 18:52:54 +0900756 }
757}
758
Nick Kralevich32b90232012-09-19 11:15:24 -0700759static void load_override_properties() {
Elliott Hughesc0e919c2015-02-04 14:46:36 -0800760 if (ALLOW_LOCAL_PROP_OVERRIDE) {
Tom Cherrybe048922019-02-16 12:03:19 -0800761 std::map<std::string, std::string> properties;
762 load_properties_from_file("/data/local.prop", nullptr, &properties);
763 for (const auto& [name, value] : properties) {
764 std::string error;
765 if (PropertySet(name, value, &error) != PROP_SUCCESS) {
766 LOG(ERROR) << "Could not set '" << name << "' to '" << value
767 << "' in /data/local.prop: " << error;
768 }
769 }
Nick Kralevich32b90232012-09-19 11:15:24 -0700770 }
Nick Kralevich32b90232012-09-19 11:15:24 -0700771}
772
Steven Laver57a740e2019-01-29 20:19:05 -0800773// If the ro.product.[brand|device|manufacturer|model|name] properties have not been explicitly
774// set, derive them from ro.product.${partition}.* properties
775static void property_initialize_ro_product_props() {
776 const char* RO_PRODUCT_PROPS_PREFIX = "ro.product.";
777 const char* RO_PRODUCT_PROPS[] = {
778 "brand", "device", "manufacturer", "model", "name",
779 };
780 const char* RO_PRODUCT_PROPS_ALLOWED_SOURCES[] = {
Justin Yun7eaf9b52019-06-28 14:28:00 +0900781 "odm", "product", "system_ext", "system", "vendor",
Steven Laver57a740e2019-01-29 20:19:05 -0800782 };
Justin Yun7eaf9b52019-06-28 14:28:00 +0900783 const char* RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER = "product,odm,vendor,system_ext,system";
Steven Laver57a740e2019-01-29 20:19:05 -0800784 const std::string EMPTY = "";
785
786 std::string ro_product_props_source_order =
787 GetProperty("ro.product.property_source_order", EMPTY);
788
789 if (!ro_product_props_source_order.empty()) {
790 // Verify that all specified sources are valid
791 for (const auto& source : Split(ro_product_props_source_order, ",")) {
792 // Verify that the specified source is valid
793 bool is_allowed_source = false;
794 for (const auto& allowed_source : RO_PRODUCT_PROPS_ALLOWED_SOURCES) {
795 if (source == allowed_source) {
796 is_allowed_source = true;
797 break;
798 }
799 }
800 if (!is_allowed_source) {
801 LOG(ERROR) << "Found unexpected source in ro.product.property_source_order; "
802 "using the default property source order";
803 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
804 break;
805 }
806 }
807 } else {
808 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
809 }
810
811 for (const auto& ro_product_prop : RO_PRODUCT_PROPS) {
812 std::string base_prop(RO_PRODUCT_PROPS_PREFIX);
813 base_prop += ro_product_prop;
814
815 std::string base_prop_val = GetProperty(base_prop, EMPTY);
816 if (!base_prop_val.empty()) {
817 continue;
818 }
819
820 for (const auto& source : Split(ro_product_props_source_order, ",")) {
821 std::string target_prop(RO_PRODUCT_PROPS_PREFIX);
822 target_prop += source;
823 target_prop += '.';
824 target_prop += ro_product_prop;
825
826 std::string target_prop_val = GetProperty(target_prop, EMPTY);
827 if (!target_prop_val.empty()) {
828 LOG(INFO) << "Setting product property " << base_prop << " to '" << target_prop_val
829 << "' (from " << target_prop << ")";
830 std::string error;
831 uint32_t res = PropertySet(base_prop, target_prop_val, &error);
832 if (res != PROP_SUCCESS) {
833 LOG(ERROR) << "Error setting product property " << base_prop << ": err=" << res
834 << " (" << error << ")";
835 }
836 break;
837 }
838 }
839 }
840}
841
842// If the ro.build.fingerprint property has not been set, derive it from constituent pieces
843static void property_derive_build_fingerprint() {
844 std::string build_fingerprint = GetProperty("ro.build.fingerprint", "");
845 if (!build_fingerprint.empty()) {
846 return;
847 }
848
849 const std::string UNKNOWN = "unknown";
850 build_fingerprint = GetProperty("ro.product.brand", UNKNOWN);
851 build_fingerprint += '/';
852 build_fingerprint += GetProperty("ro.product.name", UNKNOWN);
853 build_fingerprint += '/';
854 build_fingerprint += GetProperty("ro.product.device", UNKNOWN);
855 build_fingerprint += ':';
856 build_fingerprint += GetProperty("ro.build.version.release", UNKNOWN);
857 build_fingerprint += '/';
858 build_fingerprint += GetProperty("ro.build.id", UNKNOWN);
859 build_fingerprint += '/';
860 build_fingerprint += GetProperty("ro.build.version.incremental", UNKNOWN);
861 build_fingerprint += ':';
862 build_fingerprint += GetProperty("ro.build.type", UNKNOWN);
863 build_fingerprint += '/';
864 build_fingerprint += GetProperty("ro.build.tags", UNKNOWN);
865
866 LOG(INFO) << "Setting property 'ro.build.fingerprint' to '" << build_fingerprint << "'";
867
868 std::string error;
869 uint32_t res = PropertySet("ro.build.fingerprint", build_fingerprint, &error);
870 if (res != PROP_SUCCESS) {
871 LOG(ERROR) << "Error setting property 'ro.build.fingerprint': err=" << res << " (" << error
872 << ")";
873 }
874}
875
Tom Cherryc88d8f92019-08-19 15:21:25 -0700876void PropertyLoadBootDefaults() {
Jiyong Park3b316ee2019-01-13 02:42:31 +0900877 // TODO(b/117892318): merge prop.default and build.prop files into one
Tom Cherrybe048922019-02-16 12:03:19 -0800878 // We read the properties and their values into a map, in order to always allow properties
879 // loaded in the later property files to override the properties in loaded in the earlier
880 // property files, regardless of if they are "ro." properties or not.
881 std::map<std::string, std::string> properties;
882 if (!load_properties_from_file("/system/etc/prop.default", nullptr, &properties)) {
Jiyong Park3b316ee2019-01-13 02:42:31 +0900883 // Try recovery path
Tom Cherrybe048922019-02-16 12:03:19 -0800884 if (!load_properties_from_file("/prop.default", nullptr, &properties)) {
Jiyong Park3b316ee2019-01-13 02:42:31 +0900885 // Try legacy path
Tom Cherrybe048922019-02-16 12:03:19 -0800886 load_properties_from_file("/default.prop", nullptr, &properties);
Jiyong Park3b316ee2019-01-13 02:42:31 +0900887 }
888 }
Tom Cherrybe048922019-02-16 12:03:19 -0800889 load_properties_from_file("/system/build.prop", nullptr, &properties);
Justin Yun7eaf9b52019-06-28 14:28:00 +0900890 load_properties_from_file("/system_ext/build.prop", nullptr, &properties);
Tom Cherrybe048922019-02-16 12:03:19 -0800891 load_properties_from_file("/vendor/default.prop", nullptr, &properties);
892 load_properties_from_file("/vendor/build.prop", nullptr, &properties);
Bowgo Tsai9fc8dcf2019-05-17 15:40:18 +0800893 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_Q__) {
894 load_properties_from_file("/odm/etc/build.prop", nullptr, &properties);
895 } else {
896 load_properties_from_file("/odm/default.prop", nullptr, &properties);
897 load_properties_from_file("/odm/build.prop", nullptr, &properties);
898 }
Tom Cherrybe048922019-02-16 12:03:19 -0800899 load_properties_from_file("/product/build.prop", nullptr, &properties);
Tom Cherrybe048922019-02-16 12:03:19 -0800900 load_properties_from_file("/factory/factory.prop", "ro.*", &properties);
901
Tom Cherryc88d8f92019-08-19 15:21:25 -0700902 if (access(kDebugRamdiskProp, R_OK) == 0) {
Bowgo Tsai30afda72019-04-11 23:57:24 +0800903 LOG(INFO) << "Loading " << kDebugRamdiskProp;
904 load_properties_from_file(kDebugRamdiskProp, nullptr, &properties);
Bowgo Tsai1dacd422019-03-04 17:53:34 +0800905 }
906
Tom Cherrybe048922019-02-16 12:03:19 -0800907 for (const auto& [name, value] : properties) {
908 std::string error;
909 if (PropertySet(name, value, &error) != PROP_SUCCESS) {
910 LOG(ERROR) << "Could not set '" << name << "' to '" << value
911 << "' while loading .prop files" << error;
912 }
913 }
Jiyong Park3b316ee2019-01-13 02:42:31 +0900914
Steven Laver57a740e2019-01-29 20:19:05 -0800915 property_initialize_ro_product_props();
916 property_derive_build_fingerprint();
917
Jiyong Park3b316ee2019-01-13 02:42:31 +0900918 update_sys_usb_config();
Riley Andrewse4b7b292014-06-16 15:06:21 -0700919}
920
Tom Cherry2ae2f602017-12-14 01:58:17 +0000921bool LoadPropertyInfoFromFile(const std::string& filename,
922 std::vector<PropertyInfoEntry>* property_infos) {
923 auto file_contents = std::string();
924 if (!ReadFileToString(filename, &file_contents)) {
925 PLOG(ERROR) << "Could not read properties from '" << filename << "'";
926 return false;
927 }
928
Tom Cherry919458c2018-01-03 14:39:28 -0800929 auto errors = std::vector<std::string>{};
Tom Cherry4b077c52019-12-11 07:56:51 -0800930 bool require_prefix_or_exact = SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__;
931 ParsePropertyInfoFile(file_contents, require_prefix_or_exact, property_infos, &errors);
Tom Cherry919458c2018-01-03 14:39:28 -0800932 // Individual parsing errors are reported but do not cause a failed boot, which is what
933 // returning false would do here.
934 for (const auto& error : errors) {
935 LOG(ERROR) << "Could not read line from '" << filename << "': " << error;
Tom Cherry2ae2f602017-12-14 01:58:17 +0000936 }
Tom Cherry919458c2018-01-03 14:39:28 -0800937
Tom Cherry2ae2f602017-12-14 01:58:17 +0000938 return true;
939}
940
941void CreateSerializedPropertyInfo() {
942 auto property_infos = std::vector<PropertyInfoEntry>();
943 if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
944 if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",
945 &property_infos)) {
946 return;
947 }
948 // Don't check for failure here, so we always have a sane list of properties.
949 // E.g. In case of recovery, the vendor partition will not have mounted and we
950 // still need the system / platform properties to function.
Bowgo Tsai1a191bf2019-10-02 16:23:32 +0800951 if (access("/system_ext/etc/selinux/system_ext_property_contexts", R_OK) != -1) {
952 LoadPropertyInfoFromFile("/system_ext/etc/selinux/system_ext_property_contexts",
953 &property_infos);
954 }
Bowgo Tsai36cf3532017-12-07 16:05:25 +0800955 if (!LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",
956 &property_infos)) {
957 // Fallback to nonplat_* if vendor_* doesn't exist.
958 LoadPropertyInfoFromFile("/vendor/etc/selinux/nonplat_property_contexts",
959 &property_infos);
960 }
Jinguang Dongf42e08d2019-02-15 16:56:28 +0800961 if (access("/product/etc/selinux/product_property_contexts", R_OK) != -1) {
962 LoadPropertyInfoFromFile("/product/etc/selinux/product_property_contexts",
963 &property_infos);
964 }
965 if (access("/odm/etc/selinux/odm_property_contexts", R_OK) != -1) {
966 LoadPropertyInfoFromFile("/odm/etc/selinux/odm_property_contexts", &property_infos);
967 }
Tom Cherry2ae2f602017-12-14 01:58:17 +0000968 } else {
969 if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {
970 return;
971 }
Bowgo Tsai1a191bf2019-10-02 16:23:32 +0800972 LoadPropertyInfoFromFile("/system_ext_property_contexts", &property_infos);
Bowgo Tsai36cf3532017-12-07 16:05:25 +0800973 if (!LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos)) {
974 // Fallback to nonplat_* if vendor_* doesn't exist.
975 LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos);
976 }
Jinguang Dongf42e08d2019-02-15 16:56:28 +0800977 LoadPropertyInfoFromFile("/product_property_contexts", &property_infos);
978 LoadPropertyInfoFromFile("/odm_property_contexts", &property_infos);
Tom Cherry2ae2f602017-12-14 01:58:17 +0000979 }
Tom Cherry927c5d52017-12-11 01:40:07 -0800980
Tom Cherry2ae2f602017-12-14 01:58:17 +0000981 auto serialized_contexts = std::string();
982 auto error = std::string();
Tom Cherry927c5d52017-12-11 01:40:07 -0800983 if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,
Tom Cherry2ae2f602017-12-14 01:58:17 +0000984 &error)) {
985 LOG(ERROR) << "Unable to serialize property contexts: " << error;
986 return;
987 }
988
989 constexpr static const char kPropertyInfosPath[] = "/dev/__properties__/property_info";
990 if (!WriteStringToFile(serialized_contexts, kPropertyInfosPath, 0444, 0, 0, false)) {
991 PLOG(ERROR) << "Unable to write serialized property infos to file";
992 }
993 selinux_android_restorecon(kPropertyInfosPath, 0);
994}
995
Tom Cherryc88d8f92019-08-19 15:21:25 -0700996static void ExportKernelBootProps() {
997 constexpr const char* UNSET = "";
998 struct {
999 const char* src_prop;
1000 const char* dst_prop;
1001 const char* default_value;
1002 } prop_map[] = {
1003 // clang-format off
1004 { "ro.boot.serialno", "ro.serialno", UNSET, },
1005 { "ro.boot.mode", "ro.bootmode", "unknown", },
1006 { "ro.boot.baseband", "ro.baseband", "unknown", },
1007 { "ro.boot.bootloader", "ro.bootloader", "unknown", },
1008 { "ro.boot.hardware", "ro.hardware", "unknown", },
1009 { "ro.boot.revision", "ro.revision", "0", },
1010 // clang-format on
1011 };
1012 for (const auto& prop : prop_map) {
1013 std::string value = GetProperty(prop.src_prop, prop.default_value);
1014 if (value != UNSET) InitPropertySet(prop.dst_prop, value);
1015 }
1016}
1017
1018static void ProcessKernelDt() {
1019 if (!is_android_dt_value_expected("compatible", "android,firmware")) {
1020 return;
1021 }
1022
1023 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(get_android_dt_dir().c_str()), closedir);
1024 if (!dir) return;
1025
1026 std::string dt_file;
1027 struct dirent* dp;
1028 while ((dp = readdir(dir.get())) != NULL) {
1029 if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") ||
1030 !strcmp(dp->d_name, "name")) {
1031 continue;
1032 }
1033
1034 std::string file_name = get_android_dt_dir() + dp->d_name;
1035
1036 android::base::ReadFileToString(file_name, &dt_file);
1037 std::replace(dt_file.begin(), dt_file.end(), ',', '.');
1038
1039 InitPropertySet("ro.boot."s + dp->d_name, dt_file);
1040 }
1041}
1042
1043static void ProcessKernelCmdline() {
1044 bool for_emulator = false;
1045 ImportKernelCmdline([&](const std::string& key, const std::string& value) {
1046 if (key == "qemu") {
1047 for_emulator = true;
1048 } else if (StartsWith(key, "androidboot.")) {
1049 InitPropertySet("ro.boot." + key.substr(12), value);
1050 }
1051 });
1052
1053 if (for_emulator) {
1054 ImportKernelCmdline([&](const std::string& key, const std::string& value) {
1055 // In the emulator, export any kernel option with the "ro.kernel." prefix.
1056 InitPropertySet("ro.kernel." + key, value);
1057 });
1058 }
1059}
1060
1061void PropertyInit() {
1062 selinux_callback cb;
1063 cb.func_audit = PropertyAuditCallback;
1064 selinux_set_callback(SELINUX_CB_AUDIT, cb);
1065
1066 mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);
1067 CreateSerializedPropertyInfo();
1068 if (__system_property_area_init()) {
1069 LOG(FATAL) << "Failed to initialize property area";
1070 }
1071 if (!property_info_area.LoadDefaultPath()) {
1072 LOG(FATAL) << "Failed to load serialized property info file";
1073 }
1074
1075 // If arguments are passed both on the command line and in DT,
1076 // properties set in DT always have priority over the command-line ones.
1077 ProcessKernelDt();
1078 ProcessKernelCmdline();
1079
1080 // Propagate the kernel variables to internal variables
1081 // used by init as well as the current required properties.
1082 ExportKernelBootProps();
1083
1084 PropertyLoadBootDefaults();
1085}
1086
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001087static void HandleInitSocket() {
1088 auto message = ReadMessage(init_socket);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001089 if (!message.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001090 LOG(ERROR) << "Could not read message from init_dedicated_recv_socket: " << message.error();
1091 return;
1092 }
1093
1094 auto init_message = InitMessage{};
1095 if (!init_message.ParseFromString(*message)) {
1096 LOG(ERROR) << "Could not parse message from init";
1097 return;
1098 }
1099
1100 switch (init_message.msg_case()) {
1101 case InitMessage::kLoadPersistentProperties: {
1102 load_override_properties();
1103 // Read persistent properties after all default values have been loaded.
1104 auto persistent_properties = LoadPersistentProperties();
1105 for (const auto& persistent_property_record : persistent_properties.properties()) {
1106 InitPropertySet(persistent_property_record.name(),
1107 persistent_property_record.value());
1108 }
1109 InitPropertySet("ro.persistent_properties.ready", "true");
1110 persistent_properties_loaded = true;
1111 break;
1112 }
1113 case InitMessage::kStopSendingMessages: {
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001114 accept_messages = false;
1115 break;
1116 }
1117 case InitMessage::kStartSendingMessages: {
1118 accept_messages = true;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001119 break;
1120 }
1121 default:
1122 LOG(ERROR) << "Unknown message type from init: " << init_message.msg_case();
1123 }
1124}
1125
1126static void PropertyServiceThread() {
1127 Epoll epoll;
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001128 if (auto result = epoll.Open(); !result.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001129 LOG(FATAL) << result.error();
1130 }
1131
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001132 if (auto result = epoll.RegisterHandler(property_set_fd, handle_property_set_fd);
1133 !result.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001134 LOG(FATAL) << result.error();
1135 }
1136
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001137 if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001138 LOG(FATAL) << result.error();
1139 }
1140
Tom Cherry832f9f12020-03-10 11:47:24 -07001141 while (true) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001142 auto pending_functions = epoll.Wait(std::nullopt);
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001143 if (!pending_functions.ok()) {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001144 LOG(ERROR) << pending_functions.error();
1145 } else {
1146 for (const auto& function : *pending_functions) {
1147 (*function)();
1148 }
1149 }
1150 }
1151}
1152
1153void StartPropertyService(int* epoll_socket) {
Tom Cherryc88d8f92019-08-19 15:21:25 -07001154 InitPropertySet("ro.property_service.version", "2");
Dimitry Ivanovc9bb0332017-01-24 20:43:58 +00001155
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001156 int sockets[2];
1157 if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != 0) {
1158 PLOG(FATAL) << "Failed to socketpair() between property_service and init";
1159 }
Tom Cherry832f9f12020-03-10 11:47:24 -07001160 *epoll_socket = sockets[0];
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001161 init_socket = sockets[1];
Nikita Ioffeba6968e2019-10-07 16:26:33 +01001162 accept_messages = true;
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001163
Tom Cherry3da2ba62019-08-28 17:47:49 +00001164 if (auto result = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
Bernie Innocenticecebbb2020-02-06 03:49:33 +09001165 false, 0666, 0, 0, {});
1166 result.ok()) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -07001167 property_set_fd = *result;
1168 } else {
Tom Cherry1ab3dfc2019-04-22 17:46:37 -07001169 LOG(FATAL) << "start_property_service socket creation failed: " << result.error();
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001170 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001171
Elliott Hughesc6c26ed2015-04-24 18:50:30 -07001172 listen(property_set_fd, 8);
Colin Crossd11beb22010-04-13 19:33:37 -07001173
Tom Cherry832f9f12020-03-10 11:47:24 -07001174 std::thread{PropertyServiceThread}.detach();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001175}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001176
1177} // namespace init
1178} // namespace android