summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/main/java/org/mozilla/geckoview/ContentBlocking.java
blob: 6135c17d95bbdb548c13a5087fa0bd8616dfd3a5 (plain)
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
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * vim: ts=4 sw=4 expandtab:
 * 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/. */

package org.mozilla.geckoview;

import android.annotation.SuppressLint;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import androidx.annotation.AnyThread;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.mozilla.gecko.util.GeckoBundle;

/** Content Blocking API to hold and control anti-tracking, cookie and Safe Browsing settings. */
@AnyThread
public class ContentBlocking {
  /** {@link SafeBrowsingProvider} configuration for Google's legacy SafeBrowsing server. */
  public static final SafeBrowsingProvider GOOGLE_LEGACY_SAFE_BROWSING_PROVIDER =
      SafeBrowsingProvider.withName("google")
          .version("2.2")
          .lists(
              "goog-badbinurl-shavar",
              "goog-downloadwhite-digest256",
              "goog-phish-shavar",
              "googpub-phish-shavar",
              "goog-malware-shavar",
              "goog-unwanted-shavar")
          .updateUrl(
              "https://safebrowsing.google.com/safebrowsing/downloads?client=SAFEBROWSING_ID&appver=%MAJOR_VERSION%&pver=2.2&key=%GOOGLE_SAFEBROWSING_API_KEY%")
          .getHashUrl(
              "https://safebrowsing.google.com/safebrowsing/gethash?client=SAFEBROWSING_ID&appver=%MAJOR_VERSION%&pver=2.2")
          .reportUrl("https://safebrowsing.google.com/safebrowsing/diagnostic?site=")
          .reportPhishingMistakeUrl("https://%LOCALE%.phish-error.mozilla.com/?url=")
          .reportMalwareMistakeUrl("https://%LOCALE%.malware-error.mozilla.com/?url=")
          .advisoryUrl("https://developers.google.com/safe-browsing/v4/advisory")
          .advisoryName("Google Safe Browsing")
          .build();

  /** {@link SafeBrowsingProvider} configuration for Google's SafeBrowsing server. */
  public static final SafeBrowsingProvider GOOGLE_SAFE_BROWSING_PROVIDER =
      SafeBrowsingProvider.withName("google4")
          .version("4")
          .lists(
              "goog-badbinurl-proto",
              "goog-downloadwhite-proto",
              "goog-phish-proto",
              "googpub-phish-proto",
              "goog-malware-proto",
              "goog-unwanted-proto",
              "goog-harmful-proto")
          .updateUrl(
              "https://safebrowsing.googleapis.com/v4/threatListUpdates:fetch?$ct=application/x-protobuf&key=%GOOGLE_SAFEBROWSING_API_KEY%&$httpMethod=POST")
          .getHashUrl(
              "https://safebrowsing.googleapis.com/v4/fullHashes:find?$ct=application/x-protobuf&key=%GOOGLE_SAFEBROWSING_API_KEY%&$httpMethod=POST")
          .reportUrl("https://safebrowsing.google.com/safebrowsing/diagnostic?site=")
          .reportPhishingMistakeUrl("https://%LOCALE%.phish-error.mozilla.com/?url=")
          .reportMalwareMistakeUrl("https://%LOCALE%.malware-error.mozilla.com/?url=")
          .advisoryUrl("https://developers.google.com/safe-browsing/v4/advisory")
          .advisoryName("Google Safe Browsing")
          .dataSharingUrl(
              "https://safebrowsing.googleapis.com/v4/threatHits?$ct=application/x-protobuf&key=%GOOGLE_SAFEBROWSING_API_KEY%&$httpMethod=POST")
          .dataSharingEnabled(false)
          .build();

  // This class shouldn't be instantiated
  protected ContentBlocking() {}

  @AnyThread
  public static class Settings extends RuntimeSettings {
    private final Map<String, SafeBrowsingProvider> mSafeBrowsingProviders = new HashMap<>();

    private static final SafeBrowsingProvider[] DEFAULT_PROVIDERS = {
      ContentBlocking.GOOGLE_LEGACY_SAFE_BROWSING_PROVIDER,
      ContentBlocking.GOOGLE_SAFE_BROWSING_PROVIDER
    };

    @AnyThread
    public static class Builder extends RuntimeSettings.Builder<Settings> {
      @Override
      protected @NonNull Settings newSettings(final @Nullable Settings settings) {
        return new Settings(settings);
      }

      /**
       * Set custom safe browsing providers.
       *
       * @param providers one or more custom providers.
       * @return This Builder instance.
       * @see SafeBrowsingProvider
       */
      public @NonNull Builder safeBrowsingProviders(
          final @NonNull SafeBrowsingProvider... providers) {
        getSettings().setSafeBrowsingProviders(providers);
        return this;
      }

      /**
       * Set the safe browsing table for phishing threats.
       *
       * @param safeBrowsingPhishingTable one or more lists for safe browsing phishing.
       * @return This Builder instance.
       * @see SafeBrowsingProvider
       */
      public @NonNull Builder safeBrowsingPhishingTable(
          final @NonNull String[] safeBrowsingPhishingTable) {
        getSettings().setSafeBrowsingPhishingTable(safeBrowsingPhishingTable);
        return this;
      }

      /**
       * Set the safe browsing table for malware threats.
       *
       * @param safeBrowsingMalwareTable one or more lists for safe browsing malware.
       * @return This Builder instance.
       * @see SafeBrowsingProvider
       */
      public @NonNull Builder safeBrowsingMalwareTable(
          final @NonNull String[] safeBrowsingMalwareTable) {
        getSettings().setSafeBrowsingMalwareTable(safeBrowsingMalwareTable);
        return this;
      }

      /**
       * Set anti-tracking categories.
       *
       * @param cat The categories of resources that should be blocked. Use one or more of the
       *     {@link ContentBlocking.AntiTracking} flags.
       * @return This Builder instance.
       */
      public @NonNull Builder antiTracking(final @CBAntiTracking int cat) {
        getSettings().setAntiTracking(cat);
        return this;
      }

      /**
       * Set safe browsing categories.
       *
       * @param cat The categories of resources that should be blocked. Use one or more of the
       *     {@link ContentBlocking.SafeBrowsing} flags.
       * @return This Builder instance.
       */
      public @NonNull Builder safeBrowsing(final @CBSafeBrowsing int cat) {
        getSettings().setSafeBrowsing(cat);
        return this;
      }

      /**
       * Set cookie storage behavior.
       *
       * @param behavior The storage behavior that should be applied. Use one of the {@link
       *     CookieBehavior} flags.
       * @return The Builder instance.
       */
      public @NonNull Builder cookieBehavior(final @CBCookieBehavior int behavior) {
        getSettings().setCookieBehavior(behavior);
        return this;
      }

      /**
       * Set cookie storage behavior in private browsing mode.
       *
       * @param behavior The storage behavior that should be applied. Use one of the {@link
       *     CookieBehavior} flags.
       * @return The Builder instance.
       */
      public @NonNull Builder cookieBehaviorPrivateMode(final @CBCookieBehavior int behavior) {
        getSettings().setCookieBehaviorPrivateMode(behavior);
        return this;
      }

      /**
       * Set the ETP behavior level.
       *
       * @param level The level of ETP blocking to use. Only takes effect if cookie behavior is set
       *     to {@link ContentBlocking.CookieBehavior#ACCEPT_NON_TRACKERS} or {@link
       *     ContentBlocking.CookieBehavior#ACCEPT_FIRST_PARTY_AND_ISOLATE_OTHERS}.
       * @return The Builder instance.
       */
      public @NonNull Builder enhancedTrackingProtectionLevel(final @CBEtpLevel int level) {
        getSettings().setEnhancedTrackingProtectionLevel(level);
        return this;
      }

      /**
       * Set whether or not email tracker blocking is enabled in private mode.
       *
       * @param enabled A boolean indicating whether or not email tracker blocking should be enabled
       *     in private mode.
       * @return The builder instance.
       */
      public @NonNull Builder emailTrackerBlockingPrivateMode(final boolean enabled) {
        getSettings().setEmailTrackerBlockingPrivateBrowsing(enabled);
        return this;
      }

      /**
       * Set whether or not strict social tracking protection is enabled. This will block resources
       * from loading if they are on the social tracking protection list, rather than just blocking
       * cookies as with normal social tracking protection.
       *
       * @param enabled A boolean indicating whether or not strict social tracking protection should
       *     be enabled.
       * @return The builder instance.
       */
      public @NonNull Builder strictSocialTrackingProtection(final boolean enabled) {
        getSettings().setStrictSocialTrackingProtection(enabled);
        return this;
      }

      /**
       * Set whether or not to automatically purge tracking cookies. This will purge cookies from
       * tracking sites that do not have recent user interaction provided that the cookie behavior
       * is set to either {@link ContentBlocking.CookieBehavior#ACCEPT_NON_TRACKERS} or {@link
       * ContentBlocking.CookieBehavior#ACCEPT_FIRST_PARTY_AND_ISOLATE_OTHERS}.
       *
       * @param enabled A boolean indicating whether or not cookie purging should be enabled.
       * @return The builder instance.
       */
      public @NonNull Builder cookiePurging(final boolean enabled) {
        getSettings().setCookiePurging(enabled);
        return this;
      }

      /**
       * Set the Cookie Banner Handling Mode.
       *
       * @param mode The mode of the Cookie Banner Handling one of the {@link CBCookieBannerMode}.
       * @return The Builder instance.
       */
      public @NonNull Builder cookieBannerHandlingMode(final @CBCookieBannerMode int mode) {
        getSettings().setCookieBannerMode(mode);
        return this;
      }

      /**
       * When set to true, enable the use of global CookieBannerRules.
       *
       * @param enabled A boolean indicating whether to enable the use of global CookieBannerRules.
       * @return The Builder instance.
       */
      public @NonNull Builder cookieBannerGlobalRulesEnabled(final boolean enabled) {
        getSettings().setCookieBannerGlobalRulesEnabled(enabled);
        return this;
      }

      /**
       * When set to true, enable the use of global CookieBannerRules in sub-frames.
       *
       * @param enabled A boolean indicating whether to enable the use of global CookieBannerRules
       *     in sub-frames.
       * @return The Builder instance.
       */
      public @NonNull Builder cookieBannerGlobalRulesSubFramesEnabled(final boolean enabled) {
        getSettings().setCookieBannerGlobalRulesSubFramesEnabled(enabled);
        return this;
      }

      /**
       * When set to true, query parameter stripping is enabled in normal mode.
       *
       * @param enabled A boolean indicating whether to query parameter stripping enabled in normal
       *     mode.
       * @return The Builder instance.
       */
      public @NonNull Builder queryParameterStrippingEnabled(final boolean enabled) {
        getSettings().setQueryParameterStrippingEnabled(enabled);
        return this;
      }

      /**
       * When set to true, query parameter stripping is enabled in private mode.
       *
       * @param enabled A boolean indicating whether to query parameter stripping enabled in private
       *     mode.
       * @return The Builder instance.
       */
      public @NonNull Builder queryParameterStrippingPrivateBrowsingEnabled(final boolean enabled) {
        getSettings().setQueryParameterStrippingPrivateBrowsingEnabled(enabled);
        return this;
      }

      /**
       * The allowed list for the query parameter stripping feature.
       *
       * @param list an array of identifiers for query parameter's stripping feature.
       * @return The Builder instance.
       */
      public @NonNull Builder queryParameterStrippingAllowList(final @NonNull String... list) {
        getSettings().setQueryParameterStrippingAllowList(list);
        return this;
      }

      /**
       * The strip list for the query parameter stripping feature.
       *
       * @param list an array of identifiers for the strip list of the query parameter's stripping
       *     feature.
       * @return The Builder instance.
       */
      public @NonNull Builder queryParameterStrippingStripList(final @NonNull String... list) {
        getSettings().setQueryParameterStrippingStripList(list);
        return this;
      }

      /**
       * Set the Cookie Banner Handling Mode for private browsing.
       *
       * @param mode The mode of the Cookie Banner Handling one of the {@link CBCookieBannerMode}.
       * @return The Builder instance.
       */
      public @NonNull Builder cookieBannerHandlingModePrivateBrowsing(
          final @CBCookieBannerMode int mode) {
        getSettings().setCookieBannerModePrivateBrowsing(mode);
        return this;
      }

      /**
       * When set to true, cookie banners are detected and detection events are dispatched, but they
       * will not be handled.
       *
       * @param enabled A boolean indicating whether to enable cookie banner detect only mode.
       * @return The Builder instance.
       */
      public @NonNull Builder cookieBannerHandlingDetectOnlyMode(final boolean enabled) {
        getSettings().setCookieBannerDetectOnlyMode(enabled);
        return this;
      }
    }

    /* package */ final Pref<String> mAt =
        new Pref<String>(
            "urlclassifier.trackingTable", ContentBlocking.catToAtPref(AntiTracking.DEFAULT));
    /* package */ final Pref<Boolean> mCm =
        new Pref<Boolean>("privacy.trackingprotection.cryptomining.enabled", false);
    /* package */ final Pref<String> mCmList =
        new Pref<String>(
            "urlclassifier.features.cryptomining.blacklistTables",
            ContentBlocking.catToCmListPref(AntiTracking.NONE));
    /* package */ final Pref<Boolean> mFp =
        new Pref<Boolean>("privacy.trackingprotection.fingerprinting.enabled", false);
    /* package */ final Pref<String> mFpList =
        new Pref<String>(
            "urlclassifier.features.fingerprinting.blacklistTables",
            ContentBlocking.catToFpListPref(AntiTracking.NONE));
    /* package */ final Pref<Boolean> mSt =
        new Pref<Boolean>("privacy.socialtracking.block_cookies.enabled", false);
    /* package */ final Pref<Boolean> mStStrict =
        new Pref<Boolean>("privacy.trackingprotection.socialtracking.enabled", false);
    /* package */ final Pref<String> mStList =
        new Pref<String>(
            "urlclassifier.features.socialtracking.annotate.blacklistTables",
            ContentBlocking.catToPref(AntiTracking.NONE, AntiTracking.STP, STP));

    /* package */ final Pref<Boolean> mSbMalware =
        new Pref<Boolean>("browser.safebrowsing.malware.enabled", true);
    /* package */ final Pref<Boolean> mSbPhishing =
        new Pref<Boolean>("browser.safebrowsing.phishing.enabled", true);
    /* package */ final Pref<Integer> mCookieBehavior =
        new Pref<Integer>("network.cookie.cookieBehavior", CookieBehavior.ACCEPT_NON_TRACKERS);
    /* package */ final Pref<Integer> mCookieBehaviorPrivateMode =
        new Pref<Integer>(
            "network.cookie.cookieBehavior.pbmode", CookieBehavior.ACCEPT_NON_TRACKERS);
    /* package */ final Pref<Boolean> mCookiePurging =
        new Pref<Boolean>("privacy.purge_trackers.enabled", false);

    /* package */ final Pref<Boolean> mEtpEnabled =
        new Pref<Boolean>("privacy.trackingprotection.annotate_channels", false);
    /* package */ final Pref<Boolean> mEtpStrict =
        new Pref<Boolean>("privacy.annotate_channels.strict_list.enabled", false);

    /* package */ final Pref<Integer> mCbhMode =
        new Pref<Integer>(
            "cookiebanners.service.mode", CookieBannerMode.COOKIE_BANNER_MODE_DISABLED);
    /* package */ final Pref<Integer> mCbhModePrivateBrowsing =
        new Pref<Integer>(
            "cookiebanners.service.mode.privateBrowsing",
            CookieBannerMode.COOKIE_BANNER_MODE_REJECT);

    /* package */ final Pref<Boolean> mChbDetectOnlyMode =
        new Pref<Boolean>("cookiebanners.service.detectOnly", false);
    /* package */
    final Pref<Boolean> mCbhGlobalRulesEnabled =
        new Pref<Boolean>("cookiebanners.service.enableGlobalRules", false);

    final Pref<Boolean> mCbhGlobalRulesSubFramesEnabled =
        new Pref<Boolean>("cookiebanners.service.enableGlobalRules.subFrames", false);

    /* package */ final Pref<Boolean> mQueryParameterStrippingEnabled =
        new Pref<Boolean>("privacy.query_stripping.enabled", false);

    /* package */ final Pref<Boolean> mQueryParameterStrippingPrivateBrowsingEnabled =
        new Pref<Boolean>("privacy.query_stripping.enabled.pbmode", false);

    /* package */ final Pref<String> mQueryParameterStrippingAllowList =
        new Pref<>("privacy.query_stripping.allow_list", "");

    /* package */ final Pref<String> mQueryParameterStrippingStripList =
        new Pref<>("privacy.query_stripping.strip_list", "");

    /* package */ final Pref<Boolean> mEtb =
        new Pref<Boolean>("privacy.trackingprotection.emailtracking.enabled", false);

    /* package */ final Pref<Boolean> mEtbPrivateBrowsing =
        new Pref<Boolean>("privacy.trackingprotection.emailtracking.pbmode.enabled", false);

    /* package */ final Pref<String> mEtbList =
        new Pref<String>(
            "urlclassifier.features.emailtracking.blocklistTables",
            ContentBlocking.catToPref(AntiTracking.NONE, AntiTracking.EMAIL, EMAIL));

    /* package */ final Pref<String> mSafeBrowsingMalwareTable =
        new Pref<>(
            "urlclassifier.malwareTable",
            ContentBlocking.listsToPref(
                "goog-malware-proto",
                "goog-unwanted-proto",
                "moztest-harmful-simple",
                "moztest-malware-simple",
                "moztest-unwanted-simple"));
    /* package */ final Pref<String> mSafeBrowsingPhishingTable =
        new Pref<>(
            "urlclassifier.phishTable",
            ContentBlocking.listsToPref(
                // In official builds, we are allowed to use Google's private phishing
                // list (see bug 1288840).
                BuildConfig.MOZILLA_OFFICIAL ? "goog-phish-proto" : "googpub-phish-proto",
                "moztest-phish-simple"));

    /** Construct default settings. */
    /* package */ Settings() {
      this(null /* settings */);
    }

    /**
     * Copy-construct settings.
     *
     * @param settings Copy from this settings.
     */
    /* package */ Settings(final @Nullable Settings settings) {
      this(null /* parent */, settings);
    }

    /**
     * Copy-construct nested settings.
     *
     * @param parent The parent settings used for nesting.
     * @param settings Copy from this settings.
     */
    /* package */ Settings(
        final @Nullable RuntimeSettings parent, final @Nullable Settings settings) {
      super(parent);

      if (settings != null) {
        updatePrefs(settings);
      } else {
        // Set default browsing providers
        setSafeBrowsingProviders(DEFAULT_PROVIDERS);
      }
    }

    @Override
    protected void updatePrefs(final @NonNull RuntimeSettings settings) {
      super.updatePrefs(settings);

      final ContentBlocking.Settings source = (ContentBlocking.Settings) settings;
      for (final SafeBrowsingProvider provider : source.mSafeBrowsingProviders.values()) {
        mSafeBrowsingProviders.put(provider.getName(), new SafeBrowsingProvider(this, provider));
      }
    }

    /**
     * Get the collection of {@link SafeBrowsingProvider} for this runtime.
     *
     * @return an unmodifiable collection of {@link SafeBrowsingProvider}
     * @see SafeBrowsingProvider
     */
    public @NonNull Collection<SafeBrowsingProvider> getSafeBrowsingProviders() {
      return Collections.unmodifiableCollection(mSafeBrowsingProviders.values());
    }

    /**
     * Sets the collection of {@link SafeBrowsingProvider} for this runtime.
     *
     * <p>By default the collection is composed of {@link
     * ContentBlocking#GOOGLE_LEGACY_SAFE_BROWSING_PROVIDER} and {@link
     * ContentBlocking#GOOGLE_SAFE_BROWSING_PROVIDER}.
     *
     * @param providers {@link SafeBrowsingProvider} instances for this runtime.
     * @return the {@link Settings} instance.
     * @see SafeBrowsingProvider
     */
    public @NonNull Settings setSafeBrowsingProviders(
        final @NonNull SafeBrowsingProvider... providers) {
      mSafeBrowsingProviders.clear();

      for (final SafeBrowsingProvider provider : providers) {
        mSafeBrowsingProviders.put(provider.getName(), new SafeBrowsingProvider(this, provider));
      }

      return this;
    }

    /**
     * Get the table for SafeBrowsing Phishing. The identifiers present in this table must match one
     * of the identifiers present in {@link SafeBrowsingProvider#getLists}.
     *
     * @return an array of identifiers for SafeBrowsing's Phishing feature
     * @see SafeBrowsingProvider.Builder#lists
     */
    public @NonNull String[] getSafeBrowsingPhishingTable() {
      return ContentBlocking.prefToLists(mSafeBrowsingPhishingTable.get());
    }

    /**
     * Sets the table for SafeBrowsing Phishing.
     *
     * @param table an array of identifiers for SafeBrowsing's Phishing feature.
     * @return this {@link Settings} instance.
     * @see SafeBrowsingProvider.Builder#lists
     */
    public @NonNull Settings setSafeBrowsingPhishingTable(final @NonNull String... table) {
      mSafeBrowsingPhishingTable.commit(ContentBlocking.listsToPref(table));
      return this;
    }

    /**
     * Get the table for SafeBrowsing Malware. The identifiers present in this table must match one
     * of the identifiers present in {@link SafeBrowsingProvider#getLists}.
     *
     * @return an array of identifiers for SafeBrowsing's Malware feature
     * @see SafeBrowsingProvider.Builder#lists
     */
    public @NonNull String[] getSafeBrowsingMalwareTable() {
      return ContentBlocking.prefToLists(mSafeBrowsingMalwareTable.get());
    }

    /**
     * Sets the allowed list for the query parameter stripping feature.
     *
     * @param list an array of identifiers for the allowed list of the query parameter's stripping
     *     feature.
     * @return this {@link Settings} instance.
     */
    public @NonNull Settings setQueryParameterStrippingAllowList(final @NonNull String... list) {
      mQueryParameterStrippingAllowList.commit(ContentBlocking.listsToPref(list));
      return this;
    }

    /**
     * Get the allowed list for the query parameter stripping feature.
     *
     * @return an array of identifiers for the allowed list for the query parameter stripping
     *     feature.
     */
    public @NonNull String[] getQueryParameterStrippingAllowList() {
      return ContentBlocking.prefToLists(mQueryParameterStrippingAllowList.get());
    }

    /**
     * Sets the strip list for the query parameter stripping feature.
     *
     * @param list an array of identifiers for the strip list of the query parameter's stripping
     *     feature.
     * @return this {@link Settings} instance.
     */
    public @NonNull Settings setQueryParameterStrippingStripList(final @NonNull String... list) {
      mQueryParameterStrippingStripList.commit(ContentBlocking.listsToPref(list));
      return this;
    }

    /**
     * Get the strip list for the query parameter stripping feature
     *
     * @return an array of identifiers for the allowed list for the query parameter stripping
     *     feature.
     */
    public @NonNull String[] getQueryParameterStrippingStripList() {
      return ContentBlocking.prefToLists(mQueryParameterStrippingStripList.get());
    }

    /**
     * Sets the table for SafeBrowsing Malware.
     *
     * @param table an array of identifiers for SafeBrowsing's Malware feature.
     * @return this {@link Settings} instance.
     * @see SafeBrowsingProvider.Builder#lists
     */
    public @NonNull Settings setSafeBrowsingMalwareTable(final @NonNull String... table) {
      mSafeBrowsingMalwareTable.commit(ContentBlocking.listsToPref(table));
      return this;
    }

    /**
     * Set anti-tracking categories.
     *
     * @param cat The categories of resources that should be blocked. Use one or more of the {@link
     *     ContentBlocking.AntiTracking} flags.
     * @return This Settings instance.
     */
    public @NonNull Settings setAntiTracking(final @CBAntiTracking int cat) {
      mAt.commit(ContentBlocking.catToAtPref(cat));

      mCm.commit(ContentBlocking.catToCmPref(cat));
      mCmList.commit(ContentBlocking.catToCmListPref(cat));

      mFp.commit(ContentBlocking.catToFpPref(cat));
      mFpList.commit(ContentBlocking.catToFpListPref(cat));

      mSt.commit(ContentBlocking.catToStPref(cat));
      mStList.commit(ContentBlocking.catToPref(cat, AntiTracking.STP, STP));

      mEtb.commit(ContentBlocking.catToEtbPref(cat));
      mEtbList.commit(ContentBlocking.catToPref(cat, AntiTracking.EMAIL, EMAIL));
      return this;
    }

    /**
     * Set the ETP behavior level.
     *
     * @param level The level of ETP blocking to use; must be one of {@link
     *     ContentBlocking.EtpLevel} flags. Only takes effect if the cookie behavior is {@link
     *     ContentBlocking.CookieBehavior#ACCEPT_NON_TRACKERS} or {@link
     *     ContentBlocking.CookieBehavior#ACCEPT_FIRST_PARTY_AND_ISOLATE_OTHERS}.
     * @return This Settings instance.
     */
    public @NonNull Settings setEnhancedTrackingProtectionLevel(final @CBEtpLevel int level) {
      mEtpEnabled.commit(
          level == ContentBlocking.EtpLevel.DEFAULT || level == ContentBlocking.EtpLevel.STRICT);
      mEtpStrict.commit(level == ContentBlocking.EtpLevel.STRICT);
      return this;
    }

    /**
     * Set whether or not strict social tracking protection is enabled (ie, whether to block content
     * or just cookies). Will only block if social tracking protection lists are supplied to {@link
     * #setAntiTracking}.
     *
     * @param enabled A boolean indicating whether or not to enable strict social tracking
     *     protection.
     * @return This Settings instance.
     */
    public @NonNull Settings setStrictSocialTrackingProtection(final boolean enabled) {
      mStStrict.commit(enabled);
      return this;
    }

    /**
     * Set safe browsing categories.
     *
     * @param cat The categories of resources that should be blocked. Use one or more of the {@link
     *     ContentBlocking.SafeBrowsing} flags.
     * @return This Settings instance.
     */
    public @NonNull Settings setSafeBrowsing(final @CBSafeBrowsing int cat) {
      mSbMalware.commit(ContentBlocking.catToSbMalware(cat));
      mSbPhishing.commit(ContentBlocking.catToSbPhishing(cat));
      return this;
    }

    /**
     * Get the set anti-tracking categories.
     *
     * @return The categories of resources to be blocked.
     */
    public @CBAntiTracking int getAntiTrackingCategories() {
      return ContentBlocking.atListToAtCat(mAt.get())
          | ContentBlocking.cmListToAtCat(mCmList.get())
          | ContentBlocking.fpListToAtCat(mFpList.get())
          | ContentBlocking.stListToAtCat(mStList.get())
          | ContentBlocking.etbListToAtCat(mEtbList.get());
    }

    /**
     * Get the set ETP behavior level.
     *
     * @return The current ETP level; one of {@link ContentBlocking.EtpLevel}.
     */
    public @CBEtpLevel int getEnhancedTrackingProtectionLevel() {
      if (mEtpStrict.get()) {
        return ContentBlocking.EtpLevel.STRICT;
      } else if (mEtpEnabled.get()) {
        return ContentBlocking.EtpLevel.DEFAULT;
      }
      return ContentBlocking.EtpLevel.NONE;
    }

    /**
     * Get whether or not strict social tracking protection is enabled.
     *
     * @return A boolean indicating whether or not strict social tracking protection is enabled.
     */
    public boolean getStrictSocialTrackingProtection() {
      return mStStrict.get();
    }

    /**
     * Get the set safe browsing categories.
     *
     * @return The categories of resources to be blocked.
     */
    public @CBSafeBrowsing int getSafeBrowsingCategories() {
      return ContentBlocking.sbMalwareToSbCat(mSbMalware.get())
          | ContentBlocking.sbPhishingToSbCat(mSbPhishing.get());
    }

    /**
     * Get the assigned cookie storage behavior.
     *
     * @return The assigned behavior, as one of {@link CookieBehavior} flags.
     */
    @SuppressLint("WrongConstant")
    public @CBCookieBehavior int getCookieBehavior() {
      return mCookieBehavior.get();
    }

    /**
     * Set cookie storage behavior.
     *
     * @param behavior The storage behavior that should be applied. Use one of the {@link
     *     CookieBehavior} flags.
     * @return This Settings instance.
     */
    public @NonNull Settings setCookieBehavior(final @CBCookieBehavior int behavior) {
      mCookieBehavior.commit(behavior);
      return this;
    }

    /**
     * Get the assigned private mode cookie storage behavior.
     *
     * @return The assigned behavior, as one of {@link CookieBehavior} flags.
     */
    @SuppressLint("WrongConstant")
    public @CBCookieBehavior int getCookieBehaviorPrivateMode() {
      return mCookieBehaviorPrivateMode.get();
    }

    /**
     * Set cookie storage behavior for private browsing mode.
     *
     * @param behavior The storage behavior that should be applied. Use one of the {@link
     *     CookieBehavior} flags.
     * @return This Settings instance.
     */
    public @NonNull Settings setCookieBehaviorPrivateMode(final @CBCookieBehavior int behavior) {
      mCookieBehaviorPrivateMode.commit(behavior);
      return this;
    }

    /**
     * Get whether or not cookie purging is enabled.
     *
     * @return A boolean indicating whether or not cookie purging is enabled.
     */
    public boolean getCookiePurging() {
      return mCookiePurging.get();
    }

    /**
     * Enable or disable cookie purging. This will automatically purge cookies from tracking sites
     * that have no recent user interaction, provided the cookie behavior is set to {@link
     * ContentBlocking.CookieBehavior#ACCEPT_NON_TRACKERS} or {@link
     * ContentBlocking.CookieBehavior#ACCEPT_FIRST_PARTY_AND_ISOLATE_OTHERS}.
     *
     * @param enabled A boolean indicating whether to enable cookie purging.
     * @return This Settings instance.
     */
    public @NonNull Settings setCookiePurging(final boolean enabled) {
      mCookiePurging.commit(enabled);
      return this;
    }

    /**
     * Set the Cookie Banner Handling Mode to the new provided {@link CBCookieBannerMode} value.
     *
     * @param mode Integer indicating the new mode.
     * @return This Settings instance.
     */
    public @NonNull Settings setCookieBannerMode(final @CBCookieBannerMode int mode) {
      mCbhMode.commit(mode);
      return this;
    }

    /**
     * When set to true, cookie banners are detected and detection events are dispatched, but they
     * will not be handled. Requires the service to be enabled for the desired mode via
     * setCookieBannerMode.
     *
     * @param enabled A boolean indicating whether to enable cookie banners.
     * @return This Settings instance.
     */
    public @NonNull Settings setCookieBannerDetectOnlyMode(final boolean enabled) {
      mChbDetectOnlyMode.commit(enabled);
      return this;
    }

    /**
     * Enables/disables the use of global CookieBannerRules, which apply to all sites. This enable
     * handling of CMPs across sites without the use of site-specific rules.
     *
     * @param enabled A boolean indicating whether or not to enable.
     * @return This Settings instance.
     */
    public @NonNull Settings setCookieBannerGlobalRulesEnabled(final boolean enabled) {
      mCbhGlobalRulesEnabled.commit(enabled);
      return this;
    }

    /**
     * Indicates if global CookieBannerRules is enabled or not.
     *
     * @return Indicates if global CookieBannerRule is enabled or disabled.
     */
    public boolean getCookieBannerGlobalRulesEnabled() {
      return mCbhGlobalRulesEnabled.get();
    }

    /**
     * Whether global rules are allowed to run in sub-frames. Running query selectors in every
     * sub-frame may negatively impact performance, but is required for some CMPs.
     *
     * @param enabled A boolean indicating whether or not to enable.
     * @return This Settings instance.
     */
    public @NonNull Settings setCookieBannerGlobalRulesSubFramesEnabled(final boolean enabled) {
      mCbhGlobalRulesSubFramesEnabled.commit(enabled);
      return this;
    }

    /**
     * Indicates if email tracker blocking is enabled in private mode.
     *
     * @return Indicates if email tracker blocking is enabled or disabled in private mode.
     */
    public @NonNull Boolean getEmailTrackerBlockingPrivateBrowsingEnabled() {
      return mEtbPrivateBrowsing.get();
    }

    /**
     * Sets whether email tracker blocking is enabled in private mode.
     *
     * @param enabled A boolean indicating whether or not to enable.
     * @return This Settings instance.
     */
    public @NonNull Settings setEmailTrackerBlockingPrivateBrowsing(final boolean enabled) {
      mEtbPrivateBrowsing.commit(enabled);
      return this;
    }

    /**
     * Sets whether query parameter stripping is enabled in normal mode.
     *
     * @param enabled A boolean indicating whether or not to enable.
     * @return This Settings instance.
     */
    public @NonNull Settings setQueryParameterStrippingEnabled(final boolean enabled) {
      mQueryParameterStrippingEnabled.commit(enabled);
      return this;
    }

    /**
     * Indicates if query parameter stripping is enabled in normal mode.
     *
     * @return Indicates if query parameter stripping is enabled or disabled in normal mode.
     */
    public boolean getQueryParameterStrippingEnabled() {
      return mQueryParameterStrippingEnabled.get();
    }

    /**
     * Sets Whether query parameter stripping is enabled in private mode.
     *
     * @param enabled A boolean indicating whether or not to enable in private mode.
     * @return This Settings instance.
     */
    public @NonNull Settings setQueryParameterStrippingPrivateBrowsingEnabled(
        final boolean enabled) {
      mQueryParameterStrippingPrivateBrowsingEnabled.commit(enabled);
      return this;
    }

    /**
     * Indicates if query parameter stripping is enabled in private mode.
     *
     * @return Indicates if global CookieBannerRules is enabled or disabled in sub-frames.
     */
    public boolean getQueryParameterStrippingPrivateBrowsingEnabled() {
      return mQueryParameterStrippingPrivateBrowsingEnabled.get();
    }

    /**
     * Indicates if global CookieBannerRules is enabled or not in sub-frames.
     *
     * @return Indicates if global CookieBannerRules is enabled or disabled in sub-frames.
     */
    public boolean getCookieBannerGlobalRulesSubFramesEnabled() {
      return mCbhGlobalRulesSubFramesEnabled.get();
    }

    /**
     * Indicates if cookie banner handling detect only mode is enabled.
     *
     * @return boolean indicating if the cookie banner handling detect only mode setting is enabled.
     */
    public boolean getCookieBannerDetectOnlyMode() {
      return mChbDetectOnlyMode.get();
    }

    /**
     * Gets the current cookie banner handling mode.
     *
     * @return int the current cookie banner handling mode, one of the {@link CBCookieBannerMode}.
     */
    @SuppressLint("WrongConstant")
    public @CBCookieBannerMode int getCookieBannerMode() {
      return mCbhMode.get();
    }

    /**
     * Set the Cookie Banner Handling Mode for private browsing to the new provided {@link
     * CBCookieBannerMode} value.
     *
     * @param mode Integer indicating the new mode.
     * @return This Settings instance.
     */
    public @NonNull Settings setCookieBannerModePrivateBrowsing(
        final @CBCookieBannerMode int mode) {
      mCbhModePrivateBrowsing.commit(mode);
      return this;
    }

    /**
     * Gets the current cookie banner handling mode for private browsing.
     *
     * @return int the current cookie banner handling mode, one of the {@link CBCookieBannerMode}.
     */
    @SuppressLint("WrongConstant")
    public @CBCookieBannerMode int getCookieBannerModePrivateBrowsing() {
      return mCbhModePrivateBrowsing.get();
    }

    public static final Parcelable.Creator<Settings> CREATOR =
        new Parcelable.Creator<Settings>() {
          @Override
          public Settings createFromParcel(final Parcel in) {
            final Settings settings = new Settings();
            settings.readFromParcel(in);
            return settings;
          }

          @Override
          public Settings[] newArray(final int size) {
            return new Settings[size];
          }
        };
  }

  /**
   * Holds configuration for a SafeBrowsing provider. <br>
   * <br>
   * This class can be used to modify existing configuration for SafeBrowsing providers or to add a
   * custom SafeBrowsing provider to the app. <br>
   * <br>
   * Default configuration for Google's SafeBrowsing servers can be found at {@link
   * ContentBlocking#GOOGLE_SAFE_BROWSING_PROVIDER} and {@link
   * ContentBlocking#GOOGLE_LEGACY_SAFE_BROWSING_PROVIDER}. <br>
   * <br>
   * This class is immutable, once constructed its values cannot be changed. <br>
   * <br>
   * You can, however, use the {@link #from} method to build upon an existing configuration. For
   * example to override the Google's server configuration, you can do the following: <br>
   *
   * <pre><code>
   *     SafeBrowsingProvider override = SafeBrowsingProvider
   *         .from(ContentBlocking.GOOGLE_SAFE_BROWSING_PROVIDER)
   *         .getHashUrl("http://my-custom-server.com/...")
   *         .updateUrl("http://my-custom-server.com/...")
   *         .build();
   *
   *     runtime.getContentBlocking().setSafeBrowsingProviders(override);
   * </code></pre>
   *
   * This will override the configuration. <br>
   * <br>
   * You can also add a custom SafeBrowsing provider using the {@link #withName} method. For
   * example, to add a custom provider that provides the list <code>testprovider-phish-digest256
   * </code> do the following: <br>
   *
   * <pre><code>
   *     SafeBrowsingProvider custom = SafeBrowsingProvider
   *         .withName("custom-provider")
   *         .version("2.2")
   *         .lists("testprovider-phish-digest256")
   *         .updateUrl("http://my-custom-server2.com/...")
   *         .getHashUrl("http://my-custom-server2.com/...")
   *         .build();
   * </code></pre>
   *
   * And then add the custom provider (adding optionally existing providers): <br>
   *
   * <pre><code>
   *     runtime.getContentBlocking().setSafeBrowsingProviders(
   *         custom,
   *         // Add this if you want to keep the existing configuration too.
   *         ContentBlocking.GOOGLE_SAFE_BROWSING_PROVIDER,
   *         ContentBlocking.GOOGLE_LEGACY_SAFE_BROWSING_PROVIDER);
   * </code></pre>
   *
   * And set the list in the phishing configuration <br>
   *
   * <pre><code>
   *     runtime.getContentBlocking().setSafeBrowsingPhishingTable(
   *          "testprovider-phish-digest256",
   *          // Existing configuration
   *          "goog-phish-proto");
   * </code></pre>
   *
   * Note that any list present in the phishing or malware tables need to appear in one safe
   * browsing provider's {@link #getLists} property.
   *
   * <p>See also <a href="https://developers.google.com/safe-browsing/v4">safe-browsing/v4</a>.
   */
  @AnyThread
  public static class SafeBrowsingProvider extends RuntimeSettings {
    private static final String ROOT = "browser.safebrowsing.provider.";

    private final String mName;

    /* package */ final Pref<String> mVersion;
    /* package */ final Pref<String> mLists;
    /* package */ final Pref<String> mUpdateUrl;
    /* package */ final Pref<String> mGetHashUrl;
    /* package */ final Pref<String> mReportUrl;
    /* package */ final Pref<String> mReportPhishingMistakeUrl;
    /* package */ final Pref<String> mReportMalwareMistakeUrl;
    /* package */ final Pref<String> mAdvisoryUrl;
    /* package */ final Pref<String> mAdvisoryName;
    /* package */ final Pref<String> mDataSharingUrl;
    /* package */ final Pref<Boolean> mDataSharingEnabled;

    /**
     * Creates a {@link SafeBrowsingProvider.Builder} for a provider with the given name.
     *
     * <p>Note: the <code>mozilla</code> name is reserved for internal use, and this method will
     * throw if you attempt to build a provider with that name.
     *
     * @param name The name of the provider.
     * @return a {@link Builder} instance that can be used to build a provider.
     * @throws IllegalArgumentException if this method is called with <code>name="mozilla"</code>
     */
    @NonNull
    public static Builder withName(final @NonNull String name) {
      if ("mozilla".equals(name)) {
        throw new IllegalArgumentException("The 'mozilla' name is reserved for internal use.");
      }
      return new Builder(name);
    }

    /**
     * Creates a {@link SafeBrowsingProvider.Builder} based on the given provider.
     *
     * <p>All properties not otherwise specified will be copied from the provider given in input.
     *
     * @param provider The source provider for this builder.
     * @return a {@link Builder} instance that can be used to create a configuration based on the
     *     builder in input.
     */
    @NonNull
    public static Builder from(final @NonNull SafeBrowsingProvider provider) {
      return new Builder(provider);
    }

    @AnyThread
    public static class Builder {
      final SafeBrowsingProvider mProvider;

      private Builder(final String name) {
        mProvider = new SafeBrowsingProvider(name);
      }

      private Builder(final SafeBrowsingProvider source) {
        mProvider = new SafeBrowsingProvider(source);
      }

      /**
       * Sets the SafeBrowsing protocol session for this provider.
       *
       * @param version the version strong, e.g. "2.2" or "4".
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder version(final @NonNull String version) {
        mProvider.mVersion.set(version);
        return this;
      }

      /**
       * Sets the lists provided by this provider.
       *
       * @param lists one or more lists for this provider, e.g. "goog-malware-proto",
       *     "goog-unwanted-proto"
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder lists(final @NonNull String... lists) {
        mProvider.mLists.set(ContentBlocking.listsToPref(lists));
        return this;
      }

      /**
       * Sets the url that will be used to update the threat list for this provider.
       *
       * <p>See also <a
       * href="https://developers.google.com/safe-browsing/v4/reference/rest/v4/threatListUpdates/fetch">
       * v4/threadListUpdates/fetch </a>.
       *
       * @param updateUrl the update url endpoint for this provider
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder updateUrl(final @NonNull String updateUrl) {
        mProvider.mUpdateUrl.set(updateUrl);
        return this;
      }

      /**
       * Sets the url that will be used to get the full hashes that match a partial hash.
       *
       * <p>See also <a
       * href="https://developers.google.com/safe-browsing/v4/reference/rest/v4/fullHashes/find">
       * v4/fullHashes/find </a>.
       *
       * @param getHashUrl the gethash url endpoint for this provider
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder getHashUrl(final @NonNull String getHashUrl) {
        mProvider.mGetHashUrl.set(getHashUrl);
        return this;
      }

      /**
       * Set the url that will be used to report a url to the SafeBrowsing provider.
       *
       * @param reportUrl the url endpoint to report a url to this provider.
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder reportUrl(final @NonNull String reportUrl) {
        mProvider.mReportUrl.set(reportUrl);
        return this;
      }

      /**
       * Set the url that will be used to report a url mistakenly reported as Phishing to the
       * SafeBrowsing provider.
       *
       * @param reportPhishingMistakeUrl the url endpoint to report a url to this provider.
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder reportPhishingMistakeUrl(
          final @NonNull String reportPhishingMistakeUrl) {
        mProvider.mReportPhishingMistakeUrl.set(reportPhishingMistakeUrl);
        return this;
      }

      /**
       * Set the url that will be used to report a url mistakenly reported as Malware to the
       * SafeBrowsing provider.
       *
       * @param reportMalwareMistakeUrl the url endpoint to report a url to this provider.
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder reportMalwareMistakeUrl(
          final @NonNull String reportMalwareMistakeUrl) {
        mProvider.mReportMalwareMistakeUrl.set(reportMalwareMistakeUrl);
        return this;
      }

      /**
       * Set the url that will be used to give a general advisory about this SafeBrowsing provider.
       *
       * @param advisoryUrl the adivisory page url for this provider.
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder advisoryUrl(final @NonNull String advisoryUrl) {
        mProvider.mAdvisoryUrl.set(advisoryUrl);
        return this;
      }

      /**
       * Set the advisory name for this provider.
       *
       * @param advisoryName the adivisory name for this provider.
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder advisoryName(final @NonNull String advisoryName) {
        mProvider.mAdvisoryName.set(advisoryName);
        return this;
      }

      /**
       * Set url to share threat data to the provider, if enabled by {@link #dataSharingEnabled}.
       *
       * @param dataSharingUrl the url endpoint
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder dataSharingUrl(final @NonNull String dataSharingUrl) {
        mProvider.mDataSharingUrl.set(dataSharingUrl);
        return this;
      }

      /**
       * Set whether to share threat data with the provider, off by default.
       *
       * @param dataSharingEnabled <code>true</code> if the browser should share threat data with
       *     the provider.
       * @return this {@link Builder} instance.
       */
      public @NonNull Builder dataSharingEnabled(final boolean dataSharingEnabled) {
        mProvider.mDataSharingEnabled.set(dataSharingEnabled);
        return this;
      }

      /**
       * Build the {@link SafeBrowsingProvider} based on this {@link Builder} instance.
       *
       * @return thie {@link SafeBrowsingProvider} instance.
       */
      public @NonNull SafeBrowsingProvider build() {
        return new SafeBrowsingProvider(mProvider);
      }
    }

    /* package */ SafeBrowsingProvider(final SafeBrowsingProvider source) {
      this(/* name */ null, /* parent */ null, source);
    }

    /* package */ SafeBrowsingProvider(
        final RuntimeSettings parent, final SafeBrowsingProvider source) {
      this(/* name */ null, parent, source);
    }

    /* package */ SafeBrowsingProvider(final String name) {
      this(name, /* parent */ null, /* source */ null);
    }

    /* package */ SafeBrowsingProvider(
        final String name, final RuntimeSettings parent, final SafeBrowsingProvider source) {
      super(parent);

      if (name != null) {
        mName = name;
      } else if (source != null) {
        mName = source.mName;
      } else {
        throw new IllegalArgumentException("Either name or source must be non-null");
      }

      mVersion = new Pref<>(ROOT + mName + ".pver", null);
      mLists = new Pref<>(ROOT + mName + ".lists", null);
      mUpdateUrl = new Pref<>(ROOT + mName + ".updateURL", null);
      mGetHashUrl = new Pref<>(ROOT + mName + ".gethashURL", null);
      mReportUrl = new Pref<>(ROOT + mName + ".reportURL", null);
      mReportPhishingMistakeUrl = new Pref<>(ROOT + mName + ".reportPhishMistakeURL", null);
      mReportMalwareMistakeUrl = new Pref<>(ROOT + mName + ".reportMalwareMistakeURL", null);
      mAdvisoryUrl = new Pref<>(ROOT + mName + ".advisoryURL", null);
      mAdvisoryName = new Pref<>(ROOT + mName + ".advisoryName", null);
      mDataSharingUrl = new Pref<>(ROOT + mName + ".dataSharingURL", null);
      mDataSharingEnabled = new Pref<>(ROOT + mName + ".dataSharing.enabled", false);

      if (source != null) {
        updatePrefs(source);
      }
    }

    /**
     * Get the name of this provider.
     *
     * @return a string containing the name.
     */
    public @NonNull String getName() {
      return mName;
    }

    /**
     * Get the version for this provider.
     *
     * @return a string representing the version, e.g. "2.2" or "4".
     */
    public @Nullable String getVersion() {
      return mVersion.get();
    }

    /**
     * Get the lists provided by this provider.
     *
     * @return an array of string identifiers for the lists
     */
    public @NonNull String[] getLists() {
      return ContentBlocking.prefToLists(mLists.get());
    }

    /**
     * Get the url that will be used to update the threat list for this provider.
     *
     * <p>See also <a
     * href="https://developers.google.com/safe-browsing/v4/reference/rest/v4/threatListUpdates/fetch">
     * v4/threadListUpdates/fetch </a>.
     *
     * @return a string containing the URL.
     */
    public @Nullable String getUpdateUrl() {
      return mUpdateUrl.get();
    }

    /**
     * Get the url that will be used to get the full hashes that match a partial hash.
     *
     * <p>See also <a
     * href="https://developers.google.com/safe-browsing/v4/reference/rest/v4/fullHashes/find">
     * v4/fullHashes/find </a>.
     *
     * @return a string containing the URL.
     */
    public @Nullable String getGetHashUrl() {
      return mGetHashUrl.get();
    }

    /**
     * Get the url that will be used to report a url to the SafeBrowsing provider.
     *
     * @return a string containing the URL.
     */
    public @Nullable String getReportUrl() {
      return mReportUrl.get();
    }

    /**
     * Get the url that will be used to report a url mistakenly reported as Phishing to the
     * SafeBrowsing provider.
     *
     * @return a string containing the URL.
     */
    public @Nullable String getReportPhishingMistakeUrl() {
      return mReportPhishingMistakeUrl.get();
    }

    /**
     * Get the url that will be used to report a url mistakenly reported as Malware to the
     * SafeBrowsing provider.
     *
     * @return a string containing the URL.
     */
    public @Nullable String getReportMalwareMistakeUrl() {
      return mReportMalwareMistakeUrl.get();
    }

    /**
     * Get the url that will be used to give a general advisory about this SafeBrowsing provider.
     *
     * @return a string containing the URL.
     */
    public @Nullable String getAdvisoryUrl() {
      return mAdvisoryUrl.get();
    }

    /**
     * Get the advisory name for this provider.
     *
     * @return a string containing the URL.
     */
    public @Nullable String getAdvisoryName() {
      return mAdvisoryName.get();
    }

    /**
     * Get the url to share threat data to the provider, if enabled by {@link
     * #getDataSharingEnabled}.
     *
     * @return this {@link Builder} instance.
     */
    public @Nullable String getDataSharingUrl() {
      return mDataSharingUrl.get();
    }

    /**
     * Get whether to share threat data with the provider.
     *
     * @return <code>true</code> if the browser should whare threat data with the provider, <code>
     *     false</code> otherwise.
     */
    public @Nullable Boolean getDataSharingEnabled() {
      return mDataSharingEnabled.get();
    }

    @Override // Parcelable
    @AnyThread
    public void writeToParcel(final Parcel out, final int flags) {
      out.writeValue(mName);
      super.writeToParcel(out, flags);
    }

    /** Creator instance for this class. */
    public static final Parcelable.Creator<SafeBrowsingProvider> CREATOR =
        new Parcelable.Creator<SafeBrowsingProvider>() {
          @Override
          public SafeBrowsingProvider createFromParcel(final Parcel source) {
            final String name = (String) source.readValue(getClass().getClassLoader());
            final SafeBrowsingProvider settings = new SafeBrowsingProvider(name);
            settings.readFromParcel(source);
            return settings;
          }

          @Override
          public SafeBrowsingProvider[] newArray(final int size) {
            return new SafeBrowsingProvider[size];
          }
        };
  }

  private static String listsToPref(final String... lists) {
    final StringBuilder prefBuilder = new StringBuilder();

    for (final String list : lists) {
      if (list.contains(",")) {
        // We use ',' as the separator, so the list name cannot contain it.
        // Should never happen.
        throw new IllegalArgumentException("List name cannot contain ',' character.");
      }

      prefBuilder.append(list);
      prefBuilder.append(",");
    }

    // Remove trailing ","
    if (lists.length > 0) {
      prefBuilder.setLength(prefBuilder.length() - 1);
    }

    return prefBuilder.toString();
  }

  private static String[] prefToLists(final String pref) {
    return pref != null ? pref.split(",") : new String[] {};
  }

  public static class AntiTracking {
    public static final int NONE = 0;

    /** Block advertisement trackers. */
    public static final int AD = 1 << 1;

    /** Block analytics trackers. */
    public static final int ANALYTIC = 1 << 2;

    /**
     * Block social trackers. Note: This is not the same as "Social Tracking Protection", which is
     * controlled by {@link #STP}.
     */
    public static final int SOCIAL = 1 << 3;

    /** Block content trackers. May cause issues with some web sites. */
    public static final int CONTENT = 1 << 4;

    /** Block Gecko test trackers (used for tests). */
    public static final int TEST = 1 << 5;

    /** Block cryptocurrency miners. */
    public static final int CRYPTOMINING = 1 << 6;

    /** Block fingerprinting trackers. */
    public static final int FINGERPRINTING = 1 << 7;

    /** Block trackers on the Social Tracking Protection list. */
    public static final int STP = 1 << 8;

    /** Block email trackers */
    public static final int EMAIL = 1 << 9;

    /** Block ad, analytic, social and test trackers. */
    public static final int DEFAULT = AD | ANALYTIC | SOCIAL | TEST;

    /** Block all known trackers. May cause issues with some web sites. */
    public static final int STRICT = DEFAULT | CONTENT | CRYPTOMINING | FINGERPRINTING | EMAIL;

    protected AntiTracking() {}
  }

  @Retention(RetentionPolicy.SOURCE)
  @IntDef(
      flag = true,
      value = {
        AntiTracking.AD,
        AntiTracking.ANALYTIC,
        AntiTracking.SOCIAL,
        AntiTracking.CONTENT,
        AntiTracking.TEST,
        AntiTracking.CRYPTOMINING,
        AntiTracking.FINGERPRINTING,
        AntiTracking.DEFAULT,
        AntiTracking.STRICT,
        AntiTracking.STP,
        AntiTracking.EMAIL,
        AntiTracking.NONE
      })
  public @interface CBAntiTracking {}

  public static class SafeBrowsing {
    public static final int NONE = 0;

    /** Block malware sites. */
    public static final int MALWARE = 1 << 10;

    /** Block unwanted sites. */
    public static final int UNWANTED = 1 << 11;

    /** Block harmful sites. */
    public static final int HARMFUL = 1 << 12;

    /** Block phishing sites. */
    public static final int PHISHING = 1 << 13;

    /** Block all unsafe sites. */
    public static final int DEFAULT = MALWARE | UNWANTED | HARMFUL | PHISHING;

    protected SafeBrowsing() {}
  }

  @Retention(RetentionPolicy.SOURCE)
  @IntDef(
      flag = true,
      value = {
        SafeBrowsing.MALWARE, SafeBrowsing.UNWANTED,
        SafeBrowsing.HARMFUL, SafeBrowsing.PHISHING,
        SafeBrowsing.DEFAULT, SafeBrowsing.NONE
      })
  public @interface CBSafeBrowsing {}

  // Sync values with nsICookieService.idl.
  public static class CookieBehavior {
    /** Accept first-party and third-party cookies and site data. */
    public static final int ACCEPT_ALL = 0;

    /**
     * Accept only first-party cookies and site data to block cookies which are not associated with
     * the domain of the visited site.
     */
    public static final int ACCEPT_FIRST_PARTY = 1;

    /** Do not store any cookies and site data. */
    public static final int ACCEPT_NONE = 2;

    /**
     * Accept first-party and third-party cookies and site data only from sites previously visited
     * in a first-party context.
     */
    public static final int ACCEPT_VISITED = 3;

    /**
     * Accept only first-party and non-tracking third-party cookies and site data to block cookies
     * which are not associated with the domain of the visited site set by known trackers.
     */
    public static final int ACCEPT_NON_TRACKERS = 4;

    /**
     * Enable dynamic first party isolation (dFPI); this will block third-party tracking cookies in
     * accordance with the ETP level and isolate non-tracking third-party cookies.
     */
    public static final int ACCEPT_FIRST_PARTY_AND_ISOLATE_OTHERS = 5;

    protected CookieBehavior() {}
  }

  @Retention(RetentionPolicy.SOURCE)
  @IntDef({
    CookieBehavior.ACCEPT_ALL, CookieBehavior.ACCEPT_FIRST_PARTY,
    CookieBehavior.ACCEPT_NONE, CookieBehavior.ACCEPT_VISITED,
    CookieBehavior.ACCEPT_NON_TRACKERS
  })
  public @interface CBCookieBehavior {}

  @Retention(RetentionPolicy.SOURCE)
  @IntDef({EtpLevel.NONE, EtpLevel.DEFAULT, EtpLevel.STRICT})
  public @interface CBEtpLevel {}

  /** Possible settings for ETP. */
  public static class EtpLevel {
    /** Do not enable ETP at all. */
    public static final int NONE = 0;

    /** Enable ETP for ads, analytic, and social tracking lists. */
    public static final int DEFAULT = 1;

    /**
     * Enable ETP for all of the default lists as well as the content list. May break many sites!
     */
    public static final int STRICT = 2;
  }

  /** Holds content block event details. */
  public static class BlockEvent {
    /** The URI of the blocked resource. */
    public final @NonNull String uri;

    private final @CBAntiTracking int mAntiTrackingCat;
    private final @CBSafeBrowsing int mSafeBrowsingCat;
    private final @CBCookieBehavior int mCookieBehaviorCat;
    private final boolean mIsBlocking;

    @SuppressWarnings("checkstyle:javadocmethod")
    public BlockEvent(
        @NonNull final String uri,
        final @CBAntiTracking int atCat,
        final @CBSafeBrowsing int sbCat,
        final @CBCookieBehavior int cbCat,
        final boolean isBlocking) {
      this.uri = uri;
      this.mAntiTrackingCat = atCat;
      this.mSafeBrowsingCat = sbCat;
      this.mCookieBehaviorCat = cbCat;
      this.mIsBlocking = isBlocking;
    }

    /**
     * The anti-tracking category types of the blocked resource.
     *
     * @return One or more of the {@link AntiTracking} flags.
     */
    @UiThread
    public @CBAntiTracking int getAntiTrackingCategory() {
      return mAntiTrackingCat;
    }

    /**
     * The safe browsing category types of the blocked resource.
     *
     * @return One or more of the {@link SafeBrowsing} flags.
     */
    @UiThread
    public @CBSafeBrowsing int getSafeBrowsingCategory() {
      return mSafeBrowsingCat;
    }

    /**
     * The cookie types of the blocked resource.
     *
     * @return One or more of the {@link CookieBehavior} flags.
     */
    @UiThread
    public @CBCookieBehavior int getCookieBehaviorCategory() {
      return mCookieBehaviorCat;
    }

    /* package */ static BlockEvent fromBundle(@NonNull final GeckoBundle bundle) {
      final String uri = bundle.getString("uri");
      final String blockedList = bundle.getString("blockedList");
      final String loadedList = TextUtils.join(",", bundle.getStringArray("loadedLists"));
      final long error = bundle.getLong("error", 0L);
      final long category = bundle.getLong("category", 0L);

      final String matchedList = blockedList != null ? blockedList : loadedList;

      // Note: Even if loadedList is non-empty it does not necessarily
      // mean that the event is not a blocking event.
      final boolean blocking =
          (blockedList != null || error != 0L || ContentBlocking.isBlockingGeckoCbCat(category));

      return new BlockEvent(
          uri,
          ContentBlocking.atListToAtCat(matchedList)
              | ContentBlocking.cmListToAtCat(matchedList)
              | ContentBlocking.fpListToAtCat(matchedList)
              | ContentBlocking.stListToAtCat(matchedList)
              | ContentBlocking.etbListToAtCat(matchedList),
          ContentBlocking.errorToSbCat(error),
          ContentBlocking.geckoCatToCbCat(category),
          blocking);
    }

    @UiThread
    @SuppressWarnings("checkstyle:javadocmethod")
    public boolean isBlocking() {
      return mIsBlocking;
    }
  }

  /** GeckoSession applications implement this interface to handle content blocking events. */
  public interface Delegate {
    /**
     * A content element has been blocked from loading. Set blocked element categories via {@link
     * GeckoRuntimeSettings} and enable content blocking via {@link GeckoSessionSettings}.
     *
     * @param session The GeckoSession that initiated the callback.
     * @param event The {@link BlockEvent} details.
     */
    @UiThread
    default void onContentBlocked(
        @NonNull final GeckoSession session, @NonNull final BlockEvent event) {}

    /**
     * A content element that could be blocked has been loaded.
     *
     * @param session The GeckoSession that initiated the callback.
     * @param event The {@link BlockEvent} details.
     */
    @UiThread
    default void onContentLoaded(
        @NonNull final GeckoSession session, @NonNull final BlockEvent event) {}
  }

  private static final String TEST = "moztest-track-simple";
  private static final String AD = "ads-track-digest256";
  private static final String ANALYTIC = "analytics-track-digest256";
  private static final String SOCIAL = "social-track-digest256";
  private static final String CONTENT = "content-track-digest256";
  private static final String CRYPTOMINING = "base-cryptomining-track-digest256";
  private static final String FINGERPRINTING = "base-fingerprinting-track-digest256";
  private static final String STP =
      "social-tracking-protection-facebook-digest256,social-tracking-protection-linkedin-digest256,social-tracking-protection-twitter-digest256";
  private static final String EMAIL = "base-email-track-digest256";

  /* package */ static @CBSafeBrowsing int sbMalwareToSbCat(final boolean enabled) {
    return enabled
        ? (SafeBrowsing.MALWARE | SafeBrowsing.UNWANTED | SafeBrowsing.HARMFUL)
        : SafeBrowsing.NONE;
  }

  /* package */ static @CBSafeBrowsing int sbPhishingToSbCat(final boolean enabled) {
    return enabled ? SafeBrowsing.PHISHING : SafeBrowsing.NONE;
  }

  /* package */ static boolean catToSbMalware(@CBAntiTracking final int cat) {
    return (cat & (SafeBrowsing.MALWARE | SafeBrowsing.UNWANTED | SafeBrowsing.HARMFUL)) != 0;
  }

  /* package */ static boolean catToSbPhishing(@CBAntiTracking final int cat) {
    return (cat & SafeBrowsing.PHISHING) != 0;
  }

  /* package */ static String catToAtPref(@CBAntiTracking final int cat) {
    final StringBuilder builder = new StringBuilder();

    if ((cat & AntiTracking.TEST) != 0) {
      builder.append(TEST).append(',');
    }
    if ((cat & AntiTracking.AD) != 0) {
      builder.append(AD).append(',');
    }
    if ((cat & AntiTracking.ANALYTIC) != 0) {
      builder.append(ANALYTIC).append(',');
    }
    if ((cat & AntiTracking.SOCIAL) != 0) {
      builder.append(SOCIAL).append(',');
    }
    if ((cat & AntiTracking.CONTENT) != 0) {
      builder.append(CONTENT).append(',');
    }
    if (builder.length() == 0) {
      return "";
    }
    // Trim final ','.
    return builder.substring(0, builder.length() - 1);
  }

  /* package */ static boolean catToCmPref(@CBAntiTracking final int cat) {
    return (cat & AntiTracking.CRYPTOMINING) != 0;
  }

  /* package */ static String catToCmListPref(@CBAntiTracking final int cat) {
    final StringBuilder builder = new StringBuilder();

    if ((cat & AntiTracking.CRYPTOMINING) != 0) {
      builder.append(CRYPTOMINING);
    }
    return builder.toString();
  }

  /* package */ static boolean catToFpPref(@CBAntiTracking final int cat) {
    return (cat & AntiTracking.FINGERPRINTING) != 0;
  }

  /* package */ static String catToFpListPref(@CBAntiTracking final int cat) {
    final StringBuilder builder = new StringBuilder();

    if ((cat & AntiTracking.FINGERPRINTING) != 0) {
      builder.append(FINGERPRINTING);
    }
    return builder.toString();
  }

  /* package */ static @CBAntiTracking int fpListToAtCat(final String list) {
    int cat = AntiTracking.NONE;
    if (list == null) {
      return cat;
    }
    if (list.indexOf(FINGERPRINTING) != -1) {
      cat |= AntiTracking.FINGERPRINTING;
    }
    return cat;
  }

  /* package */ static boolean catToStPref(@CBAntiTracking final int cat) {
    return (cat & AntiTracking.STP) != 0;
  }

  /* package */ static boolean catToEtbPref(@CBAntiTracking final int cat) {
    return (cat & AntiTracking.EMAIL) != 0;
  }

  /**
   * Generic method for converting a category of anti-tracking to a Pref.
   *
   * @param cat Int representing the enabled anti-tracking blockers.
   * @param tbCat Int representing the category mask to check for.
   * @param catPrefString String to return if [cat] contains [tbCat].
   * @return Pref string if [cat] contains [tbCat] otherwise empty string.
   */
  /* package */ static String catToPref(
      @CBAntiTracking final int cat, final int tbCat, final String catPrefString) {
    if ((cat & tbCat) != 0) {
      return catPrefString;
    } else {
      return "";
    }
  }

  /* package */ static @CBAntiTracking int atListToAtCat(final String list) {
    int cat = AntiTracking.NONE;

    if (list == null) {
      return cat;
    }
    if (list.indexOf(TEST) != -1) {
      cat |= AntiTracking.TEST;
    }
    if (list.indexOf(AD) != -1) {
      cat |= AntiTracking.AD;
    }
    if (list.indexOf(ANALYTIC) != -1) {
      cat |= AntiTracking.ANALYTIC;
    }
    if (list.indexOf(SOCIAL) != -1) {
      cat |= AntiTracking.SOCIAL;
    }
    if (list.indexOf(CONTENT) != -1) {
      cat |= AntiTracking.CONTENT;
    }
    return cat;
  }

  /* package */ static @CBAntiTracking int cmListToAtCat(final String list) {
    int cat = AntiTracking.NONE;
    if (list == null) {
      return cat;
    }
    if (list.indexOf(CRYPTOMINING) != -1) {
      cat |= AntiTracking.CRYPTOMINING;
    }
    return cat;
  }

  /* package */ static @CBAntiTracking int stListToAtCat(final String list) {
    int cat = AntiTracking.NONE;
    if (list == null) {
      return cat;
    }
    if (list.indexOf(STP) != -1) {
      cat |= AntiTracking.STP;
    }
    return cat;
  }

  /* package */ static @CBAntiTracking int etbListToAtCat(final String list) {
    int cat = AntiTracking.NONE;
    if (list == null) {
      return cat;
    }
    if (list.indexOf(EMAIL) != -1) {
      cat |= AntiTracking.EMAIL;
    }
    return cat;
  }

  /* package */ static @CBSafeBrowsing int errorToSbCat(final long error) {
    // Match flags with XPCOM ErrorList.h.
    if (error == 0x805D001FL) {
      return SafeBrowsing.PHISHING;
    }
    if (error == 0x805D001EL) {
      return SafeBrowsing.MALWARE;
    }
    if (error == 0x805D0023L) {
      return SafeBrowsing.UNWANTED;
    }
    if (error == 0x805D0026L) {
      return SafeBrowsing.HARMFUL;
    }
    return SafeBrowsing.NONE;
  }

  // Match flags with nsIWebProgressListener.idl.
  private static final long STATE_COOKIES_LOADED = 0x8000L;
  private static final long STATE_COOKIES_LOADED_TRACKER = 0x40000L;
  private static final long STATE_COOKIES_LOADED_SOCIALTRACKER = 0x80000L;
  private static final long STATE_COOKIES_BLOCKED_TRACKER = 0x20000000L;
  private static final long STATE_COOKIES_BLOCKED_SOCIALTRACKER = 0x01000000L;
  private static final long STATE_COOKIES_BLOCKED_ALL = 0x40000000L;
  private static final long STATE_COOKIES_BLOCKED_FOREIGN = 0x80L;

  /* package */ static boolean isBlockingGeckoCbCat(final long geckoCat) {
    return (geckoCat
            & (STATE_COOKIES_BLOCKED_TRACKER
                | STATE_COOKIES_BLOCKED_SOCIALTRACKER
                | STATE_COOKIES_BLOCKED_ALL
                | STATE_COOKIES_BLOCKED_FOREIGN))
        != 0;
  }

  /* package */ static @CBCookieBehavior int geckoCatToCbCat(final long geckoCat) {
    if ((geckoCat & STATE_COOKIES_LOADED) != 0) {
      // We don't know which setting would actually block this cookie, so
      // we return the most strict value.
      return CookieBehavior.ACCEPT_NONE;
    }
    if ((geckoCat & STATE_COOKIES_BLOCKED_FOREIGN) != 0) {
      return CookieBehavior.ACCEPT_FIRST_PARTY;
    }
    // If we receive STATE_COOKIES_LOADED_{SOCIAL,}TRACKER we know that this
    // setting would block this cookie.
    if ((geckoCat
            & (STATE_COOKIES_BLOCKED_TRACKER
                | STATE_COOKIES_BLOCKED_SOCIALTRACKER
                | STATE_COOKIES_LOADED_TRACKER
                | STATE_COOKIES_LOADED_SOCIALTRACKER))
        != 0) {
      return CookieBehavior.ACCEPT_NON_TRACKERS;
    }
    if ((geckoCat & STATE_COOKIES_BLOCKED_ALL) != 0) {
      return CookieBehavior.ACCEPT_NONE;
    }
    // TODO: There are more reasons why cookies may be blocked.
    return CookieBehavior.ACCEPT_ALL;
  }

  // Cookie Banner Handling feature.

  public static class CookieBannerMode {
    /** Do not enable handling cookie banners. */
    public static final int COOKIE_BANNER_MODE_DISABLED = 0;

    /** Only handle banners where selecting "reject all" is possible. */
    public static final int COOKIE_BANNER_MODE_REJECT = 1;

    /** Reject cookies when possible otherwise accept the cookies. */
    public static final int COOKIE_BANNER_MODE_REJECT_OR_ACCEPT = 2;

    protected CookieBannerMode() {}
  }

  @Retention(RetentionPolicy.SOURCE)
  @IntDef({
    CookieBannerMode.COOKIE_BANNER_MODE_DISABLED,
    CookieBannerMode.COOKIE_BANNER_MODE_REJECT,
    CookieBannerMode.COOKIE_BANNER_MODE_REJECT_OR_ACCEPT,
  })
  public @interface CBCookieBannerMode {}
}