blob: b73ddfb69a31e2f85d6d1e08d7e8dc9bd0940b90 [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>
Elliott Hughes4f713192015-12-04 22:00:26 -080037#include <android-base/stringprintf.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070038#include <android-base/strings.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070039#include <processgroup/processgroup.h>
40#include <selinux/selinux.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070041#include <system/thread_defs.h>
Tom Cherrybac32992015-07-31 12:45:25 -070042
Tom Cherrybac32992015-07-31 12:45:25 -070043#include "init.h"
Tom Cherrybac32992015-07-31 12:45:25 -070044#include "property_service.h"
45#include "util.h"
46
James Hawkinse78ea772017-03-24 11:43:02 -070047using android::base::boot_clock;
Elliott Hughesda46b392016-10-11 17:09:00 -070048using android::base::ParseInt;
Tom Cherryb7349902015-08-26 11:43:36 -070049using android::base::StringPrintf;
50using android::base::WriteStringToFile;
51
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040052static std::string ComputeContextFromExecutable(std::string& service_name,
53 const std::string& service_path) {
54 std::string computed_context;
55
56 char* raw_con = nullptr;
57 char* raw_filecon = nullptr;
58
59 if (getcon(&raw_con) == -1) {
60 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
61 return "";
62 }
63 std::unique_ptr<char> mycon(raw_con);
64
65 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
66 LOG(ERROR) << "could not get file context while starting '" << service_name << "'";
67 return "";
68 }
69 std::unique_ptr<char> filecon(raw_filecon);
70
71 char* new_con = nullptr;
72 int rc = security_compute_create(mycon.get(), filecon.get(),
73 string_to_security_class("process"), &new_con);
74 if (rc == 0) {
75 computed_context = new_con;
76 free(new_con);
77 }
78 if (rc == 0 && computed_context == mycon.get()) {
79 LOG(ERROR) << "service " << service_name << " does not have a SELinux domain defined";
80 return "";
81 }
82 if (rc < 0) {
83 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
84 return "";
85 }
86 return computed_context;
87}
88
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070089static void SetUpPidNamespace(const std::string& service_name) {
90 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
91
92 // It's OK to LOG(FATAL) in this function since it's running in the first
93 // child process.
94 if (mount("", "/proc", "proc", kSafeFlags | MS_REMOUNT, "") == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -070095 PLOG(FATAL) << "couldn't remount(/proc) for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070096 }
97
98 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -070099 PLOG(FATAL) << "couldn't set name for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700100 }
101
102 pid_t child_pid = fork();
103 if (child_pid == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700104 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700105 }
106
107 if (child_pid > 0) {
108 // So that we exit with the right status.
109 static int init_exitstatus = 0;
110 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
111
112 pid_t waited_pid;
113 int status;
114 while ((waited_pid = wait(&status)) > 0) {
115 // This loop will end when there are no processes left inside the
116 // PID namespace or when the init process inside the PID namespace
117 // gets a signal.
118 if (waited_pid == child_pid) {
119 init_exitstatus = status;
120 }
121 }
122 if (!WIFEXITED(init_exitstatus)) {
123 _exit(EXIT_FAILURE);
124 }
125 _exit(WEXITSTATUS(init_exitstatus));
126 }
127}
128
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400129static void ExpandArgs(const std::vector<std::string>& args, std::vector<char*>* strs) {
130 std::vector<std::string> expanded_args;
131 expanded_args.resize(args.size());
132 strs->push_back(const_cast<char*>(args[0].c_str()));
133 for (std::size_t i = 1; i < args.size(); ++i) {
134 if (!expand_props(args[i], &expanded_args[i])) {
135 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
136 }
137 strs->push_back(const_cast<char*>(expanded_args[i].c_str()));
138 }
139 strs->push_back(nullptr);
140}
141
Tom Cherrybac32992015-07-31 12:45:25 -0700142ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
143}
144
145ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
146 const std::string& value)
147 : name(name), value(value) {
148}
149
Wei Wang641ff0a2017-03-27 10:59:11 -0700150Service::Service(const std::string& name, const std::vector<std::string>& args)
151 : name_(name),
152 classnames_({"default"}),
153 flags_(0),
154 pid_(0),
155 crash_count_(0),
156 uid_(0),
157 gid_(0),
158 namespace_flags_(0),
159 seclabel_(""),
Tom Cherry012c5732017-04-18 13:21:54 -0700160 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Tom Cherry7da54852017-05-01 14:16:41 -0700161 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700162 ioprio_class_(IoSchedClass_NONE),
163 ioprio_pri_(0),
164 priority_(0),
165 oom_score_adjust_(-1000),
166 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700167 onrestart_.InitSingleTrigger("onrestart");
168}
169
Wei Wang641ff0a2017-03-27 10:59:11 -0700170Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
171 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
172 unsigned namespace_flags, const std::string& seclabel,
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700173 const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700174 : name_(name),
175 classnames_({"default"}),
176 flags_(flags),
177 pid_(0),
178 crash_count_(0),
179 uid_(uid),
180 gid_(gid),
181 supp_gids_(supp_gids),
182 capabilities_(capabilities),
183 namespace_flags_(namespace_flags),
184 seclabel_(seclabel),
Tom Cherry012c5732017-04-18 13:21:54 -0700185 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Tom Cherry7da54852017-05-01 14:16:41 -0700186 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700187 ioprio_class_(IoSchedClass_NONE),
188 ioprio_pri_(0),
189 priority_(0),
190 oom_score_adjust_(-1000),
191 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700192 onrestart_.InitSingleTrigger("onrestart");
193}
194
195void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700196 if ((flags_ & SVC_TEMPORARY) != 0) {
197 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700198 return;
199 }
200
Tom Cherryb7349902015-08-26 11:43:36 -0700201 std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700202 property_set(prop_name.c_str(), new_state.c_str());
Elliott Hughes9605a942016-11-10 17:43:47 -0800203
204 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800205 uint64_t start_ns = time_started_.time_since_epoch().count();
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000206 property_set(StringPrintf("ro.boottime.%s", name_.c_str()).c_str(),
207 StringPrintf("%" PRIu64, start_ns).c_str());
Elliott Hughes9605a942016-11-10 17:43:47 -0800208 }
Tom Cherrybac32992015-07-31 12:45:25 -0700209}
210
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700211void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700212 // If we've already seen a successful result from killProcessGroup*(), then we have removed
213 // the cgroup already and calling these functions a second time will simply result in an error.
214 // This is true regardless of which signal was sent.
215 // These functions handle their own logging, so no additional logging is needed.
216 if (!process_cgroup_empty_) {
217 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
218 << ") process group...";
219 int r;
220 if (signal == SIGTERM) {
221 r = killProcessGroupOnce(uid_, pid_, signal);
222 } else {
223 r = killProcessGroup(uid_, pid_, signal);
224 }
225
226 if (r == 0) process_cgroup_empty_ = true;
227 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700228}
229
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400230void Service::SetProcessAttributes() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400231 // Keep capabilites on uid change.
232 if (capabilities_.any() && uid_) {
233 if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED) != 0) {
234 PLOG(FATAL) << "prtcl(PR_SET_KEEPCAPS) failed for " << name_;
235 }
236 }
237
Elliott Hughese18e7e52016-07-25 18:18:16 -0700238 // TODO: work out why this fails for `console` then upgrade to FATAL.
239 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400240
241 if (gid_) {
242 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700243 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400244 }
245 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700246 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
247 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400248 }
249 if (uid_) {
250 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700251 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400252 }
253 }
254 if (!seclabel_.empty()) {
255 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700256 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400257 }
258 }
259 if (priority_ != 0) {
260 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700261 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400262 }
263 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400264 if (capabilities_.any()) {
265 if (!SetCapsForExec(capabilities_)) {
266 LOG(FATAL) << "cannot set capabilities for " << name_;
267 }
268 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400269}
270
Tom Cherryb27004a2017-03-27 16:27:30 -0700271void Service::Reap() {
Tom Cherrybac32992015-07-31 12:45:25 -0700272 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700273 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700274 }
275
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700276 // Remove any descriptor resources we may have created.
277 std::for_each(descriptors_.begin(), descriptors_.end(),
278 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700279
Tom Cherryb27004a2017-03-27 16:27:30 -0700280 if (flags_ & SVC_TEMPORARY) {
281 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700282 }
283
284 pid_ = 0;
285 flags_ &= (~SVC_RUNNING);
286
287 // Oneshot processes go into the disabled state on exit,
288 // except when manually restarted.
289 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
290 flags_ |= SVC_DISABLED;
291 }
292
293 // Disabled and reset processes do not get restarted automatically.
294 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
295 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700296 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700297 }
298
Elliott Hughes9605a942016-11-10 17:43:47 -0800299 // If we crash > 4 times in 4 minutes, reboot into recovery.
300 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700301 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800302 if (now < time_crashed_ + 4min) {
303 if (++crash_count_ > 4) {
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000304 LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
305 panic();
Tom Cherrybac32992015-07-31 12:45:25 -0700306 }
307 } else {
308 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800309 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700310 }
311 }
312
313 flags_ &= (~SVC_RESTART);
314 flags_ |= SVC_RESTARTING;
315
316 // Execute all onrestart commands for this service.
317 onrestart_.ExecuteAllCommands();
318
319 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700320 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700321}
322
323void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700324 LOG(INFO) << "service " << name_;
Wei Wang641ff0a2017-03-27 10:59:11 -0700325 LOG(INFO) << " class '" << android::base::Join(classnames_, " ") << "'";
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700326 LOG(INFO) << " exec "<< android::base::Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700327 std::for_each(descriptors_.begin(), descriptors_.end(),
328 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700329}
330
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400331bool Service::ParseCapabilities(const std::vector<std::string>& args, std::string* err) {
332 capabilities_ = 0;
333
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500334 if (!CapAmbientSupported()) {
335 *err = "capabilities requested but the kernel does not support ambient capabilities";
336 return false;
337 }
338
339 unsigned int last_valid_cap = GetLastValidCap();
340 if (last_valid_cap >= capabilities_.size()) {
341 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
342 }
343
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400344 for (size_t i = 1; i < args.size(); i++) {
345 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500346 int res = LookupCap(arg);
347 if (res < 0) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400348 *err = StringPrintf("invalid capability '%s'", arg.c_str());
349 return false;
350 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500351 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
352 if (cap > last_valid_cap) {
353 *err = StringPrintf("capability '%s' not supported by the kernel", arg.c_str());
354 return false;
355 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400356 capabilities_[cap] = true;
357 }
358 return true;
359}
360
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400361bool Service::ParseClass(const std::vector<std::string>& args, std::string* err) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700362 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherryb7349902015-08-26 11:43:36 -0700363 return true;
364}
Tom Cherrybac32992015-07-31 12:45:25 -0700365
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400366bool Service::ParseConsole(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700367 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200368 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherryb7349902015-08-26 11:43:36 -0700369 return true;
370}
Tom Cherrybac32992015-07-31 12:45:25 -0700371
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400372bool Service::ParseCritical(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700373 flags_ |= SVC_CRITICAL;
374 return true;
375}
Tom Cherrybac32992015-07-31 12:45:25 -0700376
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400377bool Service::ParseDisabled(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700378 flags_ |= SVC_DISABLED;
379 flags_ |= SVC_RC_DISABLED;
380 return true;
381}
Tom Cherrybac32992015-07-31 12:45:25 -0700382
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400383bool Service::ParseGroup(const std::vector<std::string>& args, std::string* err) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700384 std::string decode_uid_err;
385 if (!DecodeUid(args[1], &gid_, &decode_uid_err)) {
386 *err = "Unable to find GID for '" + args[1] + "': " + decode_uid_err;
387 return false;
388 }
Tom Cherryb7349902015-08-26 11:43:36 -0700389 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700390 gid_t gid;
391 if (!DecodeUid(args[n], &gid, &decode_uid_err)) {
392 *err = "Unable to find GID for '" + args[n] + "': " + decode_uid_err;
393 return false;
394 }
395 supp_gids_.emplace_back(gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700396 }
397 return true;
398}
399
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400400bool Service::ParsePriority(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700401 priority_ = 0;
402 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800403 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
404 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700405 *err = StringPrintf("process priority value must be range %d - %d",
406 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
407 return false;
408 }
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700409 return true;
410}
411
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400412bool Service::ParseIoprio(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700413 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherryb7349902015-08-26 11:43:36 -0700414 *err = "priority value must be range 0 - 7";
415 return false;
416 }
417
418 if (args[1] == "rt") {
419 ioprio_class_ = IoSchedClass_RT;
420 } else if (args[1] == "be") {
421 ioprio_class_ = IoSchedClass_BE;
422 } else if (args[1] == "idle") {
423 ioprio_class_ = IoSchedClass_IDLE;
424 } else {
425 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
426 return false;
427 }
428
429 return true;
430}
431
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400432bool Service::ParseKeycodes(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700433 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700434 int code;
435 if (ParseInt(args[i], &code)) {
436 keycodes_.emplace_back(code);
437 } else {
438 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
439 }
Tom Cherryb7349902015-08-26 11:43:36 -0700440 }
441 return true;
442}
443
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400444bool Service::ParseOneshot(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700445 flags_ |= SVC_ONESHOT;
446 return true;
447}
448
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400449bool Service::ParseOnrestart(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700450 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700451 int line = onrestart_.NumCommands() + 1;
452 onrestart_.AddCommand(str_args, line, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700453 return true;
454}
455
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400456bool Service::ParseNamespace(const std::vector<std::string>& args, std::string* err) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700457 for (size_t i = 1; i < args.size(); i++) {
458 if (args[i] == "pid") {
459 namespace_flags_ |= CLONE_NEWPID;
460 // PID namespaces require mount namespaces.
461 namespace_flags_ |= CLONE_NEWNS;
462 } else if (args[i] == "mnt") {
463 namespace_flags_ |= CLONE_NEWNS;
464 } else {
465 *err = "namespace must be 'pid' or 'mnt'";
466 return false;
467 }
468 }
469 return true;
470}
471
Marco Nelissen310f6702016-07-22 12:07:06 -0700472bool Service::ParseOomScoreAdjust(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700473 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Marco Nelissen310f6702016-07-22 12:07:06 -0700474 *err = "oom_score_adjust value must be in range -1000 - +1000";
475 return false;
476 }
Marco Nelissen310f6702016-07-22 12:07:06 -0700477 return true;
478}
479
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400480bool Service::ParseSeclabel(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700481 seclabel_ = args[1];
482 return true;
483}
484
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400485bool Service::ParseSetenv(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700486 envvars_.emplace_back(args[1], args[2]);
487 return true;
488}
489
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700490template <typename T>
491bool Service::AddDescriptor(const std::vector<std::string>& args, std::string* err) {
492 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry517e1f12017-05-04 17:40:33 -0700493 uid_t uid = 0;
494 gid_t gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700495 std::string context = args.size() > 6 ? args[6] : "";
496
Tom Cherry517e1f12017-05-04 17:40:33 -0700497 std::string decode_uid_err;
498 if (args.size() > 4) {
499 if (!DecodeUid(args[4], &uid, &decode_uid_err)) {
500 *err = "Unable to find UID for '" + args[4] + "': " + decode_uid_err;
501 return false;
502 }
503 }
504
505 if (args.size() > 5) {
506 if (!DecodeUid(args[5], &gid, &decode_uid_err)) {
507 *err = "Unable to find GID for '" + args[5] + "': " + decode_uid_err;
508 return false;
509 }
510 }
511
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700512 auto descriptor = std::make_unique<T>(args[1], args[2], uid, gid, perm, context);
513
514 auto old =
515 std::find_if(descriptors_.begin(), descriptors_.end(),
516 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
517
518 if (old != descriptors_.end()) {
519 *err = "duplicate descriptor " + args[1] + " " + args[2];
520 return false;
521 }
522
523 descriptors_.emplace_back(std::move(descriptor));
524 return true;
525}
526
527// name type perm [ uid gid context ]
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400528bool Service::ParseSocket(const std::vector<std::string>& args, std::string* err) {
Mark Salyzynb066fcc2017-05-05 14:44:35 -0700529 if (!android::base::StartsWith(args[2], "dgram") &&
530 !android::base::StartsWith(args[2], "stream") &&
531 !android::base::StartsWith(args[2], "seqpacket")) {
Tom Cherryb7349902015-08-26 11:43:36 -0700532 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
533 return false;
534 }
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700535 return AddDescriptor<SocketInfo>(args, err);
536}
Tom Cherryb7349902015-08-26 11:43:36 -0700537
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700538// name type perm [ uid gid context ]
539bool Service::ParseFile(const std::vector<std::string>& args, std::string* err) {
540 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
541 *err = "file type must be 'r', 'w' or 'rw'";
542 return false;
543 }
544 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
545 *err = "file name must not be relative";
546 return false;
547 }
548 return AddDescriptor<FileInfo>(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700549}
550
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400551bool Service::ParseUser(const std::vector<std::string>& args, std::string* err) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700552 std::string decode_uid_err;
553 if (!DecodeUid(args[1], &uid_, &decode_uid_err)) {
554 *err = "Unable to find UID for '" + args[1] + "': " + decode_uid_err;
555 return false;
556 }
Tom Cherryb7349902015-08-26 11:43:36 -0700557 return true;
558}
559
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400560bool Service::ParseWritepid(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700561 writepid_files_.assign(args.begin() + 1, args.end());
562 return true;
563}
564
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400565class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700566 public:
567 OptionParserMap() {}
568
569 private:
570 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700571};
572
Tom Cherryad54d092017-04-19 16:18:50 -0700573const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700574 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700575 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400576 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400577 {"capabilities",
578 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700579 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400580 {"console", {0, 1, &Service::ParseConsole}},
581 {"critical", {0, 0, &Service::ParseCritical}},
582 {"disabled", {0, 0, &Service::ParseDisabled}},
583 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
584 {"ioprio", {2, 2, &Service::ParseIoprio}},
585 {"priority", {1, 1, &Service::ParsePriority}},
586 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
587 {"oneshot", {0, 0, &Service::ParseOneshot}},
588 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700589 {"oom_score_adjust",
590 {1, 1, &Service::ParseOomScoreAdjust}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400591 {"namespace", {1, 2, &Service::ParseNamespace}},
592 {"seclabel", {1, 1, &Service::ParseSeclabel}},
593 {"setenv", {2, 2, &Service::ParseSetenv}},
594 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn978fd0e2016-12-02 08:05:22 -0800595 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400596 {"user", {1, 1, &Service::ParseUser}},
597 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700598 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700599 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400600 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700601}
602
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400603bool Service::ParseLine(const std::vector<std::string>& args, std::string* err) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400604 static const OptionParserMap parser_map;
Tom Cherryfe062052017-04-24 16:59:05 -0700605 auto parser = parser_map.FindFunction(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700606
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400607 if (!parser) {
Tom Cherryb7349902015-08-26 11:43:36 -0700608 return false;
609 }
610
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400611 return (this->*parser)(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700612}
613
Tom Cherryb27004a2017-03-27 16:27:30 -0700614bool Service::ExecStart(std::unique_ptr<Timer>* exec_waiter) {
615 flags_ |= SVC_EXEC | SVC_ONESHOT;
616
617 exec_waiter->reset(new Timer);
618
619 if (!Start()) {
620 exec_waiter->reset();
621 return false;
622 }
623 return true;
624}
625
Elliott Hughesbdeac392016-04-12 15:38:27 -0700626bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700627 // Starting a service removes it from the disabled or reset state and
628 // immediately takes it out of the restarting state if it was in there.
629 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700630
631 // Running processes require no additional work --- if they're in the
632 // process of exiting, we've ensured that they will immediately restart
633 // on exit, unless they are ONESHOT.
634 if (flags_ & SVC_RUNNING) {
635 return false;
636 }
637
638 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200639 if (needs_console) {
640 if (console_.empty()) {
641 console_ = default_console;
642 }
643
Adrian Salido24ef8602016-12-20 15:52:15 -0800644 // Make sure that open call succeeds to ensure a console driver is
645 // properly registered for the device node
646 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
647 if (console_fd < 0) {
648 PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200649 flags_ |= SVC_DISABLED;
650 return false;
651 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800652 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700653 }
654
655 struct stat sb;
656 if (stat(args_[0].c_str(), &sb) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700657 PLOG(ERROR) << "cannot find '" << args_[0] << "', disabling '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700658 flags_ |= SVC_DISABLED;
659 return false;
660 }
661
Tom Cherrybac32992015-07-31 12:45:25 -0700662 std::string scon;
663 if (!seclabel_.empty()) {
664 scon = seclabel_;
665 } else {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400666 scon = ComputeContextFromExecutable(name_, args_[0]);
667 if (scon == "") {
Tom Cherrybac32992015-07-31 12:45:25 -0700668 return false;
669 }
670 }
671
Wei Wanga285dac2016-10-04 14:05:39 -0700672 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700673
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700674 pid_t pid = -1;
675 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400676 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700677 } else {
678 pid = fork();
679 }
680
Tom Cherrybac32992015-07-31 12:45:25 -0700681 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700682 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700683
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700684 if (namespace_flags_ & CLONE_NEWPID) {
685 // This will fork again to run an init process inside the PID
686 // namespace.
687 SetUpPidNamespace(name_);
688 }
689
Tom Cherrybac32992015-07-31 12:45:25 -0700690 for (const auto& ei : envvars_) {
691 add_environment(ei.name.c_str(), ei.value.c_str());
692 }
693
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700694 std::for_each(descriptors_.begin(), descriptors_.end(),
695 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700696
Alex Vakulenko08286762016-05-03 12:00:00 -0700697 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
698 auto cpuset_predicate = [](const std::string& path) {
699 return android::base::StartsWith(path, "/dev/cpuset/");
700 };
701 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
702 if (iter == writepid_files_.end()) {
703 // There were no "writepid" instructions for cpusets, check if the system default
704 // cpuset is specified to be used for the process.
Tom Cherryccf23532017-03-28 16:40:41 -0700705 std::string default_cpuset = android::base::GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700706 if (!default_cpuset.empty()) {
707 // Make sure the cpuset name starts and ends with '/'.
708 // A single '/' means the 'root' cpuset.
709 if (default_cpuset.front() != '/') {
710 default_cpuset.insert(0, 1, '/');
711 }
712 if (default_cpuset.back() != '/') {
713 default_cpuset.push_back('/');
714 }
715 writepid_files_.push_back(
716 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
717 }
718 }
Anestis Bechtsoudisb702b462016-02-05 16:38:48 +0200719 std::string pid_str = StringPrintf("%d", getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700720 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700721 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700722 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700723 }
724 }
725
726 if (ioprio_class_ != IoSchedClass_NONE) {
727 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400728 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700729 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700730 }
731 }
732
733 if (needs_console) {
734 setsid();
735 OpenConsole();
736 } else {
737 ZapStdio();
738 }
739
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400740 // As requested, set our gid, supplemental gids, uid, context, and
741 // priority. Aborts on failure.
742 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700743
Tom Cherrybac32992015-07-31 12:45:25 -0700744 std::vector<char*> strs;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400745 ExpandArgs(args_, &strs);
Tom Cherrybac35362016-06-07 11:22:00 -0700746 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700747 PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700748 }
749
750 _exit(127);
751 }
752
753 if (pid < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700754 PLOG(ERROR) << "failed to fork for '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700755 pid_ = 0;
756 return false;
757 }
758
Marco Nelissen310f6702016-07-22 12:07:06 -0700759 if (oom_score_adjust_ != -1000) {
760 std::string oom_str = StringPrintf("%d", oom_score_adjust_);
761 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
762 if (!WriteStringToFile(oom_str, oom_file)) {
763 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
764 }
765 }
766
Elliott Hughes9605a942016-11-10 17:43:47 -0800767 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700768 pid_ = pid;
769 flags_ |= SVC_RUNNING;
Tom Cherry33838b12017-05-04 11:32:36 -0700770 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700771
772 errno = -createProcessGroup(uid_, pid_);
773 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400774 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
775 << name_ << "'";
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700776 }
Tom Cherrybac32992015-07-31 12:45:25 -0700777
778 if ((flags_ & SVC_EXEC) != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400779 LOG(INFO) << android::base::StringPrintf(
780 "SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...", pid_, uid_, gid_,
781 supp_gids_.size(), !seclabel_.empty() ? seclabel_.c_str() : "default");
Tom Cherrybac32992015-07-31 12:45:25 -0700782 }
783
784 NotifyStateChange("running");
785 return true;
786}
787
Tom Cherrybac32992015-07-31 12:45:25 -0700788bool Service::StartIfNotDisabled() {
789 if (!(flags_ & SVC_DISABLED)) {
790 return Start();
791 } else {
792 flags_ |= SVC_DISABLED_START;
793 }
794 return true;
795}
796
797bool Service::Enable() {
798 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
799 if (flags_ & SVC_DISABLED_START) {
800 return Start();
801 }
802 return true;
803}
804
805void Service::Reset() {
806 StopOrReset(SVC_RESET);
807}
808
809void Service::Stop() {
810 StopOrReset(SVC_DISABLED);
811}
812
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800813void Service::Terminate() {
814 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
815 flags_ |= SVC_DISABLED;
816 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700817 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800818 NotifyStateChange("stopping");
819 }
820}
821
Tom Cherrybac32992015-07-31 12:45:25 -0700822void Service::Restart() {
823 if (flags_ & SVC_RUNNING) {
824 /* Stop, wait, then start the service. */
825 StopOrReset(SVC_RESTART);
826 } else if (!(flags_ & SVC_RESTARTING)) {
827 /* Just start the service since it's not running. */
828 Start();
829 } /* else: Service is restarting anyways. */
830}
831
Elliott Hughes9605a942016-11-10 17:43:47 -0800832void Service::RestartIfNeeded(time_t* process_needs_restart_at) {
833 boot_clock::time_point now = boot_clock::now();
834 boot_clock::time_point next_start = time_started_ + 5s;
835 if (now > next_start) {
Tom Cherrybac32992015-07-31 12:45:25 -0700836 flags_ &= (~SVC_RESTARTING);
837 Start();
838 return;
839 }
840
Elliott Hughes9605a942016-11-10 17:43:47 -0800841 time_t next_start_time_t = time(nullptr) +
842 time_t(std::chrono::duration_cast<std::chrono::seconds>(next_start - now).count());
843 if (next_start_time_t < *process_needs_restart_at || *process_needs_restart_at == 0) {
844 *process_needs_restart_at = next_start_time_t;
Tom Cherrybac32992015-07-31 12:45:25 -0700845 }
846}
847
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700848// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700849void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700850 // The service is still SVC_RUNNING until its process exits, but if it has
851 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700852 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
853
854 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700855 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700856 how = SVC_DISABLED;
857 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700858
859 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700860 if (how == SVC_RESET) {
861 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
862 } else {
863 flags_ |= how;
864 }
865
866 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700867 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700868 NotifyStateChange("stopping");
869 } else {
870 NotifyStateChange("stopped");
871 }
872}
873
874void Service::ZapStdio() const {
875 int fd;
876 fd = open("/dev/null", O_RDWR);
877 dup2(fd, 0);
878 dup2(fd, 1);
879 dup2(fd, 2);
880 close(fd);
881}
882
883void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200884 int fd = open(console_.c_str(), O_RDWR);
885 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700886 ioctl(fd, TIOCSCTTY, 0);
887 dup2(fd, 0);
888 dup2(fd, 1);
889 dup2(fd, 2);
890 close(fd);
891}
892
Tom Cherrybac32992015-07-31 12:45:25 -0700893int ServiceManager::exec_count_ = 0;
894
895ServiceManager::ServiceManager() {
896}
897
898ServiceManager& ServiceManager::GetInstance() {
899 static ServiceManager instance;
900 return instance;
901}
902
Tom Cherryb7349902015-08-26 11:43:36 -0700903void ServiceManager::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -0700904 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700905}
906
Tom Cherryb27004a2017-03-27 16:27:30 -0700907bool ServiceManager::Exec(const std::vector<std::string>& args) {
908 Service* svc = MakeExecOneshotService(args);
909 if (!svc) {
910 LOG(ERROR) << "Could not create exec service";
911 return false;
912 }
913 if (!svc->ExecStart(&exec_waiter_)) {
914 LOG(ERROR) << "Could not start exec service";
915 ServiceManager::GetInstance().RemoveService(*svc);
916 return false;
917 }
918 return true;
919}
920
921bool ServiceManager::ExecStart(const std::string& name) {
922 Service* svc = FindServiceByName(name);
923 if (!svc) {
924 LOG(ERROR) << "ExecStart(" << name << "): Service not found";
925 return false;
926 }
927 if (!svc->ExecStart(&exec_waiter_)) {
928 LOG(ERROR) << "ExecStart(" << name << "): Could not start Service";
929 return false;
930 }
931 return true;
932}
933
934bool ServiceManager::IsWaitingForExec() const { return exec_waiter_ != nullptr; }
935
Tom Cherrybac32992015-07-31 12:45:25 -0700936Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
937 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
938 // SECLABEL can be a - to denote default
939 std::size_t command_arg = 1;
940 for (std::size_t i = 1; i < args.size(); ++i) {
941 if (args[i] == "--") {
942 command_arg = i + 1;
943 break;
944 }
945 }
946 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700947 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -0700948 return nullptr;
949 }
950
951 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700952 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -0700953 return nullptr;
954 }
955 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
956
957 exec_count_++;
Tom Cherry86e31a82017-04-25 17:31:06 -0700958 std::string name =
959 "exec " + std::to_string(exec_count_) + " (" + android::base::Join(str_args, " ") + ")";
960
Tom Cherryb27004a2017-03-27 16:27:30 -0700961 unsigned flags = SVC_EXEC | SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400962 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700963 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700964
965 std::string seclabel = "";
966 if (command_arg > 2 && args[1] != "-") {
967 seclabel = args[1];
968 }
969 uid_t uid = 0;
970 if (command_arg > 3) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700971 std::string decode_uid_err;
972 if (!DecodeUid(args[2], &uid, &decode_uid_err)) {
973 LOG(ERROR) << "Unable to find UID for '" << args[2] << "': " << decode_uid_err;
974 return nullptr;
975 }
Tom Cherrybac32992015-07-31 12:45:25 -0700976 }
977 gid_t gid = 0;
978 std::vector<gid_t> supp_gids;
979 if (command_arg > 4) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700980 std::string decode_uid_err;
981 if (!DecodeUid(args[3], &gid, &decode_uid_err)) {
982 LOG(ERROR) << "Unable to find GID for '" << args[3] << "': " << decode_uid_err;
983 return nullptr;
984 }
Tom Cherrybac32992015-07-31 12:45:25 -0700985 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
986 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700987 gid_t supp_gid;
988 if (!DecodeUid(args[4 + i], &supp_gid, &decode_uid_err)) {
989 LOG(ERROR) << "Unable to find UID for '" << args[4 + i] << "': " << decode_uid_err;
990 return nullptr;
991 }
992 supp_gids.push_back(supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700993 }
994 }
995
Wei Wang641ff0a2017-03-27 10:59:11 -0700996 auto svc_p = std::make_unique<Service>(name, flags, uid, gid, supp_gids, no_capabilities,
997 namespace_flags, seclabel, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -0700998 Service* svc = svc_p.get();
Tom Cherry9bdddd72017-03-23 16:07:51 -0700999 services_.emplace_back(std::move(svc_p));
Tom Cherrybac32992015-07-31 12:45:25 -07001000
1001 return svc;
1002}
1003
1004Service* ServiceManager::FindServiceByName(const std::string& name) const {
1005 auto svc = std::find_if(services_.begin(), services_.end(),
1006 [&name] (const std::unique_ptr<Service>& s) {
1007 return name == s->name();
1008 });
1009 if (svc != services_.end()) {
1010 return svc->get();
1011 }
1012 return nullptr;
1013}
1014
1015Service* ServiceManager::FindServiceByPid(pid_t pid) const {
1016 auto svc = std::find_if(services_.begin(), services_.end(),
1017 [&pid] (const std::unique_ptr<Service>& s) {
1018 return s->pid() == pid;
1019 });
1020 if (svc != services_.end()) {
1021 return svc->get();
1022 }
1023 return nullptr;
1024}
1025
1026Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
1027 auto svc = std::find_if(services_.begin(), services_.end(),
1028 [&keychord_id] (const std::unique_ptr<Service>& s) {
1029 return s->keychord_id() == keychord_id;
1030 });
1031
1032 if (svc != services_.end()) {
1033 return svc->get();
1034 }
1035 return nullptr;
1036}
1037
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001038void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -07001039 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001040 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -07001041 }
1042}
1043
1044void ServiceManager::ForEachServiceInClass(const std::string& classname,
1045 void (*func)(Service* svc)) const {
1046 for (const auto& s : services_) {
Wei Wang641ff0a2017-03-27 10:59:11 -07001047 if (s->classnames().find(classname) != s->classnames().end()) {
Tom Cherrybac32992015-07-31 12:45:25 -07001048 func(s.get());
1049 }
1050 }
1051}
1052
1053void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
1054 void (*func)(Service* svc)) const {
1055 for (const auto& s : services_) {
1056 if (s->flags() & matchflags) {
1057 func(s.get());
1058 }
1059 }
1060}
1061
Tom Cherryb7349902015-08-26 11:43:36 -07001062void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001063 auto svc_it = std::find_if(services_.begin(), services_.end(),
1064 [&svc] (const std::unique_ptr<Service>& s) {
1065 return svc.name() == s->name();
1066 });
1067 if (svc_it == services_.end()) {
1068 return;
1069 }
1070
1071 services_.erase(svc_it);
1072}
1073
Tom Cherryb7349902015-08-26 11:43:36 -07001074void ServiceManager::DumpState() const {
1075 for (const auto& s : services_) {
1076 s->DumpState();
1077 }
Tom Cherryb7349902015-08-26 11:43:36 -07001078}
1079
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001080bool ServiceManager::ReapOneProcess() {
1081 int status;
1082 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
1083 if (pid == 0) {
1084 return false;
1085 } else if (pid == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001086 PLOG(ERROR) << "waitpid failed";
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001087 return false;
Tom Marshall62696902017-06-09 18:29:23 +00001088 } else if (PropertyChildReap(pid)) {
1089 return true;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001090 }
1091
1092 Service* svc = FindServiceByPid(pid);
1093
1094 std::string name;
Keun-young Park4de31e12017-04-27 16:25:06 -07001095 std::string wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001096 if (svc) {
1097 name = android::base::StringPrintf("Service '%s' (pid %d)",
1098 svc->name().c_str(), pid);
Keun-young Park4de31e12017-04-27 16:25:06 -07001099 if (svc->flags() & SVC_EXEC) {
1100 wait_string =
1101 android::base::StringPrintf(" waiting took %f seconds", exec_waiter_->duration_s());
1102 }
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001103 } else {
1104 name = android::base::StringPrintf("Untracked pid %d", pid);
1105 }
1106
1107 if (WIFEXITED(status)) {
Keun-young Park4de31e12017-04-27 16:25:06 -07001108 LOG(INFO) << name << " exited with status " << WEXITSTATUS(status) << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001109 } else if (WIFSIGNALED(status)) {
Keun-young Park4de31e12017-04-27 16:25:06 -07001110 LOG(INFO) << name << " killed by signal " << WTERMSIG(status) << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001111 } else if (WIFSTOPPED(status)) {
Keun-young Park4de31e12017-04-27 16:25:06 -07001112 LOG(INFO) << name << " stopped by signal " << WSTOPSIG(status) << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001113 } else {
Keun-young Park4de31e12017-04-27 16:25:06 -07001114 LOG(INFO) << name << " state changed" << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001115 }
1116
1117 if (!svc) {
1118 return true;
1119 }
1120
Tom Cherryb27004a2017-03-27 16:27:30 -07001121 svc->Reap();
1122
1123 if (svc->flags() & SVC_EXEC) {
Tom Cherryb27004a2017-03-27 16:27:30 -07001124 exec_waiter_.reset();
1125 }
1126 if (svc->flags() & SVC_TEMPORARY) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001127 RemoveService(*svc);
1128 }
1129
1130 return true;
1131}
1132
1133void ServiceManager::ReapAnyOutstandingChildren() {
1134 while (ReapOneProcess()) {
1135 }
1136}
1137
Tom Cherry30a6f272017-04-19 15:31:58 -07001138bool ServiceParser::ParseSection(std::vector<std::string>&& args, const std::string& filename,
Tom Cherry012c5732017-04-18 13:21:54 -07001139 int line, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -07001140 if (args.size() < 3) {
1141 *err = "services must have a name and a program";
1142 return false;
1143 }
1144
1145 const std::string& name = args[1];
1146 if (!IsValidName(name)) {
1147 *err = StringPrintf("invalid service name '%s'", name.c_str());
1148 return false;
1149 }
1150
Tom Cherry30a6f272017-04-19 15:31:58 -07001151 Service* old_service = service_manager_->FindServiceByName(name);
1152 if (old_service) {
1153 *err = "ignored duplicate definition of service '" + name + "'";
1154 return false;
1155 }
1156
Tom Cherryb7349902015-08-26 11:43:36 -07001157 std::vector<std::string> str_args(args.begin() + 2, args.end());
Wei Wang641ff0a2017-03-27 10:59:11 -07001158 service_ = std::make_unique<Service>(name, str_args);
Tom Cherryb7349902015-08-26 11:43:36 -07001159 return true;
1160}
1161
Tom Cherry30a6f272017-04-19 15:31:58 -07001162bool ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) {
1163 return service_ ? service_->ParseLine(std::move(args), err) : false;
Tom Cherryb7349902015-08-26 11:43:36 -07001164}
1165
1166void ServiceParser::EndSection() {
1167 if (service_) {
Tom Cherry30a6f272017-04-19 15:31:58 -07001168 service_manager_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001169 }
1170}
1171
1172bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001173 // Property names can be any length, but may only contain certain characters.
1174 // Property values can contain any characters, but may only be a certain length.
1175 // (The latter restriction is needed because `start` and `stop` work by writing
1176 // the service name to the "ctl.start" and "ctl.stop" properties.)
1177 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001178}