blob: e509f46e288db74c8b72f757b29edb93dbf2b294 [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;
Viorel Suman70daa672016-03-21 10:08:07 +0200175 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherryb7349902015-08-26 11:43:36 -0700176 return true;
177}
Tom Cherrybac32992015-07-31 12:45:25 -0700178
Tom Cherryb7349902015-08-26 11:43:36 -0700179bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
180 flags_ |= SVC_CRITICAL;
181 return true;
182}
Tom Cherrybac32992015-07-31 12:45:25 -0700183
Tom Cherryb7349902015-08-26 11:43:36 -0700184bool Service::HandleDisabled(const std::vector<std::string>& args, std::string* err) {
185 flags_ |= SVC_DISABLED;
186 flags_ |= SVC_RC_DISABLED;
187 return true;
188}
Tom Cherrybac32992015-07-31 12:45:25 -0700189
Tom Cherryb7349902015-08-26 11:43:36 -0700190bool Service::HandleGroup(const std::vector<std::string>& args, std::string* err) {
191 gid_ = decode_uid(args[1].c_str());
192 for (std::size_t n = 2; n < args.size(); n++) {
193 supp_gids_.emplace_back(decode_uid(args[n].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700194 }
195 return true;
196}
197
Tom Cherryb7349902015-08-26 11:43:36 -0700198bool Service::HandleIoprio(const std::vector<std::string>& args, std::string* err) {
199 ioprio_pri_ = std::stoul(args[2], 0, 8);
200
201 if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
202 *err = "priority value must be range 0 - 7";
203 return false;
204 }
205
206 if (args[1] == "rt") {
207 ioprio_class_ = IoSchedClass_RT;
208 } else if (args[1] == "be") {
209 ioprio_class_ = IoSchedClass_BE;
210 } else if (args[1] == "idle") {
211 ioprio_class_ = IoSchedClass_IDLE;
212 } else {
213 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
214 return false;
215 }
216
217 return true;
218}
219
220bool Service::HandleKeycodes(const std::vector<std::string>& args, std::string* err) {
221 for (std::size_t i = 1; i < args.size(); i++) {
222 keycodes_.emplace_back(std::stoi(args[i]));
223 }
224 return true;
225}
226
227bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
228 flags_ |= SVC_ONESHOT;
229 return true;
230}
231
232bool Service::HandleOnrestart(const std::vector<std::string>& args, std::string* err) {
233 std::vector<std::string> str_args(args.begin() + 1, args.end());
234 onrestart_.AddCommand(str_args, "", 0, err);
235 return true;
236}
237
238bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
239 seclabel_ = args[1];
240 return true;
241}
242
243bool Service::HandleSetenv(const std::vector<std::string>& args, std::string* err) {
244 envvars_.emplace_back(args[1], args[2]);
245 return true;
246}
247
248/* name type perm [ uid gid context ] */
249bool Service::HandleSocket(const std::vector<std::string>& args, std::string* err) {
250 if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
251 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
252 return false;
253 }
254
255 int perm = std::stoul(args[3], 0, 8);
256 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
257 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
258 std::string socketcon = args.size() > 6 ? args[6] : "";
259
260 sockets_.emplace_back(args[1], args[2], uid, gid, perm, socketcon);
261 return true;
262}
263
264bool Service::HandleUser(const std::vector<std::string>& args, std::string* err) {
265 uid_ = decode_uid(args[1].c_str());
266 return true;
267}
268
269bool Service::HandleWritepid(const std::vector<std::string>& args, std::string* err) {
270 writepid_files_.assign(args.begin() + 1, args.end());
271 return true;
272}
273
274class Service::OptionHandlerMap : public KeywordMap<OptionHandler> {
275public:
276 OptionHandlerMap() {
277 }
278private:
279 Map& map() const override;
280};
281
282Service::OptionHandlerMap::Map& Service::OptionHandlerMap::map() const {
283 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
284 static const Map option_handlers = {
285 {"class", {1, 1, &Service::HandleClass}},
Viorel Suman70daa672016-03-21 10:08:07 +0200286 {"console", {0, 1, &Service::HandleConsole}},
Tom Cherryb7349902015-08-26 11:43:36 -0700287 {"critical", {0, 0, &Service::HandleCritical}},
288 {"disabled", {0, 0, &Service::HandleDisabled}},
289 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::HandleGroup}},
290 {"ioprio", {2, 2, &Service::HandleIoprio}},
291 {"keycodes", {1, kMax, &Service::HandleKeycodes}},
292 {"oneshot", {0, 0, &Service::HandleOneshot}},
293 {"onrestart", {1, kMax, &Service::HandleOnrestart}},
294 {"seclabel", {1, 1, &Service::HandleSeclabel}},
295 {"setenv", {2, 2, &Service::HandleSetenv}},
296 {"socket", {3, 6, &Service::HandleSocket}},
297 {"user", {1, 1, &Service::HandleUser}},
298 {"writepid", {1, kMax, &Service::HandleWritepid}},
299 };
300 return option_handlers;
301}
302
303bool Service::HandleLine(const std::vector<std::string>& args, std::string* err) {
304 if (args.empty()) {
305 *err = "option needed, but not provided";
306 return false;
307 }
308
309 static const OptionHandlerMap handler_map;
310 auto handler = handler_map.FindFunction(args[0], args.size() - 1, err);
311
312 if (!handler) {
313 return false;
314 }
315
316 return (this->*handler)(args, err);
317}
318
Tom Cherrybac32992015-07-31 12:45:25 -0700319bool Service::Start(const std::vector<std::string>& dynamic_args) {
320 // Starting a service removes it from the disabled or reset state and
321 // immediately takes it out of the restarting state if it was in there.
322 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
323 time_started_ = 0;
324
325 // Running processes require no additional work --- if they're in the
326 // process of exiting, we've ensured that they will immediately restart
327 // on exit, unless they are ONESHOT.
328 if (flags_ & SVC_RUNNING) {
329 return false;
330 }
331
332 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200333 if (needs_console) {
334 if (console_.empty()) {
335 console_ = default_console;
336 }
337
338 bool have_console = (open(console_.c_str(), O_RDWR | O_CLOEXEC) != -1);
339 if (!have_console) {
340 ERROR("service '%s' couldn't open console '%s': %s\n",
341 name_.c_str(), console_.c_str(), strerror(errno));
342 flags_ |= SVC_DISABLED;
343 return false;
344 }
Tom Cherrybac32992015-07-31 12:45:25 -0700345 }
346
347 struct stat sb;
348 if (stat(args_[0].c_str(), &sb) == -1) {
349 ERROR("cannot find '%s' (%s), disabling '%s'\n",
350 args_[0].c_str(), strerror(errno), name_.c_str());
351 flags_ |= SVC_DISABLED;
352 return false;
353 }
354
355 if ((!(flags_ & SVC_ONESHOT)) && !dynamic_args.empty()) {
356 ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
357 args_[0].c_str());
358 flags_ |= SVC_DISABLED;
359 return false;
360 }
361
362 std::string scon;
363 if (!seclabel_.empty()) {
364 scon = seclabel_;
365 } else {
366 char* mycon = nullptr;
367 char* fcon = nullptr;
368
369 INFO("computing context for service '%s'\n", args_[0].c_str());
370 int rc = getcon(&mycon);
371 if (rc < 0) {
372 ERROR("could not get context while starting '%s'\n", name_.c_str());
373 return false;
374 }
375
376 rc = getfilecon(args_[0].c_str(), &fcon);
377 if (rc < 0) {
378 ERROR("could not get context while starting '%s'\n", name_.c_str());
379 free(mycon);
380 return false;
381 }
382
383 char* ret_scon = nullptr;
384 rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
385 &ret_scon);
386 if (rc == 0) {
387 scon = ret_scon;
388 free(ret_scon);
389 }
390 if (rc == 0 && scon == mycon) {
391 ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
392 free(mycon);
393 free(fcon);
394 return false;
395 }
396 free(mycon);
397 free(fcon);
398 if (rc < 0) {
399 ERROR("could not get context while starting '%s'\n", name_.c_str());
400 return false;
401 }
402 }
403
404 NOTICE("Starting service '%s'...\n", name_.c_str());
405
406 pid_t pid = fork();
407 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700408 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700409
410 for (const auto& ei : envvars_) {
411 add_environment(ei.name.c_str(), ei.value.c_str());
412 }
413
414 for (const auto& si : sockets_) {
415 int socket_type = ((si.type == "stream" ? SOCK_STREAM :
416 (si.type == "dgram" ? SOCK_DGRAM :
417 SOCK_SEQPACKET)));
418 const char* socketcon =
419 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
420
421 int s = create_socket(si.name.c_str(), socket_type, si.perm,
422 si.uid, si.gid, socketcon);
423 if (s >= 0) {
424 PublishSocket(si.name, s);
425 }
426 }
427
Anestis Bechtsoudisb702b462016-02-05 16:38:48 +0200428 std::string pid_str = StringPrintf("%d", getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700429 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700430 if (!WriteStringToFile(pid_str, file)) {
Tom Cherrybac32992015-07-31 12:45:25 -0700431 ERROR("couldn't write %s to %s: %s\n",
432 pid_str.c_str(), file.c_str(), strerror(errno));
433 }
434 }
435
436 if (ioprio_class_ != IoSchedClass_NONE) {
437 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
438 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
439 getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
440 }
441 }
442
443 if (needs_console) {
444 setsid();
445 OpenConsole();
446 } else {
447 ZapStdio();
448 }
449
450 setpgid(0, getpid());
451
452 // As requested, set our gid, supplemental gids, and uid.
453 if (gid_) {
454 if (setgid(gid_) != 0) {
455 ERROR("setgid failed: %s\n", strerror(errno));
456 _exit(127);
457 }
458 }
459 if (!supp_gids_.empty()) {
460 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
461 ERROR("setgroups failed: %s\n", strerror(errno));
462 _exit(127);
463 }
464 }
465 if (uid_) {
466 if (setuid(uid_) != 0) {
467 ERROR("setuid failed: %s\n", strerror(errno));
468 _exit(127);
469 }
470 }
471 if (!seclabel_.empty()) {
472 if (setexeccon(seclabel_.c_str()) < 0) {
473 ERROR("cannot setexeccon('%s'): %s\n",
474 seclabel_.c_str(), strerror(errno));
475 _exit(127);
476 }
477 }
478
479 std::vector<char*> strs;
480 for (const auto& s : args_) {
481 strs.push_back(const_cast<char*>(s.c_str()));
482 }
483 for (const auto& s : dynamic_args) {
484 strs.push_back(const_cast<char*>(s.c_str()));
485 }
486 strs.push_back(nullptr);
487 if (execve(args_[0].c_str(), (char**) &strs[0], (char**) ENV) < 0) {
488 ERROR("cannot execve('%s'): %s\n", args_[0].c_str(), strerror(errno));
489 }
490
491 _exit(127);
492 }
493
494 if (pid < 0) {
495 ERROR("failed to start '%s'\n", name_.c_str());
496 pid_ = 0;
497 return false;
498 }
499
500 time_started_ = gettime();
501 pid_ = pid;
502 flags_ |= SVC_RUNNING;
503
504 if ((flags_ & SVC_EXEC) != 0) {
505 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
506 pid_, uid_, gid_, supp_gids_.size(),
507 !seclabel_.empty() ? seclabel_.c_str() : "default");
508 }
509
510 NotifyStateChange("running");
511 return true;
512}
513
514bool Service::Start() {
515 const std::vector<std::string> null_dynamic_args;
516 return Start(null_dynamic_args);
517}
518
519bool Service::StartIfNotDisabled() {
520 if (!(flags_ & SVC_DISABLED)) {
521 return Start();
522 } else {
523 flags_ |= SVC_DISABLED_START;
524 }
525 return true;
526}
527
528bool Service::Enable() {
529 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
530 if (flags_ & SVC_DISABLED_START) {
531 return Start();
532 }
533 return true;
534}
535
536void Service::Reset() {
537 StopOrReset(SVC_RESET);
538}
539
540void Service::Stop() {
541 StopOrReset(SVC_DISABLED);
542}
543
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800544void Service::Terminate() {
545 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
546 flags_ |= SVC_DISABLED;
547 if (pid_) {
548 NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
549 pid_);
550 kill(-pid_, SIGTERM);
551 NotifyStateChange("stopping");
552 }
553}
554
Tom Cherrybac32992015-07-31 12:45:25 -0700555void Service::Restart() {
556 if (flags_ & SVC_RUNNING) {
557 /* Stop, wait, then start the service. */
558 StopOrReset(SVC_RESTART);
559 } else if (!(flags_ & SVC_RESTARTING)) {
560 /* Just start the service since it's not running. */
561 Start();
562 } /* else: Service is restarting anyways. */
563}
564
565void Service::RestartIfNeeded(time_t& process_needs_restart) {
566 time_t next_start_time = time_started_ + 5;
567
568 if (next_start_time <= gettime()) {
569 flags_ &= (~SVC_RESTARTING);
570 Start();
571 return;
572 }
573
574 if ((next_start_time < process_needs_restart) ||
575 (process_needs_restart == 0)) {
576 process_needs_restart = next_start_time;
577 }
578}
579
580/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
581void Service::StopOrReset(int how) {
582 /* The service is still SVC_RUNNING until its process exits, but if it has
583 * already exited it shoudn't attempt a restart yet. */
584 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
585
586 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
587 /* Hrm, an illegal flag. Default to SVC_DISABLED */
588 how = SVC_DISABLED;
589 }
590 /* if the service has not yet started, prevent
591 * it from auto-starting with its class
592 */
593 if (how == SVC_RESET) {
594 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
595 } else {
596 flags_ |= how;
597 }
598
599 if (pid_) {
600 NOTICE("Service '%s' is being killed...\n", name_.c_str());
601 kill(-pid_, SIGKILL);
602 NotifyStateChange("stopping");
603 } else {
604 NotifyStateChange("stopped");
605 }
606}
607
608void Service::ZapStdio() const {
609 int fd;
610 fd = open("/dev/null", O_RDWR);
611 dup2(fd, 0);
612 dup2(fd, 1);
613 dup2(fd, 2);
614 close(fd);
615}
616
617void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200618 int fd = open(console_.c_str(), O_RDWR);
619 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700620 ioctl(fd, TIOCSCTTY, 0);
621 dup2(fd, 0);
622 dup2(fd, 1);
623 dup2(fd, 2);
624 close(fd);
625}
626
627void Service::PublishSocket(const std::string& name, int fd) const {
Tom Cherryb7349902015-08-26 11:43:36 -0700628 std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
629 std::string val = StringPrintf("%d", fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700630 add_environment(key.c_str(), val.c_str());
631
632 /* make sure we don't close-on-exec */
633 fcntl(fd, F_SETFD, 0);
634}
635
636int ServiceManager::exec_count_ = 0;
637
638ServiceManager::ServiceManager() {
639}
640
641ServiceManager& ServiceManager::GetInstance() {
642 static ServiceManager instance;
643 return instance;
644}
645
Tom Cherryb7349902015-08-26 11:43:36 -0700646void ServiceManager::AddService(std::unique_ptr<Service> service) {
647 Service* old_service = FindServiceByName(service->name());
648 if (old_service) {
649 ERROR("ignored duplicate definition of service '%s'",
650 service->name().c_str());
651 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700652 }
Tom Cherryb7349902015-08-26 11:43:36 -0700653 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700654}
655
656Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
657 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
658 // SECLABEL can be a - to denote default
659 std::size_t command_arg = 1;
660 for (std::size_t i = 1; i < args.size(); ++i) {
661 if (args[i] == "--") {
662 command_arg = i + 1;
663 break;
664 }
665 }
666 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
667 ERROR("exec called with too many supplementary group ids\n");
668 return nullptr;
669 }
670
671 if (command_arg >= args.size()) {
672 ERROR("exec called without command\n");
673 return nullptr;
674 }
675 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
676
677 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700678 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700679 unsigned flags = SVC_EXEC | SVC_ONESHOT;
680
681 std::string seclabel = "";
682 if (command_arg > 2 && args[1] != "-") {
683 seclabel = args[1];
684 }
685 uid_t uid = 0;
686 if (command_arg > 3) {
687 uid = decode_uid(args[2].c_str());
688 }
689 gid_t gid = 0;
690 std::vector<gid_t> supp_gids;
691 if (command_arg > 4) {
692 gid = decode_uid(args[3].c_str());
693 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
694 for (size_t i = 0; i < nr_supp_gids; ++i) {
695 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
696 }
697 }
698
699 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
700 supp_gids, seclabel, str_args));
701 if (!svc_p) {
702 ERROR("Couldn't allocate service for exec of '%s'",
703 str_args[0].c_str());
704 return nullptr;
705 }
706 Service* svc = svc_p.get();
707 services_.push_back(std::move(svc_p));
708
709 return svc;
710}
711
712Service* ServiceManager::FindServiceByName(const std::string& name) const {
713 auto svc = std::find_if(services_.begin(), services_.end(),
714 [&name] (const std::unique_ptr<Service>& s) {
715 return name == s->name();
716 });
717 if (svc != services_.end()) {
718 return svc->get();
719 }
720 return nullptr;
721}
722
723Service* ServiceManager::FindServiceByPid(pid_t pid) const {
724 auto svc = std::find_if(services_.begin(), services_.end(),
725 [&pid] (const std::unique_ptr<Service>& s) {
726 return s->pid() == pid;
727 });
728 if (svc != services_.end()) {
729 return svc->get();
730 }
731 return nullptr;
732}
733
734Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
735 auto svc = std::find_if(services_.begin(), services_.end(),
736 [&keychord_id] (const std::unique_ptr<Service>& s) {
737 return s->keychord_id() == keychord_id;
738 });
739
740 if (svc != services_.end()) {
741 return svc->get();
742 }
743 return nullptr;
744}
745
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800746void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700747 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800748 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -0700749 }
750}
751
752void ServiceManager::ForEachServiceInClass(const std::string& classname,
753 void (*func)(Service* svc)) const {
754 for (const auto& s : services_) {
755 if (classname == s->classname()) {
756 func(s.get());
757 }
758 }
759}
760
761void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
762 void (*func)(Service* svc)) const {
763 for (const auto& s : services_) {
764 if (s->flags() & matchflags) {
765 func(s.get());
766 }
767 }
768}
769
Tom Cherryb7349902015-08-26 11:43:36 -0700770void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -0700771 auto svc_it = std::find_if(services_.begin(), services_.end(),
772 [&svc] (const std::unique_ptr<Service>& s) {
773 return svc.name() == s->name();
774 });
775 if (svc_it == services_.end()) {
776 return;
777 }
778
779 services_.erase(svc_it);
780}
781
Tom Cherryb7349902015-08-26 11:43:36 -0700782void ServiceManager::DumpState() const {
783 for (const auto& s : services_) {
784 s->DumpState();
785 }
786 INFO("\n");
787}
788
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800789bool ServiceManager::ReapOneProcess() {
790 int status;
791 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
792 if (pid == 0) {
793 return false;
794 } else if (pid == -1) {
795 ERROR("waitpid failed: %s\n", strerror(errno));
796 return false;
797 }
798
799 Service* svc = FindServiceByPid(pid);
800
801 std::string name;
802 if (svc) {
803 name = android::base::StringPrintf("Service '%s' (pid %d)",
804 svc->name().c_str(), pid);
805 } else {
806 name = android::base::StringPrintf("Untracked pid %d", pid);
807 }
808
809 if (WIFEXITED(status)) {
810 NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
811 } else if (WIFSIGNALED(status)) {
812 NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
813 } else if (WIFSTOPPED(status)) {
814 NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
815 } else {
816 NOTICE("%s state changed", name.c_str());
817 }
818
819 if (!svc) {
820 return true;
821 }
822
823 if (svc->Reap()) {
824 waiting_for_exec = false;
825 RemoveService(*svc);
826 }
827
828 return true;
829}
830
831void ServiceManager::ReapAnyOutstandingChildren() {
832 while (ReapOneProcess()) {
833 }
834}
835
Tom Cherryb7349902015-08-26 11:43:36 -0700836bool ServiceParser::ParseSection(const std::vector<std::string>& args,
837 std::string* err) {
838 if (args.size() < 3) {
839 *err = "services must have a name and a program";
840 return false;
841 }
842
843 const std::string& name = args[1];
844 if (!IsValidName(name)) {
845 *err = StringPrintf("invalid service name '%s'", name.c_str());
846 return false;
847 }
848
849 std::vector<std::string> str_args(args.begin() + 2, args.end());
850 service_ = std::make_unique<Service>(name, "default", str_args);
851 return true;
852}
853
854bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
855 const std::string& filename, int line,
856 std::string* err) const {
857 return service_ ? service_->HandleLine(args, err) : false;
858}
859
860void ServiceParser::EndSection() {
861 if (service_) {
862 ServiceManager::GetInstance().AddService(std::move(service_));
863 }
864}
865
866bool ServiceParser::IsValidName(const std::string& name) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700867 if (name.size() > 16) {
868 return false;
869 }
870 for (const auto& c : name) {
871 if (!isalnum(c) && (c != '_') && (c != '-')) {
872 return false;
873 }
874 }
875 return true;
876}