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;
36 import java.io.FileNotFoundException;
37 import java.io.FileOutputStream;
38 import java.util.Arrays;
39 import java.util.Date;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
44 import java.util.Random;
45 import java.util.Vector;
47 import javax.servlet.http.Cookie;
48 import javax.servlet.http.HttpServletRequest;
49 import javax.servlet.http.HttpServletResponse;
51 import mir.entity.Entity;
52 import mir.log.LoggerWrapper;
53 import mir.session.HTTPAdapters;
54 import mir.session.Request;
55 import mir.util.DateToMapAdapter;
56 import mir.util.InternetFunctions;
57 import mir.util.StringRoutines;
58 import mircoders.entity.*;
59 import mircoders.entity.EntityContent;
60 import mircoders.localizer.MirAdminInterfaceLocalizer;
62 import org.apache.commons.collections.ExtendedProperties;
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() {
314 List result = new Vector();
316 Iterator i = log.iterator();
317 while (i.hasNext()) {
318 LogEntry logEntry = (LogEntry) i.next();
319 Map entry = new HashMap();
321 entry.put("ip", logEntry.getIpNumber());
322 entry.put("id", logEntry.getId());
323 entry.put("timestamp", new DateToMapAdapter(logEntry.getTimeStamp()));
324 if (logEntry.getIsArticle())
325 entry.put("type", "content");
327 entry.put("type", "comment");
328 entry.put("browser", logEntry.getBrowserString());
337 public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {
338 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));
341 public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {
342 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));
347 ExtendedProperties configuration = new ExtendedProperties();
350 configuration = new ExtendedProperties(configFile);
352 catch (FileNotFoundException e) {
355 getFilterConfig(filters, "abuse.filter", configuration);
357 setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
358 setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
359 setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
360 setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
361 setLogSize(configuration.getInt("abuse.logSize", 10));
362 setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
363 setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
365 catch (Throwable t) {
366 throw new RuntimeException(t.toString());
371 ExtendedProperties configuration = new ExtendedProperties();
373 setFilterConfig(filters, "abuse.filter", configuration);
375 configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0");
376 configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0");
377 configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0");
378 configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0");
379 configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
380 configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
381 configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
383 configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
385 catch (Throwable t) {
386 throw new RuntimeException(t.toString());
390 public List getFilterTypes() {
391 List result = new Vector();
393 Map entry = new HashMap();
394 entry.put("resource", "ip");
395 entry.put("id", IP_FILTER_TYPE);
398 entry = new HashMap();
399 entry.put("resource", "regexp");
400 entry.put("id", REGEXP_FILTER_TYPE);
406 public List getArticleActions() {
408 List result = new Vector();
410 Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
411 while (i.hasNext()) {
412 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
413 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
415 Map action = new HashMap();
416 action.put("resource", operation.getName());
417 action.put("identifier", operation.getName());
424 catch (Throwable t) {
425 throw new RuntimeException("can't get article actions");
429 public List getCommentActions() {
431 List result = new Vector();
433 Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
434 while (i.hasNext()) {
435 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
436 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
438 Map action = new HashMap();
439 action.put("resource", operation.getName());
440 action.put("identifier", operation.getName());
447 catch (Throwable t) {
448 throw new RuntimeException("can't get comment actions");
452 public List getFilters() {
453 return getFiltersAsMaps(filters);
456 public void addFilter(String aType, String anExpression) {
457 addFilter(filters, aType, anExpression);
460 public void setFilter(String anIdentifier, String aType, String anExpression) {
461 setFilter(filters, anIdentifier, aType, anExpression);
464 public void deleteFilter(String anIdentifier) {
465 deleteFilter(filters, anIdentifier);
468 public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception {
471 private List getFiltersAsMaps(List aFilters) {
472 synchronized(aFilters) {
473 List result = new Vector();
475 Iterator i = aFilters.iterator();
476 while (i.hasNext()) {
477 Filter filter = (Filter) i.next();
478 Map map = new HashMap();
480 map.put("id", filter.getId());
481 map.put("expression", filter.getExpression());
482 map.put("type", filter.getType());
490 private void addFilter(List aFilters, String aType, String anExpression) {
491 Filter filter = new Filter();
493 filter.setId(generateId());
494 filter.setExpression(anExpression);
495 filter.setType(aType);
497 synchronized (aFilters) {
498 aFilters.add(filter);
502 private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) {
503 synchronized (aFilters) {
504 Filter filter = findFilter(aFilters, anIdentifier);
507 filter.setExpression(anExpression);
508 filter.setType(aType);
513 private Filter findFilter(List aFilters, String anIdentifier) {
514 synchronized (aFilters) {
515 Iterator i = aFilters.iterator();
516 while (i.hasNext()) {
517 Filter filter = (Filter) i.next();
519 if (filter.getId().equals(anIdentifier)) {
528 private void deleteFilter(List aFilters, String anIdentifier) {
529 synchronized (aFilters) {
530 Filter filter = findFilter(aFilters, anIdentifier);
533 aFilters.remove(filter);
538 private String generateId() {
540 maxIdentifier = maxIdentifier+1;
542 return Integer.toString(maxIdentifier);
546 private static class Filter {
547 private String identifier;
548 private String expression;
557 public String getId() {
561 public void setId(String anId) {
565 public String getExpression() {
569 public void setExpression(String anExpression) {
570 expression = anExpression;
573 public String getType() {
577 public void setType(String aType) {
582 private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
583 synchronized(aFilters) {
584 Iterator i = aFilters.iterator();
586 while (i.hasNext()) {
587 Filter filter = (Filter) i.next();
589 aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression());
594 private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
595 synchronized(aFilters) {
598 Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator();
600 while (i.hasNext()) {
601 String filter = (String) i.next();
602 List parts = StringRoutines.separateString(filter, ":");
604 if (parts.size()==2) {
605 addFilter( (String) parts.get(0), (String) parts.get(1));
611 private static class LogEntry {
612 private String ipNumber;
613 private String browserString;
615 private Date timeStamp;
616 private boolean isArticle;
618 public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
619 ipNumber = anIpNumber;
620 browserString = aBrowserString;
622 isArticle = anIsArticle;
623 timeStamp=aTimeStamp;
626 public String getIpNumber() {
630 public String getBrowserString() {
631 return browserString;
634 public String getId() {
638 public Date getTimeStamp() {
642 public boolean getIsArticle() {
647 private void truncateLog() {
652 while (log.size()>0 && log.size()>logSize) {
659 private void appendLog(LogEntry anEntry) {
668 public void logAdminUsage(EntityUsers aUser, String aDescription) {
670 String user = "unknown (" + aUser.toString() +")";
672 user = aUser.getValue("login");
673 adminUsageLogger.info(user + ": " + aDescription);
675 catch (Throwable t) {
676 logger.error("Error while logging admin usage ("+aUser.toString()+", "+aDescription+"): " +t.toString());