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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
|
/* 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/. */
// Cannot use Services.appinfo here, or else xpcshell-tests will blow up, as
// most tests later register different nsIAppInfo implementations, which
// wouldn't be reflected in Services.appinfo anymore, as the lazy getter
// underlying it would have been initialized if we used it here.
if ("@mozilla.org/xre/app-info;1" in Cc) {
// eslint-disable-next-line mozilla/use-services
let runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
if (runtime.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
// Refuse to run in child processes.
throw new Error("You cannot use the AddonManager in child processes!");
}
}
import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
const MOZ_COMPATIBILITY_NIGHTLY = ![
"aurora",
"beta",
"release",
"esr",
].includes(AppConstants.MOZ_UPDATE_CHANNEL);
const INTL_LOCALES_CHANGED = "intl:app-locales-changed";
const PREF_AMO_ABUSEREPORT = "extensions.abuseReport.amWebAPI.enabled";
const PREF_BLOCKLIST_PINGCOUNTVERSION = "extensions.blocklist.pingCountVersion";
const PREF_EM_UPDATE_ENABLED = "extensions.update.enabled";
const PREF_EM_LAST_APP_VERSION = "extensions.lastAppVersion";
const PREF_EM_LAST_PLATFORM_VERSION = "extensions.lastPlatformVersion";
const PREF_EM_AUTOUPDATE_DEFAULT = "extensions.update.autoUpdateDefault";
const PREF_EM_STRICT_COMPATIBILITY = "extensions.strictCompatibility";
const PREF_EM_CHECK_UPDATE_SECURITY = "extensions.checkUpdateSecurity";
const PREF_SYS_ADDON_UPDATE_ENABLED = "extensions.systemAddon.update.enabled";
const PREF_REMOTESETTINGS_DISABLED = "extensions.remoteSettings.disabled";
const PREF_USE_REMOTE = "extensions.webextensions.remote";
const PREF_MIN_WEBEXT_PLATFORM_VERSION =
"extensions.webExtensionsMinPlatformVersion";
const PREF_WEBAPI_TESTING = "extensions.webapi.testing";
const PREF_EM_POSTDOWNLOAD_THIRD_PARTY =
"extensions.postDownloadThirdPartyPrompt";
const UPDATE_REQUEST_VERSION = 2;
const BRANCH_REGEXP = /^([^\.]+\.[0-9]+[a-z]*).*/gi;
const PREF_EM_CHECK_COMPATIBILITY_BASE = "extensions.checkCompatibility";
var PREF_EM_CHECK_COMPATIBILITY = MOZ_COMPATIBILITY_NIGHTLY
? PREF_EM_CHECK_COMPATIBILITY_BASE + ".nightly"
: undefined;
const WEBAPI_INSTALL_HOSTS =
AppConstants.MOZ_APP_NAME !== "thunderbird"
? ["addons.mozilla.org"]
: ["addons.thunderbird.net"];
const WEBAPI_TEST_INSTALL_HOSTS =
AppConstants.MOZ_APP_NAME !== "thunderbird"
? ["addons.allizom.org", "addons-dev.allizom.org", "example.com"]
: ["addons-stage.thunderbird.net", "example.com"];
const AMO_ATTRIBUTION_ALLOWED_SOURCES = ["amo", "disco", "rtamo"];
const AMO_ATTRIBUTION_DATA_KEYS = [
"utm_campaign",
"utm_content",
"utm_medium",
"utm_source",
];
const AMO_ATTRIBUTION_DATA_MAX_LENGTH = 40;
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
// This global is overridden by xpcshell tests, and therefore cannot be
// a const.
import { AsyncShutdown as realAsyncShutdown } from "resource://gre/modules/AsyncShutdown.sys.mjs";
var AsyncShutdown = realAsyncShutdown;
const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
AbuseReporter: "resource://gre/modules/AbuseReporter.sys.mjs",
AddonRepository: "resource://gre/modules/addons/AddonRepository.sys.mjs",
Extension: "resource://gre/modules/Extension.sys.mjs",
RemoteSettings: "resource://services-settings/remote-settings.sys.mjs",
TelemetryTimestamps: "resource://gre/modules/TelemetryTimestamps.sys.mjs",
isGatedPermissionType:
"resource://gre/modules/addons/siteperms-addon-utils.sys.mjs",
isKnownPublicSuffix:
"resource://gre/modules/addons/siteperms-addon-utils.sys.mjs",
isPrincipalInSitePermissionsBlocklist:
"resource://gre/modules/addons/siteperms-addon-utils.sys.mjs",
});
XPCOMUtils.defineLazyPreferenceGetter(
lazy,
"WEBEXT_POSTDOWNLOAD_THIRD_PARTY",
PREF_EM_POSTDOWNLOAD_THIRD_PARTY,
false
);
// Initialize the WebExtension process script service as early as possible,
// since it needs to be able to track things like new frameLoader globals that
// are created before other framework code has been initialized.
Services.ppmm.loadProcessScript(
"resource://gre/modules/extensionProcessScriptLoader.js",
true
);
const INTEGER = /^[1-9]\d*$/;
const CATEGORY_PROVIDER_MODULE = "addon-provider-module";
import { Log } from "resource://gre/modules/Log.sys.mjs";
// Configure a logger at the parent 'addons' level to format
// messages for all the modules under addons.*
const PARENT_LOGGER_ID = "addons";
var parentLogger = Log.repository.getLogger(PARENT_LOGGER_ID);
parentLogger.level = Log.Level.Warn;
var formatter = new Log.BasicFormatter();
// Set parent logger (and its children) to append to
// the Javascript section of the Browser Console
parentLogger.addAppender(new Log.ConsoleAppender(formatter));
// Create a new logger (child of 'addons' logger)
// for use by the Addons Manager
const LOGGER_ID = "addons.manager";
var logger = Log.repository.getLogger(LOGGER_ID);
// Provide the ability to enable/disable logging
// messages at runtime.
// If the "extensions.logging.enabled" preference is
// missing or 'false', messages at the WARNING and higher
// severity should be logged to the JS console and standard error.
// If "extensions.logging.enabled" is set to 'true', messages
// at DEBUG and higher should go to JS console and standard error.
const PREF_LOGGING_ENABLED = "extensions.logging.enabled";
const NS_PREFBRANCH_PREFCHANGE_TOPIC_ID = "nsPref:changed";
const UNNAMED_PROVIDER = "<unnamed-provider>";
function providerName(aProvider) {
return aProvider.name || UNNAMED_PROVIDER;
}
// A reference to XPIProvider. This should only be used to access properties or
// methods that are independent of XPIProvider startup.
var gXPIProvider;
/**
* Preference listener which listens for a change in the
* "extensions.logging.enabled" preference and changes the logging level of the
* parent 'addons' level logger accordingly.
*/
var PrefObserver = {
init() {
Services.prefs.addObserver(PREF_LOGGING_ENABLED, this);
Services.obs.addObserver(this, "xpcom-shutdown");
this.observe(null, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID, PREF_LOGGING_ENABLED);
},
observe(aSubject, aTopic, aData) {
if (aTopic == "xpcom-shutdown") {
Services.prefs.removeObserver(PREF_LOGGING_ENABLED, this);
Services.obs.removeObserver(this, "xpcom-shutdown");
} else if (aTopic == NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) {
let debugLogEnabled = Services.prefs.getBoolPref(
PREF_LOGGING_ENABLED,
false
);
if (debugLogEnabled) {
parentLogger.level = Log.Level.Debug;
} else {
parentLogger.level = Log.Level.Warn;
}
}
},
};
PrefObserver.init();
/**
* Calls a callback method consuming any thrown exception. Any parameters after
* the callback parameter will be passed to the callback.
*
* @param aCallback
* The callback method to call
*/
function safeCall(aCallback, ...aArgs) {
try {
aCallback.apply(null, aArgs);
} catch (e) {
logger.warn("Exception calling callback", e);
}
}
/**
* Report an exception thrown by a provider API method.
*/
function reportProviderError(aProvider, aMethod, aError) {
let method = `provider ${providerName(aProvider)}.${aMethod}`;
AddonManagerPrivate.recordException("AMI", method, aError);
logger.error("Exception calling " + method, aError);
}
/**
* Calls a method on a provider if it exists and consumes any thrown exception.
* Any parameters after the aDefault parameter are passed to the provider's method.
*
* @param aProvider
* The provider to call
* @param aMethod
* The method name to call
* @param aDefault
* A default return value if the provider does not implement the named
* method or throws an error.
* @return the return value from the provider, or aDefault if the provider does not
* implement method or throws an error
*/
function callProvider(aProvider, aMethod, aDefault, ...aArgs) {
if (!(aMethod in aProvider)) {
return aDefault;
}
try {
return aProvider[aMethod].apply(aProvider, aArgs);
} catch (e) {
reportProviderError(aProvider, aMethod, e);
return aDefault;
}
}
/**
* Calls a method on a provider if it exists and consumes any thrown exception.
* Parameters after aMethod are passed to aProvider.aMethod().
* If the provider does not implement the method, or the method throws, calls
* the callback with 'undefined'.
*
* @param aProvider
* The provider to call
* @param aMethod
* The method name to call
*/
async function promiseCallProvider(aProvider, aMethod, ...aArgs) {
if (!(aMethod in aProvider)) {
return undefined;
}
try {
return aProvider[aMethod].apply(aProvider, aArgs);
} catch (e) {
reportProviderError(aProvider, aMethod, e);
return undefined;
}
}
/**
* Gets the currently selected locale for display.
* @return the selected locale or "en-US" if none is selected
*/
function getLocale() {
return Services.locale.requestedLocale || "en-US";
}
const WEB_EXPOSED_ADDON_PROPERTIES = [
"id",
"version",
"type",
"name",
"description",
"isActive",
];
function webAPIForAddon(addon) {
if (!addon) {
return null;
}
// These web-exposed Addon properties (see AddonManager.webidl)
// just come directly from an Addon object.
let result = {};
for (let prop of WEB_EXPOSED_ADDON_PROPERTIES) {
result[prop] = addon[prop];
}
// These properties are computed.
result.isEnabled = !addon.userDisabled;
result.canUninstall = Boolean(
addon.permissions & AddonManager.PERM_CAN_UNINSTALL
);
return result;
}
/**
* Listens for a browser changing origin and cancels the installs that were
* started by it.
*/
function BrowserListener(aBrowser, aInstallingPrincipal, aInstall) {
this.browser = aBrowser;
this.messageManager = this.browser.messageManager;
this.principal = aInstallingPrincipal;
this.install = aInstall;
aBrowser.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION);
Services.obs.addObserver(this, "message-manager-close", true);
aInstall.addListener(this);
this.registered = true;
}
BrowserListener.prototype = {
browser: null,
install: null,
registered: false,
unregister() {
if (!this.registered) {
return;
}
this.registered = false;
Services.obs.removeObserver(this, "message-manager-close");
// The browser may have already been detached
if (this.browser.removeProgressListener) {
this.browser.removeProgressListener(this);
}
this.install.removeListener(this);
this.install = null;
},
cancelInstall() {
try {
this.install.cancel();
} catch (e) {
// install may have already failed or been cancelled, ignore these
}
},
observe(subject, topic, data) {
if (subject != this.messageManager) {
return;
}
// The browser's message manager has closed and so the browser is
// going away, cancel the install
this.cancelInstall();
},
onLocationChange(webProgress, request, location) {
if (
this.browser.contentPrincipal &&
this.principal.subsumes(this.browser.contentPrincipal)
) {
return;
}
// The browser has navigated to a new origin so cancel the install
this.cancelInstall();
},
onDownloadCancelled(install) {
this.unregister();
},
onDownloadFailed(install) {
this.unregister();
},
onInstallFailed(install) {
this.unregister();
},
onInstallEnded(install) {
this.unregister();
},
QueryInterface: ChromeUtils.generateQI([
"nsISupportsWeakReference",
"nsIWebProgressListener",
"nsIObserver",
]),
};
/**
* This represents an author of an add-on (e.g. creator or developer)
*
* @param aName
* The name of the author
* @param aURL
* The URL of the author's profile page
*/
function AddonAuthor(aName, aURL) {
this.name = aName;
this.url = aURL;
}
AddonAuthor.prototype = {
name: null,
url: null,
// Returns the author's name, defaulting to the empty string
toString() {
return this.name || "";
},
};
/**
* This represents an screenshot for an add-on
*
* @param aURL
* The URL to the full version of the screenshot
* @param aWidth
* The width in pixels of the screenshot
* @param aHeight
* The height in pixels of the screenshot
* @param aThumbnailURL
* The URL to the thumbnail version of the screenshot
* @param aThumbnailWidth
* The width in pixels of the thumbnail version of the screenshot
* @param aThumbnailHeight
* The height in pixels of the thumbnail version of the screenshot
* @param aCaption
* The caption of the screenshot
*/
function AddonScreenshot(
aURL,
aWidth,
aHeight,
aThumbnailURL,
aThumbnailWidth,
aThumbnailHeight,
aCaption
) {
this.url = aURL;
if (aWidth) {
this.width = aWidth;
}
if (aHeight) {
this.height = aHeight;
}
if (aThumbnailURL) {
this.thumbnailURL = aThumbnailURL;
}
if (aThumbnailWidth) {
this.thumbnailWidth = aThumbnailWidth;
}
if (aThumbnailHeight) {
this.thumbnailHeight = aThumbnailHeight;
}
if (aCaption) {
this.caption = aCaption;
}
}
AddonScreenshot.prototype = {
url: null,
width: null,
height: null,
thumbnailURL: null,
thumbnailWidth: null,
thumbnailHeight: null,
caption: null,
// Returns the screenshot URL, defaulting to the empty string
toString() {
return this.url || "";
},
};
var gStarted = false;
var gStartedPromise = Promise.withResolvers();
var gStartupComplete = false;
var gCheckCompatibility = true;
var gStrictCompatibility = true;
var gCheckUpdateSecurityDefault = true;
var gCheckUpdateSecurity = gCheckUpdateSecurityDefault;
var gUpdateEnabled = true;
var gAutoUpdateDefault = true;
var gWebExtensionsMinPlatformVersion = "";
var gFinalShutdownBarrier = null;
var gBeforeShutdownBarrier = null;
var gRepoShutdownState = "";
var gShutdownInProgress = false;
var gBrowserUpdated = null;
export var AMTelemetry;
export var AMRemoteSettings;
export var AMBrowserExtensionsImport;
/**
* This is the real manager, kept here rather than in AddonManager to keep its
* contents hidden from API users.
* @class
* @lends AddonManager
*/
var AddonManagerInternal = {
managerListeners: new Set(),
installListeners: new Set(),
addonListeners: new Set(),
pendingProviders: new Set(),
providers: new Set(),
providerShutdowns: new Map(),
typesByProvider: new Map(),
startupChanges: {},
// Store telemetry details per addon provider
telemetryDetails: {},
upgradeListeners: new Map(),
externalExtensionLoaders: new Map(),
recordTimestamp(name, value) {
lazy.TelemetryTimestamps.add(name, value);
},
/**
* Start up a provider, and register its shutdown hook if it has one
*
* @param {string} aProvider - An add-on provider.
* @param {boolean} aAppChanged - Whether or not the app version has changed since last session.
* @param {string} aOldAppVersion - Previous application version, if changed.
* @param {string} aOldPlatformVersion - Previous platform version, if changed.
*
* @private
*/
_startProvider(aProvider, aAppChanged, aOldAppVersion, aOldPlatformVersion) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
logger.debug(`Starting provider: ${providerName(aProvider)}`);
callProvider(
aProvider,
"startup",
null,
aAppChanged,
aOldAppVersion,
aOldPlatformVersion
);
if ("shutdown" in aProvider) {
let name = providerName(aProvider);
let AMProviderShutdown = () => {
// If the provider has been unregistered, it will have been removed from
// this.providers. If it hasn't been unregistered, then this is a normal
// shutdown - and we move it to this.pendingProviders in case we're
// running in a test that will start AddonManager again.
if (this.providers.has(aProvider)) {
this.providers.delete(aProvider);
this.pendingProviders.add(aProvider);
}
return new Promise((resolve, reject) => {
logger.debug("Calling shutdown blocker for " + name);
resolve(aProvider.shutdown());
}).catch(err => {
logger.warn("Failure during shutdown of " + name, err);
AddonManagerPrivate.recordException(
"AMI",
"Async shutdown of " + name,
err
);
});
};
logger.debug("Registering shutdown blocker for " + name);
this.providerShutdowns.set(aProvider, AMProviderShutdown);
AddonManagerPrivate.finalShutdown.addBlocker(name, AMProviderShutdown);
}
this.pendingProviders.delete(aProvider);
this.providers.add(aProvider);
logger.debug(`Provider finished startup: ${providerName(aProvider)}`);
},
_getProviderByName(aName) {
for (let provider of this.providers) {
if (providerName(provider) == aName) {
return provider;
}
}
return undefined;
},
/**
* Initializes the AddonManager, loading any known providers and initializing
* them.
*/
startup() {
try {
if (gStarted) {
return;
}
this.recordTimestamp("AMI_startup_begin");
// Enable the addonsManager telemetry event category.
AMTelemetry.init();
// Enable the AMRemoteSettings client.
AMRemoteSettings.init();
// clear this for xpcshell test restarts
for (let provider in this.telemetryDetails) {
delete this.telemetryDetails[provider];
}
let appChanged = undefined;
let oldAppVersion = null;
try {
oldAppVersion = Services.prefs.getCharPref(PREF_EM_LAST_APP_VERSION);
appChanged = Services.appinfo.version != oldAppVersion;
} catch (e) {}
gBrowserUpdated = appChanged;
let oldPlatformVersion = Services.prefs.getCharPref(
PREF_EM_LAST_PLATFORM_VERSION,
""
);
if (appChanged !== false) {
logger.debug("Application has been upgraded");
Services.prefs.setCharPref(
PREF_EM_LAST_APP_VERSION,
Services.appinfo.version
);
Services.prefs.setCharPref(
PREF_EM_LAST_PLATFORM_VERSION,
Services.appinfo.platformVersion
);
Services.prefs.setIntPref(
PREF_BLOCKLIST_PINGCOUNTVERSION,
appChanged === undefined ? 0 : -1
);
}
if (!MOZ_COMPATIBILITY_NIGHTLY) {
PREF_EM_CHECK_COMPATIBILITY =
PREF_EM_CHECK_COMPATIBILITY_BASE +
"." +
Services.appinfo.version.replace(BRANCH_REGEXP, "$1");
}
gCheckCompatibility = Services.prefs.getBoolPref(
PREF_EM_CHECK_COMPATIBILITY,
gCheckCompatibility
);
Services.prefs.addObserver(PREF_EM_CHECK_COMPATIBILITY, this);
gStrictCompatibility = Services.prefs.getBoolPref(
PREF_EM_STRICT_COMPATIBILITY,
gStrictCompatibility
);
Services.prefs.addObserver(PREF_EM_STRICT_COMPATIBILITY, this);
let defaultBranch = Services.prefs.getDefaultBranch("");
gCheckUpdateSecurityDefault = defaultBranch.getBoolPref(
PREF_EM_CHECK_UPDATE_SECURITY,
gCheckUpdateSecurityDefault
);
gCheckUpdateSecurity = Services.prefs.getBoolPref(
PREF_EM_CHECK_UPDATE_SECURITY,
gCheckUpdateSecurity
);
Services.prefs.addObserver(PREF_EM_CHECK_UPDATE_SECURITY, this);
gUpdateEnabled = Services.prefs.getBoolPref(
PREF_EM_UPDATE_ENABLED,
gUpdateEnabled
);
Services.prefs.addObserver(PREF_EM_UPDATE_ENABLED, this);
gAutoUpdateDefault = Services.prefs.getBoolPref(
PREF_EM_AUTOUPDATE_DEFAULT,
gAutoUpdateDefault
);
Services.prefs.addObserver(PREF_EM_AUTOUPDATE_DEFAULT, this);
gWebExtensionsMinPlatformVersion = Services.prefs.getCharPref(
PREF_MIN_WEBEXT_PLATFORM_VERSION,
gWebExtensionsMinPlatformVersion
);
Services.prefs.addObserver(PREF_MIN_WEBEXT_PLATFORM_VERSION, this);
// Watch for changes to PREF_REMOTESETTINGS_DISABLED.
Services.prefs.addObserver(PREF_REMOTESETTINGS_DISABLED, this);
// Watch for language changes, refresh the addon cache when it changes.
Services.obs.addObserver(this, INTL_LOCALES_CHANGED);
// Watch for changes in the `AMBrowserExtensionsImport` singleton.
Services.obs.addObserver(this, AMBrowserExtensionsImport.TOPIC_CANCELLED);
Services.obs.addObserver(this, AMBrowserExtensionsImport.TOPIC_COMPLETE);
Services.obs.addObserver(this, AMBrowserExtensionsImport.TOPIC_PENDING);
// Ensure all default providers have had a chance to register themselves.
const { XPIExports } = ChromeUtils.importESModule(
"resource://gre/modules/addons/XPIExports.sys.mjs"
);
gXPIProvider = XPIExports.XPIProvider;
gXPIProvider.registerProvider();
// Load any providers registered in the category manager
for (let { entry, value: url } of Services.catMan.enumerateCategory(
CATEGORY_PROVIDER_MODULE
)) {
try {
ChromeUtils.importESModule(url);
logger.debug(`Loaded provider scope for ${url}`);
} catch (e) {
AddonManagerPrivate.recordException(
"AMI",
"provider " + url + " load failed",
e
);
logger.error(
"Exception loading provider " +
entry +
' from category "' +
url +
'"',
e
);
}
}
// Register our shutdown handler with the AsyncShutdown manager
gBeforeShutdownBarrier = new AsyncShutdown.Barrier(
"AddonManager: Waiting to start provider shutdown."
);
gFinalShutdownBarrier = new AsyncShutdown.Barrier(
"AddonManager: Waiting for providers to shut down."
);
AsyncShutdown.profileBeforeChange.addBlocker(
"AddonManager: shutting down.",
this.shutdownManager.bind(this),
{ fetchState: this.shutdownState.bind(this) }
);
// Once we start calling providers we must allow all normal methods to work.
gStarted = true;
for (let provider of this.pendingProviders) {
this._startProvider(
provider,
appChanged,
oldAppVersion,
oldPlatformVersion
);
}
// If this is a new profile just pretend that there were no changes
if (appChanged === undefined) {
for (let type in this.startupChanges) {
delete this.startupChanges[type];
}
}
gStartupComplete = true;
gStartedPromise.resolve();
this.recordTimestamp("AMI_startup_end");
} catch (e) {
logger.error("startup failed", e);
AddonManagerPrivate.recordException("AMI", "startup failed", e);
gStartedPromise.reject("startup failed");
}
// Disable the quarantined domains feature if the system add-on has been
// disabled in a previous version.
if (
Services.prefs.getBoolPref(
"extensions.webextensions.addons-restricted-domains@mozilla.com.disabled",
false
)
) {
Services.prefs.setBoolPref(
"extensions.quarantinedDomains.enabled",
false
);
logger.debug(
"Disabled quarantined domains because the system add-on was disabled"
);
}
Glean.extensions.useRemotePolicy.set(
WebExtensionPolicy.useRemoteWebExtensions
);
Glean.extensions.useRemotePref.set(
Services.prefs.getBoolPref(PREF_USE_REMOTE)
);
Services.prefs.addObserver(PREF_USE_REMOTE, this);
logger.debug("Completed startup sequence");
this.callManagerListeners("onStartup");
},
/**
* Registers a new AddonProvider.
*
* @param {string} aProvider -The provider to register
* @param {string[]} [aTypes] - An optional array of add-on types
*/
registerProvider(aProvider, aTypes) {
if (!aProvider || typeof aProvider != "object") {
throw Components.Exception(
"aProvider must be specified",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aTypes && !Array.isArray(aTypes)) {
throw Components.Exception(
"aTypes must be an array or null",
Cr.NS_ERROR_INVALID_ARG
);
}
this.pendingProviders.add(aProvider);
if (aTypes) {
this.typesByProvider.set(aProvider, new Set(aTypes));
}
// If we're registering after startup call this provider's startup.
if (gStarted) {
this._startProvider(aProvider);
}
},
/**
* Unregisters an AddonProvider.
*
* @param aProvider
* The provider to unregister
* @return Whatever the provider's 'shutdown' method returns (if anything).
* For providers that have async shutdown methods returning Promises,
* the caller should wait for that Promise to resolve.
*/
unregisterProvider(aProvider) {
if (!aProvider || typeof aProvider != "object") {
throw Components.Exception(
"aProvider must be specified",
Cr.NS_ERROR_INVALID_ARG
);
}
this.providers.delete(aProvider);
// The test harness will unregister XPIProvider *after* shutdown, which is
// after the provider will have been moved from providers to
// pendingProviders.
this.pendingProviders.delete(aProvider);
this.typesByProvider.delete(aProvider);
// If we're unregistering after startup but before shutting down,
// remove the blocker for this provider's shutdown and call it.
// If we're already shutting down, just let gFinalShutdownBarrier
// call it to avoid races.
if (gStarted && !gShutdownInProgress) {
logger.debug(
"Unregistering shutdown blocker for " + providerName(aProvider)
);
let shutter = this.providerShutdowns.get(aProvider);
if (shutter) {
this.providerShutdowns.delete(aProvider);
gFinalShutdownBarrier.client.removeBlocker(shutter);
return shutter();
}
}
return undefined;
},
/**
* Mark a provider as safe to access via AddonManager APIs, before its
* startup has completed.
*
* Normally a provider isn't marked as safe until after its (synchronous)
* startup() method has returned. Until a provider has been marked safe,
* it won't be used by any of the AddonManager APIs. markProviderSafe()
* allows a provider to mark itself as safe during its startup; this can be
* useful if the provider wants to perform tasks that block startup, which
* happen after its required initialization tasks and therefore when the
* provider is in a safe state.
*
* @param aProvider Provider object to mark safe
*/
markProviderSafe(aProvider) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aProvider || typeof aProvider != "object") {
throw Components.Exception(
"aProvider must be specified",
Cr.NS_ERROR_INVALID_ARG
);
}
if (!this.pendingProviders.has(aProvider)) {
return;
}
this.pendingProviders.delete(aProvider);
this.providers.add(aProvider);
},
/**
* Calls a method on all registered providers if it exists and consumes any
* thrown exception. Return values are ignored. Any parameters after the
* method parameter are passed to the provider's method.
* WARNING: Do not use for asynchronous calls; callProviders() does not
* invoke callbacks if provider methods throw synchronous exceptions.
*
* @param aMethod
* The method name to call
*/
callProviders(aMethod, ...aArgs) {
if (!aMethod || typeof aMethod != "string") {
throw Components.Exception(
"aMethod must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
let providers = [...this.providers];
for (let provider of providers) {
try {
if (aMethod in provider) {
provider[aMethod].apply(provider, aArgs);
}
} catch (e) {
reportProviderError(provider, aMethod, e);
}
}
},
/**
* Report the current state of asynchronous shutdown
*/
shutdownState() {
let state = [];
for (let barrier of [gBeforeShutdownBarrier, gFinalShutdownBarrier]) {
if (barrier) {
state.push({ name: barrier.client.name, state: barrier.state });
}
}
state.push({
name: "AddonRepository: async shutdown",
state: gRepoShutdownState,
});
return state;
},
/**
* Shuts down the addon manager and all registered providers, this must clean
* up everything in order for automated tests to fake restarts.
* @return Promise{null} that resolves when all providers and dependent modules
* have finished shutting down
*/
async shutdownManager() {
logger.debug("before shutdown");
try {
await gBeforeShutdownBarrier.wait();
} catch (e) {
Cu.reportError(e);
}
logger.debug("shutdown");
this.callManagerListeners("onShutdown");
if (!gStartupComplete) {
gStartedPromise.reject("shutting down");
}
gRepoShutdownState = "pending";
gShutdownInProgress = true;
// Clean up listeners
Services.prefs.removeObserver(PREF_EM_CHECK_COMPATIBILITY, this);
Services.prefs.removeObserver(PREF_EM_STRICT_COMPATIBILITY, this);
Services.prefs.removeObserver(PREF_EM_CHECK_UPDATE_SECURITY, this);
Services.prefs.removeObserver(PREF_EM_UPDATE_ENABLED, this);
Services.prefs.removeObserver(PREF_EM_AUTOUPDATE_DEFAULT, this);
Services.prefs.removeObserver(PREF_REMOTESETTINGS_DISABLED, this);
Services.obs.removeObserver(this, INTL_LOCALES_CHANGED);
Services.obs.removeObserver(
this,
AMBrowserExtensionsImport.TOPIC_CANCELLED
);
Services.obs.removeObserver(this, AMBrowserExtensionsImport.TOPIC_COMPLETE);
Services.obs.removeObserver(this, AMBrowserExtensionsImport.TOPIC_PENDING);
AMRemoteSettings.shutdown();
let savedError = null;
// Only shut down providers if they've been started.
if (gStarted) {
try {
await gFinalShutdownBarrier.wait();
} catch (err) {
savedError = err;
logger.error("Failure during wait for shutdown barrier", err);
AddonManagerPrivate.recordException(
"AMI",
"Async shutdown of AddonManager providers",
err
);
}
}
gXPIProvider = null;
// Shut down AddonRepository after providers (if any).
try {
gRepoShutdownState = "in progress";
await lazy.AddonRepository.shutdown();
gRepoShutdownState = "done";
} catch (err) {
savedError = err;
logger.error("Failure during AddonRepository shutdown", err);
AddonManagerPrivate.recordException(
"AMI",
"Async shutdown of AddonRepository",
err
);
}
logger.debug("Async provider shutdown done");
this.managerListeners.clear();
this.installListeners.clear();
this.addonListeners.clear();
this.providerShutdowns.clear();
for (let type in this.startupChanges) {
delete this.startupChanges[type];
}
gStarted = false;
gStartedPromise = Promise.withResolvers();
gStartupComplete = false;
gFinalShutdownBarrier = null;
gBeforeShutdownBarrier = null;
gShutdownInProgress = false;
if (savedError) {
throw savedError;
}
},
/**
* Notified when a preference we're interested in has changed.
*/
observe(aSubject, aTopic, aData) {
switch (aTopic) {
case INTL_LOCALES_CHANGED: {
// Asynchronously fetch and update the addons cache.
lazy.AddonRepository.backgroundUpdateCheck();
return;
}
case AMBrowserExtensionsImport.TOPIC_CANCELLED:
case AMBrowserExtensionsImport.TOPIC_COMPLETE:
case AMBrowserExtensionsImport.TOPIC_PENDING:
this.callManagerListeners("onBrowserExtensionsImportChanged");
return;
}
switch (aData) {
case PREF_EM_CHECK_COMPATIBILITY: {
let oldValue = gCheckCompatibility;
gCheckCompatibility = Services.prefs.getBoolPref(
PREF_EM_CHECK_COMPATIBILITY,
true
);
this.callManagerListeners("onCompatibilityModeChanged");
if (gCheckCompatibility != oldValue) {
this.updateAddonAppDisabledStates();
}
break;
}
case PREF_EM_STRICT_COMPATIBILITY: {
let oldValue = gStrictCompatibility;
gStrictCompatibility = Services.prefs.getBoolPref(
PREF_EM_STRICT_COMPATIBILITY,
true
);
this.callManagerListeners("onCompatibilityModeChanged");
if (gStrictCompatibility != oldValue) {
this.updateAddonAppDisabledStates();
}
break;
}
case PREF_EM_CHECK_UPDATE_SECURITY: {
let oldValue = gCheckUpdateSecurity;
gCheckUpdateSecurity = Services.prefs.getBoolPref(
PREF_EM_CHECK_UPDATE_SECURITY,
true
);
this.callManagerListeners("onCheckUpdateSecurityChanged");
if (gCheckUpdateSecurity != oldValue) {
this.updateAddonAppDisabledStates();
}
break;
}
case PREF_EM_UPDATE_ENABLED: {
gUpdateEnabled = Services.prefs.getBoolPref(
PREF_EM_UPDATE_ENABLED,
true
);
this.callManagerListeners("onUpdateModeChanged");
break;
}
case PREF_EM_AUTOUPDATE_DEFAULT: {
gAutoUpdateDefault = Services.prefs.getBoolPref(
PREF_EM_AUTOUPDATE_DEFAULT,
true
);
this.callManagerListeners("onUpdateModeChanged");
break;
}
case PREF_MIN_WEBEXT_PLATFORM_VERSION: {
gWebExtensionsMinPlatformVersion = Services.prefs.getCharPref(
PREF_MIN_WEBEXT_PLATFORM_VERSION
);
break;
}
case PREF_REMOTESETTINGS_DISABLED: {
if (Services.prefs.getBoolPref(PREF_REMOTESETTINGS_DISABLED, false)) {
AMRemoteSettings.shutdown();
} else {
AMRemoteSettings.init();
}
break;
}
case PREF_USE_REMOTE: {
Glean.extensions.useRemotePref.set(
Services.prefs.getBoolPref(PREF_USE_REMOTE)
);
break;
}
}
},
/**
* Replaces %...% strings in an addon url (update and updateInfo) with
* appropriate values.
*
* @param aAddon
* The Addon representing the add-on
* @param aUri
* The string representation of the URI to escape
* @param aAppVersion
* The optional application version to use for %APP_VERSION%
* @return The appropriately escaped URI.
*/
escapeAddonURI(aAddon, aUri, aAppVersion) {
if (!aAddon || typeof aAddon != "object") {
throw Components.Exception(
"aAddon must be an Addon object",
Cr.NS_ERROR_INVALID_ARG
);
}
if (!aUri || typeof aUri != "string") {
throw Components.Exception(
"aUri must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aAppVersion && typeof aAppVersion != "string") {
throw Components.Exception(
"aAppVersion must be a string or null",
Cr.NS_ERROR_INVALID_ARG
);
}
var addonStatus =
aAddon.userDisabled || aAddon.softDisabled
? "userDisabled"
: "userEnabled";
if (!aAddon.isCompatible) {
addonStatus += ",incompatible";
}
let { blocklistState } = aAddon;
if (blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED) {
addonStatus += ",blocklisted";
}
if (blocklistState == Ci.nsIBlocklistService.STATE_SOFTBLOCKED) {
addonStatus += ",softblocked";
}
let params = new Map(
Object.entries({
ITEM_ID: aAddon.id,
ITEM_VERSION: aAddon.version,
ITEM_STATUS: addonStatus,
APP_ID: Services.appinfo.ID,
APP_VERSION: aAppVersion ? aAppVersion : Services.appinfo.version,
REQ_VERSION: UPDATE_REQUEST_VERSION,
APP_OS: Services.appinfo.OS,
APP_ABI: Services.appinfo.XPCOMABI,
APP_LOCALE: getLocale(),
CURRENT_APP_VERSION: Services.appinfo.version,
})
);
let uri = aUri.replace(/%([A-Z_]+)%/g, (m0, m1) => params.get(m1) || m0);
// escape() does not properly encode + symbols in any embedded FVF strings.
return uri.replace(/\+/g, "%2B");
},
_updatePromptHandler(info) {
let oldPerms = info.existingAddon.userPermissions;
if (!oldPerms) {
// Updating from a legacy add-on, just let it proceed
return Promise.resolve();
}
let newPerms = info.addon.userPermissions;
let difference = lazy.Extension.comparePermissions(oldPerms, newPerms);
// If there are no new permissions, just go ahead with the update
if (!difference.origins.length && !difference.permissions.length) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
let subject = {
wrappedJSObject: {
addon: info.addon,
permissions: difference,
resolve,
reject,
// Reference to the related AddonInstall object (used in AMTelemetry to
// link the recorded event to the other events from the same install flow).
install: info.install,
},
};
Services.obs.notifyObservers(subject, "webextension-update-permissions");
});
},
// Returns true if System Addons should be updated
systemUpdateEnabled() {
if (!Services.prefs.getBoolPref(PREF_SYS_ADDON_UPDATE_ENABLED)) {
return false;
}
if (Services.policies && !Services.policies.isAllowed("SysAddonUpdate")) {
return false;
}
return true;
},
/**
* Performs a background update check by starting an update for all add-ons
* that can be updated.
* @return Promise{null} Resolves when the background update check is complete
* (the resulting addon installations may still be in progress).
*/
backgroundUpdateCheck() {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
let buPromise = (async () => {
logger.debug("Background update check beginning");
Services.obs.notifyObservers(null, "addons-background-update-start");
if (this.updateEnabled) {
// Keep track of all the async add-on updates happening in parallel
let updates = [];
let allAddons = await this.getAllAddons();
// Repopulate repository cache first, to ensure compatibility overrides
// are up to date before checking for addon updates.
await lazy.AddonRepository.backgroundUpdateCheck();
for (let addon of allAddons) {
// Check all add-ons for updates so that any compatibility updates will
// be applied
if (!(addon.permissions & AddonManager.PERM_CAN_UPGRADE)) {
continue;
}
updates.push(
new Promise((resolve, reject) => {
addon.findUpdates(
{
onUpdateAvailable(aAddon, aInstall) {
// Start installing updates when the add-on can be updated and
// background updates should be applied.
logger.debug("Found update for add-on ${id}", aAddon);
if (AddonManager.shouldAutoUpdate(aAddon)) {
// XXX we really should resolve when this install is done,
// not when update-available check completes, no?
logger.debug(`Starting upgrade install of ${aAddon.id}`);
aInstall.promptHandler = (...args) =>
AddonManagerInternal._updatePromptHandler(...args);
aInstall.install();
}
},
onUpdateFinished: aAddon => {
logger.debug("onUpdateFinished for ${id}", aAddon);
resolve();
},
},
AddonManager.UPDATE_WHEN_PERIODIC_UPDATE
);
})
);
}
Services.obs.notifyObservers(
null,
"addons-background-updates-found",
updates.length
);
await Promise.all(updates);
}
if (AddonManagerInternal.systemUpdateEnabled()) {
try {
await AddonManagerInternal._getProviderByName(
"XPIProvider"
).updateSystemAddons();
} catch (e) {
logger.warn("Failed to update system addons", e);
}
}
logger.debug("Background update check complete");
Services.obs.notifyObservers(null, "addons-background-update-complete");
})();
// Fork the promise chain so we can log the error and let our caller see it too.
buPromise.catch(e => logger.warn("Error in background update", e));
return buPromise;
},
/**
* Adds a add-on to the list of detected changes for this startup. If
* addStartupChange is called multiple times for the same add-on in the same
* startup then only the most recent change will be remembered.
*
* @param aType
* The type of change as a string. Providers can define their own
* types of changes or use the existing defined STARTUP_CHANGE_*
* constants
* @param aID
* The ID of the add-on
*/
addStartupChange(aType, aID) {
if (!aType || typeof aType != "string") {
throw Components.Exception(
"aType must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
if (!aID || typeof aID != "string") {
throw Components.Exception(
"aID must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
if (gStartupComplete) {
return;
}
logger.debug("Registering startup change '" + aType + "' for " + aID);
// Ensure that an ID is only listed in one type of change
for (let type in this.startupChanges) {
this.removeStartupChange(type, aID);
}
if (!(aType in this.startupChanges)) {
this.startupChanges[aType] = [];
}
this.startupChanges[aType].push(aID);
},
/**
* Removes a startup change for an add-on.
*
* @param aType
* The type of change
* @param aID
* The ID of the add-on
*/
removeStartupChange(aType, aID) {
if (!aType || typeof aType != "string") {
throw Components.Exception(
"aType must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
if (!aID || typeof aID != "string") {
throw Components.Exception(
"aID must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
if (gStartupComplete) {
return;
}
if (!(aType in this.startupChanges)) {
return;
}
this.startupChanges[aType] = this.startupChanges[aType].filter(
aItem => aItem != aID
);
},
/**
* Calls all registered AddonManagerListeners with an event. Any parameters
* after the method parameter are passed to the listener.
*
* @param aMethod
* The method on the listeners to call
*/
callManagerListeners(aMethod, ...aArgs) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aMethod || typeof aMethod != "string") {
throw Components.Exception(
"aMethod must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
let managerListeners = new Set(this.managerListeners);
for (let listener of managerListeners) {
try {
if (aMethod in listener) {
listener[aMethod].apply(listener, aArgs);
}
} catch (e) {
logger.warn(
"AddonManagerListener threw exception when calling " + aMethod,
e
);
}
}
},
/**
* Calls all registered InstallListeners with an event. Any parameters after
* the extraListeners parameter are passed to the listener.
*
* @param aMethod
* The method on the listeners to call
* @param aExtraListeners
* An optional array of extra InstallListeners to also call
* @return false if any of the listeners returned false, true otherwise
*/
callInstallListeners(aMethod, aExtraListeners, ...aArgs) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aMethod || typeof aMethod != "string") {
throw Components.Exception(
"aMethod must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aExtraListeners && !Array.isArray(aExtraListeners)) {
throw Components.Exception(
"aExtraListeners must be an array or null",
Cr.NS_ERROR_INVALID_ARG
);
}
let result = true;
let listeners;
if (aExtraListeners) {
listeners = new Set(
aExtraListeners.concat(Array.from(this.installListeners))
);
} else {
listeners = new Set(this.installListeners);
}
for (let listener of listeners) {
try {
if (aMethod in listener) {
if (listener[aMethod].apply(listener, aArgs) === false) {
result = false;
}
}
} catch (e) {
logger.warn(
"InstallListener threw exception when calling " + aMethod,
e
);
}
}
return result;
},
/**
* Calls all registered AddonListeners with an event. Any parameters after
* the method parameter are passed to the listener.
*
* @param aMethod
* The method on the listeners to call
*/
callAddonListeners(aMethod, ...aArgs) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aMethod || typeof aMethod != "string") {
throw Components.Exception(
"aMethod must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
let addonListeners = new Set(this.addonListeners);
for (let listener of addonListeners) {
try {
if (aMethod in listener) {
listener[aMethod].apply(listener, aArgs);
}
} catch (e) {
logger.warn("AddonListener threw exception when calling " + aMethod, e);
}
}
},
/**
* Notifies all providers that an add-on has been enabled when that type of
* add-on only supports a single add-on being enabled at a time. This allows
* the providers to disable theirs if necessary.
*
* @param aID
* The ID of the enabled add-on
* @param aType
* The type of the enabled add-on
* @param aPendingRestart
* A boolean indicating if the change will only take place the next
* time the application is restarted
*/
async notifyAddonChanged(aID, aType, aPendingRestart) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (aID && typeof aID != "string") {
throw Components.Exception(
"aID must be a string or null",
Cr.NS_ERROR_INVALID_ARG
);
}
if (!aType || typeof aType != "string") {
throw Components.Exception(
"aType must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
// Temporary hack until bug 520124 lands.
// We can get here during synchronous startup, at which point it's
// considered unsafe (and therefore disallowed by AddonManager.sys.mjs) to
// access providers that haven't been initialized yet. Since this is when
// XPIProvider is starting up, XPIProvider can't access itself via APIs
// going through AddonManager.sys.mjs. Thankfully, this is the only use
// of this API, and we know it's safe to use this API with both
// providers; so we have this hack to allow bypassing the normal
// safetey guard.
// The notifyAddonChanged/addonChanged API will be unneeded and therefore
// removed by bug 520124, so this is a temporary quick'n'dirty hack.
let providers = [...this.providers, ...this.pendingProviders];
for (let provider of providers) {
let result = callProvider(
provider,
"addonChanged",
null,
aID,
aType,
aPendingRestart
);
if (result) {
await result;
}
}
},
/**
* Notifies all providers they need to update the appDisabled property for
* their add-ons in response to an application change such as a blocklist
* update.
*/
updateAddonAppDisabledStates() {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
this.callProviders("updateAddonAppDisabledStates");
},
/**
* Notifies all providers that the repository has updated its data for
* installed add-ons.
*/
updateAddonRepositoryData() {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
return (async () => {
for (let provider of this.providers) {
await promiseCallProvider(provider, "updateAddonRepositoryData");
}
// only tests should care about this
Services.obs.notifyObservers(null, "TEST:addon-repository-data-updated");
})();
},
/**
* Asynchronously gets an AddonInstall for a URL.
*
* @param aUrl
* The string represenation of the URL where the add-on is located
* @param {Object} [aOptions = {}]
* Additional options for this install
* @param {string} [aOptions.hash]
* An optional hash of the add-on
* @param {string} [aOptions.name]
* An optional placeholder name while the add-on is being downloaded
* @param {string|Object} [aOptions.icons]
* Optional placeholder icons while the add-on is being downloaded
* @param {string} [aOptions.version]
* An optional placeholder version while the add-on is being downloaded
* @param {XULElement} [aOptions.browser]
* An optional <browser> element for download permissions prompts.
* @param {nsIPrincipal} [aOptions.triggeringPrincipal]
* The principal which is attempting to install the add-on.
* @param {Object} [aOptions.telemetryInfo]
* An optional object which provides details about the installation source
* included in the addon manager telemetry events.
* @throws if aUrl is not specified or if an optional argument of
* an improper type is passed.
*/
async getInstallForURL(aUrl, aOptions = {}) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aUrl || typeof aUrl != "string") {
throw Components.Exception(
"aURL must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aOptions.hash && typeof aOptions.hash != "string") {
throw Components.Exception(
"hash must be a string or null",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aOptions.name && typeof aOptions.name != "string") {
throw Components.Exception(
"name must be a string or null",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aOptions.icons) {
if (typeof aOptions.icons == "string") {
aOptions.icons = { 32: aOptions.icons };
} else if (typeof aOptions.icons != "object") {
throw Components.Exception(
"icons must be a string, an object or null",
Cr.NS_ERROR_INVALID_ARG
);
}
} else {
aOptions.icons = {};
}
if (aOptions.version && typeof aOptions.version != "string") {
throw Components.Exception(
"version must be a string or null",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aOptions.browser && !Element.isInstance(aOptions.browser)) {
throw Components.Exception(
"aOptions.browser must be an Element or null",
Cr.NS_ERROR_INVALID_ARG
);
}
for (let provider of this.providers) {
let install = await promiseCallProvider(
provider,
"getInstallForURL",
aUrl,
aOptions
);
if (install) {
return install;
}
}
return null;
},
/**
* Asynchronously gets an AddonInstall for an nsIFile.
*
* @param aFile
* The nsIFile where the add-on is located
* @param aMimetype
* An optional mimetype hint for the add-on
* @param aTelemetryInfo
* An optional object which provides details about the installation source
* included in the addon manager telemetry events.
* @param aUseSystemLocation
* If true the addon is installed into the system profile location.
* @throws if the aFile or aCallback arguments are not specified
*/
getInstallForFile(aFile, aMimetype, aTelemetryInfo, aUseSystemLocation) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!(aFile instanceof Ci.nsIFile)) {
throw Components.Exception(
"aFile must be a nsIFile",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aMimetype && typeof aMimetype != "string") {
throw Components.Exception(
"aMimetype must be a string or null",
Cr.NS_ERROR_INVALID_ARG
);
}
return (async () => {
for (let provider of this.providers) {
let install = await promiseCallProvider(
provider,
"getInstallForFile",
aFile,
aTelemetryInfo,
aUseSystemLocation
);
if (install) {
return install;
}
}
return null;
})();
},
/**
* Get a SitePermsAddonInstall instance.
*
* @param {Element} aBrowser: The optional browser element that started the install
* @param {nsIPrincipal} aInstallingPrincipal
* @param {String} aSitePerm
* @returns {Promise<SitePermsAddonInstall|null>} The promise will resolve with null if there
* are no provider with a getSitePermsAddonInstallForWebpage method. In practice,
* this should only be the case when SitePermsAddonProvider is not enabled,
* i.e. when dom.sitepermsaddon-provider.enabled is false.
* @throws {Components.Exception} Will throw an error if:
* - the AddonManager is not initialized
* - `aInstallingPrincipal` is not a nsIPrincipal
* - `aInstallingPrincipal` scheme is not https
* - `aInstallingPrincipal` is a public etld
* - `aInstallingPrincipal` is a plain ip address
* - `aInstallingPrincipal` is in the blocklist
* - `aSitePerm` is not a gated permission
* - `aBrowser` is not null and not an element
*/
async getSitePermsAddonInstallForWebpage(
aBrowser,
aInstallingPrincipal,
aSitePerm
) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (
!aInstallingPrincipal ||
!(aInstallingPrincipal instanceof Ci.nsIPrincipal)
) {
throw Components.Exception(
"aInstallingPrincipal must be a nsIPrincipal",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aBrowser && !Element.isInstance(aBrowser)) {
throw Components.Exception(
"aBrowser must be an Element, or null",
Cr.NS_ERROR_INVALID_ARG
);
}
if (lazy.isPrincipalInSitePermissionsBlocklist(aInstallingPrincipal)) {
throw Components.Exception(
`SitePermsAddons can't be installed`,
Cr.NS_ERROR_INVALID_ARG
);
}
// Block install from null principal.
// /!\ We need to do this check before checking if this is a remote origin iframe,
// otherwise isThirdPartyPrincipal might throw.
if (aInstallingPrincipal.isNullPrincipal) {
throw Components.Exception(
`SitePermsAddons can't be installed from sandboxed subframes`,
Cr.NS_ERROR_INVALID_ARG
);
}
// Block install from remote origin iframe
if (
aBrowser &&
aBrowser.contentPrincipal.isThirdPartyPrincipal(aInstallingPrincipal)
) {
throw Components.Exception(
`SitePermsAddons can't be installed from cross origin subframes`,
Cr.NS_ERROR_INVALID_ARG
);
}
if (aInstallingPrincipal.isIpAddress) {
throw Components.Exception(
`SitePermsAddons install disallowed when the host is an IP address`,
Cr.NS_ERROR_INVALID_ARG
);
}
// Gated APIs should probably not be available on non-secure origins,
// but let's double check here.
if (aInstallingPrincipal.scheme !== "https") {
throw Components.Exception(
`SitePermsAddons can only be installed from secure origins`,
Cr.NS_ERROR_INVALID_ARG
);
}
// Install origin cannot be on a known etld (e.g. github.io).
if (lazy.isKnownPublicSuffix(aInstallingPrincipal.siteOriginNoSuffix)) {
throw Components.Exception(
`SitePermsAddon can't be installed from public eTLDs ${aInstallingPrincipal.siteOriginNoSuffix}`,
Cr.NS_ERROR_INVALID_ARG
);
}
if (!lazy.isGatedPermissionType(aSitePerm)) {
throw Components.Exception(
`"${aSitePerm}" is not a gated permission`,
Cr.NS_ERROR_INVALID_ARG
);
}
for (let provider of this.providers) {
let install = await promiseCallProvider(
provider,
"getSitePermsAddonInstallForWebpage",
aInstallingPrincipal,
aSitePerm
);
if (install) {
return install;
}
}
return null;
},
/**
* Uninstall an addon from the system profile location.
*
* @param {string} aID
* The ID of the addon to remove.
* @returns A promise that resolves when the addon is uninstalled.
*/
uninstallSystemProfileAddon(aID) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
return AddonManagerInternal._getProviderByName(
"XPIProvider"
).uninstallSystemProfileAddon(aID);
},
/**
* Asynchronously gets all current AddonInstalls optionally limiting to a list
* of types.
*
* @param aTypes
* An optional array of types to retrieve. Each type is a string name
* @throws If the aCallback argument is not specified
*/
getInstallsByTypes(aTypes) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (aTypes && !Array.isArray(aTypes)) {
throw Components.Exception(
"aTypes must be an array or null",
Cr.NS_ERROR_INVALID_ARG
);
}
return (async () => {
let installs = [];
for (let provider of this.providers) {
let providerInstalls = await promiseCallProvider(
provider,
"getInstallsByTypes",
aTypes
);
if (providerInstalls) {
installs.push(...providerInstalls);
}
}
return installs;
})();
},
/**
* Asynchronously gets all current AddonInstalls.
*/
getAllInstalls() {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
return this.getInstallsByTypes(null);
},
/**
* Checks whether installation is enabled for a particular mimetype.
*
* @param aMimetype
* The mimetype to check
* @return true if installation is enabled for the mimetype
*/
isInstallEnabled(aMimetype) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aMimetype || typeof aMimetype != "string") {
throw Components.Exception(
"aMimetype must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
let providers = [...this.providers];
for (let provider of providers) {
if (
callProvider(provider, "supportsMimetype", false, aMimetype) &&
callProvider(provider, "isInstallEnabled")
) {
return true;
}
}
return false;
},
/**
* Checks whether a particular source is allowed to install add-ons of a
* given mimetype.
*
* @param aMimetype
* The mimetype of the add-on
* @param aInstallingPrincipal
* The nsIPrincipal that initiated the install
* @return true if the source is allowed to install this mimetype
*/
isInstallAllowed(aMimetype, aInstallingPrincipal) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aMimetype || typeof aMimetype != "string") {
throw Components.Exception(
"aMimetype must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
if (
!aInstallingPrincipal ||
!(aInstallingPrincipal instanceof Ci.nsIPrincipal)
) {
throw Components.Exception(
"aInstallingPrincipal must be a nsIPrincipal",
Cr.NS_ERROR_INVALID_ARG
);
}
if (
this.isInstallAllowedByPolicy(
aInstallingPrincipal,
null,
true /* explicit */
)
) {
return true;
}
let providers = [...this.providers];
for (let provider of providers) {
if (
callProvider(provider, "supportsMimetype", false, aMimetype) &&
callProvider(provider, "isInstallAllowed", null, aInstallingPrincipal)
) {
return true;
}
}
return false;
},
/**
* Checks whether a particular source is allowed to install add-ons based
* on policy.
*
* @param aInstallingPrincipal
* The nsIPrincipal that initiated the install
* @param aInstall
* The AddonInstall to be installed
* @param explicit
* If this is set, we only return true if the source is explicitly
* blocked via policy.
*
* @return boolean
* By default, returns true if the source is blocked by policy
* or there is no policy.
* If explicit is set, only returns true of the source is
* blocked by policy, false otherwise. This is needed for
* handling inverse cases.
*/
isInstallAllowedByPolicy(aInstallingPrincipal, aInstall, explicit) {
if (Services.policies) {
let extensionSettings = Services.policies.getExtensionSettings("*");
if (extensionSettings && extensionSettings.install_sources) {
if (
(!aInstall ||
Services.policies.allowedInstallSource(aInstall.sourceURI)) &&
(!aInstallingPrincipal ||
!aInstallingPrincipal.URI ||
Services.policies.allowedInstallSource(aInstallingPrincipal.URI))
) {
return true;
}
return false;
}
}
return !explicit;
},
installNotifyObservers(
aTopic,
aBrowser,
aUri,
aInstall,
aInstallFn,
aCancelFn
) {
let info = {
wrappedJSObject: {
browser: aBrowser,
originatingURI: aUri,
installs: [aInstall],
install: aInstallFn,
cancel: aCancelFn,
},
};
Services.obs.notifyObservers(info, aTopic);
},
startInstall(browser, url, install) {
this.installNotifyObservers("addon-install-started", browser, url, install);
// Local installs may already be in a failed state in which case
// we won't get any further events, detect those cases now.
if (
install.state == AddonManager.STATE_DOWNLOADED &&
install.addon.appDisabled
) {
install.cancel();
this.installNotifyObservers(
"addon-install-failed",
browser,
url,
install
);
return;
}
let self = this;
let listener = {
onDownloadCancelled() {
install.removeListener(listener);
},
onDownloadFailed() {
install.removeListener(listener);
self.installNotifyObservers(
"addon-install-failed",
browser,
url,
install
);
},
onDownloadEnded() {
if (install.addon.appDisabled) {
// App disabled items are not compatible and so fail to install.
install.removeListener(listener);
install.cancel();
self.installNotifyObservers(
"addon-install-failed",
browser,
url,
install
);
}
},
onInstallCancelled() {
install.removeListener(listener);
},
onInstallFailed() {
install.removeListener(listener);
self.installNotifyObservers(
"addon-install-failed",
browser,
url,
install
);
},
onInstallEnded() {
install.removeListener(listener);
// If installing a theme that is disabled and can be enabled
// then enable it
if (
install.addon.type == "theme" &&
!!install.addon.userDisabled &&
!install.addon.appDisabled
) {
install.addon.enable();
}
let subject = {
wrappedJSObject: { target: browser, addon: install.addon },
};
Services.obs.notifyObservers(subject, "webextension-install-notify");
},
};
install.addListener(listener);
// Start downloading if it hasn't already begun
install.install();
},
/**
* Starts installation of a SitePermsAddonInstall notifying the registered
* web install listener of a blocked or started install.
*
* @param aBrowser
* The optional browser element that started the install
* @param aInstallingPrincipal
* The nsIPrincipal that initiated the install
* @param aPermission
* The permission to install
* @returns {Promise} A promise that will resolve when the user installs the addon.
* The promise will reject if the user blocked the install, or if the addon
* can't be installed (e.g. the principal isn't supported).
* @throws {Components.Exception} Will throw an error if the AddonManager is not initialized
* or if `aInstallingPrincipal` is not a nsIPrincipal.
*/
async installSitePermsAddonFromWebpage(
aBrowser,
aInstallingPrincipal,
aPermission
) {
const synthAddonInstall =
await AddonManagerInternal.getSitePermsAddonInstallForWebpage(
aBrowser,
aInstallingPrincipal,
aPermission
);
const promiseInstall = new Promise((resolve, reject) => {
const installListener = {
onInstallFailed() {
synthAddonInstall.removeListener(installListener);
reject(new Error("Install Failed"));
},
onInstallCancelled() {
synthAddonInstall.removeListener(installListener);
reject(new Error("Install Cancelled"));
},
onInstallEnded() {
synthAddonInstall.removeListener(installListener);
resolve();
},
};
synthAddonInstall.addListener(installListener);
});
let startInstall = () => {
AddonManagerInternal.setupPromptHandler(
aBrowser,
aInstallingPrincipal.URI,
synthAddonInstall,
true,
"SitePermissionAddonPrompt"
);
AddonManagerInternal.startInstall(
aBrowser,
aInstallingPrincipal.URI,
synthAddonInstall
);
};
startInstall();
return promiseInstall;
},
/**
* Starts installation of an AddonInstall notifying the registered
* web install listener of a blocked or started install.
*
* @param aMimetype
* The mimetype of the add-on being installed
* @param aBrowser
* The optional browser element that started the install
* @param aInstallingPrincipal
* The nsIPrincipal that initiated the install
* @param aInstall
* The AddonInstall to be installed
* @param [aDetails]
* Additional optional details
* @param [aDetails.hasCrossOriginAncestor]
* Boolean value set to true if any of cross-origin ancestors of the triggering frame
* (if set to true the installation will be denied).
*/
installAddonFromWebpage(
aMimetype,
aBrowser,
aInstallingPrincipal,
aInstall,
aDetails
) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aMimetype || typeof aMimetype != "string") {
throw Components.Exception(
"aMimetype must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
if (aBrowser && !Element.isInstance(aBrowser)) {
throw Components.Exception(
"aSource must be an Element, or null",
Cr.NS_ERROR_INVALID_ARG
);
}
if (
!aInstallingPrincipal ||
!(aInstallingPrincipal instanceof Ci.nsIPrincipal)
) {
throw Components.Exception(
"aInstallingPrincipal must be a nsIPrincipal",
Cr.NS_ERROR_INVALID_ARG
);
}
// When a chrome in-content UI has loaded a <browser> inside to host a
// website we want to do our security checks on the inner-browser but
// notify front-end that install events came from the top browser (the
// main tab's browser).
// aBrowser is null in GeckoView.
let topBrowser = aBrowser?.browsingContext.top.embedderElement;
try {
// Use fullscreenElement to check for DOM fullscreen, while still allowing
// macOS fullscreen, which still has a browser chrome.
if (topBrowser && topBrowser.ownerDocument.fullscreenElement) {
// Addon installation and the resulting notifications should be
// blocked in DOM fullscreen for security and usability reasons.
// Installation prompts in fullscreen can trick the user into
// installing unwanted addons.
// In fullscreen the notification box does not have a clear
// visual association with its parent anymore.
aInstall.cancel();
this.installNotifyObservers(
"addon-install-fullscreen-blocked",
topBrowser,
aInstallingPrincipal.URI,
aInstall
);
return;
} else if (!this.isInstallEnabled(aMimetype)) {
aInstall.cancel();
this.installNotifyObservers(
"addon-install-disabled",
topBrowser,
aInstallingPrincipal.URI,
aInstall
);
return;
} else if (
!this.isInstallAllowedByPolicy(
aInstallingPrincipal,
aInstall,
false /* explicit */
)
) {
aInstall.cancel();
this.installNotifyObservers(
"addon-install-policy-blocked",
topBrowser,
aInstallingPrincipal.URI,
aInstall
);
return;
} else if (
// Block the install request if the triggering frame does have any cross-origin
// ancestor.
aDetails?.hasCrossOriginAncestor ||
// Block the install if triggered by a null principal.
aInstallingPrincipal.isNullPrincipal ||
(aBrowser &&
(!aBrowser.contentPrincipal ||
// When we attempt to handle an XPI load immediately after a
// process switch, the DocShell it's being loaded into will have
// a null principal, since it won't have been initialized yet.
// Allowing installs in this case is relatively safe, since
// there isn't much to gain by spoofing an install request from
// a null principal in any case. This exception can be removed
// once content handlers are triggered by DocumentChannel in the
// parent process.
!(
aBrowser.contentPrincipal.isNullPrincipal ||
aInstallingPrincipal.subsumes(aBrowser.contentPrincipal)
)))
) {
aInstall.cancel();
this.installNotifyObservers(
"addon-install-origin-blocked",
topBrowser,
aInstallingPrincipal.URI,
aInstall
);
return;
}
if (aBrowser) {
// The install may start now depending on the web install listener,
// listen for the browser navigating to a new origin and cancel the
// install in that case.
new BrowserListener(aBrowser, aInstallingPrincipal, aInstall);
}
let startInstall = source => {
AddonManagerInternal.setupPromptHandler(
aBrowser,
aInstallingPrincipal.URI,
aInstall,
true,
source
);
AddonManagerInternal.startInstall(
aBrowser,
aInstallingPrincipal.URI,
aInstall
);
};
let installAllowed = this.isInstallAllowed(
aMimetype,
aInstallingPrincipal
);
let installPerm = Services.perms.testPermissionFromPrincipal(
aInstallingPrincipal,
"install"
);
if (installAllowed) {
startInstall("AMO");
} else if (installPerm === Ci.nsIPermissionManager.DENY_ACTION) {
// Block without prompt
aInstall.cancel();
this.installNotifyObservers(
"addon-install-blocked-silent",
topBrowser,
aInstallingPrincipal.URI,
aInstall
);
} else if (!lazy.WEBEXT_POSTDOWNLOAD_THIRD_PARTY) {
// Block with prompt
this.installNotifyObservers(
"addon-install-blocked",
topBrowser,
aInstallingPrincipal.URI,
aInstall,
() => startInstall("other"),
() => aInstall.cancel()
);
} else {
// We download the addon and validate whether a 3rd party
// install prompt should be shown using e.g. recommended
// state and install_origins.
logger.info(`Addon download before validation.`);
startInstall("other");
}
} catch (e) {
// In the event that the weblistener throws during instantiation or when
// calling onWebInstallBlocked or onWebInstallRequested the
// install should get cancelled.
logger.warn("Failure calling web installer", e);
aInstall.cancel();
}
},
/**
* Starts installation of an AddonInstall created from add-ons manager
* front-end code (e.g., drag-and-drop of xpis or "Install Add-on from File"
*
* @param browser
* The browser element where the installation was initiated
* @param uri
* The URI of the page where the installation was initiated
* @param install
* The AddonInstall to be installed
*/
installAddonFromAOM(browser, uri, install) {
if (!this.isInstallAllowedByPolicy(null, install)) {
install.cancel();
this.installNotifyObservers(
"addon-install-policy-blocked",
browser,
install.sourceURI,
install
);
return;
}
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
AddonManagerInternal.setupPromptHandler(
browser,
uri,
install,
true,
"local"
);
AddonManagerInternal.startInstall(browser, uri, install);
},
/**
* Adds a new InstallListener if the listener is not already registered.
*
* @param aListener
* The InstallListener to add
*/
addInstallListener(aListener) {
if (!aListener || typeof aListener != "object") {
throw Components.Exception(
"aListener must be a InstallListener object",
Cr.NS_ERROR_INVALID_ARG
);
}
this.installListeners.add(aListener);
},
/**
* Removes an InstallListener if the listener is registered.
*
* @param aListener
* The InstallListener to remove
*/
removeInstallListener(aListener) {
if (!aListener || typeof aListener != "object") {
throw Components.Exception(
"aListener must be a InstallListener object",
Cr.NS_ERROR_INVALID_ARG
);
}
this.installListeners.delete(aListener);
},
/**
* Adds new or overrides existing UpgradeListener.
*
* @param aInstanceID
* The instance ID of an addon to register a listener for.
* @param aCallback
* The callback to invoke when updates are available for this addon.
* @throws if there is no addon matching the instanceID
*/
addUpgradeListener(aInstanceID, aCallback) {
if (!aInstanceID || typeof aInstanceID != "symbol") {
throw Components.Exception(
"aInstanceID must be a symbol",
Cr.NS_ERROR_INVALID_ARG
);
}
if (!aCallback || typeof aCallback != "function") {
throw Components.Exception(
"aCallback must be a function",
Cr.NS_ERROR_INVALID_ARG
);
}
let addonId = this.syncGetAddonIDByInstanceID(aInstanceID);
if (!addonId) {
throw Error(`No addon matching instanceID: ${String(aInstanceID)}`);
}
logger.debug(`Registering upgrade listener for ${addonId}`);
this.upgradeListeners.set(addonId, aCallback);
},
/**
* Removes an UpgradeListener if the listener is registered.
*
* @param aInstanceID
* The instance ID of the addon to remove
*/
removeUpgradeListener(aInstanceID) {
if (!aInstanceID || typeof aInstanceID != "symbol") {
throw Components.Exception(
"aInstanceID must be a symbol",
Cr.NS_ERROR_INVALID_ARG
);
}
let addonId = this.syncGetAddonIDByInstanceID(aInstanceID);
if (!addonId) {
throw Error(`No addon for instanceID: ${aInstanceID}`);
}
if (this.upgradeListeners.has(addonId)) {
this.upgradeListeners.delete(addonId);
} else {
throw Error(`No upgrade listener registered for addon ID: ${addonId}`);
}
},
addExternalExtensionLoader(loader) {
this.externalExtensionLoaders.set(loader.name, loader);
},
/**
* Installs a temporary add-on from a local file or directory.
*
* @param aFile
* An nsIFile for the file or directory of the add-on to be
* temporarily installed.
* @returns a Promise that rejects if the add-on is not a valid restartless
* add-on or if the same ID is already temporarily installed.
*/
installTemporaryAddon(aFile) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!(aFile instanceof Ci.nsIFile)) {
throw Components.Exception(
"aFile must be a nsIFile",
Cr.NS_ERROR_INVALID_ARG
);
}
return AddonManagerInternal._getProviderByName(
"XPIProvider"
).installTemporaryAddon(aFile);
},
/**
* Installs an add-on from a built-in location
* (ie a resource: url referencing assets shipped with the application)
*
* @param aBase
* A string containing the base URL. Must be a resource: URL.
* @returns a Promise that resolves when the addon is installed.
*/
installBuiltinAddon(aBase) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
return AddonManagerInternal._getProviderByName(
"XPIProvider"
).installBuiltinAddon(aBase);
},
/**
* Like `installBuiltinAddon`, but only installs the addon at `aBase`
* if an existing built-in addon with the ID `aID` and version doesn't
* already exist.
*
* @param {string} aID
* The ID of the add-on being registered.
* @param {string} aVersion
* The version of the add-on being registered.
* @param {string} aBase
* A string containing the base URL. Must be a resource: URL.
* @returns a Promise that resolves when the addon is installed.
*/
maybeInstallBuiltinAddon(aID, aVersion, aBase) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
return AddonManagerInternal._getProviderByName(
"XPIProvider"
).maybeInstallBuiltinAddon(aID, aVersion, aBase);
},
syncGetAddonIDByInstanceID(aInstanceID) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aInstanceID || typeof aInstanceID != "symbol") {
throw Components.Exception(
"aInstanceID must be a Symbol()",
Cr.NS_ERROR_INVALID_ARG
);
}
return AddonManagerInternal._getProviderByName(
"XPIProvider"
).getAddonIDByInstanceID(aInstanceID);
},
/**
* Gets an icon from the icon set provided by the add-on
* that is closest to the specified size.
*
* The optional window parameter will be used to determine
* the screen resolution and select a more appropriate icon.
* Calling this method with 48px on retina screens will try to
* match an icon of size 96px.
*
* @param aAddon
* An addon object, meaning:
* An object with either an icons property that is a key-value list
* of icon size and icon URL, or an object having an iconURL property.
* @param aSize
* Ideal icon size in pixels
* @param aWindow
* Optional window object for determining the correct scale.
* @return {String} The absolute URL of the icon or null if the addon doesn't have icons
*/
getPreferredIconURL(aAddon, aSize, aWindow = undefined) {
if (aWindow && aWindow.devicePixelRatio) {
aSize *= aWindow.devicePixelRatio;
}
let icons = aAddon.icons;
// certain addon-types only have iconURLs
if (!icons) {
icons = {};
if (aAddon.iconURL) {
icons[32] = aAddon.iconURL;
icons[48] = aAddon.iconURL;
}
}
// quick return if the exact size was found
if (icons[aSize]) {
return icons[aSize];
}
let bestSize = null;
for (let size of Object.keys(icons)) {
if (!INTEGER.test(size)) {
throw Components.Exception(
"Invalid icon size, must be an integer",
Cr.NS_ERROR_ILLEGAL_VALUE
);
}
size = parseInt(size, 10);
if (!bestSize) {
bestSize = size;
continue;
}
if (size > aSize && bestSize > aSize) {
// If both best size and current size are larger than the wanted size then choose
// the one closest to the wanted size
bestSize = Math.min(bestSize, size);
} else {
// Otherwise choose the largest of the two so we'll prefer sizes as close to below aSize
// or above aSize
bestSize = Math.max(bestSize, size);
}
}
return icons[bestSize] || null;
},
/**
* Asynchronously gets an add-on with a specific ID.
*
* @type {function}
* @param {string} aID
* The ID of the add-on to retrieve
* @returns {Promise} resolves with the found Addon or null if no such add-on exists. Never rejects.
* @throws if the aID argument is not specified
*/
getAddonByID(aID) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aID || typeof aID != "string") {
throw Components.Exception(
"aID must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
let promises = Array.from(this.providers, p =>
promiseCallProvider(p, "getAddonByID", aID)
);
return Promise.all(promises).then(aAddons => {
return aAddons.find(a => !!a) || null;
});
},
/**
* Asynchronously get an add-on with a specific Sync GUID.
*
* @param aGUID
* String GUID of add-on to retrieve
* @throws if the aGUID argument is not specified
*/
getAddonBySyncGUID(aGUID) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!aGUID || typeof aGUID != "string") {
throw Components.Exception(
"aGUID must be a non-empty string",
Cr.NS_ERROR_INVALID_ARG
);
}
return (async () => {
for (let provider of this.providers) {
let addon = await promiseCallProvider(
provider,
"getAddonBySyncGUID",
aGUID
);
if (addon) {
return addon;
}
}
return null;
})();
},
/**
* Asynchronously gets an array of add-ons.
*
* @param aIDs
* The array of IDs to retrieve
* @return {Promise}
* @resolves The array of found add-ons.
* @rejects Never
* @throws if the aIDs argument is not specified
*/
getAddonsByIDs(aIDs) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!Array.isArray(aIDs)) {
throw Components.Exception(
"aIDs must be an array",
Cr.NS_ERROR_INVALID_ARG
);
}
let promises = aIDs.map(a => AddonManagerInternal.getAddonByID(a));
return Promise.all(promises);
},
/**
* Asynchronously gets add-ons of specific types.
*
* @param aTypes
* An optional array of types to retrieve. Each type is a string name
*/
getAddonsByTypes(aTypes) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (aTypes && !Array.isArray(aTypes)) {
throw Components.Exception(
"aTypes must be an array or null",
Cr.NS_ERROR_INVALID_ARG
);
}
return (async () => {
let addons = [];
for (let provider of this.providers) {
let providerAddons = await promiseCallProvider(
provider,
"getAddonsByTypes",
aTypes
);
if (providerAddons) {
addons.push(...providerAddons);
}
}
return addons;
})();
},
/**
* Gets active add-ons of specific types.
*
* This is similar to getAddonsByTypes() but it may return a limited
* amount of information about only active addons. Consequently, it
* can be implemented by providers using only immediately available
* data as opposed to getAddonsByTypes which may require I/O).
*
* @param aTypes
* An optional array of types to retrieve. Each type is a string name
*
* @resolve {addons: Array, fullData: bool}
* fullData is true if addons contains all the data we have on those
* addons. It is false if addons only contains partial data.
*/
async getActiveAddons(aTypes) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (aTypes && !Array.isArray(aTypes)) {
throw Components.Exception(
"aTypes must be an array or null",
Cr.NS_ERROR_INVALID_ARG
);
}
let addons = [],
fullData = true;
for (let provider of this.providers) {
let providerAddons, providerFullData;
if ("getActiveAddons" in provider) {
({ addons: providerAddons, fullData: providerFullData } =
await callProvider(provider, "getActiveAddons", null, aTypes));
} else {
providerAddons = await promiseCallProvider(
provider,
"getAddonsByTypes",
aTypes
);
providerAddons = providerAddons.filter(a => a.isActive);
providerFullData = true;
}
if (providerAddons) {
addons.push(...providerAddons);
fullData = fullData && providerFullData;
}
}
return { addons, fullData };
},
/**
* Asynchronously gets all installed add-ons.
*/
getAllAddons() {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
return this.getAddonsByTypes(null);
},
/**
* Adds a new AddonManagerListener if the listener is not already registered.
*
* @param {AddonManagerListener} aListener
* The listener to add
*/
addManagerListener(aListener) {
if (!aListener || typeof aListener != "object") {
throw Components.Exception(
"aListener must be an AddonManagerListener object",
Cr.NS_ERROR_INVALID_ARG
);
}
this.managerListeners.add(aListener);
},
/**
* Removes an AddonManagerListener if the listener is registered.
*
* @param {AddonManagerListener} aListener
* The listener to remove
*/
removeManagerListener(aListener) {
if (!aListener || typeof aListener != "object") {
throw Components.Exception(
"aListener must be an AddonManagerListener object",
Cr.NS_ERROR_INVALID_ARG
);
}
this.managerListeners.delete(aListener);
},
/**
* Adds a new AddonListener if the listener is not already registered.
*
* @param {AddonManagerListener} aListener
* The AddonListener to add.
*/
addAddonListener(aListener) {
if (!aListener || typeof aListener != "object") {
throw Components.Exception(
"aListener must be an AddonListener object",
Cr.NS_ERROR_INVALID_ARG
);
}
this.addonListeners.add(aListener);
},
/**
* Removes an AddonListener if the listener is registered.
*
* @param {object} aListener
* The AddonListener to remove
*/
removeAddonListener(aListener) {
if (!aListener || typeof aListener != "object") {
throw Components.Exception(
"aListener must be an AddonListener object",
Cr.NS_ERROR_INVALID_ARG
);
}
this.addonListeners.delete(aListener);
},
/**
* @param {string} addonType
* @returns {boolean}
* Whether there is a provider that provides the given addon type.
*/
hasAddonType(addonType) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
for (let addonTypes of this.typesByProvider.values()) {
if (addonTypes.has(addonType)) {
return true;
}
}
return false;
},
get autoUpdateDefault() {
return gAutoUpdateDefault;
},
set autoUpdateDefault(aValue) {
aValue = !!aValue;
if (aValue != gAutoUpdateDefault) {
Services.prefs.setBoolPref(PREF_EM_AUTOUPDATE_DEFAULT, aValue);
}
},
get checkCompatibility() {
return gCheckCompatibility;
},
set checkCompatibility(aValue) {
aValue = !!aValue;
if (aValue != gCheckCompatibility) {
if (!aValue) {
Services.prefs.setBoolPref(PREF_EM_CHECK_COMPATIBILITY, false);
} else {
Services.prefs.clearUserPref(PREF_EM_CHECK_COMPATIBILITY);
}
}
},
get strictCompatibility() {
return gStrictCompatibility;
},
set strictCompatibility(aValue) {
aValue = !!aValue;
if (aValue != gStrictCompatibility) {
Services.prefs.setBoolPref(PREF_EM_STRICT_COMPATIBILITY, aValue);
}
},
get checkUpdateSecurityDefault() {
return gCheckUpdateSecurityDefault;
},
get checkUpdateSecurity() {
return gCheckUpdateSecurity;
},
set checkUpdateSecurity(aValue) {
aValue = !!aValue;
if (aValue != gCheckUpdateSecurity) {
if (aValue != gCheckUpdateSecurityDefault) {
Services.prefs.setBoolPref(PREF_EM_CHECK_UPDATE_SECURITY, aValue);
} else {
Services.prefs.clearUserPref(PREF_EM_CHECK_UPDATE_SECURITY);
}
}
},
get updateEnabled() {
return gUpdateEnabled;
},
set updateEnabled(aValue) {
aValue = !!aValue;
if (aValue != gUpdateEnabled) {
Services.prefs.setBoolPref(PREF_EM_UPDATE_ENABLED, aValue);
}
},
/**
* Verify whether we need to show the 3rd party install prompt.
*
* Bypass the third party install prompt if this is an install:
* - is an install from a recognized source
* - is a an addon that can bypass the panel, such as a recommended addon
*
* @param {browser} browser browser user is installing from
* @param {nsIURI} url URI for the principal of the installing source
* @param {AddonInstallWrapper} install
* @param {Object} info information such as addon wrapper
* @param {AddonWrapper} info.addon
* @param {string} source simplified string describing source of install and is
* generated based on the installing principal and checking
* against site permissions and enterprise policy.
* It may be one of "AMO", "local" or "other".
* @returns {Promise} Rejected when the installation should not proceed.
*/
_verifyThirdPartyInstall(browser, url, install, info, source) {
// If we are not post-download processing, this panel was already shown.
// Otherwise, if this is from AMO or local, bypass the prompt.
if (
!lazy.WEBEXT_POSTDOWNLOAD_THIRD_PARTY ||
["AMO", "local"].includes(source)
) {
return Promise.resolve();
}
// verify both the installing source and the xpi url are allowed.
if (
!info.addon.validInstallOrigins({
installFrom: url,
source: install.sourceURI,
})
) {
install.error = AddonManager.ERROR_INVALID_DOMAIN;
return Promise.reject();
}
// Some addons such as recommended addons do not result in this prompt.
if (info.addon.canBypassThirdParyInstallPrompt) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
this.installNotifyObservers(
"addon-install-blocked",
browser,
url,
install,
resolve,
reject
);
});
},
setupPromptHandler(browser, url, install, requireConfirm, source) {
install.promptHandler = info =>
new Promise((resolve, reject) => {
this._verifyThirdPartyInstall(browser, url, install, info, source)
.then(() => {
// All installs end up in this callback when the add-on is available
// for installation. There are numerous different things that can
// happen from here though. For webextensions, if the application
// implements webextension permission prompts, those always take
// precedence.
// If this add-on is not a webextension or if the application does not
// implement permission prompts, no confirmation is displayed for
// installs created from about:addons (in which case requireConfirm
// is false).
// In the remaining cases, a confirmation prompt is displayed but the
// application may override it either by implementing the
// "@mozilla.org/addons/web-install-prompt;1" contract or by setting
// the customConfirmationUI preference and responding to the
// "addon-install-confirmation" notification. If the application
// does not implement its own prompt, use the built-in xul dialog.
if (info.addon.userPermissions) {
let subject = {
wrappedJSObject: {
target: browser,
info: Object.assign({ resolve, reject, source }, info),
},
};
subject.wrappedJSObject.info.permissions =
info.addon.userPermissions;
Services.obs.notifyObservers(
subject,
"webextension-permission-prompt"
);
} else if (info.addon.sitePermissions) {
// Handle prompting for DOM permissions in SitePermission addons.
let { sitePermissions, siteOrigin } = info.addon;
let subject = {
wrappedJSObject: {
target: browser,
info: Object.assign(
{ resolve, reject, source, sitePermissions, siteOrigin },
info
),
},
};
Services.obs.notifyObservers(
subject,
"webextension-permission-prompt"
);
} else if (requireConfirm) {
// The methods below all want to call the install() or cancel()
// method on the provided AddonInstall object to either accept
// or reject the confirmation. Fit that into our promise-based
// control flow by wrapping the install object. However,
// xpInstallConfirm.xul matches the install object it is passed
// with the argument passed to an InstallListener, so give it
// access to the underlying object through the .wrapped property.
let proxy = new Proxy(install, {
get(target, property) {
if (property == "install") {
return resolve;
} else if (property == "cancel") {
return reject;
} else if (property == "wrapped") {
return target;
}
let result = target[property];
return typeof result == "function"
? result.bind(target)
: result;
},
});
// Check for a custom installation prompt that may be provided by the
// applicaton
if ("@mozilla.org/addons/web-install-prompt;1" in Cc) {
try {
let prompt = Cc[
"@mozilla.org/addons/web-install-prompt;1"
].getService(Ci.amIWebInstallPrompt);
prompt.confirm(browser, url, [proxy]);
return;
} catch (e) {}
}
this.installNotifyObservers(
"addon-install-confirmation",
browser,
url,
proxy
);
} else {
resolve();
}
})
.catch(e => {
// Error is undefined if the promise was rejected.
if (e) {
Cu.reportError(`Install prompt handler error: ${e}`);
}
reject();
});
});
},
webAPI: {
// installs maps integer ids to AddonInstall instances.
installs: new Map(),
nextInstall: 0,
sendEvent: null,
setEventHandler(fn) {
this.sendEvent = fn;
},
async getAddonByID(target, id) {
return webAPIForAddon(await AddonManager.getAddonByID(id));
},
// helper to copy (and convert) the properties we care about
copyProps(install, obj) {
obj.state = AddonManager.stateToString(install.state);
obj.error = AddonManager.errorToString(install.error);
obj.progress = install.progress;
obj.maxProgress = install.maxProgress;
},
forgetInstall(id) {
let info = this.installs.get(id);
if (!info) {
throw new Error(`forgetInstall cannot find ${id}`);
}
info.install.removeListener(info.listener);
this.installs.delete(id);
},
createInstall(target, options) {
// Throw an appropriate error if the given URL is not valid
// as an installation source. Return silently if it is okay.
function checkInstallUri(uri) {
if (Services.policies && !Services.policies.allowedInstallSource(uri)) {
// eslint-disable-next-line no-throw-literal
return {
success: false,
code: "addon-install-policy-blocked",
message: `Install from ${uri.spec} not permitted by policy`,
};
}
if (WEBAPI_INSTALL_HOSTS.includes(uri.host)) {
return { success: true };
}
if (
Services.prefs.getBoolPref(PREF_WEBAPI_TESTING, false) &&
WEBAPI_TEST_INSTALL_HOSTS.includes(uri.host)
) {
return { success: true };
}
// eslint-disable-next-line no-throw-literal
return {
success: false,
code: "addon-install-webapi-blocked",
message: `Install from ${uri.host} not permitted`,
};
}
const makeListener = (id, mm) => {
const events = [
"onDownloadStarted",
"onDownloadProgress",
"onDownloadEnded",
"onDownloadCancelled",
"onDownloadFailed",
"onInstallStarted",
"onInstallEnded",
"onInstallCancelled",
"onInstallFailed",
];
let listener = {};
let installPromise = new Promise((resolve, reject) => {
events.forEach(event => {
listener[event] = (install, addon) => {
let data = { event, id };
AddonManager.webAPI.copyProps(install, data);
this.sendEvent(mm, data);
if (event == "onInstallEnded") {
resolve(addon);
} else if (
event == "onDownloadFailed" ||
event == "onInstallFailed"
) {
reject({ message: "install failed" });
} else if (
event == "onDownloadCancelled" ||
event == "onInstallCancelled"
) {
reject({ message: "install cancelled" });
} else if (event == "onDownloadEnded") {
if (install.addon.appDisabled) {
// App disabled items are not compatible and so fail to install
install.cancel();
AddonManagerInternal.installNotifyObservers(
"addon-install-failed",
target,
Services.io.newURI(options.url),
install
);
}
}
};
});
});
// We create the promise here since this is where we're setting
// up the InstallListener, but if the install is never started,
// no handlers will be attached so make sure we terminate errors.
installPromise.catch(() => {});
return { listener, installPromise };
};
let uri;
try {
uri = Services.io.newURI(options.url);
const { success, code, message } = checkInstallUri(uri);
if (!success) {
let info = {
wrappedJSObject: {
browser: target,
originatingURI: uri,
installs: [],
},
};
Cu.reportError(`${code}: ${message}`);
Services.obs.notifyObservers(info, code);
return Promise.reject({ code, message });
}
} catch (err) {
// Reject Components.Exception errors (e.g. NS_ERROR_MALFORMED_URI) as is.
if (err instanceof Components.Exception) {
return Promise.reject({ message: err.message });
}
return Promise.reject({
message: "Install Failed on unexpected error",
});
}
return AddonManagerInternal.getInstallForURL(options.url, {
browser: target,
triggeringPrincipal: options.triggeringPrincipal,
hash: options.hash,
telemetryInfo: {
source: AddonManager.getInstallSourceFromHost(options.sourceHost),
sourceURL: options.sourceURL,
method: "amWebAPI",
},
}).then(install => {
let requireConfirm = true;
if (
target.contentDocument &&
target.contentDocument.nodePrincipal.isSystemPrincipal
) {
requireConfirm = false;
}
AddonManagerInternal.setupPromptHandler(
target,
null,
install,
requireConfirm,
"AMO"
);
let id = this.nextInstall++;
let { listener, installPromise } = makeListener(
id,
target.messageManager
);
install.addListener(listener);
this.installs.set(id, {
install,
target,
listener,
installPromise,
messageManager: target.messageManager,
});
let result = { id };
this.copyProps(install, result);
return result;
});
},
async addonUninstall(target, id) {
let addon = await AddonManager.getAddonByID(id);
if (!addon) {
return false;
}
if (!(addon.permissions & AddonManager.PERM_CAN_UNINSTALL)) {
return Promise.reject({ message: "Addon cannot be uninstalled" });
}
try {
addon.uninstall();
return true;
} catch (err) {
Cu.reportError(err);
return false;
}
},
async addonSetEnabled(target, id, value) {
let addon = await AddonManager.getAddonByID(id);
if (!addon) {
throw new Error(`No such addon ${id}`);
}
if (value) {
await addon.enable();
} else {
await addon.disable();
}
},
async addonInstallDoInstall(target, id) {
let state = this.installs.get(id);
if (!state) {
throw new Error(`invalid id ${id}`);
}
let addon = await state.install.install();
if (addon.type == "theme" && !addon.appDisabled) {
await addon.enable();
}
await new Promise(resolve => {
let subject = {
wrappedJSObject: { target, addon, callback: resolve },
};
Services.obs.notifyObservers(subject, "webextension-install-notify");
});
},
addonInstallCancel(target, id) {
let state = this.installs.get(id);
if (!state) {
return Promise.reject(`invalid id ${id}`);
}
return Promise.resolve(state.install.cancel());
},
clearInstalls(ids) {
for (let id of ids) {
this.forgetInstall(id);
}
},
clearInstallsFrom(mm) {
for (let [id, info] of this.installs) {
if (info.messageManager == mm) {
this.forgetInstall(id);
}
}
},
async addonReportAbuse(target, id) {
if (!Services.prefs.getBoolPref(PREF_AMO_ABUSEREPORT, false)) {
return Promise.reject({
message: "amWebAPI reportAbuse not supported",
});
}
let existingDialog = lazy.AbuseReporter.getOpenDialog();
if (existingDialog) {
existingDialog.close();
}
const dialog = await lazy.AbuseReporter.openDialog(
id,
"amo",
target
).catch(err => {
Cu.reportError(err);
return Promise.reject({
message: "Error creating abuse report",
});
});
return dialog.promiseReport.then(
async report => {
if (!report) {
return false;
}
await report.submit().catch(err => {
Cu.reportError(err);
return Promise.reject({
message: "Error submitting abuse report",
});
});
return true;
},
err => {
Cu.reportError(err);
dialog.close();
return Promise.reject({
message: "Error creating abuse report",
});
}
);
},
},
};
/**
* Should not be used outside of core Mozilla code. This is a private API for
* the startup and platform integration code to use. Refer to the methods on
* AddonManagerInternal for documentation however note that these methods are
* subject to change at any time.
*/
export var AddonManagerPrivate = {
startup() {
AddonManagerInternal.startup();
},
addonIsActive(addonId) {
return AddonManagerInternal._getProviderByName("XPIProvider").addonIsActive(
addonId
);
},
/**
* Gets an array of add-ons which were side-loaded prior to the last
* startup, and are currently disabled.
*
* @returns {Promise<Array<Addon>>}
*/
getNewSideloads() {
return AddonManagerInternal._getProviderByName(
"XPIProvider"
).getNewSideloads();
},
get browserUpdated() {
return gBrowserUpdated;
},
registerProvider(aProvider, aTypes) {
AddonManagerInternal.registerProvider(aProvider, aTypes);
},
unregisterProvider(aProvider) {
AddonManagerInternal.unregisterProvider(aProvider);
},
/**
* Get a list of addon types that was passed to registerProvider for the
* provider with the given name.
*
* @param {string} aProviderName
* @returns {Array<string>}
*/
getAddonTypesByProvider(aProviderName) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
for (let [provider, addonTypes] of AddonManagerInternal.typesByProvider) {
if (providerName(provider) === aProviderName) {
// Return an array because methods such as getAddonsByTypes expect
// aTypes to be an array.
return Array.from(addonTypes);
}
}
throw Components.Exception(
`No addonTypes found for provider: ${aProviderName}`,
Cr.NS_ERROR_INVALID_ARG
);
},
markProviderSafe(aProvider) {
AddonManagerInternal.markProviderSafe(aProvider);
},
backgroundUpdateCheck() {
return AddonManagerInternal.backgroundUpdateCheck();
},
backgroundUpdateTimerHandler() {
// Don't return the promise here, since the caller doesn't care.
AddonManagerInternal.backgroundUpdateCheck();
},
addStartupChange(aType, aID) {
AddonManagerInternal.addStartupChange(aType, aID);
},
removeStartupChange(aType, aID) {
AddonManagerInternal.removeStartupChange(aType, aID);
},
notifyAddonChanged(aID, aType, aPendingRestart) {
return AddonManagerInternal.notifyAddonChanged(aID, aType, aPendingRestart);
},
updateAddonAppDisabledStates() {
AddonManagerInternal.updateAddonAppDisabledStates();
},
updateAddonRepositoryData() {
return AddonManagerInternal.updateAddonRepositoryData();
},
callInstallListeners(...aArgs) {
return AddonManagerInternal.callInstallListeners.apply(
AddonManagerInternal,
aArgs
);
},
callAddonListeners(...aArgs) {
AddonManagerInternal.callAddonListeners.apply(AddonManagerInternal, aArgs);
},
AddonAuthor,
AddonScreenshot,
get BOOTSTRAP_REASONS() {
// BOOTSTRAP_REASONS is a set of constants, and may be accessed before the
// provider has fully been started.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1760146#c1
return gXPIProvider.BOOTSTRAP_REASONS;
},
setAddonStartupData(addonId, startupData) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
// TODO bug 1761079: Ensure that XPIProvider is available before calling it.
gXPIProvider.setStartupData(addonId, startupData);
},
unregisterDictionaries(aDicts) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
// TODO bug 1761093: Use _getProviderByName instead of gXPIProvider.
gXPIProvider.unregisterDictionaries(aDicts);
},
recordTimestamp(name, value) {
AddonManagerInternal.recordTimestamp(name, value);
},
_simpleMeasures: {},
recordSimpleMeasure(name, value) {
this._simpleMeasures[name] = value;
},
recordException(aModule, aContext, aException) {
let report = {
module: aModule,
context: aContext,
};
if (typeof aException == "number") {
report.message = Components.Exception("", aException).name;
} else {
report.message = aException.toString();
if (aException.fileName) {
report.file = aException.fileName;
report.line = aException.lineNumber;
}
}
this._simpleMeasures.exception = report;
},
getSimpleMeasures() {
return this._simpleMeasures;
},
getTelemetryDetails() {
return AddonManagerInternal.telemetryDetails;
},
setTelemetryDetails(aProvider, aDetails) {
AddonManagerInternal.telemetryDetails[aProvider] = aDetails;
},
// Start a timer, record a simple measure of the time interval when
// timer.done() is called
simpleTimer(aName) {
let startTime = Cu.now();
return {
done: () =>
this.recordSimpleMeasure(aName, Math.round(Cu.now() - startTime)),
};
},
async recordTiming(name, task) {
let timer = this.simpleTimer(name);
try {
return await task();
} finally {
timer.done();
}
},
/**
* Helper to call update listeners when no update is available.
*
* This can be used as an implementation for Addon.findUpdates() when
* no update mechanism is available.
*/
callNoUpdateListeners(addon, listener, reason, appVersion, platformVersion) {
if ("onNoCompatibilityUpdateAvailable" in listener) {
safeCall(listener.onNoCompatibilityUpdateAvailable.bind(listener), addon);
}
if ("onNoUpdateAvailable" in listener) {
safeCall(listener.onNoUpdateAvailable.bind(listener), addon);
}
if ("onUpdateFinished" in listener) {
safeCall(listener.onUpdateFinished.bind(listener), addon);
}
},
get webExtensionsMinPlatformVersion() {
return gWebExtensionsMinPlatformVersion;
},
hasUpgradeListener(aId) {
return AddonManagerInternal.upgradeListeners.has(aId);
},
getUpgradeListener(aId) {
return AddonManagerInternal.upgradeListeners.get(aId);
},
get externalExtensionLoaders() {
return AddonManagerInternal.externalExtensionLoaders;
},
/**
* Predicate that returns true if we think the given extension ID
* might have been generated by XPIProvider.
*/
isTemporaryInstallID(extensionId) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
if (!extensionId || typeof extensionId != "string") {
throw Components.Exception(
"extensionId must be a string",
Cr.NS_ERROR_INVALID_ARG
);
}
return AddonManagerInternal._getProviderByName(
"XPIProvider"
).isTemporaryInstallID(extensionId);
},
isDBLoaded() {
let provider = AddonManagerInternal._getProviderByName("XPIProvider");
return provider ? provider.isDBLoaded : false;
},
get databaseReady() {
let provider = AddonManagerInternal._getProviderByName("XPIProvider");
return provider ? provider.databaseReady : new Promise(() => {});
},
/**
* Async shutdown barrier which blocks the completion of add-on
* manager shutdown. This should generally only be used by add-on
* providers (i.e., XPIProvider) to complete their final shutdown
* tasks.
*/
get finalShutdown() {
return gFinalShutdownBarrier.client;
},
// Used by tests to call repo shutdown.
overrideAddonRepository(mockRepo) {
lazy.AddonRepository = mockRepo;
},
// Used by tests to shut down AddonManager.
overrideAsyncShutdown(mockAsyncShutdown) {
AsyncShutdown = mockAsyncShutdown;
},
};
/**
* This is the public API that UI and developers should be calling. All methods
* just forward to AddonManagerInternal.
* @class
*/
export var AddonManager = {
// Map used to convert the known install source hostnames into the value to set into the
// telemetry events.
_installHostSource: new Map([
["addons.mozilla.org", "amo"],
["discovery.addons.mozilla.org", "disco"],
]),
// Constants for the AddonInstall.state property
// These will show up as AddonManager.STATE_* (eg, STATE_AVAILABLE)
_states: new Map([
// The install is available for download.
["STATE_AVAILABLE", 0],
// The install is being downloaded.
["STATE_DOWNLOADING", 1],
// The install is checking the update for compatibility information.
["STATE_CHECKING_UPDATE", 2],
// The install is downloaded and ready to install.
["STATE_DOWNLOADED", 3],
// The download failed.
["STATE_DOWNLOAD_FAILED", 4],
// The install may not proceed until the user accepts a prompt
["STATE_AWAITING_PROMPT", 5],
// Any prompts are done
["STATE_PROMPTS_DONE", 6],
// The install has been postponed.
["STATE_POSTPONED", 7],
// The install is ready to be applied.
["STATE_READY", 8],
// The add-on is being installed.
["STATE_INSTALLING", 9],
// The add-on has been installed.
["STATE_INSTALLED", 10],
// The install failed.
["STATE_INSTALL_FAILED", 11],
// The install has been cancelled.
["STATE_CANCELLED", 12],
]),
// Constants representing different types of errors while downloading an
// add-on as a preparation for installation.
// These will show up as AddonManager.ERROR_* (eg, ERROR_NETWORK_FAILURE)
// The _errors codes are translated to text for a panel in browser-addons.js.
// The localized messages are located in extensionsUI.ftl.
// Errors with the "Updates only:" prefix are not translated
// because the error is dumped to the console instead of a panel.
_errors: new Map([
// The download failed due to network problems.
["ERROR_NETWORK_FAILURE", -1],
// The downloaded file did not match the provided hash.
["ERROR_INCORRECT_HASH", -2],
// The downloaded file seems to be corrupted in some way.
["ERROR_CORRUPT_FILE", -3],
// An error occurred trying to write to the filesystem.
["ERROR_FILE_ACCESS", -4],
// The add-on must be signed and isn't.
["ERROR_SIGNEDSTATE_REQUIRED", -5],
// Updates only: The downloaded add-on had a different type than expected.
["ERROR_UNEXPECTED_ADDON_TYPE", -6],
// Updates only: The addon did not have the expected ID.
["ERROR_INCORRECT_ID", -7],
// The addon install_origins does not list the 3rd party domain.
["ERROR_INVALID_DOMAIN", -8],
// Updates only: The downloaded add-on had a different version than expected.
["ERROR_UNEXPECTED_ADDON_VERSION", -9],
// The add-on is blocklisted.
["ERROR_BLOCKLISTED", -10],
// The add-on is incompatible (w.r.t. the compatibility range).
["ERROR_INCOMPATIBLE", -11],
// The add-on type is not supported by the platform.
["ERROR_UNSUPPORTED_ADDON_TYPE", -12],
]),
// The update check timed out
ERROR_TIMEOUT: -1,
// There was an error while downloading the update information.
ERROR_DOWNLOAD_ERROR: -2,
// The update information was malformed in some way.
ERROR_PARSE_ERROR: -3,
// The update information was not in any known format.
ERROR_UNKNOWN_FORMAT: -4,
// The update information was not correctly signed or there was an SSL error.
ERROR_SECURITY_ERROR: -5,
// The update was cancelled
ERROR_CANCELLED: -6,
// These must be kept in sync with AddonUpdateChecker.
// No error was encountered.
UPDATE_STATUS_NO_ERROR: 0,
// The update check timed out
UPDATE_STATUS_TIMEOUT: -1,
// There was an error while downloading the update information.
UPDATE_STATUS_DOWNLOAD_ERROR: -2,
// The update information was malformed in some way.
UPDATE_STATUS_PARSE_ERROR: -3,
// The update information was not in any known format.
UPDATE_STATUS_UNKNOWN_FORMAT: -4,
// The update information was not correctly signed or there was an SSL error.
UPDATE_STATUS_SECURITY_ERROR: -5,
// The update was cancelled.
UPDATE_STATUS_CANCELLED: -6,
// Constants to indicate why an update check is being performed
// Update check has been requested by the user.
UPDATE_WHEN_USER_REQUESTED: 1,
// Update check is necessary to see if the Addon is compatibile with a new
// version of the application.
UPDATE_WHEN_NEW_APP_DETECTED: 2,
// Update check is necessary because a new application has been installed.
UPDATE_WHEN_NEW_APP_INSTALLED: 3,
// Update check is a regular background update check.
UPDATE_WHEN_PERIODIC_UPDATE: 16,
// Update check is needed to check an Addon that is being installed.
UPDATE_WHEN_ADDON_INSTALLED: 17,
// Constants for operations in Addon.pendingOperations
// Indicates that the Addon has no pending operations.
PENDING_NONE: 0,
// Indicates that the Addon will be enabled after the application restarts.
PENDING_ENABLE: 1,
// Indicates that the Addon will be disabled after the application restarts.
PENDING_DISABLE: 2,
// Indicates that the Addon will be uninstalled after the application restarts.
PENDING_UNINSTALL: 4,
// Indicates that the Addon will be installed after the application restarts.
PENDING_INSTALL: 8,
PENDING_UPGRADE: 16,
// Constants for operations in Addon.operationsRequiringRestart
// Indicates that restart isn't required for any operation.
OP_NEEDS_RESTART_NONE: 0,
// Indicates that restart is required for enabling the addon.
OP_NEEDS_RESTART_ENABLE: 1,
// Indicates that restart is required for disabling the addon.
OP_NEEDS_RESTART_DISABLE: 2,
// Indicates that restart is required for uninstalling the addon.
OP_NEEDS_RESTART_UNINSTALL: 4,
// Indicates that restart is required for installing the addon.
OP_NEEDS_RESTART_INSTALL: 8,
// Constants for permissions in Addon.permissions.
// Indicates that the Addon can be uninstalled.
PERM_CAN_UNINSTALL: 1,
// Indicates that the Addon can be enabled by the user.
PERM_CAN_ENABLE: 2,
// Indicates that the Addon can be disabled by the user.
PERM_CAN_DISABLE: 4,
// Indicates that the Addon can be upgraded.
PERM_CAN_UPGRADE: 8,
// Indicates that the Addon can be set to be allowed/disallowed
// in private browsing windows.
PERM_CAN_CHANGE_PRIVATEBROWSING_ACCESS: 32,
// Indicates that internal APIs can uninstall the add-on, even if the
// front-end cannot.
PERM_API_CAN_UNINSTALL: 64,
// General descriptions of where items are installed.
// Installed in this profile.
SCOPE_PROFILE: 1,
// Installed for all of this user's profiles.
SCOPE_USER: 2,
// Installed and owned by the application.
SCOPE_APPLICATION: 4,
// Installed for all users of the computer.
SCOPE_SYSTEM: 8,
// Installed temporarily
SCOPE_TEMPORARY: 16,
// The combination of all scopes.
SCOPE_ALL: 31,
// Constants for Addon.applyBackgroundUpdates.
// Indicates that the Addon should not update automatically.
AUTOUPDATE_DISABLE: 0,
// Indicates that the Addon should update automatically only if
// that's the global default.
AUTOUPDATE_DEFAULT: 1,
// Indicates that the Addon should update automatically.
AUTOUPDATE_ENABLE: 2,
// Constants for how Addon options should be shown.
// Options will be displayed in a new tab, if possible
OPTIONS_TYPE_TAB: 3,
// Similar to OPTIONS_TYPE_INLINE, but rather than generating inline
// options from a specially-formatted XUL file, the contents of the
// file are simply displayed in an inline <browser> element.
OPTIONS_TYPE_INLINE_BROWSER: 5,
// Constants for displayed or hidden options notifications
// Options notification will be displayed
OPTIONS_NOTIFICATION_DISPLAYED: "addon-options-displayed",
// Options notification will be hidden
OPTIONS_NOTIFICATION_HIDDEN: "addon-options-hidden",
// Constants for getStartupChanges, addStartupChange and removeStartupChange
// Add-ons that were detected as installed during startup. Doesn't include
// add-ons that were pending installation the last time the application ran.
STARTUP_CHANGE_INSTALLED: "installed",
// Add-ons that were detected as changed during startup. This includes an
// add-on moving to a different location, changing version or just having
// been detected as possibly changed.
STARTUP_CHANGE_CHANGED: "changed",
// Add-ons that were detected as uninstalled during startup. Doesn't include
// add-ons that were pending uninstallation the last time the application ran.
STARTUP_CHANGE_UNINSTALLED: "uninstalled",
// Add-ons that were detected as disabled during startup, normally because of
// an application change making an add-on incompatible. Doesn't include
// add-ons that were pending being disabled the last time the application ran.
STARTUP_CHANGE_DISABLED: "disabled",
// Add-ons that were detected as enabled during startup, normally because of
// an application change making an add-on compatible. Doesn't include
// add-ons that were pending being enabled the last time the application ran.
STARTUP_CHANGE_ENABLED: "enabled",
// Constants for Addon.signedState. Any states that should cause an add-on
// to be unusable in builds that require signing should have negative values.
// Add-on signing is not required, e.g. because the pref is disabled.
SIGNEDSTATE_NOT_REQUIRED: undefined,
// Add-on is signed but signature verification has failed.
SIGNEDSTATE_BROKEN: -2,
// Add-on may be signed but by an certificate that doesn't chain to our
// our trusted certificate.
SIGNEDSTATE_UNKNOWN: -1,
// Add-on is unsigned.
SIGNEDSTATE_MISSING: 0,
// Add-on is preliminarily reviewed.
SIGNEDSTATE_PRELIMINARY: 1,
// Add-on is fully reviewed.
SIGNEDSTATE_SIGNED: 2,
// Add-on is system add-on.
SIGNEDSTATE_SYSTEM: 3,
// Add-on is signed with a "Mozilla Extensions" certificate
SIGNEDSTATE_PRIVILEGED: 4,
get __AddonManagerInternal__() {
return AppConstants.DEBUG ? AddonManagerInternal : undefined;
},
/** Boolean indicating whether AddonManager startup has completed. */
get isReady() {
return gStartupComplete && !gShutdownInProgress;
},
/**
* A promise that is resolved when the AddonManager startup has completed.
* This may be rejected if startup of the AddonManager is not successful, or
* if shutdown is started before the AddonManager has finished starting.
*/
get readyPromise() {
return gStartedPromise.promise;
},
/** @constructor */
init() {
this._stateToString = new Map();
for (let [name, value] of this._states) {
this[name] = value;
this._stateToString.set(value, name);
}
this._errorToString = new Map();
for (let [name, value] of this._errors) {
this[name] = value;
this._errorToString.set(value, name);
}
},
stateToString(state) {
return this._stateToString.get(state);
},
errorToString(err) {
return err ? this._errorToString.get(err) : null;
},
getInstallSourceFromHost(host) {
if (this._installHostSource.has(host)) {
return this._installHostSource.get(host);
}
if (WEBAPI_TEST_INSTALL_HOSTS.includes(host)) {
return "test-host";
}
return "unknown";
},
getInstallForURL(aUrl, aOptions) {
return AddonManagerInternal.getInstallForURL(aUrl, aOptions);
},
getInstallForFile(
aFile,
aMimetype,
aTelemetryInfo,
aUseSystemLocation = false
) {
return AddonManagerInternal.getInstallForFile(
aFile,
aMimetype,
aTelemetryInfo,
aUseSystemLocation
);
},
uninstallSystemProfileAddon(aID) {
return AddonManagerInternal.uninstallSystemProfileAddon(aID);
},
stageLangpacksForAppUpdate(appVersion, platformVersion) {
return AddonManagerInternal._getProviderByName(
"XPIProvider"
).stageLangpacksForAppUpdate(appVersion, platformVersion);
},
/**
* Gets an array of add-on IDs that changed during the most recent startup.
*
* @param aType
* The type of startup change to get
* @return An array of add-on IDs
*/
getStartupChanges(aType) {
if (!(aType in AddonManagerInternal.startupChanges)) {
return [];
}
return AddonManagerInternal.startupChanges[aType].slice(0);
},
getAddonByID(aID) {
return AddonManagerInternal.getAddonByID(aID);
},
getAddonBySyncGUID(aGUID) {
return AddonManagerInternal.getAddonBySyncGUID(aGUID);
},
getAddonsByIDs(aIDs) {
return AddonManagerInternal.getAddonsByIDs(aIDs);
},
getAddonsByTypes(aTypes) {
return AddonManagerInternal.getAddonsByTypes(aTypes);
},
getActiveAddons(aTypes) {
return AddonManagerInternal.getActiveAddons(aTypes);
},
getAllAddons() {
return AddonManagerInternal.getAllAddons();
},
getInstallsByTypes(aTypes) {
return AddonManagerInternal.getInstallsByTypes(aTypes);
},
getAllInstalls() {
return AddonManagerInternal.getAllInstalls();
},
isInstallEnabled(aType) {
return AddonManagerInternal.isInstallEnabled(aType);
},
isInstallAllowed(aType, aInstallingPrincipal) {
return AddonManagerInternal.isInstallAllowed(aType, aInstallingPrincipal);
},
installSitePermsAddonFromWebpage(
aBrowser,
aInstallingPrincipal,
aPermission
) {
return AddonManagerInternal.installSitePermsAddonFromWebpage(
aBrowser,
aInstallingPrincipal,
aPermission
);
},
installAddonFromWebpage(
aType,
aBrowser,
aInstallingPrincipal,
aInstall,
details
) {
AddonManagerInternal.installAddonFromWebpage(
aType,
aBrowser,
aInstallingPrincipal,
aInstall,
details
);
},
installAddonFromAOM(aBrowser, aUri, aInstall) {
AddonManagerInternal.installAddonFromAOM(aBrowser, aUri, aInstall);
},
installTemporaryAddon(aDirectory) {
return AddonManagerInternal.installTemporaryAddon(aDirectory);
},
installBuiltinAddon(aBase) {
return AddonManagerInternal.installBuiltinAddon(aBase);
},
maybeInstallBuiltinAddon(aID, aVersion, aBase) {
return AddonManagerInternal.maybeInstallBuiltinAddon(aID, aVersion, aBase);
},
addManagerListener(aListener) {
AddonManagerInternal.addManagerListener(aListener);
},
removeManagerListener(aListener) {
AddonManagerInternal.removeManagerListener(aListener);
},
addInstallListener(aListener) {
AddonManagerInternal.addInstallListener(aListener);
},
removeInstallListener(aListener) {
AddonManagerInternal.removeInstallListener(aListener);
},
getUpgradeListener(aId) {
return AddonManagerInternal.upgradeListeners.get(aId);
},
addUpgradeListener(aInstanceID, aCallback) {
AddonManagerInternal.addUpgradeListener(aInstanceID, aCallback);
},
removeUpgradeListener(aInstanceID) {
return AddonManagerInternal.removeUpgradeListener(aInstanceID);
},
addExternalExtensionLoader(loader) {
return AddonManagerInternal.addExternalExtensionLoader(loader);
},
addAddonListener(aListener) {
AddonManagerInternal.addAddonListener(aListener);
},
removeAddonListener(aListener) {
AddonManagerInternal.removeAddonListener(aListener);
},
hasAddonType(addonType) {
return AddonManagerInternal.hasAddonType(addonType);
},
hasProvider(name) {
if (!gStarted) {
throw Components.Exception(
"AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED
);
}
return !!AddonManagerInternal._getProviderByName(name);
},
/**
* Determines whether an Addon should auto-update or not.
*
* @param aAddon
* The Addon representing the add-on
* @return true if the addon should auto-update, false otherwise.
*/
shouldAutoUpdate(aAddon) {
if (!aAddon || typeof aAddon != "object") {
throw Components.Exception(
"aAddon must be specified",
Cr.NS_ERROR_INVALID_ARG
);
}
// Special case colorway built-in themes being migrated to an AMO installed theme
// when an update was found and:
//
// - `extensions.update.enable` is set to true (and so add-on updates are still
// being checked automatically on the background)
// - `extensions.update.autoUpdateDefault` is set to false (likely because the
// user has disabled auto-applying add-ons updates in about:addons to review
// extensions changelogs before accepting an update, e.g. to avoid unexpected
// issues that a new version of an extension may be introducing in the update)
//
// TODO(Bug 1815898): remove this special case along with other AOM/XPIProvider
// special cases introduced for colorways themes or colorways migration.
if (aAddon.isBuiltinColorwayTheme) {
return true;
}
if (!("applyBackgroundUpdates" in aAddon)) {
return false;
}
if (!(aAddon.permissions & AddonManager.PERM_CAN_UPGRADE)) {
return false;
}
if (aAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_ENABLE) {
return true;
}
if (aAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_DISABLE) {
return false;
}
return this.autoUpdateDefault;
},
get checkCompatibility() {
return AddonManagerInternal.checkCompatibility;
},
set checkCompatibility(aValue) {
AddonManagerInternal.checkCompatibility = aValue;
},
get strictCompatibility() {
return AddonManagerInternal.strictCompatibility;
},
set strictCompatibility(aValue) {
AddonManagerInternal.strictCompatibility = aValue;
},
get checkUpdateSecurityDefault() {
return AddonManagerInternal.checkUpdateSecurityDefault;
},
get checkUpdateSecurity() {
return AddonManagerInternal.checkUpdateSecurity;
},
set checkUpdateSecurity(aValue) {
AddonManagerInternal.checkUpdateSecurity = aValue;
},
get updateEnabled() {
return AddonManagerInternal.updateEnabled;
},
set updateEnabled(aValue) {
AddonManagerInternal.updateEnabled = aValue;
},
get autoUpdateDefault() {
return AddonManagerInternal.autoUpdateDefault;
},
set autoUpdateDefault(aValue) {
AddonManagerInternal.autoUpdateDefault = aValue;
},
escapeAddonURI(aAddon, aUri, aAppVersion) {
return AddonManagerInternal.escapeAddonURI(aAddon, aUri, aAppVersion);
},
getPreferredIconURL(aAddon, aSize, aWindow = undefined) {
return AddonManagerInternal.getPreferredIconURL(aAddon, aSize, aWindow);
},
get webAPI() {
return AddonManagerInternal.webAPI;
},
/**
* Async shutdown barrier which blocks the start of AddonManager
* shutdown. Callers should add blockers to this barrier if they need
* to complete add-on manager operations before it shuts down.
*/
get beforeShutdown() {
return gBeforeShutdownBarrier.client;
},
};
/**
* Manage AddonManager settings propagated over RemoteSettings synced data.
*
* See :doc:`AMRemoteSettings Overview <AMRemoteSettings-overview>`.
*
* .. warning::
* Before landing any change to ``AMRemoteSettings`` or the format expected for the
* remotely controlled settings (on the service or Firefos side), please read the
* documentation page linked above and make sure to keep the JSON Schema described
* and controlled settings groups included in that documentation page in sync with
* the one actually set on the RemoteSettings service side.
*/
AMRemoteSettings = {
RS_COLLECTION: "addons-manager-settings",
/**
* RemoteSettings settings group map.
*
* .. note::
* Please keep in sync the "Controlled Settings Groups" documentation from
* :doc:`AMRemoteSettings Overview <AMRemoteSettings-overview>` in sync with
* the settings groups defined here.
*/
RS_ENTRIES_MAP: {
installTriggerDeprecation: [
"extensions.InstallTriggerImpl.enabled",
"extensions.InstallTrigger.enabled",
],
quarantinedDomains: ["extensions.quarantinedDomains.list"],
},
client: null,
onSync: null,
promiseStartup: null,
init() {
try {
if (!this.promiseStartup) {
// Creating a promise to resolved when the browser startup was completed,
// used to process the existing entries (if any) after the startup is completed
// and to only to it ones.
this.promiseStartup = new Promise(resolve => {
function observer() {
resolve();
Services.obs.removeObserver(
observer,
"browser-delayed-startup-finished"
);
}
Services.obs.addObserver(
observer,
"browser-delayed-startup-finished"
);
});
}
if (Services.prefs.getBoolPref(PREF_REMOTESETTINGS_DISABLED, false)) {
return;
}
if (!this.client) {
this.client = lazy.RemoteSettings(this.RS_COLLECTION);
this.onSync = this.processEntries.bind(this);
this.client.on("sync", this.onSync);
// Process existing entries if any, once the browser has been fully initialized.
this.promiseStartup.then(() => this.processEntries());
}
} catch (err) {
logger.error("Failure to initialize AddonManager RemoteSettings", err);
}
},
shutdown() {
try {
if (this.client) {
this.client.off("sync", this.onSync);
this.client = null;
this.onSync = null;
}
this.promiseStartup = null;
} catch (err) {
logger.error("Failure on shutdown AddonManager RemoteSettings", err);
}
},
/**
* Process all the settings groups that are included in the collection entry with ``"id"`` set to ``"AddonManagerSettings"``
* (if any).
*
* .. note::
* This method may need to be updated if the preference value type is not yet expected by this method
* (which means that it would be ignored until handled explicitly).
*/
async processEntries() {
const entries = await this.client.get({ syncIfEmpty: false }).catch(err => {
logger.error("Failure to process AddonManager RemoteSettings", err);
return [];
});
const processEntryPref = (entryId, groupName, prefName, prefValue) => {
try {
logger.debug(
`Process AddonManager RemoteSettings "${entryId}" - "${groupName}": ${prefName}`
);
// Support for controlling boolean and string AddonManager settings.
switch (typeof prefValue) {
case "boolean":
Services.prefs.setBoolPref(prefName, prefValue);
break;
case "string":
Services.prefs.setStringPref(prefName, prefValue);
break;
default:
throw new Error(`Unexpected type ${typeof prefValue}`);
}
// Notify observers about the pref set from AMRemoteSettings.
Services.obs.notifyObservers(
{ entryId, groupName, prefName, prefValue },
"am-remote-settings-setpref"
);
} catch (e) {
logger.error(
`Failed to process AddonManager RemoteSettings "${entryId}" - "${groupName}": ${prefName}`,
e
);
}
};
for (const entry of entries) {
logger.debug(`Processing AddonManager RemoteSettings "${entry.id}"`);
for (const [groupName, prefs] of Object.entries(this.RS_ENTRIES_MAP)) {
const data = entry[groupName];
if (!data) {
continue;
}
for (const pref of prefs) {
// Skip the pref if it is not included in the remote settings data.
if (!(pref in data)) {
continue;
}
processEntryPref(entry.id, groupName, pref, data[pref]);
}
}
}
},
};
/**
* Listens to the AddonManager install and addon events and send telemetry events.
*/
AMTelemetry = {
telemetrySetupDone: false,
init() {
// Enable the addonsManager telemetry event category before the AddonManager
// has completed its startup, otherwise telemetry events recorded during the
// AddonManager/XPIProvider startup will not be recorded.
Services.telemetry.setEventRecordingEnabled("addonsManager", true);
},
// This method is called by the AddonManager, once it has been started, so that we can
// init the telemetry event category and start listening for the events related to the
// addons installation and management.
onStartup() {
if (this.telemetrySetupDone) {
return;
}
this.telemetrySetupDone = true;
Services.obs.addObserver(this, "addon-install-origin-blocked");
Services.obs.addObserver(this, "addon-install-disabled");
Services.obs.addObserver(this, "addon-install-blocked");
AddonManager.addInstallListener(this);
AddonManager.addAddonListener(this);
},
// Observer Service notification callback.
observe(subject, topic, data) {
switch (topic) {
case "addon-install-blocked": {
const { installs } = subject.wrappedJSObject;
this.recordInstallEvent(installs[0], { step: "site_warning" });
break;
}
case "addon-install-origin-blocked": {
const { installs } = subject.wrappedJSObject;
this.recordInstallEvent(installs[0], { step: "site_blocked" });
break;
}
case "addon-install-disabled": {
const { installs } = subject.wrappedJSObject;
this.recordInstallEvent(installs[0], {
step: "install_disabled_warning",
});
break;
}
}
},
// AddonManager install listener callbacks.
onNewInstall(install) {
this.recordInstallEvent(install, { step: "started" });
},
onInstallCancelled(install) {
this.recordInstallEvent(install, { step: "cancelled" });
},
onInstallPostponed(install) {
this.recordInstallEvent(install, { step: "postponed" });
},
onInstallFailed(install) {
this.recordInstallEvent(install, { step: "failed" });
},
onInstallEnded(install) {
this.recordInstallEvent(install, { step: "completed" });
// Skip install_stats events for install objects related to.
// add-on updates.
if (!install.existingAddon) {
this.recordInstallStatsEvent(install);
}
},
onDownloadStarted(install) {
this.recordInstallEvent(install, { step: "download_started" });
},
onDownloadCancelled(install) {
this.recordInstallEvent(install, { step: "cancelled" });
},
onDownloadEnded(install) {
let download_time = Math.round(Cu.now() - install.downloadStartedAt);
this.recordInstallEvent(install, {
step: "download_completed",
download_time,
});
},
onDownloadFailed(install) {
let download_time = Math.round(Cu.now() - install.downloadStartedAt);
this.recordInstallEvent(install, {
step: "download_failed",
download_time,
});
},
// Addon listeners callbacks.
onUninstalled(addon) {
this.recordManageEvent(addon, "uninstall");
},
onEnabled(addon) {
this.recordManageEvent(addon, "enable");
},
onDisabled(addon) {
this.recordManageEvent(addon, "disable");
},
// Internal helpers methods.
/**
* Get a trimmed version of the given string if it is longer than 80 chars.
*
* @param {string} str
* The original string content.
*
* @returns {string}
* The trimmed version of the string when longer than 80 chars, or the given string
* unmodified otherwise.
*/
getTrimmedString(str) {
if (str.length <= 80) {
return str;
}
const length = str.length;
// Trim the string to prevent a flood of warnings messages logged internally by recordEvent,
// the trimmed version is going to be composed by the first 40 chars and the last 37 and 3 dots
// that joins the two parts, to visually indicate that the string has been trimmed.
return `${str.slice(0, 40)}...${str.slice(length - 37, length)}`;
},
/**
* Retrieve the addonId for the given AddonInstall instance.
*
* @param {AddonInstall} install
* The AddonInstall instance to retrieve the addonId from.
*
* @returns {string | null}
* The addonId for the given AddonInstall instance (if any).
*/
getAddonIdFromInstall(install) {
// Returns the id of the extension that is being installed, as soon as the
// addon is available in the AddonInstall instance (after being downloaded
// and validated successfully).
if (install.addon) {
return install.addon.id;
}
// While updating an addon, the existing addon can be
// used to retrieve the addon id since the first update event.
if (install.existingAddon) {
return install.existingAddon.id;
}
return null;
},
/**
* Retrieve the telemetry event's object property value for the given
* AddonInstall instance.
*
* @param {AddonInstall} install
* The AddonInstall instance to retrieve the event object from.
*
* @returns {string}
* The object for the given AddonInstall instance.
*/
getEventObjectFromInstall(install) {
let addonType;
if (install.type) {
// The AddonInstall wrapper already provides a type (if it was known when the
// install object has been created).
addonType = install.type;
} else if (install.addon) {
// The install flow has reached a step that has an addon instance which we can
// check to know the extension type (e.g. after download for the DownloadAddonInstall).
addonType = install.addon.type;
} else if (install.existingAddon) {
// The install flow is an update and we can look the existingAddon to check which was
// the add-on type that is being installed.
addonType = install.existingAddon.type;
}
return this.getEventObjectFromAddonType(addonType);
},
/**
* Retrieve the telemetry event source for the given AddonInstall instance.
*
* @param {AddonInstall} install
* The AddonInstall instance to retrieve the source from.
*
* @returns {Object | null}
* The telemetry infor ({source, method}) from the given AddonInstall instance.
*/
getInstallTelemetryInfo(install) {
if (install.installTelemetryInfo) {
return install.installTelemetryInfo;
} else if (
install.existingAddon &&
install.existingAddon.installTelemetryInfo
) {
// Get the install source from the existing addon (e.g. for an extension update).
return install.existingAddon.installTelemetryInfo;
}
return null;
},
/**
* Get the telemetry event's object property for the given addon type
*
* @param {string} addonType
* The addon type to convert into the related telemetry event object.
*
* @returns {string}
* The object for the given addon type.
*/
getEventObjectFromAddonType(addonType) {
switch (addonType) {
case undefined:
return "unknown";
case "extension":
case "theme":
case "locale":
case "dictionary":
case "sitepermission":
return addonType;
// TODO(Bug 1789718): Remove after the deprecated XPIProvider-based implementation is also removed.
case "sitepermission-deprecated":
// Telemetry events' object maximum length is 20 chars (See https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/collection/events.html#limits)
// and the value needs to matching the "^[a-zA-Z][a-zA-Z0-9_.]*[a-zA-Z0-9]$" pattern.
return "siteperm_deprecated";
default:
// Currently this should only include gmp-plugins ("plugin").
return "other";
}
},
convertToString(value) {
if (value == null) {
// Convert null and undefined to empty strings.
return "";
}
switch (typeof value) {
case "string":
return value;
case "boolean":
return value ? "1" : "0";
}
return String(value);
},
/**
* Return the UTM parameters found in `sourceURL` for AMO attribution data.
*
* @param {string} sourceURL
* The source URL from where the add-on has been installed.
*
* @returns {object}
* An object containing the attribution data for AMO if any. Keys
* are defined in `AMO_ATTRIBUTION_DATA_KEYS`. Values are strings.
*/
parseAttributionDataForAMO(sourceURL) {
let searchParams;
try {
searchParams = new URL(sourceURL).searchParams;
} catch {
return {};
}
const utmKeys = [...searchParams.keys()].filter(key =>
AMO_ATTRIBUTION_DATA_KEYS.includes(key)
);
return utmKeys.reduce((params, key) => {
let value = searchParams.get(key);
if (typeof value === "string") {
value = value.slice(0, AMO_ATTRIBUTION_DATA_MAX_LENGTH);
}
return { ...params, [key]: value };
}, {});
},
/**
* Record an "install stats" event when the source is included in
* `AMO_ATTRIBUTION_ALLOWED_SOURCES`.
*
* @param {AddonInstall} install
* The AddonInstall instance to record an install_stats event for.
*/
recordInstallStatsEvent(install) {
const telemetryInfo = this.getInstallTelemetryInfo(install);
if (!AMO_ATTRIBUTION_ALLOWED_SOURCES.includes(telemetryInfo?.source)) {
return;
}
const method = "install_stats";
const object = this.getEventObjectFromInstall(install);
const addonId = this.getAddonIdFromInstall(install);
if (!addonId) {
Cu.reportError(
"Missing addonId when trying to record an install_stats event"
);
return;
}
let extra = {
addon_id: this.getTrimmedString(addonId),
};
if (
telemetryInfo?.source === "amo" &&
typeof telemetryInfo?.sourceURL === "string"
) {
extra = {
...extra,
...this.parseAttributionDataForAMO(telemetryInfo.sourceURL),
};
}
if (
telemetryInfo?.source === "disco" &&
typeof telemetryInfo?.taarRecommended === "boolean"
) {
extra = {
...extra,
taar_based: this.convertToString(telemetryInfo.taarRecommended),
};
}
this.recordEvent({ method, object, value: install.hashedAddonId, extra });
Glean.addonsManager.installStats.record(
this.formatExtraVars({
addon_id: extra.addon_id,
addon_type: object,
taar_based: extra.taar_based,
utm_campaign: extra.utm_campaign,
utm_content: extra.utm_content,
utm_medium: extra.utm_medium,
utm_source: extra.utm_source,
})
);
},
/**
* Convert all the telemetry event's extra_vars into strings, if needed.
*
* @param {object} extraVars
* @returns {object} The formatted extra vars.
*/
formatExtraVars({ addon, ...extraVars }) {
if (addon) {
extraVars.addonId = addon.id;
extraVars.type = addon.type;
}
// All the extra_vars in a telemetry event have to be strings.
for (var [key, value] of Object.entries(extraVars)) {
if (value == undefined) {
delete extraVars[key];
} else {
extraVars[key] = this.convertToString(value);
}
}
if (extraVars.addonId) {
extraVars.addonId = this.getTrimmedString(extraVars.addonId);
}
return extraVars;
},
/**
* Record an install or update event for the given AddonInstall instance.
*
* @param {AddonInstall} install
* The AddonInstall instance to record an install or update event for.
* @param {object} extraVars
* The additional extra_vars to include in the recorded event.
* @param {string} extraVars.step
* The current step in the install or update flow.
* @param {string} extraVars.download_time
* The number of ms needed to download the extension.
* @param {string} extraVars.num_strings
* The number of permission description string for the extension
* permission doorhanger.
*/
recordInstallEvent(install, extraVars) {
// Early exit if AMTelemetry's telemetry setup has not been done yet.
if (!this.telemetrySetupDone) {
return;
}
let extra = {};
let telemetryInfo = this.getInstallTelemetryInfo(install);
if (telemetryInfo && typeof telemetryInfo.source === "string") {
extra.source = telemetryInfo.source;
}
if (extra.source === "internal") {
// Do not record the telemetry event for installation sources
// that are marked as "internal".
return;
}
// Also include the install source's method when applicable (e.g. install events with
// source "about:addons" may have "install-from-file" or "url" as their source method).
if (telemetryInfo && typeof telemetryInfo.method === "string") {
extra.method = telemetryInfo.method;
}
let addonId = this.getAddonIdFromInstall(install);
let object = this.getEventObjectFromInstall(install);
let installId = String(install.installId);
let eventMethod = install.existingAddon ? "update" : "install";
if (addonId) {
extra.addon_id = this.getTrimmedString(addonId);
}
if (install.error) {
extra.error = AddonManager.errorToString(install.error);
}
if (
eventMethod === "install" &&
Services.prefs.getBoolPref("extensions.install_origins.enabled", true)
) {
// This is converted to "1" / "0".
extra.install_origins = Array.isArray(install.addon?.installOrigins);
}
if (eventMethod === "update") {
// For "update" telemetry events, also include an extra var which determine
// if the update has been requested by the user.
extra.updated_from = install.isUserRequestedUpdate ? "user" : "app";
}
// All the extra vars in a telemetry event have to be strings.
extra = this.formatExtraVars({ ...extraVars, ...extra });
this.recordEvent({ method: eventMethod, object, value: installId, extra });
Glean.addonsManager[eventMethod]?.record(
this.formatExtraVars({
addon_id: extra.addon_id,
addon_type: object,
install_id: installId,
download_time: extra.download_time,
error: extra.error,
source: extra.source,
source_method: extra.method,
num_strings: extra.num_strings,
updated_from: extra.updated_from,
install_origins: extra.install_origins,
step: extra.step,
})
);
},
/**
* Record a manage event for the given addon.
*
* @param {AddonWrapper} addon
* The AddonWrapper instance.
* @param {object} extraVars
* The additional extra_vars to include in the recorded event.
* @param {string} extraVars.num_strings
* The number of permission description string for the extension
* permission doorhanger.
*/
recordManageEvent(addon, method, extraVars) {
// Early exit if AMTelemetry's telemetry setup has not been done yet.
if (!this.telemetrySetupDone) {
return;
}
let extra = {};
if (addon.installTelemetryInfo) {
if ("source" in addon.installTelemetryInfo) {
extra.source = addon.installTelemetryInfo.source;
}
// Also include the install source's method when applicable (e.g. install events with
// source "about:addons" may have "install-from-file" or "url" as their source method).
if ("method" in addon.installTelemetryInfo) {
extra.method = addon.installTelemetryInfo.method;
}
}
if (extra.source === "internal") {
// Do not record the telemetry event for installation sources
// that are marked as "internal".
return;
}
let object = this.getEventObjectFromAddonType(addon.type);
let value = this.getTrimmedString(addon.id);
extra = { ...extraVars, ...extra };
let hasExtraVars = !!Object.keys(extra).length;
extra = this.formatExtraVars(extra);
this.recordEvent({
method,
object,
value,
extra: hasExtraVars ? extra : null,
});
Glean.addonsManager.manage.record(
this.formatExtraVars({
method,
addon_id: value,
addon_type: object,
source: extra.source,
source_method: extra.method,
num_strings: extra.num_strings,
})
);
},
/**
* Record an event on abuse report submissions.
*
* @params {object} opts
* @params {string} opts.addonId
* The id of the addon being reported.
* @params {string} [opts.addonType]
* The type of the addon being reported (only present for an existing
* addonId).
* @params {string} [opts.errorType]
* The AbuseReport errorType for a submission failure.
* @params {string} opts.reportEntryPoint
* The entry point of the abuse report.
*/
recordReportEvent({ addonId, addonType, errorType, reportEntryPoint }) {
this.recordEvent({
method: "report",
object: reportEntryPoint,
value: addonId,
extra: this.formatExtraVars({
addon_type: addonType,
error_type: errorType,
}),
});
Glean.addonsManager.report.record(
this.formatExtraVars({
addon_id: addonId,
addon_type: addonType,
entry_point: reportEntryPoint,
error_type: errorType,
})
);
},
/**
* @params {object} opts
* @params {nsIURI} opts.displayURI
*/
recordSuspiciousSiteEvent({ displayURI }) {
let site = displayURI?.displayHost ?? "(unknown)";
this.recordEvent({
method: "reportSuspiciousSite",
object: "suspiciousSite",
value: site,
extra: {},
});
Glean.addonsManager.reportSuspiciousSite.record(
this.formatExtraVars({ suspiciousSite: site })
);
},
recordEvent({ method, object, value, extra }) {
if (typeof value != "string") {
// The value must be a string or null, make sure it's valid so sending
// the event doesn't fail.
value = null;
}
try {
Services.telemetry.recordEvent(
"addonsManager",
method,
object,
value,
extra
);
} catch (err) {
// If the telemetry throws just log the error so it doesn't break any
// functionality.
Cu.reportError(err);
}
},
};
/**
* AMBrowserExtensionsImport is used by the migration wizard to import/install
* Firefox add-ons based on a set of non-Firefox browser extensions.
*/
AMBrowserExtensionsImport = {
TELEMETRY_SOURCE: "browser-import",
TOPIC_CANCELLED: "webextension-imported-addons-cancelled",
TOPIC_COMPLETE: "webextension-imported-addons-complete",
TOPIC_PENDING: "webextension-imported-addons-pending",
// AddonId => AddonInstall
_pendingInstallsMap: new Map(),
_importInProgress: false,
_canCompleteOrCancelInstalls: false,
// Prompt handler set on the AddonInstall instances part of the imports
// (which currently makes sure we are not prompting for permissions when the
// imported addons are being downloaded, staged and then installed).
_installPromptHandler: () => {},
// Optionally override the `AddonRepository`, mainly for testing purposes.
_addonRepository: null,
get hasPendingImportedAddons() {
return !!this._pendingInstallsMap.size;
},
get importedAddonIDs() {
return Array.from(this._pendingInstallsMap.keys());
},
get canCompleteOrCancelInstalls() {
return this._canCompleteOrCancelInstalls && this.hasPendingImportedAddons;
},
get addonRepository() {
return this._addonRepository || lazy.AddonRepository;
},
/**
* Stage an install for each add-on mapped to a browser extension ID in the
* list of IDs passed to this method.
*
* @param {string} browserId A browser identifier.
* @param {Array<string} extensionIDs A list of non-Firefox extension IDs.
* @returns {Promise<object>} The return value is an object with data for
* the caller.
* @throws {Error} When there are pending imported add-ons.
*/
async stageInstalls(browserId, extensionIDs) {
// In case we have an import in progress, we throw so that the caller knows
// that there is already an import in progress, which it may want to either
// cancel or complete.
if (this._importInProgress) {
throw new Error(
"Cannot stage installs because there are pending imported add-ons"
);
}
this._importInProgress = true;
this._canCompleteOrCancelInstalls = false;
let importedAddons = [];
// We first retrieve a list of `AddonSearchResult`, which are the Firefox
// add-ons mapped to the list of extension IDs passed to this method. We
// might not have as many mapped add-ons as extension IDs because not all
// browser extensions will be mapped to Firefox add-ons.
try {
let matchedIDs = [];
let unmatchedIDs = [];
({
addons: importedAddons,
matchedIDs,
unmatchedIDs,
} = await this.addonRepository.getMappedAddons(browserId, extensionIDs));
Glean.browserMigration.matchedExtensions.set(matchedIDs);
Glean.browserMigration.unmatchedExtensions.set(unmatchedIDs);
} catch (err) {
Cu.reportError(err);
}
const alreadyInstalledIDs = (await AddonManager.getAllAddons()).map(
addon => addon.id
);
const { _pendingInstallsMap } = this;
const results = await Promise.allSettled(
// For each add-on to import, we create an `AddonInstall` instance and we
// start the install process until we reach the "downloaded ended" step.
// At this point, we call `postpone()`, and we are done when the add-on
// install has been postponed.
importedAddons
// Do not import add-ons already installed.
.filter(({ id }) => !alreadyInstalledIDs.includes(id))
.map(async ({ id, sourceURI, name, version, icons }) => {
let addonInstall;
try {
addonInstall = await AddonManager.getInstallForURL(sourceURI.spec, {
name,
version,
icons,
telemetryInfo: { source: this.TELEMETRY_SOURCE },
promptHandler: this._installPromptHandler,
});
} catch (err) {
return Promise.reject(err);
}
return new Promise((resolve, reject) => {
const rejectWithMessage = err => () => reject(new Error(err));
addonInstall.addListener({
onDownloadEnded(install) {
install
.postpone(null, /* requiresRestart */ false)
.then(_pendingInstallsMap.set(id, install));
},
onInstallPostponed() {
resolve();
},
onDownloadCancelled: rejectWithMessage("Download cancelled"),
onDownloadFailed: rejectWithMessage("Download failed"),
onInstallCancelled: rejectWithMessage("Install cancelled"),
onInstallFailed: rejectWithMessage("Install failed"),
});
addonInstall.install();
});
})
);
this._reportErrors(results);
// All the imported add-ons should have been staged for install at this
// point, unless there was no add-on mapped OR some errors.
const { importedAddonIDs } = this;
this._canCompleteOrCancelInstalls = !!importedAddonIDs.length;
this._importInProgress = !!importedAddonIDs.length;
if (importedAddonIDs.length) {
Services.obs.notifyObservers(null, this.TOPIC_PENDING);
}
return { importedAddonIDs };
},
/**
* Finalize the installation of the add-ons for which we staged their install.
*
* @returns {Promise<void>}
* @throws {Error} When there is no import in progress.
*/
async completeInstalls() {
if (!this._importInProgress) {
throw new Error("No import in progress");
}
const results = await Promise.allSettled(
Array.from(this._pendingInstallsMap.values()).map(install => {
return install.continuePostponedInstall();
})
);
this._reportErrors(results);
this._clearInternalState();
Services.obs.notifyObservers(null, this.TOPIC_COMPLETE);
},
/**
* Cancel the installation of the add-ons for which we staged their install.
*
* @returns {Promise<void>}
* @throws {Error} When there is no import in progress.
*/
async cancelInstalls() {
if (!this._importInProgress) {
throw new Error("No import in progress");
}
const results = await Promise.allSettled(
Array.from(this._pendingInstallsMap.values()).map(install => {
return install.cancel();
})
);
this._reportErrors(results);
this._clearInternalState();
Services.obs.notifyObservers(null, this.TOPIC_CANCELLED);
},
_reportErrors(results) {
results
.filter(result => result.status === "rejected")
.forEach(result => Cu.reportError(result.reason));
},
_clearInternalState() {
this._pendingInstallsMap.clear();
this._importInProgress = false;
this._canCompleteOrCancelInstalls = false;
},
};
AddonManager.init();
// Setup the AMTelemetry once the AddonManager has been started.
AddonManager.addManagerListener(AMTelemetry);
Object.freeze(AddonManagerInternal);
Object.freeze(AddonManagerPrivate);
Object.freeze(AddonManager);
|