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