d3e8747fe521807c5dbfea8f5718f2a3010531e1
[Sone.git] / src / main / java / net / pterodactylus / sone / freenet / wot / WebOfTrustConnector.java
1 /*
2  * Sone - WebOfTrustConnector.java - Copyright © 2010–2013 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.sone.freenet.wot;
19
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.concurrent.atomic.AtomicLong;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27
28 import net.pterodactylus.sone.freenet.plugin.PluginConnector;
29 import net.pterodactylus.sone.freenet.plugin.PluginException;
30 import net.pterodactylus.sone.freenet.plugin.event.ReceivedReplyEvent;
31 import net.pterodactylus.util.logging.Logging;
32
33 import com.google.common.base.Optional;
34 import com.google.common.collect.MapMaker;
35 import com.google.common.eventbus.Subscribe;
36 import com.google.common.primitives.Ints;
37 import com.google.inject.Inject;
38
39 import freenet.support.SimpleFieldSet;
40 import freenet.support.api.Bucket;
41
42 /**
43  * Connector for the Web of Trust plugin.
44  *
45  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
46  */
47 public class WebOfTrustConnector {
48
49         /** The logger. */
50         private static final Logger logger = Logging.getLogger(WebOfTrustConnector.class);
51
52         /** The name of the WoT plugin. */
53         private static final String WOT_PLUGIN_NAME = "plugins.WebOfTrust.WebOfTrust";
54
55         /** Counter for connection identifiers. */
56         private final AtomicLong counter = new AtomicLong();
57
58         /** The plugin connector. */
59         private final PluginConnector pluginConnector;
60
61         /** Map for replies. */
62         private final Map<PluginIdentifier, Reply> replies = new MapMaker().makeMap();
63
64         /**
65          * Creates a new Web of Trust connector that uses the given plugin
66          * connector.
67          *
68          * @param pluginConnector
69          *            The plugin connector
70          */
71         @Inject
72         public WebOfTrustConnector(PluginConnector pluginConnector) {
73                 this.pluginConnector = pluginConnector;
74         }
75
76         //
77         // ACTIONS
78         //
79
80         /**
81          * Stops the web of trust connector.
82          */
83         public void stop() {
84                 /* does nothing. */
85         }
86
87         /**
88          * Loads all own identities from the Web of Trust plugin.
89          *
90          * @return All own identity
91          * @throws WebOfTrustException
92          *             if the own identities can not be loaded
93          */
94         public Set<OwnIdentity> loadAllOwnIdentities() throws WebOfTrustException {
95                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetOwnIdentities").get());
96                 SimpleFieldSet fields = reply.getFields();
97                 int ownIdentityCounter = -1;
98                 Set<OwnIdentity> ownIdentities = new HashSet<OwnIdentity>();
99                 while (true) {
100                         String id = fields.get("Identity" + ++ownIdentityCounter);
101                         if (id == null) {
102                                 break;
103                         }
104                         String requestUri = fields.get("RequestURI" + ownIdentityCounter);
105                         String insertUri = fields.get("InsertURI" + ownIdentityCounter);
106                         String nickname = fields.get("Nickname" + ownIdentityCounter);
107                         DefaultOwnIdentity ownIdentity = new DefaultOwnIdentity(id, nickname, requestUri, insertUri);
108                         ownIdentity.setContexts(parseContexts("Contexts" + ownIdentityCounter + ".", fields));
109                         ownIdentity.setProperties(parseProperties("Properties" + ownIdentityCounter + ".", fields));
110                         ownIdentities.add(ownIdentity);
111                 }
112                 return ownIdentities;
113         }
114
115         /**
116          * Loads all identities that the given identities trusts with a score of
117          * more than 0.
118          *
119          * @param ownIdentity
120          *            The own identity
121          * @return All trusted identities
122          * @throws PluginException
123          *             if an error occured talking to the Web of Trust plugin
124          */
125         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity) throws PluginException {
126                 return loadTrustedIdentities(ownIdentity, null);
127         }
128
129         /**
130          * Loads all identities that the given identities trusts with a score of
131          * more than 0 and the (optional) given context.
132          *
133          * @param ownIdentity
134          *            The own identity
135          * @param context
136          *            The context to filter, or {@code null}
137          * @return All trusted identities
138          * @throws PluginException
139          *             if an error occured talking to the Web of Trust plugin
140          */
141         public Set<Identity> loadTrustedIdentities(OwnIdentity ownIdentity, String context) throws PluginException {
142                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentitiesByScore").put("Truster", ownIdentity.getId()).put("Selection", "+").put("Context", (context == null) ? "" : context).put("WantTrustValues", "true").get());
143                 SimpleFieldSet fields = reply.getFields();
144                 Set<Identity> identities = new HashSet<Identity>();
145                 int identityCounter = -1;
146                 while (true) {
147                         String id = fields.get("Identity" + ++identityCounter);
148                         if (id == null) {
149                                 break;
150                         }
151                         String nickname = fields.get("Nickname" + identityCounter);
152                         String requestUri = fields.get("RequestURI" + identityCounter);
153                         DefaultIdentity identity = new DefaultIdentity(id, nickname, requestUri);
154                         identity.setContexts(parseContexts("Contexts" + identityCounter + ".", fields));
155                         identity.setProperties(parseProperties("Properties" + identityCounter + ".", fields));
156                         Integer trust = Ints.tryParse(fields.get("Trust" + identityCounter));
157                         int score = Optional.fromNullable(Ints.tryParse(fields.get("Score" + identityCounter))).or(0);
158                         int rank = Optional.fromNullable(Ints.tryParse(fields.get("Rank" + identityCounter))).or(0);
159                         identity.setTrust(ownIdentity, new Trust(trust, score, rank));
160                         identities.add(identity);
161                 }
162                 return identities;
163         }
164
165         /**
166          * Adds the given context to the given identity.
167          *
168          * @param ownIdentity
169          *            The identity to add the context to
170          * @param context
171          *            The context to add
172          * @throws PluginException
173          *             if an error occured talking to the Web of Trust plugin
174          */
175         public void addContext(OwnIdentity ownIdentity, String context) throws PluginException {
176                 performRequest(SimpleFieldSetConstructor.create().put("Message", "AddContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
177         }
178
179         /**
180          * Removes the given context from the given identity.
181          *
182          * @param ownIdentity
183          *            The identity to remove the context from
184          * @param context
185          *            The context to remove
186          * @throws PluginException
187          *             if an error occured talking to the Web of Trust plugin
188          */
189         public void removeContext(OwnIdentity ownIdentity, String context) throws PluginException {
190                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveContext").put("Identity", ownIdentity.getId()).put("Context", context).get());
191         }
192
193         /**
194          * Returns the value of the property with the given name.
195          *
196          * @param identity
197          *            The identity whose properties to check
198          * @param name
199          *            The name of the property to return
200          * @return The value of the property, or {@code null} if there is no value
201          * @throws PluginException
202          *             if an error occured talking to the Web of Trust plugin
203          */
204         public String getProperty(Identity identity, String name) throws PluginException {
205                 Reply reply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetProperty").put("Identity", identity.getId()).put("Property", name).get());
206                 return reply.getFields().get("Property");
207         }
208
209         /**
210          * Sets the property with the given name to the given value.
211          *
212          * @param ownIdentity
213          *            The identity to set the property on
214          * @param name
215          *            The name of the property to set
216          * @param value
217          *            The value to set
218          * @throws PluginException
219          *             if an error occured talking to the Web of Trust plugin
220          */
221         public void setProperty(OwnIdentity ownIdentity, String name, String value) throws PluginException {
222                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetProperty").put("Identity", ownIdentity.getId()).put("Property", name).put("Value", value).get());
223         }
224
225         /**
226          * Removes the property with the given name.
227          *
228          * @param ownIdentity
229          *            The identity to remove the property from
230          * @param name
231          *            The name of the property to remove
232          * @throws PluginException
233          *             if an error occured talking to the Web of Trust plugin
234          */
235         public void removeProperty(OwnIdentity ownIdentity, String name) throws PluginException {
236                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveProperty").put("Identity", ownIdentity.getId()).put("Property", name).get());
237         }
238
239         /**
240          * Returns the trust for the given identity assigned to it by the given own
241          * identity.
242          *
243          * @param ownIdentity
244          *            The own identity
245          * @param identity
246          *            The identity to get the trust for
247          * @return The trust for the given identity
248          * @throws PluginException
249          *             if an error occured talking to the Web of Trust plugin
250          */
251         public Trust getTrust(OwnIdentity ownIdentity, Identity identity) throws PluginException {
252                 Reply getTrustReply = performRequest(SimpleFieldSetConstructor.create().put("Message", "GetIdentity").put("Truster", ownIdentity.getId()).put("Identity", identity.getId()).get());
253                 String trust = getTrustReply.getFields().get("Trust");
254                 String score = getTrustReply.getFields().get("Score");
255                 String rank = getTrustReply.getFields().get("Rank");
256                 Integer explicit = null;
257                 Integer implicit = null;
258                 Integer distance = null;
259                 try {
260                         explicit = Integer.valueOf(trust);
261                 } catch (NumberFormatException nfe1) {
262                         /* ignore. */
263                 }
264                 try {
265                         implicit = Integer.valueOf(score);
266                         distance = Integer.valueOf(rank);
267                 } catch (NumberFormatException nfe1) {
268                         /* ignore. */
269                 }
270                 return new Trust(explicit, implicit, distance);
271         }
272
273         /**
274          * Sets the trust for the given identity.
275          *
276          * @param ownIdentity
277          *            The trusting identity
278          * @param identity
279          *            The trusted identity
280          * @param trust
281          *            The amount of trust (-100 thru 100)
282          * @param comment
283          *            The comment or explanation of the trust value
284          * @throws PluginException
285          *             if an error occured talking to the Web of Trust plugin
286          */
287         public void setTrust(OwnIdentity ownIdentity, Identity identity, int trust, String comment) throws PluginException {
288                 performRequest(SimpleFieldSetConstructor.create().put("Message", "SetTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).put("Value", String.valueOf(trust)).put("Comment", comment).get());
289         }
290
291         /**
292          * Removes any trust assignment of the given own identity for the given
293          * identity.
294          *
295          * @param ownIdentity
296          *            The own identity
297          * @param identity
298          *            The identity to remove all trust for
299          * @throws WebOfTrustException
300          *             if an error occurs
301          */
302         public void removeTrust(OwnIdentity ownIdentity, Identity identity) throws WebOfTrustException {
303                 performRequest(SimpleFieldSetConstructor.create().put("Message", "RemoveTrust").put("Truster", ownIdentity.getId()).put("Trustee", identity.getId()).get());
304         }
305
306         /**
307          * Pings the Web of Trust plugin. If the plugin can not be reached, a
308          * {@link PluginException} is thrown.
309          *
310          * @throws PluginException
311          *             if the plugin is not loaded
312          */
313         public void ping() throws PluginException {
314                 performRequest(SimpleFieldSetConstructor.create().put("Message", "Ping").get());
315         }
316
317         //
318         // PRIVATE ACTIONS
319         //
320
321         /**
322          * Parses the contexts from the given fields.
323          *
324          * @param prefix
325          *            The prefix to use to access the contexts
326          * @param fields
327          *            The fields to parse the contexts from
328          * @return The parsed contexts
329          */
330         private static Set<String> parseContexts(String prefix, SimpleFieldSet fields) {
331                 Set<String> contexts = new HashSet<String>();
332                 int contextCounter = -1;
333                 while (true) {
334                         String context = fields.get(prefix + "Context" + ++contextCounter);
335                         if (context == null) {
336                                 break;
337                         }
338                         contexts.add(context);
339                 }
340                 return contexts;
341         }
342
343         /**
344          * Parses the properties from the given fields.
345          *
346          * @param prefix
347          *            The prefix to use to access the properties
348          * @param fields
349          *            The fields to parse the properties from
350          * @return The parsed properties
351          */
352         private static Map<String, String> parseProperties(String prefix, SimpleFieldSet fields) {
353                 Map<String, String> properties = new HashMap<String, String>();
354                 int propertiesCounter = -1;
355                 while (true) {
356                         String propertyName = fields.get(prefix + "Property" + ++propertiesCounter + ".Name");
357                         if (propertyName == null) {
358                                 break;
359                         }
360                         String propertyValue = fields.get(prefix + "Property" + propertiesCounter + ".Value");
361                         properties.put(propertyName, propertyValue);
362                 }
363                 return properties;
364         }
365
366         /**
367          * Sends a request containing the given fields and waits for the target
368          * message.
369          *
370          * @param fields
371          *            The fields of the message
372          * @return The reply message
373          * @throws PluginException
374          *             if the request could not be sent
375          */
376         private Reply performRequest(SimpleFieldSet fields) throws PluginException {
377                 return performRequest(fields, null);
378         }
379
380         /**
381          * Sends a request containing the given fields and waits for the target
382          * message.
383          *
384          * @param fields
385          *            The fields of the message
386          * @param data
387          *            The payload of the message
388          * @return The reply message
389          * @throws PluginException
390          *             if the request could not be sent
391          */
392         private Reply performRequest(SimpleFieldSet fields, Bucket data) throws PluginException {
393                 String identifier = "FCP-Command-" + System.currentTimeMillis() + "-" + counter.getAndIncrement();
394                 Reply reply = new Reply();
395                 PluginIdentifier pluginIdentifier = new PluginIdentifier(WOT_PLUGIN_NAME, identifier);
396                 replies.put(pluginIdentifier, reply);
397
398                 logger.log(Level.FINE, String.format("Sending FCP Request: %s", fields.get("Message")));
399                 synchronized (reply) {
400                         try {
401                                 pluginConnector.sendRequest(WOT_PLUGIN_NAME, identifier, fields, data);
402                                 while (reply.getFields() == null) {
403                                         try {
404                                                 reply.wait();
405                                         } catch (InterruptedException ie1) {
406                                                 logger.log(Level.WARNING, String.format("Got interrupted while waiting for reply on %s.", fields.get("Message")), ie1);
407                                         }
408                                 }
409                         } finally {
410                                 replies.remove(pluginIdentifier);
411                         }
412                 }
413                 logger.log(Level.FINEST, String.format("Received FCP Response for %s: %s", fields.get("Message"), (reply.getFields() != null) ? reply.getFields().get("Message") : null));
414                 if ((reply.getFields() == null) || "Error".equals(reply.getFields().get("Message"))) {
415                         throw new PluginException("Could not perform request for " + fields.get("Message"));
416                 }
417                 return reply;
418         }
419
420         /**
421          * Notifies the connector that a plugin reply was received.
422          *
423          * @param receivedReplyEvent
424          *            The event
425          */
426         @Subscribe
427         public void receivedReply(ReceivedReplyEvent receivedReplyEvent) {
428                 PluginIdentifier pluginIdentifier = new PluginIdentifier(receivedReplyEvent.pluginName(), receivedReplyEvent.identifier());
429                 Reply reply = replies.remove(pluginIdentifier);
430                 if (reply == null) {
431                         return;
432                 }
433                 logger.log(Level.FINEST, String.format("Received Reply from Plugin: %s", receivedReplyEvent.fieldSet().get("Message")));
434                 synchronized (reply) {
435                         reply.setFields(receivedReplyEvent.fieldSet());
436                         reply.setData(receivedReplyEvent.data());
437                         reply.notify();
438                 }
439         }
440
441         /**
442          * Container for the data of the reply from a plugin.
443          *
444          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
445          */
446         private static class Reply {
447
448                 /** The fields of the reply. */
449                 private SimpleFieldSet fields;
450
451                 /** The payload of the reply. */
452                 private Bucket data;
453
454                 /** Empty constructor. */
455                 public Reply() {
456                         /* do nothing. */
457                 }
458
459                 /**
460                  * Returns the fields of the reply.
461                  *
462                  * @return The fields of the reply
463                  */
464                 public SimpleFieldSet getFields() {
465                         return fields;
466                 }
467
468                 /**
469                  * Sets the fields of the reply.
470                  *
471                  * @param fields
472                  *            The fields of the reply
473                  */
474                 public void setFields(SimpleFieldSet fields) {
475                         this.fields = fields;
476                 }
477
478                 /**
479                  * Returns the payload of the reply.
480                  *
481                  * @return The payload of the reply (may be {@code null})
482                  */
483                 @SuppressWarnings("unused")
484                 public Bucket getData() {
485                         return data;
486                 }
487
488                 /**
489                  * Sets the payload of the reply.
490                  *
491                  * @param data
492                  *            The payload of the reply (may be {@code null})
493                  */
494                 public void setData(Bucket data) {
495                         this.data = data;
496                 }
497
498         }
499
500         /**
501          * Helper method to create {@link SimpleFieldSet}s with terser code.
502          *
503          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
504          */
505         private static class SimpleFieldSetConstructor {
506
507                 /** The field set being created. */
508                 private SimpleFieldSet simpleFieldSet;
509
510                 /**
511                  * Creates a new simple field set constructor.
512                  *
513                  * @param shortLived
514                  *            {@code true} if the resulting simple field set should be
515                  *            short-lived, {@code false} otherwise
516                  */
517                 private SimpleFieldSetConstructor(boolean shortLived) {
518                         simpleFieldSet = new SimpleFieldSet(shortLived);
519                 }
520
521                 //
522                 // ACCESSORS
523                 //
524
525                 /**
526                  * Returns the created simple field set.
527                  *
528                  * @return The created simple field set
529                  */
530                 public SimpleFieldSet get() {
531                         return simpleFieldSet;
532                 }
533
534                 /**
535                  * Sets the field with the given name to the given value.
536                  *
537                  * @param name
538                  *            The name of the fleld
539                  * @param value
540                  *            The value of the field
541                  * @return This constructor (for method chaining)
542                  */
543                 public SimpleFieldSetConstructor put(String name, String value) {
544                         simpleFieldSet.putOverwrite(name, value);
545                         return this;
546                 }
547
548                 //
549                 // ACTIONS
550                 //
551
552                 /**
553                  * Creates a new simple field set constructor.
554                  *
555                  * @return The created simple field set constructor
556                  */
557                 public static SimpleFieldSetConstructor create() {
558                         return create(true);
559                 }
560
561                 /**
562                  * Creates a new simple field set constructor.
563                  *
564                  * @param shortLived
565                  *            {@code true} if the resulting simple field set should be
566                  *            short-lived, {@code false} otherwise
567                  * @return The created simple field set constructor
568                  */
569                 public static SimpleFieldSetConstructor create(boolean shortLived) {
570                         SimpleFieldSetConstructor simpleFieldSetConstructor = new SimpleFieldSetConstructor(shortLived);
571                         return simpleFieldSetConstructor;
572                 }
573
574         }
575
576         /**
577          * Container for identifying plugins. Plugins are identified by their plugin
578          * name and their unique identifier.
579          *
580          * @author <a href="mailto:d.roden@xplosion.de">David Roden</a>
581          */
582         private static class PluginIdentifier {
583
584                 /** The plugin name. */
585                 private final String pluginName;
586
587                 /** The plugin identifier. */
588                 private final String identifier;
589
590                 /**
591                  * Creates a new plugin identifier.
592                  *
593                  * @param pluginName
594                  *            The name of the plugin
595                  * @param identifier
596                  *            The identifier of the plugin
597                  */
598                 public PluginIdentifier(String pluginName, String identifier) {
599                         this.pluginName = pluginName;
600                         this.identifier = identifier;
601                 }
602
603                 //
604                 // OBJECT METHODS
605                 //
606
607                 /**
608                  * {@inheritDoc}
609                  */
610                 @Override
611                 public int hashCode() {
612                         return pluginName.hashCode() ^ identifier.hashCode();
613                 }
614
615                 /**
616                  * {@inheritDoc}
617                  */
618                 @Override
619                 public boolean equals(Object object) {
620                         if (!(object instanceof PluginIdentifier)) {
621                                 return false;
622                         }
623                         PluginIdentifier pluginIdentifier = (PluginIdentifier) object;
624                         return pluginName.equals(pluginIdentifier.pluginName) && identifier.equals(pluginIdentifier.identifier);
625                 }
626
627         }
628
629 }