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