Bug 1883706: part 3) Implement `createHTML`, `createScript` and `createScriptURL...
[gecko.git] / chrome / nsChromeRegistryChrome.cpp
blob0bb93b4cfac5d01ee0e0d920efe6898d65acb935
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"
13 #if defined(XP_WIN)
14 # include <windows.h>
15 #elif defined(XP_MACOSX)
16 # include <CoreServices/CoreServices.h>
17 #endif
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 "nsIObserverService.h"
31 #include "mozilla/AppShutdown.h"
32 #include "mozilla/Components.h"
33 #include "mozilla/Preferences.h"
34 #include "nsIResProtocolHandler.h"
35 #include "nsIScriptError.h"
36 #include "nsIXULRuntime.h"
38 #define PACKAGE_OVERRIDE_BRANCH "chrome.override_package."
39 #define SKIN "classic/1.0"_ns
41 using namespace mozilla;
42 using mozilla::dom::ContentParent;
43 using mozilla::dom::PContentParent;
44 using mozilla::intl::LocaleService;
46 // We use a "best-fit" algorithm for matching locales and themes.
47 // 1) the exact selected locale/theme
48 // 2) (locales only) same language, different country
49 // e.g. en-GB is the selected locale, only en-US is available
50 // 3) any available locale/theme
52 /**
53 * Match the language-part of two lang-COUNTRY codes, hopefully but
54 * not guaranteed to be in the form ab-CD or abz-CD. "ab" should also
55 * work, any other garbage-in will produce undefined results as long
56 * as it does not crash.
58 static bool LanguagesMatch(const nsACString& a, const nsACString& b) {
59 if (a.Length() < 2 || b.Length() < 2) return false;
61 nsACString::const_iterator as, ae, bs, be;
62 a.BeginReading(as);
63 a.EndReading(ae);
64 b.BeginReading(bs);
65 b.EndReading(be);
67 while (*as == *bs) {
68 if (*as == '-') return true;
70 ++as;
71 ++bs;
73 // reached the end
74 if (as == ae && bs == be) return true;
76 // "a" is short
77 if (as == ae) return (*bs == '-');
79 // "b" is short
80 if (bs == be) return (*as == '-');
83 return false;
86 nsChromeRegistryChrome::nsChromeRegistryChrome()
87 : mProfileLoaded(false), mDynamicRegistration(true) {}
89 nsChromeRegistryChrome::~nsChromeRegistryChrome() {}
91 nsresult nsChromeRegistryChrome::Init() {
92 nsresult rv = nsChromeRegistry::Init();
93 if (NS_FAILED(rv)) return rv;
95 bool safeMode = false;
96 nsCOMPtr<nsIXULRuntime> xulrun(do_GetService(XULAPPINFO_SERVICE_CONTRACTID));
97 if (xulrun) xulrun->GetInSafeMode(&safeMode);
99 nsCOMPtr<nsIObserverService> obsService =
100 mozilla::services::GetObserverService();
101 if (obsService) {
102 obsService->AddObserver(this, "profile-initial-state", true);
103 obsService->AddObserver(this, "intl:app-locales-changed", true);
106 return NS_OK;
109 NS_IMETHODIMP
110 nsChromeRegistryChrome::GetLocalesForPackage(
111 const nsACString& aPackage, nsIUTF8StringEnumerator** aResult) {
112 nsCString realpackage;
113 nsresult rv = OverrideLocalePackage(aPackage, realpackage);
114 if (NS_FAILED(rv)) return rv;
116 nsTArray<nsCString>* a = new nsTArray<nsCString>;
117 if (!a) return NS_ERROR_OUT_OF_MEMORY;
119 PackageEntry* entry;
120 if (mPackagesHash.Get(realpackage, &entry)) {
121 entry->locales.EnumerateToArray(a);
124 rv = NS_NewAdoptingUTF8StringEnumerator(aResult, a);
125 if (NS_FAILED(rv)) delete a;
127 return rv;
130 NS_IMETHODIMP
131 nsChromeRegistryChrome::IsLocaleRTL(const nsACString& package, bool* aResult) {
132 *aResult = false;
134 nsAutoCString locale;
135 GetSelectedLocale(package, locale);
136 if (locale.Length() < 2) return NS_OK;
138 *aResult = LocaleService::IsLocaleRTL(locale);
139 return NS_OK;
143 * This method negotiates only between the app locale and the available
144 * chrome packages.
146 * If you want to get the current application's UI locale, please use
147 * LocaleService::GetAppLocaleAsBCP47.
149 nsresult nsChromeRegistryChrome::GetSelectedLocale(const nsACString& aPackage,
150 nsACString& aLocale) {
151 nsAutoCString reqLocale;
152 if (aPackage.EqualsLiteral("global")) {
153 LocaleService::GetInstance()->GetAppLocaleAsBCP47(reqLocale);
154 } else {
155 AutoTArray<nsCString, 10> requestedLocales;
156 LocaleService::GetInstance()->GetRequestedLocales(requestedLocales);
157 reqLocale.Assign(requestedLocales[0]);
160 nsCString realpackage;
161 nsresult rv = OverrideLocalePackage(aPackage, realpackage);
162 if (NS_FAILED(rv)) return rv;
163 PackageEntry* entry;
164 if (!mPackagesHash.Get(realpackage, &entry)) return NS_ERROR_FILE_NOT_FOUND;
166 aLocale = entry->locales.GetSelected(reqLocale, nsProviderArray::LOCALE);
167 if (aLocale.IsEmpty()) return NS_ERROR_FAILURE;
169 return NS_OK;
172 nsresult nsChromeRegistryChrome::OverrideLocalePackage(
173 const nsACString& aPackage, nsACString& aOverride) {
174 const nsACString& pref = nsLiteralCString(PACKAGE_OVERRIDE_BRANCH) + aPackage;
175 nsAutoCString override;
176 nsresult rv = mozilla::Preferences::GetCString(PromiseFlatCString(pref).get(),
177 override);
178 if (NS_SUCCEEDED(rv)) {
179 aOverride = override;
180 } else {
181 aOverride = aPackage;
183 return NS_OK;
186 NS_IMETHODIMP
187 nsChromeRegistryChrome::Observe(nsISupports* aSubject, const char* aTopic,
188 const char16_t* someData) {
189 nsresult rv = NS_OK;
191 if (!strcmp("profile-initial-state", aTopic)) {
192 mProfileLoaded = true;
193 } else if (!strcmp("intl:app-locales-changed", aTopic)) {
194 if (mProfileLoaded) {
195 FlushAllCaches();
197 } else {
198 NS_ERROR("Unexpected observer topic!");
201 return rv;
204 NS_IMETHODIMP
205 nsChromeRegistryChrome::CheckForNewChrome() {
206 if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed)) {
207 MOZ_ASSERT(false, "checking for new chrome during shutdown");
208 return NS_ERROR_UNEXPECTED;
211 mPackagesHash.Clear();
212 mOverrideTable.Clear();
214 mDynamicRegistration = false;
216 nsComponentManagerImpl::gComponentManager->RereadChromeManifests();
218 mDynamicRegistration = true;
220 SendRegisteredChrome(nullptr);
221 return NS_OK;
224 static void SerializeURI(nsIURI* aURI, SerializedURI& aSerializedURI) {
225 if (!aURI) return;
227 aURI->GetSpec(aSerializedURI.spec);
230 void nsChromeRegistryChrome::SendRegisteredChrome(
231 mozilla::dom::PContentParent* aParent) {
232 nsTArray<ChromePackage> packages;
233 nsTArray<SubstitutionMapping> resources;
234 nsTArray<OverrideMapping> overrides;
236 for (const auto& entry : mPackagesHash) {
237 ChromePackage chromePackage;
238 ChromePackageFromPackageEntry(entry.GetKey(), entry.GetWeak(),
239 &chromePackage, SKIN);
240 packages.AppendElement(chromePackage);
243 // If we were passed a parent then a new child process has been created and
244 // has requested all of the chrome so send it the resources too. Otherwise
245 // resource mappings are sent by the resource protocol handler dynamically.
246 if (aParent) {
247 nsCOMPtr<nsIIOService> io(do_GetIOService());
248 NS_ENSURE_TRUE_VOID(io);
250 nsCOMPtr<nsIProtocolHandler> ph;
251 nsresult rv = io->GetProtocolHandler("resource", getter_AddRefs(ph));
252 NS_ENSURE_SUCCESS_VOID(rv);
254 nsCOMPtr<nsIResProtocolHandler> irph(do_QueryInterface(ph));
255 nsResProtocolHandler* rph = static_cast<nsResProtocolHandler*>(irph.get());
256 rv = rph->CollectSubstitutions(resources);
257 NS_ENSURE_SUCCESS_VOID(rv);
260 for (const auto& entry : mOverrideTable) {
261 SerializedURI chromeURI, overrideURI;
263 SerializeURI(entry.GetKey(), chromeURI);
264 SerializeURI(entry.GetWeak(), overrideURI);
266 overrides.AppendElement(
267 OverrideMapping{std::move(chromeURI), std::move(overrideURI)});
270 nsAutoCString appLocale;
271 LocaleService::GetInstance()->GetAppLocaleAsBCP47(appLocale);
273 if (aParent) {
274 bool success = aParent->SendRegisterChrome(packages, resources, overrides,
275 appLocale, false);
276 NS_ENSURE_TRUE_VOID(success);
277 } else {
278 nsTArray<ContentParent*> parents;
279 ContentParent::GetAll(parents);
280 if (!parents.Length()) return;
282 for (uint32_t i = 0; i < parents.Length(); i++) {
283 DebugOnly<bool> success = parents[i]->SendRegisterChrome(
284 packages, resources, overrides, appLocale, true);
285 NS_WARNING_ASSERTION(success,
286 "couldn't reset a child's registered chrome");
291 /* static */
292 void nsChromeRegistryChrome::ChromePackageFromPackageEntry(
293 const nsACString& aPackageName, PackageEntry* aPackage,
294 ChromePackage* aChromePackage, const nsCString& aSelectedSkin) {
295 nsAutoCString appLocale;
296 LocaleService::GetInstance()->GetAppLocaleAsBCP47(appLocale);
298 SerializeURI(aPackage->baseURI, aChromePackage->contentBaseURI);
299 SerializeURI(aPackage->locales.GetBase(appLocale, nsProviderArray::LOCALE),
300 aChromePackage->localeBaseURI);
301 SerializeURI(aPackage->skins.GetBase(aSelectedSkin, nsProviderArray::ANY),
302 aChromePackage->skinBaseURI);
303 aChromePackage->package = aPackageName;
304 aChromePackage->flags = aPackage->flags;
307 static bool CanLoadResource(nsIURI* aResourceURI) {
308 bool isLocalResource = false;
309 (void)NS_URIChainHasFlags(aResourceURI,
310 nsIProtocolHandler::URI_IS_LOCAL_RESOURCE,
311 &isLocalResource);
312 return isLocalResource;
315 nsIURI* nsChromeRegistryChrome::GetBaseURIFromPackage(
316 const nsCString& aPackage, const nsCString& aProvider,
317 const nsCString& aPath) {
318 PackageEntry* entry;
319 if (!mPackagesHash.Get(aPackage, &entry)) {
320 if (!mInitialized) return nullptr;
322 LogMessage("No chrome package registered for chrome://%s/%s/%s",
323 aPackage.get(), aProvider.get(), aPath.get());
325 return nullptr;
328 if (aProvider.EqualsLiteral("locale")) {
329 nsAutoCString appLocale;
330 LocaleService::GetInstance()->GetAppLocaleAsLangTag(appLocale);
331 return entry->locales.GetBase(appLocale, nsProviderArray::LOCALE);
334 if (aProvider.EqualsLiteral("skin")) {
335 return entry->skins.GetBase(SKIN, nsProviderArray::ANY);
338 if (aProvider.EqualsLiteral("content")) {
339 return entry->baseURI;
341 return nullptr;
344 nsresult nsChromeRegistryChrome::GetFlagsFromPackage(const nsCString& aPackage,
345 uint32_t* aFlags) {
346 PackageEntry* entry;
347 if (!mPackagesHash.Get(aPackage, &entry)) return NS_ERROR_FILE_NOT_FOUND;
349 *aFlags = entry->flags;
350 return NS_OK;
353 nsChromeRegistryChrome::ProviderEntry*
354 nsChromeRegistryChrome::nsProviderArray::GetProvider(
355 const nsACString& aPreferred, MatchType aType) {
356 size_t i = mArray.Length();
357 if (!i) return nullptr;
359 ProviderEntry* found = nullptr; // Only set if we find a partial-match locale
360 ProviderEntry* entry = nullptr;
362 while (i--) {
363 entry = &mArray[i];
364 if (aPreferred.Equals(entry->provider)) return entry;
366 if (aType != LOCALE) continue;
368 if (LanguagesMatch(aPreferred, entry->provider)) {
369 found = entry;
370 continue;
373 if (!found && entry->provider.EqualsLiteral("en-US")) found = entry;
376 if (!found && aType != EXACT) return entry;
378 return found;
381 nsIURI* nsChromeRegistryChrome::nsProviderArray::GetBase(
382 const nsACString& aPreferred, MatchType aType) {
383 ProviderEntry* provider = GetProvider(aPreferred, aType);
385 if (!provider) return nullptr;
387 return provider->baseURI;
390 const nsACString& nsChromeRegistryChrome::nsProviderArray::GetSelected(
391 const nsACString& aPreferred, MatchType aType) {
392 ProviderEntry* entry = GetProvider(aPreferred, aType);
394 if (entry) return entry->provider;
396 return EmptyCString();
399 void nsChromeRegistryChrome::nsProviderArray::SetBase(
400 const nsACString& aProvider, nsIURI* aBaseURL) {
401 ProviderEntry* provider = GetProvider(aProvider, EXACT);
403 if (provider) {
404 provider->baseURI = aBaseURL;
405 return;
408 // no existing entries, add a new one
409 mArray.AppendElement(ProviderEntry(aProvider, aBaseURL));
412 void nsChromeRegistryChrome::nsProviderArray::EnumerateToArray(
413 nsTArray<nsCString>* a) {
414 int32_t i = mArray.Length();
415 while (i--) {
416 a->AppendElement(mArray[i].provider);
420 nsIURI* nsChromeRegistry::ManifestProcessingContext::GetManifestURI() {
421 if (!mManifestURI) {
422 nsCString uri;
423 mFile.GetURIString(uri);
424 NS_NewURI(getter_AddRefs(mManifestURI), uri);
426 return mManifestURI;
429 already_AddRefed<nsIURI>
430 nsChromeRegistry::ManifestProcessingContext::ResolveURI(const char* uri) {
431 nsIURI* baseuri = GetManifestURI();
432 if (!baseuri) return nullptr;
434 nsCOMPtr<nsIURI> resolved;
435 nsresult rv = NS_NewURI(getter_AddRefs(resolved), uri, baseuri);
436 if (NS_FAILED(rv)) return nullptr;
438 return resolved.forget();
441 static void EnsureLowerCase(char* aBuf) {
442 for (; *aBuf; ++aBuf) {
443 char ch = *aBuf;
444 if (ch >= 'A' && ch <= 'Z') *aBuf = ch + 'a' - 'A';
448 static void SendManifestEntry(const ChromeRegistryItem& aItem) {
449 nsTArray<ContentParent*> parents;
450 ContentParent::GetAll(parents);
451 if (!parents.Length()) return;
453 for (uint32_t i = 0; i < parents.Length(); i++) {
454 Unused << parents[i]->SendRegisterChromeItem(aItem);
458 void nsChromeRegistryChrome::ManifestContent(ManifestProcessingContext& cx,
459 int lineno, char* const* argv,
460 int flags) {
461 char* package = argv[0];
462 char* uri = argv[1];
464 EnsureLowerCase(package);
466 nsCOMPtr<nsIURI> resolved = cx.ResolveURI(uri);
467 if (!resolved) {
468 LogMessageWithContext(
469 cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
470 "During chrome registration, unable to create URI '%s'.", uri);
471 return;
474 if (!CanLoadResource(resolved)) {
475 LogMessageWithContext(resolved, lineno, nsIScriptError::warningFlag,
476 "During chrome registration, cannot register "
477 "non-local URI '%s' as content.",
478 uri);
479 return;
482 nsDependentCString packageName(package);
483 PackageEntry* entry = mPackagesHash.GetOrInsertNew(packageName);
484 entry->baseURI = resolved;
485 entry->flags = flags;
487 if (mDynamicRegistration) {
488 ChromePackage chromePackage;
489 ChromePackageFromPackageEntry(packageName, entry, &chromePackage, SKIN);
490 SendManifestEntry(chromePackage);
494 void nsChromeRegistryChrome::ManifestLocale(ManifestProcessingContext& cx,
495 int lineno, char* const* argv,
496 int flags) {
497 char* package = argv[0];
498 char* provider = argv[1];
499 char* uri = argv[2];
501 EnsureLowerCase(package);
503 nsCOMPtr<nsIURI> resolved = cx.ResolveURI(uri);
504 if (!resolved) {
505 LogMessageWithContext(
506 cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
507 "During chrome registration, unable to create URI '%s'.", uri);
508 return;
511 if (!CanLoadResource(resolved)) {
512 LogMessageWithContext(resolved, lineno, nsIScriptError::warningFlag,
513 "During chrome registration, cannot register "
514 "non-local URI '%s' as content.",
515 uri);
516 return;
519 nsDependentCString packageName(package);
520 PackageEntry* entry = mPackagesHash.GetOrInsertNew(packageName);
521 entry->locales.SetBase(nsDependentCString(provider), resolved);
523 if (mDynamicRegistration) {
524 ChromePackage chromePackage;
525 ChromePackageFromPackageEntry(packageName, entry, &chromePackage, SKIN);
526 SendManifestEntry(chromePackage);
529 // We use mainPackage as the package we track for reporting new locales being
530 // registered. For most cases it will be "global", but for Fennec it will be
531 // "browser".
532 nsAutoCString mainPackage;
533 nsresult rv = OverrideLocalePackage("global"_ns, mainPackage);
534 if (NS_FAILED(rv)) {
535 return;
539 void nsChromeRegistryChrome::ManifestSkin(ManifestProcessingContext& cx,
540 int lineno, char* const* argv,
541 int flags) {
542 char* package = argv[0];
543 char* provider = argv[1];
544 char* uri = argv[2];
546 EnsureLowerCase(package);
548 nsCOMPtr<nsIURI> resolved = cx.ResolveURI(uri);
549 if (!resolved) {
550 LogMessageWithContext(
551 cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
552 "During chrome registration, unable to create URI '%s'.", uri);
553 return;
556 if (!CanLoadResource(resolved)) {
557 LogMessageWithContext(resolved, lineno, nsIScriptError::warningFlag,
558 "During chrome registration, cannot register "
559 "non-local URI '%s' as content.",
560 uri);
561 return;
564 nsDependentCString packageName(package);
565 PackageEntry* entry = mPackagesHash.GetOrInsertNew(packageName);
566 entry->skins.SetBase(nsDependentCString(provider), resolved);
568 if (mDynamicRegistration) {
569 ChromePackage chromePackage;
570 ChromePackageFromPackageEntry(packageName, entry, &chromePackage, SKIN);
571 SendManifestEntry(chromePackage);
575 void nsChromeRegistryChrome::ManifestOverride(ManifestProcessingContext& cx,
576 int lineno, char* const* argv,
577 int flags) {
578 char* chrome = argv[0];
579 char* resolved = argv[1];
581 nsCOMPtr<nsIURI> chromeuri = cx.ResolveURI(chrome);
582 nsCOMPtr<nsIURI> resolveduri = cx.ResolveURI(resolved);
583 if (!chromeuri || !resolveduri) {
584 LogMessageWithContext(cx.GetManifestURI(), lineno,
585 nsIScriptError::warningFlag,
586 "During chrome registration, unable to create URI.");
587 return;
590 if (cx.mType == NS_SKIN_LOCATION) {
591 bool chromeSkinOnly =
592 chromeuri->SchemeIs("chrome") && resolveduri->SchemeIs("chrome");
593 if (chromeSkinOnly) {
594 nsAutoCString chromePath, resolvedPath;
595 chromeuri->GetPathQueryRef(chromePath);
596 resolveduri->GetPathQueryRef(resolvedPath);
597 chromeSkinOnly = StringBeginsWith(chromePath, "/skin/"_ns) &&
598 StringBeginsWith(resolvedPath, "/skin/"_ns);
600 if (!chromeSkinOnly) {
601 LogMessageWithContext(
602 cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
603 "Cannot register non-chrome://.../skin/ URIs '%s' and '%s' as "
604 "overrides and/or to be overridden from a skin manifest.",
605 chrome, resolved);
606 return;
610 if (!CanLoadResource(resolveduri)) {
611 LogMessageWithContext(
612 cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
613 "Cannot register non-local URI '%s' for an override.", resolved);
614 return;
616 mOverrideTable.InsertOrUpdate(chromeuri, resolveduri);
618 if (mDynamicRegistration) {
619 SerializedURI serializedChrome;
620 SerializedURI serializedOverride;
622 SerializeURI(chromeuri, serializedChrome);
623 SerializeURI(resolveduri, serializedOverride);
625 OverrideMapping override = {serializedChrome, serializedOverride};
626 SendManifestEntry(override);
630 void nsChromeRegistryChrome::ManifestResource(ManifestProcessingContext& cx,
631 int lineno, char* const* argv,
632 int flags) {
633 char* package = argv[0];
634 char* uri = argv[1];
636 EnsureLowerCase(package);
637 nsDependentCString host(package);
639 nsCOMPtr<nsIIOService> io = mozilla::components::IO::Service();
640 if (!io) {
641 NS_WARNING("No IO service trying to process chrome manifests");
642 return;
645 nsCOMPtr<nsIProtocolHandler> ph;
646 nsresult rv = io->GetProtocolHandler("resource", getter_AddRefs(ph));
647 if (NS_FAILED(rv)) return;
649 nsCOMPtr<nsIResProtocolHandler> rph = do_QueryInterface(ph);
651 nsCOMPtr<nsIURI> resolved = cx.ResolveURI(uri);
652 if (!resolved) {
653 LogMessageWithContext(
654 cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
655 "During chrome registration, unable to create URI '%s'.", uri);
656 return;
659 if (!CanLoadResource(resolved)) {
660 LogMessageWithContext(
661 cx.GetManifestURI(), lineno, nsIScriptError::warningFlag,
662 "Warning: cannot register non-local URI '%s' as a resource.", uri);
663 return;
666 // By default, Firefox resources are not content-accessible unless the
667 // manifests opts in.
668 bool contentAccessible = (flags & nsChromeRegistry::CONTENT_ACCESSIBLE);
670 uint32_t substitutionFlags = 0;
671 if (contentAccessible) {
672 substitutionFlags |= nsIResProtocolHandler::ALLOW_CONTENT_ACCESS;
674 rv = rph->SetSubstitutionWithFlags(host, resolved, substitutionFlags);
675 if (NS_FAILED(rv)) {
676 LogMessageWithContext(cx.GetManifestURI(), lineno,
677 nsIScriptError::warningFlag,
678 "Warning: cannot set substitution for '%s'.", uri);