Bug 1591736 - Fix AddonManagerWebAPI::IsAPIEnabled in out-of-process iframes r=mixedpuppy
[gecko.git] / chrome / nsChromeRegistry.cpp
blobe8f32e28f6574dc3cc62d20ed9874a905d283245
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 sw=2 et tw=78: */
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 "nsChromeRegistry.h"
8 #include "nsChromeRegistryChrome.h"
9 #include "nsChromeRegistryContent.h"
11 #include "nsCOMPtr.h"
12 #include "nsError.h"
13 #include "nsEscape.h"
14 #include "nsNetUtil.h"
15 #include "nsString.h"
16 #include "nsQueryObject.h"
18 #include "mozilla/dom/URL.h"
19 #include "nsIConsoleService.h"
20 #include "mozilla/dom/Document.h"
21 #include "nsIObserverService.h"
22 #include "nsIScriptError.h"
23 #include "nsIWindowMediator.h"
24 #include "nsIPrefService.h"
25 #include "mozilla/Preferences.h"
26 #include "mozilla/PresShell.h"
27 #include "mozilla/Printf.h"
28 #include "mozilla/StyleSheet.h"
29 #include "mozilla/StyleSheetInlines.h"
30 #include "mozilla/dom/Location.h"
31 #include "nsIURIMutator.h"
33 #include "unicode/uloc.h"
35 nsChromeRegistry* nsChromeRegistry::gChromeRegistry;
37 // DO NOT use namespace mozilla; it'll break due to a naming conflict between
38 // mozilla::TextRange and a TextRange in OSX headers.
39 using mozilla::PresShell;
40 using mozilla::StyleSheet;
41 using mozilla::dom::Document;
42 using mozilla::dom::Location;
44 ////////////////////////////////////////////////////////////////////////////////
46 void nsChromeRegistry::LogMessage(const char* aMsg, ...) {
47 nsCOMPtr<nsIConsoleService> console(
48 do_GetService(NS_CONSOLESERVICE_CONTRACTID));
49 if (!console) return;
51 va_list args;
52 va_start(args, aMsg);
53 mozilla::SmprintfPointer formatted = mozilla::Vsmprintf(aMsg, args);
54 va_end(args);
55 if (!formatted) return;
57 console->LogStringMessage(NS_ConvertUTF8toUTF16(formatted.get()).get());
60 void nsChromeRegistry::LogMessageWithContext(nsIURI* aURL, uint32_t aLineNumber,
61 uint32_t flags, const char* aMsg,
62 ...) {
63 nsresult rv;
65 nsCOMPtr<nsIConsoleService> console(
66 do_GetService(NS_CONSOLESERVICE_CONTRACTID));
68 nsCOMPtr<nsIScriptError> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
69 if (!console || !error) return;
71 va_list args;
72 va_start(args, aMsg);
73 mozilla::SmprintfPointer formatted = mozilla::Vsmprintf(aMsg, args);
74 va_end(args);
75 if (!formatted) return;
77 nsCString spec;
78 if (aURL) aURL->GetSpec(spec);
80 rv = error->Init(
81 NS_ConvertUTF8toUTF16(formatted.get()), NS_ConvertUTF8toUTF16(spec),
82 EmptyString(), aLineNumber, 0, flags, "chrome registration",
83 false /* from private window */, true /* from chrome context */);
85 if (NS_FAILED(rv)) return;
87 console->LogMessage(error);
90 nsChromeRegistry::~nsChromeRegistry() { gChromeRegistry = nullptr; }
92 NS_INTERFACE_MAP_BEGIN(nsChromeRegistry)
93 NS_INTERFACE_MAP_ENTRY(nsIChromeRegistry)
94 NS_INTERFACE_MAP_ENTRY(nsIXULChromeRegistry)
95 NS_INTERFACE_MAP_ENTRY(nsIToolkitChromeRegistry)
96 NS_INTERFACE_MAP_ENTRY(nsIObserver)
97 NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
98 NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIChromeRegistry)
99 NS_INTERFACE_MAP_END
101 NS_IMPL_ADDREF(nsChromeRegistry)
102 NS_IMPL_RELEASE(nsChromeRegistry)
104 ////////////////////////////////////////////////////////////////////////////////
105 // nsIChromeRegistry methods:
107 already_AddRefed<nsIChromeRegistry> nsChromeRegistry::GetService() {
108 if (!gChromeRegistry) {
109 // We don't actually want this ref, we just want the service to
110 // initialize if it hasn't already.
111 nsCOMPtr<nsIChromeRegistry> reg(
112 do_GetService(NS_CHROMEREGISTRY_CONTRACTID));
113 if (!gChromeRegistry) return nullptr;
115 nsCOMPtr<nsIChromeRegistry> registry = gChromeRegistry;
116 return registry.forget();
119 nsresult nsChromeRegistry::Init() {
120 // This initialization process is fairly complicated and may cause reentrant
121 // getservice calls to resolve chrome URIs (especially locale files). We
122 // don't want that, so we inform the protocol handler about our existence
123 // before we are actually fully initialized.
124 gChromeRegistry = this;
126 mInitialized = true;
128 return NS_OK;
131 nsresult nsChromeRegistry::GetProviderAndPath(nsIURI* aChromeURL,
132 nsACString& aProvider,
133 nsACString& aPath) {
134 nsresult rv;
136 NS_ASSERTION(aChromeURL->SchemeIs("chrome"), "Non-chrome URI?");
138 nsAutoCString path;
139 rv = aChromeURL->GetPathQueryRef(path);
140 NS_ENSURE_SUCCESS(rv, rv);
142 if (path.Length() < 3) {
143 LogMessage("Invalid chrome URI: %s", path.get());
144 return NS_ERROR_FAILURE;
147 path.SetLength(nsUnescapeCount(path.BeginWriting()));
148 NS_ASSERTION(path.First() == '/', "Path should always begin with a slash!");
150 int32_t slash = path.FindChar('/', 1);
151 if (slash == 1) {
152 LogMessage("Invalid chrome URI: %s", path.get());
153 return NS_ERROR_FAILURE;
156 if (slash == -1) {
157 aPath.Truncate();
158 } else {
159 if (slash == (int32_t)path.Length() - 1)
160 aPath.Truncate();
161 else
162 aPath.Assign(path.get() + slash + 1, path.Length() - slash - 1);
164 --slash;
167 aProvider.Assign(path.get() + 1, slash);
168 return NS_OK;
171 nsresult nsChromeRegistry::Canonify(nsCOMPtr<nsIURI>& aChromeURL) {
172 NS_NAMED_LITERAL_CSTRING(kSlash, "/");
174 nsresult rv;
176 nsAutoCString provider, path;
177 rv = GetProviderAndPath(aChromeURL, provider, path);
178 NS_ENSURE_SUCCESS(rv, rv);
180 if (path.IsEmpty()) {
181 nsAutoCString package;
182 rv = aChromeURL->GetHost(package);
183 NS_ENSURE_SUCCESS(rv, rv);
185 // we re-use the "path" local string to build a new URL path
186 path.Assign(kSlash + provider + kSlash + package);
187 if (provider.EqualsLiteral("content")) {
188 path.AppendLiteral(".xul");
189 } else if (provider.EqualsLiteral("locale")) {
190 path.AppendLiteral(".dtd");
191 } else if (provider.EqualsLiteral("skin")) {
192 path.AppendLiteral(".css");
193 } else {
194 return NS_ERROR_INVALID_ARG;
196 return NS_MutateURI(aChromeURL).SetPathQueryRef(path).Finalize(aChromeURL);
197 } else {
198 // prevent directory traversals ("..")
199 // path is already unescaped once, but uris can get unescaped twice
200 const char* pos = path.BeginReading();
201 const char* end = path.EndReading();
202 // Must start with [a-zA-Z0-9].
203 if (!('a' <= *pos && *pos <= 'z') && !('A' <= *pos && *pos <= 'Z') &&
204 !('0' <= *pos && *pos <= '9')) {
205 return NS_ERROR_DOM_BAD_URI;
207 while (pos < end) {
208 switch (*pos) {
209 case ':':
210 return NS_ERROR_DOM_BAD_URI;
211 case '.':
212 if (pos[1] == '.') return NS_ERROR_DOM_BAD_URI;
213 break;
214 case '%':
215 // chrome: URIs with double-escapes are trying to trick us.
216 // watch for %2e, and %25 in case someone triple unescapes
217 if (pos[1] == '2' &&
218 (pos[2] == 'e' || pos[2] == 'E' || pos[2] == '5'))
219 return NS_ERROR_DOM_BAD_URI;
220 break;
221 case '?':
222 case '#':
223 pos = end;
224 continue;
226 ++pos;
230 return NS_OK;
233 NS_IMETHODIMP
234 nsChromeRegistry::ConvertChromeURL(nsIURI* aChromeURI, nsIURI** aResult) {
235 nsresult rv;
236 if (NS_WARN_IF(!aChromeURI)) {
237 return NS_ERROR_INVALID_ARG;
240 if (mOverrideTable.Get(aChromeURI, aResult)) return NS_OK;
242 nsCOMPtr<nsIURL> chromeURL(do_QueryInterface(aChromeURI));
243 NS_ENSURE_TRUE(chromeURL, NS_NOINTERFACE);
245 nsAutoCString package, provider, path;
246 rv = chromeURL->GetHostPort(package);
247 NS_ENSURE_SUCCESS(rv, rv);
249 rv = GetProviderAndPath(chromeURL, provider, path);
250 NS_ENSURE_SUCCESS(rv, rv);
252 nsIURI* baseURI = GetBaseURIFromPackage(package, provider, path);
254 uint32_t flags;
255 rv = GetFlagsFromPackage(package, &flags);
256 if (NS_FAILED(rv)) return rv;
258 if (!baseURI) {
259 LogMessage("No chrome package registered for chrome://%s/%s/%s",
260 package.get(), provider.get(), path.get());
261 return NS_ERROR_FILE_NOT_FOUND;
264 return NS_NewURI(aResult, path, nullptr, baseURI);
267 ////////////////////////////////////////////////////////////////////////
269 void nsChromeRegistry::FlushAllCaches() {
270 nsCOMPtr<nsIObserverService> obsSvc = mozilla::services::GetObserverService();
271 NS_ASSERTION(obsSvc, "Couldn't get observer service.");
273 obsSvc->NotifyObservers((nsIChromeRegistry*)this, NS_CHROME_FLUSH_TOPIC,
274 nullptr);
277 NS_IMETHODIMP
278 nsChromeRegistry::AllowScriptsForPackage(nsIURI* aChromeURI, bool* aResult) {
279 nsresult rv;
280 *aResult = false;
282 NS_ASSERTION(aChromeURI->SchemeIs("chrome"),
283 "Non-chrome URI passed to AllowScriptsForPackage!");
285 nsCOMPtr<nsIURL> url(do_QueryInterface(aChromeURI));
286 NS_ENSURE_TRUE(url, NS_NOINTERFACE);
288 nsAutoCString provider, file;
289 rv = GetProviderAndPath(url, provider, file);
290 NS_ENSURE_SUCCESS(rv, rv);
292 if (!provider.EqualsLiteral("skin")) *aResult = true;
294 return NS_OK;
297 NS_IMETHODIMP
298 nsChromeRegistry::AllowContentToAccess(nsIURI* aURI, bool* aResult) {
299 nsresult rv;
301 *aResult = false;
303 NS_ASSERTION(aURI->SchemeIs("chrome"),
304 "Non-chrome URI passed to AllowContentToAccess!");
306 nsCOMPtr<nsIURL> url = do_QueryInterface(aURI);
307 if (!url) {
308 NS_ERROR("Chrome URL doesn't implement nsIURL.");
309 return NS_ERROR_UNEXPECTED;
312 nsAutoCString package;
313 rv = url->GetHostPort(package);
314 NS_ENSURE_SUCCESS(rv, rv);
316 uint32_t flags;
317 rv = GetFlagsFromPackage(package, &flags);
319 if (NS_SUCCEEDED(rv)) {
320 *aResult = !!(flags & CONTENT_ACCESSIBLE);
322 return NS_OK;
325 NS_IMETHODIMP
326 nsChromeRegistry::CanLoadURLRemotely(nsIURI* aURI, bool* aResult) {
327 nsresult rv;
329 *aResult = false;
331 NS_ASSERTION(aURI->SchemeIs("chrome"),
332 "Non-chrome URI passed to CanLoadURLRemotely!");
334 nsCOMPtr<nsIURL> url = do_QueryInterface(aURI);
335 if (!url) {
336 NS_ERROR("Chrome URL doesn't implement nsIURL.");
337 return NS_ERROR_UNEXPECTED;
340 nsAutoCString package;
341 rv = url->GetHostPort(package);
342 NS_ENSURE_SUCCESS(rv, rv);
344 uint32_t flags;
345 rv = GetFlagsFromPackage(package, &flags);
347 if (NS_SUCCEEDED(rv)) {
348 *aResult = !!(flags & REMOTE_ALLOWED);
350 return NS_OK;
353 NS_IMETHODIMP
354 nsChromeRegistry::MustLoadURLRemotely(nsIURI* aURI, bool* aResult) {
355 nsresult rv;
357 *aResult = false;
359 NS_ASSERTION(aURI->SchemeIs("chrome"),
360 "Non-chrome URI passed to MustLoadURLRemotely!");
362 nsCOMPtr<nsIURL> url = do_QueryInterface(aURI);
363 if (!url) {
364 NS_ERROR("Chrome URL doesn't implement nsIURL.");
365 return NS_ERROR_UNEXPECTED;
368 nsAutoCString package;
369 rv = url->GetHostPort(package);
370 NS_ENSURE_SUCCESS(rv, rv);
372 uint32_t flags;
373 rv = GetFlagsFromPackage(package, &flags);
375 if (NS_SUCCEEDED(rv)) {
376 *aResult = !!(flags & REMOTE_REQUIRED);
378 return NS_OK;
381 bool nsChromeRegistry::GetDirectionForLocale(const nsACString& aLocale) {
382 int pref = mozilla::Preferences::GetInt("intl.uidirection", -1);
383 if (pref >= 0) {
384 return (pref > 0);
386 nsAutoCString locale(aLocale);
387 SanitizeForBCP47(locale);
388 return uloc_isRightToLeft(locale.get());
391 already_AddRefed<nsChromeRegistry> nsChromeRegistry::GetSingleton() {
392 if (gChromeRegistry) {
393 RefPtr<nsChromeRegistry> registry = gChromeRegistry;
394 return registry.forget();
397 RefPtr<nsChromeRegistry> cr;
398 if (GeckoProcessType_Content == XRE_GetProcessType())
399 cr = new nsChromeRegistryContent();
400 else
401 cr = new nsChromeRegistryChrome();
403 if (NS_FAILED(cr->Init())) return nullptr;
405 return cr.forget();
408 void nsChromeRegistry::SanitizeForBCP47(nsACString& aLocale) {
409 // Currently, the only locale code we use that's not BCP47-conformant is
410 // "ja-JP-mac" on OS X, but let's try to be more general than just
411 // hard-coding that here.
412 const int32_t LANG_TAG_CAPACITY = 128;
413 char langTag[LANG_TAG_CAPACITY];
414 nsAutoCString locale(aLocale);
415 UErrorCode err = U_ZERO_ERROR;
416 // This is a fail-safe method that will set langTag to "und" if it cannot
417 // match any part of the input locale code.
418 int32_t len =
419 uloc_toLanguageTag(locale.get(), langTag, LANG_TAG_CAPACITY, false, &err);
420 if (U_SUCCESS(err) && len > 0) {
421 aLocale.Assign(langTag, len);