DarknetPeerNode.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
LOGICAL_LINESNumber of statements
OPERATORSNumber of operators
PROGRAM_LENGTHHalstead program length
BLOCKSNumber of blocks
RETURNSNumber of return points from functions
CYCLOMATICCyclomatic complexity
OPERANDSNumber of operands
ELOCEffective lines of code
JAVA0034JAVA0034 Missing braces in if statement
LOCLines of code
FUNCTIONSNumber of function declarations
INTERFACE_COMPLEXITYInterface complexity
SIZESize of the file in bytes
UNIQUE_OPERANDSNumber of unique operands
PROGRAM_VOCABHalstead program vocabulary
LINESNumber of lines in the source file
JAVA0177JAVA0177 Variable declaration missing initializer
EXEC_COMMENTSComments in executable code
EXITSProcedure exits
JAVA0150JAVA0150 java.lang.Error (or subclass) thrown
COMPARISONSNumber of comparison operators
JAVA0145JAVA0145 Tab character used in source file
JAVA0117JAVA0117 Missing javadoc: method 'method'
JAVA0143JAVA0143 Synchronized method
PARAMSNumber of formal parameter declarations
LINE_COMMENTNumber of line comments
JAVA0144JAVA0144 Line exceeds maximum M characters
JAVA0025JAVA0025 Method override is empty
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
WHITESPACENumber of whitespace lines
JAVA0115JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
DECL_COMMENTSComments in declarations
UNIQUE_OPERATORSNumber of unique operators
JAVA0267JAVA0267 Use of System.err
JAVA0170JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0166JAVA0166 Generic exception caught
JAVA0128JAVA0128 Public constructor in non-public class
PROGRAM_VOLUMEHalstead program volume
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0126JAVA0126 Method declares unchecked exception in throws
LOOPSNumber of loops
JAVA0100JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0075JAVA0075 Method parameter hides field
NEST_DEPTHMaximum nesting depth
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
DOC_COMMENTNumber of javadoc comment lines
package freenet.node; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import freenet.client.DefaultMIMETypes; import freenet.io.comm.DMT; import freenet.io.comm.DisconnectedException; import freenet.io.comm.FreenetInetAddress; import freenet.io.comm.Message; import freenet.io.comm.NotConnectedException; import freenet.io.comm.Peer; import freenet.io.comm.PeerParseException; import freenet.io.comm.ReferenceSignatureVerificationException; import freenet.io.comm.RetrievalException; import freenet.io.xfer.BulkReceiver; import freenet.io.xfer.BulkTransmitter; import freenet.io.xfer.PartiallyReceivedBulk; import freenet.l10n.L10n; import freenet.node.useralerts.AbstractUserAlert; import freenet.node.useralerts.N2NTMUserAlert; import freenet.node.useralerts.UserAlert; import freenet.support.Base64; import freenet.support.Fields; import freenet.support.HTMLNode; import freenet.support.IllegalBase64Exception; import freenet.support.Logger; import freenet.support.SimpleFieldSet; import freenet.support.SizeUtil; import freenet.support.io.FileUtil; import freenet.support.io.RandomAccessFileWrapper; import freenet.support.io.RandomAccessThing; public class DarknetPeerNode extends PeerNode { /** Name of this node */ String myName; /** True if this peer is not to be connected with */ private boolean isDisabled; /** True if we don't send handshake requests to this peer, but will connect if we receive one */ private boolean isListenOnly; /** True if we send handshake requests to this peer in infrequent bursts */ private boolean isBurstOnly; /** True if we want to ignore the source port of the node's sent packets. * This is normally set when dealing with an Evil Corporate Firewall which rewrites the port on outgoing * packets but does not redirect incoming packets destined to the rewritten port. * What it does is this: If we have an address with the same IP but a different port, to the detectedPeer, * we use that instead. */ private boolean ignoreSourcePort; /** True if we want to allow LAN/localhost addresses. */ private boolean allowLocalAddresses; /** Extra peer data file numbers */ private LinkedHashSet extraPeerDataFileNumbers; /** Private comment on the peer for /friends/ page */ private String privateDarknetComment; /** Private comment on the peer for /friends/ page's extra peer data file number */ private int privateDarknetCommentFileNumber; /** Queued-to-send N2NM extra peer data file numbers */ private LinkedHashSet queuedToSendN2NMExtraPeerDataFileNumbers; private static boolean logMINOR; /** * Create a darknet PeerNode from a SimpleFieldSet * @param fs The SimpleFieldSet to parse * @param node2 The running Node we are part of. */ public DarknetPeerNode(SimpleFieldSet fs, Node node2, NodeCrypto crypto, PeerManager peers, boolean fromLocal, OutgoingPacketMangler mangler) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException { super(fs, node2, crypto, peers, fromLocal, false, mangler, false); logMINOR = Logger.shouldLog(Logger.MINOR, this); String name = fs.get("myName"); if(name == null) throw new FSParseException("No name"); myName = name; if(fromLocal) { SimpleFieldSet metadata = fs.subset("metadata"); isDisabled = Fields.stringToBool(metadata.get("isDisabled"), false); isListenOnly = Fields.stringToBool(metadata.get("isListenOnly"), false); isBurstOnly = Fields.stringToBool(metadata.get("isBurstOnly"), false); disableRouting = disableRoutingHasBeenSetLocally = Fields.stringToBool(metadata.get("disableRoutingHasBeenSetLocally"), false); ignoreSourcePort = Fields.stringToBool(metadata.get("ignoreSourcePort"), false); allowLocalAddresses = Fields.stringToBool(metadata.get("allowLocalAddresses"), false); } // Setup the private darknet comment note privateDarknetComment = ""; privateDarknetCommentFileNumber = -1; // Setup the extraPeerDataFileNumbers extraPeerDataFileNumbers = new LinkedHashSet(); // Setup the queuedToSendN2NMExtraPeerDataFileNumbers queuedToSendN2NMExtraPeerDataFileNumbers = new LinkedHashSet(); } /** * * Normally this is the address that packets have been received from from this node. * However, if ignoreSourcePort is set, we will search for a similar address with a different port * number in the node reference. */ public synchronized Peer getPeer(){ Peer detectedPeer = super.getPeer(); if(ignoreSourcePort) { FreenetInetAddress addr = detectedPeer == null ? null : detectedPeer.getFreenetAddress(); int port = detectedPeer == null ? -1 : detectedPeer.getPort(); if(nominalPeer == null) return detectedPeer; for(int i=0;i<nominalPeer.size();i++) { Peer p = (Peer) nominalPeer.get(i); if(p.getPort() != port && p.getFreenetAddress().equals(addr)) { return p; } } } return detectedPeer; } /** * @return True, if we are disconnected and it has been a * sufficient time period since we last sent a handshake * attempt. */ public boolean shouldSendHandshake() { synchronized(this) { if(isDisabled) return false; if(isListenOnly) return false; if(!super.shouldSendHandshake()) return false; } return true; } protected synchronized boolean innerProcessNewNoderef(SimpleFieldSet fs, boolean forARK, boolean forDiffNodeRef) throws FSParseException { boolean changedAnything = super.innerProcessNewNoderef(fs, forARK, forDiffNodeRef); String name = fs.get("myName"); if(name != null && !name.equals(myName)) { changedAnything = true; myName = name; } return changedAnything; } public synchronized SimpleFieldSet exportFieldSet() { SimpleFieldSet fs = super.exportFieldSet(); fs.putSingle("myName", getName()); return fs; } public synchronized SimpleFieldSet exportMetadataFieldSet() { SimpleFieldSet fs = super.exportMetadataFieldSet(); if(isDisabled) fs.putSingle("isDisabled", "true"); if(isListenOnly) fs.putSingle("isListenOnly", "true"); if(isBurstOnly) fs.putSingle("isBurstOnly", "true"); if(ignoreSourcePort) fs.putSingle("ignoreSourcePort", "true"); if(allowLocalAddresses) fs.putSingle("allowLocalAddresses", "true"); if(disableRoutingHasBeenSetLocally) fs.putSingle("disableRoutingHasBeenSetLocally", "true"); return fs; } public synchronized String getName() { return myName; } protected synchronized int getPeerNodeStatus(long now, long backedOffUntil) { if(isDisabled) { return PeerManager.PEER_NODE_STATUS_DISABLED; } int status = super.getPeerNodeStatus(now, backedOffUntil); if(status == PeerManager.PEER_NODE_STATUS_CONNECTED || status == PeerManager.PEER_NODE_STATUS_CLOCK_PROBLEM || status == PeerManager.PEER_NODE_STATUS_ROUTING_BACKED_OFF || status == PeerManager.PEER_NODE_STATUS_CONN_ERROR || status == PeerManager.PEER_NODE_STATUS_TOO_NEW || status == PeerManager.PEER_NODE_STATUS_TOO_OLD || status == PeerManager.PEER_NODE_STATUS_ROUTING_DISABLED || status == PeerManager.PEER_NODE_STATUS_DISCONNECTING) return status; if(isListenOnly) return PeerManager.PEER_NODE_STATUS_LISTEN_ONLY; if(isBurstOnly) return PeerManager.PEER_NODE_STATUS_LISTENING; return status; } public void enablePeer() { synchronized(this) { isDisabled = false; } setPeerNodeStatus(System.currentTimeMillis()); node.peers.writePeers(); } public void disablePeer() { synchronized(this) { isDisabled = true; } if(isConnected()) { forceDisconnect(true); } stopARKFetcher(); setPeerNodeStatus(System.currentTimeMillis()); node.peers.writePeers(); } public synchronized boolean isDisabled() { return isDisabled; } public void setListenOnly(boolean setting) { synchronized(this) { isListenOnly = setting; } if(setting && isBurstOnly()) { setBurstOnly(false); } if(setting) { stopARKFetcher(); } setPeerNodeStatus(System.currentTimeMillis()); node.peers.writePeers(); } public synchronized boolean isListenOnly() { return isListenOnly; } public void setBurstOnly(boolean setting) { synchronized(this) { isBurstOnly = setting; } if(setting && isListenOnly()) { setListenOnly(false); } long now = System.currentTimeMillis(); if(!setting) { synchronized(this) { sendHandshakeTime = now; // don't keep any long handshake delays we might have had under BurstOnly } } setPeerNodeStatus(now); node.peers.writePeers(); } public void setIgnoreSourcePort(boolean setting) { synchronized(this) { ignoreSourcePort = setting; } } /** * Change the routing status of a peer * * @param shouldRoute * @param localRequest (true everywhere but in NodeDispatcher) */ public void setRoutingStatus(boolean shouldRoute, boolean localRequest) { synchronized(this) { if(localRequest) disableRoutingHasBeenSetLocally = !shouldRoute; else disableRoutingHasBeenSetRemotely = !shouldRoute; disableRouting = disableRoutingHasBeenSetLocally || disableRoutingHasBeenSetRemotely; } if(localRequest) { Message msg = DMT.createRoutingStatus(shouldRoute); try { sendAsync(msg, null, 0, node.nodeStats.setRoutingStatusCtr); } catch(NotConnectedException e) { // ok } } setPeerNodeStatus(System.currentTimeMillis()); node.peers.writePeers(); } public boolean isIgnoreSourcePort() { return ignoreSourcePort; } public boolean isIgnoreSource() { return ignoreSourcePort; } public boolean isBurstOnly() { synchronized(this) { if(isBurstOnly) return true; } return super.isBurstOnly(); } public boolean allowLocalAddresses() { synchronized(this) { if(allowLocalAddresses) return true; } return super.allowLocalAddresses(); } public void setAllowLocalAddresses(boolean setting) { synchronized(this) { allowLocalAddresses = setting; } node.peers.writePeers(); } public boolean readExtraPeerData() { String extraPeerDataDirPath = node.getExtraPeerDataDir(); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { return false; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return false; } File[] extraPeerDataFiles = extraPeerDataPeerDir.listFiles(); if(extraPeerDataFiles == null) { return false; } boolean gotError = false; boolean readResult = false; for (int i = 0; i < extraPeerDataFiles.length; i++) { Integer fileNumber; try { fileNumber = new Integer(extraPeerDataFiles[i].getName()); } catch (NumberFormatException e) { gotError = true; continue; } synchronized(extraPeerDataFileNumbers) { extraPeerDataFileNumbers.add(fileNumber); } readResult = readExtraPeerDataFile(extraPeerDataFiles[i], fileNumber.intValue()); if(!readResult) { gotError = true; } } return !gotError; } public boolean rereadExtraPeerDataFile(int fileNumber) { if(logMINOR) Logger.minor(this, "Rereading peer data file "+fileNumber+" for "+shortToString()); String extraPeerDataDirPath = node.getExtraPeerDataDir(); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { Logger.error(this, "Extra peer data directory for peer does not exist: "+extraPeerDataPeerDir.getPath()); return false; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return false; } File extraPeerDataFile = new File(extraPeerDataDirPath+File.separator+getIdentityString()+File.separator+fileNumber); if(!extraPeerDataFile.exists()) { Logger.error(this, "Extra peer data file for peer does not exist: "+extraPeerDataFile.getPath()); return false; } return readExtraPeerDataFile(extraPeerDataFile, fileNumber); } public boolean readExtraPeerDataFile(File extraPeerDataFile, int fileNumber) { if(logMINOR) Logger.minor(this, "Reading "+extraPeerDataFile+" : "+fileNumber+" for "+shortToString()); boolean gotError = false; if(!extraPeerDataFile.exists()) { if(logMINOR) Logger.minor(this, "Does not exist"); return false; } Logger.normal(this, "extraPeerDataFile: "+extraPeerDataFile.getPath()); FileInputStream fis; try { fis = new FileInputStream(extraPeerDataFile); } catch (FileNotFoundException e1) { Logger.normal(this, "Extra peer data file not found: "+extraPeerDataFile.getPath()); return false; } InputStreamReader isr; try { isr = new InputStreamReader(fis, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } BufferedReader br = new BufferedReader(isr); SimpleFieldSet fs = null; try { // Read in the single SimpleFieldSet fs = new SimpleFieldSet(br, false, true); } catch (EOFException e3) { // End of file, fine } catch (IOException e4) { Logger.error(this, "Could not read extra peer data file: "+e4, e4); } finally { try { br.close(); } catch (IOException e5) { Logger.error(this, "Ignoring "+e5+" caught reading "+extraPeerDataFile.getPath(), e5); } } if(fs == null) { Logger.normal(this, "Deleting corrupt (too short?) file: "+extraPeerDataFile); deleteExtraPeerDataFile(fileNumber); return true; } boolean parseResult = false; try { parseResult = parseExtraPeerData(fs, extraPeerDataFile, fileNumber); if(!parseResult) { gotError = true; } } catch (FSParseException e2) { Logger.error(this, "Could not parse extra peer data: "+e2+ '\n' +fs.toString(),e2); gotError = true; } return !gotError; } private boolean parseExtraPeerData(SimpleFieldSet fs, File extraPeerDataFile, int fileNumber) throws FSParseException { String extraPeerDataTypeString = fs.get("extraPeerDataType"); int extraPeerDataType = -1; try { extraPeerDataType = Integer.parseInt(extraPeerDataTypeString); } catch (NumberFormatException e) { Logger.error(this, "NumberFormatException parsing extraPeerDataType ("+extraPeerDataTypeString+") in file "+extraPeerDataFile.getPath()); return false; } if(extraPeerDataType == Node.EXTRA_PEER_DATA_TYPE_N2NTM) { node.handleNodeToNodeTextMessageSimpleFieldSet(fs, this, fileNumber); return true; } else if(extraPeerDataType == Node.EXTRA_PEER_DATA_TYPE_PEER_NOTE) { String peerNoteTypeString = fs.get("peerNoteType"); int peerNoteType = -1; try { peerNoteType = Integer.parseInt(peerNoteTypeString); } catch (NumberFormatException e) { Logger.error(this, "NumberFormatException parsing peerNoteType ("+peerNoteTypeString+") in file "+extraPeerDataFile.getPath()); return false; } if(peerNoteType == Node.PEER_NOTE_TYPE_PRIVATE_DARKNET_COMMENT) { synchronized(privateDarknetComment) { try { privateDarknetComment = new String(Base64.decode(fs.get("privateDarknetComment"))); } catch (IllegalBase64Exception e) { Logger.error(this, "Bad Base64 encoding when decoding a private darknet comment SimpleFieldSet", e); return false; } privateDarknetCommentFileNumber = fileNumber; } return true; } Logger.error(this, "Read unknown peer note type '"+peerNoteType+"' from file "+extraPeerDataFile.getPath()); return false; } else if(extraPeerDataType == Node.EXTRA_PEER_DATA_TYPE_QUEUED_TO_SEND_N2NM) { boolean sendSuccess = false; int type = fs.getInt("n2nType"); if(isConnected()) { Message n2nm; if(fs.get("extraPeerDataType") != null) { fs.removeValue("extraPeerDataType"); } if(fs.get("senderFileNumber") != null) { fs.removeValue("senderFileNumber"); } fs.putOverwrite("senderFileNumber", String.valueOf(fileNumber)); if(fs.get("sentTime") != null) { fs.removeValue("sentTime"); } fs.putOverwrite("sentTime", Long.toString(System.currentTimeMillis())); try { n2nm = DMT.createNodeToNodeMessage(type, fs.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { Logger.error(this, "UnsupportedEncodingException processing extraPeerDataType ("+extraPeerDataTypeString+") in file "+extraPeerDataFile.getPath(), e); throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } try { synchronized(queuedToSendN2NMExtraPeerDataFileNumbers) { node.usm.send(this, n2nm, null); Logger.normal(this, "Sent queued ("+fileNumber+") N2NM to '"+getName()+"': "+n2nm); sendSuccess = true; queuedToSendN2NMExtraPeerDataFileNumbers.remove(new Integer(fileNumber)); } deleteExtraPeerDataFile(fileNumber); } catch (NotConnectedException e) { sendSuccess = false; // redundant, but clear } } if(!sendSuccess) { synchronized(queuedToSendN2NMExtraPeerDataFileNumbers) { fs.putOverwrite("extraPeerDataType", Integer.toString(extraPeerDataType)); fs.removeValue("sentTime"); queuedToSendN2NMExtraPeerDataFileNumbers.add(new Integer(fileNumber)); } } return true; } Logger.error(this, "Read unknown extra peer data type '"+extraPeerDataType+"' from file "+extraPeerDataFile.getPath()); return false; } public int writeNewExtraPeerDataFile(SimpleFieldSet fs, int extraPeerDataType) { String extraPeerDataDirPath = node.getExtraPeerDataDir(); if(extraPeerDataType > 0) fs.putOverwrite("extraPeerDataType", Integer.toString(extraPeerDataType)); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { if(!extraPeerDataPeerDir.mkdir()) { Logger.error(this, "Extra peer data directory for peer could not be created: "+extraPeerDataPeerDir.getPath()); return -1; } } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return -1; } Integer[] localFileNumbers; int nextFileNumber = 0; synchronized(extraPeerDataFileNumbers) { // Find the first free slot localFileNumbers = (Integer[]) extraPeerDataFileNumbers.toArray(new Integer[extraPeerDataFileNumbers.size()]); Arrays.sort(localFileNumbers); for (int i = 0; i < localFileNumbers.length; i++) { if(localFileNumbers[i].intValue() > nextFileNumber) { break; } nextFileNumber = localFileNumbers[i].intValue() + 1; } extraPeerDataFileNumbers.add(new Integer(nextFileNumber)); } FileOutputStream fos; File extraPeerDataFile = new File(extraPeerDataPeerDir.getPath()+File.separator+nextFileNumber); if(extraPeerDataFile.exists()) { Logger.error(this, "Extra peer data file already exists: "+extraPeerDataFile.getPath()); return -1; } String f = extraPeerDataFile.getPath(); try { fos = new FileOutputStream(f); } catch (FileNotFoundException e2) { Logger.error(this, "Cannot write extra peer data file to disk: Cannot create " + f + " - " + e2, e2); return -1; } OutputStreamWriter w; try { w = new OutputStreamWriter(fos, "UTF-8"); } catch (UnsupportedEncodingException e2) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e2, e2); } BufferedWriter bw = new BufferedWriter(w); try { fs.writeTo(bw); bw.close(); } catch (IOException e) { try { fos.close(); } catch (IOException e1) { Logger.error(this, "Cannot close extra peer data file: "+e, e); } Logger.error(this, "Cannot write file: " + e, e); return -1; } return nextFileNumber; } public void deleteExtraPeerDataFile(int fileNumber) { String extraPeerDataDirPath = node.getExtraPeerDataDir(); File extraPeerDataPeerDir = new File(extraPeerDataDirPath, getIdentityString()); if(!extraPeerDataPeerDir.exists()) { Logger.error(this, "Extra peer data directory for peer does not exist: "+extraPeerDataPeerDir.getPath()); return; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return; } File extraPeerDataFile = new File(extraPeerDataPeerDir, Integer.toString(fileNumber)); if(!extraPeerDataFile.exists()) { Logger.error(this, "Extra peer data file for peer does not exist: "+extraPeerDataFile.getPath()); return; } synchronized(extraPeerDataFileNumbers) { extraPeerDataFileNumbers.remove(new Integer(fileNumber)); } if(!extraPeerDataFile.delete()) { if(extraPeerDataFile.exists()) { Logger.error(this, "Cannot delete file "+extraPeerDataFile+" after sending message to "+getPeer()+" - it may be resent on resting the node"); } else { Logger.normal(this, "File does not exist when deleting: "+extraPeerDataFile+" after sending message to "+getPeer()); } } } public void removeExtraPeerDataDir() { String extraPeerDataDirPath = node.getExtraPeerDataDir(); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { Logger.error(this, "Extra peer data directory for peer does not exist: "+extraPeerDataPeerDir.getPath()); return; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return; } Integer[] localFileNumbers; synchronized(extraPeerDataFileNumbers) { localFileNumbers = (Integer[]) extraPeerDataFileNumbers.toArray(new Integer[extraPeerDataFileNumbers.size()]); } for (int i = 0; i < localFileNumbers.length; i++) { deleteExtraPeerDataFile(localFileNumbers[i].intValue()); } extraPeerDataPeerDir.delete(); } public boolean rewriteExtraPeerDataFile(SimpleFieldSet fs, int extraPeerDataType, int fileNumber) { String extraPeerDataDirPath = node.getExtraPeerDataDir(); if(extraPeerDataType > 0) fs.putOverwrite("extraPeerDataType", Integer.toString(extraPeerDataType)); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { Logger.error(this, "Extra peer data directory for peer does not exist: "+extraPeerDataPeerDir.getPath()); return false; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return false; } File extraPeerDataFile = new File(extraPeerDataDirPath+File.separator+getIdentityString()+File.separator+fileNumber); if(!extraPeerDataFile.exists()) { Logger.error(this, "Extra peer data file for peer does not exist: "+extraPeerDataFile.getPath()); return false; } String f = extraPeerDataFile.getPath(); FileOutputStream fos; try { fos = new FileOutputStream(f); } catch (FileNotFoundException e2) { Logger.error(this, "Cannot write extra peer data file to disk: Cannot open " + f + " - " + e2, e2); return false; } OutputStreamWriter w; try { w = new OutputStreamWriter(fos, "UTF-8"); } catch (UnsupportedEncodingException e2) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e2, e2); } BufferedWriter bw = new BufferedWriter(w); try { fs.writeTo(bw); bw.close(); } catch (IOException e) { try { fos.close(); } catch (IOException e1) { Logger.error(this, "Cannot close extra peer data file: "+e, e); } Logger.error(this, "Cannot write file: " + e, e); return false; } return true; } public synchronized String getPrivateDarknetCommentNote() { return privateDarknetComment; } public synchronized void setPrivateDarknetCommentNote(String comment) { int localFileNumber; synchronized(privateDarknetComment) { privateDarknetComment = comment; localFileNumber = privateDarknetCommentFileNumber; } SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("peerNoteType", Node.PEER_NOTE_TYPE_PRIVATE_DARKNET_COMMENT); try { fs.putSingle("privateDarknetComment", Base64.encode(comment.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } if(localFileNumber == -1) { localFileNumber = writeNewExtraPeerDataFile(fs, Node.EXTRA_PEER_DATA_TYPE_PEER_NOTE); synchronized(privateDarknetComment) { privateDarknetCommentFileNumber = localFileNumber; } } else { rewriteExtraPeerDataFile(fs, Node.EXTRA_PEER_DATA_TYPE_PEER_NOTE, localFileNumber); } } public void queueN2NM(SimpleFieldSet fs) { int fileNumber = writeNewExtraPeerDataFile( fs, Node.EXTRA_PEER_DATA_TYPE_QUEUED_TO_SEND_N2NM); synchronized(queuedToSendN2NMExtraPeerDataFileNumbers) { queuedToSendN2NMExtraPeerDataFileNumbers.add(new Integer(fileNumber)); } } public void sendQueuedN2NMs() { if(logMINOR) Logger.minor(this, "Sending queued N2NMs for "+shortToString()); Integer[] localFileNumbers; synchronized(queuedToSendN2NMExtraPeerDataFileNumbers) { localFileNumbers = (Integer[]) queuedToSendN2NMExtraPeerDataFileNumbers.toArray(new Integer[queuedToSendN2NMExtraPeerDataFileNumbers.size()]); } Arrays.sort(localFileNumbers); for (int i = 0; i < localFileNumbers.length; i++) { rereadExtraPeerDataFile(localFileNumbers[i].intValue()); } } void startARKFetcher() { synchronized(this) { if(isListenOnly) { Logger.minor(this, "Not starting ark fetcher for "+this+" as it's in listen-only mode."); return; } } super.startARKFetcher(); } public String getTMCIPeerInfo() { return getName()+'\t'+super.getTMCIPeerInfo(); } /** * A method to be called once at the beginning of every time isConnected() is true */ protected void onConnect() { sendQueuedN2NMs(); } // File transfer offers // FIXME this should probably be somewhere else, along with the N2NM stuff... but where? // FIXME this should be persistent across node restarts /** Files I have offered to this peer */ private final HashMap myFileOffersByUID = new HashMap(); /** Files this peer has offered to me */ private final HashMap hisFileOffersByUID = new HashMap(); private void storeOffers() { // FIXME do something } class FileOffer { final long uid; final String filename; final String mimeType; final String comment; private RandomAccessThing data; final long size; /** Who is offering it? True = I am offering it, False = I am being offered it */ final boolean amIOffering; private PartiallyReceivedBulk prb; private BulkTransmitter transmitter; private BulkReceiver receiver; /** True if the offer has either been accepted or rejected */ private boolean acceptedOrRejected; FileOffer(long uid, RandomAccessThing data, String filename, String mimeType, String comment) throws IOException { this.uid = uid; this.data = data; this.filename = filename; this.mimeType = mimeType; this.comment = comment; size = data.size(); amIOffering = true; } public FileOffer(SimpleFieldSet fs, boolean amIOffering) throws FSParseException { uid = fs.getLong("uid"); size = fs.getLong("size"); mimeType = fs.get("metadata.contentType"); filename = FileUtil.sanitize(fs.get("filename"), mimeType); String s = fs.get("comment"); if(s != null) { try { s = new String(Base64.decode(s), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } catch (IllegalBase64Exception e) { // Maybe it wasn't encoded? FIXME remove } } comment = s; this.amIOffering = amIOffering; } public void toFieldSet(SimpleFieldSet fs) { fs.put("uid", uid); fs.putSingle("filename", filename); fs.putSingle("metadata.contentType", mimeType); try { fs.putSingle("comment", Base64.encode(comment.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } fs.put("size", size); } public void accept() { acceptedOrRejected = true; File dest = new File(node.clientCore.downloadDir, "direct-"+FileUtil.sanitize(getName())+"-"+filename); try { data = new RandomAccessFileWrapper(dest, "rw"); } catch (FileNotFoundException e) { // Impossible throw new Error("Impossible: FileNotFoundException opening with RAF with rw! "+e, e); } prb = new PartiallyReceivedBulk(node.usm, size, Node.PACKET_SIZE, data, false); receiver = new BulkReceiver(prb, DarknetPeerNode.this, uid, null); // FIXME make this persistent node.executor.execute(new Runnable() { public void run() { if(logMINOR) Logger.minor(this, "Received file"); try { if(!receiver.receive()) { String err = "Failed to receive "+this; Logger.error(this, err); System.err.println(err); onReceiveFailure(); } else { onReceiveSuccess(); } } catch (Throwable t) { Logger.error(this, "Caught "+t+" receiving file", t); onReceiveFailure(); } finally { remove(); } if(logMINOR) Logger.minor(this, "Received file"); } }, "Receiver for bulk transfer "+uid+":"+filename); sendFileOfferAccepted(uid); } protected void remove() { Long l = new Long(uid); synchronized(DarknetPeerNode.this) { myFileOffersByUID.remove(l); hisFileOffersByUID.remove(l); } data.close(); } public void send() throws DisconnectedException { prb = new PartiallyReceivedBulk(node.usm, size, Node.PACKET_SIZE, data, true); transmitter = new BulkTransmitter(prb, DarknetPeerNode.this, uid, false, node.nodeStats.nodeToNodeCounter); if(logMINOR) Logger.minor(this, "Sending "+uid); node.executor.execute(new Runnable() { public void run() { if(logMINOR) Logger.minor(this, "Sending file"); try { if(!transmitter.send()) { String err = "Failed to send "+uid+" for "+FileOffer.this; Logger.error(this, err); System.err.println(err); } } catch (Throwable t) { Logger.error(this, "Caught "+t+" sending file", t); remove(); } if(logMINOR) Logger.minor(this, "Sent file"); } }, "Sender for bulk transfer "+uid+":"+filename); } public void reject() { acceptedOrRejected = true; sendFileOfferRejected(uid); } public void onRejected() { transmitter.cancel("FileOffer: Offer rejected"); // FIXME prb's can't be shared, right? Well they aren't here... prb.abort(RetrievalException.CANCELLED_BY_RECEIVER, "Cancelled by receiver"); } protected void onReceiveFailure() { UserAlert alert = new AbstractUserAlert() { public String dismissButtonText() { return L10n.getString("UserAlert.hide"); } public HTMLNode getHTMLText() { HTMLNode div = new HTMLNode("div"); div.addChild("p", l10n("failedReceiveHeader", new String[] { "filename", "node" }, new String[] { filename, getName() })); // Descriptive table HTMLNode table = div.addChild("table", "border", "0"); HTMLNode row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("fileLabel")); row.addChild("td").addChild("#", filename); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("sizeLabel")); row.addChild("td").addChild("#", SizeUtil.formatSize(size)); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("mimeLabel")); row.addChild("td").addChild("#", mimeType); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("senderLabel")); row.addChild("td").addChild("#", getName()); row = table.addChild("tr"); if(comment != null && comment.length() > 0) { row.addChild("td").addChild("#", l10n("commentLabel")); addComment(row.addChild("td")); } return div; } public short getPriorityClass() { return UserAlert.MINOR; } public String getText() { StringBuffer sb = new StringBuffer(); sb.append(l10n("failedReceiveHeader", new String[] { "filename", "node" }, new String[] { filename, getName() })); sb.append('\n'); sb.append(l10n("fileLabel")); sb.append(' '); sb.append(filename); sb.append('\n'); sb.append(l10n("sizeLabel")); sb.append(' '); sb.append(SizeUtil.formatSize(size)); sb.append('\n'); sb.append(l10n("mimeLabel")); sb.append(' '); sb.append(mimeType); sb.append('\n'); sb.append(l10n("senderLabel")); sb.append(' '); sb.append(getName()); sb.append('\n'); if(comment != null && comment.length() > 0) { sb.append(l10n("commentLabel")); sb.append(' '); sb.append(comment); } return sb.toString(); } public String getTitle() { return l10n("failedReceiveTitle"); } public boolean isValid() { return true; } public void isValid(boolean validity) { // Ignore } public void onDismiss() { // Ignore } public boolean shouldUnregisterOnDismiss() { return true; } public boolean userCanDismiss() { return true; } public String getShortText() { return l10n("failedReceiveShort", new String[] { "filename", "node" }, new String[] { filename, getName() }); } }; node.clientCore.alerts.register(alert); } private void onReceiveSuccess() { UserAlert alert = new AbstractUserAlert() { public String dismissButtonText() { return L10n.getString("UserAlert.hide"); } public HTMLNode getHTMLText() { HTMLNode div = new HTMLNode("div"); // FIXME localise!!! div.addChild("p", l10n("succeededReceiveHeader", new String[] { "filename", "node" }, new String[] { filename, getName() })); // Descriptive table HTMLNode table = div.addChild("table", "border", "0"); HTMLNode row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("fileLabel")); row.addChild("td").addChild("#", filename); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("sizeLabel")); row.addChild("td").addChild("#", SizeUtil.formatSize(size)); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("mimeLabel")); row.addChild("td").addChild("#", mimeType); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("senderLabel")); row.addChild("td").addChild("#", getName()); row = table.addChild("tr"); if(comment != null && comment.length() > 0) { row.addChild("td").addChild("#", l10n("commentLabel")); addComment(row.addChild("td")); } return div; } public short getPriorityClass() { return UserAlert.MINOR; } public String getText() { StringBuffer sb = new StringBuffer(); sb.append(l10n("succeededReceiveHeader", new String[] { "filename", "node" }, new String[] { filename, getName() })); sb.append('\n'); sb.append(l10n("fileLabel")); sb.append(' '); sb.append(filename); sb.append('\n'); sb.append(l10n("sizeLabel")); sb.append(' '); sb.append(SizeUtil.formatSize(size)); sb.append('\n'); sb.append(l10n("mimeLabel")); sb.append(' '); sb.append(mimeType); sb.append('\n'); sb.append(l10n("senderLabel")); sb.append(' '); sb.append(userToString()); sb.append('\n'); if(comment != null && comment.length() > 0) { sb.append(l10n("commentLabel")); sb.append(' '); sb.append(comment); } return sb.toString(); } public String getTitle() { return l10n("succeededReceiveTitle"); } public boolean isValid() { return true; } public void isValid(boolean validity) { // Ignore } public void onDismiss() { // Ignore } public boolean shouldUnregisterOnDismiss() { return true; } public boolean userCanDismiss() { return true; } public String getShortText() { return l10n("succeededReceiveShort", new String[] { "filename", "node" }, new String[] { filename, getName() }); } }; node.clientCore.alerts.register(alert); } /** Ask the user whether (s)he wants to download a file from a direct peer */ public UserAlert askUserUserAlert() { return new AbstractUserAlert() { public String dismissButtonText() { return null; // Cannot hide, but can reject } public HTMLNode getHTMLText() { HTMLNode div = new HTMLNode("div"); div.addChild("p", l10n("offeredFileHeader", "name", getName())); // Descriptive table HTMLNode table = div.addChild("table", "border", "0"); HTMLNode row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("fileLabel")); row.addChild("td").addChild("#", filename); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("sizeLabel")); row.addChild("td").addChild("#", SizeUtil.formatSize(size)); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("mimeLabel")); row.addChild("td").addChild("#", mimeType); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("senderLabel")); row.addChild("td").addChild("#", getName()); row = table.addChild("tr"); if(comment != null && comment.length() > 0) { row.addChild("td").addChild("#", l10n("commentLabel")); addComment(row.addChild("td")); } // Accept/reject form // Hopefully we will have a container when this function is called! HTMLNode form = node.clientCore.getToadletContainer().addFormChild(div, "/friends/", "f2fFileOfferAcceptForm"); // FIXME node_ is inefficient form.addChild("input", new String[] { "type", "name" }, new String[] { "hidden", "node_"+DarknetPeerNode.this.hashCode() }); form.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "id", Long.toString(uid) }); form.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "acceptTransfer", l10n("acceptTransferButton") }); form.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "rejectTransfer", l10n("rejectTransferButton") }); return div; } public short getPriorityClass() { return UserAlert.MINOR; } public String getText() { StringBuffer sb = new StringBuffer(); sb.append(l10n("offeredFileHeader", "name", getName())); sb.append('\n'); sb.append(l10n("fileLabel")); sb.append(' '); sb.append(filename); sb.append('\n'); sb.append(l10n("sizeLabel")); sb.append(' '); sb.append(SizeUtil.formatSize(size)); sb.append('\n'); sb.append(l10n("mimeLabel")); sb.append(' '); sb.append(mimeType); sb.append('\n'); sb.append(l10n("senderLabel")); sb.append(' '); sb.append(userToString()); sb.append('\n'); if(comment != null && comment.length() > 0) { sb.append(l10n("commentLabel")); sb.append(' '); sb.append(comment); } return sb.toString(); } public String getTitle() { return l10n("askUserTitle"); } public boolean isValid() { if(acceptedOrRejected) { node.clientCore.alerts.unregister(this); return false; } return true; } public void isValid(boolean validity) { // Ignore } public void onDismiss() { // Ignore } public boolean shouldUnregisterOnDismiss() { return false; } public boolean userCanDismiss() { return false; // should accept or reject } public String getShortText() { return l10n("offeredFileShort", new String[] { "filename", "node" }, new String[] { filename, getName() }); } }; } protected void addComment(HTMLNode node) { String[] lines = comment.split("\n"); for (int i = 0, c = lines.length; i < c; i++) { node.addChild("#", lines[i]); if(i != lines.length - 1) node.addChild("br"); } } private String l10n(String key) { return L10n.getString("FileOffer."+key); } private String l10n(String key, String pattern, String value) { return L10n.getString("FileOffer."+key, pattern, value); } private String l10n(String key, String[] pattern, String[] value) { return L10n.getString("FileOffer."+key, pattern, value); } } public int sendTextMessage(String message) { long now = System.currentTimeMillis(); SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_USERALERT); try { fs.putSingle("source_nodename", Base64.encode(node.getMyName().getBytes("UTF-8"))); fs.putSingle("target_nodename", Base64.encode(getName().getBytes("UTF-8"))); fs.putSingle("text", Base64.encode(message.getBytes("UTF-8"))); fs.put("composedTime", now); sendNodeToNodeMessage(fs, Node.N2N_MESSAGE_TYPE_FPROXY, true, now, true); this.setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } } public int sendFileOfferAccepted(long uid) { // FIXME: perhaps can be refactored to use sendNodeToNodeMessage() storeOffers(); long now = System.currentTimeMillis(); SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("n2nType", Node.N2N_MESSAGE_TYPE_FPROXY); fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_ACCEPTED); try { fs.putSingle("source_nodename", Base64.encode(node.getMyName().getBytes("UTF-8"))); fs.putSingle("target_nodename", Base64.encode(getName().getBytes("UTF-8"))); fs.put("composedTime", now); fs.put("sentTime", now); fs.put("uid", uid); if(logMINOR) Logger.minor(this, "Sending node to node message (file offer accepted):\n"+fs); Message n2ntm; n2ntm = DMT.createNodeToNodeMessage( Node.N2N_MESSAGE_TYPE_FPROXY, fs .toString().getBytes("UTF-8")); try { sendAsync(n2ntm, null, 0, node.nodeStats.nodeToNodeCounter); } catch (NotConnectedException e) { fs.removeValue("sentTime"); queueN2NM(fs); setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } this.setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } } public int sendFileOfferRejected(long uid) { // FIXME: perhaps can be refactored to use sendNodeToNodeMessage() storeOffers(); long now = System.currentTimeMillis(); SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("n2nType", Node.N2N_MESSAGE_TYPE_FPROXY); fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_REJECTED); try { fs.putSingle("source_nodename", Base64.encode(node.getMyName().getBytes("UTF-8"))); fs.putSingle("target_nodename", Base64.encode(getName().getBytes("UTF-8"))); fs.put("composedTime", now); fs.put("sentTime", now); fs.put("uid", uid); if(logMINOR) Logger.minor(this, "Sending node to node message (file offer rejected):\n"+fs); Message n2ntm; n2ntm = DMT.createNodeToNodeMessage( Node.N2N_MESSAGE_TYPE_FPROXY, fs .toString().getBytes("UTF-8")); try { sendAsync(n2ntm, null, 0, node.nodeStats.nodeToNodeCounter); } catch (NotConnectedException e) { fs.removeValue("sentTime"); queueN2NM(fs); setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } this.setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } } public int sendFileOffer(File filename, String message) throws IOException { // FIXME: perhaps can be refactored to use sendNodeToNodeMessage() String fnam = filename.getName(); String mime = DefaultMIMETypes.guessMIMEType(fnam, false); long uid = node.random.nextLong(); RandomAccessThing data = new RandomAccessFileWrapper(filename, "r"); FileOffer fo = new FileOffer(uid, data, fnam, mime, message); synchronized(this) { myFileOffersByUID.put(new Long(uid), fo); } storeOffers(); long now = System.currentTimeMillis(); SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("n2nType", Node.N2N_MESSAGE_TYPE_FPROXY); fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER); try { fs.putSingle("source_nodename", Base64.encode(node.getMyName().getBytes("UTF-8"))); fs.putSingle("target_nodename", Base64.encode(getName().getBytes("UTF-8"))); fs.put("composedTime", now); fs.put("sentTime", now); fo.toFieldSet(fs); if(logMINOR) Logger.minor(this, "Sending node to node message (file offer):\n"+fs); Message n2ntm; int status = getPeerNodeStatus(); n2ntm = DMT.createNodeToNodeMessage( Node.N2N_MESSAGE_TYPE_FPROXY, fs .toString().getBytes("UTF-8")); try { sendAsync(n2ntm, null, 0, node.nodeStats.nodeToNodeCounter); } catch (NotConnectedException e) { fs.removeValue("sentTime"); queueN2NM(fs); setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } return status; } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } } public void handleFproxyN2NTM(SimpleFieldSet fs, int fileNumber) { String source_nodename = null; String target_nodename = null; String text = null; long composedTime; long sentTime; long receivedTime; try { source_nodename = new String(Base64.decode(fs.get("source_nodename"))); target_nodename = new String(Base64.decode(fs.get("target_nodename"))); text = new String(Base64.decode(fs.get("text"))); composedTime = fs.getLong("composedTime", -1); sentTime = fs.getLong("sentTime", -1); receivedTime = fs.getLong("receivedTime", -1); } catch (IllegalBase64Exception e) { Logger.error(this, "Bad Base64 encoding when decoding a N2NTM SimpleFieldSet", e); return; } N2NTMUserAlert userAlert = new N2NTMUserAlert(this, source_nodename, target_nodename, text, fileNumber, composedTime, sentTime, receivedTime); node.clientCore.alerts.register(userAlert); } public void handleFproxyFileOffer(SimpleFieldSet fs, int fileNumber) { final FileOffer offer; try { offer = new FileOffer(fs, false); } catch (FSParseException e) { Logger.error(this, "Could not parse offer: "+e+" on "+this+" :\n"+fs, e); return; } Long u = new Long(offer.uid); synchronized(this) { if(hisFileOffersByUID.containsKey(u)) return; // Ignore re-advertisement hisFileOffersByUID.put(u, offer); } // Don't persist for now - FIXME this.deleteExtraPeerDataFile(fileNumber); UserAlert alert = offer.askUserUserAlert(); node.clientCore.alerts.register(alert); } public void acceptTransfer(long id) { if(logMINOR) Logger.minor(this, "Accepting transfer "+id+" on "+this); FileOffer fo; synchronized(this) { fo = (FileOffer) hisFileOffersByUID.get(new Long(id)); } fo.accept(); } public void rejectTransfer(long id) { FileOffer fo; synchronized(this) { fo = (FileOffer) hisFileOffersByUID.remove(new Long(id)); } fo.reject(); } public void handleFproxyFileOfferAccepted(SimpleFieldSet fs, int fileNumber) { // Don't persist for now - FIXME this.deleteExtraPeerDataFile(fileNumber); long uid; try { uid = fs.getLong("uid"); } catch (FSParseException e) { Logger.error(this, "Could not parse offer accepted: "+e+" on "+this+" :\n"+fs, e); return; } if(logMINOR) Logger.minor(this, "Offer accepted for "+uid); Long u = new Long(uid); FileOffer fo; synchronized(this) { fo = (FileOffer) (myFileOffersByUID.get(u)); } if(fo == null) { Logger.error(this, "No such offer: "+uid); try { sendAsync(DMT.createFNPBulkSendAborted(uid), null, 0, node.nodeStats.nodeToNodeCounter); } catch (NotConnectedException e) { // Fine by me! } return; } try { fo.send(); } catch (DisconnectedException e) { Logger.error(this, "Cannot send because node disconnected: "+e+" for "+uid+":"+fo.filename, e); } } public void handleFproxyFileOfferRejected(SimpleFieldSet fs, int fileNumber) { // Don't persist for now - FIXME this.deleteExtraPeerDataFile(fileNumber); long uid; try { uid = fs.getLong("uid"); } catch (FSParseException e) { Logger.error(this, "Could not parse offer rejected: "+e+" on "+this+" :\n"+fs, e); return; } FileOffer fo; synchronized(this) { fo = (FileOffer) myFileOffersByUID.remove(new Long(uid)); } fo.onRejected(); } public String userToString() { return ""+getPeer()+" : "+getName(); } public PeerNodeStatus getStatus(boolean noHeavy) { return new DarknetPeerNodeStatus(this, noHeavy); } public boolean isDarknet() { return true; } public boolean isOpennet() { return false; } public void onSuccess(boolean insert, boolean ssk) { // Ignore it } public void onRemove() { // Do nothing // FIXME is there anything we should do? } public boolean isRealConnection() { return true; } public boolean recordStatus() { return true; } protected boolean generateIdentityFromPubkey() { return false; } public boolean equals(Object o) { if(o == this) return true; // Only equal to seednode of its own type. if(o instanceof DarknetPeerNode) { return super.equals(o); } else return false; } public final boolean shouldDisconnectAndRemoveNow() { return false; } }

The table below shows all metrics for DarknetPeerNode.java.

MetricValueDescription
BLOCKS288.00Number of blocks
BLOCK_COMMENT 0.00Number of block comment lines
COMMENTS83.00Comment lines
COMMENT_DENSITY 0.08Comment density
COMPARISONS124.00Number of comparison operators
CYCLOMATIC270.00Cyclomatic complexity
DECL_COMMENTS21.00Comments in declarations
DOC_COMMENT44.00Number of javadoc comment lines
ELOC1069.00Effective lines of code
EXEC_COMMENTS35.00Comments in executable code
EXITS135.00Procedure exits
FUNCTIONS108.00Number of function declarations
HALSTEAD_DIFFICULTY117.08Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY250.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 0.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 7.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
JAVA003438.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.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 0.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 1.00JAVA0075 Method parameter hides field
JAVA0076 0.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 0.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 0.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 0.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
JAVA0108 4.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 2.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 0.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 3.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA011738.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 1.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 1.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 1.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
JAVA014310.00JAVA0143 Synchronized method
JAVA0144 9.00JAVA0144 Line exceeds maximum M characters
JAVA01454205.00JAVA0145 Tab character used in source file
JAVA015012.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 2.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 2.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 0.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
JAVA017725.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.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 0.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 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 2.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 4.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 0.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
LINES1542.00Number of lines in the source file
LINE_COMMENT39.00Number of line comments
LOC1310.00Lines of code
LOGICAL_LINES736.00Number of statements
LOOPS 6.00Number of loops
NEST_DEPTH 5.00Maximum nesting depth
OPERANDS3159.00Number of operands
OPERATORS6206.00Number of operators
PARAMS69.00Number of formal parameter declarations
PROGRAM_LENGTH9365.00Halstead program length
PROGRAM_VOCAB797.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS181.00Number of return points from functions
SIZE50292.00Size of the file in bytes
UNIQUE_OPERANDS742.00Number of unique operands
UNIQUE_OPERATORS55.00Number of unique operators
WHITESPACE149.00Number of whitespace lines