• Home
  • 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 #ifndef _INIT_SERVICE_H
18 #define _INIT_SERVICE_H
19 
20 #include <signal.h>
21 #include <sys/resource.h>
22 #include <sys/types.h>
23 
24 #include <chrono>
25 #include <memory>
26 #include <optional>
27 #include <set>
28 #include <string>
29 #include <vector>
30 
31 #include <android-base/chrono_utils.h>
32 #include <cutils/iosched_policy.h>
33 
34 #include "action.h"
35 #include "capabilities.h"
36 #include "descriptors.h"
37 #include "keyword_map.h"
38 #include "parser.h"
39 #include "subcontext.h"
40 
41 #define SVC_DISABLED 0x001        // do not autostart with class
42 #define SVC_ONESHOT 0x002         // do not restart on exit
43 #define SVC_RUNNING 0x004         // currently active
44 #define SVC_RESTARTING 0x008      // waiting to restart
45 #define SVC_CONSOLE 0x010         // requires console
46 #define SVC_CRITICAL 0x020        // will reboot into bootloader if keeps crashing
47 #define SVC_RESET 0x040           // Use when stopping a process,
48                                   // but not disabling so it can be restarted with its class.
49 #define SVC_RC_DISABLED 0x080     // Remember if the disabled flag was set in the rc script.
50 #define SVC_RESTART 0x100         // Use to safely restart (stop, wait, start) a service.
51 #define SVC_DISABLED_START 0x200  // A start was requested but it was disabled at the time.
52 #define SVC_EXEC 0x400  // This service was started by either 'exec' or 'exec_start' and stops
53                         // init from processing more commands until it completes
54 
55 #define SVC_SHUTDOWN_CRITICAL 0x800  // This service is critical for shutdown and
56                                      // should not be killed during shutdown
57 #define SVC_TEMPORARY 0x1000  // This service was started by 'exec' and should be removed from the
58                               // service list once it is reaped.
59 
60 #define NR_SVC_SUPP_GIDS 12    // twelve supplementary groups
61 
62 namespace android {
63 namespace init {
64 
65 class Service {
66   public:
67     Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
68             const std::vector<std::string>& args);
69 
70     Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid,
71             const std::vector<gid_t>& supp_gids, unsigned namespace_flags,
72             const std::string& seclabel, Subcontext* subcontext_for_restart_commands,
73             const std::vector<std::string>& args);
74 
75     static std::unique_ptr<Service> MakeTemporaryOneshotService(const std::vector<std::string>& args);
76 
IsRunning()77     bool IsRunning() { return (flags_ & SVC_RUNNING) != 0; }
78     Result<Success> ParseLine(std::vector<std::string>&& args);
79     Result<Success> ExecStart();
80     Result<Success> Start();
81     Result<Success> StartIfNotDisabled();
82     Result<Success> StartIfPostData();
83     Result<Success> Enable();
84     void Reset();
85     void ResetIfPostData();
86     void Stop();
87     void Terminate();
88     void Timeout();
89     void Restart();
90     void Reap(const siginfo_t& siginfo);
91     void DumpState() const;
SetShutdownCritical()92     void SetShutdownCritical() { flags_ |= SVC_SHUTDOWN_CRITICAL; }
IsShutdownCritical()93     bool IsShutdownCritical() const { return (flags_ & SVC_SHUTDOWN_CRITICAL) != 0; }
UnSetExec()94     void UnSetExec() {
95         is_exec_service_running_ = false;
96         flags_ &= ~SVC_EXEC;
97     }
AddReapCallback(std::function<void (const siginfo_t & siginfo)> callback)98     void AddReapCallback(std::function<void(const siginfo_t& siginfo)> callback) {
99         reap_callbacks_.emplace_back(std::move(callback));
100     }
101 
is_exec_service_running()102     static bool is_exec_service_running() { return is_exec_service_running_; }
103 
name()104     const std::string& name() const { return name_; }
classnames()105     const std::set<std::string>& classnames() const { return classnames_; }
flags()106     unsigned flags() const { return flags_; }
pid()107     pid_t pid() const { return pid_; }
time_started()108     android::base::boot_clock::time_point time_started() const { return time_started_; }
crash_count()109     int crash_count() const { return crash_count_; }
uid()110     uid_t uid() const { return uid_; }
gid()111     gid_t gid() const { return gid_; }
namespace_flags()112     unsigned namespace_flags() const { return namespace_flags_; }
supp_gids()113     const std::vector<gid_t>& supp_gids() const { return supp_gids_; }
seclabel()114     const std::string& seclabel() const { return seclabel_; }
keycodes()115     const std::vector<int>& keycodes() const { return keycodes_; }
ioprio_class()116     IoSchedClass ioprio_class() const { return ioprio_class_; }
ioprio_pri()117     int ioprio_pri() const { return ioprio_pri_; }
interfaces()118     const std::set<std::string>& interfaces() const { return interfaces_; }
priority()119     int priority() const { return priority_; }
oom_score_adjust()120     int oom_score_adjust() const { return oom_score_adjust_; }
is_override()121     bool is_override() const { return override_; }
process_cgroup_empty()122     bool process_cgroup_empty() const { return process_cgroup_empty_; }
start_order()123     unsigned long start_order() const { return start_order_; }
set_sigstop(bool value)124     void set_sigstop(bool value) { sigstop_ = value; }
restart_period()125     std::chrono::seconds restart_period() const { return restart_period_; }
timeout_period()126     std::optional<std::chrono::seconds> timeout_period() const { return timeout_period_; }
args()127     const std::vector<std::string>& args() const { return args_; }
is_updatable()128     bool is_updatable() const { return updatable_; }
is_post_data()129     bool is_post_data() const { return post_data_; }
130 
131   private:
132     using OptionParser = Result<Success> (Service::*)(std::vector<std::string>&& args);
133     class OptionParserMap;
134 
135     Result<Success> SetUpMountNamespace() const;
136     Result<Success> SetUpPidNamespace() const;
137     Result<Success> EnterNamespaces() const;
138     void NotifyStateChange(const std::string& new_state) const;
139     void StopOrReset(int how);
140     void ZapStdio() const;
141     void OpenConsole() const;
142     void KillProcessGroup(int signal);
143     void SetProcessAttributes();
144 
145     Result<Success> ParseCapabilities(std::vector<std::string>&& args);
146     Result<Success> ParseClass(std::vector<std::string>&& args);
147     Result<Success> ParseConsole(std::vector<std::string>&& args);
148     Result<Success> ParseCritical(std::vector<std::string>&& args);
149     Result<Success> ParseDisabled(std::vector<std::string>&& args);
150     Result<Success> ParseEnterNamespace(std::vector<std::string>&& args);
151     Result<Success> ParseGroup(std::vector<std::string>&& args);
152     Result<Success> ParsePriority(std::vector<std::string>&& args);
153     Result<Success> ParseInterface(std::vector<std::string>&& args);
154     Result<Success> ParseIoprio(std::vector<std::string>&& args);
155     Result<Success> ParseKeycodes(std::vector<std::string>&& args);
156     Result<Success> ParseOneshot(std::vector<std::string>&& args);
157     Result<Success> ParseOnrestart(std::vector<std::string>&& args);
158     Result<Success> ParseOomScoreAdjust(std::vector<std::string>&& args);
159     Result<Success> ParseOverride(std::vector<std::string>&& args);
160     Result<Success> ParseMemcgLimitInBytes(std::vector<std::string>&& args);
161     Result<Success> ParseMemcgLimitPercent(std::vector<std::string>&& args);
162     Result<Success> ParseMemcgLimitProperty(std::vector<std::string>&& args);
163     Result<Success> ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args);
164     Result<Success> ParseMemcgSwappiness(std::vector<std::string>&& args);
165     Result<Success> ParseNamespace(std::vector<std::string>&& args);
166     Result<Success> ParseProcessRlimit(std::vector<std::string>&& args);
167     Result<Success> ParseRestartPeriod(std::vector<std::string>&& args);
168     Result<Success> ParseSeclabel(std::vector<std::string>&& args);
169     Result<Success> ParseSetenv(std::vector<std::string>&& args);
170     Result<Success> ParseShutdown(std::vector<std::string>&& args);
171     Result<Success> ParseSigstop(std::vector<std::string>&& args);
172     Result<Success> ParseSocket(std::vector<std::string>&& args);
173     Result<Success> ParseTimeoutPeriod(std::vector<std::string>&& args);
174     Result<Success> ParseFile(std::vector<std::string>&& args);
175     Result<Success> ParseUser(std::vector<std::string>&& args);
176     Result<Success> ParseWritepid(std::vector<std::string>&& args);
177     Result<Success> ParseUpdatable(std::vector<std::string>&& args);
178 
179     template <typename T>
180     Result<Success> AddDescriptor(std::vector<std::string>&& args);
181 
182     static unsigned long next_start_order_;
183     static bool is_exec_service_running_;
184 
185     std::string name_;
186     std::set<std::string> classnames_;
187     std::string console_;
188 
189     unsigned flags_;
190     pid_t pid_;
191     android::base::boot_clock::time_point time_started_;  // time of last start
192     android::base::boot_clock::time_point time_crashed_;  // first crash within inspection window
193     int crash_count_;                     // number of times crashed within window
194 
195     uid_t uid_;
196     gid_t gid_;
197     std::vector<gid_t> supp_gids_;
198     std::optional<CapSet> capabilities_;
199     unsigned namespace_flags_;
200     // Pair of namespace type, path to namespace.
201     std::vector<std::pair<int, std::string>> namespaces_to_enter_;
202 
203     std::string seclabel_;
204 
205     std::vector<std::unique_ptr<DescriptorInfo>> descriptors_;
206     std::vector<std::pair<std::string, std::string>> environment_vars_;
207 
208     Action onrestart_;  // Commands to execute on restart.
209 
210     std::vector<std::string> writepid_files_;
211 
212     std::set<std::string> interfaces_;  // e.g. some.package.foo@1.0::IBaz/instance-name
213 
214     // keycodes for triggering this service via /dev/input/input*
215     std::vector<int> keycodes_;
216 
217     IoSchedClass ioprio_class_;
218     int ioprio_pri_;
219     int priority_;
220 
221     int oom_score_adjust_;
222 
223     int swappiness_ = -1;
224     int soft_limit_in_bytes_ = -1;
225 
226     int limit_in_bytes_ = -1;
227     int limit_percent_ = -1;
228     std::string limit_property_;
229 
230     bool process_cgroup_empty_ = false;
231 
232     bool override_ = false;
233 
234     unsigned long start_order_;
235 
236     std::vector<std::pair<int, rlimit>> rlimits_;
237 
238     bool sigstop_ = false;
239 
240     std::chrono::seconds restart_period_ = 5s;
241     std::optional<std::chrono::seconds> timeout_period_;
242 
243     bool updatable_ = false;
244 
245     std::vector<std::string> args_;
246 
247     std::vector<std::function<void(const siginfo_t& siginfo)>> reap_callbacks_;
248 
249     bool pre_apexd_ = false;
250 
251     bool post_data_ = false;
252 
253     bool running_at_post_data_reset_ = false;
254 };
255 
256 class ServiceList {
257   public:
258     static ServiceList& GetInstance();
259 
260     // Exposed for testing
261     ServiceList();
262 
263     void AddService(std::unique_ptr<Service> service);
264     void RemoveService(const Service& svc);
265 
266     template <typename T, typename F = decltype(&Service::name)>
267     Service* FindService(T value, F function = &Service::name) const {
268         auto svc = std::find_if(services_.begin(), services_.end(),
269                                 [&function, &value](const std::unique_ptr<Service>& s) {
270                                     return std::invoke(function, s) == value;
271                                 });
272         if (svc != services_.end()) {
273             return svc->get();
274         }
275         return nullptr;
276     }
277 
FindInterface(const std::string & interface_name)278     Service* FindInterface(const std::string& interface_name) {
279         for (const auto& svc : services_) {
280             if (svc->interfaces().count(interface_name) > 0) {
281                 return svc.get();
282             }
283         }
284 
285         return nullptr;
286     }
287 
288     void DumpState() const;
289 
begin()290     auto begin() const { return services_.begin(); }
end()291     auto end() const { return services_.end(); }
services()292     const std::vector<std::unique_ptr<Service>>& services() const { return services_; }
293     const std::vector<Service*> services_in_shutdown_order() const;
294 
295     void MarkPostData();
296     bool IsPostData();
297     void MarkServicesUpdate();
IsServicesUpdated()298     bool IsServicesUpdated() const { return services_update_finished_; }
299     void DelayService(const Service& service);
300 
301   private:
302     std::vector<std::unique_ptr<Service>> services_;
303 
304     bool post_data_ = false;
305     bool services_update_finished_ = false;
306     std::vector<std::string> delayed_service_names_;
307 };
308 
309 class ServiceParser : public SectionParser {
310   public:
ServiceParser(ServiceList * service_list,std::vector<Subcontext> * subcontexts)311     ServiceParser(ServiceList* service_list, std::vector<Subcontext>* subcontexts)
312         : service_list_(service_list), subcontexts_(subcontexts), service_(nullptr) {}
313     Result<Success> ParseSection(std::vector<std::string>&& args, const std::string& filename,
314                                  int line) override;
315     Result<Success> ParseLineSection(std::vector<std::string>&& args, int line) override;
316     Result<Success> EndSection() override;
EndFile()317     void EndFile() override { filename_ = ""; }
318 
319   private:
320     bool IsValidName(const std::string& name) const;
321 
322     ServiceList* service_list_;
323     std::vector<Subcontext>* subcontexts_;
324     std::unique_ptr<Service> service_;
325     std::string filename_;
326 };
327 
328 }  // namespace init
329 }  // namespace android
330 
331 #endif
332