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