Use an atomic reference instead of volatile.
[Sone.git] / src / main / java / net / pterodactylus / sone / fcp / FcpInterface.java
1 /*
2  * Sone - FcpInterface.java - Copyright © 2011–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.fcp;
19
20 import static com.google.common.base.Preconditions.checkNotNull;
21
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.concurrent.atomic.AtomicBoolean;
26 import java.util.concurrent.atomic.AtomicReference;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import net.pterodactylus.sone.core.Core;
31 import net.pterodactylus.sone.core.Options.Option;
32 import net.pterodactylus.sone.core.Options.OptionWatcher;
33 import net.pterodactylus.sone.freenet.fcp.Command.AccessType;
34 import net.pterodactylus.sone.freenet.fcp.Command.ErrorResponse;
35 import net.pterodactylus.sone.freenet.fcp.Command.Response;
36 import net.pterodactylus.util.logging.Logging;
37
38 import freenet.pluginmanager.FredPluginFCP;
39 import freenet.pluginmanager.PluginNotFoundException;
40 import freenet.pluginmanager.PluginReplySender;
41 import freenet.support.SimpleFieldSet;
42 import freenet.support.api.Bucket;
43
44 import com.google.common.annotations.VisibleForTesting;
45 import com.google.inject.Inject;
46 import com.google.inject.Singleton;
47
48 /**
49  * Implementation of an FCP interface for other clients or plugins to
50  * communicate with Sone.
51  *
52  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
53  */
54 @Singleton
55 public class FcpInterface {
56
57         /**
58          * The action level that full access for the FCP connection is required.
59          *
60          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
61          */
62         public enum FullAccessRequired {
63
64                 /** No action requires full access. */
65                 NO,
66
67                 /** All writing actions require full access. */
68                 WRITING,
69
70                 /** All actions require full access. */
71                 ALWAYS,
72
73         }
74
75         /** The logger. */
76         private static final Logger logger = Logging.getLogger(FcpInterface.class);
77
78         /** Whether the FCP interface is currently active. */
79         private final AtomicBoolean active = new AtomicBoolean();
80
81         /** What function full access is required for. */
82         private final AtomicReference<FullAccessRequired> fullAccessRequired = new AtomicReference<FullAccessRequired>(FullAccessRequired.ALWAYS);
83
84         /** All available FCP commands. */
85         private final Map<String, AbstractSoneCommand> commands = Collections.synchronizedMap(new HashMap<String, AbstractSoneCommand>());
86
87         /**
88          * Creates a new FCP interface.
89          *
90          * @param core
91          *            The core
92          */
93         @Inject
94         public FcpInterface(Core core) {
95                 commands.put("Version", new VersionCommand(core));
96                 commands.put("GetLocalSones", new GetLocalSonesCommand(core));
97                 commands.put("GetSones", new GetSonesCommand(core));
98                 commands.put("GetSone", new GetSoneCommand(core));
99                 commands.put("GetPost", new GetPostCommand(core));
100                 commands.put("GetPosts", new GetPostsCommand(core));
101                 commands.put("GetPostFeed", new GetPostFeedCommand(core));
102                 commands.put("LockSone", new LockSoneCommand(core));
103                 commands.put("UnlockSone", new UnlockSoneCommand(core));
104                 commands.put("LikePost", new LikePostCommand(core));
105                 commands.put("LikeReply", new LikeReplyCommand(core));
106                 commands.put("CreatePost", new CreatePostCommand(core));
107                 commands.put("CreateReply", new CreateReplyCommand(core));
108                 commands.put("DeletePost", new DeletePostCommand(core));
109                 commands.put("DeleteReply", new DeleteReplyCommand(core));
110         }
111
112         //
113         // ACCESSORS
114         //
115
116         @VisibleForTesting
117         boolean isActive() {
118                 return active.get();
119         }
120
121         /**
122          * Sets whether the FCP interface should handle requests. If {@code active}
123          * is {@code false}, all requests are answered with an error.
124          *
125          * @param active
126          *            {@code true} to activate the FCP interface, {@code false} to
127          *            deactivate the FCP interface
128          */
129         public void setActive(boolean active) {
130                 this.active.set(active);
131         }
132
133         @VisibleForTesting
134         FullAccessRequired getFullAccessRequired() {
135                 return fullAccessRequired.get();
136         }
137
138         /**
139          * Sets the action level for which full FCP access is required.
140          *
141          * @param fullAccessRequired
142          *            The action level for which full FCP access is required
143          */
144         public void setFullAccessRequired(FullAccessRequired fullAccessRequired) {
145                 this.fullAccessRequired.set(checkNotNull(fullAccessRequired, "fullAccessRequired must not be null"));
146         }
147
148         //
149         // ACTIONS
150         //
151
152         /**
153          * Handles a plugin FCP request.
154          *
155          * @param pluginReplySender
156          *            The reply sender
157          * @param parameters
158          *            The message parameters
159          * @param data
160          *            The message data (may be {@code null})
161          * @param accessType
162          *            One of {@link FredPluginFCP#ACCESS_DIRECT},
163          *            {@link FredPluginFCP#ACCESS_FCP_FULL},
164          *            {@link FredPluginFCP#ACCESS_FCP_RESTRICTED}
165          */
166         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
167                 if (!active.get()) {
168                         try {
169                                 sendReply(pluginReplySender, null, new ErrorResponse(400, "FCP Interface deactivated"));
170                         } catch (PluginNotFoundException pnfe1) {
171                                 logger.log(Level.FINE, "Could not set error to plugin.", pnfe1);
172                         }
173                         return;
174                 }
175                 AbstractSoneCommand command = commands.get(parameters.get("Message"));
176                 if ((accessType == FredPluginFCP.ACCESS_FCP_RESTRICTED) && (((fullAccessRequired.get() == FullAccessRequired.WRITING) && command.requiresWriteAccess()) || (fullAccessRequired.get() == FullAccessRequired.ALWAYS))) {
177                         try {
178                                 sendReply(pluginReplySender, null, new ErrorResponse(401, "Not authorized"));
179                         } catch (PluginNotFoundException pnfe1) {
180                                 logger.log(Level.FINE, "Could not set error to plugin.", pnfe1);
181                         }
182                         return;
183                 }
184                 try {
185                         if (command == null) {
186                                 sendReply(pluginReplySender, null, new ErrorResponse("Unrecognized Message: " + parameters.get("Message")));
187                                 return;
188                         }
189                         String identifier = parameters.get("Identifier");
190                         if ((identifier == null) || (identifier.length() == 0)) {
191                                 sendReply(pluginReplySender, null, new ErrorResponse("Missing Identifier."));
192                                 return;
193                         }
194                         try {
195                                 Response response = command.execute(parameters, data, AccessType.values()[accessType]);
196                                 sendReply(pluginReplySender, identifier, response);
197                         } catch (Exception e1) {
198                                 logger.log(Level.WARNING, "Could not process FCP command “%s”.", command);
199                                 sendReply(pluginReplySender, identifier, new ErrorResponse("Error executing command: " + e1.getMessage()));
200                         }
201                 } catch (PluginNotFoundException pnfe1) {
202                         logger.log(Level.WARNING, "Could not find destination plugin: " + pluginReplySender);
203                 }
204         }
205
206         //
207         // PRIVATE METHODS
208         //
209
210         /**
211          * Sends the given response to the given plugin.
212          *
213          * @param pluginReplySender
214          *            The reply sender
215          * @param identifier
216          *            The identifier (may be {@code null})
217          * @param response
218          *            The response to send
219          * @throws PluginNotFoundException
220          *             if the plugin can not be found
221          */
222         private static void sendReply(PluginReplySender pluginReplySender, String identifier, Response response) throws PluginNotFoundException {
223                 SimpleFieldSet replyParameters = response.getReplyParameters();
224                 if (identifier != null) {
225                         replyParameters.putOverwrite("Identifier", identifier);
226                 }
227                 if (response.hasData()) {
228                         pluginReplySender.send(replyParameters, response.getData());
229                 } else if (response.hasBucket()) {
230                         pluginReplySender.send(replyParameters, response.getBucket());
231                 } else {
232                         pluginReplySender.send(replyParameters);
233                 }
234         }
235
236         public class SetActive implements OptionWatcher<Boolean> {
237
238                 @Override
239                 public void optionChanged(Option<Boolean> option, Boolean oldValue, Boolean newValue) {
240                         setActive(newValue);
241                 }
242
243         }
244
245         public class SetFullAccessRequired implements OptionWatcher<Integer> {
246
247                 @Override
248                 public void optionChanged(Option<Integer> option, Integer oldValue, Integer newValue) {
249                         setFullAccessRequired(FullAccessRequired.values()[newValue]);
250                 }
251
252         }
253
254 }