1 /*
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>
20 #include <inttypes.h>
21 #include <linux/securebits.h>
22 #include <sched.h>
23 #include <sys/mount.h>
24 #include <sys/prctl.h>
25 #include <sys/resource.h>
26 #include <sys/stat.h>
27 #include <sys/time.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <termios.h>
31 #include <unistd.h>
32
33 #include <selinux/selinux.h>
34
35 #include <android-base/file.h>
36 #include <android-base/parseint.h>
37 #include <android-base/properties.h>
38 #include <android-base/stringprintf.h>
39 #include <android-base/strings.h>
40 #include <system/thread_defs.h>
41
42 #include <processgroup/processgroup.h>
43
44 #include "action.h"
45 #include "init.h"
46 #include "init_parser.h"
47 #include "log.h"
48 #include "property_service.h"
49 #include "util.h"
50
51 using android::base::ParseInt;
52 using android::base::StringPrintf;
53 using android::base::WriteStringToFile;
54
ComputeContextFromExecutable(std::string & service_name,const std::string & service_path)55 static std::string ComputeContextFromExecutable(std::string& service_name,
56 const std::string& service_path) {
57 std::string computed_context;
58
59 char* raw_con = nullptr;
60 char* raw_filecon = nullptr;
61
62 if (getcon(&raw_con) == -1) {
63 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
64 return "";
65 }
66 std::unique_ptr<char> mycon(raw_con);
67
68 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
69 LOG(ERROR) << "could not get file context while starting '" << service_name << "'";
70 return "";
71 }
72 std::unique_ptr<char> filecon(raw_filecon);
73
74 char* new_con = nullptr;
75 int rc = security_compute_create(mycon.get(), filecon.get(),
76 string_to_security_class("process"), &new_con);
77 if (rc == 0) {
78 computed_context = new_con;
79 free(new_con);
80 }
81 if (rc == 0 && computed_context == mycon.get()) {
82 LOG(ERROR) << "service " << service_name << " does not have a SELinux domain defined";
83 return "";
84 }
85 if (rc < 0) {
86 LOG(ERROR) << "could not get context while starting '" << service_name << "'";
87 return "";
88 }
89 return computed_context;
90 }
91
SetUpPidNamespace(const std::string & service_name)92 static void SetUpPidNamespace(const std::string& service_name) {
93 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
94
95 // It's OK to LOG(FATAL) in this function since it's running in the first
96 // child process.
97 if (mount("", "/proc", "proc", kSafeFlags | MS_REMOUNT, "") == -1) {
98 PLOG(FATAL) << "couldn't remount(/proc) for " << service_name;
99 }
100
101 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) {
102 PLOG(FATAL) << "couldn't set name for " << service_name;
103 }
104
105 pid_t child_pid = fork();
106 if (child_pid == -1) {
107 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name;
108 }
109
110 if (child_pid > 0) {
111 // So that we exit with the right status.
112 static int init_exitstatus = 0;
113 signal(SIGTERM, [](int) { _exit(init_exitstatus); });
114
115 pid_t waited_pid;
116 int status;
117 while ((waited_pid = wait(&status)) > 0) {
118 // This loop will end when there are no processes left inside the
119 // PID namespace or when the init process inside the PID namespace
120 // gets a signal.
121 if (waited_pid == child_pid) {
122 init_exitstatus = status;
123 }
124 }
125 if (!WIFEXITED(init_exitstatus)) {
126 _exit(EXIT_FAILURE);
127 }
128 _exit(WEXITSTATUS(init_exitstatus));
129 }
130 }
131
ExpandArgs(const std::vector<std::string> & args,std::vector<char * > * strs)132 static void ExpandArgs(const std::vector<std::string>& args, std::vector<char*>* strs) {
133 std::vector<std::string> expanded_args;
134 expanded_args.resize(args.size());
135 strs->push_back(const_cast<char*>(args[0].c_str()));
136 for (std::size_t i = 1; i < args.size(); ++i) {
137 if (!expand_props(args[i], &expanded_args[i])) {
138 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
139 }
140 strs->push_back(const_cast<char*>(expanded_args[i].c_str()));
141 }
142 strs->push_back(nullptr);
143 }
144
ServiceEnvironmentInfo()145 ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
146 }
147
ServiceEnvironmentInfo(const std::string & name,const std::string & value)148 ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
149 const std::string& value)
150 : name(name), value(value) {
151 }
152
Service(const std::string & name,const std::vector<std::string> & args)153 Service::Service(const std::string& name, const std::vector<std::string>& args)
154 : name_(name),
155 classnames_({"default"}),
156 flags_(0),
157 pid_(0),
158 crash_count_(0),
159 uid_(0),
160 gid_(0),
161 namespace_flags_(0),
162 seclabel_(""),
163 keychord_id_(0),
164 ioprio_class_(IoSchedClass_NONE),
165 ioprio_pri_(0),
166 priority_(0),
167 oom_score_adjust_(-1000),
168 args_(args) {
169 onrestart_.InitSingleTrigger("onrestart");
170 }
171
Service(const std::string & name,unsigned flags,uid_t uid,gid_t gid,const std::vector<gid_t> & supp_gids,const CapSet & capabilities,unsigned namespace_flags,const std::string & seclabel,const std::vector<std::string> & args)172 Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
173 const std::vector<gid_t>& supp_gids, const CapSet& capabilities,
174 unsigned namespace_flags, const std::string& seclabel,
175 const std::vector<std::string>& args)
176 : name_(name),
177 classnames_({"default"}),
178 flags_(flags),
179 pid_(0),
180 crash_count_(0),
181 uid_(uid),
182 gid_(gid),
183 supp_gids_(supp_gids),
184 capabilities_(capabilities),
185 namespace_flags_(namespace_flags),
186 seclabel_(seclabel),
187 keychord_id_(0),
188 ioprio_class_(IoSchedClass_NONE),
189 ioprio_pri_(0),
190 priority_(0),
191 oom_score_adjust_(-1000),
192 args_(args) {
193 onrestart_.InitSingleTrigger("onrestart");
194 }
195
NotifyStateChange(const std::string & new_state) const196 void Service::NotifyStateChange(const std::string& new_state) const {
197 if ((flags_ & SVC_TEMPORARY) != 0) {
198 // Services created by 'exec' are temporary and don't have properties tracking their state.
199 return;
200 }
201
202 std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
203 property_set(prop_name.c_str(), new_state.c_str());
204
205 if (new_state == "running") {
206 uint64_t start_ns = time_started_.time_since_epoch().count();
207 property_set(StringPrintf("ro.boottime.%s", name_.c_str()).c_str(),
208 StringPrintf("%" PRIu64, start_ns).c_str());
209 }
210 }
211
KillProcessGroup(int signal)212 void Service::KillProcessGroup(int signal) {
213 LOG(INFO) << "Sending signal " << signal
214 << " to service '" << name_
215 << "' (pid " << pid_ << ") process group...";
216 int r;
217 if (signal == SIGTERM) {
218 r = killProcessGroupOnce(uid_, pid_, signal);
219 } else {
220 r = killProcessGroup(uid_, pid_, signal);
221 }
222 if (r == -1) {
223 PLOG(ERROR) << "killProcessGroup(" << uid_ << ", " << pid_ << ", " << signal << ") failed";
224 }
225 if (kill(-pid_, signal) == -1) {
226 PLOG(ERROR) << "kill(" << pid_ << ", " << signal << ") failed";
227 }
228 }
229
SetProcessAttributes()230 void Service::SetProcessAttributes() {
231 // Keep capabilites on uid change.
232 if (capabilities_.any() && uid_) {
233 if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED) != 0) {
234 PLOG(FATAL) << "prtcl(PR_SET_KEEPCAPS) failed for " << name_;
235 }
236 }
237
238 // TODO: work out why this fails for `console` then upgrade to FATAL.
239 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
240
241 if (gid_) {
242 if (setgid(gid_) != 0) {
243 PLOG(FATAL) << "setgid failed for " << name_;
244 }
245 }
246 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
247 PLOG(FATAL) << "setgroups failed for " << name_;
248 }
249 if (uid_) {
250 if (setuid(uid_) != 0) {
251 PLOG(FATAL) << "setuid failed for " << name_;
252 }
253 }
254 if (!seclabel_.empty()) {
255 if (setexeccon(seclabel_.c_str()) < 0) {
256 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
257 }
258 }
259 if (priority_ != 0) {
260 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
261 PLOG(FATAL) << "setpriority failed for " << name_;
262 }
263 }
264 if (capabilities_.any()) {
265 if (!SetCapsForExec(capabilities_)) {
266 LOG(FATAL) << "cannot set capabilities for " << name_;
267 }
268 }
269 }
270
Reap()271 void Service::Reap() {
272 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
273 KillProcessGroup(SIGKILL);
274 }
275
276 // Remove any descriptor resources we may have created.
277 std::for_each(descriptors_.begin(), descriptors_.end(),
278 std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
279
280 if (flags_ & SVC_TEMPORARY) {
281 return;
282 }
283
284 pid_ = 0;
285 flags_ &= (~SVC_RUNNING);
286
287 // Oneshot processes go into the disabled state on exit,
288 // except when manually restarted.
289 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
290 flags_ |= SVC_DISABLED;
291 }
292
293 // Disabled and reset processes do not get restarted automatically.
294 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
295 NotifyStateChange("stopped");
296 return;
297 }
298
299 // If we crash > 4 times in 4 minutes, reboot into recovery.
300 boot_clock::time_point now = boot_clock::now();
301 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
302 if (now < time_crashed_ + 4min) {
303 if (++crash_count_ > 4) {
304 LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes";
305 panic();
306 }
307 } else {
308 time_crashed_ = now;
309 crash_count_ = 1;
310 }
311 }
312
313 flags_ &= (~SVC_RESTART);
314 flags_ |= SVC_RESTARTING;
315
316 // Execute all onrestart commands for this service.
317 onrestart_.ExecuteAllCommands();
318
319 NotifyStateChange("restarting");
320 return;
321 }
322
DumpState() const323 void Service::DumpState() const {
324 LOG(INFO) << "service " << name_;
325 LOG(INFO) << " class '" << android::base::Join(classnames_, " ") << "'";
326 LOG(INFO) << " exec "<< android::base::Join(args_, " ");
327 std::for_each(descriptors_.begin(), descriptors_.end(),
328 [] (const auto& info) { LOG(INFO) << *info; });
329 }
330
ParseCapabilities(const std::vector<std::string> & args,std::string * err)331 bool Service::ParseCapabilities(const std::vector<std::string>& args, std::string* err) {
332 capabilities_ = 0;
333
334 if (!CapAmbientSupported()) {
335 *err = "capabilities requested but the kernel does not support ambient capabilities";
336 return false;
337 }
338
339 unsigned int last_valid_cap = GetLastValidCap();
340 if (last_valid_cap >= capabilities_.size()) {
341 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
342 }
343
344 for (size_t i = 1; i < args.size(); i++) {
345 const std::string& arg = args[i];
346 int res = LookupCap(arg);
347 if (res < 0) {
348 *err = StringPrintf("invalid capability '%s'", arg.c_str());
349 return false;
350 }
351 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
352 if (cap > last_valid_cap) {
353 *err = StringPrintf("capability '%s' not supported by the kernel", arg.c_str());
354 return false;
355 }
356 capabilities_[cap] = true;
357 }
358 return true;
359 }
360
ParseClass(const std::vector<std::string> & args,std::string * err)361 bool Service::ParseClass(const std::vector<std::string>& args, std::string* err) {
362 classnames_ = std::set<std::string>(args.begin() + 1, args.end());
363 return true;
364 }
365
ParseConsole(const std::vector<std::string> & args,std::string * err)366 bool Service::ParseConsole(const std::vector<std::string>& args, std::string* err) {
367 flags_ |= SVC_CONSOLE;
368 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
369 return true;
370 }
371
ParseCritical(const std::vector<std::string> & args,std::string * err)372 bool Service::ParseCritical(const std::vector<std::string>& args, std::string* err) {
373 flags_ |= SVC_CRITICAL;
374 return true;
375 }
376
ParseDisabled(const std::vector<std::string> & args,std::string * err)377 bool Service::ParseDisabled(const std::vector<std::string>& args, std::string* err) {
378 flags_ |= SVC_DISABLED;
379 flags_ |= SVC_RC_DISABLED;
380 return true;
381 }
382
ParseGroup(const std::vector<std::string> & args,std::string * err)383 bool Service::ParseGroup(const std::vector<std::string>& args, std::string* err) {
384 gid_ = decode_uid(args[1].c_str());
385 for (std::size_t n = 2; n < args.size(); n++) {
386 supp_gids_.emplace_back(decode_uid(args[n].c_str()));
387 }
388 return true;
389 }
390
ParsePriority(const std::vector<std::string> & args,std::string * err)391 bool Service::ParsePriority(const std::vector<std::string>& args, std::string* err) {
392 priority_ = 0;
393 if (!ParseInt(args[1], &priority_,
394 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
395 static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
396 *err = StringPrintf("process priority value must be range %d - %d",
397 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
398 return false;
399 }
400 return true;
401 }
402
ParseIoprio(const std::vector<std::string> & args,std::string * err)403 bool Service::ParseIoprio(const std::vector<std::string>& args, std::string* err) {
404 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
405 *err = "priority value must be range 0 - 7";
406 return false;
407 }
408
409 if (args[1] == "rt") {
410 ioprio_class_ = IoSchedClass_RT;
411 } else if (args[1] == "be") {
412 ioprio_class_ = IoSchedClass_BE;
413 } else if (args[1] == "idle") {
414 ioprio_class_ = IoSchedClass_IDLE;
415 } else {
416 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
417 return false;
418 }
419
420 return true;
421 }
422
ParseKeycodes(const std::vector<std::string> & args,std::string * err)423 bool Service::ParseKeycodes(const std::vector<std::string>& args, std::string* err) {
424 for (std::size_t i = 1; i < args.size(); i++) {
425 int code;
426 if (ParseInt(args[i], &code)) {
427 keycodes_.emplace_back(code);
428 } else {
429 LOG(WARNING) << "ignoring invalid keycode: " << args[i];
430 }
431 }
432 return true;
433 }
434
ParseOneshot(const std::vector<std::string> & args,std::string * err)435 bool Service::ParseOneshot(const std::vector<std::string>& args, std::string* err) {
436 flags_ |= SVC_ONESHOT;
437 return true;
438 }
439
ParseOnrestart(const std::vector<std::string> & args,std::string * err)440 bool Service::ParseOnrestart(const std::vector<std::string>& args, std::string* err) {
441 std::vector<std::string> str_args(args.begin() + 1, args.end());
442 onrestart_.AddCommand(str_args, "", 0, err);
443 return true;
444 }
445
ParseNamespace(const std::vector<std::string> & args,std::string * err)446 bool Service::ParseNamespace(const std::vector<std::string>& args, std::string* err) {
447 for (size_t i = 1; i < args.size(); i++) {
448 if (args[i] == "pid") {
449 namespace_flags_ |= CLONE_NEWPID;
450 // PID namespaces require mount namespaces.
451 namespace_flags_ |= CLONE_NEWNS;
452 } else if (args[i] == "mnt") {
453 namespace_flags_ |= CLONE_NEWNS;
454 } else {
455 *err = "namespace must be 'pid' or 'mnt'";
456 return false;
457 }
458 }
459 return true;
460 }
461
ParseOomScoreAdjust(const std::vector<std::string> & args,std::string * err)462 bool Service::ParseOomScoreAdjust(const std::vector<std::string>& args, std::string* err) {
463 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
464 *err = "oom_score_adjust value must be in range -1000 - +1000";
465 return false;
466 }
467 return true;
468 }
469
ParseSeclabel(const std::vector<std::string> & args,std::string * err)470 bool Service::ParseSeclabel(const std::vector<std::string>& args, std::string* err) {
471 seclabel_ = args[1];
472 return true;
473 }
474
ParseSetenv(const std::vector<std::string> & args,std::string * err)475 bool Service::ParseSetenv(const std::vector<std::string>& args, std::string* err) {
476 envvars_.emplace_back(args[1], args[2]);
477 return true;
478 }
479
480 template <typename T>
AddDescriptor(const std::vector<std::string> & args,std::string * err)481 bool Service::AddDescriptor(const std::vector<std::string>& args, std::string* err) {
482 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
483 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
484 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
485 std::string context = args.size() > 6 ? args[6] : "";
486
487 auto descriptor = std::make_unique<T>(args[1], args[2], uid, gid, perm, context);
488
489 auto old =
490 std::find_if(descriptors_.begin(), descriptors_.end(),
491 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
492
493 if (old != descriptors_.end()) {
494 *err = "duplicate descriptor " + args[1] + " " + args[2];
495 return false;
496 }
497
498 descriptors_.emplace_back(std::move(descriptor));
499 return true;
500 }
501
502 // name type perm [ uid gid context ]
ParseSocket(const std::vector<std::string> & args,std::string * err)503 bool Service::ParseSocket(const std::vector<std::string>& args, std::string* err) {
504 if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
505 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
506 return false;
507 }
508 return AddDescriptor<SocketInfo>(args, err);
509 }
510
511 // name type perm [ uid gid context ]
ParseFile(const std::vector<std::string> & args,std::string * err)512 bool Service::ParseFile(const std::vector<std::string>& args, std::string* err) {
513 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
514 *err = "file type must be 'r', 'w' or 'rw'";
515 return false;
516 }
517 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
518 *err = "file name must not be relative";
519 return false;
520 }
521 return AddDescriptor<FileInfo>(args, err);
522 }
523
ParseUser(const std::vector<std::string> & args,std::string * err)524 bool Service::ParseUser(const std::vector<std::string>& args, std::string* err) {
525 uid_ = decode_uid(args[1].c_str());
526 return true;
527 }
528
ParseWritepid(const std::vector<std::string> & args,std::string * err)529 bool Service::ParseWritepid(const std::vector<std::string>& args, std::string* err) {
530 writepid_files_.assign(args.begin() + 1, args.end());
531 return true;
532 }
533
534 class Service::OptionParserMap : public KeywordMap<OptionParser> {
535 public:
OptionParserMap()536 OptionParserMap() {
537 }
538 private:
539 Map& map() const override;
540 };
541
map() const542 Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
543 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
544 // clang-format off
545 static const Map option_parsers = {
546 {"capabilities",
547 {1, kMax, &Service::ParseCapabilities}},
548 {"class", {1, kMax, &Service::ParseClass}},
549 {"console", {0, 1, &Service::ParseConsole}},
550 {"critical", {0, 0, &Service::ParseCritical}},
551 {"disabled", {0, 0, &Service::ParseDisabled}},
552 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
553 {"ioprio", {2, 2, &Service::ParseIoprio}},
554 {"priority", {1, 1, &Service::ParsePriority}},
555 {"keycodes", {1, kMax, &Service::ParseKeycodes}},
556 {"oneshot", {0, 0, &Service::ParseOneshot}},
557 {"onrestart", {1, kMax, &Service::ParseOnrestart}},
558 {"oom_score_adjust",
559 {1, 1, &Service::ParseOomScoreAdjust}},
560 {"namespace", {1, 2, &Service::ParseNamespace}},
561 {"seclabel", {1, 1, &Service::ParseSeclabel}},
562 {"setenv", {2, 2, &Service::ParseSetenv}},
563 {"socket", {3, 6, &Service::ParseSocket}},
564 {"file", {2, 2, &Service::ParseFile}},
565 {"user", {1, 1, &Service::ParseUser}},
566 {"writepid", {1, kMax, &Service::ParseWritepid}},
567 };
568 // clang-format on
569 return option_parsers;
570 }
571
ParseLine(const std::vector<std::string> & args,std::string * err)572 bool Service::ParseLine(const std::vector<std::string>& args, std::string* err) {
573 if (args.empty()) {
574 *err = "option needed, but not provided";
575 return false;
576 }
577
578 static const OptionParserMap parser_map;
579 auto parser = parser_map.FindFunction(args[0], args.size() - 1, err);
580
581 if (!parser) {
582 return false;
583 }
584
585 return (this->*parser)(args, err);
586 }
587
ExecStart(std::unique_ptr<Timer> * exec_waiter)588 bool Service::ExecStart(std::unique_ptr<Timer>* exec_waiter) {
589 flags_ |= SVC_EXEC | SVC_ONESHOT;
590
591 exec_waiter->reset(new Timer);
592
593 if (!Start()) {
594 exec_waiter->reset();
595 return false;
596 }
597 return true;
598 }
599
Start()600 bool Service::Start() {
601 // Starting a service removes it from the disabled or reset state and
602 // immediately takes it out of the restarting state if it was in there.
603 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
604
605 // Running processes require no additional work --- if they're in the
606 // process of exiting, we've ensured that they will immediately restart
607 // on exit, unless they are ONESHOT.
608 if (flags_ & SVC_RUNNING) {
609 return false;
610 }
611
612 bool needs_console = (flags_ & SVC_CONSOLE);
613 if (needs_console) {
614 if (console_.empty()) {
615 console_ = default_console;
616 }
617
618 // Make sure that open call succeeds to ensure a console driver is
619 // properly registered for the device node
620 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
621 if (console_fd < 0) {
622 PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'";
623 flags_ |= SVC_DISABLED;
624 return false;
625 }
626 close(console_fd);
627 }
628
629 struct stat sb;
630 if (stat(args_[0].c_str(), &sb) == -1) {
631 PLOG(ERROR) << "cannot find '" << args_[0] << "', disabling '" << name_ << "'";
632 flags_ |= SVC_DISABLED;
633 return false;
634 }
635
636 std::string scon;
637 if (!seclabel_.empty()) {
638 scon = seclabel_;
639 } else {
640 LOG(INFO) << "computing context for service '" << name_ << "'";
641 scon = ComputeContextFromExecutable(name_, args_[0]);
642 if (scon == "") {
643 return false;
644 }
645 }
646
647 LOG(INFO) << "starting service '" << name_ << "'...";
648
649 pid_t pid = -1;
650 if (namespace_flags_) {
651 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
652 } else {
653 pid = fork();
654 }
655
656 if (pid == 0) {
657 umask(077);
658
659 if (namespace_flags_ & CLONE_NEWPID) {
660 // This will fork again to run an init process inside the PID
661 // namespace.
662 SetUpPidNamespace(name_);
663 }
664
665 for (const auto& ei : envvars_) {
666 add_environment(ei.name.c_str(), ei.value.c_str());
667 }
668
669 std::for_each(descriptors_.begin(), descriptors_.end(),
670 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
671
672 // See if there were "writepid" instructions to write to files under /dev/cpuset/.
673 auto cpuset_predicate = [](const std::string& path) {
674 return android::base::StartsWith(path, "/dev/cpuset/");
675 };
676 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
677 if (iter == writepid_files_.end()) {
678 // There were no "writepid" instructions for cpusets, check if the system default
679 // cpuset is specified to be used for the process.
680 std::string default_cpuset = android::base::GetProperty("ro.cpuset.default", "");
681 if (!default_cpuset.empty()) {
682 // Make sure the cpuset name starts and ends with '/'.
683 // A single '/' means the 'root' cpuset.
684 if (default_cpuset.front() != '/') {
685 default_cpuset.insert(0, 1, '/');
686 }
687 if (default_cpuset.back() != '/') {
688 default_cpuset.push_back('/');
689 }
690 writepid_files_.push_back(
691 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str()));
692 }
693 }
694 std::string pid_str = StringPrintf("%d", getpid());
695 for (const auto& file : writepid_files_) {
696 if (!WriteStringToFile(pid_str, file)) {
697 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
698 }
699 }
700
701 if (ioprio_class_ != IoSchedClass_NONE) {
702 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
703 PLOG(ERROR) << "failed to set pid " << getpid()
704 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
705 }
706 }
707
708 if (needs_console) {
709 setsid();
710 OpenConsole();
711 } else {
712 ZapStdio();
713 }
714
715 // As requested, set our gid, supplemental gids, uid, context, and
716 // priority. Aborts on failure.
717 SetProcessAttributes();
718
719 std::vector<char*> strs;
720 ExpandArgs(args_, &strs);
721 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
722 PLOG(ERROR) << "cannot execve('" << strs[0] << "')";
723 }
724
725 _exit(127);
726 }
727
728 if (pid < 0) {
729 PLOG(ERROR) << "failed to fork for '" << name_ << "'";
730 pid_ = 0;
731 return false;
732 }
733
734 if (oom_score_adjust_ != -1000) {
735 std::string oom_str = StringPrintf("%d", oom_score_adjust_);
736 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
737 if (!WriteStringToFile(oom_str, oom_file)) {
738 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno);
739 }
740 }
741
742 time_started_ = boot_clock::now();
743 pid_ = pid;
744 flags_ |= SVC_RUNNING;
745
746 errno = -createProcessGroup(uid_, pid_);
747 if (errno != 0) {
748 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
749 << name_ << "'";
750 }
751
752 if ((flags_ & SVC_EXEC) != 0) {
753 LOG(INFO) << android::base::StringPrintf(
754 "SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...", pid_, uid_, gid_,
755 supp_gids_.size(), !seclabel_.empty() ? seclabel_.c_str() : "default");
756 }
757
758 NotifyStateChange("running");
759 return true;
760 }
761
StartIfNotDisabled()762 bool Service::StartIfNotDisabled() {
763 if (!(flags_ & SVC_DISABLED)) {
764 return Start();
765 } else {
766 flags_ |= SVC_DISABLED_START;
767 }
768 return true;
769 }
770
Enable()771 bool Service::Enable() {
772 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
773 if (flags_ & SVC_DISABLED_START) {
774 return Start();
775 }
776 return true;
777 }
778
Reset()779 void Service::Reset() {
780 StopOrReset(SVC_RESET);
781 }
782
Stop()783 void Service::Stop() {
784 StopOrReset(SVC_DISABLED);
785 }
786
Terminate()787 void Service::Terminate() {
788 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
789 flags_ |= SVC_DISABLED;
790 if (pid_) {
791 KillProcessGroup(SIGTERM);
792 NotifyStateChange("stopping");
793 }
794 }
795
Restart()796 void Service::Restart() {
797 if (flags_ & SVC_RUNNING) {
798 /* Stop, wait, then start the service. */
799 StopOrReset(SVC_RESTART);
800 } else if (!(flags_ & SVC_RESTARTING)) {
801 /* Just start the service since it's not running. */
802 Start();
803 } /* else: Service is restarting anyways. */
804 }
805
RestartIfNeeded(time_t * process_needs_restart_at)806 void Service::RestartIfNeeded(time_t* process_needs_restart_at) {
807 boot_clock::time_point now = boot_clock::now();
808 boot_clock::time_point next_start = time_started_ + 5s;
809 if (now > next_start) {
810 flags_ &= (~SVC_RESTARTING);
811 Start();
812 return;
813 }
814
815 time_t next_start_time_t = time(nullptr) +
816 time_t(std::chrono::duration_cast<std::chrono::seconds>(next_start - now).count());
817 if (next_start_time_t < *process_needs_restart_at || *process_needs_restart_at == 0) {
818 *process_needs_restart_at = next_start_time_t;
819 }
820 }
821
822 // The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
StopOrReset(int how)823 void Service::StopOrReset(int how) {
824 // The service is still SVC_RUNNING until its process exits, but if it has
825 // already exited it shoudn't attempt a restart yet.
826 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
827
828 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
829 // An illegal flag: default to SVC_DISABLED.
830 how = SVC_DISABLED;
831 }
832
833 // If the service has not yet started, prevent it from auto-starting with its class.
834 if (how == SVC_RESET) {
835 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
836 } else {
837 flags_ |= how;
838 }
839
840 if (pid_) {
841 KillProcessGroup(SIGKILL);
842 NotifyStateChange("stopping");
843 } else {
844 NotifyStateChange("stopped");
845 }
846 }
847
ZapStdio() const848 void Service::ZapStdio() const {
849 int fd;
850 fd = open("/dev/null", O_RDWR);
851 dup2(fd, 0);
852 dup2(fd, 1);
853 dup2(fd, 2);
854 close(fd);
855 }
856
OpenConsole() const857 void Service::OpenConsole() const {
858 int fd = open(console_.c_str(), O_RDWR);
859 if (fd == -1) fd = open("/dev/null", O_RDWR);
860 ioctl(fd, TIOCSCTTY, 0);
861 dup2(fd, 0);
862 dup2(fd, 1);
863 dup2(fd, 2);
864 close(fd);
865 }
866
867 int ServiceManager::exec_count_ = 0;
868
ServiceManager()869 ServiceManager::ServiceManager() {
870 }
871
GetInstance()872 ServiceManager& ServiceManager::GetInstance() {
873 static ServiceManager instance;
874 return instance;
875 }
876
AddService(std::unique_ptr<Service> service)877 void ServiceManager::AddService(std::unique_ptr<Service> service) {
878 Service* old_service = FindServiceByName(service->name());
879 if (old_service) {
880 LOG(ERROR) << "ignored duplicate definition of service '" << service->name() << "'";
881 return;
882 }
883 services_.emplace_back(std::move(service));
884 }
885
Exec(const std::vector<std::string> & args)886 bool ServiceManager::Exec(const std::vector<std::string>& args) {
887 Service* svc = MakeExecOneshotService(args);
888 if (!svc) {
889 LOG(ERROR) << "Could not create exec service";
890 return false;
891 }
892 if (!svc->ExecStart(&exec_waiter_)) {
893 LOG(ERROR) << "Could not start exec service";
894 ServiceManager::GetInstance().RemoveService(*svc);
895 return false;
896 }
897 return true;
898 }
899
ExecStart(const std::string & name)900 bool ServiceManager::ExecStart(const std::string& name) {
901 Service* svc = FindServiceByName(name);
902 if (!svc) {
903 LOG(ERROR) << "ExecStart(" << name << "): Service not found";
904 return false;
905 }
906 if (!svc->ExecStart(&exec_waiter_)) {
907 LOG(ERROR) << "ExecStart(" << name << "): Could not start Service";
908 return false;
909 }
910 return true;
911 }
912
IsWaitingForExec() const913 bool ServiceManager::IsWaitingForExec() const { return exec_waiter_ != nullptr; }
914
MakeExecOneshotService(const std::vector<std::string> & args)915 Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
916 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
917 // SECLABEL can be a - to denote default
918 std::size_t command_arg = 1;
919 for (std::size_t i = 1; i < args.size(); ++i) {
920 if (args[i] == "--") {
921 command_arg = i + 1;
922 break;
923 }
924 }
925 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
926 LOG(ERROR) << "exec called with too many supplementary group ids";
927 return nullptr;
928 }
929
930 if (command_arg >= args.size()) {
931 LOG(ERROR) << "exec called without command";
932 return nullptr;
933 }
934 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
935
936 exec_count_++;
937 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
938 unsigned flags = SVC_EXEC | SVC_ONESHOT | SVC_TEMPORARY;
939 CapSet no_capabilities;
940 unsigned namespace_flags = 0;
941
942 std::string seclabel = "";
943 if (command_arg > 2 && args[1] != "-") {
944 seclabel = args[1];
945 }
946 uid_t uid = 0;
947 if (command_arg > 3) {
948 uid = decode_uid(args[2].c_str());
949 }
950 gid_t gid = 0;
951 std::vector<gid_t> supp_gids;
952 if (command_arg > 4) {
953 gid = decode_uid(args[3].c_str());
954 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
955 for (size_t i = 0; i < nr_supp_gids; ++i) {
956 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
957 }
958 }
959
960 auto svc_p = std::make_unique<Service>(name, flags, uid, gid, supp_gids, no_capabilities,
961 namespace_flags, seclabel, str_args);
962 Service* svc = svc_p.get();
963 services_.emplace_back(std::move(svc_p));
964
965 return svc;
966 }
967
FindServiceByName(const std::string & name) const968 Service* ServiceManager::FindServiceByName(const std::string& name) const {
969 auto svc = std::find_if(services_.begin(), services_.end(),
970 [&name] (const std::unique_ptr<Service>& s) {
971 return name == s->name();
972 });
973 if (svc != services_.end()) {
974 return svc->get();
975 }
976 return nullptr;
977 }
978
FindServiceByPid(pid_t pid) const979 Service* ServiceManager::FindServiceByPid(pid_t pid) const {
980 auto svc = std::find_if(services_.begin(), services_.end(),
981 [&pid] (const std::unique_ptr<Service>& s) {
982 return s->pid() == pid;
983 });
984 if (svc != services_.end()) {
985 return svc->get();
986 }
987 return nullptr;
988 }
989
FindServiceByKeychord(int keychord_id) const990 Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
991 auto svc = std::find_if(services_.begin(), services_.end(),
992 [&keychord_id] (const std::unique_ptr<Service>& s) {
993 return s->keychord_id() == keychord_id;
994 });
995
996 if (svc != services_.end()) {
997 return svc->get();
998 }
999 return nullptr;
1000 }
1001
ForEachService(const std::function<void (Service *)> & callback) const1002 void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const {
1003 for (const auto& s : services_) {
1004 callback(s.get());
1005 }
1006 }
1007
ForEachServiceInClass(const std::string & classname,void (* func)(Service * svc)) const1008 void ServiceManager::ForEachServiceInClass(const std::string& classname,
1009 void (*func)(Service* svc)) const {
1010 for (const auto& s : services_) {
1011 if (s->classnames().find(classname) != s->classnames().end()) {
1012 func(s.get());
1013 }
1014 }
1015 }
1016
ForEachServiceWithFlags(unsigned matchflags,void (* func)(Service * svc)) const1017 void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
1018 void (*func)(Service* svc)) const {
1019 for (const auto& s : services_) {
1020 if (s->flags() & matchflags) {
1021 func(s.get());
1022 }
1023 }
1024 }
1025
RemoveService(const Service & svc)1026 void ServiceManager::RemoveService(const Service& svc) {
1027 auto svc_it = std::find_if(services_.begin(), services_.end(),
1028 [&svc] (const std::unique_ptr<Service>& s) {
1029 return svc.name() == s->name();
1030 });
1031 if (svc_it == services_.end()) {
1032 return;
1033 }
1034
1035 services_.erase(svc_it);
1036 }
1037
DumpState() const1038 void ServiceManager::DumpState() const {
1039 for (const auto& s : services_) {
1040 s->DumpState();
1041 }
1042 }
1043
ReapOneProcess()1044 bool ServiceManager::ReapOneProcess() {
1045 int status;
1046 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
1047 if (pid == 0) {
1048 return false;
1049 } else if (pid == -1) {
1050 PLOG(ERROR) << "waitpid failed";
1051 return false;
1052 }
1053
1054 Service* svc = FindServiceByPid(pid);
1055
1056 std::string name;
1057 std::string wait_string;
1058 if (svc) {
1059 name = android::base::StringPrintf("Service '%s' (pid %d)",
1060 svc->name().c_str(), pid);
1061 if (svc->flags() & SVC_EXEC) {
1062 wait_string =
1063 android::base::StringPrintf(" waiting took %f seconds", exec_waiter_->duration_s());
1064 }
1065 } else {
1066 name = android::base::StringPrintf("Untracked pid %d", pid);
1067 }
1068
1069 if (WIFEXITED(status)) {
1070 LOG(INFO) << name << " exited with status " << WEXITSTATUS(status) << wait_string;
1071 } else if (WIFSIGNALED(status)) {
1072 LOG(INFO) << name << " killed by signal " << WTERMSIG(status) << wait_string;
1073 } else if (WIFSTOPPED(status)) {
1074 LOG(INFO) << name << " stopped by signal " << WSTOPSIG(status) << wait_string;
1075 } else {
1076 LOG(INFO) << name << " state changed" << wait_string;
1077 }
1078
1079 if (!svc) {
1080 return true;
1081 }
1082
1083 svc->Reap();
1084
1085 if (svc->flags() & SVC_EXEC) {
1086 exec_waiter_.reset();
1087 }
1088 if (svc->flags() & SVC_TEMPORARY) {
1089 RemoveService(*svc);
1090 }
1091
1092 return true;
1093 }
1094
ReapAnyOutstandingChildren()1095 void ServiceManager::ReapAnyOutstandingChildren() {
1096 while (ReapOneProcess()) {
1097 }
1098 }
1099
ParseSection(const std::vector<std::string> & args,std::string * err)1100 bool ServiceParser::ParseSection(const std::vector<std::string>& args,
1101 std::string* err) {
1102 if (args.size() < 3) {
1103 *err = "services must have a name and a program";
1104 return false;
1105 }
1106
1107 const std::string& name = args[1];
1108 if (!IsValidName(name)) {
1109 *err = StringPrintf("invalid service name '%s'", name.c_str());
1110 return false;
1111 }
1112
1113 std::vector<std::string> str_args(args.begin() + 2, args.end());
1114 service_ = std::make_unique<Service>(name, str_args);
1115 return true;
1116 }
1117
ParseLineSection(const std::vector<std::string> & args,const std::string & filename,int line,std::string * err) const1118 bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
1119 const std::string& filename, int line,
1120 std::string* err) const {
1121 return service_ ? service_->ParseLine(args, err) : false;
1122 }
1123
EndSection()1124 void ServiceParser::EndSection() {
1125 if (service_) {
1126 ServiceManager::GetInstance().AddService(std::move(service_));
1127 }
1128 }
1129
IsValidName(const std::string & name) const1130 bool ServiceParser::IsValidName(const std::string& name) const {
1131 // Property names can be any length, but may only contain certain characters.
1132 // Property values can contain any characters, but may only be a certain length.
1133 // (The latter restriction is needed because `start` and `stop` work by writing
1134 // the service name to the "ctl.start" and "ctl.stop" properties.)
1135 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
1136 }
1137