2 * jFCPlib - FcpClient.java -
3 * Copyright © 2009 David Roden
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 package net.pterodactylus.fcp.highlevel;
22 import java.io.IOException;
23 import java.net.InetAddress;
25 import java.net.UnknownHostException;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
32 import java.util.concurrent.CountDownLatch;
34 import net.pterodactylus.fcp.AddPeer;
35 import net.pterodactylus.fcp.ClientHello;
36 import net.pterodactylus.fcp.CloseConnectionDuplicateClientName;
37 import net.pterodactylus.fcp.DataFound;
38 import net.pterodactylus.fcp.EndListPeerNotes;
39 import net.pterodactylus.fcp.EndListPeers;
40 import net.pterodactylus.fcp.EndListPersistentRequests;
41 import net.pterodactylus.fcp.FcpAdapter;
42 import net.pterodactylus.fcp.FcpConnection;
43 import net.pterodactylus.fcp.FcpListener;
44 import net.pterodactylus.fcp.GenerateSSK;
45 import net.pterodactylus.fcp.GetFailed;
46 import net.pterodactylus.fcp.ListPeerNotes;
47 import net.pterodactylus.fcp.ListPeers;
48 import net.pterodactylus.fcp.ListPersistentRequests;
49 import net.pterodactylus.fcp.ModifyPeer;
50 import net.pterodactylus.fcp.ModifyPeerNote;
51 import net.pterodactylus.fcp.NodeHello;
52 import net.pterodactylus.fcp.NodeRef;
53 import net.pterodactylus.fcp.Peer;
54 import net.pterodactylus.fcp.PeerNote;
55 import net.pterodactylus.fcp.PeerRemoved;
56 import net.pterodactylus.fcp.PersistentGet;
57 import net.pterodactylus.fcp.PersistentPut;
58 import net.pterodactylus.fcp.ProtocolError;
59 import net.pterodactylus.fcp.RemovePeer;
60 import net.pterodactylus.fcp.SSKKeypair;
61 import net.pterodactylus.fcp.SimpleProgress;
62 import net.pterodactylus.fcp.WatchGlobal;
63 import net.pterodactylus.util.thread.ObjectWrapper;
66 * High-level FCP client that hides the details of the underlying FCP
69 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
71 public class FcpClient {
73 /** Object used for synchronization. */
74 private final Object syncObject = new Object();
76 /** The name of this client. */
77 private final String name;
79 /** The underlying FCP connection. */
80 private final FcpConnection fcpConnection;
83 * Creates an FCP client with the given name.
86 * The name of the FCP client
87 * @throws UnknownHostException
88 * if the hostname “localhost” is unknown
90 public FcpClient(String name) throws UnknownHostException {
91 this(name, "localhost");
95 * Creates an FCP client.
98 * The name of the FCP client
100 * The hostname of the Freenet node
101 * @throws UnknownHostException
102 * if the given hostname can not be resolved
104 public FcpClient(String name, String hostname) throws UnknownHostException {
105 this(name, hostname, FcpConnection.DEFAULT_PORT);
109 * Creates an FCP client.
112 * The name of the FCP client
114 * The hostname of the Freenet node
116 * The Freenet node’s FCP port
117 * @throws UnknownHostException
118 * if the given hostname can not be resolved
120 public FcpClient(String name, String hostname, int port) throws UnknownHostException {
121 this(name, InetAddress.getByName(hostname), port);
125 * Creates an FCP client.
128 * The name of the FCP client
130 * The host address of the Freenet node
132 public FcpClient(String name, InetAddress host) {
133 this(name, host, FcpConnection.DEFAULT_PORT);
137 * Creates an FCP client.
140 * The name of the FCP client
142 * The host address of the Freenet node
144 * The Freenet node’s FCP port
146 public FcpClient(String name, InetAddress host, int port) {
148 fcpConnection = new FcpConnection(host, port);
156 * Connects the FCP client.
158 * @throws IOException
159 * if an I/O error occurs
160 * @throws FcpException
161 * if an FCP error occurs
163 public void connect() throws IOException, FcpException {
164 new ExtendedFcpAdapter() {
170 @SuppressWarnings("synthetic-access")
171 public void run() throws IOException {
172 fcpConnection.connect();
173 ClientHello clientHello = new ClientHello(name);
174 fcpConnection.sendMessage(clientHello);
175 WatchGlobal watchGlobal = new WatchGlobal(true);
176 fcpConnection.sendMessage(watchGlobal);
183 public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
184 completionLatch.countDown();
190 * Disconnects the FCP client.
192 public void disconnect() {
193 synchronized (syncObject) {
194 fcpConnection.close();
195 syncObject.notifyAll();
204 * Returns all peers that the node has.
206 * @param withMetadata
207 * <code>true</code> to include peer metadata
208 * @param withVolatile
209 * <code>true</code> to include volatile peer data
210 * @return A set containing the node’s peers
211 * @throws IOException
212 * if an I/O error occurs
213 * @throws FcpException
214 * if an FCP error occurs
216 public Collection<Peer> getPeers(final boolean withMetadata, final boolean withVolatile) throws IOException, FcpException {
217 final Set<Peer> peers = Collections.synchronizedSet(new HashSet<Peer>());
218 new ExtendedFcpAdapter() {
220 /** The ID of the “ListPeers” request. */
221 @SuppressWarnings("synthetic-access")
222 private String identifier = createIdentifier("list-peers");
228 @SuppressWarnings("synthetic-access")
229 public void run() throws IOException {
230 fcpConnection.sendMessage(new ListPeers(identifier, withMetadata, withVolatile));
237 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
238 if (peer.getIdentifier().equals(identifier)) {
247 public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
248 if (endListPeers.getIdentifier().equals(identifier)) {
249 completionLatch.countDown();
257 * Returns all darknet peers.
259 * @param withMetadata
260 * <code>true</code> to include peer metadata
261 * @param withVolatile
262 * <code>true</code> to include volatile peer data
263 * @return A set containing the node’s darknet peers
264 * @throws IOException
265 * if an I/O error occurs
266 * @throws FcpException
267 * if an FCP error occurs
269 public Collection<Peer> getDarknetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
270 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
271 Collection<Peer> darknetPeers = new HashSet<Peer>();
272 for (Peer peer : allPeers) {
273 if (!peer.isOpennet() && !peer.isSeed()) {
274 darknetPeers.add(peer);
281 * Returns all opennet peers.
283 * @param withMetadata
284 * <code>true</code> to include peer metadata
285 * @param withVolatile
286 * <code>true</code> to include volatile peer data
287 * @return A set containing the node’s opennet peers
288 * @throws IOException
289 * if an I/O error occurs
290 * @throws FcpException
291 * if an FCP error occurs
293 public Collection<Peer> getOpennetPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
294 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
295 Collection<Peer> opennetPeers = new HashSet<Peer>();
296 for (Peer peer : allPeers) {
297 if (peer.isOpennet() && !peer.isSeed()) {
298 opennetPeers.add(peer);
305 * Returns all seed peers.
307 * @param withMetadata
308 * <code>true</code> to include peer metadata
309 * @param withVolatile
310 * <code>true</code> to include volatile peer data
311 * @return A set containing the node’s seed peers
312 * @throws IOException
313 * if an I/O error occurs
314 * @throws FcpException
315 * if an FCP error occurs
317 public Collection<Peer> getSeedPeers(boolean withMetadata, boolean withVolatile) throws IOException, FcpException {
318 Collection<Peer> allPeers = getPeers(withMetadata, withVolatile);
319 Collection<Peer> seedPeers = new HashSet<Peer>();
320 for (Peer peer : allPeers) {
329 * Adds the given peer to the node.
333 * @throws IOException
334 * if an I/O error occurs
335 * @throws FcpException
336 * if an FCP error occurs
338 public void addPeer(Peer peer) throws IOException, FcpException {
339 addPeer(peer.getNodeRef());
343 * Adds the peer defined by the noderef to the node.
346 * The noderef that defines the new peer
347 * @throws IOException
348 * if an I/O error occurs
349 * @throws FcpException
350 * if an FCP error occurs
352 public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
353 addPeer(new AddPeer(nodeRef));
357 * Adds a peer, reading the noderef from the given URL.
360 * The URL to read the noderef from
361 * @throws IOException
362 * if an I/O error occurs
363 * @throws FcpException
364 * if an FCP error occurs
366 public void addPeer(URL url) throws IOException, FcpException {
367 addPeer(new AddPeer(url));
371 * Adds a peer, reading the noderef of the peer from the given file.
372 * <strong>Note:</strong> the file to read the noderef from has to reside on
373 * the same machine as the node!
376 * The name of the file containing the peer’s noderef
377 * @throws IOException
378 * if an I/O error occurs
379 * @throws FcpException
380 * if an FCP error occurs
382 public void addPeer(String file) throws IOException, FcpException {
383 addPeer(new AddPeer(file));
387 * Sends the given {@link AddPeer} message to the node. This method should
388 * not be called directly. Use one of {@link #addPeer(Peer)},
389 * {@link #addPeer(NodeRef)}, {@link #addPeer(URL)}, or
390 * {@link #addPeer(String)} instead.
393 * The “AddPeer” message
394 * @throws IOException
395 * if an I/O error occurs
396 * @throws FcpException
397 * if an FCP error occurs
399 private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
400 new ExtendedFcpAdapter() {
406 @SuppressWarnings("synthetic-access")
407 public void run() throws IOException {
408 fcpConnection.sendMessage(addPeer);
415 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
416 completionLatch.countDown();
422 * Modifies the given peer.
426 * @param allowLocalAddresses
427 * <code>true</code> to allow local address, <code>false</code>
428 * to not allow local address, <code>null</code> to not change
431 * <code>true</code> to disable the peer, <code>false</code> to
432 * enable the peer, <code>null</code> to not change the setting
434 * <code>true</code> to enable “listen only” for the peer,
435 * <code>false</code> to disable it, <code>null</code> to not
437 * @throws IOException
438 * if an I/O error occurs
439 * @throws FcpException
440 * if an FCP error occurs
442 public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
443 new ExtendedFcpAdapter() {
449 @SuppressWarnings("synthetic-access")
450 public void run() throws IOException {
451 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
458 public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
459 completionLatch.countDown();
465 * Removes the given peer.
469 * @throws IOException
470 * if an I/O error occurs
471 * @throws FcpException
472 * if an FCP error occurs
474 public void removePeer(final Peer peer) throws IOException, FcpException {
475 new ExtendedFcpAdapter() {
481 @SuppressWarnings("synthetic-access")
482 public void run() throws IOException {
483 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
490 public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
491 completionLatch.countDown();
497 // PEER NOTES MANAGEMENT
501 * Returns the peer note of the given peer.
504 * The peer to get the note for
505 * @return The peer’s note
506 * @throws IOException
507 * if an I/O error occurs
508 * @throws FcpException
509 * if an FCP error occurs
511 public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
512 final ObjectWrapper<PeerNote> objectWrapper = new ObjectWrapper<PeerNote>();
513 new ExtendedFcpAdapter() {
519 @SuppressWarnings("synthetic-access")
520 public void run() throws IOException {
521 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
528 public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
529 if (peerNote.getNodeIdentifier().equals(peer.getIdentity())) {
530 objectWrapper.set(peerNote);
538 public void receivedEndListPeerNotes(FcpConnection fcpConnection, EndListPeerNotes endListPeerNotes) {
539 completionLatch.countDown();
542 return objectWrapper.get();
546 * Replaces the peer note for the given peer.
551 * The new base64-encoded note text
553 * The type of the note (currently only <code>1</code> is
555 * @throws IOException
556 * if an I/O error occurs
557 * @throws FcpException
558 * if an FCP error occurs
560 public void modifyPeerNote(final Peer peer, final String noteText, final int noteType) throws IOException, FcpException {
561 new ExtendedFcpAdapter() {
567 @SuppressWarnings("synthetic-access")
568 public void run() throws IOException {
569 fcpConnection.sendMessage(new ModifyPeerNote(peer.getIdentity(), noteText, noteType));
576 public void receivedPeer(FcpConnection fcpConnection, Peer receivedPeer) {
577 if (receivedPeer.getIdentity().equals(peer.getIdentity())) {
578 completionLatch.countDown();
589 * Generates a new SSK key pair.
591 * @return The generated key pair
592 * @throws IOException
593 * if an I/O error occurs
594 * @throws FcpException
595 * if an FCP error occurs
597 public SSKKeypair generateKeyPair() throws IOException, FcpException {
598 final ObjectWrapper<SSKKeypair> sskKeypairWrapper = new ObjectWrapper<SSKKeypair>();
599 new ExtendedFcpAdapter() {
605 @SuppressWarnings("synthetic-access")
606 public void run() throws IOException {
607 fcpConnection.sendMessage(new GenerateSSK());
614 public void receivedSSKKeypair(FcpConnection fcpConnection, SSKKeypair sskKeypair) {
615 sskKeypairWrapper.set(sskKeypair);
616 completionLatch.countDown();
619 return sskKeypairWrapper.get();
623 // REQUEST MANAGEMENT
627 * Returns all currently visible persistent get requests.
630 * <code>true</code> to return get requests from the global
631 * queue, <code>false</code> to only show requests from the
633 * @return All get requests
634 * @throws IOException
635 * if an I/O error occurs
636 * @throws FcpException
637 * if an FCP error occurs
639 public Collection<Request> getGetRequests(final boolean global) throws IOException, FcpException {
640 return getRequests(global);
643 public Collection<Request> getRequests(final boolean global) throws IOException, FcpException {
644 final Map<String, Request> requests = Collections.synchronizedMap(new HashMap<String, Request>());
645 new ExtendedFcpAdapter() {
651 @SuppressWarnings("synthetic-access")
652 public void run() throws IOException {
653 fcpConnection.sendMessage(new ListPersistentRequests());
660 public void receivedPersistentGet(FcpConnection fcpConnection, PersistentGet persistentGet) {
661 if (!persistentGet.isGlobal() || global) {
662 GetRequest getRequest = new GetRequest(persistentGet);
663 requests.put(persistentGet.getIdentifier(), getRequest);
670 * @see net.pterodactylus.fcp.FcpAdapter#receivedDataFound(net.pterodactylus.fcp.FcpConnection,
671 * net.pterodactylus.fcp.DataFound)
674 public void receivedDataFound(FcpConnection fcpConnection, DataFound dataFound) {
675 Request getRequest = requests.get(dataFound.getIdentifier());
676 if (getRequest == null) {
679 getRequest.setComplete(true);
680 getRequest.setLength(dataFound.getDataLength());
681 getRequest.setContentType(dataFound.getMetadataContentType());
687 * @see net.pterodactylus.fcp.FcpAdapter#receivedGetFailed(net.pterodactylus.fcp.FcpConnection,
688 * net.pterodactylus.fcp.GetFailed)
691 public void receivedGetFailed(FcpConnection fcpConnection, GetFailed getFailed) {
692 Request getRequest = requests.get(getFailed.getIdentifier());
693 if (getRequest == null) {
696 getRequest.setComplete(true);
697 getRequest.setFailed(true);
698 getRequest.setFatal(getFailed.isFatal());
699 getRequest.setErrorCode(getFailed.getCode());
705 * @see net.pterodactylus.fcp.FcpAdapter#receivedPersistentPut(net.pterodactylus.fcp.FcpConnection,
706 * net.pterodactylus.fcp.PersistentPut)
709 public void receivedPersistentPut(FcpConnection fcpConnection, PersistentPut persistentPut) {
710 if (!persistentPut.isGlobal() || global) {
711 PutRequest putRequest = new PutRequest(persistentPut);
712 requests.put(persistentPut.getIdentifier(), putRequest);
719 * @see net.pterodactylus.fcp.FcpAdapter#receivedSimpleProgress(net.pterodactylus.fcp.FcpConnection,
720 * net.pterodactylus.fcp.SimpleProgress)
723 public void receivedSimpleProgress(FcpConnection fcpConnection, SimpleProgress simpleProgress) {
724 Request request = requests.get(simpleProgress.getIdentifier());
725 if (request == null) {
728 request.setTotalBlocks(simpleProgress.getTotal());
729 request.setRequiredBlocks(simpleProgress.getRequired());
730 request.setFailedBlocks(simpleProgress.getFailed());
731 request.setFatallyFailedBlocks(simpleProgress.getFatallyFailed());
732 request.setSucceededBlocks(simpleProgress.getSucceeded());
733 request.setFinalizedTotal(simpleProgress.isFinalizedTotal());
740 public void receivedEndListPersistentRequests(FcpConnection fcpConnection, EndListPersistentRequests endListPersistentRequests) {
741 completionLatch.countDown();
744 return requests.values();
752 * Creates a unique request identifier.
755 * The basename of the request
756 * @return The created request identifier
758 private String createIdentifier(String basename) {
759 return basename + "-" + System.currentTimeMillis() + "-" + (int) (Math.random() * Integer.MAX_VALUE);
763 * Implementation of an {@link FcpListener} that can store an
764 * {@link FcpException} and wait for the arrival of a certain command.
766 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
768 private abstract class ExtendedFcpAdapter extends FcpAdapter {
770 /** The count down latch used to wait for completion. */
771 protected final CountDownLatch completionLatch = new CountDownLatch(1);
773 /** The FCP exception, if any. */
774 protected FcpException fcpException;
777 * Creates a new extended FCP adapter.
779 public ExtendedFcpAdapter() {
784 * Executes the FCP commands in {@link #run()}, wrapping the execution
785 * and catching exceptions.
787 * @throws IOException
788 * if an I/O error occurs
789 * @throws FcpException
790 * if an FCP error occurs
792 @SuppressWarnings("synthetic-access")
793 public void execute() throws IOException, FcpException {
794 fcpConnection.addFcpListener(this);
799 completionLatch.await();
801 } catch (InterruptedException ie1) {
802 /* ignore, we’ll loop. */
806 fcpConnection.removeFcpListener(this);
808 if (fcpException != null) {
814 * The FCP commands that actually get executed.
816 * @throws IOException
817 * if an I/O error occurs
819 public abstract void run() throws IOException;
825 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
826 fcpException = new FcpException("Connection closed", throwable);
827 completionLatch.countDown();
834 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
835 fcpException = new FcpException("Connection closed, duplicate client name");
836 completionLatch.countDown();
843 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
844 fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
845 completionLatch.countDown();