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 Blocklist: "resource://gre/modules/Blocklist.jsm",
15 InstallRDF: "resource://legacy/RDFManifestConverter.jsm",
17 const Services = globalThis.Services || ChromeUtils.import("resource://gre/modules/Services.jsm").Services;
19 (ChromeUtils.defineLazyGetter||XPCOMUtils.defineLazyGetter)(this, "BOOTSTRAP_REASONS", () => {
20 const {XPIProvider} = ChromeUtils.import("resource://gre/modules/addons/XPIProvider.jsm");
21 return XPIProvider.BOOTSTRAP_REASONS;
24 var logger = console.createInstance({ prefix: "addons.bootstrap" });
27 * Valid IDs fit this pattern.
29 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;
31 // Properties that exist in the install manifest
32 const PROP_METADATA = ["id", "version", "type", "internalName", "updateURL",
33 "optionsURL", "optionsType", "aboutURL", "iconURL"];
34 const PROP_LOCALE_SINGLE = ["name", "description", "creator", "homepageURL"];
35 const PROP_LOCALE_MULTI = ["developers", "translators", "contributors"];
37 // Map new string type identifiers to old style nsIUpdateItem types.
39 // 32 = multipackage xpi file
49 const COMPATIBLE_BY_DEFAULT_TYPES = {
54 const hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty);
56 function isXPI(filename) {
57 let ext = filename.slice(-4).toLowerCase();
58 return ext === ".xpi" || ext === ".zip";
62 * Gets an nsIURI for a file within another file, either a directory or an XPI
63 * file. If aFile is a directory then this will return a file: URI, if it is an
64 * XPI file then it will return a jar: URI.
66 * @param {nsIFile} aFile
67 * The file containing the resources, must be either a directory or an
69 * @param {string} aPath
70 * The path to find the resource at, "/" separated. If aPath is empty
71 * then the uri to the root of the contained files will be returned
73 * An nsIURI pointing at the resource
75 function getURIForResourceInFile(aFile, aPath) {
76 if (!isXPI(aFile.leafName)) {
77 let resource = aFile.clone();
79 aPath.split("/").forEach(part => resource.append(part));
81 return Services.io.newFileURI(resource);
84 return buildJarURI(aFile, aPath);
88 * Creates a jar: URI for a file inside a ZIP file.
90 * @param {nsIFile} aJarfile
91 * The ZIP file as an nsIFile
92 * @param {string} aPath
93 * The path inside the ZIP file
95 * An nsIURI for the file
97 function buildJarURI(aJarfile, aPath) {
98 let uri = Services.io.newFileURI(aJarfile);
99 uri = "jar:" + uri.spec + "!/" + aPath;
100 return Services.io.newURI(uri);
103 var BootstrapLoader = {
105 manifestFile: "install.rdf",
106 async loadManifest(pkg) {
108 * Reads locale properties from either the main install manifest root or
109 * an em:localized section in the install manifest.
111 * @param {Object} aSource
112 * The resource to read the properties from.
113 * @param {boolean} isDefault
114 * True if the locale is to be read from the main install manifest
116 * @param {string[]} aSeenLocales
117 * An array of locale names already seen for this install manifest.
118 * Any locale names seen as a part of this function will be added to
121 * an object containing the locale properties
123 function readLocale(aSource, isDefault, aSeenLocales) {
127 for (let localeName of aSource.locales || []) {
129 logger.warn("Ignoring empty locale in localized properties");
132 if (aSeenLocales.includes(localeName)) {
133 logger.warn("Ignoring duplicate locale in localized properties");
136 aSeenLocales.push(localeName);
137 locale.locales.push(localeName);
140 if (locale.locales.length == 0) {
141 logger.warn("Ignoring localized properties with no listed locales");
146 for (let prop of [...PROP_LOCALE_SINGLE, ...PROP_LOCALE_MULTI]) {
147 if (hasOwnProperty(aSource, prop)) {
148 locale[prop] = aSource[prop];
155 let manifestData = await pkg.readString("install.rdf");
156 let manifest = InstallRDF.loadFromString(manifestData).decode();
158 let addon = new AddonInternal();
159 for (let prop of PROP_METADATA) {
160 if (hasOwnProperty(manifest, prop)) {
161 addon[prop] = manifest[prop];
166 addon.type = "extension";
168 let type = addon.type;
170 for (let name in TYPES) {
171 if (TYPES[name] == type) {
178 if (!(addon.type in TYPES))
179 throw new Error("Install manifest specifies unknown type: " + addon.type);
182 throw new Error("No ID in install manifest");
183 if (!gIDTest.test(addon.id))
184 throw new Error("Illegal add-on ID " + addon.id);
186 throw new Error("No version in install manifest");
188 addon.strictCompatibility = (!(addon.type in COMPATIBLE_BY_DEFAULT_TYPES) ||
189 manifest.strictCompatibility == "true");
191 // Only read these properties for extensions.
192 if (addon.type == "extension") {
193 if (manifest.bootstrap != "true") {
194 throw new Error("Non-restartless extensions no longer supported");
197 if (addon.optionsType &&
198 addon.optionsType != AddonManager.OPTIONS_TYPE_INLINE_BROWSER &&
199 addon.optionsType != AddonManager.OPTIONS_TYPE_TAB) {
200 throw new Error("Install manifest specifies unknown optionsType: " + addon.optionsType);
203 // Convert legacy dictionaries into a format the WebExtension
204 // dictionary loader can process.
205 if (addon.type === "dictionary") {
207 let dictionaries = {};
208 await pkg.iterFiles(({path}) => {
209 let match = /^dictionaries\/([^\/]+)\.dic$/.exec(path);
211 let lang = match[1].replace(/_/g, "-");
212 dictionaries[lang] = match[0];
215 addon.startupData = {dictionaries};
218 // Only extensions are allowed to provide an optionsURL, optionsType,
219 // optionsBrowserStyle, or aboutURL. For all other types they are silently ignored
220 addon.aboutURL = null;
221 addon.optionsBrowserStyle = null;
222 addon.optionsType = null;
223 addon.optionsURL = null;
226 addon.defaultLocale = readLocale(manifest, true);
228 let seenLocales = [];
230 for (let localeData of manifest.localized || []) {
231 let locale = readLocale(localeData, false, seenLocales);
233 addon.locales.push(locale);
236 let dependencies = new Set(manifest.dependencies);
237 addon.dependencies = Object.freeze(Array.from(dependencies));
239 let seenApplications = [];
240 addon.targetApplications = [];
241 for (let targetApp of manifest.targetApplications || []) {
242 if (!targetApp.id || !targetApp.minVersion ||
243 !targetApp.maxVersion) {
244 logger.warn("Ignoring invalid targetApplication entry in install manifest");
247 if (seenApplications.includes(targetApp.id)) {
248 logger.warn("Ignoring duplicate targetApplication entry for " + targetApp.id +
249 " in install manifest");
252 seenApplications.push(targetApp.id);
253 addon.targetApplications.push(targetApp);
256 // Note that we don't need to check for duplicate targetPlatform entries since
257 // the RDF service coalesces them for us.
258 addon.targetPlatforms = [];
259 for (let targetPlatform of manifest.targetPlatforms || []) {
265 let pos = targetPlatform.indexOf("_");
267 platform.os = targetPlatform.substring(0, pos);
268 platform.abi = targetPlatform.substring(pos + 1);
270 platform.os = targetPlatform;
273 addon.targetPlatforms.push(platform);
276 addon.userDisabled = false;
277 addon.softDisabled = addon.blocklistState == Blocklist.STATE_SOFTBLOCKED;
278 addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT;
280 addon.userPermissions = null;
283 if (await pkg.hasResource("icon.png")) {
284 addon.icons[32] = "icon.png";
285 addon.icons[48] = "icon.png";
288 if (await pkg.hasResource("icon64.png")) {
289 addon.icons[64] = "icon64.png";
296 let file = addon.file || addon._sourceBundle;
297 let uri = getURIForResourceInFile(file, "bootstrap.js").spec;
298 let principal = Services.scriptSecurityManager.getSystemPrincipal();
300 let sandbox = new Cu.Sandbox(principal, {
303 wantGlobalProperties: ["ChromeUtils"],
304 metadata: { addonID: addon.id, URI: uri },
308 Object.assign(sandbox, BOOTSTRAP_REASONS);
310 (ChromeUtils.defineLazyGetter||XPCOMUtils.defineLazyGetter)(sandbox, "console", () =>
311 console.createInstance({ consoleID: `addon/${addon.id}` }));
313 Services.scriptloader.loadSubScript(uri, sandbox);
315 logger.warn(`Error loading bootstrap.js for ${addon.id}`, e);
318 function findMethod(name) {
320 return sandbox[name];
324 let method = Cu.evalInSandbox(name, sandbox);
329 logger.warn(`Add-on ${addon.id} is missing bootstrap method ${name}`);
333 let install = findMethod("install");
334 let uninstall = findMethod("uninstall");
335 let startup = findMethod("startup");
336 let shutdown = findMethod("shutdown");
339 install: (...args) => install(...args),
343 // Forget any cached files we might've had from this extension.
344 Services.obs.notifyObservers(null, "startupcache-invalidate");
348 if (addon.type == "extension") {
349 logger.debug(`Registering manifest for ${file.path}\n`);
350 Components.manager.addBootstrappedManifestLocation(file);
352 return startup(...args);
355 shutdown(data, reason) {
357 return shutdown(data, reason);
361 if (reason != BOOTSTRAP_REASONS.APP_SHUTDOWN) {
362 logger.debug(`Removing manifest for ${file.path}\n`);
363 Components.manager.removeBootstrappedManifestLocation(file);