blob: d3c9f923641b25e0699d2c3fd51d6328d0bc7575 [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
Tom Cherry76af7e62017-08-22 16:13:59 -070060static Result<std::string> ComputeContextFromExecutable(std::string& service_name,
61 const std::string& service_path) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040062 std::string computed_context;
63
64 char* raw_con = nullptr;
65 char* raw_filecon = nullptr;
66
67 if (getcon(&raw_con) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070068 return Error() << "Could not get security context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040069 }
70 std::unique_ptr<char> mycon(raw_con);
71
72 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
Tom Cherry76af7e62017-08-22 16:13:59 -070073 return Error() << "Could not get file context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040074 }
75 std::unique_ptr<char> filecon(raw_filecon);
76
77 char* new_con = nullptr;
78 int rc = security_compute_create(mycon.get(), filecon.get(),
79 string_to_security_class("process"), &new_con);
80 if (rc == 0) {
81 computed_context = new_con;
82 free(new_con);
83 }
84 if (rc == 0 && computed_context == mycon.get()) {
Tom Cherry76af7e62017-08-22 16:13:59 -070085 return Error() << "Service does not have an SELinux domain defined";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040086 }
87 if (rc < 0) {
Tom Cherry76af7e62017-08-22 16:13:59 -070088 return Error() << "Could not get process context";
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -040089 }
90 return computed_context;
91}
92
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -070093static void SetUpPidNamespace(const std::string& service_name) {
94 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
95
96 // It's OK to LOG(FATAL) in this function since it's running in the first
97 // child process.
98 if (mount("", "/proc", "proc", kSafeFlags | MS_REMOUNT, "") == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -070099 PLOG(FATAL) << "couldn't remount(/proc) for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700100 }
101
102 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700103 PLOG(FATAL) << "couldn't set name for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700104 }
105
106 pid_t child_pid = fork();
107 if (child_pid == -1) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700108 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700109 }
110
111 if (child_pid > 0) {
112 // So that we exit with the right status.
113 static int init_exitstatus = 0;
114 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
115
116 pid_t waited_pid;
117 int status;
118 while ((waited_pid = wait(&status)) > 0) {
119 // This loop will end when there are no processes left inside the
120 // PID namespace or when the init process inside the PID namespace
121 // gets a signal.
122 if (waited_pid == child_pid) {
123 init_exitstatus = status;
124 }
125 }
126 if (!WIFEXITED(init_exitstatus)) {
127 _exit(EXIT_FAILURE);
128 }
129 _exit(WEXITSTATUS(init_exitstatus));
130 }
131}
132
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400133static void ExpandArgs(const std::vector<std::string>& args, std::vector<char*>* strs) {
134 std::vector<std::string> expanded_args;
135 expanded_args.resize(args.size());
136 strs->push_back(const_cast<char*>(args[0].c_str()));
137 for (std::size_t i = 1; i < args.size(); ++i) {
138 if (!expand_props(args[i], &expanded_args[i])) {
139 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
140 }
141 strs->push_back(const_cast<char*>(expanded_args[i].c_str()));
142 }
143 strs->push_back(nullptr);
144}
145
Tom Cherry59383792017-07-26 16:09:09 -0700146unsigned long Service::next_start_order_ = 1;
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700147bool Service::is_exec_service_running_ = false;
Tom Cherry59383792017-07-26 16:09:09 -0700148
Wei Wang641ff0a2017-03-27 10:59:11 -0700149Service::Service(const std::string& name, const std::vector<std::string>& args)
Tom Cherry5d17d042017-07-21 12:42:07 -0700150 : Service(name, 0, 0, 0, {}, 0, 0, "", args) {}
Tom Cherrybac32992015-07-31 12:45:25 -0700151
Wei Wang641ff0a2017-03-27 10:59:11 -0700152Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
153 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
154 unsigned namespace_flags, const std::string& seclabel,
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700155 const std::vector<std::string>& args)
Wei Wang641ff0a2017-03-27 10:59:11 -0700156 : name_(name),
157 classnames_({"default"}),
158 flags_(flags),
159 pid_(0),
160 crash_count_(0),
161 uid_(uid),
162 gid_(gid),
163 supp_gids_(supp_gids),
164 capabilities_(capabilities),
165 namespace_flags_(namespace_flags),
166 seclabel_(seclabel),
Tom Cherry012c5732017-04-18 13:21:54 -0700167 onrestart_(false, "<Service '" + name + "' onrestart>", 0),
Tom Cherry7da54852017-05-01 14:16:41 -0700168 keychord_id_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700169 ioprio_class_(IoSchedClass_NONE),
170 ioprio_pri_(0),
171 priority_(0),
172 oom_score_adjust_(-1000),
Robert Benead4852262017-07-16 19:38:11 -0700173 swappiness_(-1),
174 soft_limit_in_bytes_(-1),
175 limit_in_bytes_(-1),
Tom Cherry59383792017-07-26 16:09:09 -0700176 start_order_(0),
Wei Wang641ff0a2017-03-27 10:59:11 -0700177 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700178 onrestart_.InitSingleTrigger("onrestart");
179}
180
181void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherryb27004a2017-03-27 16:27:30 -0700182 if ((flags_ & SVC_TEMPORARY) != 0) {
183 // Services created by 'exec' are temporary and don't have properties tracking their state.
Tom Cherrybac32992015-07-31 12:45:25 -0700184 return;
185 }
186
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700187 std::string prop_name = "init.svc." + name_;
188 property_set(prop_name, new_state);
Elliott Hughes9605a942016-11-10 17:43:47 -0800189
190 if (new_state == "running") {
Elliott Hughes9605a942016-11-10 17:43:47 -0800191 uint64_t start_ns = time_started_.time_since_epoch().count();
Tom Cherryfed33732017-08-18 10:47:46 -0700192 std::string boottime_property = "ro.boottime." + name_;
193 if (GetProperty(boottime_property, "").empty()) {
194 property_set(boottime_property, std::to_string(start_ns));
195 }
Elliott Hughes9605a942016-11-10 17:43:47 -0800196 }
Tom Cherrybac32992015-07-31 12:45:25 -0700197}
198
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700199void Service::KillProcessGroup(int signal) {
Tom Cherry33838b12017-05-04 11:32:36 -0700200 // If we've already seen a successful result from killProcessGroup*(), then we have removed
201 // the cgroup already and calling these functions a second time will simply result in an error.
202 // This is true regardless of which signal was sent.
203 // These functions handle their own logging, so no additional logging is needed.
204 if (!process_cgroup_empty_) {
205 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
206 << ") process group...";
207 int r;
208 if (signal == SIGTERM) {
209 r = killProcessGroupOnce(uid_, pid_, signal);
210 } else {
211 r = killProcessGroup(uid_, pid_, signal);
212 }
213
214 if (r == 0) process_cgroup_empty_ = true;
215 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700216}
217
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400218void Service::SetProcessAttributes() {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400219 // Keep capabilites on uid change.
220 if (capabilities_.any() && uid_) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700221 // If Android is running in a container, some securebits might already
222 // be locked, so don't change those.
Ben Fennemaa7243602017-07-25 14:37:21 -0700223 unsigned long securebits = prctl(PR_GET_SECUREBITS);
224 if (securebits == -1UL) {
Luis Hector Chavezf5965512017-06-30 14:04:20 -0700225 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
226 }
227 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
228 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
229 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400230 }
231 }
232
Elliott Hughese18e7e52016-07-25 18:18:16 -0700233 // TODO: work out why this fails for `console` then upgrade to FATAL.
234 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400235
236 if (gid_) {
237 if (setgid(gid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700238 PLOG(FATAL) << "setgid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400239 }
240 }
Nick Kralevich80960d22016-10-29 12:20:00 -0700241 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
242 PLOG(FATAL) << "setgroups failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400243 }
244 if (uid_) {
245 if (setuid(uid_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700246 PLOG(FATAL) << "setuid failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400247 }
248 }
249 if (!seclabel_.empty()) {
250 if (setexeccon(seclabel_.c_str()) < 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700251 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400252 }
253 }
254 if (priority_ != 0) {
255 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
Elliott Hughese18e7e52016-07-25 18:18:16 -0700256 PLOG(FATAL) << "setpriority failed for " << name_;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400257 }
258 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400259 if (capabilities_.any()) {
260 if (!SetCapsForExec(capabilities_)) {
261 LOG(FATAL) << "cannot set capabilities for " << name_;
262 }
263 }
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400264}
265
Tom Cherryb27004a2017-03-27 16:27:30 -0700266void Service::Reap() {
Tom Cherrybac32992015-07-31 12:45:25 -0700267 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700268 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700269 }
270
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700271 // Remove any descriptor resources we may have created.
272 std::for_each(descriptors_.begin(), descriptors_.end(),
273 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
Tom Cherrybac32992015-07-31 12:45:25 -0700274
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700275 if (flags_ & SVC_EXEC) UnSetExec();
276
277 if (flags_ & SVC_TEMPORARY) return;
Tom Cherrybac32992015-07-31 12:45:25 -0700278
279 pid_ = 0;
280 flags_ &= (~SVC_RUNNING);
Tom Cherry59383792017-07-26 16:09:09 -0700281 start_order_ = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700282
283 // Oneshot processes go into the disabled state on exit,
284 // except when manually restarted.
285 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
286 flags_ |= SVC_DISABLED;
287 }
288
289 // Disabled and reset processes do not get restarted automatically.
290 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
291 NotifyStateChange("stopped");
Tom Cherryb27004a2017-03-27 16:27:30 -0700292 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700293 }
294
Elliott Hughes9605a942016-11-10 17:43:47 -0800295 // If we crash > 4 times in 4 minutes, reboot into recovery.
296 boot_clock::time_point now = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700297 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
Elliott Hughes9605a942016-11-10 17:43:47 -0800298 if (now < time_crashed_ + 4min) {
299 if (++crash_count_ > 4) {
Tom Cherryd8db7ab2017-08-17 17:28:30 -0700300 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
Tom Cherrybac32992015-07-31 12:45:25 -0700301 }
302 } else {
303 time_crashed_ = now;
Elliott Hughes9605a942016-11-10 17:43:47 -0800304 crash_count_ = 1;
Tom Cherrybac32992015-07-31 12:45:25 -0700305 }
306 }
307
308 flags_ &= (~SVC_RESTART);
309 flags_ |= SVC_RESTARTING;
310
311 // Execute all onrestart commands for this service.
312 onrestart_.ExecuteAllCommands();
313
314 NotifyStateChange("restarting");
Tom Cherryb27004a2017-03-27 16:27:30 -0700315 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700316}
317
318void Service::DumpState() const {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700319 LOG(INFO) << "service " << name_;
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700320 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
321 LOG(INFO) << " exec " << Join(args_, " ");
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700322 std::for_each(descriptors_.begin(), descriptors_.end(),
323 [] (const auto& info) { LOG(INFO) << *info; });
Tom Cherrybac32992015-07-31 12:45:25 -0700324}
325
Tom Cherry89bcc852017-08-02 17:01:36 -0700326Result<Success> Service::ParseCapabilities(const std::vector<std::string>& args) {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400327 capabilities_ = 0;
328
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500329 if (!CapAmbientSupported()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700330 return Error()
331 << "capabilities requested but the kernel does not support ambient capabilities";
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500332 }
333
334 unsigned int last_valid_cap = GetLastValidCap();
335 if (last_valid_cap >= capabilities_.size()) {
336 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
337 }
338
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400339 for (size_t i = 1; i < args.size(); i++) {
340 const std::string& arg = args[i];
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500341 int res = LookupCap(arg);
342 if (res < 0) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700343 return Error() << StringPrintf("invalid capability '%s'", arg.c_str());
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400344 }
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500345 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
346 if (cap > last_valid_cap) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700347 return Error() << StringPrintf("capability '%s' not supported by the kernel",
348 arg.c_str());
Jorge Lucangeli Obesf3f824e2016-12-15 12:13:38 -0500349 }
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400350 capabilities_[cap] = true;
351 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700352 return Success();
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400353}
354
Tom Cherry89bcc852017-08-02 17:01:36 -0700355Result<Success> Service::ParseClass(const std::vector<std::string>& args) {
Wei Wang641ff0a2017-03-27 10:59:11 -0700356 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700357 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700358}
Tom Cherrybac32992015-07-31 12:45:25 -0700359
Tom Cherry89bcc852017-08-02 17:01:36 -0700360Result<Success> Service::ParseConsole(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700361 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200362 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherry89bcc852017-08-02 17:01:36 -0700363 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700364}
Tom Cherrybac32992015-07-31 12:45:25 -0700365
Tom Cherry89bcc852017-08-02 17:01:36 -0700366Result<Success> Service::ParseCritical(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700367 flags_ |= SVC_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700368 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700369}
Tom Cherrybac32992015-07-31 12:45:25 -0700370
Tom Cherry89bcc852017-08-02 17:01:36 -0700371Result<Success> Service::ParseDisabled(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700372 flags_ |= SVC_DISABLED;
373 flags_ |= SVC_RC_DISABLED;
Tom Cherry89bcc852017-08-02 17:01:36 -0700374 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700375}
Tom Cherrybac32992015-07-31 12:45:25 -0700376
Tom Cherry89bcc852017-08-02 17:01:36 -0700377Result<Success> Service::ParseGroup(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700378 auto gid = DecodeUid(args[1]);
379 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700380 return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700381 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700382 gid_ = *gid;
383
Tom Cherryb7349902015-08-26 11:43:36 -0700384 for (std::size_t n = 2; n < args.size(); n++) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700385 gid = DecodeUid(args[n]);
386 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700387 return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700388 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700389 supp_gids_.emplace_back(*gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700390 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700391 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700392}
393
Tom Cherry89bcc852017-08-02 17:01:36 -0700394Result<Success> Service::ParsePriority(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700395 priority_ = 0;
396 if (!ParseInt(args[1], &priority_,
Keun-young Parkdd34ca42016-11-11 18:06:31 -0800397 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
398 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700399 return Error() << StringPrintf("process priority value must be range %d - %d",
400 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700401 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700402 return Success();
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700403}
404
Tom Cherry89bcc852017-08-02 17:01:36 -0700405Result<Success> Service::ParseIoprio(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700406 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700407 return Error() << "priority value must be range 0 - 7";
Tom Cherryb7349902015-08-26 11:43:36 -0700408 }
409
410 if (args[1] == "rt") {
411 ioprio_class_ = IoSchedClass_RT;
412 } else if (args[1] == "be") {
413 ioprio_class_ = IoSchedClass_BE;
414 } else if (args[1] == "idle") {
415 ioprio_class_ = IoSchedClass_IDLE;
416 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700417 return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
Tom Cherryb7349902015-08-26 11:43:36 -0700418 }
419
Tom Cherry89bcc852017-08-02 17:01:36 -0700420 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700421}
422
Tom Cherry89bcc852017-08-02 17:01:36 -0700423Result<Success> Service::ParseKeycodes(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700424 for (std::size_t i = 1; i < args.size(); i++) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700425 int code;
426 if (ParseInt(args[i], &code)) {
427 keycodes_.emplace_back(code);
428 } else {
429 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
430 }
Tom Cherryb7349902015-08-26 11:43:36 -0700431 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700432 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700433}
434
Tom Cherry89bcc852017-08-02 17:01:36 -0700435Result<Success> Service::ParseOneshot(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700436 flags_ |= SVC_ONESHOT;
Tom Cherry89bcc852017-08-02 17:01:36 -0700437 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700438}
439
Tom Cherry89bcc852017-08-02 17:01:36 -0700440Result<Success> Service::ParseOnrestart(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700441 std::vector<std::string> str_args(args.begin() + 1, args.end());
Tom Cherry012c5732017-04-18 13:21:54 -0700442 int line = onrestart_.NumCommands() + 1;
Tom Cherry89bcc852017-08-02 17:01:36 -0700443 if (auto result = onrestart_.AddCommand(str_args, line); !result) {
444 return Error() << "cannot add Onrestart command: " << result.error();
445 }
446 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700447}
448
Tom Cherry89bcc852017-08-02 17:01:36 -0700449Result<Success> Service::ParseNamespace(const std::vector<std::string>& args) {
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700450 for (size_t i = 1; i < args.size(); i++) {
451 if (args[i] == "pid") {
452 namespace_flags_ |= CLONE_NEWPID;
453 // PID namespaces require mount namespaces.
454 namespace_flags_ |= CLONE_NEWNS;
455 } else if (args[i] == "mnt") {
456 namespace_flags_ |= CLONE_NEWNS;
457 } else {
Tom Cherry89bcc852017-08-02 17:01:36 -0700458 return Error() << "namespace must be 'pid' or 'mnt'";
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700459 }
460 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700461 return Success();
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700462}
463
Tom Cherry89bcc852017-08-02 17:01:36 -0700464Result<Success> Service::ParseOomScoreAdjust(const std::vector<std::string>& args) {
Elliott Hughesda46b392016-10-11 17:09:00 -0700465 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700466 return Error() << "oom_score_adjust value must be in range -1000 - +1000";
Marco Nelissen310f6702016-07-22 12:07:06 -0700467 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700468 return Success();
Marco Nelissen310f6702016-07-22 12:07:06 -0700469}
470
Tom Cherry89bcc852017-08-02 17:01:36 -0700471Result<Success> Service::ParseMemcgSwappiness(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700472 if (!ParseInt(args[1], &swappiness_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700473 return Error() << "swappiness value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700474 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700475 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700476}
477
Tom Cherry89bcc852017-08-02 17:01:36 -0700478Result<Success> Service::ParseMemcgLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700479 if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700480 return Error() << "limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700481 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700482 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700483}
484
Tom Cherry89bcc852017-08-02 17:01:36 -0700485Result<Success> Service::ParseMemcgSoftLimitInBytes(const std::vector<std::string>& args) {
Robert Benead4852262017-07-16 19:38:11 -0700486 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700487 return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
Robert Benead4852262017-07-16 19:38:11 -0700488 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700489 return Success();
Robert Benead4852262017-07-16 19:38:11 -0700490}
491
Tom Cherry89bcc852017-08-02 17:01:36 -0700492Result<Success> Service::ParseSeclabel(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700493 seclabel_ = args[1];
Tom Cherry89bcc852017-08-02 17:01:36 -0700494 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700495}
496
Tom Cherry89bcc852017-08-02 17:01:36 -0700497Result<Success> Service::ParseSetenv(const std::vector<std::string>& args) {
Tom Cherry6de21f12017-08-22 15:41:03 -0700498 environment_vars_.emplace_back(args[1], args[2]);
Tom Cherry89bcc852017-08-02 17:01:36 -0700499 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700500}
501
Tom Cherry89bcc852017-08-02 17:01:36 -0700502Result<Success> Service::ParseShutdown(const std::vector<std::string>& args) {
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700503 if (args[1] == "critical") {
504 flags_ |= SVC_SHUTDOWN_CRITICAL;
Tom Cherry89bcc852017-08-02 17:01:36 -0700505 return Success();
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700506 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700507 return Error() << "Invalid shutdown option";
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700508}
509
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700510template <typename T>
Tom Cherry89bcc852017-08-02 17:01:36 -0700511Result<Success> Service::AddDescriptor(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700512 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Tom Cherry11a3aee2017-08-03 12:54:07 -0700513 Result<uid_t> uid = 0;
514 Result<gid_t> gid = 0;
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700515 std::string context = args.size() > 6 ? args[6] : "";
516
Tom Cherry517e1f12017-05-04 17:40:33 -0700517 if (args.size() > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700518 uid = DecodeUid(args[4]);
519 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700520 return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700521 }
522 }
523
524 if (args.size() > 5) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700525 gid = DecodeUid(args[5]);
526 if (!gid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700527 return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700528 }
529 }
530
Tom Cherry11a3aee2017-08-03 12:54:07 -0700531 auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700532
533 auto old =
534 std::find_if(descriptors_.begin(), descriptors_.end(),
535 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
536
537 if (old != descriptors_.end()) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700538 return Error() << "duplicate descriptor " << args[1] << " " << args[2];
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700539 }
540
541 descriptors_.emplace_back(std::move(descriptor));
Tom Cherry89bcc852017-08-02 17:01:36 -0700542 return Success();
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700543}
544
545// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700546Result<Success> Service::ParseSocket(const std::vector<std::string>& args) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700547 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
548 !StartsWith(args[2], "seqpacket")) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700549 return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
Tom Cherryb7349902015-08-26 11:43:36 -0700550 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700551 return AddDescriptor<SocketInfo>(args);
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700552}
Tom Cherryb7349902015-08-26 11:43:36 -0700553
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700554// name type perm [ uid gid context ]
Tom Cherry89bcc852017-08-02 17:01:36 -0700555Result<Success> Service::ParseFile(const std::vector<std::string>& args) {
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700556 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
Tom Cherry89bcc852017-08-02 17:01:36 -0700557 return Error() << "file type must be 'r', 'w' or 'rw'";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700558 }
559 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700560 return Error() << "file name must not be relative";
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700561 }
Tom Cherry89bcc852017-08-02 17:01:36 -0700562 return AddDescriptor<FileInfo>(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700563}
564
Tom Cherry89bcc852017-08-02 17:01:36 -0700565Result<Success> Service::ParseUser(const std::vector<std::string>& args) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700566 auto uid = DecodeUid(args[1]);
567 if (!uid) {
Tom Cherry89bcc852017-08-02 17:01:36 -0700568 return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700569 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700570 uid_ = *uid;
Tom Cherry89bcc852017-08-02 17:01:36 -0700571 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700572}
573
Tom Cherry89bcc852017-08-02 17:01:36 -0700574Result<Success> Service::ParseWritepid(const std::vector<std::string>& args) {
Tom Cherryb7349902015-08-26 11:43:36 -0700575 writepid_files_.assign(args.begin() + 1, args.end());
Tom Cherry89bcc852017-08-02 17:01:36 -0700576 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -0700577}
578
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400579class Service::OptionParserMap : public KeywordMap<OptionParser> {
Tom Cherryad54d092017-04-19 16:18:50 -0700580 public:
581 OptionParserMap() {}
582
583 private:
584 const Map& map() const override;
Tom Cherryb7349902015-08-26 11:43:36 -0700585};
586
Tom Cherryad54d092017-04-19 16:18:50 -0700587const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
Tom Cherryb7349902015-08-26 11:43:36 -0700588 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
Wei Wang641ff0a2017-03-27 10:59:11 -0700589 // clang-format off
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400590 static const Map option_parsers = {
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400591 {"capabilities",
592 {1, kMax, &Service::ParseCapabilities}},
Wei Wang641ff0a2017-03-27 10:59:11 -0700593 {"class", {1, kMax, &Service::ParseClass}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400594 {"console", {0, 1, &Service::ParseConsole}},
595 {"critical", {0, 0, &Service::ParseCritical}},
596 {"disabled", {0, 0, &Service::ParseDisabled}},
597 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
598 {"ioprio", {2, 2, &Service::ParseIoprio}},
599 {"priority", {1, 1, &Service::ParsePriority}},
600 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
601 {"oneshot", {0, 0, &Service::ParseOneshot}},
602 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
Marco Nelissen310f6702016-07-22 12:07:06 -0700603 {"oom_score_adjust",
604 {1, 1, &Service::ParseOomScoreAdjust}},
Robert Benead4852262017-07-16 19:38:11 -0700605 {"memcg.swappiness",
606 {1, 1, &Service::ParseMemcgSwappiness}},
607 {"memcg.soft_limit_in_bytes",
608 {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
609 {"memcg.limit_in_bytes",
610 {1, 1, &Service::ParseMemcgLimitInBytes}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400611 {"namespace", {1, 2, &Service::ParseNamespace}},
612 {"seclabel", {1, 1, &Service::ParseSeclabel}},
613 {"setenv", {2, 2, &Service::ParseSetenv}},
Keun-young Parkcccb34f2017-07-05 11:38:44 -0700614 {"shutdown", {1, 1, &Service::ParseShutdown}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400615 {"socket", {3, 6, &Service::ParseSocket}},
Mark Salyzyn978fd0e2016-12-02 08:05:22 -0800616 {"file", {2, 2, &Service::ParseFile}},
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400617 {"user", {1, 1, &Service::ParseUser}},
618 {"writepid", {1, kMax, &Service::ParseWritepid}},
Tom Cherryb7349902015-08-26 11:43:36 -0700619 };
Wei Wang641ff0a2017-03-27 10:59:11 -0700620 // clang-format on
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400621 return option_parsers;
Tom Cherryb7349902015-08-26 11:43:36 -0700622}
623
Tom Cherry89bcc852017-08-02 17:01:36 -0700624Result<Success> Service::ParseLine(const std::vector<std::string>& args) {
Jorge Lucangeli Obes177b27d2016-06-29 14:32:49 -0400625 static const OptionParserMap parser_map;
Tom Cherry89bcc852017-08-02 17:01:36 -0700626 auto parser = parser_map.FindFunction(args);
Tom Cherryb7349902015-08-26 11:43:36 -0700627
Tom Cherry76af7e62017-08-22 16:13:59 -0700628 if (!parser) return parser.error();
Tom Cherryb7349902015-08-26 11:43:36 -0700629
Tom Cherry89bcc852017-08-02 17:01:36 -0700630 return std::invoke(*parser, this, args);
Tom Cherryb7349902015-08-26 11:43:36 -0700631}
632
Tom Cherry76af7e62017-08-22 16:13:59 -0700633Result<Success> Service::ExecStart() {
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700634 flags_ |= SVC_ONESHOT;
Tom Cherryb27004a2017-03-27 16:27:30 -0700635
Tom Cherry76af7e62017-08-22 16:13:59 -0700636 if (auto result = Start(); !result) {
637 return result;
Tom Cherryb27004a2017-03-27 16:27:30 -0700638 }
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700639
640 flags_ |= SVC_EXEC;
641 is_exec_service_running_ = true;
642
643 LOG(INFO) << "SVC_EXEC pid " << pid_ << " (uid " << uid_ << " gid " << gid_ << "+"
644 << supp_gids_.size() << " context " << (!seclabel_.empty() ? seclabel_ : "default")
645 << ") started; waiting...";
646
Tom Cherry76af7e62017-08-22 16:13:59 -0700647 return Success();
Tom Cherryb27004a2017-03-27 16:27:30 -0700648}
649
Tom Cherry76af7e62017-08-22 16:13:59 -0700650Result<Success> Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700651 // Starting a service removes it from the disabled or reset state and
652 // immediately takes it out of the restarting state if it was in there.
653 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
Tom Cherrybac32992015-07-31 12:45:25 -0700654
655 // Running processes require no additional work --- if they're in the
656 // process of exiting, we've ensured that they will immediately restart
657 // on exit, unless they are ONESHOT.
658 if (flags_ & SVC_RUNNING) {
Tom Cherry76af7e62017-08-22 16:13:59 -0700659 // It is not an error to try to start a service that is already running.
660 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700661 }
662
663 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200664 if (needs_console) {
665 if (console_.empty()) {
666 console_ = default_console;
667 }
668
Adrian Salido24ef8602016-12-20 15:52:15 -0800669 // Make sure that open call succeeds to ensure a console driver is
670 // properly registered for the device node
671 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
672 if (console_fd < 0) {
Viorel Suman70daa672016-03-21 10:08:07 +0200673 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700674 return ErrnoError() << "Couldn't open console '" << console_ << "'";
Viorel Suman70daa672016-03-21 10:08:07 +0200675 }
Adrian Salido24ef8602016-12-20 15:52:15 -0800676 close(console_fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700677 }
678
679 struct stat sb;
680 if (stat(args_[0].c_str(), &sb) == -1) {
Tom Cherrybac32992015-07-31 12:45:25 -0700681 flags_ |= SVC_DISABLED;
Tom Cherry76af7e62017-08-22 16:13:59 -0700682 return ErrnoError() << "Cannot find '" << args_[0] << "'";
Tom Cherrybac32992015-07-31 12:45:25 -0700683 }
684
Tom Cherrybac32992015-07-31 12:45:25 -0700685 std::string scon;
686 if (!seclabel_.empty()) {
687 scon = seclabel_;
688 } else {
Tom Cherry76af7e62017-08-22 16:13:59 -0700689 auto result = ComputeContextFromExecutable(name_, args_[0]);
690 if (!result) {
691 return result.error();
Tom Cherrybac32992015-07-31 12:45:25 -0700692 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700693 scon = *result;
Tom Cherrybac32992015-07-31 12:45:25 -0700694 }
695
Wei Wanga285dac2016-10-04 14:05:39 -0700696 LOG(INFO) << "starting service '" << name_ << "'...";
Tom Cherrybac32992015-07-31 12:45:25 -0700697
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700698 pid_t pid = -1;
699 if (namespace_flags_) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400700 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700701 } else {
702 pid = fork();
703 }
704
Tom Cherrybac32992015-07-31 12:45:25 -0700705 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700706 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700707
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700708 if (namespace_flags_ & CLONE_NEWPID) {
709 // This will fork again to run an init process inside the PID
710 // namespace.
711 SetUpPidNamespace(name_);
712 }
713
Tom Cherry6de21f12017-08-22 15:41:03 -0700714 for (const auto& [key, value] : environment_vars_) {
715 setenv(key.c_str(), value.c_str(), 1);
Tom Cherrybac32992015-07-31 12:45:25 -0700716 }
717
Mark Salyzyn62767fe2016-10-27 07:45:34 -0700718 std::for_each(descriptors_.begin(), descriptors_.end(),
719 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
Tom Cherrybac32992015-07-31 12:45:25 -0700720
Alex Vakulenko08286762016-05-03 12:00:00 -0700721 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
722 auto cpuset_predicate = [](const std::string& path) {
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700723 return StartsWith(path, "/dev/cpuset/");
Alex Vakulenko08286762016-05-03 12:00:00 -0700724 };
725 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
726 if (iter == writepid_files_.end()) {
727 // There were no "writepid" instructions for cpusets, check if the system default
728 // cpuset is specified to be used for the process.
Tom Cherry81f5d3e2017-06-22 12:53:17 -0700729 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
Alex Vakulenko08286762016-05-03 12:00:00 -0700730 if (!default_cpuset.empty()) {
731 // Make sure the cpuset name starts and ends with '/'.
732 // A single '/' means the 'root' cpuset.
733 if (default_cpuset.front() != '/') {
734 default_cpuset.insert(0, 1, '/');
735 }
736 if (default_cpuset.back() != '/') {
737 default_cpuset.push_back('/');
738 }
739 writepid_files_.push_back(
740 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
741 }
742 }
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700743 std::string pid_str = std::to_string(getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700744 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700745 if (!WriteStringToFile(pid_str, file)) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700746 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
Tom Cherrybac32992015-07-31 12:45:25 -0700747 }
748 }
749
750 if (ioprio_class_ != IoSchedClass_NONE) {
751 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400752 PLOG(ERROR) << "failed to set pid " << getpid()
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700753 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
Tom Cherrybac32992015-07-31 12:45:25 -0700754 }
755 }
756
757 if (needs_console) {
758 setsid();
759 OpenConsole();
760 } else {
761 ZapStdio();
762 }
763
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400764 // As requested, set our gid, supplemental gids, uid, context, and
765 // priority. Aborts on failure.
766 SetProcessAttributes();
Tom Cherrybac32992015-07-31 12:45:25 -0700767
Tom Cherrybac32992015-07-31 12:45:25 -0700768 std::vector<char*> strs;
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400769 ExpandArgs(args_, &strs);
Tom Cherry6de21f12017-08-22 15:41:03 -0700770 if (execv(strs[0], (char**)&strs[0]) < 0) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700771 PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
Tom Cherrybac32992015-07-31 12:45:25 -0700772 }
773
774 _exit(127);
775 }
776
777 if (pid < 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700778 pid_ = 0;
Tom Cherry76af7e62017-08-22 16:13:59 -0700779 return ErrnoError() << "Failed to fork";
Tom Cherrybac32992015-07-31 12:45:25 -0700780 }
781
Marco Nelissen310f6702016-07-22 12:07:06 -0700782 if (oom_score_adjust_ != -1000) {
Tom Cherry1c3a53f2017-06-22 16:50:31 -0700783 std::string oom_str = std::to_string(oom_score_adjust_);
Marco Nelissen310f6702016-07-22 12:07:06 -0700784 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
785 if (!WriteStringToFile(oom_str, oom_file)) {
786 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
787 }
788 }
789
Elliott Hughes9605a942016-11-10 17:43:47 -0800790 time_started_ = boot_clock::now();
Tom Cherrybac32992015-07-31 12:45:25 -0700791 pid_ = pid;
792 flags_ |= SVC_RUNNING;
Tom Cherry59383792017-07-26 16:09:09 -0700793 start_order_ = next_start_order_++;
Tom Cherry33838b12017-05-04 11:32:36 -0700794 process_cgroup_empty_ = false;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700795
796 errno = -createProcessGroup(uid_, pid_);
797 if (errno != 0) {
Jorge Lucangeli Obes344d01f2016-07-08 13:32:26 -0400798 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
799 << name_ << "'";
Robert Benead4852262017-07-16 19:38:11 -0700800 } else {
801 if (swappiness_ != -1) {
802 if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
803 PLOG(ERROR) << "setProcessGroupSwappiness failed";
804 }
805 }
806
807 if (soft_limit_in_bytes_ != -1) {
808 if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
809 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
810 }
811 }
812
813 if (limit_in_bytes_ != -1) {
814 if (!setProcessGroupLimit(uid_, pid_, limit_in_bytes_)) {
815 PLOG(ERROR) << "setProcessGroupLimit failed";
816 }
817 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700818 }
Tom Cherrybac32992015-07-31 12:45:25 -0700819
Tom Cherrybac32992015-07-31 12:45:25 -0700820 NotifyStateChange("running");
Tom Cherry76af7e62017-08-22 16:13:59 -0700821 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700822}
823
Tom Cherry76af7e62017-08-22 16:13:59 -0700824Result<Success> Service::StartIfNotDisabled() {
Tom Cherrybac32992015-07-31 12:45:25 -0700825 if (!(flags_ & SVC_DISABLED)) {
826 return Start();
827 } else {
828 flags_ |= SVC_DISABLED_START;
829 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700830 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700831}
832
Tom Cherry76af7e62017-08-22 16:13:59 -0700833Result<Success> Service::Enable() {
Tom Cherrybac32992015-07-31 12:45:25 -0700834 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
835 if (flags_ & SVC_DISABLED_START) {
836 return Start();
837 }
Tom Cherry76af7e62017-08-22 16:13:59 -0700838 return Success();
Tom Cherrybac32992015-07-31 12:45:25 -0700839}
840
841void Service::Reset() {
842 StopOrReset(SVC_RESET);
843}
844
845void Service::Stop() {
846 StopOrReset(SVC_DISABLED);
847}
848
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800849void Service::Terminate() {
850 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
851 flags_ |= SVC_DISABLED;
852 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700853 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800854 NotifyStateChange("stopping");
855 }
856}
857
Tom Cherrybac32992015-07-31 12:45:25 -0700858void Service::Restart() {
859 if (flags_ & SVC_RUNNING) {
860 /* Stop, wait, then start the service. */
861 StopOrReset(SVC_RESTART);
862 } else if (!(flags_ & SVC_RESTARTING)) {
863 /* Just start the service since it's not running. */
Tom Cherry76af7e62017-08-22 16:13:59 -0700864 if (auto result = Start(); !result) {
865 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
866 }
Tom Cherrybac32992015-07-31 12:45:25 -0700867 } /* else: Service is restarting anyways. */
868}
869
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700870// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700871void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700872 // The service is still SVC_RUNNING until its process exits, but if it has
873 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700874 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
875
876 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700877 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700878 how = SVC_DISABLED;
879 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700880
881 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700882 if (how == SVC_RESET) {
883 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
884 } else {
885 flags_ |= how;
886 }
887
888 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700889 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700890 NotifyStateChange("stopping");
891 } else {
892 NotifyStateChange("stopped");
893 }
894}
895
896void Service::ZapStdio() const {
897 int fd;
898 fd = open("/dev/null", O_RDWR);
899 dup2(fd, 0);
900 dup2(fd, 1);
901 dup2(fd, 2);
902 close(fd);
903}
904
905void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200906 int fd = open(console_.c_str(), O_RDWR);
907 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700908 ioctl(fd, TIOCSCTTY, 0);
909 dup2(fd, 0);
910 dup2(fd, 1);
911 dup2(fd, 2);
912 close(fd);
913}
914
Tom Cherry911b9b12017-07-27 16:20:58 -0700915ServiceList::ServiceList() {}
Tom Cherrybac32992015-07-31 12:45:25 -0700916
Tom Cherry911b9b12017-07-27 16:20:58 -0700917ServiceList& ServiceList::GetInstance() {
918 static ServiceList instance;
Tom Cherrybac32992015-07-31 12:45:25 -0700919 return instance;
920}
921
Tom Cherry911b9b12017-07-27 16:20:58 -0700922void ServiceList::AddService(std::unique_ptr<Service> service) {
Tom Cherryb7349902015-08-26 11:43:36 -0700923 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700924}
925
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700926std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
Tom Cherrybac32992015-07-31 12:45:25 -0700927 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
928 // SECLABEL can be a - to denote default
929 std::size_t command_arg = 1;
930 for (std::size_t i = 1; i < args.size(); ++i) {
931 if (args[i] == "--") {
932 command_arg = i + 1;
933 break;
934 }
935 }
936 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700937 LOG(ERROR) << "exec called with too many supplementary group ids";
Tom Cherrybac32992015-07-31 12:45:25 -0700938 return nullptr;
939 }
940
941 if (command_arg >= args.size()) {
Elliott Hughesf86b5a62016-06-24 15:12:21 -0700942 LOG(ERROR) << "exec called without command";
Tom Cherrybac32992015-07-31 12:45:25 -0700943 return nullptr;
944 }
945 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
946
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700947 static size_t exec_count = 0;
948 exec_count++;
949 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
Tom Cherry86e31a82017-04-25 17:31:06 -0700950
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700951 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
Jorge Lucangeli Obes24b29132016-10-27 10:33:03 -0400952 CapSet no_capabilities;
Jorge Lucangeli Obes1b3fa3d2016-04-21 15:35:09 -0700953 unsigned namespace_flags = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700954
955 std::string seclabel = "";
956 if (command_arg > 2 && args[1] != "-") {
957 seclabel = args[1];
958 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700959 Result<uid_t> uid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700960 if (command_arg > 3) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700961 uid = DecodeUid(args[2]);
962 if (!uid) {
963 LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700964 return nullptr;
965 }
Tom Cherrybac32992015-07-31 12:45:25 -0700966 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700967 Result<gid_t> gid = 0;
Tom Cherrybac32992015-07-31 12:45:25 -0700968 std::vector<gid_t> supp_gids;
969 if (command_arg > 4) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700970 gid = DecodeUid(args[3]);
971 if (!gid) {
972 LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700973 return nullptr;
974 }
Tom Cherrybac32992015-07-31 12:45:25 -0700975 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
976 for (size_t i = 0; i < nr_supp_gids; ++i) {
Tom Cherry11a3aee2017-08-03 12:54:07 -0700977 auto supp_gid = DecodeUid(args[4 + i]);
978 if (!supp_gid) {
979 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
980 << "': " << supp_gid.error();
Tom Cherry517e1f12017-05-04 17:40:33 -0700981 return nullptr;
982 }
Tom Cherry11a3aee2017-08-03 12:54:07 -0700983 supp_gids.push_back(*supp_gid);
Tom Cherrybac32992015-07-31 12:45:25 -0700984 }
985 }
986
Tom Cherry11a3aee2017-08-03 12:54:07 -0700987 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, no_capabilities,
Tom Cherry3b81f2d2017-07-28 14:48:41 -0700988 namespace_flags, seclabel, str_args);
Tom Cherrybac32992015-07-31 12:45:25 -0700989}
990
Tom Cherry59383792017-07-26 16:09:09 -0700991// Shutdown services in the opposite order that they were started.
Tom Cherry911b9b12017-07-27 16:20:58 -0700992const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
Tom Cherry59383792017-07-26 16:09:09 -0700993 std::vector<Service*> shutdown_services;
994 for (const auto& service : services_) {
995 if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
996 }
997 std::sort(shutdown_services.begin(), shutdown_services.end(),
998 [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
Tom Cherry911b9b12017-07-27 16:20:58 -0700999 return shutdown_services;
Tom Cherry59383792017-07-26 16:09:09 -07001000}
1001
Tom Cherry911b9b12017-07-27 16:20:58 -07001002void ServiceList::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -07001003 auto svc_it = std::find_if(services_.begin(), services_.end(),
1004 [&svc] (const std::unique_ptr<Service>& s) {
1005 return svc.name() == s->name();
1006 });
1007 if (svc_it == services_.end()) {
1008 return;
1009 }
1010
1011 services_.erase(svc_it);
1012}
1013
Tom Cherry911b9b12017-07-27 16:20:58 -07001014void ServiceList::DumpState() const {
Tom Cherryb7349902015-08-26 11:43:36 -07001015 for (const auto& s : services_) {
1016 s->DumpState();
1017 }
Tom Cherryb7349902015-08-26 11:43:36 -07001018}
1019
Tom Cherry89bcc852017-08-02 17:01:36 -07001020Result<Success> ServiceParser::ParseSection(std::vector<std::string>&& args,
1021 const std::string& filename, int line) {
Tom Cherryb7349902015-08-26 11:43:36 -07001022 if (args.size() < 3) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001023 return Error() << "services must have a name and a program";
Tom Cherryb7349902015-08-26 11:43:36 -07001024 }
1025
1026 const std::string& name = args[1];
1027 if (!IsValidName(name)) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001028 return Error() << "invalid service name '" << name << "'";
Tom Cherryb7349902015-08-26 11:43:36 -07001029 }
1030
Tom Cherry911b9b12017-07-27 16:20:58 -07001031 Service* old_service = service_list_->FindService(name);
Tom Cherry30a6f272017-04-19 15:31:58 -07001032 if (old_service) {
Tom Cherry89bcc852017-08-02 17:01:36 -07001033 return Error() << "ignored duplicate definition of service '" << name << "'";
Tom Cherry30a6f272017-04-19 15:31:58 -07001034 }
1035
Tom Cherryb7349902015-08-26 11:43:36 -07001036 std::vector<std::string> str_args(args.begin() + 2, args.end());
Wei Wang641ff0a2017-03-27 10:59:11 -07001037 service_ = std::make_unique<Service>(name, str_args);
Tom Cherry89bcc852017-08-02 17:01:36 -07001038 return Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001039}
1040
Tom Cherry89bcc852017-08-02 17:01:36 -07001041Result<Success> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
1042 return service_ ? service_->ParseLine(std::move(args)) : Success();
Tom Cherryb7349902015-08-26 11:43:36 -07001043}
1044
1045void ServiceParser::EndSection() {
1046 if (service_) {
Tom Cherry911b9b12017-07-27 16:20:58 -07001047 service_list_->AddService(std::move(service_));
Tom Cherryb7349902015-08-26 11:43:36 -07001048 }
1049}
1050
1051bool ServiceParser::IsValidName(const std::string& name) const {
Elliott Hughesb7788fd2017-02-28 09:54:36 -08001052 // Property names can be any length, but may only contain certain characters.
1053 // Property values can contain any characters, but may only be a certain length.
1054 // (The latter restriction is needed because `start` and `stop` work by writing
1055 // the service name to the "ctl.start" and "ctl.stop" properties.)
1056 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
Tom Cherrybac32992015-07-31 12:45:25 -07001057}
Tom Cherry81f5d3e2017-06-22 12:53:17 -07001058
1059} // namespace init
1060} // namespace android