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.transform.exec.internal;
15 import java.io.IOException;
16 import java.nio.file.Files;
17 import java.nio.file.Path;
18 import java.util.HashSet;
20 import java.util.stream.Stream;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.openhab.core.service.WatchService;
24 import org.osgi.service.component.annotations.Activate;
25 import org.osgi.service.component.annotations.Component;
26 import org.osgi.service.component.annotations.Deactivate;
27 import org.osgi.service.component.annotations.Reference;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
32 * The {@link ExecTransformationWhitelistWatchService} provides a whitelist check for exec commands
34 * @author Jan N. Klug - Initial contribution
36 @Component(service = ExecTransformationWhitelistWatchService.class)
38 public class ExecTransformationWhitelistWatchService implements WatchService.WatchEventListener {
39 private static final Path COMMAND_WHITELIST_FILE = Path.of("misc", "exec.whitelist");
41 private final Logger logger = LoggerFactory.getLogger(ExecTransformationWhitelistWatchService.class);
42 private final Set<String> commandWhitelist = new HashSet<>();
43 private final WatchService watchService;
46 public ExecTransformationWhitelistWatchService(
47 final @Reference(target = WatchService.CONFIG_WATCHER_FILTER) WatchService watchService) {
48 this.watchService = watchService;
49 watchService.registerListener(this, COMMAND_WHITELIST_FILE);
51 // read initial content
52 processWatchEvent(WatchService.Kind.CREATE, COMMAND_WHITELIST_FILE);
56 public void deactivate() {
57 watchService.unregisterListener(this);
61 public void processWatchEvent(WatchService.Kind kind, Path path) {
62 if (path.endsWith(COMMAND_WHITELIST_FILE)) {
63 commandWhitelist.clear();
64 try (Stream<String> lines = Files.lines(path)) {
65 lines.filter(line -> !line.trim().startsWith("#")).forEach(commandWhitelist::add);
66 logger.debug("Updated command whitelist: {}", commandWhitelist);
67 } catch (IOException e) {
68 logger.warn("Cannot read whitelist file, exec transformations won't be processed: {}", e.getMessage());
74 * Check if a command is whitelisted
76 * @param command the command to check alias
77 * @return true if whitelisted, false if not
79 public boolean isWhitelisted(String command) {
80 return commandWhitelist.contains(command);