f69e0e63d362e4750b5f16bbce060813de6b7058
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / dom / ScriptLoader.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2001 Dirk Mueller (mueller@kde.org)
5  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
6  * Copyright (C) 2008 Nikolas Zimmermann <zimmermann@kde.org>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 #include "config.h"
25 #include "core/dom/ScriptLoader.h"
26
27 #include "bindings/core/v8/ScriptController.h"
28 #include "bindings/core/v8/ScriptSourceCode.h"
29 #include "core/HTMLNames.h"
30 #include "core/SVGNames.h"
31 #include "core/dom/Document.h"
32 #include "core/events/Event.h"
33 #include "core/dom/IgnoreDestructiveWriteCountIncrementer.h"
34 #include "core/dom/ScriptLoaderClient.h"
35 #include "core/dom/ScriptRunner.h"
36 #include "core/dom/ScriptableDocumentParser.h"
37 #include "core/dom/Text.h"
38 #include "core/fetch/FetchRequest.h"
39 #include "core/fetch/ResourceFetcher.h"
40 #include "core/fetch/ScriptResource.h"
41 #include "core/html/HTMLScriptElement.h"
42 #include "core/html/imports/HTMLImport.h"
43 #include "core/html/parser/HTMLParserIdioms.h"
44 #include "core/frame/LocalFrame.h"
45 #include "core/frame/csp/ContentSecurityPolicy.h"
46 #include "core/inspector/ConsoleMessage.h"
47 #include "core/svg/SVGScriptElement.h"
48 #include "platform/MIMETypeRegistry.h"
49 #include "platform/weborigin/SecurityOrigin.h"
50 #include "wtf/StdLibExtras.h"
51 #include "wtf/text/StringBuilder.h"
52 #include "wtf/text/StringHash.h"
53
54 namespace blink {
55
56 ScriptLoader::ScriptLoader(Element* element, bool parserInserted, bool alreadyStarted)
57     : m_element(element)
58     , m_resource(0)
59     , m_startLineNumber(WTF::OrdinalNumber::beforeFirst())
60     , m_parserInserted(parserInserted)
61     , m_isExternalScript(false)
62     , m_alreadyStarted(alreadyStarted)
63     , m_haveFiredLoad(false)
64     , m_willBeParserExecuted(false)
65     , m_readyToBeParserExecuted(false)
66     , m_willExecuteWhenDocumentFinishedParsing(false)
67     , m_forceAsync(!parserInserted)
68     , m_willExecuteInOrder(false)
69 {
70     ASSERT(m_element);
71     if (parserInserted && element->document().scriptableDocumentParser() && !element->document().isInDocumentWrite())
72         m_startLineNumber = element->document().scriptableDocumentParser()->lineNumber();
73 }
74
75 ScriptLoader::~ScriptLoader()
76 {
77     stopLoadRequest();
78 }
79
80 void ScriptLoader::didNotifySubtreeInsertionsToDocument()
81 {
82     if (!m_parserInserted)
83         prepareScript(); // FIXME: Provide a real starting line number here.
84 }
85
86 void ScriptLoader::childrenChanged()
87 {
88     if (!m_parserInserted && m_element->inDocument())
89         prepareScript(); // FIXME: Provide a real starting line number here.
90 }
91
92 void ScriptLoader::handleSourceAttribute(const String& sourceUrl)
93 {
94     if (ignoresLoadRequest() || sourceUrl.isEmpty())
95         return;
96
97     prepareScript(); // FIXME: Provide a real starting line number here.
98 }
99
100 void ScriptLoader::handleAsyncAttribute()
101 {
102     m_forceAsync = false;
103 }
104
105 // Helper function
106 static bool isLegacySupportedJavaScriptLanguage(const String& language)
107 {
108     // Mozilla 1.8 accepts javascript1.0 - javascript1.7, but WinIE 7 accepts only javascript1.1 - javascript1.3.
109     // Mozilla 1.8 and WinIE 7 both accept javascript and livescript.
110     // WinIE 7 accepts ecmascript and jscript, but Mozilla 1.8 doesn't.
111     // Neither Mozilla 1.8 nor WinIE 7 accept leading or trailing whitespace.
112     // We want to accept all the values that either of these browsers accept, but not other values.
113
114     // FIXME: This function is not HTML5 compliant. These belong in the MIME registry as "text/javascript<version>" entries.
115     typedef HashSet<String, CaseFoldingHash> LanguageSet;
116     DEFINE_STATIC_LOCAL(LanguageSet, languages, ());
117     if (languages.isEmpty()) {
118         languages.add("javascript");
119         languages.add("javascript1.0");
120         languages.add("javascript1.1");
121         languages.add("javascript1.2");
122         languages.add("javascript1.3");
123         languages.add("javascript1.4");
124         languages.add("javascript1.5");
125         languages.add("javascript1.6");
126         languages.add("javascript1.7");
127         languages.add("livescript");
128         languages.add("ecmascript");
129         languages.add("jscript");
130     }
131
132     return languages.contains(language);
133 }
134
135 void ScriptLoader::dispatchErrorEvent()
136 {
137     m_element->dispatchEvent(Event::create(EventTypeNames::error));
138 }
139
140 void ScriptLoader::dispatchLoadEvent()
141 {
142     if (ScriptLoaderClient* client = this->client())
143         client->dispatchLoadEvent();
144     setHaveFiredLoadEvent(true);
145 }
146
147 bool ScriptLoader::isScriptTypeSupported(LegacyTypeSupport supportLegacyTypes) const
148 {
149     // FIXME: isLegacySupportedJavaScriptLanguage() is not valid HTML5. It is used here to maintain backwards compatibility with existing layout tests. The specific violations are:
150     // - Allowing type=javascript. type= should only support MIME types, such as text/javascript.
151     // - Allowing a different set of languages for language= and type=. language= supports Javascript 1.1 and 1.4-1.6, but type= does not.
152
153     String type = client()->typeAttributeValue();
154     String language = client()->languageAttributeValue();
155     if (type.isEmpty() && language.isEmpty())
156         return true; // Assume text/javascript.
157     if (type.isEmpty()) {
158         type = "text/" + language.lower();
159         if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(type) || isLegacySupportedJavaScriptLanguage(language))
160             return true;
161     } else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(type.stripWhiteSpace()) || (supportLegacyTypes == AllowLegacyTypeInTypeAttribute && isLegacySupportedJavaScriptLanguage(type))) {
162         return true;
163     }
164
165     return false;
166 }
167
168 // http://dev.w3.org/html5/spec/Overview.html#prepare-a-script
169 bool ScriptLoader::prepareScript(const TextPosition& scriptStartPosition, LegacyTypeSupport supportLegacyTypes)
170 {
171     if (m_alreadyStarted)
172         return false;
173
174     ScriptLoaderClient* client = this->client();
175
176     bool wasParserInserted;
177     if (m_parserInserted) {
178         wasParserInserted = true;
179         m_parserInserted = false;
180     } else {
181         wasParserInserted = false;
182     }
183
184     if (wasParserInserted && !client->asyncAttributeValue())
185         m_forceAsync = true;
186
187     // FIXME: HTML5 spec says we should check that all children are either comments or empty text nodes.
188     if (!client->hasSourceAttribute() && !m_element->hasChildren())
189         return false;
190
191     if (!m_element->inDocument())
192         return false;
193
194     if (!isScriptTypeSupported(supportLegacyTypes))
195         return false;
196
197     if (wasParserInserted) {
198         m_parserInserted = true;
199         m_forceAsync = false;
200     }
201
202     m_alreadyStarted = true;
203
204     // FIXME: If script is parser inserted, verify it's still in the original document.
205     Document& elementDocument = m_element->document();
206     Document* contextDocument = elementDocument.contextDocument().get();
207
208     if (!contextDocument || !contextDocument->allowExecutingScripts(m_element))
209         return false;
210
211     if (!isScriptForEventSupported())
212         return false;
213
214     if (!client->charsetAttributeValue().isEmpty())
215         m_characterEncoding = client->charsetAttributeValue();
216     else
217         m_characterEncoding = elementDocument.charset();
218
219     if (client->hasSourceAttribute()) {
220         if (!fetchScript(client->sourceAttributeValue()))
221             return false;
222     }
223
224     if (client->hasSourceAttribute() && client->deferAttributeValue() && m_parserInserted && !client->asyncAttributeValue()) {
225         m_willExecuteWhenDocumentFinishedParsing = true;
226         m_willBeParserExecuted = true;
227     } else if (client->hasSourceAttribute() && m_parserInserted && !client->asyncAttributeValue()) {
228         m_willBeParserExecuted = true;
229     } else if (!client->hasSourceAttribute() && m_parserInserted && !elementDocument.isRenderingReady()) {
230         m_willBeParserExecuted = true;
231         m_readyToBeParserExecuted = true;
232     } else if (client->hasSourceAttribute() && !client->asyncAttributeValue() && !m_forceAsync) {
233         m_willExecuteInOrder = true;
234         contextDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::IN_ORDER_EXECUTION);
235         m_resource->addClient(this);
236     } else if (client->hasSourceAttribute()) {
237         contextDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::ASYNC_EXECUTION);
238         m_resource->addClient(this);
239     } else {
240         // Reset line numbering for nested writes.
241         TextPosition position = elementDocument.isInDocumentWrite() ? TextPosition() : scriptStartPosition;
242         KURL scriptURL = (!elementDocument.isInDocumentWrite() && m_parserInserted) ? elementDocument.url() : KURL();
243         executeScript(ScriptSourceCode(scriptContent(), scriptURL, position));
244     }
245
246     return true;
247 }
248
249 bool ScriptLoader::fetchScript(const String& sourceUrl)
250 {
251     ASSERT(m_element);
252
253     RefPtrWillBeRawPtr<Document> elementDocument(m_element->document());
254     if (!m_element->inDocument() || m_element->document() != elementDocument)
255         return false;
256
257     ASSERT(!m_resource);
258     if (!stripLeadingAndTrailingHTMLSpaces(sourceUrl).isEmpty()) {
259         FetchRequest request(ResourceRequest(elementDocument->completeURL(sourceUrl)), m_element->localName());
260
261         AtomicString crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
262         if (!crossOriginMode.isNull())
263             request.setCrossOriginAccessControl(elementDocument->securityOrigin(), crossOriginMode);
264         request.setCharset(scriptCharset());
265
266         bool scriptPassesCSP = elementDocument->contentSecurityPolicy()->allowScriptWithNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr));
267         if (scriptPassesCSP)
268             request.setContentSecurityCheck(DoNotCheckContentSecurityPolicy);
269
270         m_resource = elementDocument->fetcher()->fetchScript(request);
271         m_isExternalScript = true;
272     }
273
274     if (m_resource)
275         return true;
276
277     dispatchErrorEvent();
278     return false;
279 }
280
281 bool isHTMLScriptLoader(Element* element)
282 {
283     ASSERT(element);
284     return isHTMLScriptElement(*element);
285 }
286
287 bool isSVGScriptLoader(Element* element)
288 {
289     ASSERT(element);
290     return isSVGScriptElement(*element);
291 }
292
293 void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode)
294 {
295     ASSERT(m_alreadyStarted);
296
297     if (sourceCode.isEmpty())
298         return;
299
300     RefPtrWillBeRawPtr<Document> elementDocument(m_element->document());
301     RefPtrWillBeRawPtr<Document> contextDocument = elementDocument->contextDocument().get();
302     if (!contextDocument)
303         return;
304
305     LocalFrame* frame = contextDocument->frame();
306
307     const ContentSecurityPolicy* csp = elementDocument->contentSecurityPolicy();
308     bool shouldBypassMainWorldCSP = (frame && frame->script().shouldBypassMainWorldCSP())
309         || csp->allowScriptWithNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr))
310         || csp->allowScriptWithHash(sourceCode.source());
311
312     if (!m_isExternalScript && (!shouldBypassMainWorldCSP && !csp->allowInlineScript(elementDocument->url(), m_startLineNumber)))
313         return;
314
315     if (m_isExternalScript) {
316         ScriptResource* resource = m_resource ? m_resource.get() : sourceCode.resource();
317         if (resource && !resource->mimeTypeAllowedByNosniff()) {
318             contextDocument->addConsoleMessage(ConsoleMessage::create(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + resource->url().elidedString() + "' because its MIME type ('" + resource->mimeType() + "') is not executable, and strict MIME type checking is enabled."));
319             return;
320         }
321     }
322
323     // FIXME: Can this be moved earlier in the function?
324     // Why are we ever attempting to execute scripts without a frame?
325     if (!frame)
326         return;
327
328     const bool isImportedScript = contextDocument != elementDocument;
329     // http://www.whatwg.org/specs/web-apps/current-work/#execute-the-script-block step 2.3
330     // with additional support for HTML imports.
331     IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript || isImportedScript ? contextDocument.get() : 0);
332
333     if (isHTMLScriptLoader(m_element))
334         contextDocument->pushCurrentScript(toHTMLScriptElement(m_element));
335
336     AccessControlStatus corsCheck = NotSharableCrossOrigin;
337     if (!m_isExternalScript || (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin())))
338         corsCheck = SharableCrossOrigin;
339
340     // Create a script from the script element node, using the script
341     // block's source and the script block's type.
342     // Note: This is where the script is compiled and actually executed.
343     frame->script().executeScriptInMainWorld(sourceCode, corsCheck);
344
345     if (isHTMLScriptLoader(m_element)) {
346         ASSERT(contextDocument->currentScript() == m_element);
347         contextDocument->popCurrentScript();
348     }
349 }
350
351 void ScriptLoader::stopLoadRequest()
352 {
353     if (m_resource) {
354         if (!m_willBeParserExecuted)
355             m_resource->removeClient(this);
356         m_resource = 0;
357     }
358 }
359
360 void ScriptLoader::execute(ScriptResource* resource)
361 {
362     ASSERT(!m_willBeParserExecuted);
363     ASSERT(resource);
364     if (resource->errorOccurred()) {
365         dispatchErrorEvent();
366     } else if (!resource->wasCanceled()) {
367         executeScript(ScriptSourceCode(resource));
368         dispatchLoadEvent();
369     }
370     resource->removeClient(this);
371 }
372
373 void ScriptLoader::notifyFinished(Resource* resource)
374 {
375     ASSERT(!m_willBeParserExecuted);
376
377     RefPtrWillBeRawPtr<Document> elementDocument(m_element->document());
378     RefPtrWillBeRawPtr<Document> contextDocument = elementDocument->contextDocument().get();
379     if (!contextDocument)
380         return;
381
382     // Resource possibly invokes this notifyFinished() more than
383     // once because ScriptLoader doesn't unsubscribe itself from
384     // Resource here and does it in execute() instead.
385     // We use m_resource to check if this function is already called.
386     ASSERT_UNUSED(resource, resource == m_resource);
387     if (!m_resource)
388         return;
389     if (m_resource->errorOccurred()) {
390         dispatchErrorEvent();
391         contextDocument->scriptRunner()->notifyScriptLoadError(this, m_willExecuteInOrder ? ScriptRunner::IN_ORDER_EXECUTION : ScriptRunner::ASYNC_EXECUTION);
392         return;
393     }
394     if (m_willExecuteInOrder)
395         contextDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::IN_ORDER_EXECUTION);
396     else
397         contextDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::ASYNC_EXECUTION);
398
399     m_resource = 0;
400 }
401
402 bool ScriptLoader::ignoresLoadRequest() const
403 {
404     return m_alreadyStarted || m_isExternalScript || m_parserInserted || !element() || !element()->inDocument();
405 }
406
407 bool ScriptLoader::isScriptForEventSupported() const
408 {
409     String eventAttribute = client()->eventAttributeValue();
410     String forAttribute = client()->forAttributeValue();
411     if (!eventAttribute.isEmpty() && !forAttribute.isEmpty()) {
412         forAttribute = forAttribute.stripWhiteSpace();
413         if (!equalIgnoringCase(forAttribute, "window"))
414             return false;
415
416         eventAttribute = eventAttribute.stripWhiteSpace();
417         if (!equalIgnoringCase(eventAttribute, "onload") && !equalIgnoringCase(eventAttribute, "onload()"))
418             return false;
419     }
420     return true;
421 }
422
423 String ScriptLoader::scriptContent() const
424 {
425     return m_element->textFromChildren();
426 }
427
428 ScriptLoaderClient* ScriptLoader::client() const
429 {
430     if (isHTMLScriptLoader(m_element))
431         return toHTMLScriptElement(m_element);
432
433     if (isSVGScriptLoader(m_element))
434         return toSVGScriptElement(m_element);
435
436     ASSERT_NOT_REACHED();
437     return 0;
438 }
439
440 ScriptLoader* toScriptLoaderIfPossible(Element* element)
441 {
442     if (isHTMLScriptLoader(element))
443         return toHTMLScriptElement(element)->loader();
444
445     if (isSVGScriptLoader(element))
446         return toSVGScriptElement(element)->loader();
447
448     return 0;
449 }
450
451 }