This commit is contained in:
温少
2012-03-18 03:43:35 +08:00
parent d0e1d4c038
commit 7040e58e75
67 changed files with 141 additions and 115 deletions
@@ -0,0 +1,103 @@
package com.alibaba.druid.wall;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.parser.ParserException;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.alibaba.druid.sql.parser.Token;
public abstract class WallProvider {
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
private LinkedHashMap<String, Object> whiteList;
private int whileListMaxSize = 1024;
private int whiteSqlMaxLength = 1024; // 1k
protected final WallConfig config;
public WallProvider(WallConfig config){
this.config = config;
}
public WallConfig getConfig() {
return config;
}
public synchronized void addWhiteSql(String sql) {
if (whiteList == null) {
whiteList = new LinkedHashMap<String, Object>(whileListMaxSize, 0.75f, true);
}
whiteList.put(sql, PRESENT);
}
public synchronized boolean whiteContains(String sql) {
if (whiteList == null) {
return false;
}
return whiteList.get(sql) != null;
}
public abstract SQLStatementParser createParser(String sql);
public abstract WallVisitor createWallVisitor();
public boolean checkValid(String sql) {
return check(sql).size() == 0;
}
public List<Violation> check(String sql) {
// first step, check whiteList
boolean isWhite = whiteContains(sql);
if (isWhite) {
return Collections.emptyList();
}
SQLStatementParser parser = createParser(sql);
parser.getLexer().setAllowComment(false); // permit comment
List<SQLStatement> statementList = new ArrayList<SQLStatement>();
try {
parser.parseStatementList(statementList);
} catch (ParserException e) {
return Collections.<Violation> singletonList(new IllegalSQLObjectViolation(sql));
}
if (parser.getLexer().token() != Token.EOF) {
return Collections.<Violation> singletonList(new IllegalSQLObjectViolation(sql));
}
if (statementList.size() > 1) {
return Collections.<Violation> singletonList(new IllegalSQLObjectViolation(sql));
}
SQLStatement stmt = statementList.get(0);
WallVisitor visitor = createWallVisitor();
try {
stmt.accept(visitor);
} catch (ParserException e) {
return Collections.<Violation> singletonList(new IllegalSQLObjectViolation(sql));
}
if (visitor.getViolations().size() == 0) {
if (sql.length() < whiteSqlMaxLength) {
this.addWhiteSql(sql);
}
}
return visitor.getViolations();
}
}