• Home
  • History
  • Annotate
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  #pragma once
18  
19  #include <signal.h>
20  #include <sys/types.h>
21  
22  #include <algorithm>
23  #include <chrono>
24  #include <memory>
25  #include <optional>
26  #include <set>
27  #include <string>
28  #include <vector>
29  
30  #include <android-base/chrono_utils.h>
31  #include <cutils/iosched_policy.h>
32  
33  #include "action.h"
34  #include "capabilities.h"
35  #include "interprocess_fifo.h"
36  #include "keyword_map.h"
37  #include "mount_namespace.h"
38  #include "parser.h"
39  #include "service_utils.h"
40  #include "subcontext.h"
41  
42  #define SVC_DISABLED 0x001        // do not autostart with class
43  #define SVC_ONESHOT 0x002         // do not restart on exit
44  #define SVC_RUNNING 0x004         // currently active
45  #define SVC_RESTARTING 0x008      // waiting to restart
46  #define SVC_CONSOLE 0x010         // requires console
47  #define SVC_CRITICAL 0x020        // will reboot into bootloader if keeps crashing
48  #define SVC_RESET 0x040           // Use when stopping a process,
49                                    // but not disabling so it can be restarted with its class.
50  #define SVC_RC_DISABLED 0x080     // Remember if the disabled flag was set in the rc script.
51  #define SVC_RESTART 0x100         // Use to safely restart (stop, wait, start) a service.
52  #define SVC_DISABLED_START 0x200  // A start was requested but it was disabled at the time.
53  #define SVC_EXEC 0x400  // This service was started by either 'exec' or 'exec_start' and stops
54                          // init from processing more commands until it completes
55  
56  #define SVC_SHUTDOWN_CRITICAL 0x800  // This service is critical for shutdown and
57                                       // should not be killed during shutdown
58  #define SVC_TEMPORARY 0x1000  // This service was started by 'exec' and should be removed from the
59                                // service list once it is reaped.
60  #define SVC_GENTLE_KILL 0x2000  // This service should be stopped with SIGTERM instead of SIGKILL
61                                  // Will still be SIGKILLed after timeout period of 200 ms
62  
63  #define NR_SVC_SUPP_GIDS 32    // thirty two supplementary groups
64  
65  namespace android {
66  namespace init {
67  
68  class Service {
69      friend class ServiceParser;
70  
71    public:
72      Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
73              const std::string& filename, const std::vector<std::string>& args);
74  
75      Service(const std::string& name, unsigned flags, std::optional<uid_t> uid, gid_t gid,
76              const std::vector<gid_t>& supp_gids, int namespace_flags, const std::string& seclabel,
77              Subcontext* subcontext_for_restart_commands, const std::string& filename,
78              const std::vector<std::string>& args);
79      Service(const Service&) = delete;
80      void operator=(const Service&) = delete;
81  
82      static Result<std::unique_ptr<Service>> MakeTemporaryOneshotService(
83              const std::vector<std::string>& args);
84  
IsRunning()85      bool IsRunning() { return (flags_ & SVC_RUNNING) != 0; }
IsEnabled()86      bool IsEnabled() { return (flags_ & SVC_DISABLED) == 0; }
87      Result<void> ExecStart();
88      Result<void> Start();
89      Result<void> StartIfNotDisabled();
90      Result<void> Enable();
91      void Reset();
92      void Stop();
93      void Terminate();
94      void Timeout();
95      void Restart();
96      void Reap(const siginfo_t& siginfo);
97      void DumpState() const;
SetShutdownCritical()98      void SetShutdownCritical() { flags_ |= SVC_SHUTDOWN_CRITICAL; }
IsShutdownCritical()99      bool IsShutdownCritical() const { return (flags_ & SVC_SHUTDOWN_CRITICAL) != 0; }
UnSetExec()100      void UnSetExec() {
101          is_exec_service_running_ = false;
102          flags_ &= ~SVC_EXEC;
103      }
AddReapCallback(std::function<void (const siginfo_t & siginfo)> callback)104      void AddReapCallback(std::function<void(const siginfo_t& siginfo)> callback) {
105          reap_callbacks_.emplace_back(std::move(callback));
106      }
107      void SetStartedInFirstStage(pid_t pid);
108      bool MarkSocketPersistent(const std::string& socket_name);
CheckAllCommands()109      size_t CheckAllCommands() const { return onrestart_.CheckAllCommands(); }
110  
is_exec_service_running()111      static bool is_exec_service_running() { return is_exec_service_running_; }
112  
name()113      const std::string& name() const { return name_; }
classnames()114      const std::set<std::string>& classnames() const { return classnames_; }
flags()115      unsigned flags() const { return flags_; }
pid()116      pid_t pid() const { return pid_; }
time_started()117      android::base::boot_clock::time_point time_started() const { return time_started_; }
crash_count()118      int crash_count() const { return crash_count_; }
was_last_exit_ok()119      int was_last_exit_ok() const { return was_last_exit_ok_; }
uid()120      uid_t uid() const { return proc_attr_.uid(); }
gid()121      gid_t gid() const { return proc_attr_.gid; }
namespace_flags()122      int namespace_flags() const { return namespaces_.flags; }
supp_gids()123      const std::vector<gid_t>& supp_gids() const { return proc_attr_.supp_gids; }
seclabel()124      const std::string& seclabel() const { return seclabel_; }
keycodes()125      const std::vector<int>& keycodes() const { return keycodes_; }
ioprio_class()126      IoSchedClass ioprio_class() const { return proc_attr_.ioprio_class; }
ioprio_pri()127      int ioprio_pri() const { return proc_attr_.ioprio_pri; }
interfaces()128      const std::set<std::string>& interfaces() const { return interfaces_; }
priority()129      int priority() const { return proc_attr_.priority; }
oom_score_adjust()130      int oom_score_adjust() const { return oom_score_adjust_; }
is_override()131      bool is_override() const { return override_; }
process_cgroup_empty()132      bool process_cgroup_empty() const { return process_cgroup_empty_; }
start_order()133      unsigned long start_order() const { return start_order_; }
set_sigstop(bool value)134      void set_sigstop(bool value) { sigstop_ = value; }
restart_period()135      std::chrono::seconds restart_period() const {
136          // If the service exited abnormally or due to timeout, late limit the restart even if
137          // restart_period is set to a very short value.
138          // If not, i.e. restart after a deliberate and successful exit, respect the period.
139          if (!was_last_exit_ok_) {
140              return std::max(restart_period_, default_restart_period_);
141          }
142          return restart_period_;
143      }
timeout_period()144      std::optional<std::chrono::seconds> timeout_period() const { return timeout_period_; }
args()145      const std::vector<std::string>& args() const { return args_; }
is_updatable()146      bool is_updatable() const { return updatable_; }
is_post_data()147      bool is_post_data() const { return post_data_; }
is_from_apex()148      bool is_from_apex() const { return base::StartsWith(filename_, "/apex/"); }
set_oneshot(bool value)149      void set_oneshot(bool value) {
150          if (value) {
151              flags_ |= SVC_ONESHOT;
152          } else {
153              flags_ &= ~SVC_ONESHOT;
154          }
155      }
subcontext()156      const Subcontext* subcontext() const { return subcontext_; }
filename()157      const std::string& filename() const { return filename_; }
set_filename(const std::string & name)158      void set_filename(const std::string& name) { filename_ = name; }
GetSigchldFd()159      static int GetSigchldFd() {
160          static int sigchld_fd = CreateSigchldFd().release();
161          return sigchld_fd;
162      }
163  
164    private:
165      void NotifyStateChange(const std::string& new_state) const;
166      void StopOrReset(int how);
167      void KillProcessGroup(int signal);
168      void SetProcessAttributesAndCaps(InterprocessFifo setsid_finished);
169      void ResetFlagsForStart();
170      Result<void> CheckConsole();
171      void ConfigureMemcg();
172      void RunService(const std::vector<Descriptor>& descriptors, InterprocessFifo cgroups_activated,
173                      InterprocessFifo setsid_finished);
174      void SetMountNamespace();
175      static ::android::base::unique_fd CreateSigchldFd();
176  
177      static unsigned long next_start_order_;
178      static bool is_exec_service_running_;
179  
180      const std::string name_;
181      std::set<std::string> classnames_;
182  
183      unsigned flags_;
184      pid_t pid_;
185      android::base::boot_clock::time_point time_started_;  // time of last start
186      android::base::boot_clock::time_point time_crashed_;  // first crash within inspection window
187      int crash_count_;                     // number of times crashed within window
188      bool upgraded_mte_ = false;           // whether we upgraded async MTE -> sync MTE before
189      std::chrono::minutes fatal_crash_window_ = 4min;  // fatal() when more than 4 crashes in it
190      std::optional<std::string> fatal_reboot_target_;  // reboot target of fatal handler
191      bool was_last_exit_ok_ =
192              true;  // true if the service never exited, or exited with status code 0
193  
194      std::optional<CapSet> capabilities_;
195      ProcessAttributes proc_attr_;
196      NamespaceInfo namespaces_;
197  
198      std::string seclabel_;
199  
200      std::vector<SocketDescriptor> sockets_;
201      std::vector<FileDescriptor> files_;
202      std::vector<std::pair<std::string, std::string>> environment_vars_;
203      // Environment variables that only get applied to the next run.
204      std::vector<std::pair<std::string, std::string>> once_environment_vars_;
205  
206      const Subcontext* const subcontext_;
207      Action onrestart_;  // Commands to execute on restart.
208  
209      std::vector<std::string> writepid_files_;
210  
211      std::vector<std::string> task_profiles_;
212  
213      std::set<std::string> interfaces_;  // e.g. some.package.foo@1.0::IBaz/instance-name
214  
215      // keycodes for triggering this service via /dev/input/input*
216      std::vector<int> keycodes_;
217  
218      int oom_score_adjust_;
219  
220      int swappiness_ = -1;
221      int soft_limit_in_bytes_ = -1;
222  
223      int limit_in_bytes_ = -1;
224      int limit_percent_ = -1;
225      std::string limit_property_;
226  
227      bool process_cgroup_empty_ = false;
228  
229      bool override_ = false;
230  
231      unsigned long start_order_;
232  
233      bool sigstop_ = false;
234  
235      const std::chrono::seconds default_restart_period_ = 5s;
236      std::chrono::seconds restart_period_ = default_restart_period_;
237      std::optional<std::chrono::seconds> timeout_period_;
238  
239      bool updatable_ = false;
240  
241      const std::vector<std::string> args_;
242  
243      std::vector<std::function<void(const siginfo_t& siginfo)>> reap_callbacks_;
244  
245      std::optional<MountNamespace> mount_namespace_;
246  
247      bool post_data_ = false;
248  
249      std::optional<std::string> on_failure_reboot_target_;
250  
251      std::string filename_;
252  };
253  
254  }  // namespace init
255  }  // namespace android
256