blob: 4ac4571f244076279f55bcc038cac82b8dfe8c78 [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>
Mark Salyzyneca25072018-05-16 15:10:24 -070021#include <linux/input.h>
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -040022#include <linux/securebits.h>
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070023#include <sched.h>
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070024#include <sys/prctl.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070025#include <sys/resource.h>
Tom Cherrybac32992015-07-31 12:45:25 -070026#include <sys/stat.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070027#include <sys/time.h>
Tom Cherrybac32992015-07-31 12:45:25 -070028#include <termios.h>
Dan Albertaf9ba4d2015-08-11 16:37:04 -070029#include <unistd.h>
Tom Cherrybac32992015-07-31 12:45:25 -070030
Elliott Hughes4f713192015-12-04 22:00:26 -080031#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070032#include <android-base/logging.h>
Elliott Hughesda46b392016-10-11 17:09:00 -070033#include <android-base/parseint.h>
Elliott Hughesdc803122018-05-24 18:00:39 -070034#include <android-base/properties.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080035#include <android-base/stringprintf.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070036#include <android-base/strings.h>
Steven Morelande055d732017-10-05 18:50:22 -070037#include <hidl-util/FQName.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070038#include <processgroup/processgroup.h>
39#include <selinux/selinux.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070040#include <system/thread_defs.h>
Tom Cherrybac32992015-07-31 12:45:25 -070041
Tom Cherry7ac013d2017-08-25 10:39:25 -070042#include "rlimit_parser.h"
Tom Cherry2aeb1ad2019-06-26 10:46:20 -070043#include "service_list.h"
Tom Cherrybac32992015-07-31 12:45:25 -070044#include "util.h"
45
Tom Cherryde6bd502018-02-13 16:50:08 -080046#if defined(__ANDROID__)
Jiyong Parkd7f7c202019-05-10 21:12:15 +090047#include <ApexProperties.sysprop.h>
Tom Cherry40acb372018-08-01 13:41:12 -070048#include <android/api-level.h>
Tom Cherryde6bd502018-02-13 16:50:08 -080049#include <sys/system_properties.h>
50
Tom Cherryde6bd502018-02-13 16:50:08 -080051#include "init.h"
Jiyong Park68660412019-01-16 23:00:59 +090052#include "mount_namespace.h"
Tom Cherryde6bd502018-02-13 16:50:08 -080053#include "property_service.h"
Tom Cherry40acb372018-08-01 13:41:12 -070054#include "selinux.h"
Tom Cherryde6bd502018-02-13 16:50:08 -080055#else
56#include "host_init_stubs.h"
57#endif
58
James Hawkinse78ea772017-03-24 11:43:02 -070059using android::base::boot_clock;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070060using android::base::GetProperty;
61using android::base::Join;
Elliott Hughesda46b392016-10-11 17:09:00 -070062using android::base::ParseInt;
Tom Cherry79166842018-10-16 10:58:06 -070063using android::base::Split;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070064using android::base::StartsWith;
Tom Cherryb7349902015-08-26 11:43:36 -070065using android::base::StringPrintf;
66using android::base::WriteStringToFile;
67
Tom Cherry81f5d3e2017-06-22 12:53:17 -070068namespace android {
69namespace init {
70
Tom Cherryaead51b2018-04-20 16:18:12 -070071static Result<std::string> ComputeContextFromExecutable(const std::string& service_path) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040072 std::string computed_context;
73
74 char* raw_con = nullptr;
75 char* raw_filecon = nullptr;
76
77 if (getcon(&raw_con) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070078 return Error() << "Could not get security context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040079 }
80 std::unique_ptr<char> mycon(raw_con);
81
82 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070083 return Error() << "Could not get file context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040084 }
85 std::unique_ptr<char> filecon(raw_filecon);
86
87 char* new_con = nullptr;
88 int rc = security_compute_create(mycon.get(), filecon.get(),
89 string_to_security_class("process"), &new_con);
90 if (rc == 0) {
91 computed_context = new_con;
92 free(new_con);
93 }
94 if (rc == 0 && computed_context == mycon.get()) {
Nick Kralevich1ea19eb2017-08-25 12:08:57 -070095 return Error() << "File " << service_path << "(labeled \"" << filecon.get()
96 << "\") has incorrect label or no domain transition from " << mycon.get()
97 << " to another SELinux domain defined. Have you configured your "
98 "service correctly? https://source.android.com/security/selinux/"
99 "device-policy#label_new_services_and_address_denials";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400100 }
101 if (rc < 0) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700102 return Error() << "Could not get process context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400103 }
104 return computed_context;
105}
106
Tom Cherry8f380482018-04-17 14:48:44 -0700107static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400108 std::vector<std::string> expanded_args;
Tom Cherry5e405ca2017-09-11 16:08:54 -0700109 std::vector<char*> c_strings;
110
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400111 expanded_args.resize(args.size());
Tom Cherry5e405ca2017-09-11 16:08:54 -0700112 c_strings.push_back(const_cast<char*>(args[0].data()));
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400113 for (std::size_t i = 1; i < args.size(); ++i) {
114 if (!expand_props(args[i], &expanded_args[i])) {
115 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
116 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700117 c_strings.push_back(expanded_args[i].data());
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400118 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700119 c_strings.push_back(nullptr);
120
Tom Cherry8f380482018-04-17 14:48:44 -0700121 if (sigstop) {
122 kill(getpid(), SIGSTOP);
123 }
124
Tom Cherry5e405ca2017-09-11 16:08:54 -0700125 return execv(c_strings[0], c_strings.data()) == 0;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400126}
127
Jiyong Park68660412019-01-16 23:00:59 +0900128static bool IsRuntimeApexReady() {
129 struct stat buf;
130 return stat("/apex/com.android.runtime/", &buf) == 0;
131}
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,
137 const std::vector<std::string>& args)
Tom Cherry1cd082d2019-02-06 10:45:56 -0800138 : Service(name, 0, 0, 0, {}, 0, "", subcontext_for_restart_commands, args) {}
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 Cherry1cd082d2019-02-06 10:45:56 -0800141 const std::vector<gid_t>& supp_gids, unsigned namespace_flags,
142 const std::string& seclabel, Subcontext* subcontext_for_restart_commands,
143 const std::vector<std::string>& args)
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", {}),
Wei Wang641ff0a2017-03-27 10:59:11 -0700159 oom_score_adjust_(-1000),
Tom Cherry59383792017-07-26 16:09:09 -0700160 start_order_(0),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800161 args_(args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700162
163void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700164 if ((flags_ & SVC_TEMPORARY) != 0) {
165 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700166 return;
167 }
168
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700169 std::string prop_name = "init.svc." + name_;
170 property_set(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800171
172 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800173 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherryfed33732017-08-18 10:47:46 -0700174 std::string boottime_property = "ro.boottime." + name_;
175 if (GetProperty(boottime_property, "").empty()) {
176 property_set(boottime_property, std::to_string(start_ns));
177 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800178 }
Tom Cherrybac32992015-07-31 12:45:25 -0700179}
180
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700181void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700182 // If we've already seen a successful result from killProcessGroup*(), then we have removed
183 // the cgroup already and calling these functions a second time will simply result in an error.
184 // This is true regardless of which signal was sent.
185 // These functions handle their own logging, so no additional logging is needed.
186 if (!process_cgroup_empty_) {
187 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
188 << ") process group...";
189 int r;
190 if (signal == SIGTERM) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700191 r = killProcessGroupOnce(proc_attr_.uid, pid_, signal);
Tom Cherry33838b12017-05-04 11:32:36 -0700192 } else {
Vic Yange01ca4d2019-05-29 15:58:32 -0700193 r = killProcessGroup(proc_attr_.uid, pid_, signal);
Tom Cherry33838b12017-05-04 11:32:36 -0700194 }
195
196 if (r == 0) process_cgroup_empty_ = true;
197 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700198}
199
Vic Yange01ca4d2019-05-29 15:58:32 -0700200void Service::SetProcessAttributesAndCaps() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400201 // Keep capabilites on uid change.
Vic Yange01ca4d2019-05-29 15:58:32 -0700202 if (capabilities_ && proc_attr_.uid) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700203 // If Android is running in a container, some securebits might already
204 // be locked, so don't change those.
Ben Fennemaa7243602017-07-25 14:37:21 -0700205 unsigned long securebits = prctl(PR_GET_SECUREBITS);
206 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700207 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
208 }
209 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
210 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
211 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400212 }
213 }
214
Vic Yange01ca4d2019-05-29 15:58:32 -0700215 if (auto result = SetProcessAttributes(proc_attr_); !result) {
216 LOG(FATAL) << "cannot set attribute for " << name_ << ": " << result.error();
217 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400218
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400219 if (!seclabel_.empty()) {
220 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700221 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400222 }
223 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700224
Tom Cherry1cd082d2019-02-06 10:45:56 -0800225 if (capabilities_) {
226 if (!SetCapsForExec(*capabilities_)) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400227 LOG(FATAL) << "cannot set capabilities for " << name_;
228 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700229 } else if (proc_attr_.uid) {
Luis Hector Chavez94fb5b02017-11-16 15:52:00 -0800230 // Inheritable caps can be non-zero when running in a container.
231 if (!DropInheritableCaps()) {
232 LOG(FATAL) << "cannot drop inheritable caps for " << name_;
233 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400234 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400235}
236
Paul Crowleyc73b2152018-04-13 17:38:57 +0000237void Service::Reap(const siginfo_t& siginfo) {
Tom Cherrybac32992015-07-31 12:45:25 -0700238 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700239 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700240 }
241
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700242 // Remove any descriptor resources we may have created.
243 std::for_each(descriptors_.begin(), descriptors_.end(),
244 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700245
Paul Crowleyc73b2152018-04-13 17:38:57 +0000246 for (const auto& f : reap_callbacks_) {
247 f(siginfo);
248 }
249
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700250 if (flags_ & SVC_EXEC) UnSetExec();
251
252 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700253
254 pid_ = 0;
255 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700256 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700257
258 // Oneshot processes go into the disabled state on exit,
259 // except when manually restarted.
Martijn Coenen70788f92019-04-23 16:26:01 +0200260 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART) && !(flags_ & SVC_RESET)) {
Tom Cherrybac32992015-07-31 12:45:25 -0700261 flags_ |= SVC_DISABLED;
262 }
263
264 // Disabled and reset processes do not get restarted automatically.
265 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
266 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700267 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700268 }
269
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900270#if defined(__ANDROID__)
271 static bool is_apex_updatable = android::sysprop::ApexProperties::updatable().value_or(false);
272#else
273 static bool is_apex_updatable = false;
274#endif
275 const bool is_process_updatable = !pre_apexd_ && is_apex_updatable;
276
Zimuzo88de80f2019-04-27 21:10:35 +0100277 // If we crash > 4 times in 4 minutes or before boot_completed,
278 // reboot into bootloader or set crashing property
Elliott Hughes9605a942016-11-10 17:43:47 -0800279 boot_clock::time_point now = boot_clock::now();
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900280 if (((flags_ & SVC_CRITICAL) || is_process_updatable) && !(flags_ & SVC_RESTART)) {
Zimuzo88de80f2019-04-27 21:10:35 +0100281 bool boot_completed = android::base::GetBoolProperty("sys.boot_completed", false);
282 if (now < time_crashed_ + 4min || !boot_completed) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800283 if (++crash_count_ > 4) {
Zimuzoc55a8c62019-01-07 10:19:02 +0000284 if (flags_ & SVC_CRITICAL) {
285 // Aborts into bootloader
Zimuzo88de80f2019-04-27 21:10:35 +0100286 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times "
287 << (boot_completed ? "in 4 minutes" : "before boot completed");
Zimuzoc55a8c62019-01-07 10:19:02 +0000288 } else {
Zimuzo88de80f2019-04-27 21:10:35 +0100289 LOG(ERROR) << "updatable process '" << name_ << "' exited 4 times "
290 << (boot_completed ? "in 4 minutes" : "before boot completed");
Zimuzoc55a8c62019-01-07 10:19:02 +0000291 // Notifies update_verifier and apexd
292 property_set("ro.init.updatable_crashing", "1");
293 }
Tom Cherrybac32992015-07-31 12:45:25 -0700294 }
295 } else {
296 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800297 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700298 }
299 }
300
301 flags_ &= (~SVC_RESTART);
302 flags_ |= SVC_RESTARTING;
303
304 // Execute all onrestart commands for this service.
305 onrestart_.ExecuteAllCommands();
306
307 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700308 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700309}
310
311void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700312 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700313 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
314 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700315 std::for_each(descriptors_.begin(), descriptors_.end(),
316 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700317}
318
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700319Result<void> Service::ParseCapabilities(std::vector<std::string>&& args) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400320 capabilities_ = 0;
321
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500322 if (!CapAmbientSupported()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700323 return Error()
324 << "capabilities requested but the kernel does not support ambient capabilities";
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500325 }
326
327 unsigned int last_valid_cap = GetLastValidCap();
Tom Cherry1cd082d2019-02-06 10:45:56 -0800328 if (last_valid_cap >= capabilities_->size()) {
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500329 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
330 }
331
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400332 for (size_t i = 1; i < args.size(); i++) {
333 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500334 int res = LookupCap(arg);
335 if (res < 0) {
Tom Cherryf4db2aa2019-06-14 14:54:02 -0700336 return Errorf("invalid capability '{}'", arg);
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400337 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500338 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
339 if (cap > last_valid_cap) {
Tom Cherryf4db2aa2019-06-14 14:54:02 -0700340 return Errorf("capability '{}' not supported by the kernel", arg);
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500341 }
Tom Cherry1cd082d2019-02-06 10:45:56 -0800342 (*capabilities_)[cap] = true;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400343 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700344 return {};
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400345}
346
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700347Result<void> Service::ParseClass(std::vector<std::string>&& args) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700348 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700349 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700350}
Tom Cherrybac32992015-07-31 12:45:25 -0700351
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700352Result<void> Service::ParseConsole(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700353 flags_ |= SVC_CONSOLE;
Vic Yange01ca4d2019-05-29 15:58:32 -0700354 proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700355 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700356}
Tom Cherrybac32992015-07-31 12:45:25 -0700357
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700358Result<void> Service::ParseCritical(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700359 flags_ |= SVC_CRITICAL;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700360 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700361}
Tom Cherrybac32992015-07-31 12:45:25 -0700362
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700363Result<void> Service::ParseDisabled(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700364 flags_ |= SVC_DISABLED;
365 flags_ |= SVC_RC_DISABLED;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700366 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700367}
Tom Cherrybac32992015-07-31 12:45:25 -0700368
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700369Result<void> Service::ParseEnterNamespace(std::vector<std::string>&& args) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700370 if (args[1] != "net") {
371 return Error() << "Init only supports entering network namespaces";
372 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700373 if (!namespaces_.namespaces_to_enter.empty()) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700374 return Error() << "Only one network namespace may be entered";
375 }
376 // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
377 // present. Therefore, they also require mount namespaces.
Vic Yange01ca4d2019-05-29 15:58:32 -0700378 namespaces_.flags |= CLONE_NEWNS;
379 namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700380 return {};
Tom Cherryaead51b2018-04-20 16:18:12 -0700381}
382
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700383Result<void> Service::ParseGroup(std::vector<std::string>&& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700384 auto gid = DecodeUid(args[1]);
385 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700386 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700387 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700388 proc_attr_.gid = *gid;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700389
Tom Cherryb7349902015-08-26 11:43:36 -0700390 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700391 gid = DecodeUid(args[n]);
392 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700393 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700394 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700395 proc_attr_.supp_gids.emplace_back(*gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700396 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700397 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700398}
399
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700400Result<void> Service::ParsePriority(std::vector<std::string>&& args) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700401 proc_attr_.priority = 0;
402 if (!ParseInt(args[1], &proc_attr_.priority,
403 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800404 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Tom Cherryf4db2aa2019-06-14 14:54:02 -0700405 return Errorf("process priority value must be range {} - {}", ANDROID_PRIORITY_HIGHEST,
406 ANDROID_PRIORITY_LOWEST);
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700407 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700408 return {};
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700409}
410
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700411Result<void> Service::ParseInterface(std::vector<std::string>&& args) {
Steven Morelande055d732017-10-05 18:50:22 -0700412 const std::string& interface_name = args[1];
413 const std::string& instance_name = args[2];
414
Steven Moreland422367b2018-03-06 14:57:46 -0800415 FQName fq_name;
416 if (!FQName::parse(interface_name, &fq_name)) {
Steven Morelande055d732017-10-05 18:50:22 -0700417 return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
418 }
419
420 if (!fq_name.isFullyQualified()) {
421 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
422 }
423
424 if (fq_name.isValidValueName()) {
425 return Error() << "Interface name must not be a value name '" << interface_name << "'";
426 }
427
428 const std::string fullname = interface_name + "/" + instance_name;
429
430 for (const auto& svc : ServiceList::GetInstance()) {
431 if (svc->interfaces().count(fullname) > 0) {
432 return Error() << "Interface '" << fullname << "' redefined in " << name()
433 << " but is already defined by " << svc->name();
434 }
435 }
436
437 interfaces_.insert(fullname);
438
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700439 return {};
Steven Morelande055d732017-10-05 18:50:22 -0700440}
441
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700442Result<void> Service::ParseIoprio(std::vector<std::string>&& args) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700443 if (!ParseInt(args[2], &proc_attr_.ioprio_pri, 0, 7)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700444 return Error() << "priority value must be range 0 - 7";
Tom Cherryb7349902015-08-26 11:43:36 -0700445 }
446
447 if (args[1] == "rt") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700448 proc_attr_.ioprio_class = IoSchedClass_RT;
Tom Cherryb7349902015-08-26 11:43:36 -0700449 } else if (args[1] == "be") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700450 proc_attr_.ioprio_class = IoSchedClass_BE;
Tom Cherryb7349902015-08-26 11:43:36 -0700451 } else if (args[1] == "idle") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700452 proc_attr_.ioprio_class = IoSchedClass_IDLE;
Tom Cherryb7349902015-08-26 11:43:36 -0700453 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700454 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
Tom Cherryb7349902015-08-26 11:43:36 -0700455 }
456
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700457 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700458}
459
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700460Result<void> Service::ParseKeycodes(std::vector<std::string>&& args) {
Tom Cherry79166842018-10-16 10:58:06 -0700461 auto it = args.begin() + 1;
462 if (args.size() == 2 && StartsWith(args[1], "$")) {
463 std::string expanded;
464 if (!expand_props(args[1], &expanded)) {
465 return Error() << "Could not expand property '" << args[1] << "'";
466 }
467
468 // If the property is not set, it defaults to none, in which case there are no keycodes
469 // for this service.
470 if (expanded == "none") {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700471 return {};
Tom Cherry79166842018-10-16 10:58:06 -0700472 }
473
474 args = Split(expanded, ",");
475 it = args.begin();
476 }
477
478 for (; it != args.end(); ++it) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700479 int code;
Tom Cherry79166842018-10-16 10:58:06 -0700480 if (ParseInt(*it, &code, 0, KEY_MAX)) {
Mark Salyzyneca25072018-05-16 15:10:24 -0700481 for (auto& key : keycodes_) {
Tom Cherry79166842018-10-16 10:58:06 -0700482 if (key == code) return Error() << "duplicate keycode: " << *it;
Mark Salyzyneca25072018-05-16 15:10:24 -0700483 }
Mark Salyzyn13857252018-05-18 15:25:15 -0700484 keycodes_.insert(std::upper_bound(keycodes_.begin(), keycodes_.end(), code), code);
Elliott Hughesda46b392016-10-11 17:09:00 -0700485 } else {
Tom Cherry79166842018-10-16 10:58:06 -0700486 return Error() << "invalid keycode: " << *it;
Elliott Hughesda46b392016-10-11 17:09:00 -0700487 }
Tom Cherryb7349902015-08-26 11:43:36 -0700488 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700489 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700490}
491
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700492Result<void> Service::ParseOneshot(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700493 flags_ |= SVC_ONESHOT;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700494 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700495}
496
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700497Result<void> Service::ParseOnrestart(std::vector<std::string>&& args) {
Tom Cherry018a4382018-10-17 11:11:23 -0700498 args.erase(args.begin());
Tom Cherry012c5732017-04-18 13:21:54 -0700499 int line = onrestart_.NumCommands() + 1;
Tom Cherry018a4382018-10-17 11:11:23 -0700500 if (auto result = onrestart_.AddCommand(std::move(args), line); !result) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700501 return Error() << "cannot add Onrestart command: " << result.error();
502 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700503 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700504}
505
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700506Result<void> Service::ParseNamespace(std::vector<std::string>&& args) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700507 for (size_t i = 1; i < args.size(); i++) {
508 if (args[i] == "pid") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700509 namespaces_.flags |= CLONE_NEWPID;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700510 // PID namespaces require mount namespaces.
Vic Yange01ca4d2019-05-29 15:58:32 -0700511 namespaces_.flags |= CLONE_NEWNS;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700512 } else if (args[i] == "mnt") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700513 namespaces_.flags |= CLONE_NEWNS;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700514 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700515 return Error() << "namespace must be 'pid' or 'mnt'";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700516 }
517 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700518 return {};
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700519}
520
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700521Result<void> Service::ParseOomScoreAdjust(std::vector<std::string>&& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700522 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700523 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
Marco Nelissen310f6702016-07-22 12:07:06 -0700524 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700525 return {};
Marco Nelissen310f6702016-07-22 12:07:06 -0700526}
527
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700528Result<void> Service::ParseOverride(std::vector<std::string>&& args) {
Steven Moreland6f5333a2017-11-13 15:31:54 -0800529 override_ = true;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700530 return {};
Steven Moreland6f5333a2017-11-13 15:31:54 -0800531}
532
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700533Result<void> Service::ParseMemcgSwappiness(std::vector<std::string>&& args) {
Robert Benead4852262017-07-16 19:38:11 -0700534 if (!ParseInt(args[1], &swappiness_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700535 return Error() << "swappiness value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700536 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700537 return {};
Robert Benead4852262017-07-16 19:38:11 -0700538}
539
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700540Result<void> Service::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
Robert Benead4852262017-07-16 19:38:11 -0700541 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700542 return Error() << "limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700543 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700544 return {};
Robert Benead4852262017-07-16 19:38:11 -0700545}
546
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700547Result<void> Service::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700548 if (!ParseInt(args[1], &limit_percent_, 0)) {
549 return Error() << "limit_percent value must be equal or greater than 0";
550 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700551 return {};
Peter Collingbourned7157c22018-10-30 15:49:33 -0700552}
553
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700554Result<void> Service::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700555 limit_property_ = std::move(args[1]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700556 return {};
Peter Collingbourned7157c22018-10-30 15:49:33 -0700557}
558
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700559Result<void> Service::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
Robert Benead4852262017-07-16 19:38:11 -0700560 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700561 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700562 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700563 return {};
Robert Benead4852262017-07-16 19:38:11 -0700564}
565
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700566Result<void> Service::ParseProcessRlimit(std::vector<std::string>&& args) {
Tom Cherry7ac013d2017-08-25 10:39:25 -0700567 auto rlimit = ParseRlimit(args);
568 if (!rlimit) return rlimit.error();
569
Vic Yange01ca4d2019-05-29 15:58:32 -0700570 proc_attr_.rlimits.emplace_back(*rlimit);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700571 return {};
Tom Cherry7ac013d2017-08-25 10:39:25 -0700572}
573
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700574Result<void> Service::ParseRestartPeriod(std::vector<std::string>&& args) {
Tom Cherry73f535e2018-09-27 16:10:46 -0700575 int period;
576 if (!ParseInt(args[1], &period, 5)) {
577 return Error() << "restart_period value must be an integer >= 5";
578 }
579 restart_period_ = std::chrono::seconds(period);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700580 return {};
Tom Cherry73f535e2018-09-27 16:10:46 -0700581}
582
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700583Result<void> Service::ParseSeclabel(std::vector<std::string>&& args) {
Tom Cherry018a4382018-10-17 11:11:23 -0700584 seclabel_ = std::move(args[1]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700585 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700586}
587
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700588Result<void> Service::ParseSigstop(std::vector<std::string>&& args) {
Tom Cherry8f380482018-04-17 14:48:44 -0700589 sigstop_ = true;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700590 return {};
Tom Cherry8f380482018-04-17 14:48:44 -0700591}
592
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700593Result<void> Service::ParseSetenv(std::vector<std::string>&& args) {
Tom Cherry018a4382018-10-17 11:11:23 -0700594 environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700595 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700596}
597
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700598Result<void> Service::ParseShutdown(std::vector<std::string>&& args) {
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700599 if (args[1] == "critical") {
600 flags_ |= SVC_SHUTDOWN_CRITICAL;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700601 return {};
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700602 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700603 return Error() << "Invalid shutdown option";
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700604}
605
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700606Result<void> Service::ParseTimeoutPeriod(std::vector<std::string>&& args) {
Tom Cherry73f535e2018-09-27 16:10:46 -0700607 int period;
608 if (!ParseInt(args[1], &period, 1)) {
609 return Error() << "timeout_period value must be an integer >= 1";
610 }
611 timeout_period_ = std::chrono::seconds(period);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700612 return {};
Tom Cherry73f535e2018-09-27 16:10:46 -0700613}
614
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700615template <typename T>
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700616Result<void> Service::AddDescriptor(std::vector<std::string>&& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700617 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700618 Result<uid_t> uid = 0;
619 Result<gid_t> gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700620 std::string context = args.size() > 6 ? args[6] : "";
621
Tom Cherry517e1f12017-05-04 17:40:33 -0700622 if (args.size() > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700623 uid = DecodeUid(args[4]);
624 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700625 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700626 }
627 }
628
629 if (args.size() > 5) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700630 gid = DecodeUid(args[5]);
631 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700632 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700633 }
634 }
635
Tom Cherry11a3aee2017-08-03 12:54:07 -0700636 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700637
638 auto old =
639 std::find_if(descriptors_.begin(), descriptors_.end(),
640 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
641
642 if (old != descriptors_.end()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700643 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700644 }
645
646 descriptors_.emplace_back(std::move(descriptor));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700647 return {};
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700648}
649
650// name type perm [ uid gid context ]
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700651Result<void> Service::ParseSocket(std::vector<std::string>&& args) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700652 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
653 !StartsWith(args[2], "seqpacket")) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700654 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
Tom Cherryb7349902015-08-26 11:43:36 -0700655 }
Tom Cherry018a4382018-10-17 11:11:23 -0700656 return AddDescriptor<SocketInfo>(std::move(args));
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700657}
Tom Cherryb7349902015-08-26 11:43:36 -0700658
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700659// name type perm [ uid gid context ]
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700660Result<void> Service::ParseFile(std::vector<std::string>&& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700661 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
Tom Cherry89bcc852017-08-02 17:01:36 -0700662 return Error() << "file type must be 'r', 'w' or 'rw'";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700663 }
Yifan Hong567f1872019-03-19 14:38:48 -0700664 std::string expanded;
665 if (!expand_props(args[1], &expanded)) {
666 return Error() << "Could not expand property in file path '" << args[1] << "'";
667 }
668 args[1] = std::move(expanded);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700669 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700670 return Error() << "file name must not be relative";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700671 }
Tom Cherry018a4382018-10-17 11:11:23 -0700672 return AddDescriptor<FileInfo>(std::move(args));
Tom Cherryb7349902015-08-26 11:43:36 -0700673}
674
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700675Result<void> Service::ParseUser(std::vector<std::string>&& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700676 auto uid = DecodeUid(args[1]);
677 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700678 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700679 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700680 proc_attr_.uid = *uid;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700681 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700682}
683
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700684Result<void> Service::ParseWritepid(std::vector<std::string>&& args) {
Tom Cherry018a4382018-10-17 11:11:23 -0700685 args.erase(args.begin());
686 writepid_files_ = std::move(args);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700687 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700688}
689
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700690Result<void> Service::ParseUpdatable(std::vector<std::string>&& args) {
Jiyong Park80aa4472018-11-12 12:08:41 +0900691 updatable_ = true;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700692 return {};
Jiyong Park80aa4472018-11-12 12:08:41 +0900693}
694
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400695class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700696 public:
697 OptionParserMap() {}
698
699 private:
700 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700701};
702
Tom Cherryad54d092017-04-19 16:18:50 -0700703const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700704 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700705 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400706 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400707 {"capabilities",
Tom Cherry1cd082d2019-02-06 10:45:56 -0800708 {0, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700709 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400710 {"console", {0, 1, &Service::ParseConsole}},
711 {"critical", {0, 0, &Service::ParseCritical}},
712 {"disabled", {0, 0, &Service::ParseDisabled}},
Tom Cherryaead51b2018-04-20 16:18:12 -0700713 {"enter_namespace",
714 {2, 2, &Service::ParseEnterNamespace}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800715 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400716 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
Steven Morelande055d732017-10-05 18:50:22 -0700717 {"interface", {2, 2, &Service::ParseInterface}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400718 {"ioprio", {2, 2, &Service::ParseIoprio}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400719 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
Robert Benead4852262017-07-16 19:38:11 -0700720 {"memcg.limit_in_bytes",
721 {1, 1, &Service::ParseMemcgLimitInBytes}},
Peter Collingbourned7157c22018-10-30 15:49:33 -0700722 {"memcg.limit_percent",
723 {1, 1, &Service::ParseMemcgLimitPercent}},
724 {"memcg.limit_property",
725 {1, 1, &Service::ParseMemcgLimitProperty}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800726 {"memcg.soft_limit_in_bytes",
727 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
728 {"memcg.swappiness",
729 {1, 1, &Service::ParseMemcgSwappiness}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400730 {"namespace", {1, 2, &Service::ParseNamespace}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800731 {"oneshot", {0, 0, &Service::ParseOneshot}},
732 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
733 {"oom_score_adjust",
734 {1, 1, &Service::ParseOomScoreAdjust}},
735 {"override", {0, 0, &Service::ParseOverride}},
736 {"priority", {1, 1, &Service::ParsePriority}},
Tom Cherry73f535e2018-09-27 16:10:46 -0700737 {"restart_period",
738 {1, 1, &Service::ParseRestartPeriod}},
Tom Cherry7ac013d2017-08-25 10:39:25 -0700739 {"rlimit", {3, 3, &Service::ParseProcessRlimit}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400740 {"seclabel", {1, 1, &Service::ParseSeclabel}},
741 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700742 {"shutdown", {1, 1, &Service::ParseShutdown}},
Tom Cherry8f380482018-04-17 14:48:44 -0700743 {"sigstop", {0, 0, &Service::ParseSigstop}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400744 {"socket", {3, 6, &Service::ParseSocket}},
Tom Cherry73f535e2018-09-27 16:10:46 -0700745 {"timeout_period",
746 {1, 1, &Service::ParseTimeoutPeriod}},
Jiyong Park80aa4472018-11-12 12:08:41 +0900747 {"updatable", {0, 0, &Service::ParseUpdatable}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400748 {"user", {1, 1, &Service::ParseUser}},
749 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700750 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700751 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400752 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700753}
754
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700755Result<void> Service::ParseLine(std::vector<std::string>&& args) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400756 static const OptionParserMap parser_map;
Tom Cherry89bcc852017-08-02 17:01:36 -0700757 auto parser = parser_map.FindFunction(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700758
Tom Cherry76af7e62017-08-22 16:13:59 -0700759 if (!parser) return parser.error();
Tom Cherryb7349902015-08-26 11:43:36 -0700760
Tom Cherry018a4382018-10-17 11:11:23 -0700761 return std::invoke(*parser, this, std::move(args));
Tom Cherryb7349902015-08-26 11:43:36 -0700762}
763
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700764Result<void> Service::ExecStart() {
Jiyong Park80aa4472018-11-12 12:08:41 +0900765 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
766 // Don't delay the service for ExecStart() as the semantic is that
767 // the caller might depend on the side effect of the execution.
768 return Error() << "Cannot start an updatable service '" << name_
769 << "' before configs from APEXes are all loaded";
770 }
771
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700772 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700773
Tom Cherry76af7e62017-08-22 16:13:59 -0700774 if (auto result = Start(); !result) {
775 return result;
Tom Cherryb27004a2017-03-27 16:27:30 -0700776 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700777
778 flags_ |= SVC_EXEC;
779 is_exec_service_running_ = true;
780
Vic Yange01ca4d2019-05-29 15:58:32 -0700781 LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << proc_attr_.uid
782 << " gid " << proc_attr_.gid << "+" << proc_attr_.supp_gids.size() << " context "
Wei Wang2c4ee752018-06-20 14:54:52 -0700783 << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700784
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700785 return {};
Tom Cherryb27004a2017-03-27 16:27:30 -0700786}
787
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700788Result<void> Service::Start() {
Jiyong Park80aa4472018-11-12 12:08:41 +0900789 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
790 ServiceList::GetInstance().DelayService(*this);
791 return Error() << "Cannot start an updatable service '" << name_
792 << "' before configs from APEXes are all loaded. "
793 << "Queued for execution.";
794 }
795
Tao Wu990d43c2017-10-26 10:43:10 -0700796 bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
Tom Cherrybac32992015-07-31 12:45:25 -0700797 // Starting a service removes it from the disabled or reset state and
798 // immediately takes it out of the restarting state if it was in there.
799 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700800
801 // Running processes require no additional work --- if they're in the
802 // process of exiting, we've ensured that they will immediately restart
Tao Wu990d43c2017-10-26 10:43:10 -0700803 // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
804 // stopping status, we just set SVC_RESTART flag so it will get restarted
805 // in Reap().
Tom Cherrybac32992015-07-31 12:45:25 -0700806 if (flags_ & SVC_RUNNING) {
Tao Wu990d43c2017-10-26 10:43:10 -0700807 if ((flags_ & SVC_ONESHOT) && disabled) {
808 flags_ |= SVC_RESTART;
809 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700810 // It is not an error to try to start a service that is already running.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700811 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700812 }
813
814 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200815 if (needs_console) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700816 if (proc_attr_.console.empty()) {
817 proc_attr_.console = default_console;
Viorel Suman70daa672016-03-21 10:08:07 +0200818 }
819
Adrian Salido24ef8602016-12-20 15:52:15 -0800820 // Make sure that open call succeeds to ensure a console driver is
821 // properly registered for the device node
Vic Yange01ca4d2019-05-29 15:58:32 -0700822 int console_fd = open(proc_attr_.console.c_str(), O_RDWR | O_CLOEXEC);
Adrian Salido24ef8602016-12-20 15:52:15 -0800823 if (console_fd < 0) {
Viorel Suman70daa672016-03-21 10:08:07 +0200824 flags_ |= SVC_DISABLED;
Vic Yange01ca4d2019-05-29 15:58:32 -0700825 return ErrnoError() << "Couldn't open console '" << proc_attr_.console << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200826 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800827 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700828 }
829
830 struct stat sb;
831 if (stat(args_[0].c_str(), &sb) == -1) {
Tom Cherrybac32992015-07-31 12:45:25 -0700832 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700833 return ErrnoError() << "Cannot find '" << args_[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700834 }
835
Tom Cherrybac32992015-07-31 12:45:25 -0700836 std::string scon;
837 if (!seclabel_.empty()) {
838 scon = seclabel_;
839 } else {
Tom Cherryaead51b2018-04-20 16:18:12 -0700840 auto result = ComputeContextFromExecutable(args_[0]);
Tom Cherry76af7e62017-08-22 16:13:59 -0700841 if (!result) {
842 return result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700843 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700844 scon = *result;
Tom Cherrybac32992015-07-31 12:45:25 -0700845 }
846
Jiyong Park68660412019-01-16 23:00:59 +0900847 if (!IsRuntimeApexReady() && !pre_apexd_) {
848 // If this service is started before the runtime APEX gets available,
849 // mark it as pre-apexd one. Note that this marking is permanent. So
850 // for example, if the service is re-launched (e.g., due to crash),
851 // it is still recognized as pre-apexd... for consistency.
852 pre_apexd_ = true;
853 }
854
Martijn Coenen70788f92019-04-23 16:26:01 +0200855 post_data_ = ServiceList::GetInstance().IsPostData();
856
Wei Wanga285dac2016-10-04 14:05:39 -0700857 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700858
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700859 pid_t pid = -1;
Vic Yange01ca4d2019-05-29 15:58:32 -0700860 if (namespaces_.flags) {
861 pid = clone(nullptr, nullptr, namespaces_.flags | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700862 } else {
863 pid = fork();
864 }
865
Tom Cherrybac32992015-07-31 12:45:25 -0700866 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700867 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700868
Vic Yange01ca4d2019-05-29 15:58:32 -0700869 if (auto result = EnterNamespaces(namespaces_, name_, pre_apexd_); !result) {
870 LOG(FATAL) << "Service '" << name_
871 << "' failed to set up namespaces: " << result.error();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700872 }
873
Tom Cherry6de21f12017-08-22 15:41:03 -0700874 for (const auto& [key, value] : environment_vars_) {
875 setenv(key.c_str(), value.c_str(), 1);
Tom Cherrybac32992015-07-31 12:45:25 -0700876 }
877
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700878 std::for_each(descriptors_.begin(), descriptors_.end(),
879 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700880
Vic Yange01ca4d2019-05-29 15:58:32 -0700881 if (auto result = WritePidToFiles(&writepid_files_); !result) {
882 LOG(ERROR) << "failed to write pid to files: " << result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700883 }
884
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400885 // As requested, set our gid, supplemental gids, uid, context, and
886 // priority. Aborts on failure.
Vic Yange01ca4d2019-05-29 15:58:32 -0700887 SetProcessAttributesAndCaps();
Tom Cherrybac32992015-07-31 12:45:25 -0700888
Tom Cherry8f380482018-04-17 14:48:44 -0700889 if (!ExpandArgsAndExecv(args_, sigstop_)) {
Tom Cherry5e405ca2017-09-11 16:08:54 -0700890 PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700891 }
892
893 _exit(127);
894 }
895
896 if (pid < 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700897 pid_ = 0;
Tom Cherry76af7e62017-08-22 16:13:59 -0700898 return ErrnoError() << "Failed to fork";
Tom Cherrybac32992015-07-31 12:45:25 -0700899 }
900
Marco Nelissen310f6702016-07-22 12:07:06 -0700901 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700902 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700903 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
904 if (!WriteStringToFile(oom_str, oom_file)) {
Elliott Hughes076305e2019-03-08 12:34:53 -0800905 PLOG(ERROR) << "couldn't write oom_score_adj";
Marco Nelissen310f6702016-07-22 12:07:06 -0700906 }
907 }
908
Elliott Hughes9605a942016-11-10 17:43:47 -0800909 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700910 pid_ = pid;
911 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -0700912 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -0700913 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700914
Peter Collingbourned7157c22018-10-30 15:49:33 -0700915 bool use_memcg = swappiness_ != -1 || soft_limit_in_bytes_ != -1 || limit_in_bytes_ != -1 ||
916 limit_percent_ != -1 || !limit_property_.empty();
Vic Yange01ca4d2019-05-29 15:58:32 -0700917 errno = -createProcessGroup(proc_attr_.uid, pid_, use_memcg);
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700918 if (errno != 0) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700919 PLOG(ERROR) << "createProcessGroup(" << proc_attr_.uid << ", " << pid_
920 << ") failed for service '" << name_ << "'";
Peter Collingbourned7157c22018-10-30 15:49:33 -0700921 } else if (use_memcg) {
Robert Benead4852262017-07-16 19:38:11 -0700922 if (swappiness_ != -1) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700923 if (!setProcessGroupSwappiness(proc_attr_.uid, pid_, swappiness_)) {
Robert Benead4852262017-07-16 19:38:11 -0700924 PLOG(ERROR) << "setProcessGroupSwappiness failed";
925 }
926 }
927
928 if (soft_limit_in_bytes_ != -1) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700929 if (!setProcessGroupSoftLimit(proc_attr_.uid, pid_, soft_limit_in_bytes_)) {
Robert Benead4852262017-07-16 19:38:11 -0700930 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
931 }
932 }
933
Peter Collingbourned7157c22018-10-30 15:49:33 -0700934 size_t computed_limit_in_bytes = limit_in_bytes_;
935 if (limit_percent_ != -1) {
936 long page_size = sysconf(_SC_PAGESIZE);
937 long num_pages = sysconf(_SC_PHYS_PAGES);
938 if (page_size > 0 && num_pages > 0) {
939 size_t max_mem = SIZE_MAX;
940 if (size_t(num_pages) < SIZE_MAX / size_t(page_size)) {
941 max_mem = size_t(num_pages) * size_t(page_size);
942 }
943 computed_limit_in_bytes =
944 std::min(computed_limit_in_bytes, max_mem / 100 * limit_percent_);
945 }
946 }
947
948 if (!limit_property_.empty()) {
949 // This ends up overwriting computed_limit_in_bytes but only if the
950 // property is defined.
951 computed_limit_in_bytes = android::base::GetUintProperty(
952 limit_property_, computed_limit_in_bytes, SIZE_MAX);
953 }
954
955 if (computed_limit_in_bytes != size_t(-1)) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700956 if (!setProcessGroupLimit(proc_attr_.uid, pid_, computed_limit_in_bytes)) {
Robert Benead4852262017-07-16 19:38:11 -0700957 PLOG(ERROR) << "setProcessGroupLimit failed";
958 }
959 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700960 }
Tom Cherrybac32992015-07-31 12:45:25 -0700961
Tom Cherrybac32992015-07-31 12:45:25 -0700962 NotifyStateChange("running");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700963 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700964}
965
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700966Result<void> Service::StartIfNotDisabled() {
Tom Cherrybac32992015-07-31 12:45:25 -0700967 if (!(flags_ & SVC_DISABLED)) {
968 return Start();
969 } else {
970 flags_ |= SVC_DISABLED_START;
971 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700972 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700973}
974
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700975Result<void> Service::Enable() {
Tom Cherrybac32992015-07-31 12:45:25 -0700976 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
977 if (flags_ & SVC_DISABLED_START) {
978 return Start();
979 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700980 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700981}
982
983void Service::Reset() {
984 StopOrReset(SVC_RESET);
985}
986
Martijn Coenen70788f92019-04-23 16:26:01 +0200987void Service::ResetIfPostData() {
988 if (post_data_) {
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200989 if (flags_ & SVC_RUNNING) {
990 running_at_post_data_reset_ = true;
991 }
Martijn Coenen70788f92019-04-23 16:26:01 +0200992 StopOrReset(SVC_RESET);
993 }
994}
995
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700996Result<void> Service::StartIfPostData() {
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200997 // Start the service, but only if it was started after /data was mounted,
998 // and it was still running when we reset the post-data services.
999 if (running_at_post_data_reset_) {
1000 return Start();
1001 }
1002
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001003 return {};
Martijn Coenenacc45aa2019-05-15 22:04:13 +02001004}
1005
Tom Cherrybac32992015-07-31 12:45:25 -07001006void Service::Stop() {
1007 StopOrReset(SVC_DISABLED);
1008}
1009
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001010void Service::Terminate() {
1011 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1012 flags_ |= SVC_DISABLED;
1013 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001014 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001015 NotifyStateChange("stopping");
1016 }
1017}
1018
Tom Cherry73f535e2018-09-27 16:10:46 -07001019void Service::Timeout() {
1020 // All process state flags will be taken care of in Reap(), we really just want to kill the
1021 // process here when it times out. Oneshot processes will transition to be disabled, and
1022 // all other processes will transition to be restarting.
1023 LOG(INFO) << "Service '" << name_ << "' expired its timeout of " << timeout_period_->count()
1024 << " seconds and will now be killed";
1025 if (pid_) {
1026 KillProcessGroup(SIGKILL);
1027 NotifyStateChange("stopping");
1028 }
1029}
1030
Tom Cherrybac32992015-07-31 12:45:25 -07001031void Service::Restart() {
1032 if (flags_ & SVC_RUNNING) {
1033 /* Stop, wait, then start the service. */
1034 StopOrReset(SVC_RESTART);
1035 } else if (!(flags_ & SVC_RESTARTING)) {
1036 /* Just start the service since it's not running. */
Tom Cherry76af7e62017-08-22 16:13:59 -07001037 if (auto result = Start(); !result) {
1038 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
1039 }
Tom Cherrybac32992015-07-31 12:45:25 -07001040 } /* else: Service is restarting anyways. */
1041}
1042
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001043// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -07001044void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001045 // The service is still SVC_RUNNING until its process exits, but if it has
1046 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -07001047 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1048
1049 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001050 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -07001051 how = SVC_DISABLED;
1052 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001053
1054 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -07001055 if (how == SVC_RESET) {
1056 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
1057 } else {
1058 flags_ |= how;
1059 }
Tao Wu84b856d2017-10-27 11:29:13 -07001060 // Make sure it's in right status when a restart immediately follow a
1061 // stop/reset or vice versa.
1062 if (how == SVC_RESTART) {
1063 flags_ &= (~(SVC_DISABLED | SVC_RESET));
1064 } else {
1065 flags_ &= (~SVC_RESTART);
1066 }
Tom Cherrybac32992015-07-31 12:45:25 -07001067
1068 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001069 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -07001070 NotifyStateChange("stopping");
1071 } else {
1072 NotifyStateChange("stopped");
1073 }
1074}
1075
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001076std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -07001077 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
1078 // SECLABEL can be a - to denote default
1079 std::size_t command_arg = 1;
1080 for (std::size_t i = 1; i < args.size(); ++i) {
1081 if (args[i] == "--") {
1082 command_arg = i + 1;
1083 break;
1084 }
1085 }
1086 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001087 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -07001088 return nullptr;
1089 }
1090
1091 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001092 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -07001093 return nullptr;
1094 }
1095 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
1096
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001097 static size_t exec_count = 0;
1098 exec_count++;
1099 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -07001100
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001101 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001102 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001103
1104 std::string seclabel = "";
1105 if (command_arg > 2 && args[1] != "-") {
1106 seclabel = args[1];
1107 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001108 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001109 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001110 uid = DecodeUid(args[2]);
1111 if (!uid) {
1112 LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001113 return nullptr;
1114 }
Tom Cherrybac32992015-07-31 12:45:25 -07001115 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001116 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001117 std::vector<gid_t> supp_gids;
1118 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001119 gid = DecodeUid(args[3]);
1120 if (!gid) {
1121 LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001122 return nullptr;
1123 }
Tom Cherrybac32992015-07-31 12:45:25 -07001124 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
1125 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001126 auto supp_gid = DecodeUid(args[4 + i]);
1127 if (!supp_gid) {
1128 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
1129 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001130 return nullptr;
1131 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001132 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -07001133 }
1134 }
1135
Tom Cherry1cd082d2019-02-06 10:45:56 -08001136 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, namespace_flags, seclabel,
1137 nullptr, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001138}
1139
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001140} // namespace init
1141} // namespace android