2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 #include <sys/types.h>
26 #include <selinux/selinux.h>
28 #include <android-base/file.h>
29 #include <android-base/stringprintf.h>
30 #include <cutils/android_reboot.h>
31 #include <cutils/sockets.h>
35 #include "init_parser.h"
37 #include "property_service.h"
40 using android::base::StringPrintf;
41 using android::base::WriteStringToFile;
43 #define CRITICAL_CRASH_THRESHOLD 4 // if we crash >4 times ...
44 #define CRITICAL_CRASH_WINDOW (4*60) // ... in 4 minutes, goto recovery
46 SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
49 SocketInfo::SocketInfo(const std::string& name, const std::string& type, uid_t uid,
50 gid_t gid, int perm, const std::string& socketcon)
51 : name(name), type(type), uid(uid), gid(gid), perm(perm), socketcon(socketcon) {
54 ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
57 ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
58 const std::string& value)
59 : name(name), value(value) {
62 Service::Service(const std::string& name, const std::string& classname,
63 const std::vector<std::string>& args)
64 : name_(name), classname_(classname), flags_(0), pid_(0), time_started_(0),
65 time_crashed_(0), nr_crashed_(0), uid_(0), gid_(0), seclabel_(""),
66 ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
67 onrestart_.InitSingleTrigger("onrestart");
70 Service::Service(const std::string& name, const std::string& classname,
71 unsigned flags, uid_t uid, gid_t gid, const std::vector<gid_t>& supp_gids,
72 const std::string& seclabel, const std::vector<std::string>& args)
73 : name_(name), classname_(classname), flags_(flags), pid_(0), time_started_(0),
74 time_crashed_(0), nr_crashed_(0), uid_(uid), gid_(gid), supp_gids_(supp_gids),
75 seclabel_(seclabel), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
76 onrestart_.InitSingleTrigger("onrestart");
79 void Service::NotifyStateChange(const std::string& new_state) const {
80 if ((flags_ & SVC_EXEC) != 0) {
81 // 'exec' commands don't have properties tracking their state.
85 std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
86 if (prop_name.length() >= PROP_NAME_MAX) {
87 // If the property name would be too long, we can't set it.
88 ERROR("Property name \"init.svc.%s\" too long; not setting to %s\n",
89 name_.c_str(), new_state.c_str());
93 property_set(prop_name.c_str(), new_state.c_str());
96 bool Service::Reap() {
97 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
98 NOTICE("Service '%s' (pid %d) killing any children in process group\n",
100 kill(-pid_, SIGKILL);
103 // Remove any sockets we may have created.
104 for (const auto& si : sockets_) {
105 std::string tmp = StringPrintf(ANDROID_SOCKET_DIR "/%s", si.name.c_str());
109 if (flags_ & SVC_EXEC) {
110 INFO("SVC_EXEC pid %d finished...\n", pid_);
115 flags_ &= (~SVC_RUNNING);
117 // Oneshot processes go into the disabled state on exit,
118 // except when manually restarted.
119 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
120 flags_ |= SVC_DISABLED;
123 // Disabled and reset processes do not get restarted automatically.
124 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
125 NotifyStateChange("stopped");
129 time_t now = gettime();
130 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
131 if (time_crashed_ + CRITICAL_CRASH_WINDOW >= now) {
132 if (++nr_crashed_ > CRITICAL_CRASH_THRESHOLD) {
133 ERROR("critical process '%s' exited %d times in %d minutes; "
134 "rebooting into recovery mode\n", name_.c_str(),
135 CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
136 android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
145 flags_ &= (~SVC_RESTART);
146 flags_ |= SVC_RESTARTING;
148 // Execute all onrestart commands for this service.
149 onrestart_.ExecuteAllCommands();
151 NotifyStateChange("restarting");
155 void Service::DumpState() const {
156 INFO("service %s\n", name_.c_str());
157 INFO(" class '%s'\n", classname_.c_str());
159 for (const auto& s : args_) {
160 INFO(" '%s'", s.c_str());
163 for (const auto& si : sockets_) {
164 INFO(" socket %s %s 0%o\n", si.name.c_str(), si.type.c_str(), si.perm);
168 bool Service::HandleClass(const std::vector<std::string>& args, std::string* err) {
169 classname_ = args[1];
173 bool Service::HandleConsole(const std::vector<std::string>& args, std::string* err) {
174 flags_ |= SVC_CONSOLE;
178 bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
179 flags_ |= SVC_CRITICAL;
183 bool Service::HandleDisabled(const std::vector<std::string>& args, std::string* err) {
184 flags_ |= SVC_DISABLED;
185 flags_ |= SVC_RC_DISABLED;
189 bool Service::HandleGroup(const std::vector<std::string>& args, std::string* err) {
190 gid_ = decode_uid(args[1].c_str());
191 for (std::size_t n = 2; n < args.size(); n++) {
192 supp_gids_.emplace_back(decode_uid(args[n].c_str()));
197 bool Service::HandleIoprio(const std::vector<std::string>& args, std::string* err) {
198 ioprio_pri_ = std::stoul(args[2], 0, 8);
200 if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
201 *err = "priority value must be range 0 - 7";
205 if (args[1] == "rt") {
206 ioprio_class_ = IoSchedClass_RT;
207 } else if (args[1] == "be") {
208 ioprio_class_ = IoSchedClass_BE;
209 } else if (args[1] == "idle") {
210 ioprio_class_ = IoSchedClass_IDLE;
212 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
219 bool Service::HandleKeycodes(const std::vector<std::string>& args, std::string* err) {
220 for (std::size_t i = 1; i < args.size(); i++) {
221 keycodes_.emplace_back(std::stoi(args[i]));
226 bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
227 flags_ |= SVC_ONESHOT;
231 bool Service::HandleOnrestart(const std::vector<std::string>& args, std::string* err) {
232 std::vector<std::string> str_args(args.begin() + 1, args.end());
233 onrestart_.AddCommand(str_args, "", 0, err);
237 bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
242 bool Service::HandleSetenv(const std::vector<std::string>& args, std::string* err) {
243 envvars_.emplace_back(args[1], args[2]);
247 /* name type perm [ uid gid context ] */
248 bool Service::HandleSocket(const std::vector<std::string>& args, std::string* err) {
249 if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
250 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
254 int perm = std::stoul(args[3], 0, 8);
255 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
256 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
257 std::string socketcon = args.size() > 6 ? args[6] : "";
259 sockets_.emplace_back(args[1], args[2], uid, gid, perm, socketcon);
263 bool Service::HandleUser(const std::vector<std::string>& args, std::string* err) {
264 uid_ = decode_uid(args[1].c_str());
268 bool Service::HandleWritepid(const std::vector<std::string>& args, std::string* err) {
269 writepid_files_.assign(args.begin() + 1, args.end());
273 class Service::OptionHandlerMap : public KeywordMap<OptionHandler> {
278 Map& map() const override;
281 Service::OptionHandlerMap::Map& Service::OptionHandlerMap::map() const {
282 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
283 static const Map option_handlers = {
284 {"class", {1, 1, &Service::HandleClass}},
285 {"console", {0, 0, &Service::HandleConsole}},
286 {"critical", {0, 0, &Service::HandleCritical}},
287 {"disabled", {0, 0, &Service::HandleDisabled}},
288 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::HandleGroup}},
289 {"ioprio", {2, 2, &Service::HandleIoprio}},
290 {"keycodes", {1, kMax, &Service::HandleKeycodes}},
291 {"oneshot", {0, 0, &Service::HandleOneshot}},
292 {"onrestart", {1, kMax, &Service::HandleOnrestart}},
293 {"seclabel", {1, 1, &Service::HandleSeclabel}},
294 {"setenv", {2, 2, &Service::HandleSetenv}},
295 {"socket", {3, 6, &Service::HandleSocket}},
296 {"user", {1, 1, &Service::HandleUser}},
297 {"writepid", {1, kMax, &Service::HandleWritepid}},
299 return option_handlers;
302 bool Service::HandleLine(const std::vector<std::string>& args, std::string* err) {
304 *err = "option needed, but not provided";
308 static const OptionHandlerMap handler_map;
309 auto handler = handler_map.FindFunction(args[0], args.size() - 1, err);
315 return (this->*handler)(args, err);
318 bool Service::Start() {
319 // Starting a service removes it from the disabled or reset state and
320 // immediately takes it out of the restarting state if it was in there.
321 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
324 // Running processes require no additional work --- if they're in the
325 // process of exiting, we've ensured that they will immediately restart
326 // on exit, unless they are ONESHOT.
327 if (flags_ & SVC_RUNNING) {
331 bool needs_console = (flags_ & SVC_CONSOLE);
332 if (needs_console && !have_console) {
333 ERROR("service '%s' requires console\n", name_.c_str());
334 flags_ |= SVC_DISABLED;
339 if (stat(args_[0].c_str(), &sb) == -1) {
340 ERROR("cannot find '%s' (%s), disabling '%s'\n",
341 args_[0].c_str(), strerror(errno), name_.c_str());
342 flags_ |= SVC_DISABLED;
347 if (!seclabel_.empty()) {
350 char* mycon = nullptr;
351 char* fcon = nullptr;
353 INFO("computing context for service '%s'\n", args_[0].c_str());
354 int rc = getcon(&mycon);
356 ERROR("could not get context while starting '%s'\n", name_.c_str());
360 rc = getfilecon(args_[0].c_str(), &fcon);
362 ERROR("could not get context while starting '%s'\n", name_.c_str());
367 char* ret_scon = nullptr;
368 rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
374 if (rc == 0 && scon == mycon) {
375 ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
376 if (selinux_status_getenforce() > 0) {
385 ERROR("could not get context while starting '%s'\n", name_.c_str());
390 NOTICE("Starting service '%s'...\n", name_.c_str());
396 for (const auto& ei : envvars_) {
397 add_environment(ei.name.c_str(), ei.value.c_str());
400 for (const auto& si : sockets_) {
401 int socket_type = ((si.type == "stream" ? SOCK_STREAM :
402 (si.type == "dgram" ? SOCK_DGRAM :
404 const char* socketcon =
405 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
407 int s = create_socket(si.name.c_str(), socket_type, si.perm,
408 si.uid, si.gid, socketcon);
410 PublishSocket(si.name, s);
414 std::string pid_str = StringPrintf("%d", getpid());
415 for (const auto& file : writepid_files_) {
416 if (!WriteStringToFile(pid_str, file)) {
417 ERROR("couldn't write %s to %s: %s\n",
418 pid_str.c_str(), file.c_str(), strerror(errno));
422 if (ioprio_class_ != IoSchedClass_NONE) {
423 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
424 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
425 getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
436 setpgid(0, getpid());
438 // As requested, set our gid, supplemental gids, and uid.
440 if (setgid(gid_) != 0) {
441 ERROR("setgid failed: %s\n", strerror(errno));
445 if (!supp_gids_.empty()) {
446 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
447 ERROR("setgroups failed: %s\n", strerror(errno));
452 if (setuid(uid_) != 0) {
453 ERROR("setuid failed: %s\n", strerror(errno));
457 if (!seclabel_.empty()) {
458 if (setexeccon(seclabel_.c_str()) < 0) {
459 ERROR("cannot setexeccon('%s'): %s\n",
460 seclabel_.c_str(), strerror(errno));
465 std::vector<std::string> expanded_args;
466 std::vector<char*> strs;
467 expanded_args.resize(args_.size());
468 strs.push_back(const_cast<char*>(args_[0].c_str()));
469 for (std::size_t i = 1; i < args_.size(); ++i) {
470 if (!expand_props(args_[i], &expanded_args[i])) {
471 ERROR("%s: cannot expand '%s'\n", args_[0].c_str(), args_[i].c_str());
474 strs.push_back(const_cast<char*>(expanded_args[i].c_str()));
476 strs.push_back(nullptr);
478 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
479 ERROR("cannot execve('%s'): %s\n", strs[0], strerror(errno));
486 ERROR("failed to start '%s'\n", name_.c_str());
491 time_started_ = gettime();
493 flags_ |= SVC_RUNNING;
495 if ((flags_ & SVC_EXEC) != 0) {
496 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
497 pid_, uid_, gid_, supp_gids_.size(),
498 !seclabel_.empty() ? seclabel_.c_str() : "default");
501 NotifyStateChange("running");
505 bool Service::StartIfNotDisabled() {
506 if (!(flags_ & SVC_DISABLED)) {
509 flags_ |= SVC_DISABLED_START;
514 bool Service::Enable() {
515 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
516 if (flags_ & SVC_DISABLED_START) {
522 void Service::Reset() {
523 StopOrReset(SVC_RESET);
526 void Service::Stop() {
527 StopOrReset(SVC_DISABLED);
530 void Service::Terminate() {
531 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
532 flags_ |= SVC_DISABLED;
534 NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
536 kill(-pid_, SIGTERM);
537 NotifyStateChange("stopping");
541 void Service::Restart() {
542 if (flags_ & SVC_RUNNING) {
543 /* Stop, wait, then start the service. */
544 StopOrReset(SVC_RESTART);
545 } else if (!(flags_ & SVC_RESTARTING)) {
546 /* Just start the service since it's not running. */
548 } /* else: Service is restarting anyways. */
551 void Service::RestartIfNeeded(time_t& process_needs_restart) {
552 time_t next_start_time = time_started_ + 5;
554 if (next_start_time <= gettime()) {
555 flags_ &= (~SVC_RESTARTING);
560 if ((next_start_time < process_needs_restart) ||
561 (process_needs_restart == 0)) {
562 process_needs_restart = next_start_time;
566 /* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
567 void Service::StopOrReset(int how) {
568 /* The service is still SVC_RUNNING until its process exits, but if it has
569 * already exited it shoudn't attempt a restart yet. */
570 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
572 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
573 /* Hrm, an illegal flag. Default to SVC_DISABLED */
576 /* if the service has not yet started, prevent
577 * it from auto-starting with its class
579 if (how == SVC_RESET) {
580 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
586 NOTICE("Service '%s' is being killed...\n", name_.c_str());
587 kill(-pid_, SIGKILL);
588 NotifyStateChange("stopping");
590 NotifyStateChange("stopped");
594 void Service::ZapStdio() const {
596 fd = open("/dev/null", O_RDWR);
603 void Service::OpenConsole() const {
605 if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
606 fd = open("/dev/null", O_RDWR);
608 ioctl(fd, TIOCSCTTY, 0);
615 void Service::PublishSocket(const std::string& name, int fd) const {
616 std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
617 std::string val = StringPrintf("%d", fd);
618 add_environment(key.c_str(), val.c_str());
620 /* make sure we don't close-on-exec */
621 fcntl(fd, F_SETFD, 0);
624 int ServiceManager::exec_count_ = 0;
626 ServiceManager::ServiceManager() {
629 ServiceManager& ServiceManager::GetInstance() {
630 static ServiceManager instance;
634 void ServiceManager::AddService(std::unique_ptr<Service> service) {
635 Service* old_service = FindServiceByName(service->name());
637 ERROR("ignored duplicate definition of service '%s'",
638 service->name().c_str());
641 services_.emplace_back(std::move(service));
644 Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
645 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
646 // SECLABEL can be a - to denote default
647 std::size_t command_arg = 1;
648 for (std::size_t i = 1; i < args.size(); ++i) {
649 if (args[i] == "--") {
654 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
655 ERROR("exec called with too many supplementary group ids\n");
659 if (command_arg >= args.size()) {
660 ERROR("exec called without command\n");
663 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
666 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
667 unsigned flags = SVC_EXEC | SVC_ONESHOT;
669 std::string seclabel = "";
670 if (command_arg > 2 && args[1] != "-") {
674 if (command_arg > 3) {
675 uid = decode_uid(args[2].c_str());
678 std::vector<gid_t> supp_gids;
679 if (command_arg > 4) {
680 gid = decode_uid(args[3].c_str());
681 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
682 for (size_t i = 0; i < nr_supp_gids; ++i) {
683 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
687 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
688 supp_gids, seclabel, str_args));
690 ERROR("Couldn't allocate service for exec of '%s'",
691 str_args[0].c_str());
694 Service* svc = svc_p.get();
695 services_.push_back(std::move(svc_p));
700 Service* ServiceManager::FindServiceByName(const std::string& name) const {
701 auto svc = std::find_if(services_.begin(), services_.end(),
702 [&name] (const std::unique_ptr<Service>& s) {
703 return name == s->name();
705 if (svc != services_.end()) {
711 Service* ServiceManager::FindServiceByPid(pid_t pid) const {
712 auto svc = std::find_if(services_.begin(), services_.end(),
713 [&pid] (const std::unique_ptr<Service>& s) {
714 return s->pid() == pid;
716 if (svc != services_.end()) {
722 Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
723 auto svc = std::find_if(services_.begin(), services_.end(),
724 [&keychord_id] (const std::unique_ptr<Service>& s) {
725 return s->keychord_id() == keychord_id;
728 if (svc != services_.end()) {
734 void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const {
735 for (const auto& s : services_) {
740 void ServiceManager::ForEachServiceInClass(const std::string& classname,
741 void (*func)(Service* svc)) const {
742 for (const auto& s : services_) {
743 if (classname == s->classname()) {
749 void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
750 void (*func)(Service* svc)) const {
751 for (const auto& s : services_) {
752 if (s->flags() & matchflags) {
758 void ServiceManager::RemoveService(const Service& svc) {
759 auto svc_it = std::find_if(services_.begin(), services_.end(),
760 [&svc] (const std::unique_ptr<Service>& s) {
761 return svc.name() == s->name();
763 if (svc_it == services_.end()) {
767 services_.erase(svc_it);
770 void ServiceManager::DumpState() const {
771 for (const auto& s : services_) {
777 bool ServiceManager::ReapOneProcess() {
779 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
782 } else if (pid == -1) {
783 ERROR("waitpid failed: %s\n", strerror(errno));
785 } else if (property_child_reap(pid)) {
789 Service* svc = FindServiceByPid(pid);
793 name = android::base::StringPrintf("Service '%s' (pid %d)",
794 svc->name().c_str(), pid);
796 name = android::base::StringPrintf("Untracked pid %d", pid);
799 if (WIFEXITED(status)) {
800 NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
801 } else if (WIFSIGNALED(status)) {
802 NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
803 } else if (WIFSTOPPED(status)) {
804 NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
806 NOTICE("%s state changed", name.c_str());
814 waiting_for_exec = false;
821 void ServiceManager::ReapAnyOutstandingChildren() {
822 while (ReapOneProcess()) {
826 bool ServiceParser::ParseSection(const std::vector<std::string>& args,
828 if (args.size() < 3) {
829 *err = "services must have a name and a program";
833 const std::string& name = args[1];
834 if (!IsValidName(name)) {
835 *err = StringPrintf("invalid service name '%s'", name.c_str());
839 std::vector<std::string> str_args(args.begin() + 2, args.end());
840 service_ = std::make_unique<Service>(name, "default", str_args);
844 bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
845 const std::string& filename, int line,
846 std::string* err) const {
847 return service_ ? service_->HandleLine(args, err) : false;
850 void ServiceParser::EndSection() {
852 ServiceManager::GetInstance().AddService(std::move(service_));
856 bool ServiceParser::IsValidName(const std::string& name) const {
857 if (name.size() > 16) {
860 for (const auto& c : name) {
861 if (!isalnum(c) && (c != '_') && (c != '-')) {