1 18 package freecs.util; 19 20 import freecs.Server; 21 22 import java.util.Hashtable ; 23 import java.util.Enumeration ; 24 import java.net.InetAddress ; 25 26 27 public class TrafficMonitor extends Thread { 28 public static final TrafficMonitor tm = new TrafficMonitor(); 29 30 private Hashtable addr; 31 private long checkInterval = 10000; 32 33 private TrafficMonitor () { 34 addr = new Hashtable (); 35 } 36 37 40 public static void startTrafficMonitor () { 41 if (tm.isAlive()) 42 return; 43 tm.setName("TrafficMonitor"); 44 tm.start (); 45 } 46 47 57 public AddressState mayPass (InetAddress ia) { 58 AddressState as = (AddressState) addr.get(ia); 59 if (as == null) { 60 addr.put (ia, new AddressState ()); 61 return null; 62 } 63 as.diff = System.currentTimeMillis () - as.lastCheck; 64 if (as.diff > checkInterval) { 65 as.reqCount = 1; 66 as.lastCheck = System.currentTimeMillis (); 67 return null; 68 } 69 as.reqCount++; 70 if ((as.isProxy 71 && as.reqCount > Server.srv.MAX_REQUESTS_PER_PROXY_IP) 72 || as.reqCount > Server.srv.MAX_REQUESTS_PER_IP) { 73 return as; 74 } 75 return null; 76 } 77 78 84 public void markAsProxy (InetAddress ia) { 85 if (!Server.srv.USE_TRAFFIC_MONITOR) 86 return; 87 AddressState as; 88 as = (AddressState) addr.get(ia); 89 if (as == null) { 90 Server.log (this, "markAsProxy: AddressState is null", Server.MSG_STATE, Server.LVL_MAJOR); 91 return; 92 } 93 if (!as.isProxy) { 94 StringBuffer sb = new StringBuffer ("TrafficMonitor.markAsProxy: identified a proxy ("); 95 sb.append (ia.toString ()); 96 sb.append (")"); 97 as.isProxy = true; 98 } 99 } 100 101 105 public void run () { 106 long lastMessage=0; 107 while (Server.srv.isRunning ()) try { 108 if (Server.DEBUG || lastMessage + 5000 > System.currentTimeMillis()) { 109 Server.log (this, "loopstart", Server.MSG_STATE, Server.LVL_VERY_VERBOSE); 110 lastMessage = System.currentTimeMillis(); 111 } 112 long now = System.currentTimeMillis (); 113 long lowestValue = 60000; 114 for (Enumeration e = addr.keys (); e.hasMoreElements (); ) { 115 InetAddress tia = (InetAddress ) e.nextElement (); 116 if (tia==null) 117 continue; 118 AddressState as = (AddressState) addr.get (tia); 119 if (as==null) 120 continue; 121 long diff = now - as.lastCheck; 122 if (diff > 60000) { 123 addr.remove (tia); 124 } else if (diff < lowestValue) { 125 lowestValue=diff; 126 } 127 } 128 if (lowestValue < 33) 129 lowestValue = 33; 130 try { 131 Thread.sleep (lowestValue); 132 } catch (InterruptedException ie) {} 133 } catch (Exception e) { 134 Server.debug (this, "run:", e, Server.MSG_ERROR, Server.LVL_MAJOR); 135 } 136 } 137 138 public class AddressState { 139 volatile long lastCheck; 140 public volatile long reqCount; 141 public volatile long diff; 142 volatile boolean isProxy = false; 143 private AddressState () { 144 lastCheck = System.currentTimeMillis (); 145 reqCount = 1; 146 } 147 } 148 149 public String toString() { 150 return "[TrafficMonitor]"; 151 } 152 } | Popular Tags |