blob: 86e650faf235e5a530c1348ea7f1df0d723c2487 [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
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400137static void ExpandArgs(const std::vector<std::string>& args, std::vector<char*>* strs) {
138 std::vector<std::string> expanded_args;
139 expanded_args.resize(args.size());
140 strs->push_back(const_cast<char*>(args[0].c_str()));
141 for (std::size_t i = 1; i < args.size(); ++i) {
142 if (!expand_props(args[i], &expanded_args[i])) {
143 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
144 }
145 strs->push_back(const_cast<char*>(expanded_args[i].c_str()));
146 }
147 strs->push_back(nullptr);
148}
149
Tom Cherrybac32992015-07-31 12:45:25 -0700150ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
151}
152
153ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
154 const std::string& value)
155 : name(name), value(value) {
156}
157
Tom Cherry59383792017-07-26 16:09:09 -0700158unsigned long Service::next_start_order_ = 1;
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700159bool Service::is_exec_service_running_ = false;
Tom Cherry59383792017-07-26 16:09:09 -0700160
Wei Wang641ff0a2017-03-27 10:59:11 -0700161Service::Service(const std::string& name, const std::vector<std::string>& args)
Tom Cherry5d17d042017-07-21 12:42:07 -0700162 : Service(name, 0, 0, 0, {}, 0, 0, "", args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700163
Wei Wang641ff0a2017-03-27 10:59:11 -0700164Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
165 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
166 unsigned namespace_flags, const std::string& seclabel,
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700167 const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700168 : name_(name),
169 classnames_({"default"}),
170 flags_(flags),
171 pid_(0),
172 crash_count_(0),
173 uid_(uid),
174 gid_(gid),
175 supp_gids_(supp_gids),
176 capabilities_(capabilities),
177 namespace_flags_(namespace_flags),
178 seclabel_(seclabel),
Tom Cherry012c5732017-04-18 13:21:54 -0700179 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Tom Cherry7da54852017-05-01 14:16:41 -0700180 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700181 ioprio_class_(IoSchedClass_NONE),
182 ioprio_pri_(0),
183 priority_(0),
184 oom_score_adjust_(-1000),
Robert Benead4852262017-07-16 19:38:11 -0700185 swappiness_(-1),
186 soft_limit_in_bytes_(-1),
187 limit_in_bytes_(-1),
Tom Cherry59383792017-07-26 16:09:09 -0700188 start_order_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700189 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 Cherry1c3a53f2017-06-22 16:50:31 -0700199 std::string prop_name = "init.svc." + name_;
200 property_set(prop_name, new_state);
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();
Tom Cherryfed33732017-08-18 10:47:46 -0700204 std::string boottime_property = "ro.boottime." + name_;
205 if (GetProperty(boottime_property, "").empty()) {
206 property_set(boottime_property, std::to_string(start_ns));
207 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800208 }
Tom Cherrybac32992015-07-31 12:45:25 -0700209}
210
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700211void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700212 // If we've already seen a successful result from killProcessGroup*(), then we have removed
213 // the cgroup already and calling these functions a second time will simply result in an error.
214 // This is true regardless of which signal was sent.
215 // These functions handle their own logging, so no additional logging is needed.
216 if (!process_cgroup_empty_) {
217 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
218 << ") process group...";
219 int r;
220 if (signal == SIGTERM) {
221 r = killProcessGroupOnce(uid_, pid_, signal);
222 } else {
223 r = killProcessGroup(uid_, pid_, signal);
224 }
225
226 if (r == 0) process_cgroup_empty_ = true;
227 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700228}
229
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400230void Service::SetProcessAttributes() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400231 // Keep capabilites on uid change.
232 if (capabilities_.any() && uid_) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700233 // If Android is running in a container, some securebits might already
234 // be locked, so don't change those.
Ben Fennemaa7243602017-07-25 14:37:21 -0700235 unsigned long securebits = prctl(PR_GET_SECUREBITS);
236 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700237 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
238 }
239 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
240 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
241 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400242 }
243 }
244
Elliott Hughese18e7e52016-07-25 18:18:16 -0700245 // TODO: work out why this fails for `console` then upgrade to FATAL.
246 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400247
248 if (gid_) {
249 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700250 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400251 }
252 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700253 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
254 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400255 }
256 if (uid_) {
257 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700258 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400259 }
260 }
261 if (!seclabel_.empty()) {
262 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700263 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400264 }
265 }
266 if (priority_ != 0) {
267 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700268 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400269 }
270 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400271 if (capabilities_.any()) {
272 if (!SetCapsForExec(capabilities_)) {
273 LOG(FATAL) << "cannot set capabilities for " << name_;
274 }
275 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400276}
277
Tom Cherryb27004a2017-03-27 16:27:30 -0700278void Service::Reap() {
Tom Cherrybac32992015-07-31 12:45:25 -0700279 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700280 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700281 }
282
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700283 // Remove any descriptor resources we may have created.
284 std::for_each(descriptors_.begin(), descriptors_.end(),
285 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700286
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700287 if (flags_ & SVC_EXEC) UnSetExec();
288
289 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700290
291 pid_ = 0;
292 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700293 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700294
295 // Oneshot processes go into the disabled state on exit,
296 // except when manually restarted.
297 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
298 flags_ |= SVC_DISABLED;
299 }
300
301 // Disabled and reset processes do not get restarted automatically.
302 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
303 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700304 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700305 }
306
Elliott Hughes9605a942016-11-10 17:43:47 -0800307 // If we crash > 4 times in 4 minutes, reboot into recovery.
308 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700309 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800310 if (now < time_crashed_ + 4min) {
311 if (++crash_count_ > 4) {
Elliott Hughes331cf2f2016-11-29 19:20:58 +0000312 LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
313 panic();
Tom Cherrybac32992015-07-31 12:45:25 -0700314 }
315 } else {
316 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800317 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700318 }
319 }
320
321 flags_ &= (~SVC_RESTART);
322 flags_ |= SVC_RESTARTING;
323
324 // Execute all onrestart commands for this service.
325 onrestart_.ExecuteAllCommands();
326
327 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700328 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700329}
330
331void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700332 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700333 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
334 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700335 std::for_each(descriptors_.begin(), descriptors_.end(),
336 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700337}
338
Tom Cherry89bcc852017-08-02 17:01:36 -0700339Result<Success> Service::ParseCapabilities(const std::vector<std::string>& args) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400340 capabilities_ = 0;
341
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500342 if (!CapAmbientSupported()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700343 return Error()
344 << "capabilities requested but the kernel does not support ambient capabilities";
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500345 }
346
347 unsigned int last_valid_cap = GetLastValidCap();
348 if (last_valid_cap >= capabilities_.size()) {
349 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
350 }
351
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400352 for (size_t i = 1; i < args.size(); i++) {
353 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500354 int res = LookupCap(arg);
355 if (res < 0) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700356 return Error() << StringPrintf("invalid capability '%s'", arg.c_str());
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400357 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500358 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
359 if (cap > last_valid_cap) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700360 return Error() << StringPrintf("capability '%s' not supported by the kernel",
361 arg.c_str());
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500362 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400363 capabilities_[cap] = true;
364 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700365 return Success();
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400366}
367
Tom Cherry89bcc852017-08-02 17:01:36 -0700368Result<Success> Service::ParseClass(const std::vector<std::string>& args) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700369 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700370 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700371}
Tom Cherrybac32992015-07-31 12:45:25 -0700372
Tom Cherry89bcc852017-08-02 17:01:36 -0700373Result<Success> Service::ParseConsole(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700374 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200375 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherry89bcc852017-08-02 17:01:36 -0700376 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700377}
Tom Cherrybac32992015-07-31 12:45:25 -0700378
Tom Cherry89bcc852017-08-02 17:01:36 -0700379Result<Success> Service::ParseCritical(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700380 flags_ |= SVC_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700381 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700382}
Tom Cherrybac32992015-07-31 12:45:25 -0700383
Tom Cherry89bcc852017-08-02 17:01:36 -0700384Result<Success> Service::ParseDisabled(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700385 flags_ |= SVC_DISABLED;
386 flags_ |= SVC_RC_DISABLED;
Tom Cherry89bcc852017-08-02 17:01:36 -0700387 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700388}
Tom Cherrybac32992015-07-31 12:45:25 -0700389
Tom Cherry89bcc852017-08-02 17:01:36 -0700390Result<Success> Service::ParseGroup(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700391 auto gid = DecodeUid(args[1]);
392 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700393 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700394 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700395 gid_ = *gid;
396
Tom Cherryb7349902015-08-26 11:43:36 -0700397 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700398 gid = DecodeUid(args[n]);
399 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700400 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700401 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700402 supp_gids_.emplace_back(*gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700403 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700404 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700405}
406
Tom Cherry89bcc852017-08-02 17:01:36 -0700407Result<Success> Service::ParsePriority(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700408 priority_ = 0;
409 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800410 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
411 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700412 return Error() << StringPrintf("process priority value must be range %d - %d",
413 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700414 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700415 return Success();
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700416}
417
Tom Cherry89bcc852017-08-02 17:01:36 -0700418Result<Success> Service::ParseIoprio(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700419 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700420 return Error() << "priority value must be range 0 - 7";
Tom Cherryb7349902015-08-26 11:43:36 -0700421 }
422
423 if (args[1] == "rt") {
424 ioprio_class_ = IoSchedClass_RT;
425 } else if (args[1] == "be") {
426 ioprio_class_ = IoSchedClass_BE;
427 } else if (args[1] == "idle") {
428 ioprio_class_ = IoSchedClass_IDLE;
429 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700430 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
Tom Cherryb7349902015-08-26 11:43:36 -0700431 }
432
Tom Cherry89bcc852017-08-02 17:01:36 -0700433 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700434}
435
Tom Cherry89bcc852017-08-02 17:01:36 -0700436Result<Success> Service::ParseKeycodes(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700437 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700438 int code;
439 if (ParseInt(args[i], &code)) {
440 keycodes_.emplace_back(code);
441 } else {
442 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
443 }
Tom Cherryb7349902015-08-26 11:43:36 -0700444 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700445 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700446}
447
Tom Cherry89bcc852017-08-02 17:01:36 -0700448Result<Success> Service::ParseOneshot(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700449 flags_ |= SVC_ONESHOT;
Tom Cherry89bcc852017-08-02 17:01:36 -0700450 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700451}
452
Tom Cherry89bcc852017-08-02 17:01:36 -0700453Result<Success> Service::ParseOnrestart(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700454 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700455 int line = onrestart_.NumCommands() + 1;
Tom Cherry89bcc852017-08-02 17:01:36 -0700456 if (auto result = onrestart_.AddCommand(str_args, line); !result) {
457 return Error() << "cannot add Onrestart command: " << result.error();
458 }
459 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700460}
461
Tom Cherry89bcc852017-08-02 17:01:36 -0700462Result<Success> Service::ParseNamespace(const std::vector<std::string>& args) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700463 for (size_t i = 1; i < args.size(); i++) {
464 if (args[i] == "pid") {
465 namespace_flags_ |= CLONE_NEWPID;
466 // PID namespaces require mount namespaces.
467 namespace_flags_ |= CLONE_NEWNS;
468 } else if (args[i] == "mnt") {
469 namespace_flags_ |= CLONE_NEWNS;
470 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700471 return Error() << "namespace must be 'pid' or 'mnt'";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700472 }
473 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700474 return Success();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700475}
476
Tom Cherry89bcc852017-08-02 17:01:36 -0700477Result<Success> Service::ParseOomScoreAdjust(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700478 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700479 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
Marco Nelissen310f6702016-07-22 12:07:06 -0700480 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700481 return Success();
Marco Nelissen310f6702016-07-22 12:07:06 -0700482}
483
Tom Cherry89bcc852017-08-02 17:01:36 -0700484Result<Success> Service::ParseMemcgSwappiness(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700485 if (!ParseInt(args[1], &swappiness_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700486 return Error() << "swappiness value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700487 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700488 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700489}
490
Tom Cherry89bcc852017-08-02 17:01:36 -0700491Result<Success> Service::ParseMemcgLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700492 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700493 return Error() << "limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700494 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700495 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700496}
497
Tom Cherry89bcc852017-08-02 17:01:36 -0700498Result<Success> Service::ParseMemcgSoftLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700499 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700500 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700501 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700502 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700503}
504
Tom Cherry89bcc852017-08-02 17:01:36 -0700505Result<Success> Service::ParseSeclabel(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700506 seclabel_ = args[1];
Tom Cherry89bcc852017-08-02 17:01:36 -0700507 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700508}
509
Tom Cherry89bcc852017-08-02 17:01:36 -0700510Result<Success> Service::ParseSetenv(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700511 envvars_.emplace_back(args[1], args[2]);
Tom Cherry89bcc852017-08-02 17:01:36 -0700512 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700513}
514
Tom Cherry89bcc852017-08-02 17:01:36 -0700515Result<Success> Service::ParseShutdown(const std::vector<std::string>& args) {
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700516 if (args[1] == "critical") {
517 flags_ |= SVC_SHUTDOWN_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700518 return Success();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700519 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700520 return Error() << "Invalid shutdown option";
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700521}
522
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700523template <typename T>
Tom Cherry89bcc852017-08-02 17:01:36 -0700524Result<Success> Service::AddDescriptor(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700525 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700526 Result<uid_t> uid = 0;
527 Result<gid_t> gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700528 std::string context = args.size() > 6 ? args[6] : "";
529
Tom Cherry517e1f12017-05-04 17:40:33 -0700530 if (args.size() > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700531 uid = DecodeUid(args[4]);
532 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700533 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700534 }
535 }
536
537 if (args.size() > 5) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700538 gid = DecodeUid(args[5]);
539 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700540 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700541 }
542 }
543
Tom Cherry11a3aee2017-08-03 12:54:07 -0700544 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700545
546 auto old =
547 std::find_if(descriptors_.begin(), descriptors_.end(),
548 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
549
550 if (old != descriptors_.end()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700551 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700552 }
553
554 descriptors_.emplace_back(std::move(descriptor));
Tom Cherry89bcc852017-08-02 17:01:36 -0700555 return Success();
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700556}
557
558// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700559Result<Success> Service::ParseSocket(const std::vector<std::string>& args) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700560 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
561 !StartsWith(args[2], "seqpacket")) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700562 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
Tom Cherryb7349902015-08-26 11:43:36 -0700563 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700564 return AddDescriptor<SocketInfo>(args);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700565}
Tom Cherryb7349902015-08-26 11:43:36 -0700566
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700567// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700568Result<Success> Service::ParseFile(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700569 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
Tom Cherry89bcc852017-08-02 17:01:36 -0700570 return Error() << "file type must be 'r', 'w' or 'rw'";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700571 }
572 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700573 return Error() << "file name must not be relative";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700574 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700575 return AddDescriptor<FileInfo>(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700576}
577
Tom Cherry89bcc852017-08-02 17:01:36 -0700578Result<Success> Service::ParseUser(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700579 auto uid = DecodeUid(args[1]);
580 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700581 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700582 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700583 uid_ = *uid;
Tom Cherry89bcc852017-08-02 17:01:36 -0700584 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700585}
586
Tom Cherry89bcc852017-08-02 17:01:36 -0700587Result<Success> Service::ParseWritepid(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700588 writepid_files_.assign(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700589 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700590}
591
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400592class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700593 public:
594 OptionParserMap() {}
595
596 private:
597 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700598};
599
Tom Cherryad54d092017-04-19 16:18:50 -0700600const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700601 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700602 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400603 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400604 {"capabilities",
605 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700606 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400607 {"console", {0, 1, &Service::ParseConsole}},
608 {"critical", {0, 0, &Service::ParseCritical}},
609 {"disabled", {0, 0, &Service::ParseDisabled}},
610 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
611 {"ioprio", {2, 2, &Service::ParseIoprio}},
612 {"priority", {1, 1, &Service::ParsePriority}},
613 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
614 {"oneshot", {0, 0, &Service::ParseOneshot}},
615 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700616 {"oom_score_adjust",
617 {1, 1, &Service::ParseOomScoreAdjust}},
Robert Benead4852262017-07-16 19:38:11 -0700618 {"memcg.swappiness",
619 {1, 1, &Service::ParseMemcgSwappiness}},
620 {"memcg.soft_limit_in_bytes",
621 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
622 {"memcg.limit_in_bytes",
623 {1, 1, &Service::ParseMemcgLimitInBytes}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400624 {"namespace", {1, 2, &Service::ParseNamespace}},
625 {"seclabel", {1, 1, &Service::ParseSeclabel}},
626 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700627 {"shutdown", {1, 1, &Service::ParseShutdown}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400628 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn978fd0e2016-12-02 08:05:22 -0800629 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400630 {"user", {1, 1, &Service::ParseUser}},
631 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700632 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700633 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400634 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700635}
636
Tom Cherry89bcc852017-08-02 17:01:36 -0700637Result<Success> Service::ParseLine(const std::vector<std::string>& args) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400638 static const OptionParserMap parser_map;
Tom Cherry89bcc852017-08-02 17:01:36 -0700639 auto parser = parser_map.FindFunction(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700640
Tom Cherry89bcc852017-08-02 17:01:36 -0700641 if (!parser) return Error() << parser.error();
Tom Cherryb7349902015-08-26 11:43:36 -0700642
Tom Cherry89bcc852017-08-02 17:01:36 -0700643 return std::invoke(*parser, this, args);
Tom Cherryb7349902015-08-26 11:43:36 -0700644}
645
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700646bool Service::ExecStart() {
647 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700648
649 if (!Start()) {
Tom Cherryb27004a2017-03-27 16:27:30 -0700650 return false;
651 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700652
653 flags_ |= SVC_EXEC;
654 is_exec_service_running_ = true;
655
656 LOG(INFO) << "SVC_EXEC pid " << pid_ << " (uid " << uid_ << " gid " << gid_ << "+"
657 << supp_gids_.size() << " context " << (!seclabel_.empty() ? seclabel_ : "default")
658 << ") started; waiting...";
659
Tom Cherryb27004a2017-03-27 16:27:30 -0700660 return true;
661}
662
Elliott Hughesbdeac392016-04-12 15:38:27 -0700663bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700664 // Starting a service removes it from the disabled or reset state and
665 // immediately takes it out of the restarting state if it was in there.
666 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700667
668 // Running processes require no additional work --- if they're in the
669 // process of exiting, we've ensured that they will immediately restart
670 // on exit, unless they are ONESHOT.
671 if (flags_ & SVC_RUNNING) {
672 return false;
673 }
674
675 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200676 if (needs_console) {
677 if (console_.empty()) {
678 console_ = default_console;
679 }
680
Adrian Salido24ef8602016-12-20 15:52:15 -0800681 // Make sure that open call succeeds to ensure a console driver is
682 // properly registered for the device node
683 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
684 if (console_fd < 0) {
685 PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200686 flags_ |= SVC_DISABLED;
687 return false;
688 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800689 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700690 }
691
692 struct stat sb;
693 if (stat(args_[0].c_str(), &sb) == -1) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700694 PLOG(ERROR) << "cannot find '" << args_[0] << "', disabling '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700695 flags_ |= SVC_DISABLED;
696 return false;
697 }
698
Tom Cherrybac32992015-07-31 12:45:25 -0700699 std::string scon;
700 if (!seclabel_.empty()) {
701 scon = seclabel_;
702 } else {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400703 scon = ComputeContextFromExecutable(name_, args_[0]);
704 if (scon == "") {
Tom Cherrybac32992015-07-31 12:45:25 -0700705 return false;
706 }
707 }
708
Wei Wanga285dac2016-10-04 14:05:39 -0700709 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700710
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700711 pid_t pid = -1;
712 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400713 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700714 } else {
715 pid = fork();
716 }
717
Tom Cherrybac32992015-07-31 12:45:25 -0700718 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700719 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700720
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700721 if (namespace_flags_ & CLONE_NEWPID) {
722 // This will fork again to run an init process inside the PID
723 // namespace.
724 SetUpPidNamespace(name_);
725 }
726
Tom Cherrybac32992015-07-31 12:45:25 -0700727 for (const auto& ei : envvars_) {
728 add_environment(ei.name.c_str(), ei.value.c_str());
729 }
730
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700731 std::for_each(descriptors_.begin(), descriptors_.end(),
732 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700733
Alex Vakulenko08286762016-05-03 12:00:00 -0700734 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
735 auto cpuset_predicate = [](const std::string& path) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700736 return StartsWith(path, "/dev/cpuset/");
Alex Vakulenko08286762016-05-03 12:00:00 -0700737 };
738 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
739 if (iter == writepid_files_.end()) {
740 // There were no "writepid" instructions for cpusets, check if the system default
741 // cpuset is specified to be used for the process.
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700742 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700743 if (!default_cpuset.empty()) {
744 // Make sure the cpuset name starts and ends with '/'.
745 // A single '/' means the 'root' cpuset.
746 if (default_cpuset.front() != '/') {
747 default_cpuset.insert(0, 1, '/');
748 }
749 if (default_cpuset.back() != '/') {
750 default_cpuset.push_back('/');
751 }
752 writepid_files_.push_back(
753 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
754 }
755 }
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700756 std::string pid_str = std::to_string(getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700757 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700758 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700759 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700760 }
761 }
762
763 if (ioprio_class_ != IoSchedClass_NONE) {
764 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400765 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700766 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700767 }
768 }
769
770 if (needs_console) {
771 setsid();
772 OpenConsole();
773 } else {
774 ZapStdio();
775 }
776
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400777 // As requested, set our gid, supplemental gids, uid, context, and
778 // priority. Aborts on failure.
779 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700780
Tom Cherrybac32992015-07-31 12:45:25 -0700781 std::vector<char*> strs;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400782 ExpandArgs(args_, &strs);
Tom Cherrybac35362016-06-07 11:22:00 -0700783 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700784 PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700785 }
786
787 _exit(127);
788 }
789
790 if (pid < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700791 PLOG(ERROR) << "failed to fork for '" << name_ << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700792 pid_ = 0;
793 return false;
794 }
795
Marco Nelissen310f6702016-07-22 12:07:06 -0700796 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700797 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700798 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
799 if (!WriteStringToFile(oom_str, oom_file)) {
800 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
801 }
802 }
803
Elliott Hughes9605a942016-11-10 17:43:47 -0800804 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700805 pid_ = pid;
806 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -0700807 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -0700808 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700809
810 errno = -createProcessGroup(uid_, pid_);
811 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400812 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
813 << name_ << "'";
Robert Benead4852262017-07-16 19:38:11 -0700814 } else {
815 if (swappiness_ != -1) {
816 if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
817 PLOG(ERROR) << "setProcessGroupSwappiness failed";
818 }
819 }
820
821 if (soft_limit_in_bytes_ != -1) {
822 if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
823 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
824 }
825 }
826
827 if (limit_in_bytes_ != -1) {
828 if (!setProcessGroupLimit(uid_, pid_, limit_in_bytes_)) {
829 PLOG(ERROR) << "setProcessGroupLimit failed";
830 }
831 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700832 }
Tom Cherrybac32992015-07-31 12:45:25 -0700833
Tom Cherrybac32992015-07-31 12:45:25 -0700834 NotifyStateChange("running");
835 return true;
836}
837
Tom Cherrybac32992015-07-31 12:45:25 -0700838bool Service::StartIfNotDisabled() {
839 if (!(flags_ & SVC_DISABLED)) {
840 return Start();
841 } else {
842 flags_ |= SVC_DISABLED_START;
843 }
844 return true;
845}
846
847bool Service::Enable() {
848 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
849 if (flags_ & SVC_DISABLED_START) {
850 return Start();
851 }
852 return true;
853}
854
855void Service::Reset() {
856 StopOrReset(SVC_RESET);
857}
858
859void Service::Stop() {
860 StopOrReset(SVC_DISABLED);
861}
862
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800863void Service::Terminate() {
864 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
865 flags_ |= SVC_DISABLED;
866 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700867 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800868 NotifyStateChange("stopping");
869 }
870}
871
Tom Cherrybac32992015-07-31 12:45:25 -0700872void Service::Restart() {
873 if (flags_ & SVC_RUNNING) {
874 /* Stop, wait, then start the service. */
875 StopOrReset(SVC_RESTART);
876 } else if (!(flags_ & SVC_RESTARTING)) {
877 /* Just start the service since it's not running. */
878 Start();
879 } /* else: Service is restarting anyways. */
880}
881
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700882// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700883void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700884 // The service is still SVC_RUNNING until its process exits, but if it has
885 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700886 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
887
888 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700889 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700890 how = SVC_DISABLED;
891 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700892
893 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700894 if (how == SVC_RESET) {
895 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
896 } else {
897 flags_ |= how;
898 }
899
900 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700901 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700902 NotifyStateChange("stopping");
903 } else {
904 NotifyStateChange("stopped");
905 }
906}
907
908void Service::ZapStdio() const {
909 int fd;
910 fd = open("/dev/null", O_RDWR);
911 dup2(fd, 0);
912 dup2(fd, 1);
913 dup2(fd, 2);
914 close(fd);
915}
916
917void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200918 int fd = open(console_.c_str(), O_RDWR);
919 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700920 ioctl(fd, TIOCSCTTY, 0);
921 dup2(fd, 0);
922 dup2(fd, 1);
923 dup2(fd, 2);
924 close(fd);
925}
926
Tom Cherry911b9b12017-07-27 16:20:58 -0700927ServiceList::ServiceList() {}
Tom Cherrybac32992015-07-31 12:45:25 -0700928
Tom Cherry911b9b12017-07-27 16:20:58 -0700929ServiceList& ServiceList::GetInstance() {
930 static ServiceList instance;
Tom Cherrybac32992015-07-31 12:45:25 -0700931 return instance;
932}
933
Tom Cherry911b9b12017-07-27 16:20:58 -0700934void ServiceList::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -0700935 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700936}
937
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700938std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700939 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
940 // SECLABEL can be a - to denote default
941 std::size_t command_arg = 1;
942 for (std::size_t i = 1; i < args.size(); ++i) {
943 if (args[i] == "--") {
944 command_arg = i + 1;
945 break;
946 }
947 }
948 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700949 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -0700950 return nullptr;
951 }
952
953 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700954 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -0700955 return nullptr;
956 }
957 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
958
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700959 static size_t exec_count = 0;
960 exec_count++;
961 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -0700962
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700963 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400964 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700965 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700966
967 std::string seclabel = "";
968 if (command_arg > 2 && args[1] != "-") {
969 seclabel = args[1];
970 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700971 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700972 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700973 uid = DecodeUid(args[2]);
974 if (!uid) {
975 LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700976 return nullptr;
977 }
Tom Cherrybac32992015-07-31 12:45:25 -0700978 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700979 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700980 std::vector<gid_t> supp_gids;
981 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700982 gid = DecodeUid(args[3]);
983 if (!gid) {
984 LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700985 return nullptr;
986 }
Tom Cherrybac32992015-07-31 12:45:25 -0700987 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
988 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700989 auto supp_gid = DecodeUid(args[4 + i]);
990 if (!supp_gid) {
991 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
992 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700993 return nullptr;
994 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700995 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700996 }
997 }
998
Tom Cherry11a3aee2017-08-03 12:54:07 -0700999 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, no_capabilities,
Tom Cherry3b81f2d2017-07-28 14:48:41 -07001000 namespace_flags, seclabel, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -07001001}
1002
Tom Cherry59383792017-07-26 16:09:09 -07001003// Shutdown services in the opposite order that they were started.
Tom Cherry911b9b12017-07-27 16:20:58 -07001004const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
Tom Cherry59383792017-07-26 16:09:09 -07001005 std::vector<Service*> shutdown_services;
1006 for (const auto& service : services_) {
1007 if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
1008 }
1009 std::sort(shutdown_services.begin(), shutdown_services.end(),
1010 [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
Tom Cherry911b9b12017-07-27 16:20:58 -07001011 return shutdown_services;
Tom Cherry59383792017-07-26 16:09:09 -07001012}
1013
Tom Cherry911b9b12017-07-27 16:20:58 -07001014void ServiceList::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001015 auto svc_it = std::find_if(services_.begin(), services_.end(),
1016 [&svc] (const std::unique_ptr<Service>& s) {
1017 return svc.name() == s->name();
1018 });
1019 if (svc_it == services_.end()) {
1020 return;
1021 }
1022
1023 services_.erase(svc_it);
1024}
1025
Tom Cherry911b9b12017-07-27 16:20:58 -07001026void ServiceList::DumpState() const {
Tom Cherryb7349902015-08-26 11:43:36 -07001027 for (const auto& s : services_) {
1028 s->DumpState();
1029 }
Tom Cherryb7349902015-08-26 11:43:36 -07001030}
1031
Tom Cherry89bcc852017-08-02 17:01:36 -07001032Result<Success> ServiceParser::ParseSection(std::vector<std::string>&& args,
1033 const std::string& filename, int line) {
Tom Cherryb7349902015-08-26 11:43:36 -07001034 if (args.size() < 3) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001035 return Error() << "services must have a name and a program";
Tom Cherryb7349902015-08-26 11:43:36 -07001036 }
1037
1038 const std::string& name = args[1];
1039 if (!IsValidName(name)) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001040 return Error() << "invalid service name '" << name << "'";
Tom Cherryb7349902015-08-26 11:43:36 -07001041 }
1042
Tom Cherry911b9b12017-07-27 16:20:58 -07001043 Service* old_service = service_list_->FindService(name);
Tom Cherry30a6f272017-04-19 15:31:58 -07001044 if (old_service) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001045 return Error() << "ignored duplicate definition of service '" << name << "'";
Tom Cherry30a6f272017-04-19 15:31:58 -07001046 }
1047
Tom Cherryb7349902015-08-26 11:43:36 -07001048 std::vector<std::string> str_args(args.begin() + 2, args.end());
Wei Wang641ff0a2017-03-27 10:59:11 -07001049 service_ = std::make_unique<Service>(name, str_args);
Tom Cherry89bcc852017-08-02 17:01:36 -07001050 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001051}
1052
Tom Cherry89bcc852017-08-02 17:01:36 -07001053Result<Success> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
1054 return service_ ? service_->ParseLine(std::move(args)) : Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001055}
1056
1057void ServiceParser::EndSection() {
1058 if (service_) {
Tom Cherry911b9b12017-07-27 16:20:58 -07001059 service_list_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001060 }
1061}
1062
1063bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001064 // Property names can be any length, but may only contain certain characters.
1065 // Property values can contain any characters, but may only be a certain length.
1066 // (The latter restriction is needed because `start` and `stop` work by writing
1067 // the service name to the "ctl.start" and "ctl.stop" properties.)
1068 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001069}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001070
1071} // namespace init
1072} // namespace android