How to set a time limit on a java function running a regex

后端 未结 10 908
难免孤独
难免孤独 2020-12-17 02:41

I am running a regex in a java function to parse a document and return true if it has found the string specified by the regex and return false if it hasn\'t. But the problem

10条回答
  •  一生所求
    2020-12-17 03:23

    The below answer is perhaps late for the post and Java version has also changed. However, the mechanism mentioned below works for me.

    The central idea is to change the input text which is being evaluated to an empty string while the matching is in progress. The input for the below test has been taken from OWASP ReDoS example. The input text has been changed as the one provided was not of adequate length for the complexity.

    package org.test.xpath;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class InterruptableMatcherTest {
    
        public static void main(String[] args) throws Exception{
    
            Pattern pattern=Pattern.compile("^(([a-z])+.)+[A-Z]([a-z])+$");
            String input="aaaaaaaaaaaaaaaaaaaaaffffdffffdffffdffffdffffdffffdffffdffffdffffdffffdffffdffffdffffdaaaaaaaaaaaa!";
    
            PatternMatcher patternMatcher=new PatternMatcher(pattern, input);
            Thread thread=new Thread(patternMatcher);
    
            thread.start();
    
            Thread.sleep(1*1000);
            System.out.println("Done sleeping ...");
            if(patternMatcher.running)patternMatcher.reset();//Without this call the program will hang
            thread.join();
    
        }//main closing
    
    }//class closing
    
    class PatternMatcher implements Runnable{
    
        Pattern pattern;
        Matcher matcher;
    
        boolean running=false;
    
        PatternMatcher(Pattern pattern, String input) {
    
            this.pattern=pattern;
            matcher=this.pattern.matcher(input);
    
        }//constructor closing
    
        @Override
        public void run() {
    
            running=true;
            matcher.matches();
            running=false;
    
        }//run closing
    
        void reset(){
    
            System.out.println("Reset called ...");
            matcher.reset("");
    
        }//reset closing
    
    }//class closing
    

    The reset() method, resets the input of the matcher to an empty String. refer code for Matcher class, Matcher reset(CharSequence input) method, which calls the Matcher reset(), which in turn sets the start and end of the text region to be matched to 0, effectively stopping the matching process in the next stage match. The mechanism works for me by terminating the matching process after a set timeout.

提交回复
热议问题