blob: d20e90a70cfbb5170c9da0dacb5326ff1432c94d [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 Cherry81f5d3e2017-06-22 12:53:17 -070063using android::base::StartsWith;
Tom Cherryb7349902015-08-26 11:43:36 -070064using android::base::StringPrintf;
Tom Cherryaead51b2018-04-20 16:18:12 -070065using android::base::unique_fd;
Tom Cherryb7349902015-08-26 11:43:36 -070066using android::base::WriteStringToFile;
67
Tom Cherry81f5d3e2017-06-22 12:53:17 -070068namespace android {
69namespace init {
70
Tom Cherryaead51b2018-04-20 16:18:12 -070071static Result<std::string> ComputeContextFromExecutable(const std::string& service_path) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040072 std::string computed_context;
73
74 char* raw_con = nullptr;
75 char* raw_filecon = nullptr;
76
77 if (getcon(&raw_con) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070078 return Error() << "Could not get security context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040079 }
80 std::unique_ptr<char> mycon(raw_con);
81
82 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070083 return Error() << "Could not get file context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040084 }
85 std::unique_ptr<char> filecon(raw_filecon);
86
87 char* new_con = nullptr;
88 int rc = security_compute_create(mycon.get(), filecon.get(),
89 string_to_security_class("process"), &new_con);
90 if (rc == 0) {
91 computed_context = new_con;
92 free(new_con);
93 }
94 if (rc == 0 && computed_context == mycon.get()) {
Nick Kralevich1ea19eb2017-08-25 12:08:57 -070095 return Error() << "File " << service_path << "(labeled \"" << filecon.get()
96 << "\") has incorrect label or no domain transition from " << mycon.get()
97 << " to another SELinux domain defined. Have you configured your "
98 "service correctly? https://source.android.com/security/selinux/"
99 "device-policy#label_new_services_and_address_denials";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400100 }
101 if (rc < 0) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700102 return Error() << "Could not get process context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400103 }
104 return computed_context;
105}
106
Tom Cherryaead51b2018-04-20 16:18:12 -0700107Result<Success> Service::SetUpMountNamespace() const {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700108 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
109
Joe Tanen4bfdcb32017-10-25 08:07:26 -0400110 // Recursively remount / as slave like zygote does so unmounting and mounting /proc
111 // doesn't interfere with the parent namespace's /proc mount. This will also
112 // prevent any other mounts/unmounts initiated by the service from interfering
113 // with the parent namespace but will still allow mount events from the parent
114 // namespace to propagate to the child.
115 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700116 return ErrnoError() << "Could not remount(/) recursively as slave";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700117 }
118
Tom Cherryaead51b2018-04-20 16:18:12 -0700119 // umount() then mount() /proc and/or /sys
120 // Note that it is not sufficient to mount with MS_REMOUNT.
121 if (namespace_flags_ & CLONE_NEWPID) {
122 if (umount("/proc") == -1) {
123 return ErrnoError() << "Could not umount(/proc)";
124 }
125 if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
126 return ErrnoError() << "Could not mount(/proc)";
127 }
128 }
129 bool remount_sys = std::any_of(namespaces_to_enter_.begin(), namespaces_to_enter_.end(),
130 [](const auto& entry) { return entry.first == CLONE_NEWNET; });
131 if (remount_sys) {
132 if (umount2("/sys", MNT_DETACH) == -1) {
133 return ErrnoError() << "Could not umount(/sys)";
134 }
Tom Cherry9bb0a4d2018-07-13 11:07:11 -0700135 if (mount("", "/sys", "sysfs", kSafeFlags, "") == -1) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700136 return ErrnoError() << "Could not mount(/sys)";
137 }
138 }
139 return Success();
140}
141
142Result<Success> Service::SetUpPidNamespace() const {
143 if (prctl(PR_SET_NAME, name_.c_str()) == -1) {
144 return ErrnoError() << "Could not set name";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700145 }
146
147 pid_t child_pid = fork();
148 if (child_pid == -1) {
Tom Cherryaead51b2018-04-20 16:18:12 -0700149 return ErrnoError() << "Could not fork init inside the PID namespace";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700150 }
151
152 if (child_pid > 0) {
153 // So that we exit with the right status.
154 static int init_exitstatus = 0;
155 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
156
157 pid_t waited_pid;
158 int status;
159 while ((waited_pid = wait(&status)) > 0) {
160 // This loop will end when there are no processes left inside the
161 // PID namespace or when the init process inside the PID namespace
162 // gets a signal.
163 if (waited_pid == child_pid) {
164 init_exitstatus = status;
165 }
166 }
167 if (!WIFEXITED(init_exitstatus)) {
168 _exit(EXIT_FAILURE);
169 }
170 _exit(WEXITSTATUS(init_exitstatus));
171 }
Tom Cherryaead51b2018-04-20 16:18:12 -0700172 return Success();
173}
174
175Result<Success> Service::EnterNamespaces() const {
176 for (const auto& [nstype, path] : namespaces_to_enter_) {
177 auto fd = unique_fd{open(path.c_str(), O_RDONLY | O_CLOEXEC)};
178 if (!fd) {
179 return ErrnoError() << "Could not open namespace at " << path;
180 }
181 if (setns(fd, nstype) == -1) {
182 return ErrnoError() << "Could not setns() namespace at " << path;
183 }
184 }
185 return Success();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700186}
187
Tom Cherry8f380482018-04-17 14:48:44 -0700188static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400189 std::vector<std::string> expanded_args;
Tom Cherry5e405ca2017-09-11 16:08:54 -0700190 std::vector<char*> c_strings;
191
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400192 expanded_args.resize(args.size());
Tom Cherry5e405ca2017-09-11 16:08:54 -0700193 c_strings.push_back(const_cast<char*>(args[0].data()));
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400194 for (std::size_t i = 1; i < args.size(); ++i) {
195 if (!expand_props(args[i], &expanded_args[i])) {
196 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
197 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700198 c_strings.push_back(expanded_args[i].data());
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400199 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700200 c_strings.push_back(nullptr);
201
Tom Cherry8f380482018-04-17 14:48:44 -0700202 if (sigstop) {
203 kill(getpid(), SIGSTOP);
204 }
205
Tom Cherry5e405ca2017-09-11 16:08:54 -0700206 return execv(c_strings[0], c_strings.data()) == 0;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400207}
208
Tom Cherry59383792017-07-26 16:09:09 -0700209unsigned long Service::next_start_order_ = 1;
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700210bool Service::is_exec_service_running_ = false;
Tom Cherry59383792017-07-26 16:09:09 -0700211
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700212Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
213 const std::vector<std::string>& args)
214 : Service(name, 0, 0, 0, {}, 0, 0, "", subcontext_for_restart_commands, args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700215
Wei Wang641ff0a2017-03-27 10:59:11 -0700216Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
217 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
218 unsigned namespace_flags, const std::string& seclabel,
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700219 Subcontext* subcontext_for_restart_commands, const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700220 : name_(name),
221 classnames_({"default"}),
222 flags_(flags),
223 pid_(0),
224 crash_count_(0),
225 uid_(uid),
226 gid_(gid),
227 supp_gids_(supp_gids),
228 capabilities_(capabilities),
229 namespace_flags_(namespace_flags),
230 seclabel_(seclabel),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800231 onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0,
232 "onrestart", {}),
Wei Wang641ff0a2017-03-27 10:59:11 -0700233 ioprio_class_(IoSchedClass_NONE),
234 ioprio_pri_(0),
235 priority_(0),
236 oom_score_adjust_(-1000),
Robert Benead4852262017-07-16 19:38:11 -0700237 swappiness_(-1),
238 soft_limit_in_bytes_(-1),
239 limit_in_bytes_(-1),
Tom Cherry59383792017-07-26 16:09:09 -0700240 start_order_(0),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800241 args_(args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700242
243void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700244 if ((flags_ & SVC_TEMPORARY) != 0) {
245 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700246 return;
247 }
248
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700249 std::string prop_name = "init.svc." + name_;
250 property_set(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800251
252 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800253 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherryfed33732017-08-18 10:47:46 -0700254 std::string boottime_property = "ro.boottime." + name_;
255 if (GetProperty(boottime_property, "").empty()) {
256 property_set(boottime_property, std::to_string(start_ns));
257 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800258 }
Tom Cherrybac32992015-07-31 12:45:25 -0700259}
260
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700261void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700262 // If we've already seen a successful result from killProcessGroup*(), then we have removed
263 // the cgroup already and calling these functions a second time will simply result in an error.
264 // This is true regardless of which signal was sent.
265 // These functions handle their own logging, so no additional logging is needed.
266 if (!process_cgroup_empty_) {
267 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
268 << ") process group...";
269 int r;
270 if (signal == SIGTERM) {
271 r = killProcessGroupOnce(uid_, pid_, signal);
272 } else {
273 r = killProcessGroup(uid_, pid_, signal);
274 }
275
276 if (r == 0) process_cgroup_empty_ = true;
277 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700278}
279
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400280void Service::SetProcessAttributes() {
Tom Cherry7ac013d2017-08-25 10:39:25 -0700281 for (const auto& rlimit : rlimits_) {
282 if (setrlimit(rlimit.first, &rlimit.second) == -1) {
283 LOG(FATAL) << StringPrintf("setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed",
284 rlimit.first, rlimit.second.rlim_cur, rlimit.second.rlim_max);
285 }
286 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400287 // Keep capabilites on uid change.
288 if (capabilities_.any() && uid_) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700289 // If Android is running in a container, some securebits might already
290 // be locked, so don't change those.
Ben Fennemaa7243602017-07-25 14:37:21 -0700291 unsigned long securebits = prctl(PR_GET_SECUREBITS);
292 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700293 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
294 }
295 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
296 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
297 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400298 }
299 }
300
Elliott Hughese18e7e52016-07-25 18:18:16 -0700301 // TODO: work out why this fails for `console` then upgrade to FATAL.
302 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400303
304 if (gid_) {
305 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700306 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400307 }
308 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700309 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
310 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400311 }
312 if (uid_) {
313 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700314 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400315 }
316 }
317 if (!seclabel_.empty()) {
318 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700319 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400320 }
321 }
322 if (priority_ != 0) {
323 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700324 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400325 }
326 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400327 if (capabilities_.any()) {
328 if (!SetCapsForExec(capabilities_)) {
329 LOG(FATAL) << "cannot set capabilities for " << name_;
330 }
Luis Hector Chavez94fb5b02017-11-16 15:52:00 -0800331 } else if (uid_) {
332 // Inheritable caps can be non-zero when running in a container.
333 if (!DropInheritableCaps()) {
334 LOG(FATAL) << "cannot drop inheritable caps for " << name_;
335 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400336 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400337}
338
Paul Crowleyc73b2152018-04-13 17:38:57 +0000339void Service::Reap(const siginfo_t& siginfo) {
Tom Cherrybac32992015-07-31 12:45:25 -0700340 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700341 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700342 }
343
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700344 // Remove any descriptor resources we may have created.
345 std::for_each(descriptors_.begin(), descriptors_.end(),
346 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700347
Paul Crowleyc73b2152018-04-13 17:38:57 +0000348 for (const auto& f : reap_callbacks_) {
349 f(siginfo);
350 }
351
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700352 if (flags_ & SVC_EXEC) UnSetExec();
353
354 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700355
356 pid_ = 0;
357 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700358 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700359
360 // Oneshot processes go into the disabled state on exit,
361 // except when manually restarted.
362 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
363 flags_ |= SVC_DISABLED;
364 }
365
366 // Disabled and reset processes do not get restarted automatically.
367 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
368 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700369 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700370 }
371
Elliott Hughes9605a942016-11-10 17:43:47 -0800372 // If we crash > 4 times in 4 minutes, reboot into recovery.
373 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700374 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800375 if (now < time_crashed_ + 4min) {
376 if (++crash_count_ > 4) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700377 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
Tom Cherrybac32992015-07-31 12:45:25 -0700378 }
379 } else {
380 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800381 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700382 }
383 }
384
385 flags_ &= (~SVC_RESTART);
386 flags_ |= SVC_RESTARTING;
387
388 // Execute all onrestart commands for this service.
389 onrestart_.ExecuteAllCommands();
390
391 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700392 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700393}
394
395void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700396 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700397 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
398 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700399 std::for_each(descriptors_.begin(), descriptors_.end(),
400 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700401}
402
Tom Cherry89bcc852017-08-02 17:01:36 -0700403Result<Success> Service::ParseCapabilities(const std::vector<std::string>& args) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400404 capabilities_ = 0;
405
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500406 if (!CapAmbientSupported()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700407 return Error()
408 << "capabilities requested but the kernel does not support ambient capabilities";
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500409 }
410
411 unsigned int last_valid_cap = GetLastValidCap();
412 if (last_valid_cap >= capabilities_.size()) {
413 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
414 }
415
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400416 for (size_t i = 1; i < args.size(); i++) {
417 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500418 int res = LookupCap(arg);
419 if (res < 0) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700420 return Error() << StringPrintf("invalid capability '%s'", arg.c_str());
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400421 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500422 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
423 if (cap > last_valid_cap) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700424 return Error() << StringPrintf("capability '%s' not supported by the kernel",
425 arg.c_str());
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500426 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400427 capabilities_[cap] = true;
428 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700429 return Success();
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400430}
431
Tom Cherry89bcc852017-08-02 17:01:36 -0700432Result<Success> Service::ParseClass(const std::vector<std::string>& args) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700433 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700434 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700435}
Tom Cherrybac32992015-07-31 12:45:25 -0700436
Tom Cherry89bcc852017-08-02 17:01:36 -0700437Result<Success> Service::ParseConsole(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700438 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200439 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherry89bcc852017-08-02 17:01:36 -0700440 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700441}
Tom Cherrybac32992015-07-31 12:45:25 -0700442
Tom Cherry89bcc852017-08-02 17:01:36 -0700443Result<Success> Service::ParseCritical(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700444 flags_ |= SVC_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700445 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700446}
Tom Cherrybac32992015-07-31 12:45:25 -0700447
Tom Cherry89bcc852017-08-02 17:01:36 -0700448Result<Success> Service::ParseDisabled(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700449 flags_ |= SVC_DISABLED;
450 flags_ |= SVC_RC_DISABLED;
Tom Cherry89bcc852017-08-02 17:01:36 -0700451 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700452}
Tom Cherrybac32992015-07-31 12:45:25 -0700453
Tom Cherryaead51b2018-04-20 16:18:12 -0700454Result<Success> Service::ParseEnterNamespace(const std::vector<std::string>& args) {
455 if (args[1] != "net") {
456 return Error() << "Init only supports entering network namespaces";
457 }
458 if (!namespaces_to_enter_.empty()) {
459 return Error() << "Only one network namespace may be entered";
460 }
461 // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
462 // present. Therefore, they also require mount namespaces.
463 namespace_flags_ |= CLONE_NEWNS;
464 namespaces_to_enter_.emplace_back(CLONE_NEWNET, args[2]);
465 return Success();
466}
467
Tom Cherry89bcc852017-08-02 17:01:36 -0700468Result<Success> Service::ParseGroup(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700469 auto gid = DecodeUid(args[1]);
470 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700471 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700472 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700473 gid_ = *gid;
474
Tom Cherryb7349902015-08-26 11:43:36 -0700475 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700476 gid = DecodeUid(args[n]);
477 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700478 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700479 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700480 supp_gids_.emplace_back(*gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700481 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700482 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700483}
484
Tom Cherry89bcc852017-08-02 17:01:36 -0700485Result<Success> Service::ParsePriority(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700486 priority_ = 0;
487 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800488 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
489 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700490 return Error() << StringPrintf("process priority value must be range %d - %d",
491 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700492 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700493 return Success();
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700494}
495
Steven Morelande055d732017-10-05 18:50:22 -0700496Result<Success> Service::ParseInterface(const std::vector<std::string>& args) {
497 const std::string& interface_name = args[1];
498 const std::string& instance_name = args[2];
499
Steven Moreland422367b2018-03-06 14:57:46 -0800500 FQName fq_name;
501 if (!FQName::parse(interface_name, &fq_name)) {
Steven Morelande055d732017-10-05 18:50:22 -0700502 return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
503 }
504
505 if (!fq_name.isFullyQualified()) {
506 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
507 }
508
509 if (fq_name.isValidValueName()) {
510 return Error() << "Interface name must not be a value name '" << interface_name << "'";
511 }
512
513 const std::string fullname = interface_name + "/" + instance_name;
514
515 for (const auto& svc : ServiceList::GetInstance()) {
516 if (svc->interfaces().count(fullname) > 0) {
517 return Error() << "Interface '" << fullname << "' redefined in " << name()
518 << " but is already defined by " << svc->name();
519 }
520 }
521
522 interfaces_.insert(fullname);
523
524 return Success();
525}
526
Tom Cherry89bcc852017-08-02 17:01:36 -0700527Result<Success> Service::ParseIoprio(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700528 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700529 return Error() << "priority value must be range 0 - 7";
Tom Cherryb7349902015-08-26 11:43:36 -0700530 }
531
532 if (args[1] == "rt") {
533 ioprio_class_ = IoSchedClass_RT;
534 } else if (args[1] == "be") {
535 ioprio_class_ = IoSchedClass_BE;
536 } else if (args[1] == "idle") {
537 ioprio_class_ = IoSchedClass_IDLE;
538 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700539 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
Tom Cherryb7349902015-08-26 11:43:36 -0700540 }
541
Tom Cherry89bcc852017-08-02 17:01:36 -0700542 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700543}
544
Tom Cherry89bcc852017-08-02 17:01:36 -0700545Result<Success> Service::ParseKeycodes(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700546 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700547 int code;
Mark Salyzyneca25072018-05-16 15:10:24 -0700548 if (ParseInt(args[i], &code, 0, KEY_MAX)) {
549 for (auto& key : keycodes_) {
550 if (key == code) return Error() << "duplicate keycode: " << args[i];
551 }
Mark Salyzyn13857252018-05-18 15:25:15 -0700552 keycodes_.insert(std::upper_bound(keycodes_.begin(), keycodes_.end(), code), code);
Elliott Hughesda46b392016-10-11 17:09:00 -0700553 } else {
Mark Salyzyneca25072018-05-16 15:10:24 -0700554 return Error() << "invalid keycode: " << args[i];
Elliott Hughesda46b392016-10-11 17:09:00 -0700555 }
Tom Cherryb7349902015-08-26 11:43:36 -0700556 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700557 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700558}
559
Tom Cherry89bcc852017-08-02 17:01:36 -0700560Result<Success> Service::ParseOneshot(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700561 flags_ |= SVC_ONESHOT;
Tom Cherry89bcc852017-08-02 17:01:36 -0700562 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700563}
564
Tom Cherry89bcc852017-08-02 17:01:36 -0700565Result<Success> Service::ParseOnrestart(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700566 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700567 int line = onrestart_.NumCommands() + 1;
Tom Cherry89bcc852017-08-02 17:01:36 -0700568 if (auto result = onrestart_.AddCommand(str_args, line); !result) {
569 return Error() << "cannot add Onrestart command: " << result.error();
570 }
571 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700572}
573
Tom Cherry89bcc852017-08-02 17:01:36 -0700574Result<Success> Service::ParseNamespace(const std::vector<std::string>& args) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700575 for (size_t i = 1; i < args.size(); i++) {
576 if (args[i] == "pid") {
577 namespace_flags_ |= CLONE_NEWPID;
578 // PID namespaces require mount namespaces.
579 namespace_flags_ |= CLONE_NEWNS;
580 } else if (args[i] == "mnt") {
581 namespace_flags_ |= CLONE_NEWNS;
582 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700583 return Error() << "namespace must be 'pid' or 'mnt'";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700584 }
585 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700586 return Success();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700587}
588
Tom Cherry89bcc852017-08-02 17:01:36 -0700589Result<Success> Service::ParseOomScoreAdjust(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700590 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700591 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
Marco Nelissen310f6702016-07-22 12:07:06 -0700592 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700593 return Success();
Marco Nelissen310f6702016-07-22 12:07:06 -0700594}
595
Steven Moreland6f5333a2017-11-13 15:31:54 -0800596Result<Success> Service::ParseOverride(const std::vector<std::string>& args) {
597 override_ = true;
598 return Success();
599}
600
Tom Cherry89bcc852017-08-02 17:01:36 -0700601Result<Success> Service::ParseMemcgSwappiness(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700602 if (!ParseInt(args[1], &swappiness_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700603 return Error() << "swappiness value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700604 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700605 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700606}
607
Tom Cherry89bcc852017-08-02 17:01:36 -0700608Result<Success> Service::ParseMemcgLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700609 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700610 return Error() << "limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700611 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700612 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700613}
614
Tom Cherry89bcc852017-08-02 17:01:36 -0700615Result<Success> Service::ParseMemcgSoftLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700616 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700617 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700618 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700619 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700620}
621
Tom Cherry7ac013d2017-08-25 10:39:25 -0700622Result<Success> Service::ParseProcessRlimit(const std::vector<std::string>& args) {
623 auto rlimit = ParseRlimit(args);
624 if (!rlimit) return rlimit.error();
625
626 rlimits_.emplace_back(*rlimit);
627 return Success();
628}
629
Tom Cherry89bcc852017-08-02 17:01:36 -0700630Result<Success> Service::ParseSeclabel(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700631 seclabel_ = args[1];
Tom Cherry89bcc852017-08-02 17:01:36 -0700632 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700633}
634
Tom Cherry8f380482018-04-17 14:48:44 -0700635Result<Success> Service::ParseSigstop(const std::vector<std::string>& args) {
636 sigstop_ = true;
637 return Success();
638}
639
Tom Cherry89bcc852017-08-02 17:01:36 -0700640Result<Success> Service::ParseSetenv(const std::vector<std::string>& args) {
Tom Cherry6de21f12017-08-22 15:41:03 -0700641 environment_vars_.emplace_back(args[1], args[2]);
Tom Cherry89bcc852017-08-02 17:01:36 -0700642 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700643}
644
Tom Cherry89bcc852017-08-02 17:01:36 -0700645Result<Success> Service::ParseShutdown(const std::vector<std::string>& args) {
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700646 if (args[1] == "critical") {
647 flags_ |= SVC_SHUTDOWN_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700648 return Success();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700649 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700650 return Error() << "Invalid shutdown option";
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700651}
652
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700653template <typename T>
Tom Cherry89bcc852017-08-02 17:01:36 -0700654Result<Success> Service::AddDescriptor(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700655 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700656 Result<uid_t> uid = 0;
657 Result<gid_t> gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700658 std::string context = args.size() > 6 ? args[6] : "";
659
Tom Cherry517e1f12017-05-04 17:40:33 -0700660 if (args.size() > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700661 uid = DecodeUid(args[4]);
662 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700663 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700664 }
665 }
666
667 if (args.size() > 5) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700668 gid = DecodeUid(args[5]);
669 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700670 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700671 }
672 }
673
Tom Cherry11a3aee2017-08-03 12:54:07 -0700674 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700675
676 auto old =
677 std::find_if(descriptors_.begin(), descriptors_.end(),
678 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
679
680 if (old != descriptors_.end()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700681 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700682 }
683
684 descriptors_.emplace_back(std::move(descriptor));
Tom Cherry89bcc852017-08-02 17:01:36 -0700685 return Success();
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700686}
687
688// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700689Result<Success> Service::ParseSocket(const std::vector<std::string>& args) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700690 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
691 !StartsWith(args[2], "seqpacket")) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700692 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
Tom Cherryb7349902015-08-26 11:43:36 -0700693 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700694 return AddDescriptor<SocketInfo>(args);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700695}
Tom Cherryb7349902015-08-26 11:43:36 -0700696
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700697// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700698Result<Success> Service::ParseFile(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700699 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
Tom Cherry89bcc852017-08-02 17:01:36 -0700700 return Error() << "file type must be 'r', 'w' or 'rw'";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700701 }
702 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700703 return Error() << "file name must not be relative";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700704 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700705 return AddDescriptor<FileInfo>(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700706}
707
Tom Cherry89bcc852017-08-02 17:01:36 -0700708Result<Success> Service::ParseUser(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700709 auto uid = DecodeUid(args[1]);
710 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700711 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700712 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700713 uid_ = *uid;
Tom Cherry89bcc852017-08-02 17:01:36 -0700714 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700715}
716
Tom Cherry89bcc852017-08-02 17:01:36 -0700717Result<Success> Service::ParseWritepid(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700718 writepid_files_.assign(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700719 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700720}
721
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400722class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700723 public:
724 OptionParserMap() {}
725
726 private:
727 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700728};
729
Tom Cherryad54d092017-04-19 16:18:50 -0700730const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700731 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700732 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400733 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400734 {"capabilities",
735 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700736 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400737 {"console", {0, 1, &Service::ParseConsole}},
738 {"critical", {0, 0, &Service::ParseCritical}},
739 {"disabled", {0, 0, &Service::ParseDisabled}},
Tom Cherryaead51b2018-04-20 16:18:12 -0700740 {"enter_namespace",
741 {2, 2, &Service::ParseEnterNamespace}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800742 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400743 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
Steven Morelande055d732017-10-05 18:50:22 -0700744 {"interface", {2, 2, &Service::ParseInterface}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400745 {"ioprio", {2, 2, &Service::ParseIoprio}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400746 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
Robert Benead4852262017-07-16 19:38:11 -0700747 {"memcg.limit_in_bytes",
748 {1, 1, &Service::ParseMemcgLimitInBytes}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800749 {"memcg.soft_limit_in_bytes",
750 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
751 {"memcg.swappiness",
752 {1, 1, &Service::ParseMemcgSwappiness}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400753 {"namespace", {1, 2, &Service::ParseNamespace}},
Tom Cherrye2f341e2018-03-08 13:51:10 -0800754 {"oneshot", {0, 0, &Service::ParseOneshot}},
755 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
756 {"oom_score_adjust",
757 {1, 1, &Service::ParseOomScoreAdjust}},
758 {"override", {0, 0, &Service::ParseOverride}},
759 {"priority", {1, 1, &Service::ParsePriority}},
Tom Cherry7ac013d2017-08-25 10:39:25 -0700760 {"rlimit", {3, 3, &Service::ParseProcessRlimit}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400761 {"seclabel", {1, 1, &Service::ParseSeclabel}},
762 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700763 {"shutdown", {1, 1, &Service::ParseShutdown}},
Tom Cherry8f380482018-04-17 14:48:44 -0700764 {"sigstop", {0, 0, &Service::ParseSigstop}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400765 {"socket", {3, 6, &Service::ParseSocket}},
766 {"user", {1, 1, &Service::ParseUser}},
767 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700768 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700769 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400770 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700771}
772
Tom Cherry89bcc852017-08-02 17:01:36 -0700773Result<Success> Service::ParseLine(const std::vector<std::string>& args) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400774 static const OptionParserMap parser_map;
Tom Cherry89bcc852017-08-02 17:01:36 -0700775 auto parser = parser_map.FindFunction(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700776
Tom Cherry76af7e62017-08-22 16:13:59 -0700777 if (!parser) return parser.error();
Tom Cherryb7349902015-08-26 11:43:36 -0700778
Tom Cherry89bcc852017-08-02 17:01:36 -0700779 return std::invoke(*parser, this, args);
Tom Cherryb7349902015-08-26 11:43:36 -0700780}
781
Tom Cherry76af7e62017-08-22 16:13:59 -0700782Result<Success> Service::ExecStart() {
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700783 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700784
Tom Cherry76af7e62017-08-22 16:13:59 -0700785 if (auto result = Start(); !result) {
786 return result;
Tom Cherryb27004a2017-03-27 16:27:30 -0700787 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700788
789 flags_ |= SVC_EXEC;
790 is_exec_service_running_ = true;
791
Wei Wang2c4ee752018-06-20 14:54:52 -0700792 LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << uid_ << " gid "
793 << gid_ << "+" << supp_gids_.size() << " context "
794 << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700795
Tom Cherry76af7e62017-08-22 16:13:59 -0700796 return Success();
Tom Cherryb27004a2017-03-27 16:27:30 -0700797}
798
Tom Cherry76af7e62017-08-22 16:13:59 -0700799Result<Success> Service::Start() {
Tao Wu990d43c2017-10-26 10:43:10 -0700800 bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
Tom Cherrybac32992015-07-31 12:45:25 -0700801 // Starting a service removes it from the disabled or reset state and
802 // immediately takes it out of the restarting state if it was in there.
803 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700804
805 // Running processes require no additional work --- if they're in the
806 // process of exiting, we've ensured that they will immediately restart
Tao Wu990d43c2017-10-26 10:43:10 -0700807 // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
808 // stopping status, we just set SVC_RESTART flag so it will get restarted
809 // in Reap().
Tom Cherrybac32992015-07-31 12:45:25 -0700810 if (flags_ & SVC_RUNNING) {
Tao Wu990d43c2017-10-26 10:43:10 -0700811 if ((flags_ & SVC_ONESHOT) && disabled) {
812 flags_ |= SVC_RESTART;
813 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700814 // It is not an error to try to start a service that is already running.
815 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700816 }
817
818 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200819 if (needs_console) {
820 if (console_.empty()) {
821 console_ = default_console;
822 }
823
Adrian Salido24ef8602016-12-20 15:52:15 -0800824 // Make sure that open call succeeds to ensure a console driver is
825 // properly registered for the device node
826 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
827 if (console_fd < 0) {
Viorel Suman70daa672016-03-21 10:08:07 +0200828 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700829 return ErrnoError() << "Couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200830 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800831 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700832 }
833
834 struct stat sb;
835 if (stat(args_[0].c_str(), &sb) == -1) {
Tom Cherrybac32992015-07-31 12:45:25 -0700836 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700837 return ErrnoError() << "Cannot find '" << args_[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700838 }
839
Tom Cherrybac32992015-07-31 12:45:25 -0700840 std::string scon;
841 if (!seclabel_.empty()) {
842 scon = seclabel_;
843 } else {
Tom Cherryaead51b2018-04-20 16:18:12 -0700844 auto result = ComputeContextFromExecutable(args_[0]);
Tom Cherry76af7e62017-08-22 16:13:59 -0700845 if (!result) {
846 return result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700847 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700848 scon = *result;
Tom Cherrybac32992015-07-31 12:45:25 -0700849 }
850
Wei Wanga285dac2016-10-04 14:05:39 -0700851 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700852
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700853 pid_t pid = -1;
854 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400855 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700856 } else {
857 pid = fork();
858 }
859
Tom Cherrybac32992015-07-31 12:45:25 -0700860 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700861 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700862
Tom Cherryaead51b2018-04-20 16:18:12 -0700863 if (auto result = EnterNamespaces(); !result) {
864 LOG(FATAL) << "Service '" << name_ << "' could not enter namespaces: " << result.error();
865 }
866
867 if (namespace_flags_ & CLONE_NEWNS) {
868 if (auto result = SetUpMountNamespace(); !result) {
869 LOG(FATAL) << "Service '" << name_
870 << "' could not set up mount namespace: " << result.error();
871 }
872 }
873
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700874 if (namespace_flags_ & CLONE_NEWPID) {
875 // This will fork again to run an init process inside the PID
876 // namespace.
Tom Cherryaead51b2018-04-20 16:18:12 -0700877 if (auto result = SetUpPidNamespace(); !result) {
878 LOG(FATAL) << "Service '" << name_
879 << "' could not set up PID namespace: " << result.error();
880 }
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700881 }
882
Tom Cherry6de21f12017-08-22 15:41:03 -0700883 for (const auto& [key, value] : environment_vars_) {
884 setenv(key.c_str(), value.c_str(), 1);
Tom Cherrybac32992015-07-31 12:45:25 -0700885 }
886
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700887 std::for_each(descriptors_.begin(), descriptors_.end(),
888 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700889
Alex Vakulenko08286762016-05-03 12:00:00 -0700890 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
891 auto cpuset_predicate = [](const std::string& path) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700892 return StartsWith(path, "/dev/cpuset/");
Alex Vakulenko08286762016-05-03 12:00:00 -0700893 };
894 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
895 if (iter == writepid_files_.end()) {
896 // There were no "writepid" instructions for cpusets, check if the system default
897 // cpuset is specified to be used for the process.
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700898 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700899 if (!default_cpuset.empty()) {
900 // Make sure the cpuset name starts and ends with '/'.
901 // A single '/' means the 'root' cpuset.
902 if (default_cpuset.front() != '/') {
903 default_cpuset.insert(0, 1, '/');
904 }
905 if (default_cpuset.back() != '/') {
906 default_cpuset.push_back('/');
907 }
908 writepid_files_.push_back(
909 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
910 }
911 }
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700912 std::string pid_str = std::to_string(getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700913 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700914 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700915 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700916 }
917 }
918
919 if (ioprio_class_ != IoSchedClass_NONE) {
920 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400921 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700922 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700923 }
924 }
925
926 if (needs_console) {
927 setsid();
928 OpenConsole();
929 } else {
930 ZapStdio();
931 }
932
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400933 // As requested, set our gid, supplemental gids, uid, context, and
934 // priority. Aborts on failure.
935 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700936
Tom Cherry8f380482018-04-17 14:48:44 -0700937 if (!ExpandArgsAndExecv(args_, sigstop_)) {
Tom Cherry5e405ca2017-09-11 16:08:54 -0700938 PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700939 }
940
941 _exit(127);
942 }
943
944 if (pid < 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700945 pid_ = 0;
Tom Cherry76af7e62017-08-22 16:13:59 -0700946 return ErrnoError() << "Failed to fork";
Tom Cherrybac32992015-07-31 12:45:25 -0700947 }
948
Marco Nelissen310f6702016-07-22 12:07:06 -0700949 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700950 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700951 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
952 if (!WriteStringToFile(oom_str, oom_file)) {
953 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
954 }
955 }
956
Elliott Hughes9605a942016-11-10 17:43:47 -0800957 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700958 pid_ = pid;
959 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -0700960 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -0700961 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700962
963 errno = -createProcessGroup(uid_, pid_);
964 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400965 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
966 << name_ << "'";
Robert Benead4852262017-07-16 19:38:11 -0700967 } else {
968 if (swappiness_ != -1) {
969 if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
970 PLOG(ERROR) << "setProcessGroupSwappiness failed";
971 }
972 }
973
974 if (soft_limit_in_bytes_ != -1) {
975 if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
976 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
977 }
978 }
979
980 if (limit_in_bytes_ != -1) {
981 if (!setProcessGroupLimit(uid_, pid_, limit_in_bytes_)) {
982 PLOG(ERROR) << "setProcessGroupLimit failed";
983 }
984 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700985 }
Tom Cherrybac32992015-07-31 12:45:25 -0700986
Tom Cherrybac32992015-07-31 12:45:25 -0700987 NotifyStateChange("running");
Tom Cherry76af7e62017-08-22 16:13:59 -0700988 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700989}
990
Tom Cherry76af7e62017-08-22 16:13:59 -0700991Result<Success> Service::StartIfNotDisabled() {
Tom Cherrybac32992015-07-31 12:45:25 -0700992 if (!(flags_ & SVC_DISABLED)) {
993 return Start();
994 } else {
995 flags_ |= SVC_DISABLED_START;
996 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700997 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700998}
999
Tom Cherry76af7e62017-08-22 16:13:59 -07001000Result<Success> Service::Enable() {
Tom Cherrybac32992015-07-31 12:45:25 -07001001 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
1002 if (flags_ & SVC_DISABLED_START) {
1003 return Start();
1004 }
Tom Cherry76af7e62017-08-22 16:13:59 -07001005 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -07001006}
1007
1008void Service::Reset() {
1009 StopOrReset(SVC_RESET);
1010}
1011
1012void Service::Stop() {
1013 StopOrReset(SVC_DISABLED);
1014}
1015
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001016void Service::Terminate() {
1017 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1018 flags_ |= SVC_DISABLED;
1019 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001020 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001021 NotifyStateChange("stopping");
1022 }
1023}
1024
Tom Cherrybac32992015-07-31 12:45:25 -07001025void Service::Restart() {
1026 if (flags_ & SVC_RUNNING) {
1027 /* Stop, wait, then start the service. */
1028 StopOrReset(SVC_RESTART);
1029 } else if (!(flags_ & SVC_RESTARTING)) {
1030 /* Just start the service since it's not running. */
Tom Cherry76af7e62017-08-22 16:13:59 -07001031 if (auto result = Start(); !result) {
1032 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
1033 }
Tom Cherrybac32992015-07-31 12:45:25 -07001034 } /* else: Service is restarting anyways. */
1035}
1036
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001037// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -07001038void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001039 // The service is still SVC_RUNNING until its process exits, but if it has
1040 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -07001041 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1042
1043 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001044 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -07001045 how = SVC_DISABLED;
1046 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001047
1048 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -07001049 if (how == SVC_RESET) {
1050 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
1051 } else {
1052 flags_ |= how;
1053 }
Tao Wu84b856d2017-10-27 11:29:13 -07001054 // Make sure it's in right status when a restart immediately follow a
1055 // stop/reset or vice versa.
1056 if (how == SVC_RESTART) {
1057 flags_ &= (~(SVC_DISABLED | SVC_RESET));
1058 } else {
1059 flags_ &= (~SVC_RESTART);
1060 }
Tom Cherrybac32992015-07-31 12:45:25 -07001061
1062 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -07001063 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -07001064 NotifyStateChange("stopping");
1065 } else {
1066 NotifyStateChange("stopped");
1067 }
1068}
1069
1070void Service::ZapStdio() const {
1071 int fd;
1072 fd = open("/dev/null", O_RDWR);
1073 dup2(fd, 0);
1074 dup2(fd, 1);
1075 dup2(fd, 2);
1076 close(fd);
1077}
1078
1079void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +02001080 int fd = open(console_.c_str(), O_RDWR);
1081 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -07001082 ioctl(fd, TIOCSCTTY, 0);
1083 dup2(fd, 0);
1084 dup2(fd, 1);
1085 dup2(fd, 2);
1086 close(fd);
1087}
1088
Tom Cherry911b9b12017-07-27 16:20:58 -07001089ServiceList::ServiceList() {}
Tom Cherrybac32992015-07-31 12:45:25 -07001090
Tom Cherry911b9b12017-07-27 16:20:58 -07001091ServiceList& ServiceList::GetInstance() {
1092 static ServiceList instance;
Tom Cherrybac32992015-07-31 12:45:25 -07001093 return instance;
1094}
1095
Tom Cherry911b9b12017-07-27 16:20:58 -07001096void ServiceList::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -07001097 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -07001098}
1099
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001100std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -07001101 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
1102 // SECLABEL can be a - to denote default
1103 std::size_t command_arg = 1;
1104 for (std::size_t i = 1; i < args.size(); ++i) {
1105 if (args[i] == "--") {
1106 command_arg = i + 1;
1107 break;
1108 }
1109 }
1110 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001111 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -07001112 return nullptr;
1113 }
1114
1115 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001116 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -07001117 return nullptr;
1118 }
1119 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
1120
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001121 static size_t exec_count = 0;
1122 exec_count++;
1123 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -07001124
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001125 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -04001126 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001127 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001128
1129 std::string seclabel = "";
1130 if (command_arg > 2 && args[1] != "-") {
1131 seclabel = args[1];
1132 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001133 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001134 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001135 uid = DecodeUid(args[2]);
1136 if (!uid) {
1137 LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001138 return nullptr;
1139 }
Tom Cherrybac32992015-07-31 12:45:25 -07001140 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001141 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001142 std::vector<gid_t> supp_gids;
1143 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001144 gid = DecodeUid(args[3]);
1145 if (!gid) {
1146 LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001147 return nullptr;
1148 }
Tom Cherrybac32992015-07-31 12:45:25 -07001149 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
1150 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001151 auto supp_gid = DecodeUid(args[4 + i]);
1152 if (!supp_gid) {
1153 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
1154 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001155 return nullptr;
1156 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001157 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -07001158 }
1159 }
1160
Tom Cherry11a3aee2017-08-03 12:54:07 -07001161 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, no_capabilities,
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001162 namespace_flags, seclabel, nullptr, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001163}
1164
Tom Cherry59383792017-07-26 16:09:09 -07001165// Shutdown services in the opposite order that they were started.
Tom Cherry911b9b12017-07-27 16:20:58 -07001166const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
Tom Cherry59383792017-07-26 16:09:09 -07001167 std::vector<Service*> shutdown_services;
1168 for (const auto& service : services_) {
1169 if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
1170 }
1171 std::sort(shutdown_services.begin(), shutdown_services.end(),
1172 [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
Tom Cherry911b9b12017-07-27 16:20:58 -07001173 return shutdown_services;
Tom Cherry59383792017-07-26 16:09:09 -07001174}
1175
Tom Cherry911b9b12017-07-27 16:20:58 -07001176void ServiceList::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001177 auto svc_it = std::find_if(services_.begin(), services_.end(),
1178 [&svc] (const std::unique_ptr<Service>& s) {
1179 return svc.name() == s->name();
1180 });
1181 if (svc_it == services_.end()) {
1182 return;
1183 }
1184
1185 services_.erase(svc_it);
1186}
1187
Tom Cherry911b9b12017-07-27 16:20:58 -07001188void ServiceList::DumpState() const {
Tom Cherryb7349902015-08-26 11:43:36 -07001189 for (const auto& s : services_) {
1190 s->DumpState();
1191 }
Tom Cherryb7349902015-08-26 11:43:36 -07001192}
1193
Tom Cherry89bcc852017-08-02 17:01:36 -07001194Result<Success> ServiceParser::ParseSection(std::vector<std::string>&& args,
1195 const std::string& filename, int line) {
Tom Cherryb7349902015-08-26 11:43:36 -07001196 if (args.size() < 3) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001197 return Error() << "services must have a name and a program";
Tom Cherryb7349902015-08-26 11:43:36 -07001198 }
1199
1200 const std::string& name = args[1];
1201 if (!IsValidName(name)) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001202 return Error() << "invalid service name '" << name << "'";
Tom Cherryb7349902015-08-26 11:43:36 -07001203 }
1204
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001205 Subcontext* restart_action_subcontext = nullptr;
1206 if (subcontexts_) {
1207 for (auto& subcontext : *subcontexts_) {
Elliott Hughes579e6822017-12-20 09:41:00 -08001208 if (StartsWith(filename, subcontext.path_prefix())) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001209 restart_action_subcontext = &subcontext;
1210 break;
1211 }
1212 }
1213 }
1214
Tom Cherryb7349902015-08-26 11:43:36 -07001215 std::vector<std::string> str_args(args.begin() + 2, args.end());
Tom Cherry40acb372018-08-01 13:41:12 -07001216
1217 if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
1218 if (str_args[0] == "/sbin/watchdogd") {
1219 str_args[0] = "/system/bin/watchdogd";
1220 }
1221 }
1222
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001223 service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
Tom Cherry89bcc852017-08-02 17:01:36 -07001224 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001225}
1226
Tom Cherry89bcc852017-08-02 17:01:36 -07001227Result<Success> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
1228 return service_ ? service_->ParseLine(std::move(args)) : Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001229}
1230
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001231Result<Success> ServiceParser::EndSection() {
Tom Cherryb7349902015-08-26 11:43:36 -07001232 if (service_) {
Steven Moreland5e1bea32017-11-10 14:43:58 -08001233 Service* old_service = service_list_->FindService(service_->name());
1234 if (old_service) {
Steven Moreland6f5333a2017-11-13 15:31:54 -08001235 if (!service_->is_override()) {
1236 return Error() << "ignored duplicate definition of service '" << service_->name()
1237 << "'";
1238 }
1239
1240 service_list_->RemoveService(*old_service);
1241 old_service = nullptr;
Steven Moreland5e1bea32017-11-10 14:43:58 -08001242 }
1243
Tom Cherry911b9b12017-07-27 16:20:58 -07001244 service_list_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001245 }
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001246
1247 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001248}
1249
1250bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001251 // Property names can be any length, but may only contain certain characters.
1252 // Property values can contain any characters, but may only be a certain length.
1253 // (The latter restriction is needed because `start` and `stop` work by writing
1254 // the service name to the "ctl.start" and "ctl.stop" properties.)
Tom Cherryde6bd502018-02-13 16:50:08 -08001255 return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001256}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001257
1258} // namespace init
1259} // namespace android