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