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 "HTMLNames.h" 28 #include "SVGNames.h" 29 #include "bindings/v8/ScriptController.h" 30 #include "bindings/v8/ScriptSourceCode.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/HTMLImport.h" 42 #include "core/html/HTMLScriptElement.h" 43 #include "core/html/parser/HTMLParserIdioms.h" 44 #include "core/frame/ContentSecurityPolicy.h" 45 #include "core/frame/Frame.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 , m_isPotentiallyCORSEnabled(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("javascript"); 120 languages.add("javascript1.0"); 121 languages.add("javascript1.1"); 122 languages.add("javascript1.2"); 123 languages.add("javascript1.3"); 124 languages.add("javascript1.4"); 125 languages.add("javascript1.5"); 126 languages.add("javascript1.6"); 127 languages.add("javascript1.7"); 128 languages.add("livescript"); 129 languages.add("ecmascript"); 130 languages.add("jscript"); 131 } 132 133 return languages.contains(language); 134 } 135 136 void ScriptLoader::dispatchErrorEvent() 137 { 138 m_element->dispatchEvent(Event::create(EventTypeNames::error)); 139 } 140 141 void ScriptLoader::dispatchLoadEvent() 142 { 143 if (ScriptLoaderClient* client = this->client()) 144 client->dispatchLoadEvent(); 145 setHaveFiredLoadEvent(true); 146 } 147 148 bool ScriptLoader::isScriptTypeSupported(LegacyTypeSupport supportLegacyTypes) const 149 { 150 // FIXME: isLegacySupportedJavaScriptLanguage() is not valid HTML5. It is used here to maintain backwards compatibility with existing layout tests. The specific violations are: 151 // - Allowing type=javascript. type= should only support MIME types, such as text/javascript. 152 // - Allowing a different set of languages for language= and type=. language= supports Javascript 1.1 and 1.4-1.6, but type= does not. 153 154 String type = client()->typeAttributeValue(); 155 String language = client()->languageAttributeValue(); 156 if (type.isEmpty() && language.isEmpty()) 157 return true; // Assume text/javascript. 158 if (type.isEmpty()) { 159 type = "text/" + language.lower(); 160 if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(type) || isLegacySupportedJavaScriptLanguage(language)) 161 return true; 162 } else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(type.stripWhiteSpace().lower()) || (supportLegacyTypes == AllowLegacyTypeInTypeAttribute && isLegacySupportedJavaScriptLanguage(type))) { 163 return true; 164 } 165 166 return false; 167 } 168 169 // http://dev.w3.org/html5/spec/Overview.html#prepare-a-script 170 bool ScriptLoader::prepareScript(const TextPosition& scriptStartPosition, LegacyTypeSupport supportLegacyTypes) 171 { 172 if (m_alreadyStarted) 173 return false; 174 175 ScriptLoaderClient* client = this->client(); 176 177 bool wasParserInserted; 178 if (m_parserInserted) { 179 wasParserInserted = true; 180 m_parserInserted = false; 181 } else { 182 wasParserInserted = false; 183 } 184 185 if (wasParserInserted && !client->asyncAttributeValue()) 186 m_forceAsync = true; 187 188 // FIXME: HTML5 spec says we should check that all children are either comments or empty text nodes. 189 if (!client->hasSourceAttribute() && !m_element->firstChild()) 190 return false; 191 192 if (!m_element->inDocument()) 193 return false; 194 195 if (!isScriptTypeSupported(supportLegacyTypes)) 196 return false; 197 198 if (wasParserInserted) { 199 m_parserInserted = true; 200 m_forceAsync = false; 201 } 202 203 m_alreadyStarted = true; 204 205 // FIXME: If script is parser inserted, verify it's still in the original document. 206 Document& elementDocument = m_element->document(); 207 Document* contextDocument = elementDocument.contextDocument().get(); 208 209 if (!contextDocument || !contextDocument->allowExecutingScripts(m_element)) 210 return false; 211 212 if (!isScriptForEventSupported()) 213 return false; 214 215 if (!client->charsetAttributeValue().isEmpty()) 216 m_characterEncoding = client->charsetAttributeValue(); 217 else 218 m_characterEncoding = elementDocument.charset(); 219 220 if (client->hasSourceAttribute()) { 221 if (!fetchScript(client->sourceAttributeValue())) 222 return false; 223 } 224 225 if (client->hasSourceAttribute() && client->deferAttributeValue() && m_parserInserted && !client->asyncAttributeValue()) { 226 m_willExecuteWhenDocumentFinishedParsing = true; 227 m_willBeParserExecuted = true; 228 } else if (client->hasSourceAttribute() && m_parserInserted && !client->asyncAttributeValue()) { 229 m_willBeParserExecuted = true; 230 } else if (!client->hasSourceAttribute() && m_parserInserted && !elementDocument.haveStylesheetsAndImportsLoaded()) { 231 m_willBeParserExecuted = true; 232 m_readyToBeParserExecuted = true; 233 } else if (client->hasSourceAttribute() && !client->asyncAttributeValue() && !m_forceAsync) { 234 m_willExecuteInOrder = true; 235 contextDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::IN_ORDER_EXECUTION); 236 m_resource->addClient(this); 237 } else if (client->hasSourceAttribute()) { 238 contextDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::ASYNC_EXECUTION); 239 m_resource->addClient(this); 240 } else { 241 // Reset line numbering for nested writes. 242 TextPosition position = elementDocument.isInDocumentWrite() ? TextPosition() : scriptStartPosition; 243 KURL scriptURL = (!elementDocument.isInDocumentWrite() && m_parserInserted) ? elementDocument.url() : KURL(); 244 if (!executePotentiallyCrossOriginScript(ScriptSourceCode(scriptContent(), scriptURL, position))) 245 return false; 246 } 247 248 return true; 249 } 250 251 bool ScriptLoader::fetchScript(const String& sourceUrl) 252 { 253 ASSERT(m_element); 254 255 RefPtr<Document> elementDocument(m_element->document()); 256 if (!m_element->dispatchBeforeLoadEvent(sourceUrl)) 257 return false; 258 if (!m_element->inDocument() || m_element->document() != elementDocument) 259 return false; 260 261 ASSERT(!m_resource); 262 if (!stripLeadingAndTrailingHTMLSpaces(sourceUrl).isEmpty()) { 263 FetchRequest request(ResourceRequest(elementDocument->completeURL(sourceUrl)), m_element->localName()); 264 265 String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr); 266 if (!crossOriginMode.isNull()) { 267 StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials; 268 request.setCrossOriginAccessControl(elementDocument->securityOrigin(), allowCredentials); 269 m_isPotentiallyCORSEnabled = true; 270 } 271 request.setCharset(scriptCharset()); 272 273 bool isValidScriptNonce = elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)); 274 if (isValidScriptNonce) 275 request.setContentSecurityCheck(DoNotCheckContentSecurityPolicy); 276 277 m_resource = elementDocument->fetcher()->fetchScript(request); 278 m_isExternalScript = true; 279 } 280 281 if (m_resource) 282 return true; 283 284 dispatchErrorEvent(); 285 return false; 286 } 287 288 bool isHTMLScriptLoader(Element* element) 289 { 290 return element->hasTagName(HTMLNames::scriptTag); 291 } 292 293 bool isSVGScriptLoader(Element* element) 294 { 295 return element->hasTagName(SVGNames::scriptTag); 296 } 297 298 void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode) 299 { 300 ASSERT(m_alreadyStarted); 301 302 if (sourceCode.isEmpty()) 303 return; 304 305 RefPtr<Document> elementDocument(m_element->document()); 306 RefPtr<Document> contextDocument = elementDocument->contextDocument().get(); 307 if (!contextDocument) 308 return; 309 310 Frame* frame = contextDocument->frame(); 311 312 bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source()); 313 314 if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber))) 315 return; 316 317 if (m_isExternalScript && m_resource && !m_resource->mimeTypeAllowedByNosniff()) { 318 contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_resource->url().elidedString() + "' because its MIME type ('" + m_resource->mimeType() + "') is not executable, and strict MIME type checking is enabled."); 319 return; 320 } 321 322 if (frame) { 323 IgnoreDestructiveWriteCountIncrementer ignoreDesctructiveWriteCountIncrementer(m_isExternalScript ? contextDocument.get() : 0); 324 325 if (isHTMLScriptLoader(m_element)) 326 contextDocument->pushCurrentScript(toHTMLScriptElement(m_element)); 327 328 AccessControlStatus corsCheck = NotSharableCrossOrigin; 329 if (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 bool ScriptLoader::executePotentiallyCrossOriginScript(const ScriptSourceCode& sourceCode) 367 { 368 if (sourceCode.resource() 369 && isPotentiallyCORSEnabled() 370 && !m_element->document().fetcher()->canAccess(sourceCode.resource(), PotentiallyCORSEnabled)) { 371 dispatchErrorEvent(); 372 return false; 373 } 374 executeScript(sourceCode); 375 return true; 376 } 377 378 void ScriptLoader::notifyFinished(Resource* resource) 379 { 380 ASSERT(!m_willBeParserExecuted); 381 382 RefPtr<Document> elementDocument(m_element->document()); 383 RefPtr<Document> contextDocument = elementDocument->contextDocument().get(); 384 if (!contextDocument) 385 return; 386 387 // Resource possibly invokes this notifyFinished() more than 388 // once because ScriptLoader doesn't unsubscribe itself from 389 // Resource here and does it in execute() instead. 390 // We use m_resource to check if this function is already called. 391 ASSERT_UNUSED(resource, resource == m_resource); 392 if (!m_resource) 393 return; 394 CORSEnabled corsEnabled = isPotentiallyCORSEnabled() ? PotentiallyCORSEnabled : NotCORSEnabled; 395 if (!elementDocument->fetcher()->canAccess(m_resource.get(), corsEnabled)) { 396 dispatchErrorEvent(); 397 contextDocument->scriptRunner()->notifyScriptLoadError(this, m_willExecuteInOrder ? ScriptRunner::IN_ORDER_EXECUTION : ScriptRunner::ASYNC_EXECUTION); 398 return; 399 } 400 401 if (m_willExecuteInOrder) 402 contextDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::IN_ORDER_EXECUTION); 403 else 404 contextDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::ASYNC_EXECUTION); 405 406 m_resource = 0; 407 } 408 409 bool ScriptLoader::ignoresLoadRequest() const 410 { 411 return m_alreadyStarted || m_isExternalScript || m_parserInserted || !element() || !element()->inDocument(); 412 } 413 414 bool ScriptLoader::isScriptForEventSupported() const 415 { 416 String eventAttribute = client()->eventAttributeValue(); 417 String forAttribute = client()->forAttributeValue(); 418 if (!eventAttribute.isEmpty() && !forAttribute.isEmpty()) { 419 forAttribute = forAttribute.stripWhiteSpace(); 420 if (!equalIgnoringCase(forAttribute, "window")) 421 return false; 422 423 eventAttribute = eventAttribute.stripWhiteSpace(); 424 if (!equalIgnoringCase(eventAttribute, "onload") && !equalIgnoringCase(eventAttribute, "onload()")) 425 return false; 426 } 427 return true; 428 } 429 430 String ScriptLoader::scriptContent() const 431 { 432 return m_element->textFromChildren(); 433 } 434 435 ScriptLoaderClient* ScriptLoader::client() const 436 { 437 if (isHTMLScriptLoader(m_element)) 438 return toHTMLScriptElement(m_element); 439 440 if (isSVGScriptLoader(m_element)) 441 return toSVGScriptElement(m_element); 442 443 ASSERT_NOT_REACHED(); 444 return 0; 445 } 446 447 ScriptLoader* toScriptLoaderIfPossible(Element* element) 448 { 449 if (isHTMLScriptLoader(element)) 450 return toHTMLScriptElement(element)->loader(); 451 452 if (isSVGScriptLoader(element)) 453 return toSVGScriptElement(element)->loader(); 454 455 return 0; 456 } 457 458 } 459