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/mount.h> 24 #include <sys/prctl.h> 25 #include <sys/resource.h> 26 #include <sys/stat.h> 27 #include <sys/system_properties.h> 28 #include <sys/time.h> 29 #include <sys/wait.h> 30 #include <termios.h> 31 #include <unistd.h> 32 33 #include <android-base/file.h> 34 #include <android-base/logging.h> 35 #include <android-base/parseint.h> 36 #include <android-base/properties.h> 37 #include <android-base/scopeguard.h> 38 #include <android-base/stringprintf.h> 39 #include <android-base/strings.h> 40 #include <processgroup/processgroup.h> 41 #include <selinux/selinux.h> 42 #include <system/thread_defs.h> 43 44 #include "init.h" 45 #include "property_service.h" 46 #include "util.h" 47 48 using android::base::boot_clock; 49 using android::base::GetProperty; 50 using android::base::Join; 51 using android::base::make_scope_guard; 52 using android::base::ParseInt; 53 using android::base::StartsWith; 54 using android::base::StringPrintf; 55 using android::base::WriteStringToFile; 56 57 namespace android { 58 namespace init { 59 60 static std::string ComputeContextFromExecutable(std::string& service_name, 61 const std::string& service_path) { 62 std::string computed_context; 63 64 char* raw_con = nullptr; 65 char* raw_filecon = nullptr; 66 67 if (getcon(&raw_con) == -1) { 68 LOG(ERROR) << "could not get context while starting '" << service_name << "'"; 69 return ""; 70 } 71 std::unique_ptr<char> mycon(raw_con); 72 73 if (getfilecon(service_path.c_str(), &raw_filecon) == -1) { 74 LOG(ERROR) << "could not get file context while starting '" << service_name << "'"; 75 return ""; 76 } 77 std::unique_ptr<char> filecon(raw_filecon); 78 79 char* new_con = nullptr; 80 int rc = security_compute_create(mycon.get(), filecon.get(), 81 string_to_security_class("process"), &new_con); 82 if (rc == 0) { 83 computed_context = new_con; 84 free(new_con); 85 } 86 if (rc == 0 && computed_context == mycon.get()) { 87 LOG(ERROR) << "service " << service_name << " does not have a SELinux domain defined"; 88 return ""; 89 } 90 if (rc < 0) { 91 LOG(ERROR) << "could not get context while starting '" << service_name << "'"; 92 return ""; 93 } 94 return computed_context; 95 } 96 97 static void SetUpPidNamespace(const std::string& service_name) { 98 constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID; 99 100 // It's OK to LOG(FATAL) in this function since it's running in the first 101 // child process. 102 if (mount("", "/proc", "proc", kSafeFlags | MS_REMOUNT, "") == -1) { 103 PLOG(FATAL) << "couldn't remount(/proc) for " << service_name; 104 } 105 106 if (prctl(PR_SET_NAME, service_name.c_str()) == -1) { 107 PLOG(FATAL) << "couldn't set name for " << service_name; 108 } 109 110 pid_t child_pid = fork(); 111 if (child_pid == -1) { 112 PLOG(FATAL) << "couldn't fork init inside the PID namespace for " << service_name; 113 } 114 115 if (child_pid > 0) { 116 // So that we exit with the right status. 117 static int init_exitstatus = 0; 118 signal(SIGTERM, [](int) { _exit(init_exitstatus); }); 119 120 pid_t waited_pid; 121 int status; 122 while ((waited_pid = wait(&status)) > 0) { 123 // This loop will end when there are no processes left inside the 124 // PID namespace or when the init process inside the PID namespace 125 // gets a signal. 126 if (waited_pid == child_pid) { 127 init_exitstatus = status; 128 } 129 } 130 if (!WIFEXITED(init_exitstatus)) { 131 _exit(EXIT_FAILURE); 132 } 133 _exit(WEXITSTATUS(init_exitstatus)); 134 } 135 } 136 137 static bool ExpandArgsAndExecve(const std::vector<std::string>& args) { 138 std::vector<std::string> expanded_args; 139 std::vector<char*> c_strings; 140 141 expanded_args.resize(args.size()); 142 c_strings.push_back(const_cast<char*>(args[0].data())); 143 for (std::size_t i = 1; i < args.size(); ++i) { 144 if (!expand_props(args[i], &expanded_args[i])) { 145 LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'"; 146 } 147 c_strings.push_back(expanded_args[i].data()); 148 } 149 c_strings.push_back(nullptr); 150 151 return execve(c_strings[0], c_strings.data(), (char**)ENV) == 0; 152 } 153 154 ServiceEnvironmentInfo::ServiceEnvironmentInfo() { 155 } 156 157 ServiceEnvironmentInfo::ServiceEnvironmentInfo(const std::string& name, 158 const std::string& value) 159 : name(name), value(value) { 160 } 161 162 Service::Service(const std::string& name, const std::vector<std::string>& args) 163 : name_(name), 164 classnames_({"default"}), 165 flags_(0), 166 pid_(0), 167 crash_count_(0), 168 uid_(0), 169 gid_(0), 170 namespace_flags_(0), 171 seclabel_(""), 172 onrestart_(false, "<Service '" + name + "' onrestart>", 0), 173 keychord_id_(0), 174 ioprio_class_(IoSchedClass_NONE), 175 ioprio_pri_(0), 176 priority_(0), 177 oom_score_adjust_(-1000), 178 swappiness_(-1), 179 soft_limit_in_bytes_(-1), 180 limit_in_bytes_(-1), 181 args_(args) { 182 onrestart_.InitSingleTrigger("onrestart"); 183 } 184 185 Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid, 186 const std::vector<gid_t>& supp_gids, const CapSet& capabilities, 187 unsigned namespace_flags, const std::string& seclabel, 188 const std::vector<std::string>& args) 189 : name_(name), 190 classnames_({"default"}), 191 flags_(flags), 192 pid_(0), 193 crash_count_(0), 194 uid_(uid), 195 gid_(gid), 196 supp_gids_(supp_gids), 197 capabilities_(capabilities), 198 namespace_flags_(namespace_flags), 199 seclabel_(seclabel), 200 onrestart_(false, "<Service '" + name + "' onrestart>", 0), 201 keychord_id_(0), 202 ioprio_class_(IoSchedClass_NONE), 203 ioprio_pri_(0), 204 priority_(0), 205 oom_score_adjust_(-1000), 206 swappiness_(-1), 207 soft_limit_in_bytes_(-1), 208 limit_in_bytes_(-1), 209 args_(args) { 210 onrestart_.InitSingleTrigger("onrestart"); 211 } 212 213 void Service::NotifyStateChange(const std::string& new_state) const { 214 if ((flags_ & SVC_TEMPORARY) != 0) { 215 // Services created by 'exec' are temporary and don't have properties tracking their state. 216 return; 217 } 218 219 std::string prop_name = "init.svc." + name_; 220 property_set(prop_name, new_state); 221 222 if (new_state == "running") { 223 uint64_t start_ns = time_started_.time_since_epoch().count(); 224 property_set("ro.boottime." + name_, std::to_string(start_ns)); 225 } 226 } 227 228 void Service::KillProcessGroup(int signal) { 229 // If we've already seen a successful result from killProcessGroup*(), then we have removed 230 // the cgroup already and calling these functions a second time will simply result in an error. 231 // This is true regardless of which signal was sent. 232 // These functions handle their own logging, so no additional logging is needed. 233 if (!process_cgroup_empty_) { 234 LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_ 235 << ") process group..."; 236 int r; 237 if (signal == SIGTERM) { 238 r = killProcessGroupOnce(uid_, pid_, signal); 239 } else { 240 r = killProcessGroup(uid_, pid_, signal); 241 } 242 243 if (r == 0) process_cgroup_empty_ = true; 244 } 245 } 246 247 void Service::SetProcessAttributes() { 248 // Keep capabilites on uid change. 249 if (capabilities_.any() && uid_) { 250 // If Android is running in a container, some securebits might already 251 // be locked, so don't change those. 252 unsigned long securebits = prctl(PR_GET_SECUREBITS); 253 if (securebits == -1UL) { 254 PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_; 255 } 256 securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED; 257 if (prctl(PR_SET_SECUREBITS, securebits) != 0) { 258 PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_; 259 } 260 } 261 262 // TODO: work out why this fails for `console` then upgrade to FATAL. 263 if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_; 264 265 if (gid_) { 266 if (setgid(gid_) != 0) { 267 PLOG(FATAL) << "setgid failed for " << name_; 268 } 269 } 270 if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) { 271 PLOG(FATAL) << "setgroups failed for " << name_; 272 } 273 if (uid_) { 274 if (setuid(uid_) != 0) { 275 PLOG(FATAL) << "setuid failed for " << name_; 276 } 277 } 278 if (!seclabel_.empty()) { 279 if (setexeccon(seclabel_.c_str()) < 0) { 280 PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_; 281 } 282 } 283 if (priority_ != 0) { 284 if (setpriority(PRIO_PROCESS, 0, priority_) != 0) { 285 PLOG(FATAL) << "setpriority failed for " << name_; 286 } 287 } 288 if (capabilities_.any()) { 289 if (!SetCapsForExec(capabilities_)) { 290 LOG(FATAL) << "cannot set capabilities for " << name_; 291 } 292 } 293 } 294 295 void Service::Reap() { 296 if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) { 297 KillProcessGroup(SIGKILL); 298 } 299 300 // Remove any descriptor resources we may have created. 301 std::for_each(descriptors_.begin(), descriptors_.end(), 302 std::bind(&DescriptorInfo::Clean, std::placeholders::_1)); 303 304 if (flags_ & SVC_TEMPORARY) { 305 return; 306 } 307 308 pid_ = 0; 309 flags_ &= (~SVC_RUNNING); 310 311 // Oneshot processes go into the disabled state on exit, 312 // except when manually restarted. 313 if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) { 314 flags_ |= SVC_DISABLED; 315 } 316 317 // Disabled and reset processes do not get restarted automatically. 318 if (flags_ & (SVC_DISABLED | SVC_RESET)) { 319 NotifyStateChange("stopped"); 320 return; 321 } 322 323 // If we crash > 4 times in 4 minutes, reboot into recovery. 324 boot_clock::time_point now = boot_clock::now(); 325 if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) { 326 if (now < time_crashed_ + 4min) { 327 if (++crash_count_ > 4) { 328 LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes"; 329 panic(); 330 } 331 } else { 332 time_crashed_ = now; 333 crash_count_ = 1; 334 } 335 } 336 337 flags_ &= (~SVC_RESTART); 338 flags_ |= SVC_RESTARTING; 339 340 // Execute all onrestart commands for this service. 341 onrestart_.ExecuteAllCommands(); 342 343 NotifyStateChange("restarting"); 344 return; 345 } 346 347 void Service::DumpState() const { 348 LOG(INFO) << "service " << name_; 349 LOG(INFO) << " class '" << Join(classnames_, " ") << "'"; 350 LOG(INFO) << " exec " << Join(args_, " "); 351 std::for_each(descriptors_.begin(), descriptors_.end(), 352 [] (const auto& info) { LOG(INFO) << *info; }); 353 } 354 355 bool Service::ParseCapabilities(const std::vector<std::string>& args, std::string* err) { 356 capabilities_ = 0; 357 358 if (!CapAmbientSupported()) { 359 *err = "capabilities requested but the kernel does not support ambient capabilities"; 360 return false; 361 } 362 363 unsigned int last_valid_cap = GetLastValidCap(); 364 if (last_valid_cap >= capabilities_.size()) { 365 LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP"; 366 } 367 368 for (size_t i = 1; i < args.size(); i++) { 369 const std::string& arg = args[i]; 370 int res = LookupCap(arg); 371 if (res < 0) { 372 *err = StringPrintf("invalid capability '%s'", arg.c_str()); 373 return false; 374 } 375 unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0. 376 if (cap > last_valid_cap) { 377 *err = StringPrintf("capability '%s' not supported by the kernel", arg.c_str()); 378 return false; 379 } 380 capabilities_[cap] = true; 381 } 382 return true; 383 } 384 385 bool Service::ParseClass(const std::vector<std::string>& args, std::string* err) { 386 classnames_ = std::set<std::string>(args.begin() + 1, args.end()); 387 return true; 388 } 389 390 bool Service::ParseConsole(const std::vector<std::string>& args, std::string* err) { 391 flags_ |= SVC_CONSOLE; 392 console_ = args.size() > 1 ? "/dev/" + args[1] : ""; 393 return true; 394 } 395 396 bool Service::ParseCritical(const std::vector<std::string>& args, std::string* err) { 397 flags_ |= SVC_CRITICAL; 398 return true; 399 } 400 401 bool Service::ParseDisabled(const std::vector<std::string>& args, std::string* err) { 402 flags_ |= SVC_DISABLED; 403 flags_ |= SVC_RC_DISABLED; 404 return true; 405 } 406 407 bool Service::ParseGroup(const std::vector<std::string>& args, std::string* err) { 408 std::string decode_uid_err; 409 if (!DecodeUid(args[1], &gid_, &decode_uid_err)) { 410 *err = "Unable to find GID for '" + args[1] + "': " + decode_uid_err; 411 return false; 412 } 413 for (std::size_t n = 2; n < args.size(); n++) { 414 gid_t gid; 415 if (!DecodeUid(args[n], &gid, &decode_uid_err)) { 416 *err = "Unable to find GID for '" + args[n] + "': " + decode_uid_err; 417 return false; 418 } 419 supp_gids_.emplace_back(gid); 420 } 421 return true; 422 } 423 424 bool Service::ParsePriority(const std::vector<std::string>& args, std::string* err) { 425 priority_ = 0; 426 if (!ParseInt(args[1], &priority_, 427 static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative 428 static_cast<int>(ANDROID_PRIORITY_LOWEST))) { 429 *err = StringPrintf("process priority value must be range %d - %d", 430 ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST); 431 return false; 432 } 433 return true; 434 } 435 436 bool Service::ParseIoprio(const std::vector<std::string>& args, std::string* err) { 437 if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) { 438 *err = "priority value must be range 0 - 7"; 439 return false; 440 } 441 442 if (args[1] == "rt") { 443 ioprio_class_ = IoSchedClass_RT; 444 } else if (args[1] == "be") { 445 ioprio_class_ = IoSchedClass_BE; 446 } else if (args[1] == "idle") { 447 ioprio_class_ = IoSchedClass_IDLE; 448 } else { 449 *err = "ioprio option usage: ioprio <rt|be|idle> <0-7>"; 450 return false; 451 } 452 453 return true; 454 } 455 456 bool Service::ParseKeycodes(const std::vector<std::string>& args, std::string* err) { 457 for (std::size_t i = 1; i < args.size(); i++) { 458 int code; 459 if (ParseInt(args[i], &code)) { 460 keycodes_.emplace_back(code); 461 } else { 462 LOG(WARNING) << "ignoring invalid keycode: " << args[i]; 463 } 464 } 465 return true; 466 } 467 468 bool Service::ParseOneshot(const std::vector<std::string>& args, std::string* err) { 469 flags_ |= SVC_ONESHOT; 470 return true; 471 } 472 473 bool Service::ParseOnrestart(const std::vector<std::string>& args, std::string* err) { 474 std::vector<std::string> str_args(args.begin() + 1, args.end()); 475 int line = onrestart_.NumCommands() + 1; 476 onrestart_.AddCommand(str_args, line, err); 477 return true; 478 } 479 480 bool Service::ParseNamespace(const std::vector<std::string>& args, std::string* err) { 481 for (size_t i = 1; i < args.size(); i++) { 482 if (args[i] == "pid") { 483 namespace_flags_ |= CLONE_NEWPID; 484 // PID namespaces require mount namespaces. 485 namespace_flags_ |= CLONE_NEWNS; 486 } else if (args[i] == "mnt") { 487 namespace_flags_ |= CLONE_NEWNS; 488 } else { 489 *err = "namespace must be 'pid' or 'mnt'"; 490 return false; 491 } 492 } 493 return true; 494 } 495 496 bool Service::ParseOomScoreAdjust(const std::vector<std::string>& args, std::string* err) { 497 if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) { 498 *err = "oom_score_adjust value must be in range -1000 - +1000"; 499 return false; 500 } 501 return true; 502 } 503 504 bool Service::ParseMemcgSwappiness(const std::vector<std::string>& args, std::string* err) { 505 if (!ParseInt(args[1], &swappiness_, 0)) { 506 *err = "swappiness value must be equal or greater than 0"; 507 return false; 508 } 509 return true; 510 } 511 512 bool Service::ParseMemcgLimitInBytes(const std::vector<std::string>& args, std::string* err) { 513 if (!ParseInt(args[1], &limit_in_bytes_, 0)) { 514 *err = "limit_in_bytes value must be equal or greater than 0"; 515 return false; 516 } 517 return true; 518 } 519 520 bool Service::ParseMemcgSoftLimitInBytes(const std::vector<std::string>& args, std::string* err) { 521 if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) { 522 *err = "soft_limit_in_bytes value must be equal or greater than 0"; 523 return false; 524 } 525 return true; 526 } 527 528 bool Service::ParseSeclabel(const std::vector<std::string>& args, std::string* err) { 529 seclabel_ = args[1]; 530 return true; 531 } 532 533 bool Service::ParseSetenv(const std::vector<std::string>& args, std::string* err) { 534 envvars_.emplace_back(args[1], args[2]); 535 return true; 536 } 537 538 bool Service::ParseShutdown(const std::vector<std::string>& args, std::string* err) { 539 if (args[1] == "critical") { 540 flags_ |= SVC_SHUTDOWN_CRITICAL; 541 return true; 542 } 543 return false; 544 } 545 546 template <typename T> 547 bool Service::AddDescriptor(const std::vector<std::string>& args, std::string* err) { 548 int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1; 549 uid_t uid = 0; 550 gid_t gid = 0; 551 std::string context = args.size() > 6 ? args[6] : ""; 552 553 std::string decode_uid_err; 554 if (args.size() > 4) { 555 if (!DecodeUid(args[4], &uid, &decode_uid_err)) { 556 *err = "Unable to find UID for '" + args[4] + "': " + decode_uid_err; 557 return false; 558 } 559 } 560 561 if (args.size() > 5) { 562 if (!DecodeUid(args[5], &gid, &decode_uid_err)) { 563 *err = "Unable to find GID for '" + args[5] + "': " + decode_uid_err; 564 return false; 565 } 566 } 567 568 auto descriptor = std::make_unique<T>(args[1], args[2], uid, gid, perm, context); 569 570 auto old = 571 std::find_if(descriptors_.begin(), descriptors_.end(), 572 [&descriptor] (const auto& other) { return descriptor.get() == other.get(); }); 573 574 if (old != descriptors_.end()) { 575 *err = "duplicate descriptor " + args[1] + " " + args[2]; 576 return false; 577 } 578 579 descriptors_.emplace_back(std::move(descriptor)); 580 return true; 581 } 582 583 // name type perm [ uid gid context ] 584 bool Service::ParseSocket(const std::vector<std::string>& args, std::string* err) { 585 if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") && 586 !StartsWith(args[2], "seqpacket")) { 587 *err = "socket type must be 'dgram', 'stream' or 'seqpacket'"; 588 return false; 589 } 590 return AddDescriptor<SocketInfo>(args, err); 591 } 592 593 // name type perm [ uid gid context ] 594 bool Service::ParseFile(const std::vector<std::string>& args, std::string* err) { 595 if (args[2] != "r" && args[2] != "w" && args[2] != "rw") { 596 *err = "file type must be 'r', 'w' or 'rw'"; 597 return false; 598 } 599 if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) { 600 *err = "file name must not be relative"; 601 return false; 602 } 603 return AddDescriptor<FileInfo>(args, err); 604 } 605 606 bool Service::ParseUser(const std::vector<std::string>& args, std::string* err) { 607 std::string decode_uid_err; 608 if (!DecodeUid(args[1], &uid_, &decode_uid_err)) { 609 *err = "Unable to find UID for '" + args[1] + "': " + decode_uid_err; 610 return false; 611 } 612 return true; 613 } 614 615 bool Service::ParseWritepid(const std::vector<std::string>& args, std::string* err) { 616 writepid_files_.assign(args.begin() + 1, args.end()); 617 return true; 618 } 619 620 class Service::OptionParserMap : public KeywordMap<OptionParser> { 621 public: 622 OptionParserMap() {} 623 624 private: 625 const Map& map() const override; 626 }; 627 628 const Service::OptionParserMap::Map& Service::OptionParserMap::map() const { 629 constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max(); 630 // clang-format off 631 static const Map option_parsers = { 632 {"capabilities", 633 {1, kMax, &Service::ParseCapabilities}}, 634 {"class", {1, kMax, &Service::ParseClass}}, 635 {"console", {0, 1, &Service::ParseConsole}}, 636 {"critical", {0, 0, &Service::ParseCritical}}, 637 {"disabled", {0, 0, &Service::ParseDisabled}}, 638 {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}}, 639 {"ioprio", {2, 2, &Service::ParseIoprio}}, 640 {"priority", {1, 1, &Service::ParsePriority}}, 641 {"keycodes", {1, kMax, &Service::ParseKeycodes}}, 642 {"oneshot", {0, 0, &Service::ParseOneshot}}, 643 {"onrestart", {1, kMax, &Service::ParseOnrestart}}, 644 {"oom_score_adjust", 645 {1, 1, &Service::ParseOomScoreAdjust}}, 646 {"memcg.swappiness", 647 {1, 1, &Service::ParseMemcgSwappiness}}, 648 {"memcg.soft_limit_in_bytes", 649 {1, 1, &Service::ParseMemcgSoftLimitInBytes}}, 650 {"memcg.limit_in_bytes", 651 {1, 1, &Service::ParseMemcgLimitInBytes}}, 652 {"namespace", {1, 2, &Service::ParseNamespace}}, 653 {"seclabel", {1, 1, &Service::ParseSeclabel}}, 654 {"setenv", {2, 2, &Service::ParseSetenv}}, 655 {"shutdown", {1, 1, &Service::ParseShutdown}}, 656 {"socket", {3, 6, &Service::ParseSocket}}, 657 {"file", {2, 2, &Service::ParseFile}}, 658 {"user", {1, 1, &Service::ParseUser}}, 659 {"writepid", {1, kMax, &Service::ParseWritepid}}, 660 }; 661 // clang-format on 662 return option_parsers; 663 } 664 665 bool Service::ParseLine(const std::vector<std::string>& args, std::string* err) { 666 static const OptionParserMap parser_map; 667 auto parser = parser_map.FindFunction(args, err); 668 669 if (!parser) { 670 return false; 671 } 672 673 return (this->*parser)(args, err); 674 } 675 676 bool Service::ExecStart(std::unique_ptr<android::base::Timer>* exec_waiter) { 677 flags_ |= SVC_EXEC | SVC_ONESHOT; 678 679 exec_waiter->reset(new android::base::Timer); 680 681 if (!Start()) { 682 exec_waiter->reset(); 683 return false; 684 } 685 return true; 686 } 687 688 bool Service::Start() { 689 // Starting a service removes it from the disabled or reset state and 690 // immediately takes it out of the restarting state if it was in there. 691 flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START)); 692 693 // Running processes require no additional work --- if they're in the 694 // process of exiting, we've ensured that they will immediately restart 695 // on exit, unless they are ONESHOT. 696 if (flags_ & SVC_RUNNING) { 697 return false; 698 } 699 700 bool needs_console = (flags_ & SVC_CONSOLE); 701 if (needs_console) { 702 if (console_.empty()) { 703 console_ = default_console; 704 } 705 706 // Make sure that open call succeeds to ensure a console driver is 707 // properly registered for the device node 708 int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC); 709 if (console_fd < 0) { 710 PLOG(ERROR) << "service '" << name_ << "' couldn't open console '" << console_ << "'"; 711 flags_ |= SVC_DISABLED; 712 return false; 713 } 714 close(console_fd); 715 } 716 717 struct stat sb; 718 if (stat(args_[0].c_str(), &sb) == -1) { 719 PLOG(ERROR) << "cannot find '" << args_[0] << "', disabling '" << name_ << "'"; 720 flags_ |= SVC_DISABLED; 721 return false; 722 } 723 724 std::string scon; 725 if (!seclabel_.empty()) { 726 scon = seclabel_; 727 } else { 728 scon = ComputeContextFromExecutable(name_, args_[0]); 729 if (scon == "") { 730 return false; 731 } 732 } 733 734 LOG(INFO) << "starting service '" << name_ << "'..."; 735 736 pid_t pid = -1; 737 if (namespace_flags_) { 738 pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr); 739 } else { 740 pid = fork(); 741 } 742 743 if (pid == 0) { 744 umask(077); 745 746 if (namespace_flags_ & CLONE_NEWPID) { 747 // This will fork again to run an init process inside the PID 748 // namespace. 749 SetUpPidNamespace(name_); 750 } 751 752 for (const auto& ei : envvars_) { 753 add_environment(ei.name.c_str(), ei.value.c_str()); 754 } 755 756 std::for_each(descriptors_.begin(), descriptors_.end(), 757 std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon)); 758 759 // See if there were "writepid" instructions to write to files under /dev/cpuset/. 760 auto cpuset_predicate = [](const std::string& path) { 761 return StartsWith(path, "/dev/cpuset/"); 762 }; 763 auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate); 764 if (iter == writepid_files_.end()) { 765 // There were no "writepid" instructions for cpusets, check if the system default 766 // cpuset is specified to be used for the process. 767 std::string default_cpuset = GetProperty("ro.cpuset.default", ""); 768 if (!default_cpuset.empty()) { 769 // Make sure the cpuset name starts and ends with '/'. 770 // A single '/' means the 'root' cpuset. 771 if (default_cpuset.front() != '/') { 772 default_cpuset.insert(0, 1, '/'); 773 } 774 if (default_cpuset.back() != '/') { 775 default_cpuset.push_back('/'); 776 } 777 writepid_files_.push_back( 778 StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str())); 779 } 780 } 781 std::string pid_str = std::to_string(getpid()); 782 for (const auto& file : writepid_files_) { 783 if (!WriteStringToFile(pid_str, file)) { 784 PLOG(ERROR) << "couldn't write " << pid_str << " to " << file; 785 } 786 } 787 788 if (ioprio_class_ != IoSchedClass_NONE) { 789 if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) { 790 PLOG(ERROR) << "failed to set pid " << getpid() 791 << " ioprio=" << ioprio_class_ << "," << ioprio_pri_; 792 } 793 } 794 795 if (needs_console) { 796 setsid(); 797 OpenConsole(); 798 } else { 799 ZapStdio(); 800 } 801 802 // As requested, set our gid, supplemental gids, uid, context, and 803 // priority. Aborts on failure. 804 SetProcessAttributes(); 805 806 if (!ExpandArgsAndExecve(args_)) { 807 PLOG(ERROR) << "cannot execve('" << args_[0] << "')"; 808 } 809 810 _exit(127); 811 } 812 813 if (pid < 0) { 814 PLOG(ERROR) << "failed to fork for '" << name_ << "'"; 815 pid_ = 0; 816 return false; 817 } 818 819 if (oom_score_adjust_ != -1000) { 820 std::string oom_str = std::to_string(oom_score_adjust_); 821 std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid); 822 if (!WriteStringToFile(oom_str, oom_file)) { 823 PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno); 824 } 825 } 826 827 time_started_ = boot_clock::now(); 828 pid_ = pid; 829 flags_ |= SVC_RUNNING; 830 process_cgroup_empty_ = false; 831 832 errno = -createProcessGroup(uid_, pid_); 833 if (errno != 0) { 834 PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '" 835 << name_ << "'"; 836 } else { 837 if (swappiness_ != -1) { 838 if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) { 839 PLOG(ERROR) << "setProcessGroupSwappiness failed"; 840 } 841 } 842 843 if (soft_limit_in_bytes_ != -1) { 844 if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) { 845 PLOG(ERROR) << "setProcessGroupSoftLimit failed"; 846 } 847 } 848 849 if (limit_in_bytes_ != -1) { 850 if (!setProcessGroupLimit(uid_, pid_, limit_in_bytes_)) { 851 PLOG(ERROR) << "setProcessGroupLimit failed"; 852 } 853 } 854 } 855 856 if ((flags_ & SVC_EXEC) != 0) { 857 LOG(INFO) << "SVC_EXEC pid " << pid_ << " (uid " << uid_ << " gid " << gid_ << "+" 858 << supp_gids_.size() << " context " 859 << (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting..."; 860 } 861 862 NotifyStateChange("running"); 863 return true; 864 } 865 866 bool Service::StartIfNotDisabled() { 867 if (!(flags_ & SVC_DISABLED)) { 868 return Start(); 869 } else { 870 flags_ |= SVC_DISABLED_START; 871 } 872 return true; 873 } 874 875 bool Service::Enable() { 876 flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED); 877 if (flags_ & SVC_DISABLED_START) { 878 return Start(); 879 } 880 return true; 881 } 882 883 void Service::Reset() { 884 StopOrReset(SVC_RESET); 885 } 886 887 void Service::Stop() { 888 StopOrReset(SVC_DISABLED); 889 } 890 891 void Service::Terminate() { 892 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START); 893 flags_ |= SVC_DISABLED; 894 if (pid_) { 895 KillProcessGroup(SIGTERM); 896 NotifyStateChange("stopping"); 897 } 898 } 899 900 void Service::Restart() { 901 if (flags_ & SVC_RUNNING) { 902 /* Stop, wait, then start the service. */ 903 StopOrReset(SVC_RESTART); 904 } else if (!(flags_ & SVC_RESTARTING)) { 905 /* Just start the service since it's not running. */ 906 Start(); 907 } /* else: Service is restarting anyways. */ 908 } 909 910 void Service::RestartIfNeeded(time_t* process_needs_restart_at) { 911 boot_clock::time_point now = boot_clock::now(); 912 boot_clock::time_point next_start = time_started_ + 5s; 913 if (now > next_start) { 914 flags_ &= (~SVC_RESTARTING); 915 Start(); 916 return; 917 } 918 919 time_t next_start_time_t = time(nullptr) + 920 time_t(std::chrono::duration_cast<std::chrono::seconds>(next_start - now).count()); 921 if (next_start_time_t < *process_needs_restart_at || *process_needs_restart_at == 0) { 922 *process_needs_restart_at = next_start_time_t; 923 } 924 } 925 926 // The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART. 927 void Service::StopOrReset(int how) { 928 // The service is still SVC_RUNNING until its process exits, but if it has 929 // already exited it shoudn't attempt a restart yet. 930 flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START); 931 932 if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) { 933 // An illegal flag: default to SVC_DISABLED. 934 how = SVC_DISABLED; 935 } 936 937 // If the service has not yet started, prevent it from auto-starting with its class. 938 if (how == SVC_RESET) { 939 flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET; 940 } else { 941 flags_ |= how; 942 } 943 944 if (pid_) { 945 KillProcessGroup(SIGKILL); 946 NotifyStateChange("stopping"); 947 } else { 948 NotifyStateChange("stopped"); 949 } 950 } 951 952 void Service::ZapStdio() const { 953 int fd; 954 fd = open("/dev/null", O_RDWR); 955 dup2(fd, 0); 956 dup2(fd, 1); 957 dup2(fd, 2); 958 close(fd); 959 } 960 961 void Service::OpenConsole() const { 962 int fd = open(console_.c_str(), O_RDWR); 963 if (fd == -1) fd = open("/dev/null", O_RDWR); 964 ioctl(fd, TIOCSCTTY, 0); 965 dup2(fd, 0); 966 dup2(fd, 1); 967 dup2(fd, 2); 968 close(fd); 969 } 970 971 int ServiceManager::exec_count_ = 0; 972 973 ServiceManager::ServiceManager() { 974 } 975 976 ServiceManager& ServiceManager::GetInstance() { 977 static ServiceManager instance; 978 return instance; 979 } 980 981 void ServiceManager::AddService(std::unique_ptr<Service> service) { 982 services_.emplace_back(std::move(service)); 983 } 984 985 bool ServiceManager::Exec(const std::vector<std::string>& args) { 986 Service* svc = MakeExecOneshotService(args); 987 if (!svc) { 988 LOG(ERROR) << "Could not create exec service"; 989 return false; 990 } 991 if (!svc->ExecStart(&exec_waiter_)) { 992 LOG(ERROR) << "Could not start exec service"; 993 ServiceManager::GetInstance().RemoveService(*svc); 994 return false; 995 } 996 return true; 997 } 998 999 bool ServiceManager::ExecStart(const std::string& name) { 1000 Service* svc = FindServiceByName(name); 1001 if (!svc) { 1002 LOG(ERROR) << "ExecStart(" << name << "): Service not found"; 1003 return false; 1004 } 1005 if (!svc->ExecStart(&exec_waiter_)) { 1006 LOG(ERROR) << "ExecStart(" << name << "): Could not start Service"; 1007 return false; 1008 } 1009 return true; 1010 } 1011 1012 bool ServiceManager::IsWaitingForExec() const { return exec_waiter_ != nullptr; } 1013 1014 Service* ServiceManager::MakeExecOneshotService(const std::vector<std::string>& args) { 1015 // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS... 1016 // SECLABEL can be a - to denote default 1017 std::size_t command_arg = 1; 1018 for (std::size_t i = 1; i < args.size(); ++i) { 1019 if (args[i] == "--") { 1020 command_arg = i + 1; 1021 break; 1022 } 1023 } 1024 if (command_arg > 4 + NR_SVC_SUPP_GIDS) { 1025 LOG(ERROR) << "exec called with too many supplementary group ids"; 1026 return nullptr; 1027 } 1028 1029 if (command_arg >= args.size()) { 1030 LOG(ERROR) << "exec called without command"; 1031 return nullptr; 1032 } 1033 std::vector<std::string> str_args(args.begin() + command_arg, args.end()); 1034 1035 exec_count_++; 1036 std::string name = "exec " + std::to_string(exec_count_) + " (" + Join(str_args, " ") + ")"; 1037 1038 unsigned flags = SVC_EXEC | SVC_ONESHOT | SVC_TEMPORARY; 1039 CapSet no_capabilities; 1040 unsigned namespace_flags = 0; 1041 1042 std::string seclabel = ""; 1043 if (command_arg > 2 && args[1] != "-") { 1044 seclabel = args[1]; 1045 } 1046 uid_t uid = 0; 1047 if (command_arg > 3) { 1048 std::string decode_uid_err; 1049 if (!DecodeUid(args[2], &uid, &decode_uid_err)) { 1050 LOG(ERROR) << "Unable to find UID for '" << args[2] << "': " << decode_uid_err; 1051 return nullptr; 1052 } 1053 } 1054 gid_t gid = 0; 1055 std::vector<gid_t> supp_gids; 1056 if (command_arg > 4) { 1057 std::string decode_uid_err; 1058 if (!DecodeUid(args[3], &gid, &decode_uid_err)) { 1059 LOG(ERROR) << "Unable to find GID for '" << args[3] << "': " << decode_uid_err; 1060 return nullptr; 1061 } 1062 std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */; 1063 for (size_t i = 0; i < nr_supp_gids; ++i) { 1064 gid_t supp_gid; 1065 if (!DecodeUid(args[4 + i], &supp_gid, &decode_uid_err)) { 1066 LOG(ERROR) << "Unable to find UID for '" << args[4 + i] << "': " << decode_uid_err; 1067 return nullptr; 1068 } 1069 supp_gids.push_back(supp_gid); 1070 } 1071 } 1072 1073 auto svc_p = std::make_unique<Service>(name, flags, uid, gid, supp_gids, no_capabilities, 1074 namespace_flags, seclabel, str_args); 1075 Service* svc = svc_p.get(); 1076 services_.emplace_back(std::move(svc_p)); 1077 1078 return svc; 1079 } 1080 1081 Service* ServiceManager::FindServiceByName(const std::string& name) const { 1082 auto svc = std::find_if(services_.begin(), services_.end(), 1083 [&name] (const std::unique_ptr<Service>& s) { 1084 return name == s->name(); 1085 }); 1086 if (svc != services_.end()) { 1087 return svc->get(); 1088 } 1089 return nullptr; 1090 } 1091 1092 Service* ServiceManager::FindServiceByPid(pid_t pid) const { 1093 auto svc = std::find_if(services_.begin(), services_.end(), 1094 [&pid] (const std::unique_ptr<Service>& s) { 1095 return s->pid() == pid; 1096 }); 1097 if (svc != services_.end()) { 1098 return svc->get(); 1099 } 1100 return nullptr; 1101 } 1102 1103 Service* ServiceManager::FindServiceByKeychord(int keychord_id) const { 1104 auto svc = std::find_if(services_.begin(), services_.end(), 1105 [&keychord_id] (const std::unique_ptr<Service>& s) { 1106 return s->keychord_id() == keychord_id; 1107 }); 1108 1109 if (svc != services_.end()) { 1110 return svc->get(); 1111 } 1112 return nullptr; 1113 } 1114 1115 void ServiceManager::ForEachService(const std::function<void(Service*)>& callback) const { 1116 for (const auto& s : services_) { 1117 callback(s.get()); 1118 } 1119 } 1120 1121 void ServiceManager::ForEachServiceInClass(const std::string& classname, 1122 void (*func)(Service* svc)) const { 1123 for (const auto& s : services_) { 1124 if (s->classnames().find(classname) != s->classnames().end()) { 1125 func(s.get()); 1126 } 1127 } 1128 } 1129 1130 void ServiceManager::ForEachServiceWithFlags(unsigned matchflags, 1131 void (*func)(Service* svc)) const { 1132 for (const auto& s : services_) { 1133 if (s->flags() & matchflags) { 1134 func(s.get()); 1135 } 1136 } 1137 } 1138 1139 void ServiceManager::RemoveService(const Service& svc) { 1140 auto svc_it = std::find_if(services_.begin(), services_.end(), 1141 [&svc] (const std::unique_ptr<Service>& s) { 1142 return svc.name() == s->name(); 1143 }); 1144 if (svc_it == services_.end()) { 1145 return; 1146 } 1147 1148 services_.erase(svc_it); 1149 } 1150 1151 void ServiceManager::DumpState() const { 1152 for (const auto& s : services_) { 1153 s->DumpState(); 1154 } 1155 } 1156 1157 bool ServiceManager::ReapOneProcess() { 1158 siginfo_t siginfo = {}; 1159 // This returns a zombie pid or informs us that there are no zombies left to be reaped. 1160 // It does NOT reap the pid; that is done below. 1161 if (TEMP_FAILURE_RETRY(waitid(P_ALL, 0, &siginfo, WEXITED | WNOHANG | WNOWAIT)) != 0) { 1162 PLOG(ERROR) << "waitid failed"; 1163 return false; 1164 } 1165 1166 auto pid = siginfo.si_pid; 1167 if (pid == 0) return false; 1168 1169 // At this point we know we have a zombie pid, so we use this scopeguard to reap the pid 1170 // whenever the function returns from this point forward. 1171 // We do NOT want to reap the zombie earlier as in Service::Reap(), we kill(-pid, ...) and we 1172 // want the pid to remain valid throughout that (and potentially future) usages. 1173 auto reaper = make_scope_guard([pid] { TEMP_FAILURE_RETRY(waitpid(pid, nullptr, WNOHANG)); }); 1174 1175 if (PropertyChildReap(pid)) { 1176 return true; 1177 } 1178 1179 Service* svc = FindServiceByPid(pid); 1180 1181 std::string name; 1182 std::string wait_string; 1183 if (svc) { 1184 name = StringPrintf("Service '%s' (pid %d)", svc->name().c_str(), pid); 1185 if (svc->flags() & SVC_EXEC) { 1186 wait_string = StringPrintf(" waiting took %f seconds", 1187 exec_waiter_->duration().count() / 1000.0f); 1188 } 1189 } else { 1190 name = StringPrintf("Untracked pid %d", pid); 1191 } 1192 1193 auto status = siginfo.si_status; 1194 if (WIFEXITED(status)) { 1195 LOG(INFO) << name << " exited with status " << WEXITSTATUS(status) << wait_string; 1196 } else if (WIFSIGNALED(status)) { 1197 LOG(INFO) << name << " killed by signal " << WTERMSIG(status) << wait_string; 1198 } 1199 1200 if (!svc) { 1201 return true; 1202 } 1203 1204 svc->Reap(); 1205 1206 if (svc->flags() & SVC_EXEC) { 1207 exec_waiter_.reset(); 1208 } 1209 if (svc->flags() & SVC_TEMPORARY) { 1210 RemoveService(*svc); 1211 } 1212 1213 return true; 1214 } 1215 1216 void ServiceManager::ReapAnyOutstandingChildren() { 1217 while (ReapOneProcess()) { 1218 } 1219 } 1220 1221 void ServiceManager::ClearExecWait() { 1222 // Clear EXEC flag if there is one pending 1223 // And clear the wait flag 1224 for (const auto& s : services_) { 1225 s->UnSetExec(); 1226 } 1227 exec_waiter_.reset(); 1228 } 1229 1230 bool ServiceParser::ParseSection(std::vector<std::string>&& args, const std::string& filename, 1231 int line, std::string* err) { 1232 if (args.size() < 3) { 1233 *err = "services must have a name and a program"; 1234 return false; 1235 } 1236 1237 const std::string& name = args[1]; 1238 if (!IsValidName(name)) { 1239 *err = StringPrintf("invalid service name '%s'", name.c_str()); 1240 return false; 1241 } 1242 1243 Service* old_service = service_manager_->FindServiceByName(name); 1244 if (old_service) { 1245 *err = "ignored duplicate definition of service '" + name + "'"; 1246 return false; 1247 } 1248 1249 std::vector<std::string> str_args(args.begin() + 2, args.end()); 1250 service_ = std::make_unique<Service>(name, str_args); 1251 return true; 1252 } 1253 1254 bool ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line, std::string* err) { 1255 return service_ ? service_->ParseLine(std::move(args), err) : false; 1256 } 1257 1258 void ServiceParser::EndSection() { 1259 if (service_) { 1260 service_manager_->AddService(std::move(service_)); 1261 } 1262 } 1263 1264 bool ServiceParser::IsValidName(const std::string& name) const { 1265 // Property names can be any length, but may only contain certain characters. 1266 // Property values can contain any characters, but may only be a certain length. 1267 // (The latter restriction is needed because `start` and `stop` work by writing 1268 // the service name to the "ctl.start" and "ctl.stop" properties.) 1269 return is_legal_property_name("init.svc." + name) && name.size() <= PROP_VALUE_MAX; 1270 } 1271 1272 } // namespace init 1273 } // namespace android 1274