1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.html;
16
17 import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
18
19 import java.net.MalformedURLException;
20 import java.net.URL;
21 import java.nio.charset.Charset;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.htmlunit.FailingHttpStatusCodeException;
26 import org.htmlunit.SgmlPage;
27 import org.htmlunit.WebClient;
28 import org.htmlunit.WebWindow;
29 import org.htmlunit.html.HtmlPage.JavaScriptLoadResult;
30 import org.htmlunit.html.csp.ContentSecurityPolicy;
31 import org.htmlunit.javascript.AbstractJavaScriptEngine;
32 import org.htmlunit.javascript.PostponedAction;
33 import org.htmlunit.javascript.host.Window;
34 import org.htmlunit.javascript.host.dom.Document;
35 import org.htmlunit.javascript.host.event.Event;
36 import org.htmlunit.javascript.host.event.EventTarget;
37 import org.htmlunit.javascript.host.html.HTMLDocument;
38 import org.htmlunit.protocol.javascript.JavaScriptURLConnection;
39 import org.htmlunit.util.EncodingSniffer;
40 import org.htmlunit.util.MimeType;
41 import org.htmlunit.util.StringUtils;
42 import org.htmlunit.xml.XmlPage;
43
44
45
46
47
48
49
50
51
52
53
54 public final class ScriptElementSupport {
55
56 private static final Log LOG = LogFactory.getLog(ScriptElementSupport.class);
57
58
59 private static final String SLASH_SLASH_COLON = "//:";
60
61 private ScriptElementSupport() {
62
63 }
64
65
66
67
68
69
70
71 public static void onAllChildrenAddedToPage(final ScriptElement script, final boolean postponed) {
72 final DomElement element = (DomElement) script;
73 if (element.getOwnerDocument() instanceof XmlPage) {
74 return;
75 }
76 if (LOG.isDebugEnabled()) {
77 LOG.debug("Script node added: " + element.asXml());
78 }
79
80 final SgmlPage page = element.getPage();
81 final WebClient webClient = page.getWebClient();
82 if (!webClient.isJavaScriptEngineEnabled()) {
83 LOG.debug("Script found but not executed because javascript engine is disabled");
84 return;
85 }
86
87 final String srcAttrib = script.getScriptSource();
88 final boolean hasNoSrcAttrib = ATTRIBUTE_NOT_DEFINED == srcAttrib;
89
90
91 if (!hasNoSrcAttrib && script.isDeferred() && script.wasParserInserted()) {
92
93
94 return;
95 }
96
97 final WebWindow webWindow = page.getEnclosingWindow();
98 if (webWindow != null) {
99 final StringBuilder description = new StringBuilder()
100 .append("Execution of ")
101 .append(hasNoSrcAttrib ? "inline " : "external ")
102 .append(element.getClass().getSimpleName());
103 if (!hasNoSrcAttrib) {
104 description.append(" (").append(srcAttrib).append(')');
105 }
106
107 final PostponedAction action = new PostponedAction(page, description.toString()) {
108 @Override
109 public void execute() {
110
111 HTMLDocument jsDoc = null;
112 final Window window = webWindow.getScriptableObject();
113 if (window != null) {
114 jsDoc = (HTMLDocument) window.getDocument();
115 jsDoc.setExecutingDynamicExternalPosponed(element.getStartLineNumber() == -1
116 && !hasNoSrcAttrib);
117 }
118 try {
119 executeScriptIfNeeded(script, false, false);
120 }
121 finally {
122 if (jsDoc != null) {
123 jsDoc.setExecutingDynamicExternalPosponed(false);
124 }
125 }
126 }
127 };
128
129 final AbstractJavaScriptEngine<?> engine = webClient.getJavaScriptEngine();
130 if (element.hasAttribute("async") && !hasNoSrcAttrib) {
131 engine.addPostponedAction(action);
132 }
133 else if (postponed && !hasNoSrcAttrib) {
134 engine.addPostponedAction(action);
135 }
136 else {
137 try {
138 action.execute();
139 if (engine != null) {
140 engine.processPostponedActions();
141 }
142 }
143 catch (final RuntimeException e) {
144 throw e;
145 }
146 catch (final Exception e) {
147 throw new RuntimeException(e);
148 }
149 }
150 }
151 }
152
153
154
155
156
157
158
159
160
161
162 public static void executeScriptIfNeeded(final ScriptElement script, final boolean ignoreAttachedToPage,
163 final boolean ignorePageIsAncestor) {
164 try {
165 doExecuteScriptIfNeeded(script, ignoreAttachedToPage, ignorePageIsAncestor);
166 }
167 finally {
168
169
170 final AbstractJavaScriptEngine<?> engine =
171 ((DomElement) script).getPage().getWebClient().getJavaScriptEngine();
172 if (engine == null || !engine.isScriptRunning()) {
173 ContentSecurityPolicy.firePendingViolations();
174 }
175 }
176 }
177
178 private static void doExecuteScriptIfNeeded(final ScriptElement script, final boolean ignoreAttachedToPage,
179 final boolean ignorePageIsAncestor) {
180 if (!isExecutionNeeded(script, ignoreAttachedToPage, ignorePageIsAncestor)) {
181 return;
182 }
183
184 final String src = script.getScriptSource();
185 final DomElement element = (DomElement) script;
186 if (SLASH_SLASH_COLON.equals(src)) {
187 executeEvent(element, Event.TYPE_ERROR);
188 return;
189 }
190
191 final HtmlPage page = (HtmlPage) element.getPage();
192 if (src != ATTRIBUTE_NOT_DEFINED) {
193 if (!src.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
194
195 if (LOG.isDebugEnabled()) {
196 LOG.debug("Loading external JavaScript: " + src);
197 }
198 try {
199 script.setExecuted(true);
200
201 String scriptSrc = src;
202 if (page.getContentSecurityPolicy() != null) {
203 URL scriptUrl = null;
204 try {
205
206 final URL resolvedUrl = page.getFullyQualifiedUrl(src);
207 scriptUrl = ContentSecurityPolicy.upgradeInsecureRequest(page, resolvedUrl);
208 if (scriptUrl != resolvedUrl) {
209 scriptSrc = scriptUrl.toExternalForm();
210 }
211 }
212 catch (final MalformedURLException e) {
213
214 }
215 if (scriptUrl != null
216 && !ContentSecurityPolicy.allowsExternalScript(page, element, scriptUrl)) {
217 executeEvent(element, Event.TYPE_ERROR);
218 return;
219 }
220 }
221
222 Charset charset = EncodingSniffer.toCharset(script.getScriptCharset());
223 if (charset == null) {
224 charset = page.getCharset();
225 }
226
227 final JavaScriptLoadResult result;
228 final Window win = page.getEnclosingWindow().getScriptableObject();
229 final Document doc = win.getDocument();
230 try {
231 doc.setCurrentScript(element.getScriptableObject());
232 result = page.loadExternalJavaScriptFile(scriptSrc, charset, script.isCrossorigin(), element);
233 }
234 finally {
235 doc.setCurrentScript(null);
236 }
237
238 if (result == JavaScriptLoadResult.SUCCESS) {
239 executeEvent(element, Event.TYPE_LOAD);
240 }
241 else if (result == JavaScriptLoadResult.DOWNLOAD_ERROR) {
242 executeEvent(element, Event.TYPE_ERROR);
243 }
244 else if (result == JavaScriptLoadResult.NO_CONTENT) {
245 executeEvent(element, Event.TYPE_LOAD);
246 }
247 }
248 catch (final FailingHttpStatusCodeException e) {
249 executeEvent(element, Event.TYPE_ERROR);
250 throw e;
251 }
252 }
253 }
254 else if (element.getFirstChild() != null) {
255
256 final Window win = page.getEnclosingWindow().getScriptableObject();
257 final Document doc = win.getDocument();
258 try {
259 doc.setCurrentScript(element.getScriptableObject());
260 executeInlineScript(script);
261 }
262 finally {
263 doc.setCurrentScript(null);
264 }
265 }
266 }
267
268
269
270
271
272
273
274
275
276 private static boolean isExecutionNeeded(final ScriptElement script, final boolean ignoreAttachedToPage,
277 final boolean ignorePageIsAncestor) {
278 if (script.isExecuted() || script.wasCreatedByDomParser()) {
279 return false;
280 }
281
282 final DomElement element = (DomElement) script;
283 if (!ignoreAttachedToPage && !element.isAttachedToPage()) {
284 return false;
285 }
286
287
288 final SgmlPage page = element.getPage();
289 if (!page.getWebClient().isJavaScriptEnabled()) {
290 return false;
291 }
292
293
294 final HtmlPage htmlPage = element.getHtmlPageOrNull();
295 if (htmlPage != null && htmlPage.isParsingHtmlSnippet()) {
296 return false;
297 }
298
299
300 for (DomNode o = element; o != null; o = o.getParentNode()) {
301 if (o instanceof HtmlInlineFrame || o instanceof HtmlNoFrames) {
302 return false;
303 }
304 }
305
306
307
308 if (page.getEnclosingWindow() != null && page.getEnclosingWindow().getEnclosedPage() != page) {
309 return false;
310 }
311
312
313 final String t = element.getAttributeDirect("type");
314 final String l = element.getAttributeDirect("language");
315 if (!isJavaScript(t, l)) {
316
317
318
319 if (LOG.isDebugEnabled()) {
320 LOG.debug("Script is not JavaScript (type: '" + t + "', language: '" + l + "'). Skipping execution.");
321 }
322 return false;
323 }
324
325
326
327 return ignorePageIsAncestor || element.getPage().isAncestorOf(element);
328 }
329
330
331
332
333
334
335
336
337
338
339 public static boolean isJavaScript(final String typeAttribute, final String languageAttribute) {
340 final String type = typeAttribute.trim();
341 if (!StringUtils.isEmptyOrNull(type)) {
342 return MimeType.isJavascriptMimeType(type);
343 }
344
345 if (!StringUtils.isEmptyOrNull(languageAttribute)) {
346 return StringUtils.startsWithIgnoreCase(languageAttribute, "javascript");
347 }
348 return true;
349 }
350
351 private static void executeEvent(final DomElement element, final String type) {
352 final EventTarget eventTarget = element.getScriptableObject();
353 final Event event = new Event(element, type);
354
355 event.setParentScope(eventTarget.getParentScope());
356 event.setPrototype(eventTarget.getPrototype(event.getClass()));
357
358 eventTarget.executeEventLocally(event);
359 }
360
361
362
363
364 private static void executeInlineScript(final ScriptElement script) {
365 final DomElement element = (DomElement) script;
366 final String forr = element.getAttributeDirect("for");
367 String event = element.getAttributeDirect("event");
368
369 if (event.endsWith("()")) {
370 event = event.substring(0, event.length() - 2);
371 }
372
373 final String scriptCode = getScriptCode(element);
374 if (forr == ATTRIBUTE_NOT_DEFINED || "onload".equals(event)) {
375 final HtmlPage page = (HtmlPage) element.getPage();
376 if (!ContentSecurityPolicy.allowsInlineScript(page, element, scriptCode)) {
377 script.setExecuted(true);
378 return;
379 }
380
381 final String url = element.getPage().getUrl().toExternalForm();
382 final int line1 = element.getStartLineNumber();
383 final int line2 = element.getEndLineNumber();
384 final int col1 = element.getStartColumnNumber();
385 final int col2 = element.getEndColumnNumber();
386 final String desc = "script in " + url + " from (" + line1 + ", " + col1
387 + ") to (" + line2 + ", " + col2 + ")";
388
389 script.setExecuted(true);
390 page.executeJavaScript(scriptCode, desc, line1);
391 }
392 }
393
394
395
396
397 private static String getScriptCode(final DomElement element) {
398 final StringBuilder scriptCode = new StringBuilder();
399 for (final DomNode node : element.getChildren()) {
400 if (node instanceof DomText domText) {
401 scriptCode.append(domText.getData());
402 }
403 }
404 return scriptCode.toString();
405 }
406 }