View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
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    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.javascript;
16  
17  import static org.htmlunit.BrowserVersionFeatures.JS_ARRAY_SORT_ACCEPTS_INCONSISTENT_COMPERATOR;
18  import static org.htmlunit.BrowserVersionFeatures.JS_PROPERTY_DESCRIPTOR_NAME;
19  
20  import java.io.Serializable;
21  import java.util.function.Consumer;
22  
23  import org.htmlunit.BrowserVersion;
24  import org.htmlunit.ScriptException;
25  import org.htmlunit.ScriptPreProcessor;
26  import org.htmlunit.WebClient;
27  import org.htmlunit.corejs.javascript.Callable;
28  import org.htmlunit.corejs.javascript.CompilerEnvirons;
29  import org.htmlunit.corejs.javascript.Context;
30  import org.htmlunit.corejs.javascript.ContextAction;
31  import org.htmlunit.corejs.javascript.ContextFactory;
32  import org.htmlunit.corejs.javascript.ErrorReporter;
33  import org.htmlunit.corejs.javascript.Evaluator;
34  import org.htmlunit.corejs.javascript.EvaluatorException;
35  import org.htmlunit.corejs.javascript.Function;
36  import org.htmlunit.corejs.javascript.Script;
37  import org.htmlunit.corejs.javascript.ScriptRuntime;
38  import org.htmlunit.corejs.javascript.ScriptStackElement;
39  import org.htmlunit.corejs.javascript.ScriptableObject;
40  import org.htmlunit.corejs.javascript.VarScope;
41  import org.htmlunit.corejs.javascript.debug.Debugger;
42  import org.htmlunit.html.HtmlElement;
43  import org.htmlunit.html.HtmlPage;
44  import org.htmlunit.html.csp.ContentSecurityPolicy;
45  import org.htmlunit.javascript.host.Window;
46  
47  /**
48   * ContextFactory that supports termination of scripts if they exceed a timeout. Based on example from
49   * <a href="http://www.mozilla.org/rhino/apidocs/org/mozilla/javascript/ContextFactory.html">ContextFactory</a>.
50   *
51   * @author Andre Soereng
52   * @author Ahmed Ashour
53   * @author Marc Guillemot
54   * @author Ronald Brill
55   */
56  public class HtmlUnitContextFactory extends ContextFactory {
57  
58      private static final int INSTRUCTION_COUNT_THRESHOLD = 10_000;
59  
60      private final WebClient webClient_;
61      private final BrowserVersion browserVersion_;
62      private long timeout_;
63      private Debugger debugger_;
64      private boolean deminifyFunctionCode_;
65  
66      /**
67       * Creates a new instance of HtmlUnitContextFactory.
68       *
69       * @param webClient the web client using this factory
70       */
71      public HtmlUnitContextFactory(final WebClient webClient) {
72          super();
73          webClient_ = webClient;
74          browserVersion_ = webClient.getBrowserVersion();
75      }
76  
77      /**
78       * Sets the number of milliseconds a script is allowed to execute before
79       * being terminated. A value of 0 or less means no timeout.
80       *
81       * @param timeout the timeout value
82       */
83      public void setTimeout(final long timeout) {
84          timeout_ = timeout;
85      }
86  
87      /**
88       * Returns the number of milliseconds a script is allowed to execute before
89       * being terminated. A value of 0 or less means no timeout.
90       *
91       * @return the timeout value (default value is <code>0</code>)
92       */
93      public long getTimeout() {
94          return timeout_;
95      }
96  
97      /**
98       * Sets the JavaScript debugger to use to receive JavaScript execution debugging information.
99       * The HtmlUnit default implementation ({@link DebuggerImpl}, {@link DebugFrameImpl}) may be
100      * used, or a custom debugger may be used instead. By default, no debugger is used.
101      *
102      * @param debugger the JavaScript debugger to use (maybe {@code null})
103      */
104     public void setDebugger(final Debugger debugger) {
105         debugger_ = debugger;
106     }
107 
108     /**
109      * Returns the JavaScript debugger to use to receive JavaScript execution debugging information.
110      * By default, no debugger is used, and this method returns {@code null}.
111      *
112      * @return the JavaScript debugger to use to receive JavaScript execution debugging information
113      */
114     public Debugger getDebugger() {
115         return debugger_;
116     }
117 
118     /**
119      * Configures if the code of <code>new Function("...some code...")</code> should be deminified to be more readable
120      * when using the debugger. This is a small performance cost.
121      * @param deminify the new value
122      */
123     public void setDeminifyFunctionCode(final boolean deminify) {
124         deminifyFunctionCode_ = deminify;
125     }
126 
127     /**
128      * Indicates code of calls like <code>new Function("...some code...")</code> should be deminified to be more
129      * readable when using the debugger.
130      * @return the de-minify status
131      */
132     public boolean isDeminifyFunctionCode() {
133         return deminifyFunctionCode_;
134     }
135 
136     /**
137      * Custom context to store execution time and handle timeouts.
138      */
139     private class TimeoutContext extends Context {
140         private long startTime_;
141 
142         protected TimeoutContext(final ContextFactory factory) {
143             super(factory);
144         }
145 
146         public void startClock() {
147             startTime_ = System.currentTimeMillis();
148         }
149 
150         public void terminateScriptIfNecessary() {
151             if (timeout_ > 0) {
152                 final long currentTime = System.currentTimeMillis();
153                 if (currentTime - startTime_ > timeout_) {
154                     // Terminate script by throwing an Error instance to ensure that the
155                     // script will never get control back through catch or finally.
156                     throw new TimeoutError(timeout_, currentTime - startTime_);
157                 }
158             }
159         }
160 
161         @Override
162         protected Script compileString(final String source, final Evaluator compiler,
163                 final ErrorReporter compilationErrorReporter, final String sourceName,
164                 final int lineno, final Object securityDomain,
165                 final Consumer<CompilerEnvirons> compilerEnvironsProcessor) {
166 
167             // this method gets called by Context.compileString and by ScriptRuntime.evalSpecial
168             // which is used for window.eval. We have to take care in which case we are.
169             final boolean isWindowEval = compiler != null;
170 
171             // Remove HTML comments around the source if needed
172             String code = source;
173             if (!isWindowEval) {
174 
175                 // **** Memory Optimization ****
176                 // final String sourceCodeTrimmed = source.trim();
177                 // if (sourceCodeTrimmed.startsWith("<!--")) {
178                 // **** Memory Optimization ****
179                 // do not trim because this will create a copy of the
180                 // whole string (usually large for libs like jQuery
181                 // if there is whitespace to trim (e.g. cr at end)
182                 final int length = source.length();
183                 int start = 0;
184                 while ((start < length) && (source.charAt(start) <= ' ')) {
185                     start++;
186                 }
187                 if (start + 3 < length
188                         && source.charAt(start++) == '<'
189                         && source.charAt(start++) == '!'
190                         && source.charAt(start++) == '-'
191                         && source.charAt(start++) == '-') {
192                     code = source.replaceFirst("<!--", "// <!--");
193                 }
194             }
195 
196             // Pre process the source code
197             final HtmlPage page = (HtmlPage) Context.getCurrentContext()
198                 .getThreadLocal(JavaScriptEngine.KEY_STARTING_PAGE);
199             code = preProcess(page, code, sourceName, lineno, null);
200 
201             return super.compileString(code, compiler, compilationErrorReporter,
202                     sourceName, lineno, securityDomain, compilerEnvironsProcessor);
203         }
204 
205         /**
206          * Like the browsers, checks the Content-Security-Policy of the realm (page) the
207          * string is compiled for (eval, new Function()).
208          */
209         @Override
210         protected void ensureCanCompileStrings(final VarScope scope, final String source) {
211             ensureEvalAllowed(source, scope);
212         }
213 
214         @Override
215         protected Function compileFunction(final VarScope scope, final String source,
216                 final Evaluator compiler, final ErrorReporter compilationErrorReporter,
217                 final String sourceName, final int lineno, final Object securityDomain) {
218 
219             String code = source;
220             if (deminifyFunctionCode_) {
221                 final Function f = super.compileFunction(scope, source, compiler,
222                         compilationErrorReporter, sourceName, lineno, securityDomain);
223                 code = decompileFunction(f, 4).trim().replace("\n    ", "\n");
224             }
225             return super.compileFunction(scope, code, compiler,
226                     compilationErrorReporter, sourceName, lineno, securityDomain);
227         }
228     }
229 
230     /**
231      * Throws an EvalError if the Content-Security-Policy of the page
232      * does not allow the evaluation of strings as code.
233      * Like the browsers, the policy of the realm of the called function is used (e.g. for
234      * {@code frame.contentWindow.eval(...)} or {@code new frame.contentWindow.Function(...)} the
235      * policy of the frame); if the realm has no page the page of the running script is used.
236      *
237      * @param source the source to evaluate
238      * @param scope the scope of the realm
239      */
240     private static void ensureEvalAllowed(final String source, final VarScope scope) {
241         final Context cx = Context.getCurrentContext();
242         if (cx == null) {
243             return;
244         }
245 
246         Object page = null;
247         if (scope != null
248                 && ScriptableObject.getTopLevelScope(scope).getGlobalThis() instanceof Window window) {
249             page = window.getWebWindow().getEnclosedPage();
250         }
251         if (!(page instanceof HtmlPage)) {
252             page = cx.getThreadLocal(JavaScriptEngine.KEY_RUNNING_PAGE);
253         }
254         if (!(page instanceof HtmlPage)) {
255             page = cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_PAGE);
256         }
257         if (page instanceof HtmlPage htmlPage) {
258             // the line of the code calling eval (the first script frame)
259             int lineNumber = 0;
260             final ScriptStackElement[] stack = new EvaluatorException("eval").getScriptStack();
261             if (stack.length > 0) {
262                 lineNumber = Math.max(0, stack[0].lineNumber);
263             }
264             if (!ContentSecurityPolicy.allowsEval(htmlPage, source, lineNumber)) {
265                 throw ScriptRuntime.constructError("EvalError",
266                         "Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed "
267                         + "source of script in the Content Security Policy of the page.");
268             }
269         }
270     }
271 
272     /**
273      * Pre process the specified source code in the context of the given page using the processor specified
274      * in the {@link WebClient}. This method delegates to the pre processor handler specified in the
275      * <code>WebClient</code>. If no pre processor handler is defined, the original source code is returned
276      * unchanged.
277      * @param htmlPage the page
278      * @param sourceCode the code to process
279      * @param sourceName a name for the chunk of code (used in error messages)
280      * @param lineNumber the line number of the source code
281      * @param htmlElement the HTML element that will act as the context
282      * @return the source code after being pre processed
283      * @see org.htmlunit.ScriptPreProcessor
284      */
285     protected String preProcess(
286         final HtmlPage htmlPage, final String sourceCode, final String sourceName, final int lineNumber,
287         final HtmlElement htmlElement) {
288 
289         String newSourceCode = sourceCode;
290         final ScriptPreProcessor preProcessor = webClient_.getScriptPreProcessor();
291         if (preProcessor != null) {
292             newSourceCode = preProcessor.preProcess(htmlPage, sourceCode, sourceName, lineNumber, htmlElement);
293             if (newSourceCode == null) {
294                 newSourceCode = "";
295             }
296         }
297         return newSourceCode;
298     }
299 
300     /**
301      * {@inheritDoc}
302      */
303     @Override
304     protected Context makeContext() {
305         final TimeoutContext cx = new TimeoutContext(this);
306         cx.setLanguageVersion(Context.VERSION_ES6);
307         cx.setLocale(browserVersion_.getBrowserLocale());
308         cx.setTimeZone(browserVersion_.getSystemTimezone());
309 
310         // make sure no java classes are usable from js
311         cx.setClassShutter(fullClassName -> false);
312 
313         // Use pure interpreter mode to get observeInstructionCount() callbacks.
314         cx.setInterpretedMode(true);
315 
316         // Set threshold on how often we want to receive the callbacks
317         cx.setInstructionObserverThreshold(INSTRUCTION_COUNT_THRESHOLD);
318 
319         cx.setErrorReporter(new HtmlUnitErrorReporter(webClient_.getJavaScriptErrorListener()));
320         // We don't want to wrap String & Co.
321         cx.getWrapFactory().setJavaPrimitiveWrap(false);
322 
323         if (debugger_ != null) {
324             cx.setDebugger(debugger_, null);
325         }
326 
327         cx.setMaximumInterpreterStackDepth(5_000);
328 
329         return cx;
330     }
331 
332     /**
333      * Run-time calls this when instruction counting is enabled and the counter
334      * reaches limit set by setInstructionObserverThreshold(). A script can be
335      * terminated by throwing an Error instance here.
336      *
337      * @param cx the context calling us
338      * @param instructionCount amount of script instruction executed since last call to observeInstructionCount
339      */
340     @Override
341     protected void observeInstructionCount(final Context cx, final int instructionCount) {
342         final TimeoutContext tcx = (TimeoutContext) cx;
343         tcx.terminateScriptIfNecessary();
344 
345         // stop scripts of pages that are no longer the enclosed page
346         // of their window (e.g. a setTimeout function still running
347         // while the window navigates to a new page)
348         final Object runningPage = cx.getThreadLocal(JavaScriptEngine.KEY_RUNNING_PAGE);
349         if (runningPage instanceof HtmlPage page
350                 && page != page.getEnclosingWindow().getEnclosedPage()) {
351             throw new PageUnloadedError();
352         }
353     }
354 
355     /**
356      * {@inheritDoc}
357      */
358     @Override
359     protected Object doTopCall(final Callable callable,
360             final Context cx, final VarScope scope,
361             final Object thisObj, final Object[] args) {
362 
363         final TimeoutContext tcx = (TimeoutContext) cx;
364         tcx.startClock();
365         return super.doTopCall(callable, cx, scope, thisObj, args);
366     }
367 
368     /**
369      * {@inheritDoc}
370      */
371     @Override
372     protected Object doTopCall(final Script script,
373             final Context cx, final VarScope scope,
374             final Object thisObj) {
375 
376         final TimeoutContext tcx = (TimeoutContext) cx;
377         tcx.startClock();
378         return super.doTopCall(script, cx, scope, thisObj);
379     }
380 
381     /**
382      * Same as {@link ContextFactory}{@link #call(ContextAction)} but with handling
383      * of some exceptions.
384      *
385      * @param <T> return type of the action
386      * @param action the contextAction
387      * @param page the page
388      * @return the result of the call
389      */
390     public final <T> T callSecured(final ContextAction<T> action, final HtmlPage page) {
391         try {
392             return call(action);
393         }
394         catch (final StackOverflowError e) {
395             webClient_.getJavaScriptErrorListener().scriptException(page, new ScriptException(page, e));
396             return null;
397         }
398     }
399 
400     /**
401      * {@inheritDoc}
402      */
403     @Override
404     protected boolean hasFeature(final Context cx, final int featureIndex) {
405         return switch (featureIndex) {
406             case Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER,
407                  Context.FEATURE_OLD_UNDEF_NULL_THIS,
408                  Context.FEATURE_LITTLE_ENDIAN,
409                  Context.FEATURE_LOCATION_INFORMATION_IN_ERROR,
410                  Context.FEATURE_INTL_402,
411                  Context.FEATURE_HTMLUNIT_FN_ARGUMENTS_IS_RO_VIEW -> true;
412             case Context.FEATURE_E4X -> false;
413             case Context.FEATURE_HTMLUNIT_MEMBERBOX_NAME -> browserVersion_.hasFeature(JS_PROPERTY_DESCRIPTOR_NAME);
414             case Context.FEATURE_HTMLUNIT_ARRAY_SORT_COMPERATOR_ACCEPTS_BOOL ->
415                 browserVersion_.hasFeature(JS_ARRAY_SORT_ACCEPTS_INCONSISTENT_COMPERATOR);
416             default -> super.hasFeature(cx, featureIndex);
417         };
418     }
419 
420     private static final class HtmlUnitErrorReporter implements ErrorReporter, Serializable {
421 
422         private final JavaScriptErrorListener javaScriptErrorListener_;
423 
424         /**
425          * Ctor.
426          *
427          * @param javaScriptErrorListener the listener to be used
428          */
429         HtmlUnitErrorReporter(final JavaScriptErrorListener javaScriptErrorListener) {
430             javaScriptErrorListener_ = javaScriptErrorListener;
431         }
432 
433         /**
434          * Logs a warning.
435          *
436          * @param message the message to be displayed
437          * @param sourceName the name of the source file
438          * @param line the line number
439          * @param lineSource the source code that failed
440          * @param lineOffset the line offset
441          */
442         @Override
443         public void warning(
444                 final String message, final String sourceName, final int line,
445                 final String lineSource, final int lineOffset) {
446             javaScriptErrorListener_.warn(message, sourceName, line, lineSource, lineOffset);
447         }
448 
449         /**
450          * Logs an error.
451          *
452          * @param message the message to be displayed
453          * @param sourceName the name of the source file
454          * @param line the line number
455          * @param lineSource the source code that failed
456          * @param lineOffset the line offset
457          */
458         @Override
459         public void error(final String message, final String sourceName, final int line,
460                 final String lineSource, final int lineOffset) {
461             // no need to log here, this is only used to create the exception
462             // gets logged if not catched later on
463             throw new EvaluatorException(message, sourceName, line, lineSource, lineOffset);
464         }
465 
466         /**
467          * Logs a runtime error.
468          *
469          * @param message the message to be displayed
470          * @param sourceName the name of the source file
471          * @param line the line number
472          * @param lineSource the source code that failed
473          * @param lineOffset the line offset
474          * @return an evaluator exception
475          */
476         @Override
477         public EvaluatorException runtimeError(
478                 final String message, final String sourceName, final int line,
479                 final String lineSource, final int lineOffset) {
480             // no need to log here, this is only used to create the exception
481             // gets logged if not catched later on
482             return new EvaluatorException(message, sourceName, line, lineSource, lineOffset);
483         }
484     }
485 }