blob: 7b983921b69ae22cc0b9b5b91649f50256adaf29 [file] [log] [blame]
Tom Cherrybac32992015-07-31 12:45:25 -07001/*
2 * Copyright (C) 2015 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.h"
18
19#include <fcntl.h>
Elliott Hughes9605a942016-11-10 17:43:47 -080020#include <inttypes.h>
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -040021#include <linux/securebits.h>
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070022#include <sched.h>
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070023#include <sys/prctl.h>
Tom Cherrybac32992015-07-31 12:45:25 -070024#include <sys/stat.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070025#include <sys/time.h>
Tom Cherrybac32992015-07-31 12:45:25 -070026#include <termios.h>
Dan Albertaf9ba4d2015-08-11 16:37:04 -070027#include <unistd.h>
Tom Cherrybac32992015-07-31 12:45:25 -070028
Elliott Hughes4f713192015-12-04 22:00:26 -080029#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070030#include <android-base/logging.h>
Elliott Hughesdc803122018-05-24 18:00:39 -070031#include <android-base/properties.h>
Tom Cherry60971e62019-09-10 10:40:47 -070032#include <android-base/scopeguard.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080033#include <android-base/stringprintf.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070034#include <android-base/strings.h>
Tom Cherry2e4c85f2019-07-09 13:33:36 -070035#include <cutils/sockets.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070036#include <processgroup/processgroup.h>
37#include <selinux/selinux.h>
Tom Cherrybac32992015-07-31 12:45:25 -070038
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -070039#include "lmkd_service.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070040#include "service_list.h"
Tom Cherrybac32992015-07-31 12:45:25 -070041#include "util.h"
42
Tom Cherrya2f91362020-02-20 10:50:00 -080043#ifdef INIT_FULL_SOURCES
Jiyong Parkd7f7c202019-05-10 21:12:15 +090044#include <ApexProperties.sysprop.h>
Tom Cherryd89ed132019-11-19 14:19:40 -080045#include <android/api-level.h>
Tom Cherryde6bd502018-02-13 16:50:08 -080046
Jiyong Park68660412019-01-16 23:00:59 +090047#include "mount_namespace.h"
Woody Lin45215ae2019-12-26 22:22:28 +080048#include "reboot_utils.h"
Tom Cherryd89ed132019-11-19 14:19:40 -080049#include "selinux.h"
Tom Cherryde6bd502018-02-13 16:50:08 -080050#else
51#include "host_init_stubs.h"
52#endif
53
James Hawkinse78ea772017-03-24 11:43:02 -070054using android::base::boot_clock;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070055using android::base::GetProperty;
56using android::base::Join;
Tom Cherry60971e62019-09-10 10:40:47 -070057using android::base::make_scope_guard;
Tom Cherryc88d8f92019-08-19 15:21:25 -070058using android::base::SetProperty;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070059using android::base::StartsWith;
Tom Cherryb7349902015-08-26 11:43:36 -070060using android::base::StringPrintf;
61using android::base::WriteStringToFile;
62
Tom Cherry81f5d3e2017-06-22 12:53:17 -070063namespace android {
64namespace init {
65
Tom Cherryaead51b2018-04-20 16:18:12 -070066static Result<std::string> ComputeContextFromExecutable(const std::string& service_path) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040067 std::string computed_context;
68
69 char* raw_con = nullptr;
70 char* raw_filecon = nullptr;
71
72 if (getcon(&raw_con) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070073 return Error() << "Could not get security context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040074 }
75 std::unique_ptr<char> mycon(raw_con);
76
77 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070078 return Error() << "Could not get file context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040079 }
80 std::unique_ptr<char> filecon(raw_filecon);
81
82 char* new_con = nullptr;
83 int rc = security_compute_create(mycon.get(), filecon.get(),
84 string_to_security_class("process"), &new_con);
85 if (rc == 0) {
86 computed_context = new_con;
87 free(new_con);
88 }
89 if (rc == 0 && computed_context == mycon.get()) {
Nick Kralevich1ea19eb2017-08-25 12:08:57 -070090 return Error() << "File " << service_path << "(labeled \"" << filecon.get()
91 << "\") has incorrect label or no domain transition from " << mycon.get()
92 << " to another SELinux domain defined. Have you configured your "
93 "service correctly? https://source.android.com/security/selinux/"
Steven Moreland9e987cb2020-04-09 12:45:03 -070094 "device-policy#label_new_services_and_address_denials. Note: this "
95 "error shows up even in permissive mode in order to make auditing "
96 "denials possible.";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040097 }
98 if (rc < 0) {
Tom Cherry76af7e62017-08-22 16:13:59 -070099 return Error() << "Could not get process context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400100 }
101 return computed_context;
102}
103
Tom Cherry8f380482018-04-17 14:48:44 -0700104static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400105 std::vector<std::string> expanded_args;
Tom Cherry5e405ca2017-09-11 16:08:54 -0700106 std::vector<char*> c_strings;
107
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400108 expanded_args.resize(args.size());
Tom Cherry5e405ca2017-09-11 16:08:54 -0700109 c_strings.push_back(const_cast<char*>(args[0].data()));
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400110 for (std::size_t i = 1; i < args.size(); ++i) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700111 auto expanded_arg = ExpandProps(args[i]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900112 if (!expanded_arg.ok()) {
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700113 LOG(FATAL) << args[0] << ": cannot expand arguments': " << expanded_arg.error();
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400114 }
Tom Cherryc5cf85d2019-07-31 13:59:15 -0700115 expanded_args[i] = *expanded_arg;
Tom Cherry5e405ca2017-09-11 16:08:54 -0700116 c_strings.push_back(expanded_args[i].data());
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400117 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700118 c_strings.push_back(nullptr);
119
Tom Cherry8f380482018-04-17 14:48:44 -0700120 if (sigstop) {
121 kill(getpid(), SIGSTOP);
122 }
123
Tom Cherry5e405ca2017-09-11 16:08:54 -0700124 return execv(c_strings[0], c_strings.data()) == 0;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400125}
126
Martin Stjernholmcacf0432019-08-21 18:34:31 +0100127static bool AreRuntimeApexesReady() {
Jiyong Park68660412019-01-16 23:00:59 +0900128 struct stat buf;
Martin Stjernholmcacf0432019-08-21 18:34:31 +0100129 return stat("/apex/com.android.art/", &buf) == 0 &&
130 stat("/apex/com.android.runtime/", &buf) == 0;
Jiyong Park68660412019-01-16 23:00:59 +0900131}
132
Tom Cherry59383792017-07-26 16:09:09 -0700133unsigned long Service::next_start_order_ = 1;
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700134bool Service::is_exec_service_running_ = false;
Tom Cherry59383792017-07-26 16:09:09 -0700135
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700136Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000137 const std::vector<std::string>& args, bool from_apex)
138 : Service(name, 0, 0, 0, {}, 0, "", subcontext_for_restart_commands, args, from_apex) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700139
Wei Wang641ff0a2017-03-27 10:59:11 -0700140Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
Tom Cherry247ffbf2019-07-08 15:09:36 -0700141 const std::vector<gid_t>& supp_gids, int namespace_flags,
Tom Cherry1cd082d2019-02-06 10:45:56 -0800142 const std::string& seclabel, Subcontext* subcontext_for_restart_commands,
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000143 const std::vector<std::string>& args, bool from_apex)
Wei Wang641ff0a2017-03-27 10:59:11 -0700144 : name_(name),
145 classnames_({"default"}),
146 flags_(flags),
147 pid_(0),
148 crash_count_(0),
Vic Yange01ca4d2019-05-29 15:58:32 -0700149 proc_attr_{.ioprio_class = IoSchedClass_NONE,
150 .ioprio_pri = 0,
151 .uid = uid,
152 .gid = gid,
153 .supp_gids = supp_gids,
154 .priority = 0},
155 namespaces_{.flags = namespace_flags},
Wei Wang641ff0a2017-03-27 10:59:11 -0700156 seclabel_(seclabel),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800157 onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0,
158 "onrestart", {}),
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700159 oom_score_adjust_(DEFAULT_OOM_SCORE_ADJUST),
Tom Cherry59383792017-07-26 16:09:09 -0700160 start_order_(0),
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000161 args_(args),
162 from_apex_(from_apex) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700163
164void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700165 if ((flags_ & SVC_TEMPORARY) != 0) {
166 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700167 return;
168 }
169
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700170 std::string prop_name = "init.svc." + name_;
Tom Cherryc88d8f92019-08-19 15:21:25 -0700171 SetProperty(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800172
173 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800174 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherryfed33732017-08-18 10:47:46 -0700175 std::string boottime_property = "ro.boottime." + name_;
176 if (GetProperty(boottime_property, "").empty()) {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700177 SetProperty(boottime_property, std::to_string(start_ns));
Tom Cherryfed33732017-08-18 10:47:46 -0700178 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800179 }
Daniel Normanc7887712019-07-19 11:04:01 -0700180
181 // init.svc_debug_pid.* properties are only for tests, and should not be used
182 // on device for security checks.
183 std::string pid_property = "init.svc_debug_pid." + name_;
184 if (new_state == "running") {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700185 SetProperty(pid_property, std::to_string(pid_));
Daniel Normanc7887712019-07-19 11:04:01 -0700186 } else if (new_state == "stopped") {
Tom Cherryc88d8f92019-08-19 15:21:25 -0700187 SetProperty(pid_property, "");
Daniel Normanc7887712019-07-19 11:04:01 -0700188 }
Tom Cherrybac32992015-07-31 12:45:25 -0700189}
190
Tom Cherryd89ed132019-11-19 14:19:40 -0800191void Service::KillProcessGroup(int signal, bool report_oneshot) {
Tom Cherry33838b12017-05-04 11:32:36 -0700192 // If we've already seen a successful result from killProcessGroup*(), then we have removed
193 // the cgroup already and calling these functions a second time will simply result in an error.
194 // This is true regardless of which signal was sent.
195 // These functions handle their own logging, so no additional logging is needed.
196 if (!process_cgroup_empty_) {
197 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
198 << ") process group...";
Tom Cherryd89ed132019-11-19 14:19:40 -0800199 int max_processes = 0;
Tom Cherry33838b12017-05-04 11:32:36 -0700200 int r;
201 if (signal == SIGTERM) {
Tom Cherryd89ed132019-11-19 14:19:40 -0800202 r = killProcessGroupOnce(proc_attr_.uid, pid_, signal, &max_processes);
Tom Cherry33838b12017-05-04 11:32:36 -0700203 } else {
Tom Cherryd89ed132019-11-19 14:19:40 -0800204 r = killProcessGroup(proc_attr_.uid, pid_, signal, &max_processes);
205 }
206
207 if (report_oneshot && max_processes > 0) {
208 LOG(WARNING)
209 << "Killed " << max_processes
210 << " additional processes from a oneshot process group for service '" << name_
211 << "'. This is new behavior, previously child processes would not be killed in "
212 "this case.";
Tom Cherry33838b12017-05-04 11:32:36 -0700213 }
214
215 if (r == 0) process_cgroup_empty_ = true;
216 }
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700217
218 if (oom_score_adjust_ != DEFAULT_OOM_SCORE_ADJUST) {
219 LmkdUnregister(name_, pid_);
220 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700221}
222
Vic Yange01ca4d2019-05-29 15:58:32 -0700223void Service::SetProcessAttributesAndCaps() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400224 // Keep capabilites on uid change.
Vic Yange01ca4d2019-05-29 15:58:32 -0700225 if (capabilities_ && proc_attr_.uid) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700226 // If Android is running in a container, some securebits might already
227 // be locked, so don't change those.
Ben Fennemaa7243602017-07-25 14:37:21 -0700228 unsigned long securebits = prctl(PR_GET_SECUREBITS);
229 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700230 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
231 }
232 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
233 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
234 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400235 }
236 }
237
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900238 if (auto result = SetProcessAttributes(proc_attr_); !result.ok()) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700239 LOG(FATAL) << "cannot set attribute for " << name_ << ": " << result.error();
240 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400241
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400242 if (!seclabel_.empty()) {
243 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700244 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400245 }
246 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700247
Tom Cherry1cd082d2019-02-06 10:45:56 -0800248 if (capabilities_) {
249 if (!SetCapsForExec(*capabilities_)) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400250 LOG(FATAL) << "cannot set capabilities for " << name_;
251 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700252 } else if (proc_attr_.uid) {
Luis Hector Chavez94fb5b02017-11-16 15:52:00 -0800253 // Inheritable caps can be non-zero when running in a container.
254 if (!DropInheritableCaps()) {
255 LOG(FATAL) << "cannot drop inheritable caps for " << name_;
256 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400257 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400258}
259
Paul Crowleyc73b2152018-04-13 17:38:57 +0000260void Service::Reap(const siginfo_t& siginfo) {
Tom Cherrybac32992015-07-31 12:45:25 -0700261 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Tom Cherryd89ed132019-11-19 14:19:40 -0800262 KillProcessGroup(SIGKILL, false);
263 } else {
264 // Legacy behavior from ~2007 until Android R: this else branch did not exist and we did not
265 // kill the process group in this case.
266 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
267 // The new behavior in Android R is to kill these process groups in all cases. The
268 // 'true' parameter instructions KillProcessGroup() to report a warning message where it
269 // detects a difference in behavior has occurred.
270 KillProcessGroup(SIGKILL, true);
271 }
Tom Cherrybac32992015-07-31 12:45:25 -0700272 }
273
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700274 // Remove any socket resources we may have created.
275 for (const auto& socket : sockets_) {
276 auto path = ANDROID_SOCKET_DIR "/" + socket.name;
277 unlink(path.c_str());
278 }
Tom Cherrybac32992015-07-31 12:45:25 -0700279
Paul Crowleyc73b2152018-04-13 17:38:57 +0000280 for (const auto& f : reap_callbacks_) {
281 f(siginfo);
282 }
283
Tom Cherry60971e62019-09-10 10:40:47 -0700284 if ((siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) && on_failure_reboot_target_) {
285 LOG(ERROR) << "Service with 'reboot_on_failure' option failed, shutting down system.";
Tom Cherry18278d22019-11-12 16:21:20 -0800286 trigger_shutdown(*on_failure_reboot_target_);
Tom Cherry60971e62019-09-10 10:40:47 -0700287 }
288
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700289 if (flags_ & SVC_EXEC) UnSetExec();
290
291 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700292
293 pid_ = 0;
294 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700295 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700296
297 // Oneshot processes go into the disabled state on exit,
298 // except when manually restarted.
Martijn Coenen70788f92019-04-23 16:26:01 +0200299 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART) && !(flags_ & SVC_RESET)) {
Tom Cherrybac32992015-07-31 12:45:25 -0700300 flags_ |= SVC_DISABLED;
301 }
302
303 // Disabled and reset processes do not get restarted automatically.
304 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
305 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700306 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700307 }
308
Tom Cherrya2f91362020-02-20 10:50:00 -0800309#if INIT_FULL_SOURCES
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900310 static bool is_apex_updatable = android::sysprop::ApexProperties::updatable().value_or(false);
311#else
312 static bool is_apex_updatable = false;
313#endif
314 const bool is_process_updatable = !pre_apexd_ && is_apex_updatable;
315
Woody Lin45215ae2019-12-26 22:22:28 +0800316 // If we crash > 4 times in 'fatal_crash_window_' minutes or before boot_completed,
Zimuzo88de80f2019-04-27 21:10:35 +0100317 // reboot into bootloader or set crashing property
Elliott Hughes9605a942016-11-10 17:43:47 -0800318 boot_clock::time_point now = boot_clock::now();
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900319 if (((flags_ & SVC_CRITICAL) || is_process_updatable) && !(flags_ & SVC_RESTART)) {
Zimuzo88de80f2019-04-27 21:10:35 +0100320 bool boot_completed = android::base::GetBoolProperty("sys.boot_completed", false);
Woody Lin45215ae2019-12-26 22:22:28 +0800321 if (now < time_crashed_ + fatal_crash_window_ || !boot_completed) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800322 if (++crash_count_ > 4) {
Woody Lin45215ae2019-12-26 22:22:28 +0800323 auto exit_reason = boot_completed ?
324 "in " + std::to_string(fatal_crash_window_.count()) + " minutes" :
325 "before boot completed";
Zimuzoc55a8c62019-01-07 10:19:02 +0000326 if (flags_ & SVC_CRITICAL) {
Woody Lin45215ae2019-12-26 22:22:28 +0800327 // Aborts into `fatal_reboot_target_'.
328 SetFatalRebootTarget(fatal_reboot_target_);
Zimuzo88de80f2019-04-27 21:10:35 +0100329 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times "
Woody Lin45215ae2019-12-26 22:22:28 +0800330 << exit_reason;
Zimuzoc55a8c62019-01-07 10:19:02 +0000331 } else {
Steven Morelandabc5f882020-11-06 17:00:58 +0000332 LOG(ERROR) << "process with updatable components '" << name_
333 << "' exited 4 times " << exit_reason;
Zimuzoc55a8c62019-01-07 10:19:02 +0000334 // Notifies update_verifier and apexd
Gavin Corkery5d0deb52019-12-10 23:00:24 +0000335 SetProperty("sys.init.updatable_crashing_process_name", name_);
Nikita Ioffe018ddd72019-12-20 16:34:48 +0000336 SetProperty("sys.init.updatable_crashing", "1");
Zimuzoc55a8c62019-01-07 10:19:02 +0000337 }
Tom Cherrybac32992015-07-31 12:45:25 -0700338 }
339 } else {
340 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800341 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700342 }
343 }
344
345 flags_ &= (~SVC_RESTART);
346 flags_ |= SVC_RESTARTING;
347
348 // Execute all onrestart commands for this service.
349 onrestart_.ExecuteAllCommands();
350
351 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700352 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700353}
354
355void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700356 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700357 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
358 LOG(INFO) << " exec " << Join(args_, " ");
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700359 for (const auto& socket : sockets_) {
360 LOG(INFO) << " socket " << socket.name;
361 }
362 for (const auto& file : files_) {
363 LOG(INFO) << " file " << file.name;
364 }
Tom Cherrybac32992015-07-31 12:45:25 -0700365}
366
Tom Cherryb7349902015-08-26 11:43:36 -0700367
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700368Result<void> Service::ExecStart() {
Tom Cherry60971e62019-09-10 10:40:47 -0700369 auto reboot_on_failure = make_scope_guard([this] {
370 if (on_failure_reboot_target_) {
Tom Cherry18278d22019-11-12 16:21:20 -0800371 trigger_shutdown(*on_failure_reboot_target_);
Tom Cherry60971e62019-09-10 10:40:47 -0700372 }
373 });
374
Jiyong Park80aa4472018-11-12 12:08:41 +0900375 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
376 // Don't delay the service for ExecStart() as the semantic is that
377 // the caller might depend on the side effect of the execution.
378 return Error() << "Cannot start an updatable service '" << name_
379 << "' before configs from APEXes are all loaded";
380 }
381
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700382 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700383
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900384 if (auto result = Start(); !result.ok()) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700385 return result;
Tom Cherryb27004a2017-03-27 16:27:30 -0700386 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700387
388 flags_ |= SVC_EXEC;
389 is_exec_service_running_ = true;
390
Vic Yange01ca4d2019-05-29 15:58:32 -0700391 LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << proc_attr_.uid
392 << " gid " << proc_attr_.gid << "+" << proc_attr_.supp_gids.size() << " context "
Wei Wang2c4ee752018-06-20 14:54:52 -0700393 << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700394
Tom Cherry60971e62019-09-10 10:40:47 -0700395 reboot_on_failure.Disable();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700396 return {};
Tom Cherryb27004a2017-03-27 16:27:30 -0700397}
398
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700399Result<void> Service::Start() {
Tom Cherry60971e62019-09-10 10:40:47 -0700400 auto reboot_on_failure = make_scope_guard([this] {
401 if (on_failure_reboot_target_) {
Tom Cherry18278d22019-11-12 16:21:20 -0800402 trigger_shutdown(*on_failure_reboot_target_);
Tom Cherry60971e62019-09-10 10:40:47 -0700403 }
404 });
405
Jiyong Park80aa4472018-11-12 12:08:41 +0900406 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
407 ServiceList::GetInstance().DelayService(*this);
408 return Error() << "Cannot start an updatable service '" << name_
409 << "' before configs from APEXes are all loaded. "
410 << "Queued for execution.";
411 }
412
Tao Wu990d43c2017-10-26 10:43:10 -0700413 bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
Tom Cherrybac32992015-07-31 12:45:25 -0700414 // Starting a service removes it from the disabled or reset state and
415 // immediately takes it out of the restarting state if it was in there.
416 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700417
418 // Running processes require no additional work --- if they're in the
419 // process of exiting, we've ensured that they will immediately restart
Tao Wu990d43c2017-10-26 10:43:10 -0700420 // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
421 // stopping status, we just set SVC_RESTART flag so it will get restarted
422 // in Reap().
Tom Cherrybac32992015-07-31 12:45:25 -0700423 if (flags_ & SVC_RUNNING) {
Tao Wu990d43c2017-10-26 10:43:10 -0700424 if ((flags_ & SVC_ONESHOT) && disabled) {
425 flags_ |= SVC_RESTART;
426 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700427 // It is not an error to try to start a service that is already running.
Tom Cherry60971e62019-09-10 10:40:47 -0700428 reboot_on_failure.Disable();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700429 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700430 }
431
432 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200433 if (needs_console) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700434 if (proc_attr_.console.empty()) {
Tom Cherryff88e302019-06-26 14:20:53 -0700435 proc_attr_.console = "/dev/" + GetProperty("ro.boot.console", "console");
Viorel Suman70daa672016-03-21 10:08:07 +0200436 }
437
Adrian Salido24ef8602016-12-20 15:52:15 -0800438 // Make sure that open call succeeds to ensure a console driver is
439 // properly registered for the device node
Vic Yange01ca4d2019-05-29 15:58:32 -0700440 int console_fd = open(proc_attr_.console.c_str(), O_RDWR | O_CLOEXEC);
Adrian Salido24ef8602016-12-20 15:52:15 -0800441 if (console_fd < 0) {
Viorel Suman70daa672016-03-21 10:08:07 +0200442 flags_ |= SVC_DISABLED;
Vic Yange01ca4d2019-05-29 15:58:32 -0700443 return ErrnoError() << "Couldn't open console '" << proc_attr_.console << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200444 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800445 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700446 }
447
448 struct stat sb;
449 if (stat(args_[0].c_str(), &sb) == -1) {
Tom Cherrybac32992015-07-31 12:45:25 -0700450 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700451 return ErrnoError() << "Cannot find '" << args_[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700452 }
453
Tom Cherrybac32992015-07-31 12:45:25 -0700454 std::string scon;
455 if (!seclabel_.empty()) {
456 scon = seclabel_;
457 } else {
Tom Cherryaead51b2018-04-20 16:18:12 -0700458 auto result = ComputeContextFromExecutable(args_[0]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900459 if (!result.ok()) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700460 return result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700461 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700462 scon = *result;
Tom Cherrybac32992015-07-31 12:45:25 -0700463 }
464
Martin Stjernholmcacf0432019-08-21 18:34:31 +0100465 if (!AreRuntimeApexesReady() && !pre_apexd_) {
466 // If this service is started before the Runtime and ART APEXes get
467 // available, mark it as pre-apexd one. Note that this marking is
468 // permanent. So for example, if the service is re-launched (e.g., due
469 // to crash), it is still recognized as pre-apexd... for consistency.
Jiyong Park68660412019-01-16 23:00:59 +0900470 pre_apexd_ = true;
471 }
472
Jooyung Han4f23d5a2020-06-09 13:44:17 +0900473 // For pre-apexd services, override mount namespace as "bootstrap" one before starting.
474 // Note: "ueventd" is supposed to be run in "default" mount namespace even if it's pre-apexd
475 // to support loading firmwares from APEXes.
476 std::optional<MountNamespace> override_mount_namespace;
477 if (name_ == "ueventd") {
478 override_mount_namespace = NS_DEFAULT;
479 } else if (pre_apexd_) {
480 override_mount_namespace = NS_BOOTSTRAP;
481 }
482
Martijn Coenen70788f92019-04-23 16:26:01 +0200483 post_data_ = ServiceList::GetInstance().IsPostData();
484
Wei Wanga285dac2016-10-04 14:05:39 -0700485 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700486
Tom Cherry5241d102019-09-10 14:20:35 -0700487 std::vector<Descriptor> descriptors;
488 for (const auto& socket : sockets_) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900489 if (auto result = socket.Create(scon); result.ok()) {
Tom Cherry5241d102019-09-10 14:20:35 -0700490 descriptors.emplace_back(std::move(*result));
491 } else {
492 LOG(INFO) << "Could not create socket '" << socket.name << "': " << result.error();
493 }
494 }
495
496 for (const auto& file : files_) {
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900497 if (auto result = file.Create(); result.ok()) {
Tom Cherry5241d102019-09-10 14:20:35 -0700498 descriptors.emplace_back(std::move(*result));
499 } else {
500 LOG(INFO) << "Could not open file '" << file.name << "': " << result.error();
501 }
502 }
503
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700504 pid_t pid = -1;
Vic Yange01ca4d2019-05-29 15:58:32 -0700505 if (namespaces_.flags) {
506 pid = clone(nullptr, nullptr, namespaces_.flags | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700507 } else {
508 pid = fork();
509 }
510
Tom Cherrybac32992015-07-31 12:45:25 -0700511 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700512 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700513
Jooyung Han4f23d5a2020-06-09 13:44:17 +0900514 if (auto result = EnterNamespaces(namespaces_, name_, override_mount_namespace);
515 !result.ok()) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700516 LOG(FATAL) << "Service '" << name_
517 << "' failed to set up namespaces: " << result.error();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700518 }
519
Tom Cherry6de21f12017-08-22 15:41:03 -0700520 for (const auto& [key, value] : environment_vars_) {
521 setenv(key.c_str(), value.c_str(), 1);
Tom Cherrybac32992015-07-31 12:45:25 -0700522 }
523
Tom Cherry5241d102019-09-10 14:20:35 -0700524 for (const auto& descriptor : descriptors) {
525 descriptor.Publish();
Tom Cherry2e4c85f2019-07-09 13:33:36 -0700526 }
Tom Cherrybac32992015-07-31 12:45:25 -0700527
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900528 if (auto result = WritePidToFiles(&writepid_files_); !result.ok()) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700529 LOG(ERROR) << "failed to write pid to files: " << result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700530 }
531
Suren Baghdasaryanc9c0bba2020-04-30 11:58:39 -0700532 if (task_profiles_.size() > 0 && !SetTaskProfiles(getpid(), task_profiles_)) {
533 LOG(ERROR) << "failed to set task profiles";
534 }
535
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400536 // As requested, set our gid, supplemental gids, uid, context, and
537 // priority. Aborts on failure.
Vic Yange01ca4d2019-05-29 15:58:32 -0700538 SetProcessAttributesAndCaps();
Tom Cherrybac32992015-07-31 12:45:25 -0700539
Tom Cherry8f380482018-04-17 14:48:44 -0700540 if (!ExpandArgsAndExecv(args_, sigstop_)) {
Tom Cherry93280212019-09-26 15:24:40 -0700541 PLOG(ERROR) << "cannot execv('" << args_[0]
542 << "'). See the 'Debugging init' section of init's README.md for tips";
Tom Cherrybac32992015-07-31 12:45:25 -0700543 }
544
545 _exit(127);
546 }
547
548 if (pid < 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700549 pid_ = 0;
Tom Cherry76af7e62017-08-22 16:13:59 -0700550 return ErrnoError() << "Failed to fork";
Tom Cherrybac32992015-07-31 12:45:25 -0700551 }
552
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700553 if (oom_score_adjust_ != DEFAULT_OOM_SCORE_ADJUST) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700554 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700555 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
556 if (!WriteStringToFile(oom_str, oom_file)) {
Elliott Hughes076305e2019-03-08 12:34:53 -0800557 PLOG(ERROR) << "couldn't write oom_score_adj";
Marco Nelissen310f6702016-07-22 12:07:06 -0700558 }
559 }
560
Elliott Hughes9605a942016-11-10 17:43:47 -0800561 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700562 pid_ = pid;
563 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -0700564 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -0700565 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700566
Peter Collingbourned7157c22018-10-30 15:49:33 -0700567 bool use_memcg = swappiness_ != -1 || soft_limit_in_bytes_ != -1 || limit_in_bytes_ != -1 ||
568 limit_percent_ != -1 || !limit_property_.empty();
Vic Yange01ca4d2019-05-29 15:58:32 -0700569 errno = -createProcessGroup(proc_attr_.uid, pid_, use_memcg);
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700570 if (errno != 0) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700571 PLOG(ERROR) << "createProcessGroup(" << proc_attr_.uid << ", " << pid_
572 << ") failed for service '" << name_ << "'";
Peter Collingbourned7157c22018-10-30 15:49:33 -0700573 } else if (use_memcg) {
Robert Benead4852262017-07-16 19:38:11 -0700574 if (swappiness_ != -1) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700575 if (!setProcessGroupSwappiness(proc_attr_.uid, pid_, swappiness_)) {
Robert Benead4852262017-07-16 19:38:11 -0700576 PLOG(ERROR) << "setProcessGroupSwappiness failed";
577 }
578 }
579
580 if (soft_limit_in_bytes_ != -1) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700581 if (!setProcessGroupSoftLimit(proc_attr_.uid, pid_, soft_limit_in_bytes_)) {
Robert Benead4852262017-07-16 19:38:11 -0700582 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
583 }
584 }
585
Peter Collingbourned7157c22018-10-30 15:49:33 -0700586 size_t computed_limit_in_bytes = limit_in_bytes_;
587 if (limit_percent_ != -1) {
588 long page_size = sysconf(_SC_PAGESIZE);
589 long num_pages = sysconf(_SC_PHYS_PAGES);
590 if (page_size > 0 && num_pages > 0) {
591 size_t max_mem = SIZE_MAX;
592 if (size_t(num_pages) < SIZE_MAX / size_t(page_size)) {
593 max_mem = size_t(num_pages) * size_t(page_size);
594 }
595 computed_limit_in_bytes =
596 std::min(computed_limit_in_bytes, max_mem / 100 * limit_percent_);
597 }
598 }
599
600 if (!limit_property_.empty()) {
601 // This ends up overwriting computed_limit_in_bytes but only if the
602 // property is defined.
603 computed_limit_in_bytes = android::base::GetUintProperty(
604 limit_property_, computed_limit_in_bytes, SIZE_MAX);
605 }
606
607 if (computed_limit_in_bytes != size_t(-1)) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700608 if (!setProcessGroupLimit(proc_attr_.uid, pid_, computed_limit_in_bytes)) {
Robert Benead4852262017-07-16 19:38:11 -0700609 PLOG(ERROR) << "setProcessGroupLimit failed";
610 }
611 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700612 }
Tom Cherrybac32992015-07-31 12:45:25 -0700613
Suren Baghdasaryanc29c2ba2019-10-22 17:18:42 -0700614 if (oom_score_adjust_ != DEFAULT_OOM_SCORE_ADJUST) {
615 LmkdRegister(name_, proc_attr_.uid, pid_, oom_score_adjust_);
616 }
617
Tom Cherrybac32992015-07-31 12:45:25 -0700618 NotifyStateChange("running");
Tom Cherry60971e62019-09-10 10:40:47 -0700619 reboot_on_failure.Disable();
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700620 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700621}
622
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700623Result<void> Service::StartIfNotDisabled() {
Tom Cherrybac32992015-07-31 12:45:25 -0700624 if (!(flags_ & SVC_DISABLED)) {
625 return Start();
626 } else {
627 flags_ |= SVC_DISABLED_START;
628 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700629 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700630}
631
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700632Result<void> Service::Enable() {
Tom Cherrybac32992015-07-31 12:45:25 -0700633 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
634 if (flags_ & SVC_DISABLED_START) {
635 return Start();
636 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700637 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700638}
639
640void Service::Reset() {
641 StopOrReset(SVC_RESET);
642}
643
Martijn Coenen70788f92019-04-23 16:26:01 +0200644void Service::ResetIfPostData() {
645 if (post_data_) {
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200646 if (flags_ & SVC_RUNNING) {
647 running_at_post_data_reset_ = true;
648 }
Martijn Coenen70788f92019-04-23 16:26:01 +0200649 StopOrReset(SVC_RESET);
650 }
651}
652
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700653Result<void> Service::StartIfPostData() {
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200654 // Start the service, but only if it was started after /data was mounted,
655 // and it was still running when we reset the post-data services.
656 if (running_at_post_data_reset_) {
657 return Start();
658 }
659
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700660 return {};
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200661}
662
Tom Cherrybac32992015-07-31 12:45:25 -0700663void Service::Stop() {
664 StopOrReset(SVC_DISABLED);
665}
666
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800667void Service::Terminate() {
668 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
669 flags_ |= SVC_DISABLED;
670 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700671 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800672 NotifyStateChange("stopping");
673 }
674}
675
Tom Cherry73f535e2018-09-27 16:10:46 -0700676void Service::Timeout() {
677 // All process state flags will be taken care of in Reap(), we really just want to kill the
678 // process here when it times out. Oneshot processes will transition to be disabled, and
679 // all other processes will transition to be restarting.
680 LOG(INFO) << "Service '" << name_ << "' expired its timeout of " << timeout_period_->count()
681 << " seconds and will now be killed";
682 if (pid_) {
683 KillProcessGroup(SIGKILL);
684 NotifyStateChange("stopping");
685 }
686}
687
Tom Cherrybac32992015-07-31 12:45:25 -0700688void Service::Restart() {
689 if (flags_ & SVC_RUNNING) {
690 /* Stop, wait, then start the service. */
691 StopOrReset(SVC_RESTART);
692 } else if (!(flags_ & SVC_RESTARTING)) {
693 /* Just start the service since it's not running. */
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900694 if (auto result = Start(); !result.ok()) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700695 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
696 }
Tom Cherrybac32992015-07-31 12:45:25 -0700697 } /* else: Service is restarting anyways. */
698}
699
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700700// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700701void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700702 // The service is still SVC_RUNNING until its process exits, but if it has
703 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700704 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
705
706 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700707 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700708 how = SVC_DISABLED;
709 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700710
711 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700712 if (how == SVC_RESET) {
713 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
714 } else {
715 flags_ |= how;
716 }
Tao Wu84b856d2017-10-27 11:29:13 -0700717 // Make sure it's in right status when a restart immediately follow a
718 // stop/reset or vice versa.
719 if (how == SVC_RESTART) {
720 flags_ &= (~(SVC_DISABLED | SVC_RESET));
721 } else {
722 flags_ &= (~SVC_RESTART);
723 }
Tom Cherrybac32992015-07-31 12:45:25 -0700724
725 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700726 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700727 NotifyStateChange("stopping");
728 } else {
729 NotifyStateChange("stopped");
730 }
731}
732
Tom Cherry4772f1d2019-07-30 09:34:41 -0700733Result<std::unique_ptr<Service>> Service::MakeTemporaryOneshotService(
734 const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700735 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
736 // SECLABEL can be a - to denote default
737 std::size_t command_arg = 1;
738 for (std::size_t i = 1; i < args.size(); ++i) {
739 if (args[i] == "--") {
740 command_arg = i + 1;
741 break;
742 }
743 }
744 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700745 return Error() << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -0700746 }
747
748 if (command_arg >= args.size()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700749 return Error() << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -0700750 }
751 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
752
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700753 static size_t exec_count = 0;
754 exec_count++;
755 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -0700756
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700757 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700758 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700759
760 std::string seclabel = "";
761 if (command_arg > 2 && args[1] != "-") {
762 seclabel = args[1];
763 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700764 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700765 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700766 uid = DecodeUid(args[2]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900767 if (!uid.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700768 return Error() << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700769 }
Tom Cherrybac32992015-07-31 12:45:25 -0700770 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700771 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700772 std::vector<gid_t> supp_gids;
773 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700774 gid = DecodeUid(args[3]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900775 if (!gid.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700776 return Error() << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700777 }
Tom Cherrybac32992015-07-31 12:45:25 -0700778 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
779 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700780 auto supp_gid = DecodeUid(args[4 + i]);
Bernie Innocenticecebbb2020-02-06 03:49:33 +0900781 if (!supp_gid.ok()) {
Tom Cherry4772f1d2019-07-30 09:34:41 -0700782 return Error() << "Unable to decode GID for '" << args[4 + i]
783 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700784 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700785 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700786 }
787 }
788
Tom Cherry1cd082d2019-02-06 10:45:56 -0800789 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, namespace_flags, seclabel,
Nikita Ioffe091c4d12019-12-05 12:35:19 +0000790 nullptr, str_args, false);
Tom Cherrybac32992015-07-31 12:45:25 -0700791}
792
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700793} // namespace init
794} // namespace android