Add generateKeyPair().
[jFCPlib.git] / src / net / pterodactylus / fcp / highlevel / FcpClient.java
1 /*
2  * jFCPlib - FcpClient.java -
3  * Copyright © 2009 David Roden
4  *
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.
9  *
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.
14  *
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.
18  */
19
20 package net.pterodactylus.fcp.highlevel;
21
22 import java.io.IOException;
23 import java.net.InetAddress;
24 import java.net.URL;
25 import java.net.UnknownHostException;
26 import java.util.Collections;
27 import java.util.HashSet;
28 import java.util.Set;
29 import java.util.concurrent.CountDownLatch;
30
31 import net.pterodactylus.fcp.AddPeer;
32 import net.pterodactylus.fcp.ClientHello;
33 import net.pterodactylus.fcp.CloseConnectionDuplicateClientName;
34 import net.pterodactylus.fcp.EndListPeerNotes;
35 import net.pterodactylus.fcp.EndListPeers;
36 import net.pterodactylus.fcp.FcpAdapter;
37 import net.pterodactylus.fcp.FcpConnection;
38 import net.pterodactylus.fcp.FcpListener;
39 import net.pterodactylus.fcp.GenerateSSK;
40 import net.pterodactylus.fcp.ListPeerNotes;
41 import net.pterodactylus.fcp.ListPeers;
42 import net.pterodactylus.fcp.ModifyPeer;
43 import net.pterodactylus.fcp.ModifyPeerNote;
44 import net.pterodactylus.fcp.NodeHello;
45 import net.pterodactylus.fcp.NodeRef;
46 import net.pterodactylus.fcp.Peer;
47 import net.pterodactylus.fcp.PeerNote;
48 import net.pterodactylus.fcp.PeerRemoved;
49 import net.pterodactylus.fcp.ProtocolError;
50 import net.pterodactylus.fcp.RemovePeer;
51 import net.pterodactylus.fcp.SSKKeypair;
52 import net.pterodactylus.util.thread.ObjectWrapper;
53
54 /**
55  * High-level FCP client that hides the details of the underlying FCP
56  * implementation.
57  *
58  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
59  */
60 public class FcpClient {
61
62         /** Object used for synchronization. */
63         private final Object syncObject = new Object();
64
65         /** The name of this client. */
66         private final String name;
67
68         /** The underlying FCP connection. */
69         private final FcpConnection fcpConnection;
70
71         /**
72          * Creates an FCP client with the given name.
73          *
74          * @param name
75          *            The name of the FCP client
76          * @throws UnknownHostException
77          *             if the hostname “localhost” is unknown
78          */
79         public FcpClient(String name) throws UnknownHostException {
80                 this(name, "localhost");
81         }
82
83         /**
84          * Creates an FCP client.
85          *
86          * @param name
87          *            The name of the FCP client
88          * @param hostname
89          *            The hostname of the Freenet node
90          * @throws UnknownHostException
91          *             if the given hostname can not be resolved
92          */
93         public FcpClient(String name, String hostname) throws UnknownHostException {
94                 this(name, hostname, FcpConnection.DEFAULT_PORT);
95         }
96
97         /**
98          * Creates an FCP client.
99          *
100          * @param name
101          *            The name of the FCP client
102          * @param hostname
103          *            The hostname of the Freenet node
104          * @param port
105          *            The Freenet node’s FCP port
106          * @throws UnknownHostException
107          *             if the given hostname can not be resolved
108          */
109         public FcpClient(String name, String hostname, int port) throws UnknownHostException {
110                 this(name, InetAddress.getByName(hostname), port);
111         }
112
113         /**
114          * Creates an FCP client.
115          *
116          * @param name
117          *            The name of the FCP client
118          * @param host
119          *            The host address of the Freenet node
120          */
121         public FcpClient(String name, InetAddress host) {
122                 this(name, host, FcpConnection.DEFAULT_PORT);
123         }
124
125         /**
126          * Creates an FCP client.
127          *
128          * @param name
129          *            The name of the FCP client
130          * @param host
131          *            The host address of the Freenet node
132          * @param port
133          *            The Freenet node’s FCP port
134          */
135         public FcpClient(String name, InetAddress host, int port) {
136                 this.name = name;
137                 fcpConnection = new FcpConnection(host, port);
138         }
139
140         //
141         // ACTIONS
142         //
143
144         /**
145          * Connects the FCP client.
146          *
147          * @throws IOException
148          *             if an I/O error occurs
149          * @throws FcpException
150          *             if an FCP error occurs
151          */
152         public void connect() throws IOException, FcpException {
153                 new ExtendedFcpAdapter() {
154
155                         /**
156                          * {@inheritDoc}
157                          */
158                         @Override
159                         @SuppressWarnings("synthetic-access")
160                         public void run() throws IOException {
161                                 fcpConnection.connect();
162                                 ClientHello clientHello = new ClientHello(name);
163                                 fcpConnection.sendMessage(clientHello);
164                         }
165
166                         /**
167                          * {@inheritDoc}
168                          */
169                         @Override
170                         public void receivedNodeHello(FcpConnection fcpConnection, NodeHello nodeHello) {
171                                 completionLatch.countDown();
172                         }
173                 }.execute();
174         }
175
176         /**
177          * Disconnects the FCP client.
178          */
179         public void disconnect() {
180                 synchronized (syncObject) {
181                         fcpConnection.close();
182                         syncObject.notifyAll();
183                 }
184         }
185
186         //
187         // PEER MANAGEMENT
188         //
189
190         /**
191          * Returns all peers that the node has.
192          *
193          * @param withMetadata
194          *            <code>true</code> to include peer metadata
195          * @param withVolatile
196          *            <code>true</code> to include volatile peer data
197          * @return A set containing the node’s peers
198          * @throws IOException
199          *             if an I/O error occurs
200          * @throws FcpException
201          *             if an FCP error occurs
202          */
203         public Set<Peer> getPeers(final boolean withMetadata, final boolean withVolatile) throws IOException, FcpException {
204                 final Set<Peer> peers = Collections.synchronizedSet(new HashSet<Peer>());
205                 new ExtendedFcpAdapter() {
206
207                         /** The ID of the “ListPeers” request. */
208                         private String identifier = "list-peers-" + System.currentTimeMillis();
209
210                         /**
211                          * {@inheritDoc}
212                          */
213                         @Override
214                         @SuppressWarnings("synthetic-access")
215                         public void run() throws IOException {
216                                 fcpConnection.sendMessage(new ListPeers(identifier, withMetadata, withVolatile));
217                         }
218
219                         /**
220                          * {@inheritDoc}
221                          */
222                         @Override
223                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
224                                 if (peer.getIdentifier().equals(identifier)) {
225                                         peers.add(peer);
226                                 }
227                         }
228
229                         /**
230                          * {@inheritDoc}
231                          */
232                         @Override
233                         public void receivedEndListPeers(FcpConnection fcpConnection, EndListPeers endListPeers) {
234                                 if (endListPeers.getIdentifier().equals(identifier)) {
235                                         completionLatch.countDown();
236                                 }
237                         }
238                 }.execute();
239                 return peers;
240         }
241
242         /**
243          * Adds the given peer to the node.
244          *
245          * @param peer
246          *            The peer to add
247          * @throws IOException
248          *             if an I/O error occurs
249          * @throws FcpException
250          *             if an FCP error occurs
251          */
252         public void addPeer(Peer peer) throws IOException, FcpException {
253                 addPeer(peer.getNodeRef());
254         }
255
256         /**
257          * Adds the peer defined by the noderef to the node.
258          *
259          * @param nodeRef
260          *            The noderef that defines the new peer
261          * @throws IOException
262          *             if an I/O error occurs
263          * @throws FcpException
264          *             if an FCP error occurs
265          */
266         public void addPeer(NodeRef nodeRef) throws IOException, FcpException {
267                 addPeer(new AddPeer(nodeRef));
268         }
269
270         /**
271          * Adds a peer, reading the noderef from the given URL.
272          *
273          * @param url
274          *            The URL to read the noderef from
275          * @throws IOException
276          *             if an I/O error occurs
277          * @throws FcpException
278          *             if an FCP error occurs
279          */
280         public void addPeer(URL url) throws IOException, FcpException {
281                 addPeer(new AddPeer(url));
282         }
283
284         /**
285          * Adds a peer, reading the noderef of the peer from the given file.
286          * <strong>Note:</strong> the file to read the noderef from has to reside on
287          * the same machine as the node!
288          *
289          * @param file
290          *            The name of the file containing the peer’s noderef
291          * @throws IOException
292          *             if an I/O error occurs
293          * @throws FcpException
294          *             if an FCP error occurs
295          */
296         public void addPeer(String file) throws IOException, FcpException {
297                 addPeer(new AddPeer(file));
298         }
299
300         /**
301          * Sends the given {@link AddPeer} message to the node. This method should
302          * not be called directly. Use one of {@link #addPeer(Peer)},
303          * {@link #addPeer(NodeRef)}, {@link #addPeer(URL)}, or
304          * {@link #addPeer(String)} instead.
305          *
306          * @param addPeer
307          *            The “AddPeer” message
308          * @throws IOException
309          *             if an I/O error occurs
310          * @throws FcpException
311          *             if an FCP error occurs
312          */
313         private void addPeer(final AddPeer addPeer) throws IOException, FcpException {
314                 new ExtendedFcpAdapter() {
315
316                         /**
317                          * {@inheritDoc}
318                          */
319                         @Override
320                         @SuppressWarnings("synthetic-access")
321                         public void run() throws IOException {
322                                 fcpConnection.sendMessage(addPeer);
323                         }
324
325                         /**
326                          * {@inheritDoc}
327                          */
328                         @Override
329                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
330                                 completionLatch.countDown();
331                         }
332                 }.execute();
333         }
334
335         /**
336          * Modifies the given peer.
337          *
338          * @param peer
339          *            The peer to modify
340          * @param allowLocalAddresses
341          *            <code>true</code> to allow local address, <code>false</code>
342          *            to not allow local address, <code>null</code> to not change
343          *            the setting
344          * @param disabled
345          *            <code>true</code> to disable the peer, <code>false</code> to
346          *            enable the peer, <code>null</code> to not change the setting
347          * @param listenOnly
348          *            <code>true</code> to enable “listen only” for the peer,
349          *            <code>false</code> to disable it, <code>null</code> to not
350          *            change it
351          * @throws IOException
352          *             if an I/O error occurs
353          * @throws FcpException
354          *             if an FCP error occurs
355          */
356         public void modifyPeer(final Peer peer, final Boolean allowLocalAddresses, final Boolean disabled, final Boolean listenOnly) throws IOException, FcpException {
357                 new ExtendedFcpAdapter() {
358
359                         /**
360                          * {@inheritDoc}
361                          */
362                         @Override
363                         @SuppressWarnings("synthetic-access")
364                         public void run() throws IOException {
365                                 fcpConnection.sendMessage(new ModifyPeer(peer.getIdentity(), allowLocalAddresses, disabled, listenOnly));
366                         }
367
368                         /**
369                          * {@inheritDoc}
370                          */
371                         @Override
372                         public void receivedPeer(FcpConnection fcpConnection, Peer peer) {
373                                 completionLatch.countDown();
374                         }
375                 }.execute();
376         }
377
378         /**
379          * Removes the given peer.
380          *
381          * @param peer
382          *            The peer to remove
383          * @throws IOException
384          *             if an I/O error occurs
385          * @throws FcpException
386          *             if an FCP error occurs
387          */
388         public void removePeer(final Peer peer) throws IOException, FcpException {
389                 new ExtendedFcpAdapter() {
390
391                         /**
392                          * {@inheritDoc}
393                          */
394                         @Override
395                         @SuppressWarnings("synthetic-access")
396                         public void run() throws IOException {
397                                 fcpConnection.sendMessage(new RemovePeer(peer.getIdentity()));
398                         }
399
400                         /**
401                          * {@inheritDoc}
402                          */
403                         @Override
404                         public void receivedPeerRemoved(FcpConnection fcpConnection, PeerRemoved peerRemoved) {
405                                 completionLatch.countDown();
406                         }
407                 }.execute();
408         }
409
410         //
411         // PEER NOTES MANAGEMENT
412         //
413
414         /**
415          * Returns the peer note of the given peer.
416          *
417          * @param peer
418          *            The peer to get the note for
419          * @return The peer’s note
420          * @throws IOException
421          *             if an I/O error occurs
422          * @throws FcpException
423          *             if an FCP error occurs
424          */
425         public PeerNote getPeerNote(final Peer peer) throws IOException, FcpException {
426                 final ObjectWrapper<PeerNote> objectWrapper = new ObjectWrapper<PeerNote>();
427                 new ExtendedFcpAdapter() {
428
429                         /**
430                          * {@inheritDoc}
431                          */
432                         @Override
433                         @SuppressWarnings("synthetic-access")
434                         public void run() throws IOException {
435                                 fcpConnection.sendMessage(new ListPeerNotes(peer.getIdentity()));
436                         }
437
438                         /**
439                          * {@inheritDoc}
440                          */
441                         @Override
442                         public void receivedPeerNote(FcpConnection fcpConnection, PeerNote peerNote) {
443                                 if (peerNote.getNodeIdentifier().equals(peer.getIdentity())) {
444                                         objectWrapper.set(peerNote);
445                                 }
446                         }
447
448                         /**
449                          * {@inheritDoc}
450                          */
451                         @Override
452                         public void receivedEndListPeerNotes(FcpConnection fcpConnection, EndListPeerNotes endListPeerNotes) {
453                                 completionLatch.countDown();
454                         }
455                 }.execute();
456                 return objectWrapper.get();
457         }
458
459         /**
460          * Replaces the peer note for the given peer.
461          *
462          * @param peer
463          *            The peer
464          * @param noteText
465          *            The new base64-encoded note text
466          * @param noteType
467          *            The type of the note (currently only <code>1</code> is
468          *            allowed)
469          * @throws IOException
470          *             if an I/O error occurs
471          * @throws FcpException
472          *             if an FCP error occurs
473          */
474         public void modifyPeerNote(final Peer peer, final String noteText, final int noteType) throws IOException, FcpException {
475                 new ExtendedFcpAdapter() {
476
477                         /**
478                          * {@inheritDoc}
479                          */
480                         @Override
481                         @SuppressWarnings("synthetic-access")
482                         public void run() throws IOException {
483                                 fcpConnection.sendMessage(new ModifyPeerNote(peer.getIdentity(), noteText, noteType));
484                         }
485
486                         /**
487                          * {@inheritDoc}
488                          */
489                         @Override
490                         public void receivedPeer(FcpConnection fcpConnection, Peer receivedPeer) {
491                                 if (receivedPeer.getIdentity().equals(peer.getIdentity())) {
492                                         completionLatch.countDown();
493                                 }
494                         }
495                 }.execute();
496         }
497
498         //
499         // KEY GENERATION
500         //
501
502         /**
503          * Generates a new SSK key pair.
504          *
505          * @return The generated key pair
506          * @throws IOException
507          *             if an I/O error occurs
508          * @throws FcpException
509          *             if an FCP error occurs
510          */
511         public SSKKeypair generateKeyPair() throws IOException, FcpException {
512                 final ObjectWrapper<SSKKeypair> sskKeypairWrapper = new ObjectWrapper<SSKKeypair>();
513                 new ExtendedFcpAdapter() {
514
515                         /**
516                          * {@inheritDoc}
517                          */
518                         @Override
519                         @SuppressWarnings("synthetic-access")
520                         public void run() throws IOException {
521                                 fcpConnection.sendMessage(new GenerateSSK());
522                         }
523
524                         /**
525                          * {@inheritDoc}
526                          */
527                         @Override
528                         public void receivedSSKKeypair(FcpConnection fcpConnection, SSKKeypair sskKeypair) {
529                                 sskKeypairWrapper.set(sskKeypair);
530                                 completionLatch.countDown();
531                         }
532                 }.execute();
533                 return sskKeypairWrapper.get();
534         }
535
536         /**
537          * Implementation of an {@link FcpListener} that can store an
538          * {@link FcpException} and wait for the arrival of a certain command.
539          *
540          * @author David ‘Bombe’ Roden &lt;bombe@freenetproject.org&gt;
541          */
542         private abstract class ExtendedFcpAdapter extends FcpAdapter {
543
544                 /** The count down latch used to wait for completion. */
545                 protected final CountDownLatch completionLatch = new CountDownLatch(1);
546
547                 /** The FCP exception, if any. */
548                 protected FcpException fcpException;
549
550                 /**
551                  * Creates a new extended FCP adapter.
552                  */
553                 public ExtendedFcpAdapter() {
554                         /* do nothing. */
555                 }
556
557                 /**
558                  * Executes the FCP commands in {@link #run()}, wrapping the execution
559                  * and catching exceptions.
560                  *
561                  * @throws IOException
562                  *             if an I/O error occurs
563                  * @throws FcpException
564                  *             if an FCP error occurs
565                  */
566                 @SuppressWarnings("synthetic-access")
567                 public void execute() throws IOException, FcpException {
568                         fcpConnection.addFcpListener(this);
569                         try {
570                                 run();
571                                 while (true) {
572                                         try {
573                                                 completionLatch.await();
574                                                 break;
575                                         } catch (InterruptedException ie1) {
576                                                 /* ignore, we’ll loop. */
577                                         }
578                                 }
579                         } finally {
580                                 fcpConnection.removeFcpListener(this);
581                         }
582                         if (fcpException != null) {
583                                 throw fcpException;
584                         }
585                 }
586
587                 /**
588                  * The FCP commands that actually get executed.
589                  *
590                  * @throws IOException
591                  *             if an I/O error occurs
592                  */
593                 public abstract void run() throws IOException;
594
595                 /**
596                  * {@inheritDoc}
597                  */
598                 @Override
599                 public void connectionClosed(FcpConnection fcpConnection, Throwable throwable) {
600                         fcpException = new FcpException("Connection closed", throwable);
601                         completionLatch.countDown();
602                 }
603
604                 /**
605                  * {@inheritDoc}
606                  */
607                 @Override
608                 public void receivedCloseConnectionDuplicateClientName(FcpConnection fcpConnection, CloseConnectionDuplicateClientName closeConnectionDuplicateClientName) {
609                         fcpException = new FcpException("Connection closed, duplicate client name");
610                         completionLatch.countDown();
611                 }
612
613                 /**
614                  * {@inheritDoc}
615                  */
616                 @Override
617                 public void receivedProtocolError(FcpConnection fcpConnection, ProtocolError protocolError) {
618                         fcpException = new FcpException("Protocol error (" + protocolError.getCode() + ", " + protocolError.getCodeDescription());
619                         completionLatch.countDown();
620                 }
621
622         }
623
624 }