blob: f3eafe410cc96003996c4bd17b57a11ce9e1637c [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>
24#include <sys/mount.h>
25#include <sys/prctl.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070026#include <sys/resource.h>
Tom Cherrybac32992015-07-31 12:45:25 -070027#include <sys/stat.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070028#include <sys/time.h>
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -080029#include <sys/wait.h>
Tom Cherrybac32992015-07-31 12:45:25 -070030#include <termios.h>
Dan Albertaf9ba4d2015-08-11 16:37:04 -070031#include <unistd.h>
Tom Cherrybac32992015-07-31 12:45:25 -070032
Elliott Hughes4f713192015-12-04 22:00:26 -080033#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070034#include <android-base/logging.h>
Elliott Hughesda46b392016-10-11 17:09:00 -070035#include <android-base/parseint.h>
Elliott Hughesdc803122018-05-24 18:00:39 -070036#include <android-base/properties.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080037#include <android-base/stringprintf.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070038#include <android-base/strings.h>
Tom Cherryaead51b2018-04-20 16:18:12 -070039#include <android-base/unique_fd.h>
Steven Morelande055d732017-10-05 18:50:22 -070040#include <hidl-util/FQName.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070041#include <processgroup/processgroup.h>
42#include <selinux/selinux.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070043#include <system/thread_defs.h>
Tom Cherrybac32992015-07-31 12:45:25 -070044
Tom Cherry7ac013d2017-08-25 10:39:25 -070045#include "rlimit_parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070046#include "util.h"
47
Tom Cherryde6bd502018-02-13 16:50:08 -080048#if defined(__ANDROID__)
Tom Cherry40acb372018-08-01 13:41:12 -070049#include <android/api-level.h>
Tom Cherryde6bd502018-02-13 16:50:08 -080050#include <sys/system_properties.h>
51
Tom Cherryde6bd502018-02-13 16:50:08 -080052#include "init.h"
53#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;
Tom Cherryaead51b2018-04-20 16:18:12 -070066using android::base::unique_fd;
Tom Cherryb7349902015-08-26 11:43:36 -070067using android::base::WriteStringToFile;
68
Tom Cherry81f5d3e2017-06-22 12:53:17 -070069namespace android {
70namespace init {
71
Tom Cherryaead51b2018-04-20 16:18:12 -070072static Result<std::string> ComputeContextFromExecutable(const std::string& service_path) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040073 std::string computed_context;
74
75 char* raw_con = nullptr;
76 char* raw_filecon = nullptr;
77
78 if (getcon(&raw_con) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070079 return Error() << "Could not get security context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040080 }
81 std::unique_ptr<char> mycon(raw_con);
82
83 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070084 return Error() << "Could not get file context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040085 }
86 std::unique_ptr<char> filecon(raw_filecon);
87
88 char* new_con = nullptr;
89 int rc = security_compute_create(mycon.get(), filecon.get(),
90 string_to_security_class("process"), &new_con);
91 if (rc == 0) {
92 computed_context = new_con;
93 free(new_con);
94 }
95 if (rc == 0 && computed_context == mycon.get()) {
Nick Kralevich1ea19eb2017-08-25 12:08:57 -070096 return Error() << "File " << service_path << "(labeled \"" << filecon.get()
97 << "\") has incorrect label or no domain transition from " << mycon.get()
98 << " to another SELinux domain defined. Have you configured your "
99 "service correctly? https://source.android.com/security/selinux/"
100 "device-policy#label_new_services_and_address_denials";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400101 }
102 if (rc < 0) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700103 return Error() << "Could not get process context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400104 }
105 return computed_context;
106}
107
Tom Cherryaead51b2018-04-20 16:18:12 -0700108Result<Success> Service::SetUpMountNamespace() const {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700109 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
110
Joe Tanen4bfdcb32017-10-25 08:07:26 -0400111 // Recursively remount / as slave like zygote does so unmounting and mounting /proc
112 // doesn't interfere with the parent namespace's /proc mount. This will also
113 // prevent any other mounts/unmounts initiated by the service from interfering
114 // with the parent namespace but will still allow mount events from the parent
115 // namespace to propagate to the child.
116 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700117 return ErrnoError() << "Could not remount(/) recursively as slave";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700118 }
119
Tom Cherryaead51b2018-04-20 16:18:12 -0700120 // umount() then mount() /proc and/or /sys
121 // Note that it is not sufficient to mount with MS_REMOUNT.
122 if (namespace_flags_ & CLONE_NEWPID) {
123 if (umount("/proc") == -1) {
124 return ErrnoError() << "Could not umount(/proc)";
125 }
126 if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
127 return ErrnoError() << "Could not mount(/proc)";
128 }
129 }
130 bool remount_sys = std::any_of(namespaces_to_enter_.begin(), namespaces_to_enter_.end(),
131 [](const auto& entry) { return entry.first == CLONE_NEWNET; });
132 if (remount_sys) {
133 if (umount2("/sys", MNT_DETACH) == -1) {
134 return ErrnoError() << "Could not umount(/sys)";
135 }
Tom Cherry9bb0a4d2018-07-13 11:07:11 -0700136 if (mount("", "/sys", "sysfs", kSafeFlags, "") == -1) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700137 return ErrnoError() << "Could not mount(/sys)";
138 }
139 }
140 return Success();
141}
142
Jiyong Park25990882019-01-02 23:37:15 +0900143Result<Success> Service::SetUpPreApexdMounts() const {
144 // If a pre-apexd service is 're' launched after the runtime APEX is
145 // available, unmount the linker and bionic libs which are currently
146 // bind mounted to the files in the runtime APEX. This will reveal
147 // the hidden mount points (targetting the bootstrap ones in the
148 // system partition) which were setup before the runtime APEX was
149 // started. Note that these unmounts are done in a separate mount namespace
150 // for the process. It does not affect other processes including the init.
151 if (pre_apexd_ && ServiceList::GetInstance().IsRuntimeAvailable()) {
152 if (access(kLinkerMountPoint, F_OK) == 0) {
153 if (umount(kLinkerMountPoint) == -1) {
154 return ErrnoError() << "Could not umount " << kLinkerMountPoint;
155 }
156 for (const auto& libname : kBionicLibFileNames) {
157 std::string mount_point = kBionicLibsMountPointDir + libname;
158 if (umount(mount_point.c_str()) == -1) {
159 return ErrnoError() << "Could not umount " << mount_point;
160 }
161 }
162 }
163
164 if (access(kLinkerMountPoint64, F_OK) == 0) {
165 if (umount(kLinkerMountPoint64) == -1) {
166 return ErrnoError() << "Could not umount " << kLinkerMountPoint64;
167 }
168 for (const auto& libname : kBionicLibFileNames) {
169 std::string mount_point = kBionicLibsMountPointDir64 + libname;
170 std::string source = kBootstrapBionicLibsDir64 + libname;
171 if (umount(mount_point.c_str()) == -1) {
172 return ErrnoError() << "Could not umount " << mount_point;
173 }
174 }
175 }
176 }
177 return Success();
178}
179
Tom Cherryaead51b2018-04-20 16:18:12 -0700180Result<Success> Service::SetUpPidNamespace() const {
181 if (prctl(PR_SET_NAME, name_.c_str()) == -1) {
182 return ErrnoError() << "Could not set name";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700183 }
184
185 pid_t child_pid = fork();
186 if (child_pid == -1) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700187 return ErrnoError() << "Could not fork init inside the PID namespace";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700188 }
189
190 if (child_pid > 0) {
191 // So that we exit with the right status.
192 static int init_exitstatus = 0;
193 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
194
195 pid_t waited_pid;
196 int status;
197 while ((waited_pid = wait(&status)) > 0) {
198 // This loop will end when there are no processes left inside the
199 // PID namespace or when the init process inside the PID namespace
200 // gets a signal.
201 if (waited_pid == child_pid) {
202 init_exitstatus = status;
203 }
204 }
205 if (!WIFEXITED(init_exitstatus)) {
206 _exit(EXIT_FAILURE);
207 }
208 _exit(WEXITSTATUS(init_exitstatus));
209 }
Tom Cherryaead51b2018-04-20 16:18:12 -0700210 return Success();
211}
212
213Result<Success> Service::EnterNamespaces() const {
214 for (const auto& [nstype, path] : namespaces_to_enter_) {
215 auto fd = unique_fd{open(path.c_str(), O_RDONLY | O_CLOEXEC)};
216 if (!fd) {
217 return ErrnoError() << "Could not open namespace at " << path;
218 }
219 if (setns(fd, nstype) == -1) {
220 return ErrnoError() << "Could not setns() namespace at " << path;
221 }
222 }
223 return Success();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700224}
225
Tom Cherry8f380482018-04-17 14:48:44 -0700226static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400227 std::vector<std::string> expanded_args;
Tom Cherry5e405ca2017-09-11 16:08:54 -0700228 std::vector<char*> c_strings;
229
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400230 expanded_args.resize(args.size());
Tom Cherry5e405ca2017-09-11 16:08:54 -0700231 c_strings.push_back(const_cast<char*>(args[0].data()));
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400232 for (std::size_t i = 1; i < args.size(); ++i) {
233 if (!expand_props(args[i], &expanded_args[i])) {
234 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
235 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700236 c_strings.push_back(expanded_args[i].data());
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400237 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700238 c_strings.push_back(nullptr);
239
Tom Cherry8f380482018-04-17 14:48:44 -0700240 if (sigstop) {
241 kill(getpid(), SIGSTOP);
242 }
243
Tom Cherry5e405ca2017-09-11 16:08:54 -0700244 return execv(c_strings[0], c_strings.data()) == 0;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400245}
246
Tom Cherry59383792017-07-26 16:09:09 -0700247unsigned long Service::next_start_order_ = 1;
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700248bool Service::is_exec_service_running_ = false;
Tom Cherry59383792017-07-26 16:09:09 -0700249
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700250Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
251 const std::vector<std::string>& args)
252 : Service(name, 0, 0, 0, {}, 0, 0, "", subcontext_for_restart_commands, args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700253
Wei Wang641ff0a2017-03-27 10:59:11 -0700254Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
255 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
256 unsigned namespace_flags, const std::string& seclabel,
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700257 Subcontext* subcontext_for_restart_commands, const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700258 : name_(name),
259 classnames_({"default"}),
260 flags_(flags),
261 pid_(0),
262 crash_count_(0),
263 uid_(uid),
264 gid_(gid),
265 supp_gids_(supp_gids),
266 capabilities_(capabilities),
267 namespace_flags_(namespace_flags),
268 seclabel_(seclabel),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800269 onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0,
270 "onrestart", {}),
Wei Wang641ff0a2017-03-27 10:59:11 -0700271 ioprio_class_(IoSchedClass_NONE),
272 ioprio_pri_(0),
273 priority_(0),
274 oom_score_adjust_(-1000),
Tom Cherry59383792017-07-26 16:09:09 -0700275 start_order_(0),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800276 args_(args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700277
278void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700279 if ((flags_ & SVC_TEMPORARY) != 0) {
280 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700281 return;
282 }
283
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700284 std::string prop_name = "init.svc." + name_;
285 property_set(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800286
287 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800288 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherryfed33732017-08-18 10:47:46 -0700289 std::string boottime_property = "ro.boottime." + name_;
290 if (GetProperty(boottime_property, "").empty()) {
291 property_set(boottime_property, std::to_string(start_ns));
292 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800293 }
Tom Cherrybac32992015-07-31 12:45:25 -0700294}
295
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700296void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700297 // If we've already seen a successful result from killProcessGroup*(), then we have removed
298 // the cgroup already and calling these functions a second time will simply result in an error.
299 // This is true regardless of which signal was sent.
300 // These functions handle their own logging, so no additional logging is needed.
301 if (!process_cgroup_empty_) {
302 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
303 << ") process group...";
304 int r;
305 if (signal == SIGTERM) {
306 r = killProcessGroupOnce(uid_, pid_, signal);
307 } else {
308 r = killProcessGroup(uid_, pid_, signal);
309 }
310
311 if (r == 0) process_cgroup_empty_ = true;
312 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700313}
314
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400315void Service::SetProcessAttributes() {
Tom Cherry7ac013d2017-08-25 10:39:25 -0700316 for (const auto& rlimit : rlimits_) {
317 if (setrlimit(rlimit.first, &rlimit.second) == -1) {
318 LOG(FATAL) << StringPrintf("setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed",
319 rlimit.first, rlimit.second.rlim_cur, rlimit.second.rlim_max);
320 }
321 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400322 // Keep capabilites on uid change.
323 if (capabilities_.any() && uid_) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700324 // If Android is running in a container, some securebits might already
325 // be locked, so don't change those.
Ben Fennemaa7243602017-07-25 14:37:21 -0700326 unsigned long securebits = prctl(PR_GET_SECUREBITS);
327 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700328 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
329 }
330 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
331 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
332 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400333 }
334 }
335
Elliott Hughese18e7e52016-07-25 18:18:16 -0700336 // TODO: work out why this fails for `console` then upgrade to FATAL.
337 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400338
339 if (gid_) {
340 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700341 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400342 }
343 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700344 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
345 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400346 }
347 if (uid_) {
348 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700349 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400350 }
351 }
352 if (!seclabel_.empty()) {
353 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700354 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400355 }
356 }
357 if (priority_ != 0) {
358 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700359 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400360 }
361 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400362 if (capabilities_.any()) {
363 if (!SetCapsForExec(capabilities_)) {
364 LOG(FATAL) << "cannot set capabilities for " << name_;
365 }
Luis Hector Chavez94fb5b02017-11-16 15:52:00 -0800366 } else if (uid_) {
367 // Inheritable caps can be non-zero when running in a container.
368 if (!DropInheritableCaps()) {
369 LOG(FATAL) << "cannot drop inheritable caps for " << name_;
370 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400371 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400372}
373
Paul Crowleyc73b2152018-04-13 17:38:57 +0000374void Service::Reap(const siginfo_t& siginfo) {
Tom Cherrybac32992015-07-31 12:45:25 -0700375 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700376 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700377 }
378
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700379 // Remove any descriptor resources we may have created.
380 std::for_each(descriptors_.begin(), descriptors_.end(),
381 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700382
Paul Crowleyc73b2152018-04-13 17:38:57 +0000383 for (const auto& f : reap_callbacks_) {
384 f(siginfo);
385 }
386
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700387 if (flags_ & SVC_EXEC) UnSetExec();
388
389 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700390
391 pid_ = 0;
392 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700393 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700394
395 // Oneshot processes go into the disabled state on exit,
396 // except when manually restarted.
397 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
398 flags_ |= SVC_DISABLED;
399 }
400
401 // Disabled and reset processes do not get restarted automatically.
402 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
403 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700404 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700405 }
406
Zimuzoc55a8c62019-01-07 10:19:02 +0000407 // If we crash > 4 times in 4 minutes, reboot into bootloader or set crashing property
Elliott Hughes9605a942016-11-10 17:43:47 -0800408 boot_clock::time_point now = boot_clock::now();
Zimuzoc661b662019-01-14 16:16:07 +0000409 if (((flags_ & SVC_CRITICAL) || !pre_apexd_) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800410 if (now < time_crashed_ + 4min) {
411 if (++crash_count_ > 4) {
Zimuzoc55a8c62019-01-07 10:19:02 +0000412 if (flags_ & SVC_CRITICAL) {
413 // Aborts into bootloader
414 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
415 } else {
416 LOG(ERROR) << "updatable process '" << name_ << "' exited 4 times in 4 minutes";
417 // Notifies update_verifier and apexd
418 property_set("ro.init.updatable_crashing", "1");
419 }
Tom Cherrybac32992015-07-31 12:45:25 -0700420 }
421 } else {
422 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800423 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700424 }
425 }
426
427 flags_ &= (~SVC_RESTART);
428 flags_ |= SVC_RESTARTING;
429
430 // Execute all onrestart commands for this service.
431 onrestart_.ExecuteAllCommands();
432
433 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700434 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700435}
436
437void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700438 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700439 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
440 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700441 std::for_each(descriptors_.begin(), descriptors_.end(),
442 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700443}
444
Tom Cherry018a4382018-10-17 11:11:23 -0700445Result<Success> Service::ParseCapabilities(std::vector<std::string>&& args) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400446 capabilities_ = 0;
447
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500448 if (!CapAmbientSupported()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700449 return Error()
450 << "capabilities requested but the kernel does not support ambient capabilities";
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500451 }
452
453 unsigned int last_valid_cap = GetLastValidCap();
454 if (last_valid_cap >= capabilities_.size()) {
455 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
456 }
457
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400458 for (size_t i = 1; i < args.size(); i++) {
459 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500460 int res = LookupCap(arg);
461 if (res < 0) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700462 return Error() << StringPrintf("invalid capability '%s'", arg.c_str());
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400463 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500464 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
465 if (cap > last_valid_cap) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700466 return Error() << StringPrintf("capability '%s' not supported by the kernel",
467 arg.c_str());
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500468 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400469 capabilities_[cap] = true;
470 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700471 return Success();
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400472}
473
Tom Cherry018a4382018-10-17 11:11:23 -0700474Result<Success> Service::ParseClass(std::vector<std::string>&& args) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700475 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700476 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700477}
Tom Cherrybac32992015-07-31 12:45:25 -0700478
Tom Cherry018a4382018-10-17 11:11:23 -0700479Result<Success> Service::ParseConsole(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700480 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200481 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherry89bcc852017-08-02 17:01:36 -0700482 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700483}
Tom Cherrybac32992015-07-31 12:45:25 -0700484
Tom Cherry018a4382018-10-17 11:11:23 -0700485Result<Success> Service::ParseCritical(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700486 flags_ |= SVC_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700487 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700488}
Tom Cherrybac32992015-07-31 12:45:25 -0700489
Tom Cherry018a4382018-10-17 11:11:23 -0700490Result<Success> Service::ParseDisabled(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700491 flags_ |= SVC_DISABLED;
492 flags_ |= SVC_RC_DISABLED;
Tom Cherry89bcc852017-08-02 17:01:36 -0700493 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700494}
Tom Cherrybac32992015-07-31 12:45:25 -0700495
Tom Cherry018a4382018-10-17 11:11:23 -0700496Result<Success> Service::ParseEnterNamespace(std::vector<std::string>&& args) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700497 if (args[1] != "net") {
498 return Error() << "Init only supports entering network namespaces";
499 }
500 if (!namespaces_to_enter_.empty()) {
501 return Error() << "Only one network namespace may be entered";
502 }
503 // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
504 // present. Therefore, they also require mount namespaces.
505 namespace_flags_ |= CLONE_NEWNS;
Tom Cherry018a4382018-10-17 11:11:23 -0700506 namespaces_to_enter_.emplace_back(CLONE_NEWNET, std::move(args[2]));
Tom Cherryaead51b2018-04-20 16:18:12 -0700507 return Success();
508}
509
Tom Cherry018a4382018-10-17 11:11:23 -0700510Result<Success> Service::ParseGroup(std::vector<std::string>&& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700511 auto gid = DecodeUid(args[1]);
512 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700513 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700514 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700515 gid_ = *gid;
516
Tom Cherryb7349902015-08-26 11:43:36 -0700517 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700518 gid = DecodeUid(args[n]);
519 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700520 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700521 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700522 supp_gids_.emplace_back(*gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700523 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700524 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700525}
526
Tom Cherry018a4382018-10-17 11:11:23 -0700527Result<Success> Service::ParsePriority(std::vector<std::string>&& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700528 priority_ = 0;
529 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800530 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
531 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700532 return Error() << StringPrintf("process priority value must be range %d - %d",
533 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700534 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700535 return Success();
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700536}
537
Tom Cherry018a4382018-10-17 11:11:23 -0700538Result<Success> Service::ParseInterface(std::vector<std::string>&& args) {
Steven Morelande055d732017-10-05 18:50:22 -0700539 const std::string& interface_name = args[1];
540 const std::string& instance_name = args[2];
541
Steven Moreland422367b2018-03-06 14:57:46 -0800542 FQName fq_name;
543 if (!FQName::parse(interface_name, &fq_name)) {
Steven Morelande055d732017-10-05 18:50:22 -0700544 return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
545 }
546
547 if (!fq_name.isFullyQualified()) {
548 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
549 }
550
551 if (fq_name.isValidValueName()) {
552 return Error() << "Interface name must not be a value name '" << interface_name << "'";
553 }
554
555 const std::string fullname = interface_name + "/" + instance_name;
556
557 for (const auto& svc : ServiceList::GetInstance()) {
558 if (svc->interfaces().count(fullname) > 0) {
559 return Error() << "Interface '" << fullname << "' redefined in " << name()
560 << " but is already defined by " << svc->name();
561 }
562 }
563
564 interfaces_.insert(fullname);
565
566 return Success();
567}
568
Tom Cherry018a4382018-10-17 11:11:23 -0700569Result<Success> Service::ParseIoprio(std::vector<std::string>&& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700570 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700571 return Error() << "priority value must be range 0 - 7";
Tom Cherryb7349902015-08-26 11:43:36 -0700572 }
573
574 if (args[1] == "rt") {
575 ioprio_class_ = IoSchedClass_RT;
576 } else if (args[1] == "be") {
577 ioprio_class_ = IoSchedClass_BE;
578 } else if (args[1] == "idle") {
579 ioprio_class_ = IoSchedClass_IDLE;
580 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700581 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
Tom Cherryb7349902015-08-26 11:43:36 -0700582 }
583
Tom Cherry89bcc852017-08-02 17:01:36 -0700584 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700585}
586
Tom Cherry018a4382018-10-17 11:11:23 -0700587Result<Success> Service::ParseKeycodes(std::vector<std::string>&& args) {
Tom Cherry79166842018-10-16 10:58:06 -0700588 auto it = args.begin() + 1;
589 if (args.size() == 2 && StartsWith(args[1], "$")) {
590 std::string expanded;
591 if (!expand_props(args[1], &expanded)) {
592 return Error() << "Could not expand property '" << args[1] << "'";
593 }
594
595 // If the property is not set, it defaults to none, in which case there are no keycodes
596 // for this service.
597 if (expanded == "none") {
598 return Success();
599 }
600
601 args = Split(expanded, ",");
602 it = args.begin();
603 }
604
605 for (; it != args.end(); ++it) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700606 int code;
Tom Cherry79166842018-10-16 10:58:06 -0700607 if (ParseInt(*it, &code, 0, KEY_MAX)) {
Mark Salyzyneca25072018-05-16 15:10:24 -0700608 for (auto& key : keycodes_) {
Tom Cherry79166842018-10-16 10:58:06 -0700609 if (key == code) return Error() << "duplicate keycode: " << *it;
Mark Salyzyneca25072018-05-16 15:10:24 -0700610 }
Mark Salyzyn13857252018-05-18 15:25:15 -0700611 keycodes_.insert(std::upper_bound(keycodes_.begin(), keycodes_.end(), code), code);
Elliott Hughesda46b392016-10-11 17:09:00 -0700612 } else {
Tom Cherry79166842018-10-16 10:58:06 -0700613 return Error() << "invalid keycode: " << *it;
Elliott Hughesda46b392016-10-11 17:09:00 -0700614 }
Tom Cherryb7349902015-08-26 11:43:36 -0700615 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700616 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700617}
618
Tom Cherry018a4382018-10-17 11:11:23 -0700619Result<Success> Service::ParseOneshot(std::vector<std::string>&& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700620 flags_ |= SVC_ONESHOT;
Tom Cherry89bcc852017-08-02 17:01:36 -0700621 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700622}
623
Tom Cherry018a4382018-10-17 11:11:23 -0700624Result<Success> Service::ParseOnrestart(std::vector<std::string>&& args) {
625 args.erase(args.begin());
Tom Cherry012c5732017-04-18 13:21:54 -0700626 int line = onrestart_.NumCommands() + 1;
Tom Cherry018a4382018-10-17 11:11:23 -0700627 if (auto result = onrestart_.AddCommand(std::move(args), line); !result) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700628 return Error() << "cannot add Onrestart command: " << result.error();
629 }
630 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700631}
632
Tom Cherry018a4382018-10-17 11:11:23 -0700633Result<Success> Service::ParseNamespace(std::vector<std::string>&& args) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700634 for (size_t i = 1; i < args.size(); i++) {
635 if (args[i] == "pid") {
636 namespace_flags_ |= CLONE_NEWPID;
637 // PID namespaces require mount namespaces.
638 namespace_flags_ |= CLONE_NEWNS;
639 } else if (args[i] == "mnt") {
640 namespace_flags_ |= CLONE_NEWNS;
641 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700642 return Error() << "namespace must be 'pid' or 'mnt'";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700643 }
644 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700645 return Success();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700646}
647
Tom Cherry018a4382018-10-17 11:11:23 -0700648Result<Success> Service::ParseOomScoreAdjust(std::vector<std::string>&& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700649 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700650 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
Marco Nelissen310f6702016-07-22 12:07:06 -0700651 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700652 return Success();
Marco Nelissen310f6702016-07-22 12:07:06 -0700653}
654
Tom Cherry018a4382018-10-17 11:11:23 -0700655Result<Success> Service::ParseOverride(std::vector<std::string>&& args) {
Steven Moreland6f5333a2017-11-13 15:31:54 -0800656 override_ = true;
657 return Success();
658}
659
Tom Cherry018a4382018-10-17 11:11:23 -0700660Result<Success> Service::ParseMemcgSwappiness(std::vector<std::string>&& args) {
Robert Benead4852262017-07-16 19:38:11 -0700661 if (!ParseInt(args[1], &swappiness_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700662 return Error() << "swappiness value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700663 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700664 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700665}
666
Tom Cherry018a4382018-10-17 11:11:23 -0700667Result<Success> Service::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
Robert Benead4852262017-07-16 19:38:11 -0700668 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700669 return Error() << "limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700670 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700671 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700672}
673
Peter Collingbourned7157c22018-10-30 15:49:33 -0700674Result<Success> Service::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
675 if (!ParseInt(args[1], &limit_percent_, 0)) {
676 return Error() << "limit_percent value must be equal or greater than 0";
677 }
678 return Success();
679}
680
681Result<Success> Service::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
682 limit_property_ = std::move(args[1]);
683 return Success();
684}
685
Tom Cherry018a4382018-10-17 11:11:23 -0700686Result<Success> Service::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
Robert Benead4852262017-07-16 19:38:11 -0700687 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700688 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700689 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700690 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700691}
692
Tom Cherry018a4382018-10-17 11:11:23 -0700693Result<Success> Service::ParseProcessRlimit(std::vector<std::string>&& args) {
Tom Cherry7ac013d2017-08-25 10:39:25 -0700694 auto rlimit = ParseRlimit(args);
695 if (!rlimit) return rlimit.error();
696
697 rlimits_.emplace_back(*rlimit);
698 return Success();
699}
700
Tom Cherry018a4382018-10-17 11:11:23 -0700701Result<Success> Service::ParseRestartPeriod(std::vector<std::string>&& args) {
Tom Cherry73f535e2018-09-27 16:10:46 -0700702 int period;
703 if (!ParseInt(args[1], &period, 5)) {
704 return Error() << "restart_period value must be an integer >= 5";
705 }
706 restart_period_ = std::chrono::seconds(period);
707 return Success();
708}
709
Tom Cherry018a4382018-10-17 11:11:23 -0700710Result<Success> Service::ParseSeclabel(std::vector<std::string>&& args) {
711 seclabel_ = std::move(args[1]);
Tom Cherry89bcc852017-08-02 17:01:36 -0700712 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700713}
714
Tom Cherry018a4382018-10-17 11:11:23 -0700715Result<Success> Service::ParseSigstop(std::vector<std::string>&& args) {
Tom Cherry8f380482018-04-17 14:48:44 -0700716 sigstop_ = true;
717 return Success();
718}
719
Tom Cherry018a4382018-10-17 11:11:23 -0700720Result<Success> Service::ParseSetenv(std::vector<std::string>&& args) {
721 environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
Tom Cherry89bcc852017-08-02 17:01:36 -0700722 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700723}
724
Tom Cherry018a4382018-10-17 11:11:23 -0700725Result<Success> Service::ParseShutdown(std::vector<std::string>&& args) {
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700726 if (args[1] == "critical") {
727 flags_ |= SVC_SHUTDOWN_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700728 return Success();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700729 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700730 return Error() << "Invalid shutdown option";
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700731}
732
Tom Cherry018a4382018-10-17 11:11:23 -0700733Result<Success> Service::ParseTimeoutPeriod(std::vector<std::string>&& args) {
Tom Cherry73f535e2018-09-27 16:10:46 -0700734 int period;
735 if (!ParseInt(args[1], &period, 1)) {
736 return Error() << "timeout_period value must be an integer >= 1";
737 }
738 timeout_period_ = std::chrono::seconds(period);
739 return Success();
740}
741
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700742template <typename T>
Tom Cherry018a4382018-10-17 11:11:23 -0700743Result<Success> Service::AddDescriptor(std::vector<std::string>&& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700744 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700745 Result<uid_t> uid = 0;
746 Result<gid_t> gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700747 std::string context = args.size() > 6 ? args[6] : "";
748
Tom Cherry517e1f12017-05-04 17:40:33 -0700749 if (args.size() > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700750 uid = DecodeUid(args[4]);
751 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700752 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700753 }
754 }
755
756 if (args.size() > 5) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700757 gid = DecodeUid(args[5]);
758 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700759 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700760 }
761 }
762
Tom Cherry11a3aee2017-08-03 12:54:07 -0700763 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700764
765 auto old =
766 std::find_if(descriptors_.begin(), descriptors_.end(),
767 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
768
769 if (old != descriptors_.end()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700770 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700771 }
772
773 descriptors_.emplace_back(std::move(descriptor));
Tom Cherry89bcc852017-08-02 17:01:36 -0700774 return Success();
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700775}
776
777// name type perm [ uid gid context ]
Tom Cherry018a4382018-10-17 11:11:23 -0700778Result<Success> Service::ParseSocket(std::vector<std::string>&& args) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700779 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
780 !StartsWith(args[2], "seqpacket")) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700781 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
Tom Cherryb7349902015-08-26 11:43:36 -0700782 }
Tom Cherry018a4382018-10-17 11:11:23 -0700783 return AddDescriptor<SocketInfo>(std::move(args));
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700784}
Tom Cherryb7349902015-08-26 11:43:36 -0700785
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700786// name type perm [ uid gid context ]
Tom Cherry018a4382018-10-17 11:11:23 -0700787Result<Success> Service::ParseFile(std::vector<std::string>&& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700788 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
Tom Cherry89bcc852017-08-02 17:01:36 -0700789 return Error() << "file type must be 'r', 'w' or 'rw'";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700790 }
791 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700792 return Error() << "file name must not be relative";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700793 }
Tom Cherry018a4382018-10-17 11:11:23 -0700794 return AddDescriptor<FileInfo>(std::move(args));
Tom Cherryb7349902015-08-26 11:43:36 -0700795}
796
Tom Cherry018a4382018-10-17 11:11:23 -0700797Result<Success> Service::ParseUser(std::vector<std::string>&& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700798 auto uid = DecodeUid(args[1]);
799 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700800 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700801 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700802 uid_ = *uid;
Tom Cherry89bcc852017-08-02 17:01:36 -0700803 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700804}
805
Tom Cherry018a4382018-10-17 11:11:23 -0700806Result<Success> Service::ParseWritepid(std::vector<std::string>&& args) {
807 args.erase(args.begin());
808 writepid_files_ = std::move(args);
Tom Cherry89bcc852017-08-02 17:01:36 -0700809 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700810}
811
Jiyong Park80aa4472018-11-12 12:08:41 +0900812Result<Success> Service::ParseUpdatable(std::vector<std::string>&& args) {
813 updatable_ = true;
814 return Success();
815}
816
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400817class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700818 public:
819 OptionParserMap() {}
820
821 private:
822 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700823};
824
Tom Cherryad54d092017-04-19 16:18:50 -0700825const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700826 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700827 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400828 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400829 {"capabilities",
830 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700831 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400832 {"console", {0, 1, &Service::ParseConsole}},
833 {"critical", {0, 0, &Service::ParseCritical}},
834 {"disabled", {0, 0, &Service::ParseDisabled}},
Tom Cherryaead51b2018-04-20 16:18:12 -0700835 {"enter_namespace",
836 {2, 2, &Service::ParseEnterNamespace}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800837 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400838 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
Steven Morelande055d732017-10-05 18:50:22 -0700839 {"interface", {2, 2, &Service::ParseInterface}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400840 {"ioprio", {2, 2, &Service::ParseIoprio}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400841 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
Robert Benead4852262017-07-16 19:38:11 -0700842 {"memcg.limit_in_bytes",
843 {1, 1, &Service::ParseMemcgLimitInBytes}},
Peter Collingbourned7157c22018-10-30 15:49:33 -0700844 {"memcg.limit_percent",
845 {1, 1, &Service::ParseMemcgLimitPercent}},
846 {"memcg.limit_property",
847 {1, 1, &Service::ParseMemcgLimitProperty}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800848 {"memcg.soft_limit_in_bytes",
849 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
850 {"memcg.swappiness",
851 {1, 1, &Service::ParseMemcgSwappiness}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400852 {"namespace", {1, 2, &Service::ParseNamespace}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800853 {"oneshot", {0, 0, &Service::ParseOneshot}},
854 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
855 {"oom_score_adjust",
856 {1, 1, &Service::ParseOomScoreAdjust}},
857 {"override", {0, 0, &Service::ParseOverride}},
858 {"priority", {1, 1, &Service::ParsePriority}},
Tom Cherry73f535e2018-09-27 16:10:46 -0700859 {"restart_period",
860 {1, 1, &Service::ParseRestartPeriod}},
Tom Cherry7ac013d2017-08-25 10:39:25 -0700861 {"rlimit", {3, 3, &Service::ParseProcessRlimit}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400862 {"seclabel", {1, 1, &Service::ParseSeclabel}},
863 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700864 {"shutdown", {1, 1, &Service::ParseShutdown}},
Tom Cherry8f380482018-04-17 14:48:44 -0700865 {"sigstop", {0, 0, &Service::ParseSigstop}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400866 {"socket", {3, 6, &Service::ParseSocket}},
Tom Cherry73f535e2018-09-27 16:10:46 -0700867 {"timeout_period",
868 {1, 1, &Service::ParseTimeoutPeriod}},
Jiyong Park80aa4472018-11-12 12:08:41 +0900869 {"updatable", {0, 0, &Service::ParseUpdatable}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400870 {"user", {1, 1, &Service::ParseUser}},
871 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700872 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700873 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400874 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700875}
876
Tom Cherry018a4382018-10-17 11:11:23 -0700877Result<Success> Service::ParseLine(std::vector<std::string>&& args) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400878 static const OptionParserMap parser_map;
Tom Cherry89bcc852017-08-02 17:01:36 -0700879 auto parser = parser_map.FindFunction(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700880
Tom Cherry76af7e62017-08-22 16:13:59 -0700881 if (!parser) return parser.error();
Tom Cherryb7349902015-08-26 11:43:36 -0700882
Tom Cherry018a4382018-10-17 11:11:23 -0700883 return std::invoke(*parser, this, std::move(args));
Tom Cherryb7349902015-08-26 11:43:36 -0700884}
885
Tom Cherry76af7e62017-08-22 16:13:59 -0700886Result<Success> Service::ExecStart() {
Jiyong Park80aa4472018-11-12 12:08:41 +0900887 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
888 // Don't delay the service for ExecStart() as the semantic is that
889 // the caller might depend on the side effect of the execution.
890 return Error() << "Cannot start an updatable service '" << name_
891 << "' before configs from APEXes are all loaded";
892 }
893
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700894 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700895
Tom Cherry76af7e62017-08-22 16:13:59 -0700896 if (auto result = Start(); !result) {
897 return result;
Tom Cherryb27004a2017-03-27 16:27:30 -0700898 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700899
900 flags_ |= SVC_EXEC;
901 is_exec_service_running_ = true;
902
Wei Wang2c4ee752018-06-20 14:54:52 -0700903 LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << uid_ << " gid "
904 << gid_ << "+" << supp_gids_.size() << " context "
905 << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700906
Tom Cherry76af7e62017-08-22 16:13:59 -0700907 return Success();
Tom Cherryb27004a2017-03-27 16:27:30 -0700908}
909
Tom Cherry76af7e62017-08-22 16:13:59 -0700910Result<Success> Service::Start() {
Jiyong Park80aa4472018-11-12 12:08:41 +0900911 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
912 ServiceList::GetInstance().DelayService(*this);
913 return Error() << "Cannot start an updatable service '" << name_
914 << "' before configs from APEXes are all loaded. "
915 << "Queued for execution.";
916 }
917
Tao Wu990d43c2017-10-26 10:43:10 -0700918 bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
Tom Cherrybac32992015-07-31 12:45:25 -0700919 // Starting a service removes it from the disabled or reset state and
920 // immediately takes it out of the restarting state if it was in there.
921 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700922
923 // Running processes require no additional work --- if they're in the
924 // process of exiting, we've ensured that they will immediately restart
Tao Wu990d43c2017-10-26 10:43:10 -0700925 // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
926 // stopping status, we just set SVC_RESTART flag so it will get restarted
927 // in Reap().
Tom Cherrybac32992015-07-31 12:45:25 -0700928 if (flags_ & SVC_RUNNING) {
Tao Wu990d43c2017-10-26 10:43:10 -0700929 if ((flags_ & SVC_ONESHOT) && disabled) {
930 flags_ |= SVC_RESTART;
931 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700932 // It is not an error to try to start a service that is already running.
933 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700934 }
935
936 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200937 if (needs_console) {
938 if (console_.empty()) {
939 console_ = default_console;
940 }
941
Adrian Salido24ef8602016-12-20 15:52:15 -0800942 // Make sure that open call succeeds to ensure a console driver is
943 // properly registered for the device node
944 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
945 if (console_fd < 0) {
Viorel Suman70daa672016-03-21 10:08:07 +0200946 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700947 return ErrnoError() << "Couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200948 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800949 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700950 }
951
952 struct stat sb;
953 if (stat(args_[0].c_str(), &sb) == -1) {
Tom Cherrybac32992015-07-31 12:45:25 -0700954 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700955 return ErrnoError() << "Cannot find '" << args_[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700956 }
957
Tom Cherrybac32992015-07-31 12:45:25 -0700958 std::string scon;
959 if (!seclabel_.empty()) {
960 scon = seclabel_;
961 } else {
Tom Cherryaead51b2018-04-20 16:18:12 -0700962 auto result = ComputeContextFromExecutable(args_[0]);
Tom Cherry76af7e62017-08-22 16:13:59 -0700963 if (!result) {
964 return result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700965 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700966 scon = *result;
Tom Cherrybac32992015-07-31 12:45:25 -0700967 }
968
Jiyong Park25990882019-01-02 23:37:15 +0900969 if (!ServiceList::GetInstance().IsRuntimeAvailable() && !pre_apexd_) {
970 // If this service is started before the runtime APEX gets available,
971 // mark it as pre-apexd one. Note that this marking is permanent. So
972 // for example, if the service is re-launched (e.g., due to crash),
973 // it is still recognized as pre-apexd... for consistency.
974 pre_apexd_ = true;
975 }
976
Wei Wanga285dac2016-10-04 14:05:39 -0700977 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700978
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700979 pid_t pid = -1;
980 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400981 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700982 } else {
983 pid = fork();
984 }
985
Tom Cherrybac32992015-07-31 12:45:25 -0700986 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700987 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700988
Tom Cherryaead51b2018-04-20 16:18:12 -0700989 if (auto result = EnterNamespaces(); !result) {
990 LOG(FATAL) << "Service '" << name_ << "' could not enter namespaces: " << result.error();
991 }
992
Jiyong Park5ab13002019-01-09 13:40:25 +0900993 // b/122559956: mount namespace is not cloned for the devices that don't support
994 // the update of bionic libraries via APEX. In that case, because the bionic
995 // libraries in the runtime APEX and the bootstrap bionic libraries are
996 // identical, it doesn't matter which libs are used. This is also to avoid the
997 // bug in sdcardfs which is triggered when we have multiple mount namespaces
998 // across vold and the others. BIONIC_UPDATABLE shall be true only for the
999 // devices where kernel has the fix for the sdcardfs bug (see the commit message
1000 // for the fix).
1001 static bool bionic_updatable =
1002 android::base::GetBoolProperty("ro.apex.bionic_updatable", false);
1003
1004 if (bionic_updatable && pre_apexd_) {
Jiyong Park25990882019-01-02 23:37:15 +09001005 // pre-apexd process gets a private copy of the mount namespace.
1006 // However, this does not mean that mount/unmount events are not
1007 // shared across pre-apexd processes and post-apexd processes.
1008 // *Most* of the events are still shared because the propagation
1009 // type of / is set to 'shared'. (see `mount rootfs rootfs /shared
1010 // rec` in init.rc)
1011 //
1012 // This unsharing is required to not propagate the mount events
1013 // under /system/lib/{libc|libdl|libm}.so and /system/bin/linker(64)
1014 // whose propagation type is set to private. With this,
1015 // bind-mounting the bionic libs and the dynamic linker from the
1016 // runtime APEX to the mount points does not affect pre-apexd
1017 // processes which should use the bootstrap ones.
1018 if (unshare(CLONE_NEWNS) != 0) {
1019 LOG(FATAL) << "Creating a new mount namespace for service"
1020 << " '" << name_ << "' failed: " << strerror(errno);
1021 }
1022 }
1023
Tom Cherryaead51b2018-04-20 16:18:12 -07001024 if (namespace_flags_ & CLONE_NEWNS) {
1025 if (auto result = SetUpMountNamespace(); !result) {
1026 LOG(FATAL) << "Service '" << name_
1027 << "' could not set up mount namespace: " << result.error();
1028 }
1029 }
1030
Jiyong Park5ab13002019-01-09 13:40:25 +09001031 // b/122559956: same as above
1032 if (bionic_updatable && pre_apexd_ && ServiceList::GetInstance().IsRuntimeAvailable()) {
Jiyong Park25990882019-01-02 23:37:15 +09001033 if (auto result = SetUpPreApexdMounts(); !result) {
1034 LOG(FATAL) << "Pre-apexd service '" << name_
1035 << "' could not setup the mount points: " << result.error();
1036 }
1037 }
1038
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001039 if (namespace_flags_ & CLONE_NEWPID) {
1040 // This will fork again to run an init process inside the PID
1041 // namespace.
Tom Cherryaead51b2018-04-20 16:18:12 -07001042 if (auto result = SetUpPidNamespace(); !result) {
1043 LOG(FATAL) << "Service '" << name_
1044 << "' could not set up PID namespace: " << result.error();
1045 }
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001046 }
1047
Tom Cherry6de21f12017-08-22 15:41:03 -07001048 for (const auto& [key, value] : environment_vars_) {
1049 setenv(key.c_str(), value.c_str(), 1);
Tom Cherrybac32992015-07-31 12:45:25 -07001050 }
1051
Mark Salyzyn62767fe2016-10-27 07:45:34 -07001052 std::for_each(descriptors_.begin(), descriptors_.end(),
1053 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -07001054
Alex Vakulenko08286762016-05-03 12:00:00 -07001055 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
1056 auto cpuset_predicate = [](const std::string& path) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001057 return StartsWith(path, "/dev/cpuset/");
Alex Vakulenko08286762016-05-03 12:00:00 -07001058 };
1059 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
1060 if (iter == writepid_files_.end()) {
1061 // There were no "writepid" instructions for cpusets, check if the system default
1062 // cpuset is specified to be used for the process.
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001063 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -07001064 if (!default_cpuset.empty()) {
1065 // Make sure the cpuset name starts and ends with '/'.
1066 // A single '/' means the 'root' cpuset.
1067 if (default_cpuset.front() != '/') {
1068 default_cpuset.insert(0, 1, '/');
1069 }
1070 if (default_cpuset.back() != '/') {
1071 default_cpuset.push_back('/');
1072 }
1073 writepid_files_.push_back(
1074 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
1075 }
1076 }
Tom Cherry1c3a53f2017-06-22 16:50:31 -07001077 std::string pid_str = std::to_string(getpid());
Tom Cherrybac32992015-07-31 12:45:25 -07001078 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -07001079 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001080 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -07001081 }
1082 }
1083
1084 if (ioprio_class_ != IoSchedClass_NONE) {
1085 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -04001086 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001087 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -07001088 }
1089 }
1090
1091 if (needs_console) {
1092 setsid();
1093 OpenConsole();
1094 } else {
1095 ZapStdio();
1096 }
1097
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -04001098 // As requested, set our gid, supplemental gids, uid, context, and
1099 // priority. Aborts on failure.
1100 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -07001101
Tom Cherry8f380482018-04-17 14:48:44 -07001102 if (!ExpandArgsAndExecv(args_, sigstop_)) {
Tom Cherry5e405ca2017-09-11 16:08:54 -07001103 PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -07001104 }
1105
1106 _exit(127);
1107 }
1108
1109 if (pid < 0) {
Tom Cherrybac32992015-07-31 12:45:25 -07001110 pid_ = 0;
Tom Cherry76af7e62017-08-22 16:13:59 -07001111 return ErrnoError() << "Failed to fork";
Tom Cherrybac32992015-07-31 12:45:25 -07001112 }
1113
Marco Nelissen310f6702016-07-22 12:07:06 -07001114 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -07001115 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -07001116 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
1117 if (!WriteStringToFile(oom_str, oom_file)) {
1118 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
1119 }
1120 }
1121
Elliott Hughes9605a942016-11-10 17:43:47 -08001122 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -07001123 pid_ = pid;
1124 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -07001125 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -07001126 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001127
Peter Collingbourned7157c22018-10-30 15:49:33 -07001128 bool use_memcg = swappiness_ != -1 || soft_limit_in_bytes_ != -1 || limit_in_bytes_ != -1 ||
1129 limit_percent_ != -1 || !limit_property_.empty();
1130 errno = -createProcessGroup(uid_, pid_, use_memcg);
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001131 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -04001132 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
1133 << name_ << "'";
Peter Collingbourned7157c22018-10-30 15:49:33 -07001134 } else if (use_memcg) {
Robert Benead4852262017-07-16 19:38:11 -07001135 if (swappiness_ != -1) {
1136 if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
1137 PLOG(ERROR) << "setProcessGroupSwappiness failed";
1138 }
1139 }
1140
1141 if (soft_limit_in_bytes_ != -1) {
1142 if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
1143 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
1144 }
1145 }
1146
Peter Collingbourned7157c22018-10-30 15:49:33 -07001147 size_t computed_limit_in_bytes = limit_in_bytes_;
1148 if (limit_percent_ != -1) {
1149 long page_size = sysconf(_SC_PAGESIZE);
1150 long num_pages = sysconf(_SC_PHYS_PAGES);
1151 if (page_size > 0 && num_pages > 0) {
1152 size_t max_mem = SIZE_MAX;
1153 if (size_t(num_pages) < SIZE_MAX / size_t(page_size)) {
1154 max_mem = size_t(num_pages) * size_t(page_size);
1155 }
1156 computed_limit_in_bytes =
1157 std::min(computed_limit_in_bytes, max_mem / 100 * limit_percent_);
1158 }
1159 }
1160
1161 if (!limit_property_.empty()) {
1162 // This ends up overwriting computed_limit_in_bytes but only if the
1163 // property is defined.
1164 computed_limit_in_bytes = android::base::GetUintProperty(
1165 limit_property_, computed_limit_in_bytes, SIZE_MAX);
1166 }
1167
1168 if (computed_limit_in_bytes != size_t(-1)) {
1169 if (!setProcessGroupLimit(uid_, pid_, computed_limit_in_bytes)) {
Robert Benead4852262017-07-16 19:38:11 -07001170 PLOG(ERROR) << "setProcessGroupLimit failed";
1171 }
1172 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001173 }
Tom Cherrybac32992015-07-31 12:45:25 -07001174
Tom Cherrybac32992015-07-31 12:45:25 -07001175 NotifyStateChange("running");
Tom Cherry76af7e62017-08-22 16:13:59 -07001176 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -07001177}
1178
Tom Cherry76af7e62017-08-22 16:13:59 -07001179Result<Success> Service::StartIfNotDisabled() {
Tom Cherrybac32992015-07-31 12:45:25 -07001180 if (!(flags_ & SVC_DISABLED)) {
1181 return Start();
1182 } else {
1183 flags_ |= SVC_DISABLED_START;
1184 }
Tom Cherry76af7e62017-08-22 16:13:59 -07001185 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -07001186}
1187
Tom Cherry76af7e62017-08-22 16:13:59 -07001188Result<Success> Service::Enable() {
Tom Cherrybac32992015-07-31 12:45:25 -07001189 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
1190 if (flags_ & SVC_DISABLED_START) {
1191 return Start();
1192 }
Tom Cherry76af7e62017-08-22 16:13:59 -07001193 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -07001194}
1195
1196void Service::Reset() {
1197 StopOrReset(SVC_RESET);
1198}
1199
1200void Service::Stop() {
1201 StopOrReset(SVC_DISABLED);
1202}
1203
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001204void Service::Terminate() {
1205 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1206 flags_ |= SVC_DISABLED;
1207 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001208 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001209 NotifyStateChange("stopping");
1210 }
1211}
1212
Tom Cherry73f535e2018-09-27 16:10:46 -07001213void Service::Timeout() {
1214 // All process state flags will be taken care of in Reap(), we really just want to kill the
1215 // process here when it times out. Oneshot processes will transition to be disabled, and
1216 // all other processes will transition to be restarting.
1217 LOG(INFO) << "Service '" << name_ << "' expired its timeout of " << timeout_period_->count()
1218 << " seconds and will now be killed";
1219 if (pid_) {
1220 KillProcessGroup(SIGKILL);
1221 NotifyStateChange("stopping");
1222 }
1223}
1224
Tom Cherrybac32992015-07-31 12:45:25 -07001225void Service::Restart() {
1226 if (flags_ & SVC_RUNNING) {
1227 /* Stop, wait, then start the service. */
1228 StopOrReset(SVC_RESTART);
1229 } else if (!(flags_ & SVC_RESTARTING)) {
1230 /* Just start the service since it's not running. */
Tom Cherry76af7e62017-08-22 16:13:59 -07001231 if (auto result = Start(); !result) {
1232 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
1233 }
Tom Cherrybac32992015-07-31 12:45:25 -07001234 } /* else: Service is restarting anyways. */
1235}
1236
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001237// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -07001238void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001239 // The service is still SVC_RUNNING until its process exits, but if it has
1240 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -07001241 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1242
1243 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001244 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -07001245 how = SVC_DISABLED;
1246 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001247
1248 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -07001249 if (how == SVC_RESET) {
1250 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
1251 } else {
1252 flags_ |= how;
1253 }
Tao Wu84b856d2017-10-27 11:29:13 -07001254 // Make sure it's in right status when a restart immediately follow a
1255 // stop/reset or vice versa.
1256 if (how == SVC_RESTART) {
1257 flags_ &= (~(SVC_DISABLED | SVC_RESET));
1258 } else {
1259 flags_ &= (~SVC_RESTART);
1260 }
Tom Cherrybac32992015-07-31 12:45:25 -07001261
1262 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001263 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -07001264 NotifyStateChange("stopping");
1265 } else {
1266 NotifyStateChange("stopped");
1267 }
1268}
1269
1270void Service::ZapStdio() const {
1271 int fd;
1272 fd = open("/dev/null", O_RDWR);
1273 dup2(fd, 0);
1274 dup2(fd, 1);
1275 dup2(fd, 2);
1276 close(fd);
1277}
1278
1279void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +02001280 int fd = open(console_.c_str(), O_RDWR);
1281 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -07001282 ioctl(fd, TIOCSCTTY, 0);
1283 dup2(fd, 0);
1284 dup2(fd, 1);
1285 dup2(fd, 2);
1286 close(fd);
1287}
1288
Tom Cherry911b9b12017-07-27 16:20:58 -07001289ServiceList::ServiceList() {}
Tom Cherrybac32992015-07-31 12:45:25 -07001290
Tom Cherry911b9b12017-07-27 16:20:58 -07001291ServiceList& ServiceList::GetInstance() {
1292 static ServiceList instance;
Tom Cherrybac32992015-07-31 12:45:25 -07001293 return instance;
1294}
1295
Tom Cherry911b9b12017-07-27 16:20:58 -07001296void ServiceList::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -07001297 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -07001298}
1299
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001300std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -07001301 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
1302 // SECLABEL can be a - to denote default
1303 std::size_t command_arg = 1;
1304 for (std::size_t i = 1; i < args.size(); ++i) {
1305 if (args[i] == "--") {
1306 command_arg = i + 1;
1307 break;
1308 }
1309 }
1310 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001311 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -07001312 return nullptr;
1313 }
1314
1315 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001316 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -07001317 return nullptr;
1318 }
1319 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
1320
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001321 static size_t exec_count = 0;
1322 exec_count++;
1323 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -07001324
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001325 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -04001326 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001327 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001328
1329 std::string seclabel = "";
1330 if (command_arg > 2 && args[1] != "-") {
1331 seclabel = args[1];
1332 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001333 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001334 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001335 uid = DecodeUid(args[2]);
1336 if (!uid) {
1337 LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001338 return nullptr;
1339 }
Tom Cherrybac32992015-07-31 12:45:25 -07001340 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001341 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001342 std::vector<gid_t> supp_gids;
1343 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001344 gid = DecodeUid(args[3]);
1345 if (!gid) {
1346 LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001347 return nullptr;
1348 }
Tom Cherrybac32992015-07-31 12:45:25 -07001349 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
1350 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001351 auto supp_gid = DecodeUid(args[4 + i]);
1352 if (!supp_gid) {
1353 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
1354 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001355 return nullptr;
1356 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001357 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -07001358 }
1359 }
1360
Tom Cherry11a3aee2017-08-03 12:54:07 -07001361 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, no_capabilities,
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001362 namespace_flags, seclabel, nullptr, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001363}
1364
Tom Cherry59383792017-07-26 16:09:09 -07001365// Shutdown services in the opposite order that they were started.
Tom Cherry911b9b12017-07-27 16:20:58 -07001366const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
Tom Cherry59383792017-07-26 16:09:09 -07001367 std::vector<Service*> shutdown_services;
1368 for (const auto& service : services_) {
1369 if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
1370 }
1371 std::sort(shutdown_services.begin(), shutdown_services.end(),
1372 [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
Tom Cherry911b9b12017-07-27 16:20:58 -07001373 return shutdown_services;
Tom Cherry59383792017-07-26 16:09:09 -07001374}
1375
Tom Cherry911b9b12017-07-27 16:20:58 -07001376void ServiceList::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001377 auto svc_it = std::find_if(services_.begin(), services_.end(),
1378 [&svc] (const std::unique_ptr<Service>& s) {
1379 return svc.name() == s->name();
1380 });
1381 if (svc_it == services_.end()) {
1382 return;
1383 }
1384
1385 services_.erase(svc_it);
1386}
1387
Tom Cherry911b9b12017-07-27 16:20:58 -07001388void ServiceList::DumpState() const {
Tom Cherryb7349902015-08-26 11:43:36 -07001389 for (const auto& s : services_) {
1390 s->DumpState();
1391 }
Tom Cherryb7349902015-08-26 11:43:36 -07001392}
1393
Jiyong Park80aa4472018-11-12 12:08:41 +09001394void ServiceList::MarkServicesUpdate() {
1395 services_update_finished_ = true;
1396
1397 // start the delayed services
1398 for (const auto& name : delayed_service_names_) {
1399 Service* service = FindService(name);
1400 if (service == nullptr) {
1401 LOG(ERROR) << "delayed service '" << name << "' could not be found.";
1402 continue;
1403 }
1404 if (auto result = service->Start(); !result) {
1405 LOG(ERROR) << result.error_string();
1406 }
1407 }
1408 delayed_service_names_.clear();
1409}
1410
Jiyong Park25990882019-01-02 23:37:15 +09001411void ServiceList::MarkRuntimeAvailable() {
1412 runtime_available_ = true;
1413}
1414
Jiyong Park80aa4472018-11-12 12:08:41 +09001415void ServiceList::DelayService(const Service& service) {
1416 if (services_update_finished_) {
1417 LOG(ERROR) << "Cannot delay the start of service '" << service.name()
1418 << "' because all services are already updated. Ignoring.";
1419 return;
1420 }
1421 delayed_service_names_.emplace_back(service.name());
1422}
1423
Tom Cherry89bcc852017-08-02 17:01:36 -07001424Result<Success> ServiceParser::ParseSection(std::vector<std::string>&& args,
1425 const std::string& filename, int line) {
Tom Cherryb7349902015-08-26 11:43:36 -07001426 if (args.size() < 3) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001427 return Error() << "services must have a name and a program";
Tom Cherryb7349902015-08-26 11:43:36 -07001428 }
1429
1430 const std::string& name = args[1];
1431 if (!IsValidName(name)) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001432 return Error() << "invalid service name '" << name << "'";
Tom Cherryb7349902015-08-26 11:43:36 -07001433 }
1434
Jiyong Park80aa4472018-11-12 12:08:41 +09001435 filename_ = filename;
1436
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001437 Subcontext* restart_action_subcontext = nullptr;
1438 if (subcontexts_) {
1439 for (auto& subcontext : *subcontexts_) {
Elliott Hughes579e6822017-12-20 09:41:00 -08001440 if (StartsWith(filename, subcontext.path_prefix())) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001441 restart_action_subcontext = &subcontext;
1442 break;
1443 }
1444 }
1445 }
1446
Tom Cherryb7349902015-08-26 11:43:36 -07001447 std::vector<std::string> str_args(args.begin() + 2, args.end());
Tom Cherry40acb372018-08-01 13:41:12 -07001448
1449 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
1450 if (str_args[0] == "/sbin/watchdogd") {
1451 str_args[0] = "/system/bin/watchdogd";
1452 }
1453 }
1454
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001455 service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
Tom Cherry89bcc852017-08-02 17:01:36 -07001456 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001457}
1458
Tom Cherry89bcc852017-08-02 17:01:36 -07001459Result<Success> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
1460 return service_ ? service_->ParseLine(std::move(args)) : Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001461}
1462
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001463Result<Success> ServiceParser::EndSection() {
Tom Cherryb7349902015-08-26 11:43:36 -07001464 if (service_) {
Steven Moreland5e1bea32017-11-10 14:43:58 -08001465 Service* old_service = service_list_->FindService(service_->name());
1466 if (old_service) {
Steven Moreland6f5333a2017-11-13 15:31:54 -08001467 if (!service_->is_override()) {
1468 return Error() << "ignored duplicate definition of service '" << service_->name()
1469 << "'";
1470 }
1471
Jiyong Park80aa4472018-11-12 12:08:41 +09001472 if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
1473 return Error() << "cannot update a non-updatable service '" << service_->name()
1474 << "' with a config in APEX";
1475 }
1476
Steven Moreland6f5333a2017-11-13 15:31:54 -08001477 service_list_->RemoveService(*old_service);
1478 old_service = nullptr;
Steven Moreland5e1bea32017-11-10 14:43:58 -08001479 }
1480
Tom Cherry911b9b12017-07-27 16:20:58 -07001481 service_list_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001482 }
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001483
1484 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001485}
1486
1487bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001488 // Property names can be any length, but may only contain certain characters.
1489 // Property values can contain any characters, but may only be a certain length.
1490 // (The latter restriction is needed because `start` and `stop` work by writing
1491 // the service name to the "ctl.start" and "ctl.stop" properties.)
Tom Cherryde6bd502018-02-13 16:50:08 -08001492 return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001493}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001494
1495} // namespace init
1496} // namespace android