OSDN Git Service

Merge remote-tracking branch 'x86/nougat-x86' into cm-14.1-x86
[android-x86/system-core.git] / init / service.cpp
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 <sys/stat.h>
21 #include <sys/types.h>
22 #include <sys/wait.h>
23 #include <termios.h>
24 #include <unistd.h>
25
26 #include <selinux/selinux.h>
27
28 #include <android-base/file.h>
29 #include <android-base/stringprintf.h>
30 #include <cutils/android_reboot.h>
31 #include <cutils/sockets.h>
32
33 #include "action.h"
34 #include "init.h"
35 #include "init_parser.h"
36 #include "log.h"
37 #include "property_service.h"
38 #include "util.h"
39
40 using android::base::StringPrintf;
41 using android::base::WriteStringToFile;
42
43 #define CRITICAL_CRASH_THRESHOLD    4       // if we crash >4 times ...
44 #define CRITICAL_CRASH_WINDOW       (4*60)  // ... in 4 minutes, goto recovery
45
46 SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
47 }
48
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) {
52 }
53
54 ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
55 }
56
57 ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
58                                                const std::string& value)
59     : name(name), value(value) {
60 }
61
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");
68 }
69
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");
77 }
78
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.
82         return;
83     }
84
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());
90         return;
91     }
92
93     property_set(prop_name.c_str(), new_state.c_str());
94 }
95
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",
99                name_.c_str(), pid_);
100         kill(-pid_, SIGKILL);
101     }
102
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());
106         unlink(tmp.c_str());
107     }
108
109     if (flags_ & SVC_EXEC) {
110         INFO("SVC_EXEC pid %d finished...\n", pid_);
111         return true;
112     }
113
114     pid_ = 0;
115     flags_ &= (~SVC_RUNNING);
116
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;
121     }
122
123     // Disabled and reset processes do not get restarted automatically.
124     if (flags_ & (SVC_DISABLED | SVC_RESET))  {
125         NotifyStateChange("stopped");
126         return false;
127     }
128
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");
137                 return false;
138             }
139         } else {
140             time_crashed_ = now;
141             nr_crashed_ = 1;
142         }
143     }
144
145     flags_ &= (~SVC_RESTART);
146     flags_ |= SVC_RESTARTING;
147
148     // Execute all onrestart commands for this service.
149     onrestart_.ExecuteAllCommands();
150
151     NotifyStateChange("restarting");
152     return false;
153 }
154
155 void Service::DumpState() const {
156     INFO("service %s\n", name_.c_str());
157     INFO("  class '%s'\n", classname_.c_str());
158     INFO("  exec");
159     for (const auto& s : args_) {
160         INFO(" '%s'", s.c_str());
161     }
162     INFO("\n");
163     for (const auto& si : sockets_) {
164         INFO("  socket %s %s 0%o\n", si.name.c_str(), si.type.c_str(), si.perm);
165     }
166 }
167
168 bool Service::HandleClass(const std::vector<std::string>& args, std::string* err) {
169     classname_ = args[1];
170     return true;
171 }
172
173 bool Service::HandleConsole(const std::vector<std::string>& args, std::string* err) {
174     flags_ |= SVC_CONSOLE;
175     return true;
176 }
177
178 bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
179     flags_ |= SVC_CRITICAL;
180     return true;
181 }
182
183 bool Service::HandleDisabled(const std::vector<std::string>& args, std::string* err) {
184     flags_ |= SVC_DISABLED;
185     flags_ |= SVC_RC_DISABLED;
186     return true;
187 }
188
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()));
193     }
194     return true;
195 }
196
197 bool Service::HandleIoprio(const std::vector<std::string>& args, std::string* err) {
198     ioprio_pri_ = std::stoul(args[2], 0, 8);
199
200     if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
201         *err = "priority value must be range 0 - 7";
202         return false;
203     }
204
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;
211     } else {
212         *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
213         return false;
214     }
215
216     return true;
217 }
218
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]));
222     }
223     return true;
224 }
225
226 bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
227     flags_ |= SVC_ONESHOT;
228     return true;
229 }
230
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);
234     return true;
235 }
236
237 bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
238     seclabel_ = args[1];
239     return true;
240 }
241
242 bool Service::HandleSetenv(const std::vector<std::string>& args, std::string* err) {
243     envvars_.emplace_back(args[1], args[2]);
244     return true;
245 }
246
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'";
251         return false;
252     }
253
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] : "";
258
259     sockets_.emplace_back(args[1], args[2], uid, gid, perm, socketcon);
260     return true;
261 }
262
263 bool Service::HandleUser(const std::vector<std::string>& args, std::string* err) {
264     uid_ = decode_uid(args[1].c_str());
265     return true;
266 }
267
268 bool Service::HandleWritepid(const std::vector<std::string>& args, std::string* err) {
269     writepid_files_.assign(args.begin() + 1, args.end());
270     return true;
271 }
272
273 class Service::OptionHandlerMap : public KeywordMap<OptionHandler> {
274 public:
275     OptionHandlerMap() {
276     }
277 private:
278     Map& map() const override;
279 };
280
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}},
298     };
299     return option_handlers;
300 }
301
302 bool Service::HandleLine(const std::vector<std::string>& args, std::string* err) {
303     if (args.empty()) {
304         *err = "option needed, but not provided";
305         return false;
306     }
307
308     static const OptionHandlerMap handler_map;
309     auto handler = handler_map.FindFunction(args[0], args.size() - 1, err);
310
311     if (!handler) {
312         return false;
313     }
314
315     return (this->*handler)(args, err);
316 }
317
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));
322     time_started_ = 0;
323
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) {
328         return false;
329     }
330
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;
335         return false;
336     }
337
338     struct stat sb;
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;
343         return false;
344     }
345
346     std::string scon;
347     if (!seclabel_.empty()) {
348         scon = seclabel_;
349     } else {
350         char* mycon = nullptr;
351         char* fcon = nullptr;
352
353         INFO("computing context for service '%s'\n", args_[0].c_str());
354         int rc = getcon(&mycon);
355         if (rc < 0) {
356             ERROR("could not get context while starting '%s'\n", name_.c_str());
357             return false;
358         }
359
360         rc = getfilecon(args_[0].c_str(), &fcon);
361         if (rc < 0) {
362             ERROR("could not get context while starting '%s'\n", name_.c_str());
363             free(mycon);
364             return false;
365         }
366
367         char* ret_scon = nullptr;
368         rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
369                                      &ret_scon);
370         if (rc == 0) {
371             scon = ret_scon;
372             free(ret_scon);
373         }
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) {
377                 free(mycon);
378                 free(fcon);
379                 return false;
380             }
381         }
382         free(mycon);
383         free(fcon);
384         if (rc < 0) {
385             ERROR("could not get context while starting '%s'\n", name_.c_str());
386             return false;
387         }
388     }
389
390     NOTICE("Starting service '%s'...\n", name_.c_str());
391
392     pid_t pid = fork();
393     if (pid == 0) {
394         umask(077);
395
396         for (const auto& ei : envvars_) {
397             add_environment(ei.name.c_str(), ei.value.c_str());
398         }
399
400         for (const auto& si : sockets_) {
401             int socket_type = ((si.type == "stream" ? SOCK_STREAM :
402                                 (si.type == "dgram" ? SOCK_DGRAM :
403                                  SOCK_SEQPACKET)));
404             const char* socketcon =
405                 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
406
407             int s = create_socket(si.name.c_str(), socket_type, si.perm,
408                                   si.uid, si.gid, socketcon);
409             if (s >= 0) {
410                 PublishSocket(si.name, s);
411             }
412         }
413
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));
419             }
420         }
421
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));
426             }
427         }
428
429         if (needs_console) {
430             setsid();
431             OpenConsole();
432         } else {
433             ZapStdio();
434         }
435
436         setpgid(0, getpid());
437
438         // As requested, set our gid, supplemental gids, and uid.
439         if (gid_) {
440             if (setgid(gid_) != 0) {
441                 ERROR("setgid failed: %s\n", strerror(errno));
442                 _exit(127);
443             }
444         }
445         if (!supp_gids_.empty()) {
446             if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
447                 ERROR("setgroups failed: %s\n", strerror(errno));
448                 _exit(127);
449             }
450         }
451         if (uid_) {
452             if (setuid(uid_) != 0) {
453                 ERROR("setuid failed: %s\n", strerror(errno));
454                 _exit(127);
455             }
456         }
457         if (!seclabel_.empty()) {
458             if (setexeccon(seclabel_.c_str()) < 0) {
459                 ERROR("cannot setexeccon('%s'): %s\n",
460                       seclabel_.c_str(), strerror(errno));
461                 _exit(127);
462             }
463         }
464
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());
472                 _exit(127);
473             }
474             strs.push_back(const_cast<char*>(expanded_args[i].c_str()));
475         }
476         strs.push_back(nullptr);
477
478         if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
479             ERROR("cannot execve('%s'): %s\n", strs[0], strerror(errno));
480         }
481
482         _exit(127);
483     }
484
485     if (pid < 0) {
486         ERROR("failed to start '%s'\n", name_.c_str());
487         pid_ = 0;
488         return false;
489     }
490
491     time_started_ = gettime();
492     pid_ = pid;
493     flags_ |= SVC_RUNNING;
494
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");
499     }
500
501     NotifyStateChange("running");
502     return true;
503 }
504
505 bool Service::StartIfNotDisabled() {
506     if (!(flags_ & SVC_DISABLED)) {
507         return Start();
508     } else {
509         flags_ |= SVC_DISABLED_START;
510     }
511     return true;
512 }
513
514 bool Service::Enable() {
515     flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
516     if (flags_ & SVC_DISABLED_START) {
517         return Start();
518     }
519     return true;
520 }
521
522 void Service::Reset() {
523     StopOrReset(SVC_RESET);
524 }
525
526 void Service::Stop() {
527     StopOrReset(SVC_DISABLED);
528 }
529
530 void Service::Terminate() {
531     flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
532     flags_ |= SVC_DISABLED;
533     if (pid_) {
534         NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
535                pid_);
536         kill(-pid_, SIGTERM);
537         NotifyStateChange("stopping");
538     }
539 }
540
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. */
547         Start();
548     } /* else: Service is restarting anyways. */
549 }
550
551 void Service::RestartIfNeeded(time_t& process_needs_restart) {
552     time_t next_start_time = time_started_ + 5;
553
554     if (next_start_time <= gettime()) {
555         flags_ &= (~SVC_RESTARTING);
556         Start();
557         return;
558     }
559
560     if ((next_start_time < process_needs_restart) ||
561         (process_needs_restart == 0)) {
562         process_needs_restart = next_start_time;
563     }
564 }
565
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);
571
572     if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
573         /* Hrm, an illegal flag.  Default to SVC_DISABLED */
574         how = SVC_DISABLED;
575     }
576         /* if the service has not yet started, prevent
577          * it from auto-starting with its class
578          */
579     if (how == SVC_RESET) {
580         flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
581     } else {
582         flags_ |= how;
583     }
584
585     if (pid_) {
586         NOTICE("Service '%s' is being killed...\n", name_.c_str());
587         kill(-pid_, SIGKILL);
588         NotifyStateChange("stopping");
589     } else {
590         NotifyStateChange("stopped");
591     }
592 }
593
594 void Service::ZapStdio() const {
595     int fd;
596     fd = open("/dev/null", O_RDWR);
597     dup2(fd, 0);
598     dup2(fd, 1);
599     dup2(fd, 2);
600     close(fd);
601 }
602
603 void Service::OpenConsole() const {
604     int fd;
605     if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
606         fd = open("/dev/null", O_RDWR);
607     }
608     ioctl(fd, TIOCSCTTY, 0);
609     dup2(fd, 0);
610     dup2(fd, 1);
611     dup2(fd, 2);
612     close(fd);
613 }
614
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());
619
620     /* make sure we don't close-on-exec */
621     fcntl(fd, F_SETFD, 0);
622 }
623
624 int ServiceManager::exec_count_ = 0;
625
626 ServiceManager::ServiceManager() {
627 }
628
629 ServiceManager& ServiceManager::GetInstance() {
630     static ServiceManager instance;
631     return instance;
632 }
633
634 void ServiceManager::AddService(std::unique_ptr<Service> service) {
635     Service* old_service = FindServiceByName(service->name());
636     if (old_service) {
637         ERROR("ignored duplicate definition of service '%s'",
638               service->name().c_str());
639         return;
640     }
641     services_.emplace_back(std::move(service));
642 }
643
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] == "--") {
650             command_arg = i + 1;
651             break;
652         }
653     }
654     if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
655         ERROR("exec called with too many supplementary group ids\n");
656         return nullptr;
657     }
658
659     if (command_arg >= args.size()) {
660         ERROR("exec called without command\n");
661         return nullptr;
662     }
663     std::vector<std::string> str_args(args.begin() + command_arg, args.end());
664
665     exec_count_++;
666     std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
667     unsigned flags = SVC_EXEC | SVC_ONESHOT;
668
669     std::string seclabel = "";
670     if (command_arg > 2 && args[1] != "-") {
671         seclabel = args[1];
672     }
673     uid_t uid = 0;
674     if (command_arg > 3) {
675         uid = decode_uid(args[2].c_str());
676     }
677     gid_t gid = 0;
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()));
684         }
685     }
686
687     std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
688                                                supp_gids, seclabel, str_args));
689     if (!svc_p) {
690         ERROR("Couldn't allocate service for exec of '%s'",
691               str_args[0].c_str());
692         return nullptr;
693     }
694     Service* svc = svc_p.get();
695     services_.push_back(std::move(svc_p));
696
697     return svc;
698 }
699
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();
704                             });
705     if (svc != services_.end()) {
706         return svc->get();
707     }
708     return nullptr;
709 }
710
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;
715                             });
716     if (svc != services_.end()) {
717         return svc->get();
718     }
719     return nullptr;
720 }
721
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;
726                             });
727
728     if (svc != services_.end()) {
729         return svc->get();
730     }
731     return nullptr;
732 }
733
734 void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const {
735     for (const auto& s : services_) {
736         callback(s.get());
737     }
738 }
739
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()) {
744             func(s.get());
745         }
746     }
747 }
748
749 void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
750                                              void (*func)(Service* svc)) const {
751     for (const auto& s : services_) {
752         if (s->flags() & matchflags) {
753             func(s.get());
754         }
755     }
756 }
757
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();
762                                });
763     if (svc_it == services_.end()) {
764         return;
765     }
766
767     services_.erase(svc_it);
768 }
769
770 void ServiceManager::DumpState() const {
771     for (const auto& s : services_) {
772         s->DumpState();
773     }
774     INFO("\n");
775 }
776
777 bool ServiceManager::ReapOneProcess() {
778     int status;
779     pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
780     if (pid == 0) {
781         return false;
782     } else if (pid == -1) {
783         ERROR("waitpid failed: %s\n", strerror(errno));
784         return false;
785     } else if (property_child_reap(pid)) {
786         return true;
787     }
788
789     Service* svc = FindServiceByPid(pid);
790
791     std::string name;
792     if (svc) {
793         name = android::base::StringPrintf("Service '%s' (pid %d)",
794                                            svc->name().c_str(), pid);
795     } else {
796         name = android::base::StringPrintf("Untracked pid %d", pid);
797     }
798
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));
805     } else {
806         NOTICE("%s state changed", name.c_str());
807     }
808
809     if (!svc) {
810         return true;
811     }
812
813     if (svc->Reap()) {
814         waiting_for_exec = false;
815         RemoveService(*svc);
816     }
817
818     return true;
819 }
820
821 void ServiceManager::ReapAnyOutstandingChildren() {
822     while (ReapOneProcess()) {
823     }
824 }
825
826 bool ServiceParser::ParseSection(const std::vector<std::string>& args,
827                                  std::string* err) {
828     if (args.size() < 3) {
829         *err = "services must have a name and a program";
830         return false;
831     }
832
833     const std::string& name = args[1];
834     if (!IsValidName(name)) {
835         *err = StringPrintf("invalid service name '%s'", name.c_str());
836         return false;
837     }
838
839     std::vector<std::string> str_args(args.begin() + 2, args.end());
840     service_ = std::make_unique<Service>(name, "default", str_args);
841     return true;
842 }
843
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;
848 }
849
850 void ServiceParser::EndSection() {
851     if (service_) {
852         ServiceManager::GetInstance().AddService(std::move(service_));
853     }
854 }
855
856 bool ServiceParser::IsValidName(const std::string& name) const {
857     if (name.size() > 16) {
858         return false;
859     }
860     for (const auto& c : name) {
861         if (!isalnum(c) && (c != '_') && (c != '-')) {
862             return false;
863         }
864     }
865     return true;
866 }