MCPcopy Create free account
hub / github.com/USBGuard/usbguard / parseFromFile

Method parseFromFile

src/Library/UMockdevDeviceDefinition.cpp:267–325  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

265 }
266
267 std::vector<std::unique_ptr<UMockdevDeviceDefinition>> UMockdevDeviceDefinition::parseFromFile(const std::string& filepath,
268 bool sort_by_hierarchy)
269 {
270 const std::string umockdev_name = filenameFromPath(filepath, /*include_extension=*/true);
271 std::vector<std::unique_ptr<UMockdevDeviceDefinition>> definitions;
272
273 try {
274 USBGUARD_LOG(Debug) << "Parsing umockdev definitions from " << filepath;
275 tao::pegtl::file_input<> input(filepath);
276 tao::pegtl::parse<UMockdevParser::grammar, UMockdevParser::actions>(input, definitions, umockdev_name);
277 USBGUARD_LOG(Debug) << "Parsed " << definitions.size() << " definition(s)";
278 }
279 catch (...) {
280 USBGUARD_LOG(Error) << "UMockdevDeviceDefinition: " << filepath << ": parsing failed at line <LINE>";
281 throw;
282 }
283
284 const auto lambdaSysfsPathHierarchyCompare = [](const std::unique_ptr<UMockdevDeviceDefinition>& a,
285 const std::unique_ptr<UMockdevDeviceDefinition>& b) {
286 const std::string full_a = a->getSysfsPath();
287 const std::string full_b = b->getSysfsPath();
288 const std::size_t component_count_a = countPathComponents(full_a);
289 const std::size_t component_count_b = countPathComponents(full_b);
290 USBGUARD_LOG(Debug) << "c_c_a=" << component_count_a << " c_c_b=" << component_count_b;
291
292 if (component_count_a < component_count_b) {
293 return true;
294 }
295 else if (component_count_a > component_count_b) {
296 return false;
297 }
298
299 const std::string base_a = filenameFromPath(full_a, /*include_extension=*/true);
300 const std::string base_b = filenameFromPath(full_b, /*include_extension=*/true);
301 const bool a_has_usb_prefix = hasPrefix("usb", base_a);
302 const bool b_has_usb_prefix = hasPrefix("usb", base_b);
303 USBGUARD_LOG(Debug) << "a_p=" << a_has_usb_prefix << " b_p=" << b_has_usb_prefix;
304
305 if (a_has_usb_prefix) {
306 if (!b_has_usb_prefix) {
307 return true;
308 }
309 }
310 else {
311 if (b_has_usb_prefix) {
312 return false;
313 }
314 }
315
316 return base_a < base_b;
317 };
318
319 if (sort_by_hierarchy) {
320 USBGUARD_LOG(Debug) << "Sorting definitions";
321 std::sort(definitions.begin(), definitions.end(), lambdaSysfsPathHierarchyCompare);
322 }
323
324 return definitions;

Callers

nothing calls this directly

Calls 3

filenameFromPathFunction · 0.85
countPathComponentsFunction · 0.85
hasPrefixFunction · 0.85

Tested by

no test coverage detected