* @brief a helper function which loads the classifier from files. * @param args classname + filename in ' : ' format. * @param denylist true - load as a denylist classifier, false - allowlist. * @return true if successful, false otherwise. */
| 278 | * @return true if successful, false otherwise. |
| 279 | */ |
| 280 | bool |
| 281 | Configs::loadClassifiers(const String &args, bool denylist) |
| 282 | { |
| 283 | static const char *EXPECTED_FORMAT = "<classname>:<filename>"; |
| 284 | |
| 285 | std::size_t d = args.find(':'); |
| 286 | if (String::npos == d) { |
| 287 | CacheKeyError("failed to parse classifier string '%s', expected format: '%s'", optarg ? optarg : "null", EXPECTED_FORMAT); |
| 288 | return false; |
| 289 | } |
| 290 | |
| 291 | String classname(optarg, 0, d); |
| 292 | String filename(optarg, d + 1, String::npos); |
| 293 | |
| 294 | if (classname.empty() || filename.empty()) { |
| 295 | CacheKeyError("'<classname>' and '<filename>' in '%s' cannot be empty, expected format: '%s'", optarg ? optarg : "null", |
| 296 | EXPECTED_FORMAT); |
| 297 | return false; |
| 298 | } |
| 299 | |
| 300 | String path(makeConfigPath(filename)); |
| 301 | |
| 302 | std::ifstream ifstr; |
| 303 | String regex; |
| 304 | unsigned lineno = 0; |
| 305 | |
| 306 | ifstr.open(path.c_str()); |
| 307 | if (!ifstr) { |
| 308 | CacheKeyError("failed to load classifier '%s' from '%s'", classname.c_str(), path.c_str()); |
| 309 | return false; |
| 310 | } |
| 311 | |
| 312 | MultiPattern *multiPattern; |
| 313 | if (denylist) { |
| 314 | multiPattern = new NonMatchingMultiPattern(classname); |
| 315 | } else { |
| 316 | multiPattern = new MultiPattern(classname); |
| 317 | } |
| 318 | if (nullptr == multiPattern) { |
| 319 | CacheKeyError("failed to allocate classifier '%s'", classname.c_str()); |
| 320 | return false; |
| 321 | } |
| 322 | |
| 323 | CacheKeyDebug("loading classifier '%s' from '%s'", classname.c_str(), path.c_str()); |
| 324 | |
| 325 | while (std::getline(ifstr, regex)) { |
| 326 | Pattern *p; |
| 327 | String::size_type pos; |
| 328 | |
| 329 | ++lineno; |
| 330 | |
| 331 | // Allow #-prefixed comments. |
| 332 | pos = regex.find_first_of('#'); |
| 333 | if (pos != String::npos) { |
| 334 | regex.resize(pos); |
| 335 | } |
| 336 | |
| 337 | if (regex.empty()) { |