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