blob: fad61c6dac100ac7a857772dc27b83b87e86b6e2 [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
Collin Mullinerf7e79b92016-06-01 21:03:55 +000033#include <processgroup/processgroup.h>
34
Tom Cherrybac32992015-07-31 12:45:25 -070035#include "action.h"
36#include "init.h"
37#include "init_parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070038#include "log.h"
39#include "property_service.h"
40#include "util.h"
41
Tom Cherryb7349902015-08-26 11:43:36 -070042using android::base::StringPrintf;
43using android::base::WriteStringToFile;
44
Tom Cherrybac32992015-07-31 12:45:25 -070045#define CRITICAL_CRASH_THRESHOLD 4 // if we crash >4 times ...
46#define CRITICAL_CRASH_WINDOW (4*60) // ... in 4 minutes, goto recovery
47
48SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
49}
50
51SocketInfo::SocketInfo(const std::string& name, const std::string& type, uid_t uid,
52 gid_t gid, int perm, const std::string& socketcon)
53 : name(name), type(type), uid(uid), gid(gid), perm(perm), socketcon(socketcon) {
54}
55
56ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
57}
58
59ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
60 const std::string& value)
61 : name(name), value(value) {
62}
63
64Service::Service(const std::string& name, const std::string& classname,
65 const std::vector<std::string>& args)
66 : name_(name), classname_(classname), flags_(0), pid_(0), time_started_(0),
67 time_crashed_(0), nr_crashed_(0), uid_(0), gid_(0), seclabel_(""),
68 ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
69 onrestart_.InitSingleTrigger("onrestart");
70}
71
72Service::Service(const std::string& name, const std::string& classname,
73 unsigned flags, uid_t uid, gid_t gid, const std::vector<gid_t>& supp_gids,
74 const std::string& seclabel, const std::vector<std::string>& args)
75 : name_(name), classname_(classname), flags_(flags), pid_(0), time_started_(0),
76 time_crashed_(0), nr_crashed_(0), uid_(uid), gid_(gid), supp_gids_(supp_gids),
77 seclabel_(seclabel), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
78 onrestart_.InitSingleTrigger("onrestart");
79}
80
81void Service::NotifyStateChange(const std::string& new_state) const {
Tom Cherrybac32992015-07-31 12:45:25 -070082 if ((flags_ & SVC_EXEC) != 0) {
83 // 'exec' commands don't have properties tracking their state.
84 return;
85 }
86
Tom Cherryb7349902015-08-26 11:43:36 -070087 std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -070088 if (prop_name.length() >= PROP_NAME_MAX) {
89 // If the property name would be too long, we can't set it.
90 ERROR("Property name \"init.svc.%s\" too long; not setting to %s\n",
91 name_.c_str(), new_state.c_str());
92 return;
93 }
94
95 property_set(prop_name.c_str(), new_state.c_str());
96}
97
98bool Service::Reap() {
99 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
100 NOTICE("Service '%s' (pid %d) killing any children in process group\n",
101 name_.c_str(), pid_);
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000102 killProcessGroup(uid_, pid_, SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700103 }
104
105 // Remove any sockets we may have created.
106 for (const auto& si : sockets_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700107 std::string tmp = StringPrintf(ANDROID_SOCKET_DIR "/%s", si.name.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700108 unlink(tmp.c_str());
109 }
110
111 if (flags_ & SVC_EXEC) {
112 INFO("SVC_EXEC pid %d finished...\n", pid_);
113 return true;
114 }
115
116 pid_ = 0;
117 flags_ &= (~SVC_RUNNING);
118
119 // Oneshot processes go into the disabled state on exit,
120 // except when manually restarted.
121 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
122 flags_ |= SVC_DISABLED;
123 }
124
125 // Disabled and reset processes do not get restarted automatically.
126 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
127 NotifyStateChange("stopped");
128 return false;
129 }
130
131 time_t now = gettime();
132 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
133 if (time_crashed_ + CRITICAL_CRASH_WINDOW >= now) {
134 if (++nr_crashed_ > CRITICAL_CRASH_THRESHOLD) {
135 ERROR("critical process '%s' exited %d times in %d minutes; "
136 "rebooting into recovery mode\n", name_.c_str(),
137 CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
138 android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
139 return false;
140 }
141 } else {
142 time_crashed_ = now;
143 nr_crashed_ = 1;
144 }
145 }
146
147 flags_ &= (~SVC_RESTART);
148 flags_ |= SVC_RESTARTING;
149
150 // Execute all onrestart commands for this service.
151 onrestart_.ExecuteAllCommands();
152
153 NotifyStateChange("restarting");
154 return false;
155}
156
157void Service::DumpState() const {
158 INFO("service %s\n", name_.c_str());
159 INFO(" class '%s'\n", classname_.c_str());
160 INFO(" exec");
161 for (const auto& s : args_) {
162 INFO(" '%s'", s.c_str());
163 }
164 INFO("\n");
165 for (const auto& si : sockets_) {
166 INFO(" socket %s %s 0%o\n", si.name.c_str(), si.type.c_str(), si.perm);
167 }
168}
169
Tom Cherryb7349902015-08-26 11:43:36 -0700170bool Service::HandleClass(const std::vector<std::string>& args, std::string* err) {
171 classname_ = args[1];
172 return true;
173}
Tom Cherrybac32992015-07-31 12:45:25 -0700174
Tom Cherryb7349902015-08-26 11:43:36 -0700175bool Service::HandleConsole(const std::vector<std::string>& args, std::string* err) {
176 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200177 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherryb7349902015-08-26 11:43:36 -0700178 return true;
179}
Tom Cherrybac32992015-07-31 12:45:25 -0700180
Tom Cherryb7349902015-08-26 11:43:36 -0700181bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
182 flags_ |= SVC_CRITICAL;
183 return true;
184}
Tom Cherrybac32992015-07-31 12:45:25 -0700185
Tom Cherryb7349902015-08-26 11:43:36 -0700186bool Service::HandleDisabled(const std::vector<std::string>& args, std::string* err) {
187 flags_ |= SVC_DISABLED;
188 flags_ |= SVC_RC_DISABLED;
189 return true;
190}
Tom Cherrybac32992015-07-31 12:45:25 -0700191
Tom Cherryb7349902015-08-26 11:43:36 -0700192bool Service::HandleGroup(const std::vector<std::string>& args, std::string* err) {
193 gid_ = decode_uid(args[1].c_str());
194 for (std::size_t n = 2; n < args.size(); n++) {
195 supp_gids_.emplace_back(decode_uid(args[n].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700196 }
197 return true;
198}
199
Tom Cherryb7349902015-08-26 11:43:36 -0700200bool Service::HandleIoprio(const std::vector<std::string>& args, std::string* err) {
201 ioprio_pri_ = std::stoul(args[2], 0, 8);
202
203 if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
204 *err = "priority value must be range 0 - 7";
205 return false;
206 }
207
208 if (args[1] == "rt") {
209 ioprio_class_ = IoSchedClass_RT;
210 } else if (args[1] == "be") {
211 ioprio_class_ = IoSchedClass_BE;
212 } else if (args[1] == "idle") {
213 ioprio_class_ = IoSchedClass_IDLE;
214 } else {
215 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
216 return false;
217 }
218
219 return true;
220}
221
222bool Service::HandleKeycodes(const std::vector<std::string>& args, std::string* err) {
223 for (std::size_t i = 1; i < args.size(); i++) {
224 keycodes_.emplace_back(std::stoi(args[i]));
225 }
226 return true;
227}
228
229bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
230 flags_ |= SVC_ONESHOT;
231 return true;
232}
233
234bool Service::HandleOnrestart(const std::vector<std::string>& args, std::string* err) {
235 std::vector<std::string> str_args(args.begin() + 1, args.end());
236 onrestart_.AddCommand(str_args, "", 0, err);
237 return true;
238}
239
240bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
241 seclabel_ = args[1];
242 return true;
243}
244
245bool Service::HandleSetenv(const std::vector<std::string>& args, std::string* err) {
246 envvars_.emplace_back(args[1], args[2]);
247 return true;
248}
249
250/* name type perm [ uid gid context ] */
251bool Service::HandleSocket(const std::vector<std::string>& args, std::string* err) {
252 if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
253 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
254 return false;
255 }
256
257 int perm = std::stoul(args[3], 0, 8);
258 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
259 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
260 std::string socketcon = args.size() > 6 ? args[6] : "";
261
262 sockets_.emplace_back(args[1], args[2], uid, gid, perm, socketcon);
263 return true;
264}
265
266bool Service::HandleUser(const std::vector<std::string>& args, std::string* err) {
267 uid_ = decode_uid(args[1].c_str());
268 return true;
269}
270
271bool Service::HandleWritepid(const std::vector<std::string>& args, std::string* err) {
272 writepid_files_.assign(args.begin() + 1, args.end());
273 return true;
274}
275
276class Service::OptionHandlerMap : public KeywordMap<OptionHandler> {
277public:
278 OptionHandlerMap() {
279 }
280private:
281 Map& map() const override;
282};
283
284Service::OptionHandlerMap::Map& Service::OptionHandlerMap::map() const {
285 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
286 static const Map option_handlers = {
287 {"class", {1, 1, &Service::HandleClass}},
Viorel Suman70daa672016-03-21 10:08:07 +0200288 {"console", {0, 1, &Service::HandleConsole}},
Tom Cherryb7349902015-08-26 11:43:36 -0700289 {"critical", {0, 0, &Service::HandleCritical}},
290 {"disabled", {0, 0, &Service::HandleDisabled}},
291 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::HandleGroup}},
292 {"ioprio", {2, 2, &Service::HandleIoprio}},
293 {"keycodes", {1, kMax, &Service::HandleKeycodes}},
294 {"oneshot", {0, 0, &Service::HandleOneshot}},
295 {"onrestart", {1, kMax, &Service::HandleOnrestart}},
296 {"seclabel", {1, 1, &Service::HandleSeclabel}},
297 {"setenv", {2, 2, &Service::HandleSetenv}},
298 {"socket", {3, 6, &Service::HandleSocket}},
299 {"user", {1, 1, &Service::HandleUser}},
300 {"writepid", {1, kMax, &Service::HandleWritepid}},
301 };
302 return option_handlers;
303}
304
305bool Service::HandleLine(const std::vector<std::string>& args, std::string* err) {
306 if (args.empty()) {
307 *err = "option needed, but not provided";
308 return false;
309 }
310
311 static const OptionHandlerMap handler_map;
312 auto handler = handler_map.FindFunction(args[0], args.size() - 1, err);
313
314 if (!handler) {
315 return false;
316 }
317
318 return (this->*handler)(args, err);
319}
320
Elliott Hughesbdeac392016-04-12 15:38:27 -0700321bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700322 // Starting a service removes it from the disabled or reset state and
323 // immediately takes it out of the restarting state if it was in there.
324 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
325 time_started_ = 0;
326
327 // Running processes require no additional work --- if they're in the
328 // process of exiting, we've ensured that they will immediately restart
329 // on exit, unless they are ONESHOT.
330 if (flags_ & SVC_RUNNING) {
331 return false;
332 }
333
334 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200335 if (needs_console) {
336 if (console_.empty()) {
337 console_ = default_console;
338 }
339
340 bool have_console = (open(console_.c_str(), O_RDWR | O_CLOEXEC) != -1);
341 if (!have_console) {
342 ERROR("service '%s' couldn't open console '%s': %s\n",
343 name_.c_str(), console_.c_str(), strerror(errno));
344 flags_ |= SVC_DISABLED;
345 return false;
346 }
Tom Cherrybac32992015-07-31 12:45:25 -0700347 }
348
349 struct stat sb;
350 if (stat(args_[0].c_str(), &sb) == -1) {
351 ERROR("cannot find '%s' (%s), disabling '%s'\n",
352 args_[0].c_str(), strerror(errno), name_.c_str());
353 flags_ |= SVC_DISABLED;
354 return false;
355 }
356
Tom Cherrybac32992015-07-31 12:45:25 -0700357 std::string scon;
358 if (!seclabel_.empty()) {
359 scon = seclabel_;
360 } else {
361 char* mycon = nullptr;
362 char* fcon = nullptr;
363
364 INFO("computing context for service '%s'\n", args_[0].c_str());
365 int rc = getcon(&mycon);
366 if (rc < 0) {
367 ERROR("could not get context while starting '%s'\n", name_.c_str());
368 return false;
369 }
370
371 rc = getfilecon(args_[0].c_str(), &fcon);
372 if (rc < 0) {
373 ERROR("could not get context while starting '%s'\n", name_.c_str());
374 free(mycon);
375 return false;
376 }
377
378 char* ret_scon = nullptr;
379 rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
380 &ret_scon);
381 if (rc == 0) {
382 scon = ret_scon;
383 free(ret_scon);
384 }
385 if (rc == 0 && scon == mycon) {
386 ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
387 free(mycon);
388 free(fcon);
389 return false;
390 }
391 free(mycon);
392 free(fcon);
393 if (rc < 0) {
394 ERROR("could not get context while starting '%s'\n", name_.c_str());
395 return false;
396 }
397 }
398
399 NOTICE("Starting service '%s'...\n", name_.c_str());
400
401 pid_t pid = fork();
402 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700403 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700404
405 for (const auto& ei : envvars_) {
406 add_environment(ei.name.c_str(), ei.value.c_str());
407 }
408
409 for (const auto& si : sockets_) {
410 int socket_type = ((si.type == "stream" ? SOCK_STREAM :
411 (si.type == "dgram" ? SOCK_DGRAM :
412 SOCK_SEQPACKET)));
413 const char* socketcon =
414 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
415
416 int s = create_socket(si.name.c_str(), socket_type, si.perm,
417 si.uid, si.gid, socketcon);
418 if (s >= 0) {
419 PublishSocket(si.name, s);
420 }
421 }
422
Anestis Bechtsoudisb702b462016-02-05 16:38:48 +0200423 std::string pid_str = StringPrintf("%d", getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700424 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700425 if (!WriteStringToFile(pid_str, file)) {
Tom Cherrybac32992015-07-31 12:45:25 -0700426 ERROR("couldn't write %s to %s: %s\n",
427 pid_str.c_str(), file.c_str(), strerror(errno));
428 }
429 }
430
431 if (ioprio_class_ != IoSchedClass_NONE) {
432 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
433 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
434 getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
435 }
436 }
437
438 if (needs_console) {
439 setsid();
440 OpenConsole();
441 } else {
442 ZapStdio();
443 }
444
445 setpgid(0, getpid());
446
447 // As requested, set our gid, supplemental gids, and uid.
448 if (gid_) {
449 if (setgid(gid_) != 0) {
450 ERROR("setgid failed: %s\n", strerror(errno));
451 _exit(127);
452 }
453 }
454 if (!supp_gids_.empty()) {
455 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
456 ERROR("setgroups failed: %s\n", strerror(errno));
457 _exit(127);
458 }
459 }
460 if (uid_) {
461 if (setuid(uid_) != 0) {
462 ERROR("setuid failed: %s\n", strerror(errno));
463 _exit(127);
464 }
465 }
466 if (!seclabel_.empty()) {
467 if (setexeccon(seclabel_.c_str()) < 0) {
468 ERROR("cannot setexeccon('%s'): %s\n",
469 seclabel_.c_str(), strerror(errno));
470 _exit(127);
471 }
472 }
473
Tom Cherrybac35362016-06-07 11:22:00 -0700474 std::vector<std::string> expanded_args;
Tom Cherrybac32992015-07-31 12:45:25 -0700475 std::vector<char*> strs;
Tom Cherrybac35362016-06-07 11:22:00 -0700476 expanded_args.resize(args_.size());
477 strs.push_back(const_cast<char*>(args_[0].c_str()));
478 for (std::size_t i = 1; i < args_.size(); ++i) {
479 if (!expand_props(args_[i], &expanded_args[i])) {
480 ERROR("%s: cannot expand '%s'\n", args_[0].c_str(), args_[i].c_str());
481 _exit(127);
482 }
483 strs.push_back(const_cast<char*>(expanded_args[i].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700484 }
Tom Cherrybac32992015-07-31 12:45:25 -0700485 strs.push_back(nullptr);
Tom Cherrybac35362016-06-07 11:22:00 -0700486
487 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
488 ERROR("cannot execve('%s'): %s\n", strs[0], strerror(errno));
Tom Cherrybac32992015-07-31 12:45:25 -0700489 }
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;
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000503 createProcessGroup(uid_, pid_);
Tom Cherrybac32992015-07-31 12:45:25 -0700504
505 if ((flags_ & SVC_EXEC) != 0) {
506 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
507 pid_, uid_, gid_, supp_gids_.size(),
508 !seclabel_.empty() ? seclabel_.c_str() : "default");
509 }
510
511 NotifyStateChange("running");
512 return true;
513}
514
Tom Cherrybac32992015-07-31 12:45:25 -0700515bool Service::StartIfNotDisabled() {
516 if (!(flags_ & SVC_DISABLED)) {
517 return Start();
518 } else {
519 flags_ |= SVC_DISABLED_START;
520 }
521 return true;
522}
523
524bool Service::Enable() {
525 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
526 if (flags_ & SVC_DISABLED_START) {
527 return Start();
528 }
529 return true;
530}
531
532void Service::Reset() {
533 StopOrReset(SVC_RESET);
534}
535
536void Service::Stop() {
537 StopOrReset(SVC_DISABLED);
538}
539
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800540void Service::Terminate() {
541 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
542 flags_ |= SVC_DISABLED;
543 if (pid_) {
544 NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
545 pid_);
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000546 killProcessGroup(uid_, pid_, SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800547 NotifyStateChange("stopping");
548 }
549}
550
Tom Cherrybac32992015-07-31 12:45:25 -0700551void Service::Restart() {
552 if (flags_ & SVC_RUNNING) {
553 /* Stop, wait, then start the service. */
554 StopOrReset(SVC_RESTART);
555 } else if (!(flags_ & SVC_RESTARTING)) {
556 /* Just start the service since it's not running. */
557 Start();
558 } /* else: Service is restarting anyways. */
559}
560
561void Service::RestartIfNeeded(time_t& process_needs_restart) {
562 time_t next_start_time = time_started_ + 5;
563
564 if (next_start_time <= gettime()) {
565 flags_ &= (~SVC_RESTARTING);
566 Start();
567 return;
568 }
569
570 if ((next_start_time < process_needs_restart) ||
571 (process_needs_restart == 0)) {
572 process_needs_restart = next_start_time;
573 }
574}
575
576/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
577void Service::StopOrReset(int how) {
578 /* The service is still SVC_RUNNING until its process exits, but if it has
579 * already exited it shoudn't attempt a restart yet. */
580 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
581
582 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
583 /* Hrm, an illegal flag. Default to SVC_DISABLED */
584 how = SVC_DISABLED;
585 }
586 /* if the service has not yet started, prevent
587 * it from auto-starting with its class
588 */
589 if (how == SVC_RESET) {
590 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
591 } else {
592 flags_ |= how;
593 }
594
595 if (pid_) {
596 NOTICE("Service '%s' is being killed...\n", name_.c_str());
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000597 killProcessGroup(uid_, pid_, SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700598 NotifyStateChange("stopping");
599 } else {
600 NotifyStateChange("stopped");
601 }
602}
603
604void Service::ZapStdio() const {
605 int fd;
606 fd = open("/dev/null", O_RDWR);
607 dup2(fd, 0);
608 dup2(fd, 1);
609 dup2(fd, 2);
610 close(fd);
611}
612
613void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200614 int fd = open(console_.c_str(), O_RDWR);
615 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}