blob: 4ea8936d74952e577c2ce65e1bc2cf5e2e68b07a [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
102bool Service::Reap() {
103 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
104 NOTICE("Service '%s' (pid %d) killing any children in process group\n",
105 name_.c_str(), pid_);
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000106 killProcessGroup(uid_, pid_, SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700107 }
108
109 // Remove any sockets we may have created.
110 for (const auto& si : sockets_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700111 std::string tmp = StringPrintf(ANDROID_SOCKET_DIR "/%s", si.name.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700112 unlink(tmp.c_str());
113 }
114
115 if (flags_ & SVC_EXEC) {
116 INFO("SVC_EXEC pid %d finished...\n", pid_);
117 return true;
118 }
119
120 pid_ = 0;
121 flags_ &= (~SVC_RUNNING);
122
123 // Oneshot processes go into the disabled state on exit,
124 // except when manually restarted.
125 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
126 flags_ |= SVC_DISABLED;
127 }
128
129 // Disabled and reset processes do not get restarted automatically.
130 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
131 NotifyStateChange("stopped");
132 return false;
133 }
134
135 time_t now = gettime();
136 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
137 if (time_crashed_ + CRITICAL_CRASH_WINDOW >= now) {
138 if (++nr_crashed_ > CRITICAL_CRASH_THRESHOLD) {
139 ERROR("critical process '%s' exited %d times in %d minutes; "
140 "rebooting into recovery mode\n", name_.c_str(),
141 CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
142 android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
143 return false;
144 }
145 } else {
146 time_crashed_ = now;
147 nr_crashed_ = 1;
148 }
149 }
150
151 flags_ &= (~SVC_RESTART);
152 flags_ |= SVC_RESTARTING;
153
154 // Execute all onrestart commands for this service.
155 onrestart_.ExecuteAllCommands();
156
157 NotifyStateChange("restarting");
158 return false;
159}
160
161void Service::DumpState() const {
162 INFO("service %s\n", name_.c_str());
163 INFO(" class '%s'\n", classname_.c_str());
164 INFO(" exec");
165 for (const auto& s : args_) {
166 INFO(" '%s'", s.c_str());
167 }
168 INFO("\n");
169 for (const auto& si : sockets_) {
170 INFO(" socket %s %s 0%o\n", si.name.c_str(), si.type.c_str(), si.perm);
171 }
172}
173
Tom Cherryb7349902015-08-26 11:43:36 -0700174bool Service::HandleClass(const std::vector<std::string>& args, std::string* err) {
175 classname_ = args[1];
176 return true;
177}
Tom Cherrybac32992015-07-31 12:45:25 -0700178
Tom Cherryb7349902015-08-26 11:43:36 -0700179bool Service::HandleConsole(const std::vector<std::string>& args, std::string* err) {
180 flags_ |= SVC_CONSOLE;
Viorel Suman70daa672016-03-21 10:08:07 +0200181 console_ = args.size() > 1 ? "/dev/" + args[1] : "";
Tom Cherryb7349902015-08-26 11:43:36 -0700182 return true;
183}
Tom Cherrybac32992015-07-31 12:45:25 -0700184
Tom Cherryb7349902015-08-26 11:43:36 -0700185bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
186 flags_ |= SVC_CRITICAL;
187 return true;
188}
Tom Cherrybac32992015-07-31 12:45:25 -0700189
Tom Cherryb7349902015-08-26 11:43:36 -0700190bool Service::HandleDisabled(const std::vector<std::string>& args, std::string* err) {
191 flags_ |= SVC_DISABLED;
192 flags_ |= SVC_RC_DISABLED;
193 return true;
194}
Tom Cherrybac32992015-07-31 12:45:25 -0700195
Tom Cherryb7349902015-08-26 11:43:36 -0700196bool Service::HandleGroup(const std::vector<std::string>& args, std::string* err) {
197 gid_ = decode_uid(args[1].c_str());
198 for (std::size_t n = 2; n < args.size(); n++) {
199 supp_gids_.emplace_back(decode_uid(args[n].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700200 }
201 return true;
202}
203
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700204bool Service::HandlePriority(const std::vector<std::string>& args, std::string* err) {
205 priority_ = std::stoi(args[1]);
206
207 if (priority_ < ANDROID_PRIORITY_HIGHEST || priority_ > ANDROID_PRIORITY_LOWEST) {
208 priority_ = 0;
209 *err = StringPrintf("process priority value must be range %d - %d",
210 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
211 return false;
212 }
213
214 return true;
215}
216
Tom Cherryb7349902015-08-26 11:43:36 -0700217bool Service::HandleIoprio(const std::vector<std::string>& args, std::string* err) {
218 ioprio_pri_ = std::stoul(args[2], 0, 8);
219
220 if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
221 *err = "priority value must be range 0 - 7";
222 return false;
223 }
224
225 if (args[1] == "rt") {
226 ioprio_class_ = IoSchedClass_RT;
227 } else if (args[1] == "be") {
228 ioprio_class_ = IoSchedClass_BE;
229 } else if (args[1] == "idle") {
230 ioprio_class_ = IoSchedClass_IDLE;
231 } else {
232 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
233 return false;
234 }
235
236 return true;
237}
238
239bool Service::HandleKeycodes(const std::vector<std::string>& args, std::string* err) {
240 for (std::size_t i = 1; i < args.size(); i++) {
241 keycodes_.emplace_back(std::stoi(args[i]));
242 }
243 return true;
244}
245
246bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
247 flags_ |= SVC_ONESHOT;
248 return true;
249}
250
251bool Service::HandleOnrestart(const std::vector<std::string>& args, std::string* err) {
252 std::vector<std::string> str_args(args.begin() + 1, args.end());
253 onrestart_.AddCommand(str_args, "", 0, err);
254 return true;
255}
256
257bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
258 seclabel_ = args[1];
259 return true;
260}
261
262bool Service::HandleSetenv(const std::vector<std::string>& args, std::string* err) {
263 envvars_.emplace_back(args[1], args[2]);
264 return true;
265}
266
267/* name type perm [ uid gid context ] */
268bool Service::HandleSocket(const std::vector<std::string>& args, std::string* err) {
269 if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
270 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
271 return false;
272 }
273
274 int perm = std::stoul(args[3], 0, 8);
275 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
276 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
277 std::string socketcon = args.size() > 6 ? args[6] : "";
278
279 sockets_.emplace_back(args[1], args[2], uid, gid, perm, socketcon);
280 return true;
281}
282
283bool Service::HandleUser(const std::vector<std::string>& args, std::string* err) {
284 uid_ = decode_uid(args[1].c_str());
285 return true;
286}
287
288bool Service::HandleWritepid(const std::vector<std::string>& args, std::string* err) {
289 writepid_files_.assign(args.begin() + 1, args.end());
290 return true;
291}
292
293class Service::OptionHandlerMap : public KeywordMap<OptionHandler> {
294public:
295 OptionHandlerMap() {
296 }
297private:
298 Map& map() const override;
299};
300
301Service::OptionHandlerMap::Map& Service::OptionHandlerMap::map() const {
302 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
303 static const Map option_handlers = {
304 {"class", {1, 1, &Service::HandleClass}},
Viorel Suman70daa672016-03-21 10:08:07 +0200305 {"console", {0, 1, &Service::HandleConsole}},
Tom Cherryb7349902015-08-26 11:43:36 -0700306 {"critical", {0, 0, &Service::HandleCritical}},
307 {"disabled", {0, 0, &Service::HandleDisabled}},
308 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::HandleGroup}},
309 {"ioprio", {2, 2, &Service::HandleIoprio}},
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700310 {"priority", {1, 1, &Service::HandlePriority}},
Tom Cherryb7349902015-08-26 11:43:36 -0700311 {"keycodes", {1, kMax, &Service::HandleKeycodes}},
312 {"oneshot", {0, 0, &Service::HandleOneshot}},
313 {"onrestart", {1, kMax, &Service::HandleOnrestart}},
314 {"seclabel", {1, 1, &Service::HandleSeclabel}},
315 {"setenv", {2, 2, &Service::HandleSetenv}},
316 {"socket", {3, 6, &Service::HandleSocket}},
317 {"user", {1, 1, &Service::HandleUser}},
318 {"writepid", {1, kMax, &Service::HandleWritepid}},
319 };
320 return option_handlers;
321}
322
323bool Service::HandleLine(const std::vector<std::string>& args, std::string* err) {
324 if (args.empty()) {
325 *err = "option needed, but not provided";
326 return false;
327 }
328
329 static const OptionHandlerMap handler_map;
330 auto handler = handler_map.FindFunction(args[0], args.size() - 1, err);
331
332 if (!handler) {
333 return false;
334 }
335
336 return (this->*handler)(args, err);
337}
338
Elliott Hughesbdeac392016-04-12 15:38:27 -0700339bool Service::Start() {
Tom Cherrybac32992015-07-31 12:45:25 -0700340 // Starting a service removes it from the disabled or reset state and
341 // immediately takes it out of the restarting state if it was in there.
342 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
343 time_started_ = 0;
344
345 // Running processes require no additional work --- if they're in the
346 // process of exiting, we've ensured that they will immediately restart
347 // on exit, unless they are ONESHOT.
348 if (flags_ & SVC_RUNNING) {
349 return false;
350 }
351
352 bool needs_console = (flags_ & SVC_CONSOLE);
Viorel Suman70daa672016-03-21 10:08:07 +0200353 if (needs_console) {
354 if (console_.empty()) {
355 console_ = default_console;
356 }
357
358 bool have_console = (open(console_.c_str(), O_RDWR | O_CLOEXEC) != -1);
359 if (!have_console) {
360 ERROR("service '%s' couldn't open console '%s': %s\n",
361 name_.c_str(), console_.c_str(), strerror(errno));
362 flags_ |= SVC_DISABLED;
363 return false;
364 }
Tom Cherrybac32992015-07-31 12:45:25 -0700365 }
366
367 struct stat sb;
368 if (stat(args_[0].c_str(), &sb) == -1) {
369 ERROR("cannot find '%s' (%s), disabling '%s'\n",
370 args_[0].c_str(), strerror(errno), name_.c_str());
371 flags_ |= SVC_DISABLED;
372 return false;
373 }
374
Tom Cherrybac32992015-07-31 12:45:25 -0700375 std::string scon;
376 if (!seclabel_.empty()) {
377 scon = seclabel_;
378 } else {
379 char* mycon = nullptr;
380 char* fcon = nullptr;
381
382 INFO("computing context for service '%s'\n", args_[0].c_str());
383 int rc = getcon(&mycon);
384 if (rc < 0) {
385 ERROR("could not get context while starting '%s'\n", name_.c_str());
386 return false;
387 }
388
389 rc = getfilecon(args_[0].c_str(), &fcon);
390 if (rc < 0) {
391 ERROR("could not get context while starting '%s'\n", name_.c_str());
392 free(mycon);
393 return false;
394 }
395
396 char* ret_scon = nullptr;
397 rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
398 &ret_scon);
399 if (rc == 0) {
400 scon = ret_scon;
401 free(ret_scon);
402 }
403 if (rc == 0 && scon == mycon) {
404 ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
405 free(mycon);
406 free(fcon);
407 return false;
408 }
409 free(mycon);
410 free(fcon);
411 if (rc < 0) {
412 ERROR("could not get context while starting '%s'\n", name_.c_str());
413 return false;
414 }
415 }
416
417 NOTICE("Starting service '%s'...\n", name_.c_str());
418
419 pid_t pid = fork();
420 if (pid == 0) {
Tom Cherrybac32992015-07-31 12:45:25 -0700421 umask(077);
Tom Cherrybac32992015-07-31 12:45:25 -0700422
423 for (const auto& ei : envvars_) {
424 add_environment(ei.name.c_str(), ei.value.c_str());
425 }
426
427 for (const auto& si : sockets_) {
428 int socket_type = ((si.type == "stream" ? SOCK_STREAM :
429 (si.type == "dgram" ? SOCK_DGRAM :
430 SOCK_SEQPACKET)));
431 const char* socketcon =
432 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
433
434 int s = create_socket(si.name.c_str(), socket_type, si.perm,
435 si.uid, si.gid, socketcon);
436 if (s >= 0) {
437 PublishSocket(si.name, s);
438 }
439 }
440
Anestis Bechtsoudisb702b462016-02-05 16:38:48 +0200441 std::string pid_str = StringPrintf("%d", getpid());
Tom Cherrybac32992015-07-31 12:45:25 -0700442 for (const auto& file : writepid_files_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700443 if (!WriteStringToFile(pid_str, file)) {
Tom Cherrybac32992015-07-31 12:45:25 -0700444 ERROR("couldn't write %s to %s: %s\n",
445 pid_str.c_str(), file.c_str(), strerror(errno));
446 }
447 }
448
449 if (ioprio_class_ != IoSchedClass_NONE) {
450 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
451 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
452 getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
453 }
454 }
455
456 if (needs_console) {
457 setsid();
458 OpenConsole();
459 } else {
460 ZapStdio();
461 }
462
463 setpgid(0, getpid());
464
465 // As requested, set our gid, supplemental gids, and uid.
466 if (gid_) {
467 if (setgid(gid_) != 0) {
468 ERROR("setgid failed: %s\n", strerror(errno));
469 _exit(127);
470 }
471 }
472 if (!supp_gids_.empty()) {
473 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
474 ERROR("setgroups failed: %s\n", strerror(errno));
475 _exit(127);
476 }
477 }
478 if (uid_) {
479 if (setuid(uid_) != 0) {
480 ERROR("setuid failed: %s\n", strerror(errno));
481 _exit(127);
482 }
483 }
484 if (!seclabel_.empty()) {
485 if (setexeccon(seclabel_.c_str()) < 0) {
486 ERROR("cannot setexeccon('%s'): %s\n",
487 seclabel_.c_str(), strerror(errno));
488 _exit(127);
489 }
490 }
Vitalii Tomkiv081705c2016-05-18 17:36:30 -0700491 if (priority_ != 0) {
492 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
493 ERROR("setpriority failed: %s\n", strerror(errno));
494 _exit(127);
495 }
496 }
Tom Cherrybac32992015-07-31 12:45:25 -0700497
498 std::vector<char*> strs;
499 for (const auto& s : args_) {
500 strs.push_back(const_cast<char*>(s.c_str()));
501 }
Tom Cherrybac32992015-07-31 12:45:25 -0700502 strs.push_back(nullptr);
503 if (execve(args_[0].c_str(), (char**) &strs[0], (char**) ENV) < 0) {
504 ERROR("cannot execve('%s'): %s\n", args_[0].c_str(), strerror(errno));
505 }
506
507 _exit(127);
508 }
509
510 if (pid < 0) {
511 ERROR("failed to start '%s'\n", name_.c_str());
512 pid_ = 0;
513 return false;
514 }
515
516 time_started_ = gettime();
517 pid_ = pid;
518 flags_ |= SVC_RUNNING;
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000519 createProcessGroup(uid_, pid_);
Tom Cherrybac32992015-07-31 12:45:25 -0700520
521 if ((flags_ & SVC_EXEC) != 0) {
522 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
523 pid_, uid_, gid_, supp_gids_.size(),
524 !seclabel_.empty() ? seclabel_.c_str() : "default");
525 }
526
527 NotifyStateChange("running");
528 return true;
529}
530
Tom Cherrybac32992015-07-31 12:45:25 -0700531bool Service::StartIfNotDisabled() {
532 if (!(flags_ & SVC_DISABLED)) {
533 return Start();
534 } else {
535 flags_ |= SVC_DISABLED_START;
536 }
537 return true;
538}
539
540bool Service::Enable() {
541 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
542 if (flags_ & SVC_DISABLED_START) {
543 return Start();
544 }
545 return true;
546}
547
548void Service::Reset() {
549 StopOrReset(SVC_RESET);
550}
551
552void Service::Stop() {
553 StopOrReset(SVC_DISABLED);
554}
555
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800556void Service::Terminate() {
557 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
558 flags_ |= SVC_DISABLED;
559 if (pid_) {
560 NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
561 pid_);
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000562 killProcessGroup(uid_, pid_, SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800563 NotifyStateChange("stopping");
564 }
565}
566
Tom Cherrybac32992015-07-31 12:45:25 -0700567void Service::Restart() {
568 if (flags_ & SVC_RUNNING) {
569 /* Stop, wait, then start the service. */
570 StopOrReset(SVC_RESTART);
571 } else if (!(flags_ & SVC_RESTARTING)) {
572 /* Just start the service since it's not running. */
573 Start();
574 } /* else: Service is restarting anyways. */
575}
576
577void Service::RestartIfNeeded(time_t& process_needs_restart) {
578 time_t next_start_time = time_started_ + 5;
579
580 if (next_start_time <= gettime()) {
581 flags_ &= (~SVC_RESTARTING);
582 Start();
583 return;
584 }
585
586 if ((next_start_time < process_needs_restart) ||
587 (process_needs_restart == 0)) {
588 process_needs_restart = next_start_time;
589 }
590}
591
592/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
593void Service::StopOrReset(int how) {
594 /* The service is still SVC_RUNNING until its process exits, but if it has
595 * already exited it shoudn't attempt a restart yet. */
596 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
597
598 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
599 /* Hrm, an illegal flag. Default to SVC_DISABLED */
600 how = SVC_DISABLED;
601 }
602 /* if the service has not yet started, prevent
603 * it from auto-starting with its class
604 */
605 if (how == SVC_RESET) {
606 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
607 } else {
608 flags_ |= how;
609 }
610
611 if (pid_) {
612 NOTICE("Service '%s' is being killed...\n", name_.c_str());
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000613 killProcessGroup(uid_, pid_, SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700614 NotifyStateChange("stopping");
615 } else {
616 NotifyStateChange("stopped");
617 }
618}
619
620void Service::ZapStdio() const {
621 int fd;
622 fd = open("/dev/null", O_RDWR);
623 dup2(fd, 0);
624 dup2(fd, 1);
625 dup2(fd, 2);
626 close(fd);
627}
628
629void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200630 int fd = open(console_.c_str(), O_RDWR);
631 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700632 ioctl(fd, TIOCSCTTY, 0);
633 dup2(fd, 0);
634 dup2(fd, 1);
635 dup2(fd, 2);
636 close(fd);
637}
638
639void Service::PublishSocket(const std::string& name, int fd) const {
Tom Cherryb7349902015-08-26 11:43:36 -0700640 std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
641 std::string val = StringPrintf("%d", fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700642 add_environment(key.c_str(), val.c_str());
643
644 /* make sure we don't close-on-exec */
645 fcntl(fd, F_SETFD, 0);
646}
647
648int ServiceManager::exec_count_ = 0;
649
650ServiceManager::ServiceManager() {
651}
652
653ServiceManager& ServiceManager::GetInstance() {
654 static ServiceManager instance;
655 return instance;
656}
657
Tom Cherryb7349902015-08-26 11:43:36 -0700658void ServiceManager::AddService(std::unique_ptr<Service> service) {
659 Service* old_service = FindServiceByName(service->name());
660 if (old_service) {
661 ERROR("ignored duplicate definition of service '%s'",
662 service->name().c_str());
663 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700664 }
Tom Cherryb7349902015-08-26 11:43:36 -0700665 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700666}
667
668Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
669 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
670 // SECLABEL can be a - to denote default
671 std::size_t command_arg = 1;
672 for (std::size_t i = 1; i < args.size(); ++i) {
673 if (args[i] == "--") {
674 command_arg = i + 1;
675 break;
676 }
677 }
678 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
679 ERROR("exec called with too many supplementary group ids\n");
680 return nullptr;
681 }
682
683 if (command_arg >= args.size()) {
684 ERROR("exec called without command\n");
685 return nullptr;
686 }
687 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
688
689 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700690 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700691 unsigned flags = SVC_EXEC | SVC_ONESHOT;
692
693 std::string seclabel = "";
694 if (command_arg > 2 && args[1] != "-") {
695 seclabel = args[1];
696 }
697 uid_t uid = 0;
698 if (command_arg > 3) {
699 uid = decode_uid(args[2].c_str());
700 }
701 gid_t gid = 0;
702 std::vector<gid_t> supp_gids;
703 if (command_arg > 4) {
704 gid = decode_uid(args[3].c_str());
705 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
706 for (size_t i = 0; i < nr_supp_gids; ++i) {
707 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
708 }
709 }
710
711 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
712 supp_gids, seclabel, str_args));
713 if (!svc_p) {
714 ERROR("Couldn't allocate service for exec of '%s'",
715 str_args[0].c_str());
716 return nullptr;
717 }
718 Service* svc = svc_p.get();
719 services_.push_back(std::move(svc_p));
720
721 return svc;
722}
723
724Service* ServiceManager::FindServiceByName(const std::string& name) const {
725 auto svc = std::find_if(services_.begin(), services_.end(),
726 [&name] (const std::unique_ptr<Service>& s) {
727 return name == s->name();
728 });
729 if (svc != services_.end()) {
730 return svc->get();
731 }
732 return nullptr;
733}
734
735Service* ServiceManager::FindServiceByPid(pid_t pid) const {
736 auto svc = std::find_if(services_.begin(), services_.end(),
737 [&pid] (const std::unique_ptr<Service>& s) {
738 return s->pid() == pid;
739 });
740 if (svc != services_.end()) {
741 return svc->get();
742 }
743 return nullptr;
744}
745
746Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
747 auto svc = std::find_if(services_.begin(), services_.end(),
748 [&keychord_id] (const std::unique_ptr<Service>& s) {
749 return s->keychord_id() == keychord_id;
750 });
751
752 if (svc != services_.end()) {
753 return svc->get();
754 }
755 return nullptr;
756}
757
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800758void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700759 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800760 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -0700761 }
762}
763
764void ServiceManager::ForEachServiceInClass(const std::string& classname,
765 void (*func)(Service* svc)) const {
766 for (const auto& s : services_) {
767 if (classname == s->classname()) {
768 func(s.get());
769 }
770 }
771}
772
773void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
774 void (*func)(Service* svc)) const {
775 for (const auto& s : services_) {
776 if (s->flags() & matchflags) {
777 func(s.get());
778 }
779 }
780}
781
Tom Cherryb7349902015-08-26 11:43:36 -0700782void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -0700783 auto svc_it = std::find_if(services_.begin(), services_.end(),
784 [&svc] (const std::unique_ptr<Service>& s) {
785 return svc.name() == s->name();
786 });
787 if (svc_it == services_.end()) {
788 return;
789 }
790
791 services_.erase(svc_it);
792}
793
Tom Cherryb7349902015-08-26 11:43:36 -0700794void ServiceManager::DumpState() const {
795 for (const auto& s : services_) {
796 s->DumpState();
797 }
798 INFO("\n");
799}
800
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800801bool ServiceManager::ReapOneProcess() {
802 int status;
803 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
804 if (pid == 0) {
805 return false;
806 } else if (pid == -1) {
807 ERROR("waitpid failed: %s\n", strerror(errno));
808 return false;
809 }
810
811 Service* svc = FindServiceByPid(pid);
812
813 std::string name;
814 if (svc) {
815 name = android::base::StringPrintf("Service '%s' (pid %d)",
816 svc->name().c_str(), pid);
817 } else {
818 name = android::base::StringPrintf("Untracked pid %d", pid);
819 }
820
821 if (WIFEXITED(status)) {
822 NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
823 } else if (WIFSIGNALED(status)) {
824 NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
825 } else if (WIFSTOPPED(status)) {
826 NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
827 } else {
828 NOTICE("%s state changed", name.c_str());
829 }
830
831 if (!svc) {
832 return true;
833 }
834
835 if (svc->Reap()) {
836 waiting_for_exec = false;
837 RemoveService(*svc);
838 }
839
840 return true;
841}
842
843void ServiceManager::ReapAnyOutstandingChildren() {
844 while (ReapOneProcess()) {
845 }
846}
847
Tom Cherryb7349902015-08-26 11:43:36 -0700848bool ServiceParser::ParseSection(const std::vector<std::string>& args,
849 std::string* err) {
850 if (args.size() < 3) {
851 *err = "services must have a name and a program";
852 return false;
853 }
854
855 const std::string& name = args[1];
856 if (!IsValidName(name)) {
857 *err = StringPrintf("invalid service name '%s'", name.c_str());
858 return false;
859 }
860
861 std::vector<std::string> str_args(args.begin() + 2, args.end());
862 service_ = std::make_unique<Service>(name, "default", str_args);
863 return true;
864}
865
866bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
867 const std::string& filename, int line,
868 std::string* err) const {
869 return service_ ? service_->HandleLine(args, err) : false;
870}
871
872void ServiceParser::EndSection() {
873 if (service_) {
874 ServiceManager::GetInstance().AddService(std::move(service_));
875 }
876}
877
878bool ServiceParser::IsValidName(const std::string& name) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700879 if (name.size() > 16) {
880 return false;
881 }
882 for (const auto& c : name) {
883 if (!isalnum(c) && (c != '_') && (c != '-')) {
884 return false;
885 }
886 }
887 return true;
888}