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
153 FilterRule findMatchingFilter(Entity anEntity, Request aRequest) {
\r
154 Iterator iterator = filterRules.iterator();
\r
156 while (iterator.hasNext()) {
\r
157 FilterRule rule = (FilterRule) iterator.next();
\r
159 if (rule.test(anEntity, aRequest))
\r
166 public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
\r
167 logComment(aComment, aRequest);
\r
170 long time = System.currentTimeMillis();
\r
172 FilterRule filterRule = findMatchingFilter(aComment, aRequest);
\r
174 if (filterRule!=null) {
\r
175 logger.debug("Match for " + filterRule.getType()+" rule '"+ filterRule.getExpression()+"'");
\r
176 filterRule.setLastHit(new GregorianCalendar().getTime());
\r
177 MirGlobal.performCommentOperation(null, aComment, filterRule.getCommentAction());
\r
178 setCookie(aResponse);
\r
181 logger.debug("checkComment: " + (System.currentTimeMillis()-time) + "ms");
\r
183 catch (Throwable t) {
\r
184 t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
\r
185 logger.error("Abuse.checkComment: " + t.toString());
\r
189 public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {
\r
190 logArticle(anArticle, aRequest);
\r
193 long time = System.currentTimeMillis();
\r
195 FilterRule filterRule = findMatchingFilter(anArticle, aRequest);
\r
197 if (filterRule!=null) {
\r
198 logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression()+"'");
\r
199 filterRule.setLastHit(new GregorianCalendar().getTime());
\r
200 MirGlobal.performArticleOperation(null, anArticle, filterRule.getArticleAction());
\r
201 setCookie(aResponse);
\r
204 logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");
\r
206 catch (Throwable t) {
\r
207 t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
\r
208 logger.error("Abuse.checkArticle: " + t.toString());
\r
212 public boolean getLogEnabled() {
\r
216 public void setLogEnabled(boolean anEnabled) {
\r
217 if (!configuration.getString("Abuse.DisallowIPLogging", "0").equals("1"))
\r
218 logEnabled = anEnabled;
\r
222 public int getLogSize() {
\r
226 public void setLogSize(int aSize) {
\r
231 public boolean getOpenPostingDisabled() {
\r
232 return openPostingDisabled;
\r
235 public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
\r
236 openPostingDisabled = anOpenPostingDisabled;
\r
239 public boolean getOpenPostingPassword() {
\r
240 return openPostingPassword;
\r
243 public void setOpenPostingPassword(boolean anOpenPostingPassword) {
\r
244 openPostingPassword = anOpenPostingPassword;
\r
247 public boolean getCookieOnBlock() {
\r
248 return cookieOnBlock;
\r
251 public void setCookieOnBlock(boolean aCookieOnBlock) {
\r
252 cookieOnBlock = aCookieOnBlock;
\r
255 public String getArticleBlockAction() {
\r
256 return articleBlockAction;
\r
259 public void setArticleBlockAction(String anAction) {
\r
260 articleBlockAction = anAction;
\r
263 public String getCommentBlockAction() {
\r
264 return commentBlockAction;
\r
267 public void setCommentBlockAction(String anAction) {
\r
268 commentBlockAction = anAction;
\r
271 public List getLog() {
\r
272 synchronized(log) {
\r
274 List result = new Vector();
\r
276 Iterator i = log.iterator();
\r
277 while (i.hasNext()) {
\r
278 LogEntry logEntry = (LogEntry) i.next();
\r
279 Map entry = new HashMap();
\r
281 entry.put("ip", logEntry.getIpNumber());
\r
282 entry.put("id", logEntry.getId());
\r
283 entry.put("timestamp", new GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
\r
284 if (logEntry.getIsArticle())
\r
285 entry.put("type", "content");
\r
287 entry.put("type", "comment");
\r
288 entry.put("browser", logEntry.getBrowserString());
\r
295 catch (Throwable t) {
\r
296 throw new RuntimeException(t.toString());
\r
301 public void logComment(Entity aComment, Request aRequest) {
\r
302 String ipAddress = aRequest.getHeader("ip");
\r
303 String id = aComment.getId();
\r
304 String browser = aRequest.getHeader("User-Agent");
\r
306 logComment(ipAddress, id, new Date(), browser);
\r
309 public void logArticle(Entity anArticle, Request aRequest) {
\r
310 String ipAddress = aRequest.getHeader("ip");
\r
311 String id = anArticle.getId();
\r
312 String browser = aRequest.getHeader("User-Agent");
\r
314 logArticle(ipAddress, id, new Date(), browser);
\r
317 public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {
\r
318 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));
\r
321 public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {
\r
322 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));
\r
325 public void load() {
\r
327 ExtendedProperties configuration = new ExtendedProperties();
\r
330 configuration = new ExtendedProperties(configFile);
\r
332 catch (FileNotFoundException e) {
\r
335 getFilterConfig(filterRules, "abuse.filter", configuration);
\r
337 setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
\r
338 setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
\r
339 setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
\r
340 setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
\r
341 setLogSize(configuration.getInt("abuse.logSize", 10));
\r
342 setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
\r
343 setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
\r
345 catch (Throwable t) {
\r
346 throw new RuntimeException(t.toString());
\r
349 public void save() {
\r
351 ExtendedProperties configuration = new ExtendedProperties();
\r
353 setFilterConfig(filterRules, "abuse.filter", configuration);
\r
355 configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0");
\r
356 configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0");
\r
357 configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0");
\r
358 configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0");
\r
359 configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
\r
360 configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
\r
361 configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
\r
363 configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
\r
365 catch (Throwable t) {
\r
366 throw new RuntimeException(t.toString());
\r
370 public List getFilterTypes() {
\r
372 List result = new Vector();
\r
374 Iterator i = filterTypeIds.iterator();
\r
375 while (i.hasNext()) {
\r
376 String id = (String) i.next();
\r
378 Map action = new HashMap();
\r
379 action.put("resource", id);
\r
380 action.put("identifier", id);
\r
382 result.add(action);
\r
387 catch (Throwable t) {
\r
388 throw new RuntimeException("can't get article actions");
\r
392 public List getArticleActions() {
\r
394 List result = new Vector();
\r
396 Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
\r
397 while (i.hasNext()) {
\r
398 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
\r
399 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
\r
401 Map action = new HashMap();
\r
402 action.put("resource", operation.getName());
\r
403 action.put("identifier", operation.getName());
\r
405 result.add(action);
\r
410 catch (Throwable t) {
\r
411 throw new RuntimeException("can't get article actions");
\r
415 public List getCommentActions() {
\r
417 List result = new Vector();
\r
419 Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
\r
420 while (i.hasNext()) {
\r
421 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
\r
422 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
\r
424 Map action = new HashMap();
\r
425 action.put("resource", operation.getName());
\r
426 action.put("identifier", operation.getName());
\r
428 result.add(action);
\r
433 catch (Throwable t) {
\r
434 throw new RuntimeException("can't get comment actions");
\r
438 public List getFilters() {
\r
439 List result = new Vector();
\r
441 synchronized(filterRules) {
\r
442 Iterator i = filterRules.iterator();
\r
443 while (i.hasNext()) {
\r
444 FilterRule filter = (FilterRule) i.next();
\r
445 result.add(filter.clone());
\r
451 public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
\r
452 return addFilter(filterRules, aType, anExpression, aComments, aCommentAction, anArticleAction);
\r
455 public FilterRule getFilter(String anId) {
\r
456 synchronized (filterRules) {
\r
457 FilterRule result = (FilterRule) findFilter(filterRules, anId);
\r
461 return (FilterRule) result.clone();
\r
465 public String setFilter(String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
\r
466 return setFilter(filterRules, anIdentifier, aType, anExpression, aComments, aCommentAction, anArticleAction);
\r
469 public void deleteFilter(String anIdentifier) {
\r
470 deleteFilter(filterRules, anIdentifier);
\r
473 private String addFilter(List aFilters, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
\r
474 MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
\r
477 return "invalidtype";
\r
479 if (!type.validate(anExpression)) {
\r
480 return "invalidexpression";
\r
483 FilterRule filter = new FilterRule();
\r
485 filter.setId(generateId());
\r
486 filter.setExpression(anExpression);
\r
487 filter.setType(aType);
\r
488 filter.setComments(aComments);
\r
489 filter.setArticleAction(anArticleAction);
\r
490 filter.setCommentAction(aCommentAction);
\r
492 synchronized (aFilters) {
\r
493 aFilters.add(filter);
\r
499 private String setFilter(List aFilters, String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {
\r
500 MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);
\r
503 return "invalidtype";
\r
505 if (!type.validate(anExpression)) {
\r
506 return "invalidexpression";
\r
509 synchronized (aFilters) {
\r
510 FilterRule filter = findFilter(aFilters, anIdentifier);
\r
512 if (filter!=null) {
\r
513 filter.setExpression(anExpression);
\r
514 filter.setType(aType);
\r
515 filter.setCommentAction(aCommentAction);
\r
516 filter.setArticleAction(anArticleAction);
\r
517 filter.setComments(aComments);
\r
524 private FilterRule findFilter(List aFilters, String anIdentifier) {
\r
525 synchronized (aFilters) {
\r
526 Iterator i = aFilters.iterator();
\r
527 while (i.hasNext()) {
\r
528 FilterRule filter = (FilterRule) i.next();
\r
530 if (filter.getId().equals(anIdentifier)) {
\r
539 private void deleteFilter(List aFilters, String anIdentifier) {
\r
540 synchronized (aFilters) {
\r
541 FilterRule filter = findFilter(aFilters, anIdentifier);
\r
543 if (filter!=null) {
\r
544 aFilters.remove(filter);
\r
549 private String generateId() {
\r
550 synchronized(this) {
\r
551 maxIdentifier = maxIdentifier+1;
\r
553 return Integer.toString(maxIdentifier);
\r
557 public class FilterRule {
\r
558 private String identifier;
\r
559 private String expression;
\r
560 private String type;
\r
561 private String comments;
\r
562 private String articleAction;
\r
563 private String commentAction;
\r
564 private Date lastHit;
\r
566 public FilterRule() {
\r
571 articleAction = articleBlockAction;
\r
572 commentAction = commentBlockAction;
\r
576 public Date getLastHit() {
\r
580 public void setLastHit(Date aDate) {
\r
584 public String getId() {
\r
588 public void setId(String anId) {
\r
592 public String getExpression() {
\r
596 public void setExpression(String anExpression) {
\r
597 expression = anExpression;
\r
600 public String getType() {
\r
604 public void setType(String aType) {
\r
608 public void setComments(String aComments) {
\r
609 comments = aComments;
\r
612 public String getComments() {
\r
616 public String getArticleAction() {
\r
617 return articleAction;
\r
620 public void setArticleAction(String anArticleAction) {
\r
621 articleAction = anArticleAction;
\r
624 public String getCommentAction() {
\r
625 return commentAction;
\r
628 public void setCommentAction(String aCommentAction) {
\r
629 commentAction = aCommentAction;
\r
632 public boolean test(Entity anEntity, Request aRequest) {
\r
633 MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) filterTypes.get(type);
\r
635 if (filterType != null)
\r
636 return filterType.test(expression, anEntity, aRequest);
\r
638 catch (Throwable t) {
\r
639 logger.error("error while testing "+type+"-filter '"+expression+"'");
\r
645 public Object clone() {
\r
646 FilterRule result = new FilterRule();
\r
647 result.setComments(getComments());
\r
648 result.setExpression(getExpression());
\r
649 result.setId(getId());
\r
650 result.setType(getType());
\r
651 result.setArticleAction(getArticleAction());
\r
652 result.setCommentAction(getCommentAction());
\r
653 result.setLastHit(getLastHit());
\r
659 private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
\r
660 synchronized(aFilters) {
\r
661 Iterator i = aFilters.iterator();
\r
663 while (i.hasNext()) {
\r
664 FilterRule filter = (FilterRule) i.next();
\r
666 String comments = StringRoutines.replaceStringCharacters(filter.getComments(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} );
\r
668 aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression()+":"+filter.getArticleAction() + ":" + filter.getCommentAction() + ":" +
\r
674 private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
\r
675 synchronized(aFilters) {
\r
678 if (aConfiguration.getStringArray(aConfigKey)!=null) {
\r
680 Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).
\r
683 while (i.hasNext()) {
\r
684 String filter = (String) i.next();
\r
685 List parts = StringRoutines.splitStringWithEscape(filter, ':', '\\');
\r
686 if (parts.size() == 2) {
\r
687 parts.add(articleBlockAction);
\r
688 parts.add(commentBlockAction);
\r
692 if (parts.size() == 5) {
\r
693 addFilter( (String) parts.get(0), (String) parts.get(1), (String) parts.get(4), (String) parts.get(3), (String) parts.get(2));
\r
700 private static class LogEntry {
\r
701 private String ipNumber;
\r
702 private String browserString;
\r
704 private Date timeStamp;
\r
705 private boolean isArticle;
\r
707 public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
\r
708 ipNumber = anIpNumber;
\r
709 browserString = aBrowserString;
\r
711 isArticle = anIsArticle;
\r
712 timeStamp=aTimeStamp;
\r
715 public String getIpNumber() {
\r
719 public String getBrowserString() {
\r
720 return browserString;
\r
723 public String getId() {
\r
727 public Date getTimeStamp() {
\r
731 public boolean getIsArticle() {
\r
736 private void truncateLog() {
\r
737 synchronized(log) {
\r
741 while (log.size()>0 && log.size()>logSize) {
\r
748 private void appendLog(LogEntry anEntry) {
\r
749 synchronized (log) {
\r
757 public void logAdminUsage(EntityUsers aUser, String aDescription) {
\r
759 String user = "unknown (" + aUser.toString() +")";
\r
761 user = aUser.getValue("login");
\r
762 adminUsageLogger.info(user + ": " + aDescription);
\r
764 catch (Throwable t) {
\r
765 logger.error("Error while logging admin usage ("+aUser.toString()+", "+aDescription+"): " +t.toString());
\r