LocationManager.java

Index Score
freenet.node
Freenet

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
JAVA0034JAVA0034 Missing braces in if statement
EXEC_COMMENTSComments in executable code
CYCLOMATICCyclomatic complexity
OPERATORSNumber of operators
LOGICAL_LINESNumber of statements
PROGRAM_LENGTHHalstead program length
SIZESize of the file in bytes
OPERANDSNumber of operands
LINE_COMMENTNumber of line comments
LOOPSNumber of loops
ELOCEffective lines of code
UNIQUE_OPERANDSNumber of unique operands
BLOCKSNumber of blocks
LOCLines of code
PROGRAM_VOCABHalstead program vocabulary
COMPARISONSNumber of comparison operators
EXITSProcedure exits
LINESNumber of lines in the source file
INTERFACE_COMPLEXITYInterface complexity
RETURNSNumber of return points from functions
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
PARAMSNumber of formal parameter declarations
JAVA0144JAVA0144 Line exceeds maximum M characters
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0143JAVA0143 Synchronized method
FUNCTIONSNumber of function declarations
DECL_COMMENTSComments in declarations
JAVA0035JAVA0035 Missing braces in for statement
JAVA0076JAVA0076 Use of magic number
WHITESPACENumber of whitespace lines
NEST_DEPTHMaximum nesting depth
JAVA0007JAVA0007 Should not declare public field
JAVA0116JAVA0116 Missing javadoc: field 'field'
JAVA0117JAVA0117 Missing javadoc: method 'method'
JAVA0177JAVA0177 Variable declaration missing initializer
JAVA0264JAVA0264 Integer math in long context - check for overflow
COMMENTSComment lines
UNIQUE_OPERATORSNumber of unique operators
JAVA0170JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0166JAVA0166 Generic exception caught
JAVA0285JAVA0285 Dereference of potentially null variable
JAVA0254JAVA0254 Use enhanced for loop construct instead of Iterator
DOC_COMMENTNumber of javadoc comment lines
JAVA0049JAVA0049 Nested block at depth N (maximum: M)
JAVA0036JAVA0036 Missing braces in while statement
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0179JAVA0179 Local variable hides visible field
JAVA0087JAVA0087 Use of Thread.sleep()
JAVA0173JAVA0173 Unused method parameter
JAVA0100JAVA0100 Class contains N non-final fields (maximum: M)
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package freenet.node; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.security.MessageDigest; import java.text.DateFormat; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.Vector; import freenet.crypt.RandomSource; import freenet.crypt.SHA256; import freenet.io.comm.ByteCounter; import freenet.io.comm.DMT; import freenet.io.comm.DisconnectedException; import freenet.io.comm.Message; import freenet.io.comm.MessageFilter; import freenet.io.comm.NotConnectedException; import freenet.node.PeerManager.LocationUIDPair; import freenet.support.Fields; import freenet.support.Logger; import freenet.support.ShortBuffer; import freenet.support.TimeSortedHashtable; import freenet.support.io.Closer; import freenet.support.math.BootstrappingDecayingRunningAverage; /** * @author amphibian * * Tracks the Location of the node. Negotiates swap attempts. * Initiates swap attempts. Deals with locking. */ public class LocationManager implements ByteCounter { public class MyCallback extends SendMessageOnErrorCallback { RecentlyForwardedItem item; public MyCallback(Message message, PeerNode pn, RecentlyForwardedItem item) { super(message, pn, LocationManager.this); this.item = item; } public void disconnected() { super.disconnected(); removeRecentlyForwardedItem(item); } public void acknowledged() { item.successfullyForwarded = true; } } static final int TIMEOUT = 60*1000; static final int SWAP_MAX_HTL = 10; /** Number of swap evaluations, either incoming or outgoing, between resetting our location. * There is a 2 in SWAP_RESET chance that a reset will occur on one or other end of a swap request. * * ALCHEMY: This depends on a number of factors, not least the size of the network. It is hard to * get a good value from simulations. But it can take time to recover after a random reset, so we * have increased it from 4000 to 16000 on 8 april 2008. At the time location churn was significant, * and some of it likely caused by this. OTOH if we get major keyspace fragmentation, we must * reduce it to 8000 or 4000. */ static final int SWAP_RESET = 16000; // FIXME vary automatically static final int SEND_SWAP_INTERVAL = 8000; /** The average time between sending a swap request, and completion. */ final BootstrappingDecayingRunningAverage averageSwapTime; /** Minimum swap delay */ static final int MIN_SWAP_TIME = Node.MIN_INTERVAL_BETWEEN_INCOMING_SWAP_REQUESTS; /** Maximum swap delay */ static final int MAX_SWAP_TIME = 60*1000; /** Don't start swapping until our peers have had a reasonable chance to reconnect. */ private static final long STARTUP_DELAY = 60*1000; private static boolean logMINOR; final RandomSource r; final SwapRequestSender sender; final Node node; long timeLastSuccessfullySwapped; public LocationManager(RandomSource r, Node node) { loc = r.nextDouble(); sender = new SwapRequestSender(); this.r = r; this.node = node; recentlyForwardedIDs = new Hashtable(); // FIXME persist to disk! averageSwapTime = new BootstrappingDecayingRunningAverage(SEND_SWAP_INTERVAL, 0, Integer.MAX_VALUE, 20, null); timeLocSet = System.currentTimeMillis(); logMINOR = Logger.shouldLog(Logger.MINOR, this); } private double loc; private long timeLocSet; private double locChangeSession = 0.0; int numberOfRemotePeerLocationsSeenInSwaps = 0; /** * @return The current Location of this node. */ public synchronized double getLocation() { return loc; } /** * @param l */ public synchronized void setLocation(double l) { if(l < 0.0 || l > 1.0) { Logger.error(this, "Setting invalid location: "+l, new Exception("error")); return; } this.loc = l; timeLocSet = System.currentTimeMillis(); } public synchronized void updateLocationChangeSession(double newLoc) { double oldLoc = loc; double diff = Location.change(oldLoc, newLoc); if(logMINOR) Logger.minor(this, "updateLocationChangeSession: oldLoc: "+oldLoc+" -> newLoc: "+newLoc+" moved: "+diff); this.locChangeSession += diff; } /** * Start a thread to send FNPSwapRequests every second when * we are not locked. */ public void startSender() { if(node.enableSwapping) node.getTicker().queueTimedJob(sender, STARTUP_DELAY); } /** * Sends an FNPSwapRequest every second unless the LM is locked * (which it will be most of the time) */ public class SwapRequestSender implements Runnable { public void run() { freenet.support.Logger.OSThread.logPID(this); Thread.currentThread().setName("SwapRequestSender"); while(true) { try { long startTime = System.currentTimeMillis(); double nextRandom = r.nextDouble(); while(true) { int sleepTime = getSendSwapInterval(); sleepTime *= nextRandom; sleepTime = Math.min(sleepTime, Integer.MAX_VALUE); long endTime = startTime + (int)sleepTime; long now = System.currentTimeMillis(); long diff = endTime - now; try { if(diff > 0) Thread.sleep(Math.min((int)diff, 10000)); } catch (InterruptedException e) { // Ignore } if(System.currentTimeMillis() >= endTime) break; } // Don't send one if we are locked if(lock()) { if(System.currentTimeMillis() - timeLastSuccessfullySwapped > 30*1000) { try { boolean myFlag = false; double myLoc = getLocation(); PeerNode[] peers = node.peers.connectedPeers; for(int i=0;i<peers.length;i++) { PeerNode pn = peers[i]; if(pn.isRoutable()) { synchronized(pn) { double ploc = pn.getLocation(); if(Math.abs(ploc - myLoc) <= Double.MIN_VALUE) { // Don't reset location unless we're SURE there is a problem. // If the node has had its location equal to ours for at least 2 minutes, and ours has been likewise... long now = System.currentTimeMillis(); if(now - pn.getLocSetTime() > 120*1000 && now - timeLocSet > 120*1000) { myFlag = true; // Log an ERROR // As this is an ERROR, it results from either a bug or malicious action. // If it happens very frequently, it indicates either an attack or a serious bug. Logger.error(this, "Randomizing location: my loc="+myLoc+" but loc="+ploc+" for "+pn); break; } else { Logger.normal(this, "Node "+pn+" has identical location to us, waiting until this has persisted for 2 minutes..."); } } } } } if(myFlag) { setLocation(node.random.nextDouble()); announceLocChange(true, true, true); node.writeNodeFile(); } } finally { unlock(false); } } else unlock(false); } else { continue; } // Send a swap request startSwapRequest(); } catch (Throwable t) { Logger.error(this, "Caught "+t, t); } } } } /** * Create a new SwapRequest, send it from this node out into * the wilderness. */ private void startSwapRequest() { node.executor.execute(new OutgoingSwapRequestHandler(), "Outgoing swap request handler for port "+node.getDarknetPortNumber()); } public int getSendSwapInterval() { int interval = (int) averageSwapTime.currentValue(); if(interval < MIN_SWAP_TIME) interval = MIN_SWAP_TIME; if(interval > MAX_SWAP_TIME) interval = MAX_SWAP_TIME; return interval; } /** * Similar to OutgoingSwapRequestHandler, except that we did * not initiate the SwapRequest. */ public class IncomingSwapRequestHandler implements Runnable { Message origMessage; PeerNode pn; long uid; Long luid; RecentlyForwardedItem item; IncomingSwapRequestHandler(Message msg, PeerNode pn, RecentlyForwardedItem item) { this.origMessage = msg; this.pn = pn; this.item = item; uid = origMessage.getLong(DMT.UID); luid = new Long(uid); } public void run() { freenet.support.Logger.OSThread.logPID(this); MessageDigest md = SHA256.getMessageDigest(); boolean reachedEnd = false; try { // We are already locked by caller // Because if we can't get lock they need to send a reject // Firstly, is their message valid? byte[] hisHash = ((ShortBuffer)origMessage.getObject(DMT.HASH)).getData(); if(hisHash.length != md.getDigestLength()) { Logger.error(this, "Invalid SwapRequest from peer: wrong length hash "+hisHash.length+" on "+uid); // FIXME: Should we send a reject? return; } // Looks okay, lets get on with it // Only one ID because we are only receiving addForwardedItem(uid, uid, pn, null); // Create my side long random = r.nextLong(); double myLoc = getLocation(); LocationUIDPair[] friendLocsAndUIDs = node.peers.getPeerLocationsAndUIDs(); double[] friendLocs = extractLocs(friendLocsAndUIDs); long[] myValueLong = new long[1+1+friendLocs.length]; myValueLong[0] = random; myValueLong[1] = Double.doubleToLongBits(myLoc); for(int i=0;i<friendLocs.length;i++) myValueLong[i+2] = Double.doubleToLongBits(friendLocs[i]); byte[] myValue = Fields.longsToBytes(myValueLong); byte[] myHash = md.digest(myValue); Message m = DMT.createFNPSwapReply(uid, myHash); MessageFilter filter = MessageFilter.create().setType(DMT.FNPSwapCommit).setField(DMT.UID, uid).setTimeout(TIMEOUT).setSource(pn); node.usm.send(pn, m, LocationManager.this); Message commit; try { commit = node.usm.waitFor(filter, LocationManager.this); } catch (DisconnectedException e) { if(logMINOR) Logger.minor(this, "Disconnected from "+pn+" while waiting for SwapCommit"); return; } if(commit == null) { // Timed out. Abort Logger.error(this, "Timed out waiting for SwapCommit on "+uid+" - this can happen occasionally due to connection closes, if it happens often, there may be a serious problem"); return; } // We have a SwapCommit byte[] hisBuf = ((ShortBuffer)commit.getObject(DMT.DATA)).getData(); if((hisBuf.length % 8 != 0) || (hisBuf.length < 16)) { Logger.error(this, "Bad content length in SwapComplete - malicious node? on "+uid); return; } // First does it verify? byte[] rehash = md.digest(hisBuf); if(!java.util.Arrays.equals(rehash, hisHash)) { Logger.error(this, "Bad hash in SwapCommit - malicious node? on "+uid); return; } // Now decode it long[] hisBufLong = Fields.bytesToLongs(hisBuf); if(hisBufLong.length < 2) { Logger.error(this, "Bad buffer length (no random, no location)- malicious node? on "+uid); return; } long hisRandom = hisBufLong[0]; double hisLoc = Double.longBitsToDouble(hisBufLong[1]); if((hisLoc < 0.0) || (hisLoc > 1.0)) { Logger.error(this, "Bad loc: "+hisLoc+" on "+uid); return; } registerKnownLocation(hisLoc); double[] hisFriendLocs = new double[hisBufLong.length-2]; for(int i=0;i<hisFriendLocs.length;i++) { hisFriendLocs[i] = Double.longBitsToDouble(hisBufLong[i+2]); if((hisFriendLocs[i] < 0.0) || (hisFriendLocs[i] > 1.0)) { Logger.error(this, "Bad friend loc: "+hisFriendLocs[i]+" on "+uid); return; } registerLocationLink(hisLoc, hisFriendLocs[i]); registerKnownLocation(hisFriendLocs[i]); } numberOfRemotePeerLocationsSeenInSwaps += hisFriendLocs.length; // Send our SwapComplete Message confirm = DMT.createFNPSwapComplete(uid, myValue); //confirm.addSubMessage(DMT.createFNPSwapLocations(extractUIDs(friendLocsAndUIDs))); node.usm.send(pn, confirm, LocationManager.this); boolean shouldSwap = shouldSwap(myLoc, friendLocs, hisLoc, hisFriendLocs, random ^ hisRandom); spyOnLocations(commit, true, shouldSwap, myLoc); if(shouldSwap) { timeLastSuccessfullySwapped = System.currentTimeMillis(); // Swap updateLocationChangeSession(hisLoc); setLocation(hisLoc); if(logMINOR) Logger.minor(this, "Swapped: "+myLoc+" <-> "+hisLoc+" - "+uid); swaps++; announceLocChange(true, false, false); node.writeNodeFile(); } else { if(logMINOR) Logger.minor(this, "Didn't swap: "+myLoc+" <-> "+hisLoc+" - "+uid); noSwaps++; } reachedEnd = true; // Randomise our location every 2*SWAP_RESET swap attempts, whichever way it went. if(node.random.nextInt(SWAP_RESET) == 0) { setLocation(node.random.nextDouble()); announceLocChange(true, true, false); node.writeNodeFile(); } SHA256.returnMessageDigest(md); } catch (Throwable t) { Logger.error(this, "Caught "+t, t); } finally { unlock(reachedEnd); // we only count the time taken by our outgoing swap requests removeRecentlyForwardedItem(item); } } } /** * Locks the LocationManager. * Sends an FNPSwapRequest out into the network. * Waits for a reply. * Etc. */ public class OutgoingSwapRequestHandler implements Runnable { RecentlyForwardedItem item; public void run() { freenet.support.Logger.OSThread.logPID(this); long uid = r.nextLong(); if(!lock()) return; boolean reachedEnd = false; try { startedSwaps++; // We can't lock friends_locations, so lets just // pretend that they're locked long random = r.nextLong(); double myLoc = getLocation(); LocationUIDPair[] friendLocsAndUIDs = node.peers.getPeerLocationsAndUIDs(); double[] friendLocs = extractLocs(friendLocsAndUIDs); long[] myValueLong = new long[1+1+friendLocs.length]; myValueLong[0] = random; myValueLong[1] = Double.doubleToLongBits(myLoc); for(int i=0;i<friendLocs.length;i++) myValueLong[i+2] = Double.doubleToLongBits(friendLocs[i]); byte[] myValue = Fields.longsToBytes(myValueLong); byte[] myHash = SHA256.digest(myValue); Message m = DMT.createFNPSwapRequest(uid, myHash, SWAP_MAX_HTL); PeerNode pn = node.peers.getRandomPeer(); if(pn == null) { // Nowhere to send return; } // Only 1 ID because we are sending; we won't receive item = addForwardedItem(uid, uid, null, pn); if(logMINOR) Logger.minor(this, "Sending SwapRequest "+uid+" to "+pn); MessageFilter filter1 = MessageFilter.create().setType(DMT.FNPSwapRejected).setField(DMT.UID, uid).setSource(pn).setTimeout(TIMEOUT); MessageFilter filter2 = MessageFilter.create().setType(DMT.FNPSwapReply).setField(DMT.UID, uid).setSource(pn).setTimeout(TIMEOUT); MessageFilter filter = filter1.or(filter2); node.usm.send(pn, m, LocationManager.this); if(logMINOR) Logger.minor(this, "Waiting for SwapReply/SwapRejected on "+uid); Message reply; try { reply = node.usm.waitFor(filter, LocationManager.this); } catch (DisconnectedException e) { if(logMINOR) Logger.minor(this, "Disconnected while waiting for SwapReply/SwapRejected for "+uid); return; } if(reply == null) { if(pn.isRoutable() && (System.currentTimeMillis() - pn.timeLastConnectionCompleted() > TIMEOUT*2)) { // Timed out! Abort... Logger.error(this, "Timed out waiting for SwapRejected/SwapReply on "+uid); } return; } if(reply.getSpec() == DMT.FNPSwapRejected) { // Failed. Abort. if(logMINOR) Logger.minor(this, "Swap rejected on "+uid); return; } // We have an FNPSwapReply, yay // FNPSwapReply is exactly the same format as FNPSwapRequest byte[] hisHash = ((ShortBuffer)reply.getObject(DMT.HASH)).getData(); Message confirm = DMT.createFNPSwapCommit(uid, myValue); //confirm.addSubMessage(DMT.createFNPSwapLocations(extractUIDs(friendLocsAndUIDs))); filter1.clearOr(); MessageFilter filter3 = MessageFilter.create().setField(DMT.UID, uid).setType(DMT.FNPSwapComplete).setTimeout(TIMEOUT).setSource(pn); filter = filter1.or(filter3); node.usm.send(pn, confirm, LocationManager.this); if(logMINOR) Logger.minor(this, "Waiting for SwapComplete: uid = "+uid); try { reply = node.usm.waitFor(filter, LocationManager.this); } catch (DisconnectedException e) { if(logMINOR) Logger.minor(this, "Disconnected waiting for SwapComplete on "+uid); return; } if(reply == null) { if(pn.isRoutable() && (System.currentTimeMillis() - pn.timeLastConnectionCompleted() > TIMEOUT*2)) { // Hrrrm! Logger.error(this, "Timed out waiting for SwapComplete - malicious node?? on "+uid); } return; } if(reply.getSpec() == DMT.FNPSwapRejected) { Logger.error(this, "Got SwapRejected while waiting for SwapComplete. This can happen occasionally because of badly timed disconnects, but if it happens frequently it indicates a bug or an attack"); return; } byte[] hisBuf = ((ShortBuffer)reply.getObject(DMT.DATA)).getData(); if((hisBuf.length % 8 != 0) || (hisBuf.length < 16)) { Logger.error(this, "Bad content length in SwapComplete - malicious node? on "+uid); return; } // First does it verify? byte[] rehash = SHA256.digest(hisBuf); if(!java.util.Arrays.equals(rehash, hisHash)) { Logger.error(this, "Bad hash in SwapComplete - malicious node? on "+uid); return; } // Now decode it long[] hisBufLong = Fields.bytesToLongs(hisBuf); if(hisBufLong.length < 2) { Logger.error(this, "Bad buffer length (no random, no location)- malicious node? on " + uid); return; } long hisRandom = hisBufLong[0]; double hisLoc = Double.longBitsToDouble(hisBufLong[1]); if((hisLoc < 0.0) || (hisLoc > 1.0)) { Logger.error(this, "Bad loc: "+hisLoc+" on "+uid); return; } registerKnownLocation(hisLoc); double[] hisFriendLocs = new double[hisBufLong.length-2]; for(int i=0;i<hisFriendLocs.length;i++) { hisFriendLocs[i] = Double.longBitsToDouble(hisBufLong[i+2]); if((hisFriendLocs[i] < 0.0) || (hisFriendLocs[i] > 1.0)) { Logger.error(this, "Bad friend loc: "+hisFriendLocs[i]+" on "+uid); return; } registerLocationLink(hisLoc, hisFriendLocs[i]); registerKnownLocation(hisFriendLocs[i]); } numberOfRemotePeerLocationsSeenInSwaps += hisFriendLocs.length; boolean shouldSwap = shouldSwap(myLoc, friendLocs, hisLoc, hisFriendLocs, random ^ hisRandom); spyOnLocations(reply, true, shouldSwap, myLoc); if(shouldSwap) { timeLastSuccessfullySwapped = System.currentTimeMillis(); // Swap updateLocationChangeSession(hisLoc); setLocation(hisLoc); if(logMINOR) Logger.minor(this, "Swapped: "+myLoc+" <-> "+hisLoc+" - "+uid); swaps++; announceLocChange(true, false, false); node.writeNodeFile(); } else { if(logMINOR) Logger.minor(this, "Didn't swap: "+myLoc+" <-> "+hisLoc+" - "+uid); noSwaps++; } reachedEnd = true; // Randomise our location every 2*SWAP_RESET swap attempts, whichever way it went. if(node.random.nextInt(SWAP_RESET) == 0) { setLocation(node.random.nextDouble()); announceLocChange(true, true, false); node.writeNodeFile(); } } catch (Throwable t) { Logger.error(this, "Caught "+t, t); } finally { unlock(reachedEnd); if(item != null) removeRecentlyForwardedItem(item); } } } /** * Tell all connected peers that our location has changed */ protected void announceLocChange() { announceLocChange(false, false, false); } private void announceLocChange(boolean log, boolean randomReset, boolean fromDupLocation) { Message msg = DMT.createFNPLocChangeNotificationNew(getLocation(), node.peers.getPeerLocationDoubles(true)); node.peers.localBroadcast(msg, false, true, this); if(log) recordLocChange(randomReset, fromDupLocation); } private void recordLocChange(final boolean randomReset, final boolean fromDupLocation) { node.executor.execute(new Runnable() { public void run() { File locationLog = new File(node.nodeDir, "location.log.txt"); if(locationLog.exists() && locationLog.length() > 1024*1024*10) locationLog.delete(); FileWriter fw = null; try { fw = new FileWriter(locationLog, true); fw.write(""+DateFormat.getDateTimeInstance().format(new Date())+" : "+getLocation()+(randomReset ? " (random reset"+(fromDupLocation?" from duplicated location" : "")+")" : "")+'\n'); fw.close(); } catch (IOException e) { Logger.error(this, "Unable to write changed location to "+locationLog+" : "+e, e); } finally { if(fw != null) Closer.close(fw); } } }, "Record new location"); } private boolean locked; public static int swaps; public static int noSwaps; public static int startedSwaps; public static int swapsRejectedAlreadyLocked; public static int swapsRejectedNowhereToGo; public static int swapsRejectedRateLimit; public static int swapsRejectedLoop; public static int swapsRejectedRecognizedID; long lockedTime; /** * Lock the LocationManager. * @return True if we managed to lock the LocationManager, * false if it was already locked. */ synchronized boolean lock() { if(locked) { if(logMINOR) Logger.minor(this, "Already locked"); return false; } if(logMINOR) Logger.minor(this, "Locking on port "+node.getDarknetPortNumber()); locked = true; lockedTime = System.currentTimeMillis(); return true; } /** * Unlock the node for swapping. * @param logSwapTime If true, log the swap time. */ void unlock(boolean logSwapTime) { Message nextMessage; synchronized(this) { if(!locked) throw new IllegalStateException("Unlocking when not locked!"); long lockTime = System.currentTimeMillis() - lockedTime; if(logMINOR) { Logger.minor(this, "Unlocking on port "+node.getDarknetPortNumber()); Logger.minor(this, "lockTime: "+lockTime); } averageSwapTime.report(lockTime); if(incomingMessageQueue.isEmpty()) { locked = false; return; } // Otherwise, stay locked, and start the next one from the queue. nextMessage = (Message) incomingMessageQueue.removeFirst(); lockedTime = System.currentTimeMillis(); } long oldID = nextMessage.getLong(DMT.UID); long newID = oldID+1; PeerNode pn = (PeerNode) nextMessage.getSource(); innerHandleSwapRequest(oldID, newID, pn, nextMessage); } /** * Should we swap? This method implements the core of the Freenet * 0.7 routing algorithm - the criteria for swapping. * Oskar says this is derived from the Metropolis-Hastings algorithm. * * Anyway: * Two nodes choose each other and decide to attempt a switch. They * calculate the distance of all their edges currently (that is the * distance between their currend ID and that of their neighbors), and * multiply up all these values to get A. Then they calculate the * distance to all their neighbors as it would be if they switched * IDs, and multiply up these values to get B. * * If A > B then they switch. * * If A <= B, then calculate p = A / B. They then switch with * probability p (that is, switch if rand.nextFloat() < p). * * @param myLoc My location as a double. * @param friendLocs Locations of my friends as doubles. * @param hisLoc His location as a double * @param hisFriendLocs Locations of his friends as doubles. * @param rand Shared random number used to decide whether to swap. * @return */ private boolean shouldSwap(double myLoc, double[] friendLocs, double hisLoc, double[] hisFriendLocs, long rand) { // A = distance from us to all our neighbours, for both nodes, // all multiplied together // Dump if(Math.abs(hisLoc - myLoc) <= Double.MIN_VALUE * 2) return false; // Probably swapping with self StringBuffer sb = new StringBuffer(); sb.append("my: ").append(myLoc).append(", his: ").append(hisLoc).append(", myFriends: "); sb.append(friendLocs.length).append(", hisFriends: ").append(hisFriendLocs.length).append(" mine:\n"); for(int i=0;i<friendLocs.length;i++) { sb.append(friendLocs[i]); sb.append(' '); } sb.append("\nhis:\n"); for(int i=0;i<hisFriendLocs.length;i++) { sb.append(hisFriendLocs[i]); sb.append(' '); } if(logMINOR) Logger.minor(this, sb.toString()); double A = 1.0; for(int i=0;i<friendLocs.length;i++) { if(Math.abs(friendLocs[i] - myLoc) <= Double.MIN_VALUE*2) continue; A *= Location.distance(friendLocs[i], myLoc); } for(int i=0;i<hisFriendLocs.length;i++) { if(Math.abs(hisFriendLocs[i] - hisLoc) <= Double.MIN_VALUE*2) continue; A *= Location.distance(hisFriendLocs[i], hisLoc); } // B = the same, with our two values swapped double B = 1.0; for(int i=0;i<friendLocs.length;i++) { if(Math.abs(friendLocs[i] - hisLoc) <= Double.MIN_VALUE*2) continue; B *= Location.distance(friendLocs[i], hisLoc); } for(int i=0;i<hisFriendLocs.length;i++) { if(Math.abs(hisFriendLocs[i] - myLoc) <= Double.MIN_VALUE*2) continue; B *= Location.distance(hisFriendLocs[i], myLoc); } //Logger.normal(this, "A="+A+" B="+B); if(A>B) return true; double p = A / B; // Take last 63 bits, then turn into a double double randProb = ((double)(rand & Long.MAX_VALUE)) / ((double) Long.MAX_VALUE); //Logger.normal(this, "p="+p+" randProb="+randProb); if(randProb < p) return true; return false; } static final double SWAP_ACCEPT_PROB = 0.25; final Hashtable recentlyForwardedIDs; static class RecentlyForwardedItem { final long incomingID; // unnecessary? final long outgoingID; final long addedTime; long lastMessageTime; // can delete when no messages for 2*TIMEOUT final PeerNode requestSender; PeerNode routedTo; // Set when a request is accepted. Unset when we send one. boolean successfullyForwarded; RecentlyForwardedItem(long id, long outgoingID, PeerNode from, PeerNode to) { this.incomingID = id; this.outgoingID = outgoingID; requestSender = from; routedTo = to; addedTime = System.currentTimeMillis(); lastMessageTime = addedTime; } } /** Queue of swap requests to handle after this one. */ private final LinkedList incomingMessageQueue = new LinkedList(); static final int MAX_INCOMING_QUEUE_LENGTH = 10; /** Prevent timeouts and deadlocks due to A waiting for B waiting for A */ static final long MAX_TIME_ON_INCOMING_QUEUE = 30*1000; void removeTooOldQueuedItems() { while(true) { Message first; synchronized(this) { if(incomingMessageQueue.isEmpty()) return; first = (Message) incomingMessageQueue.getFirst(); if(first.age() < MAX_TIME_ON_INCOMING_QUEUE) return; incomingMessageQueue.removeFirst(); if(logMINOR) Logger.minor(this, "Cancelling queued item: "+first+" - too long on queue, maybe circular waiting?"); swapsRejectedAlreadyLocked++; } long oldID = first.getLong(DMT.UID); PeerNode pn = (PeerNode) first.getSource(); // Reject Message reject = DMT.createFNPSwapRejected(oldID); try { pn.sendAsync(reject, null, 0, this); } catch (NotConnectedException e1) { if(logMINOR) Logger.minor(this, "Lost connection rejecting SwapRequest (locked) from "+pn); } } } /** * Handle an incoming SwapRequest * @return True if we have handled the message, false if it needs * to be handled otherwise. */ public boolean handleSwapRequest(Message m, PeerNode pn) { long oldID = m.getLong(DMT.UID); Long luid = new Long(oldID); long newID = oldID+1; /** * UID is used to record the state i.e. UID x, came in from node a, forwarded to node b. * We increment it on each hop, because in order for the node selection to be as random as * possible we *must allow loops*! I.e. the same swap chain may pass over the same node * twice or more. However, if we get a request with either the incoming or the outgoing * UID, we can safely kill it as it's clearly the result of a bug. */ RecentlyForwardedItem item = (RecentlyForwardedItem) recentlyForwardedIDs.get(luid); if(item != null) { if(logMINOR) Logger.minor(this, "Rejecting - same ID as previous request"); // Reject Message reject = DMT.createFNPSwapRejected(oldID); try { pn.sendAsync(reject, null, 0, this); } catch (NotConnectedException e) { if(logMINOR) Logger.minor(this, "Lost connection to "+pn+" rejecting SwapRequest"); } swapsRejectedRecognizedID++; return true; } if(pn.shouldRejectSwapRequest()) { if(logMINOR) Logger.minor(this, "Advised to reject SwapRequest by PeerNode - rate limit"); // Reject Message reject = DMT.createFNPSwapRejected(oldID); try { pn.sendAsync(reject, null, 0, this); } catch (NotConnectedException e) { if(logMINOR) Logger.minor(this, "Lost connection rejecting SwapRequest from "+pn); } swapsRejectedRateLimit++; return true; } if(logMINOR) Logger.minor(this, "SwapRequest from "+pn+" - uid="+oldID); int htl = m.getInt(DMT.HTL); if(htl > SWAP_MAX_HTL) { Logger.error(this, "Bogus swap HTL: "+htl+" from "+pn+" uid="+oldID); htl = SWAP_MAX_HTL; } htl--; if(!node.enableSwapping) { // Reject Message reject = DMT.createFNPSwapRejected(oldID); try { pn.sendAsync(reject, null, 0, this); } catch (NotConnectedException e1) { if(logMINOR) Logger.minor(this, "Lost connection rejecting SwapRequest (locked) from "+pn); } return true; } // Either forward it or handle it if(htl <= 0) { if(logMINOR) Logger.minor(this, "Accepting?... "+oldID); // Accept - handle locally lockOrQueue(m, oldID, newID, pn); return true; } else { m.set(DMT.HTL, htl); m.set(DMT.UID, newID); if(logMINOR) Logger.minor(this, "Forwarding... "+oldID); while(true) { // Forward PeerNode randomPeer = node.peers.getRandomPeerInSwappingNetworkOf(pn); if(randomPeer == null) { if(logMINOR) Logger.minor(this, "Late reject "+oldID); Message reject = DMT.createFNPSwapRejected(oldID); try { pn.sendAsync(reject, null, 0, this); } catch (NotConnectedException e1) { Logger.normal(this, "Late reject but disconnected from sender: "+pn); } swapsRejectedNowhereToGo++; return true; } if(logMINOR) Logger.minor(this, "Forwarding "+oldID+" to "+randomPeer); item = addForwardedItem(oldID, newID, pn, randomPeer); item.successfullyForwarded = false; try { // Forward the request. // Note that we MUST NOT send this blocking as we are on the // receiver thread. randomPeer.sendAsync(m, new MyCallback(DMT.createFNPSwapRejected(oldID), pn, item), 0, LocationManager.this); } catch (NotConnectedException e) { if(logMINOR) Logger.minor(this, "Not connected"); // Try a different node continue; } return true; } } } /** * If we can obtain the lock, then execute the swap by calling innerHandleSwapRequest(). * If we can queue the message, queue it. * Otherwise, reject it. */ void lockOrQueue(Message msg, long oldID, long newID, PeerNode pn) { boolean runNow = false; boolean reject = false; if(logMINOR) Logger.minor(this, "Locking on port "+node.getDarknetPortNumber()+" for uid "+oldID+" from "+pn); synchronized(this) { if(!locked) { locked = true; runNow = true; lockedTime = System.currentTimeMillis(); } else { // Locked. if((!node.enableSwapQueueing) || incomingMessageQueue.size() > MAX_INCOMING_QUEUE_LENGTH) { // Reject anyway. reject = true; swapsRejectedAlreadyLocked++; if(logMINOR) Logger.minor(this, "Incoming queue length too large: "+incomingMessageQueue.size()+" rejecting "+msg); } else { // Queue it. incomingMessageQueue.addLast(msg); if(logMINOR) Logger.minor(this, "Queued "+msg+" queue length "+incomingMessageQueue.size()); } } } if(reject) { if(logMINOR) Logger.minor(this, "Rejecting "+msg); Message rejected = DMT.createFNPSwapRejected(oldID); try { pn.sendAsync(rejected, null, 0, this); } catch (NotConnectedException e1) { if(logMINOR) Logger.minor(this, "Lost connection rejecting SwapRequest (locked) from "+pn); } } else if(runNow) { if(logMINOR) Logger.minor(this, "Running "+msg); boolean completed = false; try { innerHandleSwapRequest(oldID, newID, pn, msg); completed = true; } finally { if(!completed) unlock(false); } } } private void innerHandleSwapRequest(long oldID, long newID, PeerNode pn, Message m) { RecentlyForwardedItem item = addForwardedItem(oldID, newID, pn, null); // Locked, do it IncomingSwapRequestHandler isrh = new IncomingSwapRequestHandler(m, pn, item); if(logMINOR) Logger.minor(this, "Handling... "+oldID+" from "+pn); node.executor.execute(isrh, "Incoming swap request handler for port "+node.getDarknetPortNumber()); } private RecentlyForwardedItem addForwardedItem(long uid, long oid, PeerNode pn, PeerNode randomPeer) { RecentlyForwardedItem item = new RecentlyForwardedItem(uid, oid, pn, randomPeer); synchronized(recentlyForwardedIDs) { recentlyForwardedIDs.put(new Long(uid), item); recentlyForwardedIDs.put(new Long(oid), item); } return item; } /** * Handle an unmatched FNPSwapReply * @return True if we recognized and forwarded this reply. */ public boolean handleSwapReply(Message m, PeerNode source) { long uid = m.getLong(DMT.UID); Long luid = new Long(uid); RecentlyForwardedItem item = (RecentlyForwardedItem) recentlyForwardedIDs.get(luid); if(item == null) { Logger.error(this, "Unrecognized SwapReply: ID "+uid); return false; } if(item.requestSender == null) { if(logMINOR) Logger.minor(this, "SwapReply from "+source+" on chain originated locally "+uid); return false; } if(item.routedTo == null) { Logger.error(this, "Got SwapReply on "+uid+" but routedTo is null!"); return false; } if(source != item.routedTo) { Logger.error(this, "Unmatched swapreply "+uid+" from wrong source: From "+source+ " should be "+item.routedTo+" to "+item.requestSender); return true; } item.lastMessageTime = System.currentTimeMillis(); // Returning to source - use incomingID m.set(DMT.UID, item.incomingID); if(logMINOR) Logger.minor(this, "Forwarding SwapReply "+uid+" from "+source+" to "+item.requestSender); try { item.requestSender.sendAsync(m, null, 0, this); } catch (NotConnectedException e) { if(logMINOR) Logger.minor(this, "Lost connection forwarding SwapReply "+uid+" to "+item.requestSender); } return true; } /** * Handle an unmatched FNPSwapRejected * @return True if we recognized and forwarded this message. */ public boolean handleSwapRejected(Message m, PeerNode source) { long uid = m.getLong(DMT.UID); Long luid = new Long(uid); RecentlyForwardedItem item = (RecentlyForwardedItem) recentlyForwardedIDs.get(luid); if(item == null) return false; if(item.requestSender == null){ if(logMINOR) Logger.minor(this, "Got a FNPSwapRejected without any requestSender set! we can't and won't claim it! UID="+uid); return false; } if(item.routedTo == null) { Logger.error(this, "Got SwapRejected on "+uid+" but routedTo is null!"); return false; } if(source != item.routedTo) { Logger.error(this, "Unmatched swapreply "+uid+" from wrong source: From "+source+ " should be "+item.routedTo+" to "+item.requestSender); return true; } removeRecentlyForwardedItem(item); item.lastMessageTime = System.currentTimeMillis(); if(logMINOR) Logger.minor(this, "Forwarding SwapRejected "+uid+" from "+source+" to "+item.requestSender); // Returning to source - use incomingID m.set(DMT.UID, item.incomingID); try { item.requestSender.sendAsync(m, null, 0, this); } catch (NotConnectedException e) { if(logMINOR) Logger.minor(this, "Lost connection forwarding SwapRejected "+uid+" to "+item.requestSender); } return true; } /** * Handle an unmatched FNPSwapCommit * @return True if we recognized and forwarded this message. */ public boolean handleSwapCommit(Message m, PeerNode source) { long uid = m.getLong(DMT.UID); Long luid = new Long(uid); RecentlyForwardedItem item = (RecentlyForwardedItem) recentlyForwardedIDs.get(luid); if(item == null) return false; if(item.routedTo == null) return false; if(source != item.requestSender) { Logger.error(this, "Unmatched swapreply "+uid+" from wrong source: From "+source+ " should be "+item.requestSender+" to "+item.routedTo); return true; } item.lastMessageTime = System.currentTimeMillis(); if(logMINOR) Logger.minor(this, "Forwarding SwapCommit "+uid+ ',' +item.outgoingID+" from "+source+" to "+item.routedTo); // Sending onwards - use outgoing ID m.set(DMT.UID, item.outgoingID); try { item.routedTo.sendAsync(m, new SendMessageOnErrorCallback(DMT.createFNPSwapRejected(item.incomingID), item.requestSender, this), 0, this); } catch (NotConnectedException e) { if(logMINOR) Logger.minor(this, "Lost connection forwarding SwapCommit "+uid+" to "+item.routedTo); } spyOnLocations(m, false); return true; } /** * Handle an unmatched FNPSwapComplete * @return True if we recognized and forwarded this message. */ public boolean handleSwapComplete(Message m, PeerNode source) { long uid = m.getLong(DMT.UID); if(logMINOR) Logger.minor(this, "handleSwapComplete("+uid+ ')'); Long luid = new Long(uid); RecentlyForwardedItem item = (RecentlyForwardedItem) recentlyForwardedIDs.get(luid); if(item == null) { if(logMINOR) Logger.minor(this, "Item not found: "+uid+": "+m); return false; } if(item.requestSender == null) { if(logMINOR) Logger.minor(this, "Not matched "+uid+": "+m); return false; } if(item.routedTo == null) { Logger.error(this, "Got SwapComplete on "+uid+" but routedTo == null! (meaning we accepted it, presumably)"); return false; } if(source != item.routedTo) { Logger.error(this, "Unmatched swapreply "+uid+" from wrong source: From "+source+ " should be "+item.routedTo+" to "+item.requestSender); return true; } if(logMINOR) Logger.minor(this, "Forwarding SwapComplete "+uid+" from "+source+" to "+item.requestSender); // Returning to source - use incomingID m.set(DMT.UID, item.incomingID); try { item.requestSender.sendAsync(m, null, 0, this); } catch (NotConnectedException e) { Logger.normal(this, "Lost connection forwarding SwapComplete "+uid+" to "+item.requestSender); } item.lastMessageTime = System.currentTimeMillis(); removeRecentlyForwardedItem(item); spyOnLocations(m, false); return true; } private void spyOnLocations(Message m, boolean ignoreIfOld) { spyOnLocations(m, ignoreIfOld, false, -1.0); } /** Spy on locations in somebody else's swap request. Greatly increases the * speed at which we can gather location data to estimate the network's size. * @param swappingWithMe True if this node is participating in the swap, false if it is * merely spying on somebody else's swap. */ private void spyOnLocations(Message m, boolean ignoreIfOld, boolean swappingWithMe, double myLoc) { long[] uids = null; Message uidsMessage = m.getSubMessage(DMT.FNPSwapNodeUIDs); if(uidsMessage != null) { uids = Fields.bytesToLongs(((ShortBuffer) uidsMessage.getObject(DMT.NODE_UIDS)).getData()); } byte[] data = ((ShortBuffer)m.getObject(DMT.DATA)).getData(); if(data.length < 16 || data.length % 8 != 0) { Logger.error(this, "Data invalid length in swap commit: "+data.length, new Exception("error")); return; } double[] locations = Fields.bytesToDoubles(data, 8, data.length-8); double hisLoc = locations[0]; if(hisLoc < 0.0 || hisLoc > 1.0) { Logger.error(this, "Invalid hisLoc in swap commit: "+hisLoc, new Exception("error")); return; } if(uids != null) { registerKnownLocation(hisLoc, uids[0]); if(swappingWithMe) registerKnownLocation(myLoc, uids[0]); } else if (!ignoreIfOld) registerKnownLocation(hisLoc); for(int i=1;i<locations.length;i++) { double loc = locations[i]; if(uids != null) { registerKnownLocation(loc, uids[i-1]); registerLink(uids[0], uids[i-1]); } else if(!ignoreIfOld) { registerKnownLocation(loc); registerLocationLink(hisLoc, loc); } } } public void clearOldSwapChains() { long now = System.currentTimeMillis(); synchronized(recentlyForwardedIDs) { RecentlyForwardedItem[] items = new RecentlyForwardedItem[recentlyForwardedIDs.size()]; if(items.length < 1) return; items = (RecentlyForwardedItem[]) recentlyForwardedIDs.values().toArray(items); for(int i=0;i<items.length;i++) { if(now - items[i].lastMessageTime > (TIMEOUT*2)) { removeRecentlyForwardedItem(items[i]); } } } } /** * We lost the connection to a node, or it was restarted. */ public void lostOrRestartedNode(PeerNode pn) { Vector v = new Vector(); synchronized(recentlyForwardedIDs) { Set entrySet = recentlyForwardedIDs.entrySet(); Iterator it = entrySet.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Long l = (Long) entry.getKey(); RecentlyForwardedItem item = (RecentlyForwardedItem) entry.getValue(); if(item == null) { Logger.error(this, "Key is "+l+" but no value on recentlyForwardedIDs - shouldn't be possible"); continue; } if(item.routedTo != pn) continue; if(item.successfullyForwarded) { v.add(item); } } // remove them Iterator it2 = v.iterator(); while (it2.hasNext()) removeRecentlyForwardedItem((RecentlyForwardedItem) it2.next()); } int dumped=v.size(); if (dumped!=0 && logMINOR) Logger.minor(this, "lostOrRestartedNode dumping "+dumped+" swap requests for "+pn.getPeer()); for(int i=0;i<dumped;i++) { RecentlyForwardedItem item = (RecentlyForwardedItem) v.get(i); // Just reject it to avoid locking problems etc Message msg = DMT.createFNPSwapRejected(item.incomingID); if(logMINOR) Logger.minor(this, "Rejecting in lostOrRestartedNode: "+item.incomingID+ " from "+item.requestSender); try { item.requestSender.sendAsync(msg, null, 0, this); } catch (NotConnectedException e1) { Logger.normal(this, "Both sender and receiver disconnected for "+item); } } } private void removeRecentlyForwardedItem(RecentlyForwardedItem item) { if(logMINOR) Logger.minor(this, "Removing: "+item); if(item == null) { Logger.error(this, "removeRecentlyForwardedItem(null)", new Exception("error")); } synchronized(recentlyForwardedIDs) { recentlyForwardedIDs.remove(new Long(item.incomingID)); recentlyForwardedIDs.remove(new Long(item.outgoingID)); } } private static final long MAX_AGE = 7*24*60*60*1000; private final TimeSortedHashtable<Double> knownLocs = new TimeSortedHashtable<Double>(); void registerLocationLink(double d, double t) { if(logMINOR) Logger.minor(this, "Known Link: "+d+ ' ' +t); } void registerKnownLocation(double d, long uid) { if(logMINOR) Logger.minor(this, "LOCATION: "+d+" UID: "+uid); registerKnownLocation(d); } void registerKnownLocation(double d) { if(logMINOR) Logger.minor(this, "Known Location: "+d); long now = System.currentTimeMillis(); synchronized(knownLocs) { Logger.minor(this, "Adding location "+d+" knownLocs size "+knownLocs.size()); knownLocs.push(d, now); Logger.minor(this, "Added location "+d+" knownLocs size "+knownLocs.size()); knownLocs.removeBefore(now - MAX_AGE); Logger.minor(this, "Added and pruned location "+d+" knownLocs size "+knownLocs.size()); } if(logMINOR) Logger.minor(this, "Estimated net size(session): "+knownLocs.size()); } void registerLink(long uid1, long uid2) { if(logMINOR) Logger.minor(this, "UID LINK: "+uid1+" , "+uid2); } //Return the estimated network size based on locations seen after timestamp or for the whole session if -1 public int getNetworkSizeEstimate(long timestamp) { return knownLocs.countValuesAfter(timestamp); } /** * Method called by Node.getKnownLocations(long timestamp) * * @Return an array containing two cells : Locations and their last seen time for a given timestamp. */ public Object[] getKnownLocations(long timestamp) { synchronized (knownLocs) { return knownLocs.pairsAfter(timestamp, new Double[knownLocs.size()]); } } static double[] extractLocs(LocationUIDPair[] pairs) { double[] locs = new double[pairs.length]; for(int i=0;i<pairs.length;i++) locs[i] = pairs[i].location; return locs; } static long[] extractUIDs(LocationUIDPair[] pairs) { long[] uids = new long[pairs.length]; for(int i=0;i<pairs.length;i++) uids[i] = pairs[i].uid; return uids; } public static double[] extractLocs(PeerNode[] peers, boolean indicateBackoff) { double[] locs = new double[peers.length]; for(int i=0;i<peers.length;i++) { locs[i] = peers[i].getLocation(); if(indicateBackoff) { if(peers[i].isRoutingBackedOff()) locs[i] += 1; else locs[i] = -1 - locs[i]; } } return locs; } public static long[] extractUIDs(PeerNode[] peers) { long[] uids = new long[peers.length]; for(int i=0;i<peers.length;i++) uids[i] = peers[i].swapIdentifier; return uids; } public synchronized double getLocChangeSession() { return locChangeSession; } public int getAverageSwapTime() { return (int) averageSwapTime.currentValue(); } public void receivedBytes(int x) { node.nodeStats.swappingReceivedBytes(x); } public void sentBytes(int x) { node.nodeStats.swappingSentBytes(x); } public void sentPayload(int x) { Logger.error(this, "LocationManager sentPayload()?", new Exception("debug")); } }

The table below shows all metrics for LocationManager.java.

MetricValueDescription
BLOCKS199.00Number of blocks
BLOCK_COMMENT 3.00Number of block comment lines
COMMENTS203.00Comment lines
COMMENT_DENSITY 0.24Comment density
COMPARISONS132.00Number of comparison operators
CYCLOMATIC262.00Cyclomatic complexity
DECL_COMMENTS32.00Comments in declarations
DOC_COMMENT130.00Number of javadoc comment lines
ELOC830.00Effective lines of code
EXEC_COMMENTS58.00Comments in executable code
EXITS135.00Procedure exits
FUNCTIONS51.00Number of function declarations
HALSTEAD_DIFFICULTY128.97Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY176.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 1.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 0.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 8.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA003486.00JAVA0034 Missing braces in if statement
JAVA0035 5.00JAVA0035 Missing braces in for statement
JAVA0036 1.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 2.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA007617.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 1.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 1.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 2.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 1.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA010819.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 1.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 0.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 0.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 8.00JAVA0116 Missing javadoc: field 'field'
JAVA011710.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 1.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 0.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 1.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 5.00JAVA0143 Synchronized method
JAVA014411.00JAVA0144 Line exceeds maximum M characters
JAVA0145545.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 3.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 3.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 1.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 4.00JAVA0177 Variable declaration missing initializer
JAVA0179 1.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 2.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 3.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 8.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 2.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES1386.00Number of lines in the source file
LINE_COMMENT70.00Number of line comments
LOC999.00Lines of code
LOGICAL_LINES626.00Number of statements
LOOPS24.00Number of loops
NEST_DEPTH11.00Maximum nesting depth
OPERANDS2771.00Number of operands
OPERATORS5447.00Number of operators
PARAMS72.00Number of formal parameter declarations
PROGRAM_LENGTH8218.00Halstead program length
PROGRAM_VOCAB775.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS104.00Number of return points from functions
SIZE55748.00Size of the file in bytes
UNIQUE_OPERANDS709.00Number of unique operands
UNIQUE_OPERATORS66.00Number of unique operators
WHITESPACE184.00Number of whitespace lines