1 /* 2 * Copyright (c) 2010, 2015, 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 jdk.nashorn.internal.runtime; 27 28 import static jdk.nashorn.internal.lookup.Lookup.MH; 29 import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; 30 import static jdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED; 31 32 import java.io.BufferedReader; 33 import java.io.File; 34 import java.io.IOException; 35 import java.io.InputStreamReader; 36 import java.io.OutputStreamWriter; 37 import java.io.StreamTokenizer; 38 import java.io.StringReader; 39 import java.lang.invoke.MethodHandle; 40 import java.lang.invoke.MethodHandles; 41 import java.util.ArrayList; 42 import java.util.List; 43 import java.util.Map; 44 45 /** 46 * Global functions supported only in scripting mode. 47 */ 48 public final class ScriptingFunctions { 49 50 /** Handle to implementation of {@link ScriptingFunctions#readLine} - Nashorn extension */ 51 public static final MethodHandle READLINE = findOwnMH("readLine", Object.class, Object.class, Object.class); 52 53 /** Handle to implementation of {@link ScriptingFunctions#readFully} - Nashorn extension */ 54 public static final MethodHandle READFULLY = findOwnMH("readFully", Object.class, Object.class, Object.class); 55 56 /** Handle to implementation of {@link ScriptingFunctions#exec} - Nashorn extension */ 57 public static final MethodHandle EXEC = findOwnMH("exec", Object.class, Object.class, Object.class, Object.class); 58 59 /** EXEC name - special property used by $EXEC API. */ 60 public static final String EXEC_NAME = "$EXEC"; 61 62 /** OUT name - special property used by $EXEC API. */ 63 public static final String OUT_NAME = "$OUT"; 64 65 /** ERR name - special property used by $EXEC API. */ 66 public static final String ERR_NAME = "$ERR"; 67 68 /** EXIT name - special property used by $EXEC API. */ 69 public static final String EXIT_NAME = "$EXIT"; 70 71 /** Names of special properties used by $ENV API. */ 72 public static final String ENV_NAME = "$ENV"; 73 74 private static final String PWD_NAME = "PWD"; 75 76 private ScriptingFunctions() { 77 } 78 79 /** 80 * Nashorn extension: global.readLine (scripting-mode-only) 81 * Read one line of input from the standard input. 82 * 83 * @param self self reference 84 * @param prompt String used as input prompt 85 * 86 * @return line that was read 87 * 88 * @throws IOException if an exception occurs 89 */ 90 public static Object readLine(final Object self, final Object prompt) throws IOException { 91 if (prompt != UNDEFINED) { 92 System.out.print(JSType.toString(prompt)); 93 } 94 final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 95 return reader.readLine(); 96 } 97 98 /** 99 * Nashorn extension: Read the entire contents of a text file and return as String. 100 * 101 * @param self self reference 102 * @param file The input file whose content is read. 103 * 104 * @return String content of the input file. 105 * 106 * @throws IOException if an exception occurs 107 */ 108 public static Object readFully(final Object self, final Object file) throws IOException { 109 File f = null; 110 111 if (file instanceof File) { 112 f = (File)file; 113 } else if (JSType.isString(file)) { 114 f = new java.io.File(((CharSequence)file).toString()); 115 } 116 117 if (f == null || !f.isFile()) { 118 throw typeError("not.a.file", ScriptRuntime.safeToString(file)); 119 } 120 121 return new String(Source.readFully(f)); 122 } 123 124 /** 125 * Nashorn extension: exec a string in a separate process. 126 * 127 * @param self self reference 128 * @param string string to execute 129 * @param input input 130 * 131 * @return output string from the request 132 * @throws IOException if any stream access fails 133 * @throws InterruptedException if execution is interrupted 134 */ 135 public static Object exec(final Object self, final Object string, final Object input) throws IOException, InterruptedException { 136 // Current global is need to fetch additional inputs and for additional results. 137 final ScriptObject global = Context.getGlobal(); 138 139 // Set up initial process. 140 final ProcessBuilder processBuilder = new ProcessBuilder(tokenizeCommandLine(JSType.toString(string))); 141 142 // Current ENV property state. 143 final Object env = global.get(ENV_NAME); 144 if (env instanceof ScriptObject) { 145 final ScriptObject envProperties = (ScriptObject)env; 146 147 // If a working directory is present, use it. 148 final Object pwd = envProperties.get(PWD_NAME); 149 if (pwd != UNDEFINED) { 150 processBuilder.directory(new File(JSType.toString(pwd))); 151 } 152 153 // Set up ENV variables. 154 final Map<String, String> environment = processBuilder.environment(); 155 environment.clear(); 156 for (final Map.Entry<Object, Object> entry : envProperties.entrySet()) { 157 environment.put(JSType.toString(entry.getKey()), JSType.toString(entry.getValue())); 158 } 159 } 160 161 // Start the process. 162 final Process process = processBuilder.start(); 163 final IOException exception[] = new IOException[2]; 164 165 // Collect output. 166 final StringBuilder outBuffer = new StringBuilder(); 167 final Thread outThread = new Thread(new Runnable() { 168 @Override 169 public void run() { 170 final char buffer[] = new char[1024]; 171 try (final InputStreamReader inputStream = new InputStreamReader(process.getInputStream())) { 172 for (int length; (length = inputStream.read(buffer, 0, buffer.length)) != -1; ) { 173 outBuffer.append(buffer, 0, length); 174 } 175 } catch (final IOException ex) { 176 exception[0] = ex; 177 } 178 } 179 }, "$EXEC output"); 180 181 // Collect errors. 182 final StringBuilder errBuffer = new StringBuilder(); 183 final Thread errThread = new Thread(new Runnable() { 184 @Override 185 public void run() { 186 final char buffer[] = new char[1024]; 187 try (final InputStreamReader inputStream = new InputStreamReader(process.getErrorStream())) { 188 for (int length; (length = inputStream.read(buffer, 0, buffer.length)) != -1; ) { 189 errBuffer.append(buffer, 0, length); 190 } 191 } catch (final IOException ex) { 192 exception[1] = ex; 193 } 194 } 195 }, "$EXEC error"); 196 197 // Start gathering output. 198 outThread.start(); 199 errThread.start(); 200 201 // If input is present, pass on to process. 202 try (OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream())) { 203 if (input != UNDEFINED) { 204 final String in = JSType.toString(input); 205 outputStream.write(in, 0, in.length()); 206 } 207 } catch (final IOException ex) { 208 // Process was not expecting input. May be normal state of affairs. 209 } 210 211 // Wait for the process to complete. 212 final int exit = process.waitFor(); 213 outThread.join(); 214 errThread.join(); 215 216 final String out = outBuffer.toString(); 217 final String err = errBuffer.toString(); 218 219 // Set globals for secondary results. 220 global.set(OUT_NAME, out, 0); 221 global.set(ERR_NAME, err, 0); 222 global.set(EXIT_NAME, exit, 0); 223 224 // Propagate exception if present. 225 for (final IOException element : exception) { 226 if (element != null) { 227 throw element; 228 } 229 } 230 231 // Return the result from stdout. 232 return out; 233 } 234 235 private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) { 236 return MH.findStatic(MethodHandles.lookup(), ScriptingFunctions.class, name, MH.type(rtype, types)); 237 } 238 239 /** 240 * Break an exec string into tokens, honoring quoted arguments and escaped 241 * spaces. 242 * 243 * @param execString a {@link String} with the command line to execute. 244 * @return a {@link List} of {@link String}s representing the tokens that 245 * constitute the command line. 246 * @throws IOException in case {@link StreamTokenizer#nextToken()} raises it. 247 */ 248 public static List<String> tokenizeCommandLine(final String execString) throws IOException { 249 final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(execString)); 250 tokenizer.resetSyntax(); 251 tokenizer.wordChars(0, 255); 252 tokenizer.whitespaceChars(0, ' '); 253 tokenizer.commentChar('#'); 254 tokenizer.quoteChar('"'); 255 tokenizer.quoteChar('\''); 256 final List<String> cmdList = new ArrayList<>(); 257 final StringBuilder toAppend = new StringBuilder(); 258 while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) { 259 final String s = tokenizer.sval; 260 // The tokenizer understands about honoring quoted strings and recognizes 261 // them as one token that possibly contains multiple space-separated words. 262 // It does not recognize quoted spaces, though, and will split after the 263 // escaping \ character. This is handled here. 264 if (s.endsWith("\\")) { 265 // omit trailing \, append space instead 266 toAppend.append(s.substring(0, s.length() - 1)).append(' '); 267 } else { 268 cmdList.add(toAppend.append(s).toString()); 269 toAppend.setLength(0); 270 } 271 } 272 if (toAppend.length() != 0) { 273 cmdList.add(toAppend.toString()); 274 } 275 return cmdList; 276 } 277 }