michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: // vim:cindent:ts=2:et:sw=2: michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* code for loading in @font-face defined font data */ michael@0: michael@0: #ifdef MOZ_LOGGING michael@0: #define FORCE_PR_LOG /* Allow logging in the release build */ michael@0: #endif /* MOZ_LOGGING */ michael@0: #include "prlog.h" michael@0: michael@0: #include "nsFontFaceLoader.h" michael@0: michael@0: #include "nsError.h" michael@0: #include "nsNetUtil.h" michael@0: #include "nsContentUtils.h" michael@0: #include "mozilla/Preferences.h" michael@0: michael@0: #include "nsPresContext.h" michael@0: #include "nsIPresShell.h" michael@0: #include "nsIPrincipal.h" michael@0: #include "nsIScriptSecurityManager.h" michael@0: michael@0: #include "nsIContentPolicy.h" michael@0: #include "nsContentPolicyUtils.h" michael@0: #include "nsCrossSiteListenerProxy.h" michael@0: #include "nsIContentSecurityPolicy.h" michael@0: #include "nsIDocShell.h" michael@0: #include "nsIWebNavigation.h" michael@0: #include "nsISupportsPriority.h" michael@0: #include "nsINetworkSeer.h" michael@0: michael@0: #include "nsIConsoleService.h" michael@0: michael@0: #include "nsStyleSet.h" michael@0: #include "nsPrintfCString.h" michael@0: #include "mozilla/gfx/2D.h" michael@0: michael@0: using namespace mozilla; michael@0: michael@0: #ifdef PR_LOGGING michael@0: static PRLogModuleInfo* michael@0: GetFontDownloaderLog() michael@0: { michael@0: static PRLogModuleInfo* sLog; michael@0: if (!sLog) michael@0: sLog = PR_NewLogModule("fontdownloader"); michael@0: return sLog; michael@0: } michael@0: #endif /* PR_LOGGING */ michael@0: michael@0: #define LOG(args) PR_LOG(GetFontDownloaderLog(), PR_LOG_DEBUG, args) michael@0: #define LOG_ENABLED() PR_LOG_TEST(GetFontDownloaderLog(), PR_LOG_DEBUG) michael@0: michael@0: michael@0: nsFontFaceLoader::nsFontFaceLoader(gfxMixedFontFamily* aFontFamily, michael@0: gfxProxyFontEntry* aProxy, michael@0: nsIURI* aFontURI, michael@0: nsUserFontSet* aFontSet, michael@0: nsIChannel* aChannel) michael@0: : mFontFamily(aFontFamily), michael@0: mFontEntry(aProxy), michael@0: mFontURI(aFontURI), michael@0: mFontSet(aFontSet), michael@0: mChannel(aChannel) michael@0: { michael@0: } michael@0: michael@0: nsFontFaceLoader::~nsFontFaceLoader() michael@0: { michael@0: if (mFontEntry) { michael@0: mFontEntry->mLoader = nullptr; michael@0: } michael@0: if (mLoadTimer) { michael@0: mLoadTimer->Cancel(); michael@0: mLoadTimer = nullptr; michael@0: } michael@0: if (mFontSet) { michael@0: mFontSet->RemoveLoader(this); michael@0: } michael@0: } michael@0: michael@0: void michael@0: nsFontFaceLoader::StartedLoading(nsIStreamLoader* aStreamLoader) michael@0: { michael@0: int32_t loadTimeout = michael@0: Preferences::GetInt("gfx.downloadable_fonts.fallback_delay", 3000); michael@0: if (loadTimeout > 0) { michael@0: mLoadTimer = do_CreateInstance("@mozilla.org/timer;1"); michael@0: if (mLoadTimer) { michael@0: mLoadTimer->InitWithFuncCallback(LoadTimerCallback, michael@0: static_cast(this), michael@0: loadTimeout, michael@0: nsITimer::TYPE_ONE_SHOT); michael@0: } michael@0: } else if (loadTimeout == 0) { michael@0: mFontEntry->mLoadingState = gfxProxyFontEntry::LOADING_SLOWLY; michael@0: } // -1 disables fallback michael@0: mStreamLoader = aStreamLoader; michael@0: } michael@0: michael@0: void michael@0: nsFontFaceLoader::LoadTimerCallback(nsITimer* aTimer, void* aClosure) michael@0: { michael@0: nsFontFaceLoader* loader = static_cast(aClosure); michael@0: michael@0: if (!loader->mFontSet) { michael@0: // We've been canceled michael@0: return; michael@0: } michael@0: michael@0: gfxProxyFontEntry* pe = loader->mFontEntry.get(); michael@0: bool updateUserFontSet = true; michael@0: michael@0: // If the entry is loading, check whether it's >75% done; if so, michael@0: // we allow another timeout period before showing a fallback font. michael@0: if (pe->mLoadingState == gfxProxyFontEntry::LOADING_STARTED) { michael@0: int64_t contentLength; michael@0: uint32_t numBytesRead; michael@0: if (NS_SUCCEEDED(loader->mChannel->GetContentLength(&contentLength)) && michael@0: contentLength > 0 && michael@0: contentLength < UINT32_MAX && michael@0: NS_SUCCEEDED(loader->mStreamLoader->GetNumBytesRead(&numBytesRead)) && michael@0: numBytesRead > 3 * (uint32_t(contentLength) >> 2)) michael@0: { michael@0: // More than 3/4 the data has been downloaded, so allow 50% extra michael@0: // time and hope the remainder will arrive before the additional michael@0: // time expires. michael@0: pe->mLoadingState = gfxProxyFontEntry::LOADING_ALMOST_DONE; michael@0: uint32_t delay; michael@0: loader->mLoadTimer->GetDelay(&delay); michael@0: loader->mLoadTimer->InitWithFuncCallback(LoadTimerCallback, michael@0: static_cast(loader), michael@0: delay >> 1, michael@0: nsITimer::TYPE_ONE_SHOT); michael@0: updateUserFontSet = false; michael@0: LOG(("fontdownloader (%p) 75%% done, resetting timer\n", loader)); michael@0: } michael@0: } michael@0: michael@0: // If the font is not 75% loaded, or if we've already timed out once michael@0: // before, we mark this entry as "loading slowly", so the fallback michael@0: // font will be used in the meantime, and tell the context to refresh. michael@0: if (updateUserFontSet) { michael@0: pe->mLoadingState = gfxProxyFontEntry::LOADING_SLOWLY; michael@0: gfxUserFontSet* fontSet = loader->mFontSet; michael@0: nsPresContext* ctx = loader->mFontSet->GetPresContext(); michael@0: NS_ASSERTION(ctx, "userfontset doesn't have a presContext?"); michael@0: if (ctx) { michael@0: fontSet->IncrementGeneration(); michael@0: ctx->UserFontSetUpdated(); michael@0: LOG(("fontdownloader (%p) timeout reflow\n", loader)); michael@0: } michael@0: } michael@0: } michael@0: michael@0: NS_IMPL_ISUPPORTS(nsFontFaceLoader, nsIStreamLoaderObserver) michael@0: michael@0: NS_IMETHODIMP michael@0: nsFontFaceLoader::OnStreamComplete(nsIStreamLoader* aLoader, michael@0: nsISupports* aContext, michael@0: nsresult aStatus, michael@0: uint32_t aStringLen, michael@0: const uint8_t* aString) michael@0: { michael@0: if (!mFontSet) { michael@0: // We've been canceled michael@0: return aStatus; michael@0: } michael@0: michael@0: mFontSet->RemoveLoader(this); michael@0: michael@0: #ifdef PR_LOGGING michael@0: if (LOG_ENABLED()) { michael@0: nsAutoCString fontURI; michael@0: mFontURI->GetSpec(fontURI); michael@0: if (NS_SUCCEEDED(aStatus)) { michael@0: LOG(("fontdownloader (%p) download completed - font uri: (%s)\n", michael@0: this, fontURI.get())); michael@0: } else { michael@0: LOG(("fontdownloader (%p) download failed - font uri: (%s) error: %8.8x\n", michael@0: this, fontURI.get(), aStatus)); michael@0: } michael@0: } michael@0: #endif michael@0: michael@0: nsPresContext* ctx = mFontSet->GetPresContext(); michael@0: NS_ASSERTION(ctx && !ctx->PresShell()->IsDestroying(), michael@0: "We should have been canceled already"); michael@0: michael@0: if (NS_SUCCEEDED(aStatus)) { michael@0: // for HTTP requests, check whether the request _actually_ succeeded; michael@0: // the "request status" in aStatus does not necessarily indicate this, michael@0: // because HTTP responses such as 404 (Not Found) will still result in michael@0: // a success code and potentially an HTML error page from the server michael@0: // as the resulting data. We don't want to use that as a font. michael@0: nsCOMPtr request; michael@0: nsCOMPtr httpChannel; michael@0: aLoader->GetRequest(getter_AddRefs(request)); michael@0: httpChannel = do_QueryInterface(request); michael@0: if (httpChannel) { michael@0: bool succeeded; michael@0: nsresult rv = httpChannel->GetRequestSucceeded(&succeeded); michael@0: if (NS_SUCCEEDED(rv) && !succeeded) { michael@0: aStatus = NS_ERROR_NOT_AVAILABLE; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // The userFontSet is responsible for freeing the downloaded data michael@0: // (aString) when finished with it; the pointer is no longer valid michael@0: // after OnLoadComplete returns. michael@0: // This is called even in the case of a failed download (HTTP 404, etc), michael@0: // as there may still be data to be freed (e.g. an error page), michael@0: // and we need the fontSet to initiate loading the next source. michael@0: bool fontUpdate = mFontSet->OnLoadComplete(mFontFamily, mFontEntry, aString, michael@0: aStringLen, aStatus); michael@0: michael@0: // when new font loaded, need to reflow michael@0: if (fontUpdate) { michael@0: // Update layout for the presence of the new font. Since this is michael@0: // asynchronous, reflows will coalesce. michael@0: ctx->UserFontSetUpdated(); michael@0: LOG(("fontdownloader (%p) reflow\n", this)); michael@0: } michael@0: michael@0: // done with font set michael@0: mFontSet = nullptr; michael@0: if (mLoadTimer) { michael@0: mLoadTimer->Cancel(); michael@0: mLoadTimer = nullptr; michael@0: } michael@0: michael@0: return NS_SUCCESS_ADOPTED_DATA; michael@0: } michael@0: michael@0: void michael@0: nsFontFaceLoader::Cancel() michael@0: { michael@0: mFontEntry->mLoadingState = gfxProxyFontEntry::NOT_LOADING; michael@0: mFontEntry->mLoader = nullptr; michael@0: mFontSet = nullptr; michael@0: if (mLoadTimer) { michael@0: mLoadTimer->Cancel(); michael@0: mLoadTimer = nullptr; michael@0: } michael@0: mChannel->Cancel(NS_BINDING_ABORTED); michael@0: } michael@0: michael@0: nsresult michael@0: nsFontFaceLoader::CheckLoadAllowed(nsIPrincipal* aSourcePrincipal, michael@0: nsIURI* aTargetURI, michael@0: nsISupports* aContext) michael@0: { michael@0: nsresult rv; michael@0: michael@0: if (!aSourcePrincipal) michael@0: return NS_OK; michael@0: michael@0: // check with the security manager michael@0: nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager(); michael@0: rv = secMan->CheckLoadURIWithPrincipal(aSourcePrincipal, aTargetURI, michael@0: nsIScriptSecurityManager::STANDARD); michael@0: if (NS_FAILED(rv)) { michael@0: return rv; michael@0: } michael@0: michael@0: // check content policy michael@0: int16_t shouldLoad = nsIContentPolicy::ACCEPT; michael@0: rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_FONT, michael@0: aTargetURI, michael@0: aSourcePrincipal, michael@0: aContext, michael@0: EmptyCString(), // mime type michael@0: nullptr, michael@0: &shouldLoad, michael@0: nsContentUtils::GetContentPolicy(), michael@0: nsContentUtils::GetSecurityManager()); michael@0: michael@0: if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) { michael@0: return NS_ERROR_CONTENT_BLOCKED; michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsUserFontSet::nsUserFontSet(nsPresContext* aContext) michael@0: : mPresContext(aContext) michael@0: { michael@0: NS_ASSERTION(mPresContext, "null context passed to nsUserFontSet"); michael@0: } michael@0: michael@0: nsUserFontSet::~nsUserFontSet() michael@0: { michael@0: NS_ASSERTION(mLoaders.Count() == 0, "mLoaders should have been emptied"); michael@0: } michael@0: michael@0: static PLDHashOperator DestroyIterator(nsPtrHashKey* aKey, michael@0: void* aUserArg) michael@0: { michael@0: aKey->GetKey()->Cancel(); michael@0: return PL_DHASH_REMOVE; michael@0: } michael@0: michael@0: void michael@0: nsUserFontSet::Destroy() michael@0: { michael@0: mPresContext = nullptr; michael@0: mLoaders.EnumerateEntries(DestroyIterator, nullptr); michael@0: mRules.Clear(); michael@0: } michael@0: michael@0: void michael@0: nsUserFontSet::RemoveLoader(nsFontFaceLoader* aLoader) michael@0: { michael@0: mLoaders.RemoveEntry(aLoader); michael@0: } michael@0: michael@0: nsresult michael@0: nsUserFontSet::StartLoad(gfxMixedFontFamily* aFamily, michael@0: gfxProxyFontEntry* aProxy, michael@0: const gfxFontFaceSrc* aFontFaceSrc) michael@0: { michael@0: nsresult rv; michael@0: michael@0: nsIPresShell* ps = mPresContext->PresShell(); michael@0: if (!ps) michael@0: return NS_ERROR_FAILURE; michael@0: michael@0: nsCOMPtr streamLoader; michael@0: nsCOMPtr loadGroup(ps->GetDocument()->GetDocumentLoadGroup()); michael@0: michael@0: nsCOMPtr channel; michael@0: // get Content Security Policy from principal to pass into channel michael@0: nsCOMPtr channelPolicy; michael@0: nsCOMPtr csp; michael@0: rv = aProxy->mPrincipal->GetCsp(getter_AddRefs(csp)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: if (csp) { michael@0: channelPolicy = do_CreateInstance("@mozilla.org/nschannelpolicy;1"); michael@0: channelPolicy->SetContentSecurityPolicy(csp); michael@0: channelPolicy->SetLoadType(nsIContentPolicy::TYPE_FONT); michael@0: } michael@0: rv = NS_NewChannel(getter_AddRefs(channel), michael@0: aFontFaceSrc->mURI, michael@0: nullptr, michael@0: loadGroup, michael@0: nullptr, michael@0: nsIRequest::LOAD_NORMAL, michael@0: channelPolicy); michael@0: michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: nsRefPtr fontLoader = michael@0: new nsFontFaceLoader(aFamily, aProxy, aFontFaceSrc->mURI, this, channel); michael@0: michael@0: if (!fontLoader) michael@0: return NS_ERROR_OUT_OF_MEMORY; michael@0: michael@0: #ifdef PR_LOGGING michael@0: if (LOG_ENABLED()) { michael@0: nsAutoCString fontURI, referrerURI; michael@0: aFontFaceSrc->mURI->GetSpec(fontURI); michael@0: if (aFontFaceSrc->mReferrer) michael@0: aFontFaceSrc->mReferrer->GetSpec(referrerURI); michael@0: LOG(("fontdownloader (%p) download start - font uri: (%s) " michael@0: "referrer uri: (%s)\n", michael@0: fontLoader.get(), fontURI.get(), referrerURI.get())); michael@0: } michael@0: #endif michael@0: michael@0: nsCOMPtr httpChannel(do_QueryInterface(channel)); michael@0: if (httpChannel) michael@0: httpChannel->SetReferrer(aFontFaceSrc->mReferrer); michael@0: nsCOMPtr priorityChannel(do_QueryInterface(channel)); michael@0: if (priorityChannel) { michael@0: priorityChannel->AdjustPriority(nsISupportsPriority::PRIORITY_HIGH); michael@0: } michael@0: michael@0: rv = NS_NewStreamLoader(getter_AddRefs(streamLoader), fontLoader); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: nsIDocument *document = ps->GetDocument(); michael@0: mozilla::net::SeerLearn(aFontFaceSrc->mURI, document->GetDocumentURI(), michael@0: nsINetworkSeer::LEARN_LOAD_SUBRESOURCE, loadGroup); michael@0: michael@0: bool inherits = false; michael@0: rv = NS_URIChainHasFlags(aFontFaceSrc->mURI, michael@0: nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT, michael@0: &inherits); michael@0: if (NS_SUCCEEDED(rv) && inherits) { michael@0: // allow data, javascript, etc URI's michael@0: rv = channel->AsyncOpen(streamLoader, nullptr); michael@0: } else { michael@0: nsRefPtr listener = michael@0: new nsCORSListenerProxy(streamLoader, aProxy->mPrincipal, false); michael@0: rv = listener->Init(channel); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: rv = channel->AsyncOpen(listener, nullptr); michael@0: } michael@0: if (NS_FAILED(rv)) { michael@0: fontLoader->DropChannel(); // explicitly need to break ref cycle michael@0: } michael@0: } michael@0: michael@0: if (NS_SUCCEEDED(rv)) { michael@0: mLoaders.PutEntry(fontLoader); michael@0: fontLoader->StartedLoading(streamLoader); michael@0: aProxy->mLoader = fontLoader; // let the font entry remember the loader, michael@0: // in case we need to cancel it michael@0: } michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: static PLDHashOperator DetachFontEntries(const nsAString& aKey, michael@0: nsRefPtr& aFamily, michael@0: void* aUserArg) michael@0: { michael@0: aFamily->DetachFontEntries(); michael@0: return PL_DHASH_NEXT; michael@0: } michael@0: michael@0: static PLDHashOperator RemoveIfEmpty(const nsAString& aKey, michael@0: nsRefPtr& aFamily, michael@0: void* aUserArg) michael@0: { michael@0: return aFamily->GetFontList().Length() ? PL_DHASH_NEXT : PL_DHASH_REMOVE; michael@0: } michael@0: michael@0: bool michael@0: nsUserFontSet::UpdateRules(const nsTArray& aRules) michael@0: { michael@0: bool modified = false; michael@0: michael@0: // The @font-face rules that make up the user font set have changed, michael@0: // so we need to update the set. However, we want to preserve existing michael@0: // font entries wherever possible, so that we don't discard and then michael@0: // re-download resources in the (common) case where at least some of the michael@0: // same rules are still present. michael@0: michael@0: nsTArray oldRules; michael@0: mRules.SwapElements(oldRules); michael@0: michael@0: // Remove faces from the font family records; we need to re-insert them michael@0: // because we might end up with faces in a different order even if they're michael@0: // the same font entries as before. (The order can affect font selection michael@0: // where multiple faces match the requested style, perhaps with overlapping michael@0: // unicode-range coverage.) michael@0: mFontFamilies.Enumerate(DetachFontEntries, nullptr); michael@0: michael@0: for (uint32_t i = 0, i_end = aRules.Length(); i < i_end; ++i) { michael@0: // Insert each rule into our list, migrating old font entries if possible michael@0: // rather than creating new ones; set modified to true if we detect michael@0: // that rule ordering has changed, or if a new entry is created. michael@0: InsertRule(aRules[i].mRule, aRules[i].mSheetType, oldRules, modified); michael@0: } michael@0: michael@0: // Remove any residual families that have no font entries (i.e., they were michael@0: // not defined at all by the updated set of @font-face rules). michael@0: mFontFamilies.Enumerate(RemoveIfEmpty, nullptr); michael@0: michael@0: // If any rules are left in the old list, note that the set has changed michael@0: // (even if the new set was built entirely by migrating old font entries). michael@0: if (oldRules.Length() > 0) { michael@0: modified = true; michael@0: // Any in-progress loaders for obsolete rules should be cancelled, michael@0: // as the resource being downloaded will no longer be required. michael@0: // We need to explicitly remove any loaders here, otherwise the loaders michael@0: // will keep their "orphaned" font entries alive until they complete, michael@0: // even after the oldRules array is deleted. michael@0: size_t count = oldRules.Length(); michael@0: for (size_t i = 0; i < count; ++i) { michael@0: gfxFontEntry* fe = oldRules[i].mFontEntry; michael@0: if (!fe->mIsProxy) { michael@0: continue; michael@0: } michael@0: gfxProxyFontEntry* proxy = static_cast(fe); michael@0: nsFontFaceLoader* loader = proxy->mLoader; michael@0: if (loader) { michael@0: loader->Cancel(); michael@0: RemoveLoader(loader); michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (modified) { michael@0: IncrementGeneration(); michael@0: } michael@0: michael@0: // local rules have been rebuilt, so clear the flag michael@0: mLocalRulesUsed = false; michael@0: michael@0: return modified; michael@0: } michael@0: michael@0: static bool michael@0: HasLocalSrc(const nsCSSValue::Array *aSrcArr) michael@0: { michael@0: size_t numSrc = aSrcArr->Count(); michael@0: for (size_t i = 0; i < numSrc; i++) { michael@0: if (aSrcArr->Item(i).GetUnit() == eCSSUnit_Local_Font) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: void michael@0: nsUserFontSet::InsertRule(nsCSSFontFaceRule* aRule, uint8_t aSheetType, michael@0: nsTArray& aOldRules, michael@0: bool& aFontSetModified) michael@0: { michael@0: NS_ABORT_IF_FALSE(aRule->GetType() == mozilla::css::Rule::FONT_FACE_RULE, michael@0: "InsertRule passed a non-fontface CSS rule"); michael@0: michael@0: // set up family name michael@0: nsAutoString fontfamily; michael@0: nsCSSValue val; michael@0: uint32_t unit; michael@0: michael@0: aRule->GetDesc(eCSSFontDesc_Family, val); michael@0: unit = val.GetUnit(); michael@0: if (unit == eCSSUnit_String) { michael@0: val.GetStringValue(fontfamily); michael@0: } else { michael@0: NS_ASSERTION(unit == eCSSUnit_Null, michael@0: "@font-face family name has unexpected unit"); michael@0: } michael@0: if (fontfamily.IsEmpty()) { michael@0: // If there is no family name, this rule cannot contribute a michael@0: // usable font, so there is no point in processing it further. michael@0: return; michael@0: } michael@0: michael@0: // first, we check in oldRules; if the rule exists there, just move it michael@0: // to the new rule list, and put the entry into the appropriate family michael@0: for (uint32_t i = 0; i < aOldRules.Length(); ++i) { michael@0: const FontFaceRuleRecord& ruleRec = aOldRules[i]; michael@0: michael@0: if (ruleRec.mContainer.mRule == aRule && michael@0: ruleRec.mContainer.mSheetType == aSheetType) { michael@0: michael@0: // if local rules were used, don't use the old font entry michael@0: // for rules containing src local usage michael@0: if (mLocalRulesUsed) { michael@0: aRule->GetDesc(eCSSFontDesc_Src, val); michael@0: unit = val.GetUnit(); michael@0: if (unit == eCSSUnit_Array && HasLocalSrc(val.GetArrayValue())) { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: AddFontFace(fontfamily, ruleRec.mFontEntry); michael@0: mRules.AppendElement(ruleRec); michael@0: aOldRules.RemoveElementAt(i); michael@0: // note the set has been modified if an old rule was skipped to find michael@0: // this one - something has been dropped, or ordering changed michael@0: if (i > 0) { michael@0: aFontSetModified = true; michael@0: } michael@0: return; michael@0: } michael@0: } michael@0: michael@0: // this is a new rule: michael@0: michael@0: uint32_t weight = NS_STYLE_FONT_WEIGHT_NORMAL; michael@0: int32_t stretch = NS_STYLE_FONT_STRETCH_NORMAL; michael@0: uint32_t italicStyle = NS_STYLE_FONT_STYLE_NORMAL; michael@0: nsString languageOverride; michael@0: michael@0: // set up weight michael@0: aRule->GetDesc(eCSSFontDesc_Weight, val); michael@0: unit = val.GetUnit(); michael@0: if (unit == eCSSUnit_Integer || unit == eCSSUnit_Enumerated) { michael@0: weight = val.GetIntValue(); michael@0: } else if (unit == eCSSUnit_Normal) { michael@0: weight = NS_STYLE_FONT_WEIGHT_NORMAL; michael@0: } else { michael@0: NS_ASSERTION(unit == eCSSUnit_Null, michael@0: "@font-face weight has unexpected unit"); michael@0: } michael@0: michael@0: // set up stretch michael@0: aRule->GetDesc(eCSSFontDesc_Stretch, val); michael@0: unit = val.GetUnit(); michael@0: if (unit == eCSSUnit_Enumerated) { michael@0: stretch = val.GetIntValue(); michael@0: } else if (unit == eCSSUnit_Normal) { michael@0: stretch = NS_STYLE_FONT_STRETCH_NORMAL; michael@0: } else { michael@0: NS_ASSERTION(unit == eCSSUnit_Null, michael@0: "@font-face stretch has unexpected unit"); michael@0: } michael@0: michael@0: // set up font style michael@0: aRule->GetDesc(eCSSFontDesc_Style, val); michael@0: unit = val.GetUnit(); michael@0: if (unit == eCSSUnit_Enumerated) { michael@0: italicStyle = val.GetIntValue(); michael@0: } else if (unit == eCSSUnit_Normal) { michael@0: italicStyle = NS_STYLE_FONT_STYLE_NORMAL; michael@0: } else { michael@0: NS_ASSERTION(unit == eCSSUnit_Null, michael@0: "@font-face style has unexpected unit"); michael@0: } michael@0: michael@0: // set up font features michael@0: nsTArray featureSettings; michael@0: aRule->GetDesc(eCSSFontDesc_FontFeatureSettings, val); michael@0: unit = val.GetUnit(); michael@0: if (unit == eCSSUnit_Normal) { michael@0: // empty list of features michael@0: } else if (unit == eCSSUnit_PairList || unit == eCSSUnit_PairListDep) { michael@0: nsRuleNode::ComputeFontFeatures(val.GetPairListValue(), featureSettings); michael@0: } else { michael@0: NS_ASSERTION(unit == eCSSUnit_Null, michael@0: "@font-face font-feature-settings has unexpected unit"); michael@0: } michael@0: michael@0: // set up font language override michael@0: aRule->GetDesc(eCSSFontDesc_FontLanguageOverride, val); michael@0: unit = val.GetUnit(); michael@0: if (unit == eCSSUnit_Normal) { michael@0: // empty feature string michael@0: } else if (unit == eCSSUnit_String) { michael@0: val.GetStringValue(languageOverride); michael@0: } else { michael@0: NS_ASSERTION(unit == eCSSUnit_Null, michael@0: "@font-face font-language-override has unexpected unit"); michael@0: } michael@0: michael@0: // set up src array michael@0: nsTArray srcArray; michael@0: michael@0: aRule->GetDesc(eCSSFontDesc_Src, val); michael@0: unit = val.GetUnit(); michael@0: if (unit == eCSSUnit_Array) { michael@0: nsCSSValue::Array* srcArr = val.GetArrayValue(); michael@0: size_t numSrc = srcArr->Count(); michael@0: michael@0: for (size_t i = 0; i < numSrc; i++) { michael@0: val = srcArr->Item(i); michael@0: unit = val.GetUnit(); michael@0: gfxFontFaceSrc* face = srcArray.AppendElements(1); michael@0: if (!face) michael@0: return; michael@0: michael@0: switch (unit) { michael@0: michael@0: case eCSSUnit_Local_Font: michael@0: val.GetStringValue(face->mLocalName); michael@0: face->mIsLocal = true; michael@0: face->mURI = nullptr; michael@0: face->mFormatFlags = 0; michael@0: break; michael@0: case eCSSUnit_URL: michael@0: face->mIsLocal = false; michael@0: face->mURI = val.GetURLValue(); michael@0: face->mReferrer = val.GetURLStructValue()->mReferrer; michael@0: face->mOriginPrincipal = val.GetURLStructValue()->mOriginPrincipal; michael@0: NS_ASSERTION(face->mOriginPrincipal, "null origin principal in @font-face rule"); michael@0: michael@0: // agent and user stylesheets are treated slightly differently, michael@0: // the same-site origin check and access control headers are michael@0: // enforced against the sheet principal rather than the document michael@0: // principal to allow user stylesheets to include @font-face rules michael@0: face->mUseOriginPrincipal = (aSheetType == nsStyleSet::eUserSheet || michael@0: aSheetType == nsStyleSet::eAgentSheet); michael@0: michael@0: face->mLocalName.Truncate(); michael@0: face->mFormatFlags = 0; michael@0: while (i + 1 < numSrc && (val = srcArr->Item(i+1), michael@0: val.GetUnit() == eCSSUnit_Font_Format)) { michael@0: nsDependentString valueString(val.GetStringBufferValue()); michael@0: if (valueString.LowerCaseEqualsASCII("woff")) { michael@0: face->mFormatFlags |= FLAG_FORMAT_WOFF; michael@0: } else if (valueString.LowerCaseEqualsASCII("opentype")) { michael@0: face->mFormatFlags |= FLAG_FORMAT_OPENTYPE; michael@0: } else if (valueString.LowerCaseEqualsASCII("truetype")) { michael@0: face->mFormatFlags |= FLAG_FORMAT_TRUETYPE; michael@0: } else if (valueString.LowerCaseEqualsASCII("truetype-aat")) { michael@0: face->mFormatFlags |= FLAG_FORMAT_TRUETYPE_AAT; michael@0: } else if (valueString.LowerCaseEqualsASCII("embedded-opentype")) { michael@0: face->mFormatFlags |= FLAG_FORMAT_EOT; michael@0: } else if (valueString.LowerCaseEqualsASCII("svg")) { michael@0: face->mFormatFlags |= FLAG_FORMAT_SVG; michael@0: } else { michael@0: // unknown format specified, mark to distinguish from the michael@0: // case where no format hints are specified michael@0: face->mFormatFlags |= FLAG_FORMAT_UNKNOWN; michael@0: } michael@0: i++; michael@0: } michael@0: if (!face->mURI) { michael@0: // if URI not valid, omit from src array michael@0: srcArray.RemoveElementAt(srcArray.Length() - 1); michael@0: NS_WARNING("null url in @font-face rule"); michael@0: continue; michael@0: } michael@0: break; michael@0: default: michael@0: NS_ASSERTION(unit == eCSSUnit_Local_Font || unit == eCSSUnit_URL, michael@0: "strange unit type in font-face src array"); michael@0: break; michael@0: } michael@0: } michael@0: } else { michael@0: NS_ASSERTION(unit == eCSSUnit_Null, "@font-face src has unexpected unit"); michael@0: } michael@0: michael@0: if (srcArray.Length() > 0) { michael@0: FontFaceRuleRecord ruleRec; michael@0: ruleRec.mContainer.mRule = aRule; michael@0: ruleRec.mContainer.mSheetType = aSheetType; michael@0: ruleRec.mFontEntry = AddFontFace(fontfamily, srcArray, michael@0: weight, stretch, italicStyle, michael@0: featureSettings, languageOverride); michael@0: if (ruleRec.mFontEntry) { michael@0: mRules.AppendElement(ruleRec); michael@0: } michael@0: // this was a new rule and fontEntry, so note that the set was modified michael@0: aFontSetModified = true; michael@0: } michael@0: } michael@0: michael@0: void michael@0: nsUserFontSet::ReplaceFontEntry(gfxMixedFontFamily* aFamily, michael@0: gfxProxyFontEntry* aProxy, michael@0: gfxFontEntry* aFontEntry) michael@0: { michael@0: // aProxy is being supplanted by the "real" font aFontEntry, so we need to michael@0: // update any rules that refer to it. Note that there may be multiple rules michael@0: // that refer to the same proxy - e.g. if a stylesheet was loaded multiple michael@0: // times, so that several identical @font-face rules are present. michael@0: for (uint32_t i = 0; i < mRules.Length(); ++i) { michael@0: if (mRules[i].mFontEntry == aProxy) { michael@0: mRules[i].mFontEntry = aFontEntry; michael@0: } michael@0: } michael@0: aFamily->ReplaceFontEntry(aProxy, aFontEntry); michael@0: } michael@0: michael@0: nsCSSFontFaceRule* michael@0: nsUserFontSet::FindRuleForEntry(gfxFontEntry* aFontEntry) michael@0: { michael@0: for (uint32_t i = 0; i < mRules.Length(); ++i) { michael@0: if (mRules[i].mFontEntry == aFontEntry) { michael@0: return mRules[i].mContainer.mRule; michael@0: } michael@0: } michael@0: return nullptr; michael@0: } michael@0: michael@0: nsresult michael@0: nsUserFontSet::LogMessage(gfxMixedFontFamily* aFamily, michael@0: gfxProxyFontEntry* aProxy, michael@0: const char* aMessage, michael@0: uint32_t aFlags, michael@0: nsresult aStatus) michael@0: { michael@0: nsCOMPtr michael@0: console(do_GetService(NS_CONSOLESERVICE_CONTRACTID)); michael@0: if (!console) { michael@0: return NS_ERROR_NOT_AVAILABLE; michael@0: } michael@0: michael@0: NS_ConvertUTF16toUTF8 familyName(aFamily->Name()); michael@0: nsAutoCString fontURI; michael@0: if (aProxy->mSrcIndex == aProxy->mSrcList.Length()) { michael@0: fontURI.AppendLiteral("(end of source list)"); michael@0: } else { michael@0: if (aProxy->mSrcList[aProxy->mSrcIndex].mURI) { michael@0: aProxy->mSrcList[aProxy->mSrcIndex].mURI->GetSpec(fontURI); michael@0: } else { michael@0: fontURI.AppendLiteral("(invalid URI)"); michael@0: } michael@0: } michael@0: michael@0: char weightKeywordBuf[8]; // plenty to sprintf() a uint16_t michael@0: const char* weightKeyword; michael@0: const nsAFlatCString& weightKeywordString = michael@0: nsCSSProps::ValueToKeyword(aProxy->Weight(), michael@0: nsCSSProps::kFontWeightKTable); michael@0: if (weightKeywordString.Length() > 0) { michael@0: weightKeyword = weightKeywordString.get(); michael@0: } else { michael@0: sprintf(weightKeywordBuf, "%u", aProxy->Weight()); michael@0: weightKeyword = weightKeywordBuf; michael@0: } michael@0: michael@0: nsPrintfCString message michael@0: ("downloadable font: %s " michael@0: "(font-family: \"%s\" style:%s weight:%s stretch:%s src index:%d)", michael@0: aMessage, michael@0: familyName.get(), michael@0: aProxy->IsItalic() ? "italic" : "normal", michael@0: weightKeyword, michael@0: nsCSSProps::ValueToKeyword(aProxy->Stretch(), michael@0: nsCSSProps::kFontStretchKTable).get(), michael@0: aProxy->mSrcIndex); michael@0: michael@0: if (NS_FAILED(aStatus)) { michael@0: message.Append(": "); michael@0: switch (aStatus) { michael@0: case NS_ERROR_DOM_BAD_URI: michael@0: message.Append("bad URI or cross-site access not allowed"); michael@0: break; michael@0: case NS_ERROR_CONTENT_BLOCKED: michael@0: message.Append("content blocked"); michael@0: break; michael@0: default: michael@0: message.Append("status="); michael@0: message.AppendInt(static_cast(aStatus)); michael@0: break; michael@0: } michael@0: } michael@0: message.Append("\nsource: "); michael@0: message.Append(fontURI); michael@0: michael@0: #ifdef PR_LOGGING michael@0: if (PR_LOG_TEST(GetUserFontsLog(), PR_LOG_DEBUG)) { michael@0: PR_LOG(GetUserFontsLog(), PR_LOG_DEBUG, michael@0: ("userfonts (%p) %s", this, message.get())); michael@0: } michael@0: #endif michael@0: michael@0: // try to give the user an indication of where the rule came from michael@0: nsCSSFontFaceRule* rule = FindRuleForEntry(aProxy); michael@0: nsString href; michael@0: nsString text; michael@0: nsresult rv; michael@0: if (rule) { michael@0: rv = rule->GetCssText(text); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: nsCOMPtr sheet; michael@0: rv = rule->GetParentStyleSheet(getter_AddRefs(sheet)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: // if the style sheet is removed while the font is loading can be null michael@0: if (sheet) { michael@0: rv = sheet->GetHref(href); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: } else { michael@0: NS_WARNING("null parent stylesheet for @font-face rule"); michael@0: href.AssignLiteral("unknown"); michael@0: } michael@0: } michael@0: michael@0: nsCOMPtr scriptError = michael@0: do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: uint64_t innerWindowID = GetPresContext()->Document()->InnerWindowID(); michael@0: rv = scriptError->InitWithWindowID(NS_ConvertUTF8toUTF16(message), michael@0: href, // file michael@0: text, // src line michael@0: 0, 0, // line & column number michael@0: aFlags, // flags michael@0: "CSS Loader", // category (make separate?) michael@0: innerWindowID); michael@0: if (NS_SUCCEEDED(rv)) { michael@0: console->LogMessage(scriptError); michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: nsresult michael@0: nsUserFontSet::CheckFontLoad(const gfxFontFaceSrc* aFontFaceSrc, michael@0: nsIPrincipal** aPrincipal, michael@0: bool* aBypassCache) michael@0: { michael@0: // check same-site origin michael@0: nsIPresShell* ps = mPresContext->PresShell(); michael@0: if (!ps) michael@0: return NS_ERROR_FAILURE; michael@0: michael@0: NS_ASSERTION(aFontFaceSrc && !aFontFaceSrc->mIsLocal, michael@0: "bad font face url passed to fontloader"); michael@0: NS_ASSERTION(aFontFaceSrc->mURI, "null font uri"); michael@0: if (!aFontFaceSrc->mURI) michael@0: return NS_ERROR_FAILURE; michael@0: michael@0: // use document principal, original principal if flag set michael@0: // this enables user stylesheets to load font files via michael@0: // @font-face rules michael@0: *aPrincipal = ps->GetDocument()->NodePrincipal(); michael@0: michael@0: NS_ASSERTION(aFontFaceSrc->mOriginPrincipal, michael@0: "null origin principal in @font-face rule"); michael@0: if (aFontFaceSrc->mUseOriginPrincipal) { michael@0: *aPrincipal = aFontFaceSrc->mOriginPrincipal; michael@0: } michael@0: michael@0: nsresult rv = nsFontFaceLoader::CheckLoadAllowed(*aPrincipal, michael@0: aFontFaceSrc->mURI, michael@0: ps->GetDocument()); michael@0: if (NS_FAILED(rv)) { michael@0: return rv; michael@0: } michael@0: michael@0: *aBypassCache = false; michael@0: michael@0: nsCOMPtr docShell = ps->GetDocument()->GetDocShell(); michael@0: if (docShell) { michael@0: uint32_t loadType; michael@0: if (NS_SUCCEEDED(docShell->GetLoadType(&loadType))) { michael@0: if ((loadType >> 16) & nsIWebNavigation::LOAD_FLAGS_BYPASS_CACHE) { michael@0: *aBypassCache = true; michael@0: } michael@0: } michael@0: } michael@0: michael@0: return rv; michael@0: } michael@0: michael@0: nsresult michael@0: nsUserFontSet::SyncLoadFontData(gfxProxyFontEntry* aFontToLoad, michael@0: const gfxFontFaceSrc* aFontFaceSrc, michael@0: uint8_t*& aBuffer, michael@0: uint32_t& aBufferLength) michael@0: { michael@0: nsresult rv; michael@0: michael@0: nsCOMPtr channel; michael@0: // get Content Security Policy from principal to pass into channel michael@0: nsCOMPtr channelPolicy; michael@0: nsCOMPtr csp; michael@0: rv = aFontToLoad->mPrincipal->GetCsp(getter_AddRefs(csp)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: if (csp) { michael@0: channelPolicy = do_CreateInstance("@mozilla.org/nschannelpolicy;1"); michael@0: channelPolicy->SetContentSecurityPolicy(csp); michael@0: channelPolicy->SetLoadType(nsIContentPolicy::TYPE_FONT); michael@0: } michael@0: rv = NS_NewChannel(getter_AddRefs(channel), michael@0: aFontFaceSrc->mURI, michael@0: nullptr, michael@0: nullptr, michael@0: nullptr, michael@0: nsIRequest::LOAD_NORMAL, michael@0: channelPolicy); michael@0: michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: // blocking stream is OK for data URIs michael@0: nsCOMPtr stream; michael@0: rv = channel->Open(getter_AddRefs(stream)); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: michael@0: uint64_t bufferLength64; michael@0: rv = stream->Available(&bufferLength64); michael@0: NS_ENSURE_SUCCESS(rv, rv); michael@0: if (bufferLength64 == 0) { michael@0: return NS_ERROR_FAILURE; michael@0: } michael@0: if (bufferLength64 > UINT32_MAX) { michael@0: return NS_ERROR_FILE_TOO_BIG; michael@0: } michael@0: aBufferLength = static_cast(bufferLength64); michael@0: michael@0: // read all the decoded data michael@0: aBuffer = static_cast (NS_Alloc(sizeof(uint8_t) * aBufferLength)); michael@0: if (!aBuffer) { michael@0: aBufferLength = 0; michael@0: return NS_ERROR_OUT_OF_MEMORY; michael@0: } michael@0: michael@0: uint32_t numRead, totalRead = 0; michael@0: while (NS_SUCCEEDED(rv = michael@0: stream->Read(reinterpret_cast(aBuffer + totalRead), michael@0: aBufferLength - totalRead, &numRead)) && michael@0: numRead != 0) michael@0: { michael@0: totalRead += numRead; michael@0: if (totalRead > aBufferLength) { michael@0: rv = NS_ERROR_FAILURE; michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // make sure there's a mime type michael@0: if (NS_SUCCEEDED(rv)) { michael@0: nsAutoCString mimeType; michael@0: rv = channel->GetContentType(mimeType); michael@0: aBufferLength = totalRead; michael@0: } michael@0: michael@0: if (NS_FAILED(rv)) { michael@0: NS_Free(aBuffer); michael@0: aBuffer = nullptr; michael@0: aBufferLength = 0; michael@0: return rv; michael@0: } michael@0: michael@0: return NS_OK; michael@0: } michael@0: michael@0: bool michael@0: nsUserFontSet::GetPrivateBrowsing() michael@0: { michael@0: nsIPresShell* ps = mPresContext->PresShell(); michael@0: if (!ps) { michael@0: return false; michael@0: } michael@0: michael@0: nsCOMPtr loadContext = ps->GetDocument()->GetLoadContext(); michael@0: return loadContext && loadContext->UsePrivateBrowsing(); michael@0: } michael@0: michael@0: void michael@0: nsUserFontSet::DoRebuildUserFontSet() michael@0: { michael@0: if (!mPresContext) { michael@0: // AFAICS, this can only happen if someone has already called Destroy() on michael@0: // this font-set, which means it is in the process of being torn down -- michael@0: // so there's no point trying to update its rules. michael@0: return; michael@0: } michael@0: michael@0: mPresContext->RebuildUserFontSet(); michael@0: }