• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/input.h>
22 #include <linux/securebits.h>
23 #include <sched.h>
24 #include <sys/mount.h>
25 #include <sys/prctl.h>
26 #include <sys/resource.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/wait.h>
30 #include <termios.h>
31 #include <unistd.h>
32 
33 #include <android-base/file.h>
34 #include <android-base/logging.h>
35 #include <android-base/parseint.h>
36 #include <android-base/properties.h>
37 #include <android-base/stringprintf.h>
38 #include <android-base/strings.h>
39 #include <android-base/unique_fd.h>
40 #include <hidl-util/FQName.h>
41 #include <processgroup/processgroup.h>
42 #include <selinux/selinux.h>
43 #include <system/thread_defs.h>
44 
45 #include "rlimit_parser.h"
46 #include "util.h"
47 
48 #if defined(__ANDROID__)
49 #include <android/api-level.h>
50 #include <sys/system_properties.h>
51 
52 #include "init.h"
53 #include "mount_namespace.h"
54 #include "property_service.h"
55 #include "selinux.h"
56 #else
57 #include "host_init_stubs.h"
58 #endif
59 
60 using android::base::boot_clock;
61 using android::base::GetProperty;
62 using android::base::Join;
63 using android::base::ParseInt;
64 using android::base::Split;
65 using android::base::StartsWith;
66 using android::base::StringPrintf;
67 using android::base::unique_fd;
68 using android::base::WriteStringToFile;
69 
70 namespace android {
71 namespace init {
72 
ComputeContextFromExecutable(const std::string & service_path)73 static Result<std::string> ComputeContextFromExecutable(const std::string& service_path) {
74     std::string computed_context;
75 
76     char* raw_con = nullptr;
77     char* raw_filecon = nullptr;
78 
79     if (getcon(&raw_con) == -1) {
80         return Error() << "Could not get security context";
81     }
82     std::unique_ptr<char> mycon(raw_con);
83 
84     if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
85         return Error() << "Could not get file context";
86     }
87     std::unique_ptr<char> filecon(raw_filecon);
88 
89     char* new_con = nullptr;
90     int rc = security_compute_create(mycon.get(), filecon.get(),
91                                      string_to_security_class("process"), &new_con);
92     if (rc == 0) {
93         computed_context = new_con;
94         free(new_con);
95     }
96     if (rc == 0 && computed_context == mycon.get()) {
97         return Error() << "File " << service_path << "(labeled \"" << filecon.get()
98                        << "\") has incorrect label or no domain transition from " << mycon.get()
99                        << " to another SELinux domain defined. Have you configured your "
100                           "service correctly? https://source.android.com/security/selinux/"
101                           "device-policy#label_new_services_and_address_denials";
102     }
103     if (rc < 0) {
104         return Error() << "Could not get process context";
105     }
106     return computed_context;
107 }
108 
SetUpMountNamespace() const109 Result<Success> Service::SetUpMountNamespace() const {
110     constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
111 
112     // Recursively remount / as slave like zygote does so unmounting and mounting /proc
113     // doesn't interfere with the parent namespace's /proc mount. This will also
114     // prevent any other mounts/unmounts initiated by the service from interfering
115     // with the parent namespace but will still allow mount events from the parent
116     // namespace to propagate to the child.
117     if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
118         return ErrnoError() << "Could not remount(/) recursively as slave";
119     }
120 
121     // umount() then mount() /proc and/or /sys
122     // Note that it is not sufficient to mount with MS_REMOUNT.
123     if (namespace_flags_ & CLONE_NEWPID) {
124         if (umount("/proc") == -1) {
125             return ErrnoError() << "Could not umount(/proc)";
126         }
127         if (mount("", "/proc", "proc", kSafeFlags, "") == -1) {
128             return ErrnoError() << "Could not mount(/proc)";
129         }
130     }
131     bool remount_sys = std::any_of(namespaces_to_enter_.begin(), namespaces_to_enter_.end(),
132                                    [](const auto& entry) { return entry.first == CLONE_NEWNET; });
133     if (remount_sys) {
134         if (umount2("/sys", MNT_DETACH) == -1) {
135             return ErrnoError() << "Could not umount(/sys)";
136         }
137         if (mount("", "/sys", "sysfs", kSafeFlags, "") == -1) {
138             return ErrnoError() << "Could not mount(/sys)";
139         }
140     }
141     return Success();
142 }
143 
SetUpPidNamespace() const144 Result<Success> Service::SetUpPidNamespace() const {
145     if (prctl(PR_SET_NAME, name_.c_str()) == -1) {
146         return ErrnoError() << "Could not set name";
147     }
148 
149     pid_t child_pid = fork();
150     if (child_pid == -1) {
151         return ErrnoError() << "Could not fork init inside the PID namespace";
152     }
153 
154     if (child_pid > 0) {
155         // So that we exit with the right status.
156         static int init_exitstatus = 0;
157         signal(SIGTERM, [](int) { _exit(init_exitstatus); });
158 
159         pid_t waited_pid;
160         int status;
161         while ((waited_pid = wait(&status)) > 0) {
162              // This loop will end when there are no processes left inside the
163              // PID namespace or when the init process inside the PID namespace
164              // gets a signal.
165             if (waited_pid == child_pid) {
166                 init_exitstatus = status;
167             }
168         }
169         if (!WIFEXITED(init_exitstatus)) {
170             _exit(EXIT_FAILURE);
171         }
172         _exit(WEXITSTATUS(init_exitstatus));
173     }
174     return Success();
175 }
176 
EnterNamespaces() const177 Result<Success> Service::EnterNamespaces() const {
178     for (const auto& [nstype, path] : namespaces_to_enter_) {
179         auto fd = unique_fd{open(path.c_str(), O_RDONLY | O_CLOEXEC)};
180         if (fd == -1) {
181             return ErrnoError() << "Could not open namespace at " << path;
182         }
183         if (setns(fd, nstype) == -1) {
184             return ErrnoError() << "Could not setns() namespace at " << path;
185         }
186     }
187     return Success();
188 }
189 
ExpandArgsAndExecv(const std::vector<std::string> & args,bool sigstop)190 static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {
191     std::vector<std::string> expanded_args;
192     std::vector<char*> c_strings;
193 
194     expanded_args.resize(args.size());
195     c_strings.push_back(const_cast<char*>(args[0].data()));
196     for (std::size_t i = 1; i < args.size(); ++i) {
197         if (!expand_props(args[i], &expanded_args[i])) {
198             LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'";
199         }
200         c_strings.push_back(expanded_args[i].data());
201     }
202     c_strings.push_back(nullptr);
203 
204     if (sigstop) {
205         kill(getpid(), SIGSTOP);
206     }
207 
208     return execv(c_strings[0], c_strings.data()) == 0;
209 }
210 
IsRuntimeApexReady()211 static bool IsRuntimeApexReady() {
212     struct stat buf;
213     return stat("/apex/com.android.runtime/", &buf) == 0;
214 }
215 
216 unsigned long Service::next_start_order_ = 1;
217 bool Service::is_exec_service_running_ = false;
218 
Service(const std::string & name,Subcontext * subcontext_for_restart_commands,const std::vector<std::string> & args)219 Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
220                  const std::vector<std::string>& args)
221     : Service(name, 0, 0, 0, {}, 0, "", subcontext_for_restart_commands, args) {}
222 
Service(const std::string & name,unsigned flags,uid_t uid,gid_t gid,const std::vector<gid_t> & supp_gids,unsigned namespace_flags,const std::string & seclabel,Subcontext * subcontext_for_restart_commands,const std::vector<std::string> & args)223 Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
224                  const std::vector<gid_t>& supp_gids, unsigned namespace_flags,
225                  const std::string& seclabel, Subcontext* subcontext_for_restart_commands,
226                  const std::vector<std::string>& args)
227     : name_(name),
228       classnames_({"default"}),
229       flags_(flags),
230       pid_(0),
231       crash_count_(0),
232       uid_(uid),
233       gid_(gid),
234       supp_gids_(supp_gids),
235       namespace_flags_(namespace_flags),
236       seclabel_(seclabel),
237       onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0,
238                  "onrestart", {}),
239       ioprio_class_(IoSchedClass_NONE),
240       ioprio_pri_(0),
241       priority_(0),
242       oom_score_adjust_(-1000),
243       start_order_(0),
244       args_(args) {}
245 
NotifyStateChange(const std::string & new_state) const246 void Service::NotifyStateChange(const std::string& new_state) const {
247     if ((flags_ & SVC_TEMPORARY) != 0) {
248         // Services created by 'exec' are temporary and don't have properties tracking their state.
249         return;
250     }
251 
252     std::string prop_name = "init.svc." + name_;
253     property_set(prop_name, new_state);
254 
255     if (new_state == "running") {
256         uint64_t start_ns = time_started_.time_since_epoch().count();
257         std::string boottime_property = "ro.boottime." + name_;
258         if (GetProperty(boottime_property, "").empty()) {
259             property_set(boottime_property, std::to_string(start_ns));
260         }
261     }
262 }
263 
KillProcessGroup(int signal)264 void Service::KillProcessGroup(int signal) {
265     // If we've already seen a successful result from killProcessGroup*(), then we have removed
266     // the cgroup already and calling these functions a second time will simply result in an error.
267     // This is true regardless of which signal was sent.
268     // These functions handle their own logging, so no additional logging is needed.
269     if (!process_cgroup_empty_) {
270         LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
271                   << ") process group...";
272         int r;
273         if (signal == SIGTERM) {
274             r = killProcessGroupOnce(uid_, pid_, signal);
275         } else {
276             r = killProcessGroup(uid_, pid_, signal);
277         }
278 
279         if (r == 0) process_cgroup_empty_ = true;
280     }
281 }
282 
SetProcessAttributes()283 void Service::SetProcessAttributes() {
284     for (const auto& rlimit : rlimits_) {
285         if (setrlimit(rlimit.first, &rlimit.second) == -1) {
286             LOG(FATAL) << StringPrintf("setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed",
287                                        rlimit.first, rlimit.second.rlim_cur, rlimit.second.rlim_max);
288         }
289     }
290     // Keep capabilites on uid change.
291     if (capabilities_ && uid_) {
292         // If Android is running in a container, some securebits might already
293         // be locked, so don't change those.
294         unsigned long securebits = prctl(PR_GET_SECUREBITS);
295         if (securebits == -1UL) {
296             PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
297         }
298         securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
299         if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
300             PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
301         }
302     }
303 
304     // TODO: work out why this fails for `console` then upgrade to FATAL.
305     if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_;
306 
307     if (gid_) {
308         if (setgid(gid_) != 0) {
309             PLOG(FATAL) << "setgid failed for " << name_;
310         }
311     }
312     if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
313         PLOG(FATAL) << "setgroups failed for " << name_;
314     }
315     if (uid_) {
316         if (setuid(uid_) != 0) {
317             PLOG(FATAL) << "setuid failed for " << name_;
318         }
319     }
320     if (!seclabel_.empty()) {
321         if (setexeccon(seclabel_.c_str()) < 0) {
322             PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
323         }
324     }
325     if (priority_ != 0) {
326         if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
327             PLOG(FATAL) << "setpriority failed for " << name_;
328         }
329     }
330     if (capabilities_) {
331         if (!SetCapsForExec(*capabilities_)) {
332             LOG(FATAL) << "cannot set capabilities for " << name_;
333         }
334     } else if (uid_) {
335         // Inheritable caps can be non-zero when running in a container.
336         if (!DropInheritableCaps()) {
337             LOG(FATAL) << "cannot drop inheritable caps for " << name_;
338         }
339     }
340 }
341 
Reap(const siginfo_t & siginfo)342 void Service::Reap(const siginfo_t& siginfo) {
343     if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
344         KillProcessGroup(SIGKILL);
345     }
346 
347     // Remove any descriptor resources we may have created.
348     std::for_each(descriptors_.begin(), descriptors_.end(),
349                   std::bind(&DescriptorInfo::Clean, std::placeholders::_1));
350 
351     for (const auto& f : reap_callbacks_) {
352         f(siginfo);
353     }
354 
355     if (flags_ & SVC_EXEC) UnSetExec();
356 
357     if (flags_ & SVC_TEMPORARY) return;
358 
359     pid_ = 0;
360     flags_ &= (~SVC_RUNNING);
361     start_order_ = 0;
362 
363     // Oneshot processes go into the disabled state on exit,
364     // except when manually restarted.
365     if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART) && !(flags_ & SVC_RESET)) {
366         flags_ |= SVC_DISABLED;
367     }
368 
369     // Disabled and reset processes do not get restarted automatically.
370     if (flags_ & (SVC_DISABLED | SVC_RESET))  {
371         NotifyStateChange("stopped");
372         return;
373     }
374 
375     // If we crash > 4 times in 4 minutes or before boot_completed,
376     // reboot into bootloader or set crashing property
377     boot_clock::time_point now = boot_clock::now();
378     if (((flags_ & SVC_CRITICAL) || !pre_apexd_) && !(flags_ & SVC_RESTART)) {
379         bool boot_completed = android::base::GetBoolProperty("sys.boot_completed", false);
380         if (now < time_crashed_ + 4min || !boot_completed) {
381             if (++crash_count_ > 4) {
382                 if (flags_ & SVC_CRITICAL) {
383                     // Aborts into bootloader
384                     LOG(FATAL) << "critical process '" << name_ << "' exited 4 times "
385                                << (boot_completed ? "in 4 minutes" : "before boot completed");
386                 } else {
387                     LOG(ERROR) << "updatable process '" << name_ << "' exited 4 times "
388                                << (boot_completed ? "in 4 minutes" : "before boot completed");
389                     // Notifies update_verifier and apexd
390                     property_set("ro.init.updatable_crashing", "1");
391                 }
392             }
393         } else {
394             time_crashed_ = now;
395             crash_count_ = 1;
396         }
397     }
398 
399     flags_ &= (~SVC_RESTART);
400     flags_ |= SVC_RESTARTING;
401 
402     // Execute all onrestart commands for this service.
403     onrestart_.ExecuteAllCommands();
404 
405     NotifyStateChange("restarting");
406     return;
407 }
408 
DumpState() const409 void Service::DumpState() const {
410     LOG(INFO) << "service " << name_;
411     LOG(INFO) << "  class '" << Join(classnames_, " ") << "'";
412     LOG(INFO) << "  exec " << Join(args_, " ");
413     std::for_each(descriptors_.begin(), descriptors_.end(),
414                   [] (const auto& info) { LOG(INFO) << *info; });
415 }
416 
ParseCapabilities(std::vector<std::string> && args)417 Result<Success> Service::ParseCapabilities(std::vector<std::string>&& args) {
418     capabilities_ = 0;
419 
420     if (!CapAmbientSupported()) {
421         return Error()
422                << "capabilities requested but the kernel does not support ambient capabilities";
423     }
424 
425     unsigned int last_valid_cap = GetLastValidCap();
426     if (last_valid_cap >= capabilities_->size()) {
427         LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
428     }
429 
430     for (size_t i = 1; i < args.size(); i++) {
431         const std::string& arg = args[i];
432         int res = LookupCap(arg);
433         if (res < 0) {
434             return Error() << StringPrintf("invalid capability '%s'", arg.c_str());
435         }
436         unsigned int cap = static_cast<unsigned int>(res);  // |res| is >= 0.
437         if (cap > last_valid_cap) {
438             return Error() << StringPrintf("capability '%s' not supported by the kernel",
439                                            arg.c_str());
440         }
441         (*capabilities_)[cap] = true;
442     }
443     return Success();
444 }
445 
ParseClass(std::vector<std::string> && args)446 Result<Success> Service::ParseClass(std::vector<std::string>&& args) {
447     classnames_ = std::set<std::string>(args.begin() + 1, args.end());
448     return Success();
449 }
450 
ParseConsole(std::vector<std::string> && args)451 Result<Success> Service::ParseConsole(std::vector<std::string>&& args) {
452     flags_ |= SVC_CONSOLE;
453     console_ = args.size() > 1 ? "/dev/" + args[1] : "";
454     return Success();
455 }
456 
ParseCritical(std::vector<std::string> && args)457 Result<Success> Service::ParseCritical(std::vector<std::string>&& args) {
458     flags_ |= SVC_CRITICAL;
459     return Success();
460 }
461 
ParseDisabled(std::vector<std::string> && args)462 Result<Success> Service::ParseDisabled(std::vector<std::string>&& args) {
463     flags_ |= SVC_DISABLED;
464     flags_ |= SVC_RC_DISABLED;
465     return Success();
466 }
467 
ParseEnterNamespace(std::vector<std::string> && args)468 Result<Success> Service::ParseEnterNamespace(std::vector<std::string>&& args) {
469     if (args[1] != "net") {
470         return Error() << "Init only supports entering network namespaces";
471     }
472     if (!namespaces_to_enter_.empty()) {
473         return Error() << "Only one network namespace may be entered";
474     }
475     // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
476     // present. Therefore, they also require mount namespaces.
477     namespace_flags_ |= CLONE_NEWNS;
478     namespaces_to_enter_.emplace_back(CLONE_NEWNET, std::move(args[2]));
479     return Success();
480 }
481 
ParseGroup(std::vector<std::string> && args)482 Result<Success> Service::ParseGroup(std::vector<std::string>&& args) {
483     auto gid = DecodeUid(args[1]);
484     if (!gid) {
485         return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
486     }
487     gid_ = *gid;
488 
489     for (std::size_t n = 2; n < args.size(); n++) {
490         gid = DecodeUid(args[n]);
491         if (!gid) {
492             return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
493         }
494         supp_gids_.emplace_back(*gid);
495     }
496     return Success();
497 }
498 
ParsePriority(std::vector<std::string> && args)499 Result<Success> Service::ParsePriority(std::vector<std::string>&& args) {
500     priority_ = 0;
501     if (!ParseInt(args[1], &priority_,
502                   static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
503                   static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
504         return Error() << StringPrintf("process priority value must be range %d - %d",
505                                        ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
506     }
507     return Success();
508 }
509 
ParseInterface(std::vector<std::string> && args)510 Result<Success> Service::ParseInterface(std::vector<std::string>&& args) {
511     const std::string& interface_name = args[1];
512     const std::string& instance_name = args[2];
513 
514     FQName fq_name;
515     if (!FQName::parse(interface_name, &fq_name)) {
516         return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
517     }
518 
519     if (!fq_name.isFullyQualified()) {
520         return Error() << "Interface name not fully-qualified '" << interface_name << "'";
521     }
522 
523     if (fq_name.isValidValueName()) {
524         return Error() << "Interface name must not be a value name '" << interface_name << "'";
525     }
526 
527     const std::string fullname = interface_name + "/" + instance_name;
528 
529     for (const auto& svc : ServiceList::GetInstance()) {
530         if (svc->interfaces().count(fullname) > 0) {
531             return Error() << "Interface '" << fullname << "' redefined in " << name()
532                            << " but is already defined by " << svc->name();
533         }
534     }
535 
536     interfaces_.insert(fullname);
537 
538     return Success();
539 }
540 
ParseIoprio(std::vector<std::string> && args)541 Result<Success> Service::ParseIoprio(std::vector<std::string>&& args) {
542     if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) {
543         return Error() << "priority value must be range 0 - 7";
544     }
545 
546     if (args[1] == "rt") {
547         ioprio_class_ = IoSchedClass_RT;
548     } else if (args[1] == "be") {
549         ioprio_class_ = IoSchedClass_BE;
550     } else if (args[1] == "idle") {
551         ioprio_class_ = IoSchedClass_IDLE;
552     } else {
553         return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
554     }
555 
556     return Success();
557 }
558 
ParseKeycodes(std::vector<std::string> && args)559 Result<Success> Service::ParseKeycodes(std::vector<std::string>&& args) {
560     auto it = args.begin() + 1;
561     if (args.size() == 2 && StartsWith(args[1], "$")) {
562         std::string expanded;
563         if (!expand_props(args[1], &expanded)) {
564             return Error() << "Could not expand property '" << args[1] << "'";
565         }
566 
567         // If the property is not set, it defaults to none, in which case there are no keycodes
568         // for this service.
569         if (expanded == "none") {
570             return Success();
571         }
572 
573         args = Split(expanded, ",");
574         it = args.begin();
575     }
576 
577     for (; it != args.end(); ++it) {
578         int code;
579         if (ParseInt(*it, &code, 0, KEY_MAX)) {
580             for (auto& key : keycodes_) {
581                 if (key == code) return Error() << "duplicate keycode: " << *it;
582             }
583             keycodes_.insert(std::upper_bound(keycodes_.begin(), keycodes_.end(), code), code);
584         } else {
585             return Error() << "invalid keycode: " << *it;
586         }
587     }
588     return Success();
589 }
590 
ParseOneshot(std::vector<std::string> && args)591 Result<Success> Service::ParseOneshot(std::vector<std::string>&& args) {
592     flags_ |= SVC_ONESHOT;
593     return Success();
594 }
595 
ParseOnrestart(std::vector<std::string> && args)596 Result<Success> Service::ParseOnrestart(std::vector<std::string>&& args) {
597     args.erase(args.begin());
598     int line = onrestart_.NumCommands() + 1;
599     if (auto result = onrestart_.AddCommand(std::move(args), line); !result) {
600         return Error() << "cannot add Onrestart command: " << result.error();
601     }
602     return Success();
603 }
604 
ParseNamespace(std::vector<std::string> && args)605 Result<Success> Service::ParseNamespace(std::vector<std::string>&& args) {
606     for (size_t i = 1; i < args.size(); i++) {
607         if (args[i] == "pid") {
608             namespace_flags_ |= CLONE_NEWPID;
609             // PID namespaces require mount namespaces.
610             namespace_flags_ |= CLONE_NEWNS;
611         } else if (args[i] == "mnt") {
612             namespace_flags_ |= CLONE_NEWNS;
613         } else {
614             return Error() << "namespace must be 'pid' or 'mnt'";
615         }
616     }
617     return Success();
618 }
619 
ParseOomScoreAdjust(std::vector<std::string> && args)620 Result<Success> Service::ParseOomScoreAdjust(std::vector<std::string>&& args) {
621     if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
622         return Error() << "oom_score_adjust value must be in range -1000 - +1000";
623     }
624     return Success();
625 }
626 
ParseOverride(std::vector<std::string> && args)627 Result<Success> Service::ParseOverride(std::vector<std::string>&& args) {
628     override_ = true;
629     return Success();
630 }
631 
ParseMemcgSwappiness(std::vector<std::string> && args)632 Result<Success> Service::ParseMemcgSwappiness(std::vector<std::string>&& args) {
633     if (!ParseInt(args[1], &swappiness_, 0)) {
634         return Error() << "swappiness value must be equal or greater than 0";
635     }
636     return Success();
637 }
638 
ParseMemcgLimitInBytes(std::vector<std::string> && args)639 Result<Success> Service::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
640     if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
641         return Error() << "limit_in_bytes value must be equal or greater than 0";
642     }
643     return Success();
644 }
645 
ParseMemcgLimitPercent(std::vector<std::string> && args)646 Result<Success> Service::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
647     if (!ParseInt(args[1], &limit_percent_, 0)) {
648         return Error() << "limit_percent value must be equal or greater than 0";
649     }
650     return Success();
651 }
652 
ParseMemcgLimitProperty(std::vector<std::string> && args)653 Result<Success> Service::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
654     limit_property_ = std::move(args[1]);
655     return Success();
656 }
657 
ParseMemcgSoftLimitInBytes(std::vector<std::string> && args)658 Result<Success> Service::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
659     if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
660         return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
661     }
662     return Success();
663 }
664 
ParseProcessRlimit(std::vector<std::string> && args)665 Result<Success> Service::ParseProcessRlimit(std::vector<std::string>&& args) {
666     auto rlimit = ParseRlimit(args);
667     if (!rlimit) return rlimit.error();
668 
669     rlimits_.emplace_back(*rlimit);
670     return Success();
671 }
672 
ParseRestartPeriod(std::vector<std::string> && args)673 Result<Success> Service::ParseRestartPeriod(std::vector<std::string>&& args) {
674     int period;
675     if (!ParseInt(args[1], &period, 5)) {
676         return Error() << "restart_period value must be an integer >= 5";
677     }
678     restart_period_ = std::chrono::seconds(period);
679     return Success();
680 }
681 
ParseSeclabel(std::vector<std::string> && args)682 Result<Success> Service::ParseSeclabel(std::vector<std::string>&& args) {
683     seclabel_ = std::move(args[1]);
684     return Success();
685 }
686 
ParseSigstop(std::vector<std::string> && args)687 Result<Success> Service::ParseSigstop(std::vector<std::string>&& args) {
688     sigstop_ = true;
689     return Success();
690 }
691 
ParseSetenv(std::vector<std::string> && args)692 Result<Success> Service::ParseSetenv(std::vector<std::string>&& args) {
693     environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
694     return Success();
695 }
696 
ParseShutdown(std::vector<std::string> && args)697 Result<Success> Service::ParseShutdown(std::vector<std::string>&& args) {
698     if (args[1] == "critical") {
699         flags_ |= SVC_SHUTDOWN_CRITICAL;
700         return Success();
701     }
702     return Error() << "Invalid shutdown option";
703 }
704 
ParseTimeoutPeriod(std::vector<std::string> && args)705 Result<Success> Service::ParseTimeoutPeriod(std::vector<std::string>&& args) {
706     int period;
707     if (!ParseInt(args[1], &period, 1)) {
708         return Error() << "timeout_period value must be an integer >= 1";
709     }
710     timeout_period_ = std::chrono::seconds(period);
711     return Success();
712 }
713 
714 template <typename T>
AddDescriptor(std::vector<std::string> && args)715 Result<Success> Service::AddDescriptor(std::vector<std::string>&& args) {
716     int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
717     Result<uid_t> uid = 0;
718     Result<gid_t> gid = 0;
719     std::string context = args.size() > 6 ? args[6] : "";
720 
721     if (args.size() > 4) {
722         uid = DecodeUid(args[4]);
723         if (!uid) {
724             return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
725         }
726     }
727 
728     if (args.size() > 5) {
729         gid = DecodeUid(args[5]);
730         if (!gid) {
731             return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
732         }
733     }
734 
735     auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
736 
737     auto old =
738         std::find_if(descriptors_.begin(), descriptors_.end(),
739                      [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
740 
741     if (old != descriptors_.end()) {
742         return Error() << "duplicate descriptor " << args[1] << " " << args[2];
743     }
744 
745     descriptors_.emplace_back(std::move(descriptor));
746     return Success();
747 }
748 
749 // name type perm [ uid gid context ]
ParseSocket(std::vector<std::string> && args)750 Result<Success> Service::ParseSocket(std::vector<std::string>&& args) {
751     if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
752         !StartsWith(args[2], "seqpacket")) {
753         return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
754     }
755     return AddDescriptor<SocketInfo>(std::move(args));
756 }
757 
758 // name type perm [ uid gid context ]
ParseFile(std::vector<std::string> && args)759 Result<Success> Service::ParseFile(std::vector<std::string>&& args) {
760     if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
761         return Error() << "file type must be 'r', 'w' or 'rw'";
762     }
763     std::string expanded;
764     if (!expand_props(args[1], &expanded)) {
765         return Error() << "Could not expand property in file path '" << args[1] << "'";
766     }
767     args[1] = std::move(expanded);
768     if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
769         return Error() << "file name must not be relative";
770     }
771     return AddDescriptor<FileInfo>(std::move(args));
772 }
773 
ParseUser(std::vector<std::string> && args)774 Result<Success> Service::ParseUser(std::vector<std::string>&& args) {
775     auto uid = DecodeUid(args[1]);
776     if (!uid) {
777         return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
778     }
779     uid_ = *uid;
780     return Success();
781 }
782 
ParseWritepid(std::vector<std::string> && args)783 Result<Success> Service::ParseWritepid(std::vector<std::string>&& args) {
784     args.erase(args.begin());
785     writepid_files_ = std::move(args);
786     return Success();
787 }
788 
ParseUpdatable(std::vector<std::string> && args)789 Result<Success> Service::ParseUpdatable(std::vector<std::string>&& args) {
790     updatable_ = true;
791     return Success();
792 }
793 
794 class Service::OptionParserMap : public KeywordMap<OptionParser> {
795   public:
OptionParserMap()796     OptionParserMap() {}
797 
798   private:
799     const Map& map() const override;
800 };
801 
map() const802 const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
803     constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
804     // clang-format off
805     static const Map option_parsers = {
806         {"capabilities",
807                         {0,     kMax, &Service::ParseCapabilities}},
808         {"class",       {1,     kMax, &Service::ParseClass}},
809         {"console",     {0,     1,    &Service::ParseConsole}},
810         {"critical",    {0,     0,    &Service::ParseCritical}},
811         {"disabled",    {0,     0,    &Service::ParseDisabled}},
812         {"enter_namespace",
813                         {2,     2,    &Service::ParseEnterNamespace}},
814         {"file",        {2,     2,    &Service::ParseFile}},
815         {"group",       {1,     NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
816         {"interface",   {2,     2,    &Service::ParseInterface}},
817         {"ioprio",      {2,     2,    &Service::ParseIoprio}},
818         {"keycodes",    {1,     kMax, &Service::ParseKeycodes}},
819         {"memcg.limit_in_bytes",
820                         {1,     1,    &Service::ParseMemcgLimitInBytes}},
821         {"memcg.limit_percent",
822                         {1,     1,    &Service::ParseMemcgLimitPercent}},
823         {"memcg.limit_property",
824                         {1,     1,    &Service::ParseMemcgLimitProperty}},
825         {"memcg.soft_limit_in_bytes",
826                         {1,     1,    &Service::ParseMemcgSoftLimitInBytes}},
827         {"memcg.swappiness",
828                         {1,     1,    &Service::ParseMemcgSwappiness}},
829         {"namespace",   {1,     2,    &Service::ParseNamespace}},
830         {"oneshot",     {0,     0,    &Service::ParseOneshot}},
831         {"onrestart",   {1,     kMax, &Service::ParseOnrestart}},
832         {"oom_score_adjust",
833                         {1,     1,    &Service::ParseOomScoreAdjust}},
834         {"override",    {0,     0,    &Service::ParseOverride}},
835         {"priority",    {1,     1,    &Service::ParsePriority}},
836         {"restart_period",
837                         {1,     1,    &Service::ParseRestartPeriod}},
838         {"rlimit",      {3,     3,    &Service::ParseProcessRlimit}},
839         {"seclabel",    {1,     1,    &Service::ParseSeclabel}},
840         {"setenv",      {2,     2,    &Service::ParseSetenv}},
841         {"shutdown",    {1,     1,    &Service::ParseShutdown}},
842         {"sigstop",     {0,     0,    &Service::ParseSigstop}},
843         {"socket",      {3,     6,    &Service::ParseSocket}},
844         {"timeout_period",
845                         {1,     1,    &Service::ParseTimeoutPeriod}},
846         {"updatable",   {0,     0,    &Service::ParseUpdatable}},
847         {"user",        {1,     1,    &Service::ParseUser}},
848         {"writepid",    {1,     kMax, &Service::ParseWritepid}},
849     };
850     // clang-format on
851     return option_parsers;
852 }
853 
ParseLine(std::vector<std::string> && args)854 Result<Success> Service::ParseLine(std::vector<std::string>&& args) {
855     static const OptionParserMap parser_map;
856     auto parser = parser_map.FindFunction(args);
857 
858     if (!parser) return parser.error();
859 
860     return std::invoke(*parser, this, std::move(args));
861 }
862 
ExecStart()863 Result<Success> Service::ExecStart() {
864     if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
865         // Don't delay the service for ExecStart() as the semantic is that
866         // the caller might depend on the side effect of the execution.
867         return Error() << "Cannot start an updatable service '" << name_
868                        << "' before configs from APEXes are all loaded";
869     }
870 
871     flags_ |= SVC_ONESHOT;
872 
873     if (auto result = Start(); !result) {
874         return result;
875     }
876 
877     flags_ |= SVC_EXEC;
878     is_exec_service_running_ = true;
879 
880     LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << uid_ << " gid "
881               << gid_ << "+" << supp_gids_.size() << " context "
882               << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
883 
884     return Success();
885 }
886 
Start()887 Result<Success> Service::Start() {
888     if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
889         ServiceList::GetInstance().DelayService(*this);
890         return Error() << "Cannot start an updatable service '" << name_
891                        << "' before configs from APEXes are all loaded. "
892                        << "Queued for execution.";
893     }
894 
895     bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
896     // Starting a service removes it from the disabled or reset state and
897     // immediately takes it out of the restarting state if it was in there.
898     flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
899 
900     // Running processes require no additional work --- if they're in the
901     // process of exiting, we've ensured that they will immediately restart
902     // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
903     // stopping status, we just set SVC_RESTART flag so it will get restarted
904     // in Reap().
905     if (flags_ & SVC_RUNNING) {
906         if ((flags_ & SVC_ONESHOT) && disabled) {
907             flags_ |= SVC_RESTART;
908         }
909         // It is not an error to try to start a service that is already running.
910         return Success();
911     }
912 
913     bool needs_console = (flags_ & SVC_CONSOLE);
914     if (needs_console) {
915         if (console_.empty()) {
916             console_ = default_console;
917         }
918 
919         // Make sure that open call succeeds to ensure a console driver is
920         // properly registered for the device node
921         int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC);
922         if (console_fd < 0) {
923             flags_ |= SVC_DISABLED;
924             return ErrnoError() << "Couldn't open console '" << console_ << "'";
925         }
926         close(console_fd);
927     }
928 
929     struct stat sb;
930     if (stat(args_[0].c_str(), &sb) == -1) {
931         flags_ |= SVC_DISABLED;
932         return ErrnoError() << "Cannot find '" << args_[0] << "'";
933     }
934 
935     std::string scon;
936     if (!seclabel_.empty()) {
937         scon = seclabel_;
938     } else {
939         auto result = ComputeContextFromExecutable(args_[0]);
940         if (!result) {
941             return result.error();
942         }
943         scon = *result;
944     }
945 
946     if (!IsRuntimeApexReady() && !pre_apexd_) {
947         // If this service is started before the runtime APEX gets available,
948         // mark it as pre-apexd one. Note that this marking is permanent. So
949         // for example, if the service is re-launched (e.g., due to crash),
950         // it is still recognized as pre-apexd... for consistency.
951         pre_apexd_ = true;
952     }
953 
954     post_data_ = ServiceList::GetInstance().IsPostData();
955 
956     LOG(INFO) << "starting service '" << name_ << "'...";
957 
958     pid_t pid = -1;
959     if (namespace_flags_) {
960         pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr);
961     } else {
962         pid = fork();
963     }
964 
965     if (pid == 0) {
966         umask(077);
967 
968         if (auto result = EnterNamespaces(); !result) {
969             LOG(FATAL) << "Service '" << name_ << "' could not enter namespaces: " << result.error();
970         }
971 
972 #if defined(__ANDROID__)
973         if (pre_apexd_) {
974             if (!SwitchToBootstrapMountNamespaceIfNeeded()) {
975                 LOG(FATAL) << "Service '" << name_ << "' could not enter "
976                            << "into the bootstrap mount namespace";
977             }
978         }
979 #endif
980 
981         if (namespace_flags_ & CLONE_NEWNS) {
982             if (auto result = SetUpMountNamespace(); !result) {
983                 LOG(FATAL) << "Service '" << name_
984                            << "' could not set up mount namespace: " << result.error();
985             }
986         }
987 
988         if (namespace_flags_ & CLONE_NEWPID) {
989             // This will fork again to run an init process inside the PID
990             // namespace.
991             if (auto result = SetUpPidNamespace(); !result) {
992                 LOG(FATAL) << "Service '" << name_
993                            << "' could not set up PID namespace: " << result.error();
994             }
995         }
996 
997         for (const auto& [key, value] : environment_vars_) {
998             setenv(key.c_str(), value.c_str(), 1);
999         }
1000 
1001         std::for_each(descriptors_.begin(), descriptors_.end(),
1002                       std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon));
1003 
1004         // See if there were "writepid" instructions to write to files under cpuset path.
1005         std::string cpuset_path;
1006         if (CgroupGetControllerPath("cpuset", &cpuset_path)) {
1007             auto cpuset_predicate = [&cpuset_path](const std::string& path) {
1008                 return StartsWith(path, cpuset_path + "/");
1009             };
1010             auto iter =
1011                     std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate);
1012             if (iter == writepid_files_.end()) {
1013                 // There were no "writepid" instructions for cpusets, check if the system default
1014                 // cpuset is specified to be used for the process.
1015                 std::string default_cpuset = GetProperty("ro.cpuset.default", "");
1016                 if (!default_cpuset.empty()) {
1017                     // Make sure the cpuset name starts and ends with '/'.
1018                     // A single '/' means the 'root' cpuset.
1019                     if (default_cpuset.front() != '/') {
1020                         default_cpuset.insert(0, 1, '/');
1021                     }
1022                     if (default_cpuset.back() != '/') {
1023                         default_cpuset.push_back('/');
1024                     }
1025                     writepid_files_.push_back(
1026                             StringPrintf("%s%stasks", cpuset_path.c_str(), default_cpuset.c_str()));
1027                 }
1028             }
1029         } else {
1030             LOG(ERROR) << "cpuset cgroup controller is not mounted!";
1031         }
1032         std::string pid_str = std::to_string(getpid());
1033         for (const auto& file : writepid_files_) {
1034             if (!WriteStringToFile(pid_str, file)) {
1035                 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file;
1036             }
1037         }
1038 
1039         if (ioprio_class_ != IoSchedClass_NONE) {
1040             if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
1041                 PLOG(ERROR) << "failed to set pid " << getpid()
1042                             << " ioprio=" << ioprio_class_ << "," << ioprio_pri_;
1043             }
1044         }
1045 
1046         if (needs_console) {
1047             setsid();
1048             OpenConsole();
1049         } else {
1050             ZapStdio();
1051         }
1052 
1053         // As requested, set our gid, supplemental gids, uid, context, and
1054         // priority. Aborts on failure.
1055         SetProcessAttributes();
1056 
1057         if (!ExpandArgsAndExecv(args_, sigstop_)) {
1058             PLOG(ERROR) << "cannot execve('" << args_[0] << "')";
1059         }
1060 
1061         _exit(127);
1062     }
1063 
1064     if (pid < 0) {
1065         pid_ = 0;
1066         return ErrnoError() << "Failed to fork";
1067     }
1068 
1069     if (oom_score_adjust_ != -1000) {
1070         std::string oom_str = std::to_string(oom_score_adjust_);
1071         std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
1072         if (!WriteStringToFile(oom_str, oom_file)) {
1073             PLOG(ERROR) << "couldn't write oom_score_adj";
1074         }
1075     }
1076 
1077     time_started_ = boot_clock::now();
1078     pid_ = pid;
1079     flags_ |= SVC_RUNNING;
1080     start_order_ = next_start_order_++;
1081     process_cgroup_empty_ = false;
1082 
1083     bool use_memcg = swappiness_ != -1 || soft_limit_in_bytes_ != -1 || limit_in_bytes_ != -1 ||
1084                       limit_percent_ != -1 || !limit_property_.empty();
1085     errno = -createProcessGroup(uid_, pid_, use_memcg);
1086     if (errno != 0) {
1087         PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '"
1088                     << name_ << "'";
1089     } else if (use_memcg) {
1090         if (swappiness_ != -1) {
1091             if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) {
1092                 PLOG(ERROR) << "setProcessGroupSwappiness failed";
1093             }
1094         }
1095 
1096         if (soft_limit_in_bytes_ != -1) {
1097             if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) {
1098                 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
1099             }
1100         }
1101 
1102         size_t computed_limit_in_bytes = limit_in_bytes_;
1103         if (limit_percent_ != -1) {
1104             long page_size = sysconf(_SC_PAGESIZE);
1105             long num_pages = sysconf(_SC_PHYS_PAGES);
1106             if (page_size > 0 && num_pages > 0) {
1107                 size_t max_mem = SIZE_MAX;
1108                 if (size_t(num_pages) < SIZE_MAX / size_t(page_size)) {
1109                     max_mem = size_t(num_pages) * size_t(page_size);
1110                 }
1111                 computed_limit_in_bytes =
1112                         std::min(computed_limit_in_bytes, max_mem / 100 * limit_percent_);
1113             }
1114         }
1115 
1116         if (!limit_property_.empty()) {
1117             // This ends up overwriting computed_limit_in_bytes but only if the
1118             // property is defined.
1119             computed_limit_in_bytes = android::base::GetUintProperty(
1120                     limit_property_, computed_limit_in_bytes, SIZE_MAX);
1121         }
1122 
1123         if (computed_limit_in_bytes != size_t(-1)) {
1124             if (!setProcessGroupLimit(uid_, pid_, computed_limit_in_bytes)) {
1125                 PLOG(ERROR) << "setProcessGroupLimit failed";
1126             }
1127         }
1128     }
1129 
1130     NotifyStateChange("running");
1131     return Success();
1132 }
1133 
StartIfNotDisabled()1134 Result<Success> Service::StartIfNotDisabled() {
1135     if (!(flags_ & SVC_DISABLED)) {
1136         return Start();
1137     } else {
1138         flags_ |= SVC_DISABLED_START;
1139     }
1140     return Success();
1141 }
1142 
Enable()1143 Result<Success> Service::Enable() {
1144     flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
1145     if (flags_ & SVC_DISABLED_START) {
1146         return Start();
1147     }
1148     return Success();
1149 }
1150 
Reset()1151 void Service::Reset() {
1152     StopOrReset(SVC_RESET);
1153 }
1154 
ResetIfPostData()1155 void Service::ResetIfPostData() {
1156     if (post_data_) {
1157         if (flags_ & SVC_RUNNING) {
1158             running_at_post_data_reset_ = true;
1159         }
1160         StopOrReset(SVC_RESET);
1161     }
1162 }
1163 
StartIfPostData()1164 Result<Success> Service::StartIfPostData() {
1165     // Start the service, but only if it was started after /data was mounted,
1166     // and it was still running when we reset the post-data services.
1167     if (running_at_post_data_reset_) {
1168         return Start();
1169     }
1170 
1171     return Success();
1172 }
1173 
Stop()1174 void Service::Stop() {
1175     StopOrReset(SVC_DISABLED);
1176 }
1177 
Terminate()1178 void Service::Terminate() {
1179     flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1180     flags_ |= SVC_DISABLED;
1181     if (pid_) {
1182         KillProcessGroup(SIGTERM);
1183         NotifyStateChange("stopping");
1184     }
1185 }
1186 
Timeout()1187 void Service::Timeout() {
1188     // All process state flags will be taken care of in Reap(), we really just want to kill the
1189     // process here when it times out.  Oneshot processes will transition to be disabled, and
1190     // all other processes will transition to be restarting.
1191     LOG(INFO) << "Service '" << name_ << "' expired its timeout of " << timeout_period_->count()
1192               << " seconds and will now be killed";
1193     if (pid_) {
1194         KillProcessGroup(SIGKILL);
1195         NotifyStateChange("stopping");
1196     }
1197 }
1198 
Restart()1199 void Service::Restart() {
1200     if (flags_ & SVC_RUNNING) {
1201         /* Stop, wait, then start the service. */
1202         StopOrReset(SVC_RESTART);
1203     } else if (!(flags_ & SVC_RESTARTING)) {
1204         /* Just start the service since it's not running. */
1205         if (auto result = Start(); !result) {
1206             LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
1207         }
1208     } /* else: Service is restarting anyways. */
1209 }
1210 
1211 // The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
StopOrReset(int how)1212 void Service::StopOrReset(int how) {
1213     // The service is still SVC_RUNNING until its process exits, but if it has
1214     // already exited it shoudn't attempt a restart yet.
1215     flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
1216 
1217     if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
1218         // An illegal flag: default to SVC_DISABLED.
1219         how = SVC_DISABLED;
1220     }
1221 
1222     // If the service has not yet started, prevent it from auto-starting with its class.
1223     if (how == SVC_RESET) {
1224         flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
1225     } else {
1226         flags_ |= how;
1227     }
1228     // Make sure it's in right status when a restart immediately follow a
1229     // stop/reset or vice versa.
1230     if (how == SVC_RESTART) {
1231         flags_ &= (~(SVC_DISABLED | SVC_RESET));
1232     } else {
1233         flags_ &= (~SVC_RESTART);
1234     }
1235 
1236     if (pid_) {
1237         KillProcessGroup(SIGKILL);
1238         NotifyStateChange("stopping");
1239     } else {
1240         NotifyStateChange("stopped");
1241     }
1242 }
1243 
ZapStdio() const1244 void Service::ZapStdio() const {
1245     int fd;
1246     fd = open("/dev/null", O_RDWR);
1247     dup2(fd, 0);
1248     dup2(fd, 1);
1249     dup2(fd, 2);
1250     close(fd);
1251 }
1252 
OpenConsole() const1253 void Service::OpenConsole() const {
1254     int fd = open(console_.c_str(), O_RDWR);
1255     if (fd == -1) fd = open("/dev/null", O_RDWR);
1256     ioctl(fd, TIOCSCTTY, 0);
1257     dup2(fd, 0);
1258     dup2(fd, 1);
1259     dup2(fd, 2);
1260     close(fd);
1261 }
1262 
ServiceList()1263 ServiceList::ServiceList() {}
1264 
GetInstance()1265 ServiceList& ServiceList::GetInstance() {
1266     static ServiceList instance;
1267     return instance;
1268 }
1269 
AddService(std::unique_ptr<Service> service)1270 void ServiceList::AddService(std::unique_ptr<Service> service) {
1271     services_.emplace_back(std::move(service));
1272 }
1273 
MakeTemporaryOneshotService(const std::vector<std::string> & args)1274 std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
1275     // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
1276     // SECLABEL can be a - to denote default
1277     std::size_t command_arg = 1;
1278     for (std::size_t i = 1; i < args.size(); ++i) {
1279         if (args[i] == "--") {
1280             command_arg = i + 1;
1281             break;
1282         }
1283     }
1284     if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
1285         LOG(ERROR) << "exec called with too many supplementary group ids";
1286         return nullptr;
1287     }
1288 
1289     if (command_arg >= args.size()) {
1290         LOG(ERROR) << "exec called without command";
1291         return nullptr;
1292     }
1293     std::vector<std::string> str_args(args.begin() + command_arg, args.end());
1294 
1295     static size_t exec_count = 0;
1296     exec_count++;
1297     std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
1298 
1299     unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
1300     unsigned namespace_flags = 0;
1301 
1302     std::string seclabel = "";
1303     if (command_arg > 2 && args[1] != "-") {
1304         seclabel = args[1];
1305     }
1306     Result<uid_t> uid = 0;
1307     if (command_arg > 3) {
1308         uid = DecodeUid(args[2]);
1309         if (!uid) {
1310             LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error();
1311             return nullptr;
1312         }
1313     }
1314     Result<gid_t> gid = 0;
1315     std::vector<gid_t> supp_gids;
1316     if (command_arg > 4) {
1317         gid = DecodeUid(args[3]);
1318         if (!gid) {
1319             LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error();
1320             return nullptr;
1321         }
1322         std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
1323         for (size_t i = 0; i < nr_supp_gids; ++i) {
1324             auto supp_gid = DecodeUid(args[4 + i]);
1325             if (!supp_gid) {
1326                 LOG(ERROR) << "Unable to decode GID for '" << args[4 + i]
1327                            << "': " << supp_gid.error();
1328                 return nullptr;
1329             }
1330             supp_gids.push_back(*supp_gid);
1331         }
1332     }
1333 
1334     return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, namespace_flags, seclabel,
1335                                      nullptr, str_args);
1336 }
1337 
1338 // Shutdown services in the opposite order that they were started.
services_in_shutdown_order() const1339 const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
1340     std::vector<Service*> shutdown_services;
1341     for (const auto& service : services_) {
1342         if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
1343     }
1344     std::sort(shutdown_services.begin(), shutdown_services.end(),
1345               [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
1346     return shutdown_services;
1347 }
1348 
RemoveService(const Service & svc)1349 void ServiceList::RemoveService(const Service& svc) {
1350     auto svc_it = std::find_if(services_.begin(), services_.end(),
1351                                [&svc] (const std::unique_ptr<Service>& s) {
1352                                    return svc.name() == s->name();
1353                                });
1354     if (svc_it == services_.end()) {
1355         return;
1356     }
1357 
1358     services_.erase(svc_it);
1359 }
1360 
DumpState() const1361 void ServiceList::DumpState() const {
1362     for (const auto& s : services_) {
1363         s->DumpState();
1364     }
1365 }
1366 
MarkPostData()1367 void ServiceList::MarkPostData() {
1368     post_data_ = true;
1369 }
1370 
IsPostData()1371 bool ServiceList::IsPostData() {
1372     return post_data_;
1373 }
1374 
MarkServicesUpdate()1375 void ServiceList::MarkServicesUpdate() {
1376     services_update_finished_ = true;
1377 
1378     // start the delayed services
1379     for (const auto& name : delayed_service_names_) {
1380         Service* service = FindService(name);
1381         if (service == nullptr) {
1382             LOG(ERROR) << "delayed service '" << name << "' could not be found.";
1383             continue;
1384         }
1385         if (auto result = service->Start(); !result) {
1386             LOG(ERROR) << result.error_string();
1387         }
1388     }
1389     delayed_service_names_.clear();
1390 }
1391 
DelayService(const Service & service)1392 void ServiceList::DelayService(const Service& service) {
1393     if (services_update_finished_) {
1394         LOG(ERROR) << "Cannot delay the start of service '" << service.name()
1395                    << "' because all services are already updated. Ignoring.";
1396         return;
1397     }
1398     delayed_service_names_.emplace_back(service.name());
1399 }
1400 
ParseSection(std::vector<std::string> && args,const std::string & filename,int line)1401 Result<Success> ServiceParser::ParseSection(std::vector<std::string>&& args,
1402                                             const std::string& filename, int line) {
1403     if (args.size() < 3) {
1404         return Error() << "services must have a name and a program";
1405     }
1406 
1407     const std::string& name = args[1];
1408     if (!IsValidName(name)) {
1409         return Error() << "invalid service name '" << name << "'";
1410     }
1411 
1412     filename_ = filename;
1413 
1414     Subcontext* restart_action_subcontext = nullptr;
1415     if (subcontexts_) {
1416         for (auto& subcontext : *subcontexts_) {
1417             if (StartsWith(filename, subcontext.path_prefix())) {
1418                 restart_action_subcontext = &subcontext;
1419                 break;
1420             }
1421         }
1422     }
1423 
1424     std::vector<std::string> str_args(args.begin() + 2, args.end());
1425 
1426     if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
1427         if (str_args[0] == "/sbin/watchdogd") {
1428             str_args[0] = "/system/bin/watchdogd";
1429         }
1430     }
1431 
1432     service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
1433     return Success();
1434 }
1435 
ParseLineSection(std::vector<std::string> && args,int line)1436 Result<Success> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
1437     return service_ ? service_->ParseLine(std::move(args)) : Success();
1438 }
1439 
EndSection()1440 Result<Success> ServiceParser::EndSection() {
1441     if (service_) {
1442         Service* old_service = service_list_->FindService(service_->name());
1443         if (old_service) {
1444             if (!service_->is_override()) {
1445                 return Error() << "ignored duplicate definition of service '" << service_->name()
1446                                << "'";
1447             }
1448 
1449             if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
1450                 return Error() << "cannot update a non-updatable service '" << service_->name()
1451                                << "' with a config in APEX";
1452             }
1453 
1454             service_list_->RemoveService(*old_service);
1455             old_service = nullptr;
1456         }
1457 
1458         service_list_->AddService(std::move(service_));
1459     }
1460 
1461     return Success();
1462 }
1463 
IsValidName(const std::string & name) const1464 bool ServiceParser::IsValidName(const std::string& name) const {
1465     // Property names can be any length, but may only contain certain characters.
1466     // Property values can contain any characters, but may only be a certain length.
1467     // (The latter restriction is needed because `start` and `stop` work by writing
1468     // the service name to the "ctl.start" and "ctl.stop" properties.)
1469     return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
1470 }
1471 
1472 }  // namespace init
1473 }  // namespace android
1474