1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 sts=2 sw=2 et tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/dom/ContentParent.h"
8 #include "RegistryMessageUtils.h"
9 #include "nsResProtocolHandler.h"
11 #include "nsChromeRegistryChrome.h"
15 #elif defined(XP_MACOSX)
16 # include <CoreServices/CoreServices.h>
19 #include "nsArrayEnumerator.h"
20 #include "nsComponentManager.h"
21 #include "nsEnumeratorUtils.h"
22 #include "nsNetUtil.h"
23 #include "nsStringEnumerator.h"
24 #include "nsTextFormatter.h"
25 #include "nsXPCOMCIDInternal.h"
27 #include "mozilla/LookAndFeel.h"
28 #include "mozilla/Unused.h"
30 #include "nsIAppStartup.h"
31 #include "nsIObserverService.h"
32 #include "mozilla/Preferences.h"
33 #include "nsIResProtocolHandler.h"
34 #include "nsIScriptError.h"
35 #include "nsIXULRuntime.h"
37 #define PACKAGE_OVERRIDE_BRANCH "chrome.override_package."
38 #define SKIN NS_LITERAL_CSTRING("classic/1.0")
40 using namespace mozilla
;
41 using mozilla::dom::ContentParent
;
42 using mozilla::dom::PContentParent
;
43 using mozilla::intl::LocaleService
;
45 // We use a "best-fit" algorithm for matching locales and themes.
46 // 1) the exact selected locale/theme
47 // 2) (locales only) same language, different country
48 // e.g. en-GB is the selected locale, only en-US is available
49 // 3) any available locale/theme
52 * Match the language-part of two lang-COUNTRY codes, hopefully but
53 * not guaranteed to be in the form ab-CD or abz-CD. "ab" should also
54 * work, any other garbage-in will produce undefined results as long
55 * as it does not crash.
57 static bool LanguagesMatch(const nsACString
& a
, const nsACString
& b
) {
58 if (a
.Length() < 2 || b
.Length() < 2) return false;
60 nsACString::const_iterator as
, ae
, bs
, be
;
67 if (*as
== '-') return true;
73 if (as
== ae
&& bs
== be
) return true;
76 if (as
== ae
) return (*bs
== '-');
79 if (bs
== be
) return (*as
== '-');
85 nsChromeRegistryChrome::nsChromeRegistryChrome()
86 : mProfileLoaded(false), mDynamicRegistration(true) {}
88 nsChromeRegistryChrome::~nsChromeRegistryChrome() {}
90 nsresult
nsChromeRegistryChrome::Init() {
91 nsresult rv
= nsChromeRegistry::Init();
92 if (NS_FAILED(rv
)) return rv
;
94 bool safeMode
= false;
95 nsCOMPtr
<nsIXULRuntime
> xulrun(do_GetService(XULAPPINFO_SERVICE_CONTRACTID
));
96 if (xulrun
) xulrun
->GetInSafeMode(&safeMode
);
98 nsCOMPtr
<nsIObserverService
> obsService
=
99 mozilla::services::GetObserverService();
101 obsService
->AddObserver(this, "profile-initial-state", true);
102 obsService
->AddObserver(this, "intl:app-locales-changed", true);
109 nsChromeRegistryChrome::GetLocalesForPackage(
110 const nsACString
& aPackage
, nsIUTF8StringEnumerator
** aResult
) {
111 nsCString realpackage
;
112 nsresult rv
= OverrideLocalePackage(aPackage
, realpackage
);
113 if (NS_FAILED(rv
)) return rv
;
115 nsTArray
<nsCString
>* a
= new nsTArray
<nsCString
>;
116 if (!a
) return NS_ERROR_OUT_OF_MEMORY
;
119 if (mPackagesHash
.Get(realpackage
, &entry
)) {
120 entry
->locales
.EnumerateToArray(a
);
123 rv
= NS_NewAdoptingUTF8StringEnumerator(aResult
, a
);
124 if (NS_FAILED(rv
)) delete a
;
130 nsChromeRegistryChrome::IsLocaleRTL(const nsACString
& package
, bool* aResult
) {
133 nsAutoCString locale
;
134 GetSelectedLocale(package
, locale
);
135 if (locale
.Length() < 2) return NS_OK
;
137 *aResult
= LocaleService::IsLocaleRTL(locale
);
142 * This method negotiates only between the app locale and the available
145 * If you want to get the current application's UI locale, please use
146 * LocaleService::GetAppLocaleAsBCP47.
148 nsresult
nsChromeRegistryChrome::GetSelectedLocale(const nsACString
& aPackage
,
149 nsACString
& aLocale
) {
150 nsAutoCString reqLocale
;
151 if (aPackage
.EqualsLiteral("global")) {
152 LocaleService::GetInstance()->GetAppLocaleAsBCP47(reqLocale
);
154 AutoTArray
<nsCString
, 10> requestedLocales
;
155 LocaleService::GetInstance()->GetRequestedLocales(requestedLocales
);
156 reqLocale
.Assign(requestedLocales
[0]);
159 nsCString realpackage
;
160 nsresult rv
= OverrideLocalePackage(aPackage
, realpackage
);
161 if (NS_FAILED(rv
)) return rv
;
163 if (!mPackagesHash
.Get(realpackage
, &entry
)) return NS_ERROR_FILE_NOT_FOUND
;
165 aLocale
= entry
->locales
.GetSelected(reqLocale
, nsProviderArray::LOCALE
);
166 if (aLocale
.IsEmpty()) return NS_ERROR_FAILURE
;
171 nsresult
nsChromeRegistryChrome::OverrideLocalePackage(
172 const nsACString
& aPackage
, nsACString
& aOverride
) {
173 const nsACString
& pref
=
174 NS_LITERAL_CSTRING(PACKAGE_OVERRIDE_BRANCH
) + aPackage
;
175 nsAutoCString override
;
176 nsresult rv
= mozilla::Preferences::GetCString(PromiseFlatCString(pref
).get(),
178 if (NS_SUCCEEDED(rv
)) {
179 aOverride
= override
;
181 aOverride
= aPackage
;
187 nsChromeRegistryChrome::Observe(nsISupports
* aSubject
, const char* aTopic
,
188 const char16_t
* someData
) {
191 if (!strcmp("profile-initial-state", aTopic
)) {
192 mProfileLoaded
= true;
193 } else if (!strcmp("intl:app-locales-changed", aTopic
)) {
194 if (mProfileLoaded
) {
198 NS_ERROR("Unexpected observer topic!");
205 nsChromeRegistryChrome::CheckForNewChrome() {
206 nsCOMPtr
<nsIAppStartup
> appStartup
= components::AppStartup::Service();
207 if (appStartup
->GetShuttingDown()) {
208 MOZ_ASSERT(false, "checking for new chrome during shutdown");
209 return NS_ERROR_UNEXPECTED
;
212 mPackagesHash
.Clear();
213 mOverrideTable
.Clear();
215 mDynamicRegistration
= false;
217 nsComponentManagerImpl::gComponentManager
->RereadChromeManifests();
219 mDynamicRegistration
= true;
221 SendRegisteredChrome(nullptr);
225 static void SerializeURI(nsIURI
* aURI
, SerializedURI
& aSerializedURI
) {
228 aURI
->GetSpec(aSerializedURI
.spec
);
231 void nsChromeRegistryChrome::SendRegisteredChrome(
232 mozilla::dom::PContentParent
* aParent
) {
233 nsTArray
<ChromePackage
> packages
;
234 nsTArray
<SubstitutionMapping
> resources
;
235 nsTArray
<OverrideMapping
> overrides
;
237 for (auto iter
= mPackagesHash
.Iter(); !iter
.Done(); iter
.Next()) {
238 ChromePackage chromePackage
;
239 ChromePackageFromPackageEntry(iter
.Key(), iter
.UserData(), &chromePackage
,
241 packages
.AppendElement(chromePackage
);
244 // If we were passed a parent then a new child process has been created and
245 // has requested all of the chrome so send it the resources too. Otherwise
246 // resource mappings are sent by the resource protocol handler dynamically.
248 nsCOMPtr
<nsIIOService
> io(do_GetIOService());
249 NS_ENSURE_TRUE_VOID(io
);
251 nsCOMPtr
<nsIProtocolHandler
> ph
;
252 nsresult rv
= io
->GetProtocolHandler("resource", getter_AddRefs(ph
));
253 NS_ENSURE_SUCCESS_VOID(rv
);
255 nsCOMPtr
<nsIResProtocolHandler
> irph(do_QueryInterface(ph
));
256 nsResProtocolHandler
* rph
= static_cast<nsResProtocolHandler
*>(irph
.get());
257 rv
= rph
->CollectSubstitutions(resources
);
258 NS_ENSURE_SUCCESS_VOID(rv
);
261 for (auto iter
= mOverrideTable
.Iter(); !iter
.Done(); iter
.Next()) {
262 SerializedURI chromeURI
, overrideURI
;
264 SerializeURI(iter
.Key(), chromeURI
);
265 SerializeURI(iter
.UserData(), overrideURI
);
267 OverrideMapping override
= {chromeURI
, overrideURI
};
268 overrides
.AppendElement(override
);
271 nsAutoCString appLocale
;
272 LocaleService::GetInstance()->GetAppLocaleAsBCP47(appLocale
);
275 bool success
= aParent
->SendRegisterChrome(packages
, resources
, overrides
,
277 NS_ENSURE_TRUE_VOID(success
);
279 nsTArray
<ContentParent
*> parents
;
280 ContentParent::GetAll(parents
);
281 if (!parents
.Length()) return;
283 for (uint32_t i
= 0; i
< parents
.Length(); i
++) {
284 DebugOnly
<bool> success
= parents
[i
]->SendRegisterChrome(
285 packages
, resources
, overrides
, appLocale
, true);
286 NS_WARNING_ASSERTION(success
,
287 "couldn't reset a child's registered chrome");
293 void nsChromeRegistryChrome::ChromePackageFromPackageEntry(
294 const nsACString
& aPackageName
, PackageEntry
* aPackage
,
295 ChromePackage
* aChromePackage
, const nsCString
& aSelectedSkin
) {
296 nsAutoCString appLocale
;
297 LocaleService::GetInstance()->GetAppLocaleAsBCP47(appLocale
);
299 SerializeURI(aPackage
->baseURI
, aChromePackage
->contentBaseURI
);
300 SerializeURI(aPackage
->locales
.GetBase(appLocale
, nsProviderArray::LOCALE
),
301 aChromePackage
->localeBaseURI
);
302 SerializeURI(aPackage
->skins
.GetBase(aSelectedSkin
, nsProviderArray::ANY
),
303 aChromePackage
->skinBaseURI
);
304 aChromePackage
->package
= aPackageName
;
305 aChromePackage
->flags
= aPackage
->flags
;
308 static bool CanLoadResource(nsIURI
* aResourceURI
) {
309 bool isLocalResource
= false;
310 (void)NS_URIChainHasFlags(aResourceURI
,
311 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE
,
313 return isLocalResource
;
316 nsIURI
* nsChromeRegistryChrome::GetBaseURIFromPackage(
317 const nsCString
& aPackage
, const nsCString
& aProvider
,
318 const nsCString
& aPath
) {
320 if (!mPackagesHash
.Get(aPackage
, &entry
)) {
321 if (!mInitialized
) return nullptr;
323 LogMessage("No chrome package registered for chrome://%s/%s/%s",
324 aPackage
.get(), aProvider
.get(), aPath
.get());
329 if (aProvider
.EqualsLiteral("locale")) {
330 nsAutoCString appLocale
;
331 LocaleService::GetInstance()->GetAppLocaleAsLangTag(appLocale
);
332 return entry
->locales
.GetBase(appLocale
, nsProviderArray::LOCALE
);
333 } else if (aProvider
.EqualsLiteral("skin")) {
334 return entry
->skins
.GetBase(SKIN
, nsProviderArray::ANY
);
335 } else if (aProvider
.EqualsLiteral("content")) {
336 return entry
->baseURI
;
341 nsresult
nsChromeRegistryChrome::GetFlagsFromPackage(const nsCString
& aPackage
,
344 if (!mPackagesHash
.Get(aPackage
, &entry
)) return NS_ERROR_FILE_NOT_FOUND
;
346 *aFlags
= entry
->flags
;
350 nsChromeRegistryChrome::ProviderEntry
*
351 nsChromeRegistryChrome::nsProviderArray::GetProvider(
352 const nsACString
& aPreferred
, MatchType aType
) {
353 size_t i
= mArray
.Length();
354 if (!i
) return nullptr;
356 ProviderEntry
* found
= nullptr; // Only set if we find a partial-match locale
357 ProviderEntry
* entry
= nullptr;
361 if (aPreferred
.Equals(entry
->provider
)) return entry
;
363 if (aType
!= LOCALE
) continue;
365 if (LanguagesMatch(aPreferred
, entry
->provider
)) {
370 if (!found
&& entry
->provider
.EqualsLiteral("en-US")) found
= entry
;
373 if (!found
&& aType
!= EXACT
) return entry
;
378 nsIURI
* nsChromeRegistryChrome::nsProviderArray::GetBase(
379 const nsACString
& aPreferred
, MatchType aType
) {
380 ProviderEntry
* provider
= GetProvider(aPreferred
, aType
);
382 if (!provider
) return nullptr;
384 return provider
->baseURI
;
387 const nsACString
& nsChromeRegistryChrome::nsProviderArray::GetSelected(
388 const nsACString
& aPreferred
, MatchType aType
) {
389 ProviderEntry
* entry
= GetProvider(aPreferred
, aType
);
391 if (entry
) return entry
->provider
;
393 return EmptyCString();
396 void nsChromeRegistryChrome::nsProviderArray::SetBase(
397 const nsACString
& aProvider
, nsIURI
* aBaseURL
) {
398 ProviderEntry
* provider
= GetProvider(aProvider
, EXACT
);
401 provider
->baseURI
= aBaseURL
;
405 // no existing entries, add a new one
406 mArray
.AppendElement(ProviderEntry(aProvider
, aBaseURL
));
409 void nsChromeRegistryChrome::nsProviderArray::EnumerateToArray(
410 nsTArray
<nsCString
>* a
) {
411 int32_t i
= mArray
.Length();
413 a
->AppendElement(mArray
[i
].provider
);
417 nsIURI
* nsChromeRegistry::ManifestProcessingContext::GetManifestURI() {
420 mFile
.GetURIString(uri
);
421 NS_NewURI(getter_AddRefs(mManifestURI
), uri
);
426 already_AddRefed
<nsIURI
>
427 nsChromeRegistry::ManifestProcessingContext::ResolveURI(const char* uri
) {
428 nsIURI
* baseuri
= GetManifestURI();
429 if (!baseuri
) return nullptr;
431 nsCOMPtr
<nsIURI
> resolved
;
432 nsresult rv
= NS_NewURI(getter_AddRefs(resolved
), uri
, baseuri
);
433 if (NS_FAILED(rv
)) return nullptr;
435 return resolved
.forget();
438 static void EnsureLowerCase(char* aBuf
) {
439 for (; *aBuf
; ++aBuf
) {
441 if (ch
>= 'A' && ch
<= 'Z') *aBuf
= ch
+ 'a' - 'A';
445 static void SendManifestEntry(const ChromeRegistryItem
& aItem
) {
446 nsTArray
<ContentParent
*> parents
;
447 ContentParent::GetAll(parents
);
448 if (!parents
.Length()) return;
450 for (uint32_t i
= 0; i
< parents
.Length(); i
++) {
451 Unused
<< parents
[i
]->SendRegisterChromeItem(aItem
);
455 void nsChromeRegistryChrome::ManifestContent(ManifestProcessingContext
& cx
,
456 int lineno
, char* const* argv
,
458 char* package
= argv
[0];
461 EnsureLowerCase(package
);
463 nsCOMPtr
<nsIURI
> resolved
= cx
.ResolveURI(uri
);
465 LogMessageWithContext(
466 cx
.GetManifestURI(), lineno
, nsIScriptError::warningFlag
,
467 "During chrome registration, unable to create URI '%s'.", uri
);
471 if (!CanLoadResource(resolved
)) {
472 LogMessageWithContext(resolved
, lineno
, nsIScriptError::warningFlag
,
473 "During chrome registration, cannot register "
474 "non-local URI '%s' as content.",
479 nsDependentCString
packageName(package
);
480 PackageEntry
* entry
= mPackagesHash
.LookupOrAdd(packageName
);
481 entry
->baseURI
= resolved
;
482 entry
->flags
= flags
;
484 if (mDynamicRegistration
) {
485 ChromePackage chromePackage
;
486 ChromePackageFromPackageEntry(packageName
, entry
, &chromePackage
, SKIN
);
487 SendManifestEntry(chromePackage
);
491 void nsChromeRegistryChrome::ManifestLocale(ManifestProcessingContext
& cx
,
492 int lineno
, char* const* argv
,
494 char* package
= argv
[0];
495 char* provider
= argv
[1];
498 EnsureLowerCase(package
);
500 nsCOMPtr
<nsIURI
> resolved
= cx
.ResolveURI(uri
);
502 LogMessageWithContext(
503 cx
.GetManifestURI(), lineno
, nsIScriptError::warningFlag
,
504 "During chrome registration, unable to create URI '%s'.", uri
);
508 if (!CanLoadResource(resolved
)) {
509 LogMessageWithContext(resolved
, lineno
, nsIScriptError::warningFlag
,
510 "During chrome registration, cannot register "
511 "non-local URI '%s' as content.",
516 nsDependentCString
packageName(package
);
517 PackageEntry
* entry
= mPackagesHash
.LookupOrAdd(packageName
);
518 entry
->locales
.SetBase(nsDependentCString(provider
), resolved
);
520 if (mDynamicRegistration
) {
521 ChromePackage chromePackage
;
522 ChromePackageFromPackageEntry(packageName
, entry
, &chromePackage
, SKIN
);
523 SendManifestEntry(chromePackage
);
526 // We use mainPackage as the package we track for reporting new locales being
527 // registered. For most cases it will be "global", but for Fennec it will be
529 nsAutoCString mainPackage
;
531 OverrideLocalePackage(NS_LITERAL_CSTRING("global"), mainPackage
);
537 void nsChromeRegistryChrome::ManifestSkin(ManifestProcessingContext
& cx
,
538 int lineno
, char* const* argv
,
540 char* package
= argv
[0];
541 char* provider
= argv
[1];
544 EnsureLowerCase(package
);
546 nsCOMPtr
<nsIURI
> resolved
= cx
.ResolveURI(uri
);
548 LogMessageWithContext(
549 cx
.GetManifestURI(), lineno
, nsIScriptError::warningFlag
,
550 "During chrome registration, unable to create URI '%s'.", uri
);
554 if (!CanLoadResource(resolved
)) {
555 LogMessageWithContext(resolved
, lineno
, nsIScriptError::warningFlag
,
556 "During chrome registration, cannot register "
557 "non-local URI '%s' as content.",
562 nsDependentCString
packageName(package
);
563 PackageEntry
* entry
= mPackagesHash
.LookupOrAdd(packageName
);
564 entry
->skins
.SetBase(nsDependentCString(provider
), resolved
);
566 if (mDynamicRegistration
) {
567 ChromePackage chromePackage
;
568 ChromePackageFromPackageEntry(packageName
, entry
, &chromePackage
, SKIN
);
569 SendManifestEntry(chromePackage
);
573 void nsChromeRegistryChrome::ManifestOverride(ManifestProcessingContext
& cx
,
574 int lineno
, char* const* argv
,
576 char* chrome
= argv
[0];
577 char* resolved
= argv
[1];
579 nsCOMPtr
<nsIURI
> chromeuri
= cx
.ResolveURI(chrome
);
580 nsCOMPtr
<nsIURI
> resolveduri
= cx
.ResolveURI(resolved
);
581 if (!chromeuri
|| !resolveduri
) {
582 LogMessageWithContext(cx
.GetManifestURI(), lineno
,
583 nsIScriptError::warningFlag
,
584 "During chrome registration, unable to create URI.");
588 if (cx
.mType
== NS_SKIN_LOCATION
) {
589 bool chromeSkinOnly
=
590 chromeuri
->SchemeIs("chrome") && resolveduri
->SchemeIs("chrome");
591 if (chromeSkinOnly
) {
592 nsAutoCString chromePath
, resolvedPath
;
593 chromeuri
->GetPathQueryRef(chromePath
);
594 resolveduri
->GetPathQueryRef(resolvedPath
);
596 StringBeginsWith(chromePath
, NS_LITERAL_CSTRING("/skin/")) &&
597 StringBeginsWith(resolvedPath
, NS_LITERAL_CSTRING("/skin/"));
599 if (!chromeSkinOnly
) {
600 LogMessageWithContext(
601 cx
.GetManifestURI(), lineno
, nsIScriptError::warningFlag
,
602 "Cannot register non-chrome://.../skin/ URIs '%s' and '%s' as "
603 "overrides and/or to be overridden from a skin manifest.",
609 if (!CanLoadResource(resolveduri
)) {
610 LogMessageWithContext(
611 cx
.GetManifestURI(), lineno
, nsIScriptError::warningFlag
,
612 "Cannot register non-local URI '%s' for an override.", resolved
);
615 mOverrideTable
.Put(chromeuri
, resolveduri
);
617 if (mDynamicRegistration
) {
618 SerializedURI serializedChrome
;
619 SerializedURI serializedOverride
;
621 SerializeURI(chromeuri
, serializedChrome
);
622 SerializeURI(resolveduri
, serializedOverride
);
624 OverrideMapping override
= {serializedChrome
, serializedOverride
};
625 SendManifestEntry(override
);
629 void nsChromeRegistryChrome::ManifestResource(ManifestProcessingContext
& cx
,
630 int lineno
, char* const* argv
,
632 char* package
= argv
[0];
635 EnsureLowerCase(package
);
636 nsDependentCString
host(package
);
638 nsCOMPtr
<nsIIOService
> io
= mozilla::services::GetIOService();
640 NS_WARNING("No IO service trying to process chrome manifests");
644 nsCOMPtr
<nsIProtocolHandler
> ph
;
645 nsresult rv
= io
->GetProtocolHandler("resource", getter_AddRefs(ph
));
646 if (NS_FAILED(rv
)) return;
648 nsCOMPtr
<nsIResProtocolHandler
> rph
= do_QueryInterface(ph
);
650 nsCOMPtr
<nsIURI
> resolved
= cx
.ResolveURI(uri
);
652 LogMessageWithContext(
653 cx
.GetManifestURI(), lineno
, nsIScriptError::warningFlag
,
654 "During chrome registration, unable to create URI '%s'.", uri
);
658 if (!CanLoadResource(resolved
)) {
659 LogMessageWithContext(
660 cx
.GetManifestURI(), lineno
, nsIScriptError::warningFlag
,
661 "Warning: cannot register non-local URI '%s' as a resource.", uri
);
665 // By default, Firefox resources are not content-accessible unless the
666 // manifests opts in.
667 bool contentAccessible
= (flags
& nsChromeRegistry::CONTENT_ACCESSIBLE
);
669 uint32_t substitutionFlags
= 0;
670 if (contentAccessible
) {
671 substitutionFlags
|= nsIResProtocolHandler::ALLOW_CONTENT_ACCESS
;
673 rv
= rph
->SetSubstitutionWithFlags(host
, resolved
, substitutionFlags
);
675 LogMessageWithContext(cx
.GetManifestURI(), lineno
,
676 nsIScriptError::warningFlag
,
677 "Warning: cannot set substitution for '%s'.", uri
);