Update year in copyright headers.
[jSite.git] / src / main / java / de / todesbaum / jsite / application / WebOfTrustInterface.java
1 /*
2  * jSite - WebOfTrustInterface.java - Copyright © 2012–2014 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 de.todesbaum.jsite.application;
20
21 import java.io.IOException;
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.concurrent.atomic.AtomicLong;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
28 import net.pterodactylus.util.logging.Logging;
29 import de.todesbaum.util.freenet.fcp2.Client;
30 import de.todesbaum.util.freenet.fcp2.Connection;
31 import de.todesbaum.util.freenet.fcp2.FcpPluginMessage;
32 import de.todesbaum.util.freenet.fcp2.Message;
33 import de.todesbaum.util.freenet.fcp2.wot.DefaultOwnIdentity;
34 import de.todesbaum.util.freenet.fcp2.wot.OwnIdentity;
35
36 /**
37  * FCP interface to the node’s web of trust.
38  *
39  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
40  */
41 public class WebOfTrustInterface implements Runnable {
42
43         /** The logger. */
44         private static final Logger logger = Logging.getLogger(WebOfTrustInterface.class);
45
46         /** Unique ID for the command identifier. */
47         private static final AtomicLong commandCounter = new AtomicLong(System.nanoTime());
48
49         /** Object used for synchronization. */
50         private final Object syncObject = new Object();
51
52         /** The freenet interface. */
53         private final Freenet7Interface freenetInterface;
54
55         /** Whether the interface should stop. */
56         private boolean shouldStop;
57
58         /** The own identities. */
59         private final List<OwnIdentity> ownIdentities = new ArrayList<OwnIdentity>();
60
61         /**
62          * Creates a new web of trust interface.
63          *
64          * @param freenetInterface
65          *            The freenet interface
66          */
67         public WebOfTrustInterface(Freenet7Interface freenetInterface) {
68                 this.freenetInterface = freenetInterface;
69         }
70
71         //
72         // ACCESSORS
73         //
74
75         /**
76          * Returns a list of own identities. If the identities have not yet been
77          * retrieved, an empty list is returned.
78          *
79          * @return The list of own identities
80          */
81         public List<OwnIdentity> getOwnIdentities() {
82                 synchronized (ownIdentities) {
83                         return new ArrayList<OwnIdentity>(ownIdentities);
84                 }
85         }
86
87         //
88         // ACTIONS
89         //
90
91         /**
92          * Starts the web of trust interface.
93          */
94         public void start() {
95                 Thread webOfTrustThread = new Thread(this, "WebOfTrust Interface");
96                 webOfTrustThread.start();
97         }
98
99         /**
100          * Stops the web of trust interface
101          */
102         public void stop() {
103                 synchronized (syncObject) {
104                         shouldStop = true;
105                         syncObject.notifyAll();
106                 }
107         }
108
109         //
110         // PRIVATE METHODS
111         //
112
113         /**
114          * Returns whether the web of trust interface should stop.
115          *
116          * @return {@code true} if the web of trust interface should stop,
117          *         {@code false} otherwise
118          */
119         private boolean shouldStop() {
120                 synchronized (syncObject) {
121                         return shouldStop;
122                 }
123         }
124
125         /**
126          * Returns the essential parts of an URI, consisting of only the
127          * private/public key, decryption key, and the flags.
128          *
129          * @param uri
130          *            The URI to shorten
131          * @return The shortened URI
132          */
133         private static String shortenUri(String uri) {
134                 String shortenedUri = uri;
135                 if (shortenedUri.charAt(3) == '@') {
136                         shortenedUri = shortenedUri.substring(4);
137                 }
138                 if (shortenedUri.indexOf('/') > -1) {
139                         shortenedUri = shortenedUri.substring(0, shortenedUri.indexOf('/'));
140                 }
141                 return shortenedUri;
142         }
143
144         //
145         // RUNNABLE METHODS
146         //
147
148         /**
149          * {@inheritDoc}
150          */
151         @Override
152         public void run() {
153                 boolean waitBeforeReconnect = false;
154                 while (!shouldStop()) {
155
156                         /* wait a minute before reconnecting for another try. */
157                         if (waitBeforeReconnect) {
158                                 logger.log(Level.FINE, "Waiting 60 seconds before reconnecting.");
159                                 synchronized (syncObject) {
160                                         try {
161                                                 syncObject.wait(60 * 1000);
162                                         } catch (InterruptedException ie1) {
163                                                 /* ignore. */
164                                         }
165                                 }
166                                 if (shouldStop()) {
167                                         continue;
168                                 }
169                         } else {
170                                 waitBeforeReconnect = true;
171                         }
172
173                         try {
174
175                                 /* connect. */
176                                 Connection connection = freenetInterface.getConnection("jSite-WoT-Connector");
177                                 logger.log(Level.INFO, String.format("Trying to connect to node at %s...", freenetInterface.getNode()));
178                                 if (!connection.connect()) {
179                                         logger.log(Level.WARNING, "Connection failed.");
180                                         continue;
181                                 }
182                                 Client client = new Client(connection);
183
184                                 /* send FCP command to WebOfTrust plugin. */
185                                 String messageIdentifier = "jSite-WoT-Command-" + commandCounter.getAndIncrement();
186                                 FcpPluginMessage pluginMessage = new FcpPluginMessage(messageIdentifier);
187                                 pluginMessage.setPluginName("plugins.WebOfTrust.WebOfTrust");
188                                 pluginMessage.setParameter("Message", "GetOwnIdentities");
189                                 client.execute(pluginMessage);
190
191                                 /* read a message. */
192                                 Message message = null;
193                                 while (!client.isDisconnected() && !shouldStop() && (message == null)) {
194                                         message = client.readMessage(1000);
195                                 }
196                                 if (message == null) {
197                                         continue;
198                                 }
199
200                                 /* evaluate message. */
201                                 if (message.getName().equals("FCPPluginReply")) {
202                                         logger.log(Level.FINE, "Got matching Reply from WebOfTrust.");
203                                         /* parse identities. */
204                                         List<OwnIdentity> ownIdentities = new ArrayList<OwnIdentity>();
205                                         int identityCounter = -1;
206                                         while (message.get("Replies.Identity" + ++identityCounter) != null) {
207                                                 String id = message.get("Replies.Identity" + identityCounter);
208                                                 String nickname = message.get("Replies.Nickname" + identityCounter);
209                                                 String requestUri = shortenUri(message.get("Replies.RequestURI" + identityCounter));
210                                                 String insertUri = shortenUri(message.get("Replies.InsertURI" + identityCounter));
211                                                 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(id, nickname, requestUri, insertUri);
212                                                 logger.log(Level.FINE, String.format("Parsed Own Identity %s.", ownIdentity));
213                                                 ownIdentities.add(ownIdentity);
214                                         }
215                                         logger.log(Level.INFO, String.format("Parsed %d Own Identities.", ownIdentities.size()));
216
217                                         synchronized (this.ownIdentities) {
218                                                 this.ownIdentities.clear();
219                                                 this.ownIdentities.addAll(ownIdentities);
220                                         }
221                                 } else if ("ProtocolError".equals(message.getName())) {
222                                         logger.log(Level.WARNING, "WebOfTrust Plugin not found!");
223                                 } else if ("Error".equals(message.getName())) {
224                                         logger.log(Level.WARNING, "WebOfTrust Plugin returned an error!");
225                                 }
226
227                                 /* disconnect. */
228                                 logger.log(Level.INFO, "Disconnecting from Node.");
229                                 connection.disconnect();
230
231                         } catch (IOException ioe1) {
232                                 logger.log(Level.WARNING, String.format("Communication with node at %s failed.", freenetInterface.getNode()), ioe1);
233                         }
234
235                 }
236         }
237
238 }