2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.exec.internal;
15 import static java.nio.file.StandardWatchEventKinds.*;
18 import java.io.IOException;
19 import java.nio.file.Files;
20 import java.nio.file.Path;
21 import java.nio.file.Paths;
22 import java.nio.file.WatchEvent;
23 import java.nio.file.WatchEvent.Kind;
24 import java.util.HashSet;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.core.OpenHAB;
30 import org.openhab.core.service.AbstractWatchService;
31 import org.osgi.service.component.annotations.Activate;
32 import org.osgi.service.component.annotations.Component;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
37 * The {@link ExecWhitelistWatchService} provides a whitelist check for exec commands
39 * @author Jan N. Klug - Initial contribution
41 @Component(service = ExecWhitelistWatchService.class)
43 public class ExecWhitelistWatchService extends AbstractWatchService {
44 private static final String COMMAND_WHITELIST_PATH = OpenHAB.getConfigFolder() + File.separator + "misc";
45 private static final String COMMAND_WHITELIST_FILE = "exec.whitelist";
47 private final Logger logger = LoggerFactory.getLogger(ExecWhitelistWatchService.class);
48 private final Set<String> commandWhitelist = new HashSet<>();
51 public ExecWhitelistWatchService() {
52 super(COMMAND_WHITELIST_PATH);
53 processWatchEvent(null, null, Paths.get(COMMAND_WHITELIST_PATH, COMMAND_WHITELIST_FILE));
57 protected boolean watchSubDirectories() {
62 protected Kind<?> @Nullable [] getWatchEventKinds(@Nullable Path directory) {
63 return new Kind<?>[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY };
67 protected void processWatchEvent(@Nullable WatchEvent<?> event, @Nullable Kind<?> kind, @Nullable Path path) {
68 if (path != null && path.endsWith(COMMAND_WHITELIST_FILE)) {
69 commandWhitelist.clear();
71 Files.lines(path).filter(line -> !line.trim().startsWith("#")).forEach(commandWhitelist::add);
72 logger.debug("Updated command whitelist: {}", commandWhitelist);
73 } catch (IOException e) {
74 logger.warn("Cannot read whitelist file, exec binding commands won't be processed: {}", e.getMessage());
80 * Check if a command is whitelisted
82 * @param command the command to check alias
83 * @return true if whitelisted, false if not
85 public boolean isWhitelisted(String command) {
86 return commandWhitelist.contains(command);