1
2
3
4
5
6
7
8
9
10
11
12
13
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
49
50
51
52
53
54
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
68
69
70
71 public HtmlUnitContextFactory(final WebClient webClient) {
72 super();
73 webClient_ = webClient;
74 browserVersion_ = webClient.getBrowserVersion();
75 }
76
77
78
79
80
81
82
83 public void setTimeout(final long timeout) {
84 timeout_ = timeout;
85 }
86
87
88
89
90
91
92
93 public long getTimeout() {
94 return timeout_;
95 }
96
97
98
99
100
101
102
103
104 public void setDebugger(final Debugger debugger) {
105 debugger_ = debugger;
106 }
107
108
109
110
111
112
113
114 public Debugger getDebugger() {
115 return debugger_;
116 }
117
118
119
120
121
122
123 public void setDeminifyFunctionCode(final boolean deminify) {
124 deminifyFunctionCode_ = deminify;
125 }
126
127
128
129
130
131
132 public boolean isDeminifyFunctionCode() {
133 return deminifyFunctionCode_;
134 }
135
136
137
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
155
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
168
169 final boolean isWindowEval = compiler != null;
170
171
172 String code = source;
173 if (!isWindowEval) {
174
175
176
177
178
179
180
181
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
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
207
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
232
233
234
235
236
237
238
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
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
274
275
276
277
278
279
280
281
282
283
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
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
311 cx.setClassShutter(fullClassName -> false);
312
313
314 cx.setInterpretedMode(true);
315
316
317 cx.setInstructionObserverThreshold(INSTRUCTION_COUNT_THRESHOLD);
318
319 cx.setErrorReporter(new HtmlUnitErrorReporter(webClient_.getJavaScriptErrorListener()));
320
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
334
335
336
337
338
339
340 @Override
341 protected void observeInstructionCount(final Context cx, final int instructionCount) {
342 final TimeoutContext tcx = (TimeoutContext) cx;
343 tcx.terminateScriptIfNecessary();
344
345
346
347
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
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
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
383
384
385
386
387
388
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
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
426
427
428
429 HtmlUnitErrorReporter(final JavaScriptErrorListener javaScriptErrorListener) {
430 javaScriptErrorListener_ = javaScriptErrorListener;
431 }
432
433
434
435
436
437
438
439
440
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
451
452
453
454
455
456
457
458 @Override
459 public void error(final String message, final String sourceName, final int line,
460 final String lineSource, final int lineOffset) {
461
462
463 throw new EvaluatorException(message, sourceName, line, lineSource, lineOffset);
464 }
465
466
467
468
469
470
471
472
473
474
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
481
482 return new EvaluatorException(message, sourceName, line, lineSource, lineOffset);
483 }
484 }
485 }