blob: 1f53a1ba309f9079b88e6621024c8c141689719a [file] [log] [blame]
Tom Cherrybac32992015-07-31 12:45:25 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "service.h"
18
19#include <fcntl.h>
Elliott Hughes9605a942016-11-10 17:43:47 -080020#include <inttypes.h>
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -040021#include <linux/securebits.h>
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070022#include <sched.h>
23#include <sys/mount.h>
24#include <sys/prctl.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070025#include <sys/resource.h>
Tom Cherrybac32992015-07-31 12:45:25 -070026#include <sys/stat.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070027#include <sys/time.h>
Tom Cherrybac32992015-07-31 12:45:25 -070028#include <sys/types.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
33#include <selinux/selinux.h>
34
Elliott Hughes4f713192015-12-04 22:00:26 -080035#include <android-base/file.h>
Elliott Hughesda46b392016-10-11 17:09:00 -070036#include <android-base/parseint.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 Cherrybac32992015-07-31 12:45:25 -070039#include <cutils/android_reboot.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070040#include <system/thread_defs.h>
Tom Cherrybac32992015-07-31 12:45:25 -070041
Collin Mullinerf7e79b92016-06-01 21:03:55 +000042#include <processgroup/processgroup.h>
43
Tom Cherrybac32992015-07-31 12:45:25 -070044#include "action.h"
45#include "init.h"
46#include "init_parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070047#include "log.h"
48#include "property_service.h"
49#include "util.h"
50
Elliott Hughesda46b392016-10-11 17:09:00 -070051using android::base::ParseInt;
Tom Cherryb7349902015-08-26 11:43:36 -070052using android::base::StringPrintf;
53using android::base::WriteStringToFile;
54
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040055static std::string ComputeContextFromExecutable(std::string& service_name,
56 const std::string& service_path) {
57 std::string computed_context;
58
59 char* raw_con = nullptr;
60 char* raw_filecon = nullptr;
61
62 if (getcon(&raw_con) == -1) {
63 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
64 return "";
65 }
66 std::unique_ptr<char> mycon(raw_con);
67
68 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
69 LOG(ERROR) << "could not get file context while starting '" << service_name << "'";
70 return "";
71 }
72 std::unique_ptr<char> filecon(raw_filecon);
73
74 char* new_con = nullptr;
75 int rc = security_compute_create(mycon.get(), filecon.get(),
76 string_to_security_class("process"), &new_con);
77 if (rc == 0) {
78 computed_context = new_con;
79 free(new_con);
80 }
81 if (rc == 0 && computed_context == mycon.get()) {
82 LOG(ERROR) << "service " << service_name << " does not have a SELinux domain defined";
83 return "";
84 }
85 if (rc < 0) {
86 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
87 return "";
88 }
89 return computed_context;
90}
91
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070092static void SetUpPidNamespace(const std::string& service_name) {
93 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
94
95 // It's OK to LOG(FATAL) in this function since it's running in the first
96 // child process.
97 if (mount("", "/proc", "proc", kSafeFlags | MS_REMOUNT, "") == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -070098 PLOG(FATAL) << "couldn't remount(/proc) for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070099 }
100
101 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700102 PLOG(FATAL) << "couldn't set name for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700103 }
104
105 pid_t child_pid = fork();
106 if (child_pid == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700107 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700108 }
109
110 if (child_pid > 0) {
111 // So that we exit with the right status.
112 static int init_exitstatus = 0;
113 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
114
115 pid_t waited_pid;
116 int status;
117 while ((waited_pid = wait(&status)) > 0) {
118 // This loop will end when there are no processes left inside the
119 // PID namespace or when the init process inside the PID namespace
120 // gets a signal.
121 if (waited_pid == child_pid) {
122 init_exitstatus = status;
123 }
124 }
125 if (!WIFEXITED(init_exitstatus)) {
126 _exit(EXIT_FAILURE);
127 }
128 _exit(WEXITSTATUS(init_exitstatus));
129 }
130}
131
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400132static void ExpandArgs(const std::vector<std::string>& args, std::vector<char*>* strs) {
133 std::vector<std::string> expanded_args;
134 expanded_args.resize(args.size());
135 strs->push_back(const_cast<char*>(args[0].c_str()));
136 for (std::size_t i = 1; i < args.size(); ++i) {
137 if (!expand_props(args[i], &expanded_args[i])) {
138 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
139 }
140 strs->push_back(const_cast<char*>(expanded_args[i].c_str()));
141 }
142 strs->push_back(nullptr);
143}
144
Tom Cherrybac32992015-07-31 12:45:25 -0700145ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
146}
147
148ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
149 const std::string& value)
150 : name(name), value(value) {
151}
152
153Service::Service(const std::string& name, const std::string& classname,
154 const std::vector<std::string>& args)
Elliott Hughes9605a942016-11-10 17:43:47 -0800155 : name_(name), classname_(classname), flags_(0), pid_(0),
156 crash_count_(0), uid_(0), gid_(0), namespace_flags_(0),
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700157 seclabel_(""), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0),
Marco Nelissen310f6702016-07-22 12:07:06 -0700158 priority_(0), oom_score_adjust_(-1000), args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700159 onrestart_.InitSingleTrigger("onrestart");
160}
161
162Service::Service(const std::string& name, const std::string& classname,
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700163 unsigned flags, uid_t uid, gid_t gid,
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400164 const std::vector<gid_t>& supp_gids,
165 const CapSet& capabilities, unsigned namespace_flags,
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700166 const std::string& seclabel,
167 const std::vector<std::string>& args)
168 : name_(name), classname_(classname), flags_(flags), pid_(0),
Elliott Hughes9605a942016-11-10 17:43:47 -0800169 crash_count_(0), uid_(uid), gid_(gid),
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400170 supp_gids_(supp_gids), capabilities_(capabilities),
171 namespace_flags_(namespace_flags), seclabel_(seclabel),
172 ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), priority_(0),
173 oom_score_adjust_(-1000), args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700174 onrestart_.InitSingleTrigger("onrestart");
175}
176
177void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700178 if ((flags_ & SVC_EXEC) != 0) {
179 // 'exec' commands don't have properties tracking their state.
180 return;
181 }
182
Tom Cherryb7349902015-08-26 11:43:36 -0700183 std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700184 if (prop_name.length() >= PROP_NAME_MAX) {
185 // If the property name would be too long, we can't set it.
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700186 LOG(ERROR) << "Property name \"init.svc." << name_ << "\" too long; not setting to " << new_state;
Tom Cherrybac32992015-07-31 12:45:25 -0700187 return;
188 }
189
190 property_set(prop_name.c_str(), new_state.c_str());
Elliott Hughes9605a942016-11-10 17:43:47 -0800191
192 if (new_state == "running") {
193 prop_name += ".start";
194 uint64_t start_ns = time_started_.time_since_epoch().count();
195 property_set(prop_name.c_str(), StringPrintf("%" PRIu64, start_ns).c_str());
196 }
Tom Cherrybac32992015-07-31 12:45:25 -0700197}
198
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700199void Service::KillProcessGroup(int signal) {
Elliott Hughes1e730242016-08-02 14:20:40 -0700200 LOG(INFO) << "Sending signal " << signal
201 << " to service '" << name_
202 << "' (pid " << pid_ << ") process group...";
203 if (killProcessGroup(uid_, pid_, signal) == -1) {
204 PLOG(ERROR) << "killProcessGroup(" << uid_ << ", " << pid_ << ", " << signal << ") failed";
205 }
206 if (kill(-pid_, signal) == -1) {
207 PLOG(ERROR) << "kill(" << pid_ << ", " << signal << ") failed";
208 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700209}
210
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400211void Service::SetProcessAttributes() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400212 // Keep capabilites on uid change.
213 if (capabilities_.any() && uid_) {
214 if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED) != 0) {
215 PLOG(FATAL) << "prtcl(PR_SET_KEEPCAPS) failed for " << name_;
216 }
217 }
218
Elliott Hughese18e7e52016-07-25 18:18:16 -0700219 // TODO: work out why this fails for `console` then upgrade to FATAL.
220 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400221
222 if (gid_) {
223 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700224 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400225 }
226 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700227 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
228 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400229 }
230 if (uid_) {
231 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700232 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400233 }
234 }
235 if (!seclabel_.empty()) {
236 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700237 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400238 }
239 }
240 if (priority_ != 0) {
241 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700242 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400243 }
244 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400245 if (capabilities_.any()) {
246 if (!SetCapsForExec(capabilities_)) {
247 LOG(FATAL) << "cannot set capabilities for " << name_;
248 }
249 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400250}
251
Tom Cherrybac32992015-07-31 12:45:25 -0700252bool Service::Reap() {
253 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700254 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700255 }
256
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700257 // Remove any descriptor resources we may have created.
258 std::for_each(descriptors_.begin(), descriptors_.end(),
259 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700260
261 if (flags_ & SVC_EXEC) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700262 LOG(INFO) << "SVC_EXEC pid " << pid_ << " finished...";
Tom Cherrybac32992015-07-31 12:45:25 -0700263 return true;
264 }
265
266 pid_ = 0;
267 flags_ &= (~SVC_RUNNING);
268
269 // Oneshot processes go into the disabled state on exit,
270 // except when manually restarted.
271 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
272 flags_ |= SVC_DISABLED;
273 }
274
275 // Disabled and reset processes do not get restarted automatically.
276 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
277 NotifyStateChange("stopped");
278 return false;
279 }
280
Elliott Hughes9605a942016-11-10 17:43:47 -0800281 // If we crash > 4 times in 4 minutes, reboot into recovery.
282 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700283 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800284 if (now < time_crashed_ + 4min) {
285 if (++crash_count_ > 4) {
286 LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes; "
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700287 << "rebooting into recovery mode";
Tom Cherrybac32992015-07-31 12:45:25 -0700288 android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
289 return false;
290 }
291 } else {
292 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800293 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700294 }
295 }
296
297 flags_ &= (~SVC_RESTART);
298 flags_ |= SVC_RESTARTING;
299
300 // Execute all onrestart commands for this service.
301 onrestart_.ExecuteAllCommands();
302
303 NotifyStateChange("restarting");
304 return false;
305}
306
307void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700308 LOG(INFO) << "service " << name_;
309 LOG(INFO) << " class '" << classname_ << "'";
310 LOG(INFO) << " exec "<< android::base::Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700311 std::for_each(descriptors_.begin(), descriptors_.end(),
312 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700313}
314
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400315bool Service::ParseCapabilities(const std::vector<std::string>& args, std::string* err) {
316 capabilities_ = 0;
317
318 for (size_t i = 1; i < args.size(); i++) {
319 const std::string& arg = args[i];
320 int cap = LookupCap(arg);
321 if (cap == -1) {
322 *err = StringPrintf("invalid capability '%s'", arg.c_str());
323 return false;
324 }
325 capabilities_[cap] = true;
326 }
327 return true;
328}
329
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400330bool Service::ParseClass(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700331 classname_ = args[1];
332 return true;
333}
Tom Cherrybac32992015-07-31 12:45:25 -0700334
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400335bool Service::ParseConsole(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700336 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200337 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherryb7349902015-08-26 11:43:36 -0700338 return true;
339}
Tom Cherrybac32992015-07-31 12:45:25 -0700340
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400341bool Service::ParseCritical(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700342 flags_ |= SVC_CRITICAL;
343 return true;
344}
Tom Cherrybac32992015-07-31 12:45:25 -0700345
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400346bool Service::ParseDisabled(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700347 flags_ |= SVC_DISABLED;
348 flags_ |= SVC_RC_DISABLED;
349 return true;
350}
Tom Cherrybac32992015-07-31 12:45:25 -0700351
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400352bool Service::ParseGroup(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700353 gid_ = decode_uid(args[1].c_str());
354 for (std::size_t n = 2; n < args.size(); n++) {
355 supp_gids_.emplace_back(decode_uid(args[n].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700356 }
357 return true;
358}
359
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400360bool Service::ParsePriority(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700361 priority_ = 0;
362 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800363 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
364 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700365 *err = StringPrintf("process priority value must be range %d - %d",
366 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
367 return false;
368 }
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700369 return true;
370}
371
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400372bool Service::ParseIoprio(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700373 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherryb7349902015-08-26 11:43:36 -0700374 *err = "priority value must be range 0 - 7";
375 return false;
376 }
377
378 if (args[1] == "rt") {
379 ioprio_class_ = IoSchedClass_RT;
380 } else if (args[1] == "be") {
381 ioprio_class_ = IoSchedClass_BE;
382 } else if (args[1] == "idle") {
383 ioprio_class_ = IoSchedClass_IDLE;
384 } else {
385 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
386 return false;
387 }
388
389 return true;
390}
391
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400392bool Service::ParseKeycodes(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700393 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700394 int code;
395 if (ParseInt(args[i], &code)) {
396 keycodes_.emplace_back(code);
397 } else {
398 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
399 }
Tom Cherryb7349902015-08-26 11:43:36 -0700400 }
401 return true;
402}
403
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400404bool Service::ParseOneshot(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700405 flags_ |= SVC_ONESHOT;
406 return true;
407}
408
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400409bool Service::ParseOnrestart(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700410 std::vector<std::string> str_args(args.begin() + 1, args.end());
411 onrestart_.AddCommand(str_args, "", 0, err);
412 return true;
413}
414
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400415bool Service::ParseNamespace(const std::vector<std::string>& args, std::string* err) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700416 for (size_t i = 1; i < args.size(); i++) {
417 if (args[i] == "pid") {
418 namespace_flags_ |= CLONE_NEWPID;
419 // PID namespaces require mount namespaces.
420 namespace_flags_ |= CLONE_NEWNS;
421 } else if (args[i] == "mnt") {
422 namespace_flags_ |= CLONE_NEWNS;
423 } else {
424 *err = "namespace must be 'pid' or 'mnt'";
425 return false;
426 }
427 }
428 return true;
429}
430
Marco Nelissen310f6702016-07-22 12:07:06 -0700431bool Service::ParseOomScoreAdjust(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700432 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Marco Nelissen310f6702016-07-22 12:07:06 -0700433 *err = "oom_score_adjust value must be in range -1000 - +1000";
434 return false;
435 }
Marco Nelissen310f6702016-07-22 12:07:06 -0700436 return true;
437}
438
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400439bool Service::ParseSeclabel(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700440 seclabel_ = args[1];
441 return true;
442}
443
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400444bool Service::ParseSetenv(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700445 envvars_.emplace_back(args[1], args[2]);
446 return true;
447}
448
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700449template <typename T>
450bool Service::AddDescriptor(const std::vector<std::string>& args, std::string* err) {
451 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
452 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
453 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
454 std::string context = args.size() > 6 ? args[6] : "";
455
456 auto descriptor = std::make_unique<T>(args[1], args[2], uid, gid, perm, context);
457
458 auto old =
459 std::find_if(descriptors_.begin(), descriptors_.end(),
460 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
461
462 if (old != descriptors_.end()) {
463 *err = "duplicate descriptor " + args[1] + " " + args[2];
464 return false;
465 }
466
467 descriptors_.emplace_back(std::move(descriptor));
468 return true;
469}
470
471// name type perm [ uid gid context ]
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400472bool Service::ParseSocket(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700473 if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
474 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
475 return false;
476 }
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700477 return AddDescriptor<SocketInfo>(args, err);
478}
Tom Cherryb7349902015-08-26 11:43:36 -0700479
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700480// name type perm [ uid gid context ]
481bool Service::ParseFile(const std::vector<std::string>& args, std::string* err) {
482 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
483 *err = "file type must be 'r', 'w' or 'rw'";
484 return false;
485 }
486 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
487 *err = "file name must not be relative";
488 return false;
489 }
490 return AddDescriptor<FileInfo>(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700491}
492
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400493bool Service::ParseUser(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700494 uid_ = decode_uid(args[1].c_str());
495 return true;
496}
497
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400498bool Service::ParseWritepid(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700499 writepid_files_.assign(args.begin() + 1, args.end());
500 return true;
501}
502
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400503class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryb7349902015-08-26 11:43:36 -0700504public:
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400505 OptionParserMap() {
Tom Cherryb7349902015-08-26 11:43:36 -0700506 }
507private:
508 Map& map() const override;
509};
510
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400511Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700512 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400513 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400514 {"capabilities",
515 {1, kMax, &Service::ParseCapabilities}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400516 {"class", {1, 1, &Service::ParseClass}},
517 {"console", {0, 1, &Service::ParseConsole}},
518 {"critical", {0, 0, &Service::ParseCritical}},
519 {"disabled", {0, 0, &Service::ParseDisabled}},
520 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
521 {"ioprio", {2, 2, &Service::ParseIoprio}},
522 {"priority", {1, 1, &Service::ParsePriority}},
523 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
524 {"oneshot", {0, 0, &Service::ParseOneshot}},
525 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700526 {"oom_score_adjust",
527 {1, 1, &Service::ParseOomScoreAdjust}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400528 {"namespace", {1, 2, &Service::ParseNamespace}},
529 {"seclabel", {1, 1, &Service::ParseSeclabel}},
530 {"setenv", {2, 2, &Service::ParseSetenv}},
531 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700532 {"file", {2, 6, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400533 {"user", {1, 1, &Service::ParseUser}},
534 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700535 };
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400536 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700537}
538
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400539bool Service::ParseLine(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700540 if (args.empty()) {
541 *err = "option needed, but not provided";
542 return false;
543 }
544
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400545 static const OptionParserMap parser_map;
546 auto parser = parser_map.FindFunction(args[0], args.size() - 1, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700547
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400548 if (!parser) {
Tom Cherryb7349902015-08-26 11:43:36 -0700549 return false;
550 }
551
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400552 return (this->*parser)(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700553}
554
Elliott Hughesbdeac392016-04-12 15:38:27 -0700555bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700556 // Starting a service removes it from the disabled or reset state and
557 // immediately takes it out of the restarting state if it was in there.
558 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700559
560 // Running processes require no additional work --- if they're in the
561 // process of exiting, we've ensured that they will immediately restart
562 // on exit, unless they are ONESHOT.
563 if (flags_ & SVC_RUNNING) {
564 return false;
565 }
566
567 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200568 if (needs_console) {
569 if (console_.empty()) {
570 console_ = default_console;
571 }
572
573 bool have_console = (open(console_.c_str(), O_RDWR | O_CLOEXEC) != -1);
574 if (!have_console) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700575 PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200576 flags_ |= SVC_DISABLED;
577 return false;
578 }
Tom Cherrybac32992015-07-31 12:45:25 -0700579 }
580
581 struct stat sb;
582 if (stat(args_[0].c_str(), &sb) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700583 PLOG(ERROR) << "cannot find '" << args_[0] << "', disabling '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700584 flags_ |= SVC_DISABLED;
585 return false;
586 }
587
Tom Cherrybac32992015-07-31 12:45:25 -0700588 std::string scon;
589 if (!seclabel_.empty()) {
590 scon = seclabel_;
591 } else {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400592 LOG(INFO) << "computing context for service '" << name_ << "'";
593 scon = ComputeContextFromExecutable(name_, args_[0]);
594 if (scon == "") {
Tom Cherrybac32992015-07-31 12:45:25 -0700595 return false;
596 }
597 }
598
Wei Wanga285dac2016-10-04 14:05:39 -0700599 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700600
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700601 pid_t pid = -1;
602 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400603 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700604 } else {
605 pid = fork();
606 }
607
Tom Cherrybac32992015-07-31 12:45:25 -0700608 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700609 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700610
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700611 if (namespace_flags_ & CLONE_NEWPID) {
612 // This will fork again to run an init process inside the PID
613 // namespace.
614 SetUpPidNamespace(name_);
615 }
616
Tom Cherrybac32992015-07-31 12:45:25 -0700617 for (const auto& ei : envvars_) {
618 add_environment(ei.name.c_str(), ei.value.c_str());
619 }
620
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700621 std::for_each(descriptors_.begin(), descriptors_.end(),
622 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700623
Anestis Bechtsoudisb702b462016-02-05 16:38:48 +0200624 std::string pid_str = StringPrintf("%d", getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700625 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700626 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700627 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700628 }
629 }
630
631 if (ioprio_class_ != IoSchedClass_NONE) {
632 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400633 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700634 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700635 }
636 }
637
638 if (needs_console) {
639 setsid();
640 OpenConsole();
641 } else {
642 ZapStdio();
643 }
644
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400645 // As requested, set our gid, supplemental gids, uid, context, and
646 // priority. Aborts on failure.
647 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700648
Tom Cherrybac32992015-07-31 12:45:25 -0700649 std::vector<char*> strs;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400650 ExpandArgs(args_, &strs);
Tom Cherrybac35362016-06-07 11:22:00 -0700651 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700652 PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700653 }
654
655 _exit(127);
656 }
657
658 if (pid < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700659 PLOG(ERROR) << "failed to fork for '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700660 pid_ = 0;
661 return false;
662 }
663
Marco Nelissen310f6702016-07-22 12:07:06 -0700664 if (oom_score_adjust_ != -1000) {
665 std::string oom_str = StringPrintf("%d", oom_score_adjust_);
666 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
667 if (!WriteStringToFile(oom_str, oom_file)) {
668 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
669 }
670 }
671
Elliott Hughes9605a942016-11-10 17:43:47 -0800672 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700673 pid_ = pid;
674 flags_ |= SVC_RUNNING;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700675
676 errno = -createProcessGroup(uid_, pid_);
677 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400678 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
679 << name_ << "'";
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700680 }
Tom Cherrybac32992015-07-31 12:45:25 -0700681
682 if ((flags_ & SVC_EXEC) != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400683 LOG(INFO) << android::base::StringPrintf(
684 "SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...", pid_, uid_, gid_,
685 supp_gids_.size(), !seclabel_.empty() ? seclabel_.c_str() : "default");
Tom Cherrybac32992015-07-31 12:45:25 -0700686 }
687
688 NotifyStateChange("running");
689 return true;
690}
691
Tom Cherrybac32992015-07-31 12:45:25 -0700692bool Service::StartIfNotDisabled() {
693 if (!(flags_ & SVC_DISABLED)) {
694 return Start();
695 } else {
696 flags_ |= SVC_DISABLED_START;
697 }
698 return true;
699}
700
701bool Service::Enable() {
702 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
703 if (flags_ & SVC_DISABLED_START) {
704 return Start();
705 }
706 return true;
707}
708
709void Service::Reset() {
710 StopOrReset(SVC_RESET);
711}
712
713void Service::Stop() {
714 StopOrReset(SVC_DISABLED);
715}
716
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800717void Service::Terminate() {
718 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
719 flags_ |= SVC_DISABLED;
720 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700721 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800722 NotifyStateChange("stopping");
723 }
724}
725
Tom Cherrybac32992015-07-31 12:45:25 -0700726void Service::Restart() {
727 if (flags_ & SVC_RUNNING) {
728 /* Stop, wait, then start the service. */
729 StopOrReset(SVC_RESTART);
730 } else if (!(flags_ & SVC_RESTARTING)) {
731 /* Just start the service since it's not running. */
732 Start();
733 } /* else: Service is restarting anyways. */
734}
735
Elliott Hughes9605a942016-11-10 17:43:47 -0800736void Service::RestartIfNeeded(time_t* process_needs_restart_at) {
737 boot_clock::time_point now = boot_clock::now();
738 boot_clock::time_point next_start = time_started_ + 5s;
739 if (now > next_start) {
Tom Cherrybac32992015-07-31 12:45:25 -0700740 flags_ &= (~SVC_RESTARTING);
741 Start();
742 return;
743 }
744
Elliott Hughes9605a942016-11-10 17:43:47 -0800745 time_t next_start_time_t = time(nullptr) +
746 time_t(std::chrono::duration_cast<std::chrono::seconds>(next_start - now).count());
747 if (next_start_time_t < *process_needs_restart_at || *process_needs_restart_at == 0) {
748 *process_needs_restart_at = next_start_time_t;
Tom Cherrybac32992015-07-31 12:45:25 -0700749 }
750}
751
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700752// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700753void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700754 // The service is still SVC_RUNNING until its process exits, but if it has
755 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700756 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
757
758 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700759 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700760 how = SVC_DISABLED;
761 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700762
763 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700764 if (how == SVC_RESET) {
765 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
766 } else {
767 flags_ |= how;
768 }
769
770 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700771 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700772 NotifyStateChange("stopping");
773 } else {
774 NotifyStateChange("stopped");
775 }
776}
777
778void Service::ZapStdio() const {
779 int fd;
780 fd = open("/dev/null", O_RDWR);
781 dup2(fd, 0);
782 dup2(fd, 1);
783 dup2(fd, 2);
784 close(fd);
785}
786
787void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200788 int fd = open(console_.c_str(), O_RDWR);
789 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700790 ioctl(fd, TIOCSCTTY, 0);
791 dup2(fd, 0);
792 dup2(fd, 1);
793 dup2(fd, 2);
794 close(fd);
795}
796
Tom Cherrybac32992015-07-31 12:45:25 -0700797int ServiceManager::exec_count_ = 0;
798
799ServiceManager::ServiceManager() {
800}
801
802ServiceManager& ServiceManager::GetInstance() {
803 static ServiceManager instance;
804 return instance;
805}
806
Tom Cherryb7349902015-08-26 11:43:36 -0700807void ServiceManager::AddService(std::unique_ptr<Service> service) {
808 Service* old_service = FindServiceByName(service->name());
809 if (old_service) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700810 LOG(ERROR) << "ignored duplicate definition of service '" << service->name() << "'";
Tom Cherryb7349902015-08-26 11:43:36 -0700811 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700812 }
Tom Cherryb7349902015-08-26 11:43:36 -0700813 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700814}
815
816Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
817 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
818 // SECLABEL can be a - to denote default
819 std::size_t command_arg = 1;
820 for (std::size_t i = 1; i < args.size(); ++i) {
821 if (args[i] == "--") {
822 command_arg = i + 1;
823 break;
824 }
825 }
826 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700827 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -0700828 return nullptr;
829 }
830
831 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700832 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -0700833 return nullptr;
834 }
835 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
836
837 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700838 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700839 unsigned flags = SVC_EXEC | SVC_ONESHOT;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400840 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700841 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700842
843 std::string seclabel = "";
844 if (command_arg > 2 && args[1] != "-") {
845 seclabel = args[1];
846 }
847 uid_t uid = 0;
848 if (command_arg > 3) {
849 uid = decode_uid(args[2].c_str());
850 }
851 gid_t gid = 0;
852 std::vector<gid_t> supp_gids;
853 if (command_arg > 4) {
854 gid = decode_uid(args[3].c_str());
855 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
856 for (size_t i = 0; i < nr_supp_gids; ++i) {
857 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
858 }
859 }
860
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400861 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid, supp_gids,
862 no_capabilities, namespace_flags, seclabel,
863 str_args));
Tom Cherrybac32992015-07-31 12:45:25 -0700864 if (!svc_p) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700865 LOG(ERROR) << "Couldn't allocate service for exec of '" << str_args[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700866 return nullptr;
867 }
868 Service* svc = svc_p.get();
869 services_.push_back(std::move(svc_p));
870
871 return svc;
872}
873
874Service* ServiceManager::FindServiceByName(const std::string& name) const {
875 auto svc = std::find_if(services_.begin(), services_.end(),
876 [&name] (const std::unique_ptr<Service>& s) {
877 return name == s->name();
878 });
879 if (svc != services_.end()) {
880 return svc->get();
881 }
882 return nullptr;
883}
884
885Service* ServiceManager::FindServiceByPid(pid_t pid) const {
886 auto svc = std::find_if(services_.begin(), services_.end(),
887 [&pid] (const std::unique_ptr<Service>& s) {
888 return s->pid() == pid;
889 });
890 if (svc != services_.end()) {
891 return svc->get();
892 }
893 return nullptr;
894}
895
896Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
897 auto svc = std::find_if(services_.begin(), services_.end(),
898 [&keychord_id] (const std::unique_ptr<Service>& s) {
899 return s->keychord_id() == keychord_id;
900 });
901
902 if (svc != services_.end()) {
903 return svc->get();
904 }
905 return nullptr;
906}
907
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -0700908void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700909 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800910 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -0700911 }
912}
913
914void ServiceManager::ForEachServiceInClass(const std::string& classname,
915 void (*func)(Service* svc)) const {
916 for (const auto& s : services_) {
917 if (classname == s->classname()) {
918 func(s.get());
919 }
920 }
921}
922
923void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
924 void (*func)(Service* svc)) const {
925 for (const auto& s : services_) {
926 if (s->flags() & matchflags) {
927 func(s.get());
928 }
929 }
930}
931
Tom Cherryb7349902015-08-26 11:43:36 -0700932void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -0700933 auto svc_it = std::find_if(services_.begin(), services_.end(),
934 [&svc] (const std::unique_ptr<Service>& s) {
935 return svc.name() == s->name();
936 });
937 if (svc_it == services_.end()) {
938 return;
939 }
940
941 services_.erase(svc_it);
942}
943
Tom Cherryb7349902015-08-26 11:43:36 -0700944void ServiceManager::DumpState() const {
945 for (const auto& s : services_) {
946 s->DumpState();
947 }
Tom Cherryb7349902015-08-26 11:43:36 -0700948}
949
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800950bool ServiceManager::ReapOneProcess() {
951 int status;
952 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
953 if (pid == 0) {
954 return false;
955 } else if (pid == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700956 PLOG(ERROR) << "waitpid failed";
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800957 return false;
958 }
959
960 Service* svc = FindServiceByPid(pid);
961
962 std::string name;
963 if (svc) {
964 name = android::base::StringPrintf("Service '%s' (pid %d)",
965 svc->name().c_str(), pid);
966 } else {
967 name = android::base::StringPrintf("Untracked pid %d", pid);
968 }
969
970 if (WIFEXITED(status)) {
Wei Wanga285dac2016-10-04 14:05:39 -0700971 LOG(INFO) << name << " exited with status " << WEXITSTATUS(status);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800972 } else if (WIFSIGNALED(status)) {
Wei Wanga285dac2016-10-04 14:05:39 -0700973 LOG(INFO) << name << " killed by signal " << WTERMSIG(status);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800974 } else if (WIFSTOPPED(status)) {
Wei Wanga285dac2016-10-04 14:05:39 -0700975 LOG(INFO) << name << " stopped by signal " << WSTOPSIG(status);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800976 } else {
Wei Wanga285dac2016-10-04 14:05:39 -0700977 LOG(INFO) << name << " state changed";
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800978 }
979
980 if (!svc) {
981 return true;
982 }
983
984 if (svc->Reap()) {
985 waiting_for_exec = false;
986 RemoveService(*svc);
987 }
988
989 return true;
990}
991
992void ServiceManager::ReapAnyOutstandingChildren() {
993 while (ReapOneProcess()) {
994 }
995}
996
Tom Cherryb7349902015-08-26 11:43:36 -0700997bool ServiceParser::ParseSection(const std::vector<std::string>& args,
998 std::string* err) {
999 if (args.size() < 3) {
1000 *err = "services must have a name and a program";
1001 return false;
1002 }
1003
1004 const std::string& name = args[1];
1005 if (!IsValidName(name)) {
1006 *err = StringPrintf("invalid service name '%s'", name.c_str());
1007 return false;
1008 }
1009
1010 std::vector<std::string> str_args(args.begin() + 2, args.end());
1011 service_ = std::make_unique<Service>(name, "default", str_args);
1012 return true;
1013}
1014
1015bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
1016 const std::string& filename, int line,
1017 std::string* err) const {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -04001018 return service_ ? service_->ParseLine(args, err) : false;
Tom Cherryb7349902015-08-26 11:43:36 -07001019}
1020
1021void ServiceParser::EndSection() {
1022 if (service_) {
1023 ServiceManager::GetInstance().AddService(std::move(service_));
1024 }
1025}
1026
1027bool ServiceParser::IsValidName(const std::string& name) const {
Iliyan Malchevf6554802016-09-19 20:58:20 -07001028 return is_legal_property_name("init.svc." + name);
Tom Cherrybac32992015-07-31 12:45:25 -07001029}