blob: 4fe374c45a959a68b1442c04d8556ec65d4405b4 [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 Cherrybac32992015-07-31 12:45:25 -070043#include "util.h"
44
Tom Cherryde6bd502018-02-13 16:50:08 -080045#if defined(__ANDROID__)
Jiyong Parkd7f7c202019-05-10 21:12:15 +090046#include <ApexProperties.sysprop.h>
Tom Cherry40acb372018-08-01 13:41:12 -070047#include <android/api-level.h>
Tom Cherryde6bd502018-02-13 16:50:08 -080048#include <sys/system_properties.h>
49
Tom Cherryde6bd502018-02-13 16:50:08 -080050#include "init.h"
Jiyong Park68660412019-01-16 23:00:59 +090051#include "mount_namespace.h"
Tom Cherryde6bd502018-02-13 16:50:08 -080052#include "property_service.h"
Tom Cherry40acb372018-08-01 13:41:12 -070053#include "selinux.h"
Tom Cherryde6bd502018-02-13 16:50:08 -080054#else
55#include "host_init_stubs.h"
56#endif
57
James Hawkinse78ea772017-03-24 11:43:02 -070058using android::base::boot_clock;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070059using android::base::GetProperty;
60using android::base::Join;
Elliott Hughesda46b392016-10-11 17:09:00 -070061using android::base::ParseInt;
Tom Cherry79166842018-10-16 10:58:06 -070062using android::base::Split;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070063using android::base::StartsWith;
Tom Cherryb7349902015-08-26 11:43:36 -070064using android::base::StringPrintf;
65using android::base::WriteStringToFile;
66
Tom Cherry81f5d3e2017-06-22 12:53:17 -070067namespace android {
68namespace init {
69
Tom Cherryaead51b2018-04-20 16:18:12 -070070static Result<std::string> ComputeContextFromExecutable(const std::string& service_path) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040071 std::string computed_context;
72
73 char* raw_con = nullptr;
74 char* raw_filecon = nullptr;
75
76 if (getcon(&raw_con) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070077 return Error() << "Could not get security context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040078 }
79 std::unique_ptr<char> mycon(raw_con);
80
81 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070082 return Error() << "Could not get file context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040083 }
84 std::unique_ptr<char> filecon(raw_filecon);
85
86 char* new_con = nullptr;
87 int rc = security_compute_create(mycon.get(), filecon.get(),
88 string_to_security_class("process"), &new_con);
89 if (rc == 0) {
90 computed_context = new_con;
91 free(new_con);
92 }
93 if (rc == 0 && computed_context == mycon.get()) {
Nick Kralevich1ea19eb2017-08-25 12:08:57 -070094 return Error() << "File " << service_path << "(labeled \"" << filecon.get()
95 << "\") has incorrect label or no domain transition from " << mycon.get()
96 << " to another SELinux domain defined. Have you configured your "
97 "service correctly? https://source.android.com/security/selinux/"
98 "device-policy#label_new_services_and_address_denials";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040099 }
100 if (rc < 0) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700101 return Error() << "Could not get process context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400102 }
103 return computed_context;
104}
105
Tom Cherry8f380482018-04-17 14:48:44 -0700106static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400107 std::vector<std::string> expanded_args;
Tom Cherry5e405ca2017-09-11 16:08:54 -0700108 std::vector<char*> c_strings;
109
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400110 expanded_args.resize(args.size());
Tom Cherry5e405ca2017-09-11 16:08:54 -0700111 c_strings.push_back(const_cast<char*>(args[0].data()));
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400112 for (std::size_t i = 1; i < args.size(); ++i) {
113 if (!expand_props(args[i], &expanded_args[i])) {
114 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
115 }
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
Jiyong Park68660412019-01-16 23:00:59 +0900127static bool IsRuntimeApexReady() {
128 struct stat buf;
129 return stat("/apex/com.android.runtime/", &buf) == 0;
130}
131
Tom Cherry59383792017-07-26 16:09:09 -0700132unsigned long Service::next_start_order_ = 1;
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700133bool Service::is_exec_service_running_ = false;
Tom Cherry59383792017-07-26 16:09:09 -0700134
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700135Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
136 const std::vector<std::string>& args)
Tom Cherry1cd082d2019-02-06 10:45:56 -0800137 : Service(name, 0, 0, 0, {}, 0, "", subcontext_for_restart_commands, args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700138
Wei Wang641ff0a2017-03-27 10:59:11 -0700139Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
Tom Cherry1cd082d2019-02-06 10:45:56 -0800140 const std::vector<gid_t>& supp_gids, unsigned namespace_flags,
141 const std::string& seclabel, Subcontext* subcontext_for_restart_commands,
142 const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700143 : name_(name),
144 classnames_({"default"}),
145 flags_(flags),
146 pid_(0),
147 crash_count_(0),
Vic Yange01ca4d2019-05-29 15:58:32 -0700148 proc_attr_{.ioprio_class = IoSchedClass_NONE,
149 .ioprio_pri = 0,
150 .uid = uid,
151 .gid = gid,
152 .supp_gids = supp_gids,
153 .priority = 0},
154 namespaces_{.flags = namespace_flags},
Wei Wang641ff0a2017-03-27 10:59:11 -0700155 seclabel_(seclabel),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800156 onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0,
157 "onrestart", {}),
Wei Wang641ff0a2017-03-27 10:59:11 -0700158 oom_score_adjust_(-1000),
Tom Cherry59383792017-07-26 16:09:09 -0700159 start_order_(0),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800160 args_(args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700161
162void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700163 if ((flags_ & SVC_TEMPORARY) != 0) {
164 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700165 return;
166 }
167
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700168 std::string prop_name = "init.svc." + name_;
169 property_set(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800170
171 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800172 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherryfed33732017-08-18 10:47:46 -0700173 std::string boottime_property = "ro.boottime." + name_;
174 if (GetProperty(boottime_property, "").empty()) {
175 property_set(boottime_property, std::to_string(start_ns));
176 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800177 }
Tom Cherrybac32992015-07-31 12:45:25 -0700178}
179
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700180void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700181 // If we've already seen a successful result from killProcessGroup*(), then we have removed
182 // the cgroup already and calling these functions a second time will simply result in an error.
183 // This is true regardless of which signal was sent.
184 // These functions handle their own logging, so no additional logging is needed.
185 if (!process_cgroup_empty_) {
186 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
187 << ") process group...";
188 int r;
189 if (signal == SIGTERM) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700190 r = killProcessGroupOnce(proc_attr_.uid, pid_, signal);
Tom Cherry33838b12017-05-04 11:32:36 -0700191 } else {
Vic Yange01ca4d2019-05-29 15:58:32 -0700192 r = killProcessGroup(proc_attr_.uid, pid_, signal);
Tom Cherry33838b12017-05-04 11:32:36 -0700193 }
194
195 if (r == 0) process_cgroup_empty_ = true;
196 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700197}
198
Vic Yange01ca4d2019-05-29 15:58:32 -0700199void Service::SetProcessAttributesAndCaps() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400200 // Keep capabilites on uid change.
Vic Yange01ca4d2019-05-29 15:58:32 -0700201 if (capabilities_ && proc_attr_.uid) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700202 // If Android is running in a container, some securebits might already
203 // be locked, so don't change those.
Ben Fennemaa7243602017-07-25 14:37:21 -0700204 unsigned long securebits = prctl(PR_GET_SECUREBITS);
205 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700206 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
207 }
208 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
209 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
210 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400211 }
212 }
213
Vic Yange01ca4d2019-05-29 15:58:32 -0700214 if (auto result = SetProcessAttributes(proc_attr_); !result) {
215 LOG(FATAL) << "cannot set attribute for " << name_ << ": " << result.error();
216 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400217
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400218 if (!seclabel_.empty()) {
219 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700220 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400221 }
222 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700223
Tom Cherry1cd082d2019-02-06 10:45:56 -0800224 if (capabilities_) {
225 if (!SetCapsForExec(*capabilities_)) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400226 LOG(FATAL) << "cannot set capabilities for " << name_;
227 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700228 } else if (proc_attr_.uid) {
Luis Hector Chavez94fb5b02017-11-16 15:52:00 -0800229 // Inheritable caps can be non-zero when running in a container.
230 if (!DropInheritableCaps()) {
231 LOG(FATAL) << "cannot drop inheritable caps for " << name_;
232 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400233 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400234}
235
Paul Crowleyc73b2152018-04-13 17:38:57 +0000236void Service::Reap(const siginfo_t& siginfo) {
Tom Cherrybac32992015-07-31 12:45:25 -0700237 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700238 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700239 }
240
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700241 // Remove any descriptor resources we may have created.
242 std::for_each(descriptors_.begin(), descriptors_.end(),
243 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700244
Paul Crowleyc73b2152018-04-13 17:38:57 +0000245 for (const auto& f : reap_callbacks_) {
246 f(siginfo);
247 }
248
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700249 if (flags_ & SVC_EXEC) UnSetExec();
250
251 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700252
253 pid_ = 0;
254 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700255 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700256
257 // Oneshot processes go into the disabled state on exit,
258 // except when manually restarted.
Martijn Coenen70788f92019-04-23 16:26:01 +0200259 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART) && !(flags_ & SVC_RESET)) {
Tom Cherrybac32992015-07-31 12:45:25 -0700260 flags_ |= SVC_DISABLED;
261 }
262
263 // Disabled and reset processes do not get restarted automatically.
264 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
265 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700266 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700267 }
268
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900269#if defined(__ANDROID__)
270 static bool is_apex_updatable = android::sysprop::ApexProperties::updatable().value_or(false);
271#else
272 static bool is_apex_updatable = false;
273#endif
274 const bool is_process_updatable = !pre_apexd_ && is_apex_updatable;
275
Zimuzo88de80f2019-04-27 21:10:35 +0100276 // If we crash > 4 times in 4 minutes or before boot_completed,
277 // reboot into bootloader or set crashing property
Elliott Hughes9605a942016-11-10 17:43:47 -0800278 boot_clock::time_point now = boot_clock::now();
Jiyong Parkd7f7c202019-05-10 21:12:15 +0900279 if (((flags_ & SVC_CRITICAL) || is_process_updatable) && !(flags_ & SVC_RESTART)) {
Zimuzo88de80f2019-04-27 21:10:35 +0100280 bool boot_completed = android::base::GetBoolProperty("sys.boot_completed", false);
281 if (now < time_crashed_ + 4min || !boot_completed) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800282 if (++crash_count_ > 4) {
Zimuzoc55a8c62019-01-07 10:19:02 +0000283 if (flags_ & SVC_CRITICAL) {
284 // Aborts into bootloader
Zimuzo88de80f2019-04-27 21:10:35 +0100285 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times "
286 << (boot_completed ? "in 4 minutes" : "before boot completed");
Zimuzoc55a8c62019-01-07 10:19:02 +0000287 } else {
Zimuzo88de80f2019-04-27 21:10:35 +0100288 LOG(ERROR) << "updatable process '" << name_ << "' exited 4 times "
289 << (boot_completed ? "in 4 minutes" : "before boot completed");
Zimuzoc55a8c62019-01-07 10:19:02 +0000290 // Notifies update_verifier and apexd
291 property_set("ro.init.updatable_crashing", "1");
292 }
Tom Cherrybac32992015-07-31 12:45:25 -0700293 }
294 } else {
295 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800296 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700297 }
298 }
299
300 flags_ &= (~SVC_RESTART);
301 flags_ |= SVC_RESTARTING;
302
303 // Execute all onrestart commands for this service.
304 onrestart_.ExecuteAllCommands();
305
306 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700307 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700308}
309
310void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700311 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700312 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
313 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700314 std::for_each(descriptors_.begin(), descriptors_.end(),
315 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700316}
317
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700318Result<void> Service::ParseCapabilities(std::vector<std::string>&& args) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400319 capabilities_ = 0;
320
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500321 if (!CapAmbientSupported()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700322 return Error()
323 << "capabilities requested but the kernel does not support ambient capabilities";
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500324 }
325
326 unsigned int last_valid_cap = GetLastValidCap();
Tom Cherry1cd082d2019-02-06 10:45:56 -0800327 if (last_valid_cap >= capabilities_->size()) {
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500328 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
329 }
330
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400331 for (size_t i = 1; i < args.size(); i++) {
332 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500333 int res = LookupCap(arg);
334 if (res < 0) {
Tom Cherryf4db2aa2019-06-14 14:54:02 -0700335 return Errorf("invalid capability '{}'", arg);
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400336 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500337 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
338 if (cap > last_valid_cap) {
Tom Cherryf4db2aa2019-06-14 14:54:02 -0700339 return Errorf("capability '{}' not supported by the kernel", arg);
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500340 }
Tom Cherry1cd082d2019-02-06 10:45:56 -0800341 (*capabilities_)[cap] = true;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400342 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700343 return {};
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400344}
345
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700346Result<void> Service::ParseClass(std::vector<std::string>&& args) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700347 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700348 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700349}
Tom Cherrybac32992015-07-31 12:45:25 -0700350
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700351Result<void> Service::ParseConsole(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700352 flags_ |= SVC_CONSOLE;
Vic Yange01ca4d2019-05-29 15:58:32 -0700353 proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700354 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700355}
Tom Cherrybac32992015-07-31 12:45:25 -0700356
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700357Result<void> Service::ParseCritical(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700358 flags_ |= SVC_CRITICAL;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700359 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700360}
Tom Cherrybac32992015-07-31 12:45:25 -0700361
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700362Result<void> Service::ParseDisabled(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700363 flags_ |= SVC_DISABLED;
364 flags_ |= SVC_RC_DISABLED;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700365 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700366}
Tom Cherrybac32992015-07-31 12:45:25 -0700367
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700368Result<void> Service::ParseEnterNamespace(std::vector<std::string>&& args) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700369 if (args[1] != "net") {
370 return Error() << "Init only supports entering network namespaces";
371 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700372 if (!namespaces_.namespaces_to_enter.empty()) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700373 return Error() << "Only one network namespace may be entered";
374 }
375 // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
376 // present. Therefore, they also require mount namespaces.
Vic Yange01ca4d2019-05-29 15:58:32 -0700377 namespaces_.flags |= CLONE_NEWNS;
378 namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700379 return {};
Tom Cherryaead51b2018-04-20 16:18:12 -0700380}
381
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700382Result<void> Service::ParseGroup(std::vector<std::string>&& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700383 auto gid = DecodeUid(args[1]);
384 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700385 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700386 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700387 proc_attr_.gid = *gid;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700388
Tom Cherryb7349902015-08-26 11:43:36 -0700389 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700390 gid = DecodeUid(args[n]);
391 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700392 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700393 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700394 proc_attr_.supp_gids.emplace_back(*gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700395 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700396 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700397}
398
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700399Result<void> Service::ParsePriority(std::vector<std::string>&& args) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700400 proc_attr_.priority = 0;
401 if (!ParseInt(args[1], &proc_attr_.priority,
402 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800403 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Tom Cherryf4db2aa2019-06-14 14:54:02 -0700404 return Errorf("process priority value must be range {} - {}", ANDROID_PRIORITY_HIGHEST,
405 ANDROID_PRIORITY_LOWEST);
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700406 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700407 return {};
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700408}
409
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700410Result<void> Service::ParseInterface(std::vector<std::string>&& args) {
Steven Morelande055d732017-10-05 18:50:22 -0700411 const std::string& interface_name = args[1];
412 const std::string& instance_name = args[2];
413
Steven Moreland422367b2018-03-06 14:57:46 -0800414 FQName fq_name;
415 if (!FQName::parse(interface_name, &fq_name)) {
Steven Morelande055d732017-10-05 18:50:22 -0700416 return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
417 }
418
419 if (!fq_name.isFullyQualified()) {
420 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
421 }
422
423 if (fq_name.isValidValueName()) {
424 return Error() << "Interface name must not be a value name '" << interface_name << "'";
425 }
426
427 const std::string fullname = interface_name + "/" + instance_name;
428
429 for (const auto& svc : ServiceList::GetInstance()) {
430 if (svc->interfaces().count(fullname) > 0) {
431 return Error() << "Interface '" << fullname << "' redefined in " << name()
432 << " but is already defined by " << svc->name();
433 }
434 }
435
436 interfaces_.insert(fullname);
437
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700438 return {};
Steven Morelande055d732017-10-05 18:50:22 -0700439}
440
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700441Result<void> Service::ParseIoprio(std::vector<std::string>&& args) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700442 if (!ParseInt(args[2], &proc_attr_.ioprio_pri, 0, 7)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700443 return Error() << "priority value must be range 0 - 7";
Tom Cherryb7349902015-08-26 11:43:36 -0700444 }
445
446 if (args[1] == "rt") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700447 proc_attr_.ioprio_class = IoSchedClass_RT;
Tom Cherryb7349902015-08-26 11:43:36 -0700448 } else if (args[1] == "be") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700449 proc_attr_.ioprio_class = IoSchedClass_BE;
Tom Cherryb7349902015-08-26 11:43:36 -0700450 } else if (args[1] == "idle") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700451 proc_attr_.ioprio_class = IoSchedClass_IDLE;
Tom Cherryb7349902015-08-26 11:43:36 -0700452 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700453 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
Tom Cherryb7349902015-08-26 11:43:36 -0700454 }
455
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700456 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700457}
458
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700459Result<void> Service::ParseKeycodes(std::vector<std::string>&& args) {
Tom Cherry79166842018-10-16 10:58:06 -0700460 auto it = args.begin() + 1;
461 if (args.size() == 2 && StartsWith(args[1], "$")) {
462 std::string expanded;
463 if (!expand_props(args[1], &expanded)) {
464 return Error() << "Could not expand property '" << args[1] << "'";
465 }
466
467 // If the property is not set, it defaults to none, in which case there are no keycodes
468 // for this service.
469 if (expanded == "none") {
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700470 return {};
Tom Cherry79166842018-10-16 10:58:06 -0700471 }
472
473 args = Split(expanded, ",");
474 it = args.begin();
475 }
476
477 for (; it != args.end(); ++it) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700478 int code;
Tom Cherry79166842018-10-16 10:58:06 -0700479 if (ParseInt(*it, &code, 0, KEY_MAX)) {
Mark Salyzyneca25072018-05-16 15:10:24 -0700480 for (auto& key : keycodes_) {
Tom Cherry79166842018-10-16 10:58:06 -0700481 if (key == code) return Error() << "duplicate keycode: " << *it;
Mark Salyzyneca25072018-05-16 15:10:24 -0700482 }
Mark Salyzyn13857252018-05-18 15:25:15 -0700483 keycodes_.insert(std::upper_bound(keycodes_.begin(), keycodes_.end(), code), code);
Elliott Hughesda46b392016-10-11 17:09:00 -0700484 } else {
Tom Cherry79166842018-10-16 10:58:06 -0700485 return Error() << "invalid keycode: " << *it;
Elliott Hughesda46b392016-10-11 17:09:00 -0700486 }
Tom Cherryb7349902015-08-26 11:43:36 -0700487 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700488 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700489}
490
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700491Result<void> Service::ParseOneshot(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700492 flags_ |= SVC_ONESHOT;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700493 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700494}
495
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700496Result<void> Service::ParseOnrestart(std::vector<std::string>&& args) {
Tom Cherry018a4382018-10-17 11:11:23 -0700497 args.erase(args.begin());
Tom Cherry012c5732017-04-18 13:21:54 -0700498 int line = onrestart_.NumCommands() + 1;
Tom Cherry018a4382018-10-17 11:11:23 -0700499 if (auto result = onrestart_.AddCommand(std::move(args), line); !result) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700500 return Error() << "cannot add Onrestart command: " << result.error();
501 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700502 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700503}
504
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700505Result<void> Service::ParseNamespace(std::vector<std::string>&& args) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700506 for (size_t i = 1; i < args.size(); i++) {
507 if (args[i] == "pid") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700508 namespaces_.flags |= CLONE_NEWPID;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700509 // PID namespaces require mount namespaces.
Vic Yange01ca4d2019-05-29 15:58:32 -0700510 namespaces_.flags |= CLONE_NEWNS;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700511 } else if (args[i] == "mnt") {
Vic Yange01ca4d2019-05-29 15:58:32 -0700512 namespaces_.flags |= CLONE_NEWNS;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700513 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700514 return Error() << "namespace must be 'pid' or 'mnt'";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700515 }
516 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700517 return {};
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700518}
519
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700520Result<void> Service::ParseOomScoreAdjust(std::vector<std::string>&& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700521 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700522 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
Marco Nelissen310f6702016-07-22 12:07:06 -0700523 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700524 return {};
Marco Nelissen310f6702016-07-22 12:07:06 -0700525}
526
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700527Result<void> Service::ParseOverride(std::vector<std::string>&& args) {
Steven Moreland6f5333a2017-11-13 15:31:54 -0800528 override_ = true;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700529 return {};
Steven Moreland6f5333a2017-11-13 15:31:54 -0800530}
531
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700532Result<void> Service::ParseMemcgSwappiness(std::vector<std::string>&& args) {
Robert Benead4852262017-07-16 19:38:11 -0700533 if (!ParseInt(args[1], &swappiness_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700534 return Error() << "swappiness value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700535 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700536 return {};
Robert Benead4852262017-07-16 19:38:11 -0700537}
538
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700539Result<void> Service::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
Robert Benead4852262017-07-16 19:38:11 -0700540 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700541 return Error() << "limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700542 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700543 return {};
Robert Benead4852262017-07-16 19:38:11 -0700544}
545
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700546Result<void> Service::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700547 if (!ParseInt(args[1], &limit_percent_, 0)) {
548 return Error() << "limit_percent value must be equal or greater than 0";
549 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700550 return {};
Peter Collingbourned7157c22018-10-30 15:49:33 -0700551}
552
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700553Result<void> Service::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
Peter Collingbourned7157c22018-10-30 15:49:33 -0700554 limit_property_ = std::move(args[1]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700555 return {};
Peter Collingbourned7157c22018-10-30 15:49:33 -0700556}
557
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700558Result<void> Service::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
Robert Benead4852262017-07-16 19:38:11 -0700559 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700560 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700561 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700562 return {};
Robert Benead4852262017-07-16 19:38:11 -0700563}
564
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700565Result<void> Service::ParseProcessRlimit(std::vector<std::string>&& args) {
Tom Cherry7ac013d2017-08-25 10:39:25 -0700566 auto rlimit = ParseRlimit(args);
567 if (!rlimit) return rlimit.error();
568
Vic Yange01ca4d2019-05-29 15:58:32 -0700569 proc_attr_.rlimits.emplace_back(*rlimit);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700570 return {};
Tom Cherry7ac013d2017-08-25 10:39:25 -0700571}
572
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700573Result<void> Service::ParseRestartPeriod(std::vector<std::string>&& args) {
Tom Cherry73f535e2018-09-27 16:10:46 -0700574 int period;
575 if (!ParseInt(args[1], &period, 5)) {
576 return Error() << "restart_period value must be an integer >= 5";
577 }
578 restart_period_ = std::chrono::seconds(period);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700579 return {};
Tom Cherry73f535e2018-09-27 16:10:46 -0700580}
581
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700582Result<void> Service::ParseSeclabel(std::vector<std::string>&& args) {
Tom Cherry018a4382018-10-17 11:11:23 -0700583 seclabel_ = std::move(args[1]);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700584 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700585}
586
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700587Result<void> Service::ParseSigstop(std::vector<std::string>&& args) {
Tom Cherry8f380482018-04-17 14:48:44 -0700588 sigstop_ = true;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700589 return {};
Tom Cherry8f380482018-04-17 14:48:44 -0700590}
591
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700592Result<void> Service::ParseSetenv(std::vector<std::string>&& args) {
Tom Cherry018a4382018-10-17 11:11:23 -0700593 environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700594 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700595}
596
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700597Result<void> Service::ParseShutdown(std::vector<std::string>&& args) {
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700598 if (args[1] == "critical") {
599 flags_ |= SVC_SHUTDOWN_CRITICAL;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700600 return {};
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700601 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700602 return Error() << "Invalid shutdown option";
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700603}
604
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700605Result<void> Service::ParseTimeoutPeriod(std::vector<std::string>&& args) {
Tom Cherry73f535e2018-09-27 16:10:46 -0700606 int period;
607 if (!ParseInt(args[1], &period, 1)) {
608 return Error() << "timeout_period value must be an integer >= 1";
609 }
610 timeout_period_ = std::chrono::seconds(period);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700611 return {};
Tom Cherry73f535e2018-09-27 16:10:46 -0700612}
613
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700614template <typename T>
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700615Result<void> Service::AddDescriptor(std::vector<std::string>&& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700616 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700617 Result<uid_t> uid = 0;
618 Result<gid_t> gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700619 std::string context = args.size() > 6 ? args[6] : "";
620
Tom Cherry517e1f12017-05-04 17:40:33 -0700621 if (args.size() > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700622 uid = DecodeUid(args[4]);
623 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700624 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700625 }
626 }
627
628 if (args.size() > 5) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700629 gid = DecodeUid(args[5]);
630 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700631 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700632 }
633 }
634
Tom Cherry11a3aee2017-08-03 12:54:07 -0700635 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700636
637 auto old =
638 std::find_if(descriptors_.begin(), descriptors_.end(),
639 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
640
641 if (old != descriptors_.end()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700642 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700643 }
644
645 descriptors_.emplace_back(std::move(descriptor));
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700646 return {};
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700647}
648
649// name type perm [ uid gid context ]
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700650Result<void> Service::ParseSocket(std::vector<std::string>&& args) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700651 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
652 !StartsWith(args[2], "seqpacket")) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700653 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
Tom Cherryb7349902015-08-26 11:43:36 -0700654 }
Tom Cherry018a4382018-10-17 11:11:23 -0700655 return AddDescriptor<SocketInfo>(std::move(args));
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700656}
Tom Cherryb7349902015-08-26 11:43:36 -0700657
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700658// name type perm [ uid gid context ]
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700659Result<void> Service::ParseFile(std::vector<std::string>&& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700660 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
Tom Cherry89bcc852017-08-02 17:01:36 -0700661 return Error() << "file type must be 'r', 'w' or 'rw'";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700662 }
Yifan Hong567f1872019-03-19 14:38:48 -0700663 std::string expanded;
664 if (!expand_props(args[1], &expanded)) {
665 return Error() << "Could not expand property in file path '" << args[1] << "'";
666 }
667 args[1] = std::move(expanded);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700668 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700669 return Error() << "file name must not be relative";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700670 }
Tom Cherry018a4382018-10-17 11:11:23 -0700671 return AddDescriptor<FileInfo>(std::move(args));
Tom Cherryb7349902015-08-26 11:43:36 -0700672}
673
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700674Result<void> Service::ParseUser(std::vector<std::string>&& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700675 auto uid = DecodeUid(args[1]);
676 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700677 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700678 }
Vic Yange01ca4d2019-05-29 15:58:32 -0700679 proc_attr_.uid = *uid;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700680 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700681}
682
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700683Result<void> Service::ParseWritepid(std::vector<std::string>&& args) {
Tom Cherry018a4382018-10-17 11:11:23 -0700684 args.erase(args.begin());
685 writepid_files_ = std::move(args);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700686 return {};
Tom Cherryb7349902015-08-26 11:43:36 -0700687}
688
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700689Result<void> Service::ParseUpdatable(std::vector<std::string>&& args) {
Jiyong Park80aa4472018-11-12 12:08:41 +0900690 updatable_ = true;
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700691 return {};
Jiyong Park80aa4472018-11-12 12:08:41 +0900692}
693
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400694class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700695 public:
696 OptionParserMap() {}
697
698 private:
699 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700700};
701
Tom Cherryad54d092017-04-19 16:18:50 -0700702const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700703 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700704 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400705 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400706 {"capabilities",
Tom Cherry1cd082d2019-02-06 10:45:56 -0800707 {0, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700708 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400709 {"console", {0, 1, &Service::ParseConsole}},
710 {"critical", {0, 0, &Service::ParseCritical}},
711 {"disabled", {0, 0, &Service::ParseDisabled}},
Tom Cherryaead51b2018-04-20 16:18:12 -0700712 {"enter_namespace",
713 {2, 2, &Service::ParseEnterNamespace}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800714 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400715 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
Steven Morelande055d732017-10-05 18:50:22 -0700716 {"interface", {2, 2, &Service::ParseInterface}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400717 {"ioprio", {2, 2, &Service::ParseIoprio}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400718 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
Robert Benead4852262017-07-16 19:38:11 -0700719 {"memcg.limit_in_bytes",
720 {1, 1, &Service::ParseMemcgLimitInBytes}},
Peter Collingbourned7157c22018-10-30 15:49:33 -0700721 {"memcg.limit_percent",
722 {1, 1, &Service::ParseMemcgLimitPercent}},
723 {"memcg.limit_property",
724 {1, 1, &Service::ParseMemcgLimitProperty}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800725 {"memcg.soft_limit_in_bytes",
726 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
727 {"memcg.swappiness",
728 {1, 1, &Service::ParseMemcgSwappiness}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400729 {"namespace", {1, 2, &Service::ParseNamespace}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800730 {"oneshot", {0, 0, &Service::ParseOneshot}},
731 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
732 {"oom_score_adjust",
733 {1, 1, &Service::ParseOomScoreAdjust}},
734 {"override", {0, 0, &Service::ParseOverride}},
735 {"priority", {1, 1, &Service::ParsePriority}},
Tom Cherry73f535e2018-09-27 16:10:46 -0700736 {"restart_period",
737 {1, 1, &Service::ParseRestartPeriod}},
Tom Cherry7ac013d2017-08-25 10:39:25 -0700738 {"rlimit", {3, 3, &Service::ParseProcessRlimit}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400739 {"seclabel", {1, 1, &Service::ParseSeclabel}},
740 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700741 {"shutdown", {1, 1, &Service::ParseShutdown}},
Tom Cherry8f380482018-04-17 14:48:44 -0700742 {"sigstop", {0, 0, &Service::ParseSigstop}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400743 {"socket", {3, 6, &Service::ParseSocket}},
Tom Cherry73f535e2018-09-27 16:10:46 -0700744 {"timeout_period",
745 {1, 1, &Service::ParseTimeoutPeriod}},
Jiyong Park80aa4472018-11-12 12:08:41 +0900746 {"updatable", {0, 0, &Service::ParseUpdatable}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400747 {"user", {1, 1, &Service::ParseUser}},
748 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700749 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700750 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400751 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700752}
753
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700754Result<void> Service::ParseLine(std::vector<std::string>&& args) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400755 static const OptionParserMap parser_map;
Tom Cherry89bcc852017-08-02 17:01:36 -0700756 auto parser = parser_map.FindFunction(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700757
Tom Cherry76af7e62017-08-22 16:13:59 -0700758 if (!parser) return parser.error();
Tom Cherryb7349902015-08-26 11:43:36 -0700759
Tom Cherry018a4382018-10-17 11:11:23 -0700760 return std::invoke(*parser, this, std::move(args));
Tom Cherryb7349902015-08-26 11:43:36 -0700761}
762
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700763Result<void> Service::ExecStart() {
Jiyong Park80aa4472018-11-12 12:08:41 +0900764 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
765 // Don't delay the service for ExecStart() as the semantic is that
766 // the caller might depend on the side effect of the execution.
767 return Error() << "Cannot start an updatable service '" << name_
768 << "' before configs from APEXes are all loaded";
769 }
770
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700771 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700772
Tom Cherry76af7e62017-08-22 16:13:59 -0700773 if (auto result = Start(); !result) {
774 return result;
Tom Cherryb27004a2017-03-27 16:27:30 -0700775 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700776
777 flags_ |= SVC_EXEC;
778 is_exec_service_running_ = true;
779
Vic Yange01ca4d2019-05-29 15:58:32 -0700780 LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << proc_attr_.uid
781 << " gid " << proc_attr_.gid << "+" << proc_attr_.supp_gids.size() << " context "
Wei Wang2c4ee752018-06-20 14:54:52 -0700782 << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700783
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700784 return {};
Tom Cherryb27004a2017-03-27 16:27:30 -0700785}
786
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700787Result<void> Service::Start() {
Jiyong Park80aa4472018-11-12 12:08:41 +0900788 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
789 ServiceList::GetInstance().DelayService(*this);
790 return Error() << "Cannot start an updatable service '" << name_
791 << "' before configs from APEXes are all loaded. "
792 << "Queued for execution.";
793 }
794
Tao Wu990d43c2017-10-26 10:43:10 -0700795 bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
Tom Cherrybac32992015-07-31 12:45:25 -0700796 // Starting a service removes it from the disabled or reset state and
797 // immediately takes it out of the restarting state if it was in there.
798 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700799
800 // Running processes require no additional work --- if they're in the
801 // process of exiting, we've ensured that they will immediately restart
Tao Wu990d43c2017-10-26 10:43:10 -0700802 // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
803 // stopping status, we just set SVC_RESTART flag so it will get restarted
804 // in Reap().
Tom Cherrybac32992015-07-31 12:45:25 -0700805 if (flags_ & SVC_RUNNING) {
Tao Wu990d43c2017-10-26 10:43:10 -0700806 if ((flags_ & SVC_ONESHOT) && disabled) {
807 flags_ |= SVC_RESTART;
808 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700809 // It is not an error to try to start a service that is already running.
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700810 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700811 }
812
813 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200814 if (needs_console) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700815 if (proc_attr_.console.empty()) {
816 proc_attr_.console = default_console;
Viorel Suman70daa672016-03-21 10:08:07 +0200817 }
818
Adrian Salido24ef8602016-12-20 15:52:15 -0800819 // Make sure that open call succeeds to ensure a console driver is
820 // properly registered for the device node
Vic Yange01ca4d2019-05-29 15:58:32 -0700821 int console_fd = open(proc_attr_.console.c_str(), O_RDWR | O_CLOEXEC);
Adrian Salido24ef8602016-12-20 15:52:15 -0800822 if (console_fd < 0) {
Viorel Suman70daa672016-03-21 10:08:07 +0200823 flags_ |= SVC_DISABLED;
Vic Yange01ca4d2019-05-29 15:58:32 -0700824 return ErrnoError() << "Couldn't open console '" << proc_attr_.console << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200825 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800826 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700827 }
828
829 struct stat sb;
830 if (stat(args_[0].c_str(), &sb) == -1) {
Tom Cherrybac32992015-07-31 12:45:25 -0700831 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700832 return ErrnoError() << "Cannot find '" << args_[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700833 }
834
Tom Cherrybac32992015-07-31 12:45:25 -0700835 std::string scon;
836 if (!seclabel_.empty()) {
837 scon = seclabel_;
838 } else {
Tom Cherryaead51b2018-04-20 16:18:12 -0700839 auto result = ComputeContextFromExecutable(args_[0]);
Tom Cherry76af7e62017-08-22 16:13:59 -0700840 if (!result) {
841 return result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700842 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700843 scon = *result;
Tom Cherrybac32992015-07-31 12:45:25 -0700844 }
845
Jiyong Park68660412019-01-16 23:00:59 +0900846 if (!IsRuntimeApexReady() && !pre_apexd_) {
847 // If this service is started before the runtime APEX gets available,
848 // mark it as pre-apexd one. Note that this marking is permanent. So
849 // for example, if the service is re-launched (e.g., due to crash),
850 // it is still recognized as pre-apexd... for consistency.
851 pre_apexd_ = true;
852 }
853
Martijn Coenen70788f92019-04-23 16:26:01 +0200854 post_data_ = ServiceList::GetInstance().IsPostData();
855
Wei Wanga285dac2016-10-04 14:05:39 -0700856 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700857
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700858 pid_t pid = -1;
Vic Yange01ca4d2019-05-29 15:58:32 -0700859 if (namespaces_.flags) {
860 pid = clone(nullptr, nullptr, namespaces_.flags | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700861 } else {
862 pid = fork();
863 }
864
Tom Cherrybac32992015-07-31 12:45:25 -0700865 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700866 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700867
Vic Yange01ca4d2019-05-29 15:58:32 -0700868 if (auto result = EnterNamespaces(namespaces_, name_, pre_apexd_); !result) {
869 LOG(FATAL) << "Service '" << name_
870 << "' failed to set up namespaces: " << result.error();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700871 }
872
Tom Cherry6de21f12017-08-22 15:41:03 -0700873 for (const auto& [key, value] : environment_vars_) {
874 setenv(key.c_str(), value.c_str(), 1);
Tom Cherrybac32992015-07-31 12:45:25 -0700875 }
876
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700877 std::for_each(descriptors_.begin(), descriptors_.end(),
878 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700879
Vic Yange01ca4d2019-05-29 15:58:32 -0700880 if (auto result = WritePidToFiles(&writepid_files_); !result) {
881 LOG(ERROR) << "failed to write pid to files: " << result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700882 }
883
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400884 // As requested, set our gid, supplemental gids, uid, context, and
885 // priority. Aborts on failure.
Vic Yange01ca4d2019-05-29 15:58:32 -0700886 SetProcessAttributesAndCaps();
Tom Cherrybac32992015-07-31 12:45:25 -0700887
Tom Cherry8f380482018-04-17 14:48:44 -0700888 if (!ExpandArgsAndExecv(args_, sigstop_)) {
Tom Cherry5e405ca2017-09-11 16:08:54 -0700889 PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700890 }
891
892 _exit(127);
893 }
894
895 if (pid < 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700896 pid_ = 0;
Tom Cherry76af7e62017-08-22 16:13:59 -0700897 return ErrnoError() << "Failed to fork";
Tom Cherrybac32992015-07-31 12:45:25 -0700898 }
899
Marco Nelissen310f6702016-07-22 12:07:06 -0700900 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700901 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700902 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
903 if (!WriteStringToFile(oom_str, oom_file)) {
Elliott Hughes076305e2019-03-08 12:34:53 -0800904 PLOG(ERROR) << "couldn't write oom_score_adj";
Marco Nelissen310f6702016-07-22 12:07:06 -0700905 }
906 }
907
Elliott Hughes9605a942016-11-10 17:43:47 -0800908 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700909 pid_ = pid;
910 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -0700911 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -0700912 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700913
Peter Collingbourned7157c22018-10-30 15:49:33 -0700914 bool use_memcg = swappiness_ != -1 || soft_limit_in_bytes_ != -1 || limit_in_bytes_ != -1 ||
915 limit_percent_ != -1 || !limit_property_.empty();
Vic Yange01ca4d2019-05-29 15:58:32 -0700916 errno = -createProcessGroup(proc_attr_.uid, pid_, use_memcg);
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700917 if (errno != 0) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700918 PLOG(ERROR) << "createProcessGroup(" << proc_attr_.uid << ", " << pid_
919 << ") failed for service '" << name_ << "'";
Peter Collingbourned7157c22018-10-30 15:49:33 -0700920 } else if (use_memcg) {
Robert Benead4852262017-07-16 19:38:11 -0700921 if (swappiness_ != -1) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700922 if (!setProcessGroupSwappiness(proc_attr_.uid, pid_, swappiness_)) {
Robert Benead4852262017-07-16 19:38:11 -0700923 PLOG(ERROR) << "setProcessGroupSwappiness failed";
924 }
925 }
926
927 if (soft_limit_in_bytes_ != -1) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700928 if (!setProcessGroupSoftLimit(proc_attr_.uid, pid_, soft_limit_in_bytes_)) {
Robert Benead4852262017-07-16 19:38:11 -0700929 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
930 }
931 }
932
Peter Collingbourned7157c22018-10-30 15:49:33 -0700933 size_t computed_limit_in_bytes = limit_in_bytes_;
934 if (limit_percent_ != -1) {
935 long page_size = sysconf(_SC_PAGESIZE);
936 long num_pages = sysconf(_SC_PHYS_PAGES);
937 if (page_size > 0 && num_pages > 0) {
938 size_t max_mem = SIZE_MAX;
939 if (size_t(num_pages) < SIZE_MAX / size_t(page_size)) {
940 max_mem = size_t(num_pages) * size_t(page_size);
941 }
942 computed_limit_in_bytes =
943 std::min(computed_limit_in_bytes, max_mem / 100 * limit_percent_);
944 }
945 }
946
947 if (!limit_property_.empty()) {
948 // This ends up overwriting computed_limit_in_bytes but only if the
949 // property is defined.
950 computed_limit_in_bytes = android::base::GetUintProperty(
951 limit_property_, computed_limit_in_bytes, SIZE_MAX);
952 }
953
954 if (computed_limit_in_bytes != size_t(-1)) {
Vic Yange01ca4d2019-05-29 15:58:32 -0700955 if (!setProcessGroupLimit(proc_attr_.uid, pid_, computed_limit_in_bytes)) {
Robert Benead4852262017-07-16 19:38:11 -0700956 PLOG(ERROR) << "setProcessGroupLimit failed";
957 }
958 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700959 }
Tom Cherrybac32992015-07-31 12:45:25 -0700960
Tom Cherrybac32992015-07-31 12:45:25 -0700961 NotifyStateChange("running");
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700962 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700963}
964
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700965Result<void> Service::StartIfNotDisabled() {
Tom Cherrybac32992015-07-31 12:45:25 -0700966 if (!(flags_ & SVC_DISABLED)) {
967 return Start();
968 } else {
969 flags_ |= SVC_DISABLED_START;
970 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700971 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700972}
973
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700974Result<void> Service::Enable() {
Tom Cherrybac32992015-07-31 12:45:25 -0700975 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
976 if (flags_ & SVC_DISABLED_START) {
977 return Start();
978 }
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700979 return {};
Tom Cherrybac32992015-07-31 12:45:25 -0700980}
981
982void Service::Reset() {
983 StopOrReset(SVC_RESET);
984}
985
Martijn Coenen70788f92019-04-23 16:26:01 +0200986void Service::ResetIfPostData() {
987 if (post_data_) {
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200988 if (flags_ & SVC_RUNNING) {
989 running_at_post_data_reset_ = true;
990 }
Martijn Coenen70788f92019-04-23 16:26:01 +0200991 StopOrReset(SVC_RESET);
992 }
993}
994
Tom Cherrybbcbc2f2019-06-10 11:08:01 -0700995Result<void> Service::StartIfPostData() {
Martijn Coenenacc45aa2019-05-15 22:04:13 +0200996 // Start the service, but only if it was started after /data was mounted,
997 // and it was still running when we reset the post-data services.
998 if (running_at_post_data_reset_) {
999 return Start();
1000 }
1001
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001002 return {};
Martijn Coenenacc45aa2019-05-15 22:04:13 +02001003}
1004
Tom Cherrybac32992015-07-31 12:45:25 -07001005void Service::Stop() {
1006 StopOrReset(SVC_DISABLED);
1007}
1008
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001009void Service::Terminate() {
1010 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1011 flags_ |= SVC_DISABLED;
1012 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001013 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001014 NotifyStateChange("stopping");
1015 }
1016}
1017
Tom Cherry73f535e2018-09-27 16:10:46 -07001018void Service::Timeout() {
1019 // All process state flags will be taken care of in Reap(), we really just want to kill the
1020 // process here when it times out. Oneshot processes will transition to be disabled, and
1021 // all other processes will transition to be restarting.
1022 LOG(INFO) << "Service '" << name_ << "' expired its timeout of " << timeout_period_->count()
1023 << " seconds and will now be killed";
1024 if (pid_) {
1025 KillProcessGroup(SIGKILL);
1026 NotifyStateChange("stopping");
1027 }
1028}
1029
Tom Cherrybac32992015-07-31 12:45:25 -07001030void Service::Restart() {
1031 if (flags_ & SVC_RUNNING) {
1032 /* Stop, wait, then start the service. */
1033 StopOrReset(SVC_RESTART);
1034 } else if (!(flags_ & SVC_RESTARTING)) {
1035 /* Just start the service since it's not running. */
Tom Cherry76af7e62017-08-22 16:13:59 -07001036 if (auto result = Start(); !result) {
1037 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
1038 }
Tom Cherrybac32992015-07-31 12:45:25 -07001039 } /* else: Service is restarting anyways. */
1040}
1041
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001042// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -07001043void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001044 // The service is still SVC_RUNNING until its process exits, but if it has
1045 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -07001046 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1047
1048 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001049 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -07001050 how = SVC_DISABLED;
1051 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001052
1053 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -07001054 if (how == SVC_RESET) {
1055 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
1056 } else {
1057 flags_ |= how;
1058 }
Tao Wu84b856d2017-10-27 11:29:13 -07001059 // Make sure it's in right status when a restart immediately follow a
1060 // stop/reset or vice versa.
1061 if (how == SVC_RESTART) {
1062 flags_ &= (~(SVC_DISABLED | SVC_RESET));
1063 } else {
1064 flags_ &= (~SVC_RESTART);
1065 }
Tom Cherrybac32992015-07-31 12:45:25 -07001066
1067 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001068 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -07001069 NotifyStateChange("stopping");
1070 } else {
1071 NotifyStateChange("stopped");
1072 }
1073}
1074
Tom Cherry911b9b12017-07-27 16:20:58 -07001075ServiceList::ServiceList() {}
Tom Cherrybac32992015-07-31 12:45:25 -07001076
Tom Cherry911b9b12017-07-27 16:20:58 -07001077ServiceList& ServiceList::GetInstance() {
1078 static ServiceList instance;
Tom Cherrybac32992015-07-31 12:45:25 -07001079 return instance;
1080}
1081
Tom Cherry911b9b12017-07-27 16:20:58 -07001082void ServiceList::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -07001083 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -07001084}
1085
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001086std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -07001087 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
1088 // SECLABEL can be a - to denote default
1089 std::size_t command_arg = 1;
1090 for (std::size_t i = 1; i < args.size(); ++i) {
1091 if (args[i] == "--") {
1092 command_arg = i + 1;
1093 break;
1094 }
1095 }
1096 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001097 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -07001098 return nullptr;
1099 }
1100
1101 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001102 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -07001103 return nullptr;
1104 }
1105 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
1106
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001107 static size_t exec_count = 0;
1108 exec_count++;
1109 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -07001110
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001111 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001112 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001113
1114 std::string seclabel = "";
1115 if (command_arg > 2 && args[1] != "-") {
1116 seclabel = args[1];
1117 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001118 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001119 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001120 uid = DecodeUid(args[2]);
1121 if (!uid) {
1122 LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001123 return nullptr;
1124 }
Tom Cherrybac32992015-07-31 12:45:25 -07001125 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001126 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001127 std::vector<gid_t> supp_gids;
1128 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001129 gid = DecodeUid(args[3]);
1130 if (!gid) {
1131 LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001132 return nullptr;
1133 }
Tom Cherrybac32992015-07-31 12:45:25 -07001134 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
1135 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001136 auto supp_gid = DecodeUid(args[4 + i]);
1137 if (!supp_gid) {
1138 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
1139 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001140 return nullptr;
1141 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001142 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -07001143 }
1144 }
1145
Tom Cherry1cd082d2019-02-06 10:45:56 -08001146 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, namespace_flags, seclabel,
1147 nullptr, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001148}
1149
Tom Cherry59383792017-07-26 16:09:09 -07001150// Shutdown services in the opposite order that they were started.
Tom Cherry911b9b12017-07-27 16:20:58 -07001151const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
Tom Cherry59383792017-07-26 16:09:09 -07001152 std::vector<Service*> shutdown_services;
1153 for (const auto& service : services_) {
1154 if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
1155 }
1156 std::sort(shutdown_services.begin(), shutdown_services.end(),
1157 [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
Tom Cherry911b9b12017-07-27 16:20:58 -07001158 return shutdown_services;
Tom Cherry59383792017-07-26 16:09:09 -07001159}
1160
Tom Cherry911b9b12017-07-27 16:20:58 -07001161void ServiceList::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001162 auto svc_it = std::find_if(services_.begin(), services_.end(),
1163 [&svc] (const std::unique_ptr<Service>& s) {
1164 return svc.name() == s->name();
1165 });
1166 if (svc_it == services_.end()) {
1167 return;
1168 }
1169
1170 services_.erase(svc_it);
1171}
1172
Tom Cherry911b9b12017-07-27 16:20:58 -07001173void ServiceList::DumpState() const {
Tom Cherryb7349902015-08-26 11:43:36 -07001174 for (const auto& s : services_) {
1175 s->DumpState();
1176 }
Tom Cherryb7349902015-08-26 11:43:36 -07001177}
1178
Martijn Coenen70788f92019-04-23 16:26:01 +02001179void ServiceList::MarkPostData() {
1180 post_data_ = true;
1181}
1182
1183bool ServiceList::IsPostData() {
1184 return post_data_;
1185}
1186
Jiyong Park80aa4472018-11-12 12:08:41 +09001187void ServiceList::MarkServicesUpdate() {
1188 services_update_finished_ = true;
1189
1190 // start the delayed services
1191 for (const auto& name : delayed_service_names_) {
1192 Service* service = FindService(name);
1193 if (service == nullptr) {
1194 LOG(ERROR) << "delayed service '" << name << "' could not be found.";
1195 continue;
1196 }
1197 if (auto result = service->Start(); !result) {
Jiyong Park8fd64c82019-05-31 03:43:34 +09001198 LOG(ERROR) << result.error().message();
Jiyong Park80aa4472018-11-12 12:08:41 +09001199 }
1200 }
1201 delayed_service_names_.clear();
1202}
1203
1204void ServiceList::DelayService(const Service& service) {
1205 if (services_update_finished_) {
1206 LOG(ERROR) << "Cannot delay the start of service '" << service.name()
1207 << "' because all services are already updated. Ignoring.";
1208 return;
1209 }
1210 delayed_service_names_.emplace_back(service.name());
1211}
1212
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001213Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
1214 const std::string& filename, int line) {
Tom Cherryb7349902015-08-26 11:43:36 -07001215 if (args.size() < 3) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001216 return Error() << "services must have a name and a program";
Tom Cherryb7349902015-08-26 11:43:36 -07001217 }
1218
1219 const std::string& name = args[1];
1220 if (!IsValidName(name)) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001221 return Error() << "invalid service name '" << name << "'";
Tom Cherryb7349902015-08-26 11:43:36 -07001222 }
1223
Jiyong Park80aa4472018-11-12 12:08:41 +09001224 filename_ = filename;
1225
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001226 Subcontext* restart_action_subcontext = nullptr;
1227 if (subcontexts_) {
1228 for (auto& subcontext : *subcontexts_) {
Elliott Hughes579e6822017-12-20 09:41:00 -08001229 if (StartsWith(filename, subcontext.path_prefix())) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001230 restart_action_subcontext = &subcontext;
1231 break;
1232 }
1233 }
1234 }
1235
Tom Cherryb7349902015-08-26 11:43:36 -07001236 std::vector<std::string> str_args(args.begin() + 2, args.end());
Tom Cherry40acb372018-08-01 13:41:12 -07001237
1238 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
1239 if (str_args[0] == "/sbin/watchdogd") {
1240 str_args[0] = "/system/bin/watchdogd";
1241 }
1242 }
1243
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001244 service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001245 return {};
Tom Cherryb7349902015-08-26 11:43:36 -07001246}
1247
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001248Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
1249 return service_ ? service_->ParseLine(std::move(args)) : Result<void>{};
Tom Cherryb7349902015-08-26 11:43:36 -07001250}
1251
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001252Result<void> ServiceParser::EndSection() {
Tom Cherryb7349902015-08-26 11:43:36 -07001253 if (service_) {
Steven Moreland5e1bea32017-11-10 14:43:58 -08001254 Service* old_service = service_list_->FindService(service_->name());
1255 if (old_service) {
Steven Moreland6f5333a2017-11-13 15:31:54 -08001256 if (!service_->is_override()) {
1257 return Error() << "ignored duplicate definition of service '" << service_->name()
1258 << "'";
1259 }
1260
Jiyong Park80aa4472018-11-12 12:08:41 +09001261 if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
1262 return Error() << "cannot update a non-updatable service '" << service_->name()
1263 << "' with a config in APEX";
1264 }
1265
Steven Moreland6f5333a2017-11-13 15:31:54 -08001266 service_list_->RemoveService(*old_service);
1267 old_service = nullptr;
Steven Moreland5e1bea32017-11-10 14:43:58 -08001268 }
1269
Tom Cherry911b9b12017-07-27 16:20:58 -07001270 service_list_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001271 }
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001272
Tom Cherrybbcbc2f2019-06-10 11:08:01 -07001273 return {};
Tom Cherryb7349902015-08-26 11:43:36 -07001274}
1275
1276bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001277 // Property names can be any length, but may only contain certain characters.
1278 // Property values can contain any characters, but may only be a certain length.
1279 // (The latter restriction is needed because `start` and `stop` work by writing
1280 // the service name to the "ctl.start" and "ctl.stop" properties.)
Tom Cherryde6bd502018-02-13 16:50:08 -08001281 return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001282}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001283
1284} // namespace init
1285} // namespace android