1 /*
2 * Copyright (C) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "config_parser.h"
16 #include <iostream>
17 #include <fstream>
18 #include <sstream>
19 #include <map>
20 #include <string>
21 #include "app_domain_verify_hilog.h"
22
23 namespace OHOS::AppDomainVerify::Dfx {
24 constexpr int MAX_FILE_SIZE = 1024;
25 constexpr int MAX_LINE_SIZE = 1024;
26
load(const std::string & filename)27 bool ConfigParser::load(const std::string& filename)
28 {
29 std::ifstream file(filename, std::ios::ate);
30 if (!file.is_open()) {
31 std::cerr << "Unable to open file: " << filename << std::endl;
32 APP_DOMAIN_VERIFY_HILOGE(APP_DOMAIN_VERIFY_MODULE_JS_NAPI, "Unable to open file: filename:%{public}s",
33 filename.c_str());
34 return false;
35 }
36
37 if (file.tellg() > MAX_FILE_SIZE) {
38 APP_DOMAIN_VERIFY_HILOGE(APP_DOMAIN_VERIFY_MODULE_JS_NAPI, "File size exceeds maximum allowed size");
39 return false;
40 }
41
42 file.seekg(0, std::ios::beg);
43 std::string line;
44 while (std::getline(file, line)) {
45 if (line.size() > MAX_LINE_SIZE) {
46 APP_DOMAIN_VERIFY_HILOGE(APP_DOMAIN_VERIFY_MODULE_JS_NAPI, "Line size exceeds maximum allowed size");
47 return false;
48 }
49 line = trim(line);
50 if (line.empty() || line[0] == ';' || line[0] == '#') {
51 continue; // Skip comments and empty lines
52 }
53
54 auto delimiterPos = line.find('=');
55 if (delimiterPos != std::string::npos) {
56 std::string key = trim(line.substr(0, delimiterPos));
57 std::string value = trim(line.substr(delimiterPos + 1));
58 configData[key] = value;
59 }
60 }
61 return true;
62 }
63
get(const std::string & key,const std::string & defaultValue) const64 std::string ConfigParser::get(const std::string& key, const std::string& defaultValue) const
65 {
66 auto it = configData.find(key);
67 if (it != configData.end()) {
68 return it->second;
69 }
70 return defaultValue;
71 }
72
trim(const std::string & str)73 std::string ConfigParser::trim(const std::string& str)
74 {
75 size_t first = str.find_first_not_of(' ');
76 if (first == std::string::npos)
77 return "";
78 size_t last = str.find_last_not_of(' ');
79 return str.substr(first, last - first + 1);
80 }
81
82 }