• 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<char*> strs;
464         for (const auto& s : args_) {
465             strs.push_back(const_cast<char*>(s.c_str()));
466         }
467         strs.push_back(nullptr);
468         if (execve(args_[0].c_str(), (char**) &strs[0], (char**) ENV) < 0) {
469             ERROR("cannot execve('%s'): %s\n", args_[0].c_str(), strerror(errno));
470         }
471 
472         _exit(127);
473     }
474 
475     if (pid < 0) {
476         ERROR("failed to start '%s'\n", name_.c_str());
477         pid_ = 0;
478         return false;
479     }
480 
481     time_started_ = gettime();
482     pid_ = pid;
483     flags_ |= SVC_RUNNING;
484 
485     if ((flags_ & SVC_EXEC) != 0) {
486         INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
487              pid_, uid_, gid_, supp_gids_.size(),
488              !seclabel_.empty() ? seclabel_.c_str() : "default");
489     }
490 
491     NotifyStateChange("running");
492     return true;
493 }
494 
StartIfNotDisabled()495 bool Service::StartIfNotDisabled() {
496     if (!(flags_ & SVC_DISABLED)) {
497         return Start();
498     } else {
499         flags_ |= SVC_DISABLED_START;
500     }
501     return true;
502 }
503 
Enable()504 bool Service::Enable() {
505     flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
506     if (flags_ & SVC_DISABLED_START) {
507         return Start();
508     }
509     return true;
510 }
511 
Reset()512 void Service::Reset() {
513     StopOrReset(SVC_RESET);
514 }
515 
Stop()516 void Service::Stop() {
517     StopOrReset(SVC_DISABLED);
518 }
519 
Terminate()520 void Service::Terminate() {
521     flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
522     flags_ |= SVC_DISABLED;
523     if (pid_) {
524         NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
525                pid_);
526         kill(-pid_, SIGTERM);
527         NotifyStateChange("stopping");
528     }
529 }
530 
Restart()531 void Service::Restart() {
532     if (flags_ & SVC_RUNNING) {
533         /* Stop, wait, then start the service. */
534         StopOrReset(SVC_RESTART);
535     } else if (!(flags_ & SVC_RESTARTING)) {
536         /* Just start the service since it's not running. */
537         Start();
538     } /* else: Service is restarting anyways. */
539 }
540 
RestartIfNeeded(time_t & process_needs_restart)541 void Service::RestartIfNeeded(time_t& process_needs_restart) {
542     time_t next_start_time = time_started_ + 5;
543 
544     if (next_start_time <= gettime()) {
545         flags_ &= (~SVC_RESTARTING);
546         Start();
547         return;
548     }
549 
550     if ((next_start_time < process_needs_restart) ||
551         (process_needs_restart == 0)) {
552         process_needs_restart = next_start_time;
553     }
554 }
555 
556 /* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
StopOrReset(int how)557 void Service::StopOrReset(int how) {
558     /* The service is still SVC_RUNNING until its process exits, but if it has
559      * already exited it shoudn't attempt a restart yet. */
560     flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
561 
562     if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
563         /* Hrm, an illegal flag.  Default to SVC_DISABLED */
564         how = SVC_DISABLED;
565     }
566         /* if the service has not yet started, prevent
567          * it from auto-starting with its class
568          */
569     if (how == SVC_RESET) {
570         flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
571     } else {
572         flags_ |= how;
573     }
574 
575     if (pid_) {
576         NOTICE("Service '%s' is being killed...\n", name_.c_str());
577         kill(-pid_, SIGKILL);
578         NotifyStateChange("stopping");
579     } else {
580         NotifyStateChange("stopped");
581     }
582 }
583 
ZapStdio() const584 void Service::ZapStdio() const {
585     int fd;
586     fd = open("/dev/null", O_RDWR);
587     dup2(fd, 0);
588     dup2(fd, 1);
589     dup2(fd, 2);
590     close(fd);
591 }
592 
OpenConsole() const593 void Service::OpenConsole() const {
594     int fd;
595     if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
596         fd = open("/dev/null", O_RDWR);
597     }
598     ioctl(fd, TIOCSCTTY, 0);
599     dup2(fd, 0);
600     dup2(fd, 1);
601     dup2(fd, 2);
602     close(fd);
603 }
604 
PublishSocket(const std::string & name,int fd) const605 void Service::PublishSocket(const std::string& name, int fd) const {
606     std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
607     std::string val = StringPrintf("%d", fd);
608     add_environment(key.c_str(), val.c_str());
609 
610     /* make sure we don't close-on-exec */
611     fcntl(fd, F_SETFD, 0);
612 }
613 
614 int ServiceManager::exec_count_ = 0;
615 
ServiceManager()616 ServiceManager::ServiceManager() {
617 }
618 
GetInstance()619 ServiceManager& ServiceManager::GetInstance() {
620     static ServiceManager instance;
621     return instance;
622 }
623 
AddService(std::unique_ptr<Service> service)624 void ServiceManager::AddService(std::unique_ptr<Service> service) {
625     Service* old_service = FindServiceByName(service->name());
626     if (old_service) {
627         ERROR("ignored duplicate definition of service '%s'",
628               service->name().c_str());
629         return;
630     }
631     services_.emplace_back(std::move(service));
632 }
633 
MakeExecOneshotService(const std::vector<std::string> & args)634 Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
635     // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
636     // SECLABEL can be a - to denote default
637     std::size_t command_arg = 1;
638     for (std::size_t i = 1; i < args.size(); ++i) {
639         if (args[i] == "--") {
640             command_arg = i + 1;
641             break;
642         }
643     }
644     if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
645         ERROR("exec called with too many supplementary group ids\n");
646         return nullptr;
647     }
648 
649     if (command_arg >= args.size()) {
650         ERROR("exec called without command\n");
651         return nullptr;
652     }
653     std::vector<std::string> str_args(args.begin() + command_arg, args.end());
654 
655     exec_count_++;
656     std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
657     unsigned flags = SVC_EXEC | SVC_ONESHOT;
658 
659     std::string seclabel = "";
660     if (command_arg > 2 && args[1] != "-") {
661         seclabel = args[1];
662     }
663     uid_t uid = 0;
664     if (command_arg > 3) {
665         uid = decode_uid(args[2].c_str());
666     }
667     gid_t gid = 0;
668     std::vector<gid_t> supp_gids;
669     if (command_arg > 4) {
670         gid = decode_uid(args[3].c_str());
671         std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
672         for (size_t i = 0; i < nr_supp_gids; ++i) {
673             supp_gids.push_back(decode_uid(args[4 + i].c_str()));
674         }
675     }
676 
677     std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
678                                                supp_gids, seclabel, str_args));
679     if (!svc_p) {
680         ERROR("Couldn't allocate service for exec of '%s'",
681               str_args[0].c_str());
682         return nullptr;
683     }
684     Service* svc = svc_p.get();
685     services_.push_back(std::move(svc_p));
686 
687     return svc;
688 }
689 
FindServiceByName(const std::string & name) const690 Service* ServiceManager::FindServiceByName(const std::string& name) const {
691     auto svc = std::find_if(services_.begin(), services_.end(),
692                             [&name] (const std::unique_ptr<Service>& s) {
693                                 return name == s->name();
694                             });
695     if (svc != services_.end()) {
696         return svc->get();
697     }
698     return nullptr;
699 }
700 
FindServiceByPid(pid_t pid) const701 Service* ServiceManager::FindServiceByPid(pid_t pid) const {
702     auto svc = std::find_if(services_.begin(), services_.end(),
703                             [&pid] (const std::unique_ptr<Service>& s) {
704                                 return s->pid() == pid;
705                             });
706     if (svc != services_.end()) {
707         return svc->get();
708     }
709     return nullptr;
710 }
711 
FindServiceByKeychord(int keychord_id) const712 Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
713     auto svc = std::find_if(services_.begin(), services_.end(),
714                             [&keychord_id] (const std::unique_ptr<Service>& s) {
715                                 return s->keychord_id() == keychord_id;
716                             });
717 
718     if (svc != services_.end()) {
719         return svc->get();
720     }
721     return nullptr;
722 }
723 
ForEachService(std::function<void (Service *)> callback) const724 void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
725     for (const auto& s : services_) {
726         callback(s.get());
727     }
728 }
729 
ForEachServiceInClass(const std::string & classname,void (* func)(Service * svc)) const730 void ServiceManager::ForEachServiceInClass(const std::string& classname,
731                                            void (*func)(Service* svc)) const {
732     for (const auto& s : services_) {
733         if (classname == s->classname()) {
734             func(s.get());
735         }
736     }
737 }
738 
ForEachServiceWithFlags(unsigned matchflags,void (* func)(Service * svc)) const739 void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
740                                              void (*func)(Service* svc)) const {
741     for (const auto& s : services_) {
742         if (s->flags() & matchflags) {
743             func(s.get());
744         }
745     }
746 }
747 
RemoveService(const Service & svc)748 void ServiceManager::RemoveService(const Service& svc) {
749     auto svc_it = std::find_if(services_.begin(), services_.end(),
750                                [&svc] (const std::unique_ptr<Service>& s) {
751                                    return svc.name() == s->name();
752                                });
753     if (svc_it == services_.end()) {
754         return;
755     }
756 
757     services_.erase(svc_it);
758 }
759 
DumpState() const760 void ServiceManager::DumpState() const {
761     for (const auto& s : services_) {
762         s->DumpState();
763     }
764     INFO("\n");
765 }
766 
ReapOneProcess()767 bool ServiceManager::ReapOneProcess() {
768     int status;
769     pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
770     if (pid == 0) {
771         return false;
772     } else if (pid == -1) {
773         ERROR("waitpid failed: %s\n", strerror(errno));
774         return false;
775     }
776 
777     Service* svc = FindServiceByPid(pid);
778 
779     std::string name;
780     if (svc) {
781         name = android::base::StringPrintf("Service '%s' (pid %d)",
782                                            svc->name().c_str(), pid);
783     } else {
784         name = android::base::StringPrintf("Untracked pid %d", pid);
785     }
786 
787     if (WIFEXITED(status)) {
788         NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
789     } else if (WIFSIGNALED(status)) {
790         NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
791     } else if (WIFSTOPPED(status)) {
792         NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
793     } else {
794         NOTICE("%s state changed", name.c_str());
795     }
796 
797     if (!svc) {
798         return true;
799     }
800 
801     if (svc->Reap()) {
802         waiting_for_exec = false;
803         RemoveService(*svc);
804     }
805 
806     return true;
807 }
808 
ReapAnyOutstandingChildren()809 void ServiceManager::ReapAnyOutstandingChildren() {
810     while (ReapOneProcess()) {
811     }
812 }
813 
ParseSection(const std::vector<std::string> & args,std::string * err)814 bool ServiceParser::ParseSection(const std::vector<std::string>& args,
815                                  std::string* err) {
816     if (args.size() < 3) {
817         *err = "services must have a name and a program";
818         return false;
819     }
820 
821     const std::string& name = args[1];
822     if (!IsValidName(name)) {
823         *err = StringPrintf("invalid service name '%s'", name.c_str());
824         return false;
825     }
826 
827     std::vector<std::string> str_args(args.begin() + 2, args.end());
828     service_ = std::make_unique<Service>(name, "default", str_args);
829     return true;
830 }
831 
ParseLineSection(const std::vector<std::string> & args,const std::string & filename,int line,std::string * err) const832 bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
833                                      const std::string& filename, int line,
834                                      std::string* err) const {
835     return service_ ? service_->HandleLine(args, err) : false;
836 }
837 
EndSection()838 void ServiceParser::EndSection() {
839     if (service_) {
840         ServiceManager::GetInstance().AddService(std::move(service_));
841     }
842 }
843 
IsValidName(const std::string & name) const844 bool ServiceParser::IsValidName(const std::string& name) const {
845     if (name.size() > 16) {
846         return false;
847     }
848     for (const auto& c : name) {
849         if (!isalnum(c) && (c != '_') && (c != '-')) {
850             return false;
851         }
852     }
853     return true;
854 }
855