• 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 <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 
SocketInfo()46 SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
47 }
48 
SocketInfo(const std::string & name,const std::string & type,uid_t uid,gid_t gid,int perm,const std::string & socketcon)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 
ServiceEnvironmentInfo()54 ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
55 }
56 
ServiceEnvironmentInfo(const std::string & name,const std::string & value)57 ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
58                                                const std::string& value)
59     : name(name), value(value) {
60 }
61 
Service(const std::string & name,const std::string & classname,const std::vector<std::string> & args)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 
Service(const std::string & name,const std::string & classname,unsigned flags,uid_t uid,gid_t gid,const std::vector<gid_t> & supp_gids,const std::string & seclabel,const std::vector<std::string> & args)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 
NotifyStateChange(const std::string & new_state) const79 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 
Reap()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 
DumpState() const155 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 
HandleClass(const std::vector<std::string> & args,std::string * err)168 bool Service::HandleClass(const std::vector<std::string>& args, std::string* err) {
169     classname_ = args[1];
170     return true;
171 }
172 
HandleConsole(const std::vector<std::string> & args,std::string * err)173 bool Service::HandleConsole(const std::vector<std::string>& args, std::string* err) {
174     flags_ |= SVC_CONSOLE;
175     return true;
176 }
177 
HandleCritical(const std::vector<std::string> & args,std::string * err)178 bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
179     flags_ |= SVC_CRITICAL;
180     return true;
181 }
182 
HandleDisabled(const std::vector<std::string> & args,std::string * err)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 
HandleGroup(const std::vector<std::string> & args,std::string * err)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 
HandleIoprio(const std::vector<std::string> & args,std::string * err)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 
HandleKeycodes(const std::vector<std::string> & args,std::string * err)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 
HandleOneshot(const std::vector<std::string> & args,std::string * err)226 bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
227     flags_ |= SVC_ONESHOT;
228     return true;
229 }
230 
HandleOnrestart(const std::vector<std::string> & args,std::string * err)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 
HandleSeclabel(const std::vector<std::string> & args,std::string * err)237 bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
238     seclabel_ = args[1];
239     return true;
240 }
241 
HandleSetenv(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]);
244     return true;
245 }
246 
247 /* name type perm [ uid gid context ] */
HandleSocket(const std::vector<std::string> & args,std::string * err)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 
HandleUser(const std::vector<std::string> & args,std::string * err)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 
HandleWritepid(const std::vector<std::string> & args,std::string * err)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:
OptionHandlerMap()275     OptionHandlerMap() {
276     }
277 private:
278     Map& map() const override;
279 };
280 
map() const281 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 
HandleLine(const std::vector<std::string> & args,std::string * err)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 
Start()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             free(mycon);
377             free(fcon);
378             return false;
379         }
380         free(mycon);
381         free(fcon);
382         if (rc < 0) {
383             ERROR("could not get context while starting '%s'\n", name_.c_str());
384             return false;
385         }
386     }
387 
388     NOTICE("Starting service '%s'...\n", name_.c_str());
389 
390     pid_t pid = fork();
391     if (pid == 0) {
392         umask(077);
393 
394         for (const auto& ei : envvars_) {
395             add_environment(ei.name.c_str(), ei.value.c_str());
396         }
397 
398         for (const auto& si : sockets_) {
399             int socket_type = ((si.type == "stream" ? SOCK_STREAM :
400                                 (si.type == "dgram" ? SOCK_DGRAM :
401                                  SOCK_SEQPACKET)));
402             const char* socketcon =
403                 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
404 
405             int s = create_socket(si.name.c_str(), socket_type, si.perm,
406                                   si.uid, si.gid, socketcon);
407             if (s >= 0) {
408                 PublishSocket(si.name, s);
409             }
410         }
411 
412         std::string pid_str = StringPrintf("%d", getpid());
413         for (const auto& file : writepid_files_) {
414             if (!WriteStringToFile(pid_str, file)) {
415                 ERROR("couldn't write %s to %s: %s\n",
416                       pid_str.c_str(), file.c_str(), strerror(errno));
417             }
418         }
419 
420         if (ioprio_class_ != IoSchedClass_NONE) {
421             if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
422                 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
423                       getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
424             }
425         }
426 
427         if (needs_console) {
428             setsid();
429             OpenConsole();
430         } else {
431             ZapStdio();
432         }
433 
434         setpgid(0, getpid());
435 
436         // As requested, set our gid, supplemental gids, and uid.
437         if (gid_) {
438             if (setgid(gid_) != 0) {
439                 ERROR("setgid failed: %s\n", strerror(errno));
440                 _exit(127);
441             }
442         }
443         if (!supp_gids_.empty()) {
444             if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
445                 ERROR("setgroups failed: %s\n", strerror(errno));
446                 _exit(127);
447             }
448         }
449         if (uid_) {
450             if (setuid(uid_) != 0) {
451                 ERROR("setuid failed: %s\n", strerror(errno));
452                 _exit(127);
453             }
454         }
455         if (!seclabel_.empty()) {
456             if (setexeccon(seclabel_.c_str()) < 0) {
457                 ERROR("cannot setexeccon('%s'): %s\n",
458                       seclabel_.c_str(), strerror(errno));
459                 _exit(127);
460             }
461         }
462 
463         std::vector<std::string> expanded_args;
464         std::vector<char*> strs;
465         expanded_args.resize(args_.size());
466         strs.push_back(const_cast<char*>(args_[0].c_str()));
467         for (std::size_t i = 1; i < args_.size(); ++i) {
468             if (!expand_props(args_[i], &expanded_args[i])) {
469                 ERROR("%s: cannot expand '%s'\n", args_[0].c_str(), args_[i].c_str());
470                 _exit(127);
471             }
472             strs.push_back(const_cast<char*>(expanded_args[i].c_str()));
473         }
474         strs.push_back(nullptr);
475 
476         if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
477             ERROR("cannot execve('%s'): %s\n", strs[0], strerror(errno));
478         }
479 
480         _exit(127);
481     }
482 
483     if (pid < 0) {
484         ERROR("failed to start '%s'\n", name_.c_str());
485         pid_ = 0;
486         return false;
487     }
488 
489     time_started_ = gettime();
490     pid_ = pid;
491     flags_ |= SVC_RUNNING;
492 
493     if ((flags_ & SVC_EXEC) != 0) {
494         INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
495              pid_, uid_, gid_, supp_gids_.size(),
496              !seclabel_.empty() ? seclabel_.c_str() : "default");
497     }
498 
499     NotifyStateChange("running");
500     return true;
501 }
502 
StartIfNotDisabled()503 bool Service::StartIfNotDisabled() {
504     if (!(flags_ & SVC_DISABLED)) {
505         return Start();
506     } else {
507         flags_ |= SVC_DISABLED_START;
508     }
509     return true;
510 }
511 
Enable()512 bool Service::Enable() {
513     flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
514     if (flags_ & SVC_DISABLED_START) {
515         return Start();
516     }
517     return true;
518 }
519 
Reset()520 void Service::Reset() {
521     StopOrReset(SVC_RESET);
522 }
523 
Stop()524 void Service::Stop() {
525     StopOrReset(SVC_DISABLED);
526 }
527 
Terminate()528 void Service::Terminate() {
529     flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
530     flags_ |= SVC_DISABLED;
531     if (pid_) {
532         NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
533                pid_);
534         kill(-pid_, SIGTERM);
535         NotifyStateChange("stopping");
536     }
537 }
538 
Restart()539 void Service::Restart() {
540     if (flags_ & SVC_RUNNING) {
541         /* Stop, wait, then start the service. */
542         StopOrReset(SVC_RESTART);
543     } else if (!(flags_ & SVC_RESTARTING)) {
544         /* Just start the service since it's not running. */
545         Start();
546     } /* else: Service is restarting anyways. */
547 }
548 
RestartIfNeeded(time_t & process_needs_restart)549 void Service::RestartIfNeeded(time_t& process_needs_restart) {
550     time_t next_start_time = time_started_ + 5;
551 
552     if (next_start_time <= gettime()) {
553         flags_ &= (~SVC_RESTARTING);
554         Start();
555         return;
556     }
557 
558     if ((next_start_time < process_needs_restart) ||
559         (process_needs_restart == 0)) {
560         process_needs_restart = next_start_time;
561     }
562 }
563 
564 /* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
StopOrReset(int how)565 void Service::StopOrReset(int how) {
566     /* The service is still SVC_RUNNING until its process exits, but if it has
567      * already exited it shoudn't attempt a restart yet. */
568     flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
569 
570     if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
571         /* Hrm, an illegal flag.  Default to SVC_DISABLED */
572         how = SVC_DISABLED;
573     }
574         /* if the service has not yet started, prevent
575          * it from auto-starting with its class
576          */
577     if (how == SVC_RESET) {
578         flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
579     } else {
580         flags_ |= how;
581     }
582 
583     if (pid_) {
584         NOTICE("Service '%s' is being killed...\n", name_.c_str());
585         kill(-pid_, SIGKILL);
586         NotifyStateChange("stopping");
587     } else {
588         NotifyStateChange("stopped");
589     }
590 }
591 
ZapStdio() const592 void Service::ZapStdio() const {
593     int fd;
594     fd = open("/dev/null", O_RDWR);
595     dup2(fd, 0);
596     dup2(fd, 1);
597     dup2(fd, 2);
598     close(fd);
599 }
600 
OpenConsole() const601 void Service::OpenConsole() const {
602     int fd;
603     if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
604         fd = open("/dev/null", O_RDWR);
605     }
606     ioctl(fd, TIOCSCTTY, 0);
607     dup2(fd, 0);
608     dup2(fd, 1);
609     dup2(fd, 2);
610     close(fd);
611 }
612 
PublishSocket(const std::string & name,int fd) const613 void Service::PublishSocket(const std::string& name, int fd) const {
614     std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
615     std::string val = StringPrintf("%d", fd);
616     add_environment(key.c_str(), val.c_str());
617 
618     /* make sure we don't close-on-exec */
619     fcntl(fd, F_SETFD, 0);
620 }
621 
622 int ServiceManager::exec_count_ = 0;
623 
ServiceManager()624 ServiceManager::ServiceManager() {
625 }
626 
GetInstance()627 ServiceManager& ServiceManager::GetInstance() {
628     static ServiceManager instance;
629     return instance;
630 }
631 
AddService(std::unique_ptr<Service> service)632 void ServiceManager::AddService(std::unique_ptr<Service> service) {
633     Service* old_service = FindServiceByName(service->name());
634     if (old_service) {
635         ERROR("ignored duplicate definition of service '%s'",
636               service->name().c_str());
637         return;
638     }
639     services_.emplace_back(std::move(service));
640 }
641 
MakeExecOneshotService(const std::vector<std::string> & args)642 Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
643     // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
644     // SECLABEL can be a - to denote default
645     std::size_t command_arg = 1;
646     for (std::size_t i = 1; i < args.size(); ++i) {
647         if (args[i] == "--") {
648             command_arg = i + 1;
649             break;
650         }
651     }
652     if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
653         ERROR("exec called with too many supplementary group ids\n");
654         return nullptr;
655     }
656 
657     if (command_arg >= args.size()) {
658         ERROR("exec called without command\n");
659         return nullptr;
660     }
661     std::vector<std::string> str_args(args.begin() + command_arg, args.end());
662 
663     exec_count_++;
664     std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
665     unsigned flags = SVC_EXEC | SVC_ONESHOT;
666 
667     std::string seclabel = "";
668     if (command_arg > 2 && args[1] != "-") {
669         seclabel = args[1];
670     }
671     uid_t uid = 0;
672     if (command_arg > 3) {
673         uid = decode_uid(args[2].c_str());
674     }
675     gid_t gid = 0;
676     std::vector<gid_t> supp_gids;
677     if (command_arg > 4) {
678         gid = decode_uid(args[3].c_str());
679         std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
680         for (size_t i = 0; i < nr_supp_gids; ++i) {
681             supp_gids.push_back(decode_uid(args[4 + i].c_str()));
682         }
683     }
684 
685     std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
686                                                supp_gids, seclabel, str_args));
687     if (!svc_p) {
688         ERROR("Couldn't allocate service for exec of '%s'",
689               str_args[0].c_str());
690         return nullptr;
691     }
692     Service* svc = svc_p.get();
693     services_.push_back(std::move(svc_p));
694 
695     return svc;
696 }
697 
FindServiceByName(const std::string & name) const698 Service* ServiceManager::FindServiceByName(const std::string& name) const {
699     auto svc = std::find_if(services_.begin(), services_.end(),
700                             [&name] (const std::unique_ptr<Service>& s) {
701                                 return name == s->name();
702                             });
703     if (svc != services_.end()) {
704         return svc->get();
705     }
706     return nullptr;
707 }
708 
FindServiceByPid(pid_t pid) const709 Service* ServiceManager::FindServiceByPid(pid_t pid) const {
710     auto svc = std::find_if(services_.begin(), services_.end(),
711                             [&pid] (const std::unique_ptr<Service>& s) {
712                                 return s->pid() == pid;
713                             });
714     if (svc != services_.end()) {
715         return svc->get();
716     }
717     return nullptr;
718 }
719 
FindServiceByKeychord(int keychord_id) const720 Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
721     auto svc = std::find_if(services_.begin(), services_.end(),
722                             [&keychord_id] (const std::unique_ptr<Service>& s) {
723                                 return s->keychord_id() == keychord_id;
724                             });
725 
726     if (svc != services_.end()) {
727         return svc->get();
728     }
729     return nullptr;
730 }
731 
ForEachService(std::function<void (Service *)> callback) const732 void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
733     for (const auto& s : services_) {
734         callback(s.get());
735     }
736 }
737 
ForEachServiceInClass(const std::string & classname,void (* func)(Service * svc)) const738 void ServiceManager::ForEachServiceInClass(const std::string& classname,
739                                            void (*func)(Service* svc)) const {
740     for (const auto& s : services_) {
741         if (classname == s->classname()) {
742             func(s.get());
743         }
744     }
745 }
746 
ForEachServiceWithFlags(unsigned matchflags,void (* func)(Service * svc)) const747 void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
748                                              void (*func)(Service* svc)) const {
749     for (const auto& s : services_) {
750         if (s->flags() & matchflags) {
751             func(s.get());
752         }
753     }
754 }
755 
RemoveService(const Service & svc)756 void ServiceManager::RemoveService(const Service& svc) {
757     auto svc_it = std::find_if(services_.begin(), services_.end(),
758                                [&svc] (const std::unique_ptr<Service>& s) {
759                                    return svc.name() == s->name();
760                                });
761     if (svc_it == services_.end()) {
762         return;
763     }
764 
765     services_.erase(svc_it);
766 }
767 
DumpState() const768 void ServiceManager::DumpState() const {
769     for (const auto& s : services_) {
770         s->DumpState();
771     }
772     INFO("\n");
773 }
774 
ReapOneProcess()775 bool ServiceManager::ReapOneProcess() {
776     int status;
777     pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
778     if (pid == 0) {
779         return false;
780     } else if (pid == -1) {
781         ERROR("waitpid failed: %s\n", strerror(errno));
782         return false;
783     }
784 
785     Service* svc = FindServiceByPid(pid);
786 
787     std::string name;
788     if (svc) {
789         name = android::base::StringPrintf("Service '%s' (pid %d)",
790                                            svc->name().c_str(), pid);
791     } else {
792         name = android::base::StringPrintf("Untracked pid %d", pid);
793     }
794 
795     if (WIFEXITED(status)) {
796         NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
797     } else if (WIFSIGNALED(status)) {
798         NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
799     } else if (WIFSTOPPED(status)) {
800         NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
801     } else {
802         NOTICE("%s state changed", name.c_str());
803     }
804 
805     if (!svc) {
806         return true;
807     }
808 
809     if (svc->Reap()) {
810         waiting_for_exec = false;
811         RemoveService(*svc);
812     }
813 
814     return true;
815 }
816 
ReapAnyOutstandingChildren()817 void ServiceManager::ReapAnyOutstandingChildren() {
818     while (ReapOneProcess()) {
819     }
820 }
821 
ParseSection(const std::vector<std::string> & args,std::string * err)822 bool ServiceParser::ParseSection(const std::vector<std::string>& args,
823                                  std::string* err) {
824     if (args.size() < 3) {
825         *err = "services must have a name and a program";
826         return false;
827     }
828 
829     const std::string& name = args[1];
830     if (!IsValidName(name)) {
831         *err = StringPrintf("invalid service name '%s'", name.c_str());
832         return false;
833     }
834 
835     std::vector<std::string> str_args(args.begin() + 2, args.end());
836     service_ = std::make_unique<Service>(name, "default", str_args);
837     return true;
838 }
839 
ParseLineSection(const std::vector<std::string> & args,const std::string & filename,int line,std::string * err) const840 bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
841                                      const std::string& filename, int line,
842                                      std::string* err) const {
843     return service_ ? service_->HandleLine(args, err) : false;
844 }
845 
EndSection()846 void ServiceParser::EndSection() {
847     if (service_) {
848         ServiceManager::GetInstance().AddService(std::move(service_));
849     }
850 }
851 
IsValidName(const std::string & name) const852 bool ServiceParser::IsValidName(const std::string& name) const {
853     if (name.size() > 16) {
854         return false;
855     }
856     for (const auto& c : name) {
857         if (!isalnum(c) && (c != '_') && (c != '-')) {
858             return false;
859         }
860     }
861     return true;
862 }
863