blob: 8130e73a9cc12f065e54b0737a3680f4ca960136 [file] [log] [blame]
Tom Cherrybac32992015-07-31 12:45:25 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "service.h"
18
19#include <fcntl.h>
Elliott Hughes9605a942016-11-10 17:43:47 -080020#include <inttypes.h>
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -040021#include <linux/securebits.h>
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070022#include <sched.h>
23#include <sys/mount.h>
24#include <sys/prctl.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070025#include <sys/resource.h>
Tom Cherrybac32992015-07-31 12:45:25 -070026#include <sys/stat.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070027#include <sys/time.h>
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -080028#include <sys/wait.h>
Tom Cherrybac32992015-07-31 12:45:25 -070029#include <termios.h>
Dan Albertaf9ba4d2015-08-11 16:37:04 -070030#include <unistd.h>
Tom Cherrybac32992015-07-31 12:45:25 -070031
Elliott Hughes4f713192015-12-04 22:00:26 -080032#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070033#include <android-base/logging.h>
Elliott Hughesda46b392016-10-11 17:09:00 -070034#include <android-base/parseint.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080035#include <android-base/stringprintf.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070036#include <android-base/strings.h>
Steven Morelande055d732017-10-05 18:50:22 -070037#include <hidl-util/FQName.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070038#include <processgroup/processgroup.h>
39#include <selinux/selinux.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070040#include <system/thread_defs.h>
Tom Cherrybac32992015-07-31 12:45:25 -070041
Tom Cherry7ac013d2017-08-25 10:39:25 -070042#include "rlimit_parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070043#include "util.h"
44
Tom Cherryde6bd502018-02-13 16:50:08 -080045#if defined(__ANDROID__)
46#include <sys/system_properties.h>
47
48#include <android-base/properties.h>
49
50#include "init.h"
51#include "property_service.h"
52#else
53#include "host_init_stubs.h"
54#endif
55
James Hawkinse78ea772017-03-24 11:43:02 -070056using android::base::boot_clock;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070057using android::base::GetProperty;
58using android::base::Join;
Elliott Hughesda46b392016-10-11 17:09:00 -070059using android::base::ParseInt;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070060using android::base::StartsWith;
Tom Cherryb7349902015-08-26 11:43:36 -070061using android::base::StringPrintf;
62using android::base::WriteStringToFile;
63
Tom Cherry81f5d3e2017-06-22 12:53:17 -070064namespace android {
65namespace init {
66
Tom Cherry76af7e62017-08-22 16:13:59 -070067static Result<std::string> ComputeContextFromExecutable(std::string& service_name,
68 const std::string& service_path) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040069 std::string computed_context;
70
71 char* raw_con = nullptr;
72 char* raw_filecon = nullptr;
73
74 if (getcon(&raw_con) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070075 return Error() << "Could not get security context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040076 }
77 std::unique_ptr<char> mycon(raw_con);
78
79 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070080 return Error() << "Could not get file context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040081 }
82 std::unique_ptr<char> filecon(raw_filecon);
83
84 char* new_con = nullptr;
85 int rc = security_compute_create(mycon.get(), filecon.get(),
86 string_to_security_class("process"), &new_con);
87 if (rc == 0) {
88 computed_context = new_con;
89 free(new_con);
90 }
91 if (rc == 0 && computed_context == mycon.get()) {
Nick Kralevich1ea19eb2017-08-25 12:08:57 -070092 return Error() << "File " << service_path << "(labeled \"" << filecon.get()
93 << "\") has incorrect label or no domain transition from " << mycon.get()
94 << " to another SELinux domain defined. Have you configured your "
95 "service correctly? https://source.android.com/security/selinux/"
96 "device-policy#label_new_services_and_address_denials";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040097 }
98 if (rc < 0) {
Tom Cherry76af7e62017-08-22 16:13:59 -070099 return Error() << "Could not get process context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400100 }
101 return computed_context;
102}
103
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700104static void SetUpPidNamespace(const std::string& service_name) {
105 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
106
107 // It's OK to LOG(FATAL) in this function since it's running in the first
108 // child process.
Joe Tanen4bfdcb32017-10-25 08:07:26 -0400109
110 // 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) {
116 PLOG(FATAL) << "couldn't remount(/) recursively as slave for " << service_name;
117 }
118 // umount() then mount() /proc.
119 // Note that it is not sufficient to mount with MS_REMOUNT.
120 if (umount("/proc") == -1) {
121 PLOG(FATAL) << "couldn't umount(/proc) for " << service_name;
122 }
123 if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
124 PLOG(FATAL) << "couldn't mount(/proc) for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700125 }
126
127 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700128 PLOG(FATAL) << "couldn't set name for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700129 }
130
131 pid_t child_pid = fork();
132 if (child_pid == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700133 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700134 }
135
136 if (child_pid > 0) {
137 // So that we exit with the right status.
138 static int init_exitstatus = 0;
139 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
140
141 pid_t waited_pid;
142 int status;
143 while ((waited_pid = wait(&status)) > 0) {
144 // This loop will end when there are no processes left inside the
145 // PID namespace or when the init process inside the PID namespace
146 // gets a signal.
147 if (waited_pid == child_pid) {
148 init_exitstatus = status;
149 }
150 }
151 if (!WIFEXITED(init_exitstatus)) {
152 _exit(EXIT_FAILURE);
153 }
154 _exit(WEXITSTATUS(init_exitstatus));
155 }
156}
157
Tom Cherry5e405ca2017-09-11 16:08:54 -0700158static bool ExpandArgsAndExecv(const std::vector<std::string>& args) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400159 std::vector<std::string> expanded_args;
Tom Cherry5e405ca2017-09-11 16:08:54 -0700160 std::vector<char*> c_strings;
161
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400162 expanded_args.resize(args.size());
Tom Cherry5e405ca2017-09-11 16:08:54 -0700163 c_strings.push_back(const_cast<char*>(args[0].data()));
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400164 for (std::size_t i = 1; i < args.size(); ++i) {
165 if (!expand_props(args[i], &expanded_args[i])) {
166 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
167 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700168 c_strings.push_back(expanded_args[i].data());
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400169 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700170 c_strings.push_back(nullptr);
171
172 return execv(c_strings[0], c_strings.data()) == 0;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400173}
174
Tom Cherry59383792017-07-26 16:09:09 -0700175unsigned long Service::next_start_order_ = 1;
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700176bool Service::is_exec_service_running_ = false;
Tom Cherry59383792017-07-26 16:09:09 -0700177
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700178Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
179 const std::vector<std::string>& args)
180 : Service(name, 0, 0, 0, {}, 0, 0, "", subcontext_for_restart_commands, args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700181
Wei Wang641ff0a2017-03-27 10:59:11 -0700182Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
183 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
184 unsigned namespace_flags, const std::string& seclabel,
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700185 Subcontext* subcontext_for_restart_commands, const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700186 : name_(name),
187 classnames_({"default"}),
188 flags_(flags),
189 pid_(0),
190 crash_count_(0),
191 uid_(uid),
192 gid_(gid),
193 supp_gids_(supp_gids),
194 capabilities_(capabilities),
195 namespace_flags_(namespace_flags),
196 seclabel_(seclabel),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800197 onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0,
198 "onrestart", {}),
Tom Cherry7da54852017-05-01 14:16:41 -0700199 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700200 ioprio_class_(IoSchedClass_NONE),
201 ioprio_pri_(0),
202 priority_(0),
203 oom_score_adjust_(-1000),
Robert Benead4852262017-07-16 19:38:11 -0700204 swappiness_(-1),
205 soft_limit_in_bytes_(-1),
206 limit_in_bytes_(-1),
Tom Cherry59383792017-07-26 16:09:09 -0700207 start_order_(0),
Tom Cherry9cbf5702018-02-13 16:24:51 -0800208 args_(args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700209
210void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700211 if ((flags_ & SVC_TEMPORARY) != 0) {
212 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700213 return;
214 }
215
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700216 std::string prop_name = "init.svc." + name_;
217 property_set(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800218
219 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800220 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherryfed33732017-08-18 10:47:46 -0700221 std::string boottime_property = "ro.boottime." + name_;
222 if (GetProperty(boottime_property, "").empty()) {
223 property_set(boottime_property, std::to_string(start_ns));
224 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800225 }
Tom Cherrybac32992015-07-31 12:45:25 -0700226}
227
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700228void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700229 // If we've already seen a successful result from killProcessGroup*(), then we have removed
230 // the cgroup already and calling these functions a second time will simply result in an error.
231 // This is true regardless of which signal was sent.
232 // These functions handle their own logging, so no additional logging is needed.
233 if (!process_cgroup_empty_) {
234 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
235 << ") process group...";
236 int r;
237 if (signal == SIGTERM) {
238 r = killProcessGroupOnce(uid_, pid_, signal);
239 } else {
240 r = killProcessGroup(uid_, pid_, signal);
241 }
242
243 if (r == 0) process_cgroup_empty_ = true;
244 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700245}
246
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400247void Service::SetProcessAttributes() {
Tom Cherry7ac013d2017-08-25 10:39:25 -0700248 for (const auto& rlimit : rlimits_) {
249 if (setrlimit(rlimit.first, &rlimit.second) == -1) {
250 LOG(FATAL) << StringPrintf("setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed",
251 rlimit.first, rlimit.second.rlim_cur, rlimit.second.rlim_max);
252 }
253 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400254 // Keep capabilites on uid change.
255 if (capabilities_.any() && uid_) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700256 // If Android is running in a container, some securebits might already
257 // be locked, so don't change those.
Ben Fennemaa7243602017-07-25 14:37:21 -0700258 unsigned long securebits = prctl(PR_GET_SECUREBITS);
259 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700260 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
261 }
262 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
263 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
264 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400265 }
266 }
267
Elliott Hughese18e7e52016-07-25 18:18:16 -0700268 // TODO: work out why this fails for `console` then upgrade to FATAL.
269 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400270
271 if (gid_) {
272 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700273 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400274 }
275 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700276 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
277 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400278 }
279 if (uid_) {
280 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700281 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400282 }
283 }
284 if (!seclabel_.empty()) {
285 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700286 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400287 }
288 }
289 if (priority_ != 0) {
290 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700291 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400292 }
293 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400294 if (capabilities_.any()) {
295 if (!SetCapsForExec(capabilities_)) {
296 LOG(FATAL) << "cannot set capabilities for " << name_;
297 }
Luis Hector Chavez94fb5b02017-11-16 15:52:00 -0800298 } else if (uid_) {
299 // Inheritable caps can be non-zero when running in a container.
300 if (!DropInheritableCaps()) {
301 LOG(FATAL) << "cannot drop inheritable caps for " << name_;
302 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400303 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400304}
305
Paul Crowleye242a972018-03-01 23:24:20 +0000306void Service::Reap() {
Tom Cherrybac32992015-07-31 12:45:25 -0700307 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700308 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700309 }
310
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700311 // Remove any descriptor resources we may have created.
312 std::for_each(descriptors_.begin(), descriptors_.end(),
313 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700314
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700315 if (flags_ & SVC_EXEC) UnSetExec();
316
317 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700318
319 pid_ = 0;
320 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700321 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700322
323 // Oneshot processes go into the disabled state on exit,
324 // except when manually restarted.
325 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
326 flags_ |= SVC_DISABLED;
327 }
328
329 // Disabled and reset processes do not get restarted automatically.
330 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
331 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700332 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700333 }
334
Elliott Hughes9605a942016-11-10 17:43:47 -0800335 // If we crash > 4 times in 4 minutes, reboot into recovery.
336 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700337 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800338 if (now < time_crashed_ + 4min) {
339 if (++crash_count_ > 4) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700340 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
Tom Cherrybac32992015-07-31 12:45:25 -0700341 }
342 } else {
343 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800344 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700345 }
346 }
347
348 flags_ &= (~SVC_RESTART);
349 flags_ |= SVC_RESTARTING;
350
351 // Execute all onrestart commands for this service.
352 onrestart_.ExecuteAllCommands();
353
354 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700355 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700356}
357
358void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700359 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700360 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
361 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700362 std::for_each(descriptors_.begin(), descriptors_.end(),
363 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700364}
365
Tom Cherry89bcc852017-08-02 17:01:36 -0700366Result<Success> Service::ParseCapabilities(const std::vector<std::string>& args) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400367 capabilities_ = 0;
368
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500369 if (!CapAmbientSupported()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700370 return Error()
371 << "capabilities requested but the kernel does not support ambient capabilities";
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500372 }
373
374 unsigned int last_valid_cap = GetLastValidCap();
375 if (last_valid_cap >= capabilities_.size()) {
376 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
377 }
378
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400379 for (size_t i = 1; i < args.size(); i++) {
380 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500381 int res = LookupCap(arg);
382 if (res < 0) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700383 return Error() << StringPrintf("invalid capability '%s'", arg.c_str());
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400384 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500385 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
386 if (cap > last_valid_cap) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700387 return Error() << StringPrintf("capability '%s' not supported by the kernel",
388 arg.c_str());
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500389 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400390 capabilities_[cap] = true;
391 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700392 return Success();
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400393}
394
Tom Cherry89bcc852017-08-02 17:01:36 -0700395Result<Success> Service::ParseClass(const std::vector<std::string>& args) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700396 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700397 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700398}
Tom Cherrybac32992015-07-31 12:45:25 -0700399
Tom Cherry89bcc852017-08-02 17:01:36 -0700400Result<Success> Service::ParseConsole(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700401 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200402 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherry89bcc852017-08-02 17:01:36 -0700403 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700404}
Tom Cherrybac32992015-07-31 12:45:25 -0700405
Tom Cherry89bcc852017-08-02 17:01:36 -0700406Result<Success> Service::ParseCritical(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700407 flags_ |= SVC_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700408 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700409}
Tom Cherrybac32992015-07-31 12:45:25 -0700410
Tom Cherry89bcc852017-08-02 17:01:36 -0700411Result<Success> Service::ParseDisabled(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700412 flags_ |= SVC_DISABLED;
413 flags_ |= SVC_RC_DISABLED;
Tom Cherry89bcc852017-08-02 17:01:36 -0700414 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700415}
Tom Cherrybac32992015-07-31 12:45:25 -0700416
Tom Cherry89bcc852017-08-02 17:01:36 -0700417Result<Success> Service::ParseGroup(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700418 auto gid = DecodeUid(args[1]);
419 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700420 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700421 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700422 gid_ = *gid;
423
Tom Cherryb7349902015-08-26 11:43:36 -0700424 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700425 gid = DecodeUid(args[n]);
426 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700427 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700428 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700429 supp_gids_.emplace_back(*gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700430 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700431 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700432}
433
Tom Cherry89bcc852017-08-02 17:01:36 -0700434Result<Success> Service::ParsePriority(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700435 priority_ = 0;
436 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800437 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
438 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700439 return Error() << StringPrintf("process priority value must be range %d - %d",
440 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700441 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700442 return Success();
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700443}
444
Steven Morelande055d732017-10-05 18:50:22 -0700445Result<Success> Service::ParseInterface(const std::vector<std::string>& args) {
446 const std::string& interface_name = args[1];
447 const std::string& instance_name = args[2];
448
449 const FQName fq_name = FQName(interface_name);
450 if (!fq_name.isValid()) {
451 return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
452 }
453
454 if (!fq_name.isFullyQualified()) {
455 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
456 }
457
458 if (fq_name.isValidValueName()) {
459 return Error() << "Interface name must not be a value name '" << interface_name << "'";
460 }
461
462 const std::string fullname = interface_name + "/" + instance_name;
463
464 for (const auto& svc : ServiceList::GetInstance()) {
465 if (svc->interfaces().count(fullname) > 0) {
466 return Error() << "Interface '" << fullname << "' redefined in " << name()
467 << " but is already defined by " << svc->name();
468 }
469 }
470
471 interfaces_.insert(fullname);
472
473 return Success();
474}
475
Tom Cherry89bcc852017-08-02 17:01:36 -0700476Result<Success> Service::ParseIoprio(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700477 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700478 return Error() << "priority value must be range 0 - 7";
Tom Cherryb7349902015-08-26 11:43:36 -0700479 }
480
481 if (args[1] == "rt") {
482 ioprio_class_ = IoSchedClass_RT;
483 } else if (args[1] == "be") {
484 ioprio_class_ = IoSchedClass_BE;
485 } else if (args[1] == "idle") {
486 ioprio_class_ = IoSchedClass_IDLE;
487 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700488 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
Tom Cherryb7349902015-08-26 11:43:36 -0700489 }
490
Tom Cherry89bcc852017-08-02 17:01:36 -0700491 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700492}
493
Tom Cherry89bcc852017-08-02 17:01:36 -0700494Result<Success> Service::ParseKeycodes(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700495 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700496 int code;
497 if (ParseInt(args[i], &code)) {
498 keycodes_.emplace_back(code);
499 } else {
500 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
501 }
Tom Cherryb7349902015-08-26 11:43:36 -0700502 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700503 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700504}
505
Tom Cherry89bcc852017-08-02 17:01:36 -0700506Result<Success> Service::ParseOneshot(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700507 flags_ |= SVC_ONESHOT;
Tom Cherry89bcc852017-08-02 17:01:36 -0700508 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700509}
510
Tom Cherry89bcc852017-08-02 17:01:36 -0700511Result<Success> Service::ParseOnrestart(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700512 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700513 int line = onrestart_.NumCommands() + 1;
Tom Cherry89bcc852017-08-02 17:01:36 -0700514 if (auto result = onrestart_.AddCommand(str_args, line); !result) {
515 return Error() << "cannot add Onrestart command: " << result.error();
516 }
517 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700518}
519
Tom Cherry89bcc852017-08-02 17:01:36 -0700520Result<Success> Service::ParseNamespace(const std::vector<std::string>& args) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700521 for (size_t i = 1; i < args.size(); i++) {
522 if (args[i] == "pid") {
523 namespace_flags_ |= CLONE_NEWPID;
524 // PID namespaces require mount namespaces.
525 namespace_flags_ |= CLONE_NEWNS;
526 } else if (args[i] == "mnt") {
527 namespace_flags_ |= CLONE_NEWNS;
528 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700529 return Error() << "namespace must be 'pid' or 'mnt'";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700530 }
531 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700532 return Success();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700533}
534
Tom Cherry89bcc852017-08-02 17:01:36 -0700535Result<Success> Service::ParseOomScoreAdjust(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700536 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700537 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
Marco Nelissen310f6702016-07-22 12:07:06 -0700538 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700539 return Success();
Marco Nelissen310f6702016-07-22 12:07:06 -0700540}
541
Steven Moreland6f5333a2017-11-13 15:31:54 -0800542Result<Success> Service::ParseOverride(const std::vector<std::string>& args) {
543 override_ = true;
544 return Success();
545}
546
Tom Cherry89bcc852017-08-02 17:01:36 -0700547Result<Success> Service::ParseMemcgSwappiness(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700548 if (!ParseInt(args[1], &swappiness_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700549 return Error() << "swappiness value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700550 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700551 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700552}
553
Tom Cherry89bcc852017-08-02 17:01:36 -0700554Result<Success> Service::ParseMemcgLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700555 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700556 return Error() << "limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700557 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700558 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700559}
560
Tom Cherry89bcc852017-08-02 17:01:36 -0700561Result<Success> Service::ParseMemcgSoftLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700562 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700563 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700564 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700565 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700566}
567
Tom Cherry7ac013d2017-08-25 10:39:25 -0700568Result<Success> Service::ParseProcessRlimit(const std::vector<std::string>& args) {
569 auto rlimit = ParseRlimit(args);
570 if (!rlimit) return rlimit.error();
571
572 rlimits_.emplace_back(*rlimit);
573 return Success();
574}
575
Tom Cherry89bcc852017-08-02 17:01:36 -0700576Result<Success> Service::ParseSeclabel(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700577 seclabel_ = args[1];
Tom Cherry89bcc852017-08-02 17:01:36 -0700578 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700579}
580
Tom Cherry89bcc852017-08-02 17:01:36 -0700581Result<Success> Service::ParseSetenv(const std::vector<std::string>& args) {
Tom Cherry6de21f12017-08-22 15:41:03 -0700582 environment_vars_.emplace_back(args[1], args[2]);
Tom Cherry89bcc852017-08-02 17:01:36 -0700583 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700584}
585
Tom Cherry89bcc852017-08-02 17:01:36 -0700586Result<Success> Service::ParseShutdown(const std::vector<std::string>& args) {
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700587 if (args[1] == "critical") {
588 flags_ |= SVC_SHUTDOWN_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700589 return Success();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700590 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700591 return Error() << "Invalid shutdown option";
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700592}
593
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700594template <typename T>
Tom Cherry89bcc852017-08-02 17:01:36 -0700595Result<Success> Service::AddDescriptor(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700596 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700597 Result<uid_t> uid = 0;
598 Result<gid_t> gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700599 std::string context = args.size() > 6 ? args[6] : "";
600
Tom Cherry517e1f12017-05-04 17:40:33 -0700601 if (args.size() > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700602 uid = DecodeUid(args[4]);
603 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700604 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700605 }
606 }
607
608 if (args.size() > 5) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700609 gid = DecodeUid(args[5]);
610 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700611 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700612 }
613 }
614
Tom Cherry11a3aee2017-08-03 12:54:07 -0700615 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700616
617 auto old =
618 std::find_if(descriptors_.begin(), descriptors_.end(),
619 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
620
621 if (old != descriptors_.end()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700622 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700623 }
624
625 descriptors_.emplace_back(std::move(descriptor));
Tom Cherry89bcc852017-08-02 17:01:36 -0700626 return Success();
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700627}
628
629// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700630Result<Success> Service::ParseSocket(const std::vector<std::string>& args) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700631 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
632 !StartsWith(args[2], "seqpacket")) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700633 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
Tom Cherryb7349902015-08-26 11:43:36 -0700634 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700635 return AddDescriptor<SocketInfo>(args);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700636}
Tom Cherryb7349902015-08-26 11:43:36 -0700637
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700638// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700639Result<Success> Service::ParseFile(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700640 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
Tom Cherry89bcc852017-08-02 17:01:36 -0700641 return Error() << "file type must be 'r', 'w' or 'rw'";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700642 }
643 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700644 return Error() << "file name must not be relative";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700645 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700646 return AddDescriptor<FileInfo>(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700647}
648
Tom Cherry89bcc852017-08-02 17:01:36 -0700649Result<Success> Service::ParseUser(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700650 auto uid = DecodeUid(args[1]);
651 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700652 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700653 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700654 uid_ = *uid;
Tom Cherry89bcc852017-08-02 17:01:36 -0700655 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700656}
657
Tom Cherry89bcc852017-08-02 17:01:36 -0700658Result<Success> Service::ParseWritepid(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700659 writepid_files_.assign(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700660 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700661}
662
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400663class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700664 public:
665 OptionParserMap() {}
666
667 private:
668 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700669};
670
Tom Cherryad54d092017-04-19 16:18:50 -0700671const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700672 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700673 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400674 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400675 {"capabilities",
676 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700677 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400678 {"console", {0, 1, &Service::ParseConsole}},
679 {"critical", {0, 0, &Service::ParseCritical}},
680 {"disabled", {0, 0, &Service::ParseDisabled}},
681 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
Steven Morelande055d732017-10-05 18:50:22 -0700682 {"interface", {2, 2, &Service::ParseInterface}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400683 {"ioprio", {2, 2, &Service::ParseIoprio}},
684 {"priority", {1, 1, &Service::ParsePriority}},
685 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
686 {"oneshot", {0, 0, &Service::ParseOneshot}},
687 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Steven Moreland6f5333a2017-11-13 15:31:54 -0800688 {"override", {0, 0, &Service::ParseOverride}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700689 {"oom_score_adjust",
690 {1, 1, &Service::ParseOomScoreAdjust}},
Robert Benead4852262017-07-16 19:38:11 -0700691 {"memcg.swappiness",
692 {1, 1, &Service::ParseMemcgSwappiness}},
693 {"memcg.soft_limit_in_bytes",
694 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
695 {"memcg.limit_in_bytes",
696 {1, 1, &Service::ParseMemcgLimitInBytes}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400697 {"namespace", {1, 2, &Service::ParseNamespace}},
Tom Cherry7ac013d2017-08-25 10:39:25 -0700698 {"rlimit", {3, 3, &Service::ParseProcessRlimit}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400699 {"seclabel", {1, 1, &Service::ParseSeclabel}},
700 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700701 {"shutdown", {1, 1, &Service::ParseShutdown}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400702 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn978fd0e2016-12-02 08:05:22 -0800703 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400704 {"user", {1, 1, &Service::ParseUser}},
705 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700706 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700707 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400708 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700709}
710
Tom Cherry89bcc852017-08-02 17:01:36 -0700711Result<Success> Service::ParseLine(const std::vector<std::string>& args) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400712 static const OptionParserMap parser_map;
Tom Cherry89bcc852017-08-02 17:01:36 -0700713 auto parser = parser_map.FindFunction(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700714
Tom Cherry76af7e62017-08-22 16:13:59 -0700715 if (!parser) return parser.error();
Tom Cherryb7349902015-08-26 11:43:36 -0700716
Tom Cherry89bcc852017-08-02 17:01:36 -0700717 return std::invoke(*parser, this, args);
Tom Cherryb7349902015-08-26 11:43:36 -0700718}
719
Tom Cherry76af7e62017-08-22 16:13:59 -0700720Result<Success> Service::ExecStart() {
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700721 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700722
Tom Cherry76af7e62017-08-22 16:13:59 -0700723 if (auto result = Start(); !result) {
724 return result;
Tom Cherryb27004a2017-03-27 16:27:30 -0700725 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700726
727 flags_ |= SVC_EXEC;
728 is_exec_service_running_ = true;
729
730 LOG(INFO) << "SVC_EXEC pid " << pid_ << " (uid " << uid_ << " gid " << gid_ << "+"
731 << supp_gids_.size() << " context " << (!seclabel_.empty() ? seclabel_ : "default")
732 << ") started; waiting...";
733
Tom Cherry76af7e62017-08-22 16:13:59 -0700734 return Success();
Tom Cherryb27004a2017-03-27 16:27:30 -0700735}
736
Tom Cherry76af7e62017-08-22 16:13:59 -0700737Result<Success> Service::Start() {
Tao Wu990d43c2017-10-26 10:43:10 -0700738 bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
Tom Cherrybac32992015-07-31 12:45:25 -0700739 // Starting a service removes it from the disabled or reset state and
740 // immediately takes it out of the restarting state if it was in there.
741 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700742
743 // Running processes require no additional work --- if they're in the
744 // process of exiting, we've ensured that they will immediately restart
Tao Wu990d43c2017-10-26 10:43:10 -0700745 // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
746 // stopping status, we just set SVC_RESTART flag so it will get restarted
747 // in Reap().
Tom Cherrybac32992015-07-31 12:45:25 -0700748 if (flags_ & SVC_RUNNING) {
Tao Wu990d43c2017-10-26 10:43:10 -0700749 if ((flags_ & SVC_ONESHOT) && disabled) {
750 flags_ |= SVC_RESTART;
751 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700752 // It is not an error to try to start a service that is already running.
753 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700754 }
755
756 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200757 if (needs_console) {
758 if (console_.empty()) {
759 console_ = default_console;
760 }
761
Adrian Salido24ef8602016-12-20 15:52:15 -0800762 // Make sure that open call succeeds to ensure a console driver is
763 // properly registered for the device node
764 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
765 if (console_fd < 0) {
Viorel Suman70daa672016-03-21 10:08:07 +0200766 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700767 return ErrnoError() << "Couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200768 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800769 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700770 }
771
772 struct stat sb;
773 if (stat(args_[0].c_str(), &sb) == -1) {
Tom Cherrybac32992015-07-31 12:45:25 -0700774 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700775 return ErrnoError() << "Cannot find '" << args_[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700776 }
777
Tom Cherrybac32992015-07-31 12:45:25 -0700778 std::string scon;
779 if (!seclabel_.empty()) {
780 scon = seclabel_;
781 } else {
Tom Cherry76af7e62017-08-22 16:13:59 -0700782 auto result = ComputeContextFromExecutable(name_, args_[0]);
783 if (!result) {
784 return result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700785 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700786 scon = *result;
Tom Cherrybac32992015-07-31 12:45:25 -0700787 }
788
Wei Wanga285dac2016-10-04 14:05:39 -0700789 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700790
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700791 pid_t pid = -1;
792 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400793 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700794 } else {
795 pid = fork();
796 }
797
Tom Cherrybac32992015-07-31 12:45:25 -0700798 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700799 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700800
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700801 if (namespace_flags_ & CLONE_NEWPID) {
802 // This will fork again to run an init process inside the PID
803 // namespace.
804 SetUpPidNamespace(name_);
805 }
806
Tom Cherry6de21f12017-08-22 15:41:03 -0700807 for (const auto& [key, value] : environment_vars_) {
808 setenv(key.c_str(), value.c_str(), 1);
Tom Cherrybac32992015-07-31 12:45:25 -0700809 }
810
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700811 std::for_each(descriptors_.begin(), descriptors_.end(),
812 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700813
Alex Vakulenko08286762016-05-03 12:00:00 -0700814 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
815 auto cpuset_predicate = [](const std::string& path) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700816 return StartsWith(path, "/dev/cpuset/");
Alex Vakulenko08286762016-05-03 12:00:00 -0700817 };
818 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
819 if (iter == writepid_files_.end()) {
820 // There were no "writepid" instructions for cpusets, check if the system default
821 // cpuset is specified to be used for the process.
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700822 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700823 if (!default_cpuset.empty()) {
824 // Make sure the cpuset name starts and ends with '/'.
825 // A single '/' means the 'root' cpuset.
826 if (default_cpuset.front() != '/') {
827 default_cpuset.insert(0, 1, '/');
828 }
829 if (default_cpuset.back() != '/') {
830 default_cpuset.push_back('/');
831 }
832 writepid_files_.push_back(
833 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
834 }
835 }
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700836 std::string pid_str = std::to_string(getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700837 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700838 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700839 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700840 }
841 }
842
843 if (ioprio_class_ != IoSchedClass_NONE) {
844 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400845 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700846 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700847 }
848 }
849
850 if (needs_console) {
851 setsid();
852 OpenConsole();
853 } else {
854 ZapStdio();
855 }
856
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400857 // As requested, set our gid, supplemental gids, uid, context, and
858 // priority. Aborts on failure.
859 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700860
Tom Cherry5e405ca2017-09-11 16:08:54 -0700861 if (!ExpandArgsAndExecv(args_)) {
862 PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700863 }
864
865 _exit(127);
866 }
867
868 if (pid < 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700869 pid_ = 0;
Tom Cherry76af7e62017-08-22 16:13:59 -0700870 return ErrnoError() << "Failed to fork";
Tom Cherrybac32992015-07-31 12:45:25 -0700871 }
872
Marco Nelissen310f6702016-07-22 12:07:06 -0700873 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700874 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700875 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
876 if (!WriteStringToFile(oom_str, oom_file)) {
877 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
878 }
879 }
880
Elliott Hughes9605a942016-11-10 17:43:47 -0800881 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700882 pid_ = pid;
883 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -0700884 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -0700885 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700886
887 errno = -createProcessGroup(uid_, pid_);
888 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400889 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
890 << name_ << "'";
Robert Benead4852262017-07-16 19:38:11 -0700891 } else {
892 if (swappiness_ != -1) {
893 if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
894 PLOG(ERROR) << "setProcessGroupSwappiness failed";
895 }
896 }
897
898 if (soft_limit_in_bytes_ != -1) {
899 if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
900 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
901 }
902 }
903
904 if (limit_in_bytes_ != -1) {
905 if (!setProcessGroupLimit(uid_, pid_, limit_in_bytes_)) {
906 PLOG(ERROR) << "setProcessGroupLimit failed";
907 }
908 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700909 }
Tom Cherrybac32992015-07-31 12:45:25 -0700910
Tom Cherrybac32992015-07-31 12:45:25 -0700911 NotifyStateChange("running");
Tom Cherry76af7e62017-08-22 16:13:59 -0700912 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700913}
914
Tom Cherry76af7e62017-08-22 16:13:59 -0700915Result<Success> Service::StartIfNotDisabled() {
Tom Cherrybac32992015-07-31 12:45:25 -0700916 if (!(flags_ & SVC_DISABLED)) {
917 return Start();
918 } else {
919 flags_ |= SVC_DISABLED_START;
920 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700921 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700922}
923
Tom Cherry76af7e62017-08-22 16:13:59 -0700924Result<Success> Service::Enable() {
Tom Cherrybac32992015-07-31 12:45:25 -0700925 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
926 if (flags_ & SVC_DISABLED_START) {
927 return Start();
928 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700929 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700930}
931
932void Service::Reset() {
933 StopOrReset(SVC_RESET);
934}
935
936void Service::Stop() {
937 StopOrReset(SVC_DISABLED);
938}
939
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800940void Service::Terminate() {
941 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
942 flags_ |= SVC_DISABLED;
943 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700944 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800945 NotifyStateChange("stopping");
946 }
947}
948
Tom Cherrybac32992015-07-31 12:45:25 -0700949void Service::Restart() {
950 if (flags_ & SVC_RUNNING) {
951 /* Stop, wait, then start the service. */
952 StopOrReset(SVC_RESTART);
953 } else if (!(flags_ & SVC_RESTARTING)) {
954 /* Just start the service since it's not running. */
Tom Cherry76af7e62017-08-22 16:13:59 -0700955 if (auto result = Start(); !result) {
956 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
957 }
Tom Cherrybac32992015-07-31 12:45:25 -0700958 } /* else: Service is restarting anyways. */
959}
960
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700961// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700962void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700963 // The service is still SVC_RUNNING until its process exits, but if it has
964 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700965 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
966
967 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700968 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700969 how = SVC_DISABLED;
970 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700971
972 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700973 if (how == SVC_RESET) {
974 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
975 } else {
976 flags_ |= how;
977 }
Tao Wu84b856d2017-10-27 11:29:13 -0700978 // Make sure it's in right status when a restart immediately follow a
979 // stop/reset or vice versa.
980 if (how == SVC_RESTART) {
981 flags_ &= (~(SVC_DISABLED | SVC_RESET));
982 } else {
983 flags_ &= (~SVC_RESTART);
984 }
Tom Cherrybac32992015-07-31 12:45:25 -0700985
986 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700987 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700988 NotifyStateChange("stopping");
989 } else {
990 NotifyStateChange("stopped");
991 }
992}
993
994void Service::ZapStdio() const {
995 int fd;
996 fd = open("/dev/null", O_RDWR);
997 dup2(fd, 0);
998 dup2(fd, 1);
999 dup2(fd, 2);
1000 close(fd);
1001}
1002
1003void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +02001004 int fd = open(console_.c_str(), O_RDWR);
1005 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -07001006 ioctl(fd, TIOCSCTTY, 0);
1007 dup2(fd, 0);
1008 dup2(fd, 1);
1009 dup2(fd, 2);
1010 close(fd);
1011}
1012
Tom Cherry911b9b12017-07-27 16:20:58 -07001013ServiceList::ServiceList() {}
Tom Cherrybac32992015-07-31 12:45:25 -07001014
Tom Cherry911b9b12017-07-27 16:20:58 -07001015ServiceList& ServiceList::GetInstance() {
1016 static ServiceList instance;
Tom Cherrybac32992015-07-31 12:45:25 -07001017 return instance;
1018}
1019
Tom Cherry911b9b12017-07-27 16:20:58 -07001020void ServiceList::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -07001021 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -07001022}
1023
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001024std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -07001025 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
1026 // SECLABEL can be a - to denote default
1027 std::size_t command_arg = 1;
1028 for (std::size_t i = 1; i < args.size(); ++i) {
1029 if (args[i] == "--") {
1030 command_arg = i + 1;
1031 break;
1032 }
1033 }
1034 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001035 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -07001036 return nullptr;
1037 }
1038
1039 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001040 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -07001041 return nullptr;
1042 }
1043 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
1044
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001045 static size_t exec_count = 0;
1046 exec_count++;
1047 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -07001048
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001049 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -04001050 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001051 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001052
1053 std::string seclabel = "";
1054 if (command_arg > 2 && args[1] != "-") {
1055 seclabel = args[1];
1056 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001057 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001058 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001059 uid = DecodeUid(args[2]);
1060 if (!uid) {
1061 LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001062 return nullptr;
1063 }
Tom Cherrybac32992015-07-31 12:45:25 -07001064 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001065 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001066 std::vector<gid_t> supp_gids;
1067 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001068 gid = DecodeUid(args[3]);
1069 if (!gid) {
1070 LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001071 return nullptr;
1072 }
Tom Cherrybac32992015-07-31 12:45:25 -07001073 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
1074 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001075 auto supp_gid = DecodeUid(args[4 + i]);
1076 if (!supp_gid) {
1077 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
1078 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001079 return nullptr;
1080 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001081 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -07001082 }
1083 }
1084
Tom Cherry11a3aee2017-08-03 12:54:07 -07001085 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, no_capabilities,
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001086 namespace_flags, seclabel, nullptr, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001087}
1088
Tom Cherry59383792017-07-26 16:09:09 -07001089// Shutdown services in the opposite order that they were started.
Tom Cherry911b9b12017-07-27 16:20:58 -07001090const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
Tom Cherry59383792017-07-26 16:09:09 -07001091 std::vector<Service*> shutdown_services;
1092 for (const auto& service : services_) {
1093 if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
1094 }
1095 std::sort(shutdown_services.begin(), shutdown_services.end(),
1096 [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
Tom Cherry911b9b12017-07-27 16:20:58 -07001097 return shutdown_services;
Tom Cherry59383792017-07-26 16:09:09 -07001098}
1099
Tom Cherry911b9b12017-07-27 16:20:58 -07001100void ServiceList::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001101 auto svc_it = std::find_if(services_.begin(), services_.end(),
1102 [&svc] (const std::unique_ptr<Service>& s) {
1103 return svc.name() == s->name();
1104 });
1105 if (svc_it == services_.end()) {
1106 return;
1107 }
1108
1109 services_.erase(svc_it);
1110}
1111
Tom Cherry911b9b12017-07-27 16:20:58 -07001112void ServiceList::DumpState() const {
Tom Cherryb7349902015-08-26 11:43:36 -07001113 for (const auto& s : services_) {
1114 s->DumpState();
1115 }
Tom Cherryb7349902015-08-26 11:43:36 -07001116}
1117
Tom Cherry89bcc852017-08-02 17:01:36 -07001118Result<Success> ServiceParser::ParseSection(std::vector<std::string>&& args,
1119 const std::string& filename, int line) {
Tom Cherryb7349902015-08-26 11:43:36 -07001120 if (args.size() < 3) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001121 return Error() << "services must have a name and a program";
Tom Cherryb7349902015-08-26 11:43:36 -07001122 }
1123
1124 const std::string& name = args[1];
1125 if (!IsValidName(name)) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001126 return Error() << "invalid service name '" << name << "'";
Tom Cherryb7349902015-08-26 11:43:36 -07001127 }
1128
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001129 Subcontext* restart_action_subcontext = nullptr;
1130 if (subcontexts_) {
1131 for (auto& subcontext : *subcontexts_) {
Elliott Hughes579e6822017-12-20 09:41:00 -08001132 if (StartsWith(filename, subcontext.path_prefix())) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001133 restart_action_subcontext = &subcontext;
1134 break;
1135 }
1136 }
1137 }
1138
Tom Cherryb7349902015-08-26 11:43:36 -07001139 std::vector<std::string> str_args(args.begin() + 2, args.end());
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001140 service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
Tom Cherry89bcc852017-08-02 17:01:36 -07001141 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001142}
1143
Tom Cherry89bcc852017-08-02 17:01:36 -07001144Result<Success> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
1145 return service_ ? service_->ParseLine(std::move(args)) : Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001146}
1147
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001148Result<Success> ServiceParser::EndSection() {
Tom Cherryb7349902015-08-26 11:43:36 -07001149 if (service_) {
Steven Moreland5e1bea32017-11-10 14:43:58 -08001150 Service* old_service = service_list_->FindService(service_->name());
1151 if (old_service) {
Steven Moreland6f5333a2017-11-13 15:31:54 -08001152 if (!service_->is_override()) {
1153 return Error() << "ignored duplicate definition of service '" << service_->name()
1154 << "'";
1155 }
1156
1157 service_list_->RemoveService(*old_service);
1158 old_service = nullptr;
Steven Moreland5e1bea32017-11-10 14:43:58 -08001159 }
1160
Tom Cherry911b9b12017-07-27 16:20:58 -07001161 service_list_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001162 }
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001163
1164 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001165}
1166
1167bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001168 // Property names can be any length, but may only contain certain characters.
1169 // Property values can contain any characters, but may only be a certain length.
1170 // (The latter restriction is needed because `start` and `stop` work by writing
1171 // the service name to the "ctl.start" and "ctl.stop" properties.)
Tom Cherryde6bd502018-02-13 16:50:08 -08001172 return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001173}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001174
1175} // namespace init
1176} // namespace android