blob: 2d401425e7e6095a080e974428e9eefe5e1ec5d1 [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>
Colin Cross504bc512010-04-13 19:35:09 -070030#include <time.h>
Mark Salyzyn62767fe2016-10-27 07:45:34 -070031#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080032
Deyao Ren238e9092022-07-21 23:05:13 +000033#include <map>
Elliott Hughes290a2282016-11-14 17:08:47 -080034#include <thread>
35
Elliott Hughes4f713192015-12-04 22:00:26 -080036#include <android-base/file.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070037#include <android-base/logging.h>
Elliott Hughesdc803122018-05-24 18:00:39 -070038#include <android-base/properties.h>
Tom Cherry2e4c85f2019-07-09 13:33:36 -070039#include <android-base/scopeguard.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080040#include <android-base/strings.h>
Mark Salyzyndb691072016-11-07 10:16:53 -080041#include <android-base/unique_fd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042#include <cutils/sockets.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070043#include <selinux/android.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080044
Tom Cherrya2f91362020-02-20 10:50:00 -080045#ifdef INIT_FULL_SOURCES
Tom Cherryc5cf85d2019-07-31 13:59:15 -070046#include <android/api-level.h>
Tom Cherry4772f1d2019-07-30 09:34:41 -070047#include <sys/system_properties.h>
Tom Cherryc5cf85d2019-07-31 13:59:15 -070048
Tom Cherry59656fb2019-05-28 10:19:44 -070049#include "reboot_utils.h"
Vic Yang92c236e2019-05-28 15:58:35 -070050#include "selabel.h"
Tom Cherryc5cf85d2019-07-31 13:59:15 -070051#include "selinux.h"
Tom Cherryde6bd502018-02-13 16:50:08 -080052#else
53#include "host_init_stubs.h"
54#endif
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080055
James Hawkinse78ea772017-03-24 11:43:02 -070056using android::base::boot_clock;
Tom Cherry4772f1d2019-07-30 09:34:41 -070057using android::base::StartsWith;
Tom Cherry517e1f12017-05-04 17:40:33 -070058using namespace std::literals::string_literals;
James Hawkinse78ea772017-03-24 11:43:02 -070059
Tom Cherry81f5d3e2017-06-22 12:53:17 -070060namespace android {
61namespace init {
62
Yu Ningc01022a2017-07-26 17:54:08 +080063const std::string kDefaultAndroidDtDir("/proc/device-tree/firmware/android/");
64
Eric Biggers48c05a62022-05-13 19:40:09 +000065const std::string kDataDirPrefix("/data/");
66
Tom Cherry18278d22019-11-12 16:21:20 -080067void (*trigger_shutdown)(const std::string& command) = nullptr;
68
Tom Cherry517e1f12017-05-04 17:40:33 -070069// DecodeUid() - decodes and returns the given string, which can be either the
Tom Cherry11a3aee2017-08-03 12:54:07 -070070// numeric or name representation, into the integer uid or gid.
71Result<uid_t> DecodeUid(const std::string& name) {
Tom Cherry517e1f12017-05-04 17:40:33 -070072 if (isalpha(name[0])) {
73 passwd* pwd = getpwnam(name.c_str());
Tom Cherry11a3aee2017-08-03 12:54:07 -070074 if (!pwd) return ErrnoError() << "getpwnam failed";
75
76 return pwd->pw_uid;
William Roberts3792e6c2016-04-06 19:18:50 -070077 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080078
79 errno = 0;
Tom Cherry517e1f12017-05-04 17:40:33 -070080 uid_t result = static_cast<uid_t>(strtoul(name.c_str(), 0, 0));
Tom Cherry11a3aee2017-08-03 12:54:07 -070081 if (errno) return ErrnoError() << "strtoul failed";
82
83 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080084}
85
86/*
Mark Salyzynb066fcc2017-05-05 14:44:35 -070087 * CreateSocket - creates a Unix domain socket in ANDROID_SOCKET_DIR
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080088 * ("/dev/socket") as dictated in init.rc. This socket is inherited by the
89 * daemon. We communicate the file descriptor's value via the environment
90 * variable ANDROID_SOCKET_ENV_PREFIX<name> ("ANDROID_SOCKET_foo").
91 */
Tom Cherry2e4c85f2019-07-09 13:33:36 -070092Result<int> CreateSocket(const std::string& name, int type, bool passcred, mode_t perm, uid_t uid,
93 gid_t gid, const std::string& socketcon) {
94 if (!socketcon.empty()) {
95 if (setsockcreatecon(socketcon.c_str()) == -1) {
96 return ErrnoError() << "setsockcreatecon(\"" << socketcon << "\") failed";
Nick Kralevich83ccb1c2015-11-23 16:26:42 -080097 }
98 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080099
Mark Salyzyndb691072016-11-07 10:16:53 -0800100 android::base::unique_fd fd(socket(PF_UNIX, type, 0));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800101 if (fd < 0) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700102 return ErrnoError() << "Failed to open socket '" << name << "'";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800103 }
104
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700105 if (!socketcon.empty()) setsockcreatecon(nullptr);
Stephen Smalley8348d272013-05-13 12:37:04 -0400106
Mark Salyzyndb691072016-11-07 10:16:53 -0800107 struct sockaddr_un addr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800108 memset(&addr, 0 , sizeof(addr));
109 addr.sun_family = AF_UNIX;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700110 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 -0800111
Mark Salyzyndb691072016-11-07 10:16:53 -0800112 if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700113 return ErrnoError() << "Failed to unlink old socket '" << name << "'";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800114 }
115
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700116 std::string secontext;
117 if (SelabelLookupFileContext(addr.sun_path, S_IFSOCK, &secontext) && !secontext.empty()) {
118 setfscreatecon(secontext.c_str());
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500119 }
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500120
Mark Salyzynb066fcc2017-05-05 14:44:35 -0700121 if (passcred) {
122 int on = 1;
123 if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on))) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700124 return ErrnoError() << "Failed to set SO_PASSCRED '" << name << "'";
Mark Salyzynb066fcc2017-05-05 14:44:35 -0700125 }
126 }
127
Mark Salyzyndb691072016-11-07 10:16:53 -0800128 int ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr));
129 int savederrno = errno;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800130
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700131 if (!secontext.empty()) {
132 setfscreatecon(nullptr);
133 }
Stephen Smalleye46f9d52012-01-13 08:48:47 -0500134
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700135 auto guard = android::base::make_scope_guard([&addr] { unlink(addr.sun_path); });
136
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800137 if (ret) {
Mark Salyzyndb691072016-11-07 10:16:53 -0800138 errno = savederrno;
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700139 return ErrnoError() << "Failed to bind socket '" << name << "'";
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800140 }
141
Mark Salyzyndb691072016-11-07 10:16:53 -0800142 if (lchown(addr.sun_path, uid, gid)) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700143 return ErrnoError() << "Failed to lchown socket '" << addr.sun_path << "'";
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800144 }
Mark Salyzyndb691072016-11-07 10:16:53 -0800145 if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700146 return ErrnoError() << "Failed to fchmodat socket '" << addr.sun_path << "'";
Nick Kralevich9bcfd642016-02-24 15:50:52 -0800147 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700149 LOG(INFO) << "Created socket '" << addr.sun_path << "'"
150 << ", mode " << std::oct << perm << std::dec
151 << ", user " << uid
152 << ", group " << gid;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800153
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700154 guard.Disable();
Mark Salyzyndb691072016-11-07 10:16:53 -0800155 return fd.release();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800156}
157
Tom Cherry11a3aee2017-08-03 12:54:07 -0700158Result<std::string> ReadFile(const std::string& path) {
Tom Cherry53089aa2017-03-31 15:47:33 -0700159 android::base::unique_fd fd(
160 TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
Elliott Hughesf682b472015-02-06 12:19:48 -0800161 if (fd == -1) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700162 return ErrnoError() << "open() failed";
Elliott Hughesf682b472015-02-06 12:19:48 -0800163 }
164
165 // For security reasons, disallow world-writable
166 // or group-writable files.
Nick Kralevich38f368c2012-01-18 10:39:01 -0800167 struct stat sb;
Elliott Hughesf682b472015-02-06 12:19:48 -0800168 if (fstat(fd, &sb) == -1) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700169 return ErrnoError() << "fstat failed()";
Nick Kralevich38f368c2012-01-18 10:39:01 -0800170 }
171 if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700172 return Error() << "Skipping insecure file";
Nick Kralevich38f368c2012-01-18 10:39:01 -0800173 }
174
Tom Cherry11a3aee2017-08-03 12:54:07 -0700175 std::string content;
176 if (!android::base::ReadFdToString(fd, &content)) {
177 return ErrnoError() << "Unable to read file contents";
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700178 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700179 return content;
Elliott Hughesf682b472015-02-06 12:19:48 -0800180}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800181
Joel Galenson4b591f12017-11-27 14:45:26 -0800182static int OpenFile(const std::string& path, int flags, mode_t mode) {
183 std::string secontext;
184 if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) {
185 setfscreatecon(secontext.c_str());
186 }
187
188 int rc = open(path.c_str(), flags, mode);
189
190 if (!secontext.empty()) {
191 int save_errno = errno;
192 setfscreatecon(nullptr);
193 errno = save_errno;
194 }
195
196 return rc;
197}
198
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700199Result<void> WriteFile(const std::string& path, const std::string& content) {
Yongqin Liudbe88e72016-12-28 16:06:19 +0800200 android::base::unique_fd fd(TEMP_FAILURE_RETRY(
Joel Galenson4b591f12017-11-27 14:45:26 -0800201 OpenFile(path, O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
Elliott Hughesf682b472015-02-06 12:19:48 -0800202 if (fd == -1) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700203 return ErrnoError() << "open() failed";
Elliott Hughesf682b472015-02-06 12:19:48 -0800204 }
Tom Cherry2cbbe9f2017-05-04 18:17:33 -0700205 if (!android::base::WriteStringToFd(content, fd)) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700206 return ErrnoError() << "Unable to write file contents";
Nick Kralevicheedbe812015-04-25 14:10:03 -0700207 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700208 return {};
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800209}
210
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700211bool mkdir_recursive(const std::string& path, mode_t mode) {
Tom Cherry060b74b2017-04-12 14:27:51 -0700212 std::string::size_type slash = 0;
213 while ((slash = path.find('/', slash + 1)) != std::string::npos) {
214 auto directory = path.substr(0, slash);
215 struct stat info;
216 if (stat(directory.c_str(), &info) != 0) {
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700217 auto ret = make_dir(directory, mode);
218 if (!ret && errno != EEXIST) return false;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700219 }
220 }
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700221 auto ret = make_dir(path, mode);
222 if (!ret && errno != EEXIST) return false;
223 return true;
Colin Crossb0ab94b2010-04-08 16:16:20 -0700224}
225
Elliott Hughes9605a942016-11-10 17:43:47 -0800226int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) {
Wei Wang4cea1212017-08-22 12:07:37 -0700227 android::base::Timer t;
228 while (t.duration() < timeout) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800229 struct stat sb;
Wei Wang4cea1212017-08-22 12:07:37 -0700230 if (stat(filename, &sb) != -1) {
231 LOG(INFO) << "wait for '" << filename << "' took " << t;
232 return 0;
233 }
Elliott Hughes290a2282016-11-14 17:08:47 -0800234 std::this_thread::sleep_for(10ms);
Elliott Hughes9605a942016-11-10 17:43:47 -0800235 }
Wei Wang4cea1212017-08-22 12:07:37 -0700236 LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t;
Elliott Hughes9605a942016-11-10 17:43:47 -0800237 return -1;
Colin Crosscd0f1732010-04-19 17:10:24 -0700238}
Colin Crossf83d0b92010-04-21 12:04:20 -0700239
Tom Cherryc88d8f92019-08-19 15:21:25 -0700240void ImportKernelCmdline(const std::function<void(const std::string&, const std::string&)>& fn) {
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700241 std::string cmdline;
242 android::base::ReadFileToString("/proc/cmdline", &cmdline);
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -0700243
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700244 for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) {
245 std::vector<std::string> pieces = android::base::Split(entry, "=");
246 if (pieces.size() == 2) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700247 fn(pieces[0], pieces[1]);
Elliott Hughese5ce30f2015-05-06 19:19:24 -0700248 }
Vladimir Chtchetkine2b995432011-09-28 09:55:31 -0700249 }
250}
Stephen Smalleye096e362012-06-11 13:37:39 -0400251
Devin Moorea4ef15b2020-12-15 16:14:37 -0800252void ImportBootconfig(const std::function<void(const std::string&, const std::string&)>& fn) {
253 std::string bootconfig;
254 android::base::ReadFileToString("/proc/bootconfig", &bootconfig);
255
256 for (const auto& entry : android::base::Split(bootconfig, "\n")) {
257 std::vector<std::string> pieces = android::base::Split(entry, "=");
258 if (pieces.size() == 2) {
Devin Moore6d5445b2021-07-07 16:34:06 -0700259 // get rid of the extra space between a list of values and remove the quotes.
260 std::string value = android::base::StringReplace(pieces[1], "\", \"", ",", true);
261 value.erase(std::remove(value.begin(), value.end(), '"'), value.end());
262 fn(android::base::Trim(pieces[0]), android::base::Trim(value));
Devin Moorea4ef15b2020-12-15 16:14:37 -0800263 }
264 }
265}
266
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700267bool make_dir(const std::string& path, mode_t mode) {
268 std::string secontext;
269 if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) {
270 setfscreatecon(secontext.c_str());
Stephen Smalleye096e362012-06-11 13:37:39 -0400271 }
Stephen Smalleye096e362012-06-11 13:37:39 -0400272
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700273 int rc = mkdir(path.c_str(), mode);
Stephen Smalleye096e362012-06-11 13:37:39 -0400274
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700275 if (!secontext.empty()) {
Stephen Smalleye096e362012-06-11 13:37:39 -0400276 int save_errno = errno;
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700277 setfscreatecon(nullptr);
Stephen Smalleye096e362012-06-11 13:37:39 -0400278 errno = save_errno;
279 }
Kenny Rootb5982bf2012-10-16 23:07:05 -0700280
Tom Cherry0c8d6d22017-08-10 12:22:44 -0700281 return rc == 0;
Stephen Smalleye096e362012-06-11 13:37:39 -0400282}
283
Andres Moralesdb5f5d42015-05-08 08:30:33 -0700284/*
Lee Campbellf13b1b32015-07-24 16:57:14 -0700285 * Returns true is pathname is a directory
286 */
287bool is_dir(const char* pathname) {
288 struct stat info;
289 if (stat(pathname, &info) == -1) {
290 return false;
291 }
292 return S_ISDIR(info.st_mode);
293}
Tom Cherryb7349902015-08-26 11:43:36 -0700294
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700295Result<std::string> ExpandProps(const std::string& src) {
Tom Cherryb7349902015-08-26 11:43:36 -0700296 const char* src_ptr = src.c_str();
297
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700298 std::string dst;
Tom Cherryb7349902015-08-26 11:43:36 -0700299
300 /* - variables can either be $x.y or ${x.y}, in case they are only part
301 * of the string.
302 * - will accept $$ as a literal $.
303 * - no nested property expansion, i.e. ${foo.${bar}} is not supported,
304 * bad things will happen
Mark Salyzyn4b561622016-06-07 08:49:01 -0700305 * - ${x.y:-default} will return default value if property empty.
Tom Cherryb7349902015-08-26 11:43:36 -0700306 */
307 while (*src_ptr) {
308 const char* c;
309
310 c = strchr(src_ptr, '$');
311 if (!c) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700312 dst.append(src_ptr);
313 return dst;
Tom Cherryb7349902015-08-26 11:43:36 -0700314 }
315
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700316 dst.append(src_ptr, c);
Tom Cherryb7349902015-08-26 11:43:36 -0700317 c++;
318
319 if (*c == '$') {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700320 dst.push_back(*(c++));
Tom Cherryb7349902015-08-26 11:43:36 -0700321 src_ptr = c;
322 continue;
323 } else if (*c == '\0') {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700324 return dst;
Tom Cherryb7349902015-08-26 11:43:36 -0700325 }
326
327 std::string prop_name;
Mark Salyzyn4b561622016-06-07 08:49:01 -0700328 std::string def_val;
Tom Cherryb7349902015-08-26 11:43:36 -0700329 if (*c == '{') {
330 c++;
331 const char* end = strchr(c, '}');
332 if (!end) {
333 // failed to find closing brace, abort.
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700334 return Error() << "unexpected end of string in '" << src << "', looking for }";
Tom Cherryb7349902015-08-26 11:43:36 -0700335 }
336 prop_name = std::string(c, end);
337 c = end + 1;
Mark Salyzyn4b561622016-06-07 08:49:01 -0700338 size_t def = prop_name.find(":-");
339 if (def < prop_name.size()) {
340 def_val = prop_name.substr(def + 2);
341 prop_name = prop_name.substr(0, def);
342 }
Tom Cherryb7349902015-08-26 11:43:36 -0700343 } else {
344 prop_name = c;
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700345 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
346 return Error() << "using deprecated syntax for specifying property '" << c
347 << "', use ${name} instead";
348 } else {
349 LOG(ERROR) << "using deprecated syntax for specifying property '" << c
350 << "', use ${name} instead";
351 }
Tom Cherryb7349902015-08-26 11:43:36 -0700352 c += prop_name.size();
353 }
354
355 if (prop_name.empty()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700356 return Error() << "invalid zero-length property name in '" << src << "'";
Tom Cherryb7349902015-08-26 11:43:36 -0700357 }
358
Tom Cherryccf23532017-03-28 16:40:41 -0700359 std::string prop_val = android::base::GetProperty(prop_name, "");
Tom Cherryb7349902015-08-26 11:43:36 -0700360 if (prop_val.empty()) {
Mark Salyzyn4b561622016-06-07 08:49:01 -0700361 if (def_val.empty()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700362 return Error() << "property '" << prop_name << "' doesn't exist while expanding '"
363 << src << "'";
Mark Salyzyn4b561622016-06-07 08:49:01 -0700364 }
365 prop_val = def_val;
Tom Cherryb7349902015-08-26 11:43:36 -0700366 }
367
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700368 dst.append(prop_val);
Tom Cherryb7349902015-08-26 11:43:36 -0700369 src_ptr = c;
370 }
371
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700372 return dst;
Tom Cherryb7349902015-08-26 11:43:36 -0700373}
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000374
Yu Ningc01022a2017-07-26 17:54:08 +0800375static std::string init_android_dt_dir() {
376 // Use the standard procfs-based path by default
377 std::string android_dt_dir = kDefaultAndroidDtDir;
378 // The platform may specify a custom Android DT path in kernel cmdline
Tom Cherryc88d8f92019-08-19 15:21:25 -0700379 ImportKernelCmdline([&](const std::string& key, const std::string& value) {
380 if (key == "androidboot.android_dt_dir") {
381 android_dt_dir = value;
382 }
383 });
Alistair Delva3bb240b2021-03-09 11:01:10 -0800384 // ..Or bootconfig
385 if (android_dt_dir == kDefaultAndroidDtDir) {
386 ImportBootconfig([&](const std::string& key, const std::string& value) {
387 if (key == "androidboot.android_dt_dir") {
388 android_dt_dir = value;
389 }
390 });
391 }
392
Yu Ningc01022a2017-07-26 17:54:08 +0800393 LOG(INFO) << "Using Android DT directory " << android_dt_dir;
394 return android_dt_dir;
395}
396
397// FIXME: The same logic is duplicated in system/core/fs_mgr/
398const std::string& get_android_dt_dir() {
399 // Set once and saves time for subsequent calls to this function
400 static const std::string kAndroidDtDir = init_android_dt_dir();
401 return kAndroidDtDir;
402}
403
404// Reads the content of device tree file under the platform's Android DT directory.
Bowgo Tsaid2620172017-04-17 22:17:09 +0800405// Returns true if the read is success, false otherwise.
406bool read_android_dt_file(const std::string& sub_path, std::string* dt_content) {
Yu Ningc01022a2017-07-26 17:54:08 +0800407 const std::string file_name = get_android_dt_dir() + sub_path;
Bowgo Tsaid2620172017-04-17 22:17:09 +0800408 if (android::base::ReadFileToString(file_name, dt_content)) {
409 if (!dt_content->empty()) {
410 dt_content->pop_back(); // Trims the trailing '\0' out.
411 return true;
412 }
413 }
414 return false;
415}
416
417bool is_android_dt_value_expected(const std::string& sub_path, const std::string& expected_content) {
418 std::string dt_content;
419 if (read_android_dt_file(sub_path, &dt_content)) {
420 if (dt_content == expected_content) {
421 return true;
422 }
423 }
424 return false;
425}
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700426
Tom Cherryde6bd502018-02-13 16:50:08 -0800427bool IsLegalPropertyName(const std::string& name) {
428 size_t namelen = name.size();
429
430 if (namelen < 1) return false;
431 if (name[0] == '.') return false;
432 if (name[namelen - 1] == '.') return false;
433
434 /* Only allow alphanumeric, plus '.', '-', '@', ':', or '_' */
435 /* Don't allow ".." to appear in a property name */
436 for (size_t i = 0; i < namelen; i++) {
437 if (name[i] == '.') {
438 // i=0 is guaranteed to never have a dot. See above.
439 if (name[i - 1] == '.') return false;
440 continue;
441 }
442 if (name[i] == '_' || name[i] == '-' || name[i] == '@' || name[i] == ':') continue;
443 if (name[i] >= 'a' && name[i] <= 'z') continue;
444 if (name[i] >= 'A' && name[i] <= 'Z') continue;
445 if (name[i] >= '0' && name[i] <= '9') continue;
446 return false;
447 }
448
449 return true;
450}
451
Tom Cherry4772f1d2019-07-30 09:34:41 -0700452Result<void> IsLegalPropertyValue(const std::string& name, const std::string& value) {
453 if (value.size() >= PROP_VALUE_MAX && !StartsWith(name, "ro.")) {
454 return Error() << "Property value too long";
455 }
456
457 if (mbstowcs(nullptr, value.data(), 0) == static_cast<std::size_t>(-1)) {
458 return Error() << "Value is not a UTF8 encoded string";
459 }
460
461 return {};
462}
463
Eric Biggers6cb5a362022-05-13 19:11:42 +0000464// Remove unnecessary slashes so that any later checks (e.g., the check for
465// whether the path is a top-level directory in /data) don't get confused.
466std::string CleanDirPath(const std::string& path) {
467 std::string result;
468 result.reserve(path.length());
469 // Collapse duplicate slashes, e.g. //data//foo// => /data/foo/
470 for (char c : path) {
471 if (c != '/' || result.empty() || result.back() != '/') {
472 result += c;
473 }
474 }
475 // Remove trailing slash, e.g. /data/foo/ => /data/foo
476 if (result.length() > 1 && result.back() == '/') {
477 result.pop_back();
478 }
479 return result;
480}
481
Paul Crowley68258e82019-10-28 07:55:03 -0700482Result<MkdirOptions> ParseMkdir(const std::vector<std::string>& args) {
Eric Biggers6cb5a362022-05-13 19:11:42 +0000483 std::string path = CleanDirPath(args[1]);
Eric Biggers48c05a62022-05-13 19:40:09 +0000484 const bool is_toplevel_data_dir =
485 StartsWith(path, kDataDirPrefix) &&
486 path.find_first_of('/', kDataDirPrefix.size()) == std::string::npos;
487 FscryptAction fscrypt_action =
488 is_toplevel_data_dir ? FscryptAction::kRequire : FscryptAction::kNone;
Paul Crowley68258e82019-10-28 07:55:03 -0700489 mode_t mode = 0755;
490 Result<uid_t> uid = -1;
491 Result<gid_t> gid = -1;
Paul Crowley68258e82019-10-28 07:55:03 -0700492 std::string ref_option = "ref";
493 bool set_option_encryption = false;
494 bool set_option_key = false;
495
496 for (size_t i = 2; i < args.size(); i++) {
497 switch (i) {
498 case 2:
499 mode = std::strtoul(args[2].c_str(), 0, 8);
500 break;
501 case 3:
502 uid = DecodeUid(args[3]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900503 if (!uid.ok()) {
Paul Crowley68258e82019-10-28 07:55:03 -0700504 return Error()
505 << "Unable to decode UID for '" << args[3] << "': " << uid.error();
506 }
507 break;
508 case 4:
509 gid = DecodeUid(args[4]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900510 if (!gid.ok()) {
Paul Crowley68258e82019-10-28 07:55:03 -0700511 return Error()
512 << "Unable to decode GID for '" << args[4] << "': " << gid.error();
513 }
514 break;
515 default:
516 auto parts = android::base::Split(args[i], "=");
517 if (parts.size() != 2) {
518 return Error() << "Can't parse option: '" << args[i] << "'";
519 }
520 auto optname = parts[0];
521 auto optval = parts[1];
522 if (optname == "encryption") {
523 if (set_option_encryption) {
524 return Error() << "Duplicated option: '" << optname << "'";
525 }
526 if (optval == "Require") {
527 fscrypt_action = FscryptAction::kRequire;
528 } else if (optval == "None") {
529 fscrypt_action = FscryptAction::kNone;
530 } else if (optval == "Attempt") {
531 fscrypt_action = FscryptAction::kAttempt;
532 } else if (optval == "DeleteIfNecessary") {
533 fscrypt_action = FscryptAction::kDeleteIfNecessary;
534 } else {
535 return Error() << "Unknown encryption option: '" << optval << "'";
536 }
537 set_option_encryption = true;
538 } else if (optname == "key") {
539 if (set_option_key) {
540 return Error() << "Duplicated option: '" << optname << "'";
541 }
542 if (optval == "ref" || optval == "per_boot_ref") {
543 ref_option = optval;
544 } else {
545 return Error() << "Unknown key option: '" << optval << "'";
546 }
547 set_option_key = true;
548 } else {
549 return Error() << "Unknown option: '" << args[i] << "'";
550 }
551 }
552 }
553 if (set_option_key && fscrypt_action == FscryptAction::kNone) {
554 return Error() << "Key option set but encryption action is none";
555 }
Eric Biggers48c05a62022-05-13 19:40:09 +0000556 if (is_toplevel_data_dir) {
Paul Crowley68258e82019-10-28 07:55:03 -0700557 if (!set_option_encryption) {
Eric Biggers6cb5a362022-05-13 19:11:42 +0000558 LOG(WARNING) << "Top-level directory needs encryption action, eg mkdir " << path
Paul Crowley68258e82019-10-28 07:55:03 -0700559 << " <mode> <uid> <gid> encryption=Require";
560 }
561 if (fscrypt_action == FscryptAction::kNone) {
Eric Biggers6cb5a362022-05-13 19:11:42 +0000562 LOG(INFO) << "Not setting encryption policy on: " << path;
Paul Crowley68258e82019-10-28 07:55:03 -0700563 }
564 }
Paul Crowley68258e82019-10-28 07:55:03 -0700565
Eric Biggers6cb5a362022-05-13 19:11:42 +0000566 return MkdirOptions{path, mode, *uid, *gid, fscrypt_action, ref_option};
Paul Crowley68258e82019-10-28 07:55:03 -0700567}
568
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700569Result<MountAllOptions> ParseMountAll(const std::vector<std::string>& args) {
570 bool compat_mode = false;
571 bool import_rc = false;
572 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
573 if (args.size() <= 1) {
574 return Error() << "mount_all requires at least 1 argument";
575 }
576 compat_mode = true;
577 import_rc = true;
578 }
579
580 std::size_t first_option_arg = args.size();
581 enum mount_mode mode = MOUNT_MODE_DEFAULT;
582
583 // If we are <= Q, then stop looking for non-fstab arguments at slot 2.
584 // Otherwise, stop looking at slot 1 (as the fstab path argument is optional >= R).
585 for (std::size_t na = args.size() - 1; na > (compat_mode ? 1 : 0); --na) {
586 if (args[na] == "--early") {
587 first_option_arg = na;
588 mode = MOUNT_MODE_EARLY;
589 } else if (args[na] == "--late") {
590 first_option_arg = na;
591 mode = MOUNT_MODE_LATE;
592 import_rc = false;
593 }
594 }
595
596 std::string fstab_path;
597 if (first_option_arg > 1) {
598 fstab_path = args[1];
599 } else if (compat_mode) {
600 return Error() << "mount_all argument 1 must be the fstab path";
601 }
602
603 std::vector<std::string> rc_paths;
604 for (std::size_t na = 2; na < first_option_arg; ++na) {
605 rc_paths.push_back(args[na]);
606 }
607
608 return MountAllOptions{rc_paths, fstab_path, mode, import_rc};
609}
610
Tom Cherry4772f1d2019-07-30 09:34:41 -0700611Result<std::pair<int, std::vector<std::string>>> ParseRestorecon(
612 const std::vector<std::string>& args) {
613 struct flag_type {
614 const char* name;
615 int value;
616 };
617 static const flag_type flags[] = {
618 {"--recursive", SELINUX_ANDROID_RESTORECON_RECURSE},
619 {"--skip-ce", SELINUX_ANDROID_RESTORECON_SKIPCE},
620 {"--cross-filesystems", SELINUX_ANDROID_RESTORECON_CROSS_FILESYSTEMS},
621 {0, 0}};
622
623 int flag = 0;
624 std::vector<std::string> paths;
625
626 bool in_flags = true;
627 for (size_t i = 1; i < args.size(); ++i) {
628 if (android::base::StartsWith(args[i], "--")) {
629 if (!in_flags) {
630 return Error() << "flags must precede paths";
631 }
632 bool found = false;
633 for (size_t j = 0; flags[j].name; ++j) {
634 if (args[i] == flags[j].name) {
635 flag |= flags[j].value;
636 found = true;
637 break;
638 }
639 }
640 if (!found) {
641 return Error() << "bad flag " << args[i];
642 }
643 } else {
644 in_flags = false;
645 paths.emplace_back(args[i]);
646 }
647 }
648 return std::pair(flag, paths);
649}
650
Alistair Delvade28a862020-06-08 11:04:53 -0700651Result<std::string> ParseSwaponAll(const std::vector<std::string>& args) {
652 if (args.size() <= 1) {
653 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
654 return Error() << "swapon_all requires at least 1 argument";
655 }
656 return {};
657 }
658 return args[1];
659}
660
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700661Result<std::string> ParseUmountAll(const std::vector<std::string>& args) {
Alistair Delvade28a862020-06-08 11:04:53 -0700662 if (args.size() <= 1) {
663 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700664 return Error() << "umount_all requires at least 1 argument";
665 }
Alistair Delvade28a862020-06-08 11:04:53 -0700666 return {};
Alistair Delvaa2cc1eb2020-05-20 16:24:00 -0700667 }
668 return args[1];
669}
670
Tom Cherry59656fb2019-05-28 10:19:44 -0700671static void InitAborter(const char* abort_message) {
672 // When init forks, it continues to use this aborter for LOG(FATAL), but we want children to
673 // simply abort instead of trying to reboot the system.
674 if (getpid() != 1) {
675 android::base::DefaultAborter(abort_message);
676 return;
677 }
678
Elliott Hughes636ebc92019-10-07 18:16:23 -0700679 InitFatalReboot(SIGABRT);
Tom Cherry59656fb2019-05-28 10:19:44 -0700680}
681
682// The kernel opens /dev/console and uses that fd for stdin/stdout/stderr if there is a serial
683// console enabled and no initramfs, otherwise it does not provide any fds for stdin/stdout/stderr.
684// SetStdioToDevNull() is used to close these existing fds if they exist and replace them with
685// /dev/null regardless.
686//
687// In the case that these fds are provided by the kernel, the exec of second stage init causes an
688// SELinux denial as it does not have access to /dev/console. In the case that they are not
689// provided, exec of any further process is potentially dangerous as the first fd's opened by that
690// process will take the stdin/stdout/stderr fileno's, which can cause issues if printf(), etc is
691// then used by that process.
692//
693// Lastly, simply calling SetStdioToDevNull() in first stage init is not enough, since first
694// stage init still runs in kernel context, future child processes will not have permissions to
695// access any fds that it opens, including the one opened below for /dev/null. Therefore,
696// SetStdioToDevNull() must be called again in second stage init.
697void SetStdioToDevNull(char** argv) {
Tom Cherry48e83e62018-10-04 13:14:14 -0700698 // Make stdin/stdout/stderr all point to /dev/null.
Tom Cherry247ffbf2019-07-08 15:09:36 -0700699 int fd = open("/dev/null", O_RDWR); // NOLINT(android-cloexec-open)
Tom Cherry48e83e62018-10-04 13:14:14 -0700700 if (fd == -1) {
701 int saved_errno = errno;
Tom Cherry59656fb2019-05-28 10:19:44 -0700702 android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
Tom Cherry48e83e62018-10-04 13:14:14 -0700703 errno = saved_errno;
704 PLOG(FATAL) << "Couldn't open /dev/null";
705 }
Tom Cherry59656fb2019-05-28 10:19:44 -0700706 dup2(fd, STDIN_FILENO);
707 dup2(fd, STDOUT_FILENO);
708 dup2(fd, STDERR_FILENO);
709 if (fd > STDERR_FILENO) close(fd);
710}
711
712void InitKernelLogging(char** argv) {
Tom Cherry75e13ba2019-05-21 13:53:05 -0700713 SetFatalRebootTarget();
Tom Cherry59656fb2019-05-28 10:19:44 -0700714 android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter);
Tom Cherry48e83e62018-10-04 13:14:14 -0700715}
716
Jiyong Park68660412019-01-16 23:00:59 +0900717bool IsRecoveryMode() {
718 return access("/system/bin/recovery", F_OK) == 0;
719}
720
Kiyoung Kim0cbee0d2021-03-02 16:45:27 +0900721// Check if default mount namespace is ready to be used with APEX modules
722static bool is_default_mount_namespace_ready = false;
723
724bool IsDefaultMountNamespaceReady() {
725 return is_default_mount_namespace_ready;
726}
727
728void SetDefaultMountNamespaceReady() {
729 is_default_mount_namespace_ready = true;
730}
731
Jiyong Park3b3d87d2021-09-28 16:11:26 +0900732bool IsMicrodroid() {
733 static bool is_microdroid = android::base::GetProperty("ro.hardware", "") == "microdroid";
734 return is_microdroid;
735}
736
Jiyong Park11d7bc52022-07-15 13:44:14 +0900737bool Has32BitAbi() {
738 static bool has = !android::base::GetProperty("ro.product.cpu.abilist32", "").empty();
739 return has;
740}
741
Deyao Rendf40ed12022-07-14 22:51:10 +0000742std::string GetApexNameFromFileName(const std::string& path) {
743 static const std::string kApexDir = "/apex/";
744 if (StartsWith(path, kApexDir)) {
745 auto begin = kApexDir.size();
746 auto end = path.find('/', begin);
747 return path.substr(begin, end - begin);
748 }
749 return "";
750}
751
Deyao Ren238e9092022-07-21 23:05:13 +0000752std::vector<std::string> FilterVersionedConfigs(const std::vector<std::string>& configs,
753 int active_sdk) {
754 std::vector<std::string> filtered_configs;
755
756 std::map<std::string, std::pair<std::string, int>> script_map;
757 for (const auto& c : configs) {
758 int sdk = 0;
759 const std::vector<std::string> parts = android::base::Split(c, ".");
760 std::string base;
761 if (parts.size() < 2) {
762 continue;
763 }
764
765 // parts[size()-1], aka the suffix, should be "rc" or "#rc"
766 // any other pattern gets discarded
767
768 const auto& suffix = parts[parts.size() - 1];
769 if (suffix == "rc") {
770 sdk = 0;
771 } else {
772 char trailer[9] = {0};
773 int r = sscanf(suffix.c_str(), "%d%8s", &sdk, trailer);
774 if (r != 2) {
775 continue;
776 }
777 if (strlen(trailer) > 2 || strcmp(trailer, "rc") != 0) {
778 continue;
779 }
780 }
781
782 if (sdk < 0 || sdk > active_sdk) {
783 continue;
784 }
785
786 base = parts[0];
787 for (unsigned int i = 1; i < parts.size() - 1; i++) {
788 base = base + "." + parts[i];
789 }
790
791 // is this preferred over what we already have
792 auto it = script_map.find(base);
793 if (it == script_map.end() || it->second.second < sdk) {
794 script_map[base] = std::make_pair(c, sdk);
795 }
796 }
797
798 for (const auto& m : script_map) {
799 filtered_configs.push_back(m.second.first);
800 }
801 return filtered_configs;
802}
803
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700804} // namespace init
805} // namespace android