1 /* 2 * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 import java.io.IOException; 29 import java.io.File; 30 import java.io.InputStream; 31 import java.io.OutputStream; 32 import java.io.FileInputStream; 33 import java.io.FileOutputStream; 34 import java.io.FileDescriptor; 35 import java.io.BufferedInputStream; 36 import java.io.BufferedOutputStream; 37 import java.lang.ProcessBuilder.Redirect; 38 import java.security.AccessController; 39 import java.security.PrivilegedAction; 40 import java.util.ArrayList; 41 import java.util.concurrent.TimeUnit; 42 import java.util.regex.Matcher; 43 import java.util.regex.Pattern; 44 45 /* This class is for the exclusive use of ProcessBuilder.start() to 46 * create new processes. 47 * 48 * @author Martin Buchholz 49 * @since 1.5 50 */ 51 52 final class ProcessImpl extends Process { 53 private static final sun.misc.JavaIOFileDescriptorAccess fdAccess 54 = sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess(); 55 56 /** 57 * Open a file for writing. If {@code append} is {@code true} then the file 58 * is opened for atomic append directly and a FileOutputStream constructed 59 * with the resulting handle. This is because a FileOutputStream created 60 * to append to a file does not open the file in a manner that guarantees 61 * that writes by the child process will be atomic. 62 */ 63 private static FileOutputStream newFileOutputStream(File f, boolean append) 64 throws IOException 65 { 66 if (append) { 67 String path = f.getPath(); 68 SecurityManager sm = System.getSecurityManager(); 69 if (sm != null) 70 sm.checkWrite(path); 71 long handle = openForAtomicAppend(path); 72 final FileDescriptor fd = new FileDescriptor(); 73 fdAccess.setHandle(fd, handle); 74 return AccessController.doPrivileged( 75 new PrivilegedAction<FileOutputStream>() { 76 public FileOutputStream run() { 77 return new FileOutputStream(fd); 78 } 79 } 80 ); 81 } else { 82 return new FileOutputStream(f); 83 } 84 } 85 86 // System-dependent portion of ProcessBuilder.start() 87 static Process start(String cmdarray[], 88 java.util.Map<String,String> environment, 89 String dir, 90 ProcessBuilder.Redirect[] redirects, 91 boolean redirectErrorStream) 92 throws IOException 93 { 94 String envblock = ProcessEnvironment.toEnvironmentBlock(environment); 95 96 FileInputStream f0 = null; 97 FileOutputStream f1 = null; 98 FileOutputStream f2 = null; 99 100 try { 101 long[] stdHandles; 102 if (redirects == null) { 103 stdHandles = new long[] { -1L, -1L, -1L }; 104 } else { 105 stdHandles = new long[3]; 106 107 if (redirects[0] == Redirect.PIPE) 108 stdHandles[0] = -1L; 109 else if (redirects[0] == Redirect.INHERIT) 110 stdHandles[0] = fdAccess.getHandle(FileDescriptor.in); 111 else { 112 f0 = new FileInputStream(redirects[0].file()); 113 stdHandles[0] = fdAccess.getHandle(f0.getFD()); 114 } 115 116 if (redirects[1] == Redirect.PIPE) 117 stdHandles[1] = -1L; 118 else if (redirects[1] == Redirect.INHERIT) 119 stdHandles[1] = fdAccess.getHandle(FileDescriptor.out); 120 else { 121 f1 = newFileOutputStream(redirects[1].file(), 122 redirects[1].append()); 123 stdHandles[1] = fdAccess.getHandle(f1.getFD()); 124 } 125 126 if (redirects[2] == Redirect.PIPE) 127 stdHandles[2] = -1L; 128 else if (redirects[2] == Redirect.INHERIT) 129 stdHandles[2] = fdAccess.getHandle(FileDescriptor.err); 130 else { 131 f2 = newFileOutputStream(redirects[2].file(), 132 redirects[2].append()); 133 stdHandles[2] = fdAccess.getHandle(f2.getFD()); 134 } 135 } 136 137 return new ProcessImpl(cmdarray, envblock, dir, 138 stdHandles, redirectErrorStream); 139 } finally { 140 // In theory, close() can throw IOException 141 // (although it is rather unlikely to happen here) 142 try { if (f0 != null) f0.close(); } 143 finally { 144 try { if (f1 != null) f1.close(); } 145 finally { if (f2 != null) f2.close(); } 146 } 147 } 148 149 } 150 151 private static class LazyPattern { 152 // Escape-support version: 153 // "(\")((?:\\\\\\1|.)+?)\\1|([^\\s\"]+)"; 154 private static final Pattern PATTERN = 155 Pattern.compile("[^\\s\"]+|\"[^\"]*\""); 156 }; 157 158 /* Parses the command string parameter into the executable name and 159 * program arguments. 160 * 161 * The command string is broken into tokens. The token separator is a space 162 * or quota character. The space inside quotation is not a token separator. 163 * There are no escape sequences. 164 */ 165 private static String[] getTokensFromCommand(String command) { 166 ArrayList<String> matchList = new ArrayList<>(8); 167 Matcher regexMatcher = LazyPattern.PATTERN.matcher(command); 168 while (regexMatcher.find()) 169 matchList.add(regexMatcher.group()); 170 return matchList.toArray(new String[matchList.size()]); 171 } 172 173 private static String createCommandLine(boolean isCmdFile, 174 final String executablePath, 175 final String cmd[]) 176 { 177 StringBuilder cmdbuf = new StringBuilder(80); 178 179 cmdbuf.append(executablePath); 180 181 for (int i = 1; i < cmd.length; ++i) { 182 cmdbuf.append(' '); 183 String s = cmd[i]; 184 if (needsEscaping(isCmdFile, s)) { 185 cmdbuf.append('"'); 186 cmdbuf.append(s); 187 188 // The code protects the [java.exe] and console command line 189 // parser, that interprets the [\"] combination as an escape 190 // sequence for the ["] char. 191 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx 192 // 193 // If the argument is an FS path, doubling of the tail [\] 194 // char is not a problem for non-console applications. 195 // 196 // The [\"] sequence is not an escape sequence for the [cmd.exe] 197 // command line parser. The case of the [""] tail escape 198 // sequence could not be realized due to the argument validation 199 // procedure. 200 if (!isCmdFile && s.endsWith("\\")) { 201 cmdbuf.append('\\'); 202 } 203 cmdbuf.append('"'); 204 } else { 205 cmdbuf.append(s); 206 } 207 } 208 return cmdbuf.toString(); 209 } 210 211 // We guarantee the only command file execution for implicit [cmd.exe] run. 212 // http://technet.microsoft.com/en-us/library/bb490954.aspx 213 private static final char CMD_BAT_ESCAPE[] = {' ', '\t', '<', '>', '&', '|', '^'}; 214 private static final char WIN32_EXECUTABLE_ESCAPE[] = {' ', '\t', '<', '>'}; 215 216 private static boolean isQuoted(boolean noQuotesInside, String arg, 217 String errorMessage) { 218 int lastPos = arg.length() - 1; 219 if (lastPos >=1 && arg.charAt(0) == '"' && arg.charAt(lastPos) == '"') { 220 // The argument has already been quoted. 221 if (noQuotesInside) { 222 if (arg.indexOf('"', 1) != lastPos) { 223 // There is ["] inside. 224 throw new IllegalArgumentException(errorMessage); 225 } 226 } 227 return true; 228 } 229 if (noQuotesInside) { 230 if (arg.indexOf('"') >= 0) { 231 // There is ["] inside. 232 throw new IllegalArgumentException(errorMessage); 233 } 234 } 235 return false; 236 } 237 238 private static boolean needsEscaping(boolean isCmdFile, String arg) { 239 // Switch off MS heuristic for internal ["]. 240 // Please, use the explicit [cmd.exe] call 241 // if you need the internal ["]. 242 // Example: "cmd.exe", "/C", "Extended_MS_Syntax" 243 244 // For [.exe] or [.com] file the unpaired/internal ["] 245 // in the argument is not a problem. 246 boolean argIsQuoted = isQuoted(isCmdFile, arg, 247 "Argument has embedded quote, use the explicit CMD.EXE call."); 248 249 if (!argIsQuoted) { 250 char testEscape[] = isCmdFile 251 ? CMD_BAT_ESCAPE 252 : WIN32_EXECUTABLE_ESCAPE; 253 for (int i = 0; i < testEscape.length; ++i) { 254 if (arg.indexOf(testEscape[i]) >= 0) { 255 return true; 256 } 257 } 258 } 259 return false; 260 } 261 262 private static String getExecutablePath(String path) 263 throws IOException 264 { 265 boolean pathIsQuoted = isQuoted(true, path, 266 "Executable name has embedded quote, split the arguments"); 267 268 // Win32 CreateProcess requires path to be normalized 269 File fileToRun = new File(pathIsQuoted 270 ? path.substring(1, path.length() - 1) 271 : path); 272 273 // From the [CreateProcess] function documentation: 274 // 275 // "If the file name does not contain an extension, .exe is appended. 276 // Therefore, if the file name extension is .com, this parameter 277 // must include the .com extension. If the file name ends in 278 // a period (.) with no extension, or if the file name contains a path, 279 // .exe is not appended." 280 // 281 // "If the file name !does not contain a directory path!, 282 // the system searches for the executable file in the following 283 // sequence:..." 284 // 285 // In practice ANY non-existent path is extended by [.exe] extension 286 // in the [CreateProcess] funcion with the only exception: 287 // the path ends by (.) 288 289 return fileToRun.getPath(); 290 } 291 292 293 private boolean isShellFile(String executablePath) { 294 String upPath = executablePath.toUpperCase(); 295 return (upPath.endsWith(".CMD") || upPath.endsWith(".BAT")); 296 } 297 298 private String quoteString(String arg) { 299 StringBuilder argbuf = new StringBuilder(arg.length() + 2); 300 return argbuf.append('"').append(arg).append('"').toString(); 301 } 302 303 304 private long handle = 0; 305 private OutputStream stdin_stream; 306 private InputStream stdout_stream; 307 private InputStream stderr_stream; 308 309 private ProcessImpl(String cmd[], 310 final String envblock, 311 final String path, 312 final long[] stdHandles, 313 final boolean redirectErrorStream) 314 throws IOException 315 { 316 String cmdstr; 317 SecurityManager security = System.getSecurityManager(); 318 boolean allowAmbigousCommands = false; 319 if (security == null) { 320 String value = System.getProperty("jdk.lang.Process.allowAmbigousCommands"); 321 if (value != null) 322 allowAmbigousCommands = !"false".equalsIgnoreCase(value); 323 } 324 if (allowAmbigousCommands) { 325 // Legacy mode. 326 327 // Normalize path if possible. 328 String executablePath = new File(cmd[0]).getPath(); 329 330 // No worry about internal and unpaired ["] . 331 if (needsEscaping(false, executablePath) ) 332 executablePath = quoteString(executablePath); 333 334 cmdstr = createCommandLine( 335 false, //legacy mode doesn't worry about extended verification 336 executablePath, 337 cmd); 338 } else { 339 String executablePath; 340 try { 341 executablePath = getExecutablePath(cmd[0]); 342 } catch (IllegalArgumentException e) { 343 // Workaround for the calls like 344 // Runtime.getRuntime().exec("\"C:\\Program Files\\foo\" bar") 345 346 // No chance to avoid CMD/BAT injection, except to do the work 347 // right from the beginning. Otherwise we have too many corner 348 // cases from 349 // Runtime.getRuntime().exec(String[] cmd [, ...]) 350 // calls with internal ["] and escape sequences. 351 352 // Restore original command line. 353 StringBuilder join = new StringBuilder(); 354 // terminal space in command line is ok 355 for (String s : cmd) 356 join.append(s).append(' '); 357 358 // Parse the command line again. 359 cmd = getTokensFromCommand(join.toString()); 360 executablePath = getExecutablePath(cmd[0]); 361 362 // Check new executable name once more 363 if (security != null) 364 security.checkExec(executablePath); 365 } 366 367 // Quotation protects from interpretation of the [path] argument as 368 // start of longer path with spaces. Quotation has no influence to 369 // [.exe] extension heuristic. 370 cmdstr = createCommandLine( 371 // We need the extended verification procedure for CMD files. 372 isShellFile(executablePath), 373 quoteString(executablePath), 374 cmd); 375 } 376 377 handle = create(cmdstr, envblock, path, 378 stdHandles, redirectErrorStream); 379 380 java.security.AccessController.doPrivileged( 381 new java.security.PrivilegedAction<Void>() { 382 public Void run() { 383 if (stdHandles[0] == -1L) 384 stdin_stream = ProcessBuilder.NullOutputStream.INSTANCE; 385 else { 386 FileDescriptor stdin_fd = new FileDescriptor(); 387 fdAccess.setHandle(stdin_fd, stdHandles[0]); 388 stdin_stream = new BufferedOutputStream( 389 new FileOutputStream(stdin_fd)); 390 } 391 392 if (stdHandles[1] == -1L) 393 stdout_stream = ProcessBuilder.NullInputStream.INSTANCE; 394 else { 395 FileDescriptor stdout_fd = new FileDescriptor(); 396 fdAccess.setHandle(stdout_fd, stdHandles[1]); 397 stdout_stream = new BufferedInputStream( 398 new FileInputStream(stdout_fd)); 399 } 400 401 if (stdHandles[2] == -1L) 402 stderr_stream = ProcessBuilder.NullInputStream.INSTANCE; 403 else { 404 FileDescriptor stderr_fd = new FileDescriptor(); 405 fdAccess.setHandle(stderr_fd, stdHandles[2]); 406 stderr_stream = new FileInputStream(stderr_fd); 407 } 408 409 return null; }}); 410 } 411 412 public OutputStream getOutputStream() { 413 return stdin_stream; 414 } 415 416 public InputStream getInputStream() { 417 return stdout_stream; 418 } 419 420 public InputStream getErrorStream() { 421 return stderr_stream; 422 } 423 424 protected void finalize() { 425 closeHandle(handle); 426 } 427 428 private static final int STILL_ACTIVE = getStillActive(); 429 private static native int getStillActive(); 430 431 public int exitValue() { 432 int exitCode = getExitCodeProcess(handle); 433 if (exitCode == STILL_ACTIVE) 434 throw new IllegalThreadStateException("process has not exited"); 435 return exitCode; 436 } 437 private static native int getExitCodeProcess(long handle); 438 439 public int waitFor() throws InterruptedException { 440 waitForInterruptibly(handle); 441 if (Thread.interrupted()) 442 throw new InterruptedException(); 443 return exitValue(); 444 } 445 446 private static native void waitForInterruptibly(long handle); 447 448 @Override 449 public boolean waitFor(long timeout, TimeUnit unit) 450 throws InterruptedException 451 { 452 if (getExitCodeProcess(handle) != STILL_ACTIVE) return true; 453 if (timeout <= 0) return false; 454 455 long msTimeout = unit.toMillis(timeout); 456 457 waitForTimeoutInterruptibly(handle, msTimeout); 458 if (Thread.interrupted()) 459 throw new InterruptedException(); 460 return (getExitCodeProcess(handle) != STILL_ACTIVE); 461 } 462 463 private static native void waitForTimeoutInterruptibly( 464 long handle, long timeout); 465 466 public void destroy() { terminateProcess(handle); } 467 468 @Override 469 public Process destroyForcibly() { 470 destroy(); 471 return this; 472 } 473 474 private static native void terminateProcess(long handle); 475 476 @Override 477 public boolean isAlive() { 478 return isProcessAlive(handle); 479 } 480 481 private static native boolean isProcessAlive(long handle); 482 483 /** 484 * Create a process using the win32 function CreateProcess. 485 * 486 * @param cmdstr the Windows commandline 487 * @param envblock NUL-separated, double-NUL-terminated list of 488 * environment strings in VAR=VALUE form 489 * @param dir the working directory of the process, or null if 490 * inheriting the current directory from the parent process 491 * @param stdHandles array of windows HANDLEs. Indexes 0, 1, and 492 * 2 correspond to standard input, standard output and 493 * standard error, respectively. On input, a value of -1 494 * means to create a pipe to connect child and parent 495 * processes. On output, a value which is not -1 is the 496 * parent pipe handle corresponding to the pipe which has 497 * been created. An element of this array is -1 on input 498 * if and only if it is <em>not</em> -1 on output. 499 * @param redirectErrorStream redirectErrorStream attribute 500 * @return the native subprocess HANDLE returned by CreateProcess 501 */ 502 private static native long create(String cmdstr, 503 String envblock, 504 String dir, 505 long[] stdHandles, 506 boolean redirectErrorStream) 507 throws IOException; 508 509 /** 510 * Opens a file for atomic append. The file is created if it doesn't 511 * already exist. 512 * 513 * @param file the file to open or create 514 * @return the native HANDLE 515 */ 516 private static native long openForAtomicAppend(String path) 517 throws IOException; 518 519 private static native boolean closeHandle(long handle); 520 }