1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.io.remotecontrol.handler;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.net.URI;
|
---|
7 | import java.net.URISyntaxException;
|
---|
8 | import java.text.MessageFormat;
|
---|
9 | import java.util.Collections;
|
---|
10 | import java.util.HashMap;
|
---|
11 | import java.util.HashSet;
|
---|
12 | import java.util.LinkedList;
|
---|
13 | import java.util.List;
|
---|
14 | import java.util.Map;
|
---|
15 | import java.util.Set;
|
---|
16 | import java.util.function.Function;
|
---|
17 | import java.util.function.Supplier;
|
---|
18 | import java.util.regex.Pattern;
|
---|
19 |
|
---|
20 | import javax.swing.JLabel;
|
---|
21 | import javax.swing.JOptionPane;
|
---|
22 |
|
---|
23 | import org.openstreetmap.josm.Main;
|
---|
24 | import org.openstreetmap.josm.actions.downloadtasks.DownloadParams;
|
---|
25 | import org.openstreetmap.josm.data.osm.DownloadPolicy;
|
---|
26 | import org.openstreetmap.josm.data.osm.UploadPolicy;
|
---|
27 | import org.openstreetmap.josm.io.remotecontrol.PermissionPrefWithDefault;
|
---|
28 | import org.openstreetmap.josm.spi.preferences.Config;
|
---|
29 | import org.openstreetmap.josm.tools.Logging;
|
---|
30 | import org.openstreetmap.josm.tools.Pair;
|
---|
31 | import org.openstreetmap.josm.tools.Utils;
|
---|
32 |
|
---|
33 | /**
|
---|
34 | * This is the parent of all classes that handle a specific remote control command
|
---|
35 | *
|
---|
36 | * @author Bodo Meissner
|
---|
37 | */
|
---|
38 | public abstract class RequestHandler {
|
---|
39 |
|
---|
40 | public static final String globalConfirmationKey = "remotecontrol.always-confirm";
|
---|
41 | public static final boolean globalConfirmationDefault = false;
|
---|
42 | public static final String loadInNewLayerKey = "remotecontrol.new-layer";
|
---|
43 | public static final boolean loadInNewLayerDefault = false;
|
---|
44 |
|
---|
45 | protected static final Pattern SPLITTER_COMMA = Pattern.compile(",\\s*");
|
---|
46 | protected static final Pattern SPLITTER_SEMIC = Pattern.compile(";\\s*");
|
---|
47 |
|
---|
48 | /** past confirmations */
|
---|
49 | protected static final PermissionCache PERMISSIONS = new PermissionCache();
|
---|
50 |
|
---|
51 | /** The GET request arguments */
|
---|
52 | protected Map<String, String> args;
|
---|
53 |
|
---|
54 | /** The request URL without "GET". */
|
---|
55 | protected String request;
|
---|
56 |
|
---|
57 | /** default response */
|
---|
58 | protected String content = "OK\r\n";
|
---|
59 | /** default content type */
|
---|
60 | protected String contentType = "text/plain";
|
---|
61 |
|
---|
62 | /** will be filled with the command assigned to the subclass */
|
---|
63 | protected String myCommand;
|
---|
64 |
|
---|
65 | /**
|
---|
66 | * who sent the request?
|
---|
67 | * the host from referer header or IP of request sender
|
---|
68 | */
|
---|
69 | protected String sender;
|
---|
70 |
|
---|
71 | /**
|
---|
72 | * Check permission and parameters and handle request.
|
---|
73 | *
|
---|
74 | * @throws RequestHandlerForbiddenException if request is forbidden by preferences
|
---|
75 | * @throws RequestHandlerBadRequestException if request is invalid
|
---|
76 | * @throws RequestHandlerErrorException if an error occurs while processing request
|
---|
77 | */
|
---|
78 | public final void handle() throws RequestHandlerForbiddenException, RequestHandlerBadRequestException, RequestHandlerErrorException {
|
---|
79 | checkMandatoryParams();
|
---|
80 | validateRequest();
|
---|
81 | checkPermission();
|
---|
82 | handleRequest();
|
---|
83 | }
|
---|
84 |
|
---|
85 | /**
|
---|
86 | * Validates the request before attempting to perform it.
|
---|
87 | * @throws RequestHandlerBadRequestException if request is invalid
|
---|
88 | * @since 5678
|
---|
89 | */
|
---|
90 | protected abstract void validateRequest() throws RequestHandlerBadRequestException;
|
---|
91 |
|
---|
92 | /**
|
---|
93 | * Handle a specific command sent as remote control.
|
---|
94 | *
|
---|
95 | * This method of the subclass will do the real work.
|
---|
96 | *
|
---|
97 | * @throws RequestHandlerErrorException if an error occurs while processing request
|
---|
98 | * @throws RequestHandlerBadRequestException if request is invalid
|
---|
99 | */
|
---|
100 | protected abstract void handleRequest() throws RequestHandlerErrorException, RequestHandlerBadRequestException;
|
---|
101 |
|
---|
102 | /**
|
---|
103 | * Get a specific message to ask the user for permission for the operation
|
---|
104 | * requested via remote control.
|
---|
105 | *
|
---|
106 | * This message will be displayed to the user if the preference
|
---|
107 | * remotecontrol.always-confirm is true.
|
---|
108 | *
|
---|
109 | * @return the message
|
---|
110 | */
|
---|
111 | public abstract String getPermissionMessage();
|
---|
112 |
|
---|
113 | /**
|
---|
114 | * Get a PermissionPref object containing the name of a special permission
|
---|
115 | * preference to individually allow the requested operation and an error
|
---|
116 | * message to be displayed when a disabled operation is requested.
|
---|
117 | *
|
---|
118 | * Default is not to check any special preference. Override this in a
|
---|
119 | * subclass to define permission preference and error message.
|
---|
120 | *
|
---|
121 | * @return the preference name and error message or null
|
---|
122 | */
|
---|
123 | public abstract PermissionPrefWithDefault getPermissionPref();
|
---|
124 |
|
---|
125 | public abstract String[] getMandatoryParams();
|
---|
126 |
|
---|
127 | public String[] getOptionalParams() {
|
---|
128 | return new String[0];
|
---|
129 | }
|
---|
130 |
|
---|
131 | public String getUsage() {
|
---|
132 | return null;
|
---|
133 | }
|
---|
134 |
|
---|
135 | public String[] getUsageExamples() {
|
---|
136 | return new String[0];
|
---|
137 | }
|
---|
138 |
|
---|
139 | /**
|
---|
140 | * Returns usage examples for the given command. To be overriden only my handlers that define several commands.
|
---|
141 | * @param cmd The command asked
|
---|
142 | * @return Usage examples for the given command
|
---|
143 | * @since 6332
|
---|
144 | */
|
---|
145 | public String[] getUsageExamples(String cmd) {
|
---|
146 | return getUsageExamples();
|
---|
147 | }
|
---|
148 |
|
---|
149 | /**
|
---|
150 | * Check permissions in preferences and display error message or ask for permission.
|
---|
151 | *
|
---|
152 | * @throws RequestHandlerForbiddenException if request is forbidden by preferences
|
---|
153 | */
|
---|
154 | public final void checkPermission() throws RequestHandlerForbiddenException {
|
---|
155 | /*
|
---|
156 | * If the subclass defines a specific preference and if this is set
|
---|
157 | * to false, abort with an error message.
|
---|
158 | *
|
---|
159 | * Note: we use the deprecated class here for compatibility with
|
---|
160 | * older versions of WMSPlugin.
|
---|
161 | */
|
---|
162 | PermissionPrefWithDefault permissionPref = getPermissionPref();
|
---|
163 | if (permissionPref != null && permissionPref.pref != null &&
|
---|
164 | !Config.getPref().getBoolean(permissionPref.pref, permissionPref.defaultVal)) {
|
---|
165 | String err = MessageFormat.format("RemoteControl: ''{0}'' forbidden by preferences", myCommand);
|
---|
166 | Logging.info(err);
|
---|
167 | throw new RequestHandlerForbiddenException(err);
|
---|
168 | }
|
---|
169 |
|
---|
170 | /*
|
---|
171 | * Did the user confirm this action previously?
|
---|
172 | * If yes, skip the global confirmation dialog.
|
---|
173 | */
|
---|
174 | if (PERMISSIONS.isAllowed(myCommand, sender)) {
|
---|
175 | return;
|
---|
176 | }
|
---|
177 |
|
---|
178 | /* Does the user want to confirm everything?
|
---|
179 | * If yes, display specific confirmation message.
|
---|
180 | */
|
---|
181 | if (Config.getPref().getBoolean(globalConfirmationKey, globalConfirmationDefault)) {
|
---|
182 | // Ensure dialog box does not exceed main window size
|
---|
183 | Integer maxWidth = (int) Math.max(200, Main.parent.getWidth()*0.6);
|
---|
184 | String message = "<html><div>" + getPermissionMessage() +
|
---|
185 | "<br/>" + tr("Do you want to allow this?") + "</div></html>";
|
---|
186 | JLabel label = new JLabel(message);
|
---|
187 | if (label.getPreferredSize().width > maxWidth) {
|
---|
188 | label.setText(message.replaceFirst("<div>", "<div style=\"width:" + maxWidth + "px;\">"));
|
---|
189 | }
|
---|
190 | Object[] choices = new Object[] {tr("Yes, always"), tr("Yes, once"), tr("No")};
|
---|
191 | int choice = JOptionPane.showOptionDialog(Main.parent, label, tr("Confirm Remote Control action"),
|
---|
192 | JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, choices, choices[1]);
|
---|
193 | if (choice != JOptionPane.YES_OPTION && choice != JOptionPane.NO_OPTION) { // Yes/no refer to always/once
|
---|
194 | String err = MessageFormat.format("RemoteControl: ''{0}'' forbidden by user''s choice", myCommand);
|
---|
195 | throw new RequestHandlerForbiddenException(err);
|
---|
196 | } else if (choice == JOptionPane.YES_OPTION) {
|
---|
197 | PERMISSIONS.allow(myCommand, sender);
|
---|
198 | }
|
---|
199 | }
|
---|
200 | }
|
---|
201 |
|
---|
202 | /**
|
---|
203 | * Set request URL and parse args.
|
---|
204 | *
|
---|
205 | * @param url The request URL.
|
---|
206 | * @throws RequestHandlerBadRequestException if request URL is invalid
|
---|
207 | */
|
---|
208 | public void setUrl(String url) throws RequestHandlerBadRequestException {
|
---|
209 | this.request = url;
|
---|
210 | try {
|
---|
211 | parseArgs();
|
---|
212 | } catch (URISyntaxException e) {
|
---|
213 | throw new RequestHandlerBadRequestException(e);
|
---|
214 | }
|
---|
215 | }
|
---|
216 |
|
---|
217 | /**
|
---|
218 | * Parse the request parameters as key=value pairs.
|
---|
219 | * The result will be stored in {@code this.args}.
|
---|
220 | *
|
---|
221 | * Can be overridden by subclass.
|
---|
222 | * @throws URISyntaxException if request URL is invalid
|
---|
223 | */
|
---|
224 | protected void parseArgs() throws URISyntaxException {
|
---|
225 | this.args = getRequestParameter(new URI(this.request));
|
---|
226 | }
|
---|
227 |
|
---|
228 | protected final String[] splitArg(String arg, Pattern splitter) {
|
---|
229 | return splitter.split(args != null ? args.get(arg) : "");
|
---|
230 | }
|
---|
231 |
|
---|
232 | /**
|
---|
233 | * Returns the request parameters.
|
---|
234 | * @param uri URI as string
|
---|
235 | * @return map of request parameters
|
---|
236 | * @see <a href="http://blog.lunatech.com/2009/02/03/what-every-web-developer-must-know-about-url-encoding">
|
---|
237 | * What every web developer must know about URL encoding</a>
|
---|
238 | */
|
---|
239 | static Map<String, String> getRequestParameter(URI uri) {
|
---|
240 | Map<String, String> r = new HashMap<>();
|
---|
241 | if (uri.getRawQuery() == null) {
|
---|
242 | return r;
|
---|
243 | }
|
---|
244 | for (String kv : uri.getRawQuery().split("&")) {
|
---|
245 | final String[] kvs = Utils.decodeUrl(kv).split("=", 2);
|
---|
246 | r.put(kvs[0], kvs.length > 1 ? kvs[1] : null);
|
---|
247 | }
|
---|
248 | return r;
|
---|
249 | }
|
---|
250 |
|
---|
251 | void checkMandatoryParams() throws RequestHandlerBadRequestException {
|
---|
252 | String[] mandatory = getMandatoryParams();
|
---|
253 | String[] optional = getOptionalParams();
|
---|
254 | List<String> missingKeys = new LinkedList<>();
|
---|
255 | boolean error = false;
|
---|
256 | if (mandatory != null && args != null) {
|
---|
257 | for (String key : mandatory) {
|
---|
258 | String value = args.get(key);
|
---|
259 | if (value == null || value.isEmpty()) {
|
---|
260 | error = true;
|
---|
261 | Logging.warn('\'' + myCommand + "' remote control request must have '" + key + "' parameter");
|
---|
262 | missingKeys.add(key);
|
---|
263 | }
|
---|
264 | }
|
---|
265 | }
|
---|
266 | Set<String> knownParams = new HashSet<>();
|
---|
267 | if (mandatory != null)
|
---|
268 | Collections.addAll(knownParams, mandatory);
|
---|
269 | if (optional != null)
|
---|
270 | Collections.addAll(knownParams, optional);
|
---|
271 | if (args != null) {
|
---|
272 | for (String par: args.keySet()) {
|
---|
273 | if (!knownParams.contains(par)) {
|
---|
274 | Logging.warn("Unknown remote control parameter {0}, skipping it", par);
|
---|
275 | }
|
---|
276 | }
|
---|
277 | }
|
---|
278 | if (error) {
|
---|
279 | throw new RequestHandlerBadRequestException(
|
---|
280 | tr("The following keys are mandatory, but have not been provided: {0}",
|
---|
281 | Utils.join(", ", missingKeys)));
|
---|
282 | }
|
---|
283 | }
|
---|
284 |
|
---|
285 | /**
|
---|
286 | * Save command associated with this handler.
|
---|
287 | *
|
---|
288 | * @param command The command.
|
---|
289 | */
|
---|
290 | public void setCommand(String command) {
|
---|
291 | if (command.charAt(0) == '/') {
|
---|
292 | command = command.substring(1);
|
---|
293 | }
|
---|
294 | myCommand = command;
|
---|
295 | }
|
---|
296 |
|
---|
297 | public String getContent() {
|
---|
298 | return content;
|
---|
299 | }
|
---|
300 |
|
---|
301 | public String getContentType() {
|
---|
302 | return contentType;
|
---|
303 | }
|
---|
304 |
|
---|
305 | private <T> T get(String key, Function<String, T> parser, Supplier<T> defaultSupplier) {
|
---|
306 | String val = args.get(key);
|
---|
307 | return val != null && !val.isEmpty() ? parser.apply(val) : defaultSupplier.get();
|
---|
308 | }
|
---|
309 |
|
---|
310 | private boolean isLoadInNewLayer() {
|
---|
311 | return get("new_layer", Boolean::parseBoolean, () -> Config.getPref().getBoolean(loadInNewLayerKey, loadInNewLayerDefault));
|
---|
312 | }
|
---|
313 |
|
---|
314 | private boolean is(String key) {
|
---|
315 | return get(key, Boolean::parseBoolean, () -> false);
|
---|
316 | }
|
---|
317 |
|
---|
318 | protected DownloadParams getDownloadParams() {
|
---|
319 | return new DownloadParams()
|
---|
320 | .withNewLayer(isLoadInNewLayer())
|
---|
321 | .withLayerName(args.get("layer_name"))
|
---|
322 | .withLocked(is("layer_locked"))
|
---|
323 | .withDownloadPolicy(get("download_policy", DownloadPolicy::of, () -> DownloadPolicy.NORMAL))
|
---|
324 | .withUploadPolicy(get("upload_policy", UploadPolicy::of, () -> UploadPolicy.NORMAL));
|
---|
325 | }
|
---|
326 |
|
---|
327 | protected void validateDownloadParams() throws RequestHandlerBadRequestException {
|
---|
328 | try {
|
---|
329 | getDownloadParams();
|
---|
330 | } catch (IllegalArgumentException e) {
|
---|
331 | throw new RequestHandlerBadRequestException(e);
|
---|
332 | }
|
---|
333 | }
|
---|
334 |
|
---|
335 | public void setSender(String sender) {
|
---|
336 | this.sender = sender;
|
---|
337 | }
|
---|
338 |
|
---|
339 | public static class RequestHandlerException extends Exception {
|
---|
340 |
|
---|
341 | /**
|
---|
342 | * Constructs a new {@code RequestHandlerException}.
|
---|
343 | * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
|
---|
344 | */
|
---|
345 | public RequestHandlerException(String message) {
|
---|
346 | super(message);
|
---|
347 | }
|
---|
348 |
|
---|
349 | /**
|
---|
350 | * Constructs a new {@code RequestHandlerException}.
|
---|
351 | * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
|
---|
352 | * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
|
---|
353 | */
|
---|
354 | public RequestHandlerException(String message, Throwable cause) {
|
---|
355 | super(message, cause);
|
---|
356 | }
|
---|
357 |
|
---|
358 | /**
|
---|
359 | * Constructs a new {@code RequestHandlerException}.
|
---|
360 | * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
|
---|
361 | */
|
---|
362 | public RequestHandlerException(Throwable cause) {
|
---|
363 | super(cause);
|
---|
364 | }
|
---|
365 | }
|
---|
366 |
|
---|
367 | public static class RequestHandlerErrorException extends RequestHandlerException {
|
---|
368 |
|
---|
369 | /**
|
---|
370 | * Constructs a new {@code RequestHandlerErrorException}.
|
---|
371 | * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
|
---|
372 | */
|
---|
373 | public RequestHandlerErrorException(Throwable cause) {
|
---|
374 | super(cause);
|
---|
375 | }
|
---|
376 | }
|
---|
377 |
|
---|
378 | public static class RequestHandlerBadRequestException extends RequestHandlerException {
|
---|
379 |
|
---|
380 | /**
|
---|
381 | * Constructs a new {@code RequestHandlerBadRequestException}.
|
---|
382 | * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
|
---|
383 | */
|
---|
384 | public RequestHandlerBadRequestException(String message) {
|
---|
385 | super(message);
|
---|
386 | }
|
---|
387 |
|
---|
388 | /**
|
---|
389 | * Constructs a new {@code RequestHandlerBadRequestException}.
|
---|
390 | * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
|
---|
391 | */
|
---|
392 | public RequestHandlerBadRequestException(Throwable cause) {
|
---|
393 | super(cause);
|
---|
394 | }
|
---|
395 |
|
---|
396 | /**
|
---|
397 | * Constructs a new {@code RequestHandlerBadRequestException}.
|
---|
398 | * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
|
---|
399 | * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
|
---|
400 | */
|
---|
401 | public RequestHandlerBadRequestException(String message, Throwable cause) {
|
---|
402 | super(message, cause);
|
---|
403 | }
|
---|
404 | }
|
---|
405 |
|
---|
406 | public static class RequestHandlerForbiddenException extends RequestHandlerException {
|
---|
407 |
|
---|
408 | /**
|
---|
409 | * Constructs a new {@code RequestHandlerForbiddenException}.
|
---|
410 | * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
|
---|
411 | */
|
---|
412 | public RequestHandlerForbiddenException(String message) {
|
---|
413 | super(message);
|
---|
414 | }
|
---|
415 | }
|
---|
416 |
|
---|
417 | public abstract static class RawURLParseRequestHandler extends RequestHandler {
|
---|
418 | @Override
|
---|
419 | protected void parseArgs() throws URISyntaxException {
|
---|
420 | Map<String, String> args = new HashMap<>();
|
---|
421 | if (request.indexOf('?') != -1) {
|
---|
422 | String query = request.substring(request.indexOf('?') + 1);
|
---|
423 | if (query.indexOf("url=") == 0) {
|
---|
424 | args.put("url", Utils.decodeUrl(query.substring(4)));
|
---|
425 | } else {
|
---|
426 | int urlIdx = query.indexOf("&url=");
|
---|
427 | if (urlIdx != -1) {
|
---|
428 | args.put("url", Utils.decodeUrl(query.substring(urlIdx + 5)));
|
---|
429 | query = query.substring(0, urlIdx);
|
---|
430 | } else if (query.indexOf('#') != -1) {
|
---|
431 | query = query.substring(0, query.indexOf('#'));
|
---|
432 | }
|
---|
433 | String[] params = query.split("&", -1);
|
---|
434 | for (String param : params) {
|
---|
435 | int eq = param.indexOf('=');
|
---|
436 | if (eq != -1) {
|
---|
437 | args.put(param.substring(0, eq), Utils.decodeUrl(param.substring(eq + 1)));
|
---|
438 | }
|
---|
439 | }
|
---|
440 | }
|
---|
441 | }
|
---|
442 | this.args = args;
|
---|
443 | }
|
---|
444 | }
|
---|
445 |
|
---|
446 | static class PermissionCache {
|
---|
447 | private final Set<Pair<String, String>> allowed = new HashSet<>();
|
---|
448 |
|
---|
449 | public void allow(String command, String sender) {
|
---|
450 | allowed.add(Pair.create(command, sender));
|
---|
451 | }
|
---|
452 |
|
---|
453 | public boolean isAllowed(String command, String sender) {
|
---|
454 | return allowed.contains(Pair.create(command, sender));
|
---|
455 | }
|
---|
456 |
|
---|
457 | public void clear() {
|
---|
458 | allowed.clear();
|
---|
459 | }
|
---|
460 | }
|
---|
461 | }
|
---|