blob: f5e54dfda6b0bc776a16567472f5d86de5b2d0b1 [file] [log] [blame]
Tom Cherrybac32992015-07-31 12:45:25 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "service.h"
18
19#include <fcntl.h>
Elliott Hughes9605a942016-11-10 17:43:47 -080020#include <inttypes.h>
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -040021#include <linux/securebits.h>
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070022#include <sched.h>
23#include <sys/mount.h>
24#include <sys/prctl.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070025#include <sys/resource.h>
Tom Cherrybac32992015-07-31 12:45:25 -070026#include <sys/stat.h>
Tom Cherryf57c0bf2017-04-07 13:46:21 -070027#include <sys/system_properties.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070028#include <sys/time.h>
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -080029#include <sys/wait.h>
Tom Cherrybac32992015-07-31 12:45:25 -070030#include <termios.h>
Dan Albertaf9ba4d2015-08-11 16:37:04 -070031#include <unistd.h>
Tom Cherrybac32992015-07-31 12:45:25 -070032
Elliott Hughes4f713192015-12-04 22:00:26 -080033#include <android-base/file.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070034#include <android-base/logging.h>
Elliott Hughesda46b392016-10-11 17:09:00 -070035#include <android-base/parseint.h>
Tom Cherryccf23532017-03-28 16:40:41 -070036#include <android-base/properties.h>
Tom Cherry8d13d802017-06-29 16:18:08 -070037#include <android-base/scopeguard.h>
Elliott Hughes4f713192015-12-04 22:00:26 -080038#include <android-base/stringprintf.h>
Elliott Hughesf86b5a62016-06-24 15:12:21 -070039#include <android-base/strings.h>
Tom Cherry3f5eaae52017-04-06 16:30:22 -070040#include <processgroup/processgroup.h>
41#include <selinux/selinux.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070042#include <system/thread_defs.h>
Tom Cherrybac32992015-07-31 12:45:25 -070043
Tom Cherrybac32992015-07-31 12:45:25 -070044#include "init.h"
Tom Cherrybac32992015-07-31 12:45:25 -070045#include "property_service.h"
46#include "util.h"
47
James Hawkinse78ea772017-03-24 11:43:02 -070048using android::base::boot_clock;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070049using android::base::GetProperty;
50using android::base::Join;
Tom Cherry8d13d802017-06-29 16:18:08 -070051using android::base::make_scope_guard;
Elliott Hughesda46b392016-10-11 17:09:00 -070052using android::base::ParseInt;
Tom Cherry81f5d3e2017-06-22 12:53:17 -070053using android::base::StartsWith;
Tom Cherryb7349902015-08-26 11:43:36 -070054using android::base::StringPrintf;
55using android::base::WriteStringToFile;
56
Tom Cherry81f5d3e2017-06-22 12:53:17 -070057namespace android {
58namespace init {
59
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040060static std::string ComputeContextFromExecutable(std::string& service_name,
61 const std::string& service_path) {
62 std::string computed_context;
63
64 char* raw_con = nullptr;
65 char* raw_filecon = nullptr;
66
67 if (getcon(&raw_con) == -1) {
68 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
69 return "";
70 }
71 std::unique_ptr<char> mycon(raw_con);
72
73 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
74 LOG(ERROR) << "could not get file context while starting '" << service_name << "'";
75 return "";
76 }
77 std::unique_ptr<char> filecon(raw_filecon);
78
79 char* new_con = nullptr;
80 int rc = security_compute_create(mycon.get(), filecon.get(),
81 string_to_security_class("process"), &new_con);
82 if (rc == 0) {
83 computed_context = new_con;
84 free(new_con);
85 }
86 if (rc == 0 && computed_context == mycon.get()) {
87 LOG(ERROR) << "service " << service_name << " does not have a SELinux domain defined";
88 return "";
89 }
90 if (rc < 0) {
91 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
92 return "";
93 }
94 return computed_context;
95}
96
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070097static void SetUpPidNamespace(const std::string& service_name) {
98 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
99
100 // It's OK to LOG(FATAL) in this function since it's running in the first
101 // child process.
102 if (mount("", "/proc", "proc", kSafeFlags | MS_REMOUNT, "") == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700103 PLOG(FATAL) << "couldn't remount(/proc) for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700104 }
105
106 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700107 PLOG(FATAL) << "couldn't set name for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700108 }
109
110 pid_t child_pid = fork();
111 if (child_pid == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700112 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700113 }
114
115 if (child_pid > 0) {
116 // So that we exit with the right status.
117 static int init_exitstatus = 0;
118 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
119
120 pid_t waited_pid;
121 int status;
122 while ((waited_pid = wait(&status)) > 0) {
123 // This loop will end when there are no processes left inside the
124 // PID namespace or when the init process inside the PID namespace
125 // gets a signal.
126 if (waited_pid == child_pid) {
127 init_exitstatus = status;
128 }
129 }
130 if (!WIFEXITED(init_exitstatus)) {
131 _exit(EXIT_FAILURE);
132 }
133 _exit(WEXITSTATUS(init_exitstatus));
134 }
135}
136
Tom Cherry48db85c2017-09-11 16:08:54 -0700137static bool ExpandArgsAndExecve(const std::vector<std::string>& args) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400138 std::vector<std::string> expanded_args;
Tom Cherry48db85c2017-09-11 16:08:54 -0700139 std::vector<char*> c_strings;
140
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400141 expanded_args.resize(args.size());
Tom Cherry48db85c2017-09-11 16:08:54 -0700142 c_strings.push_back(const_cast<char*>(args[0].data()));
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400143 for (std::size_t i = 1; i < args.size(); ++i) {
144 if (!expand_props(args[i], &expanded_args[i])) {
145 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
146 }
Tom Cherry48db85c2017-09-11 16:08:54 -0700147 c_strings.push_back(expanded_args[i].data());
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400148 }
Tom Cherry48db85c2017-09-11 16:08:54 -0700149 c_strings.push_back(nullptr);
150
151 return execve(c_strings[0], c_strings.data(), (char**)ENV) == 0;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400152}
153
Tom Cherrybac32992015-07-31 12:45:25 -0700154ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
155}
156
157ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
158 const std::string& value)
159 : name(name), value(value) {
160}
161
Wei Wang641ff0a2017-03-27 10:59:11 -0700162Service::Service(const std::string& name, const std::vector<std::string>& args)
163 : name_(name),
164 classnames_({"default"}),
165 flags_(0),
166 pid_(0),
167 crash_count_(0),
168 uid_(0),
169 gid_(0),
170 namespace_flags_(0),
171 seclabel_(""),
Tom Cherry012c5732017-04-18 13:21:54 -0700172 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Tom Cherry7da54852017-05-01 14:16:41 -0700173 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700174 ioprio_class_(IoSchedClass_NONE),
175 ioprio_pri_(0),
176 priority_(0),
177 oom_score_adjust_(-1000),
Robert Benead4852262017-07-16 19:38:11 -0700178 swappiness_(-1),
179 soft_limit_in_bytes_(-1),
180 limit_in_bytes_(-1),
Wei Wang641ff0a2017-03-27 10:59:11 -0700181 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700182 onrestart_.InitSingleTrigger("onrestart");
183}
184
Wei Wang641ff0a2017-03-27 10:59:11 -0700185Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
186 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
187 unsigned namespace_flags, const std::string& seclabel,
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700188 const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700189 : name_(name),
190 classnames_({"default"}),
191 flags_(flags),
192 pid_(0),
193 crash_count_(0),
194 uid_(uid),
195 gid_(gid),
196 supp_gids_(supp_gids),
197 capabilities_(capabilities),
198 namespace_flags_(namespace_flags),
199 seclabel_(seclabel),
Tom Cherry012c5732017-04-18 13:21:54 -0700200 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Tom Cherry7da54852017-05-01 14:16:41 -0700201 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700202 ioprio_class_(IoSchedClass_NONE),
203 ioprio_pri_(0),
204 priority_(0),
205 oom_score_adjust_(-1000),
Robert Benead4852262017-07-16 19:38:11 -0700206 swappiness_(-1),
207 soft_limit_in_bytes_(-1),
208 limit_in_bytes_(-1),
Wei Wang641ff0a2017-03-27 10:59:11 -0700209 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700210 onrestart_.InitSingleTrigger("onrestart");
211}
212
213void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700214 if ((flags_ & SVC_TEMPORARY) != 0) {
215 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700216 return;
217 }
218
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700219 std::string prop_name = "init.svc." + name_;
220 property_set(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800221
222 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800223 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700224 property_set("ro.boottime." + name_, std::to_string(start_ns));
Elliott Hughes9605a942016-11-10 17:43:47 -0800225 }
Tom Cherrybac32992015-07-31 12:45:25 -0700226}
227
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700228void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700229 // If we've already seen a successful result from killProcessGroup*(), then we have removed
230 // the cgroup already and calling these functions a second time will simply result in an error.
231 // This is true regardless of which signal was sent.
232 // These functions handle their own logging, so no additional logging is needed.
233 if (!process_cgroup_empty_) {
234 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
235 << ") process group...";
236 int r;
237 if (signal == SIGTERM) {
238 r = killProcessGroupOnce(uid_, pid_, signal);
239 } else {
240 r = killProcessGroup(uid_, pid_, signal);
241 }
242
243 if (r == 0) process_cgroup_empty_ = true;
244 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700245}
246
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400247void Service::SetProcessAttributes() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400248 // Keep capabilites on uid change.
249 if (capabilities_.any() && uid_) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700250 // If Android is running in a container, some securebits might already
251 // be locked, so don't change those.
Ben Fennema7d7e7cd2017-07-25 14:37:21 -0700252 unsigned long securebits = prctl(PR_GET_SECUREBITS);
253 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700254 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
255 }
256 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
257 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
258 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400259 }
260 }
261
Elliott Hughese18e7e52016-07-25 18:18:16 -0700262 // TODO: work out why this fails for `console` then upgrade to FATAL.
263 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400264
265 if (gid_) {
266 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700267 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400268 }
269 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700270 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
271 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400272 }
273 if (uid_) {
274 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700275 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400276 }
277 }
278 if (!seclabel_.empty()) {
279 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700280 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400281 }
282 }
283 if (priority_ != 0) {
284 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700285 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400286 }
287 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400288 if (capabilities_.any()) {
289 if (!SetCapsForExec(capabilities_)) {
290 LOG(FATAL) << "cannot set capabilities for " << name_;
291 }
292 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400293}
294
Tom Cherryb27004a2017-03-27 16:27:30 -0700295void Service::Reap() {
Tom Cherrybac32992015-07-31 12:45:25 -0700296 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700297 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700298 }
299
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700300 // Remove any descriptor resources we may have created.
301 std::for_each(descriptors_.begin(), descriptors_.end(),
302 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700303
Tom Cherryb27004a2017-03-27 16:27:30 -0700304 if (flags_ & SVC_TEMPORARY) {
305 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700306 }
307
308 pid_ = 0;
309 flags_ &= (~SVC_RUNNING);
310
311 // Oneshot processes go into the disabled state on exit,
312 // except when manually restarted.
313 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
314 flags_ |= SVC_DISABLED;
315 }
316
317 // Disabled and reset processes do not get restarted automatically.
318 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
319 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700320 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700321 }
322
Elliott Hughes9605a942016-11-10 17:43:47 -0800323 // If we crash > 4 times in 4 minutes, reboot into recovery.
324 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700325 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800326 if (now < time_crashed_ + 4min) {
327 if (++crash_count_ > 4) {
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000328 LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
329 panic();
Tom Cherrybac32992015-07-31 12:45:25 -0700330 }
331 } else {
332 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800333 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700334 }
335 }
336
337 flags_ &= (~SVC_RESTART);
338 flags_ |= SVC_RESTARTING;
339
340 // Execute all onrestart commands for this service.
341 onrestart_.ExecuteAllCommands();
342
343 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700344 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700345}
346
347void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700348 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700349 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
350 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700351 std::for_each(descriptors_.begin(), descriptors_.end(),
352 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700353}
354
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400355bool Service::ParseCapabilities(const std::vector<std::string>& args, std::string* err) {
356 capabilities_ = 0;
357
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500358 if (!CapAmbientSupported()) {
359 *err = "capabilities requested but the kernel does not support ambient capabilities";
360 return false;
361 }
362
363 unsigned int last_valid_cap = GetLastValidCap();
364 if (last_valid_cap >= capabilities_.size()) {
365 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
366 }
367
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400368 for (size_t i = 1; i < args.size(); i++) {
369 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500370 int res = LookupCap(arg);
371 if (res < 0) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400372 *err = StringPrintf("invalid capability '%s'", arg.c_str());
373 return false;
374 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500375 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
376 if (cap > last_valid_cap) {
377 *err = StringPrintf("capability '%s' not supported by the kernel", arg.c_str());
378 return false;
379 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400380 capabilities_[cap] = true;
381 }
382 return true;
383}
384
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400385bool Service::ParseClass(const std::vector<std::string>& args, std::string* err) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700386 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherryb7349902015-08-26 11:43:36 -0700387 return true;
388}
Tom Cherrybac32992015-07-31 12:45:25 -0700389
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400390bool Service::ParseConsole(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700391 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200392 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherryb7349902015-08-26 11:43:36 -0700393 return true;
394}
Tom Cherrybac32992015-07-31 12:45:25 -0700395
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400396bool Service::ParseCritical(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700397 flags_ |= SVC_CRITICAL;
398 return true;
399}
Tom Cherrybac32992015-07-31 12:45:25 -0700400
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400401bool Service::ParseDisabled(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700402 flags_ |= SVC_DISABLED;
403 flags_ |= SVC_RC_DISABLED;
404 return true;
405}
Tom Cherrybac32992015-07-31 12:45:25 -0700406
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400407bool Service::ParseGroup(const std::vector<std::string>& args, std::string* err) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700408 std::string decode_uid_err;
409 if (!DecodeUid(args[1], &gid_, &decode_uid_err)) {
410 *err = "Unable to find GID for '" + args[1] + "': " + decode_uid_err;
411 return false;
412 }
Tom Cherryb7349902015-08-26 11:43:36 -0700413 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700414 gid_t gid;
415 if (!DecodeUid(args[n], &gid, &decode_uid_err)) {
416 *err = "Unable to find GID for '" + args[n] + "': " + decode_uid_err;
417 return false;
418 }
419 supp_gids_.emplace_back(gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700420 }
421 return true;
422}
423
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400424bool Service::ParsePriority(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700425 priority_ = 0;
426 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800427 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
428 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700429 *err = StringPrintf("process priority value must be range %d - %d",
430 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
431 return false;
432 }
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700433 return true;
434}
435
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400436bool Service::ParseIoprio(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700437 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherryb7349902015-08-26 11:43:36 -0700438 *err = "priority value must be range 0 - 7";
439 return false;
440 }
441
442 if (args[1] == "rt") {
443 ioprio_class_ = IoSchedClass_RT;
444 } else if (args[1] == "be") {
445 ioprio_class_ = IoSchedClass_BE;
446 } else if (args[1] == "idle") {
447 ioprio_class_ = IoSchedClass_IDLE;
448 } else {
449 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
450 return false;
451 }
452
453 return true;
454}
455
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400456bool Service::ParseKeycodes(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700457 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700458 int code;
459 if (ParseInt(args[i], &code)) {
460 keycodes_.emplace_back(code);
461 } else {
462 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
463 }
Tom Cherryb7349902015-08-26 11:43:36 -0700464 }
465 return true;
466}
467
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400468bool Service::ParseOneshot(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700469 flags_ |= SVC_ONESHOT;
470 return true;
471}
472
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400473bool Service::ParseOnrestart(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700474 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700475 int line = onrestart_.NumCommands() + 1;
476 onrestart_.AddCommand(str_args, line, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700477 return true;
478}
479
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400480bool Service::ParseNamespace(const std::vector<std::string>& args, std::string* err) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700481 for (size_t i = 1; i < args.size(); i++) {
482 if (args[i] == "pid") {
483 namespace_flags_ |= CLONE_NEWPID;
484 // PID namespaces require mount namespaces.
485 namespace_flags_ |= CLONE_NEWNS;
486 } else if (args[i] == "mnt") {
487 namespace_flags_ |= CLONE_NEWNS;
488 } else {
489 *err = "namespace must be 'pid' or 'mnt'";
490 return false;
491 }
492 }
493 return true;
494}
495
Marco Nelissen310f6702016-07-22 12:07:06 -0700496bool Service::ParseOomScoreAdjust(const std::vector<std::string>& args, std::string* err) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700497 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Marco Nelissen310f6702016-07-22 12:07:06 -0700498 *err = "oom_score_adjust value must be in range -1000 - +1000";
499 return false;
500 }
Marco Nelissen310f6702016-07-22 12:07:06 -0700501 return true;
502}
503
Robert Benead4852262017-07-16 19:38:11 -0700504bool Service::ParseMemcgSwappiness(const std::vector<std::string>& args, std::string* err) {
505 if (!ParseInt(args[1], &swappiness_, 0)) {
506 *err = "swappiness value must be equal or greater than 0";
507 return false;
508 }
509 return true;
510}
511
512bool Service::ParseMemcgLimitInBytes(const std::vector<std::string>& args, std::string* err) {
513 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
514 *err = "limit_in_bytes value must be equal or greater than 0";
515 return false;
516 }
517 return true;
518}
519
520bool Service::ParseMemcgSoftLimitInBytes(const std::vector<std::string>& args, std::string* err) {
521 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
522 *err = "soft_limit_in_bytes value must be equal or greater than 0";
523 return false;
524 }
525 return true;
526}
527
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400528bool Service::ParseSeclabel(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700529 seclabel_ = args[1];
530 return true;
531}
532
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400533bool Service::ParseSetenv(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700534 envvars_.emplace_back(args[1], args[2]);
535 return true;
536}
537
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700538bool Service::ParseShutdown(const std::vector<std::string>& args, std::string* err) {
539 if (args[1] == "critical") {
540 flags_ |= SVC_SHUTDOWN_CRITICAL;
541 return true;
542 }
543 return false;
544}
545
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700546template <typename T>
547bool Service::AddDescriptor(const std::vector<std::string>& args, std::string* err) {
548 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry517e1f12017-05-04 17:40:33 -0700549 uid_t uid = 0;
550 gid_t gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700551 std::string context = args.size() > 6 ? args[6] : "";
552
Tom Cherry517e1f12017-05-04 17:40:33 -0700553 std::string decode_uid_err;
554 if (args.size() > 4) {
555 if (!DecodeUid(args[4], &uid, &decode_uid_err)) {
556 *err = "Unable to find UID for '" + args[4] + "': " + decode_uid_err;
557 return false;
558 }
559 }
560
561 if (args.size() > 5) {
562 if (!DecodeUid(args[5], &gid, &decode_uid_err)) {
563 *err = "Unable to find GID for '" + args[5] + "': " + decode_uid_err;
564 return false;
565 }
566 }
567
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700568 auto descriptor = std::make_unique<T>(args[1], args[2], uid, gid, perm, context);
569
570 auto old =
571 std::find_if(descriptors_.begin(), descriptors_.end(),
572 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
573
574 if (old != descriptors_.end()) {
575 *err = "duplicate descriptor " + args[1] + " " + args[2];
576 return false;
577 }
578
579 descriptors_.emplace_back(std::move(descriptor));
580 return true;
581}
582
583// name type perm [ uid gid context ]
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400584bool Service::ParseSocket(const std::vector<std::string>& args, std::string* err) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700585 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
586 !StartsWith(args[2], "seqpacket")) {
Tom Cherryb7349902015-08-26 11:43:36 -0700587 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
588 return false;
589 }
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700590 return AddDescriptor<SocketInfo>(args, err);
591}
Tom Cherryb7349902015-08-26 11:43:36 -0700592
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700593// name type perm [ uid gid context ]
594bool Service::ParseFile(const std::vector<std::string>& args, std::string* err) {
595 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
596 *err = "file type must be 'r', 'w' or 'rw'";
597 return false;
598 }
599 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
600 *err = "file name must not be relative";
601 return false;
602 }
603 return AddDescriptor<FileInfo>(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700604}
605
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400606bool Service::ParseUser(const std::vector<std::string>& args, std::string* err) {
Tom Cherry517e1f12017-05-04 17:40:33 -0700607 std::string decode_uid_err;
608 if (!DecodeUid(args[1], &uid_, &decode_uid_err)) {
609 *err = "Unable to find UID for '" + args[1] + "': " + decode_uid_err;
610 return false;
611 }
Tom Cherryb7349902015-08-26 11:43:36 -0700612 return true;
613}
614
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400615bool Service::ParseWritepid(const std::vector<std::string>& args, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -0700616 writepid_files_.assign(args.begin() + 1, args.end());
617 return true;
618}
619
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400620class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700621 public:
622 OptionParserMap() {}
623
624 private:
625 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700626};
627
Tom Cherryad54d092017-04-19 16:18:50 -0700628const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700629 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700630 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400631 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400632 {"capabilities",
633 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700634 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400635 {"console", {0, 1, &Service::ParseConsole}},
636 {"critical", {0, 0, &Service::ParseCritical}},
637 {"disabled", {0, 0, &Service::ParseDisabled}},
638 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
639 {"ioprio", {2, 2, &Service::ParseIoprio}},
640 {"priority", {1, 1, &Service::ParsePriority}},
641 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
642 {"oneshot", {0, 0, &Service::ParseOneshot}},
643 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700644 {"oom_score_adjust",
645 {1, 1, &Service::ParseOomScoreAdjust}},
Robert Benead4852262017-07-16 19:38:11 -0700646 {"memcg.swappiness",
647 {1, 1, &Service::ParseMemcgSwappiness}},
648 {"memcg.soft_limit_in_bytes",
649 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
650 {"memcg.limit_in_bytes",
651 {1, 1, &Service::ParseMemcgLimitInBytes}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400652 {"namespace", {1, 2, &Service::ParseNamespace}},
653 {"seclabel", {1, 1, &Service::ParseSeclabel}},
654 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700655 {"shutdown", {1, 1, &Service::ParseShutdown}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400656 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn978fd0e2016-12-02 08:05:22 -0800657 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400658 {"user", {1, 1, &Service::ParseUser}},
659 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700660 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700661 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400662 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700663}
664
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400665bool Service::ParseLine(const std::vector<std::string>& args, std::string* err) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400666 static const OptionParserMap parser_map;
Tom Cherryfe062052017-04-24 16:59:05 -0700667 auto parser = parser_map.FindFunction(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700668
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400669 if (!parser) {
Tom Cherryb7349902015-08-26 11:43:36 -0700670 return false;
671 }
672
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400673 return (this->*parser)(args, err);
Tom Cherryb7349902015-08-26 11:43:36 -0700674}
675
Tom Cherryede0d532017-07-06 14:20:11 -0700676bool Service::ExecStart(std::unique_ptr<android::base::Timer>* exec_waiter) {
Tom Cherryb27004a2017-03-27 16:27:30 -0700677 flags_ |= SVC_EXEC | SVC_ONESHOT;
678
Tom Cherryede0d532017-07-06 14:20:11 -0700679 exec_waiter->reset(new android::base::Timer);
Tom Cherryb27004a2017-03-27 16:27:30 -0700680
681 if (!Start()) {
682 exec_waiter->reset();
683 return false;
684 }
685 return true;
686}
687
Elliott Hughesbdeac392016-04-12 15:38:27 -0700688bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700689 // Starting a service removes it from the disabled or reset state and
690 // immediately takes it out of the restarting state if it was in there.
691 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700692
693 // Running processes require no additional work --- if they're in the
694 // process of exiting, we've ensured that they will immediately restart
695 // on exit, unless they are ONESHOT.
696 if (flags_ & SVC_RUNNING) {
697 return false;
698 }
699
700 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200701 if (needs_console) {
702 if (console_.empty()) {
703 console_ = default_console;
704 }
705
Adrian Salido24ef8602016-12-20 15:52:15 -0800706 // Make sure that open call succeeds to ensure a console driver is
707 // properly registered for the device node
708 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
709 if (console_fd < 0) {
710 PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200711 flags_ |= SVC_DISABLED;
712 return false;
713 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800714 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700715 }
716
717 struct stat sb;
718 if (stat(args_[0].c_str(), &sb) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700719 PLOG(ERROR) << "cannot find '" << args_[0] << "', disabling '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700720 flags_ |= SVC_DISABLED;
721 return false;
722 }
723
Tom Cherrybac32992015-07-31 12:45:25 -0700724 std::string scon;
725 if (!seclabel_.empty()) {
726 scon = seclabel_;
727 } else {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400728 scon = ComputeContextFromExecutable(name_, args_[0]);
729 if (scon == "") {
Tom Cherrybac32992015-07-31 12:45:25 -0700730 return false;
731 }
732 }
733
Wei Wanga285dac2016-10-04 14:05:39 -0700734 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700735
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700736 pid_t pid = -1;
737 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400738 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700739 } else {
740 pid = fork();
741 }
742
Tom Cherrybac32992015-07-31 12:45:25 -0700743 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700744 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700745
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700746 if (namespace_flags_ & CLONE_NEWPID) {
747 // This will fork again to run an init process inside the PID
748 // namespace.
749 SetUpPidNamespace(name_);
750 }
751
Tom Cherrybac32992015-07-31 12:45:25 -0700752 for (const auto& ei : envvars_) {
753 add_environment(ei.name.c_str(), ei.value.c_str());
754 }
755
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700756 std::for_each(descriptors_.begin(), descriptors_.end(),
757 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700758
Alex Vakulenko08286762016-05-03 12:00:00 -0700759 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
760 auto cpuset_predicate = [](const std::string& path) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700761 return StartsWith(path, "/dev/cpuset/");
Alex Vakulenko08286762016-05-03 12:00:00 -0700762 };
763 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
764 if (iter == writepid_files_.end()) {
765 // There were no "writepid" instructions for cpusets, check if the system default
766 // cpuset is specified to be used for the process.
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700767 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700768 if (!default_cpuset.empty()) {
769 // Make sure the cpuset name starts and ends with '/'.
770 // A single '/' means the 'root' cpuset.
771 if (default_cpuset.front() != '/') {
772 default_cpuset.insert(0, 1, '/');
773 }
774 if (default_cpuset.back() != '/') {
775 default_cpuset.push_back('/');
776 }
777 writepid_files_.push_back(
778 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
779 }
780 }
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700781 std::string pid_str = std::to_string(getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700782 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700783 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700784 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700785 }
786 }
787
788 if (ioprio_class_ != IoSchedClass_NONE) {
789 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400790 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700791 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700792 }
793 }
794
795 if (needs_console) {
796 setsid();
797 OpenConsole();
798 } else {
799 ZapStdio();
800 }
801
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400802 // As requested, set our gid, supplemental gids, uid, context, and
803 // priority. Aborts on failure.
804 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700805
Tom Cherry48db85c2017-09-11 16:08:54 -0700806 if (!ExpandArgsAndExecve(args_)) {
807 PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700808 }
809
810 _exit(127);
811 }
812
813 if (pid < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700814 PLOG(ERROR) << "failed to fork for '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700815 pid_ = 0;
816 return false;
817 }
818
Marco Nelissen310f6702016-07-22 12:07:06 -0700819 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700820 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700821 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
822 if (!WriteStringToFile(oom_str, oom_file)) {
823 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
824 }
825 }
826
Elliott Hughes9605a942016-11-10 17:43:47 -0800827 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700828 pid_ = pid;
829 flags_ |= SVC_RUNNING;
Tom Cherry33838b12017-05-04 11:32:36 -0700830 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700831
832 errno = -createProcessGroup(uid_, pid_);
833 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400834 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
835 << name_ << "'";
Robert Benead4852262017-07-16 19:38:11 -0700836 } else {
837 if (swappiness_ != -1) {
838 if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
839 PLOG(ERROR) << "setProcessGroupSwappiness failed";
840 }
841 }
842
843 if (soft_limit_in_bytes_ != -1) {
844 if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
845 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
846 }
847 }
848
849 if (limit_in_bytes_ != -1) {
850 if (!setProcessGroupLimit(uid_, pid_, limit_in_bytes_)) {
851 PLOG(ERROR) << "setProcessGroupLimit failed";
852 }
853 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700854 }
Tom Cherrybac32992015-07-31 12:45:25 -0700855
856 if ((flags_ & SVC_EXEC) != 0) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700857 LOG(INFO) << "SVC_EXEC pid " << pid_ << " (uid " << uid_ << " gid " << gid_ << "+"
858 << supp_gids_.size() << " context "
859 << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
Tom Cherrybac32992015-07-31 12:45:25 -0700860 }
861
862 NotifyStateChange("running");
863 return true;
864}
865
Tom Cherrybac32992015-07-31 12:45:25 -0700866bool Service::StartIfNotDisabled() {
867 if (!(flags_ & SVC_DISABLED)) {
868 return Start();
869 } else {
870 flags_ |= SVC_DISABLED_START;
871 }
872 return true;
873}
874
875bool Service::Enable() {
876 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
877 if (flags_ & SVC_DISABLED_START) {
878 return Start();
879 }
880 return true;
881}
882
883void Service::Reset() {
884 StopOrReset(SVC_RESET);
885}
886
887void Service::Stop() {
888 StopOrReset(SVC_DISABLED);
889}
890
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800891void Service::Terminate() {
892 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
893 flags_ |= SVC_DISABLED;
894 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700895 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800896 NotifyStateChange("stopping");
897 }
898}
899
Tom Cherrybac32992015-07-31 12:45:25 -0700900void Service::Restart() {
901 if (flags_ & SVC_RUNNING) {
902 /* Stop, wait, then start the service. */
903 StopOrReset(SVC_RESTART);
904 } else if (!(flags_ & SVC_RESTARTING)) {
905 /* Just start the service since it's not running. */
906 Start();
907 } /* else: Service is restarting anyways. */
908}
909
Elliott Hughes9605a942016-11-10 17:43:47 -0800910void Service::RestartIfNeeded(time_t* process_needs_restart_at) {
911 boot_clock::time_point now = boot_clock::now();
912 boot_clock::time_point next_start = time_started_ + 5s;
913 if (now > next_start) {
Tom Cherrybac32992015-07-31 12:45:25 -0700914 flags_ &= (~SVC_RESTARTING);
915 Start();
916 return;
917 }
918
Elliott Hughes9605a942016-11-10 17:43:47 -0800919 time_t next_start_time_t = time(nullptr) +
920 time_t(std::chrono::duration_cast<std::chrono::seconds>(next_start - now).count());
921 if (next_start_time_t < *process_needs_restart_at || *process_needs_restart_at == 0) {
922 *process_needs_restart_at = next_start_time_t;
Tom Cherrybac32992015-07-31 12:45:25 -0700923 }
924}
925
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700926// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700927void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700928 // The service is still SVC_RUNNING until its process exits, but if it has
929 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700930 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
931
932 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700933 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700934 how = SVC_DISABLED;
935 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700936
937 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700938 if (how == SVC_RESET) {
939 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
940 } else {
941 flags_ |= how;
942 }
943
944 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700945 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700946 NotifyStateChange("stopping");
947 } else {
948 NotifyStateChange("stopped");
949 }
950}
951
952void Service::ZapStdio() const {
953 int fd;
954 fd = open("/dev/null", O_RDWR);
955 dup2(fd, 0);
956 dup2(fd, 1);
957 dup2(fd, 2);
958 close(fd);
959}
960
961void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200962 int fd = open(console_.c_str(), O_RDWR);
963 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700964 ioctl(fd, TIOCSCTTY, 0);
965 dup2(fd, 0);
966 dup2(fd, 1);
967 dup2(fd, 2);
968 close(fd);
969}
970
Tom Cherrybac32992015-07-31 12:45:25 -0700971int ServiceManager::exec_count_ = 0;
972
973ServiceManager::ServiceManager() {
974}
975
976ServiceManager& ServiceManager::GetInstance() {
977 static ServiceManager instance;
978 return instance;
979}
980
Tom Cherryb7349902015-08-26 11:43:36 -0700981void ServiceManager::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -0700982 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700983}
984
Tom Cherryb27004a2017-03-27 16:27:30 -0700985bool ServiceManager::Exec(const std::vector<std::string>& args) {
986 Service* svc = MakeExecOneshotService(args);
987 if (!svc) {
988 LOG(ERROR) << "Could not create exec service";
989 return false;
990 }
991 if (!svc->ExecStart(&exec_waiter_)) {
992 LOG(ERROR) << "Could not start exec service";
993 ServiceManager::GetInstance().RemoveService(*svc);
994 return false;
995 }
996 return true;
997}
998
999bool ServiceManager::ExecStart(const std::string& name) {
1000 Service* svc = FindServiceByName(name);
1001 if (!svc) {
1002 LOG(ERROR) << "ExecStart(" << name << "): Service not found";
1003 return false;
1004 }
1005 if (!svc->ExecStart(&exec_waiter_)) {
1006 LOG(ERROR) << "ExecStart(" << name << "): Could not start Service";
1007 return false;
1008 }
1009 return true;
1010}
1011
1012bool ServiceManager::IsWaitingForExec() const { return exec_waiter_ != nullptr; }
1013
Tom Cherrybac32992015-07-31 12:45:25 -07001014Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
1015 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
1016 // SECLABEL can be a - to denote default
1017 std::size_t command_arg = 1;
1018 for (std::size_t i = 1; i < args.size(); ++i) {
1019 if (args[i] == "--") {
1020 command_arg = i + 1;
1021 break;
1022 }
1023 }
1024 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001025 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -07001026 return nullptr;
1027 }
1028
1029 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -07001030 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -07001031 return nullptr;
1032 }
1033 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
1034
1035 exec_count_++;
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001036 std::string name = "exec " + std::to_string(exec_count_) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -07001037
Tom Cherryb27004a2017-03-27 16:27:30 -07001038 unsigned flags = SVC_EXEC | SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -04001039 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -07001040 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -07001041
1042 std::string seclabel = "";
1043 if (command_arg > 2 && args[1] != "-") {
1044 seclabel = args[1];
1045 }
1046 uid_t uid = 0;
1047 if (command_arg > 3) {
Tom Cherry517e1f12017-05-04 17:40:33 -07001048 std::string decode_uid_err;
1049 if (!DecodeUid(args[2], &uid, &decode_uid_err)) {
1050 LOG(ERROR) << "Unable to find UID for '" << args[2] << "': " << decode_uid_err;
1051 return nullptr;
1052 }
Tom Cherrybac32992015-07-31 12:45:25 -07001053 }
1054 gid_t gid = 0;
1055 std::vector<gid_t> supp_gids;
1056 if (command_arg > 4) {
Tom Cherry517e1f12017-05-04 17:40:33 -07001057 std::string decode_uid_err;
1058 if (!DecodeUid(args[3], &gid, &decode_uid_err)) {
1059 LOG(ERROR) << "Unable to find GID for '" << args[3] << "': " << decode_uid_err;
1060 return nullptr;
1061 }
Tom Cherrybac32992015-07-31 12:45:25 -07001062 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
1063 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry517e1f12017-05-04 17:40:33 -07001064 gid_t supp_gid;
1065 if (!DecodeUid(args[4 + i], &supp_gid, &decode_uid_err)) {
1066 LOG(ERROR) << "Unable to find UID for '" << args[4 + i] << "': " << decode_uid_err;
1067 return nullptr;
1068 }
1069 supp_gids.push_back(supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -07001070 }
1071 }
1072
Wei Wang641ff0a2017-03-27 10:59:11 -07001073 auto svc_p = std::make_unique<Service>(name, flags, uid, gid, supp_gids, no_capabilities,
1074 namespace_flags, seclabel, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001075 Service* svc = svc_p.get();
Tom Cherry9bdddd72017-03-23 16:07:51 -07001076 services_.emplace_back(std::move(svc_p));
Tom Cherrybac32992015-07-31 12:45:25 -07001077
1078 return svc;
1079}
1080
1081Service* ServiceManager::FindServiceByName(const std::string& name) const {
1082 auto svc = std::find_if(services_.begin(), services_.end(),
1083 [&name] (const std::unique_ptr<Service>& s) {
1084 return name == s->name();
1085 });
1086 if (svc != services_.end()) {
1087 return svc->get();
1088 }
1089 return nullptr;
1090}
1091
1092Service* ServiceManager::FindServiceByPid(pid_t pid) const {
1093 auto svc = std::find_if(services_.begin(), services_.end(),
1094 [&pid] (const std::unique_ptr<Service>& s) {
1095 return s->pid() == pid;
1096 });
1097 if (svc != services_.end()) {
1098 return svc->get();
1099 }
1100 return nullptr;
1101}
1102
1103Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
1104 auto svc = std::find_if(services_.begin(), services_.end(),
1105 [&keychord_id] (const std::unique_ptr<Service>& s) {
1106 return s->keychord_id() == keychord_id;
1107 });
1108
1109 if (svc != services_.end()) {
1110 return svc->get();
1111 }
1112 return nullptr;
1113}
1114
Chih-Hung Hsieh8f7b9e32016-07-27 16:25:51 -07001115void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -07001116 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001117 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -07001118 }
1119}
1120
1121void ServiceManager::ForEachServiceInClass(const std::string& classname,
1122 void (*func)(Service* svc)) const {
1123 for (const auto& s : services_) {
Wei Wang641ff0a2017-03-27 10:59:11 -07001124 if (s->classnames().find(classname) != s->classnames().end()) {
Tom Cherrybac32992015-07-31 12:45:25 -07001125 func(s.get());
1126 }
1127 }
1128}
1129
1130void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
1131 void (*func)(Service* svc)) const {
1132 for (const auto& s : services_) {
1133 if (s->flags() & matchflags) {
1134 func(s.get());
1135 }
1136 }
1137}
1138
Tom Cherryb7349902015-08-26 11:43:36 -07001139void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001140 auto svc_it = std::find_if(services_.begin(), services_.end(),
1141 [&svc] (const std::unique_ptr<Service>& s) {
1142 return svc.name() == s->name();
1143 });
1144 if (svc_it == services_.end()) {
1145 return;
1146 }
1147
1148 services_.erase(svc_it);
1149}
1150
Tom Cherryb7349902015-08-26 11:43:36 -07001151void ServiceManager::DumpState() const {
1152 for (const auto& s : services_) {
1153 s->DumpState();
1154 }
Tom Cherryb7349902015-08-26 11:43:36 -07001155}
1156
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001157bool ServiceManager::ReapOneProcess() {
Tom Cherry8d13d802017-06-29 16:18:08 -07001158 siginfo_t siginfo = {};
1159 // This returns a zombie pid or informs us that there are no zombies left to be reaped.
1160 // It does NOT reap the pid; that is done below.
1161 if (TEMP_FAILURE_RETRY(waitid(P_ALL, 0, &siginfo, WEXITED | WNOHANG | WNOWAIT)) != 0) {
1162 PLOG(ERROR) << "waitid failed";
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001163 return false;
Tom Cherry8d13d802017-06-29 16:18:08 -07001164 }
1165
1166 auto pid = siginfo.si_pid;
1167 if (pid == 0) return false;
1168
1169 // At this point we know we have a zombie pid, so we use this scopeguard to reap the pid
1170 // whenever the function returns from this point forward.
1171 // We do NOT want to reap the zombie earlier as in Service::Reap(), we kill(-pid, ...) and we
1172 // want the pid to remain valid throughout that (and potentially future) usages.
1173 auto reaper = make_scope_guard([pid] { TEMP_FAILURE_RETRY(waitpid(pid, nullptr, WNOHANG)); });
1174
1175 if (PropertyChildReap(pid)) {
Tom Marshall62696902017-06-09 18:29:23 +00001176 return true;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001177 }
1178
1179 Service* svc = FindServiceByPid(pid);
1180
1181 std::string name;
Keun-young Park4de31e12017-04-27 16:25:06 -07001182 std::string wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001183 if (svc) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001184 name = StringPrintf("Service '%s' (pid %d)", svc->name().c_str(), pid);
Keun-young Park4de31e12017-04-27 16:25:06 -07001185 if (svc->flags() & SVC_EXEC) {
Tom Cherryede0d532017-07-06 14:20:11 -07001186 wait_string = StringPrintf(" waiting took %f seconds",
1187 exec_waiter_->duration().count() / 1000.0f);
Keun-young Park4de31e12017-04-27 16:25:06 -07001188 }
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001189 } else {
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001190 name = StringPrintf("Untracked pid %d", pid);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001191 }
1192
Tom Cherry8d13d802017-06-29 16:18:08 -07001193 auto status = siginfo.si_status;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001194 if (WIFEXITED(status)) {
Keun-young Park4de31e12017-04-27 16:25:06 -07001195 LOG(INFO) << name << " exited with status " << WEXITSTATUS(status) << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001196 } else if (WIFSIGNALED(status)) {
Keun-young Park4de31e12017-04-27 16:25:06 -07001197 LOG(INFO) << name << " killed by signal " << WTERMSIG(status) << wait_string;
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001198 }
1199
1200 if (!svc) {
1201 return true;
1202 }
1203
Tom Cherryb27004a2017-03-27 16:27:30 -07001204 svc->Reap();
1205
1206 if (svc->flags() & SVC_EXEC) {
Tom Cherryb27004a2017-03-27 16:27:30 -07001207 exec_waiter_.reset();
1208 }
1209 if (svc->flags() & SVC_TEMPORARY) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -08001210 RemoveService(*svc);
1211 }
1212
1213 return true;
1214}
1215
1216void ServiceManager::ReapAnyOutstandingChildren() {
1217 while (ReapOneProcess()) {
1218 }
1219}
1220
Wei Wangeeab4912017-06-27 22:08:45 -07001221void ServiceManager::ClearExecWait() {
1222 // Clear EXEC flag if there is one pending
1223 // And clear the wait flag
1224 for (const auto& s : services_) {
1225 s->UnSetExec();
1226 }
1227 exec_waiter_.reset();
1228}
1229
Tom Cherry30a6f272017-04-19 15:31:58 -07001230bool ServiceParser::ParseSection(std::vector<std::string>&& args, const std::string& filename,
Tom Cherry012c5732017-04-18 13:21:54 -07001231 int line, std::string* err) {
Tom Cherryb7349902015-08-26 11:43:36 -07001232 if (args.size() < 3) {
1233 *err = "services must have a name and a program";
1234 return false;
1235 }
1236
1237 const std::string& name = args[1];
1238 if (!IsValidName(name)) {
1239 *err = StringPrintf("invalid service name '%s'", name.c_str());
1240 return false;
1241 }
1242
Tom Cherry30a6f272017-04-19 15:31:58 -07001243 Service* old_service = service_manager_->FindServiceByName(name);
1244 if (old_service) {
1245 *err = "ignored duplicate definition of service '" + name + "'";
1246 return false;
1247 }
1248
Tom Cherryb7349902015-08-26 11:43:36 -07001249 std::vector<std::string> str_args(args.begin() + 2, args.end());
Wei Wang641ff0a2017-03-27 10:59:11 -07001250 service_ = std::make_unique<Service>(name, str_args);
Tom Cherryb7349902015-08-26 11:43:36 -07001251 return true;
1252}
1253
Tom Cherry30a6f272017-04-19 15:31:58 -07001254bool ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) {
1255 return service_ ? service_->ParseLine(std::move(args), err) : false;
Tom Cherryb7349902015-08-26 11:43:36 -07001256}
1257
1258void ServiceParser::EndSection() {
1259 if (service_) {
Tom Cherry30a6f272017-04-19 15:31:58 -07001260 service_manager_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001261 }
1262}
1263
1264bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001265 // Property names can be any length, but may only contain certain characters.
1266 // Property values can contain any characters, but may only be a certain length.
1267 // (The latter restriction is needed because `start` and `stop` work by writing
1268 // the service name to the "ctl.start" and "ctl.stop" properties.)
1269 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001270}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001271
1272} // namespace init
1273} // namespace android