2 * Copyright (C) 2001, 2002 The Mir-coders group
\r
4 * This file is part of Mir.
\r
6 * Mir is free software; you can redistribute it and/or modify
\r
7 * it under the terms of the GNU General Public License as published by
\r
8 * the Free Software Foundation; either version 2 of the License, or
\r
9 * (at your option) any later version.
\r
11 * Mir is distributed in the hope that it will be useful,
\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
14 * GNU General Public License for more details.
\r
16 * You should have received a copy of the GNU General Public License
\r
17 * along with Mir; if not, write to the Free Software
\r
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\r
20 * In addition, as a special exception, The Mir-coders gives permission to link
\r
21 * the code of this program with any library licensed under the Apache Software License,
\r
22 * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
\r
23 * (or with modified versions of the above that use the same license as the above),
\r
24 * and distribute linked combinations including the two. You must obey the
\r
25 * GNU General Public License in all respects for all of the code used other than
\r
26 * the above mentioned libraries. If you modify this file, you may extend this
\r
27 * exception to your version of the file, but you are not obligated to do so.
\r
28 * If you do not wish to do so, delete this exception statement from your version.
\r
31 package mircoders.global;
\r
33 import java.io.File;
\r
34 import java.io.FileNotFoundException;
\r
35 import java.io.FileOutputStream;
\r
36 import java.util.Arrays;
\r
37 import java.util.Date;
\r
38 import java.util.GregorianCalendar;
\r
39 import java.util.HashMap;
\r
40 import java.util.Iterator;
\r
41 import java.util.List;
\r
42 import java.util.Map;
\r
43 import java.util.Random;
\r
44 import java.util.Vector;
\r
45 import javax.servlet.http.Cookie;
\r
46 import javax.servlet.http.HttpServletResponse;
\r
48 import org.apache.commons.collections.ExtendedProperties;
\r
49 import mir.config.MirPropertiesConfiguration;
\r
50 import mir.entity.Entity;
\r
51 import mir.log.LoggerWrapper;
\r
52 import mir.session.Request;
\r
53 import mir.util.GeneratorFormatAdapters;
\r
54 import mir.util.StringRoutines;
\r
55 import mircoders.entity.EntityComment;
\r
56 import mircoders.entity.EntityContent;
\r
57 import mircoders.entity.EntityUsers;
\r
58 import mircoders.localizer.MirAdminInterfaceLocalizer;
\r
59 import mircoders.localizer.MirAntiAbuseFilterType;
\r
62 public class Abuse {
\r
63 private List filterRules;
\r
64 private Map filterTypes;
\r
65 private List filterTypeIds;
\r
66 private int maxIdentifier;
\r
67 private LoggerWrapper logger;
\r
68 private LoggerWrapper adminUsageLogger;
\r
69 private int logSize;
\r
70 private boolean logEnabled;
\r
71 private boolean openPostingDisabled;
\r
72 private boolean openPostingPassword;
\r
73 private boolean cookieOnBlock;
\r
74 private String articleBlockAction;
\r
75 private String commentBlockAction;
\r
77 private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");
\r
79 private MirPropertiesConfiguration configuration;
\r
81 private static String cookieName=MirGlobal.config().getString("Abuse.CookieName");
\r
82 private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge");
\r
85 logger = new LoggerWrapper("Global.Abuse");
\r
86 adminUsageLogger = new LoggerWrapper("AdminUsage");
\r
87 filterRules = new Vector();
\r
92 configuration = MirPropertiesConfiguration.instance();
\r
94 catch (Throwable e) {
\r
95 throw new RuntimeException("Can't get configuration: " + e.getMessage());
\r
100 articleBlockAction = "";
\r
101 commentBlockAction = "";
\r
102 openPostingPassword = false;
\r
103 openPostingDisabled = false;
\r
104 cookieOnBlock = false;
\r
107 filterTypes = new HashMap();
\r
108 filterTypeIds = new Vector();
\r
110 Iterator i = MirGlobal.localizer().openPostings().getAntiAbuseFilterTypes().iterator();
\r
112 while (i.hasNext()) {
\r
113 MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) i.next();
\r
114 filterTypes.put(filterType.getName(), filterType);
\r
115 filterTypeIds.add(filterType.getName());
\r
118 catch (Throwable t) {
\r
119 throw new RuntimeException("Can't get filter types: " + t.getMessage());
\r
125 private void setCookie(HttpServletResponse aResponse) {
\r
126 Random random = new Random();
\r
128 Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));
\r
129 cookie.setMaxAge(cookieMaxAge);
\r
130 cookie.setPath("/");
\r
132 if (aResponse!=null)
\r
133 aResponse.addCookie(cookie);
\r
136 private boolean checkCookie(List aCookies) {
\r
137 if (getCookieOnBlock()) {
\r
138 Iterator i = aCookies.iterator();
\r
140 while (i.hasNext()) {
\r
141 Cookie cookie = (Cookie) i.next();
\r
143 if (cookie.getName().equals(cookieName)) {
\r
144 logger.debug("cookie match");
\r
152 FilterRule findMatchingFilter(Entity anEntity, Request aRequest) {
\r
153 Iterator iterator = filterRules.iterator();
\r
155 while (iterator.hasNext()) {
\r
156 FilterRule rule = (FilterRule) iterator.next();
\r
158 if (rule.test(anEntity, aRequest))
\r
165 public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
\r
167 long time = System.currentTimeMillis();
\r
169 FilterRule filterRule = findMatchingFilter(aComment, aRequest);
\r
171 if (filterRule!=null) {
\r
172 logger.debug("Match for " + filterRule.getType()+" rule '"+ filterRule.getExpression()+"'");
\r
173 filterRule.setLastHit(new GregorianCalendar().getTime());
\r
174 MirGlobal.performCommentOperation(null, aComment, filterRule.getCommentAction());
\r
175 setCookie(aResponse);
\r
178 logger.debug("checkComment: " + (System.currentTimeMillis()-time) + "ms");
\r
180 catch (Throwable t) {
\r
181 t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
\r
182 logger.error("Abuse.checkComment: " + t.toString());
\r
186 public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {
\r
188 long time = System.currentTimeMillis();
\r
190 FilterRule filterRule = findMatchingFilter(anArticle, aRequest);
\r
192 if (filterRule!=null) {
\r
193 logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression()+"'");
\r
194 filterRule.setLastHit(new GregorianCalendar().getTime());
\r
195 MirGlobal.performArticleOperation(null, anArticle, filterRule.getArticleAction());
\r
196 setCookie(aResponse);
\r
199 logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");
\r
201 catch (Throwable t) {
\r
202 t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
\r
203 logger.error("Abuse.checkArticle: " + t.toString());
\r
207 public boolean getLogEnabled() {
\r
211 public void setLogEnabled(boolean anEnabled) {
\r
212 if (!configuration.getString("Abuse.DisallowIPLogging", "0").equals("1"))
\r
213 logEnabled = anEnabled;
\r
217 public int getLogSize() {
\r
221 public void setLogSize(int aSize) {
\r
226 public boolean getOpenPostingDisabled() {
\r
227 return openPostingDisabled;
\r
230 public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
\r
231 openPostingDisabled = anOpenPostingDisabled;
\r
234 public boolean getOpenPostingPassword() {
\r
235 return openPostingPassword;
\r
238 public void setOpenPostingPassword(boolean anOpenPostingPassword) {
\r
239 openPostingPassword = anOpenPostingPassword;
\r
242 public boolean getCookieOnBlock() {
\r
243 return cookieOnBlock;
\r
246 public void setCookieOnBlock(boolean aCookieOnBlock) {
\r
247 cookieOnBlock = aCookieOnBlock;
\r
250 public String getArticleBlockAction() {
\r
251 return articleBlockAction;
\r
254 public void setArticleBlockAction(String anAction) {
\r
255 articleBlockAction = anAction;
\r
258 public String getCommentBlockAction() {
\r
259 return commentBlockAction;
\r
262 public void setCommentBlockAction(String anAction) {
\r
263 commentBlockAction = anAction;
\r
266 public List getLog() {
\r
267 synchronized(log) {
\r
269 List result = new Vector();
\r
271 Iterator i = log.iterator();
\r
272 while (i.hasNext()) {
\r
273 LogEntry logEntry = (LogEntry) i.next();
\r
274 Map entry = new HashMap();
\r
276 entry.put("ip", logEntry.getIpNumber());
\r
277 entry.put("id", logEntry.getId());
\r
278 entry.put("timestamp", new GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
\r
279 if (logEntry.getIsArticle())
\r
280 entry.put("type", "content");
\r
282 entry.put("type", "comment");
\r
283 entry.put("browser", logEntry.getBrowserString());
\r
290 catch (Throwable t) {
\r
291 throw new RuntimeException(t.toString());
\r
296 public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {
\r
297 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));
\r
300 public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {
\r
301 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));
\r
304 public void load() {
\r
306 ExtendedProperties configuration = new ExtendedProperties();
\r
309 configuration = new ExtendedProperties(configFile);
\r
311 catch (FileNotFoundException e) {
\r
314 getFilterConfig(filterRules, "abuse.filter", configuration);
\r
316 setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
\r
317 setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
\r
318 setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
\r
319 setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
\r
320 setLogSize(configuration.getInt("abuse.logSize", 10));
\r
321 setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
\r
322 setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
\r
324 catch (Throwable t) {
\r
325 throw new RuntimeException(t.toString());
\r
328 public void save() {
\r
330 ExtendedProperties configuration = new ExtendedProperties();
\r
332 setFilterConfig(filterRules, "abuse.filter", configuration);
\r
334 configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0");
\r
335 configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0");
\r
336 configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0");
\r
337 configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0");
\r
338 configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
\r
339 configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
\r
340 configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
\r
342 configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
\r
344 catch (Throwable t) {
\r
345 throw new RuntimeException(t.toString());
\r
349 public List getFilterTypes() {
\r
351 List result = new Vector();
\r
353 Iterator i = filterTypeIds.iterator();
\r
354 while (i.hasNext()) {
\r
355 String id = (String) i.next();
\r
357 Map action = new HashMap();
\r
358 action.put("resource", id);
\r
359 action.put("identifier", id);
\r
361 result.add(action);
\r
366 catch (Throwable t) {
\r
367 throw new RuntimeException("can't get article actions");
\r
371 public List getArticleActions() {
\r
373 List result = new Vector();
\r
375 Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
\r
376 while (i.hasNext()) {
\r
377 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
\r
378 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
\r
380 Map action = new HashMap();
\r
381 action.put("resource", operation.getName());
\r
382 action.put("identifier", operation.getName());
\r
384 result.add(action);
\r
389 catch (Throwable t) {
\r
390 throw new RuntimeException("can't get article actions");
\r
394 public List getCommentActions() {
\r
396 List result = new Vector();
\r
398 Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
\r
399 while (i.hasNext()) {
\r
400 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
\r
401 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
\r
403 Map action = new HashMap();
\r
404 action.put("resource", operation.getName());
\r
405 action.put("identifier", operation.getName());
\r
407 result.add(action);
\r
412 catch (Throwable t) {
\r
413 throw new RuntimeException("can't get comment actions");
\r
417 public List getFilters() {
\r
418 List result = new Vector();
\r
420 synchronized(filterRules) {
\r
421 Iterator i = filterRules.iterator();
\r
422 while (i.hasNext()) {
\r
423 FilterRule filter = (FilterRule) i.next();
\r
424 result.add(filter.clone());
\r
430 public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
\r
431 return addFilter(filterRules, aType, anExpression, aComments, aCommentAction, anArticleAction);
\r
434 public FilterRule getFilter(String anId) {
\r
435 synchronized (filterRules) {
\r
436 FilterRule result = (FilterRule) findFilter(filterRules, anId);
\r
440 return (FilterRule) result.clone();
\r
444 public String setFilter(String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
\r
445 return setFilter(filterRules, anIdentifier, aType, anExpression, aComments, aCommentAction, anArticleAction);
\r
448 public void deleteFilter(String anIdentifier) {
\r
449 deleteFilter(filterRules, anIdentifier);
\r
452 private String addFilter(List aFilters, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
\r
453 MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
\r
456 return "invalidtype";
\r
458 if (!type.validate(anExpression)) {
\r
459 return "invalidexpression";
\r
462 FilterRule filter = new FilterRule();
\r
464 filter.setId(generateId());
\r
465 filter.setExpression(anExpression);
\r
466 filter.setType(aType);
\r
467 filter.setComments(aComments);
\r
468 filter.setArticleAction(anArticleAction);
\r
469 filter.setCommentAction(aCommentAction);
\r
471 synchronized (aFilters) {
\r
472 aFilters.add(filter);
\r
478 private String setFilter(List aFilters, String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
\r
479 MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
\r
482 return "invalidtype";
\r
484 if (!type.validate(anExpression)) {
\r
485 return "invalidexpression";
\r
488 synchronized (aFilters) {
\r
489 FilterRule filter = findFilter(aFilters, anIdentifier);
\r
491 if (filter!=null) {
\r
492 filter.setExpression(anExpression);
\r
493 filter.setType(aType);
\r
494 filter.setCommentAction(aCommentAction);
\r
495 filter.setArticleAction(anArticleAction);
\r
496 filter.setComments(aComments);
\r
503 private FilterRule findFilter(List aFilters, String anIdentifier) {
\r
504 synchronized (aFilters) {
\r
505 Iterator i = aFilters.iterator();
\r
506 while (i.hasNext()) {
\r
507 FilterRule filter = (FilterRule) i.next();
\r
509 if (filter.getId().equals(anIdentifier)) {
\r
518 private void deleteFilter(List aFilters, String anIdentifier) {
\r
519 synchronized (aFilters) {
\r
520 FilterRule filter = findFilter(aFilters, anIdentifier);
\r
522 if (filter!=null) {
\r
523 aFilters.remove(filter);
\r
528 private String generateId() {
\r
529 synchronized(this) {
\r
530 maxIdentifier = maxIdentifier+1;
\r
532 return Integer.toString(maxIdentifier);
\r
536 public class FilterRule {
\r
537 private String identifier;
\r
538 private String expression;
\r
539 private String type;
\r
540 private String comments;
\r
541 private String articleAction;
\r
542 private String commentAction;
\r
543 private Date lastHit;
\r
545 public FilterRule() {
\r
550 articleAction = articleBlockAction;
\r
551 commentAction = commentBlockAction;
\r
555 public Date getLastHit() {
\r
559 public void setLastHit(Date aDate) {
\r
563 public String getId() {
\r
567 public void setId(String anId) {
\r
571 public String getExpression() {
\r
575 public void setExpression(String anExpression) {
\r
576 expression = anExpression;
\r
579 public String getType() {
\r
583 public void setType(String aType) {
\r
587 public void setComments(String aComments) {
\r
588 comments = aComments;
\r
591 public String getComments() {
\r
595 public String getArticleAction() {
\r
596 return articleAction;
\r
599 public void setArticleAction(String anArticleAction) {
\r
600 articleAction = anArticleAction;
\r
603 public String getCommentAction() {
\r
604 return commentAction;
\r
607 public void setCommentAction(String aCommentAction) {
\r
608 commentAction = aCommentAction;
\r
611 public boolean test(Entity anEntity, Request aRequest) {
\r
612 MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) filterTypes.get(type);
\r
614 if (filterType != null)
\r
615 return filterType.test(expression, anEntity, aRequest);
\r
617 catch (Throwable t) {
\r
618 logger.error("error while testing "+type+"-filter '"+expression+"'");
\r
624 public Object clone() {
\r
625 FilterRule result = new FilterRule();
\r
626 result.setComments(getComments());
\r
627 result.setExpression(getExpression());
\r
628 result.setId(getId());
\r
629 result.setType(getType());
\r
630 result.setArticleAction(getArticleAction());
\r
631 result.setCommentAction(getCommentAction());
\r
632 result.setLastHit(getLastHit());
\r
638 private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
\r
639 synchronized(aFilters) {
\r
640 Iterator i = aFilters.iterator();
\r
642 while (i.hasNext()) {
\r
643 FilterRule filter = (FilterRule) i.next();
\r
645 String comments = StringRoutines.replaceStringCharacters(filter.getComments(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} );
\r
647 aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression()+":"+filter.getArticleAction() + ":" + filter.getCommentAction() + ":" +
\r
653 private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
\r
654 synchronized(aFilters) {
\r
657 if (aConfiguration.getStringArray(aConfigKey)!=null) {
\r
659 Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).
\r
662 while (i.hasNext()) {
\r
663 String filter = (String) i.next();
\r
664 List parts = StringRoutines.splitStringWithEscape(filter, ':', '\\');
\r
665 if (parts.size() == 2) {
\r
666 parts.add(articleBlockAction);
\r
667 parts.add(commentBlockAction);
\r
671 if (parts.size() == 5) {
\r
672 addFilter( (String) parts.get(0), (String) parts.get(1), (String) parts.get(4), (String) parts.get(3), (String) parts.get(2));
\r
679 private static class LogEntry {
\r
680 private String ipNumber;
\r
681 private String browserString;
\r
683 private Date timeStamp;
\r
684 private boolean isArticle;
\r
686 public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
\r
687 ipNumber = anIpNumber;
\r
688 browserString = aBrowserString;
\r
690 isArticle = anIsArticle;
\r
691 timeStamp=aTimeStamp;
\r
694 public String getIpNumber() {
\r
698 public String getBrowserString() {
\r
699 return browserString;
\r
702 public String getId() {
\r
706 public Date getTimeStamp() {
\r
710 public boolean getIsArticle() {
\r
715 private void truncateLog() {
\r
716 synchronized(log) {
\r
720 while (log.size()>0 && log.size()>logSize) {
\r
727 private void appendLog(LogEntry anEntry) {
\r
728 synchronized (log) {
\r
736 public void logAdminUsage(EntityUsers aUser, String aDescription) {
\r
738 String user = "unknown (" + aUser.toString() +")";
\r
740 user = aUser.getValue("login");
\r
741 adminUsageLogger.info(user + ": " + aDescription);
\r
743 catch (Throwable t) {
\r
744 logger.error("Error while logging admin usage ("+aUser.toString()+", "+aDescription+"): " +t.toString());
\r