blob: a4e33f7ecd86cdae48145b097de17fa5f0618868 [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>
Tom Cherryf57c0bf2017-04-07 13:46:21 -070027#include <sys/system_properties.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>
Tom Cherryccf23532017-03-28 16:40:41 -070036#include <android-base/properties.h>
Tom Cherry8d13d802017-06-29 16:18:08 -070037#include <android-base/scopeguard.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080038#include <android-base/stringprintf.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070039#include <android-base/strings.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 Cherrybac32992015-07-31 12:45:25 -070045#include "init.h"
Tom Cherrybac32992015-07-31 12:45:25 -070046#include "property_service.h"
Tom Cherry7ac013d2017-08-25 10:39:25 -070047#include "rlimit_parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070048#include "util.h"
49
James Hawkinse78ea772017-03-24 11:43:02 -070050using android::base::boot_clock;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070051using android::base::GetProperty;
52using android::base::Join;
Tom Cherry8d13d802017-06-29 16:18:08 -070053using android::base::make_scope_guard;
Elliott Hughesda46b392016-10-11 17:09:00 -070054using android::base::ParseInt;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070055using android::base::StartsWith;
Tom Cherryb7349902015-08-26 11:43:36 -070056using android::base::StringPrintf;
57using android::base::WriteStringToFile;
58
Tom Cherry81f5d3e2017-06-22 12:53:17 -070059namespace android {
60namespace init {
61
Tom Cherry76af7e62017-08-22 16:13:59 -070062static Result<std::string> ComputeContextFromExecutable(std::string& service_name,
63 const std::string& service_path) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040064 std::string computed_context;
65
66 char* raw_con = nullptr;
67 char* raw_filecon = nullptr;
68
69 if (getcon(&raw_con) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070070 return Error() << "Could not get security context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040071 }
72 std::unique_ptr<char> mycon(raw_con);
73
74 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070075 return Error() << "Could not get file context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040076 }
77 std::unique_ptr<char> filecon(raw_filecon);
78
79 char* new_con = nullptr;
80 int rc = security_compute_create(mycon.get(), filecon.get(),
81 string_to_security_class("process"), &new_con);
82 if (rc == 0) {
83 computed_context = new_con;
84 free(new_con);
85 }
86 if (rc == 0 && computed_context == mycon.get()) {
Nick Kralevich1ea19eb2017-08-25 12:08:57 -070087 return Error() << "File " << service_path << "(labeled \"" << filecon.get()
88 << "\") has incorrect label or no domain transition from " << mycon.get()
89 << " to another SELinux domain defined. Have you configured your "
90 "service correctly? https://source.android.com/security/selinux/"
91 "device-policy#label_new_services_and_address_denials";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040092 }
93 if (rc < 0) {
Tom Cherry76af7e62017-08-22 16:13:59 -070094 return Error() << "Could not get process context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040095 }
96 return computed_context;
97}
98
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070099static void SetUpPidNamespace(const std::string& service_name) {
100 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
101
102 // It's OK to LOG(FATAL) in this function since it's running in the first
103 // child process.
Joe Tanen4bfdcb32017-10-25 08:07:26 -0400104
105 // Recursively remount / as slave like zygote does so unmounting and mounting /proc
106 // doesn't interfere with the parent namespace's /proc mount. This will also
107 // prevent any other mounts/unmounts initiated by the service from interfering
108 // with the parent namespace but will still allow mount events from the parent
109 // namespace to propagate to the child.
110 if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
111 PLOG(FATAL) << "couldn't remount(/) recursively as slave for " << service_name;
112 }
113 // umount() then mount() /proc.
114 // Note that it is not sufficient to mount with MS_REMOUNT.
115 if (umount("/proc") == -1) {
116 PLOG(FATAL) << "couldn't umount(/proc) for " << service_name;
117 }
118 if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
119 PLOG(FATAL) << "couldn't mount(/proc) for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700120 }
121
122 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700123 PLOG(FATAL) << "couldn't set name for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700124 }
125
126 pid_t child_pid = fork();
127 if (child_pid == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700128 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700129 }
130
131 if (child_pid > 0) {
132 // So that we exit with the right status.
133 static int init_exitstatus = 0;
134 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
135
136 pid_t waited_pid;
137 int status;
138 while ((waited_pid = wait(&status)) > 0) {
139 // This loop will end when there are no processes left inside the
140 // PID namespace or when the init process inside the PID namespace
141 // gets a signal.
142 if (waited_pid == child_pid) {
143 init_exitstatus = status;
144 }
145 }
146 if (!WIFEXITED(init_exitstatus)) {
147 _exit(EXIT_FAILURE);
148 }
149 _exit(WEXITSTATUS(init_exitstatus));
150 }
151}
152
Tom Cherry5e405ca2017-09-11 16:08:54 -0700153static bool ExpandArgsAndExecv(const std::vector<std::string>& args) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400154 std::vector<std::string> expanded_args;
Tom Cherry5e405ca2017-09-11 16:08:54 -0700155 std::vector<char*> c_strings;
156
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400157 expanded_args.resize(args.size());
Tom Cherry5e405ca2017-09-11 16:08:54 -0700158 c_strings.push_back(const_cast<char*>(args[0].data()));
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400159 for (std::size_t i = 1; i < args.size(); ++i) {
160 if (!expand_props(args[i], &expanded_args[i])) {
161 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
162 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700163 c_strings.push_back(expanded_args[i].data());
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400164 }
Tom Cherry5e405ca2017-09-11 16:08:54 -0700165 c_strings.push_back(nullptr);
166
167 return execv(c_strings[0], c_strings.data()) == 0;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400168}
169
Tom Cherry59383792017-07-26 16:09:09 -0700170unsigned long Service::next_start_order_ = 1;
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700171bool Service::is_exec_service_running_ = false;
Tom Cherry59383792017-07-26 16:09:09 -0700172
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700173Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
174 const std::vector<std::string>& args)
175 : Service(name, 0, 0, 0, {}, 0, 0, "", subcontext_for_restart_commands, args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700176
Wei Wang641ff0a2017-03-27 10:59:11 -0700177Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
178 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
179 unsigned namespace_flags, const std::string& seclabel,
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700180 Subcontext* subcontext_for_restart_commands, const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700181 : name_(name),
182 classnames_({"default"}),
183 flags_(flags),
184 pid_(0),
185 crash_count_(0),
186 uid_(uid),
187 gid_(gid),
188 supp_gids_(supp_gids),
189 capabilities_(capabilities),
190 namespace_flags_(namespace_flags),
191 seclabel_(seclabel),
Tom Cherrycb0f9bb2017-09-12 15:58:47 -0700192 onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0),
Tom Cherry7da54852017-05-01 14:16:41 -0700193 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700194 ioprio_class_(IoSchedClass_NONE),
195 ioprio_pri_(0),
196 priority_(0),
197 oom_score_adjust_(-1000),
Robert Benead4852262017-07-16 19:38:11 -0700198 swappiness_(-1),
199 soft_limit_in_bytes_(-1),
200 limit_in_bytes_(-1),
Tom Cherry59383792017-07-26 16:09:09 -0700201 start_order_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700202 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700203 onrestart_.InitSingleTrigger("onrestart");
204}
205
206void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700207 if ((flags_ & SVC_TEMPORARY) != 0) {
208 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700209 return;
210 }
211
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700212 std::string prop_name = "init.svc." + name_;
213 property_set(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800214
215 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800216 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherryfed33732017-08-18 10:47:46 -0700217 std::string boottime_property = "ro.boottime." + name_;
218 if (GetProperty(boottime_property, "").empty()) {
219 property_set(boottime_property, std::to_string(start_ns));
220 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800221 }
Tom Cherrybac32992015-07-31 12:45:25 -0700222}
223
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700224void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700225 // If we've already seen a successful result from killProcessGroup*(), then we have removed
226 // the cgroup already and calling these functions a second time will simply result in an error.
227 // This is true regardless of which signal was sent.
228 // These functions handle their own logging, so no additional logging is needed.
229 if (!process_cgroup_empty_) {
230 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
231 << ") process group...";
232 int r;
233 if (signal == SIGTERM) {
234 r = killProcessGroupOnce(uid_, pid_, signal);
235 } else {
236 r = killProcessGroup(uid_, pid_, signal);
237 }
238
239 if (r == 0) process_cgroup_empty_ = true;
240 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700241}
242
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400243void Service::SetProcessAttributes() {
Tom Cherry7ac013d2017-08-25 10:39:25 -0700244 for (const auto& rlimit : rlimits_) {
245 if (setrlimit(rlimit.first, &rlimit.second) == -1) {
246 LOG(FATAL) << StringPrintf("setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed",
247 rlimit.first, rlimit.second.rlim_cur, rlimit.second.rlim_max);
248 }
249 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400250 // Keep capabilites on uid change.
251 if (capabilities_.any() && uid_) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700252 // If Android is running in a container, some securebits might already
253 // be locked, so don't change those.
Ben Fennemaa7243602017-07-25 14:37:21 -0700254 unsigned long securebits = prctl(PR_GET_SECUREBITS);
255 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700256 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
257 }
258 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
259 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
260 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400261 }
262 }
263
Elliott Hughese18e7e52016-07-25 18:18:16 -0700264 // TODO: work out why this fails for `console` then upgrade to FATAL.
265 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400266
267 if (gid_) {
268 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700269 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400270 }
271 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700272 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
273 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400274 }
275 if (uid_) {
276 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700277 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400278 }
279 }
280 if (!seclabel_.empty()) {
281 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700282 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400283 }
284 }
285 if (priority_ != 0) {
286 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700287 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400288 }
289 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400290 if (capabilities_.any()) {
291 if (!SetCapsForExec(capabilities_)) {
292 LOG(FATAL) << "cannot set capabilities for " << name_;
293 }
Luis Hector Chavez94fb5b02017-11-16 15:52:00 -0800294 } else if (uid_) {
295 // Inheritable caps can be non-zero when running in a container.
296 if (!DropInheritableCaps()) {
297 LOG(FATAL) << "cannot drop inheritable caps for " << name_;
298 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400299 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400300}
301
Tom Cherryb27004a2017-03-27 16:27:30 -0700302void Service::Reap() {
Tom Cherrybac32992015-07-31 12:45:25 -0700303 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700304 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700305 }
306
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700307 // Remove any descriptor resources we may have created.
308 std::for_each(descriptors_.begin(), descriptors_.end(),
309 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700310
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700311 if (flags_ & SVC_EXEC) UnSetExec();
312
313 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700314
315 pid_ = 0;
316 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700317 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700318
319 // Oneshot processes go into the disabled state on exit,
320 // except when manually restarted.
321 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
322 flags_ |= SVC_DISABLED;
323 }
324
325 // Disabled and reset processes do not get restarted automatically.
326 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
327 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700328 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700329 }
330
Elliott Hughes9605a942016-11-10 17:43:47 -0800331 // If we crash > 4 times in 4 minutes, reboot into recovery.
332 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700333 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800334 if (now < time_crashed_ + 4min) {
335 if (++crash_count_ > 4) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700336 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
Tom Cherrybac32992015-07-31 12:45:25 -0700337 }
338 } else {
339 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800340 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700341 }
342 }
343
344 flags_ &= (~SVC_RESTART);
345 flags_ |= SVC_RESTARTING;
346
347 // Execute all onrestart commands for this service.
348 onrestart_.ExecuteAllCommands();
349
350 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700351 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700352}
353
354void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700355 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700356 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
357 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700358 std::for_each(descriptors_.begin(), descriptors_.end(),
359 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700360}
361
Tom Cherry89bcc852017-08-02 17:01:36 -0700362Result<Success> Service::ParseCapabilities(const std::vector<std::string>& args) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400363 capabilities_ = 0;
364
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500365 if (!CapAmbientSupported()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700366 return Error()
367 << "capabilities requested but the kernel does not support ambient capabilities";
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500368 }
369
370 unsigned int last_valid_cap = GetLastValidCap();
371 if (last_valid_cap >= capabilities_.size()) {
372 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
373 }
374
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400375 for (size_t i = 1; i < args.size(); i++) {
376 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500377 int res = LookupCap(arg);
378 if (res < 0) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700379 return Error() << StringPrintf("invalid capability '%s'", arg.c_str());
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400380 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500381 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
382 if (cap > last_valid_cap) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700383 return Error() << StringPrintf("capability '%s' not supported by the kernel",
384 arg.c_str());
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500385 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400386 capabilities_[cap] = true;
387 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700388 return Success();
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400389}
390
Tom Cherry89bcc852017-08-02 17:01:36 -0700391Result<Success> Service::ParseClass(const std::vector<std::string>& args) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700392 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700393 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700394}
Tom Cherrybac32992015-07-31 12:45:25 -0700395
Tom Cherry89bcc852017-08-02 17:01:36 -0700396Result<Success> Service::ParseConsole(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700397 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200398 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherry89bcc852017-08-02 17:01:36 -0700399 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700400}
Tom Cherrybac32992015-07-31 12:45:25 -0700401
Tom Cherry89bcc852017-08-02 17:01:36 -0700402Result<Success> Service::ParseCritical(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700403 flags_ |= SVC_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700404 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700405}
Tom Cherrybac32992015-07-31 12:45:25 -0700406
Tom Cherry89bcc852017-08-02 17:01:36 -0700407Result<Success> Service::ParseDisabled(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700408 flags_ |= SVC_DISABLED;
409 flags_ |= SVC_RC_DISABLED;
Tom Cherry89bcc852017-08-02 17:01:36 -0700410 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700411}
Tom Cherrybac32992015-07-31 12:45:25 -0700412
Tom Cherry89bcc852017-08-02 17:01:36 -0700413Result<Success> Service::ParseGroup(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700414 auto gid = DecodeUid(args[1]);
415 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700416 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700417 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700418 gid_ = *gid;
419
Tom Cherryb7349902015-08-26 11:43:36 -0700420 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700421 gid = DecodeUid(args[n]);
422 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700423 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700424 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700425 supp_gids_.emplace_back(*gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700426 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700427 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700428}
429
Tom Cherry89bcc852017-08-02 17:01:36 -0700430Result<Success> Service::ParsePriority(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700431 priority_ = 0;
432 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800433 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
434 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700435 return Error() << StringPrintf("process priority value must be range %d - %d",
436 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700437 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700438 return Success();
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700439}
440
Steven Morelande055d732017-10-05 18:50:22 -0700441Result<Success> Service::ParseInterface(const std::vector<std::string>& args) {
442 const std::string& interface_name = args[1];
443 const std::string& instance_name = args[2];
444
445 const FQName fq_name = FQName(interface_name);
446 if (!fq_name.isValid()) {
447 return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
448 }
449
450 if (!fq_name.isFullyQualified()) {
451 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
452 }
453
454 if (fq_name.isValidValueName()) {
455 return Error() << "Interface name must not be a value name '" << interface_name << "'";
456 }
457
458 const std::string fullname = interface_name + "/" + instance_name;
459
460 for (const auto& svc : ServiceList::GetInstance()) {
461 if (svc->interfaces().count(fullname) > 0) {
462 return Error() << "Interface '" << fullname << "' redefined in " << name()
463 << " but is already defined by " << svc->name();
464 }
465 }
466
467 interfaces_.insert(fullname);
468
469 return Success();
470}
471
Tom Cherry89bcc852017-08-02 17:01:36 -0700472Result<Success> Service::ParseIoprio(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700473 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700474 return Error() << "priority value must be range 0 - 7";
Tom Cherryb7349902015-08-26 11:43:36 -0700475 }
476
477 if (args[1] == "rt") {
478 ioprio_class_ = IoSchedClass_RT;
479 } else if (args[1] == "be") {
480 ioprio_class_ = IoSchedClass_BE;
481 } else if (args[1] == "idle") {
482 ioprio_class_ = IoSchedClass_IDLE;
483 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700484 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
Tom Cherryb7349902015-08-26 11:43:36 -0700485 }
486
Tom Cherry89bcc852017-08-02 17:01:36 -0700487 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700488}
489
Tom Cherry89bcc852017-08-02 17:01:36 -0700490Result<Success> Service::ParseKeycodes(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700491 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700492 int code;
493 if (ParseInt(args[i], &code)) {
494 keycodes_.emplace_back(code);
495 } else {
496 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
497 }
Tom Cherryb7349902015-08-26 11:43:36 -0700498 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700499 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700500}
501
Tom Cherry89bcc852017-08-02 17:01:36 -0700502Result<Success> Service::ParseOneshot(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700503 flags_ |= SVC_ONESHOT;
Tom Cherry89bcc852017-08-02 17:01:36 -0700504 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700505}
506
Tom Cherry89bcc852017-08-02 17:01:36 -0700507Result<Success> Service::ParseOnrestart(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700508 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700509 int line = onrestart_.NumCommands() + 1;
Tom Cherry89bcc852017-08-02 17:01:36 -0700510 if (auto result = onrestart_.AddCommand(str_args, line); !result) {
511 return Error() << "cannot add Onrestart command: " << result.error();
512 }
513 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700514}
515
Tom Cherry89bcc852017-08-02 17:01:36 -0700516Result<Success> Service::ParseNamespace(const std::vector<std::string>& args) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700517 for (size_t i = 1; i < args.size(); i++) {
518 if (args[i] == "pid") {
519 namespace_flags_ |= CLONE_NEWPID;
520 // PID namespaces require mount namespaces.
521 namespace_flags_ |= CLONE_NEWNS;
522 } else if (args[i] == "mnt") {
523 namespace_flags_ |= CLONE_NEWNS;
524 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700525 return Error() << "namespace must be 'pid' or 'mnt'";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700526 }
527 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700528 return Success();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700529}
530
Tom Cherry89bcc852017-08-02 17:01:36 -0700531Result<Success> Service::ParseOomScoreAdjust(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700532 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700533 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
Marco Nelissen310f6702016-07-22 12:07:06 -0700534 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700535 return Success();
Marco Nelissen310f6702016-07-22 12:07:06 -0700536}
537
Steven Moreland6f5333a2017-11-13 15:31:54 -0800538Result<Success> Service::ParseOverride(const std::vector<std::string>& args) {
539 override_ = true;
540 return Success();
541}
542
Tom Cherry89bcc852017-08-02 17:01:36 -0700543Result<Success> Service::ParseMemcgSwappiness(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700544 if (!ParseInt(args[1], &swappiness_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700545 return Error() << "swappiness value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700546 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700547 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700548}
549
Tom Cherry89bcc852017-08-02 17:01:36 -0700550Result<Success> Service::ParseMemcgLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700551 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700552 return Error() << "limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700553 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700554 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700555}
556
Tom Cherry89bcc852017-08-02 17:01:36 -0700557Result<Success> Service::ParseMemcgSoftLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700558 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700559 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700560 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700561 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700562}
563
Tom Cherry7ac013d2017-08-25 10:39:25 -0700564Result<Success> Service::ParseProcessRlimit(const std::vector<std::string>& args) {
565 auto rlimit = ParseRlimit(args);
566 if (!rlimit) return rlimit.error();
567
568 rlimits_.emplace_back(*rlimit);
569 return Success();
570}
571
Tom Cherry89bcc852017-08-02 17:01:36 -0700572Result<Success> Service::ParseSeclabel(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700573 seclabel_ = args[1];
Tom Cherry89bcc852017-08-02 17:01:36 -0700574 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700575}
576
Tom Cherry89bcc852017-08-02 17:01:36 -0700577Result<Success> Service::ParseSetenv(const std::vector<std::string>& args) {
Tom Cherry6de21f12017-08-22 15:41:03 -0700578 environment_vars_.emplace_back(args[1], args[2]);
Tom Cherry89bcc852017-08-02 17:01:36 -0700579 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700580}
581
Tom Cherry89bcc852017-08-02 17:01:36 -0700582Result<Success> Service::ParseShutdown(const std::vector<std::string>& args) {
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700583 if (args[1] == "critical") {
584 flags_ |= SVC_SHUTDOWN_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700585 return Success();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700586 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700587 return Error() << "Invalid shutdown option";
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700588}
589
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700590template <typename T>
Tom Cherry89bcc852017-08-02 17:01:36 -0700591Result<Success> Service::AddDescriptor(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700592 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700593 Result<uid_t> uid = 0;
594 Result<gid_t> gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700595 std::string context = args.size() > 6 ? args[6] : "";
596
Tom Cherry517e1f12017-05-04 17:40:33 -0700597 if (args.size() > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700598 uid = DecodeUid(args[4]);
599 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700600 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700601 }
602 }
603
604 if (args.size() > 5) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700605 gid = DecodeUid(args[5]);
606 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700607 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700608 }
609 }
610
Tom Cherry11a3aee2017-08-03 12:54:07 -0700611 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700612
613 auto old =
614 std::find_if(descriptors_.begin(), descriptors_.end(),
615 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
616
617 if (old != descriptors_.end()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700618 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700619 }
620
621 descriptors_.emplace_back(std::move(descriptor));
Tom Cherry89bcc852017-08-02 17:01:36 -0700622 return Success();
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700623}
624
625// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700626Result<Success> Service::ParseSocket(const std::vector<std::string>& args) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700627 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
628 !StartsWith(args[2], "seqpacket")) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700629 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
Tom Cherryb7349902015-08-26 11:43:36 -0700630 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700631 return AddDescriptor<SocketInfo>(args);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700632}
Tom Cherryb7349902015-08-26 11:43:36 -0700633
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700634// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700635Result<Success> Service::ParseFile(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700636 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
Tom Cherry89bcc852017-08-02 17:01:36 -0700637 return Error() << "file type must be 'r', 'w' or 'rw'";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700638 }
639 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700640 return Error() << "file name must not be relative";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700641 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700642 return AddDescriptor<FileInfo>(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700643}
644
Tom Cherry89bcc852017-08-02 17:01:36 -0700645Result<Success> Service::ParseUser(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700646 auto uid = DecodeUid(args[1]);
647 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700648 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700649 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700650 uid_ = *uid;
Tom Cherry89bcc852017-08-02 17:01:36 -0700651 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700652}
653
Tom Cherry89bcc852017-08-02 17:01:36 -0700654Result<Success> Service::ParseWritepid(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700655 writepid_files_.assign(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700656 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700657}
658
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400659class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700660 public:
661 OptionParserMap() {}
662
663 private:
664 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700665};
666
Tom Cherryad54d092017-04-19 16:18:50 -0700667const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700668 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700669 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400670 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400671 {"capabilities",
672 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700673 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400674 {"console", {0, 1, &Service::ParseConsole}},
675 {"critical", {0, 0, &Service::ParseCritical}},
676 {"disabled", {0, 0, &Service::ParseDisabled}},
677 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
Steven Morelande055d732017-10-05 18:50:22 -0700678 {"interface", {2, 2, &Service::ParseInterface}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400679 {"ioprio", {2, 2, &Service::ParseIoprio}},
680 {"priority", {1, 1, &Service::ParsePriority}},
681 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
682 {"oneshot", {0, 0, &Service::ParseOneshot}},
683 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Steven Moreland6f5333a2017-11-13 15:31:54 -0800684 {"override", {0, 0, &Service::ParseOverride}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700685 {"oom_score_adjust",
686 {1, 1, &Service::ParseOomScoreAdjust}},
Robert Benead4852262017-07-16 19:38:11 -0700687 {"memcg.swappiness",
688 {1, 1, &Service::ParseMemcgSwappiness}},
689 {"memcg.soft_limit_in_bytes",
690 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
691 {"memcg.limit_in_bytes",
692 {1, 1, &Service::ParseMemcgLimitInBytes}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400693 {"namespace", {1, 2, &Service::ParseNamespace}},
Tom Cherry7ac013d2017-08-25 10:39:25 -0700694 {"rlimit", {3, 3, &Service::ParseProcessRlimit}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400695 {"seclabel", {1, 1, &Service::ParseSeclabel}},
696 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700697 {"shutdown", {1, 1, &Service::ParseShutdown}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400698 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn978fd0e2016-12-02 08:05:22 -0800699 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400700 {"user", {1, 1, &Service::ParseUser}},
701 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700702 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700703 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400704 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700705}
706
Tom Cherry89bcc852017-08-02 17:01:36 -0700707Result<Success> Service::ParseLine(const std::vector<std::string>& args) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400708 static const OptionParserMap parser_map;
Tom Cherry89bcc852017-08-02 17:01:36 -0700709 auto parser = parser_map.FindFunction(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700710
Tom Cherry76af7e62017-08-22 16:13:59 -0700711 if (!parser) return parser.error();
Tom Cherryb7349902015-08-26 11:43:36 -0700712
Tom Cherry89bcc852017-08-02 17:01:36 -0700713 return std::invoke(*parser, this, args);
Tom Cherryb7349902015-08-26 11:43:36 -0700714}
715
Tom Cherry76af7e62017-08-22 16:13:59 -0700716Result<Success> Service::ExecStart() {
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700717 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700718
Tom Cherry76af7e62017-08-22 16:13:59 -0700719 if (auto result = Start(); !result) {
720 return result;
Tom Cherryb27004a2017-03-27 16:27:30 -0700721 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700722
723 flags_ |= SVC_EXEC;
724 is_exec_service_running_ = true;
725
726 LOG(INFO) << "SVC_EXEC pid " << pid_ << " (uid " << uid_ << " gid " << gid_ << "+"
727 << supp_gids_.size() << " context " << (!seclabel_.empty() ? seclabel_ : "default")
728 << ") started; waiting...";
729
Tom Cherry76af7e62017-08-22 16:13:59 -0700730 return Success();
Tom Cherryb27004a2017-03-27 16:27:30 -0700731}
732
Tom Cherry76af7e62017-08-22 16:13:59 -0700733Result<Success> Service::Start() {
Tao Wu990d43c2017-10-26 10:43:10 -0700734 bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
Tom Cherrybac32992015-07-31 12:45:25 -0700735 // Starting a service removes it from the disabled or reset state and
736 // immediately takes it out of the restarting state if it was in there.
737 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700738
739 // Running processes require no additional work --- if they're in the
740 // process of exiting, we've ensured that they will immediately restart
Tao Wu990d43c2017-10-26 10:43:10 -0700741 // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
742 // stopping status, we just set SVC_RESTART flag so it will get restarted
743 // in Reap().
Tom Cherrybac32992015-07-31 12:45:25 -0700744 if (flags_ & SVC_RUNNING) {
Tao Wu990d43c2017-10-26 10:43:10 -0700745 if ((flags_ & SVC_ONESHOT) && disabled) {
746 flags_ |= SVC_RESTART;
747 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700748 // It is not an error to try to start a service that is already running.
749 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700750 }
751
752 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200753 if (needs_console) {
754 if (console_.empty()) {
755 console_ = default_console;
756 }
757
Adrian Salido24ef8602016-12-20 15:52:15 -0800758 // Make sure that open call succeeds to ensure a console driver is
759 // properly registered for the device node
760 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
761 if (console_fd < 0) {
Viorel Suman70daa672016-03-21 10:08:07 +0200762 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700763 return ErrnoError() << "Couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200764 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800765 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700766 }
767
768 struct stat sb;
769 if (stat(args_[0].c_str(), &sb) == -1) {
Tom Cherrybac32992015-07-31 12:45:25 -0700770 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700771 return ErrnoError() << "Cannot find '" << args_[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700772 }
773
Tom Cherrybac32992015-07-31 12:45:25 -0700774 std::string scon;
775 if (!seclabel_.empty()) {
776 scon = seclabel_;
777 } else {
Tom Cherry76af7e62017-08-22 16:13:59 -0700778 auto result = ComputeContextFromExecutable(name_, args_[0]);
779 if (!result) {
780 return result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700781 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700782 scon = *result;
Tom Cherrybac32992015-07-31 12:45:25 -0700783 }
784
Wei Wanga285dac2016-10-04 14:05:39 -0700785 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700786
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700787 pid_t pid = -1;
788 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400789 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700790 } else {
791 pid = fork();
792 }
793
Tom Cherrybac32992015-07-31 12:45:25 -0700794 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700795 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700796
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700797 if (namespace_flags_ & CLONE_NEWPID) {
798 // This will fork again to run an init process inside the PID
799 // namespace.
800 SetUpPidNamespace(name_);
801 }
802
Tom Cherry6de21f12017-08-22 15:41:03 -0700803 for (const auto& [key, value] : environment_vars_) {
804 setenv(key.c_str(), value.c_str(), 1);
Tom Cherrybac32992015-07-31 12:45:25 -0700805 }
806
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700807 std::for_each(descriptors_.begin(), descriptors_.end(),
808 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700809
Alex Vakulenko08286762016-05-03 12:00:00 -0700810 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
811 auto cpuset_predicate = [](const std::string& path) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700812 return StartsWith(path, "/dev/cpuset/");
Alex Vakulenko08286762016-05-03 12:00:00 -0700813 };
814 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
815 if (iter == writepid_files_.end()) {
816 // There were no "writepid" instructions for cpusets, check if the system default
817 // cpuset is specified to be used for the process.
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700818 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700819 if (!default_cpuset.empty()) {
820 // Make sure the cpuset name starts and ends with '/'.
821 // A single '/' means the 'root' cpuset.
822 if (default_cpuset.front() != '/') {
823 default_cpuset.insert(0, 1, '/');
824 }
825 if (default_cpuset.back() != '/') {
826 default_cpuset.push_back('/');
827 }
828 writepid_files_.push_back(
829 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
830 }
831 }
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700832 std::string pid_str = std::to_string(getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700833 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700834 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700835 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700836 }
837 }
838
839 if (ioprio_class_ != IoSchedClass_NONE) {
840 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400841 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700842 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700843 }
844 }
845
846 if (needs_console) {
847 setsid();
848 OpenConsole();
849 } else {
850 ZapStdio();
851 }
852
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400853 // As requested, set our gid, supplemental gids, uid, context, and
854 // priority. Aborts on failure.
855 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700856
Tom Cherry5e405ca2017-09-11 16:08:54 -0700857 if (!ExpandArgsAndExecv(args_)) {
858 PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700859 }
860
861 _exit(127);
862 }
863
864 if (pid < 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700865 pid_ = 0;
Tom Cherry76af7e62017-08-22 16:13:59 -0700866 return ErrnoError() << "Failed to fork";
Tom Cherrybac32992015-07-31 12:45:25 -0700867 }
868
Marco Nelissen310f6702016-07-22 12:07:06 -0700869 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700870 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700871 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
872 if (!WriteStringToFile(oom_str, oom_file)) {
873 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
874 }
875 }
876
Elliott Hughes9605a942016-11-10 17:43:47 -0800877 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700878 pid_ = pid;
879 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -0700880 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -0700881 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700882
883 errno = -createProcessGroup(uid_, pid_);
884 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400885 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
886 << name_ << "'";
Robert Benead4852262017-07-16 19:38:11 -0700887 } else {
888 if (swappiness_ != -1) {
889 if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
890 PLOG(ERROR) << "setProcessGroupSwappiness failed";
891 }
892 }
893
894 if (soft_limit_in_bytes_ != -1) {
895 if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
896 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
897 }
898 }
899
900 if (limit_in_bytes_ != -1) {
901 if (!setProcessGroupLimit(uid_, pid_, limit_in_bytes_)) {
902 PLOG(ERROR) << "setProcessGroupLimit failed";
903 }
904 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700905 }
Tom Cherrybac32992015-07-31 12:45:25 -0700906
Tom Cherrybac32992015-07-31 12:45:25 -0700907 NotifyStateChange("running");
Tom Cherry76af7e62017-08-22 16:13:59 -0700908 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700909}
910
Tom Cherry76af7e62017-08-22 16:13:59 -0700911Result<Success> Service::StartIfNotDisabled() {
Tom Cherrybac32992015-07-31 12:45:25 -0700912 if (!(flags_ & SVC_DISABLED)) {
913 return Start();
914 } else {
915 flags_ |= SVC_DISABLED_START;
916 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700917 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700918}
919
Tom Cherry76af7e62017-08-22 16:13:59 -0700920Result<Success> Service::Enable() {
Tom Cherrybac32992015-07-31 12:45:25 -0700921 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
922 if (flags_ & SVC_DISABLED_START) {
923 return Start();
924 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700925 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700926}
927
928void Service::Reset() {
929 StopOrReset(SVC_RESET);
930}
931
932void Service::Stop() {
933 StopOrReset(SVC_DISABLED);
934}
935
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800936void Service::Terminate() {
937 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
938 flags_ |= SVC_DISABLED;
939 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700940 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800941 NotifyStateChange("stopping");
942 }
943}
944
Tom Cherrybac32992015-07-31 12:45:25 -0700945void Service::Restart() {
946 if (flags_ & SVC_RUNNING) {
947 /* Stop, wait, then start the service. */
948 StopOrReset(SVC_RESTART);
949 } else if (!(flags_ & SVC_RESTARTING)) {
950 /* Just start the service since it's not running. */
Tom Cherry76af7e62017-08-22 16:13:59 -0700951 if (auto result = Start(); !result) {
952 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
953 }
Tom Cherrybac32992015-07-31 12:45:25 -0700954 } /* else: Service is restarting anyways. */
955}
956
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700957// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700958void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700959 // The service is still SVC_RUNNING until its process exits, but if it has
960 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700961 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
962
963 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700964 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700965 how = SVC_DISABLED;
966 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700967
968 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700969 if (how == SVC_RESET) {
970 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
971 } else {
972 flags_ |= how;
973 }
Tao Wu84b856d2017-10-27 11:29:13 -0700974 // Make sure it's in right status when a restart immediately follow a
975 // stop/reset or vice versa.
976 if (how == SVC_RESTART) {
977 flags_ &= (~(SVC_DISABLED | SVC_RESET));
978 } else {
979 flags_ &= (~SVC_RESTART);
980 }
Tom Cherrybac32992015-07-31 12:45:25 -0700981
982 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700983 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700984 NotifyStateChange("stopping");
985 } else {
986 NotifyStateChange("stopped");
987 }
988}
989
990void Service::ZapStdio() const {
991 int fd;
992 fd = open("/dev/null", O_RDWR);
993 dup2(fd, 0);
994 dup2(fd, 1);
995 dup2(fd, 2);
996 close(fd);
997}
998
999void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +02001000 int fd = open(console_.c_str(), O_RDWR);
1001 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -07001002 ioctl(fd, TIOCSCTTY, 0);
1003 dup2(fd, 0);
1004 dup2(fd, 1);
1005 dup2(fd, 2);
1006 close(fd);
1007}
1008
Tom Cherry911b9b12017-07-27 16:20:58 -07001009ServiceList::ServiceList() {}
Tom Cherrybac32992015-07-31 12:45:25 -07001010
Tom Cherry911b9b12017-07-27 16:20:58 -07001011ServiceList& ServiceList::GetInstance() {
1012 static ServiceList instance;
Tom Cherrybac32992015-07-31 12:45:25 -07001013 return instance;
1014}
1015
Tom Cherry911b9b12017-07-27 16:20:58 -07001016void ServiceList::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -07001017 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -07001018}
1019
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001020std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -07001021 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
1022 // SECLABEL can be a - to denote default
1023 std::size_t command_arg = 1;
1024 for (std::size_t i = 1; i < args.size(); ++i) {
1025 if (args[i] == "--") {
1026 command_arg = i + 1;
1027 break;
1028 }
1029 }
1030 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001031 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -07001032 return nullptr;
1033 }
1034
1035 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001036 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -07001037 return nullptr;
1038 }
1039 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
1040
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001041 static size_t exec_count = 0;
1042 exec_count++;
1043 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -07001044
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001045 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -04001046 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001047 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001048
1049 std::string seclabel = "";
1050 if (command_arg > 2 && args[1] != "-") {
1051 seclabel = args[1];
1052 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001053 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001054 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001055 uid = DecodeUid(args[2]);
1056 if (!uid) {
1057 LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001058 return nullptr;
1059 }
Tom Cherrybac32992015-07-31 12:45:25 -07001060 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001061 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001062 std::vector<gid_t> supp_gids;
1063 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001064 gid = DecodeUid(args[3]);
1065 if (!gid) {
1066 LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001067 return nullptr;
1068 }
Tom Cherrybac32992015-07-31 12:45:25 -07001069 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
1070 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001071 auto supp_gid = DecodeUid(args[4 + i]);
1072 if (!supp_gid) {
1073 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
1074 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001075 return nullptr;
1076 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001077 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -07001078 }
1079 }
1080
Tom Cherry11a3aee2017-08-03 12:54:07 -07001081 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, no_capabilities,
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001082 namespace_flags, seclabel, nullptr, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001083}
1084
Tom Cherry59383792017-07-26 16:09:09 -07001085// Shutdown services in the opposite order that they were started.
Tom Cherry911b9b12017-07-27 16:20:58 -07001086const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
Tom Cherry59383792017-07-26 16:09:09 -07001087 std::vector<Service*> shutdown_services;
1088 for (const auto& service : services_) {
1089 if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
1090 }
1091 std::sort(shutdown_services.begin(), shutdown_services.end(),
1092 [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
Tom Cherry911b9b12017-07-27 16:20:58 -07001093 return shutdown_services;
Tom Cherry59383792017-07-26 16:09:09 -07001094}
1095
Tom Cherry911b9b12017-07-27 16:20:58 -07001096void ServiceList::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001097 auto svc_it = std::find_if(services_.begin(), services_.end(),
1098 [&svc] (const std::unique_ptr<Service>& s) {
1099 return svc.name() == s->name();
1100 });
1101 if (svc_it == services_.end()) {
1102 return;
1103 }
1104
1105 services_.erase(svc_it);
1106}
1107
Tom Cherry911b9b12017-07-27 16:20:58 -07001108void ServiceList::DumpState() const {
Tom Cherryb7349902015-08-26 11:43:36 -07001109 for (const auto& s : services_) {
1110 s->DumpState();
1111 }
Tom Cherryb7349902015-08-26 11:43:36 -07001112}
1113
Tom Cherry89bcc852017-08-02 17:01:36 -07001114Result<Success> ServiceParser::ParseSection(std::vector<std::string>&& args,
1115 const std::string& filename, int line) {
Tom Cherryb7349902015-08-26 11:43:36 -07001116 if (args.size() < 3) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001117 return Error() << "services must have a name and a program";
Tom Cherryb7349902015-08-26 11:43:36 -07001118 }
1119
1120 const std::string& name = args[1];
1121 if (!IsValidName(name)) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001122 return Error() << "invalid service name '" << name << "'";
Tom Cherryb7349902015-08-26 11:43:36 -07001123 }
1124
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001125 Subcontext* restart_action_subcontext = nullptr;
1126 if (subcontexts_) {
1127 for (auto& subcontext : *subcontexts_) {
Elliott Hughes579e6822017-12-20 09:41:00 -08001128 if (StartsWith(filename, subcontext.path_prefix())) {
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001129 restart_action_subcontext = &subcontext;
1130 break;
1131 }
1132 }
1133 }
1134
Tom Cherryb7349902015-08-26 11:43:36 -07001135 std::vector<std::string> str_args(args.begin() + 2, args.end());
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001136 service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
Tom Cherry89bcc852017-08-02 17:01:36 -07001137 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001138}
1139
Tom Cherry89bcc852017-08-02 17:01:36 -07001140Result<Success> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
1141 return service_ ? service_->ParseLine(std::move(args)) : Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001142}
1143
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001144Result<Success> ServiceParser::EndSection() {
Tom Cherryb7349902015-08-26 11:43:36 -07001145 if (service_) {
Steven Moreland5e1bea32017-11-10 14:43:58 -08001146 Service* old_service = service_list_->FindService(service_->name());
1147 if (old_service) {
Steven Moreland6f5333a2017-11-13 15:31:54 -08001148 if (!service_->is_override()) {
1149 return Error() << "ignored duplicate definition of service '" << service_->name()
1150 << "'";
1151 }
1152
1153 service_list_->RemoveService(*old_service);
1154 old_service = nullptr;
Steven Moreland5e1bea32017-11-10 14:43:58 -08001155 }
1156
Tom Cherry911b9b12017-07-27 16:20:58 -07001157 service_list_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001158 }
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001159
1160 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001161}
1162
1163bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001164 // Property names can be any length, but may only contain certain characters.
1165 // Property values can contain any characters, but may only be a certain length.
1166 // (The latter restriction is needed because `start` and `stop` work by writing
1167 // the service name to the "ctl.start" and "ctl.stop" properties.)
1168 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001169}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001170
1171} // namespace init
1172} // namespace android