DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (c68fe15a81fc)

VCS Links

Line Code
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* vim: set ts=2 et sw=2 tw=80: */
/* 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/. */
// See
// https://wiki.mozilla.org/Security/Features/Application_Reputation_Design_Doc
// https://wiki.mozilla.org/Security/Features/Application_Reputation_Design_Doc
// for a description of Chrome's implementation of this feature.
#include "ApplicationReputation.h"
#include "chrome/common/safe_browsing/csd.pb.h"

#include "nsIArray.h"
#include "nsIArray.h"
#include "nsIApplicationReputation.h"
#include "nsIChannel.h"
#include "nsIHttpChannel.h"
#include "nsIIOService.h"
#include "nsISimpleEnumerator.h"
#include "nsISimpleEnumerator.h"
#include "nsIStreamListener.h"
#include "nsIStringStream.h"
#include "nsITimer.h"
#include "nsIUploadChannel2.h"
#include "nsIURI.h"
#include "nsIURL.h"
#include "nsIUrlClassifierDBService.h"
#include "nsIX509Cert.h"
#include "nsIX509Cert.h"
#include "nsIX509CertDB.h"

#include "mozilla/ArrayUtils.h"
#include "mozilla/BasePrincipal.h"
#include "mozilla/Components.h"
#include "mozilla/Components.h"
#include "mozilla/ErrorNames.h"
#include "mozilla/LoadContext.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/intl/LocaleService.h"

#include "nsCOMPtr.h"
#include "nsDebug.h"
#include "nsDebug.h"
#include "nsDependentSubstring.h"
#include "nsError.h"
#include "nsLocalFileCommon.h"
#include "nsNetCID.h"
#include "nsReadableUtils.h"
#include "nsReadableUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsString.h"
#include "nsTArray.h"
#include "nsThreadUtils.h"
#include "nsThreadUtils.h"

#include "nsIContentPolicy.h"
#include "nsICryptoHash.h"
#include "nsILoadInfo.h"
#include "nsContentUtils.h"
#include "nsWeakReference.h"
#include "nsIRedirectHistoryEntry.h"
#include "nsIRedirectHistoryEntry.h"

#include "ApplicationReputationTelemetryUtils.h"

using mozilla::ArrayLength;
using mozilla::BasePrincipal;
using mozilla::BasePrincipal;
using mozilla::OriginAttributes;
using mozilla::Preferences;
using mozilla::TimeStamp;
using mozilla::intl::LocaleService;
using mozilla::Telemetry::Accumulate;
using mozilla::Telemetry::Accumulate;
using mozilla::Telemetry::AccumulateCategorical;
using safe_browsing::ClientDownloadRequest;
using safe_browsing::ClientDownloadRequest_CertificateChain;
using safe_browsing::ClientDownloadRequest_Resource;
using safe_browsing::ClientDownloadRequest_SignatureInfo;
using safe_browsing::ClientDownloadRequest_SignatureInfo;

// Preferences that we need to initialize the query.
#define PREF_SB_APP_REP_URL "browser.safebrowsing.downloads.remote.url"
#define PREF_SB_MALWARE_ENABLED "browser.safebrowsing.malware.enabled"
#define PREF_SB_DOWNLOADS_ENABLED "browser.safebrowsing.downloads.enabled"
#define PREF_SB_DOWNLOADS_ENABLED "browser.safebrowsing.downloads.enabled"
#define PREF_SB_DOWNLOADS_REMOTE_ENABLED \
  "browser.safebrowsing.downloads.remote.enabled"
#define PREF_SB_DOWNLOADS_REMOTE_TIMEOUT \
  "browser.safebrowsing.downloads.remote.timeout_ms"
#define PREF_DOWNLOAD_BLOCK_TABLE "urlclassifier.downloadBlockTable"
#define PREF_DOWNLOAD_BLOCK_TABLE "urlclassifier.downloadBlockTable"
#define PREF_DOWNLOAD_ALLOW_TABLE "urlclassifier.downloadAllowTable"

// Preferences that are needed to action the verdict.
#define PREF_BLOCK_DANGEROUS \
  "browser.safebrowsing.downloads.remote.block_dangerous"
  "browser.safebrowsing.downloads.remote.block_dangerous"
#define PREF_BLOCK_DANGEROUS_HOST \
  "browser.safebrowsing.downloads.remote.block_dangerous_host"
#define PREF_BLOCK_POTENTIALLY_UNWANTED \
  "browser.safebrowsing.downloads.remote.block_potentially_unwanted"
#define PREF_BLOCK_UNCOMMON \
#define PREF_BLOCK_UNCOMMON \
  "browser.safebrowsing.downloads.remote.block_uncommon"

// MOZ_LOG=ApplicationReputation:5
mozilla::LazyLogModule ApplicationReputationService::prlog(
    "ApplicationReputation");
    "ApplicationReputation");
#define LOG(args) \
  MOZ_LOG(ApplicationReputationService::prlog, mozilla::LogLevel::Debug, args)
#define LOG_ENABLED() \
  MOZ_LOG_TEST(ApplicationReputationService::prlog, mozilla::LogLevel::Debug)


/**
 * Our detection of executable/binary files uses 3 lists:
 * - kNonBinaryExecutables (below)
 * - kBinaryFileExtensions (below)
 * - sExecutableExts (in nsLocalFileCommon)
 * - sExecutableExts (in nsLocalFileCommon)
 *
 * On Windows, the `sExecutableExts` list is used to determine whether files
 * count as executable. For executable files, we will not offer an "open with"
 * option when downloading, only "save as".
 *
 * On all platforms, the combination of these lists is used to determine
 * whether files should be subject to application reputation checks.
 * Specifically, all files with extensions that:
 * - are in kBinaryFileExtensions, or
 * - are in sExecutableExts **and not in kNonBinaryExecutables**
 *
 *
 * will be subject to checks.
 *
 * There are tests that verify that these lists are sorted and that extensions
 * never appear in both the sExecutableExts and kBinaryFileExtensions lists.
 *
 *
 * When adding items to any lists:
 * - please prefer adding to sExecutableExts unless it is imperative users can
 *   (potentially automatically!) open such files with a helper application
 *   without first saving them (and that outweighs any associated risk).
 * - if adding executable items that shouldn't be submitted to apprep servers,
 * - if adding executable items that shouldn't be submitted to apprep servers,
 *   add them to sExecutableExts and also to kNonBinaryExecutables.
 * - always add an associated comment in the kBinaryFileExtensions list. Add
 *   a commented-out entry with an `exec` annotation if you add the actual
 *   entry in sExecutableExts.
 *
 *
 * When removing items please consider whether items should still be in the
 * sExecutableExts list even if removing them from the kBinaryFileExtensions
 * list, and vice versa.
 *
 * Note that there is a GTest that does its best to check some of these
 * Note that there is a GTest that does its best to check some of these
 * invariants that you'll likely need to update if you're modifying these
 * lists.
 */

// Items that are in sExecutableExts but shouldn't be submitted for application
// reputation checks.
/* static */
const char* const ApplicationReputationService::kNonBinaryExecutables[] = {
    ".ad",
    ".ad",
    ".air",
};


// Items that should be submitted for application reputation checks that users
// Items that should be submitted for application reputation checks that users
// are able to open immediately (without first saving and then finding the
// file). If users shouldn't be able to open them immediately, add to
// sExecutableExts instead (see also the docstring comment above!).
// sExecutableExts instead (see also the docstring comment above!).
/* static */
const char* const ApplicationReputationService::kBinaryFileExtensions[] = {
    // Originally extracted from the "File Type Policies" Chrome extension
    // Items listed with an `exec` comment are in the sExecutableExts list in
    // nsLocalFileCommon.h .
    // nsLocalFileCommon.h .
    //".001",
    //".7z",
    //".ace",
    ".action",  // Mac script
    //".ad", exec // Windows
    //".ad", exec // Windows
    //".ade", exec  // MS Access
    //".adp", exec // MS Access
    //".air", exec // Adobe AIR installer; excluded from apprep checks.
    ".apk",  // Android package
    //".app", exec  // Executable application
    //".app", exec  // Executable application
    ".applescript",
    //".application", exec // MS ClickOnce
    //".application", exec // MS ClickOnce
    ".appref-ms",  // MS ClickOnce
    //".arc",
    //".arj",
    ".as",  // Mac archive
    //".asp", exec  // Windows Server script
    //".asp", exec  // Windows Server script
    ".asx",  // Windows Media Player
    //".b64",
    //".balz",
    //".bas", exec  // Basic script
    ".bash",  // Linux shell
    ".bash",  // Linux shell
    //".bat", exec  // Windows shell
    //".bhx",
    ".bin",
    ".btapp",      // uTorrent and Transmission
    ".btinstall",  // uTorrent and Transmission
    ".btinstall",  // uTorrent and Transmission
    ".btkey",      // uTorrent and Transmission
    ".btsearch",   // uTorrent and Transmission
    ".btskin",     // uTorrent and Transmission
    ".bz",         // Linux archive (bzip)
    ".bz2",        // Linux archive (bzip2)
    ".bz2",        // Linux archive (bzip2)
    ".bzip2",      // Linux archive (bzip2)
    ".cab",        // Windows archive
    ".caction",    // Automator action
    ".cdr",        // Mac disk image
    ".cfg",        // Windows
    ".chi",        // Windows Help
    //".chm", exec // Windows Help
    //".chm", exec // Windows Help
    ".class",  // Java
    //".cmd", exec // Windows executable
    //".com", exec // Windows executable
    ".command",        // Mac script
    ".configprofile",  // Configuration file for Apple systems
    ".configprofile",  // Configuration file for Apple systems
    ".cpgz",           // Mac archive
    ".cpi",            // Control Panel Item. Executable used for adding icons
                       // to Control Panel
    //".cpio",
    //".cpl", exec  // Windows executable
    //".crt", exec  // Windows signed certificate
    ".crx",  // Chrome extensions
    ".crx",  // Chrome extensions
    ".csh",  // Linux shell
    //".csv",
    ".dart",        // Mac disk image
    ".dc42",        // Apple DiskCopy Image
    ".deb",         // Linux package
    ".deb",         // Linux package
    ".definition",  // Automator action
    ".desktop",     // A shortcut that runs other files
    ".dex",         // Android
    ".dht",         // HTML
    ".dhtm",        // HTML
    ".dhtml",       // HTML
    ".diskcopy42",  // Apple DiskCopy Image
    ".diskcopy42",  // Apple DiskCopy Image
    ".dll",         // Windows executable
    ".dmg",         // Mac disk image
    ".dmgpart",     // Mac disk image
    ".doc",         // MS Office
    ".docb",        // MS Office
    ".docb",        // MS Office
    ".docm",        // MS Word
    ".docx",        // MS Word
    ".dot",         // MS Word
    ".dotm",        // MS Word
    ".dott",        // MS Office
    ".dotx",        // MS Word
    ".drv",         // Windows driver
    ".drv",         // Windows driver
    ".dvdr",        // Mac Disk image
    ".dylib",       // Mach object dynamic library file
    ".efi",         // Firmware
    ".eml",         // MS Outlook
    //".exe", exec // Windows executable
    //".exe", exec // Windows executable
    //".fat",
    ".fon",  // Windows font
    //".fxp", exec // MS FoxPro
    ".gadget",  // Windows
    //".gif",
    ".grp",   // Windows
    ".gz",    // Linux archive (gzip)
    ".gzip",  // Linux archive (gzip)
    ".hfs",   // Mac disk image
    ".hfs",   // Mac disk image
    //".hlp", exec // Windows Help
    ".hqx",  // Mac archive
    //".hta", exec // HTML trusted application
    ".htm", ".html",
    ".htt",  // MS HTML template
    ".htt",  // MS HTML template
    //".ica",
    ".img",      // Mac disk image
    ".imgpart",  // Mac disk image
    //".inf", exec // Windows installer
    ".ini",  // Generic config file
    ".ini",  // Generic config file
    //".ins", exec // IIS config
    ".internetconnect",  // Configuration file for Apple system
    //".inx", // InstallShield
    ".iso",  // CD image
    //".isp", exec // IIS config
    //".isu", // InstallShield
    //".jar", exec // Java
    //".jnlp", exec // Java
    //".jnlp", exec // Java
    //".job", // Windows
    //".jpg",
    //".jpeg",
    //".js", exec  // JavaScript script
    //".jse", exec // JScript
    //".jse", exec // JScript
    ".ksh",  // Linux shell
    //".lha",
    //".lnk", exec // Windows
    ".local",  // Windows
    //".lpaq1",
    //".lpaq5",
    //".lpaq8",
    //".lpaq8",
    //".lzh",
    //".lzma",
    //".mad", exec  // MS Access
    //".maf", exec  // MS Access
    //".mag", exec  // MS Access
    //".mag", exec  // MS Access
    //".mam", exec  // MS Access
    ".manifest",  // Windows
    //".maq", exec  // MS Access
    //".mar", exec  // MS Access
    //".mas", exec  // MS Access
    //".mas", exec  // MS Access
    //".mat", exec  // MS Access
    //".mau", exec  // Media attachment
    //".mav", exec  // MS Access
    //".maw", exec  // MS Access
    //".mda", exec  // MS Access
    //".mdb", exec  // MS Access
    //".mde", exec  // MS Access
    //".mde", exec  // MS Access
    //".mdt", exec  // MS Access
    //".mdw", exec  // MS Access
    //".mdz", exec  // MS Access
    ".mht",    // MS HTML
    ".mhtml",  // MS HTML
    ".mhtml",  // MS HTML
    ".mim",    // MS Mail
    //".mkv",
    ".mmc",           // MS Office
    ".mobileconfig",  // Configuration file for Apple systems
    ".mof",           // Windows
    ".mof",           // Windows
    //".mov",
    //".mp3",
    //".mp4",
    ".mpkg",  // Mac installer
    //".msc", exec  // Windows executable
    //".msc", exec  // Windows executable
    ".msg",  // MS Outlook
    //".msh", exec  // Windows shell
    //".msh1", exec // Windows shell
    //".msh1xml", exec  // Windows shell
    //".msh2", exec // Windows shell
    //".msh2xml", exec // Windows shell
    //".mshxml", exec // Windows
    //".mshxml", exec // Windows
    //".msi", exec  // Windows installer
    //".msp", exec  // Windows installer
    //".mst", exec  // Windows installer
    //".mst", exec  // Windows installer
    ".ndif",            // Mac disk image
    ".networkconnect",  // Configuration file for Apple systems
    //".ntfs", // 7z
    ".ocx",  // ActiveX
    //".ops", exec  // MS Office
    //".ops", exec  // MS Office
    ".osas",  // AppleScript
    ".osax",  // AppleScript
    //".out", // Linux binary
    ".oxt",  // OpenOffice extension, can execute arbitrary code
    //".package",
    //".package",
    //".paf", // PortableApps package
    //".paq8f",
    //".paq8jd",
    //".paq8l",
    //".paq8o",
    //".paq8o",
    ".partial",  // Downloads
    ".pax",      // Mac archive
    //".pcd", exec     // Microsoft Visual Test
    ".pdf",  // Adobe Acrobat
    //".pea",
    ".pet",  // Linux package
    //".pif", exec // Windows
    //".pif", exec // Windows
    ".pkg",  // Mac installer
    ".pl",   // Perl script
    //".plg", exec // MS Visual Studio
    //".plg", exec // MS Visual Studio
    //".png",
    ".pot",   // MS PowerPoint
    ".potm",  // MS PowerPoint
    ".potx",  // MS PowerPoint
    ".ppam",  // MS PowerPoint
    ".ppam",  // MS PowerPoint
    ".pps",   // MS PowerPoint
    ".ppsm",  // MS PowerPoint
    ".ppsx",  // MS PowerPoint
    ".ppt",   // MS PowerPoint
    ".pptm",  // MS PowerPoint
    ".pptx",  // MS PowerPoint
    //".prf", exec // MS Outlook
    //".prf", exec // MS Outlook
    //".prg", exec // Windows
    ".ps1",     // Windows shell
    ".ps1xml",  // Windows shell
    ".ps2",     // Windows shell
    ".ps2xml",  // Windows shell
    ".ps2xml",  // Windows shell
    ".psc1",    // Windows shell
    ".psc2",    // Windows shell
    //".pst", exec // MS Outlook
    ".pup",  // Linux package
    ".py",   // Python script
    ".py",   // Python script
    ".pyc",  // Python binary
    ".pyd",  // Equivalent of a DLL, for python libraries
    ".pyd",  // Equivalent of a DLL, for python libraries
    ".pyo",  // Compiled python code
    ".pyw",  // Python GUI
    //".quad",
    //".r00",
    //".r01",
    //".r01",
    //".r02",
    //".r03",
    //".r04",
    //".r05",
    //".r05",
    //".r06",
    //".r07",
    //".r08",
    //".r09",
    //".r10",
    //".r10",
    //".r11",
    //".r12",
    //".r13",
    //".r14",
    //".r15",
    //".r15",
    //".r16",
    //".r17",
    //".r18",
    //".r19",
    //".r20",
    //".r20",
    //".r21",
    //".r22",
    //".r23",
    //".r24",
    //".r25",
    //".r25",
    //".r26",
    //".r27",
    //".r28",
    //".r29",
    //".r29",
    //".rar",
    ".rb",  // Ruby script
    //".reg", exec  // Windows Registry
    ".rels",  // MS Office
    //".rgs", // Windows Registry
    ".rpm",  // Linux package
    ".rtf",  // MS Office
    //".run", // Linux shell
    //".scf", exec         // Windows shell
    //".scf", exec         // Windows shell
    ".scpt",   // AppleScript
    ".scptd",  // AppleScript
    //".scr", exec         // Windows
    //".sct", exec         // Windows shell
    ".search-ms",  // Windows
    ".search-ms",  // Windows
    ".seplugin",   // AppleScript
    ".service",    // Systemd service unit file
    //".settingcontent-ms", exec // Windows settings
    ".sh",    // Linux shell
    ".shar",  // Linux shell
    ".shar",  // Linux shell
    //".shb", exec         // Windows
    //".shs", exec         // Windows shell
    ".sht",           // HTML
    ".shtm",          // HTML
    ".shtml",         // HTML
    ".sldm",          // MS PowerPoint
    ".sldm",          // MS PowerPoint
    ".sldx",          // MS PowerPoint
    ".slk",           // MS Excel
    ".slp",           // Linux package
    ".smi",           // Mac disk image
    ".sparsebundle",  // Mac disk image
    ".sparsebundle",  // Mac disk image
    ".sparseimage",   // Mac disk image
    ".spl",           // Adobe Flash
    //".squashfs",
    ".svg",
    ".swf",   // Adobe Flash
    ".swf",   // Adobe Flash
    ".swm",   // Windows Imaging
    ".sys",   // Windows
    ".tar",   // Linux archive
    ".taz",   // Linux archive (bzip2)
    ".tbz",   // Linux archive (bzip2)
    ".tbz",   // Linux archive (bzip2)
    ".tbz2",  // Linux archive (bzip2)
    ".tcsh",  // Linux shell
    //".tif",
    ".tgz",  // Linux archive (gzip)
    //".toast", // Roxio disk image
    ".torrent",  // Bittorrent
    ".torrent",  // Bittorrent
    ".tpz",      // Linux archive (gzip)
    //".txt",
    ".txz",  // Linux archive (xz)
    ".tz",   // Linux archive (gzip)
    ".tz",   // Linux archive (gzip)
    //".u3p", // U3 Smart Apps
    ".udf",   // MS Excel
    ".udif",  // Mac disk image
    //".url", exec  // Windows
    //".uu",
    //".uu",
    //".uue",
    //".vb", exec  // Visual Basic script
    //".vbe", exec // Visual Basic script
    //".vbs", exec // Visual Basic script
    //".vbscript", // Visual Basic script
    //".vbscript", // Visual Basic script
    //".vdx", exec // MS Visio
    ".vhd",   // Windows virtual hard drive
    ".vhdx",  // Windows virtual hard drive
    ".vmdk",  // VMware virtual disk
    //".vsd", exec  // MS Visio
    //".vsd", exec  // MS Visio
    //".vsdm", exec // MS Visio
    //".vsdx", exec // MS Visio
    //".vsmacros", exec  // MS Visual Studio
    //".vss",  exec  // MS Visio
    //".vssm", exec  // MS Visio
    //".vssx", exec  // MS Visio
    //".vst",  exec  // MS Visio
    //".vstm", exec  // MS Visio
    //".vstx", exec  // MS Visio
    //".vstx", exec  // MS Visio
    //".vsw",  exec  // MS Visio
    //".vsx",  exec  // MS Visio
    //".vtx",  exec  // MS Visio
    //".wav",
    //".webp",
    //".webp",
    ".website",   // Windows
    ".wflow",     // Automator action
    ".wim",       // Windows Imaging
    ".workflow",  // Mac Automator
    //".wrc", // FreeArc archive
    //".wrc", // FreeArc archive
    //".ws",  exec  // Windows script
    //".wsc", exec  // Windows script
    //".wsf", exec  // Windows script
    //".wsh", exec  // Windows script
    ".xar",   // MS Excel
    ".xar",   // MS Excel
    ".xbap",  // XAML Browser Application
    ".xht", ".xhtm", ".xhtml",
    ".xip",     // Mac archive
    ".xla",     // MS Excel
    ".xlam",    // MS Excel
    ".xlam",    // MS Excel
    ".xldm",    // MS Excel
    ".xll",     // MS Excel
    ".xll",     // MS Excel
    ".xlm",     // MS Excel
    ".xls",     // MS Excel
    ".xlsb",    // MS Excel
    ".xlsm",    // MS Excel
    ".xlsm",    // MS Excel
    ".xlsx",    // MS Excel
    ".xlt",     // MS Excel
    ".xltm",    // MS Excel
    ".xltx",    // MS Excel
    ".xlw",     // MS Excel
    ".xlw",     // MS Excel
    ".xml",     // MS Excel
    ".xnk",     // MS Exchange
    ".xrm-ms",  // Windows
    ".xsl",     // XML Stylesheet
    //".xxe",
    //".xxe",
    ".xz",     // Linux archive (xz)
    ".z",      // InstallShield
#ifdef XP_WIN  // disable on Mac/Linux, see 1167493
    ".zip",    // Generic archive
#endif
#endif
    ".zipx",  // WinZip
              //".zpaq",
};


static const char* const kMozNonBinaryExecutables[] = {
    ".001", ".7z",   ".ace",  ".arc",   ".arj",    ".b64",      ".balz",
    ".bhx", ".cpio", ".fat",  ".lha",   ".lpaq1",  ".lpaq5",    ".lpaq8",
    ".lzh", ".lzma", ".ntfs", ".paq8f", ".paq8jd", ".paq8l",    ".paq8o",
    ".pea", ".quad", ".r00",  ".r01",   ".r02",    ".r03",      ".r04",
    ".pea", ".quad", ".r00",  ".r01",   ".r02",    ".r03",      ".r04",
    ".r05", ".r06",  ".r07",  ".r08",   ".r09",    ".r10",      ".r11",
    ".r12", ".r13",  ".r14",  ".r15",   ".r16",    ".r17",      ".r18",
    ".r19", ".r20",  ".r21",  ".r22",   ".r23",    ".r24",      ".r25",
    ".r26", ".r27",  ".r28",  ".r29",   ".rar",    ".squashfs", ".uu",
    ".uue", ".wrc",  ".xxe",  ".zpaq",  ".toast",
};


static const char* const kSafeFileExtensions[] = {
    ".jpg",  ".jpeg", ".mp3",      ".mp4",  ".png",  ".csv",  ".ica",
    ".gif",  ".txt",  ".package",  ".tif",  ".webp", ".mkv",  ".wav",
    ".mov",  ".paf",  ".vbscript", ".ad",   ".inx",  ".isu",  ".job",
    ".rgs",  ".u3p",  ".out",      ".run",  ".bmp",  ".css",  ".ehtml",
    ".flac", ".ico",  ".jfif",     ".m4a",  ".m4v",  ".mpeg", ".mpg",
    ".oga",  ".ogg",  ".ogm",      ".ogv",  ".opus", ".pjp",  ".pjpeg",
    ".svgz", ".text", ".tiff",     ".weba", ".webm", ".xbm",
    ".svgz", ".text", ".tiff",     ".weba", ".webm", ".xbm",
};

enum class LookupType { AllowlistOnly, BlocklistOnly, BothLists };

// Define the reasons that download protection service accepts or blocks this
// Define the reasons that download protection service accepts or blocks this
// download. This is now used for telemetry purposes and xpcshell test. Please
// also update the xpcshell-test if a reason is added.
//
// LocalWhitelist       : URL is found in the local whitelist
// LocalBlocklist       : URL is found in the local blocklist
// LocalBlocklist       : URL is found in the local blocklist
// NonBinary            : The downloaded non-binary file is not found in the
// local blocklist VerdictSafe          : Remote lookup reports the download is
// safe VerdictUnknown       : Remote lookup reports unknown, we treat this as a
// safe download VerdictDangerous     : Remote lookup reports the download is
// dangerous VerdictDangerousHost : Remote lookup reports the download is from a
// dangerous host VerdictUnwanted      : Remote lookup reports the download is
// potentially unwatned VerdictUncommon      : Remote lookup reports the
// download is uncommon VerdictUnrecognized  : The verdict type from remote
// lookup is not defined in the csd.proto DangerousPrefOff     : The download is
// lookup is not defined in the csd.proto DangerousPrefOff     : The download is
// dangerous, but the corresponding preference is off DangerousHostPrefOff : The
// download is from a dangerous host, but the corresponding preference is off
// UnwantedPrefOff      : The download is potentially unwanted, but the
// corresponding preference is off UncommonPrefOff      : The download us
// uncommon, but the coressponding preference is off NetworkError         :
// There is an error while requesting remote lookup RemoteLookupDisabled :
// Remote lookup is disabled or the remote lookup URL is empty InternalError :
// Remote lookup is disabled or the remote lookup URL is empty InternalError :
// An unexpected internal error DPDisabled           : Download protection is
// disabled
using Reason = mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_REASON;

class PendingDBLookup;
class PendingDBLookup;

// A single use class private to ApplicationReputationService encapsulating an
// nsIApplicationReputationQuery and an nsIApplicationReputationCallback. Once
// created by ApplicationReputationService, it is guaranteed to call mCallback.
// This class is private to ApplicationReputationService.
// This class is private to ApplicationReputationService.
class PendingLookup final : public nsIStreamListener,
                            public nsITimerCallback,
                            public nsIObserver,
                            public nsSupportsWeakReference {
 public:
 public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIREQUESTOBSERVER
  NS_DECL_NSISTREAMLISTENER
  NS_DECL_NSISTREAMLISTENER
  NS_DECL_NSITIMERCALLBACK
  NS_DECL_NSIOBSERVER

  // Constructor and destructor.
  PendingLookup(nsIApplicationReputationQuery* aQuery,
                nsIApplicationReputationCallback* aCallback);


  // Start the lookup. The lookup may have 2 parts: local and remote. In the
  // local lookup, PendingDBLookups are created to query the local allow and
  // blocklists for various URIs associated with this downloaded file. In the
  // event that no results are found, a remote lookup is sent to the Application
  // Reputation server.
  // Reputation server.
  nsresult StartLookup();

 private:
  ~PendingLookup();


  friend class PendingDBLookup;

  // Telemetry states.
  // Status of the remote response (valid or not).
  enum SERVER_RESPONSE_TYPES {
  enum SERVER_RESPONSE_TYPES {
    SERVER_RESPONSE_VALID = 0,
    SERVER_RESPONSE_FAILED = 1,
    SERVER_RESPONSE_INVALID = 2,
  };


  // The target filename for the downloaded file.
  nsCString mFileName;

  // True if extension of this file matches any extension in the
  // kBinaryFileExtensions or sExecutableExts list.
  bool mIsBinaryFile;

  // Number of blocklist and allowlist hits we have seen.
  uint32_t mBlocklistCount;
  uint32_t mAllowlistCount;

  // The query containing metadata about the downloaded file.
  // The query containing metadata about the downloaded file.
  nsCOMPtr<nsIApplicationReputationQuery> mQuery;

  // The callback with which to report the verdict.
  nsCOMPtr<nsIApplicationReputationCallback> mCallback;


  // An array of strings created from certificate information used to whitelist
  // the downloaded file.
  nsTArray<nsCString> mAllowlistSpecs;
  // The source URI of the download (i.e. final URI after any redirects).
  nsTArray<nsCString> mAnylistSpecs;
  nsTArray<nsCString> mAnylistSpecs;
  // The referrer and possibly any redirects.
  nsTArray<nsCString> mBlocklistSpecs;

  // When we started this query
  TimeStamp mStartTime;
  TimeStamp mStartTime;

  // The channel used to talk to the remote lookup server
  nsCOMPtr<nsIChannel> mChannel;


  // Timer to abort this lookup if it takes too long
  nsCOMPtr<nsITimer> mTimeoutTimer;

  // A protocol buffer for storing things we need in the remote request. We
  // store the resource chain (redirect information) as well as signature
  // store the resource chain (redirect information) as well as signature
  // information extracted using the Windows Authenticode API, if the binary is
  // signed.
  ClientDownloadRequest mRequest;

  // The response from the application reputation query. This is read in chunks
  // The response from the application reputation query. This is read in chunks
  // as part of our nsIStreamListener implementation and may contain embedded
  // NULLs.
  nsCString mResponse;


  // The clock records the start time of a remote lookup request, used by
  // telemetry.
  PRIntervalTime mTelemetryRemoteRequestStartMs;

  // Returns the type of download binary for the file.
  // Returns the type of download binary for the file.
  ClientDownloadRequest::DownloadType GetDownloadType(
      const nsACString& aFilename);

  // Clean up and call the callback. PendingLookup must not be used after this
  // function is called.
  // function is called.
  nsresult OnComplete(uint32_t aVerdict, Reason aReason, nsresult aRv);

  // Wrapper function for nsIStreamListener.onStopRequest to make it easy to
  // guarantee calling the callback
  nsresult OnStopRequestInternal(nsIRequest* aRequest, nsISupports* aContext,
                                 nsresult aResult, uint32_t& aVerdict,
                                 Reason& aReason);

  // Return the hex-encoded hash of the whole URI.
  // Return the hex-encoded hash of the whole URI.
  nsresult GetSpecHash(nsACString& aSpec, nsACString& hexEncodedHash);

  // Strip url parameters, fragments, and user@pass fields from the URI spec
  // using nsIURL. Hash data URIs and return blob URIs unfiltered.
  nsresult GetStrippedSpec(nsIURI* aUri, nsACString& spec);
  nsresult GetStrippedSpec(nsIURI* aUri, nsACString& spec);

  // Escape '/' and '%' in certificate attribute values.
  nsCString EscapeCertificateAttribute(const nsACString& aAttribute);

  // Escape ':' in fingerprint values.
  // Escape ':' in fingerprint values.
  nsCString EscapeFingerprint(const nsACString& aAttribute);

  // Generate whitelist strings for the given certificate pair from the same
  // Generate whitelist strings for the given certificate pair from the same
  // certificate chain.
  nsresult GenerateWhitelistStringsForPair(nsIX509Cert* certificate,
                                           nsIX509Cert* issuer);

  // Generate whitelist strings for the given certificate chain, which starts
  // Generate whitelist strings for the given certificate chain, which starts
  // with the signer and may go all the way to the root cert.
  nsresult GenerateWhitelistStringsForChain(
      const ClientDownloadRequest_CertificateChain& aChain);

  // For signed binaries, generate strings of the form:
  // For signed binaries, generate strings of the form:
  // http://sb-ssl.google.com/safebrowsing/csd/certificate/
  //   <issuer_cert_sha1_fingerprint>[/CN=<cn>][/O=<org>][/OU=<unit>]
  // for each (cert, issuer) pair in each chain of certificates that is
  // associated with the binary.
  nsresult GenerateWhitelistStrings();
  nsresult GenerateWhitelistStrings();

  // Parse the XPCOM certificate lists and stick them into the protocol buffer
  // version.
  nsresult ParseCertificates(
      const nsTArray<nsTArray<nsTArray<uint8_t>>>& aSigArray);
      const nsTArray<nsTArray<nsTArray<uint8_t>>>& aSigArray);

  // Adds the redirects to mBlocklistSpecs to be looked up.
  nsresult AddRedirects(nsIArray* aRedirects);

  // Helper function to ensure that we call PendingLookup::LookupNext or
  // Helper function to ensure that we call PendingLookup::LookupNext or
  // PendingLookup::OnComplete.
  nsresult DoLookupInternal();

  // Looks up all the URIs that may be responsible for allowlisting or
  // blocklisting the downloaded file. These URIs may include whitelist strings
  // generated by certificates verifying the binary as well as the target URI
  // generated by certificates verifying the binary as well as the target URI
  // from which the file was downloaded.
  nsresult LookupNext();

  // Sends a query to the remote application reputation service. Returns NS_OK
  // on success.
  // on success.
  nsresult SendRemoteQuery();

  // Helper function to ensure that we always call the callback.
  nsresult SendRemoteQueryInternal(Reason& aReason);
};
};

// A single-use class for looking up a single URI in the safebrowsing DB. This
// class is private to PendingLookup.
class PendingDBLookup final : public nsIUrlClassifierCallback {
 public:
 public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIURLCLASSIFIERCALLBACK

  // Constructor and destructor
  // Constructor and destructor
  explicit PendingDBLookup(PendingLookup* aPendingLookup);

  // Look up the given URI in the safebrowsing DBs, optionally on both the allow
  // list and the blocklist. If there is a match, call
  // PendingLookup::OnComplete. Otherwise, call PendingLookup::LookupNext.
  // PendingLookup::OnComplete. Otherwise, call PendingLookup::LookupNext.
  nsresult LookupSpec(const nsACString& aSpec, const LookupType& aLookupType);

 private:
  ~PendingDBLookup();


  // The download appeared on the allowlist, blocklist, or no list (and thus
  // could trigger a remote query.
  enum LIST_TYPES {
    ALLOW_LIST = 0,
    ALLOW_LIST = 0,
    BLOCK_LIST = 1,
    NO_LIST = 2,
  };


  nsCString mSpec;
  LookupType mLookupType;
  RefPtr<PendingLookup> mPendingLookup;
  nsresult LookupSpecInternal(const nsACString& aSpec);
};
};

NS_IMPL_ISUPPORTS(PendingDBLookup, nsIUrlClassifierCallback)

PendingDBLookup::PendingDBLookup(PendingLookup* aPendingLookup)
    : mLookupType(LookupType::BothLists), mPendingLookup(aPendingLookup) {
    : mLookupType(LookupType::BothLists), mPendingLookup(aPendingLookup) {
  LOG(("Created pending DB lookup [this = %p]", this));
}

PendingDBLookup::~PendingDBLookup() {
  LOG(("Destroying pending DB lookup [this = %p]", this));
  LOG(("Destroying pending DB lookup [this = %p]", this));
  mPendingLookup = nullptr;
}

nsresult PendingDBLookup::LookupSpec(const nsACString& aSpec,
                                     const LookupType& aLookupType) {
                                     const LookupType& aLookupType) {
  LOG(("Checking principal %s [this=%p]", aSpec.Data(), this));
  mSpec = aSpec;
  mLookupType = aLookupType;
  nsresult rv = LookupSpecInternal(aSpec);
  if (NS_FAILED(rv)) {
  if (NS_FAILED(rv)) {
    nsAutoCString errorName;
    mozilla::GetErrorName(rv, errorName);
    LOG(("Error in LookupSpecInternal() [rv = %s, this = %p]", errorName.get(),
         this));
    return mPendingLookup->LookupNext();  // ignore this lookup and move to next
  }
  }
  // LookupSpecInternal has called nsIUrlClassifierCallback.lookup, which is
  // guaranteed to call HandleEvent.
  return rv;
}


nsresult PendingDBLookup::LookupSpecInternal(const nsACString& aSpec) {
  nsresult rv;

  nsCOMPtr<nsIURI> uri;
  nsCOMPtr<nsIIOService> ios = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
  nsCOMPtr<nsIIOService> ios = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
  rv = ios->NewURI(aSpec, nullptr, nullptr, getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);

  OriginAttributes attrs;
  nsCOMPtr<nsIPrincipal> principal =
  nsCOMPtr<nsIPrincipal> principal =
      BasePrincipal::CreateContentPrincipal(uri, attrs);
  if (!principal) {
    return NS_ERROR_FAILURE;
    return NS_ERROR_FAILURE;
  }
  }

  // Check local lists to see if the URI has already been whitelisted or
  // blacklisted.
  // blacklisted.
  LOG(("Checking DB service for principal %s [this = %p]", mSpec.get(), this));
  nsCOMPtr<nsIUrlClassifierDBService> dbService =
      mozilla::components::UrlClassifierDB::Service(&rv);
  NS_ENSURE_SUCCESS(rv, rv);


  nsAutoCString tables;
  nsAutoCString allowlist;
  Preferences::GetCString(PREF_DOWNLOAD_ALLOW_TABLE, allowlist);
  if ((mLookupType != LookupType::BlocklistOnly) && !allowlist.IsEmpty()) {
    tables.Append(allowlist);
  }
  nsAutoCString blocklist;
  nsAutoCString blocklist;
  Preferences::GetCString(PREF_DOWNLOAD_BLOCK_TABLE, blocklist);
  Preferences::GetCString(PREF_DOWNLOAD_BLOCK_TABLE, blocklist);
  if ((mLookupType != LookupType::AllowlistOnly) && !blocklist.IsEmpty()) {
    if (!tables.IsEmpty()) {
      tables.Append(',');
      tables.Append(',');
    }
    tables.Append(blocklist);
  }
  return dbService->Lookup(principal, tables, this);
}
}

NS_IMETHODIMP
PendingDBLookup::HandleEvent(const nsACString& tables) {
  // HandleEvent is guaranteed to call either:
  // 1) PendingLookup::OnComplete if the URL matches the blocklist, or
  // 1) PendingLookup::OnComplete if the URL matches the blocklist, or
  // 2) PendingLookup::LookupNext if the URL does not match the blocklist.
  // Blocklisting trumps allowlisting.
  nsAutoCString blockList;
  Preferences::GetCString(PREF_DOWNLOAD_BLOCK_TABLE, blockList);
  if ((mLookupType != LookupType::AllowlistOnly) &&
  if ((mLookupType != LookupType::AllowlistOnly) &&
      FindInReadable(blockList, tables)) {
    mPendingLookup->mBlocklistCount++;
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_LOCAL, BLOCK_LIST);
    LOG(("Found principal %s on blocklist [this = %p]", mSpec.get(), this));
    return mPendingLookup->OnComplete(
    return mPendingLookup->OnComplete(
        nsIApplicationReputationService::VERDICT_DANGEROUS,
        Reason::LocalBlocklist, NS_OK);
  }


  nsAutoCString allowList;
  Preferences::GetCString(PREF_DOWNLOAD_ALLOW_TABLE, allowList);
  if ((mLookupType != LookupType::BlocklistOnly) &&
      FindInReadable(allowList, tables)) {
    mPendingLookup->mAllowlistCount++;
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_LOCAL, ALLOW_LIST);
    LOG(("Found principal %s on allowlist [this = %p]", mSpec.get(), this));
    LOG(("Found principal %s on allowlist [this = %p]", mSpec.get(), this));
    // Don't call onComplete, since blocklisting trumps allowlisting
    return mPendingLookup->LookupNext();
  }

  LOG(("Didn't find principal %s on any list [this = %p]", mSpec.get(), this));
  LOG(("Didn't find principal %s on any list [this = %p]", mSpec.get(), this));
  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_LOCAL, NO_LIST);
  return mPendingLookup->LookupNext();
}

NS_IMPL_ISUPPORTS(PendingLookup, nsIStreamListener, nsIRequestObserver,
NS_IMPL_ISUPPORTS(PendingLookup, nsIStreamListener, nsIRequestObserver,
                  nsIObserver, nsISupportsWeakReference)

PendingLookup::PendingLookup(nsIApplicationReputationQuery* aQuery,
                             nsIApplicationReputationCallback* aCallback)
    : mIsBinaryFile(false),
    : mIsBinaryFile(false),
      mBlocklistCount(0),
      mAllowlistCount(0),
      mQuery(aQuery),
      mCallback(aCallback) {
  LOG(("Created pending lookup [this = %p]", this));
  LOG(("Created pending lookup [this = %p]", this));
}

PendingLookup::~PendingLookup() {
  LOG(("Destroying pending lookup [this = %p]", this));
}
}

static const char* const kDmgFileExtensions[] = {
    ".cdr",          ".dart",        ".dc42",  ".diskcopy42",
    ".dmg",          ".dmgpart",     ".dvdr",  ".img",
    ".imgpart",      ".iso",         ".ndif",  ".smi",
    ".imgpart",      ".iso",         ".ndif",  ".smi",
    ".sparsebundle", ".sparseimage", ".toast", ".udif",
};

static const char* const kRarFileExtensions[] = {
static const char* const kRarFileExtensions[] = {
    ".r00", ".r01", ".r02", ".r03", ".r04", ".r05", ".r06", ".r07",
    ".r08", ".r09", ".r10", ".r11", ".r12", ".r13", ".r14", ".r15",
    ".r16", ".r17", ".r18", ".r19", ".r20", ".r21", ".r22", ".r23",
    ".r24", ".r25", ".r26", ".r27", ".r28", ".r29", ".rar",
    ".r24", ".r25", ".r26", ".r27", ".r28", ".r29", ".rar",
};

static const char* const kZipFileExtensions[] = {
static const char* const kZipFileExtensions[] = {
    ".zip",   // Generic archive
    ".zip",   // Generic archive
    ".zipx",  // WinZip
};


static const char* GetFileExt(const nsACString& aFilename,
                              const char* const aFileExtensions[],
                              const size_t aLength) {
  for (size_t i = 0; i < aLength; ++i) {
    if (StringEndsWith(aFilename, nsDependentCString(aFileExtensions[i]))) {
    if (StringEndsWith(aFilename, nsDependentCString(aFileExtensions[i]))) {
      return aFileExtensions[i];
    }
  }
  return nullptr;
}
}

static const char* GetFileExt(const nsACString& aFilename) {
#define _GetFileExt(_f, _l) GetFileExt(_f, _l, ArrayLength(_l))
  const char* ext = _GetFileExt(
      aFilename, ApplicationReputationService::kBinaryFileExtensions);
      aFilename, ApplicationReputationService::kBinaryFileExtensions);
  if (ext == nullptr &&
      !_GetFileExt(aFilename,
                   ApplicationReputationService::kNonBinaryExecutables)) {
    ext = _GetFileExt(aFilename, sExecutableExts);
  }
  }
  return ext;
}

// Returns true if the file extension matches one in the given array.
static bool IsFileType(const nsACString& aFilename,
static bool IsFileType(const nsACString& aFilename,
                       const char* const aFileExtensions[],
                       const size_t aLength) {
  return GetFileExt(aFilename, aFileExtensions, aLength) != nullptr;
}


static bool IsBinary(const nsACString& aFilename) {
  return IsFileType(aFilename,
                    ApplicationReputationService::kBinaryFileExtensions,
                    ArrayLength(
                        ApplicationReputationService::kBinaryFileExtensions)) ||
                        ApplicationReputationService::kBinaryFileExtensions)) ||
         (!IsFileType(
              aFilename, ApplicationReputationService::kNonBinaryExecutables,
              ArrayLength(
                  ApplicationReputationService::kNonBinaryExecutables)) &&
          IsFileType(aFilename, sExecutableExts, ArrayLength(sExecutableExts)));
          IsFileType(aFilename, sExecutableExts, ArrayLength(sExecutableExts)));
}

ClientDownloadRequest::DownloadType PendingLookup::GetDownloadType(
    const nsACString& aFilename) {
  MOZ_ASSERT(IsBinary(aFilename));

  // From
  // https://cs.chromium.org/chromium/src/chrome/common/safe_browsing/download_protection_util.cc?l=17
  if (StringEndsWith(aFilename, NS_LITERAL_CSTRING(".zip"))) {
  if (StringEndsWith(aFilename, NS_LITERAL_CSTRING(".zip"))) {
    return ClientDownloadRequest::ZIPPED_EXECUTABLE;
  } else if (StringEndsWith(aFilename, NS_LITERAL_CSTRING(".apk"))) {
    return ClientDownloadRequest::ANDROID_APK;
  } else if (StringEndsWith(aFilename, NS_LITERAL_CSTRING(".app")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".applescript")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".cdr")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dart")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dart")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dc42")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".diskcopy42")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dmg")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dmgpart")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dvdr")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".dvdr")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".img")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".imgpart")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".iso")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".mpkg")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".ndif")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".ndif")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".osas")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".osax")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".pkg")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".scpt")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".scptd")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".scptd")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".seplugin")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".smi")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".smi")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".sparsebundle")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".sparseimage")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".toast")) ||
             StringEndsWith(aFilename, NS_LITERAL_CSTRING(".udif"))) {
    return ClientDownloadRequest::MAC_EXECUTABLE;
    return ClientDownloadRequest::MAC_EXECUTABLE;
  }

  return ClientDownloadRequest::WIN_EXECUTABLE;  // default to Windows binaries
}


nsresult PendingLookup::LookupNext() {
  // We must call LookupNext or SendRemoteQuery upon return.
  // Look up all of the URLs that could allow or block this download.
  // Blocklist first.


  // If a url is in blocklist we should call PendingLookup::OnComplete directly.
  MOZ_ASSERT(mBlocklistCount == 0);

  nsCString spec;
  if (!mAnylistSpecs.IsEmpty()) {
  nsCString spec;
    // Check the source URI only.
    spec = mAnylistSpecs.PopLastElement();
    RefPtr<PendingDBLookup> lookup(new PendingDBLookup(this));

    RefPtr<PendingDBLookup> lookup(new PendingDBLookup(this));
    // We don't need to check whitelist if the file is not a binary file.
    auto type =
        mIsBinaryFile ? LookupType::BothLists : LookupType::BlocklistOnly;
    return lookup->LookupSpec(spec, type);
  }

  }
  if (!mBlocklistSpecs.IsEmpty()) {
    // Check the referrer and redirect chain.
    spec = mBlocklistSpecs.PopLastElement();
    RefPtr<PendingDBLookup> lookup(new PendingDBLookup(this));
    return lookup->LookupSpec(spec, LookupType::BlocklistOnly);
    spec = mBlocklistSpecs[index];
  }

  // Now that we've looked up all of the URIs against the blocklist,
  // if any of mAnylistSpecs or mAllowlistSpecs matched the allowlist,
  }
  // go ahead and pass.
  if (mAllowlistCount > 0) {
    return OnComplete(nsIApplicationReputationService::VERDICT_SAFE,
                      Reason::LocalWhitelist, NS_OK);
  }

  if (mAllowlistCount > 0) {
  MOZ_ASSERT_IF(!mIsBinaryFile, mAllowlistSpecs.Length() == 0);

  // Only binary signatures remain.
  if (!mAllowlistSpecs.IsEmpty()) {
    spec = mAllowlistSpecs.PopLastElement();
  MOZ_ASSERT_IF(!mIsBinaryFile, mAllowlistSpecs.Length() == 0);
    LOG(("PendingLookup::LookupNext: checking %s on allowlist", spec.get()));
    RefPtr<PendingDBLookup> lookup(new PendingDBLookup(this));
    return lookup->LookupSpec(spec, LookupType::AllowlistOnly);
  }

    spec = mAllowlistSpecs[index];
  if (!mFileName.IsEmpty()) {
    if (IsBinary(mFileName)) {
      AccumulateCategorical(
          mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE::
              BinaryFile);
  }
    } else if (IsFileType(mFileName, kSafeFileExtensions,
                          ArrayLength(kSafeFileExtensions))) {
      AccumulateCategorical(
          mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE::
              NonBinaryFile);
          mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE::
    } else if (IsFileType(mFileName, kMozNonBinaryExecutables,
                          ArrayLength(kMozNonBinaryExecutables))) {
      AccumulateCategorical(
          mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE::
              MozNonBinaryFile);
          mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE::
    } else {
      AccumulateCategorical(
          mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE::
              UnknownFile);
    }
          mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE::
  } else {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_TYPE::
            MissingFilename);
  }
              UnknownFile);

  if (IsFileType(mFileName, kDmgFileExtensions,
                 ArrayLength(kDmgFileExtensions))) {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_ARCHIVE::
            MissingFilename);
            DmgFile);
  } else if (IsFileType(mFileName, kRarFileExtensions,
                        ArrayLength(kRarFileExtensions))) {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_ARCHIVE::
    AccumulateCategorical(
            RarFile);
  } else if (IsFileType(mFileName, kZipFileExtensions,
  } else if (IsFileType(mFileName, kRarFileExtensions,
                        ArrayLength(kZipFileExtensions))) {
    AccumulateCategorical(
                        ArrayLength(kRarFileExtensions))) {
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_ARCHIVE::
    AccumulateCategorical(
            ZipFile);
  } else if (mIsBinaryFile) {
  } else if (IsFileType(mFileName, kZipFileExtensions,
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_BINARY_ARCHIVE::
            OtherBinaryFile);
  }

  } else if (mIsBinaryFile) {
  // There are no more URIs to check against local list. If the file is
  // not eligible for remote lookup, bail.
  if (!mIsBinaryFile) {
    LOG(("Not eligible for remote lookups [this=%p]", this));
    return OnComplete(nsIApplicationReputationService::VERDICT_SAFE,

                      Reason::NonBinaryFile, NS_OK);
  }

  nsresult rv = SendRemoteQuery();
  if (NS_FAILED(rv)) {
    return OnComplete(nsIApplicationReputationService::VERDICT_SAFE,
    return OnComplete(nsIApplicationReputationService::VERDICT_SAFE,
                      Reason::InternalError, rv);
  }
  return NS_OK;
}
  if (NS_FAILED(rv)) {

nsCString PendingLookup::EscapeCertificateAttribute(
    const nsACString& aAttribute) {
  // Escape '/' because it's a field separator, and '%' because Chrome does
  nsCString escaped;
  return NS_OK;
  escaped.SetCapacity(aAttribute.Length());
  for (unsigned int i = 0; i < aAttribute.Length(); ++i) {
    if (aAttribute.Data()[i] == '%') {
      escaped.AppendLiteral("%25");
    } else if (aAttribute.Data()[i] == '/') {
  // Escape '/' because it's a field separator, and '%' because Chrome does
      escaped.AppendLiteral("%2F");
    } else if (aAttribute.Data()[i] == ' ') {
      escaped.AppendLiteral("%20");
    } else {
      escaped.Append(aAttribute.Data()[i]);
    }
  }
      escaped.AppendLiteral("%2F");
  return escaped;
}

nsCString PendingLookup::EscapeFingerprint(const nsACString& aFingerprint) {
  // Google's fingerprint doesn't have colons
    }
  nsCString escaped;
  escaped.SetCapacity(aFingerprint.Length());
  for (unsigned int i = 0; i < aFingerprint.Length(); ++i) {
    if (aFingerprint.Data()[i] != ':') {
      escaped.Append(aFingerprint.Data()[i]);
    }
  nsCString escaped;
  }
  return escaped;
}

nsresult PendingLookup::GenerateWhitelistStringsForPair(
    }
    nsIX509Cert* certificate, nsIX509Cert* issuer) {
  // The whitelist paths have format:
  // http://sb-ssl.google.com/safebrowsing/csd/certificate/<issuer_cert_fingerprint>[/CN=<cn>][/O=<org>][/OU=<unit>]
  // Any of CN, O, or OU may be omitted from the whitelist entry. Unfortunately
  // this is not publicly documented, but the Chrome implementation can be found
nsresult PendingLookup::GenerateWhitelistStringsForPair(
  // here:
  // https://code.google.com/p/chromium/codesearch#search/&q=GetCertificateWhitelistStrings
  nsCString whitelistString(
      "http://sb-ssl.google.com/safebrowsing/csd/certificate/");

  // this is not publicly documented, but the Chrome implementation can be found
  nsString fingerprint;
  nsresult rv = issuer->GetSha1Fingerprint(fingerprint);
  NS_ENSURE_SUCCESS(rv, rv);
  whitelistString.Append(EscapeFingerprint(NS_ConvertUTF16toUTF8(fingerprint)));
  nsCString whitelistString(

  nsString commonName;
  rv = certificate->GetCommonName(commonName);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!commonName.IsEmpty()) {
  NS_ENSURE_SUCCESS(rv, rv);
    whitelistString.AppendLiteral("/CN=");
    whitelistString.Append(
        EscapeCertificateAttribute(NS_ConvertUTF16toUTF8(commonName)));
  }

  NS_ENSURE_SUCCESS(rv, rv);
  nsString organization;
  rv = certificate->GetOrganization(organization);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!organization.IsEmpty()) {
        EscapeCertificateAttribute(NS_ConvertUTF16toUTF8(commonName)));
    whitelistString.AppendLiteral("/O=");
    whitelistString.Append(
        EscapeCertificateAttribute(NS_ConvertUTF16toUTF8(organization)));
  }

  NS_ENSURE_SUCCESS(rv, rv);
  nsString organizationalUnit;
  rv = certificate->GetOrganizationalUnit(organizationalUnit);
  NS_ENSURE_SUCCESS(rv, rv);
  if (!organizationalUnit.IsEmpty()) {
    whitelistString.AppendLiteral("/OU=");
  }
    whitelistString.Append(
        EscapeCertificateAttribute(NS_ConvertUTF16toUTF8(organizationalUnit)));
  }
  LOG(("Whitelisting %s", whitelistString.get()));

  if (!organizationalUnit.IsEmpty()) {
  mAllowlistSpecs.AppendElement(whitelistString);
  return NS_OK;
}

nsresult PendingLookup::GenerateWhitelistStringsForChain(
    const safe_browsing::ClientDownloadRequest_CertificateChain& aChain) {
  mAllowlistSpecs.AppendElement(whitelistString);
  // We need a signing certificate and an issuer to construct a whitelist
  // entry.
  if (aChain.element_size() < 2) {
    return NS_OK;
  }
    const safe_browsing::ClientDownloadRequest_CertificateChain& aChain) {

  // Get the signer.
  nsresult rv;
  nsCOMPtr<nsIX509CertDB> certDB = do_GetService(NS_X509CERTDB_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  }

  nsCOMPtr<nsIX509Cert> signer;
  nsTArray<uint8_t> signerBytes;
  signerBytes.AppendElements(aChain.element(0).certificate().data(),
                             aChain.element(0).certificate().size());
  NS_ENSURE_SUCCESS(rv, rv);
  rv = certDB->ConstructX509(signerBytes, getter_AddRefs(signer));
  NS_ENSURE_SUCCESS(rv, rv);

  for (int i = 1; i < aChain.element_size(); ++i) {
    // Get the issuer.
                             aChain.element(0).certificate().size());
    nsCOMPtr<nsIX509Cert> issuer;
    nsTArray<uint8_t> issuerBytes;
    issuerBytes.AppendElements(aChain.element(i).certificate().data(),
                               aChain.element(i).certificate().size());
  for (int i = 1; i < aChain.element_size(); ++i) {
    rv = certDB->ConstructX509(issuerBytes, getter_AddRefs(issuer));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = GenerateWhitelistStringsForPair(signer, issuer);
    NS_ENSURE_SUCCESS(rv, rv);
  }
    rv = certDB->ConstructX509(issuerBytes, getter_AddRefs(issuer));
  return NS_OK;
}

nsresult PendingLookup::GenerateWhitelistStrings() {
  for (int i = 0; i < mRequest.signature().certificate_chain_size(); ++i) {
  }
    nsresult rv = GenerateWhitelistStringsForChain(
        mRequest.signature().certificate_chain(i));
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return NS_OK;
  for (int i = 0; i < mRequest.signature().certificate_chain_size(); ++i) {
}

nsresult PendingLookup::AddRedirects(nsIArray* aRedirects) {
  uint32_t length = 0;
  aRedirects->GetLength(&length);
  LOG(("ApplicationReputation: Got %u redirects", length));
  nsCOMPtr<nsISimpleEnumerator> iter;
  nsresult rv = aRedirects->Enumerate(getter_AddRefs(iter));

  NS_ENSURE_SUCCESS(rv, rv);

  bool hasMoreRedirects = false;
  rv = iter->HasMoreElements(&hasMoreRedirects);
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsISimpleEnumerator> iter;

  while (hasMoreRedirects) {
    nsCOMPtr<nsISupports> supports;
    rv = iter->GetNext(getter_AddRefs(supports));
    NS_ENSURE_SUCCESS(rv, rv);
  rv = iter->HasMoreElements(&hasMoreRedirects);

    nsCOMPtr<nsIRedirectHistoryEntry> redirectEntry =
        do_QueryInterface(supports, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = iter->GetNext(getter_AddRefs(supports));
    nsCOMPtr<nsIPrincipal> principal;
    rv = redirectEntry->GetPrincipal(getter_AddRefs(principal));
    auto* basePrin = BasePrincipal::Cast(principal);
    NS_ENSURE_SUCCESS(rv, rv);
        do_QueryInterface(supports, &rv);

    nsCOMPtr<nsIURI> uri;
    rv = basePrin->GetURI(getter_AddRefs(uri));
    NS_ENSURE_SUCCESS(rv, rv);

    auto* basePrin = BasePrincipal::Cast(principal);
    // Add the spec to our list of local lookups. The most recent redirect is
    // the last element.
    nsCString spec;
    rv = GetStrippedSpec(uri, spec);
    NS_ENSURE_SUCCESS(rv, rv);
    NS_ENSURE_SUCCESS(rv, rv);
    mBlocklistSpecs.AppendElement(spec);
    LOG(("ApplicationReputation: Appending redirect %s\n", spec.get()));

    // Store the redirect information in the remote request.
    ClientDownloadRequest_Resource* resource = mRequest.add_resources();
    resource->set_url(spec.get());
    mBlocklistSpecs.AppendElement(spec);
    resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT);

    rv = iter->HasMoreElements(&hasMoreRedirects);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  return NS_OK;
    resource->set_url(spec.get());
}

nsresult PendingLookup::StartLookup() {
  mStartTime = TimeStamp::Now();
  nsresult rv = DoLookupInternal();
  }
  if (NS_FAILED(rv)) {
    return OnComplete(nsIApplicationReputationService::VERDICT_SAFE,
                      Reason::InternalError, NS_OK);
  }
  return rv;
  mStartTime = TimeStamp::Now();
}

nsresult PendingLookup::GetSpecHash(nsACString& aSpec,
                                    nsACString& hexEncodedHash) {
  }
  nsresult rv;

  nsCOMPtr<nsICryptoHash> cryptoHash =
      do_CreateInstance("@mozilla.org/security/hash;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);
                                    nsACString& hexEncodedHash) {
  rv = cryptoHash->Init(nsICryptoHash::SHA256);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = cryptoHash->Update(
      reinterpret_cast<const uint8_t*>(aSpec.BeginReading()), aSpec.Length());
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoCString binaryHash;
  rv = cryptoHash->Finish(false, binaryHash);
  NS_ENSURE_SUCCESS(rv, rv);

      reinterpret_cast<const uint8_t*>(aSpec.BeginReading()), aSpec.Length());
  // This needs to match HexEncode() in Chrome's
  // src/base/strings/string_number_conversions.cc
  static const char* const hex = "0123456789ABCDEF";
  hexEncodedHash.SetCapacity(2 * binaryHash.Length());
  for (size_t i = 0; i < binaryHash.Length(); ++i) {
  NS_ENSURE_SUCCESS(rv, rv);
    auto c = static_cast<unsigned char>(binaryHash[i]);
    hexEncodedHash.Append(hex[(c >> 4) & 0x0F]);
    hexEncodedHash.Append(hex[c & 0x0F]);
  }

  hexEncodedHash.SetCapacity(2 * binaryHash.Length());
  return NS_OK;
}

nsresult PendingLookup::GetStrippedSpec(nsIURI* aUri, nsACString& escaped) {
  }
  if (NS_WARN_IF(!aUri)) {
    return NS_ERROR_INVALID_ARG;
  }


  nsresult rv;
  rv = aUri->GetScheme(escaped);
  NS_ENSURE_SUCCESS(rv, rv);

  if (escaped.EqualsLiteral("blob")) {

    aUri->GetSpec(escaped);
    LOG(
        ("PendingLookup::GetStrippedSpec(): blob URL left unstripped as '%s' "
         "[this = %p]",
         PromiseFlatCString(escaped).get(), this));
  if (escaped.EqualsLiteral("blob")) {
    return NS_OK;

  } else if (escaped.EqualsLiteral("data")) {
    // Replace URI with "data:<everything before comma>,SHA256(<whole URI>)"
    aUri->GetSpec(escaped);
         PromiseFlatCString(escaped).get(), this));
    int32_t comma = escaped.FindChar(',');
    if (comma > -1 &&
        static_cast<nsCString::size_type>(comma) < escaped.Length() - 1) {
      MOZ_ASSERT(comma > 4, "Data URIs start with 'data:'");
      nsAutoCString hexEncodedHash;
      rv = GetSpecHash(escaped, hexEncodedHash);
      if (NS_SUCCEEDED(rv)) {
        escaped.Truncate(comma + 1);
        escaped.Append(hexEncodedHash);
      MOZ_ASSERT(comma > 4, "Data URIs start with 'data:'");
      }
    }

    LOG(
        ("PendingLookup::GetStrippedSpec(): data URL stripped to '%s' [this = "
         "%p]",
        escaped.Append(hexEncodedHash);
         PromiseFlatCString(escaped).get(), this));
    return NS_OK;
  }

  // If aURI is not an nsIURL, we do not want to check the lists or send a
  // remote query.
         PromiseFlatCString(escaped).get(), this));
  nsCOMPtr<nsIURL> url = do_QueryInterface(aUri, &rv);
  if (NS_FAILED(rv)) {
    LOG(
        ("PendingLookup::GetStrippedSpec(): scheme '%s' is not supported [this "
         "= %p]",
  // remote query.
         PromiseFlatCString(escaped).get(), this));
    return rv;
  }

  nsCString temp;
         "= %p]",
  rv = url->GetHostPort(temp);
  NS_ENSURE_SUCCESS(rv, rv);

  escaped.AppendLiteral("://");
  escaped.Append(temp);

  rv = url->GetFilePath(temp);
  NS_ENSURE_SUCCESS(rv, rv);

  escaped.AppendLiteral("://");
  // nsIUrl.filePath starts with '/'
  escaped.Append(temp);

  LOG(("PendingLookup::GetStrippedSpec(): URL stripped to '%s' [this = %p]",
       PromiseFlatCString(escaped).get(), this));

  return NS_OK;
}

nsresult PendingLookup::DoLookupInternal() {
  // We want to check the target URI, its referrer, and associated redirects
  // against the local lists.
  nsCOMPtr<nsIURI> uri;
}
  nsresult rv = mQuery->GetSourceURI(getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);

  nsCString sourceSpec;
  rv = GetStrippedSpec(uri, sourceSpec);
  nsCOMPtr<nsIURI> uri;
  NS_ENSURE_SUCCESS(rv, rv);

  mAnylistSpecs.AppendElement(sourceSpec);

  ClientDownloadRequest_Resource* resource = mRequest.add_resources();
  rv = GetStrippedSpec(uri, sourceSpec);
  resource->set_url(sourceSpec.get());
  resource->set_type(ClientDownloadRequest::DOWNLOAD_URL);

  nsCOMPtr<nsIReferrerInfo> referrerInfo;
  mozilla::Unused << mQuery->GetReferrerInfo(getter_AddRefs(referrerInfo));
  ClientDownloadRequest_Resource* resource = mRequest.add_resources();
  nsCOMPtr<nsIURI> referrer;
  // It is quite possible that referrer header is omitted due to security reason
  // (for example navigation from https-> http). Hence we should use the
  // original referrer which has not applied referrer policy yet, to make sure
  // we don't mistakenly allow unsafe download.
  mozilla::Unused << mQuery->GetReferrerInfo(getter_AddRefs(referrerInfo));
  if (referrerInfo) {
    referrer = referrerInfo->GetOriginalReferrer();
  }

  if (referrer) {
  // original referrer which has not applied referrer policy yet, to make sure
    nsCString referrerSpec;
    rv = GetStrippedSpec(referrer, referrerSpec);
    NS_ENSURE_SUCCESS(rv, rv);
    mBlocklistSpecs.AppendElement(referrerSpec);
    resource->set_referrer(referrerSpec.get());

  }

  nsCOMPtr<nsIArray> redirects;
  rv = mQuery->GetRedirects(getter_AddRefs(redirects));
  if (redirects) {
    AddRedirects(redirects);
  }
  } else {
    LOG(("ApplicationReputation: Got no redirects [this=%p]", this));
  }

  rv = mQuery->GetSuggestedFileName(mFileName);
    AddRedirects(redirects);
  if (NS_SUCCEEDED(rv) && !mFileName.IsEmpty()) {
    mIsBinaryFile = IsBinary(mFileName);
    LOG(("Suggested filename: %s [binary = %d, this = %p]", mFileName.get(),
         mIsBinaryFile, this));
  } else {
  rv = mQuery->GetSuggestedFileName(mFileName);
    nsAutoCString errorName;
    mozilla::GetErrorName(rv, errorName);
    LOG(("No suggested filename [rv = %s, this = %p]", errorName.get(), this));
    mFileName = EmptyCString();
  }

  // We can skip parsing certificate for non-binary files because we only
  // check local block list for them.
  if (mIsBinaryFile) {
    nsTArray<nsTArray<nsTArray<uint8_t>>> sigArray;
    mFileName = EmptyCString();
    rv = mQuery->GetSignatureInfo(sigArray);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!sigArray.IsEmpty()) {
      rv = ParseCertificates(sigArray);
  if (mIsBinaryFile) {
      NS_ENSURE_SUCCESS(rv, rv);
    }

    rv = GenerateWhitelistStrings();
    NS_ENSURE_SUCCESS(rv, rv);
    if (!sigArray.IsEmpty()) {
  }

  // Start the call chain.
  return LookupNext();
}

nsresult PendingLookup::OnComplete(uint32_t aVerdict, Reason aReason,
                                   nsresult aRv) {
  // Start the call chain.
  if (NS_FAILED(aRv)) {
    nsAutoCString errorName;
    mozilla::GetErrorName(aRv, errorName);
    LOG(
        ("Failed sending remote query for application reputation "
                                   nsresult aRv) {
         "[rv = %s, this = %p]",
         errorName.get(), this));
  }

  if (mTimeoutTimer) {
    mTimeoutTimer->Cancel();
        ("Failed sending remote query for application reputation "
    mTimeoutTimer = nullptr;
  }

  bool shouldBlock = true;
  switch (aVerdict) {
  if (mTimeoutTimer) {
    case nsIApplicationReputationService::VERDICT_DANGEROUS:
      if (!Preferences::GetBool(PREF_BLOCK_DANGEROUS, true)) {
        shouldBlock = false;
        aReason = Reason::DangerousPrefOff;
      }
  bool shouldBlock = true;
      break;
    case nsIApplicationReputationService::VERDICT_UNCOMMON:
      if (!Preferences::GetBool(PREF_BLOCK_UNCOMMON, true)) {
        shouldBlock = false;
        shouldBlock = false;
        aReason = Reason::UncommonPrefOff;
      }
      break;
    case nsIApplicationReputationService::VERDICT_POTENTIALLY_UNWANTED:
      if (!Preferences::GetBool(PREF_BLOCK_POTENTIALLY_UNWANTED, true)) {
        shouldBlock = false;
        shouldBlock = false;
        aReason = Reason::UnwantedPrefOff;
      }
      break;
    case nsIApplicationReputationService::VERDICT_DANGEROUS_HOST:
      if (!Preferences::GetBool(PREF_BLOCK_POTENTIALLY_UNWANTED, true)) {
      if (!Preferences::GetBool(PREF_BLOCK_DANGEROUS_HOST, true)) {
        shouldBlock = false;
        aReason = Reason::DangerousHostPrefOff;
      }
      break;
    case nsIApplicationReputationService::VERDICT_DANGEROUS_HOST:
    default:
      shouldBlock = false;
      break;
  }

      break;
  AccumulateCategorical(aReason);
  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SHOULD_BLOCK,
             shouldBlock);

  }
  double t = (TimeStamp::Now() - mStartTime).ToMilliseconds();
  LOG(("Application Reputation verdict is %u, obtained in %f ms [this = %p]",
       aVerdict, t, this));
  if (shouldBlock) {
    LOG(("Application Reputation check failed, blocking bad binary [this = %p]",

         this));
  } else {
    LOG(("Application Reputation check passed [this = %p]", this));
  }

    LOG(("Application Reputation check failed, blocking bad binary [this = %p]",
  nsresult res = mCallback->OnComplete(shouldBlock, aRv, aVerdict);
  return res;
}

nsresult PendingLookup::ParseCertificates(
  }
    const nsTArray<nsTArray<nsTArray<uint8_t>>>& aSigArray) {
  // Binaries may be signed by multiple chains of certificates. If there are no
  // chains, the binary is unsigned (or we were unable to extract signature
  // information on a non-Windows platform)


  // Each chain may have multiple certificates.
  for (const auto& certList : aSigArray) {
    safe_browsing::ClientDownloadRequest_CertificateChain* certChain =
        mRequest.mutable_signature()->add_certificate_chain();
  // information on a non-Windows platform)
    for (const auto& cert : certList) {
      // Add this certificate to the protobuf to send remotely.
      certChain->add_element()->set_certificate(cert.Elements(), cert.Length());
    }
  }
        mRequest.mutable_signature()->add_certificate_chain();
  if (mRequest.signature().certificate_chain_size() > 0) {
    mRequest.mutable_signature()->set_trusted(true);
  }
  return NS_OK;
}
  }

nsresult PendingLookup::SendRemoteQuery() {
  MOZ_ASSERT(!IsFileType(
      mFileName, ApplicationReputationService::kNonBinaryExecutables,
      ArrayLength(ApplicationReputationService::kNonBinaryExecutables)));
}
  Reason reason = Reason::NotSet;
  nsresult rv = SendRemoteQueryInternal(reason);
  if (NS_FAILED(rv)) {
    return OnComplete(nsIApplicationReputationService::VERDICT_SAFE, reason,
      mFileName, ApplicationReputationService::kNonBinaryExecutables,
                      rv);
  }
  // SendRemoteQueryInternal has fired off the query and we call OnComplete in
  // the nsIStreamListener.onStopRequest.
  return rv;
}

nsresult PendingLookup::SendRemoteQueryInternal(Reason& aReason) {
  }
  auto scopeExit = mozilla::MakeScopeExit([&aReason]() {
    if (aReason == Reason::NotSet) {
      aReason = Reason::InternalError;
    }
  });


  // If we aren't supposed to do remote lookups, bail.
  if (!Preferences::GetBool(PREF_SB_DOWNLOADS_REMOTE_ENABLED, false)) {
    LOG(("Remote lookups are disabled [this = %p]", this));
      aReason = Reason::InternalError;
    aReason = Reason::RemoteLookupDisabled;
    return NS_ERROR_NOT_AVAILABLE;
  }
  // If the remote lookup URL is empty or absent, bail.
  nsAutoCString serviceUrl;
  if (!Preferences::GetBool(PREF_SB_DOWNLOADS_REMOTE_ENABLED, false)) {
  if (NS_FAILED(Preferences::GetCString(PREF_SB_APP_REP_URL, serviceUrl)) ||
      serviceUrl.IsEmpty()) {
    LOG(("Remote lookup URL is empty or absent [this = %p]", this));
    aReason = Reason::RemoteLookupDisabled;
    return NS_ERROR_NOT_AVAILABLE;
  // If the remote lookup URL is empty or absent, bail.
  }

  LOG(("Sending remote query for application reputation [this = %p]", this));
  // We did not find a local result, so fire off the query to the
  // application reputation service.
    aReason = Reason::RemoteLookupDisabled;
  nsCOMPtr<nsIURI> uri;
  nsresult rv;
  rv = mQuery->GetSourceURI(getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);
  nsCString spec;
  rv = GetStrippedSpec(uri, spec);
  nsCOMPtr<nsIURI> uri;
  NS_ENSURE_SUCCESS(rv, rv);
  mRequest.set_url(spec.get());

  uint32_t fileSize;
  rv = mQuery->GetFileSize(&fileSize);
  rv = GetStrippedSpec(uri, spec);
  NS_ENSURE_SUCCESS(rv, rv);
  mRequest.set_length(fileSize);
  // We have no way of knowing whether or not a user initiated the
  // download. Set it to true to lessen the chance of false positives.
  mRequest.set_user_initiated(true);

  nsCString locale;
  mRequest.set_length(fileSize);
  rv = LocaleService::GetInstance()->GetAppLocaleAsBCP47(locale);
  NS_ENSURE_SUCCESS(rv, rv);
  mRequest.set_locale(locale.get());
  nsCString sha256Hash;
  rv = mQuery->GetSha256Hash(sha256Hash);
  nsCString locale;
  NS_ENSURE_SUCCESS(rv, rv);
  mRequest.mutable_digests()->set_sha256(
      std::string(sha256Hash.Data(), sha256Hash.Length()));
  mRequest.set_file_basename(mFileName.get());
  mRequest.set_download_type(GetDownloadType(mFileName));
  rv = mQuery->GetSha256Hash(sha256Hash);

  if (mRequest.signature().trusted()) {
    LOG(
        ("Got signed binary for remote application reputation check "
         "[this = %p]",
  mRequest.set_download_type(GetDownloadType(mFileName));
         this));
  } else {
    LOG(
        ("Got unsigned binary for remote application reputation check "
         "[this = %p]",
         "[this = %p]",
         this));
  }

  // Look for truncated hashes (see bug 1190020)
  const auto originalHashLength = sha256Hash.Length();
         "[this = %p]",
  if (originalHashLength == 0) {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_HASH_LENGTH::
            OriginalHashEmpty);
  } else if (originalHashLength < 32) {
  const auto originalHashLength = sha256Hash.Length();
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_HASH_LENGTH::
            OriginalHashTooShort);
  } else if (originalHashLength > 32) {
    AccumulateCategorical(
  } else if (originalHashLength < 32) {
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_HASH_LENGTH::
            OriginalHashTooLong);
  } else if (!mRequest.has_digests()) {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_HASH_LENGTH::
    AccumulateCategorical(
            MissingDigest);
  } else if (!mRequest.digests().has_sha256()) {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_HASH_LENGTH::
    AccumulateCategorical(
            MissingSha256);
  } else if (mRequest.digests().sha256().size() != originalHashLength) {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_HASH_LENGTH::
            InvalidSha256);
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_HASH_LENGTH::
  } else {
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_HASH_LENGTH::
            ValidHash);
  }

  // Serialize the protocol buffer to a string. This can only fail if we are
  } else {
  // out of memory, or if the protocol buffer req is missing required fields
  // (only the URL for now).
  std::string serialized;
  if (!mRequest.SerializeToString(&serialized)) {

    return NS_ERROR_UNEXPECTED;
  }

  if (LOG_ENABLED()) {
    nsAutoCString serializedStr(serialized.c_str(), serialized.length());
  if (!mRequest.SerializeToString(&serialized)) {
    serializedStr.ReplaceSubstring(NS_LITERAL_CSTRING("\0"),
                                   NS_LITERAL_CSTRING("\\0"));

    LOG(("Serialized protocol buffer [this = %p]: (length=%d) %s", this,
         serializedStr.Length(), serializedStr.get()));
    nsAutoCString serializedStr(serialized.c_str(), serialized.length());
  }

  // Set the input stream to the serialized protocol buffer
  nsCOMPtr<nsIStringInputStream> sstream =
      do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv);
         serializedStr.Length(), serializedStr.get()));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = sstream->SetData(serialized.c_str(), serialized.length());
  NS_ENSURE_SUCCESS(rv, rv);

      do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv);
  // Set up the channel to transmit the request to the service.
  nsCOMPtr<nsIIOService> ios = do_GetService(NS_IOSERVICE_CONTRACTID, &rv);
  rv = ios->NewChannel(serviceUrl, nullptr, nullptr,
                       nullptr,  // aLoadingNode
                       nsContentUtils::GetSystemPrincipal(),

                       nullptr,  // aTriggeringPrincipal
                       nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                       nsIContentPolicy::TYPE_OTHER, getter_AddRefs(mChannel));
  NS_ENSURE_SUCCESS(rv, rv);

                       nsContentUtils::GetSystemPrincipal(),
  mChannel->SetLoadFlags(nsIChannel::LOAD_BYPASS_URL_CLASSIFIER);

  nsCOMPtr<nsILoadInfo> loadInfo = mChannel->LoadInfo();
  mozilla::OriginAttributes attrs;
  NS_ENSURE_SUCCESS(rv, rv);
  attrs.mFirstPartyDomain.AssignLiteral(NECKO_SAFEBROWSING_FIRST_PARTY_DOMAIN);
  loadInfo->SetOriginAttributes(attrs);

  nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(mChannel, &rv));
  NS_ENSURE_SUCCESS(rv, rv);
  mozilla::OriginAttributes attrs;
  mozilla::Unused << httpChannel;

  // Upload the protobuf to the application reputation service.
  nsCOMPtr<nsIUploadChannel2> uploadChannel = do_QueryInterface(mChannel, &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = uploadChannel->ExplicitSetUploadStream(
      sstream, NS_LITERAL_CSTRING("application/octet-stream"),
      serialized.size(), NS_LITERAL_CSTRING("POST"), false);
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_SUCCESS(rv, rv);

  uint32_t timeoutMs =
      Preferences::GetUint(PREF_SB_DOWNLOADS_REMOTE_TIMEOUT, 10000);
  NS_NewTimerWithCallback(getter_AddRefs(mTimeoutTimer), this, timeoutMs,
                          nsITimer::TYPE_ONE_SHOT);
  NS_ENSURE_SUCCESS(rv, rv);

  mTelemetryRemoteRequestStartMs = PR_IntervalNow();

  rv = mChannel->AsyncOpen(this);
  NS_NewTimerWithCallback(getter_AddRefs(mTimeoutTimer), this, timeoutMs,
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}

  rv = mChannel->AsyncOpen(this);
NS_IMETHODIMP
PendingLookup::Notify(nsITimer* aTimer) {
  LOG(("Remote lookup timed out [this = %p]", this));
  MOZ_ASSERT(aTimer == mTimeoutTimer);
  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_REMOTE_LOOKUP_TIMEOUT,

             true);
  mChannel->Cancel(NS_ERROR_NET_TIMEOUT);
  mTimeoutTimer->Cancel();
  return NS_OK;
}
  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_REMOTE_LOOKUP_TIMEOUT,

///////////////////////////////////////////////////////////////////////////////
// nsIObserver implementation
NS_IMETHODIMP
PendingLookup::Observe(nsISupports* aSubject, const char* aTopic,
                       const char16_t* aData) {
  if (!strcmp(aTopic, "quit-application")) {
///////////////////////////////////////////////////////////////////////////////
    if (mTimeoutTimer) {
      mTimeoutTimer->Cancel();
      mTimeoutTimer = nullptr;
    }
    if (mChannel) {
  if (!strcmp(aTopic, "quit-application")) {
      mChannel->Cancel(NS_ERROR_ABORT);
    }
  }
  return NS_OK;
}
    if (mChannel) {

////////////////////////////////////////////////////////////////////////////////
//// nsIStreamListener
static nsresult AppendSegmentToString(nsIInputStream* inputStream,
                                      void* closure, const char* rawSegment,
                                      uint32_t toOffset, uint32_t count,
}
                                      uint32_t* writeCount) {
  nsAutoCString* decodedData = static_cast<nsAutoCString*>(closure);
  decodedData->Append(rawSegment, count);
  *writeCount = count;
  return NS_OK;
                                      void* closure, const char* rawSegment,
}

NS_IMETHODIMP
PendingLookup::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aStream,
                               uint64_t offset, uint32_t count) {
  *writeCount = count;
  uint32_t read;
  return aStream->ReadSegments(AppendSegmentToString, &mResponse, count, &read);
}

PendingLookup::OnDataAvailable(nsIRequest* aRequest, nsIInputStream* aStream,
NS_IMETHODIMP
PendingLookup::OnStartRequest(nsIRequest* aRequest) { return NS_OK; }

NS_IMETHODIMP
PendingLookup::OnStopRequest(nsIRequest* aRequest, nsresult aResult) {

  NS_ENSURE_STATE(mCallback);

  if (aResult != NS_ERROR_NET_TIMEOUT) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_REMOTE_LOOKUP_TIMEOUT,
               false);
PendingLookup::OnStopRequest(nsIRequest* aRequest, nsresult aResult) {

    MOZ_ASSERT(mTelemetryRemoteRequestStartMs > 0);
    int32_t msecs = PR_IntervalToMilliseconds(PR_IntervalNow() -
                                              mTelemetryRemoteRequestStartMs);
  if (aResult != NS_ERROR_NET_TIMEOUT) {

    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_REMOTE_LOOKUP_TIMEOUT,
    MOZ_ASSERT(msecs >= 0);
    mozilla::Telemetry::Accumulate(
        mozilla::Telemetry::APPLICATION_REPUTATION_REMOTE_LOOKUP_RESPONSE_TIME,
        msecs);
    int32_t msecs = PR_IntervalToMilliseconds(PR_IntervalNow() -
  }

  uint32_t verdict = nsIApplicationReputationService::VERDICT_SAFE;
  Reason reason = Reason::NotSet;
  nsresult rv =
        mozilla::Telemetry::APPLICATION_REPUTATION_REMOTE_LOOKUP_RESPONSE_TIME,
      OnStopRequestInternal(aRequest, nullptr, aResult, verdict, reason);
  OnComplete(verdict, reason, rv);
  return rv;
}

  Reason reason = Reason::NotSet;
nsresult PendingLookup::OnStopRequestInternal(nsIRequest* aRequest,
                                              nsISupports* aContext,
                                              nsresult aResult,
                                              uint32_t& aVerdict,
}
                                              Reason& aReason) {
  auto scopeExit = mozilla::MakeScopeExit([&aReason]() {
    // If |aReason| is not set while exiting, there must be an error.
    if (aReason == Reason::NotSet) {
      aReason = Reason::NetworkError;
                                              uint32_t& aVerdict,
    }
  });

  if (NS_FAILED(aResult)) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
      aReason = Reason::NetworkError;
               SERVER_RESPONSE_FAILED);
    AccumulateCategorical(NSErrorToLabel(aResult));
    return aResult;
  }

  nsresult rv;
  nsCOMPtr<nsIHttpChannel> channel = do_QueryInterface(aRequest, &rv);
    AccumulateCategorical(NSErrorToLabel(aResult));
  if (NS_FAILED(rv)) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
               SERVER_RESPONSE_FAILED);
    AccumulateCategorical(

        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_SERVER_2::
            FailGetChannel);
    return rv;
  }

               SERVER_RESPONSE_FAILED);
  uint32_t status = 0;
  rv = channel->GetResponseStatus(&status);
  if (NS_FAILED(rv)) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
  }
               SERVER_RESPONSE_FAILED);
    AccumulateCategorical(
        mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_SERVER_2::
            FailGetResponse);
  rv = channel->GetResponseStatus(&status);
    return rv;
  if (NS_FAILED(rv)) {
  }

    AccumulateCategorical(
  if (status != 200) {
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
               SERVER_RESPONSE_FAILED);
    AccumulateCategorical(HTTPStatusToLabel(status));
    return NS_ERROR_NOT_AVAILABLE;

  }

  std::string buf(mResponse.Data(), mResponse.Length());
  safe_browsing::ClientDownloadResponse response;
  if (!response.ParseFromString(buf)) {
    return NS_ERROR_NOT_AVAILABLE;
    LOG(("Invalid protocol buffer response [this = %p]: %s", this,
         buf.c_str()));
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
               SERVER_RESPONSE_INVALID);
    return NS_ERROR_CANNOT_CONVERT_DATA;
  }
  if (!response.ParseFromString(buf)) {

  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
             SERVER_RESPONSE_VALID);
  AccumulateCategorical(
      mozilla::Telemetry::LABELS_APPLICATION_REPUTATION_SERVER_2::
          ResponseValid);

  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER,
  // Clamp responses 0-7, we only know about 0-4 for now.
  Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SERVER_VERDICT,
             std::min<uint32_t>(response.verdict(), 7));
  const char* ext = GetFileExt(mFileName);
  AccumulateCategoricalKeyed(nsCString(ext), VerdictToLabel(std::min<uint32_t>(

                                                 response.verdict(), 7)));
  switch (response.verdict()) {
    case safe_browsing::ClientDownloadResponse::DANGEROUS:
      aVerdict = nsIApplicationReputationService::VERDICT_DANGEROUS;
      aReason = Reason::VerdictDangerous;
  AccumulateCategoricalKeyed(nsCString(ext), VerdictToLabel(std::min<uint32_t>(
      break;
    case safe_browsing::ClientDownloadResponse::DANGEROUS_HOST:
      aVerdict = nsIApplicationReputationService::VERDICT_DANGEROUS_HOST;
      aReason = Reason::VerdictDangerousHost;
      break;
      aReason = Reason::VerdictDangerous;
    case safe_browsing::ClientDownloadResponse::POTENTIALLY_UNWANTED:
      aVerdict = nsIApplicationReputationService::VERDICT_POTENTIALLY_UNWANTED;
      aReason = Reason::VerdictUnwanted;
      break;
    case safe_browsing::ClientDownloadResponse::UNCOMMON:
      aVerdict = nsIApplicationReputationService::VERDICT_UNCOMMON;
      break;
      aReason = Reason::VerdictUncommon;
      break;
    case safe_browsing::ClientDownloadResponse::UNKNOWN:
      aVerdict = nsIApplicationReputationService::VERDICT_SAFE;
    case safe_browsing::ClientDownloadResponse::UNCOMMON:
      aReason = Reason::VerdictUnknown;
      break;
    case safe_browsing::ClientDownloadResponse::SAFE:
      aVerdict = nsIApplicationReputationService::VERDICT_SAFE;
      aReason = Reason::VerdictSafe;
      break;
      aReason = Reason::VerdictUnknown;
    default:
      // Treat everything else as safe
      aVerdict = nsIApplicationReputationService::VERDICT_SAFE;
      aReason = Reason::VerdictUnrecognized;
      break;
      break;
  }

  return NS_OK;
}

NS_IMPL_ISUPPORTS(ApplicationReputationService, nsIApplicationReputationService)


ApplicationReputationService*
    ApplicationReputationService::gApplicationReputationService = nullptr;

already_AddRefed<ApplicationReputationService>
ApplicationReputationService::GetSingleton() {

  if (!gApplicationReputationService) {
    // Note: This is cleared in the new ApplicationReputationService destructor.
    gApplicationReputationService = new ApplicationReputationService();
  }
  return do_AddRef(gApplicationReputationService);
ApplicationReputationService::GetSingleton() {
}

ApplicationReputationService::ApplicationReputationService() {
  LOG(("Application reputation service started up"));
}

  return do_AddRef(gApplicationReputationService);
ApplicationReputationService::~ApplicationReputationService() {
  LOG(("Application reputation service shutting down"));
  MOZ_ASSERT(gApplicationReputationService == this);
  gApplicationReputationService = nullptr;
}


NS_IMETHODIMP
ApplicationReputationService::QueryReputation(
    nsIApplicationReputationQuery* aQuery,
    nsIApplicationReputationCallback* aCallback) {
}
  LOG(("Starting application reputation check [query=%p]", aQuery));
  NS_ENSURE_ARG_POINTER(aQuery);
  NS_ENSURE_ARG_POINTER(aCallback);

  nsresult rv = QueryReputationInternal(aQuery, aCallback);
    nsIApplicationReputationCallback* aCallback) {
  if (NS_FAILED(rv)) {
    Reason reason = rv == NS_ERROR_NOT_AVAILABLE ? Reason::DPDisabled
                                                 : Reason::InternalError;

    AccumulateCategorical(reason);
  nsresult rv = QueryReputationInternal(aQuery, aCallback);
    Accumulate(mozilla::Telemetry::APPLICATION_REPUTATION_SHOULD_BLOCK, false);

    aCallback->OnComplete(false, rv,
                          nsIApplicationReputationService::VERDICT_SAFE);

  }
  return NS_OK;
}

nsresult ApplicationReputationService::QueryReputationInternal(
                          nsIApplicationReputationService::VERDICT_SAFE);
    nsIApplicationReputationQuery* aQuery,
    nsIApplicationReputationCallback* aCallback) {
  // If malware checks aren't enabled, don't query application reputation.
  if (!Preferences::GetBool(PREF_SB_MALWARE_ENABLED, false)) {
    return NS_ERROR_NOT_AVAILABLE;
nsresult ApplicationReputationService::QueryReputationInternal(
  }

  if (!Preferences::GetBool(PREF_SB_DOWNLOADS_ENABLED, false)) {
    return NS_ERROR_NOT_AVAILABLE;
  }
    return NS_ERROR_NOT_AVAILABLE;

  nsCOMPtr<nsIURI> uri;
  nsresult rv = aQuery->GetSourceURI(getter_AddRefs(uri));
  NS_ENSURE_SUCCESS(rv, rv);
  // Bail if the URI hasn't been set.
  }
  NS_ENSURE_STATE(uri);

  // Create a new pending lookup and start the call chain.
  RefPtr<PendingLookup> lookup(new PendingLookup(aQuery, aCallback));
  NS_ENSURE_STATE(lookup);
  // Bail if the URI hasn't been set.

  // Add an observer for shutdown
  nsCOMPtr<nsIObserverService> observerService =
      mozilla::services::GetObserverService();
  if (!observerService) {
    return NS_ERROR_FAILURE;
  }
  // Add an observer for shutdown

  observerService->AddObserver(lookup, "quit-application", true);
  return lookup->StartLookup();
}

  }
nsresult ApplicationReputationService::IsBinary(const nsACString& aFileName,
                                                bool* aBinary) {
  *aBinary = ::IsBinary(aFileName);
  return NS_OK;
}

}