Remove trusted identities for an own identity if the own identity is removed.
[WoTNS.git] / src / main / java / net / pterodactylus / wotns / freenet / wot / IdentityManager.java
1 /*
2  * Sone - IdentityManager.java - Copyright © 2010 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 3 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, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.wotns.freenet.wot;
19
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.Map.Entry;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.util.logging.Logging;
31 import net.pterodactylus.util.service.AbstractService;
32 import net.pterodactylus.wotns.freenet.plugin.PluginException;
33
34 /**
35  * The identity manager takes care of loading and storing identities, their
36  * contexts, and properties. It does so in a way that does not expose errors via
37  * exceptions but it only logs them and tries to return sensible defaults.
38  * <p>
39  * It is also responsible for polling identities from the Web of Trust plugin
40  * and notifying registered {@link IdentityListener}s when {@link Identity}s and
41  * {@link OwnIdentity}s are discovered or disappearing.
42  *
43  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
44  */
45 public class IdentityManager extends AbstractService {
46
47         /** Object used for synchronization. */
48         private final Object syncObject = new Object() {
49                 /* inner class for better lock names. */
50         };
51
52         /** The logger. */
53         private static final Logger logger = Logging.getLogger(IdentityManager.class);
54
55         /** The event manager. */
56         private final IdentityListenerManager identityListenerManager = new IdentityListenerManager();
57
58         /** The Web of Trust connector. */
59         private final WebOfTrustConnector webOfTrustConnector;
60
61         /** The context to filter for. */
62         private volatile String context;
63
64         /** The currently known own identities. */
65         /* synchronize access on syncObject. */
66         private Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
67
68         /** The currently trusted identities. */
69         private Map<OwnIdentity, Collection<Identity>> currentTrustedIdentities = new HashMap<OwnIdentity, Collection<Identity>>();
70
71         /**
72          * Creates a new identity manager.
73          *
74          * @param webOfTrustConnector
75          *            The Web of Trust connector
76          */
77         public IdentityManager(WebOfTrustConnector webOfTrustConnector) {
78                 super("Sone Identity Manager", false);
79                 this.webOfTrustConnector = webOfTrustConnector;
80         }
81
82         //
83         // LISTENER MANAGEMENT
84         //
85
86         /**
87          * Adds a listener for identity events.
88          *
89          * @param identityListener
90          *            The listener to add
91          */
92         public void addIdentityListener(IdentityListener identityListener) {
93                 identityListenerManager.addListener(identityListener);
94         }
95
96         /**
97          * Removes a listener for identity events.
98          *
99          * @param identityListener
100          *            The listener to remove
101          */
102         public void removeIdentityListener(IdentityListener identityListener) {
103                 identityListenerManager.removeListener(identityListener);
104         }
105
106         //
107         // ACCESSORS
108         //
109
110         /**
111          * Sets the context to filter own identities and trusted identities for.
112          *
113          * @param context
114          *            The context to filter for, or {@code null} to not filter
115          */
116         public void setContext(String context) {
117                 this.context = context;
118         }
119
120         /**
121          * Returns whether the Web of Trust plugin could be reached during the last
122          * try.
123          *
124          * @return {@code true} if the Web of Trust plugin is connected, {@code
125          *         false} otherwise
126          */
127         public boolean isConnected() {
128                 try {
129                         webOfTrustConnector.ping();
130                         return true;
131                 } catch (PluginException pe1) {
132                         /* not connected, ignore. */
133                         return false;
134                 }
135         }
136
137         /**
138          * Returns the own identity with the given ID.
139          *
140          * @param id
141          *            The ID of the own identity
142          * @return The own identity, or {@code null} if there is no such identity
143          */
144         public OwnIdentity getOwnIdentity(String id) {
145                 Set<OwnIdentity> allOwnIdentities = getAllOwnIdentities();
146                 for (OwnIdentity ownIdentity : allOwnIdentities) {
147                         if (ownIdentity.getId().equals(id)) {
148                                 return ownIdentity;
149                         }
150                 }
151                 return null;
152         }
153
154         /**
155          * Returns all own identities.
156          *
157          * @return All own identities
158          */
159         public Set<OwnIdentity> getAllOwnIdentities() {
160                 try {
161                         Set<OwnIdentity> ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
162                         Map<String, OwnIdentity> newOwnIdentities = new HashMap<String, OwnIdentity>();
163                         for (OwnIdentity ownIdentity : ownIdentities) {
164                                 newOwnIdentities.put(ownIdentity.getId(), ownIdentity);
165                         }
166                         checkOwnIdentities(newOwnIdentities);
167                         return ownIdentities;
168                 } catch (WebOfTrustException wote1) {
169                         logger.log(Level.WARNING, "Could not load all own identities!", wote1);
170                         return Collections.emptySet();
171                 }
172         }
173
174         /**
175          * Returns all identities that are trusted by the given own identity. In
176          * addition to all non-own identities the given own identity is also
177          * returned.
178          *
179          * @param ownIdentity
180          *            The own identity to get the trusted identities for
181          * @return The identities trusted by the given own identity
182          */
183         public Set<Identity> getTrustedIdentities(OwnIdentity ownIdentity) {
184                 Set<Identity> identities = new HashSet<Identity>();
185                 if ((context == null) || ownIdentity.getContexts().contains(context)) {
186                         identities.add(ownIdentity);
187                 }
188                 try {
189                         Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context);
190                         Map<String, Identity> newTrustedIdentities = new HashMap<String, Identity>();
191                         for (Identity trustedIdentity : trustedIdentities) {
192                                 newTrustedIdentities.put(trustedIdentity.getId(), trustedIdentity);
193                         }
194                         checkTrustedIdentities(ownIdentity, newTrustedIdentities);
195                 } catch (WebOfTrustException wote1) {
196                         logger.log(Level.WARNING, String.format("Could not load all trusted identities for %s.", ownIdentity), wote1);
197                 }
198                 return identities;
199         }
200
201         //
202         // SERVICE METHODS
203         //
204
205         /**
206          * {@inheritDoc}
207          */
208         @Override
209         protected void serviceRun() {
210                 while (!shouldStop()) {
211                         Map<OwnIdentity, Map<String, Identity>> currentIdentities = new HashMap<OwnIdentity, Map<String, Identity>>();
212                         @SuppressWarnings("hiding")
213                         Map<String, OwnIdentity> currentOwnIdentities = new HashMap<String, OwnIdentity>();
214
215                         Set<OwnIdentity> ownIdentities = null;
216                         boolean identitiesLoaded = false;
217                         try {
218                                 /* get all identities with the wanted context from WoT. */
219                                 ownIdentities = webOfTrustConnector.loadAllOwnIdentities();
220
221                                 /* load trusted identities. */
222                                 for (OwnIdentity ownIdentity : ownIdentities) {
223                                         if ((context != null) && !ownIdentity.hasContext(context)) {
224                                                 continue;
225                                         }
226                                         currentOwnIdentities.put(ownIdentity.getId(), ownIdentity);
227
228                                         Set<Identity> trustedIdentities = webOfTrustConnector.loadTrustedIdentities(ownIdentity, context);
229                                         Map<String, Identity> identities = new HashMap<String, Identity>();
230                                         currentIdentities.put(ownIdentity, identities);
231                                         for (Identity identity : trustedIdentities) {
232                                                 identities.put(identity.getId(), identity);
233                                         }
234
235                                         /*
236                                          * add own identities, too, as long as the WoT doesn’t do
237                                          * that.
238                                          */
239                                         for (OwnIdentity additionalOwnIdentity : ownIdentities) {
240                                                 if (additionalOwnIdentity == ownIdentity) {
241                                                         continue;
242                                                 }
243                                                 if ((context != null) && !additionalOwnIdentity.hasContext(context)) {
244                                                         continue;
245                                                 }
246                                                 identities.put(additionalOwnIdentity.getId(), additionalOwnIdentity);
247                                         }
248                                 }
249                                 identitiesLoaded = true;
250                         } catch (WebOfTrustException wote1) {
251                                 logger.log(Level.WARNING, "WoT has disappeared!", wote1);
252                         }
253
254                         if (identitiesLoaded) {
255
256                                 /* check for changes. */
257                                 checkOwnIdentities(currentOwnIdentities);
258
259                                 /* now check for changes in remote identities. */
260                                 for (OwnIdentity ownIdentity : currentOwnIdentities.values()) {
261                                         checkTrustedIdentities(ownIdentity, currentIdentities.get(ownIdentity));
262                                 }
263                         }
264
265                         /* wait a minute before checking again. */
266                         sleep(60 * 1000);
267                 }
268         }
269
270         //
271         // PRIVATE METHODS
272         //
273
274         /**
275          * Checks the given new list of own identities for added or removed own
276          * identities, as compared to {@link #currentOwnIdentities}.
277          *
278          * @param newOwnIdentities
279          *            The new own identities
280          */
281         private void checkOwnIdentities(Map<String, OwnIdentity> newOwnIdentities) {
282                 synchronized (syncObject) {
283
284                         /* find removed own identities: */
285                         for (OwnIdentity oldOwnIdentity : currentOwnIdentities.values()) {
286                                 if (!newOwnIdentities.containsKey(oldOwnIdentity.getId())) {
287                                         identityListenerManager.fireOwnIdentityRemoved(oldOwnIdentity);
288                                         currentTrustedIdentities.remove(oldOwnIdentity);
289                                 }
290                         }
291
292                         /* find added own identities. */
293                         for (OwnIdentity currentOwnIdentity : newOwnIdentities.values()) {
294                                 if (!currentOwnIdentities.containsKey(currentOwnIdentity.getId())) {
295                                         identityListenerManager.fireOwnIdentityAdded(currentOwnIdentity);
296                                 }
297                         }
298
299                         currentOwnIdentities.clear();
300                         currentOwnIdentities.putAll(newOwnIdentities);
301                 }
302         }
303
304         /**
305          * Checks the given identities for changes since the last check.
306          *
307          * @param ownIdentity
308          *            The own identity trusting the given identities
309          * @param trustedIdentities
310          *            The trusted identities
311          */
312         private void checkTrustedIdentities(OwnIdentity ownIdentity, Map<String, Identity> trustedIdentities) {
313
314                 @SuppressWarnings("hiding")
315                 Map<String, Identity> currentTrustedIdentities = new HashMap<String, Identity>();
316                 synchronized (syncObject) {
317                         if (this.currentTrustedIdentities.containsKey(ownIdentity)) {
318                                 for (Identity identity : this.currentTrustedIdentities.get(ownIdentity)) {
319                                         currentTrustedIdentities.put(identity.getId(), identity);
320                                 }
321                         }
322                 }
323
324                 /* find new identities. */
325                 for (Identity currentIdentity : trustedIdentities.values()) {
326                         if (!currentTrustedIdentities.containsKey(currentIdentity.getId())) {
327                                 identityListenerManager.fireIdentityAdded(ownIdentity, currentIdentity);
328                         }
329                 }
330
331                 /* find removed identities. */
332                 for (Identity oldIdentity : currentTrustedIdentities.values()) {
333                         if (!trustedIdentities.containsKey(oldIdentity.getId())) {
334                                 identityListenerManager.fireIdentityRemoved(ownIdentity, oldIdentity);
335                         }
336                 }
337
338                 /* check for changes in the contexts. */
339                 for (Identity oldIdentity : currentTrustedIdentities.values()) {
340                         if (!trustedIdentities.containsKey(oldIdentity.getId())) {
341                                 continue;
342                         }
343                         Identity newIdentity = trustedIdentities.get(oldIdentity.getId());
344                         Set<String> oldContexts = oldIdentity.getContexts();
345                         Set<String> newContexts = newIdentity.getContexts();
346                         if (oldContexts.size() != newContexts.size()) {
347                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
348                                 continue;
349                         }
350                         boolean changed = false;
351                         for (String oldContext : oldContexts) {
352                                 if (!newContexts.contains(oldContext)) {
353                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
354                                         changed = true;
355                                         break;
356                                 }
357                         }
358                         if (changed) {
359                                 continue;
360                         }
361                         Map<String, String> oldProperties = oldIdentity.getProperties();
362                         Map<String, String> newProperties = newIdentity.getProperties();
363                         if (oldProperties.size() != newProperties.size()) {
364                                 identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
365                                 continue;
366                         }
367                         for (Entry<String, String> oldProperty : oldProperties.entrySet()) {
368                                 if (!newProperties.containsKey(oldProperty.getKey()) || !newProperties.get(oldProperty.getKey()).equals(oldProperty.getValue())) {
369                                         identityListenerManager.fireIdentityUpdated(ownIdentity, newIdentity);
370                                         break;
371                                 }
372                         }
373                 }
374
375                 synchronized (syncObject) {
376                         this.currentTrustedIdentities.put(ownIdentity, trustedIdentities.values());
377                 }
378
379         }
380
381 }