1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 var EXPORTED_SYMBOLS = ["BootstrapLoader"];
9 const {AddonManager} = ChromeUtils.import("resource://gre/modules/AddonManager.jsm");
10 const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
12 XPCOMUtils.defineLazyModuleGetters(this, {
13 AddonInternal: "resource://gre/modules/addons/XPIDatabase.jsm",
14 InstallRDF: "resource://legacy/RDFManifestConverter.jsm",
16 const Services = globalThis.Services || ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
18 (ChromeUtils.defineLazyGetter||XPCOMUtils.defineLazyGetter)(this, "BOOTSTRAP_REASONS", () => {
19 const {XPIProvider} = ChromeUtils.import("resource://gre/modules/addons/XPIProvider.jsm");
20 return XPIProvider.BOOTSTRAP_REASONS;
23 var logger = console.createInstance({ prefix: "addons.bootstrap" });
26 * Valid IDs fit this pattern.
28 var gIDTest = /^(\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}|[a-z0-9-\._]*\@[a-z0-9-\._]+)$/i;
30 // Properties that exist in the install manifest
31 const PROP_METADATA = ["id", "version", "type", "internalName", "updateURL",
32 "optionsURL", "optionsType", "aboutURL", "iconURL"];
33 const PROP_LOCALE_SINGLE = ["name", "description", "creator", "homepageURL"];
34 const PROP_LOCALE_MULTI = ["developers", "translators", "contributors"];
36 // Map new string type identifiers to old style nsIUpdateItem types.
38 // 32 = multipackage xpi file
48 const COMPATIBLE_BY_DEFAULT_TYPES = {
53 const hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty);
55 function isXPI(filename) {
56 let ext = filename.slice(-4).toLowerCase();
57 return ext === ".xpi" || ext === ".zip";
61 * Gets an nsIURI for a file within another file, either a directory or an XPI
62 * file. If aFile is a directory then this will return a file: URI, if it is an
63 * XPI file then it will return a jar: URI.
65 * @param {nsIFile} aFile
66 * The file containing the resources, must be either a directory or an
68 * @param {string} aPath
69 * The path to find the resource at, "/" separated. If aPath is empty
70 * then the uri to the root of the contained files will be returned
72 * An nsIURI pointing at the resource
74 function getURIForResourceInFile(aFile, aPath) {
75 if (!isXPI(aFile.leafName)) {
76 let resource = aFile.clone();
78 aPath.split("/").forEach(part => resource.append(part));
80 return Services.io.newFileURI(resource);
83 return buildJarURI(aFile, aPath);
87 * Creates a jar: URI for a file inside a ZIP file.
89 * @param {nsIFile} aJarfile
90 * The ZIP file as an nsIFile
91 * @param {string} aPath
92 * The path inside the ZIP file
94 * An nsIURI for the file
96 function buildJarURI(aJarfile, aPath) {
97 let uri = Services.io.newFileURI(aJarfile);
98 uri = "jar:" + uri.spec + "!/" + aPath;
99 return Services.io.newURI(uri);
102 var BootstrapLoader = {
104 manifestFile: "install.rdf",
105 async loadManifest(pkg) {
107 * Reads locale properties from either the main install manifest root or
108 * an em:localized section in the install manifest.
110 * @param {Object} aSource
111 * The resource to read the properties from.
112 * @param {boolean} isDefault
113 * True if the locale is to be read from the main install manifest
115 * @param {string[]} aSeenLocales
116 * An array of locale names already seen for this install manifest.
117 * Any locale names seen as a part of this function will be added to
120 * an object containing the locale properties
122 function readLocale(aSource, isDefault, aSeenLocales) {
126 for (let localeName of aSource.locales || []) {
128 logger.warn("Ignoring empty locale in localized properties");
131 if (aSeenLocales.includes(localeName)) {
132 logger.warn("Ignoring duplicate locale in localized properties");
135 aSeenLocales.push(localeName);
136 locale.locales.push(localeName);
139 if (locale.locales.length == 0) {
140 logger.warn("Ignoring localized properties with no listed locales");
145 for (let prop of [...PROP_LOCALE_SINGLE, ...PROP_LOCALE_MULTI]) {
146 if (hasOwnProperty(aSource, prop)) {
147 locale[prop] = aSource[prop];
154 let manifestData = await pkg.readString("install.rdf");
155 let manifest = InstallRDF.loadFromString(manifestData).decode();
157 let addon = new AddonInternal();
158 for (let prop of PROP_METADATA) {
159 if (hasOwnProperty(manifest, prop)) {
160 addon[prop] = manifest[prop];
165 addon.type = "extension";
167 let type = addon.type;
169 for (let name in TYPES) {
170 if (TYPES[name] == type) {
177 if (!(addon.type in TYPES))
178 throw new Error("Install manifest specifies unknown type: " + addon.type);
181 throw new Error("No ID in install manifest");
182 if (!gIDTest.test(addon.id))
183 throw new Error("Illegal add-on ID " + addon.id);
185 throw new Error("No version in install manifest");
187 addon.strictCompatibility = (!(addon.type in COMPATIBLE_BY_DEFAULT_TYPES) ||
188 manifest.strictCompatibility == "true");
190 // Only read these properties for extensions.
191 if (addon.type == "extension") {
192 if (manifest.bootstrap != "true") {
193 throw new Error("Non-restartless extensions no longer supported");
196 if (addon.optionsType &&
197 addon.optionsType != AddonManager.OPTIONS_TYPE_INLINE_BROWSER &&
198 addon.optionsType != AddonManager.OPTIONS_TYPE_TAB) {
199 throw new Error("Install manifest specifies unknown optionsType: " + addon.optionsType);
202 // Convert legacy dictionaries into a format the WebExtension
203 // dictionary loader can process.
204 if (addon.type === "dictionary") {
206 let dictionaries = {};
207 await pkg.iterFiles(({path}) => {
208 let match = /^dictionaries\/([^\/]+)\.dic$/.exec(path);
210 let lang = match[1].replace(/_/g, "-");
211 dictionaries[lang] = match[0];
214 addon.startupData = {dictionaries};
217 // Only extensions are allowed to provide an optionsURL, optionsType,
218 // optionsBrowserStyle, or aboutURL. For all other types they are silently ignored
219 addon.aboutURL = null;
220 addon.optionsBrowserStyle = null;
221 addon.optionsType = null;
222 addon.optionsURL = null;
225 addon.defaultLocale = readLocale(manifest, true);
227 let seenLocales = [];
229 for (let localeData of manifest.localized || []) {
230 let locale = readLocale(localeData, false, seenLocales);
232 addon.locales.push(locale);
235 let dependencies = new Set(manifest.dependencies);
236 addon.dependencies = Object.freeze(Array.from(dependencies));
238 let seenApplications = [];
239 addon.targetApplications = [];
240 for (let targetApp of manifest.targetApplications || []) {
241 if (!targetApp.id || !targetApp.minVersion ||
242 !targetApp.maxVersion) {
243 logger.warn("Ignoring invalid targetApplication entry in install manifest");
246 if (seenApplications.includes(targetApp.id)) {
247 logger.warn("Ignoring duplicate targetApplication entry for " + targetApp.id +
248 " in install manifest");
251 seenApplications.push(targetApp.id);
252 addon.targetApplications.push(targetApp);
255 // Note that we don't need to check for duplicate targetPlatform entries since
256 // the RDF service coalesces them for us.
257 addon.targetPlatforms = [];
258 for (let targetPlatform of manifest.targetPlatforms || []) {
264 let pos = targetPlatform.indexOf("_");
266 platform.os = targetPlatform.substring(0, pos);
267 platform.abi = targetPlatform.substring(pos + 1);
269 platform.os = targetPlatform;
272 addon.targetPlatforms.push(platform);
275 addon.userDisabled = false;
276 addon.softDisabled = addon.blocklistState == Ci.nsIBlocklistService.STATE_SOFTBLOCKED;
277 addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT;
279 addon.userPermissions = null;
282 if (await pkg.hasResource("icon.png")) {
283 addon.icons[32] = "icon.png";
284 addon.icons[48] = "icon.png";
287 if (await pkg.hasResource("icon64.png")) {
288 addon.icons[64] = "icon64.png";
295 let file = addon.file || addon._sourceBundle;
296 let uri = getURIForResourceInFile(file, "bootstrap.js").spec;
297 let principal = Services.scriptSecurityManager.getSystemPrincipal();
299 let sandbox = new Cu.Sandbox(principal, {
302 wantGlobalProperties: ["ChromeUtils"],
303 metadata: { addonID: addon.id, URI: uri },
307 Object.assign(sandbox, BOOTSTRAP_REASONS);
309 (ChromeUtils.defineLazyGetter||XPCOMUtils.defineLazyGetter)(sandbox, "console", () =>
310 console.createInstance({ consoleID: `addon/${addon.id}` }));
312 Services.scriptloader.loadSubScript(uri, sandbox);
314 logger.warn(`Error loading bootstrap.js for ${addon.id}`, e);
317 function findMethod(name) {
319 return sandbox[name];
323 let method = Cu.evalInSandbox(name, sandbox);
328 logger.warn(`Add-on ${addon.id} is missing bootstrap method ${name}`);
332 let install = findMethod("install");
333 let uninstall = findMethod("uninstall");
334 let startup = findMethod("startup");
335 let shutdown = findMethod("shutdown");
338 install: (...args) => install(...args),
342 // Forget any cached files we might've had from this extension.
343 Services.obs.notifyObservers(null, "startupcache-invalidate");
347 if (addon.type == "extension") {
348 logger.debug(`Registering manifest for ${file.path}\n`);
349 Components.manager.addBootstrappedManifestLocation(file);
351 return startup(...args);
354 shutdown(data, reason) {
356 return shutdown(data, reason);
360 if (reason != BOOTSTRAP_REASONS.APP_SHUTDOWN) {
361 logger.debug(`Removing manifest for ${file.path}\n`);
362 Components.manager.removeBootstrappedManifestLocation(file);