• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 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 "parser.h"
18 
19 #include <dirent.h>
20 
21 #include <map>
22 
23 #include <android-base/chrono_utils.h>
24 #include <android-base/file.h>
25 #include <android-base/logging.h>
26 #include <android-base/stringprintf.h>
27 #include <android-base/strings.h>
28 
29 #include "tokenizer.h"
30 #include "util.h"
31 
32 namespace android {
33 namespace init {
34 
Parser()35 Parser::Parser() {}
36 
AddSectionParser(const std::string & name,std::unique_ptr<SectionParser> parser)37 void Parser::AddSectionParser(const std::string& name, std::unique_ptr<SectionParser> parser) {
38     section_parsers_[name] = std::move(parser);
39 }
40 
AddSingleLineParser(const std::string & prefix,LineCallback callback)41 void Parser::AddSingleLineParser(const std::string& prefix, LineCallback callback) {
42     line_callbacks_.emplace_back(prefix, std::move(callback));
43 }
44 
ParseData(const std::string & filename,std::string * data)45 void Parser::ParseData(const std::string& filename, std::string* data) {
46     data->push_back('\n');
47     data->push_back('\0');
48 
49     parse_state state;
50     state.line = 0;
51     state.ptr = data->data();
52     state.nexttoken = 0;
53 
54     SectionParser* section_parser = nullptr;
55     int section_start_line = -1;
56     std::vector<std::string> args;
57 
58     // If we encounter a bad section start, there is no valid parser object to parse the subsequent
59     // sections, so we must suppress errors until the next valid section is found.
60     bool bad_section_found = false;
61 
62     auto end_section = [&] {
63         bad_section_found = false;
64         if (section_parser == nullptr) return;
65 
66         if (auto result = section_parser->EndSection(); !result.ok()) {
67             parse_error_count_++;
68             LOG(ERROR) << filename << ": " << section_start_line << ": " << result.error();
69         }
70 
71         section_parser = nullptr;
72         section_start_line = -1;
73     };
74 
75     for (;;) {
76         switch (next_token(&state)) {
77             case T_EOF:
78                 end_section();
79 
80                 for (const auto& [section_name, section_parser] : section_parsers_) {
81                     section_parser->EndFile();
82                 }
83 
84                 return;
85             case T_NEWLINE: {
86                 state.line++;
87                 if (args.empty()) break;
88                 // If we have a line matching a prefix we recognize, call its callback and unset any
89                 // current section parsers.  This is meant for /sys/ and /dev/ line entries for
90                 // uevent.
91                 auto line_callback = std::find_if(
92                     line_callbacks_.begin(), line_callbacks_.end(),
93                     [&args](const auto& c) { return android::base::StartsWith(args[0], c.first); });
94                 if (line_callback != line_callbacks_.end()) {
95                     end_section();
96 
97                     if (auto result = line_callback->second(std::move(args)); !result.ok()) {
98                         parse_error_count_++;
99                         LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
100                     }
101                 } else if (section_parsers_.count(args[0])) {
102                     end_section();
103                     section_parser = section_parsers_[args[0]].get();
104                     section_start_line = state.line;
105                     if (auto result =
106                                 section_parser->ParseSection(std::move(args), filename, state.line);
107                         !result.ok()) {
108                         parse_error_count_++;
109                         LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
110                         section_parser = nullptr;
111                         bad_section_found = true;
112                     }
113                 } else if (section_parser) {
114                     if (auto result = section_parser->ParseLineSection(std::move(args), state.line);
115                         !result.ok()) {
116                         parse_error_count_++;
117                         LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
118                     }
119                 } else if (!bad_section_found) {
120                     parse_error_count_++;
121                     LOG(ERROR) << filename << ": " << state.line
122                                << ": Invalid section keyword found";
123                 }
124                 args.clear();
125                 break;
126             }
127             case T_TEXT:
128                 args.emplace_back(state.text);
129                 break;
130         }
131     }
132 }
133 
ParseConfigFileInsecure(const std::string & path)134 bool Parser::ParseConfigFileInsecure(const std::string& path) {
135     std::string config_contents;
136     if (!android::base::ReadFileToString(path, &config_contents)) {
137         return false;
138     }
139 
140     ParseData(path, &config_contents);
141     return true;
142 }
143 
ParseConfigFile(const std::string & path)144 bool Parser::ParseConfigFile(const std::string& path) {
145     LOG(INFO) << "Parsing file " << path << "...";
146     android::base::Timer t;
147     auto config_contents = ReadFile(path);
148     if (!config_contents.ok()) {
149         LOG(INFO) << "Unable to read config file '" << path << "': " << config_contents.error();
150         return false;
151     }
152 
153     ParseData(path, &config_contents.value());
154 
155     LOG(VERBOSE) << "(Parsing " << path << " took " << t << ".)";
156     return true;
157 }
158 
FilterVersionedConfigs(const std::vector<std::string> & configs,int active_sdk)159 std::vector<std::string> Parser::FilterVersionedConfigs(const std::vector<std::string>& configs,
160                                                         int active_sdk) {
161     std::vector<std::string> filtered_configs;
162 
163     std::map<std::string, std::pair<std::string, int>> script_map;
164     for (const auto& c : configs) {
165         int sdk = 0;
166         const std::vector<std::string> parts = android::base::Split(c, ".");
167         std::string base;
168         if (parts.size() < 2) {
169             continue;
170         }
171 
172         // parts[size()-1], aka the suffix, should be "rc" or "#rc"
173         // any other pattern gets discarded
174 
175         const auto& suffix = parts[parts.size() - 1];
176         if (suffix == "rc") {
177             sdk = 0;
178         } else {
179             char trailer[9] = {0};
180             int r = sscanf(suffix.c_str(), "%d%8s", &sdk, trailer);
181             if (r != 2) {
182                 continue;
183             }
184             if (strlen(trailer) > 2 || strcmp(trailer, "rc") != 0) {
185                 continue;
186             }
187         }
188 
189         if (sdk < 0 || sdk > active_sdk) {
190             continue;
191         }
192 
193         base = parts[0];
194         for (unsigned int i = 1; i < parts.size() - 1; i++) {
195             base = base + "." + parts[i];
196         }
197 
198         // is this preferred over what we already have
199         auto it = script_map.find(base);
200         if (it == script_map.end() || it->second.second < sdk) {
201             script_map[base] = std::make_pair(c, sdk);
202         }
203     }
204 
205     for (const auto& m : script_map) {
206         filtered_configs.push_back(m.second.first);
207     }
208     return filtered_configs;
209 }
210 
ParseConfigDir(const std::string & path)211 bool Parser::ParseConfigDir(const std::string& path) {
212     LOG(INFO) << "Parsing directory " << path << "...";
213     std::unique_ptr<DIR, decltype(&closedir)> config_dir(opendir(path.c_str()), closedir);
214     if (!config_dir) {
215         PLOG(INFO) << "Could not import directory '" << path << "'";
216         return false;
217     }
218     dirent* current_file;
219     std::vector<std::string> files;
220     while ((current_file = readdir(config_dir.get()))) {
221         // Ignore directories and only process regular files.
222         if (current_file->d_type == DT_REG) {
223             std::string current_path =
224                 android::base::StringPrintf("%s/%s", path.c_str(), current_file->d_name);
225             files.emplace_back(current_path);
226         }
227     }
228     // Sort first so we load files in a consistent order (bug 31996208)
229     std::sort(files.begin(), files.end());
230     for (const auto& file : files) {
231         if (!ParseConfigFile(file)) {
232             LOG(ERROR) << "could not import file '" << file << "'";
233         }
234     }
235     return true;
236 }
237 
ParseConfig(const std::string & path)238 bool Parser::ParseConfig(const std::string& path) {
239     if (is_dir(path.c_str())) {
240         return ParseConfigDir(path);
241     }
242     return ParseConfigFile(path);
243 }
244 
245 }  // namespace init
246 }  // namespace android
247