Skip to content

Commit

Permalink
Replace regex with custom logic for MQTT topic matching
Browse files Browse the repository at this point in the history
  • Loading branch information
epieffe committed Jan 2, 2025
1 parent 0a1d2de commit 269a9a1
Showing 1 changed file with 48 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -105,23 +105,58 @@ public boolean matchesPublish(

private boolean topicMatches(String topic, String pattern, long authorization)
{
for (GuardedConfig g : guarded)
int topicIndex = 0;
for (int i = 0; i < pattern.length(); ++i)
{
String identity = g.identity.apply(authorization);
if (identity != null)
char patternChar = pattern.charAt(i);
if (patternChar == '#')
{
pattern = pattern.replace(String.format("{guarded[%s].identity}", g.name), identity);
return true;
}
else if (patternChar == '+')
{
while (topicIndex < topic.length())
{
if (topic.charAt(topicIndex) == '/')
{
break;
}
topicIndex++;
}
}
else
{
if (pattern.startsWith("{guarded[", i))
{
int i2 = i + "{guarded[".length();
GuardedConfig guardedMatch = null;
for (GuardedConfig g : guarded)
{
if (pattern.startsWith(g.name, i2))
{
guardedMatch = g;
i2 += g.name.length();
break;
}
}
if (guardedMatch != null && pattern.startsWith("].identity}", i2))
{
String identity = guardedMatch.identity.apply(authorization);
if (identity != null && topic.startsWith(identity, topicIndex))
{
i = i2 + "].identity}".length();
topicIndex += identity.length();
continue;
}
}
}
if (topicIndex == topic.length() || topic.charAt(topicIndex++) != patternChar)
{
return false;
}
}
}
return topic.matches(pattern
.replace("{", "\\{")
.replace("}", "\\}")
.replace("[", "\\[")
.replace("]", "\\]")
.replace(".", "\\.")
.replace("$", "\\$")
.replace("+", "[^/]*")
.replace("#", ".*"));
return topicIndex == topic.length();
}

private static List<Matcher> asWildcardMatcher(
Expand All @@ -137,7 +172,6 @@ private static List<Matcher> asWildcardMatcher(
pattern = pattern + "(\\?.*)?";
}
matchers.add(Pattern.compile(pattern).matcher(""));

}

return matchers;
Expand Down

0 comments on commit 269a9a1

Please sign in to comment.