Skip to content

The matching algorithm explained

Nat! edited this page Feb 12, 2018 · 2 revisions

So in pseudo shellcode, this is what happens if you were to match a hardcoded filename x/foo.c against the patternfile directories:

match()
{
   if patterndir_match "ignore.d" 
   then
      return $NO
   fi 
   if patterndir_match "match.d" 
   then
      return $YES
   fi 
   return $NO
}

The results of the patternfiles are ORed together:

patterndir_match()
{
   folder=$1

   for patternfile in $folder
   do
      if patternfile_match < ${patternfile}
      then  
         return $YES
      fi
   done
   return $NO
}

If you were just to consider non-inverted patterns, then a patternfile is the OR of all patterns:

patternfile_match()
{
   while read pattern
   do
      case "x/foo.c" in
         ${pattern})
            return $YES
      ;;
   done
   return $NO
}

It gets trickier with inverted patterns though, as these introduce a NAND. So patterns are evaluated from top to bottom. An inverted pattern that matches, negates any prior match.

patternfile_match()
{
   matches=$NO
   while read pattern
   do
      case "!x/foo.c" in
         ${pattern})
            matches=$NO
            continue
         ;;
      esac

      case "x/foo.c" in
         ${pattern})
            matches=$YES
      ;;
      esac
   done
   return $matches
}
Clone this wiki locally