blob: f5b8b00a22f0296db9f7b28e70ce96a4571d91a8 [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
Elliott Hughesa3cc6022016-04-12 15:38:27 -0700319bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700320 // 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
Tom Cherrybac32992015-07-31 12:45:25 -0700355 std::string scon;
356 if (!seclabel_.empty()) {
357 scon = seclabel_;
358 } else {
359 char* mycon = nullptr;
360 char* fcon = nullptr;
361
362 INFO("computing context for service '%s'\n", args_[0].c_str());
363 int rc = getcon(&mycon);
364 if (rc < 0) {
365 ERROR("could not get context while starting '%s'\n", name_.c_str());
366 return false;
367 }
368
369 rc = getfilecon(args_[0].c_str(), &fcon);
370 if (rc < 0) {
371 ERROR("could not get context while starting '%s'\n", name_.c_str());
372 free(mycon);
373 return false;
374 }
375
376 char* ret_scon = nullptr;
377 rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
378 &ret_scon);
379 if (rc == 0) {
380 scon = ret_scon;
381 free(ret_scon);
382 }
383 if (rc == 0 && scon == mycon) {
384 ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
385 free(mycon);
386 free(fcon);
387 return false;
388 }
389 free(mycon);
390 free(fcon);
391 if (rc < 0) {
392 ERROR("could not get context while starting '%s'\n", name_.c_str());
393 return false;
394 }
395 }
396
397 NOTICE("Starting service '%s'...\n", name_.c_str());
398
399 pid_t pid = fork();
400 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700401 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700402
403 for (const auto& ei : envvars_) {
404 add_environment(ei.name.c_str(), ei.value.c_str());
405 }
406
407 for (const auto& si : sockets_) {
408 int socket_type = ((si.type == "stream" ? SOCK_STREAM :
409 (si.type == "dgram" ? SOCK_DGRAM :
410 SOCK_SEQPACKET)));
411 const char* socketcon =
412 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
413
414 int s = create_socket(si.name.c_str(), socket_type, si.perm,
415 si.uid, si.gid, socketcon);
416 if (s >= 0) {
417 PublishSocket(si.name, s);
418 }
419 }
420
Anestis Bechtsoudisb702b462016-02-05 16:38:48 +0200421 std::string pid_str = StringPrintf("%d", getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700422 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700423 if (!WriteStringToFile(pid_str, file)) {
Tom Cherrybac32992015-07-31 12:45:25 -0700424 ERROR("couldn't write %s to %s: %s\n",
425 pid_str.c_str(), file.c_str(), strerror(errno));
426 }
427 }
428
429 if (ioprio_class_ != IoSchedClass_NONE) {
430 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
431 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
432 getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
433 }
434 }
435
436 if (needs_console) {
437 setsid();
438 OpenConsole();
439 } else {
440 ZapStdio();
441 }
442
443 setpgid(0, getpid());
444
445 // As requested, set our gid, supplemental gids, and uid.
446 if (gid_) {
447 if (setgid(gid_) != 0) {
448 ERROR("setgid failed: %s\n", strerror(errno));
449 _exit(127);
450 }
451 }
452 if (!supp_gids_.empty()) {
453 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
454 ERROR("setgroups failed: %s\n", strerror(errno));
455 _exit(127);
456 }
457 }
458 if (uid_) {
459 if (setuid(uid_) != 0) {
460 ERROR("setuid failed: %s\n", strerror(errno));
461 _exit(127);
462 }
463 }
464 if (!seclabel_.empty()) {
465 if (setexeccon(seclabel_.c_str()) < 0) {
466 ERROR("cannot setexeccon('%s'): %s\n",
467 seclabel_.c_str(), strerror(errno));
468 _exit(127);
469 }
470 }
471
472 std::vector<char*> strs;
473 for (const auto& s : args_) {
474 strs.push_back(const_cast<char*>(s.c_str()));
475 }
Tom Cherrybac32992015-07-31 12:45:25 -0700476 strs.push_back(nullptr);
477 if (execve(args_[0].c_str(), (char**) &strs[0], (char**) ENV) < 0) {
478 ERROR("cannot execve('%s'): %s\n", args_[0].c_str(), strerror(errno));
479 }
480
481 _exit(127);
482 }
483
484 if (pid < 0) {
485 ERROR("failed to start '%s'\n", name_.c_str());
486 pid_ = 0;
487 return false;
488 }
489
490 time_started_ = gettime();
491 pid_ = pid;
492 flags_ |= SVC_RUNNING;
493
494 if ((flags_ & SVC_EXEC) != 0) {
495 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
496 pid_, uid_, gid_, supp_gids_.size(),
497 !seclabel_.empty() ? seclabel_.c_str() : "default");
498 }
499
500 NotifyStateChange("running");
501 return true;
502}
503
Tom Cherrybac32992015-07-31 12:45:25 -0700504bool Service::StartIfNotDisabled() {
505 if (!(flags_ & SVC_DISABLED)) {
506 return Start();
507 } else {
508 flags_ |= SVC_DISABLED_START;
509 }
510 return true;
511}
512
513bool Service::Enable() {
514 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
515 if (flags_ & SVC_DISABLED_START) {
516 return Start();
517 }
518 return true;
519}
520
521void Service::Reset() {
522 StopOrReset(SVC_RESET);
523}
524
525void Service::Stop() {
526 StopOrReset(SVC_DISABLED);
527}
528
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800529void Service::Terminate() {
530 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
531 flags_ |= SVC_DISABLED;
532 if (pid_) {
533 NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
534 pid_);
535 kill(-pid_, SIGTERM);
536 NotifyStateChange("stopping");
537 }
538}
539
Tom Cherrybac32992015-07-31 12:45:25 -0700540void Service::Restart() {
541 if (flags_ & SVC_RUNNING) {
542 /* Stop, wait, then start the service. */
543 StopOrReset(SVC_RESTART);
544 } else if (!(flags_ & SVC_RESTARTING)) {
545 /* Just start the service since it's not running. */
546 Start();
547 } /* else: Service is restarting anyways. */
548}
549
550void Service::RestartIfNeeded(time_t& process_needs_restart) {
551 time_t next_start_time = time_started_ + 5;
552
553 if (next_start_time <= gettime()) {
554 flags_ &= (~SVC_RESTARTING);
555 Start();
556 return;
557 }
558
559 if ((next_start_time < process_needs_restart) ||
560 (process_needs_restart == 0)) {
561 process_needs_restart = next_start_time;
562 }
563}
564
565/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
566void Service::StopOrReset(int how) {
567 /* The service is still SVC_RUNNING until its process exits, but if it has
568 * already exited it shoudn't attempt a restart yet. */
569 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
570
571 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
572 /* Hrm, an illegal flag. Default to SVC_DISABLED */
573 how = SVC_DISABLED;
574 }
575 /* if the service has not yet started, prevent
576 * it from auto-starting with its class
577 */
578 if (how == SVC_RESET) {
579 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
580 } else {
581 flags_ |= how;
582 }
583
584 if (pid_) {
585 NOTICE("Service '%s' is being killed...\n", name_.c_str());
586 kill(-pid_, SIGKILL);
587 NotifyStateChange("stopping");
588 } else {
589 NotifyStateChange("stopped");
590 }
591}
592
593void Service::ZapStdio() const {
594 int fd;
595 fd = open("/dev/null", O_RDWR);
596 dup2(fd, 0);
597 dup2(fd, 1);
598 dup2(fd, 2);
599 close(fd);
600}
601
602void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200603 int fd = open(console_.c_str(), O_RDWR);
604 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700605 ioctl(fd, TIOCSCTTY, 0);
606 dup2(fd, 0);
607 dup2(fd, 1);
608 dup2(fd, 2);
609 close(fd);
610}
611
612void Service::PublishSocket(const std::string& name, int fd) const {
Tom Cherryb7349902015-08-26 11:43:36 -0700613 std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
614 std::string val = StringPrintf("%d", fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700615 add_environment(key.c_str(), val.c_str());
616
617 /* make sure we don't close-on-exec */
618 fcntl(fd, F_SETFD, 0);
619}
620
621int ServiceManager::exec_count_ = 0;
622
623ServiceManager::ServiceManager() {
624}
625
626ServiceManager& ServiceManager::GetInstance() {
627 static ServiceManager instance;
628 return instance;
629}
630
Tom Cherryb7349902015-08-26 11:43:36 -0700631void ServiceManager::AddService(std::unique_ptr<Service> service) {
632 Service* old_service = FindServiceByName(service->name());
633 if (old_service) {
634 ERROR("ignored duplicate definition of service '%s'",
635 service->name().c_str());
636 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700637 }
Tom Cherryb7349902015-08-26 11:43:36 -0700638 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700639}
640
641Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
642 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
643 // SECLABEL can be a - to denote default
644 std::size_t command_arg = 1;
645 for (std::size_t i = 1; i < args.size(); ++i) {
646 if (args[i] == "--") {
647 command_arg = i + 1;
648 break;
649 }
650 }
651 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
652 ERROR("exec called with too many supplementary group ids\n");
653 return nullptr;
654 }
655
656 if (command_arg >= args.size()) {
657 ERROR("exec called without command\n");
658 return nullptr;
659 }
660 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
661
662 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700663 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700664 unsigned flags = SVC_EXEC | SVC_ONESHOT;
665
666 std::string seclabel = "";
667 if (command_arg > 2 && args[1] != "-") {
668 seclabel = args[1];
669 }
670 uid_t uid = 0;
671 if (command_arg > 3) {
672 uid = decode_uid(args[2].c_str());
673 }
674 gid_t gid = 0;
675 std::vector<gid_t> supp_gids;
676 if (command_arg > 4) {
677 gid = decode_uid(args[3].c_str());
678 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
679 for (size_t i = 0; i < nr_supp_gids; ++i) {
680 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
681 }
682 }
683
684 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
685 supp_gids, seclabel, str_args));
686 if (!svc_p) {
687 ERROR("Couldn't allocate service for exec of '%s'",
688 str_args[0].c_str());
689 return nullptr;
690 }
691 Service* svc = svc_p.get();
692 services_.push_back(std::move(svc_p));
693
694 return svc;
695}
696
697Service* ServiceManager::FindServiceByName(const std::string& name) const {
698 auto svc = std::find_if(services_.begin(), services_.end(),
699 [&name] (const std::unique_ptr<Service>& s) {
700 return name == s->name();
701 });
702 if (svc != services_.end()) {
703 return svc->get();
704 }
705 return nullptr;
706}
707
708Service* ServiceManager::FindServiceByPid(pid_t pid) const {
709 auto svc = std::find_if(services_.begin(), services_.end(),
710 [&pid] (const std::unique_ptr<Service>& s) {
711 return s->pid() == pid;
712 });
713 if (svc != services_.end()) {
714 return svc->get();
715 }
716 return nullptr;
717}
718
719Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
720 auto svc = std::find_if(services_.begin(), services_.end(),
721 [&keychord_id] (const std::unique_ptr<Service>& s) {
722 return s->keychord_id() == keychord_id;
723 });
724
725 if (svc != services_.end()) {
726 return svc->get();
727 }
728 return nullptr;
729}
730
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800731void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700732 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800733 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -0700734 }
735}
736
737void ServiceManager::ForEachServiceInClass(const std::string& classname,
738 void (*func)(Service* svc)) const {
739 for (const auto& s : services_) {
740 if (classname == s->classname()) {
741 func(s.get());
742 }
743 }
744}
745
746void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
747 void (*func)(Service* svc)) const {
748 for (const auto& s : services_) {
749 if (s->flags() & matchflags) {
750 func(s.get());
751 }
752 }
753}
754
Tom Cherryb7349902015-08-26 11:43:36 -0700755void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -0700756 auto svc_it = std::find_if(services_.begin(), services_.end(),
757 [&svc] (const std::unique_ptr<Service>& s) {
758 return svc.name() == s->name();
759 });
760 if (svc_it == services_.end()) {
761 return;
762 }
763
764 services_.erase(svc_it);
765}
766
Tom Cherryb7349902015-08-26 11:43:36 -0700767void ServiceManager::DumpState() const {
768 for (const auto& s : services_) {
769 s->DumpState();
770 }
771 INFO("\n");
772}
773
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800774bool ServiceManager::ReapOneProcess() {
775 int status;
776 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
777 if (pid == 0) {
778 return false;
779 } else if (pid == -1) {
780 ERROR("waitpid failed: %s\n", strerror(errno));
781 return false;
782 }
783
784 Service* svc = FindServiceByPid(pid);
785
786 std::string name;
787 if (svc) {
788 name = android::base::StringPrintf("Service '%s' (pid %d)",
789 svc->name().c_str(), pid);
790 } else {
791 name = android::base::StringPrintf("Untracked pid %d", pid);
792 }
793
794 if (WIFEXITED(status)) {
795 NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
796 } else if (WIFSIGNALED(status)) {
797 NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
798 } else if (WIFSTOPPED(status)) {
799 NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
800 } else {
801 NOTICE("%s state changed", name.c_str());
802 }
803
804 if (!svc) {
805 return true;
806 }
807
808 if (svc->Reap()) {
809 waiting_for_exec = false;
810 RemoveService(*svc);
811 }
812
813 return true;
814}
815
816void ServiceManager::ReapAnyOutstandingChildren() {
817 while (ReapOneProcess()) {
818 }
819}
820
Tom Cherryb7349902015-08-26 11:43:36 -0700821bool ServiceParser::ParseSection(const std::vector<std::string>& args,
822 std::string* err) {
823 if (args.size() < 3) {
824 *err = "services must have a name and a program";
825 return false;
826 }
827
828 const std::string& name = args[1];
829 if (!IsValidName(name)) {
830 *err = StringPrintf("invalid service name '%s'", name.c_str());
831 return false;
832 }
833
834 std::vector<std::string> str_args(args.begin() + 2, args.end());
835 service_ = std::make_unique<Service>(name, "default", str_args);
836 return true;
837}
838
839bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
840 const std::string& filename, int line,
841 std::string* err) const {
842 return service_ ? service_->HandleLine(args, err) : false;
843}
844
845void ServiceParser::EndSection() {
846 if (service_) {
847 ServiceManager::GetInstance().AddService(std::move(service_));
848 }
849}
850
851bool ServiceParser::IsValidName(const std::string& name) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700852 if (name.size() > 16) {
853 return false;
854 }
855 for (const auto& c : name) {
856 if (!isalnum(c) && (c != '_') && (c != '-')) {
857 return false;
858 }
859 }
860 return true;
861}