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 <sys/wait.h>
31 #include <time.h>
32 #include <unistd.h>
33 
34 #include <map>
35 #include <thread>
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 #if defined(__ANDROID__)
47 #include <fs_mgr.h>
48 #endif
49 
50 #ifdef INIT_FULL_SOURCES
51 #include <android/api-level.h>
52 #include <sys/system_properties.h>
53 
54 #include "reboot_utils.h"
55 #include "selabel.h"
56 #include "selinux.h"
57 #else
58 #include "host_init_stubs.h"
59 #endif
60 
61 using android::base::boot_clock;
62 using android::base::StartsWith;
63 using namespace std::literals::string_literals;
64 
65 namespace android {
66 namespace init {
67 
68 const std::string kDataDirPrefix("/data/");
69 
70 void (*trigger_shutdown)(const std::string& command) = nullptr;
71 
72 // DecodeUid() - decodes and returns the given string, which can be either the
73 // numeric or name representation, into the integer uid or gid.
DecodeUid(const std::string & name)74 Result<uid_t> DecodeUid(const std::string& name) {
75     if (isalpha(name[0])) {
76         passwd* pwd = getpwnam(name.c_str());
77         if (!pwd) return ErrnoError() << "getpwnam failed";
78 
79         return pwd->pw_uid;
80     }
81 
82     errno = 0;
83     uid_t result = static_cast<uid_t>(strtoul(name.c_str(), 0, 0));
84     if (errno) return ErrnoError() << "strtoul failed";
85 
86     return result;
87 }
88 
89 /*
90  * CreateSocket - creates a Unix domain socket in ANDROID_SOCKET_DIR
91  * ("/dev/socket") as dictated in init.rc. This socket is inherited by the
92  * daemon. We communicate the file descriptor's value via the environment
93  * variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo").
94  */
CreateSocket(const std::string & name,int type,bool passcred,bool should_listen,mode_t perm,uid_t uid,gid_t gid,const std::string & socketcon)95 Result<int> CreateSocket(const std::string& name, int type, bool passcred, bool should_listen,
96                          mode_t perm, uid_t uid, gid_t gid, const std::string& socketcon) {
97     if (!socketcon.empty()) {
98         if (setsockcreatecon(socketcon.c_str()) == -1) {
99             return ErrnoError() << "setsockcreatecon(\"" << socketcon << "\") failed";
100         }
101     }
102 
103     android::base::unique_fd fd(socket(PF_UNIX, type, 0));
104     if (fd < 0) {
105         return ErrnoError() << "Failed to open socket '" << name << "'";
106     }
107 
108     if (!socketcon.empty()) setsockcreatecon(nullptr);
109 
110     struct sockaddr_un addr;
111     memset(&addr, 0 , sizeof(addr));
112     addr.sun_family = AF_UNIX;
113     snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR "/%s", name.c_str());
114 
115     if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) {
116         return ErrnoError() << "Failed to unlink old socket '" << name << "'";
117     }
118 
119     std::string secontext;
120     if (SelabelLookupFileContext(addr.sun_path, S_IFSOCK, &secontext) && !secontext.empty()) {
121         setfscreatecon(secontext.c_str());
122     }
123 
124     if (passcred) {
125         int on = 1;
126         if (setsockopt(fd.get(), SOL_SOCKET, SO_PASSCRED, &on, sizeof(on))) {
127             return ErrnoError() << "Failed to set SO_PASSCRED '" << name << "'";
128         }
129     }
130 
131     int ret = bind(fd.get(), (struct sockaddr*)&addr, sizeof(addr));
132     int savederrno = errno;
133 
134     if (!secontext.empty()) {
135         setfscreatecon(nullptr);
136     }
137 
138     auto guard = android::base::make_scope_guard([&addr] { unlink(addr.sun_path); });
139 
140     if (ret) {
141         errno = savederrno;
142         return ErrnoError() << "Failed to bind socket '" << name << "'";
143     }
144 
145     if (lchown(addr.sun_path, uid, gid)) {
146         return ErrnoError() << "Failed to lchown socket '" << addr.sun_path << "'";
147     }
148     if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) {
149         return ErrnoError() << "Failed to fchmodat socket '" << addr.sun_path << "'";
150     }
151     if (should_listen && listen(fd.get(), /* use OS maximum */ 1 << 30)) {
152         return ErrnoError() << "Failed to listen on socket '" << addr.sun_path << "'";
153     }
154 
155     LOG(INFO) << "Created socket '" << addr.sun_path << "'"
156               << ", mode " << std::oct << perm << std::dec
157               << ", user " << uid
158               << ", group " << gid;
159 
160     guard.Disable();
161     return fd.release();
162 }
163 
ReadFile(const std::string & path)164 Result<std::string> ReadFile(const std::string& path) {
165     android::base::unique_fd fd(
166         TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
167     if (fd == -1) {
168         return ErrnoError() << "open() failed";
169     }
170 
171     // For security reasons, disallow world-writable
172     // or group-writable files.
173     struct stat sb;
174     if (fstat(fd.get(), &sb) == -1) {
175         return ErrnoError() << "fstat failed()";
176     }
177     if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
178         return Error() << "Skipping insecure file";
179     }
180 
181     std::string content;
182     if (!android::base::ReadFdToString(fd, &content)) {
183         return ErrnoError() << "Unable to read file contents";
184     }
185     return content;
186 }
187 
OpenFile(const std::string & path,int flags,mode_t mode)188 static int OpenFile(const std::string& path, int flags, mode_t mode) {
189     std::string secontext;
190     if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) {
191         setfscreatecon(secontext.c_str());
192     }
193 
194     int rc = open(path.c_str(), flags, mode);
195 
196     if (!secontext.empty()) {
197         int save_errno = errno;
198         setfscreatecon(nullptr);
199         errno = save_errno;
200     }
201 
202     return rc;
203 }
204 
WriteFile(const std::string & path,const std::string & content)205 Result<void> WriteFile(const std::string& path, const std::string& content) {
206     android::base::unique_fd fd(TEMP_FAILURE_RETRY(
207         OpenFile(path, O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
208     if (fd == -1) {
209         return ErrnoError() << "open() failed";
210     }
211     if (!android::base::WriteStringToFd(content, fd)) {
212         return ErrnoError() << "Unable to write file contents";
213     }
214     return {};
215 }
216 
mkdir_recursive(const std::string & path,mode_t mode)217 bool mkdir_recursive(const std::string& path, mode_t mode) {
218     std::string::size_type slash = 0;
219     while ((slash = path.find('/', slash + 1)) != std::string::npos) {
220         auto directory = path.substr(0, slash);
221         struct stat info;
222         if (stat(directory.c_str(), &info) != 0) {
223             auto ret = make_dir(directory, mode);
224             if (!ret && errno != EEXIST) return false;
225         }
226     }
227     auto ret = make_dir(path, mode);
228     if (!ret && errno != EEXIST) return false;
229     return true;
230 }
231 
wait_for_file(const char * filename,std::chrono::nanoseconds timeout)232 int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) {
233     android::base::Timer t;
234     while (t.duration() < timeout) {
235         struct stat sb;
236         if (stat(filename, &sb) != -1) {
237             LOG(INFO) << "wait for '" << filename << "' took " << t;
238             return 0;
239         }
240         std::this_thread::sleep_for(10ms);
241     }
242     LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
243     return -1;
244 }
245 
make_dir(const std::string & path,mode_t mode)246 bool make_dir(const std::string& path, mode_t mode) {
247     std::string secontext;
248     if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) {
249         setfscreatecon(secontext.c_str());
250     }
251 
252     int rc = mkdir(path.c_str(), mode);
253 
254     if (!secontext.empty()) {
255         int save_errno = errno;
256         setfscreatecon(nullptr);
257         errno = save_errno;
258     }
259 
260     return rc == 0;
261 }
262 
263 /*
264  * Returns true is pathname is a directory
265  */
is_dir(const char * pathname)266 bool is_dir(const char* pathname) {
267     struct stat info;
268     if (stat(pathname, &info) == -1) {
269         return false;
270     }
271     return S_ISDIR(info.st_mode);
272 }
273 
ExpandProps(const std::string & src)274 Result<std::string> ExpandProps(const std::string& src) {
275     const char* src_ptr = src.c_str();
276 
277     std::string dst;
278 
279     /* - variables can either be $x.y or ${x.y}, in case they are only part
280      *   of the string.
281      * - will accept $$ as a literal $.
282      * - no nested property expansion, i.e. ${foo.${bar}} is not supported,
283      *   bad things will happen
284      * - ${x.y:-default} will return default value if property empty.
285      */
286     while (*src_ptr) {
287         const char* c;
288 
289         c = strchr(src_ptr, '$');
290         if (!c) {
291             dst.append(src_ptr);
292             return dst;
293         }
294 
295         dst.append(src_ptr, c);
296         c++;
297 
298         if (*c == '$') {
299             dst.push_back(*(c++));
300             src_ptr = c;
301             continue;
302         } else if (*c == '\0') {
303             return dst;
304         }
305 
306         std::string prop_name;
307         std::string def_val;
308         if (*c == '{') {
309             c++;
310             const char* end = strchr(c, '}');
311             if (!end) {
312                 // failed to find closing brace, abort.
313                 return Error() << "unexpected end of string in '" << src << "', looking for }";
314             }
315             prop_name = std::string(c, end);
316             c = end + 1;
317             size_t def = prop_name.find(":-");
318             if (def < prop_name.size()) {
319                 def_val = prop_name.substr(def + 2);
320                 prop_name = prop_name.substr(0, def);
321             }
322         } else {
323             prop_name = c;
324             if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
325                 return Error() << "using deprecated syntax for specifying property '" << c
326                                << "', use ${name} instead";
327             } else {
328                 LOG(ERROR) << "using deprecated syntax for specifying property '" << c
329                            << "', use ${name} instead";
330             }
331             c += prop_name.size();
332         }
333 
334         if (prop_name.empty()) {
335             return Error() << "invalid zero-length property name in '" << src << "'";
336         }
337 
338         std::string prop_val = android::base::GetProperty(prop_name, "");
339         if (prop_val.empty()) {
340             if (def_val.empty()) {
341                 return Error() << "property '" << prop_name << "' doesn't exist while expanding '"
342                                << src << "'";
343             }
344             prop_val = def_val;
345         }
346 
347         dst.append(prop_val);
348         src_ptr = c;
349     }
350 
351     return dst;
352 }
353 
354 // Reads the content of device tree file under the platform's Android DT directory.
355 // Returns true if the read is success, false otherwise.
read_android_dt_file(const std::string & sub_path,std::string * dt_content)356 bool read_android_dt_file(const std::string& sub_path, std::string* dt_content) {
357 #if defined(__ANDROID__)
358     const std::string file_name = android::fs_mgr::GetAndroidDtDir() + sub_path;
359     if (android::base::ReadFileToString(file_name, dt_content)) {
360         if (!dt_content->empty()) {
361             dt_content->pop_back();  // Trims the trailing '\0' out.
362             return true;
363         }
364     }
365 #endif
366     return false;
367 }
368 
is_android_dt_value_expected(const std::string & sub_path,const std::string & expected_content)369 bool is_android_dt_value_expected(const std::string& sub_path, const std::string& expected_content) {
370     std::string dt_content;
371     if (read_android_dt_file(sub_path, &dt_content)) {
372         if (dt_content == expected_content) {
373             return true;
374         }
375     }
376     return false;
377 }
378 
IsLegalPropertyName(const std::string & name)379 bool IsLegalPropertyName(const std::string& name) {
380     size_t namelen = name.size();
381 
382     if (namelen < 1) return false;
383     if (name[0] == '.') return false;
384     if (name[namelen - 1] == '.') return false;
385 
386     /* Only allow alphanumeric, plus '.', '-', '@', ':', or '_' */
387     /* Don't allow ".." to appear in a property name */
388     for (size_t i = 0; i < namelen; i++) {
389         if (name[i] == '.') {
390             // i=0 is guaranteed to never have a dot. See above.
391             if (name[i - 1] == '.') return false;
392             continue;
393         }
394         if (name[i] == '_' || name[i] == '-' || name[i] == '@' || name[i] == ':') continue;
395         if (name[i] >= 'a' && name[i] <= 'z') continue;
396         if (name[i] >= 'A' && name[i] <= 'Z') continue;
397         if (name[i] >= '0' && name[i] <= '9') continue;
398         return false;
399     }
400 
401     return true;
402 }
403 
IsLegalPropertyValue(const std::string & name,const std::string & value)404 Result<void> IsLegalPropertyValue(const std::string& name, const std::string& value) {
405     if (value.size() >= PROP_VALUE_MAX && !StartsWith(name, "ro.")) {
406         return Error() << "Property value too long";
407     }
408 
409     if (mbstowcs(nullptr, value.data(), 0) == static_cast<std::size_t>(-1)) {
410         return Error() << "Value is not a UTF8 encoded string";
411     }
412 
413     return {};
414 }
415 
416 // Remove unnecessary slashes so that any later checks (e.g., the check for
417 // whether the path is a top-level directory in /data) don't get confused.
CleanDirPath(const std::string & path)418 std::string CleanDirPath(const std::string& path) {
419     std::string result;
420     result.reserve(path.length());
421     // Collapse duplicate slashes, e.g. //data//foo// => /data/foo/
422     for (char c : path) {
423         if (c != '/' || result.empty() || result.back() != '/') {
424             result += c;
425         }
426     }
427     // Remove trailing slash, e.g. /data/foo/ => /data/foo
428     if (result.length() > 1 && result.back() == '/') {
429         result.pop_back();
430     }
431     return result;
432 }
433 
ParseMkdir(const std::vector<std::string> & args)434 Result<MkdirOptions> ParseMkdir(const std::vector<std::string>& args) {
435     std::string path = CleanDirPath(args[1]);
436     const bool is_toplevel_data_dir =
437             StartsWith(path, kDataDirPrefix) &&
438             path.find_first_of('/', kDataDirPrefix.size()) == std::string::npos;
439     FscryptAction fscrypt_action =
440             is_toplevel_data_dir ? FscryptAction::kRequire : FscryptAction::kNone;
441     mode_t mode = 0755;
442     Result<uid_t> uid = -1;
443     Result<gid_t> gid = -1;
444     std::string ref_option = "ref";
445     bool set_option_encryption = false;
446     bool set_option_key = false;
447 
448     for (size_t i = 2; i < args.size(); i++) {
449         switch (i) {
450             case 2:
451                 mode = std::strtoul(args[2].c_str(), 0, 8);
452                 break;
453             case 3:
454                 uid = DecodeUid(args[3]);
455                 if (!uid.ok()) {
456                     return Error()
457                            << "Unable to decode UID for '" << args[3] << "': " << uid.error();
458                 }
459                 break;
460             case 4:
461                 gid = DecodeUid(args[4]);
462                 if (!gid.ok()) {
463                     return Error()
464                            << "Unable to decode GID for '" << args[4] << "': " << gid.error();
465                 }
466                 break;
467             default:
468                 auto parts = android::base::Split(args[i], "=");
469                 if (parts.size() != 2) {
470                     return Error() << "Can't parse option: '" << args[i] << "'";
471                 }
472                 auto optname = parts[0];
473                 auto optval = parts[1];
474                 if (optname == "encryption") {
475                     if (set_option_encryption) {
476                         return Error() << "Duplicated option: '" << optname << "'";
477                     }
478                     if (optval == "Require") {
479                         fscrypt_action = FscryptAction::kRequire;
480                     } else if (optval == "None") {
481                         fscrypt_action = FscryptAction::kNone;
482                     } else if (optval == "Attempt") {
483                         fscrypt_action = FscryptAction::kAttempt;
484                     } else if (optval == "DeleteIfNecessary") {
485                         fscrypt_action = FscryptAction::kDeleteIfNecessary;
486                     } else {
487                         return Error() << "Unknown encryption option: '" << optval << "'";
488                     }
489                     set_option_encryption = true;
490                 } else if (optname == "key") {
491                     if (set_option_key) {
492                         return Error() << "Duplicated option: '" << optname << "'";
493                     }
494                     if (optval == "ref" || optval == "per_boot_ref") {
495                         ref_option = optval;
496                     } else {
497                         return Error() << "Unknown key option: '" << optval << "'";
498                     }
499                     set_option_key = true;
500                 } else {
501                     return Error() << "Unknown option: '" << args[i] << "'";
502                 }
503         }
504     }
505     if (set_option_key && fscrypt_action == FscryptAction::kNone) {
506         return Error() << "Key option set but encryption action is none";
507     }
508     if (is_toplevel_data_dir) {
509         if (!set_option_encryption) {
510             LOG(WARNING) << "Top-level directory needs encryption action, eg mkdir " << path
511                          << " <mode> <uid> <gid> encryption=Require";
512         }
513         if (fscrypt_action == FscryptAction::kNone) {
514             LOG(INFO) << "Not setting encryption policy on: " << path;
515         }
516     }
517 
518     return MkdirOptions{path, mode, *uid, *gid, fscrypt_action, ref_option};
519 }
520 
ParseMountAll(const std::vector<std::string> & args)521 Result<MountAllOptions> ParseMountAll(const std::vector<std::string>& args) {
522     bool compat_mode = false;
523     bool import_rc = false;
524     if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
525         if (args.size() <= 1) {
526             return Error() << "mount_all requires at least 1 argument";
527         }
528         compat_mode = true;
529         import_rc = true;
530     }
531 
532     std::size_t first_option_arg = args.size();
533     enum mount_mode mode = MOUNT_MODE_DEFAULT;
534 
535     // If we are <= Q, then stop looking for non-fstab arguments at slot 2.
536     // Otherwise, stop looking at slot 1 (as the fstab path argument is optional >= R).
537     for (std::size_t na = args.size() - 1; na > (compat_mode ? 1 : 0); --na) {
538         if (args[na] == "--early") {
539             first_option_arg = na;
540             mode = MOUNT_MODE_EARLY;
541         } else if (args[na] == "--late") {
542             first_option_arg = na;
543             mode = MOUNT_MODE_LATE;
544             import_rc = false;
545         }
546     }
547 
548     std::string fstab_path;
549     if (first_option_arg > 1) {
550         fstab_path = args[1];
551     } else if (compat_mode) {
552         return Error() << "mount_all argument 1 must be the fstab path";
553     }
554 
555     std::vector<std::string> rc_paths;
556     for (std::size_t na = 2; na < first_option_arg; ++na) {
557         rc_paths.push_back(args[na]);
558     }
559 
560     return MountAllOptions{rc_paths, fstab_path, mode, import_rc};
561 }
562 
ParseRestorecon(const std::vector<std::string> & args)563 Result<std::pair<int, std::vector<std::string>>> ParseRestorecon(
564         const std::vector<std::string>& args) {
565     struct flag_type {
566         const char* name;
567         int value;
568     };
569     static const flag_type flags[] = {
570             {"--recursive", SELINUX_ANDROID_RESTORECON_RECURSE},
571             {"--skip-ce", SELINUX_ANDROID_RESTORECON_SKIPCE},
572             {"--cross-filesystems", SELINUX_ANDROID_RESTORECON_CROSS_FILESYSTEMS},
573             {"--force", SELINUX_ANDROID_RESTORECON_FORCE},
574             {"--data-data", SELINUX_ANDROID_RESTORECON_DATADATA},
575             {0, 0}};
576 
577     int flag = 0;
578     std::vector<std::string> paths;
579 
580     bool in_flags = true;
581     for (size_t i = 1; i < args.size(); ++i) {
582         if (android::base::StartsWith(args[i], "--")) {
583             if (!in_flags) {
584                 return Error() << "flags must precede paths";
585             }
586             bool found = false;
587             for (size_t j = 0; flags[j].name; ++j) {
588                 if (args[i] == flags[j].name) {
589                     flag |= flags[j].value;
590                     found = true;
591                     break;
592                 }
593             }
594             if (!found) {
595                 return Error() << "bad flag " << args[i];
596             }
597         } else {
598             in_flags = false;
599             paths.emplace_back(args[i]);
600         }
601     }
602     return std::pair(flag, paths);
603 }
604 
ParseSwaponAll(const std::vector<std::string> & args)605 Result<std::string> ParseSwaponAll(const std::vector<std::string>& args) {
606     if (args.size() <= 1) {
607         if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
608             return Error() << "swapon_all requires at least 1 argument";
609         }
610         return {};
611     }
612     return args[1];
613 }
614 
ParseUmountAll(const std::vector<std::string> & args)615 Result<std::string> ParseUmountAll(const std::vector<std::string>& args) {
616     if (args.size() <= 1) {
617         if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
618             return Error() << "umount_all requires at least 1 argument";
619         }
620         return {};
621     }
622     return args[1];
623 }
624 
InitAborter(const char * abort_message)625 static void InitAborter(const char* abort_message) {
626     // When init forks, it continues to use this aborter for LOG(FATAL), but we want children to
627     // simply abort instead of trying to reboot the system.
628     if (getpid() != 1) {
629         android::base::DefaultAborter(abort_message);
630         return;
631     }
632 
633     InitFatalReboot(SIGABRT);
634 }
635 
636 // The kernel opens /dev/console and uses that fd for stdin/stdout/stderr if there is a serial
637 // console enabled and no initramfs, otherwise it does not provide any fds for stdin/stdout/stderr.
638 // SetStdioToDevNull() is used to close these existing fds if they exist and replace them with
639 // /dev/null regardless.
640 //
641 // In the case that these fds are provided by the kernel, the exec of second stage init causes an
642 // SELinux denial as it does not have access to /dev/console.  In the case that they are not
643 // provided, exec of any further process is potentially dangerous as the first fd's opened by that
644 // process will take the stdin/stdout/stderr fileno's, which can cause issues if printf(), etc is
645 // then used by that process.
646 //
647 // Lastly, simply calling SetStdioToDevNull() in first stage init is not enough, since first
648 // stage init still runs in kernel context, future child processes will not have permissions to
649 // access any fds that it opens, including the one opened below for /dev/null.  Therefore,
650 // SetStdioToDevNull() must be called again in second stage init.
SetStdioToDevNull(char ** argv)651 void SetStdioToDevNull(char** argv) {
652     // Make stdin/stdout/stderr all point to /dev/null.
653     int fd = open("/dev/null", O_RDWR);  // NOLINT(android-cloexec-open)
654     if (fd == -1) {
655         int saved_errno = errno;
656         android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
657         errno = saved_errno;
658         PLOG(FATAL) << "Couldn't open /dev/null";
659     }
660     dup2(fd, STDIN_FILENO);
661     dup2(fd, STDOUT_FILENO);
662     dup2(fd, STDERR_FILENO);
663     if (fd > STDERR_FILENO) close(fd);
664 }
665 
InitKernelLogging(char ** argv)666 void InitKernelLogging(char** argv) {
667     SetFatalRebootTarget();
668     android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
669 }
670 
IsRecoveryMode()671 bool IsRecoveryMode() {
672     return access("/system/bin/recovery", F_OK) == 0;
673 }
674 
675 // Check if default mount namespace is ready to be used with APEX modules
676 static bool is_default_mount_namespace_ready = false;
677 
IsDefaultMountNamespaceReady()678 bool IsDefaultMountNamespaceReady() {
679     return is_default_mount_namespace_ready;
680 }
681 
SetDefaultMountNamespaceReady()682 void SetDefaultMountNamespaceReady() {
683     is_default_mount_namespace_ready = true;
684 }
685 
Has32BitAbi()686 bool Has32BitAbi() {
687     static bool has = !android::base::GetProperty("ro.product.cpu.abilist32", "").empty();
688     return has;
689 }
690 
GetApexNameFromFileName(const std::string & path)691 std::string GetApexNameFromFileName(const std::string& path) {
692     static const std::string kApexDir = "/apex/";
693     if (StartsWith(path, kApexDir)) {
694         auto begin = kApexDir.size();
695         auto end = path.find('/', begin);
696         return path.substr(begin, end - begin);
697     }
698     return "";
699 }
700 
FilterVersionedConfigs(const std::vector<std::string> & configs,int active_sdk)701 std::vector<std::string> FilterVersionedConfigs(const std::vector<std::string>& configs,
702                                                 int active_sdk) {
703     std::vector<std::string> filtered_configs;
704 
705     std::map<std::string, std::pair<std::string, int>> script_map;
706     for (const auto& c : configs) {
707         int sdk = 0;
708         const std::vector<std::string> parts = android::base::Split(c, ".");
709         std::string base;
710         if (parts.size() < 2) {
711             continue;
712         }
713 
714         // parts[size()-1], aka the suffix, should be "rc" or "#rc"
715         // any other pattern gets discarded
716 
717         const auto& suffix = parts[parts.size() - 1];
718         if (suffix == "rc") {
719             sdk = 0;
720         } else {
721             char trailer[9] = {0};
722             int r = sscanf(suffix.c_str(), "%d%8s", &sdk, trailer);
723             if (r != 2) {
724                 continue;
725             }
726             if (strlen(trailer) > 2 || strcmp(trailer, "rc") != 0) {
727                 continue;
728             }
729         }
730 
731         if (sdk < 0 || sdk > active_sdk) {
732             continue;
733         }
734 
735         base = parts[0];
736         for (unsigned int i = 1; i < parts.size() - 1; i++) {
737             base = base + "." + parts[i];
738         }
739 
740         // is this preferred over what we already have
741         auto it = script_map.find(base);
742         if (it == script_map.end() || it->second.second < sdk) {
743             script_map[base] = std::make_pair(c, sdk);
744         }
745     }
746 
747     for (const auto& m : script_map) {
748         filtered_configs.push_back(m.second.first);
749     }
750     return filtered_configs;
751 }
752 
753 // Forks, executes the provided program in the child, and waits for the completion in the parent.
754 // Child's stderr is captured and logged using LOG(ERROR).
ForkExecveAndWaitForCompletion(const char * filename,char * const argv[])755 bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
756     // Create a pipe used for redirecting child process's output.
757     // * pipe_fds[0] is the FD the parent will use for reading.
758     // * pipe_fds[1] is the FD the child will use for writing.
759     int pipe_fds[2];
760     if (pipe(pipe_fds) == -1) {
761         PLOG(ERROR) << "Failed to create pipe";
762         return false;
763     }
764 
765     pid_t child_pid = fork();
766     if (child_pid == -1) {
767         PLOG(ERROR) << "Failed to fork for " << filename;
768         return false;
769     }
770 
771     if (child_pid == 0) {
772         // fork succeeded -- this is executing in the child process
773 
774         // Close the pipe FD not used by this process
775         close(pipe_fds[0]);
776 
777         // Redirect stderr to the pipe FD provided by the parent
778         if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
779             PLOG(ERROR) << "Failed to redirect stderr of " << filename;
780             _exit(127);
781             return false;
782         }
783         close(pipe_fds[1]);
784 
785         if (execv(filename, argv) == -1) {
786             PLOG(ERROR) << "Failed to execve " << filename;
787             return false;
788         }
789         // Unreachable because execve will have succeeded and replaced this code
790         // with child process's code.
791         _exit(127);
792         return false;
793     } else {
794         // fork succeeded -- this is executing in the original/parent process
795 
796         // Close the pipe FD not used by this process
797         close(pipe_fds[1]);
798 
799         // Log the redirected output of the child process.
800         // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
801         // As a result, we're buffering all output and logging it in one go at the end of the
802         // invocation, instead of logging it as it comes in.
803         const int child_out_fd = pipe_fds[0];
804         std::string child_output;
805         if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
806             PLOG(ERROR) << "Failed to capture full output of " << filename;
807         }
808         close(child_out_fd);
809         if (!child_output.empty()) {
810             // Log captured output, line by line, because LOG expects to be invoked for each line
811             std::istringstream in(child_output);
812             std::string line;
813             while (std::getline(in, line)) {
814                 LOG(ERROR) << filename << ": " << line;
815             }
816         }
817 
818         // Wait for child to terminate
819         int status;
820         if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
821             PLOG(ERROR) << "Failed to wait for " << filename;
822             return false;
823         }
824 
825         if (WIFEXITED(status)) {
826             int status_code = WEXITSTATUS(status);
827             if (status_code == 0) {
828                 return true;
829             } else {
830                 LOG(ERROR) << filename << " exited with status " << status_code;
831             }
832         } else if (WIFSIGNALED(status)) {
833             LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
834         } else if (WIFSTOPPED(status)) {
835             LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
836         } else {
837             LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
838         }
839 
840         return false;
841     }
842 }
843 
844 }  // namespace init
845 }  // namespace android
846