reg exp replace now available in templates
[mir.git] / source / mircoders / global / Abuse.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
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.
10  *
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.
15  *
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
19  *
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.
29  */
30
31 package mircoders.global;
32
33 import gnu.regexp.RE;
34
35 import java.io.File;
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;
43 import java.util.Map;
44 import java.util.Random;
45 import java.util.Vector;
46
47 import javax.servlet.http.Cookie;
48 import javax.servlet.http.HttpServletRequest;
49 import javax.servlet.http.HttpServletResponse;
50
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;
61
62 import org.apache.commons.collections.ExtendedProperties;
63
64
65 public class Abuse {
66   private List filters;
67   private int maxIdentifier;
68   private LoggerWrapper logger;
69   private LoggerWrapper adminUsageLogger;
70   private int logSize;
71   private boolean logEnabled;
72   private boolean openPostingDisabled;
73   private boolean openPostingPassword;
74   private boolean cookieOnBlock;
75   private String articleBlockAction;
76   private String commentBlockAction;
77   private List log;
78   private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");
79
80
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");
85
86   public Abuse() {
87     logger = new LoggerWrapper("Global.Abuse");
88     adminUsageLogger = new LoggerWrapper("AdminUsage");
89     filters = new Vector();
90     maxIdentifier = 0;
91     log = new Vector();
92
93     logSize = 100;
94     logEnabled = false;
95     articleBlockAction = "";
96     commentBlockAction = "";
97     openPostingPassword = false;
98     openPostingDisabled = false;
99     cookieOnBlock = false;
100
101     load();
102   }
103
104   public boolean checkIpFilter(String anIpAddress) {
105     synchronized (filters) {
106       Iterator i = filters.iterator();
107
108       while (i.hasNext()) {
109         Filter filter = (Filter) i.next();
110
111         try {
112           if ( (filter.getType().equals(IP_FILTER_TYPE)) &&
113               InternetFunctions.isIpAddressInNetwork(anIpAddress, filter.getExpression())) {
114             logger.debug("ip match on " + filter.getExpression());
115             return true;
116           }
117         }
118         catch (Throwable t) {
119           logger.warn("error while checking ip address " + anIpAddress + " over network " + filter.expression + ": " + t.getMessage());
120         }
121       }
122
123       return false;
124     }
125   }
126
127   private boolean checkRegExpFilter(Entity anEntity) {
128     synchronized (filters) {
129       Iterator i = filters.iterator();
130
131       while (i.hasNext()) {
132         Filter filter = (Filter) i.next();
133
134         if (filter.getType().equals(REGEXP_FILTER_TYPE)) {
135           try {
136             RE regularExpression = new RE(filter.getExpression(), RE.REG_ICASE);
137
138             Iterator j = anEntity.getFields().iterator();
139             while (j.hasNext()) {
140               String field = anEntity.getValue( (String) j.next());
141
142               if (field != null && regularExpression.isMatch(field.toLowerCase())) {
143                 logger.debug("regexp match on " + filter.getExpression());
144                 return true;
145               }
146             }
147           }
148           catch (Throwable t) {
149             logger.warn("error while checking entity with regexp " + filter.getExpression() + ": " + t.getMessage());
150           }
151         }
152       }
153
154       return false;
155     }
156   }
157
158   private void setCookie(HttpServletResponse aResponse) {
159     Random random = new Random();
160
161     Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));
162     cookie.setMaxAge(cookieMaxAge);
163     cookie.setPath("/");
164
165     if (aResponse!=null)
166       aResponse.addCookie(cookie);
167   }
168
169   private boolean checkCookie(List aCookies) {
170     if (getCookieOnBlock()) {
171       Iterator i = aCookies.iterator();
172
173       while (i.hasNext()) {
174         Cookie cookie = (Cookie) i.next();
175
176         if (cookie.getName().equals(cookieName)) {
177           logger.debug("cookie match");
178           return true;
179         }
180       }
181     }
182
183     return false;
184   }
185
186   public boolean checkRequest(Request aRequest, HttpServletResponse aResponse, String anId, boolean anIsComment) {
187     String address = "0.0.0.0";
188     String browser = "unknown";
189     List cookies = null;
190
191     HttpServletRequest request = null;
192
193     if (aRequest instanceof HTTPAdapters.HTTPParsedRequestAdapter) {
194       request = ((HTTPAdapters.HTTPParsedRequestAdapter) aRequest).getRequest();
195     }
196     else if (aRequest instanceof HTTPAdapters.HTTPRequestAdapter) {
197       request = ((HTTPAdapters.HTTPRequestAdapter) aRequest).getRequest();
198     }
199     if (request!=null) {
200       browser = (String) request.getHeader("User-Agent");
201       address = request.getRemoteAddr();
202       cookies = Arrays.asList(request.getCookies());
203     }
204
205     if (anIsComment)
206       logComment(address, anId , new Date(), browser);
207     else
208       logArticle(address, anId , new Date(), browser);
209
210     return checkCookie(cookies) || checkIpFilter(address);
211   }
212
213   public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
214     try {
215       long time = System.currentTimeMillis();
216
217       MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);
218
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);
223       }
224
225       logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms");
226     }
227     catch (Throwable t) {
228       t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
229       logger.error("Abuse.checkComment: " + t.toString());
230     }
231   }
232
233   public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {
234     try {
235       long time = System.currentTimeMillis();
236
237       MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleArticleOperationForName(articleBlockAction);
238
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);
243       }
244
245       logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");
246     }
247     catch (Throwable t) {
248       t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
249       logger.error("Abuse.checkArticle: " + t.toString());
250     }
251   }
252
253   public boolean getLogEnabled() {
254     return logEnabled;
255   }
256
257   public void setLogEnabled(boolean anEnabled) {
258     logEnabled = anEnabled;
259     truncateLog();
260   }
261
262   public int getLogSize() {
263     return logSize;
264   }
265
266   public void setLogSize(int aSize) {
267     logSize = aSize;
268     truncateLog();
269   }
270
271   public boolean getOpenPostingDisabled() {
272     return openPostingDisabled;
273   }
274
275   public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
276     openPostingDisabled = anOpenPostingDisabled;
277   }
278
279   public boolean getOpenPostingPassword() {
280     return openPostingPassword;
281   }
282
283   public void setOpenPostingPassword(boolean anOpenPostingPassword) {
284     openPostingPassword = anOpenPostingPassword;
285   }
286
287   public boolean getCookieOnBlock() {
288     return cookieOnBlock;
289   }
290
291   public void setCookieOnBlock(boolean aCookieOnBlock) {
292     cookieOnBlock = aCookieOnBlock;
293   }
294
295   public String getArticleBlockAction() {
296     return articleBlockAction;
297   }
298
299   public void setArticleBlockAction(String anAction) {
300     articleBlockAction = anAction;
301   }
302
303   public String getCommentBlockAction() {
304     return commentBlockAction;
305   }
306
307   public void setCommentBlockAction(String anAction) {
308     commentBlockAction = anAction;
309   }
310
311
312   public List getLog() {
313     synchronized(log) {
314       List result = new Vector();
315
316       Iterator i = log.iterator();
317       while (i.hasNext()) {
318         LogEntry logEntry = (LogEntry) i.next();
319         Map entry = new HashMap();
320
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");
326         else
327           entry.put("type", "comment");
328         entry.put("browser", logEntry.getBrowserString());
329
330         result.add(entry);
331       }
332
333       return result;
334     }
335   }
336
337   public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {
338     appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));
339   }
340
341   public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {
342     appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));
343   }
344
345   public void load() {
346     try {
347       ExtendedProperties configuration = new ExtendedProperties();
348
349       try {
350         configuration = new ExtendedProperties(configFile);
351       }
352       catch (FileNotFoundException e) {
353       }
354
355       getFilterConfig(filters, "abuse.filter", configuration);
356
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", ""));
364     }
365     catch (Throwable t) {
366       throw new RuntimeException(t.toString());
367     }
368   }
369   public void save() {
370     try {
371       ExtendedProperties configuration = new ExtendedProperties();
372
373       setFilterConfig(filters, "abuse.filter", configuration);
374
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());
382
383       configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
384     }
385     catch (Throwable t) {
386       throw new RuntimeException(t.toString());
387     }
388   }
389
390   public List getFilterTypes() {
391     List result = new Vector();
392
393     Map entry = new HashMap();
394     entry.put("resource", "ip");
395     entry.put("id", IP_FILTER_TYPE);
396     result.add(entry);
397
398     entry = new HashMap();
399     entry.put("resource", "regexp");
400     entry.put("id", REGEXP_FILTER_TYPE);
401     result.add(entry);
402
403     return result;
404   }
405
406   public List getArticleActions() {
407     try {
408       List result = new Vector();
409
410       Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
411       while (i.hasNext()) {
412         MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
413             (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
414
415         Map action = new HashMap();
416         action.put("resource", operation.getName());
417         action.put("identifier", operation.getName());
418
419         result.add(action);
420       }
421
422       return result;
423     }
424     catch (Throwable t) {
425       throw new RuntimeException("can't get article actions");
426     }
427   }
428
429   public List getCommentActions() {
430     try {
431       List result = new Vector();
432
433       Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
434       while (i.hasNext()) {
435         MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
436             (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
437
438         Map action = new HashMap();
439         action.put("resource", operation.getName());
440         action.put("identifier", operation.getName());
441
442         result.add(action);
443       }
444
445       return result;
446     }
447     catch (Throwable t) {
448       throw new RuntimeException("can't get comment actions");
449     }
450   }
451
452   public List getFilters() {
453     return getFiltersAsMaps(filters);
454   }
455
456   public void addFilter(String aType, String anExpression) {
457     addFilter(filters, aType, anExpression);
458   }
459
460   public void setFilter(String anIdentifier, String aType, String anExpression) {
461     setFilter(filters, anIdentifier, aType, anExpression);
462   }
463
464   public void deleteFilter(String anIdentifier) {
465     deleteFilter(filters, anIdentifier);
466   }
467
468   public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception {
469   }
470
471   private List getFiltersAsMaps(List aFilters) {
472     synchronized(aFilters) {
473       List result = new Vector();
474
475       Iterator i = aFilters.iterator();
476       while (i.hasNext()) {
477         Filter filter = (Filter) i.next();
478         Map map = new HashMap();
479
480         map.put("id", filter.getId());
481         map.put("expression", filter.getExpression());
482         map.put("type", filter.getType());
483
484         result.add(map);
485       }
486       return result;
487     }
488   }
489
490   private void addFilter(List aFilters, String aType, String anExpression) {
491     Filter filter = new Filter();
492
493     filter.setId(generateId());
494     filter.setExpression(anExpression);
495     filter.setType(aType);
496
497     synchronized (aFilters) {
498       aFilters.add(filter);
499     }
500   }
501
502   private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) {
503     synchronized (aFilters) {
504       Filter filter = findFilter(aFilters, anIdentifier);
505
506       if (filter!=null) {
507         filter.setExpression(anExpression);
508         filter.setType(aType);
509       }
510     }
511   }
512
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();
518
519         if (filter.getId().equals(anIdentifier)) {
520           return filter;
521         }
522       }
523     }
524
525     return null;
526   }
527
528   private void deleteFilter(List aFilters, String anIdentifier) {
529     synchronized (aFilters) {
530       Filter filter = findFilter(aFilters, anIdentifier);
531
532       if (filter!=null) {
533         aFilters.remove(filter);
534       }
535     }
536   }
537
538   private String generateId() {
539     synchronized(this) {
540       maxIdentifier = maxIdentifier+1;
541
542       return Integer.toString(maxIdentifier);
543     }
544   }
545
546   private static class Filter {
547     private String identifier;
548     private String expression;
549     private String type;
550
551     public Filter() {
552       expression="";
553       type="";
554       identifier="";
555     }
556
557     public String getId() {
558       return identifier;
559     }
560
561     public void setId(String anId) {
562       identifier = anId;
563     }
564
565     public String getExpression() {
566       return expression;
567     }
568
569     public void setExpression(String anExpression) {
570       expression = anExpression;
571     }
572
573     public String getType() {
574       return type;
575     }
576
577     public void setType(String aType) {
578       type = aType;
579     }
580   }
581
582   private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
583     synchronized(aFilters) {
584       Iterator i = aFilters.iterator();
585
586       while (i.hasNext()) {
587         Filter filter = (Filter) i.next();
588
589         aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression());
590       }
591     }
592   }
593
594   private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
595     synchronized(aFilters) {
596       aFilters.clear();
597
598       Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator();
599
600       while (i.hasNext()) {
601         String filter = (String) i.next();
602         List parts = StringRoutines.separateString(filter, ":");
603
604         if (parts.size()==2) {
605           addFilter( (String) parts.get(0), (String) parts.get(1));
606         }
607       }
608     }
609   }
610
611   private static class LogEntry {
612     private String ipNumber;
613     private String browserString;
614     private String id;
615     private Date timeStamp;
616     private boolean isArticle;
617
618     public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
619       ipNumber = anIpNumber;
620       browserString = aBrowserString;
621       id = anId;
622       isArticle = anIsArticle;
623       timeStamp=aTimeStamp;
624     }
625
626     public String getIpNumber() {
627       return ipNumber;
628     }
629
630     public String getBrowserString() {
631       return browserString;
632     }
633
634     public String getId() {
635       return id;
636     }
637
638     public Date getTimeStamp() {
639       return timeStamp;
640     }
641
642     public boolean getIsArticle() {
643       return isArticle;
644     }
645   }
646
647   private void truncateLog() {
648     synchronized(log) {
649       if (!logEnabled)
650         log.clear();
651       else {
652         while (log.size()>0 && log.size()>logSize) {
653           log.remove(0);
654         }
655       }
656     }
657   };
658
659   private void appendLog(LogEntry anEntry) {
660     synchronized (log) {
661       if (logEnabled) {
662         log.add(anEntry);
663         truncateLog();
664       }
665     }
666   }
667
668   public void logAdminUsage(EntityUsers aUser, String aDescription) {
669     try {
670       String user = "unknown (" + aUser.toString() +")";
671       if (user!=null)
672         user = aUser.getValue("login");
673       adminUsageLogger.info(user + ": " + aDescription);
674     }
675     catch (Throwable t) {
676       logger.error("Error while logging admin usage ("+aUser.toString()+", "+aDescription+"): " +t.toString());
677     }
678   }
679 }