1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.filter.firewall;
21
22 import java.net.InetSocketAddress;
23 import java.net.SocketAddress;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.Map;
27
28 import org.apache.mina.core.filterchain.IoFilter;
29 import org.apache.mina.core.filterchain.IoFilterAdapter;
30 import org.apache.mina.core.session.IoSession;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34
35
36
37
38
39
40 public class ConnectionThrottleFilter extends IoFilterAdapter {
41 private static final long DEFAULT_TIME = 1000;
42
43 private long allowedInterval;
44
45 private final Map<String, Long> clients;
46
47 private final static Logger LOGGER = LoggerFactory.getLogger(ConnectionThrottleFilter.class);
48
49
50
51 public ConnectionThrottleFilter() {
52 this(DEFAULT_TIME);
53 }
54
55
56
57
58
59
60
61
62
63 public ConnectionThrottleFilter(long allowedInterval) {
64 this.allowedInterval = allowedInterval;
65 clients = Collections.synchronizedMap(new HashMap<String, Long>());
66 }
67
68
69
70
71
72
73
74
75
76 public void setAllowedInterval(long allowedInterval) {
77 this.allowedInterval = allowedInterval;
78 }
79
80
81
82
83
84
85
86
87
88
89 protected boolean isConnectionOk(IoSession session) {
90 SocketAddress remoteAddress = session.getRemoteAddress();
91 if (remoteAddress instanceof InetSocketAddress) {
92 InetSocketAddress addr = (InetSocketAddress) remoteAddress;
93 long now = System.currentTimeMillis();
94
95 if (clients.containsKey(addr.getAddress().getHostAddress())) {
96
97 LOGGER.debug("This is not a new client");
98 Long lastConnTime = clients.get(addr.getAddress()
99 .getHostAddress());
100
101 clients.put(addr.getAddress().getHostAddress(), now);
102
103
104
105 if (now - lastConnTime < allowedInterval) {
106 LOGGER.warn("Session connection interval too short");
107 return false;
108 }
109
110 return true;
111 }
112
113 clients.put(addr.getAddress().getHostAddress(), now);
114 return true;
115 }
116
117 return false;
118 }
119
120 @Override
121 public void sessionCreated(NextFilter nextFilter, IoSession session)
122 throws Exception {
123 if (!isConnectionOk(session)) {
124 LOGGER.warn("Connections coming in too fast; closing.");
125 session.close(true);
126 }
127 nextFilter.sessionCreated(session);
128 }
129 }