1 /*
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 <inttypes.h>
21 #include <linux/securebits.h>
22 #include <sched.h>
23 #include <sys/prctl.h>
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <termios.h>
27 #include <unistd.h>
28
29 #include <android-base/file.h>
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32 #include <android-base/scopeguard.h>
33 #include <android-base/stringprintf.h>
34 #include <android-base/strings.h>
35 #include <cutils/sockets.h>
36 #include <processgroup/processgroup.h>
37 #include <selinux/selinux.h>
38
39 #include "lmkd_service.h"
40 #include "service_list.h"
41 #include "util.h"
42
43 #ifdef INIT_FULL_SOURCES
44 #include <ApexProperties.sysprop.h>
45 #include <android/api-level.h>
46
47 #include "mount_namespace.h"
48 #include "reboot_utils.h"
49 #include "selinux.h"
50 #else
51 #include "host_init_stubs.h"
52 #endif
53
54 using android::base::boot_clock;
55 using android::base::GetBoolProperty;
56 using android::base::GetProperty;
57 using android::base::Join;
58 using android::base::make_scope_guard;
59 using android::base::SetProperty;
60 using android::base::StartsWith;
61 using android::base::StringPrintf;
62 using android::base::WriteStringToFile;
63
64 namespace android {
65 namespace init {
66
ComputeContextFromExecutable(const std::string & service_path)67 static Result<std::string> ComputeContextFromExecutable(const std::string& service_path) {
68 std::string computed_context;
69
70 char* raw_con = nullptr;
71 char* raw_filecon = nullptr;
72
73 if (getcon(&raw_con) == -1) {
74 return Error() << "Could not get security context";
75 }
76 std::unique_ptr<char, decltype(&freecon)> mycon(raw_con, freecon);
77
78 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) {
79 return Error() << "Could not get file context";
80 }
81 std::unique_ptr<char, decltype(&freecon)> filecon(raw_filecon, freecon);
82
83 char* new_con = nullptr;
84 int rc = security_compute_create(mycon.get(), filecon.get(),
85 string_to_security_class("process"), &new_con);
86 if (rc == 0) {
87 computed_context = new_con;
88 free(new_con);
89 }
90 if (rc == 0 && computed_context == mycon.get()) {
91 return Error() << "File " << service_path << "(labeled \"" << filecon.get()
92 << "\") has incorrect label or no domain transition from " << mycon.get()
93 << " to another SELinux domain defined. Have you configured your "
94 "service correctly? https://source.android.com/security/selinux/"
95 "device-policy#label_new_services_and_address_denials. Note: this "
96 "error shows up even in permissive mode in order to make auditing "
97 "denials possible.";
98 }
99 if (rc < 0) {
100 return Error() << "Could not get process context";
101 }
102 return computed_context;
103 }
104
ExpandArgsAndExecv(const std::vector<std::string> & args,bool sigstop)105 static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigstop) {
106 std::vector<std::string> expanded_args;
107 std::vector<char*> c_strings;
108
109 expanded_args.resize(args.size());
110 c_strings.push_back(const_cast<char*>(args[0].data()));
111 for (std::size_t i = 1; i < args.size(); ++i) {
112 auto expanded_arg = ExpandProps(args[i]);
113 if (!expanded_arg.ok()) {
114 LOG(FATAL) << args[0] << ": cannot expand arguments': " << expanded_arg.error();
115 }
116 expanded_args[i] = *expanded_arg;
117 c_strings.push_back(expanded_args[i].data());
118 }
119 c_strings.push_back(nullptr);
120
121 if (sigstop) {
122 kill(getpid(), SIGSTOP);
123 }
124
125 return execv(c_strings[0], c_strings.data()) == 0;
126 }
127
128 unsigned long Service::next_start_order_ = 1;
129 bool Service::is_exec_service_running_ = false;
130 pid_t Service::exec_service_pid_ = -1;
131 std::chrono::time_point<std::chrono::steady_clock> Service::exec_service_started_;
132
Service(const std::string & name,Subcontext * subcontext_for_restart_commands,const std::vector<std::string> & args,bool from_apex)133 Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
134 const std::vector<std::string>& args, bool from_apex)
135 : Service(name, 0, 0, 0, {}, 0, "", subcontext_for_restart_commands, args, from_apex) {}
136
Service(const std::string & name,unsigned flags,uid_t uid,gid_t gid,const std::vector<gid_t> & supp_gids,int namespace_flags,const std::string & seclabel,Subcontext * subcontext_for_restart_commands,const std::vector<std::string> & args,bool from_apex)137 Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
138 const std::vector<gid_t>& supp_gids, int namespace_flags,
139 const std::string& seclabel, Subcontext* subcontext_for_restart_commands,
140 const std::vector<std::string>& args, bool from_apex)
141 : name_(name),
142 classnames_({"default"}),
143 flags_(flags),
144 pid_(0),
145 crash_count_(0),
146 proc_attr_{.ioprio_class = IoSchedClass_NONE,
147 .ioprio_pri = 0,
148 .uid = uid,
149 .gid = gid,
150 .supp_gids = supp_gids,
151 .priority = 0},
152 namespaces_{.flags = namespace_flags},
153 seclabel_(seclabel),
154 subcontext_(subcontext_for_restart_commands),
155 onrestart_(false, subcontext_for_restart_commands, "<Service '" + name + "' onrestart>", 0,
156 "onrestart", {}),
157 oom_score_adjust_(DEFAULT_OOM_SCORE_ADJUST),
158 start_order_(0),
159 args_(args),
160 from_apex_(from_apex) {}
161
NotifyStateChange(const std::string & new_state) const162 void Service::NotifyStateChange(const std::string& new_state) const {
163 if ((flags_ & SVC_TEMPORARY) != 0) {
164 // Services created by 'exec' are temporary and don't have properties tracking their state.
165 return;
166 }
167
168 std::string prop_name = "init.svc." + name_;
169 SetProperty(prop_name, new_state);
170
171 if (new_state == "running") {
172 uint64_t start_ns = time_started_.time_since_epoch().count();
173 std::string boottime_property = "ro.boottime." + name_;
174 if (GetProperty(boottime_property, "").empty()) {
175 SetProperty(boottime_property, std::to_string(start_ns));
176 }
177 }
178
179 // init.svc_debug_pid.* properties are only for tests, and should not be used
180 // on device for security checks.
181 std::string pid_property = "init.svc_debug_pid." + name_;
182 if (new_state == "running") {
183 SetProperty(pid_property, std::to_string(pid_));
184 } else if (new_state == "stopped") {
185 SetProperty(pid_property, "");
186 }
187 }
188
KillProcessGroup(int signal,bool report_oneshot)189 void Service::KillProcessGroup(int signal, bool report_oneshot) {
190 // If we've already seen a successful result from killProcessGroup*(), then we have removed
191 // the cgroup already and calling these functions a second time will simply result in an error.
192 // This is true regardless of which signal was sent.
193 // These functions handle their own logging, so no additional logging is needed.
194 if (!process_cgroup_empty_) {
195 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_
196 << ") process group...";
197 int max_processes = 0;
198 int r;
199 if (signal == SIGTERM) {
200 r = killProcessGroupOnce(proc_attr_.uid, pid_, signal, &max_processes);
201 } else {
202 r = killProcessGroup(proc_attr_.uid, pid_, signal, &max_processes);
203 }
204
205 if (report_oneshot && max_processes > 0) {
206 LOG(WARNING)
207 << "Killed " << max_processes
208 << " additional processes from a oneshot process group for service '" << name_
209 << "'. This is new behavior, previously child processes would not be killed in "
210 "this case.";
211 }
212
213 if (r == 0) process_cgroup_empty_ = true;
214 }
215
216 if (oom_score_adjust_ != DEFAULT_OOM_SCORE_ADJUST) {
217 LmkdUnregister(name_, pid_);
218 }
219 }
220
SetProcessAttributesAndCaps()221 void Service::SetProcessAttributesAndCaps() {
222 // Keep capabilites on uid change.
223 if (capabilities_ && proc_attr_.uid) {
224 // If Android is running in a container, some securebits might already
225 // be locked, so don't change those.
226 unsigned long securebits = prctl(PR_GET_SECUREBITS);
227 if (securebits == -1UL) {
228 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_;
229 }
230 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED;
231 if (prctl(PR_SET_SECUREBITS, securebits) != 0) {
232 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_;
233 }
234 }
235
236 if (auto result = SetProcessAttributes(proc_attr_); !result.ok()) {
237 LOG(FATAL) << "cannot set attribute for " << name_ << ": " << result.error();
238 }
239
240 if (!seclabel_.empty()) {
241 if (setexeccon(seclabel_.c_str()) < 0) {
242 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_;
243 }
244 }
245
246 if (capabilities_) {
247 if (!SetCapsForExec(*capabilities_)) {
248 LOG(FATAL) << "cannot set capabilities for " << name_;
249 }
250 } else if (proc_attr_.uid) {
251 // Inheritable caps can be non-zero when running in a container.
252 if (!DropInheritableCaps()) {
253 LOG(FATAL) << "cannot drop inheritable caps for " << name_;
254 }
255 }
256 }
257
Reap(const siginfo_t & siginfo)258 void Service::Reap(const siginfo_t& siginfo) {
259 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) {
260 KillProcessGroup(SIGKILL, false);
261 } else {
262 // Legacy behavior from ~2007 until Android R: this else branch did not exist and we did not
263 // kill the process group in this case.
264 if (SelinuxGetVendorAndroidVersion() >= __ANDROID_API_R__) {
265 // The new behavior in Android R is to kill these process groups in all cases. The
266 // 'true' parameter instructions KillProcessGroup() to report a warning message where it
267 // detects a difference in behavior has occurred.
268 KillProcessGroup(SIGKILL, true);
269 }
270 }
271
272 // Remove any socket resources we may have created.
273 for (const auto& socket : sockets_) {
274 if (socket.persist) {
275 continue;
276 }
277 auto path = ANDROID_SOCKET_DIR "/" + socket.name;
278 unlink(path.c_str());
279 }
280
281 for (const auto& f : reap_callbacks_) {
282 f(siginfo);
283 }
284
285 if ((siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) && on_failure_reboot_target_) {
286 LOG(ERROR) << "Service with 'reboot_on_failure' option failed, shutting down system.";
287 trigger_shutdown(*on_failure_reboot_target_);
288 }
289
290 if (flags_ & SVC_EXEC) UnSetExec();
291
292 if (name_ == "zygote" || name_ == "zygote64") {
293 removeAllEmptyProcessGroups();
294 }
295
296 if (flags_ & SVC_TEMPORARY) return;
297
298 pid_ = 0;
299 flags_ &= (~SVC_RUNNING);
300 start_order_ = 0;
301
302 // Oneshot processes go into the disabled state on exit,
303 // except when manually restarted.
304 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART) && !(flags_ & SVC_RESET)) {
305 flags_ |= SVC_DISABLED;
306 }
307
308 // Disabled and reset processes do not get restarted automatically.
309 if (flags_ & (SVC_DISABLED | SVC_RESET)) {
310 NotifyStateChange("stopped");
311 return;
312 }
313
314 #if INIT_FULL_SOURCES
315 static bool is_apex_updatable = android::sysprop::ApexProperties::updatable().value_or(false);
316 #else
317 static bool is_apex_updatable = false;
318 #endif
319 const bool is_process_updatable = !use_bootstrap_ns_ && is_apex_updatable;
320
321 // If we crash > 4 times in 'fatal_crash_window_' minutes or before boot_completed,
322 // reboot into bootloader or set crashing property
323 boot_clock::time_point now = boot_clock::now();
324 if (((flags_ & SVC_CRITICAL) || is_process_updatable) && !(flags_ & SVC_RESTART)) {
325 bool boot_completed = GetBoolProperty("sys.boot_completed", false);
326 if (now < time_crashed_ + fatal_crash_window_ || !boot_completed) {
327 if (++crash_count_ > 4) {
328 auto exit_reason = boot_completed ?
329 "in " + std::to_string(fatal_crash_window_.count()) + " minutes" :
330 "before boot completed";
331 if (flags_ & SVC_CRITICAL) {
332 if (!GetBoolProperty("init.svc_debug.no_fatal." + name_, false)) {
333 // Aborts into `fatal_reboot_target_'.
334 SetFatalRebootTarget(fatal_reboot_target_);
335 LOG(FATAL) << "critical process '" << name_ << "' exited 4 times "
336 << exit_reason;
337 }
338 } else {
339 LOG(ERROR) << "process with updatable components '" << name_
340 << "' exited 4 times " << exit_reason;
341 // Notifies update_verifier and apexd
342 SetProperty("sys.init.updatable_crashing_process_name", name_);
343 SetProperty("sys.init.updatable_crashing", "1");
344 }
345 }
346 } else {
347 time_crashed_ = now;
348 crash_count_ = 1;
349 }
350 }
351
352 flags_ &= (~SVC_RESTART);
353 flags_ |= SVC_RESTARTING;
354
355 // Execute all onrestart commands for this service.
356 onrestart_.ExecuteAllCommands();
357
358 NotifyStateChange("restarting");
359 return;
360 }
361
DumpState() const362 void Service::DumpState() const {
363 LOG(INFO) << "service " << name_;
364 LOG(INFO) << " class '" << Join(classnames_, " ") << "'";
365 LOG(INFO) << " exec " << Join(args_, " ");
366 for (const auto& socket : sockets_) {
367 LOG(INFO) << " socket " << socket.name;
368 }
369 for (const auto& file : files_) {
370 LOG(INFO) << " file " << file.name;
371 }
372 }
373
374
ExecStart()375 Result<void> Service::ExecStart() {
376 auto reboot_on_failure = make_scope_guard([this] {
377 if (on_failure_reboot_target_) {
378 trigger_shutdown(*on_failure_reboot_target_);
379 }
380 });
381
382 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
383 // Don't delay the service for ExecStart() as the semantic is that
384 // the caller might depend on the side effect of the execution.
385 return Error() << "Cannot start an updatable service '" << name_
386 << "' before configs from APEXes are all loaded";
387 }
388
389 flags_ |= SVC_ONESHOT;
390
391 if (auto result = Start(); !result.ok()) {
392 return result;
393 }
394
395 flags_ |= SVC_EXEC;
396 is_exec_service_running_ = true;
397 exec_service_pid_ = pid_;
398 exec_service_started_ = std::chrono::steady_clock::now();
399
400 LOG(INFO) << "SVC_EXEC service '" << name_ << "' pid " << pid_ << " (uid " << proc_attr_.uid
401 << " gid " << proc_attr_.gid << "+" << proc_attr_.supp_gids.size() << " context "
402 << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
403
404 reboot_on_failure.Disable();
405 return {};
406 }
407
ClosePipe(const std::array<int,2> * pipe)408 static void ClosePipe(const std::array<int, 2>* pipe) {
409 for (const auto fd : *pipe) {
410 if (fd >= 0) {
411 close(fd);
412 }
413 }
414 }
415
CheckConsole()416 Result<void> Service::CheckConsole() {
417 if (!(flags_ & SVC_CONSOLE)) {
418 return {};
419 }
420
421 if (proc_attr_.console.empty()) {
422 proc_attr_.console = "/dev/" + GetProperty("ro.boot.console", "console");
423 }
424
425 // Make sure that open call succeeds to ensure a console driver is
426 // properly registered for the device node
427 int console_fd = open(proc_attr_.console.c_str(), O_RDWR | O_CLOEXEC);
428 if (console_fd < 0) {
429 flags_ |= SVC_DISABLED;
430 return ErrnoError() << "Couldn't open console '" << proc_attr_.console << "'";
431 }
432 close(console_fd);
433 return {};
434 }
435
436 // Configures the memory cgroup properties for the service.
ConfigureMemcg()437 void Service::ConfigureMemcg() {
438 if (swappiness_ != -1) {
439 if (!setProcessGroupSwappiness(proc_attr_.uid, pid_, swappiness_)) {
440 PLOG(ERROR) << "setProcessGroupSwappiness failed";
441 }
442 }
443
444 if (soft_limit_in_bytes_ != -1) {
445 if (!setProcessGroupSoftLimit(proc_attr_.uid, pid_, soft_limit_in_bytes_)) {
446 PLOG(ERROR) << "setProcessGroupSoftLimit failed";
447 }
448 }
449
450 size_t computed_limit_in_bytes = limit_in_bytes_;
451 if (limit_percent_ != -1) {
452 long page_size = sysconf(_SC_PAGESIZE);
453 long num_pages = sysconf(_SC_PHYS_PAGES);
454 if (page_size > 0 && num_pages > 0) {
455 size_t max_mem = SIZE_MAX;
456 if (size_t(num_pages) < SIZE_MAX / size_t(page_size)) {
457 max_mem = size_t(num_pages) * size_t(page_size);
458 }
459 computed_limit_in_bytes =
460 std::min(computed_limit_in_bytes, max_mem / 100 * limit_percent_);
461 }
462 }
463
464 if (!limit_property_.empty()) {
465 // This ends up overwriting computed_limit_in_bytes but only if the
466 // property is defined.
467 computed_limit_in_bytes =
468 android::base::GetUintProperty(limit_property_, computed_limit_in_bytes, SIZE_MAX);
469 }
470
471 if (computed_limit_in_bytes != size_t(-1)) {
472 if (!setProcessGroupLimit(proc_attr_.uid, pid_, computed_limit_in_bytes)) {
473 PLOG(ERROR) << "setProcessGroupLimit failed";
474 }
475 }
476 }
477
478 // Enters namespaces, sets environment variables, writes PID files and runs the service executable.
RunService(const std::optional<MountNamespace> & override_mount_namespace,const std::vector<Descriptor> & descriptors,std::unique_ptr<std::array<int,2>,decltype(& ClosePipe) > pipefd)479 void Service::RunService(const std::optional<MountNamespace>& override_mount_namespace,
480 const std::vector<Descriptor>& descriptors,
481 std::unique_ptr<std::array<int, 2>, decltype(&ClosePipe)> pipefd) {
482 if (auto result = EnterNamespaces(namespaces_, name_, override_mount_namespace); !result.ok()) {
483 LOG(FATAL) << "Service '" << name_ << "' failed to set up namespaces: " << result.error();
484 }
485
486 for (const auto& [key, value] : environment_vars_) {
487 setenv(key.c_str(), value.c_str(), 1);
488 }
489
490 for (const auto& descriptor : descriptors) {
491 descriptor.Publish();
492 }
493
494 if (auto result = WritePidToFiles(&writepid_files_); !result.ok()) {
495 LOG(ERROR) << "failed to write pid to files: " << result.error();
496 }
497
498 // Wait until the cgroups have been created and until the cgroup controllers have been
499 // activated.
500 char byte = 0;
501 if (read((*pipefd)[0], &byte, 1) < 0) {
502 PLOG(ERROR) << "failed to read from notification channel";
503 }
504 pipefd.reset();
505 if (!byte) {
506 LOG(FATAL) << "Service '" << name_ << "' failed to start due to a fatal error";
507 _exit(EXIT_FAILURE);
508 }
509
510 if (task_profiles_.size() > 0 && !SetTaskProfiles(getpid(), task_profiles_)) {
511 LOG(ERROR) << "failed to set task profiles";
512 }
513
514 // As requested, set our gid, supplemental gids, uid, context, and
515 // priority. Aborts on failure.
516 SetProcessAttributesAndCaps();
517
518 if (!ExpandArgsAndExecv(args_, sigstop_)) {
519 PLOG(ERROR) << "cannot execv('" << args_[0]
520 << "'). See the 'Debugging init' section of init's README.md for tips";
521 }
522 }
523
Start()524 Result<void> Service::Start() {
525 auto reboot_on_failure = make_scope_guard([this] {
526 if (on_failure_reboot_target_) {
527 trigger_shutdown(*on_failure_reboot_target_);
528 }
529 });
530
531 if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
532 ServiceList::GetInstance().DelayService(*this);
533 return Error() << "Cannot start an updatable service '" << name_
534 << "' before configs from APEXes are all loaded. "
535 << "Queued for execution.";
536 }
537
538 bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET));
539 ResetFlagsForStart();
540
541 // Running processes require no additional work --- if they're in the
542 // process of exiting, we've ensured that they will immediately restart
543 // on exit, unless they are ONESHOT. For ONESHOT service, if it's in
544 // stopping status, we just set SVC_RESTART flag so it will get restarted
545 // in Reap().
546 if (flags_ & SVC_RUNNING) {
547 if ((flags_ & SVC_ONESHOT) && disabled) {
548 flags_ |= SVC_RESTART;
549 }
550
551 LOG(INFO) << "service '" << name_
552 << "' requested start, but it is already running (flags: " << flags_ << ")";
553
554 // It is not an error to try to start a service that is already running.
555 reboot_on_failure.Disable();
556 return {};
557 }
558
559 std::unique_ptr<std::array<int, 2>, decltype(&ClosePipe)> pipefd(new std::array<int, 2>{-1, -1},
560 ClosePipe);
561 if (pipe(pipefd->data()) < 0) {
562 return ErrnoError() << "pipe()";
563 }
564
565 if (Result<void> result = CheckConsole(); !result.ok()) {
566 return result;
567 }
568
569 struct stat sb;
570 if (stat(args_[0].c_str(), &sb) == -1) {
571 flags_ |= SVC_DISABLED;
572 return ErrnoError() << "Cannot find '" << args_[0] << "'";
573 }
574
575 std::string scon;
576 if (!seclabel_.empty()) {
577 scon = seclabel_;
578 } else {
579 auto result = ComputeContextFromExecutable(args_[0]);
580 if (!result.ok()) {
581 return result.error();
582 }
583 scon = *result;
584 }
585
586 // APEXd is always started in the "current" namespace because it is the process to set up
587 // the current namespace.
588 const bool is_apexd = args_[0] == "/system/bin/apexd";
589
590 if (!IsDefaultMountNamespaceReady() && !is_apexd) {
591 // If this service is started before APEXes and corresponding linker configuration
592 // get available, mark it as pre-apexd one. Note that this marking is
593 // permanent. So for example, if the service is re-launched (e.g., due
594 // to crash), it is still recognized as pre-apexd... for consistency.
595 use_bootstrap_ns_ = true;
596 }
597
598 // For pre-apexd services, override mount namespace as "bootstrap" one before starting.
599 // Note: "ueventd" is supposed to be run in "default" mount namespace even if it's pre-apexd
600 // to support loading firmwares from APEXes.
601 std::optional<MountNamespace> override_mount_namespace;
602 if (name_ == "ueventd") {
603 override_mount_namespace = NS_DEFAULT;
604 } else if (use_bootstrap_ns_) {
605 override_mount_namespace = NS_BOOTSTRAP;
606 }
607
608 post_data_ = ServiceList::GetInstance().IsPostData();
609
610 LOG(INFO) << "starting service '" << name_ << "'...";
611
612 std::vector<Descriptor> descriptors;
613 for (const auto& socket : sockets_) {
614 if (auto result = socket.Create(scon); result.ok()) {
615 descriptors.emplace_back(std::move(*result));
616 } else {
617 LOG(INFO) << "Could not create socket '" << socket.name << "': " << result.error();
618 }
619 }
620
621 for (const auto& file : files_) {
622 if (auto result = file.Create(); result.ok()) {
623 descriptors.emplace_back(std::move(*result));
624 } else {
625 LOG(INFO) << "Could not open file '" << file.name << "': " << result.error();
626 }
627 }
628
629 pid_t pid = -1;
630 if (namespaces_.flags) {
631 pid = clone(nullptr, nullptr, namespaces_.flags | SIGCHLD, nullptr);
632 } else {
633 pid = fork();
634 }
635
636 if (pid == 0) {
637 umask(077);
638 RunService(override_mount_namespace, descriptors, std::move(pipefd));
639 _exit(127);
640 }
641
642 if (pid < 0) {
643 pid_ = 0;
644 return ErrnoError() << "Failed to fork";
645 }
646
647 if (oom_score_adjust_ != DEFAULT_OOM_SCORE_ADJUST) {
648 std::string oom_str = std::to_string(oom_score_adjust_);
649 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid);
650 if (!WriteStringToFile(oom_str, oom_file)) {
651 PLOG(ERROR) << "couldn't write oom_score_adj";
652 }
653 }
654
655 time_started_ = boot_clock::now();
656 pid_ = pid;
657 flags_ |= SVC_RUNNING;
658 start_order_ = next_start_order_++;
659 process_cgroup_empty_ = false;
660
661 bool use_memcg = swappiness_ != -1 || soft_limit_in_bytes_ != -1 || limit_in_bytes_ != -1 ||
662 limit_percent_ != -1 || !limit_property_.empty();
663 errno = -createProcessGroup(proc_attr_.uid, pid_, use_memcg);
664 if (errno != 0) {
665 if (char byte = 0; write((*pipefd)[1], &byte, 1) < 0) {
666 return ErrnoError() << "sending notification failed";
667 }
668 return Error() << "createProcessGroup(" << proc_attr_.uid << ", " << pid_
669 << ") failed for service '" << name_ << "'";
670 }
671
672 if (use_memcg) {
673 ConfigureMemcg();
674 }
675
676 if (oom_score_adjust_ != DEFAULT_OOM_SCORE_ADJUST) {
677 LmkdRegister(name_, proc_attr_.uid, pid_, oom_score_adjust_);
678 }
679
680 if (char byte = 1; write((*pipefd)[1], &byte, 1) < 0) {
681 return ErrnoError() << "sending notification failed";
682 }
683
684 NotifyStateChange("running");
685 reboot_on_failure.Disable();
686 return {};
687 }
688
SetStartedInFirstStage(pid_t pid)689 void Service::SetStartedInFirstStage(pid_t pid) {
690 LOG(INFO) << "adding first-stage service '" << name_ << "'...";
691
692 time_started_ = boot_clock::now(); // not accurate, but doesn't matter here
693 pid_ = pid;
694 flags_ |= SVC_RUNNING;
695 start_order_ = next_start_order_++;
696
697 NotifyStateChange("running");
698 }
699
ResetFlagsForStart()700 void Service::ResetFlagsForStart() {
701 // Starting a service removes it from the disabled or reset state and
702 // immediately takes it out of the restarting state if it was in there.
703 flags_ &= ~(SVC_DISABLED | SVC_RESTARTING | SVC_RESET | SVC_RESTART | SVC_DISABLED_START);
704 }
705
StartIfNotDisabled()706 Result<void> Service::StartIfNotDisabled() {
707 if (!(flags_ & SVC_DISABLED)) {
708 return Start();
709 } else {
710 flags_ |= SVC_DISABLED_START;
711 }
712 return {};
713 }
714
Enable()715 Result<void> Service::Enable() {
716 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
717 if (flags_ & SVC_DISABLED_START) {
718 return Start();
719 }
720 return {};
721 }
722
Reset()723 void Service::Reset() {
724 StopOrReset(SVC_RESET);
725 }
726
Stop()727 void Service::Stop() {
728 StopOrReset(SVC_DISABLED);
729 }
730
Terminate()731 void Service::Terminate() {
732 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
733 flags_ |= SVC_DISABLED;
734 if (pid_) {
735 KillProcessGroup(SIGTERM);
736 NotifyStateChange("stopping");
737 }
738 }
739
Timeout()740 void Service::Timeout() {
741 // All process state flags will be taken care of in Reap(), we really just want to kill the
742 // process here when it times out. Oneshot processes will transition to be disabled, and
743 // all other processes will transition to be restarting.
744 LOG(INFO) << "Service '" << name_ << "' expired its timeout of " << timeout_period_->count()
745 << " seconds and will now be killed";
746 if (pid_) {
747 KillProcessGroup(SIGKILL);
748 NotifyStateChange("stopping");
749 }
750 }
751
Restart()752 void Service::Restart() {
753 if (flags_ & SVC_RUNNING) {
754 /* Stop, wait, then start the service. */
755 StopOrReset(SVC_RESTART);
756 } else if (!(flags_ & SVC_RESTARTING)) {
757 /* Just start the service since it's not running. */
758 if (auto result = Start(); !result.ok()) {
759 LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
760 }
761 } /* else: Service is restarting anyways. */
762 }
763
764 // The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART.
StopOrReset(int how)765 void Service::StopOrReset(int how) {
766 // The service is still SVC_RUNNING until its process exits, but if it has
767 // already exited it shoudn't attempt a restart yet.
768 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START);
769
770 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) {
771 // An illegal flag: default to SVC_DISABLED.
772 how = SVC_DISABLED;
773 }
774
775 // If the service has not yet started, prevent it from auto-starting with its class.
776 if (how == SVC_RESET) {
777 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET;
778 } else {
779 flags_ |= how;
780 }
781 // Make sure it's in right status when a restart immediately follow a
782 // stop/reset or vice versa.
783 if (how == SVC_RESTART) {
784 flags_ &= (~(SVC_DISABLED | SVC_RESET));
785 } else {
786 flags_ &= (~SVC_RESTART);
787 }
788
789 if (pid_) {
790 KillProcessGroup(SIGKILL);
791 NotifyStateChange("stopping");
792 } else {
793 NotifyStateChange("stopped");
794 }
795 }
796
MakeTemporaryOneshotService(const std::vector<std::string> & args)797 Result<std::unique_ptr<Service>> Service::MakeTemporaryOneshotService(
798 const std::vector<std::string>& args) {
799 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
800 // SECLABEL can be a - to denote default
801 std::size_t command_arg = 1;
802 for (std::size_t i = 1; i < args.size(); ++i) {
803 if (args[i] == "--") {
804 command_arg = i + 1;
805 break;
806 }
807 }
808 if (command_arg > 4 + NR_SVC_SUPP_GIDS) {
809 return Error() << "exec called with too many supplementary group ids";
810 }
811
812 if (command_arg >= args.size()) {
813 return Error() << "exec called without command";
814 }
815 std::vector<std::string> str_args(args.begin() + command_arg, args.end());
816
817 static size_t exec_count = 0;
818 exec_count++;
819 std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")";
820
821 unsigned flags = SVC_ONESHOT | SVC_TEMPORARY;
822 unsigned namespace_flags = 0;
823
824 std::string seclabel = "";
825 if (command_arg > 2 && args[1] != "-") {
826 seclabel = args[1];
827 }
828 Result<uid_t> uid = 0;
829 if (command_arg > 3) {
830 uid = DecodeUid(args[2]);
831 if (!uid.ok()) {
832 return Error() << "Unable to decode UID for '" << args[2] << "': " << uid.error();
833 }
834 }
835 Result<gid_t> gid = 0;
836 std::vector<gid_t> supp_gids;
837 if (command_arg > 4) {
838 gid = DecodeUid(args[3]);
839 if (!gid.ok()) {
840 return Error() << "Unable to decode GID for '" << args[3] << "': " << gid.error();
841 }
842 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
843 for (size_t i = 0; i < nr_supp_gids; ++i) {
844 auto supp_gid = DecodeUid(args[4 + i]);
845 if (!supp_gid.ok()) {
846 return Error() << "Unable to decode GID for '" << args[4 + i]
847 << "': " << supp_gid.error();
848 }
849 supp_gids.push_back(*supp_gid);
850 }
851 }
852
853 return std::make_unique<Service>(name, flags, *uid, *gid, supp_gids, namespace_flags, seclabel,
854 nullptr, str_args, false);
855 }
856
857 // This is used for snapuserd_proxy, which hands off a socket to snapuserd. It's
858 // a special case to support the daemon launched in first-stage init. The persist
859 // feature is not part of the init language and is only used here.
MarkSocketPersistent(const std::string & socket_name)860 bool Service::MarkSocketPersistent(const std::string& socket_name) {
861 for (auto& socket : sockets_) {
862 if (socket.name == socket_name) {
863 socket.persist = true;
864 return true;
865 }
866 }
867 return false;
868 }
869
870 } // namespace init
871 } // namespace android
872