2 * Copyright (c) 2010-2021 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.handler;
15 import static org.openhab.binding.exec.internal.ExecBindingConstants.*;
17 import java.io.BufferedReader;
18 import java.io.IOException;
19 import java.io.InputStreamReader;
20 import java.math.BigDecimal;
21 import java.time.ZonedDateTime;
22 import java.util.Arrays;
23 import java.util.Calendar;
24 import java.util.Date;
25 import java.util.IllegalFormatException;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30 import java.util.regex.PatternSyntaxException;
32 import org.apache.commons.lang.StringUtils;
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.openhab.binding.exec.internal.ExecWhitelistWatchService;
36 import org.openhab.core.library.types.DateTimeType;
37 import org.openhab.core.library.types.DecimalType;
38 import org.openhab.core.library.types.OnOffType;
39 import org.openhab.core.library.types.StringType;
40 import org.openhab.core.thing.ChannelUID;
41 import org.openhab.core.thing.Thing;
42 import org.openhab.core.thing.ThingStatus;
43 import org.openhab.core.thing.binding.BaseThingHandler;
44 import org.openhab.core.transform.TransformationException;
45 import org.openhab.core.transform.TransformationHelper;
46 import org.openhab.core.transform.TransformationService;
47 import org.openhab.core.types.Command;
48 import org.openhab.core.types.RefreshType;
49 import org.osgi.framework.BundleContext;
50 import org.osgi.framework.FrameworkUtil;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * The {@link ExecHandler} is responsible for handling commands, which are
56 * sent to one of the channels.
58 * @author Karel Goderis - Initial contribution
59 * @author Constantin Piber - Added better argument support (delimiter and pass to shell)
60 * @author Jan N. Klug - Add command whitelist check
63 public class ExecHandler extends BaseThingHandler {
65 * Use this to separate between command and parameter, and also between parameters.
67 public static final String CMD_LINE_DELIMITER = "@@";
72 public static final String[] SHELL_WINDOWS = new String[] { "cmd" };
73 public static final String[] SHELL_NIX = new String[] { "sh", "bash", "zsh", "csh" };
74 private final ExecWhitelistWatchService execWhitelistWatchService;
76 private Logger logger = LoggerFactory.getLogger(ExecHandler.class);
78 private final BundleContext bundleContext;
80 // List of Configurations constants
81 public static final String INTERVAL = "interval";
82 public static final String TIME_OUT = "timeout";
83 public static final String COMMAND = "command";
84 public static final String TRANSFORM = "transform";
85 public static final String AUTORUN = "autorun";
87 // RegEx to extract a parse a function String <code>'(.*?)\((.*)\)'</code>
88 private static final Pattern EXTRACT_FUNCTION_PATTERN = Pattern.compile("(.*?)\\((.*)\\)");
90 private @Nullable ScheduledFuture<?> executionJob;
91 private @Nullable String lastInput;
93 private static Runtime rt = Runtime.getRuntime();
95 public ExecHandler(Thing thing, ExecWhitelistWatchService execWhitelistWatchService) {
97 this.bundleContext = FrameworkUtil.getBundle(ExecHandler.class).getBundleContext();
98 this.execWhitelistWatchService = execWhitelistWatchService;
102 public void handleCommand(ChannelUID channelUID, Command command) {
103 if (command instanceof RefreshType) {
104 // Placeholder for later refinement
106 if (channelUID.getId().equals(RUN)) {
107 if (command instanceof OnOffType) {
108 if (command == OnOffType.ON) {
109 scheduler.schedule(this::execute, 0, TimeUnit.SECONDS);
112 } else if (channelUID.getId().equals(INPUT)) {
113 if (command instanceof StringType) {
114 String previousInput = lastInput;
115 lastInput = command.toString();
116 if (lastInput != null && !lastInput.equals(previousInput)) {
117 if (getConfig().get(AUTORUN) != null && ((Boolean) getConfig().get(AUTORUN))) {
118 logger.trace("Executing command '{}' after a change of the input channel to '{}'",
119 getConfig().get(COMMAND), lastInput);
120 scheduler.schedule(this::execute, 0, TimeUnit.SECONDS);
129 public void initialize() {
130 if (executionJob == null || executionJob.isCancelled()) {
131 if ((getConfig().get(INTERVAL)) != null && ((BigDecimal) getConfig().get(INTERVAL)).intValue() > 0) {
132 int pollingInterval = ((BigDecimal) getConfig().get(INTERVAL)).intValue();
133 executionJob = scheduler.scheduleWithFixedDelay(this::execute, 0, pollingInterval, TimeUnit.SECONDS);
137 updateStatus(ThingStatus.ONLINE);
141 public void dispose() {
142 if (executionJob != null && !executionJob.isCancelled()) {
143 executionJob.cancel(true);
148 public void execute() {
149 String commandLine = (String) getConfig().get(COMMAND);
150 if (!execWhitelistWatchService.isWhitelisted(commandLine)) {
151 logger.warn("Tried to execute '{}', but it is not contained in whitelist.", commandLine);
156 if ((getConfig().get(TIME_OUT)) != null) {
157 timeOut = ((BigDecimal) getConfig().get(TIME_OUT)).intValue() * 1000;
160 if (commandLine != null && !commandLine.isEmpty()) {
161 updateState(RUN, OnOffType.ON);
163 // For some obscure reason, when using Apache Common Exec, or using a straight implementation of
164 // Runtime.Exec(), on Mac OS X (Yosemite and El Capitan), there seems to be a lock race condition
165 // randomly appearing (on UNIXProcess) *when* one tries to gobble up the stdout and sterr output of the
166 // subprocess in separate threads. It seems to be common "wisdom" to do that in separate threads, but
167 // only when keeping everything between .exec() and .waitfor() in the same thread, this lock race
168 // condition seems to go away. This approach of not reading the outputs in separate threads *might* be a
169 // problem for external commands that generate a lot of output, but this will be dependent on the limits
170 // of the underlying operating system.
172 Date date = Calendar.getInstance().getTime();
174 if (lastInput != null) {
175 commandLine = String.format(commandLine, date, lastInput);
177 commandLine = String.format(commandLine, date);
179 } catch (IllegalFormatException e) {
181 "An exception occurred while formatting the command line '{}' with the current time '{}' and input value '{}': {}",
182 commandLine, date, lastInput, e.getMessage());
183 updateState(RUN, OnOffType.OFF);
184 updateState(OUTPUT, new StringType(e.getMessage()));
190 if (commandLine.contains(CMD_LINE_DELIMITER)) {
191 logger.debug("Splitting by '{}'", CMD_LINE_DELIMITER);
193 cmdArray = commandLine.split(CMD_LINE_DELIMITER);
194 } catch (PatternSyntaxException e) {
195 logger.warn("An exception occurred while splitting '{}' : '{}'", commandLine, e.getMessage());
196 updateState(RUN, OnOffType.OFF);
197 updateState(OUTPUT, new StringType(e.getMessage()));
201 // Invoke shell with 'c' option and pass string
202 logger.debug("Passing to shell for parsing command.");
203 switch (getOperatingSystemType()) {
205 shell = SHELL_WINDOWS;
206 logger.debug("OS: WINDOWS ({})", getOperatingSystemName());
207 cmdArray = createCmdArray(shell, "/c", commandLine);
212 // assume sh is present, should all be POSIX-compliant
214 logger.debug("OS: *NIX ({})", getOperatingSystemName());
215 cmdArray = createCmdArray(shell, "-c", commandLine);
218 logger.debug("OS: Unknown ({})", getOperatingSystemName());
219 logger.warn("OS {} not supported, please manually split commands!", getOperatingSystemName());
220 updateState(RUN, OnOffType.OFF);
221 updateState(OUTPUT, new StringType("OS not supported, please manually split commands!"));
226 if (cmdArray.length == 0) {
227 logger.trace("Empty command received, not executing");
231 logger.trace("The command to be executed will be '{}'", Arrays.asList(cmdArray));
235 proc = rt.exec(cmdArray);
236 } catch (Exception e) {
237 logger.warn("An exception occurred while executing '{}' : '{}'", Arrays.asList(cmdArray),
239 updateState(RUN, OnOffType.OFF);
240 updateState(OUTPUT, new StringType(e.getMessage()));
244 StringBuilder outputBuilder = new StringBuilder();
245 StringBuilder errorBuilder = new StringBuilder();
247 try (InputStreamReader isr = new InputStreamReader(proc.getInputStream());
248 BufferedReader br = new BufferedReader(isr)) {
250 while ((line = br.readLine()) != null) {
251 outputBuilder.append(line).append("\n");
252 logger.debug("Exec [{}]: '{}'", "OUTPUT", line);
254 } catch (IOException e) {
255 logger.warn("An exception occurred while reading the stdout when executing '{}' : '{}'", commandLine,
259 try (InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
260 BufferedReader br = new BufferedReader(isr)) {
262 while ((line = br.readLine()) != null) {
263 errorBuilder.append(line).append("\n");
264 logger.debug("Exec [{}]: '{}'", "ERROR", line);
266 } catch (IOException e) {
267 logger.warn("An exception occurred while reading the stderr when executing '{}' : '{}'", commandLine,
271 boolean exitVal = false;
273 exitVal = proc.waitFor(timeOut, TimeUnit.MILLISECONDS);
274 } catch (InterruptedException e) {
275 logger.warn("An exception occurred while waiting for the process ('{}') to finish : '{}'", commandLine,
280 logger.warn("Forcibly termininating the process ('{}') after a timeout of {} ms", commandLine, timeOut);
281 proc.destroyForcibly();
284 updateState(RUN, OnOffType.OFF);
285 updateState(EXIT, new DecimalType(proc.exitValue()));
287 outputBuilder.append(errorBuilder.toString());
289 outputBuilder.append(errorBuilder.toString());
291 String transformedResponse = StringUtils.chomp(outputBuilder.toString());
292 String transformation = (String) getConfig().get(TRANSFORM);
294 if (transformation != null && transformation.length() > 0) {
295 transformedResponse = transformResponse(transformedResponse, transformation);
298 updateState(OUTPUT, new StringType(transformedResponse));
300 DateTimeType stampType = new DateTimeType(ZonedDateTime.now());
301 updateState(LAST_EXECUTION, stampType);
305 protected @Nullable String transformResponse(String response, String transformation) {
306 String transformedResponse;
309 String[] parts = splitTransformationConfig(transformation);
310 String transformationType = parts[0];
311 String transformationFunction = parts[1];
313 TransformationService transformationService = TransformationHelper.getTransformationService(bundleContext,
315 if (transformationService != null) {
316 transformedResponse = transformationService.transform(transformationFunction, response);
318 transformedResponse = response;
319 logger.warn("Couldn't transform response because transformationService of type '{}' is unavailable",
322 } catch (TransformationException te) {
323 logger.warn("An exception occurred while transforming '{}' with '{}' : '{}'", response, transformation,
326 // in case of an error we return the response without any transformation
327 transformedResponse = response;
330 logger.debug("Transformed response is '{}'", transformedResponse);
331 return transformedResponse;
335 * Splits a transformation configuration string into its two parts - the
336 * transformation type and the function/pattern to apply.
338 * @param transformation the string to split
339 * @return a string array with exactly two entries for the type and the function
341 protected String[] splitTransformationConfig(String transformation) {
342 Matcher matcher = EXTRACT_FUNCTION_PATTERN.matcher(transformation);
344 if (!matcher.matches()) {
345 throw new IllegalArgumentException("given transformation function '" + transformation
346 + "' does not follow the expected pattern '<function>(<pattern>)'");
351 String type = matcher.group(1);
352 String pattern = matcher.group(2);
354 return new String[] { type, pattern };
358 * Transforms the command string into an array.
359 * Either invokes the shell and passes using the "c" option
360 * or (if command already starts with one of the shells) splits by space.
362 * @param shell (path), picks to first one to execute the command
363 * @param cOption "c"-option string
364 * @param commandLine to execute
365 * @return command array
367 protected String[] createCmdArray(String[] shell, String cOption, String commandLine) {
368 boolean startsWithShell = false;
369 for (String sh : shell) {
370 if (commandLine.startsWith(sh + " ")) {
371 startsWithShell = true;
376 if (!startsWithShell) {
377 return new String[] { shell[0], cOption, commandLine };
379 logger.debug("Splitting by spaces");
381 return commandLine.split(" ");
382 } catch (PatternSyntaxException e) {
383 logger.warn("An exception occurred while splitting '{}' : '{}'", commandLine, e.getMessage());
384 updateState(RUN, OnOffType.OFF);
385 updateState(OUTPUT, new StringType(e.getMessage()));
386 return new String[] {};
392 * Contains information about which operating system openHAB is running on.
393 * Found on https://stackoverflow.com/a/31547504/7508309, slightly modified
395 * @author Constantin Piber (for Memin) - Initial contribution
406 private static OS os = OS.NOT_SET;
408 public static OS getOperatingSystemType() {
409 if (os == OS.NOT_SET) {
410 String operSys = System.getProperty("os.name").toLowerCase();
411 if (operSys.contains("win")) {
413 } else if (operSys.contains("nix") || operSys.contains("nux") || operSys.contains("aix")) {
415 } else if (operSys.contains("mac")) {
417 } else if (operSys.contains("sunos")) {
426 public static String getOperatingSystemName() {
427 String osname = System.getProperty("os.name");
428 return osname != null ? osname : "unknown";