2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
6 * Mir is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * Mir is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Mir; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * In addition, as a special exception, The Mir-coders gives permission to link
21 * the code of this program with any library licensed under the Apache Software License,
22 * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23 * (or with modified versions of the above that use the same license as the above),
24 * and distribute linked combinations including the two. You must obey the
25 * GNU General Public License in all respects for all of the code used other than
26 * the above mentioned libraries. If you modify this file, you may extend this
27 * exception to your version of the file, but you are not obligated to do so.
28 * If you do not wish to do so, delete this exception statement from your version.
31 package mircoders.global;
34 import java.io.FileNotFoundException;
35 import java.io.FileOutputStream;
36 import java.util.Arrays;
37 import java.util.Date;
38 import java.util.HashMap;
39 import java.util.Iterator;
40 import java.util.List;
42 import java.util.Random;
43 import java.util.Vector;
44 import javax.servlet.http.Cookie;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
48 import org.apache.commons.collections.ExtendedProperties;
51 import mir.config.MirPropertiesConfiguration;
52 import mir.entity.Entity;
53 import mir.log.LoggerWrapper;
54 import mir.session.HTTPAdapters;
55 import mir.session.Request;
56 import mir.util.GeneratorFormatAdapters;
57 import mir.util.InternetFunctions;
58 import mir.util.StringRoutines;
59 import mircoders.entity.EntityComment;
60 import mircoders.entity.EntityContent;
61 import mircoders.entity.EntityUsers;
62 import mircoders.localizer.MirAdminInterfaceLocalizer;
67 private int maxIdentifier;
68 private LoggerWrapper logger;
69 private LoggerWrapper adminUsageLogger;
71 private boolean logEnabled;
72 private boolean openPostingDisabled;
73 private boolean openPostingPassword;
74 private boolean cookieOnBlock;
75 private String articleBlockAction;
76 private String commentBlockAction;
78 private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");
81 private static final String IP_FILTER_TYPE="ip";
82 private static final String REGEXP_FILTER_TYPE="regexp";
83 private static String cookieName=MirGlobal.config().getString("Abuse.CookieName");
84 private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge");
87 logger = new LoggerWrapper("Global.Abuse");
88 adminUsageLogger = new LoggerWrapper("AdminUsage");
89 filters = new Vector();
95 articleBlockAction = "";
96 commentBlockAction = "";
97 openPostingPassword = false;
98 openPostingDisabled = false;
99 cookieOnBlock = false;
104 public boolean checkIpFilter(String anIpAddress) {
105 synchronized (filters) {
106 Iterator i = filters.iterator();
108 while (i.hasNext()) {
109 Filter filter = (Filter) i.next();
112 if ( (filter.getType().equals(IP_FILTER_TYPE)) &&
113 InternetFunctions.isIpAddressInNetwork(anIpAddress, filter.getExpression())) {
114 logger.debug("ip match on " + filter.getExpression());
118 catch (Throwable t) {
119 logger.warn("error while checking ip address " + anIpAddress + " over network " + filter.expression + ": " + t.getMessage());
127 private boolean checkRegExpFilter(Entity anEntity) {
128 synchronized (filters) {
129 Iterator i = filters.iterator();
131 while (i.hasNext()) {
132 Filter filter = (Filter) i.next();
134 if (filter.getType().equals(REGEXP_FILTER_TYPE)) {
136 RE regularExpression = new RE(filter.getExpression(), RE.REG_ICASE);
138 Iterator j = anEntity.getFields().iterator();
139 while (j.hasNext()) {
140 String field = anEntity.getValue( (String) j.next());
142 if (field != null && regularExpression.isMatch(field.toLowerCase())) {
143 logger.debug("regexp match on " + filter.getExpression());
148 catch (Throwable t) {
149 logger.warn("error while checking entity with regexp " + filter.getExpression() + ": " + t.getMessage());
158 private void setCookie(HttpServletResponse aResponse) {
159 Random random = new Random();
161 Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));
162 cookie.setMaxAge(cookieMaxAge);
166 aResponse.addCookie(cookie);
169 private boolean checkCookie(List aCookies) {
170 if (getCookieOnBlock()) {
171 Iterator i = aCookies.iterator();
173 while (i.hasNext()) {
174 Cookie cookie = (Cookie) i.next();
176 if (cookie.getName().equals(cookieName)) {
177 logger.debug("cookie match");
186 public boolean checkRequest(Request aRequest, HttpServletResponse aResponse, String anId, boolean anIsComment) {
187 String address = "0.0.0.0";
188 String browser = "unknown";
191 HttpServletRequest request = null;
193 if (aRequest instanceof HTTPAdapters.HTTPParsedRequestAdapter) {
194 request = ((HTTPAdapters.HTTPParsedRequestAdapter) aRequest).getRequest();
196 else if (aRequest instanceof HTTPAdapters.HTTPRequestAdapter) {
197 request = ((HTTPAdapters.HTTPRequestAdapter) aRequest).getRequest();
200 browser = (String) request.getHeader("User-Agent");
201 address = request.getRemoteAddr();
202 cookies = Arrays.asList(request.getCookies());
206 logComment(address, anId , new Date(), browser);
208 logArticle(address, anId , new Date(), browser);
210 return checkCookie(cookies) || checkIpFilter(address);
213 public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
215 long time = System.currentTimeMillis();
217 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);
219 if (checkRequest(aRequest, aResponse, aComment.getId(), true) || checkRegExpFilter(aComment)) {
220 logger.debug("performing operation " + operation.getName());
221 operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));
222 setCookie(aResponse);
225 logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms");
227 catch (Throwable t) {
228 t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
229 logger.error("Abuse.checkComment: " + t.toString());
233 public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {
235 long time = System.currentTimeMillis();
237 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleArticleOperationForName(articleBlockAction);
239 if (checkRequest(aRequest, aResponse, anArticle.getId(), false) || checkRegExpFilter(anArticle)) {
240 logger.debug("performing operation " + operation.getName());
241 operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));
242 setCookie(aResponse);
245 logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");
247 catch (Throwable t) {
248 t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
249 logger.error("Abuse.checkArticle: " + t.toString());
253 public boolean getLogEnabled() {
257 public void setLogEnabled(boolean anEnabled) {
258 logEnabled = anEnabled;
262 public int getLogSize() {
266 public void setLogSize(int aSize) {
271 public boolean getOpenPostingDisabled() {
272 return openPostingDisabled;
275 public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
276 openPostingDisabled = anOpenPostingDisabled;
279 public boolean getOpenPostingPassword() {
280 return openPostingPassword;
283 public void setOpenPostingPassword(boolean anOpenPostingPassword) {
284 openPostingPassword = anOpenPostingPassword;
287 public boolean getCookieOnBlock() {
288 return cookieOnBlock;
291 public void setCookieOnBlock(boolean aCookieOnBlock) {
292 cookieOnBlock = aCookieOnBlock;
295 public String getArticleBlockAction() {
296 return articleBlockAction;
299 public void setArticleBlockAction(String anAction) {
300 articleBlockAction = anAction;
303 public String getCommentBlockAction() {
304 return commentBlockAction;
307 public void setCommentBlockAction(String anAction) {
308 commentBlockAction = anAction;
312 public List getLog() {
315 List result = new Vector();
317 Iterator i = log.iterator();
318 while (i.hasNext()) {
319 LogEntry logEntry = (LogEntry) i.next();
320 Map entry = new HashMap();
322 entry.put("ip", logEntry.getIpNumber());
323 entry.put("id", logEntry.getId());
324 entry.put("timestamp", new GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
325 if (logEntry.getIsArticle())
326 entry.put("type", "content");
328 entry.put("type", "comment");
329 entry.put("browser", logEntry.getBrowserString());
336 catch (Throwable t) {
337 throw new RuntimeException(t.toString());
342 public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {
343 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));
346 public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {
347 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));
352 ExtendedProperties configuration = new ExtendedProperties();
355 configuration = new ExtendedProperties(configFile);
357 catch (FileNotFoundException e) {
360 getFilterConfig(filters, "abuse.filter", configuration);
362 setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
363 setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
364 setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
365 setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
366 setLogSize(configuration.getInt("abuse.logSize", 10));
367 setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
368 setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
370 catch (Throwable t) {
371 throw new RuntimeException(t.toString());
376 ExtendedProperties configuration = new ExtendedProperties();
378 setFilterConfig(filters, "abuse.filter", configuration);
380 configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0");
381 configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0");
382 configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0");
383 configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0");
384 configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
385 configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
386 configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
388 configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
390 catch (Throwable t) {
391 throw new RuntimeException(t.toString());
395 public List getFilterTypes() {
396 List result = new Vector();
398 Map entry = new HashMap();
399 entry.put("resource", "ip");
400 entry.put("id", IP_FILTER_TYPE);
403 entry = new HashMap();
404 entry.put("resource", "regexp");
405 entry.put("id", REGEXP_FILTER_TYPE);
411 public List getArticleActions() {
413 List result = new Vector();
415 Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
416 while (i.hasNext()) {
417 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
418 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
420 Map action = new HashMap();
421 action.put("resource", operation.getName());
422 action.put("identifier", operation.getName());
429 catch (Throwable t) {
430 throw new RuntimeException("can't get article actions");
434 public List getCommentActions() {
436 List result = new Vector();
438 Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
439 while (i.hasNext()) {
440 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
441 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
443 Map action = new HashMap();
444 action.put("resource", operation.getName());
445 action.put("identifier", operation.getName());
452 catch (Throwable t) {
453 throw new RuntimeException("can't get comment actions");
457 public List getFilters() {
458 return getFiltersAsMaps(filters);
461 public void addFilter(String aType, String anExpression) {
462 addFilter(filters, aType, anExpression);
465 public void setFilter(String anIdentifier, String aType, String anExpression) {
466 setFilter(filters, anIdentifier, aType, anExpression);
469 public void deleteFilter(String anIdentifier) {
470 deleteFilter(filters, anIdentifier);
473 public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception {
476 private List getFiltersAsMaps(List aFilters) {
477 synchronized(aFilters) {
478 List result = new Vector();
480 Iterator i = aFilters.iterator();
481 while (i.hasNext()) {
482 Filter filter = (Filter) i.next();
483 Map map = new HashMap();
485 map.put("id", filter.getId());
486 map.put("expression", filter.getExpression());
487 map.put("type", filter.getType());
495 private void addFilter(List aFilters, String aType, String anExpression) {
496 Filter filter = new Filter();
498 filter.setId(generateId());
499 filter.setExpression(anExpression);
500 filter.setType(aType);
502 synchronized (aFilters) {
503 aFilters.add(filter);
507 private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) {
508 synchronized (aFilters) {
509 Filter filter = findFilter(aFilters, anIdentifier);
512 filter.setExpression(anExpression);
513 filter.setType(aType);
518 private Filter findFilter(List aFilters, String anIdentifier) {
519 synchronized (aFilters) {
520 Iterator i = aFilters.iterator();
521 while (i.hasNext()) {
522 Filter filter = (Filter) i.next();
524 if (filter.getId().equals(anIdentifier)) {
533 private void deleteFilter(List aFilters, String anIdentifier) {
534 synchronized (aFilters) {
535 Filter filter = findFilter(aFilters, anIdentifier);
538 aFilters.remove(filter);
543 private String generateId() {
545 maxIdentifier = maxIdentifier+1;
547 return Integer.toString(maxIdentifier);
551 private static class Filter {
552 private String identifier;
553 private String expression;
562 public String getId() {
566 public void setId(String anId) {
570 public String getExpression() {
574 public void setExpression(String anExpression) {
575 expression = anExpression;
578 public String getType() {
582 public void setType(String aType) {
587 private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
588 synchronized(aFilters) {
589 Iterator i = aFilters.iterator();
591 while (i.hasNext()) {
592 Filter filter = (Filter) i.next();
594 aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression());
599 private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
600 synchronized(aFilters) {
603 Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator();
605 while (i.hasNext()) {
606 String filter = (String) i.next();
607 List parts = StringRoutines.separateString(filter, ":");
609 if (parts.size()==2) {
610 addFilter( (String) parts.get(0), (String) parts.get(1));
616 private static class LogEntry {
617 private String ipNumber;
618 private String browserString;
620 private Date timeStamp;
621 private boolean isArticle;
623 public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
624 ipNumber = anIpNumber;
625 browserString = aBrowserString;
627 isArticle = anIsArticle;
628 timeStamp=aTimeStamp;
631 public String getIpNumber() {
635 public String getBrowserString() {
636 return browserString;
639 public String getId() {
643 public Date getTimeStamp() {
647 public boolean getIsArticle() {
652 private void truncateLog() {
657 while (log.size()>0 && log.size()>logSize) {
664 private void appendLog(LogEntry anEntry) {
673 public void logAdminUsage(EntityUsers aUser, String aDescription) {
675 String user = "unknown (" + aUser.toString() +")";
677 user = aUser.getValue("login");
678 adminUsageLogger.info(user + ": " + aDescription);
680 catch (Throwable t) {
681 logger.error("Error while logging admin usage ("+aUser.toString()+", "+aDescription+"): " +t.toString());