X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;f=src%2Fnet%2Fpterodactylus%2Futil%2Ffcp%2FFcpConnection.java;h=32237f45449f7b0c0095f038569d69504096ef8b;hb=3b855e85f744b958b5aa74a5a7bb33e76fdee57e;hp=1b4d249791d5b98e1df7f1c550291f4002f544fc;hpb=90f3a1c8e0c85f19c82130e49d7a605cb9e55286;p=jSite2.git diff --git a/src/net/pterodactylus/util/fcp/FcpConnection.java b/src/net/pterodactylus/util/fcp/FcpConnection.java index 1b4d249..32237f4 100644 --- a/src/net/pterodactylus/util/fcp/FcpConnection.java +++ b/src/net/pterodactylus/util/fcp/FcpConnection.java @@ -26,260 +26,302 @@ import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.Map.Entry; import net.pterodactylus.util.io.Closer; /** - * TODO + * An FCP connection to a Freenet node. * * @author David ‘Bombe’ Roden <bombe@freenetproject.org> * @version $Id$ */ public class FcpConnection { + /** The default port for FCP v2. */ public static final int DEFAULT_PORT = 9481; - private final Object messageWaitSync = new Object(); - private FcpMessage receivedMessage = null; - + /** The list of FCP listeners. */ private final List fcpListeners = new ArrayList(); + /** The address of the node. */ private final InetAddress address; + + /** The port number of the node’s FCP port. */ private final int port; - private final String clientName; + /** The remote socket. */ private Socket remoteSocket; + + /** The input stream from the node. */ private InputStream remoteInputStream; + + /** The output stream to the node. */ private OutputStream remoteOutputStream; - private boolean connected; - public FcpConnection(String host, String clientName) throws UnknownHostException { - this(host, DEFAULT_PORT, clientName); + /** The connection handler. */ + private FcpConnectionHandler connectionHandler; + + /** + * Creates a new FCP connection to the Freenet node running on the given + * host, listening on the default port. + * + * @param host + * The hostname of the Freenet node + * @throws UnknownHostException + * if host can not be resolved + */ + public FcpConnection(String host) throws UnknownHostException { + this(host, DEFAULT_PORT); } - public FcpConnection(String host, int port, String clientName) throws UnknownHostException { - this(InetAddress.getByName(host), port, clientName); + /** + * Creates a new FCP connection to the Freenet node running on the given + * host, listening on the given port. + * + * @param host + * The hostname of the Freenet node + * @param port + * The port number of the node’s FCP port + * @throws UnknownHostException + * if host can not be resolved + */ + public FcpConnection(String host, int port) throws UnknownHostException { + this(InetAddress.getByName(host), port); } - public FcpConnection(InetAddress address, String clientName) { - this(address, DEFAULT_PORT, clientName); + /** + * Creates a new FCP connection to the Freenet node running at the given + * address, listening on the default port. + * + * @param address + * The address of the Freenet node + */ + public FcpConnection(InetAddress address) { + this(address, DEFAULT_PORT); } - public FcpConnection(InetAddress address, int port, String clientName) { + /** + * Creates a new FCP connection to the Freenet node running at the given + * address, listening on the given port. + * + * @param address + * The address of the Freenet node + * @param port + * The port number of the node’s FCP port + */ + public FcpConnection(InetAddress address, int port) { this.address = address; this.port = port; - this.clientName = clientName; } // // LISTENER MANAGEMENT // + /** + * Adds the given listener to the list of listeners. + * + * @param fcpListener + * The listener to add + */ public void addFcpListener(FcpListener fcpListener) { fcpListeners.add(fcpListener); } + /** + * Removes the given listener from the list of listeners. + * + * @param fcpListener + * The listener to remove + */ public void removeFcpListener(FcpListener fcpListener) { fcpListeners.remove(fcpListener); } - private void fireNodeHello(Map nodeProperties) { + /** + * Notifies listeners that a “NodeHello” message was received. + * + * @see FcpListener#receivedNodeHello(FcpConnection, NodeHello) + * @param nodeHello + * The “NodeHello” message + */ + private void fireReceivedNodeHello(NodeHello nodeHello) { for (FcpListener fcpListener: fcpListeners) { - fcpListener.fcpNodeHello(this, nodeProperties); + fcpListener.receivedNodeHello(this, nodeHello); } } - // - // ACTIONS - // - - public synchronized void connect() throws FcpException, IOException { - System.out.println("connecting..."); - remoteSocket = new Socket(address, port); - remoteInputStream = remoteSocket.getInputStream(); - remoteOutputStream = remoteSocket.getOutputStream(); - connected = true; - System.out.println("connected."); - new Thread(new FcpConnectionHandler(this, remoteInputStream)).start(); - sendMessage(clientHelloMessage); + /** + * Notifies listeners that a “CloseConnectionDuplicateClientName” message + * was received. + * + * @see FcpListener#receivedCloseConnectionDuplicateClientName(FcpConnection, + * CloseConnectionDuplicateClientName) + * @param closeConnectionDuplicateClientName + * The “CloseConnectionDuplicateClientName” message + */ + private void fireReceivedCloseConnectionDuplicateClientName(CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) { + for (FcpListener fcpListener: fcpListeners) { + fcpListener.receivedCloseConnectionDuplicateClientName(this, closeConnectionDuplicateClientName); + } } - public synchronized void disconnect() { - connected = false; - Closer.close(remoteSocket); + /** + * Notifies listeners that a “SSKKeypair” message was received. + * + * @see FcpListener#receivedSSKKeypair(FcpConnection, SSKKeypair) + * @param sskKeypair + * The “SSKKeypair” message + */ + private void fireReceivedSSKKeypair(SSKKeypair sskKeypair) { + for (FcpListener fcpListener: fcpListeners) { + fcpListener.receivedSSKKeypair(this, sskKeypair); + } } /** - * Sends a “ListPeer” command to the node and returns the properties of the - * peer. + * Notifies listeners that a “Peer” message was received. * - * @param nodeIdentifier - * The name (except for OpenNet nodes), the identity or the - * node’s “address:port” pair - * @return The properties of the peer, or null if the peer is - * unknown - * @throws IOException - * @throws FcpException + * @see FcpListener#receivedPeer(FcpConnection, Peer) + * @param peer + * The “Peer” message */ - public Map sendListPeer(String nodeIdentifier) throws IOException, FcpException { - FcpMessage listPeerMessage = new FcpMessage("ListPeer"); - listPeerMessage.setField("NodeIdentifier", nodeIdentifier); - sendMessage(listPeerMessage); - FcpMessage returnMessage = waitForMessage("Peer", "UnknownNodeIdentifier"); - if (returnMessage.getName().equals("Peer")) { - return returnMessage.getFields(); + private void fireReceivedPeer(Peer peer) { + for (FcpListener fcpListener: fcpListeners) { + fcpListener.receivedPeer(this, peer); } - return null; } - - public List> sendListPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException { - FcpMessage listPeersMessage = new FcpMessage("ListPeers"); - listPeersMessage.setField("WithMetadata", String.valueOf(withMetadata)); - listPeersMessage.setField("WithVolatile", String.valueOf(withVolatile)); - sendMessage(listPeersMessage); - List> peers = new ArrayList>(); - while (true) { - FcpMessage returnMessage = waitForMessage("Peer", "EndListPeers"); - if (returnMessage.getName().equals("EndListPeers")) { - break; - } - peers.add(returnMessage.getFields()); + + /** + * Notifies all listeners that an “EndListPeers” message was received. + * + * @see FcpListener#receivedEndListPeers(FcpConnection, EndListPeers) + * @param endListPeers + * The “EndListPeers” message + */ + private void fireReceivedEndListPeers(EndListPeers endListPeers) { + for (FcpListener fcpListener: fcpListeners) { + fcpListener.receivedEndListPeers(this, endListPeers); } - return peers; } - public List> sendListPeerNotes(String nodeIdentifier) throws IOException, FcpException { - FcpMessage listPeerNotesMessage = new FcpMessage("ListPeerNotes"); - listPeerNotesMessage.setField("NodeIdentifier", nodeIdentifier); - sendMessage(listPeerNotesMessage); - List> peerNotes = new ArrayList>(); - while (true) { - FcpMessage returnMessage = waitForMessage("PeerNote", "EndListPeerNotes"); - if (returnMessage.getName().equals("EndListPeerNotes")) { - break; - } - peerNotes.add(returnMessage.getFields()); + /** + * Notifies all listeners that a “PeerNote” message was received. + * + * @see FcpListener#receviedPeerNote(FcpConnection, PeerNote) + * @param peerNote + */ + private void fireReceivedPeerNote(PeerNote peerNote) { + for (FcpListener fcpListener: fcpListeners) { + fcpListener.receviedPeerNote(this, peerNote); } - return peerNotes; } - - public void sendTestDDARequest(String directory, boolean wantReadDirectory, boolean wantWriteDirectory) throws IOException, FcpException { - FcpMessage testDDARequestMessage = new FcpMessage("TestDDARequest"); - testDDARequestMessage.setField("Directory", directory); - testDDARequestMessage.setField("WantReadDirectory", String.valueOf(wantReadDirectory)); - testDDARequestMessage.setField("WantWriteDirectory", String.valueOf(wantWriteDirectory)); - sendMessage(testDDARequestMessage); + + /** + * Notifies all listeners that an “EndListPeerNotes” message was received. + * + * @see FcpListener#receivedEndListPeerNotes(FcpConnection, + * EndListPeerNotes) + * @param endListPeerNotes + * The “EndListPeerNotes” message + */ + private void fireReceivedEndListPeerNotes(EndListPeerNotes endListPeerNotes) { + for (FcpListener fcpListener: fcpListeners) { + fcpListener.receivedEndListPeerNotes(this, endListPeerNotes); + } } - - public FcpKeyPair generateSSK() throws IOException, FcpException { - FcpMessage generateSSKMessage = new FcpMessage("GenerateSSK"); - String identifier = hashCode() + String.valueOf(System.currentTimeMillis()); - generateSSKMessage.setField("Identifier", identifier); - sendMessage(generateSSKMessage); - FcpMessage returnMessage = waitForMessage("SSKKeypair(Identifier=" + identifier + ")"); - String publicKey = returnMessage.getField("RequestURI"); - String privateKey = returnMessage.getField("InsertURI"); - return new FcpKeyPair(publicKey, privateKey); + + /** + * Notifies all registered listeners that a message has been received. + * + * @see FcpListener#receivedMessage(FcpConnection, FcpMessage) + * @param fcpMessage + * The message that was received + */ + private void fireMessageReceived(FcpMessage fcpMessage) { + for (FcpListener fcpListener: fcpListeners) { + fcpListener.receivedMessage(this, fcpMessage); + } } - + // - // PACKAGE-PRIVATE METHODS + // ACTIONS // - void handleMessage(FcpMessage fcpMessage) { - synchronized (messageWaitSync) { - while (receivedMessage != null) { - /* previous message has not yet been consumed */ - System.out.println("waiting for message to be consumed..."); - try { - messageWaitSync.wait(); - } catch (InterruptedException ie1) { - } - } - /* TODO - check whether to send events here or later. */ - if ("NodeHello".equals(fcpMessage.getName())) { - fireNodeHello(fcpMessage.getFields()); - } - System.out.println("setting receivedMessage"); - receivedMessage = fcpMessage; - messageWaitSync.notifyAll(); + /** + * Connects to the node. + * + * @throws IOException + * if an I/O error occurs + * @throws IllegalStateException + * if there is already a connection to the node + */ + public synchronized void connect() throws IOException, IllegalStateException { + if (connectionHandler != null) { + throw new IllegalStateException("already connected, disconnect first"); } + remoteSocket = new Socket(address, port); + remoteInputStream = remoteSocket.getInputStream(); + remoteOutputStream = remoteSocket.getOutputStream(); + new Thread(connectionHandler = new FcpConnectionHandler(this, remoteInputStream)).start(); } - // - // PRIVATE METHODS - // + /** + * Disconnects from the node. If there is no connection to the node, this + * method does nothing. + */ + public synchronized void disconnect() { + if (connectionHandler == null) { + return; + } + Closer.close(remoteSocket); + connectionHandler.stop(); + connectionHandler = null; + } + /** + * Sends the given FCP message. + * + * @param fcpMessage + * The FCP message to send + * @throws IOException + * if an I/O error occurs + */ public synchronized void sendMessage(FcpMessage fcpMessage) throws IOException { System.out.println("sending message: " + fcpMessage.getName()); fcpMessage.write(remoteOutputStream); } - public FcpMessage waitForMessage(String... messageNames) throws FcpException { - FcpMessage oldMessage = null; - synchronized (messageWaitSync) { - while (true) { - while (receivedMessage == oldMessage) { - System.out.println("waiting for receivedMessage"); - try { - messageWaitSync.wait(); - } catch (InterruptedException ie1) { - } - } - System.out.println("got message: " + receivedMessage.getName()); - String receivedMessageName = receivedMessage.getName(); - if ("ProtocolError".equals(receivedMessageName)) { - int code = Integer.valueOf(receivedMessage.getField("Code")); - boolean fatal = Boolean.valueOf(receivedMessage.getField("Fatal")); - boolean global = Boolean.valueOf(receivedMessage.getField("Global")); - String codeDescription = receivedMessage.getField("CodeDescription"); - String extraDescription = receivedMessage.getField("ExtraDescription"); - String identifier = receivedMessage.getField("Identifier"); - FcpProtocolException fcpProtocolException = new FcpProtocolException(code, fatal, global); - fcpProtocolException.setCodeDescription(codeDescription); - fcpProtocolException.setExtraDescription(extraDescription); - fcpProtocolException.setIdentifier(identifier); - throw fcpProtocolException; - } - for (String messageName: messageNames) { - int firstBracket = messageName.indexOf('('); - Map wantedIdentifiers = new HashMap(); - if (firstBracket > -1) { - StringTokenizer identifierTokens = new StringTokenizer(messageName.substring(firstBracket), "()"); - while (identifierTokens.hasMoreTokens()) { - String identifierToken = identifierTokens.nextToken(); - int equalSign = identifierToken.indexOf('='); - if (equalSign > -1) { - wantedIdentifiers.put(identifierToken.substring(0, equalSign), identifierToken.substring(equalSign + 1)); - } - } - messageName = messageName.substring(0, firstBracket); - } - if (receivedMessageName.equals(messageName)) { - boolean found = true; - for (Entry wantedIdentifier: wantedIdentifiers.entrySet()) { - System.out.println("key: " + wantedIdentifier.getKey() + ", value: " + wantedIdentifier.getValue() + ", msg: " + receivedMessage.getField(wantedIdentifier.getKey())); - if (!wantedIdentifier.getValue().equals(receivedMessage.getField(wantedIdentifier.getKey()))) { - found = false; - break; - } - } - if (found) { - System.out.println("message found"); - FcpMessage foundMessage = receivedMessage; - receivedMessage = null; - messageWaitSync.notifyAll(); - return foundMessage; - } - } - } - oldMessage = receivedMessage; - } + // + // PACKAGE-PRIVATE METHODS + // + + /** + * Handles the given message, notifying listeners. This message should only + * be called by {@link FcpConnectionHandler}. + * + * @param fcpMessage + * The received message + */ + void handleMessage(FcpMessage fcpMessage) { + String messageName = fcpMessage.getName(); + if ("Peer".equals(messageName)) { + fireReceivedPeer(new Peer(fcpMessage)); + } else if ("PeerNote".equals(messageName)) { + fireReceivedPeerNote(new PeerNote(fcpMessage)); + } else if ("EndListPeerNotes".equals(messageName)) { + fireReceivedEndListPeerNotes(new EndListPeerNotes(fcpMessage)); + } else if ("EndListPeers".equals(messageName)) { + fireReceivedEndListPeers(new EndListPeers(fcpMessage)); + } else if ("SSKKeypair".equals(messageName)) { + fireReceivedSSKKeypair(new SSKKeypair(fcpMessage)); + } else if ("NodeHello".equals(messageName)) { + fireReceivedNodeHello(new NodeHello(fcpMessage)); + } else if ("CloseConnectionDuplicateClientName".equals(messageName)) { + fireReceivedCloseConnectionDuplicateClientName(new CloseConnectionDuplicateClientName(fcpMessage)); + } else { + fireMessageReceived(fcpMessage); } }