• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/system_properties.h>
35 #include <sys/types.h>
36 #include <sys/un.h>
37 #include <unistd.h>
38 #include <wchar.h>
39 
40 #include <map>
41 #include <memory>
42 #include <mutex>
43 #include <optional>
44 #include <queue>
45 #include <string_view>
46 #include <thread>
47 #include <vector>
48 
49 #include <android-base/chrono_utils.h>
50 #include <android-base/file.h>
51 #include <android-base/logging.h>
52 #include <android-base/parseint.h>
53 #include <android-base/properties.h>
54 #include <android-base/result.h>
55 #include <android-base/stringprintf.h>
56 #include <android-base/strings.h>
57 #include <fs_mgr.h>
58 #include <private/android_filesystem_config.h>
59 #include <property_info_parser/property_info_parser.h>
60 #include <property_info_serializer/property_info_serializer.h>
61 #include <selinux/android.h>
62 #include <selinux/label.h>
63 #include <selinux/selinux.h>
64 #include <vendorsupport/api_level.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 static constexpr char APPCOMPAT_OVERRIDE_PROP_FOLDERNAME[] =
79         "/dev/__properties__/appcompat_override";
80 static constexpr char APPCOMPAT_OVERRIDE_PROP_TREE_FILE[] =
81         "/dev/__properties__/appcompat_override/property_info";
82 using namespace std::literals;
83 
84 using android::base::ErrnoError;
85 using android::base::Error;
86 using android::base::GetIntProperty;
87 using android::base::GetProperty;
88 using android::base::ParseInt;
89 using android::base::ReadFileToString;
90 using android::base::Result;
91 using android::base::Split;
92 using android::base::StartsWith;
93 using android::base::StringPrintf;
94 using android::base::Timer;
95 using android::base::Trim;
96 using android::base::unique_fd;
97 using android::base::WriteStringToFile;
98 using android::properties::BuildTrie;
99 using android::properties::ParsePropertyInfoFile;
100 using android::properties::PropertyInfoAreaFile;
101 using android::properties::PropertyInfoEntry;
102 
103 namespace android {
104 namespace init {
105 
106 constexpr auto FINGERPRINT_PROP = "ro.build.fingerprint";
107 constexpr auto LEGACY_FINGERPRINT_PROP = "ro.build.legacy.fingerprint";
108 constexpr auto ID_PROP = "ro.build.id";
109 constexpr auto LEGACY_ID_PROP = "ro.build.legacy.id";
110 constexpr auto VBMETA_DIGEST_PROP = "ro.boot.vbmeta.digest";
111 constexpr auto DIGEST_SIZE_USED = 8;
112 
113 static bool persistent_properties_loaded = false;
114 
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::mutex selinux_check_access_lock;
120 static std::thread property_service_thread;
121 static std::thread property_service_for_system_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     auto lock = std::lock_guard{selinux_check_access_lock};
165     return selinux_check_access(source_context.c_str(), target_context, "file", "read",
166                                 &audit_data) == 0;
167 }
168 
CheckMacPerms(const std::string & name,const char * target_context,const char * source_context,const ucred & cr)169 static bool CheckMacPerms(const std::string& name, const char* target_context,
170                           const char* source_context, const ucred& cr) {
171     if (!target_context || !source_context) {
172         return false;
173     }
174 
175     PropertyAuditData audit_data;
176 
177     audit_data.name = name.c_str();
178     audit_data.cr = &cr;
179 
180     auto lock = std::lock_guard{selinux_check_access_lock};
181     return selinux_check_access(source_context, target_context, "property_service", "set",
182                                 &audit_data) == 0;
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 
383 static std::unique_ptr<PersistWriteThread> persist_write_thread;
384 
PropertySet(const std::string & name,const std::string & value,SocketConnection * socket,std::string * error)385 static std::optional<uint32_t> PropertySet(const std::string& name, const std::string& value,
386                                            SocketConnection* socket, std::string* error) {
387     size_t valuelen = value.size();
388 
389     if (!IsLegalPropertyName(name)) {
390         *error = "Illegal property name";
391         return {PROP_ERROR_INVALID_NAME};
392     }
393 
394     if (auto result = IsLegalPropertyValue(name, value); !result.ok()) {
395         *error = result.error().message();
396         return {PROP_ERROR_INVALID_VALUE};
397     }
398 
399     if (name == "sys.powerctl") {
400         // No action here - NotifyPropertyChange will trigger the appropriate action, and since this
401         // can come to the second thread, we mustn't call out to the __system_property_* functions
402         // which support multiple readers but only one mutator.
403     } else {
404         prop_info* pi = (prop_info*)__system_property_find(name.c_str());
405         if (pi != nullptr) {
406             // ro.* properties are actually "write-once".
407             if (StartsWith(name, "ro.")) {
408                 *error = "Read-only property was already set";
409                 return {PROP_ERROR_READ_ONLY_PROPERTY};
410             }
411 
412             __system_property_update(pi, value.c_str(), valuelen);
413         } else {
414             int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen);
415             if (rc < 0) {
416                 *error = "__system_property_add failed";
417                 return {PROP_ERROR_SET_FAILED};
418             }
419         }
420 
421         // Don't write properties to disk until after we have read all default
422         // properties to prevent them from being overwritten by default values.
423         bool need_persist = StartsWith(name, "persist.") || StartsWith(name, "next_boot.");
424         if (socket && persistent_properties_loaded && need_persist) {
425             if (persist_write_thread) {
426                 persist_write_thread->Write(name, value, std::move(*socket));
427                 return {};
428             }
429             WritePersistentProperty(name, value);
430         }
431     }
432 
433     NotifyPropertyChange(name, value);
434     return {PROP_SUCCESS};
435 }
436 
437 // Helper for PropertySet, for the case where no socket is used, and therefore an asynchronous
438 // return is not possible.
PropertySetNoSocket(const std::string & name,const std::string & value,std::string * error)439 static uint32_t PropertySetNoSocket(const std::string& name, const std::string& value,
440                                     std::string* error) {
441     auto ret = PropertySet(name, value, nullptr, error);
442     CHECK(ret.has_value());
443     return *ret;
444 }
445 
SendControlMessage(const std::string & msg,const std::string & name,pid_t pid,SocketConnection * socket,std::string * error)446 static uint32_t SendControlMessage(const std::string& msg, const std::string& name, pid_t pid,
447                                    SocketConnection* socket, std::string* error) {
448     auto lock = std::lock_guard{accept_messages_lock};
449     if (!accept_messages) {
450         // If we're already shutting down and you're asking us to stop something,
451         // just say we did (https://issuetracker.google.com/336223505).
452         if (msg == "stop") return PROP_SUCCESS;
453 
454         *error = "Received control message after shutdown, ignoring";
455         return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
456     }
457 
458     // We must release the fd before sending it to init, otherwise there will be a race with init.
459     // If init calls close() before Release(), then fdsan will see the wrong tag and abort().
460     int fd = -1;
461     if (socket != nullptr && SelinuxGetVendorAndroidVersion() > __ANDROID_API_Q__) {
462         fd = socket->Release();
463     }
464 
465     bool queue_success = QueueControlMessage(msg, name, pid, fd);
466     if (!queue_success && fd != -1) {
467         uint32_t response = PROP_ERROR_HANDLE_CONTROL_MESSAGE;
468         TEMP_FAILURE_RETRY(send(fd, &response, sizeof(response), 0));
469         close(fd);
470     }
471 
472     return PROP_SUCCESS;
473 }
474 
CheckControlPropertyPerms(const std::string & name,const std::string & value,const std::string & source_context,const ucred & cr)475 bool CheckControlPropertyPerms(const std::string& name, const std::string& value,
476                                const std::string& source_context, const ucred& cr) {
477     // We check the legacy method first but these properties are dontaudit, so we only log an audit
478     // if the newer method fails as well.  We only do this with the legacy ctl. properties.
479     if (name == "ctl.start" || name == "ctl.stop" || name == "ctl.restart") {
480         // The legacy permissions model is that ctl. properties have their name ctl.<action> and
481         // their value is the name of the service to apply that action to.  Permissions for these
482         // actions are based on the service, so we must create a fake name of ctl.<service> to
483         // check permissions.
484         auto control_string_legacy = "ctl." + value;
485         const char* target_context_legacy = nullptr;
486         const char* type_legacy = nullptr;
487         property_info_area->GetPropertyInfo(control_string_legacy.c_str(), &target_context_legacy,
488                                             &type_legacy);
489 
490         if (CheckMacPerms(control_string_legacy, target_context_legacy, source_context.c_str(), cr)) {
491             return true;
492         }
493     }
494 
495     auto control_string_full = name + "$" + value;
496     const char* target_context_full = nullptr;
497     const char* type_full = nullptr;
498     property_info_area->GetPropertyInfo(control_string_full.c_str(), &target_context_full,
499                                         &type_full);
500 
501     return CheckMacPerms(control_string_full, target_context_full, source_context.c_str(), cr);
502 }
503 
504 // 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)505 uint32_t CheckPermissions(const std::string& name, const std::string& value,
506                           const std::string& source_context, const ucred& cr, std::string* error) {
507     if (!IsLegalPropertyName(name)) {
508         *error = "Illegal property name";
509         return PROP_ERROR_INVALID_NAME;
510     }
511 
512     if (StartsWith(name, "ctl.")) {
513         if (!CheckControlPropertyPerms(name, value, source_context, cr)) {
514             *error = StringPrintf("Invalid permissions to perform '%s' on '%s'", name.c_str() + 4,
515                                   value.c_str());
516             return PROP_ERROR_HANDLE_CONTROL_MESSAGE;
517         }
518 
519         return PROP_SUCCESS;
520     }
521 
522     const char* target_context = nullptr;
523     const char* type = nullptr;
524     property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type);
525 
526     if (!CheckMacPerms(name, target_context, source_context.c_str(), cr)) {
527         *error = "SELinux permission check failed";
528         return PROP_ERROR_PERMISSION_DENIED;
529     }
530 
531     if (!CheckType(type, value)) {
532         *error = StringPrintf("Property type check failed, value doesn't match expected type '%s'",
533                               (type ?: "(null)"));
534         return PROP_ERROR_INVALID_VALUE;
535     }
536 
537     return PROP_SUCCESS;
538 }
539 
540 // This returns one of the enum of PROP_SUCCESS or PROP_ERROR*, or std::nullopt
541 // if asynchronous.
HandlePropertySet(const std::string & name,const std::string & value,const std::string & source_context,const ucred & cr,SocketConnection * socket,std::string * error)542 std::optional<uint32_t> HandlePropertySet(const std::string& name, const std::string& value,
543                                           const std::string& source_context, const ucred& cr,
544                                           SocketConnection* socket, std::string* error) {
545     if (auto ret = CheckPermissions(name, value, source_context, cr, error); ret != PROP_SUCCESS) {
546         return {ret};
547     }
548 
549     if (StartsWith(name, "ctl.")) {
550         return {SendControlMessage(name.c_str() + 4, value, cr.pid, socket, error)};
551     }
552 
553     // sys.powerctl is a special property that is used to make the device reboot.  We want to log
554     // any process that sets this property to be able to accurately blame the cause of a shutdown.
555     if (name == "sys.powerctl") {
556         std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
557         std::string process_cmdline;
558         std::string process_log_string;
559         if (ReadFileToString(cmdline_path, &process_cmdline)) {
560             // Since cmdline is null deliminated, .c_str() conveniently gives us just the process
561             // path.
562             process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
563         }
564         LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
565                   << process_log_string;
566         if (value == "reboot,userspace") {
567             *error = "Userspace reboot is deprecated.";
568             return {PROP_ERROR_INVALID_VALUE};
569         }
570     }
571 
572     // If a process other than init is writing a non-empty value, it means that process is
573     // requesting that init performs a restorecon operation on the path specified by 'value'.
574     // We use a thread to do this restorecon operation to prevent holding up init, as it may take
575     // a long time to complete.
576     if (name == kRestoreconProperty && cr.pid != 1 && !value.empty()) {
577         static AsyncRestorecon async_restorecon;
578         async_restorecon.TriggerRestorecon(value);
579         return {PROP_SUCCESS};
580     }
581 
582     return PropertySet(name, value, socket, error);
583 }
584 
585 // Helper for HandlePropertySet, for the case where no socket is used, and
586 // 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)587 uint32_t HandlePropertySetNoSocket(const std::string& name, const std::string& value,
588                                    const std::string& source_context, const ucred& cr,
589                                    std::string* error) {
590     auto ret = HandlePropertySet(name, value, source_context, cr, nullptr, error);
591     CHECK(ret.has_value());
592     return *ret;
593 }
594 
handle_property_set_fd(int fd)595 static void handle_property_set_fd(int fd) {
596     static constexpr uint32_t kDefaultSocketTimeout = 5000; /* ms */
597 
598     int s = accept4(fd, nullptr, nullptr, SOCK_CLOEXEC);
599     if (s == -1) {
600         return;
601     }
602 
603     ucred cr;
604     socklen_t cr_size = sizeof(cr);
605     if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
606         close(s);
607         PLOG(ERROR) << "sys_prop: unable to get SO_PEERCRED";
608         return;
609     }
610 
611     SocketConnection socket(s, cr);
612     uint32_t timeout_ms = kDefaultSocketTimeout;
613 
614     uint32_t cmd = 0;
615     if (!socket.RecvUint32(&cmd, &timeout_ms)) {
616         PLOG(ERROR) << "sys_prop: error while reading command from the socket";
617         socket.SendUint32(PROP_ERROR_READ_CMD);
618         return;
619     }
620 
621     switch (cmd) {
622     case PROP_MSG_SETPROP: {
623         char prop_name[PROP_NAME_MAX];
624         char prop_value[PROP_VALUE_MAX];
625 
626         if (!socket.RecvChars(prop_name, PROP_NAME_MAX, &timeout_ms) ||
627             !socket.RecvChars(prop_value, PROP_VALUE_MAX, &timeout_ms)) {
628           PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP): error while reading name/value from the socket";
629           return;
630         }
631 
632         prop_name[PROP_NAME_MAX-1] = 0;
633         prop_value[PROP_VALUE_MAX-1] = 0;
634 
635         std::string source_context;
636         if (!socket.GetSourceContext(&source_context)) {
637             PLOG(ERROR) << "Unable to set property '" << prop_name << "': getpeercon() failed";
638             return;
639         }
640 
641         const auto& cr = socket.cred();
642         std::string error;
643         auto result = HandlePropertySetNoSocket(prop_name, prop_value, source_context, cr, &error);
644         if (result != PROP_SUCCESS) {
645             LOG(ERROR) << "Unable to set property '" << prop_name << "' from uid:" << cr.uid
646                        << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
647         }
648 
649         break;
650       }
651 
652     case PROP_MSG_SETPROP2: {
653         std::string name;
654         std::string value;
655         if (!socket.RecvString(&name, &timeout_ms) ||
656             !socket.RecvString(&value, &timeout_ms)) {
657           PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP2): error while reading name/value from the socket";
658           socket.SendUint32(PROP_ERROR_READ_DATA);
659           return;
660         }
661 
662         std::string source_context;
663         if (!socket.GetSourceContext(&source_context)) {
664             PLOG(ERROR) << "Unable to set property '" << name << "': getpeercon() failed";
665             socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
666             return;
667         }
668 
669         // HandlePropertySet takes ownership of the socket if the set is handled asynchronously.
670         const auto& cr = socket.cred();
671         std::string error;
672         auto result = HandlePropertySet(name, value, source_context, cr, &socket, &error);
673         if (!result) {
674             // Result will be sent after completion.
675             return;
676         }
677         if (*result != PROP_SUCCESS) {
678             LOG(ERROR) << "Unable to set property '" << name << "' from uid:" << cr.uid
679                        << " gid:" << cr.gid << " pid:" << cr.pid << ": " << error;
680         }
681         socket.SendUint32(*result);
682         break;
683       }
684 
685     default:
686         LOG(ERROR) << "sys_prop: invalid command " << cmd;
687         socket.SendUint32(PROP_ERROR_INVALID_CMD);
688         break;
689     }
690 }
691 
InitPropertySet(const std::string & name,const std::string & value)692 uint32_t InitPropertySet(const std::string& name, const std::string& value) {
693     ucred cr = {.pid = 1, .uid = 0, .gid = 0};
694     std::string error;
695     auto result = HandlePropertySetNoSocket(name, value, kInitContext, cr, &error);
696     if (result != PROP_SUCCESS) {
697         LOG(ERROR) << "Init cannot set '" << name << "' to '" << value << "': " << error;
698     }
699 
700     return result;
701 }
702 
703 static Result<void> load_properties_from_file(const char*, const char*,
704                                               std::map<std::string, std::string>*);
705 
706 /*
707  * Filter is used to decide which properties to load: NULL loads all keys,
708  * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match.
709  */
LoadProperties(char * data,const char * filter,const char * filename,std::map<std::string,std::string> * properties)710 static void LoadProperties(char* data, const char* filter, const char* filename,
711                            std::map<std::string, std::string>* properties) {
712     char *key, *value, *eol, *sol, *tmp, *fn;
713     size_t flen = 0;
714 
715     static constexpr const char* const kVendorPathPrefixes[4] = {
716             "/vendor",
717             "/odm",
718             "/vendor_dlkm",
719             "/odm_dlkm",
720     };
721 
722     const char* context = kInitContext;
723     if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
724         for (const auto& vendor_path_prefix : kVendorPathPrefixes) {
725             if (StartsWith(filename, vendor_path_prefix)) {
726                 context = kVendorContext;
727             }
728         }
729     }
730 
731     if (filter) {
732         flen = strlen(filter);
733     }
734 
735     sol = data;
736     while ((eol = strchr(sol, '\n'))) {
737         key = sol;
738         *eol++ = 0;
739         sol = eol;
740 
741         while (isspace(*key)) key++;
742         if (*key == '#') continue;
743 
744         tmp = eol - 2;
745         while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
746 
747         if (!strncmp(key, "import ", 7) && flen == 0) {
748             fn = key + 7;
749             while (isspace(*fn)) fn++;
750 
751             key = strchr(fn, ' ');
752             if (key) {
753                 *key++ = 0;
754                 while (isspace(*key)) key++;
755             }
756 
757             std::string raw_filename(fn);
758             auto expanded_filename = ExpandProps(raw_filename);
759 
760             if (!expanded_filename.ok()) {
761                 LOG(ERROR) << "Could not expand filename ': " << expanded_filename.error();
762                 continue;
763             }
764 
765             if (auto res = load_properties_from_file(expanded_filename->c_str(), key, properties);
766                 !res.ok()) {
767                 LOG(WARNING) << res.error();
768             }
769         } else {
770             value = strchr(key, '=');
771             if (!value) continue;
772             *value++ = 0;
773 
774             tmp = value - 2;
775             while ((tmp > key) && isspace(*tmp)) *tmp-- = 0;
776 
777             while (isspace(*value)) value++;
778 
779             if (flen > 0) {
780                 if (filter[flen - 1] == '*') {
781                     if (strncmp(key, filter, flen - 1) != 0) continue;
782                 } else {
783                     if (strcmp(key, filter) != 0) continue;
784                 }
785             }
786 
787             if (StartsWith(key, "ctl.") || key == "sys.powerctl"s ||
788                 std::string{key} == kRestoreconProperty) {
789                 LOG(ERROR) << "Ignoring disallowed property '" << key
790                            << "' with special meaning in prop file '" << filename << "'";
791                 continue;
792             }
793 
794             ucred cr = {.pid = 1, .uid = 0, .gid = 0};
795             std::string error;
796             if (CheckPermissions(key, value, context, cr, &error) == PROP_SUCCESS) {
797                 auto it = properties->find(key);
798                 if (it == properties->end()) {
799                     (*properties)[key] = value;
800                 } else if (it->second != value) {
801                     LOG(WARNING) << "Overriding previous property '" << key << "':'" << it->second
802                                  << "' with new value '" << value << "'";
803                     it->second = value;
804                 }
805             } else {
806                 LOG(ERROR) << "Do not have permissions to set '" << key << "' to '" << value
807                            << "' in property file '" << filename << "': " << error;
808             }
809         }
810     }
811 }
812 
813 // Filter is used to decide which properties to load: NULL loads all keys,
814 // "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)815 static Result<void> load_properties_from_file(const char* filename, const char* filter,
816                                               std::map<std::string, std::string>* properties) {
817     Timer t;
818     auto file_contents = ReadFile(filename);
819     if (!file_contents.ok()) {
820         return Error() << "Couldn't load property file '" << filename
821                        << "': " << file_contents.error();
822     }
823     file_contents->push_back('\n');
824 
825     LoadProperties(file_contents->data(), filter, filename, properties);
826     LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)";
827     return {};
828 }
829 
LoadPropertiesFromSecondStageRes(std::map<std::string,std::string> * properties)830 static void LoadPropertiesFromSecondStageRes(std::map<std::string, std::string>* properties) {
831     std::string prop = GetRamdiskPropForSecondStage();
832     if (access(prop.c_str(), R_OK) != 0) {
833         CHECK(errno == ENOENT) << "Cannot access " << prop << ": " << strerror(errno);
834         return;
835     }
836     if (auto res = load_properties_from_file(prop.c_str(), nullptr, properties); !res.ok()) {
837         LOG(WARNING) << res.error();
838     }
839 }
840 
841 // persist.sys.usb.config values can't be combined on build-time when property
842 // files are split into each partition.
843 // So we need to apply the same rule of build/make/tools/post_process_props.py
844 // on runtime.
update_sys_usb_config()845 static void update_sys_usb_config() {
846     bool is_debuggable = android::base::GetBoolProperty("ro.debuggable", false);
847     std::string config = android::base::GetProperty("persist.sys.usb.config", "");
848     // b/150130503, add (config == "none") condition here to prevent appending
849     // ",adb" if "none" is explicitly defined in default prop.
850     if (config.empty() || config == "none") {
851         InitPropertySet("persist.sys.usb.config", is_debuggable ? "adb" : "none");
852     } else if (is_debuggable && config.find("adb") == std::string::npos &&
853                config.length() + 4 < PROP_VALUE_MAX) {
854         config.append(",adb");
855         InitPropertySet("persist.sys.usb.config", config);
856     }
857 }
858 
load_override_properties()859 static void load_override_properties() {
860     if (ALLOW_LOCAL_PROP_OVERRIDE) {
861         std::map<std::string, std::string> properties;
862         load_properties_from_file("/data/local.prop", nullptr, &properties);
863         for (const auto& [name, value] : properties) {
864             std::string error;
865             if (PropertySetNoSocket(name, value, &error) != PROP_SUCCESS) {
866                 LOG(ERROR) << "Could not set '" << name << "' to '" << value
867                            << "' in /data/local.prop: " << error;
868             }
869         }
870     }
871 }
872 
873 // If the ro.product.[brand|device|manufacturer|model|name] properties have not been explicitly
874 // set, derive them from ro.product.${partition}.* properties
property_initialize_ro_product_props()875 static void property_initialize_ro_product_props() {
876     const char* RO_PRODUCT_PROPS_PREFIX = "ro.product.";
877     const char* RO_PRODUCT_PROPS[] = {
878             "brand", "device", "manufacturer", "model", "name",
879     };
880     const char* RO_PRODUCT_PROPS_ALLOWED_SOURCES[] = {
881             "odm", "product", "system_ext", "system", "vendor",
882     };
883     const char* RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER = "product,odm,vendor,system_ext,system";
884     const std::string EMPTY = "";
885 
886     std::string ro_product_props_source_order =
887             GetProperty("ro.product.property_source_order", EMPTY);
888 
889     if (!ro_product_props_source_order.empty()) {
890         // Verify that all specified sources are valid
891         for (const auto& source : Split(ro_product_props_source_order, ",")) {
892             // Verify that the specified source is valid
893             bool is_allowed_source = false;
894             for (const auto& allowed_source : RO_PRODUCT_PROPS_ALLOWED_SOURCES) {
895                 if (source == allowed_source) {
896                     is_allowed_source = true;
897                     break;
898                 }
899             }
900             if (!is_allowed_source) {
901                 LOG(ERROR) << "Found unexpected source in ro.product.property_source_order; "
902                               "using the default property source order";
903                 ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
904                 break;
905             }
906         }
907     } else {
908         ro_product_props_source_order = RO_PRODUCT_PROPS_DEFAULT_SOURCE_ORDER;
909     }
910 
911     for (const auto& ro_product_prop : RO_PRODUCT_PROPS) {
912         std::string base_prop(RO_PRODUCT_PROPS_PREFIX);
913         base_prop += ro_product_prop;
914 
915         std::string base_prop_val = GetProperty(base_prop, EMPTY);
916         if (!base_prop_val.empty()) {
917             continue;
918         }
919 
920         for (const auto& source : Split(ro_product_props_source_order, ",")) {
921             std::string target_prop(RO_PRODUCT_PROPS_PREFIX);
922             target_prop += source;
923             target_prop += '.';
924             target_prop += ro_product_prop;
925 
926             std::string target_prop_val = GetProperty(target_prop, EMPTY);
927             if (!target_prop_val.empty()) {
928                 LOG(INFO) << "Setting product property " << base_prop << " to '" << target_prop_val
929                           << "' (from " << target_prop << ")";
930                 std::string error;
931                 auto res = PropertySetNoSocket(base_prop, target_prop_val, &error);
932                 if (res != PROP_SUCCESS) {
933                     LOG(ERROR) << "Error setting product property " << base_prop << ": err=" << res
934                                << " (" << error << ")";
935                 }
936                 break;
937             }
938         }
939     }
940 }
941 
property_initialize_build_id()942 static void property_initialize_build_id() {
943     std::string build_id = GetProperty(ID_PROP, "");
944     if (!build_id.empty()) {
945         return;
946     }
947 
948     std::string legacy_build_id = GetProperty(LEGACY_ID_PROP, "");
949     std::string vbmeta_digest = GetProperty(VBMETA_DIGEST_PROP, "");
950     if (vbmeta_digest.size() < DIGEST_SIZE_USED) {
951         LOG(ERROR) << "vbmeta digest size too small " << vbmeta_digest;
952         // Still try to set the id field in the unexpected case.
953         build_id = legacy_build_id;
954     } else {
955         // Derive the ro.build.id by appending the vbmeta digest to the base value.
956         build_id = legacy_build_id + "." + vbmeta_digest.substr(0, DIGEST_SIZE_USED);
957     }
958 
959     std::string error;
960     auto res = PropertySetNoSocket(ID_PROP, build_id, &error);
961     if (res != PROP_SUCCESS) {
962         LOG(ERROR) << "Failed to set " << ID_PROP << " to " << build_id;
963     }
964 }
965 
ConstructBuildFingerprint(bool legacy)966 static std::string ConstructBuildFingerprint(bool legacy) {
967     const std::string UNKNOWN = "unknown";
968     std::string build_fingerprint = GetProperty("ro.product.brand", UNKNOWN);
969     build_fingerprint += '/';
970     build_fingerprint += GetProperty("ro.product.name", UNKNOWN);
971 
972     // should be set in /product/etc/build.prop
973     // when we have a dev option device, and we've switched the kernel to 16kb mode
974     // we use the same system image, but we've switched out the kernel, so make it
975     // visible at a high level
976     bool has16KbDevOption =
977             android::base::GetBoolProperty("ro.product.build.16k_page.enabled", false);
978     if (has16KbDevOption && getpagesize() == 16384) {
979         build_fingerprint += "_16kb";
980     }
981 
982     build_fingerprint += '/';
983     build_fingerprint += GetProperty("ro.product.device", UNKNOWN);
984     build_fingerprint += ':';
985     build_fingerprint += GetProperty("ro.build.version.release_or_codename", UNKNOWN);
986     build_fingerprint += '/';
987 
988     std::string build_id =
989             legacy ? GetProperty(LEGACY_ID_PROP, UNKNOWN) : GetProperty(ID_PROP, UNKNOWN);
990     build_fingerprint += build_id;
991     build_fingerprint += '/';
992     build_fingerprint += GetProperty("ro.build.version.incremental", UNKNOWN);
993     build_fingerprint += ':';
994     build_fingerprint += GetProperty("ro.build.type", UNKNOWN);
995     build_fingerprint += '/';
996     build_fingerprint += GetProperty("ro.build.tags", UNKNOWN);
997 
998     return build_fingerprint;
999 }
1000 
1001 // Derive the legacy build fingerprint if we overwrite the build id at runtime.
property_derive_legacy_build_fingerprint()1002 static void property_derive_legacy_build_fingerprint() {
1003     std::string legacy_build_fingerprint = GetProperty(LEGACY_FINGERPRINT_PROP, "");
1004     if (!legacy_build_fingerprint.empty()) {
1005         return;
1006     }
1007 
1008     // The device doesn't have a legacy build id, skipping the legacy fingerprint.
1009     std::string legacy_build_id = GetProperty(LEGACY_ID_PROP, "");
1010     if (legacy_build_id.empty()) {
1011         return;
1012     }
1013 
1014     legacy_build_fingerprint = ConstructBuildFingerprint(true /* legacy fingerprint */);
1015     LOG(INFO) << "Setting property '" << LEGACY_FINGERPRINT_PROP << "' to '"
1016               << legacy_build_fingerprint << "'";
1017 
1018     std::string error;
1019     auto res = PropertySetNoSocket(LEGACY_FINGERPRINT_PROP, legacy_build_fingerprint, &error);
1020     if (res != PROP_SUCCESS) {
1021         LOG(ERROR) << "Error setting property '" << LEGACY_FINGERPRINT_PROP << "': err=" << res
1022                    << " (" << error << ")";
1023     }
1024 }
1025 
1026 // If the ro.build.fingerprint property has not been set, derive it from constituent pieces
property_derive_build_fingerprint()1027 static void property_derive_build_fingerprint() {
1028     std::string build_fingerprint = GetProperty("ro.build.fingerprint", "");
1029     if (!build_fingerprint.empty()) {
1030         return;
1031     }
1032 
1033     build_fingerprint = ConstructBuildFingerprint(false /* legacy fingerprint */);
1034     LOG(INFO) << "Setting property '" << FINGERPRINT_PROP << "' to '" << build_fingerprint << "'";
1035 
1036     std::string error;
1037     auto res = PropertySetNoSocket(FINGERPRINT_PROP, build_fingerprint, &error);
1038     if (res != PROP_SUCCESS) {
1039         LOG(ERROR) << "Error setting property '" << FINGERPRINT_PROP << "': err=" << res << " ("
1040                    << error << ")";
1041     }
1042 }
1043 
1044 // If the ro.product.cpu.abilist* properties have not been explicitly
1045 // set, derive them from ro.${partition}.product.cpu.abilist* properties.
property_initialize_ro_cpu_abilist()1046 static void property_initialize_ro_cpu_abilist() {
1047     // From high to low priority.
1048     const char* kAbilistSources[] = {
1049             "product",
1050             "odm",
1051             "vendor",
1052             "system",
1053     };
1054     const std::string EMPTY = "";
1055     const char* kAbilistProp = "ro.product.cpu.abilist";
1056     const char* kAbilist32Prop = "ro.product.cpu.abilist32";
1057     const char* kAbilist64Prop = "ro.product.cpu.abilist64";
1058 
1059     // If the properties are defined explicitly, just use them.
1060     if (GetProperty(kAbilistProp, EMPTY) != EMPTY) {
1061         return;
1062     }
1063 
1064     // Find the first source defining these properties by order.
1065     std::string abilist32_prop_val;
1066     std::string abilist64_prop_val;
1067     for (const auto& source : kAbilistSources) {
1068         const auto abilist32_prop = std::string("ro.") + source + ".product.cpu.abilist32";
1069         const auto abilist64_prop = std::string("ro.") + source + ".product.cpu.abilist64";
1070         abilist32_prop_val = GetProperty(abilist32_prop, EMPTY);
1071         abilist64_prop_val = GetProperty(abilist64_prop, EMPTY);
1072         // The properties could be empty on 32-bit-only or 64-bit-only devices,
1073         // but we cannot identify a property is empty or undefined by GetProperty().
1074         // So, we assume both of these 2 properties are empty as undefined.
1075         if (abilist32_prop_val != EMPTY || abilist64_prop_val != EMPTY) {
1076             break;
1077         }
1078     }
1079 
1080     // Merge ABI lists for ro.product.cpu.abilist
1081     auto abilist_prop_val = abilist64_prop_val;
1082     if (abilist32_prop_val != EMPTY) {
1083         if (abilist_prop_val != EMPTY) {
1084             abilist_prop_val += ",";
1085         }
1086         abilist_prop_val += abilist32_prop_val;
1087     }
1088 
1089     // Set these properties
1090     const std::pair<const char*, const std::string&> set_prop_list[] = {
1091             {kAbilistProp, abilist_prop_val},
1092             {kAbilist32Prop, abilist32_prop_val},
1093             {kAbilist64Prop, abilist64_prop_val},
1094     };
1095     for (const auto& [prop, prop_val] : set_prop_list) {
1096         LOG(INFO) << "Setting property '" << prop << "' to '" << prop_val << "'";
1097 
1098         std::string error;
1099         auto res = PropertySetNoSocket(prop, prop_val, &error);
1100         if (res != PROP_SUCCESS) {
1101             LOG(ERROR) << "Error setting property '" << prop << "': err=" << res << " (" << error
1102                        << ")";
1103         }
1104     }
1105 }
1106 
property_initialize_ro_vendor_api_level()1107 static void property_initialize_ro_vendor_api_level() {
1108     // ro.vendor.api_level shows the api_level that the vendor images (vendor, odm, ...) are
1109     // required to support.
1110     constexpr auto VENDOR_API_LEVEL_PROP = "ro.vendor.api_level";
1111 
1112     if (__system_property_find(VENDOR_API_LEVEL_PROP) != nullptr) {
1113         // The device already have ro.vendor.api_level in its vendor/build.prop.
1114         // Skip initializing the ro.vendor.api_level property.
1115         return;
1116     }
1117 
1118     auto vendor_api_level = GetIntProperty("ro.board.first_api_level", __ANDROID_VENDOR_API_MAX__);
1119     if (vendor_api_level != __ANDROID_VENDOR_API_MAX__) {
1120         // Update the vendor_api_level with "ro.board.api_level" only if both "ro.board.api_level"
1121         // and "ro.board.first_api_level" are defined.
1122         vendor_api_level = GetIntProperty("ro.board.api_level", vendor_api_level);
1123     }
1124 
1125     auto product_first_api_level =
1126             GetIntProperty("ro.product.first_api_level", __ANDROID_API_FUTURE__);
1127     if (product_first_api_level == __ANDROID_API_FUTURE__) {
1128         // Fallback to "ro.build.version.sdk" if the "ro.product.first_api_level" is not defined.
1129         product_first_api_level = GetIntProperty("ro.build.version.sdk", __ANDROID_API_FUTURE__);
1130     }
1131 
1132     vendor_api_level =
1133             std::min(AVendorSupport_getVendorApiLevelOf(product_first_api_level), vendor_api_level);
1134 
1135     if (vendor_api_level < 0) {
1136         LOG(ERROR) << "Unexpected vendor api level for " << VENDOR_API_LEVEL_PROP << ". Check "
1137                    << "ro.product.first_api_level and ro.build.version.sdk.";
1138         vendor_api_level = __ANDROID_VENDOR_API_MAX__;
1139     }
1140 
1141     std::string error;
1142     auto res = PropertySetNoSocket(VENDOR_API_LEVEL_PROP, std::to_string(vendor_api_level), &error);
1143     if (res != PROP_SUCCESS) {
1144         LOG(ERROR) << "Failed to set " << VENDOR_API_LEVEL_PROP << " with " << vendor_api_level
1145                    << ": " << error << "(" << res << ")";
1146     }
1147 }
1148 
PropertyLoadBootDefaults()1149 void PropertyLoadBootDefaults() {
1150     // We read the properties and their values into a map, in order to always allow properties
1151     // loaded in the later property files to override the properties in loaded in the earlier
1152     // property files, regardless of if they are "ro." properties or not.
1153     std::map<std::string, std::string> properties;
1154 
1155     if (IsRecoveryMode()) {
1156         if (auto res = load_properties_from_file("/prop.default", nullptr, &properties);
1157             !res.ok()) {
1158             LOG(ERROR) << res.error();
1159         }
1160     }
1161 
1162     // /<part>/etc/build.prop is the canonical location of the build-time properties since S.
1163     // Falling back to /<part>/defalt.prop and /<part>/build.prop only when legacy path has to
1164     // be supported, which is controlled by the support_legacy_path_until argument.
1165     const auto load_properties_from_partition = [&properties](const std::string& partition,
1166                                                               int support_legacy_path_until) {
1167         auto path = "/" + partition + "/etc/build.prop";
1168         if (load_properties_from_file(path.c_str(), nullptr, &properties).ok()) {
1169             return;
1170         }
1171         // To read ro.<partition>.build.version.sdk, temporarily load the legacy paths into a
1172         // separate map. Then by comparing its value with legacy_version, we know that if the
1173         // partition is old enough so that we need to respect the legacy paths.
1174         std::map<std::string, std::string> temp;
1175         auto legacy_path1 = "/" + partition + "/default.prop";
1176         auto legacy_path2 = "/" + partition + "/build.prop";
1177         load_properties_from_file(legacy_path1.c_str(), nullptr, &temp);
1178         load_properties_from_file(legacy_path2.c_str(), nullptr, &temp);
1179         bool support_legacy_path = false;
1180         auto version_prop_name = "ro." + partition + ".build.version.sdk";
1181         auto it = temp.find(version_prop_name);
1182         if (it == temp.end()) {
1183             // This is embarassing. Without the prop, we can't determine how old the partition is.
1184             // Let's be conservative by assuming it is very very old.
1185             support_legacy_path = true;
1186         } else if (int value;
1187                    ParseInt(it->second.c_str(), &value) && value <= support_legacy_path_until) {
1188             support_legacy_path = true;
1189         }
1190         if (support_legacy_path) {
1191             // We don't update temp into properties directly as it might skip any (future) logic
1192             // for resolving duplicates implemented in load_properties_from_file.  Instead, read
1193             // the files again into the properties map.
1194             load_properties_from_file(legacy_path1.c_str(), nullptr, &properties);
1195             load_properties_from_file(legacy_path2.c_str(), nullptr, &properties);
1196         } else {
1197             LOG(FATAL) << legacy_path1 << " and " << legacy_path2 << " were not loaded "
1198                        << "because " << version_prop_name << "(" << it->second << ") is newer "
1199                        << "than " << support_legacy_path_until;
1200         }
1201     };
1202 
1203     // Order matters here. The more the partition is specific to a product, the higher its
1204     // precedence is.
1205     LoadPropertiesFromSecondStageRes(&properties);
1206 
1207     // system should have build.prop, unlike the other partitions
1208     if (auto res = load_properties_from_file("/system/build.prop", nullptr, &properties);
1209         !res.ok()) {
1210         LOG(WARNING) << res.error();
1211     }
1212 
1213     load_properties_from_partition("system_ext", /* support_legacy_path_until */ 30);
1214     load_properties_from_file("/system_dlkm/etc/build.prop", nullptr, &properties);
1215     // TODO(b/117892318): uncomment the following condition when vendor.imgs for aosp_* targets are
1216     // all updated.
1217     // if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_R__) {
1218     load_properties_from_file("/vendor/default.prop", nullptr, &properties);
1219     // }
1220     load_properties_from_file("/vendor/build.prop", nullptr, &properties);
1221     load_properties_from_file("/vendor_dlkm/etc/build.prop", nullptr, &properties);
1222     load_properties_from_file("/odm_dlkm/etc/build.prop", nullptr, &properties);
1223     load_properties_from_partition("odm", /* support_legacy_path_until */ 28);
1224     load_properties_from_partition("product", /* support_legacy_path_until */ 30);
1225 
1226     if (access(kDebugRamdiskProp, R_OK) == 0) {
1227         LOG(INFO) << "Loading " << kDebugRamdiskProp;
1228         if (auto res = load_properties_from_file(kDebugRamdiskProp, nullptr, &properties);
1229             !res.ok()) {
1230             LOG(WARNING) << res.error();
1231         }
1232     }
1233 
1234     for (const auto& [name, value] : properties) {
1235         std::string error;
1236         if (PropertySetNoSocket(name, value, &error) != PROP_SUCCESS) {
1237             LOG(ERROR) << "Could not set '" << name << "' to '" << value
1238                        << "' while loading .prop files" << error;
1239         }
1240     }
1241 
1242     property_initialize_ro_product_props();
1243     property_initialize_build_id();
1244     property_derive_build_fingerprint();
1245     property_derive_legacy_build_fingerprint();
1246     property_initialize_ro_cpu_abilist();
1247     property_initialize_ro_vendor_api_level();
1248 
1249     update_sys_usb_config();
1250 }
1251 
PropertyLoadDerivedDefaults()1252 void PropertyLoadDerivedDefaults() {
1253     const char* PAGE_PROP = "ro.boot.hardware.cpu.pagesize";
1254     if (GetProperty(PAGE_PROP, "").empty()) {
1255         std::string error;
1256         if (PropertySetNoSocket(PAGE_PROP, std::to_string(getpagesize()), &error) != PROP_SUCCESS) {
1257             LOG(ERROR) << "Could not set '" << PAGE_PROP << "' because: " << error;
1258         }
1259     }
1260 }
1261 
LoadPropertyInfoFromFile(const std::string & filename,std::vector<PropertyInfoEntry> * property_infos)1262 bool LoadPropertyInfoFromFile(const std::string& filename,
1263                               std::vector<PropertyInfoEntry>* property_infos) {
1264     auto file_contents = std::string();
1265     if (!ReadFileToString(filename, &file_contents)) {
1266         PLOG(ERROR) << "Could not read properties from '" << filename << "'";
1267         return false;
1268     }
1269 
1270     auto errors = std::vector<std::string>{};
1271     bool require_prefix_or_exact = SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__;
1272     ParsePropertyInfoFile(file_contents, require_prefix_or_exact, property_infos, &errors);
1273     // Individual parsing errors are reported but do not cause a failed boot, which is what
1274     // returning false would do here.
1275     for (const auto& error : errors) {
1276         LOG(ERROR) << "Could not read line from '" << filename << "': " << error;
1277     }
1278 
1279     return true;
1280 }
1281 
CreateSerializedPropertyInfo()1282 void CreateSerializedPropertyInfo() {
1283     auto property_infos = std::vector<PropertyInfoEntry>();
1284     if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
1285         if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",
1286                                       &property_infos)) {
1287             return;
1288         }
1289         // Don't check for failure here, since we don't always have all of these partitions.
1290         // E.g. In case of recovery, the vendor partition will not have mounted and we
1291         // still need the system / platform properties to function.
1292         if (access("/system_ext/etc/selinux/system_ext_property_contexts", R_OK) != -1) {
1293             LoadPropertyInfoFromFile("/system_ext/etc/selinux/system_ext_property_contexts",
1294                                      &property_infos);
1295         }
1296         if (access("/vendor/etc/selinux/vendor_property_contexts", R_OK) != -1) {
1297             LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",
1298                                      &property_infos);
1299         }
1300         if (access("/product/etc/selinux/product_property_contexts", R_OK) != -1) {
1301             LoadPropertyInfoFromFile("/product/etc/selinux/product_property_contexts",
1302                                      &property_infos);
1303         }
1304         if (access("/odm/etc/selinux/odm_property_contexts", R_OK) != -1) {
1305             LoadPropertyInfoFromFile("/odm/etc/selinux/odm_property_contexts", &property_infos);
1306         }
1307     } else {
1308         if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {
1309             return;
1310         }
1311         LoadPropertyInfoFromFile("/system_ext_property_contexts", &property_infos);
1312         LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos);
1313         LoadPropertyInfoFromFile("/product_property_contexts", &property_infos);
1314         LoadPropertyInfoFromFile("/odm_property_contexts", &property_infos);
1315     }
1316 
1317     auto serialized_contexts = std::string();
1318     auto error = std::string();
1319     if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,
1320                    &error)) {
1321         LOG(ERROR) << "Unable to serialize property contexts: " << error;
1322         return;
1323     }
1324 
1325     if (!WriteStringToFile(serialized_contexts, PROP_TREE_FILE, 0444, 0, 0, false)) {
1326         PLOG(ERROR) << "Unable to write serialized property infos to file";
1327     }
1328     selinux_android_restorecon(PROP_TREE_FILE, 0);
1329 
1330 #ifdef WRITE_APPCOMPAT_OVERRIDE_SYSTEM_PROPERTIES
1331     mkdir(APPCOMPAT_OVERRIDE_PROP_FOLDERNAME, S_IRWXU | S_IXGRP | S_IXOTH);
1332     if (!WriteStringToFile(serialized_contexts, APPCOMPAT_OVERRIDE_PROP_TREE_FILE, 0444, 0, 0,
1333                            false)) {
1334         PLOG(ERROR) << "Unable to write appcompat override property infos to file";
1335     }
1336     selinux_android_restorecon(APPCOMPAT_OVERRIDE_PROP_TREE_FILE, 0);
1337 #endif
1338 }
1339 
ExportKernelBootProps()1340 static void ExportKernelBootProps() {
1341     constexpr const char* UNSET = "";
1342     struct {
1343         const char* src_prop;
1344         const char* dst_prop;
1345         const char* default_value;
1346     } prop_map[] = {
1347             // clang-format off
1348         { "ro.boot.serialno",   "ro.serialno",   UNSET, },
1349         { "ro.boot.mode",       "ro.bootmode",   "unknown", },
1350         { "ro.boot.baseband",   "ro.baseband",   "unknown", },
1351         { "ro.boot.bootloader", "ro.bootloader", "unknown", },
1352         { "ro.boot.hardware",   "ro.hardware",   "unknown", },
1353         { "ro.boot.revision",   "ro.revision",   "0", },
1354             // clang-format on
1355     };
1356     for (const auto& prop : prop_map) {
1357         std::string value = GetProperty(prop.src_prop, prop.default_value);
1358         if (value != UNSET) InitPropertySet(prop.dst_prop, value);
1359     }
1360 }
1361 
ProcessKernelDt()1362 static void ProcessKernelDt() {
1363     if (!is_android_dt_value_expected("compatible", "android,firmware")) {
1364         return;
1365     }
1366 
1367     std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(android::fs_mgr::GetAndroidDtDir().c_str()),
1368                                             closedir);
1369     if (!dir) return;
1370 
1371     std::string dt_file;
1372     struct dirent* dp;
1373     while ((dp = readdir(dir.get())) != NULL) {
1374         if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") ||
1375             !strcmp(dp->d_name, "name")) {
1376             continue;
1377         }
1378 
1379         std::string file_name = android::fs_mgr::GetAndroidDtDir() + dp->d_name;
1380 
1381         android::base::ReadFileToString(file_name, &dt_file);
1382         std::replace(dt_file.begin(), dt_file.end(), ',', '.');
1383 
1384         InitPropertySet("ro.boot."s + dp->d_name, dt_file);
1385     }
1386 }
1387 
1388 constexpr auto ANDROIDBOOT_PREFIX = "androidboot."sv;
1389 
ProcessKernelCmdline()1390 static void ProcessKernelCmdline() {
1391     android::fs_mgr::ImportKernelCmdline([&](const std::string& key, const std::string& value) {
1392         if (StartsWith(key, ANDROIDBOOT_PREFIX)) {
1393             InitPropertySet("ro.boot." + key.substr(ANDROIDBOOT_PREFIX.size()), value);
1394         }
1395     });
1396 }
1397 
1398 
ProcessBootconfig()1399 static void ProcessBootconfig() {
1400     android::fs_mgr::ImportBootconfig([&](const std::string& key, const std::string& value) {
1401         if (StartsWith(key, ANDROIDBOOT_PREFIX)) {
1402             InitPropertySet("ro.boot." + key.substr(ANDROIDBOOT_PREFIX.size()), value);
1403         }
1404     });
1405 }
1406 
PropertyInit()1407 void PropertyInit() {
1408     selinux_callback cb;
1409     cb.func_audit = PropertyAuditCallback;
1410     selinux_set_callback(SELINUX_CB_AUDIT, cb);
1411 
1412     mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);
1413     CreateSerializedPropertyInfo();
1414     if (__system_property_area_init()) {
1415         LOG(FATAL) << "Failed to initialize property area";
1416     }
1417     if (!property_info_area.LoadDefaultPath()) {
1418         LOG(FATAL) << "Failed to load serialized property info file";
1419     }
1420 
1421     // If arguments are passed both on the command line and in DT,
1422     // properties set in DT always have priority over the command-line ones.
1423     ProcessKernelDt();
1424     ProcessKernelCmdline();
1425     ProcessBootconfig();
1426 
1427     // Propagate the kernel variables to internal variables
1428     // used by init as well as the current required properties.
1429     ExportKernelBootProps();
1430 
1431     PropertyLoadBootDefaults();
1432     PropertyLoadDerivedDefaults();
1433 }
1434 
HandleInitSocket()1435 static void HandleInitSocket() {
1436     auto message = ReadMessage(init_socket);
1437     if (!message.ok()) {
1438         LOG(ERROR) << "Could not read message from init_dedicated_recv_socket: " << message.error();
1439         return;
1440     }
1441 
1442     auto init_message = InitMessage{};
1443     if (!init_message.ParseFromString(*message)) {
1444         LOG(ERROR) << "Could not parse message from init";
1445         return;
1446     }
1447 
1448     switch (init_message.msg_case()) {
1449         case InitMessage::kLoadPersistentProperties: {
1450             load_override_properties();
1451 
1452             auto persistent_properties = LoadPersistentProperties();
1453             for (const auto& property_record : persistent_properties.properties()) {
1454                 auto const& prop_name = property_record.name();
1455                 auto const& prop_value = property_record.value();
1456                 InitPropertySet(prop_name, prop_value);
1457             }
1458 
1459             // Apply debug ramdisk special settings after persistent properties are loaded.
1460             if (android::base::GetBoolProperty("ro.force.debuggable", false)) {
1461                 // Always enable usb adb if device is booted with debug ramdisk.
1462                 update_sys_usb_config();
1463             }
1464             InitPropertySet("ro.persistent_properties.ready", "true");
1465             persistent_properties_loaded = true;
1466             break;
1467         }
1468         default:
1469             LOG(ERROR) << "Unknown message type from init: " << init_message.msg_case();
1470     }
1471 }
1472 
PropertyServiceThread(int fd,bool listen_init)1473 static void PropertyServiceThread(int fd, bool listen_init) {
1474     Epoll epoll;
1475     if (auto result = epoll.Open(); !result.ok()) {
1476         LOG(FATAL) << result.error();
1477     }
1478 
1479     if (auto result = epoll.RegisterHandler(fd, std::bind(handle_property_set_fd, fd));
1480         !result.ok()) {
1481         LOG(FATAL) << result.error();
1482     }
1483 
1484     if (listen_init) {
1485         if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result.ok()) {
1486             LOG(FATAL) << result.error();
1487         }
1488     }
1489 
1490     while (true) {
1491         auto epoll_result = epoll.Wait(std::nullopt);
1492         if (!epoll_result.ok()) {
1493             LOG(ERROR) << epoll_result.error();
1494         }
1495     }
1496 }
1497 
PersistWriteThread()1498 PersistWriteThread::PersistWriteThread() {
1499     auto new_thread = std::thread([this]() -> void { Work(); });
1500     thread_.swap(new_thread);
1501 }
1502 
Work()1503 void PersistWriteThread::Work() {
1504     while (true) {
1505         std::tuple<std::string, std::string, SocketConnection> item;
1506 
1507         // Grab the next item within the lock.
1508         {
1509             std::unique_lock<std::mutex> lock(mutex_);
1510 
1511             while (work_.empty()) {
1512                 cv_.wait(lock);
1513             }
1514 
1515             item = std::move(work_.front());
1516             work_.pop_front();
1517         }
1518 
1519         // Perform write/fsync outside the lock.
1520         WritePersistentProperty(std::get<0>(item), std::get<1>(item));
1521         NotifyPropertyChange(std::get<0>(item), std::get<1>(item));
1522 
1523         SocketConnection& socket = std::get<2>(item);
1524         socket.SendUint32(PROP_SUCCESS);
1525     }
1526 }
1527 
Write(std::string name,std::string value,SocketConnection socket)1528 void PersistWriteThread::Write(std::string name, std::string value, SocketConnection socket) {
1529     {
1530         std::unique_lock<std::mutex> lock(mutex_);
1531         work_.emplace_back(std::move(name), std::move(value), std::move(socket));
1532     }
1533     cv_.notify_all();
1534 }
1535 
StartThread(const char * name,int mode,int gid,std::thread & t,bool listen_init)1536 void StartThread(const char* name, int mode, int gid, std::thread& t, bool listen_init) {
1537     int fd = -1;
1538     if (auto result = CreateSocket(name, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1539                                    /*passcred=*/false, /*should_listen=*/false, mode, /*uid=*/0,
1540                                    /*gid=*/gid, /*socketcon=*/{});
1541         result.ok()) {
1542         fd = *result;
1543     } else {
1544         LOG(FATAL) << "start_property_service socket creation failed: " << result.error();
1545     }
1546 
1547     listen(fd, 8);
1548 
1549     auto new_thread = std::thread(PropertyServiceThread, fd, listen_init);
1550     t.swap(new_thread);
1551 }
1552 
StartPropertyService(int * epoll_socket)1553 void StartPropertyService(int* epoll_socket) {
1554     InitPropertySet("ro.property_service.version", "2");
1555 
1556     int sockets[2];
1557     if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, sockets) != 0) {
1558         PLOG(FATAL) << "Failed to socketpair() between property_service and init";
1559     }
1560     *epoll_socket = from_init_socket = sockets[0];
1561     init_socket = sockets[1];
1562     StartSendingMessages();
1563 
1564     StartThread(PROP_SERVICE_FOR_SYSTEM_NAME, 0660, AID_SYSTEM, property_service_for_system_thread,
1565                 true);
1566     StartThread(PROP_SERVICE_NAME, 0666, 0, property_service_thread, false);
1567 
1568     auto async_persist_writes =
1569             android::base::GetBoolProperty("ro.property_service.async_persist_writes", false);
1570 
1571     if (async_persist_writes) {
1572         persist_write_thread = std::make_unique<PersistWriteThread>();
1573     }
1574 }
1575 
1576 }  // namespace init
1577 }  // namespace android
1578