blob: f2e5d228cb831f2735e7fe91878fac76cd3c09c4 [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;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070048using android::base::GetProperty;
49using android::base::Join;
Elliott Hughesda46b392016-10-11 17:09:00 -070050using android::base::ParseInt;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070051using android::base::StartsWith;
Tom Cherryb7349902015-08-26 11:43:36 -070052using android::base::StringPrintf;
53using android::base::WriteStringToFile;
54
Tom Cherry81f5d3e2017-06-22 12:53:17 -070055namespace android {
56namespace init {
57
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040058static std::string ComputeContextFromExecutable(std::string& service_name,
59 const std::string& service_path) {
60 std::string computed_context;
61
62 char* raw_con = nullptr;
63 char* raw_filecon = nullptr;
64
65 if (getcon(&raw_con) == -1) {
66 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
67 return "";
68 }
69 std::unique_ptr<char> mycon(raw_con);
70
71 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
72 LOG(ERROR) << "could not get file context while starting '" << service_name << "'";
73 return "";
74 }
75 std::unique_ptr<char> filecon(raw_filecon);
76
77 char* new_con = nullptr;
78 int rc = security_compute_create(mycon.get(), filecon.get(),
79 string_to_security_class("process"), &new_con);
80 if (rc == 0) {
81 computed_context = new_con;
82 free(new_con);
83 }
84 if (rc == 0 && computed_context == mycon.get()) {
85 LOG(ERROR) << "service " << service_name << " does not have a SELinux domain defined";
86 return "";
87 }
88 if (rc < 0) {
89 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
90 return "";
91 }
92 return computed_context;
93}
94
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070095static void SetUpPidNamespace(const std::string& service_name) {
96 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
97
98 // It's OK to LOG(FATAL) in this function since it's running in the first
99 // child process.
100 if (mount("", "/proc", "proc", kSafeFlags | MS_REMOUNT, "") == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700101 PLOG(FATAL) << "couldn't remount(/proc) for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700102 }
103
104 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700105 PLOG(FATAL) << "couldn't set name for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700106 }
107
108 pid_t child_pid = fork();
109 if (child_pid == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700110 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700111 }
112
113 if (child_pid > 0) {
114 // So that we exit with the right status.
115 static int init_exitstatus = 0;
116 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
117
118 pid_t waited_pid;
119 int status;
120 while ((waited_pid = wait(&status)) > 0) {
121 // This loop will end when there are no processes left inside the
122 // PID namespace or when the init process inside the PID namespace
123 // gets a signal.
124 if (waited_pid == child_pid) {
125 init_exitstatus = status;
126 }
127 }
128 if (!WIFEXITED(init_exitstatus)) {
129 _exit(EXIT_FAILURE);
130 }
131 _exit(WEXITSTATUS(init_exitstatus));
132 }
133}
134
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400135static void ExpandArgs(const std::vector<std::string>& args, std::vector<char*>* strs) {
136 std::vector<std::string> expanded_args;
137 expanded_args.resize(args.size());
138 strs->push_back(const_cast<char*>(args[0].c_str()));
139 for (std::size_t i = 1; i < args.size(); ++i) {
140 if (!expand_props(args[i], &expanded_args[i])) {
141 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
142 }
143 strs->push_back(const_cast<char*>(expanded_args[i].c_str()));
144 }
145 strs->push_back(nullptr);
146}
147
Tom Cherrybac32992015-07-31 12:45:25 -0700148ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
149}
150
151ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
152 const std::string& value)
153 : name(name), value(value) {
154}
155
Wei Wang641ff0a2017-03-27 10:59:11 -0700156Service::Service(const std::string& name, const std::vector<std::string>& args)
157 : name_(name),
158 classnames_({"default"}),
159 flags_(0),
160 pid_(0),
161 crash_count_(0),
162 uid_(0),
163 gid_(0),
164 namespace_flags_(0),
165 seclabel_(""),
Tom Cherry012c5732017-04-18 13:21:54 -0700166 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Tom Cherry7da54852017-05-01 14:16:41 -0700167 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700168 ioprio_class_(IoSchedClass_NONE),
169 ioprio_pri_(0),
170 priority_(0),
171 oom_score_adjust_(-1000),
172 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700173 onrestart_.InitSingleTrigger("onrestart");
174}
175
Wei Wang641ff0a2017-03-27 10:59:11 -0700176Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
177 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
178 unsigned namespace_flags, const std::string& seclabel,
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700179 const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700180 : name_(name),
181 classnames_({"default"}),
182 flags_(flags),
183 pid_(0),
184 crash_count_(0),
185 uid_(uid),
186 gid_(gid),
187 supp_gids_(supp_gids),
188 capabilities_(capabilities),
189 namespace_flags_(namespace_flags),
190 seclabel_(seclabel),
Tom Cherry012c5732017-04-18 13:21:54 -0700191 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Tom Cherry7da54852017-05-01 14:16:41 -0700192 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700193 ioprio_class_(IoSchedClass_NONE),
194 ioprio_pri_(0),
195 priority_(0),
196 oom_score_adjust_(-1000),
197 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700198 onrestart_.InitSingleTrigger("onrestart");
199}
200
201void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700202 if ((flags_ & SVC_TEMPORARY) != 0) {
203 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700204 return;
205 }
206
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700207 std::string prop_name = "init.svc." + name_;
208 property_set(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800209
210 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800211 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700212 property_set("ro.boottime." + name_, std::to_string(start_ns));
Elliott Hughes9605a942016-11-10 17:43:47 -0800213 }
Tom Cherrybac32992015-07-31 12:45:25 -0700214}
215
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700216void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700217 // If we've already seen a successful result from killProcessGroup*(), then we have removed
218 // the cgroup already and calling these functions a second time will simply result in an error.
219 // This is true regardless of which signal was sent.
220 // These functions handle their own logging, so no additional logging is needed.
221 if (!process_cgroup_empty_) {
222 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
223 << ") process group...";
224 int r;
225 if (signal == SIGTERM) {
226 r = killProcessGroupOnce(uid_, pid_, signal);
227 } else {
228 r = killProcessGroup(uid_, pid_, signal);
229 }
230
231 if (r == 0) process_cgroup_empty_ = true;
232 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700233}
234
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400235void Service::SetProcessAttributes() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400236 // Keep capabilites on uid change.
237 if (capabilities_.any() && uid_) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700238 // If Android is running in a container, some securebits might already
239 // be locked, so don't change those.
240 int64_t securebits = prctl(PR_GET_SECUREBITS);
241 if (securebits == -1) {
242 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
243 }
244 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
245 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
246 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400247 }
248 }
249
Elliott Hughese18e7e52016-07-25 18:18:16 -0700250 // TODO: work out why this fails for `console` then upgrade to FATAL.
251 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400252
253 if (gid_) {
254 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700255 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400256 }
257 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700258 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
259 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400260 }
261 if (uid_) {
262 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700263 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400264 }
265 }
266 if (!seclabel_.empty()) {
267 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700268 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400269 }
270 }
271 if (priority_ != 0) {
272 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700273 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400274 }
275 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400276 if (capabilities_.any()) {
277 if (!SetCapsForExec(capabilities_)) {
278 LOG(FATAL) << "cannot set capabilities for " << name_;
279 }
280 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400281}
282
Tom Cherryb27004a2017-03-27 16:27:30 -0700283void Service::Reap() {
Tom Cherrybac32992015-07-31 12:45:25 -0700284 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700285 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700286 }
287
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700288 // Remove any descriptor resources we may have created.
289 std::for_each(descriptors_.begin(), descriptors_.end(),
290 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700291
Tom Cherryb27004a2017-03-27 16:27:30 -0700292 if (flags_ & SVC_TEMPORARY) {
293 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700294 }
295
296 pid_ = 0;
297 flags_ &= (~SVC_RUNNING);
298
299 // Oneshot processes go into the disabled state on exit,
300 // except when manually restarted.
301 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
302 flags_ |= SVC_DISABLED;
303 }
304
305 // Disabled and reset processes do not get restarted automatically.
306 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
307 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700308 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700309 }
310
Elliott Hughes9605a942016-11-10 17:43:47 -0800311 // If we crash > 4 times in 4 minutes, reboot into recovery.
312 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700313 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800314 if (now < time_crashed_ + 4min) {
315 if (++crash_count_ > 4) {
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000316 LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
317 panic();
Tom Cherrybac32992015-07-31 12:45:25 -0700318 }
319 } else {
320 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800321 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700322 }
323 }
324
325 flags_ &= (~SVC_RESTART);
326 flags_ |= SVC_RESTARTING;
327
328 // Execute all onrestart commands for this service.
329 onrestart_.ExecuteAllCommands();
330
331 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700332 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700333}
334
335void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700336 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700337 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
338 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700339 std::for_each(descriptors_.begin(), descriptors_.end(),
340 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700341}
342
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400343bool Service::ParseCapabilities(const std::vector<std::string>& args, std::string* err) {
344 capabilities_ = 0;
345
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500346 if (!CapAmbientSupported()) {
347 *err = "capabilities requested but the kernel does not support ambient capabilities";
348 return false;
349 }
350
351 unsigned int last_valid_cap = GetLastValidCap();
352 if (last_valid_cap >= capabilities_.size()) {
353 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
354 }
355
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400356 for (size_t i = 1; i < args.size(); i++) {
357 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500358 int res = LookupCap(arg);
359 if (res < 0) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400360 *err = StringPrintf("invalid capability '%s'", arg.c_str());
361 return false;
362 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500363 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
364 if (cap > last_valid_cap) {
365 *err = StringPrintf("capability '%s' not supported by the kernel", arg.c_str());
366 return false;
367 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400368 capabilities_[cap] = true;
369 }
370 return true;
371}
372
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400373bool Service::ParseClass(const std::vector<std::string>& args, std::string* err) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700374 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherryb7349902015-08-26 11:43:36 -0700375 return true;
376}
Tom Cherrybac32992015-07-31 12:45:25 -0700377
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400378bool Service::ParseConsole(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700379 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200380 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherryb7349902015-08-26 11:43:36 -0700381 return true;
382}
Tom Cherrybac32992015-07-31 12:45:25 -0700383
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400384bool Service::ParseCritical(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700385 flags_ |= SVC_CRITICAL;
386 return true;
387}
Tom Cherrybac32992015-07-31 12:45:25 -0700388
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400389bool Service::ParseDisabled(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700390 flags_ |= SVC_DISABLED;
391 flags_ |= SVC_RC_DISABLED;
392 return true;
393}
Tom Cherrybac32992015-07-31 12:45:25 -0700394
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400395bool Service::ParseGroup(const std::vector<std::string>& args, std::string* err) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700396 std::string decode_uid_err;
397 if (!DecodeUid(args[1], &gid_, &decode_uid_err)) {
398 *err = "Unable to find GID for '" + args[1] + "': " + decode_uid_err;
399 return false;
400 }
Tom Cherryb7349902015-08-26 11:43:36 -0700401 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700402 gid_t gid;
403 if (!DecodeUid(args[n], &gid, &decode_uid_err)) {
404 *err = "Unable to find GID for '" + args[n] + "': " + decode_uid_err;
405 return false;
406 }
407 supp_gids_.emplace_back(gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700408 }
409 return true;
410}
411
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400412bool Service::ParsePriority(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700413 priority_ = 0;
414 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800415 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
416 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700417 *err = StringPrintf("process priority value must be range %d - %d",
418 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
419 return false;
420 }
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700421 return true;
422}
423
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400424bool Service::ParseIoprio(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700425 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherryb7349902015-08-26 11:43:36 -0700426 *err = "priority value must be range 0 - 7";
427 return false;
428 }
429
430 if (args[1] == "rt") {
431 ioprio_class_ = IoSchedClass_RT;
432 } else if (args[1] == "be") {
433 ioprio_class_ = IoSchedClass_BE;
434 } else if (args[1] == "idle") {
435 ioprio_class_ = IoSchedClass_IDLE;
436 } else {
437 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
438 return false;
439 }
440
441 return true;
442}
443
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400444bool Service::ParseKeycodes(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700445 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700446 int code;
447 if (ParseInt(args[i], &code)) {
448 keycodes_.emplace_back(code);
449 } else {
450 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
451 }
Tom Cherryb7349902015-08-26 11:43:36 -0700452 }
453 return true;
454}
455
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400456bool Service::ParseOneshot(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700457 flags_ |= SVC_ONESHOT;
458 return true;
459}
460
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400461bool Service::ParseOnrestart(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700462 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700463 int line = onrestart_.NumCommands() + 1;
464 onrestart_.AddCommand(str_args, line, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700465 return true;
466}
467
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400468bool Service::ParseNamespace(const std::vector<std::string>& args, std::string* err) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700469 for (size_t i = 1; i < args.size(); i++) {
470 if (args[i] == "pid") {
471 namespace_flags_ |= CLONE_NEWPID;
472 // PID namespaces require mount namespaces.
473 namespace_flags_ |= CLONE_NEWNS;
474 } else if (args[i] == "mnt") {
475 namespace_flags_ |= CLONE_NEWNS;
476 } else {
477 *err = "namespace must be 'pid' or 'mnt'";
478 return false;
479 }
480 }
481 return true;
482}
483
Marco Nelissen310f6702016-07-22 12:07:06 -0700484bool Service::ParseOomScoreAdjust(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700485 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Marco Nelissen310f6702016-07-22 12:07:06 -0700486 *err = "oom_score_adjust value must be in range -1000 - +1000";
487 return false;
488 }
Marco Nelissen310f6702016-07-22 12:07:06 -0700489 return true;
490}
491
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400492bool Service::ParseSeclabel(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700493 seclabel_ = args[1];
494 return true;
495}
496
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400497bool Service::ParseSetenv(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700498 envvars_.emplace_back(args[1], args[2]);
499 return true;
500}
501
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700502template <typename T>
503bool Service::AddDescriptor(const std::vector<std::string>& args, std::string* err) {
504 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry517e1f12017-05-04 17:40:33 -0700505 uid_t uid = 0;
506 gid_t gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700507 std::string context = args.size() > 6 ? args[6] : "";
508
Tom Cherry517e1f12017-05-04 17:40:33 -0700509 std::string decode_uid_err;
510 if (args.size() > 4) {
511 if (!DecodeUid(args[4], &uid, &decode_uid_err)) {
512 *err = "Unable to find UID for '" + args[4] + "': " + decode_uid_err;
513 return false;
514 }
515 }
516
517 if (args.size() > 5) {
518 if (!DecodeUid(args[5], &gid, &decode_uid_err)) {
519 *err = "Unable to find GID for '" + args[5] + "': " + decode_uid_err;
520 return false;
521 }
522 }
523
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700524 auto descriptor = std::make_unique<T>(args[1], args[2], uid, gid, perm, context);
525
526 auto old =
527 std::find_if(descriptors_.begin(), descriptors_.end(),
528 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
529
530 if (old != descriptors_.end()) {
531 *err = "duplicate descriptor " + args[1] + " " + args[2];
532 return false;
533 }
534
535 descriptors_.emplace_back(std::move(descriptor));
536 return true;
537}
538
539// name type perm [ uid gid context ]
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400540bool Service::ParseSocket(const std::vector<std::string>& args, std::string* err) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700541 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
542 !StartsWith(args[2], "seqpacket")) {
Tom Cherryb7349902015-08-26 11:43:36 -0700543 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
544 return false;
545 }
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700546 return AddDescriptor<SocketInfo>(args, err);
547}
Tom Cherryb7349902015-08-26 11:43:36 -0700548
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700549// name type perm [ uid gid context ]
550bool Service::ParseFile(const std::vector<std::string>& args, std::string* err) {
551 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
552 *err = "file type must be 'r', 'w' or 'rw'";
553 return false;
554 }
555 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
556 *err = "file name must not be relative";
557 return false;
558 }
559 return AddDescriptor<FileInfo>(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700560}
561
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400562bool Service::ParseUser(const std::vector<std::string>& args, std::string* err) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700563 std::string decode_uid_err;
564 if (!DecodeUid(args[1], &uid_, &decode_uid_err)) {
565 *err = "Unable to find UID for '" + args[1] + "': " + decode_uid_err;
566 return false;
567 }
Tom Cherryb7349902015-08-26 11:43:36 -0700568 return true;
569}
570
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400571bool Service::ParseWritepid(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700572 writepid_files_.assign(args.begin() + 1, args.end());
573 return true;
574}
575
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400576class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700577 public:
578 OptionParserMap() {}
579
580 private:
581 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700582};
583
Tom Cherryad54d092017-04-19 16:18:50 -0700584const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700585 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700586 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400587 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400588 {"capabilities",
589 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700590 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400591 {"console", {0, 1, &Service::ParseConsole}},
592 {"critical", {0, 0, &Service::ParseCritical}},
593 {"disabled", {0, 0, &Service::ParseDisabled}},
594 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
595 {"ioprio", {2, 2, &Service::ParseIoprio}},
596 {"priority", {1, 1, &Service::ParsePriority}},
597 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
598 {"oneshot", {0, 0, &Service::ParseOneshot}},
599 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700600 {"oom_score_adjust",
601 {1, 1, &Service::ParseOomScoreAdjust}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400602 {"namespace", {1, 2, &Service::ParseNamespace}},
603 {"seclabel", {1, 1, &Service::ParseSeclabel}},
604 {"setenv", {2, 2, &Service::ParseSetenv}},
605 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn978fd0e2016-12-02 08:05:22 -0800606 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400607 {"user", {1, 1, &Service::ParseUser}},
608 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700609 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700610 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400611 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700612}
613
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400614bool Service::ParseLine(const std::vector<std::string>& args, std::string* err) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400615 static const OptionParserMap parser_map;
Tom Cherryfe062052017-04-24 16:59:05 -0700616 auto parser = parser_map.FindFunction(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700617
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400618 if (!parser) {
Tom Cherryb7349902015-08-26 11:43:36 -0700619 return false;
620 }
621
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400622 return (this->*parser)(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700623}
624
Tom Cherryb27004a2017-03-27 16:27:30 -0700625bool Service::ExecStart(std::unique_ptr<Timer>* exec_waiter) {
626 flags_ |= SVC_EXEC | SVC_ONESHOT;
627
628 exec_waiter->reset(new Timer);
629
630 if (!Start()) {
631 exec_waiter->reset();
632 return false;
633 }
634 return true;
635}
636
Elliott Hughesbdeac392016-04-12 15:38:27 -0700637bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700638 // Starting a service removes it from the disabled or reset state and
639 // immediately takes it out of the restarting state if it was in there.
640 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700641
642 // Running processes require no additional work --- if they're in the
643 // process of exiting, we've ensured that they will immediately restart
644 // on exit, unless they are ONESHOT.
645 if (flags_ & SVC_RUNNING) {
646 return false;
647 }
648
649 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200650 if (needs_console) {
651 if (console_.empty()) {
652 console_ = default_console;
653 }
654
Adrian Salido24ef8602016-12-20 15:52:15 -0800655 // Make sure that open call succeeds to ensure a console driver is
656 // properly registered for the device node
657 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
658 if (console_fd < 0) {
659 PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200660 flags_ |= SVC_DISABLED;
661 return false;
662 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800663 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700664 }
665
666 struct stat sb;
667 if (stat(args_[0].c_str(), &sb) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700668 PLOG(ERROR) << "cannot find '" << args_[0] << "', disabling '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700669 flags_ |= SVC_DISABLED;
670 return false;
671 }
672
Tom Cherrybac32992015-07-31 12:45:25 -0700673 std::string scon;
674 if (!seclabel_.empty()) {
675 scon = seclabel_;
676 } else {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400677 scon = ComputeContextFromExecutable(name_, args_[0]);
678 if (scon == "") {
Tom Cherrybac32992015-07-31 12:45:25 -0700679 return false;
680 }
681 }
682
Wei Wanga285dac2016-10-04 14:05:39 -0700683 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700684
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700685 pid_t pid = -1;
686 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400687 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700688 } else {
689 pid = fork();
690 }
691
Tom Cherrybac32992015-07-31 12:45:25 -0700692 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700693 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700694
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700695 if (namespace_flags_ & CLONE_NEWPID) {
696 // This will fork again to run an init process inside the PID
697 // namespace.
698 SetUpPidNamespace(name_);
699 }
700
Tom Cherrybac32992015-07-31 12:45:25 -0700701 for (const auto& ei : envvars_) {
702 add_environment(ei.name.c_str(), ei.value.c_str());
703 }
704
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700705 std::for_each(descriptors_.begin(), descriptors_.end(),
706 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700707
Alex Vakulenko08286762016-05-03 12:00:00 -0700708 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
709 auto cpuset_predicate = [](const std::string& path) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700710 return StartsWith(path, "/dev/cpuset/");
Alex Vakulenko08286762016-05-03 12:00:00 -0700711 };
712 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
713 if (iter == writepid_files_.end()) {
714 // There were no "writepid" instructions for cpusets, check if the system default
715 // cpuset is specified to be used for the process.
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700716 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700717 if (!default_cpuset.empty()) {
718 // Make sure the cpuset name starts and ends with '/'.
719 // A single '/' means the 'root' cpuset.
720 if (default_cpuset.front() != '/') {
721 default_cpuset.insert(0, 1, '/');
722 }
723 if (default_cpuset.back() != '/') {
724 default_cpuset.push_back('/');
725 }
726 writepid_files_.push_back(
727 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
728 }
729 }
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700730 std::string pid_str = std::to_string(getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700731 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700732 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700733 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700734 }
735 }
736
737 if (ioprio_class_ != IoSchedClass_NONE) {
738 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400739 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700740 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700741 }
742 }
743
744 if (needs_console) {
745 setsid();
746 OpenConsole();
747 } else {
748 ZapStdio();
749 }
750
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400751 // As requested, set our gid, supplemental gids, uid, context, and
752 // priority. Aborts on failure.
753 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700754
Tom Cherrybac32992015-07-31 12:45:25 -0700755 std::vector<char*> strs;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400756 ExpandArgs(args_, &strs);
Tom Cherrybac35362016-06-07 11:22:00 -0700757 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700758 PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700759 }
760
761 _exit(127);
762 }
763
764 if (pid < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700765 PLOG(ERROR) << "failed to fork for '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700766 pid_ = 0;
767 return false;
768 }
769
Marco Nelissen310f6702016-07-22 12:07:06 -0700770 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700771 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700772 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
773 if (!WriteStringToFile(oom_str, oom_file)) {
774 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
775 }
776 }
777
Elliott Hughes9605a942016-11-10 17:43:47 -0800778 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700779 pid_ = pid;
780 flags_ |= SVC_RUNNING;
Tom Cherry33838b12017-05-04 11:32:36 -0700781 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700782
783 errno = -createProcessGroup(uid_, pid_);
784 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400785 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
786 << name_ << "'";
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700787 }
Tom Cherrybac32992015-07-31 12:45:25 -0700788
789 if ((flags_ & SVC_EXEC) != 0) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700790 LOG(INFO) << "SVC_EXEC pid " << pid_ << " (uid " << uid_ << " gid " << gid_ << "+"
791 << supp_gids_.size() << " context "
792 << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
Tom Cherrybac32992015-07-31 12:45:25 -0700793 }
794
795 NotifyStateChange("running");
796 return true;
797}
798
Tom Cherrybac32992015-07-31 12:45:25 -0700799bool Service::StartIfNotDisabled() {
800 if (!(flags_ & SVC_DISABLED)) {
801 return Start();
802 } else {
803 flags_ |= SVC_DISABLED_START;
804 }
805 return true;
806}
807
808bool Service::Enable() {
809 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
810 if (flags_ & SVC_DISABLED_START) {
811 return Start();
812 }
813 return true;
814}
815
816void Service::Reset() {
817 StopOrReset(SVC_RESET);
818}
819
820void Service::Stop() {
821 StopOrReset(SVC_DISABLED);
822}
823
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800824void Service::Terminate() {
825 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
826 flags_ |= SVC_DISABLED;
827 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700828 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800829 NotifyStateChange("stopping");
830 }
831}
832
Tom Cherrybac32992015-07-31 12:45:25 -0700833void Service::Restart() {
834 if (flags_ & SVC_RUNNING) {
835 /* Stop, wait, then start the service. */
836 StopOrReset(SVC_RESTART);
837 } else if (!(flags_ & SVC_RESTARTING)) {
838 /* Just start the service since it's not running. */
839 Start();
840 } /* else: Service is restarting anyways. */
841}
842
Elliott Hughes9605a942016-11-10 17:43:47 -0800843void Service::RestartIfNeeded(time_t* process_needs_restart_at) {
844 boot_clock::time_point now = boot_clock::now();
845 boot_clock::time_point next_start = time_started_ + 5s;
846 if (now > next_start) {
Tom Cherrybac32992015-07-31 12:45:25 -0700847 flags_ &= (~SVC_RESTARTING);
848 Start();
849 return;
850 }
851
Elliott Hughes9605a942016-11-10 17:43:47 -0800852 time_t next_start_time_t = time(nullptr) +
853 time_t(std::chrono::duration_cast<std::chrono::seconds>(next_start - now).count());
854 if (next_start_time_t < *process_needs_restart_at || *process_needs_restart_at == 0) {
855 *process_needs_restart_at = next_start_time_t;
Tom Cherrybac32992015-07-31 12:45:25 -0700856 }
857}
858
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700859// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700860void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700861 // The service is still SVC_RUNNING until its process exits, but if it has
862 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700863 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
864
865 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700866 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700867 how = SVC_DISABLED;
868 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700869
870 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700871 if (how == SVC_RESET) {
872 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
873 } else {
874 flags_ |= how;
875 }
876
877 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700878 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700879 NotifyStateChange("stopping");
880 } else {
881 NotifyStateChange("stopped");
882 }
883}
884
885void Service::ZapStdio() const {
886 int fd;
887 fd = open("/dev/null", O_RDWR);
888 dup2(fd, 0);
889 dup2(fd, 1);
890 dup2(fd, 2);
891 close(fd);
892}
893
894void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200895 int fd = open(console_.c_str(), O_RDWR);
896 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700897 ioctl(fd, TIOCSCTTY, 0);
898 dup2(fd, 0);
899 dup2(fd, 1);
900 dup2(fd, 2);
901 close(fd);
902}
903
Tom Cherrybac32992015-07-31 12:45:25 -0700904int ServiceManager::exec_count_ = 0;
905
906ServiceManager::ServiceManager() {
907}
908
909ServiceManager& ServiceManager::GetInstance() {
910 static ServiceManager instance;
911 return instance;
912}
913
Tom Cherryb7349902015-08-26 11:43:36 -0700914void ServiceManager::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -0700915 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700916}
917
Tom Cherryb27004a2017-03-27 16:27:30 -0700918bool ServiceManager::Exec(const std::vector<std::string>& args) {
919 Service* svc = MakeExecOneshotService(args);
920 if (!svc) {
921 LOG(ERROR) << "Could not create exec service";
922 return false;
923 }
924 if (!svc->ExecStart(&exec_waiter_)) {
925 LOG(ERROR) << "Could not start exec service";
926 ServiceManager::GetInstance().RemoveService(*svc);
927 return false;
928 }
929 return true;
930}
931
932bool ServiceManager::ExecStart(const std::string& name) {
933 Service* svc = FindServiceByName(name);
934 if (!svc) {
935 LOG(ERROR) << "ExecStart(" << name << "): Service not found";
936 return false;
937 }
938 if (!svc->ExecStart(&exec_waiter_)) {
939 LOG(ERROR) << "ExecStart(" << name << "): Could not start Service";
940 return false;
941 }
942 return true;
943}
944
945bool ServiceManager::IsWaitingForExec() const { return exec_waiter_ != nullptr; }
946
Tom Cherrybac32992015-07-31 12:45:25 -0700947Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
948 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
949 // SECLABEL can be a - to denote default
950 std::size_t command_arg = 1;
951 for (std::size_t i = 1; i < args.size(); ++i) {
952 if (args[i] == "--") {
953 command_arg = i + 1;
954 break;
955 }
956 }
957 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700958 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -0700959 return nullptr;
960 }
961
962 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700963 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -0700964 return nullptr;
965 }
966 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
967
968 exec_count_++;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700969 std::string name = "exec " + std::to_string(exec_count_) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -0700970
Tom Cherryb27004a2017-03-27 16:27:30 -0700971 unsigned flags = SVC_EXEC | SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400972 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700973 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700974
975 std::string seclabel = "";
976 if (command_arg > 2 && args[1] != "-") {
977 seclabel = args[1];
978 }
979 uid_t uid = 0;
980 if (command_arg > 3) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700981 std::string decode_uid_err;
982 if (!DecodeUid(args[2], &uid, &decode_uid_err)) {
983 LOG(ERROR) << "Unable to find UID for '" << args[2] << "': " << decode_uid_err;
984 return nullptr;
985 }
Tom Cherrybac32992015-07-31 12:45:25 -0700986 }
987 gid_t gid = 0;
988 std::vector<gid_t> supp_gids;
989 if (command_arg > 4) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700990 std::string decode_uid_err;
991 if (!DecodeUid(args[3], &gid, &decode_uid_err)) {
992 LOG(ERROR) << "Unable to find GID for '" << args[3] << "': " << decode_uid_err;
993 return nullptr;
994 }
Tom Cherrybac32992015-07-31 12:45:25 -0700995 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
996 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700997 gid_t supp_gid;
998 if (!DecodeUid(args[4 + i], &supp_gid, &decode_uid_err)) {
999 LOG(ERROR) << "Unable to find UID for '" << args[4 + i] << "': " << decode_uid_err;
1000 return nullptr;
1001 }
1002 supp_gids.push_back(supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -07001003 }
1004 }
1005
Wei Wang641ff0a2017-03-27 10:59:11 -07001006 auto svc_p = std::make_unique<Service>(name, flags, uid, gid, supp_gids, no_capabilities,
1007 namespace_flags, seclabel, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001008 Service* svc = svc_p.get();
Tom Cherry9bdddd72017-03-23 16:07:51 -07001009 services_.emplace_back(std::move(svc_p));
Tom Cherrybac32992015-07-31 12:45:25 -07001010
1011 return svc;
1012}
1013
1014Service* ServiceManager::FindServiceByName(const std::string& name) const {
1015 auto svc = std::find_if(services_.begin(), services_.end(),
1016 [&name] (const std::unique_ptr<Service>& s) {
1017 return name == s->name();
1018 });
1019 if (svc != services_.end()) {
1020 return svc->get();
1021 }
1022 return nullptr;
1023}
1024
1025Service* ServiceManager::FindServiceByPid(pid_t pid) const {
1026 auto svc = std::find_if(services_.begin(), services_.end(),
1027 [&pid] (const std::unique_ptr<Service>& s) {
1028 return s->pid() == pid;
1029 });
1030 if (svc != services_.end()) {
1031 return svc->get();
1032 }
1033 return nullptr;
1034}
1035
1036Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
1037 auto svc = std::find_if(services_.begin(), services_.end(),
1038 [&keychord_id] (const std::unique_ptr<Service>& s) {
1039 return s->keychord_id() == keychord_id;
1040 });
1041
1042 if (svc != services_.end()) {
1043 return svc->get();
1044 }
1045 return nullptr;
1046}
1047
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001048void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -07001049 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001050 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -07001051 }
1052}
1053
1054void ServiceManager::ForEachServiceInClass(const std::string& classname,
1055 void (*func)(Service* svc)) const {
1056 for (const auto& s : services_) {
Wei Wang641ff0a2017-03-27 10:59:11 -07001057 if (s->classnames().find(classname) != s->classnames().end()) {
Tom Cherrybac32992015-07-31 12:45:25 -07001058 func(s.get());
1059 }
1060 }
1061}
1062
1063void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
1064 void (*func)(Service* svc)) const {
1065 for (const auto& s : services_) {
1066 if (s->flags() & matchflags) {
1067 func(s.get());
1068 }
1069 }
1070}
1071
Tom Cherryb7349902015-08-26 11:43:36 -07001072void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001073 auto svc_it = std::find_if(services_.begin(), services_.end(),
1074 [&svc] (const std::unique_ptr<Service>& s) {
1075 return svc.name() == s->name();
1076 });
1077 if (svc_it == services_.end()) {
1078 return;
1079 }
1080
1081 services_.erase(svc_it);
1082}
1083
Tom Cherryb7349902015-08-26 11:43:36 -07001084void ServiceManager::DumpState() const {
1085 for (const auto& s : services_) {
1086 s->DumpState();
1087 }
Tom Cherryb7349902015-08-26 11:43:36 -07001088}
1089
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001090bool ServiceManager::ReapOneProcess() {
1091 int status;
1092 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
1093 if (pid == 0) {
1094 return false;
1095 } else if (pid == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001096 PLOG(ERROR) << "waitpid failed";
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001097 return false;
Tom Marshall62696902017-06-09 18:29:23 +00001098 } else if (PropertyChildReap(pid)) {
1099 return true;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001100 }
1101
1102 Service* svc = FindServiceByPid(pid);
1103
1104 std::string name;
Keun-young Park4de31e12017-04-27 16:25:06 -07001105 std::string wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001106 if (svc) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001107 name = StringPrintf("Service '%s' (pid %d)", svc->name().c_str(), pid);
Keun-young Park4de31e12017-04-27 16:25:06 -07001108 if (svc->flags() & SVC_EXEC) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001109 wait_string = StringPrintf(" waiting took %f seconds", exec_waiter_->duration_s());
Keun-young Park4de31e12017-04-27 16:25:06 -07001110 }
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001111 } else {
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001112 name = StringPrintf("Untracked pid %d", pid);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001113 }
1114
1115 if (WIFEXITED(status)) {
Keun-young Park4de31e12017-04-27 16:25:06 -07001116 LOG(INFO) << name << " exited with status " << WEXITSTATUS(status) << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001117 } else if (WIFSIGNALED(status)) {
Keun-young Park4de31e12017-04-27 16:25:06 -07001118 LOG(INFO) << name << " killed by signal " << WTERMSIG(status) << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001119 } else if (WIFSTOPPED(status)) {
Keun-young Park4de31e12017-04-27 16:25:06 -07001120 LOG(INFO) << name << " stopped by signal " << WSTOPSIG(status) << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001121 } else {
Keun-young Park4de31e12017-04-27 16:25:06 -07001122 LOG(INFO) << name << " state changed" << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001123 }
1124
1125 if (!svc) {
1126 return true;
1127 }
1128
Tom Cherryb27004a2017-03-27 16:27:30 -07001129 svc->Reap();
1130
1131 if (svc->flags() & SVC_EXEC) {
Tom Cherryb27004a2017-03-27 16:27:30 -07001132 exec_waiter_.reset();
1133 }
1134 if (svc->flags() & SVC_TEMPORARY) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001135 RemoveService(*svc);
1136 }
1137
1138 return true;
1139}
1140
1141void ServiceManager::ReapAnyOutstandingChildren() {
1142 while (ReapOneProcess()) {
1143 }
1144}
1145
Tom Cherry30a6f272017-04-19 15:31:58 -07001146bool ServiceParser::ParseSection(std::vector<std::string>&& args, const std::string& filename,
Tom Cherry012c5732017-04-18 13:21:54 -07001147 int line, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -07001148 if (args.size() < 3) {
1149 *err = "services must have a name and a program";
1150 return false;
1151 }
1152
1153 const std::string& name = args[1];
1154 if (!IsValidName(name)) {
1155 *err = StringPrintf("invalid service name '%s'", name.c_str());
1156 return false;
1157 }
1158
Tom Cherry30a6f272017-04-19 15:31:58 -07001159 Service* old_service = service_manager_->FindServiceByName(name);
1160 if (old_service) {
1161 *err = "ignored duplicate definition of service '" + name + "'";
1162 return false;
1163 }
1164
Tom Cherryb7349902015-08-26 11:43:36 -07001165 std::vector<std::string> str_args(args.begin() + 2, args.end());
Wei Wang641ff0a2017-03-27 10:59:11 -07001166 service_ = std::make_unique<Service>(name, str_args);
Tom Cherryb7349902015-08-26 11:43:36 -07001167 return true;
1168}
1169
Tom Cherry30a6f272017-04-19 15:31:58 -07001170bool ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) {
1171 return service_ ? service_->ParseLine(std::move(args), err) : false;
Tom Cherryb7349902015-08-26 11:43:36 -07001172}
1173
1174void ServiceParser::EndSection() {
1175 if (service_) {
Tom Cherry30a6f272017-04-19 15:31:58 -07001176 service_manager_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001177 }
1178}
1179
1180bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001181 // Property names can be any length, but may only contain certain characters.
1182 // Property values can contain any characters, but may only be a certain length.
1183 // (The latter restriction is needed because `start` and `stop` work by writing
1184 // the service name to the "ctl.start" and "ctl.stop" properties.)
1185 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001186}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001187
1188} // namespace init
1189} // namespace android