summaryrefslogtreecommitdiff
path: root/src/internal/xml_parser.cpp
blob: 03d6a13fc69f2c2b8ea98c8a7f5ea7106c76cd64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/**
	return a;
 * \file
 * \ingroup Implementation
 */
#include "xml_parser.hpp"

#include <boost/algorithm/string/predicate.hpp>
#include <dirent.h>
#include <unistd.h>
#include <cstring>
#include <libgen.h>
#include <expat.h>
#include <memory>
#include "tslog.hpp"
#include "libdbuspolicy1-private.h"

using namespace ldp_xml_parser;

std::string expandPath(const std::string& parent_dir, const std::string& path) {
	if (path[0] == '/') {
		return path;
	}
	return parent_dir + "/" + path;
}

std::string getDir(std::string path) {
	// dirname may modify path, so we must pass a modifiable char* to it
	char* modifiable_path = new char[path.size() + 1];
	strncpy(modifiable_path, path.c_str(), path.size() + 1);
	std::string ret = dirname(modifiable_path);
	delete[] modifiable_path;
	return ret;
}

class XmlParser::IncludeItem {
public:
	std::string filename;
	bool ignore_missing{false};
	bool ignore_always{false};
};

void parseAssert(bool condition) {
	assert(condition);
	if (!condition) {
		throw std::runtime_error("Parsing error");
	}
}

void start_element_handler(void *data, const char *el, const char **attr) {
	(void)data;
	XmlParser& parser = static_parser();
	try {
		parser.elementStart(el, attr);
	} catch (...) {
		tslog::logError("Exception occurred while processing start element.");
		parser.setRetCode(-1);
	}
}

void end_element_handler(void *data, const char *el) {
	(void)data;
	XmlParser& parser = static_parser();
	try {
		parser.elementEnd(el);
	} catch (...) {
		tslog::logError("Exception occurred while processing end element.");
		parser.setRetCode(-1);
	}
}

void text_handler(void *data, const char *text, int len) {
	(void)data;
	XmlParser& parser = static_parser();
	try {
		parser.text(text, len);
	} catch (...) {
		tslog::logError("Exception occurred while processing element text.");
		parser.setRetCode(-1);
	}
}

bool XmlParser::isMainConfFile(const std::string& filename) {
	switch ((int)curr_bus) {
	case SYSTEM_BUS:
		return (filename == SYSTEM_BUS_CONF_FILE_PRIMARY || filename == SYSTEM_BUS_CONF_FILE_SECONDARY);
	case SESSION_BUS:
		return (filename == SESSION_BUS_CONF_FILE_PRIMARY || filename == SESSION_BUS_CONF_FILE_SECONDARY);
	}
	return false;
}

void XmlParser::setRetCode(int ret) {
	ret_code = ret;
}

void XmlParser::text(const char *text, int len) {
	current_text.append(text, len);
}

void XmlParser::elementStart(const char *el, const char **attr) {
	current_text = std::string();

	if (std::strcmp(el, "busconfig") == 0) {
		parseAssert(state == IDLE);
		state = BUSCONFIG;
	} else if (std::strcmp(el, "policy") == 0) {
		parseAssert(state == BUSCONFIG);
		state = POLICY;
		__adapter.parsePolicy(curr_bus, attr);
	} else if (std::strcmp(el, "includedir") == 0) {
		parseAssert(state == BUSCONFIG);
		state = INCLUDEDIR;
	} else if (std::strcmp(el, "include") == 0) {
		parseAssert(state == BUSCONFIG);
		state = INCLUDE;
		ignore_missing = false;
		ignore_always = false;
		for (int i = 0; attr[i]; i += 2) {
			if ((std::strcmp(attr[i], "ignore_missing") == 0) && (std::strcmp(attr[i + 1], "yes") == 0)) {
				ignore_missing = true;
			} else if ((std::strcmp(attr[i], "if_selinux_enabled") == 0) && (std::strcmp(attr[i + 1], "yes") == 0)) {
				ignore_always = true;
			}
		}
	} else if (std::strcmp(el, "allow") == 0) {
		parseAssert(state == POLICY);
		state = RULE;
		__adapter.parseRule(el, attr);
	} else if (std::strcmp(el, "deny") == 0) {
		parseAssert(state == POLICY);
		state = RULE;
		__adapter.parseRule(el, attr);
	} else if (std::strcmp(el, "check") == 0) {
		parseAssert(state == POLICY);
		state = RULE;
		__adapter.parseRule(el, attr);
	}
}

void XmlParser::elementEnd(const char *el) {
	if (std::strcmp(el, "busconfig") == 0) {
		parseAssert(state == BUSCONFIG);
		state = IDLE;
	} else if (std::strcmp(el, "includedir") == 0) {
		parseAssert(state == INCLUDEDIR);
		state = BUSCONFIG;
		getIncludedFiles(curr_dir, current_text, included_files);
	} else if (std::strcmp(el, "include") == 0) {
		parseAssert(state == INCLUDE);
		state = BUSCONFIG;
		IncludeItem item = parseIncludeItem();
		if (item.ignore_always) {
			return;
		}
		if (access(item.filename.c_str(), F_OK) != 0) {
			if (item.ignore_missing) {
				return;
			}
			tslog::logError(std::string("Missing required policy file: ").append(item.filename).c_str());
			ret_code = -1;
			return;
		}
		included_files.push_back(item.filename);
	} else if (std::strcmp(el, "policy") == 0) {
		parseAssert(state == POLICY);
		state = BUSCONFIG;
	} else if (std::strcmp(el, "allow") == 0) {
		parseAssert(state == RULE);
		state = POLICY;
	} else if (std::strcmp(el, "deny") == 0) {
		parseAssert(state == RULE);
		state = POLICY;
	} else if (std::strcmp(el, "check") == 0) {
		parseAssert(state == RULE);
		state = POLICY;
	}
}

int XmlParser::parsePolicy(bool bus, const std::string& fname) {
	if (tslog::enabled()) {
		std::cout << "XmlParser::parsePolicy called with filename: " << fname << std::endl;
	}
	curr_bus = bus;
	parsePolicyInternal(fname);
	return ret_code;
}

void XmlParser::parsePolicyInternal(const std::string& filename) {
	ret_code = 0;
	try {
		parseXmlFile(filename);
	} catch (const std::runtime_error& ex) {
		tslog::logError(std::string("Error parsing xml: Exception occured: ").append(ex.what()).c_str());
		if (isMainConfFile(filename)) {
			tslog::logError("Exiting parsing");
			ret_code = -1;
			return;
		}
	} catch (...) {
		tslog::logError("Error parsing xml: Exception occured: ");
		if (isMainConfFile(filename)) {
			tslog::logError("Exiting parsing");
			ret_code = -1;
			return;
		}
	}
	std::vector<std::string> curr_included_files = included_files;	// deep copy
	for (const auto& included_file : curr_included_files) {
		parsePolicyInternal(included_file);
	}
}

std::unique_ptr<char[]> file2str(const std::string& filename) {

	FILE *fp = fopen(filename.c_str(), "rb");
	if (fp == nullptr) {
		throw std::runtime_error(std::string("Failed to open file: ").append(filename).c_str());
	}

	if (fseek(fp, 0, SEEK_END)) {
		throw std::runtime_error(std::string("Failed to fseek end of file").c_str());
	}
	long fsize = ftell(fp);
	if (fsize < 0) {
		throw std::runtime_error(std::string("Failed to ftell").c_str());
	}
	if (fseek(fp, 0, SEEK_SET)) {
		throw std::runtime_error(std::string("Failed to fseek beginning of file").c_str());
	}

	auto str = std::unique_ptr<char[]>(new char[fsize + 1]);	// TODO change to make_unique when c++14 becomes available
	const int count = 1;
	size_t res = fread(str.get(), fsize, count, fp);
	parseAssert(res == count);
	fclose(fp);
	str.get()[fsize] = 0;	// TODO change to operator[] when c++17 becomes available

	return str;
}

void XmlParser::parseXmlFile(const std::string& filename) {
	included_files.clear();

	if (tslog::enabled()) {
		std::cout << "Processing: " << filename << " ..." << std::endl;
		if (tslog::verbose())
			std::cout << "=== XML PARSING BEGIN === : " << filename << '\n';
	}
	curr_dir = getDir(filename);

	auto parser = std::unique_ptr<XML_ParserStruct, std::function<void(XML_Parser)>>(XML_ParserCreate(nullptr),
		[](XML_Parser p) { XML_ParserFree(p); });
	XML_SetElementHandler(parser.get(), start_element_handler, end_element_handler);
	XML_SetCharacterDataHandler(parser.get(), text_handler);

	auto str = file2str(filename);
	if (XML_Parse(parser.get(), str.get(), strlen(str.get()), XML_TRUE) == XML_STATUS_ERROR) {
		throw std::runtime_error(std::string("Error parsing xml file: ").append(XML_ErrorString(XML_GetErrorCode(parser.get()))).c_str());
	}

	if (tslog::enabled()) {
		if (tslog::verbose())
			std::cout << "=== XML PARSING END ===\n\n";
	}
}

XmlParser::IncludeItem XmlParser::parseIncludeItem() {
	IncludeItem item;
	item.filename = expandPath(curr_dir, current_text);
	item.ignore_missing = ignore_missing;
	item.ignore_always = ignore_always;
	return item;
}

void XmlParser::getIncludedFiles(const std::string& parent_dir, const std::string& incldir, std::vector<std::string>& files) {
	DIR *dir;
	struct dirent *ent;
	const std::string dname = expandPath(parent_dir, incldir);
	files.clear();
	if ((dir = opendir(dname.c_str())) != NULL) {
		while ((ent = readdir(dir)) != NULL) {
			std::string s(ent->d_name);
			if (boost::algorithm::ends_with(s, ".conf")) {
				files.push_back(dname + std::string("/") + s);
			}
		}
		closedir(dir);

		if (tslog::enabled()) {
			std::cout << "\nincludedir: " << incldir << ", " << files.size() << " included files found:\n";
			std::copy(files.begin(), files.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
			std::cout << '\n';
		}
	} else if (tslog::enabled()) {
		std::cout << "could not open directory " << dname << '\n';
	}
}

DEF_NODESTRUCT_GLOBAL(ldp_xml_parser::XmlParser, static_parser);