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 "action.h"
18 
19 #include <android-base/chrono_utils.h>
20 #include <android-base/logging.h>
21 #include <android-base/properties.h>
22 #include <android-base/strings.h>
23 
24 #include "util.h"
25 
26 using android::base::Join;
27 
28 namespace android {
29 namespace init {
30 
RunBuiltinFunction(const BuiltinFunction & function,const std::vector<std::string> & args,const std::string & context)31 Result<void> RunBuiltinFunction(const BuiltinFunction& function,
32                                 const std::vector<std::string>& args, const std::string& context) {
33     auto builtin_arguments = BuiltinArguments(context);
34 
35     builtin_arguments.args.resize(args.size());
36     builtin_arguments.args[0] = args[0];
37     for (std::size_t i = 1; i < args.size(); ++i) {
38         auto expanded_arg = ExpandProps(args[i]);
39         if (!expanded_arg.ok()) {
40             return expanded_arg.error();
41         }
42         builtin_arguments.args[i] = std::move(*expanded_arg);
43     }
44 
45     return function(builtin_arguments);
46 }
47 
Command(BuiltinFunction f,bool execute_in_subcontext,std::vector<std::string> && args,int line)48 Command::Command(BuiltinFunction f, bool execute_in_subcontext, std::vector<std::string>&& args,
49                  int line)
50     : func_(std::move(f)),
51       execute_in_subcontext_(execute_in_subcontext),
52       args_(std::move(args)),
53       line_(line) {}
54 
InvokeFunc(Subcontext * subcontext) const55 Result<void> Command::InvokeFunc(Subcontext* subcontext) const {
56     if (subcontext) {
57         if (execute_in_subcontext_) {
58             return subcontext->Execute(args_);
59         }
60 
61         auto expanded_args = subcontext->ExpandArgs(args_);
62         if (!expanded_args.ok()) {
63             return expanded_args.error();
64         }
65         return RunBuiltinFunction(func_, *expanded_args, subcontext->context());
66     }
67 
68     return RunBuiltinFunction(func_, args_, kInitContext);
69 }
70 
CheckCommand() const71 Result<void> Command::CheckCommand() const {
72     auto builtin_arguments = BuiltinArguments("host_init_verifier");
73 
74     builtin_arguments.args.resize(args_.size());
75     builtin_arguments.args[0] = args_[0];
76     for (size_t i = 1; i < args_.size(); ++i) {
77         auto expanded_arg = ExpandProps(args_[i]);
78         if (!expanded_arg.ok()) {
79             if (expanded_arg.error().message().find("doesn't exist while expanding") !=
80                 std::string::npos) {
81                 // If we failed because we won't have a property, use an empty string, which is
82                 // never returned from the parser, to indicate that this field cannot be checked.
83                 builtin_arguments.args[i] = "";
84             } else {
85                 return expanded_arg.error();
86             }
87         } else {
88             builtin_arguments.args[i] = std::move(*expanded_arg);
89         }
90     }
91 
92     return func_(builtin_arguments);
93 }
94 
BuildCommandString() const95 std::string Command::BuildCommandString() const {
96     return Join(args_, ' ');
97 }
98 
Action(bool oneshot,Subcontext * subcontext,const std::string & filename,int line,const std::string & event_trigger,const std::map<std::string,std::string> & property_triggers)99 Action::Action(bool oneshot, Subcontext* subcontext, const std::string& filename, int line,
100                const std::string& event_trigger,
101                const std::map<std::string, std::string>& property_triggers)
102     : property_triggers_(property_triggers),
103       event_trigger_(event_trigger),
104       oneshot_(oneshot),
105       subcontext_(subcontext),
106       filename_(filename),
107       line_(line) {}
108 
109 const BuiltinFunctionMap* Action::function_map_ = nullptr;
110 
AddCommand(std::vector<std::string> && args,int line)111 Result<void> Action::AddCommand(std::vector<std::string>&& args, int line) {
112     if (!function_map_) {
113         return Error() << "no function map available";
114     }
115 
116     auto map_result = function_map_->Find(args);
117     if (!map_result.ok()) {
118         return Error() << map_result.error();
119     }
120 
121     commands_.emplace_back(map_result->function, map_result->run_in_subcontext, std::move(args),
122                            line);
123     return {};
124 }
125 
AddCommand(BuiltinFunction f,std::vector<std::string> && args,int line)126 void Action::AddCommand(BuiltinFunction f, std::vector<std::string>&& args, int line) {
127     commands_.emplace_back(std::move(f), false, std::move(args), line);
128 }
129 
NumCommands() const130 std::size_t Action::NumCommands() const {
131     return commands_.size();
132 }
133 
CheckAllCommands() const134 size_t Action::CheckAllCommands() const {
135     size_t failures = 0;
136     for (const auto& command : commands_) {
137         if (auto result = command.CheckCommand(); !result.ok()) {
138             LOG(ERROR) << "Command '" << command.BuildCommandString() << "' (" << filename_ << ":"
139                        << command.line() << ") failed: " << result.error();
140             ++failures;
141         }
142     }
143     return failures;
144 }
145 
ExecuteOneCommand(std::size_t command) const146 void Action::ExecuteOneCommand(std::size_t command) const {
147     // We need a copy here since some Command execution may result in
148     // changing commands_ vector by importing .rc files through parser
149     Command cmd = commands_[command];
150     ExecuteCommand(cmd);
151 }
152 
ExecuteAllCommands() const153 void Action::ExecuteAllCommands() const {
154     for (const auto& c : commands_) {
155         ExecuteCommand(c);
156     }
157 }
158 
ExecuteCommand(const Command & command) const159 void Action::ExecuteCommand(const Command& command) const {
160     android::base::Timer t;
161     auto result = command.InvokeFunc(subcontext_);
162     auto duration = t.duration();
163 
164     // Any action longer than 50ms will be warned to user as slow operation
165     if (!result.has_value() || duration > 50ms ||
166         android::base::GetMinimumLogSeverity() <= android::base::DEBUG) {
167         std::string trigger_name = BuildTriggersString();
168         std::string cmd_str = command.BuildCommandString();
169 
170         LOG(INFO) << "Command '" << cmd_str << "' action=" << trigger_name << " (" << filename_
171                   << ":" << command.line() << ") took " << duration.count() << "ms and "
172                   << (result.ok() ? "succeeded" : "failed: " + result.error().message());
173     }
174 }
175 
176 // This function checks that all property triggers are satisfied, that is
177 // for each (name, value) in property_triggers_, check that the current
178 // value of the property 'name' == value.
179 //
180 // It takes an optional (name, value) pair, which if provided must
181 // be present in property_triggers_; it skips the check of the current
182 // property value for this pair.
CheckPropertyTriggers(const std::string & name,const std::string & value) const183 bool Action::CheckPropertyTriggers(const std::string& name, const std::string& value) const {
184     if (property_triggers_.empty()) {
185         return true;
186     }
187 
188     if (!name.empty()) {
189         auto it = property_triggers_.find(name);
190         if (it == property_triggers_.end()) {
191             return false;
192         }
193         const auto& trigger_value = it->second;
194         if (trigger_value != "*" && trigger_value != value) {
195             return false;
196         }
197     }
198 
199     for (const auto& [trigger_name, trigger_value] : property_triggers_) {
200         if (trigger_name != name) {
201             std::string prop_value = android::base::GetProperty(trigger_name, "");
202             if (trigger_value == "*" && !prop_value.empty()) {
203                 continue;
204             }
205             if (trigger_value != prop_value) return false;
206         }
207     }
208     return true;
209 }
210 
CheckEvent(const EventTrigger & event_trigger) const211 bool Action::CheckEvent(const EventTrigger& event_trigger) const {
212     return event_trigger == event_trigger_ && CheckPropertyTriggers();
213 }
214 
CheckEvent(const PropertyChange & property_change) const215 bool Action::CheckEvent(const PropertyChange& property_change) const {
216     const auto& [name, value] = property_change;
217     return event_trigger_.empty() && CheckPropertyTriggers(name, value);
218 }
219 
CheckEvent(const BuiltinAction & builtin_action) const220 bool Action::CheckEvent(const BuiltinAction& builtin_action) const {
221     return this == builtin_action;
222 }
223 
BuildTriggersString() const224 std::string Action::BuildTriggersString() const {
225     std::vector<std::string> triggers;
226 
227     for (const auto& [trigger_name, trigger_value] : property_triggers_) {
228         triggers.emplace_back(trigger_name + '=' + trigger_value);
229     }
230     if (!event_trigger_.empty()) {
231         triggers.emplace_back(event_trigger_);
232     }
233 
234     return Join(triggers, " && ");
235 }
236 
DumpState() const237 void Action::DumpState() const {
238     std::string trigger_name = BuildTriggersString();
239     LOG(INFO) << "on " << trigger_name;
240 
241     for (const auto& c : commands_) {
242         std::string cmd_str = c.BuildCommandString();
243         LOG(INFO) << "  " << cmd_str;
244     }
245 }
246 
247 }  // namespace init
248 }  // namespace android
249