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