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/dom/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/html/HTMLImport.h" 39 #include "core/html/HTMLScriptElement.h" 40 #include "core/html/parser/HTMLParserIdioms.h" 41 #include "core/loader/cache/FetchRequest.h" 42 #include "core/loader/cache/ResourceFetcher.h" 43 #include "core/loader/cache/ScriptResource.h" 44 #include "core/page/ContentSecurityPolicy.h" 45 #include "core/page/Frame.h" 46 #include "core/platform/MIMETypeRegistry.h" 47 #include "core/svg/SVGScriptElement.h" 48 #include "weborigin/SecurityOrigin.h" 49 #include "wtf/StdLibExtras.h" 50 #include "wtf/text/StringBuilder.h" 51 #include "wtf/text/StringHash.h" 52 #include "wtf/text/TextPosition.h" 53 54 namespace WebCore { 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::insertedInto(ContainerNode* insertionPoint) 81 { 82 if (insertionPoint->inDocument() && !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(eventNames().errorEvent, false, false)); 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 Document* ScriptLoader::executingDocument() const 170 { 171 Document* document = m_element->document(); 172 if (!document->import()) 173 return document; 174 return document->import()->master(); 175 } 176 177 // http://dev.w3.org/html5/spec/Overview.html#prepare-a-script 178 bool ScriptLoader::prepareScript(const TextPosition& scriptStartPosition, LegacyTypeSupport supportLegacyTypes) 179 { 180 if (m_alreadyStarted) 181 return false; 182 183 ScriptLoaderClient* client = this->client(); 184 185 bool wasParserInserted; 186 if (m_parserInserted) { 187 wasParserInserted = true; 188 m_parserInserted = false; 189 } else { 190 wasParserInserted = false; 191 } 192 193 if (wasParserInserted && !client->asyncAttributeValue()) 194 m_forceAsync = true; 195 196 // FIXME: HTML5 spec says we should check that all children are either comments or empty text nodes. 197 if (!client->hasSourceAttribute() && !m_element->firstChild()) 198 return false; 199 200 if (!m_element->inDocument()) 201 return false; 202 203 if (!isScriptTypeSupported(supportLegacyTypes)) 204 return false; 205 206 if (wasParserInserted) { 207 m_parserInserted = true; 208 m_forceAsync = false; 209 } 210 211 m_alreadyStarted = true; 212 213 // FIXME: If script is parser inserted, verify it's still in the original document. 214 Document* executingDocument = this->executingDocument(); 215 Document* elementDocument = m_element->document(); 216 217 // FIXME: Eventually we'd like to evaluate scripts which are inserted into a 218 // viewless document but this'll do for now. 219 // See http://bugs.webkit.org/show_bug.cgi?id=5727 220 if (!executingDocument->frame()) 221 return false; 222 223 if (!executingDocument->frame()->script()->canExecuteScripts(AboutToExecuteScript)) 224 return false; 225 226 if (!isScriptForEventSupported()) 227 return false; 228 229 if (!client->charsetAttributeValue().isEmpty()) 230 m_characterEncoding = client->charsetAttributeValue(); 231 else 232 m_characterEncoding = elementDocument->charset(); 233 234 if (client->hasSourceAttribute()) { 235 if (!requestScript(client->sourceAttributeValue())) 236 return false; 237 } 238 239 if (client->hasSourceAttribute() && client->deferAttributeValue() && m_parserInserted && !client->asyncAttributeValue()) { 240 m_willExecuteWhenDocumentFinishedParsing = true; 241 m_willBeParserExecuted = true; 242 } else if (client->hasSourceAttribute() && m_parserInserted && !client->asyncAttributeValue()) { 243 m_willBeParserExecuted = true; 244 } else if (!client->hasSourceAttribute() && m_parserInserted && !elementDocument->haveStylesheetsAndImportsLoaded()) { 245 m_willBeParserExecuted = true; 246 m_readyToBeParserExecuted = true; 247 } else if (client->hasSourceAttribute() && !client->asyncAttributeValue() && !m_forceAsync) { 248 m_willExecuteInOrder = true; 249 executingDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::IN_ORDER_EXECUTION); 250 m_resource->addClient(this); 251 } else if (client->hasSourceAttribute()) { 252 executingDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::ASYNC_EXECUTION); 253 m_resource->addClient(this); 254 } else { 255 // Reset line numbering for nested writes. 256 TextPosition position = elementDocument->isInDocumentWrite() ? TextPosition() : scriptStartPosition; 257 KURL scriptURL = (!elementDocument->isInDocumentWrite() && m_parserInserted) ? elementDocument->url() : KURL(); 258 executeScript(ScriptSourceCode(scriptContent(), scriptURL, position)); 259 } 260 261 return true; 262 } 263 264 bool ScriptLoader::requestScript(const String& sourceUrl) 265 { 266 ASSERT(m_element); 267 268 RefPtr<Document> elementDocument = m_element->document(); 269 if (!m_element->dispatchBeforeLoadEvent(sourceUrl)) 270 return false; 271 if (!m_element->inDocument() || m_element->document() != elementDocument) 272 return false; 273 274 ASSERT(!m_resource); 275 if (!stripLeadingAndTrailingHTMLSpaces(sourceUrl).isEmpty()) { 276 FetchRequest request(ResourceRequest(elementDocument->completeURL(sourceUrl)), m_element->localName()); 277 278 String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr); 279 if (!crossOriginMode.isNull()) { 280 StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials; 281 request.setPotentiallyCrossOriginEnabled(elementDocument->securityOrigin(), allowCredentials); 282 } 283 request.setCharset(scriptCharset()); 284 285 bool isValidScriptNonce = elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)); 286 if (isValidScriptNonce) 287 request.setContentSecurityCheck(DoNotCheckContentSecurityPolicy); 288 289 m_resource = elementDocument->fetcher()->requestScript(request); 290 m_isExternalScript = true; 291 } 292 293 if (m_resource) { 294 return true; 295 } 296 297 dispatchErrorEvent(); 298 return false; 299 } 300 301 bool isHTMLScriptLoader(Element* element) 302 { 303 return element->hasTagName(HTMLNames::scriptTag); 304 } 305 306 bool isSVGScriptLoader(Element* element) 307 { 308 return element->hasTagName(SVGNames::scriptTag); 309 } 310 311 void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode) 312 { 313 ASSERT(m_alreadyStarted); 314 315 if (sourceCode.isEmpty()) 316 return; 317 318 RefPtr<Document> executingDocument = this->executingDocument(); 319 RefPtr<Document> elementDocument = m_element->document(); 320 Frame* frame = executingDocument->frame(); 321 322 bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script()->shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)); 323 324 if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber))) 325 return; 326 327 if (m_isExternalScript && m_resource && !m_resource->mimeTypeAllowedByNosniff()) { 328 executingDocument->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."); 329 return; 330 } 331 332 if (frame) { 333 IgnoreDestructiveWriteCountIncrementer ignoreDesctructiveWriteCountIncrementer(m_isExternalScript ? executingDocument.get() : 0); 334 335 if (isHTMLScriptLoader(m_element)) 336 executingDocument->pushCurrentScript(toHTMLScriptElement(m_element)); 337 338 AccessControlStatus corsCheck = NotSharableCrossOrigin; 339 if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document()->securityOrigin())) 340 corsCheck = SharableCrossOrigin; 341 342 // Create a script from the script element node, using the script 343 // block's source and the script block's type. 344 // Note: This is where the script is compiled and actually executed. 345 frame->script()->executeScriptInMainWorld(sourceCode, corsCheck); 346 347 if (isHTMLScriptLoader(m_element)) { 348 ASSERT(executingDocument->currentScript() == m_element); 349 executingDocument->popCurrentScript(); 350 } 351 } 352 } 353 354 void ScriptLoader::stopLoadRequest() 355 { 356 if (m_resource) { 357 if (!m_willBeParserExecuted) 358 m_resource->removeClient(this); 359 m_resource = 0; 360 } 361 } 362 363 void ScriptLoader::execute(ScriptResource* resource) 364 { 365 ASSERT(!m_willBeParserExecuted); 366 ASSERT(resource); 367 if (resource->errorOccurred()) { 368 dispatchErrorEvent(); 369 } else if (!resource->wasCanceled()) { 370 executeScript(ScriptSourceCode(resource)); 371 dispatchLoadEvent(); 372 } 373 resource->removeClient(this); 374 } 375 376 void ScriptLoader::notifyFinished(Resource* resource) 377 { 378 ASSERT(!m_willBeParserExecuted); 379 380 RefPtr<Document> executingDocument = this->executingDocument(); 381 RefPtr<Document> elementDocument = m_element->document(); 382 383 // Resource possibly invokes this notifyFinished() more than 384 // once because ScriptLoader doesn't unsubscribe itself from 385 // Resource here and does it in execute() instead. 386 // We use m_resource to check if this function is already called. 387 ASSERT_UNUSED(resource, resource == m_resource); 388 if (!m_resource) 389 return; 390 if (!elementDocument->fetcher()->canAccess(m_resource.get())) { 391 dispatchErrorEvent(); 392 return; 393 } 394 395 if (m_willExecuteInOrder) 396 executingDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::IN_ORDER_EXECUTION); 397 else 398 executingDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::ASYNC_EXECUTION); 399 400 m_resource = 0; 401 } 402 403 bool ScriptLoader::ignoresLoadRequest() const 404 { 405 return m_alreadyStarted || m_isExternalScript || m_parserInserted || !element() || !element()->inDocument(); 406 } 407 408 bool ScriptLoader::isScriptForEventSupported() const 409 { 410 String eventAttribute = client()->eventAttributeValue(); 411 String forAttribute = client()->forAttributeValue(); 412 if (!eventAttribute.isEmpty() && !forAttribute.isEmpty()) { 413 forAttribute = forAttribute.stripWhiteSpace(); 414 if (!equalIgnoringCase(forAttribute, "window")) 415 return false; 416 417 eventAttribute = eventAttribute.stripWhiteSpace(); 418 if (!equalIgnoringCase(eventAttribute, "onload") && !equalIgnoringCase(eventAttribute, "onload()")) 419 return false; 420 } 421 return true; 422 } 423 424 String ScriptLoader::scriptContent() const 425 { 426 return m_element->textFromChildren(); 427 } 428 429 ScriptLoaderClient* ScriptLoader::client() const 430 { 431 if (isHTMLScriptLoader(m_element)) 432 return toHTMLScriptElement(m_element); 433 434 if (isSVGScriptLoader(m_element)) 435 return toSVGScriptElement(m_element); 436 437 ASSERT_NOT_REACHED(); 438 return 0; 439 } 440 441 ScriptLoader* toScriptLoaderIfPossible(Element* element) 442 { 443 if (isHTMLScriptLoader(element)) 444 return toHTMLScriptElement(element)->loader(); 445 446 if (isSVGScriptLoader(element)) 447 return toSVGScriptElement(element)->loader(); 448 449 return 0; 450 } 451 452 } 453