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 <errno.h>
20 
21 #include <android-base/properties.h>
22 #include <android-base/stringprintf.h>
23 #include <android-base/strings.h>
24 
25 #include "builtins.h"
26 #include "error.h"
27 #include "init_parser.h"
28 #include "log.h"
29 #include "util.h"
30 
31 using android::base::Join;
32 using android::base::StringPrintf;
33 
Command(BuiltinFunction f,const std::vector<std::string> & args,const std::string & filename,int line)34 Command::Command(BuiltinFunction f, const std::vector<std::string>& args,
35                  const std::string& filename, int line)
36     : func_(f), args_(args), filename_(filename), line_(line) {
37 }
38 
InvokeFunc() const39 int Command::InvokeFunc() const {
40     std::vector<std::string> expanded_args;
41     expanded_args.resize(args_.size());
42     expanded_args[0] = args_[0];
43     for (std::size_t i = 1; i < args_.size(); ++i) {
44         if (!expand_props(args_[i], &expanded_args[i])) {
45             LOG(ERROR) << args_[0] << ": cannot expand '" << args_[i] << "'";
46             return -EINVAL;
47         }
48     }
49 
50     return func_(expanded_args);
51 }
52 
BuildCommandString() const53 std::string Command::BuildCommandString() const {
54     return Join(args_, ' ');
55 }
56 
BuildSourceString() const57 std::string Command::BuildSourceString() const {
58     if (!filename_.empty()) {
59         return StringPrintf(" (%s:%d)", filename_.c_str(), line_);
60     } else {
61         return std::string();
62     }
63 }
64 
Action(bool oneshot)65 Action::Action(bool oneshot) : oneshot_(oneshot) {
66 }
67 
68 const KeywordMap<BuiltinFunction>* Action::function_map_ = nullptr;
69 
AddCommand(const std::vector<std::string> & args,const std::string & filename,int line,std::string * err)70 bool Action::AddCommand(const std::vector<std::string>& args,
71                         const std::string& filename, int line, std::string* err) {
72     if (!function_map_) {
73         *err = "no function map available";
74         return false;
75     }
76 
77     if (args.empty()) {
78         *err = "command needed, but not provided";
79         return false;
80     }
81 
82     auto function = function_map_->FindFunction(args[0], args.size() - 1, err);
83     if (!function) {
84         return false;
85     }
86 
87     AddCommand(function, args, filename, line);
88     return true;
89 }
90 
AddCommand(BuiltinFunction f,const std::vector<std::string> & args,const std::string & filename,int line)91 void Action::AddCommand(BuiltinFunction f,
92                         const std::vector<std::string>& args,
93                         const std::string& filename, int line) {
94     commands_.emplace_back(f, args, filename, line);
95 }
96 
CombineAction(const Action & action)97 void Action::CombineAction(const Action& action) {
98     for (const auto& c : action.commands_) {
99         commands_.emplace_back(c);
100     }
101 }
102 
NumCommands() const103 std::size_t Action::NumCommands() const {
104     return commands_.size();
105 }
106 
ExecuteOneCommand(std::size_t command) const107 void Action::ExecuteOneCommand(std::size_t command) const {
108     // We need a copy here since some Command execution may result in
109     // changing commands_ vector by importing .rc files through parser
110     Command cmd = commands_[command];
111     ExecuteCommand(cmd);
112 }
113 
ExecuteAllCommands() const114 void Action::ExecuteAllCommands() const {
115     for (const auto& c : commands_) {
116         ExecuteCommand(c);
117     }
118 }
119 
ExecuteCommand(const Command & command) const120 void Action::ExecuteCommand(const Command& command) const {
121     Timer t;
122     int result = command.InvokeFunc();
123 
124     double duration_ms = t.duration_s() * 1000;
125     // Any action longer than 50ms will be warned to user as slow operation
126     if (duration_ms > 50.0 ||
127         android::base::GetMinimumLogSeverity() <= android::base::DEBUG) {
128         std::string trigger_name = BuildTriggersString();
129         std::string cmd_str = command.BuildCommandString();
130         std::string source = command.BuildSourceString();
131 
132         LOG(INFO) << "Command '" << cmd_str << "' action=" << trigger_name << source
133                   << " returned " << result << " took " << duration_ms << "ms.";
134     }
135 }
136 
ParsePropertyTrigger(const std::string & trigger,std::string * err)137 bool Action::ParsePropertyTrigger(const std::string& trigger, std::string* err) {
138     const static std::string prop_str("property:");
139     std::string prop_name(trigger.substr(prop_str.length()));
140     size_t equal_pos = prop_name.find('=');
141     if (equal_pos == std::string::npos) {
142         *err = "property trigger found without matching '='";
143         return false;
144     }
145 
146     std::string prop_value(prop_name.substr(equal_pos + 1));
147     prop_name.erase(equal_pos);
148 
149     if (auto [it, inserted] = property_triggers_.emplace(prop_name, prop_value); !inserted) {
150         *err = "multiple property triggers found for same property";
151         return false;
152     }
153     return true;
154 }
155 
InitTriggers(const std::vector<std::string> & args,std::string * err)156 bool Action::InitTriggers(const std::vector<std::string>& args, std::string* err) {
157     const static std::string prop_str("property:");
158     for (std::size_t i = 0; i < args.size(); ++i) {
159         if (args[i].empty()) {
160             *err = "empty trigger is not valid";
161             return false;
162         }
163 
164         if (i % 2) {
165             if (args[i] != "&&") {
166                 *err = "&& is the only symbol allowed to concatenate actions";
167                 return false;
168             } else {
169                 continue;
170             }
171         }
172 
173         if (!args[i].compare(0, prop_str.length(), prop_str)) {
174             if (!ParsePropertyTrigger(args[i], err)) {
175                 return false;
176             }
177         } else {
178             if (!event_trigger_.empty()) {
179                 *err = "multiple event triggers are not allowed";
180                 return false;
181             }
182 
183             event_trigger_ = args[i];
184         }
185     }
186 
187     return true;
188 }
189 
InitSingleTrigger(const std::string & trigger)190 bool Action::InitSingleTrigger(const std::string& trigger) {
191     std::vector<std::string> name_vector{trigger};
192     std::string err;
193     bool ret = InitTriggers(name_vector, &err);
194     if (!ret) {
195         LOG(ERROR) << "InitSingleTrigger failed due to: " << err;
196     }
197     return ret;
198 }
199 
200 // This function checks that all property triggers are satisfied, that is
201 // for each (name, value) in property_triggers_, check that the current
202 // value of the property 'name' == value.
203 //
204 // It takes an optional (name, value) pair, which if provided must
205 // be present in property_triggers_; it skips the check of the current
206 // property value for this pair.
CheckPropertyTriggers(const std::string & name,const std::string & value) const207 bool Action::CheckPropertyTriggers(const std::string& name,
208                                    const std::string& value) const {
209     if (property_triggers_.empty()) {
210         return true;
211     }
212 
213     bool found = name.empty();
214     for (const auto& [trigger_name, trigger_value] : property_triggers_) {
215         if (trigger_name == name) {
216             if (trigger_value != "*" && trigger_value != value) {
217                 return false;
218             } else {
219                 found = true;
220             }
221         } else {
222             std::string prop_val = android::base::GetProperty(trigger_name, "");
223             if (prop_val.empty() || (trigger_value != "*" && trigger_value != prop_val)) {
224                 return false;
225             }
226         }
227     }
228     return found;
229 }
230 
CheckEventTrigger(const std::string & trigger) const231 bool Action::CheckEventTrigger(const std::string& trigger) const {
232     return !event_trigger_.empty() &&
233         trigger == event_trigger_ &&
234         CheckPropertyTriggers();
235 }
236 
CheckPropertyTrigger(const std::string & name,const std::string & value) const237 bool Action::CheckPropertyTrigger(const std::string& name,
238                                   const std::string& value) const {
239     return event_trigger_.empty() && CheckPropertyTriggers(name, value);
240 }
241 
TriggersEqual(const Action & other) const242 bool Action::TriggersEqual(const Action& other) const {
243     return property_triggers_ == other.property_triggers_ &&
244         event_trigger_ == other.event_trigger_;
245 }
246 
BuildTriggersString() const247 std::string Action::BuildTriggersString() const {
248     std::vector<std::string> triggers;
249 
250     for (const auto& [trigger_name, trigger_value] : property_triggers_) {
251         triggers.emplace_back(trigger_name + '=' + trigger_value);
252     }
253     if (!event_trigger_.empty()) {
254         triggers.emplace_back(event_trigger_);
255     }
256 
257     return Join(triggers, " && ");
258 }
259 
DumpState() const260 void Action::DumpState() const {
261     std::string trigger_name = BuildTriggersString();
262     LOG(INFO) << "on " << trigger_name;
263 
264     for (const auto& c : commands_) {
265         std::string cmd_str = c.BuildCommandString();
266         LOG(INFO) << "  " << cmd_str;
267     }
268 }
269 
270 class EventTrigger : public Trigger {
271 public:
EventTrigger(const std::string & trigger)272     explicit EventTrigger(const std::string& trigger) : trigger_(trigger) {
273     }
CheckTriggers(const Action & action) const274     bool CheckTriggers(const Action& action) const override {
275         return action.CheckEventTrigger(trigger_);
276     }
277 private:
278     const std::string trigger_;
279 };
280 
281 class PropertyTrigger : public Trigger {
282 public:
PropertyTrigger(const std::string & name,const std::string & value)283     PropertyTrigger(const std::string& name, const std::string& value)
284         : name_(name), value_(value) {
285     }
CheckTriggers(const Action & action) const286     bool CheckTriggers(const Action& action) const override {
287         return action.CheckPropertyTrigger(name_, value_);
288     }
289 private:
290     const std::string name_;
291     const std::string value_;
292 };
293 
294 class BuiltinTrigger : public Trigger {
295 public:
BuiltinTrigger(Action * action)296     explicit BuiltinTrigger(Action* action) : action_(action) {
297     }
CheckTriggers(const Action & action) const298     bool CheckTriggers(const Action& action) const override {
299         return action_ == &action;
300     }
301 private:
302     const Action* action_;
303 };
304 
ActionManager()305 ActionManager::ActionManager() : current_command_(0) {
306 }
307 
GetInstance()308 ActionManager& ActionManager::GetInstance() {
309     static ActionManager instance;
310     return instance;
311 }
312 
AddAction(std::unique_ptr<Action> action)313 void ActionManager::AddAction(std::unique_ptr<Action> action) {
314     auto old_action_it =
315         std::find_if(actions_.begin(), actions_.end(),
316                      [&action] (std::unique_ptr<Action>& a) {
317                          return action->TriggersEqual(*a);
318                      });
319 
320     if (old_action_it != actions_.end()) {
321         (*old_action_it)->CombineAction(*action);
322     } else {
323         actions_.emplace_back(std::move(action));
324     }
325 }
326 
QueueEventTrigger(const std::string & trigger)327 void ActionManager::QueueEventTrigger(const std::string& trigger) {
328     trigger_queue_.push(std::make_unique<EventTrigger>(trigger));
329 }
330 
QueuePropertyTrigger(const std::string & name,const std::string & value)331 void ActionManager::QueuePropertyTrigger(const std::string& name,
332                                          const std::string& value) {
333     trigger_queue_.push(std::make_unique<PropertyTrigger>(name, value));
334 }
335 
QueueAllPropertyTriggers()336 void ActionManager::QueueAllPropertyTriggers() {
337     QueuePropertyTrigger("", "");
338 }
339 
QueueBuiltinAction(BuiltinFunction func,const std::string & name)340 void ActionManager::QueueBuiltinAction(BuiltinFunction func,
341                                        const std::string& name) {
342     auto action = std::make_unique<Action>(true);
343     std::vector<std::string> name_vector{name};
344 
345     if (!action->InitSingleTrigger(name)) {
346         return;
347     }
348 
349     action->AddCommand(func, name_vector);
350 
351     trigger_queue_.push(std::make_unique<BuiltinTrigger>(action.get()));
352     actions_.emplace_back(std::move(action));
353 }
354 
ExecuteOneCommand()355 void ActionManager::ExecuteOneCommand() {
356     // Loop through the trigger queue until we have an action to execute
357     while (current_executing_actions_.empty() && !trigger_queue_.empty()) {
358         for (const auto& action : actions_) {
359             if (trigger_queue_.front()->CheckTriggers(*action)) {
360                 current_executing_actions_.emplace(action.get());
361             }
362         }
363         trigger_queue_.pop();
364     }
365 
366     if (current_executing_actions_.empty()) {
367         return;
368     }
369 
370     auto action = current_executing_actions_.front();
371 
372     if (current_command_ == 0) {
373         std::string trigger_name = action->BuildTriggersString();
374         LOG(INFO) << "processing action (" << trigger_name << ")";
375     }
376 
377     action->ExecuteOneCommand(current_command_);
378 
379     // If this was the last command in the current action, then remove
380     // the action from the executing list.
381     // If this action was oneshot, then also remove it from actions_.
382     ++current_command_;
383     if (current_command_ == action->NumCommands()) {
384         current_executing_actions_.pop();
385         current_command_ = 0;
386         if (action->oneshot()) {
387             auto eraser = [&action] (std::unique_ptr<Action>& a) {
388                 return a.get() == action;
389             };
390             actions_.erase(std::remove_if(actions_.begin(), actions_.end(), eraser));
391         }
392     }
393 }
394 
HasMoreCommands() const395 bool ActionManager::HasMoreCommands() const {
396     return !current_executing_actions_.empty() || !trigger_queue_.empty();
397 }
398 
DumpState() const399 void ActionManager::DumpState() const {
400     for (const auto& a : actions_) {
401         a->DumpState();
402     }
403 }
404 
ParseSection(const std::vector<std::string> & args,std::string * err)405 bool ActionParser::ParseSection(const std::vector<std::string>& args,
406                                 std::string* err) {
407     std::vector<std::string> triggers(args.begin() + 1, args.end());
408     if (triggers.size() < 1) {
409         *err = "actions must have a trigger";
410         return false;
411     }
412 
413     auto action = std::make_unique<Action>(false);
414     if (!action->InitTriggers(triggers, err)) {
415         return false;
416     }
417 
418     action_ = std::move(action);
419     return true;
420 }
421 
ParseLineSection(const std::vector<std::string> & args,const std::string & filename,int line,std::string * err) const422 bool ActionParser::ParseLineSection(const std::vector<std::string>& args,
423                                     const std::string& filename, int line,
424                                     std::string* err) const {
425     return action_ ? action_->AddCommand(args, filename, line, err) : false;
426 }
427 
EndSection()428 void ActionParser::EndSection() {
429     if (action_ && action_->NumCommands() > 0) {
430         ActionManager::GetInstance().AddAction(std::move(action_));
431     }
432 }
433