|
| 1 | +/* |
| 2 | + * Copyright 2003-2009 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package hudson.plugins.emailext.groovy.sandbox; |
| 17 | + |
| 18 | +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; |
| 19 | +import groovy.lang.Binding; |
| 20 | +import groovy.lang.GroovyRuntimeException; |
| 21 | +import groovy.lang.GroovyShell; |
| 22 | +import groovy.lang.MissingPropertyException; |
| 23 | +import groovy.lang.Script; |
| 24 | +import groovy.lang.Writable; |
| 25 | +import groovy.text.Template; |
| 26 | +import groovy.text.TemplateEngine; |
| 27 | +import hudson.plugins.emailext.plugins.content.ScriptContent; |
| 28 | +import jenkins.util.SystemProperties; |
| 29 | +import org.codehaus.groovy.control.CompilationFailedException; |
| 30 | +import org.codehaus.groovy.runtime.InvokerHelper; |
| 31 | +import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox; |
| 32 | + |
| 33 | +import java.io.BufferedReader; |
| 34 | +import java.io.IOException; |
| 35 | +import java.io.PrintWriter; |
| 36 | +import java.io.Reader; |
| 37 | +import java.io.StringWriter; |
| 38 | +import java.io.Writer; |
| 39 | +import java.util.Map; |
| 40 | +import java.util.concurrent.atomic.AtomicInteger; |
| 41 | +import java.util.logging.Level; |
| 42 | +import java.util.logging.Logger; |
| 43 | + |
| 44 | +/** |
| 45 | + * Processes template source files substituting variables and expressions into |
| 46 | + * placeholders in a template source text to produce the desired output. |
| 47 | + * <p> |
| 48 | + * The template engine uses JSP style <% %> script and <%= %> expression syntax |
| 49 | + * or GString style expressions. The variable '<code>out</code>' is bound to the writer that the template |
| 50 | + * is being written to. |
| 51 | + * <p> |
| 52 | + * Frequently, the template source will be in a file but here is a simple |
| 53 | + * example providing the template as a string: |
| 54 | + * <pre> |
| 55 | + * def binding = [ |
| 56 | + * firstname : "Grace", |
| 57 | + * lastname : "Hopper", |
| 58 | + * accepted : true, |
| 59 | + * title : 'Groovy for COBOL programmers' |
| 60 | + * ] |
| 61 | + * def engine = new groovy.text.SimpleTemplateEngine() |
| 62 | + * def text = '''\ |
| 63 | + * Dear <%= firstname %> $lastname, |
| 64 | + * |
| 65 | + * We <% if (accepted) print 'are pleased' else print 'regret' %> \ |
| 66 | + * to inform you that your paper entitled |
| 67 | + * '$title' was ${ accepted ? 'accepted' : 'rejected' }. |
| 68 | + * |
| 69 | + * The conference committee. |
| 70 | + * ''' |
| 71 | + * def template = engine.createTemplate(text).make(binding) |
| 72 | + * println template.toString() |
| 73 | + * </pre> |
| 74 | + * This example uses a mix of the JSP style and GString style placeholders |
| 75 | + * but you can typically use just one style if you wish. Running this |
| 76 | + * example will produce this output: |
| 77 | + * <pre> |
| 78 | + * Dear Grace Hopper, |
| 79 | + * |
| 80 | + * We are pleased to inform you that your paper entitled |
| 81 | + * 'Groovy for COBOL programmers' was accepted. |
| 82 | + * |
| 83 | + * The conference committee. |
| 84 | + * </pre> |
| 85 | + * The template engine can also be used as the engine for {@link groovy.servlet.TemplateServlet} by placing the |
| 86 | + * following in your <code>web.xml</code> file (plus a corresponding servlet-mapping element): |
| 87 | + * <pre> |
| 88 | + * <servlet> |
| 89 | + * <servlet-name>SimpleTemplate</servlet-name> |
| 90 | + * <servlet-class>groovy.servlet.TemplateServlet</servlet-class> |
| 91 | + * <init-param> |
| 92 | + * <param-name>template.engine</param-name> |
| 93 | + * <param-value>groovy.text.SimpleTemplateEngine</param-value> |
| 94 | + * </init-param> |
| 95 | + * </servlet> |
| 96 | + * </pre> |
| 97 | + * In this case, your template source file should be HTML with the appropriate embedded placeholders. |
| 98 | + * |
| 99 | + * @author sam |
| 100 | + * @author Christian Stein |
| 101 | + * @author Paul King |
| 102 | + * @author Alex Tkachman |
| 103 | + */ |
| 104 | +public class SimpleTemplateEngine extends TemplateEngine { |
| 105 | + |
| 106 | + private static final Logger LOGGER = Logger.getLogger(SimpleTemplateEngine.class.getName()); |
| 107 | + |
| 108 | + /** |
| 109 | + * Maximum size of template expansion we expect to produce. |
| 110 | + * Unit: bytes |
| 111 | + * Default: 1MB |
| 112 | + */ |
| 113 | + // public for testing |
| 114 | + @SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "non final to make it editable from the script console (convenient to temporarily change the value without restarting)") |
| 115 | + public static int MAX_EXPANDED_SIZE_BYTES = SystemProperties.getInteger(SimpleTemplateEngine.class.getName() + ".MAX_EXPANDED_SIZE_BYTES", 1024 * 1024); |
| 116 | + |
| 117 | + private static AtomicInteger counter = new AtomicInteger(1); |
| 118 | + |
| 119 | + protected final GroovyShell groovyShell; |
| 120 | + private final boolean sandbox; |
| 121 | + |
| 122 | + public SimpleTemplateEngine(GroovyShell groovyShell, boolean sandbox) { |
| 123 | + this.groovyShell = groovyShell; |
| 124 | + this.sandbox = sandbox; |
| 125 | + } |
| 126 | + |
| 127 | + public Template createTemplate(Reader reader) throws CompilationFailedException, IOException { |
| 128 | + return createTemplate(reader,"SimpleTemplateScript" + counter.getAndIncrement() + ".groovy"); |
| 129 | + } |
| 130 | + |
| 131 | + public Template createTemplate(Reader reader, String fileName) throws CompilationFailedException, IOException { |
| 132 | + SimpleTemplate template = new SimpleTemplate(sandbox); |
| 133 | + template.script = parseScript(reader,fileName); |
| 134 | + return template; |
| 135 | + } |
| 136 | + |
| 137 | + protected Script parseScript(Reader reader, String fileName) throws CompilationFailedException, IOException { |
| 138 | + String script = parse(reader); |
| 139 | + if (LOGGER.isLoggable(Level.FINE)) { |
| 140 | + LOGGER.fine("\n-- script source --"); |
| 141 | + LOGGER.fine(script); |
| 142 | + LOGGER.fine("\n-- script end --\n"); |
| 143 | + } |
| 144 | + try (GroovySandbox.Scope scope = new GroovySandbox().enter()) { |
| 145 | + return groovyShell.parse(script, fileName); |
| 146 | + } catch (Exception e) { |
| 147 | + throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e, e); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + private static class SimpleTemplate implements Template { |
| 152 | + |
| 153 | + private final boolean sandbox; |
| 154 | + |
| 155 | + SimpleTemplate(boolean sandbox) { |
| 156 | + this.sandbox = sandbox; |
| 157 | + } |
| 158 | + |
| 159 | + protected Script script; |
| 160 | + |
| 161 | + public Writable make() { |
| 162 | + return make(null); |
| 163 | + } |
| 164 | + |
| 165 | + public Writable make(final Map map) { |
| 166 | + return new Writable() { |
| 167 | + /** |
| 168 | + * Write the template document with the set binding applied to the writer. |
| 169 | + * |
| 170 | + * @see groovy.lang.Writable#writeTo(java.io.Writer) |
| 171 | + */ |
| 172 | + @Override public Writer writeTo(Writer writer) throws IOException { |
| 173 | + Binding binding; |
| 174 | + if (map == null) |
| 175 | + binding = new Binding(); |
| 176 | + else |
| 177 | + binding = new Binding(map); |
| 178 | + PrintWriter pw = new PrintWriter(writer); |
| 179 | + try { |
| 180 | + if (sandbox) { |
| 181 | + // Cannot use normal GroovySandbox.runScript here because template preparation was separated. |
| 182 | + try (GroovySandbox.Scope scope = new GroovySandbox().enter()) { |
| 183 | + final Script scriptObject = InvokerHelper.createScript(script.getClass(), binding); |
| 184 | + scriptObject.setProperty("out", pw); |
| 185 | + scriptObject.run(); |
| 186 | + } |
| 187 | + } else { |
| 188 | + final Script scriptObject = InvokerHelper.createScript(script.getClass(), binding); |
| 189 | + scriptObject.setProperty("out", pw); |
| 190 | + scriptObject.run(); |
| 191 | + } |
| 192 | + } catch (MissingPropertyException x) { |
| 193 | + throw (IOException) new IOException("did you forget to escape \\$" + x.getProperty() + " for non-Groovy variables?").initCause(x); |
| 194 | + } |
| 195 | + pw.flush(); |
| 196 | + return writer; |
| 197 | + } |
| 198 | + |
| 199 | + /** |
| 200 | + * Convert the template and binding into a result String. |
| 201 | + * |
| 202 | + * @see java.lang.Object#toString() |
| 203 | + */ |
| 204 | + public String toString() { |
| 205 | + StringWriter sw = new StringWriter(); |
| 206 | + try { |
| 207 | + writeTo(sw); |
| 208 | + } catch (IOException x) { |
| 209 | + PrintWriter pw = new PrintWriter(sw); |
| 210 | + x.printStackTrace(pw); |
| 211 | + pw.flush(); |
| 212 | + } |
| 213 | + return sw.toString(); |
| 214 | + } |
| 215 | + }; |
| 216 | + } |
| 217 | + } |
| 218 | + |
| 219 | + /** |
| 220 | + * Parse the text document looking for {@code <%} or {@code <%=} and then call out to the appropriate handler, otherwise copy the text directly |
| 221 | + * into the script while escaping quotes. |
| 222 | + * |
| 223 | + * @param reader a reader for the template text |
| 224 | + * @return the parsed text |
| 225 | + * @throws IOException if something goes wrong |
| 226 | + */ |
| 227 | + protected String parse(Reader reader) throws IOException { |
| 228 | + if (!reader.markSupported()) { |
| 229 | + reader = new BufferedReader(reader); |
| 230 | + } |
| 231 | + StringWriter sw = new StringWriter(); |
| 232 | + startScript(sw); |
| 233 | + int c; |
| 234 | + while ((c = reader.read()) != -1) { |
| 235 | + if (c == '<') { |
| 236 | + reader.mark(1); |
| 237 | + c = reader.read(); |
| 238 | + if (c != '%') { |
| 239 | + sw.write('<'); |
| 240 | + reader.reset(); |
| 241 | + } else { |
| 242 | + reader.mark(1); |
| 243 | + c = reader.read(); |
| 244 | + if (c == '=') { |
| 245 | + groovyExpression(reader, sw); |
| 246 | + } else { |
| 247 | + reader.reset(); |
| 248 | + groovySection(reader, sw); |
| 249 | + } |
| 250 | + } |
| 251 | + continue; // at least '<' is consumed ... read next chars. |
| 252 | + } |
| 253 | + if (c == '$') { |
| 254 | + reader.mark(1); |
| 255 | + c = reader.read(); |
| 256 | + if (c != '{') { |
| 257 | + sw.write('$'); |
| 258 | + reader.reset(); |
| 259 | + } else { |
| 260 | + reader.mark(1); |
| 261 | + sw.write("${"); |
| 262 | + processGSstring(reader, sw); |
| 263 | + } |
| 264 | + continue; // at least '$' is consumed ... read next chars. |
| 265 | + } |
| 266 | + if (c == '\"') { |
| 267 | + sw.write('\\'); |
| 268 | + } |
| 269 | + /* |
| 270 | + * Handle raw new line characters. |
| 271 | + */ |
| 272 | + if (c == '\n' || c == '\r') { |
| 273 | + if (c == '\r') { // on Windows, "\r\n" is a new line. |
| 274 | + reader.mark(1); |
| 275 | + c = reader.read(); |
| 276 | + if (c != '\n') { |
| 277 | + reader.reset(); |
| 278 | + } |
| 279 | + } |
| 280 | + sw.write("\n"); |
| 281 | + continue; |
| 282 | + } |
| 283 | + sw.write(c); |
| 284 | + } |
| 285 | + endScript(sw); |
| 286 | + return sw.toString(); |
| 287 | + } |
| 288 | + |
| 289 | + private void startScript(StringWriter sw) { |
| 290 | + sw.write("/* Generated by SimpleTemplateEngine */\n"); |
| 291 | + sw.write(printMethod()+"\"\"\""); |
| 292 | + } |
| 293 | + |
| 294 | + private void endScript(StringWriter sw) { |
| 295 | + sw.write("\"\"\");\n"); |
| 296 | + } |
| 297 | + |
| 298 | + private void processGSstring(Reader reader, StringWriter sw) throws IOException { |
| 299 | + int c; |
| 300 | + while ((c = reader.read()) != -1) { |
| 301 | + if (c != '\n' && c != '\r') { |
| 302 | + sw.write(c); |
| 303 | + } |
| 304 | + if (c == '}') { |
| 305 | + break; |
| 306 | + } |
| 307 | + } |
| 308 | + } |
| 309 | + |
| 310 | + /** |
| 311 | + * Closes the currently open write and writes out the following text as a GString expression until it reaches an end %>. |
| 312 | + * |
| 313 | + * @param reader a reader for the template text |
| 314 | + * @param sw a StringWriter to write expression content |
| 315 | + * @throws IOException if something goes wrong |
| 316 | + */ |
| 317 | + private void groovyExpression(Reader reader, StringWriter sw) throws IOException { |
| 318 | + sw.write("${"); |
| 319 | + int c; |
| 320 | + while ((c = reader.read()) != -1) { |
| 321 | + if (c == '%') { |
| 322 | + c = reader.read(); |
| 323 | + if (c != '>') { |
| 324 | + sw.write('%'); |
| 325 | + } else { |
| 326 | + break; |
| 327 | + } |
| 328 | + } |
| 329 | + if (c != '\n' && c != '\r') { |
| 330 | + sw.write(c); |
| 331 | + } |
| 332 | + } |
| 333 | + sw.write("}"); |
| 334 | + } |
| 335 | + |
| 336 | + /** |
| 337 | + * Closes the currently open write and writes the following text as normal Groovy script code until it reaches an end %>. |
| 338 | + * |
| 339 | + * @param reader a reader for the template text |
| 340 | + * @param sw a StringWriter to write expression content |
| 341 | + * @throws IOException if something goes wrong |
| 342 | + */ |
| 343 | + private void groovySection(Reader reader, StringWriter sw) throws IOException { |
| 344 | + sw.write("\"\"\");"); |
| 345 | + int c; |
| 346 | + while ((c = reader.read()) != -1) { |
| 347 | + if (c == '%') { |
| 348 | + c = reader.read(); |
| 349 | + if (c != '>') { |
| 350 | + sw.write('%'); |
| 351 | + } else { |
| 352 | + break; |
| 353 | + } |
| 354 | + } |
| 355 | + /* Don't eat EOL chars in sections - as they are valid instruction separators. |
| 356 | + * See http://jira.codehaus.org/browse/GROOVY-980 |
| 357 | + */ |
| 358 | + // if (c != '\n' && c != '\r') { |
| 359 | + sw.write(c); |
| 360 | + //} |
| 361 | + } |
| 362 | + sw.write(";\n"+printMethod()+"\"\"\""); |
| 363 | + } |
| 364 | + |
| 365 | + protected String printMethod() { |
| 366 | + return "out.print("; |
| 367 | + } |
| 368 | +} |
0 commit comments