blob: e78787b950ce6fe77f561e67a82d0f99f112c284 [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>
22#include <termios.h>
Dan Albertaf9ba4d2015-08-11 16:37:04 -070023#include <unistd.h>
Tom Cherrybac32992015-07-31 12:45:25 -070024
25#include <selinux/selinux.h>
26
Elliott Hughes4f713192015-12-04 22:00:26 -080027#include <android-base/file.h>
28#include <android-base/stringprintf.h>
Tom Cherrybac32992015-07-31 12:45:25 -070029#include <cutils/android_reboot.h>
30#include <cutils/sockets.h>
31
32#include "action.h"
33#include "init.h"
34#include "init_parser.h"
Tom Cherrybac32992015-07-31 12:45:25 -070035#include "log.h"
36#include "property_service.h"
37#include "util.h"
38
Tom Cherryb7349902015-08-26 11:43:36 -070039using android::base::StringPrintf;
40using android::base::WriteStringToFile;
41
Tom Cherrybac32992015-07-31 12:45:25 -070042#define CRITICAL_CRASH_THRESHOLD 4 // if we crash >4 times ...
43#define CRITICAL_CRASH_WINDOW (4*60) // ... in 4 minutes, goto recovery
44
45SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
46}
47
48SocketInfo::SocketInfo(const std::string& name, const std::string& type, uid_t uid,
49 gid_t gid, int perm, const std::string& socketcon)
50 : name(name), type(type), uid(uid), gid(gid), perm(perm), socketcon(socketcon) {
51}
52
53ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
54}
55
56ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
57 const std::string& value)
58 : name(name), value(value) {
59}
60
61Service::Service(const std::string& name, const std::string& classname,
62 const std::vector<std::string>& args)
63 : name_(name), classname_(classname), flags_(0), pid_(0), time_started_(0),
64 time_crashed_(0), nr_crashed_(0), uid_(0), gid_(0), seclabel_(""),
65 ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
66 onrestart_.InitSingleTrigger("onrestart");
67}
68
69Service::Service(const std::string& name, const std::string& classname,
70 unsigned flags, uid_t uid, gid_t gid, const std::vector<gid_t>& supp_gids,
71 const std::string& seclabel, const std::vector<std::string>& args)
72 : name_(name), classname_(classname), flags_(flags), pid_(0), time_started_(0),
73 time_crashed_(0), nr_crashed_(0), uid_(uid), gid_(gid), supp_gids_(supp_gids),
74 seclabel_(seclabel), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
75 onrestart_.InitSingleTrigger("onrestart");
76}
77
78void Service::NotifyStateChange(const std::string& new_state) const {
79 if (!properties_initialized()) {
80 // If properties aren't available yet, we can't set them.
81 return;
82 }
83
84 if ((flags_ & SVC_EXEC) != 0) {
85 // 'exec' commands don't have properties tracking their state.
86 return;
87 }
88
Tom Cherryb7349902015-08-26 11:43:36 -070089 std::string prop_name = StringPrintf("init.svc.%s", name_.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -070090 if (prop_name.length() >= PROP_NAME_MAX) {
91 // If the property name would be too long, we can't set it.
92 ERROR("Property name \"init.svc.%s\" too long; not setting to %s\n",
93 name_.c_str(), new_state.c_str());
94 return;
95 }
96
97 property_set(prop_name.c_str(), new_state.c_str());
98}
99
100bool Service::Reap() {
101 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
102 NOTICE("Service '%s' (pid %d) killing any children in process group\n",
103 name_.c_str(), pid_);
104 kill(-pid_, SIGKILL);
105 }
106
107 // Remove any sockets we may have created.
108 for (const auto& si : sockets_) {
Tom Cherryb7349902015-08-26 11:43:36 -0700109 std::string tmp = StringPrintf(ANDROID_SOCKET_DIR "/%s", si.name.c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700110 unlink(tmp.c_str());
111 }
112
113 if (flags_ & SVC_EXEC) {
114 INFO("SVC_EXEC pid %d finished...\n", pid_);
115 return true;
116 }
117
118 pid_ = 0;
119 flags_ &= (~SVC_RUNNING);
120
121 // Oneshot processes go into the disabled state on exit,
122 // except when manually restarted.
123 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) {
124 flags_ |= SVC_DISABLED;
125 }
126
127 // Disabled and reset processes do not get restarted automatically.
128 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
129 NotifyStateChange("stopped");
130 return false;
131 }
132
133 time_t now = gettime();
134 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
135 if (time_crashed_ + CRITICAL_CRASH_WINDOW >= now) {
136 if (++nr_crashed_ > CRITICAL_CRASH_THRESHOLD) {
137 ERROR("critical process '%s' exited %d times in %d minutes; "
138 "rebooting into recovery mode\n", name_.c_str(),
139 CRITICAL_CRASH_THRESHOLD, CRITICAL_CRASH_WINDOW / 60);
140 android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
141 return false;
142 }
143 } else {
144 time_crashed_ = now;
145 nr_crashed_ = 1;
146 }
147 }
148
149 flags_ &= (~SVC_RESTART);
150 flags_ |= SVC_RESTARTING;
151
152 // Execute all onrestart commands for this service.
153 onrestart_.ExecuteAllCommands();
154
155 NotifyStateChange("restarting");
156 return false;
157}
158
159void Service::DumpState() const {
160 INFO("service %s\n", name_.c_str());
161 INFO(" class '%s'\n", classname_.c_str());
162 INFO(" exec");
163 for (const auto& s : args_) {
164 INFO(" '%s'", s.c_str());
165 }
166 INFO("\n");
167 for (const auto& si : sockets_) {
168 INFO(" socket %s %s 0%o\n", si.name.c_str(), si.type.c_str(), si.perm);
169 }
170}
171
Tom Cherryb7349902015-08-26 11:43:36 -0700172bool Service::HandleClass(const std::vector<std::string>& args, std::string* err) {
173 classname_ = args[1];
174 return true;
175}
Tom Cherrybac32992015-07-31 12:45:25 -0700176
Tom Cherryb7349902015-08-26 11:43:36 -0700177bool Service::HandleConsole(const std::vector<std::string>& args, std::string* err) {
178 flags_ |= SVC_CONSOLE;
179 return true;
180}
Tom Cherrybac32992015-07-31 12:45:25 -0700181
Tom Cherryb7349902015-08-26 11:43:36 -0700182bool Service::HandleCritical(const std::vector<std::string>& args, std::string* err) {
183 flags_ |= SVC_CRITICAL;
184 return true;
185}
Tom Cherrybac32992015-07-31 12:45:25 -0700186
Tom Cherryb7349902015-08-26 11:43:36 -0700187bool Service::HandleDisabled(const std::vector<std::string>& args, std::string* err) {
188 flags_ |= SVC_DISABLED;
189 flags_ |= SVC_RC_DISABLED;
190 return true;
191}
Tom Cherrybac32992015-07-31 12:45:25 -0700192
Tom Cherryb7349902015-08-26 11:43:36 -0700193bool Service::HandleGroup(const std::vector<std::string>& args, std::string* err) {
194 gid_ = decode_uid(args[1].c_str());
195 for (std::size_t n = 2; n < args.size(); n++) {
196 supp_gids_.emplace_back(decode_uid(args[n].c_str()));
Tom Cherrybac32992015-07-31 12:45:25 -0700197 }
198 return true;
199}
200
Tom Cherryb7349902015-08-26 11:43:36 -0700201bool Service::HandleIoprio(const std::vector<std::string>& args, std::string* err) {
202 ioprio_pri_ = std::stoul(args[2], 0, 8);
203
204 if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
205 *err = "priority value must be range 0 - 7";
206 return false;
207 }
208
209 if (args[1] == "rt") {
210 ioprio_class_ = IoSchedClass_RT;
211 } else if (args[1] == "be") {
212 ioprio_class_ = IoSchedClass_BE;
213 } else if (args[1] == "idle") {
214 ioprio_class_ = IoSchedClass_IDLE;
215 } else {
216 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>";
217 return false;
218 }
219
220 return true;
221}
222
223bool Service::HandleKeycodes(const std::vector<std::string>& args, std::string* err) {
224 for (std::size_t i = 1; i < args.size(); i++) {
225 keycodes_.emplace_back(std::stoi(args[i]));
226 }
227 return true;
228}
229
230bool Service::HandleOneshot(const std::vector<std::string>& args, std::string* err) {
231 flags_ |= SVC_ONESHOT;
232 return true;
233}
234
235bool Service::HandleOnrestart(const std::vector<std::string>& args, std::string* err) {
236 std::vector<std::string> str_args(args.begin() + 1, args.end());
237 onrestart_.AddCommand(str_args, "", 0, err);
238 return true;
239}
240
241bool Service::HandleSeclabel(const std::vector<std::string>& args, std::string* err) {
242 seclabel_ = args[1];
243 return true;
244}
245
246bool Service::HandleSetenv(const std::vector<std::string>& args, std::string* err) {
247 envvars_.emplace_back(args[1], args[2]);
248 return true;
249}
250
251/* name type perm [ uid gid context ] */
252bool Service::HandleSocket(const std::vector<std::string>& args, std::string* err) {
253 if (args[2] != "dgram" && args[2] != "stream" && args[2] != "seqpacket") {
254 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'";
255 return false;
256 }
257
258 int perm = std::stoul(args[3], 0, 8);
259 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
260 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
261 std::string socketcon = args.size() > 6 ? args[6] : "";
262
263 sockets_.emplace_back(args[1], args[2], uid, gid, perm, socketcon);
264 return true;
265}
266
267bool Service::HandleUser(const std::vector<std::string>& args, std::string* err) {
268 uid_ = decode_uid(args[1].c_str());
269 return true;
270}
271
272bool Service::HandleWritepid(const std::vector<std::string>& args, std::string* err) {
273 writepid_files_.assign(args.begin() + 1, args.end());
274 return true;
275}
276
277class Service::OptionHandlerMap : public KeywordMap<OptionHandler> {
278public:
279 OptionHandlerMap() {
280 }
281private:
282 Map& map() const override;
283};
284
285Service::OptionHandlerMap::Map& Service::OptionHandlerMap::map() const {
286 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
287 static const Map option_handlers = {
288 {"class", {1, 1, &Service::HandleClass}},
289 {"console", {0, 0, &Service::HandleConsole}},
290 {"critical", {0, 0, &Service::HandleCritical}},
291 {"disabled", {0, 0, &Service::HandleDisabled}},
292 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::HandleGroup}},
293 {"ioprio", {2, 2, &Service::HandleIoprio}},
294 {"keycodes", {1, kMax, &Service::HandleKeycodes}},
295 {"oneshot", {0, 0, &Service::HandleOneshot}},
296 {"onrestart", {1, kMax, &Service::HandleOnrestart}},
297 {"seclabel", {1, 1, &Service::HandleSeclabel}},
298 {"setenv", {2, 2, &Service::HandleSetenv}},
299 {"socket", {3, 6, &Service::HandleSocket}},
300 {"user", {1, 1, &Service::HandleUser}},
301 {"writepid", {1, kMax, &Service::HandleWritepid}},
302 };
303 return option_handlers;
304}
305
306bool Service::HandleLine(const std::vector<std::string>& args, std::string* err) {
307 if (args.empty()) {
308 *err = "option needed, but not provided";
309 return false;
310 }
311
312 static const OptionHandlerMap handler_map;
313 auto handler = handler_map.FindFunction(args[0], args.size() - 1, err);
314
315 if (!handler) {
316 return false;
317 }
318
319 return (this->*handler)(args, err);
320}
321
Tom Cherrybac32992015-07-31 12:45:25 -0700322bool Service::Start(const std::vector<std::string>& dynamic_args) {
323 // Starting a service removes it from the disabled or reset state and
324 // immediately takes it out of the restarting state if it was in there.
325 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
326 time_started_ = 0;
327
328 // Running processes require no additional work --- if they're in the
329 // process of exiting, we've ensured that they will immediately restart
330 // on exit, unless they are ONESHOT.
331 if (flags_ & SVC_RUNNING) {
332 return false;
333 }
334
335 bool needs_console = (flags_ & SVC_CONSOLE);
336 if (needs_console && !have_console) {
337 ERROR("service '%s' requires console\n", name_.c_str());
338 flags_ |= SVC_DISABLED;
339 return false;
340 }
341
342 struct stat sb;
343 if (stat(args_[0].c_str(), &sb) == -1) {
344 ERROR("cannot find '%s' (%s), disabling '%s'\n",
345 args_[0].c_str(), strerror(errno), name_.c_str());
346 flags_ |= SVC_DISABLED;
347 return false;
348 }
349
350 if ((!(flags_ & SVC_ONESHOT)) && !dynamic_args.empty()) {
351 ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
352 args_[0].c_str());
353 flags_ |= SVC_DISABLED;
354 return false;
355 }
356
357 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
Tom Cherryb7349902015-08-26 11:43:36 -0700423 std::string pid_str = StringPrintf("%d", pid);
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 }
478 for (const auto& s : dynamic_args) {
479 strs.push_back(const_cast<char*>(s.c_str()));
480 }
481 strs.push_back(nullptr);
482 if (execve(args_[0].c_str(), (char**) &strs[0], (char**) ENV) < 0) {
483 ERROR("cannot execve('%s'): %s\n", args_[0].c_str(), strerror(errno));
484 }
485
486 _exit(127);
487 }
488
489 if (pid < 0) {
490 ERROR("failed to start '%s'\n", name_.c_str());
491 pid_ = 0;
492 return false;
493 }
494
495 time_started_ = gettime();
496 pid_ = pid;
497 flags_ |= SVC_RUNNING;
498
499 if ((flags_ & SVC_EXEC) != 0) {
500 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
501 pid_, uid_, gid_, supp_gids_.size(),
502 !seclabel_.empty() ? seclabel_.c_str() : "default");
503 }
504
505 NotifyStateChange("running");
506 return true;
507}
508
509bool Service::Start() {
510 const std::vector<std::string> null_dynamic_args;
511 return Start(null_dynamic_args);
512}
513
514bool Service::StartIfNotDisabled() {
515 if (!(flags_ & SVC_DISABLED)) {
516 return Start();
517 } else {
518 flags_ |= SVC_DISABLED_START;
519 }
520 return true;
521}
522
523bool Service::Enable() {
524 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
525 if (flags_ & SVC_DISABLED_START) {
526 return Start();
527 }
528 return true;
529}
530
531void Service::Reset() {
532 StopOrReset(SVC_RESET);
533}
534
535void Service::Stop() {
536 StopOrReset(SVC_DISABLED);
537}
538
539void Service::Restart() {
540 if (flags_ & SVC_RUNNING) {
541 /* Stop, wait, then start the service. */
542 StopOrReset(SVC_RESTART);
543 } else if (!(flags_ & SVC_RESTARTING)) {
544 /* Just start the service since it's not running. */
545 Start();
546 } /* else: Service is restarting anyways. */
547}
548
549void Service::RestartIfNeeded(time_t& process_needs_restart) {
550 time_t next_start_time = time_started_ + 5;
551
552 if (next_start_time <= gettime()) {
553 flags_ &= (~SVC_RESTARTING);
554 Start();
555 return;
556 }
557
558 if ((next_start_time < process_needs_restart) ||
559 (process_needs_restart == 0)) {
560 process_needs_restart = next_start_time;
561 }
562}
563
564/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
565void Service::StopOrReset(int how) {
566 /* The service is still SVC_RUNNING until its process exits, but if it has
567 * already exited it shoudn't attempt a restart yet. */
568 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
569
570 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
571 /* Hrm, an illegal flag. Default to SVC_DISABLED */
572 how = SVC_DISABLED;
573 }
574 /* if the service has not yet started, prevent
575 * it from auto-starting with its class
576 */
577 if (how == SVC_RESET) {
578 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
579 } else {
580 flags_ |= how;
581 }
582
583 if (pid_) {
584 NOTICE("Service '%s' is being killed...\n", name_.c_str());
585 kill(-pid_, SIGKILL);
586 NotifyStateChange("stopping");
587 } else {
588 NotifyStateChange("stopped");
589 }
590}
591
592void Service::ZapStdio() const {
593 int fd;
594 fd = open("/dev/null", O_RDWR);
595 dup2(fd, 0);
596 dup2(fd, 1);
597 dup2(fd, 2);
598 close(fd);
599}
600
601void Service::OpenConsole() const {
602 int fd;
603 if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
604 fd = open("/dev/null", O_RDWR);
605 }
606 ioctl(fd, TIOCSCTTY, 0);
607 dup2(fd, 0);
608 dup2(fd, 1);
609 dup2(fd, 2);
610 close(fd);
611}
612
613void Service::PublishSocket(const std::string& name, int fd) const {
Tom Cherryb7349902015-08-26 11:43:36 -0700614 std::string key = StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s", name.c_str());
615 std::string val = StringPrintf("%d", fd);
Tom Cherrybac32992015-07-31 12:45:25 -0700616 add_environment(key.c_str(), val.c_str());
617
618 /* make sure we don't close-on-exec */
619 fcntl(fd, F_SETFD, 0);
620}
621
622int ServiceManager::exec_count_ = 0;
623
624ServiceManager::ServiceManager() {
625}
626
627ServiceManager& ServiceManager::GetInstance() {
628 static ServiceManager instance;
629 return instance;
630}
631
Tom Cherryb7349902015-08-26 11:43:36 -0700632void ServiceManager::AddService(std::unique_ptr<Service> service) {
633 Service* old_service = FindServiceByName(service->name());
634 if (old_service) {
635 ERROR("ignored duplicate definition of service '%s'",
636 service->name().c_str());
637 return;
Tom Cherrybac32992015-07-31 12:45:25 -0700638 }
Tom Cherryb7349902015-08-26 11:43:36 -0700639 services_.emplace_back(std::move(service));
Tom Cherrybac32992015-07-31 12:45:25 -0700640}
641
642Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
643 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
644 // SECLABEL can be a - to denote default
645 std::size_t command_arg = 1;
646 for (std::size_t i = 1; i < args.size(); ++i) {
647 if (args[i] == "--") {
648 command_arg = i + 1;
649 break;
650 }
651 }
652 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
653 ERROR("exec called with too many supplementary group ids\n");
654 return nullptr;
655 }
656
657 if (command_arg >= args.size()) {
658 ERROR("exec called without command\n");
659 return nullptr;
660 }
661 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
662
663 exec_count_++;
Tom Cherryb7349902015-08-26 11:43:36 -0700664 std::string name = StringPrintf("exec %d (%s)", exec_count_, str_args[0].c_str());
Tom Cherrybac32992015-07-31 12:45:25 -0700665 unsigned flags = SVC_EXEC | SVC_ONESHOT;
666
667 std::string seclabel = "";
668 if (command_arg > 2 && args[1] != "-") {
669 seclabel = args[1];
670 }
671 uid_t uid = 0;
672 if (command_arg > 3) {
673 uid = decode_uid(args[2].c_str());
674 }
675 gid_t gid = 0;
676 std::vector<gid_t> supp_gids;
677 if (command_arg > 4) {
678 gid = decode_uid(args[3].c_str());
679 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
680 for (size_t i = 0; i < nr_supp_gids; ++i) {
681 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
682 }
683 }
684
685 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
686 supp_gids, seclabel, str_args));
687 if (!svc_p) {
688 ERROR("Couldn't allocate service for exec of '%s'",
689 str_args[0].c_str());
690 return nullptr;
691 }
692 Service* svc = svc_p.get();
693 services_.push_back(std::move(svc_p));
694
695 return svc;
696}
697
698Service* ServiceManager::FindServiceByName(const std::string& name) const {
699 auto svc = std::find_if(services_.begin(), services_.end(),
700 [&name] (const std::unique_ptr<Service>& s) {
701 return name == s->name();
702 });
703 if (svc != services_.end()) {
704 return svc->get();
705 }
706 return nullptr;
707}
708
709Service* ServiceManager::FindServiceByPid(pid_t pid) const {
710 auto svc = std::find_if(services_.begin(), services_.end(),
711 [&pid] (const std::unique_ptr<Service>& s) {
712 return s->pid() == pid;
713 });
714 if (svc != services_.end()) {
715 return svc->get();
716 }
717 return nullptr;
718}
719
720Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
721 auto svc = std::find_if(services_.begin(), services_.end(),
722 [&keychord_id] (const std::unique_ptr<Service>& s) {
723 return s->keychord_id() == keychord_id;
724 });
725
726 if (svc != services_.end()) {
727 return svc->get();
728 }
729 return nullptr;
730}
731
732void ServiceManager::ForEachService(void (*func)(Service* svc)) const {
733 for (const auto& s : services_) {
734 func(s.get());
735 }
736}
737
738void ServiceManager::ForEachServiceInClass(const std::string& classname,
739 void (*func)(Service* svc)) const {
740 for (const auto& s : services_) {
741 if (classname == s->classname()) {
742 func(s.get());
743 }
744 }
745}
746
747void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
748 void (*func)(Service* svc)) const {
749 for (const auto& s : services_) {
750 if (s->flags() & matchflags) {
751 func(s.get());
752 }
753 }
754}
755
Tom Cherryb7349902015-08-26 11:43:36 -0700756void ServiceManager::RemoveService(const Service& svc) {
Tom Cherrybac32992015-07-31 12:45:25 -0700757 auto svc_it = std::find_if(services_.begin(), services_.end(),
758 [&svc] (const std::unique_ptr<Service>& s) {
759 return svc.name() == s->name();
760 });
761 if (svc_it == services_.end()) {
762 return;
763 }
764
765 services_.erase(svc_it);
766}
767
Tom Cherryb7349902015-08-26 11:43:36 -0700768void ServiceManager::DumpState() const {
769 for (const auto& s : services_) {
770 s->DumpState();
771 }
772 INFO("\n");
773}
774
775bool ServiceParser::ParseSection(const std::vector<std::string>& args,
776 std::string* err) {
777 if (args.size() < 3) {
778 *err = "services must have a name and a program";
779 return false;
780 }
781
782 const std::string& name = args[1];
783 if (!IsValidName(name)) {
784 *err = StringPrintf("invalid service name '%s'", name.c_str());
785 return false;
786 }
787
788 std::vector<std::string> str_args(args.begin() + 2, args.end());
789 service_ = std::make_unique<Service>(name, "default", str_args);
790 return true;
791}
792
793bool ServiceParser::ParseLineSection(const std::vector<std::string>& args,
794 const std::string& filename, int line,
795 std::string* err) const {
796 return service_ ? service_->HandleLine(args, err) : false;
797}
798
799void ServiceParser::EndSection() {
800 if (service_) {
801 ServiceManager::GetInstance().AddService(std::move(service_));
802 }
803}
804
805bool ServiceParser::IsValidName(const std::string& name) const {
Tom Cherrybac32992015-07-31 12:45:25 -0700806 if (name.size() > 16) {
807 return false;
808 }
809 for (const auto& c : name) {
810 if (!isalnum(c) && (c != '_') && (c != '-')) {
811 return false;
812 }
813 }
814 return true;
815}