-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathXPIInstall.jsm
2808 lines (2460 loc) · 93.2 KB
/
XPIInstall.jsm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
var EXPORTED_SYMBOLS = [
"DownloadAddonInstall",
"LocalAddonInstall",
"StagedAddonInstall",
"UpdateChecker",
"loadManifestFromFile",
"verifyBundleSignedState",
];
/* globals DownloadAddonInstall, LocalAddonInstall */
ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
ChromeUtils.import("resource://gre/modules/AddonManager.jsm");
ChromeUtils.defineModuleGetter(this, "AddonRepository",
"resource://gre/modules/addons/AddonRepository.jsm");
ChromeUtils.defineModuleGetter(this, "AddonSettings",
"resource://gre/modules/addons/AddonSettings.jsm");
ChromeUtils.defineModuleGetter(this, "AppConstants",
"resource://gre/modules/AppConstants.jsm");
XPCOMUtils.defineLazyGetter(this, "CertUtils",
() => ChromeUtils.import("resource://gre/modules/CertUtils.jsm", {}));
ChromeUtils.defineModuleGetter(this, "ExtensionData",
"resource://gre/modules/Extension.jsm");
ChromeUtils.defineModuleGetter(this, "FileUtils",
"resource://gre/modules/FileUtils.jsm");
XPCOMUtils.defineLazyGetter(this, "IconDetails", () => {
return ChromeUtils.import("resource://gre/modules/ExtensionParent.jsm", {}).ExtensionParent.IconDetails;
});
ChromeUtils.defineModuleGetter(this, "LightweightThemeManager",
"resource://gre/modules/LightweightThemeManager.jsm");
ChromeUtils.defineModuleGetter(this, "NetUtil",
"resource://gre/modules/NetUtil.jsm");
ChromeUtils.defineModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
ChromeUtils.defineModuleGetter(this, "ZipUtils",
"resource://gre/modules/ZipUtils.jsm");
const {nsIBlocklistService} = Ci;
const nsIFile = Components.Constructor("@mozilla.org/file/local;1", "nsIFile",
"initWithPath");
XPCOMUtils.defineLazyServiceGetter(this, "gCertDB",
"@mozilla.org/security/x509certdb;1",
"nsIX509CertDB");
XPCOMUtils.defineLazyServiceGetter(this, "gRDF", "@mozilla.org/rdf/rdf-service;1",
Ci.nsIRDFService);
ChromeUtils.defineModuleGetter(this, "XPIInternal",
"resource://gre/modules/addons/XPIProvider.jsm");
ChromeUtils.defineModuleGetter(this, "XPIProvider",
"resource://gre/modules/addons/XPIProvider.jsm");
/* globals AddonInternal, BOOTSTRAP_REASONS, KEY_APP_SYSTEM_ADDONS, KEY_APP_SYSTEM_DEFAULTS, KEY_APP_TEMPORARY, TEMPORARY_ADDON_SUFFIX, SIGNED_TYPES, TOOLKIT_ID, XPIDatabase, XPIStates, getExternalType, isTheme, isUsableAddon, isWebExtension, mustSign, recordAddonTelemetry */
const XPI_INTERNAL_SYMBOLS = [
"AddonInternal",
"BOOTSTRAP_REASONS",
"KEY_APP_SYSTEM_ADDONS",
"KEY_APP_SYSTEM_DEFAULTS",
"KEY_APP_TEMPORARY",
"SIGNED_TYPES",
"TEMPORARY_ADDON_SUFFIX",
"TOOLKIT_ID",
"XPIDatabase",
"XPIStates",
"getExternalType",
"isTheme",
"isUsableAddon",
"isWebExtension",
"mustSign",
"recordAddonTelemetry",
];
for (let name of XPI_INTERNAL_SYMBOLS) {
XPCOMUtils.defineLazyGetter(this, name, () => XPIInternal[name]);
}
/**
* Returns a nsIFile instance for the given path, relative to the given
* base file, if provided.
*
* @param {string} path
* The (possibly relative) path of the file.
* @param {nsIFile} [base]
* An optional file to use as a base path if `path` is relative.
* @returns {nsIFile}
*/
function getFile(path, base = null) {
// First try for an absolute path, as we get in the case of proxy
// files. Ideally we would try a relative path first, but on Windows,
// paths which begin with a drive letter are valid as relative paths,
// and treated as such.
try {
return new nsIFile(path);
} catch (e) {
// Ignore invalid relative paths. The only other error we should see
// here is EOM, and either way, any errors that we care about should
// be re-thrown below.
}
// If the path isn't absolute, we must have a base path.
let file = base.clone();
file.appendRelativePath(path);
return file;
}
const PREF_EM_UPDATE_BACKGROUND_URL = "extensions.update.background.url";
const PREF_EM_UPDATE_URL = "extensions.update.url";
const PREF_XPI_SIGNATURES_DEV_ROOT = "xpinstall.signatures.dev-root";
const PREF_INSTALL_REQUIREBUILTINCERTS = "extensions.install.requireBuiltInCerts";
const FILE_RDF_MANIFEST = "install.rdf";
const FILE_WEB_MANIFEST = "manifest.json";
const KEY_TEMPDIR = "TmpD";
const RDFURI_INSTALL_MANIFEST_ROOT = "urn:mozilla:install-manifest";
const PREFIX_NS_EM = "http://www.mozilla.org/2004/em-rdf#";
// Properties that exist in the install manifest
const PROP_METADATA = ["id", "version", "type", "internalName", "updateURL",
"updateKey", "optionsURL", "optionsType", "aboutURL",
"iconURL", "icon64URL"];
const PROP_LOCALE_SINGLE = ["name", "description", "creator", "homepageURL"];
const PROP_LOCALE_MULTI = ["developers", "translators", "contributors"];
const PROP_TARGETAPP = ["id", "minVersion", "maxVersion"];
// Map new string type identifiers to old style nsIUpdateItem types.
// Retired values:
// 32 = multipackage xpi file
// 8 = locale
const TYPES = {
extension: 2,
theme: 4,
dictionary: 64,
experiment: 128,
apiextension: 256,
};
const COMPATIBLE_BY_DEFAULT_TYPES = {
extension: true,
dictionary: true,
};
const RESTARTLESS_TYPES = new Set([
"apiextension",
"dictionary",
"experiment",
"webextension",
"webextension-dictionary",
"webextension-theme",
]);
// This is a random number array that can be used as "salt" when generating
// an automatic ID based on the directory path of an add-on. It will prevent
// someone from creating an ID for a permanent add-on that could be replaced
// by a temporary add-on (because that would be confusing, I guess).
const TEMP_INSTALL_ID_GEN_SESSION =
new Uint8Array(Float64Array.of(Math.random()).buffer);
const MSG_JAR_FLUSH = "AddonJarFlush";
const MSG_MESSAGE_MANAGER_CACHES_FLUSH = "AddonMessageManagerCachesFlush";
/**
* Valid IDs fit this pattern.
*/
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;
ChromeUtils.import("resource://gre/modules/Log.jsm");
const LOGGER_ID = "addons.xpi";
// Create a new logger for use by all objects in this Addons XPI Provider module
// (Requires AddonManager.jsm)
var logger = Log.repository.getLogger(LOGGER_ID);
/**
* Sets permissions on a file
*
* @param aFile
* The file or directory to operate on.
* @param aPermissions
* The permisions to set
*/
function setFilePermissions(aFile, aPermissions) {
try {
aFile.permissions = aPermissions;
} catch (e) {
logger.warn("Failed to set permissions " + aPermissions.toString(8) + " on " +
aFile.path, e);
}
}
/**
* Write a given string to a file
*
* @param file
* The nsIFile instance to write into
* @param string
* The string to write
*/
function writeStringToFile(file, string) {
let stream = Cc["@mozilla.org/network/file-output-stream;1"].
createInstance(Ci.nsIFileOutputStream);
let converter = Cc["@mozilla.org/intl/converter-output-stream;1"].
createInstance(Ci.nsIConverterOutputStream);
try {
stream.init(file, FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE |
FileUtils.MODE_TRUNCATE, FileUtils.PERMS_FILE,
0);
converter.init(stream, "UTF-8");
converter.writeString(string);
} finally {
converter.close();
stream.close();
}
}
function EM_R(aProperty) {
return gRDF.GetResource(PREFIX_NS_EM + aProperty);
}
function getManifestFileForDir(aDir) {
let file = getFile(FILE_RDF_MANIFEST, aDir);
if (file.exists() && file.isFile())
return file;
file.leafName = FILE_WEB_MANIFEST;
if (file.exists() && file.isFile())
return file;
return null;
}
function getManifestEntryForZipReader(aZipReader) {
if (aZipReader.hasEntry(FILE_RDF_MANIFEST))
return FILE_RDF_MANIFEST;
if (aZipReader.hasEntry(FILE_WEB_MANIFEST))
return FILE_WEB_MANIFEST;
return null;
}
/**
* Converts an RDF literal, resource or integer into a string.
*
* @param aLiteral
* The RDF object to convert
* @return a string if the object could be converted or null
*/
function getRDFValue(aLiteral) {
if (aLiteral instanceof Ci.nsIRDFLiteral)
return aLiteral.Value;
if (aLiteral instanceof Ci.nsIRDFResource)
return aLiteral.Value;
if (aLiteral instanceof Ci.nsIRDFInt)
return aLiteral.Value;
return null;
}
/**
* Gets an RDF property as a string
*
* @param aDs
* The RDF datasource to read the property from
* @param aResource
* The RDF resource to read the property from
* @param aProperty
* The property to read
* @return a string if the property existed or null
*/
function getRDFProperty(aDs, aResource, aProperty) {
return getRDFValue(aDs.GetTarget(aResource, EM_R(aProperty), true));
}
/**
* Reads an AddonInternal object from a manifest stream.
*
* @param aUri
* A |file:| or |jar:| URL for the manifest
* @return an AddonInternal object
* @throws if the install manifest in the stream is corrupt or could not
* be read
*/
async function loadManifestFromWebManifest(aUri) {
// We're passed the URI for the manifest file. Get the URI for its
// parent directory.
let uri = Services.io.newURI("./", null, aUri);
let extension = new ExtensionData(uri);
let manifest = await extension.loadManifest();
// Read the list of available locales, and pre-load messages for
// all locales.
let locales = (extension.errors.length == 0) ?
await extension.initAllLocales() : null;
if (extension.errors.length > 0) {
throw new Error("Extension is invalid");
}
let bss = (manifest.browser_specific_settings && manifest.browser_specific_settings.gecko)
|| (manifest.applications && manifest.applications.gecko) || {};
if (manifest.browser_specific_settings && manifest.applications) {
logger.warn("Ignoring applications property in manifest");
}
// A * is illegal in strict_min_version
if (bss.strict_min_version && bss.strict_min_version.split(".").some(part => part == "*")) {
throw new Error("The use of '*' in strict_min_version is invalid");
}
let addon = new AddonInternal();
addon.id = bss.id;
addon.version = manifest.version;
addon.type = extension.type === "extension" ?
"webextension" : `webextension-${extension.type}`;
addon.strictCompatibility = true;
addon.bootstrap = true;
addon.multiprocessCompatible = true;
addon.internalName = null;
addon.updateURL = bss.update_url;
addon.updateKey = null;
addon.optionsBrowserStyle = true;
addon.optionsURL = null;
addon.optionsType = null;
addon.aboutURL = null;
addon.dependencies = Object.freeze(Array.from(extension.dependencies));
addon.startupData = extension.startupData;
if (manifest.options_ui) {
// Store just the relative path here, the AddonWrapper getURL
// wrapper maps this to a full URL.
addon.optionsURL = manifest.options_ui.page;
if (manifest.options_ui.open_in_tab)
addon.optionsType = AddonManager.OPTIONS_TYPE_TAB;
else
addon.optionsType = AddonManager.OPTIONS_TYPE_INLINE_BROWSER;
if (manifest.options_ui.browser_style === null)
logger.warn("Please specify whether you want browser_style " +
"or not in your options_ui options.");
else
addon.optionsBrowserStyle = manifest.options_ui.browser_style;
}
// WebExtensions don't use iconURLs
addon.iconURL = null;
addon.icon64URL = null;
addon.icons = manifest.icons || {};
addon.userPermissions = extension.manifestPermissions;
addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT;
function getLocale(aLocale) {
// Use the raw manifest, here, since we need values with their
// localization placeholders still in place.
let rawManifest = extension.rawManifest;
// As a convenience, allow author to be set if its a string bug 1313567.
let creator = typeof(rawManifest.author) === "string" ? rawManifest.author : null;
let homepageURL = rawManifest.homepage_url;
// Allow developer to override creator and homepage_url.
if (rawManifest.developer) {
if (rawManifest.developer.name) {
creator = rawManifest.developer.name;
}
if (rawManifest.developer.url) {
homepageURL = rawManifest.developer.url;
}
}
let result = {
name: extension.localize(rawManifest.name, aLocale),
description: extension.localize(rawManifest.description, aLocale),
creator: extension.localize(creator, aLocale),
homepageURL: extension.localize(homepageURL, aLocale),
developers: null,
translators: null,
contributors: null,
locales: [aLocale],
};
return result;
}
addon.defaultLocale = getLocale(extension.defaultLocale);
addon.locales = Array.from(locales.keys(), getLocale);
delete addon.defaultLocale.locales;
addon.targetApplications = [{
id: TOOLKIT_ID,
minVersion: bss.strict_min_version,
maxVersion: bss.strict_max_version,
}];
addon.targetPlatforms = [];
// Themes are disabled by default, except when they're installed from a web page.
addon.userDisabled = (extension.type === "theme");
addon.softDisabled = addon.blocklistState == nsIBlocklistService.STATE_SOFTBLOCKED;
return addon;
}
/**
* Reads an AddonInternal object from an RDF stream.
*
* @param aUri
* The URI that the manifest is being read from
* @param aStream
* An open stream to read the RDF from
* @return an AddonInternal object
* @throws if the install manifest in the RDF stream is corrupt or could not
* be read
*/
async function loadManifestFromRDF(aUri, aStream) {
function getPropertyArray(aDs, aSource, aProperty) {
let values = [];
let targets = aDs.GetTargets(aSource, EM_R(aProperty), true);
while (targets.hasMoreElements())
values.push(getRDFValue(targets.getNext()));
return values;
}
/**
* Reads locale properties from either the main install manifest root or
* an em:localized section in the install manifest.
*
* @param aDs
* The nsIRDFDatasource to read from
* @param aSource
* The nsIRDFResource to read the properties from
* @param isDefault
* True if the locale is to be read from the main install manifest
* root
* @param aSeenLocales
* An array of locale names already seen for this install manifest.
* Any locale names seen as a part of this function will be added to
* this array
* @return an object containing the locale properties
*/
function readLocale(aDs, aSource, isDefault, aSeenLocales) {
let locale = { };
if (!isDefault) {
locale.locales = [];
let targets = ds.GetTargets(aSource, EM_R("locale"), true);
while (targets.hasMoreElements()) {
let localeName = getRDFValue(targets.getNext());
if (!localeName) {
logger.warn("Ignoring empty locale in localized properties");
continue;
}
if (aSeenLocales.includes(localeName)) {
logger.warn("Ignoring duplicate locale in localized properties");
continue;
}
aSeenLocales.push(localeName);
locale.locales.push(localeName);
}
if (locale.locales.length == 0) {
logger.warn("Ignoring localized properties with no listed locales");
return null;
}
}
for (let prop of PROP_LOCALE_SINGLE) {
locale[prop] = getRDFProperty(aDs, aSource, prop);
}
for (let prop of PROP_LOCALE_MULTI) {
// Don't store empty arrays
let props = getPropertyArray(aDs, aSource,
prop.substring(0, prop.length - 1));
if (props.length > 0)
locale[prop] = props;
}
return locale;
}
let rdfParser = Cc["@mozilla.org/rdf/xml-parser;1"].
createInstance(Ci.nsIRDFXMLParser);
let ds = Cc["@mozilla.org/rdf/datasource;1?name=in-memory-datasource"].
createInstance(Ci.nsIRDFDataSource);
let listener = rdfParser.parseAsync(ds, aUri);
let channel = Cc["@mozilla.org/network/input-stream-channel;1"].
createInstance(Ci.nsIInputStreamChannel);
channel.setURI(aUri);
channel.contentStream = aStream;
channel.QueryInterface(Ci.nsIChannel);
channel.contentType = "text/xml";
listener.onStartRequest(channel, null);
try {
let pos = 0;
let count = aStream.available();
while (count > 0) {
listener.onDataAvailable(channel, null, aStream, pos, count);
pos += count;
count = aStream.available();
}
listener.onStopRequest(channel, null, Cr.NS_OK);
} catch (e) {
listener.onStopRequest(channel, null, e.result);
throw e;
}
let root = gRDF.GetResource(RDFURI_INSTALL_MANIFEST_ROOT);
let addon = new AddonInternal();
for (let prop of PROP_METADATA) {
addon[prop] = getRDFProperty(ds, root, prop);
}
if (!addon.type) {
addon.type = addon.internalName ? "theme" : "extension";
} else {
let type = addon.type;
addon.type = null;
for (let name in TYPES) {
if (TYPES[name] == type) {
addon.type = name;
break;
}
}
}
if (!(addon.type in TYPES))
throw new Error("Install manifest specifies unknown type: " + addon.type);
if (!addon.id)
throw new Error("No ID in install manifest");
if (!gIDTest.test(addon.id))
throw new Error("Illegal add-on ID " + addon.id);
if (!addon.version)
throw new Error("No version in install manifest");
addon.strictCompatibility = !(addon.type in COMPATIBLE_BY_DEFAULT_TYPES) ||
getRDFProperty(ds, root, "strictCompatibility") == "true";
// Only read these properties for extensions.
if (addon.type == "extension") {
addon.bootstrap = getRDFProperty(ds, root, "bootstrap") == "true";
let mpcValue = getRDFProperty(ds, root, "multiprocessCompatible");
addon.multiprocessCompatible = mpcValue == "true";
addon.mpcOptedOut = mpcValue == "false";
addon.hasEmbeddedWebExtension = getRDFProperty(ds, root, "hasEmbeddedWebExtension") == "true";
if (addon.optionsType &&
addon.optionsType != AddonManager.OPTIONS_INLINE_BROWSER &&
addon.optionsType != AddonManager.OPTIONS_TYPE_TAB) {
throw new Error("Install manifest specifies unknown optionsType: " + addon.optionsType);
}
if (addon.hasEmbeddedWebExtension) {
let uri = Services.io.newURI("webextension/manifest.json", null, aUri);
let embeddedAddon = await loadManifestFromWebManifest(uri);
if (embeddedAddon.optionsURL) {
if (addon.optionsType || addon.optionsURL)
logger.warn(`Addon ${addon.id} specifies optionsType or optionsURL ` +
`in both install.rdf and manifest.json`);
addon.optionsURL = embeddedAddon.optionsURL;
addon.optionsType = embeddedAddon.optionsType;
}
}
} else {
// Some add-on types are always restartless.
if (RESTARTLESS_TYPES.has(addon.type)) {
addon.bootstrap = true;
}
// Only extensions are allowed to provide an optionsURL, optionsType,
// optionsBrowserStyle, or aboutURL. For all other types they are silently ignored
addon.aboutURL = null;
addon.optionsBrowserStyle = null;
addon.optionsType = null;
addon.optionsURL = null;
if (addon.type == "theme") {
if (!addon.internalName)
throw new Error("Themes must include an internalName property");
addon.skinnable = getRDFProperty(ds, root, "skinnable") == "true";
}
}
addon.defaultLocale = readLocale(ds, root, true);
let seenLocales = [];
addon.locales = [];
let targets = ds.GetTargets(root, EM_R("localized"), true);
while (targets.hasMoreElements()) {
let target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
let locale = readLocale(ds, target, false, seenLocales);
if (locale)
addon.locales.push(locale);
}
let dependencies = new Set();
targets = ds.GetTargets(root, EM_R("dependency"), true);
while (targets.hasMoreElements()) {
let target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
let id = getRDFProperty(ds, target, "id");
dependencies.add(id);
}
addon.dependencies = Object.freeze(Array.from(dependencies));
let seenApplications = [];
addon.targetApplications = [];
targets = ds.GetTargets(root, EM_R("targetApplication"), true);
while (targets.hasMoreElements()) {
let target = targets.getNext().QueryInterface(Ci.nsIRDFResource);
let targetAppInfo = {};
for (let prop of PROP_TARGETAPP) {
targetAppInfo[prop] = getRDFProperty(ds, target, prop);
}
if (!targetAppInfo.id || !targetAppInfo.minVersion ||
!targetAppInfo.maxVersion) {
logger.warn("Ignoring invalid targetApplication entry in install manifest");
continue;
}
if (seenApplications.includes(targetAppInfo.id)) {
logger.warn("Ignoring duplicate targetApplication entry for " + targetAppInfo.id +
" in install manifest");
continue;
}
seenApplications.push(targetAppInfo.id);
addon.targetApplications.push(targetAppInfo);
}
// Note that we don't need to check for duplicate targetPlatform entries since
// the RDF service coalesces them for us.
let targetPlatforms = getPropertyArray(ds, root, "targetPlatform");
addon.targetPlatforms = [];
for (let targetPlatform of targetPlatforms) {
let platform = {
os: null,
abi: null
};
let pos = targetPlatform.indexOf("_");
if (pos != -1) {
platform.os = targetPlatform.substring(0, pos);
platform.abi = targetPlatform.substring(pos + 1);
} else {
platform.os = targetPlatform;
}
addon.targetPlatforms.push(platform);
}
// A theme's userDisabled value is true if the theme is not the selected skin
// or if there is an active lightweight theme. We ignore whether softblocking
// is in effect since it would change the active theme.
if (isTheme(addon.type)) {
addon.userDisabled = !!LightweightThemeManager.currentTheme ||
addon.internalName != XPIProvider.selectedSkin;
} else if (addon.type == "experiment") {
// Experiments are disabled by default. It is up to the Experiments Manager
// to enable them (it drives installation).
addon.userDisabled = true;
} else {
addon.userDisabled = false;
}
addon.softDisabled = addon.blocklistState == nsIBlocklistService.STATE_SOFTBLOCKED;
addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT;
// Experiments are managed and updated through an external "experiments
// manager." So disable some built-in mechanisms.
if (addon.type == "experiment") {
addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DISABLE;
addon.updateURL = null;
addon.updateKey = null;
}
// icons will be filled by the calling function
addon.icons = {};
addon.userPermissions = null;
return addon;
}
function defineSyncGUID(aAddon) {
// Define .syncGUID as a lazy property which is also settable
Object.defineProperty(aAddon, "syncGUID", {
get: () => {
// Generate random GUID used for Sync.
let guid = Cc["@mozilla.org/uuid-generator;1"]
.getService(Ci.nsIUUIDGenerator)
.generateUUID().toString();
delete aAddon.syncGUID;
aAddon.syncGUID = guid;
return guid;
},
set: (val) => {
delete aAddon.syncGUID;
aAddon.syncGUID = val;
},
configurable: true,
enumerable: true,
});
}
// Generate a unique ID based on the path to this temporary add-on location.
function generateTemporaryInstallID(aFile) {
const hasher = Cc["@mozilla.org/security/hash;1"]
.createInstance(Ci.nsICryptoHash);
hasher.init(hasher.SHA1);
const data = new TextEncoder().encode(aFile.path);
// Make it so this ID cannot be guessed.
const sess = TEMP_INSTALL_ID_GEN_SESSION;
hasher.update(sess, sess.length);
hasher.update(data, data.length);
let id = `${getHashStringForCrypto(hasher)}${TEMPORARY_ADDON_SUFFIX}`;
logger.info(`Generated temp id ${id} (${sess.join("")}) for ${aFile.path}`);
return id;
}
/**
* Loads an AddonInternal object from an add-on extracted in a directory.
*
* @param aDir
* The nsIFile directory holding the add-on
* @return an AddonInternal object
* @throws if the directory does not contain a valid install manifest
*/
var loadManifestFromDir = async function(aDir, aInstallLocation) {
function getFileSize(aFile) {
if (aFile.isSymlink())
return 0;
if (!aFile.isDirectory())
return aFile.fileSize;
let size = 0;
let entries = aFile.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
let entry;
while ((entry = entries.nextFile))
size += getFileSize(entry);
entries.close();
return size;
}
async function loadFromRDF(aUri) {
let fis = Cc["@mozilla.org/network/file-input-stream;1"].
createInstance(Ci.nsIFileInputStream);
fis.init(aUri.file, -1, -1, false);
let bis = Cc["@mozilla.org/network/buffered-input-stream;1"].
createInstance(Ci.nsIBufferedInputStream);
bis.init(fis, 4096);
try {
var addon = await loadManifestFromRDF(aUri, bis);
} finally {
bis.close();
fis.close();
}
let iconFile = getFile("icon.png", aDir);
if (iconFile.exists()) {
addon.icons[32] = "icon.png";
addon.icons[48] = "icon.png";
}
let icon64File = getFile("icon64.png", aDir);
if (icon64File.exists()) {
addon.icons[64] = "icon64.png";
}
return addon;
}
let file = getManifestFileForDir(aDir);
if (!file) {
throw new Error("Directory " + aDir.path + " does not contain a valid " +
"install manifest");
}
let uri = Services.io.newFileURI(file).QueryInterface(Ci.nsIFileURL);
let addon;
if (file.leafName == FILE_WEB_MANIFEST) {
addon = await loadManifestFromWebManifest(uri);
if (!addon.id) {
if (aInstallLocation.name == KEY_APP_TEMPORARY) {
addon.id = generateTemporaryInstallID(aDir);
} else {
addon.id = aDir.leafName;
}
}
} else {
addon = await loadFromRDF(uri);
}
addon._sourceBundle = aDir.clone();
addon._installLocation = aInstallLocation;
addon.size = getFileSize(aDir);
addon.signedState = await verifyDirSignedState(aDir, addon)
.then(({signedState}) => signedState);
addon.updateBlocklistState();
addon.appDisabled = !isUsableAddon(addon);
defineSyncGUID(addon);
return addon;
};
/**
* Loads an AddonInternal object from an nsIZipReader for an add-on.
*
* @param aZipReader
* An open nsIZipReader for the add-on's files
* @return an AddonInternal object
* @throws if the XPI file does not contain a valid install manifest
*/
var loadManifestFromZipReader = async function(aZipReader, aInstallLocation) {
async function loadFromRDF(aUri) {
let zis = aZipReader.getInputStream(entry);
let bis = Cc["@mozilla.org/network/buffered-input-stream;1"].
createInstance(Ci.nsIBufferedInputStream);
bis.init(zis, 4096);
try {
var addon = await loadManifestFromRDF(aUri, bis);
} finally {
bis.close();
zis.close();
}
if (aZipReader.hasEntry("icon.png")) {
addon.icons[32] = "icon.png";
addon.icons[48] = "icon.png";
}
if (aZipReader.hasEntry("icon64.png")) {
addon.icons[64] = "icon64.png";
}
return addon;
}
let entry = getManifestEntryForZipReader(aZipReader);
if (!entry) {
throw new Error("File " + aZipReader.file.path + " does not contain a valid " +
"install manifest");
}
let uri = buildJarURI(aZipReader.file, entry);
let isWebExtension = (entry == FILE_WEB_MANIFEST);
let addon = isWebExtension ?
await loadManifestFromWebManifest(uri) :
await loadFromRDF(uri);
addon._sourceBundle = aZipReader.file;
addon._installLocation = aInstallLocation;
addon.size = 0;
let entries = aZipReader.findEntries(null);
while (entries.hasMore())
addon.size += aZipReader.getEntry(entries.getNext()).realSize;
let {signedState, cert} = await verifyZipSignedState(aZipReader.file, addon);
addon.signedState = signedState;
if (isWebExtension && !addon.id) {
if (cert) {
addon.id = cert.commonName;
if (!gIDTest.test(addon.id)) {
throw new Error(`Webextension is signed with an invalid id (${addon.id})`);
}
}
if (!addon.id && aInstallLocation.name == KEY_APP_TEMPORARY) {
addon.id = generateTemporaryInstallID(aZipReader.file);
}
}
addon.updateBlocklistState();
addon.appDisabled = !isUsableAddon(addon);
defineSyncGUID(addon);
return addon;
};
/**
* Loads an AddonInternal object from an add-on in an XPI file.
*
* @param aXPIFile
* An nsIFile pointing to the add-on's XPI file
* @return an AddonInternal object
* @throws if the XPI file does not contain a valid install manifest
*/
var loadManifestFromZipFile = async function(aXPIFile, aInstallLocation) {
let zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].
createInstance(Ci.nsIZipReader);
try {
zipReader.open(aXPIFile);
// Can't return this promise because that will make us close the zip reader
// before it has finished loading the manifest. Wait for the result and then
// return.
let manifest = await loadManifestFromZipReader(zipReader, aInstallLocation);
return manifest;
} finally {
zipReader.close();
}
};
var loadManifestFromFile = function(aFile, aInstallLocation) {
if (aFile.isFile())
return loadManifestFromZipFile(aFile, aInstallLocation);
return loadManifestFromDir(aFile, aInstallLocation);
};
/**
* Creates a jar: URI for a file inside a ZIP file.
*
* @param aJarfile
* The ZIP file as an nsIFile
* @param aPath
* The path inside the ZIP file
* @return an nsIURI for the file
*/
function buildJarURI(aJarfile, aPath) {
let uri = Services.io.newFileURI(aJarfile);
uri = "jar:" + uri.spec + "!/" + aPath;
return Services.io.newURI(uri);
}
/**
* Sends local and remote notifications to flush a JAR file cache entry
*
* @param aJarFile
* The ZIP/XPI/JAR file as a nsIFile
*/
function flushJarCache(aJarFile) {
Services.obs.notifyObservers(aJarFile, "flush-cache-entry");
Services.mm.broadcastAsyncMessage(MSG_JAR_FLUSH, aJarFile.path);
}
function flushChromeCaches() {
// Init this, so it will get the notification.
Services.obs.notifyObservers(null, "startupcache-invalidate");
// Flush message manager cached scripts
Services.obs.notifyObservers(null, "message-manager-flush-caches");
// Also dispatch this event to child processes
Services.mm.broadcastAsyncMessage(MSG_MESSAGE_MANAGER_CACHES_FLUSH, null);
}
/**
* Creates and returns a new unique temporary file. The caller should delete
* the file when it is no longer needed.
*
* @return an nsIFile that points to a randomly named, initially empty file in
* the OS temporary files directory
*/
function getTemporaryFile() {
let file = FileUtils.getDir(KEY_TEMPDIR, []);
let random = Math.random().toString(36).replace(/0./, "").substr(-3);
file.append("tmp-" + random + ".xpi");
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
return file;
}
/**
* Returns the signedState for a given return code and certificate by verifying
* it against the expected ID.
*/
function getSignedStatus(aRv, aCert, aAddonID) {
let expectedCommonName = aAddonID;
if (aAddonID && aAddonID.length > 64) {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
let data = converter.convertToByteArray(aAddonID, {});
let crypto = Cc["@mozilla.org/security/hash;1"].
createInstance(Ci.nsICryptoHash);
crypto.init(Ci.nsICryptoHash.SHA256);
crypto.update(data, data.length);
expectedCommonName = getHashStringForCrypto(crypto);
}
switch (aRv) {