Skip to content

Commit

Permalink
Sanitize regex input
Browse files Browse the repository at this point in the history
  • Loading branch information
franzpoeschel committed May 24, 2024
1 parent 8c57285 commit 590ee98
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
24 changes: 17 additions & 7 deletions src/Series.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2749,12 +2749,12 @@ namespace
std::smatch regexMatches;
bool match = std::regex_match(filename, regexMatches, pattern);
int processedPadding =
padding != 0 ? padding : (match ? regexMatches[1].length() : 0);
padding != 0 ? padding : (match ? regexMatches[2].length() : 0);
return {
match,
processedPadding,
padding < 0 ? padding
: match ? std::stoull(regexMatches[1])
: match ? std::stoull(regexMatches[2])
: 0,
index_of_extension.has_value()
? std::make_optional<std::string>(
Expand All @@ -2763,17 +2763,26 @@ namespace
};
}

namespace
{
auto sanitize_regex(std::string const &input) -> std::string
{
std::regex specialChars{R"([-[\]{}()*+?.,\^$|#\s])"};
return std::regex_replace(input, specialChars, R"(\$&)");
}
} // namespace

std::function<Match(std::string const &)> matcher(
std::string const &prefix,
int padding,
std::string const &postfix,
std::optional<std::string> const &filenameSuffix)
{
std::string nameReg = "^" + prefix;
std::string nameReg = "^(" + sanitize_regex(prefix) + ")";
size_t index_of_extension = 0;
if (padding < 0)
{
index_of_extension = 1;
index_of_extension = 3;
}
else if (padding > 0)
{
Expand All @@ -2785,16 +2794,17 @@ namespace
// iteration number via std::stoull(regexMatches[1])
nameReg += "(([1-9][[:digit:]]*)?([[:digit:]]";
nameReg += "{" + std::to_string(padding) + "}))";
index_of_extension = 4;
index_of_extension = 6;
}
else
{
// No padding specified, any number of digits is ok.
nameReg += "([[:digit:]]";
nameReg += "+)";
index_of_extension = 2;
index_of_extension = 4;
}
nameReg += postfix + filenameSuffix.value_or("(\\.[[:alnum:]]+)") + "$";
nameReg += "(" + sanitize_regex(postfix) + ")" +
filenameSuffix.value_or("(\\.[[:alnum:]]+)") + "$";
return buildMatcher(
nameReg,
padding,
Expand Down
6 changes: 4 additions & 2 deletions test/SerialIOTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5008,8 +5008,10 @@ TEST_CASE("serial_iterator", "[serial][adios2]")
{
for (auto const &t : testedFileExtensions())
{
serial_iterator("../samples/serial_iterator_filebased_%T." + t);
serial_iterator("../samples/serial_iterator_groupbased." + t);
// Add some regex characters into the file names to see that we can deal
// with that
serial_iterator("../samples/serial_iterator_filebased_+?_%T." + t);
serial_iterator("../samples/serial_iterator_groupbased_+?." + t);
}
}

Expand Down

0 comments on commit 590ee98

Please sign in to comment.