1 /*
2  * Copyright (C) 2008 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 "init.h"
18 
19 #include <dirent.h>
20 #include <fcntl.h>
21 #include <pthread.h>
22 #include <signal.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/mount.h>
26 #include <sys/signalfd.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 
30 #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
31 #include <sys/_system_properties.h>
32 
33 #include <functional>
34 #include <map>
35 #include <memory>
36 #include <optional>
37 #include <vector>
38 
39 #include <android-base/chrono_utils.h>
40 #include <android-base/file.h>
41 #include <android-base/logging.h>
42 #include <android-base/parseint.h>
43 #include <android-base/properties.h>
44 #include <android-base/stringprintf.h>
45 #include <android-base/strings.h>
46 #include <fs_avb/fs_avb.h>
47 #include <fs_mgr_vendor_overlay.h>
48 #include <keyutils.h>
49 #include <libavb/libavb.h>
50 #include <libgsi/libgsi.h>
51 #include <processgroup/processgroup.h>
52 #include <processgroup/setup.h>
53 #include <selinux/android.h>
54 
55 #include "action_parser.h"
56 #include "builtins.h"
57 #include "epoll.h"
58 #include "first_stage_init.h"
59 #include "first_stage_mount.h"
60 #include "import_parser.h"
61 #include "keychords.h"
62 #include "mount_handler.h"
63 #include "mount_namespace.h"
64 #include "property_service.h"
65 #include "proto_utils.h"
66 #include "reboot.h"
67 #include "reboot_utils.h"
68 #include "security.h"
69 #include "selabel.h"
70 #include "selinux.h"
71 #include "service.h"
72 #include "service_parser.h"
73 #include "sigchld_handler.h"
74 #include "system/core/init/property_service.pb.h"
75 #include "util.h"
76 
77 using namespace std::chrono_literals;
78 using namespace std::string_literals;
79 
80 using android::base::boot_clock;
81 using android::base::GetProperty;
82 using android::base::ReadFileToString;
83 using android::base::StringPrintf;
84 using android::base::Timer;
85 using android::base::Trim;
86 using android::fs_mgr::AvbHandle;
87 
88 namespace android {
89 namespace init {
90 
91 static int property_triggers_enabled = 0;
92 
93 static char qemu[32];
94 
95 static int signal_fd = -1;
96 static int property_fd = -1;
97 
98 static std::unique_ptr<Timer> waiting_for_prop(nullptr);
99 static std::string wait_prop_name;
100 static std::string wait_prop_value;
101 static std::string shutdown_command;
102 static bool do_shutdown = false;
103 static bool load_debug_prop = false;
104 
105 static std::unique_ptr<Subcontext> subcontext;
106 
DumpState()107 void DumpState() {
108     ServiceList::GetInstance().DumpState();
109     ActionManager::GetInstance().DumpState();
110 }
111 
CreateParser(ActionManager & action_manager,ServiceList & service_list)112 Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
113     Parser parser;
114 
115     parser.AddSectionParser("service", std::make_unique<ServiceParser>(
116                                                &service_list, subcontext.get(), std::nullopt));
117     parser.AddSectionParser("on",
118                             std::make_unique<ActionParser>(&action_manager, subcontext.get()));
119     parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
120 
121     return parser;
122 }
123 
124 // parser that only accepts new services
CreateServiceOnlyParser(ServiceList & service_list)125 Parser CreateServiceOnlyParser(ServiceList& service_list) {
126     Parser parser;
127 
128     parser.AddSectionParser("service", std::make_unique<ServiceParser>(
129                                                &service_list, subcontext.get(), std::nullopt));
130     return parser;
131 }
132 
LoadBootScripts(ActionManager & action_manager,ServiceList & service_list)133 static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
134     Parser parser = CreateParser(action_manager, service_list);
135 
136     std::string bootscript = GetProperty("ro.boot.init_rc", "");
137     if (bootscript.empty()) {
138         parser.ParseConfig("/init.rc");
139         if (!parser.ParseConfig("/system/etc/init")) {
140             late_import_paths.emplace_back("/system/etc/init");
141         }
142         // late_import is available only in Q and earlier release. As we don't
143         // have system_ext in those versions, skip late_import for system_ext.
144         parser.ParseConfig("/system_ext/etc/init");
145         if (!parser.ParseConfig("/product/etc/init")) {
146             late_import_paths.emplace_back("/product/etc/init");
147         }
148         if (!parser.ParseConfig("/odm/etc/init")) {
149             late_import_paths.emplace_back("/odm/etc/init");
150         }
151         if (!parser.ParseConfig("/vendor/etc/init")) {
152             late_import_paths.emplace_back("/vendor/etc/init");
153         }
154     } else {
155         parser.ParseConfig(bootscript);
156     }
157 }
158 
start_waiting_for_property(const char * name,const char * value)159 bool start_waiting_for_property(const char *name, const char *value)
160 {
161     if (waiting_for_prop) {
162         return false;
163     }
164     if (GetProperty(name, "") != value) {
165         // Current property value is not equal to expected value
166         wait_prop_name = name;
167         wait_prop_value = value;
168         waiting_for_prop.reset(new Timer());
169     } else {
170         LOG(INFO) << "start_waiting_for_property(\""
171                   << name << "\", \"" << value << "\"): already set";
172     }
173     return true;
174 }
175 
ResetWaitForProp()176 void ResetWaitForProp() {
177     wait_prop_name.clear();
178     wait_prop_value.clear();
179     waiting_for_prop.reset();
180 }
181 
TriggerShutdown(const std::string & command)182 void TriggerShutdown(const std::string& command) {
183     // We can't call HandlePowerctlMessage() directly in this function,
184     // because it modifies the contents of the action queue, which can cause the action queue
185     // to get into a bad state if this function is called from a command being executed by the
186     // action queue.  Instead we set this flag and ensure that shutdown happens before the next
187     // command is run in the main init loop.
188     shutdown_command = command;
189     do_shutdown = true;
190 }
191 
property_changed(const std::string & name,const std::string & value)192 void property_changed(const std::string& name, const std::string& value) {
193     // If the property is sys.powerctl, we bypass the event queue and immediately handle it.
194     // This is to ensure that init will always and immediately shutdown/reboot, regardless of
195     // if there are other pending events to process or if init is waiting on an exec service or
196     // waiting on a property.
197     // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific
198     // commands to be executed.
199     if (name == "sys.powerctl") {
200         TriggerShutdown(value);
201     }
202 
203     if (property_triggers_enabled) ActionManager::GetInstance().QueuePropertyChange(name, value);
204 
205     // We always record how long init waited for ueventd to tell us cold boot finished.
206     // If we aren't waiting on this property, it means that ueventd finished before we even started
207     // to wait.
208     if (name == kColdBootDoneProp) {
209         auto time_waited = waiting_for_prop ? waiting_for_prop->duration().count() : 0;
210         property_set("ro.boottime.init.cold_boot_wait", std::to_string(time_waited));
211     }
212 
213     if (waiting_for_prop) {
214         if (wait_prop_name == name && wait_prop_value == value) {
215             LOG(INFO) << "Wait for property '" << wait_prop_name << "=" << wait_prop_value
216                       << "' took " << *waiting_for_prop;
217             ResetWaitForProp();
218         }
219     }
220 }
221 
HandleProcessActions()222 static std::optional<boot_clock::time_point> HandleProcessActions() {
223     std::optional<boot_clock::time_point> next_process_action_time;
224     for (const auto& s : ServiceList::GetInstance()) {
225         if ((s->flags() & SVC_RUNNING) && s->timeout_period()) {
226             auto timeout_time = s->time_started() + *s->timeout_period();
227             if (boot_clock::now() > timeout_time) {
228                 s->Timeout();
229             } else {
230                 if (!next_process_action_time || timeout_time < *next_process_action_time) {
231                     next_process_action_time = timeout_time;
232                 }
233             }
234         }
235 
236         if (!(s->flags() & SVC_RESTARTING)) continue;
237 
238         auto restart_time = s->time_started() + s->restart_period();
239         if (boot_clock::now() > restart_time) {
240             if (auto result = s->Start(); !result) {
241                 LOG(ERROR) << "Could not restart process '" << s->name() << "': " << result.error();
242             }
243         } else {
244             if (!next_process_action_time || restart_time < *next_process_action_time) {
245                 next_process_action_time = restart_time;
246             }
247         }
248     }
249     return next_process_action_time;
250 }
251 
DoControlStart(Service * service)252 static Result<void> DoControlStart(Service* service) {
253     return service->Start();
254 }
255 
DoControlStop(Service * service)256 static Result<void> DoControlStop(Service* service) {
257     service->Stop();
258     return {};
259 }
260 
DoControlRestart(Service * service)261 static Result<void> DoControlRestart(Service* service) {
262     service->Restart();
263     return {};
264 }
265 
266 enum class ControlTarget {
267     SERVICE,    // function gets called for the named service
268     INTERFACE,  // action gets called for every service that holds this interface
269 };
270 
271 struct ControlMessageFunction {
272     ControlTarget target;
273     std::function<Result<void>(Service*)> action;
274 };
275 
get_control_message_map()276 static const std::map<std::string, ControlMessageFunction>& get_control_message_map() {
277     // clang-format off
278     static const std::map<std::string, ControlMessageFunction> control_message_functions = {
279         {"sigstop_on",        {ControlTarget::SERVICE,
280                                [](auto* service) { service->set_sigstop(true); return Result<void>{}; }}},
281         {"sigstop_off",       {ControlTarget::SERVICE,
282                                [](auto* service) { service->set_sigstop(false); return Result<void>{}; }}},
283         {"start",             {ControlTarget::SERVICE,   DoControlStart}},
284         {"stop",              {ControlTarget::SERVICE,   DoControlStop}},
285         {"restart",           {ControlTarget::SERVICE,   DoControlRestart}},
286         {"interface_start",   {ControlTarget::INTERFACE, DoControlStart}},
287         {"interface_stop",    {ControlTarget::INTERFACE, DoControlStop}},
288         {"interface_restart", {ControlTarget::INTERFACE, DoControlRestart}},
289     };
290     // clang-format on
291 
292     return control_message_functions;
293 }
294 
HandleControlMessage(const std::string & msg,const std::string & name,pid_t pid)295 bool HandleControlMessage(const std::string& msg, const std::string& name, pid_t pid) {
296     const auto& map = get_control_message_map();
297     const auto it = map.find(msg);
298 
299     if (it == map.end()) {
300         LOG(ERROR) << "Unknown control msg '" << msg << "'";
301         return false;
302     }
303 
304     std::string cmdline_path = StringPrintf("proc/%d/cmdline", pid);
305     std::string process_cmdline;
306     if (ReadFileToString(cmdline_path, &process_cmdline)) {
307         std::replace(process_cmdline.begin(), process_cmdline.end(), '\0', ' ');
308         process_cmdline = Trim(process_cmdline);
309     } else {
310         process_cmdline = "unknown process";
311     }
312 
313     const ControlMessageFunction& function = it->second;
314 
315     Service* svc = nullptr;
316 
317     switch (function.target) {
318         case ControlTarget::SERVICE:
319             svc = ServiceList::GetInstance().FindService(name);
320             break;
321         case ControlTarget::INTERFACE:
322             svc = ServiceList::GetInstance().FindInterface(name);
323             break;
324         default:
325             LOG(ERROR) << "Invalid function target from static map key ctl." << msg << ": "
326                        << static_cast<std::underlying_type<ControlTarget>::type>(function.target);
327             return false;
328     }
329 
330     if (svc == nullptr) {
331         LOG(ERROR) << "Control message: Could not find '" << name << "' for ctl." << msg
332                    << " from pid: " << pid << " (" << process_cmdline << ")";
333         return false;
334     }
335 
336     if (auto result = function.action(svc); !result) {
337         LOG(ERROR) << "Control message: Could not ctl." << msg << " for '" << name
338                    << "' from pid: " << pid << " (" << process_cmdline << "): " << result.error();
339         return false;
340     }
341 
342     LOG(INFO) << "Control message: Processed ctl." << msg << " for '" << name
343               << "' from pid: " << pid << " (" << process_cmdline << ")";
344     return true;
345 }
346 
wait_for_coldboot_done_action(const BuiltinArguments & args)347 static Result<void> wait_for_coldboot_done_action(const BuiltinArguments& args) {
348     if (!start_waiting_for_property(kColdBootDoneProp, "true")) {
349         LOG(FATAL) << "Could not wait for '" << kColdBootDoneProp << "'";
350     }
351 
352     return {};
353 }
354 
SetupCgroupsAction(const BuiltinArguments &)355 static Result<void> SetupCgroupsAction(const BuiltinArguments&) {
356     // Have to create <CGROUPS_RC_DIR> using make_dir function
357     // for appropriate sepolicy to be set for it
358     make_dir(android::base::Dirname(CGROUPS_RC_PATH), 0711);
359     if (!CgroupSetup()) {
360         return ErrnoError() << "Failed to setup cgroups";
361     }
362 
363     return {};
364 }
365 
import_kernel_nv(const std::string & key,const std::string & value,bool for_emulator)366 static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
367     if (key.empty()) return;
368 
369     if (for_emulator) {
370         // In the emulator, export any kernel option with the "ro.kernel." prefix.
371         property_set("ro.kernel." + key, value);
372         return;
373     }
374 
375     if (key == "qemu") {
376         strlcpy(qemu, value.c_str(), sizeof(qemu));
377     } else if (android::base::StartsWith(key, "androidboot.")) {
378         property_set("ro.boot." + key.substr(12), value);
379     }
380 }
381 
export_oem_lock_status()382 static void export_oem_lock_status() {
383     if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) {
384         return;
385     }
386     import_kernel_cmdline(
387             false, [](const std::string& key, const std::string& value, bool in_qemu) {
388                 if (key == "androidboot.verifiedbootstate") {
389                     property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1");
390                 }
391             });
392 }
393 
export_kernel_boot_props()394 static void export_kernel_boot_props() {
395     constexpr const char* UNSET = "";
396     struct {
397         const char *src_prop;
398         const char *dst_prop;
399         const char *default_value;
400     } prop_map[] = {
401         { "ro.boot.serialno",   "ro.serialno",   UNSET, },
402         { "ro.boot.mode",       "ro.bootmode",   "unknown", },
403         { "ro.boot.baseband",   "ro.baseband",   "unknown", },
404         { "ro.boot.bootloader", "ro.bootloader", "unknown", },
405         { "ro.boot.hardware",   "ro.hardware",   "unknown", },
406         { "ro.boot.revision",   "ro.revision",   "0", },
407     };
408     for (const auto& prop : prop_map) {
409         std::string value = GetProperty(prop.src_prop, prop.default_value);
410         if (value != UNSET)
411             property_set(prop.dst_prop, value);
412     }
413 }
414 
process_kernel_dt()415 static void process_kernel_dt() {
416     if (!is_android_dt_value_expected("compatible", "android,firmware")) {
417         return;
418     }
419 
420     std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(get_android_dt_dir().c_str()), closedir);
421     if (!dir) return;
422 
423     std::string dt_file;
424     struct dirent *dp;
425     while ((dp = readdir(dir.get())) != NULL) {
426         if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) {
427             continue;
428         }
429 
430         std::string file_name = get_android_dt_dir() + dp->d_name;
431 
432         android::base::ReadFileToString(file_name, &dt_file);
433         std::replace(dt_file.begin(), dt_file.end(), ',', '.');
434 
435         property_set("ro.boot."s + dp->d_name, dt_file);
436     }
437 }
438 
process_kernel_cmdline()439 static void process_kernel_cmdline() {
440     // The first pass does the common stuff, and finds if we are in qemu.
441     // The second pass is only necessary for qemu to export all kernel params
442     // as properties.
443     import_kernel_cmdline(false, import_kernel_nv);
444     if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
445 }
446 
property_enable_triggers_action(const BuiltinArguments & args)447 static Result<void> property_enable_triggers_action(const BuiltinArguments& args) {
448     /* Enable property triggers. */
449     property_triggers_enabled = 1;
450     return {};
451 }
452 
queue_property_triggers_action(const BuiltinArguments & args)453 static Result<void> queue_property_triggers_action(const BuiltinArguments& args) {
454     ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
455     ActionManager::GetInstance().QueueAllPropertyActions();
456     return {};
457 }
458 
459 // Set the UDC controller for the ConfigFS USB Gadgets.
460 // Read the UDC controller in use from "/sys/class/udc".
461 // In case of multiple UDC controllers select the first one.
set_usb_controller()462 static void set_usb_controller() {
463     std::unique_ptr<DIR, decltype(&closedir)>dir(opendir("/sys/class/udc"), closedir);
464     if (!dir) return;
465 
466     dirent* dp;
467     while ((dp = readdir(dir.get())) != nullptr) {
468         if (dp->d_name[0] == '.') continue;
469 
470         property_set("sys.usb.controller", dp->d_name);
471         break;
472     }
473 }
474 
HandleSigtermSignal(const signalfd_siginfo & siginfo)475 static void HandleSigtermSignal(const signalfd_siginfo& siginfo) {
476     if (siginfo.ssi_pid != 0) {
477         // Drop any userspace SIGTERM requests.
478         LOG(DEBUG) << "Ignoring SIGTERM from pid " << siginfo.ssi_pid;
479         return;
480     }
481 
482     HandlePowerctlMessage("shutdown,container");
483 }
484 
HandleSignalFd()485 static void HandleSignalFd() {
486     signalfd_siginfo siginfo;
487     ssize_t bytes_read = TEMP_FAILURE_RETRY(read(signal_fd, &siginfo, sizeof(siginfo)));
488     if (bytes_read != sizeof(siginfo)) {
489         PLOG(ERROR) << "Failed to read siginfo from signal_fd";
490         return;
491     }
492 
493     switch (siginfo.ssi_signo) {
494         case SIGCHLD:
495             ReapAnyOutstandingChildren();
496             break;
497         case SIGTERM:
498             HandleSigtermSignal(siginfo);
499             break;
500         default:
501             PLOG(ERROR) << "signal_fd: received unexpected signal " << siginfo.ssi_signo;
502             break;
503     }
504 }
505 
UnblockSignals()506 static void UnblockSignals() {
507     const struct sigaction act { .sa_handler = SIG_DFL };
508     sigaction(SIGCHLD, &act, nullptr);
509 
510     sigset_t mask;
511     sigemptyset(&mask);
512     sigaddset(&mask, SIGCHLD);
513     sigaddset(&mask, SIGTERM);
514 
515     if (sigprocmask(SIG_UNBLOCK, &mask, nullptr) == -1) {
516         PLOG(FATAL) << "failed to unblock signals for PID " << getpid();
517     }
518 }
519 
InstallSignalFdHandler(Epoll * epoll)520 static void InstallSignalFdHandler(Epoll* epoll) {
521     // Applying SA_NOCLDSTOP to a defaulted SIGCHLD handler prevents the signalfd from receiving
522     // SIGCHLD when a child process stops or continues (b/77867680#comment9).
523     const struct sigaction act { .sa_handler = SIG_DFL, .sa_flags = SA_NOCLDSTOP };
524     sigaction(SIGCHLD, &act, nullptr);
525 
526     sigset_t mask;
527     sigemptyset(&mask);
528     sigaddset(&mask, SIGCHLD);
529 
530     if (!IsRebootCapable()) {
531         // If init does not have the CAP_SYS_BOOT capability, it is running in a container.
532         // In that case, receiving SIGTERM will cause the system to shut down.
533         sigaddset(&mask, SIGTERM);
534     }
535 
536     if (sigprocmask(SIG_BLOCK, &mask, nullptr) == -1) {
537         PLOG(FATAL) << "failed to block signals";
538     }
539 
540     // Register a handler to unblock signals in the child processes.
541     const int result = pthread_atfork(nullptr, nullptr, &UnblockSignals);
542     if (result != 0) {
543         LOG(FATAL) << "Failed to register a fork handler: " << strerror(result);
544     }
545 
546     signal_fd = signalfd(-1, &mask, SFD_CLOEXEC);
547     if (signal_fd == -1) {
548         PLOG(FATAL) << "failed to create signalfd";
549     }
550 
551     if (auto result = epoll->RegisterHandler(signal_fd, HandleSignalFd); !result) {
552         LOG(FATAL) << result.error();
553     }
554 }
555 
HandleKeychord(const std::vector<int> & keycodes)556 void HandleKeychord(const std::vector<int>& keycodes) {
557     // Only handle keychords if adb is enabled.
558     std::string adb_enabled = android::base::GetProperty("init.svc.adbd", "");
559     if (adb_enabled != "running") {
560         LOG(WARNING) << "Not starting service for keychord " << android::base::Join(keycodes, ' ')
561                      << " because ADB is disabled";
562         return;
563     }
564 
565     auto found = false;
566     for (const auto& service : ServiceList::GetInstance()) {
567         auto svc = service.get();
568         if (svc->keycodes() == keycodes) {
569             found = true;
570             LOG(INFO) << "Starting service '" << svc->name() << "' from keychord "
571                       << android::base::Join(keycodes, ' ');
572             if (auto result = svc->Start(); !result) {
573                 LOG(ERROR) << "Could not start service '" << svc->name() << "' from keychord "
574                            << android::base::Join(keycodes, ' ') << ": " << result.error();
575             }
576         }
577     }
578     if (!found) {
579         LOG(ERROR) << "Service for keychord " << android::base::Join(keycodes, ' ') << " not found";
580     }
581 }
582 
UmountDebugRamdisk()583 static void UmountDebugRamdisk() {
584     if (umount("/debug_ramdisk") != 0) {
585         LOG(ERROR) << "Failed to umount /debug_ramdisk";
586     }
587 }
588 
RecordStageBoottimes(const boot_clock::time_point & second_stage_start_time)589 static void RecordStageBoottimes(const boot_clock::time_point& second_stage_start_time) {
590     int64_t first_stage_start_time_ns = -1;
591     if (auto first_stage_start_time_str = getenv(kEnvFirstStageStartedAt);
592         first_stage_start_time_str) {
593         property_set("ro.boottime.init", first_stage_start_time_str);
594         android::base::ParseInt(first_stage_start_time_str, &first_stage_start_time_ns);
595     }
596     unsetenv(kEnvFirstStageStartedAt);
597 
598     int64_t selinux_start_time_ns = -1;
599     if (auto selinux_start_time_str = getenv(kEnvSelinuxStartedAt); selinux_start_time_str) {
600         android::base::ParseInt(selinux_start_time_str, &selinux_start_time_ns);
601     }
602     unsetenv(kEnvSelinuxStartedAt);
603 
604     if (selinux_start_time_ns == -1) return;
605     if (first_stage_start_time_ns == -1) return;
606 
607     property_set("ro.boottime.init.first_stage",
608                  std::to_string(selinux_start_time_ns - first_stage_start_time_ns));
609     property_set("ro.boottime.init.selinux",
610                  std::to_string(second_stage_start_time.time_since_epoch().count() -
611                                 selinux_start_time_ns));
612 }
613 
SendLoadPersistentPropertiesMessage()614 void SendLoadPersistentPropertiesMessage() {
615     auto init_message = InitMessage{};
616     init_message.set_load_persistent_properties(true);
617     if (auto result = SendMessage(property_fd, init_message); !result) {
618         LOG(ERROR) << "Failed to send load persistent properties message: " << result.error();
619     }
620 }
621 
SendStopSendingMessagesMessage()622 void SendStopSendingMessagesMessage() {
623     auto init_message = InitMessage{};
624     init_message.set_stop_sending_messages(true);
625     if (auto result = SendMessage(property_fd, init_message); !result) {
626         LOG(ERROR) << "Failed to send 'stop sending messages' message: " << result.error();
627     }
628 }
629 
SendStartSendingMessagesMessage()630 void SendStartSendingMessagesMessage() {
631     auto init_message = InitMessage{};
632     init_message.set_start_sending_messages(true);
633     if (auto result = SendMessage(property_fd, init_message); !result) {
634         LOG(ERROR) << "Failed to send 'start sending messages' message: " << result.error();
635     }
636 }
637 
HandlePropertyFd()638 static void HandlePropertyFd() {
639     auto message = ReadMessage(property_fd);
640     if (!message) {
641         LOG(ERROR) << "Could not read message from property service: " << message.error();
642         return;
643     }
644 
645     auto property_message = PropertyMessage{};
646     if (!property_message.ParseFromString(*message)) {
647         LOG(ERROR) << "Could not parse message from property service";
648         return;
649     }
650 
651     switch (property_message.msg_case()) {
652         case PropertyMessage::kControlMessage: {
653             auto& control_message = property_message.control_message();
654             bool success = HandleControlMessage(control_message.msg(), control_message.name(),
655                                                 control_message.pid());
656 
657             uint32_t response = success ? PROP_SUCCESS : PROP_ERROR_HANDLE_CONTROL_MESSAGE;
658             if (control_message.has_fd()) {
659                 int fd = control_message.fd();
660                 TEMP_FAILURE_RETRY(send(fd, &response, sizeof(response), 0));
661                 close(fd);
662             }
663             break;
664         }
665         case PropertyMessage::kChangedMessage: {
666             auto& changed_message = property_message.changed_message();
667             property_changed(changed_message.name(), changed_message.value());
668             break;
669         }
670         default:
671             LOG(ERROR) << "Unknown message type from property service: "
672                        << property_message.msg_case();
673     }
674 }
675 
SecondStageMain(int argc,char ** argv)676 int SecondStageMain(int argc, char** argv) {
677     if (REBOOT_BOOTLOADER_ON_PANIC) {
678         InstallRebootSignalHandlers();
679     }
680 
681     boot_clock::time_point start_time = boot_clock::now();
682 
683     SetStdioToDevNull(argv);
684     InitKernelLogging(argv);
685     LOG(INFO) << "init second stage started!";
686 
687     // Set init and its forked children's oom_adj.
688     if (auto result = WriteFile("/proc/1/oom_score_adj", "-1000"); !result) {
689         LOG(ERROR) << "Unable to write -1000 to /proc/1/oom_score_adj: " << result.error();
690     }
691 
692     // Set up a session keyring that all processes will have access to. It
693     // will hold things like FBE encryption keys. No process should override
694     // its session keyring.
695     keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 1);
696 
697     // Indicate that booting is in progress to background fw loaders, etc.
698     close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
699 
700     property_init();
701 
702     // If arguments are passed both on the command line and in DT,
703     // properties set in DT always have priority over the command-line ones.
704     process_kernel_dt();
705     process_kernel_cmdline();
706 
707     // Propagate the kernel variables to internal variables
708     // used by init as well as the current required properties.
709     export_kernel_boot_props();
710 
711     // Make the time that init stages started available for bootstat to log.
712     RecordStageBoottimes(start_time);
713 
714     // Set libavb version for Framework-only OTA match in Treble build.
715     const char* avb_version = getenv("INIT_AVB_VERSION");
716     if (avb_version) property_set("ro.boot.avb_version", avb_version);
717 
718     // See if need to load debug props to allow adb root, when the device is unlocked.
719     const char* force_debuggable_env = getenv("INIT_FORCE_DEBUGGABLE");
720     if (force_debuggable_env && AvbHandle::IsDeviceUnlocked()) {
721         load_debug_prop = "true"s == force_debuggable_env;
722     }
723 
724     // Clean up our environment.
725     unsetenv("INIT_AVB_VERSION");
726     unsetenv("INIT_FORCE_DEBUGGABLE");
727 
728     // Now set up SELinux for second stage.
729     SelinuxSetupKernelLogging();
730     SelabelInitialize();
731     SelinuxRestoreContext();
732 
733     Epoll epoll;
734     if (auto result = epoll.Open(); !result) {
735         PLOG(FATAL) << result.error();
736     }
737 
738     InstallSignalFdHandler(&epoll);
739 
740     property_load_boot_defaults(load_debug_prop);
741     UmountDebugRamdisk();
742     fs_mgr_vendor_overlay_mount_all();
743     export_oem_lock_status();
744 
745     StartPropertyService(&property_fd);
746     if (auto result = epoll.RegisterHandler(property_fd, HandlePropertyFd); !result) {
747         LOG(FATAL) << "Could not register epoll handler for property fd: " << result.error();
748     }
749 
750     MountHandler mount_handler(&epoll);
751     set_usb_controller();
752 
753     const BuiltinFunctionMap& function_map = GetBuiltinFunctionMap();
754     Action::set_function_map(&function_map);
755 
756     if (!SetupMountNamespaces()) {
757         PLOG(FATAL) << "SetupMountNamespaces failed";
758     }
759 
760     subcontext = InitializeSubcontext();
761 
762     ActionManager& am = ActionManager::GetInstance();
763     ServiceList& sm = ServiceList::GetInstance();
764 
765     LoadBootScripts(am, sm);
766 
767     // Turning this on and letting the INFO logging be discarded adds 0.2s to
768     // Nexus 9 boot time, so it's disabled by default.
769     if (false) DumpState();
770 
771     // Make the GSI status available before scripts start running.
772     if (android::gsi::IsGsiRunning()) {
773         property_set("ro.gsid.image_running", "1");
774     } else {
775         property_set("ro.gsid.image_running", "0");
776     }
777 
778     am.QueueBuiltinAction(SetupCgroupsAction, "SetupCgroups");
779 
780     am.QueueBuiltinAction(SetKptrRestrictAction, "SetKptrRestrict");
781     am.QueueEventTrigger("early-init");
782 
783     // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
784     am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
785     // ... so that we can start queuing up actions that require stuff from /dev.
786     am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
787     am.QueueBuiltinAction(SetMmapRndBitsAction, "SetMmapRndBits");
788     Keychords keychords;
789     am.QueueBuiltinAction(
790             [&epoll, &keychords](const BuiltinArguments& args) -> Result<void> {
791                 for (const auto& svc : ServiceList::GetInstance()) {
792                     keychords.Register(svc->keycodes());
793                 }
794                 keychords.Start(&epoll, HandleKeychord);
795                 return {};
796             },
797             "KeychordInit");
798 
799     // Trigger all the boot actions to get us started.
800     am.QueueEventTrigger("init");
801 
802     // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
803     // wasn't ready immediately after wait_for_coldboot_done
804     am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng");
805 
806     // Don't mount filesystems or start core system services in charger mode.
807     std::string bootmode = GetProperty("ro.bootmode", "");
808     if (bootmode == "charger") {
809         am.QueueEventTrigger("charger");
810     } else {
811         am.QueueEventTrigger("late-init");
812     }
813 
814     // Run all property triggers based on current state of the properties.
815     am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
816 
817     while (true) {
818         // By default, sleep until something happens.
819         auto epoll_timeout = std::optional<std::chrono::milliseconds>{};
820 
821         if (do_shutdown && !IsShuttingDown()) {
822             do_shutdown = false;
823             HandlePowerctlMessage(shutdown_command);
824         }
825 
826         if (!(waiting_for_prop || Service::is_exec_service_running())) {
827             am.ExecuteOneCommand();
828         }
829         if (!(waiting_for_prop || Service::is_exec_service_running())) {
830             if (!IsShuttingDown()) {
831                 auto next_process_action_time = HandleProcessActions();
832 
833                 // If there's a process that needs restarting, wake up in time for that.
834                 if (next_process_action_time) {
835                     epoll_timeout = std::chrono::ceil<std::chrono::milliseconds>(
836                             *next_process_action_time - boot_clock::now());
837                     if (*epoll_timeout < 0ms) epoll_timeout = 0ms;
838                 }
839             }
840 
841             // If there's more work to do, wake up again immediately.
842             if (am.HasMoreCommands()) epoll_timeout = 0ms;
843         }
844 
845         auto pending_functions = epoll.Wait(epoll_timeout);
846         if (!pending_functions) {
847             LOG(ERROR) << pending_functions.error();
848         } else if (!pending_functions->empty()) {
849             // We always reap children before responding to the other pending functions. This is to
850             // prevent a race where other daemons see that a service has exited and ask init to
851             // start it again via ctl.start before init has reaped it.
852             ReapAnyOutstandingChildren();
853             for (const auto& function : *pending_functions) {
854                 (*function)();
855             }
856         }
857     }
858 
859     return 0;
860 }
861 
862 }  // namespace init
863 }  // namespace android
864