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