blob: 6d48368e0da6e3997671fb18fab62c3f55af0210 [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 }
294 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400295}
296
Tom Cherryb27004a2017-03-27 16:27:30 -0700297void Service::Reap() {
Tom Cherrybac32992015-07-31 12:45:25 -0700298 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700299 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700300 }
301
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700302 // Remove any descriptor resources we may have created.
303 std::for_each(descriptors_.begin(), descriptors_.end(),
304 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700305
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700306 if (flags_ & SVC_EXEC) UnSetExec();
307
308 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700309
310 pid_ = 0;
311 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700312 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700313
314 // Oneshot processes go into the disabled state on exit,
315 // except when manually restarted.
316 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
317 flags_ |= SVC_DISABLED;
318 }
319
320 // Disabled and reset processes do not get restarted automatically.
321 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
322 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700323 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700324 }
325
Elliott Hughes9605a942016-11-10 17:43:47 -0800326 // If we crash > 4 times in 4 minutes, reboot into recovery.
327 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700328 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800329 if (now < time_crashed_ + 4min) {
330 if (++crash_count_ > 4) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700331 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
Tom Cherrybac32992015-07-31 12:45:25 -0700332 }
333 } else {
334 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800335 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700336 }
337 }
338
339 flags_ &= (~SVC_RESTART);
340 flags_ |= SVC_RESTARTING;
341
342 // Execute all onrestart commands for this service.
343 onrestart_.ExecuteAllCommands();
344
345 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700346 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700347}
348
349void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700350 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700351 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
352 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700353 std::for_each(descriptors_.begin(), descriptors_.end(),
354 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700355}
356
Tom Cherry89bcc852017-08-02 17:01:36 -0700357Result<Success> Service::ParseCapabilities(const std::vector<std::string>& args) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400358 capabilities_ = 0;
359
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500360 if (!CapAmbientSupported()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700361 return Error()
362 << "capabilities requested but the kernel does not support ambient capabilities";
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500363 }
364
365 unsigned int last_valid_cap = GetLastValidCap();
366 if (last_valid_cap >= capabilities_.size()) {
367 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
368 }
369
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400370 for (size_t i = 1; i < args.size(); i++) {
371 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500372 int res = LookupCap(arg);
373 if (res < 0) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700374 return Error() << StringPrintf("invalid capability '%s'", arg.c_str());
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400375 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500376 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
377 if (cap > last_valid_cap) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700378 return Error() << StringPrintf("capability '%s' not supported by the kernel",
379 arg.c_str());
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500380 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400381 capabilities_[cap] = true;
382 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700383 return Success();
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400384}
385
Tom Cherry89bcc852017-08-02 17:01:36 -0700386Result<Success> Service::ParseClass(const std::vector<std::string>& args) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700387 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700388 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700389}
Tom Cherrybac32992015-07-31 12:45:25 -0700390
Tom Cherry89bcc852017-08-02 17:01:36 -0700391Result<Success> Service::ParseConsole(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700392 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200393 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherry89bcc852017-08-02 17:01:36 -0700394 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700395}
Tom Cherrybac32992015-07-31 12:45:25 -0700396
Tom Cherry89bcc852017-08-02 17:01:36 -0700397Result<Success> Service::ParseCritical(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700398 flags_ |= SVC_CRITICAL;
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::ParseDisabled(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700403 flags_ |= SVC_DISABLED;
404 flags_ |= SVC_RC_DISABLED;
Tom Cherry89bcc852017-08-02 17:01:36 -0700405 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700406}
Tom Cherrybac32992015-07-31 12:45:25 -0700407
Tom Cherry89bcc852017-08-02 17:01:36 -0700408Result<Success> Service::ParseGroup(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700409 auto gid = DecodeUid(args[1]);
410 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700411 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700412 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700413 gid_ = *gid;
414
Tom Cherryb7349902015-08-26 11:43:36 -0700415 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700416 gid = DecodeUid(args[n]);
417 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700418 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700419 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700420 supp_gids_.emplace_back(*gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700421 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700422 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700423}
424
Tom Cherry89bcc852017-08-02 17:01:36 -0700425Result<Success> Service::ParsePriority(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700426 priority_ = 0;
427 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800428 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
429 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700430 return Error() << StringPrintf("process priority value must be range %d - %d",
431 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700432 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700433 return Success();
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700434}
435
Steven Morelande055d732017-10-05 18:50:22 -0700436Result<Success> Service::ParseInterface(const std::vector<std::string>& args) {
437 const std::string& interface_name = args[1];
438 const std::string& instance_name = args[2];
439
440 const FQName fq_name = FQName(interface_name);
441 if (!fq_name.isValid()) {
442 return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
443 }
444
445 if (!fq_name.isFullyQualified()) {
446 return Error() << "Interface name not fully-qualified '" << interface_name << "'";
447 }
448
449 if (fq_name.isValidValueName()) {
450 return Error() << "Interface name must not be a value name '" << interface_name << "'";
451 }
452
453 const std::string fullname = interface_name + "/" + instance_name;
454
455 for (const auto& svc : ServiceList::GetInstance()) {
456 if (svc->interfaces().count(fullname) > 0) {
457 return Error() << "Interface '" << fullname << "' redefined in " << name()
458 << " but is already defined by " << svc->name();
459 }
460 }
461
462 interfaces_.insert(fullname);
463
464 return Success();
465}
466
Tom Cherry89bcc852017-08-02 17:01:36 -0700467Result<Success> Service::ParseIoprio(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700468 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700469 return Error() << "priority value must be range 0 - 7";
Tom Cherryb7349902015-08-26 11:43:36 -0700470 }
471
472 if (args[1] == "rt") {
473 ioprio_class_ = IoSchedClass_RT;
474 } else if (args[1] == "be") {
475 ioprio_class_ = IoSchedClass_BE;
476 } else if (args[1] == "idle") {
477 ioprio_class_ = IoSchedClass_IDLE;
478 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700479 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
Tom Cherryb7349902015-08-26 11:43:36 -0700480 }
481
Tom Cherry89bcc852017-08-02 17:01:36 -0700482 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700483}
484
Tom Cherry89bcc852017-08-02 17:01:36 -0700485Result<Success> Service::ParseKeycodes(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700486 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700487 int code;
488 if (ParseInt(args[i], &code)) {
489 keycodes_.emplace_back(code);
490 } else {
491 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
492 }
Tom Cherryb7349902015-08-26 11:43:36 -0700493 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700494 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700495}
496
Tom Cherry89bcc852017-08-02 17:01:36 -0700497Result<Success> Service::ParseOneshot(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700498 flags_ |= SVC_ONESHOT;
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::ParseOnrestart(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700503 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700504 int line = onrestart_.NumCommands() + 1;
Tom Cherry89bcc852017-08-02 17:01:36 -0700505 if (auto result = onrestart_.AddCommand(str_args, line); !result) {
506 return Error() << "cannot add Onrestart command: " << result.error();
507 }
508 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700509}
510
Tom Cherry89bcc852017-08-02 17:01:36 -0700511Result<Success> Service::ParseNamespace(const std::vector<std::string>& args) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700512 for (size_t i = 1; i < args.size(); i++) {
513 if (args[i] == "pid") {
514 namespace_flags_ |= CLONE_NEWPID;
515 // PID namespaces require mount namespaces.
516 namespace_flags_ |= CLONE_NEWNS;
517 } else if (args[i] == "mnt") {
518 namespace_flags_ |= CLONE_NEWNS;
519 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700520 return Error() << "namespace must be 'pid' or 'mnt'";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700521 }
522 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700523 return Success();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700524}
525
Tom Cherry89bcc852017-08-02 17:01:36 -0700526Result<Success> Service::ParseOomScoreAdjust(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700527 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700528 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
Marco Nelissen310f6702016-07-22 12:07:06 -0700529 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700530 return Success();
Marco Nelissen310f6702016-07-22 12:07:06 -0700531}
532
Tom Cherry89bcc852017-08-02 17:01:36 -0700533Result<Success> Service::ParseMemcgSwappiness(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700534 if (!ParseInt(args[1], &swappiness_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700535 return Error() << "swappiness value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700536 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700537 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700538}
539
Tom Cherry89bcc852017-08-02 17:01:36 -0700540Result<Success> Service::ParseMemcgLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700541 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700542 return Error() << "limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700543 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700544 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700545}
546
Tom Cherry89bcc852017-08-02 17:01:36 -0700547Result<Success> Service::ParseMemcgSoftLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700548 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700549 return Error() << "soft_limit_in_bytes 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 Cherry7ac013d2017-08-25 10:39:25 -0700554Result<Success> Service::ParseProcessRlimit(const std::vector<std::string>& args) {
555 auto rlimit = ParseRlimit(args);
556 if (!rlimit) return rlimit.error();
557
558 rlimits_.emplace_back(*rlimit);
559 return Success();
560}
561
Tom Cherry89bcc852017-08-02 17:01:36 -0700562Result<Success> Service::ParseSeclabel(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700563 seclabel_ = args[1];
Tom Cherry89bcc852017-08-02 17:01:36 -0700564 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700565}
566
Tom Cherry89bcc852017-08-02 17:01:36 -0700567Result<Success> Service::ParseSetenv(const std::vector<std::string>& args) {
Tom Cherry6de21f12017-08-22 15:41:03 -0700568 environment_vars_.emplace_back(args[1], args[2]);
Tom Cherry89bcc852017-08-02 17:01:36 -0700569 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700570}
571
Tom Cherry89bcc852017-08-02 17:01:36 -0700572Result<Success> Service::ParseShutdown(const std::vector<std::string>& args) {
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700573 if (args[1] == "critical") {
574 flags_ |= SVC_SHUTDOWN_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700575 return Success();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700576 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700577 return Error() << "Invalid shutdown option";
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700578}
579
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700580template <typename T>
Tom Cherry89bcc852017-08-02 17:01:36 -0700581Result<Success> Service::AddDescriptor(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700582 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700583 Result<uid_t> uid = 0;
584 Result<gid_t> gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700585 std::string context = args.size() > 6 ? args[6] : "";
586
Tom Cherry517e1f12017-05-04 17:40:33 -0700587 if (args.size() > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700588 uid = DecodeUid(args[4]);
589 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700590 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700591 }
592 }
593
594 if (args.size() > 5) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700595 gid = DecodeUid(args[5]);
596 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700597 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700598 }
599 }
600
Tom Cherry11a3aee2017-08-03 12:54:07 -0700601 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700602
603 auto old =
604 std::find_if(descriptors_.begin(), descriptors_.end(),
605 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
606
607 if (old != descriptors_.end()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700608 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700609 }
610
611 descriptors_.emplace_back(std::move(descriptor));
Tom Cherry89bcc852017-08-02 17:01:36 -0700612 return Success();
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700613}
614
615// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700616Result<Success> Service::ParseSocket(const std::vector<std::string>& args) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700617 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
618 !StartsWith(args[2], "seqpacket")) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700619 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
Tom Cherryb7349902015-08-26 11:43:36 -0700620 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700621 return AddDescriptor<SocketInfo>(args);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700622}
Tom Cherryb7349902015-08-26 11:43:36 -0700623
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700624// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700625Result<Success> Service::ParseFile(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700626 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
Tom Cherry89bcc852017-08-02 17:01:36 -0700627 return Error() << "file type must be 'r', 'w' or 'rw'";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700628 }
629 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700630 return Error() << "file name must not be relative";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700631 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700632 return AddDescriptor<FileInfo>(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700633}
634
Tom Cherry89bcc852017-08-02 17:01:36 -0700635Result<Success> Service::ParseUser(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700636 auto uid = DecodeUid(args[1]);
637 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700638 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700639 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700640 uid_ = *uid;
Tom Cherry89bcc852017-08-02 17:01:36 -0700641 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700642}
643
Tom Cherry89bcc852017-08-02 17:01:36 -0700644Result<Success> Service::ParseWritepid(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700645 writepid_files_.assign(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700646 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700647}
648
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400649class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700650 public:
651 OptionParserMap() {}
652
653 private:
654 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700655};
656
Tom Cherryad54d092017-04-19 16:18:50 -0700657const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700658 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700659 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400660 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400661 {"capabilities",
662 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700663 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400664 {"console", {0, 1, &Service::ParseConsole}},
665 {"critical", {0, 0, &Service::ParseCritical}},
666 {"disabled", {0, 0, &Service::ParseDisabled}},
667 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
Steven Morelande055d732017-10-05 18:50:22 -0700668 {"interface", {2, 2, &Service::ParseInterface}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400669 {"ioprio", {2, 2, &Service::ParseIoprio}},
670 {"priority", {1, 1, &Service::ParsePriority}},
671 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
672 {"oneshot", {0, 0, &Service::ParseOneshot}},
673 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700674 {"oom_score_adjust",
675 {1, 1, &Service::ParseOomScoreAdjust}},
Robert Benead4852262017-07-16 19:38:11 -0700676 {"memcg.swappiness",
677 {1, 1, &Service::ParseMemcgSwappiness}},
678 {"memcg.soft_limit_in_bytes",
679 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
680 {"memcg.limit_in_bytes",
681 {1, 1, &Service::ParseMemcgLimitInBytes}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400682 {"namespace", {1, 2, &Service::ParseNamespace}},
Tom Cherry7ac013d2017-08-25 10:39:25 -0700683 {"rlimit", {3, 3, &Service::ParseProcessRlimit}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400684 {"seclabel", {1, 1, &Service::ParseSeclabel}},
685 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700686 {"shutdown", {1, 1, &Service::ParseShutdown}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400687 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn978fd0e2016-12-02 08:05:22 -0800688 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400689 {"user", {1, 1, &Service::ParseUser}},
690 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700691 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700692 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400693 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700694}
695
Tom Cherry89bcc852017-08-02 17:01:36 -0700696Result<Success> Service::ParseLine(const std::vector<std::string>& args) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400697 static const OptionParserMap parser_map;
Tom Cherry89bcc852017-08-02 17:01:36 -0700698 auto parser = parser_map.FindFunction(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700699
Tom Cherry76af7e62017-08-22 16:13:59 -0700700 if (!parser) return parser.error();
Tom Cherryb7349902015-08-26 11:43:36 -0700701
Tom Cherry89bcc852017-08-02 17:01:36 -0700702 return std::invoke(*parser, this, args);
Tom Cherryb7349902015-08-26 11:43:36 -0700703}
704
Tom Cherry76af7e62017-08-22 16:13:59 -0700705Result<Success> Service::ExecStart() {
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700706 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700707
Tom Cherry76af7e62017-08-22 16:13:59 -0700708 if (auto result = Start(); !result) {
709 return result;
Tom Cherryb27004a2017-03-27 16:27:30 -0700710 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700711
712 flags_ |= SVC_EXEC;
713 is_exec_service_running_ = true;
714
715 LOG(INFO) << "SVC_EXEC pid " << pid_ << " (uid " << uid_ << " gid " << gid_ << "+"
716 << supp_gids_.size() << " context " << (!seclabel_.empty() ? seclabel_ : "default")
717 << ") started; waiting...";
718
Tom Cherry76af7e62017-08-22 16:13:59 -0700719 return Success();
Tom Cherryb27004a2017-03-27 16:27:30 -0700720}
721
Tom Cherry76af7e62017-08-22 16:13:59 -0700722Result<Success> Service::Start() {
Tao Wu990d43c2017-10-26 10:43:10 -0700723 bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
Tom Cherrybac32992015-07-31 12:45:25 -0700724 // Starting a service removes it from the disabled or reset state and
725 // immediately takes it out of the restarting state if it was in there.
726 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700727
728 // Running processes require no additional work --- if they're in the
729 // process of exiting, we've ensured that they will immediately restart
Tao Wu990d43c2017-10-26 10:43:10 -0700730 // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
731 // stopping status, we just set SVC_RESTART flag so it will get restarted
732 // in Reap().
Tom Cherrybac32992015-07-31 12:45:25 -0700733 if (flags_ & SVC_RUNNING) {
Tao Wu990d43c2017-10-26 10:43:10 -0700734 if ((flags_ & SVC_ONESHOT) && disabled) {
735 flags_ |= SVC_RESTART;
736 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700737 // It is not an error to try to start a service that is already running.
738 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700739 }
740
741 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200742 if (needs_console) {
743 if (console_.empty()) {
744 console_ = default_console;
745 }
746
Adrian Salido24ef8602016-12-20 15:52:15 -0800747 // Make sure that open call succeeds to ensure a console driver is
748 // properly registered for the device node
749 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
750 if (console_fd < 0) {
Viorel Suman70daa672016-03-21 10:08:07 +0200751 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700752 return ErrnoError() << "Couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200753 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800754 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700755 }
756
757 struct stat sb;
758 if (stat(args_[0].c_str(), &sb) == -1) {
Tom Cherrybac32992015-07-31 12:45:25 -0700759 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700760 return ErrnoError() << "Cannot find '" << args_[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700761 }
762
Tom Cherrybac32992015-07-31 12:45:25 -0700763 std::string scon;
764 if (!seclabel_.empty()) {
765 scon = seclabel_;
766 } else {
Tom Cherry76af7e62017-08-22 16:13:59 -0700767 auto result = ComputeContextFromExecutable(name_, args_[0]);
768 if (!result) {
769 return result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700770 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700771 scon = *result;
Tom Cherrybac32992015-07-31 12:45:25 -0700772 }
773
Wei Wanga285dac2016-10-04 14:05:39 -0700774 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700775
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700776 pid_t pid = -1;
777 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400778 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700779 } else {
780 pid = fork();
781 }
782
Tom Cherrybac32992015-07-31 12:45:25 -0700783 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700784 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700785
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700786 if (namespace_flags_ & CLONE_NEWPID) {
787 // This will fork again to run an init process inside the PID
788 // namespace.
789 SetUpPidNamespace(name_);
790 }
791
Tom Cherry6de21f12017-08-22 15:41:03 -0700792 for (const auto& [key, value] : environment_vars_) {
793 setenv(key.c_str(), value.c_str(), 1);
Tom Cherrybac32992015-07-31 12:45:25 -0700794 }
795
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700796 std::for_each(descriptors_.begin(), descriptors_.end(),
797 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700798
Alex Vakulenko08286762016-05-03 12:00:00 -0700799 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
800 auto cpuset_predicate = [](const std::string& path) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700801 return StartsWith(path, "/dev/cpuset/");
Alex Vakulenko08286762016-05-03 12:00:00 -0700802 };
803 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
804 if (iter == writepid_files_.end()) {
805 // There were no "writepid" instructions for cpusets, check if the system default
806 // cpuset is specified to be used for the process.
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700807 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700808 if (!default_cpuset.empty()) {
809 // Make sure the cpuset name starts and ends with '/'.
810 // A single '/' means the 'root' cpuset.
811 if (default_cpuset.front() != '/') {
812 default_cpuset.insert(0, 1, '/');
813 }
814 if (default_cpuset.back() != '/') {
815 default_cpuset.push_back('/');
816 }
817 writepid_files_.push_back(
818 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
819 }
820 }
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700821 std::string pid_str = std::to_string(getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700822 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700823 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700824 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700825 }
826 }
827
828 if (ioprio_class_ != IoSchedClass_NONE) {
829 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400830 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700831 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700832 }
833 }
834
835 if (needs_console) {
836 setsid();
837 OpenConsole();
838 } else {
839 ZapStdio();
840 }
841
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400842 // As requested, set our gid, supplemental gids, uid, context, and
843 // priority. Aborts on failure.
844 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700845
Tom Cherry5e405ca2017-09-11 16:08:54 -0700846 if (!ExpandArgsAndExecv(args_)) {
847 PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700848 }
849
850 _exit(127);
851 }
852
853 if (pid < 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700854 pid_ = 0;
Tom Cherry76af7e62017-08-22 16:13:59 -0700855 return ErrnoError() << "Failed to fork";
Tom Cherrybac32992015-07-31 12:45:25 -0700856 }
857
Marco Nelissen310f6702016-07-22 12:07:06 -0700858 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700859 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700860 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
861 if (!WriteStringToFile(oom_str, oom_file)) {
862 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
863 }
864 }
865
Elliott Hughes9605a942016-11-10 17:43:47 -0800866 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700867 pid_ = pid;
868 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -0700869 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -0700870 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700871
872 errno = -createProcessGroup(uid_, pid_);
873 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400874 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
875 << name_ << "'";
Robert Benead4852262017-07-16 19:38:11 -0700876 } else {
877 if (swappiness_ != -1) {
878 if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
879 PLOG(ERROR) << "setProcessGroupSwappiness failed";
880 }
881 }
882
883 if (soft_limit_in_bytes_ != -1) {
884 if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
885 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
886 }
887 }
888
889 if (limit_in_bytes_ != -1) {
890 if (!setProcessGroupLimit(uid_, pid_, limit_in_bytes_)) {
891 PLOG(ERROR) << "setProcessGroupLimit failed";
892 }
893 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700894 }
Tom Cherrybac32992015-07-31 12:45:25 -0700895
Tom Cherrybac32992015-07-31 12:45:25 -0700896 NotifyStateChange("running");
Tom Cherry76af7e62017-08-22 16:13:59 -0700897 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700898}
899
Tom Cherry76af7e62017-08-22 16:13:59 -0700900Result<Success> Service::StartIfNotDisabled() {
Tom Cherrybac32992015-07-31 12:45:25 -0700901 if (!(flags_ & SVC_DISABLED)) {
902 return Start();
903 } else {
904 flags_ |= SVC_DISABLED_START;
905 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700906 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700907}
908
Tom Cherry76af7e62017-08-22 16:13:59 -0700909Result<Success> Service::Enable() {
Tom Cherrybac32992015-07-31 12:45:25 -0700910 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
911 if (flags_ & SVC_DISABLED_START) {
912 return Start();
913 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700914 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700915}
916
917void Service::Reset() {
918 StopOrReset(SVC_RESET);
919}
920
921void Service::Stop() {
922 StopOrReset(SVC_DISABLED);
923}
924
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800925void Service::Terminate() {
926 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
927 flags_ |= SVC_DISABLED;
928 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700929 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800930 NotifyStateChange("stopping");
931 }
932}
933
Tom Cherrybac32992015-07-31 12:45:25 -0700934void Service::Restart() {
935 if (flags_ & SVC_RUNNING) {
936 /* Stop, wait, then start the service. */
937 StopOrReset(SVC_RESTART);
938 } else if (!(flags_ & SVC_RESTARTING)) {
939 /* Just start the service since it's not running. */
Tom Cherry76af7e62017-08-22 16:13:59 -0700940 if (auto result = Start(); !result) {
941 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
942 }
Tom Cherrybac32992015-07-31 12:45:25 -0700943 } /* else: Service is restarting anyways. */
944}
945
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700946// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700947void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700948 // The service is still SVC_RUNNING until its process exits, but if it has
949 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700950 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
951
952 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700953 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700954 how = SVC_DISABLED;
955 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700956
957 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700958 if (how == SVC_RESET) {
959 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
960 } else {
961 flags_ |= how;
962 }
Tao Wu84b856d2017-10-27 11:29:13 -0700963 // Make sure it's in right status when a restart immediately follow a
964 // stop/reset or vice versa.
965 if (how == SVC_RESTART) {
966 flags_ &= (~(SVC_DISABLED | SVC_RESET));
967 } else {
968 flags_ &= (~SVC_RESTART);
969 }
Tom Cherrybac32992015-07-31 12:45:25 -0700970
971 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700972 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700973 NotifyStateChange("stopping");
974 } else {
975 NotifyStateChange("stopped");
976 }
977}
978
979void Service::ZapStdio() const {
980 int fd;
981 fd = open("/dev/null", O_RDWR);
982 dup2(fd, 0);
983 dup2(fd, 1);
984 dup2(fd, 2);
985 close(fd);
986}
987
988void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200989 int fd = open(console_.c_str(), O_RDWR);
990 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700991 ioctl(fd, TIOCSCTTY, 0);
992 dup2(fd, 0);
993 dup2(fd, 1);
994 dup2(fd, 2);
995 close(fd);
996}
997
Tom Cherry911b9b12017-07-27 16:20:58 -0700998ServiceList::ServiceList() {}
Tom Cherrybac32992015-07-31 12:45:25 -0700999
Tom Cherry911b9b12017-07-27 16:20:58 -07001000ServiceList& ServiceList::GetInstance() {
1001 static ServiceList instance;
Tom Cherrybac32992015-07-31 12:45:25 -07001002 return instance;
1003}
1004
Tom Cherry911b9b12017-07-27 16:20:58 -07001005void ServiceList::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -07001006 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -07001007}
1008
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001009std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -07001010 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
1011 // SECLABEL can be a - to denote default
1012 std::size_t command_arg = 1;
1013 for (std::size_t i = 1; i < args.size(); ++i) {
1014 if (args[i] == "--") {
1015 command_arg = i + 1;
1016 break;
1017 }
1018 }
1019 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001020 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -07001021 return nullptr;
1022 }
1023
1024 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001025 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -07001026 return nullptr;
1027 }
1028 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
1029
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001030 static size_t exec_count = 0;
1031 exec_count++;
1032 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -07001033
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001034 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -04001035 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001036 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001037
1038 std::string seclabel = "";
1039 if (command_arg > 2 && args[1] != "-") {
1040 seclabel = args[1];
1041 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001042 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001043 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001044 uid = DecodeUid(args[2]);
1045 if (!uid) {
1046 LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001047 return nullptr;
1048 }
Tom Cherrybac32992015-07-31 12:45:25 -07001049 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001050 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001051 std::vector<gid_t> supp_gids;
1052 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001053 gid = DecodeUid(args[3]);
1054 if (!gid) {
1055 LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001056 return nullptr;
1057 }
Tom Cherrybac32992015-07-31 12:45:25 -07001058 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
1059 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -07001060 auto supp_gid = DecodeUid(args[4 + i]);
1061 if (!supp_gid) {
1062 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
1063 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -07001064 return nullptr;
1065 }
Tom Cherry11a3aee2017-08-03 12:54:07 -07001066 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -07001067 }
1068 }
1069
Tom Cherry11a3aee2017-08-03 12:54:07 -07001070 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, no_capabilities,
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001071 namespace_flags, seclabel, nullptr, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001072}
1073
Tom Cherry59383792017-07-26 16:09:09 -07001074// Shutdown services in the opposite order that they were started.
Tom Cherry911b9b12017-07-27 16:20:58 -07001075const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
Tom Cherry59383792017-07-26 16:09:09 -07001076 std::vector<Service*> shutdown_services;
1077 for (const auto& service : services_) {
1078 if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
1079 }
1080 std::sort(shutdown_services.begin(), shutdown_services.end(),
1081 [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
Tom Cherry911b9b12017-07-27 16:20:58 -07001082 return shutdown_services;
Tom Cherry59383792017-07-26 16:09:09 -07001083}
1084
Tom Cherry911b9b12017-07-27 16:20:58 -07001085void ServiceList::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001086 auto svc_it = std::find_if(services_.begin(), services_.end(),
1087 [&svc] (const std::unique_ptr<Service>& s) {
1088 return svc.name() == s->name();
1089 });
1090 if (svc_it == services_.end()) {
1091 return;
1092 }
1093
1094 services_.erase(svc_it);
1095}
1096
Tom Cherry911b9b12017-07-27 16:20:58 -07001097void ServiceList::DumpState() const {
Tom Cherryb7349902015-08-26 11:43:36 -07001098 for (const auto& s : services_) {
1099 s->DumpState();
1100 }
Tom Cherryb7349902015-08-26 11:43:36 -07001101}
1102
Tom Cherry89bcc852017-08-02 17:01:36 -07001103Result<Success> ServiceParser::ParseSection(std::vector<std::string>&& args,
1104 const std::string& filename, int line) {
Tom Cherryb7349902015-08-26 11:43:36 -07001105 if (args.size() < 3) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001106 return Error() << "services must have a name and a program";
Tom Cherryb7349902015-08-26 11:43:36 -07001107 }
1108
1109 const std::string& name = args[1];
1110 if (!IsValidName(name)) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001111 return Error() << "invalid service name '" << name << "'";
Tom Cherryb7349902015-08-26 11:43:36 -07001112 }
1113
Tom Cherry911b9b12017-07-27 16:20:58 -07001114 Service* old_service = service_list_->FindService(name);
Tom Cherry30a6f272017-04-19 15:31:58 -07001115 if (old_service) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001116 return Error() << "ignored duplicate definition of service '" << name << "'";
Tom Cherry30a6f272017-04-19 15:31:58 -07001117 }
1118
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001119 Subcontext* restart_action_subcontext = nullptr;
1120 if (subcontexts_) {
1121 for (auto& subcontext : *subcontexts_) {
1122 if (StartsWith(filename, subcontext.path_prefix().c_str())) {
1123 restart_action_subcontext = &subcontext;
1124 break;
1125 }
1126 }
1127 }
1128
Tom Cherryb7349902015-08-26 11:43:36 -07001129 std::vector<std::string> str_args(args.begin() + 2, args.end());
Tom Cherrycb0f9bb2017-09-12 15:58:47 -07001130 service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
Tom Cherry89bcc852017-08-02 17:01:36 -07001131 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001132}
1133
Tom Cherry89bcc852017-08-02 17:01:36 -07001134Result<Success> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
1135 return service_ ? service_->ParseLine(std::move(args)) : Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001136}
1137
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001138Result<Success> ServiceParser::EndSection() {
Tom Cherryb7349902015-08-26 11:43:36 -07001139 if (service_) {
Tom Cherry911b9b12017-07-27 16:20:58 -07001140 service_list_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001141 }
Steven Moreland7d0a5c32017-11-10 14:20:47 -08001142
1143 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001144}
1145
1146bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001147 // Property names can be any length, but may only contain certain characters.
1148 // Property values can contain any characters, but may only be a certain length.
1149 // (The latter restriction is needed because `start` and `stop` work by writing
1150 // the service name to the "ctl.start" and "ctl.stop" properties.)
1151 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001152}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001153
1154} // namespace init
1155} // namespace android