blob: 4175d054f22413b3d60c4eaaa69a9827c0721318 [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
474 std::vector<char*> strs;
475 for (const auto& s : args_) {
476 strs.push_back(const_cast<char*>(s.c_str()));
477 }
Tom Cherrybac32992015-07-31 12:45:25 -0700478 strs.push_back(nullptr);
479 if (execve(args_[0].c_str(), (char**) &strs[0], (char**) ENV) < 0) {
480 ERROR("cannot execve('%s'): %s\n", args_[0].c_str(), strerror(errno));
481 }
482
483 _exit(127);
484 }
485
486 if (pid < 0) {
487 ERROR("failed to start '%s'\n", name_.c_str());
488 pid_ = 0;
489 return false;
490 }
491
492 time_started_ = gettime();
493 pid_ = pid;
494 flags_ |= SVC_RUNNING;
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000495 createProcessGroup(uid_, pid_);
Tom Cherrybac32992015-07-31 12:45:25 -0700496
497 if ((flags_ & SVC_EXEC) != 0) {
498 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
499 pid_, uid_, gid_, supp_gids_.size(),
500 !seclabel_.empty() ? seclabel_.c_str() : "default");
501 }
502
503 NotifyStateChange("running");
504 return true;
505}
506
Tom Cherrybac32992015-07-31 12:45:25 -0700507bool Service::StartIfNotDisabled() {
508 if (!(flags_ & SVC_DISABLED)) {
509 return Start();
510 } else {
511 flags_ |= SVC_DISABLED_START;
512 }
513 return true;
514}
515
516bool Service::Enable() {
517 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
518 if (flags_ & SVC_DISABLED_START) {
519 return Start();
520 }
521 return true;
522}
523
524void Service::Reset() {
525 StopOrReset(SVC_RESET);
526}
527
528void Service::Stop() {
529 StopOrReset(SVC_DISABLED);
530}
531
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800532void Service::Terminate() {
533 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
534 flags_ |= SVC_DISABLED;
535 if (pid_) {
536 NOTICE("Sending SIGTERM to service '%s' (pid %d)...\n", name_.c_str(),
537 pid_);
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000538 killProcessGroup(uid_, pid_, SIGTERM);
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800539 NotifyStateChange("stopping");
540 }
541}
542
Tom Cherrybac32992015-07-31 12:45:25 -0700543void Service::Restart() {
544 if (flags_ & SVC_RUNNING) {
545 /* Stop, wait, then start the service. */
546 StopOrReset(SVC_RESTART);
547 } else if (!(flags_ & SVC_RESTARTING)) {
548 /* Just start the service since it's not running. */
549 Start();
550 } /* else: Service is restarting anyways. */
551}
552
553void Service::RestartIfNeeded(time_t& process_needs_restart) {
554 time_t next_start_time = time_started_ + 5;
555
556 if (next_start_time <= gettime()) {
557 flags_ &= (~SVC_RESTARTING);
558 Start();
559 return;
560 }
561
562 if ((next_start_time < process_needs_restart) ||
563 (process_needs_restart == 0)) {
564 process_needs_restart = next_start_time;
565 }
566}
567
568/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
569void Service::StopOrReset(int how) {
570 /* The service is still SVC_RUNNING until its process exits, but if it has
571 * already exited it shoudn't attempt a restart yet. */
572 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
573
574 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
575 /* Hrm, an illegal flag. Default to SVC_DISABLED */
576 how = SVC_DISABLED;
577 }
578 /* if the service has not yet started, prevent
579 * it from auto-starting with its class
580 */
581 if (how == SVC_RESET) {
582 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
583 } else {
584 flags_ |= how;
585 }
586
587 if (pid_) {
588 NOTICE("Service '%s' is being killed...\n", name_.c_str());
Collin Mullinerf7e79b92016-06-01 21:03:55 +0000589 killProcessGroup(uid_, pid_, SIGKILL);
Tom Cherrybac32992015-07-31 12:45:25 -0700590 NotifyStateChange("stopping");
591 } else {
592 NotifyStateChange("stopped");
593 }
594}
595
596void Service::ZapStdio() const {
597 int fd;
598 fd = open("/dev/null", O_RDWR);
599 dup2(fd, 0);
600 dup2(fd, 1);
601 dup2(fd, 2);
602 close(fd);
603}
604
605void Service::OpenConsole() const {
Viorel Suman70daa672016-03-21 10:08:07 +0200606 int fd = open(console_.c_str(), O_RDWR);
607 if (fd == -1) fd = open("/dev/null", O_RDWR);
Tom Cherrybac32992015-07-31 12:45:25 -0700608 ioctl(fd, TIOCSCTTY, 0);
609 dup2(fd, 0);
610 dup2(fd, 1);
611 dup2(fd, 2);
612 close(fd);
613}
614
615void Service::PublishSocket(const std::string& name, int fd) const {
Tom Cherryb7349902015-08-26 11:43:36 -0700616 std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
617 std::string val = StringPrintf("%d", fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700618 add_environment(key.c_str(), val.c_str());
619
620 /* make sure we don't close-on-exec */
621 fcntl(fd, F_SETFD, 0);
622}
623
624int ServiceManager::exec_count_ = 0;
625
626ServiceManager::ServiceManager() {
627}
628
629ServiceManager& ServiceManager::GetInstance() {
630 static ServiceManager instance;
631 return instance;
632}
633
Tom Cherryb7349902015-08-26 11:43:36 -0700634void ServiceManager::AddService(std::unique_ptr<Service> service) {
635 Service* old_service = FindServiceByName(service->name());
636 if (old_service) {
637 ERROR("ignored duplicate definition of service '%s'",
638 service->name().c_str());
639 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700640 }
Tom Cherryb7349902015-08-26 11:43:36 -0700641 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700642}
643
644Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
645 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
646 // SECLABEL can be a - to denote default
647 std::size_t command_arg = 1;
648 for (std::size_t i = 1; i < args.size(); ++i) {
649 if (args[i] == "--") {
650 command_arg = i + 1;
651 break;
652 }
653 }
654 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
655 ERROR("exec called with too many supplementary group ids\n");
656 return nullptr;
657 }
658
659 if (command_arg >= args.size()) {
660 ERROR("exec called without command\n");
661 return nullptr;
662 }
663 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
664
665 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700666 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700667 unsigned flags = SVC_EXEC | SVC_ONESHOT;
668
669 std::string seclabel = "";
670 if (command_arg > 2 && args[1] != "-") {
671 seclabel = args[1];
672 }
673 uid_t uid = 0;
674 if (command_arg > 3) {
675 uid = decode_uid(args[2].c_str());
676 }
677 gid_t gid = 0;
678 std::vector<gid_t> supp_gids;
679 if (command_arg > 4) {
680 gid = decode_uid(args[3].c_str());
681 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
682 for (size_t i = 0; i < nr_supp_gids; ++i) {
683 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
684 }
685 }
686
687 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
688 supp_gids, seclabel, str_args));
689 if (!svc_p) {
690 ERROR("Couldn't allocate service for exec of '%s'",
691 str_args[0].c_str());
692 return nullptr;
693 }
694 Service* svc = svc_p.get();
695 services_.push_back(std::move(svc_p));
696
697 return svc;
698}
699
700Service* ServiceManager::FindServiceByName(const std::string& name) const {
701 auto svc = std::find_if(services_.begin(), services_.end(),
702 [&name] (const std::unique_ptr<Service>& s) {
703 return name == s->name();
704 });
705 if (svc != services_.end()) {
706 return svc->get();
707 }
708 return nullptr;
709}
710
711Service* ServiceManager::FindServiceByPid(pid_t pid) const {
712 auto svc = std::find_if(services_.begin(), services_.end(),
713 [&pid] (const std::unique_ptr<Service>& s) {
714 return s->pid() == pid;
715 });
716 if (svc != services_.end()) {
717 return svc->get();
718 }
719 return nullptr;
720}
721
722Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
723 auto svc = std::find_if(services_.begin(), services_.end(),
724 [&keychord_id] (const std::unique_ptr<Service>& s) {
725 return s->keychord_id() == keychord_id;
726 });
727
728 if (svc != services_.end()) {
729 return svc->get();
730 }
731 return nullptr;
732}
733
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800734void ServiceManager::ForEachService(std::function<void(Service*)> callback) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700735 for (const auto& s : services_) {
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800736 callback(s.get());
Tom Cherrybac32992015-07-31 12:45:25 -0700737 }
738}
739
740void ServiceManager::ForEachServiceInClass(const std::string& classname,
741 void (*func)(Service* svc)) const {
742 for (const auto& s : services_) {
743 if (classname == s->classname()) {
744 func(s.get());
745 }
746 }
747}
748
749void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
750 void (*func)(Service* svc)) const {
751 for (const auto& s : services_) {
752 if (s->flags() & matchflags) {
753 func(s.get());
754 }
755 }
756}
757
Tom Cherryb7349902015-08-26 11:43:36 -0700758void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -0700759 auto svc_it = std::find_if(services_.begin(), services_.end(),
760 [&svc] (const std::unique_ptr<Service>& s) {
761 return svc.name() == s->name();
762 });
763 if (svc_it == services_.end()) {
764 return;
765 }
766
767 services_.erase(svc_it);
768}
769
Tom Cherryb7349902015-08-26 11:43:36 -0700770void ServiceManager::DumpState() const {
771 for (const auto& s : services_) {
772 s->DumpState();
773 }
774 INFO("\n");
775}
776
Bertrand SIMONNETb7e03e82015-12-18 11:39:59 -0800777bool ServiceManager::ReapOneProcess() {
778 int status;
779 pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, WNOHANG));
780 if (pid == 0) {
781 return false;
782 } else if (pid == -1) {
783 ERROR("waitpid failed: %s\n", strerror(errno));
784 return false;
785 }
786
787 Service* svc = FindServiceByPid(pid);
788
789 std::string name;
790 if (svc) {
791 name = android::base::StringPrintf("Service '%s' (pid %d)",
792 svc->name().c_str(), pid);
793 } else {
794 name = android::base::StringPrintf("Untracked pid %d", pid);
795 }
796
797 if (WIFEXITED(status)) {
798 NOTICE("%s exited with status %d\n", name.c_str(), WEXITSTATUS(status));
799 } else if (WIFSIGNALED(status)) {
800 NOTICE("%s killed by signal %d\n", name.c_str(), WTERMSIG(status));
801 } else if (WIFSTOPPED(status)) {
802 NOTICE("%s stopped by signal %d\n", name.c_str(), WSTOPSIG(status));
803 } else {
804 NOTICE("%s state changed", name.c_str());
805 }
806
807 if (!svc) {
808 return true;
809 }
810
811 if (svc->Reap()) {
812 waiting_for_exec = false;
813 RemoveService(*svc);
814 }
815
816 return true;
817}
818
819void ServiceManager::ReapAnyOutstandingChildren() {
820 while (ReapOneProcess()) {
821 }
822}
823
Tom Cherryb7349902015-08-26 11:43:36 -0700824bool ServiceParser::ParseSection(const std::vector<std::string>& args,
825 std::string* err) {
826 if (args.size() < 3) {
827 *err = "services must have a name and a program";
828 return false;
829 }
830
831 const std::string& name = args[1];
832 if (!IsValidName(name)) {
833 *err = StringPrintf("invalid service name '%s'", name.c_str());
834 return false;
835 }
836
837 std::vector<std::string> str_args(args.begin() + 2, args.end());
838 service_ = std::make_unique<Service>(name, "default", str_args);
839 return true;
840}
841
842bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
843 const std::string& filename, int line,
844 std::string* err) const {
845 return service_ ? service_->HandleLine(args, err) : false;
846}
847
848void ServiceParser::EndSection() {
849 if (service_) {
850 ServiceManager::GetInstance().AddService(std::move(service_));
851 }
852}
853
854bool ServiceParser::IsValidName(const std::string& name) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700855 if (name.size() > 16) {
856 return false;
857 }
858 for (const auto& c : name) {
859 if (!isalnum(c) && (c != '_') && (c != '-')) {
860 return false;
861 }
862 }
863 return true;
864}