blob: d917b30e00685cbcd32d55fd3c67366d189d8a5d [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>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070020#include <sys/resource.h>
Tom Cherrybac32992015-07-31 12:45:25 -070021#include <sys/stat.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070022#include <sys/time.h>
Tom Cherrybac32992015-07-31 12:45:25 -070023#include <sys/types.h>
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -080024#include <sys/wait.h>
Tom Cherrybac32992015-07-31 12:45:25 -070025#include <termios.h>
Dan Albertaf9ba4d2015-08-11 16:37:04 -070026#include <unistd.h>
Tom Cherrybac32992015-07-31 12:45:25 -070027
28#include <selinux/selinux.h>
29
Elliott Hughes4f713192015-12-04 22:00:26 -080030#include <android-base/file.h>
31#include <android-base/stringprintf.h>
Tom Cherrybac32992015-07-31 12:45:25 -070032#include <cutils/android_reboot.h>
33#include <cutils/sockets.h>
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070034#include <system/thread_defs.h>
Tom Cherrybac32992015-07-31 12:45:25 -070035
Collin Mullinerf7e79b92016-06-01 21:03:55 +000036#include <processgroup/processgroup.h>
37
Tom Cherrybac32992015-07-31 12:45:25 -070038#include "action.h"
39#include "init.h"
40#include "init_parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070041#include "log.h"
42#include "property_service.h"
43#include "util.h"
44
Tom Cherryb7349902015-08-26 11:43:36 -070045using android::base::StringPrintf;
46using android::base::WriteStringToFile;
47
Tom Cherrybac32992015-07-31 12:45:25 -070048#define CRITICAL_CRASH_THRESHOLD 4 // if we crash >4 times ...
49#define CRITICAL_CRASH_WINDOW (4*60) // ... in 4 minutes, goto recovery
50
51SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
52}
53
54SocketInfo::SocketInfo(const std::string& name, const std::string& type, uid_t uid,
55 gid_t gid, int perm, const std::string& socketcon)
56 : name(name), type(type), uid(uid), gid(gid), perm(perm), socketcon(socketcon) {
57}
58
59ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
60}
61
62ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
63 const std::string& value)
64 : name(name), value(value) {
65}
66
67Service::Service(const std::string& name, const std::string& classname,
68 const std::vector<std::string>& args)
69 : name_(name), classname_(classname), flags_(0), pid_(0), time_started_(0),
70 time_crashed_(0), nr_crashed_(0), uid_(0), gid_(0), seclabel_(""),
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070071 ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), priority_(0), args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -070072 onrestart_.InitSingleTrigger("onrestart");
73}
74
75Service::Service(const std::string& name, const std::string& classname,
76 unsigned flags, uid_t uid, gid_t gid, const std::vector<gid_t>& supp_gids,
77 const std::string& seclabel, const std::vector<std::string>& args)
78 : name_(name), classname_(classname), flags_(flags), pid_(0), time_started_(0),
79 time_crashed_(0), nr_crashed_(0), uid_(uid), gid_(gid), supp_gids_(supp_gids),
Vitalii Tomkiv081705c2016-05-18 17:36:30 -070080 seclabel_(seclabel), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), priority_(0),
81 args_(args) {
Tom Cherrybac32992015-07-31 12:45:25 -070082 onrestart_.InitSingleTrigger("onrestart");
83}
84
85void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherrybac32992015-07-31 12:45:25 -070086 if ((flags_ & SVC_EXEC) != 0) {
87 // 'exec' commands don't have properties tracking their state.
88 return;
89 }
90
Tom Cherryb7349902015-08-26 11:43:36 -070091 std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -070092 if (prop_name.length() >= PROP_NAME_MAX) {
93 // If the property name would be too long, we can't set it.
94 ERROR("Property name \"init.svc.%s\" too long; not setting to %s\n",
95 name_.c_str(), new_state.c_str());
96 return;
97 }
98
99 property_set(prop_name.c_str(), new_state.c_str());
100}
101
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700102void Service::KillProcessGroup(int signal) {
103 NOTICE("Sending signal %d to service '%s' (pid %d) process group...\n",
104 signal, name_.c_str(), pid_);
105 kill(pid_, signal);
106 killProcessGroup(uid_, pid_, signal);
107}
108
Tom Cherrybac32992015-07-31 12:45:25 -0700109bool Service::Reap() {
110 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700111 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700112 }
113
114 // Remove any sockets we may have created.
115 for (const auto& si : sockets_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700116 std::string tmp = StringPrintf(ANDROID_SOCKET_DIR "/%s", si.name.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700117 unlink(tmp.c_str());
118 }
119
120 if (flags_ & SVC_EXEC) {
121 INFO("SVC_EXEC pid %d finished...\n", pid_);
122 return true;
123 }
124
125 pid_ = 0;
126 flags_ &= (~SVC_RUNNING);
127
128 // Oneshot processes go into the disabled state on exit,
129 // except when manually restarted.
130 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
131 flags_ |= SVC_DISABLED;
132 }
133
134 // Disabled and reset processes do not get restarted automatically.
135 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
136 NotifyStateChange("stopped");
137 return false;
138 }
139
140 time_t now = gettime();
141 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
142 if (time_crashed_ + CRITICAL_CRASH_WINDOW >= now) {
143 if (++nr_crashed_ > CRITICAL_CRASH_THRESHOLD) {
144 ERROR("critical process '%s' exited %d times in %d minutes; "
145 "rebooting into recovery mode\n", name_.c_str(),
146 CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
147 android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
148 return false;
149 }
150 } else {
151 time_crashed_ = now;
152 nr_crashed_ = 1;
153 }
154 }
155
156 flags_ &= (~SVC_RESTART);
157 flags_ |= SVC_RESTARTING;
158
159 // Execute all onrestart commands for this service.
160 onrestart_.ExecuteAllCommands();
161
162 NotifyStateChange("restarting");
163 return false;
164}
165
166void Service::DumpState() const {
167 INFO("service %s\n", name_.c_str());
168 INFO(" class '%s'\n", classname_.c_str());
169 INFO(" exec");
170 for (const auto& s : args_) {
171 INFO(" '%s'", s.c_str());
172 }
173 INFO("\n");
174 for (const auto& si : sockets_) {
175 INFO(" socket %s %s 0%o\n", si.name.c_str(), si.type.c_str(), si.perm);
176 }
177}
178
Tom Cherryb7349902015-08-26 11:43:36 -0700179bool Service::HandleClass(const std::vector<std::string>& args, std::string* err) {
180 classname_ = args[1];
181 return true;
182}
Tom Cherrybac32992015-07-31 12:45:25 -0700183
Tom Cherryb7349902015-08-26 11:43:36 -0700184bool Service::HandleConsole(const std::vector<std::string>& args, std::string* err) {
185 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200186 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherryb7349902015-08-26 11:43:36 -0700187 return true;
188}
Tom Cherrybac32992015-07-31 12:45:25 -0700189
Tom Cherryb7349902015-08-26 11:43:36 -0700190bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
191 flags_ |= SVC_CRITICAL;
192 return true;
193}
Tom Cherrybac32992015-07-31 12:45:25 -0700194
Tom Cherryb7349902015-08-26 11:43:36 -0700195bool Service::HandleDisabled(const std::vector<std::string>& args, std::string* err) {
196 flags_ |= SVC_DISABLED;
197 flags_ |= SVC_RC_DISABLED;
198 return true;
199}
Tom Cherrybac32992015-07-31 12:45:25 -0700200
Tom Cherryb7349902015-08-26 11:43:36 -0700201bool Service::HandleGroup(const std::vector<std::string>& args, std::string* err) {
202 gid_ = decode_uid(args[1].c_str());
203 for (std::size_t n = 2; n < args.size(); n++) {
204 supp_gids_.emplace_back(decode_uid(args[n].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700205 }
206 return true;
207}
208
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700209bool Service::HandlePriority(const std::vector<std::string>& args, std::string* err) {
210 priority_ = std::stoi(args[1]);
211
212 if (priority_ < ANDROID_PRIORITY_HIGHEST || priority_ > ANDROID_PRIORITY_LOWEST) {
213 priority_ = 0;
214 *err = StringPrintf("process priority value must be range %d - %d",
215 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
216 return false;
217 }
218
219 return true;
220}
221
Tom Cherryb7349902015-08-26 11:43:36 -0700222bool Service::HandleIoprio(const std::vector<std::string>& args, std::string* err) {
223 ioprio_pri_ = std::stoul(args[2], 0, 8);
224
225 if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
226 *err = "priority value must be range 0 - 7";
227 return false;
228 }
229
230 if (args[1] == "rt") {
231 ioprio_class_ = IoSchedClass_RT;
232 } else if (args[1] == "be") {
233 ioprio_class_ = IoSchedClass_BE;
234 } else if (args[1] == "idle") {
235 ioprio_class_ = IoSchedClass_IDLE;
236 } else {
237 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
238 return false;
239 }
240
241 return true;
242}
243
244bool Service::HandleKeycodes(const std::vector<std::string>& args, std::string* err) {
245 for (std::size_t i = 1; i < args.size(); i++) {
246 keycodes_.emplace_back(std::stoi(args[i]));
247 }
248 return true;
249}
250
251bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
252 flags_ |= SVC_ONESHOT;
253 return true;
254}
255
256bool Service::HandleOnrestart(const std::vector<std::string>& args, std::string* err) {
257 std::vector<std::string> str_args(args.begin() + 1, args.end());
258 onrestart_.AddCommand(str_args, "", 0, err);
259 return true;
260}
261
262bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
263 seclabel_ = args[1];
264 return true;
265}
266
267bool Service::HandleSetenv(const std::vector<std::string>& args, std::string* err) {
268 envvars_.emplace_back(args[1], args[2]);
269 return true;
270}
271
272/* name type perm [ uid gid context ] */
273bool Service::HandleSocket(const std::vector<std::string>& args, std::string* err) {
274 if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
275 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
276 return false;
277 }
278
279 int perm = std::stoul(args[3], 0, 8);
280 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
281 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
282 std::string socketcon = args.size() > 6 ? args[6] : "";
283
284 sockets_.emplace_back(args[1], args[2], uid, gid, perm, socketcon);
285 return true;
286}
287
288bool Service::HandleUser(const std::vector<std::string>& args, std::string* err) {
289 uid_ = decode_uid(args[1].c_str());
290 return true;
291}
292
293bool Service::HandleWritepid(const std::vector<std::string>& args, std::string* err) {
294 writepid_files_.assign(args.begin() + 1, args.end());
295 return true;
296}
297
298class Service::OptionHandlerMap : public KeywordMap<OptionHandler> {
299public:
300 OptionHandlerMap() {
301 }
302private:
303 Map& map() const override;
304};
305
306Service::OptionHandlerMap::Map& Service::OptionHandlerMap::map() const {
307 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
308 static const Map option_handlers = {
309 {"class", {1, 1, &Service::HandleClass}},
Viorel Suman70daa672016-03-21 10:08:07 +0200310 {"console", {0, 1, &Service::HandleConsole}},
Tom Cherryb7349902015-08-26 11:43:36 -0700311 {"critical", {0, 0, &Service::HandleCritical}},
312 {"disabled", {0, 0, &Service::HandleDisabled}},
313 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::HandleGroup}},
314 {"ioprio", {2, 2, &Service::HandleIoprio}},
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700315 {"priority", {1, 1, &Service::HandlePriority}},
Tom Cherryb7349902015-08-26 11:43:36 -0700316 {"keycodes", {1, kMax, &Service::HandleKeycodes}},
317 {"oneshot", {0, 0, &Service::HandleOneshot}},
318 {"onrestart", {1, kMax, &Service::HandleOnrestart}},
319 {"seclabel", {1, 1, &Service::HandleSeclabel}},
320 {"setenv", {2, 2, &Service::HandleSetenv}},
321 {"socket", {3, 6, &Service::HandleSocket}},
322 {"user", {1, 1, &Service::HandleUser}},
323 {"writepid", {1, kMax, &Service::HandleWritepid}},
324 };
325 return option_handlers;
326}
327
328bool Service::HandleLine(const std::vector<std::string>& args, std::string* err) {
329 if (args.empty()) {
330 *err = "option needed, but not provided";
331 return false;
332 }
333
334 static const OptionHandlerMap handler_map;
335 auto handler = handler_map.FindFunction(args[0], args.size() - 1, err);
336
337 if (!handler) {
338 return false;
339 }
340
341 return (this->*handler)(args, err);
342}
343
Elliott Hughesbdeac392016-04-12 15:38:27 -0700344bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700345 // Starting a service removes it from the disabled or reset state and
346 // immediately takes it out of the restarting state if it was in there.
347 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
348 time_started_ = 0;
349
350 // Running processes require no additional work --- if they're in the
351 // process of exiting, we've ensured that they will immediately restart
352 // on exit, unless they are ONESHOT.
353 if (flags_ & SVC_RUNNING) {
354 return false;
355 }
356
357 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200358 if (needs_console) {
359 if (console_.empty()) {
360 console_ = default_console;
361 }
362
363 bool have_console = (open(console_.c_str(), O_RDWR | O_CLOEXEC) != -1);
364 if (!have_console) {
365 ERROR("service '%s' couldn't open console '%s': %s\n",
366 name_.c_str(), console_.c_str(), strerror(errno));
367 flags_ |= SVC_DISABLED;
368 return false;
369 }
Tom Cherrybac32992015-07-31 12:45:25 -0700370 }
371
372 struct stat sb;
373 if (stat(args_[0].c_str(), &sb) == -1) {
374 ERROR("cannot find '%s' (%s), disabling '%s'\n",
375 args_[0].c_str(), strerror(errno), name_.c_str());
376 flags_ |= SVC_DISABLED;
377 return false;
378 }
379
Tom Cherrybac32992015-07-31 12:45:25 -0700380 std::string scon;
381 if (!seclabel_.empty()) {
382 scon = seclabel_;
383 } else {
384 char* mycon = nullptr;
385 char* fcon = nullptr;
386
387 INFO("computing context for service '%s'\n", args_[0].c_str());
388 int rc = getcon(&mycon);
389 if (rc < 0) {
390 ERROR("could not get context while starting '%s'\n", name_.c_str());
391 return false;
392 }
393
394 rc = getfilecon(args_[0].c_str(), &fcon);
395 if (rc < 0) {
396 ERROR("could not get context while starting '%s'\n", name_.c_str());
397 free(mycon);
398 return false;
399 }
400
401 char* ret_scon = nullptr;
402 rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
403 &ret_scon);
404 if (rc == 0) {
405 scon = ret_scon;
406 free(ret_scon);
407 }
408 if (rc == 0 && scon == mycon) {
409 ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
410 free(mycon);
411 free(fcon);
412 return false;
413 }
414 free(mycon);
415 free(fcon);
416 if (rc < 0) {
417 ERROR("could not get context while starting '%s'\n", name_.c_str());
418 return false;
419 }
420 }
421
422 NOTICE("Starting service '%s'...\n", name_.c_str());
423
424 pid_t pid = fork();
425 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700426 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700427
428 for (const auto& ei : envvars_) {
429 add_environment(ei.name.c_str(), ei.value.c_str());
430 }
431
432 for (const auto& si : sockets_) {
433 int socket_type = ((si.type == "stream" ? SOCK_STREAM :
434 (si.type == "dgram" ? SOCK_DGRAM :
435 SOCK_SEQPACKET)));
436 const char* socketcon =
437 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
438
439 int s = create_socket(si.name.c_str(), socket_type, si.perm,
440 si.uid, si.gid, socketcon);
441 if (s >= 0) {
442 PublishSocket(si.name, s);
443 }
444 }
445
Anestis Bechtsoudisb702b462016-02-05 16:38:48 +0200446 std::string pid_str = StringPrintf("%d", getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700447 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700448 if (!WriteStringToFile(pid_str, file)) {
Tom Cherrybac32992015-07-31 12:45:25 -0700449 ERROR("couldn't write %s to %s: %s\n",
450 pid_str.c_str(), file.c_str(), strerror(errno));
451 }
452 }
453
454 if (ioprio_class_ != IoSchedClass_NONE) {
455 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
456 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
457 getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
458 }
459 }
460
461 if (needs_console) {
462 setsid();
463 OpenConsole();
464 } else {
465 ZapStdio();
466 }
467
468 setpgid(0, getpid());
469
470 // As requested, set our gid, supplemental gids, and uid.
471 if (gid_) {
472 if (setgid(gid_) != 0) {
473 ERROR("setgid failed: %s\n", strerror(errno));
474 _exit(127);
475 }
476 }
477 if (!supp_gids_.empty()) {
478 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
479 ERROR("setgroups failed: %s\n", strerror(errno));
480 _exit(127);
481 }
482 }
483 if (uid_) {
484 if (setuid(uid_) != 0) {
485 ERROR("setuid failed: %s\n", strerror(errno));
486 _exit(127);
487 }
488 }
489 if (!seclabel_.empty()) {
490 if (setexeccon(seclabel_.c_str()) < 0) {
491 ERROR("cannot setexeccon('%s'): %s\n",
492 seclabel_.c_str(), strerror(errno));
493 _exit(127);
494 }
495 }
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700496 if (priority_ != 0) {
497 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
498 ERROR("setpriority failed: %s\n", strerror(errno));
499 _exit(127);
500 }
501 }
Tom Cherrybac32992015-07-31 12:45:25 -0700502
Tom Cherrybac35362016-06-07 11:22:00 -0700503 std::vector<std::string> expanded_args;
Tom Cherrybac32992015-07-31 12:45:25 -0700504 std::vector<char*> strs;
Tom Cherrybac35362016-06-07 11:22:00 -0700505 expanded_args.resize(args_.size());
506 strs.push_back(const_cast<char*>(args_[0].c_str()));
507 for (std::size_t i = 1; i < args_.size(); ++i) {
508 if (!expand_props(args_[i], &expanded_args[i])) {
509 ERROR("%s: cannot expand '%s'\n", args_[0].c_str(), args_[i].c_str());
510 _exit(127);
511 }
512 strs.push_back(const_cast<char*>(expanded_args[i].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700513 }
Tom Cherrybac32992015-07-31 12:45:25 -0700514 strs.push_back(nullptr);
Tom Cherrybac35362016-06-07 11:22:00 -0700515
516 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
517 ERROR("cannot execve('%s'): %s\n", strs[0], strerror(errno));
Tom Cherrybac32992015-07-31 12:45:25 -0700518 }
519
520 _exit(127);
521 }
522
523 if (pid < 0) {
524 ERROR("failed to start '%s'\n", name_.c_str());
525 pid_ = 0;
526 return false;
527 }
528
529 time_started_ = gettime();
530 pid_ = pid;
531 flags_ |= SVC_RUNNING;
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700532
533 errno = -createProcessGroup(uid_, pid_);
534 if (errno != 0) {
535 ERROR("createProcessGroup(%d, %d) failed for service '%s': %s\n",
536 uid_, pid_, name_.c_str(), strerror(errno));
537 }
Tom Cherrybac32992015-07-31 12:45:25 -0700538
539 if ((flags_ & SVC_EXEC) != 0) {
540 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
541 pid_, uid_, gid_, supp_gids_.size(),
542 !seclabel_.empty() ? seclabel_.c_str() : "default");
543 }
544
545 NotifyStateChange("running");
546 return true;
547}
548
Tom Cherrybac32992015-07-31 12:45:25 -0700549bool Service::StartIfNotDisabled() {
550 if (!(flags_ & SVC_DISABLED)) {
551 return Start();
552 } else {
553 flags_ |= SVC_DISABLED_START;
554 }
555 return true;
556}
557
558bool Service::Enable() {
559 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
560 if (flags_ & SVC_DISABLED_START) {
561 return Start();
562 }
563 return true;
564}
565
566void Service::Reset() {
567 StopOrReset(SVC_RESET);
568}
569
570void Service::Stop() {
571 StopOrReset(SVC_DISABLED);
572}
573
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800574void Service::Terminate() {
575 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
576 flags_ |= SVC_DISABLED;
577 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700578 KillProcessGroup(SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800579 NotifyStateChange("stopping");
580 }
581}
582
Tom Cherrybac32992015-07-31 12:45:25 -0700583void Service::Restart() {
584 if (flags_ & SVC_RUNNING) {
585 /* Stop, wait, then start the service. */
586 StopOrReset(SVC_RESTART);
587 } else if (!(flags_ & SVC_RESTARTING)) {
588 /* Just start the service since it's not running. */
589 Start();
590 } /* else: Service is restarting anyways. */
591}
592
593void Service::RestartIfNeeded(time_t& process_needs_restart) {
594 time_t next_start_time = time_started_ + 5;
595
596 if (next_start_time <= gettime()) {
597 flags_ &= (~SVC_RESTARTING);
598 Start();
599 return;
600 }
601
602 if ((next_start_time < process_needs_restart) ||
603 (process_needs_restart == 0)) {
604 process_needs_restart = next_start_time;
605 }
606}
607
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700608// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
Tom Cherrybac32992015-07-31 12:45:25 -0700609void Service::StopOrReset(int how) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700610 // The service is still SVC_RUNNING until its process exits, but if it has
611 // already exited it shoudn't attempt a restart yet.
Tom Cherrybac32992015-07-31 12:45:25 -0700612 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
613
614 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700615 // An illegal flag: default to SVC_DISABLED.
Tom Cherrybac32992015-07-31 12:45:25 -0700616 how = SVC_DISABLED;
617 }
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700618
619 // If the service has not yet started, prevent it from auto-starting with its class.
Tom Cherrybac32992015-07-31 12:45:25 -0700620 if (how == SVC_RESET) {
621 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
622 } else {
623 flags_ |= how;
624 }
625
626 if (pid_) {
Elliott Hughesad8e94e2016-06-15 14:49:57 -0700627 KillProcessGroup(SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700628 NotifyStateChange("stopping");
629 } else {
630 NotifyStateChange("stopped");
631 }
632}
633
634void Service::ZapStdio() const {
635 int fd;
636 fd = open("/dev/null", O_RDWR);
637 dup2(fd, 0);
638 dup2(fd, 1);
639 dup2(fd, 2);
640 close(fd);
641}
642
643void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200644 int fd = open(console_.c_str(), O_RDWR);
645 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700646 ioctl(fd, TIOCSCTTY, 0);
647 dup2(fd, 0);
648 dup2(fd, 1);
649 dup2(fd, 2);
650 close(fd);
651}
652
653void Service::PublishSocket(const std::string& name, int fd) const {
Tom Cherryb7349902015-08-26 11:43:36 -0700654 std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
655 std::string val = StringPrintf("%d", fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700656 add_environment(key.c_str(), val.c_str());
657
658 /* make sure we don't close-on-exec */
659 fcntl(fd, F_SETFD, 0);
660}
661
662int ServiceManager::exec_count_ = 0;
663
664ServiceManager::ServiceManager() {
665}
666
667ServiceManager& ServiceManager::GetInstance() {
668 static ServiceManager instance;
669 return instance;
670}
671
Tom Cherryb7349902015-08-26 11:43:36 -0700672void ServiceManager::AddService(std::unique_ptr<Service> service) {
673 Service* old_service = FindServiceByName(service->name());
674 if (old_service) {
675 ERROR("ignored duplicate definition of service '%s'",
676 service->name().c_str());
677 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700678 }
Tom Cherryb7349902015-08-26 11:43:36 -0700679 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700680}
681
682Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
683 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
684 // SECLABEL can be a - to denote default
685 std::size_t command_arg = 1;
686 for (std::size_t i = 1; i < args.size(); ++i) {
687 if (args[i] == "--") {
688 command_arg = i + 1;
689 break;
690 }
691 }
692 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
693 ERROR("exec called with too many supplementary group ids\n");
694 return nullptr;
695 }
696
697 if (command_arg >= args.size()) {
698 ERROR("exec called without command\n");
699 return nullptr;
700 }
701 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
702
703 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700704 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700705 unsigned flags = SVC_EXEC | SVC_ONESHOT;
706
707 std::string seclabel = "";
708 if (command_arg > 2 && args[1] != "-") {
709 seclabel = args[1];
710 }
711 uid_t uid = 0;
712 if (command_arg > 3) {
713 uid = decode_uid(args[2].c_str());
714 }
715 gid_t gid = 0;
716 std::vector<gid_t> supp_gids;
717 if (command_arg > 4) {
718 gid = decode_uid(args[3].c_str());
719 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
720 for (size_t i = 0; i < nr_supp_gids; ++i) {
721 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
722 }
723 }
724
725 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
726 supp_gids, seclabel, str_args));
727 if (!svc_p) {
728 ERROR("Couldn't allocate service for exec of '%s'",
729 str_args[0].c_str());
730 return nullptr;
731 }
732 Service* svc = svc_p.get();
733 services_.push_back(std::move(svc_p));
734
735 return svc;
736}
737
738Service* ServiceManager::FindServiceByName(const std::string& name) const {
739 auto svc = std::find_if(services_.begin(), services_.end(),
740 [&name] (const std::unique_ptr<Service>& s) {
741 return name == s->name();
742 });
743 if (svc != services_.end()) {
744 return svc->get();
745 }
746 return nullptr;
747}
748
749Service* ServiceManager::FindServiceByPid(pid_t pid) const {
750 auto svc = std::find_if(services_.begin(), services_.end(),
751 [&pid] (const std::unique_ptr<Service>& s) {
752 return s->pid() == pid;
753 });
754 if (svc != services_.end()) {
755 return svc->get();
756 }
757 return nullptr;
758}
759
760Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
761 auto svc = std::find_if(services_.begin(), services_.end(),
762 [&keychord_id] (const std::unique_ptr<Service>& s) {
763 return s->keychord_id() == keychord_id;
764 });
765
766 if (svc != services_.end()) {
767 return svc->get();
768 }
769 return nullptr;
770}
771
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800772void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700773 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800774 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -0700775 }
776}
777
778void ServiceManager::ForEachServiceInClass(const std::string& classname,
779 void (*func)(Service* svc)) const {
780 for (const auto& s : services_) {
781 if (classname == s->classname()) {
782 func(s.get());
783 }
784 }
785}
786
787void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
788 void (*func)(Service* svc)) const {
789 for (const auto& s : services_) {
790 if (s->flags() & matchflags) {
791 func(s.get());
792 }
793 }
794}
795
Tom Cherryb7349902015-08-26 11:43:36 -0700796void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -0700797 auto svc_it = std::find_if(services_.begin(), services_.end(),
798 [&svc] (const std::unique_ptr<Service>& s) {
799 return svc.name() == s->name();
800 });
801 if (svc_it == services_.end()) {
802 return;
803 }
804
805 services_.erase(svc_it);
806}
807
Tom Cherryb7349902015-08-26 11:43:36 -0700808void ServiceManager::DumpState() const {
809 for (const auto& s : services_) {
810 s->DumpState();
811 }
812 INFO("\n");
813}
814
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800815bool ServiceManager::ReapOneProcess() {
816 int status;
817 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
818 if (pid == 0) {
819 return false;
820 } else if (pid == -1) {
821 ERROR("waitpid failed: %s\n", strerror(errno));
822 return false;
823 }
824
825 Service* svc = FindServiceByPid(pid);
826
827 std::string name;
828 if (svc) {
829 name = android::base::StringPrintf("Service '%s' (pid %d)",
830 svc->name().c_str(), pid);
831 } else {
832 name = android::base::StringPrintf("Untracked pid %d", pid);
833 }
834
835 if (WIFEXITED(status)) {
836 NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
837 } else if (WIFSIGNALED(status)) {
838 NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
839 } else if (WIFSTOPPED(status)) {
840 NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
841 } else {
842 NOTICE("%s state changed", name.c_str());
843 }
844
845 if (!svc) {
846 return true;
847 }
848
849 if (svc->Reap()) {
850 waiting_for_exec = false;
851 RemoveService(*svc);
852 }
853
854 return true;
855}
856
857void ServiceManager::ReapAnyOutstandingChildren() {
858 while (ReapOneProcess()) {
859 }
860}
861
Tom Cherryb7349902015-08-26 11:43:36 -0700862bool ServiceParser::ParseSection(const std::vector<std::string>& args,
863 std::string* err) {
864 if (args.size() < 3) {
865 *err = "services must have a name and a program";
866 return false;
867 }
868
869 const std::string& name = args[1];
870 if (!IsValidName(name)) {
871 *err = StringPrintf("invalid service name '%s'", name.c_str());
872 return false;
873 }
874
875 std::vector<std::string> str_args(args.begin() + 2, args.end());
876 service_ = std::make_unique<Service>(name, "default", str_args);
877 return true;
878}
879
880bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
881 const std::string& filename, int line,
882 std::string* err) const {
883 return service_ ? service_->HandleLine(args, err) : false;
884}
885
886void ServiceParser::EndSection() {
887 if (service_) {
888 ServiceManager::GetInstance().AddService(std::move(service_));
889 }
890}
891
892bool ServiceParser::IsValidName(const std::string& name) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700893 if (name.size() > 16) {
894 return false;
895 }
896 for (const auto& c : name) {
897 if (!isalnum(c) && (c != '_') && (c != '-')) {
898 return false;
899 }
900 }
901 return true;
902}