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 the com.oreilly.servlet library, any library
\r
22 * licensed under the Apache Software License, The Sun (tm) Java Advanced
\r
23 * Imaging library (JAI), The Sun JIMI library (or with modified versions of
\r
24 * the above that use the same license as the above), and distribute linked
\r
25 * combinations including the two. You must obey the GNU General Public
\r
26 * License in all respects for all of the code used other than the above
\r
27 * mentioned libraries. If you modify this file, you may extend this exception
\r
28 * to your version of the file, but you are not obligated to do so. If you do
\r
29 * not wish to do so, delete this exception statement from your version.
\r
32 package mircoders.global;
\r
34 import java.io.File;
\r
35 import java.io.FileNotFoundException;
\r
36 import java.io.FileOutputStream;
\r
37 import java.util.Arrays;
\r
38 import java.util.Date;
\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.HttpServletRequest;
\r
47 import javax.servlet.http.HttpServletResponse;
\r
49 import org.apache.commons.collections.ExtendedProperties;
\r
51 import gnu.regexp.RE;
\r
53 import mir.entity.Entity;
\r
54 import mir.log.LoggerWrapper;
\r
55 import mir.util.DateToMapAdapter;
\r
56 import mir.util.InternetFunctions;
\r
57 import mir.util.StringRoutines;
\r
58 import mir.session.*;
\r
59 import mircoders.entity.EntityComment;
\r
60 import mircoders.entity.EntityContent;
\r
61 import mircoders.localizer.MirAdminInterfaceLocalizer;
\r
64 public class Abuse {
\r
65 private List filters;
\r
66 private int maxIdentifier;
\r
67 private LoggerWrapper logger;
\r
68 private int logSize;
\r
69 private boolean logEnabled;
\r
70 private boolean openPostingDisabled;
\r
71 private boolean openPostingPassword;
\r
72 private boolean cookieOnBlock;
\r
73 private String articleBlockAction;
\r
74 private String commentBlockAction;
\r
76 private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");
\r
79 private static final String IP_FILTER_TYPE="ip";
\r
80 private static final String REGEXP_FILTER_TYPE="regexp";
\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 filters = new Vector();
\r
92 articleBlockAction = "";
\r
93 commentBlockAction = "";
\r
94 openPostingPassword = false;
\r
95 openPostingDisabled = false;
\r
96 cookieOnBlock = false;
\r
101 public boolean checkIpFilter(String anIpAddress) {
\r
102 synchronized (filters) {
\r
103 Iterator i = filters.iterator();
\r
105 while (i.hasNext()) {
\r
106 Filter filter = (Filter) i.next();
\r
109 if ( (filter.getType().equals(IP_FILTER_TYPE)) &&
\r
110 InternetFunctions.isIpAddressInNetwork(anIpAddress, filter.getExpression())) {
\r
111 logger.debug("ip match on " + filter.getExpression());
\r
115 catch (Throwable t) {
\r
116 logger.warn("error while checking ip address " + anIpAddress + " over network " + filter.expression + ": " + t.getMessage());
\r
124 private boolean checkRegExpFilter(Entity anEntity) {
\r
125 synchronized (filters) {
\r
126 Iterator i = filters.iterator();
\r
128 while (i.hasNext()) {
\r
129 Filter filter = (Filter) i.next();
\r
131 if (filter.getType().equals(REGEXP_FILTER_TYPE)) {
\r
133 RE regularExpression = new RE(filter.getExpression());
\r
135 Iterator j = anEntity.getFields().iterator();
\r
136 while (j.hasNext()) {
\r
137 String field = anEntity.getValue( (String) j.next());
\r
139 if (field != null && regularExpression.isMatch(field.toLowerCase())) {
\r
140 logger.debug("regexp match on " + filter.getExpression());
\r
145 catch (Throwable t) {
\r
146 logger.warn("error while checking entity with regexp " + filter.getExpression() + ": " + t.getMessage());
\r
155 private void setCookie(HttpServletResponse aResponse) {
\r
156 Random random = new Random();
\r
158 Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));
\r
159 cookie.setMaxAge(cookieMaxAge);
\r
160 cookie.setPath("/");
\r
162 if (aResponse!=null)
\r
163 aResponse.addCookie(cookie);
\r
166 private boolean checkCookie(List aCookies) {
\r
167 if (getCookieOnBlock()) {
\r
168 Iterator i = aCookies.iterator();
\r
170 while (i.hasNext()) {
\r
171 Cookie cookie = (Cookie) i.next();
\r
173 if (cookie.getName().equals(cookieName)) {
\r
174 logger.debug("cookie match");
\r
183 public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
\r
185 long time = System.currentTimeMillis();
\r
186 String address = "0.0.0.0";
\r
187 String browser = "unknown";
\r
188 Cookie[] cookies = {};
\r
190 HttpServletRequest request = null;
\r
192 if (aRequest instanceof HTTPAdapters.HTTPParsedRequestAdapter) {
\r
193 request = ((HTTPAdapters.HTTPParsedRequestAdapter) aRequest).getRequest();
\r
195 else if (aRequest instanceof HTTPAdapters.HTTPRequestAdapter) {
\r
196 request = ((HTTPAdapters.HTTPRequestAdapter) aRequest).getRequest();
\r
198 if (request!=null) {
\r
199 browser = (String) request.getHeader("User-Agent");
\r
200 address = request.getRemoteAddr();
\r
201 cookies = request.getCookies();
\r
204 logComment(address, aComment.getId(), new Date(), browser);
\r
206 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);
\r
208 if (checkCookie(Arrays.asList(cookies)) || checkIpFilter(address) || checkRegExpFilter(aComment)) {
\r
209 operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));
\r
210 setCookie(aResponse);
\r
213 logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms");
\r
215 catch (Throwable t) {
\r
216 logger.error("Abuse.checkComment: " + t.toString());
\r
220 public void checkArticle(EntityContent anArticle, HttpServletRequest aRequest, HttpServletResponse aResponse) {
\r
222 long time = System.currentTimeMillis();
\r
224 logArticle(aRequest.getRemoteAddr(), anArticle.getId(), new Date(), (String) aRequest.getHeader("User-Agent"));
\r
226 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);
\r
228 if (checkCookie(Arrays.asList(aRequest.getCookies())) || checkIpFilter(aRequest.getRemoteAddr()) || checkRegExpFilter(anArticle)) {
\r
229 operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));
\r
230 setCookie(aResponse);
\r
233 logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");
\r
235 catch (Throwable t) {
\r
236 logger.error("Abuse.checkArticle: " + t.toString());
\r
240 public boolean getLogEnabled() {
\r
244 public void setLogEnabled(boolean anEnabled) {
\r
245 logEnabled = anEnabled;
\r
249 public int getLogSize() {
\r
253 public void setLogSize(int aSize) {
\r
258 public boolean getOpenPostingDisabled() {
\r
259 return openPostingDisabled;
\r
262 public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
\r
263 openPostingDisabled = anOpenPostingDisabled;
\r
266 public boolean getOpenPostingPassword() {
\r
267 return openPostingPassword;
\r
270 public void setOpenPostingPassword(boolean anOpenPostingPassword) {
\r
271 openPostingPassword = anOpenPostingPassword;
\r
274 public boolean getCookieOnBlock() {
\r
275 return cookieOnBlock;
\r
278 public void setCookieOnBlock(boolean aCookieOnBlock) {
\r
279 cookieOnBlock = aCookieOnBlock;
\r
282 public String getArticleBlockAction() {
\r
283 return articleBlockAction;
\r
286 public void setArticleBlockAction(String anAction) {
\r
287 articleBlockAction = anAction;
\r
290 public String getCommentBlockAction() {
\r
291 return commentBlockAction;
\r
294 public void setCommentBlockAction(String anAction) {
\r
295 commentBlockAction = anAction;
\r
299 public List getLog() {
\r
300 synchronized(log) {
\r
301 List result = new Vector();
\r
303 Iterator i = log.iterator();
\r
304 while (i.hasNext()) {
\r
305 LogEntry logEntry = (LogEntry) i.next();
\r
306 Map entry = new HashMap();
\r
308 entry.put("ip", logEntry.getIpNumber());
\r
309 entry.put("id", logEntry.getId());
\r
310 entry.put("timestamp", new DateToMapAdapter(logEntry.getTimeStamp()));
\r
311 if (logEntry.getIsArticle())
\r
312 entry.put("type", "content");
\r
314 entry.put("type", "comment");
\r
315 entry.put("browser", logEntry.getBrowserString());
\r
324 public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {
\r
325 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));
\r
328 public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {
\r
329 appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));
\r
332 public void load() {
\r
334 ExtendedProperties configuration = new ExtendedProperties();
\r
337 configuration = new ExtendedProperties(configFile);
\r
339 catch (FileNotFoundException e) {
\r
342 getFilterConfig(filters, "abuse.filter", configuration);
\r
344 setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
\r
345 setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
\r
346 setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
\r
347 setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
\r
348 setLogSize(configuration.getInt("abuse.logSize", 10));
\r
349 setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
\r
350 setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
\r
352 catch (Throwable t) {
\r
353 throw new RuntimeException(t.toString());
\r
356 public void save() {
\r
358 ExtendedProperties configuration = new ExtendedProperties();
\r
360 setFilterConfig(filters, "abuse.filter", configuration);
\r
362 configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0");
\r
363 configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0");
\r
364 configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0");
\r
365 configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0");
\r
366 configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
\r
367 configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
\r
368 configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
\r
370 configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
\r
372 catch (Throwable t) {
\r
373 throw new RuntimeException(t.toString());
\r
377 public List getFilterTypes() {
\r
378 List result = new Vector();
\r
380 Map entry = new HashMap();
\r
381 entry.put("resource", "ip");
\r
382 entry.put("id", IP_FILTER_TYPE);
\r
385 entry = new HashMap();
\r
386 entry.put("resource", "regexp");
\r
387 entry.put("id", REGEXP_FILTER_TYPE);
\r
393 public List getArticleActions() {
\r
395 List result = new Vector();
\r
397 Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
\r
398 while (i.hasNext()) {
\r
399 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
\r
400 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
\r
402 Map action = new HashMap();
\r
403 action.put("resource", operation.getName());
\r
404 action.put("identifier", operation.getName());
\r
406 result.add(action);
\r
411 catch (Throwable t) {
\r
412 throw new RuntimeException("can't get article actions");
\r
416 public List getCommentActions() {
\r
418 List result = new Vector();
\r
420 Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
\r
421 while (i.hasNext()) {
\r
422 MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
\r
423 (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
\r
425 Map action = new HashMap();
\r
426 action.put("resource", operation.getName());
\r
427 action.put("identifier", operation.getName());
\r
429 result.add(action);
\r
434 catch (Throwable t) {
\r
435 throw new RuntimeException("can't get comment actions");
\r
439 public List getFilters() {
\r
440 return getFiltersAsMaps(filters);
\r
443 public void addFilter(String aType, String anExpression) {
\r
444 addFilter(filters, aType, anExpression);
\r
447 public void setFilter(String anIdentifier, String aType, String anExpression) {
\r
448 setFilter(filters, anIdentifier, aType, anExpression);
\r
451 public void deleteFilter(String anIdentifier) {
\r
452 deleteFilter(filters, anIdentifier);
\r
455 public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception {
\r
458 private List getFiltersAsMaps(List aFilters) {
\r
459 synchronized(aFilters) {
\r
460 List result = new Vector();
\r
462 Iterator i = aFilters.iterator();
\r
463 while (i.hasNext()) {
\r
464 Filter filter = (Filter) i.next();
\r
465 Map map = new HashMap();
\r
467 map.put("id", filter.getId());
\r
468 map.put("expression", filter.getExpression());
\r
469 map.put("type", filter.getType());
\r
477 private void addFilter(List aFilters, String aType, String anExpression) {
\r
478 Filter filter = new Filter();
\r
480 filter.setId(generateId());
\r
481 filter.setExpression(anExpression);
\r
482 filter.setType(aType);
\r
484 synchronized (aFilters) {
\r
485 aFilters.add(filter);
\r
489 private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) {
\r
490 synchronized (aFilters) {
\r
491 Filter filter = findFilter(aFilters, anIdentifier);
\r
493 if (filter!=null) {
\r
494 filter.setExpression(anExpression);
\r
495 filter.setType(aType);
\r
500 private Filter findFilter(List aFilters, String anIdentifier) {
\r
501 synchronized (aFilters) {
\r
502 Iterator i = aFilters.iterator();
\r
503 while (i.hasNext()) {
\r
504 Filter filter = (Filter) i.next();
\r
506 if (filter.getId().equals(anIdentifier)) {
\r
515 private void deleteFilter(List aFilters, String anIdentifier) {
\r
516 synchronized (aFilters) {
\r
517 Filter filter = findFilter(aFilters, anIdentifier);
\r
519 if (filter!=null) {
\r
520 aFilters.remove(filter);
\r
525 private String generateId() {
\r
526 synchronized(this) {
\r
527 maxIdentifier = maxIdentifier+1;
\r
529 return Integer.toString(maxIdentifier);
\r
533 private static class Filter {
\r
534 private String identifier;
\r
535 private String expression;
\r
536 private String type;
\r
544 public String getId() {
\r
548 public void setId(String anId) {
\r
552 public String getExpression() {
\r
556 public void setExpression(String anExpression) {
\r
557 expression = anExpression;
\r
560 public String getType() {
\r
564 public void setType(String aType) {
\r
569 private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
\r
570 synchronized(aFilters) {
\r
571 Iterator i = aFilters.iterator();
\r
573 while (i.hasNext()) {
\r
574 Filter filter = (Filter) i.next();
\r
576 aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression());
\r
581 private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
\r
582 synchronized(aFilters) {
\r
585 Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator();
\r
587 while (i.hasNext()) {
\r
588 String filter = (String) i.next();
\r
589 List parts = StringRoutines.separateString(filter, ":");
\r
591 if (parts.size()==2) {
\r
592 addFilter( (String) parts.get(0), (String) parts.get(1));
\r
598 private static class LogEntry {
\r
599 private String ipNumber;
\r
600 private String browserString;
\r
602 private Date timeStamp;
\r
603 private boolean isArticle;
\r
605 public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
\r
606 ipNumber = anIpNumber;
\r
607 browserString = aBrowserString;
\r
609 isArticle = anIsArticle;
\r
610 timeStamp=aTimeStamp;
\r
613 public String getIpNumber() {
\r
617 public String getBrowserString() {
\r
618 return browserString;
\r
621 public String getId() {
\r
625 public Date getTimeStamp() {
\r
629 public boolean getIsArticle() {
\r
634 private void truncateLog() {
\r
635 synchronized(log) {
\r
639 while (log.size()>0 && log.size()>logSize) {
\r
646 private void appendLog(LogEntry anEntry) {
\r
647 synchronized (log) {
\r