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 "util.h"
18 
19 #include <ctype.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <pwd.h>
23 #include <signal.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/socket.h>
29 #include <sys/un.h>
30 #include <time.h>
31 #include <unistd.h>
32 
33 #include <mutex>
34 #include <thread>
35 #include <vector>
36 
37 #include <android-base/file.h>
38 #include <android-base/logging.h>
39 #include <android-base/properties.h>
40 #include <android-base/scopeguard.h>
41 #include <android-base/strings.h>
42 #include <android-base/unique_fd.h>
43 #include <cutils/sockets.h>
44 #include <selinux/android.h>
45 
46 #ifdef INIT_FULL_SOURCES
47 #include <android/api-level.h>
48 #include <sys/system_properties.h>
49 
50 #include "reboot_utils.h"
51 #include "selabel.h"
52 #include "selinux.h"
53 #else
54 #include "host_init_stubs.h"
55 #endif
56 
57 using android::base::boot_clock;
58 using android::base::StartsWith;
59 using namespace std::literals::string_literals;
60 
61 namespace android {
62 namespace init {
63 
64 const std::string kDefaultAndroidDtDir("/proc/device-tree/firmware/android/");
65 
66 void (*trigger_shutdown)(const std::string& command) = nullptr;
67 
68 // DecodeUid() - decodes and returns the given string, which can be either the
69 // numeric or name representation, into the integer uid or gid.
DecodeUid(const std::string & name)70 Result<uid_t> DecodeUid(const std::string& name) {
71     if (isalpha(name[0])) {
72         passwd* pwd = getpwnam(name.c_str());
73         if (!pwd) return ErrnoError() << "getpwnam failed";
74 
75         return pwd->pw_uid;
76     }
77 
78     errno = 0;
79     uid_t result = static_cast<uid_t>(strtoul(name.c_str(), 0, 0));
80     if (errno) return ErrnoError() << "strtoul failed";
81 
82     return result;
83 }
84 
85 /*
86  * CreateSocket - creates a Unix domain socket in ANDROID_SOCKET_DIR
87  * ("/dev/socket") as dictated in init.rc. This socket is inherited by the
88  * daemon. We communicate the file descriptor's value via the environment
89  * variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo").
90  */
CreateSocket(const std::string & name,int type,bool passcred,mode_t perm,uid_t uid,gid_t gid,const std::string & socketcon)91 Result<int> CreateSocket(const std::string& name, int type, bool passcred, mode_t perm, uid_t uid,
92                          gid_t gid, const std::string& socketcon) {
93     if (!socketcon.empty()) {
94         if (setsockcreatecon(socketcon.c_str()) == -1) {
95             return ErrnoError() << "setsockcreatecon(\"" << socketcon << "\") failed";
96         }
97     }
98 
99     android::base::unique_fd fd(socket(PF_UNIX, type, 0));
100     if (fd < 0) {
101         return ErrnoError() << "Failed to open socket '" << name << "'";
102     }
103 
104     if (!socketcon.empty()) setsockcreatecon(nullptr);
105 
106     struct sockaddr_un addr;
107     memset(&addr, 0 , sizeof(addr));
108     addr.sun_family = AF_UNIX;
109     snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR "/%s", name.c_str());
110 
111     if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) {
112         return ErrnoError() << "Failed to unlink old socket '" << name << "'";
113     }
114 
115     std::string secontext;
116     if (SelabelLookupFileContext(addr.sun_path, S_IFSOCK, &secontext) && !secontext.empty()) {
117         setfscreatecon(secontext.c_str());
118     }
119 
120     if (passcred) {
121         int on = 1;
122         if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on))) {
123             return ErrnoError() << "Failed to set SO_PASSCRED '" << name << "'";
124         }
125     }
126 
127     int ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr));
128     int savederrno = errno;
129 
130     if (!secontext.empty()) {
131         setfscreatecon(nullptr);
132     }
133 
134     auto guard = android::base::make_scope_guard([&addr] { unlink(addr.sun_path); });
135 
136     if (ret) {
137         errno = savederrno;
138         return ErrnoError() << "Failed to bind socket '" << name << "'";
139     }
140 
141     if (lchown(addr.sun_path, uid, gid)) {
142         return ErrnoError() << "Failed to lchown socket '" << addr.sun_path << "'";
143     }
144     if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) {
145         return ErrnoError() << "Failed to fchmodat socket '" << addr.sun_path << "'";
146     }
147 
148     LOG(INFO) << "Created socket '" << addr.sun_path << "'"
149               << ", mode " << std::oct << perm << std::dec
150               << ", user " << uid
151               << ", group " << gid;
152 
153     guard.Disable();
154     return fd.release();
155 }
156 
ReadFile(const std::string & path)157 Result<std::string> ReadFile(const std::string& path) {
158     android::base::unique_fd fd(
159         TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
160     if (fd == -1) {
161         return ErrnoError() << "open() failed";
162     }
163 
164     // For security reasons, disallow world-writable
165     // or group-writable files.
166     struct stat sb;
167     if (fstat(fd, &sb) == -1) {
168         return ErrnoError() << "fstat failed()";
169     }
170     if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
171         return Error() << "Skipping insecure file";
172     }
173 
174     std::string content;
175     if (!android::base::ReadFdToString(fd, &content)) {
176         return ErrnoError() << "Unable to read file contents";
177     }
178     return content;
179 }
180 
OpenFile(const std::string & path,int flags,mode_t mode)181 static int OpenFile(const std::string& path, int flags, mode_t mode) {
182     std::string secontext;
183     if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) {
184         setfscreatecon(secontext.c_str());
185     }
186 
187     int rc = open(path.c_str(), flags, mode);
188 
189     if (!secontext.empty()) {
190         int save_errno = errno;
191         setfscreatecon(nullptr);
192         errno = save_errno;
193     }
194 
195     return rc;
196 }
197 
WriteFile(const std::string & path,const std::string & content)198 Result<void> WriteFile(const std::string& path, const std::string& content) {
199     android::base::unique_fd fd(TEMP_FAILURE_RETRY(
200         OpenFile(path, O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
201     if (fd == -1) {
202         return ErrnoError() << "open() failed";
203     }
204     if (!android::base::WriteStringToFd(content, fd)) {
205         return ErrnoError() << "Unable to write file contents";
206     }
207     return {};
208 }
209 
mkdir_recursive(const std::string & path,mode_t mode)210 bool mkdir_recursive(const std::string& path, mode_t mode) {
211     std::string::size_type slash = 0;
212     while ((slash = path.find('/', slash + 1)) != std::string::npos) {
213         auto directory = path.substr(0, slash);
214         struct stat info;
215         if (stat(directory.c_str(), &info) != 0) {
216             auto ret = make_dir(directory, mode);
217             if (!ret && errno != EEXIST) return false;
218         }
219     }
220     auto ret = make_dir(path, mode);
221     if (!ret && errno != EEXIST) return false;
222     return true;
223 }
224 
wait_for_file(const char * filename,std::chrono::nanoseconds timeout)225 int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) {
226     android::base::Timer t;
227     while (t.duration() < timeout) {
228         struct stat sb;
229         if (stat(filename, &sb) != -1) {
230             LOG(INFO) << "wait for '" << filename << "' took " << t;
231             return 0;
232         }
233         std::this_thread::sleep_for(10ms);
234     }
235     LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
236     return -1;
237 }
238 
ImportKernelCmdline(const std::function<void (const std::string &,const std::string &)> & fn)239 void ImportKernelCmdline(const std::function<void(const std::string&, const std::string&)>& fn) {
240     std::string cmdline;
241     android::base::ReadFileToString("/proc/cmdline", &cmdline);
242 
243     for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) {
244         std::vector<std::string> pieces = android::base::Split(entry, "=");
245         if (pieces.size() == 2) {
246             fn(pieces[0], pieces[1]);
247         }
248     }
249 }
250 
make_dir(const std::string & path,mode_t mode)251 bool make_dir(const std::string& path, mode_t mode) {
252     std::string secontext;
253     if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) {
254         setfscreatecon(secontext.c_str());
255     }
256 
257     int rc = mkdir(path.c_str(), mode);
258 
259     if (!secontext.empty()) {
260         int save_errno = errno;
261         setfscreatecon(nullptr);
262         errno = save_errno;
263     }
264 
265     return rc == 0;
266 }
267 
268 /*
269  * Returns true is pathname is a directory
270  */
is_dir(const char * pathname)271 bool is_dir(const char* pathname) {
272     struct stat info;
273     if (stat(pathname, &info) == -1) {
274         return false;
275     }
276     return S_ISDIR(info.st_mode);
277 }
278 
ExpandProps(const std::string & src)279 Result<std::string> ExpandProps(const std::string& src) {
280     const char* src_ptr = src.c_str();
281 
282     std::string dst;
283 
284     /* - variables can either be $x.y or ${x.y}, in case they are only part
285      *   of the string.
286      * - will accept $$ as a literal $.
287      * - no nested property expansion, i.e. ${foo.${bar}} is not supported,
288      *   bad things will happen
289      * - ${x.y:-default} will return default value if property empty.
290      */
291     while (*src_ptr) {
292         const char* c;
293 
294         c = strchr(src_ptr, '$');
295         if (!c) {
296             dst.append(src_ptr);
297             return dst;
298         }
299 
300         dst.append(src_ptr, c);
301         c++;
302 
303         if (*c == '$') {
304             dst.push_back(*(c++));
305             src_ptr = c;
306             continue;
307         } else if (*c == '\0') {
308             return dst;
309         }
310 
311         std::string prop_name;
312         std::string def_val;
313         if (*c == '{') {
314             c++;
315             const char* end = strchr(c, '}');
316             if (!end) {
317                 // failed to find closing brace, abort.
318                 return Error() << "unexpected end of string in '" << src << "', looking for }";
319             }
320             prop_name = std::string(c, end);
321             c = end + 1;
322             size_t def = prop_name.find(":-");
323             if (def < prop_name.size()) {
324                 def_val = prop_name.substr(def + 2);
325                 prop_name = prop_name.substr(0, def);
326             }
327         } else {
328             prop_name = c;
329             if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
330                 return Error() << "using deprecated syntax for specifying property '" << c
331                                << "', use ${name} instead";
332             } else {
333                 LOG(ERROR) << "using deprecated syntax for specifying property '" << c
334                            << "', use ${name} instead";
335             }
336             c += prop_name.size();
337         }
338 
339         if (prop_name.empty()) {
340             return Error() << "invalid zero-length property name in '" << src << "'";
341         }
342 
343         std::string prop_val = android::base::GetProperty(prop_name, "");
344         if (prop_val.empty()) {
345             if (def_val.empty()) {
346                 return Error() << "property '" << prop_name << "' doesn't exist while expanding '"
347                                << src << "'";
348             }
349             prop_val = def_val;
350         }
351 
352         dst.append(prop_val);
353         src_ptr = c;
354     }
355 
356     return dst;
357 }
358 
init_android_dt_dir()359 static std::string init_android_dt_dir() {
360     // Use the standard procfs-based path by default
361     std::string android_dt_dir = kDefaultAndroidDtDir;
362     // The platform may specify a custom Android DT path in kernel cmdline
363     ImportKernelCmdline([&](const std::string& key, const std::string& value) {
364         if (key == "androidboot.android_dt_dir") {
365             android_dt_dir = value;
366         }
367     });
368     LOG(INFO) << "Using Android DT directory " << android_dt_dir;
369     return android_dt_dir;
370 }
371 
372 // FIXME: The same logic is duplicated in system/core/fs_mgr/
get_android_dt_dir()373 const std::string& get_android_dt_dir() {
374     // Set once and saves time for subsequent calls to this function
375     static const std::string kAndroidDtDir = init_android_dt_dir();
376     return kAndroidDtDir;
377 }
378 
379 // Reads the content of device tree file under the platform's Android DT directory.
380 // Returns true if the read is success, false otherwise.
read_android_dt_file(const std::string & sub_path,std::string * dt_content)381 bool read_android_dt_file(const std::string& sub_path, std::string* dt_content) {
382     const std::string file_name = get_android_dt_dir() + sub_path;
383     if (android::base::ReadFileToString(file_name, dt_content)) {
384         if (!dt_content->empty()) {
385             dt_content->pop_back();  // Trims the trailing '\0' out.
386             return true;
387         }
388     }
389     return false;
390 }
391 
is_android_dt_value_expected(const std::string & sub_path,const std::string & expected_content)392 bool is_android_dt_value_expected(const std::string& sub_path, const std::string& expected_content) {
393     std::string dt_content;
394     if (read_android_dt_file(sub_path, &dt_content)) {
395         if (dt_content == expected_content) {
396             return true;
397         }
398     }
399     return false;
400 }
401 
IsLegalPropertyName(const std::string & name)402 bool IsLegalPropertyName(const std::string& name) {
403     size_t namelen = name.size();
404 
405     if (namelen < 1) return false;
406     if (name[0] == '.') return false;
407     if (name[namelen - 1] == '.') return false;
408 
409     /* Only allow alphanumeric, plus '.', '-', '@', ':', or '_' */
410     /* Don't allow ".." to appear in a property name */
411     for (size_t i = 0; i < namelen; i++) {
412         if (name[i] == '.') {
413             // i=0 is guaranteed to never have a dot. See above.
414             if (name[i - 1] == '.') return false;
415             continue;
416         }
417         if (name[i] == '_' || name[i] == '-' || name[i] == '@' || name[i] == ':') continue;
418         if (name[i] >= 'a' && name[i] <= 'z') continue;
419         if (name[i] >= 'A' && name[i] <= 'Z') continue;
420         if (name[i] >= '0' && name[i] <= '9') continue;
421         return false;
422     }
423 
424     return true;
425 }
426 
IsLegalPropertyValue(const std::string & name,const std::string & value)427 Result<void> IsLegalPropertyValue(const std::string& name, const std::string& value) {
428     if (value.size() >= PROP_VALUE_MAX && !StartsWith(name, "ro.")) {
429         return Error() << "Property value too long";
430     }
431 
432     if (mbstowcs(nullptr, value.data(), 0) == static_cast<std::size_t>(-1)) {
433         return Error() << "Value is not a UTF8 encoded string";
434     }
435 
436     return {};
437 }
438 
FscryptInferAction(const std::string & dir)439 static FscryptAction FscryptInferAction(const std::string& dir) {
440     const std::string prefix = "/data/";
441 
442     if (!android::base::StartsWith(dir, prefix)) {
443         return FscryptAction::kNone;
444     }
445 
446     // Special-case /data/media/obb per b/64566063
447     if (dir == "/data/media/obb") {
448         // Try to set policy on this directory, but if it is non-empty this may fail.
449         return FscryptAction::kAttempt;
450     }
451 
452     // Only set policy on first level /data directories
453     // To make this less restrictive, consider using a policy file.
454     // However this is overkill for as long as the policy is simply
455     // to apply a global policy to all /data folders created via makedir
456     if (dir.find_first_of('/', prefix.size()) != std::string::npos) {
457         return FscryptAction::kNone;
458     }
459 
460     // Special case various directories that must not be encrypted,
461     // often because their subdirectories must be encrypted.
462     // This isn't a nice way to do this, see b/26641735
463     std::vector<std::string> directories_to_exclude = {
464             "lost+found", "system_ce", "system_de", "misc_ce",     "misc_de",
465             "vendor_ce",  "vendor_de", "media",     "data",        "user",
466             "user_de",    "apex",      "preloads",  "app-staging", "gsi",
467     };
468     for (const auto& d : directories_to_exclude) {
469         if ((prefix + d) == dir) {
470             return FscryptAction::kNone;
471         }
472     }
473     // Empty these directories if policy setting fails.
474     std::vector<std::string> wipe_on_failure = {
475             "rollback", "rollback-observer",  // b/139193659
476     };
477     for (const auto& d : wipe_on_failure) {
478         if ((prefix + d) == dir) {
479             return FscryptAction::kDeleteIfNecessary;
480         }
481     }
482     return FscryptAction::kRequire;
483 }
484 
ParseMkdir(const std::vector<std::string> & args)485 Result<MkdirOptions> ParseMkdir(const std::vector<std::string>& args) {
486     mode_t mode = 0755;
487     Result<uid_t> uid = -1;
488     Result<gid_t> gid = -1;
489     FscryptAction fscrypt_inferred_action = FscryptInferAction(args[1]);
490     FscryptAction fscrypt_action = fscrypt_inferred_action;
491     std::string ref_option = "ref";
492     bool set_option_encryption = false;
493     bool set_option_key = false;
494 
495     for (size_t i = 2; i < args.size(); i++) {
496         switch (i) {
497             case 2:
498                 mode = std::strtoul(args[2].c_str(), 0, 8);
499                 break;
500             case 3:
501                 uid = DecodeUid(args[3]);
502                 if (!uid.ok()) {
503                     return Error()
504                            << "Unable to decode UID for '" << args[3] << "': " << uid.error();
505                 }
506                 break;
507             case 4:
508                 gid = DecodeUid(args[4]);
509                 if (!gid.ok()) {
510                     return Error()
511                            << "Unable to decode GID for '" << args[4] << "': " << gid.error();
512                 }
513                 break;
514             default:
515                 auto parts = android::base::Split(args[i], "=");
516                 if (parts.size() != 2) {
517                     return Error() << "Can't parse option: '" << args[i] << "'";
518                 }
519                 auto optname = parts[0];
520                 auto optval = parts[1];
521                 if (optname == "encryption") {
522                     if (set_option_encryption) {
523                         return Error() << "Duplicated option: '" << optname << "'";
524                     }
525                     if (optval == "Require") {
526                         fscrypt_action = FscryptAction::kRequire;
527                     } else if (optval == "None") {
528                         fscrypt_action = FscryptAction::kNone;
529                     } else if (optval == "Attempt") {
530                         fscrypt_action = FscryptAction::kAttempt;
531                     } else if (optval == "DeleteIfNecessary") {
532                         fscrypt_action = FscryptAction::kDeleteIfNecessary;
533                     } else {
534                         return Error() << "Unknown encryption option: '" << optval << "'";
535                     }
536                     set_option_encryption = true;
537                 } else if (optname == "key") {
538                     if (set_option_key) {
539                         return Error() << "Duplicated option: '" << optname << "'";
540                     }
541                     if (optval == "ref" || optval == "per_boot_ref") {
542                         ref_option = optval;
543                     } else {
544                         return Error() << "Unknown key option: '" << optval << "'";
545                     }
546                     set_option_key = true;
547                 } else {
548                     return Error() << "Unknown option: '" << args[i] << "'";
549                 }
550         }
551     }
552     if (set_option_key && fscrypt_action == FscryptAction::kNone) {
553         return Error() << "Key option set but encryption action is none";
554     }
555     const std::string prefix = "/data/";
556     if (StartsWith(args[1], prefix) &&
557         args[1].find_first_of('/', prefix.size()) == std::string::npos) {
558         if (!set_option_encryption) {
559             LOG(WARNING) << "Top-level directory needs encryption action, eg mkdir " << args[1]
560                          << " <mode> <uid> <gid> encryption=Require";
561         }
562         if (fscrypt_action == FscryptAction::kNone) {
563             LOG(INFO) << "Not setting encryption policy on: " << args[1];
564         }
565     }
566     if (fscrypt_action != fscrypt_inferred_action) {
567         LOG(WARNING) << "Inferred action different from explicit one, expected "
568                      << static_cast<int>(fscrypt_inferred_action) << " but got "
569                      << static_cast<int>(fscrypt_action);
570     }
571 
572     return MkdirOptions{args[1], mode, *uid, *gid, fscrypt_action, ref_option};
573 }
574 
ParseMountAll(const std::vector<std::string> & args)575 Result<MountAllOptions> ParseMountAll(const std::vector<std::string>& args) {
576     bool compat_mode = false;
577     bool import_rc = false;
578     if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
579         if (args.size() <= 1) {
580             return Error() << "mount_all requires at least 1 argument";
581         }
582         compat_mode = true;
583         import_rc = true;
584     }
585 
586     std::size_t first_option_arg = args.size();
587     enum mount_mode mode = MOUNT_MODE_DEFAULT;
588 
589     // If we are <= Q, then stop looking for non-fstab arguments at slot 2.
590     // Otherwise, stop looking at slot 1 (as the fstab path argument is optional >= R).
591     for (std::size_t na = args.size() - 1; na > (compat_mode ? 1 : 0); --na) {
592         if (args[na] == "--early") {
593             first_option_arg = na;
594             mode = MOUNT_MODE_EARLY;
595         } else if (args[na] == "--late") {
596             first_option_arg = na;
597             mode = MOUNT_MODE_LATE;
598             import_rc = false;
599         }
600     }
601 
602     std::string fstab_path;
603     if (first_option_arg > 1) {
604         fstab_path = args[1];
605     } else if (compat_mode) {
606         return Error() << "mount_all argument 1 must be the fstab path";
607     }
608 
609     std::vector<std::string> rc_paths;
610     for (std::size_t na = 2; na < first_option_arg; ++na) {
611         rc_paths.push_back(args[na]);
612     }
613 
614     return MountAllOptions{rc_paths, fstab_path, mode, import_rc};
615 }
616 
ParseRestorecon(const std::vector<std::string> & args)617 Result<std::pair<int, std::vector<std::string>>> ParseRestorecon(
618         const std::vector<std::string>& args) {
619     struct flag_type {
620         const char* name;
621         int value;
622     };
623     static const flag_type flags[] = {
624             {"--recursive", SELINUX_ANDROID_RESTORECON_RECURSE},
625             {"--skip-ce", SELINUX_ANDROID_RESTORECON_SKIPCE},
626             {"--cross-filesystems", SELINUX_ANDROID_RESTORECON_CROSS_FILESYSTEMS},
627             {0, 0}};
628 
629     int flag = 0;
630     std::vector<std::string> paths;
631 
632     bool in_flags = true;
633     for (size_t i = 1; i < args.size(); ++i) {
634         if (android::base::StartsWith(args[i], "--")) {
635             if (!in_flags) {
636                 return Error() << "flags must precede paths";
637             }
638             bool found = false;
639             for (size_t j = 0; flags[j].name; ++j) {
640                 if (args[i] == flags[j].name) {
641                     flag |= flags[j].value;
642                     found = true;
643                     break;
644                 }
645             }
646             if (!found) {
647                 return Error() << "bad flag " << args[i];
648             }
649         } else {
650             in_flags = false;
651             paths.emplace_back(args[i]);
652         }
653     }
654     return std::pair(flag, paths);
655 }
656 
ParseSwaponAll(const std::vector<std::string> & args)657 Result<std::string> ParseSwaponAll(const std::vector<std::string>& args) {
658     if (args.size() <= 1) {
659         if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
660             return Error() << "swapon_all requires at least 1 argument";
661         }
662         return {};
663     }
664     return args[1];
665 }
666 
ParseUmountAll(const std::vector<std::string> & args)667 Result<std::string> ParseUmountAll(const std::vector<std::string>& args) {
668     if (args.size() <= 1) {
669         if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
670             return Error() << "umount_all requires at least 1 argument";
671         }
672         return {};
673     }
674     return args[1];
675 }
676 
InitAborter(const char * abort_message)677 static void InitAborter(const char* abort_message) {
678     // When init forks, it continues to use this aborter for LOG(FATAL), but we want children to
679     // simply abort instead of trying to reboot the system.
680     if (getpid() != 1) {
681         android::base::DefaultAborter(abort_message);
682         return;
683     }
684 
685     InitFatalReboot(SIGABRT);
686 }
687 
688 // The kernel opens /dev/console and uses that fd for stdin/stdout/stderr if there is a serial
689 // console enabled and no initramfs, otherwise it does not provide any fds for stdin/stdout/stderr.
690 // SetStdioToDevNull() is used to close these existing fds if they exist and replace them with
691 // /dev/null regardless.
692 //
693 // In the case that these fds are provided by the kernel, the exec of second stage init causes an
694 // SELinux denial as it does not have access to /dev/console.  In the case that they are not
695 // provided, exec of any further process is potentially dangerous as the first fd's opened by that
696 // process will take the stdin/stdout/stderr fileno's, which can cause issues if printf(), etc is
697 // then used by that process.
698 //
699 // Lastly, simply calling SetStdioToDevNull() in first stage init is not enough, since first
700 // stage init still runs in kernel context, future child processes will not have permissions to
701 // access any fds that it opens, including the one opened below for /dev/null.  Therefore,
702 // SetStdioToDevNull() must be called again in second stage init.
SetStdioToDevNull(char ** argv)703 void SetStdioToDevNull(char** argv) {
704     // Make stdin/stdout/stderr all point to /dev/null.
705     int fd = open("/dev/null", O_RDWR);  // NOLINT(android-cloexec-open)
706     if (fd == -1) {
707         int saved_errno = errno;
708         android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
709         errno = saved_errno;
710         PLOG(FATAL) << "Couldn't open /dev/null";
711     }
712     dup2(fd, STDIN_FILENO);
713     dup2(fd, STDOUT_FILENO);
714     dup2(fd, STDERR_FILENO);
715     if (fd > STDERR_FILENO) close(fd);
716 }
717 
InitKernelLogging(char ** argv)718 void InitKernelLogging(char** argv) {
719     SetFatalRebootTarget();
720     android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
721 }
722 
IsRecoveryMode()723 bool IsRecoveryMode() {
724     return access("/system/bin/recovery", F_OK) == 0;
725 }
726 
727 // TODO(b/155203339): remove this
728 // Devices in the lab seem to be stuck during shutdown, but the logs don't capture the last actions
729 // before shutdown started, so we record those lines, ignoring requests to shutdown, and replay them
730 // if we identify that the device is stuck.
731 constexpr size_t kRecordedLogsSize = 30;
732 std::string recorded_logs[kRecordedLogsSize];
733 size_t recorded_log_position = 0;
734 std::mutex recorded_logs_lock;
735 
InitSecondStageLogging(char ** argv)736 void InitSecondStageLogging(char** argv) {
737     SetFatalRebootTarget();
738     auto second_stage_logger = [](android::base::LogId log_id, android::base::LogSeverity severity,
739                                   const char* tag, const char* file, unsigned int line,
740                                   const char* message) {
741         // We only store logs for init, not its children, and only if they're not related to
742         // sys.powerctl.
743         if (getpid() == 1 && strstr(message, "sys.powerctl") == nullptr) {
744             auto lock = std::lock_guard{recorded_logs_lock};
745             recorded_logs[recorded_log_position++] = message;
746             if (recorded_log_position == kRecordedLogsSize) {
747                 recorded_log_position = 0;
748             }
749         }
750         android::base::KernelLogger(log_id, severity, tag, file, line, message);
751     };
752     android::base::InitLogging(argv, second_stage_logger, InitAborter);
753 }
754 
DumpShutdownDebugInformation()755 void DumpShutdownDebugInformation() {
756     auto lock = std::lock_guard{recorded_logs_lock};
757     android::base::KernelLogger(
758             android::base::MAIN, android::base::ERROR, "init", nullptr, 0,
759             "===================== Dumping previous init lines =====================");
760     for (size_t i = recorded_log_position; i < kRecordedLogsSize; ++i) {
761         android::base::KernelLogger(android::base::MAIN, android::base::ERROR, "init", nullptr, 0,
762                                     recorded_logs[i].c_str());
763     }
764     for (size_t i = 0; i < recorded_log_position; ++i) {
765         android::base::KernelLogger(android::base::MAIN, android::base::ERROR, "init", nullptr, 0,
766                                     recorded_logs[i].c_str());
767     }
768     android::base::KernelLogger(android::base::MAIN, android::base::ERROR, "init", nullptr, 0,
769                                 "===================== End of dump =====================");
770 }
771 
772 }  // namespace init
773 }  // namespace android
774