]> git.basschouten.com Git - openhab-addons.git/blob
8ef8613e7af0e49ceabee196438b8ac4ce7d7745
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.exec.internal.handler;
14
15 import static org.openhab.binding.exec.internal.ExecBindingConstants.*;
16
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;
31
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;
53
54 /**
55  * The {@link ExecHandler} is responsible for handling commands, which are
56  * sent to one of the channels.
57  *
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
61  */
62 @NonNullByDefault
63 public class ExecHandler extends BaseThingHandler {
64     /**
65      * Use this to separate between command and parameter, and also between parameters.
66      */
67     public static final String CMD_LINE_DELIMITER = "@@";
68
69     /**
70      * Shell executables
71      */
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;
75
76     private Logger logger = LoggerFactory.getLogger(ExecHandler.class);
77
78     private final BundleContext bundleContext;
79
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";
86
87     // RegEx to extract a parse a function String <code>'(.*?)\((.*)\)'</code>
88     private static final Pattern EXTRACT_FUNCTION_PATTERN = Pattern.compile("(.*?)\\((.*)\\)");
89
90     private @Nullable ScheduledFuture<?> executionJob;
91     private @Nullable String lastInput;
92
93     private static Runtime rt = Runtime.getRuntime();
94
95     public ExecHandler(Thing thing, ExecWhitelistWatchService execWhitelistWatchService) {
96         super(thing);
97         this.bundleContext = FrameworkUtil.getBundle(ExecHandler.class).getBundleContext();
98         this.execWhitelistWatchService = execWhitelistWatchService;
99     }
100
101     @Override
102     public void handleCommand(ChannelUID channelUID, Command command) {
103         if (command instanceof RefreshType) {
104             // Placeholder for later refinement
105         } else {
106             if (channelUID.getId().equals(RUN)) {
107                 if (command instanceof OnOffType) {
108                     if (command == OnOffType.ON) {
109                         scheduler.schedule(this::execute, 0, TimeUnit.SECONDS);
110                     }
111                 }
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);
121                         }
122                     }
123                 }
124             }
125         }
126     }
127
128     @Override
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);
134             }
135         }
136
137         updateStatus(ThingStatus.ONLINE);
138     }
139
140     @Override
141     public void dispose() {
142         if (executionJob != null && !executionJob.isCancelled()) {
143             executionJob.cancel(true);
144             executionJob = null;
145         }
146     }
147
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);
152             return;
153         }
154
155         int timeOut = 60000;
156         if ((getConfig().get(TIME_OUT)) != null) {
157             timeOut = ((BigDecimal) getConfig().get(TIME_OUT)).intValue() * 1000;
158         }
159
160         if (commandLine != null && !commandLine.isEmpty()) {
161             updateState(RUN, OnOffType.ON);
162
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.
171
172             Date date = Calendar.getInstance().getTime();
173             try {
174                 if (lastInput != null) {
175                     commandLine = String.format(commandLine, date, lastInput);
176                 } else {
177                     commandLine = String.format(commandLine, date);
178                 }
179             } catch (IllegalFormatException e) {
180                 logger.warn(
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()));
185                 return;
186             }
187
188             String[] cmdArray;
189             String[] shell;
190             if (commandLine.contains(CMD_LINE_DELIMITER)) {
191                 logger.debug("Splitting by '{}'", CMD_LINE_DELIMITER);
192                 try {
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()));
198                     return;
199                 }
200             } else {
201                 // Invoke shell with 'c' option and pass string
202                 logger.debug("Passing to shell for parsing command.");
203                 switch (getOperatingSystemType()) {
204                     case WINDOWS:
205                         shell = SHELL_WINDOWS;
206                         logger.debug("OS: WINDOWS ({})", getOperatingSystemName());
207                         cmdArray = createCmdArray(shell, "/c", commandLine);
208                         break;
209                     case LINUX:
210                     case MAC:
211                     case SOLARIS:
212                         // assume sh is present, should all be POSIX-compliant
213                         shell = SHELL_NIX;
214                         logger.debug("OS: *NIX ({})", getOperatingSystemName());
215                         cmdArray = createCmdArray(shell, "-c", commandLine);
216                         break;
217                     default:
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!"));
222                         return;
223                 }
224             }
225
226             if (cmdArray.length == 0) {
227                 logger.trace("Empty command received, not executing");
228                 return;
229             }
230
231             logger.trace("The command to be executed will be '{}'", Arrays.asList(cmdArray));
232
233             Process proc;
234             try {
235                 proc = rt.exec(cmdArray);
236             } catch (Exception e) {
237                 logger.warn("An exception occurred while executing '{}' : '{}'", Arrays.asList(cmdArray),
238                         e.getMessage());
239                 updateState(RUN, OnOffType.OFF);
240                 updateState(OUTPUT, new StringType(e.getMessage()));
241                 return;
242             }
243
244             StringBuilder outputBuilder = new StringBuilder();
245             StringBuilder errorBuilder = new StringBuilder();
246
247             try (InputStreamReader isr = new InputStreamReader(proc.getInputStream());
248                     BufferedReader br = new BufferedReader(isr)) {
249                 String line;
250                 while ((line = br.readLine()) != null) {
251                     outputBuilder.append(line).append("\n");
252                     logger.debug("Exec [{}]: '{}'", "OUTPUT", line);
253                 }
254             } catch (IOException e) {
255                 logger.warn("An exception occurred while reading the stdout when executing '{}' : '{}'", commandLine,
256                         e.getMessage());
257             }
258
259             try (InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
260                     BufferedReader br = new BufferedReader(isr)) {
261                 String line;
262                 while ((line = br.readLine()) != null) {
263                     errorBuilder.append(line).append("\n");
264                     logger.debug("Exec [{}]: '{}'", "ERROR", line);
265                 }
266             } catch (IOException e) {
267                 logger.warn("An exception occurred while reading the stderr when executing '{}' : '{}'", commandLine,
268                         e.getMessage());
269             }
270
271             boolean exitVal = false;
272             try {
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,
276                         e.getMessage());
277             }
278
279             if (!exitVal) {
280                 logger.warn("Forcibly termininating the process ('{}') after a timeout of {} ms", commandLine, timeOut);
281                 proc.destroyForcibly();
282             }
283
284             updateState(RUN, OnOffType.OFF);
285             updateState(EXIT, new DecimalType(proc.exitValue()));
286
287             outputBuilder.append(errorBuilder.toString());
288
289             outputBuilder.append(errorBuilder.toString());
290
291             String transformedResponse = StringUtils.chomp(outputBuilder.toString());
292             String transformation = (String) getConfig().get(TRANSFORM);
293
294             if (transformation != null && transformation.length() > 0) {
295                 transformedResponse = transformResponse(transformedResponse, transformation);
296             }
297
298             updateState(OUTPUT, new StringType(transformedResponse));
299
300             DateTimeType stampType = new DateTimeType(ZonedDateTime.now());
301             updateState(LAST_EXECUTION, stampType);
302         }
303     }
304
305     protected @Nullable String transformResponse(String response, String transformation) {
306         String transformedResponse;
307
308         try {
309             String[] parts = splitTransformationConfig(transformation);
310             String transformationType = parts[0];
311             String transformationFunction = parts[1];
312
313             TransformationService transformationService = TransformationHelper.getTransformationService(bundleContext,
314                     transformationType);
315             if (transformationService != null) {
316                 transformedResponse = transformationService.transform(transformationFunction, response);
317             } else {
318                 transformedResponse = response;
319                 logger.warn("Couldn't transform response because transformationService of type '{}' is unavailable",
320                         transformationType);
321             }
322         } catch (TransformationException te) {
323             logger.warn("An exception occurred while transforming '{}' with '{}' : '{}'", response, transformation,
324                     te.getMessage());
325
326             // in case of an error we return the response without any transformation
327             transformedResponse = response;
328         }
329
330         logger.debug("Transformed response is '{}'", transformedResponse);
331         return transformedResponse;
332     }
333
334     /**
335      * Splits a transformation configuration string into its two parts - the
336      * transformation type and the function/pattern to apply.
337      *
338      * @param transformation the string to split
339      * @return a string array with exactly two entries for the type and the function
340      */
341     protected String[] splitTransformationConfig(String transformation) {
342         Matcher matcher = EXTRACT_FUNCTION_PATTERN.matcher(transformation);
343
344         if (!matcher.matches()) {
345             throw new IllegalArgumentException("given transformation function '" + transformation
346                     + "' does not follow the expected pattern '<function>(<pattern>)'");
347         }
348         matcher.reset();
349
350         matcher.find();
351         String type = matcher.group(1);
352         String pattern = matcher.group(2);
353
354         return new String[] { type, pattern };
355     }
356
357     /**
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.
361      *
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
366      */
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;
372                 break;
373             }
374         }
375
376         if (!startsWithShell) {
377             return new String[] { shell[0], cOption, commandLine };
378         } else {
379             logger.debug("Splitting by spaces");
380             try {
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[] {};
387             }
388         }
389     }
390
391     /**
392      * Contains information about which operating system openHAB is running on.
393      * Found on https://stackoverflow.com/a/31547504/7508309, slightly modified
394      *
395      * @author Constantin Piber (for Memin) - Initial contribution
396      */
397     public enum OS {
398         WINDOWS,
399         LINUX,
400         MAC,
401         SOLARIS,
402         UNKNOWN,
403         NOT_SET
404     }
405
406     private static OS os = OS.NOT_SET;
407
408     public static OS getOperatingSystemType() {
409         if (os == OS.NOT_SET) {
410             String operSys = System.getProperty("os.name").toLowerCase();
411             if (operSys.contains("win")) {
412                 os = OS.WINDOWS;
413             } else if (operSys.contains("nix") || operSys.contains("nux") || operSys.contains("aix")) {
414                 os = OS.LINUX;
415             } else if (operSys.contains("mac")) {
416                 os = OS.MAC;
417             } else if (operSys.contains("sunos")) {
418                 os = OS.SOLARIS;
419             } else {
420                 os = OS.UNKNOWN;
421             }
422         }
423         return os;
424     }
425
426     public static String getOperatingSystemName() {
427         String osname = System.getProperty("os.name");
428         return osname != null ? osname : "unknown";
429     }
430 }