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.EntityComment;
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;
70 private boolean logEnabled;
71 private boolean openPostingDisabled;
72 private boolean openPostingPassword;
73 private boolean cookieOnBlock;
74 private String articleBlockAction;
75 private String commentBlockAction;
77 private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");
80 private static final String IP_FILTER_TYPE="ip";
81 private static final String REGEXP_FILTER_TYPE="regexp";
82 private static String cookieName=MirGlobal.config().getString("Abuse.CookieName");
83 private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge");
86 logger = new LoggerWrapper("Global.Abuse");
87 filters = new Vector();
93 articleBlockAction = "";
94 commentBlockAction = "";
95 openPostingPassword = false;
96 openPostingDisabled = false;
97 cookieOnBlock = false;
102 public boolean checkIpFilter(String anIpAddress) {
103 synchronized (filters) {
104 Iterator i = filters.iterator();
106 while (i.hasNext()) {
107 Filter filter = (Filter) i.next();
110 if ( (filter.getType().equals(IP_FILTER_TYPE)) &&
111 InternetFunctions.isIpAddressInNetwork(anIpAddress, filter.getExpression())) {
112 logger.debug("ip match on " + filter.getExpression());
116 catch (Throwable t) {
117 logger.warn("error while checking ip address " + anIpAddress + " over network " + filter.expression + ": " + t.getMessage());
125 private boolean checkRegExpFilter(Entity anEntity) {
126 synchronized (filters) {
127 Iterator i = filters.iterator();
129 while (i.hasNext()) {
130 Filter filter = (Filter) i.next();
132 if (filter.getType().equals(REGEXP_FILTER_TYPE)) {
134 RE regularExpression = new RE(filter.getExpression());
136 Iterator j = anEntity.getFields().iterator();
137 while (j.hasNext()) {
138 String field = anEntity.getValue( (String) j.next());
140 if (field != null && regularExpression.isMatch(field.toLowerCase())) {
141 logger.debug("regexp match on " + filter.getExpression());
146 catch (Throwable t) {
147 logger.warn("error while checking entity with regexp " + filter.getExpression() + ": " + t.getMessage());
156 private void setCookie(HttpServletResponse aResponse) {
157 Random random = new Random();
159 Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));
160 cookie.setMaxAge(cookieMaxAge);
164 aResponse.addCookie(cookie);
167 private boolean checkCookie(List aCookies) {
168 if (getCookieOnBlock()) {
169 Iterator i = aCookies.iterator();
171 while (i.hasNext()) {
172 Cookie cookie = (Cookie) i.next();
174 if (cookie.getName().equals(cookieName)) {
175 logger.debug("cookie match");
184 public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
186 long time = System.currentTimeMillis();
187 String address = "0.0.0.0";
188 String browser = "unknown";
189 Cookie[] cookies = {};
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 = request.getCookies();
205 logComment(address, aComment.getId(), new Date(), browser);
207 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);
209 if (checkCookie(Arrays.asList(cookies)) || checkIpFilter(address) || checkRegExpFilter(aComment)) {
210 operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));
211 setCookie(aResponse);
214 logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms");
216 catch (Throwable t) {
217 logger.error("Abuse.checkComment: " + t.toString());
221 public void checkArticle(EntityContent anArticle, HttpServletRequest aRequest, HttpServletResponse aResponse) {
223 long time = System.currentTimeMillis();
225 logArticle(aRequest.getRemoteAddr(), anArticle.getId(), new Date(), (String) aRequest.getHeader("User-Agent"));
227 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);
229 if (checkCookie(Arrays.asList(aRequest.getCookies())) || checkIpFilter(aRequest.getRemoteAddr()) || checkRegExpFilter(anArticle)) {
230 operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));
231 setCookie(aResponse);
234 logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");
236 catch (Throwable t) {
237 logger.error("Abuse.checkArticle: " + t.toString());
241 public boolean getLogEnabled() {
245 public void setLogEnabled(boolean anEnabled) {
246 logEnabled = anEnabled;
250 public int getLogSize() {
254 public void setLogSize(int aSize) {
259 public boolean getOpenPostingDisabled() {
260 return openPostingDisabled;
263 public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
264 openPostingDisabled = anOpenPostingDisabled;
267 public boolean getOpenPostingPassword() {
268 return openPostingPassword;
271 public void setOpenPostingPassword(boolean anOpenPostingPassword) {
272 openPostingPassword = anOpenPostingPassword;
275 public boolean getCookieOnBlock() {
276 return cookieOnBlock;
279 public void setCookieOnBlock(boolean aCookieOnBlock) {
280 cookieOnBlock = aCookieOnBlock;
283 public String getArticleBlockAction() {
284 return articleBlockAction;
287 public void setArticleBlockAction(String anAction) {
288 articleBlockAction = anAction;
291 public String getCommentBlockAction() {
292 return commentBlockAction;
295 public void setCommentBlockAction(String anAction) {
296 commentBlockAction = anAction;
300 public List getLog() {
302 List result = new Vector();
304 Iterator i = log.iterator();
305 while (i.hasNext()) {
306 LogEntry logEntry = (LogEntry) i.next();
307 Map entry = new HashMap();
309 entry.put("ip", logEntry.getIpNumber());
310 entry.put("id", logEntry.getId());
311 entry.put("timestamp", new DateToMapAdapter(logEntry.getTimeStamp()));
312 if (logEntry.getIsArticle())
313 entry.put("type", "content");
315 entry.put("type", "comment");
316 entry.put("browser", logEntry.getBrowserString());
325 public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {
326 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));
329 public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {
330 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));
335 ExtendedProperties configuration = new ExtendedProperties();
338 configuration = new ExtendedProperties(configFile);
340 catch (FileNotFoundException e) {
343 getFilterConfig(filters, "abuse.filter", configuration);
345 setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
346 setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
347 setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
348 setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
349 setLogSize(configuration.getInt("abuse.logSize", 10));
350 setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
351 setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
353 catch (Throwable t) {
354 throw new RuntimeException(t.toString());
359 ExtendedProperties configuration = new ExtendedProperties();
361 setFilterConfig(filters, "abuse.filter", configuration);
363 configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0");
364 configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0");
365 configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0");
366 configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0");
367 configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
368 configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
369 configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
371 configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
373 catch (Throwable t) {
374 throw new RuntimeException(t.toString());
378 public List getFilterTypes() {
379 List result = new Vector();
381 Map entry = new HashMap();
382 entry.put("resource", "ip");
383 entry.put("id", IP_FILTER_TYPE);
386 entry = new HashMap();
387 entry.put("resource", "regexp");
388 entry.put("id", REGEXP_FILTER_TYPE);
394 public List getArticleActions() {
396 List result = new Vector();
398 Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
399 while (i.hasNext()) {
400 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
401 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
403 Map action = new HashMap();
404 action.put("resource", operation.getName());
405 action.put("identifier", operation.getName());
412 catch (Throwable t) {
413 throw new RuntimeException("can't get article actions");
417 public List getCommentActions() {
419 List result = new Vector();
421 Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
422 while (i.hasNext()) {
423 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
424 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
426 Map action = new HashMap();
427 action.put("resource", operation.getName());
428 action.put("identifier", operation.getName());
435 catch (Throwable t) {
436 throw new RuntimeException("can't get comment actions");
440 public List getFilters() {
441 return getFiltersAsMaps(filters);
444 public void addFilter(String aType, String anExpression) {
445 addFilter(filters, aType, anExpression);
448 public void setFilter(String anIdentifier, String aType, String anExpression) {
449 setFilter(filters, anIdentifier, aType, anExpression);
452 public void deleteFilter(String anIdentifier) {
453 deleteFilter(filters, anIdentifier);
456 public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception {
459 private List getFiltersAsMaps(List aFilters) {
460 synchronized(aFilters) {
461 List result = new Vector();
463 Iterator i = aFilters.iterator();
464 while (i.hasNext()) {
465 Filter filter = (Filter) i.next();
466 Map map = new HashMap();
468 map.put("id", filter.getId());
469 map.put("expression", filter.getExpression());
470 map.put("type", filter.getType());
478 private void addFilter(List aFilters, String aType, String anExpression) {
479 Filter filter = new Filter();
481 filter.setId(generateId());
482 filter.setExpression(anExpression);
483 filter.setType(aType);
485 synchronized (aFilters) {
486 aFilters.add(filter);
490 private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) {
491 synchronized (aFilters) {
492 Filter filter = findFilter(aFilters, anIdentifier);
495 filter.setExpression(anExpression);
496 filter.setType(aType);
501 private Filter findFilter(List aFilters, String anIdentifier) {
502 synchronized (aFilters) {
503 Iterator i = aFilters.iterator();
504 while (i.hasNext()) {
505 Filter filter = (Filter) i.next();
507 if (filter.getId().equals(anIdentifier)) {
516 private void deleteFilter(List aFilters, String anIdentifier) {
517 synchronized (aFilters) {
518 Filter filter = findFilter(aFilters, anIdentifier);
521 aFilters.remove(filter);
526 private String generateId() {
528 maxIdentifier = maxIdentifier+1;
530 return Integer.toString(maxIdentifier);
534 private static class Filter {
535 private String identifier;
536 private String expression;
545 public String getId() {
549 public void setId(String anId) {
553 public String getExpression() {
557 public void setExpression(String anExpression) {
558 expression = anExpression;
561 public String getType() {
565 public void setType(String aType) {
570 private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
571 synchronized(aFilters) {
572 Iterator i = aFilters.iterator();
574 while (i.hasNext()) {
575 Filter filter = (Filter) i.next();
577 aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression());
582 private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
583 synchronized(aFilters) {
586 Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator();
588 while (i.hasNext()) {
589 String filter = (String) i.next();
590 List parts = StringRoutines.separateString(filter, ":");
592 if (parts.size()==2) {
593 addFilter( (String) parts.get(0), (String) parts.get(1));
599 private static class LogEntry {
600 private String ipNumber;
601 private String browserString;
603 private Date timeStamp;
604 private boolean isArticle;
606 public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
607 ipNumber = anIpNumber;
608 browserString = aBrowserString;
610 isArticle = anIsArticle;
611 timeStamp=aTimeStamp;
614 public String getIpNumber() {
618 public String getBrowserString() {
619 return browserString;
622 public String getId() {
626 public Date getTimeStamp() {
630 public boolean getIsArticle() {
635 private void truncateLog() {
640 while (log.size()>0 && log.size()>logSize) {
647 private void appendLog(LogEntry anEntry) {