blob: 35f2acf6663002b0e267c34d8ed0a64b407e624d [file] [log] [blame]
Vic Yange01ca4d2019-05-29 15:58:32 -07001/*
2 * Copyright (C) 2019 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 "service_utils.h"
18
19#include <grp.h>
20#include <sys/mount.h>
21#include <sys/prctl.h>
22#include <sys/wait.h>
23
24#include <android-base/file.h>
25#include <android-base/logging.h>
26#include <android-base/properties.h>
27#include <android-base/stringprintf.h>
28#include <android-base/strings.h>
Tom Cherry2e4c85f2019-07-09 13:33:36 -070029#include <cutils/android_get_control_file.h>
30#include <cutils/sockets.h>
Vic Yange01ca4d2019-05-29 15:58:32 -070031#include <processgroup/processgroup.h>
32
33#include "mount_namespace.h"
Tom Cherry2e4c85f2019-07-09 13:33:36 -070034#include "util.h"
Vic Yange01ca4d2019-05-29 15:58:32 -070035
36using android::base::GetProperty;
37using android::base::StartsWith;
38using android::base::StringPrintf;
39using android::base::unique_fd;
40using android::base::WriteStringToFile;
41
42namespace android {
43namespace init {
44
45namespace {
46
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070047Result<void> EnterNamespace(int nstype, const char* path) {
Vic Yange01ca4d2019-05-29 15:58:32 -070048 auto fd = unique_fd{open(path, O_RDONLY | O_CLOEXEC)};
49 if (fd == -1) {
50 return ErrnoError() << "Could not open namespace at " << path;
51 }
52 if (setns(fd, nstype) == -1) {
53 return ErrnoError() << "Could not setns() namespace at " << path;
54 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070055 return {};
Vic Yange01ca4d2019-05-29 15:58:32 -070056}
57
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070058Result<void> SetUpMountNamespace(bool remount_proc, bool remount_sys) {
Vic Yange01ca4d2019-05-29 15:58:32 -070059 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
60
61 // Recursively remount / as slave like zygote does so unmounting and mounting /proc
62 // doesn't interfere with the parent namespace's /proc mount. This will also
63 // prevent any other mounts/unmounts initiated by the service from interfering
64 // with the parent namespace but will still allow mount events from the parent
65 // namespace to propagate to the child.
66 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
67 return ErrnoError() << "Could not remount(/) recursively as slave";
68 }
69
70 // umount() then mount() /proc and/or /sys
71 // Note that it is not sufficient to mount with MS_REMOUNT.
72 if (remount_proc) {
73 if (umount("/proc") == -1) {
74 return ErrnoError() << "Could not umount(/proc)";
75 }
76 if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
77 return ErrnoError() << "Could not mount(/proc)";
78 }
79 }
80 if (remount_sys) {
81 if (umount2("/sys", MNT_DETACH) == -1) {
82 return ErrnoError() << "Could not umount(/sys)";
83 }
84 if (mount("", "/sys", "sysfs", kSafeFlags, "") == -1) {
85 return ErrnoError() << "Could not mount(/sys)";
86 }
87 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070088 return {};
Vic Yange01ca4d2019-05-29 15:58:32 -070089}
90
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070091Result<void> SetUpPidNamespace(const char* name) {
Vic Yange01ca4d2019-05-29 15:58:32 -070092 if (prctl(PR_SET_NAME, name) == -1) {
93 return ErrnoError() << "Could not set name";
94 }
95
96 pid_t child_pid = fork();
97 if (child_pid == -1) {
98 return ErrnoError() << "Could not fork init inside the PID namespace";
99 }
100
101 if (child_pid > 0) {
102 // So that we exit with the right status.
103 static int init_exitstatus = 0;
104 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
105
106 pid_t waited_pid;
107 int status;
108 while ((waited_pid = wait(&status)) > 0) {
109 // This loop will end when there are no processes left inside the
110 // PID namespace or when the init process inside the PID namespace
111 // gets a signal.
112 if (waited_pid == child_pid) {
113 init_exitstatus = status;
114 }
115 }
116 if (!WIFEXITED(init_exitstatus)) {
117 _exit(EXIT_FAILURE);
118 }
119 _exit(WEXITSTATUS(init_exitstatus));
120 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700121 return {};
Vic Yange01ca4d2019-05-29 15:58:32 -0700122}
123
124void ZapStdio() {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700125 auto fd = unique_fd{open("/dev/null", O_RDWR | O_CLOEXEC)};
Vic Yange01ca4d2019-05-29 15:58:32 -0700126 dup2(fd, 0);
127 dup2(fd, 1);
128 dup2(fd, 2);
Vic Yange01ca4d2019-05-29 15:58:32 -0700129}
130
131void OpenConsole(const std::string& console) {
Tom Cherry247ffbf2019-07-08 15:09:36 -0700132 auto fd = unique_fd{open(console.c_str(), O_RDWR | O_CLOEXEC)};
133 if (fd == -1) fd.reset(open("/dev/null", O_RDWR | O_CLOEXEC));
Vic Yange01ca4d2019-05-29 15:58:32 -0700134 ioctl(fd, TIOCSCTTY, 0);
135 dup2(fd, 0);
136 dup2(fd, 1);
137 dup2(fd, 2);
Vic Yange01ca4d2019-05-29 15:58:32 -0700138}
139
Tom Cherry5241d102019-09-10 14:20:35 -0700140} // namespace
141
142void Descriptor::Publish() const {
143 auto published_name = name_;
144
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700145 for (auto& c : published_name) {
146 c = isalnum(c) ? c : '_';
147 }
148
Tom Cherry5241d102019-09-10 14:20:35 -0700149 int fd = fd_.get();
150 // For safety, the FD is created as CLOEXEC, so that must be removed before publishing.
151 auto fd_flags = fcntl(fd, F_GETFD);
152 fd_flags &= ~FD_CLOEXEC;
153 if (fcntl(fd, F_SETFD, fd_flags) != 0) {
154 PLOG(ERROR) << "Failed to remove CLOEXEC from '" << published_name << "'";
155 }
156
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700157 std::string val = std::to_string(fd);
158 setenv(published_name.c_str(), val.c_str(), 1);
159}
160
Tom Cherry5241d102019-09-10 14:20:35 -0700161Result<Descriptor> SocketDescriptor::Create(const std::string& global_context) const {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700162 const auto& socket_context = context.empty() ? global_context : context;
Tom Cherry5241d102019-09-10 14:20:35 -0700163 auto result = CreateSocket(name, type | SOCK_CLOEXEC, passcred, perm, uid, gid, socket_context);
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700164 if (!result) {
165 return result.error();
166 }
167
Tom Cherry5241d102019-09-10 14:20:35 -0700168 return Descriptor(ANDROID_SOCKET_ENV_PREFIX + name, unique_fd(*result));
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700169}
170
Tom Cherry5241d102019-09-10 14:20:35 -0700171Result<Descriptor> FileDescriptor::Create() const {
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700172 int flags = (type == "r") ? O_RDONLY : (type == "w") ? O_WRONLY : O_RDWR;
173
174 // Make sure we do not block on open (eg: devices can chose to block on carrier detect). Our
175 // intention is never to delay launch of a service for such a condition. The service can
176 // perform its own blocking on carrier detect.
Tom Cherry5241d102019-09-10 14:20:35 -0700177 unique_fd fd(TEMP_FAILURE_RETRY(open(name.c_str(), flags | O_NONBLOCK | O_CLOEXEC)));
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700178
179 if (fd < 0) {
180 return ErrnoError() << "Failed to open file '" << name << "'";
181 }
182
183 // Fixup as we set O_NONBLOCK for open, the intent for fd is to block reads.
184 fcntl(fd, F_SETFL, flags);
185
186 LOG(INFO) << "Opened file '" << name << "', flags " << flags;
187
Tom Cherry5241d102019-09-10 14:20:35 -0700188 return Descriptor(ANDROID_FILE_ENV_PREFIX + name, std::move(fd));
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700189}
190
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700191Result<void> EnterNamespaces(const NamespaceInfo& info, const std::string& name, bool pre_apexd) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700192 for (const auto& [nstype, path] : info.namespaces_to_enter) {
193 if (auto result = EnterNamespace(nstype, path.c_str()); !result) {
194 return result;
195 }
196 }
197
198#if defined(__ANDROID__)
199 if (pre_apexd) {
200 if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
201 return Error() << "could not enter into the bootstrap mount namespace";
202 }
203 }
204#endif
205
206 if (info.flags & CLONE_NEWNS) {
207 bool remount_proc = info.flags & CLONE_NEWPID;
208 bool remount_sys =
209 std::any_of(info.namespaces_to_enter.begin(), info.namespaces_to_enter.end(),
210 [](const auto& entry) { return entry.first == CLONE_NEWNET; });
211 if (auto result = SetUpMountNamespace(remount_proc, remount_sys); !result) {
212 return result;
213 }
214 }
215
216 if (info.flags & CLONE_NEWPID) {
217 // This will fork again to run an init process inside the PID namespace.
218 if (auto result = SetUpPidNamespace(name.c_str()); !result) {
219 return result;
220 }
221 }
222
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700223 return {};
Vic Yange01ca4d2019-05-29 15:58:32 -0700224}
225
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700226Result<void> SetProcessAttributes(const ProcessAttributes& attr) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700227 if (attr.ioprio_class != IoSchedClass_NONE) {
228 if (android_set_ioprio(getpid(), attr.ioprio_class, attr.ioprio_pri)) {
229 PLOG(ERROR) << "failed to set pid " << getpid() << " ioprio=" << attr.ioprio_class
230 << "," << attr.ioprio_pri;
231 }
232 }
233
234 if (!attr.console.empty()) {
235 setsid();
236 OpenConsole(attr.console);
237 } else {
238 if (setpgid(0, getpid()) == -1) {
239 return ErrnoError() << "setpgid failed";
240 }
241 ZapStdio();
242 }
243
244 for (const auto& rlimit : attr.rlimits) {
245 if (setrlimit(rlimit.first, &rlimit.second) == -1) {
246 return ErrnoError() << StringPrintf(
247 "setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed", rlimit.first,
248 rlimit.second.rlim_cur, rlimit.second.rlim_max);
249 }
250 }
251
252 if (attr.gid) {
253 if (setgid(attr.gid) != 0) {
254 return ErrnoError() << "setgid failed";
255 }
256 }
257 if (setgroups(attr.supp_gids.size(), const_cast<gid_t*>(&attr.supp_gids[0])) != 0) {
258 return ErrnoError() << "setgroups failed";
259 }
260 if (attr.uid) {
261 if (setuid(attr.uid) != 0) {
262 return ErrnoError() << "setuid failed";
263 }
264 }
265
266 if (attr.priority != 0) {
267 if (setpriority(PRIO_PROCESS, 0, attr.priority) != 0) {
268 return ErrnoError() << "setpriority failed";
269 }
270 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700271 return {};
Vic Yange01ca4d2019-05-29 15:58:32 -0700272}
273
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700274Result<void> WritePidToFiles(std::vector<std::string>* files) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700275 // See if there were "writepid" instructions to write to files under cpuset path.
276 std::string cpuset_path;
277 if (CgroupGetControllerPath("cpuset", &cpuset_path)) {
278 auto cpuset_predicate = [&cpuset_path](const std::string& path) {
279 return StartsWith(path, cpuset_path + "/");
280 };
281 auto iter = std::find_if(files->begin(), files->end(), cpuset_predicate);
282 if (iter == files->end()) {
283 // There were no "writepid" instructions for cpusets, check if the system default
284 // cpuset is specified to be used for the process.
285 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
286 if (!default_cpuset.empty()) {
287 // Make sure the cpuset name starts and ends with '/'.
288 // A single '/' means the 'root' cpuset.
289 if (default_cpuset.front() != '/') {
290 default_cpuset.insert(0, 1, '/');
291 }
292 if (default_cpuset.back() != '/') {
293 default_cpuset.push_back('/');
294 }
295 files->push_back(
296 StringPrintf("%s%stasks", cpuset_path.c_str(), default_cpuset.c_str()));
297 }
298 }
299 } else {
300 LOG(ERROR) << "cpuset cgroup controller is not mounted!";
301 }
302 std::string pid_str = std::to_string(getpid());
303 for (const auto& file : *files) {
304 if (!WriteStringToFile(pid_str, file)) {
305 return ErrnoError() << "couldn't write " << pid_str << " to " << file;
306 }
307 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700308 return {};
Vic Yange01ca4d2019-05-29 15:58:32 -0700309}
310
311} // namespace init
312} // namespace android