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