blob: 5c2a0cb81acb9516ae31795e22c58a6b8e49713c [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>
23
24#include <selinux/selinux.h>
25
26#include <base/file.h>
27#include <base/stringprintf.h>
28#include <cutils/android_reboot.h>
29#include <cutils/sockets.h>
30
31#include "action.h"
32#include "init.h"
33#include "init_parser.h"
34#include "keywords.h"
35#include "log.h"
36#include "property_service.h"
37#include "util.h"
38
39#define CRITICAL_CRASH_THRESHOLD 4 // if we crash >4 times ...
40#define CRITICAL_CRASH_WINDOW (4*60) // ... in 4 minutes, goto recovery
41
42SocketInfo::SocketInfo() : uid(0), gid(0), perm(0) {
43}
44
45SocketInfo::SocketInfo(const std::string& name, const std::string& type, uid_t uid,
46 gid_t gid, int perm, const std::string& socketcon)
47 : name(name), type(type), uid(uid), gid(gid), perm(perm), socketcon(socketcon) {
48}
49
50ServiceEnvironmentInfo::ServiceEnvironmentInfo() {
51}
52
53ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name,
54 const std::string& value)
55 : name(name), value(value) {
56}
57
58Service::Service(const std::string& name, const std::string& classname,
59 const std::vector<std::string>& args)
60 : name_(name), classname_(classname), flags_(0), pid_(0), time_started_(0),
61 time_crashed_(0), nr_crashed_(0), uid_(0), gid_(0), seclabel_(""),
62 ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
63 onrestart_.InitSingleTrigger("onrestart");
64}
65
66Service::Service(const std::string& name, const std::string& classname,
67 unsigned flags, uid_t uid, gid_t gid, const std::vector<gid_t>& supp_gids,
68 const std::string& seclabel, const std::vector<std::string>& args)
69 : name_(name), classname_(classname), flags_(flags), pid_(0), time_started_(0),
70 time_crashed_(0), nr_crashed_(0), uid_(uid), gid_(gid), supp_gids_(supp_gids),
71 seclabel_(seclabel), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
72 onrestart_.InitSingleTrigger("onrestart");
73}
74
75void Service::NotifyStateChange(const std::string& new_state) const {
76 if (!properties_initialized()) {
77 // If properties aren't available yet, we can't set them.
78 return;
79 }
80
81 if ((flags_ & SVC_EXEC) != 0) {
82 // 'exec' commands don't have properties tracking their state.
83 return;
84 }
85
86 std::string prop_name = android::base::StringPrintf("init.svc.%s", name_.c_str());
87 if (prop_name.length() >= PROP_NAME_MAX) {
88 // If the property name would be too long, we can't set it.
89 ERROR("Property name \"init.svc.%s\" too long; not setting to %s\n",
90 name_.c_str(), new_state.c_str());
91 return;
92 }
93
94 property_set(prop_name.c_str(), new_state.c_str());
95}
96
97bool Service::Reap() {
98 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
99 NOTICE("Service '%s' (pid %d) killing any children in process group\n",
100 name_.c_str(), pid_);
101 kill(-pid_, SIGKILL);
102 }
103
104 // Remove any sockets we may have created.
105 for (const auto& si : sockets_) {
106 std::string tmp = android::base::StringPrintf(ANDROID_SOCKET_DIR "/%s",
107 si.name.c_str());
108 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
170bool Service::HandleLine(int kw, const std::vector<std::string>& args, std::string* err) {
171 std::vector<std::string> str_args;
172
173 ioprio_class_ = IoSchedClass_NONE;
174
175 switch (kw) {
176 case K_class:
177 if (args.size() != 2) {
178 *err = "class option requires a classname\n";
179 return false;
180 } else {
181 classname_ = args[1];
182 }
183 break;
184 case K_console:
185 flags_ |= SVC_CONSOLE;
186 break;
187 case K_disabled:
188 flags_ |= SVC_DISABLED;
189 flags_ |= SVC_RC_DISABLED;
190 break;
191 case K_ioprio:
192 if (args.size() != 3) {
193 *err = "ioprio optin usage: ioprio <rt|be|idle> <ioprio 0-7>\n";
194 return false;
195 } else {
196 ioprio_pri_ = std::stoul(args[2], 0, 8);
197
198 if (ioprio_pri_ < 0 || ioprio_pri_ > 7) {
199 *err = "priority value must be range 0 - 7\n";
200 return false;
201 }
202
203 if (args[1] == "rt") {
204 ioprio_class_ = IoSchedClass_RT;
205 } else if (args[1] == "be") {
206 ioprio_class_ = IoSchedClass_BE;
207 } else if (args[1] == "idle") {
208 ioprio_class_ = IoSchedClass_IDLE;
209 } else {
210 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>\n";
211 return false;
212 }
213 }
214 break;
215 case K_group:
216 if (args.size() < 2) {
217 *err = "group option requires a group id\n";
218 return false;
219 } else if (args.size() > NR_SVC_SUPP_GIDS + 2) {
220 *err = android::base::StringPrintf("group option accepts at most %d supp. groups\n",
221 NR_SVC_SUPP_GIDS);
222 return false;
223 } else {
224 gid_ = decode_uid(args[1].c_str());
225 for (std::size_t n = 2; n < args.size(); n++) {
226 supp_gids_.push_back(decode_uid(args[n].c_str()));
227 }
228 }
229 break;
230 case K_keycodes:
231 if (args.size() < 2) {
232 *err = "keycodes option requires atleast one keycode\n";
233 return false;
234 } else {
235 for (std::size_t i = 1; i < args.size(); i++) {
236 keycodes_.push_back(std::stoi(args[i]));
237 }
238 }
239 break;
240 case K_oneshot:
241 flags_ |= SVC_ONESHOT;
242 break;
243 case K_onrestart:
244 if (args.size() < 2) {
245 return false;
246 }
247 str_args.assign(args.begin() + 1, args.end());
248 add_command_to_action(&onrestart_, str_args, "", 0, err);
249 break;
250 case K_critical:
251 flags_ |= SVC_CRITICAL;
252 break;
253 case K_setenv: { /* name value */
254 if (args.size() < 3) {
255 *err = "setenv option requires name and value arguments\n";
256 return false;
257 }
258
259 envvars_.push_back({args[1], args[2]});
260 break;
261 }
262 case K_socket: {/* name type perm [ uid gid context ] */
263 if (args.size() < 4) {
264 *err = "socket option requires name, type, perm arguments\n";
265 return false;
266 }
267 if (args[2] != "dgram" && args[2] != "stream" &&
268 args[2] != "seqpacket") {
269 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'\n";
270 return false;
271 }
272
273 int perm = std::stoul(args[3], 0, 8);
274 uid_t uid = args.size() > 4 ? decode_uid(args[4].c_str()) : 0;
275 gid_t gid = args.size() > 5 ? decode_uid(args[5].c_str()) : 0;
276 std::string socketcon = args.size() > 6 ? args[6] : "";
277
278 sockets_.push_back({args[1], args[2], uid, gid, perm, socketcon});
279 break;
280 }
281 case K_user:
282 if (args.size() != 2) {
283 *err = "user option requires a user id\n";
284 return false;
285 } else {
286 uid_ = decode_uid(args[1].c_str());
287 }
288 break;
289 case K_seclabel:
290 if (args.size() != 2) {
291 *err = "seclabel option requires a label string\n";
292 return false;
293 } else {
294 seclabel_ = args[1];
295 }
296 break;
297 case K_writepid:
298 if (args.size() < 2) {
299 *err = "writepid option requires at least one filename\n";
300 return false;
301 }
302 writepid_files_.assign(args.begin() + 1, args.end());
303 break;
304
305 default:
306 *err = android::base::StringPrintf("invalid option '%s'\n", args[0].c_str());
307 return false;
308 }
309 return true;
310}
311
312bool Service::Start(const std::vector<std::string>& dynamic_args) {
313 // Starting a service removes it from the disabled or reset state and
314 // immediately takes it out of the restarting state if it was in there.
315 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
316 time_started_ = 0;
317
318 // Running processes require no additional work --- if they're in the
319 // process of exiting, we've ensured that they will immediately restart
320 // on exit, unless they are ONESHOT.
321 if (flags_ & SVC_RUNNING) {
322 return false;
323 }
324
325 bool needs_console = (flags_ & SVC_CONSOLE);
326 if (needs_console && !have_console) {
327 ERROR("service '%s' requires console\n", name_.c_str());
328 flags_ |= SVC_DISABLED;
329 return false;
330 }
331
332 struct stat sb;
333 if (stat(args_[0].c_str(), &sb) == -1) {
334 ERROR("cannot find '%s' (%s), disabling '%s'\n",
335 args_[0].c_str(), strerror(errno), name_.c_str());
336 flags_ |= SVC_DISABLED;
337 return false;
338 }
339
340 if ((!(flags_ & SVC_ONESHOT)) && !dynamic_args.empty()) {
341 ERROR("service '%s' must be one-shot to use dynamic args, disabling\n",
342 args_[0].c_str());
343 flags_ |= SVC_DISABLED;
344 return false;
345 }
346
347 std::string scon;
348 if (!seclabel_.empty()) {
349 scon = seclabel_;
350 } else {
351 char* mycon = nullptr;
352 char* fcon = nullptr;
353
354 INFO("computing context for service '%s'\n", args_[0].c_str());
355 int rc = getcon(&mycon);
356 if (rc < 0) {
357 ERROR("could not get context while starting '%s'\n", name_.c_str());
358 return false;
359 }
360
361 rc = getfilecon(args_[0].c_str(), &fcon);
362 if (rc < 0) {
363 ERROR("could not get context while starting '%s'\n", name_.c_str());
364 free(mycon);
365 return false;
366 }
367
368 char* ret_scon = nullptr;
369 rc = security_compute_create(mycon, fcon, string_to_security_class("process"),
370 &ret_scon);
371 if (rc == 0) {
372 scon = ret_scon;
373 free(ret_scon);
374 }
375 if (rc == 0 && scon == mycon) {
376 ERROR("Service %s does not have a SELinux domain defined.\n", name_.c_str());
377 free(mycon);
378 free(fcon);
379 return false;
380 }
381 free(mycon);
382 free(fcon);
383 if (rc < 0) {
384 ERROR("could not get context while starting '%s'\n", name_.c_str());
385 return false;
386 }
387 }
388
389 NOTICE("Starting service '%s'...\n", name_.c_str());
390
391 pid_t pid = fork();
392 if (pid == 0) {
393 int fd, sz;
394
395 umask(077);
396 if (properties_initialized()) {
397 get_property_workspace(&fd, &sz);
398 std::string tmp = android::base::StringPrintf("%d,%d", dup(fd), sz);
399 add_environment("ANDROID_PROPERTY_WORKSPACE", tmp.c_str());
400 }
401
402 for (const auto& ei : envvars_) {
403 add_environment(ei.name.c_str(), ei.value.c_str());
404 }
405
406 for (const auto& si : sockets_) {
407 int socket_type = ((si.type == "stream" ? SOCK_STREAM :
408 (si.type == "dgram" ? SOCK_DGRAM :
409 SOCK_SEQPACKET)));
410 const char* socketcon =
411 !si.socketcon.empty() ? si.socketcon.c_str() : scon.c_str();
412
413 int s = create_socket(si.name.c_str(), socket_type, si.perm,
414 si.uid, si.gid, socketcon);
415 if (s >= 0) {
416 PublishSocket(si.name, s);
417 }
418 }
419
420 std::string pid_str = android::base::StringPrintf("%d", pid);
421 for (const auto& file : writepid_files_) {
422 if (!android::base::WriteStringToFile(pid_str, file)) {
423 ERROR("couldn't write %s to %s: %s\n",
424 pid_str.c_str(), file.c_str(), strerror(errno));
425 }
426 }
427
428 if (ioprio_class_ != IoSchedClass_NONE) {
429 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) {
430 ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
431 getpid(), ioprio_class_, ioprio_pri_, strerror(errno));
432 }
433 }
434
435 if (needs_console) {
436 setsid();
437 OpenConsole();
438 } else {
439 ZapStdio();
440 }
441
442 setpgid(0, getpid());
443
444 // As requested, set our gid, supplemental gids, and uid.
445 if (gid_) {
446 if (setgid(gid_) != 0) {
447 ERROR("setgid failed: %s\n", strerror(errno));
448 _exit(127);
449 }
450 }
451 if (!supp_gids_.empty()) {
452 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) {
453 ERROR("setgroups failed: %s\n", strerror(errno));
454 _exit(127);
455 }
456 }
457 if (uid_) {
458 if (setuid(uid_) != 0) {
459 ERROR("setuid failed: %s\n", strerror(errno));
460 _exit(127);
461 }
462 }
463 if (!seclabel_.empty()) {
464 if (setexeccon(seclabel_.c_str()) < 0) {
465 ERROR("cannot setexeccon('%s'): %s\n",
466 seclabel_.c_str(), strerror(errno));
467 _exit(127);
468 }
469 }
470
471 std::vector<char*> strs;
472 for (const auto& s : args_) {
473 strs.push_back(const_cast<char*>(s.c_str()));
474 }
475 for (const auto& s : dynamic_args) {
476 strs.push_back(const_cast<char*>(s.c_str()));
477 }
478 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;
495
496 if ((flags_ & SVC_EXEC) != 0) {
497 INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
498 pid_, uid_, gid_, supp_gids_.size(),
499 !seclabel_.empty() ? seclabel_.c_str() : "default");
500 }
501
502 NotifyStateChange("running");
503 return true;
504}
505
506bool Service::Start() {
507 const std::vector<std::string> null_dynamic_args;
508 return Start(null_dynamic_args);
509}
510
511bool Service::StartIfNotDisabled() {
512 if (!(flags_ & SVC_DISABLED)) {
513 return Start();
514 } else {
515 flags_ |= SVC_DISABLED_START;
516 }
517 return true;
518}
519
520bool Service::Enable() {
521 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
522 if (flags_ & SVC_DISABLED_START) {
523 return Start();
524 }
525 return true;
526}
527
528void Service::Reset() {
529 StopOrReset(SVC_RESET);
530}
531
532void Service::Stop() {
533 StopOrReset(SVC_DISABLED);
534}
535
536void Service::Restart() {
537 if (flags_ & SVC_RUNNING) {
538 /* Stop, wait, then start the service. */
539 StopOrReset(SVC_RESTART);
540 } else if (!(flags_ & SVC_RESTARTING)) {
541 /* Just start the service since it's not running. */
542 Start();
543 } /* else: Service is restarting anyways. */
544}
545
546void Service::RestartIfNeeded(time_t& process_needs_restart) {
547 time_t next_start_time = time_started_ + 5;
548
549 if (next_start_time <= gettime()) {
550 flags_ &= (~SVC_RESTARTING);
551 Start();
552 return;
553 }
554
555 if ((next_start_time < process_needs_restart) ||
556 (process_needs_restart == 0)) {
557 process_needs_restart = next_start_time;
558 }
559}
560
561/* The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART */
562void Service::StopOrReset(int how) {
563 /* The service is still SVC_RUNNING until its process exits, but if it has
564 * already exited it shoudn't attempt a restart yet. */
565 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
566
567 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
568 /* Hrm, an illegal flag. Default to SVC_DISABLED */
569 how = SVC_DISABLED;
570 }
571 /* if the service has not yet started, prevent
572 * it from auto-starting with its class
573 */
574 if (how == SVC_RESET) {
575 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
576 } else {
577 flags_ |= how;
578 }
579
580 if (pid_) {
581 NOTICE("Service '%s' is being killed...\n", name_.c_str());
582 kill(-pid_, SIGKILL);
583 NotifyStateChange("stopping");
584 } else {
585 NotifyStateChange("stopped");
586 }
587}
588
589void Service::ZapStdio() const {
590 int fd;
591 fd = open("/dev/null", O_RDWR);
592 dup2(fd, 0);
593 dup2(fd, 1);
594 dup2(fd, 2);
595 close(fd);
596}
597
598void Service::OpenConsole() const {
599 int fd;
600 if ((fd = open(console_name.c_str(), O_RDWR)) < 0) {
601 fd = open("/dev/null", O_RDWR);
602 }
603 ioctl(fd, TIOCSCTTY, 0);
604 dup2(fd, 0);
605 dup2(fd, 1);
606 dup2(fd, 2);
607 close(fd);
608}
609
610void Service::PublishSocket(const std::string& name, int fd) const {
611 std::string key = android::base::StringPrintf(ANDROID_SOCKET_ENV_PREFIX "%s",
612 name.c_str());
613 std::string val = android::base::StringPrintf("%d", fd);
614 add_environment(key.c_str(), val.c_str());
615
616 /* make sure we don't close-on-exec */
617 fcntl(fd, F_SETFD, 0);
618}
619
620int ServiceManager::exec_count_ = 0;
621
622ServiceManager::ServiceManager() {
623}
624
625ServiceManager& ServiceManager::GetInstance() {
626 static ServiceManager instance;
627 return instance;
628}
629
630Service* ServiceManager::AddNewService(const std::string& name,
631 const std::string& classname,
632 const std::vector<std::string>& args,
633 std::string* err) {
634 if (!IsValidName(name)) {
635 *err = android::base::StringPrintf("invalid service name '%s'\n", name.c_str());
636 return nullptr;
637 }
638
639 Service* svc = ServiceManager::GetInstance().FindServiceByName(name);
640 if (svc) {
641 *err = android::base::StringPrintf("ignored duplicate definition of service '%s'\n",
642 name.c_str());
643 return nullptr;
644 }
645
646 std::unique_ptr<Service> svc_p(new Service(name, classname, args));
647 if (!svc_p) {
648 ERROR("Couldn't allocate service for service '%s'", name.c_str());
649 return nullptr;
650 }
651 svc = svc_p.get();
652 services_.push_back(std::move(svc_p));
653
654 return svc;
655}
656
657Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) {
658 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
659 // SECLABEL can be a - to denote default
660 std::size_t command_arg = 1;
661 for (std::size_t i = 1; i < args.size(); ++i) {
662 if (args[i] == "--") {
663 command_arg = i + 1;
664 break;
665 }
666 }
667 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
668 ERROR("exec called with too many supplementary group ids\n");
669 return nullptr;
670 }
671
672 if (command_arg >= args.size()) {
673 ERROR("exec called without command\n");
674 return nullptr;
675 }
676 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
677
678 exec_count_++;
679 std::string name = android::base::StringPrintf("exec %d (%s)", exec_count_,
680 str_args[0].c_str());
681 unsigned flags = SVC_EXEC | SVC_ONESHOT;
682
683 std::string seclabel = "";
684 if (command_arg > 2 && args[1] != "-") {
685 seclabel = args[1];
686 }
687 uid_t uid = 0;
688 if (command_arg > 3) {
689 uid = decode_uid(args[2].c_str());
690 }
691 gid_t gid = 0;
692 std::vector<gid_t> supp_gids;
693 if (command_arg > 4) {
694 gid = decode_uid(args[3].c_str());
695 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
696 for (size_t i = 0; i < nr_supp_gids; ++i) {
697 supp_gids.push_back(decode_uid(args[4 + i].c_str()));
698 }
699 }
700
701 std::unique_ptr<Service> svc_p(new Service(name, "default", flags, uid, gid,
702 supp_gids, seclabel, str_args));
703 if (!svc_p) {
704 ERROR("Couldn't allocate service for exec of '%s'",
705 str_args[0].c_str());
706 return nullptr;
707 }
708 Service* svc = svc_p.get();
709 services_.push_back(std::move(svc_p));
710
711 return svc;
712}
713
714Service* ServiceManager::FindServiceByName(const std::string& name) const {
715 auto svc = std::find_if(services_.begin(), services_.end(),
716 [&name] (const std::unique_ptr<Service>& s) {
717 return name == s->name();
718 });
719 if (svc != services_.end()) {
720 return svc->get();
721 }
722 return nullptr;
723}
724
725Service* ServiceManager::FindServiceByPid(pid_t pid) const {
726 auto svc = std::find_if(services_.begin(), services_.end(),
727 [&pid] (const std::unique_ptr<Service>& s) {
728 return s->pid() == pid;
729 });
730 if (svc != services_.end()) {
731 return svc->get();
732 }
733 return nullptr;
734}
735
736Service* ServiceManager::FindServiceByKeychord(int keychord_id) const {
737 auto svc = std::find_if(services_.begin(), services_.end(),
738 [&keychord_id] (const std::unique_ptr<Service>& s) {
739 return s->keychord_id() == keychord_id;
740 });
741
742 if (svc != services_.end()) {
743 return svc->get();
744 }
745 return nullptr;
746}
747
748void ServiceManager::ForEachService(void (*func)(Service* svc)) const {
749 for (const auto& s : services_) {
750 func(s.get());
751 }
752}
753
754void ServiceManager::ForEachServiceInClass(const std::string& classname,
755 void (*func)(Service* svc)) const {
756 for (const auto& s : services_) {
757 if (classname == s->classname()) {
758 func(s.get());
759 }
760 }
761}
762
763void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
764 void (*func)(Service* svc)) const {
765 for (const auto& s : services_) {
766 if (s->flags() & matchflags) {
767 func(s.get());
768 }
769 }
770}
771
772void ServiceManager::RemoveService(const Service& svc)
773{
774 auto svc_it = std::find_if(services_.begin(), services_.end(),
775 [&svc] (const std::unique_ptr<Service>& s) {
776 return svc.name() == s->name();
777 });
778 if (svc_it == services_.end()) {
779 return;
780 }
781
782 services_.erase(svc_it);
783}
784
785bool ServiceManager::IsValidName(const std::string& name) const
786{
787 if (name.size() > 16) {
788 return false;
789 }
790 for (const auto& c : name) {
791 if (!isalnum(c) && (c != '_') && (c != '-')) {
792 return false;
793 }
794 }
795 return true;
796}
797
798void ServiceManager::DumpState() const
799{
800 for (const auto& s : services_) {
801 s->DumpState();
802 }
803 INFO("\n");
804}