Deny commands that change data when FCP connection is restricted.
[Sone.git] / src / main / java / net / pterodactylus / sone / fcp / FcpInterface.java
1 /*
2  * Sone - FcpInterface.java - Copyright © 2011 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 java.util.Collections;
21 import java.util.HashMap;
22 import java.util.Map;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25
26 import net.pterodactylus.sone.core.Core;
27 import net.pterodactylus.sone.freenet.fcp.Command.AccessType;
28 import net.pterodactylus.sone.freenet.fcp.Command.ErrorResponse;
29 import net.pterodactylus.sone.freenet.fcp.Command.Response;
30 import net.pterodactylus.sone.freenet.fcp.FcpException;
31 import net.pterodactylus.util.logging.Logging;
32 import freenet.pluginmanager.FredPluginFCP;
33 import freenet.pluginmanager.PluginNotFoundException;
34 import freenet.pluginmanager.PluginReplySender;
35 import freenet.support.SimpleFieldSet;
36 import freenet.support.api.Bucket;
37
38 /**
39  * Implementation of an FCP interface for other clients or plugins to
40  * communicate with Sone.
41  *
42  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
43  */
44 public class FcpInterface {
45
46         /** The logger. */
47         private static final Logger logger = Logging.getLogger(FcpInterface.class);
48
49         /** Whether the FCP interface is currently active. */
50         private volatile boolean active;
51
52         /** Whether to allow write access from full access hosts only. */
53         private volatile boolean allowWriteFromFullAccessOnly;
54
55         /** All available FCP commands. */
56         private final Map<String, AbstractSoneCommand> commands = Collections.synchronizedMap(new HashMap<String, AbstractSoneCommand>());
57
58         /**
59          * Creates a new FCP interface.
60          *
61          * @param core
62          *            The core
63          */
64         public FcpInterface(Core core) {
65                 commands.put("Version", new VersionCommand(core));
66                 commands.put("GetLocalSones", new GetLocalSonesCommand(core));
67                 commands.put("GetPost", new GetPostCommand(core));
68                 commands.put("GetPosts", new GetPostsCommand(core));
69                 commands.put("GetPostFeed", new GetPostFeedCommand(core));
70                 commands.put("LikePost", new LikePostCommand(core));
71                 commands.put("LikeReply", new LikeReplyCommand(core));
72                 commands.put("CreatePost", new CreatePostCommand(core));
73                 commands.put("CreateReply", new CreateReplyCommand(core));
74                 commands.put("DeletePost", new DeletePostCommand(core));
75                 commands.put("DeleteReply", new DeleteReplyCommand(core));
76         }
77
78         //
79         // ACCESSORS
80         //
81
82         /**
83          * Sets whether the FCP interface should handle requests. If {@code active}
84          * is {@code false}, all requests are answered with an error.
85          *
86          * @param active
87          *            {@code true} to activate the FCP interface, {@code false} to
88          *            deactivate the FCP interface
89          */
90         public void setActive(boolean active) {
91                 this.active = active;
92         }
93
94         /**
95          * Sets whether write access is only allowed from full access hosts.
96          *
97          * @param allowWriteFromFullAccessOnly
98          *            {@code true} to allow write access only from full access
99          *            hosts, {@code false} to always allow write access
100          */
101         public void setAllowWriteFromFullAccessOnly(boolean allowWriteFromFullAccessOnly) {
102                 this.allowWriteFromFullAccessOnly = allowWriteFromFullAccessOnly;
103         }
104
105         //
106         // ACTIONS
107         //
108
109         /**
110          * Handles a plugin FCP request.
111          *
112          * @param pluginReplySender
113          *            The reply sender
114          * @param parameters
115          *            The message parameters
116          * @param data
117          *            The message data (may be {@code null})
118          * @param accessType
119          *            One of {@link FredPluginFCP#ACCESS_DIRECT},
120          *            {@link FredPluginFCP#ACCESS_FCP_FULL},
121          *            {@link FredPluginFCP#ACCESS_FCP_RESTRICTED}
122          */
123         public void handle(PluginReplySender pluginReplySender, SimpleFieldSet parameters, Bucket data, int accessType) {
124                 if (!active) {
125                         try {
126                                 sendReply(pluginReplySender, null, new ErrorResponse(400, "FCP Interface deactivated"));
127                         } catch (PluginNotFoundException pnfe1) {
128                                 logger.log(Level.FINE, "Could not set error to plugin.", pnfe1);
129                         }
130                         return;
131                 }
132                 AbstractSoneCommand command = commands.get(parameters.get("Message"));
133                 if (allowWriteFromFullAccessOnly && command.requiresWriteAccess() && (accessType == FredPluginFCP.ACCESS_FCP_RESTRICTED)) {
134                         try {
135                                 sendReply(pluginReplySender, null, new ErrorResponse(401, "No Write Access"));
136                         } catch (PluginNotFoundException pnfe1) {
137                                 logger.log(Level.FINE, "Could not set error to plugin.", pnfe1);
138                         }
139                         return;
140                 }
141                 try {
142                         if (command == null) {
143                                 sendReply(pluginReplySender, null, new ErrorResponse("Unrecognized Message: " + parameters.get("Message")));
144                                 return;
145                         }
146                         String identifier = parameters.get("Identifier");
147                         if ((identifier == null) || (identifier.length() == 0)) {
148                                 sendReply(pluginReplySender, null, new ErrorResponse("Missing Identifier."));
149                                 return;
150                         }
151                         try {
152                                 Response response = command.execute(parameters, data, AccessType.values()[accessType]);
153                                 sendReply(pluginReplySender, identifier, response);
154                         } catch (FcpException fe1) {
155                                 sendReply(pluginReplySender, identifier, new ErrorResponse("Error executing command: " + fe1.getMessage()));
156                         }
157                 } catch (PluginNotFoundException pnfe1) {
158                         logger.log(Level.WARNING, "Could not find destination plugin: " + pluginReplySender);
159                 }
160         }
161
162         //
163         // PRIVATE METHODS
164         //
165
166         /**
167          * Sends the given response to the given plugin.
168          *
169          * @param pluginReplySender
170          *            The reply sender
171          * @param identifier
172          *            The identifier (may be {@code null})
173          * @param response
174          *            The response to send
175          * @throws PluginNotFoundException
176          *             if the plugin can not be found
177          */
178         private void sendReply(PluginReplySender pluginReplySender, String identifier, Response response) throws PluginNotFoundException {
179                 SimpleFieldSet replyParameters = response.getReplyParameters();
180                 if (identifier != null) {
181                         replyParameters.putOverwrite("Identifier", identifier);
182                 }
183                 if (response.hasData()) {
184                         pluginReplySender.send(replyParameters, response.getData());
185                 } else if (response.hasBucket()) {
186                         pluginReplySender.send(replyParameters, response.getBucket());
187                 } else {
188                         pluginReplySender.send(replyParameters);
189                 }
190         }
191
192 }