blob: dc2455e2f06203d0ef679e93541648012b3e1b55 [file] [log] [blame]
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001/*
2 * Copyright (C) 2017 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 "subcontext.h"
18
19#include <fcntl.h>
20#include <poll.h>
Wei Wang30bbf7d2020-07-06 15:26:49 -070021#include <sys/time.h>
22#include <sys/resource.h>
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070023#include <unistd.h>
24
25#include <android-base/file.h>
26#include <android-base/logging.h>
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070027#include <android-base/properties.h>
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070028#include <android-base/strings.h>
29#include <selinux/android.h>
30
31#include "action.h"
Tom Cherryd52a5b32019-07-22 16:05:36 -070032#include "builtins.h"
Jooyung Han7bfe4772020-09-14 17:29:13 +090033#include "mount_namespace.h"
Tom Cherry1ab3dfc2019-04-22 17:46:37 -070034#include "proto_utils.h"
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070035#include "util.h"
36
Tom Cherrya2f91362020-02-20 10:50:00 -080037#ifdef INIT_FULL_SOURCES
Tom Cherry40acb372018-08-01 13:41:12 -070038#include <android/api-level.h>
Tom Cherryde6bd502018-02-13 16:50:08 -080039#include "property_service.h"
Vic Yang92c236e2019-05-28 15:58:35 -070040#include "selabel.h"
Tom Cherryde6bd502018-02-13 16:50:08 -080041#include "selinux.h"
42#else
43#include "host_init_stubs.h"
44#endif
Tom Cherry32228482018-01-18 16:14:25 -080045
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070046using android::base::GetExecutablePath;
47using android::base::Join;
48using android::base::Socketpair;
49using android::base::Split;
50using android::base::StartsWith;
51using android::base::unique_fd;
52
53namespace android {
54namespace init {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070055namespace {
56
Tom Cherry18278d22019-11-12 16:21:20 -080057std::string shutdown_command;
Tom Cherrye3e77d32020-04-28 13:55:19 -070058static bool subcontext_terminated_by_shutdown;
59static std::unique_ptr<Subcontext> subcontext;
Tom Cherry18278d22019-11-12 16:21:20 -080060
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070061class SubcontextProcess {
62 public:
Tom Cherryd52a5b32019-07-22 16:05:36 -070063 SubcontextProcess(const BuiltinFunctionMap* function_map, std::string context, int init_fd)
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070064 : function_map_(function_map), context_(std::move(context)), init_fd_(init_fd){};
65 void MainLoop();
66
67 private:
68 void RunCommand(const SubcontextCommand::ExecuteCommand& execute_command,
Tom Cherryc49719f2018-01-10 11:04:34 -080069 SubcontextReply* reply) const;
70 void ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command,
71 SubcontextReply* reply) const;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070072
Tom Cherryd52a5b32019-07-22 16:05:36 -070073 const BuiltinFunctionMap* function_map_;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070074 const std::string context_;
75 const int init_fd_;
76};
77
78void SubcontextProcess::RunCommand(const SubcontextCommand::ExecuteCommand& execute_command,
Tom Cherryc49719f2018-01-10 11:04:34 -080079 SubcontextReply* reply) const {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070080 // Need to use ArraySplice instead of this code.
81 auto args = std::vector<std::string>();
82 for (const auto& string : execute_command.args()) {
83 args.emplace_back(string);
84 }
85
Tom Cherryd52a5b32019-07-22 16:05:36 -070086 auto map_result = function_map_->Find(args);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070087 Result<void> result;
Bernie Innocenticecebbb2020-02-06 03:49:33 +090088 if (!map_result.ok()) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070089 result = Error() << "Cannot find command: " << map_result.error();
90 } else {
Tom Cherryd52a5b32019-07-22 16:05:36 -070091 result = RunBuiltinFunction(map_result->function, args, context_);
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070092 }
93
Bernie Innocenticecebbb2020-02-06 03:49:33 +090094 if (result.ok()) {
Tom Cherryc49719f2018-01-10 11:04:34 -080095 reply->set_success(true);
Tom Cherrycb0f9bb2017-09-12 15:58:47 -070096 } else {
Tom Cherryc49719f2018-01-10 11:04:34 -080097 auto* failure = reply->mutable_failure();
Jiyong Park8fd64c82019-05-31 03:43:34 +090098 failure->set_error_string(result.error().message());
99 failure->set_error_errno(result.error().code());
Tom Cherryc49719f2018-01-10 11:04:34 -0800100 }
101}
102
103void SubcontextProcess::ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command,
104 SubcontextReply* reply) const {
105 for (const auto& arg : expand_args_command.args()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700106 auto expanded_arg = ExpandProps(arg);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900107 if (!expanded_arg.ok()) {
Tom Cherryc49719f2018-01-10 11:04:34 -0800108 auto* failure = reply->mutable_failure();
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700109 failure->set_error_string(expanded_arg.error().message());
Tom Cherryc49719f2018-01-10 11:04:34 -0800110 failure->set_error_errno(0);
111 return;
112 } else {
113 auto* expand_args_reply = reply->mutable_expand_args_reply();
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700114 expand_args_reply->add_expanded_args(*expanded_arg);
Tom Cherryc49719f2018-01-10 11:04:34 -0800115 }
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700116 }
117}
118
119void SubcontextProcess::MainLoop() {
120 pollfd ufd[1];
121 ufd[0].events = POLLIN;
122 ufd[0].fd = init_fd_;
123
124 while (true) {
125 ufd[0].revents = 0;
126 int nr = TEMP_FAILURE_RETRY(poll(ufd, arraysize(ufd), -1));
127 if (nr == 0) continue;
128 if (nr < 0) {
129 PLOG(FATAL) << "poll() of subcontext socket failed, continuing";
130 }
131
132 auto init_message = ReadMessage(init_fd_);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900133 if (!init_message.ok()) {
Jiyong Park8fd64c82019-05-31 03:43:34 +0900134 if (init_message.error().code() == 0) {
Luis Hector Chavez72353592018-09-21 12:27:02 -0700135 // If the init file descriptor was closed, let's exit quietly. If
136 // this was accidental, init will restart us. If init died, this
137 // avoids calling abort(3) unnecessarily.
138 return;
139 }
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700140 LOG(FATAL) << "Could not read message from init: " << init_message.error();
141 }
142
143 auto subcontext_command = SubcontextCommand();
144 if (!subcontext_command.ParseFromString(*init_message)) {
145 LOG(FATAL) << "Unable to parse message from init";
146 }
147
148 auto reply = SubcontextReply();
149 switch (subcontext_command.command_case()) {
150 case SubcontextCommand::kExecuteCommand: {
Tom Cherryc49719f2018-01-10 11:04:34 -0800151 RunCommand(subcontext_command.execute_command(), &reply);
152 break;
153 }
154 case SubcontextCommand::kExpandArgsCommand: {
155 ExpandArgs(subcontext_command.expand_args_command(), &reply);
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700156 break;
157 }
158 default:
159 LOG(FATAL) << "Unknown message type from init: "
160 << subcontext_command.command_case();
161 }
162
Tom Cherry18278d22019-11-12 16:21:20 -0800163 if (!shutdown_command.empty()) {
164 reply.set_trigger_shutdown(shutdown_command);
165 shutdown_command.clear();
166 }
167
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900168 if (auto result = SendMessage(init_fd_, reply); !result.ok()) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700169 LOG(FATAL) << "Failed to send message to init: " << result.error();
170 }
171 }
172}
173
174} // namespace
175
Tom Cherryd52a5b32019-07-22 16:05:36 -0700176int SubcontextMain(int argc, char** argv, const BuiltinFunctionMap* function_map) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700177 if (argc < 4) LOG(FATAL) << "Fewer than 4 args specified to subcontext (" << argc << ")";
178
179 auto context = std::string(argv[2]);
180 auto init_fd = std::atoi(argv[3]);
181
Tom Cherry0d1452e2017-10-19 14:39:35 -0700182 SelabelInitialize();
Tom Cherry32228482018-01-18 16:14:25 -0800183
Tom Cherry18278d22019-11-12 16:21:20 -0800184 trigger_shutdown = [](const std::string& command) { shutdown_command = command; };
185
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700186 auto subcontext_process = SubcontextProcess(function_map, context, init_fd);
Wei Wang30bbf7d2020-07-06 15:26:49 -0700187 // Restore prio before main loop
188 setpriority(PRIO_PROCESS, 0, 0);
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700189 subcontext_process.MainLoop();
190 return 0;
191}
192
193void Subcontext::Fork() {
194 unique_fd subcontext_socket;
195 if (!Socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, &socket_, &subcontext_socket)) {
196 LOG(FATAL) << "Could not create socket pair to communicate to subcontext";
197 return;
198 }
199
200 auto result = fork();
201
202 if (result == -1) {
203 LOG(FATAL) << "Could not fork subcontext";
204 } else if (result == 0) {
205 socket_.reset();
206
207 // We explicitly do not use O_CLOEXEC here, such that we can reference this FD by number
208 // in the subcontext process after we exec.
Tom Cherry247ffbf2019-07-08 15:09:36 -0700209 int child_fd = dup(subcontext_socket); // NOLINT(android-cloexec-dup)
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700210 if (child_fd < 0) {
211 PLOG(FATAL) << "Could not dup child_fd";
212 }
213
Tom Cherry1c005f32019-11-20 15:51:36 -0800214 // We don't switch contexts if we're running the unit tests. We don't use std::optional,
215 // since we still need a real context string to pass to the builtin functions.
216 if (context_ != kTestContext) {
217 if (setexeccon(context_.c_str()) < 0) {
218 PLOG(FATAL) << "Could not set execcon for '" << context_ << "'";
219 }
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700220 }
Jooyung Han7bfe4772020-09-14 17:29:13 +0900221#if defined(__ANDROID__)
222 // subcontext init runs in "default" mount namespace
223 // so that it can access /apex/*
224 if (auto result = SwitchToMountNamespaceIfNeeded(NS_DEFAULT); !result.ok()) {
225 LOG(FATAL) << "Could not switch to \"default\" mount namespace: " << result.error();
226 }
227#endif
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700228 auto init_path = GetExecutablePath();
229 auto child_fd_string = std::to_string(child_fd);
230 const char* args[] = {init_path.c_str(), "subcontext", context_.c_str(),
231 child_fd_string.c_str(), nullptr};
232 execv(init_path.data(), const_cast<char**>(args));
233
234 PLOG(FATAL) << "Could not execv subcontext init";
235 } else {
236 subcontext_socket.reset();
237 pid_ = result;
238 LOG(INFO) << "Forked subcontext for '" << context_ << "' with pid " << pid_;
239 }
240}
241
242void Subcontext::Restart() {
243 LOG(ERROR) << "Restarting subcontext '" << context_ << "'";
244 if (pid_) {
245 kill(pid_, SIGKILL);
246 }
247 pid_ = 0;
248 socket_.reset();
249 Fork();
250}
251
Tom Cherry14c24722019-09-18 13:47:19 -0700252bool Subcontext::PathMatchesSubcontext(const std::string& path) {
253 for (const auto& prefix : path_prefixes_) {
254 if (StartsWith(path, prefix)) {
255 return true;
256 }
257 }
258 return false;
259}
260
Tom Cherryc49719f2018-01-10 11:04:34 -0800261Result<SubcontextReply> Subcontext::TransmitMessage(const SubcontextCommand& subcontext_command) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900262 if (auto result = SendMessage(socket_, subcontext_command); !result.ok()) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700263 Restart();
264 return ErrnoError() << "Failed to send message to subcontext";
265 }
266
267 auto subcontext_message = ReadMessage(socket_);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900268 if (!subcontext_message.ok()) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700269 Restart();
270 return Error() << "Failed to receive result from subcontext: " << subcontext_message.error();
271 }
272
Tom Cherryc49719f2018-01-10 11:04:34 -0800273 auto subcontext_reply = SubcontextReply{};
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700274 if (!subcontext_reply.ParseFromString(*subcontext_message)) {
275 Restart();
276 return Error() << "Unable to parse message from subcontext";
277 }
Tom Cherry18278d22019-11-12 16:21:20 -0800278
279 if (subcontext_reply.has_trigger_shutdown()) {
280 trigger_shutdown(subcontext_reply.trigger_shutdown());
281 }
282
Tom Cherryc49719f2018-01-10 11:04:34 -0800283 return subcontext_reply;
284}
285
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700286Result<void> Subcontext::Execute(const std::vector<std::string>& args) {
Tom Cherryc49719f2018-01-10 11:04:34 -0800287 auto subcontext_command = SubcontextCommand();
288 std::copy(
289 args.begin(), args.end(),
290 RepeatedPtrFieldBackInserter(subcontext_command.mutable_execute_command()->mutable_args()));
291
292 auto subcontext_reply = TransmitMessage(subcontext_command);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900293 if (!subcontext_reply.ok()) {
Tom Cherryc49719f2018-01-10 11:04:34 -0800294 return subcontext_reply.error();
295 }
296
Tom Cherry32228482018-01-18 16:14:25 -0800297 if (subcontext_reply->reply_case() == SubcontextReply::kFailure) {
298 auto& failure = subcontext_reply->failure();
299 return ResultError(failure.error_string(), failure.error_errno());
300 }
301
Tom Cherryc49719f2018-01-10 11:04:34 -0800302 if (subcontext_reply->reply_case() != SubcontextReply::kSuccess) {
303 return Error() << "Unexpected message type from subcontext: "
304 << subcontext_reply->reply_case();
305 }
306
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700307 return {};
Tom Cherryc49719f2018-01-10 11:04:34 -0800308}
309
310Result<std::vector<std::string>> Subcontext::ExpandArgs(const std::vector<std::string>& args) {
311 auto subcontext_command = SubcontextCommand{};
312 std::copy(args.begin(), args.end(),
313 RepeatedPtrFieldBackInserter(
314 subcontext_command.mutable_expand_args_command()->mutable_args()));
315
316 auto subcontext_reply = TransmitMessage(subcontext_command);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900317 if (!subcontext_reply.ok()) {
Tom Cherryc49719f2018-01-10 11:04:34 -0800318 return subcontext_reply.error();
319 }
320
Tom Cherry32228482018-01-18 16:14:25 -0800321 if (subcontext_reply->reply_case() == SubcontextReply::kFailure) {
322 auto& failure = subcontext_reply->failure();
323 return ResultError(failure.error_string(), failure.error_errno());
324 }
325
Tom Cherryc49719f2018-01-10 11:04:34 -0800326 if (subcontext_reply->reply_case() != SubcontextReply::kExpandArgsReply) {
327 return Error() << "Unexpected message type from subcontext: "
328 << subcontext_reply->reply_case();
329 }
330
331 auto& reply = subcontext_reply->expand_args_reply();
332 auto expanded_args = std::vector<std::string>{};
333 for (const auto& string : reply.expanded_args()) {
334 expanded_args.emplace_back(string);
335 }
336 return expanded_args;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700337}
338
Tom Cherrye3e77d32020-04-28 13:55:19 -0700339void InitializeSubcontext() {
Tom Cherry40acb372018-08-01 13:41:12 -0700340 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_P__) {
Tom Cherrye3e77d32020-04-28 13:55:19 -0700341 subcontext.reset(
342 new Subcontext(std::vector<std::string>{"/vendor", "/odm"}, kVendorContext));
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700343 }
Tom Cherrye3e77d32020-04-28 13:55:19 -0700344}
345
346Subcontext* GetSubcontext() {
347 return subcontext.get();
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700348}
349
350bool SubcontextChildReap(pid_t pid) {
Tom Cherrye3e77d32020-04-28 13:55:19 -0700351 if (subcontext->pid() == pid) {
352 if (!subcontext_terminated_by_shutdown) {
353 subcontext->Restart();
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700354 }
Tom Cherrye3e77d32020-04-28 13:55:19 -0700355 return true;
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700356 }
357 return false;
358}
359
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700360void SubcontextTerminate() {
Tom Cherrye3e77d32020-04-28 13:55:19 -0700361 subcontext_terminated_by_shutdown = true;
362 kill(subcontext->pid(), SIGTERM);
Luis Hector Chavez92c49bc2018-07-27 11:19:25 -0700363}
364
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700365} // namespace init
366} // namespace android