• 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,bool follow_symlinks=false)134 bool Parser::ParseConfigFileInsecure(const std::string& path, bool follow_symlinks = false) {
135     std::string config_contents;
136     if (!android::base::ReadFileToString(path, &config_contents, follow_symlinks)) {
137         return false;
138     }
139 
140     ParseData(path, &config_contents);
141     return true;
142 }
143 
ParseConfigFile(const std::string & path)144 Result<void> 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         return Error() << "Unable to read config file '" << path
150                        << "': " << config_contents.error();
151     }
152 
153     ParseData(path, &config_contents.value());
154 
155     LOG(VERBOSE) << "(Parsing " << path << " took " << t << ".)";
156     return {};
157 }
158 
ParseConfigDir(const std::string & path)159 bool Parser::ParseConfigDir(const std::string& path) {
160     LOG(INFO) << "Parsing directory " << path << "...";
161     std::unique_ptr<DIR, decltype(&closedir)> config_dir(opendir(path.c_str()), closedir);
162     if (!config_dir) {
163         PLOG(INFO) << "Could not import directory '" << path << "'";
164         return false;
165     }
166     dirent* current_file;
167     std::vector<std::string> files;
168     while ((current_file = readdir(config_dir.get()))) {
169         // Ignore directories and only process regular files.
170         if (current_file->d_type == DT_REG) {
171             std::string current_path =
172                 android::base::StringPrintf("%s/%s", path.c_str(), current_file->d_name);
173             files.emplace_back(current_path);
174         }
175     }
176     // Sort first so we load files in a consistent order (bug 31996208)
177     std::sort(files.begin(), files.end());
178     for (const auto& file : files) {
179         if (auto result = ParseConfigFile(file); !result.ok()) {
180             LOG(ERROR) << "could not import file '" << file << "': " << result.error();
181         }
182     }
183     return true;
184 }
185 
ParseConfig(const std::string & path)186 bool Parser::ParseConfig(const std::string& path) {
187     if (is_dir(path.c_str())) {
188         return ParseConfigDir(path);
189     }
190     auto result = ParseConfigFile(path);
191     if (!result.ok()) {
192         LOG(INFO) << result.error();
193     }
194     return result.ok();
195 }
196 
197 }  // namespace init
198 }  // namespace android
199