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
41 public class ConnectionThrottleFilter extends IoFilterAdapter {
42 private static final long DEFAULT_TIME = 1000;
43
44 private long allowedInterval;
45
46 private final Map<String, Long> clients;
47
48 private final Logger logger = LoggerFactory.getLogger(getClass());
49
50
51
52 public ConnectionThrottleFilter() {
53 this(DEFAULT_TIME);
54 }
55
56
57
58
59
60
61
62
63
64 public ConnectionThrottleFilter(long allowedInterval) {
65 this.allowedInterval = allowedInterval;
66 clients = Collections.synchronizedMap(new HashMap<String, Long>());
67 }
68
69
70
71
72
73
74
75
76
77 public void setAllowedInterval(long allowedInterval) {
78 this.allowedInterval = allowedInterval;
79 }
80
81
82
83
84
85
86
87
88
89
90 protected boolean isConnectionOk(IoSession session) {
91 SocketAddress remoteAddress = session.getRemoteAddress();
92 if (remoteAddress instanceof InetSocketAddress) {
93 InetSocketAddress addr = (InetSocketAddress) remoteAddress;
94 long now = System.currentTimeMillis();
95
96 if (clients.containsKey(addr.getAddress().getHostAddress())) {
97
98 logger.debug("This is not a new client");
99 Long lastConnTime = clients.get(addr.getAddress()
100 .getHostAddress());
101
102 clients.put(addr.getAddress().getHostAddress(), now);
103
104
105
106 if (now - lastConnTime < allowedInterval) {
107 logger.warn("Session connection interval too short");
108 return false;
109 } else {
110 return true;
111 }
112 } else {
113 clients.put(addr.getAddress().getHostAddress(), now);
114 return true;
115 }
116 }
117
118 return false;
119 }
120
121 @Override
122 public void sessionCreated(NextFilter nextFilter, IoSession session)
123 throws Exception {
124 if (!isConnectionOk(session)) {
125 logger.warn("Connections coming in too fast; closing.");
126 session.close();
127 }
128 nextFilter.sessionCreated(session);
129 }
130 }