blob: c0745e3404c1ba18723cde0388e7020b26ec2ed3 [file] [log] [blame]
Tom Cherrybac32992015-07-31 12:45:25 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "service.h"
18
19#include <fcntl.h>
Elliott Hughes9605a942016-11-10 17:43:47 -080020#include <inttypes.h>
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -040021#include <linux/securebits.h>
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070022#include <sched.h>
23#include <sys/mount.h>
24#include <sys/prctl.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070025#include <sys/resource.h>
Tom Cherrybac32992015-07-31 12:45:25 -070026#include <sys/stat.h>
Tom Cherryf57c0bf2017-04-07 13:46:21 -070027#include <sys/system_properties.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070028#include <sys/time.h>
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -080029#include <sys/wait.h>
Tom Cherrybac32992015-07-31 12:45:25 -070030#include <termios.h>
Dan Albertaf9ba4d2015-08-11 16:37:04 -070031#include <unistd.h>
Tom Cherrybac32992015-07-31 12:45:25 -070032
Elliott Hughes4f713192015-12-04 22:00:26 -080033#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070034#include <android-base/logging.h>
Elliott Hughesda46b392016-10-11 17:09:00 -070035#include <android-base/parseint.h>
Tom Cherryccf23532017-03-28 16:40:41 -070036#include <android-base/properties.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080037#include <android-base/stringprintf.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070038#include <android-base/strings.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070039#include <processgroup/processgroup.h>
40#include <selinux/selinux.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070041#include <system/thread_defs.h>
Tom Cherrybac32992015-07-31 12:45:25 -070042
Tom Cherrybac32992015-07-31 12:45:25 -070043#include "init.h"
Tom Cherrybac32992015-07-31 12:45:25 -070044#include "property_service.h"
45#include "util.h"
46
James Hawkinse78ea772017-03-24 11:43:02 -070047using android::base::boot_clock;
Elliott Hughesda46b392016-10-11 17:09:00 -070048using android::base::ParseInt;
Tom Cherryb7349902015-08-26 11:43:36 -070049using android::base::StringPrintf;
50using android::base::WriteStringToFile;
51
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040052static std::string ComputeContextFromExecutable(std::string& service_name,
53 const std::string& service_path) {
54 std::string computed_context;
55
56 char* raw_con = nullptr;
57 char* raw_filecon = nullptr;
58
59 if (getcon(&raw_con) == -1) {
60 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
61 return "";
62 }
63 std::unique_ptr<char> mycon(raw_con);
64
65 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
66 LOG(ERROR) << "could not get file context while starting '" << service_name << "'";
67 return "";
68 }
69 std::unique_ptr<char> filecon(raw_filecon);
70
71 char* new_con = nullptr;
72 int rc = security_compute_create(mycon.get(), filecon.get(),
73 string_to_security_class("process"), &new_con);
74 if (rc == 0) {
75 computed_context = new_con;
76 free(new_con);
77 }
78 if (rc == 0 && computed_context == mycon.get()) {
79 LOG(ERROR) << "service " << service_name << " does not have a SELinux domain defined";
80 return "";
81 }
82 if (rc < 0) {
83 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
84 return "";
85 }
86 return computed_context;
87}
88
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070089static void SetUpPidNamespace(const std::string& service_name) {
90 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
91
92 // It's OK to LOG(FATAL) in this function since it's running in the first
93 // child process.
94 if (mount("", "/proc", "proc", kSafeFlags | MS_REMOUNT, "") == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -070095 PLOG(FATAL) << "couldn't remount(/proc) for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070096 }
97
98 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -070099 PLOG(FATAL) << "couldn't set name for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700100 }
101
102 pid_t child_pid = fork();
103 if (child_pid == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700104 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700105 }
106
107 if (child_pid > 0) {
108 // So that we exit with the right status.
109 static int init_exitstatus = 0;
110 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
111
112 pid_t waited_pid;
113 int status;
114 while ((waited_pid = wait(&status)) > 0) {
115 // This loop will end when there are no processes left inside the
116 // PID namespace or when the init process inside the PID namespace
117 // gets a signal.
118 if (waited_pid == child_pid) {
119 init_exitstatus = status;
120 }
121 }
122 if (!WIFEXITED(init_exitstatus)) {
123 _exit(EXIT_FAILURE);
124 }
125 _exit(WEXITSTATUS(init_exitstatus));
126 }
127}
128
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400129static void ExpandArgs(const std::vector<std::string>& args, std::vector<char*>* strs) {
130 std::vector<std::string> expanded_args;
131 expanded_args.resize(args.size());
132 strs->push_back(const_cast<char*>(args[0].c_str()));
133 for (std::size_t i = 1; i < args.size(); ++i) {
134 if (!expand_props(args[i], &expanded_args[i])) {
135 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
136 }
137 strs->push_back(const_cast<char*>(expanded_args[i].c_str()));
138 }
139 strs->push_back(nullptr);
140}
141
Tom Cherrybac32992015-07-31 12:45:25 -0700142ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
143}
144
145ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
146 const std::string& value)
147 : name(name), value(value) {
148}
149
Wei Wang641ff0a2017-03-27 10:59:11 -0700150Service::Service(const std::string& name, const std::vector<std::string>& args)
151 : name_(name),
152 classnames_({"default"}),
153 flags_(0),
154 pid_(0),
155 crash_count_(0),
156 uid_(0),
157 gid_(0),
158 namespace_flags_(0),
159 seclabel_(""),
Tom Cherry012c5732017-04-18 13:21:54 -0700160 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700161 ioprio_class_(IoSchedClass_NONE),
162 ioprio_pri_(0),
163 priority_(0),
164 oom_score_adjust_(-1000),
165 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700166 onrestart_.InitSingleTrigger("onrestart");
167}
168
Wei Wang641ff0a2017-03-27 10:59:11 -0700169Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
170 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
171 unsigned namespace_flags, const std::string& seclabel,
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700172 const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700173 : name_(name),
174 classnames_({"default"}),
175 flags_(flags),
176 pid_(0),
177 crash_count_(0),
178 uid_(uid),
179 gid_(gid),
180 supp_gids_(supp_gids),
181 capabilities_(capabilities),
182 namespace_flags_(namespace_flags),
183 seclabel_(seclabel),
Tom Cherry012c5732017-04-18 13:21:54 -0700184 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700185 ioprio_class_(IoSchedClass_NONE),
186 ioprio_pri_(0),
187 priority_(0),
188 oom_score_adjust_(-1000),
189 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700190 onrestart_.InitSingleTrigger("onrestart");
191}
192
193void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700194 if ((flags_ & SVC_TEMPORARY) != 0) {
195 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700196 return;
197 }
198
Tom Cherryb7349902015-08-26 11:43:36 -0700199 std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700200 property_set(prop_name.c_str(), new_state.c_str());
Elliott Hughes9605a942016-11-10 17:43:47 -0800201
202 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800203 uint64_t start_ns = time_started_.time_since_epoch().count();
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000204 property_set(StringPrintf("ro.boottime.%s", name_.c_str()).c_str(),
205 StringPrintf("%" PRIu64, start_ns).c_str());
Elliott Hughes9605a942016-11-10 17:43:47 -0800206 }
Tom Cherrybac32992015-07-31 12:45:25 -0700207}
208
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700209void Service::KillProcessGroup(int signal) {
Elliott Hughes1e730242016-08-02 14:20:40 -0700210 LOG(INFO) << "Sending signal " << signal
211 << " to service '" << name_
212 << "' (pid " << pid_ << ") process group...";
Keun-young Parkacd55b32017-03-28 17:55:43 -0700213 int r;
214 if (signal == SIGTERM) {
215 r = killProcessGroupOnce(uid_, pid_, signal);
216 } else {
217 r = killProcessGroup(uid_, pid_, signal);
218 }
219 if (r == -1) {
William Robertse6ec2662017-04-19 16:12:09 -0700220 LOG(ERROR) << "killProcessGroup(" << uid_ << ", " << pid_ << ", " << signal << ") failed";
Elliott Hughes1e730242016-08-02 14:20:40 -0700221 }
222 if (kill(-pid_, signal) == -1) {
223 PLOG(ERROR) << "kill(" << pid_ << ", " << signal << ") failed";
224 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700225}
226
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400227void Service::SetProcessAttributes() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400228 // Keep capabilites on uid change.
229 if (capabilities_.any() && uid_) {
230 if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED) != 0) {
231 PLOG(FATAL) << "prtcl(PR_SET_KEEPCAPS) failed for " << name_;
232 }
233 }
234
Elliott Hughese18e7e52016-07-25 18:18:16 -0700235 // TODO: work out why this fails for `console` then upgrade to FATAL.
236 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400237
238 if (gid_) {
239 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700240 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400241 }
242 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700243 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
244 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400245 }
246 if (uid_) {
247 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700248 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400249 }
250 }
251 if (!seclabel_.empty()) {
252 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700253 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400254 }
255 }
256 if (priority_ != 0) {
257 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700258 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400259 }
260 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400261 if (capabilities_.any()) {
262 if (!SetCapsForExec(capabilities_)) {
263 LOG(FATAL) << "cannot set capabilities for " << name_;
264 }
265 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400266}
267
Tom Cherryb27004a2017-03-27 16:27:30 -0700268void Service::Reap() {
Tom Cherrybac32992015-07-31 12:45:25 -0700269 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700270 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700271 }
272
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700273 // Remove any descriptor resources we may have created.
274 std::for_each(descriptors_.begin(), descriptors_.end(),
275 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700276
277 if (flags_ & SVC_EXEC) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700278 LOG(INFO) << "SVC_EXEC pid " << pid_ << " finished...";
Tom Cherryb27004a2017-03-27 16:27:30 -0700279 }
280
281 if (flags_ & SVC_TEMPORARY) {
282 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700283 }
284
285 pid_ = 0;
286 flags_ &= (~SVC_RUNNING);
287
288 // Oneshot processes go into the disabled state on exit,
289 // except when manually restarted.
290 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
291 flags_ |= SVC_DISABLED;
292 }
293
294 // Disabled and reset processes do not get restarted automatically.
295 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
296 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700297 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700298 }
299
Elliott Hughes9605a942016-11-10 17:43:47 -0800300 // If we crash > 4 times in 4 minutes, reboot into recovery.
301 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700302 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800303 if (now < time_crashed_ + 4min) {
304 if (++crash_count_ > 4) {
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000305 LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
306 panic();
Tom Cherrybac32992015-07-31 12:45:25 -0700307 }
308 } else {
309 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800310 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700311 }
312 }
313
314 flags_ &= (~SVC_RESTART);
315 flags_ |= SVC_RESTARTING;
316
317 // Execute all onrestart commands for this service.
318 onrestart_.ExecuteAllCommands();
319
320 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700321 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700322}
323
324void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700325 LOG(INFO) << "service " << name_;
Wei Wang641ff0a2017-03-27 10:59:11 -0700326 LOG(INFO) << " class '" << android::base::Join(classnames_, " ") << "'";
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700327 LOG(INFO) << " exec "<< android::base::Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700328 std::for_each(descriptors_.begin(), descriptors_.end(),
329 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700330}
331
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400332bool Service::ParseCapabilities(const std::vector<std::string>& args, std::string* err) {
333 capabilities_ = 0;
334
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500335 if (!CapAmbientSupported()) {
336 *err = "capabilities requested but the kernel does not support ambient capabilities";
337 return false;
338 }
339
340 unsigned int last_valid_cap = GetLastValidCap();
341 if (last_valid_cap >= capabilities_.size()) {
342 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
343 }
344
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400345 for (size_t i = 1; i < args.size(); i++) {
346 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500347 int res = LookupCap(arg);
348 if (res < 0) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400349 *err = StringPrintf("invalid capability '%s'", arg.c_str());
350 return false;
351 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500352 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
353 if (cap > last_valid_cap) {
354 *err = StringPrintf("capability '%s' not supported by the kernel", arg.c_str());
355 return false;
356 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400357 capabilities_[cap] = true;
358 }
359 return true;
360}
361
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400362bool Service::ParseClass(const std::vector<std::string>& args, std::string* err) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700363 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherryb7349902015-08-26 11:43:36 -0700364 return true;
365}
Tom Cherrybac32992015-07-31 12:45:25 -0700366
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400367bool Service::ParseConsole(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700368 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200369 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherryb7349902015-08-26 11:43:36 -0700370 return true;
371}
Tom Cherrybac32992015-07-31 12:45:25 -0700372
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400373bool Service::ParseCritical(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700374 flags_ |= SVC_CRITICAL;
375 return true;
376}
Tom Cherrybac32992015-07-31 12:45:25 -0700377
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400378bool Service::ParseDisabled(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700379 flags_ |= SVC_DISABLED;
380 flags_ |= SVC_RC_DISABLED;
381 return true;
382}
Tom Cherrybac32992015-07-31 12:45:25 -0700383
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400384bool Service::ParseGroup(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700385 gid_ = decode_uid(args[1].c_str());
386 for (std::size_t n = 2; n < args.size(); n++) {
387 supp_gids_.emplace_back(decode_uid(args[n].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700388 }
389 return true;
390}
391
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400392bool Service::ParsePriority(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700393 priority_ = 0;
394 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800395 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
396 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700397 *err = StringPrintf("process priority value must be range %d - %d",
398 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
399 return false;
400 }
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700401 return true;
402}
403
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400404bool Service::ParseIoprio(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700405 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherryb7349902015-08-26 11:43:36 -0700406 *err = "priority value must be range 0 - 7";
407 return false;
408 }
409
410 if (args[1] == "rt") {
411 ioprio_class_ = IoSchedClass_RT;
412 } else if (args[1] == "be") {
413 ioprio_class_ = IoSchedClass_BE;
414 } else if (args[1] == "idle") {
415 ioprio_class_ = IoSchedClass_IDLE;
416 } else {
417 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
418 return false;
419 }
420
421 return true;
422}
423
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400424bool Service::ParseKeycodes(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700425 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700426 int code;
427 if (ParseInt(args[i], &code)) {
428 keycodes_.emplace_back(code);
429 } else {
430 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
431 }
Tom Cherryb7349902015-08-26 11:43:36 -0700432 }
433 return true;
434}
435
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400436bool Service::ParseOneshot(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700437 flags_ |= SVC_ONESHOT;
438 return true;
439}
440
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400441bool Service::ParseOnrestart(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700442 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700443 int line = onrestart_.NumCommands() + 1;
444 onrestart_.AddCommand(str_args, line, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700445 return true;
446}
447
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400448bool Service::ParseNamespace(const std::vector<std::string>& args, std::string* err) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700449 for (size_t i = 1; i < args.size(); i++) {
450 if (args[i] == "pid") {
451 namespace_flags_ |= CLONE_NEWPID;
452 // PID namespaces require mount namespaces.
453 namespace_flags_ |= CLONE_NEWNS;
454 } else if (args[i] == "mnt") {
455 namespace_flags_ |= CLONE_NEWNS;
456 } else {
457 *err = "namespace must be 'pid' or 'mnt'";
458 return false;
459 }
460 }
461 return true;
462}
463
Marco Nelissen310f6702016-07-22 12:07:06 -0700464bool Service::ParseOomScoreAdjust(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700465 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Marco Nelissen310f6702016-07-22 12:07:06 -0700466 *err = "oom_score_adjust value must be in range -1000 - +1000";
467 return false;
468 }
Marco Nelissen310f6702016-07-22 12:07:06 -0700469 return true;
470}
471
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400472bool Service::ParseSeclabel(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700473 seclabel_ = args[1];
474 return true;
475}
476
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400477bool Service::ParseSetenv(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700478 envvars_.emplace_back(args[1], args[2]);
479 return true;
480}
481
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700482template <typename T>
483bool Service::AddDescriptor(const std::vector<std::string>& args, std::string* err) {
484 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
485 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
486 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
487 std::string context = args.size() > 6 ? args[6] : "";
488
489 auto descriptor = std::make_unique<T>(args[1], args[2], uid, gid, perm, context);
490
491 auto old =
492 std::find_if(descriptors_.begin(), descriptors_.end(),
493 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
494
495 if (old != descriptors_.end()) {
496 *err = "duplicate descriptor " + args[1] + " " + args[2];
497 return false;
498 }
499
500 descriptors_.emplace_back(std::move(descriptor));
501 return true;
502}
503
504// name type perm [ uid gid context ]
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400505bool Service::ParseSocket(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700506 if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
507 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
508 return false;
509 }
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700510 return AddDescriptor<SocketInfo>(args, err);
511}
Tom Cherryb7349902015-08-26 11:43:36 -0700512
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700513// name type perm [ uid gid context ]
514bool Service::ParseFile(const std::vector<std::string>& args, std::string* err) {
515 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
516 *err = "file type must be 'r', 'w' or 'rw'";
517 return false;
518 }
519 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
520 *err = "file name must not be relative";
521 return false;
522 }
523 return AddDescriptor<FileInfo>(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700524}
525
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400526bool Service::ParseUser(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700527 uid_ = decode_uid(args[1].c_str());
528 return true;
529}
530
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400531bool Service::ParseWritepid(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700532 writepid_files_.assign(args.begin() + 1, args.end());
533 return true;
534}
535
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400536class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryb7349902015-08-26 11:43:36 -0700537public:
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400538 OptionParserMap() {
Tom Cherryb7349902015-08-26 11:43:36 -0700539 }
540private:
541 Map& map() const override;
542};
543
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400544Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700545 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700546 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400547 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400548 {"capabilities",
549 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700550 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400551 {"console", {0, 1, &Service::ParseConsole}},
552 {"critical", {0, 0, &Service::ParseCritical}},
553 {"disabled", {0, 0, &Service::ParseDisabled}},
554 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
555 {"ioprio", {2, 2, &Service::ParseIoprio}},
556 {"priority", {1, 1, &Service::ParsePriority}},
557 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
558 {"oneshot", {0, 0, &Service::ParseOneshot}},
559 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700560 {"oom_score_adjust",
561 {1, 1, &Service::ParseOomScoreAdjust}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400562 {"namespace", {1, 2, &Service::ParseNamespace}},
563 {"seclabel", {1, 1, &Service::ParseSeclabel}},
564 {"setenv", {2, 2, &Service::ParseSetenv}},
565 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn978fd0e2016-12-02 08:05:22 -0800566 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400567 {"user", {1, 1, &Service::ParseUser}},
568 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700569 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700570 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400571 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700572}
573
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400574bool Service::ParseLine(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700575 if (args.empty()) {
576 *err = "option needed, but not provided";
577 return false;
578 }
579
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400580 static const OptionParserMap parser_map;
581 auto parser = parser_map.FindFunction(args[0], args.size() - 1, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700582
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400583 if (!parser) {
Tom Cherryb7349902015-08-26 11:43:36 -0700584 return false;
585 }
586
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400587 return (this->*parser)(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700588}
589
Tom Cherryb27004a2017-03-27 16:27:30 -0700590bool Service::ExecStart(std::unique_ptr<Timer>* exec_waiter) {
591 flags_ |= SVC_EXEC | SVC_ONESHOT;
592
593 exec_waiter->reset(new Timer);
594
595 if (!Start()) {
596 exec_waiter->reset();
597 return false;
598 }
599 return true;
600}
601
Elliott Hughesbdeac392016-04-12 15:38:27 -0700602bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700603 // Starting a service removes it from the disabled or reset state and
604 // immediately takes it out of the restarting state if it was in there.
605 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700606
607 // Running processes require no additional work --- if they're in the
608 // process of exiting, we've ensured that they will immediately restart
609 // on exit, unless they are ONESHOT.
610 if (flags_ & SVC_RUNNING) {
611 return false;
612 }
613
614 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200615 if (needs_console) {
616 if (console_.empty()) {
617 console_ = default_console;
618 }
619
Adrian Salido24ef8602016-12-20 15:52:15 -0800620 // Make sure that open call succeeds to ensure a console driver is
621 // properly registered for the device node
622 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
623 if (console_fd < 0) {
624 PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200625 flags_ |= SVC_DISABLED;
626 return false;
627 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800628 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700629 }
630
631 struct stat sb;
632 if (stat(args_[0].c_str(), &sb) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700633 PLOG(ERROR) << "cannot find '" << args_[0] << "', disabling '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700634 flags_ |= SVC_DISABLED;
635 return false;
636 }
637
Tom Cherrybac32992015-07-31 12:45:25 -0700638 std::string scon;
639 if (!seclabel_.empty()) {
640 scon = seclabel_;
641 } else {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400642 LOG(INFO) << "computing context for service '" << name_ << "'";
643 scon = ComputeContextFromExecutable(name_, args_[0]);
644 if (scon == "") {
Tom Cherrybac32992015-07-31 12:45:25 -0700645 return false;
646 }
647 }
648
Wei Wanga285dac2016-10-04 14:05:39 -0700649 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700650
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700651 pid_t pid = -1;
652 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400653 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700654 } else {
655 pid = fork();
656 }
657
Tom Cherrybac32992015-07-31 12:45:25 -0700658 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700659 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700660
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700661 if (namespace_flags_ & CLONE_NEWPID) {
662 // This will fork again to run an init process inside the PID
663 // namespace.
664 SetUpPidNamespace(name_);
665 }
666
Tom Cherrybac32992015-07-31 12:45:25 -0700667 for (const auto& ei : envvars_) {
668 add_environment(ei.name.c_str(), ei.value.c_str());
669 }
670
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700671 std::for_each(descriptors_.begin(), descriptors_.end(),
672 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700673
Alex Vakulenko08286762016-05-03 12:00:00 -0700674 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
675 auto cpuset_predicate = [](const std::string& path) {
676 return android::base::StartsWith(path, "/dev/cpuset/");
677 };
678 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
679 if (iter == writepid_files_.end()) {
680 // There were no "writepid" instructions for cpusets, check if the system default
681 // cpuset is specified to be used for the process.
Tom Cherryccf23532017-03-28 16:40:41 -0700682 std::string default_cpuset = android::base::GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700683 if (!default_cpuset.empty()) {
684 // Make sure the cpuset name starts and ends with '/'.
685 // A single '/' means the 'root' cpuset.
686 if (default_cpuset.front() != '/') {
687 default_cpuset.insert(0, 1, '/');
688 }
689 if (default_cpuset.back() != '/') {
690 default_cpuset.push_back('/');
691 }
692 writepid_files_.push_back(
693 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
694 }
695 }
Anestis Bechtsoudisb702b462016-02-05 16:38:48 +0200696 std::string pid_str = StringPrintf("%d", getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700697 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700698 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700699 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700700 }
701 }
702
703 if (ioprio_class_ != IoSchedClass_NONE) {
704 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400705 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700706 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700707 }
708 }
709
710 if (needs_console) {
711 setsid();
712 OpenConsole();
713 } else {
714 ZapStdio();
715 }
716
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400717 // As requested, set our gid, supplemental gids, uid, context, and
718 // priority. Aborts on failure.
719 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700720
Tom Cherrybac32992015-07-31 12:45:25 -0700721 std::vector<char*> strs;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400722 ExpandArgs(args_, &strs);
Tom Cherrybac35362016-06-07 11:22:00 -0700723 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700724 PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700725 }
726
727 _exit(127);
728 }
729
730 if (pid < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700731 PLOG(ERROR) << "failed to fork for '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700732 pid_ = 0;
733 return false;
734 }
735
Marco Nelissen310f6702016-07-22 12:07:06 -0700736 if (oom_score_adjust_ != -1000) {
737 std::string oom_str = StringPrintf("%d", oom_score_adjust_);
738 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
739 if (!WriteStringToFile(oom_str, oom_file)) {
740 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
741 }
742 }
743
Elliott Hughes9605a942016-11-10 17:43:47 -0800744 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700745 pid_ = pid;
746 flags_ |= SVC_RUNNING;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700747
748 errno = -createProcessGroup(uid_, pid_);
749 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400750 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
751 << name_ << "'";
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700752 }
Tom Cherrybac32992015-07-31 12:45:25 -0700753
754 if ((flags_ & SVC_EXEC) != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400755 LOG(INFO) << android::base::StringPrintf(
756 "SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...", pid_, uid_, gid_,
757 supp_gids_.size(), !seclabel_.empty() ? seclabel_.c_str() : "default");
Tom Cherrybac32992015-07-31 12:45:25 -0700758 }
759
760 NotifyStateChange("running");
761 return true;
762}
763
Tom Cherrybac32992015-07-31 12:45:25 -0700764bool Service::StartIfNotDisabled() {
765 if (!(flags_ & SVC_DISABLED)) {
766 return Start();
767 } else {
768 flags_ |= SVC_DISABLED_START;
769 }
770 return true;
771}
772
773bool Service::Enable() {
774 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
775 if (flags_ & SVC_DISABLED_START) {
776 return Start();
777 }
778 return true;
779}
780
781void Service::Reset() {
782 StopOrReset(SVC_RESET);
783}
784
785void Service::Stop() {
786 StopOrReset(SVC_DISABLED);
787}
788
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800789void Service::Terminate() {
790 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
791 flags_ |= SVC_DISABLED;
792 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700793 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800794 NotifyStateChange("stopping");
795 }
796}
797
Tom Cherrybac32992015-07-31 12:45:25 -0700798void Service::Restart() {
799 if (flags_ & SVC_RUNNING) {
800 /* Stop, wait, then start the service. */
801 StopOrReset(SVC_RESTART);
802 } else if (!(flags_ & SVC_RESTARTING)) {
803 /* Just start the service since it's not running. */
804 Start();
805 } /* else: Service is restarting anyways. */
806}
807
Elliott Hughes9605a942016-11-10 17:43:47 -0800808void Service::RestartIfNeeded(time_t* process_needs_restart_at) {
809 boot_clock::time_point now = boot_clock::now();
810 boot_clock::time_point next_start = time_started_ + 5s;
811 if (now > next_start) {
Tom Cherrybac32992015-07-31 12:45:25 -0700812 flags_ &= (~SVC_RESTARTING);
813 Start();
814 return;
815 }
816
Elliott Hughes9605a942016-11-10 17:43:47 -0800817 time_t next_start_time_t = time(nullptr) +
818 time_t(std::chrono::duration_cast<std::chrono::seconds>(next_start - now).count());
819 if (next_start_time_t < *process_needs_restart_at || *process_needs_restart_at == 0) {
820 *process_needs_restart_at = next_start_time_t;
Tom Cherrybac32992015-07-31 12:45:25 -0700821 }
822}
823
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700824// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700825void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700826 // The service is still SVC_RUNNING until its process exits, but if it has
827 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700828 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
829
830 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700831 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700832 how = SVC_DISABLED;
833 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700834
835 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700836 if (how == SVC_RESET) {
837 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
838 } else {
839 flags_ |= how;
840 }
841
842 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700843 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700844 NotifyStateChange("stopping");
845 } else {
846 NotifyStateChange("stopped");
847 }
848}
849
850void Service::ZapStdio() const {
851 int fd;
852 fd = open("/dev/null", O_RDWR);
853 dup2(fd, 0);
854 dup2(fd, 1);
855 dup2(fd, 2);
856 close(fd);
857}
858
859void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200860 int fd = open(console_.c_str(), O_RDWR);
861 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700862 ioctl(fd, TIOCSCTTY, 0);
863 dup2(fd, 0);
864 dup2(fd, 1);
865 dup2(fd, 2);
866 close(fd);
867}
868
Tom Cherrybac32992015-07-31 12:45:25 -0700869int ServiceManager::exec_count_ = 0;
870
871ServiceManager::ServiceManager() {
872}
873
874ServiceManager& ServiceManager::GetInstance() {
875 static ServiceManager instance;
876 return instance;
877}
878
Tom Cherryb7349902015-08-26 11:43:36 -0700879void ServiceManager::AddService(std::unique_ptr<Service> service) {
880 Service* old_service = FindServiceByName(service->name());
881 if (old_service) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700882 LOG(ERROR) << "ignored duplicate definition of service '" << service->name() << "'";
Tom Cherryb7349902015-08-26 11:43:36 -0700883 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700884 }
Tom Cherryb7349902015-08-26 11:43:36 -0700885 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700886}
887
Tom Cherryb27004a2017-03-27 16:27:30 -0700888bool ServiceManager::Exec(const std::vector<std::string>& args) {
889 Service* svc = MakeExecOneshotService(args);
890 if (!svc) {
891 LOG(ERROR) << "Could not create exec service";
892 return false;
893 }
894 if (!svc->ExecStart(&exec_waiter_)) {
895 LOG(ERROR) << "Could not start exec service";
896 ServiceManager::GetInstance().RemoveService(*svc);
897 return false;
898 }
899 return true;
900}
901
902bool ServiceManager::ExecStart(const std::string& name) {
903 Service* svc = FindServiceByName(name);
904 if (!svc) {
905 LOG(ERROR) << "ExecStart(" << name << "): Service not found";
906 return false;
907 }
908 if (!svc->ExecStart(&exec_waiter_)) {
909 LOG(ERROR) << "ExecStart(" << name << "): Could not start Service";
910 return false;
911 }
912 return true;
913}
914
915bool ServiceManager::IsWaitingForExec() const { return exec_waiter_ != nullptr; }
916
Tom Cherrybac32992015-07-31 12:45:25 -0700917Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
918 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
919 // SECLABEL can be a - to denote default
920 std::size_t command_arg = 1;
921 for (std::size_t i = 1; i < args.size(); ++i) {
922 if (args[i] == "--") {
923 command_arg = i + 1;
924 break;
925 }
926 }
927 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700928 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -0700929 return nullptr;
930 }
931
932 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700933 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -0700934 return nullptr;
935 }
936 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
937
938 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700939 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherryb27004a2017-03-27 16:27:30 -0700940 unsigned flags = SVC_EXEC | SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400941 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700942 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700943
944 std::string seclabel = "";
945 if (command_arg > 2 && args[1] != "-") {
946 seclabel = args[1];
947 }
948 uid_t uid = 0;
949 if (command_arg > 3) {
950 uid = decode_uid(args[2].c_str());
951 }
952 gid_t gid = 0;
953 std::vector<gid_t> supp_gids;
954 if (command_arg > 4) {
955 gid = decode_uid(args[3].c_str());
956 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
957 for (size_t i = 0; i < nr_supp_gids; ++i) {
958 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
959 }
960 }
961
Wei Wang641ff0a2017-03-27 10:59:11 -0700962 auto svc_p = std::make_unique<Service>(name, flags, uid, gid, supp_gids, no_capabilities,
963 namespace_flags, seclabel, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -0700964 Service* svc = svc_p.get();
Tom Cherry9bdddd72017-03-23 16:07:51 -0700965 services_.emplace_back(std::move(svc_p));
Tom Cherrybac32992015-07-31 12:45:25 -0700966
967 return svc;
968}
969
970Service* ServiceManager::FindServiceByName(const std::string& name) const {
971 auto svc = std::find_if(services_.begin(), services_.end(),
972 [&name] (const std::unique_ptr<Service>& s) {
973 return name == s->name();
974 });
975 if (svc != services_.end()) {
976 return svc->get();
977 }
978 return nullptr;
979}
980
981Service* ServiceManager::FindServiceByPid(pid_t pid) const {
982 auto svc = std::find_if(services_.begin(), services_.end(),
983 [&pid] (const std::unique_ptr<Service>& s) {
984 return s->pid() == pid;
985 });
986 if (svc != services_.end()) {
987 return svc->get();
988 }
989 return nullptr;
990}
991
992Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
993 auto svc = std::find_if(services_.begin(), services_.end(),
994 [&keychord_id] (const std::unique_ptr<Service>& s) {
995 return s->keychord_id() == keychord_id;
996 });
997
998 if (svc != services_.end()) {
999 return svc->get();
1000 }
1001 return nullptr;
1002}
1003
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001004void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -07001005 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001006 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -07001007 }
1008}
1009
1010void ServiceManager::ForEachServiceInClass(const std::string& classname,
1011 void (*func)(Service* svc)) const {
1012 for (const auto& s : services_) {
Wei Wang641ff0a2017-03-27 10:59:11 -07001013 if (s->classnames().find(classname) != s->classnames().end()) {
Tom Cherrybac32992015-07-31 12:45:25 -07001014 func(s.get());
1015 }
1016 }
1017}
1018
1019void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
1020 void (*func)(Service* svc)) const {
1021 for (const auto& s : services_) {
1022 if (s->flags() & matchflags) {
1023 func(s.get());
1024 }
1025 }
1026}
1027
Tom Cherryb7349902015-08-26 11:43:36 -07001028void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001029 auto svc_it = std::find_if(services_.begin(), services_.end(),
1030 [&svc] (const std::unique_ptr<Service>& s) {
1031 return svc.name() == s->name();
1032 });
1033 if (svc_it == services_.end()) {
1034 return;
1035 }
1036
1037 services_.erase(svc_it);
1038}
1039
Tom Cherryb7349902015-08-26 11:43:36 -07001040void ServiceManager::DumpState() const {
1041 for (const auto& s : services_) {
1042 s->DumpState();
1043 }
Tom Cherryb7349902015-08-26 11:43:36 -07001044}
1045
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001046bool ServiceManager::ReapOneProcess() {
1047 int status;
1048 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
1049 if (pid == 0) {
1050 return false;
1051 } else if (pid == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001052 PLOG(ERROR) << "waitpid failed";
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001053 return false;
1054 }
1055
1056 Service* svc = FindServiceByPid(pid);
1057
1058 std::string name;
1059 if (svc) {
1060 name = android::base::StringPrintf("Service '%s' (pid %d)",
1061 svc->name().c_str(), pid);
1062 } else {
1063 name = android::base::StringPrintf("Untracked pid %d", pid);
1064 }
1065
1066 if (WIFEXITED(status)) {
Wei Wanga285dac2016-10-04 14:05:39 -07001067 LOG(INFO) << name << " exited with status " << WEXITSTATUS(status);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001068 } else if (WIFSIGNALED(status)) {
Wei Wanga285dac2016-10-04 14:05:39 -07001069 LOG(INFO) << name << " killed by signal " << WTERMSIG(status);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001070 } else if (WIFSTOPPED(status)) {
Wei Wanga285dac2016-10-04 14:05:39 -07001071 LOG(INFO) << name << " stopped by signal " << WSTOPSIG(status);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001072 } else {
Wei Wanga285dac2016-10-04 14:05:39 -07001073 LOG(INFO) << name << " state changed";
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001074 }
1075
1076 if (!svc) {
1077 return true;
1078 }
1079
Tom Cherryb27004a2017-03-27 16:27:30 -07001080 svc->Reap();
1081
1082 if (svc->flags() & SVC_EXEC) {
1083 LOG(INFO) << "Wait for exec took " << *exec_waiter_;
1084 exec_waiter_.reset();
1085 }
1086 if (svc->flags() & SVC_TEMPORARY) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001087 RemoveService(*svc);
1088 }
1089
1090 return true;
1091}
1092
1093void ServiceManager::ReapAnyOutstandingChildren() {
1094 while (ReapOneProcess()) {
1095 }
1096}
1097
Tom Cherry012c5732017-04-18 13:21:54 -07001098bool ServiceParser::ParseSection(const std::vector<std::string>& args, const std::string& filename,
1099 int line, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -07001100 if (args.size() < 3) {
1101 *err = "services must have a name and a program";
1102 return false;
1103 }
1104
1105 const std::string& name = args[1];
1106 if (!IsValidName(name)) {
1107 *err = StringPrintf("invalid service name '%s'", name.c_str());
1108 return false;
1109 }
1110
1111 std::vector<std::string> str_args(args.begin() + 2, args.end());
Wei Wang641ff0a2017-03-27 10:59:11 -07001112 service_ = std::make_unique<Service>(name, str_args);
Tom Cherryb7349902015-08-26 11:43:36 -07001113 return true;
1114}
1115
Tom Cherry012c5732017-04-18 13:21:54 -07001116bool ServiceParser::ParseLineSection(const std::vector<std::string>& args, int line,
1117 std::string* err) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -04001118 return service_ ? service_->ParseLine(args, err) : false;
Tom Cherryb7349902015-08-26 11:43:36 -07001119}
1120
1121void ServiceParser::EndSection() {
1122 if (service_) {
1123 ServiceManager::GetInstance().AddService(std::move(service_));
1124 }
1125}
1126
1127bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001128 // Property names can be any length, but may only contain certain characters.
1129 // Property values can contain any characters, but may only be a certain length.
1130 // (The latter restriction is needed because `start` and `stop` work by writing
1131 // the service name to the "ctl.start" and "ctl.stop" properties.)
1132 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001133}