blob: e5efc7da61bc3b80a4d1bfa96831e11b1abb5c74 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
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
Tom Cherry3f5eaae52017-04-06 16:30:22 -070017#include "util.h"
18
Mark Salyzyn62767fe2016-10-27 07:45:34 -070019#include <ctype.h>
20#include <errno.h>
21#include <fcntl.h>
Mark Salyzyn62767fe2016-10-27 07:45:34 -070022#include <pwd.h>
Elliott Hughes636ebc92019-10-07 18:16:23 -070023#include <signal.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080024#include <stdarg.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <stdio.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070026#include <stdlib.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080027#include <string.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070028#include <sys/socket.h>
29#include <sys/un.h>
Nikita Ioffefe7b83f2024-03-04 14:59:49 +000030#include <sys/wait.h>
Colin Cross504bc512010-04-13 19:35:09 -070031#include <time.h>
Mark Salyzyn62767fe2016-10-27 07:45:34 -070032#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080033
Deyao Ren238e9092022-07-21 23:05:13 +000034#include <map>
Elliott Hughes290a2282016-11-14 17:08:47 -080035#include <thread>
36
Elliott Hughes4f713192015-12-04 22:00:26 -080037#include <android-base/file.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070038#include <android-base/logging.h>
Elliott Hughesdc803122018-05-24 18:00:39 -070039#include <android-base/properties.h>
Tom Cherry2e4c85f2019-07-09 13:33:36 -070040#include <android-base/scopeguard.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080041#include <android-base/strings.h>
Mark Salyzyndb691072016-11-07 10:16:53 -080042#include <android-base/unique_fd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080043#include <cutils/sockets.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070044#include <selinux/android.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080045
Yi-Yo Chiangb8c23252023-07-25 22:08:55 +080046#if defined(__ANDROID__)
47#include <fs_mgr.h>
48#endif
49
Tom Cherrya2f91362020-02-20 10:50:00 -080050#ifdef INIT_FULL_SOURCES
Tom Cherryc5cf85d2019-07-31 13:59:15 -070051#include <android/api-level.h>
Tom Cherry4772f1d2019-07-30 09:34:41 -070052#include <sys/system_properties.h>
Tom Cherryc5cf85d2019-07-31 13:59:15 -070053
Tom Cherry59656fb2019-05-28 10:19:44 -070054#include "reboot_utils.h"
Vic Yang92c236e2019-05-28 15:58:35 -070055#include "selabel.h"
Tom Cherryc5cf85d2019-07-31 13:59:15 -070056#include "selinux.h"
Tom Cherryde6bd502018-02-13 16:50:08 -080057#else
58#include "host_init_stubs.h"
59#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080060
James Hawkinse78ea772017-03-24 11:43:02 -070061using android::base::boot_clock;
Tom Cherry4772f1d2019-07-30 09:34:41 -070062using android::base::StartsWith;
Tom Cherry517e1f12017-05-04 17:40:33 -070063using namespace std::literals::string_literals;
James Hawkinse78ea772017-03-24 11:43:02 -070064
Tom Cherry81f5d3e2017-06-22 12:53:17 -070065namespace android {
66namespace init {
67
Eric Biggers48c05a62022-05-13 19:40:09 +000068const std::string kDataDirPrefix("/data/");
69
Tom Cherry18278d22019-11-12 16:21:20 -080070void (*trigger_shutdown)(const std::string& command) = nullptr;
71
Tom Cherry517e1f12017-05-04 17:40:33 -070072// DecodeUid() - decodes and returns the given string, which can be either the
Tom Cherry11a3aee2017-08-03 12:54:07 -070073// numeric or name representation, into the integer uid or gid.
74Result<uid_t> DecodeUid(const std::string& name) {
Tom Cherry517e1f12017-05-04 17:40:33 -070075 if (isalpha(name[0])) {
76 passwd* pwd = getpwnam(name.c_str());
Tom Cherry11a3aee2017-08-03 12:54:07 -070077 if (!pwd) return ErrnoError() << "getpwnam failed";
78
79 return pwd->pw_uid;
William Roberts3792e6c2016-04-06 19:18:50 -070080 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080081
82 errno = 0;
Tom Cherry517e1f12017-05-04 17:40:33 -070083 uid_t result = static_cast<uid_t>(strtoul(name.c_str(), 0, 0));
Tom Cherry11a3aee2017-08-03 12:54:07 -070084 if (errno) return ErrnoError() << "strtoul failed";
85
86 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080087}
88
89/*
Mark Salyzynb066fcc2017-05-05 14:44:35 -070090 * CreateSocket - creates a Unix domain socket in ANDROID_SOCKET_DIR
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080091 * ("/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 */
Adam Langleyecc14a52022-05-11 22:32:47 +000095Result<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) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -070097 if (!socketcon.empty()) {
98 if (setsockcreatecon(socketcon.c_str()) == -1) {
99 return ErrnoError() << "setsockcreatecon(\"" << socketcon << "\") failed";
Nick Kralevich83ccb1c2015-11-23 16:26:42 -0800100 }
101 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800102
Mark Salyzyndb691072016-11-07 10:16:53 -0800103 android::base::unique_fd fd(socket(PF_UNIX, type, 0));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800104 if (fd < 0) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700105 return ErrnoError() << "Failed to open socket '" << name << "'";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800106 }
107
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700108 if (!socketcon.empty()) setsockcreatecon(nullptr);
Stephen Smalley8348d272013-05-13 12:37:04 -0400109
Mark Salyzyndb691072016-11-07 10:16:53 -0800110 struct sockaddr_un addr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800111 memset(&addr, 0 , sizeof(addr));
112 addr.sun_family = AF_UNIX;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700113 snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR "/%s", name.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800114
Mark Salyzyndb691072016-11-07 10:16:53 -0800115 if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700116 return ErrnoError() << "Failed to unlink old socket '" << name << "'";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800117 }
118
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700119 std::string secontext;
120 if (SelabelLookupFileContext(addr.sun_path, S_IFSOCK, &secontext) && !secontext.empty()) {
121 setfscreatecon(secontext.c_str());
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500122 }
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500123
Mark Salyzynb066fcc2017-05-05 14:44:35 -0700124 if (passcred) {
125 int on = 1;
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800126 if (setsockopt(fd.get(), SOL_SOCKET, SO_PASSCRED, &on, sizeof(on))) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700127 return ErrnoError() << "Failed to set SO_PASSCRED '" << name << "'";
Mark Salyzynb066fcc2017-05-05 14:44:35 -0700128 }
129 }
130
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800131 int ret = bind(fd.get(), (struct sockaddr*)&addr, sizeof(addr));
Mark Salyzyndb691072016-11-07 10:16:53 -0800132 int savederrno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800133
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700134 if (!secontext.empty()) {
135 setfscreatecon(nullptr);
136 }
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500137
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700138 auto guard = android::base::make_scope_guard([&addr] { unlink(addr.sun_path); });
139
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800140 if (ret) {
Mark Salyzyndb691072016-11-07 10:16:53 -0800141 errno = savederrno;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700142 return ErrnoError() << "Failed to bind socket '" << name << "'";
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800143 }
144
Mark Salyzyndb691072016-11-07 10:16:53 -0800145 if (lchown(addr.sun_path, uid, gid)) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700146 return ErrnoError() << "Failed to lchown socket '" << addr.sun_path << "'";
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800147 }
Mark Salyzyndb691072016-11-07 10:16:53 -0800148 if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700149 return ErrnoError() << "Failed to fchmodat socket '" << addr.sun_path << "'";
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800150 }
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800151 if (should_listen && listen(fd.get(), /* use OS maximum */ 1 << 30)) {
Adam Langleyecc14a52022-05-11 22:32:47 +0000152 return ErrnoError() << "Failed to listen on socket '" << addr.sun_path << "'";
153 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800154
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700155 LOG(INFO) << "Created socket '" << addr.sun_path << "'"
156 << ", mode " << std::oct << perm << std::dec
157 << ", user " << uid
158 << ", group " << gid;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800159
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700160 guard.Disable();
Mark Salyzyndb691072016-11-07 10:16:53 -0800161 return fd.release();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800162}
163
Tom Cherry11a3aee2017-08-03 12:54:07 -0700164Result<std::string> ReadFile(const std::string& path) {
Tom Cherry53089aa2017-03-31 15:47:33 -0700165 android::base::unique_fd fd(
166 TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
Elliott Hughesf682b472015-02-06 12:19:48 -0800167 if (fd == -1) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700168 return ErrnoError() << "open() failed";
Elliott Hughesf682b472015-02-06 12:19:48 -0800169 }
170
171 // For security reasons, disallow world-writable
172 // or group-writable files.
Nick Kralevich38f368c2012-01-18 10:39:01 -0800173 struct stat sb;
Bart Van Asscheaee2ec82022-12-02 18:48:15 -0800174 if (fstat(fd.get(), &sb) == -1) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700175 return ErrnoError() << "fstat failed()";
Nick Kralevich38f368c2012-01-18 10:39:01 -0800176 }
177 if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700178 return Error() << "Skipping insecure file";
Nick Kralevich38f368c2012-01-18 10:39:01 -0800179 }
180
Tom Cherry11a3aee2017-08-03 12:54:07 -0700181 std::string content;
182 if (!android::base::ReadFdToString(fd, &content)) {
183 return ErrnoError() << "Unable to read file contents";
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700184 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700185 return content;
Elliott Hughesf682b472015-02-06 12:19:48 -0800186}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800187
Joel Galenson4b591f12017-11-27 14:45:26 -0800188static 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
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700205Result<void> WriteFile(const std::string& path, const std::string& content) {
Yongqin Liudbe88e72016-12-28 16:06:19 +0800206 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
Joel Galenson4b591f12017-11-27 14:45:26 -0800207 OpenFile(path, O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
Elliott Hughesf682b472015-02-06 12:19:48 -0800208 if (fd == -1) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700209 return ErrnoError() << "open() failed";
Elliott Hughesf682b472015-02-06 12:19:48 -0800210 }
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700211 if (!android::base::WriteStringToFd(content, fd)) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700212 return ErrnoError() << "Unable to write file contents";
Nick Kralevicheedbe812015-04-25 14:10:03 -0700213 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700214 return {};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800215}
216
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700217bool mkdir_recursive(const std::string& path, mode_t mode) {
Tom Cherry060b74b2017-04-12 14:27:51 -0700218 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) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700223 auto ret = make_dir(directory, mode);
224 if (!ret && errno != EEXIST) return false;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700225 }
226 }
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700227 auto ret = make_dir(path, mode);
228 if (!ret && errno != EEXIST) return false;
229 return true;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700230}
231
Elliott Hughes9605a942016-11-10 17:43:47 -0800232int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) {
Wei Wang4cea1212017-08-22 12:07:37 -0700233 android::base::Timer t;
234 while (t.duration() < timeout) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800235 struct stat sb;
Wei Wang4cea1212017-08-22 12:07:37 -0700236 if (stat(filename, &sb) != -1) {
237 LOG(INFO) << "wait for '" << filename << "' took " << t;
238 return 0;
239 }
Elliott Hughes290a2282016-11-14 17:08:47 -0800240 std::this_thread::sleep_for(10ms);
Elliott Hughes9605a942016-11-10 17:43:47 -0800241 }
Wei Wang4cea1212017-08-22 12:07:37 -0700242 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
Elliott Hughes9605a942016-11-10 17:43:47 -0800243 return -1;
Colin Crosscd0f1732010-04-19 17:10:24 -0700244}
Colin Crossf83d0b92010-04-21 12:04:20 -0700245
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700246bool 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());
Stephen Smalleye096e362012-06-11 13:37:39 -0400250 }
Stephen Smalleye096e362012-06-11 13:37:39 -0400251
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700252 int rc = mkdir(path.c_str(), mode);
Stephen Smalleye096e362012-06-11 13:37:39 -0400253
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700254 if (!secontext.empty()) {
Stephen Smalleye096e362012-06-11 13:37:39 -0400255 int save_errno = errno;
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700256 setfscreatecon(nullptr);
Stephen Smalleye096e362012-06-11 13:37:39 -0400257 errno = save_errno;
258 }
Kenny Rootb5982bf2012-10-16 23:07:05 -0700259
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700260 return rc == 0;
Stephen Smalleye096e362012-06-11 13:37:39 -0400261}
262
Andres Moralesdb5f5d42015-05-08 08:30:33 -0700263/*
Lee Campbellf13b1b32015-07-24 16:57:14 -0700264 * Returns true is pathname is a directory
265 */
266bool 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}
Tom Cherryb7349902015-08-26 11:43:36 -0700273
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700274Result<std::string> ExpandProps(const std::string& src) {
Tom Cherryb7349902015-08-26 11:43:36 -0700275 const char* src_ptr = src.c_str();
276
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700277 std::string dst;
Tom Cherryb7349902015-08-26 11:43:36 -0700278
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
Mark Salyzyn4b561622016-06-07 08:49:01 -0700284 * - ${x.y:-default} will return default value if property empty.
Tom Cherryb7349902015-08-26 11:43:36 -0700285 */
286 while (*src_ptr) {
287 const char* c;
288
289 c = strchr(src_ptr, '$');
290 if (!c) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700291 dst.append(src_ptr);
292 return dst;
Tom Cherryb7349902015-08-26 11:43:36 -0700293 }
294
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700295 dst.append(src_ptr, c);
Tom Cherryb7349902015-08-26 11:43:36 -0700296 c++;
297
298 if (*c == '$') {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700299 dst.push_back(*(c++));
Tom Cherryb7349902015-08-26 11:43:36 -0700300 src_ptr = c;
301 continue;
302 } else if (*c == '\0') {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700303 return dst;
Tom Cherryb7349902015-08-26 11:43:36 -0700304 }
305
306 std::string prop_name;
Mark Salyzyn4b561622016-06-07 08:49:01 -0700307 std::string def_val;
Tom Cherryb7349902015-08-26 11:43:36 -0700308 if (*c == '{') {
309 c++;
310 const char* end = strchr(c, '}');
311 if (!end) {
312 // failed to find closing brace, abort.
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700313 return Error() << "unexpected end of string in '" << src << "', looking for }";
Tom Cherryb7349902015-08-26 11:43:36 -0700314 }
315 prop_name = std::string(c, end);
316 c = end + 1;
Mark Salyzyn4b561622016-06-07 08:49:01 -0700317 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 }
Tom Cherryb7349902015-08-26 11:43:36 -0700322 } else {
323 prop_name = c;
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700324 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 }
Tom Cherryb7349902015-08-26 11:43:36 -0700331 c += prop_name.size();
332 }
333
334 if (prop_name.empty()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700335 return Error() << "invalid zero-length property name in '" << src << "'";
Tom Cherryb7349902015-08-26 11:43:36 -0700336 }
337
Tom Cherryccf23532017-03-28 16:40:41 -0700338 std::string prop_val = android::base::GetProperty(prop_name, "");
Tom Cherryb7349902015-08-26 11:43:36 -0700339 if (prop_val.empty()) {
Mark Salyzyn4b561622016-06-07 08:49:01 -0700340 if (def_val.empty()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700341 return Error() << "property '" << prop_name << "' doesn't exist while expanding '"
342 << src << "'";
Mark Salyzyn4b561622016-06-07 08:49:01 -0700343 }
344 prop_val = def_val;
Tom Cherryb7349902015-08-26 11:43:36 -0700345 }
346
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700347 dst.append(prop_val);
Tom Cherryb7349902015-08-26 11:43:36 -0700348 src_ptr = c;
349 }
350
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700351 return dst;
Tom Cherryb7349902015-08-26 11:43:36 -0700352}
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000353
Yu Ningc01022a2017-07-26 17:54:08 +0800354// Reads the content of device tree file under the platform's Android DT directory.
Bowgo Tsaid2620172017-04-17 22:17:09 +0800355// Returns true if the read is success, false otherwise.
356bool read_android_dt_file(const std::string& sub_path, std::string* dt_content) {
Yi-Yo Chiangb8c23252023-07-25 22:08:55 +0800357#if defined(__ANDROID__)
358 const std::string file_name = android::fs_mgr::GetAndroidDtDir() + sub_path;
Bowgo Tsaid2620172017-04-17 22:17:09 +0800359 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 }
Yi-Yo Chiangb8c23252023-07-25 22:08:55 +0800365#endif
Bowgo Tsaid2620172017-04-17 22:17:09 +0800366 return false;
367}
368
369bool 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}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700378
Tom Cherryde6bd502018-02-13 16:50:08 -0800379bool 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
Tom Cherry4772f1d2019-07-30 09:34:41 -0700404Result<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
Eric Biggers6cb5a362022-05-13 19:11:42 +0000416// 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.
418std::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
Paul Crowley68258e82019-10-28 07:55:03 -0700434Result<MkdirOptions> ParseMkdir(const std::vector<std::string>& args) {
Eric Biggers6cb5a362022-05-13 19:11:42 +0000435 std::string path = CleanDirPath(args[1]);
Eric Biggers48c05a62022-05-13 19:40:09 +0000436 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;
Paul Crowley68258e82019-10-28 07:55:03 -0700441 mode_t mode = 0755;
442 Result<uid_t> uid = -1;
443 Result<gid_t> gid = -1;
Paul Crowley68258e82019-10-28 07:55:03 -0700444 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]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900455 if (!uid.ok()) {
Paul Crowley68258e82019-10-28 07:55:03 -0700456 return Error()
457 << "Unable to decode UID for '" << args[3] << "': " << uid.error();
458 }
459 break;
460 case 4:
461 gid = DecodeUid(args[4]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900462 if (!gid.ok()) {
Paul Crowley68258e82019-10-28 07:55:03 -0700463 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 }
Eric Biggers48c05a62022-05-13 19:40:09 +0000508 if (is_toplevel_data_dir) {
Paul Crowley68258e82019-10-28 07:55:03 -0700509 if (!set_option_encryption) {
Eric Biggers6cb5a362022-05-13 19:11:42 +0000510 LOG(WARNING) << "Top-level directory needs encryption action, eg mkdir " << path
Paul Crowley68258e82019-10-28 07:55:03 -0700511 << " <mode> <uid> <gid> encryption=Require";
512 }
513 if (fscrypt_action == FscryptAction::kNone) {
Eric Biggers6cb5a362022-05-13 19:11:42 +0000514 LOG(INFO) << "Not setting encryption policy on: " << path;
Paul Crowley68258e82019-10-28 07:55:03 -0700515 }
516 }
Paul Crowley68258e82019-10-28 07:55:03 -0700517
Eric Biggers6cb5a362022-05-13 19:11:42 +0000518 return MkdirOptions{path, mode, *uid, *gid, fscrypt_action, ref_option};
Paul Crowley68258e82019-10-28 07:55:03 -0700519}
520
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700521Result<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
Tom Cherry4772f1d2019-07-30 09:34:41 -0700563Result<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 {0, 0}};
574
575 int flag = 0;
576 std::vector<std::string> paths;
577
578 bool in_flags = true;
579 for (size_t i = 1; i < args.size(); ++i) {
580 if (android::base::StartsWith(args[i], "--")) {
581 if (!in_flags) {
582 return Error() << "flags must precede paths";
583 }
584 bool found = false;
585 for (size_t j = 0; flags[j].name; ++j) {
586 if (args[i] == flags[j].name) {
587 flag |= flags[j].value;
588 found = true;
589 break;
590 }
591 }
592 if (!found) {
593 return Error() << "bad flag " << args[i];
594 }
595 } else {
596 in_flags = false;
597 paths.emplace_back(args[i]);
598 }
599 }
600 return std::pair(flag, paths);
601}
602
Alistair Delvade28a862020-06-08 11:04:53 -0700603Result<std::string> ParseSwaponAll(const std::vector<std::string>& args) {
604 if (args.size() <= 1) {
605 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
606 return Error() << "swapon_all requires at least 1 argument";
607 }
608 return {};
609 }
610 return args[1];
611}
612
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700613Result<std::string> ParseUmountAll(const std::vector<std::string>& args) {
Alistair Delvade28a862020-06-08 11:04:53 -0700614 if (args.size() <= 1) {
615 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700616 return Error() << "umount_all requires at least 1 argument";
617 }
Alistair Delvade28a862020-06-08 11:04:53 -0700618 return {};
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700619 }
620 return args[1];
621}
622
Tom Cherry59656fb2019-05-28 10:19:44 -0700623static void InitAborter(const char* abort_message) {
624 // When init forks, it continues to use this aborter for LOG(FATAL), but we want children to
625 // simply abort instead of trying to reboot the system.
626 if (getpid() != 1) {
627 android::base::DefaultAborter(abort_message);
628 return;
629 }
630
Elliott Hughes636ebc92019-10-07 18:16:23 -0700631 InitFatalReboot(SIGABRT);
Tom Cherry59656fb2019-05-28 10:19:44 -0700632}
633
634// The kernel opens /dev/console and uses that fd for stdin/stdout/stderr if there is a serial
635// console enabled and no initramfs, otherwise it does not provide any fds for stdin/stdout/stderr.
636// SetStdioToDevNull() is used to close these existing fds if they exist and replace them with
637// /dev/null regardless.
638//
639// In the case that these fds are provided by the kernel, the exec of second stage init causes an
640// SELinux denial as it does not have access to /dev/console. In the case that they are not
641// provided, exec of any further process is potentially dangerous as the first fd's opened by that
642// process will take the stdin/stdout/stderr fileno's, which can cause issues if printf(), etc is
643// then used by that process.
644//
645// Lastly, simply calling SetStdioToDevNull() in first stage init is not enough, since first
646// stage init still runs in kernel context, future child processes will not have permissions to
647// access any fds that it opens, including the one opened below for /dev/null. Therefore,
648// SetStdioToDevNull() must be called again in second stage init.
649void SetStdioToDevNull(char** argv) {
Tom Cherry48e83e62018-10-04 13:14:14 -0700650 // Make stdin/stdout/stderr all point to /dev/null.
Tom Cherry247ffbf2019-07-08 15:09:36 -0700651 int fd = open("/dev/null", O_RDWR); // NOLINT(android-cloexec-open)
Tom Cherry48e83e62018-10-04 13:14:14 -0700652 if (fd == -1) {
653 int saved_errno = errno;
Tom Cherry59656fb2019-05-28 10:19:44 -0700654 android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
Tom Cherry48e83e62018-10-04 13:14:14 -0700655 errno = saved_errno;
656 PLOG(FATAL) << "Couldn't open /dev/null";
657 }
Tom Cherry59656fb2019-05-28 10:19:44 -0700658 dup2(fd, STDIN_FILENO);
659 dup2(fd, STDOUT_FILENO);
660 dup2(fd, STDERR_FILENO);
661 if (fd > STDERR_FILENO) close(fd);
662}
663
664void InitKernelLogging(char** argv) {
Tom Cherry75e13ba2019-05-21 13:53:05 -0700665 SetFatalRebootTarget();
Tom Cherry59656fb2019-05-28 10:19:44 -0700666 android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
Tom Cherry48e83e62018-10-04 13:14:14 -0700667}
668
Jiyong Park68660412019-01-16 23:00:59 +0900669bool IsRecoveryMode() {
670 return access("/system/bin/recovery", F_OK) == 0;
671}
672
Kiyoung Kim0cbee0d2021-03-02 16:45:27 +0900673// Check if default mount namespace is ready to be used with APEX modules
674static bool is_default_mount_namespace_ready = false;
675
676bool IsDefaultMountNamespaceReady() {
677 return is_default_mount_namespace_ready;
678}
679
680void SetDefaultMountNamespaceReady() {
681 is_default_mount_namespace_ready = true;
682}
683
Jiyong Park11d7bc52022-07-15 13:44:14 +0900684bool Has32BitAbi() {
685 static bool has = !android::base::GetProperty("ro.product.cpu.abilist32", "").empty();
686 return has;
687}
688
Deyao Rendf40ed12022-07-14 22:51:10 +0000689std::string GetApexNameFromFileName(const std::string& path) {
690 static const std::string kApexDir = "/apex/";
691 if (StartsWith(path, kApexDir)) {
692 auto begin = kApexDir.size();
693 auto end = path.find('/', begin);
694 return path.substr(begin, end - begin);
695 }
696 return "";
697}
698
Deyao Ren238e9092022-07-21 23:05:13 +0000699std::vector<std::string> FilterVersionedConfigs(const std::vector<std::string>& configs,
700 int active_sdk) {
701 std::vector<std::string> filtered_configs;
702
703 std::map<std::string, std::pair<std::string, int>> script_map;
704 for (const auto& c : configs) {
705 int sdk = 0;
706 const std::vector<std::string> parts = android::base::Split(c, ".");
707 std::string base;
708 if (parts.size() < 2) {
709 continue;
710 }
711
712 // parts[size()-1], aka the suffix, should be "rc" or "#rc"
713 // any other pattern gets discarded
714
715 const auto& suffix = parts[parts.size() - 1];
716 if (suffix == "rc") {
717 sdk = 0;
718 } else {
719 char trailer[9] = {0};
720 int r = sscanf(suffix.c_str(), "%d%8s", &sdk, trailer);
721 if (r != 2) {
722 continue;
723 }
724 if (strlen(trailer) > 2 || strcmp(trailer, "rc") != 0) {
725 continue;
726 }
727 }
728
729 if (sdk < 0 || sdk > active_sdk) {
730 continue;
731 }
732
733 base = parts[0];
734 for (unsigned int i = 1; i < parts.size() - 1; i++) {
735 base = base + "." + parts[i];
736 }
737
738 // is this preferred over what we already have
739 auto it = script_map.find(base);
740 if (it == script_map.end() || it->second.second < sdk) {
741 script_map[base] = std::make_pair(c, sdk);
742 }
743 }
744
745 for (const auto& m : script_map) {
746 filtered_configs.push_back(m.second.first);
747 }
748 return filtered_configs;
749}
750
Nikita Ioffefe7b83f2024-03-04 14:59:49 +0000751// Forks, executes the provided program in the child, and waits for the completion in the parent.
752// Child's stderr is captured and logged using LOG(ERROR).
753bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) {
754 // Create a pipe used for redirecting child process's output.
755 // * pipe_fds[0] is the FD the parent will use for reading.
756 // * pipe_fds[1] is the FD the child will use for writing.
757 int pipe_fds[2];
758 if (pipe(pipe_fds) == -1) {
759 PLOG(ERROR) << "Failed to create pipe";
760 return false;
761 }
762
763 pid_t child_pid = fork();
764 if (child_pid == -1) {
765 PLOG(ERROR) << "Failed to fork for " << filename;
766 return false;
767 }
768
769 if (child_pid == 0) {
770 // fork succeeded -- this is executing in the child process
771
772 // Close the pipe FD not used by this process
773 close(pipe_fds[0]);
774
775 // Redirect stderr to the pipe FD provided by the parent
776 if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) {
777 PLOG(ERROR) << "Failed to redirect stderr of " << filename;
778 _exit(127);
779 return false;
780 }
781 close(pipe_fds[1]);
782
783 if (execv(filename, argv) == -1) {
784 PLOG(ERROR) << "Failed to execve " << filename;
785 return false;
786 }
787 // Unreachable because execve will have succeeded and replaced this code
788 // with child process's code.
789 _exit(127);
790 return false;
791 } else {
792 // fork succeeded -- this is executing in the original/parent process
793
794 // Close the pipe FD not used by this process
795 close(pipe_fds[1]);
796
797 // Log the redirected output of the child process.
798 // It's unfortunate that there's no standard way to obtain an istream for a file descriptor.
799 // As a result, we're buffering all output and logging it in one go at the end of the
800 // invocation, instead of logging it as it comes in.
801 const int child_out_fd = pipe_fds[0];
802 std::string child_output;
803 if (!android::base::ReadFdToString(child_out_fd, &child_output)) {
804 PLOG(ERROR) << "Failed to capture full output of " << filename;
805 }
806 close(child_out_fd);
807 if (!child_output.empty()) {
808 // Log captured output, line by line, because LOG expects to be invoked for each line
809 std::istringstream in(child_output);
810 std::string line;
811 while (std::getline(in, line)) {
812 LOG(ERROR) << filename << ": " << line;
813 }
814 }
815
816 // Wait for child to terminate
817 int status;
818 if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) {
819 PLOG(ERROR) << "Failed to wait for " << filename;
820 return false;
821 }
822
823 if (WIFEXITED(status)) {
824 int status_code = WEXITSTATUS(status);
825 if (status_code == 0) {
826 return true;
827 } else {
828 LOG(ERROR) << filename << " exited with status " << status_code;
829 }
830 } else if (WIFSIGNALED(status)) {
831 LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status);
832 } else if (WIFSTOPPED(status)) {
833 LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status);
834 } else {
835 LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status;
836 }
837
838 return false;
839 }
840}
841
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700842} // namespace init
843} // namespace android