blob: 6e688786d10a0cd6fe1ed06bec12b505729db826 [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
Tom Cherrybac35362016-06-07 11:22:00 -0700498 std::vector<std::string> expanded_args;
Tom Cherrybac32992015-07-31 12:45:25 -0700499 std::vector<char*> strs;
Tom Cherrybac35362016-06-07 11:22:00 -0700500 expanded_args.resize(args_.size());
501 strs.push_back(const_cast<char*>(args_[0].c_str()));
502 for (std::size_t i = 1; i < args_.size(); ++i) {
503 if (!expand_props(args_[i], &expanded_args[i])) {
504 ERROR("%s: cannot expand '%s'\n", args_[0].c_str(), args_[i].c_str());
505 _exit(127);
506 }
507 strs.push_back(const_cast<char*>(expanded_args[i].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700508 }
Tom Cherrybac32992015-07-31 12:45:25 -0700509 strs.push_back(nullptr);
Tom Cherrybac35362016-06-07 11:22:00 -0700510
511 if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
512 ERROR("cannot execve('%s'): %s\n", strs[0], strerror(errno));
Tom Cherrybac32992015-07-31 12:45:25 -0700513 }
514
515 _exit(127);
516 }
517
518 if (pid < 0) {
519 ERROR("failed to start '%s'\n", name_.c_str());
520 pid_ = 0;
521 return false;
522 }
523
524 time_started_ = gettime();
525 pid_ = pid;
526 flags_ |= SVC_RUNNING;
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000527 createProcessGroup(uid_, pid_);
Tom Cherrybac32992015-07-31 12:45:25 -0700528
529 if ((flags_ & SVC_EXEC) != 0) {
530 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
531 pid_, uid_, gid_, supp_gids_.size(),
532 !seclabel_.empty() ? seclabel_.c_str() : "default");
533 }
534
535 NotifyStateChange("running");
536 return true;
537}
538
Tom Cherrybac32992015-07-31 12:45:25 -0700539bool Service::StartIfNotDisabled() {
540 if (!(flags_ & SVC_DISABLED)) {
541 return Start();
542 } else {
543 flags_ |= SVC_DISABLED_START;
544 }
545 return true;
546}
547
548bool Service::Enable() {
549 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
550 if (flags_ & SVC_DISABLED_START) {
551 return Start();
552 }
553 return true;
554}
555
556void Service::Reset() {
557 StopOrReset(SVC_RESET);
558}
559
560void Service::Stop() {
561 StopOrReset(SVC_DISABLED);
562}
563
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800564void Service::Terminate() {
565 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
566 flags_ |= SVC_DISABLED;
567 if (pid_) {
568 NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
569 pid_);
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000570 killProcessGroup(uid_, pid_, SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800571 NotifyStateChange("stopping");
572 }
573}
574
Tom Cherrybac32992015-07-31 12:45:25 -0700575void Service::Restart() {
576 if (flags_ & SVC_RUNNING) {
577 /* Stop, wait, then start the service. */
578 StopOrReset(SVC_RESTART);
579 } else if (!(flags_ & SVC_RESTARTING)) {
580 /* Just start the service since it's not running. */
581 Start();
582 } /* else: Service is restarting anyways. */
583}
584
585void Service::RestartIfNeeded(time_t& process_needs_restart) {
586 time_t next_start_time = time_started_ + 5;
587
588 if (next_start_time <= gettime()) {
589 flags_ &= (~SVC_RESTARTING);
590 Start();
591 return;
592 }
593
594 if ((next_start_time < process_needs_restart) ||
595 (process_needs_restart == 0)) {
596 process_needs_restart = next_start_time;
597 }
598}
599
600/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
601void Service::StopOrReset(int how) {
602 /* The service is still SVC_RUNNING until its process exits, but if it has
603 * already exited it shoudn't attempt a restart yet. */
604 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
605
606 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
607 /* Hrm, an illegal flag. Default to SVC_DISABLED */
608 how = SVC_DISABLED;
609 }
610 /* if the service has not yet started, prevent
611 * it from auto-starting with its class
612 */
613 if (how == SVC_RESET) {
614 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
615 } else {
616 flags_ |= how;
617 }
618
619 if (pid_) {
620 NOTICE("Service '%s' is being killed...\n", name_.c_str());
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000621 killProcessGroup(uid_, pid_, SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700622 NotifyStateChange("stopping");
623 } else {
624 NotifyStateChange("stopped");
625 }
626}
627
628void Service::ZapStdio() const {
629 int fd;
630 fd = open("/dev/null", O_RDWR);
631 dup2(fd, 0);
632 dup2(fd, 1);
633 dup2(fd, 2);
634 close(fd);
635}
636
637void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200638 int fd = open(console_.c_str(), O_RDWR);
639 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700640 ioctl(fd, TIOCSCTTY, 0);
641 dup2(fd, 0);
642 dup2(fd, 1);
643 dup2(fd, 2);
644 close(fd);
645}
646
647void Service::PublishSocket(const std::string& name, int fd) const {
Tom Cherryb7349902015-08-26 11:43:36 -0700648 std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
649 std::string val = StringPrintf("%d", fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700650 add_environment(key.c_str(), val.c_str());
651
652 /* make sure we don't close-on-exec */
653 fcntl(fd, F_SETFD, 0);
654}
655
656int ServiceManager::exec_count_ = 0;
657
658ServiceManager::ServiceManager() {
659}
660
661ServiceManager& ServiceManager::GetInstance() {
662 static ServiceManager instance;
663 return instance;
664}
665
Tom Cherryb7349902015-08-26 11:43:36 -0700666void ServiceManager::AddService(std::unique_ptr<Service> service) {
667 Service* old_service = FindServiceByName(service->name());
668 if (old_service) {
669 ERROR("ignored duplicate definition of service '%s'",
670 service->name().c_str());
671 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700672 }
Tom Cherryb7349902015-08-26 11:43:36 -0700673 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700674}
675
676Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
677 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
678 // SECLABEL can be a - to denote default
679 std::size_t command_arg = 1;
680 for (std::size_t i = 1; i < args.size(); ++i) {
681 if (args[i] == "--") {
682 command_arg = i + 1;
683 break;
684 }
685 }
686 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
687 ERROR("exec called with too many supplementary group ids\n");
688 return nullptr;
689 }
690
691 if (command_arg >= args.size()) {
692 ERROR("exec called without command\n");
693 return nullptr;
694 }
695 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
696
697 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700698 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700699 unsigned flags = SVC_EXEC | SVC_ONESHOT;
700
701 std::string seclabel = "";
702 if (command_arg > 2 && args[1] != "-") {
703 seclabel = args[1];
704 }
705 uid_t uid = 0;
706 if (command_arg > 3) {
707 uid = decode_uid(args[2].c_str());
708 }
709 gid_t gid = 0;
710 std::vector<gid_t> supp_gids;
711 if (command_arg > 4) {
712 gid = decode_uid(args[3].c_str());
713 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
714 for (size_t i = 0; i < nr_supp_gids; ++i) {
715 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
716 }
717 }
718
719 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
720 supp_gids, seclabel, str_args));
721 if (!svc_p) {
722 ERROR("Couldn't allocate service for exec of '%s'",
723 str_args[0].c_str());
724 return nullptr;
725 }
726 Service* svc = svc_p.get();
727 services_.push_back(std::move(svc_p));
728
729 return svc;
730}
731
732Service* ServiceManager::FindServiceByName(const std::string& name) const {
733 auto svc = std::find_if(services_.begin(), services_.end(),
734 [&name] (const std::unique_ptr<Service>& s) {
735 return name == s->name();
736 });
737 if (svc != services_.end()) {
738 return svc->get();
739 }
740 return nullptr;
741}
742
743Service* ServiceManager::FindServiceByPid(pid_t pid) const {
744 auto svc = std::find_if(services_.begin(), services_.end(),
745 [&pid] (const std::unique_ptr<Service>& s) {
746 return s->pid() == pid;
747 });
748 if (svc != services_.end()) {
749 return svc->get();
750 }
751 return nullptr;
752}
753
754Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
755 auto svc = std::find_if(services_.begin(), services_.end(),
756 [&keychord_id] (const std::unique_ptr<Service>& s) {
757 return s->keychord_id() == keychord_id;
758 });
759
760 if (svc != services_.end()) {
761 return svc->get();
762 }
763 return nullptr;
764}
765
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800766void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700767 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800768 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -0700769 }
770}
771
772void ServiceManager::ForEachServiceInClass(const std::string& classname,
773 void (*func)(Service* svc)) const {
774 for (const auto& s : services_) {
775 if (classname == s->classname()) {
776 func(s.get());
777 }
778 }
779}
780
781void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
782 void (*func)(Service* svc)) const {
783 for (const auto& s : services_) {
784 if (s->flags() & matchflags) {
785 func(s.get());
786 }
787 }
788}
789
Tom Cherryb7349902015-08-26 11:43:36 -0700790void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -0700791 auto svc_it = std::find_if(services_.begin(), services_.end(),
792 [&svc] (const std::unique_ptr<Service>& s) {
793 return svc.name() == s->name();
794 });
795 if (svc_it == services_.end()) {
796 return;
797 }
798
799 services_.erase(svc_it);
800}
801
Tom Cherryb7349902015-08-26 11:43:36 -0700802void ServiceManager::DumpState() const {
803 for (const auto& s : services_) {
804 s->DumpState();
805 }
806 INFO("\n");
807}
808
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800809bool ServiceManager::ReapOneProcess() {
810 int status;
811 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
812 if (pid == 0) {
813 return false;
814 } else if (pid == -1) {
815 ERROR("waitpid failed: %s\n", strerror(errno));
816 return false;
817 }
818
819 Service* svc = FindServiceByPid(pid);
820
821 std::string name;
822 if (svc) {
823 name = android::base::StringPrintf("Service '%s' (pid %d)",
824 svc->name().c_str(), pid);
825 } else {
826 name = android::base::StringPrintf("Untracked pid %d", pid);
827 }
828
829 if (WIFEXITED(status)) {
830 NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
831 } else if (WIFSIGNALED(status)) {
832 NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
833 } else if (WIFSTOPPED(status)) {
834 NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
835 } else {
836 NOTICE("%s state changed", name.c_str());
837 }
838
839 if (!svc) {
840 return true;
841 }
842
843 if (svc->Reap()) {
844 waiting_for_exec = false;
845 RemoveService(*svc);
846 }
847
848 return true;
849}
850
851void ServiceManager::ReapAnyOutstandingChildren() {
852 while (ReapOneProcess()) {
853 }
854}
855
Tom Cherryb7349902015-08-26 11:43:36 -0700856bool ServiceParser::ParseSection(const std::vector<std::string>& args,
857 std::string* err) {
858 if (args.size() < 3) {
859 *err = "services must have a name and a program";
860 return false;
861 }
862
863 const std::string& name = args[1];
864 if (!IsValidName(name)) {
865 *err = StringPrintf("invalid service name '%s'", name.c_str());
866 return false;
867 }
868
869 std::vector<std::string> str_args(args.begin() + 2, args.end());
870 service_ = std::make_unique<Service>(name, "default", str_args);
871 return true;
872}
873
874bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
875 const std::string& filename, int line,
876 std::string* err) const {
877 return service_ ? service_->HandleLine(args, err) : false;
878}
879
880void ServiceParser::EndSection() {
881 if (service_) {
882 ServiceManager::GetInstance().AddService(std::move(service_));
883 }
884}
885
886bool ServiceParser::IsValidName(const std::string& name) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700887 if (name.size() > 16) {
888 return false;
889 }
890 for (const auto& c : name) {
891 if (!isalnum(c) && (c != '_') && (c != '-')) {
892 return false;
893 }
894 }
895 return true;
896}