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 <android-base/chrono_utils.h>
22 #include <android-base/file.h>
23 #include <android-base/logging.h>
24 #include <android-base/stringprintf.h>
25 #include <android-base/strings.h>
26 
27 #include "tokenizer.h"
28 #include "util.h"
29 
30 namespace android {
31 namespace init {
32 
Parser()33 Parser::Parser() {}
34 
AddSectionParser(const std::string & name,std::unique_ptr<SectionParser> parser)35 void Parser::AddSectionParser(const std::string& name, std::unique_ptr<SectionParser> parser) {
36     section_parsers_[name] = std::move(parser);
37 }
38 
AddSingleLineParser(const std::string & prefix,LineCallback callback)39 void Parser::AddSingleLineParser(const std::string& prefix, LineCallback callback) {
40     line_callbacks_.emplace_back(prefix, std::move(callback));
41 }
42 
ParseData(const std::string & filename,std::string * data)43 void Parser::ParseData(const std::string& filename, std::string* data) {
44     data->push_back('\n');
45     data->push_back('\0');
46 
47     parse_state state;
48     state.line = 0;
49     state.ptr = data->data();
50     state.nexttoken = 0;
51 
52     SectionParser* section_parser = nullptr;
53     int section_start_line = -1;
54     std::vector<std::string> args;
55 
56     // If we encounter a bad section start, there is no valid parser object to parse the subsequent
57     // sections, so we must suppress errors until the next valid section is found.
58     bool bad_section_found = false;
59 
60     auto end_section = [&] {
61         bad_section_found = false;
62         if (section_parser == nullptr) return;
63 
64         if (auto result = section_parser->EndSection(); !result.ok()) {
65             parse_error_count_++;
66             LOG(ERROR) << filename << ": " << section_start_line << ": " << result.error();
67         }
68 
69         section_parser = nullptr;
70         section_start_line = -1;
71     };
72 
73     for (;;) {
74         switch (next_token(&state)) {
75             case T_EOF:
76                 end_section();
77 
78                 for (const auto& [section_name, section_parser] : section_parsers_) {
79                     section_parser->EndFile();
80                 }
81 
82                 return;
83             case T_NEWLINE: {
84                 state.line++;
85                 if (args.empty()) break;
86                 // If we have a line matching a prefix we recognize, call its callback and unset any
87                 // current section parsers.  This is meant for /sys/ and /dev/ line entries for
88                 // uevent.
89                 auto line_callback = std::find_if(
90                     line_callbacks_.begin(), line_callbacks_.end(),
91                     [&args](const auto& c) { return android::base::StartsWith(args[0], c.first); });
92                 if (line_callback != line_callbacks_.end()) {
93                     end_section();
94 
95                     if (auto result = line_callback->second(std::move(args)); !result.ok()) {
96                         parse_error_count_++;
97                         LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
98                     }
99                 } else if (section_parsers_.count(args[0])) {
100                     end_section();
101                     section_parser = section_parsers_[args[0]].get();
102                     section_start_line = state.line;
103                     if (auto result =
104                                 section_parser->ParseSection(std::move(args), filename, state.line);
105                         !result.ok()) {
106                         parse_error_count_++;
107                         LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
108                         section_parser = nullptr;
109                         bad_section_found = true;
110                     }
111                 } else if (section_parser) {
112                     if (auto result = section_parser->ParseLineSection(std::move(args), state.line);
113                         !result.ok()) {
114                         parse_error_count_++;
115                         LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
116                     }
117                 } else if (!bad_section_found) {
118                     parse_error_count_++;
119                     LOG(ERROR) << filename << ": " << state.line
120                                << ": Invalid section keyword found";
121                 }
122                 args.clear();
123                 break;
124             }
125             case T_TEXT:
126                 args.emplace_back(state.text);
127                 break;
128         }
129     }
130 }
131 
ParseConfigFileInsecure(const std::string & path)132 bool Parser::ParseConfigFileInsecure(const std::string& path) {
133     std::string config_contents;
134     if (!android::base::ReadFileToString(path, &config_contents)) {
135         return false;
136     }
137 
138     ParseData(path, &config_contents);
139     return true;
140 }
141 
ParseConfigFile(const std::string & path)142 bool Parser::ParseConfigFile(const std::string& path) {
143     LOG(INFO) << "Parsing file " << path << "...";
144     android::base::Timer t;
145     auto config_contents = ReadFile(path);
146     if (!config_contents.ok()) {
147         LOG(INFO) << "Unable to read config file '" << path << "': " << config_contents.error();
148         return false;
149     }
150 
151     ParseData(path, &config_contents.value());
152 
153     LOG(VERBOSE) << "(Parsing " << path << " took " << t << ".)";
154     return true;
155 }
156 
ParseConfigDir(const std::string & path)157 bool Parser::ParseConfigDir(const std::string& path) {
158     LOG(INFO) << "Parsing directory " << path << "...";
159     std::unique_ptr<DIR, decltype(&closedir)> config_dir(opendir(path.c_str()), closedir);
160     if (!config_dir) {
161         PLOG(INFO) << "Could not import directory '" << path << "'";
162         return false;
163     }
164     dirent* current_file;
165     std::vector<std::string> files;
166     while ((current_file = readdir(config_dir.get()))) {
167         // Ignore directories and only process regular files.
168         if (current_file->d_type == DT_REG) {
169             std::string current_path =
170                 android::base::StringPrintf("%s/%s", path.c_str(), current_file->d_name);
171             files.emplace_back(current_path);
172         }
173     }
174     // Sort first so we load files in a consistent order (bug 31996208)
175     std::sort(files.begin(), files.end());
176     for (const auto& file : files) {
177         if (!ParseConfigFile(file)) {
178             LOG(ERROR) << "could not import file '" << file << "'";
179         }
180     }
181     return true;
182 }
183 
ParseConfig(const std::string & path)184 bool Parser::ParseConfig(const std::string& path) {
185     if (is_dir(path.c_str())) {
186         return ParseConfigDir(path);
187     }
188     return ParseConfigFile(path);
189 }
190 
191 }  // namespace init
192 }  // namespace android
193