d1fd31d4f17d7319a937518b741164a082cad8d9
[jSite.git] / src / main / java / de / todesbaum / jsite / application / WebOfTrustInterface.java
1 /*
2  * jSite - WebOfTrustInterface.java - Copyright © 2012 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         // RUNNABLE METHODS
127         //
128
129         /**
130          * {@inheritDoc}
131          */
132         @Override
133         public void run() {
134                 boolean waitBeforeReconnect = false;
135                 while (!shouldStop()) {
136
137                         /* wait a minute before reconnecting for another try. */
138                         if (waitBeforeReconnect) {
139                                 logger.log(Level.FINE, "Waiting 60 seconds before reconnecting.");
140                                 synchronized (syncObject) {
141                                         try {
142                                                 syncObject.wait(60 * 1000);
143                                         } catch (InterruptedException ie1) {
144                                                 /* ignore. */
145                                         }
146                                 }
147                                 if (shouldStop()) {
148                                         continue;
149                                 }
150                         } else {
151                                 waitBeforeReconnect = true;
152                         }
153
154                         try {
155
156                                 /* connect. */
157                                 Connection connection = freenetInterface.getConnection("jSite-WoT-Connector");
158                                 logger.log(Level.INFO, String.format("Trying to connect to node at %s...", freenetInterface.getNode()));
159                                 if (!connection.connect()) {
160                                         logger.log(Level.WARNING, "Connection failed.");
161                                         continue;
162                                 }
163                                 Client client = new Client(connection);
164
165                                 /* send FCP command to WebOfTrust plugin. */
166                                 String messageIdentifier = "jSite-WoT-Command-" + commandCounter.getAndIncrement();
167                                 FcpPluginMessage pluginMessage = new FcpPluginMessage(messageIdentifier);
168                                 pluginMessage.setPluginName("plugins.WebOfTrust.WebOfTrust");
169                                 pluginMessage.setParameter("Message", "GetOwnIdentities");
170                                 client.execute(pluginMessage);
171
172                                 /* read a message. */
173                                 Message message = null;
174                                 while (!client.isDisconnected() && !shouldStop() && (message == null)) {
175                                         message = client.readMessage(1000);
176                                 }
177                                 if (message == null) {
178                                         continue;
179                                 }
180
181                                 /* evaluate message. */
182                                 if (message.getName().equals("FCPPluginReply")) {
183                                         logger.log(Level.FINE, "Got matching Reply from WebOfTrust.");
184                                         /* parse identities. */
185                                         List<OwnIdentity> ownIdentities = new ArrayList<OwnIdentity>();
186                                         int identityCounter = -1;
187                                         while (message.get("Replies.Identity" + ++identityCounter) != null) {
188                                                 String id = message.get("Replies.Identity" + identityCounter);
189                                                 String nickname = message.get("Replies.Nickname " + identityCounter);
190                                                 String requestUri = message.get("Replies.RequestURI" + identityCounter);
191                                                 String insertUri = message.get("Replies.InsertURI" + identityCounter);
192                                                 DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(id, nickname, requestUri, insertUri);
193                                                 logger.log(Level.FINE, String.format("Parsed Own Identity %s.", ownIdentity));
194                                                 ownIdentities.add(ownIdentity);
195                                         }
196                                         logger.log(Level.INFO, String.format("Parsed %d Own Identities.", ownIdentities.size()));
197
198                                         synchronized (this.ownIdentities) {
199                                                 this.ownIdentities.clear();
200                                                 this.ownIdentities.addAll(ownIdentities);
201                                         }
202                                 } else if ("ProtocolError".equals(message.getName())) {
203                                         logger.log(Level.WARNING, "WebOfTrust Plugin not found!");
204                                 }
205
206                                 /* disconnect. */
207                                 logger.log(Level.INFO, "Disconnecting from Node.");
208                                 connection.disconnect();
209
210                         } catch (IOException ioe1) {
211                                 logger.log(Level.WARNING, String.format("Communication with node at %s failed.", freenetInterface.getNode()), ioe1);
212                         }
213
214                 }
215         }
216
217 }