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