blob: 0ddc48485b3261cf8fbb2fafea2c7ea471206bef [file] [log] [blame]
Tom Cherrybac32992015-07-31 12:45:25 -07001/*
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>
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -080022#include <sys/wait.h>
Tom Cherrybac32992015-07-31 12:45:25 -070023#include <termios.h>
Dan Albertaf9ba4d2015-08-11 16:37:04 -070024#include <unistd.h>
Tom Cherrybac32992015-07-31 12:45:25 -070025
26#include <selinux/selinux.h>
27
Elliott Hughes4f713192015-12-04 22:00:26 -080028#include <android-base/file.h>
29#include <android-base/stringprintf.h>
Tom Cherrybac32992015-07-31 12:45:25 -070030#include <cutils/android_reboot.h>
31#include <cutils/sockets.h>
32
33#include "action.h"
34#include "init.h"
35#include "init_parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070036#include "log.h"
37#include "property_service.h"
38#include "util.h"
39
Tom Cherryb7349902015-08-26 11:43:36 -070040using android::base::StringPrintf;
41using android::base::WriteStringToFile;
42
Tom Cherrybac32992015-07-31 12:45:25 -070043#define CRITICAL_CRASH_THRESHOLD 4 // if we crash >4 times ...
44#define CRITICAL_CRASH_WINDOW (4*60) // ... in 4 minutes, goto recovery
45
46SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
47}
48
49SocketInfo::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
54ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
55}
56
57ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
58 const std::string& value)
59 : name(name), value(value) {
60}
61
62Service::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
70Service::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
79void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherrybac32992015-07-31 12:45:25 -070080 if ((flags_ & SVC_EXEC) != 0) {
81 // 'exec' commands don't have properties tracking their state.
82 return;
83 }
84
Tom Cherryb7349902015-08-26 11:43:36 -070085 std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -070086 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
96bool 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_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700105 std::string tmp = StringPrintf(ANDROID_SOCKET_DIR "/%s", si.name.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700106 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
155void 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
Tom Cherryb7349902015-08-26 11:43:36 -0700168bool Service::HandleClass(const std::vector<std::string>& args, std::string* err) {
169 classname_ = args[1];
170 return true;
171}
Tom Cherrybac32992015-07-31 12:45:25 -0700172
Tom Cherryb7349902015-08-26 11:43:36 -0700173bool Service::HandleConsole(const std::vector<std::string>& args, std::string* err) {
174 flags_ |= SVC_CONSOLE;
175 return true;
176}
Tom Cherrybac32992015-07-31 12:45:25 -0700177
Tom Cherryb7349902015-08-26 11:43:36 -0700178bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
179 flags_ |= SVC_CRITICAL;
180 return true;
181}
Tom Cherrybac32992015-07-31 12:45:25 -0700182
Tom Cherryb7349902015-08-26 11:43:36 -0700183bool Service::HandleDisabled(const std::vector<std::string>& args, std::string* err) {
184 flags_ |= SVC_DISABLED;
185 flags_ |= SVC_RC_DISABLED;
186 return true;
187}
Tom Cherrybac32992015-07-31 12:45:25 -0700188
Tom Cherryb7349902015-08-26 11:43:36 -0700189bool 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()));
Tom Cherrybac32992015-07-31 12:45:25 -0700193 }
194 return true;
195}
196
Tom Cherryb7349902015-08-26 11:43:36 -0700197bool 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
219bool 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
226bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
227 flags_ |= SVC_ONESHOT;
228 return true;
229}
230
231bool 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
237bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
238 seclabel_ = args[1];
239 return true;
240}
241
242bool 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 ] */
248bool 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
263bool Service::HandleUser(const std::vector<std::string>& args, std::string* err) {
264 uid_ = decode_uid(args[1].c_str());
265 return true;
266}
267
268bool 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
273class Service::OptionHandlerMap : public KeywordMap<OptionHandler> {
274public:
275 OptionHandlerMap() {
276 }
277private:
278 Map& map() const override;
279};
280
281Service::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
302bool 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
Tom Cherrybac32992015-07-31 12:45:25 -0700318bool Service::Start(const std::vector<std::string>& dynamic_args) {
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 if ((!(flags_ & SVC_ONESHOT)) && !dynamic_args.empty()) {
347 ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
348 args_[0].c_str());
349 flags_ |= SVC_DISABLED;
350 return false;
351 }
352
353 std::string scon;
354 if (!seclabel_.empty()) {
355 scon = seclabel_;
356 } else {
357 char* mycon = nullptr;
358 char* fcon = nullptr;
359
360 INFO("computing context for service '%s'\n", args_[0].c_str());
361 int rc = getcon(&mycon);
362 if (rc < 0) {
363 ERROR("could not get context while starting '%s'\n", name_.c_str());
364 return false;
365 }
366
367 rc = getfilecon(args_[0].c_str(), &fcon);
368 if (rc < 0) {
369 ERROR("could not get context while starting '%s'\n", name_.c_str());
370 free(mycon);
371 return false;
372 }
373
374 char* ret_scon = nullptr;
375 rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
376 &ret_scon);
377 if (rc == 0) {
378 scon = ret_scon;
379 free(ret_scon);
380 }
381 if (rc == 0 && scon == mycon) {
382 ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
383 free(mycon);
384 free(fcon);
385 return false;
386 }
387 free(mycon);
388 free(fcon);
389 if (rc < 0) {
390 ERROR("could not get context while starting '%s'\n", name_.c_str());
391 return false;
392 }
393 }
394
395 NOTICE("Starting service '%s'...\n", name_.c_str());
396
397 pid_t pid = fork();
398 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700399 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700400
401 for (const auto& ei : envvars_) {
402 add_environment(ei.name.c_str(), ei.value.c_str());
403 }
404
405 for (const auto& si : sockets_) {
406 int socket_type = ((si.type == "stream" ? SOCK_STREAM :
407 (si.type == "dgram" ? SOCK_DGRAM :
408 SOCK_SEQPACKET)));
409 const char* socketcon =
410 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
411
412 int s = create_socket(si.name.c_str(), socket_type, si.perm,
413 si.uid, si.gid, socketcon);
414 if (s >= 0) {
415 PublishSocket(si.name, s);
416 }
417 }
418
Tom Cherryb7349902015-08-26 11:43:36 -0700419 std::string pid_str = StringPrintf("%d", pid);
Tom Cherrybac32992015-07-31 12:45:25 -0700420 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700421 if (!WriteStringToFile(pid_str, file)) {
Tom Cherrybac32992015-07-31 12:45:25 -0700422 ERROR("couldn't write %s to %s: %s\n",
423 pid_str.c_str(), file.c_str(), strerror(errno));
424 }
425 }
426
427 if (ioprio_class_ != IoSchedClass_NONE) {
428 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
429 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
430 getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
431 }
432 }
433
434 if (needs_console) {
435 setsid();
436 OpenConsole();
437 } else {
438 ZapStdio();
439 }
440
441 setpgid(0, getpid());
442
443 // As requested, set our gid, supplemental gids, and uid.
444 if (gid_) {
445 if (setgid(gid_) != 0) {
446 ERROR("setgid failed: %s\n", strerror(errno));
447 _exit(127);
448 }
449 }
450 if (!supp_gids_.empty()) {
451 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
452 ERROR("setgroups failed: %s\n", strerror(errno));
453 _exit(127);
454 }
455 }
456 if (uid_) {
457 if (setuid(uid_) != 0) {
458 ERROR("setuid failed: %s\n", strerror(errno));
459 _exit(127);
460 }
461 }
462 if (!seclabel_.empty()) {
463 if (setexeccon(seclabel_.c_str()) < 0) {
464 ERROR("cannot setexeccon('%s'): %s\n",
465 seclabel_.c_str(), strerror(errno));
466 _exit(127);
467 }
468 }
469
470 std::vector<char*> strs;
471 for (const auto& s : args_) {
472 strs.push_back(const_cast<char*>(s.c_str()));
473 }
474 for (const auto& s : dynamic_args) {
475 strs.push_back(const_cast<char*>(s.c_str()));
476 }
477 strs.push_back(nullptr);
478 if (execve(args_[0].c_str(), (char**) &strs[0], (char**) ENV) < 0) {
479 ERROR("cannot execve('%s'): %s\n", args_[0].c_str(), 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
505bool Service::Start() {
506 const std::vector<std::string> null_dynamic_args;
507 return Start(null_dynamic_args);
508}
509
510bool Service::StartIfNotDisabled() {
511 if (!(flags_ & SVC_DISABLED)) {
512 return Start();
513 } else {
514 flags_ |= SVC_DISABLED_START;
515 }
516 return true;
517}
518
519bool Service::Enable() {
520 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
521 if (flags_ & SVC_DISABLED_START) {
522 return Start();
523 }
524 return true;
525}
526
527void Service::Reset() {
528 StopOrReset(SVC_RESET);
529}
530
531void Service::Stop() {
532 StopOrReset(SVC_DISABLED);
533}
534
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800535void Service::Terminate() {
536 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
537 flags_ |= SVC_DISABLED;
538 if (pid_) {
539 NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
540 pid_);
541 kill(-pid_, SIGTERM);
542 NotifyStateChange("stopping");
543 }
544}
545
Tom Cherrybac32992015-07-31 12:45:25 -0700546void Service::Restart() {
547 if (flags_ & SVC_RUNNING) {
548 /* Stop, wait, then start the service. */
549 StopOrReset(SVC_RESTART);
550 } else if (!(flags_ & SVC_RESTARTING)) {
551 /* Just start the service since it's not running. */
552 Start();
553 } /* else: Service is restarting anyways. */
554}
555
556void Service::RestartIfNeeded(time_t& process_needs_restart) {
557 time_t next_start_time = time_started_ + 5;
558
559 if (next_start_time <= gettime()) {
560 flags_ &= (~SVC_RESTARTING);
561 Start();
562 return;
563 }
564
565 if ((next_start_time < process_needs_restart) ||
566 (process_needs_restart == 0)) {
567 process_needs_restart = next_start_time;
568 }
569}
570
571/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
572void Service::StopOrReset(int how) {
573 /* The service is still SVC_RUNNING until its process exits, but if it has
574 * already exited it shoudn't attempt a restart yet. */
575 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
576
577 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
578 /* Hrm, an illegal flag. Default to SVC_DISABLED */
579 how = SVC_DISABLED;
580 }
581 /* if the service has not yet started, prevent
582 * it from auto-starting with its class
583 */
584 if (how == SVC_RESET) {
585 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
586 } else {
587 flags_ |= how;
588 }
589
590 if (pid_) {
591 NOTICE("Service '%s' is being killed...\n", name_.c_str());
592 kill(-pid_, SIGKILL);
593 NotifyStateChange("stopping");
594 } else {
595 NotifyStateChange("stopped");
596 }
597}
598
599void Service::ZapStdio() const {
600 int fd;
601 fd = open("/dev/null", O_RDWR);
602 dup2(fd, 0);
603 dup2(fd, 1);
604 dup2(fd, 2);
605 close(fd);
606}
607
608void Service::OpenConsole() const {
609 int fd;
610 if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
611 fd = open("/dev/null", O_RDWR);
612 }
613 ioctl(fd, TIOCSCTTY, 0);
614 dup2(fd, 0);
615 dup2(fd, 1);
616 dup2(fd, 2);
617 close(fd);
618}
619
620void Service::PublishSocket(const std::string& name, int fd) const {
Tom Cherryb7349902015-08-26 11:43:36 -0700621 std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
622 std::string val = StringPrintf("%d", fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700623 add_environment(key.c_str(), val.c_str());
624
625 /* make sure we don't close-on-exec */
626 fcntl(fd, F_SETFD, 0);
627}
628
629int ServiceManager::exec_count_ = 0;
630
631ServiceManager::ServiceManager() {
632}
633
634ServiceManager& ServiceManager::GetInstance() {
635 static ServiceManager instance;
636 return instance;
637}
638
Tom Cherryb7349902015-08-26 11:43:36 -0700639void ServiceManager::AddService(std::unique_ptr<Service> service) {
640 Service* old_service = FindServiceByName(service->name());
641 if (old_service) {
642 ERROR("ignored duplicate definition of service '%s'",
643 service->name().c_str());
644 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700645 }
Tom Cherryb7349902015-08-26 11:43:36 -0700646 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700647}
648
649Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
650 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
651 // SECLABEL can be a - to denote default
652 std::size_t command_arg = 1;
653 for (std::size_t i = 1; i < args.size(); ++i) {
654 if (args[i] == "--") {
655 command_arg = i + 1;
656 break;
657 }
658 }
659 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
660 ERROR("exec called with too many supplementary group ids\n");
661 return nullptr;
662 }
663
664 if (command_arg >= args.size()) {
665 ERROR("exec called without command\n");
666 return nullptr;
667 }
668 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
669
670 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700671 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700672 unsigned flags = SVC_EXEC | SVC_ONESHOT;
673
674 std::string seclabel = "";
675 if (command_arg > 2 && args[1] != "-") {
676 seclabel = args[1];
677 }
678 uid_t uid = 0;
679 if (command_arg > 3) {
680 uid = decode_uid(args[2].c_str());
681 }
682 gid_t gid = 0;
683 std::vector<gid_t> supp_gids;
684 if (command_arg > 4) {
685 gid = decode_uid(args[3].c_str());
686 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
687 for (size_t i = 0; i < nr_supp_gids; ++i) {
688 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
689 }
690 }
691
692 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
693 supp_gids, seclabel, str_args));
694 if (!svc_p) {
695 ERROR("Couldn't allocate service for exec of '%s'",
696 str_args[0].c_str());
697 return nullptr;
698 }
699 Service* svc = svc_p.get();
700 services_.push_back(std::move(svc_p));
701
702 return svc;
703}
704
705Service* ServiceManager::FindServiceByName(const std::string& name) const {
706 auto svc = std::find_if(services_.begin(), services_.end(),
707 [&name] (const std::unique_ptr<Service>& s) {
708 return name == s->name();
709 });
710 if (svc != services_.end()) {
711 return svc->get();
712 }
713 return nullptr;
714}
715
716Service* ServiceManager::FindServiceByPid(pid_t pid) const {
717 auto svc = std::find_if(services_.begin(), services_.end(),
718 [&pid] (const std::unique_ptr<Service>& s) {
719 return s->pid() == pid;
720 });
721 if (svc != services_.end()) {
722 return svc->get();
723 }
724 return nullptr;
725}
726
727Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
728 auto svc = std::find_if(services_.begin(), services_.end(),
729 [&keychord_id] (const std::unique_ptr<Service>& s) {
730 return s->keychord_id() == keychord_id;
731 });
732
733 if (svc != services_.end()) {
734 return svc->get();
735 }
736 return nullptr;
737}
738
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800739void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700740 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800741 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -0700742 }
743}
744
745void ServiceManager::ForEachServiceInClass(const std::string& classname,
746 void (*func)(Service* svc)) const {
747 for (const auto& s : services_) {
748 if (classname == s->classname()) {
749 func(s.get());
750 }
751 }
752}
753
754void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
755 void (*func)(Service* svc)) const {
756 for (const auto& s : services_) {
757 if (s->flags() & matchflags) {
758 func(s.get());
759 }
760 }
761}
762
Tom Cherryb7349902015-08-26 11:43:36 -0700763void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -0700764 auto svc_it = std::find_if(services_.begin(), services_.end(),
765 [&svc] (const std::unique_ptr<Service>& s) {
766 return svc.name() == s->name();
767 });
768 if (svc_it == services_.end()) {
769 return;
770 }
771
772 services_.erase(svc_it);
773}
774
Tom Cherryb7349902015-08-26 11:43:36 -0700775void ServiceManager::DumpState() const {
776 for (const auto& s : services_) {
777 s->DumpState();
778 }
779 INFO("\n");
780}
781
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800782bool ServiceManager::ReapOneProcess() {
783 int status;
784 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
785 if (pid == 0) {
786 return false;
787 } else if (pid == -1) {
788 ERROR("waitpid failed: %s\n", strerror(errno));
789 return false;
790 }
791
792 Service* svc = FindServiceByPid(pid);
793
794 std::string name;
795 if (svc) {
796 name = android::base::StringPrintf("Service '%s' (pid %d)",
797 svc->name().c_str(), pid);
798 } else {
799 name = android::base::StringPrintf("Untracked pid %d", pid);
800 }
801
802 if (WIFEXITED(status)) {
803 NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
804 } else if (WIFSIGNALED(status)) {
805 NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
806 } else if (WIFSTOPPED(status)) {
807 NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
808 } else {
809 NOTICE("%s state changed", name.c_str());
810 }
811
812 if (!svc) {
813 return true;
814 }
815
816 if (svc->Reap()) {
817 waiting_for_exec = false;
818 RemoveService(*svc);
819 }
820
821 return true;
822}
823
824void ServiceManager::ReapAnyOutstandingChildren() {
825 while (ReapOneProcess()) {
826 }
827}
828
Tom Cherryb7349902015-08-26 11:43:36 -0700829bool ServiceParser::ParseSection(const std::vector<std::string>& args,
830 std::string* err) {
831 if (args.size() < 3) {
832 *err = "services must have a name and a program";
833 return false;
834 }
835
836 const std::string& name = args[1];
837 if (!IsValidName(name)) {
838 *err = StringPrintf("invalid service name '%s'", name.c_str());
839 return false;
840 }
841
842 std::vector<std::string> str_args(args.begin() + 2, args.end());
843 service_ = std::make_unique<Service>(name, "default", str_args);
844 return true;
845}
846
847bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
848 const std::string& filename, int line,
849 std::string* err) const {
850 return service_ ? service_->HandleLine(args, err) : false;
851}
852
853void ServiceParser::EndSection() {
854 if (service_) {
855 ServiceManager::GetInstance().AddService(std::move(service_));
856 }
857}
858
859bool ServiceParser::IsValidName(const std::string& name) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700860 if (name.size() > 16) {
861 return false;
862 }
863 for (const auto& c : name) {
864 if (!isalnum(c) && (c != '_') && (c != '-')) {
865 return false;
866 }
867 }
868 return true;
869}