1 /*
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 
17 #include "property_service.h"
18 
19 #include <android/api-level.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <limits.h>
25 #include <netinet/in.h>
26 #include <stdarg.h>
27 #include <stddef.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/mman.h>
32 #include <sys/poll.h>
33 #include <sys/select.h>
34 #include <sys/types.h>
35 #include <sys/un.h>
36 #include <unistd.h>
37 #include <wchar.h>
38 
39 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
40 #include <sys/_system_properties.h>
41 
42 #include <map>
43 #include <memory>
44 #include <mutex>
45 #include <optional>
46 #include <queue>
47 #include <string_view>
48 #include <thread>
49 #include <vector>
50 
51 #include <InitProperties.sysprop.h>
52 #include <android-base/chrono_utils.h>
53 #include <android-base/file.h>
54 #include <android-base/logging.h>
55 #include <android-base/parseint.h>
56 #include <android-base/properties.h>
57 #include <android-base/result.h>
58 #include <android-base/stringprintf.h>
59 #include <android-base/strings.h>
60 #include <property_info_parser/property_info_parser.h>
61 #include <property_info_serializer/property_info_serializer.h>
62 #include <selinux/android.h>
63 #include <selinux/label.h>
64 #include <selinux/selinux.h>
65 
66 #include "debug_ramdisk.h"
67 #include "epoll.h"
68 #include "init.h"
69 #include "persistent_properties.h"
70 #include "property_type.h"
71 #include "proto_utils.h"
72 #include "second_stage_resources.h"
73 #include "selinux.h"
74 #include "subcontext.h"
75 #include "system/core/init/property_service.pb.h"
76 #include "util.h"
77 
78 using namespace std::literals;
79 
80 using android::base::ErrnoError;
81 using android::base::Error;
82 using android::base::GetProperty;
83 using android::base::ParseInt;
84 using android::base::ReadFileToString;
85 using android::base::Result;
86 using android::base::Split;
87 using android::base::StartsWith;
88 using android::base::StringPrintf;
89 using android::base::Timer;
90 using android::base::Trim;
91 using android::base::unique_fd;
92 using android::base::WriteStringToFile;
93 using android::properties::BuildTrie;
94 using android::properties::ParsePropertyInfoFile;
95 using android::properties::PropertyInfoAreaFile;
96 using android::properties::PropertyInfoEntry;
97 using android::sysprop::InitProperties::is_userspace_reboot_supported;
98 
99 namespace android {
100 namespace init {
101 
102 class PersistWriteThread;
103 
104 constexpr auto FINGERPRINT_PROP = "ro.build.fingerprint";
105 constexpr auto LEGACY_FINGERPRINT_PROP = "ro.build.legacy.fingerprint";
106 constexpr auto ID_PROP = "ro.build.id";
107 constexpr auto LEGACY_ID_PROP = "ro.build.legacy.id";
108 constexpr auto VBMETA_DIGEST_PROP = "ro.boot.vbmeta.digest";
109 constexpr auto DIGEST_SIZE_USED = 8;
110 constexpr auto API_LEVEL_CURRENT = 10000;
111 
112 static bool persistent_properties_loaded = false;
113 
114 static int property_set_fd = -1;
115 static int from_init_socket = -1;
116 static int init_socket = -1;
117 static bool accept_messages = false;
118 static std::mutex accept_messages_lock;
119 static std::thread property_service_thread;
120 
121 static std::unique_ptr<PersistWriteThread> persist_write_thread;
122 
123 static PropertyInfoAreaFile property_info_area;
124 
125 struct PropertyAuditData {
126     const ucred* cr;
127     const char* name;
128 };
129 
PropertyAuditCallback(void * data,security_class_t,char * buf,size_t len)130 static int PropertyAuditCallback(void* data, security_class_t /*cls*/, char* buf, size_t len) {
131     auto* d = reinterpret_cast<PropertyAuditData*>(data);
132 
133     if (!d || !d->name || !d->cr) {
134         LOG(ERROR) << "AuditCallback invoked with null data arguments!";
135         return 0;
136     }
137 
138     snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name, d->cr->pid, d->cr->uid,
139              d->cr->gid);
140     return 0;
141 }
142 
StartSendingMessages()143 void StartSendingMessages() {
144     auto lock = std::lock_guard{accept_messages_lock};
145     accept_messages = true;
146 }
147 
StopSendingMessages()148 void StopSendingMessages() {
149     auto lock = std::lock_guard{accept_messages_lock};
150     accept_messages = false;
151 }
152 
CanReadProperty(const std::string & source_context,const std::string & name)153 bool CanReadProperty(const std::string& source_context, const std::string& name) {
154     const char* target_context = nullptr;
155     property_info_area->GetPropertyInfo(name.c_str(), &target_context, nullptr);
156 
157     PropertyAuditData audit_data;
158 
159     audit_data.name = name.c_str();
160 
161     ucred cr = {.pid = 0, .uid = 0, .gid = 0};
162     audit_data.cr = &cr;
163 
164     return selinux_check_access(source_context.c_str(), target_context, "file", "read",
165                                 &audit_data) == 0;
166 }
167 
CheckMacPerms(const std::string & name,const char * target_context,const char * source_context,const ucred & cr)168 static bool CheckMacPerms(const std::string& name, const char* target_context,
169                           const char* source_context, const ucred& cr) {
170     if (!target_context || !source_context) {
171         return false;
172     }
173 
174     PropertyAuditData audit_data;
175 
176     audit_data.name = name.c_str();
177     audit_data.cr = &cr;
178 
179     bool has_access = (selinux_check_access(source_context, target_context, "property_service",
180                                             "set", &audit_data) == 0);
181 
182     return has_access;
183 }
184 
NotifyPropertyChange(const std::string & name,const std::string & value)185 void NotifyPropertyChange(const std::string& name, const std::string& value) {
186     // If init hasn't started its main loop, then it won't be handling property changed messages
187     // anyway, so there's no need to try to send them.
188     auto lock = std::lock_guard{accept_messages_lock};
189     if (accept_messages) {
190         PropertyChanged(name, value);
191     }
192 }
193 
194 class AsyncRestorecon {
195   public:
TriggerRestorecon(const std::string & path)196     void TriggerRestorecon(const std::string& path) {
197         auto guard = std::lock_guard{mutex_};
198         paths_.emplace(path);
199 
200         if (!thread_started_) {
201             thread_started_ = true;
202             std::thread{&AsyncRestorecon::ThreadFunction, this}.detach();
203         }
204     }
205 
206   private:
ThreadFunction()207     void ThreadFunction() {
208         auto lock = std::unique_lock{mutex_};
209 
210         while (!paths_.empty()) {
211             auto path = paths_.front();
212             paths_.pop();
213 
214             lock.unlock();
215             if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) {
216                 LOG(ERROR) << "Asynchronous restorecon of '" << path << "' failed'";
217             }
218             android::base::SetProperty(kRestoreconProperty, path);
219             lock.lock();
220         }
221 
222         thread_started_ = false;
223     }
224 
225     std::mutex mutex_;
226     std::queue<std::string> paths_;
227     bool thread_started_ = false;
228 };
229 
230 class SocketConnection {
231   public:
232     SocketConnection() = default;
SocketConnection(int socket,const ucred & cred)233     SocketConnection(int socket, const ucred& cred) : socket_(socket), cred_(cred) {}
234     SocketConnection(SocketConnection&&) = default;
235 
RecvUint32(uint32_t * value,uint32_t * timeout_ms)236     bool RecvUint32(uint32_t* value, uint32_t* timeout_ms) {
237         return RecvFully(value, sizeof(*value), timeout_ms);
238     }
239 
RecvChars(char * chars,size_t size,uint32_t * timeout_ms)240     bool RecvChars(char* chars, size_t size, uint32_t* timeout_ms) {
241         return RecvFully(chars, size, timeout_ms);
242     }
243 
RecvString(std::string * value,uint32_t * timeout_ms)244     bool RecvString(std::string* value, uint32_t* timeout_ms) {
245         uint32_t len = 0;
246         if (!RecvUint32(&len, timeout_ms)) {
247             return false;
248         }
249 
250         if (len == 0) {
251             *value = "";
252             return true;
253         }
254 
255         // http://b/35166374: don't allow init to make arbitrarily large allocations.
256         if (len > 0xffff) {
257             LOG(ERROR) << "sys_prop: RecvString asked to read huge string: " << len;
258             errno = ENOMEM;
259             return false;
260         }
261 
262         std::vector<char> chars(len);
263         if (!RecvChars(&chars[0], len, timeout_ms)) {
264             return false;
265         }
266 
267         *value = std::string(&chars[0], len);
268         return true;
269     }
270 
SendUint32(uint32_t value)271     bool SendUint32(uint32_t value) {
272         if (!socket_.ok()) {
273             return true;
274         }
275         int result = TEMP_FAILURE_RETRY(send(socket_.get(), &value, sizeof(value), 0));
276         return result == sizeof(value);
277     }
278 
GetSourceContext(std::string * source_context) const279     bool GetSourceContext(std::string* source_context) const {
280         char* c_source_context = nullptr;
281         if (getpeercon(socket_.get(), &c_source_context) != 0) {
282             return false;
283         }
284         *source_context = c_source_context;
285         freecon(c_source_context);
286         return true;
287     }
288 
Release()289     [[nodiscard]] int Release() { return socket_.release(); }
290 
cred()291     const ucred& cred() { return cred_; }
292 
293     SocketConnection& operator=(SocketConnection&&) = default;
294 
295   private:
PollIn(uint32_t * timeout_ms)296     bool PollIn(uint32_t* timeout_ms) {
297         struct pollfd ufd = {
298                 .fd = socket_.get(),
299                 .events = POLLIN,
300         };
301         while (*timeout_ms > 0) {
302             auto start_time = std::chrono::steady_clock::now();
303             int nr = poll(&ufd, 1, *timeout_ms);
304             auto now = std::chrono::steady_clock::now();
305             auto time_elapsed =
306                 std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
307             uint64_t millis = time_elapsed.count();
308             *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis;
309 
310             if (nr > 0) {
311                 return true;
312             }
313 
314             if (nr == 0) {
315                 // Timeout
316                 break;
317             }
318 
319             if (nr < 0 && errno != EINTR) {
320                 PLOG(ERROR) << "sys_prop: error waiting for uid " << cred_.uid
321                             << " to send property message";
322                 return false;
323             } else {  // errno == EINTR
324                 // Timer rounds milliseconds down in case of EINTR we want it to be rounded up
325                 // to avoid slowing init down by causing EINTR with under millisecond timeout.
326                 if (*timeout_ms > 0) {
327                     --(*timeout_ms);
328                 }
329             }
330         }
331 
332         LOG(ERROR) << "sys_prop: timeout waiting for uid " << cred_.uid
333                    << " to send property message.";
334         return false;
335     }
336 
RecvFully(void * data_ptr,size_t size,uint32_t * timeout_ms)337     bool RecvFully(void* data_ptr, size_t size, uint32_t* timeout_ms) {
338         size_t bytes_left = size;
339         char* data = static_cast<char*>(data_ptr);
340         while (*timeout_ms > 0 && bytes_left > 0) {
341             if (!PollIn(timeout_ms)) {
342                 return false;
343             }
344 
345             int result = TEMP_FAILURE_RETRY(recv(socket_.get(), data, bytes_left, MSG_DONTWAIT));
346             if (result <= 0) {
347                 PLOG(ERROR) << "sys_prop: recv error";
348                 return false;
349             }
350 
351             bytes_left -= result;
352             data += result;
353         }
354 
355         if (bytes_left != 0) {
356             LOG(ERROR) << "sys_prop: recv data is not properly obtained.";
357         }
358 
359         return bytes_left == 0;
360     }
361 
362     unique_fd socket_;
363     ucred cred_;
364 
365     DISALLOW_COPY_AND_ASSIGN(SocketConnection);
366 };
367 
368 class PersistWriteThread {
369   public:
370     PersistWriteThread();
371     void Write(std::string name, std::string value, SocketConnection socket);
372 
373   private:
374     void Work();
375 
376   private:
377     std::thread thread_;
378     std::mutex mutex_;
379     std::condition_variable cv_;
380     std::deque<std::tuple<std::string, std::string, SocketConnection>> work_;
381 };
382 
PropertySet(const std::string & name,const std::string & value,SocketConnection * socket,std::string * error)383 static std::optional<uint32_t> PropertySet(const std::string& name, const std::string& value,
384                                            SocketConnection* socket, std::string* error) {
385     size_t valuelen = value.size();
386 
387     if (!IsLegalPropertyName(name)) {
388         *error = "Illegal property name";
389         return {PROP_ERROR_INVALID_NAME};
390     }
391 
392     if (auto result = IsLegalPropertyValue(name, value); !result.ok()) {
393         *error = result.error().message();
394         return {PROP_ERROR_INVALID_VALUE};
395     }
396 
397     prop_info* pi = (prop_info*)__system_property_find(name.c_str());
398     if (pi != nullptr) {
399         // ro.* properties are actually "write-once".
400         if (StartsWith(name, "ro.")) {
401             *error = "Read-only property was already set";
402             return {PROP_ERROR_READ_ONLY_PROPERTY};
403         }
404 
405         __system_property_update(pi, value.c_str(), valuelen);
406     } else {
407         int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
408         if (rc < 0) {
409             *error = "__system_property_add failed";
410             return {PROP_ERROR_SET_FAILED};
411         }
412     }
413 
414     // Don't write properties to disk until after we have read all default
415     // properties to prevent them from being overwritten by default values.
416     if (socket && persistent_properties_loaded && StartsWith(name, "persist.")) {
417         if (persist_write_thread) {
418             persist_write_thread->Write(name, value, std::move(*socket));
419             return {};
420         }
421         WritePersistentProperty(name, value);
422     }
423 
424     NotifyPropertyChange(name, value);
425     return {PROP_SUCCESS};
426 }
427 
428 // Helper for PropertySet, for the case where no socket is used, and therefore an asynchronous
429 // return is not possible.
PropertySetNoSocket(const std::string & name,const std::string & value,std::string * error)430 static uint32_t PropertySetNoSocket(const std::string& name, const std::string& value,
431                                     std::string* error) {
432     auto ret = PropertySet(name, value, nullptr, error);
433     CHECK(ret.has_value());
434     return *ret;
435 }
436 
SendControlMessage(const std::string & msg,const std::string & name,pid_t pid,SocketConnection * socket,std::string * error)437 static uint32_t SendControlMessage(const std::string& msg, const std::string& name, pid_t pid,
438                                    SocketConnection* socket, std::string* error) {
439     auto lock = std::lock_guard{accept_messages_lock};
440     if (!accept_messages) {
441         *error = "Received control message after shutdown, ignoring";
442         return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
443     }
444 
445     // We must release the fd before sending it to init, otherwise there will be a race with init.
446     // If init calls close() before Release(), then fdsan will see the wrong tag and abort().
447     int fd = -1;
448     if (socket != nullptr && SelinuxGetVendorAndroidVersion() > __ANDROID_API_Q__) {
449         fd = socket->Release();
450     }
451 
452     bool queue_success = QueueControlMessage(msg, name, pid, fd);
453     if (!queue_success && fd != -1) {
454         uint32_t response = PROP_ERROR_HANDLE_CONTROL_MESSAGE;
455         TEMP_FAILURE_RETRY(send(fd, &response, sizeof(response), 0));
456         close(fd);
457     }
458 
459     return PROP_SUCCESS;
460 }
461 
CheckControlPropertyPerms(const std::string & name,const std::string & value,const std::string & source_context,const ucred & cr)462 bool CheckControlPropertyPerms(const std::string& name, const std::string& value,
463                                const std::string& source_context, const ucred& cr) {
464     // We check the legacy method first but these properties are dontaudit, so we only log an audit
465     // if the newer method fails as well.  We only do this with the legacy ctl. properties.
466     if (name == "ctl.start" || name == "ctl.stop" || name == "ctl.restart") {
467         // The legacy permissions model is that ctl. properties have their name ctl.<action> and
468         // their value is the name of the service to apply that action to.  Permissions for these
469         // actions are based on the service, so we must create a fake name of ctl.<service> to
470         // check permissions.
471         auto control_string_legacy = "ctl." + value;
472         const char* target_context_legacy = nullptr;
473         const char* type_legacy = nullptr;
474         property_info_area->GetPropertyInfo(control_string_legacy.c_str(), &target_context_legacy,
475                                             &type_legacy);
476 
477         if (CheckMacPerms(control_string_legacy, target_context_legacy, source_context.c_str(), cr)) {
478             return true;
479         }
480     }
481 
482     auto control_string_full = name + "$" + value;
483     const char* target_context_full = nullptr;
484     const char* type_full = nullptr;
485     property_info_area->GetPropertyInfo(control_string_full.c_str(), &target_context_full,
486                                         &type_full);
487 
488     return CheckMacPerms(control_string_full, target_context_full, source_context.c_str(), cr);
489 }
490 
491 // This returns one of the enum of PROP_SUCCESS or PROP_ERROR*.
CheckPermissions(const std::string & name,const std::string & value,const std::string & source_context,const ucred & cr,std::string * error)492 uint32_t CheckPermissions(const std::string& name, const std::string& value,
493                           const std::string& source_context, const ucred& cr, std::string* error) {
494     if (!IsLegalPropertyName(name)) {
495         *error = "Illegal property name";
496         return PROP_ERROR_INVALID_NAME;
497     }
498 
499     if (StartsWith(name, "ctl.")) {
500         if (!CheckControlPropertyPerms(name, value, source_context, cr)) {
501             *error = StringPrintf("Invalid permissions to perform '%s' on '%s'", name.c_str() + 4,
502                                   value.c_str());
503             return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
504         }
505 
506         return PROP_SUCCESS;
507     }
508 
509     const char* target_context = nullptr;
510     const char* type = nullptr;
511     property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type);
512 
513     if (!CheckMacPerms(name, target_context, source_context.c_str(), cr)) {
514         *error = "SELinux permission check failed";
515         return PROP_ERROR_PERMISSION_DENIED;
516     }
517 
518     if (!CheckType(type, value)) {
519         *error = StringPrintf("Property type check failed, value doesn't match expected type '%s'",
520                               (type ?: "(null)"));
521         return PROP_ERROR_INVALID_VALUE;
522     }
523 
524     return PROP_SUCCESS;
525 }
526 
527 // This returns one of the enum of PROP_SUCCESS or PROP_ERROR*, or std::nullopt
528 // if asynchronous.
HandlePropertySet(const std::string & name,const std::string & value,const std::string & source_context,const ucred & cr,SocketConnection * socket,std::string * error)529 std::optional<uint32_t> HandlePropertySet(const std::string& name, const std::string& value,
530                                           const std::string& source_context, const ucred& cr,
531                                           SocketConnection* socket, std::string* error) {
532     if (auto ret = CheckPermissions(name, value, source_context, cr, error); ret != PROP_SUCCESS) {
533         return {ret};
534     }
535 
536     if (StartsWith(name, "ctl.")) {
537         return {SendControlMessage(name.c_str() + 4, value, cr.pid, socket, error)};
538     }
539 
540     // sys.powerctl is a special property that is used to make the device reboot.  We want to log
541     // any process that sets this property to be able to accurately blame the cause of a shutdown.
542     if (name == "sys.powerctl") {
543         std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
544         std::string process_cmdline;
545         std::string process_log_string;
546         if (ReadFileToString(cmdline_path, &process_cmdline)) {
547             // Since cmdline is null deliminated, .c_str() conveniently gives us just the process
548             // path.
549             process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
550         }
551         LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
552                   << process_log_string;
553         if (value == "reboot,userspace" && !is_userspace_reboot_supported().value_or(false)) {
554             *error = "Userspace reboot is not supported by this device";
555             return {PROP_ERROR_INVALID_VALUE};
556         }
557     }
558 
559     // If a process other than init is writing a non-empty value, it means that process is
560     // requesting that init performs a restorecon operation on the path specified by 'value'.
561     // We use a thread to do this restorecon operation to prevent holding up init, as it may take
562     // a long time to complete.
563     if (name == kRestoreconProperty && cr.pid != 1 && !value.empty()) {
564         static AsyncRestorecon async_restorecon;
565         async_restorecon.TriggerRestorecon(value);
566         return {PROP_SUCCESS};
567     }
568 
569     return PropertySet(name, value, socket, error);
570 }
571 
572 // Helper for HandlePropertySet, for the case where no socket is used, and
573 // therefore an asynchronous return is not possible.
HandlePropertySetNoSocket(const std::string & name,const std::string & value,const std::string & source_context,const ucred & cr,std::string * error)574 uint32_t HandlePropertySetNoSocket(const std::string& name, const std::string& value,
575                                    const std::string& source_context, const ucred& cr,
576                                    std::string* error) {
577     auto ret = HandlePropertySet(name, value, source_context, cr, nullptr, error);
578     CHECK(ret.has_value());
579     return *ret;
580 }
581 
handle_property_set_fd()582 static void handle_property_set_fd() {
583     static constexpr uint32_t kDefaultSocketTimeout = 2000; /* ms */
584 
585     int s = accept4(property_set_fd, nullptr, nullptr, SOCK_CLOEXEC);
586     if (s == -1) {
587         return;
588     }
589 
590     ucred cr;
591     socklen_t cr_size = sizeof(cr);
592     if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
593         close(s);
594         PLOG(ERROR) << "sys_prop: unable to get SO_PEERCRED";
595         return;
596     }
597 
598     SocketConnection socket(s, cr);
599     uint32_t timeout_ms = kDefaultSocketTimeout;
600 
601     uint32_t cmd = 0;
602     if (!socket.RecvUint32(&cmd, &timeout_ms)) {
603         PLOG(ERROR) << "sys_prop: error while reading command from the socket";
604         socket.SendUint32(PROP_ERROR_READ_CMD);
605         return;
606     }
607 
608     switch (cmd) {
609     case PROP_MSG_SETPROP: {
610         char prop_name[PROP_NAME_MAX];
611         char prop_value[PROP_VALUE_MAX];
612 
613         if (!socket.RecvChars(prop_name, PROP_NAME_MAX, &timeout_ms) ||
614             !socket.RecvChars(prop_value, PROP_VALUE_MAX, &timeout_ms)) {
615           PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP): error while reading name/value from the socket";
616           return;
617         }
618 
619         prop_name[PROP_NAME_MAX-1] = 0;
620         prop_value[PROP_VALUE_MAX-1] = 0;
621 
622         std::string source_context;
623         if (!socket.GetSourceContext(&source_context)) {
624             PLOG(ERROR) << "Unable to set property '" << prop_name << "': getpeercon() failed";
625             return;
626         }
627 
628         const auto& cr = socket.cred();
629         std::string error;
630         auto result = HandlePropertySetNoSocket(prop_name, prop_value, source_context, cr, &error);
631         if (result != PROP_SUCCESS) {
632             LOG(ERROR) << "Unable to set property '" << prop_name << "' from uid:" << cr.uid
633                        << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
634         }
635 
636         break;
637       }
638 
639     case PROP_MSG_SETPROP2: {
640         std::string name;
641         std::string value;
642         if (!socket.RecvString(&name, &timeout_ms) ||
643             !socket.RecvString(&value, &timeout_ms)) {
644           PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP2): error while reading name/value from the socket";
645           socket.SendUint32(PROP_ERROR_READ_DATA);
646           return;
647         }
648 
649         std::string source_context;
650         if (!socket.GetSourceContext(&source_context)) {
651             PLOG(ERROR) << "Unable to set property '" << name << "': getpeercon() failed";
652             socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
653             return;
654         }
655 
656         // HandlePropertySet takes ownership of the socket if the set is handled asynchronously.
657         const auto& cr = socket.cred();
658         std::string error;
659         auto result = HandlePropertySet(name, value, source_context, cr, &socket, &error);
660         if (!result) {
661             // Result will be sent after completion.
662             return;
663         }
664         if (*result != PROP_SUCCESS) {
665             LOG(ERROR) << "Unable to set property '" << name << "' from uid:" << cr.uid
666                        << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
667         }
668         socket.SendUint32(*result);
669         break;
670       }
671 
672     default:
673         LOG(ERROR) << "sys_prop: invalid command " << cmd;
674         socket.SendUint32(PROP_ERROR_INVALID_CMD);
675         break;
676     }
677 }
678 
InitPropertySet(const std::string & name,const std::string & value)679 uint32_t InitPropertySet(const std::string& name, const std::string& value) {
680     ucred cr = {.pid = 1, .uid = 0, .gid = 0};
681     std::string error;
682     auto result = HandlePropertySetNoSocket(name, value, kInitContext, cr, &error);
683     if (result != PROP_SUCCESS) {
684         LOG(ERROR) << "Init cannot set '" << name << "' to '" << value << "': " << error;
685     }
686 
687     return result;
688 }
689 
690 static Result<void> load_properties_from_file(const char*, const char*,
691                                               std::map<std::string, std::string>*);
692 
693 /*
694  * Filter is used to decide which properties to load: NULL loads all keys,
695  * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
696  */
LoadProperties(char * data,const char * filter,const char * filename,std::map<std::string,std::string> * properties)697 static void LoadProperties(char* data, const char* filter, const char* filename,
698                            std::map<std::string, std::string>* properties) {
699     char *key, *value, *eol, *sol, *tmp, *fn;
700     size_t flen = 0;
701 
702     static constexpr const char* const kVendorPathPrefixes[4] = {
703             "/vendor",
704             "/odm",
705             "/vendor_dlkm",
706             "/odm_dlkm",
707     };
708 
709     const char* context = kInitContext;
710     if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
711         for (const auto& vendor_path_prefix : kVendorPathPrefixes) {
712             if (StartsWith(filename, vendor_path_prefix)) {
713                 context = kVendorContext;
714             }
715         }
716     }
717 
718     if (filter) {
719         flen = strlen(filter);
720     }
721 
722     sol = data;
723     while ((eol = strchr(sol, '\n'))) {
724         key = sol;
725         *eol++ = 0;
726         sol = eol;
727 
728         while (isspace(*key)) key++;
729         if (*key == '#') continue;
730 
731         tmp = eol - 2;
732         while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
733 
734         if (!strncmp(key, "import ", 7) && flen == 0) {
735             fn = key + 7;
736             while (isspace(*fn)) fn++;
737 
738             key = strchr(fn, ' ');
739             if (key) {
740                 *key++ = 0;
741                 while (isspace(*key)) key++;
742             }
743 
744             std::string raw_filename(fn);
745             auto expanded_filename = ExpandProps(raw_filename);
746 
747             if (!expanded_filename.ok()) {
748                 LOG(ERROR) << "Could not expand filename ': " << expanded_filename.error();
749                 continue;
750             }
751 
752             if (auto res = load_properties_from_file(expanded_filename->c_str(), key, properties);
753                 !res.ok()) {
754                 LOG(WARNING) << res.error();
755             }
756         } else {
757             value = strchr(key, '=');
758             if (!value) continue;
759             *value++ = 0;
760 
761             tmp = value - 2;
762             while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
763 
764             while (isspace(*value)) value++;
765 
766             if (flen > 0) {
767                 if (filter[flen - 1] == '*') {
768                     if (strncmp(key, filter, flen - 1) != 0) continue;
769                 } else {
770                     if (strcmp(key, filter) != 0) continue;
771                 }
772             }
773 
774             if (StartsWith(key, "ctl.") || key == "sys.powerctl"s ||
775                 std::string{key} == kRestoreconProperty) {
776                 LOG(ERROR) << "Ignoring disallowed property '" << key
777                            << "' with special meaning in prop file '" << filename << "'";
778                 continue;
779             }
780 
781             ucred cr = {.pid = 1, .uid = 0, .gid = 0};
782             std::string error;
783             if (CheckPermissions(key, value, context, cr, &error) == PROP_SUCCESS) {
784                 auto it = properties->find(key);
785                 if (it == properties->end()) {
786                     (*properties)[key] = value;
787                 } else if (it->second != value) {
788                     LOG(WARNING) << "Overriding previous property '" << key << "':'" << it->second
789                                  << "' with new value '" << value << "'";
790                     it->second = value;
791                 }
792             } else {
793                 LOG(ERROR) << "Do not have permissions to set '" << key << "' to '" << value
794                            << "' in property file '" << filename << "': " << error;
795             }
796         }
797     }
798 }
799 
800 // Filter is used to decide which properties to load: NULL loads all keys,
801 // "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
load_properties_from_file(const char * filename,const char * filter,std::map<std::string,std::string> * properties)802 static Result<void> load_properties_from_file(const char* filename, const char* filter,
803                                               std::map<std::string, std::string>* properties) {
804     Timer t;
805     auto file_contents = ReadFile(filename);
806     if (!file_contents.ok()) {
807         return Error() << "Couldn't load property file '" << filename
808                        << "': " << file_contents.error();
809     }
810     file_contents->push_back('\n');
811 
812     LoadProperties(file_contents->data(), filter, filename, properties);
813     LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
814     return {};
815 }
816 
LoadPropertiesFromSecondStageRes(std::map<std::string,std::string> * properties)817 static void LoadPropertiesFromSecondStageRes(std::map<std::string, std::string>* properties) {
818     std::string prop = GetRamdiskPropForSecondStage();
819     if (access(prop.c_str(), R_OK) != 0) {
820         CHECK(errno == ENOENT) << "Cannot access " << prop << ": " << strerror(errno);
821         return;
822     }
823     if (auto res = load_properties_from_file(prop.c_str(), nullptr, properties); !res.ok()) {
824         LOG(WARNING) << res.error();
825     }
826 }
827 
828 // persist.sys.usb.config values can't be combined on build-time when property
829 // files are split into each partition.
830 // So we need to apply the same rule of build/make/tools/post_process_props.py
831 // on runtime.
update_sys_usb_config()832 static void update_sys_usb_config() {
833     bool is_debuggable = android::base::GetBoolProperty("ro.debuggable", false);
834     std::string config = android::base::GetProperty("persist.sys.usb.config", "");
835     // b/150130503, add (config == "none") condition here to prevent appending
836     // ",adb" if "none" is explicitly defined in default prop.
837     if (config.empty() || config == "none") {
838         InitPropertySet("persist.sys.usb.config", is_debuggable ? "adb" : "none");
839     } else if (is_debuggable && config.find("adb") == std::string::npos &&
840                config.length() + 4 < PROP_VALUE_MAX) {
841         config.append(",adb");
842         InitPropertySet("persist.sys.usb.config", config);
843     }
844 }
845 
load_override_properties()846 static void load_override_properties() {
847     if (ALLOW_LOCAL_PROP_OVERRIDE) {
848         std::map<std::string, std::string> properties;
849         load_properties_from_file("/data/local.prop", nullptr, &properties);
850         for (const auto& [name, value] : properties) {
851             std::string error;
852             if (PropertySetNoSocket(name, value, &error) != PROP_SUCCESS) {
853                 LOG(ERROR) << "Could not set '" << name << "' to '" << value
854                            << "' in /data/local.prop: " << error;
855             }
856         }
857     }
858 }
859 
860 // If the ro.product.[brand|device|manufacturer|model|name] properties have not been explicitly
861 // set, derive them from ro.product.${partition}.* properties
property_initialize_ro_product_props()862 static void property_initialize_ro_product_props() {
863     const char* RO_PRODUCT_PROPS_PREFIX = "ro.product.";
864     const char* RO_PRODUCT_PROPS[] = {
865             "brand", "device", "manufacturer", "model", "name",
866     };
867     const char* RO_PRODUCT_PROPS_ALLOWED_SOURCES[] = {
868             "odm", "product", "system_ext", "system", "vendor",
869     };
870     const char* RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER = "product,odm,vendor,system_ext,system";
871     const std::string EMPTY = "";
872 
873     std::string ro_product_props_source_order =
874             GetProperty("ro.product.property_source_order", EMPTY);
875 
876     if (!ro_product_props_source_order.empty()) {
877         // Verify that all specified sources are valid
878         for (const auto& source : Split(ro_product_props_source_order, ",")) {
879             // Verify that the specified source is valid
880             bool is_allowed_source = false;
881             for (const auto& allowed_source : RO_PRODUCT_PROPS_ALLOWED_SOURCES) {
882                 if (source == allowed_source) {
883                     is_allowed_source = true;
884                     break;
885                 }
886             }
887             if (!is_allowed_source) {
888                 LOG(ERROR) << "Found unexpected source in ro.product.property_source_order; "
889                               "using the default property source order";
890                 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
891                 break;
892             }
893         }
894     } else {
895         ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
896     }
897 
898     for (const auto& ro_product_prop : RO_PRODUCT_PROPS) {
899         std::string base_prop(RO_PRODUCT_PROPS_PREFIX);
900         base_prop += ro_product_prop;
901 
902         std::string base_prop_val = GetProperty(base_prop, EMPTY);
903         if (!base_prop_val.empty()) {
904             continue;
905         }
906 
907         for (const auto& source : Split(ro_product_props_source_order, ",")) {
908             std::string target_prop(RO_PRODUCT_PROPS_PREFIX);
909             target_prop += source;
910             target_prop += '.';
911             target_prop += ro_product_prop;
912 
913             std::string target_prop_val = GetProperty(target_prop, EMPTY);
914             if (!target_prop_val.empty()) {
915                 LOG(INFO) << "Setting product property " << base_prop << " to '" << target_prop_val
916                           << "' (from " << target_prop << ")";
917                 std::string error;
918                 auto res = PropertySetNoSocket(base_prop, target_prop_val, &error);
919                 if (res != PROP_SUCCESS) {
920                     LOG(ERROR) << "Error setting product property " << base_prop << ": err=" << res
921                                << " (" << error << ")";
922                 }
923                 break;
924             }
925         }
926     }
927 }
928 
property_initialize_build_id()929 static void property_initialize_build_id() {
930     std::string build_id = GetProperty(ID_PROP, "");
931     if (!build_id.empty()) {
932         return;
933     }
934 
935     std::string legacy_build_id = GetProperty(LEGACY_ID_PROP, "");
936     std::string vbmeta_digest = GetProperty(VBMETA_DIGEST_PROP, "");
937     if (vbmeta_digest.size() < DIGEST_SIZE_USED) {
938         LOG(ERROR) << "vbmeta digest size too small " << vbmeta_digest;
939         // Still try to set the id field in the unexpected case.
940         build_id = legacy_build_id;
941     } else {
942         // Derive the ro.build.id by appending the vbmeta digest to the base value.
943         build_id = legacy_build_id + "." + vbmeta_digest.substr(0, DIGEST_SIZE_USED);
944     }
945 
946     std::string error;
947     auto res = PropertySetNoSocket(ID_PROP, build_id, &error);
948     if (res != PROP_SUCCESS) {
949         LOG(ERROR) << "Failed to set " << ID_PROP << " to " << build_id;
950     }
951 }
952 
ConstructBuildFingerprint(bool legacy)953 static std::string ConstructBuildFingerprint(bool legacy) {
954     const std::string UNKNOWN = "unknown";
955     std::string build_fingerprint = GetProperty("ro.product.brand", UNKNOWN);
956     build_fingerprint += '/';
957     build_fingerprint += GetProperty("ro.product.name", UNKNOWN);
958     build_fingerprint += '/';
959     build_fingerprint += GetProperty("ro.product.device", UNKNOWN);
960     build_fingerprint += ':';
961     build_fingerprint += GetProperty("ro.build.version.release_or_codename", UNKNOWN);
962     build_fingerprint += '/';
963 
964     std::string build_id =
965             legacy ? GetProperty(LEGACY_ID_PROP, UNKNOWN) : GetProperty(ID_PROP, UNKNOWN);
966     build_fingerprint += build_id;
967     build_fingerprint += '/';
968     build_fingerprint += GetProperty("ro.build.version.incremental", UNKNOWN);
969     build_fingerprint += ':';
970     build_fingerprint += GetProperty("ro.build.type", UNKNOWN);
971     build_fingerprint += '/';
972     build_fingerprint += GetProperty("ro.build.tags", UNKNOWN);
973 
974     return build_fingerprint;
975 }
976 
977 // Derive the legacy build fingerprint if we overwrite the build id at runtime.
property_derive_legacy_build_fingerprint()978 static void property_derive_legacy_build_fingerprint() {
979     std::string legacy_build_fingerprint = GetProperty(LEGACY_FINGERPRINT_PROP, "");
980     if (!legacy_build_fingerprint.empty()) {
981         return;
982     }
983 
984     // The device doesn't have a legacy build id, skipping the legacy fingerprint.
985     std::string legacy_build_id = GetProperty(LEGACY_ID_PROP, "");
986     if (legacy_build_id.empty()) {
987         return;
988     }
989 
990     legacy_build_fingerprint = ConstructBuildFingerprint(true /* legacy fingerprint */);
991     LOG(INFO) << "Setting property '" << LEGACY_FINGERPRINT_PROP << "' to '"
992               << legacy_build_fingerprint << "'";
993 
994     std::string error;
995     auto res = PropertySetNoSocket(LEGACY_FINGERPRINT_PROP, legacy_build_fingerprint, &error);
996     if (res != PROP_SUCCESS) {
997         LOG(ERROR) << "Error setting property '" << LEGACY_FINGERPRINT_PROP << "': err=" << res
998                    << " (" << error << ")";
999     }
1000 }
1001 
1002 // If the ro.build.fingerprint property has not been set, derive it from constituent pieces
property_derive_build_fingerprint()1003 static void property_derive_build_fingerprint() {
1004     std::string build_fingerprint = GetProperty("ro.build.fingerprint", "");
1005     if (!build_fingerprint.empty()) {
1006         return;
1007     }
1008 
1009     build_fingerprint = ConstructBuildFingerprint(false /* legacy fingerprint */);
1010     LOG(INFO) << "Setting property '" << FINGERPRINT_PROP << "' to '" << build_fingerprint << "'";
1011 
1012     std::string error;
1013     auto res = PropertySetNoSocket(FINGERPRINT_PROP, build_fingerprint, &error);
1014     if (res != PROP_SUCCESS) {
1015         LOG(ERROR) << "Error setting property '" << FINGERPRINT_PROP << "': err=" << res << " ("
1016                    << error << ")";
1017     }
1018 }
1019 
1020 // If the ro.product.cpu.abilist* properties have not been explicitly
1021 // set, derive them from ro.${partition}.product.cpu.abilist* properties.
property_initialize_ro_cpu_abilist()1022 static void property_initialize_ro_cpu_abilist() {
1023     // From high to low priority.
1024     const char* kAbilistSources[] = {
1025             "product",
1026             "odm",
1027             "vendor",
1028             "system",
1029     };
1030     const std::string EMPTY = "";
1031     const char* kAbilistProp = "ro.product.cpu.abilist";
1032     const char* kAbilist32Prop = "ro.product.cpu.abilist32";
1033     const char* kAbilist64Prop = "ro.product.cpu.abilist64";
1034 
1035     // If the properties are defined explicitly, just use them.
1036     if (GetProperty(kAbilistProp, EMPTY) != EMPTY) {
1037         return;
1038     }
1039 
1040     // Find the first source defining these properties by order.
1041     std::string abilist32_prop_val;
1042     std::string abilist64_prop_val;
1043     for (const auto& source : kAbilistSources) {
1044         const auto abilist32_prop = std::string("ro.") + source + ".product.cpu.abilist32";
1045         const auto abilist64_prop = std::string("ro.") + source + ".product.cpu.abilist64";
1046         abilist32_prop_val = GetProperty(abilist32_prop, EMPTY);
1047         abilist64_prop_val = GetProperty(abilist64_prop, EMPTY);
1048         // The properties could be empty on 32-bit-only or 64-bit-only devices,
1049         // but we cannot identify a property is empty or undefined by GetProperty().
1050         // So, we assume both of these 2 properties are empty as undefined.
1051         if (abilist32_prop_val != EMPTY || abilist64_prop_val != EMPTY) {
1052             break;
1053         }
1054     }
1055 
1056     // Merge ABI lists for ro.product.cpu.abilist
1057     auto abilist_prop_val = abilist64_prop_val;
1058     if (abilist32_prop_val != EMPTY) {
1059         if (abilist_prop_val != EMPTY) {
1060             abilist_prop_val += ",";
1061         }
1062         abilist_prop_val += abilist32_prop_val;
1063     }
1064 
1065     // Set these properties
1066     const std::pair<const char*, const std::string&> set_prop_list[] = {
1067             {kAbilistProp, abilist_prop_val},
1068             {kAbilist32Prop, abilist32_prop_val},
1069             {kAbilist64Prop, abilist64_prop_val},
1070     };
1071     for (const auto& [prop, prop_val] : set_prop_list) {
1072         LOG(INFO) << "Setting property '" << prop << "' to '" << prop_val << "'";
1073 
1074         std::string error;
1075         auto res = PropertySetNoSocket(prop, prop_val, &error);
1076         if (res != PROP_SUCCESS) {
1077             LOG(ERROR) << "Error setting property '" << prop << "': err=" << res << " (" << error
1078                        << ")";
1079         }
1080     }
1081 }
1082 
read_api_level_props(const std::vector<std::string> & api_level_props)1083 static int read_api_level_props(const std::vector<std::string>& api_level_props) {
1084     int api_level = API_LEVEL_CURRENT;
1085     for (const auto& api_level_prop : api_level_props) {
1086         api_level = android::base::GetIntProperty(api_level_prop, API_LEVEL_CURRENT);
1087         if (api_level != API_LEVEL_CURRENT) {
1088             break;
1089         }
1090     }
1091     return api_level;
1092 }
1093 
property_initialize_ro_vendor_api_level()1094 static void property_initialize_ro_vendor_api_level() {
1095     // ro.vendor.api_level shows the api_level that the vendor images (vendor, odm, ...) are
1096     // required to support.
1097     constexpr auto VENDOR_API_LEVEL_PROP = "ro.vendor.api_level";
1098 
1099     // Api level properties of the board. The order of the properties must be kept.
1100     std::vector<std::string> BOARD_API_LEVEL_PROPS = {"ro.board.api_level",
1101                                                       "ro.board.first_api_level"};
1102     // Api level properties of the device. The order of the properties must be kept.
1103     std::vector<std::string> DEVICE_API_LEVEL_PROPS = {"ro.product.first_api_level",
1104                                                        "ro.build.version.sdk"};
1105 
1106     int api_level = std::min(read_api_level_props(BOARD_API_LEVEL_PROPS),
1107                              read_api_level_props(DEVICE_API_LEVEL_PROPS));
1108     std::string error;
1109     auto res = PropertySetNoSocket(VENDOR_API_LEVEL_PROP, std::to_string(api_level), &error);
1110     if (res != PROP_SUCCESS) {
1111         LOG(ERROR) << "Failed to set " << VENDOR_API_LEVEL_PROP << " with " << api_level << ": "
1112                    << error << "(" << res << ")";
1113     }
1114 }
1115 
PropertyLoadBootDefaults()1116 void PropertyLoadBootDefaults() {
1117     // We read the properties and their values into a map, in order to always allow properties
1118     // loaded in the later property files to override the properties in loaded in the earlier
1119     // property files, regardless of if they are "ro." properties or not.
1120     std::map<std::string, std::string> properties;
1121 
1122     if (IsRecoveryMode()) {
1123         if (auto res = load_properties_from_file("/prop.default", nullptr, &properties);
1124             !res.ok()) {
1125             LOG(ERROR) << res.error();
1126         }
1127     }
1128 
1129     // /<part>/etc/build.prop is the canonical location of the build-time properties since S.
1130     // Falling back to /<part>/defalt.prop and /<part>/build.prop only when legacy path has to
1131     // be supported, which is controlled by the support_legacy_path_until argument.
1132     const auto load_properties_from_partition = [&properties](const std::string& partition,
1133                                                               int support_legacy_path_until) {
1134         auto path = "/" + partition + "/etc/build.prop";
1135         if (load_properties_from_file(path.c_str(), nullptr, &properties).ok()) {
1136             return;
1137         }
1138         // To read ro.<partition>.build.version.sdk, temporarily load the legacy paths into a
1139         // separate map. Then by comparing its value with legacy_version, we know that if the
1140         // partition is old enough so that we need to respect the legacy paths.
1141         std::map<std::string, std::string> temp;
1142         auto legacy_path1 = "/" + partition + "/default.prop";
1143         auto legacy_path2 = "/" + partition + "/build.prop";
1144         load_properties_from_file(legacy_path1.c_str(), nullptr, &temp);
1145         load_properties_from_file(legacy_path2.c_str(), nullptr, &temp);
1146         bool support_legacy_path = false;
1147         auto version_prop_name = "ro." + partition + ".build.version.sdk";
1148         auto it = temp.find(version_prop_name);
1149         if (it == temp.end()) {
1150             // This is embarassing. Without the prop, we can't determine how old the partition is.
1151             // Let's be conservative by assuming it is very very old.
1152             support_legacy_path = true;
1153         } else if (int value;
1154                    ParseInt(it->second.c_str(), &value) && value <= support_legacy_path_until) {
1155             support_legacy_path = true;
1156         }
1157         if (support_legacy_path) {
1158             // We don't update temp into properties directly as it might skip any (future) logic
1159             // for resolving duplicates implemented in load_properties_from_file.  Instead, read
1160             // the files again into the properties map.
1161             load_properties_from_file(legacy_path1.c_str(), nullptr, &properties);
1162             load_properties_from_file(legacy_path2.c_str(), nullptr, &properties);
1163         } else {
1164             LOG(FATAL) << legacy_path1 << " and " << legacy_path2 << " were not loaded "
1165                        << "because " << version_prop_name << "(" << it->second << ") is newer "
1166                        << "than " << support_legacy_path_until;
1167         }
1168     };
1169 
1170     // Order matters here. The more the partition is specific to a product, the higher its
1171     // precedence is.
1172     LoadPropertiesFromSecondStageRes(&properties);
1173 
1174     // system should have build.prop, unlike the other partitions
1175     if (auto res = load_properties_from_file("/system/build.prop", nullptr, &properties);
1176         !res.ok()) {
1177         LOG(WARNING) << res.error();
1178     }
1179 
1180     load_properties_from_partition("system_ext", /* support_legacy_path_until */ 30);
1181     load_properties_from_file("/system_dlkm/etc/build.prop", nullptr, &properties);
1182     // TODO(b/117892318): uncomment the following condition when vendor.imgs for aosp_* targets are
1183     // all updated.
1184     // if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_R__) {
1185     load_properties_from_file("/vendor/default.prop", nullptr, &properties);
1186     // }
1187     load_properties_from_file("/vendor/build.prop", nullptr, &properties);
1188     load_properties_from_file("/vendor_dlkm/etc/build.prop", nullptr, &properties);
1189     load_properties_from_file("/odm_dlkm/etc/build.prop", nullptr, &properties);
1190     load_properties_from_partition("odm", /* support_legacy_path_until */ 28);
1191     load_properties_from_partition("product", /* support_legacy_path_until */ 30);
1192 
1193     if (access(kDebugRamdiskProp, R_OK) == 0) {
1194         LOG(INFO) << "Loading " << kDebugRamdiskProp;
1195         if (auto res = load_properties_from_file(kDebugRamdiskProp, nullptr, &properties);
1196             !res.ok()) {
1197             LOG(WARNING) << res.error();
1198         }
1199     }
1200 
1201     for (const auto& [name, value] : properties) {
1202         std::string error;
1203         if (PropertySetNoSocket(name, value, &error) != PROP_SUCCESS) {
1204             LOG(ERROR) << "Could not set '" << name << "' to '" << value
1205                        << "' while loading .prop files" << error;
1206         }
1207     }
1208 
1209     property_initialize_ro_product_props();
1210     property_initialize_build_id();
1211     property_derive_build_fingerprint();
1212     property_derive_legacy_build_fingerprint();
1213     property_initialize_ro_cpu_abilist();
1214     property_initialize_ro_vendor_api_level();
1215 
1216     update_sys_usb_config();
1217 }
1218 
LoadPropertyInfoFromFile(const std::string & filename,std::vector<PropertyInfoEntry> * property_infos)1219 bool LoadPropertyInfoFromFile(const std::string& filename,
1220                               std::vector<PropertyInfoEntry>* property_infos) {
1221     auto file_contents = std::string();
1222     if (!ReadFileToString(filename, &file_contents)) {
1223         PLOG(ERROR) << "Could not read properties from '" << filename << "'";
1224         return false;
1225     }
1226 
1227     auto errors = std::vector<std::string>{};
1228     bool require_prefix_or_exact = SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__;
1229     ParsePropertyInfoFile(file_contents, require_prefix_or_exact, property_infos, &errors);
1230     // Individual parsing errors are reported but do not cause a failed boot, which is what
1231     // returning false would do here.
1232     for (const auto& error : errors) {
1233         LOG(ERROR) << "Could not read line from '" << filename << "': " << error;
1234     }
1235 
1236     return true;
1237 }
1238 
CreateSerializedPropertyInfo()1239 void CreateSerializedPropertyInfo() {
1240     auto property_infos = std::vector<PropertyInfoEntry>();
1241     if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
1242         if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",
1243                                       &property_infos)) {
1244             return;
1245         }
1246         // Don't check for failure here, since we don't always have all of these partitions.
1247         // E.g. In case of recovery, the vendor partition will not have mounted and we
1248         // still need the system / platform properties to function.
1249         if (access("/dev/selinux/apex_property_contexts", R_OK) != -1) {
1250             LoadPropertyInfoFromFile("/dev/selinux/apex_property_contexts", &property_infos);
1251         }
1252         if (access("/system_ext/etc/selinux/system_ext_property_contexts", R_OK) != -1) {
1253             LoadPropertyInfoFromFile("/system_ext/etc/selinux/system_ext_property_contexts",
1254                                      &property_infos);
1255         }
1256         if (access("/vendor/etc/selinux/vendor_property_contexts", R_OK) != -1) {
1257             LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",
1258                                      &property_infos);
1259         }
1260         if (access("/product/etc/selinux/product_property_contexts", R_OK) != -1) {
1261             LoadPropertyInfoFromFile("/product/etc/selinux/product_property_contexts",
1262                                      &property_infos);
1263         }
1264         if (access("/odm/etc/selinux/odm_property_contexts", R_OK) != -1) {
1265             LoadPropertyInfoFromFile("/odm/etc/selinux/odm_property_contexts", &property_infos);
1266         }
1267     } else {
1268         if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {
1269             return;
1270         }
1271         LoadPropertyInfoFromFile("/system_ext_property_contexts", &property_infos);
1272         LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos);
1273         LoadPropertyInfoFromFile("/product_property_contexts", &property_infos);
1274         LoadPropertyInfoFromFile("/odm_property_contexts", &property_infos);
1275         LoadPropertyInfoFromFile("/dev/selinux/apex_property_contexts", &property_infos);
1276     }
1277 
1278     auto serialized_contexts = std::string();
1279     auto error = std::string();
1280     if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,
1281                    &error)) {
1282         LOG(ERROR) << "Unable to serialize property contexts: " << error;
1283         return;
1284     }
1285 
1286     constexpr static const char kPropertyInfosPath[] = "/dev/__properties__/property_info";
1287     if (!WriteStringToFile(serialized_contexts, kPropertyInfosPath, 0444, 0, 0, false)) {
1288         PLOG(ERROR) << "Unable to write serialized property infos to file";
1289     }
1290     selinux_android_restorecon(kPropertyInfosPath, 0);
1291 }
1292 
ExportKernelBootProps()1293 static void ExportKernelBootProps() {
1294     constexpr const char* UNSET = "";
1295     struct {
1296         const char* src_prop;
1297         const char* dst_prop;
1298         const char* default_value;
1299     } prop_map[] = {
1300             // clang-format off
1301         { "ro.boot.serialno",   "ro.serialno",   UNSET, },
1302         { "ro.boot.mode",       "ro.bootmode",   "unknown", },
1303         { "ro.boot.baseband",   "ro.baseband",   "unknown", },
1304         { "ro.boot.bootloader", "ro.bootloader", "unknown", },
1305         { "ro.boot.hardware",   "ro.hardware",   "unknown", },
1306         { "ro.boot.revision",   "ro.revision",   "0", },
1307             // clang-format on
1308     };
1309     for (const auto& prop : prop_map) {
1310         std::string value = GetProperty(prop.src_prop, prop.default_value);
1311         if (value != UNSET) InitPropertySet(prop.dst_prop, value);
1312     }
1313 }
1314 
ProcessKernelDt()1315 static void ProcessKernelDt() {
1316     if (!is_android_dt_value_expected("compatible", "android,firmware")) {
1317         return;
1318     }
1319 
1320     std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(get_android_dt_dir().c_str()), closedir);
1321     if (!dir) return;
1322 
1323     std::string dt_file;
1324     struct dirent* dp;
1325     while ((dp = readdir(dir.get())) != NULL) {
1326         if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") ||
1327             !strcmp(dp->d_name, "name")) {
1328             continue;
1329         }
1330 
1331         std::string file_name = get_android_dt_dir() + dp->d_name;
1332 
1333         android::base::ReadFileToString(file_name, &dt_file);
1334         std::replace(dt_file.begin(), dt_file.end(), ',', '.');
1335 
1336         InitPropertySet("ro.boot."s + dp->d_name, dt_file);
1337     }
1338 }
1339 
1340 constexpr auto ANDROIDBOOT_PREFIX = "androidboot."sv;
1341 
ProcessKernelCmdline()1342 static void ProcessKernelCmdline() {
1343     ImportKernelCmdline([&](const std::string& key, const std::string& value) {
1344         if (StartsWith(key, ANDROIDBOOT_PREFIX)) {
1345             InitPropertySet("ro.boot." + key.substr(ANDROIDBOOT_PREFIX.size()), value);
1346         }
1347     });
1348 }
1349 
1350 
ProcessBootconfig()1351 static void ProcessBootconfig() {
1352     ImportBootconfig([&](const std::string& key, const std::string& value) {
1353         if (StartsWith(key, ANDROIDBOOT_PREFIX)) {
1354             InitPropertySet("ro.boot." + key.substr(ANDROIDBOOT_PREFIX.size()), value);
1355         }
1356     });
1357 }
1358 
PropertyInit()1359 void PropertyInit() {
1360     selinux_callback cb;
1361     cb.func_audit = PropertyAuditCallback;
1362     selinux_set_callback(SELINUX_CB_AUDIT, cb);
1363 
1364     mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);
1365     CreateSerializedPropertyInfo();
1366     if (__system_property_area_init()) {
1367         LOG(FATAL) << "Failed to initialize property area";
1368     }
1369     if (!property_info_area.LoadDefaultPath()) {
1370         LOG(FATAL) << "Failed to load serialized property info file";
1371     }
1372 
1373     // If arguments are passed both on the command line and in DT,
1374     // properties set in DT always have priority over the command-line ones.
1375     ProcessKernelDt();
1376     ProcessKernelCmdline();
1377     ProcessBootconfig();
1378 
1379     // Propagate the kernel variables to internal variables
1380     // used by init as well as the current required properties.
1381     ExportKernelBootProps();
1382 
1383     PropertyLoadBootDefaults();
1384 }
1385 
HandleInitSocket()1386 static void HandleInitSocket() {
1387     auto message = ReadMessage(init_socket);
1388     if (!message.ok()) {
1389         LOG(ERROR) << "Could not read message from init_dedicated_recv_socket: " << message.error();
1390         return;
1391     }
1392 
1393     auto init_message = InitMessage{};
1394     if (!init_message.ParseFromString(*message)) {
1395         LOG(ERROR) << "Could not parse message from init";
1396         return;
1397     }
1398 
1399     switch (init_message.msg_case()) {
1400         case InitMessage::kLoadPersistentProperties: {
1401             load_override_properties();
1402             // Read persistent properties after all default values have been loaded.
1403             auto persistent_properties = LoadPersistentProperties();
1404             for (const auto& persistent_property_record : persistent_properties.properties()) {
1405                 InitPropertySet(persistent_property_record.name(),
1406                                 persistent_property_record.value());
1407             }
1408             // Apply debug ramdisk special settings after persistent properties are loaded.
1409             if (android::base::GetBoolProperty("ro.force.debuggable", false)) {
1410                 // Always enable usb adb if device is booted with debug ramdisk.
1411                 update_sys_usb_config();
1412             }
1413             InitPropertySet("ro.persistent_properties.ready", "true");
1414             persistent_properties_loaded = true;
1415             break;
1416         }
1417         default:
1418             LOG(ERROR) << "Unknown message type from init: " << init_message.msg_case();
1419     }
1420 }
1421 
PropertyServiceThread()1422 static void PropertyServiceThread() {
1423     Epoll epoll;
1424     if (auto result = epoll.Open(); !result.ok()) {
1425         LOG(FATAL) << result.error();
1426     }
1427 
1428     if (auto result = epoll.RegisterHandler(property_set_fd, handle_property_set_fd);
1429         !result.ok()) {
1430         LOG(FATAL) << result.error();
1431     }
1432 
1433     if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result.ok()) {
1434         LOG(FATAL) << result.error();
1435     }
1436 
1437     while (true) {
1438         auto epoll_result = epoll.Wait(std::nullopt);
1439         if (!epoll_result.ok()) {
1440             LOG(ERROR) << epoll_result.error();
1441         }
1442     }
1443 }
1444 
PersistWriteThread()1445 PersistWriteThread::PersistWriteThread() {
1446     auto new_thread = std::thread([this]() -> void { Work(); });
1447     thread_.swap(new_thread);
1448 }
1449 
Work()1450 void PersistWriteThread::Work() {
1451     while (true) {
1452         std::tuple<std::string, std::string, SocketConnection> item;
1453 
1454         // Grab the next item within the lock.
1455         {
1456             std::unique_lock<std::mutex> lock(mutex_);
1457 
1458             while (work_.empty()) {
1459                 cv_.wait(lock);
1460             }
1461 
1462             item = std::move(work_.front());
1463             work_.pop_front();
1464         }
1465 
1466         std::this_thread::sleep_for(1s);
1467 
1468         // Perform write/fsync outside the lock.
1469         WritePersistentProperty(std::get<0>(item), std::get<1>(item));
1470         NotifyPropertyChange(std::get<0>(item), std::get<1>(item));
1471 
1472         SocketConnection& socket = std::get<2>(item);
1473         socket.SendUint32(PROP_SUCCESS);
1474     }
1475 }
1476 
Write(std::string name,std::string value,SocketConnection socket)1477 void PersistWriteThread::Write(std::string name, std::string value, SocketConnection socket) {
1478     {
1479         std::unique_lock<std::mutex> lock(mutex_);
1480         work_.emplace_back(std::move(name), std::move(value), std::move(socket));
1481     }
1482     cv_.notify_all();
1483 }
1484 
StartPropertyService(int * epoll_socket)1485 void StartPropertyService(int* epoll_socket) {
1486     InitPropertySet("ro.property_service.version", "2");
1487 
1488     int sockets[2];
1489     if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != 0) {
1490         PLOG(FATAL) << "Failed to socketpair() between property_service and init";
1491     }
1492     *epoll_socket = from_init_socket = sockets[0];
1493     init_socket = sockets[1];
1494     StartSendingMessages();
1495 
1496     if (auto result = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1497                                    /*passcred=*/false, /*should_listen=*/false, 0666, /*uid=*/0,
1498                                    /*gid=*/0, /*socketcon=*/{});
1499         result.ok()) {
1500         property_set_fd = *result;
1501     } else {
1502         LOG(FATAL) << "start_property_service socket creation failed: " << result.error();
1503     }
1504 
1505     listen(property_set_fd, 8);
1506 
1507     auto new_thread = std::thread{PropertyServiceThread};
1508     property_service_thread.swap(new_thread);
1509 
1510     auto async_persist_writes =
1511             android::base::GetBoolProperty("ro.property_service.async_persist_writes", false);
1512 
1513     if (async_persist_writes) {
1514         persist_write_thread = std::make_unique<PersistWriteThread>();
1515     }
1516 }
1517 
1518 }  // namespace init
1519 }  // namespace android
1520