diff --git a/src/main/java/org/codehaus/plexus/util/cli/Commandline.java b/src/main/java/org/codehaus/plexus/util/cli/Commandline.java index 649159ec..b0fee17d 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/Commandline.java +++ b/src/main/java/org/codehaus/plexus/util/cli/Commandline.java @@ -59,12 +59,14 @@ import java.io.File; import java.io.IOException; +import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import java.util.Vector; +import java.util.function.Predicate; import org.codehaus.plexus.util.Os; import org.codehaus.plexus.util.StringUtils; @@ -96,6 +98,18 @@ * @author Stefan Bodewig */ public class Commandline implements Cloneable { + /** + * System property that controls how a command line with the default shell is started on Windows. With + * false, every command is wrapped in cmd.exe /X /D /C "...", as in plexus-utils 3.1.0 to + * 4.2.x. With any other value or none, an executable that resolves to an .exe or .com + * file is started directly. The property is read each time a command line is built. + * + * @see #getCommandline() + * @since 4.3.0 + */ + public static final String WINDOWS_DIRECT_EXECUTION_PROPERTY = + "org.codehaus.plexus.util.cli.windowsDirectExecution"; + /** * @deprecated Use {@link org.codehaus.plexus.util.Os} class instead. */ @@ -118,6 +132,11 @@ public class Commandline implements Cloneable { private Shell shell; + /** + * Whether the caller chose the shell, as opposed to the one detected from the operating system. + */ + private boolean shellChosenByCaller; + /** * @deprecated Use {@link Commandline#setExecutable(String)} instead. */ @@ -140,6 +159,7 @@ public class Commandline implements Cloneable { */ public Commandline(String toProcess, Shell shell) { this.shell = shell; + this.shellChosenByCaller = true; String[] tmp = new String[0]; try { @@ -162,6 +182,7 @@ public Commandline(String toProcess, Shell shell) { */ public Commandline(Shell shell) { this.shell = shell; + this.shellChosenByCaller = true; } /** @@ -246,15 +267,23 @@ private void setDefaultShell() { // If this is windows set the shell to command.com or cmd.exe with correct arguments. if (Os.isFamily(Os.FAMILY_WINDOWS)) { if (Os.isFamily(Os.FAMILY_WIN9X)) { - setShell(new CommandShell()); + setDefaultShell(new CommandShell()); } else { - setShell(new CmdShell()); + setDefaultShell(new CmdShell()); } } else { - setShell(new BourneShell()); + setDefaultShell(new BourneShell()); } } + /** + * Sets a shell that counts as detected, not as chosen by the caller. + */ + void setDefaultShell(Shell shell) { + this.shell = shell; + this.shellChosenByCaller = false; + } + /** *

Creates an argument object.

* @@ -462,17 +491,136 @@ public String[] getEnvironmentVariables() throws CommandLineException { } /** - * @return Returns the executable and all defined arguments. - * For Windows Family, {@link Commandline#getShellCommandline()} is returned + * Returns the command line that {@link #execute()} starts. + *

+ * On Windows, the executable is looked up the way cmd.exe would: in the working directory and then + * on the PATH of the process to start, with the PATHEXT extensions. If that yields an + * .exe or .com file, the result is the path of that file followed by the arguments as + * given, as {@link #getRawCommandline()} returns them, and no shell is involved. In every other case the result + * is {@link #getShellCommandline()}: for .bat and .cmd scripts, for commands built into + * cmd.exe, for names that cannot be resolved, when a shell was set with {@link #setShell(Shell)} or + * a constructor, when the detected shell was reconfigured through {@link #getShell()}, and when the system + * property {@link #WINDOWS_DIRECT_EXECUTION_PROPERTY} is false. {@link #execute()} also falls back + * to the shell form when the direct start fails. + *

+ *

+ * An argument for a directly started executable is not interpreted by cmd.exe: + * &, |, <, >, ^ and + * %NAME% reach the program as they are. A caller that needs redirection, chaining or variable + * expansion has to ask for a shell, for example with setShell(new CmdShell()). + *

+ * + * @return the executable and all defined arguments; on other platforms than Windows, the same as + * {@link #getRawCommandline()} */ public String[] getCommandline() { if (Os.isFamily(Os.FAMILY_WINDOWS)) { - return getShellCommandline(); + File workDir = getWorkingDirectory(); + String cwd = workDir != null ? workDir.getAbsolutePath() : System.getProperty("user.dir"); + return getWindowsCommandline(windowsChildEnvironment(), cwd, WINDOWS_IS_FILE); } return getRawCommandline(); } + private static final Predicate WINDOWS_IS_FILE = new Predicate() { + @Override + public boolean test(String path) { + return new File(path).isFile(); + } + }; + + /** + * The Windows branch of {@link #getCommandline()}, with everything it reads from the platform passed in. + * + * @param environment the environment of the process to start + * @param workingDirectory the absolute working directory of the process to start + * @param isFile tells whether an absolute path denotes an existing regular file + * @return the command line to start + */ + String[] getWindowsCommandline(Map environment, String workingDirectory, Predicate isFile) { + verifyShellState(); + + if (isWindowsDirectExecutionAllowed()) { + WindowsExecutableResolver.Resolution resolution; + try { + resolution = WindowsExecutableResolver.resolve( + getLiteralExecutable(), environment, workingDirectory, isFile); + } catch (RuntimeException e) { + // for example a SecurityException from the file check: let cmd.exe decide + resolution = null; + } + if (resolution != null && resolution.getKind() == WindowsExecutableResolver.Kind.NATIVE) { + String[] result = getRawCommandline(); + result[0] = resolution.getPath(); + return result; + } + } + + return getShellCommandline(); + } + + /** + * Direct execution applies to the shell this class picks on Windows and to nothing else: a shell that the caller + * set, or the detected one after the caller changed how it quotes or how it is invoked, is a request to go + * through that shell. + */ + private boolean isWindowsDirectExecutionAllowed() { + if (shellChosenByCaller || shell == null || shell.getClass() != CmdShell.class) { + return false; + } + if ("false".equalsIgnoreCase(System.getProperty(WINDOWS_DIRECT_EXECUTION_PROPERTY))) { + return false; + } + if (!sameExecutable(getLiteralExecutable(), shell.getOriginalExecutable())) { + // set on the shell behind our back: the shell form is the only one that honours it + return false; + } + CmdShell pristine = new CmdShell(); + return pristine.getShellCommand().equals(shell.getShellCommand()) + && pristine.getShellArgsList().equals(shell.getShellArgsList()) + && shell.isQuotedArgumentsEnabled() + && shell.isQuotedExecutableEnabled() + && !shell.isUnconditionalQuoting(); + } + + private static boolean sameExecutable(String literal, String inShell) { + if (literal == null || inShell == null) { + return literal == null && inShell == null; + } + // Shell.setExecutable() rewrites the separators + return literal.replace('/', '\\').equals(inShell.replace('/', '\\')); + } + + /** + * @return what {@link #getEnvironmentVariables()} hands to the process, without adding the system environment to + * this command line as that method does + */ + Map windowsChildEnvironment() { + Map environment = new LinkedHashMap<>(); + Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); + for (String name : systemEnvVars.stringPropertyNames()) { + environment.put(name, systemEnvVars.getProperty(name)); + } + synchronized (envVars) { + for (Map.Entry entry : envVars.entrySet()) { + // Windows keeps one variable per case-insensitive name + String existing = null; + for (String name : environment.keySet()) { + if (name.equalsIgnoreCase(entry.getKey())) { + existing = name; + break; + } + } + if (existing != null) { + environment.remove(existing); + } + environment.put(entry.getKey(), entry.getValue()); + } + } + return environment; + } + /** * Returns the executable and all defined arguments. * @return the command line as array not escaped neither quoted @@ -522,6 +670,10 @@ public String[] getArguments() { return res; } + /** + * @return the {@linkplain #getShellCommandline() shell form} of this command line on every platform, which is a + * readable rendering and not necessarily what {@link #execute()} starts; see {@link #getCommandline()} + */ @Override public String toString() { return StringUtils.join(getShellCommandline(), " "); @@ -534,6 +686,7 @@ public int size() { @Override public Object clone() { Commandline c = new Commandline((Shell) shell.clone()); + c.shellChosenByCaller = shellChosenByCaller; c.executable = executable; c.workingDir = workingDir; c.addArguments(getArguments()); @@ -598,7 +751,9 @@ public File getWorkingDirectory() { } /** - * Executes the command. + * Executes the command line that {@link #getCommandline()} returns. On Windows, if starting a command directly + * fails with an {@link IOException} (for example a missing file, a permission problem, an image that needs + * elevation or is not a valid one), the command is started once more through the shell. * @return the Process * @throws CommandLineException if error */ @@ -615,9 +770,7 @@ public Process execute() throws CommandLineException { File workingDir = shell.getWorkingDirectory(); try { - if (workingDir == null) { - process = Runtime.getRuntime().exec(getCommandline(), environment, workingDir); - } else { + if (workingDir != null) { if (!workingDir.exists()) { throw new CommandLineException( "Working directory \"" + workingDir.getPath() + "\" does not exist!"); @@ -625,8 +778,19 @@ public Process execute() throws CommandLineException { throw new CommandLineException( "Path \"" + workingDir.getPath() + "\" does not specify a directory."); } + } - process = Runtime.getRuntime().exec(getCommandline(), environment, workingDir); + String[] commandline = getCommandline(); + try { + process = Runtime.getRuntime().exec(commandline, environment, workingDir); + } catch (IOException e) { + String[] shellCommandline = Os.isFamily(Os.FAMILY_WINDOWS) ? getShellCommandline() : commandline; + if (Arrays.equals(commandline, shellCommandline)) { + throw e; + } + // No process was created. Whatever stopped the direct start (an image that needs elevation or is + // not a valid one, an argument the JDK refuses), cmd.exe gets to deal with it as it did before. + process = Runtime.getRuntime().exec(shellCommandline, environment, workingDir); } } catch (IOException ex) { throw new CommandLineException("Error while executing process.", ex); @@ -662,6 +826,7 @@ public Properties getSystemEnvVars() throws Exception { */ public void setShell(Shell shell) { this.shell = shell; + this.shellChosenByCaller = true; } /** diff --git a/src/main/java/org/codehaus/plexus/util/cli/WindowsExecutableResolver.java b/src/main/java/org/codehaus/plexus/util/cli/WindowsExecutableResolver.java new file mode 100644 index 00000000..1e338959 --- /dev/null +++ b/src/main/java/org/codehaus/plexus/util/cli/WindowsExecutableResolver.java @@ -0,0 +1,324 @@ +package org.codehaus.plexus.util.cli; + +/* + * Copyright The Codehaus Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; + +/** + * Finds the file that cmd.exe would run for a command name, so that {@link Commandline} can start native + * images without a shell. + *

+ * The search follows cmd.exe, not CreateProcess: internal commands win over files, the + * working directory is searched before PATH, and in each directory the name is tried as given (when it + * has an extension) and then with each PATHEXT extension in order. + *

+ *

+ * The only answer that changes how a process is started is {@link Kind#NATIVE}. Whenever the resolver cannot tell + * what cmd.exe would do, it answers {@link Kind#UNRESOLVED} and the caller keeps the shell, so that a + * mistake here costs the optimisation and never the behaviour. + *

+ *

+ * All path handling is done on strings with Windows rules, so that the logic can be tested on any platform. + *

+ */ +final class WindowsExecutableResolver { + /** + * What a command name stands for. + */ + enum Kind { + /** An existing .exe or .com file, which CreateProcess runs as is. */ + NATIVE, + /** An existing .bat or .cmd file, which only cmd.exe can interpret. */ + SCRIPT, + /** An existing file of another type, run by cmd.exe through its file association. */ + ASSOCIATED, + /** A command implemented by cmd.exe itself, such as echo or dir. */ + BUILTIN, + /** Nothing was found, or the name is in a form this class does not interpret. */ + UNRESOLVED + } + + static final class Resolution { + private static final Resolution UNRESOLVED = new Resolution(Kind.UNRESOLVED, null); + + private static final Resolution BUILTIN = new Resolution(Kind.BUILTIN, null); + + private final Kind kind; + + private final String path; + + private Resolution(Kind kind, String path) { + this.kind = kind; + this.path = path; + } + + Kind getKind() { + return kind; + } + + /** + * @return the absolute path of the file found, or null for {@link Kind#BUILTIN} and + * {@link Kind#UNRESOLVED} + */ + String getPath() { + return path; + } + + @Override + public String toString() { + return path == null ? kind.toString() : kind + " " + path; + } + } + + private static final String DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD"; + + /** + * Characters that make cmd.exe do more with a command name than look up a file: quoting, wildcards, + * redirection, command chaining, escaping, variable expansion and its own token separators. + */ + private static final String UNSUPPORTED_CHARS = "\"*?<>|&^%!,;=\t"; + + private static final Set BUILTINS = new HashSet<>(Arrays.asList( + "assoc", + "break", + "call", + "cd", + "chcp", + "chdir", + "cls", + "color", + "copy", + "date", + "del", + "dir", + "dpath", + "echo", + "endlocal", + "erase", + "exit", + "for", + "ftype", + "goto", + "if", + "keys", + "md", + "mkdir", + "mklink", + "move", + "path", + "pause", + "popd", + "prompt", + "pushd", + "rd", + "rem", + "ren", + "rename", + "rmdir", + "set", + "setlocal", + "shift", + "start", + "time", + "title", + "type", + "ver", + "verify", + "vol")); + + private WindowsExecutableResolver() {} + + /** + * @param executable the command name as the caller gave it, with or without directory and extension + * @param environment the environment of the process to start; names are matched case-insensitively + * @param workingDirectory the absolute working directory of the process to start + * @param isFile tells whether an absolute path denotes an existing regular file + * @return what cmd.exe would run, never null + */ + static Resolution resolve( + String executable, Map environment, String workingDirectory, Predicate isFile) { + if (executable == null || workingDirectory == null) { + return Resolution.UNRESOLVED; + } + String name = executable.replace('/', '\\'); + if (name.isEmpty() || !name.equals(name.trim()) || containsAny(name, UNSUPPORTED_CHARS)) { + return Resolution.UNRESOLVED; + } + String cwd = workingDirectory.replace('/', '\\'); + if (!isAbsolute(cwd)) { + return Resolution.UNRESOLVED; + } + + List extensions = pathExtensions(getIgnoreCase(environment, "PATHEXT")); + + int lastSeparator = name.lastIndexOf('\\'); + if (lastSeparator >= 0 || name.indexOf(':') >= 0) { + // a directory was given: cmd.exe looks there and nowhere else + if (lastSeparator < 0 || lastSeparator == name.length() - 1) { + return Resolution.UNRESOLVED; + } + String directory = absoluteDirectory(name.substring(0, lastSeparator + 1), cwd); + if (directory == null) { + return Resolution.UNRESOLVED; + } + Resolution found = findIn(directory, name.substring(lastSeparator + 1), extensions, isFile); + return found != null ? found : Resolution.UNRESOLVED; + } + + if (BUILTINS.contains(name.toLowerCase(Locale.ROOT))) { + return Resolution.BUILTIN; + } + + List directories = new ArrayList<>(); + if (getIgnoreCase(environment, "NoDefaultCurrentDirectoryInExePath") == null) { + directories.add(cwd); + } + String path = getIgnoreCase(environment, "PATH"); + if (path != null) { + for (String entry : path.split(";")) { + entry = entry.trim(); + if (entry.isEmpty()) { + continue; + } + String directory = containsAny(entry, UNSUPPORTED_CHARS) ? null : absoluteDirectory(entry, cwd); + if (directory == null) { + // cmd.exe may find the command here, and we cannot tell: do not look any further + return findFirst(directories, name, extensions, isFile, Resolution.UNRESOLVED); + } + directories.add(directory); + } + } + return findFirst(directories, name, extensions, isFile, Resolution.UNRESOLVED); + } + + private static Resolution findFirst( + List directories, + String name, + List extensions, + Predicate isFile, + Resolution otherwise) { + for (String directory : directories) { + Resolution found = findIn(directory, name, extensions, isFile); + if (found != null) { + return found; + } + } + return otherwise; + } + + private static Resolution findIn(String directory, String name, List extensions, Predicate isFile) { + String base = directory.endsWith("\\") ? directory + name : directory + '\\' + name; + if (name.endsWith(".") || name.endsWith(" ")) { + // Win32 drops trailing dots and spaces, so the file found would not be the one named + return Resolution.UNRESOLVED; + } + if (name.indexOf('.') >= 0 && isFile.test(base)) { + return new Resolution(kindOf(base), base); + } + for (String extension : extensions) { + String candidate = base + extension; + if (isFile.test(candidate)) { + return new Resolution(kindOf(candidate), candidate); + } + } + return null; + } + + private static Kind kindOf(String path) { + String lower = path.toLowerCase(Locale.ROOT); + if (lower.endsWith(".exe") || lower.endsWith(".com")) { + return Kind.NATIVE; + } + if (lower.endsWith(".bat") || lower.endsWith(".cmd")) { + return Kind.SCRIPT; + } + return Kind.ASSOCIATED; + } + + private static List pathExtensions(String pathext) { + List result = new ArrayList<>(); + for (String extension : (pathext == null || pathext.trim().isEmpty() ? DEFAULT_PATHEXT : pathext).split(";")) { + extension = extension.trim(); + if (extension.length() > 1 && extension.charAt(0) == '.' && !containsAny(extension, "\\/:")) { + result.add(extension); + } + } + return result; + } + + /** + * @return the directory as an absolute path, or null if it is in a form that depends on more than the + * working directory (C:foo, \foo) + */ + private static String absoluteDirectory(String directory, String cwd) { + String dir = directory.replace('/', '\\'); + if (isAbsolute(dir)) { + return dir; + } + if (dir.startsWith("\\") || dir.indexOf(':') >= 0) { + return null; + } + return cwd.endsWith("\\") ? cwd + dir : cwd + '\\' + dir; + } + + /** + * @return true for C:\... and \\server\share... + */ + private static boolean isAbsolute(String path) { + if (path.startsWith("\\\\")) { + return path.length() > 2 && path.indexOf(':') < 0; + } + return path.length() >= 3 + && isLetter(path.charAt(0)) + && path.charAt(1) == ':' + && path.charAt(2) == '\\' + && path.indexOf(':', 2) < 0; + } + + private static boolean isLetter(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + } + + private static boolean containsAny(String value, String chars) { + for (int i = 0; i < value.length(); i++) { + if (chars.indexOf(value.charAt(i)) >= 0) { + return true; + } + } + return false; + } + + private static String getIgnoreCase(Map environment, String name) { + String value = environment.get(name); + if (value != null) { + return value; + } + for (Map.Entry entry : environment.entrySet()) { + if (name.equalsIgnoreCase(entry.getKey())) { + return entry.getValue(); + } + } + return null; + } +} diff --git a/src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java b/src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java index 8b5a7fe8..8496620c 100644 --- a/src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java +++ b/src/main/java/org/codehaus/plexus/util/cli/shell/Shell.java @@ -74,6 +74,15 @@ public void setUnconditionalQuoting(boolean unconditionallyQuote) { this.unconditionallyQuote = unconditionallyQuote; } + /** + * @return whether arguments and executable are quoted even when they contain nothing that requires it + * @see #setUnconditionalQuoting(boolean) + * @since 4.3.0 + */ + public boolean isUnconditionalQuoting() { + return unconditionallyQuote; + } + /** * Set the command to execute the shell (eg. COMMAND.COM, /bin/bash,...) * diff --git a/src/test/java/org/codehaus/plexus/util/cli/CommandlineWindowsLaunchTest.java b/src/test/java/org/codehaus/plexus/util/cli/CommandlineWindowsLaunchTest.java new file mode 100644 index 00000000..bc98c8b9 --- /dev/null +++ b/src/test/java/org/codehaus/plexus/util/cli/CommandlineWindowsLaunchTest.java @@ -0,0 +1,444 @@ +package org.codehaus.plexus.util.cli; + +/* + * Copyright The Codehaus Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; + +import org.codehaus.plexus.util.cli.shell.BourneShell; +import org.codehaus.plexus.util.cli.shell.CmdShell; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * How {@link Commandline} starts a process on Windows: directly for native images, through cmd.exe for + * everything else. The tests of the decision run on every platform against a faked file system and environment; the + * tests that start processes run on Windows only. + */ +class CommandlineWindowsLaunchTest { + private static final String CWD = "C:\\work"; + + private static final String[] SHELL = {"cmd.exe", "/X", "/D", "/C"}; + + private final Map env = new HashMap<>(); + + private final Set files = new HashSet<>(); + + private final Predicate isFile = new Predicate() { + @Override + public boolean test(String path) { + return files.contains(path.toLowerCase(Locale.ROOT)); + } + }; + + CommandlineWindowsLaunchTest() { + env.put("PATH", "C:\\tools"); + env.put("PATHEXT", ".com;.exe;.bat;.cmd"); + for (String path : Arrays.asList("C:\\tools\\git.exe", "C:\\tools\\mvn.cmd", "C:\\tools\\echo.exe")) { + files.add(path.toLowerCase(Locale.ROOT)); + } + } + + /** + * @return a command line as new Commandline() builds it on Windows + */ + private static Commandline windowsCommandline(String executable, String... arguments) { + Commandline cl = new Commandline(); + cl.setDefaultShell(new CmdShell()); + cl.setExecutable(executable); + cl.addArguments(arguments); + return cl; + } + + private String[] launch(Commandline cl) { + return cl.getWindowsCommandline(env, CWD, isFile); + } + + private static void assertShell(String expectedCommand, String[] commandline) { + assertEquals(5, commandline.length, Arrays.toString(commandline)); + assertArrayEquals(SHELL, Arrays.copyOf(commandline, 4)); + if (expectedCommand != null) { + assertEquals(expectedCommand, commandline[4]); + } + } + + @Test + void nativeImageIsStartedDirectlyWithArgumentsUntouched() { + String[] commandline = launch(windowsCommandline("git", "log", "a&b", "x y", "%PATH%", "^", "a|b", ">out")); + assertArrayEquals( + new String[] {"C:\\tools\\git.exe", "log", "a&b", "x y", "%PATH%", "^", "a|b", ">out"}, commandline); + } + + @Test + void scriptKeepsTheShell() { + assertShell("\"mvn -version\"", launch(windowsCommandline("mvn", "-version"))); + } + + @Test + void builtinKeepsTheShellEvenWithAnExeOfThatName() { + assertShell("\"echo Hello\"", launch(windowsCommandline("echo", "Hello"))); + } + + @Test + void unresolvedNameKeepsTheShell() { + assertShell("\"svn --version\"", launch(windowsCommandline("svn", "--version"))); + } + + @Test + void noExecutableKeepsTheShell() { + Commandline cl = new Commandline(); + cl.setDefaultShell(new CmdShell()); + cl.addArguments(new String[] {"git", "status"}); + assertShell("\"git status\"", launch(cl)); + } + + @Test + void shellSetByCallerIsKept() { + Commandline cl = windowsCommandline("git", "status"); + cl.setShell(new CmdShell()); + assertShell("\"git status\"", launch(cl)); + + cl = new Commandline(new CmdShell()); + cl.setExecutable("git"); + assertShell("\"git\"", launch(cl)); + + cl = new Commandline("git status", new BourneShell()); + assertEquals("/bin/sh", launch(cl)[0]); + } + + @Test + void subclassOfCmdShellIsKept() { + Commandline cl = new Commandline(); + cl.setDefaultShell(new CmdShell() {}); + cl.setExecutable("git"); + cl.addArguments(new String[] {"status"}); + assertShell("\"git status\"", launch(cl)); + } + + @Test + void reconfiguredDefaultShellIsKept() { + Commandline cl = windowsCommandline("git", "status"); + cl.getShell().setQuotedArgumentsEnabled(false); + assertShell(null, launch(cl)); + + cl = windowsCommandline("git", "status"); + cl.getShell().setUnconditionalQuoting(true); + assertShell(null, launch(cl)); + + cl = windowsCommandline("git", "status"); + cl.getShell().setQuotedExecutableEnabled(false); + assertShell(null, launch(cl)); + + cl = windowsCommandline("git", "status"); + cl.getShell().setShellArgs(new String[] {"/X", "/C"}); + assertArrayEquals(new String[] {"cmd.exe", "/X", "/C", "\"git status\""}, launch(cl)); + + cl = windowsCommandline("git", "status"); + cl.getShell().setShellCommand("C:\\Windows\\System32\\cmd.exe"); + assertEquals("C:\\Windows\\System32\\cmd.exe", launch(cl)[0]); + + // reading from the shell changes nothing + cl = windowsCommandline("git", "status"); + assertEquals("git", cl.getShell().getOriginalExecutable()); + assertEquals("C:\\tools\\git.exe", launch(cl)[0]); + } + + @Test + void cloneKeepsTheCallersChoice() { + Commandline cl = windowsCommandline("git", "status"); + cl.setShell(new CmdShell()); + assertNotEquals("C:\\tools\\git.exe", launch((Commandline) cl.clone())[0]); + } + + @Test + void systemPropertyRestoresTheShellForEverything() { + Commandline cl = windowsCommandline("git", "status"); + System.setProperty(Commandline.WINDOWS_DIRECT_EXECUTION_PROPERTY, "false"); + try { + assertShell("\"git status\"", launch(cl)); + } finally { + System.clearProperty(Commandline.WINDOWS_DIRECT_EXECUTION_PROPERTY); + } + assertEquals("C:\\tools\\git.exe", launch(cl)[0]); + } + + @Test + void failingFileCheckKeepsTheShell() { + Commandline cl = windowsCommandline("git", "status"); + String[] commandline = cl.getWindowsCommandline(env, CWD, new Predicate() { + @Override + public boolean test(String path) { + throw new SecurityException(path); + } + }); + assertShell("\"git status\"", commandline); + } + + @Test + void shellExecutableSetBehindTheCommandlineIsKept() { + Commandline cl = windowsCommandline("git", "status"); + cl.getShell().setExecutable("mvn"); + assertShell("\"mvn status\"", launch(cl)); + + // the separators the shell rewrites are not a difference + files.add("c:\\jdk/bin\\java.exe".replace('/', '\\')); + cl = windowsCommandline("C:/jdk/bin\\java"); + assertEquals("c:\\jdk\\bin\\java.exe", launch(cl)[0].toLowerCase(Locale.ROOT)); + } + + @Test + void lookupEnvironmentIsTheChildsAndLeavesTheCommandlineAlone() { + String systemName = null; + for (String name : System.getenv().keySet()) { + if ("PATH".equalsIgnoreCase(name)) { + systemName = name; + } + } + assertTrue(systemName != null, "this test needs a PATH"); + + Commandline cl = windowsCommandline("git", "status"); + cl.addEnvironment("ONLY", "this"); + // a different spelling than the system's, as Windows callers may use + String ownName = systemName.equals("Path") ? "PATH" : "Path"; + cl.addEnvironment(ownName, "C:\\own"); + + Map environment = cl.windowsChildEnvironment(); + + assertEquals(2, cl.envVars.size(), "the system environment must not leak into the command line"); + assertEquals("this", environment.get("ONLY")); + assertEquals("C:\\own", environment.get(ownName)); + int paths = 0; + for (String name : environment.keySet()) { + if ("PATH".equalsIgnoreCase(name)) { + paths++; + } + } + assertEquals(1, paths, environment.keySet().toString()); + assertTrue(environment.size() > 2, "the system environment is part of the child's"); + } + + /** + * The process gets the environment the lookup used: one variable per name, whatever the spelling. + */ + @Test + @EnabledOnOs(OS.WINDOWS) + void lookupAndProcessSeeTheSameVariable() throws Exception { + Commandline cl = new Commandline(); + // the inherited variable reaches the command line as PATH, see CommandLineUtils.getSystemEnvVars() + cl.addEnvironment("Path", "C:\\own"); + + assertEquals("C:\\own", cl.windowsChildEnvironment().get("Path")); + List paths = new ArrayList<>(); + for (String variable : cl.getEnvironmentVariables()) { + if (variable.regionMatches(true, 0, "PATH=", 0, 5)) { + paths.add(variable); + } + } + assertEquals(Collections.singletonList("Path=C:\\own"), paths); + } + + @Test + void toStringStaysTheShellForm() { + assertEquals( + "cmd.exe /X /D /C \"git status\"", + windowsCommandline("git", "status").toString()); + } + + // ---------------------------------------------------------------------- + // Windows only: real processes + // ---------------------------------------------------------------------- + + private static File javaExe() { + return new File(System.getProperty("java.home"), OS.WINDOWS.isCurrentOs() ? "bin\\java.exe" : "bin/java"); + } + + private static String testClasses() throws Exception { + return new File(ArgumentEcho.class + .getProtectionDomain() + .getCodeSource() + .getLocation() + .toURI()) + .getAbsolutePath(); + } + + private static String run(Commandline cl, int expectedExitCode) throws Exception { + CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer(); + CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); + int exitCode = CommandLineUtils.executeCommandLine(cl, out, err); + assertEquals(expectedExitCode, exitCode, err.getOutput()); + return out.getOutput(); + } + + private static String pathWith(Path dir) { + return dir + File.pathSeparator + System.getenv("PATH"); + } + + /** + * Runs everywhere, so that a failure on Windows is about Windows and not about the way the test starts Java. + */ + @Test + void exeReceivesShellMetacharactersLiterally() throws Exception { + String[] arguments = {"a&b", "x y", "%PATH%", "a|b", ">out", "^caret", "100%", "a&echo injected"}; + + Commandline cl = new Commandline(); + cl.setExecutable(javaExe().getAbsolutePath()); + cl.addArguments(new String[] {"-cp", testClasses(), ArgumentEcho.class.getName()}); + cl.addArguments(arguments); + + assertEquals(javaExe().getAbsolutePath(), cl.getCommandline()[0]); + String expected = String.join(System.lineSeparator(), arguments) + System.lineSeparator(); + assertEquals(expected, run(cl, 0)); + } + + @Test + @EnabledOnOs(OS.WINDOWS) + void exeIsFoundThroughPathAndPathext(@TempDir Path dir) throws Exception { + Files.copy(javaExe().toPath(), dir.resolve("plexus-utils-probe.exe")); + + Commandline cl = new Commandline(); + cl.addEnvironment("PATH", pathWith(dir)); + cl.setExecutable("plexus-utils-probe"); + + String[] commandline = cl.getCommandline(); + assertEquals(1, commandline.length); + assertTrue(new File(commandline[0]).isAbsolute(), commandline[0]); + assertTrue(commandline[0].toLowerCase(Locale.ROOT).endsWith("plexus-utils-probe.exe"), commandline[0]); + } + + /** + * plexus-utils#17 + */ + @Test + @EnabledOnOs(OS.WINDOWS) + void extensionlessScriptOnPathRunsThroughTheShell(@TempDir Path dir) throws Exception { + Files.write(dir.resolve("plexus-utils-shim.cmd"), "@echo shim %1\r\n".getBytes(StandardCharsets.US_ASCII)); + + Commandline cl = new Commandline(); + cl.addEnvironment("PATH", pathWith(dir)); + cl.setExecutable("plexus-utils-shim"); + cl.createArg().setValue("called"); + + assertEquals("cmd.exe", cl.getCommandline()[0]); + assertEquals("shim called", run(cl, 0).trim()); + } + + @Test + @EnabledOnOs(OS.WINDOWS) + void scriptInWorkingDirectoryRunsThroughTheShell(@TempDir Path dir) throws Exception { + Files.write(dir.resolve("plexus-utils-local.bat"), "@echo local\r\n".getBytes(StandardCharsets.US_ASCII)); + + Commandline cl = new Commandline(); + cl.setWorkingDirectory(dir.toFile()); + cl.setExecutable("plexus-utils-local"); + + assertEquals("cmd.exe", cl.getCommandline()[0]); + assertEquals("local", run(cl, 0).trim()); + } + + @Test + @EnabledOnOs(OS.WINDOWS) + void builtinRunsThroughTheShell() throws Exception { + Commandline cl = new Commandline(); + cl.setExecutable("echo"); + cl.createArg().setValue("Hello"); + + assertEquals("cmd.exe", cl.getCommandline()[0]); + assertEquals("Hello", run(cl, 0).trim()); + } + + @Test + @EnabledOnOs(OS.WINDOWS) + void unknownCommandIsReportedByTheShellNotByAnException() throws Exception { + Commandline cl = new Commandline(); + cl.setExecutable("plexus-utils-no-such-command"); + + assertEquals("cmd.exe", cl.getCommandline()[0]); + CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); + int exitCode = CommandLineUtils.executeCommandLine(cl, new CommandLineUtils.StringStreamConsumer(), err); + assertNotEquals(0, exitCode); + assertFalse(err.getOutput().isEmpty()); + } + + /** + * The direct start of a file that is no image fails; cmd.exe then reports it as it always did. + */ + @Test + @EnabledOnOs(OS.WINDOWS) + void failedDirectStartFallsBackToTheShell(@TempDir Path dir) throws Exception { + Path bogus = dir.resolve("plexus-utils-bogus.exe"); + Files.write(bogus, "not an image".getBytes(StandardCharsets.US_ASCII)); + + Commandline cl = new Commandline(); + cl.setExecutable(bogus.toString()); + + assertEquals(bogus.toString(), cl.getCommandline()[0]); + int exitCode = CommandLineUtils.executeCommandLine( + cl, new CommandLineUtils.StringStreamConsumer(), new CommandLineUtils.StringStreamConsumer()); + assertNotEquals(0, exitCode); + } + + @Test + @EnabledOnOs(OS.WINDOWS) + void callerCanStillAskForTheShell() throws Exception { + Commandline cl = new Commandline(); + cl.setShell(new CmdShell()); + cl.setExecutable(javaExe().getAbsolutePath()); + cl.addArguments(new String[] {"-cp", testClasses(), ArgumentEcho.class.getName(), "one&echo two"}); + + assertEquals("cmd.exe", cl.getCommandline()[0]); + // quoted because of the space, so cmd.exe leaves it alone + assertEquals("one&echo two", run(cl, 0).trim()); + + cl = new Commandline(); + cl.setShell(new CmdShell()); + cl.setExecutable(javaExe().getAbsolutePath()); + cl.addArguments(new String[] {"-cp", testClasses(), ArgumentEcho.class.getName(), "one&echo", "two"}); + // unquoted, cmd.exe treats & as a command separator: the behaviour direct execution removes + assertEquals("one" + System.lineSeparator() + "two", run(cl, 0).trim()); + } + + /** + * Prints each argument on a line of its own. + */ + public static final class ArgumentEcho { + public static void main(String[] args) { + for (String arg : args) { + System.out.println(arg); + } + } + } +} diff --git a/src/test/java/org/codehaus/plexus/util/cli/WindowsExecutableResolverTest.java b/src/test/java/org/codehaus/plexus/util/cli/WindowsExecutableResolverTest.java new file mode 100644 index 00000000..8a5def1c --- /dev/null +++ b/src/test/java/org/codehaus/plexus/util/cli/WindowsExecutableResolverTest.java @@ -0,0 +1,235 @@ +package org.codehaus.plexus.util.cli; + +/* + * Copyright The Codehaus Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; + +import org.codehaus.plexus.util.cli.WindowsExecutableResolver.Kind; +import org.codehaus.plexus.util.cli.WindowsExecutableResolver.Resolution; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Runs on every platform: the file system and the environment are faked. + */ +class WindowsExecutableResolverTest { + private static final String CWD = "C:\\work"; + + private final Map env = new HashMap<>(); + + private final Set files = new HashSet<>(); + + private final Predicate isFile = new Predicate() { + @Override + public boolean test(String path) { + // NTFS is case-insensitive + return files.contains(path.toLowerCase(Locale.ROOT)); + } + }; + + WindowsExecutableResolverTest() { + env.put("Path", "C:\\tools;C:\\Program Files (x86)\\Git\\cmd;"); + env.put("PATHEXT", ".COM;.EXE;.BAT;.CMD;.VBS"); + } + + private void file(String... paths) { + for (String path : paths) { + files.add(path.toLowerCase(Locale.ROOT)); + } + } + + private Resolution resolve(String executable) { + return WindowsExecutableResolver.resolve(executable, env, CWD, isFile); + } + + private void assertResolved(Kind kind, String path, String executable) { + Resolution resolution = resolve(executable); + assertEquals(kind, resolution.getKind(), executable); + // the extension comes from PATHEXT as written there, usually in upper case + String expected = path == null ? null : path.toLowerCase(Locale.ROOT); + String actual = + resolution.getPath() == null ? null : resolution.getPath().toLowerCase(Locale.ROOT); + assertEquals(expected, actual, executable); + } + + @Test + void extensionlessNameOnPathResolvesToExe() { + file("C:\\Program Files (x86)\\Git\\cmd\\git.exe"); + assertResolved(Kind.NATIVE, "C:\\Program Files (x86)\\Git\\cmd\\git.exe", "git"); + assertResolved(Kind.NATIVE, "C:\\Program Files (x86)\\Git\\cmd\\git.exe", "GIT.EXE"); + assertEquals( + "C:\\Program Files (x86)\\Git\\cmd\\git.EXE", resolve("git").getPath()); + assertEquals( + "C:\\Program Files (x86)\\Git\\cmd\\GIT.EXE", resolve("GIT.EXE").getPath()); + } + + @Test + void extensionlessNameOnPathResolvesToScript() { + // plexus-utils#17: mvn, npm and friends are .cmd shims + file("C:\\tools\\mvn.cmd", "C:\\tools\\npm.bat"); + assertResolved(Kind.SCRIPT, "C:\\tools\\mvn.cmd", "mvn"); + assertResolved(Kind.SCRIPT, "C:\\tools\\npm.bat", "npm"); + } + + @Test + void pathextOrderDecidesWithinOneDirectory() { + file("C:\\tools\\tool.exe", "C:\\tools\\tool.cmd", "C:\\tools\\tool.com"); + assertResolved(Kind.NATIVE, "C:\\tools\\tool.com", "tool"); + + env.put("PATHEXT", ".CMD;.EXE"); + assertResolved(Kind.SCRIPT, "C:\\tools\\tool.cmd", "tool"); + } + + @Test + void earlierDirectoryWinsOverEarlierExtension() { + file("C:\\tools\\tool.cmd", "C:\\Program Files (x86)\\Git\\cmd\\tool.exe"); + assertResolved(Kind.SCRIPT, "C:\\tools\\tool.cmd", "tool"); + } + + @Test + void workingDirectoryIsSearchedBeforePath() { + file("C:\\work\\tool.bat", "C:\\tools\\tool.exe"); + assertResolved(Kind.SCRIPT, "C:\\work\\tool.bat", "tool"); + + env.put("NoDefaultCurrentDirectoryInExePath", "1"); + assertResolved(Kind.NATIVE, "C:\\tools\\tool.exe", "tool"); + } + + @Test + void nameWithExtensionIsTriedAsGivenThenWithPathext() { + file("C:\\tools\\tool.exe.cmd"); + assertResolved(Kind.SCRIPT, "C:\\tools\\tool.exe.cmd", "tool.exe"); + + file("C:\\tools\\tool.exe"); + assertResolved(Kind.NATIVE, "C:\\tools\\tool.exe", "tool.exe"); + } + + @Test + void extensionlessFileIsNotACommand() { + file("C:\\tools\\tool"); + assertResolved(Kind.UNRESOLVED, null, "tool"); + } + + @Test + void otherFileTypesAreLeftToTheShell() { + file("C:\\tools\\report.vbs", "C:\\tools\\notes.txt"); + assertResolved(Kind.ASSOCIATED, "C:\\tools\\report.vbs", "report"); + assertResolved(Kind.ASSOCIATED, "C:\\tools\\notes.txt", "notes.txt"); + } + + @Test + void builtinsWinOverFiles() { + file("C:\\tools\\echo.exe", "C:\\tools\\dir.exe"); + for (String builtin : Arrays.asList("echo", "ECHO", "dir", "set", "cd", "copy", "type", "start")) { + assertResolved(Kind.BUILTIN, null, builtin); + } + // naming the file is how cmd.exe is told to run it + assertResolved(Kind.NATIVE, "C:\\tools\\echo.exe", "echo.exe"); + assertResolved(Kind.NATIVE, "C:\\tools\\echo.exe", "C:\\tools\\echo"); + } + + @Test + void pathGivenIsTheOnlyPlaceSearched() { + file("C:\\tools\\java.exe", "C:\\jdk\\bin\\java.exe", "C:\\work\\bin\\run.cmd", "\\\\server\\share\\x.exe"); + assertResolved(Kind.NATIVE, "C:\\jdk\\bin\\java.exe", "C:\\jdk\\bin\\java.exe"); + assertResolved(Kind.NATIVE, "C:\\jdk\\bin\\java.exe", "C:/jdk/bin/java"); + assertResolved(Kind.SCRIPT, "C:\\work\\bin\\run.cmd", "bin\\run"); + // the fake file system does not normalise paths + file("C:\\work\\.\\bin\\run.cmd"); + assertResolved(Kind.SCRIPT, "C:\\work\\.\\bin\\run.cmd", "./bin/run.cmd"); + assertResolved(Kind.NATIVE, "\\\\server\\share\\x.exe", "\\\\server\\share\\x"); + assertResolved(Kind.UNRESOLVED, null, "C:\\other\\java.exe"); + assertResolved(Kind.UNRESOLVED, null, "bin\\java"); + } + + @Test + void formsThatNeedMoreThanTheWorkingDirectoryAreUnresolved() { + file("C:\\work\\tool.exe", "C:\\tool.exe", "C:\\tools\\tool.exe"); + for (String executable : Arrays.asList("C:tool.exe", "\\tool.exe", "C:\\tools\\", "", " tool", "tool.")) { + assertResolved(Kind.UNRESOLVED, null, executable); + } + assertEquals( + Kind.UNRESOLVED, + WindowsExecutableResolver.resolve(null, env, CWD, isFile).getKind()); + assertEquals( + Kind.UNRESOLVED, + WindowsExecutableResolver.resolve("tool", env, null, isFile).getKind()); + assertEquals( + Kind.UNRESOLVED, + WindowsExecutableResolver.resolve("tool", env, "work", isFile).getKind()); + } + + @Test + void namesThatCmdInterpretsAreUnresolved() { + file("C:\\tools\\tool.exe", "C:\\tools\\a&b.exe", "C:\\tools\\%tool%.exe"); + for (String executable : Arrays.asList( + "\"C:\\tools\\tool.exe\"", + "\"tool\"", + "a&b", + "%tool%", + "%TOOLS%\\tool.exe", + "tool.exe>out", + "to*l", + "tool|more", + "^tool", + "tool;x", + "tool,x", + "tool=x")) { + assertResolved(Kind.UNRESOLVED, null, executable); + } + } + + @Test + void pathEntryThatCannotBeInterpretedStopsTheSearch() { + file("C:\\tools\\tool.exe"); + + env.put("Path", "C:\\first;\"C:\\quoted dir\";C:\\tools"); + assertResolved(Kind.UNRESOLVED, null, "tool"); + + env.put("Path", "\\rooted;C:\\tools"); + assertResolved(Kind.UNRESOLVED, null, "tool"); + + // but a hit before that entry is what cmd.exe finds as well + env.put("Path", "C:\\tools;D:relative"); + assertResolved(Kind.NATIVE, "C:\\tools\\tool.exe", "tool"); + } + + @Test + void relativeAndEmptyPathEntries() { + file("C:\\work\\bin\\tool.exe"); + env.put("Path", ";; bin ;"); + assertResolved(Kind.NATIVE, "C:\\work\\bin\\tool.exe", "tool"); + } + + @Test + void environmentDefaults() { + file("C:\\work\\tool.cmd", "C:\\work\\other.vbs"); + env.clear(); + assertResolved(Kind.SCRIPT, "C:\\work\\tool.cmd", "tool"); + // .VBS is not in the default PATHEXT + assertResolved(Kind.UNRESOLVED, null, "other"); + assertNull(resolve("missing").getPath()); + } +}