Reformat source code, new line length for comments (79), some trailing whitespace...
[jFCPlib.git] / src / main / java / net / pterodactylus / fcp / FcpConnection.java
1 /*
2  * jFCPlib - FpcConnection.java - Copyright © 2008 David Roden
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */
18
19 package net.pterodactylus.fcp;
20
21 import java.io.Closeable;
22 import java.io.FilterInputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.net.InetAddress;
27 import java.net.Socket;
28 import java.net.UnknownHostException;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.Map;
32 import java.util.logging.Logger;
33
34 import net.pterodactylus.util.logging.Logging;
35
36 /**
37  * An FCP connection to a Freenet node.
38  *
39  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
40  */
41 public class FcpConnection implements Closeable {
42
43         /** Logger. */
44         private static final Logger logger = Logging.getLogger(FcpConnection.class.getName());
45
46         /** The default port for FCP v2. */
47         public static final int DEFAULT_PORT = 9481;
48
49         /** Listener management. */
50         private final FcpListenerManager fcpListenerManager = new FcpListenerManager(this);
51
52         /** The address of the node. */
53         private final InetAddress address;
54
55         /** The port number of the node’s FCP port. */
56         private final int port;
57
58         /** The remote socket. */
59         private Socket remoteSocket;
60
61         /** The input stream from the node. */
62         private InputStream remoteInputStream;
63
64         /** The output stream to the node. */
65         private OutputStream remoteOutputStream;
66
67         /** The connection handler. */
68         private FcpConnectionHandler connectionHandler;
69
70         /** Incoming message statistics. */
71         private static final Map<String, Integer> incomingMessageStatistics = Collections.synchronizedMap(new HashMap<String, Integer>());
72
73         /**
74          * Creates a new FCP connection to the freenet node running on localhost,
75          * using the default port.
76          *
77          * @throws UnknownHostException
78          *             if the hostname can not be resolved
79          */
80         public FcpConnection() throws UnknownHostException {
81                 this(InetAddress.getLocalHost());
82         }
83
84         /**
85          * Creates a new FCP connection to the Freenet node running on the given
86          * host, listening on the default port.
87          *
88          * @param host
89          *            The hostname of the Freenet node
90          * @throws UnknownHostException
91          *             if <code>host</code> can not be resolved
92          */
93         public FcpConnection(String host) throws UnknownHostException {
94                 this(host, DEFAULT_PORT);
95         }
96
97         /**
98          * Creates a new FCP connection to the Freenet node running on the given
99          * host, listening on the given port.
100          *
101          * @param host
102          *            The hostname of the Freenet node
103          * @param port
104          *            The port number of the node’s FCP port
105          * @throws UnknownHostException
106          *             if <code>host</code> can not be resolved
107          */
108         public FcpConnection(String host, int port) throws UnknownHostException {
109                 this(InetAddress.getByName(host), port);
110         }
111
112         /**
113          * Creates a new FCP connection to the Freenet node running at the given
114          * address, listening on the default port.
115          *
116          * @param address
117          *            The address of the Freenet node
118          */
119         public FcpConnection(InetAddress address) {
120                 this(address, DEFAULT_PORT);
121         }
122
123         /**
124          * Creates a new FCP connection to the Freenet node running at the given
125          * address, listening on the given port.
126          *
127          * @param address
128          *            The address of the Freenet node
129          * @param port
130          *            The port number of the node’s FCP port
131          */
132         public FcpConnection(InetAddress address, int port) {
133                 this.address = address;
134                 this.port = port;
135         }
136
137         //
138         // LISTENER MANAGEMENT
139         //
140
141         /**
142          * Adds the given listener to the list of listeners.
143          *
144          * @param fcpListener
145          *            The listener to add
146          */
147         public void addFcpListener(FcpListener fcpListener) {
148                 fcpListenerManager.addListener(fcpListener);
149         }
150
151         /**
152          * Removes the given listener from the list of listeners.
153          *
154          * @param fcpListener
155          *            The listener to remove
156          */
157         public void removeFcpListener(FcpListener fcpListener) {
158                 fcpListenerManager.removeListener(fcpListener);
159         }
160
161         //
162         // ACTIONS
163         //
164
165         /**
166          * Connects to the node.
167          *
168          * @throws IOException
169          *             if an I/O error occurs
170          * @throws IllegalStateException
171          *             if there is already a connection to the node
172          */
173         public synchronized void connect() throws IOException, IllegalStateException {
174                 if (connectionHandler != null) {
175                         throw new IllegalStateException("already connected, disconnect first");
176                 }
177                 logger.info("connecting to " + address + ":" + port + "…");
178                 remoteSocket = new Socket(address, port);
179                 remoteInputStream = remoteSocket.getInputStream();
180                 remoteOutputStream = remoteSocket.getOutputStream();
181                 new Thread(connectionHandler = new FcpConnectionHandler(this, remoteInputStream)).start();
182         }
183
184         /**
185          * Disconnects from the node. If there is no connection to the node, this
186          * method does nothing.
187          *
188          * @deprecated Use {@link #close()} instead
189          */
190         @Deprecated
191         public synchronized void disconnect() {
192                 close();
193         }
194
195         /**
196          * Closes the connection. If there is no connection to the node, this
197          * method does nothing.
198          */
199         @Override
200         public void close() {
201                 handleDisconnect(null);
202         }
203
204         /**
205          * Sends the given FCP message.
206          *
207          * @param fcpMessage
208          *            The FCP message to send
209          * @throws IOException
210          *             if an I/O error occurs
211          */
212         public synchronized void sendMessage(FcpMessage fcpMessage) throws IOException {
213                 logger.fine("sending message: " + fcpMessage.getName());
214                 fcpMessage.write(remoteOutputStream);
215         }
216
217         //
218         // PACKAGE-PRIVATE METHODS
219         //
220
221         /**
222          * Handles the given message, notifying listeners. This message should only
223          * be called by {@link FcpConnectionHandler}.
224          *
225          * @param fcpMessage
226          *            The received message
227          */
228         void handleMessage(FcpMessage fcpMessage) {
229                 logger.fine("received message: " + fcpMessage.getName());
230                 String messageName = fcpMessage.getName();
231                 countMessage(messageName);
232                 if ("SimpleProgress".equals(messageName)) {
233                         fcpListenerManager.fireReceivedSimpleProgress(new SimpleProgress(fcpMessage));
234                 } else if ("ProtocolError".equals(messageName)) {
235                         fcpListenerManager.fireReceivedProtocolError(new ProtocolError(fcpMessage));
236                 } else if ("PersistentGet".equals(messageName)) {
237                         fcpListenerManager.fireReceivedPersistentGet(new PersistentGet(fcpMessage));
238                 } else if ("PersistentPut".equals(messageName)) {
239                         fcpListenerManager.fireReceivedPersistentPut(new PersistentPut(fcpMessage));
240                 } else if ("PersistentPutDir".equals(messageName)) {
241                         fcpListenerManager.fireReceivedPersistentPutDir(new PersistentPutDir(fcpMessage));
242                 } else if ("URIGenerated".equals(messageName)) {
243                         fcpListenerManager.fireReceivedURIGenerated(new URIGenerated(fcpMessage));
244                 } else if ("EndListPersistentRequests".equals(messageName)) {
245                         fcpListenerManager.fireReceivedEndListPersistentRequests(new EndListPersistentRequests(fcpMessage));
246                 } else if ("Peer".equals(messageName)) {
247                         fcpListenerManager.fireReceivedPeer(new Peer(fcpMessage));
248                 } else if ("PeerNote".equals(messageName)) {
249                         fcpListenerManager.fireReceivedPeerNote(new PeerNote(fcpMessage));
250                 } else if ("StartedCompression".equals(messageName)) {
251                         fcpListenerManager.fireReceivedStartedCompression(new StartedCompression(fcpMessage));
252                 } else if ("FinishedCompression".equals(messageName)) {
253                         fcpListenerManager.fireReceivedFinishedCompression(new FinishedCompression(fcpMessage));
254                 } else if ("GetFailed".equals(messageName)) {
255                         fcpListenerManager.fireReceivedGetFailed(new GetFailed(fcpMessage));
256                 } else if ("PutFetchable".equals(messageName)) {
257                         fcpListenerManager.fireReceivedPutFetchable(new PutFetchable(fcpMessage));
258                 } else if ("PutSuccessful".equals(messageName)) {
259                         fcpListenerManager.fireReceivedPutSuccessful(new PutSuccessful(fcpMessage));
260                 } else if ("PutFailed".equals(messageName)) {
261                         fcpListenerManager.fireReceivedPutFailed(new PutFailed(fcpMessage));
262                 } else if ("DataFound".equals(messageName)) {
263                         fcpListenerManager.fireReceivedDataFound(new DataFound(fcpMessage));
264                 } else if ("SubscribedUSKUpdate".equals(messageName)) {
265                         fcpListenerManager.fireReceivedSubscribedUSKUpdate(new SubscribedUSKUpdate(fcpMessage));
266                 } else if ("IdentifierCollision".equals(messageName)) {
267                         fcpListenerManager.fireReceivedIdentifierCollision(new IdentifierCollision(fcpMessage));
268                 } else if ("AllData".equals(messageName)) {
269                         LimitedInputStream payloadInputStream = getInputStream(FcpUtils.safeParseLong(fcpMessage.getField("DataLength")));
270                         fcpListenerManager.fireReceivedAllData(new AllData(fcpMessage, payloadInputStream));
271                         try {
272                                 payloadInputStream.consume();
273                         } catch (IOException ioe1) {
274                                 /* well, ignore. when the connection handler fails, all fails. */
275                         }
276                 } else if ("EndListPeerNotes".equals(messageName)) {
277                         fcpListenerManager.fireReceivedEndListPeerNotes(new EndListPeerNotes(fcpMessage));
278                 } else if ("EndListPeers".equals(messageName)) {
279                         fcpListenerManager.fireReceivedEndListPeers(new EndListPeers(fcpMessage));
280                 } else if ("SSKKeypair".equals(messageName)) {
281                         fcpListenerManager.fireReceivedSSKKeypair(new SSKKeypair(fcpMessage));
282                 } else if ("PeerRemoved".equals(messageName)) {
283                         fcpListenerManager.fireReceivedPeerRemoved(new PeerRemoved(fcpMessage));
284                 } else if ("PersistentRequestModified".equals(messageName)) {
285                         fcpListenerManager.fireReceivedPersistentRequestModified(new PersistentRequestModified(fcpMessage));
286                 } else if ("PersistentRequestRemoved".equals(messageName)) {
287                         fcpListenerManager.fireReceivedPersistentRequestRemoved(new PersistentRequestRemoved(fcpMessage));
288                 } else if ("UnknownPeerNoteType".equals(messageName)) {
289                         fcpListenerManager.fireReceivedUnknownPeerNoteType(new UnknownPeerNoteType(fcpMessage));
290                 } else if ("UnknownNodeIdentifier".equals(messageName)) {
291                         fcpListenerManager.fireReceivedUnknownNodeIdentifier(new UnknownNodeIdentifier(fcpMessage));
292                 } else if ("FCPPluginReply".equals(messageName)) {
293                         LimitedInputStream payloadInputStream = getInputStream(FcpUtils.safeParseLong(fcpMessage.getField("DataLength")));
294                         fcpListenerManager.fireReceivedFCPPluginReply(new FCPPluginReply(fcpMessage, payloadInputStream));
295                         try {
296                                 payloadInputStream.consume();
297                         } catch (IOException ioe1) {
298                                 /* ignore. */
299                         }
300                 } else if ("PluginInfo".equals(messageName)) {
301                         fcpListenerManager.fireReceivedPluginInfo(new PluginInfo(fcpMessage));
302                 } else if ("NodeData".equals(messageName)) {
303                         fcpListenerManager.fireReceivedNodeData(new NodeData(fcpMessage));
304                 } else if ("TestDDAReply".equals(messageName)) {
305                         fcpListenerManager.fireReceivedTestDDAReply(new TestDDAReply(fcpMessage));
306                 } else if ("TestDDAComplete".equals(messageName)) {
307                         fcpListenerManager.fireReceivedTestDDAComplete(new TestDDAComplete(fcpMessage));
308                 } else if ("ConfigData".equals(messageName)) {
309                         fcpListenerManager.fireReceivedConfigData(new ConfigData(fcpMessage));
310                 } else if ("NodeHello".equals(messageName)) {
311                         fcpListenerManager.fireReceivedNodeHello(new NodeHello(fcpMessage));
312                 } else if ("CloseConnectionDuplicateClientName".equals(messageName)) {
313                         fcpListenerManager.fireReceivedCloseConnectionDuplicateClientName(new CloseConnectionDuplicateClientName(fcpMessage));
314                 } else if ("SentFeed".equals(messageName)) {
315                         fcpListenerManager.fireSentFeed(new SentFeed(fcpMessage));
316                 } else if ("ReceivedBookmarkFeed".equals(messageName)) {
317                         fcpListenerManager.fireReceivedBookmarkFeed(new ReceivedBookmarkFeed(fcpMessage));
318                 } else {
319                         fcpListenerManager.fireMessageReceived(fcpMessage);
320                 }
321         }
322
323         /**
324          * Handles a disconnect from the node.
325          *
326          * @param throwable
327          *            The exception that caused the disconnect, or
328          *            <code>null</code> if there was no exception
329          */
330         synchronized void handleDisconnect(Throwable throwable) {
331                 FcpUtils.close(remoteInputStream);
332                 FcpUtils.close(remoteOutputStream);
333                 FcpUtils.close(remoteSocket);
334                 if (connectionHandler != null) {
335                         connectionHandler.stop();
336                         connectionHandler = null;
337                         fcpListenerManager.fireConnectionClosed(throwable);
338                 }
339         }
340
341         //
342         // PRIVATE METHODS
343         //
344
345         /**
346          * Incremets the counter in {@link #incomingMessageStatistics} by
347          * <cod>1</code> for the given message name.
348          *
349          * @param name
350          *            The name of the message to count
351          */
352         private void countMessage(String name) {
353                 int oldValue = 0;
354                 if (incomingMessageStatistics.containsKey(name)) {
355                         oldValue = incomingMessageStatistics.get(name);
356                 }
357                 incomingMessageStatistics.put(name, oldValue + 1);
358                 logger.finest("count for " + name + ": " + (oldValue + 1));
359         }
360
361         /**
362          * Returns a limited input stream from the node’s input stream.
363          *
364          * @param dataLength
365          *            The length of the stream
366          * @return The limited input stream
367          */
368         private synchronized LimitedInputStream getInputStream(long dataLength) {
369                 if (dataLength <= 0) {
370                         return new LimitedInputStream(null, 0);
371                 }
372                 return new LimitedInputStream(remoteInputStream, dataLength);
373         }
374
375         /**
376          * A wrapper around an {@link InputStream} that only supplies a limit
377          * number of bytes from the underlying input stream.
378          *
379          * @author David ‘Bombe’ Roden &lt;bombe@freenetproject.org&gt;
380          */
381         private static class LimitedInputStream extends FilterInputStream {
382
383                 /** The remaining number of bytes that can be read. */
384                 private long remaining;
385
386                 /**
387                  * Creates a new LimitedInputStream that supplies at most
388                  * <code>length</code> bytes from the given input stream.
389                  *
390                  * @param inputStream
391                  *            The input stream
392                  * @param length
393                  *            The number of bytes to read
394                  */
395                 public LimitedInputStream(InputStream inputStream, long length) {
396                         super(inputStream);
397                         remaining = length;
398                 }
399
400                 /**
401                  * @see java.io.FilterInputStream#available()
402                  */
403                 @Override
404                 public synchronized int available() throws IOException {
405                         if (remaining == 0) {
406                                 return 0;
407                         }
408                         return (int) Math.min(super.available(), Math.min(Integer.MAX_VALUE, remaining));
409                 }
410
411                 /**
412                  * @see java.io.FilterInputStream#read()
413                  */
414                 @Override
415                 public synchronized int read() throws IOException {
416                         int read = -1;
417                         if (remaining > 0) {
418                                 read = super.read();
419                                 remaining--;
420                         }
421                         return read;
422                 }
423
424                 /**
425                  * @see java.io.FilterInputStream#read(byte[], int, int)
426                  */
427                 @Override
428                 public synchronized int read(byte[] b, int off, int len) throws IOException {
429                         if (remaining == 0) {
430                                 return -1;
431                         }
432                         int toCopy = (int) Math.min(len, Math.min(remaining, Integer.MAX_VALUE));
433                         int read = super.read(b, off, toCopy);
434                         remaining -= read;
435                         return read;
436                 }
437
438                 /**
439                  * @see java.io.FilterInputStream#skip(long)
440                  */
441                 @Override
442                 public synchronized long skip(long n) throws IOException {
443                         if ((n < 0) || (remaining == 0)) {
444                                 return 0;
445                         }
446                         long skipped = super.skip(Math.min(n, remaining));
447                         remaining -= skipped;
448                         return skipped;
449                 }
450
451                 /**
452                  * {@inheritDoc} This method does nothing, as {@link #mark(int)} and
453                  * {@link #reset()} are not supported.
454                  *
455                  * @see java.io.FilterInputStream#mark(int)
456                  */
457                 @Override
458                 public synchronized void mark(int readlimit) {
459                         /* do nothing. */
460                 }
461
462                 /**
463                  * {@inheritDoc}
464                  *
465                  * @see java.io.FilterInputStream#markSupported()
466                  * @return <code>false</code>
467                  */
468                 @Override
469                 public boolean markSupported() {
470                         return false;
471                 }
472
473                 /**
474                  * {@inheritDoc} This method does nothing, as {@link #mark(int)} and
475                  * {@link #reset()} are not supported.
476                  *
477                  * @see java.io.FilterInputStream#reset()
478                  */
479                 @Override
480                 public synchronized void reset() throws IOException {
481                         /* do nothing. */
482                 }
483
484                 /**
485                  * Consumes the input stream, i.e. read all bytes until the limit is
486                  * reached.
487                  *
488                  * @throws IOException
489                  *             if an I/O error occurs
490                  */
491                 public synchronized void consume() throws IOException {
492                         while (remaining > 0) {
493                                 skip(remaining);
494                         }
495                 }
496
497         }
498
499 }