001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io.remotecontrol.handler;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.net.URI;
007import java.net.URISyntaxException;
008import java.text.MessageFormat;
009import java.util.Collections;
010import java.util.HashMap;
011import java.util.HashSet;
012import java.util.LinkedList;
013import java.util.List;
014import java.util.Map;
015import java.util.Set;
016import java.util.function.Function;
017import java.util.function.Supplier;
018import java.util.regex.Pattern;
019
020import javax.swing.JLabel;
021import javax.swing.JOptionPane;
022
023import org.openstreetmap.josm.actions.downloadtasks.DownloadParams;
024import org.openstreetmap.josm.data.osm.DownloadPolicy;
025import org.openstreetmap.josm.data.osm.UploadPolicy;
026import org.openstreetmap.josm.data.preferences.BooleanProperty;
027import org.openstreetmap.josm.data.preferences.IntegerProperty;
028import org.openstreetmap.josm.gui.MainApplication;
029import org.openstreetmap.josm.gui.util.GuiHelper;
030import org.openstreetmap.josm.io.OsmApiException;
031import org.openstreetmap.josm.io.remotecontrol.PermissionPrefWithDefault;
032import org.openstreetmap.josm.spi.preferences.Config;
033import org.openstreetmap.josm.tools.Logging;
034import org.openstreetmap.josm.tools.Pair;
035import org.openstreetmap.josm.tools.Utils;
036
037/**
038 * This is the parent of all classes that handle a specific remote control command
039 *
040 * @author Bodo Meissner
041 */
042public abstract class RequestHandler {
043
044    /** preference to determine if all Remote Control actions must be confirmed manually */
045    public static final BooleanProperty GLOBAL_CONFIRMATION = new BooleanProperty("remotecontrol.always-confirm", false);
046    /** preference to determine if remote control loads data in a new layer */
047    public static final BooleanProperty LOAD_IN_NEW_LAYER = new BooleanProperty("remotecontrol.new-layer", false);
048    /** preference to define OSM download timeout in seconds */
049    public static final IntegerProperty OSM_DOWNLOAD_TIMEOUT = new IntegerProperty("remotecontrol.osm.download.timeout", 5*60);
050
051    protected static final Pattern SPLITTER_COMMA = Pattern.compile(",\\s*");
052    protected static final Pattern SPLITTER_SEMIC = Pattern.compile(";\\s*");
053
054    /** past confirmations */
055    protected static final PermissionCache PERMISSIONS = new PermissionCache();
056
057    /** The GET request arguments */
058    protected Map<String, String> args;
059
060    /** The request URL without "GET". */
061    protected String request;
062
063    /** default response */
064    protected String content = "OK\r\n";
065    /** default content type */
066    protected String contentType = "text/plain";
067
068    /** will be filled with the command assigned to the subclass */
069    protected String myCommand;
070
071    /**
072     * who sent the request?
073     * the host from referer header or IP of request sender
074     */
075    protected String sender;
076
077    /**
078     * Check permission and parameters and handle request.
079     *
080     * @throws RequestHandlerForbiddenException if request is forbidden by preferences
081     * @throws RequestHandlerBadRequestException if request is invalid
082     * @throws RequestHandlerErrorException if an error occurs while processing request
083     */
084    public final void handle() throws RequestHandlerForbiddenException, RequestHandlerBadRequestException, RequestHandlerErrorException {
085        checkMandatoryParams();
086        validateRequest();
087        checkPermission();
088        handleRequest();
089    }
090
091    /**
092     * Validates the request before attempting to perform it.
093     * @throws RequestHandlerBadRequestException if request is invalid
094     * @since 5678
095     */
096    protected abstract void validateRequest() throws RequestHandlerBadRequestException;
097
098    /**
099     * Handle a specific command sent as remote control.
100     * Any time-consuming operation must be performed asynchronously to avoid delaying the HTTP response.
101     * <p>
102     * This method of the subclass will do the real work.
103     *
104     * @throws RequestHandlerErrorException if an error occurs while processing request
105     * @throws RequestHandlerBadRequestException if request is invalid
106     */
107    protected abstract void handleRequest() throws RequestHandlerErrorException, RequestHandlerBadRequestException;
108
109    /**
110     * Get a specific message to ask the user for permission for the operation
111     * requested via remote control.
112     * <p>
113     * This message will be displayed to the user if the preference
114     * remotecontrol.always-confirm is true.
115     *
116     * @return the message
117     */
118    public abstract String getPermissionMessage();
119
120    /**
121     * Get a PermissionPref object containing the name of a special permission
122     * preference to individually allow the requested operation and an error
123     * message to be displayed when a disabled operation is requested.
124     * <p>
125     * Default is not to check any special preference. Override this in a
126     * subclass to define permission preference and error message.
127     *
128     * @return the preference name and error message or null
129     */
130    public abstract PermissionPrefWithDefault getPermissionPref();
131
132    /**
133     * Returns the mandatory parameters. Both used to enforce their presence at runtime and for documentation.
134     * @return the mandatory parameters
135     */
136    public abstract String[] getMandatoryParams();
137
138    /**
139     * Returns the optional parameters. Both used to enforce their presence at runtime and for documentation.
140     * @return the optional parameters
141     */
142    public String[] getOptionalParams() {
143        return new String[0];
144    }
145
146    /**
147     * Returns usage description, for bad requests and documentation.
148     * @return usage description
149     */
150    public String getUsage() {
151        return null;
152    }
153
154    /**
155     * Returns usage examples, for bad requests and documentation.
156     * @return Usage examples
157     */
158    public String[] getUsageExamples() {
159        return new String[0];
160    }
161
162    /**
163     * Returns usage examples for the given command. To be overridden only my handlers that define several commands.
164     * @param cmd The command asked
165     * @return Usage examples for the given command
166     * @since 6332
167     */
168    public String[] getUsageExamples(String cmd) {
169        return getUsageExamples();
170    }
171
172    /**
173     * Check permissions in preferences and display error message or ask for permission.
174     *
175     * @throws RequestHandlerForbiddenException if request is forbidden by preferences
176     */
177    public final void checkPermission() throws RequestHandlerForbiddenException {
178        /*
179         * If the subclass defines a specific preference and if this is set
180         * to false, abort with an error message.
181         *
182         * Note: we use the deprecated class here for compatibility with
183         * older versions of WMSPlugin.
184         */
185        PermissionPrefWithDefault permissionPref = getPermissionPref();
186        if (permissionPref != null && permissionPref.pref != null &&
187                !Config.getPref().getBoolean(permissionPref.pref, permissionPref.defaultVal)) {
188            String err = MessageFormat.format("RemoteControl: ''{0}'' forbidden by preferences", myCommand);
189            Logging.info(err);
190            throw new RequestHandlerForbiddenException(err);
191        }
192
193        /*
194         * Did the user confirm this action previously?
195         * If yes, skip the global confirmation dialog.
196         */
197        if (PERMISSIONS.isAllowed(myCommand, sender)) {
198            return;
199        }
200
201        /* Does the user want to confirm everything?
202         * If yes, display specific confirmation message.
203         */
204        if (Boolean.TRUE.equals(GLOBAL_CONFIRMATION.get())) {
205            // Ensure dialog box does not exceed main window size
206            final int maxWidth = (int) Math.max(200, MainApplication.getMainFrame().getWidth() * 0.6);
207            final String message = "<html><div>" + getPermissionMessage() +
208                    "<br/>" + tr("Do you want to allow this?") + "</div></html>";
209            final Object[] choices = {tr("Yes, always"), tr("Yes, once"), tr("No")};
210            final int choice;
211            final Integer tChoice = GuiHelper.runInEDTAndWaitAndReturn(() -> {
212                final JLabel label = new JLabel(message);
213                if (label.getPreferredSize().width > maxWidth) {
214                    label.setText(message.replaceFirst("<div>", "<div style=\"width:" + maxWidth + "px;\">"));
215                }
216                return JOptionPane.showOptionDialog(MainApplication.getMainFrame(), label, tr("Confirm Remote Control action"),
217                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, choices, choices[1]);
218            });
219            if (tChoice == null) {
220                // I have no clue how this would ever happen, but just in case.
221                throw new RequestHandlerForbiddenException(MessageFormat.format("RemoteControl: ''{0}'' forbidden due to NPE", myCommand));
222            }
223            choice = tChoice;
224            if (choice != JOptionPane.YES_OPTION && choice != JOptionPane.NO_OPTION) { // Yes/no refer to always/once
225                String err = MessageFormat.format("RemoteControl: ''{0}'' forbidden by user''s choice", myCommand);
226                throw new RequestHandlerForbiddenException(err);
227            } else if (choice == JOptionPane.YES_OPTION) {
228                PERMISSIONS.allow(myCommand, sender);
229            }
230        }
231    }
232
233    /**
234     * Set request URL and parse args.
235     *
236     * @param url The request URL.
237     * @throws RequestHandlerBadRequestException if request URL is invalid
238     */
239    public void setUrl(String url) throws RequestHandlerBadRequestException {
240        this.request = url;
241        try {
242            parseArgs();
243        } catch (URISyntaxException e) {
244            throw new RequestHandlerBadRequestException(e);
245        }
246    }
247
248    /**
249     * Parse the request parameters as key=value pairs.
250     * The result will be stored in {@code this.args}.
251     * <p>
252     * Can be overridden by subclass.
253     * @throws URISyntaxException if request URL is invalid
254     */
255    protected void parseArgs() throws URISyntaxException {
256        this.args = getRequestParameter(new URI(this.request));
257    }
258
259    protected final String[] splitArg(String arg, Pattern splitter) {
260        return splitter.split(args != null ? args.get(arg) : "", -1);
261    }
262
263    /**
264     * Returns the request parameters.
265     * @param uri URI as string
266     * @return map of request parameters
267     * @see <a href="http://blog.lunatech.com/2009/02/03/what-every-web-developer-must-know-about-url-encoding">
268     *      What every web developer must know about URL encoding</a>
269     */
270    static Map<String, String> getRequestParameter(URI uri) {
271        Map<String, String> r = new HashMap<>();
272        if (uri.getRawQuery() == null) {
273            return r;
274        }
275        for (String kv : uri.getRawQuery().split("&", -1)) {
276            final String[] kvs = Utils.decodeUrl(kv).split("=", 2);
277            r.put(kvs[0], kvs.length > 1 ? kvs[1] : null);
278        }
279        return r;
280    }
281
282    void checkMandatoryParams() throws RequestHandlerBadRequestException {
283        String[] mandatory = getMandatoryParams();
284        String[] optional = getOptionalParams();
285        List<String> missingKeys = new LinkedList<>();
286        boolean error = false;
287        if (mandatory != null && args != null) {
288            for (String key : mandatory) {
289                String value = args.get(key);
290                if (Utils.isEmpty(value)) {
291                    error = true;
292                    Logging.warn('\'' + myCommand + "' remote control request must have '" + key + "' parameter");
293                    missingKeys.add(key);
294                }
295            }
296        }
297        Set<String> knownParams = new HashSet<>();
298        if (mandatory != null)
299            Collections.addAll(knownParams, mandatory);
300        if (optional != null)
301            Collections.addAll(knownParams, optional);
302        if (args != null) {
303            for (String par: args.keySet()) {
304                if (!knownParams.contains(par)) {
305                    Logging.warn("Unknown remote control parameter {0}, skipping it", par);
306                }
307            }
308        }
309        if (error) {
310            throw new RequestHandlerBadRequestException(
311                    tr("The following keys are mandatory, but have not been provided: {0}",
312                            String.join(", ", missingKeys)));
313        }
314    }
315
316    /**
317     * Save command associated with this handler.
318     *
319     * @param command The command.
320     */
321    public void setCommand(String command) {
322        if (command.charAt(0) == '/') {
323            command = command.substring(1);
324        }
325        myCommand = command;
326    }
327
328    /**
329     * Returns the command associated with this handler.
330     * @return the command associated with this handler.
331     */
332    public String getCommand() {
333        return myCommand;
334    }
335
336    /**
337     * Returns the response content.
338     * @return the response content
339     */
340    public String getContent() {
341        return content;
342    }
343
344    /**
345     * Returns the response content type.
346     * @return the response content type
347     */
348    public String getContentType() {
349        return contentType;
350    }
351
352    private <T> T get(String key, Function<String, T> parser, Supplier<T> defaultSupplier) {
353        String val = args.get(key);
354        return !Utils.isEmpty(val) ? parser.apply(val) : defaultSupplier.get();
355    }
356
357    private boolean get(String key) {
358        return get(key, Boolean::parseBoolean, () -> Boolean.FALSE);
359    }
360
361    private boolean isLoadInNewLayer() {
362        return get("new_layer", Boolean::parseBoolean, LOAD_IN_NEW_LAYER::get);
363    }
364
365    protected DownloadParams getDownloadParams() {
366        DownloadParams result = new DownloadParams();
367        if (args != null) {
368            result.withNewLayer(isLoadInNewLayer())
369                    .withLayerName(args.get("layer_name"))
370                    .withLocked(get("layer_locked"))
371                    .withDownloadPolicy(get("download_policy", DownloadPolicy::of, () -> DownloadPolicy.NORMAL))
372                    .withUploadPolicy(get("upload_policy", UploadPolicy::of, () -> UploadPolicy.NORMAL));
373        }
374        return result;
375    }
376
377    protected void validateDownloadParams() throws RequestHandlerBadRequestException {
378        try {
379            getDownloadParams();
380        } catch (IllegalArgumentException e) {
381            throw new RequestHandlerBadRequestException(e);
382        }
383    }
384
385    /**
386     * Sets who sent the request (the host from referer header or IP of request sender)
387     * @param sender the host from referer header or IP of request sender
388     */
389    public void setSender(String sender) {
390        this.sender = sender;
391    }
392
393    /**
394     * Base exception of remote control handler errors.
395     */
396    public static class RequestHandlerException extends Exception {
397
398        /**
399         * Constructs a new {@code RequestHandlerException}.
400         * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
401         */
402        public RequestHandlerException(String message) {
403            super(message);
404        }
405
406        /**
407         * Constructs a new {@code RequestHandlerException}.
408         * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
409         * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
410         */
411        public RequestHandlerException(String message, Throwable cause) {
412            super(message, cause);
413        }
414
415        /**
416         * Constructs a new {@code RequestHandlerException}.
417         * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
418         */
419        public RequestHandlerException(Throwable cause) {
420            super(cause);
421        }
422    }
423
424    /**
425     * Error raised when a runtime error occurred.
426     */
427    public static class RequestHandlerErrorException extends RequestHandlerException {
428
429        /**
430         * Constructs a new {@code RequestHandlerErrorException}.
431         * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
432         * @since 17330
433         */
434        public RequestHandlerErrorException(String message) {
435            super(message);
436        }
437
438        /**
439         * Constructs a new {@code RequestHandlerErrorException}.
440         * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
441         */
442        public RequestHandlerErrorException(Throwable cause) {
443            super(cause);
444        }
445    }
446
447    /**
448     * Error raised for OSM API errors.
449     * @since 17330
450     */
451    public static class RequestHandlerOsmApiException extends RequestHandlerErrorException {
452
453        /**
454         * Constructs a new {@code RequestHandlerOsmApiException}.
455         * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
456         */
457        public RequestHandlerOsmApiException(OsmApiException cause) {
458            super(cause);
459        }
460    }
461
462    /**
463     * Error raised for bad requests.
464     */
465    public static class RequestHandlerBadRequestException extends RequestHandlerException {
466
467        /**
468         * Constructs a new {@code RequestHandlerBadRequestException}.
469         * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
470         */
471        public RequestHandlerBadRequestException(String message) {
472            super(message);
473        }
474
475        /**
476         * Constructs a new {@code RequestHandlerBadRequestException}.
477         * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
478         */
479        public RequestHandlerBadRequestException(Throwable cause) {
480            super(cause);
481        }
482
483        /**
484         * Constructs a new {@code RequestHandlerBadRequestException}.
485         * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
486         * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
487         */
488        public RequestHandlerBadRequestException(String message, Throwable cause) {
489            super(message, cause);
490        }
491    }
492
493    /**
494     * Error raised for forbidden usage.
495     */
496    public static class RequestHandlerForbiddenException extends RequestHandlerException {
497
498        /**
499         * Constructs a new {@code RequestHandlerForbiddenException}.
500         * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
501         */
502        public RequestHandlerForbiddenException(String message) {
503            super(message);
504        }
505    }
506
507    /**
508     * Handler that takes a URL as a parameter.
509     */
510    public abstract static class RawURLParseRequestHandler extends RequestHandler {
511        @Override
512        protected void parseArgs() throws URISyntaxException {
513            Map<String, String> args = new HashMap<>();
514            if (request.indexOf('?') != -1) {
515                String query = request.substring(request.indexOf('?') + 1);
516                if (query.indexOf("url=") == 0) {
517                    args.put("url", Utils.decodeUrl(query.substring(4)));
518                } else {
519                    int urlIdx = query.indexOf("&url=");
520                    if (urlIdx != -1) {
521                        args.put("url", Utils.decodeUrl(query.substring(urlIdx + 5)));
522                        query = query.substring(0, urlIdx);
523                    } else if (query.indexOf('#') != -1) {
524                        query = query.substring(0, query.indexOf('#'));
525                    }
526                    String[] params = query.split("&", -1);
527                    for (String param : params) {
528                        int eq = param.indexOf('=');
529                        if (eq != -1) {
530                            args.put(param.substring(0, eq), Utils.decodeUrl(param.substring(eq + 1)));
531                        }
532                    }
533                }
534            }
535            this.args = args;
536        }
537    }
538
539    static class PermissionCache {
540        private final Set<Pair<String, String>> allowed = new HashSet<>();
541
542        public void allow(String command, String sender) {
543            allowed.add(Pair.create(command, sender));
544        }
545
546        public boolean isAllowed(String command, String sender) {
547            return allowed.contains(Pair.create(command, sender));
548        }
549
550        public void clear() {
551            allowed.clear();
552        }
553    }
554}